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;
55 * Main public entry point. Use this to get
56 * the singleton object.
58 * @return Schema the (single) Schema object
63 if (empty(self::$_single)) {
64 self::$_single = new Schema();
66 return self::$_single;
70 * Returns a TableDef object for the table
71 * in the schema with the given name.
73 * Throws an exception if the table is not found.
75 * @param string $name Name of the table to get
77 * @return TableDef tabledef for that table.
78 * @throws SchemaTableMissingException
81 public function getTableDef($name)
83 $query = "SELECT * FROM INFORMATION_SCHEMA.COLUMNS " .
84 "WHERE TABLE_SCHEMA='%s' AND TABLE_NAME='%s'";
85 $schema = $this->conn->dsn['database'];
86 $sql = sprintf($query, $schema, $name);
87 $res = $this->conn->query($sql);
89 if (PEAR::isError($res)) {
90 throw new Exception($res->getMessage());
92 if ($res->numRows() == 0) {
94 throw new SchemaTableMissingException("No such table: $name");
100 $td->columns = array();
104 while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
106 $cd = new ColumnDef();
108 $cd->name = $row['COLUMN_NAME'];
110 $packed = $row['COLUMN_TYPE'];
112 if (preg_match('/^(\w+)\((\d+)\)$/', $packed, $match)) {
113 $cd->type = $match[1];
114 $cd->size = $match[2];
119 $cd->nullable = ($row['IS_NULLABLE'] == 'YES') ? true : false;
120 $cd->key = $row['COLUMN_KEY'];
121 $cd->default = $row['COLUMN_DEFAULT'];
122 $cd->extra = $row['EXTRA'];
124 // Autoincrement is stuck into the extra column.
125 // Pull it out so we don't accidentally mod it every time...
126 $extra = preg_replace('/(^|\s)auto_increment(\s|$)/i', '$1$2', $cd->extra);
127 if ($extra != $cd->extra) {
128 $cd->extra = trim($extra);
129 $cd->auto_increment = true;
132 // mysql extensions -- not (yet) used by base class
133 $cd->charset = $row['CHARACTER_SET_NAME'];
134 $cd->collate = $row['COLLATION_NAME'];
136 $td->columns[] = $cd;
144 * Pull the given table properties from INFORMATION_SCHEMA.
145 * Most of the good stuff is MySQL extensions.
148 * @throws Exception if table info can't be looked up
151 function getTableProperties($table, $props)
153 $query = "SELECT %s FROM INFORMATION_SCHEMA.TABLES " .
154 "WHERE TABLE_SCHEMA='%s' AND TABLE_NAME='%s'";
155 $schema = $this->conn->dsn['database'];
156 $sql = sprintf($query, implode(',', $props), $schema, $table);
157 $res = $this->conn->query($sql);
160 $ok = $res->fetchInto($row, DB_FETCHMODE_ASSOC);
166 throw new SchemaTableMissingException("No such table: $table");
171 * Creates a table with the given names and columns.
173 * @param string $name Name of the table
174 * @param array $columns Array of ColumnDef objects
177 * @return boolean success flag
180 public function createTable($name, $columns)
186 $sql = "CREATE TABLE $name (\n";
188 for ($i = 0; $i < count($columns); $i++) {
196 $sql .= $this->_columnSql($cd);
199 $idx = $this->_indexList($columns);
201 if ($idx['primary']) {
202 $sql .= ",\nconstraint primary key (" . implode(',', $idx['primary']) . ")";
205 foreach ($idx['uniques'] as $u) {
206 $key = $this->_uniqueKey($name, $u);
207 $sql .= ",\nunique index $key ($u)";
210 foreach ($idx['indices'] as $i) {
211 $key = $this->_key($name, $i);
212 $sql .= ",\nindex $key ($i)";
215 $sql .= ") ENGINE=InnoDB CHARACTER SET utf8 COLLATE utf8_bin; ";
217 $res = $this->conn->query($sql);
219 if (PEAR::isError($res)) {
220 throw new Exception($res->getMessage());
227 * Look over a list of column definitions and list up which
228 * indices will be present
230 private function _indexList(array $columns)
232 $list = array('uniques' => array(),
233 'primary' => array(),
234 'indices' => array());
235 foreach ($columns as $cd) {
238 $list['uniques'][] = $cd->name;
241 $list['primary'][] = $cd->name;
244 $list['indices'][] = $cd->name;
252 * Get the unique index key name for a given column on this table
254 function _uniqueKey($tableName, $columnName)
256 return $this->_key($tableName, $columnName);
260 * Get the index key name for a given column on this table
262 function _key($tableName, $columnName)
264 return "{$tableName}_{$columnName}_idx";
268 * Ensures that a table exists with the given
269 * name and the given column definitions.
271 * If the table does not yet exist, it will
272 * create the table. If it does exist, it will
273 * alter the table to match the column definitions.
275 * @param string $tableName name of the table
276 * @param array $columns array of ColumnDef
277 * objects for the table
279 * @return boolean success flag
282 public function ensureTable($tableName, $columns)
284 // XXX: DB engine portability -> toilet
287 $td = $this->getTableDef($tableName);
288 } catch (SchemaTableMissingException $e) {
289 return $this->createTable($tableName, $columns);
292 $cur = $this->_names($td->columns);
293 $new = $this->_names($columns);
295 $dropIndex = array();
296 $toadd = array_diff($new, $cur);
297 $todrop = array_diff($cur, $new);
298 $same = array_intersect($new, $cur);
301 $tableProps = array();
303 foreach ($same as $m) {
304 $curCol = $this->_byName($td->columns, $m);
305 $newCol = $this->_byName($columns, $m);
307 if (!$newCol->equals($curCol)) {
308 $tomod[] = $newCol->name;
312 // Earlier versions may have accidentally left tables at default
313 // charsets which might be latin1 or other freakish things.
314 if ($this->_isString($curCol)) {
315 if ($curCol->charset != 'utf8') {
316 $tomod[] = $newCol->name;
322 // Find any indices we have to change...
323 $curIdx = $this->_indexList($td->columns);
324 $newIdx = $this->_indexList($columns);
326 if ($curIdx['primary'] != $newIdx['primary']) {
327 if ($curIdx['primary']) {
328 $dropIndex[] = 'drop primary key';
330 if ($newIdx['primary']) {
331 $keys = implode(',', $newIdx['primary']);
332 $addIndex[] = "add constraint primary key ($keys)";
336 $dropUnique = array_diff($curIdx['uniques'], $newIdx['uniques']);
337 $addUnique = array_diff($newIdx['uniques'], $curIdx['uniques']);
338 foreach ($dropUnique as $columnName) {
339 $dropIndex[] = 'drop key ' . $this->_uniqueKey($tableName, $columnName);
341 foreach ($addUnique as $columnName) {
342 $addIndex[] = 'add constraint unique key ' . $this->_uniqueKey($tableName, $columnName) . " ($columnName)";;
345 $dropMultiple = array_diff($curIdx['indices'], $newIdx['indices']);
346 $addMultiple = array_diff($newIdx['indices'], $curIdx['indices']);
347 foreach ($dropMultiple as $columnName) {
348 $dropIndex[] = 'drop key ' . $this->_key($tableName, $columnName);
350 foreach ($addMultiple as $columnName) {
351 $addIndex[] = 'add key ' . $this->_key($tableName, $columnName) . " ($columnName)";
354 // Check for table properties: make sure we're using a sane
355 // engine type and charset/collation.
356 // @fixme make the default engine configurable?
357 $oldProps = $this->getTableProperties($tableName, array('ENGINE', 'TABLE_COLLATION'));
358 if (strtolower($oldProps['ENGINE']) != 'innodb') {
359 $tableProps['ENGINE'] = 'InnoDB';
361 if (strtolower($oldProps['TABLE_COLLATION']) != 'utf8_bin') {
362 $tableProps['DEFAULT CHARSET'] = 'utf8';
363 $tableProps['COLLATE'] = 'utf8_bin';
366 if (count($dropIndex) + count($toadd) + count($todrop) + count($tomod) + count($addIndex) + count($tableProps) == 0) {
371 // For efficiency, we want this all in one
372 // query, instead of using our methods.
376 foreach ($dropIndex as $indexSql) {
377 $phrase[] = $indexSql;
380 foreach ($toadd as $columnName) {
381 $cd = $this->_byName($columns, $columnName);
383 $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
386 foreach ($todrop as $columnName) {
387 $phrase[] = 'DROP COLUMN ' . $columnName;
390 foreach ($tomod as $columnName) {
391 $cd = $this->_byName($columns, $columnName);
393 $phrase[] = 'MODIFY COLUMN ' . $this->_columnSql($cd);
396 foreach ($addIndex as $indexSql) {
397 $phrase[] = $indexSql;
400 foreach ($tableProps as $key => $val) {
401 $phrase[] = "$key=$val";
404 $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
406 common_log(LOG_DEBUG, __METHOD__ . ': ' . $sql);
407 $res = $this->conn->query($sql);
409 if (PEAR::isError($res)) {
410 throw new Exception($res->getMessage());
417 * Is this column a string type?
419 private function _isString(array $cd)
421 $strings = array('char', 'varchar', 'text');
422 return in_array(strtolower($cd['type']), $strings);
426 * Return the proper SQL for creating or
429 * Appropriate for use in CREATE TABLE or
430 * ALTER TABLE statements.
432 * @param ColumnDef $cd column to create
434 * @return string correct SQL for that column
437 function columnSql(array $cd)
440 $line[] = parent::_columnSql($cd);
442 if ($cd['type'] == 'serial') {
443 $line[] = 'auto_increment';
446 if (!empty($cd['extra'])) {
447 $line[] = $cd['extra']; // hisss boooo
450 if (!empty($cd['description'])) {
452 $line[] = $this->quote($cd['description']);
455 return implode(' ', $line);
458 function mapType($column)
460 $map = array('serial' => 'int',
462 'numeric' => 'decimal');
464 $type = $column['type'];
465 if (isset($map[$type])) {
469 if (!empty($column['size'])) {
470 $size = $column['size'];
471 if ($type == 'int' &&
472 in_array($size, array('tiny', 'small', 'medium', 'big'))) {
473 $type = $size . $type;
474 } else if (in_array($type, array('blob', 'text')) &&
475 in_array($size, array('tiny', 'medium', 'long'))) {
476 $type = $size . $type;
483 function typeAndSize($column)
485 if ($column['type'] == 'enum') {
486 $vals = array_map(array($this, 'quote'), $column['enum']);
487 return 'enum(' . implode(',', $vals) . ')';
488 } else if ($this->_isString($column)) {
489 return parent::typeAndSize($column) . ' CHARSET utf8';
491 return parent::typeAndSize($column);