Skip to content

Commit

Permalink
feat: add db existence check (openware#56)
Browse files Browse the repository at this point in the history
  • Loading branch information
dimast-x authored Apr 4, 2022
1 parent 7bf218e commit 086be9f
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
2 changes: 2 additions & 0 deletions pkg/storage/sql/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ module github.com/openware/kaigara/pkg/storage/sql
go 1.14

require (
github.com/go-sql-driver/mysql v1.6.0 // indirect
github.com/lib/pq v1.10.2 // indirect
github.com/openware/kaigara/pkg/encryptor v0.0.0-20220225091359-d368f0dfe8db
github.com/openware/pkg v0.0.0-20220225074124-ddad5f429a07
github.com/stretchr/testify v1.7.0
Expand Down
49 changes: 49 additions & 0 deletions pkg/storage/sql/sql.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
package sql

import (
"database/sql"
"encoding/json"
"errors"
"fmt"

_ "github.com/go-sql-driver/mysql"
_ "github.com/lib/pq"
"github.com/openware/kaigara/pkg/encryptor/types"
"github.com/openware/pkg/database"
"gorm.io/datatypes"
Expand All @@ -31,6 +34,10 @@ type Data struct {

func NewStorageService(deploymentID string, cnf *database.Config, encryptor types.Encryptor, logLevel logger.LogLevel) (*StorageService, error) {
cnf.Name = "kaigara_" + deploymentID
if err := ensureDatabaseExists(cnf); err != nil {
return nil, err
}

db, err := database.Connect(cnf)
if err != nil {
return nil, err
Expand All @@ -49,6 +56,48 @@ func NewStorageService(deploymentID string, cnf *database.Config, encryptor type
}, nil
}

func ensureDatabaseExists(cnf *database.Config) error {
switch cnf.Driver {
case "mysql":
dsn := fmt.Sprintf(
"%s:%s@tcp(%s:%s)/?charset=utf8&parseTime=True&loc=Local",
cnf.User, cnf.Pass, cnf.Host, cnf.Port,
)
conn, err := sql.Open(cnf.Driver, dsn)
if err != nil {
return err
}
defer conn.Close()
if _, err = conn.Exec("CREATE DATABASE IF NOT EXISTS " + cnf.Name); err != nil {
return err
}
case "postgres":
dsn := fmt.Sprintf(
"user=%s password=%s host=%s port=%s sslmode=disable",
cnf.User, cnf.Pass, cnf.Host, cnf.Port,
)
conn, err := sql.Open(cnf.Driver, dsn)
if err != nil {
return err
}
defer conn.Close()
if res, err := conn.Exec(fmt.Sprintf("SELECT 1 FROM pg_database WHERE datname='%s'", cnf.Name)); err != nil {
return err
} else if rows, err := res.RowsAffected(); err != nil {
return err
} else if rows > 0 {
return nil
}
if _, err = conn.Exec("CREATE DATABASE " + cnf.Name); err != nil {
return err
}
default:
return fmt.Errorf("unsupported database driver: %s", cnf.Driver)
}

return nil
}

func (ss *StorageService) Read(appName, scope string) error {
var data Data
res := ss.db.First(&data, "app_name = ? AND scope = ?", appName, scope)
Expand Down

0 comments on commit 086be9f

Please sign in to comment.