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/
48 class MysqlSchema extends Schema
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 a table exists with the given
377 * name and the given column definitions.
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 string $tableName name of the table
384 * @param array $columns array of ColumnDef
385 * objects for the table
387 * @return boolean success flag
390 public function ensureTable($tableName, $columns)
392 // XXX: DB engine portability -> toilet
395 $td = $this->getTableDef($tableName);
396 } catch (Exception $e) {
397 if (preg_match('/no such table/', $e->getMessage())) {
398 return $this->createTable($tableName, $columns);
404 $cur = $this->_names($td->columns);
405 $new = $this->_names($columns);
407 $toadd = array_diff($new, $cur);
408 $todrop = array_diff($cur, $new);
409 $same = array_intersect($new, $cur);
412 foreach ($same as $m) {
413 $curCol = $this->_byName($td->columns, $m);
414 $newCol = $this->_byName($columns, $m);
416 if (!$newCol->equals($curCol)) {
417 $tomod[] = $newCol->name;
421 if (count($toadd) + count($todrop) + count($tomod) == 0) {
426 // For efficiency, we want this all in one
427 // query, instead of using our methods.
431 foreach ($toadd as $columnName) {
432 $cd = $this->_byName($columns, $columnName);
434 $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
437 foreach ($todrop as $columnName) {
438 $phrase[] = 'DROP COLUMN ' . $columnName;
441 foreach ($tomod as $columnName) {
442 $cd = $this->_byName($columns, $columnName);
444 $phrase[] = 'MODIFY COLUMN ' . $this->_columnSql($cd);
447 $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
449 $res = $this->conn->query($sql);
451 if (PEAR::isError($res)) {
452 throw new Exception($res->getMessage());
459 * Returns the array of names from an array of
462 * @param array $cds array of ColumnDef objects
464 * @return array strings for name values
467 private function _names($cds)
471 foreach ($cds as $cd) {
472 $names[] = $cd->name;
479 * Get a ColumnDef from an array matching
482 * @param array $cds Array of ColumnDef objects
483 * @param string $name Name of the column
485 * @return ColumnDef matching item or null if no match.
488 private function _byName($cds, $name)
490 foreach ($cds as $cd) {
491 if ($cd->name == $name) {
500 * Return the proper SQL for creating or
503 * Appropriate for use in CREATE TABLE or
504 * ALTER TABLE statements.
506 * @param ColumnDef $cd column to create
508 * @return string correct SQL for that column
511 private function _columnSql($cd)
513 $sql = "{$cd->name} ";
515 if (!empty($cd->size)) {
516 $sql .= "{$cd->type}({$cd->size}) ";
518 $sql .= "{$cd->type} ";
521 if (!empty($cd->default)) {
522 $sql .= "default {$cd->default} ";
524 $sql .= ($cd->nullable) ? "null " : "not null ";
527 if (!empty($cd->auto_increment)) {
528 $sql .= " auto_increment ";
531 if (!empty($cd->extra)) {
532 $sql .= "{$cd->extra} ";