]> git.mxchange.org Git - quix0rs-gnu-social.git/blobdiff - lib/schema.php
quick syntax fix
[quix0rs-gnu-social.git] / lib / schema.php
index 137b814e0269ed727978e11e55ce25cca763a199..40a9fb505d60c97bba60ce983d2ac89dfb3df37b 100644 (file)
@@ -41,46 +41,54 @@ if (!defined('STATUSNET')) {
  * @category Database
  * @package  StatusNet
  * @author   Evan Prodromou <evan@status.net>
+ * @author   Brion Vibber <brion@status.net>
  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
  * @link     http://status.net/
  */
 
 class Schema
 {
-    static $_single = null;
+    static $_static = null;
     protected $conn = null;
 
     /**
      * Constructor. Only run once for singleton object.
      */
 
-    protected function __construct()
+    protected function __construct($conn = null)
     {
-        // XXX: there should be an easier way to do this.
-        $user = new User();
-
-        $this->conn = $user->getDatabaseConnection();
-
-        $user->free();
+        if (is_null($conn)) {
+            // XXX: there should be an easier way to do this.
+            $user = new User();
+            $conn = $user->getDatabaseConnection();
+            $user->free();
+            unset($user);
+        }
 
-        unset($user);
+        $this->conn = $conn;
     }
 
     /**
      * Main public entry point. Use this to get
-     * the singleton object.
+     * the schema object.
      *
-     * @return Schema the (single) Schema object
+     * @return Schema the Schema object for the connection
      */
 
-    static function get()
+    static function get($conn = null)
     {
+        if (is_null($conn)) {
+            $key = 'default';
+        } else {
+            $key = md5(serialize($conn->dsn));
+        }
+        
         $type = common_config('db', 'type');
-        if (empty(self::$_single)) {
+        if (empty(self::$_static[$key])) {
             $schemaClass = ucfirst($type).'Schema';
-            self::$_single = new $schemaClass();
+            self::$_static[$key] = new $schemaClass($conn);
         }
-        return self::$_single;
+        return self::$_static[$key];
     }
 
     /**
@@ -216,7 +224,7 @@ class Schema
         }
 
         if (empty($name)) {
-            $name = "$table_".implode("_", $columnNames)."_idx";
+            $name = "{$table}_".implode("_", $columnNames)."_idx";
         }
 
         $res = $this->conn->query("ALTER TABLE $table ".
@@ -337,12 +345,12 @@ class Schema
      * @return boolean success flag
      */
 
-    public function ensureTable($tableName, $columns)
+    public function ensureTable($tableName, $def)
     {
         // XXX: DB engine portability -> toilet
 
         try {
-            $td = $this->getTableDef($tableName);
+            $old = $this->getTableDef($tableName);
         } catch (Exception $e) {
             if (preg_match('/no such table/', $e->getMessage())) {
                 return $this->createTable($tableName, $columns);
@@ -351,20 +359,22 @@ class Schema
             }
         }
 
-        $cur = $this->_names($td->columns);
-        $new = $this->_names($columns);
+        $cur = array_keys($old['fields']);
+        $new = array_keys($def['fields']);
 
         $toadd  = array_diff($new, $cur);
         $todrop = array_diff($cur, $new);
         $same   = array_intersect($new, $cur);
         $tomod  = array();
 
-        foreach ($same as $m) {
-            $curCol = $this->_byName($td->columns, $m);
-            $newCol = $this->_byName($columns, $m);
+        // Find which fields have actually changed definition
+        // in a way that we need to tweak them for this DB type.
+        foreach ($same as $name) {
+            $curCol = $old['fields'][$name];
+            $newCol = $cur['fields'][$name];
 
-            if (!$newCol->equals($curCol)) {
-                $tomod[] = $newCol->name;
+            if (!$this->columnsEqual($curCol, $newCol)) {
+                $tomod[] = $name;
             }
         }
 
@@ -379,19 +389,18 @@ class Schema
         $phrase = array();
 
         foreach ($toadd as $columnName) {
-            $cd = $this->_byName($columns, $columnName);
-
-            $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
+            $this->appendAlterAddColumn($phrase, $columnName,
+                    $def['fields'][$columnName]);
         }
 
         foreach ($todrop as $columnName) {
-            $phrase[] = 'DROP COLUMN ' . $columnName;
+            $this->appendAlterModifyColumn($phrase, $columnName,
+                    $old['fields'][$columnName],
+                    $def['fields'][$columnName]);
         }
 
         foreach ($tomod as $columnName) {
-            $cd = $this->_byName($columns, $columnName);
-
-            $phrase[] = 'MODIFY COLUMN ' . $this->_columnSql($cd);
+            $this->appendAlterDropColumn($phrase, $columnName);
         }
 
         $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
@@ -405,6 +414,90 @@ class Schema
         return true;
     }
 
+    /**
+     * Append phrase(s) to an array of partial ALTER TABLE chunks in order
+     * to add the given column definition to the table.
+     *
+     * @param array $phrase
+     * @param string $columnName
+     * @param array $cd 
+     */
+    function appendAlterAddColumn(array &$phrase, $columnName, array $cd)
+    {
+        $phrase[] = 'ADD COLUMN ' .
+                    $this->quoteIdentifier($columnName) .
+                    ' ' .
+                    $this->columnSql($cd);
+    }
+
+    /**
+     * Append phrase(s) to an array of partial ALTER TABLE chunks in order
+     * to alter the given column from its old state to a new one.
+     *
+     * @param array $phrase
+     * @param string $columnName
+     * @param array $old previous column definition as found in DB
+     * @param array $cd current column definition
+     */
+    function appendAlterModifyColumn(array &$phrase, $columnName, array $old, array $cd)
+    {
+        $phrase[] = 'MODIFY COLUMN ' .
+                    $this->quoteIdentifier($columnName) .
+                    ' ' .
+                    $this->columnSql($cd);
+    }
+
+    /**
+     * Append phrase(s) to an array of partial ALTER TABLE chunks in order
+     * to drop the given column definition from the table.
+     *
+     * @param array $phrase
+     * @param string $columnName
+     */
+    function appendAlterDropColumn(array &$phrase, $columnName)
+    {
+        $phrase[] = 'DROP COLUMN ' . $this->quoteIdentifier($columnName);
+    }
+
+    /**
+     * Quote a db/table/column identifier if necessary.
+     *
+     * @param string $name
+     * @return string
+     */
+    function quoteIdentifier($name)
+    {
+        return $name;
+    }
+
+    function quoteDefaultValue($cd)
+    {
+        if ($cd['type'] == 'datetime' && $cd['default'] == 'CURRENT_TIMESTAMP') {
+            return $cd['default'];
+        } else {
+            return $this->quoteValue($cd['default']);
+        }
+    }
+
+    function quoteValue($val)
+    {
+        return $this->conn->escape($val);
+    }
+
+    /**
+     * Check if two column definitions are equivalent.
+     * The default implementation checks _everything_ but in many cases
+     * you may be able to discard a bunch of equivalencies.
+     *
+     * @param array $a
+     * @param array $b
+     * @return boolean
+     */
+    function columnsEqual(array $a, array $b)
+    {
+        return !array_diff_assoc($a, $b) && !array_diff_assoc($b, $a);
+    }
+
     /**
      * Returns the array of names from an array of
      * ColumnDef objects.
@@ -414,7 +507,7 @@ class Schema
      * @return array strings for name values
      */
 
-    private function _names($cds)
+    protected function _names($cds)
     {
         $names = array();
 
@@ -435,7 +528,7 @@ class Schema
      * @return ColumnDef matching item or null if no match.
      */
 
-    private function _byName($cds, $name)
+    protected function _byName($cds, $name)
     {
         foreach ($cds as $cd) {
             if ($cd->name == $name) {
@@ -458,30 +551,169 @@ class Schema
      * @return string correct SQL for that column
      */
 
-    private function _columnSql($cd)
+    function columnSql(array $cd)
     {
-        $sql = "{$cd->name} ";
+        $line = array();
+        $line[] = $this->typeAndSize();
+
+        if (isset($cd['default'])) {
+            $line[] = 'default';
+            $line[] = $this->quoted($cd['default']);
+        } else if (!empty($cd['not null'])) {
+            // Can't have both not null AND default!
+            $line[] = 'not null';
+        }
 
-        if (!empty($cd->size)) {
-            $sql .= "{$cd->type}({$cd->size}) ";
-        } else {
-            $sql .= "{$cd->type} ";
+        return implode(' ', $line);
+    }
+
+    /**
+     *
+     * @param string $column canonical type name in defs
+     * @return string native DB type name
+     */
+    function mapType($column)
+    {
+        return $column;
+    }
+
+    function typeAndSize($column)
+    {
+        $type = $this->mapType($column);
+        $lengths = array();
+
+        if ($column['type'] == 'numeric') {
+            if (isset($column['precision'])) {
+                $lengths[] = $column['precision'];
+                if (isset($column['scale'])) {
+                    $lengths[] = $column['scale'];
+                }
+            }
+        } else if (isset($column['length'])) {
+            $lengths[] = $column['length'];
         }
 
-        if (!empty($cd->default)) {
-            $sql .= "default {$cd->default} ";
+        if ($lengths) {
+            return $type . '(' . implode(',', $lengths) . ')';
         } else {
-            $sql .= ($cd->nullable) ? "null " : "not null ";
+            return $type;
         }
+    }
+
+    /**
+     * Map a native type back to an independent type + size
+     *
+     * @param string $type
+     * @return array ($type, $size) -- $size may be null
+     */
+    protected function reverseMapType($type)
+    {
+        return array($type, null);
+    }
+
+    /**
+     * Convert an old-style set of ColumnDef objects into the current
+     * Drupal-style schema definition array, for backwards compatibility
+     * with plugins written for 0.9.x.
+     *
+     * @param string $tableName
+     * @param array $defs
+     * @return array
+     */
+    function oldToNew($tableName, $defs)
+    {
+        $table = array();
+        $prefixes = array(
+            'tiny',
+            'small',
+            'medium',
+            'big',
+        );
+        foreach ($defs as $cd) {
+            $cd->addToTableDef($table);
+            $column = array();
+            $column['type'] = $cd->type;
+            foreach ($prefixes as $prefix) {
+                if (substr($cd->type, 0, strlen($prefix)) == $prefix) {
+                    $column['type'] = substr($cd->type, strlen($prefix));
+                    $column['size'] = $prefix;
+                    break;
+                }
+            }
 
-        if (!empty($cd->auto_increment)) {
-            $sql .= " auto_increment ";
+            if ($cd->size) {
+                if ($cd->type == 'varchar' || $cd->type == 'char') {
+                    $column['length'] = $cd->size;
+                }
+            }
+            if (!$cd->nullable) {
+                $column['not null'] = true;
+            }
+            if ($cd->autoincrement) {
+                $column['type'] = 'serial';
+            }
+            if ($cd->default) {
+                $column['default'] = $cd->default;
+            }
+            $table['fields'][$cd->name] = $column;
+
+            if ($cd->key == 'PRI') {
+                // If multiple columns are defined as primary key,
+                // we'll pile them on in sequence.
+                if (!isset($table['primary key'])) {
+                    $table['primary key'] = array();
+                }
+                $table['primary key'][] = $cd->name;
+            } else if ($cd->key == 'MUL') {
+                // Individual multiple-value indexes are only per-column
+                // using the old ColumnDef syntax.
+                $idx = "{$tableName}_{$cd->name}_idx";
+                $table['indexes'][$idx] = array($cd->name);
+            } else if ($cd->key == 'UNI') {
+                // Individual unique-value indexes are only per-column
+                // using the old ColumnDef syntax.
+                $idx = "{$tableName}_{$cd->name}_idx";
+                $table['unique keys'][$idx] = array($cd->name);
+            }
         }
 
-        if (!empty($cd->extra)) {
-            $sql .= "{$cd->extra} ";
+        return $table;
+    }
+
+    function isNumericType($type)
+    {
+        $type = strtolower($type);
+        $known = array('int', 'serial', 'numeric');
+        return in_array($type, $known);
+    }
+
+    /**
+     * Pull info from the query into a fun-fun array of dooooom
+     *
+     * @param string $sql
+     * @return array of arrays
+     */
+    protected function fetchQueryData($sql)
+    {
+        $res = $this->conn->query($sql);
+        if (PEAR::isError($res)) {
+            throw new Exception($res->getMessage());
+        }
+
+        $out = array();
+        $row = array();
+        while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
+            $out[] = $row;
         }
+        $res->free();
 
-        return $sql;
+        return $out;
     }
+
 }
+
+class SchemaTableMissingException extends Exception
+{
+    // no-op
+}
+