diff --git a/context/goals/v1.data.extensions.md b/context/goals/v1.data.extensions.md index 4011b52..0019a68 100644 --- a/context/goals/v1.data.extensions.md +++ b/context/goals/v1.data.extensions.md @@ -7,136 +7,115 @@ ## Tasks 1. [x] extension-stage -2. [ ] sqlint-extensions +2. [x] sqlint-extensions 3. [ ] pgvector-sql 4. [ ] pgvector-go 5. [ ] principles -## Task brief · extension-stage +## Task brief · sqlint-extensions **Problem** -An application can't tell sqlate's migrator which Postgres extensions its schema needs. Today an -extension is either installed by hand or written into an ordinary migration with up and down -scripts. Those scripts pile up one per upgrade and have no honest down for a version that has no -downgrade script. The goal needs the migrator to reconcile each declared extension to the version -the image ships, ahead of every set and under the migrator's lock, so that starting replicas take -turns activating. A typed failure must come before any set runs, and `Verify` and a status report -must expose a mismatch, so go-database's admin service applies it unchanged. +sqlint keeps native forms out of standard-tier files only for the configured engine. When a module +uses a Postgres extension such as pgvector, nothing stops that extension's operators, types or +functions from appearing in a standard-tier file, so the file passes as portable when it isn't. +The goal needs an `extensions` key whose listed modules add their native forms to the engine's deny +list. A listed module must either declare its forms or give a reason why it has none; otherwise it +is refused. pgvector-sql then builds the first such module, and it needs postgres's extension +capability and `pgtest.MigratedWith` released, built against sqlate v0.8.0. **Behaviors** -1. `migrate.Options.Extensions` lists declarations in order. Each has a name and a removed flag, - and no version. `New` refuses an empty or duplicate name. It also refuses any declarations - when the dialect lacks the extension capability, and it still does no I/O. -2. The extension capability is a new migrate interface that returns statement text, as `Catalog` - does. It returns: - - a state query bound to the extension name, giving the installed version (none when not - installed), the image's default version (none when the image doesn't offer the extension), - and whether an update path runs from the installed version to the default; - - the activation statements: create the extension if it doesn't exist, then update it to its - default; - - the removal statement: drop the extension if it exists, with RESTRICT. - - The dialect quotes the name. -3. `Up` checks every set's history and then the extensions. It checks every active declaration - before activating any of them. If an extension isn't available in the image, the run fails - with a typed error naming it. The run also fails if the installed version differs from the - default and no update path leads to the default, which covers an installed version newer than - the image's. That error names the extension and both versions. Either failure comes before any - activation and before any set. -4. A declaration whose installed version already equals the default runs no statement, so a - pre-installed database passes under an unprivileged role. A missing or older extension is - activated, each declaration in its own transaction, in declared order, and each activation is - logged. -5. A positive `Steps`, on the migrator or on a layer, runs the same check and activation after its - existing refusals and before applying anything. It removes nothing. -6. After its sets, `Up` removes each removed declaration in declared order, each in its own - transaction, logging each drop. If a dependent object is left behind, RESTRICT fails the run - with the driver's error, mapped through the dialect. A removed declaration whose extension - isn't installed, or isn't available, is a no-op. -7. Deleting a declaration only stops the migrator from managing it and never drops the extension. - `Down`, `Reset`, and `Force` skip the stage, and `Reset` leaves extensions installed. -8. With `Unlocked`, the stage runs without the lock, as the sets do. -9. `Verify` checks extensions before sets, on the pool and without the lock. An active - declaration that is missing or behind the default fails with a typed error that unwraps to - `ErrPending`. So does a removed declaration that is still installed. An unavailable extension, - or one with no update path, fails with its own class, not `ErrPending`. `Layer.Verify` and - `Status` stay set-only. -10. `Migrator.Extensions(ctx)` reads each declaration's state in declared order, on the pool and - without the lock. Each entry reports the name, the removed flag, the installed version, the - image's default version, and whether the declaration is pending: missing or behind for an - active declaration, still installed for a removed one. An unavailable extension shows an empty - default version and is not an error. -11. Every typed error names the extension. `errors.Is` classifies it as `ErrExtensionUnavailable`, - `ErrNoUpdatePath`, or `ErrPending`, and `errors.As` reaches the detail. -12. `postgres.Dialect` implements the capability: - - the state query reads `pg_available_extensions` and `pg_extension_update_paths`; - - activation is `CREATE EXTENSION IF NOT EXISTS` then `ALTER EXTENSION … UPDATE`; - - removal is `DROP EXTENSION IF EXISTS … RESTRICT`. - - It references no new migrate symbol outside integration-tagged code, so the postgres module - still builds against sqlate v0.7.0 when the workspace file is off. -13. `pgtest.MigratedWith(t, env, prefix, opts, sets...)` is `Migrated` with the caller's - `migrate.Options`. `Migrated` becomes `MigratedWith` with empty options. -14. The live proofs use the integration image's contrib extensions: - - hstore pre-installed at 1.4 makes `Verify` unwrap to `ErrPending` and `Extensions` report - it pending; after `Up` it is at 1.8 and `Verify` passes; - - a name the image lacks fails `Up` before any set and leaves no history row; - - a removed hstore with a dependent column fails `Up`, and once a set migration drops the - column the same `Up` drops hstore; - - `Reset` leaves hstore installed; - - two concurrent `Up` runs both succeed with one activation. -15. The unit tier, over the scripted driver, covers what the image can't stage: an installed - version newer than the default with no update path fails before any activation and before - any set. -16. The guide documents the stage, `Extensions`, the new errors, the capability, and - `MigratedWith`. The base changelog records v0.8.0, and postgres's changelog records its - additions under Unreleased. +1. A module's `sqlint.toml` accepts a top-level `extensions` list of strings. `Load` refuses each of + these, one error line each, beginning `sqlint.toml:`: + - a value that isn't a list of strings; + - an empty entry; + - a repeated entry; + - any `extensions` while `engine` is unset. +2. `Load` accepts `[export] reason`, a string, beside `[export.native_forms]`. It also tells a + `native_forms` table declared empty apart from an absent one. So an extension module's own file, + with `native_forms = {}` and a `reason`, loads clean. +3. Each entry is found the way `engine` is. When its first segment contains a dot it is a module + path, resolved through the `Resolver` to the version go.mod pins, workspace and replace included. + Otherwise it is a directory of the tree. An entry that doesn't resolve, or that has no + `sqlint.toml`, is a finding against `sqlint.toml` naming `extensions` and the entry, the way a + failed engine lookup is reported today. The rest of the tree is still linted. +4. A listed module is accepted when its export has at least one native form, or an empty + `native_forms` table beside a non-empty `reason`. Anything else is refused, including a missing + table or an empty table with no reason. A refusal is a finding against `sqlint.toml` that names + the entry and says it exports neither native forms nor a reason. A refused module adds no forms, + and the rest of the tree is still linted. +5. An accepted module's forms join the engine's deny list. They are matched exactly where the + engine's are: + - in standard-tier files only; + - in roles whose `native_forms` switch is on, overrides included; + - against code with literals, quoted identifiers and comments stripped. + + Native-tier files are never checked against them. A form whose expression doesn't compile is a + finding against `sqlint.toml` naming the entry and the form, and the module's other forms still + apply. +6. A finding from an extension's form names the listed entry beside the form's name. For example: + `"<=>" (cosine_distance, from ) in a standard-tier file; declare the tier native and name + the port`. The same form name may appear in the engine and in several extensions. Findings from + the engine's forms are unchanged. +7. sqlint never reads the `native:` header. It stays free text, and the guide documents the + convention that a native file using an extension names that extension there + (`native: postgres, pgvector — <=> cosine distance`). +8. postgres and sqlint require sqlate v0.8.0. Each builds, tests and lints with the workspace off. +9. The guide's sqlint section documents: + - the `extensions` key and how entries are found; + - an extension module's export: forms, or an empty table with a `reason`; + - the `Load` refusals and the findings against `sqlint.toml`; + - the extension finding's message; + - the `native:` header convention; + - that review keeps the `extensions` list in step with `migrate.Options.Extensions`, since + sqlint can't read Go values. +10. sqlint's changelog records the key and the v0.8.0 requirement under Unreleased. postgres's + changelog records `v0.9.0`: the additions now under Unreleased, plus the v0.8.0 requirement. **Test seams** -- `migrate.Migrator` over the scripted `database/sql` driver, with a test dialect that implements - the extension capability (behaviors 1–11 and 15). -- `pgtest.MigratedWith` and `migrate.Migrator` against the integration PostgreSQL, under the - integration tag and the committed workspace (behaviors 12–14). +- `sqlint.Load` over configuration text (behaviors 1–2). +- `sqlint.Lint` over `fstest.MapFS` fixture trees. Extension modules are fixtures, found either as + directories of the tree or through a stub `Resolver` keyed by module path (behaviors 3–6). No + pgvector module is needed. **Slices** -1. Upgrade sqlate: marathon (claude-plugins) 0.22.0 → 0.24.0 and jdx/mise-action v5.2.10 → - v5.3.0. Done when `mise run currency` exits 0 and the check passes. -2. Declarations and the capability: the `Options.Extensions` declaration, `New`'s validation, the - capability interface, the extension error classes, and `Migrator.Extensions` reporting, with - unit tests and the guide. -3. Activation in `Up` and positive `Steps`: check-all-then-activate, the failures before any - activation or set, one transaction per activation, logging, and `Unlocked`. Includes the - newer-than-image unit case and the guide. -4. `Verify` reports extensions before sets: pending activation and pending removal unwrap to - `ErrPending`, and unavailable or no-path fail as their own classes. Unit tests and the guide. -5. Removal at the end of `Up`, with `Down`, `Reset`, and `Force` skipping the stage. Unit tests - and the guide. -6. postgres: the capability's statements with unit tests of their text, `pgtest.MigratedWith`, - the live proofs in behavior 14, the postgres changelog under Unreleased, the base changelog's - v0.8.0 entry, and the guide. +1. Upgrade sqlate: postgres and sqlint move from sqlate v0.7.0 to v0.8.0. postgres's changelog gets + its `v0.9.0` entry and sqlint's gets the requirement under Unreleased. Done when a fresh + `mise run currency` exits 0 (rerun it, since the Go proxy's version list lags new tags) and the + check passes. +2. The `extensions` key in `Load`: the list, its refusals, `extensions` without `engine`, and + `[export] reason` with an empty `native_forms` table. Unit tests, and the guide's configuration + block and prose. +3. Lookup and the deny list in `Lint`: + - entries found as module paths or directories; + - lookup failures and refused modules reported against `sqlint.toml`; + - accepted forms joining the deny list in standard-tier files only; + - bad expressions reported; + - the finding naming the entry. + + Unit tests over fixture modules, the guide's checks and the `native:` header convention, and + sqlint's changelog under Unreleased. **Out of scope** -- No extension version declared in Go, no history table, no schema option: an extension installs - where the session's default schema puts it. -- No `CASCADE` on create or drop, and no drop when a declaration is deleted. -- Shipped sets declaring extensions. -- pgvector, its module, the canonical image's pgvector build and its currency line, sqlint's - `extensions` key, and go-database's `admin.Status` field. -- Moving postgres onto v0.8.0 and releasing `postgres/v0.9.0`, which sqlint-extensions does. +- The `sqlate/postgres/pgvector` module, its forms, and any `extensions` entry in sqlate's own + configuration. pgvector-sql does these. +- Checking `extensions` against `migrate.Options.Extensions`. +- Enforcing extension names in the `native:` header. +- Requiring an engine to export native forms. An engine with none still yields an empty list. +- Releasing sqlint, and stripping dollar-quoted bodies before matching. **Door** -One-way for the `v0.8.0` tag: once pushed, migrate's new exported API is public at that version -(the `Options.Extensions` declaration, the capability interface, `Migrator.Extensions`, and the -error classes). Everything else stays two-way until `postgres/v0.9.0`: postgres's capability -methods and `pgtest.MigratedWith` merge unreleased, and so do the tests and the guide. +One-way for the `postgres/v0.9.0` tag. Once it is pushed, postgres's `ExtensionCatalog` methods +and `pgtest.MigratedWith` are public at that version, requiring sqlate v0.8.0. sqlint's +`extensions` key, the export's `reason`, and the finding format merge unreleased. They stay two-way +until pgvector-sql releases sqlint. **Release** -`v0.8.0` +`postgres/v0.9.0` ## Decisions @@ -144,15 +123,14 @@ methods and `pgtest.MigratedWith` merge unreleased, and so do the tests and the built from source, pgvector pinned by `ARG PGVECTOR_VERSION`. Rejected: pgvector/pgvector's Debian images, PGDG on Debian, and a version declared in Go. - plan: Shipped migration sets declare no extensions; only the application does. -- plan: sqlint's `extensions` key; a listed module exports forms, or `forms = []` with a `reason`, - or is refused. No sqlint check against `Options.Extensions`. - plan: Module paths `sqlate/postgres/pgvector` and `go-database/postgres/pgvector`; the latter uses pgvector-go's root module over `database/sql` and depends on the former's metric table. - extension-stage: A removed declaration still installed is pending: `Verify` unwraps to `ErrPending` and `Extensions` marks it pending, so `admin.Status` reports it not `Ready`. -- extension-stage: Releases `v0.8.0` alone. postgres's capability and `pgtest.MigratedWith` merge - unreleased against v0.7.0; sqlint-extensions' upgrade slice moves postgres onto v0.8.0 and - releases `postgres/v0.9.0` before pgvector-sql needs it. +- sqlint-extensions: sqlint stays unreleased; pgvector-sql's Release line adds `sqlint/v0.5.0` + once pgvector's real forms have exercised the key. +- sqlint-extensions: rejected sqlfluff and squawk, which lint against a fixed dialect and can't + read a module's exported deny list. ## Pending edits @@ -166,3 +144,6 @@ methods and `pgtest.MigratedWith` merge unreleased, and so do the tests and the - coordinator · `context/postgres-extensions.md`: the check fails on any installed version with no update path to the image's default (read through `pg_extension_update_paths`), not only a newer one; a migrate dialect capability supplies the standard pair. +- coordinator · `context/postgres-extensions.md`, "sqlint": an extension module with no forms + declares an empty `[export.native_forms]` table beside `[export] reason`, not `forms = []`; an + `extensions` entry is a module path or a directory of the tree. diff --git a/docs/features.md b/docs/features.md index d206241..c4ea704 100644 --- a/docs/features.md +++ b/docs/features.md @@ -570,6 +570,8 @@ role's, every check is on, and no source is registered. ```toml # The engine whose export names the native forms, and the pattern sources. engine = "github.com/standards-lab/sqlate/postgres" +# Modules whose exported native forms join the engine's; listing any requires an engine. +# extensions = ["github.com/example/sqlate-pgvector"] [sources] sql = "github.com/standards-lab/sqlate" @@ -602,15 +604,18 @@ single_statement = true [export] patterns = "patterns" # overlay = "overlay" +# An extension module that adds no syntax declares the table empty and says why: +# reason = "the extension adds functions, not syntax" +# native_forms = {} # [export.native_forms] # returning = '(?i)\bRETURNING\b' ``` A glob is slash-separated; each segment is a `path.Match` pattern and `**` matches any run of -segments. A source or the engine is a path: a directory of the tree, or a module path (its -first segment contains a dot). A producer, a module or a directory that contains its own -`sqlint.toml`, declares in `[export]` what a consumer reads: the directory its patterns -publish, the overlay directory an engine supplies, and the native forms an engine names. A +segments. A source, the engine, or an extension is a path: a directory of the tree, or a module +path (its first segment contains a dot). A producer, a module or a directory that contains its own +`sqlint.toml`, declares in `[export]` what a consumer reads: the directory its patterns publish, +the overlay directory an engine supplies, and the native forms an engine or an extension names. A bare directory is the pattern files themselves. An engine is always a producer. The `sql` namespace always resolves to the patterns the library embeds: the linter does not read the path of a `sql` entry, and applies the entry's overlay, when one is declared, to those patterns. @@ -622,6 +627,31 @@ and comments stripped first. The PostgreSQL module exports `returning`, `on_conf `concurrently`, `limit`, `serial`, `jsonb`, `timestamptz`, `cast` (the `::` operator), `pg_catalog` (any `pg_` function), `now`, and `uuidv7`. +`extensions` lists the modules whose native forms join the engine's. An extension module +exports its own forms in `[export.native_forms]`, or declares the table empty, `native_forms = {}`, +beside a `reason`, a string saying why it names none; a `reason` may also accompany forms. +`Load` refuses an `extensions` that is not a list of strings, an empty entry, an entry listed +twice, and any `extensions` while `engine` is unset, one line each. + +`Lint` finds each entry the way it finds the engine: a module path through the `Resolver`, and +anything else as a directory of the tree. It accepts a module whose export names at least one +native form, or declares the table empty beside a non-empty `reason`. `Lint` reports each of these +failures against `sqlint.toml` and lints the rest of the tree with what resolved: + +- an entry that does not resolve, or has no `sqlint.toml`: `extensions: : ` and the error; +- a refused module, one with no `native_forms` table or an empty table and no reason: + `extensions: exports neither native forms nor a reason`; it adds no forms; +- a form whose expression does not compile: `extensions: : native_forms.: ` and the + error; the module's other forms still apply. + +An accepted module's forms are matched exactly where the engine's are, and a finding from one names +the entry beside the form: `"<=>" (cosine_distance, from github.com/example/sqlate-pgvector) in a +standard-tier file; declare the tier native and name the port`. A name the engine and an extension +both export is matched and reported for each. A native file that uses an extension's syntax names +the extension in its free-text `native:` header, `native: postgres, pgvector — <=> cosine distance`; +the linter does not read that header, so review checks it. The linter cannot read Go values either, +so review keeps the `extensions` list in step with `migrate.Options.Extensions`. + ### The checks | Role | Check | Switch | @@ -629,7 +659,7 @@ and comments stripped first. The PostgreSQL module exports `returning`, `on_conf | statements | The directory compiles against the configured sources, the way a program compiles it: the header grammar, the parameter syntax, the field contract, includes resolving. | always | | statements | A file is named for its operation, not its SQL verb (`insert_`, `select_`, `update_`, `upsert_`, `merge_`). | `verb_named` | | statements, patterns | `{{` appears in no comment and no string literal. | `delimiter` | -| statements, patterns | A standard-tier file matches none of the engine's native forms. | `native_forms` | +| statements, patterns | A standard-tier file matches none of the native forms of the engine and the accepted extensions. | `native_forms` | | statements | A statement that includes one of the guard protocol's patterns includes both: a statement with a `SET` list that includes `guard_where` also includes `guard_set`, and a statement that includes `guard_set` also includes `guard_where`. The guard's check and a guarded delete include `guard_where` alone. The include is matched by pattern name under any namespace. | `guard` | | patterns | The directory validates as a catalog source: a tier on every file, a port on every native file, parameters only. | always | | migrations | A file headed `transaction: none` contains exactly one statement. | `single_statement` | @@ -641,7 +671,7 @@ and comments stripped first. The PostgreSQL module exports `returning`, `on_conf renders `path:line: message`. A nil configuration is the defaults. The `Resolver` turns a module path into the filesystem of the module's root; `GoList(root)` resolves through `go list -m` in the module at `root`, to the version its `go.mod` pins, a workspace or replace -directive included. A source or engine that does not resolve is a finding against +directive included. A source, engine, or extension that does not resolve is a finding against `sqlint.toml`, and the rest of the tree is linted with what did. Errors in the file's own syntax are `Load`'s, one line each. diff --git a/postgres/CHANGELOG.md b/postgres/CHANGELOG.md index 75d5c5d..cf8a261 100644 --- a/postgres/CHANGELOG.md +++ b/postgres/CHANGELOG.md @@ -7,6 +7,8 @@ changelog covers this sub-module only; the base module keeps its own. ## [Unreleased] +## [v0.9.0] - 2026-11-24 + ### Added - `Dialect.ExtensionState`, `Dialect.ActivateExtension`, and `Dialect.RemoveExtension`, the @@ -22,6 +24,12 @@ changelog covers this sub-module only; the base module keeps its own. removal waits for a set migration to drop the column depending on it, `Reset` leaves an extension installed, and two concurrent `Up` runs activate an extension once. +### Changed + +- The `sqlate` requirement is v0.8.0, whose `migrate.ExtensionCatalog` the dialect implements. + +Requires `github.com/standards-lab/sqlate v0.8.0`. + ## [v0.8.0] - 2026-11-17 ### Added @@ -157,7 +165,8 @@ The first release of the PostgreSQL dialect, against `github.com/standards-lab/s - The integration tier: the migrate and query proofs against a live engine, behind the `integration` build tag. -[Unreleased]: https://github.com/standards-lab/sqlate/compare/postgres/v0.8.0...HEAD +[Unreleased]: https://github.com/standards-lab/sqlate/compare/postgres/v0.9.0...HEAD +[v0.9.0]: https://github.com/standards-lab/sqlate/compare/postgres/v0.8.0...postgres/v0.9.0 [v0.8.0]: https://github.com/standards-lab/sqlate/compare/postgres/v0.7.0...postgres/v0.8.0 [v0.7.0]: https://github.com/standards-lab/sqlate/compare/postgres/v0.6.0...postgres/v0.7.0 [v0.6.0]: https://github.com/standards-lab/sqlate/compare/postgres/v0.5.0...postgres/v0.6.0 diff --git a/postgres/go.mod b/postgres/go.mod index 65a8f1f..4f3df41 100644 --- a/postgres/go.mod +++ b/postgres/go.mod @@ -4,7 +4,7 @@ go 1.27 require ( github.com/jackc/pgx/v5 v5.13.0 - github.com/standards-lab/sqlate v0.7.0 + github.com/standards-lab/sqlate v0.8.0 ) require ( diff --git a/postgres/go.sum b/postgres/go.sum index f69959e..336a20f 100644 --- a/postgres/go.sum +++ b/postgres/go.sum @@ -11,8 +11,8 @@ github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/standards-lab/sqlate v0.7.0 h1:GVb3OCDXwSS9RCxQ2BRIfV73zwBeJBhkvDLBJnTYd/U= -github.com/standards-lab/sqlate v0.7.0/go.mod h1:pikNmGf/z3x46SBWFXgt/xKIDZuquSgCoXy5OWBFFR4= +github.com/standards-lab/sqlate v0.8.0 h1:G1uUIWmc2DxJz5YhtBvIlftfURnb3b2RKsYB59Wa03Y= +github.com/standards-lab/sqlate v0.8.0/go.mod h1:pikNmGf/z3x46SBWFXgt/xKIDZuquSgCoXy5OWBFFR4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= diff --git a/sqlint/CHANGELOG.md b/sqlint/CHANGELOG.md index 9ec8b4f..09efbd6 100644 --- a/sqlint/CHANGELOG.md +++ b/sqlint/CHANGELOG.md @@ -7,6 +7,28 @@ changelog covers this sub-module only; the base module keeps its own. ## [Unreleased] +### Added + +- An `extensions` key in `sqlint.toml` lists the modules whose exported native forms join the + engine's, read into `Config.Extensions`. Each entry is found as the engine is, a module path + through the `Resolver` or a directory of the tree. `Load` refuses an `extensions` that is not a + list of strings, an empty entry, an entry listed twice, and any `extensions` without an `engine`. +- `[export] reason`, read into `Export.Reason`: an extension module that names no forms declares + `native_forms = {}` beside a reason saying why. +- `Lint` reports against `sqlint.toml` an entry that does not resolve or has no `sqlint.toml` + (`extensions: : …`), a module that exports neither native forms nor a reason + (`extensions: exports neither native forms nor a reason`), and a form whose + expression does not compile (`extensions: : native_forms.: …`). +- A finding from an extension's form names the entry beside the form: + `"<=>" (cosine_distance, from ) in a standard-tier file; declare the tier native and + name the port`. Findings from the engine's forms are unchanged. + +### Changed + +- The `sqlate` requirement is v0.8.0. + +Requires `github.com/standards-lab/sqlate v0.8.0`. + ## [v0.4.0] - 2026-11-11 ### Changed diff --git a/sqlint/body.go b/sqlint/body.go index 2eeb71e..7c83404 100644 --- a/sqlint/body.go +++ b/sqlint/body.go @@ -29,7 +29,7 @@ func (l *linter) lintBody(p, text string, end int, delimiter, forms, guard bool) if forms { for _, f := range l.forms { if m := f.re.FindString(code); m != "" { - l.report(p, line, fmt.Sprintf("%q (%s) in a standard-tier file; declare the tier native and name the port", m, f.name)) + l.report(p, line, fmt.Sprintf("%q (%s) in a standard-tier file; declare the tier native and name the port", m, f.label())) } } } @@ -96,3 +96,10 @@ func codeOnly(line string, inBlock bool) (string, bool) { } return b.String(), inBlock } + +func (f form) label() string { + if f.from == "" { + return f.name + } + return f.name + ", from " + f.from +} diff --git a/sqlint/config.go b/sqlint/config.go index c37a95f..8006dd3 100644 --- a/sqlint/config.go +++ b/sqlint/config.go @@ -22,6 +22,9 @@ type Config struct { // Engine is the path of the engine whose export declares the native // forms; empty means the native-forms check has no list. Engine string + // Extensions are the module paths whose exported native forms join + // the engine's; listing any requires an engine. + Extensions []string // Sources maps a namespace to the source registered under it. Sources map[string]Source // Roles maps each role's name to the role. @@ -39,13 +42,17 @@ type Source struct { // Export is a producer's declaration: the directory its namespace // publishes, the overlay directory an engine supplies, and the native -// forms an engine names, each a regular expression under the name the -// finding reports, so the engine states in what position a spelling -// counts, word boundaries and case, and not only which spelling. +// forms an engine or an extension names, each a regular expression under +// the name the finding reports, so the producer states in what position a +// spelling counts, word boundaries and case, and not only which spelling. +// NativeForms is nil when the export declares no native_forms table, and +// empty, not nil, when it declares the table empty; Reason is the +// producer's account of why it names the forms it does, or none. type Export struct { Patterns string `toml:"patterns"` Overlay string `toml:"overlay"` NativeForms map[string]string `toml:"native_forms"` + Reason string `toml:"reason"` } // Role is one role's directory globs and switches, with any per-glob @@ -76,6 +83,7 @@ func defaults() *Config { type raw struct { Engine string `toml:"engine"` + Extensions toml.Primitive `toml:"extensions"` Sources map[string]toml.Primitive `toml:"sources"` Statements map[string]toml.Primitive `toml:"statements"` Patterns map[string]toml.Primitive `toml:"patterns"` @@ -124,6 +132,12 @@ func parseConfig(text string) (*Config, error) { } c.Sources[ns] = s } + if md.IsDefined("extensions") { + c.Extensions = parseExtensions(md, r.Extensions, fail) + if r.Engine == "" { + fail("extensions: listed without an engine") + } + } for name, table := range map[string]map[string]toml.Primitive{"statements": r.Statements, "patterns": r.Patterns, "migrations": r.Migrations} { if table == nil { continue @@ -138,6 +152,26 @@ func parseConfig(text string) (*Config, error) { return c, errors.Join(errs...) } +func parseExtensions(md toml.MetaData, prim toml.Primitive, fail func(string, ...any)) []string { + var list []string + if err := md.PrimitiveDecode(prim, &list); err != nil { + fail("extensions: a list of module paths") + return nil + } + var out []string + for i, ext := range list { + switch { + case ext == "": + fail("extensions[%d]: empty", i) + case slices.Contains(out, ext): + fail("extensions[%d]: %q is listed twice", i, ext) + default: + out = append(out, ext) + } + } + return out +} + 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...)) } diff --git a/sqlint/doc.go b/sqlint/doc.go index d615686..2fd7e05 100644 --- a/sqlint/doc.go +++ b/sqlint/doc.go @@ -8,8 +8,8 @@ // - a file is named for its operation and not its SQL verb // - the parameter delimiter does not appear inside a comment or a string // literal -// - a standard-tier file uses no native form the configured engine -// declares +// - a standard-tier file uses no native form the configured engine or +// an accepted extension declares // - a statement that includes one of the guard protocol's patterns // includes both: guard_set beside guard_where in a SET statement, and // guard_where beside guard_set diff --git a/sqlint/go.mod b/sqlint/go.mod index d60caec..b910bda 100644 --- a/sqlint/go.mod +++ b/sqlint/go.mod @@ -4,5 +4,5 @@ go 1.27 require ( github.com/BurntSushi/toml v1.6.0 - github.com/standards-lab/sqlate v0.7.0 + github.com/standards-lab/sqlate v0.8.0 ) diff --git a/sqlint/go.sum b/sqlint/go.sum index 2366f7a..238bbd9 100644 --- a/sqlint/go.sum +++ b/sqlint/go.sum @@ -1,4 +1,4 @@ github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk= github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= -github.com/standards-lab/sqlate v0.7.0 h1:GVb3OCDXwSS9RCxQ2BRIfV73zwBeJBhkvDLBJnTYd/U= -github.com/standards-lab/sqlate v0.7.0/go.mod h1:pikNmGf/z3x46SBWFXgt/xKIDZuquSgCoXy5OWBFFR4= +github.com/standards-lab/sqlate v0.8.0 h1:G1uUIWmc2DxJz5YhtBvIlftfURnb3b2RKsYB59Wa03Y= +github.com/standards-lab/sqlate v0.8.0/go.mod h1:pikNmGf/z3x46SBWFXgt/xKIDZuquSgCoXy5OWBFFR4= diff --git a/sqlint/lint.go b/sqlint/lint.go index deba6fd..c279448 100644 --- a/sqlint/lint.go +++ b/sqlint/lint.go @@ -39,14 +39,16 @@ type linter struct { type form struct { name string + from string re *regexp.Regexp } // Lint walks fsys under cfg and returns every finding, in walk order. A // nil cfg is the defaults. resolve turns a module path into its root // filesystem; nil refuses every module path. A source or engine that does -// not resolve is a finding against File; the rest of the tree is linted -// with what did. +// not resolve is a finding against File, as is an extension that does +// not resolve or exports neither native forms nor a reason; the rest of +// the tree is linted with what did. func Lint(fsys fs.FS, cfg *Config, resolve Resolver) []Finding { if cfg == nil { cfg = defaults() @@ -57,6 +59,7 @@ func Lint(fsys fs.FS, cfg *Config, resolve Resolver) []Finding { l := &linter{fsys: fsys, cfg: cfg, resolve: resolve} l.resolveSources() l.resolveEngine() + l.resolveExtensions() _ = fs.WalkDir(fsys, ".", func(p string, d fs.DirEntry, err error) error { if err != nil || !d.IsDir() { return nil @@ -166,27 +169,52 @@ func (l *linter) resolveEngine() { if l.cfg.Engine == "" { return } - fsys, base, err := l.locate(l.cfg.Engine) + if export, ok := l.producer("engine: ", l.cfg.Engine); ok { + l.addForms("engine: ", "", export.NativeForms) + } +} + +func (l *linter) resolveExtensions() { + for _, ext := range l.cfg.Extensions { + prefix := "extensions: " + ext + ": " + export, ok := l.producer(prefix, ext) + if !ok { + continue + } + if export.NativeForms == nil || (len(export.NativeForms) == 0 && export.Reason == "") { + l.report(File, 0, fmt.Sprintf("extensions: %s exports neither native forms nor a reason", ext)) + continue + } + l.addForms(prefix, ext, export.NativeForms) + } +} + +func (l *linter) producer(prefix, value string) (Export, bool) { + fsys, base, err := l.locate(value) if err != nil { - l.report(File, 0, fmt.Sprintf("engine: %v", err)) - return + l.report(File, 0, prefix+err.Error()) + return Export{}, false } export, err := readExport(fsys, base) if err != nil { - l.report(File, 0, fmt.Sprintf("engine: %v", err)) - return + l.report(File, 0, prefix+err.Error()) + return Export{}, false } - names := make([]string, 0, len(export.NativeForms)) - for name := range export.NativeForms { + return export, true +} + +func (l *linter) addForms(prefix, from string, forms map[string]string) { + names := make([]string, 0, len(forms)) + for name := range forms { names = append(names, name) } sort.Strings(names) for _, name := range names { - re, err := regexp.Compile(export.NativeForms[name]) + re, err := regexp.Compile(forms[name]) if err != nil { - l.report(File, 0, fmt.Sprintf("engine: native_forms.%s: %v", name, err)) + l.report(File, 0, fmt.Sprintf("%snative_forms.%s: %v", prefix, name, err)) continue } - l.forms = append(l.forms, form{name: name, re: re}) + l.forms = append(l.forms, form{name: name, from: from, re: re}) } } diff --git a/sqlint/lint_test.go b/sqlint/lint_test.go index b680c85..f7bde5b 100644 --- a/sqlint/lint_test.go +++ b/sqlint/lint_test.go @@ -156,6 +156,66 @@ func TestLoad_ReportsConfigurationErrors(t *testing.T) { } } +func TestLoad_RefusesMalformedExtensions(t *testing.T) { + cases := []struct{ line, want string }{ + {`extensions = "example.com/ext"`, "extensions: a list of module paths"}, + {`extensions = ["example.com/ext", 3]`, "extensions: a list of module paths"}, + {`extensions = ["example.com/ext", ""]`, "extensions[1]: empty"}, + {`extensions = ["example.com/ext", "example.com/other", "example.com/ext"]`, `extensions[2]: "example.com/ext" is listed twice`}, + } + for _, tc := range cases { + c, err := sqlint.Load(tree(tc.line + "\n" + config)) + if err == nil || err.Error() != "sqlint.toml: "+tc.want { + t.Errorf("Load(%s) error = %v, want the one line %q", tc.line, err, tc.want) + } + if c == nil || c.Engine != "engine" { + t.Errorf("Load(%s) returned no configuration beside the error", tc.line) + } + } + _, err := sqlint.Load(tree(`extensions = ["example.com/ext"]`)) + if err == nil || err.Error() != "sqlint.toml: extensions: listed without an engine" { + t.Errorf("extensions without an engine: error = %v", err) + } +} + +func TestLoad_ReadsExtensions(t *testing.T) { + c, err := sqlint.Load(tree(`extensions = ["example.com/ext", "example.com/other"]` + "\n" + config)) + if err != nil { + t.Fatal(err) + } + if want := []string{"example.com/ext", "example.com/other"}; !slices.Equal(c.Extensions, want) { + t.Errorf("Extensions = %q, want %q", c.Extensions, want) + } +} + +func TestLoad_ExportsDeclaredEmptyFormsWithAReason(t *testing.T) { + cases := map[string]struct { + text string + forms map[string]string + reason string + }{ + "empty with a reason": {"[export]\nreason = \"the module adds functions, not syntax\"\nnative_forms = {}\n", map[string]string{}, "the module adds functions, not syntax"}, + "forms with a reason": {"[export]\nreason = \"vectors\"\n[export.native_forms]\ndistance = '<->'\n", map[string]string{"distance": "<->"}, "vectors"}, + "absent": {"[export]\npatterns = \"patterns\"\n", nil, ""}, + } + for name, tc := range cases { + c, err := sqlint.Load(tree(tc.text)) + if err != nil { + t.Errorf("%s: Load error = %v", name, err) + continue + } + if (c.Export.NativeForms == nil) != (tc.forms == nil) || !maps.Equal(c.Export.NativeForms, tc.forms) { + t.Errorf("%s: NativeForms = %#v, want %#v", name, c.Export.NativeForms, tc.forms) + } + if c.Export.Reason != tc.reason { + t.Errorf("%s: Reason = %q, want %q", name, c.Export.Reason, tc.reason) + } + } + if _, err := sqlint.Load(tree("[export]\nreason = 3\n")); err == nil || !strings.HasPrefix(err.Error(), "sqlint.toml: ") { + t.Errorf("a reason that is not a string: error = %v", err) + } +} + func TestLint_ReportsResolutionFailures(t *testing.T) { cases := map[string]string{ "sources.app: open missing": source(`app = "missing"`), @@ -407,3 +467,81 @@ func TestLint_MisspelledNotNull(t *testing.T) { 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")} want(t, lint(fsys, nil), `domain/f/statements: query: sized.sql: field declaration "size bigint nott null": the type contains "not" or "null"`) } + +func extensionTree(entries ...string) fstest.MapFS { + cfg := `extensions = ["` + strings.Join(entries, `", "`) + `"]` + "\n" + config + "\n[statements.\"admin/*/statements\"]\nnative_forms = false\n" + fsys := tree(cfg) + fsys["vec/sqlint.toml"] = &fstest.MapFile{Data: []byte("[export.native_forms]\ncosine_distance = '<=>'\nreturning = '(?i)\\bRETURNING\\b'\n")} + fsys["bare/notes.md"] = &fstest.MapFile{Data: []byte("no export")} + fsys["formless/sqlint.toml"] = &fstest.MapFile{Data: []byte("[export]\nreason = \"no table\"\n")} + fsys["unexplained/sqlint.toml"] = &fstest.MapFile{Data: []byte("[export]\nnative_forms = {}\n")} + fsys["functions/sqlint.toml"] = &fstest.MapFile{Data: []byte("[export]\nreason = \"the extension adds functions, not syntax\"\nnative_forms = {}\n")} + fsys["halfbad/sqlint.toml"] = &fstest.MapFile{Data: []byte("[export.native_forms]\nbad = '(unclosed'\ncontains = '@>'\n")} + fsys["domain/v/statements/nearest.sql"] = &fstest.MapFile{Data: []byte("--| tier: standard\nSELECT id FROM t\nORDER BY v <=> {{q}}\n, '<=>' -- <=>\nWHERE area && {{box}} AND tags @> {{tags}}")} + fsys["domain/v/statements/native.sql"] = &fstest.MapFile{Data: []byte("--| tier: native\n--| native: postgres, pgvector — <=> cosine distance\nSELECT id FROM t ORDER BY v <=> {{q}} WHERE area && {{box}} AND tags @> {{tags}}")} + fsys["admin/x/statements/nearest.sql"] = &fstest.MapFile{Data: []byte("--| tier: standard\nSELECT id FROM t ORDER BY v <=> {{q}} WHERE area && {{box}}")} + return fsys +} + +var extensionModules = sqlint.Resolver(func(module string) (fs.FS, error) { + if module == "example.com/geo" { + return fstest.MapFS{"sqlint.toml": {Data: []byte("[export.native_forms]\noverlaps = '&&'\n")}}, nil + } + return nil, fmt.Errorf("no module %s", module) +}) + +func TestLint_ExtensionFormsJoinTheEngines(t *testing.T) { + findings := lint(extensionTree("vec", "example.com/geo"), extensionModules) + want(t, findings, + `domain/v/statements/nearest.sql:3: "<=>" (cosine_distance, from vec) in a standard-tier file; declare the tier native and name the port`, + `domain/v/statements/nearest.sql:5: "&&" (overlaps, from example.com/geo) in a standard-tier file; declare the tier native and name the port`, + `domain/a/statements/list.sql:4: "RETURNING" (returning, from vec) in a standard-tier file; declare the tier native and name the port`, + ) + if !slices.Contains(findings, `domain/a/statements/list.sql:4: "RETURNING" (returning) in a standard-tier file; declare the tier native and name the port`) { + t.Errorf("the engine's finding changed:\n%s", strings.Join(findings, "\n")) + } + reject(t, findings, "nearest.sql:4:", "domain/v/statements/native.sql", "admin/x/statements/nearest.sql", "sqlint.toml") + n := 0 + for _, f := range findings { + if strings.Contains(f, "nearest.sql") { + n++ + } + } + if n != 2 { + t.Errorf("nearest.sql: %d findings, want 2:\n%s", n, strings.Join(findings, "\n")) + } +} + +func TestLint_ReportsExtensionFailures(t *testing.T) { + cases := map[string]string{ + "nowhere": "sqlint.toml: extensions: nowhere: open nowhere: file does not exist", + "example.com/missing": "sqlint.toml: extensions: example.com/missing: no module example.com/missing", + "bare": "sqlint.toml: extensions: bare: bare declares no sqlint.toml", + "formless": "sqlint.toml: extensions: formless exports neither native forms nor a reason", + "unexplained": "sqlint.toml: extensions: unexplained exports neither native forms nor a reason", + "halfbad": "sqlint.toml: extensions: halfbad: native_forms.bad: error parsing regexp", + } + for entry, wantMsg := range cases { + findings := lint(extensionTree(entry, "vec"), extensionModules) + want(t, findings, wantMsg, `nearest.sql:3: "<=>" (cosine_distance, from vec)`, "insert_thing.sql: named for its SQL verb") + sqlintFindings := 0 + for _, f := range findings { + if strings.HasPrefix(f, "sqlint.toml: ") { + sqlintFindings++ + } + } + if sqlintFindings != 1 { + t.Errorf("%s: %d findings against sqlint.toml, want 1:\n%s", entry, sqlintFindings, strings.Join(findings, "\n")) + } + } + want(t, lint(extensionTree("halfbad"), nil), `nearest.sql:5: "@>" (contains, from halfbad)`) +} + +func TestLint_ExtensionWithAReasonAddsNothing(t *testing.T) { + with := lint(extensionTree("functions", "vec"), nil) + without := lint(extensionTree("vec"), nil) + if !slices.Equal(with, without) { + t.Errorf("findings with an empty table and a reason:\n%s\nwant those without the entry:\n%s", strings.Join(with, "\n"), strings.Join(without, "\n")) + } + reject(t, with, "sqlint.toml", "functions") +}