'SERIAL UNIQUE', 'timestamp' => 'timestamp with time zone', 'blob' => 'bytea', ); function alterTable(MTrackDBSchema_Table $from, MTrackDBSchema_Table $to) { $sql = array(); $actions = array(); /* if keys have changed, we drop the old key definitions before changing the columns */ if (is_array($from->keys)) foreach ($from->keys as $k) { if (!isset($to->keys[$k->name]) || $to->keys[$k->name] != $k) { if ($k->type == 'primary') { $actions[] = "DROP CONSTRAINT {$from->name}_pkey"; } else { $sql[] = "DROP INDEX $k->name"; } } } foreach ($from->fields as $f) { if (!isset($to->fields[$f->name])) { $actions[] = "DROP COLUMN $f->name"; continue; } } foreach ($to->fields as $f) { if (isset($from->fields[$f->name])) continue; $actions[] = "ADD COLUMN " . $this->computeFieldCreate($f); } /* changed and new keys */ if (is_array($from->keys)) foreach ($from->keys as $k) { if (isset($to->keys[$k->name]) && $to->keys[$k->name] != $k) { if ($k->type == 'primary') { $actions[] = "ADD primary key (" . join(', ', $k->fields) . ")"; } else { $sql[] = $this->computeIndexCreate($to, $k); } } } if (is_array($to->keys)) foreach ($to->keys as $k) { if (isset($from->keys[$k->name])) continue; if ($k->type == 'primary') { $actions[] = "ADD primary key (" . join(', ', $k->fields) . ")"; } else { $sql[] = $this->computeIndexCreate($to, $k); } } if (count($actions)) { $sql[] = "ALTER TABLE $from->name " . join(",\n", $actions); } echo "Need to alter $from->name\n"; echo "SQL:\n"; var_dump($sql); foreach ($sql as $s) { $this->db->exec($s); } } }