Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixing #42, allows operation with less privileged user #43

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 28 additions & 9 deletions mysql/mysql.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -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.
Expand Down