87 lines
1.9 KiB
Go
87 lines
1.9 KiB
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"embed"
|
|
|
|
goose "github.com/pressly/goose/v3"
|
|
"github.com/sirupsen/logrus"
|
|
_ "modernc.org/sqlite"
|
|
|
|
"git.janky.solutions/finn/lockserver/config"
|
|
)
|
|
|
|
func Get() (*Queries, *sql.DB, error) {
|
|
db, err := sql.Open("sqlite", config.C.SqliteDatabase)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
|
|
return New(db), db, nil
|
|
}
|
|
|
|
//go:embed migrations
|
|
var migrations embed.FS
|
|
|
|
func Migrate() error {
|
|
logrus.WithField("dbfile", config.C.SqliteDatabase).Info("migrating database")
|
|
|
|
_, conn, err := Get()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer conn.Close()
|
|
|
|
goose.SetBaseFS(migrations)
|
|
|
|
if err := goose.SetDialect("sqlite3"); err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := goose.Up(conn, "migrations"); err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func NullString(s string) sql.NullString {
|
|
return sql.NullString{
|
|
Valid: s != "",
|
|
String: s,
|
|
}
|
|
}
|
|
|
|
type loggingDBTX struct {
|
|
Next DBTX
|
|
}
|
|
|
|
func (l loggingDBTX) ExecContext(ctx context.Context, query string, params ...interface{}) (sql.Result, error) {
|
|
logrus.WithFields(logrus.Fields{
|
|
"query": query,
|
|
"params": params,
|
|
}).Debug("ExecContext")
|
|
return l.Next.ExecContext(ctx, query, params...)
|
|
}
|
|
|
|
func (l loggingDBTX) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) {
|
|
logrus.WithFields(logrus.Fields{
|
|
"query": query,
|
|
}).Debug("PrepareContext")
|
|
return l.Next.PrepareContext(ctx, query)
|
|
}
|
|
func (l loggingDBTX) QueryContext(ctx context.Context, query string, params ...interface{}) (*sql.Rows, error) {
|
|
logrus.WithFields(logrus.Fields{
|
|
"query": query,
|
|
"params": params,
|
|
}).Debug("QueryContext")
|
|
return l.Next.QueryContext(ctx, query, params...)
|
|
}
|
|
func (l loggingDBTX) QueryRowContext(ctx context.Context, query string, params ...interface{}) *sql.Row {
|
|
logrus.WithFields(logrus.Fields{
|
|
"query": query,
|
|
"params": params,
|
|
}).Debug("QueryRowContext")
|
|
return l.Next.QueryRowContext(ctx, query, params...)
|
|
}
|