diff --git a/mysql/mysql.go b/mysql/mysql.go index 0273491..0573198 100644 --- a/mysql/mysql.go +++ b/mysql/mysql.go @@ -44,10 +44,18 @@ func (db *DB) Open(dataSourceName string, opt ...database.Option) error { if err != nil { return errors.Wrap(err, "error connecting to mysql") } - _, err = _db.Exec(fmt.Sprintf("CREATE DATABASE IF NOT EXISTS `%s`", opts.Database)) - if err != nil { - return errors.Wrapf(err, "error creating database %s (if not exists)", opts.Database) + _db_check, err := _db.Query(fmt.Sprintf("SHOW DATABASES LIKE `%s`", opts.Database)) + if err != nil { + return errors.Wrapf(err, "error checking if database %s exists", opts.Database) + } + // db doesn't exist, create it + if !_db_check.Next() { + _, err = _db.Exec(fmt.Sprintf("CREATE DATABASE IF NOT EXISTS `%s`", opts.Database)) + if err != nil { + return errors.Wrapf(err, "error creating database %s (if not exists)", opts.Database) + } } + parsedDSN.DBName = opts.Database db.db, err = sql.Open("mysql", parsedDSN.FormatDSN()) if err != nil { @@ -82,6 +90,10 @@ func createTableQry(bucket []byte) string { return fmt.Sprintf("CREATE TABLE IF NOT EXISTS `%s`(nkey VARBINARY(255), nvalue BLOB, PRIMARY KEY (nkey));", bucket) } +func checkTableQry(bucket []byte) string { + return fmt.Sprintf("SHOW TABLES LIKE `%s`;", bucket) +} + func deleteTableQry(bucket []byte) string { return fmt.Sprintf("DROP TABLE `%s`", bucket) } @@ -259,13 +271,20 @@ func (db *DB) Update(tx *database.Tx) error { return nil } -// CreateTable creates a table in the database. -func (db *DB) CreateTable(bucket []byte) error { - _, err := db.db.Exec(createTableQry(bucket)) +// CreateTable creates a table in the database. +func (db *DB) CreateTable(bucket []byte) error { + _check, err := db.db.Query(checkTableQry(bucket)) if err != nil { - return errors.Wrapf(err, "failed to create table %s", bucket) - } - return nil + return errors.Wrapf(err, "failed to check table %s", bucket) + } + // table doesn't exist, create it + if !_check.Next() { + _, err := db.db.Exec(createTableQry(bucket)) + if err != nil { + return errors.Wrapf(err, "failed to create table %s", bucket) + } + } + return nil } // DeleteTable deletes a table in the database.