db->query('select version from mtrack_schema'); if ($q) { foreach ($q as $row) { return $row[0]; } } } catch (Exception $e) { } /* do we have any tables at all? if we do, we treat that as schema * version 0 */ foreach ($this->db->query('select count(*) from sqlite_master') as $row) { if ($row[0] > 0) { $this->db->exec( 'create table mtrack_schema (version integer not null)'); return 0; } } return null; } var $typemap = array( 'autoinc' => 'INTEGER PRIMARY KEY AUTOINCREMENT', 'longtext' => 'text' ); function createTable(MTrackDBSchema_Table $table) { parent::createTable($table); } function alterTable(MTrackDBSchema_Table $from, MTrackDBSchema_Table $to) { $tname = $from->name . '_' . uniqid(); $sql = array(); foreach ($to->fields as $f) { if ($f->type == 'autoinc') { $pri_key = $f->name; } $str = $this->computeFieldCreate($f); $sql[] = $str; } $sql = "CREATE TEMPORARY TABLE $tname (\n" . join(",\n", $sql) . ")\n"; $this->db->exec($sql); /* copy old data into this table */ $sql = "INSERT INTO $tname ("; $new_names = array(); $old_names = array(); foreach ($from->fields as $f) { if (!isset($to->fields[$f->name])) { // to_field does not exist in new schema. // look for it. foreach( $to->fields as $tf) { if (!empty($tf->oldname) && $tf->oldname == $f->name) { $new_names[] = $f->name; $old_names[] = $f->oldname; break; } } continue; } $new_names[] = $f->name; $old_names[] = $f->name; } $sql .= join(', ', $new_names); $sql .= ") SELECT " . join(', ', $names) . " from $from->name"; #echo "$sql\n"; $this->db->exec($sql); $this->db->exec("DROP TABLE $from->name"); $this->createTable($to); $sql = "INSERT INTO $from->name ("; $names = array(); foreach ($from->fields as $f) { if (!isset($to->fields[$f->name])) continue; $names[] = $f->name; } $sql .= join(', ', $names); $sql .= ") SELECT " . join(', ', $names) . " from $tname"; #echo "$sql\n"; $this->db->exec($sql); $this->db->exec("DROP TABLE $tname"); } }