1
0
forked from MTSR/mapserver

sqlite migration

This commit is contained in:
Thomas Rudin 2019-01-09 08:44:14 +01:00
parent 98350f48f9
commit 3b005e8958
2 changed files with 48 additions and 1 deletions

View File

@ -3,16 +3,55 @@ package db
import ( import (
"database/sql" "database/sql"
_ "github.com/mattn/go-sqlite3" _ "github.com/mattn/go-sqlite3"
"github.com/sirupsen/logrus"
) )
const migrateScript = ` const migrateScript = `
alter table blocks add mtime timestamp default NULL;
update blocks set mtime = current_timestamp;
create index blocks_mtime on blocks(mtime);
CREATE TRIGGER update_blocks_mtime_insert after insert on blocks for each row
begin
update blocks set mtime = current_timestamp where pos = new.pos;
end;
CREATE TRIGGER update_blocks_mtime_update after update on blocks for each row
begin
update blocks set mtime = current_timestamp where pos = old.pos;
end;
` `
type Sqlite3Accessor struct { type Sqlite3Accessor struct {
db *sql.DB db *sql.DB
filename string
} }
func (db *Sqlite3Accessor) Migrate() error { func (db *Sqlite3Accessor) Migrate() error {
log := logrus.WithFields(logrus.Fields{"prefix": "db/sqlite.Migrate","filename":db.filename})
//RW connection
rwdb, err := sql.Open("sqlite3", db.filename + "?mode=rw")
if err != nil {
return err
}
defer rwdb.Close()
hasMtime := true
_, err = rwdb.Query("select max(mtime) from blocks")
if err != nil {
hasMtime = false
}
if !hasMtime {
log.Info("Migrating database")
_, err = rwdb.Exec(migrateScript)
if err != nil {
return err
}
}
return nil return nil
} }
@ -34,6 +73,6 @@ func NewSqliteAccessor(filename string) (*Sqlite3Accessor, error) {
return nil, err return nil, err
} }
sq := &Sqlite3Accessor{db: db} sq := &Sqlite3Accessor{db: db, filename: filename}
return sq, nil return sq, nil
} }

View File

@ -36,4 +36,12 @@ func TestMigrate(t *testing.T){
} }
createEmptyDatabase(tmpfile.Name()) createEmptyDatabase(tmpfile.Name())
a, err := NewSqliteAccessor(tmpfile.Name())
if err != nil {
panic(err)
}
err = a.Migrate()
if err != nil {
panic(err)
}
} }