diff --git a/cmd/camtool/dbinit.go b/cmd/camtool/dbinit.go index a237fec76..61ca30ca0 100644 --- a/cmd/camtool/dbinit.go +++ b/cmd/camtool/dbinit.go @@ -169,9 +169,11 @@ func (c *dbinitCmd) RunCommand(args []string) error { } doQuery(db, fmt.Sprintf(`SELECT replaceintometa('version', '%d')`, postgres.SchemaVersion())) case "mysql": - for _, tableSql := range mysql.SQLCreateTables() { - tableSql = strings.Replace(tableSql, "/*DB*/", dbname, -1) - do(db, tableSql) + if err := mysql.CreateDB(db, dbname); err != nil { + exitf("%v", err) + } + for _, tableSQL := range mysql.SQLCreateTables() { + do(db, tableSQL) } do(db, fmt.Sprintf(`REPLACE INTO meta VALUES ('version', '%d')`, mysql.SchemaVersion())) case "sqlite": diff --git a/pkg/sorted/mysql/dbschema.go b/pkg/sorted/mysql/dbschema.go index 4aa51a7f7..6d83e589b 100644 --- a/pkg/sorted/mysql/dbschema.go +++ b/pkg/sorted/mysql/dbschema.go @@ -28,7 +28,6 @@ func SchemaVersion() int { // which is purely about bytes. func SQLCreateTables() []string { return []string{ - `CREATE DATABASE IF NOT EXISTS /*DB*/`, `CREATE TABLE IF NOT EXISTS /*DB*/.rows ( k VARCHAR(255) NOT NULL PRIMARY KEY, v VARCHAR(255)) diff --git a/pkg/sorted/mysql/mysqlkv.go b/pkg/sorted/mysql/mysqlkv.go index 7c66e7f13..74bfafb6a 100644 --- a/pkg/sorted/mysql/mysqlkv.go +++ b/pkg/sorted/mysql/mysqlkv.go @@ -20,6 +20,7 @@ package mysql import ( "database/sql" + "errors" "fmt" "os" "strings" @@ -68,6 +69,9 @@ func newKeyValueFromJSONConfig(cfg jsonconfig.Obj) (sorted.KeyValue, error) { return nil, err } + if err := CreateDB(db, database); err != nil { + return nil, err + } for _, tableSQL := range SQLCreateTables() { tableSQL = strings.Replace(tableSQL, "/*DB*/", database, -1) if _, err := db.Exec(tableSQL); err != nil { @@ -108,6 +112,17 @@ func newKeyValueFromJSONConfig(cfg jsonconfig.Obj) (sorted.KeyValue, error) { return kv, nil } +// CreateDB creates the named database if it does not already exist. +func CreateDB(db *sql.DB, dbname string) error { + if dbname == "" { + return errors.New("can not create database: database name is missing") + } + if _, err := db.Exec(fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s", dbname)); err != nil { + return fmt.Errorf("error creating database %v: %v", dbname, err) + } + return nil +} + // We keep a cache of open database handles. var ( dbsmu sync.Mutex