]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/schema.php
40a9fb505d60c97bba60ce983d2ac89dfb3df37b
[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         $uniques = array();
132         $primary = array();
133         $indices = array();
134
135         $sql = "CREATE TABLE $name (\n";
136
137         for ($i = 0; $i < count($columns); $i++) {
138
139             $cd =& $columns[$i];
140
141             if ($i > 0) {
142                 $sql .= ",\n";
143             }
144
145             $sql .= $this->_columnSql($cd);
146
147             switch ($cd->key) {
148             case 'UNI':
149                 $uniques[] = $cd->name;
150                 break;
151             case 'PRI':
152                 $primary[] = $cd->name;
153                 break;
154             case 'MUL':
155                 $indices[] = $cd->name;
156                 break;
157             }
158         }
159
160         if (count($primary) > 0) { // it really should be...
161             $sql .= ",\nconstraint primary key (" . implode(',', $primary) . ")";
162         }
163
164         foreach ($uniques as $u) {
165             $sql .= ",\nunique index {$name}_{$u}_idx ($u)";
166         }
167
168         foreach ($indices as $i) {
169             $sql .= ",\nindex {$name}_{$i}_idx ($i)";
170         }
171
172         $sql .= "); ";
173
174         $res = $this->conn->query($sql);
175
176         if (PEAR::isError($res)) {
177             throw new Exception($res->getMessage());
178         }
179
180         return true;
181     }
182
183     /**
184      * Drops a table from the schema
185      *
186      * Throws an exception if the table is not found.
187      *
188      * @param string $name Name of the table to drop
189      *
190      * @return boolean success flag
191      */
192
193     public function dropTable($name)
194     {
195         $res = $this->conn->query("DROP TABLE $name");
196
197         if (PEAR::isError($res)) {
198             throw new Exception($res->getMessage());
199         }
200
201         return true;
202     }
203
204     /**
205      * Adds an index to a table.
206      *
207      * If no name is provided, a name will be made up based
208      * on the table name and column names.
209      *
210      * Throws an exception on database error, esp. if the table
211      * does not exist.
212      *
213      * @param string $table       Name of the table
214      * @param array  $columnNames Name of columns to index
215      * @param string $name        (Optional) name of the index
216      *
217      * @return boolean success flag
218      */
219
220     public function createIndex($table, $columnNames, $name=null)
221     {
222         if (!is_array($columnNames)) {
223             $columnNames = array($columnNames);
224         }
225
226         if (empty($name)) {
227             $name = "{$table}_".implode("_", $columnNames)."_idx";
228         }
229
230         $res = $this->conn->query("ALTER TABLE $table ".
231                                    "ADD INDEX $name (".
232                                    implode(",", $columnNames).")");
233
234         if (PEAR::isError($res)) {
235             throw new Exception($res->getMessage());
236         }
237
238         return true;
239     }
240
241     /**
242      * Drops a named index from a table.
243      *
244      * @param string $table name of the table the index is on.
245      * @param string $name  name of the index
246      *
247      * @return boolean success flag
248      */
249
250     public function dropIndex($table, $name)
251     {
252         $res = $this->conn->query("ALTER TABLE $table DROP INDEX $name");
253
254         if (PEAR::isError($res)) {
255             throw new Exception($res->getMessage());
256         }
257
258         return true;
259     }
260
261     /**
262      * Adds a column to a table
263      *
264      * @param string    $table     name of the table
265      * @param ColumnDef $columndef Definition of the new
266      *                             column.
267      *
268      * @return boolean success flag
269      */
270
271     public function addColumn($table, $columndef)
272     {
273         $sql = "ALTER TABLE $table ADD COLUMN " . $this->_columnSql($columndef);
274
275         $res = $this->conn->query($sql);
276
277         if (PEAR::isError($res)) {
278             throw new Exception($res->getMessage());
279         }
280
281         return true;
282     }
283
284     /**
285      * Modifies a column in the schema.
286      *
287      * The name must match an existing column and table.
288      *
289      * @param string    $table     name of the table
290      * @param ColumnDef $columndef new definition of the column.
291      *
292      * @return boolean success flag
293      */
294
295     public function modifyColumn($table, $columndef)
296     {
297         $sql = "ALTER TABLE $table MODIFY COLUMN " .
298           $this->_columnSql($columndef);
299
300         $res = $this->conn->query($sql);
301
302         if (PEAR::isError($res)) {
303             throw new Exception($res->getMessage());
304         }
305
306         return true;
307     }
308
309     /**
310      * Drops a column from a table
311      *
312      * The name must match an existing column.
313      *
314      * @param string $table      name of the table
315      * @param string $columnName name of the column to drop
316      *
317      * @return boolean success flag
318      */
319
320     public function dropColumn($table, $columnName)
321     {
322         $sql = "ALTER TABLE $table DROP COLUMN $columnName";
323
324         $res = $this->conn->query($sql);
325
326         if (PEAR::isError($res)) {
327             throw new Exception($res->getMessage());
328         }
329
330         return true;
331     }
332
333     /**
334      * Ensures that a table exists with the given
335      * name and the given column definitions.
336      *
337      * If the table does not yet exist, it will
338      * create the table. If it does exist, it will
339      * alter the table to match the column definitions.
340      *
341      * @param string $tableName name of the table
342      * @param array  $columns   array of ColumnDef
343      *                          objects for the table
344      *
345      * @return boolean success flag
346      */
347
348     public function ensureTable($tableName, $def)
349     {
350         // XXX: DB engine portability -> toilet
351
352         try {
353             $old = $this->getTableDef($tableName);
354         } catch (Exception $e) {
355             if (preg_match('/no such table/', $e->getMessage())) {
356                 return $this->createTable($tableName, $columns);
357             } else {
358                 throw $e;
359             }
360         }
361
362         $cur = array_keys($old['fields']);
363         $new = array_keys($def['fields']);
364
365         $toadd  = array_diff($new, $cur);
366         $todrop = array_diff($cur, $new);
367         $same   = array_intersect($new, $cur);
368         $tomod  = array();
369
370         // Find which fields have actually changed definition
371         // in a way that we need to tweak them for this DB type.
372         foreach ($same as $name) {
373             $curCol = $old['fields'][$name];
374             $newCol = $cur['fields'][$name];
375
376             if (!$this->columnsEqual($curCol, $newCol)) {
377                 $tomod[] = $name;
378             }
379         }
380
381         if (count($toadd) + count($todrop) + count($tomod) == 0) {
382             // nothing to do
383             return true;
384         }
385
386         // For efficiency, we want this all in one
387         // query, instead of using our methods.
388
389         $phrase = array();
390
391         foreach ($toadd as $columnName) {
392             $this->appendAlterAddColumn($phrase, $columnName,
393                     $def['fields'][$columnName]);
394         }
395
396         foreach ($todrop as $columnName) {
397             $this->appendAlterModifyColumn($phrase, $columnName,
398                     $old['fields'][$columnName],
399                     $def['fields'][$columnName]);
400         }
401
402         foreach ($tomod as $columnName) {
403             $this->appendAlterDropColumn($phrase, $columnName);
404         }
405
406         $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
407
408         $res = $this->conn->query($sql);
409
410         if (PEAR::isError($res)) {
411             throw new Exception($res->getMessage());
412         }
413
414         return true;
415     }
416
417     /**
418      * Append phrase(s) to an array of partial ALTER TABLE chunks in order
419      * to add the given column definition to the table.
420      *
421      * @param array $phrase
422      * @param string $columnName
423      * @param array $cd 
424      */
425     function appendAlterAddColumn(array &$phrase, $columnName, array $cd)
426     {
427         $phrase[] = 'ADD COLUMN ' .
428                     $this->quoteIdentifier($columnName) .
429                     ' ' .
430                     $this->columnSql($cd);
431     }
432
433     /**
434      * Append phrase(s) to an array of partial ALTER TABLE chunks in order
435      * to alter the given column from its old state to a new one.
436      *
437      * @param array $phrase
438      * @param string $columnName
439      * @param array $old previous column definition as found in DB
440      * @param array $cd current column definition
441      */
442     function appendAlterModifyColumn(array &$phrase, $columnName, array $old, array $cd)
443     {
444         $phrase[] = 'MODIFY COLUMN ' .
445                     $this->quoteIdentifier($columnName) .
446                     ' ' .
447                     $this->columnSql($cd);
448     }
449
450     /**
451      * Append phrase(s) to an array of partial ALTER TABLE chunks in order
452      * to drop the given column definition from the table.
453      *
454      * @param array $phrase
455      * @param string $columnName
456      */
457     function appendAlterDropColumn(array &$phrase, $columnName)
458     {
459         $phrase[] = 'DROP COLUMN ' . $this->quoteIdentifier($columnName);
460     }
461
462     /**
463      * Quote a db/table/column identifier if necessary.
464      *
465      * @param string $name
466      * @return string
467      */
468     function quoteIdentifier($name)
469     {
470         return $name;
471     }
472
473     function quoteDefaultValue($cd)
474     {
475         if ($cd['type'] == 'datetime' && $cd['default'] == 'CURRENT_TIMESTAMP') {
476             return $cd['default'];
477         } else {
478             return $this->quoteValue($cd['default']);
479         }
480     }
481
482     function quoteValue($val)
483     {
484         return $this->conn->escape($val);
485     }
486
487     /**
488      * Check if two column definitions are equivalent.
489      * The default implementation checks _everything_ but in many cases
490      * you may be able to discard a bunch of equivalencies.
491      *
492      * @param array $a
493      * @param array $b
494      * @return boolean
495      */
496     function columnsEqual(array $a, array $b)
497     {
498         return !array_diff_assoc($a, $b) && !array_diff_assoc($b, $a);
499     }
500
501     /**
502      * Returns the array of names from an array of
503      * ColumnDef objects.
504      *
505      * @param array $cds array of ColumnDef objects
506      *
507      * @return array strings for name values
508      */
509
510     protected function _names($cds)
511     {
512         $names = array();
513
514         foreach ($cds as $cd) {
515             $names[] = $cd->name;
516         }
517
518         return $names;
519     }
520
521     /**
522      * Get a ColumnDef from an array matching
523      * name.
524      *
525      * @param array  $cds  Array of ColumnDef objects
526      * @param string $name Name of the column
527      *
528      * @return ColumnDef matching item or null if no match.
529      */
530
531     protected function _byName($cds, $name)
532     {
533         foreach ($cds as $cd) {
534             if ($cd->name == $name) {
535                 return $cd;
536             }
537         }
538
539         return null;
540     }
541
542     /**
543      * Return the proper SQL for creating or
544      * altering a column.
545      *
546      * Appropriate for use in CREATE TABLE or
547      * ALTER TABLE statements.
548      *
549      * @param ColumnDef $cd column to create
550      *
551      * @return string correct SQL for that column
552      */
553
554     function columnSql(array $cd)
555     {
556         $line = array();
557         $line[] = $this->typeAndSize();
558
559         if (isset($cd['default'])) {
560             $line[] = 'default';
561             $line[] = $this->quoted($cd['default']);
562         } else if (!empty($cd['not null'])) {
563             // Can't have both not null AND default!
564             $line[] = 'not null';
565         }
566
567         return implode(' ', $line);
568     }
569
570     /**
571      *
572      * @param string $column canonical type name in defs
573      * @return string native DB type name
574      */
575     function mapType($column)
576     {
577         return $column;
578     }
579
580     function typeAndSize($column)
581     {
582         $type = $this->mapType($column);
583         $lengths = array();
584
585         if ($column['type'] == 'numeric') {
586             if (isset($column['precision'])) {
587                 $lengths[] = $column['precision'];
588                 if (isset($column['scale'])) {
589                     $lengths[] = $column['scale'];
590                 }
591             }
592         } else if (isset($column['length'])) {
593             $lengths[] = $column['length'];
594         }
595
596         if ($lengths) {
597             return $type . '(' . implode(',', $lengths) . ')';
598         } else {
599             return $type;
600         }
601     }
602
603     /**
604      * Map a native type back to an independent type + size
605      *
606      * @param string $type
607      * @return array ($type, $size) -- $size may be null
608      */
609     protected function reverseMapType($type)
610     {
611         return array($type, null);
612     }
613
614     /**
615      * Convert an old-style set of ColumnDef objects into the current
616      * Drupal-style schema definition array, for backwards compatibility
617      * with plugins written for 0.9.x.
618      *
619      * @param string $tableName
620      * @param array $defs
621      * @return array
622      */
623     function oldToNew($tableName, $defs)
624     {
625         $table = array();
626         $prefixes = array(
627             'tiny',
628             'small',
629             'medium',
630             'big',
631         );
632         foreach ($defs as $cd) {
633             $cd->addToTableDef($table);
634             $column = array();
635             $column['type'] = $cd->type;
636             foreach ($prefixes as $prefix) {
637                 if (substr($cd->type, 0, strlen($prefix)) == $prefix) {
638                     $column['type'] = substr($cd->type, strlen($prefix));
639                     $column['size'] = $prefix;
640                     break;
641                 }
642             }
643
644             if ($cd->size) {
645                 if ($cd->type == 'varchar' || $cd->type == 'char') {
646                     $column['length'] = $cd->size;
647                 }
648             }
649             if (!$cd->nullable) {
650                 $column['not null'] = true;
651             }
652             if ($cd->autoincrement) {
653                 $column['type'] = 'serial';
654             }
655             if ($cd->default) {
656                 $column['default'] = $cd->default;
657             }
658             $table['fields'][$cd->name] = $column;
659
660             if ($cd->key == 'PRI') {
661                 // If multiple columns are defined as primary key,
662                 // we'll pile them on in sequence.
663                 if (!isset($table['primary key'])) {
664                     $table['primary key'] = array();
665                 }
666                 $table['primary key'][] = $cd->name;
667             } else if ($cd->key == 'MUL') {
668                 // Individual multiple-value indexes are only per-column
669                 // using the old ColumnDef syntax.
670                 $idx = "{$tableName}_{$cd->name}_idx";
671                 $table['indexes'][$idx] = array($cd->name);
672             } else if ($cd->key == 'UNI') {
673                 // Individual unique-value indexes are only per-column
674                 // using the old ColumnDef syntax.
675                 $idx = "{$tableName}_{$cd->name}_idx";
676                 $table['unique keys'][$idx] = array($cd->name);
677             }
678         }
679
680         return $table;
681     }
682
683     function isNumericType($type)
684     {
685         $type = strtolower($type);
686         $known = array('int', 'serial', 'numeric');
687         return in_array($type, $known);
688     }
689
690     /**
691      * Pull info from the query into a fun-fun array of dooooom
692      *
693      * @param string $sql
694      * @return array of arrays
695      */
696     protected function fetchQueryData($sql)
697     {
698         $res = $this->conn->query($sql);
699         if (PEAR::isError($res)) {
700             throw new Exception($res->getMessage());
701         }
702
703         $out = array();
704         $row = array();
705         while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
706             $out[] = $row;
707         }
708         $res->free();
709
710         return $out;
711     }
712
713 }
714
715 class SchemaTableMissingException extends Exception
716 {
717     // no-op
718 }
719