inc/DBSchema/Generic.php
[web.mtrack] / inc / DBSchema / Generic.php
1 <?php
2
3 require_once 'Interface/DBSchema_Driver.php';
4
5 class MTrackDBSchema_Generic implements IMTrackDBSchema_Driver {
6   var $db;
7   var $typemap = array();
8
9   function setDB(PDO $db) {
10     $this->db = $db;
11   }
12
13   function determineVersion() {
14     try {
15       $q = $this->db->query('select version from mtrack_schema');
16       if ($q) {
17         foreach ($q as $row) {
18           return $row[0];
19         }
20       }
21     } catch (Exception $e) {
22         print_r($e->toString());
23     }
24     return null;
25   }
26
27   function computeFieldCreate($f) {
28     $str = "\t$f->name ";
29     $str .= isset($this->typemap[$f->type]) ? $this->typemap[$f->type] : $f->type;
30     if (isset($f->nullable) && $f->nullable == '0') {
31       $str .= ' NOT NULL ';
32     }
33     if (isset($f->default)) {
34       if (!strlen($f->default)) {
35         $str .= " DEFAULT ''";
36       } else {
37         $str .= " DEFAULT $f->default";
38       }
39     }
40     return $str;
41   }
42
43   function computeIndexCreate($table, $k) {
44     switch ($k->type) {
45       case 'unique':
46         $kt = ' UNIQUE ';
47         break;
48       case 'multiple':
49       default:
50         $kt = '';
51     }
52     return "CREATE $kt INDEX $k->name on $table->name (" . join(', ', $k->fields) . ")";
53   }
54
55   function createTable(MTrackDBSchema_Table $table)
56   {
57     echo "Create $table->name\n";
58
59     $pri_key = null;
60
61     $sql = array();
62     foreach ($table->fields as $f) {
63       if ($f->type == 'autoinc') {
64         $pri_key = $f->name;
65       }
66       $str = $this->computeFieldCreate($f);
67       $sql[] = $str;
68     }
69
70     if (is_array($table->keys)) foreach ($table->keys as $k) {
71       if ($k->type != 'primary') continue;
72       if ($pri_key !== null) continue;
73       $sql[] = "\tprimary key (" . join(', ', $k->fields) . ")";
74     }
75
76     $sql = "CREATE TABLE $table->name (\n" .
77       join(",\n", $sql) .
78       ")\n";
79
80     echo $sql;
81
82     $this->db->exec($sql);
83
84     if (is_array($table->keys)) foreach ($table->keys as $k) {
85       if ($k->type == 'primary') continue;
86       $this->db->exec($this->computeIndexCreate($table, $k));
87     }
88   }
89
90   function alterTable(MTrackDBSchema_Table $from, MTrackDBSchema_Table $to)
91   {
92     /* if keys have changed, we drop the old key definitions before changing the columns */
93
94     echo "Need to alter $from->name\n";
95     throw new Exception("bang!");
96   }
97
98   function dropTable(MTrackDBSchema_Table $table)
99   {
100     echo "Drop $table->name\n";
101     $this->db->exec("drop table $table->name");
102   }
103 }