mysql: create database now distinct from create tables

Because we do not want the database name to be optional with a
placeholder (/*DB*/) in the statement that creates the database, since
it is not actually optional there - as opposed to when creating tables.

Change-Id: I05351d76d95071492d763758a11454f219524510
This commit is contained in:
mpl 2014-08-08 19:29:05 +02:00
parent 44ac2e4a3e
commit df7952b9ba
3 changed files with 20 additions and 4 deletions

View File

@ -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":

View File

@ -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))

View File

@ -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