Simple implementation of creating tables with composite primary keys.
authorChuck Hagenbuch <chuck@horde.org>
Wed, 13 Jan 2010 02:53:20 +0000 (21:53 -0500)
committerChuck Hagenbuch <chuck@horde.org>
Wed, 13 Jan 2010 04:32:03 +0000 (23:32 -0500)
Just lets you specify an array of columns to include in the PRIMARY KEY(...)
clause, all of which must be added to the table expliclity.

framework/Db/lib/Horde/Db/Adapter/Base/TableDefinition.php

index bf777c6..c8b4d42 100644 (file)
@@ -27,6 +27,7 @@ class Horde_Db_Adapter_Base_TableDefinition implements ArrayAccess, IteratorAggr
     protected $_base    = null;
     protected $_options = null;
     protected $_columns = null;
+    protected $_primaryKey = null;
 
     /**
      * Class Constructor
@@ -64,8 +65,12 @@ class Horde_Db_Adapter_Base_TableDefinition implements ArrayAccess, IteratorAggr
      */
     public function primaryKey($name)
     {
-        $natives = $this->_native();
-        $this->column($name, $natives['primaryKey']);
+        if (is_scalar($name)) {
+            $natives = $this->_native();
+            $this->column($name, $natives['primaryKey']);
+        }
+
+        $this->_primaryKey = $name;
     }
 
     /**
@@ -142,8 +147,21 @@ class Horde_Db_Adapter_Base_TableDefinition implements ArrayAccess, IteratorAggr
     {
         $cols = array();
         foreach ($this->_columns as $col) { $cols[] = $col->toSql(); }
+        $sql = '  ' . implode(", \n  ", $cols);
+
+        // Specify composite primary keys as well
+        if (is_array($this->_primaryKey)) {
+            $pk = array();
+            foreach ($this->_primaryKey as $pkColumn) { $pk[] = $this->_base->quoteColumnName($pkColumn); }
+            $sql .= ", \n  PRIMARY KEY(" . implode(', ', $pk) . ')';
+        }
 
-        return "  ".implode(", \n  ", $cols);
+        return $sql;
+    }
+
+    public function __toString()
+    {
+        return $this->toSql();
     }