Skip to content

Commit

Permalink
check schema and table before create it (#3716)
Browse files Browse the repository at this point in the history
  • Loading branch information
antergone authored and jefferai committed Dec 19, 2017
1 parent 8c4f369 commit ccf10f6
Showing 1 changed file with 29 additions and 6 deletions.
35 changes: 29 additions & 6 deletions physical/mysql/mysql.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,16 +100,39 @@ func NewMySQLBackend(conf map[string]string, logger log.Logger) (physical.Backen

db.SetMaxOpenConns(maxParInt)

// Check schema exists
var schemaExist bool
schemaRows, err := db.Query("SELECT SCHEMA_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME = ?", database)
if err != nil {
return nil, fmt.Errorf("failed to check mysql schema exist: %v", err)
}
defer schemaRows.Close()
schemaExist = schemaRows.Next()

// Check table exists
var tableExist bool
tableRows, err := db.Query("SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", table, database)

if err != nil {
return nil, fmt.Errorf("failed to check mysql table exist: %v", err)
}
defer tableRows.Close()
tableExist = tableRows.Next()

// Create the required database if it doesn't exists.
if _, err := db.Exec("CREATE DATABASE IF NOT EXISTS " + database); err != nil {
return nil, fmt.Errorf("failed to create mysql database: %v", err)
if !schemaExist {
if _, err := db.Exec("CREATE DATABASE IF NOT EXISTS " + database); err != nil {
return nil, fmt.Errorf("failed to create mysql database: %v", err)
}
}

// Create the required table if it doesn't exists.
create_query := "CREATE TABLE IF NOT EXISTS " + dbTable +
" (vault_key varbinary(512), vault_value mediumblob, PRIMARY KEY (vault_key))"
if _, err := db.Exec(create_query); err != nil {
return nil, fmt.Errorf("failed to create mysql table: %v", err)
if !tableExist {
create_query := "CREATE TABLE IF NOT EXISTS " + dbTable +
" (vault_key varbinary(512), vault_value mediumblob, PRIMARY KEY (vault_key))"
if _, err := db.Exec(create_query); err != nil {
return nil, fmt.Errorf("failed to create mysql table: %v", err)
}
}

// Setup the backend.
Expand Down

0 comments on commit ccf10f6

Please sign in to comment.