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 $type = common_config('db', 'type');
79 if (empty(self::$_single)) {
80 $schemaClass = ucfirst($type).'Schema';
81 self::$_single = new $schemaClass();
83 return self::$_single;
87 * Gets a ColumnDef object for a single column.
89 * Throws an exception if the table is not found.
91 * @param string $table name of the table
92 * @param string $column name of the column
94 * @return ColumnDef definition of the column or null
98 public function getColumnDef($table, $column)
100 $td = $this->getTableDef($table);
102 foreach ($td->columns as $cd) {
103 if ($cd->name == $column) {
112 * Creates a table with the given names and columns.
114 * @param string $name Name of the table
115 * @param array $columns Array of ColumnDef objects
118 * @return boolean success flag
121 public function createTable($name, $columns)
127 $sql = "CREATE TABLE $name (\n";
129 for ($i = 0; $i < count($columns); $i++) {
137 $sql .= $this->_columnSql($cd);
141 $uniques[] = $cd->name;
144 $primary[] = $cd->name;
147 $indices[] = $cd->name;
152 if (count($primary) > 0) { // it really should be...
153 $sql .= ",\nconstraint primary key (" . implode(',', $primary) . ")";
156 foreach ($uniques as $u) {
157 $sql .= ",\nunique index {$name}_{$u}_idx ($u)";
160 foreach ($indices as $i) {
161 $sql .= ",\nindex {$name}_{$i}_idx ($i)";
166 $res = $this->conn->query($sql);
168 if (PEAR::isError($res)) {
169 throw new Exception($res->getMessage());
176 * Drops a table from the schema
178 * Throws an exception if the table is not found.
180 * @param string $name Name of the table to drop
182 * @return boolean success flag
185 public function dropTable($name)
187 $res = $this->conn->query("DROP TABLE $name");
189 if (PEAR::isError($res)) {
190 throw new Exception($res->getMessage());
197 * Adds an index to a table.
199 * If no name is provided, a name will be made up based
200 * on the table name and column names.
202 * Throws an exception on database error, esp. if the table
205 * @param string $table Name of the table
206 * @param array $columnNames Name of columns to index
207 * @param string $name (Optional) name of the index
209 * @return boolean success flag
212 public function createIndex($table, $columnNames, $name=null)
214 if (!is_array($columnNames)) {
215 $columnNames = array($columnNames);
219 $name = "$table_".implode("_", $columnNames)."_idx";
222 $res = $this->conn->query("ALTER TABLE $table ".
224 implode(",", $columnNames).")");
226 if (PEAR::isError($res)) {
227 throw new Exception($res->getMessage());
234 * Drops a named index from a table.
236 * @param string $table name of the table the index is on.
237 * @param string $name name of the index
239 * @return boolean success flag
242 public function dropIndex($table, $name)
244 $res = $this->conn->query("ALTER TABLE $table DROP INDEX $name");
246 if (PEAR::isError($res)) {
247 throw new Exception($res->getMessage());
254 * Adds a column to a table
256 * @param string $table name of the table
257 * @param ColumnDef $columndef Definition of the new
260 * @return boolean success flag
263 public function addColumn($table, $columndef)
265 $sql = "ALTER TABLE $table ADD COLUMN " . $this->_columnSql($columndef);
267 $res = $this->conn->query($sql);
269 if (PEAR::isError($res)) {
270 throw new Exception($res->getMessage());
277 * Modifies a column in the schema.
279 * The name must match an existing column and table.
281 * @param string $table name of the table
282 * @param ColumnDef $columndef new definition of the column.
284 * @return boolean success flag
287 public function modifyColumn($table, $columndef)
289 $sql = "ALTER TABLE $table MODIFY COLUMN " .
290 $this->_columnSql($columndef);
292 $res = $this->conn->query($sql);
294 if (PEAR::isError($res)) {
295 throw new Exception($res->getMessage());
302 * Drops a column from a table
304 * The name must match an existing column.
306 * @param string $table name of the table
307 * @param string $columnName name of the column to drop
309 * @return boolean success flag
312 public function dropColumn($table, $columnName)
314 $sql = "ALTER TABLE $table DROP COLUMN $columnName";
316 $res = $this->conn->query($sql);
318 if (PEAR::isError($res)) {
319 throw new Exception($res->getMessage());
326 * Ensures that a table exists with the given
327 * name and the given column definitions.
329 * If the table does not yet exist, it will
330 * create the table. If it does exist, it will
331 * alter the table to match the column definitions.
333 * @param string $tableName name of the table
334 * @param array $columns array of ColumnDef
335 * objects for the table
337 * @return boolean success flag
340 public function ensureTable($tableName, $columns)
342 // XXX: DB engine portability -> toilet
345 $td = $this->getTableDef($tableName);
346 } catch (Exception $e) {
347 if (preg_match('/no such table/', $e->getMessage())) {
348 return $this->createTable($tableName, $columns);
354 $cur = $this->_names($td->columns);
355 $new = $this->_names($columns);
357 $toadd = array_diff($new, $cur);
358 $todrop = array_diff($cur, $new);
359 $same = array_intersect($new, $cur);
362 foreach ($same as $m) {
363 $curCol = $this->_byName($td->columns, $m);
364 $newCol = $this->_byName($columns, $m);
366 if (!$newCol->equals($curCol)) {
367 $tomod[] = $newCol->name;
371 if (count($toadd) + count($todrop) + count($tomod) == 0) {
376 // For efficiency, we want this all in one
377 // query, instead of using our methods.
381 foreach ($toadd as $columnName) {
382 $cd = $this->_byName($columns, $columnName);
384 $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
387 foreach ($todrop as $columnName) {
388 $phrase[] = 'DROP COLUMN ' . $columnName;
391 foreach ($tomod as $columnName) {
392 $cd = $this->_byName($columns, $columnName);
394 $phrase[] = 'MODIFY COLUMN ' . $this->_columnSql($cd);
397 $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
399 $res = $this->conn->query($sql);
401 if (PEAR::isError($res)) {
402 throw new Exception($res->getMessage());
409 * Returns the array of names from an array of
412 * @param array $cds array of ColumnDef objects
414 * @return array strings for name values
417 private function _names($cds)
421 foreach ($cds as $cd) {
422 $names[] = $cd->name;
429 * Get a ColumnDef from an array matching
432 * @param array $cds Array of ColumnDef objects
433 * @param string $name Name of the column
435 * @return ColumnDef matching item or null if no match.
438 private function _byName($cds, $name)
440 foreach ($cds as $cd) {
441 if ($cd->name == $name) {
450 * Return the proper SQL for creating or
453 * Appropriate for use in CREATE TABLE or
454 * ALTER TABLE statements.
456 * @param ColumnDef $cd column to create
458 * @return string correct SQL for that column
461 private function _columnSql($cd)
463 $sql = "{$cd->name} ";
465 if (!empty($cd->size)) {
466 $sql .= "{$cd->type}({$cd->size}) ";
468 $sql .= "{$cd->type} ";
471 if (!empty($cd->default)) {
472 $sql .= "default {$cd->default} ";
474 $sql .= ($cd->nullable) ? "null " : "not null ";
477 if (!empty($cd->auto_increment)) {
478 $sql .= " auto_increment ";
481 if (!empty($cd->extra)) {
482 $sql .= "{$cd->extra} ";
489 class SchemaTableMissingException extends Exception