check schema and table before create it (#3716)
This commit is contained in:
parent
7e033efa4c
commit
d68cc66954
|
@ -100,17 +100,40 @@ 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 !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.
|
||||
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.
|
||||
m := &MySQLBackend{
|
||||
|
|
Loading…
Reference in a new issue