From 91887bcee5b8b6d4599bfcc3f270ee36160ba781 Mon Sep 17 00:00:00 2001 From: mappu Date: Mon, 2 Apr 2018 16:19:28 +1200 Subject: [PATCH] db: add schema table, initial schema-upgrade system --- DB.go | 75 ++++++++++++++++++++++++++++++++++++++++------------------- 1 file changed, 51 insertions(+), 24 deletions(-) diff --git a/DB.go b/DB.go index fab87fc..3f91ce9 100644 --- a/DB.go +++ b/DB.go @@ -3,6 +3,7 @@ package yatwiki import ( "database/sql" "fmt" + "log" "strings" "time" @@ -33,40 +34,66 @@ func NewWikiDB(dbFilePath string, compressionLevel int) (*WikiDB, error) { return &wdb, nil } +func (this *WikiDB) multiTx(stmts ...string) (err error) { + tx, err := this.db.Begin() + if err != nil { + return err + } + + for _, stmt := range stmts { + _, err := tx.Exec(stmt) + if err != nil { + tx.Rollback() + return err + } + } + + return tx.Commit() +} + func (this *WikiDB) assertSchema() error { _, err := this.db.Exec(` - CREATE TABLE IF NOT EXISTS articles ( - id INTEGER PRIMARY KEY, - article INTEGER, - modified INTEGER, - body BLOB, - author TEXT + CREATE TABLE IF NOT EXISTS schema ( + id INTEGER PRIMARY KEY );`) if err != nil { return err } - _, err = this.db.Exec(` - CREATE TABLE IF NOT EXISTS titles ( - id INTEGER PRIMARY KEY, - title TEXT - );`) - if err != nil { - return err + // Look up current value from schema table + schemaLookup := this.db.QueryRow(`SELECT MAX(id) mid FROM schema`) + currentSchema := int64(0) + if err = schemaLookup.Scan(¤tSchema); err == nil { + // That's fine } - _, err = this.db.Exec(` - CREATE INDEX IF NOT EXISTS articles_modified_index ON articles (modified) - `) - if err != nil { - return err - } + log.Printf("Found DB version %d\n", currentSchema) - _, err = this.db.Exec(` - CREATE INDEX IF NOT EXISTS articles_title_index ON articles (article) - `) - if err != nil { - return err + // Schema 0 ==> Schema 1 + + if currentSchema == 0 { + log.Println("Upgrading to DB version 1") + + err := this.multiTx( + `CREATE TABLE IF NOT EXISTS articles ( + id INTEGER PRIMARY KEY, + article INTEGER, + modified INTEGER, + body BLOB, + author TEXT + );`, + `CREATE TABLE IF NOT EXISTS titles ( + id INTEGER PRIMARY KEY, + title TEXT + );`, + `CREATE INDEX IF NOT EXISTS articles_modified_index ON articles (modified)`, + `CREATE INDEX IF NOT EXISTS articles_title_index ON articles (article)`, + `INSERT INTO schema (id) VALUES (1);`, + ) + if err != nil { + return err + } + currentSchema = 1 } return nil