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 include "lib/schema.{$type}.php";
81 $class = $type.='Schema';
82 self::$_single = new $class();
84 return self::$_single;
89 * Gets a ColumnDef object for a single column.
91 * Throws an exception if the table is not found.
93 * @param string $table name of the table
94 * @param string $column name of the column
96 * @return ColumnDef definition of the column or null
100 public function getColumnDef($table, $column)
102 $td = $this->getTableDef($table);
104 foreach ($td->columns as $cd) {
105 if ($cd->name == $column) {
114 * Creates a table with the given names and columns.
116 * @param string $name Name of the table
117 * @param array $columns Array of ColumnDef objects
120 * @return boolean success flag
123 public function createTable($name, $columns)
129 $sql = "CREATE TABLE $name (\n";
131 for ($i = 0; $i < count($columns); $i++) {
139 $sql .= $this->_columnSql($cd);
143 $uniques[] = $cd->name;
146 $primary[] = $cd->name;
149 $indices[] = $cd->name;
154 if (count($primary) > 0) { // it really should be...
155 $sql .= ",\nconstraint primary key (" . implode(',', $primary) . ")";
158 foreach ($uniques as $u) {
159 $sql .= ",\nunique index {$name}_{$u}_idx ($u)";
162 foreach ($indices as $i) {
163 $sql .= ",\nindex {$name}_{$i}_idx ($i)";
168 $res = $this->conn->query($sql);
170 if (PEAR::isError($res)) {
171 throw new Exception($res->getMessage());
178 * Drops a table from the schema
180 * Throws an exception if the table is not found.
182 * @param string $name Name of the table to drop
184 * @return boolean success flag
187 public function dropTable($name)
189 $res = $this->conn->query("DROP TABLE $name");
191 if (PEAR::isError($res)) {
192 throw new Exception($res->getMessage());
199 * Adds an index to a table.
201 * If no name is provided, a name will be made up based
202 * on the table name and column names.
204 * Throws an exception on database error, esp. if the table
207 * @param string $table Name of the table
208 * @param array $columnNames Name of columns to index
209 * @param string $name (Optional) name of the index
211 * @return boolean success flag
214 public function createIndex($table, $columnNames, $name=null)
216 if (!is_array($columnNames)) {
217 $columnNames = array($columnNames);
221 $name = "$table_".implode("_", $columnNames)."_idx";
224 $res = $this->conn->query("ALTER TABLE $table ".
226 implode(",", $columnNames).")");
228 if (PEAR::isError($res)) {
229 throw new Exception($res->getMessage());
236 * Drops a named index from a table.
238 * @param string $table name of the table the index is on.
239 * @param string $name name of the index
241 * @return boolean success flag
244 public function dropIndex($table, $name)
246 $res = $this->conn->query("ALTER TABLE $table DROP INDEX $name");
248 if (PEAR::isError($res)) {
249 throw new Exception($res->getMessage());
256 * Adds a column to a table
258 * @param string $table name of the table
259 * @param ColumnDef $columndef Definition of the new
262 * @return boolean success flag
265 public function addColumn($table, $columndef)
267 $sql = "ALTER TABLE $table ADD COLUMN " . $this->_columnSql($columndef);
269 $res = $this->conn->query($sql);
271 if (PEAR::isError($res)) {
272 throw new Exception($res->getMessage());
279 * Modifies a column in the schema.
281 * The name must match an existing column and table.
283 * @param string $table name of the table
284 * @param ColumnDef $columndef new definition of the column.
286 * @return boolean success flag
289 public function modifyColumn($table, $columndef)
291 $sql = "ALTER TABLE $table MODIFY COLUMN " .
292 $this->_columnSql($columndef);
294 $res = $this->conn->query($sql);
296 if (PEAR::isError($res)) {
297 throw new Exception($res->getMessage());
304 * Drops a column from a table
306 * The name must match an existing column.
308 * @param string $table name of the table
309 * @param string $columnName name of the column to drop
311 * @return boolean success flag
314 public function dropColumn($table, $columnName)
316 $sql = "ALTER TABLE $table DROP COLUMN $columnName";
318 $res = $this->conn->query($sql);
320 if (PEAR::isError($res)) {
321 throw new Exception($res->getMessage());
328 * Ensures that a table exists with the given
329 * name and the given column definitions.
331 * If the table does not yet exist, it will
332 * create the table. If it does exist, it will
333 * alter the table to match the column definitions.
335 * @param string $tableName name of the table
336 * @param array $columns array of ColumnDef
337 * objects for the table
339 * @return boolean success flag
342 public function ensureTable($tableName, $columns)
344 // XXX: DB engine portability -> toilet
347 $td = $this->getTableDef($tableName);
348 } catch (Exception $e) {
349 if (preg_match('/no such table/', $e->getMessage())) {
350 return $this->createTable($tableName, $columns);
356 $cur = $this->_names($td->columns);
357 $new = $this->_names($columns);
359 $toadd = array_diff($new, $cur);
360 $todrop = array_diff($cur, $new);
361 $same = array_intersect($new, $cur);
364 foreach ($same as $m) {
365 $curCol = $this->_byName($td->columns, $m);
366 $newCol = $this->_byName($columns, $m);
368 if (!$newCol->equals($curCol)) {
369 $tomod[] = $newCol->name;
373 if (count($toadd) + count($todrop) + count($tomod) == 0) {
378 // For efficiency, we want this all in one
379 // query, instead of using our methods.
383 foreach ($toadd as $columnName) {
384 $cd = $this->_byName($columns, $columnName);
386 $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
389 foreach ($todrop as $columnName) {
390 $phrase[] = 'DROP COLUMN ' . $columnName;
393 foreach ($tomod as $columnName) {
394 $cd = $this->_byName($columns, $columnName);
396 $phrase[] = 'MODIFY COLUMN ' . $this->_columnSql($cd);
399 $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
401 $res = $this->conn->query($sql);
403 if (PEAR::isError($res)) {
404 throw new Exception($res->getMessage());
411 * Returns the array of names from an array of
414 * @param array $cds array of ColumnDef objects
416 * @return array strings for name values
419 private function _names($cds)
423 foreach ($cds as $cd) {
424 $names[] = $cd->name;
431 * Get a ColumnDef from an array matching
434 * @param array $cds Array of ColumnDef objects
435 * @param string $name Name of the column
437 * @return ColumnDef matching item or null if no match.
440 private function _byName($cds, $name)
442 foreach ($cds as $cd) {
443 if ($cd->name == $name) {
452 * Return the proper SQL for creating or
455 * Appropriate for use in CREATE TABLE or
456 * ALTER TABLE statements.
458 * @param ColumnDef $cd column to create
460 * @return string correct SQL for that column
463 private function _columnSql($cd)
465 $sql = "{$cd->name} ";
467 if (!empty($cd->size)) {
468 $sql .= "{$cd->type}({$cd->size}) ";
470 $sql .= "{$cd->type} ";
473 if (!empty($cd->default)) {
474 $sql .= "default {$cd->default} ";
476 $sql .= ($cd->nullable) ? "null " : "not null ";
479 if (!empty($cd->auto_increment)) {
480 $sql .= " auto_increment ";
483 if (!empty($cd->extra)) {
484 $sql .= "{$cd->extra} ";