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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 8 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:<name>` 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 |
Expand Down Expand Up @@ -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")
```

Expand Down Expand Up @@ -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, <the op's tsquery>[,
Expand Down
32 changes: 32 additions & 0 deletions confx/cliflags/cliflags.go
Original file line number Diff line number Diff line change
@@ -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
}
60 changes: 60 additions & 0 deletions confx/cliflags/cliflags_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
Loading
Loading