4 require_once 'DBSchema/Generic.php';
6 class MTrackDBSchema_mysql extends MTrackDBSchema_Generic
9 'autoinc' => 'INT(11) NOT NULL AUTO_INCREMENT',
10 'timestamp' => 'datetime',
11 'blob' => 'longtext', // eak what blob is stored?
12 'text' => 'VARCHAR(128)',
16 function determineVersion() {
17 $ret = parent::determineVersion();
21 parse_str(str_replace(array(";",":"), "&", $this->db->dsn), $dsn);
24 $this->db->query("CREATE DATABASE {$dsn['dbname']}");
25 } catch (Exception $e) {
26 // technically this should not get here..
27 // as pdo's dsn design is borked..
31 // assume we need to create database..
36 function computeFieldCreate($f)
38 $str = "\t`$f->name` ";
39 $str .= isset($this->typemap[$f->type]) ? $this->typemap[$f->type] : $f->type;
40 if (isset($f->nullable) && $f->nullable == '0') {
43 if (!isset($f->default)) {
46 if (!strlen($f->default)) {
47 return $str . " DEFAULT ''";
50 return $str . ($f->default == 'CURRENT_TIMESTAMP' ? '' : 'DEFAULT '. $f->default);
53 // may as well rewrite this.. as we have too loop throug hit anyway..
54 function createTable(MTrackDBSchema_Table $table)
56 echo "Create $table->name\n";
60 foreach ($table->fields as $f) {
61 if ($f->type == 'autoinc') {
65 $str = $this->computeFieldCreate($f);
68 if (is_array($table->keys)) {
70 foreach ($table->keys as $kn=>$k) {
71 if ($k->type != 'primary') continue;
72 // if ($pri_key !== null) continue;
73 $sql[] = "\tprimary key (`" . join('`, `', $k->fields) . "`)";
77 $sql = "CREATE TABLE $table->name (\n" .
83 $this->db->exec($sql);
85 function alterTable(MTrackDBSchema_Table $from, MTrackDBSchema_Table $to)
90 /* if keys have changed, we drop the old key definitions before changing the columns */
91 if (is_array($from->keys)) foreach ($from->keys as $k) {
92 if (!isset($to->keys[$k->name]) || $to->keys[$k->name] != $k) {
93 if ($k->type == 'primary') {
94 $actions[] = "DROP PRIMARY KEY";
96 $actions[] = "DROP INDEX $k->name";
101 foreach ($from->fields as $f) {
102 if (!isset($to->fields[$f->name])) {
103 $actions[] = "DROP COLUMN $f->name";
107 foreach ($to->fields as $f) {
108 if (isset($from->fields[$f->name])) continue;
109 $actions[] = "ADD COLUMN " . $this->computeFieldCreate($f);
112 /* changed and new keys */
113 if (is_array($from->keys)) foreach ($from->keys as $k) {
114 if (isset($to->keys[$k->name]) && $to->keys[$k->name] != $k) {
115 if ($k->type == 'primary') {
116 $actions[] = "ADD primary key (" . join(', ', $k->fields) . ")";
118 $sql[] = $this->computeIndexCreate($to, $k);
122 if (is_array($to->keys)) foreach ($to->keys as $k) {
123 if (isset($from->keys[$k->name])) continue;
124 if ($k->type == 'primary') {
125 $actions[] = "ADD primary key (" . join(', ', $k->fields) . ")";
127 $sql[] = $this->computeIndexCreate($to, $k);
131 if (count($actions)) {
132 $sql[] = "ALTER TABLE $from->name " . join(",\n", $actions);
134 echo "Need to alter $from->name\n";
137 foreach ($sql as $s) {