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