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 $_static = null;
51 protected $conn = null;
54 * Constructor. Only run once for singleton object.
57 protected function __construct($conn = null)
60 // XXX: there should be an easier way to do this.
62 $conn = $user->getDatabaseConnection();
71 * Main public entry point. Use this to get
74 * @return Schema the Schema object for the connection
77 static function get($conn = null)
82 $key = md5(serialize($conn->dsn));
85 $type = common_config('db', 'type');
86 if (empty(self::$_static[$key])) {
87 $schemaClass = ucfirst($type).'Schema';
88 self::$_static[$key] = new $schemaClass($conn);
90 return self::$_static[$key];
94 * Gets a ColumnDef object for a single column.
96 * Throws an exception if the table is not found.
98 * @param string $table name of the table
99 * @param string $column name of the column
101 * @return ColumnDef definition of the column or null
105 public function getColumnDef($table, $column)
107 $td = $this->getTableDef($table);
109 foreach ($td->columns as $cd) {
110 if ($cd->name == $column) {
119 * Creates a table with the given names and columns.
121 * @param string $name Name of the table
122 * @param array $columns Array of ColumnDef objects
125 * @return boolean success flag
128 public function createTable($name, $columns)
134 $sql = "CREATE TABLE $name (\n";
136 for ($i = 0; $i < count($columns); $i++) {
144 $sql .= $this->_columnSql($cd);
148 $uniques[] = $cd->name;
151 $primary[] = $cd->name;
154 $indices[] = $cd->name;
159 if (count($primary) > 0) { // it really should be...
160 $sql .= ",\nconstraint primary key (" . implode(',', $primary) . ")";
163 foreach ($uniques as $u) {
164 $sql .= ",\nunique index {$name}_{$u}_idx ($u)";
167 foreach ($indices as $i) {
168 $sql .= ",\nindex {$name}_{$i}_idx ($i)";
173 $res = $this->conn->query($sql);
175 if (PEAR::isError($res)) {
176 throw new Exception($res->getMessage());
183 * Drops a table from the schema
185 * Throws an exception if the table is not found.
187 * @param string $name Name of the table to drop
189 * @return boolean success flag
192 public function dropTable($name)
194 $res = $this->conn->query("DROP TABLE $name");
196 if (PEAR::isError($res)) {
197 throw new Exception($res->getMessage());
204 * Adds an index to a table.
206 * If no name is provided, a name will be made up based
207 * on the table name and column names.
209 * Throws an exception on database error, esp. if the table
212 * @param string $table Name of the table
213 * @param array $columnNames Name of columns to index
214 * @param string $name (Optional) name of the index
216 * @return boolean success flag
219 public function createIndex($table, $columnNames, $name=null)
221 if (!is_array($columnNames)) {
222 $columnNames = array($columnNames);
226 $name = "$table_".implode("_", $columnNames)."_idx";
229 $res = $this->conn->query("ALTER TABLE $table ".
231 implode(",", $columnNames).")");
233 if (PEAR::isError($res)) {
234 throw new Exception($res->getMessage());
241 * Drops a named index from a table.
243 * @param string $table name of the table the index is on.
244 * @param string $name name of the index
246 * @return boolean success flag
249 public function dropIndex($table, $name)
251 $res = $this->conn->query("ALTER TABLE $table DROP INDEX $name");
253 if (PEAR::isError($res)) {
254 throw new Exception($res->getMessage());
261 * Adds a column to a table
263 * @param string $table name of the table
264 * @param ColumnDef $columndef Definition of the new
267 * @return boolean success flag
270 public function addColumn($table, $columndef)
272 $sql = "ALTER TABLE $table ADD COLUMN " . $this->_columnSql($columndef);
274 $res = $this->conn->query($sql);
276 if (PEAR::isError($res)) {
277 throw new Exception($res->getMessage());
284 * Modifies a column in the schema.
286 * The name must match an existing column and table.
288 * @param string $table name of the table
289 * @param ColumnDef $columndef new definition of the column.
291 * @return boolean success flag
294 public function modifyColumn($table, $columndef)
296 $sql = "ALTER TABLE $table MODIFY COLUMN " .
297 $this->_columnSql($columndef);
299 $res = $this->conn->query($sql);
301 if (PEAR::isError($res)) {
302 throw new Exception($res->getMessage());
309 * Drops a column from a table
311 * The name must match an existing column.
313 * @param string $table name of the table
314 * @param string $columnName name of the column to drop
316 * @return boolean success flag
319 public function dropColumn($table, $columnName)
321 $sql = "ALTER TABLE $table DROP COLUMN $columnName";
323 $res = $this->conn->query($sql);
325 if (PEAR::isError($res)) {
326 throw new Exception($res->getMessage());
333 * Ensures that a table exists with the given
334 * name and the given column definitions.
336 * If the table does not yet exist, it will
337 * create the table. If it does exist, it will
338 * alter the table to match the column definitions.
340 * @param string $tableName name of the table
341 * @param array $columns array of ColumnDef
342 * objects for the table
344 * @return boolean success flag
347 public function ensureTable($tableName, $columns)
349 // XXX: DB engine portability -> toilet
352 $td = $this->getTableDef($tableName);
353 } catch (Exception $e) {
354 if (preg_match('/no such table/', $e->getMessage())) {
355 return $this->createTable($tableName, $columns);
361 $cur = $this->_names($td->columns);
362 $new = $this->_names($columns);
364 $toadd = array_diff($new, $cur);
365 $todrop = array_diff($cur, $new);
366 $same = array_intersect($new, $cur);
369 foreach ($same as $m) {
370 $curCol = $this->_byName($td->columns, $m);
371 $newCol = $this->_byName($columns, $m);
373 if (!$newCol->equals($curCol)) {
374 $tomod[] = $newCol->name;
378 if (count($toadd) + count($todrop) + count($tomod) == 0) {
383 // For efficiency, we want this all in one
384 // query, instead of using our methods.
388 foreach ($toadd as $columnName) {
389 $cd = $this->_byName($columns, $columnName);
391 $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
394 foreach ($todrop as $columnName) {
395 $phrase[] = 'DROP COLUMN ' . $columnName;
398 foreach ($tomod as $columnName) {
399 $cd = $this->_byName($columns, $columnName);
401 $phrase[] = 'MODIFY COLUMN ' . $this->_columnSql($cd);
404 $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
406 $res = $this->conn->query($sql);
408 if (PEAR::isError($res)) {
409 throw new Exception($res->getMessage());
416 * Returns the array of names from an array of
419 * @param array $cds array of ColumnDef objects
421 * @return array strings for name values
424 private function _names($cds)
428 foreach ($cds as $cd) {
429 $names[] = $cd->name;
436 * Get a ColumnDef from an array matching
439 * @param array $cds Array of ColumnDef objects
440 * @param string $name Name of the column
442 * @return ColumnDef matching item or null if no match.
445 private function _byName($cds, $name)
447 foreach ($cds as $cd) {
448 if ($cd->name == $name) {
457 * Return the proper SQL for creating or
460 * Appropriate for use in CREATE TABLE or
461 * ALTER TABLE statements.
463 * @param ColumnDef $cd column to create
465 * @return string correct SQL for that column
468 private function _columnSql($cd)
470 $sql = "{$cd->name} ";
472 if (!empty($cd->size)) {
473 $sql .= "{$cd->type}({$cd->size}) ";
475 $sql .= "{$cd->type} ";
478 if (!empty($cd->default)) {
479 $sql .= "default {$cd->default} ";
481 $sql .= ($cd->nullable) ? "null " : "not null ";
484 if (!empty($cd->auto_increment)) {
485 $sql .= " auto_increment ";
488 if (!empty($cd->extra)) {
489 $sql .= "{$cd->extra} ";
496 class SchemaTableMissingException extends Exception