From 3b005e895839bdd0c5d9e8e05171a2d42e1a74a2 Mon Sep 17 00:00:00 2001 From: Thomas Rudin Date: Wed, 9 Jan 2019 08:44:14 +0100 Subject: [PATCH] sqlite migration --- db/sqlite.go | 41 ++++++++++++++++++++++++++++++++++++++++- db/sqlite_test.go | 8 ++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) 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) + } }