2024-04-09 04:25:36 +00:00
|
|
|
package db
|
|
|
|
|
|
|
|
import (
|
2024-04-24 00:34:57 +00:00
|
|
|
"context"
|
2024-04-09 04:25:36 +00:00
|
|
|
"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) {
|
2024-04-24 00:34:57 +00:00
|
|
|
db, err := sql.Open("sqlite3", config.C.SqliteDatabase)
|
2024-04-09 04:25:36 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return New(db), db, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
//go:embed migrations
|
|
|
|
var migrations embed.FS
|
|
|
|
|
|
|
|
func Migrate() error {
|
2024-04-24 00:34:57 +00:00
|
|
|
logrus.WithField("dbfile", config.C.SqliteDatabase).Info("migrating database")
|
2024-04-09 04:25:36 +00:00
|
|
|
|
|
|
|
_, 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,
|
|
|
|
}
|
|
|
|
}
|
2024-04-24 00:34:57 +00:00
|
|
|
|
|
|
|
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...)
|
|
|
|
}
|