Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 0 additions & 4 deletions .claude/marathon.toml
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
10 changes: 0 additions & 10 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -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
*~
Expand Down
16 changes: 9 additions & 7 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -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
11 changes: 6 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

Expand Down
1 change: 1 addition & 0 deletions STANDARDS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
5 changes: 1 addition & 4 deletions compose.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
# sqlate's development stack: the PostgreSQL the integration tier runs
# against. Each service builds from compose/<service>/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:
Expand Down
1 change: 0 additions & 1 deletion compose/postgres.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 2 additions & 9 deletions compose/postgres/Dockerfile
Original file line number Diff line number Diff line change
@@ -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.
FROM postgres:18.7-alpine
# 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"]
31 changes: 18 additions & 13 deletions context/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)).
11 changes: 11 additions & 0 deletions context/second-engine.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# A second engine

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`.

The sub-module carries three parts of its own, each still open:

- 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.
32 changes: 21 additions & 11 deletions docs/features.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`. |

Expand Down Expand Up @@ -330,9 +330,11 @@ 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
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`
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. 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
Expand Down Expand Up @@ -421,11 +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`. 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
Expand Down Expand Up @@ -591,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
Expand Down Expand Up @@ -630,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

Expand All @@ -643,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
`testing`, so only test files import it.
the drop is retried while the server reports a session still closing. A create that fails is
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.
6 changes: 3 additions & 3 deletions docs/quick-start.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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 \
Expand Down
4 changes: 3 additions & 1 deletion errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 0 additions & 4 deletions header/header.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand Down
2 changes: 0 additions & 2 deletions migrate/export_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
3 changes: 0 additions & 3 deletions migrate/files.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Loading