Coverage for Doctrine_Export_Sqlite

Back to coverage report

1 <?php
2 /*
3  *  $Id: Sqlite.php 3967 2008-03-11 02:51:33Z jwage $
4  *
5  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
6  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
12  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
13  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
14  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
15  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
16  *
17  * This software consists of voluntary contributions made by many individuals
18  * and is licensed under the LGPL. For more information, see
19  * <http://www.phpdoctrine.org>.
20  */
21 Doctrine::autoload('Doctrine_Export');
22 /**
23  * Doctrine_Export_Sqlite
24  *
25  * @package     Doctrine
26  * @subpackage  Export
27  * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
28  * @author      Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
29  * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
30  * @link        www.phpdoctrine.org
31  * @since       1.0
32  * @version     $Revision: 3967 $
33  */
34 class Doctrine_Export_Sqlite extends Doctrine_Export
35 {
36     /**
37      * dropDatabase
38      *
39      * drop an existing database
40      *
41      * @param string $databaseFile          Path of the database that should be dropped
42      * @throws Doctrine_Export_Exception    if the database file does not exist
43      * @throws Doctrine_Export_Exception    if something failed during the removal of the database file
44      * @return void
45      */
46     public function dropDatabase($databaseFile)
47     {
48         if ( ! @file_exists($databaseFile)) {
49             throw new Doctrine_Export_Exception('database does not exist');
50         }
51
52         $result = @unlink($databaseFile);
53
54         if ( ! $result) {
55             throw new Doctrine_Export_Exception('could not remove the database file');
56         }
57     }
58
59     /**
60      * createDatabase
61      *
62      * Create sqlite database file
63      *
64      * @param string $databaseFile  Path of the database that should be dropped
65      * @return void
66      */
67     public function createDatabase($databaseFile)
68     {
69         return new PDO('sqlite:' . $databaseFile);
70     }
71
72     /**
73      * Get the stucture of a field into an array
74      *
75      * @param string    $table         name of the table on which the index is to be created
76      * @param string    $name         name of the index to be created
77      * @param array     $definition        associative array that defines properties of the index to be created.
78      *                                 Currently, only one property named FIELDS is supported. This property
79      *                                 is also an associative with the names of the index fields as array
80      *                                 indexes. Each entry of this array is set to another type of associative
81      *                                 array that specifies properties of the index that are specific to
82      *                                 each field.
83      *
84      *                                Currently, only the sorting property is supported. It should be used
85      *                                 to define the sorting direction of the index. It may be set to either
86      *                                 ascending or descending.
87      *
88      *                                Not all DBMS support index sorting direction configuration. The DBMS
89      *                                 drivers of those that do not support it ignore this property. Use the
90      *                                 function support() to determine whether the DBMS driver can manage indexes.
91      *                                 Example
92      *                                    array(
93      *                                        'fields' => array(
94      *                                            'user_name' => array(
95      *                                                'sorting' => 'ascending'
96      *                                            ),
97      *                                            'last_login' => array()
98      *                                        )
99      *                                    )
100      * @throws PDOException
101      * @return void
102      */
103     public function createIndexSql($table, $name, array $definition)
104     {
105         $name  = $this->conn->formatter->getIndexName($name);
106         $name  = $this->conn->quoteIdentifier($name);
107         $query = 'CREATE INDEX ' . $name . ' ON ' . $table;
108         $query .= ' (' . $this->getIndexFieldDeclarationList($definition['fields']) . ')';
109
110         return $query;
111     }
112
113     /**
114      * getIndexFieldDeclarationList
115      * Obtain DBMS specific SQL code portion needed to set an index
116      * declaration to be used in statements like CREATE TABLE.
117      *
118      * @return string   
119      */
120     public function getIndexFieldDeclarationList(array $fields)
121     {
122         $declFields = array();
123
124         foreach ($fields as $fieldName => $field) {
125             $fieldString = $this->conn->quoteIdentifier($fieldName);
126
127             if (is_array($field)) {
128                 if (isset($field['sorting'])) {
129                     $sort = strtoupper($field['sorting']);
130                     switch ($sort) {
131                         case 'ASC':
132                         case 'DESC':
133                             $fieldString .= ' ' . $sort;
134                             break;
135                         default:
136                             throw new Doctrine_Export_Exception('Unknown index sorting option given.');
137                     }
138                 }
139             } else {
140                 $fieldString = $this->conn->quoteIdentifier($field);
141             }
142             $declFields[] = $fieldString;
143         }
144         return implode(', ', $declFields);
145     }
146
147     /**
148      * create a new table
149      *
150      * @param string $name   Name of the database that should be created
151      * @param array $fields  Associative array that contains the definition of each field of the new table
152      *                       The indexes of the array entries are the names of the fields of the table an
153      *                       the array entry values are associative arrays like those that are meant to be
154      *                       passed with the field definitions to get[Type]Declaration() functions.
155      *                          array(
156      *                              'id' => array(
157      *                                  'type' => 'integer',
158      *                                  'unsigned' => 1
159      *                                  'notnull' => 1
160      *                                  'default' => 0
161      *                              ),
162      *                              'name' => array(
163      *                                  'type' => 'text',
164      *                                  'length' => 12
165      *                              ),
166      *                              'password' => array(
167      *                                  'type' => 'text',
168      *                                  'length' => 12
169      *                              )
170      *                          );
171      * @param array $options  An associative array of table options:
172      *
173      * @return void
174      */
175     public function createTableSql($name, array $fields, array $options = array())
176     {
177         if ( ! $name) {
178             throw new Doctrine_Export_Exception('no valid table name specified');
179         }
180         
181         if (empty($fields)) {
182             throw new Doctrine_Export_Exception('no fields specified for table '.$name);
183         }
184         $queryFields = $this->getFieldDeclarationList($fields);
185         
186         $autoinc = false;
187         foreach($fields as $field) {
188             if (isset($field['autoincrement']) && $field['autoincrement'] || 
189               (isset($field['autoinc']) && $field['autoinc'])) {
190                 $autoinc = true;
191                 break;
192             }
193         }
194
195         if ( ! $autoinc && isset($options['primary']) && ! empty($options['primary'])) {
196             $keyColumns = array_values($options['primary']);
197             $keyColumns = array_map(array($this->conn, 'quoteIdentifier'), $keyColumns);
198             $queryFields.= ', PRIMARY KEY('.implode(', ', $keyColumns).')';
199         }
200
201         $name  = $this->conn->quoteIdentifier($name, true);
202         $sql   = 'CREATE TABLE ' . $name . ' (' . $queryFields;
203
204         if ($check = $this->getCheckDeclaration($fields)) {
205             $sql .= ', ' . $check;
206         }
207
208         if (isset($options['checks']) && $check = $this->getCheckDeclaration($options['checks'])) {
209             $sql .= ', ' . $check;
210         }
211
212         $sql .= ')';
213
214         $query[] = $sql;
215
216         if (isset($options['indexes']) && ! empty($options['indexes'])) {
217             foreach ($options['indexes'] as $index => $definition) {
218                 $query[] = $this->createIndexSql($name, $index, $definition);
219             }
220         }
221
222         return $query;
223     }
224
225     /**
226      * getAdvancedForeignKeyOptions
227      * Return the FOREIGN KEY query section dealing with non-standard options
228      * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
229      *
230      * @param array $definition         foreign key definition
231      * @return string
232      * @access protected
233      */
234     public function getAdvancedForeignKeyOptions(array $definition)
235     {
236         $query = '';
237         if (isset($definition['match'])) {
238             $query .= ' MATCH ' . $definition['match'];
239         }
240         if (isset($definition['onUpdate'])) {
241             $query .= ' ON UPDATE ' . $definition['onUpdate'];
242         }
243         if (isset($definition['onDelete'])) {
244             $query .= ' ON DELETE ' . $definition['onDelete'];
245         }
246         if (isset($definition['deferrable'])) {
247             $query .= ' DEFERRABLE';
248         } else {
249             $query .= ' NOT DEFERRABLE';
250         }
251         if (isset($definition['feferred'])) {
252             $query .= ' INITIALLY DEFERRED';
253         } else {
254             $query .= ' INITIALLY IMMEDIATE';
255         }
256         return $query;
257     }
258
259     /**
260      * create sequence
261      *
262      * @param string    $seqName        name of the sequence to be created
263      * @param string    $start          start value of the sequence; default is 1
264      * @param array     $options  An associative array of table options:
265      *                          array(
266      *                              'comment' => 'Foo',
267      *                              'charset' => 'utf8',
268      *                              'collate' => 'utf8_unicode_ci',
269      *                          );
270      * @return boolean
271      */
272     public function createSequence($seqName, $start = 1, array $options = array())
273     {
274         $sequenceName   = $this->conn->quoteIdentifier($this->conn->getSequenceName($seqName), true);
275         $seqcolName     = $this->conn->quoteIdentifier($this->conn->getAttribute(Doctrine::ATTR_SEQCOL_NAME), true);
276         $query          = 'CREATE TABLE ' . $sequenceName . ' (' . $seqcolName . ' INTEGER PRIMARY KEY DEFAULT 0 NOT NULL)';
277
278         $this->conn->exec($query);
279
280         if ($start == 1) {
281             return true;
282         }
283
284         try {
285             $this->conn->exec('INSERT INTO ' . $sequenceName . ' (' . $seqcolName . ') VALUES (' . ($start-1) . ')');
286             return true;
287         } catch(Doctrine_Connection_Exception $e) {
288             // Handle error    
289
290             try {
291                 $result = $db->exec('DROP TABLE ' . $sequenceName);
292             } catch(Doctrine_Connection_Exception $e) {
293                 throw new Doctrine_Export_Exception('could not drop inconsistent sequence table');
294             }
295         }
296         throw new Doctrine_Export_Exception('could not create sequence table');
297     }
298
299     /**
300      * drop existing sequence
301      *
302      * @param string $sequenceName      name of the sequence to be dropped
303      * @return string
304      */
305     public function dropSequenceSql($sequenceName)
306     {
307         $sequenceName = $this->conn->quoteIdentifier($this->conn->getSequenceName($sequenceName), true);
308
309         return 'DROP TABLE ' . $sequenceName;
310     }
311     
312     public function alterTableSql($name, array $changes, $check = false)
313     {
314         if ( ! $name) {
315             throw new Doctrine_Export_Exception('no valid table name specified');
316         }
317         foreach ($changes as $changeName => $change) {
318             switch ($changeName) {
319                 case 'add':
320                 case 'change':
321                 case 'rename':
322                 case 'name':
323                     break;
324                 default:
325                     throw new Doctrine_Export_Exception('change type "' . $changeName . '" not yet supported');
326             }
327         }
328
329         if ($check) {
330             return true;
331         }
332
333         $query = '';
334         if ( ! empty($changes['name'])) {
335             $change_name = $this->conn->quoteIdentifier($changes['name']);
336             $query .= 'RENAME TO ' . $change_name;
337         }
338
339         if ( ! empty($changes['add']) && is_array($changes['add'])) {
340             foreach ($changes['add'] as $fieldName => $field) {
341                 if ($query) {
342                     $query.= ', ';
343                 }
344                 $query.= 'ADD ' . $this->getDeclaration($fieldName, $field);
345             }
346         }
347
348         $rename = array();
349         if ( ! empty($changes['rename']) && is_array($changes['rename'])) {
350             foreach ($changes['rename'] as $fieldName => $field) {
351                 $rename[$field['name']] = $fieldName;
352             }
353         }
354
355         if ( ! empty($changes['change']) && is_array($changes['change'])) {
356             foreach ($changes['change'] as $fieldName => $field) {
357                 if ($query) {
358                     $query.= ', ';
359                 }
360                 if (isset($rename[$fieldName])) {
361                     $oldFieldName = $rename[$fieldName];
362                     unset($rename[$fieldName]);
363                 } else {
364                     $oldFieldName = $fieldName;
365                 }
366                 $oldFieldName = $this->conn->quoteIdentifier($oldFieldName, true);
367                 $query .= 'CHANGE ' . $oldFieldName . ' ' 
368                         . $this->getDeclaration($fieldName, $field['definition']);
369             }
370         }
371
372         if ( ! empty($rename) && is_array($rename)) {
373             foreach ($rename as $renameName => $renamedField) {
374                 if ($query) {
375                     $query.= ', ';
376                 }
377                 $field = $changes['rename'][$renamedField];
378                 $renamedField = $this->conn->quoteIdentifier($renamedField, true);
379                 $query .= 'CHANGE ' . $renamedField . ' '
380                         . $this->getDeclaration($field['name'], $field['definition']);
381             }
382         }
383
384         if ( ! $query) {
385             return false;
386         }
387
388         $name = $this->conn->quoteIdentifier($name, true);
389         
390         return 'ALTER TABLE ' . $name . ' ' . $query;
391     }
392 }