Files
zeekay 3bb86da715 Add sdk/: the shared framework, from the private build
The code is the private build's sdk/ with the module path swapped and the
hostnames, private issue refs and incident prose taken out. Its self-contained
tests come with it; the framework's own tests need the private test kits and stay
behind. Builds and vets in this module; needs luxfi/kms v1.12.26.

Claude-Session: https://claude.ai/code/session_015XYKLn69gF4x75RWePpDBV
2026-11-20 20:25:04 -08:00

370 lines
15 KiB
Go

package dialect
import (
"context"
"database/sql"
"database/sql/driver"
"errors"
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"time"
)
// Dialect is one engine.
type Dialect struct{ postgres bool }
// servers holds the driver types that speak to a PostgreSQL server. The SDK links
// no server driver; the one that opens server handles names itself here, once.
var servers sync.Map // reflect.Type -> struct{}
// Server marks d's type as a PostgreSQL driver. Every handle on any other driver
// is SQLite, the SDK's own engine.
func Server(d driver.Driver) { servers.Store(reflect.TypeOf(d), struct{}{}) }
// Of is the engine db is on.
func Of(db *sql.DB) Dialect {
_, pg := servers.Load(reflect.TypeOf(db.Driver()))
return Dialect{postgres: pg}
}
// Postgres reports whether the engine is PostgreSQL.
func (d Dialect) Postgres() bool { return d.postgres }
// Identity is the column definition of a table's own integer id, assigned by the
// engine in insertion order: write `id ` + d.Identity() + `,`. BY DEFAULT on
// PostgreSQL, so a copy of existing rows (cmd/sqlmove) keeps the ids it read.
func (d Dialect) Identity() string {
if d.postgres {
return `BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY`
}
return `INTEGER PRIMARY KEY AUTOINCREMENT`
}
// JSON is the type of a column SQL looks inside with ->>. A document the store only
// reads back whole stays TEXT: jsonb normalises key order and spacing, and TEXT
// returns the bytes it was given.
func (d Dialect) JSON() string {
if d.postgres {
return `JSONB`
}
return `TEXT`
}
// Blob is the type of a column of raw bytes.
func (d Dialect) Blob() string {
if d.postgres {
return `BYTEA`
}
return `BLOB`
}
// Querier is the one read a *sql.DB and a *sql.Tx both answer.
type Querier interface {
QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
}
// HasColumn reports whether table has the column, in the schema the handle is on.
// It is how a migration adds a column once: neither engine's ALTER TABLE ADD
// COLUMN both skips an existing one and parses on the other.
func (d Dialect) HasColumn(ctx context.Context, q Querier, table, column string) (bool, error) {
query := `SELECT COUNT(*) FROM pragma_table_info($1) WHERE name = $2`
if d.postgres {
query = `SELECT COUNT(*) FROM information_schema.columns
WHERE table_schema = current_schema() AND table_name = $1 AND column_name = $2`
}
var n int
if err := q.QueryRowContext(ctx, query, table, column).Scan(&n); err != nil {
return false, err
}
return n > 0, nil
}
// BeginWrite starts a transaction that reads, then writes, and makes it the only
// writing transaction on its store until it ends.
//
// SQLite needs no help: a store's handle is pinned to one connection, so a second
// transaction waits at Begin. PostgreSQL pools several, and a read-modify-write
// (a balance read, checked, then written) would interleave and lose one update. The
// lock is per schema, so it serialises exactly what the file did, one store's
// writers, and nothing else. Reads outside a transaction never ask for it.
//
// The isolation level is stated, READ COMMITTED, rather than left to the server's
// default_transaction_isolation: the lock, not the level, is what makes the
// transaction safe, and a server configured otherwise would change what a store's
// tests proved. SQLite has one level and is asked for none.
func (d Dialect) BeginWrite(ctx context.Context, db *sql.DB) (*sql.Tx, error) {
if !d.postgres {
return db.BeginTx(ctx, nil)
}
tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelReadCommitted})
if err != nil {
return nil, err
}
if _, err := tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(hashtextextended(current_schema() || ':write', 0))`); err != nil {
_ = tx.Rollback()
return nil, err
}
return tx, nil
}
// Serialize is BeginWrite for a store whose writers contend per thing and not per
// store: it makes the transaction the only writing one for key until it ends, and
// transactions for other keys proceed. A singleton on a hot path (every request of
// every payer asks it) would otherwise queue them all behind one lock, and the
// slowest transaction would be the platform's latency. The key names what the
// transaction reads and writes, and every transaction that touches the same rows
// must name the same key; two keys that hash alike merely wait for each other.
//
// On SQLite it is BeginWrite: the store's one connection serialises everything,
// which is a stricter order than any key asks for.
func (d Dialect) Serialize(ctx context.Context, db *sql.DB, key string) (*sql.Tx, error) {
if !d.postgres {
return db.BeginTx(ctx, nil)
}
tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelReadCommitted})
if err != nil {
return nil, err
}
if _, err := tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(hashtextextended(current_schema() || ':write:' || $1, 0))`, key); err != nil {
_ = tx.Rollback()
return nil, err
}
return tx, nil
}
// LockWait is how long a caller waits for a lock another replica holds before it
// gives up: the holder of a lock that is gone drops its connection and frees it, so a
// wait this long is a fault to fail on, not a queue to stand in.
const LockWait = 30 * time.Second
// Held takes the lock begin takes (BeginWrite, Serialize) for as long as the caller's
// work lasts, and no longer than release says. Those begin a transaction on the
// context they are given, and database/sql rolls a transaction back when its context
// ends, so a request's own context would end the lock under work still running when a
// client goes away, and a context that is cancelled when the lock is taken would end
// it at once. Held gives begin a context of its own: the wait is abandoned when ctx
// ends or wait runs out (wait <= 0: only ctx bounds it), and once the lock is held
// nothing but release ends it. release commits the transaction, which is how the work
// done through tx lands, and answers why it did not.
func Held(ctx context.Context, wait time.Duration, begin func(context.Context) (*sql.Tx, error)) (tx *sql.Tx, release func() error, err error) {
held, end := context.WithCancel(context.WithoutCancel(ctx))
live := context.AfterFunc(ctx, end)
var timer *time.Timer
if wait > 0 {
timer = time.AfterFunc(wait, end)
}
tx, err = begin(held)
ok := live() // false: ctx ended while the lock was being waited for
if timer != nil {
ok = timer.Stop() && ok // false: so did the wait
}
if err == nil && !ok {
_ = tx.Rollback()
if err = ctx.Err(); err == nil {
err = context.DeadlineExceeded
}
}
if err != nil {
end()
return nil, nil, err
}
return tx, func() error { err := tx.Commit(); end(); return err }, nil
}
// Migrate runs fn, a store's migration, in one transaction that holds the store's
// migration lock, so two replicas opening one store do not run its DDL at once:
// CREATE TABLE IF NOT EXISTS is not safe against itself on PostgreSQL, and two pods
// starting together is how a store is first opened. SQLite takes no lock (a file has
// one opener) and runs fn in a transaction all the same, so a migration is atomic on
// both.
//
// FN RUNS ON THE CONNECTION THAT HOLDS THE LOCK, and everything it does goes through
// tx. A migration that took the lock on one connection and ran its DDL on another
// would need two slots of the process's connection budget to make progress, and a
// storm of first opens would each take one and wait forever for the second. It also
// could not run at all on SQLite, whose one connection tx already holds. The lock is
// the transaction's own (pg_advisory_xact_lock), released by commit or rollback with
// nothing to forget; a caller waiting for it waits inside the transaction, holding
// one slot, behind a holder that needs no more.
func (d Dialect) Migrate(ctx context.Context, db *sql.DB, fn func(tx *sql.Tx) error) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer func() { _ = tx.Rollback() }()
if d.postgres {
if _, err := tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(hashtextextended(current_schema() || ':migrate', 0))`); err != nil {
return err
}
}
if err := fn(tx); err != nil {
return err
}
return tx.Commit()
}
// Unique reports whether err is an insert or update refused by a UNIQUE or PRIMARY KEY
// constraint, on either engine: PostgreSQL's 23505, or SQLite's "UNIQUE constraint
// failed". It is how a store tells a name already taken from a fault, where the driver
// error is the only place the engine says so.
func Unique(err error) bool {
if err == nil {
return false
}
// A server error states its SQLSTATE; 23505 is unique_violation.
var pg interface{ SQLState() string }
if errors.As(err, &pg) {
return pg.SQLState() == "23505"
}
return strings.Contains(err.Error(), "UNIQUE constraint failed")
}
// Args collects the arguments of a statement whose text is written in pieces, and
// names each as it is added: Mark appends a value and answers the $n that stands for
// it, so the numbers rise in the order the text is written, which is the one numbering
// both engines read alike. Values are what the statement is executed with.
type Args struct{ vals []any }
// Mark adds v and answers its placeholder.
func (a *Args) Mark(v any) string {
a.vals = append(a.vals, v)
return "$" + strconv.Itoa(len(a.vals))
}
// Values are the arguments added so far, in the order of their marks.
func (a *Args) Values() []any { return a.vals }
// Refuse makes table refuse a change to its rows: a trigger called name, before every
// event (UPDATE or DELETE) on a row where when holds, that fails the statement with
// message. when is a boolean expression over OLD and NEW in the spelling both engines
// read (`IS DISTINCT FROM`, `IN`), or empty for every row. It is how a table of records
// is kept from being rewritten by a statement nothing else guards, and it does nothing
// when the trigger is already there, so it can be made on every open.
//
// message is put inside quotes: it holds no quote and no percent sign.
func (d Dialect) Refuse(ctx context.Context, tx *sql.Tx, name, table, event, when, message string) error {
if !identifier.MatchString(name) || !identifier.MatchString(table) || (event != "UPDATE" && event != "DELETE") ||
strings.ContainsAny(message, "'%") {
return fmt.Errorf("dialect: cannot refuse %s on %s with %q", event, table, message)
}
if when != "" {
when = " WHEN (" + when + ")"
}
if !d.postgres {
_, err := tx.ExecContext(ctx, `CREATE TRIGGER IF NOT EXISTS `+name+` BEFORE `+event+` ON `+table+when+
` BEGIN SELECT RAISE(ABORT, '`+message+`'); END`)
return err
}
if _, err := tx.ExecContext(ctx, `CREATE OR REPLACE FUNCTION refusal() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN RAISE EXCEPTION '%', TG_ARGV[0]; END
$$`); err != nil {
return err
}
var n int
if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM pg_trigger WHERE tgrelid = $1::regclass AND tgname = $2`, table, name).Scan(&n); err != nil {
return err
}
if n > 0 {
return nil
}
_, err := tx.ExecContext(ctx, `CREATE TRIGGER `+name+` BEFORE `+event+` ON `+table+` FOR EACH ROW`+when+
` EXECUTE FUNCTION refusal('`+message+`')`)
return err
}
// Sequence gives table the seq column its rows are listed in the order they were
// written by. A file ordered them by rowid, which a server has no spelling of and a
// copy of the rows does not keep, so the order is a column the store numbers itself
// (NextSeq) as it writes. A table that has none gains the column, and a file's rows are
// numbered by rowid, once; rows already numbered are not touched, so it can run on every
// open. A table with a trigger that refuses UPDATE must have it lifted around the call.
func (d Dialect) Sequence(ctx context.Context, tx *sql.Tx, table string) error {
if !identifier.MatchString(table) {
return fmt.Errorf("dialect: %q is not a plain identifier", table)
}
have, err := d.HasColumn(ctx, tx, table, "seq")
if err != nil {
return err
}
if !have {
if _, err := tx.ExecContext(ctx, `ALTER TABLE `+table+` ADD COLUMN seq BIGINT NOT NULL DEFAULT 0`); err != nil {
return err
}
}
if d.postgres {
return nil
}
_, err = tx.ExecContext(ctx, `UPDATE `+table+` SET seq = rowid WHERE seq = 0`)
return err
}
// NextSeq is the expression for the number a new row of table takes in its seq column:
// one past the largest. The writer starts with BeginWrite, so no other writer takes
// the same number.
func NextSeq(table string) string {
return `(SELECT COALESCE(MAX(seq), 0) + 1 FROM ` + table + `)`
}
// Marks is the placeholders $first ... $first+n-1, comma separated, for an IN list:
// Marks(2, 3) is "$2,$3,$4". SQLite numbers $n by first appearance rather than by
// n, so the numbers in a statement must rise in the order they are written.
func Marks(first, n int) string {
var b strings.Builder
for i := range n {
if i > 0 {
b.WriteByte(',')
}
b.WriteByte('$')
b.WriteString(strconv.Itoa(first + i))
}
return b.String()
}
// Resync moves an identity column's next value past the largest id in the table.
//
// A copy of existing rows (cmd/sqlmove) inserts explicit ids, which the identity
// does not see, so the first insert after it would take id 1 and collide.
// cmd/sqlmove calls Resync for every table whose id column is Identity() once
// its rows are in. SQLite's AUTOINCREMENT follows explicit ids by itself and is
// asked for nothing. An empty table's next id is 1.
//
// A column with no sequence behind it is an error and not a quiet no-op: the call
// was made because someone believed the column was an identity, and a copy that
// then collides on its first insert is found by the customer instead.
func (d Dialect) Resync(ctx context.Context, db *sql.DB, table, column string) error {
if !named.MatchString(table) || !named.MatchString(column) {
return fmt.Errorf("dialect: %q.%q is not a plain identifier", table, column)
}
if !d.postgres {
// AUTOINCREMENT follows explicit ids by itself and there is nothing to move, but a
// table or column that is not there is still a call that was made in error.
ok, err := d.HasColumn(ctx, db, table, column)
if err != nil {
return err
}
if !ok {
return fmt.Errorf("dialect: %s.%s does not exist", table, column)
}
return nil
}
var seq sql.NullString
if err := db.QueryRowContext(ctx, `SELECT pg_get_serial_sequence($1, $2)`, `"`+table+`"`, column).Scan(&seq); err != nil {
return err
}
if !seq.Valid {
return fmt.Errorf("dialect: %s.%s has no sequence, so it is not an Identity() column and there is nothing to resync", table, column)
}
_, err := db.ExecContext(ctx, `SELECT setval($1::text::regclass, COALESCE(MAX("`+column+`"), 0) + 1, false) FROM "`+table+`"`, seq.String)
return err
}
var identifier = regexp.MustCompile(`^[a-z_][a-z0-9_]*$`)
// named is an identifier a module chose and a copy has to keep as it was spelled: a Base
// collection is camelCase, which PostgreSQL holds only quoted.
var named = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)