Subversion-Projekte lars-tiefland.php_share

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
1 lars 1
<?php
2
/*
3
 *  $Id: Sqlite.php 7490 2010-03-29 19:53:27Z 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.doctrine-project.org>.
20
 */
21
 
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.doctrine-project.org
31
 * @since       1.0
32
 * @version     $Revision: 7490 $
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
        $type  = '';
108
 
109
        if (isset($definition['type'])) {
110
            switch (strtolower($definition['type'])) {
111
                case 'unique':
112
                    $type = strtoupper($definition['type']) . ' ';
113
                break;
114
                default:
115
                    throw new Doctrine_Export_Exception(
116
                        'Unknown type ' . $definition['type'] . ' for index ' . $name . ' in table ' . $table
117
                    );
118
            }
119
        }
120
 
121
        $query = 'CREATE ' . $type . 'INDEX ' . $name . ' ON ' . $table;
122
        $query .= ' (' . $this->getIndexFieldDeclarationList($definition['fields']) . ')';
123
 
124
        return $query;
125
    }
126
 
127
    /**
128
     * getIndexFieldDeclarationList
129
     * Obtain DBMS specific SQL code portion needed to set an index
130
     * declaration to be used in statements like CREATE TABLE.
131
     *
132
     * @return string
133
     */
134
    public function getIndexFieldDeclarationList(array $fields)
135
    {
136
        $declFields = array();
137
 
138
        foreach ($fields as $fieldName => $field) {
139
            $fieldString = $this->conn->quoteIdentifier($fieldName);
140
 
141
            if (is_array($field)) {
142
                if (isset($field['sorting'])) {
143
                    $sort = strtoupper($field['sorting']);
144
                    switch ($sort) {
145
                        case 'ASC':
146
                        case 'DESC':
147
                            $fieldString .= ' ' . $sort;
148
                            break;
149
                        default:
150
                            throw new Doctrine_Export_Exception('Unknown index sorting option given.');
151
                    }
152
                }
153
            } else {
154
                $fieldString = $this->conn->quoteIdentifier($field);
155
            }
156
            $declFields[] = $fieldString;
157
        }
158
        return implode(', ', $declFields);
159
    }
160
 
161
    /**
162
     * create a new table
163
     *
164
     * @param string $name   Name of the database that should be created
165
     * @param array $fields  Associative array that contains the definition of each field of the new table
166
     *                       The indexes of the array entries are the names of the fields of the table an
167
     *                       the array entry values are associative arrays like those that are meant to be
168
     *                       passed with the field definitions to get[Type]Declaration() functions.
169
     *                          array(
170
     *                              'id' => array(
171
     *                                  'type' => 'integer',
172
     *                                  'unsigned' => 1
173
     *                                  'notnull' => 1
174
     *                                  'default' => 0
175
     *                              ),
176
     *                              'name' => array(
177
     *                                  'type' => 'text',
178
     *                                  'length' => 12
179
     *                              ),
180
     *                              'password' => array(
181
     *                                  'type' => 'text',
182
     *                                  'length' => 12
183
     *                              )
184
     *                          );
185
     * @param array $options  An associative array of table options:
186
     *
187
     * @return void
188
     */
189
    public function createTableSql($name, array $fields, array $options = array())
