diff --git a/db/sqlite.go b/db/sqlite.go index 4c5cef6..b7138cd 100644 --- a/db/sqlite.go +++ b/db/sqlite.go @@ -3,16 +3,55 @@ package db import ( "database/sql" _ "github.com/mattn/go-sqlite3" + "github.com/sirupsen/logrus" ) 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 { db *sql.DB + filename string } 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 } @@ -34,6 +73,6 @@ func NewSqliteAccessor(filename string) (*Sqlite3Accessor, error) { return nil, err } - sq := &Sqlite3Accessor{db: db} + sq := &Sqlite3Accessor{db: db, filename: filename} return sq, nil } diff --git a/db/sqlite_test.go b/db/sqlite_test.go index a322499..f22606c 100644 --- a/db/sqlite_test.go +++ b/db/sqlite_test.go @@ -36,4 +36,12 @@ func TestMigrate(t *testing.T){ } createEmptyDatabase(tmpfile.Name()) + a, err := NewSqliteAccessor(tmpfile.Name()) + if err != nil { + panic(err) + } + err = a.Migrate() + if err != nil { + panic(err) + } }