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"
|
|
|
|
|
|
|
|
goose "github.com/pressly/goose/v3"
|
|
|
|
"github.com/sirupsen/logrus"
|
2024-04-24 03:28:26 +00:00
|
|
|
_ "modernc.org/sqlite"
|
2024-04-09 04:25:36 +00:00
|
|
|
|
|
|
|
"git.janky.solutions/finn/lockserver/config"
|
|
|
|
)
|
|
|
|
|
2024-11-23 03:50:18 +00:00
|
|
|
const sqliteParams = "?_pragma=foreign_keys(1)&_time_format=sqlite"
|
|
|
|
|
2024-04-09 04:25:36 +00:00
|
|
|
func Get() (*Queries, *sql.DB, error) {
|
2024-11-23 03:50:18 +00:00
|
|
|
db, err := sql.Open("sqlite", config.C.SqliteDatabase+sqliteParams)
|
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...)
|
|
|
|
}
|