190
    {
191
        if ( ! $name) {
192
            throw new Doctrine_Export_Exception('no valid table name specified');
193
        }
194
 
195
        if (empty($fields)) {
196
            throw new Doctrine_Export_Exception('no fields specified for table '.$name);
197
        }
198
        $queryFields = $this->getFieldDeclarationList($fields);
199
 
200
        $autoinc = false;
201
        foreach($fields as $field) {
202
            if (isset($field['autoincrement']) && $field['autoincrement'] ||
203
              (isset($field['autoinc']) && $field['autoinc'])) {
204
                $autoinc = true;
205
                break;
206
            }
207
        }
208
 
209
        if ( ! $autoinc && isset($options['primary']) && ! empty($options['primary'])) {
210
            $keyColumns = array_values($options['primary']);
211
            $keyColumns = array_map(array($this->conn, 'quoteIdentifier'), $keyColumns);
212
            $queryFields.= ', PRIMARY KEY('.implode(', ', $keyColumns).')';
213
        }
214
 
215
        $name  = $this->conn->quoteIdentifier($name, true);
216
        $sql   = 'CREATE TABLE ' . $name . ' (' . $queryFields;
217
 
218
        if ($check = $this->getCheckDeclaration($fields)) {
219
            $sql .= ', ' . $check;
220
        }
221
 
222
        if (isset($options['checks']) && $check = $this->getCheckDeclaration($options['checks'])) {
223
            $sql .= ', ' . $check;
224
        }
225
 
226
        $sql .= ')';
227
 
228
        $query[] = $sql;
229
 
230
        if (isset($options['indexes']) && ! empty($options['indexes'])) {
231
            foreach ($options['indexes'] as $index => $definition) {
232
                $query[] = $this->createIndexSql($name, $index, $definition);
233
            }
234
        }
235
 
236
        return $query;
237
    }
238
 
239
    /**
240
     * getAdvancedForeignKeyOptions
241
     * Return the FOREIGN KEY query section dealing with non-standard options
242
     * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
243
     *
244
     * @param array $definition         foreign key definition
245
     * @return string
246
     * @access protected
247
     */
248
    public function getAdvancedForeignKeyOptions(array $definition)
249
    {
250
        $query = '';
251
        if (isset($definition['match'])) {
252
            $query .= ' MATCH ' . $definition['match'];
253
        }
254
        if (isset($definition['onUpdate'])) {
255
            $query .= ' ON UPDATE ' . $definition['onUpdate'];
256
        }
257
        if (isset($definition['onDelete'])) {
258
            $query .= ' ON DELETE ' . $definition['onDelete'];
259
        }
260
        if (isset($definition['deferrable'])) {
261
            $query .= ' DEFERRABLE';
262
        } else {
263
            $query .= ' NOT DEFERRABLE';
264
        }
265
        if (isset($definition['feferred'])) {
266
            $query .= ' INITIALLY DEFERRED';
267
        } else {
268
            $query .= ' INITIALLY IMMEDIATE';
269
        }
270
        return $query;
271
    }
272
 
273
    /**
274
     * create sequence
275
     *
276
     * @param string    $seqName        name of the sequence to be created
277
     * @param string    $start          start value of the sequence; default is 1
278
     * @param array     $options  An associative array of table options:
279
     *                          array(
280
     *                              'comment' => 'Foo',
281
     *                              'charset' => 'utf8',
282
     *                              'collate' => 'utf8_unicode_ci',
283
     *                          );
284
     * @return boolean
285
     */
286
    public function createSequence($seqName, $start = 1, array $options = array())
287
    {
288
        $sequenceName   = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($seqName), true);
289
        $seqcolName     = $this->conn->quoteIdentifier($this->conn->getAttribute(Doctrine_Core::ATTR_SEQCOL_NAME), true);
290
        $query          = 'CREATE TABLE ' . $sequenceName . ' (' . $seqcolName . ' INTEGER PRIMARY KEY DEFAULT 0 NOT NULL)';
291
 
292
        $this->conn->exec($query);
293
 
294
        if ($start == 1) {
295
            return true;
296
        }
297
 
298
        try {
299
            $this->conn->exec('INSERT INTO ' . $sequenceName . ' (' . $seqcolName . ') VALUES (' . ($start-1) . ')');
300
            return true;
301
        } catch(Doctrine_Connection_Exception $e) {
302
            // Handle error
303
 
304
            try {
305
                $result = $db->exec('DROP TABLE ' . $sequenceName);
306
            } catch(Doctrine_Connection_Exception $e) {
307
                throw new Doctrine_Export_Exception('could not drop inconsistent sequence table');
308
            }
309
        }
