6484095841bf2d042cbabba744f4c915fba98ec6
[web.mtrack] / inc / DBSchema / mysql.php
1 <?php
2
3
4 require_once 'DBSchema/Generic.php';
5
6 class MTrackDBSchema_mysql extends MTrackDBSchema_Generic 
7 {
8     var $typemap = array(
9         'autoinc' => 'AUTO_INCREMENT',
10         'timestamp' => 'datetime',
11         'blob' => 'longtext', // eak what blob is stored?
12     );
13
14
15     function determineVersion() {
16         $ret = parent::determineVersion();
17         if ($ret) {
18             return $ret;
19         }
20         parse_str(str_replace(array(";",":"), "&", $db->dsn), $dsn)
21         $this->db->query("CREATE DATABASE '{$dsn['dbname']}'");
22         // assume we need to create database..
23         return null;
24     }
25   
26   
27   function alterTable(MTrackDBSchema_Table $from, MTrackDBSchema_Table $to)
28   {
29     $sql = array();
30     $actions = array();
31
32     /* if keys have changed, we drop the old key definitions before changing the columns */
33     if (is_array($from->keys)) foreach ($from->keys as $k) {
34       if (!isset($to->keys[$k->name]) || $to->keys[$k->name] != $k) {
35         if ($k->type == 'primary') {
36           $actions[] = "DROP PRIMARY KEY";
37         } else {
38           $actions[] = "DROP INDEX $k->name";
39         }
40       }
41     }
42
43     foreach ($from->fields as $f) {
44       if (!isset($to->fields[$f->name])) {
45         $actions[] = "DROP COLUMN $f->name";
46         continue;
47       }
48     }
49     foreach ($to->fields as $f) {
50       if (isset($from->fields[$f->name])) continue;
51       $actions[] = "ADD COLUMN " . $this->computeFieldCreate($f);
52     }
53
54     /* changed and new keys */
55     if (is_array($from->keys)) foreach ($from->keys as $k) {
56       if (isset($to->keys[$k->name]) && $to->keys[$k->name] != $k) {
57         if ($k->type == 'primary') {
58           $actions[] = "ADD primary key (" . join(', ', $k->fields) . ")";
59         } else {
60           $sql[] = $this->computeIndexCreate($to, $k);
61         }
62       }
63     }
64     if (is_array($to->keys)) foreach ($to->keys as $k) {
65       if (isset($from->keys[$k->name])) continue;
66       if ($k->type == 'primary') {
67         $actions[] = "ADD primary key (" . join(', ', $k->fields) . ")";
68       } else {
69         $sql[] = $this->computeIndexCreate($to, $k);
70       }
71     }
72
73     if (count($actions)) {
74       $sql[] = "ALTER TABLE $from->name " . join(",\n", $actions);
75     }
76     echo "Need to alter $from->name\n";
77     echo "SQL:\n";
78     var_dump($sql);
79     foreach ($sql as $s) {
80       $this->db->exec($s);
81     }
82   }
83 }