3 * StatusNet, the distributed open-source microblogging tool
5 * Database schema utilities
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.
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.
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/>.
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/
30 if (!defined('STATUSNET')) {
35 * Class representing the database schema
37 * A class representing the database schema. Can be used to
38 * manipulate the schema -- especially for plugins and upgrade
43 * @author Evan Prodromou <evan@status.net>
44 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
45 * @link http://status.net/
50 static $_single = null;
51 protected $conn = null;
54 * Constructor. Only run once for singleton object.
57 protected function __construct()
59 // XXX: there should be an easier way to do this.
62 $this->conn = $user->getDatabaseConnection();
70 * Main public entry point. Use this to get
71 * the singleton object.
73 * @return Schema the (single) Schema object
78 if (empty(self::$_single)) {
79 self::$_single = new Schema();
81 return self::$_single;
85 * Returns a TableDef object for the table
86 * in the schema with the given name.
88 * Throws an exception if the table is not found.
90 * @param string $name Name of the table to get
92 * @return TableDef tabledef for that table.
95 public function getTableDef($name)
97 $res =& $this->conn->query('DESCRIBE ' . $name);
99 if (PEAR::isError($res)) {
100 throw new Exception($res->getMessage());
103 $td = new TableDef();
106 $td->columns = array();
110 while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
112 $cd = new ColumnDef();
114 $cd->name = $row['Field'];
116 $packed = $row['Type'];
118 if (preg_match('/^(\w+)\((\d+)\)$/', $packed, $match)) {
119 $cd->type = $match[1];
120 $cd->size = $match[2];
125 $cd->nullable = ($row['Null'] == 'YES') ? true : false;
126 $cd->key = $row['Key'];
127 $cd->default = $row['Default'];
128 $cd->extra = $row['Extra'];
130 $td->columns[] = $cd;
137 * Gets a ColumnDef object for a single column.
139 * Throws an exception if the table is not found.
141 * @param string $table name of the table
142 * @param string $column name of the column
144 * @return ColumnDef definition of the column or null
148 public function getColumnDef($table, $column)
150 $td = $this->getTableDef($table);
152 foreach ($td->columns as $cd) {
153 if ($cd->name == $column) {
162 * Creates a table with the given names and columns.
164 * @param string $name Name of the table
165 * @param array $columns Array of ColumnDef objects
168 * @return boolean success flag
171 public function createTable($name, $columns)
177 $sql = "CREATE TABLE $name (\n";
179 for ($i = 0; $i < count($columns); $i++) {
187 $sql .= $this->_columnSql($cd);
191 $uniques[] = $cd->name;
194 $primary[] = $cd->name;
197 $indices[] = $cd->name;
202 if (count($primary) > 0) { // it really should be...
203 $sql .= ",\nconstraint primary key (" . implode(',', $primary) . ")";
206 foreach ($uniques as $u) {
207 $sql .= ",\nunique index {$name}_{$u}_idx ($u)";
210 foreach ($indices as $i) {
211 $sql .= ",\nindex {$name}_{$i}_idx ($i)";
216 $res =& $this->conn->query($sql);
218 if (PEAR::isError($res)) {
219 throw new Exception($res->getMessage());
226 * Drops a table from the schema
228 * Throws an exception if the table is not found.
230 * @param string $name Name of the table to drop
232 * @return boolean success flag
235 public function dropTable($name)
237 $res =& $this->conn->query("DROP TABLE $name");
239 if (PEAR::isError($res)) {
240 throw new Exception($res->getMessage());
247 * Adds an index to a table.
249 * If no name is provided, a name will be made up based
250 * on the table name and column names.
252 * Throws an exception on database error, esp. if the table
255 * @param string $table Name of the table
256 * @param array $columnNames Name of columns to index
257 * @param string $name (Optional) name of the index
259 * @return boolean success flag
262 public function createIndex($table, $columnNames, $name=null)
264 if (!is_array($columnNames)) {
265 $columnNames = array($columnNames);
269 $name = "$table_".implode("_", $columnNames)."_idx";
272 $res =& $this->conn->query("ALTER TABLE $table ".
274 implode(",", $columnNames).")");
276 if (PEAR::isError($res)) {
277 throw new Exception($res->getMessage());
284 * Drops a named index from a table.
286 * @param string $table name of the table the index is on.
287 * @param string $name name of the index
289 * @return boolean success flag
292 public function dropIndex($table, $name)
294 $res =& $this->conn->query("ALTER TABLE $table DROP INDEX $name");
296 if (PEAR::isError($res)) {
297 throw new Exception($res->getMessage());
304 * Adds a column to a table
306 * @param string $table name of the table
307 * @param ColumnDef $columndef Definition of the new
310 * @return boolean success flag
313 public function addColumn($table, $columndef)
315 $sql = "ALTER TABLE $table ADD COLUMN " . $this->_columnSql($columndef);
317 $res =& $this->conn->query($sql);
319 if (PEAR::isError($res)) {
320 throw new Exception($res->getMessage());
327 * Modifies a column in the schema.
329 * The name must match an existing column and table.
331 * @param string $table name of the table
332 * @param ColumnDef $columndef new definition of the column.
334 * @return boolean success flag
337 public function modifyColumn($table, $columndef)
339 $sql = "ALTER TABLE $table MODIFY COLUMN " .
340 $this->_columnSql($columndef);
342 $res =& $this->conn->query($sql);
344 if (PEAR::isError($res)) {
345 throw new Exception($res->getMessage());
352 * Drops a column from a table
354 * The name must match an existing column.
356 * @param string $table name of the table
357 * @param string $columnName name of the column to drop
359 * @return boolean success flag
362 public function dropColumn($table, $columnName)
364 $sql = "ALTER TABLE $table DROP COLUMN $columnName";
366 $res =& $this->conn->query($sql);
368 if (PEAR::isError($res)) {
369 throw new Exception($res->getMessage());
376 * Ensures that the table that backs a given
377 * Plugin_DataObject class exists.
379 * If the table does not yet exist, it will
380 * create the table. If it does exist, it will
381 * alter the table to match the column definitions.
383 * @param Plugin_DataObject $dataObjectClass
385 * @return boolean success flag
388 public function ensureDataObject($dataObjectClass)
390 $obj = new $dataObjectClass();
391 $tableDef = $obj->tableDef();
392 return $this->ensureTable($tableDef->name,$tableDef->columns);
396 * Ensures that a table exists with the given
397 * name and the given column definitions.
399 * If the table does not yet exist, it will
400 * create the table. If it does exist, it will
401 * alter the table to match the column definitions.
403 * @param string $tableName name of the table
404 * @param array $columns array of ColumnDef
405 * objects for the table
407 * @return boolean success flag
410 public function ensureTable($tableName, $columns)
412 // XXX: DB engine portability -> toilet
415 $td = $this->getTableDef($tableName);
416 } catch (Exception $e) {
417 if (preg_match('/no such table/', $e->getMessage())) {
418 return $this->createTable($tableName, $columns);
424 $cur = $this->_names($td->columns);
425 $new = $this->_names($columns);
427 $toadd = array_diff($new, $cur);
428 $todrop = array_diff($cur, $new);
429 $same = array_intersect($new, $cur);
432 foreach ($same as $m) {
433 $curCol = $this->_byName($td->columns, $m);
434 $newCol = $this->_byName($columns, $m);
436 if (!$newCol->equals($curCol)) {
437 $tomod[] = $newCol->name;
441 if (count($toadd) + count($todrop) + count($tomod) == 0) {
446 // For efficiency, we want this all in one
447 // query, instead of using our methods.
451 foreach ($toadd as $columnName) {
452 $cd = $this->_byName($columns, $columnName);
454 $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
457 foreach ($todrop as $columnName) {
458 $phrase[] = 'DROP COLUMN ' . $columnName;
461 foreach ($tomod as $columnName) {
462 $cd = $this->_byName($columns, $columnName);
464 $phrase[] = 'MODIFY COLUMN ' . $this->_columnSql($cd);
467 $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
469 $res =& $this->conn->query($sql);
471 if (PEAR::isError($res)) {
472 throw new Exception($res->getMessage());
479 * Returns the array of names from an array of
482 * @param array $cds array of ColumnDef objects
484 * @return array strings for name values
487 private function _names($cds)
491 foreach ($cds as $cd) {
492 $names[] = $cd->name;
499 * Get a ColumnDef from an array matching
502 * @param array $cds Array of ColumnDef objects
503 * @param string $name Name of the column
505 * @return ColumnDef matching item or null if no match.
508 private function _byName($cds, $name)
510 foreach ($cds as $cd) {
511 if ($cd->name == $name) {
520 * Return the proper SQL for creating or
523 * Appropriate for use in CREATE TABLE or
524 * ALTER TABLE statements.
526 * @param ColumnDef $cd column to create
528 * @return string correct SQL for that column
531 private function _columnSql($cd)
533 $sql = "{$cd->name} ";
535 if (!empty($cd->size)) {
536 $sql .= "{$cd->type}({$cd->size}) ";
538 $sql .= "{$cd->type} ";
541 if (!empty($cd->default)) {
542 $sql .= "default {$cd->default} ";
544 $sql .= ($cd->nullable) ? "null " : "not null ";
552 * A class encapsulating the structure of a table.
556 * @author Evan Prodromou <evan@status.net>
557 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
558 * @link http://status.net/
563 /** name of the table */
565 /** array of ColumnDef objects for the columns. */
571 * @param string $name name of the table
572 * @param array $columns columns in the table
575 function __construct($name=null,$columns=null)
578 $this->columns = $columns;
583 * A class encapsulating the structure of a column in a table.
587 * @author Evan Prodromou <evan@status.net>
588 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
589 * @link http://status.net/
594 /** name of the column. */
596 /** type of column, e.g. 'int', 'varchar' */
598 /** size of the column. */
600 /** boolean flag; can it be null? */
603 * type of key: null = no key; 'PRI' => primary;
604 * 'UNI' => unique key; 'MUL' => multiple values.
607 /** default value if any. */
609 /** 'extra' stuff. Returned by MySQL, largely
612 /** auto increment this field if no value is specific for it during an insert **/
613 public $auto_increment;
618 * @param string $name name of the column
619 * @param string $type type of the column
620 * @param int $size size of the column
621 * @param boolean $nullable can this be null?
622 * @param string $key type of key
623 * @param value $default default value
624 * @param value $extra unused
627 function __construct($name=null, $type=null, $size=null,
628 $nullable=true, $key=null, $default=null,
629 $extra=null, $auto_increment=false)
631 $this->name = strtolower($name);
632 $this->type = strtolower($type);
633 $this->size = $size+0;
634 $this->nullable = $nullable;
636 $this->default = $default;
637 $this->extra = $extra;
638 $this->auto_increment = $auto_increment;
642 * Compares this columndef with another to see
643 * if they're functionally equivalent.
645 * @param ColumnDef $other column to compare
647 * @return boolean true if equivalent, otherwise false.
650 function equals($other)
652 return ($this->name == $other->name &&
653 $this->_typeMatch($other) &&
654 $this->_defaultMatch($other) &&
655 $this->_nullMatch($other) &&
656 $this->key == $other->key &&
657 $this->auto_increment == $other->auto_increment);
661 * Does the type of this column match the
662 * type of the other column?
664 * Checks the type and size of a column. Tries
665 * to ignore differences between synonymous
666 * data types, like 'integer' and 'int'.
668 * @param ColumnDef $other other column to check
670 * @return boolean true if they're about equivalent
673 private function _typeMatch($other)
675 switch ($this->type) {
678 return ($other->type == 'integer' ||
679 $other->type == 'int');
682 return ($this->type == $other->type &&
683 $this->size == $other->size);
688 * Does the default behaviour of this column match
691 * @param ColumnDef $other other column to check
693 * @return boolean true if defaults are effectively the same.
696 private function _defaultMatch($other)
698 return ((is_null($this->default) && is_null($other->default)) ||
699 ($this->default == $other->default));
703 * Does the null behaviour of this column match
706 * @param ColumnDef $other other column to check
708 * @return boolean true if these columns 'null' the same.
711 private function _nullMatch($other)
713 return ((!is_null($this->default) && !is_null($other->default) &&
714 $this->default == $other->default) ||
715 ($this->nullable == $other->nullable));