lockserver/db/helpers.go

91 lines
2 KiB
Go
Raw Normal View History

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"
)
2024-11-23 03:50:18 +00:00
const sqliteParams = "?_pragma=foreign_keys(1)&_time_format=sqlite"
func Get() (*Queries, *sql.DB, error) {
2024-11-23 03:50:18 +00:00
db, err := sql.Open("sqlite", config.C.SqliteDatabase+sqliteParams)
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 {
2024-11-25 00:08:06 +00:00
return sql.NullString{Valid: s != "", String: s}
}
func NullInt64(i int64) sql.NullInt64 {
return sql.NullInt64{Valid: true, Int64: i}
}
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...)
}