svncommit
2008-09-18 d0b973cf6aed4a7cb705f706624d25b31d19ed52
commit | author | age
95ebbc 1 <?php
T 2 // +----------------------------------------------------------------------+
3 // | PHP versions 4 and 5                                                 |
4 // +----------------------------------------------------------------------+
5 // | Copyright (c) 1998-2007 Manuel Lemos, Tomas V.V.Cox,                 |
6 // | Stig. S. Bakken, Lukas Smith, Lorenzo Alberton                       |
7 // | All rights reserved.                                                 |
8 // +----------------------------------------------------------------------+
9 // | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
10 // | API as well as database abstraction for PHP applications.            |
11 // | This LICENSE is in the BSD license style.                            |
12 // |                                                                      |
13 // | Redistribution and use in source and binary forms, with or without   |
14 // | modification, are permitted provided that the following conditions   |
15 // | are met:                                                             |
16 // |                                                                      |
17 // | Redistributions of source code must retain the above copyright       |
18 // | notice, this list of conditions and the following disclaimer.        |
19 // |                                                                      |
20 // | Redistributions in binary form must reproduce the above copyright    |
21 // | notice, this list of conditions and the following disclaimer in the  |
22 // | documentation and/or other materials provided with the distribution. |
23 // |                                                                      |
24 // | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
25 // | Lukas Smith nor the names of his contributors may be used to endorse |
26 // | or promote products derived from this software without specific prior|
27 // | written permission.                                                  |
28 // |                                                                      |
29 // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
30 // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
31 // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
32 // | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
33 // | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
34 // | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
35 // | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
36 // |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
37 // | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
38 // | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
39 // | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
40 // | POSSIBILITY OF SUCH DAMAGE.                                          |
41 // +----------------------------------------------------------------------+
42 // | Authors: Lukas Smith <smith@pooteeweet.org>                          |
43 // |          Lorenzo Alberton <l.alberton@quipo.it>                      |
44 // +----------------------------------------------------------------------+
45 //
d1403f 46 // $Id: sqlite.php,v 1.79 2008/03/05 11:08:53 quipo Exp $
95ebbc 47 //
T 48
49 require_once 'MDB2/Driver/Reverse/Common.php';
50
51 /**
52  * MDB2 SQlite driver for the schema reverse engineering module
53  *
54  * @package MDB2
55  * @category Database
56  * @author  Lukas Smith <smith@pooteeweet.org>
57  */
58 class MDB2_Driver_Reverse_sqlite extends MDB2_Driver_Reverse_Common
59 {
60     function _getTableColumns($sql)
61     {
62         $db =& $this->getDBInstance();
63         if (PEAR::isError($db)) {
64             return $db;
65         }
66         $start_pos  = strpos($sql, '(');
67         $end_pos    = strrpos($sql, ')');
68         $column_def = substr($sql, $start_pos+1, $end_pos-$start_pos-1);
69         // replace the decimal length-places-separator with a colon
70         $column_def = preg_replace('/(\d),(\d)/', '\1:\2', $column_def);
71         $column_sql = split(',', $column_def);
72         $columns    = array();
73         $count      = count($column_sql);
74         if ($count == 0) {
75             return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
76                 'unexpected empty table column definition list', __FUNCTION__);
77         }
78         $regexp = '/^\s*([^\s]+) +(CHAR|VARCHAR|VARCHAR2|TEXT|BOOLEAN|SMALLINT|INT|INTEGER|DECIMAL|BIGINT|DOUBLE|FLOAT|DATETIME|DATE|TIME|LONGTEXT|LONGBLOB)( ?\(([1-9][0-9]*)(:([1-9][0-9]*))?\))?( UNSIGNED)?( PRIMARY KEY)?( DEFAULT (\'[^\']*\'|[^ ]+))?( NULL| NOT NULL)?( PRIMARY KEY)?$/i';
79         $regexp2 = '/^\s*([^ ]+) +(PRIMARY|UNIQUE|CHECK)$/i';
80         for ($i=0, $j=0; $i<$count; ++$i) {
81             if (!preg_match($regexp, trim($column_sql[$i]), $matches)) {
82                 if (!preg_match($regexp2, trim($column_sql[$i]))) {
83                     continue;
84                 }
85                 return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
86                     'unexpected table column SQL definition: "'.$column_sql[$i].'"', __FUNCTION__);
87             }
88             $columns[$j]['name'] = trim($matches[1], implode('', $db->identifier_quoting));
89             $columns[$j]['type'] = strtolower($matches[2]);
90             if (isset($matches[4]) && strlen($matches[4])) {
91                 $columns[$j]['length'] = $matches[4];
92             }
93             if (isset($matches[6]) && strlen($matches[6])) {
94                 $columns[$j]['decimal'] = $matches[6];
95             }
96             if (isset($matches[7]) && strlen($matches[7])) {
97                 $columns[$j]['unsigned'] = true;
98             }
99             if (isset($matches[8]) && strlen($matches[8])) {
100                 $columns[$j]['autoincrement'] = true;
101             }
102             if (isset($matches[10]) && strlen($matches[10])) {
103                 $default = $matches[10];
104                 if (strlen($default) && $default[0]=="'") {
105                     $default = str_replace("''", "'", substr($default, 1, strlen($default)-2));
106                 }
107                 if ($default === 'NULL') {
108                     $default = null;
109                 }
110                 $columns[$j]['default'] = $default;
111             }
112             if (isset($matches[11]) && strlen($matches[11])) {
113                 $columns[$j]['notnull'] = ($matches[11] === ' NOT NULL');
114             }
115             ++$j;
116         }
117         return $columns;
118     }
119
120     // {{{ getTableFieldDefinition()
121
122     /**
123      * Get the stucture of a field into an array
124      *
125      * @param string $table_name name of table that should be used in method
126      * @param string $field_name name of field that should be used in method
127      * @return mixed data array on success, a MDB2 error on failure.
128      *          The returned array contains an array for each field definition,
129      *          with (some of) these indices:
130      *          [notnull] [nativetype] [length] [fixed] [default] [type] [mdb2type]
131      * @access public
132      */
133     function getTableFieldDefinition($table_name, $field_name)
134     {
135         $db =& $this->getDBInstance();
136         if (PEAR::isError($db)) {
137             return $db;
138         }
139         
140         list($schema, $table) = $this->splitTableSchema($table_name);
141
142         $result = $db->loadModule('Datatype', null, true);
143         if (PEAR::isError($result)) {
144             return $result;
145         }
146         $query = "SELECT sql FROM sqlite_master WHERE type='table' AND ";
147         if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
148             $query.= 'LOWER(name)='.$db->quote(strtolower($table), 'text');
149         } else {
150             $query.= 'name='.$db->quote($table, 'text');
151         }
152         $sql = $db->queryOne($query);
153         if (PEAR::isError($sql)) {
154             return $sql;
155         }
156         $columns = $this->_getTableColumns($sql);
157         foreach ($columns as $column) {
158             if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
159                 if ($db->options['field_case'] == CASE_LOWER) {
160                     $column['name'] = strtolower($column['name']);
161                 } else {
162                     $column['name'] = strtoupper($column['name']);
163                 }
164             } else {
165                 $column = array_change_key_case($column, $db->options['field_case']);
166             }
167             if ($field_name == $column['name']) {
168                 $mapped_datatype = $db->datatype->mapNativeDatatype($column);
169                 if (PEAR::isError($mapped_datatype)) {
170                     return $mapped_datatype;
171                 }
172                 list($types, $length, $unsigned, $fixed) = $mapped_datatype;
173                 $notnull = false;
174                 if (!empty($column['notnull'])) {
175                     $notnull = $column['notnull'];
176                 }
177                 $default = false;
178                 if (array_key_exists('default', $column)) {
179                     $default = $column['default'];
180                     if (is_null($default) && $notnull) {
181                         $default = '';
182                     }
183                 }
184                 $autoincrement = false;
185                 if (!empty($column['autoincrement'])) {
186                     $autoincrement = true;
187                 }
188
189                 $definition[0] = array(
190                     'notnull' => $notnull,
191                     'nativetype' => preg_replace('/^([a-z]+)[^a-z].*/i', '\\1', $column['type'])
192                 );
193                 if (!is_null($length)) {
194                     $definition[0]['length'] = $length;
195                 }
196                 if (!is_null($unsigned)) {
197                     $definition[0]['unsigned'] = $unsigned;
198                 }
199                 if (!is_null($fixed)) {
200                     $definition[0]['fixed'] = $fixed;
201                 }
202                 if ($default !== false) {
203                     $definition[0]['default'] = $default;
204                 }
205                 if ($autoincrement !== false) {
206                     $definition[0]['autoincrement'] = $autoincrement;
207                 }
208                 foreach ($types as $key => $type) {
209                     $definition[$key] = $definition[0];
210                     if ($type == 'clob' || $type == 'blob') {
211                         unset($definition[$key]['default']);
212                     }
213                     $definition[$key]['type'] = $type;
214                     $definition[$key]['mdb2type'] = $type;
215                 }
216                 return $definition;
217             }
218         }
219
220         return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
221             'it was not specified an existing table column', __FUNCTION__);
222     }
223
224     // }}}
225     // {{{ getTableIndexDefinition()
226
227     /**
228      * Get the stucture of an index into an array
229      *
230      * @param string $table_name name of table that should be used in method
231      * @param string $index_name name of index that should be used in method
232      * @return mixed data array on success, a MDB2 error on failure
233      * @access public
234      */
235     function getTableIndexDefinition($table_name, $index_name)
236     {
237         $db =& $this->getDBInstance();
238         if (PEAR::isError($db)) {
239             return $db;
240         }
241         
242         list($schema, $table) = $this->splitTableSchema($table_name);
243
244         $query = "SELECT sql FROM sqlite_master WHERE type='index' AND ";
245         if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
246             $query.= 'LOWER(name)=%s AND LOWER(tbl_name)=' . $db->quote(strtolower($table), 'text');
247         } else {
248             $query.= 'name=%s AND tbl_name=' . $db->quote($table, 'text');
249         }
250         $query.= ' AND sql NOT NULL ORDER BY name';
251         $index_name_mdb2 = $db->getIndexName($index_name);
252         if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
253             $qry = sprintf($query, $db->quote(strtolower($index_name_mdb2), 'text'));
254         } else {
255             $qry = sprintf($query, $db->quote($index_name_mdb2, 'text'));
256         }
257         $sql = $db->queryOne($qry, 'text');
258         if (PEAR::isError($sql) || empty($sql)) {
259             // fallback to the given $index_name, without transformation
260             if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
261                 $qry = sprintf($query, $db->quote(strtolower($index_name), 'text'));
262             } else {
263                 $qry = sprintf($query, $db->quote($index_name, 'text'));
264             }
265             $sql = $db->queryOne($qry, 'text');
266         }
267         if (PEAR::isError($sql)) {
268             return $sql;
269         }
270         if (!$sql) {
271             return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
272                 'it was not specified an existing table index', __FUNCTION__);
273         }
274
275         $sql = strtolower($sql);
276         $start_pos = strpos($sql, '(');
277         $end_pos = strrpos($sql, ')');
278         $column_names = substr($sql, $start_pos+1, $end_pos-$start_pos-1);
279         $column_names = split(',', $column_names);
280
281         if (preg_match("/^create unique/", $sql)) {
282             return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
283                 'it was not specified an existing table index', __FUNCTION__);
284         }
285
286         $definition = array();
287         $count = count($column_names);
288         for ($i=0; $i<$count; ++$i) {
289             $column_name = strtok($column_names[$i], ' ');
290             $collation = strtok(' ');
291             $definition['fields'][$column_name] = array(
292                 'position' => $i+1
293             );
294             if (!empty($collation)) {
295                 $definition['fields'][$column_name]['sorting'] =
296                     ($collation=='ASC' ? 'ascending' : 'descending');
297             }
298         }
299
300         if (empty($definition['fields'])) {
301             return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
302                 'it was not specified an existing table index', __FUNCTION__);
303         }
304         return $definition;
305     }
306
307     // }}}
308     // {{{ getTableConstraintDefinition()
309
310     /**
311      * Get the stucture of a constraint into an array
312      *
313      * @param string $table_name      name of table that should be used in method
314      * @param string $constraint_name name of constraint that should be used in method
315      * @return mixed data array on success, a MDB2 error on failure
316      * @access public
317      */
318     function getTableConstraintDefinition($table_name, $constraint_name)
319     {
320         $db =& $this->getDBInstance();
321         if (PEAR::isError($db)) {
322             return $db;
323         }
324         
325         list($schema, $table) = $this->splitTableSchema($table_name);
326
327         $query = "SELECT sql FROM sqlite_master WHERE type='index' AND ";
328         if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
329             $query.= 'LOWER(name)=%s AND LOWER(tbl_name)=' . $db->quote(strtolower($table), 'text');
330         } else {
331             $query.= 'name=%s AND tbl_name=' . $db->quote($table, 'text');
332         }
333         $query.= ' AND sql NOT NULL ORDER BY name';
334         $constraint_name_mdb2 = $db->getIndexName($constraint_name);
335         if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
336             $qry = sprintf($query, $db->quote(strtolower($constraint_name_mdb2), 'text'));
337         } else {
338             $qry = sprintf($query, $db->quote($constraint_name_mdb2, 'text'));
339         }
340         $sql = $db->queryOne($qry, 'text');
341         if (PEAR::isError($sql) || empty($sql)) {
342             // fallback to the given $index_name, without transformation
343             if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
344                 $qry = sprintf($query, $db->quote(strtolower($constraint_name), 'text'));
345             } else {
346                 $qry = sprintf($query, $db->quote($constraint_name, 'text'));
347             }
348             $sql = $db->queryOne($qry, 'text');
349         }
350         if (PEAR::isError($sql)) {
351             return $sql;
352         }
353         //default values, eventually overridden
354         $definition = array(
355             'primary' => false,
356             'unique'  => false,
357             'foreign' => false,
358             'check'   => false,
359             'fields'  => array(),
360             'references' => array(
361                 'table'  => '',
362                 'fields' => array(),
363             ),
364             'onupdate'  => '',
365             'ondelete'  => '',
366             'match'     => '',
367             'deferrable'        => false,
368             'initiallydeferred' => false,
369         );
370         if (!$sql) {
371             $query = "SELECT sql FROM sqlite_master WHERE type='table' AND ";
372             if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
373                 $query.= 'LOWER(name)='.$db->quote(strtolower($table), 'text');
374             } else {
375                 $query.= 'name='.$db->quote($table, 'text');
376             }
377             $query.= " AND sql NOT NULL ORDER BY name";
378             $sql = $db->queryOne($query, 'text');
379             if (PEAR::isError($sql)) {
380                 return $sql;
381             }
382             if ($constraint_name == 'primary') {
383                 // search in table definition for PRIMARY KEYs
384                 if (preg_match("/\bPRIMARY\s+KEY\b\s*\(([^)]+)/i", $sql, $tmp)) {
385                     $definition['primary'] = true;
386                     $definition['fields'] = array();
387                     $column_names = split(',', $tmp[1]);
388                     $colpos = 1;
389                     foreach ($column_names as $column_name) {
390                         $definition['fields'][trim($column_name)] = array(
391                             'position' => $colpos++
392                         );
393                     }
394                     return $definition;
395                 }
d1403f 396                 if (preg_match("/\"([^\"]+)\"[^\,\"]+\bPRIMARY\s+KEY\b[^\,\)]*/i", $sql, $tmp)) {
A 397                     $definition['primary'] = true;
398                     $definition['fields'] = array();
399                     $column_names = split(',', $tmp[1]);
400                     $colpos = 1;
401                     foreach ($column_names as $column_name) {
402                         $definition['fields'][trim($column_name)] = array(
403                             'position' => $colpos++
404                         );
405                     }
406                     return $definition;
407                 }
95ebbc 408             } else {
T 409                 // search in table definition for FOREIGN KEYs
410                 $pattern = "/\bCONSTRAINT\b\s+%s\s+
411                     \bFOREIGN\s+KEY\b\s*\(([^\)]+)\)\s*
412                     \bREFERENCES\b\s+([^\s]+)\s*\(([^\)]+)\)\s*
413                     (?:\bMATCH\s*([^\s]+))?\s*
414                     (?:\bON\s+UPDATE\s+([^\s,\)]+))?\s*
415                     (?:\bON\s+DELETE\s+([^\s,\)]+))?\s*
416                     /imsx";
417                 $found_fk = false;
418                 if (preg_match(sprintf($pattern, $constraint_name_mdb2), $sql, $tmp)) {
419                     $found_fk = true;
420                 } elseif (preg_match(sprintf($pattern, $constraint_name), $sql, $tmp)) {
421                     $found_fk = true;
422                 }
423                 if ($found_fk) {
424                     $definition['foreign'] = true;
425                     $definition['match'] = 'SIMPLE';
426                     $definition['onupdate'] = 'NO ACTION';
427                     $definition['ondelete'] = 'NO ACTION';
428                     $definition['references']['table'] = $tmp[2];
429                     $column_names = split(',', $tmp[1]);
430                     $colpos = 1;
431                     foreach ($column_names as $column_name) {
432                         $definition['fields'][trim($column_name)] = array(
433                             'position' => $colpos++
434                         );
435                     }
436                     $referenced_cols = split(',', $tmp[3]);
437                     $colpos = 1;
438                     foreach ($referenced_cols as $column_name) {
439                         $definition['references']['fields'][trim($column_name)] = array(
440                             'position' => $colpos++
441                         );
442                     }
443                     if (isset($tmp[4])) {
444                         $definition['match']    = $tmp[4];
445                     }
446                     if (isset($tmp[5])) {
447                         $definition['onupdate'] = $tmp[5];
448                     }
449                     if (isset($tmp[6])) {
450                         $definition['ondelete'] = $tmp[6];
451                     }
452                     return $definition;
453                 }
454             }
455             $sql = false;
456         }
457         if (!$sql) {
458             return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
459                 $constraint_name . ' is not an existing table constraint', __FUNCTION__);
460         }
461
462         $sql = strtolower($sql);
463         $start_pos = strpos($sql, '(');
464         $end_pos   = strrpos($sql, ')');
465         $column_names = substr($sql, $start_pos+1, $end_pos-$start_pos-1);
466         $column_names = split(',', $column_names);
467
468         if (!preg_match("/^create unique/", $sql)) {
469             return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
470                 $constraint_name . ' is not an existing table constraint', __FUNCTION__);
471         }
472
473         $definition['unique'] = true;
474         $count = count($column_names);
475         for ($i=0; $i<$count; ++$i) {
476             $column_name = strtok($column_names[$i]," ");
477             $collation = strtok(" ");
478             $definition['fields'][$column_name] = array(
479                 'position' => $i+1
480             );
481             if (!empty($collation)) {
482                 $definition['fields'][$column_name]['sorting'] =
483                     ($collation=='ASC' ? 'ascending' : 'descending');
484             }
485         }
486
487         if (empty($definition['fields'])) {
488             return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
489                 $constraint_name . ' is not an existing table constraint', __FUNCTION__);
490         }
491         return $definition;
492     }
493
494     // }}}
495     // {{{ getTriggerDefinition()
496
497     /**
498      * Get the structure of a trigger into an array
499      *
500      * EXPERIMENTAL
501      *
502      * WARNING: this function is experimental and may change the returned value
503      * at any time until labelled as non-experimental
504      *
505      * @param string    $trigger    name of trigger that should be used in method
506      * @return mixed data array on success, a MDB2 error on failure
507      * @access public
508      */
509     function getTriggerDefinition($trigger)
510     {
511         $db =& $this->getDBInstance();
512         if (PEAR::isError($db)) {
513             return $db;
514         }
515
516         $query = "SELECT name as trigger_name,
517                          tbl_name AS table_name,
518                          sql AS trigger_body,
519                          NULL AS trigger_type,
520                          NULL AS trigger_event,
521                          NULL AS trigger_comment,
522                          1 AS trigger_enabled
523                     FROM sqlite_master
524                    WHERE type='trigger'";
525         if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
526             $query.= ' AND LOWER(name)='.$db->quote(strtolower($trigger), 'text');
527         } else {
528             $query.= ' AND name='.$db->quote($trigger, 'text');
529         }
530         $types = array(
531             'trigger_name'    => 'text',
532             'table_name'      => 'text',
533             'trigger_body'    => 'text',
534             'trigger_type'    => 'text',
535             'trigger_event'   => 'text',
536             'trigger_comment' => 'text',
537             'trigger_enabled' => 'boolean',
538         );
539         $def = $db->queryRow($query, $types, MDB2_FETCHMODE_ASSOC);
540         if (PEAR::isError($def)) {
541             return $def;
542         }
543         if (empty($def)) {
544             return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
545                 'it was not specified an existing trigger', __FUNCTION__);
546         }
547         if (preg_match("/^create\s+(?:temp|temporary)?trigger\s+(?:if\s+not\s+exists\s+)?.*(before|after)?\s+(insert|update|delete)/Uims", $def['trigger_body'], $tmp)) {
548             $def['trigger_type'] = strtoupper($tmp[1]);
549             $def['trigger_event'] = strtoupper($tmp[2]);
550         }
551         return $def;
552     }
553
554     // }}}
555     // {{{ tableInfo()
556
557     /**
558      * Returns information about a table
559      *
560      * @param string         $result  a string containing the name of a table
561      * @param int            $mode    a valid tableInfo mode
562      *
563      * @return array  an associative array with the information requested.
564      *                 A MDB2_Error object on failure.
565      *
566      * @see MDB2_Driver_Common::tableInfo()
567      * @since Method available since Release 1.7.0
568      */
569     function tableInfo($result, $mode = null)
570     {
571         if (is_string($result)) {
572            return parent::tableInfo($result, $mode);
573         }
574
575         $db =& $this->getDBInstance();
576         if (PEAR::isError($db)) {
577             return $db;
578         }
579
580         return $db->raiseError(MDB2_ERROR_NOT_CAPABLE, null, null,
581            'This DBMS can not obtain tableInfo from result sets', __FUNCTION__);
582     }
583 }
584
585 ?>