]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/schema.php
fix typo on params on Schema->createTable()
[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         foreach ($td->columns as $cd) {
111             if ($cd->name == $column) {
112                 return $cd;
113             }
114         }
115
116         return null;
117     }
118
119     /**
120      * Creates a table with the given names and columns.
121      *
122      * @param string $tableName    Name of the table
123      * @param array  $def          Table definition array listing fields and indexes.
124      *
125      * @return boolean success flag
126      */
127
128     public function createTable($tableName, $def)
129     {
130         $statements = $this->buildCreateTable($tableName, $def);
131         return $this->runSqlSet($statements);
132     }
133
134     /**
135      * Build a set of SQL statements to create a table with the given
136      * name and columns.
137      *
138      * @param string $name    Name of the table
139      * @param array  $def     Table definition array
140      *
141      * @return boolean success flag
142      */
143     public function buildCreateTable($name, $def)
144     {
145         $def = $this->filterDef($def);
146         $sql = array();
147
148         foreach ($def['fields'] as $col => $colDef) {
149             $this->appendColumnDef($sql, $col, $colDef);
150         }
151
152         // Primary and unique keys are constraints, so go within
153         // the CREATE TABLE statement normally.
154         if (!empty($def['primary key'])) {
155             $this->appendPrimaryKeyDef($sql, $def['primary key']);
156         }
157
158         if (!empty($def['unique keys'])) {
159             foreach ($def['unique keys'] as $col => $colDef) {
160                 $this->appendUniqueKeyDef($sql, $col, $colDef);
161             }
162         }
163
164         // Multi-value indexes are advisory and for best portability
165         // should be created as separate statements.
166         $statements = array();
167         $statements[] = $this->startCreateTable($name, $def) . "\n" .
168                         implode($sql, ",\n") . "\n" .
169                         $this->endCreateTable($name, $def);
170         if (!empty($def['indexes'])) {
171             foreach ($def['indexes'] as $col => $colDef) {
172                 $this->appendCreateIndex($statements, $name, $col, $colDef);
173             }
174         }
175
176         return $statements;
177     }
178
179     /**
180      * Set up a 'create table' SQL statement.
181      *
182      * @param string $name table name
183      * @param array $def table definition
184      * @param $string
185      */
186     function startCreateTable($name, array $def)
187     {
188         return 'CREATE TABLE ' . $this->quoteIdentifier($name)  . ' (';
189     }
190
191     /**
192      * Close out a 'create table' SQL statement.
193      *
194      * @param string $name table name
195      * @param array $def table definition
196      * @return string
197      */
198     function endCreateTable($name, array $def)
199     {
200         return ')';
201     }
202
203     /**
204      * Append an SQL fragment with a column definition in a CREATE TABLE statement.
205      *
206      * @param array $sql
207      * @param string $name
208      * @param array $def
209      */
210     function appendColumnDef(array &$sql, $name, array $def)
211     {
212         $sql[] = "$name " . $this->columnSql($def);
213     }
214
215     /**
216      * Append an SQL fragment with a constraint definition for a primary
217      * key in a CREATE TABLE statement.
218      *
219      * @param array $sql
220      * @param array $def
221      */
222     function appendPrimaryKeyDef(array &$sql, array $def)
223     {
224         $sql[] = "PRIMARY KEY " . $this->buildIndexList($def);
225     }
226
227     /**
228      * Append an SQL fragment with a constraint definition for a primary
229      * key in a CREATE TABLE statement.
230      *
231      * @param array $sql
232      * @param string $name
233      * @param array $def
234      */
235     function appendUniqueKeyDef(array &$sql, $name, array $def)
236     {
237         $sql[] = "UNIQUE $name " . $this->buildIndexList($def);
238     }
239
240     /**
241      * Append an SQL statement with an index definition for an advisory
242      * index over one or more columns on a table.
243      *
244      * @param array $statements
245      * @param string $table
246      * @param string $name
247      * @param array $def
248      */
249     function appendCreateIndex(array &$statements, $table, $name, array $def)
250     {
251         $statements[] = "CREATE INDEX $name ON $table " . $this->buildIndexList($def);
252     }
253
254     function buildIndexList(array $def)
255     {
256         // @fixme
257         return '(' . implode(',', array_map(array($this, 'buildIndexItem'), $def)) . ')';
258     }
259
260     function buildIndexItem($def)
261     {
262         if (is_array($def)) {
263             list($name, $size) = $def;
264             return $this->quoteIdentifier($name) . '(' . intval($size) . ')';
265         }
266         return $this->quoteIdentifier($def);
267     }
268
269     /**
270      * Drops a table from the schema
271      *
272      * Throws an exception if the table is not found.
273      *
274      * @param string $name Name of the table to drop
275      *
276      * @return boolean success flag
277      */
278
279     public function dropTable($name)
280     {
281         $res = $this->conn->query("DROP TABLE $name");
282
283         if (PEAR::isError($res)) {
284             throw new Exception($res->getMessage());
285         }
286
287         return true;
288     }
289
290     /**
291      * Adds an index to a table.
292      *
293      * If no name is provided, a name will be made up based
294      * on the table name and column names.
295      *
296      * Throws an exception on database error, esp. if the table
297      * does not exist.
298      *
299      * @param string $table       Name of the table
300      * @param array  $columnNames Name of columns to index
301      * @param string $name        (Optional) name of the index
302      *
303      * @return boolean success flag
304      */
305
306     public function createIndex($table, $columnNames, $name=null)
307     {
308         if (!is_array($columnNames)) {
309             $columnNames = array($columnNames);
310         }
311
312         if (empty($name)) {
313             $name = "{$table}_".implode("_", $columnNames)."_idx";
314         }
315
316         $res = $this->conn->query("ALTER TABLE $table ".
317                                    "ADD INDEX $name (".
318                                    implode(",", $columnNames).")");
319
320         if (PEAR::isError($res)) {
321             throw new Exception($res->getMessage());
322         }
323
324         return true;
325     }
326
327     /**
328      * Drops a named index from a table.
329      *
330      * @param string $table name of the table the index is on.
331      * @param string $name  name of the index
332      *
333      * @return boolean success flag
334      */
335
336     public function dropIndex($table, $name)
337     {
338         $res = $this->conn->query("ALTER TABLE $table DROP INDEX $name");
339
340         if (PEAR::isError($res)) {
341             throw new Exception($res->getMessage());
342         }
343
344         return true;
345     }
346
347     /**
348      * Adds a column to a table
349      *
350      * @param string    $table     name of the table
351      * @param ColumnDef $columndef Definition of the new
352      *                             column.
353      *
354      * @return boolean success flag
355      */
356
357     public function addColumn($table, $columndef)
358     {
359         $sql = "ALTER TABLE $table ADD COLUMN " . $this->_columnSql($columndef);
360
361         $res = $this->conn->query($sql);
362
363         if (PEAR::isError($res)) {
364             throw new Exception($res->getMessage());
365         }
366
367         return true;
368     }
369
370     /**
371      * Modifies a column in the schema.
372      *
373      * The name must match an existing column and table.
374      *
375      * @param string    $table     name of the table
376      * @param ColumnDef $columndef new definition of the column.
377      *
378      * @return boolean success flag
379      */
380
381     public function modifyColumn($table, $columndef)
382     {
383         $sql = "ALTER TABLE $table MODIFY COLUMN " .
384           $this->_columnSql($columndef);
385
386         $res = $this->conn->query($sql);
387
388         if (PEAR::isError($res)) {
389             throw new Exception($res->getMessage());
390         }
391
392         return true;
393     }
394
395     /**
396      * Drops a column from a table
397      *
398      * The name must match an existing column.
399      *
400      * @param string $table      name of the table
401      * @param string $columnName name of the column to drop
402      *
403      * @return boolean success flag
404      */
405
406     public function dropColumn($table, $columnName)
407     {
408         $sql = "ALTER TABLE $table DROP COLUMN $columnName";
409
410         $res = $this->conn->query($sql);
411
412         if (PEAR::isError($res)) {
413             throw new Exception($res->getMessage());
414         }
415
416         return true;
417     }
418
419     /**
420      * Ensures that a table exists with the given
421      * name and the given column definitions.
422      *
423      * If the table does not yet exist, it will
424      * create the table. If it does exist, it will
425      * alter the table to match the column definitions.
426      *
427      * @param string $tableName name of the table
428      * @param array  $def       Table definition array
429      *
430      * @return boolean success flag
431      */
432
433     public function ensureTable($tableName, $def)
434     {
435         $statements = $this->buildEnsureTable($tableName, $def);
436         return $this->runSqlSet($statements);
437     }
438
439     /**
440      * Run a given set of SQL commands on the connection in sequence.
441      * Empty input is ok.
442      *
443      * @fixme if multiple statements, wrap in a transaction?
444      * @param array $statements
445      * @return boolean success flag
446      */
447     function runSqlSet(array $statements)
448     {
449         $ok = true;
450         foreach ($statements as $sql) {
451             $res = $this->conn->query($sql);
452
453             if (PEAR::isError($res)) {
454                 throw new Exception($res->getMessage());
455             }
456         }
457         return $ok;
458     }
459
460     /**
461      * Check a table's status, and if needed build a set
462      * of SQL statements which change it to be consistent
463      * with the given table definition.
464      *
465      * If the table does not yet exist, statements will
466      * be returned to create the table. If it does exist,
467      * statements will be returned to alter the table to
468      * match the column definitions.
469      *
470      * @param string $tableName name of the table
471      * @param array  $columns   array of ColumnDef
472      *                          objects for the table
473      *
474      * @return array of SQL statements
475      */
476
477     function buildEnsureTable($tableName, $def)
478     {
479         try {
480             $old = $this->getTableDef($tableName);
481         } catch (Exception $e) {
482             // @fixme this is a terrible check :D
483             if (preg_match('/no such table/', $e->getMessage())) {
484                 return $this->buildCreateTable($tableName, $def);
485             } else {
486                 throw $e;
487             }
488         }
489
490         $old = $this->filterDef($old);
491         $def = $this->filterDef($def);
492
493         // @fixme check if not present
494         $fields = $this->diffArrays($old, $def, 'fields', array($this, 'columnsEqual'));
495         $uniques = $this->diffArrays($old, $def, 'unique keys');
496         $indexes = $this->diffArrays($old, $def, 'indexes');
497
498         $total = $fields['count'] + $uniques['count'] + $indexes['count'];
499         if ($total == 0) {
500             // nothing to do
501             return array();
502         }
503
504         // For efficiency, we want this all in one
505         // query, instead of using our methods.
506
507         $phrase = array();
508
509         foreach ($uniques['del'] + $uniques['mod'] as $keyName) {
510             $this->appendAlterDropUnique($phrase, $keyName);
511         }
512
513         foreach ($fields['add'] as $columnName) {
514             $this->appendAlterAddColumn($phrase, $columnName,
515                     $def['fields'][$columnName]);
516         }
517
518         foreach ($fields['mod'] as $columnName) {
519             $this->appendAlterModifyColumn($phrase, $columnName,
520                     $old['fields'][$columnName],
521                     $def['fields'][$columnName]);
522         }
523
524         foreach ($fields['del'] as $columnName) {
525             $this->appendAlterDropColumn($phrase, $columnName);
526         }
527
528         foreach ($uniques['mod'] + $uniques['add'] as $keyName) {
529             $this->appendAlterAddUnique($phrase, $keyName, $def['unique keys'][$keyName]);
530         }
531
532         $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(",\n", $phrase);
533
534         return array($sql);
535     }
536
537     function diffArrays($oldDef, $newDef, $section, $compareCallback=null)
538     {
539         $old = isset($oldDef[$section]) ? $oldDef[$section] : array();
540         $new = isset($newDef[$section]) ? $newDef[$section] : array();
541
542         $oldKeys = array_keys($old);
543         $newKeys = array_keys($new);
544
545         $toadd  = array_diff($newKeys, $oldKeys);
546         $todrop = array_diff($oldKeys, $newKeys);
547         $same   = array_intersect($newKeys, $oldKeys);
548         $tomod  = array();
549         $tokeep = array();
550
551         // Find which fields have actually changed definition
552         // in a way that we need to tweak them for this DB type.
553         foreach ($same as $name) {
554             if ($compareCallback) {
555                 $same = call_user_func($compareCallback, $old[$name], $new[$name]);
556             } else {
557                 $same = ($old[$name] == $new[$name]);
558             }
559             if ($same) {
560                 $tokeep[] = $name;
561                 continue;
562             }
563             $tomod[] = $name;
564         }
565         return array('add' => $toadd,
566                      'del' => $todrop,
567                      'mod' => $tomod,
568                      'keep' => $tokeep,
569                      'count' => count($toadd) + count($todrop) + count($tomod));
570     }
571
572     /**
573      * Append phrase(s) to an array of partial ALTER TABLE chunks in order
574      * to add the given column definition to the table.
575      *
576      * @param array $phrase
577      * @param string $columnName
578      * @param array $cd 
579      */
580     function appendAlterAddColumn(array &$phrase, $columnName, array $cd)
581     {
582         $phrase[] = 'ADD COLUMN ' .
583                     $this->quoteIdentifier($columnName) .
584                     ' ' .
585                     $this->columnSql($cd);
586     }
587
588     /**
589      * Append phrase(s) to an array of partial ALTER TABLE chunks in order
590      * to alter the given column from its old state to a new one.
591      *
592      * @param array $phrase
593      * @param string $columnName
594      * @param array $old previous column definition as found in DB
595      * @param array $cd current column definition
596      */
597     function appendAlterModifyColumn(array &$phrase, $columnName, array $old, array $cd)
598     {
599         $phrase[] = 'MODIFY COLUMN ' .
600                     $this->quoteIdentifier($columnName) .
601                     ' ' .
602                     $this->columnSql($cd);
603     }
604
605     /**
606      * Append phrase(s) to an array of partial ALTER TABLE chunks in order
607      * to drop the given column definition from the table.
608      *
609      * @param array $phrase
610      * @param string $columnName
611      */
612     function appendAlterDropColumn(array &$phrase, $columnName)
613     {
614         $phrase[] = 'DROP COLUMN ' . $this->quoteIdentifier($columnName);
615     }
616
617     function appendAlterAddUnique(array &$phrase, $keyName, array $def)
618     {
619         $sql = array();
620         $sql[] = 'ADD';
621         $this->appendUniqueKeyDef($sql, $keyName, $def);
622         $phrase[] = implode(' ', $sql);'ADD CONSTRAINT ' . $keyName;
623     }
624
625     function appendAlterDropUnique(array &$phrase, $keyName)
626     {
627         $phrase[] = 'DROP CONSTRAINT ' . $keyName;
628     }
629
630     /**
631      * Quote a db/table/column identifier if necessary.
632      *
633      * @param string $name
634      * @return string
635      */
636     function quoteIdentifier($name)
637     {
638         return $name;
639     }
640
641     function quoteDefaultValue($cd)
642     {
643         if ($cd['type'] == 'datetime' && $cd['default'] == 'CURRENT_TIMESTAMP') {
644             return $cd['default'];
645         } else {
646             return $this->quoteValue($cd['default']);
647         }
648     }
649
650     function quoteValue($val)
651     {
652         if (is_int($val) || is_float($val) || is_double($val)) {
653             return strval($val);
654         } else {
655             return '"' . $this->conn->escapeSimple($val) . '"';
656         }
657     }
658
659     /**
660      * Check if two column definitions are equivalent.
661      * The default implementation checks _everything_ but in many cases
662      * you may be able to discard a bunch of equivalencies.
663      *
664      * @param array $a
665      * @param array $b
666      * @return boolean
667      */
668     function columnsEqual(array $a, array $b)
669     {
670         return !array_diff_assoc($a, $b) && !array_diff_assoc($b, $a);
671     }
672
673     /**
674      * Returns the array of names from an array of
675      * ColumnDef objects.
676      *
677      * @param array $cds array of ColumnDef objects
678      *
679      * @return array strings for name values
680      */
681
682     protected function _names($cds)
683     {
684         $names = array();
685
686         foreach ($cds as $cd) {
687             $names[] = $cd->name;
688         }
689
690         return $names;
691     }
692
693     /**
694      * Get a ColumnDef from an array matching
695      * name.
696      *
697      * @param array  $cds  Array of ColumnDef objects
698      * @param string $name Name of the column
699      *
700      * @return ColumnDef matching item or null if no match.
701      */
702
703     protected function _byName($cds, $name)
704     {
705         foreach ($cds as $cd) {
706             if ($cd->name == $name) {
707                 return $cd;
708             }
709         }
710
711         return null;
712     }
713
714     /**
715      * Return the proper SQL for creating or
716      * altering a column.
717      *
718      * Appropriate for use in CREATE TABLE or
719      * ALTER TABLE statements.
720      *
721      * @param ColumnDef $cd column to create
722      *
723      * @return string correct SQL for that column
724      */
725
726     function columnSql(array $cd)
727     {
728         $line = array();
729         $line[] = $this->typeAndSize($cd);
730
731         if (isset($cd['default'])) {
732             $line[] = 'default';
733             $line[] = $this->quoteDefaultValue($cd);
734         } else if (!empty($cd['not null'])) {
735             // Can't have both not null AND default!
736             $line[] = 'not null';
737         }
738
739         return implode(' ', $line);
740     }
741
742     /**
743      *
744      * @param string $column canonical type name in defs
745      * @return string native DB type name
746      */
747     function mapType($column)
748     {
749         return $column;
750     }
751
752     function typeAndSize($column)
753     {
754         $type = $this->mapType($column);
755         $lengths = array();
756
757         if ($column['type'] == 'numeric') {
758             if (isset($column['precision'])) {
759                 $lengths[] = $column['precision'];
760                 if (isset($column['scale'])) {
761                     $lengths[] = $column['scale'];
762                 }
763             }
764         } else if (isset($column['length'])) {
765             $lengths[] = $column['length'];
766         }
767
768         if ($lengths) {
769             return $type . '(' . implode(',', $lengths) . ')';
770         } else {
771             return $type;
772         }
773     }
774
775     /**
776      * Map a native type back to an independent type + size
777      *
778      * @param string $type
779      * @return array ($type, $size) -- $size may be null
780      */
781     protected function reverseMapType($type)
782     {
783         return array($type, null);
784     }
785
786     /**
787      * Convert an old-style set of ColumnDef objects into the current
788      * Drupal-style schema definition array, for backwards compatibility
789      * with plugins written for 0.9.x.
790      *
791      * @param string $tableName
792      * @param array $defs
793      * @return array
794      */
795     function oldToNew($tableName, $defs)
796     {
797         $table = array();
798         $prefixes = array(
799             'tiny',
800             'small',
801             'medium',
802             'big',
803         );
804         foreach ($defs as $cd) {
805             $cd->addToTableDef($table);
806             $column = array();
807             $column['type'] = $cd->type;
808             foreach ($prefixes as $prefix) {
809                 if (substr($cd->type, 0, strlen($prefix)) == $prefix) {
810                     $column['type'] = substr($cd->type, strlen($prefix));
811                     $column['size'] = $prefix;
812                     break;
813                 }
814             }
815
816             if ($cd->size) {
817                 if ($cd->type == 'varchar' || $cd->type == 'char') {
818                     $column['length'] = $cd->size;
819                 }
820             }
821             if (!$cd->nullable) {
822                 $column['not null'] = true;
823             }
824             if ($cd->autoincrement) {
825                 $column['type'] = 'serial';
826             }
827             if ($cd->default) {
828                 $column['default'] = $cd->default;
829             }
830             $table['fields'][$cd->name] = $column;
831
832             if ($cd->key == 'PRI') {
833                 // If multiple columns are defined as primary key,
834                 // we'll pile them on in sequence.
835                 if (!isset($table['primary key'])) {
836                     $table['primary key'] = array();
837                 }
838                 $table['primary key'][] = $cd->name;
839             } else if ($cd->key == 'MUL') {
840                 // Individual multiple-value indexes are only per-column
841                 // using the old ColumnDef syntax.
842                 $idx = "{$tableName}_{$cd->name}_idx";
843                 $table['indexes'][$idx] = array($cd->name);
844             } else if ($cd->key == 'UNI') {
845                 // Individual unique-value indexes are only per-column
846                 // using the old ColumnDef syntax.
847                 $idx = "{$tableName}_{$cd->name}_idx";
848                 $table['unique keys'][$idx] = array($cd->name);
849             }
850         }
851
852         return $table;
853     }
854
855     /**
856      * Filter the given table definition array to match features available
857      * in this database.
858      *
859      * This lets us strip out unsupported things like comments, foreign keys,
860      * or type variants that we wouldn't get back from getTableDef().
861      *
862      * @param array $tableDef
863      */
864     function filterDef(array $tableDef)
865     {
866         return $tableDef;
867     }
868
869     function isNumericType($type)
870     {
871         $type = strtolower($type);
872         $known = array('int', 'serial', 'numeric');
873         return in_array($type, $known);
874     }
875
876     /**
877      * Pull info from the query into a fun-fun array of dooooom
878      *
879      * @param string $sql
880      * @return array of arrays
881      */
882     protected function fetchQueryData($sql)
883     {
884         $res = $this->conn->query($sql);
885         if (PEAR::isError($res)) {
886             throw new Exception($res->getMessage());
887         }
888
889         $out = array();
890         $row = array();
891         while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
892             $out[] = $row;
893         }
894         $res->free();
895
896         return $out;
897     }
898
899 }
900
901 class SchemaTableMissingException extends Exception
902 {
903     // no-op
904 }
905