diff --git a/CHANGELOG.md b/CHANGELOG.md index 63d607b..9df7f83 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,30 @@ becomes the release notes of the next tag. `smarttags.Vocabulary`; `smartcomments/catalog.Check` runs it over every commented object of a catalog. +### Breaking: API hygiene + +See [docs/upgrading.md](docs/upgrading.md#api-hygiene). + +- `confx.Load` takes `WithFlags(values)` instead of a pflag set; + `confx/cliflags.Changed` replaces `confx.ChangedFlags`. `WithRemoved` + names keys removed without a replacement. `MovedKeys`, + `ParseTrustedProxy`, `ValidChannelName` and `TX.Mutations` are gone, and + the shared doc tags no longer name a product. +- `pgexec.SanitizeMessage` is gone (use `Classify`); `ParseIsolation` and + `ParseDetail` return an error instead of falling back. +- `contract.ParsePolicy`; `confx.Contract.Default` is a `contract.Policy`; + `Contract.View` returns an error for an unknown policy; `Apply`, + `OmitAll` and `TransformCatalog` are gone. +- `postgis.OutputSQL(ref, Output)`, `Derived.SQL(ref, f, Output)` and + `RasterAccessor.SQL(ref, Output)` replace the json/jsonb × precision + variants; `Ops()`, `Deriveds()`, `RasterAccessors()` and + `contrib.VectorTypes()` replace the mutable variables; `Op.Index` and + `Op.Arg` are `Op.Indexable` and `Op.OperandType`. +- `jwtmint.Sign`, `postgis.OpsDoc`, `OpNames` and `DerivedSuffixes` are + gone. +- `watch.New(Config)` validates up front; `OnChange(ctx, cat)`; `Run` no + longer writes into the watcher's configuration. + ## [0.18.0] - 2026-11-23 ### Breaking: identity and strict config diff --git a/README.md b/README.md index 2e0d988..fcaa140 100644 --- a/README.md +++ b/README.md @@ -28,18 +28,18 @@ fixture both products are tested against. |---|---| | `introspect` | `Catalog` model (`Table`, `Column`, `Constraint`, `ForeignKey`, `Index`, `Enum`, `Composite`, `Function`, `Extension`, privileges, RLS flag, comments; `Column.Spatial` (`SpatialType`: PostGIS subtype, SRID, Z/M from the geometry/geography typmod) and `Column.SQLType` (built-in modifiers such as `character varying(255)`, `numeric(10,2)`); `Catalog.ServerVersionNum` for version gating; `Column.GeneratedKind` (identity `ALWAYS` / `BY DEFAULT`, stored, virtual) with `Column.GeneratedAlways` (never writable), `Identity` and `OmittableOnInsert`; domains (`Catalog.Domains`: base type, parent domain, NOT NULL, CHECK constraints, default, comment; `Column.Domain` / `FuncArg.Domain` / `Function.ReturnDomain` refs, `Catalog.Domain`, `DomainByRef`, `DomainChain`); PostgreSQL 18 temporal keys (`Constraint.WithoutOverlaps`, `ForeignKey.Period` with `JoinPairs`, `Table.RowKeys`) and `ForeignKey.NotEnforced`; check constraints (`Table.Checks`) and the columns of index expressions and predicates (`Index.ExpressionColumns`), with `Table.ConstraintColumns` / `Table.ConstraintReferences` for integrity-error sanitizing; `ForeignKey.NotValid` and `MayDangle`; `Column.NotNull` only for validated NOT NULL constraints; `Index.OpClasses` per indexed column), `Introspect(ctx, querier, schemas)` (pg_catalog reader incl. `@enum` table conversion and installed extensions; functions ordered by schema, name and input parameter types so overload keep-first is stable; refuses PostgreSQL < 14 with `*UnsupportedServerError`), `HasExtension`, polymorphic signatures (`IsPolymorphic`, `Function.PolymorphicFamilies`, `Catalog.ResolvePolymorphic`, `Catalog.ParseTypeName` for SQL type spellings), `Clone` (deep copy for per-contract catalog hooks), `Diff` (human-readable drift lines), `Hash` (non-mutating; covers the server's major version, not its minor), `CatalogFormatVersion` (a golden test of the JSON field set fails until it is bumped) | | `smarttags` | PostGraphile-style smart-comment parser: `Parse`, `Strip`, `Tags`, `Omits` (`@omit` and the omit tokens of `@behavior`: `-select`, `-insert`, `-update`, `-delete`, the PostGraphile V5 `-filterBy` / `-orderBy` and their deprecated forms `-filter` / `-order`), `Contracts` (`@contract` / `@behavior ±contract:` membership), `Check` (unknown `@omit` actions, unknown and deprecated `@behavior` tokens against a product's `Vocabulary`), list splitting | -| `contract` | schema contracts (see [Schema contracts](#schema-contracts)): `Contract{Name, Default}` with the `Include`/`Exclude` policies, `View` (clone + filter), `Apply`, `OmitAll`; also a `CatalogHook` | +| `contract` | schema contracts (see [Schema contracts](#schema-contracts)): `Contract{Name, Default}` with the `Include`/`Exclude` policies (`ParsePolicy` rejects anything else), `View` (clone + filter; an unknown policy is an error) | | `inflect` | naming pipeline types (`Kind`, `Input`, `Next`) + string helpers (`UpperCamel`, `LowerCamel`, `Singularize`, `Pluralize`, `EnumValue`, `ByColumns`); products define their own `Kind` constants and `Default` | | `cache` | gzip+JSON catalog cache: `Save` (records the `Writer`: product, version, pdbcore version) / `Load` / `Check`, format-version (`*FormatVersionError`) and content-hash (`ErrCorrupt`) checks, 256 MiB decompression guard | -| `watch` | `Watcher`: DDL event trigger + `LISTEN/NOTIFY` (`TriggerName`, `Channel`), hash-polling fallback when the trigger cannot be installed → `OnChange(*Catalog)` | -| `postgis` | spatial value layer: flavour detection, GeoJSON/WKT/EWKT parsing to one bound parameter, filter `Ops`, derived accessors, transform/simplify/buffer/KNN/distance SQL (`BufferSQL`, metres on geography; `DistanceSQL`, metres on the spheroid with `SpheroidDistanceSQL`), GeoJSON output with a bound coordinate precision (`OutputPrecisionSQL`/`OutputJSONPrecisionSQL`, `CheckPrecision`); `postgis_raster` columns (`IsRaster`): header-only metadata `RasterAccessors` (width, height, bands, SRID, pixel size, envelope as GeoJSON), `RasterValueSQL` (`ST_Value` at a bound point, reprojected to the raster's SRID), `RasterSummaryStatsSQL` (`ST_SummaryStats` of a band as a JSON object), `RasterIntersectsSQL` (served by a GiST index on `ST_ConvexHull(col)`) and `Raster*Cost` weights for cost estimators | +| `watch` | `New(Config)` → `Watcher`: DDL event trigger + `LISTEN/NOTIFY` (`TriggerName`, `Channel`), hash-polling fallback when the trigger cannot be installed → `OnChange(ctx, *Catalog)`; `New` validates the names, `Run` never modifies the configuration | +| `postgis` | spatial value layer: flavour detection, GeoJSON/WKT/EWKT parsing to one bound parameter, filter operators (`Ops()`), derived accessors (`Deriveds()`), transform/simplify/buffer/KNN/distance SQL (`BufferSQL`, metres on geography; `DistanceSQL`, metres on the spheroid with `SpheroidDistanceSQL`), GeoJSON output (`OutputSQL(ref, Output{JSON, Precision})`: jsonb or json, optionally with a bound coordinate precision checked by `CheckPrecision`); `postgis_raster` columns (`IsRaster`): header-only metadata `RasterAccessors()` (width, height, bands, SRID, pixel size, envelope as GeoJSON), `RasterValueSQL` (`ST_Value` at a bound point, reprojected to the raster's SRID), `RasterSummaryStatsSQL` (`ST_SummaryStats` of a band as a JSON object), `RasterIntersectsSQL` (served by a GiST index on `ST_ConvexHull(col)`) and `Raster*Cost` weights for cost estimators | | `contrib` | operator vocabularies + value coercion for full-text search (`tsvector`, and `to_tsvector` over text and json/jsonb documents, with `ts_headline` snippets), `pg_trgm`, `unaccent`, `fuzzystrmatch`, `hstore`, `ltree`, `citext`, `intarray`, range/multirange, `inet`/`cidr`, pgvector (`vector`, `halfvec`, `sparsevec`, plus bit distances on `bit`/`varbit`), `cube` and `earthdistance` (`earth` columns, `<@>` on `point`) columns (see [Contrib vocabularies](#contrib-vocabularies)): `ForColumn`/`ForType` lookup bound to the extension's schema, filter `Op`s, ordering `Expr`s (`Expr.Score` marks the selectable similarity/distance values, `Expr.Derived` the per-use parameterised values such as an hstore key's value, `Expr.OrderSQL` the index-served ordering form), `Accessor`s, value `Codec`s, `Op.RankSQL`/`Op.HeadlineSQL` with validated `HeadlineOptions`, `HeadlineDocumentSQL`/`HeadlineDocumentCost` to bound and price a headline's document | | `auth` | `Authenticator`: JWT (HS*, JWKS RS*/ES* with a kid-matched cache refreshed by one shared background fetch, stale keys served for one extra TTL during endpoint outages, failure backoff, endpoint details logged and never returned to clients), trusted-gateway claim headers with `TrustedProxies` (one spelling per claim: `User-Id` is `user_id`; underscores, repeats and case-folded duplicates are rejected; optional `HeaderClaims` allowlist; the gateway must strip every client-supplied prefixed header), typed `Mode` (`jwt`, `headers`, `none`; `New` rejects anything else, a headers mode without trusted proxies, and a jwt mode without a key), case-insensitive `Bearer`, clock-skew `Leeway`, role claim paths (`app_metadata.role`, `realm_access.roles[0]`), role resolution and allowlist, optional anonymous access, `SkipRoleSwitch`; `ErrInvalidToken` / `ErrAuthRequired` / `ErrRoleNotAllowed`, and `Challenge` for the `WWW-Authenticate` value | -| `pgexec` | pool `Connect` (connections to PostgreSQL < 14 fail), `RunTx` (isolation, `SET LOCAL ROLE`, claims via `set_config(prefix.k, v, true)` and optionally as one JSON setting, 40001/40P01 retries), `QueryTx` (one pipelined round trip), `Savepoint` (run a step in a SAVEPOINT inside a `RunTx` callback; a failure rolls back to it and comes back as `*RolledBackError`, so the transaction goes on), `Observer` (per-attempt duration and error via `TxOptions.Observer`, `Observe` for direct statements), `Identity`, `Classify` PG errors into classes with `dev`/`prod`/`strict` message policies (21* cardinality violations, malformed tsquery/ltree operands, unknown text search configs and raster/geometry SRID mismatches are user input), `QuoteIdent`/`ValidRole`/`ValidClaimKey` | -| `jwtmint` | composite-typed function results → signed HS256 JWT (`MintsFunction`, `Mint`, `Sign`) | +| `pgexec` | pool `Connect` (connections to PostgreSQL < 14 fail), `RunTx` (isolation from `ParseIsolation`, which rejects unknown spellings, `SET LOCAL ROLE`, claims via `set_config(prefix.k, v, true)` and optionally as one JSON setting, 40001/40P01 retries), `QueryTx` (one pipelined round trip), `Savepoint` (run a step in a SAVEPOINT inside a `RunTx` callback; a failure rolls back to it and comes back as `*RolledBackError`, so the transaction goes on), `Observer` (per-attempt duration and error via `TxOptions.Observer`, `Observe` for direct statements), `Identity`, `Classify` PG errors into classes and client messages under a `Detail` policy (`ParseDetail`: `dev`/`prod`/`strict`, anything else rejected; the one error-message API) (21* cardinality violations, malformed tsquery/ltree operands, unknown text search configs and raster/geometry SRID mismatches are user input), `QuoteIdent`/`ValidRole`/`ValidClaimKey` | +| `jwtmint` | composite-typed function results → signed HS256 JWT (`MintsFunction`, `Mint`) | | `httpx` | CORS (`CORSPolicy`: origins, preflight methods, exposed headers) + preflight, `AddVary`, gzip, `Healthz`, `ListenAndServe` with the standard timeouts and graceful shutdown | | `metrics` | Prometheus instrumentation on a per-instance registry (or a caller's `Registerer` + `ConstLabels`): HTTP `Middleware` (requests, duration, in flight by route class, method, status class; `SetRoute`), `DBObserver` (a `pgexec.Observer`: duration, errors by SQLSTATE class, retries), `RegisterPool` (pgxpool `Stat`), `SchemaRebuilt`, `ObserveCompile`, product counters via `NewCounter`; `NewRegistry` + `RegisterPoolOn` for several instances (one per contract) on one registry; a nil `*Metrics` records nothing (see [Metrics](#metrics)) | -| `confx` | strict koanf `Load` (defaults < YAML < env < changed flags; unknown keys are errors naming the key they moved to or the closest valid one, `MovedKeys`/`WithMoved`), env key mapper (`_` → `.`, `__` → `_`, comma-separated lists), `ExampleYAML` from `koanf`/`doc` tags, `Discover`, `ParseTrustedProxy`, shared config sections (`Database`, `Schema`, `Filters`, `Auth`/`JWT`/`Headers`, `Roles`, `Claims`, `TX`, `Watch`, `Errors`, `Plugins[S]` with typed per-plugin settings, `Log`, `Metrics`, `Contract` list entries) + `Validate*` helpers (`ValidateIdentity`, `ValidatePluginNames`, `ValidateContracts`), `AuthConfig(Auth, Roles)`, `IdentityWarnings` | +| `confx` | strict koanf `Load` (defaults < YAML < env < `WithFlags` command-line values, which `confx/cliflags.Changed` reads from a pflag set; unknown keys are errors naming the key they moved to (`WithMoved`), why they were removed (`WithRemoved`) or the closest valid one), env key mapper (`_` → `.`, `__` → `_`, comma-separated lists), `ExampleYAML` from `koanf`/`doc` tags, `Discover`, shared config sections (`Database`, `Schema`, `Filters`, `Auth`/`JWT`/`Headers`, `Roles`, `Claims`, `TX`, `Watch`, `Errors`, `Plugins[S]` with typed per-plugin settings, `Log`, `Metrics`, `Contract` list entries) + `Validate*` helpers (`ValidateIdentity`, `ValidatePluginNames`, `ValidateContracts`), `AuthConfig(Auth, Roles)`, `IdentityWarnings` | | `plugin` | `Plugin`, `Registry` (priority + registration order), `CatalogHook`, `InflectionHook`, `TransformCatalog`, `Inflector` chain | | `smartcomments/catalog` | catalog half of the smart-comments plugin (`@omit`, `@primaryKey`, `@unique`, `@foreignKey`, `@notNull`, `@filterable`, `@anyelement` / `@anycompatible` on polymorphic functions, `@name` index) — products add their transport half on top | | `testutil` | `FixtureSQL` (embedded DDL) and `FixtureCatalog()`, the one fixture both products test against; `testutil/cmd/fixture` prints the SQL; `drift_test.go` is the fixture drift gate | @@ -111,7 +111,7 @@ _ = m.RegisterPool(pool) opts := pgexec.TxOptions{Observer: m.DBObserver()} // nil observer on a nil *Metrics handler = m.Middleware(handler, classify) // classify: *http.Request -> route class mux.Handle(cfg.Metrics.Path, m.Handler()) // or a separate listener on cfg.Metrics.Addr -watcher.OnChange = func(cat *introspect.Catalog) { m.SchemaRebuilt(rebuild(cat)) } +cfg.OnChange = func(ctx context.Context, cat *introspect.Catalog) { m.SchemaRebuilt(rebuild(ctx, cat)) } // watch.Config hits, _ := m.NewCounter("document_cache_requests_total", "Document cache lookups.", "result") ``` @@ -206,7 +206,7 @@ non-atomic column expression groups the same bound or unbound. | `earthpoint` (`earthdistance`) | `point` (core; only with earthdistance installed), (lon, lat) | `earthDistanceMilesLessThan` (`(col <@> point($2, $1)) < $3`, statute miles) | `earthDistanceMiles` (`<@>`), ordering and score | — | none | | `inet` | `inet`, `cidr` | `containedBy` (`<<`), `containedByOrEquals` (`<<=`), `contains` (`>>`), `containsOrEquals` (`>>=`), `containsOrContainedBy` (`&&`) | `family`, `masklen`, `host`, `network` | text ↔ `$1::inet` / `$1::cidr` | GiST `inet_ops`, SP-GiST | -Output SQL comes in two flavours. `OutputSQL` (`postgis.OutputSQL`, `Derived.SQL`, `Codec.OutputSQL`, `RangeOutputSQL`, `MultirangeOutputSQL`, `HstoreOutputSQL`) yields `jsonb`; the `OutputJSONSQL`/`JSONSQL` counterparts yield `json`, which skips jsonb construction and is markedly cheaper. Use json when the value is only embedded in a `json_build_object`/`json_agg` response; keep jsonb when it is compared, grouped, deduplicated or aggregated with jsonb functions. +Output SQL comes in two flavours. `Codec.OutputSQL`, `RangeOutputSQL`, `MultirangeOutputSQL` and `HstoreOutputSQL` yield `jsonb`; their `OutputJSONSQL` counterparts yield `json` (in `postgis`, `OutputSQL`, `Derived.SQL` and `RasterAccessor.SQL` take an `Output` with `JSON: true` instead), which skips jsonb construction and is markedly cheaper. Use json when the value is only embedded in a `json_build_object`/`json_agg` response; keep jsonb when it is compared, grouped, deduplicated or aggregated with jsonb functions. Full-text matches also render a highlighted snippet: `Op.HeadlineSQL(doc, options, phs...)` is `ts_headline([config,] doc, [, diff --git a/confx/cliflags/cliflags.go b/confx/cliflags/cliflags.go new file mode 100644 index 0000000..7576e14 --- /dev/null +++ b/confx/cliflags/cliflags.go @@ -0,0 +1,32 @@ +// Package cliflags adapts a spf13/pflag flag set to [confx.WithFlags], so +// package confx itself does not depend on pflag. Config flags are named +// after koanf paths (--server.addr sets server.addr). +package cliflags + +import ( + flag "github.com/spf13/pflag" +) + +// Changed returns the flags explicitly set on fs, minus any names in except +// (e.g. "config"), as koanf path to value: a []string for slice flags +// (StringSlice, StringArray, IntSlice, ...), the flag's string form +// otherwise. Unset flags are left out so they cannot shadow file and +// environment values. +func Changed(fs *flag.FlagSet, except ...string) map[string]any { + skip := make(map[string]bool, len(except)) + for _, n := range except { + skip[n] = true + } + out := map[string]any{} + fs.Visit(func(f *flag.Flag) { + if skip[f.Name] { + return + } + if sv, ok := f.Value.(flag.SliceValue); ok { + out[f.Name] = sv.GetSlice() + return + } + out[f.Name] = f.Value.String() + }) + return out +} diff --git a/confx/cliflags/cliflags_test.go b/confx/cliflags/cliflags_test.go new file mode 100644 index 0000000..166f180 --- /dev/null +++ b/confx/cliflags/cliflags_test.go @@ -0,0 +1,60 @@ +package cliflags_test + +import ( + "reflect" + "testing" + "time" + + flag "github.com/spf13/pflag" + + "github.com/suprbdev/pdbcore/confx" + "github.com/suprbdev/pdbcore/confx/cliflags" +) + +func TestChanged(t *testing.T) { + fs := flag.NewFlagSet("t", flag.ContinueOnError) + fs.String("config", "", "") + fs.String("server.addr", ":8080", "") + fs.Bool("server.compression", false, "") + fs.StringSlice("schema.schemas", nil, "") + fs.Duration("database.statement_timeout", time.Second, "") + fs.Int("limits.max_depth", 10, "") + if err := fs.Parse([]string{"--config=x.yaml", "--server.compression", "--schema.schemas=app,audit", + "--database.statement_timeout=3s"}); err != nil { + t.Fatal(err) + } + got := cliflags.Changed(fs, "config") + want := map[string]any{ + "server.compression": "true", + "schema.schemas": []string{"app", "audit"}, + "database.statement_timeout": "3s", + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("Changed = %#v, want %#v", got, want) + } + + var cfg struct { + Server struct { + Addr string `koanf:"addr"` + Compression bool `koanf:"compression"` + } `koanf:"server"` + Schema struct { + Schemas []string `koanf:"schemas"` + } `koanf:"schema"` + Database struct { + StatementTimeout time.Duration `koanf:"statement_timeout"` + } `koanf:"database"` + Limits struct { + MaxDepth int `koanf:"max_depth"` + } `koanf:"limits"` + } + cfg.Server.Addr = ":9000" + cfg.Limits.MaxDepth = 7 + if err := confx.Load("CLIFLAGS_TEST_", "", &cfg, confx.WithFlags(got)); err != nil { + t.Fatal(err) + } + if cfg.Server.Addr != ":9000" || !cfg.Server.Compression || !reflect.DeepEqual(cfg.Schema.Schemas, []string{"app", "audit"}) || + cfg.Database.StatementTimeout != 3*time.Second || cfg.Limits.MaxDepth != 7 { + t.Fatalf("cfg = %+v", cfg) + } +} diff --git a/confx/confx_test.go b/confx/confx_test.go index e74f806..c8afef3 100644 --- a/confx/confx_test.go +++ b/confx/confx_test.go @@ -8,14 +8,11 @@ import ( "strings" "testing" "time" - - flag "github.com/spf13/pflag" ) // pdbqServer mirrors pdbq's Server section so the reference-YAML golden -// (testdata/pdbq.example.yaml, the body of pdbq's committed example) proves -// ExampleYAML reproduces pdbq's output byte for byte over the shared -// sections. +// (testdata/pdbq.example.yaml, shaped like the body of pdbq's committed +// example) pins what ExampleYAML renders over the shared sections. type pdbqServer struct { Addr string `koanf:"addr" doc:"Listen address for the HTTP server."` GraphiQL bool `koanf:"graphiql" doc:"Serve the GraphiQL playground at / (off by default; enable for development)."` @@ -34,10 +31,9 @@ type pdbqServer struct { DisableIntrospection bool `koanf:"disable_introspection" doc:"Reject __schema / __type introspection queries (off by default). Enable in production to hide the schema shape; __typename keeps working."` } -// pdbqTX is pdbq's own 4-field TX (per_request sits second, which struct +// pdbqTX is pdbq's own TX (per_request sits first, which struct // embedding cannot express — see TestSquashEmbedding). type pdbqTX struct { - Mutations bool `koanf:"mutations" doc:"Wrap every mutation in a transaction."` PerRequest bool `koanf:"per_request" doc:"Use one transaction for the whole request instead of one per operation."` Isolation string `koanf:"isolation" doc:"Transaction isolation level: read_committed, repeatable_read, serializable."` MaxRetries int `koanf:"max_retries" doc:"Automatic retries of a transactional operation after a serialization failure or deadlock (SQLSTATE 40001/40P01). 0 disables; the whole operation re-runs, which is safe because the failed attempt rolled back."` @@ -80,7 +76,7 @@ func pdbqDefaults() pdbqConfig { Auth: DefaultAuth("X-Pdbq-Claim-"), Roles: DefaultRoles(), Claims: DefaultClaims(), - TX: pdbqTX{Mutations: true, Isolation: "read_committed"}, + TX: pdbqTX{Isolation: "read_committed"}, Watch: Watch{PollInterval: 5 * time.Second, Channel: "pdbq_ddl"}, Errors: Errors{Detail: "prod"}, Plugins: Plugins[pdbqPlugins]{}, @@ -116,7 +112,7 @@ func TestExampleYAMLDocOverride(t *testing.T) { if !strings.Contains(out, "# custom detail doc\n detail: \"prod\"") { t.Fatalf("override not applied:\n%s", out) } - if strings.Contains(out, "GraphQL errors") { + if strings.Contains(out, "error detail in error responses") { t.Fatal("original doc must be replaced") } } @@ -138,27 +134,19 @@ func TestSquashEmbedding(t *testing.T) { t.Fatal(err) } t.Setenv("PDBX_TRANSACTIONS_MAX__RETRIES", "3") - fs := flag.NewFlagSet("t", flag.ContinueOnError) - fs.Bool("transactions.mutations", true, "") - if err := fs.Parse([]string{"--transactions.mutations=false"}); err != nil { - t.Fatal(err) - } - cfg := squashConfig{TX: squashTX{TX: TX{Mutations: true, Isolation: "read_committed"}}} - if err := Load("PDBX_", path, ChangedFlags(fs), &cfg); err != nil { + cfg := squashConfig{TX: squashTX{TX: TX{Isolation: "read_committed"}}} + if err := Load("PDBX_", path, &cfg, WithFlags(map[string]any{"transactions.max_retries": "5"})); err != nil { t.Fatal(err) } - if cfg.TX.Isolation != "serializable" || !cfg.TX.PerRequest || cfg.TX.MaxRetries != 3 || cfg.TX.Mutations { + if cfg.TX.Isolation != "serializable" || !cfg.TX.PerRequest || cfg.TX.MaxRetries != 5 { t.Fatalf("squash load = %+v", cfg.TX) } // ExampleYAML inlines the embedded fields, but embedded fields can only - // come before or after the wrapper's own fields — pdbq's per_request - // sits between mutations and isolation, so byte-identical output needs - // pdbq to keep its own TX struct. + // come before or after the wrapper's own fields. out := ExampleYAML(cfg) want := "transactions:\n" + - " # Wrap every mutation in a transaction.\n mutations: false\n" + " # Transaction isolation level: read_committed, repeatable_read, serializable.\n isolation: \"serializable\"\n" + - " # Automatic retries of a transactional operation after a serialization failure or deadlock (SQLSTATE 40001/40P01). 0 disables; the whole operation re-runs, which is safe because the failed attempt rolled back.\n max_retries: 3\n" + + " # Automatic retries of a transactional operation after a serialization failure or deadlock (SQLSTATE 40001/40P01). 0 disables; the whole operation re-runs, which is safe because the failed attempt rolled back.\n max_retries: 5\n" + " # Use one transaction for the whole request instead of one per operation.\n per_request: true\n\n" if out != want { t.Fatalf("squash example:\n%s\nwant:\n%s", out, want) @@ -181,15 +169,8 @@ roles: } t.Setenv("PDBQ_SERVER_ADDR", ":7777") // env overrides file t.Setenv("PDBQ_LOG_LEVEL", "debug") - fs := flag.NewFlagSet("t", flag.ContinueOnError) - fs.String("log.level", "", "") - fs.String("errors.detail", "", "") - fs.String("config", "", "") - if err := fs.Parse([]string{"--log.level=warn", "--config=" + path}); err != nil { - t.Fatal(err) - } cfg := pdbqDefaults() - if err := Load("PDBQ_", path, ChangedFlags(fs, "config"), &cfg); err != nil { + if err := Load("PDBQ_", path, &cfg, WithFlags(map[string]any{"log.level": "warn"})); err != nil { t.Fatal(err) } if cfg.Database.URL != "postgres://file/db" { @@ -214,7 +195,7 @@ roles: func TestLoadMissingFile(t *testing.T) { cfg := pdbqDefaults() - err := Load("PDBQ_", filepath.Join(t.TempDir(), "nope.yaml"), nil, &cfg) + err := Load("PDBQ_", filepath.Join(t.TempDir(), "nope.yaml"), &cfg) if err == nil || !strings.HasPrefix(err.Error(), "config: read ") { t.Fatalf("err = %v", err) } @@ -253,14 +234,14 @@ func TestDiscover(t *testing.T) { func TestParseTrustedProxy(t *testing.T) { for _, s := range []string{"10.0.0.0/8", "10.0.0.5", "::1", "fe80::/10"} { - if _, err := ParseTrustedProxy(s); err != nil { + if _, err := parseTrustedProxy(s); err != nil { t.Errorf("%s rejected: %v", s, err) } } - if p, _ := ParseTrustedProxy("10.0.0.5"); p.Bits() != 32 { + if p, _ := parseTrustedProxy("10.0.0.5"); p.Bits() != 32 { t.Errorf("single IP must be /32, got %v", p) } - if _, err := ParseTrustedProxy("not-an-ip"); err == nil { + if _, err := parseTrustedProxy("not-an-ip"); err == nil { t.Error("garbage accepted") } } @@ -366,7 +347,7 @@ func TestValidateRejects(t *testing.T) { "watch channel length": {func() []string { return ValidateWatch(Watch{Enabled: true, Channel: strings.Repeat("c", 64)}, "") }, `watch.channel: "` + strings.Repeat("c", 64) + `" is longer than 63 bytes`}, "isolation": {func() []string { return ValidateTX(TX{Isolation: "chaos"}) }, - `transactions.isolation: "chaos" invalid`}, + `transactions.isolation: "chaos" is not 'read_committed', 'repeatable_read' or 'serializable'`}, "max_retries": {func() []string { return ValidateTX(TX{Isolation: "serializable", MaxRetries: -1}) }, "transactions.max_retries must be >= 0"}, "watch+cache": {func() []string { return ValidateWatch(Watch{Enabled: true, Channel: "c"}, "x") }, @@ -481,7 +462,7 @@ func TestLoadSplitsEnvLists(t *testing.T) { t.Setenv("PDBX_SCHEMA_SCHEMAS", "public, audit") t.Setenv("PDBX_DATABASE_URL", "postgres://a,b@h/db") cfg := pdbqDefaults() - if err := Load("PDBX_", "", nil, &cfg); err != nil { + if err := Load("PDBX_", "", &cfg); err != nil { t.Fatal(err) } if len(cfg.Schema.Schemas) != 2 || cfg.Schema.Schemas[0] != "public" || cfg.Schema.Schemas[1] != "audit" { @@ -573,7 +554,7 @@ contracts: t.Fatal(err) } var c cfg - if err := Load("PDBX_", path, nil, &c); err != nil { + if err := Load("PDBX_", path, &c); err != nil { t.Fatal(err) } want := []Contract{{Name: "public"}, {Name: "partner", Default: "exclude", Path: "/partners"}, {Name: "internal"}} @@ -583,7 +564,7 @@ contracts: t.Setenv("PDBX_CONTRACTS", "public,partner") c = cfg{} - if err := Load("PDBX_", "", nil, &c); err != nil { + if err := Load("PDBX_", "", &c); err != nil { t.Fatal(err) } if want := []Contract{{Name: "public"}, {Name: "partner"}}; !slices.Equal(c.Contracts, want) { diff --git a/confx/load.go b/confx/load.go index 838e914..62a7a39 100644 --- a/confx/load.go +++ b/confx/load.go @@ -12,20 +12,20 @@ import ( "github.com/knadh/koanf/parsers/yaml" "github.com/knadh/koanf/providers/env" "github.com/knadh/koanf/providers/file" - "github.com/knadh/koanf/providers/posflag" "github.com/knadh/koanf/v2" - flag "github.com/spf13/pflag" ) // LoadOption customises Load. type LoadOption func(*loadOpts) type loadOpts struct { - moved map[string]string + hints + flags map[string]any } -// WithMoved adds product keys to MovedKeys: old key (or old section, which -// maps every key below it) to the key that replaced it. +// WithMoved adds product keys to the keys Load knows were moved: old key +// (or old section, which maps every key below it) to the key that +// replaced it. func WithMoved(moved map[string]string) LoadOption { return func(o *loadOpts) { for k, v := range moved { @@ -34,22 +34,46 @@ func WithMoved(moved map[string]string) LoadOption { } } +// WithRemoved names keys that were removed without a replacement: old key +// (or old section, covering every key below it) to the reason, e.g. +// "mutations always run in a transaction". Load reports such a key as +// "unknown key : removed: ". +func WithRemoved(removed map[string]string) LoadOption { + return func(o *loadOpts) { + for k, v := range removed { + o.removed[k] = v + } + } +} + +// WithFlags layers command-line values over the file and the environment: +// koanf path (e.g. server.addr) to value. Pass only the flags the user +// actually set so unset flags cannot shadow YAML/env values. Values are +// decoded like environment values: strings set booleans, numbers and +// durations, and a []string sets a list. +func WithFlags(values map[string]any) LoadOption { + return func(o *loadOpts) { + for k, v := range values { + o.flags[k] = v + } + } +} + // Load layers configuration into dst (which already holds the defaults): // optional YAML file, then envPrefix-prefixed environment variables, then -// flags. Pass only the flags the user actually set (see ChangedFlags) so -// unset flags cannot shadow YAML/env values; flag names are koanf paths. +// command-line values (WithFlags). // // Loading is strict: a file key that dst has no field for is an error -// naming the key it moved to (MovedKeys, WithMoved) or the closest valid -// key. An environment variable with the prefix is checked the same way -// when its first segment names a section of dst (or of a moved key), or -// nearly does; other variables with the prefix (PDBQ_TEST_DATABASE_URL) -// are ignored. Values are decoded with weak typing, so environment strings -// set booleans, numbers, durations and lists. Validation is the caller's -// job. -func Load(envPrefix, path string, flags *flag.FlagSet, dst any, opts ...LoadOption) error { - o := loadOpts{moved: map[string]string{}} - for k, v := range MovedKeys { +// naming the key it moved to (WithMoved), the reason it was removed +// (WithRemoved) or the closest valid key. An environment variable with +// the prefix is checked the same way when its first segment names a +// section of dst (or of a moved or removed key), or nearly does; other +// variables with the prefix (PDBQ_TEST_DATABASE_URL) are ignored. Values +// are decoded with weak typing, so environment strings set booleans, +// numbers, durations and lists. Validation is the caller's job. +func Load(envPrefix, path string, dst any, opts ...LoadOption) error { + o := loadOpts{hints: hints{moved: map[string]string{}, removed: map[string]string{}}, flags: map[string]any{}} + for k, v := range movedKeys { o.moved[k] = v } for _, opt := range opts { @@ -68,7 +92,7 @@ func Load(envPrefix, path string, flags *flag.FlagSet, dst any, opts ...LoadOpti continue } msg := "unknown key " + key - if hint := schema.unknownKey(key, o.moved, func(p string) string { return p }); hint != "" { + if hint := schema.unknownKey(key, o.hints, func(p string) string { return p }); hint != "" { msg += ": " + hint } errs = append(errs, msg) @@ -92,12 +116,12 @@ func Load(envPrefix, path string, flags *flag.FlagSet, dst any, opts ...LoadOpti continue } top, _, _ := strings.Cut(key, ".") - if !schema.section(top, o.moved) { + if !schema.section(top, o.hints) { ek.Delete(key) continue } msg := fmt.Sprintf("unknown environment variable %s (%s)", envVars[key], key) - if hint := schema.unknownKey(key, o.moved, func(p string) string { return envName(envPrefix, p) }); hint != "" { + if hint := schema.unknownKey(key, o.hints, func(p string) string { return envName(envPrefix, p) }); hint != "" { msg += ": " + hint } errs = append(errs, msg) @@ -109,9 +133,9 @@ func Load(envPrefix, path string, flags *flag.FlagSet, dst any, opts ...LoadOpti if err := k.Merge(ek); err != nil { return fmt.Errorf("config: %w", err) } - if flags != nil { - if err := k.Load(posflag.Provider(flags, ".", k), nil); err != nil { - return fmt.Errorf("config: flags: %w", err) + for key, v := range o.flags { + if err := k.Set(key, v); err != nil { + return fmt.Errorf("config: flag %s: %w", key, err) } } err := k.UnmarshalWithConf("", dst, koanf.UnmarshalConf{DecoderConfig: &mapstructure.DecoderConfig{ @@ -127,23 +151,6 @@ func Load(envPrefix, path string, flags *flag.FlagSet, dst any, opts ...LoadOpti return nil } -// ChangedFlags returns a FlagSet holding only the flags explicitly set on -// fs, minus any names in except (e.g. "config") — the only-changed-flags -// bridge products hand to Load. -func ChangedFlags(fs *flag.FlagSet, except ...string) *flag.FlagSet { - skip := map[string]bool{} - for _, n := range except { - skip[n] = true - } - changed := flag.NewFlagSet("changed", flag.ContinueOnError) - fs.Visit(func(f *flag.Flag) { - if !skip[f.Name] { - changed.AddFlag(f) - } - }) - return changed -} - // EnvKeyMapper maps PREFIX_SERVER_MAX__DEPTH -> server.max_depth: the prefix // is stripped, a double underscore preserves an underscore inside a key, and // a single underscore is a level separator. @@ -222,9 +229,9 @@ func Discover(names ...string) string { return "" } -// ParseTrustedProxy parses one rls.auth.trusted_proxies entry: either a CIDR +// parseTrustedProxy parses one auth.headers.trusted_proxies entry: either a CIDR // block ("10.0.0.0/8") or a single IP ("10.0.0.1", treated as /32 or /128). -func ParseTrustedProxy(s string) (netip.Prefix, error) { +func parseTrustedProxy(s string) (netip.Prefix, error) { if strings.Contains(s, "/") { return netip.ParsePrefix(s) } diff --git a/confx/sections.go b/confx/sections.go index b0b1b19..b2635f6 100644 --- a/confx/sections.go +++ b/confx/sections.go @@ -26,7 +26,7 @@ type Database struct { // Schema selects what is introspected and how. type Schema struct { Schemas []string `koanf:"schemas" doc:"PostgreSQL schemas to expose."` - CachePath string `koanf:"cache_path" doc:"Boot from this schema cache file instead of introspecting (see pdbq schema dump)."` + CachePath string `koanf:"cache_path" doc:"Boot from this schema cache file (written by the schema dump command) instead of introspecting."` Functions bool `koanf:"functions" doc:"Expose PostgreSQL functions as custom queries/mutations."` } @@ -58,7 +58,7 @@ type JWT struct { // Headers is the auth.headers section. type Headers struct { - Prefix string `koanf:"prefix" doc:"Header prefix mapped to claims, e.g. X-Pdbq-Claim-. The rest of the name maps to one claim (User-Id is user_id); requests with a claim header containing an underscore or other punctuation, repeated, or folding onto another claim header are rejected. The gateway must strip every client-supplied header with this prefix, in any letter case."` + Prefix string `koanf:"prefix" doc:"Header prefix mapped to claims, e.g. X-Claim-. The rest of the name maps to one claim (User-Id is user_id); requests with a claim header containing an underscore or other punctuation, repeated, or folding onto another claim header are rejected. The gateway must strip every client-supplied header with this prefix, in any letter case."` Claims []string `koanf:"claims" doc:"Claim names (e.g. user_id) accepted from claim headers; role_claim is always accepted. Requests carrying any other claim header are rejected. Empty accepts any claim."` RoleClaim string `koanf:"role_claim" doc:"Claim carrying the database role (role is sent as Role). A missing claim falls back to roles.default."` TrustedProxies []string `koanf:"trusted_proxies" doc:"CIDR blocks (or single IPs) allowed to send claim headers; required in headers mode. Requests from other peers that carry claim headers are rejected."` @@ -106,10 +106,9 @@ func DefaultClaims() Claims { return Claims{Prefix: DefaultClaimsPrefix} } -// TX is the transaction policy shared by both products. pdbq adds -// per_request in its own wrapper. +// TX is the transaction policy shared by both products, which add their +// own keys in their own sections. type TX struct { - Mutations bool `koanf:"mutations" doc:"Wrap every mutation in a transaction."` Isolation string `koanf:"isolation" doc:"Transaction isolation level: read_committed, repeatable_read, serializable."` MaxRetries int `koanf:"max_retries" doc:"Automatic retries of a transactional operation after a serialization failure or deadlock (SQLSTATE 40001/40P01). 0 disables; the whole operation re-runs, which is safe because the failed attempt rolled back."` } @@ -123,7 +122,7 @@ type Watch struct { // Errors is the error-detail policy. type Errors struct { - Detail string `koanf:"detail" doc:"'dev' exposes full PostgreSQL error detail in GraphQL errors; 'prod' sanitizes but passes constraint-violation and bad-input messages through; 'strict' hides every database error message (constraint and column names never leak)."` + Detail string `koanf:"detail" doc:"'dev' exposes full PostgreSQL error detail in error responses; 'prod' sanitizes but passes constraint-violation and bad-input messages through; 'strict' hides every database error message (constraint and column names never leak)."` } // Plugins disables and configures plugins by name. S is the product's @@ -165,9 +164,9 @@ func DefaultMetrics() Metrics { // Contract is one entry of the contracts list: a named, audience-specific // view of the API served under its own path (see package contract). type Contract struct { - Name string `koanf:"name" doc:"Contract name, matched against @contract and @behavior ±contract: smart tags: lower-case letters, digits, _ and -."` - Default string `koanf:"default" doc:"Policy for tables and functions without a tag for this contract: 'include' (the default: the contract is everything not tagged out) or 'exclude' (only what is tagged in)."` - Path string `koanf:"path" doc:"URL path the contract is served under; defaults to its name."` + Name string `koanf:"name" doc:"Contract name, matched against @contract and @behavior ±contract: smart tags: lower-case letters, digits, _ and -."` + Default contract.Policy `koanf:"default" doc:"Policy for tables and functions without a tag for this contract: 'include' (the default: the contract is everything not tagged out) or 'exclude' (only what is tagged in)."` + Path string `koanf:"path" doc:"URL path the contract is served under; defaults to its name."` } // UnmarshalText makes a bare string a contract of that name with the @@ -190,7 +189,7 @@ func (c Contract) URLPath(base string) string { // Spec returns the catalog filter of the contract. func (c Contract) Spec() contract.Contract { - return contract.Contract{Name: c.Name, Default: contract.Policy(c.Default)} + return contract.Contract{Name: c.Name, Default: c.Default} } // FindContract returns the contract named name, or false. diff --git a/confx/strict.go b/confx/strict.go index 9ac9fd5..292b2f9 100644 --- a/confx/strict.go +++ b/confx/strict.go @@ -9,10 +9,10 @@ import ( "time" ) -// MovedKeys maps configuration keys removed before 1.0 to the key that +// movedKeys maps configuration keys removed before 1.0 to the key that // replaced them. Load names the replacement when a file or environment // variable still uses an old key; products add their own with WithMoved. -var MovedKeys = map[string]string{ +var movedKeys = map[string]string{ "rls.enabled": "roles.switch", "rls.anonymous_role": "roles.anonymous", "rls.default_role": "roles.default", @@ -112,9 +112,16 @@ func (s keySchema) known(key string) bool { return false } -// section reports whether name is a top-level key of the schema or of a -// moved key, or a near miss of one. -func (s keySchema) section(name string, moved map[string]string) bool { +// hints holds the keys an unknown key is explained by: moved maps an old +// key (or section) to its replacement, removed maps one to the reason it +// is gone. +type hints struct { + moved, removed map[string]string +} + +// section reports whether name is a top-level key of the schema, of a +// moved key or of a removed key, or a near miss of one. +func (s keySchema) section(name string, h hints) bool { tops := []string{} for p := range s { if !strings.Contains(p, ".") { @@ -124,32 +131,38 @@ func (s keySchema) section(name string, moved map[string]string) bool { tops = append(tops, p) } } - for old := range moved { - if top, _, _ := strings.Cut(old, "."); top == name { - return true + for _, m := range []map[string]string{h.moved, h.removed} { + for old := range m { + if top, _, _ := strings.Cut(old, "."); top == name { + return true + } } } return len(name) >= 4 && closest(name, tops) != "" } -// unknownKey describes an unknown key: where it moved to, or the closest -// known or moved key; name renders a path for the message. -func (s keySchema) unknownKey(key string, moved map[string]string, name func(string) string) string { - if to, ok := movedTo(key, moved); ok { +// unknownKey describes an unknown key: where it moved to, why it was +// removed, or the closest known or moved key; name renders a path for the +// message. +func (s keySchema) unknownKey(key string, h hints, name func(string) string) string { + if to, ok := movedTo(key, h.moved); ok { return fmt.Sprintf("moved to %s", name(to)) } - cands := make([]string, 0, len(s)+len(moved)) + if why, ok := removedAt(key, h.removed); ok { + return "removed: " + why + } + cands := make([]string, 0, len(s)+len(h.moved)) for p := range s { cands = append(cands, p) } - for old := range moved { + for old := range h.moved { cands = append(cands, old) } best := closest(key, cands) if best == "" { return "" } - if to, ok := movedTo(best, moved); ok { + if to, ok := movedTo(best, h.moved); ok { return fmt.Sprintf("did you mean %s (formerly %s)?", name(to), best) } return fmt.Sprintf("did you mean %s?", name(best)) @@ -173,6 +186,20 @@ func movedTo(key string, moved map[string]string) (string, bool) { return moved[best] + key[len(best):], true } +// removedAt reports why key, or the section it lies in, was removed. +func removedAt(key string, removed map[string]string) (string, bool) { + for k := key; ; { + if why, ok := removed[k]; ok { + return why, true + } + i := strings.LastIndexByte(k, '.') + if i < 0 { + return "", false + } + k = k[:i] + } +} + // closest returns the candidate nearest to s by edit distance, or "" when // none is within max(2, len(s)/5) edits. Ties go to the lexically smallest. func closest(s string, cands []string) string { diff --git a/confx/strict_test.go b/confx/strict_test.go index d1a28d8..256846a 100644 --- a/confx/strict_test.go +++ b/confx/strict_test.go @@ -38,7 +38,7 @@ plugins: totally_unrelated: 1 `) cfg := pdbqDefaults() - err := Load("PDBX_", path, nil, &cfg, WithMoved(map[string]string{"plugins.settings.advanced-filters": "plugins.settings.advanced_filters"})) + err := Load("PDBX_", path, &cfg, WithMoved(map[string]string{"plugins.settings.advanced-filters": "plugins.settings.advanced_filters"})) if err == nil { t.Fatal("unknown keys accepted") } @@ -71,7 +71,7 @@ func TestLoadRejectsUnknownEnvKeysInKnownSections(t *testing.T) { t.Setenv("PDBX_TEST_DATABASE_URL", "postgres://test") t.Setenv("PDBX_PRINT_SDL_DIGEST", "1") cfg := pdbqDefaults() - err := Load("PDBX_", "", nil, &cfg) + err := Load("PDBX_", "", &cfg) if err == nil { t.Fatal("unknown env keys accepted") } @@ -95,7 +95,7 @@ func TestLoadIgnoresUnrelatedPrefixedEnv(t *testing.T) { t.Setenv("PDBX_TEST_DATABASE_URL", "postgres://test") t.Setenv("PDBX_TEST_PDBQ_DIR", "/x") cfg := pdbqDefaults() - if err := Load("PDBX_", "", nil, &cfg); err != nil { + if err := Load("PDBX_", "", &cfg); err != nil { t.Fatal(err) } } @@ -107,7 +107,7 @@ func TestLoadDecodesEnvIntoTypedSettings(t *testing.T) { t.Setenv("PDBX_AUTH_JWT_LEEWAY", "30s") t.Setenv("PDBX_ROLES_ALLOWED", "app_user, app_admin") cfg := pdbqDefaults() - if err := Load("PDBX_", "", nil, &cfg); err != nil { + if err := Load("PDBX_", "", &cfg); err != nil { t.Fatal(err) } s := cfg.Plugins.Settings.AdvancedFilters @@ -117,7 +117,7 @@ func TestLoadDecodesEnvIntoTypedSettings(t *testing.T) { } t.Setenv("PDBX_PLUGINS_SETTINGS_ADVANCED__FILTERS_MAX__DEPTH", "deep") cfg = pdbqDefaults() - if err := Load("PDBX_", "", nil, &cfg); err == nil || !strings.Contains(err.Error(), "max_depth") { + if err := Load("PDBX_", "", &cfg); err == nil || !strings.Contains(err.Error(), "max_depth") { t.Fatalf("bad int accepted: %v", err) } } @@ -127,7 +127,7 @@ func TestLoadRejectsUnknownKeysInListEntries(t *testing.T) { var c struct { Contracts []Contract `koanf:"contracts"` } - err := Load("PDBX_", path, nil, &c) + err := Load("PDBX_", path, &c) if err == nil || !strings.Contains(err.Error(), "default_policy") { t.Fatalf("err = %v", err) } @@ -136,7 +136,7 @@ func TestLoadRejectsUnknownKeysInListEntries(t *testing.T) { func TestLoadAcceptsMapKeys(t *testing.T) { path := writeYAML(t, "filters:\n allow_columns:\n public.users: [email]\n") cfg := pdbqDefaults() - if err := Load("PDBX_", path, nil, &cfg); err != nil { + if err := Load("PDBX_", path, &cfg); err != nil { t.Fatal(err) } if len(cfg.Filters.AllowColumns) == 0 { @@ -167,3 +167,32 @@ func TestEditDistance(t *testing.T) { } } } + +func TestLoadNamesRemovedKeys(t *testing.T) { + path := writeYAML(t, ` +transactions: + mutations: true +legacy: + thing: 1 +`) + t.Setenv("PDBX_TRANSACTIONS_MUTATIONS", "false") + t.Setenv("PDBX_LEGACY_OTHER", "x") + cfg := pdbqDefaults() + err := Load("PDBX_", path, &cfg, WithRemoved(map[string]string{ + "transactions.mutations": "mutations always run in a transaction", + "legacy": "the legacy section is gone", + })) + if err == nil { + t.Fatal("removed keys accepted") + } + for _, want := range []string{ + "unknown key transactions.mutations: removed: mutations always run in a transaction", + "unknown key legacy.thing: removed: the legacy section is gone", + "unknown environment variable PDBX_TRANSACTIONS_MUTATIONS (transactions.mutations): removed: mutations always run in a transaction", + "unknown environment variable PDBX_LEGACY_OTHER (legacy.other): removed: the legacy section is gone", + } { + if !strings.Contains(err.Error(), want) { + t.Errorf("error lacks %q:\n%v", want, err) + } + } +} diff --git a/confx/testdata/pdbq.example.yaml b/confx/testdata/pdbq.example.yaml index 3f8ff73..2f1a4ab 100644 --- a/confx/testdata/pdbq.example.yaml +++ b/confx/testdata/pdbq.example.yaml @@ -43,7 +43,7 @@ server: schema: # PostgreSQL schemas to expose. schemas: ["public"] - # Boot from this schema cache file instead of introspecting (see pdbq schema dump). + # Boot from this schema cache file (written by the schema dump command) instead of introspecting. cache_path: "" # Expose PostgreSQL functions as custom queries/mutations. functions: true @@ -77,7 +77,7 @@ auth: role_claim_path: "role" # Gateway claim headers (headers mode). headers: - # Header prefix mapped to claims, e.g. X-Pdbq-Claim-. The rest of the name maps to one claim (User-Id is user_id); requests with a claim header containing an underscore or other punctuation, repeated, or folding onto another claim header are rejected. The gateway must strip every client-supplied header with this prefix, in any letter case. + # Header prefix mapped to claims, e.g. X-Claim-. The rest of the name maps to one claim (User-Id is user_id); requests with a claim header containing an underscore or other punctuation, repeated, or folding onto another claim header are rejected. The gateway must strip every client-supplied header with this prefix, in any letter case. prefix: "X-Pdbq-Claim-" # Claim names (e.g. user_id) accepted from claim headers; role_claim is always accepted. Requests carrying any other claim header are rejected. Empty accepts any claim. claims: [] @@ -105,8 +105,6 @@ claims: json_setting: "" transactions: - # Wrap every mutation in a transaction. - mutations: true # Use one transaction for the whole request instead of one per operation. per_request: false # Transaction isolation level: read_committed, repeatable_read, serializable. @@ -123,7 +121,7 @@ watch: channel: "pdbq_ddl" errors: - # 'dev' exposes full PostgreSQL error detail in GraphQL errors; 'prod' sanitizes but passes constraint-violation and bad-input messages through; 'strict' hides every database error message (constraint and column names never leak). + # 'dev' exposes full PostgreSQL error detail in error responses; 'prod' sanitizes but passes constraint-violation and bad-input messages through; 'strict' hides every database error message (constraint and column names never leak). detail: "prod" plugins: diff --git a/confx/validate.go b/confx/validate.go index ac5d120..df2a12e 100644 --- a/confx/validate.go +++ b/confx/validate.go @@ -12,7 +12,8 @@ import ( "github.com/suprbdev/pdbcore/pgexec" ) -// InvalidConfig joins validation messages into pdbq's error shape, or nil +// InvalidConfig joins validation messages into one error, "invalid +// config:" followed by one indented "- message" line each, or returns nil // when there are none. func InvalidConfig(errs []string) error { if len(errs) == 0 { @@ -21,13 +22,12 @@ func InvalidConfig(errs []string) error { return fmt.Errorf("invalid config:\n - %s", strings.Join(errs, "\n - ")) } -// ValidateErrors checks errors.detail. +// ValidateErrors checks errors.detail (see [pgexec.ParseDetail]). func ValidateErrors(e Errors) []string { - switch e.Detail { - case "dev", "prod", "strict": - return nil + if _, err := pgexec.ParseDetail(e.Detail); err != nil { + return []string{"errors.detail: " + err.Error()} } - return []string{fmt.Sprintf("errors.detail: %q is not 'dev', 'prod' or 'strict'", e.Detail)} + return nil } // ValidateIdentity checks the auth, roles and claims sections together: @@ -71,7 +71,7 @@ func ValidateIdentity(a Auth, r Roles, c Claims) []string { } } for _, p := range a.Headers.TrustedProxies { - if _, err := ParseTrustedProxy(p); err != nil { + if _, err := parseTrustedProxy(p); err != nil { add("auth.headers.trusted_proxies: %q is not a valid IP or CIDR block", p) } } @@ -123,13 +123,12 @@ func IdentityWarnings(a Auth, r Roles) []string { return out } -// ValidateTX checks transactions.isolation and transactions.max_retries. +// ValidateTX checks transactions.isolation (see [pgexec.ParseIsolation]) +// and transactions.max_retries. func ValidateTX(t TX) []string { var errs []string - switch t.Isolation { - case "read_committed", "repeatable_read", "serializable": - default: - errs = append(errs, fmt.Sprintf("transactions.isolation: %q invalid", t.Isolation)) + if _, err := pgexec.ParseIsolation(t.Isolation); err != nil { + errs = append(errs, "transactions.isolation: "+err.Error()) } if t.MaxRetries < 0 { errs = append(errs, "transactions.max_retries must be >= 0") @@ -144,7 +143,7 @@ func ValidateWatch(w Watch, cachePath string) []string { if w.Enabled && cachePath != "" { errs = append(errs, "watch.enabled cannot be combined with schema.cache_path") } - if w.Enabled && !ValidChannelName(w.Channel) { + if w.Enabled && !validChannelName(w.Channel) { errs = append(errs, fmt.Sprintf("watch.channel: %q invalid: only letters, digits and underscores are allowed", w.Channel)) } if w.Enabled && len(w.Channel) > 63 { @@ -196,10 +195,8 @@ func ValidateContracts(cs []Contract, base string, rootShared bool) []string { errs = append(errs, fmt.Sprintf("%s.name: %q is used by another contract", key, c.Name)) } names[c.Name] = true - switch contract.Policy(c.Default) { - case "", contract.Include, contract.Exclude: - default: - errs = append(errs, fmt.Sprintf("%s.default: %q is not 'include' or 'exclude'", key, c.Default)) + if _, err := contract.ParsePolicy(string(c.Default)); err != nil { + errs = append(errs, fmt.Sprintf("%s.default: %v", key, err)) } p := c.URLPath(base) if !validContractPath(p) { @@ -335,10 +332,10 @@ func validHeaderPrefix(p string) bool { return true } -// ValidChannelName restricts the watch NOTIFY channel to [a-zA-Z0-9_]; the +// validChannelName restricts the watch NOTIFY channel to [a-zA-Z0-9_]; the // value is interpolated into trigger DDL (see package watch) where broader // characters cannot be safely escaped. -func ValidChannelName(s string) bool { +func validChannelName(s string) bool { for _, r := range s { ok := r == '_' || (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') if !ok { @@ -393,7 +390,7 @@ func AuthConfig(a Auth, r Roles) (auth.Config, error) { SkipRoleSwitch: !r.Switch, } for _, p := range a.Headers.TrustedProxies { - if pfx, err := ParseTrustedProxy(p); err == nil { + if pfx, err := parseTrustedProxy(p); err == nil { cfg.TrustedProxies = append(cfg.TrustedProxies, pfx) } } diff --git a/contract/contract.go b/contract/contract.go index 94c8d30..2a6bcc7 100644 --- a/contract/contract.go +++ b/contract/contract.go @@ -7,7 +7,7 @@ // COMMENT ON COLUMN app.users.email IS '@behavior -contract:public'; // COMMENT ON FUNCTION app.search(text) IS '@behavior +contract:partner'; // -// A contract only ever removes surface. [Contract.Apply] drops the tables, +// A contract only ever removes surface. [Contract.View] drops the tables, // functions and foreign keys the contract hides from the catalog and marks // hidden columns with a bare @omit, so the products' own @omit handling // (which already covers every surface a column reaches: output, filters, @@ -33,7 +33,7 @@ package contract import ( - "context" + "fmt" "strings" "github.com/suprbdev/pdbcore/introspect" @@ -54,6 +54,19 @@ const ( Exclude Policy = "exclude" ) +// ParsePolicy maps the config spelling of a policy ("include", "exclude", +// or "" for [Include]) to its Policy. Any other value is an error naming +// the accepted ones. +func ParsePolicy(s string) (Policy, error) { + switch Policy(s) { + case "", Include: + return Include, nil + case Exclude: + return Exclude, nil + } + return "", fmt.Errorf("%q is not 'include' or 'exclude'", s) +} + // Contract is one named view of the catalog. type Contract struct { // Name is matched case-insensitively against the names in @contract @@ -64,35 +77,31 @@ type Contract struct { Default Policy } -// Summary counts what [Contract.Apply] hid. +// Summary counts what [Contract.View] hid. type Summary struct { Tables, Columns, Functions, ForeignKeys int } -// View returns a deep copy of c with the contract applied; c is not -// modified. -func (ct Contract) View(c *introspect.Catalog) (*introspect.Catalog, Summary) { +// View returns a deep copy of c without everything the contract hides +// (see the package documentation), and what it hid; c is not modified. +// Columns are not removed, since keys, indexes and foreign keys keep +// naming them: a hidden column's comment gets a leading bare @omit tag +// line instead. A Default other than "", [Include] or [Exclude] is an +// error. +func (ct Contract) View(c *introspect.Catalog) (*introspect.Catalog, Summary, error) { + policy, err := ParsePolicy(string(ct.Default)) + if err != nil { + return nil, Summary{}, fmt.Errorf("contract %s: default: %w", ct.Name, err) + } cp := c.Clone() - return cp, ct.Apply(cp) -} - -// TransformCatalog applies the contract; it makes a Contract a -// plugin.CatalogHook. Products apply contracts before the plugin catalog -// hooks rather than registering them, so plugins.disabled cannot turn a -// contract off. -func (ct Contract) TransformCatalog(_ context.Context, c *introspect.Catalog) error { - ct.Apply(c) - return nil + return cp, apply(cp, strings.ToLower(ct.Name), policy == Include), nil } -// Apply removes from c, in place, everything the contract hides (see the -// package documentation) and reindexes c. Columns are not removed, since -// keys, indexes and foreign keys keep naming them: a hidden column's -// comment gets a leading bare @omit tag line instead. -func (ct Contract) Apply(c *introspect.Catalog) Summary { +// apply removes from c, in place, everything contract name hides, given +// def, whether untagged tables and functions are in the contract, and +// reindexes c. +func apply(c *introspect.Catalog, name string, def bool) Summary { var sum Summary - name := strings.ToLower(ct.Name) - def := ct.Default != Exclude in := func(comment string, def bool) bool { if !strings.Contains(comment, "@") { return def @@ -140,7 +149,7 @@ func (ct Contract) Apply(c *introspect.Catalog) Summary { for _, t := range c.Tables { for _, col := range t.Columns { if !in(col.Comment, true) || rowOfHidden(col.TypeSchema, col.PGType) { - col.Comment = OmitAll(col.Comment) + col.Comment = omitAll(col.Comment) sum.Columns++ } } @@ -186,10 +195,10 @@ func functionUsesHidden(f *introspect.Function, rowOfHidden func(schema, typ str return false } -// OmitAll returns comment with a bare @omit tag line in front: the object +// omitAll returns comment with a bare @omit tag line in front: the object // is hidden from every surface, and its other tags and description stay // as they were. -func OmitAll(comment string) string { +func omitAll(comment string) string { if comment == "" { return "@omit" } diff --git a/contract/contract_test.go b/contract/contract_test.go index 06adcf4..3a18777 100644 --- a/contract/contract_test.go +++ b/contract/contract_test.go @@ -1,20 +1,16 @@ package contract_test import ( - "context" "slices" "strings" "testing" "github.com/suprbdev/pdbcore/contract" "github.com/suprbdev/pdbcore/introspect" - "github.com/suprbdev/pdbcore/plugin" "github.com/suprbdev/pdbcore/smarttags" "github.com/suprbdev/pdbcore/testutil" ) -var _ plugin.CatalogHook = contract.Contract{} - func col(name, comment string) *introspect.Column { return &introspect.Column{Name: name, PGType: "text", TypeSchema: "pg_catalog", Comment: comment} } @@ -94,7 +90,7 @@ func eq(t *testing.T, what string, got, want []string) { func TestApplyIncludePolicy(t *testing.T) { orig := catalog() - view, sum := contract.Contract{Name: "public"}.View(orig) + view, sum := mustView(t, contract.Contract{Name: "public"}, orig) eq(t, "tables", tableNames(view), []string{"users", "posts", "events", "events_2026", "events_2026_q1"}) eq(t, "users omitted columns", omitted(view, "users"), []string{"email", "notes", "secret_row", "secret_rows"}) @@ -115,7 +111,7 @@ func TestApplyIncludePolicy(t *testing.T) { } func TestApplyExcludePolicy(t *testing.T) { - view, _ := contract.Contract{Name: "PARTNER", Default: contract.Exclude}.View(catalog()) + view, _ := mustView(t, contract.Contract{Name: "PARTNER", Default: contract.Exclude}, catalog()) eq(t, "tables", tableNames(view), []string{"posts"}) eq(t, "posts foreign keys", fkNames(view, "posts"), nil) @@ -124,7 +120,7 @@ func TestApplyExcludePolicy(t *testing.T) { } func TestApplyInternal(t *testing.T) { - view, sum := contract.Contract{Name: "internal", Default: contract.Include}.View(catalog()) + view, sum := mustView(t, contract.Contract{Name: "internal", Default: contract.Include}, catalog()) eq(t, "tables", tableNames(view), []string{"users", "posts", "secrets", "events", "events_2026", "events_2026_q1"}) eq(t, "users omitted columns", omitted(view, "users"), nil) @@ -137,40 +133,37 @@ func TestApplyInternal(t *testing.T) { func TestPartitionsFollowTheirParent(t *testing.T) { c := catalog() c.Table("app", "events").Comment = "@behavior -contract:public" - view, _ := contract.Contract{Name: "public"}.View(c) + view, _ := mustView(t, contract.Contract{Name: "public"}, c) eq(t, "tables", tableNames(view), []string{"users", "posts"}) c = catalog() c.Table("app", "events").Comment = "@behavior +contract:partner" c.Table("app", "events_2026_q1").Comment = "@behavior -contract:partner" - view, _ = contract.Contract{Name: "partner", Default: contract.Exclude}.View(c) + view, _ = mustView(t, contract.Contract{Name: "partner", Default: contract.Exclude}, c) eq(t, "tables", tableNames(view), []string{"posts", "events", "events_2026"}) c = catalog() c.Table("app", "events").PartitionOf = "app.events_2026_q1" - view, _ = contract.Contract{Name: "public"}.View(c) + view, _ = mustView(t, contract.Contract{Name: "public"}, c) eq(t, "tables (partition cycle)", tableNames(view), []string{"users", "posts"}) } -func TestTransformCatalog(t *testing.T) { - c := catalog() - if err := (contract.Contract{Name: "public"}).TransformCatalog(context.Background(), c); err != nil { - t.Fatal(err) - } - if c.Table("app", "secrets") != nil { - t.Error("TransformCatalog left the hidden table") +func TestViewRejectsUnknownPolicy(t *testing.T) { + _, _, err := contract.Contract{Name: "public", Default: "exlude"}.View(catalog()) + if err == nil || !strings.Contains(err.Error(), `"exlude" is not 'include' or 'exclude'`) { + t.Fatalf("err = %v", err) } } -func TestOmitAll(t *testing.T) { - for _, comment := range []string{"", "A description.", "@name people\nPeople.", "@omit read"} { - tags, desc := smarttags.Parse(contract.OmitAll(comment)) - if _, all := tags.Omits(); !all { - t.Errorf("OmitAll(%q) does not omit everything", comment) +func TestParsePolicy(t *testing.T) { + for in, want := range map[string]contract.Policy{"": contract.Include, "include": contract.Include, "exclude": contract.Exclude} { + if got, err := contract.ParsePolicy(in); err != nil || got != want { + t.Errorf("ParsePolicy(%q) = %q, %v, want %q", in, got, err, want) } - _, wantDesc := smarttags.Parse(comment) - if desc != wantDesc { - t.Errorf("OmitAll(%q) description = %q, want %q", comment, desc, wantDesc) + } + for _, in := range []string{"Include", "none", " exclude"} { + if _, err := contract.ParsePolicy(in); err == nil { + t.Errorf("ParsePolicy(%q) accepted", in) } } } @@ -198,7 +191,7 @@ func TestApplyOnlyRemoves(t *testing.T) { f.Comment = next() } for _, ct := range []contract.Contract{{Name: "a"}, {Name: "b", Default: contract.Exclude}, {Name: "c"}} { - view, _ := ct.View(c) + view, _ := mustView(t, ct, c) for _, vt := range view.Tables { ot := c.Table(vt.Schema, vt.Name) if ot == nil { @@ -208,7 +201,7 @@ func TestApplyOnlyRemoves(t *testing.T) { t.Fatalf("%s: %s columns changed", ct.Name, vt.Name) } for k, vc := range vt.Columns { - if oc := ot.Columns[k]; vc.Name != oc.Name || (vc.Comment != oc.Comment && vc.Comment != contract.OmitAll(oc.Comment)) { + if oc := ot.Columns[k]; vc.Name != oc.Name || (vc.Comment != oc.Comment && vc.Comment != omittedComment(oc.Comment)) { t.Fatalf("%s: %s.%s comment %q from %q", ct.Name, vt.Name, vc.Name, vc.Comment, oc.Comment) } } @@ -247,7 +240,7 @@ func TestCloneOfFixtureHashesTheSame(t *testing.T) { if got != want { t.Fatalf("clone hash %s, want %s", got, want) } - view, _ := contract.Contract{Name: "nobody", Default: contract.Exclude}.View(c) + view, _ := mustView(t, contract.Contract{Name: "nobody", Default: contract.Exclude}, c) if len(view.Tables) != 0 || len(view.Functions) != 0 { t.Fatalf("exclude-all view kept %d tables, %d functions", len(view.Tables), len(view.Functions)) } @@ -255,3 +248,19 @@ func TestCloneOfFixtureHashesTheSame(t *testing.T) { t.Fatal("View changed its input") } } + +func mustView(t *testing.T, ct contract.Contract, c *introspect.Catalog) (*introspect.Catalog, contract.Summary) { + t.Helper() + view, sum, err := ct.View(c) + if err != nil { + t.Fatal(err) + } + return view, sum +} + +func omittedComment(comment string) string { + if comment == "" { + return "@omit" + } + return "@omit\n" + comment +} diff --git a/contract/omit_test.go b/contract/omit_test.go new file mode 100644 index 0000000..3309f9f --- /dev/null +++ b/contract/omit_test.go @@ -0,0 +1,20 @@ +package contract + +import ( + "testing" + + "github.com/suprbdev/pdbcore/smarttags" +) + +func TestOmitAll(t *testing.T) { + for _, comment := range []string{"", "A description.", "@name people\nPeople.", "@omit read"} { + tags, desc := smarttags.Parse(omitAll(comment)) + if _, all := tags.Omits(); !all { + t.Errorf("omitAll(%q) does not omit everything", comment) + } + _, wantDesc := smarttags.Parse(comment) + if desc != wantDesc { + t.Errorf("omitAll(%q) description = %q, want %q", comment, desc, wantDesc) + } + } +} diff --git a/contrib/contrib_test.go b/contrib/contrib_test.go index 849f53c..dc9fbb5 100644 --- a/contrib/contrib_test.go +++ b/contrib/contrib_test.go @@ -120,7 +120,7 @@ func allVocabularies(t *testing.T) []contrib.Vocabulary { m(contrib.Inet("inet")), m(contrib.Inet("cidr")), contrib.Unaccent("varchar"), contrib.Fuzzy("bpchar"), contrib.Intarray(), } - for _, typ := range contrib.VectorTypes { + for _, typ := range contrib.VectorTypes() { vs = append(vs, m(contrib.Vector(typ))) } vs = append(vs, m(contrib.Bit("bit")), m(contrib.Bit("varbit"))) diff --git a/contrib/vector.go b/contrib/vector.go index bd5b7ef..5e49ffc 100644 --- a/contrib/vector.go +++ b/contrib/vector.go @@ -4,6 +4,7 @@ import ( "encoding/json" "fmt" "math" + "slices" "strconv" "strings" ) @@ -13,8 +14,11 @@ import ( // the non-zero elements of a sparsevec. const MaxVectorDims = 16000 -// VectorTypes lists the pgvector column types the vector vocabulary covers. -var VectorTypes = []string{"vector", "halfvec", "sparsevec"} +// VectorTypes returns the pgvector column types the vector vocabulary +// covers. The slice is a fresh copy. +func VectorTypes() []string { return slices.Clone(vectorTypes) } + +var vectorTypes = []string{"vector", "halfvec", "sparsevec"} // IsVector reports whether a pg type name (as Column.PGType spells it) is // one of [VectorTypes], ignoring a schema qualifier; arrays are not. @@ -23,7 +27,7 @@ func IsVector(pgType string) bool { if arr { return false } - for _, t := range VectorTypes { + for _, t := range vectorTypes { if base == t { return true } diff --git a/docs/upgrading.md b/docs/upgrading.md index 0434269..c5332ce 100644 --- a/docs/upgrading.md +++ b/docs/upgrading.md @@ -113,3 +113,49 @@ Go API changes: `CORSPolicy{Origins, AllowMethods, ExposeHeaders}`; CORS and gzip add to `Vary` instead of replacing it. - The test fixture's policies read `jwt.claims.user_id`. + +### API hygiene + +- **`confx.Load(envPrefix, path, dst, opts...)`** no longer takes a pflag + set. Pass command-line values with `confx.WithFlags(values)` (koanf path + to value); `confx/cliflags.Changed(fs, except...)` builds that map from + the flags set on a pflag set and replaces `confx.ChangedFlags`. +- **`confx.WithRemoved(map[old]reason)`** names keys removed without a + replacement: `unknown key transactions.mutations: removed: `. + `confx.MovedKeys`, `ParseTrustedProxy` and `ValidChannelName` are no + longer exported; `TX.Mutations` is gone (no product read it). +- **Neutral doc tags.** The `schema.cache_path`, `auth.headers.prefix` and + `errors.detail` docs no longer name a product; products that want their + own wording pass `confx.WithDoc`. +- **One error-message API.** `pgexec.SanitizeMessage(pgErr, strict)` is + gone: `pgexec.Classify(err, detail).Message` renders the same text + (`Prod` for `strict=false`, `Strict` for `strict=true`). +- **Rejecting parsers.** `pgexec.ParseIsolation` returns + `(pgx.TxIsoLevel, error)` and `pgexec.ParseDetail` returns + `(Detail, error)`; neither falls back to a default any more (`Detail` + gains `String`). `confx.ValidateTX` reports + `transactions.isolation: "x" is not 'read_committed', 'repeatable_read' or 'serializable'`. + `contract.ParsePolicy` accepts `""`, `include` and `exclude`; + `confx.Contract.Default` is a `contract.Policy`, and `Contract.View` + returns `(*Catalog, Summary, error)`, failing on an unknown policy. + `Contract.Apply`, `OmitAll` and the `CatalogHook` method + `TransformCatalog` are gone: use `View`. +- **`postgis` output.** `OutputSQL(ref, Output{JSON, Precision})` replaces + `OutputSQL`, `OutputJSONSQL`, `OutputPrecisionSQL` and + `OutputJSONPrecisionSQL`; `Derived.SQL(ref, f, Output)` replaces + `SQL`, `JSONSQL`, `PrecisionSQL` and `JSONPrecisionSQL`; + `RasterAccessor.SQL(ref, Output)` replaces `SQL` and `JSONSQL`. +- **Accessors instead of mutable variables.** `postgis.Ops()`, + `postgis.Deriveds()`, `postgis.RasterAccessors()` and + `contrib.VectorTypes()` return fresh copies. +- **Renamed fields.** `postgis.Op.Index` is `Indexable` and `postgis.Op.Arg` + is `OperandType`, so they no longer clash with `contrib.Op.Index` + (`[]IndexHint`) and `contrib.Op.Arg` (`ArgKind`). +- **Pruned exports.** `jwtmint.Sign`, `postgis.OpsDoc`, `postgis.OpNames` + and `postgis.DerivedSuffixes` are gone. +- **`watch.New(watch.Config{...}) (*Watcher, error)`** replaces the + `Watcher` struct literal. It validates the channel and trigger names + (and requires `Pool` and `OnChange`) up front, fills in the defaults + without `Run` writing back into the configuration, and `OnChange` is + `func(ctx context.Context, cat *introspect.Catalog)` with `Run`'s + context. diff --git a/go.mod b/go.mod index 276eca5..a8f3532 100644 --- a/go.mod +++ b/go.mod @@ -9,7 +9,6 @@ require ( github.com/knadh/koanf/parsers/yaml v1.1.0 github.com/knadh/koanf/providers/env v1.1.0 github.com/knadh/koanf/providers/file v1.2.1 - github.com/knadh/koanf/providers/posflag v1.0.1 github.com/knadh/koanf/v2 v2.3.5 github.com/prometheus/client_golang v1.25.0 github.com/spf13/pflag v1.0.10 diff --git a/go.sum b/go.sum index 298f42b..11ed831 100644 --- a/go.sum +++ b/go.sum @@ -29,8 +29,6 @@ github.com/knadh/koanf/providers/env v1.1.0 h1:U2VXPY0f+CsNDkvdsG8GcsnK4ah85WwWy github.com/knadh/koanf/providers/env v1.1.0/go.mod h1:QhHHHZ87h9JxJAn2czdEl6pdkNnDh/JS1Vtsyt65hTY= github.com/knadh/koanf/providers/file v1.2.1 h1:bEWbtQwYrA+W2DtdBrQWyXqJaJSG3KrP3AESOJYp9wM= github.com/knadh/koanf/providers/file v1.2.1/go.mod h1:bp1PM5f83Q+TOUu10J/0ApLBd9uIzg+n9UgthfY+nRA= -github.com/knadh/koanf/providers/posflag v1.0.1 h1:EnMxHSrPkYCFnKgBUl5KBgrjed8gVFrcXDzaW4l/C6Y= -github.com/knadh/koanf/providers/posflag v1.0.1/go.mod h1:3Wn3+YG3f4ljzRyCUgIwH7G0sZ1pMjCOsNBovrbKmAk= github.com/knadh/koanf/v2 v2.3.5 h1:2dXJUYaKGm4SGYeoAtBviq9+02JZo/pxQ2ssOd60rJg= github.com/knadh/koanf/v2 v2.3.5/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= diff --git a/jwtmint/mint.go b/jwtmint/mint.go index fcdb1fa..f02c5ca 100644 --- a/jwtmint/mint.go +++ b/jwtmint/mint.go @@ -56,16 +56,16 @@ func Mint(o Options, raw json.RawMessage, set bool) (json.RawMessage, error) { if claims == nil { return json.RawMessage("null"), nil } - token, err := Sign(o, claims) + token, err := sign(o, claims) if err != nil { return raw, fmt.Errorf("mint: sign: %w", err) } return json.Marshal(token) } -// Sign builds the HS256 token for one claims map: nil-valued claims are +// sign builds the HS256 token for one claims map: nil-valued claims are // dropped and Issuer/Audience are added when set. -func Sign(o Options, claims map[string]any) (string, error) { +func sign(o Options, claims map[string]any) (string, error) { mc := jwt.MapClaims{} for k, v := range claims { if v != nil { diff --git a/pgexec/classify.go b/pgexec/classify.go index 9a7bea6..d4e4919 100644 --- a/pgexec/classify.go +++ b/pgexec/classify.go @@ -3,6 +3,7 @@ package pgexec import ( "context" "errors" + "fmt" "strings" "github.com/jackc/pgx/v5/pgconn" @@ -67,16 +68,29 @@ const ( Strict ) -// ParseDetail maps the config strings "dev", "prod", "strict"; anything else -// is Prod. -func ParseDetail(s string) Detail { +// ParseDetail maps the config strings "dev", "prod" and "strict" to their +// Detail. Any other value is an error naming the accepted ones. +func ParseDetail(s string) (Detail, error) { switch s { + case "prod": + return Prod, nil case "dev": - return Dev + return Dev, nil case "strict": - return Strict + return Strict, nil } - return Prod + return Prod, fmt.Errorf("%q is not 'dev', 'prod' or 'strict'", s) +} + +// String returns the config spelling of d: "prod", "dev" or "strict". +func (d Detail) String() string { + switch d { + case Dev: + return "dev" + case Strict: + return "strict" + } + return "prod" } // Classified is the result of Classify. @@ -105,7 +119,7 @@ func Classify(err error, detail Detail) Classified { if detail == Dev { c.Message = pgErr.Message } else { - c.Message = SanitizeMessage(pgErr, detail == Strict) + c.Message = sanitizeMessage(pgErr, detail == Strict) } return c } @@ -205,11 +219,11 @@ func classOf(code string) Class { return Internal } -// SanitizeMessage keeps actionable constraint-class errors and hides the +// sanitizeMessage keeps actionable constraint-class errors and hides the // rest behind a generic message. strict hides those too: PG constraint // messages embed constraint/table/column names, which strict mode treats as // sensitive. -func SanitizeMessage(pgErr *pgconn.PgError, strict bool) string { +func sanitizeMessage(pgErr *pgconn.PgError, strict bool) string { if isPostGISInputError(pgErr) { if strict { return "invalid input value" diff --git a/pgexec/classify_test.go b/pgexec/classify_test.go index 5aa9ea9..3c19852 100644 --- a/pgexec/classify_test.go +++ b/pgexec/classify_test.go @@ -3,6 +3,7 @@ package pgexec import ( "context" "errors" + "strings" "testing" "github.com/jackc/pgx/v5/pgconn" @@ -77,8 +78,7 @@ func TestClassifyMessagePolicy(t *testing.T) { } } -// SanitizeMessage must stay byte-identical to pdbq's sanitizePGMessage. -func TestSanitizeMessageMatchesPdbq(t *testing.T) { +func TestClassifyMessages(t *testing.T) { cases := []struct { code, msg string strict bool @@ -94,8 +94,12 @@ func TestSanitizeMessageMatchesPdbq(t *testing.T) { {"P0001", "raise", true, "database error"}, } for _, tc := range cases { - if got := SanitizeMessage(pgErr(tc.code, tc.msg), tc.strict); got != tc.want { - t.Errorf("SanitizeMessage(%s, strict=%v) = %q, want %q", tc.code, tc.strict, got, tc.want) + detail := Prod + if tc.strict { + detail = Strict + } + if got := Classify(pgErr(tc.code, tc.msg), detail).Message; got != tc.want { + t.Errorf("Classify(%s, %v).Message = %q, want %q", tc.code, detail, got, tc.want) } } } @@ -124,9 +128,18 @@ func TestClassifyNonPG(t *testing.T) { } func TestParseDetail(t *testing.T) { - for in, want := range map[string]Detail{"dev": Dev, "prod": Prod, "strict": Strict, "": Prod, "x": Prod} { - if got := ParseDetail(in); got != want { - t.Errorf("ParseDetail(%q) = %v, want %v", in, got, want) + for in, want := range map[string]Detail{"dev": Dev, "prod": Prod, "strict": Strict} { + got, err := ParseDetail(in) + if err != nil || got != want { + t.Errorf("ParseDetail(%q) = %v, %v, want %v", in, got, err, want) + } + if got.String() != in { + t.Errorf("%v.String() = %q, want %q", got, got.String(), in) + } + } + for _, in := range []string{"", "x", "Dev"} { + if _, err := ParseDetail(in); err == nil || !strings.Contains(err.Error(), "is not 'dev', 'prod' or 'strict'") { + t.Errorf("ParseDetail(%q) error = %v", in, err) } } } diff --git a/pgexec/tx.go b/pgexec/tx.go index 3e68db1..7423ab9 100644 --- a/pgexec/tx.go +++ b/pgexec/tx.go @@ -219,14 +219,16 @@ func IsSerializationFailure(err error) bool { } // ParseIsolation maps the config spelling ("read_committed", -// "repeatable_read", "serializable") to pgx's level; anything else is -// ReadCommitted. -func ParseIsolation(s string) pgx.TxIsoLevel { +// "repeatable_read", "serializable") to pgx's level. Any other value is an +// error naming the accepted ones. +func ParseIsolation(s string) (pgx.TxIsoLevel, error) { switch s { + case "read_committed": + return pgx.ReadCommitted, nil case "repeatable_read": - return pgx.RepeatableRead + return pgx.RepeatableRead, nil case "serializable": - return pgx.Serializable + return pgx.Serializable, nil } - return pgx.ReadCommitted + return "", fmt.Errorf("%q is not 'read_committed', 'repeatable_read' or 'serializable'", s) } diff --git a/pgexec/tx_test.go b/pgexec/tx_test.go index bee9bc0..0d06c58 100644 --- a/pgexec/tx_test.go +++ b/pgexec/tx_test.go @@ -317,11 +317,16 @@ func TestIsSerializationFailure(t *testing.T) { func TestParseIsolation(t *testing.T) { cases := map[string]pgx.TxIsoLevel{ "read_committed": pgx.ReadCommitted, "repeatable_read": pgx.RepeatableRead, - "serializable": pgx.Serializable, "": pgx.ReadCommitted, "chaos": pgx.ReadCommitted, + "serializable": pgx.Serializable, } for in, want := range cases { - if got := ParseIsolation(in); got != want { - t.Errorf("ParseIsolation(%q) = %v, want %v", in, got, want) + if got, err := ParseIsolation(in); err != nil || got != want { + t.Errorf("ParseIsolation(%q) = %v, %v, want %v", in, got, err, want) + } + } + for _, in := range []string{"", "chaos", "SERIALIZABLE"} { + if _, err := ParseIsolation(in); err == nil { + t.Errorf("ParseIsolation(%q) accepted", in) } } } diff --git a/postgis/e2e_raster_test.go b/postgis/e2e_raster_test.go index 06a22cf..8f6b1c6 100644 --- a/postgis/e2e_raster_test.go +++ b/postgis/e2e_raster_test.go @@ -65,8 +65,8 @@ func rasterTx(t *testing.T) (pgx.Tx, context.Context) { func TestRasterAccessorsLive(t *testing.T) { tx, ctx := rasterTx(t) var cols []string - for _, a := range postgis.RasterAccessors { - cols = append(cols, "'"+a.Suffix+"', "+a.JSONSQL("r.rast")) + for _, a := range postgis.RasterAccessors() { + cols = append(cols, "'"+a.Suffix+"', "+a.SQL("r.rast", postgis.Output{JSON: true})) } var out []map[string]any if err := tx.QueryRow(ctx, "SELECT json_agg(json_build_object("+strings.Join(cols, ", ")+") ORDER BY id) FROM rasters AS r").Scan(&out); err != nil { diff --git a/postgis/e2e_test.go b/postgis/e2e_test.go index 22e3086..fe80e06 100644 --- a/postgis/e2e_test.go +++ b/postgis/e2e_test.go @@ -78,8 +78,8 @@ func TestDerivedsExecute(t *testing.T) { if f == postgis.Geography && !s.geography { continue } - for _, d := range postgis.Deriveds { - q := "SELECT " + d.SQL("t.g", f) + " FROM (SELECT " + column(f) + " AS g) AS t" + for _, d := range postgis.Deriveds() { + q := "SELECT " + d.SQL("t.g", f, postgis.Output{}) + " FROM (SELECT " + column(f) + " AS g) AS t" var got any if err := conn.QueryRow(ctx, q, s.wkt).Scan(&got); err != nil { t.Errorf("%s %s on %s: %v\n%s", f, d.Suffix, s.wkt, err, q) @@ -135,7 +135,7 @@ func TestDerivedValues(t *testing.T) { if !ok { t.Fatalf("derived %q not found", tc.suffix) } - q := "SELECT " + d.SQL("t.g", f) + " FROM (SELECT " + column(f) + " AS g) AS t" + q := "SELECT " + d.SQL("t.g", f, postgis.Output{}) + " FROM (SELECT " + column(f) + " AS g) AS t" var got any if err := conn.QueryRow(ctx, q, tc.wkt).Scan(&got); err != nil { t.Errorf("%s %s on %s: %v", f, tc.suffix, tc.wkt, err) @@ -156,7 +156,7 @@ func TestGeographyMeasures(t *testing.T) { const square = "POLYGON((-0.130 51.507,-0.126 51.507,-0.126 51.509,-0.130 51.509,-0.130 51.507))" for suffix, want := range map[string][2]float64{"Perimeter": {990, 1010}, "Length": {0, 0}, "Area": {61000, 62500}} { d, _ := postgis.DerivedBySuffix(suffix) - q := "SELECT " + d.SQL("t.g", postgis.Geography) + " FROM (SELECT " + column(postgis.Geography) + " AS g) AS t" + q := "SELECT " + d.SQL("t.g", postgis.Geography, postgis.Output{}) + " FROM (SELECT " + column(postgis.Geography) + " AS g) AS t" var got float64 if err := conn.QueryRow(ctx, q, square).Scan(&got); err != nil { t.Fatalf("%s: %v", suffix, err) @@ -166,7 +166,7 @@ func TestGeographyMeasures(t *testing.T) { } } d, _ := postgis.DerivedBySuffix("Centroid") - q := "SELECT ST_AsText(ST_GeomFromGeoJSON(" + d.SQL("t.g", postgis.Geography) + "::text)) FROM (SELECT " + column(postgis.Geography) + " AS g) AS t" + q := "SELECT ST_AsText(ST_GeomFromGeoJSON(" + d.SQL("t.g", postgis.Geography, postgis.Output{}) + "::text)) FROM (SELECT " + column(postgis.Geography) + " AS g) AS t" for _, wkt := range []string{square, "GEOMETRYCOLLECTION(POINT(0 0),POINT(2 0))"} { var got string if err := conn.QueryRow(ctx, q, wkt).Scan(&got); err != nil { @@ -216,7 +216,7 @@ func TestOpsExecute(t *testing.T) { "coordinates": []any{[]any{[]any{0.0, 0.0}, []any{3.0, 0.0}, []any{3.0, 3.0}, []any{0.0, 0.0}}}, } for _, f := range []postgis.Flavour{postgis.Geometry, postgis.Geography} { - for _, op := range postgis.Ops { + for _, op := range postgis.Ops() { if op.Kind() == postgis.ArgBoolean { continue } @@ -377,13 +377,13 @@ func TestJSONOutputMatchesJSONB(t *testing.T) { if f == postgis.Geography && !s.geography { continue } - for _, d := range postgis.Deriveds { + for _, d := range postgis.Deriveds() { from := " FROM (SELECT " + column(f) + " AS g) AS t" var a, b any - if err := conn.QueryRow(ctx, "SELECT "+d.SQL("t.g", f)+from, s.wkt).Scan(&a); err != nil { + if err := conn.QueryRow(ctx, "SELECT "+d.SQL("t.g", f, postgis.Output{})+from, s.wkt).Scan(&a); err != nil { t.Fatalf("%s %s on %s: %v", f, d.Suffix, s.wkt, err) } - if err := conn.QueryRow(ctx, "SELECT "+d.JSONSQL("t.g", f)+from, s.wkt).Scan(&b); err != nil { + if err := conn.QueryRow(ctx, "SELECT "+d.SQL("t.g", f, postgis.Output{JSON: true})+from, s.wkt).Scan(&b); err != nil { t.Fatalf("%s %s json on %s: %v", f, d.Suffix, s.wkt, err) } if fmt.Sprint(a) != fmt.Sprint(b) { @@ -393,7 +393,7 @@ func TestJSONOutputMatchesJSONB(t *testing.T) { } } var got any - if err := conn.QueryRow(ctx, "SELECT "+postgis.OutputJSONSQL("NULL::geometry")).Scan(&got); err != nil || got != nil { + if err := conn.QueryRow(ctx, "SELECT "+postgis.OutputSQL("NULL::geometry", postgis.Output{JSON: true})).Scan(&got); err != nil || got != nil { t.Errorf("NULL geometry = %v, %v; want NULL", got, err) } } @@ -441,7 +441,7 @@ func TestPrecisionAndBufferLive(t *testing.T) { {6, "[-0.128123,51.508123]"}, } { var got string - q := "SELECT (" + postgis.OutputJSONPrecisionSQL(column(f), "$2") + "->'coordinates')::text" + q := "SELECT (" + postgis.OutputSQL(column(f), postgis.Output{JSON: true, Precision: "$2"}) + "->'coordinates')::text" if err := conn.QueryRow(ctx, q, pt, tc.digits).Scan(&got); err != nil { t.Fatalf("%s precision %d: %v\n%s", f, tc.digits, err, q) } @@ -449,7 +449,7 @@ func TestPrecisionAndBufferLive(t *testing.T) { t.Errorf("%s precision %d = %s, want %s", f, tc.digits, got, tc.want) } var jb string - q = "SELECT (" + postgis.OutputPrecisionSQL(column(f), "$2") + "->'coordinates')::text" + q = "SELECT (" + postgis.OutputSQL(column(f), postgis.Output{Precision: "$2"}) + "->'coordinates')::text" if err := conn.QueryRow(ctx, q, pt, tc.digits).Scan(&jb); err != nil { t.Fatalf("%s jsonb precision %d: %v", f, tc.digits, err) } diff --git a/postgis/ops.go b/postgis/ops.go index 1dcb0e0..abbdc11 100644 --- a/postgis/ops.go +++ b/postgis/ops.go @@ -3,27 +3,30 @@ package postgis import ( "fmt" "math" + "slices" "strings" ) -// Op describes one spatial filter operator: its field name (as exposed by -// pdbq's GeometryFilterOps; pdbr maps it to its own grammar), the input shape -// it takes, and how it renders as SQL. +// Op describes one spatial filter operator: its name (products expose it +// under their own grammar), the input shape it takes, and how it renders +// as SQL. type Op struct { - // Name is the operator's field name (pdbq: inside GeometryFilterOps). + // Name is the operator's name, e.g. intersects or dwithin. Name string - // Arg is the operand type name (pdbq SDL spelling). - Arg string + // OperandType names the operand's type: [TypeName] for a geometry, + // "BBoxInput" for an envelope, "DWithinInput" for a geometry and + // distance, "Boolean" for isNull. [Op.Kind] classifies the same shape. + OperandType string // Description documents the operator in the generated schema. Description string - // Index reports whether the operator can use a GiST index directly. + // Indexable reports whether the operator can use a GiST index directly. // Index-usable operators are documented as such so users can tell the // cheap ones from the exact-but-expensive ones. For an operator without // a geography overload the flag describes geometry columns only: a // geography column is cast to geometry, which a GiST index on the // geography column cannot serve (an expression index on col::geometry // can). - Index bool + Indexable bool // Geography reports whether PostGIS provides a geography overload. The // others (ST_Within, ST_Contains, ~, @, ...) exist for geometry only, so // a compiler must cast a geography column and its operand to geometry @@ -76,8 +79,7 @@ func fn(name string) func(string, string, []string) string { } } -// Ops is the spatial operator vocabulary exposed on every geometry and -// geography column. +// ops is the spatial operator vocabulary returned by [Ops]. // // Ordering matters only for schema readability: the index-usable bounding-box // operators come first because they are the ones that stay fast on large @@ -92,171 +94,178 @@ func fn(name string) func(string, string, []string) string { // bboxIntersectsND, bboxIntersects2D, ...), takes a geometry, as connection-filter-postgis does: // PostGIS compares against that geometry's bounding box, and a geometry can // carry the Z/M extent that &&& needs where an envelope cannot. -var Ops = []Op{ +var ops = []Op{ { - Name: "bboxIntersects", Arg: "BBoxInput", Index: true, Geography: true, + Name: "bboxIntersects", OperandType: "BBoxInput", Indexable: true, Geography: true, Description: "Bounding boxes overlap (&&). Index-usable; the cheap first pass for viewport queries.", render: binary("&&"), }, { - Name: "bboxContains", Arg: "BBoxInput", Index: true, + Name: "bboxContains", OperandType: "BBoxInput", Indexable: true, Description: "This column's bounding box contains the given box (~).", render: binary("~"), }, { - Name: "bboxContainedBy", Arg: "BBoxInput", Index: true, + Name: "bboxContainedBy", OperandType: "BBoxInput", Indexable: true, Description: "This column's bounding box is contained by the given box (@).", render: binary("@"), }, { - Name: "intersects", Arg: TypeName, Index: true, Geography: true, + Name: "intersects", OperandType: TypeName, Indexable: true, Geography: true, Description: "Geometries share any portion of space (ST_Intersects).", render: fn("ST_Intersects"), }, { - Name: "disjoint", Arg: TypeName, + Name: "disjoint", OperandType: TypeName, Description: "Geometries share no space (ST_Disjoint). Cannot use an index.", render: fn("ST_Disjoint"), }, { - Name: "contains", Arg: TypeName, Index: true, + Name: "contains", OperandType: TypeName, Indexable: true, Description: "This column's geometry contains the given geometry (ST_Contains).", render: fn("ST_Contains"), }, { - Name: "containsProperly", Arg: TypeName, Index: true, + Name: "containsProperly", OperandType: TypeName, Indexable: true, Description: "Contains with no boundary contact (ST_ContainsProperly).", render: fn("ST_ContainsProperly"), }, { - Name: "within", Arg: TypeName, Index: true, + Name: "within", OperandType: TypeName, Indexable: true, Description: "This column's geometry lies within the given geometry (ST_Within).", render: fn("ST_Within"), }, { - Name: "covers", Arg: TypeName, Index: true, Geography: true, + Name: "covers", OperandType: TypeName, Indexable: true, Geography: true, Description: "No point of the given geometry lies outside this column (ST_Covers).", render: fn("ST_Covers"), }, { - Name: "coveredBy", Arg: TypeName, Index: true, Geography: true, + Name: "coveredBy", OperandType: TypeName, Indexable: true, Geography: true, Description: "No point of this column lies outside the given geometry (ST_CoveredBy).", render: fn("ST_CoveredBy"), }, { - Name: "crosses", Arg: TypeName, Index: true, + Name: "crosses", OperandType: TypeName, Indexable: true, Description: "Geometries cross (ST_Crosses).", render: fn("ST_Crosses"), }, { - Name: "overlaps", Arg: TypeName, Index: true, + Name: "overlaps", OperandType: TypeName, Indexable: true, Description: "Geometries overlap at the same dimension (ST_Overlaps).", render: fn("ST_Overlaps"), }, { - Name: "touches", Arg: TypeName, Index: true, + Name: "touches", OperandType: TypeName, Indexable: true, Description: "Geometries touch at a boundary but interiors do not intersect (ST_Touches).", render: fn("ST_Touches"), }, { - Name: "equals", Arg: TypeName, Index: true, + Name: "equals", OperandType: TypeName, Indexable: true, Description: "Geometries are spatially equal, ignoring vertex order (ST_Equals).", render: fn("ST_Equals"), }, { - Name: "dwithin", Arg: "DWithinInput", Index: true, Geography: true, + Name: "dwithin", OperandType: "DWithinInput", Indexable: true, Geography: true, Description: "Within the given distance of the geometry (ST_DWithin). Distance is metres for geography, SRID units for geometry.", render: func(col, geom string, extra []string) string { return fmt.Sprintf("ST_DWithin(%s, %s, %s)", col, geom, extra[0]) }, }, { - Name: "beyond", Arg: "DWithinInput", Geography: true, + Name: "beyond", OperandType: "DWithinInput", Geography: true, Description: "Further than the given distance from the geometry (ST_DWithin negated).", render: func(col, geom string, extra []string) string { return fmt.Sprintf("NOT ST_DWithin(%s, %s, %s)", col, geom, extra[0]) }, }, { - Name: "isNull", Arg: "Boolean", + Name: "isNull", OperandType: "Boolean", Description: "Test whether the column is null.", render: nil, // handled structurally by the compiler }, { - Name: "bboxLeftOf", Arg: TypeName, Index: true, + Name: "bboxLeftOf", OperandType: TypeName, Indexable: true, Description: "This column's bounding box is strictly to the left of the given geometry's (<<).", render: binary("<<"), }, { - Name: "bboxRightOf", Arg: TypeName, Index: true, + Name: "bboxRightOf", OperandType: TypeName, Indexable: true, Description: "This column's bounding box is strictly to the right of the given geometry's (>>).", render: binary(">>"), }, { - Name: "bboxBelow", Arg: TypeName, Index: true, + Name: "bboxBelow", OperandType: TypeName, Indexable: true, Description: "This column's bounding box is strictly below the given geometry's (<<|).", render: binary("<<|"), }, { - Name: "bboxAbove", Arg: TypeName, Index: true, + Name: "bboxAbove", OperandType: TypeName, Indexable: true, Description: "This column's bounding box is strictly above the given geometry's (|>>).", render: binary("|>>"), }, { - Name: "bboxOverlapsOrLeftOf", Arg: TypeName, Index: true, + Name: "bboxOverlapsOrLeftOf", OperandType: TypeName, Indexable: true, Description: "This column's bounding box overlaps or is to the left of the given geometry's (&<).", render: binary("&<"), }, { - Name: "bboxOverlapsOrRightOf", Arg: TypeName, Index: true, + Name: "bboxOverlapsOrRightOf", OperandType: TypeName, Indexable: true, Description: "This column's bounding box overlaps or is to the right of the given geometry's (&>).", render: binary("&>"), }, { - Name: "bboxOverlapsOrBelow", Arg: TypeName, Index: true, + Name: "bboxOverlapsOrBelow", OperandType: TypeName, Indexable: true, Description: "This column's bounding box overlaps or is below the given geometry's (&<|).", render: binary("&<|"), }, { - Name: "bboxOverlapsOrAbove", Arg: TypeName, Index: true, + Name: "bboxOverlapsOrAbove", OperandType: TypeName, Indexable: true, Description: "This column's bounding box overlaps or is above the given geometry's (|&>).", render: binary("|&>"), }, { - Name: "bboxEquals", Arg: TypeName, Index: true, + Name: "bboxEquals", OperandType: TypeName, Indexable: true, Description: "This column's bounding box is the same as the given geometry's (~=).", render: binary("~="), }, { - Name: "exactlyEquals", Arg: TypeName, Geography: true, + Name: "exactlyEquals", OperandType: TypeName, Geography: true, Description: "Same coordinates in the same order and the same SRID (=). Uses a B-tree index, not a GiST one.", render: binary("="), }, { - Name: "orderingEquals", Arg: TypeName, Index: true, + Name: "orderingEquals", OperandType: TypeName, Indexable: true, Description: "Geometries are equal and their vertices are in the same order (ST_OrderingEquals).", render: fn("ST_OrderingEquals"), }, { - Name: "intersects3D", Arg: TypeName, Index: true, + Name: "intersects3D", OperandType: TypeName, Indexable: true, Description: "Geometries share any portion of 3D space (ST_3DIntersects). The default 2D GiST index prefilters on the 2D bounding box; an n-D GiST index (gist_geometry_ops_nd) also prunes on Z.", render: fn("ST_3DIntersects"), }, { - Name: "bboxIntersectsND", Arg: TypeName, Index: true, + Name: "bboxIntersectsND", OperandType: TypeName, Indexable: true, Description: "n-D bounding boxes (including Z and M) overlap (&&&). Uses an n-D GiST index (gist_geometry_ops_nd), not the default 2D one.", render: binary("&&&"), }, { - Name: "bboxIntersects2D", Arg: TypeName, Index: true, Geography: true, + Name: "bboxIntersects2D", OperandType: TypeName, Indexable: true, Geography: true, Description: "This column's 2D bounding box overlaps the given geometry's (&&).", render: binary("&&"), }, } -// OpByName looks up an operator by field name. +// Ops returns the spatial operator vocabulary exposed on every geometry +// and geography column, in declaration order: the index-usable +// bounding-box operators first, then the exact DE-9IM predicates. The list +// is append-only, so generated schemas only grow at the end. The slice is +// a fresh copy. +func Ops() []Op { return slices.Clone(ops) } + +// OpByName looks up an operator by name. func OpByName(name string) (Op, bool) { - for _, op := range Ops { + for _, op := range ops { if op.Name == name { return op, true } @@ -287,24 +296,40 @@ func BBoxSQL(minX, minY, maxX, maxY string, srid int, f Flavour) string { return expr } -// OutputSQL renders a spatial column as the GeoJSON text the response carries. +// Output selects how [OutputSQL] renders GeoJSON. The zero Output renders +// jsonb with PostGIS's default precision. +type Output struct { + // JSON renders json instead of jsonb. It skips the jsonb parse and + // re-serialisation, so it is the cheaper choice when the value is only + // embedded in a response (json_build_object, json_agg) and never + // compared, grouped or aggregated with jsonb functions. + JSON bool + // Precision rounds the coordinates to that many decimal places + // (ST_AsGeoJSON's maxdecimaldigits; PostGIS defaults to 9, 6 is about + // 10 cm on lon/lat data and shrinks payloads substantially). It is the + // placeholder of an integer parameter validated with + // [CheckPrecision], so the SQL text does not depend on its value; "" + // keeps the default. + Precision string +} + +// OutputSQL renders a spatial value as the GeoJSON a response carries. // -// ST_AsGeoJSON returns text, so the result is re-parsed into jsonb to embed it -// as a real JSON object rather than a JSON-encoded string. No NULL guard is -// needed: ST_AsGeoJSON is STRICT (NULL in, NULL out) and NULL::jsonb is NULL — -// and ref may be a computed-column function call, which a CASE guard would -// evaluate twice. -func OutputSQL(ref string) string { - return "ST_AsGeoJSON(" + ref + ")::jsonb" -} - -// OutputJSONSQL is [OutputSQL] producing json instead of jsonb. It skips the -// jsonb parse and re-serialisation, so it is the cheaper choice when the value -// is only embedded in a response (json_build_object, json_agg) and never -// compared, grouped or aggregated with jsonb functions. Like [OutputSQL] it -// evaluates ref once and yields NULL for NULL. -func OutputJSONSQL(ref string) string { - return "ST_AsGeoJSON(" + ref + ")::json" +// ST_AsGeoJSON returns text, so the result is re-parsed into jsonb (or json, +// see [Output.JSON]) to embed it as a real JSON object rather than a +// JSON-encoded string. No NULL guard is needed: ST_AsGeoJSON is STRICT (NULL +// in, NULL out) and NULL::jsonb is NULL — and ref may be a computed-column +// function call, which a CASE guard would evaluate twice. +func OutputSQL(ref string, o Output) string { + args := ref + if o.Precision != "" { + args += ", " + cast(o.Precision, "int4") + } + typ := "jsonb" + if o.JSON { + typ = "json" + } + return "ST_AsGeoJSON(" + args + ")::" + typ } // MaxPrecision is the largest GeoJSON precision consumers accept: 15 @@ -321,21 +346,6 @@ func CheckPrecision(digits int64) error { return nil } -// OutputPrecisionSQL is [OutputSQL] with the coordinates rounded to digits -// decimal places (ST_AsGeoJSON's maxdecimaldigits; PostGIS defaults to 9, -// 6 is about 10 cm on lon/lat data and shrinks payloads substantially). -// digits is the placeholder of an integer parameter validated with -// [CheckPrecision], so the SQL text does not depend on its value. -func OutputPrecisionSQL(ref, digits string) string { - return "ST_AsGeoJSON(" + ref + ", " + cast(digits, "int4") + ")::jsonb" -} - -// OutputJSONPrecisionSQL is [OutputPrecisionSQL] producing json instead of -// jsonb (see [OutputJSONSQL]). -func OutputJSONPrecisionSQL(ref, digits string) string { - return "ST_AsGeoJSON(" + ref + ", " + cast(digits, "int4") + ")::json" -} - // BufferCost is the cost, in column reads per returned row, a consumer's cost // estimate charges for a buffer projection argument ([BufferSQL]): // ST_Buffer builds a new polygon around every vertex of the value. @@ -374,7 +384,8 @@ func cast(ph, typ string) string { type Derived struct { // Suffix is appended to the column's field name. Suffix string - // Type is the generated field's type name (pdbq SDL spelling). + // Type is the generated field's type name: Boolean, Int, Float, String + // or [TypeName]. Type string // Description documents the field. Description string @@ -387,17 +398,8 @@ type Derived struct { applies func(geomSubtype) bool } -// Deriveds are the derived accessors generated for every spatial column. -// -// Each is a pure function of the column, so they compile into the same single -// statement as an ordinary column read — no extra round trip. Accessors that -// PostGIS only defines for one geometry type (X, Y, Z, M, StartPoint, -// EndPoint) render a CASE guard on ST_GeometryType that yields NULL for every -// other type instead of an error, so their SQL references the column twice. -// [Derived.Applies] reports which accessors are worth exposing once a -// column's typmod is known. The list is append-only so generated schemas -// only grow at the end. -var Deriveds = []Derived{ +// deriveds backs [Deriveds]. The list is append-only. +var deriveds = []Derived{ { Suffix: "Area", Type: "Float", Description: "Area of the geometry (ST_Area): square metres for geography, SRID units for geometry.", @@ -691,9 +693,20 @@ func (d Derived) AppliesTo(subtype string, hasZ, hasM bool) bool { return d.applies(st) } +// Deriveds returns the derived accessors generated for every spatial +// column, in declaration order (append-only, so generated schemas only +// grow at the end). Each is a pure function of the column, so it compiles +// into the same single statement as an ordinary column read. Accessors +// that PostGIS only defines for one geometry type (X, Y, Z, M, StartPoint, +// EndPoint) render a CASE guard on ST_GeometryType that yields NULL for +// every other type instead of an error, so their SQL references the +// column twice. [Derived.AppliesTo] reports which accessors are worth +// exposing once a column's typmod is known. The slice is a fresh copy. +func Deriveds() []Derived { return slices.Clone(deriveds) } + // DerivedBySuffix looks up a derived accessor. func DerivedBySuffix(suffix string) (Derived, bool) { - for _, d := range Deriveds { + for _, d := range deriveds { if d.Suffix == suffix { return d, true } @@ -701,43 +714,13 @@ func DerivedBySuffix(suffix string) (Derived, bool) { return Derived{}, false } -// SQL renders the derived accessor over a column reference, wrapping geometry -// valued results as GeoJSON. -func (d Derived) SQL(ref string, f Flavour) string { - expr := d.sql(ref, f) - if d.GeoJSON { - return OutputSQL(expr) - } - return expr -} - -// JSONSQL is [Derived.SQL] with geometry valued results rendered as json -// rather than jsonb (see [OutputJSONSQL]); other accessors are unchanged. -func (d Derived) JSONSQL(ref string, f Flavour) string { - expr := d.sql(ref, f) - if d.GeoJSON { - return OutputJSONSQL(expr) - } - return expr -} - -// PrecisionSQL is [Derived.SQL] with a geometry valued result rendered by -// [OutputPrecisionSQL]; accessors that return no geometry ignore digits. -func (d Derived) PrecisionSQL(ref string, f Flavour, digits string) string { - expr := d.sql(ref, f) - if d.GeoJSON { - return OutputPrecisionSQL(expr, digits) - } - return expr -} - -// JSONPrecisionSQL is [Derived.JSONSQL] with a geometry valued result -// rendered by [OutputJSONPrecisionSQL]; accessors that return no geometry -// ignore digits. -func (d Derived) JSONPrecisionSQL(ref string, f Flavour, digits string) string { +// SQL renders the derived accessor over a column reference, rendering a +// geometry valued result as GeoJSON with o (see [OutputSQL]); accessors +// that return no geometry ignore o. +func (d Derived) SQL(ref string, f Flavour, o Output) string { expr := d.sql(ref, f) if d.GeoJSON { - return OutputJSONPrecisionSQL(expr, digits) + return OutputSQL(expr, o) } return expr } @@ -788,30 +771,3 @@ func SpheroidDistanceSQL(col, geom string) string { func KNNSQL(col, geom string) string { return fmt.Sprintf("%s <-> %s", col, geom) } - -// DerivedSuffixes returns the accessor suffixes in declaration order. -func DerivedSuffixes() []string { - out := make([]string, len(Deriveds)) - for i, d := range Deriveds { - out[i] = d.Suffix - } - return out -} - -// OpNames returns the operator names in declaration order. -func OpNames() []string { - out := make([]string, len(Ops)) - for i, op := range Ops { - out[i] = op.Name - } - return out -} - -// String renders the operator vocabulary for documentation/debugging. -func OpsDoc() string { - var b strings.Builder - for _, op := range Ops { - fmt.Fprintf(&b, "%s(%s): %s\n", op.Name, op.Arg, op.Description) - } - return b.String() -} diff --git a/postgis/postgis.go b/postgis/postgis.go index b5e5cc1..8b15574 100644 --- a/postgis/postgis.go +++ b/postgis/postgis.go @@ -79,8 +79,8 @@ func (f Flavour) Spatial() bool { return f == Geometry || f == Geography } // is in whatever unit its SRID uses. func (f Flavour) MetresNative() bool { return f == Geography } -// TypeName is the scalar name every spatial column maps to (pdbq's GraphQL -// scalar; pdbr's OpenAPI schema). Values are GeoJSON objects on the way out +// TypeName is the type name every spatial value maps to (a GraphQL +// scalar, an OpenAPI component schema). Values are GeoJSON objects on the way out // and GeoJSON-or-WKT on the way in. const TypeName = "GeoJSON" diff --git a/postgis/postgis_test.go b/postgis/postgis_test.go index 93bdc4a..58b404a 100644 --- a/postgis/postgis_test.go +++ b/postgis/postgis_test.go @@ -320,7 +320,7 @@ func TestOpsRender(t *testing.T) { t.Errorf("%s rendered %q, want %q", tc.op, got, tc.want) } } - for _, name := range OpNames() { + for _, name := range opNames() { if !covered[name] { t.Errorf("operator %q has no rendering test", name) } @@ -340,8 +340,8 @@ func TestOpOrderIsAppendOnly(t *testing.T) { "bboxOverlapsOrAbove", "bboxEquals", "exactlyEquals", "orderingEquals", "intersects3D", "bboxIntersectsND", "bboxIntersects2D", } - if got := OpNames(); strings.Join(got, ",") != strings.Join(want, ",") { - t.Errorf("OpNames() = %v\nwant %v", got, want) + if got := opNames(); strings.Join(got, ",") != strings.Join(want, ",") { + t.Errorf("opNames() = %v\nwant %v", got, want) } } @@ -383,8 +383,8 @@ func TestOpFlags(t *testing.T) { if op.Geography != tc.geography { t.Errorf("%s Geography = %v, want %v", tc.op, op.Geography, tc.geography) } - if op.Index != tc.index { - t.Errorf("%s Index = %v, want %v", tc.op, op.Index, tc.index) + if op.Indexable != tc.index { + t.Errorf("%s Index = %v, want %v", tc.op, op.Indexable, tc.index) } if op.Description == "" { t.Errorf("%s has no description", tc.op) @@ -450,7 +450,7 @@ func TestOutputSQLEvaluatesRefOnce(t *testing.T) { // needed — and ref may be a computed-column function call, so it must // appear exactly once to avoid double evaluation. ref := `"t"."geom"` - got := OutputSQL(ref) + got := OutputSQL(ref, Output{}) for _, want := range []string{"ST_AsGeoJSON", "::jsonb"} { if !strings.Contains(got, want) { t.Errorf("OutputSQL missing %q: %s", want, got) @@ -469,7 +469,7 @@ func TestDerivedGeographyCasts(t *testing.T) { if !ok { t.Fatalf("derived %q not found", suffix) } - if got := d.SQL(`"t"."g"`, Geography); !strings.Contains(got, "::geometry") { + if got := d.SQL(`"t"."g"`, Geography, Output{}); !strings.Contains(got, "::geometry") { t.Errorf("%s on geography is not cast: %s", suffix, got) } } @@ -477,7 +477,7 @@ func TestDerivedGeographyCasts(t *testing.T) { // there), so they must NOT be cast away. for _, suffix := range []string{"Area", "Length", "Perimeter"} { d, _ := DerivedBySuffix(suffix) - if got := d.SQL(`"t"."g"`, Geography); strings.Contains(got, "::geometry") { + if got := d.SQL(`"t"."g"`, Geography, Output{}); strings.Contains(got, "::geometry") { t.Errorf("%s on geography should keep spheroidal units: %s", suffix, got) } } @@ -542,14 +542,14 @@ func TestDerivedSQL(t *testing.T) { if !ok { t.Fatalf("derived %q not found", tc.suffix) } - if got := d.SQL(ref, Geometry); got != tc.geometry { + if got := d.SQL(ref, Geometry, Output{}); got != tc.geometry { t.Errorf("%s geometry SQL = %s\nwant %s", tc.suffix, got, tc.geometry) } - if got := d.SQL(ref, Geography); got != tc.geo { + if got := d.SQL(ref, Geography, Output{}); got != tc.geo { t.Errorf("%s geography SQL = %s\nwant %s", tc.suffix, got, tc.geo) } } - for _, s := range DerivedSuffixes() { + for _, s := range derivedSuffixes() { if !covered[s] { t.Errorf("derived %q has no rendering test", s) } @@ -564,8 +564,8 @@ func TestDerivedOrderIsAppendOnly(t *testing.T) { "X", "Y", "Z", "M", "NumPoints", "NumGeometries", "StartPoint", "EndPoint", "PointOnSurface", "Wkt", "Ewkt", "IsEmpty", "IsSimple", "Xmin", "Ymin", "Xmax", "Ymax", } - if got := DerivedSuffixes(); strings.Join(got, ",") != strings.Join(want, ",") { - t.Errorf("DerivedSuffixes() = %v\nwant %v", got, want) + if got := derivedSuffixes(); strings.Join(got, ",") != strings.Join(want, ",") { + t.Errorf("derivedSuffixes() = %v\nwant %v", got, want) } } @@ -608,7 +608,7 @@ func TestDerivedApplies(t *testing.T) { for _, s := range tc.want { want[s] = true } - for _, d := range Deriveds { + for _, d := range Deriveds() { exp := !gated[d.Suffix] || want[d.Suffix] if got := d.Applies(tc.subtype); got != exp { t.Errorf("%s.Applies(%q) = %v, want %v", d.Suffix, tc.subtype, got, exp) @@ -707,11 +707,11 @@ func TestParseDoesNotMutateInput(t *testing.T) { func TestOutputJSONSQL(t *testing.T) { ref := `"t"."geom"` - if got, want := OutputJSONSQL(ref), `ST_AsGeoJSON("t"."geom")::json`; got != want { + if got, want := OutputSQL(ref, Output{JSON: true}), `ST_AsGeoJSON("t"."geom")::json`; got != want { t.Errorf("OutputJSONSQL = %s, want %s", got, want) } - for _, d := range Deriveds { - got, jsonb := d.JSONSQL(ref, Geometry), d.SQL(ref, Geometry) + for _, d := range Deriveds() { + got, jsonb := d.SQL(ref, Geometry, Output{JSON: true}), d.SQL(ref, Geometry, Output{}) want := strings.ReplaceAll(jsonb, "::jsonb", "::json") if got != want { t.Errorf("%s JSONSQL = %s, want %s", d.Suffix, got, want) @@ -733,23 +733,23 @@ func TestDistanceRenders(t *testing.T) { func TestPrecisionAndBuffer(t *testing.T) { const ref = `"t"."g"` - if got, want := OutputPrecisionSQL(ref, "$2"), `ST_AsGeoJSON("t"."g", $2::int4)::jsonb`; got != want { + if got, want := OutputSQL(ref, Output{Precision: "$2"}), `ST_AsGeoJSON("t"."g", $2::int4)::jsonb`; got != want { t.Errorf("OutputPrecisionSQL = %s, want %s", got, want) } - if got, want := OutputJSONPrecisionSQL(ref, "$2"), `ST_AsGeoJSON("t"."g", $2::int4)::json`; got != want { + if got, want := OutputSQL(ref, Output{JSON: true, Precision: "$2"}), `ST_AsGeoJSON("t"."g", $2::int4)::json`; got != want { t.Errorf("OutputJSONPrecisionSQL = %s, want %s", got, want) } - if got, want := OutputJSONPrecisionSQL(ref, "coalesce($2, 9)"), `ST_AsGeoJSON("t"."g", (coalesce($2, 9))::int4)::json`; got != want { + if got, want := OutputSQL(ref, Output{JSON: true, Precision: "coalesce($2, 9)"}), `ST_AsGeoJSON("t"."g", (coalesce($2, 9))::int4)::json`; got != want { t.Errorf("OutputJSONPrecisionSQL = %s, want %s", got, want) } if got, want := BufferSQL(ref, "$1"), `ST_Buffer("t"."g", $1::float8)`; got != want { t.Errorf("BufferSQL = %s, want %s", got, want) } - for _, d := range Deriveds { - plain, prec := d.JSONSQL(ref, Geography), d.JSONPrecisionSQL(ref, Geography, "$1") - jsonbPrec := d.PrecisionSQL(ref, Geography, "$1") + for _, d := range Deriveds() { + plain, prec := d.SQL(ref, Geography, Output{JSON: true}), d.SQL(ref, Geography, Output{JSON: true, Precision: "$1"}) + jsonbPrec := d.SQL(ref, Geography, Output{Precision: "$1"}) if !d.GeoJSON { - if prec != plain || jsonbPrec != d.SQL(ref, Geography) { + if prec != plain || jsonbPrec != d.SQL(ref, Geography, Output{}) { t.Errorf("%s is not geometry valued but precision changed it: %s", d.Suffix, prec) } continue @@ -782,3 +782,40 @@ func TestPrecisionAndBuffer(t *testing.T) { } } } + +func opNames() []string { + var out []string + for _, op := range Ops() { + out = append(out, op.Name) + } + return out +} + +func derivedSuffixes() []string { + var out []string + for _, d := range Deriveds() { + out = append(out, d.Suffix) + } + return out +} + +func TestOutputSQLOptions(t *testing.T) { + cases := []struct { + o Output + want string + }{ + {Output{}, "ST_AsGeoJSON(t.g)::jsonb"}, + {Output{JSON: true}, "ST_AsGeoJSON(t.g)::json"}, + {Output{Precision: "$2"}, "ST_AsGeoJSON(t.g, $2::int4)::jsonb"}, + {Output{JSON: true, Precision: "$2"}, "ST_AsGeoJSON(t.g, $2::int4)::json"}, + {Output{Precision: "x.p"}, "ST_AsGeoJSON(t.g, (x.p)::int4)::jsonb"}, + } + for _, tc := range cases { + if got := OutputSQL("t.g", tc.o); got != tc.want { + t.Errorf("OutputSQL(%+v) = %q, want %q", tc.o, got, tc.want) + } + } + if a, b := Ops(), Ops(); &a[0] == &b[0] { + t.Error("Ops shares its backing array") + } +} diff --git a/postgis/raster.go b/postgis/raster.go index 26e0982..42d35ff 100644 --- a/postgis/raster.go +++ b/postgis/raster.go @@ -1,6 +1,9 @@ package postgis -import "strings" +import ( + "slices" + "strings" +) // RasterTypeName is the pg type name of a postgis_raster column. const RasterTypeName = "raster" @@ -38,8 +41,7 @@ const ( type RasterAccessor struct { // Suffix is appended to the column's field name. Suffix string - // Type is the generated field's type name (pdbq SDL spelling): Int, - // Float or GeoJSON. + // Type is the generated field's type name: Int, Float or [TypeName]. Type string // Description documents the field. Description string @@ -49,20 +51,12 @@ type RasterAccessor struct { sql func(ref string) string } -// SQL renders the accessor over a raster reference, wrapping geometry -// valued results as GeoJSON ([OutputSQL]). It is NULL for a NULL raster. -func (a RasterAccessor) SQL(ref string) string { +// SQL renders the accessor over a raster reference, rendering a geometry +// valued result as GeoJSON with o (see [OutputSQL]); accessors that return +// no geometry ignore o. It is NULL for a NULL raster. +func (a RasterAccessor) SQL(ref string, o Output) string { if a.GeoJSON { - return OutputSQL(a.sql(ref)) - } - return a.sql(ref) -} - -// JSONSQL is [RasterAccessor.SQL] with geometry valued results rendered as -// json rather than jsonb ([OutputJSONSQL]). -func (a RasterAccessor) JSONSQL(ref string) string { - if a.GeoJSON { - return OutputJSONSQL(a.sql(ref)) + return OutputSQL(a.sql(ref), o) } return a.sql(ref) } @@ -71,10 +65,13 @@ func rasterFn(name string) func(string) string { return func(ref string) string { return name + "(" + ref + ")" } } -// RasterAccessors are the metadata accessors of a raster column. They read -// only the raster header, so they are cheap whatever the raster's size. The -// list is append-only so generated schemas only grow at the end. -var RasterAccessors = []RasterAccessor{ +// RasterAccessors returns the metadata accessors of a raster column. They +// read only the raster header, so they are cheap whatever the raster's +// size. The list is append-only so generated schemas only grow at the end. +// The slice is a fresh copy. +func RasterAccessors() []RasterAccessor { return slices.Clone(rasterAccessors) } + +var rasterAccessors = []RasterAccessor{ {Suffix: "Width", Type: "Int", Description: "Width of the raster in pixels (ST_Width).", sql: rasterFn("ST_Width")}, {Suffix: "Height", Type: "Int", Description: "Height of the raster in pixels (ST_Height).", sql: rasterFn("ST_Height")}, {Suffix: "NumBands", Type: "Int", Description: "Number of bands of the raster (ST_NumBands).", sql: rasterFn("ST_NumBands")}, @@ -86,7 +83,7 @@ var RasterAccessors = []RasterAccessor{ // RasterAccessorBySuffix looks up a raster metadata accessor. func RasterAccessorBySuffix(suffix string) (RasterAccessor, bool) { - for _, a := range RasterAccessors { + for _, a := range rasterAccessors { if a.Suffix == suffix { return a, true } diff --git a/postgis/raster_test.go b/postgis/raster_test.go index e1e7ec5..3c5f40a 100644 --- a/postgis/raster_test.go +++ b/postgis/raster_test.go @@ -26,11 +26,11 @@ func TestRasterAccessors(t *testing.T) { "PixelHeight": "ST_PixelHeight(t.r)", "Envelope": "ST_AsGeoJSON(ST_Envelope(t.r))::jsonb", } - if len(RasterAccessors) != len(want) { - t.Fatalf("%d accessors", len(RasterAccessors)) + if len(RasterAccessors()) != len(want) { + t.Fatalf("%d accessors", len(RasterAccessors())) } - for _, a := range RasterAccessors { - if got := a.SQL("t.r"); got != want[a.Suffix] { + for _, a := range RasterAccessors() { + if got := a.SQL("t.r", Output{}); got != want[a.Suffix] { t.Errorf("%s = %s", a.Suffix, got) } if a.Description == "" || a.Type == "" || a.GeoJSON != (a.Type == TypeName) { @@ -41,11 +41,11 @@ func TestRasterAccessors(t *testing.T) { } } env, _ := RasterAccessorBySuffix("Envelope") - if got := env.JSONSQL("t.r"); got != "ST_AsGeoJSON(ST_Envelope(t.r))::json" { + if got := env.SQL("t.r", Output{JSON: true}); got != "ST_AsGeoJSON(ST_Envelope(t.r))::json" { t.Errorf("Envelope json = %s", got) } w, _ := RasterAccessorBySuffix("Width") - if w.JSONSQL("t.r") != w.SQL("t.r") { + if w.SQL("t.r", Output{JSON: true}) != w.SQL("t.r", Output{}) { t.Error("JSONSQL changes a scalar accessor") } if _, ok := RasterAccessorBySuffix("Pixels"); ok { diff --git a/smartcomments/catalog/catalog_test.go b/smartcomments/catalog/catalog_test.go index f4ab2a4..8abfef8 100644 --- a/smartcomments/catalog/catalog_test.go +++ b/smartcomments/catalog/catalog_test.go @@ -330,21 +330,14 @@ func TestPolymorphicNeverResolvesToHiddenTable(t *testing.T) { }) check(t, cat, true) }) - t.Run("contract applied first", func(t *testing.T) { - cat := testutil.FixtureCatalog() - prep(cat) - cat.Table("public", "metrics").Comment = "@behavior -contract:public" - contract.Contract{Name: "public"}.Apply(cat) - if err := plugin.NewRegistry(catalog.New()).TransformCatalog(context.Background(), nil, cat); err != nil { - t.Fatal(err) - } - check(t, cat, true) - }) t.Run("contract view clone", func(t *testing.T) { base := testutil.FixtureCatalog() prep(base) base.Table("public", "metrics").Comment = "@behavior -contract:public" - cat, _ := contract.Contract{Name: "public"}.View(base) + cat, _, err := contract.Contract{Name: "public"}.View(base) + if err != nil { + t.Fatal(err) + } if err := plugin.NewRegistry(catalog.New()).TransformCatalog(context.Background(), nil, cat); err != nil { t.Fatal(err) } diff --git a/watch/filter_test.go b/watch/filter_test.go index 4c305b0..44fca2f 100644 --- a/watch/filter_test.go +++ b/watch/filter_test.go @@ -128,7 +128,7 @@ func TestNotifyFilter(t *testing.T) { t.Fatal(err) } } - w := &Watcher{Pool: pool, Schemas: []string{schema}, Channel: name, TriggerName: name} + w := testWatcher(Config{Pool: pool, Schemas: []string{schema}, Channel: name, TriggerName: name}) if err := w.installTrigger(ctx); err != nil { t.Fatal(err) } @@ -184,7 +184,7 @@ func TestNotifyFilterHostileSchemaName(t *testing.T) { if _, err := pool.Exec(ctx, "CREATE SCHEMA "+quoteIdent(schema)); err != nil { t.Fatal(err) } - w := &Watcher{Pool: pool, Schemas: []string{schema, "public"}, Channel: name, TriggerName: name} + w := testWatcher(Config{Pool: pool, Schemas: []string{schema, "public"}, Channel: name, TriggerName: name}) if err := w.installTrigger(ctx); err != nil { t.Fatal(err) } @@ -212,7 +212,7 @@ func TestInstallTriggerUpgradesOldInstall(t *testing.T) { t.Fatal(err) } } - w := &Watcher{Pool: pool, Schemas: []string{"public"}, Channel: name, TriggerName: name} + w := testWatcher(Config{Pool: pool, Schemas: []string{"public"}, Channel: name, TriggerName: name}) for range 2 { if err := w.installTrigger(ctx); err != nil { t.Fatal(err) @@ -303,16 +303,16 @@ func TestWatcherSkipsUnchangedCatalog(t *testing.T) { var mu sync.Mutex var changes []*introspect.Catalog changed := make(chan *introspect.Catalog, 8) - w := &Watcher{ + w := mustNew(t, Config{ Pool: pool, Schemas: []string{schema}, Channel: name, TriggerName: name, InitialHash: hash, Log: slog.New(logTap{logs}), - OnChange: func(c *introspect.Catalog) { + OnChange: func(_ context.Context, c *introspect.Catalog) { mu.Lock() changes = append(changes, c) mu.Unlock() changed <- c }, - } + }) runCtx, stop := context.WithCancel(ctx) done := make(chan error, 1) go func() { done <- w.Run(runCtx) }() @@ -372,11 +372,11 @@ func TestRunDetectsChangeBeforeListening(t *testing.T) { t.Fatal(err) } changed := make(chan *introspect.Catalog, 1) - w := &Watcher{ + w := mustNew(t, Config{ Pool: pool, Schemas: []string{schema}, Channel: name, TriggerName: name, InitialHash: hash, Log: slog.New(logTap{make(chan string)}), - OnChange: func(c *introspect.Catalog) { changed <- c }, - } + OnChange: func(_ context.Context, c *introspect.Catalog) { changed <- c }, + }) runCtx, stop := context.WithCancel(ctx) done := make(chan error, 1) go func() { done <- w.Run(runCtx) }() @@ -405,18 +405,18 @@ func TestPollComparesAgainstInitialHash(t *testing.T) { } hash, _ := boot.Hash() changed := make(chan *introspect.Catalog, 4) - w := &Watcher{ + w := testWatcher(Config{ Pool: pool, Schemas: []string{schema}, PollInterval: 50 * time.Millisecond, Log: slog.New(logTap{make(chan string)}), - OnChange: func(c *introspect.Catalog) { changed <- c }, - } - w.lastHash = hash + OnChange: func(_ context.Context, c *introspect.Catalog) { changed <- c }, + }) + r := &run{Watcher: w, lastHash: hash} if _, err := pool.Exec(ctx, "CREATE TABLE "+schema+".early (id int)"); err != nil { t.Fatal(err) } pollCtx, stop := context.WithCancel(ctx) done := make(chan error, 1) - go func() { done <- w.poll(pollCtx) }() + go func() { done <- r.poll(pollCtx) }() c := waitFor(t, changed, "the first poll", func(*introspect.Catalog) bool { return true }) if c.Table(schema, "early") == nil { t.Fatal("poll catalog lacks the table") diff --git a/watch/watch.go b/watch/watch.go index 72307fc..819379c 100644 --- a/watch/watch.go +++ b/watch/watch.go @@ -8,8 +8,8 @@ import ( "errors" "fmt" "log/slog" + "slices" "strings" - "sync" "time" "github.com/jackc/pgx/v5" @@ -18,19 +18,23 @@ import ( "github.com/suprbdev/pdbcore/introspect" ) -// Watcher triggers OnChange whenever the introspected catalog of Schemas -// changes. The event trigger only notifies for DDL that can touch Schemas -// (objects in them, objects without a schema such as grants and -// extensions, and ALTERs that may move an object out of them); temp-schema -// objects never notify. A notification or poll whose catalog hash equals -// the last one applied does not call OnChange. -type Watcher struct { - Pool *pgxpool.Pool - Schemas []string - Channel string +// Config configures a [Watcher]. +type Config struct { + // Pool is the database to watch; required. + Pool *pgxpool.Pool + // Schemas are the schemas introspected; empty means public. + Schemas []string + // Channel is the NOTIFY channel of the DDL event trigger: letters, + // digits and underscores, at most 63 bytes. + Channel string + // PollInterval is the hash-polling interval used when the event + // trigger cannot be installed. PollInterval time.Duration - OnChange func(cat *introspect.Catalog) - Log *slog.Logger + // OnChange receives every changed catalog, with the context Run was + // given; required. It runs on Run's goroutine. + OnChange func(ctx context.Context, cat *introspect.Catalog) + // Log receives the watcher's messages; nil uses slog.Default(). + Log *slog.Logger // TriggerName names the ddl_command_end event trigger; the sql_drop // trigger is TriggerName + "_drop" and the notify function they share // is TriggerName + "_notify". Defaults to Channel + "_watch". Products @@ -51,87 +55,113 @@ type Watcher struct { // re-checks anyway; DDL in a still-open transaction that commits later // is then not reported. InstallWait time.Duration - - lastHash string - readyOnce sync.Once - ready chan struct{} } -func (w *Watcher) readyChan() chan struct{} { - w.readyOnce.Do(func() { w.ready = make(chan struct{}) }) - return w.ready +// Watcher calls [Config.OnChange] whenever the introspected catalog of the +// configured schemas changes. The event trigger only notifies for DDL that +// can touch them (objects in them, objects without a schema such as grants +// and extensions, and ALTERs that may move an object out of them); +// temp-schema objects never notify. A notification or poll whose catalog +// hash equals the last one applied does not call OnChange. Create one with +// [New]. +type Watcher struct { + cfg Config + ready chan struct{} } -// DefaultInstallWait is the default [Watcher.InstallWait]. +// DefaultInstallWait is the default [Config.InstallWait]. const DefaultInstallWait = 30 * time.Second const installPollInterval = 50 * time.Millisecond +// New validates cfg, fills in its defaults and returns the Watcher. It is +// an error when Pool or OnChange is nil, or when Channel or TriggerName is +// not a valid name or too long to install. +func New(cfg Config) (*Watcher, error) { + if !validChannel(cfg.Channel) { + return nil, fmt.Errorf("watch: invalid channel name %q: only letters, digits and underscores are allowed", cfg.Channel) + } + if cfg.TriggerName == "" { + cfg.TriggerName = cfg.Channel + "_watch" + } + if !validChannel(cfg.TriggerName) { + return nil, fmt.Errorf("watch: invalid trigger name %q: only letters, digits and underscores are allowed", cfg.TriggerName) + } + if len(cfg.Channel) > maxIdentLen { + return nil, fmt.Errorf("watch: channel name %q is longer than %d bytes", cfg.Channel, maxIdentLen) + } + if len(cfg.TriggerName)+len(longestSuffix) > maxIdentLen { + return nil, fmt.Errorf("watch: trigger name %q is too long: with the %q suffix it must fit in %d bytes", cfg.TriggerName, longestSuffix, maxIdentLen) + } + if cfg.Pool == nil { + return nil, errors.New("watch: Pool is required") + } + if cfg.OnChange == nil { + return nil, errors.New("watch: OnChange is required") + } + if len(cfg.Schemas) == 0 { + cfg.Schemas = []string{"public"} + } else { + cfg.Schemas = slices.Clone(cfg.Schemas) + } + if cfg.Log == nil { + cfg.Log = slog.Default() + } + if cfg.InstallWait <= 0 { + cfg.InstallWait = DefaultInstallWait + } + return &Watcher{cfg: cfg, ready: make(chan struct{})}, nil +} + // Ready returns a channel that is closed once Run is listening for DDL // notifications, or, when the event trigger cannot be installed, once the // polling loop has started. Every change made after Ready is closed reaches // OnChange, as does any change made since InitialHash was taken. The channel -// is never closed if Run returns an error before reaching that point. It may -// be called before Run. +// is never closed if Run returns an error before reaching that point. // // When InitialHash is set and the event trigger was installed, Ready is // closed only after every transaction that was open at install time has // ended and the catalog has been re-checked against InitialHash, because // DDL run in such a transaction before the trigger existed is neither // notified nor visible until it commits. A long-running transaction -// therefore delays Ready, up to [Watcher.InstallWait]. +// therefore delays Ready, up to [Config.InstallWait]. func (w *Watcher) Ready() <-chan struct{} { - return w.readyChan() + return w.ready +} + +// run is the state of one Run: the hash of the catalog last applied. +type run struct { + *Watcher + lastHash string } // Run blocks until ctx is cancelled. It tries to install the event trigger; -// on permission failure it degrades to hash polling with a warning. +// on permission failure it degrades to hash polling with a warning. Run +// must be called at most once. func (w *Watcher) Run(ctx context.Context) error { - if w.Log == nil { - w.Log = slog.Default() - } - if !validChannel(w.Channel) { - return fmt.Errorf("watch: invalid channel name %q: only letters, digits and underscores are allowed", w.Channel) - } - if w.TriggerName == "" { - w.TriggerName = w.Channel + "_watch" - } - if !validChannel(w.TriggerName) { - return fmt.Errorf("watch: invalid trigger name %q: only letters, digits and underscores are allowed", w.TriggerName) - } - if len(w.Channel) > maxIdentLen { - return fmt.Errorf("watch: channel name %q is longer than %d bytes", w.Channel, maxIdentLen) - } - if len(w.TriggerName)+len(longestSuffix) > maxIdentLen { - return fmt.Errorf("watch: trigger name %q is too long: with the %q suffix it must fit in %d bytes", w.TriggerName, longestSuffix, maxIdentLen) - } - if len(w.Schemas) == 0 { - w.Schemas = []string{"public"} - } - w.lastHash = w.InitialHash - ready := w.readyChan() - conn, err := w.Pool.Acquire(ctx) + r := &run{Watcher: w, lastHash: w.cfg.InitialHash} + conn, err := w.cfg.Pool.Acquire(ctx) if err != nil { return err } defer conn.Release() - if _, err := conn.Exec(ctx, "LISTEN "+quoteIdent(w.Channel)); err != nil { + if _, err := conn.Exec(ctx, "LISTEN "+quoteIdent(w.cfg.Channel)); err != nil { return err } if err := w.installTrigger(ctx); err != nil { - w.Log.Warn("watch: cannot install DDL event trigger; falling back to polling", - "err", err, "interval", w.PollInterval) - return w.poll(ctx) + w.cfg.Log.Warn("watch: cannot install DDL event trigger; falling back to polling", + "err", err, "interval", w.cfg.PollInterval) + return r.poll(ctx) } - w.Log.Info("watch: DDL event trigger installed", "channel", w.Channel) - if w.lastHash != "" { + w.cfg.Log.Info("watch: DDL event trigger installed", "channel", w.cfg.Channel) + if r.lastHash != "" { if err := w.waitInstallTxns(ctx); err != nil { return nil } - w.reintrospect(ctx) + r.reintrospect(ctx) } - close(ready) - return w.listen(ctx, conn.Conn()) + close(w.ready) + return r.listen(ctx, conn.Conn()) } // waitInstallTxns blocks until every transaction holding an xid below the @@ -141,26 +171,23 @@ func (w *Watcher) Run(ctx context.Context) error { // trigger. It returns the context error if ctx is cancelled. func (w *Watcher) waitInstallTxns(ctx context.Context) error { var xmax string - if err := w.Pool.QueryRow(ctx, `SELECT pg_snapshot_xmax(pg_current_snapshot())::text`).Scan(&xmax); err != nil { - w.Log.Warn("watch: cannot snapshot open transactions; re-checking immediately", "err", err) + if err := w.cfg.Pool.QueryRow(ctx, `SELECT pg_snapshot_xmax(pg_current_snapshot())::text`).Scan(&xmax); err != nil { + w.cfg.Log.Warn("watch: cannot snapshot open transactions; re-checking immediately", "err", err) return nil } - wait := w.InstallWait - if wait <= 0 { - wait = DefaultInstallWait - } + wait := w.cfg.InstallWait deadline := time.NewTimer(wait) defer deadline.Stop() tick := time.NewTicker(installPollInterval) defer tick.Stop() for { var done bool - err := w.Pool.QueryRow(ctx, `SELECT pg_snapshot_xmin(pg_current_snapshot()) >= $1::xid8`, xmax).Scan(&done) + err := w.cfg.Pool.QueryRow(ctx, `SELECT pg_snapshot_xmin(pg_current_snapshot()) >= $1::xid8`, xmax).Scan(&done) if err != nil { if ctx.Err() != nil { return ctx.Err() } - w.Log.Warn("watch: cannot poll open transactions; re-checking immediately", "err", err) + w.cfg.Log.Warn("watch: cannot poll open transactions; re-checking immediately", "err", err) return nil } if done { @@ -170,7 +197,7 @@ func (w *Watcher) waitInstallTxns(ctx context.Context) error { case <-ctx.Done(): return ctx.Err() case <-deadline.C: - w.Log.Warn("watch: transactions open at trigger install still running; re-checking anyway", "wait", wait) + w.cfg.Log.Warn("watch: transactions open at trigger install still running; re-checking anyway", "wait", wait) return nil case <-tick.C: } @@ -181,18 +208,18 @@ func (w *Watcher) waitInstallTxns(ctx context.Context) error { // ddl_command_end and sql_drop event triggers when missing. Installs from // older versions (one unfiltered trigger) are upgraded in place. func (w *Watcher) installTrigger(ctx context.Context) error { - fnName := w.TriggerName + "_notify" + fnName := w.cfg.TriggerName + "_notify" fn := fmt.Sprintf(` CREATE OR REPLACE FUNCTION %s() RETURNS event_trigger - LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp AS %s;`, quoteIdent(fnName), dollarQuote(notifyBody(w.Channel, w.Schemas))) - if _, err := w.Pool.Exec(ctx, fn); err != nil { + LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp AS %s;`, quoteIdent(fnName), dollarQuote(notifyBody(w.cfg.Channel, w.cfg.Schemas))) + if _, err := w.cfg.Pool.Exec(ctx, fn); err != nil { return err } for _, t := range []struct{ name, event string }{ - {w.TriggerName, "ddl_command_end"}, - {w.TriggerName + "_drop", "sql_drop"}, + {w.cfg.TriggerName, "ddl_command_end"}, + {w.cfg.TriggerName + "_drop", "sql_drop"}, } { - _, err := w.Pool.Exec(ctx, fmt.Sprintf(` + _, err := w.cfg.Pool.Exec(ctx, fmt.Sprintf(` DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM pg_event_trigger WHERE evtname = %s) THEN CREATE EVENT TRIGGER %s ON %s EXECUTE FUNCTION %s(); @@ -248,7 +275,7 @@ BEGIN END`, watched, quoteLit(channel)) } -func (w *Watcher) listen(ctx context.Context, conn *pgx.Conn) error { +func (r *run) listen(ctx context.Context, conn *pgx.Conn) error { for { _, err := conn.WaitForNotification(ctx) if err != nil { @@ -260,7 +287,7 @@ func (w *Watcher) listen(ctx context.Context, conn *pgx.Conn) error { // Debounce bursts of DDL (e.g. a migration) before re-introspecting. time.Sleep(250 * time.Millisecond) drainNotifications(ctx, conn) - w.reintrospect(ctx) + r.reintrospect(ctx) } } @@ -275,59 +302,60 @@ func drainNotifications(ctx context.Context, conn *pgx.Conn) { } } -func (w *Watcher) poll(ctx context.Context) error { - ticker := time.NewTicker(w.PollInterval) +func (r *run) poll(ctx context.Context) error { + ticker := time.NewTicker(r.cfg.PollInterval) defer ticker.Stop() - close(w.readyChan()) + close(r.ready) for { select { case <-ctx.Done(): return nil case <-ticker.C: - cat, err := introspect.Introspect(ctx, w.Pool, w.Schemas) + cat, err := introspect.Introspect(ctx, r.cfg.Pool, r.cfg.Schemas) if err != nil { - w.Log.Warn("watch: poll introspection failed", "err", err) + r.cfg.Log.Warn("watch: poll introspection failed", "err", err) continue } hash, err := cat.Hash() if err != nil { continue } - if w.lastHash == "" { - w.lastHash = hash + if r.lastHash == "" { + r.lastHash = hash continue } - if hash != w.lastHash { - w.lastHash = hash - w.Log.Info("watch: schema drift detected (poll)") - w.OnChange(cat) + if hash != r.lastHash { + r.lastHash = hash + r.cfg.Log.Info("watch: schema drift detected (poll)") + r.cfg.OnChange(ctx, cat) } } } } -func (w *Watcher) reintrospect(ctx context.Context) { - cat, err := introspect.Introspect(ctx, w.Pool, w.Schemas) +func (r *run) reintrospect(ctx context.Context) { + cat, err := introspect.Introspect(ctx, r.cfg.Pool, r.cfg.Schemas) if err != nil { - w.Log.Error("watch: re-introspection failed", "err", err) + r.cfg.Log.Error("watch: re-introspection failed", "err", err) return } if hash, err := cat.Hash(); err == nil { - if hash == w.lastHash { - w.Log.Debug("watch: DDL left the catalog unchanged; not rebuilding") + if hash == r.lastHash { + r.cfg.Log.Debug("watch: DDL left the catalog unchanged; not rebuilding") return } - w.lastHash = hash + r.lastHash = hash } - w.Log.Info("watch: schema changed, rebuilding") - w.OnChange(cat) + r.cfg.Log.Info("watch: schema changed, rebuilding") + r.cfg.OnChange(ctx, cat) } // maxIdentLen is PostgreSQL's identifier limit (NAMEDATALEN - 1); longer // names are silently truncated, which could make two triggers collide. const maxIdentLen = 63 -// longestSuffix is the longest suffix installTrigger appends to TriggerName. +// longestSuffix is the longest suffix installTrigger appends to the +// trigger name. const longestSuffix = "_notify" func quoteIdent(s string) string { diff --git a/watch/watch_test.go b/watch/watch_test.go index 0adfd5c..0c245f3 100644 --- a/watch/watch_test.go +++ b/watch/watch_test.go @@ -13,27 +13,54 @@ import ( "github.com/suprbdev/pdbcore/introspect" ) -func TestRunRejectsInvalidNames(t *testing.T) { - w := &Watcher{Channel: "bad$$chan"} - if err := w.Run(context.Background()); err == nil || !strings.Contains(err.Error(), "invalid channel name") { - t.Fatalf("err = %v", err) +func TestNewRejectsInvalidConfig(t *testing.T) { + ok := Config{Pool: &pgxpool.Pool{}, Channel: "ok", OnChange: func(context.Context, *introspect.Catalog) {}} + cases := []struct { + edit func(*Config) + want string + }{ + {func(c *Config) { c.Channel = "bad$$chan" }, "invalid channel name"}, + {func(c *Config) { c.TriggerName = "no-dashes" }, "invalid trigger name"}, + {func(c *Config) { c.Channel = strings.Repeat("c", 64) }, "longer than 63 bytes"}, + {func(c *Config) { c.TriggerName = strings.Repeat("t", 57) }, "is too long"}, + {func(c *Config) { c.Channel = strings.Repeat("c", 51) }, "is too long"}, + {func(c *Config) { c.Pool = nil }, "Pool is required"}, + {func(c *Config) { c.OnChange = nil }, "OnChange is required"}, + } + for _, tc := range cases { + cfg := ok + tc.edit(&cfg) + if _, err := New(cfg); err == nil || !strings.Contains(err.Error(), tc.want) { + t.Errorf("want %q, err = %v", tc.want, err) + } } - w = &Watcher{Channel: "ok", TriggerName: "no-dashes"} - if err := w.Run(context.Background()); err == nil || !strings.Contains(err.Error(), "invalid trigger name") { - t.Fatalf("err = %v", err) + schemas := []string{"app"} + cfg := ok + cfg.Schemas = schemas + w, err := New(cfg) + if err != nil { + t.Fatal(err) } - w = &Watcher{Channel: strings.Repeat("c", 64)} - if err := w.Run(context.Background()); err == nil || !strings.Contains(err.Error(), "longer than 63 bytes") { - t.Fatalf("err = %v", err) + schemas[0] = "changed" + if w.cfg.TriggerName != "ok_watch" || w.cfg.Log == nil || w.cfg.InstallWait != DefaultInstallWait || w.cfg.Schemas[0] != "app" { + t.Errorf("defaults = %+v", w.cfg) } - w = &Watcher{Channel: "ok", TriggerName: strings.Repeat("t", 57)} - if err := w.Run(context.Background()); err == nil || !strings.Contains(err.Error(), "is too long") { - t.Fatalf("err = %v", err) + if w, _ := New(ok); len(w.cfg.Schemas) != 1 || w.cfg.Schemas[0] != "public" { + t.Errorf("default schemas = %v", w.cfg.Schemas) } - w = &Watcher{Channel: strings.Repeat("c", 51)} - if err := w.Run(context.Background()); err == nil || !strings.Contains(err.Error(), "is too long") { - t.Fatalf("default trigger name from a long channel: err = %v", err) +} + +func mustNew(t *testing.T, cfg Config) *Watcher { + t.Helper() + w, err := New(cfg) + if err != nil { + t.Fatal(err) } + return w +} + +func testWatcher(cfg Config) *Watcher { + return &Watcher{cfg: cfg, ready: make(chan struct{})} } func TestQuoting(t *testing.T) { @@ -69,11 +96,11 @@ func TestWatchEndToEnd(t *testing.T) { defer dropTriggers(pool, "pdbcore_test_ddl_watch") changes := make(chan *introspect.Catalog, 4) - w := &Watcher{ + w := mustNew(t, Config{ Pool: pool, Schemas: []string{"watch_test"}, Channel: "pdbcore_test_ddl", PollInterval: time.Second, - OnChange: func(c *introspect.Catalog) { changes <- c }, - } + OnChange: func(_ context.Context, c *introspect.Catalog) { changes <- c }, + }) runCtx, stop := context.WithCancel(ctx) done := make(chan error, 1) go func() { done <- w.Run(runCtx) }() @@ -177,11 +204,11 @@ func TestWatchDDLDuringStartup(t *testing.T) { } changes := make(chan *introspect.Catalog, 4) - w := &Watcher{ + w := mustNew(t, Config{ Pool: pool, Schemas: []string{schema}, Channel: "pdbcore_startup", PollInterval: time.Second, InitialHash: hash, - OnChange: func(c *introspect.Catalog) { changes <- c }, - } + OnChange: func(_ context.Context, c *introspect.Catalog) { changes <- c }, + }) runCtx, stop := context.WithCancel(ctx) done := make(chan error, 1) go func() { done <- w.Run(runCtx) }() @@ -259,11 +286,11 @@ func TestWatchReadyPollFallback(t *testing.T) { t.Fatal(err) } changes := make(chan *introspect.Catalog, 4) - w := &Watcher{ + w := mustNew(t, Config{ Pool: pool, Schemas: []string{schema}, Channel: "pdbcore_poll", PollInterval: 100 * time.Millisecond, InitialHash: hash, - OnChange: func(c *introspect.Catalog) { changes <- c }, - } + OnChange: func(_ context.Context, c *introspect.Catalog) { changes <- c }, + }) runCtx, stop := context.WithCancel(ctx) done := make(chan error, 1) go func() { done <- w.Run(runCtx) }()