lockserver/db/helpers.go
Finn 350fc3b339
All checks were successful
/ build-container (push) Successful in 1m3s
rip out all auth stuff, add a containerfile
2024-04-23 17:34:57 -07:00

87 lines
1.9 KiB
Go

package db
import (
"context"
"database/sql"
"embed"
_ "github.com/mattn/go-sqlite3"
goose "github.com/pressly/goose/v3"
"github.com/sirupsen/logrus"
"git.janky.solutions/finn/lockserver/config"
)
func Get() (*Queries, *sql.DB, error) {
db, err := sql.Open("sqlite3", 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...)
}