From a7b7670d5ffbee5ecb748623b1788dda74c7c4b2 Mon Sep 17 00:00:00 2001 From: vilmibm Date: Fri, 22 Apr 2022 14:49:36 -0500 Subject: [PATCH] db initialization --- server/cmd/main.go | 39 ++++++++++++++++++++++++++++++++++----- server/cmd/schema.sql | 2 ++ 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/server/cmd/main.go b/server/cmd/main.go index cde32a3..ff9dd9b 100644 --- a/server/cmd/main.go +++ b/server/cmd/main.go @@ -4,11 +4,13 @@ import ( "database/sql" _ "embed" "encoding/json" + "errors" "flag" "fmt" "io" "net/http" "os" + "strings" _ "github.com/mattn/go-sqlite3" ) @@ -38,10 +40,12 @@ type Opts struct { Logf func(string, ...interface{}) Config Config DB *sql.DB + Reset bool } func main() { var configFlag = flag.String("config", "config.yml", "A path to a config file.") + var resetFlag = flag.Bool("reset", false, "reset the database. WARNING this wipes everything.") flag.Parse() io := iostreams{ Err: os.Stderr, @@ -49,6 +53,7 @@ func main() { } opts := &Opts{ ConfigPath: *configFlag, + Reset: *resetFlag, IO: io, // TODO use real logger Log: func(s string) { @@ -92,7 +97,7 @@ func _main(opts *Opts) error { } defer teardown() - err = ensureSchema(*opts, "1.0.0") + err = ensureSchema(*opts) if err != nil { return err } @@ -108,10 +113,34 @@ func _main(opts *Opts) error { return nil } -func ensureSchema(opts Opts, version string) error { - // TODO make idempotent - // TODO actually respect version - _, err := opts.DB.Exec(schemaSQL) +func ensureSchema(opts Opts) error { + db := opts.DB + + if opts.Reset { + err := os.Remove(opts.Config.DBPath) + if err != nil { + return fmt.Errorf("failed to delete database: %w", err) + } + } + rows, err := db.Query("select version from meta") + if err == nil { + //defer rows.Close() + rows.Next() + var version string + err = rows.Scan(&version) + if err != nil { + return fmt.Errorf("failed to check database schema version: %w", err) + } else if version == "" { + return errors.New("database is in unknown state") + } + return nil + } + + if !strings.Contains(err.Error(), "no such table") { + return fmt.Errorf("got error checking database state: %w", err) + } + + _, err = db.Exec(schemaSQL) if err != nil { return fmt.Errorf("failed to initialize database schema: %w", err) } diff --git a/server/cmd/schema.sql b/server/cmd/schema.sql index 43474d8..b93a2a2 100644 --- a/server/cmd/schema.sql +++ b/server/cmd/schema.sql @@ -2,6 +2,8 @@ create table meta ( version text -- schema version ); +insert into meta values ("1.0.0"); + create table users ( user_id text, -- string (uuid1) user_name text, -- string