db: add schema table, initial schema-upgrade system

This commit is contained in:
mappu 2018-04-02 16:19:28 +12:00
parent 993bd6c4f3
commit 91887bcee5

71
DB.go
View File

@ -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 (
CREATE TABLE IF NOT EXISTS schema (
id INTEGER PRIMARY KEY
);`)
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(&currentSchema); err == nil {
// That's fine
}
log.Printf("Found DB version %d\n", currentSchema)
// 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
);`)
if err != nil {
return err
}
_, err = this.db.Exec(`
CREATE TABLE IF NOT EXISTS titles (
);`,
`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
}
_, err = this.db.Exec(`
CREATE INDEX IF NOT EXISTS articles_modified_index ON articles (modified)
`)
if err != nil {
return err
}
_, err = this.db.Exec(`
CREATE INDEX IF NOT EXISTS articles_title_index ON articles (article)
`)
if err != nil {
return err
currentSchema = 1
}
return nil