Initial commit
This commit is contained in:
commit
b6014c6ffc
47 files changed
+4329
No files matched your search
@@ -0,0 +1,99 @@
|
||||
// Package db wraps the DB connection and applies the schema on startup so
|
||||
// there's no separate migrate step for the operator to remember. Supports
|
||||
// Postgres (production) and SQLite (local dev/testing without a real
|
||||
// Postgres instance) via DB_DRIVER.
|
||||
package db
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/golang-migrate/migrate/v4"
|
||||
"github.com/golang-migrate/migrate/v4/database/postgres"
|
||||
"github.com/golang-migrate/migrate/v4/source/iofs"
|
||||
"github.com/jmoiron/sqlx"
|
||||
|
||||
_ "github.com/lib/pq" // postgres driver
|
||||
_ "modernc.org/sqlite" // pure-Go sqlite driver, no CGO
|
||||
|
||||
"vlog/migrations"
|
||||
)
|
||||
|
||||
// Connect opens the DB connection for the given driver ("postgres" or
|
||||
// "sqlite") and applies the schema.
|
||||
func Connect(driver, databaseURL string) (*sqlx.DB, error) {
|
||||
switch driver {
|
||||
case "postgres":
|
||||
return connectPostgres(databaseURL)
|
||||
case "sqlite":
|
||||
return connectSQLite(databaseURL)
|
||||
default:
|
||||
return nil, fmt.Errorf("invalid DB_DRIVER %q (must be postgres or sqlite)", driver)
|
||||
}
|
||||
}
|
||||
|
||||
func connectPostgres(databaseURL string) (*sqlx.DB, error) {
|
||||
conn, err := sqlx.Connect("postgres", databaseURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("connect to postgres: %w", err)
|
||||
}
|
||||
|
||||
sourceDriver, err := iofs.New(migrations.PostgresFS, "postgres")
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
return nil, fmt.Errorf("load embedded migrations: %w", err)
|
||||
}
|
||||
dbDriver, err := postgres.WithInstance(conn.DB, &postgres.Config{})
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
return nil, fmt.Errorf("init postgres migrate driver: %w", err)
|
||||
}
|
||||
m, err := migrate.NewWithInstance("iofs", sourceDriver, "postgres", dbDriver)
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
return nil, fmt.Errorf("init migrate instance: %w", err)
|
||||
}
|
||||
if err := m.Up(); err != nil && err != migrate.ErrNoChange {
|
||||
conn.Close()
|
||||
return nil, fmt.Errorf("run migrations: %w", err)
|
||||
}
|
||||
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
// connectSQLite treats databaseURL as a filesystem path to the DB file
|
||||
// (e.g. "./data/vlog.db"). The schema is applied idempotently on every
|
||||
// startup rather than through golang-migrate — see migrations/sqlite/schema.sql.
|
||||
func connectSQLite(path string) (*sqlx.DB, error) {
|
||||
if dir := filepath.Dir(path); dir != "." && dir != "" {
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return nil, fmt.Errorf("create sqlite db directory: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
conn, err := sqlx.Connect("sqlite", path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("connect to sqlite: %w", err)
|
||||
}
|
||||
|
||||
// SQLite handles one writer at a time anyway; capping the pool at a
|
||||
// single connection sidesteps per-connection PRAGMA/locking headaches
|
||||
// entirely. Fine for the local dev/testing use case this is for.
|
||||
conn.SetMaxOpenConns(1)
|
||||
|
||||
if _, err := conn.Exec(`PRAGMA foreign_keys = ON`); err != nil {
|
||||
conn.Close()
|
||||
return nil, fmt.Errorf("enable sqlite foreign keys: %w", err)
|
||||
}
|
||||
if _, err := conn.Exec(migrations.SQLiteSchemaSQL); err != nil {
|
||||
conn.Close()
|
||||
return nil, fmt.Errorf("apply sqlite schema: %w", err)
|
||||
}
|
||||
if err := ensureSQLiteColumns(conn); err != nil {
|
||||
conn.Close()
|
||||
return nil, fmt.Errorf("apply sqlite column additions: %w", err)
|
||||
}
|
||||
|
||||
return conn, nil
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/jmoiron/sqlx"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
// TestSQLiteAddsMissingColumns simulates exactly the bug a user hit: an
|
||||
// existing local .db file created before share_token/service_interval_*/
|
||||
// is_service existed. Connect must add them in place, not require deleting
|
||||
// the file. The "old" schema is hand-built (not via schema.sql, which
|
||||
// already has the new columns) so CREATE TABLE IF NOT EXISTS in the real
|
||||
// connectSQLite is a genuine no-op against it, same as it would be against
|
||||
// a real pre-existing file.
|
||||
func TestSQLiteAddsMissingColumns(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "old.db")
|
||||
|
||||
oldConn, err := sqlx.Connect("sqlite", path)
|
||||
if err != nil {
|
||||
t.Fatalf("open old-style db: %v", err)
|
||||
}
|
||||
for _, stmt := range []string{
|
||||
`CREATE TABLE users (id TEXT PRIMARY KEY, oidc_sub TEXT NOT NULL UNIQUE, email TEXT NOT NULL, name TEXT, created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP)`,
|
||||
`CREATE TABLE cars (id TEXT PRIMARY KEY, user_id TEXT NOT NULL, rego TEXT NOT NULL, odometer INTEGER, created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP)`,
|
||||
`CREATE TABLE service_entries (id TEXT PRIMARY KEY, car_id TEXT NOT NULL, entry_date DATE NOT NULL, entry_type TEXT NOT NULL, odometer INTEGER, created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP)`,
|
||||
} {
|
||||
if _, err := oldConn.Exec(stmt); err != nil {
|
||||
t.Fatalf("build old-style schema (%s): %v", stmt, err)
|
||||
}
|
||||
}
|
||||
oldConn.Close()
|
||||
|
||||
// Reconnecting through the real path (as a fresh app start would) must
|
||||
// backfill the missing columns without erroring and without the
|
||||
// caller/operator doing anything special.
|
||||
conn, err := connectSQLite(path)
|
||||
if err != nil {
|
||||
t.Fatalf("connect against old-style schema: %v", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
if _, err := conn.Exec(`INSERT INTO cars (id, user_id, rego, service_interval_km) VALUES ('c1', 'u1', 'ABC123', 10000)`); err != nil {
|
||||
t.Fatalf("insert using backfilled column: %v", err)
|
||||
}
|
||||
if _, err := conn.Exec(`UPDATE cars SET share_token = 'tok1' WHERE id = 'c1'`); err != nil {
|
||||
t.Fatalf("update using backfilled share_token column: %v", err)
|
||||
}
|
||||
var count int
|
||||
if err := conn.Get(&count, `SELECT COUNT(*) FROM cars WHERE share_token = 'tok1'`); err != nil || count != 1 {
|
||||
t.Fatalf("expected to find the row by its backfilled share_token, err=%v count=%d", err, count)
|
||||
}
|
||||
|
||||
// The share_token uniqueness constraint must actually be enforced, not
|
||||
// just present as an unconstrained column.
|
||||
if _, err := conn.Exec(`INSERT INTO cars (id, user_id, rego, share_token) VALUES ('c2', 'u1', 'XYZ789', 'tok1')`); err == nil {
|
||||
t.Fatal("expected duplicate share_token to be rejected")
|
||||
}
|
||||
|
||||
if _, err := conn.Exec(`INSERT INTO service_entries (id, car_id, entry_date, entry_type, is_service) VALUES ('e1', 'c1', '2026-01-01', 'Service', 1)`); err != nil {
|
||||
t.Fatalf("insert using backfilled is_service column: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/jmoiron/sqlx"
|
||||
)
|
||||
|
||||
// sqliteColumnAdditions lists every column added to a pre-existing table
|
||||
// since schema.sql's original CREATE TABLE statements. CREATE TABLE IF NOT
|
||||
// EXISTS is a no-op against a table that already exists, so an existing
|
||||
// local .db file never picks up new columns just by editing schema.sql —
|
||||
// this applies them the same way a real migration would, without requiring
|
||||
// the developer to delete and recreate their local dev database every time
|
||||
// the schema grows during active development.
|
||||
var sqliteColumnAdditions = []struct {
|
||||
table string
|
||||
column string
|
||||
ddl string // type + constraints, everything after the column name
|
||||
}{
|
||||
{"cars", "share_token", "TEXT"},
|
||||
{"cars", "service_interval_km", "INTEGER"},
|
||||
{"cars", "service_interval_months", "INTEGER"},
|
||||
{"service_entries", "is_service", "BOOLEAN NOT NULL DEFAULT 0"},
|
||||
}
|
||||
|
||||
// ensureSQLiteColumns adds any missing columns from the list above, and
|
||||
// (re)creates the share_token uniqueness index — SQLite's ALTER TABLE ADD
|
||||
// COLUMN can't declare UNIQUE inline, so that's a separate CREATE UNIQUE
|
||||
// INDEX IF NOT EXISTS, safe to run every time regardless of whether the
|
||||
// column was just added or already existed.
|
||||
func ensureSQLiteColumns(conn *sqlx.DB) error {
|
||||
for _, c := range sqliteColumnAdditions {
|
||||
var existing []string
|
||||
// pragma_table_info as a table-valued function (not the bare PRAGMA
|
||||
// statement) so this is a normal SELECT we can project down to just
|
||||
// the column we need — the bare PRAGMA form always returns every
|
||||
// column (cid, name, type, ...), which sqlx's strict struct scan
|
||||
// rejects unless every one of them has a matching destination field.
|
||||
if err := conn.Select(&existing, `SELECT name FROM pragma_table_info(?)`, c.table); err != nil {
|
||||
return fmt.Errorf("inspect %s columns: %w", c.table, err)
|
||||
}
|
||||
found := false
|
||||
for _, name := range existing {
|
||||
if name == c.column {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
if _, err := conn.Exec(fmt.Sprintf(`ALTER TABLE %s ADD COLUMN %s %s`, c.table, c.column, c.ddl)); err != nil {
|
||||
return fmt.Errorf("add column %s.%s: %w", c.table, c.column, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := conn.Exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_cars_share_token ON cars(share_token)`); err != nil {
|
||||
return fmt.Errorf("create share_token index: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
Reference in new issue
Block a user