all good
This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"embed"
|
||||
"errors"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
|
||||
"github.com/pressly/goose/v3"
|
||||
)
|
||||
|
||||
type DatabaseClient struct {
|
||||
DB *sql.DB
|
||||
Queries *Queries
|
||||
}
|
||||
|
||||
// content holds migrations files ( embeded into the go program )
|
||||
//
|
||||
//go:embed migrations/*
|
||||
var embedMigrations embed.FS
|
||||
|
||||
type NewDatabaseParams struct {
|
||||
DatabaseName *string
|
||||
}
|
||||
|
||||
func NewDatabase(params NewDatabaseParams) (error, *DatabaseClient) {
|
||||
|
||||
databaseName := "database"
|
||||
|
||||
if params.DatabaseName != nil {
|
||||
databaseName = *params.DatabaseName
|
||||
}
|
||||
|
||||
err, normalizedDatabaseName := normalizeDatabaseName(databaseName)
|
||||
if err != nil {
|
||||
return err, nil
|
||||
}
|
||||
|
||||
db, err := sql.Open("sqlite", "./"+normalizedDatabaseName+".db")
|
||||
if err != nil {
|
||||
return err, nil
|
||||
}
|
||||
// setup database
|
||||
|
||||
goose.SetBaseFS(embedMigrations)
|
||||
|
||||
if err := goose.SetDialect("sqlite3"); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
if err := goose.Up(db, "migrations"); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return nil, &DatabaseClient{
|
||||
DB: db,
|
||||
Queries: New(db),
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func normalizeDatabaseName(databaseName string) (error, string) {
|
||||
|
||||
t := strings.TrimSpace(databaseName)
|
||||
|
||||
l := strings.ToLower(t)
|
||||
|
||||
pattern := "[a-zA-Z]+"
|
||||
|
||||
re, err := regexp.Compile(pattern)
|
||||
|
||||
if err != nil {
|
||||
return err, ""
|
||||
}
|
||||
|
||||
s := re.MatchString(l)
|
||||
|
||||
if s == false {
|
||||
return errors.New(databaseName + " doesn't follow the pattern " + pattern), ""
|
||||
}
|
||||
|
||||
return nil, l
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user