]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/schema.php
Merge branch 'fixes/private_scope_on_tags' into social-master
[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         global $_PEAR;
349
350         $res = $this->conn->query("DROP TABLE $name");
351
352         if ($_PEAR->isError($res)) {
353             throw new Exception($res->getMessage());
354         }
355
356         return true;
357     }
358
359     /**
360      * Adds an index to a table.
361      *
362      * If no name is provided, a name will be made up based
363      * on the table name and column names.
364      *
365      * Throws an exception on database error, esp. if the table
366      * does not exist.
367      *
368      * @param string $table       Name of the table
369      * @param array  $columnNames Name of columns to index
370      * @param string $name        (Optional) name of the index
371      *
372      * @return boolean success flag
373      */
374
375     public function createIndex($table, $columnNames, $name=null)
376     {
377         global $_PEAR;
378
379         if (!is_array($columnNames)) {
380             $columnNames = array($columnNames);
381         }
382
383         if (empty($name)) {
384             $name = "{$table}_".implode("_", $columnNames)."_idx";
385         }
386
387         $res = $this->conn->query("ALTER TABLE $table ".
388                                    "ADD INDEX $name (".
389                                    implode(",", $columnNames).")");
390
391         if ($_PEAR->isError($res)) {
392             throw new Exception($res->getMessage());
393         }
394
395         return true;
396     }
397
398     /**
399      * Drops a named index from a table.
400      *
401      * @param string $table name of the table the index is on.
402      * @param string $name  name of the index
403      *
404      * @return boolean success flag
405      */
406
407     public function dropIndex($table, $name)
408     {
409         global $_PEAR;
410
411         $res = $this->conn->query("ALTER TABLE $table DROP INDEX $name");
412
413         if ($_PEAR->isError($res)) {
414             throw new Exception($res->getMessage());
415         }
416
417         return true;
418     }
419
420     /**
421      * Adds a column to a table
422      *
423      * @param string    $table     name of the table
424      * @param ColumnDef $columndef Definition of the new
425      *                             column.
426      *
427      * @return boolean success flag
428      */
429
430     public function addColumn($table, $columndef)
431     {
432         global $_PEAR;
433
434         $sql = "ALTER TABLE $table ADD COLUMN " . $this->_columnSql($columndef);
435
436         $res = $this->conn->query($sql);
437
438         if ($_PEAR->isError($res)) {
439             throw new Exception($res->getMessage());
440         }
441
442         return true;
443     }
444
445     /**
446      * Modifies a column in the schema.
447      *
448      * The name must match an existing column and table.
449      *
450      * @param string    $table     name of the table
451      * @param ColumnDef $columndef new definition of the column.
452      *
453      * @return boolean success flag
454      */
455
456     public function modifyColumn($table, $columndef)
457     {
458         global $_PEAR;
459
460         $sql = "ALTER TABLE $table MODIFY COLUMN " .
461           $this->_columnSql($columndef);
462
463         $res = $this->conn->query($sql);
464
465         if ($_PEAR->isError($res)) {
466             throw new Exception($res->getMessage());
467         }
468
469         return true;
470     }
471
472     /**
473      * Drops a column from a table
474      *
475      * The name must match an existing column.
476      *
477      * @param string $table      name of the table
478      * @param string $columnName name of the column to drop
479      *
480      * @return boolean success flag
481      */
482
483     public function dropColumn($table, $columnName)
484     {
485         global $_PEAR;
486
487         $sql = "ALTER TABLE $table DROP COLUMN $columnName";
488
489         $res = $this->conn->query($sql);
490
491         if ($_PEAR->isError($res)) {
492             throw new Exception($res->getMessage());
493         }
494
495         return true;
496     }
497
498     /**
499      * Ensures that a table exists with the given
500      * name and the given column definitions.
501      *
502      * If the table does not yet exist, it will
503      * create the table. If it does exist, it will
504      * alter the table to match the column definitions.
505      *
506      * @param string $tableName name of the table
507      * @param array  $def       Table definition array
508      *
509      * @return boolean success flag
510      */
511
512     public function ensureTable($tableName, $def)
513     {
514         $statements = $this->buildEnsureTable($tableName, $def);
515         return $this->runSqlSet($statements);
516     }
517
518     /**
519      * Run a given set of SQL commands on the connection in sequence.
520      * Empty input is ok.
521      *
522      * @fixme if multiple statements, wrap in a transaction?
523      * @param array $statements
524      * @return boolean success flag
525      */
526     function runSqlSet(array $statements)
527     {
528         global $_PEAR;
529
530         $ok = true;
531         foreach ($statements as $sql) {
532             if (defined('DEBUG_INSTALLER')) {
533                 echo "<tt>" . htmlspecialchars($sql) . "</tt><br/>\n";
534             }
535             $res = $this->conn->query($sql);
536
537             if ($_PEAR->isError($res)) {
538                 throw new Exception($res->getMessage());
539             }
540         }
541         return $ok;
542     }
543
544     /**
545      * Check a table's status, and if needed build a set
546      * of SQL statements which change it to be consistent
547      * with the given table definition.
548      *
549      * If the table does not yet exist, statements will
550      * be returned to create the table. If it does exist,
551      * statements will be returned to alter the table to
552      * match the column definitions.
553      *
554      * @param string $tableName name of the table
555      * @param array  $columns   array of ColumnDef
556      *                          objects for the table
557      *
558      * @return array of SQL statements
559      */
560
561     function buildEnsureTable($tableName, array $def)
562     {
563         try {
564             $old = $this->getTableDef($tableName);
565         } catch (SchemaTableMissingException $e) {
566             return $this->buildCreateTable($tableName, $def);
567         }
568
569         // Filter the DB-independent table definition to match the current
570         // database engine's features and limitations.
571         $def = $this->validateDef($tableName, $def);
572         $def = $this->filterDef($def);
573
574         $statements = array();
575         $fields = $this->diffArrays($old, $def, 'fields', array($this, 'columnsEqual'));
576         $uniques = $this->diffArrays($old, $def, 'unique keys');
577         $indexes = $this->diffArrays($old, $def, 'indexes');
578         $foreign = $this->diffArrays($old, $def, 'foreign keys');
579         $fulltext = $this->diffArrays($old, $def, 'fulltext indexes');
580
581         // Drop any obsolete or modified indexes ahead...
582         foreach ($indexes['del'] + $indexes['mod'] as $indexName) {
583             $this->appendDropIndex($statements, $tableName, $indexName);
584         }
585
586         // Drop any obsolete or modified fulltext indexes ahead...
587         foreach ($fulltext['del'] + $fulltext['mod'] as $indexName) {
588             $this->appendDropIndex($statements, $tableName, $indexName);
589         }
590
591         // For efficiency, we want this all in one
592         // query, instead of using our methods.
593
594         $phrase = array();
595
596         foreach ($foreign['del'] + $foreign['mod'] as $keyName) {
597             $this->appendAlterDropForeign($phrase, $keyName);
598         }
599
600         foreach ($uniques['del'] + $uniques['mod'] as $keyName) {
601             $this->appendAlterDropUnique($phrase, $keyName);
602         }
603
604         if (isset($old['primary key']) && (!isset($def['primary key']) || $def['primary key'] != $old['primary key'])) {
605             $this->appendAlterDropPrimary($phrase);
606         }
607
608         foreach ($fields['add'] as $columnName) {
609             $this->appendAlterAddColumn($phrase, $columnName,
610                     $def['fields'][$columnName]);
611         }
612
613         foreach ($fields['mod'] as $columnName) {
614             $this->appendAlterModifyColumn($phrase, $columnName,
615                     $old['fields'][$columnName],
616                     $def['fields'][$columnName]);
617         }
618
619         foreach ($fields['del'] as $columnName) {
620             $this->appendAlterDropColumn($phrase, $columnName);
621         }
622
623         if (isset($def['primary key']) && (!isset($old['primary key']) || $old['primary key'] != $def['primary key'])) {
624             $this->appendAlterAddPrimary($phrase, $def['primary key']);
625         }
626
627         foreach ($uniques['mod'] + $uniques['add'] as $keyName) {
628             $this->appendAlterAddUnique($phrase, $keyName, $def['unique keys'][$keyName]);
629         }
630
631         foreach ($foreign['mod'] + $foreign['add'] as $keyName) {
632             $this->appendAlterAddForeign($phrase, $keyName, $def['foreign keys'][$keyName]);
633         }
634
635         $this->appendAlterExtras($phrase, $tableName, $def);
636
637         if (count($phrase) > 0) {
638             $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(",\n", $phrase);
639             $statements[] = $sql;
640         }
641
642         // Now create any indexes...
643         foreach ($indexes['mod'] + $indexes['add'] as $indexName) {
644             $this->appendCreateIndex($statements, $tableName, $indexName, $def['indexes'][$indexName]);
645         }
646
647         foreach ($fulltext['mod'] + $fulltext['add'] as $indexName) {
648             $colDef = $def['fulltext indexes'][$indexName];
649             $this->appendCreateFulltextIndex($statements, $tableName, $indexName, $colDef);
650         }
651
652         return $statements;
653     }
654
655     function diffArrays($oldDef, $newDef, $section, $compareCallback=null)
656     {
657         $old = isset($oldDef[$section]) ? $oldDef[$section] : array();
658         $new = isset($newDef[$section]) ? $newDef[$section] : array();
659
660         $oldKeys = array_keys($old);
661         $newKeys = array_keys($new);
662
663         $toadd  = array_diff($newKeys, $oldKeys);
664         $todrop = array_diff($oldKeys, $newKeys);
665         $same   = array_intersect($newKeys, $oldKeys);
666         $tomod  = array();
667         $tokeep = array();
668
669         // Find which fields have actually changed definition
670         // in a way that we need to tweak them for this DB type.
671         foreach ($same as $name) {
672             if ($compareCallback) {
673                 $same = call_user_func($compareCallback, $old[$name], $new[$name]);
674             } else {
675                 $same = ($old[$name] == $new[$name]);
676             }
677             if ($same) {
678                 $tokeep[] = $name;
679                 continue;
680             }
681             $tomod[] = $name;
682         }
683         return array('add' => $toadd,
684                      'del' => $todrop,
685                      'mod' => $tomod,
686                      'keep' => $tokeep,
687                      'count' => count($toadd) + count($todrop) + count($tomod));
688     }
689
690     /**
691      * Append phrase(s) to an array of partial ALTER TABLE chunks in order
692      * to add the given column definition to the table.
693      *
694      * @param array $phrase
695      * @param string $columnName
696      * @param array $cd 
697      */
698     function appendAlterAddColumn(array &$phrase, $columnName, array $cd)
699     {
700         $phrase[] = 'ADD COLUMN ' .
701                     $this->quoteIdentifier($columnName) .
702                     ' ' .
703                     $this->columnSql($cd);
704     }
705
706     /**
707      * Append phrase(s) to an array of partial ALTER TABLE chunks in order
708      * to alter the given column from its old state to a new one.
709      *
710      * @param array $phrase
711      * @param string $columnName
712      * @param array $old previous column definition as found in DB
713      * @param array $cd current column definition
714      */
715     function appendAlterModifyColumn(array &$phrase, $columnName, array $old, array $cd)
716     {
717         $phrase[] = 'MODIFY COLUMN ' .
718                     $this->quoteIdentifier($columnName) .
719                     ' ' .
720                     $this->columnSql($cd);
721     }
722
723     /**
724      * Append phrase(s) to an array of partial ALTER TABLE chunks in order
725      * to drop the given column definition from the table.
726      *
727      * @param array $phrase
728      * @param string $columnName
729      */
730     function appendAlterDropColumn(array &$phrase, $columnName)
731     {
732         $phrase[] = 'DROP COLUMN ' . $this->quoteIdentifier($columnName);
733     }
734
735     function appendAlterAddUnique(array &$phrase, $keyName, array $def)
736     {
737         $sql = array();
738         $sql[] = 'ADD';
739         $this->appendUniqueKeyDef($sql, $keyName, $def);
740         $phrase[] = implode(' ', $sql);
741     }
742
743     function appendAlterAddForeign(array &$phrase, $keyName, array $def)
744     {
745         $sql = array();
746         $sql[] = 'ADD';
747         $this->appendForeignKeyDef($sql, $keyName, $def);
748         $phrase[] = implode(' ', $sql);
749     }
750
751     function appendAlterAddPrimary(array &$phrase, array $def)
752     {
753         $sql = array();
754         $sql[] = 'ADD';
755         $this->appendPrimaryKeyDef($sql, $def);
756         $phrase[] = implode(' ', $sql);
757     }
758
759     function appendAlterDropPrimary(array &$phrase)
760     {
761         $phrase[] = 'DROP CONSTRAINT PRIMARY KEY';
762     }
763
764     function appendAlterDropUnique(array &$phrase, $keyName)
765     {
766         $phrase[] = 'DROP CONSTRAINT ' . $keyName;
767     }
768
769     function appendAlterDropForeign(array &$phrase, $keyName)
770     {
771         $phrase[] = 'DROP FOREIGN KEY ' . $keyName;
772     }
773
774     function appendAlterExtras(array &$phrase, $tableName, array $def)
775     {
776         // no-op
777     }
778
779     /**
780      * Quote a db/table/column identifier if necessary.
781      *
782      * @param string $name
783      * @return string
784      */
785     function quoteIdentifier($name)
786     {
787         return $name;
788     }
789
790     function quoteDefaultValue($cd)
791     {
792         if ($cd['type'] == 'datetime' && $cd['default'] == 'CURRENT_TIMESTAMP') {
793             return $cd['default'];
794         } else {
795             return $this->quoteValue($cd['default']);
796         }
797     }
798
799     function quoteValue($val)
800     {
801         return $this->conn->quoteSmart($val);
802     }
803
804     /**
805      * Check if two column definitions are equivalent.
806      * The default implementation checks _everything_ but in many cases
807      * you may be able to discard a bunch of equivalencies.
808      *
809      * @param array $a
810      * @param array $b
811      * @return boolean
812      */
813     function columnsEqual(array $a, array $b)
814     {
815         return !array_diff_assoc($a, $b) && !array_diff_assoc($b, $a);
816     }
817
818     /**
819      * Returns the array of names from an array of
820      * ColumnDef objects.
821      *
822      * @param array $cds array of ColumnDef objects
823      *
824      * @return array strings for name values
825      */
826
827     protected function _names($cds)
828     {
829         $names = array();
830
831         foreach ($cds as $cd) {
832             $names[] = $cd->name;
833         }
834
835         return $names;
836     }
837
838     /**
839      * Get a ColumnDef from an array matching
840      * name.
841      *
842      * @param array  $cds  Array of ColumnDef objects
843      * @param string $name Name of the column
844      *
845      * @return ColumnDef matching item or null if no match.
846      */
847
848     protected function _byName($cds, $name)
849     {
850         foreach ($cds as $cd) {
851             if ($cd->name == $name) {
852                 return $cd;
853             }
854         }
855
856         return null;
857     }
858
859     /**
860      * Return the proper SQL for creating or
861      * altering a column.
862      *
863      * Appropriate for use in CREATE TABLE or
864      * ALTER TABLE statements.
865      *
866      * @param ColumnDef $cd column to create
867      *
868      * @return string correct SQL for that column
869      */
870
871     function columnSql(array $cd)
872     {
873         $line = array();
874         $line[] = $this->typeAndSize($cd);
875
876         if (isset($cd['default'])) {
877             $line[] = 'default';
878             $line[] = $this->quoteDefaultValue($cd);
879         } else if (!empty($cd['not null'])) {
880             // Can't have both not null AND default!
881             $line[] = 'not null';
882         }
883
884         return implode(' ', $line);
885     }
886
887     /**
888      *
889      * @param string $column canonical type name in defs
890      * @return string native DB type name
891      */
892     function mapType($column)
893     {
894         return $column;
895     }
896
897     function typeAndSize($column)
898     {
899         //$type = $this->mapType($column);
900         $type = $column['type'];
901         if (isset($column['size'])) {
902             $type = $column['size'] . $type;
903         }
904         $lengths = array();
905
906         if (isset($column['precision'])) {
907             $lengths[] = $column['precision'];
908             if (isset($column['scale'])) {
909                 $lengths[] = $column['scale'];
910             }
911         } else if (isset($column['length'])) {
912             $lengths[] = $column['length'];
913         }
914
915         if ($lengths) {
916             return $type . '(' . implode(',', $lengths) . ')';
917         } else {
918             return $type;
919         }
920     }
921
922     /**
923      * Convert an old-style set of ColumnDef objects into the current
924      * Drupal-style schema definition array, for backwards compatibility
925      * with plugins written for 0.9.x.
926      *
927      * @param string $tableName
928      * @param array $defs: array of ColumnDef objects
929      * @return array
930      */
931     protected function oldToNew($tableName, array $defs)
932     {
933         $table = array();
934         $prefixes = array(
935             'tiny',
936             'small',
937             'medium',
938             'big',
939         );
940         foreach ($defs as $cd) {
941             $column = array();
942             $column['type'] = $cd->type;
943             foreach ($prefixes as $prefix) {
944                 if (substr($cd->type, 0, strlen($prefix)) == $prefix) {
945                     $column['type'] = substr($cd->type, strlen($prefix));
946                     $column['size'] = $prefix;
947                     break;
948                 }
949             }
950
951             if ($cd->size) {
952                 if ($cd->type == 'varchar' || $cd->type == 'char') {
953                     $column['length'] = $cd->size;
954                 }
955             }
956             if (!$cd->nullable) {
957                 $column['not null'] = true;
958             }
959             if ($cd->auto_increment) {
960                 $column['type'] = 'serial';
961             }
962             if ($cd->default) {
963                 $column['default'] = $cd->default;
964             }
965             $table['fields'][$cd->name] = $column;
966
967             if ($cd->key == 'PRI') {
968                 // If multiple columns are defined as primary key,
969                 // we'll pile them on in sequence.
970                 if (!isset($table['primary key'])) {
971                     $table['primary key'] = array();
972                 }
973                 $table['primary key'][] = $cd->name;
974             } else if ($cd->key == 'MUL') {
975                 // Individual multiple-value indexes are only per-column
976                 // using the old ColumnDef syntax.
977                 $idx = "{$tableName}_{$cd->name}_idx";
978                 $table['indexes'][$idx] = array($cd->name);
979             } else if ($cd->key == 'UNI') {
980                 // Individual unique-value indexes are only per-column
981                 // using the old ColumnDef syntax.
982                 $idx = "{$tableName}_{$cd->name}_idx";
983                 $table['unique keys'][$idx] = array($cd->name);
984             }
985         }
986
987         return $table;
988     }
989
990     /**
991      * Filter the given table definition array to match features available
992      * in this database.
993      *
994      * This lets us strip out unsupported things like comments, foreign keys,
995      * or type variants that we wouldn't get back from getTableDef().
996      *
997      * @param array $tableDef
998      */
999     function filterDef(array $tableDef)
1000     {
1001         return $tableDef;
1002     }
1003
1004     /**
1005      * Validate a table definition array, checking for basic structure.
1006      *
1007      * If necessary, converts from an old-style array of ColumnDef objects.
1008      *
1009      * @param string $tableName
1010      * @param array $def: table definition array
1011      * @return array validated table definition array
1012      *
1013      * @throws Exception on wildly invalid input
1014      */
1015     function validateDef($tableName, array $def)
1016     {
1017         if (isset($def[0]) && $def[0] instanceof ColumnDef) {
1018             $def = $this->oldToNew($tableName, $def);
1019         }
1020
1021         // A few quick checks :D
1022         if (!isset($def['fields'])) {
1023             throw new Exception("Invalid table definition for $tableName: no fields.");
1024         }
1025
1026         return $def;
1027     }
1028
1029     function isNumericType($type)
1030     {
1031         $type = strtolower($type);
1032         $known = array('int', 'serial', 'numeric');
1033         return in_array($type, $known);
1034     }
1035
1036     /**
1037      * Pull info from the query into a fun-fun array of dooooom
1038      *
1039      * @param string $sql
1040      * @return array of arrays
1041      */
1042     protected function fetchQueryData($sql)
1043     {
1044         global $_PEAR;
1045
1046         $res = $this->conn->query($sql);
1047         if ($_PEAR->isError($res)) {
1048             throw new Exception($res->getMessage());
1049         }
1050
1051         $out = array();
1052         $row = array();
1053         while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
1054             $out[] = $row;
1055         }
1056         $res->free();
1057
1058         return $out;
1059     }
1060
1061 }
1062
1063 class SchemaTableMissingException extends Exception
1064 {
1065     // no-op
1066 }
1067