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 common_log(LOG_INFO, $sql);
217 $res = $this->conn->query($sql);
219 if (PEAR::isError($res)) {
220 throw new Exception($res->getMessage());
227 * Drops a table from the schema
229 * Throws an exception if the table is not found.
231 * @param string $name Name of the table to drop
233 * @return boolean success flag
236 public function dropTable($name)
238 $res = $this->conn->query("DROP TABLE $name");
240 if (PEAR::isError($res)) {
241 throw new Exception($res->getMessage());
248 * Adds an index to a table.
250 * If no name is provided, a name will be made up based
251 * on the table name and column names.
253 * Throws an exception on database error, esp. if the table
256 * @param string $table Name of the table
257 * @param array $columnNames Name of columns to index
258 * @param string $name (Optional) name of the index
260 * @return boolean success flag
263 public function createIndex($table, $columnNames, $name=null)
265 if (!is_array($columnNames)) {
266 $columnNames = array($columnNames);
270 $name = "$table_".implode("_", $columnNames)."_idx";
273 $res = $this->conn->query("ALTER TABLE $table ".
275 implode(",", $columnNames).")");
277 if (PEAR::isError($res)) {
278 throw new Exception($res->getMessage());
285 * Drops a named index from a table.
287 * @param string $table name of the table the index is on.
288 * @param string $name name of the index
290 * @return boolean success flag
293 public function dropIndex($table, $name)
295 $res = $this->conn->query("ALTER TABLE $table DROP INDEX $name");
297 if (PEAR::isError($res)) {
298 throw new Exception($res->getMessage());
305 * Adds a column to a table
307 * @param string $table name of the table
308 * @param ColumnDef $columndef Definition of the new
311 * @return boolean success flag
314 public function addColumn($table, $columndef)
316 $sql = "ALTER TABLE $table ADD COLUMN " . $this->_columnSql($columndef);
318 $res = $this->conn->query($sql);
320 if (PEAR::isError($res)) {
321 throw new Exception($res->getMessage());
328 * Modifies a column in the schema.
330 * The name must match an existing column and table.
332 * @param string $table name of the table
333 * @param ColumnDef $columndef new definition of the column.
335 * @return boolean success flag
338 public function modifyColumn($table, $columndef)
340 $sql = "ALTER TABLE $table MODIFY COLUMN " .
341 $this->_columnSql($columndef);
343 $res = $this->conn->query($sql);
345 if (PEAR::isError($res)) {
346 throw new Exception($res->getMessage());
353 * Drops a column from a table
355 * The name must match an existing column.
357 * @param string $table name of the table
358 * @param string $columnName name of the column to drop
360 * @return boolean success flag
363 public function dropColumn($table, $columnName)
365 $sql = "ALTER TABLE $table DROP COLUMN $columnName";
367 $res = $this->conn->query($sql);
369 if (PEAR::isError($res)) {
370 throw new Exception($res->getMessage());
377 * Ensures that a table exists with the given
378 * name and the given column definitions.
380 * If the table does not yet exist, it will
381 * create the table. If it does exist, it will
382 * alter the table to match the column definitions.
384 * @param string $tableName name of the table
385 * @param array $columns array of ColumnDef
386 * objects for the table
388 * @return boolean success flag
391 public function ensureTable($tableName, $columns)
393 // XXX: DB engine portability -> toilet
396 $td = $this->getTableDef($tableName);
397 } catch (Exception $e) {
398 if (preg_match('/no such table/', $e->getMessage())) {
399 return $this->createTable($tableName, $columns);
405 $cur = $this->_names($td->columns);
406 $new = $this->_names($columns);
408 $toadd = array_diff($new, $cur);
409 $todrop = array_diff($cur, $new);
410 $same = array_intersect($new, $cur);
413 foreach ($same as $m) {
414 $curCol = $this->_byName($td->columns, $m);
415 $newCol = $this->_byName($columns, $m);
417 if (!$newCol->equals($curCol)) {
418 $tomod[] = $newCol->name;
422 if (count($toadd) + count($todrop) + count($tomod) == 0) {
427 // For efficiency, we want this all in one
428 // query, instead of using our methods.
432 foreach ($toadd as $columnName) {
433 $cd = $this->_byName($columns, $columnName);
435 $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
438 foreach ($todrop as $columnName) {
439 $phrase[] = 'DROP COLUMN ' . $columnName;
442 foreach ($tomod as $columnName) {
443 $cd = $this->_byName($columns, $columnName);
445 $phrase[] = 'MODIFY COLUMN ' . $this->_columnSql($cd);
448 $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
450 $res = $this->conn->query($sql);
452 if (PEAR::isError($res)) {
453 throw new Exception($res->getMessage());
460 * Returns the array of names from an array of
463 * @param array $cds array of ColumnDef objects
465 * @return array strings for name values
468 private function _names($cds)
472 foreach ($cds as $cd) {
473 $names[] = $cd->name;
480 * Get a ColumnDef from an array matching
483 * @param array $cds Array of ColumnDef objects
484 * @param string $name Name of the column
486 * @return ColumnDef matching item or null if no match.
489 private function _byName($cds, $name)
491 foreach ($cds as $cd) {
492 if ($cd->name == $name) {
501 * Return the proper SQL for creating or
504 * Appropriate for use in CREATE TABLE or
505 * ALTER TABLE statements.
507 * @param ColumnDef $cd column to create
509 * @return string correct SQL for that column
512 private function _columnSql($cd)
514 $sql = "{$cd->name} ";
516 if (!empty($cd->size)) {
517 $sql .= "{$cd->type}({$cd->size}) ";
519 $sql .= "{$cd->type} ";
522 if (!empty($cd->default)) {
523 $sql .= "default {$cd->default} ";
525 $sql .= ($cd->nullable) ? "null " : "not null ";
528 if (!empty($cd->auto_increment)) {
529 $sql .= " auto_increment ";
532 if (!empty($cd->extra)) {
533 $sql .= "{$cd->extra} ";