]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/schema.php
acc9412841935aa8d4cb5ffc7c37de705ff68dc8
[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         $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 $key " . $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, 'quoteIdentifier'), $def)) . ')';
258     }
259
260     /**
261      * Drops a table from the schema
262      *
263      * Throws an exception if the table is not found.
264      *
265      * @param string $name Name of the table to drop
266      *
267      * @return boolean success flag
268      */
269
270     public function dropTable($name)
271     {
272         $res = $this->conn->query("DROP TABLE $name");
273
274         if (PEAR::isError($res)) {
275             throw new Exception($res->getMessage());
276         }
277
278         return true;
279     }
280
281     /**
282      * Adds an index to a table.
283      *
284      * If no name is provided, a name will be made up based
285      * on the table name and column names.
286      *
287      * Throws an exception on database error, esp. if the table
288      * does not exist.
289      *
290      * @param string $table       Name of the table
291      * @param array  $columnNames Name of columns to index
292      * @param string $name        (Optional) name of the index
293      *
294      * @return boolean success flag
295      */
296
297     public function createIndex($table, $columnNames, $name=null)
298     {
299         if (!is_array($columnNames)) {
300             $columnNames = array($columnNames);
301         }
302
303         if (empty($name)) {
304             $name = "{$table}_".implode("_", $columnNames)."_idx";
305         }
306
307         $res = $this->conn->query("ALTER TABLE $table ".
308                                    "ADD INDEX $name (".
309                                    implode(",", $columnNames).")");
310
311         if (PEAR::isError($res)) {
312             throw new Exception($res->getMessage());
313         }
314
315         return true;
316     }
317
318     /**
319      * Drops a named index from a table.
320      *
321      * @param string $table name of the table the index is on.
322      * @param string $name  name of the index
323      *
324      * @return boolean success flag
325      */
326
327     public function dropIndex($table, $name)
328     {
329         $res = $this->conn->query("ALTER TABLE $table DROP INDEX $name");
330
331         if (PEAR::isError($res)) {
332             throw new Exception($res->getMessage());
333         }
334
335         return true;
336     }
337
338     /**
339      * Adds a column to a table
340      *
341      * @param string    $table     name of the table
342      * @param ColumnDef $columndef Definition of the new
343      *                             column.
344      *
345      * @return boolean success flag
346      */
347
348     public function addColumn($table, $columndef)
349     {
350         $sql = "ALTER TABLE $table ADD COLUMN " . $this->_columnSql($columndef);
351
352         $res = $this->conn->query($sql);
353
354         if (PEAR::isError($res)) {
355             throw new Exception($res->getMessage());
356         }
357
358         return true;
359     }
360
361     /**
362      * Modifies a column in the schema.
363      *
364      * The name must match an existing column and table.
365      *
366      * @param string    $table     name of the table
367      * @param ColumnDef $columndef new definition of the column.
368      *
369      * @return boolean success flag
370      */
371
372     public function modifyColumn($table, $columndef)
373     {
374         $sql = "ALTER TABLE $table MODIFY COLUMN " .
375           $this->_columnSql($columndef);
376
377         $res = $this->conn->query($sql);
378
379         if (PEAR::isError($res)) {
380             throw new Exception($res->getMessage());
381         }
382
383         return true;
384     }
385
386     /**
387      * Drops a column from a table
388      *
389      * The name must match an existing column.
390      *
391      * @param string $table      name of the table
392      * @param string $columnName name of the column to drop
393      *
394      * @return boolean success flag
395      */
396
397     public function dropColumn($table, $columnName)
398     {
399         $sql = "ALTER TABLE $table DROP COLUMN $columnName";
400
401         $res = $this->conn->query($sql);
402
403         if (PEAR::isError($res)) {
404             throw new Exception($res->getMessage());
405         }
406
407         return true;
408     }
409
410     /**
411      * Ensures that a table exists with the given
412      * name and the given column definitions.
413      *
414      * If the table does not yet exist, it will
415      * create the table. If it does exist, it will
416      * alter the table to match the column definitions.
417      *
418      * @param string $tableName name of the table
419      * @param array  $def       Table definition array
420      *
421      * @return boolean success flag
422      */
423
424     public function ensureTable($tableName, $def)
425     {
426         $statements = $this->buildEnsureTable($tableName, $def);
427         return $this->runSqlSet($statements);
428     }
429
430     /**
431      * Run a given set of SQL commands on the connection in sequence.
432      * Empty input is ok.
433      *
434      * @fixme if multiple statements, wrap in a transaction?
435      * @param array $statements
436      * @return boolean success flag
437      */
438     function runSqlSet(array $statements)
439     {
440         $ok = true;
441         foreach ($statements as $sql) {
442             $res = $this->conn->query($sql);
443
444             if (PEAR::isError($res)) {
445                 throw new Exception($res->getMessage());
446             }
447         }
448         return $ok;
449     }
450
451     /**
452      * Check a table's status, and if needed build a set
453      * of SQL statements which change it to be consistent
454      * with the given table definition.
455      *
456      * If the table does not yet exist, statements will
457      * be returned to create the table. If it does exist,
458      * statements will be returned to alter the table to
459      * match the column definitions.
460      *
461      * @param string $tableName name of the table
462      * @param array  $columns   array of ColumnDef
463      *                          objects for the table
464      *
465      * @return array of SQL statements
466      */
467
468     function buildEnsureTable($tableName, $def)
469     {
470         try {
471             $old = $this->getTableDef($tableName);
472         } catch (Exception $e) {
473             // @fixme this is a terrible check :D
474             if (preg_match('/no such table/', $e->getMessage())) {
475                 return $this->buildCreateTable($tableName, $def);
476             } else {
477                 throw $e;
478             }
479         }
480
481         $cur = array_keys($old['fields']);
482         $new = array_keys($def['fields']);
483
484         $toadd  = array_diff($new, $cur);
485         $todrop = array_diff($cur, $new);
486         $same   = array_intersect($new, $cur);
487         $tomod  = array();
488
489         // Find which fields have actually changed definition
490         // in a way that we need to tweak them for this DB type.
491         foreach ($same as $name) {
492             $curCol = $old['fields'][$name];
493             $newCol = $cur['fields'][$name];
494
495             if (!$this->columnsEqual($curCol, $newCol)) {
496                 $tomod[] = $name;
497             }
498         }
499
500         if (count($toadd) + count($todrop) + count($tomod) == 0) {
501             // nothing to do
502             return true;
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 ($toadd as $columnName) {
511             $this->appendAlterAddColumn($phrase, $columnName,
512                     $def['fields'][$columnName]);
513         }
514
515         foreach ($todrop as $columnName) {
516             $this->appendAlterModifyColumn($phrase, $columnName,
517                     $old['fields'][$columnName],
518                     $def['fields'][$columnName]);
519         }
520
521         foreach ($tomod as $columnName) {
522             $this->appendAlterDropColumn($phrase, $columnName);
523         }
524
525         $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
526
527         $res = $this->conn->query($sql);
528
529         if (PEAR::isError($res)) {
530             throw new Exception($res->getMessage());
531         }
532
533         return true;
534     }
535
536     /**
537      * Append phrase(s) to an array of partial ALTER TABLE chunks in order
538      * to add the given column definition to the table.
539      *
540      * @param array $phrase
541      * @param string $columnName
542      * @param array $cd 
543      */
544     function appendAlterAddColumn(array &$phrase, $columnName, array $cd)
545     {
546         $phrase[] = 'ADD COLUMN ' .
547                     $this->quoteIdentifier($columnName) .
548                     ' ' .
549                     $this->columnSql($cd);
550     }
551
552     /**
553      * Append phrase(s) to an array of partial ALTER TABLE chunks in order
554      * to alter the given column from its old state to a new one.
555      *
556      * @param array $phrase
557      * @param string $columnName
558      * @param array $old previous column definition as found in DB
559      * @param array $cd current column definition
560      */
561     function appendAlterModifyColumn(array &$phrase, $columnName, array $old, array $cd)
562     {
563         $phrase[] = 'MODIFY COLUMN ' .
564                     $this->quoteIdentifier($columnName) .
565                     ' ' .
566                     $this->columnSql($cd);
567     }
568
569     /**
570      * Append phrase(s) to an array of partial ALTER TABLE chunks in order
571      * to drop the given column definition from the table.
572      *
573      * @param array $phrase
574      * @param string $columnName
575      */
576     function appendAlterDropColumn(array &$phrase, $columnName)
577     {
578         $phrase[] = 'DROP COLUMN ' . $this->quoteIdentifier($columnName);
579     }
580
581     /**
582      * Quote a db/table/column identifier if necessary.
583      *
584      * @param string $name
585      * @return string
586      */
587     function quoteIdentifier($name)
588     {
589         return $name;
590     }
591
592     function quoteDefaultValue($cd)
593     {
594         if ($cd['type'] == 'datetime' && $cd['default'] == 'CURRENT_TIMESTAMP') {
595             return $cd['default'];
596         } else {
597             return $this->quoteValue($cd['default']);
598         }
599     }
600
601     function quoteValue($val)
602     {
603         if (is_int($val) || is_float($val) || is_double($val)) {
604             return strval($val);
605         } else {
606             return '"' . $this->conn->escapeSimple($val) . '"';
607         }
608     }
609
610     /**
611      * Check if two column definitions are equivalent.
612      * The default implementation checks _everything_ but in many cases
613      * you may be able to discard a bunch of equivalencies.
614      *
615      * @param array $a
616      * @param array $b
617      * @return boolean
618      */
619     function columnsEqual(array $a, array $b)
620     {
621         return !array_diff_assoc($a, $b) && !array_diff_assoc($b, $a);
622     }
623
624     /**
625      * Returns the array of names from an array of
626      * ColumnDef objects.
627      *
628      * @param array $cds array of ColumnDef objects
629      *
630      * @return array strings for name values
631      */
632
633     protected function _names($cds)
634     {
635         $names = array();
636
637         foreach ($cds as $cd) {
638             $names[] = $cd->name;
639         }
640
641         return $names;
642     }
643
644     /**
645      * Get a ColumnDef from an array matching
646      * name.
647      *
648      * @param array  $cds  Array of ColumnDef objects
649      * @param string $name Name of the column
650      *
651      * @return ColumnDef matching item or null if no match.
652      */
653
654     protected function _byName($cds, $name)
655     {
656         foreach ($cds as $cd) {
657             if ($cd->name == $name) {
658                 return $cd;
659             }
660         }
661
662         return null;
663     }
664
665     /**
666      * Return the proper SQL for creating or
667      * altering a column.
668      *
669      * Appropriate for use in CREATE TABLE or
670      * ALTER TABLE statements.
671      *
672      * @param ColumnDef $cd column to create
673      *
674      * @return string correct SQL for that column
675      */
676
677     function columnSql(array $cd)
678     {
679         $line = array();
680         $line[] = $this->typeAndSize($cd);
681
682         if (isset($cd['default'])) {
683             $line[] = 'default';
684             $line[] = $this->quoteDefaultValue($cd);
685         } else if (!empty($cd['not null'])) {
686             // Can't have both not null AND default!
687             $line[] = 'not null';
688         }
689
690         return implode(' ', $line);
691     }
692
693     /**
694      *
695      * @param string $column canonical type name in defs
696      * @return string native DB type name
697      */
698     function mapType($column)
699     {
700         return $column;
701     }
702
703     function typeAndSize($column)
704     {
705         $type = $this->mapType($column);
706         $lengths = array();
707
708         if ($column['type'] == 'numeric') {
709             if (isset($column['precision'])) {
710                 $lengths[] = $column['precision'];
711                 if (isset($column['scale'])) {
712                     $lengths[] = $column['scale'];
713                 }
714             }
715         } else if (isset($column['length'])) {
716             $lengths[] = $column['length'];
717         }
718
719         if ($lengths) {
720             return $type . '(' . implode(',', $lengths) . ')';
721         } else {
722             return $type;
723         }
724     }
725
726     /**
727      * Map a native type back to an independent type + size
728      *
729      * @param string $type
730      * @return array ($type, $size) -- $size may be null
731      */
732     protected function reverseMapType($type)
733     {
734         return array($type, null);
735     }
736
737     /**
738      * Convert an old-style set of ColumnDef objects into the current
739      * Drupal-style schema definition array, for backwards compatibility
740      * with plugins written for 0.9.x.
741      *
742      * @param string $tableName
743      * @param array $defs
744      * @return array
745      */
746     function oldToNew($tableName, $defs)
747     {
748         $table = array();
749         $prefixes = array(
750             'tiny',
751             'small',
752             'medium',
753             'big',
754         );
755         foreach ($defs as $cd) {
756             $cd->addToTableDef($table);
757             $column = array();
758             $column['type'] = $cd->type;
759             foreach ($prefixes as $prefix) {
760                 if (substr($cd->type, 0, strlen($prefix)) == $prefix) {
761                     $column['type'] = substr($cd->type, strlen($prefix));
762                     $column['size'] = $prefix;
763                     break;
764                 }
765             }
766
767             if ($cd->size) {
768                 if ($cd->type == 'varchar' || $cd->type == 'char') {
769                     $column['length'] = $cd->size;
770                 }
771             }
772             if (!$cd->nullable) {
773                 $column['not null'] = true;
774             }
775             if ($cd->autoincrement) {
776                 $column['type'] = 'serial';
777             }
778             if ($cd->default) {
779                 $column['default'] = $cd->default;
780             }
781             $table['fields'][$cd->name] = $column;
782
783             if ($cd->key == 'PRI') {
784                 // If multiple columns are defined as primary key,
785                 // we'll pile them on in sequence.
786                 if (!isset($table['primary key'])) {
787                     $table['primary key'] = array();
788                 }
789                 $table['primary key'][] = $cd->name;
790             } else if ($cd->key == 'MUL') {
791                 // Individual multiple-value indexes are only per-column
792                 // using the old ColumnDef syntax.
793                 $idx = "{$tableName}_{$cd->name}_idx";
794                 $table['indexes'][$idx] = array($cd->name);
795             } else if ($cd->key == 'UNI') {
796                 // Individual unique-value indexes are only per-column
797                 // using the old ColumnDef syntax.
798                 $idx = "{$tableName}_{$cd->name}_idx";
799                 $table['unique keys'][$idx] = array($cd->name);
800             }
801         }
802
803         return $table;
804     }
805
806     function isNumericType($type)
807     {
808         $type = strtolower($type);
809         $known = array('int', 'serial', 'numeric');
810         return in_array($type, $known);
811     }
812
813     /**
814      * Pull info from the query into a fun-fun array of dooooom
815      *
816      * @param string $sql
817      * @return array of arrays
818      */
819     protected function fetchQueryData($sql)
820     {
821         $res = $this->conn->query($sql);
822         if (PEAR::isError($res)) {
823             throw new Exception($res->getMessage());
824         }
825
826         $out = array();
827         $row = array();
828         while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
829             $out[] = $row;
830         }
831         $res->free();
832
833         return $out;
834     }
835
836 }
837
838 class SchemaTableMissingException extends Exception
839 {
840     // no-op
841 }
842