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