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