final move of files
[web.mtrack] / MTrack / DBSchema / pgsql.php
1 <?php
2
3
4 require_once 'DBSchema/Generic.php';
5
6 class MTrackDBSchema_pgsql extends MTrackDBSchema_Generic {
7   var $typemap = array(
8     'autoinc' => 'SERIAL UNIQUE',
9     'timestamp' => 'timestamp with time zone',
10     'blob' => 'bytea',
11   );
12
13   function alterTable(MTrackDBSchema_Table $from, MTrackDBSchema_Table $to)
14   {
15     $sql = array();
16     $actions = array();
17
18     /* if keys have changed, we drop the old key definitions before changing the columns */
19     if (is_array($from->keys)) foreach ($from->keys as $k) {
20       if (!isset($to->keys[$k->name]) || $to->keys[$k->name] != $k) {
21         if ($k->type == 'primary') {
22           $actions[] = "DROP CONSTRAINT {$from->name}_pkey";
23         } else {
24           $sql[] = "DROP INDEX $k->name";
25         }
26       }
27     }
28
29     foreach ($from->fields as $f) {
30       if (!isset($to->fields[$f->name])) {
31         $actions[] = "DROP COLUMN $f->name";
32         continue;
33       }
34     }
35     foreach ($to->fields as $f) {
36       if (isset($from->fields[$f->name])) continue;
37       $actions[] = "ADD COLUMN " . $this->computeFieldCreate($f);
38     }
39
40     /* changed and new keys */
41     if (is_array($from->keys)) foreach ($from->keys as $k) {
42       if (isset($to->keys[$k->name]) && $to->keys[$k->name] != $k) {
43         if ($k->type == 'primary') {
44           $actions[] = "ADD primary key (" . join(', ', $k->fields) . ")";
45         } else {
46           $sql[] = $this->computeIndexCreate($to, $k);
47         }
48       }
49     }
50     if (is_array($to->keys)) foreach ($to->keys as $k) {
51       if (isset($from->keys[$k->name])) continue;
52       if ($k->type == 'primary') {
53         $actions[] = "ADD primary key (" . join(', ', $k->fields) . ")";
54       } else {
55         $sql[] = $this->computeIndexCreate($to, $k);
56       }
57     }
58
59     if (count($actions)) {
60       $sql[] = "ALTER TABLE $from->name " . join(",\n", $actions);
61     }
62     echo "Need to alter $from->name\n";
63     echo "SQL:\n";
64     var_dump($sql);
65     foreach ($sql as $s) {
66       $this->db->exec($s);
67     }
68   }
69 }