310
        throw new Doctrine_Export_Exception('could not create sequence table');
311
    }
312
 
313
    /**
314
     * drop existing sequence
315
     *
316
     * @param string $sequenceName      name of the sequence to be dropped
317
     * @return string
318
     */
319
    public function dropSequenceSql($sequenceName)
320
    {
321
        $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($sequenceName), true);
322
 
323
        return 'DROP TABLE ' . $sequenceName;
324
    }
325
 
326
    public function alterTableSql($name, array $changes, $check = false)
327
    {
328
        if ( ! $name) {
329
            throw new Doctrine_Export_Exception('no valid table name specified');
330
        }
331
        foreach ($changes as $changeName => $change) {
332
            switch ($changeName) {
333
                case 'add':
334
                case 'change':
335
                case 'rename':
336
                case 'name':
337
                    break;
338
                default:
339
                    throw new Doctrine_Export_Exception('change type "' . $changeName . '" not yet supported');
340
            }
341
        }
342
 
343
        if ($check) {
344
            return true;
345
        }
346
 
347
        $query = '';
348
        if ( ! empty($changes['name'])) {
349
            $change_name = $this->conn->quoteIdentifier($changes['name']);
350
            $query .= 'RENAME TO ' . $change_name;
351
        }
352
 
353
        if ( ! empty($changes['add']) && is_array($changes['add'])) {
354
            foreach ($changes['add'] as $fieldName => $field) {
355
                if ($query) {
356
                    $query.= ', ';
357
                }
358
                $query.= 'ADD ' . $this->getDeclaration($fieldName, $field);
359
            }
360
        }
361
 
362
        $rename = array();
363
        if ( ! empty($changes['rename']) && is_array($changes['rename'])) {
364
            foreach ($changes['rename'] as $fieldName => $field) {
365
                $rename[$field['name']] = $fieldName;
366
            }
367
        }
368
 
369
        if ( ! empty($changes['change']) && is_array($changes['change'])) {
370
            foreach ($changes['change'] as $fieldName => $field) {
371
                if ($query) {
372
                    $query.= ', ';
373
                }
374
                if (isset($rename[$fieldName])) {
375
                    $oldFieldName = $rename[$fieldName];
376
                    unset($rename[$fieldName]);
377
                } else {
378
                    $oldFieldName = $fieldName;
379
                }
380
                $oldFieldName = $this->conn->quoteIdentifier($oldFieldName, true);
381
                $query .= 'CHANGE ' . $oldFieldName . ' '
382
                        . $this->getDeclaration($fieldName, $field['definition']);
383
            }
384
        }
385
 
386
        if ( ! empty($rename) && is_array($rename)) {
387
            foreach ($rename as $renameName => $renamedField) {
388
                if ($query) {
389
                    $query.= ', ';
390
                }
391
                $field = $changes['rename'][$renamedField];
392
                $renamedField = $this->conn->quoteIdentifier($renamedField, true);
393
                $query .= 'CHANGE ' . $renamedField . ' '
394
                        . $this->getDeclaration($field['name'], $field['definition']);
395
            }
396
        }
397
 
398
        if ( ! $query) {
399
            return false;
400
        }
401
 
402
        $name = $this->conn->quoteIdentifier($name, true);
403
 
404
        return 'ALTER TABLE ' . $name . ' ' . $query;
405
    }
406
 
407
    /**
408
     * createForeignKey
409
     *
410
     * Sqlite does not support foreign keys so we are not even going to do anything if this function is called
411
     * to avoid any sql errors if a user tries to use this on sqlite
412
     *
413
     * @param string    $table         name of the table on which the foreign key is to be created
414
     * @param array     $definition    associative array that defines properties of the foreign key to be created.
415
     * @return string
416
     */
417
    public function createForeignKey($table, array $definition)
418
    {
419
        return false;
420
    }
421
}