From 859ff8558221f7fb7af7d2a4a9f2db7df3b219e8 Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Fri, 20 Nov 2026 22:58:06 -0500 Subject: [PATCH 01/10] harness.adoption: sqlate upgrade mise-action moves to v5.2.10 and the development and integration PostgreSQL to 19.0-alpine; the quick start names PostgreSQL 19 and shows the new FROM line. mise run acceptance passes on 19 after a db:reset of the old volume. No CHANGELOG line: no go.mod requirement changes. --- .github/workflows/ci.yml | 2 +- compose/postgres/Dockerfile | 2 +- docs/quick-start.md | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 31c18a4..fd7b5e5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -12,7 +12,7 @@ jobs: steps: - uses: actions/checkout@v7.0.1 - - uses: jdx/mise-action@v5.2.9 + - uses: jdx/mise-action@v5.2.10 - name: mise run check run: mise run check diff --git a/compose/postgres/Dockerfile b/compose/postgres/Dockerfile index 80f88d7..2285d9b 100644 --- a/compose/postgres/Dockerfile +++ b/compose/postgres/Dockerfile @@ -1,6 +1,6 @@ # The development stack's PostgreSQL: the database the integration tier # connects to through SQLATE_DSN. This FROM line is PostgreSQL's one pin. -FROM postgres:18.7-alpine +FROM postgres:19.0-alpine # The user, password, and database SQLATE_DSN names; development values, not # secrets. diff --git a/docs/quick-start.md b/docs/quick-start.md index 024ae8f..30c7499 100644 --- a/docs/quick-start.md +++ b/docs/quick-start.md @@ -12,7 +12,7 @@ A tutorial that builds a working program from an empty directory: The library is used on its own, over a plain `*sql.DB`. Every file is written in full at the step that needs it, and every block is taken from a program -that compiles, runs against PostgreSQL 18, and passes its tests. The [concepts](concepts.md) +that compiles, runs against PostgreSQL 19, and passes its tests. The [concepts](concepts.md) document explains the grammar the files use, and the [features](features.md) document explains each mechanism. @@ -76,14 +76,14 @@ mise trust && mise install ## 2. Start PostgreSQL -`compose/postgres/Dockerfile` builds PostgreSQL 18 with the user, password, and database the +`compose/postgres/Dockerfile` builds PostgreSQL 19 with the user, password, and database the connection string names, and a health check the `db:up` task waits on. Its `FROM` line is the image's one pin. `compose/postgres/Dockerfile`: ```dockerfile -FROM postgres:18.7-alpine +FROM postgres:19.0-alpine ENV POSTGRES_USER=app \ POSTGRES_PASSWORD=app \ From 5e133a725bf48a923ade7285f7ad5e1ac8c8735d Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Fri, 20 Nov 2026 22:58:53 -0500 Subject: [PATCH 02/10] harness.adoption: sqlate capability map passes lint-context The capability map lists the seven packages as (built) entries, each linking its doc.go; pgtest is named inside the postgres entry rather than given its own entry. The dollar-quoting note is linked from a (planned) entry, so the Notes section that duplicated it goes. The second-engine paragraph moves into context/second-engine.md as its open points, homed at the backlog goal second-providers in standards-lab/roadmap/index.toml. --- context/README.md | 31 ++++++++++++++++++------------- context/second-engine.md | 12 ++++++++++++ 2 files changed, 30 insertions(+), 13 deletions(-) create mode 100644 context/second-engine.md diff --git a/context/README.md b/context/README.md index 81e9932..dc42188 100644 --- a/context/README.md +++ b/context/README.md @@ -18,16 +18,21 @@ the code do not express. ## Capability map -Every package is built: the session layer at the root, `header`, `query`, `migrate`, and -`sqltest` in the base module, and the `postgres` and `sqlint` sub-modules. The README's -Packages section lists them, the code and each package's `doc.go` are authoritative for the -API, and the guide documents their use. Detail for what is unbuilt is added when it is about -to be built. - -A second engine is a second sub-module, named for the engine. It carries its own dialect and -`sqlint.toml`, plus an overlay for each library pattern it does not accept as written in -standard SQL. - -## Notes - -- `dollar-quoting.md` — the `sqlint` linter's planned handling of PostgreSQL dollar-quoted strings. +- **Session layer** (built): the root package wraps a plain `*sql.DB`, owns transactions, and + maps every driver error through the engine's dialect ([doc.go](../doc.go)). +- **header** (built): reads the `--|` declaration header of an authored `.sql` file + ([header/doc.go](../header/doc.go)). +- **query** (built): compiles authored statements against the pattern catalog and binds them to + typed handles ([query/doc.go](../query/doc.go)). +- **migrate** (built): versions a schema over authored SQL under the engine's lock + ([migrate/doc.go](../migrate/doc.go)). +- **sqltest** (built): the scripted `database/sql` driver for hermetic tests + ([sqltest/doc.go](../sqltest/doc.go)). +- **postgres** (built): the PostgreSQL dialect sub-module, with `pgtest` for integration tests' + throwaway databases ([postgres/doc.go](../postgres/doc.go)). +- **sqlint** (built): the conventions linter sub-module and its command + ([sqlint/doc.go](../sqlint/doc.go)). +- **Dollar-quoted strings in sqlint** (planned): `sqlint` strips PostgreSQL dollar-quoted bodies + before it matches code ([dollar-quoting.md](dollar-quoting.md)). +- **A second engine** (planned): a second engine sub-module beside `postgres` + ([second-engine.md](second-engine.md)). diff --git a/context/second-engine.md b/context/second-engine.md new file mode 100644 index 0000000..58f59cc --- /dev/null +++ b/context/second-engine.md @@ -0,0 +1,12 @@ +# A second engine + +A second engine is a second sub-module beside `postgres`, named for the engine. Its roadmap home is +the backlog goal `second-providers` in `standards-lab/roadmap/index.toml`. + +Open points: + +- The sub-module carries its own dialect: bind-parameter rendering, error classification, the + migrate lock, the version statement, and the keyset predicate, as `postgres/doc.go` lists them. +- It carries its own `sqlint.toml`. +- It carries an overlay for each library pattern the engine does not accept as written in + standard SQL. From 9aa42fa051f677050a4b42d490c0273c40d37d3a Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Fri, 20 Nov 2026 23:01:58 -0500 Subject: [PATCH 03/10] harness.adoption: sqlate root, header and sqltest comments are the five kinds Unexported-identifier docs, test-function docs and in-body comments go. Reasoning a reader needs moves to exported docs: ErrConnectionFailed says a context deadline is not a connectivity failure, and Session says why QueryRowContext is left out. --- errors.go | 4 +++- header/header.go | 4 ---- session.go | 13 ++----------- sqlate_test.go | 26 ++++++-------------------- sqltest/driver.go | 5 ----- sqltest/driver_test.go | 2 -- sqltest/locking_test.go | 3 --- sqltest/recorder.go | 8 -------- 8 files changed, 11 insertions(+), 54 deletions(-) diff --git a/errors.go b/errors.go index d1ac31f..9acf389 100644 --- a/errors.go +++ b/errors.go @@ -10,7 +10,9 @@ var ( // failure to obtain a connection or begin a transaction, and a network // error or driver.ErrBadConn raised by any session call. It is wrapped // as fmt.Errorf("%w: %w", ErrConnectionFailed, err) so errors.Is - // matches it and the driver's error stays reachable. + // matches it and the driver's error stays reachable. A context deadline + // or cancellation is not a connectivity failure: it reports the caller's + // budget, not the engine's reachability, and the dialect maps it. ErrConnectionFailed = errors.New("database connection failed") // ErrInvalidValue classifies a data exception: a bound value the engine diff --git a/header/header.go b/header/header.go index e5bee85..9f5e75f 100644 --- a/header/header.go +++ b/header/header.go @@ -49,8 +49,6 @@ func Parse(text string) (Header, error) { var h Header inHeader := true offset := 0 - // open is the index in h.declarations of the declaration a fold may - // continue, or -1 when no declaration is open. open := -1 for n := 1; offset < len(text); n++ { raw, next := text[offset:], len(text) @@ -63,8 +61,6 @@ func Parse(text string) (Header, error) { h.end = offset } if !strings.HasPrefix(line, Marker) { - // A blank line, a prose line, and the body all close the - // declaration a fold may continue. open = -1 offset = next continue diff --git a/session.go b/session.go index a89524e..fd54bd5 100644 --- a/session.go +++ b/session.go @@ -29,7 +29,8 @@ type Dialect interface { // *Tx, so the same statement handle runs against the pool or inside a // transaction. Every method classifies a connectivity failure and maps every // other driver error through the dialect; the dialect itself is not on the -// interface, because runners never need it at request time. +// interface, because runners never need it at request time. QueryRowContext +// is left out: *sql.Row defers its error to Scan, where nothing can map it. type Session interface { ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) @@ -109,10 +110,6 @@ func (d *DB) Dialect() Dialect { return d.dialect } // routes every other error through the dialect; nil stays nil. func (d *DB) MapError(err error) error { return mapError(d.dialect, err) } -// mapError is the mapping both sessions share. A connectivity failure is -// classified here, before the dialect, because it is the driver's and not -// the engine's: the engine never saw the statement, so the dialect's -// vocabulary does not apply to it. func mapError(dialect Dialect, err error) error { if err == nil { return nil @@ -123,12 +120,6 @@ func mapError(dialect Dialect, err error) error { return dialect.MapError(err) } -// connectionFailed reports whether err is the driver failing to reach the -// engine: a network error anywhere in the chain (a refused or reset -// connection, a dial that timed out), or driver.ErrBadConn once -// database/sql has exhausted its retries. A context deadline is excluded: -// it implements net.Error but reports the caller's budget, not the -// engine's reachability, and stays the dialect's to map. func connectionFailed(err error) bool { if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) { return false diff --git a/sqlate_test.go b/sqlate_test.go index adc275a..d7a5aee 100644 --- a/sqlate_test.go +++ b/sqlate_test.go @@ -45,8 +45,8 @@ func TestWrap_PanicsOnNil(t *testing.T) { func TestDB_EveryMethodMaps(t *testing.T) { ctx := context.Background() db, rec := wrap(t, - sqltest.Response{Err: errDriver}, // exec - sqltest.Response{Err: errDriver}, // query + sqltest.Response{Err: errDriver}, + sqltest.Response{Err: errDriver}, ) rec.FailPrepare = func(string) error { return errDriver } @@ -219,8 +219,6 @@ func TestTransact_PanicRollsBackAndRepanics(t *testing.T) { _, _ = db.Transact(context.Background(), func(*sqlate.Tx) (int, error) { panic("boom") }, nil) } -// appDB is an application's own pool type, a sqlate.Beginner through the -// *sqlate.DB it embeds. type appDB struct{ *sqlate.DB } func TestTransact_RunsTheUnitOnAnEmbeddingBeginner(t *testing.T) { @@ -278,18 +276,14 @@ func TestConn_RunsOnThePoolAndWrapsAFailureAsConnectionFailed(t *testing.T) { } } -// A connectivity failure is the driver's, not the engine's: a network error -// from any session call, or driver.ErrBadConn after database/sql's retries, -// wraps ErrConnectionFailed before the dialect sees it, on the pool session -// and inside a transaction alike, with the driver's error still reachable. func TestMapError_ClassifiesConnectivityBeforeTheDialect(t *testing.T) { ctx := context.Background() refused := &net.OpError{Op: "dial", Net: "tcp", Err: syscall.ECONNREFUSED} db, rec := wrap(t, - sqltest.Response{Err: refused}, // pool exec - sqltest.Response{Err: refused}, // pool query - sqltest.Response{Err: refused}, // tx exec - sqltest.Response{Err: refused}, // tx query + sqltest.Response{Err: refused}, + sqltest.Response{Err: refused}, + sqltest.Response{Err: refused}, + sqltest.Response{Err: refused}, ) rec.FailPrepare = func(string) error { return refused } rec.FailCommit = refused @@ -313,8 +307,6 @@ func TestMapError_ClassifiesConnectivityBeforeTheDialect(t *testing.T) { connectionFailed(err) _, err = db.PrepareContext(ctx, "SELECT 1") connectionFailed(err) - // database/sql retries ErrBadConn on fresh connections before surfacing - // it, so it is asserted through the mapper rather than the driver. connectionFailed(db.MapError(fmt.Errorf("query: %w", driver.ErrBadConn))) tx, err := db.Begin(ctx, nil) @@ -330,9 +322,6 @@ func TestMapError_ClassifiesConnectivityBeforeTheDialect(t *testing.T) { connectionFailed(tx.Commit()) } -// A context deadline implements net.Error but reports the caller's budget, -// not the engine's reachability: it is not a connectivity failure, and the -// dialect maps it like any other error. func TestMapError_ContextDeadlineIsNotConnectivity(t *testing.T) { db, _ := wrap(t) for _, ctxErr := range []error{context.DeadlineExceeded, context.Canceled} { @@ -346,9 +335,6 @@ func TestMapError_ContextDeadlineIsNotConnectivity(t *testing.T) { } } -// A ConstraintError's message names the most specific handle the driver -// exposed: the constraint, the column when the violation carries no -// constraint name, and the class alone when the driver exposed neither. func TestConstraintError_ErrorNamesTheHandleTheDriverExposed(t *testing.T) { cases := []struct { name string diff --git a/sqltest/driver.go b/sqltest/driver.go index c6bdb3a..cb842d5 100644 --- a/sqltest/driver.go +++ b/sqltest/driver.go @@ -33,9 +33,6 @@ func (drv) Open(string) (driver.Conn, error) { return nil, errors.New("sqltest: open by DSN unsupported; use Open") } -// conn implements the context-aware driver interfaces: exec, query, -// prepare, begin with options, ping, and the named-value checker that -// accepts every argument unconverted. type conn struct{ rec *Recorder } var ( @@ -125,8 +122,6 @@ var ( func (s *stmt) Close() error { return nil } -// NumInput returns -1 so database/sql skips its argument-count check; the -// scripted driver does not parse SQL. func (s *stmt) NumInput() int { return -1 } func (s *stmt) CheckNamedValue(*driver.NamedValue) error { return nil } diff --git a/sqltest/driver_test.go b/sqltest/driver_test.go index d213faa..7406fb8 100644 --- a/sqltest/driver_test.go +++ b/sqltest/driver_test.go @@ -185,8 +185,6 @@ func TestOpen_ScriptedErrorSkipsTheShapeCheck(t *testing.T) { func TestWithTotal_AppendsTheCountToEveryRowAndLeavesTheResponse(t *testing.T) { r := sqltest.Response{Columns: []string{"id"}, Rows: [][]driver.Value{{"a"}, {"b"}}} got := sqltest.WithTotal(r, 7) - // The trailing column's name is the one query reads, which query's own - // suite proves by reading a total through WithTotal. if len(got.Columns) != 2 || got.Columns[0] != "id" { t.Errorf("columns = %v", got.Columns) } diff --git a/sqltest/locking_test.go b/sqltest/locking_test.go index 112b740..04d17d8 100644 --- a/sqltest/locking_test.go +++ b/sqltest/locking_test.go @@ -10,13 +10,10 @@ import ( "github.com/standards-lab/sqlate/sqltest" ) -// flag scripts the one boolean row a try-lock or unlock statement reads. func flag(b bool) sqltest.Response { return sqltest.Response{Columns: []string{"ok"}, Rows: [][]driver.Value{{b}}} } -// pinned opens a pool over the script and pins one connection, as a lock -// protocol does. func pinned(t *testing.T, responses ...sqltest.Response) (*sql.Conn, *sqltest.Recorder) { t.Helper() pool, rec := sqltest.Open(t, responses...) diff --git a/sqltest/recorder.go b/sqltest/recorder.go index 79dce1e..46a38e5 100644 --- a/sqltest/recorder.go +++ b/sqltest/recorder.go @@ -61,7 +61,6 @@ func WithTotal(r Response, n int64) Response { return out } -// totalColumn is the name query reserves for a counted page's total. const totalColumn = "sqlate_total" // Recorder is the shared state behind every connection a connector hands @@ -139,10 +138,6 @@ func (r *Recorder) record(c Call) { r.calls = append(r.calls, c) } -// next records the call, checks the arguments against the statement's -// placeholders, and pops the next response, rejecting an empty queue and a -// response of the wrong shape. The call is recorded even when it fails, so -// the log shows what ran. func (r *Recorder) next(op Op, query string, args []driver.NamedValue) (Response, error) { r.mu.Lock() defer r.mu.Unlock() @@ -168,7 +163,6 @@ func (r *Recorder) next(op Op, query string, args []driver.NamedValue) (Response return resp, nil } -// fits checks the response's shape against the call that consumed it. func (resp Response) fits(op Op) error { switch op { case OpExec: @@ -195,8 +189,6 @@ func (resp Response) fits(op Op) error { var placeholder = regexp.MustCompile(`\$([0-9]+)`) -// placeholders returns the argument count a statement binds: the highest $N -// in its text, the stub dialect's placeholder form. func placeholders(query string) int { max := 0 for _, m := range placeholder.FindAllStringSubmatch(query, -1) { From 1b2053757827725c0f0750f5cc514b5c5e1977dd Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Fri, 20 Nov 2026 23:01:58 -0500 Subject: [PATCH 04/10] harness.adoption: sqlate migrate comments are the five kinds Unexported-identifier docs, test-function docs and in-body comments go. Scripted test responses carry names (ran, failed, rowWritten, rowMissing, rowFound) in place of trailing step labels. --- migrate/export_test.go | 2 - migrate/files.go | 3 -- migrate/migrate.go | 67 +----------------------------- migrate/migrate_test.go | 91 +++++++++++++++-------------------------- migrate/sets.go | 4 -- migrate/sets_test.go | 70 ------------------------------- migrate/statements.go | 8 ---- 7 files changed, 34 insertions(+), 211 deletions(-) diff --git a/migrate/export_test.go b/migrate/export_test.go index 32b4148..3d654bf 100644 --- a/migrate/export_test.go +++ b/migrate/export_test.go @@ -2,6 +2,4 @@ package migrate import "time" -// SetAfter replaces m's lock-wait timer, so a test drives the TryLock -// backoff without sleeping. func SetAfter(m *Migrator, after func(time.Duration) <-chan time.Time) { m.after = after } diff --git a/migrate/files.go b/migrate/files.go index 5869ab9..0a0381e 100644 --- a/migrate/files.go +++ b/migrate/files.go @@ -94,9 +94,6 @@ func Files(fsys fs.FS, dir string) ([]Migration, error) { return out, nil } -// declarations reads a file's header and returns whether the migration runs in a -// transaction ("none" opts out, "required" or no declaration keeps it, any -// other value is an error) and the body the engine receives. func declarations(text string) (transactional bool, body string, err error) { h, err := header.Parse(text) if err != nil { diff --git a/migrate/migrate.go b/migrate/migrate.go index 3038b53..58a07f9 100644 --- a/migrate/migrate.go +++ b/migrate/migrate.go @@ -46,15 +46,9 @@ type Migrator struct { layers []*layer opts Options locker sqlate.Locker - // after is the lock wait's timer, time.After unless a test replaces it, - // so the unit suite drives the backoff without sleeping. - after func(time.Duration) <-chan time.Time + after func(time.Duration) <-chan time.Time } -// The lock wait's backoff between TryLock attempts: the first pause, doubled -// after each refusal up to the cap. A short first pause keeps a starter -// that loses a brief race fast; the cap bounds how long a waiter idles -// after the holder releases. const ( lockPollFirst = 25 * time.Millisecond lockPollMax = time.Second @@ -118,8 +112,6 @@ func New(db *sqlate.DB, sets []Set, opts Options) (*Migrator, error) { return &Migrator{db: db, layers: layers, opts: opts, locker: locker, after: time.After}, nil } -// validate checks one set's migrations: versions positive and strictly -// increasing, names and up texts present. func validate(set Set) error { last := 0 for _, mig := range set.Migrations { @@ -138,8 +130,6 @@ func validate(set Set) error { return nil } -// topLayer is the handle on the last set declared, the one a method without -// a set name acts on. func (m *Migrator) topLayer() Layer { return Layer{m: m, i: len(m.layers) - 1} } // Layers returns a handle on every set, in declared order. @@ -258,7 +248,6 @@ func (m *Migrator) Status(ctx context.Context) ([]SetStatus, error) { return out, nil } -// version reads one layer's history head from the pool. func (m *Migrator) version(ctx context.Context, l *layer) (Version, error) { var v Version ok, err := m.tableExists(ctx, m.db, l) @@ -278,7 +267,6 @@ func (m *Migrator) version(ctx context.Context, l *layer) (Version, error) { return v, nil } -// verify checks one layer's history against its migrations, from the pool. func (m *Migrator) verify(ctx context.Context, l *layer) error { applied, err := m.read(ctx, m.db, l) if err != nil { @@ -297,9 +285,6 @@ func (m *Migrator) verify(ctx context.Context, l *layer) error { return nil } -// status reads one layer's state from the pool. Pending migrations and a -// dirty row are state it reports, not failures; a history row the set does -// not carry is an *UnknownVersionError. func (m *Migrator) status(ctx context.Context, l *layer) (SetStatus, error) { applied, err := m.read(ctx, m.db, l) if err != nil { @@ -324,7 +309,6 @@ func (m *Migrator) status(ctx context.Context, l *layer) (SetStatus, error) { return s, nil } -// read returns the layer's history, nil when its table does not exist. func (m *Migrator) read(ctx context.Context, q querier, l *layer) ([]row, error) { ok, err := m.tableExists(ctx, q, l) if err != nil || !ok { @@ -333,10 +317,6 @@ func (m *Migrator) read(ctx context.Context, q querier, l *layer) ([]row, error) return m.readHistory(ctx, q, l) } -// preflight makes sure every set's history table exists and reads and -// checks every set's history on the pinned connection, in declared order, -// before any set runs. It runs inside the lock, so no starter can change a -// history between the check and the run. func (m *Migrator) preflight(ctx context.Context, conn *sql.Conn) ([][]row, error) { applied := make([][]row, len(m.layers)) for i, l := range m.layers { @@ -355,8 +335,6 @@ func (m *Migrator) preflight(ctx context.Context, conn *sql.Conn) ([][]row, erro return applied, nil } -// aboveApplied refuses a revert of layer i while a layer above it still has -// applied migrations. func (m *Migrator) aboveApplied(applied [][]row, i int) error { for j := i + 1; j < len(m.layers); j++ { if len(applied[j]) > 0 { @@ -366,8 +344,6 @@ func (m *Migrator) aboveApplied(applied [][]row, i int) error { return nil } -// belowPending refuses an apply on layer i while a layer below it still has -// pending migrations. func (m *Migrator) belowPending(applied [][]row, i int) error { for j := range i { if len(applied[j]) < len(m.layers[j].migrations) { @@ -377,8 +353,6 @@ func (m *Migrator) belowPending(applied [][]row, i int) error { return nil } -// applyPending applies up to n of the layer's pending migrations, in -// version order. func (m *Migrator) applyPending(ctx context.Context, conn *sql.Conn, l *layer, applied []row, n int) error { pending := l.migrations[len(applied):] if n < len(pending) { @@ -392,8 +366,6 @@ func (m *Migrator) applyPending(ctx context.Context, conn *sql.Conn, l *layer, a return nil } -// revertApplied reverts up to n of the layer's applied migrations, most -// recent first. func (m *Migrator) revertApplied(ctx context.Context, conn *sql.Conn, l *layer, applied []row, n int) error { for i := 0; i < n && len(applied)-1-i >= 0; i++ { mig := l.migrations[len(applied)-1-i] @@ -404,14 +376,6 @@ func (m *Migrator) revertApplied(ctx context.Context, conn *sql.Conn, l *layer, return nil } -// locked pins a connection, takes the lock when the dialect has one (see -// lock for how it waits), runs fn, and releases the lock under a context -// that survives cancellation, before the connection returns to the pool. -// Once ctx has ended the driver has discarded the connection and the -// session's end releases the lock, so an unlock failure then is noise and -// is not reported. A dialect without the capability is ErrNoLocker unless -// Unlocked. The history tables are not created here: preflight creates -// every set's table, and Force creates only its own set's. func (m *Migrator) locked(ctx context.Context, fn func(context.Context, *sql.Conn) error) (err error) { if m.locker == nil && !m.opts.Unlocked { return ErrNoLocker @@ -438,15 +402,6 @@ func (m *Migrator) locked(ctx context.Context, fn func(context.Context, *sql.Con return fn(ctx, conn) } -// lock takes the migration lock on conn. A dialect with TryLocker is polled: -// each refusal pauses, from lockPollFirst doubling to lockPollMax, and -// tries again, so no statement stays open on conn while another session -// holds the lock. A blocking Lock would hold its statement open for the -// whole wait, and a holder running CREATE INDEX CONCURRENTLY waits for -// every open transaction, the waiter's lock statement included, which -// postgres reports as a deadlock (40P01) and aborts the waiter. A dialect -// with Locker alone keeps its blocking Lock. The wait ends with ctx's -// error when ctx ends, holding nothing. func (m *Migrator) lock(ctx context.Context, conn *sql.Conn) error { try, ok := m.locker.(sqlate.TryLocker) if !ok { @@ -470,10 +425,6 @@ func (m *Migrator) lock(ctx context.Context, conn *sql.Conn) error { } } -// applyOne runs one migration of one layer: in a transaction with its -// history insert, so a failure records nothing; or, when the migration opts -// out, as a dirty insert, the statement, then the clean-up, so a failure -// leaves the row dirty and every later run refuses until Force. func (m *Migrator) applyOne(ctx context.Context, conn *sql.Conn, l *layer, mig Migration) error { if mig.Transactional { err := m.inTx(ctx, conn, func(tx *sql.Tx) error { @@ -502,7 +453,6 @@ func (m *Migrator) applyOne(ctx context.Context, conn *sql.Conn, l *layer, mig M return nil } -// revertOne runs one migration's down with the symmetric history change. func (m *Migrator) revertOne(ctx context.Context, conn *sql.Conn, l *layer, mig Migration) error { if mig.Down == "" { return fmt.Errorf("%w: %d %s", ErrNoDown, mig.Version, mig.Name) @@ -534,11 +484,6 @@ func (m *Migrator) revertOne(ctx context.Context, conn *sql.Conn, l *layer, mig return nil } -// inTx runs fn in a transaction on the pinned connection, rolling back on -// error and mapping the failure. Once ctx has ended, database/sql rolls the -// transaction back itself and the driver discards the connection, so the -// explicit rollback's result reports nothing new and is not joined; nor is -// ErrTxDone, the same fact reported when that rollback runs first. func (m *Migrator) inTx(ctx context.Context, conn *sql.Conn, fn func(*sql.Tx) error) error { tx, err := conn.BeginTx(ctx, nil) if err != nil { @@ -560,15 +505,10 @@ type row struct { dirty bool } -// querier is the read half of the session, satisfied by *sqlate.DB and by a -// pinned *sql.Conn. Single-row reads go through QueryContext because the -// Session interface deliberately leaves QueryRowContext out: *sql.Row -// defers its error to Scan, where nothing can map it. type querier interface { QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) } -// queryOne scans the first row into dest, reporting whether there was one. func (m *Migrator) queryOne(ctx context.Context, q querier, query string, args []any, dest ...any) (bool, error) { rows, err := q.QueryContext(ctx, query, args...) if err != nil { @@ -584,9 +524,6 @@ func (m *Migrator) queryOne(ctx context.Context, q querier, query string, args [ return true, m.db.MapError(rows.Err()) } -// ensureHistory creates the layer's history table when it does not exist -// and, over a catalog that is a HistoryUpgrader, upgrades a table an -// earlier release created when the catalog reports it outdated. func (m *Migrator) ensureHistory(ctx context.Context, conn *sql.Conn, l *layer) error { if _, err := conn.ExecContext(ctx, l.sql.create); err != nil { return m.db.MapError(err) @@ -630,8 +567,6 @@ func (m *Migrator) readHistory(ctx context.Context, q querier, l *layer) ([]row, return out, m.db.MapError(rows.Err()) } -// checkPrefix refuses a dirty row and requires the applied rows to be the -// migrations' prefix, by version and name. func checkPrefix(migrations []Migration, applied []row) error { for i, r := range applied { if r.dirty { diff --git a/migrate/migrate_test.go b/migrate/migrate_test.go index 28c5410..e8fdcd3 100644 --- a/migrate/migrate_test.go +++ b/migrate/migrate_test.go @@ -22,9 +22,14 @@ var ( {Version: 2, Name: "b", Up: "CREATE INDEX CONCURRENTLY ix ON a (x)", Down: "DROP INDEX CONCURRENTLY ix"}, } historyCols = []string{"version", "name", "dirty"} - locked = sqltest.Response{} // lock - created = sqltest.Response{} // CREATE TABLE IF NOT EXISTS - unlocked = sqltest.Response{Columns: []string{"unlock"}, Rows: [][]driver.Value{{true}}} // unlock + locked = sqltest.Response{} + created = sqltest.Response{} + unlocked = sqltest.Response{Columns: []string{"unlock"}, Rows: [][]driver.Value{{true}}} + ran = sqltest.Response{} + failed = sqltest.Response{Err: errDriver} + rowWritten = sqltest.Response{} + rowMissing = sqltest.Response{} + rowFound = sqltest.Response{Affected: 1} ) func history(rows ...[]driver.Value) sqltest.Response { @@ -39,9 +44,6 @@ func exists(yes bool) sqltest.Response { return sqltest.Response{Columns: []string{"count"}, Rows: [][]driver.Value{{n}}} } -// lockingDialect is the stub dialect with the lock capability an engine -// sub-module supplies: Lock executes one statement on the pinned connection -// and Unlock queries one row whose boolean says whether the lock was held. type lockingDialect struct{ sqltest.Dialect } func (lockingDialect) Lock(ctx context.Context, conn *sql.Conn, name string) error { @@ -60,15 +62,11 @@ func (lockingDialect) Unlock(ctx context.Context, conn *sql.Conn, name string) e return nil } -// newMigrator builds a one-set migrator over the driver fake with the lock -// capability, so lock and unlock calls are part of the recorded script. The -// set leaves its table empty, so it uses migrate.DefaultTable. func newMigrator(t *testing.T, opts migrate.Options, responses ...sqltest.Response) (*migrate.Migrator, *sqltest.Recorder) { t.Helper() return newMigratorTable(t, "", opts, responses...) } -// newMigratorTable is newMigrator with the set's history table named. func newMigratorTable(t *testing.T, table string, opts migrate.Options, responses ...sqltest.Response) (*migrate.Migrator, *sqltest.Recorder) { t.Helper() pool, rec := sqltest.Open(t, responses...) @@ -128,8 +126,8 @@ func TestNew_ValidatesTheSet(t *testing.T) { func TestSteps_TransactionalMigrationAppliesInsideOneTransaction(t *testing.T) { m, rec := newMigrator(t, migrate.Options{}, locked, created, history(), - sqltest.Response{}, // up - sqltest.Response{}, // history insert + ran, + rowWritten, unlocked, ) if err := m.Steps(context.Background(), 1); err != nil { @@ -162,7 +160,7 @@ func TestSteps_TransactionalMigrationAppliesInsideOneTransaction(t *testing.T) { func TestSteps_TransactionalFailureRecordsNothingAndStillUnlocks(t *testing.T) { m, rec := newMigrator(t, migrate.Options{}, locked, created, history(), - sqltest.Response{Err: errDriver}, // up fails + failed, unlocked, ) err := m.Up(context.Background()) @@ -185,9 +183,9 @@ func TestSteps_TransactionalFailureRecordsNothingAndStillUnlocks(t *testing.T) { func TestUp_NonTransactionalMigrationMarksDirtyThenClean(t *testing.T) { m, rec := newMigrator(t, migrate.Options{}, locked, created, history([]driver.Value{int64(1), "a", false}), - sqltest.Response{}, // insert dirty - sqltest.Response{}, // up - sqltest.Response{}, // set clean + rowWritten, + ran, + rowWritten, unlocked, ) if err := m.Up(context.Background()); err != nil { @@ -213,8 +211,8 @@ func TestUp_NonTransactionalMigrationMarksDirtyThenClean(t *testing.T) { func TestUp_NonTransactionalFailureLeavesTheRowDirty(t *testing.T) { m, rec := newMigrator(t, migrate.Options{}, locked, created, history([]driver.Value{int64(1), "a", false}), - sqltest.Response{}, // insert dirty - sqltest.Response{Err: errDriver}, // up fails + rowWritten, + failed, unlocked, ) err := m.Up(context.Background()) @@ -257,11 +255,11 @@ func TestSteps_RefusesHistoryTheSetDoesNotCarry(t *testing.T) { func TestDown_RevertsTheMostRecentApplied(t *testing.T) { m, rec := newMigrator(t, migrate.Options{}, locked, created, history([]driver.Value{int64(1), "a", false}, []driver.Value{int64(2), "b", false}), - sqltest.Response{}, // set dirty (b is non-transactional) - sqltest.Response{}, // down - sqltest.Response{}, // delete row - sqltest.Response{}, // a: begin → down - sqltest.Response{}, // a: delete row + rowWritten, + ran, + rowWritten, + ran, + rowWritten, unlocked, ) if err := m.Down(context.Background(), 2); err != nil { @@ -299,9 +297,9 @@ func TestDown_WithoutDownTextIsErrNoDown(t *testing.T) { func TestForce_ResetsTheHistoryWithoutTouchingTheSchema(t *testing.T) { m, rec := newMigrator(t, migrate.Options{}, locked, created, - sqltest.Response{}, // delete above 1 - sqltest.Response{}, // set clean → 0 rows - sqltest.Response{}, // insert 1 + rowWritten, + rowMissing, + rowWritten, unlocked, ) if err := m.Force(context.Background(), 1); err != nil { @@ -320,16 +318,13 @@ func TestForce_ResetsTheHistoryWithoutTouchingTheSchema(t *testing.T) { assertOps(t, rec, sqltest.OpExec, sqltest.OpExec, sqltest.OpExec, sqltest.OpExec, sqltest.OpExec, sqltest.OpQuery) } -// Forcing above an empty or shorter history writes the set's whole prefix -// through the version, not the version's row alone, so the history the -// prefix check reads back is one the set carries. func TestForce_WritesThePrefixThroughTheVersion(t *testing.T) { m, rec := newMigrator(t, migrate.Options{}, locked, created, - sqltest.Response{}, // delete above 2 - sqltest.Response{}, // set 1 clean → 0 rows - sqltest.Response{}, // insert 1 - sqltest.Response{Affected: 1}, // set 2 clean → present + rowWritten, + rowMissing, + rowWritten, + rowFound, unlocked, ) if err := m.Force(context.Background(), 2); err != nil { @@ -406,8 +401,6 @@ func TestVersion_ReadsTheHead(t *testing.T) { } } -// catalogDialect is a dialect with the lock capability and its own Catalog, -// the shape an engine without IF NOT EXISTS or information_schema ships. type catalogDialect struct{ lockingDialect } func (catalogDialect) CreateHistory(table string) string { @@ -432,7 +425,7 @@ func TestNew_TakesTheCatalogFromTheDialect(t *testing.T) { if err := m.Steps(ctx, 0); err != nil { t.Fatalf("Steps: %v", err) } - _ = m.Force(ctx, 0) // one locked run: lock, create, delete above, unlock + _ = m.Force(ctx, 0) if got := rec.SQL(sqltest.OpQuery)[0]; got != "SELECT COUNT(*) FROM sys.tables WHERE name = $1" { t.Errorf("exists = %q", got) } @@ -441,8 +434,6 @@ func TestNew_TakesTheCatalogFromTheDialect(t *testing.T) { } } -// upgradingDialect is a dialect whose Catalog is also a HistoryUpgrader: -// StandardCatalog's pair with an outdated check and its upgrade. type upgradingDialect struct { lockingDialect migrate.StandardCatalog @@ -473,8 +464,6 @@ func TestHistory_UpgradesAnOutdatedTableOnlyWhenTheCatalogSaysSo(t *testing.T) { } current := history([]driver.Value{int64(1), "a", false}, []driver.Value{int64(2), "b", false}) - // An outdated table is upgraded after it is created and before the - // history is read, inside the lock. m, rec := open(locked, created, outdated(true), sqltest.Response{}, current, unlocked) if err := m.Up(ctx); err != nil { t.Fatalf("Up: %v", err) @@ -488,15 +477,12 @@ func TestHistory_UpgradesAnOutdatedTableOnlyWhenTheCatalogSaysSo(t *testing.T) { t.Errorf("upgrade = %q", calls[3].SQL) } - // A current table is checked and left alone, so a second run does not - // upgrade it again. m, rec = open(locked, created, outdated(false), current, unlocked) if err := m.Up(ctx); err != nil { t.Fatalf("Up: %v", err) } assertOps(t, rec, sqltest.OpExec, sqltest.OpExec, sqltest.OpQuery, sqltest.OpQuery, sqltest.OpQuery) - // Force, which creates its own set's table, upgrades it the same way. m, rec = open(locked, created, outdated(true), sqltest.Response{}, sqltest.Response{}, unlocked) if err := m.Force(ctx, 0); err != nil { t.Fatalf("Force: %v", err) @@ -505,7 +491,6 @@ func TestHistory_UpgradesAnOutdatedTableOnlyWhenTheCatalogSaysSo(t *testing.T) { t.Errorf("Force execs = %q, want the upgrade after the create", got) } - // A failing upgrade fails the run, naming the set. m, _ = open(locked, created, outdated(true), sqltest.Response{Err: errDriver}, unlocked) var setErr *migrate.SetError if err := m.Up(ctx); !errors.As(err, &setErr) || setErr.Set != "app" || !errors.Is(err, errDriver) { @@ -515,7 +500,7 @@ func TestHistory_UpgradesAnOutdatedTableOnlyWhenTheCatalogSaysSo(t *testing.T) { func TestLocked_DialectWithoutLockerFailsUnlessUnlocked(t *testing.T) { pool, rec := sqltest.Open(t, created, history(), sqltest.Response{}, sqltest.Response{}) - db := sqlate.Wrap(pool, sqltest.Dialect{}) // the stub dialect has no Locker + db := sqlate.Wrap(pool, sqltest.Dialect{}) m, err := migrate.New(db, []migrate.Set{{Name: "app", Migrations: set[:1]}}, migrate.Options{}) if err != nil { t.Fatal(err) @@ -554,7 +539,7 @@ func TestOptions_TableAndLockNameDefaultsAndOverrides(t *testing.T) { m1, rec1 := newMigrator(t, migrate.Options{}, locked, created, history(), unlocked) m2, rec2 := newMigratorTable(t, "other", migrate.Options{}, locked, created, history(), unlocked) - _ = m1.Steps(context.Background(), 0) // no-op: no calls + _ = m1.Steps(context.Background(), 0) _ = m1.Up(context.Background()) _ = m2.Up(context.Background()) if rec1.Calls()[0].Args[0] != "migrate.schema_version" || rec2.Calls()[0].Args[0] != "migrate.other" { @@ -562,15 +547,10 @@ func TestOptions_TableAndLockNameDefaultsAndOverrides(t *testing.T) { } } -// tryLockAnswer is the scripted try-lock row: true grants the lock, false -// is a refusal while another session holds it. func tryLockAnswer(granted bool) sqltest.Response { return sqltest.Response{Columns: []string{"try_lock"}, Rows: [][]driver.Value{{granted}}} } -// newTryMigrator builds a one-set migrator, over the first migration only, -// on sqltest.LockingDialect, so the run takes the lock by polling TryLock, -// with its lock-wait timer replaced by after. func newTryMigrator(t *testing.T, after func(time.Duration) <-chan time.Time, responses ...sqltest.Response) (*migrate.Migrator, *sqltest.Recorder) { t.Helper() pool, rec := sqltest.Open(t, responses...) @@ -582,7 +562,6 @@ func newTryMigrator(t *testing.T, after func(time.Duration) <-chan time.Time, re return m, rec } -// fired is a lock-wait timer that has already fired. func fired() <-chan time.Time { c := make(chan time.Time, 1) c <- time.Time{} @@ -590,7 +569,7 @@ func fired() <-chan time.Time { } func TestLocked_TryLockerPollsUntilGranted(t *testing.T) { - const refusals = 8 // enough to reach the cap and hold it + const refusals = 8 responses := make([]sqltest.Response, 0, refusals+6) for range refusals { responses = append(responses, tryLockAnswer(false)) @@ -604,8 +583,6 @@ func TestLocked_TryLockerPollsUntilGranted(t *testing.T) { if err := m.Up(context.Background()); err != nil { t.Fatalf("Up: %v", err) } - // One pause per refusal: the documented schedule, 25ms doubling to a 1s - // cap. ms := time.Millisecond want := []time.Duration{25 * ms, 50 * ms, 100 * ms, 200 * ms, 400 * ms, 800 * ms, time.Second, time.Second} if !slices.Equal(pauses, want) { @@ -633,13 +610,11 @@ func TestLocked_ContextEndingDuringTheWaitHoldsNothing(t *testing.T) { defer cancel() m, rec := newTryMigrator(t, func(time.Duration) <-chan time.Time { cancel() - return nil // never fires: only ctx ends the wait + return nil }, tryLockAnswer(false)) if err := m.Up(ctx); !errors.Is(err, context.Canceled) { t.Fatalf("Up = %v, want context.Canceled", err) } - // The one refused try-lock and nothing after it: no lock is held, so - // none is released, and the run did no work. assertOps(t, rec, sqltest.OpQuery) } diff --git a/migrate/sets.go b/migrate/sets.go index 22b9a78..a02fd45 100644 --- a/migrate/sets.go +++ b/migrate/sets.go @@ -34,9 +34,6 @@ type SetStatus struct { Dirty bool } -// layer is one set as the migrator holds it: the table after defaulting, -// the validated copy of the migrations, and the statements rendered for -// the table. type layer struct { name string table string @@ -167,7 +164,6 @@ func (l Layer) Force(ctx context.Context, version int) error { }) } -// copyOf returns a copy of ms, so a caller never holds a migrator's slice. func copyOf(ms []Migration) []Migration { out := make([]Migration, len(ms)) copy(out, ms) diff --git a/migrate/sets_test.go b/migrate/sets_test.go index b6a0283..a131047 100644 --- a/migrate/sets_test.go +++ b/migrate/sets_test.go @@ -13,9 +13,6 @@ import ( "github.com/standards-lab/sqlate/sqltest" ) -// The two sets every multi-set proof declares: a library set over its own -// history table and the program's own set over the default one, the library -// declared first because the program's migrations reference its objects. var ( library = migrate.Set{ Name: "lib", @@ -30,26 +27,19 @@ var ( {Version: 1, Name: "app_one", Up: "CREATE TABLE app_one ()", Down: "DROP TABLE app_one", Transactional: true}, }, } - // two is a set of two migrations, for the states one migration cannot - // show: a partly applied history. two = migrate.Set{Name: "two", Table: "two_schema_version", Migrations: set} libApplied = [][]driver.Value{{int64(1), "lib_one", false}} appApplied = [][]driver.Value{{int64(1), "app_one", false}} - // step scripts one statement of a migration or of its history row. step = sqltest.Response{} ) -// migrationTexts are the two sets' up and down texts, the statements a -// refused run must not have executed. var migrationTexts = []string{ "CREATE TABLE lib_one ()", "DROP TABLE lib_one", "CREATE TABLE app_one ()", "DROP TABLE app_one", } -// newSets builds a migrator over the declared sets and the driver fake with -// the lock capability, so lock and unlock calls are part of the script. func newSets(t *testing.T, sets []migrate.Set, responses ...sqltest.Response) (*migrate.Migrator, *sqltest.Recorder) { t.Helper() pool, rec := sqltest.Open(t, responses...) @@ -60,7 +50,6 @@ func newSets(t *testing.T, sets []migrate.Set, responses ...sqltest.Response) (* return m, rec } -// script flattens the parts of a response sequence. func script(parts ...[]sqltest.Response) []sqltest.Response { var out []sqltest.Response for _, p := range parts { @@ -71,14 +60,10 @@ func script(parts ...[]sqltest.Response) []sqltest.Response { func one(r ...sqltest.Response) []sqltest.Response { return r } -// checked scripts one set's pre-flight: the history table's create and the -// ordered read returning applied. func checked(applied ...[]driver.Value) []sqltest.Response { return []sqltest.Response{created, history(applied...)} } -// assertPrefixes checks that got has one text per want, in order, each -// starting with its want. func assertPrefixes(t *testing.T, got, want []string) { t.Helper() if len(got) != len(want) { @@ -91,8 +76,6 @@ func assertPrefixes(t *testing.T, got, want []string) { } } -// assertOneLock checks that the run took exactly one lock, under name, as -// its first call, and released it as its last. func assertOneLock(t *testing.T, rec *sqltest.Recorder, name string) { t.Helper() calls := rec.Calls() @@ -113,7 +96,6 @@ func assertOneLock(t *testing.T, rec *sqltest.Recorder, name string) { } } -// assertNoMigrationText checks that no set's up or down text ran. func assertNoMigrationText(t *testing.T, rec *sqltest.Recorder) { t.Helper() for _, text := range rec.SQL(sqltest.OpExec) { @@ -123,11 +105,6 @@ func assertNoMigrationText(t *testing.T, rec *sqltest.Recorder) { } } -// TestNewValidation covers the checks New makes before any I/O: a database, -// at least one set, a name on every set, no repeated name, no shared -// history table (an empty table and the explicit default are the same -// table), a table name that is a plain identifier, and each set's own -// migration ordering. func TestNewValidation(t *testing.T) { pool, _ := sqltest.Open(t) db := sqlate.Wrap(pool, lockingDialect{}) @@ -164,9 +141,6 @@ func TestNewValidation(t *testing.T) { } } -// TestUpOrder proves Up takes one lock, creates and reads every set's -// history before any migration runs, then applies the sets in declared -// order, each over its own history table. func TestUpOrder(t *testing.T) { responses := script(one(locked), checked(), checked(), one(step, step, step, step), one(unlocked)) m, rec := newSets(t, []migrate.Set{library, app}, responses...) @@ -191,16 +165,12 @@ func TestUpOrder(t *testing.T) { assertOneLock(t, rec, "migrate.schema_version") } -// TestLockName proves the lock name defaults to "migrate." over the top -// set's history table, and that Options.LockName overrides it. func TestLockName(t *testing.T) { responses := script(one(locked), checked(), checked(), one(step, step, step, step), one(unlocked)) m, rec := newSets(t, []migrate.Set{app, library}, responses...) if err := m.Up(context.Background()); err != nil { t.Fatalf("Up: %v", err) } - // The sets are declared the other way round here, so the default names - // the library's table: the top set's, not the first set's. assertOneLock(t, rec, "migrate.lib_schema_version") pool, rec := sqltest.Open(t, script(one(locked), checked(), one(step, step), one(unlocked))...) @@ -214,9 +184,6 @@ func TestLockName(t *testing.T) { assertOneLock(t, rec, "acme.schema") } -// TestNoLocker proves a dialect without the lock capability refuses a run -// with ErrNoLocker before any call, and runs without a lock under -// Options.Unlocked. func TestNoLocker(t *testing.T) { pool, rec := sqltest.Open(t) m, err := migrate.New(sqlate.Wrap(pool, sqltest.Dialect{}), []migrate.Set{library, app}, migrate.Options{}) @@ -248,8 +215,6 @@ func TestNoLocker(t *testing.T) { } } -// TestDown_RevertsTheTopSetOnly proves Migrator.Down reverts the top set -// and leaves the sets below it applied, with no history table dropped. func TestDown_RevertsTheTopSetOnly(t *testing.T) { responses := script(one(locked), checked(libApplied...), checked(appApplied...), one(step, step), one(unlocked)) m, rec := newSets(t, []migrate.Set{library, app}, responses...) @@ -267,9 +232,6 @@ func TestDown_RevertsTheTopSetOnly(t *testing.T) { }) } -// TestDown_RefusesALayerBelowAnAppliedOne proves a revert of the library -// set is refused with ErrAboveApplied while the program's set is still -// applied, naming both layers, with no migration text run. func TestDown_RefusesALayerBelowAnAppliedOne(t *testing.T) { responses := script(one(locked), checked(libApplied...), checked(appApplied...), one(unlocked)) m, rec := newSets(t, []migrate.Set{library, app}, responses...) @@ -290,9 +252,6 @@ func TestDown_RefusesALayerBelowAnAppliedOne(t *testing.T) { } } -// TestSteps_RefusesALayerAboveAPendingOne proves an apply on the program's -// set is refused with ErrBelowPending while the library set still has -// pending migrations, naming both layers, with no migration text run. func TestSteps_RefusesALayerAboveAPendingOne(t *testing.T) { responses := script(one(locked), checked(), checked(), one(unlocked)) m, rec := newSets(t, []migrate.Set{library, app}, responses...) @@ -313,9 +272,6 @@ func TestSteps_RefusesALayerAboveAPendingOne(t *testing.T) { } } -// TestResetOrder proves Reset reverts the sets in reverse declared order -// and drops each set's history table once that set is reverted, all under -// the one lock. func TestResetOrder(t *testing.T) { responses := script( one(locked), checked(libApplied...), checked(appApplied...), @@ -338,8 +294,6 @@ func TestResetOrder(t *testing.T) { assertOneLock(t, rec, "migrate.schema_version") } -// TestUpStopsAtFailure proves a failing set stops the run before the sets -// after it, the error names the set, and the lock is released. func TestUpStopsAtFailure(t *testing.T) { responses := script( one(locked), checked(), checked(), @@ -365,11 +319,6 @@ func TestUpStopsAtFailure(t *testing.T) { } } -// TestDirtyRefusal proves every mutating verb refuses a dirty set before -// any set runs, even when the dirty set is not the first: the library set -// is clean and pending, the program's history has a dirty row, and no -// migration text of either set runs. The error names the set, classifies as -// ErrDirty, and carries the version. func TestDirtyRefusal(t *testing.T) { dirty := [][]driver.Value{{int64(1), "app_one", true}} for _, op := range []struct { @@ -410,8 +359,6 @@ func TestDirtyRefusal(t *testing.T) { } } -// TestUnknownHistoryRefusal proves a history row the set does not carry -// refuses the run, classified as ErrUnknownVersion and naming the set. func TestUnknownHistoryRefusal(t *testing.T) { responses := script(one(locked), checked([]driver.Value{int64(1), "someone_elses", false}), one(unlocked)) m, rec := newSets(t, []migrate.Set{library}, responses...) @@ -426,13 +373,9 @@ func TestUnknownHistoryRefusal(t *testing.T) { } } -// TestStatus proves Status reads each set in declared order without a lock, -// two calls per set, and reports every field of SetStatus. func TestStatus(t *testing.T) { ctx := context.Background() - // The library set at its head and the program's set with no history - // table: the read of a missing table is the existence check alone. m, rec := newSets(t, []migrate.Set{library, app}, exists(true), history(libApplied...), exists(false)) got, err := m.Status(ctx) @@ -458,8 +401,6 @@ func TestStatus(t *testing.T) { t.Errorf("%d scripted responses unconsumed", rec.Pending()) } - // A partly applied set: the head is the applied version and the rest of - // the set is pending. m, _ = newSets(t, []migrate.Set{two}, exists(true), history([]driver.Value{int64(1), "a", false})) got, err = m.Status(ctx) if err != nil { @@ -469,14 +410,12 @@ func TestStatus(t *testing.T) { t.Errorf("partial status = %+v, want version 1 of 2 with 2 pending", s) } - // A dirty row is state Status reports, not a failure. m, _ = newSets(t, []migrate.Set{library}, exists(true), history([]driver.Value{int64(1), "lib_one", true})) got, err = m.Status(ctx) if err != nil || len(got) != 1 || !got[0].Dirty || got[0].Version != 1 { t.Errorf("dirty Status = %+v, %v; want version 1 dirty", got, err) } - // A history row the set does not carry is an error naming the set. m, _ = newSets(t, []migrate.Set{library}, exists(true), history([]driver.Value{int64(1), "other", false})) _, err = m.Status(ctx) se, ok := errors.AsType[*migrate.SetError](err) @@ -485,9 +424,6 @@ func TestStatus(t *testing.T) { } } -// TestForce proves Layer.Force runs the named set's override under the -// lock, that Layer reports a name the migrator does not hold, and that -// Migrator.Force acts on the top set. func TestForce(t *testing.T) { ctx := context.Background() m, rec := newSets(t, []migrate.Set{app, library}, script(one(locked), one(created, step), one(unlocked))...) @@ -510,7 +446,6 @@ func TestForce(t *testing.T) { t.Error(`Layer("nope") reported a set the migrator does not hold`) } - // Migrator.Force acts on the top set, the library here, not the first. m, rec = newSets(t, []migrate.Set{app, library}, script(one(locked), one(created, step), one(unlocked))...) if err := m.Force(ctx, 0); err != nil { t.Fatalf("Migrator.Force: %v", err) @@ -522,8 +457,6 @@ func TestForce(t *testing.T) { }) } -// TestLayers proves Layers reports every set in declared order and that -// Migrations and Version on the migrator read the top set. func TestLayers(t *testing.T) { head := sqltest.Response{Columns: []string{"version", "dirty"}, Rows: [][]driver.Value{{int64(1), false}}} m, rec := newSets(t, []migrate.Set{library, app}, exists(true), head) @@ -560,9 +493,6 @@ func TestLayers(t *testing.T) { } } -// TestVerify_CoversEverySetInOrder proves Verify reports the first set's -// fault and stops there: the library set is pending, so the program's set -// is never read. func TestVerify_CoversEverySetInOrder(t *testing.T) { m, rec := newSets(t, []migrate.Set{library, app}, exists(false)) err := m.Verify(context.Background()) diff --git a/migrate/statements.go b/migrate/statements.go index 1ffcb3f..ab1f45a 100644 --- a/migrate/statements.go +++ b/migrate/statements.go @@ -77,18 +77,10 @@ func (StandardCatalog) HistoryExists(param string) string { return "SELECT COUNT(*) FROM information_schema.tables WHERE table_name = " + param } -// statements are the texts one set's layer runs against its history table, -// rendered once with the dialect's placeholders: the catalog pair from the -// Catalog, the outdated check and its upgrade from a HistoryUpgrader (both -// empty for a catalog without one), the rest standard DML, and drop, the -// DDL Reset runs to remove the set's own history table once that set is -// reverted. Booleans bind as parameters, never as literals. type statements struct { create, exists, outdated, upgrade, all, head, insert, setDirty, del, delAbove, drop string } -// history renders the statements for the history table t over -// catalog c, with p as the dialect's placeholder. func history(t string, p func(int) string, c Catalog) statements { var outdated, upgrade string if u, ok := c.(HistoryUpgrader); ok { From d5ca35a1be727bb8edf6deed8e27149f92432cbe Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Fri, 20 Nov 2026 23:01:58 -0500 Subject: [PATCH 05/10] harness.adoption: sqlate query comments are the five kinds Unexported-identifier docs, test-function docs and in-body comments go. docs/features.md takes the reasoning with no other home: the cursor hash guards against accident, not forgery, and the migration lock's release survives the run's cancellation. --- docs/features.md | 8 ++- query/cursor.go | 30 ---------- query/cursor_test.go | 44 ++------------ query/guard.go | 3 - query/guard_test.go | 16 +---- query/main_test.go | 5 +- query/mapper.go | 27 +-------- query/mapper_test.go | 13 ++--- query/params.go | 40 ------------- query/params_test.go | 7 --- query/patterns.go | 42 -------------- query/patterns_test.go | 23 -------- query/projection.go | 122 ++------------------------------------- query/projection_test.go | 62 ++------------------ query/returning.go | 60 ++----------------- query/returning_test.go | 14 +---- query/rows_test.go | 3 - query/statement.go | 18 +----- query/statements.go | 30 ---------- query/statements_test.go | 2 - query/utc.go | 8 --- query/utc_test.go | 9 --- 22 files changed, 36 insertions(+), 550 deletions(-) diff --git a/docs/features.md b/docs/features.md index 0d5e491..397d445 100644 --- a/docs/features.md +++ b/docs/features.md @@ -330,7 +330,9 @@ standard spelling of the predicate is a chain of disjuncts, `(a > x) OR (a = x A engine may overlay it as a row-value comparison, `(a, b) > (x, y)`. A cursor is opaque, URL-safe text a caller relays unchanged. It records the base, the keyed fields, the direction, and the values, under a hash of those and each keyed field's declared type, so a cursor from -before a contract change is refused. It also records the filters, so `Continue` under other +before a contract change is refused. The hash is unkeyed and guards against accident, not +forgery: a cursor's values re-enter the read only as bound parameters cast to the fields' types, +so a forged cursor can at most select another page. It also records the filters, so `Continue` under other filters than the page that issued it is refused as a `CursorMismatch`. Filters with a value that has no JSON form, such as a float NaN, cannot be recorded, and their page reports `More` without a `Next`. @@ -421,7 +423,9 @@ the lock: each refused `TryLock` pauses, from 25ms doubling to a 1s cap, and tri the wait ends with the context's error when the context ends, holding nothing. No statement stays open while a starter waits, so a holder's `CREATE INDEX CONCURRENTLY`, which waits for every open transaction, cannot deadlock with the waiter. A dialect with `Locker` alone waits in -its blocking `Lock`. A dialect without `Locker` fails with `ErrNoLocker` unless +its blocking `Lock`. The lock is released under a context that survives the run's cancellation; +once the context has ended, the engine releases it with the discarded connection's session, and +an unlock failure then is not reported. A dialect without `Locker` fails with `ErrNoLocker` unless `Options.Unlocked` opts out, in which case concurrent starters are unsafe. Inside the lock, every run that applies or reverts migrations creates and reads every set's history table first, so a dirty set or a history that does not match its set refuses the run before any migration diff --git a/query/cursor.go b/query/cursor.go index 4baecb3..15880be 100644 --- a/query/cursor.go +++ b/query/cursor.go @@ -15,14 +15,8 @@ import ( // content is not a contract and a consumer never builds one. type Cursor string -// cursorVersion is the body format; a cursor of another version is malformed. const cursorVersion = 1 -// cursorBody is a cursor's decoded content. It names the base and the keyed -// terms so a cursor from before a contract change is caught by name, and -// the terms' declared types are covered by the check prefix instead. Filters -// is the filter signature of the request that issued it, so a continuation -// under other filters is caught by comparison. type cursorBody struct { V int `json:"v"` Base string `json:"base"` @@ -32,12 +26,6 @@ type cursorBody struct { Values []string `json:"values"` } -// filterSignature is the canonical text of filters for a cursor's -// fingerprint: their JSON encoding, in the order given, and empty for no -// filters, so a nil and an empty slice agree. false when a value cannot be -// represented this way (for example a float NaN, which encoding/json -// refuses); no cursor is then issued for the page, the same way an ordering -// that cannot be continued issues none. func filterSignature(filters []Filter) (string, bool) { if len(filters) == 0 { return "", true @@ -49,12 +37,6 @@ func filterSignature(filters []Filter) (string, bool) { return string(b), true } -// signature is what a cursor is bound to beyond its body: the base's name -// and each keyed term's name, declared type, and direction. It is hashed -// with the body, so a cursor issued when a keyed field had another type no -// longer verifies. The hash is unkeyed and guards against accident, not -// forgery: a cursor's values re-enter the read only as bound parameters cast -// to the fields' types, so a forged one can at most select another page. func (p Projection[T]) signature(o ordering) string { var sb strings.Builder sb.WriteString(p.base.name) @@ -73,7 +55,6 @@ func (p Projection[T]) signature(o ordering) string { return sb.String() } -// check is the 4-byte prefix over a signature and a body's exact bytes. func check(signature string, body []byte) [4]byte { h := sha256.New() h.Write([]byte(signature)) @@ -84,8 +65,6 @@ func check(signature string, body []byte) [4]byte { return out } -// keyedNames is the keyed terms' field names, what a cursor records and a -// later request is checked against. func keyedNames(o ordering) []string { names := make([]string, len(o.keyed)) for i, t := range o.keyed { @@ -94,13 +73,9 @@ func keyedNames(o ordering) []string { return names } -// encodeCursor issues the cursor that continues past values under o and the -// filters whose signature is filterSig: the body and its check prefix as one -// base64 string. func (p Projection[T]) encodeCursor(o ordering, filterSig string, values []string) Cursor { body, err := json.Marshal(cursorBody{V: cursorVersion, Base: p.base.name, Terms: keyedNames(o), Desc: o.desc, Filters: filterSig, Values: values}) if err != nil { - // The body holds strings, bools, and an int only, which always marshal. panic(err) } c := check(p.signature(o), body) @@ -108,11 +83,6 @@ func (p Projection[T]) encodeCursor(o ordering, filterSig string, values []strin return Cursor(base64.RawURLEncoding.EncodeToString(raw)) } -// decodeCursor reads the keyed values back out of c, refusing a request o -// cannot continue by cursor, a cursor that does not decode or verify, and -// one issued for another base, another ordering, or other filters. Filters -// that have no signature cannot be shown to match, so they are refused as a -// mismatch. func (p Projection[T]) decodeCursor(c Cursor, o ordering, filters []Filter) ([]string, error) { if !o.cursorable { return nil, &CursorError{Reason: CursorUnsupported} diff --git a/query/cursor_test.go b/query/cursor_test.go index 06ad5f6..0d3fbec 100644 --- a/query/cursor_test.go +++ b/query/cursor_test.go @@ -15,8 +15,6 @@ import ( "github.com/standards-lab/sqlate/sqltest" ) -// member is the row of the composite-key base, whose key fields are both -// declared not null, so its orderings can be continued by a cursor. type member struct { Org string ID string @@ -44,8 +42,6 @@ func memberView(t *testing.T) query.Projection[member] { return catalog().MustCompile(projectionFiles, "sql", sqltest.Dialect{}).Statement("member").Project(scanMember) } -// issue lists one page over the member base and returns the cursor it -// issued, failing the test when it issued none. func issue(t *testing.T, sorts []query.Sort, filters ...query.Filter) query.Cursor { t.Helper() db, _ := session(t, sqltest.WithTotal(members("a", "b", "c"), 9)) @@ -61,8 +57,6 @@ func issue(t *testing.T, sorts []query.Sort, filters ...query.Filter) query.Curs func TestContinue_ContinuesFromThePagesLastItem(t *testing.T) { c := issue(t, nil) - // The cursor's page takes no page number: the keyset predicate stands in - // for the offset, which stays 0. db, rec := session(t, sqltest.WithTotal(members("c"), 9)) got, err := memberView(t).Continue(context.Background(), db, query.Directives{}, c, 2) if err != nil { @@ -73,8 +67,6 @@ func TestContinue_ContinuesFromThePagesLastItem(t *testing.T) { } keyset := "(q.org > CAST($1 AS uuid) OR (q.org = CAST($1 AS uuid) AND q.id > CAST($2 AS uuid)))" calls := rec.Calls() - // One statement: the window counts under the request's filters alone, - // and the keyset predicate outside it narrows the page, not the total. if len(calls) != 1 { t.Fatalf("ops = %v, want the counted page alone", rec.Ops()) } @@ -84,8 +76,6 @@ func TestContinue_ContinuesFromThePagesLastItem(t *testing.T) { if got.Total != 9 { t.Errorf("total = %d, want the window's 9", got.Total) } - // The page's last item was ("o", "b"): each keyed value is bound once, - // and the disjunct that repeats it reuses its placeholder. if a := calls[0].Args; len(a) != 4 || a[0] != "o" || a[1] != "b" || a[2] != 0 || a[3] != 3 { t.Errorf("page args = %v", a) } @@ -133,9 +123,7 @@ func TestContinue_RefusesAnotherOrderingOrAnotherBase(t *testing.T) { after query.Cursor }{ "another direction": {descending, ascending}, - // Sorting by the second key field first puts the keyed prefix in the - // other order, which the cursor records by name. - "another prefix": {[]query.Sort{{Field: "id"}}, ascending}, + "another prefix": {[]query.Sort{{Field: "id"}}, ascending}, } for name, c := range cases { db, _ := session(t) @@ -149,8 +137,6 @@ func TestContinue_RefusesAnotherOrderingOrAnotherBase(t *testing.T) { } } - // The same key fields and types under another base: the cursor names the - // base it was issued for, so it is refused by name. other := catalog().MustCompile(fstest.MapFS{ "sql/archive.sql": {Data: []byte("--| tier: standard\n--| key: org, id\n--| field: org uuid not null\n--| field: id uuid not null\nSELECT org, id FROM archive")}, }, "sql", sqltest.Dialect{}).Statement("archive").Project(query.Scalar[string]) @@ -165,11 +151,10 @@ func TestContinue_RefusesAnotherOrderingOrAnotherBase(t *testing.T) { func TestContinue_RefusesOtherFilters(t *testing.T) { c := issue(t, nil, query.Filter{Field: "name", Op: query.OpEq, Value: "M"}) cases := map[string][]query.Filter{ - "no filters": nil, - "another value": {{Field: "name", Op: query.OpEq, Value: "N"}}, - "another op": {{Field: "name", Op: query.OpNe, Value: "M"}}, - "another filter": {{Field: "name", Op: query.OpEq, Value: "M"}, {Field: "org", Op: query.OpEq, Value: "o"}}, - // A value with no JSON form cannot be shown to match. + "no filters": nil, + "another value": {{Field: "name", Op: query.OpEq, Value: "N"}}, + "another op": {{Field: "name", Op: query.OpNe, Value: "M"}}, + "another filter": {{Field: "name", Op: query.OpEq, Value: "M"}, {Field: "org", Op: query.OpEq, Value: "o"}}, "unrepresentable": {{Field: "name", Op: query.OpEq, Value: math.NaN()}}, } for name, filters := range cases { @@ -184,15 +169,12 @@ func TestContinue_RefusesOtherFilters(t *testing.T) { } } - // The same filters rebuilt as a new slice continue: the cursor compares - // their content, not their identity. db, _ := session(t, sqltest.WithTotal(members("c"), 9)) same := []query.Filter{{Field: "name", Op: query.OpEq, Value: "M"}} if _, err := memberView(t).Continue(context.Background(), db, query.Directives{Filters: same}, c, 2); err != nil { t.Errorf("the same filters = %v, want the page", err) } - // No filters and an empty filter slice are the same request. unfiltered := issue(t, nil) db, _ = session(t, sqltest.WithTotal(members("c"), 9)) if _, err := memberView(t).Continue(context.Background(), db, query.Directives{Filters: []query.Filter{}}, unfiltered, 2); err != nil { @@ -201,8 +183,6 @@ func TestContinue_RefusesOtherFilters(t *testing.T) { } func TestList_FiltersWithNoSignatureIssueNoCursor(t *testing.T) { - // A NaN has no JSON form, so the filters cannot be bound into a cursor: - // the page still reports that a further page exists, without one. db, _ := session(t, sqltest.WithTotal(members("a", "b", "c"), 9)) got, err := memberView(t).List(context.Background(), db, query.Directives{ Filters: []query.Filter{{Field: "name", Op: query.OpEq, Value: math.NaN()}}, @@ -217,11 +197,7 @@ func TestList_FiltersWithNoSignatureIssueNoCursor(t *testing.T) { func TestContinue_RefusesAnOrderingItCannotContinue(t *testing.T) { c := issue(t, nil) - // A nullable field in the keyed prefix: the keyset predicate cannot - // compare it, so the sort cannot be continued. nullable := []query.Sort{{Field: "name"}, {Field: "org"}, {Field: "id"}} - // Two directions across the keyed prefix: one comparison cannot serve - // both. mixed := []query.Sort{{Field: "org"}, {Field: "id", Descending: true}} for name, sorts := range map[string][]query.Sort{"nullable field": nullable, "mixed directions": mixed} { db, rec := session(t) @@ -239,8 +215,6 @@ func TestContinue_RefusesAnOrderingItCannotContinue(t *testing.T) { func TestContinue_RefusesTextItDidNotIssue(t *testing.T) { issued := issue(t, nil) - // A type change under the same base, prefix, and direction: the keyed - // fields' declared types are bound into the cursor, not only carried in it. retyped := catalog().MustCompile(fstest.MapFS{ "sql/member.sql": {Data: []byte("--| tier: standard\n--| key: org, id\n--| field: org uuid not null\n--| field: id text not null\n--| field: name text\n" + memberBase)}, }, "sql", sqltest.Dialect{}).Statement("member").Project(scanMember) @@ -256,10 +230,6 @@ func TestContinue_RefusesTextItDidNotIssue(t *testing.T) { "too short": {memberView(t), "AQI", malformed}, "retyped field": {retyped, issued, malformed}, } - // The cursor is opaque, so every single-character change to the text it - // issued is text it did not issue: refused as malformed, or as naming - // another base, ordering, or filters when the change reads as one. The - // last character is left out: it may carry bits that encode nothing. const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" for i := range len(issued) - 1 { swap := alphabet[(strings.IndexByte(alphabet, issued[i])+1)%len(alphabet)] @@ -280,8 +250,6 @@ func TestContinue_RefusesTextItDidNotIssue(t *testing.T) { } func TestList_KeyedColumnsAreMatchedInThePagesOwnCase(t *testing.T) { - // An engine folds an unquoted alias's case, so the keyed field is found - // case-insensitively when no column matches it exactly. folded := sqltest.Response{Columns: []string{"ORG", "ID", "NAME"}, Rows: [][]driver.Value{ {"o", "a", "M"}, {"o", "b", "M"}, {"o", "c", "M"}, }} @@ -301,8 +269,6 @@ func TestList_AKeyedFieldThePageDoesNotOutputIsTheContractsDefect(t *testing.T) } func TestList_NullInAKeyedColumnIsTheBasesDefect(t *testing.T) { - // The page's last row carries a null where the contract declared the - // field not null, so no cursor can be issued from it. db, _ := session(t, sqltest.WithTotal(members("a", nil, "c"), 9)) _, err := memberView(t).List(context.Background(), db, query.Directives{}, query.Page{Number: 1, Size: 2}) if err == nil { diff --git a/query/guard.go b/query/guard.go index 8c63734..5c236f4 100644 --- a/query/guard.go +++ b/query/guard.go @@ -73,9 +73,6 @@ func (g Guard) Run(ctx context.Context, s sqlate.Session, version int64, args Ar if err != nil { return 0, err } - // Unreachable for a plain Guard, whose command matches on the key and - // the version alone: a row at the expected version would have matched - // the update. Kept for shape-consistency with RowGuard.Run. if current == version { return 0, fmt.Errorf("%w: version %d unchanged", ErrRefused, version) } diff --git a/query/guard_test.go b/query/guard_test.go index 900ed05..458d894 100644 --- a/query/guard_test.go +++ b/query/guard_test.go @@ -18,11 +18,8 @@ import ( var guardFiles = fstest.MapFS{ "sql/edit.sql": {Data: []byte("--| tier: standard\nUPDATE organization SET name = {{name}}, version = version + 1 WHERE id = {{id}} AND version = {{version}}")}, "sql/version.sql": {Data: []byte("--| tier: standard\nSELECT version FROM organization WHERE id = {{id}}")}, - // The claim command's WHERE carries a predicate of its own, so a row at - // the expected version can still refuse the write; it reads its row back - // through item. - "sql/claim.sql": {Data: []byte("--| tier: standard\n--| returning: item\nUPDATE item SET owner = {{owner}}, version = version + 1 WHERE id = {{id}} AND version = {{version}} AND status = 'pending'")}, - "sql/item.sql": {Data: []byte("--| tier: standard\nSELECT id, status, version FROM item WHERE id = {{id}}")}, + "sql/claim.sql": {Data: []byte("--| tier: standard\n--| returning: item\nUPDATE item SET owner = {{owner}}, version = version + 1 WHERE id = {{id}} AND version = {{version}} AND status = 'pending'")}, + "sql/item.sql": {Data: []byte("--| tier: standard\nSELECT id, status, version FROM item WHERE id = {{id}}")}, } type item struct { @@ -43,8 +40,6 @@ func guard(t *testing.T) query.Guard { return stmts.Statement("edit").Guarded(stmts.Statement("version"), "version") } -// rowGuard is the claim guard compiled for d: sqltest.Dialect runs the -// fallback, sqltest.ReturningDialect the single-statement form. func rowGuard(t *testing.T, d sqlate.Dialect) query.RowGuard[item] { t.Helper() stmts := catalog().MustCompile(guardFiles, "sql", d) @@ -104,9 +99,6 @@ func TestGuard_CommandFailurePassesThroughMapped(t *testing.T) { } } -// forms are the two ways a returning command runs: the fallback, the -// command and then its read in one transaction, and the single-statement -// form of a dialect with query.Returner. var forms = []struct { name string dialect sqlate.Dialect @@ -116,7 +108,6 @@ var forms = []struct { {"native", sqltest.ReturningDialect{}, true}, } -// statements counts the exec and query calls, the statements the engine ran. func statements(rec *sqltest.Recorder) int { n := 0 for _, op := range rec.Ops() { @@ -127,7 +118,6 @@ func statements(rec *sqltest.Recorder) int { return n } -// firstStatement is the first exec or query call, the command. func firstStatement(rec *sqltest.Recorder) sqltest.Call { calls := rec.Calls() i := slices.IndexFunc(calls, func(c sqltest.Call) bool { return c.Op == sqltest.OpExec || c.Op == sqltest.OpQuery }) @@ -142,7 +132,7 @@ func TestRowGuard_Outcomes(t *testing.T) { cases := []struct { name string fallback, native []sqltest.Response - statements [2]int // fallback, native + statements [2]int check func(t *testing.T, row item, err error) }{ { diff --git a/query/main_test.go b/query/main_test.go index a5ba249..b9cdf17 100644 --- a/query/main_test.go +++ b/query/main_test.go @@ -4,12 +4,9 @@ import ( "os" "testing" "time" - _ "time/tzdata" // Europe/London loads on a host without a zone database. + _ "time/tzdata" ) -// TestMain runs the package's tests with time.Local set to Europe/London, -// so a time the package returned in time.Local, not time.UTC, fails the -// tests' == comparisons whatever zone the host runs in. func TestMain(m *testing.M) { london, err := time.LoadLocation("Europe/London") if err != nil { diff --git a/query/mapper.go b/query/mapper.go index 5031093..871855f 100644 --- a/query/mapper.go +++ b/query/mapper.go @@ -8,20 +8,6 @@ import ( "sync" ) -// The struct-tag mapper: an entity's tags are its binding and scan -// contract, so a program writes neither scan functions nor Args literals. -// A field's column name is its `db` tag, else its `json` tag's name, else -// the field name lowercased; `db:"-"` excludes it. An untagged embedded -// struct flattens: its fields become columns of the outer type, as if -// declared there, and an outer field of the same name shadows one reached -// through an embed. A tagged embedded struct is one column instead, -// holding the whole embedded value; an embedded pointer contributes no -// column; the embedded type must itself be exported, since an unexported -// field is invisible to reflection. Column and parameter names coincide -// with the API vocabulary by convention, since a base aliases its output -// columns to the contract names, which is why the json tag is the usual -// source and db the override. - // Scanner returns the ScanFunc for T from its tags: each row's columns are // matched to fields by name, in the row's order, and scanned into a fresh // T. A column T has no field for is an error, so a SELECT list that grows @@ -92,15 +78,8 @@ func (a Args) With(name string, v any) Args { return out } -var fieldCache sync.Map // reflect.Type → map[string][]int +var fieldCache sync.Map -// fieldsOf indexes a struct type's exported fields by column name, once -// per type. Each name maps to the field's index path, which -// reflect.Value.FieldByIndex resolves: an untagged embedded struct is -// flattened, so the path reaches through it to the field it holds. A -// tagged embedded field is one column holding the whole embedded value, -// an embedded pointer contributes no column at all, and `db:"-"` -// excludes a field or an embedded struct entirely. func fieldsOf(t reflect.Type) map[string][]int { if m, ok := fieldCache.Load(t); ok { return m.(map[string][]int) @@ -137,10 +116,6 @@ func fieldsOf(t reflect.Type) map[string][]int { } m[name] = []int{i} } - // This type's own fields are indexed above and the embedded ones - // below, so a name declared here shadows the same name reached - // through an embedded struct; between two embedded structs offering - // one name, the one declared first wins. for _, i := range embedded { for name, path := range fieldsOf(t.Field(i).Type) { if _, taken := m[name]; taken { diff --git a/query/mapper_test.go b/query/mapper_test.go index de279b0..2bf3992 100644 --- a/query/mapper_test.go +++ b/query/mapper_test.go @@ -25,14 +25,11 @@ type entity struct { hidden int //nolint:unused // proves unexported fields are skipped } -// Identity is embedded by the types below. An embedded field takes the -// name of its type, so the type is exported to be indexed at all. type Identity struct { ID string `json:"id"` CreatedAt time.Time `json:"created_at"` } -// Audit is embedded by pointer, which contributes no column. type Audit struct { Editor string `json:"editor"` } @@ -58,7 +55,7 @@ type auditable struct { } func TestScanner_MatchesColumnsToTagsInRowOrder(t *testing.T) { - now := time.Now().UTC() // a scan returns times in UTC + now := time.Now().UTC() db, rec := session(t, sqltest.Response{ Columns: []string{"name", "id", "nickname", "parent_id", "created_at", "plain"}, Rows: [][]driver.Value{{"Acme", "a", "ac", nil, now, int64(7)}}, @@ -88,8 +85,6 @@ func TestScanner_UnknownColumnIsAnError(t *testing.T) { } } -// fakeRow is a Row that is not *sql.Rows: the shape of an adapter that -// shows a scan fewer columns than the statement returns. type fakeRow struct { cols []string vals []any @@ -108,7 +103,7 @@ func (r *fakeRow) Scan(dest ...any) error { } func TestScanner_ReadsAnyRow(t *testing.T) { - now := time.Now().UTC() // a scan returns times in UTC + now := time.Now().UTC() row := &fakeRow{ cols: []string{"plain", "id", "created_at"}, vals: []any{int64(3), "a", now}, @@ -156,7 +151,7 @@ func TestArgsOf_BindsByColumnName(t *testing.T) { } func TestEmbedded_FieldsAreColumnsInBothDirections(t *testing.T) { - now := time.Now().UTC() // a scan returns times in UTC + now := time.Now().UTC() db, rec := session(t, sqltest.Response{ Columns: []string{"name", "id", "created_at"}, Rows: [][]driver.Value{{"Acme", "a", now}}, @@ -181,7 +176,7 @@ func TestEmbedded_FieldsAreColumnsInBothDirections(t *testing.T) { } func TestEmbedded_OuterFieldShadowsTheEmbeddedOne(t *testing.T) { - now := time.Now().UTC() // a scan returns times in UTC + now := time.Now().UTC() db, _ := session(t, sqltest.Response{ Columns: []string{"id", "created_at"}, Rows: [][]driver.Value{{"outer", now}}, diff --git a/query/params.go b/query/params.go index fb00d12..63bb96a 100644 --- a/query/params.go +++ b/query/params.go @@ -8,55 +8,26 @@ import ( "strings" ) -// A parameter is written {{name}}, or {{name:type}} to bind it through -// CAST to an SQL type, standard or the engine's own as the file's tier -// declares; the type is the author's and is written into the SQL verbatim, -// where Verify catches a name the engine does not know. {{name...}} and -// {{name...:type}} expand: the argument is a non-empty slice, and the -// parameter renders as one placeholder per element, so an IN list binds -// as values and never as text. Whitespace inside the braces is allowed. -// The delimiter is reserved: it means a parameter wherever it appears in -// the body, string literals and comments included, so the body needs no -// lexer, and a {{ that does not form a parameter is a load error. var ( parameter = regexp.MustCompile(`\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*(\.\.\.)?\s*(?::\s*(` + typeToken + `)\s*)?\}\}`) opener = "{{" ) -// A pattern include is written {{> name}} and is resolved at load, before -// the parameters are; see patterns.go. - -// typeToken is an SQL type as written in a cast or a field contract: a -// name, optionally with a length or precision, such as text, uuid, -// numeric(12,2), or varchar(200). const typeToken = `[A-Za-z_][A-Za-z0-9_ ]*?(?:\([0-9]+(?:\s*,\s*[0-9]+)?\))?` var sqlType = regexp.MustCompile(`^` + typeToken + `$`) -// param is one declared parameter: its name and whether it expands. A -// name that occurs with and without expansion is a load error: a parameter -// has one arity. The type is the occurrence's, so a name may cast where it -// needs to and bind plain elsewhere. type param struct { name string expand bool } -// occurrence is one place a parameter appears in the body, in the -// template an expanded statement renders at bind: the text before it, the -// parameter's index, and the type this occurrence casts through (empty -// for none). type occurrence struct { before string index int typ string } -// compiled is the rewrite's result. For a statement with no expansion, text -// is final and the parameters' positions are their first occurrences. For -// an expanded statement the text depends on each list's length, so the -// body is kept as occurrences and rendered at bind; text is then the -// arity-one rendering, what Verify prepares and Text reports. type compiled struct { text string params []param @@ -64,10 +35,6 @@ type compiled struct { tail string } -// rewrite resolves the parameters of body to the dialect's positional -// placeholders. Each distinct name takes the position of its first -// occurrence; later occurrences rebind to it; an expanded name takes as -// many consecutive positions as its list has elements. func rewrite(body string, placeholder func(int) string) (compiled, error) { var c compiled index := map[string]int{} @@ -106,8 +73,6 @@ func rewrite(body string, placeholder func(int) string) (compiled, error) { return c, nil } -// render writes the body with placeholders assigned in first-occurrence -// order, an expanded parameter taking arity(i) consecutive positions. func (c compiled) render(placeholder func(int) string, arity func(int) int) string { var out strings.Builder start := make([]int, len(c.params)) @@ -146,9 +111,6 @@ func (c compiled) render(placeholder func(int) string, arity func(int) int) stri return out.String() } -// arities reads each expanded parameter's list length from args, and -// returns the cache key naming them. A missing argument, a non-slice, or an -// empty list is an ArgumentError. func (c compiled) arities(statement string, args Args) ([]int, string, error) { n := make([]int, len(c.params)) var key strings.Builder @@ -174,8 +136,6 @@ func (c compiled) arities(statement string, args Args) ([]int, string, error) { return n, key.String(), nil } -// malformed reports a {{ that does not open a parameter, quoting the text -// from it to the end of its line. func malformed(body string, at int) error { rest := body[at:] if i := strings.IndexByte(rest, '\n'); i >= 0 { diff --git a/query/params_test.go b/query/params_test.go index 7a5c12d..78dd2b4 100644 --- a/query/params_test.go +++ b/query/params_test.go @@ -12,7 +12,6 @@ import ( "github.com/standards-lab/sqlate/sqltest" ) -// load parses one file through Load, the only public path to the scanner. func load(t *testing.T, text string) query.Statement { t.Helper() stmts, err := catalog().Compile(fstest.MapFS{"sql/s.sql": {Data: []byte(text)}}, "sql", sqltest.Dialect{}) @@ -51,8 +50,6 @@ func TestParams_Syntax(t *testing.T) { } } -// The header is not scanned and not sent: a {{ in a declaration's prose is -// neither a parameter nor an error, and the engine receives the body only. func TestParams_HeaderIsNotScannedOrSent(t *testing.T) { st := load(t, "--| tier: native\n--| native: postgres — binds {{key}} to pg_advisory_xact_lock\n-- prose\n\nSELECT pg_advisory_xact_lock({{key}})") if st.Text() != "SELECT pg_advisory_xact_lock($1)" { @@ -80,10 +77,6 @@ func TestParams_MalformedIsALoadError(t *testing.T) { } } -// An expanded parameter renders one placeholder per element of its list, -// typed when declared so, the positions of every other parameter shifting -// with it; the rendering is cached by the lists' lengths and Text is the -// arity-one form Verify prepares. func TestExpansion_RendersOnePlaceholderPerElement(t *testing.T) { stmt := load(t, "--| tier: standard\nSELECT 1 FROM t WHERE tenant = {{tenant}} AND id IN ({{ids...:uuid}}) AND status = {{status}}") if got := stmt.Text(); got != "SELECT 1 FROM t WHERE tenant = $1 AND id IN (CAST($2 AS uuid)) AND status = $3" { diff --git a/query/patterns.go b/query/patterns.go index 9952d02..8684609 100644 --- a/query/patterns.go +++ b/query/patterns.go @@ -13,26 +13,6 @@ import ( "github.com/standards-lab/sqlate/header" ) -// The pattern catalog: reusable protocol SQL, authored as files, each -// declaring its tier, published under a namespace. A pattern's body contains -// slots in the {{ }} syntax; a pattern contains slots only and never includes -// another, so it reads on its own. Two uses: -// -// - at request time, the collection read composes its page, counted or -// not, and its single-row read from the library's patterns over a -// program's base and the request's declarations; the library fills the -// slots with text it composed from other patterns, never with request -// input; -// - at load time, a statement includes a pattern with {{> namespace.name}}, -// and the pattern's text is spliced in before parameters are rewritten, -// so a protocol's predicate and columns are written once. -// -// Any package may publish patterns: the library's own are Patterns(), an -// application registers its namespace beside them, and an engine overlays -// the library's request-time patterns it must spell differently. The -// catalog is built once, where the program starts, and every set of -// statements is compiled against it. - //go:embed patterns/*.sql var patternFiles embed.FS @@ -64,7 +44,6 @@ type Pattern struct { Text string } -// layer is one directory of pattern files. type layer struct { fsys fs.FS dir string @@ -121,8 +100,6 @@ func (s Source) Overlay(fsys fs.FS, dir string) Source { return s } -// pattern is one catalog entry: its body, tier, the slots it declares, and -// the alternate slots an overlay may declare in their place. type pattern struct { name string tier Tier @@ -245,11 +222,6 @@ func (c *Catalog) Patterns() []Pattern { return out } -// readLayer reads every pattern file of one directory: the header must -// declare a tier, a native tier its port, and the body's {{ }} occurrences -// are its slots; an include inside a pattern is an error. An optional -// alternate declaration names the slots an overlay may declare in place of -// the body's own, as a comma-separated list. func readLayer(ns string, l layer) (map[string]pattern, error) { entries, err := fs.ReadDir(l.fsys, l.dir) if err != nil { @@ -315,8 +287,6 @@ func readLayer(ns string, l layer) (map[string]pattern, error) { return out, errors.Join(errs...) } -// sameSet reports whether two slot lists name the same slots, in any order -// and multiplicity. func sameSet(a, b []string) bool { set := func(xs []string) map[string]bool { m := map[string]bool{} @@ -337,7 +307,6 @@ func sameSet(a, b []string) bool { return true } -// lookup finds a pattern by qualified name. func (c *Catalog) lookup(ns, name string) (pattern, bool) { set, ok := c.namespaces[ns] if !ok { @@ -347,12 +316,6 @@ func (c *Catalog) lookup(ns, name string) (pattern, bool) { return p, ok } -// render fills one of the library's request-time patterns, resolved under -// Namespace, which only the library's source registers under. Every slot the -// pattern declares must be filled; a fill that names no slot is ignored, -// which is how one call serves a pattern's own slots and its alternate set. -// An unfilled slot is a defect in the library or an overlay, not a request -// error, and panics. func (c *Catalog) render(name string, fill map[string]string) string { set, ok := c.namespaces[Namespace] if !ok { @@ -372,11 +335,6 @@ func (c *Catalog) render(name string, fill map[string]string) string { }) } -// expand splices {{> namespace.name}} includes into a statement body, so a -// statement contains a pattern's text as if authored there. An unqualified -// include, an unknown namespace or pattern, or a native pattern in a -// standard-tier statement is a load error naming it. Patterns contain no -// includes, so one pass expands everything. func (c *Catalog) expand(body string, tier Tier) (string, error) { var err error body = bare.ReplaceAllStringFunc(body, func(m string) string { diff --git a/query/patterns_test.go b/query/patterns_test.go index 480db92..c31763d 100644 --- a/query/patterns_test.go +++ b/query/patterns_test.go @@ -11,8 +11,6 @@ import ( "github.com/standards-lab/sqlate/sqltest" ) -// A statement file includes the guard patterns; the spliced text binds the -// pattern's parameters like the file's own. func TestLoad_ExpandsPatternIncludes(t *testing.T) { st := load(t, "--| tier: standard\nUPDATE t SET a = {{a}}, {{> sql.guard_set}}\nWHERE {{> sql.guard_where}}") if st.Text() != "UPDATE t SET a = $1, updated_at = CURRENT_TIMESTAMP, version = version + 1\nWHERE id = $2 AND version = $3" { @@ -37,8 +35,6 @@ func TestLoad_RejectsBadIncludes(t *testing.T) { } } -// The guard runs over the included patterns exactly as over hand-written -// text. func TestGuard_OverIncludedPatterns(t *testing.T) { stmts := catalog().MustCompile(fstest.MapFS{ "sql/edit.sql": {Data: []byte("--| tier: standard\nUPDATE t SET a = {{a}}, {{> sql.guard_set}} WHERE {{> sql.guard_where}}")}, @@ -54,8 +50,6 @@ func TestGuard_OverIncludedPatterns(t *testing.T) { } } -// A port overlays the library's paging: the collection read composes with -// the port's spelling and the slots the library fills are unchanged. func TestOverlay_RespellsPagingForAPort(t *testing.T) { mysql := fstest.MapFS{"port/paging.sql": {Data: []byte("--| tier: native\n--| native: mysql — LIMIT/OFFSET\n LIMIT {{fetch}} OFFSET {{offset}}")}} c := query.MustCatalog(query.Patterns().Overlay(mysql, "port")) @@ -69,9 +63,6 @@ func TestOverlay_RespellsPagingForAPort(t *testing.T) { if _, err := view.List(context.Background(), db, query.Directives{}, query.Page{Number: 3, Size: 4}); err != nil { t.Fatal(err) } - // The library binds offset then fetch, whatever order the port's text - // names them in; the page fetches one row past its size. - // The counted page takes the same respelling. for i, want := range []string{ "SELECT * FROM (SELECT id FROM t) q ORDER BY q.id LIMIT $2 OFFSET $1", "SELECT * FROM (SELECT q.*, COUNT(*) OVER () AS sqlate_total FROM (SELECT id FROM t) q) q ORDER BY q.id LIMIT $2 OFFSET $1", @@ -86,8 +77,6 @@ func TestOverlay_RespellsPagingForAPort(t *testing.T) { } } -// A pattern declares an alternate slot set, and an overlay respells it with -// either that set or the pattern's own; any other set is still refused. func TestOverlay_AcceptsAPatternsAlternateSlots(t *testing.T) { base := query.Publish("app", fstest.MapFS{ "p/paging.sql": {Data: []byte("--| tier: standard\n--| alternate: x, y\nLIMIT {{a}}")}, @@ -133,8 +122,6 @@ func TestNewCatalog_RejectsWhatItCannotCompose(t *testing.T) { } } -// An application publishes its namespace beside the library's, and a -// statement includes from both; an alias renames the application's. func TestCompile_IncludesAcrossNamespacesAndAliases(t *testing.T) { app := query.Publish("app", fstest.MapFS{ "p/identity.sql": {Data: []byte("--| tier: native\n--| native: postgres — RETURNING\nRETURNING id, version")}, @@ -156,8 +143,6 @@ func TestCompile_IncludesAcrossNamespacesAndAliases(t *testing.T) { } } -// A native pattern spliced into a standard-tier statement would hide the -// port; the compile refuses it. func TestCompile_RefusesANativePatternInAStandardStatement(t *testing.T) { app := query.Publish("app", fstest.MapFS{"p/identity.sql": {Data: []byte("--| tier: native\n--| native: postgres — RETURNING\nRETURNING id")}}, "p") _, err := query.MustCatalog(query.Patterns(), app).Compile(fstest.MapFS{ @@ -168,9 +153,6 @@ func TestCompile_RefusesANativePatternInAStandardStatement(t *testing.T) { } } -// A pattern file that NewCatalog cannot read is a catalog error naming the -// file and its namespace: no tier, a tier it does not know, a native -// declaration on the wrong tier, or an include inside a pattern. func TestNewCatalog_RejectsMalformedPatterns(t *testing.T) { cases := map[string]string{ "no tier": "SELECT {{a}}", @@ -187,8 +169,6 @@ func TestNewCatalog_RejectsMalformedPatterns(t *testing.T) { } } -// The inventory lists every registered pattern ordered by namespace, then -// name, each with its tier, native note, slots in body order, and body. func TestCatalog_PatternsReportsTheInventoryInOrder(t *testing.T) { c := query.MustCatalog( query.Publish("zeta", fstest.MapFS{"p/b.sql": {Data: []byte("--| tier: standard\nWHERE {{second}} = {{first}}")}}, "p"), @@ -215,9 +195,6 @@ func TestCatalog_PatternsReportsTheInventoryInOrder(t *testing.T) { } } -// A projection composes its reads from the library's patterns, so a catalog -// without them cannot serve one: the read is a defect in the program's -// wiring and panics, naming what is missing. func TestProjection_PanicsWithoutTheLibrarysPatterns(t *testing.T) { app := query.Publish("app", fstest.MapFS{"p/x.sql": {Data: []byte("--| tier: standard\nSELECT 1")}}, "p") db, rec := session(t) diff --git a/query/projection.go b/query/projection.go index 33a7078..14a3d0a 100644 --- a/query/projection.go +++ b/query/projection.go @@ -72,9 +72,6 @@ const ( // an empty page other than the first List page has no row to carry it. const NoTotal = -1 -// totalColumn is the reserved name of the count's column, the last output -// column of a counted page. The library reads it and never shows it to a -// scan, and no contract field may take the name. const totalColumn = "sqlate_total" // Collection is one page of a collection read: the items, the total under @@ -123,7 +120,6 @@ type Projection[T any] struct { fields map[string]Field } -// newProjection is Statement.Project. func newProjection[T any](base Statement, scan ScanFunc[T]) Projection[T] { if base.returning != nil { panic(fmt.Sprintf("query: %s: a returning command is not a projection base", base.name)) @@ -138,8 +134,6 @@ func newProjection[T any](base Statement, scan ScanFunc[T]) Projection[T] { } fields := make(map[string]Field, len(base.fields)) for _, f := range base.fields { - // An engine folds an unquoted name's case, so the reserved name is - // refused in any case. if strings.EqualFold(f.Name, totalColumn) { panic(fmt.Sprintf("query: %s: field %q is the name the library reserves for the page's total", base.name, f.Name)) } @@ -182,9 +176,6 @@ func (p Projection[T]) Continue(ctx context.Context, s sqlate.Session, d Directi return p.list(ctx, s, d, size, 0, after, base) } -// list is the shared body of List and Continue: bind, filter, resolve the -// order, then read one page, by offset when after is empty and past the -// cursor's position otherwise, counted when the request asks for the total. func (p Projection[T]) list(ctx context.Context, s sqlate.Session, d Directives, size, offset int, after Cursor, base []Args) (Collection[T], error) { var none Collection[T] if d.Total != TotalExact && d.Total != TotalNone { @@ -220,9 +211,6 @@ func (p Projection[T]) list(ctx context.Context, s sqlate.Session, d Directives, } defer func() { _ = rows.Close() }() - // Under TotalExact, the consumer's scan reads through an adapter that - // hides the trailing count column and scans the count with the row; the - // library's own reads below read the full row, count column included. var row Row = rows var adapter *countedRow if counted { @@ -236,8 +224,6 @@ func (p Projection[T]) list(ctx context.Context, s sqlate.Session, d Directives, row = adapter } - // The keyed columns are located once for the row set, and only when a - // cursor can be issued at all. var index []int var width int if o.cursorable { @@ -255,8 +241,6 @@ func (p Projection[T]) list(ctx context.Context, s sqlate.Session, d Directives, more := false for rows.Next() { if len(out) == size { - // The row past the page: it is never scanned, and its only - // report is that a further page exists. more = true break } @@ -286,15 +270,10 @@ func (p Projection[T]) list(ctx context.Context, s sqlate.Session, d Directives, case len(out) > 0: total = int(adapter.total) case after == "" && offset == 0: - // An empty first page is an empty result: nothing is under the - // filters. An empty later page only says the offset is past the - // end, which carries no count. total = 0 } c := Collection[T]{Items: out, Total: total, More: more} if more && last != nil { - // Filters with no signature cannot be bound into a cursor, so the - // page reports a further page without one. if sig, ok := filterSignature(d.Filters); ok { c.Next = p.encodeCursor(o, sig, last) } @@ -346,8 +325,6 @@ func (p Projection[T]) Verify(ctx context.Context, db sqlate.Session) error { predicates := make([]string, 0, len(p.base.fields)) for _, f := range p.base.fields { cols = append(cols, "q."+f.Name) - // The probe is only ever prepared, never executed, so the cast takes - // the literal NULL in place of a placeholder and binds nothing. value := p.base.catalog.render("value", map[string]string{"placeholder": "NULL", "type": f.Type}) predicates = append(predicates, p.base.catalog.render("filter_eq", map[string]string{"field": f.Name, "value": value})) } @@ -360,11 +337,7 @@ func (p Projection[T]) Verify(ctx context.Context, db sqlate.Session) error { return err } - // The base's own parameters keep the placeholders they compiled with, so - // the binding starts with one unbound value each and the request-time - // placeholders follow them; a prepare binds nothing. b := &binding{dialect: p.base.dialect, catalog: p.base.catalog, values: make([]any, len(p.base.compiled.params))} - // The key alone, ascending: no sort names a field, so this cannot fail. o, _ := p.order(nil) for _, probe := range []struct { name string @@ -383,35 +356,22 @@ func (p Projection[T]) Verify(ctx context.Context, db sqlate.Session) error { return nil } -// binding is one composed read's bind list, in the page text's placeholder -// order: the base's own values, the filters', the cursor's, then the paging -// bounds. Each request value sits at the position its placeholder was -// allocated, so a dialect with positional placeholders reads them in order. type binding struct { dialect sqlate.Dialect catalog *Catalog values []any } -// value binds v at the next position and returns it as the value pattern's -// text, cast to field's declared type. func (b *binding) value(field Field, v any) string { b.values = append(b.values, v) return b.catalog.render("value", map[string]string{"placeholder": b.dialect.Placeholder(len(b.values)), "type": field.Type}) } -// raw binds v at the next position and returns its bare placeholder, for -// the paging bounds. func (b *binding) raw(v any) string { b.values = append(b.values, v) return b.dialect.Placeholder(len(b.values)) } -// bind seeds a binding with the base's own values in its parameter order, -// so every request-time placeholder is numbered after the base's. base is -// merged left to right, a later value winning; a parameter no Args names -// is an ArgumentError, and an extra name is ignored as Statement.bind -// ignores it. func (p Projection[T]) bind(base []Args) (*binding, error) { b := &binding{dialect: p.base.dialect, catalog: p.base.catalog} if len(p.base.compiled.params) == 0 { @@ -432,9 +392,6 @@ func (p Projection[T]) bind(base []Args) (*binding, error) { return b, nil } -// predicates lowers the filters to one predicate each, in filter order: the -// operator's filter pattern over the field, each request value bound through -// the value pattern's cast to the field's declared type. func (p Projection[T]) predicates(b *binding, filters []Filter) ([]string, error) { if len(filters) == 0 { return nil, nil @@ -468,7 +425,6 @@ func (p Projection[T]) predicates(b *binding, filters []Filter) ([]string, error return predicates, nil } -// clause renders the WHERE clause over predicates; empty when there are none. func (p Projection[T]) clause(predicates []string) string { if len(predicates) == 0 { return "" @@ -476,12 +432,6 @@ func (p Projection[T]) clause(predicates []string) string { return p.base.catalog.render("where", map[string]string{"predicates": strings.Join(predicates, " AND ")}) } -// page composes the page text: the base as a derived table under the -// filters' predicates and the keyset predicate, ordered by o, with offset -// and fetch bound last. When counted, the filters apply inside the window -// that counts the rows and the keyset predicate outside it, so a cursor -// narrows the page but not the total. Either way the keyset's values bind -// after the filters', their order in the text. func (p Projection[T]) page(b *binding, predicates, keyset []string, o ordering, offset, fetch int, counted bool) string { paging := p.base.catalog.render("paging", map[string]string{"offset": b.raw(offset), "fetch": b.raw(fetch)}) if counted { @@ -490,25 +440,13 @@ func (p Projection[T]) page(b *binding, predicates, keyset []string, o ordering, return p.base.catalog.render("collection", map[string]string{"base": p.base.compiled.text, "where": p.clause(append(slices.Clip(predicates), keyset...)), "order": o.text, "paging": paging}) } -// countedRow is the Row a scan reads a counted page through: it shows the -// page's columns without the trailing count, and each Scan reads the count -// alongside the consumer's destinations, recording that the row was read. type countedRow struct { - rows *sql.Rows - // cols is the page's columns without the count, the columns a scan sees. + rows *sql.Rows cols []string total int64 - // read reports whether the current row's Scan ran; the caller resets - // it before each row. - read bool + read bool } -// newCountedRow returns the adapter over a counted page of the base named -// base, whose output columns are cols. The count must be the last column -// and the only one of its name, in any case: a pattern overlay that moved -// the count would otherwise hide a real column and read it as the total, -// and a base that outputs a column of the name, declared or not, would -// read as a second count. func newCountedRow(base string, rows *sql.Rows, cols []string) (*countedRow, error) { if len(cols) == 0 || !strings.EqualFold(cols[len(cols)-1], totalColumn) { last := "" @@ -524,18 +462,10 @@ func newCountedRow(base string, rows *sql.Rows, cols []string) (*countedRow, err return &countedRow{rows: rows, cols: visible}, nil } -// Columns returns the page's columns without the trailing count. func (c *countedRow) Columns() ([]string, error) { - // A copy, as sql.Rows.Columns returns one, so a scan that changes it - // changes nothing here. return slices.Clone(c.cols), nil } -// Scan scans the row into dest and the count into the adapter, and records -// that the row was read. dest is checked against the columns the scan sees, -// in database/sql's words, so a wrong count is reported without the hidden -// column. Scan copies dest rather than appending to it, so the caller's -// slice is left as it was. func (c *countedRow) Scan(dest ...any) error { if len(dest) != len(c.cols) { return fmt.Errorf("sql: expected %d destination arguments in Scan, not %d", len(c.cols), len(dest)) @@ -547,36 +477,19 @@ func (c *countedRow) Scan(dest ...any) error { return c.rows.Scan(all...) } -// term is one ORDER BY term. type term struct { field Field desc bool } -// ordering is a request's resolved sort: every ORDER BY term after the key -// fields were appended, the keyed prefix a cursor continues from, its shared -// direction, whether a cursor can continue it, and the rendered clause. type ordering struct { - // terms is the caller's sorts, then each key field absent from them, in - // key order. - terms []term - // keyed is the shortest prefix of terms that contains every key field: - // the terms a cursor records, since they order the rows uniquely. - keyed []term - // desc is the keyed prefix's shared direction; false when it has none. - desc bool - // cursorable reports one direction across the keyed prefix and every - // field in it declared not null, the two conditions the keyset predicate - // needs to select exactly the rows past a cursor's row. + terms []term + keyed []term + desc bool cursorable bool - // text is the ORDER BY clause. - text string + text string } -// order resolves the sorts against the field contract and appends the key -// fields the caller did not sort by, so the ordering is total. An appended -// key field takes the keyed prefix's direction, since a cursor compares the -// whole prefix one way. func (p Projection[T]) order(sorts []Sort) (ordering, error) { var o ordering o.terms = make([]term, 0, len(sorts)+len(p.base.key)) @@ -587,8 +500,6 @@ func (p Projection[T]) order(sorts []Sort) (ordering, error) { } o.terms = append(o.terms, term{field: f, desc: s.Descending}) } - // The keyed prefix reaches the last key field the caller sorted by; a key - // field the caller left out is appended, so the prefix is every term. covered, last := 0, -1 for _, k := range p.base.key { for i, t := range o.terms { @@ -632,11 +543,6 @@ func (p Projection[T]) order(sorts []Sort) (ordering, error) { return o, nil } -// keyset composes the keyset predicate for continuing past values under o: -// each keyed value bound once, cast to its field's type, then the expanded -// chain of disjuncts for the standard spelling and the column, operator, and -// value lists for an overlay's row-value spelling; render takes whichever -// slots the catalog's pattern declares. func (p Projection[T]) keyset(b *binding, o ordering, values []string) string { bound := make([]string, len(o.keyed)) columns := make([]string, len(o.keyed)) @@ -669,10 +575,6 @@ func (p Projection[T]) keyset(b *binding, o ordering, values []string) string { }) } -// keyedColumns locates each keyed term among the page's columns: the base's -// output column of the same name, matched exactly, else case-insensitively, -// since an engine folds an unquoted alias's case. A keyed field the page does -// not output is the contract's defect, which Verify reports at startup. func (p Projection[T]) keyedColumns(cols []string, o ordering) ([]int, error) { index := make([]int, len(o.keyed)) for k, t := range o.keyed { @@ -688,9 +590,6 @@ func (p Projection[T]) keyedColumns(cols []string, o ordering) ([]int, error) { return index, nil } -// readKeyed scans the current row a second time, into untyped destinations, -// and renders the keyed values as text; it runs before the consumer's scan -// because a scan into sql.RawBytes forbids a later Scan of the same row. func (p Projection[T]) readKeyed(rows *sql.Rows, width int, index []int, o ordering) ([]string, error) { dests := make([]any, width) for i := range dests { @@ -710,10 +609,6 @@ func (p Projection[T]) readKeyed(rows *sql.Rows, width int, index []int, o order return out, nil } -// cursorValue renders a driver value as the text the field's CAST reads -// back: the driver.Value kinds database/sql delivers, a text column a driver -// returns as bytes included. A null is a contract violation, since a keyed -// field is declared not null. func cursorValue(v any) (string, error) { switch v := v.(type) { case nil: @@ -729,17 +624,12 @@ func cursorValue(v any) (string, error) { case bool: return strconv.FormatBool(v), nil case time.Time: - // In UTC, so the cursor's text is the same on every host whatever - // location the driver gave the value; the CAST reads the offset. return v.UTC().Format(time.RFC3339Nano), nil default: return fmt.Sprint(v), nil } } -// engine classifies a query failure: a data exception (a value the engine -// could not read as the field's type) is the request's fault and becomes -// an InvalidValueError; anything else is returned mapped. func (p Projection[T]) engine(err error) error { if errors.Is(err, sqlate.ErrInvalidValue) { return &InvalidValueError{Err: err} diff --git a/query/projection_test.go b/query/projection_test.go index a77c826..3250483 100644 --- a/query/projection_test.go +++ b/query/projection_test.go @@ -29,19 +29,14 @@ func scanPerson(rows query.Row) (person, error) { return p, err } -// The base file ends with a semicolon, which the loader strips so the -// statement composes as a derived table. var projectionFiles = fstest.MapFS{ "sql/person_view.sql": {Data: []byte("--| tier: standard\n--| key: id\n--| field: id uuid\n--| field: name text\n--| field: age integer\n" + base + ";\n")}, "sql/no_contract.sql": {Data: []byte("--| tier: standard\nSELECT 1")}, "sql/with_param.sql": {Data: []byte("--| tier: standard\n--| key: id\n--| field: id uuid\nSELECT id FROM t WHERE tenant = {{tenant}}")}, "sql/two_params.sql": {Data: []byte("--| tier: standard\n--| key: id\n--| field: id uuid\n--| field: name text\nSELECT id, name FROM t WHERE tenant = {{tenant}} AND region = {{region}}")}, "sql/expanded_param.sql": {Data: []byte("--| tier: standard\n--| key: id\n--| field: id uuid\nSELECT id FROM t WHERE id IN ({{ids...}})")}, - // A composite key whose fields are declared not null: the contract a - // cursor needs. - "sql/member.sql": {Data: []byte("--| tier: standard\n--| key: org, id\n--| field: org uuid not null\n--| field: id uuid not null\n--| field: name text\nSELECT org, id, name FROM member")}, - // A cursorable base that binds a parameter of its own. - "sql/tenant_member.sql": {Data: []byte("--| tier: standard\n--| key: id\n--| field: id uuid not null\nSELECT id FROM member WHERE tenant = {{tenant}}")}, + "sql/member.sql": {Data: []byte("--| tier: standard\n--| key: org, id\n--| field: org uuid not null\n--| field: id uuid not null\n--| field: name text\nSELECT org, id, name FROM member")}, + "sql/tenant_member.sql": {Data: []byte("--| tier: standard\n--| key: id\n--| field: id uuid not null\nSELECT id FROM member WHERE tenant = {{tenant}}")}, } func projection(t *testing.T) query.Projection[person] { @@ -49,9 +44,6 @@ func projection(t *testing.T) query.Projection[person] { return catalog().MustCompile(projectionFiles, "sql", sqltest.Dialect{}).Statement("person_view").Project(scanPerson) } -// counted is the page text a List or Continue sends under TotalExact: the -// base filtered inside the window that counts it, then after, order, and -// paging outside it. func counted(base, where, after, rest string) string { return "SELECT * FROM (SELECT q.*, COUNT(*) OVER () AS sqlate_total FROM (" + base + ") q" + where + ") q" + after + rest } @@ -76,7 +68,6 @@ func TestList_ComposesOneCountedPageOverTheBase(t *testing.T) { if got.More || got.Next != "" { t.Errorf("a short page reported more = %v, next = %q", got.More, got.Next) } - // The total and the page are one statement, so they read one snapshot. calls := rec.Calls() if len(calls) != 1 { t.Fatalf("ops = %v, want the counted page alone", rec.Ops()) @@ -122,7 +113,6 @@ func TestList_OperatorLowering(t *testing.T) { if !strings.HasPrefix(page.SQL, counted(base, " WHERE "+c.want, "", " ORDER BY")) { t.Errorf("sql = %q", page.SQL) } - // The filter's values, then the paging bounds. if len(page.Args) != len(c.args)+2 { t.Errorf("args = %v, want %v then the paging bounds", page.Args, c.args) } @@ -143,10 +133,7 @@ func TestList_KeyIsTheTieBreakerUnlessSortedBy(t *testing.T) { for i, want := range []string{ " ORDER BY q.id OFFSET $1 ROWS FETCH NEXT $2 ROWS ONLY", " ORDER BY q.id DESC OFFSET $1 ROWS FETCH NEXT $2 ROWS ONLY", - // The sorts run in two directions, so the tie-breaker takes neither - // and the ordering cannot be continued by a cursor. " ORDER BY q.age, q.name DESC, q.id OFFSET $1 ROWS FETCH NEXT $2 ROWS ONLY", - // One direction across the sorts, so the tie-breaker takes it too. " ORDER BY q.name DESC, q.id DESC OFFSET $1 ROWS FETCH NEXT $2 ROWS ONLY", } { if got := pages[i]; !strings.HasSuffix(got, want) { @@ -185,10 +172,8 @@ func TestList_DirectiveErrorsUnwrapToErrDirectivesBeforeAnyIO(t *testing.T) { after query.Cursor size int }{ - "no cursor": {"", 5}, - "size 0": {"whatever", 0}, - // person_view declares no field not null, so no ordering over it can - // be continued by a cursor. + "no cursor": {"", 5}, + "size 0": {"whatever", 0}, "cursor unsupported": {"whatever", 5}, } for name, c := range continued { @@ -207,15 +192,11 @@ func TestList_DirectiveErrorsUnwrapToErrDirectivesBeforeAnyIO(t *testing.T) { } } -// dataException is a driver error that exposes an SQLSTATE, the shape an -// engine's dialect classifies. type dataException struct{ code, msg string } func (e dataException) Error() string { return e.msg } func (e dataException) SQLState() string { return e.code } -// invalidValueDialect maps SQLSTATE class 22 to ErrInvalidValue the way an -// engine sub-module does, over the stub dialect for everything else. type invalidValueDialect struct{ sqltest.Dialect } func (d invalidValueDialect) MapError(err error) error { @@ -267,10 +248,7 @@ func TestVerify_ProbesEveryContractField(t *testing.T) { t.Fatal(err) } fields := "SELECT q.id, q.name, q.age FROM (" + base + ") q WHERE q.id = CAST(NULL AS uuid) AND q.name = CAST(NULL AS text) AND q.age = CAST(NULL AS integer)" - // The cursor page probes the keyset predicate and the paging clause, so - // an engine's respelling of either is prepared at startup too. cursor := "SELECT * FROM (" + base + ") q WHERE (q.id > CAST($1 AS uuid)) ORDER BY q.id OFFSET $2 ROWS FETCH NEXT $3 ROWS ONLY" - // The counted cursor page probes the window's layering with them. countedCursor := counted(base, "", " WHERE (q.id > CAST($1 AS uuid))", " ORDER BY q.id OFFSET $2 ROWS FETCH NEXT $3 ROWS ONLY") if got := rec.SQL(sqltest.OpPrepare); len(got) != 3 || got[0] != fields || got[1] != cursor || got[2] != countedCursor { t.Errorf("probes = %q", got) @@ -311,8 +289,6 @@ func TestProject_RequiresAContractAndNoExpandedParameter(t *testing.T) { stmts.Statement(name).Project(scanPerson) }() } - // A base that binds parameters of its own, none of them expanded, is - // projectable: List, Continue, and One bind them from their base arguments. stmts.Statement("with_param").Project(scanPerson) } @@ -329,8 +305,6 @@ func TestProject_RefusesTheReservedTotalName(t *testing.T) { stmts.Statement("v").Project(query.Scalar[string]) } -// tenantView is the projection over a base that binds one parameter of its -// own, so the request's placeholders are numbered after the base's. func tenantView(t *testing.T, name string) query.Projection[string] { t.Helper() return catalog().MustCompile(projectionFiles, "sql", sqltest.Dialect{}).Statement(name).Project(query.Scalar[string]) @@ -361,9 +335,6 @@ func TestList_BindsTheBasesOwnParametersBeforeTheRequests(t *testing.T) { t.Errorf("page args = %v, want the base's value, the filter's, then the paging bounds", a) } - // Continued, the keyset predicate sits outside the window and its value - // binds after the filter's and before the paging bounds: the text's - // order, which a dialect with positional placeholders reads. view := tenantView(t, "tenant_member") notZ := []query.Filter{{Field: "id", Op: query.OpNe, Value: "z"}} db, _ = session(t, sqltest.WithTotal(ids("a", "b"), 2)) @@ -453,8 +424,6 @@ func TestList_TotalNoneSkipsTheCount(t *testing.T) { } func TestList_MoreReportsTheRowPastThePage(t *testing.T) { - // The page reads one row past its size: three rows for a page of two - // means a further page, and the extra row is not scanned. db, rec := session(t, sqltest.WithTotal(people(3), 9)) got, err := projection(t).List(context.Background(), db, query.Directives{}, query.Page{Number: 1, Size: 2}) if err != nil { @@ -463,8 +432,6 @@ func TestList_MoreReportsTheRowPastThePage(t *testing.T) { if !got.More || len(got.Items) != 2 || got.Items[1].ID != "b" { t.Fatalf("List = %+v", got) } - // person_view declares no field not null, so the page reports a further - // page without issuing a cursor for it. if got.Next != "" { t.Errorf("next = %q, want none over a nullable key", got.Next) } @@ -481,8 +448,6 @@ func TestList_ScannerNeverSeesTheTotalColumn(t *testing.T) { } db, _ := session(t, sqltest.WithTotal(people(2), 2)) view := catalog().MustCompile(projectionFiles, "sql", sqltest.Dialect{}).Statement("person_view").Project(query.Scanner[row]()) - // Scanner refuses a column it has no field for, so a page it reads - // shows it only the base's columns. got, err := view.List(context.Background(), db, query.Directives{}, query.Page{Number: 1, Size: 5}) if err != nil || got.Total != 2 || len(got.Items) != 2 || got.Items[1].Age != 21 { t.Fatalf("List = %+v, %v", got, err) @@ -493,8 +458,6 @@ func TestList_TheScansDestinationsAreLeftAsGiven(t *testing.T) { var spare []any scan := func(rows query.Row) (person, error) { var p person - // Spare capacity past the destinations: the count must not be - // appended into the caller's backing array. dest := make([]any, 3, 4) dest[0], dest[1], dest[2] = &p.ID, &p.Name, &p.Age err := rows.Scan(dest...) @@ -513,9 +476,6 @@ func TestList_TheScansDestinationsAreLeftAsGiven(t *testing.T) { } func TestList_ReadsTheTotalFromWithTotalsColumn(t *testing.T) { - // sqltest.WithTotal keeps its own copy of the reserved name; a counted - // read checks the last column's name, so a copy that drifted would fail - // here. db, _ := session(t, sqltest.WithTotal(people(2), 7)) got, err := projection(t).List(context.Background(), db, query.Directives{}, query.Page{Number: 1, Size: 5}) if err != nil || got.Total != 7 || len(got.Items) != 2 { @@ -531,8 +491,6 @@ func TestList_RefusesACountedPageWithoutItsTotalColumnLast(t *testing.T) { want string }{ { - // An overlay that moved the count: the last column would be - // hidden from the scan and read as the total. name: "count not last", page: sqltest.Response{Columns: []string{"id", "sqlate_total", "name", "age"}, Rows: [][]driver.Value{{"a", int64(1), "P", int64(20)}}}, want: `query: person_view: a counted page's last column is "age", not sqlate_total`, @@ -543,7 +501,6 @@ func TestList_RefusesACountedPageWithoutItsTotalColumnLast(t *testing.T) { want: `query: person_view: a counted page's last column is "age", not sqlate_total`, }, { - // A base that outputs the reserved name without declaring it. name: "base outputs the name", page: sqltest.WithTotal(sqltest.Response{Columns: []string{"id", "name", "age", "SQLATE_TOTAL"}, Rows: [][]driver.Value{{"a", "P", int64(20), int64(5)}}}, 1), want: "query: person_view: the base outputs a column named sqlate_total, which the library reserves", @@ -559,7 +516,6 @@ func TestList_RefusesACountedPageWithoutItsTotalColumnLast(t *testing.T) { t.Errorf("%s: the refused page leaked its row set", c.name) } } - // Continue reads through the same check, naming its own base. db, _ := session(t, members("c")) _, err := memberView(t).Continue(ctx, db, query.Directives{}, issue(t, nil), 2) if want := `query: member: a counted page's last column is "name", not sqlate_total`; err == nil || err.Error() != want { @@ -575,8 +531,6 @@ func TestList_AWrongDestinationCountNamesTheVisibleColumns(t *testing.T) { view := catalog().MustCompile(projectionFiles, "sql", sqltest.Dialect{}).Statement("person_view").Project(short) db, _ := session(t, sqltest.WithTotal(people(1), 1)) _, err := view.List(context.Background(), db, query.Directives{}, query.Page{Number: 1, Size: 5}) - // The same words database/sql uses over an uncounted page, with the - // count column left out of both sides. if want := "sql: expected 3 destination arguments in Scan, not 2"; err == nil || !strings.Contains(err.Error(), want) { t.Errorf("err = %v, want %q", err, want) } @@ -598,8 +552,6 @@ func TestList_AScanThatDoesNotReadItsRowIsAnError(t *testing.T) { if rec.RowsLeaked() != 0 { t.Error("the failed page leaked its row set") } - // Without the count there is nothing to read, and the scan is its own - // business. db, _ = session(t, people(2)) if _, err := view.List(context.Background(), db, query.Directives{Total: query.TotalNone}, query.Page{Number: 1, Size: 5}); err != nil { t.Errorf("TotalNone = %v", err) @@ -609,13 +561,11 @@ func TestList_AScanThatDoesNotReadItsRowIsAnError(t *testing.T) { func TestList_AnEmptyPageCarriesATotalOnlyOnTheFirstPage(t *testing.T) { p := projection(t) ctx := context.Background() - // Nothing under the filters: the first page is empty and the total is 0. db, _ := session(t, sqltest.WithTotal(people(0), 0)) got, err := p.List(ctx, db, query.Directives{}, query.Page{Number: 1, Size: 5}) if err != nil || got.Total != 0 || len(got.Items) != 0 || got.More { t.Errorf("empty first page = %+v, %v; want total 0", got, err) } - // Past the end, no row carries the count. db, _ = session(t, sqltest.WithTotal(people(0), 0)) got, err = p.List(ctx, db, query.Directives{}, query.Page{Number: 3, Size: 5}) if err != nil || got.Total != query.NoTotal || len(got.Items) != 0 || got.More { @@ -630,10 +580,6 @@ func TestList_AnEmptyPageCarriesATotalOnlyOnTheFirstPage(t *testing.T) { } func TestList_TheTotalAgreesWithThePage(t *testing.T) { - // Every page of a result of n rows, as an engine returns it: the rows - // from the offset, one past the size, each carrying n. Whenever a page - // reports a total, its items end at or before it and More says whether - // they end before it. const size = 2 for n := range 6 { table := people(n) diff --git a/query/returning.go b/query/returning.go index 5761828..81f439e 100644 --- a/query/returning.go +++ b/query/returning.go @@ -34,14 +34,6 @@ type Returner interface { Returning(verb Verb, body string, columns []string) (text string, ok bool) } -// returnForm is a command's resolved returning declaration. read reads the -// changed row back and is also the fallback's second step; verb is the -// command's verb; columns are the read's bare column names in scan order; -// native is the single-statement form the dialect rendered, nil when the -// dialect declined or does not implement Returner. renderings caches the -// single-statement form's expanded text by the lists' lengths, as -// Statement.renderings does the command's own; it is nil when the form has -// no expansion or there is no form. type returnForm struct { read Statement verb Verb @@ -51,34 +43,17 @@ type returnForm struct { } var ( - // leadingComment is a line or block comment at the start of a body, - // skipped when reading the statement's leading keyword. leadingComment = regexp.MustCompile(`^(?:\s+|--[^\n]*(?:\n|$)|/\*(?s:.*?)\*/)+`) - // commandVerb is the leading keyword a returning command starts with, - // and the table it changes: the name after INSERT INTO or UPDATE, schema - // qualified or not, as written. - commandVerb = regexp.MustCompile(`(?i)^(insert\s+into|update)\s+([^\s(,;]*)`) - // readList is the SELECT list of a returning read: everything before its - // first FROM, each item then checked on its own. - readList = regexp.MustCompile(`(?is)^select\s+(.+?)\s+from\s`) - // readFrom is what follows a returning read's first FROM: the table it - // reads, schema qualified or not, and the word after it, the table's - // alias unless it is a keyword, with or without AS. - readFrom = regexp.MustCompile(`(?i)^\s*([^\s(),;]+)(?:\s+(?:as\s+)?([a-z_][a-z0-9_]*))?`) - // readColumn is one item of a returning read's SELECT list: a column, - // optionally qualified by a table or alias. - readColumn = regexp.MustCompile(`^(?:([a-z_][a-z0-9_]*)\.)?([a-z_][a-z0-9_]*)$`) + commandVerb = regexp.MustCompile(`(?i)^(insert\s+into|update)\s+([^\s(,;]*)`) + readList = regexp.MustCompile(`(?is)^select\s+(.+?)\s+from\s`) + readFrom = regexp.MustCompile(`(?i)^\s*([^\s(),;]+)(?:\s+(?:as\s+)?([a-z_][a-z0-9_]*))?`) + readColumn = regexp.MustCompile(`^(?:([a-z_][a-z0-9_]*)\.)?([a-z_][a-z0-9_]*)$`) ) -// stripLeading returns body without its leading whitespace and comments. func stripLeading(body string) string { return body[len(leadingComment.FindString(body)):] } -// commandVerbOf reads the verb of a returning command's body, INSERT INTO or -// UPDATE, matched case-insensitively, and the table it changes, as written. -// Anything else, DELETE or a leading WITH among them, is an error naming what -// the body starts with. func commandVerbOf(body string) (Verb, string, error) { rest := stripLeading(body) m := commandVerb.FindStringSubmatch(rest) @@ -98,17 +73,12 @@ func commandVerbOf(body string) (Verb, string, error) { return Insert, m[2], nil } -// fromKeywords are the words that may follow a read's FROM table and are -// not its alias. var fromKeywords = []string{ "where", "join", "inner", "left", "right", "full", "cross", "natural", "group", "order", "having", "limit", "offset", "fetch", "for", "window", "union", "intersect", "except", "on", "using", } -// readShape is what a returning read's body declares: the returned columns -// in scan order, the qualifier every item carries (empty for none), and -// the table after its first FROM with its alias (empty for none). type readShape struct { columns []string qualifier string @@ -116,10 +86,6 @@ type readShape struct { alias string } -// readShapeOf reads the shape of a returning read's body: the body is -// SELECT , , … FROM …, each a lowercase column or -// table.column, every item under the same qualifier or none, no name twice. -// The columns are the bare names, in the list's order. func readShapeOf(body string) (readShape, error) { var shape readShape text := stripLeading(body) @@ -157,9 +123,6 @@ func readShapeOf(body string) (readShape, error) { return shape, nil } -// readsTarget checks that a returning read reads the table its command -// changes: the read's FROM table is the command's target, compared as -// written, and a qualifier on its columns is that table's alias or its name. func readsTarget(readName string, shape readShape, target string) error { if shape.table != target { return fmt.Errorf("returning read %q reads %q; the command changes %q", readName, shape.table, target) @@ -173,13 +136,6 @@ func readsTarget(readName string, shape readShape, target string) error { return nil } -// resolveReturning resolves a command's returning declaration against the -// statements compiled beside it. It checks the command's verb and the named -// read and its shape, that the read reads the table the command changes, -// and, when d implements Returner and accepts, compiles -// the single-statement form, its parameters rewritten as the command's are. -// sources holds, by name, every statement's body after include expansion -// and its returning declaration. func resolveReturning(st *Statement, sources map[string]source, stmts map[string]Statement, d sqlate.Dialect) error { readName, body := sources[st.name].returning, sources[st.name].body if st.tier != TierStandard { @@ -310,8 +266,6 @@ func (r Returning[T]) One(ctx context.Context, s sqlate.Session, args Args) (T, return zero, false, ErrTransactionRequired } -// single runs the single-statement form. A returned row is the changed -// row; when none is returned, the read reads the row as it is. func (r Returning[T]) single(ctx context.Context, s sqlate.Session, args Args) (T, bool, error) { var zero T form := r.cmd.returning @@ -328,9 +282,6 @@ func (r Returning[T]) single(ctx context.Context, s sqlate.Session, args Args) ( if err := rows.Err(); err != nil { return zero, false, mapErr(s, err) } - // Next returning false has closed the row set unless the driver - // reports a further result set; Close releases it before the read, - // which may share the connection. if err := rows.Close(); err != nil { return zero, false, mapErr(s, err) } @@ -350,7 +301,6 @@ func (r Returning[T]) single(ctx context.Context, s sqlate.Session, args Args) ( return row, true, nil } -// fallback runs the command and then its read, on tx. func (r Returning[T]) fallback(ctx context.Context, tx *sqlate.Tx, args Args) (T, bool, error) { var zero T n, err := r.cmd.Exec(ctx, tx, args) @@ -370,8 +320,6 @@ func (r Returning[T]) fallback(ctx context.Context, tx *sqlate.Tx, args Args) (T return row, n == 1, nil } -// changedRow is the fallback's outcome carried out of the transaction One -// opens: the row and whether the command changed it. type changedRow[T any] struct { row T changed bool diff --git a/query/returning_test.go b/query/returning_test.go index 6c526eb..c3247d0 100644 --- a/query/returning_test.go +++ b/query/returning_test.go @@ -16,8 +16,6 @@ import ( "github.com/standards-lab/sqlate/sqltest" ) -// returningFiles is a command that reads its row back through a qualified -// read, and an insert that reads it through an unqualified one. var returningFiles = fstest.MapFS{ "sql/rename.sql": {Data: []byte("--| tier: standard\n--| returning: org_row\nUPDATE organization SET name = {{name}} WHERE id = {{id}}")}, "sql/org_row.sql": {Data: []byte("--| tier: standard\nSELECT o.id, o.name, o.version FROM organization o WHERE o.id = {{id}}")}, @@ -60,7 +58,6 @@ func TestReturning_HasNoSingleStatementFormWhenTheDialectLacksTheCapability(t *t } } -// decliner implements query.Returner and declines every verb. type decliner struct{ sqltest.Dialect } func (decliner) Returning(query.Verb, string, []string) (string, bool) { return "", false } @@ -75,8 +72,6 @@ func TestReturning_HasNoSingleStatementFormWhenTheDialectDeclines(t *testing.T) } } -// recorder implements query.Returner, keeping what it was asked, and appends -// the clause. type recorder struct { sqltest.Dialect verbs *[]query.Verb @@ -118,7 +113,6 @@ func TestReturning_PassesTheDialectTheExpandedBodyVerbAndColumns(t *testing.T) { } } -// injector implements query.Returner and writes a parameter of its own. type injector struct{ sqltest.Dialect } func (injector) Returning(_ query.Verb, body string, _ []string) (string, bool) { @@ -250,7 +244,6 @@ func TestVerify_PreparesTheSingleStatementFormAndNamesItsFailure(t *testing.T) { } } -// orgVersion is the row org_row reads: the organization and its version. type orgVersion struct { ID string Name string @@ -273,7 +266,6 @@ func orgVersionRows(n int) sqltest.Response { return r } -// rename is the rename command's handle compiled for d. func rename(t *testing.T, d sqlate.Dialect) query.Returning[orgVersion] { t.Helper() return catalog().MustCompile(returningFiles, "sql", d).Statement("rename").Returning(scanOrgVersion) @@ -291,7 +283,7 @@ func TestReturningOne_Outcomes(t *testing.T) { ) cases := []struct { name string - fallback, native *script // nil: the outcome does not arise on the form + fallback, native *script check func(t *testing.T, row orgVersion, changed bool, err error) }{ { @@ -425,7 +417,6 @@ func TestReturningOne_InsideATransactionOpensNone(t *testing.T) { if _, _, err := r.One(ctx, tx, renameArgs); !errors.Is(err, query.ErrNotOneRow) { t.Errorf("%s: err = %v, want ErrNotOneRow", f.name, err) } - // The caller's transaction is the caller's to end. _ = tx.Rollback() if !slices.Equal(rec.Ops(), want) { t.Errorf("%s: ops %v, want %v", f.name, rec.Ops(), want) @@ -433,11 +424,8 @@ func TestReturningOne_InsideATransactionOpensNone(t *testing.T) { } } -// wrapped is a session that is neither a *sqlate.Tx nor a sqlate.Beginner. type wrapped struct{ sqlate.Session } -// appDB is an application's own pool type, a sqlate.Beginner through the -// *sqlate.DB it embeds. type appDB struct{ *sqlate.DB } func TestReturningOne_TheFallbackNeedsATransactionOrABeginner(t *testing.T) { diff --git a/query/rows_test.go b/query/rows_test.go index 2448f51..7da80c2 100644 --- a/query/rows_test.go +++ b/query/rows_test.go @@ -49,8 +49,6 @@ var testFiles = fstest.MapFS{ "sql/in_tree.sql": {Data: []byte("--| tier: standard\nSELECT COUNT(*) FROM t WHERE node = {{node}} AND (a = {{candidate}} OR b = {{node}})")}, } -// catalog is the library's own patterns, the catalog every test compiles -// against unless it registers more. func catalog() *query.Catalog { return query.MustCatalog(query.Patterns()) } func source(t *testing.T) *query.Statements { @@ -140,7 +138,6 @@ func TestRows_ErrorsCrossTheMappingBoundary(t *testing.T) { t.Errorf("query error = %v, want mapped", err) } - // A scan failure: the row is narrower than the scan function reads. db, rec := session(t, sqltest.Response{Columns: []string{"id"}, Rows: [][]driver.Value{{"a"}}}) if _, err := all.One(ctx, db, nil); !errors.As(err, &mapped) { t.Errorf("scan error = %v, want mapped through ErrorMapper", err) diff --git a/query/statement.go b/query/statement.go index 7bfab34..feda804 100644 --- a/query/statement.go +++ b/query/statement.go @@ -54,12 +54,8 @@ type Statement struct { fields []Field dialect sqlate.Dialect catalog *Catalog - // renderings caches an expanded statement's text by the lengths of its - // lists; nil for a statement with no expansion, whose text is final. renderings *sync.Map - // returning is the resolved returning declaration of a command; nil for - // a statement that declares none. - returning *returnForm + returning *returnForm } // Catalog is the catalog the statement compiled against. @@ -177,7 +173,6 @@ func (st Statement) Exec(ctx context.Context, s sqlate.Session, args Args) (int6 return n, mapErr(s, err) } -// query runs the statement for its rows. func (st Statement) query(ctx context.Context, s sqlate.Session, args Args) (*sql.Rows, error) { text, values, err := st.bind(s, args) if err != nil { @@ -186,18 +181,10 @@ func (st Statement) query(ctx context.Context, s sqlate.Session, args Args) (*sq return s.QueryContext(ctx, text, values...) } -// bind checks the session against the transaction requirement and orders -// args by the statement's parameters, an expanded parameter's list -// flattened into consecutive values; for an expanded statement the text is -// rendered for the lists' lengths, cached by them. func (st Statement) bind(s sqlate.Session, args Args) (string, []any, error) { return st.bindForm(st.compiled, st.renderings, s, args) } -// bindForm is bind over one compiled form of the statement and that form's -// renderings cache: the statement's own, or a returning command's -// single-statement form, which binds the same parameters under the same -// transaction requirement. func (st Statement) bindForm(c compiled, renderings *sync.Map, s sqlate.Session, args Args) (string, []any, error) { if st.txRequired { if _, ok := s.(*sqlate.Tx); !ok { @@ -237,9 +224,6 @@ func (st Statement) bindForm(c compiled, renderings *sync.Map, s sqlate.Session, return text, values, nil } -// mapErr routes an error that arose after a call returned (rows.Err, Scan, -// RowsAffected) through the session's mapper, since the session's methods -// cannot see it. func mapErr(s sqlate.Session, err error) error { if err == nil { return nil diff --git a/query/statements.go b/query/statements.go index d936c04..0a3f1d4 100644 --- a/query/statements.go +++ b/query/statements.go @@ -64,9 +64,6 @@ func (c *Catalog) Compile(fsys fs.FS, dir string, d sqlate.Dialect) (*Statements stmts.statements[st.name] = st sources[st.name] = src } - // A returning declaration names a read of the same directory, so it - // resolves once every file is parsed; in name order, so the first - // failure reported is stable. for _, st := range stmts.Statements() { if sources[st.name].returning == "" { continue @@ -152,27 +149,11 @@ func Verify(ctx context.Context, db sqlate.Session, vs ...Verifier) error { return errors.Join(errs...) } -// source is what Compile keeps of a statement for resolving returning -// declarations: its body after include expansion, its parameters still -// {{…}} slots, and the read its returning declaration names, empty for none. type source struct { body string returning string } -// parse reads the header, expands the body's pattern includes, and rewrites -// its parameters; the engine receives the body, less a trailing semicolon -// so the statement composes as a derived table. The header grammar: tier -// required (standard | native); native required when the tier is native, -// the engine feature used and the port as free text; port optional and -// native only, the port as its own declaration; transaction optional -// (required); key optional, naming one declared field or several separated -// by commas, each named once; field repeated, " " with an -// optional trailing "not null", matched case-insensitively, the name an -// identifier; returning optional, naming the statement of the same -// directory that reads the changed row back, resolved by Compile once every -// file is parsed. The source returned beside the statement is its expanded -// body and returning declaration, which that resolution reads. func (c *Catalog) parse(name, text string, d sqlate.Dialect) (Statement, source, error) { st := Statement{name: name, dialect: d, catalog: c} var src source @@ -258,11 +239,8 @@ func (c *Catalog) parse(name, text string, d sqlate.Dialect) (Statement, source, return st, src, err } -// notNullSuffix is the optional trailing suffix of a field declaration. const notNullSuffix = " not null" -// cutNotNull returns decl without its trailing "not null" suffix, matched -// case-insensitively as SQL keywords are, and whether the suffix was there. func cutNotNull(decl string) (string, bool) { if len(decl) > len(notNullSuffix) && strings.EqualFold(decl[len(decl)-len(notNullSuffix):], notNullSuffix) { return decl[:len(decl)-len(notNullSuffix)], true @@ -270,12 +248,6 @@ func cutNotNull(decl string) (string, bool) { return decl, false } -// strayNotNull reports whether a field's type, with its "not null" suffix -// already cut, still contains the word not or null, or ends in the one-word -// spelling notnull or not_null. Each marks a misspelled suffix, such as -// "nott null", "not null", or "notnull", which the type grammar would -// otherwise accept as part of the type, leaving the field nullable and the -// failure to the engine. No SQL type name contains any of these words. func strayNotNull(typ string) bool { words := strings.Fields(typ) for _, w := range words { @@ -290,6 +262,4 @@ func strayNotNull(typ string) bool { return false } -// identifier is a contract field name as it appears in the composed SQL: -// unquoted, lowercase, the base's own alias for the column. var identifier = regexp.MustCompile(`^[a-z_][a-z0-9_]*$`) diff --git a/query/statements_test.go b/query/statements_test.go index acbe58e..0ca3085 100644 --- a/query/statements_test.go +++ b/query/statements_test.go @@ -139,8 +139,6 @@ func TestLoad_RejectsBrokenHeaders(t *testing.T) { if err == nil || !strings.Contains(err.Error(), "s.sql") { t.Errorf("%s: err = %v, want a load error naming the file", name, err) } - // A misspelled suffix passes the type grammar, so only the - // suffix check refuses it. if strings.HasPrefix(name, "not null") && (err == nil || !strings.Contains(err.Error(), `the type contains "not" or "null"`)) { t.Errorf("%s: err = %v, want the misspelled suffix named", name, err) } diff --git a/query/utc.go b/query/utc.go index 3ebaa18..986a25a 100644 --- a/query/utc.go +++ b/query/utc.go @@ -5,14 +5,6 @@ import ( "time" ) -// inUTC moves the time dest points to into time.UTC, for each destination -// kind database/sql scans a time into: a time.Time, a *time.Time, a valid -// sql.NullTime or sql.Null[time.Time], and an untyped destination holding a -// time.Time. Every other destination is left as it is. Scanner and Scalar -// run it on every value they scan, so their times do not depend on -// time.Local or on the driver: pgx, for one, delivers a timestamptz in -// time.Local, and the same row would read differently on two hosts. The -// instant is unchanged, and a zero time stays zero. func inUTC(dest any) { switch d := dest.(type) { case *time.Time: diff --git a/query/utc_test.go b/query/utc_test.go index 9461149..26dda8d 100644 --- a/query/utc_test.go +++ b/query/utc_test.go @@ -11,8 +11,6 @@ import ( "github.com/standards-lab/sqlate/sqltest" ) -// stamped holds every time destination kind Scanner converts, one of them -// reached through an embedded struct. type stamped struct { Identity Updated *time.Time `json:"updated"` @@ -25,12 +23,8 @@ type stamped struct { } func TestScanner_ReturnsTimesInUTC(t *testing.T) { - // A winter instant: London's wall clock (time.Local, from TestMain) - // reads as UTC's, offset zero, so only a comparison of whole values - // tells a value left in time.Local from one in time.UTC. at := time.Date(2026, 1, 15, 12, 30, 0, 500, time.Local) utc := time.Date(2026, 1, 15, 12, 30, 0, 500, time.UTC) - // A summer instant, an hour ahead of UTC on London's wall clock. summer := time.Date(2026, 7, 1, 9, 0, 0, 0, time.Local) summerUTC := time.Date(2026, 7, 1, 8, 0, 0, 0, time.UTC) db, _ := session(t, sqltest.Response{ @@ -95,9 +89,6 @@ func TestScalar_ReturnsTimesInUTC(t *testing.T) { } func TestContinue_CarriesATimeKeyInUTC(t *testing.T) { - // The page's last item is keyed by a summer instant London's wall clock - // reads an hour ahead of UTC; the cursor carries it as UTC text, so the - // same row issues the same cursor on every host. last := time.Date(2026, 7, 1, 9, 0, 0, 0, time.Local) db, _ := session(t, sqltest.WithTotal(members(last.Add(-time.Hour), last, last.Add(time.Hour)), 9)) page, err := memberView(t).List(context.Background(), db, query.Directives{}, query.Page{Number: 1, Size: 2}) From bd2633de7db9dc3351ad22b3ba94ee63eca5a452 Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Fri, 20 Nov 2026 23:06:34 -0500 Subject: [PATCH 06/10] harness.adoption: sqlate postgres and sqlint comments are the five kinds Unexported-identifier docs, test-function docs, test-file package comments and in-body comments go from the postgres and sqlint modules. Names take what trailing labels said: continuedPageOffset, firstGuardWhereLine and firstGuardSetLine, refusedByPredicate and publishable, and the probe Force's failure message names the top set. docs/features.md takes the reasoning with no other home: PostgreSQL 19 records NOT NULL as a named constraint yet its violation reports none, pgtest drops after a failed create, and the compose PostgreSQL's health check probes over TCP rather than the socket. --- docs/features.md | 8 +- postgres/dialect_test.go | 4 - postgres/live_test.go | 12 -- postgres/lock_live_test.go | 12 -- postgres/main_test.go | 5 +- postgres/migrate_live_test.go | 167 +--------------------------- postgres/patterns_test.go | 4 - postgres/pgtest/pgtest.go | 18 +-- postgres/pgtest/pgtest_live_test.go | 10 -- postgres/query_live_test.go | 79 ++----------- postgres/returning_live_test.go | 71 ++---------- postgres/total_live_test.go | 87 ++------------- sqlint/body.go | 46 ++------ sqlint/cmd/sqlint/main.go | 1 - sqlint/config.go | 21 ---- sqlint/dialect.go | 3 - sqlint/glob.go | 3 - sqlint/lint.go | 23 ---- sqlint/lint_test.go | 45 -------- sqlint/migrations.go | 2 - sqlint/patterns.go | 3 - sqlint/statements.go | 9 +- 22 files changed, 47 insertions(+), 586 deletions(-) diff --git a/docs/features.md b/docs/features.md index 397d445..898ea41 100644 --- a/docs/features.md +++ b/docs/features.md @@ -595,6 +595,8 @@ package rather than the command. | anything else | the error unchanged, `sql.ErrNoRows` included | Each `ConstraintError` carries the constraint, table, and column names the server reports. +PostgreSQL 19 records a `NOT NULL` as a named constraint in `pg_constraint`, yet its not-null +violation still reports no constraint name, so `Column` remains that error's handle. `Lock` and `Unlock` implement `sqlate.Locker` over `pg_advisory_lock` and `pg_advisory_unlock` on a pinned connection. The name enters the engine's key space through `hashtext`, so locks are @@ -634,6 +636,9 @@ agrees with its total when writes commit between the statement and the caller, w read as its own statement does not; that it agrees under concurrent writers; and that the counted page scans its base once under one window while the uncounted page keeps the key's index order. `mise run acceptance` runs them against a compose PostgreSQL and tears it down. +The compose PostgreSQL reports healthy once it accepts TCP connections to the app database. The +probe goes over TCP, not the socket, because the first start's initialization runs a temporary +server on the socket alone, which would report ready before the real server starts. ### pgtest: a test's throwaway database @@ -647,5 +652,6 @@ under the PostgreSQL dialect, and `Database.Session()` wraps the pool under `Dia When the test ends the pool is closed and the database dropped `WITH (FORCE)`, so a session still open on it, such as a started process's pool, is ended rather than holding the drop back; -the drop is retried while the server reports a session still closing. The package imports +the drop is retried while the server reports a session still closing. A create that fails is +followed by a drop too, since one that timed out can still finish on the server. The package imports `testing`, so only test files import it. diff --git a/postgres/dialect_test.go b/postgres/dialect_test.go index 55dad0b..df600eb 100644 --- a/postgres/dialect_test.go +++ b/postgres/dialect_test.go @@ -39,8 +39,6 @@ func TestDialect_ReturningDeclinesAnUnknownVerb(t *testing.T) { } } -// A body ending in a line comment keeps the clause: it starts on a line of -// its own, outside the comment. func TestDialect_ReturningAfterATrailingLineComment(t *testing.T) { body := "UPDATE item SET status = 'x' WHERE id = {{id}} -- the key" got, ok := (postgres.Dialect{}).Returning(query.Update, body, []string{"id"}) @@ -54,8 +52,6 @@ var returningFiles = fstest.MapFS{ "sql/create_item.sql": {Data: []byte("--| tier: standard\n--| returning: item_by_id\nINSERT INTO item (id, a, b) VALUES ({{id}}, {{a}}, {{b}})")}, } -// Compiled through query, the command's single-statement form carries the -// read's bare columns and the engine's placeholders. func TestDialect_ReturningCompilesThroughQuery(t *testing.T) { stmts := query.MustCatalog(postgres.Patterns()).MustCompile(returningFiles, "sql", postgres.Dialect{}) st := stmts.Statement("create_item") diff --git a/postgres/live_test.go b/postgres/live_test.go index f86dbdb..e185df8 100644 --- a/postgres/live_test.go +++ b/postgres/live_test.go @@ -1,10 +1,5 @@ //go:build integration -// The live-engine acceptance proofs run against the PostgreSQL named by -// SQLATE_DSN (the compose stack: `mise run db:up`, then -// `mise run integration`) and skip when it is unset. They are not -// part of the unit tier: each is a proof the engine alone can give, -// demonstrated in the session that establishes the claim. package postgres_test import ( @@ -21,15 +16,11 @@ import ( "github.com/standards-lab/sqlate/postgres" ) -// live opens a session over the live database, or skips. func live(t testing.TB) *sqlate.DB { t.Helper() return liveIn(t, "") } -// liveIn is live with every session's TimeZone set to zone, or the -// server's default when zone is empty: a runtime parameter pgx sends at -// connect. func liveIn(t testing.TB, zone string) *sqlate.DB { t.Helper() dsn := os.Getenv("SQLATE_DSN") @@ -54,7 +45,6 @@ func liveIn(t testing.TB, zone string) *sqlate.DB { return sqlate.Wrap(pool, postgres.Dialect{}) } -// sqlState reads the SQLSTATE of a driver error, or "". func sqlState(err error) string { if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok { return pgErr.Code @@ -62,8 +52,6 @@ func sqlState(err error) string { return "" } -// Proof: the server-version statement runs on the engine and reads its -// version. func TestLive_ServerVersion(t *testing.T) { db := live(t) rows, err := db.QueryContext(context.Background(), postgres.Dialect{}.ServerVersion()) diff --git a/postgres/lock_live_test.go b/postgres/lock_live_test.go index 606a1a4..e170cee 100644 --- a/postgres/lock_live_test.go +++ b/postgres/lock_live_test.go @@ -14,8 +14,6 @@ import ( "github.com/standards-lab/sqlate/postgres" ) -// pin pins one connection of db, closed at cleanup unless the test closed -// it first. func pin(t *testing.T, db *sqlate.DB) *sql.Conn { t.Helper() conn, err := db.Conn(context.Background()) @@ -26,7 +24,6 @@ func pin(t *testing.T, db *sqlate.DB) *sql.Conn { return conn } -// tryLock is Dialect.TryLock that fails the test on an error. func tryLock(t *testing.T, conn *sql.Conn, name string) bool { t.Helper() got, err := postgres.Dialect{}.TryLock(context.Background(), conn, name) @@ -36,10 +33,6 @@ func tryLock(t *testing.T, conn *sql.Conn, name string) bool { return got } -// Proof: TryLock shares Lock's key space and session scope. A name one -// session holds, through Lock or TryLock, is refused to TryLock on another -// without waiting, and is granted again once the holder unlocks it or its -// connection closes. func TestLive_TryLock(t *testing.T) { ctx := context.Background() d := postgres.Dialect{} @@ -96,14 +89,9 @@ func TestLive_TryLock(t *testing.T) { if tryLock(t, other, name) { t.Fatal("TryLock on another session took a held name") } - // Closing a pinned conn returns it to the pool with its session, and - // the lock, intact; a Raw func answering driver.ErrBadConn makes - // database/sql close the driver connection, which ends the session. if err := holder.Raw(func(any) error { return driver.ErrBadConn }); !errors.Is(err, driver.ErrBadConn) { t.Fatalf("Raw = %v, want the discard", err) } - // The server ends the backend after the socket closes, not with it, - // so the grant is awaited. deadline := time.Now().Add(5 * time.Second) for !tryLock(t, other, name) { if time.Now().After(deadline) { diff --git a/postgres/main_test.go b/postgres/main_test.go index 760e566..dbd0b5d 100644 --- a/postgres/main_test.go +++ b/postgres/main_test.go @@ -4,12 +4,9 @@ import ( "os" "testing" "time" - _ "time/tzdata" // Europe/London loads on a host without a zone database. + _ "time/tzdata" ) -// TestMain runs the package's tests with time.Local set to Europe/London, -// so a time the package returned in time.Local, not time.UTC, fails the -// tests' == comparisons whatever zone the host runs in. func TestMain(m *testing.M) { london, err := time.LoadLocation("Europe/London") if err != nil { diff --git a/postgres/migrate_live_test.go b/postgres/migrate_live_test.go index 0b6e0a4..a430bca 100644 --- a/postgres/migrate_live_test.go +++ b/postgres/migrate_live_test.go @@ -1,9 +1,5 @@ //go:build integration -// The live-engine acceptance proofs for migrate: the cases a mature library -// has met, run against the live PostgreSQL named by SQLATE_DSN. Each -// proof owns its object names and drops them on exit, so the proofs run in -// any order and survive an aborted run. `mise run integration`. package postgres_test import ( @@ -24,8 +20,6 @@ import ( "github.com/standards-lab/sqlate/postgres" ) -// scratch drops the named objects now and at cleanup: the history table -// and every table or index a proof creates. func scratch(t testing.TB, db *sqlate.DB, history string, tables ...string) { t.Helper() drop := func() { @@ -70,10 +64,6 @@ func indexValid(t testing.TB, db *sqlate.DB, index string) (exists, valid bool) return true, valid } -// Proof: non-transactional DDL. CREATE INDEX CONCURRENTLY refuses a -// transaction block (SQLSTATE 25001); the "-- transaction: none" opt-out -// runs it under autocommit on the pinned connection, and the history row -// goes dirty → clean around it. func TestLive_NonTransactionalDDL(t *testing.T) { ctx := context.Background() db := live(t) @@ -110,9 +100,6 @@ func TestLive_NonTransactionalDDL(t *testing.T) { } } -// Proof: forcing a set from an empty history to its head writes the whole -// prefix, so the history reads back as current and Verify, Status, and a -// later Down all accept it. func TestLive_ForceFromEmptyWritesThePrefix(t *testing.T) { ctx := context.Background() db := live(t) @@ -144,11 +131,6 @@ func TestLive_ForceFromEmptyWritesThePrefix(t *testing.T) { } } -// Proof: dirty state and force, with the orphan PostgreSQL leaves behind. A -// unique index built CONCURRENTLY over duplicate rows fails after the -// catalog entry exists, so the index remains INVALID: the history row is -// dirty, every run refuses, Verify reports it, and the repair is drop the -// orphan, Force the previous version, fix the data, and re-run. func TestLive_DirtyStateAndForce(t *testing.T) { ctx := context.Background() db := live(t) @@ -178,7 +160,6 @@ func TestLive_DirtyStateAndForce(t *testing.T) { t.Errorf("second Up = %v, want the discovered DirtyError", err) } - // The repair, as an operator would do it. if _, err := db.ExecContext(ctx, "DROP INDEX live_dirty_uq"); err != nil { t.Fatal(err) } @@ -199,16 +180,11 @@ func TestLive_DirtyStateAndForce(t *testing.T) { } } -// slowSet is a set whose first migration holds its transaction open long -// enough for a second starter to collide with it. var slowSet = []migrate.Migration{ {Version: 1, Name: "slow", Up: "SELECT pg_sleep(0.4)", Down: "SELECT 1", Transactional: true}, {Version: 2, Name: "table", Up: "CREATE TABLE live_race (x int)", Down: "DROP TABLE live_race", Transactional: true}, } -// Proof: concurrent starters in one process. Four migrators over one pool -// start together; the lock serializes them, every Up succeeds, and the -// history and the schema each show one application. func TestLive_ConcurrentStartersInProcess(t *testing.T) { db := live(t) scratch(t, db, "live_race_history", "live_race") @@ -228,9 +204,6 @@ func TestLive_ConcurrentStartersInProcess(t *testing.T) { assertAppliedOnce(t, db, "live_race_history", len(slowSet)) } -// Proof: the unlocked negative. The same race without the lock: every -// starter reads an empty history and applies; the collision surfaces as -// duplicate_table (42P07) or a duplicate history row (23505) in all but one. func TestLive_UnlockedStartersCollide(t *testing.T) { db := live(t) scratch(t, db, "live_race_history", "live_race") @@ -258,9 +231,6 @@ func TestLive_UnlockedStartersCollide(t *testing.T) { t.Logf("unlocked: %d of 4 starters collided", failed) } -// Proof: concurrent starters across processes. The test binary re-executes -// itself four times, each child a process with its own pool running Up on -// the same history; the advisory lock serializes them across sessions. func TestLive_ConcurrentStartersAcrossProcesses(t *testing.T) { db := live(t) scratch(t, db, "live_race_history", "live_race") @@ -285,7 +255,6 @@ func TestLive_ConcurrentStartersAcrossProcesses(t *testing.T) { assertAppliedOnce(t, db, "live_race_history", len(slowSet)) } -// TestLive_Helper is the child process of the cross-process proof. func TestLive_Helper(t *testing.T) { if os.Getenv("SQLATE_HELPER") != "starter" { t.Skip("helper") @@ -333,11 +302,6 @@ func assertAppliedOnce(t testing.TB, db *sqlate.DB, history string, want int) { } } -// Proof: the cancelled-context run. A migration sleeping past the deadline -// is cancelled mid-statement: Up returns the cancellation and nothing else -// (pgx discards the connection, so the rollback and the unlock on it cannot -// succeed and are not reported), nothing is recorded, no advisory lock -// survives, and the next run proceeds at once. func TestLive_CancelledContext(t *testing.T) { db := live(t) scratch(t, db, "live_cancel_history") @@ -365,8 +329,6 @@ func TestLive_CancelledContext(t *testing.T) { t.Errorf("%d advisory locks held after the cancelled run", n) } - // The lock is free: a fresh run over a fast set completes well within - // the time the cancelled sleep would still be holding it. fast := migrator(t, db, "live_cancel_history", []migrate.Migration{{Version: 1, Name: "slow", Up: "SELECT 1", Transactional: true}}, migrate.Options{}) ctx2, cancel2 := context.WithTimeout(context.Background(), 2*time.Second) defer cancel2() @@ -375,9 +337,6 @@ func TestLive_CancelledContext(t *testing.T) { } } -// The multi-set fixtures: a lower set and an upper set whose table holds a -// foreign key into the lower set's table, the shape a library's set and the -// program's set over it take. const ( lowerHistory = "live_ms_lower_history" upperHistory = "live_ms_upper_history" @@ -388,10 +347,6 @@ var lowerMigrations = []migrate.Migration{ {Version: 2, Name: "column", Up: "ALTER TABLE live_ms_lower ADD COLUMN note text", Down: "ALTER TABLE live_ms_lower DROP COLUMN note", Transactional: true}, } -// rehearsal is the upgrade rehearsal's fixture: a third migration over the -// lower set's two, so a set that carries it stands for a later version of -// the library applied over an installed database. It adds an index, an -// object that reverts in its own transaction without touching the tables. var rehearsal = migrate.Migration{ Version: 3, Name: "rehearsal", Up: "CREATE INDEX live_ms_lower_rehearsal ON live_ms_lower (name)", @@ -412,10 +367,8 @@ var upperSet = migrate.Set{Name: "upper", Table: upperHistory, Migrations: []mig {Version: 2, Name: "index", Up: "CREATE INDEX live_ms_upper_lower_ix ON live_ms_upper (lower_id)", Down: "DROP INDEX live_ms_upper_lower_ix", Transactional: true}, }} -// multiset returns the two sets in canonical order, lower first. func multiset(rehearsed bool) []migrate.Set { return []migrate.Set{lowerSet(rehearsed), upperSet} } -// scratchMultiset drops every object the multi-set proofs create, now and at cleanup. func scratchMultiset(t testing.TB, db *sqlate.DB) { t.Helper() scratch(t, db, upperHistory, "live_ms_upper") @@ -424,7 +377,6 @@ func scratchMultiset(t testing.TB, db *sqlate.DB) { scratch(t, db, "live_probe_history") } -// count returns a one-row integer query's value. func count(t testing.TB, db *sqlate.DB, q string, args ...any) int { t.Helper() rows, err := db.QueryContext(context.Background(), q, args...) @@ -439,7 +391,6 @@ func count(t testing.TB, db *sqlate.DB, q string, args ...any) int { return n } -// text returns a one-row text query's value. func text(t testing.TB, db *sqlate.DB, q string, args ...any) string { t.Helper() rows, err := db.QueryContext(context.Background(), q, args...) @@ -454,8 +405,6 @@ func text(t testing.TB, db *sqlate.DB, q string, args ...any) string { return s } -// relationExists reports whether name resolves to a relation on the search -// path. to_regclass yields NULL for a missing relation, which matches no oid. func relationExists(t testing.TB, db *sqlate.DB, name string) bool { t.Helper() return count(t, db, "SELECT COUNT(*) FROM pg_class WHERE oid = to_regclass($1)", name) == 1 @@ -470,8 +419,6 @@ func assertRelations(t testing.TB, db *sqlate.DB, want bool, names ...string) { } } -// assertClean checks Status reports every set at the given version, with -// nothing pending and nothing dirty. func assertClean(t testing.TB, m *migrate.Migrator, versions ...int) { t.Helper() sets, err := m.Status(context.Background()) @@ -488,9 +435,6 @@ func assertClean(t testing.TB, m *migrate.Migrator, versions ...int) { } } -// assertReverted checks Status reports every set fully reverted: version 0, -// all of its migrations pending (the set's count, given per set in declared -// order), and clean. func assertReverted(t testing.TB, m *migrate.Migrator, migrations ...int) { t.Helper() sets, err := m.Status(context.Background()) @@ -507,7 +451,6 @@ func assertReverted(t testing.TB, m *migrate.Migrator, migrations ...int) { } } -// seedRows writes a row in each table, the upper one referencing the lower one. func seedRows(t testing.TB, db *sqlate.DB) { t.Helper() ctx := context.Background() @@ -521,8 +464,6 @@ func seedRows(t testing.TB, db *sqlate.DB) { } } -// assertDependentObjects checks err is a SetError naming set over SQLSTATE -// 2BP01, classified as sqlate.ErrDependentObjects. func assertDependentObjects(t testing.TB, what string, err error, set string) { t.Helper() var se *migrate.SetError @@ -534,10 +475,6 @@ func assertDependentObjects(t testing.TB, what string, err error, set string) { } } -// Proof: fresh replay. Up on an empty database applies both sets and Status -// reports them clean; Reset leaves neither the sets' objects nor their -// history tables; Up again replays every set from zero, so a row written -// between the runs does not survive. func TestLive_MultisetFreshReplay(t *testing.T) { ctx := context.Background() db := live(t) @@ -582,11 +519,6 @@ func TestLive_MultisetFreshReplay(t *testing.T) { } } -// Proof: the upgrade rehearsal. A database installed at lower version 2 -// holds rows; a migrator over the set with the rehearsal as version 3, on a -// second pool as a restarted process would open, applies only the fixture; -// the rows and the earlier history rows survive untouched; and the older -// binary's view of the newer history is ErrUnknownVersion. func TestLive_MultisetUpgradeAfterRestart(t *testing.T) { ctx := context.Background() db := live(t) @@ -603,7 +535,6 @@ func TestLive_MultisetUpgradeAfterRestart(t *testing.T) { rowsBefore := count(t, db, "SELECT (SELECT COUNT(*) FROM live_ms_lower) + (SELECT COUNT(*) FROM live_ms_upper)") appliedAt := text(t, db, "SELECT applied_at::text FROM "+lowerHistory+" WHERE version = 1") - // The restart: a second pool over the same database. restarted := live(t) upgraded := migratorOver(t, restarted, multiset(true), migrate.Options{}) status, err := upgraded.Status(ctx) @@ -623,34 +554,17 @@ func TestLive_MultisetUpgradeAfterRestart(t *testing.T) { if n := count(t, restarted, "SELECT COUNT(*) FROM "+lowerHistory); n != 3 { t.Errorf("lower history holds %d rows after the upgrade, want 3", n) } - // Only the fixture was applied: row 1 keeps the applied_at of the install. if got := text(t, restarted, "SELECT applied_at::text FROM "+lowerHistory+" WHERE version = 1"); got != appliedAt { t.Errorf("version 1 applied_at = %s after the upgrade, was %s: the upgrade re-applied it", got, appliedAt) } if rowsAfter := count(t, restarted, "SELECT (SELECT COUNT(*) FROM live_ms_lower) + (SELECT COUNT(*) FROM live_ms_upper)"); rowsAfter != rowsBefore { t.Errorf("%d rows after the upgrade, %d before", rowsAfter, rowsBefore) } - // The older binary, over the two-migration set, sees a history row it does not carry. if err := installed.Verify(ctx); !errors.Is(err, migrate.ErrUnknownVersion) { t.Errorf("the installed binary's Verify over the upgraded history = %v, want ErrUnknownVersion", err) } } -// Proof: reset order across foreign keys. With a row in live_ms_upper -// referencing live_ms_lower, Reset succeeds because the upper set reverts -// first. A migrator holding both sets refuses to revert the lower one while -// the upper has applied migrations, before the engine is touched -// (ErrAboveApplied). A migrator declared in the wrong order, and one holding -// the lower set alone, reach the engine and are refused there: a SetError -// naming the lower set over SQLSTATE 2BP01, classified as -// sqlate.ErrDependentObjects. -// -// Finding: the refusal stops the set at the migration that fails, and the -// migrations above it are already reverted. The lower set runs with the -// rehearsal as version 3: the wrong-order reset drops the index (3) and the -// column (2) in their own transactions and then fails at version 1's DROP -// TABLE, so the lower head is 1 afterwards. The history stays consistent -// with the schema, and the right order succeeds after. func TestLive_MultisetResetOrderAcrossForeignKeys(t *testing.T) { ctx := context.Background() db := live(t) @@ -703,14 +617,8 @@ func TestLive_MultisetResetOrderAcrossForeignKeys(t *testing.T) { assertRelations(t, db, false, objects...) } -// gateName is the advisory lock the test holds so a starter's first -// migration blocks inside its run, holding the migrator's lock, until the -// test has seen the second starter wait. const gateName = "live.gate" -// gateSet is a set whose one migration creates a table and then waits on the -// gate inside its transaction. The two statements run as one text: migrate -// hands a zero-argument Exec to pgx, which runs it over the simple protocol. var gateSet = migrate.Set{ Name: "gate", Table: "live_gate_history", @@ -723,9 +631,6 @@ var gateSet = migrate.Set{ }}, } -// holdGate takes the gate on a pinned connection and returns the release, -// which cleanup also runs, so a failed wait does not leave the starters -// blocked behind the gate while the pool's Close waits for them. func holdGate(t *testing.T, db *sqlate.DB) func() { t.Helper() ctx := context.Background() @@ -749,8 +654,6 @@ func holdGate(t *testing.T, db *sqlate.DB) func() { return release } -// waitForWaiters polls pg_stat_activity, scoped to the test's database, -// until n backends wait on a lock. func waitForWaiters(t *testing.T, db *sqlate.DB, n int) { t.Helper() deadline := time.Now().Add(20 * time.Second) @@ -766,15 +669,6 @@ func waitForWaiters(t *testing.T, db *sqlate.DB, n int) { } } -// waitForQueue polls pg_stat_activity, scoped to the test's database, until -// one starter waits on the gate inside its run, holding the migrator's lock, -// and another waits for that lock: refused by a try-lock it polls, or, on a -// dialect migrate cannot poll, blocked in the lock statement. A polling -// waiter is idle between attempts, and pg_stat_activity keeps an idle -// backend's last statement, so only a try-lock issued after the wait began -// counts: the waiter retries within a second, while a backend left idle -// after an earlier try-lock never does. The gate holder's own lock -// statement is idle, so it never counts as the waiter. func waitForQueue(t *testing.T, db *sqlate.DB) { t.Helper() const ( @@ -793,8 +687,6 @@ func waitForQueue(t *testing.T, db *sqlate.DB) { } } -// startBoth releases two starters through a barrier and runs each one's Up, -// returning the two errors once both have ended. func startBoth(ctx context.Context, a, b *migrate.Migrator) (errA, errB error) { var start, done sync.WaitGroup start.Add(1) @@ -811,17 +703,6 @@ func startBoth(ctx context.Context, a, b *migrate.Migrator) (errA, errB error) { return errA, errB } -// Proof: two starters serialize under one lock. Two migrators over the gate -// set and both real sets start Up together on one empty database. The first -// to take the lock blocks on the gate inside its first migration; the test -// sees the second waiting for the migrator's lock before it releases the -// gate. Both succeed, every migration is applied once, and each history -// holds one row per migration. The control runs the same race Unlocked: the -// second starter then waits on the first's transaction instead and fails -// with a duplicate object, which is what the lock prevents. Postgres reports -// it as a unique violation on the catalog's own index (23505) when the -// second CREATE TABLE waited on the first's transaction, or as 42P07 when the -// first had committed before the check. func TestLive_MultisetStartersSerialize(t *testing.T) { ctx := context.Background() db := live(t) @@ -851,8 +732,6 @@ func TestLive_MultisetStartersSerialize(t *testing.T) { } } - // Revert every set with the history tables left in place, so the - // control's two preflights find them and do not race on creating them. layers := a.Layers() for _, layer := range slices.Backward(layers) { if err := layer.Down(ctx, len(layer.Migrations())); err != nil { @@ -863,7 +742,6 @@ func TestLive_MultisetStartersSerialize(t *testing.T) { assertRelations(t, db, true, "live_gate_history", lowerHistory, upperHistory) assertRelations(t, db, false, "live_gate", "live_ms_lower", "live_ms_upper") - // The control: the same race without the lock. release = holdGate(t, db) a = migratorOver(t, db, sets, migrate.Options{Unlocked: true}) b = migratorOver(t, db, sets, migrate.Options{Unlocked: true}) @@ -883,7 +761,6 @@ func TestLive_MultisetStartersSerialize(t *testing.T) { t.Errorf("the unlocked loser failed with %v, want a duplicate object (SQLSTATE 42P07 or 23505)", failed) } t.Logf("the unlocked loser failed with SQLSTATE %s: %v", sqlState(failed), failed) - // The winner still applied everything once. for table, want := range histories { if n := count(t, db, "SELECT COUNT(*) FROM "+table); n != want { t.Errorf("after the control %s holds %d rows, want %d", table, n, want) @@ -891,15 +768,6 @@ func TestLive_MultisetStartersSerialize(t *testing.T) { } } -// Proof: dirty refusal on the engine, across sets. A non-transactional -// migration whose statement fails leaves its history row dirty. A migrator -// holding the lower set below the dirty set refuses every mutating verb, -// its own and its layers', with a SetError naming the dirty set and the -// version, classified as ErrDirty, before the lower set runs. Status and the -// probe layer's Verify report it; the migrator's Verify reports the first -// fault in declared order, which is the lower set's pending migrations. Force to version 0, the operator's statement that -// nothing of the set is applied, clears the mark, and Reset then leaves no -// history table. func TestLive_MultisetDirtyRefusal(t *testing.T) { ctx := context.Background() db := live(t) @@ -937,9 +805,6 @@ func TestLive_MultisetDirtyRefusal(t *testing.T) { t.Errorf("%s over a dirty set = %v, want ErrDirty naming set probe at version 1", name, err) } } - // Verify reports the first fault in declared order, so the lower set, - // never applied, faults as pending before the probe is reached; the - // probe's own layer reports the dirty row. var se *migrate.SetError if err := m.Verify(ctx); !errors.Is(err, migrate.ErrPending) || !errors.As(err, &se) || se.Set != "lower" { t.Errorf("Verify over a pending lower set and a dirty probe = %v, want ErrPending naming set lower first", err) @@ -948,7 +813,6 @@ func TestLive_MultisetDirtyRefusal(t *testing.T) { if err := probeLayer.Verify(ctx); !errors.Is(err, migrate.ErrDirty) || !errors.As(err, &se) || se.Set != "probe" || !errors.As(err, &de) || de.Version != 1 { t.Errorf("the probe layer's Verify = %v, want ErrDirty naming set probe at version 1", err) } - // Nothing of the lower set ran; preflight created its history table and left it empty. assertRelations(t, db, false, "live_ms_lower") status, err := m.Status(ctx) if err != nil { @@ -961,8 +825,8 @@ func TestLive_MultisetDirtyRefusal(t *testing.T) { t.Errorf("probe status = %+v, want version 1 dirty", p) } - if err := m.Force(ctx, 0); err != nil { // probe is the top set - t.Fatalf("Force: %v", err) + if err := m.Force(ctx, 0); err != nil { + t.Fatalf("Force on probe, the top set: %v", err) } if status, _ := m.Status(ctx); status[1].Dirty || status[1].Version != 0 { t.Errorf("probe status after Force = %+v, want version 0 clean", status[1]) @@ -971,7 +835,6 @@ func TestLive_MultisetDirtyRefusal(t *testing.T) { t.Fatalf("Reset after Force: %v", err) } assertRelations(t, db, false, "live_probe_history", lowerHistory) - // Up applies the lower set and dirties the probe again. err = m.Up(ctx) if !errors.As(err, &se) || se.Set != "probe" || !errors.As(err, &de) || de.Version != 1 { t.Errorf("Up after the reset = %v, want the probe's DirtyError again", err) @@ -979,12 +842,6 @@ func TestLive_MultisetDirtyRefusal(t *testing.T) { assertRelations(t, db, true, "live_ms_lower") } -// Proof: the history existence check is schema-qualified. A table of the -// history's name in another schema satisfies migrate.StandardCatalog's -// unqualified form and not the dialect's; the migrator's reads over the pool -// (Version, Status, Verify) therefore report an absent history rather than -// reading a table the current schema does not hold, and Up creates the real -// one in the current schema, leaving the decoy untouched. func TestLive_HistoryExistsIsSchemaQualified(t *testing.T) { ctx := context.Background() db := live(t) @@ -999,7 +856,6 @@ func TestLive_HistoryExistsIsSchemaQualified(t *testing.T) { t.Fatal(err) } - // The decoy is visible to the unqualified form and invisible to the qualified one. if n := count(t, db, migrate.StandardCatalog{}.HistoryExists("$1"), history); n != 1 { t.Fatalf("the standard existence check counts %d, want 1: the decoy is not visible and this proof proves nothing", n) } @@ -1033,13 +889,6 @@ func TestLive_HistoryExistsIsSchemaQualified(t *testing.T) { } } -// Proof: a history table created before v0.5.0, its applied_at a timestamp -// without time zone, is altered in place on the next Up. The column becomes -// timestamp with time zone, each stored wall clock is read as UTC whatever -// the session's zone (Asia/Tokyo here, nine hours from UTC, so a conversion -// through the session's zone would move the instant), the default still -// stamps new rows, and a second Up finds the table current and leaves it -// alone. func TestLive_HistoryUpgradeKeepsEachInstant(t *testing.T) { ctx := context.Background() db := liveIn(t, "Asia/Tokyo") @@ -1088,8 +937,6 @@ func TestLive_HistoryUpgradeKeepsEachInstant(t *testing.T) { } } -// Proof: a history the dialect creates is timestamp with time zone from -// the start, and the outdated check does not report it. func TestLive_HistoryIsCreatedTimeZoneAware(t *testing.T) { ctx := context.Background() db := live(t) @@ -1107,16 +954,6 @@ func TestLive_HistoryIsCreatedTimeZoneAware(t *testing.T) { } } -// Proof: a concurrent index build does not deadlock the waiter. The first -// starter to take the lock creates a table and blocks on the gate inside -// that migration; the test sees the second waiting for the migrator's lock, -// then releases the gate, and the holder runs CREATE INDEX CONCURRENTLY, -// which waits for every transaction open when it starts. A waiter blocked in -// pg_advisory_lock holds its statement open, so the build and the waiter -// wait on each other and postgres aborts one with deadlock_detected (40P01); -// migrate polls pg_try_advisory_lock instead, leaving nothing open while it -// waits. Both starters succeed, each migration is applied once, and the -// index exists and is valid. func TestLive_ConcurrentIndexBuildDoesNotDeadlockTheWaiter(t *testing.T) { ctx := context.Background() db := live(t) diff --git a/postgres/patterns_test.go b/postgres/patterns_test.go index 157ff56..2d4bc38 100644 --- a/postgres/patterns_test.go +++ b/postgres/patterns_test.go @@ -12,8 +12,6 @@ import ( "github.com/standards-lab/sqlate/sqltest" ) -// The engine's patterns are the library's with the keyset predicate alone -// respelled: every other pattern is accepted as written. func TestPatterns_RespellOnlyTheKeysetPredicate(t *testing.T) { library := query.MustCatalog(query.Patterns()).Patterns() engine := query.MustCatalog(postgres.Patterns()).Patterns() @@ -31,8 +29,6 @@ func TestPatterns_RespellOnlyTheKeysetPredicate(t *testing.T) { } } -// A cursor issued by one page continues on the next through the overlay's -// row-value comparison, each keyed value bound once. func TestPatterns_CursorContinuesWithARowValueComparison(t *testing.T) { view := query.MustCatalog(postgres.Patterns()).MustCompile(fstest.MapFS{ "sql/member.sql": {Data: []byte("--| tier: standard\n--| key: org, id\n--| field: org uuid not null\n--| field: id uuid not null\nSELECT org, id FROM member")}, diff --git a/postgres/pgtest/pgtest.go b/postgres/pgtest/pgtest.go index 69a1840..f0a08dc 100644 --- a/postgres/pgtest/pgtest.go +++ b/postgres/pgtest/pgtest.go @@ -11,14 +11,12 @@ import ( "time" "github.com/jackc/pgx/v5" - _ "github.com/jackc/pgx/v5/stdlib" // registers the "pgx" database/sql driver + _ "github.com/jackc/pgx/v5/stdlib" "github.com/standards-lab/sqlate" "github.com/standards-lab/sqlate/migrate" "github.com/standards-lab/sqlate/postgres" ) -// timeout bounds each statement the package runs against the server, and -// each attempt of the drop separately. const timeout = 30 * time.Second // Database is one test's throwaway database: the pool over it and the DSN @@ -67,9 +65,6 @@ func Migrated(t testing.TB, env, prefix string, sets ...migrate.Set) *Database { return d } -// scratch creates the database _test_ over a connection to -// admin and returns its name, registering its drop as a cleanup. The name -// is quoted, so it reaches the server exactly as the DSN spells it. func scratch(t testing.TB, admin, prefix string) string { t.Helper() name := prefix + "_test_" + suffix(t) @@ -81,9 +76,6 @@ func scratch(t testing.TB, admin, prefix string) string { ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() if _, err := db.ExecContext(ctx, "CREATE DATABASE "+ident); err != nil { - // A create that timed out can still finish on the server, so the - // database is dropped if it exists, on a context of its own: ctx - // may be the one that expired. dctx, dcancel := context.WithTimeout(context.Background(), timeout) _, _ = db.ExecContext(dctx, "DROP DATABASE IF EXISTS "+ident+" WITH (FORCE)") dcancel() @@ -91,9 +83,6 @@ func scratch(t testing.TB, admin, prefix string) string { t.Fatalf("create database %s: %v", name, err) } t.Cleanup(func() { - // WITH (FORCE) ends the database's other sessions, and the server - // can still report one closing, so the drop retries, each attempt - // with a deadline of its own so one stall does not use up the rest. var err error for attempt := range 4 { if attempt > 0 { @@ -114,8 +103,6 @@ func scratch(t testing.TB, admin, prefix string) string { return name } -// pool opens a pool on dsn and pings it. Its cleanup is registered after -// the drop's, so it runs first: the pool closes before the database drops. func pool(t testing.TB, dsn string) *sql.DB { t.Helper() p, err := sql.Open("pgx", dsn) @@ -131,7 +118,6 @@ func pool(t testing.TB, dsn string) *sql.DB { return p } -// databaseDSN returns admin with its database replaced by name. func databaseDSN(t testing.TB, admin, name string) string { t.Helper() u, err := url.Parse(admin) @@ -142,8 +128,6 @@ func databaseDSN(t testing.TB, admin, name string) string { return u.String() } -// suffix returns eight random hex characters, so parallel tests and -// packages never pick the same database name. func suffix(t testing.TB) string { var b [4]byte if _, err := rand.Read(b[:]); err != nil { diff --git a/postgres/pgtest/pgtest_live_test.go b/postgres/pgtest/pgtest_live_test.go index 62fe1e8..c96657b 100644 --- a/postgres/pgtest/pgtest_live_test.go +++ b/postgres/pgtest/pgtest_live_test.go @@ -1,8 +1,5 @@ //go:build integration -// The live proof of pgtest runs against the PostgreSQL named by SQLATE_DSN -// (the compose stack: `mise run db:up`, then `mise run integration`) and -// skips when it is unset, the module's live-test convention. package pgtest_test import ( @@ -20,9 +17,6 @@ import ( const env = "SQLATE_DSN" -// Proof: Migrated creates _test_, applies the set to it, and -// the database is dropped when the test that made it ends, even with a -// session of another pool still open on it. func TestLive_MigratedDroppedWithSessionOpen(t *testing.T) { admin := os.Getenv(env) if admin == "" { @@ -65,8 +59,6 @@ func TestLive_MigratedDroppedWithSessionOpen(t *testing.T) { t.Fatalf("the migrated table is not usable: %v", err) } - // A second pool, outside pgtest's cleanup, holds a session open on - // the database past the end of the subtest. held, err = sql.Open("pgx", d.DSN) if err != nil { t.Fatal(err) @@ -85,13 +77,11 @@ func TestLive_MigratedDroppedWithSessionOpen(t *testing.T) { if exists(t, admin, name) { t.Errorf("database %s still exists after its test's cleanup", name) } - // The drop ended the held session rather than waiting for it. if err := conn.PingContext(ctx); err == nil { t.Error("the held session survived the drop") } } -// exists reports whether the server admin connects to has the database. func exists(t testing.TB, admin, name string) bool { t.Helper() db, err := sql.Open("pgx", admin) diff --git a/postgres/query_live_test.go b/postgres/query_live_test.go index 9cdc3e4..dc98aff 100644 --- a/postgres/query_live_test.go +++ b/postgres/query_live_test.go @@ -1,9 +1,5 @@ //go:build integration -// Live proofs for the projection and the guard against the compose -// PostgreSQL: the engine parses request values through the contract's -// declared types, a value it cannot read is an InvalidValueError, and the -// guard's three outcomes hold against real rows. `mise run integration`. package postgres_test import ( @@ -42,7 +38,6 @@ func scanRow(rows query.Row) (row, error) { return r, err } -// liveQ creates the proofs' table with three rows and drops it at cleanup. func liveQ(t testing.TB, db *sqlate.DB) { t.Helper() ctx := context.Background() @@ -56,7 +51,6 @@ func liveQ(t testing.TB, db *sqlate.DB) { } } -// liveStatements compiles the proofs' files over the engine's patterns. func liveStatements(db *sqlate.DB) *query.Statements { return query.MustCatalog(postgres.Patterns()).MustCompile(liveFiles, "sql", db.Dialect()) } @@ -71,8 +65,6 @@ func TestLive_ProjectionAndGuard(t *testing.T) { t.Fatalf("Verify: %v", err) } - // Request values arrive as text and the engine parses them by the - // contract's types: "2" as integer, an RFC 3339 date as timestamp. c, err := view.List(ctx, db, query.Directives{ Sort: []query.Sort{{Field: "n", Descending: true}}, Filters: []query.Filter{{Field: "n", Op: query.OpGe, Value: "2"}, {Field: "at", Op: query.OpIsNotNull}}, @@ -83,14 +75,10 @@ func TestLive_ProjectionAndGuard(t *testing.T) { c, err = view.List(ctx, db, query.Directives{ Filters: []query.Filter{{Field: "at", Op: query.OpLt, Value: "2026-02-01T00:00:00Z"}, {Field: "name", Op: query.OpIn, Value: []any{"a", "b", "c"}}}, }, query.Page{Number: 2, Size: 2}) - // A page past the end has no row to carry the count, so it reports - // none rather than a count its statement never read. if err != nil || c.Total != query.NoTotal || len(c.Items) != 0 || c.More { t.Fatalf("page past the end: List = %+v, %v; want no items and NoTotal", c, err) } - // A value the engine cannot read as the field's type is the request's - // fault, classified through the dialect's class-22 mapping. for _, f := range []query.Filter{ {Field: "id", Op: query.OpEq, Value: "not-a-uuid"}, {Field: "n", Op: query.OpGt, Value: "many"}, @@ -139,9 +127,6 @@ type pageRow struct { N int64 } -// recorder is the session the cursor proof reads through: *sqlate.DB with -// every query's text kept, so the proof can say which spelling of the keyset -// predicate the engine ran. type recorder struct { *sqlate.DB queries []string @@ -152,12 +137,6 @@ func (r *recorder) QueryContext(ctx context.Context, q string, args ...any) (*sq return r.DB.QueryContext(ctx, q, args...) } -// Proof: cursor paging end to end through the engine's row-value overlay. A -// walk by cursor over a two-column keyed prefix (text, then the uuid key) -// yields the rows of the offset read in the same order with no gap or -// repeat, the total holds on every page, the last page issues no cursor, the -// descending walk continues with the opposite comparison, and a cursor from -// another ordering is refused before any SQL. func TestLive_CursorPagingThroughTheOverlay(t *testing.T) { ctx := context.Background() db := live(t) @@ -210,8 +189,6 @@ func TestLive_CursorPagingThroughTheOverlay(t *testing.T) { if !slices.Equal(walked, whole.Items) { t.Errorf("cursor walk = %v\nwant the offset read %v", walked, whole.Items) } - // Each continued page is one statement carrying both the row-value - // keyset predicate and the window that counts its total. const rowValue = "(q.grp, q.id) > (CAST($1 AS text), CAST($2 AS uuid))" continued := 0 for _, q := range rec.queries { @@ -223,8 +200,6 @@ func TestLive_CursorPagingThroughTheOverlay(t *testing.T) { t.Errorf("%d queries carried the row-value keyset predicate and the window count, want 2 (pages 2 and 3):\n%s", continued, strings.Join(rec.queries, "\n")) } - // Descending: the keyed prefix takes the sort's direction and the - // comparison flips. desc := []query.Sort{{Field: "grp", Descending: true}} wholeDesc, err := pages.List(ctx, db, query.Directives{Sort: desc}, query.Page{Number: 1, Size: 10}) if err != nil { @@ -264,15 +239,6 @@ func scanVersioned(rows query.Row) (versioned, error) { return v, err } -// Proof: the typed guard's three outcomes against real rows, on both forms -// of the returning command: the engine's RETURNING, and the command then its -// read under a dialect that hides the capability. The publish command -// carries a predicate of its own beyond the key and the version (n > 1), so -// a row at the expected version can still refuse the write: no row is -// sql.ErrNoRows, another version is ErrVersionMismatch with both versions in -// its text, and the expected version refused by the command's own predicate -// is a *RefusedError carrying the row the handle read back. A hit returns -// the changed row at its new version. func TestLive_RowGuardThreeWay(t *testing.T) { ctx := context.Background() db := live(t) @@ -291,11 +257,11 @@ func TestLive_RowGuardThreeWay(t *testing.T) { } view := stmts.Statement("view").Project(scanRow) publish := stmts.Statement("publish").Returning(scanVersioned).Guarded("version", func(v versioned) int64 { return v.Version }) - a, err := view.One(ctx, db, "name", "a") // n = 1: the command's own predicate refuses it + refusedByPredicate, err := view.One(ctx, db, "name", "a") if err != nil { t.Fatal(err) } - c, err := view.One(ctx, db, "name", "c") // n = 3 + publishable, err := view.One(ctx, db, "name", "c") if err != nil { t.Fatal(err) } @@ -303,23 +269,23 @@ func TestLive_RowGuardThreeWay(t *testing.T) { if _, err := publish.Run(ctx, db, 1, query.Args{"id": "00000000-0000-0000-0000-000000000000", "name": "x"}); !errors.Is(err, sql.ErrNoRows) { t.Errorf("no row = %v, want sql.ErrNoRows", err) } - _, err = publish.Run(ctx, db, 7, query.Args{"id": a.ID, "name": "x"}) + _, err = publish.Run(ctx, db, 7, query.Args{"id": refusedByPredicate.ID, "name": "x"}) if !errors.Is(err, query.ErrVersionMismatch) || !strings.Contains(err.Error(), "expected 7, current 1") { t.Errorf("another version = %v, want ErrVersionMismatch expected 7, current 1", err) } - _, err = publish.Run(ctx, db, 1, query.Args{"id": a.ID, "name": "x"}) + _, err = publish.Run(ctx, db, 1, query.Args{"id": refusedByPredicate.ID, "name": "x"}) var refused *query.RefusedError[versioned] - if !errors.As(err, &refused) || !errors.Is(err, query.ErrRefused) || refused.Version != 1 || refused.Row.ID != a.ID || refused.Row.Name != "a" || refused.Row.N != 1 || refused.Row.Version != 1 { + if !errors.As(err, &refused) || !errors.Is(err, query.ErrRefused) || refused.Version != 1 || refused.Row.ID != refusedByPredicate.ID || refused.Row.Name != "a" || refused.Row.N != 1 || refused.Row.Version != 1 { t.Errorf("refused at the expected version = %v (%+v), want a RefusedError carrying row a at version 1", err, refused) } - hit, err := publish.Run(ctx, db, 1, query.Args{"id": c.ID, "name": "C"}) - if err != nil || hit.ID != c.ID || hit.Name != "C" || hit.Version != 2 { + hit, err := publish.Run(ctx, db, 1, query.Args{"id": publishable.ID, "name": "C"}) + if err != nil || hit.ID != publishable.ID || hit.Name != "C" || hit.Version != 2 { t.Fatalf("hit = %+v, %v, want row c named C at version 2", hit, err) } - if got, _ := view.One(ctx, db, "id", c.ID); got.Name != "C" { + if got, _ := view.One(ctx, db, "id", publishable.ID); got.Name != "C" { t.Errorf("the hit did not persist: %+v", got) } - if got, _ := view.One(ctx, db, "id", a.ID); got.Name != "a" { + if got, _ := view.One(ctx, db, "id", refusedByPredicate.ID); got.Name != "a" { t.Errorf("the refused write changed the row: %+v", got) } }) @@ -331,11 +297,6 @@ var probeFiles = fstest.MapFS{ "sql/mistyped.sql": {Data: []byte("--| tier: standard\n--| key: id\n--| field: id uuid not null\n--| field: n text\nSELECT id, n FROM live_q")}, } -// Proof: the field-contract probe. A base whose SQL prepares but whose -// declared contract names a field it does not output, or declares a type -// the engine cannot compare its column against, fails Verify at startup: -// the misspelled field as an undefined column (42703), the mistyped one as -// an operator the engine does not have (42883). func TestLive_TypeProbe(t *testing.T) { ctx := context.Background() db := live(t) @@ -358,9 +319,6 @@ func TestLive_TypeProbe(t *testing.T) { } } -// Identity is the sub-struct the embedded-scan proof shares between -// entities. It is exported because the mapper reaches an embedded struct -// through an exported field only. type Identity struct { ID string CreatedAt sql.NullTime `db:"at"` @@ -372,10 +330,6 @@ type entity struct { N int64 } -// Proof: an untagged embedded struct flattens into the outer type's columns -// against a real multi-column row: id and at (through its db tag) land in -// the embedded Identity, name and n in the entity itself, both through the -// row handle and through the projection. func TestLive_EmbeddedStructScan(t *testing.T) { ctx := context.Background() db := live(t) @@ -401,13 +355,6 @@ func TestLive_EmbeddedStructScan(t *testing.T) { } } -// Proof: the not-null violation's column. The engine names the column and -// the table on a null in a NOT NULL column and no constraint, so -// ConstraintError.Column is the consumer's handle to the field; a named -// constraint, the primary key here, fills Constraint instead. PostgreSQL 18 -// records a NOT NULL as a named constraint in pg_constraint -// (live_q_name_not_null), and its error report still leaves the constraint -// name out. func TestLive_NotNullNamesTheColumn(t *testing.T) { ctx := context.Background() db := live(t) @@ -429,7 +376,6 @@ func TestLive_NotNullNamesTheColumn(t *testing.T) { } t.Logf("not-null: %v", err) - // The contrast: a named constraint fills Constraint. _, err = db.ExecContext(ctx, "INSERT INTO live_q (id, name, n) SELECT id, 'dup', 9 FROM live_q LIMIT 1") if !errors.As(err, &ce) || !errors.Is(err, sqlate.ErrUniqueViolation) || ce.Constraint != "live_q_pkey" { t.Errorf("duplicate key = %v, want a ConstraintError naming live_q_pkey", err) @@ -437,13 +383,6 @@ func TestLive_NotNullNamesTheColumn(t *testing.T) { t.Logf("unique: %v", err) } -// Proof: a timestamp with time zone read through Scanner and Scalar is in -// time.UTC while time.Local is not (Europe/London, from TestMain). pgx -// delivers the column in time.Local: in summer London's wall clock is an -// hour ahead and the driver's value prints as BST, while in winter it prints -// as GMT and only a comparison of whole values tells it from UTC. The proof -// first checks that the driver's own value is not in UTC, so it cannot pass -// vacuously. func TestLive_ScanReturnsTimesInUTC(t *testing.T) { ctx := context.Background() db := live(t) diff --git a/postgres/returning_live_test.go b/postgres/returning_live_test.go index 3016325..a72c05a 100644 --- a/postgres/returning_live_test.go +++ b/postgres/returning_live_test.go @@ -1,14 +1,5 @@ //go:build integration -// Live proof for the returning command against the compose PostgreSQL. The -// same files compile twice: under the dialect, which renders each command's -// single-statement form with RETURNING, and under a wrapper that hides the -// query.Returner capability, so each command runs the fallback, the command -// and then its read in a transaction. In every outcome of a plain and a -// guarded command, both forms return the row an immediate read returns, -// on the pool and inside a caller's transaction; they differ only in the -// statements the engine receives. -// `mise run integration`. package postgres_test import ( @@ -31,8 +22,6 @@ import ( "github.com/standards-lab/sqlate/query" ) -// returningFS holds the proof's pattern namespace, live, and its statements: -// the read, and three returning commands naming it. var returningFS = fstest.MapFS{ "patterns/item_columns.sql": {Data: []byte("--| tier: standard\ni.id, i.status, i.size, i.version, i.created_at, i.updated_at")}, "sql/item_by_id.sql": {Data: []byte("--| tier: standard\nSELECT {{> live.item_columns}} FROM item i WHERE i.id = {{id}}")}, @@ -54,13 +43,8 @@ func scanItem(rows query.Row) (item, error) { return it, err } -// shape is the row less what differs between the two forms by construction: -// the client-supplied id and the timestamps. func shape(it item) item { return item{Status: it.Status, Size: it.Size, Version: it.Version} } -// tracer records the statements the engine receives, by leading keyword: -// the count below the session, where a transaction's statements are -// visible too. type tracer struct { mu sync.Mutex sent []string @@ -85,8 +69,6 @@ func (tr *tracer) take() []string { return sent } -// liveTraced is live over a pool whose connections report every statement -// to the returned tracer. func liveTraced(t testing.TB) (*sqlate.DB, *tracer) { t.Helper() dsn := os.Getenv("SQLATE_DSN") @@ -107,8 +89,6 @@ func liveTraced(t testing.TB) (*sqlate.DB, *tracer) { return sqlate.Wrap(pool, postgres.Dialect{}), tr } -// counted is the session each scenario runs through: *sqlate.DB with the -// calls a returning handle makes on it counted. type counted struct { *sqlate.DB exec, query, begin int @@ -129,22 +109,17 @@ func (c *counted) Begin(ctx context.Context, opts *sql.TxOptions) (*sqlate.Tx, e return c.DB.Begin(ctx, opts) } -// calls is what one scenario cost: the session's calls and the engine's -// statements. type calls struct { exec, query, begin int sent []string } -// result is one scenario's outcome: the row, whether the command changed -// it, and the error. type result struct { row item changed bool err error } -// form is one compilation of the proof's files and its handles. type form struct { name string stmts *query.Statements @@ -152,21 +127,11 @@ type form struct { create query.Returning[item] claim query.RowGuard[item] retire query.Returning[item] - changed calls // a changed row: the cost the form promises - same calls // an unchanged row that exists - absent calls // no row at all + changed calls + same calls + absent calls } -// Proof: the returning command's two forms return the same row. Every -// scenario runs on both: an insert; a guarded claim that succeeds, meets -// another version, is refused by its own status predicate, and finds no -// row; a predicate-form retire, then the same retire again, which changes -// nothing and returns the retired row. Each result equals an immediate read -// by the read statement, and the forms' rows are equal apart from the id and -// timestamps. The single-statement form is one query for a changed row and -// two for an unchanged one; the fallback is a transaction it begins, -// holding the command and then its read. A column renamed out from under -// the read fails Verify, naming the single-statement form (returning). func TestLive_ReturningTwoForms(t *testing.T) { ctx := context.Background() db, tr := liveTraced(t) @@ -221,8 +186,6 @@ func TestLive_ReturningTwoForms(t *testing.T) { } } - // run runs one scenario's operation on a counted session and reports - // its result and what it cost. run := func(op func(s sqlate.Session) (item, bool, error)) (result, calls) { s := &counted{DB: db} tr.take() @@ -242,7 +205,7 @@ func TestLive_ReturningTwoForms(t *testing.T) { scenarios := []struct { name string verb string - key string // the item the outcome is read back by + key string op func(f form, id func(string) string) func(sqlate.Session) (item, bool, error) cost func(f form) calls check func(r result) bool @@ -315,8 +278,6 @@ func TestLive_ReturningTwoForms(t *testing.T) { }, } - // Item b, held, is the row the claim's own predicate refuses at the - // expected version. for _, f := range forms { if _, _, err := f.create.One(ctx, db, query.Args{"id": f.name + "-b", "status": "held", "size": 5}); err != nil { t.Fatalf("%s: create b: %v", f.name, err) @@ -359,9 +320,6 @@ func TestLive_ReturningTwoForms(t *testing.T) { } } - // A column renamed out from under the read: the claim and the retire do - // not name it, so their own text still prepares and only their - // single-statement form fails, named (returning). if _, err := db.ExecContext(ctx, "ALTER TABLE item RENAME COLUMN size TO bulk"); err != nil { t.Fatal(err) } @@ -377,8 +335,6 @@ func TestLive_ReturningTwoForms(t *testing.T) { } } -// txFS is the proof's statements over their own table, so the scenarios -// inside a caller's transaction share no rows with the two-forms proof. var txFS = fstest.MapFS{ "sql/tx_item_by_id.sql": {Data: []byte("--| tier: standard\nSELECT i.id, i.status, i.size, i.version, i.created_at, i.updated_at FROM tx_item i WHERE i.id = {{id}}")}, "sql/tx_create.sql": {Data: []byte("--| tier: standard\n--| returning: tx_item_by_id\nINSERT INTO tx_item (id, status, size) VALUES ({{id}}, {{status}}, {{size}})")}, @@ -386,14 +342,6 @@ var txFS = fstest.MapFS{ "sql/tx_retire.sql": {Data: []byte("--| tier: standard\n--| returning: tx_item_by_id\nUPDATE tx_item\nSET status = 'retired', version = version + 1\nWHERE id = {{id}} AND status <> 'retired'")}, } -// Proof: both forms run inside a caller's transaction, on the one -// connection it holds. In one db.Transact per form: an insert; a guarded -// claim that succeeds, then meets another version; a retire, then the same -// retire again, which changes nothing. On the single-statement form an -// unchanged outcome is the command returning no row and then the read on -// the same connection, which the driver refuses while the command's row set -// is still open. The fallback begins no transaction of its own: the engine -// receives one BEGIN, the caller's, and one COMMIT. func TestLive_ReturningInsideACallersTransaction(t *testing.T) { ctx := context.Background() db, tr := liveTraced(t) @@ -414,16 +362,15 @@ func TestLive_ReturningInsideACallersTransaction(t *testing.T) { for _, f := range []struct { name string d sqlate.Dialect - // sent is what the engine receives for the unit, by leading keyword. sent []string }{ {"native", postgres.Dialect{}, []string{ "BEGIN", - "INSERT", // create: changed - "UPDATE", // claim: changed - "UPDATE", "SELECT", // claim again: unchanged, then the read - "UPDATE", // retire: changed - "UPDATE", "SELECT", // retire again: unchanged, then the read + "INSERT", + "UPDATE", + "UPDATE", "SELECT", + "UPDATE", + "UPDATE", "SELECT", "COMMIT", }}, {"fallback", struct{ sqlate.Dialect }{postgres.Dialect{}}, []string{ diff --git a/postgres/total_live_test.go b/postgres/total_live_test.go index 03d636f..ef90a60 100644 --- a/postgres/total_live_test.go +++ b/postgres/total_live_test.go @@ -1,14 +1,5 @@ //go:build integration -// Live proofs for the exact total against the compose PostgreSQL. The count -// is a window in the page's own statement, so the total and the page read -// one snapshot and agree even while writes land between the statement and -// the caller. A count run as its own statement before the page is shown to -// disagree under the same writes. The agreement holds under concurrent -// writers on the pool, where the two-statement form is shown to disagree -// too. The counted page scans its base once under one -// window, and the uncounted page keeps the key's index order. -// `mise run integration`. package postgres_test import ( @@ -34,10 +25,6 @@ type totalRow struct { N int64 } -// liveTotal creates a proof's table, keyed by a uuid primary key (and so -// indexed on the key), with rows 'x' rows and a fifth as many 'y' rows the -// filters exclude, n spread over 0..999, and drops it at cleanup. It returns -// the table's projection under the engine's patterns. func liveTotal(t testing.TB, db *sqlate.DB, table string, rows int) query.Projection[totalRow] { t.Helper() ctx := context.Background() @@ -61,13 +48,10 @@ func liveTotal(t testing.TB, db *sqlate.DB, table string, rows int) query.Projec return items } -// onlyX is the proofs' filter: the 'x' rows, which every write touches. +const continuedPageOffset = -1 + var onlyX = []query.Filter{{Field: "grp", Op: query.OpEq, Value: "x"}} -// disagreement reports how a page with items disagrees with the total it is -// read against, or "" when they agree. offset is the page's offset, or -1 -// for a Continue page, whose offset is unknown: then only the bounds a -// position does not enter are checked. func disagreement(c query.Collection[totalRow], total, offset, size int) string { n := len(c.Items) for _, it := range c.Items { @@ -82,22 +66,16 @@ func disagreement(c query.Collection[totalRow], total, offset, size int) string return fmt.Sprintf("%d items and no total", n) case c.More && n != size: return fmt.Sprintf("More with %d items on a page of %d", n, size) - case offset < 0 && n > total: + case offset == continuedPageOffset && n > total: return fmt.Sprintf("%d items past a total of %d", n, total) - case offset >= 0 && offset+n > total: + case offset != continuedPageOffset && offset+n > total: return fmt.Sprintf("items end at %d past a total of %d", offset+n, total) - case offset >= 0 && c.More != (offset+n < total): + case offset != continuedPageOffset && c.More != (offset+n < total): return fmt.Sprintf("More = %v with items ending at %d of a total of %d", c.More, offset+n, total) } return "" } -// racer is a session that, each time a query returns, commits a write to the -// filtered rows on a connection of its own: an 'x' row inserted, then the -// lowest 'x' row deleted, alternately. The write lands after the engine has -// begun the query's statement, and so taken its snapshot, and before the -// caller reads a row of it: between a total being computed and the caller -// seeing it. type racer struct { *sqlate.DB t testing.TB @@ -123,7 +101,6 @@ func (r *racer) QueryContext(ctx context.Context, q string, args ...any) (*sql.R return rows, nil } -// countX reads the filtered rows' count now, failing the test on an error. func countX(t testing.TB, s sqlate.Session, table string) int { t.Helper() n, err := readX(s, table) @@ -133,7 +110,6 @@ func countX(t testing.TB, s sqlate.Session, table string) int { return n } -// readX reads the filtered rows' count now. func readX(s sqlate.Session, table string) (int, error) { rows, err := s.QueryContext(context.Background(), "SELECT COUNT(*) FROM "+table+" WHERE grp = 'x'") if err != nil { @@ -148,14 +124,6 @@ func readX(s sqlate.Session, table string) (int, error) { return n, err } -// Proof: the counted total agrees with its page when a write commits between -// the page's statement and the caller reading it. Every read runs through a -// racer, and each page is shown to have raced a write (the count now differs -// from the page's total) and still to agree with its total: a page with More -// is full, and an offset page's items end at or before the total, before it -// exactly when More. The control runs the two-statement form under the -// same racer, an explicit COUNT(*) statement and then an uncounted page, -// and the two disagree every round. func TestLive_TotalAgreesUnderRacingWrites(t *testing.T) { ctx := context.Background() db := live(t) @@ -207,7 +175,7 @@ func TestLive_TotalAgreesUnderRacingWrites(t *testing.T) { if err != nil { t.Fatalf("cursor page %d: %v", page, err) } - offset := -1 // a Continue page's offset is unknown + offset := continuedPageOffset if page == 1 { offset = 0 } @@ -225,9 +193,6 @@ func TestLive_TotalAgreesUnderRacingWrites(t *testing.T) { } t.Logf("counted: %d pages, each raced by a write (%d writes), 0 disagreements", pages, r.writes) - // The counted rounds, the control's shape under TotalExact: each round - // reads every filtered row on one page, so its items number exactly its - // total, and the write racing it still lands. const rounds = 6 agreed := 0 for round := range rounds { @@ -246,16 +211,8 @@ func TestLive_TotalAgreesUnderRacingWrites(t *testing.T) { } t.Logf("counted rounds agreed in %d of %d", agreed, rounds) - // The control: the total from its own statement, then the page. Each - // round's page reads every filtered row, as a counted round does, so it - // agrees with the count only when nothing changed between the two - // statements. disagreed := 0 for round := range rounds { - // Each round runs two queries, so the write racing the count - // would be the same every round; stepping the racer on odd - // rounds puts an insert between the two in some rounds and a - // delete in others. r.writes += round % 2 total := countX(t, r, table) c, err := items.List(ctx, r, query.Directives{Sort: byN, Filters: onlyX, Total: query.TotalNone}, query.Page{Number: 1, Size: 1000}) @@ -276,17 +233,11 @@ func TestLive_TotalAgreesUnderRacingWrites(t *testing.T) { t.Logf("control: two statements disagreed in %d of %d rounds", disagreed, rounds) } -// stressResult is what one stress run saw: its reads and writes, and the -// pages that disagreed with their totals, the first five described. type stressResult struct { lists, continues, writes, violations int64 first []string } -// stress runs two writers that insert and delete batches of 50 filtered -// rows for two seconds against four readers outside any transaction. Each -// reader calls read in a loop, which reports each disagreement it finds -// through violate and whether it continued a page. func stress(t *testing.T, db *sqlate.DB, table string, read func(violate func(string)) (continued int)) stressResult { t.Helper() ctx := context.Background() @@ -306,8 +257,6 @@ func stress(t *testing.T, db *sqlate.DB, table string, read func(violate func(st var wg sync.WaitGroup for range 2 { wg.Go(func() { - // SKIP LOCKED keeps the two writers' deletes from waiting on, - // and so deadlocking with, each other's rows. insert := fmt.Sprintf("INSERT INTO %s (grp, n) SELECT 'x', (random() * 999)::int FROM generate_series(1, 50)", table) del := fmt.Sprintf("DELETE FROM %s WHERE id IN (SELECT id FROM %[1]s WHERE grp = 'x' ORDER BY random() LIMIT 50 FOR UPDATE SKIP LOCKED)", table) for i := 0; time.Now().Before(deadline); i++ { @@ -335,12 +284,6 @@ func stress(t *testing.T, db *sqlate.DB, table string, read func(violate func(st return stressResult{lists: lists.Load(), continues: continues.Load(), writes: writes.Load(), violations: violations.Load(), first: first} } -// Proof: under concurrent writers on the pool, every counted page a reader -// sees agrees with its own total. Four readers run List at a random page and -// Continue from it while the writers run; no page may disagree. The control -// runs the same stress over the two-statement form, a COUNT(*) statement -// and then an uncounted page of the whole filtered listing, and shows the -// stress catches it disagreeing. func TestLive_TotalAgreesUnderConcurrentWrites(t *testing.T) { ctx := context.Background() db := live(t) @@ -354,7 +297,7 @@ func TestLive_TotalAgreesUnderConcurrentWrites(t *testing.T) { t.Errorf("List: %v", err) return 0 } - empty := query.NoTotal // an empty later page carries no count + empty := query.NoTotal if number == 1 { empty = 0 } @@ -373,7 +316,7 @@ func TestLive_TotalAgreesUnderConcurrentWrites(t *testing.T) { if len(c.Items) == 0 && c.Total != query.NoTotal { violate(fmt.Sprintf("empty Continue page: Total = %d", c.Total)) } - if msg := disagreement(c, c.Total, -1, size); msg != "" { + if msg := disagreement(c, c.Total, continuedPageOffset, size); msg != "" { violate("Continue: " + msg) } } @@ -387,9 +330,6 @@ func TestLive_TotalAgreesUnderConcurrentWrites(t *testing.T) { t.Errorf("the stress ran no reads or writes of some kind") } - // The control: the same stress over the two-statement form. Each read - // is the whole filtered listing on one page, so it agrees with the - // count only when no batch committed between the two statements. const control = "live_total_stress_control" plain := liveTotal(t, db, control, 400) res = stress(t, db, control, func(violate func(string)) int { @@ -414,7 +354,6 @@ func TestLive_TotalAgreesUnderConcurrentWrites(t *testing.T) { } } -// capture is a session that keeps the last query's text and arguments. type capture struct { *sqlate.DB text string @@ -426,7 +365,6 @@ func (c *capture) QueryContext(ctx context.Context, q string, args ...any) (*sql return c.DB.QueryContext(ctx, q, args...) } -// planNode is one node of EXPLAIN (FORMAT JSON)'s plan tree. type planNode struct { NodeType string `json:"Node Type"` Relation string `json:"Relation Name"` @@ -440,8 +378,6 @@ type explained struct { ExecutionTime float64 `json:"Execution Time"` } -// explain runs EXPLAIN with the given options over a captured statement and -// its arguments. func explain(t testing.TB, db *sqlate.DB, options string, c *capture) explained { t.Helper() rows, err := db.QueryContext(context.Background(), "EXPLAIN ("+options+") "+c.text, c.args...) @@ -463,7 +399,6 @@ func explain(t testing.TB, db *sqlate.DB, options string, c *capture) explained return out[0] } -// walk visits a plan tree depth first. func walk(n planNode, visit func(planNode)) { visit(n) for _, c := range n.Plans { @@ -471,7 +406,6 @@ func walk(n planNode, visit func(planNode)) { } } -// planShape lists a plan's node types depth first, a scan with its relation. func planShape(n planNode) string { var parts []string walk(n, func(n planNode) { @@ -484,11 +418,6 @@ func planShape(n planNode) string { return strings.Join(parts, " > ") } -// Proof: the plans of the two total modes over 10k rows sorted by the -// indexed key. The counted page has exactly one WindowAgg and scans its base -// relation once, so the count costs no second pass; the uncounted page has no -// WindowAgg and no Sort beneath its Limit, reading the key's index in order. -// Each plan's execution time and shared buffers are logged, not asserted. func TestLive_TotalPlans(t *testing.T) { ctx := context.Background() db := live(t) diff --git a/sqlint/body.go b/sqlint/body.go index 651e6e0..2eeb71e 100644 --- a/sqlint/body.go +++ b/sqlint/body.go @@ -6,30 +6,14 @@ import ( "strings" ) -// guardInclude matches an include of one of the guard protocol's two -// patterns under any namespace, the way the loader parses an include; the -// library publishes them, and an engine overlay or another source may -// respell them, so the name and not the namespace identifies them. var guardInclude = regexp.MustCompile(`\{\{>\s*[a-z_][a-z0-9_]*\.(guard_where|guard_set)\s*\}\}`) -// setClause matches the SET keyword, which marks a statement as one that -// assigns columns: the guarded command, and not the guard's check or a -// guarded delete, neither of which has a version to advance. var setClause = regexp.MustCompile(`(?i)\bSET\b`) -// lintBody checks the body's lines: the reserved delimiter in a comment or -// a literal, the engine's native forms in a standard-tier file, and the -// guard protocol's two includes appearing together. A form is matched -// against the line's code only, string literals and the comment tail -// stripped first, because whether text is data or syntax is a property of -// SQL, not of the engine, and a per-line expression cannot track quote -// state. The guard check spans the body, since the includes sit on -// different lines of a command, and reports on the include that is -// present. func (l *linter) lintBody(p, text string, end int, delimiter, forms, guard bool) { line := 1 + strings.Count(text[:end], "\n") inBlock := false - var whereLine, setLine int // the first guard_where and guard_set includes, 0 for none + var firstGuardWhereLine, firstGuardSetLine int hasSet := false for ln := range strings.SplitSeq(text[end:], "\n") { if delimiter { @@ -52,30 +36,24 @@ func (l *linter) lintBody(p, text string, end int, delimiter, forms, guard bool) if guard { for _, m := range guardInclude.FindAllStringSubmatch(code, -1) { switch { - case m[1] == "guard_where" && whereLine == 0: - whereLine = line - case m[1] == "guard_set" && setLine == 0: - setLine = line + case m[1] == "guard_where" && firstGuardWhereLine == 0: + firstGuardWhereLine = line + case m[1] == "guard_set" && firstGuardSetLine == 0: + firstGuardSetLine = line } } hasSet = hasSet || setClause.MatchString(code) } line++ } - // A guarded command advances the version it checks and checks the - // version it advances; the guard's check and a guarded delete include - // the predicate alone, and have no SET list. - if whereLine > 0 && setLine == 0 && hasSet { - l.report(p, whereLine, "includes guard_where in a SET statement without guard_set; a guarded command advances the version it checks") + if firstGuardWhereLine > 0 && firstGuardSetLine == 0 && hasSet { + l.report(p, firstGuardWhereLine, "includes guard_where in a SET statement without guard_set; a guarded command advances the version it checks") } - if setLine > 0 && whereLine == 0 { - l.report(p, setLine, "includes guard_set without guard_where; a guarded command checks the version it advances") + if firstGuardSetLine > 0 && firstGuardWhereLine == 0 { + l.report(p, firstGuardSetLine, "includes guard_set without guard_where; a guarded command checks the version it advances") } } -// inLiteral reports a {{ inside a single-quoted literal on one line, -// tracking the quote state so a closed literal followed by a parameter is -// not one. func inLiteral(line string) bool { open := false for i := 0; i < len(line); i++ { @@ -89,12 +67,6 @@ func inLiteral(line string) bool { return false } -// codeOnly returns the line with every single-quoted literal and -// double-quoted identifier emptied, the line-comment tail removed, and -// block-comment text removed (inBlock records an open block comment -// across lines), so a form matches syntax and never data, a name, or -// prose. A quote doubled inside a literal ('it”s') closes and reopens, -// which empties it all the same. func codeOnly(line string, inBlock bool) (string, bool) { var b strings.Builder var quote byte diff --git a/sqlint/cmd/sqlint/main.go b/sqlint/cmd/sqlint/main.go index 50045ed..e9b0134 100644 --- a/sqlint/cmd/sqlint/main.go +++ b/sqlint/cmd/sqlint/main.go @@ -18,7 +18,6 @@ func main() { var lines []string cfg, err := sqlint.Load(fsys) if err != nil { - // Each line of a configuration error begins with the file's name. lines = append(lines, strings.Split(err.Error(), "\n")...) } if cfg != nil { diff --git a/sqlint/config.go b/sqlint/config.go index b68f890..c37a95f 100644 --- a/sqlint/config.go +++ b/sqlint/config.go @@ -56,15 +56,12 @@ type Role struct { Overrides map[string]map[string]bool } -// The checks each role knows, by switch name. var roleChecks = map[string][]string{ "statements": {"verb_named", "delimiter", "native_forms", "guard"}, "patterns": {"delimiter", "native_forms"}, "migrations": {"single_statement"}, } -// defaults are the conventions as they stand: every directory of each -// role's name, every check on. func defaults() *Config { c := &Config{Sources: map[string]Source{}, Roles: map[string]*Role{}} for name, checks := range roleChecks { @@ -77,8 +74,6 @@ func defaults() *Config { return c } -// raw is the file as TOML sees it; the role tables decode in two passes -// because they mix scalar switches with glob-keyed override tables. type raw struct { Engine string `toml:"engine"` Sources map[string]toml.Primitive `toml:"sources"` @@ -137,16 +132,12 @@ func parseConfig(text string) (*Config, error) { errs = append(errs, err) } } - // Every primitive is decoded by now, so what remains undecoded is a key - // the configuration does not know. for _, k := range md.Undecoded() { fail("unknown key %s", k) } return c, errors.Join(errs...) } -// parseRole fills role from its table: dirs, the known switches, and one -// override table per dirs entry, containing switches only. func parseRole(md toml.MetaData, name string, table map[string]toml.Primitive, role *Role) error { var errs []error fail := func(format string, args ...any) { errs = append(errs, fmt.Errorf(File+": "+name+": "+format, args...)) } @@ -205,9 +196,6 @@ func parseRole(md toml.MetaData, name string, table map[string]toml.Primitive, r return errors.Join(errs...) } -// switches resolves the checks in force for dir: the first dirs entry -// that matches names the set, and its override refines the role's -// switches. A directory no entry matches is not the role's. func (r *Role) switches(dir string) (map[string]bool, bool) { for _, glob := range r.Dirs { if !match(glob, dir) { @@ -221,18 +209,11 @@ func (r *Role) switches(dir string) (map[string]bool, bool) { return nil, false } -// isModulePath reports whether a source or engine value is a Go module -// path (its first segment contains a dot, as a module path's host does) -// rather than a directory relative to the configuration. func isModulePath(p string) bool { first, _, _ := strings.Cut(p, "/") return strings.Contains(first, ".") } -// isProducer reports whether base in fsys declares itself: a module -// always does, and a directory does when it contains File. A directory -// without one is the pattern files themselves, the module's own, -// declared entirely in the root configuration. func isProducer(fsys fs.FS, base string) bool { if base == "." { return true @@ -241,8 +222,6 @@ func isProducer(fsys fs.FS, base string) bool { return err == nil } -// readExport reads a producer's File under base in fsys and returns its -// export; a producer without one declares nothing. func readExport(fsys fs.FS, base string) (Export, error) { text, err := fs.ReadFile(fsys, path.Join(base, File)) if errors.Is(err, fs.ErrNotExist) { diff --git a/sqlint/dialect.go b/sqlint/dialect.go index fde211b..61dd070 100644 --- a/sqlint/dialect.go +++ b/sqlint/dialect.go @@ -2,9 +2,6 @@ package sqlint import "strconv" -// stubDialect is the dialect statement directories compile against: $N -// placeholders, no error mapping. Compilation needs a dialect only for -// the placeholders, and the linter runs no SQL. type stubDialect struct{} func (stubDialect) Name() string { return "sqlint" } diff --git a/sqlint/glob.go b/sqlint/glob.go index 4c840ee..4fe5720 100644 --- a/sqlint/glob.go +++ b/sqlint/glob.go @@ -5,9 +5,6 @@ import ( "strings" ) -// match reports whether the slash-separated glob matches the directory -// path: each segment is a path.Match pattern, and "**" matches any run of -// segments, including none. func match(glob, dir string) bool { return matchSegments(strings.Split(glob, "/"), strings.Split(path.Clean(dir), "/")) } diff --git a/sqlint/lint.go b/sqlint/lint.go index dfeac16..deba6fd 100644 --- a/sqlint/lint.go +++ b/sqlint/lint.go @@ -28,7 +28,6 @@ func (f Finding) String() string { return fmt.Sprintf("%s: %s", f.Path, f.Message) } -// linter is one run over one tree. type linter struct { fsys fs.FS cfg *Config @@ -38,8 +37,6 @@ type linter struct { findings []Finding } -// form is one native form the engine declared: the name the finding -// reports and the expression that recognizes it. type form struct { name string re *regexp.Regexp @@ -85,9 +82,6 @@ func (l *linter) report(p string, line int, msg string) { l.findings = append(l.findings, Finding{Path: p, Line: line, Message: msg}) } -// locate turns a source or engine value into a filesystem and a base -// path: a module path through the resolver, anything else a directory of -// the tree. func (l *linter) locate(value string) (fs.FS, string, error) { if isModulePath(value) { fsys, err := l.resolve(value) @@ -99,16 +93,6 @@ func (l *linter) locate(value string) (fs.FS, string, error) { return l.fsys, value, nil } -// resolveSources builds the catalog the statement directories compile -// against: each namespace's source, and for the library its engine -// overlay. A producer, a module or a directory that contains its own -// configuration, names its pattern directory in its export; a bare -// directory is the pattern files themselves. The library's own namespace, -// query.Namespace, always resolves to the patterns the query package -// embeds: the path of a sources.sql entry is not read, and only its -// overlay, when declared, is resolved as for any other source. A source -// that does not resolve is a finding against the configuration; the -// catalog is built from the rest. func (l *linter) resolveSources() { var sources []query.Source names := make([]string, 0, len(l.cfg.Sources)) @@ -153,9 +137,6 @@ func (l *linter) resolveSources() { l.catalog = catalog } -// source returns the base source of namespace ns, the library's embedded -// patterns for query.Namespace and otherwise the patterns value names, and -// false after reporting a value that does not resolve. func (l *linter) source(ns, value string) (query.Source, bool) { if ns == query.Namespace { return query.Patterns(), true @@ -181,10 +162,6 @@ func (l *linter) source(ns, value string) (query.Source, bool) { return query.Publish(ns, fsys, dir), true } -// resolveEngine reads the native forms the configured engine declares and -// compiles each; an engine is always a producer, since a consumer never -// defines one. A malformed expression is a finding against the -// configuration, before any file is read. func (l *linter) resolveEngine() { if l.cfg.Engine == "" { return diff --git a/sqlint/lint_test.go b/sqlint/lint_test.go index ee29a23..b680c85 100644 --- a/sqlint/lint_test.go +++ b/sqlint/lint_test.go @@ -13,9 +13,6 @@ import ( "github.com/standards-lab/sqlate/sqlint" ) -// lint loads the configuration from fsys and lints under it, returning -// the findings rendered the way the command prints them, after the lines -// of any configuration error. func lint(fsys fs.FS, resolve sqlint.Resolver) []string { var lines []string cfg, err := sqlint.Load(fsys) @@ -28,10 +25,6 @@ func lint(fsys fs.FS, resolve sqlint.Resolver) []string { return lines } -// tree is a module the way the linter sees it: a configuration naming the -// library and the engine, the engine's export, and the files each -// convention catches. The library's namespace always resolves to the -// patterns the query package embeds, so the tree holds no copy of them. func tree(config string) fstest.MapFS { return fstest.MapFS{ "sqlint.toml": {Data: []byte(config)}, @@ -114,15 +107,12 @@ func TestLint_FindsEachConvention(t *testing.T) { reject(t, findings, "native.sql", "edit.sql", "version.sql", "delete.sql", "sqlint.toml") } -// An override refines the role's switches for one directory set; the -// other sets keep the role's. func TestLint_OverrideRefinesOneDirectorySet(t *testing.T) { findings := lint(tree(config+"\n[statements.\"admin/*/statements\"]\nnative_forms = false\nverb_named = false\n"), nil) reject(t, findings, "seed.sql") want(t, findings, `list.sql:4: "RETURNING" (returning) in a standard-tier file`, "insert_thing.sql: named for its SQL verb") } -// A switch off at the role turns the check off everywhere. func TestLint_RoleSwitchesOff(t *testing.T) { cfg := strings.NewReplacer("[statements]\n", "[statements]\nnative_forms = false\nguard = false\n", "[migrations]\n", "[migrations]\nsingle_statement = false\n").Replace(config) findings := lint(tree(cfg), nil) @@ -130,10 +120,6 @@ func TestLint_RoleSwitchesOff(t *testing.T) { want(t, findings, "0002_b.up.sql: header") } -// Without a configuration the roles are every directory of the role's -// name, every check on, and no source: an include is a load error and -// the native-forms list is empty. The guard check reads the include's -// name from the body, so it holds without a catalog. func TestLint_Defaults(t *testing.T) { fsys := tree(config) delete(fsys, "sqlint.toml") @@ -148,8 +134,6 @@ func TestLint_Defaults(t *testing.T) { reject(t, findings, "in a standard-tier file", "sqlint.toml") } -// Errors in the file's own syntax are Load's, each line beginning with -// the file's name, beside the configuration that parsed. func TestLoad_ReportsConfigurationErrors(t *testing.T) { cases := map[string]string{ `statements: override "nope/*" names no entry of dirs`: config + "\n[statements.\"nope/*\"]\nnative_forms = false\n", @@ -172,8 +156,6 @@ func TestLoad_ReportsConfigurationErrors(t *testing.T) { } } -// A source or engine that does not resolve is a finding against the -// configuration file, and the rest of the tree is linted with what did. func TestLint_ReportsResolutionFailures(t *testing.T) { cases := map[string]string{ "sources.app: open missing": source(`app = "missing"`), @@ -201,8 +183,6 @@ func TestLint_ReportsResolutionFailures(t *testing.T) { } } -// A nil configuration is the defaults, and a finding renders as the -// command prints it. func TestLint_NilConfigIsDefaultsAndFindingString(t *testing.T) { fsys := tree(config) delete(fsys, "sqlint.toml") @@ -220,9 +200,6 @@ func TestLint_NilConfigIsDefaultsAndFindingString(t *testing.T) { } } -// A role's dirs entry matches a directory segment by segment, each segment -// a path.Match pattern, with "**" standing for any run of segments, -// including none. func TestLint_RoleGlobsMatchBySegment(t *testing.T) { cases := []struct { glob, dir string @@ -249,8 +226,6 @@ func TestLint_RoleGlobsMatchBySegment(t *testing.T) { } } -// A source whose first segment holds a dot is a module path, resolved -// through the resolver; anything else is a directory of the tree. func TestLint_ModulePathsAreTheDottedOnes(t *testing.T) { for value, module := range map[string]bool{ "github.com/x/y": true, @@ -268,9 +243,6 @@ func TestLint_ModulePathsAreTheDottedOnes(t *testing.T) { } } -// A module path resolves through the resolver to the module's root -// filesystem, and its export is read there; an overlay resolves the same -// way and respells the library's pattern. func TestLint_ResolvesPackagePaths(t *testing.T) { packages := map[string]fstest.MapFS{ "github.com/standards-lab/sqlate": { @@ -310,9 +282,6 @@ dirs = ["domain/*/statements"] want(t, lint(fsys, nil), "sqlint.toml: sources.lib: no module resolution for github.com/standards-lab/sqlate") } -// A bare directory under [sources] is the pattern files themselves, the -// service's own namespace declared entirely in the root file, while a -// directory that contains sqlint.toml is a producer whose export is read. func TestLint_BareDirectoryIsThePatternsThemselves(t *testing.T) { fsys := tree(source(`app = "admin/x/patterns"`)) fsys["admin/x/patterns/identity.sql"] = &fstest.MapFile{Data: []byte("--| tier: native\n--| native: postgres — RETURNING\nRETURNING id, version")} @@ -322,11 +291,6 @@ func TestLint_BareDirectoryIsThePatternsThemselves(t *testing.T) { want(t, findings, `orphan.sql: include of unknown namespace "org" (registered: app, sql)`) } -// The header forms a statement or pattern may use lint clean through the -// compile: a port folded across lines, a composite key, a not-null field, -// and a pattern's alternate slot set with an overlay that declares it. The -// library's namespace takes an overlay the same way, onto the embedded -// patterns, whatever path its entry names. func TestLint_HeaderFormsLintClean(t *testing.T) { overlay, err := os.ReadFile("../postgres/overlay/keyset.sql") if err != nil { @@ -353,10 +317,6 @@ func source(line string) string { return strings.Replace(config, "[sources]\n", "[sources]\n"+line+"\n", 1) } -// Every native form the PostgreSQL engine declares trips exactly once on -// the line written for it, and none trips on identifiers, literals, -// comments, or a native-tier file. The engine's real declaration is the -// input, so an entry added there is exercised here. func TestNativeForms_TrippedOnceAndSilentOtherwise(t *testing.T) { engine, err := os.ReadFile("../postgres/sqlint.toml") if err != nil { @@ -415,9 +375,6 @@ func TestNativeForms_TrippedOnceAndSilentOtherwise(t *testing.T) { } } -// A returning pair lints clean; each shape the query package refuses is a -// compile finding against its directory; and RETURNING written into a -// standard file is still a native form, the declaration notwithstanding. func TestLint_ReturningCommands(t *testing.T) { read := "--| tier: standard\nSELECT i.id, i.status FROM item i WHERE i.id = {{id}}" fsys := tree(config) @@ -445,8 +402,6 @@ func TestLint_ReturningCommands(t *testing.T) { ) } -// A field declaration whose not null suffix is misspelled is a compile -// finding against its directory: the type would otherwise absorb the typo. func TestLint_MisspelledNotNull(t *testing.T) { fsys := tree(config) fsys["domain/f/statements/sized.sql"] = &fstest.MapFile{Data: []byte("--| tier: standard\n--| key: id\n--| field: id uuid not null\n--| field: size bigint nott null\nSELECT id, size FROM t")} diff --git a/sqlint/migrations.go b/sqlint/migrations.go index 91b12c3..c4df6bf 100644 --- a/sqlint/migrations.go +++ b/sqlint/migrations.go @@ -8,8 +8,6 @@ import ( "github.com/standards-lab/sqlate/header" ) -// lintMigrations checks each migration's header and, for a -// non-transactional file, that it contains exactly one statement. func (l *linter) lintMigrations(dir string, on map[string]bool) { entries, _ := fs.ReadDir(l.fsys, dir) for _, e := range entries { diff --git a/sqlint/patterns.go b/sqlint/patterns.go index 4ba94b9..f81aee0 100644 --- a/sqlint/patterns.go +++ b/sqlint/patterns.go @@ -2,9 +2,6 @@ package sqlint import "github.com/standards-lab/sqlate/query" -// lintPatterns validates a pattern directory as a catalog source (tier -// declared, a port named for a native pattern, slots only), then applies -// the body rules. func (l *linter) lintPatterns(dir string, on map[string]bool) { if _, err := query.NewCatalog(query.Publish("lint", l.fsys, dir)); err != nil { l.report(dir, 0, err.Error()) diff --git a/sqlint/statements.go b/sqlint/statements.go index 3ba5701..8a4b396 100644 --- a/sqlint/statements.go +++ b/sqlint/statements.go @@ -9,13 +9,8 @@ import ( "github.com/standards-lab/sqlate/header" ) -// verbNamed catches a file named for its SQL verb rather than its -// operation; delete is both a verb and a command and is allowed. var verbNamed = regexp.MustCompile(`^(insert|select|update|upsert|merge)(_|\.)`) -// lintStatements compiles a statement directory the way a program does, -// against the resolved catalog, then applies the rules the compiler -// leaves to review. func (l *linter) lintStatements(dir string, on map[string]bool) { if l.catalog != nil { if _, err := l.catalog.Compile(l.fsys, dir, stubDialect{}); err != nil { @@ -25,8 +20,6 @@ func (l *linter) lintStatements(dir string, on map[string]bool) { l.lintFiles(dir, on) } -// lintFiles applies the per-file rules of a statement or pattern -// directory under its switches. func (l *linter) lintFiles(dir string, on map[string]bool) { entries, _ := fs.ReadDir(l.fsys, dir) for _, e := range entries { @@ -40,7 +33,7 @@ func (l *linter) lintFiles(dir string, on map[string]bool) { text, _ := fs.ReadFile(l.fsys, p) h, err := header.Parse(string(text)) if err != nil { - continue // reported by the compile or the catalog + continue } tier, _ := h.Get("tier") l.lintBody(p, string(text), h.End(), on["delimiter"], on["native_forms"] && tier == "standard", on["guard"]) From cab431c44f1a765754fb0541a7c49bb048706b58 Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Fri, 20 Nov 2026 23:06:34 -0500 Subject: [PATCH 07/10] harness.adoption: sqlate config comments, nolintlint, currency functions, STANDARDS comment rule golangci-lint enables nolintlint with require-explanation and require-specific for every module, from the one root .golangci.yml each module's run reads, with go-core's header and references. Comments go from mise.toml, .gitignore, .claude/marathon.toml and compose.yml; the check and upgrade descriptions take what their in-script comments said. compose.yml, the Dockerfile and both sqlint.toml files point at README.md or docs/features.md with a reference line; README.md says the stack's port sits beside a service's own on 5432. scripts/currency.sh keeps its header and its sections become named functions. STANDARDS.md cites comments.md for Go source, tests, scripts and every configuration file, and a SQL file's header is its package documentation and its template metadata. --- .claude/marathon.toml | 4 - .gitignore | 10 --- .golangci.yml | 16 ++-- README.md | 9 ++- STANDARDS.md | 1 + compose.yml | 5 +- compose/postgres.yml | 1 - compose/postgres/Dockerfile | 9 +-- mise.toml | 19 +---- postgres/sqlint.toml | 8 +- scripts/currency.sh | 142 +++++++++++++++++++----------------- sqlint.toml | 6 +- 12 files changed, 98 insertions(+), 132 deletions(-) diff --git a/.claude/marathon.toml b/.claude/marathon.toml index 08655d8..f776fa4 100644 --- a/.claude/marathon.toml +++ b/.claude/marathon.toml @@ -1,12 +1,8 @@ -# Project kind: this repository holds production Go source, checked by `mise run check`. [project] kind = "code" check = "mise run check" -# The read-only, development-time command that reports every pin trailing its latest release; -# it reads the network, so CI never runs it. currency = "mise run currency" -# Remote platform, the commands that publish and merge a finished branch, and the CI wait. [remote] platform = "github" publish = "gh pr create" diff --git a/.gitignore b/.gitignore index db44c15..44f8960 100644 --- a/.gitignore +++ b/.gitignore @@ -1,18 +1,8 @@ -# go.work and go.work.sum are committed; this repo is multi-module by design. - -# Marathon session plan files. .claude/plans/ - -# marathon's task and session briefs. .claude/briefs/ - -# Per-machine mise overrides. mise.local.toml - -# Build output. bin/ -# Editor and OS. *.swp *.swo *~ diff --git a/.golangci.yml b/.golangci.yml index e448b90..083999d 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,15 +1,17 @@ -# golangci-lint v2 configuration, run per module by `mise run check`. +# golangci-lint v2 configuration, run per module by `mise run check`: the standard set plus +# testpackage and nolintlint. +# See architecture/standards/go-elemental/principles/tests-and-docs.md +# See architecture/principles/comments.md version: "2" linters: - # The standard set (errcheck, govet, ineffassign, staticcheck, unused), - # plus testpackage, which keeps tests black-box. Its skip regexp is - # narrowed to export_test.go, the one white-box file allowed: it exports a - # clock or probe hook the API cannot reach deterministically, and the - # tests that use it stay in the external test package. default: standard enable: + - nolintlint - testpackage settings: + nolintlint: + require-explanation: true + require-specific: true testpackage: - skip-regexp: 'export_test\.go' + skip-regexp: export_test\.go diff --git a/README.md b/README.md index c4e51ff..f893a4a 100644 --- a/README.md +++ b/README.md @@ -132,10 +132,11 @@ mise run integration # run the integration tier against the running PostgreSQL mise run acceptance # run db:up and integration, then db:reset whatever the result ``` -`compose.yml` runs PostgreSQL on port 5433; `POSTGRES_PORT` moves it. The service builds from -`compose/postgres/Dockerfile`, whose `FROM` line is its one image pin and which carries its -configuration and health check; `mise run currency` reports a pin behind its latest. `mise.toml` -sets `SQLATE_DSN`, whose port follows the same variable. The integration tier is not part of CI. +`compose.yml` runs PostgreSQL on port 5433, beside a service's own on 5432; `POSTGRES_PORT` +moves it. The service builds from `compose/postgres/Dockerfile`, whose `FROM` line is its one +image pin and which carries its configuration and health check; `mise run currency` reports a +pin behind its latest. `mise.toml` sets `SQLATE_DSN`, whose port follows the same variable. The +integration tier is not part of CI. ## License diff --git a/STANDARDS.md b/STANDARDS.md index b124f20..61156c4 100644 --- a/STANDARDS.md +++ b/STANDARDS.md @@ -14,4 +14,5 @@ The judgement calls the standards-reviewer applies to sqlate, beyond what `mise - `architecture/principles/service-tiers.md`: the `Dialect` boundary between the base module and each engine sub-module. - `architecture/principles/tool-beside-library.md`: the `sqlint` package and its command. - `architecture/principles/validation-first.md`: authored SQL, `sqlint.Load` and `migrate.New`. +- `architecture/principles/comments.md` governs Go source, tests, scripts, and every configuration file (TOML, YAML, `.gitignore`, Dockerfile, compose), not just exported API; a SQL file's header is its package documentation and its template metadata. - `architecture/principles/context-architecture.md`: the guide and each `doc.go` are the homes. diff --git a/compose.yml b/compose.yml index 57b8a91..f514617 100644 --- a/compose.yml +++ b/compose.yml @@ -1,7 +1,4 @@ -# sqlate's development stack: the PostgreSQL the integration tier runs -# against. Each service builds from compose//Dockerfile, which pins -# its image and carries its configuration and health check. The named volume -# keeps the data across `mise run db:down`; `mise run db:reset` drops it. +# See README.md name: sqlate include: diff --git a/compose/postgres.yml b/compose/postgres.yml index 1f150fe..13b8802 100644 --- a/compose/postgres.yml +++ b/compose/postgres.yml @@ -3,7 +3,6 @@ services: build: context: postgres ports: - # 5433 by default so the stack coexists with a service's own on 5432. - "127.0.0.1:${POSTGRES_PORT:-5433}:5432" volumes: - sqlate-postgres:/var/lib/postgresql diff --git a/compose/postgres/Dockerfile b/compose/postgres/Dockerfile index 2285d9b..9a44ace 100644 --- a/compose/postgres/Dockerfile +++ b/compose/postgres/Dockerfile @@ -1,16 +1,9 @@ -# The development stack's PostgreSQL: the database the integration tier -# connects to through SQLATE_DSN. This FROM line is PostgreSQL's one pin. +# See docs/features.md FROM postgres:19.0-alpine -# The user, password, and database SQLATE_DSN names; development values, not -# secrets. ENV POSTGRES_USER=app \ POSTGRES_PASSWORD=app \ POSTGRES_DB=app -# Healthy once the server accepts TCP connections to the app database. The -# probe goes over TCP, not the socket, because the first start's -# initialization runs a temporary server on the socket alone, which would -# report ready before the real server starts. HEALTHCHECK --start-period=30s --start-interval=1s --interval=5s --timeout=3s --retries=5 \ CMD ["pg_isready", "-h", "127.0.0.1", "-U", "app", "-d", "app"] diff --git a/mise.toml b/mise.toml index f79efc0..5ef0930 100644 --- a/mise.toml +++ b/mise.toml @@ -4,17 +4,12 @@ golangci-lint = "2.15.0" jq = "1.8.2" "aqua:google/go-containerregistry" = "0.22.1" -# Space-separated list of module directories, kept in sync with the go.work -# use-list. "." is the base module; postgres and sqlint are the sub-modules. [env] GO_MODULES = ". postgres sqlint" -# The compose stack's PostgreSQL, whose port follows POSTGRES_PORT as -# compose.yml's does. SQLATE_DSN = "postgres://app:app@127.0.0.1:{{ get_env(name='POSTGRES_PORT', default='5433') }}/app?sslmode=disable" -# The one check: read-only and deterministic, stopping at the first failure. [tasks.check] -description = "Build, vet, format, fix, tidy, test, and lint every module, then sqlint the repository; writes nothing" +description = "Build, vet, format, fix, tidy, test, and lint every module, then sqlint the repository under the committed go.work, through which it resolves the modules sqlint.toml names; writes nothing" run = ''' set -eu export GOWORK=off @@ -30,25 +25,20 @@ for mod in $GO_MODULES; do go test -race ./... golangci-lint run ./... done -# sqlint resolves the modules sqlint.toml names with go list -m, which the -# base module reaches only through the committed go.work, so it runs with -# the workspace on. echo "check: sqlint" cd "$MISE_PROJECT_ROOT" env -u GOWORK go run github.com/standards-lab/sqlate/sqlint/cmd/sqlint . ''' -# Currency: report what trails its latest, and the convenience that upgrades it. [tasks.currency] description = "Report every requirement, Go version, tool, action pin, and image tag behind its latest; writes nothing" run = "scripts/currency.sh" [tasks.upgrade] -description = "Upgrade every module's go directive and direct requirements and the local mise tools to their latest, rewriting go.mod and mise.toml" +description = "Upgrade every module's go directive (to the current Go minor, with no toolchain line) and direct requirements and the local mise tools to their latest, rewriting go.mod and mise.toml" run = ''' set -eu export GOWORK=off -# The go directive follows the current Go minor, with no toolchain line. go_minor=$(mise latest go | cut -d. -f1,2) for mod in $GO_MODULES; do cd "$MISE_PROJECT_ROOT/$mod" @@ -61,7 +51,6 @@ cd "$MISE_PROJECT_ROOT" mise upgrade --bump --local ''' -# Maintenance. [tasks.tidy] description = "Run go mod tidy across all modules" run = ''' @@ -72,7 +61,6 @@ for mod in $GO_MODULES; do done ''' -# Verification. [tasks.fmt] description = "Format all Go source" run = "gofmt -w ." @@ -109,7 +97,6 @@ for mod in $GO_MODULES; do done ''' -# Testing. [tasks.test] description = "Run the unit tier across all modules" run = ''' @@ -133,8 +120,6 @@ mise run db:up mise run integration ''' -# The development stack: compose.yml's PostgreSQL, whose data lives in a named -# volume that db:down keeps and db:reset drops. [tasks."db:up"] description = "Build and start the compose PostgreSQL and wait until it is healthy" run = "docker compose up -d --wait --build" diff --git a/postgres/sqlint.toml b/postgres/sqlint.toml index 153c538..e87138e 100644 --- a/postgres/sqlint.toml +++ b/postgres/sqlint.toml @@ -1,10 +1,4 @@ -# The engine's sqlint.toml. A consumer that configures this engine reads -# [export]: the native forms a standard-tier file must not use, each a -# regular expression (RE2) under the name a finding reports, so the engine -# states in what position a spelling counts (word boundaries, case) and -# not just which spelling. The lint matches code only: string literals and -# comments are stripped first. The overlay directory respells one library -# pattern, the keyset predicate, as a row-value comparison. +# See docs/features.md [export] overlay = "overlay" diff --git a/scripts/currency.sh b/scripts/currency.sh index 6aa91e9..36c3118 100755 --- a/scripts/currency.sh +++ b/scripts/currency.sh @@ -2,10 +2,6 @@ # currency reports every dependency, toolchain, and pin that trails its latest # release, one line each, and exits non-zero when it reports any. It reads the # network and writes nothing. Run it through `mise run currency`. -# -# Each scan captures its command's output in a variable before reading it, so -# under set -e a scan command that fails (a go list missing a go.sum entry) -# fails currency instead of reporting nothing. set -euo pipefail cd "$MISE_PROJECT_ROOT" export GOWORK=off @@ -16,9 +12,7 @@ report() { stale=1 } -# matches prints each match of a grep pattern in the given files that exist. -# A missing file or no match is no output; any other grep error fails. -matches() { +matches_in_existing_files() { local pattern=$1 file local files=() shift @@ -29,79 +23,97 @@ matches() { grep -ho "$pattern" "${files[@]}" || [ $? -eq 1 ] } -go_minor=$(mise latest go | cut -d. -f1,2) - -for mod in $GO_MODULES; do - # Direct requirements with a newer version within their major. +report_outdated_requirements() { + local mod=$1 updates line updates=$(cd "$mod" && go list -m -u -f \ '{{if and (not .Main) (not .Indirect) .Update}}{{.Path}} {{.Version}} -> {{.Update.Version}}{{end}}' all) while read -r line; do - [ -n "$line" ] && report "$mod/go.mod: $line" + if [ -n "$line" ]; then + report "$mod/go.mod: $line" + fi done <<<"$updates" +} - # The go directive's minor against the current Go minor. +report_outdated_go_directive() { + local mod=$1 go_minor=$2 directive directive=$(cd "$mod" && go mod edit -json | jq -r .Go | cut -d. -f1,2) [ "$directive" = "$go_minor" ] || report "$mod/go.mod: go $directive -> go $go_minor" -done +} -# mise tools pinned below their latest version. -outdated=$(mise outdated --bump --local --json | - jq -r 'to_entries[] | "\(.key) \(.value.requested) -> \(.value.bump)"') -while read -r line; do - [ -n "$line" ] && report "mise.toml: $line" -done <<<"$outdated" +report_outdated_mise_tools() { + local outdated line + outdated=$(mise outdated --bump --local --json | + jq -r 'to_entries[] | "\(.key) \(.value.requested) -> \(.value.bump)"') + while read -r line; do + if [ -n "$line" ]; then + report "mise.toml: $line" + fi + done <<<"$outdated" +} -# The workflows of the project root and of the git top-level, de-duplicated. -# They are one directory when the project is the repository, and two when the -# repository nests the project in a subdirectory, as the template repository -# does. A project not yet in git has only its own. -root=$(pwd -P) -top=$(git rev-parse --show-toplevel 2>/dev/null || echo "$root") -workflows=("$root"/.github/workflows/*.yml) -[ "$top" = "$root" ] || workflows+=("$top"/.github/workflows/*.yml) +project_and_toplevel_workflows() { + local root top + root=$(pwd -P) + top=$(git rev-parse --show-toplevel 2>/dev/null || echo "$root") + printf '%s\n' "$root"/.github/workflows/*.yml + if [ "$top" != "$root" ]; then + printf '%s\n' "$top"/.github/workflows/*.yml + fi +} -# GitHub Actions pinned below the action's latest release. -actions=$(matches 'uses: *[^ ]*@[^ ]*' "${workflows[@]}" | sed 's/uses: *//' | sort -u) -for uses in $actions; do - action=${uses%@*} - pin=${uses#*@} - repo=$(echo "$action" | cut -d/ -f1,2) - latest=$(gh api "repos/$repo/releases/latest" --jq .tag_name) - [ "$pin" = "$latest" ] || report ".github/workflows: $action $pin -> $latest" -done +report_outdated_actions() { + local workflows actions uses action pin repo latest + mapfile -t workflows < <(project_and_toplevel_workflows) + actions=$(matches_in_existing_files 'uses: *[^ ]*@[^ ]*' "${workflows[@]}" | sed 's/uses: *//' | sort -u) + for uses in $actions; do + action=${uses%@*} + pin=${uses#*@} + repo=$(echo "$action" | cut -d/ -f1,2) + latest=$(gh api "repos/$repo/releases/latest" --jq .tag_name) + [ "$pin" = "$latest" ] || report ".github/workflows: $action $pin -> $latest" + done +} -# latest_tag prints the highest semver tag of an image that carries the given -# pin's variant suffix (18.6-alpine -> -alpine). A tag needs at least one dot -# to count: some images also publish bare build numbers (Grafana's 98813352) -# that would otherwise sort above every release. -latest_tag() { - local image=$1 pin=$2 suffix pattern latest +latest_dotted_release_tag() { + local image=$1 pin=$2 suffix dotted_release_pattern latest suffix=${pin#"${pin%%[!0-9.]*}"} - pattern="^[0-9]+(\.[0-9]+)+${suffix//./\\.}\$" - latest=$(crane ls "$image" | grep -E "$pattern" | sed "s/${suffix}\$//" | sort -V | tail -n1) || return + dotted_release_pattern="^[0-9]+(\.[0-9]+)+${suffix//./\\.}\$" + latest=$(crane ls "$image" | grep -E "$dotted_release_pattern" | sed "s/${suffix}\$//" | sort -V | tail -n1) || return echo "$latest$suffix" } -# Compose and CI images pinned on an image: line below their latest. A -# compose service that builds from compose//Dockerfile has no image: -# line; its pin is the Dockerfile's FROM line, scanned below. -images=$(matches '^ *image: *[^ ]*' compose.yml compose/*.yml "${workflows[@]}" | - sed 's/^ *image: *//' | tr -d "\"'" | sort -u) -for ref in $images; do - image=${ref%:*} - pin=${ref##*:} - latest=$(latest_tag "$image" "$pin") - [ "$pin" = "$latest" ] || report "images: $image $pin -> $latest" -done +report_outdated_image_lines() { + local workflows images ref image pin latest + mapfile -t workflows < <(project_and_toplevel_workflows) + images=$(matches_in_existing_files '^ *image: *[^ ]*' compose.yml compose/*.yml "${workflows[@]}" | + sed 's/^ *image: *//' | tr -d "\"'" | sort -u) + for ref in $images; do + image=${ref%:*} + pin=${ref##*:} + latest=$(latest_dotted_release_tag "$image" "$pin") + [ "$pin" = "$latest" ] || report "images: $image $pin -> $latest" + done +} -# Compose services' Dockerfiles pinned on their FROM line below the latest. -for dockerfile in compose/*/Dockerfile; do - [ -e "$dockerfile" ] || continue - ref=$(sed -n 's/^FROM *\([^ ]*\).*/\1/p' "$dockerfile" | head -n1) - image=${ref%:*} - pin=${ref##*:} - latest=$(latest_tag "$image" "$pin") - [ "$pin" = "$latest" ] || report "$dockerfile: $image $pin -> $latest" -done +report_outdated_dockerfile_bases() { + local dockerfile ref image pin latest + for dockerfile in compose/*/Dockerfile; do + [ -e "$dockerfile" ] || continue + ref=$(sed -n 's/^FROM *\([^ ]*\).*/\1/p' "$dockerfile" | head -n1) + image=${ref%:*} + pin=${ref##*:} + latest=$(latest_dotted_release_tag "$image" "$pin") + [ "$pin" = "$latest" ] || report "$dockerfile: $image $pin -> $latest" + done +} +go_minor=$(mise latest go | cut -d. -f1,2) +for mod in $GO_MODULES; do + report_outdated_requirements "$mod" + report_outdated_go_directive "$mod" "$go_minor" +done +report_outdated_mise_tools +report_outdated_actions +report_outdated_image_lines +report_outdated_dockerfile_bases exit "$stale" diff --git a/sqlint.toml b/sqlint.toml index 619d225..7dad523 100644 --- a/sqlint.toml +++ b/sqlint.toml @@ -1,8 +1,4 @@ -# sqlint: the module's SQL conventions, one file per module at its root. -# [export] is what a consumer reads when it names this module as a source: -# the directory its patterns publish under the consumer's chosen namespace. -# The roles below lint the module's own files against the PostgreSQL -# sub-module's native forms. +# See docs/features.md engine = "postgres" From 6d862e68c43b4b3d5bf08aa389f155019801832f Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Fri, 20 Nov 2026 23:07:21 -0500 Subject: [PATCH 08/10] harness.adoption: pin marathon tools; check runs lint-context and lint-references mise.toml pins github:standards-lab/claude-plugins at 0.22.0 (marathon/v prefix) and sets task.run_auto_install = false, as go-core. The check runs both lints after the module loop and sqlint through a run_lint function that fails on a lint missing from PATH with a message naming mise install, and exits nonzero when either lint fails. The description and README check line name every step, sqlint included. --- README.md | 2 +- mise.toml | 18 +++++++++++++++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f893a4a..0085d44 100644 --- a/README.md +++ b/README.md @@ -122,7 +122,7 @@ The repository is a Go workspace of three modules. Tasks run through [mise](https://mise.jdx.dev): ```sh -mise run check # build, vet, format, fix, tidy, unit tier, lint, sqlint; writes nothing +mise run check # build, vet, format, fix, tidy, unit tier, lint, sqlint, lint-context, lint-references; writes nothing mise run currency # report requirements, Go, tools, actions, and images behind their latest mise run upgrade # upgrade every module's go directive and requirements, and the tools, to their latest mise run db:up # build and start the compose PostgreSQL and wait until it is healthy diff --git a/mise.toml b/mise.toml index 5ef0930..5b1c067 100644 --- a/mise.toml +++ b/mise.toml @@ -1,4 +1,8 @@ +[settings] +task.run_auto_install = false + [tools] +"github:standards-lab/claude-plugins" = { version = "0.22.0", version_prefix = "marathon/v" } go = "1.27.4" golangci-lint = "2.15.0" jq = "1.8.2" @@ -9,10 +13,19 @@ GO_MODULES = ". postgres sqlint" SQLATE_DSN = "postgres://app:app@127.0.0.1:{{ get_env(name='POSTGRES_PORT', default='5433') }}/app?sslmode=disable" [tasks.check] -description = "Build, vet, format, fix, tidy, test, and lint every module, then sqlint the repository under the committed go.work, through which it resolves the modules sqlint.toml names; writes nothing" +description = "Build, vet, format, fix, tidy, test, and lint every module, then sqlint the repository under the committed go.work, through which it resolves the modules sqlint.toml names, then run lint-context and lint-references; writes nothing" run = ''' set -eu export GOWORK=off +fail=0 +run_lint() { + if ! command -v "$1" >/dev/null; then + echo "FAIL: $1 is not on PATH; run mise install" >&2 + fail=1 + return + fi + "$1" || fail=1 +} for mod in $GO_MODULES; do echo "check: $mod" cd "$MISE_PROJECT_ROOT/$mod" @@ -28,6 +41,9 @@ done echo "check: sqlint" cd "$MISE_PROJECT_ROOT" env -u GOWORK go run github.com/standards-lab/sqlate/sqlint/cmd/sqlint . +run_lint lint-context +run_lint lint-references +exit "$fail" ''' [tasks.currency] From 9c33f395a3bf6fe759f0e4e42d14ddc50a6cc6ff Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Fri, 20 Nov 2026 23:10:35 -0500 Subject: [PATCH 09/10] harness.adoption: standards review --- docs/features.md | 6 +++--- mise.toml | 21 ++++++++++----------- query/cursor_test.go | 17 +++++++++++++++++ query/guard.go | 6 ++++-- query/guard_test.go | 8 ++++++++ scripts/currency.sh | 37 ++++++++++++++++++------------------- 6 files changed, 60 insertions(+), 35 deletions(-) diff --git a/docs/features.md b/docs/features.md index 898ea41..caa5e0d 100644 --- a/docs/features.md +++ b/docs/features.md @@ -193,7 +193,7 @@ error passes through the session's mapper. | `Exec(ctx, session, args)` | none | Returns the rows affected. | | `Scan(scan)` | `Rows[T]` | `One` returns the first row (`sql.ErrNoRows` when none); `All` returns every row; `Each` yields rows one at a time as an `iter.Seq2[T, error]`, closing the row set when the loop ends. | | `Project(scan)` | `Projection[T]` | `List(ctx, session, directives, page, base...)` reads one page by offset and returns a `Collection[T]`; `Continue(ctx, session, directives, after, size, base...)` reads the `size` rows past a previous page's cursor and returns the same; `One(ctx, session, field, value, base...)` is the base under one equality predicate; `Verify` probes the field contract. A base without a key or field contract, or one with an expanded parameter (`{{name...}}`), panics at binding; a base's other parameters bind from the `base` arguments. | -| `Guarded(check, version)` | `Guard` | `Run(ctx, session, version, args)` binds the expected version under the named parameter, runs the command, and returns the new version; when the command changed nothing it runs the check: no row is `sql.ErrNoRows`, a row is `ErrVersionMismatch` wrapping the expected and current versions. | +| `Guarded(check, version)` | `Guard` | `Run(ctx, session, version, args)` binds the expected version under the named parameter, runs the command, and returns the new version; when the command changed nothing it runs the check: no row is `sql.ErrNoRows`, a row at another version is `ErrVersionMismatch` wrapping the expected and current versions, and a row at the expected version, which a predicate of the command's own refused, is `ErrRefused`. | | `Returning(scan)` | `Returning[T]` | For a returning command. `One(ctx, session, args)` runs the command and returns the row as it stands afterward and whether the command changed it: no row at all is `sql.ErrNoRows`; a command that changed more than one row, or whose read does not find the row it changed, is `ErrNotOneRow`. `Guarded(version, current)` returns a `RowGuard[T]`. | | `Returning(scan).Guarded(version, current)` | `RowGuard[T]` | For a guarded command whose own predicate, beyond the key and the version, can refuse a row. `current` reads a row's version. `Run(ctx, session, version, args)` returns the changed row; when the command changed nothing it classifies the row its read found: no row is `sql.ErrNoRows`, a row at another version is `ErrVersionMismatch`, and a row at the expected version is a `*RefusedError[T]` carrying the row, which unwraps to `ErrRefused`. | @@ -332,8 +332,8 @@ URL-safe text a caller relays unchanged. It records the base, the keyed fields, and the values, under a hash of those and each keyed field's declared type, so a cursor from before a contract change is refused. The hash is unkeyed and guards against accident, not forgery: a cursor's values re-enter the read only as bound parameters cast to the fields' types, -so a forged cursor can at most select another page. It also records the filters, so `Continue` under other -filters than the page that issued it is refused as a `CursorMismatch`. Filters with a value +so a forged cursor can at most select another page. It also records the filters, so `Continue` +under other filters than the page that issued it is refused as a `CursorMismatch`. Filters with a value that has no JSON form, such as a float NaN, cannot be recorded, and their page reports `More` without a `Next`. diff --git a/mise.toml b/mise.toml index 5b1c067..e56ec15 100644 --- a/mise.toml +++ b/mise.toml @@ -1,3 +1,4 @@ +# See architecture/standards/go-elemental/principles/release-and-ci.md [settings] task.run_auto_install = false @@ -17,15 +18,6 @@ description = "Build, vet, format, fix, tidy, test, and lint every module, then run = ''' set -eu export GOWORK=off -fail=0 -run_lint() { - if ! command -v "$1" >/dev/null; then - echo "FAIL: $1 is not on PATH; run mise install" >&2 - fail=1 - return - fi - "$1" || fail=1 -} for mod in $GO_MODULES; do echo "check: $mod" cd "$MISE_PROJECT_ROOT/$mod" @@ -41,8 +33,15 @@ done echo "check: sqlint" cd "$MISE_PROJECT_ROOT" env -u GOWORK go run github.com/standards-lab/sqlate/sqlint/cmd/sqlint . -run_lint lint-context -run_lint lint-references +fail=0 +for lint in lint-context lint-references; do + if ! command -v "$lint" >/dev/null; then + echo "FAIL: $lint is not on PATH; run mise install" >&2 + fail=1 + elif ! "$lint"; then + fail=1 + fi +done exit "$fail" ''' diff --git a/query/cursor_test.go b/query/cursor_test.go index 0d3fbec..c2dcf64 100644 --- a/query/cursor_test.go +++ b/query/cursor_test.go @@ -2,6 +2,7 @@ package query_test import ( "context" + "database/sql" "database/sql/driver" "errors" "math" @@ -260,6 +261,22 @@ func TestList_KeyedColumnsAreMatchedInThePagesOwnCase(t *testing.T) { } } +func TestList_IssuesACursorWhenTheScanReadsIntoRawBytes(t *testing.T) { + view := catalog().MustCompile(projectionFiles, "sql", sqltest.Dialect{}).Statement("member").Project(func(rows query.Row) (member, error) { + var org, id, name sql.RawBytes + err := rows.Scan(&org, &id, &name) + return member{Org: string(org), ID: string(id), Name: string(name)}, err + }) + db, _ := session(t, sqltest.WithTotal(members("a", "b", "c"), 9)) + got, err := view.List(context.Background(), db, query.Directives{}, query.Page{Number: 1, Size: 2}) + if err != nil { + t.Fatalf("List = %+v, %v", got, err) + } + if len(got.Items) != 2 || got.Items[1].ID != "b" || got.Next == "" { + t.Errorf("page = %+v, want two items and a cursor", got) + } +} + func TestList_AKeyedFieldThePageDoesNotOutputIsTheContractsDefect(t *testing.T) { db, _ := session(t, sqltest.WithTotal(sqltest.Response{Columns: []string{"id", "name"}, Rows: [][]driver.Value{{"a", "M"}}}, 9)) _, err := memberView(t).List(context.Background(), db, query.Directives{}, query.Page{Number: 1, Size: 2}) diff --git a/query/guard.go b/query/guard.go index 5c236f4..1047291 100644 --- a/query/guard.go +++ b/query/guard.go @@ -53,8 +53,10 @@ type Guard struct { // Run executes the command with version bound under the guard's parameter // name alongside args. A row affected is success and the new version, // version+1, with no second round trip. No row affected runs the check with -// the same args: no row is sql.ErrNoRows, a row is ErrVersionMismatch -// with the expected and current versions. +// the same args: no row is sql.ErrNoRows, a row at another version is +// ErrVersionMismatch with the expected and current versions, and a row at +// the expected version, which a predicate of the command's own refused, is +// ErrRefused. func (g Guard) Run(ctx context.Context, s sqlate.Session, version int64, args Args) (int64, error) { bound := make(Args, len(args)+1) maps.Copy(bound, args) diff --git a/query/guard_test.go b/query/guard_test.go index 458d894..7a6e69f 100644 --- a/query/guard_test.go +++ b/query/guard_test.go @@ -91,6 +91,14 @@ func TestGuard_MissClassifiesNotFoundAndMismatch(t *testing.T) { } } +func TestGuard_MissAtTheExpectedVersionIsRefused(t *testing.T) { + db, _ := session(t, sqltest.Response{Affected: 0}, versionRow(3)) + _, err := guard(t).Run(context.Background(), db, 3, query.Args{"id": "x", "name": "n"}) + if !errors.Is(err, query.ErrRefused) || errors.Is(err, query.ErrVersionMismatch) { + t.Errorf("err = %v, want ErrRefused", err) + } +} + func TestGuard_CommandFailurePassesThroughMapped(t *testing.T) { db, _ := session(t, sqltest.Response{Err: errDriver}) _, err := guard(t).Run(context.Background(), db, 1, query.Args{"id": "x", "name": "n"}) diff --git a/scripts/currency.sh b/scripts/currency.sh index 36c3118..695ee9d 100755 --- a/scripts/currency.sh +++ b/scripts/currency.sh @@ -1,7 +1,13 @@ #!/usr/bin/env bash # currency reports every dependency, toolchain, and pin that trails its latest # release, one line each, and exits non-zero when it reports any. It reads the -# network and writes nothing. Run it through `mise run currency`. +# network and writes nothing. Run it through `mise run currency`. The actions it +# checks are those of the project root's workflows and, when the repository nests +# the project in a subdirectory, of the git top-level's. +# +# Each scan captures its command's output in a variable before reading it, so +# under set -e a scan command that fails (a go list missing a go.sum entry) +# fails currency instead of reporting nothing. set -euo pipefail cd "$MISE_PROJECT_ROOT" export GOWORK=off @@ -12,7 +18,7 @@ report() { stale=1 } -matches_in_existing_files() { +matches() { local pattern=$1 file local files=() shift @@ -51,20 +57,9 @@ report_outdated_mise_tools() { done <<<"$outdated" } -project_and_toplevel_workflows() { - local root top - root=$(pwd -P) - top=$(git rev-parse --show-toplevel 2>/dev/null || echo "$root") - printf '%s\n' "$root"/.github/workflows/*.yml - if [ "$top" != "$root" ]; then - printf '%s\n' "$top"/.github/workflows/*.yml - fi -} - report_outdated_actions() { - local workflows actions uses action pin repo latest - mapfile -t workflows < <(project_and_toplevel_workflows) - actions=$(matches_in_existing_files 'uses: *[^ ]*@[^ ]*' "${workflows[@]}" | sed 's/uses: *//' | sort -u) + local actions uses action pin repo latest + actions=$(matches 'uses: *[^ ]*@[^ ]*' "${workflows[@]}" | sed 's/uses: *//' | sort -u) for uses in $actions; do action=${uses%@*} pin=${uses#*@} @@ -83,9 +78,8 @@ latest_dotted_release_tag() { } report_outdated_image_lines() { - local workflows images ref image pin latest - mapfile -t workflows < <(project_and_toplevel_workflows) - images=$(matches_in_existing_files '^ *image: *[^ ]*' compose.yml compose/*.yml "${workflows[@]}" | + local images ref image pin latest + images=$(matches '^ *image: *[^ ]*' compose.yml compose/*.yml "${workflows[@]}" | sed 's/^ *image: *//' | tr -d "\"'" | sort -u) for ref in $images; do image=${ref%:*} @@ -99,7 +93,7 @@ report_outdated_dockerfile_bases() { local dockerfile ref image pin latest for dockerfile in compose/*/Dockerfile; do [ -e "$dockerfile" ] || continue - ref=$(sed -n 's/^FROM *\([^ ]*\).*/\1/p' "$dockerfile" | head -n1) + ref=$(sed -n '/^FROM /{s/^FROM *\([^ ]*\).*/\1/p;q;}' "$dockerfile") image=${ref%:*} pin=${ref##*:} latest=$(latest_dotted_release_tag "$image" "$pin") @@ -107,6 +101,11 @@ report_outdated_dockerfile_bases() { done } +root=$(pwd -P) +top=$(git rev-parse --show-toplevel 2>/dev/null || echo "$root") +workflows=("$root"/.github/workflows/*.yml) +[ "$top" = "$root" ] || workflows+=("$top"/.github/workflows/*.yml) + go_minor=$(mise latest go | cut -d. -f1,2) for mod in $GO_MODULES; do report_outdated_requirements "$mod" From 46af4d53729de8f1478637db3967f55dd3e64b98 Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Fri, 20 Nov 2026 23:15:09 -0500 Subject: [PATCH 10/10] harness.adoption: editor pass --- context/second-engine.md | 15 +++++++-------- docs/features.md | 24 ++++++++++++------------ 2 files changed, 19 insertions(+), 20 deletions(-) diff --git a/context/second-engine.md b/context/second-engine.md index 58f59cc..faeb354 100644 --- a/context/second-engine.md +++ b/context/second-engine.md @@ -1,12 +1,11 @@ # A second engine -A second engine is a second sub-module beside `postgres`, named for the engine. Its roadmap home is -the backlog goal `second-providers` in `standards-lab/roadmap/index.toml`. +A second engine is planned as a second sub-module beside `postgres`, named for the engine. The +roadmap tracks it as the backlog goal `second-providers` in `standards-lab/roadmap/index.toml`. -Open points: +The sub-module carries three parts of its own, each still open: -- The sub-module carries its own dialect: bind-parameter rendering, error classification, the - migrate lock, the version statement, and the keyset predicate, as `postgres/doc.go` lists them. -- It carries its own `sqlint.toml`. -- It carries an overlay for each library pattern the engine does not accept as written in - standard SQL. +- a dialect: bind-parameter rendering, error classification, the migrate lock, the version + statement, and the keyset predicate, as `postgres/doc.go` lists them. +- a `sqlint.toml`. +- an overlay for each library pattern the engine does not accept as written in standard SQL. diff --git a/docs/features.md b/docs/features.md index caa5e0d..d2ac889 100644 --- a/docs/features.md +++ b/docs/features.md @@ -332,9 +332,9 @@ URL-safe text a caller relays unchanged. It records the base, the keyed fields, and the values, under a hash of those and each keyed field's declared type, so a cursor from before a contract change is refused. The hash is unkeyed and guards against accident, not forgery: a cursor's values re-enter the read only as bound parameters cast to the fields' types, -so a forged cursor can at most select another page. It also records the filters, so `Continue` -under other filters than the page that issued it is refused as a `CursorMismatch`. Filters with a value -that has no JSON form, such as a float NaN, cannot be recorded, and their page reports `More` +so a forged cursor can at most select another page. A cursor also records the filters, so +`Continue` under other filters than the page that issued it is refused as a `CursorMismatch`. +Filters with a value that has no JSON form, such as a float NaN, cannot be recorded, and their page reports `More` without a `Next`. Every error a request's declarations can cause unwraps to `ErrDirectives`, so a caller's @@ -423,13 +423,13 @@ the lock: each refused `TryLock` pauses, from 25ms doubling to a 1s cap, and tri the wait ends with the context's error when the context ends, holding nothing. No statement stays open while a starter waits, so a holder's `CREATE INDEX CONCURRENTLY`, which waits for every open transaction, cannot deadlock with the waiter. A dialect with `Locker` alone waits in -its blocking `Lock`. The lock is released under a context that survives the run's cancellation; -once the context has ended, the engine releases it with the discarded connection's session, and -an unlock failure then is not reported. A dialect without `Locker` fails with `ErrNoLocker` unless -`Options.Unlocked` opts out, in which case concurrent starters are unsafe. Inside the lock, -every run that applies or reverts migrations creates and reads every set's history table first, -so a dirty set or a history that does not match its set refuses the run before any migration -runs. `Force` is the exception, since it repairs a dirty history. +its blocking `Lock`. The lock is released under a context that survives the run's +cancellation. Once the run's context has ended, an unlock failure is not reported, because the +discarded connection's session ends and releases the lock. A dialect without `Locker` fails with +`ErrNoLocker` unless `Options.Unlocked` opts out, in which case concurrent starters are unsafe. +Inside the lock, every run that applies or reverts migrations creates and reads every set's +history table first, so a dirty set or a history that does not match its set refuses the run +before any migration runs. `Force` is the exception, since it repairs a dirty history. **Transactions and dirty state.** A transactional migration runs inside a transaction and leaves nothing behind on failure. A migration headed `transaction: none` runs under autocommit @@ -653,5 +653,5 @@ under the PostgreSQL dialect, and `Database.Session()` wraps the pool under `Dia When the test ends the pool is closed and the database dropped `WITH (FORCE)`, so a session still open on it, such as a started process's pool, is ended rather than holding the drop back; the drop is retried while the server reports a session still closing. A create that fails is -followed by a drop too, since one that timed out can still finish on the server. The package imports -`testing`, so only test files import it. +followed by a drop too, since a create that timed out can still finish on the server. The +package imports `testing`, so only test files import it.