// Package db is the data layer. SQLite and Postgres share one schema and // one set of queries; the few places where they differ go through Dialect. package db import ( "context" "database/sql" "embed" "errors" "fmt" "io/fs" "net/url" "os" "path/filepath" "strconv" "strings" "time" "github.com/pressly/goose/v3" _ "modernc.org/sqlite" // registers the "sqlite" driver ) //go:embed migrations/*.sql var migrationsFS embed.FS // Dialect names a SQL backend. type Dialect string // The supported dialects. const ( SQLite Dialect = "sqlite" Postgres Dialect = "postgres" ) // ErrNotFound is returned when a row does not exist. var ErrNotFound = errors.New("db: not found") // DB is an open database. type DB struct { SQL *sql.DB Dialect Dialect } // Open connects to the database named by driver ("sqlite" or "postgres"). // For sqlite the DSN is a file path. func Open(ctx context.Context, driver, dsn string) (*DB, error) { switch Dialect(driver) { case SQLite: return openSQLite(ctx, dsn) case Postgres: return openPostgres(ctx, dsn) } return nil, fmt.Errorf("db: unknown driver %q", driver) } func openSQLite(ctx context.Context, path string) (*DB, error) { if path == "" { return nil, errors.New("db: sqlite needs a file path") } if dir := filepath.Dir(path); dir != "." { if err := os.MkdirAll(dir, 0o750); err != nil { return nil, err } } q := url.Values{} q.Add("_pragma", "busy_timeout(10000)") q.Add("_pragma", "journal_mode(WAL)") q.Add("_pragma", "synchronous(NORMAL)") q.Add("_pragma", "foreign_keys(1)") // Every transaction takes the write lock up front. This is what makes // job claiming atomic on SQLite and avoids lock upgrade deadlocks. q.Set("_txlock", "immediate") sqldb, err := sql.Open("sqlite", "file:"+path+"?"+q.Encode()) if err != nil { return nil, err } sqldb.SetMaxOpenConns(4) sqldb.SetMaxIdleConns(4) if err := sqldb.PingContext(ctx); err != nil { sqldb.Close() return nil, fmt.Errorf("db: open sqlite %s: %w", path, err) } return &DB{SQL: sqldb, Dialect: SQLite}, nil } // Close closes the pool. func (d *DB) Close() error { return d.SQL.Close() } // Migrate applies all pending migrations. func (d *DB) Migrate(ctx context.Context) error { sub, err := fs.Sub(migrationsFS, "migrations") if err != nil { return err } dialect := goose.DialectSQLite3 if d.Dialect == Postgres { dialect = goose.DialectPostgres } p, err := goose.NewProvider(dialect, d.SQL, sub) if err != nil { return fmt.Errorf("db: migrations: %w", err) } if _, err := p.Up(ctx); err != nil { return fmt.Errorf("db: migrate: %w", err) } return nil } // querier is satisfied by *sql.DB and *sql.Tx. type querier interface { ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row } // Store runs queries, either on the pool or inside a transaction. type Store struct { db *DB q querier inTx bool } // Store returns a Store that runs each query on the pool. func (d *DB) Store() *Store { return &Store{db: d, q: d.SQL} } // Dialect returns the dialect of the underlying database. func (s *Store) Dialect() Dialect { return s.db.Dialect } // InTx runs fn in a transaction. Nested calls reuse the outer transaction. // On SQLite the transaction holds the write lock from the start. func (s *Store) InTx(ctx context.Context, fn func(tx *Store) error) error { if s.inTx { return fn(s) } tx, err := s.db.SQL.BeginTx(ctx, nil) if err != nil { return err } if err := fn(&Store{db: s.db, q: tx, inTx: true}); err != nil { _ = tx.Rollback() return err } return tx.Commit() } // Rebind turns "?" placeholders into the form the database expects. Code // outside this package that runs its own SQL, mostly tests, uses it to stay // portable. func (d *DB) Rebind(query string) string { return (&Store{db: d}).rebind(query) } // rebind turns "?" placeholders into "$1, $2, ..." for Postgres. func (s *Store) rebind(query string) string { if s.db.Dialect != Postgres { return query } var b strings.Builder b.Grow(len(query) + 8) n := 0 for i := 0; i < len(query); i++ { if query[i] == '?' { n++ b.WriteByte('$') b.WriteString(strconv.Itoa(n)) continue } b.WriteByte(query[i]) } return b.String() } func (s *Store) exec(ctx context.Context, query string, args ...any) (int64, error) { res, err := s.q.ExecContext(ctx, s.rebind(query), args...) if err != nil { return 0, err } return res.RowsAffected() } func (s *Store) row(ctx context.Context, query string, args ...any) *sql.Row { return s.q.QueryRowContext(ctx, s.rebind(query), args...) } func (s *Store) rows(ctx context.Context, query string, args ...any) (*sql.Rows, error) { return s.q.QueryContext(ctx, s.rebind(query), args...) } // NowMilli is the timestamp format used in every table. func NowMilli() int64 { return time.Now().UnixMilli() } func notFound(err error) error { if errors.Is(err, sql.ErrNoRows) { return ErrNotFound } return err } // in builds "?, ?, ?" and the matching argument list. func in[T any](vals []T) (string, []any) { args := make([]any, len(vals)) for i, v := range vals { args[i] = v } return strings.TrimSuffix(strings.Repeat("?, ", len(vals)), ", "), args }