64 lines
2.4 KiB
Go
64 lines
2.4 KiB
Go
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"},
|
|
{"cars", "name", "TEXT"},
|
|
{"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
|
|
}
|