]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/schema.php
Merge branch 'master' of gitorious.org:statusnet/mainline
[quix0rs-gnu-social.git] / lib / schema.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Database schema utilities
6  *
7  * PHP version 5
8  *
9  * LICENCE: This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU Affero General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU Affero General Public License for more details.
18  *
19  * You should have received a copy of the GNU Affero General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  *
22  * @category  Database
23  * @package   StatusNet
24  * @author    Evan Prodromou <evan@status.net>
25  * @copyright 2009 StatusNet, Inc.
26  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
27  * @link      http://status.net/
28  */
29
30 if (!defined('STATUSNET')) {
31     exit(1);
32 }
33
34 /**
35  * Class representing the database schema
36  *
37  * A class representing the database schema. Can be used to
38  * manipulate the schema -- especially for plugins and upgrade
39  * utilities.
40  *
41  * @category Database
42  * @package  StatusNet
43  * @author   Evan Prodromou <evan@status.net>
44  * @author   Brion Vibber <brion@status.net>
45  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
46  * @link     http://status.net/
47  */
48
49 class Schema
50 {
51     static $_static = null;
52     protected $conn = null;
53
54     /**
55      * Constructor. Only run once for singleton object.
56      */
57
58     protected function __construct($conn = null)
59     {
60         if (is_null($conn)) {
61             // XXX: there should be an easier way to do this.
62             $user = new User();
63             $conn = $user->getDatabaseConnection();
64             $user->free();
65             unset($user);
66         }
67
68         $this->conn = $conn;
69     }
70
71     /**
72      * Main public entry point. Use this to get
73      * the schema object.
74      *
75      * @return Schema the Schema object for the connection
76      */
77
78     static function get($conn = null)
79     {
80         if (is_null($conn)) {
81             $key = 'default';
82         } else {
83             $key = md5(serialize($conn->dsn));
84         }
85         
86         $type = common_config('db', 'type');
87         if (empty(self::$_static[$key])) {
88             $schemaClass = ucfirst($type).'Schema';
89             self::$_static[$key] = new $schemaClass($conn);
90         }
91         return self::$_static[$key];
92     }
93
94     /**
95      * Gets a ColumnDef object for a single column.
96      *
97      * Throws an exception if the table is not found.
98      *
99      * @param string $table  name of the table
100      * @param string $column name of the column
101      *
102      * @return ColumnDef definition of the column or null
103      *                   if not found.
104      */
105
106     public function getColumnDef($table, $column)
107     {
108         $td = $this->getTableDef($table);
109
110         if (!empty($td) && !empty($td->columns)) {
111             foreach ($td->columns as $cd) {
112                 if ($cd->name == $column) {
113                     return $cd;
114                 }
115             }
116         }
117
118         return null;
119     }
120
121     /**
122      * Creates a table with the given names and columns.
123      *
124      * @param string $tableName    Name of the table
125      * @param array  $def          Table definition array listing fields and indexes.
126      *
127      * @return boolean success flag
128      */
129
130     public function createTable($tableName, $def)
131     {
132         $statements = $this->buildCreateTable($tableName, $def);
133         return $this->runSqlSet($statements);
134     }
135
136     /**
137      * Build a set of SQL statements to create a table with the given
138      * name and columns.
139      *
140      * @param string $name    Name of the table
141      * @param array  $def     Table definition array
142      *
143      * @return boolean success flag
144      */
145     public function buildCreateTable($name, $def)
146     {
147         $def = $this->validateDef($name, $def);
148         $def = $this->filterDef($def);
149         $sql = array();
150
151         foreach ($def['fields'] as $col => $colDef) {
152             $this->appendColumnDef($sql, $col, $colDef);
153         }
154
155         // Primary, unique, and foreign keys are constraints, so go within
156         // the CREATE TABLE statement normally.
157         if (!empty($def['primary key'])) {
158             $this->appendPrimaryKeyDef($sql, $def['primary key']);
159         }
160
161         if (!empty($def['unique keys'])) {
162             foreach ($def['unique keys'] as $col => $colDef) {
163                 $this->appendUniqueKeyDef($sql, $col, $colDef);
164             }
165         }
166
167         if (!empty($def['foreign keys'])) {
168             foreach ($def['foreign keys'] as $keyName => $keyDef) {
169                 $this->appendForeignKeyDef($sql, $keyName, $keyDef);
170             }
171         }
172
173         // Wrap the CREATE TABLE around the main body chunks...
174         $statements = array();
175         $statements[] = $this->startCreateTable($name, $def) . "\n" .
176                         implode($sql, ",\n") . "\n" .
177                         $this->endCreateTable($name, $def);
178
179         // Multi-value indexes are advisory and for best portability
180         // should be created as separate statements.
181         if (!empty($def['indexes'])) {
182             foreach ($def['indexes'] as $col => $colDef) {
183                 $this->appendCreateIndex($statements, $name, $col, $colDef);
184             }
185         }
186         if (!empty($def['fulltext indexes'])) {
187             foreach ($def['fulltext indexes'] as $col => $colDef) {
188                 $this->appendCreateFulltextIndex($statements, $name, $col, $colDef);
189             }
190         }
191
192         return $statements;
193     }
194
195     /**
196      * Set up a 'create table' SQL statement.
197      *
198      * @param string $name table name
199      * @param array $def table definition
200      * @param $string
201      */
202     function startCreateTable($name, array $def)
203     {
204         return 'CREATE TABLE ' . $this->quoteIdentifier($name)  . ' (';
205     }
206
207     /**
208      * Close out a 'create table' SQL statement.
209      *
210      * @param string $name table name
211      * @param array $def table definition
212      * @return string
213      */
214     function endCreateTable($name, array $def)
215     {
216         return ')';
217     }
218
219     /**
220      * Append an SQL fragment with a column definition in a CREATE TABLE statement.
221      *
222      * @param array $sql
223      * @param string $name
224      * @param array $def
225      */
226     function appendColumnDef(array &$sql, $name, array $def)
227     {
228         $sql[] = "$name " . $this->columnSql($def);
229     }
230
231     /**
232      * Append an SQL fragment with a constraint definition for a primary
233      * key in a CREATE TABLE statement.
234      *
235      * @param array $sql
236      * @param array $def
237      */
238     function appendPrimaryKeyDef(array &$sql, array $def)
239     {
240         $sql[] = "PRIMARY KEY " . $this->buildIndexList($def);
241     }
242
243     /**
244      * Append an SQL fragment with a constraint definition for a unique
245      * key in a CREATE TABLE statement.
246      *
247      * @param array $sql
248      * @param string $name
249      * @param array $def
250      */
251     function appendUniqueKeyDef(array &$sql, $name, array $def)
252     {
253         $sql[] = "CONSTRAINT $name UNIQUE " . $this->buildIndexList($def);
254     }
255
256     /**
257      * Append an SQL fragment with a constraint definition for a foreign
258      * key in a CREATE TABLE statement.
259      *
260      * @param array $sql
261      * @param string $name
262      * @param array $def
263      */
264     function appendForeignKeyDef(array &$sql, $name, array $def)
265     {
266         if (count($def) != 2) {
267             throw new Exception("Invalid foreign key def for $name: " . var_export($def, true));
268         }
269         list($refTable, $map) = $def;
270         $srcCols = array_keys($map);
271         $refCols = array_values($map);
272         $sql[] = "CONSTRAINT $name FOREIGN KEY " .
273                  $this->buildIndexList($srcCols) .
274                  " REFERENCES " .
275                  $this->quoteIdentifier($refTable) .
276                  " " .
277                  $this->buildIndexList($refCols);
278     }
279
280     /**
281      * Append an SQL statement with an index definition for an advisory
282      * index over one or more columns on a table.
283      *
284      * @param array $statements
285      * @param string $table
286      * @param string $name
287      * @param array $def
288      */
289     function appendCreateIndex(array &$statements, $table, $name, array $def)
290     {
291         $statements[] = "CREATE INDEX $name ON $table " . $this->buildIndexList($def);
292     }
293
294     /**
295      * Append an SQL statement with an index definition for a full-text search
296      * index over one or more columns on a table.
297      *
298      * @param array $statements
299      * @param string $table
300      * @param string $name
301      * @param array $def
302      */
303     function appendCreateFulltextIndex(array &$statements, $table, $name, array $def)
304     {
305         throw new Exception("Fulltext index not supported in this database");
306     }
307
308     /**
309      * Append an SQL statement to drop an index from a table.
310      *
311      * @param array $statements
312      * @param string $table
313      * @param string $name
314      * @param array $def
315      */
316     function appendDropIndex(array &$statements, $table, $name)
317     {
318         $statements[] = "DROP INDEX $name ON " . $this->quoteIdentifier($table);
319     }
320
321     function buildIndexList(array $def)
322     {
323         // @fixme
324         return '(' . implode(',', array_map(array($this, 'buildIndexItem'), $def)) . ')';
325     }
326
327     function buildIndexItem($def)
328     {
329         if (is_array($def)) {
330             list($name, $size) = $def;
331             return $this->quoteIdentifier($name) . '(' . intval($size) . ')';
332         }
333         return $this->quoteIdentifier($def);
334     }
335
336     /**
337      * Drops a table from the schema
338      *
339      * Throws an exception if the table is not found.
340      *
341      * @param string $name Name of the table to drop
342      *
343      * @return boolean success flag
344      */
345
346     public function dropTable($name)
347     {
348         $res = $this->conn->query("DROP TABLE $name");
349
350         if (PEAR::isError($res)) {
351             throw new Exception($res->getMessage());
352         }
353
354         return true;
355     }
356
357     /**
358      * Adds an index to a table.
359      *
360      * If no name is provided, a name will be made up based
361      * on the table name and column names.
362      *
363      * Throws an exception on database error, esp. if the table
364      * does not exist.
365      *
366      * @param string $table       Name of the table
367      * @param array  $columnNames Name of columns to index
368      * @param string $name        (Optional) name of the index
369      *
370      * @return boolean success flag
371      */
372
373     public function createIndex($table, $columnNames, $name=null)
374     {
375         if (!is_array($columnNames)) {
376             $columnNames = array($columnNames);
377         }
378
379         if (empty($name)) {
380             $name = "{$table}_".implode("_", $columnNames)."_idx";
381         }
382
383         $res = $this->conn->query("ALTER TABLE $table ".
384                                    "ADD INDEX $name (".
385                                    implode(",", $columnNames).")");
386
387         if (PEAR::isError($res)) {
388             throw new Exception($res->getMessage());
389         }
390
391         return true;
392     }
393
394     /**
395      * Drops a named index from a table.
396      *
397      * @param string $table name of the table the index is on.
398      * @param string $name  name of the index
399      *
400      * @return boolean success flag
401      */
402
403     public function dropIndex($table, $name)
404     {
405         $res = $this->conn->query("ALTER TABLE $table DROP INDEX $name");
406
407         if (PEAR::isError($res)) {
408             throw new Exception($res->getMessage());
409         }
410
411         return true;
412     }
413
414     /**
415      * Adds a column to a table
416      *
417      * @param string    $table     name of the table
418      * @param ColumnDef $columndef Definition of the new
419      *                             column.
420      *
421      * @return boolean success flag
422      */
423
424     public function addColumn($table, $columndef)
425     {
426         $sql = "ALTER TABLE $table ADD COLUMN " . $this->_columnSql($columndef);
427
428         $res = $this->conn->query($sql);
429
430         if (PEAR::isError($res)) {
431             throw new Exception($res->getMessage());
432         }
433
434         return true;
435     }
436
437     /**
438      * Modifies a column in the schema.
439      *
440      * The name must match an existing column and table.
441      *
442      * @param string    $table     name of the table
443      * @param ColumnDef $columndef new definition of the column.
444      *
445      * @return boolean success flag
446      */
447
448     public function modifyColumn($table, $columndef)
449     {
450         $sql = "ALTER TABLE $table MODIFY COLUMN " .
451           $this->_columnSql($columndef);
452
453         $res = $this->conn->query($sql);
454
455         if (PEAR::isError($res)) {
456             throw new Exception($res->getMessage());
457         }
458
459         return true;
460     }
461
462     /**
463      * Drops a column from a table
464      *
465      * The name must match an existing column.
466      *
467      * @param string $table      name of the table
468      * @param string $columnName name of the column to drop
469      *
470      * @return boolean success flag
471      */
472
473     public function dropColumn($table, $columnName)
474     {
475         $sql = "ALTER TABLE $table DROP COLUMN $columnName";
476
477         $res = $this->conn->query($sql);
478
479         if (PEAR::isError($res)) {
480             throw new Exception($res->getMessage());
481         }
482
483         return true;
484     }
485
486     /**
487      * Ensures that a table exists with the given
488      * name and the given column definitions.
489      *
490      * If the table does not yet exist, it will
491      * create the table. If it does exist, it will
492      * alter the table to match the column definitions.
493      *
494      * @param string $tableName name of the table
495      * @param array  $def       Table definition array
496      *
497      * @return boolean success flag
498      */
499
500     public function ensureTable($tableName, $def)
501     {
502         $statements = $this->buildEnsureTable($tableName, $def);
503         return $this->runSqlSet($statements);
504     }
505
506     /**
507      * Run a given set of SQL commands on the connection in sequence.
508      * Empty input is ok.
509      *
510      * @fixme if multiple statements, wrap in a transaction?
511      * @param array $statements
512      * @return boolean success flag
513      */
514     function runSqlSet(array $statements)
515     {
516         $ok = true;
517         foreach ($statements as $sql) {
518             if (defined('DEBUG_INSTALLER')) {
519                 echo "<tt>" . htmlspecialchars($sql) . "</tt><br/>\n";
520             }
521             $res = $this->conn->query($sql);
522
523             if (PEAR::isError($res)) {
524                 throw new Exception($res->getMessage());
525             }
526         }
527         return $ok;
528     }
529
530     /**
531      * Check a table's status, and if needed build a set
532      * of SQL statements which change it to be consistent
533      * with the given table definition.
534      *
535      * If the table does not yet exist, statements will
536      * be returned to create the table. If it does exist,
537      * statements will be returned to alter the table to
538      * match the column definitions.
539      *
540      * @param string $tableName name of the table
541      * @param array  $columns   array of ColumnDef
542      *                          objects for the table
543      *
544      * @return array of SQL statements
545      */
546
547     function buildEnsureTable($tableName, array $def)
548     {
549         try {
550             $old = $this->getTableDef($tableName);
551         } catch (SchemaTableMissingException $e) {
552             return $this->buildCreateTable($tableName, $def);
553         }
554
555         // Filter the DB-independent table definition to match the current
556         // database engine's features and limitations.
557         $def = $this->validateDef($tableName, $def);
558         $def = $this->filterDef($def);
559
560         $statements = array();
561         $fields = $this->diffArrays($old, $def, 'fields', array($this, 'columnsEqual'));
562         $uniques = $this->diffArrays($old, $def, 'unique keys');
563         $indexes = $this->diffArrays($old, $def, 'indexes');
564         $foreign = $this->diffArrays($old, $def, 'foreign keys');
565
566         // Drop any obsolete or modified indexes ahead...
567         foreach ($indexes['del'] + $indexes['mod'] as $indexName) {
568             $this->appendDropIndex($statements, $tableName, $indexName);
569         }
570
571         // For efficiency, we want this all in one
572         // query, instead of using our methods.
573
574         $phrase = array();
575
576         foreach ($foreign['del'] + $foreign['mod'] as $keyName) {
577             $this->appendAlterDropForeign($phrase, $keyName);
578         }
579
580         foreach ($uniques['del'] + $uniques['mod'] as $keyName) {
581             $this->appendAlterDropUnique($phrase, $keyName);
582         }
583
584         if (isset($old['primary key']) && (!isset($def['primary key']) || $def['primary key'] != $old['primary key'])) {
585             $this->appendAlterDropPrimary($phrase);
586         }
587
588         foreach ($fields['add'] as $columnName) {
589             $this->appendAlterAddColumn($phrase, $columnName,
590                     $def['fields'][$columnName]);
591         }
592
593         foreach ($fields['mod'] as $columnName) {
594             $this->appendAlterModifyColumn($phrase, $columnName,
595                     $old['fields'][$columnName],
596                     $def['fields'][$columnName]);
597         }
598
599         foreach ($fields['del'] as $columnName) {
600             $this->appendAlterDropColumn($phrase, $columnName);
601         }
602
603         if (isset($def['primary key']) && (!isset($old['primary key']) || $old['primary key'] != $def['primary key'])) {
604             $this->appendAlterAddPrimary($phrase, $def['primary key']);
605         }
606
607         foreach ($uniques['mod'] + $uniques['add'] as $keyName) {
608             $this->appendAlterAddUnique($phrase, $keyName, $def['unique keys'][$keyName]);
609         }
610
611         foreach ($foreign['mod'] + $foreign['add'] as $keyName) {
612             $this->appendAlterAddForeign($phrase, $keyName, $def['foreign keys'][$keyName]);
613         }
614
615         $this->appendAlterExtras($phrase, $tableName, $def);
616
617         if (count($phrase) > 0) {
618             $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(",\n", $phrase);
619             $statements[] = $sql;
620         }
621
622         // Now create any indexes...
623         foreach ($indexes['mod'] + $indexes['add'] as $indexName) {
624             $this->appendCreateIndex($statements, $tableName, $indexName, $def['indexes'][$indexName]);
625         }
626
627         return $statements;
628     }
629
630     function diffArrays($oldDef, $newDef, $section, $compareCallback=null)
631     {
632         $old = isset($oldDef[$section]) ? $oldDef[$section] : array();
633         $new = isset($newDef[$section]) ? $newDef[$section] : array();
634
635         $oldKeys = array_keys($old);
636         $newKeys = array_keys($new);
637
638         $toadd  = array_diff($newKeys, $oldKeys);
639         $todrop = array_diff($oldKeys, $newKeys);
640         $same   = array_intersect($newKeys, $oldKeys);
641         $tomod  = array();
642         $tokeep = array();
643
644         // Find which fields have actually changed definition
645         // in a way that we need to tweak them for this DB type.
646         foreach ($same as $name) {
647             if ($compareCallback) {
648                 $same = call_user_func($compareCallback, $old[$name], $new[$name]);
649             } else {
650                 $same = ($old[$name] == $new[$name]);
651             }
652             if ($same) {
653                 $tokeep[] = $name;
654                 continue;
655             }
656             $tomod[] = $name;
657         }
658         return array('add' => $toadd,
659                      'del' => $todrop,
660                      'mod' => $tomod,
661                      'keep' => $tokeep,
662                      'count' => count($toadd) + count($todrop) + count($tomod));
663     }
664
665     /**
666      * Append phrase(s) to an array of partial ALTER TABLE chunks in order
667      * to add the given column definition to the table.
668      *
669      * @param array $phrase
670      * @param string $columnName
671      * @param array $cd 
672      */
673     function appendAlterAddColumn(array &$phrase, $columnName, array $cd)
674     {
675         $phrase[] = 'ADD COLUMN ' .
676                     $this->quoteIdentifier($columnName) .
677                     ' ' .
678                     $this->columnSql($cd);
679     }
680
681     /**
682      * Append phrase(s) to an array of partial ALTER TABLE chunks in order
683      * to alter the given column from its old state to a new one.
684      *
685      * @param array $phrase
686      * @param string $columnName
687      * @param array $old previous column definition as found in DB
688      * @param array $cd current column definition
689      */
690     function appendAlterModifyColumn(array &$phrase, $columnName, array $old, array $cd)
691     {
692         $phrase[] = 'MODIFY COLUMN ' .
693                     $this->quoteIdentifier($columnName) .
694                     ' ' .
695                     $this->columnSql($cd);
696     }
697
698     /**
699      * Append phrase(s) to an array of partial ALTER TABLE chunks in order
700      * to drop the given column definition from the table.
701      *
702      * @param array $phrase
703      * @param string $columnName
704      */
705     function appendAlterDropColumn(array &$phrase, $columnName)
706     {
707         $phrase[] = 'DROP COLUMN ' . $this->quoteIdentifier($columnName);
708     }
709
710     function appendAlterAddUnique(array &$phrase, $keyName, array $def)
711     {
712         $sql = array();
713         $sql[] = 'ADD';
714         $this->appendUniqueKeyDef($sql, $keyName, $def);
715         $phrase[] = implode(' ', $sql);
716     }
717
718     function appendAlterAddForeign(array &$phrase, $keyName, array $def)
719     {
720         $sql = array();
721         $sql[] = 'ADD';
722         $this->appendForeignKeyDef($sql, $keyName, $def);
723         $phrase[] = implode(' ', $sql);
724     }
725
726     function appendAlterAddPrimary(array &$phrase, array $def)
727     {
728         $sql = array();
729         $sql[] = 'ADD';
730         $this->appendPrimaryKeyDef($sql, $def);
731         $phrase[] = implode(' ', $sql);
732     }
733
734     function appendAlterDropPrimary(array &$phrase)
735     {
736         $phrase[] = 'DROP CONSTRAINT PRIMARY KEY';
737     }
738
739     function appendAlterDropUnique(array &$phrase, $keyName)
740     {
741         $phrase[] = 'DROP CONSTRAINT ' . $keyName;
742     }
743
744     function appendAlterDropForeign(array &$phrase, $keyName)
745     {
746         $phrase[] = 'DROP FOREIGN KEY ' . $keyName;
747     }
748
749     function appendAlterExtras(array &$phrase, $tableName, array $def)
750     {
751         // no-op
752     }
753
754     /**
755      * Quote a db/table/column identifier if necessary.
756      *
757      * @param string $name
758      * @return string
759      */
760     function quoteIdentifier($name)
761     {
762         return $name;
763     }
764
765     function quoteDefaultValue($cd)
766     {
767         if ($cd['type'] == 'datetime' && $cd['default'] == 'CURRENT_TIMESTAMP') {
768             return $cd['default'];
769         } else {
770             return $this->quoteValue($cd['default']);
771         }
772     }
773
774     function quoteValue($val)
775     {
776         return $this->conn->quoteSmart($val);
777     }
778
779     /**
780      * Check if two column definitions are equivalent.
781      * The default implementation checks _everything_ but in many cases
782      * you may be able to discard a bunch of equivalencies.
783      *
784      * @param array $a
785      * @param array $b
786      * @return boolean
787      */
788     function columnsEqual(array $a, array $b)
789     {
790         return !array_diff_assoc($a, $b) && !array_diff_assoc($b, $a);
791     }
792
793     /**
794      * Returns the array of names from an array of
795      * ColumnDef objects.
796      *
797      * @param array $cds array of ColumnDef objects
798      *
799      * @return array strings for name values
800      */
801
802     protected function _names($cds)
803     {
804         $names = array();
805
806         foreach ($cds as $cd) {
807             $names[] = $cd->name;
808         }
809
810         return $names;
811     }
812
813     /**
814      * Get a ColumnDef from an array matching
815      * name.
816      *
817      * @param array  $cds  Array of ColumnDef objects
818      * @param string $name Name of the column
819      *
820      * @return ColumnDef matching item or null if no match.
821      */
822
823     protected function _byName($cds, $name)
824     {
825         foreach ($cds as $cd) {
826             if ($cd->name == $name) {
827                 return $cd;
828             }
829         }
830
831         return null;
832     }
833
834     /**
835      * Return the proper SQL for creating or
836      * altering a column.
837      *
838      * Appropriate for use in CREATE TABLE or
839      * ALTER TABLE statements.
840      *
841      * @param ColumnDef $cd column to create
842      *
843      * @return string correct SQL for that column
844      */
845
846     function columnSql(array $cd)
847     {
848         $line = array();
849         $line[] = $this->typeAndSize($cd);
850
851         if (isset($cd['default'])) {
852             $line[] = 'default';
853             $line[] = $this->quoteDefaultValue($cd);
854         } else if (!empty($cd['not null'])) {
855             // Can't have both not null AND default!
856             $line[] = 'not null';
857         }
858
859         return implode(' ', $line);
860     }
861
862     /**
863      *
864      * @param string $column canonical type name in defs
865      * @return string native DB type name
866      */
867     function mapType($column)
868     {
869         return $column;
870     }
871
872     function typeAndSize($column)
873     {
874         //$type = $this->mapType($column);
875         $type = $column['type'];
876         if (isset($column['size'])) {
877             $type = $column['size'] . $type;
878         }
879         $lengths = array();
880
881         if (isset($column['precision'])) {
882             $lengths[] = $column['precision'];
883             if (isset($column['scale'])) {
884                 $lengths[] = $column['scale'];
885             }
886         } else if (isset($column['length'])) {
887             $lengths[] = $column['length'];
888         }
889
890         if ($lengths) {
891             return $type . '(' . implode(',', $lengths) . ')';
892         } else {
893             return $type;
894         }
895     }
896
897     /**
898      * Convert an old-style set of ColumnDef objects into the current
899      * Drupal-style schema definition array, for backwards compatibility
900      * with plugins written for 0.9.x.
901      *
902      * @param string $tableName
903      * @param array $defs: array of ColumnDef objects
904      * @return array
905      */
906     protected function oldToNew($tableName, array $defs)
907     {
908         $table = array();
909         $prefixes = array(
910             'tiny',
911             'small',
912             'medium',
913             'big',
914         );
915         foreach ($defs as $cd) {
916             $column = array();
917             $column['type'] = $cd->type;
918             foreach ($prefixes as $prefix) {
919                 if (substr($cd->type, 0, strlen($prefix)) == $prefix) {
920                     $column['type'] = substr($cd->type, strlen($prefix));
921                     $column['size'] = $prefix;
922                     break;
923                 }
924             }
925
926             if ($cd->size) {
927                 if ($cd->type == 'varchar' || $cd->type == 'char') {
928                     $column['length'] = $cd->size;
929                 }
930             }
931             if (!$cd->nullable) {
932                 $column['not null'] = true;
933             }
934             if ($cd->auto_increment) {
935                 $column['type'] = 'serial';
936             }
937             if ($cd->default) {
938                 $column['default'] = $cd->default;
939             }
940             $table['fields'][$cd->name] = $column;
941
942             if ($cd->key == 'PRI') {
943                 // If multiple columns are defined as primary key,
944                 // we'll pile them on in sequence.
945                 if (!isset($table['primary key'])) {
946                     $table['primary key'] = array();
947                 }
948                 $table['primary key'][] = $cd->name;
949             } else if ($cd->key == 'MUL') {
950                 // Individual multiple-value indexes are only per-column
951                 // using the old ColumnDef syntax.
952                 $idx = "{$tableName}_{$cd->name}_idx";
953                 $table['indexes'][$idx] = array($cd->name);
954             } else if ($cd->key == 'UNI') {
955                 // Individual unique-value indexes are only per-column
956                 // using the old ColumnDef syntax.
957                 $idx = "{$tableName}_{$cd->name}_idx";
958                 $table['unique keys'][$idx] = array($cd->name);
959             }
960         }
961
962         return $table;
963     }
964
965     /**
966      * Filter the given table definition array to match features available
967      * in this database.
968      *
969      * This lets us strip out unsupported things like comments, foreign keys,
970      * or type variants that we wouldn't get back from getTableDef().
971      *
972      * @param array $tableDef
973      */
974     function filterDef(array $tableDef)
975     {
976         return $tableDef;
977     }
978
979     /**
980      * Validate a table definition array, checking for basic structure.
981      *
982      * If necessary, converts from an old-style array of ColumnDef objects.
983      *
984      * @param string $tableName
985      * @param array $def: table definition array
986      * @return array validated table definition array
987      *
988      * @throws Exception on wildly invalid input
989      */
990     function validateDef($tableName, array $def)
991     {
992         if (isset($def[0]) && $def[0] instanceof ColumnDef) {
993             $def = $this->oldToNew($tableName, $def);
994         }
995
996         // A few quick checks :D
997         if (!isset($def['fields'])) {
998             throw new Exception("Invalid table definition for $tableName: no fields.");
999         }
1000
1001         return $def;
1002     }
1003
1004     function isNumericType($type)
1005     {
1006         $type = strtolower($type);
1007         $known = array('int', 'serial', 'numeric');
1008         return in_array($type, $known);
1009     }
1010
1011     /**
1012      * Pull info from the query into a fun-fun array of dooooom
1013      *
1014      * @param string $sql
1015      * @return array of arrays
1016      */
1017     protected function fetchQueryData($sql)
1018     {
1019         $res = $this->conn->query($sql);
1020         if (PEAR::isError($res)) {
1021             throw new Exception($res->getMessage());
1022         }
1023
1024         $out = array();
1025         $row = array();
1026         while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
1027             $out[] = $row;
1028         }
1029         $res->free();
1030
1031         return $out;
1032     }
1033
1034 }
1035
1036 class SchemaTableMissingException extends Exception
1037 {
1038     // no-op
1039 }
1040