diff --git a/CHANGELOG.md b/CHANGELOG.md index 27444ce..cd62d85 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,26 @@ becomes the release notes of the next tag. a database error in one query root field no longer fails the later fields with `pg:25P02` or adds a pathless `internal` error logged at `ERROR`: the query runs again with each root field in its own savepoint. +- Removed config keys (`transactions.mutations`, + `plugins.settings.nested_mutations.force_transactions`) are reported with + the reason they were removed, and `transactions.isolation` errors name + the accepted values ([upgrading](docs/upgrading.md#config-messages-and-embedding-api-pdbcore-api-hygiene)). +- `PDBQ_*` variables that double the underscore right after a section + (`PDBQ_ROLES__ALLOWED`) are errors with a did-you-mean hint instead of + being ignored; `database.connect_timeout`, `database.max_conns`, + `database.statement_timeout`, `auth.jwt.jwks_cache_ttl` (with a JWKS URL) + and `watch.poll_interval` (with the watch on) are validated. +- `pdbq.LoadConfig` takes command-line values as `map[string]any` instead of + a `*pflag.FlagSet`. +- The `@omit` / `@behavior` checks use pdbcore's shared smart-tag + vocabulary, so pdbq and pdbr warn about the same comments. +- Built against pdbcore's API hygiene changes (see its changelog). + +### Fixed + +- A live boot no longer alphabetises `schema.schemas` in place; type names + resolve through the schemas in their configured order, as on a + schema-cache boot. ## [0.30.0] - 2026-11-24 diff --git a/cmd/pdbq/main.go b/cmd/pdbq/main.go index a347fb7..c72203d 100644 --- a/cmd/pdbq/main.go +++ b/cmd/pdbq/main.go @@ -19,6 +19,7 @@ import ( "github.com/suprbdev/pdbcore/cache" "github.com/suprbdev/pdbcore/confx" + "github.com/suprbdev/pdbcore/confx/cliflags" pgcontrib "github.com/suprbdev/pdbcore/contrib" "github.com/suprbdev/pdbcore/pgexec" "github.com/suprbdev/pdbq" @@ -128,14 +129,14 @@ func loadConfig(cmd *cobra.Command) (config.Config, error) { // changedConfigFlags returns the config flags the user set on cmd. Config // flags are named after dotted koanf paths; command-local flags (--config, // --output, --var, ...) have no dot and stay out of the config. -func changedConfigFlags(cmd *cobra.Command) *flag.FlagSet { +func changedConfigFlags(cmd *cobra.Command) map[string]any { var local []string cmd.Flags().VisitAll(func(f *flag.Flag) { if !strings.Contains(f.Name, ".") { local = append(local, f.Name) } }) - return confx.ChangedFlags(cmd.Flags(), local...) + return cliflags.Changed(cmd.Flags(), local...) } // loadCLIConfig loads the config of a command that runs without an HTTP diff --git a/docs/configuration.md b/docs/configuration.md index 4425d17..7d18997 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -45,8 +45,8 @@ same names: `limits.*` (`max_body_bytes`, `max_depth`, `max_cost`, | Key | Default | Notes | |---|---|---| | `database.url` | — | required | -| `database.max_conns` | 10 | maximum pooled connections | -| `database.connect_timeout` | `10s` | timeout for establishing a connection | +| `database.max_conns` | 10 | maximum pooled connections; `0` uses the pgx pool default, negative is an error | +| `database.connect_timeout` | `10s` | timeout for establishing a connection; must be positive | | `database.statement_timeout` | `25s` | per-statement timeout on every request (`0` disables); kept below `server.request_timeout` so a slow statement fails with SQLSTATE `57014` (code `pg:57014`) before the request is cut off | | `server.addr` | `:8080` | | | `server.graphiql` | `false` | GraphiQL playground at `/` (enable for dev) | @@ -128,7 +128,7 @@ same names: `limits.*` (`max_body_bytes`, `max_depth`, `max_cost`, | `transactions.partial.enabled` | `false` | let a request opt in (`extensions.partialMutations`) to running each mutation root field in its own savepoint, so a failing field does not roll back the others; see [Mutations](mutations.md#partial-success). Same key as pdbr's partial bulk writes | | `transactions.partial.max_items` | 1000 | most mutation root fields a partial request may have (each is a statement and a savepoint); more is rejected; must be `>= 1` | | `watch.enabled` | `false` | dev only; refuses to combine with cache | -| `watch.poll_interval` | `5s` | fallback polling when event triggers can't be installed | +| `watch.poll_interval` | `5s` | fallback polling when event triggers can't be installed; must be positive when `watch.enabled` | | `watch.channel` | `pdbq_ddl` | NOTIFY channel used by the DDL event trigger | | `errors.detail` | `prod` | `dev` exposes full PG error detail; `strict` hides even constraint-violation messages; status and `extensions.code` never change ([errors.md](errors.md)) | | `plugins.disabled` | `[]` | built-in plugin names to disable: `smart_comments`, `simple_names`, `advanced_filters`, `postgis`, `contrib`, `aggregates`, `nested_mutations`; any other name is an error (with a "did you mean" hint) | diff --git a/docs/upgrading.md b/docs/upgrading.md index 175b785..4084c59 100644 --- a/docs/upgrading.md +++ b/docs/upgrading.md @@ -418,3 +418,32 @@ values they send; databases rename deprecated behavior tokens. | `@behavior -filter` / `-order` | `@behavior -filterBy` / `-orderBy` (PostGraphile V5) | the old tokens still work with a build-time deprecation warning | | `@filterable` (alias `@sortable`) on foreign keys and computed columns under `relations_opt_in` / `computed_opt_in` admitted both filters and orderings | `@filterable` admits the filter surface, `@sortable` the orderBy surface | tag both to keep both; on columns either tag still admits both past `filters.indexed_only` | | unknown `@omit` actions and `@behavior` tokens were ignored silently | ignored with a build-time warning naming the object and the token | `@omit reed` no longer goes unnoticed | + +### Config messages and embedding API (pdbcore API hygiene) + +- **Removed keys say so.** `transactions.mutations` and + `plugins.settings.nested_mutations.force_transactions` (and their + `PDBQ_*` variables) are reported as + `unknown key transactions.mutations: removed: mutations always run in a transaction` + instead of a bare "unknown key". +- **Doubled underscores after a section are errors.** `PDBQ_ROLES__ALLOWED` + (and the like) used to be ignored silently, so the setting kept its + default; it is now `unknown environment variable PDBQ_ROLES__ALLOWED + (roles_allowed): did you mean PDBQ_ROLES_ALLOWED?`. +- **New checks:** `database.connect_timeout` must be positive (`0` waited + forever), `database.max_conns` and `database.statement_timeout` must not + be negative, `auth.jwt.jwks_cache_ttl` must be positive with + `auth.jwt.jwks_url` (`0` silently meant one hour), and + `watch.poll_interval` must be positive with `watch.enabled` (`0` crashed + the polling fallback). +- **`transactions.isolation` errors name the accepted values:** + `transactions.isolation: "x" is not 'read_committed', 'repeatable_read' or 'serializable'` + (was `"x" invalid`). +- **Embedding.** `pdbq.LoadConfig(path, flags)` takes the command-line + values as `map[string]any` (koanf path to value) instead of a + `*pflag.FlagSet`; build it from a pflag set with + `cliflags.Changed(fs, except...)` from + `github.com/suprbdev/pdbcore/confx/cliflags`. +- The smart-comment checks (unknown `@omit` actions, unknown and deprecated + `@behavior` tokens) now come from pdbcore and are shared with pdbr; the + warnings are unchanged. diff --git a/examples/pdbq.example.yaml b/examples/pdbq.example.yaml index 1c2272e..13588e9 100644 --- a/examples/pdbq.example.yaml +++ b/examples/pdbq.example.yaml @@ -6,9 +6,9 @@ database: # PostgreSQL connection URL, e.g. postgres://user:pass@host:5432/db. Also honours standard PG* env vars when empty. url: "" - # Maximum pooled connections. + # Maximum pooled connections; 0 uses the pgx pool default (the larger of 4 and the number of CPUs). max_conns: 10 - # Timeout for establishing a connection. + # Timeout for establishing a connection (must be positive). connect_timeout: "10s" # Per-statement timeout applied to every request (0 disables). Keep it below the HTTP request timeout so a slow statement fails with SQLSTATE 57014 (a timeout error the client can act on) before the request is cut off. statement_timeout: "25s" @@ -223,7 +223,7 @@ transactions: watch: # Re-introspect and hot-swap the schema on DDL changes (dev only; refuses to combine with schema.cache_path). enabled: false - # Poll interval used when event triggers cannot be installed. + # Poll interval used when event triggers cannot be installed (must be positive). poll_interval: "5s" # NOTIFY channel used by the DDL event trigger. channel: "pdbq_ddl" diff --git a/facade.go b/facade.go index f6d4c62..6e21995 100644 --- a/facade.go +++ b/facade.go @@ -8,8 +8,6 @@ import ( "fmt" "net/http" - flag "github.com/spf13/pflag" - "github.com/suprbdev/pdbcore/confx" "github.com/suprbdev/pdbcore/introspect" "github.com/suprbdev/pdbcore/watch" @@ -59,8 +57,9 @@ type ( func DefaultConfig() Config { return config.DefaultConfig() } // LoadConfig builds the effective config: defaults < YAML < PDBQ_* env < -// flags (nil flags is fine). -func LoadConfig(path string, flags *flag.FlagSet) (Config, error) { +// flags, given as koanf path to value (nil is fine; cliflags.Changed in +// github.com/suprbdev/pdbcore/confx/cliflags reads them from a pflag set). +func LoadConfig(path string, flags map[string]any) (Config, error) { return config.Load(path, flags) } @@ -311,7 +310,7 @@ func (a *App) installLive(ctx context.Context, t *live.Tracker) { // calling rebuild with every changed catalog. func (a *App) startWatch(ctx context.Context, catHash string, rebuild func(context.Context, *introspect.Catalog)) { wctx, cancel := context.WithCancel(ctx) - w := &watch.Watcher{ + w, err := watch.New(watch.Config{ Pool: a.pool, Schemas: a.Config.Schema.Schemas, Channel: a.Config.Watch.Channel, @@ -319,7 +318,12 @@ func (a *App) startWatch(ctx context.Context, catHash string, rebuild func(conte InitialHash: catHash, PollInterval: a.Config.Watch.PollInterval, Log: a.Log, - OnChange: func(cat *introspect.Catalog) { rebuild(wctx, cat) }, + OnChange: rebuild, + }) + if err != nil { + cancel() + a.Log.Error("watch: not started", "err", err) + return } done := make(chan struct{}) go func() { diff --git a/go.mod b/go.mod index 6bb0615..6a85cfe 100644 --- a/go.mod +++ b/go.mod @@ -8,7 +8,6 @@ require ( github.com/knadh/koanf/parsers/yaml v1.1.0 // indirect github.com/knadh/koanf/providers/env v1.1.0 // indirect github.com/knadh/koanf/providers/file v1.2.1 // indirect - github.com/knadh/koanf/providers/posflag v1.0.1 // indirect github.com/knadh/koanf/v2 v2.3.5 // indirect github.com/spf13/cobra v1.10.2 github.com/spf13/pflag v1.0.10 @@ -42,5 +41,5 @@ require ( require ( github.com/coder/websocket v1.8.15 github.com/prometheus/client_golang v1.25.0 - github.com/suprbdev/pdbcore v0.18.0 + github.com/suprbdev/pdbcore v0.19.0 ) diff --git a/go.sum b/go.sum index 90b5004..e148b4a 100644 --- a/go.sum +++ b/go.sum @@ -40,8 +40,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= @@ -72,8 +70,8 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= -github.com/suprbdev/pdbcore v0.18.0 h1:3sptk5S+ffSLIQmvTVd74rL6NjUHQ2zql91lHnFkH1Q= -github.com/suprbdev/pdbcore v0.18.0/go.mod h1:FNV4SnduAkZoFDBZ7PRGXcSjELkHjA9mURORywAVHlc= +github.com/suprbdev/pdbcore v0.19.0 h1:0j+vkzyt1bKcREPh6OUT9vX69dzL5QMzAAJvd1Ck+KM= +github.com/suprbdev/pdbcore v0.19.0/go.mod h1:loM9g7/i1GhIY4CRmHeAiMucJ57nxTgxN0YNHc7tW7w= github.com/vektah/gqlparser/v2 v2.5.36 h1:CN9mKVHgMkc+XftdOWIhb4HEL8wKSYkFAqhf8booa7s= github.com/vektah/gqlparser/v2 v2.5.36/go.mod h1:cAJ9qwVgPaUkWv6Gn8vn0mqOE0Ui5Pn56wNy5396XWo= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= diff --git a/internal/compile/aggregates.go b/internal/compile/aggregates.go index 7b563d0..a9a14e8 100644 --- a/internal/compile/aggregates.go +++ b/internal/compile/aggregates.go @@ -111,7 +111,7 @@ func (s *stmt) groupKeyText(expr string, c *introspect.Column) string { return "to_jsonb(" + expr + ")::text" } if postgis.FlavourOf(c.PGType).Spatial() { - return "to_jsonb(" + postgis.OutputSQL(expr) + ") #>> '{}'" + return "to_jsonb(" + postgis.OutputSQL(expr, postgis.Output{}) + ") #>> '{}'" } return "to_jsonb(" + s.exprJSON(expr, c) + ") #>> '{}'" } diff --git a/internal/compile/rows.go b/internal/compile/rows.go index 4ef229e..7b0fe59 100644 --- a/internal/compile/rows.go +++ b/internal/compile/rows.go @@ -239,7 +239,7 @@ func arrayJSON(ref string, c *introspect.Column) string { func (s *stmt) spatialArrayJSON(ref string) string { elem := s.alias("g") return fmt.Sprintf("CASE WHEN %s IS NULL THEN NULL ELSE (SELECT coalesce(json_agg(%s ORDER BY %s.o), '[]'::json) FROM (SELECT generate_subscripts(%s, 1) AS o) AS %s) END", - ref, postgis.OutputJSONSQL("("+ref+")["+elem+".o]"), elem, ref, elem) + ref, postgis.OutputSQL("("+ref+")["+elem+".o]", postgis.Output{JSON: true}), elem, ref, elem) } // exprJSON renders a scalar value expression for inclusion in the JSON @@ -254,7 +254,7 @@ func (s *stmt) exprJSON(ref string, c *introspect.Column) string { if postgis.FlavourOf(c.PGType).Spatial() { // PostGIS values render as WKB hex by default; the GeoJSON scalar // contract is a real JSON object. - return postgis.OutputJSONSQL(ref) + return postgis.OutputSQL(ref, postgis.Output{JSON: true}) } switch c.PGType { case "int8", "numeric", "money": diff --git a/internal/compile/spatial.go b/internal/compile/spatial.go index 5efefe3..3a6129d 100644 --- a/internal/compile/spatial.go +++ b/internal/compile/spatial.go @@ -12,7 +12,7 @@ import ( "github.com/suprbdev/pdbcore/postgis" ) -// spatialOp compiles one operator of a PostGIS filter (see postgis.Ops). +// spatialOp compiles one operator of a PostGIS filter (see postgis.Ops()). // // Every operand — GeoJSON geometry, bounding-box corner, distance — travels as // a bind parameter. The SQL text depends only on which operator was used and @@ -283,9 +283,9 @@ func (s *stmt) spatialFieldSQL(alias string, c *introspect.Column, f *ast.Field, return s.typedGeometryDigitsSQL(expr, digits, gt, f.SelectionSet, depth) } if digits != "" { - return postgis.OutputJSONPrecisionSQL(expr, digits), nil + return postgis.OutputSQL(expr, postgis.Output{JSON: true, Precision: digits}), nil } - return postgis.OutputJSONSQL(expr), nil + return postgis.OutputSQL(expr, postgis.Output{JSON: true}), nil } // spatialDerivedSQL renders a derived spatial accessor field (locationArea, @@ -295,7 +295,7 @@ func (s *stmt) spatialDerivedSQL(alias string, c *introspect.Column, suffix stri if !ok { return "", fmt.Errorf("compile: unknown spatial accessor %q", suffix) } - return d.JSONSQL(alias+"."+quoteIdent(c.Name), postgis.FlavourOf(c.PGType)), nil + return d.SQL(alias+"."+quoteIdent(c.Name), postgis.FlavourOf(c.PGType), postgis.Output{JSON: true}), nil } // rasterAccessorSQL renders a raster metadata accessor field (rastWidth, @@ -305,7 +305,7 @@ func (s *stmt) rasterAccessorSQL(alias string, c *introspect.Column, suffix stri if !ok { return "", fmt.Errorf("compile: unknown raster accessor %q", suffix) } - return a.JSONSQL(alias + "." + quoteIdent(c.Name)), nil + return a.SQL(alias+"."+quoteIdent(c.Name), postgis.Output{JSON: true}), nil } // rasterBand binds the 1-based band number of a raster field's band: diff --git a/internal/compile/typedgeo.go b/internal/compile/typedgeo.go index fb28654..7d30823 100644 --- a/internal/compile/typedgeo.go +++ b/internal/compile/typedgeo.go @@ -86,9 +86,9 @@ func (s *stmt) typedGeometrySQL(expr string, t geotype.Type, sel ast.SelectionSe // object (x, y, points, geojson, ...) carries the same precision. func (s *stmt) typedGeometryDigitsSQL(expr, digits string, t geotype.Type, sel ast.SelectionSet, depth int) (string, error) { ctx := geoCtx{dims: quoteLiteral(t.Dims.Suffix())} - geojson := postgis.OutputJSONSQL(geoValue + ".g") + geojson := postgis.OutputSQL(geoValue+".g", postgis.Output{JSON: true}) if digits != "" { - geojson = postgis.OutputJSONPrecisionSQL(geoValue+".g", digits) + geojson = postgis.OutputSQL(geoValue+".g", postgis.Output{JSON: true, Precision: digits}) } cols := fmt.Sprintf("%s AS j, ST_SRID(%s.g) AS srid", geojson, geoValue) if t.AnyDims { diff --git a/internal/config/config.go b/internal/config/config.go index d84c4b7..8eb60ad 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -11,7 +11,6 @@ import ( "strings" "time" - flag "github.com/spf13/pflag" "github.com/suprbdev/pdbcore/auth" "github.com/suprbdev/pdbcore/confx" pgcontrib "github.com/suprbdev/pdbcore/contrib" @@ -356,13 +355,21 @@ func DefaultConfig() Config { // ClaimHeaderPrefix is the default auth.headers.prefix. const ClaimHeaderPrefix = "X-Pdbq-Claim-" +// RemovedKeys maps pdbq keys removed before 1.0 without a replacement to +// the reason, so loading an old config says why the key is unknown. +var RemovedKeys = map[string]string{ + "transactions.mutations": "mutations always run in a transaction", + "plugins.settings.nested_mutations.force_transactions": "nested mutations always run in a transaction", +} + // Load builds the effective config: defaults, then optional YAML file, then -// PDBQ_* env vars, then flags (highest precedence), and validates it. Pass -// only the flags the user set (confx.ChangedFlags) so unset flags do not -// shadow YAML/env. Loading is strict: unknown keys in the file, and unknown -// PDBQ_* variables inside a config section, are errors naming the key they -// moved to or the closest valid key. -func Load(path string, flags *flag.FlagSet) (Config, error) { +// PDBQ_* env vars, then flags (highest precedence: koanf path to value, +// see confx.WithFlags), and validates it. Pass only the flags the user set +// (cliflags.Changed) so unset flags do not shadow YAML/env. Loading is +// strict: unknown keys in the file, and unknown PDBQ_* variables inside a +// config section, are errors naming the key they moved to, why they were +// removed, or the closest valid key. +func Load(path string, flags map[string]any) (Config, error) { cfg, err := LoadUnvalidated(path, flags) if err != nil { return cfg, err @@ -375,9 +382,9 @@ func Load(path string, flags *flag.FlagSet) (Config, error) { // LoadUnvalidated is Load without the final Validate, for callers that // override keys before validating (see [Config.ConnectionIdentity]). -func LoadUnvalidated(path string, flags *flag.FlagSet) (Config, error) { +func LoadUnvalidated(path string, flags map[string]any) (Config, error) { cfg := DefaultConfig() - if err := confx.Load("PDBQ_", path, flags, &cfg, confx.WithMoved(MovedKeys)); err != nil { + if err := confx.Load("PDBQ_", path, &cfg, confx.WithMoved(MovedKeys), confx.WithRemoved(RemovedKeys), confx.WithFlags(flags)); err != nil { return cfg, err } return cfg, nil @@ -395,6 +402,7 @@ func (c *Config) ConnectionIdentity() { // Validate checks cross-field invariants. func (c *Config) Validate() error { var errs []string + errs = append(errs, confx.ValidateDatabase(c.Database)...) errs = append(errs, confx.ValidateErrors(c.Errors)...) errs = append(errs, confx.ValidateIdentity(c.Auth, c.Roles, c.Claims)...) errs = append(errs, confx.ValidateTX(confx.TX{Isolation: c.TX.Isolation, MaxRetries: c.TX.MaxRetries})...) diff --git a/internal/config/example.go b/internal/config/example.go index 77fd2fc..d34868d 100644 --- a/internal/config/example.go +++ b/internal/config/example.go @@ -15,7 +15,11 @@ func ExampleYAML() string { b.WriteString("# Generated by `pdbq config example` from the config structs — reference, not for direct use.\n") b.WriteString("# Every key is also settable via env (PDBQ_SECTION_KEY, double underscore for '_' in names)\n") b.WriteString("# or command-line flags; precedence is flags > env > file.\n\n") - b.WriteString(confx.ExampleYAML(DefaultConfig())) + b.WriteString(confx.ExampleYAML(DefaultConfig(), + confx.WithDoc("schema.cache_path", "Boot from this schema cache file instead of introspecting (see pdbq schema dump)."), + confx.WithDoc("auth.headers.prefix", "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."), + confx.WithDoc("errors.detail", "'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)."), + )) return b.String() } diff --git a/internal/config/regroup_test.go b/internal/config/regroup_test.go index b54cd6e..a1cb33b 100644 --- a/internal/config/regroup_test.go +++ b/internal/config/regroup_test.go @@ -58,12 +58,15 @@ func TestMovedKeysFromEnv(t *testing.T) { } func TestRemovedKeysRejected(t *testing.T) { - for _, yaml := range []string{ - "transactions:\n mutations: true\n", - "plugins:\n settings:\n nested_mutations:\n force_transactions: true\n", + for yaml, want := range map[string]string{ + "transactions:\n mutations: true\n": "unknown key transactions.mutations: removed: mutations always run in a transaction", + "plugins:\n settings:\n nested_mutations:\n force_transactions: true\n": "unknown key plugins.settings.nested_mutations.force_transactions: removed: nested mutations always run in a transaction", } { - wantLoadError(t, writeConfig(t, "auth:\n jwt:\n secret: s\n"+yaml), "unknown key") + wantLoadError(t, writeConfig(t, "auth:\n jwt:\n secret: s\n"+yaml), want) } + t.Setenv("PDBQ_AUTH_JWT_SECRET", "s") + t.Setenv("PDBQ_TRANSACTIONS_MUTATIONS", "false") + wantLoadError(t, "", "unknown environment variable PDBQ_TRANSACTIONS_MUTATIONS (transactions.mutations): removed: mutations always run in a transaction") } func TestRegroupedKeysLoad(t *testing.T) { @@ -143,3 +146,17 @@ func TestRegroupDefaults(t *testing.T) { t.Errorf("incremental.max_responses %d, transactions.partial %+v", cfg.Incremental.MaxResponses, cfg.TX.Partial) } } + +func TestDoubledUnderscoreAfterSectionRejected(t *testing.T) { + t.Setenv("PDBQ_AUTH_JWT_SECRET", "s") + t.Setenv("PDBQ_ROLES__ALLOWED", "app_user") + wantLoadError(t, "", "unknown environment variable PDBQ_ROLES__ALLOWED (roles_allowed): did you mean PDBQ_ROLES_ALLOWED?") +} + +func TestSharedDurationsValidated(t *testing.T) { + t.Setenv("PDBQ_AUTH_JWT_SECRET", "s") + t.Setenv("PDBQ_DATABASE_CONNECT__TIMEOUT", "0s") + t.Setenv("PDBQ_WATCH_ENABLED", "true") + t.Setenv("PDBQ_WATCH_POLL__INTERVAL", "0s") + wantLoadError(t, "", "database.connect_timeout must be > 0", "watch.poll_interval must be > 0") +} diff --git a/internal/exec/exec.go b/internal/exec/exec.go index 6d7cfc4..c92d84d 100644 --- a/internal/exec/exec.go +++ b/internal/exec/exec.go @@ -1497,7 +1497,11 @@ func (e *Executor) gqlError(err error, f *ast.Field) *gqlerror.Error { ext["table"] = pgErr.TableName ext["constraint"] = pgErr.ConstraintName } else { - msg = pgexec.SanitizeMessage(pgErr, e.Opts.StrictErrors) + detail := pgexec.Prod + if e.Opts.StrictErrors { + detail = pgexec.Strict + } + msg = pgexec.Classify(pgErr, detail).Message if e.Built != nil && !e.Opts.StrictErrors { msg = integrityMessage(e.Built.Catalog, pgErr, msg) } diff --git a/internal/omit/omit.go b/internal/omit/omit.go index d41f84a..5703b67 100644 --- a/internal/omit/omit.go +++ b/internal/omit/omit.go @@ -60,47 +60,15 @@ const ( // Hides reports whether the smart tags in comment hide their object from // action a: a bare @omit, an @omit listing a, or the @behavior token // mapping to a (-select, -insert, -update, -delete, the PostGraphile V5 -// -filterBy and -orderBy, and their deprecated forms -filter and -order). +// -filterBy and -orderBy, and their deprecated forms -filter and -order; +// see smarttags.Tags.Omits). func Hides(comment string, a Action) bool { if !strings.Contains(comment, "@") { return false } tags, _ := smarttags.Parse(comment) actions, everything := tags.Omits() - if everything || actions[string(a)] { - return true - } - for _, v := range tags.All("behavior") { - for _, tok := range smarttags.SplitList(v) { - if BehaviorActions[strings.ToLower(tok)] == a { - return true - } - } - } - return false -} - -// BehaviorActions maps the negative @behavior tokens that hide an object -// from an action, lowercased, to that action. pdbcore's smarttags.Omits -// maps the rest of them (and the deprecated -filter and -order, see -// [DeprecatedBehaviors]); pdbq adds PostGraphile V5's -filterBy and -// -orderBy. -var BehaviorActions = map[string]Action{ - "-select": Read, - "-insert": Create, - "-update": Update, - "-delete": Delete, - "-filterby": Filter, - "-orderby": Order, - "-filter": Filter, - "-order": Order, -} - -// DeprecatedBehaviors maps the deprecated @behavior tokens, lowercased, to -// the PostGraphile V5 token replacing them. -var DeprecatedBehaviors = map[string]string{ - "-filter": "-filterBy", - "-order": "-orderBy", + return everything || actions[string(a)] } // Everything reports whether comment carries a bare @omit. diff --git a/internal/plugins/contrib/headline_test.go b/internal/plugins/contrib/headline_test.go index 359b73e..e2f5069 100644 --- a/internal/plugins/contrib/headline_test.go +++ b/internal/plugins/contrib/headline_test.go @@ -88,7 +88,10 @@ func TestHeadlineOmitAndContracts(t *testing.T) { cat = contribfixture.Catalog() cat.Table("public", "documents").Column("title").Comment = "@behavior -contract:public" cat.Table("public", "documents").Column("keywords").Comment = "@behavior -contract:public" - view, _ := contract.Contract{Name: "public"}.View(cat) + view, _, err := contract.Contract{Name: "public"}.View(cat) + if err != nil { + t.Fatal(err) + } b = buildWith(t, view, nil, true, true) if b.Objects["Document"].Field("keywordsHeadline") != nil { t.Error("a column hidden by the contract kept its headline") diff --git a/internal/plugins/postgis/postgis.go b/internal/plugins/postgis/postgis.go index 418dce2..8d9b09c 100644 --- a/internal/plugins/postgis/postgis.go +++ b/internal/plugins/postgis/postgis.go @@ -313,12 +313,12 @@ func (p *Plugin) ensureOpsInput(b *schema.Builder) { "Bounding-box operators and dwithin can use a GiST index; the exact " + "predicates are precise but scan more rows.", } - for _, op := range postgis.Ops { + for _, op := range postgis.Ops() { desc := op.Description - if op.Index { + if op.Indexable { desc += " Index-usable." } - in.AddField(&schema.InputField{Name: op.Name, Type: op.Arg, Description: desc}) + in.AddField(&schema.InputField{Name: op.Name, Type: op.OperandType, Description: desc}) } b.Inputs[opsInputName] = in } @@ -337,7 +337,7 @@ func (p *Plugin) addDerivedFields(b *schema.Builder, t *introspect.Table, cols [ continue } base := b.Inflect(inflect.KindFieldName, inflect.Input{Schema: t.Schema, Table: t.Name, Column: c.Name}) - for _, d := range postgis.Deriveds { + for _, d := range postgis.Deriveds() { if !derivedApplies(d, c) { continue } @@ -710,7 +710,7 @@ func (rb *rasterBuild) addFields(t *introspect.Table, cols []*introspect.Column) continue } base := b.Inflect(inflect.KindFieldName, inflect.Input{Schema: t.Schema, Table: t.Name, Column: c.Name}) - for _, a := range postgis.RasterAccessors { + for _, a := range postgis.RasterAccessors() { add(&schema.Field{ Name: base + a.Suffix, Type: a.Type, Description: a.Description, Meta: &schema.FieldMeta{Kind: schema.KindRasterAccessor, Table: t, Column: c, Nested: map[string]any{"suffix": a.Suffix}}, diff --git a/internal/plugins/postgis/raster_test.go b/internal/plugins/postgis/raster_test.go index 96f513d..0ff374f 100644 --- a/internal/plugins/postgis/raster_test.go +++ b/internal/plugins/postgis/raster_test.go @@ -60,7 +60,7 @@ func TestRasterFields(t *testing.T) { if obj.Field("rast") != nil || obj.Field("mask") != nil { t.Error("raster columns have an output field") } - for _, a := range postgis.RasterAccessors { + for _, a := range postgis.RasterAccessors() { f := obj.Field("rast" + a.Suffix) if f == nil || f.Type != a.Type || f.Meta.Kind != schema.KindRasterAccessor || f.Meta.Nested["suffix"] != a.Suffix { t.Errorf("rast%s: %+v", a.Suffix, f) diff --git a/internal/plugins/smartcomments/validate.go b/internal/plugins/smartcomments/validate.go index 5813a5b..309a7e0 100644 --- a/internal/plugins/smartcomments/validate.go +++ b/internal/plugins/smartcomments/validate.go @@ -4,16 +4,21 @@ import ( "strings" "github.com/suprbdev/pdbcore/introspect" + "github.com/suprbdev/pdbcore/smartcomments/catalog" "github.com/suprbdev/pdbcore/smarttags" "github.com/suprbdev/pdbq/internal/omit" ) -// omitActions are the @omit actions pdbq honours (package omit), lowercased -// as smarttags.Omits reads them. -var omitActions = map[string]bool{ - string(omit.Read): true, string(omit.Create): true, string(omit.Update): true, string(omit.Delete): true, - string(omit.Filter): true, string(omit.Order): true, string(omit.Many): true, string(omit.All): true, - string(omit.Aggregates): true, +// vocabulary is what pdbq honours: the @omit actions of package omit, and +// on top of pdbcore's omit and contract tokens, the @behavior tokens of the +// aggregates plugin. +var vocabulary = smarttags.Vocabulary{ + OmitActions: []string{ + string(omit.Read), string(omit.Create), string(omit.Update), string(omit.Delete), + string(omit.Filter), string(omit.Order), string(omit.Many), string(omit.All), + string(omit.Aggregates), + }, + Behavior: aggregatesBehavior, } // aggregatesBehaviors are the @behavior tokens of the aggregates plugin, @@ -31,100 +36,15 @@ var ( } ) -// knownBehavior reports whether pdbq honours the @behavior token tok: an -// omit token of [omit.BehaviorActions] (any case), an aggregates token, or -// a schema-contract token (±contract:, contract:). -func knownBehavior(tok string) bool { - if _, ok := omit.BehaviorActions[strings.ToLower(tok)]; ok { - return true - } - if aggregatesColumnBehaviors[tok] || aggregatesTableBehaviors[strings.TrimLeft(tok, "+-")] { - return true - } - rest := tok - if rest != "" && (rest[0] == '+' || rest[0] == '-') { - rest = rest[1:] - } - name, ok := strings.CutPrefix(strings.ToLower(rest), "contract:") - return ok && name != "" +func aggregatesBehavior(tok string) bool { + return aggregatesColumnBehaviors[tok] || aggregatesTableBehaviors[strings.TrimLeft(tok, "+-")] } // validateTags notes a warning for every unknown @omit action, unknown // @behavior token and deprecated @behavior token in the comments of the -// catalog's objects, once per object and token. +// catalog's objects, once per object and token (see catalog.Check). func (p *Plugin) validateTags(c *introspect.Catalog) { - for _, t := range c.Tables { - kind := "table" - if t.Kind != introspect.RelTable { - kind = "view" - } - key := tableKey(t.Schema, t.Name) - p.validateComment(kind, key, t.Comment) - for _, col := range t.Columns { - p.validateComment("column", key+"."+col.Name, col.Comment) - } - for _, fk := range t.ForeignKeys { - p.validateComment("constraint", key+"."+fk.Name, fk.Comment) - } - cons := append([]*introspect.Constraint{t.PrimaryKey}, t.Uniques...) - for _, con := range cons { - if con != nil { - p.validateComment("constraint", key+"."+con.Name, con.Comment) - } - } - } - for _, ct := range c.Composites { - key := tableKey(ct.Schema, ct.Name) - for _, f := range ct.Fields { - p.validateComment("column", key+"."+f.Name, f.Comment) - } - } - for _, f := range c.Functions { - p.validateComment("function", tableKey(f.Schema, f.Name), f.Comment) - } - for _, e := range c.Enums { - p.validateComment("enum", tableKey(e.Schema, e.Name), e.Comment) - } - for _, d := range c.Domains { - p.validateComment("domain", tableKey(d.Schema, d.Name), d.Comment) - } -} - -// validateComment checks the @omit and @behavior tags of one object's -// comment. -func (p *Plugin) validateComment(kind, name, comment string) { - if !strings.Contains(comment, "@") { - return - } - tags, _ := smarttags.Parse(comment) - seen := map[string]bool{} - once := func(tok string) bool { - if seen[tok] { - return false - } - seen[tok] = true - return true - } - for _, v := range tags.All("omit") { - for _, a := range smarttags.SplitList(v) { - if !omitActions[strings.ToLower(a)] && once("omit "+a) { - p.note("smart_comments: unknown @omit action ignored", kind, name, "action", a) - } - } - } - for _, v := range tags.All("behavior") { - for _, tok := range smarttags.SplitList(v) { - switch { - case !knownBehavior(tok): - if once("behavior " + tok) { - p.note("smart_comments: unknown @behavior token ignored", kind, name, "token", tok) - } - case omit.DeprecatedBehaviors[strings.ToLower(tok)] != "": - if once("behavior " + tok) { - p.note("smart_comments: deprecated @behavior token", kind, name, "token", tok, - "use", omit.DeprecatedBehaviors[strings.ToLower(tok)]) - } - } - } + for _, f := range catalog.Check(c, vocabulary) { + p.note("smart_comments: "+f.Message(), f.Args()...) } } diff --git a/internal/schema/types.go b/internal/schema/types.go index 764269e..c29c2c9 100644 --- a/internal/schema/types.go +++ b/internal/schema/types.go @@ -77,7 +77,7 @@ const ( KindContribDerived FieldKind = "contrib_derived" // KindRasterAccessor is a metadata accessor of a postgis_raster column // (postgis plugin): Width, Srid, Envelope, ..., - // named by Meta.Nested["suffix"] (see postgis.RasterAccessors). + // named by Meta.Nested["suffix"] (see postgis.RasterAccessors()). KindRasterAccessor FieldKind = "raster_accessor" // KindRasterValue is Value(point:, band:) of a raster column // (postgis plugin): the pixel value of a band at a point (ST_Value). diff --git a/pdbq.go b/pdbq.go index 97be0a2..9ec3ae2 100644 --- a/pdbq.go +++ b/pdbq.go @@ -388,7 +388,10 @@ func (a *App) BuildContractSchema(ctx context.Context, cat *introspect.Catalog, if err != nil { return nil, err } - view, sum := ct.Spec().View(cat) + view, sum, err := ct.Spec().View(cat) + if err != nil { + return nil, err + } a.Log.Debug("contract view", "contract", name, "hidden_tables", sum.Tables, "hidden_columns", sum.Columns, "hidden_functions", sum.Functions, "hidden_foreign_keys", sum.ForeignKeys) built, err := a.BuildSchema(ctx, view) @@ -411,7 +414,10 @@ func (a *App) executor(built *schema.Built, instruments *exec.Metrics) *exec.Exe for _, h := range a.Registry.RequestHooks(disabled) { hooks = append(hooks, h) } - iso := pgexec.ParseIsolation(a.Config.TX.Isolation) + iso, err := pgexec.ParseIsolation(a.Config.TX.Isolation) + if err != nil { + a.Log.Error("invalid transactions.isolation; transactions use the server's default isolation", "err", err) + } return exec.New(a.pool, built, compileFn, hooks, exec.Options{ MaxDepth: a.Config.Limits.MaxDepth, MaxCost: a.Config.Limits.MaxCost,