diff --git a/CHANGELOG.md b/CHANGELOG.md index a2b14ee..84e0af3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,7 +22,23 @@ becomes the release notes of the next tag. that decides `has_next` reads only the root. Applies to `SETOF ` RPCs too. -### Fixes +### Changed + +- `@behavior -filterBy` / `-orderBy` (PostGraphile V5) are honoured; `-filter` + / `-order` still work with a deprecation warning. Unknown `@omit` actions + and `@behavior` tokens are reported at build time, with pdbq's vocabulary + shared through pdbcore ([upgrading](docs/upgrading.md#smart-tags-config-messages-and-embedding-api-pdbcore-api-hygiene)). +- Removed config keys name the reason they were removed; `PDBR_*` variables + that double the underscore after a section are errors with a did-you-mean + hint; `transactions.isolation` errors name the accepted values; + `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. +- `pdbr.LoadConfig` takes command-line values as `map[string]any` instead of + a `*pflag.FlagSet`. +- Built against pdbcore's API hygiene changes (see its changelog). + +### Fixed - CSV output keeps carriage returns and line feeds inside values byte for byte (quoted, RFC 4180); a bare `\r` was dropped and `\n` became `\r\n`. @@ -33,6 +49,9 @@ becomes the release notes of the next tag. forms. `select=*` still returns it and a JSON body still writes it. - `401`/`403` answers from authentication carry `Vary: Accept` like every other API response. +- A live boot no longer alphabetises `schema.schemas`: the bare + `/{table}` and `/rpc/{fn}` aliases come from the first configured schema, + as on a schema-cache boot. ### Breaking diff --git a/cmd/pdbr/main.go b/cmd/pdbr/main.go index c58f6d0..ef42e91 100644 --- a/cmd/pdbr/main.go +++ b/cmd/pdbr/main.go @@ -16,6 +16,7 @@ import ( "github.com/suprbdev/pdbcore/cache" "github.com/suprbdev/pdbcore/confx" + "github.com/suprbdev/pdbcore/confx/cliflags" "github.com/suprbdev/pdbcore/contrib" "github.com/suprbdev/pdbcore/introspect" @@ -108,14 +109,14 @@ func loadConfigRaw(cmd *cobra.Command) (config.Config, error) { // the flags named after a config path (configFlags), leaving out --config // and command options such as --cache or --print-sql, which strict loading // would reject as unknown keys. -func changedConfigFlags(cmd *cobra.Command) *pflag.FlagSet { +func changedConfigFlags(cmd *cobra.Command) map[string]any { var local []string cmd.Flags().VisitAll(func(f *pflag.Flag) { if !strings.Contains(f.Name, ".") { local = append(local, f.Name) } }) - return confx.ChangedFlags(cmd.Flags(), local...) + return cliflags.Changed(cmd.Flags(), local...) } // loadConnectionConfig loads the config of a command that serves no HTTP diff --git a/docs/configuration.md b/docs/configuration.md index 9e01e1a..8f134a7 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -70,8 +70,8 @@ See [cli.md](cli.md) for details. | Key | Type | Default | Notes | |---|---|---|---| | `database.url` | string | — | required; standard `PG*` env vars are honoured when empty | -| `database.max_conns` | int | 10 | maximum pooled connections; each request uses at most one | -| `database.connect_timeout` | duration | `10s` | timeout for establishing a connection | +| `database.max_conns` | int | 10 | maximum pooled connections; each request uses at most one; `0` uses the pgx pool default, negative is an error | +| `database.connect_timeout` | duration | `10s` | timeout for establishing a connection; must be positive | | `database.statement_timeout` | duration | `25s` | per-statement timeout on every request (`0` disables); expiry → `504 pg:57014`. Keep it below `server.request_timeout` (`30s`) so a slow statement fails with a database timeout the client can act on before the request itself is cut off | | `server.addr` | string | `:8080` | listen address | | `server.base_path` | string | `""` | prefix for every API route, e.g. `/api`; `""` (the default, as in PostgREST) mounts the API at the root. `/healthz` and `/readyz` are never prefixed | @@ -126,7 +126,7 @@ See [cli.md](cli.md) for details. | `transactions.partial.enabled` | bool | `false` | let a bulk `POST` or `PUT` opt in with `Prefer: partial=items` to running each element in its own savepoint: a failing element is reported without rolling back the others, answered as a per-element report (`207` when one failed). Not honoured for `PATCH`, `DELETE` or a single object. See [mutations.md](mutations.md#partial-success-for-bulk-writes) | | `transactions.partial.max_items` | int | `1000` | most elements a bulk body may carry with `Prefer: partial=items` (each element is its own statement and savepoint); more answers `413 body_too_large` | | `watch.enabled` | bool | `false` | dev only; refuses to combine with cache | -| `watch.poll_interval` | duration | `5s` | fallback polling when event triggers can't be installed | +| `watch.poll_interval` | duration | `5s` | fallback polling when event triggers can't be installed; must be positive when `watch.enabled` | | `watch.channel` | string | `pdbr_ddl` | NOTIFY channel used by the DDL event trigger | | `errors.detail` | string | `prod` | `dev` adds full PG detail + `pg` object to problems; `strict` hides even constraint-violation messages | | `plugins.disabled` | []string | `[]` | built-in plugins to disable: `smart_comments`, `advanced_filters`, `postgis`, `nested_mutations` (other names are rejected); see [plugins.md](plugins.md) | diff --git a/docs/smart-comments.md b/docs/smart-comments.md index 57cf90a..1113843 100644 --- a/docs/smart-comments.md +++ b/docs/smart-comments.md @@ -35,10 +35,17 @@ Parsing rules (`pdbcore/smarttags.Parse`): - List-valued tags (`@omit`, `@primaryKey`, `@unique`, `@behavior`) split on commas and whitespace: `@omit create, update` ≡ `@omit create update`. `@omit` actions are lower-cased. -- `@behavior` (PostGraphile V5 style) contributes only its **negative** - tokens, mapped onto `@omit` actions: `-insert` → `create`, `-update` → - `update`, `-delete` → `delete`, `-select` → `read`, `-filter` → `filter`, - `-order` → `order`; other tokens are ignored. +- `@behavior` (PostGraphile V5 style) contributes its **negative** omit + tokens, mapped onto `@omit` actions (matched case-insensitively): + `-insert` → `create`, `-update` → `update`, `-delete` → `delete`, + `-select` → `read`, `-filterBy` → `filter`, `-orderBy` → `order`, and the + contract tokens (`±contract:`, see [Contracts](#contracts)). + The older `-filter` and `-order` still work but are deprecated. +- Unknown `@omit` actions (`@omit reed`) and unknown `@behavior` tokens are + ignored with a build-time warning naming the object and the token, and a + deprecated `@behavior` token warns with its replacement + (`smart_comments: deprecated @behavior token column=app.users.email token=-filter use=-filterBy`). + pdbq reads and checks the same tokens. Disable everything with `plugins.disabled: [smart_comments]` (see [What survives without the plugin](#what-survives-without-the-plugin)). diff --git a/docs/upgrading.md b/docs/upgrading.md index 6cdee80..1bcbe91 100644 --- a/docs/upgrading.md +++ b/docs/upgrading.md @@ -435,3 +435,20 @@ below is breaking; the old spellings are `400` errors (`invalid_filter`, | no `Vary` from the API | `Vary: Accept` | added to `Vary: Origin` / `Accept-Encoding` | | `/{schema}/rpc/{pk}` = row of a table named `rpc` when no such function exists | always the function (`404` without one) | the table keeps its list and `/by/` routes | | `pdbr request` runs as the connection role | same by default; `--role`, `--claims` | `--print-sql` output is unchanged by them | + +### Smart tags, config messages and embedding API (pdbcore API hygiene) + +| Before | Now | Notes | +|---|---|---| +| `@behavior -filterBy` / `-orderBy` were ignored | honoured as `@omit filter` / `@omit order` (PostGraphile V5 spellings, as in pdbq) | `-filter` / `-order` still work with a build-time deprecation warning naming `-filterBy` / `-orderBy` | +| 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; pdbq checks the same tokens | +| a live boot alphabetised `schema.schemas` (a cache boot did not), so the bare `/{table}` and `/rpc/{fn}` aliases could come from another schema than the first one listed | the bare aliases always come from `schema.schemas[0]` | check deployments that listed schemas out of alphabetical order: their bare paths change on a live boot | +| `PDBR_ROLES__ALLOWED` (doubled underscore after the section) was ignored | `unknown environment variable PDBR_ROLES__ALLOWED (roles_allowed): did you mean PDBR_ROLES_ALLOWED?` | any section | +| `transactions.mutations`: `unknown key transactions.mutations` | `unknown key transactions.mutations: removed: every write runs in a transaction` | also `plugins.settings.nested_mutations.force_transactions` | +| `transactions.isolation: "x" invalid` | `transactions.isolation: "x" is not 'read_committed', 'repeatable_read' or 'serializable'` | | +| `database.connect_timeout: 0` waited forever; negative `max_conns` / `statement_timeout`, `auth.jwt.jwks_cache_ttl: 0` with a JWKS URL (one hour) and `watch.poll_interval: 0` (a crash of the polling fallback) were accepted | config errors | `database.max_conns: 0` still means the pgx pool default | + +**Embedding.** `pdbr.LoadConfig(path, flags)` takes 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`. diff --git a/examples/pdbr.example.yaml b/examples/pdbr.example.yaml index a9b7348..01b03f1 100644 --- a/examples/pdbr.example.yaml +++ b/examples/pdbr.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" @@ -148,7 +148,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: "pdbr_ddl" diff --git a/facade.go b/facade.go index 0772dfb..b33ea27 100644 --- a/facade.go +++ b/facade.go @@ -4,8 +4,6 @@ package pdbr import ( - flag "github.com/spf13/pflag" - "github.com/suprbdev/pdbcore/confx" coreinflect "github.com/suprbdev/pdbcore/inflect" "github.com/suprbdev/pdbcore/introspect" @@ -48,8 +46,10 @@ type ( func DefaultConfig() Config { return config.DefaultConfig() } // LoadConfig builds the effective config: defaults < YAML < PDBR_* env < -// flags (nil flags is fine) and validates it. -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), +// and validates it. +func LoadConfig(path string, flags map[string]any) (Config, error) { return config.Load(path, flags) } diff --git a/go.mod b/go.mod index 5f8fb59..04bce76 100644 --- a/go.mod +++ b/go.mod @@ -9,7 +9,7 @@ require ( github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 github.com/spf13/cobra v1.10.2 github.com/spf13/pflag v1.0.10 - github.com/suprbdev/pdbcore v0.18.0 + github.com/suprbdev/pdbcore v0.19.0 go.yaml.in/yaml/v3 v3.0.5 golang.org/x/sync v0.23.0 ) @@ -27,7 +27,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/mitchellh/copystructure v1.2.0 // indirect github.com/mitchellh/reflectwalk v1.0.2 // indirect diff --git a/go.sum b/go.sum index e4f8ba4..27897fa 100644 --- a/go.sum +++ b/go.sum @@ -34,8 +34,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= @@ -68,8 +66,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= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ= diff --git a/internal/compile/aggregate.go b/internal/compile/aggregate.go index 1923e69..a72e46b 100644 --- a/internal/compile/aggregate.go +++ b/internal/compile/aggregate.go @@ -343,7 +343,7 @@ func aggregateJSON(ref string, a *plan.Aggregate) string { case a.OutputCast != nil: return "to_json((" + ref + ")::" + typeRefSQL(a.OutputCast) + ")" case a.Func.Spatial(): - return postgis.OutputJSONSQL(ref) + return postgis.OutputSQL(ref, postgis.Output{JSON: true}) } return "to_json(" + ref + ")" } diff --git a/internal/compile/filter.go b/internal/compile/filter.go index cd08af1..bd62f04 100644 --- a/internal/compile/filter.go +++ b/internal/compile/filter.go @@ -822,7 +822,7 @@ func spatialOpName(op plan.Op) (string, bool) { return "", false } name = strings.ReplaceAll(strings.TrimPrefix(name, "st_"), "_", "") - for _, o := range postgis.Ops { + for _, o := range postgis.Ops() { if o.Kind() != postgis.ArgBoolean && strings.ToLower(o.Name) == name { return o.Name, true } diff --git a/internal/compile/raster.go b/internal/compile/raster.go index a8b3039..252c01d 100644 --- a/internal/compile/raster.go +++ b/internal/compile/raster.go @@ -24,11 +24,11 @@ func (s *stmt) rasterPseudoSQL(p *api.PseudoColumn, args map[string]any, alias s case err != nil: return "", err case !ok: - return rv.Accessor.JSONSQL(ref), nil + return rv.Accessor.SQL(ref, postgis.Output{JSON: true}), nil case rv.Accessor.Suffix != "Envelope": return "", errUser(CodeInvalidSelect, "precision applies to GeoJSON values; %s is not one", p.Key) } - return postgis.OutputJSONPrecisionSQL("ST_Envelope("+ref+")", digits), nil + return postgis.OutputSQL("ST_Envelope("+ref+")", postgis.Output{JSON: true, Precision: digits}), nil case rv.Value: if s.plan.Near == nil { return "", errUser(CodeInvalidParameter, "%s requires ~near=", p.Key) diff --git a/internal/compile/rows.go b/internal/compile/rows.go index cba1921..8dc7d1b 100644 --- a/internal/compile/rows.go +++ b/internal/compile/rows.go @@ -353,7 +353,7 @@ func (s *stmt) renderedRef(alias string, c *introspect.Column) string { // verbatim. func (s *stmt) exprJSON(ref string, c *introspect.Column) string { if postgis.IsSpatial(c.PGType) { - return postgis.OutputJSONSQL(ref) + return postgis.OutputSQL(ref, postgis.Output{JSON: true}) } if v, ok := api.DistanceOnly(s.catalog(), c); ok && v.Codec != nil { return v.Codec.OutputJSONSQL(ref) @@ -372,7 +372,7 @@ func (s *stmt) exprJSON(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) %s) END", - ref, postgis.OutputJSONSQL("("+ref+")["+elem+".o]"), elem, ref, elem) + ref, postgis.OutputSQL("("+ref+")["+elem+".o]", postgis.Output{JSON: true}), elem, ref, elem) } // spatialFieldSQL renders a selected spatial column, applying the optional @@ -385,9 +385,9 @@ func (s *stmt) spatialFieldSQL(ref string, c *introspect.Column, args map[string } digits, ok, err := s.precisionArg(args) if err != nil || !ok { - return postgis.OutputJSONSQL(expr), err + return postgis.OutputSQL(expr, postgis.Output{JSON: true}), err } - return postgis.OutputJSONPrecisionSQL(expr, digits), nil + return postgis.OutputSQL(expr, postgis.Output{JSON: true, Precision: digits}), nil } // spatialArgs applies buffer=, then simplify=, then transform= to a spatial @@ -473,16 +473,16 @@ func (s *stmt) pseudoJSON(f *plan.FieldSel, alias string) (string, error) { return "", err } if ok { - return d.JSONPrecisionSQL(expr, flavour, digits), nil + return d.SQL(expr, flavour, postgis.Output{JSON: true, Precision: digits}), nil } - return d.JSONSQL(expr, flavour), nil + return d.SQL(expr, flavour, postgis.Output{JSON: true}), nil } // derivedFor matches an accessor name ("area", "geometry_type", // "GeometryType") against the pdbcore accessor table. func derivedFor(accessor string) (postgis.Derived, bool) { want := strings.ToLower(strings.ReplaceAll(accessor, "_", "")) - for _, d := range postgis.Deriveds { + for _, d := range postgis.Deriveds() { if strings.ToLower(d.Suffix) == want { return d, true } diff --git a/internal/compile/rpc.go b/internal/compile/rpc.go index 5cf754e..363c9f7 100644 --- a/internal/compile/rpc.go +++ b/internal/compile/rpc.go @@ -175,7 +175,7 @@ func (s *stmt) valueJSON(ref string, fn *introspect.Function, depth int) (string return "to_json(" + ref + ")", nil } if postgis.IsSpatial(ret.PGType) { - return postgis.OutputJSONSQL(ref), nil + return postgis.OutputSQL(ref, postgis.Output{JSON: true}), nil } return "to_json(" + s.exprJSON(ref, ret) + ")", nil } diff --git a/internal/config/config.go b/internal/config/config.go index 5569c61..653a2be 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -13,8 +13,6 @@ import ( "strings" "time" - flag "github.com/spf13/pflag" - "github.com/suprbdev/pdbcore/auth" "github.com/suprbdev/pdbcore/confx" "github.com/suprbdev/pdbcore/contrib" @@ -206,13 +204,21 @@ func DefaultConfig() Config { } } +// RemovedKeys maps pdbr 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": "every write runs in a transaction", + "plugins.settings.nested_mutations.force_transactions": "nested writes always run in a transaction", +} + // Load builds the effective config: defaults, then the optional YAML file, -// then PDBR_* env vars, then flags (highest precedence), and validates it. -// Pass only the flags the user actually set (confx.ChangedFlags). Loading -// is strict: unknown keys in the file, and unknown PDBR_* variables inside -// a config section, are errors naming the key they moved to or the +// then PDBR_* env vars, then flags (highest precedence: koanf path to +// value, see confx.WithFlags), and validates it. Pass only the flags the +// user actually set (cliflags.Changed). Loading is strict: unknown keys in +// the file, and unknown PDBR_* variables inside a config section, are +// errors naming the key they moved to, why they were removed, or the // closest valid one. -func Load(path string, flags *flag.FlagSet) (Config, error) { +func Load(path string, flags map[string]any) (Config, error) { cfg, err := LoadUnvalidated(path, flags) if err != nil { return cfg, err @@ -222,9 +228,9 @@ func Load(path string, flags *flag.FlagSet) (Config, error) { // LoadUnvalidated is Load without the final Validate, for callers that // adjust the config first (UseConnectionIdentity) and then validate it. -func LoadUnvalidated(path string, flags *flag.FlagSet) (Config, error) { +func LoadUnvalidated(path string, flags map[string]any) (Config, error) { cfg := DefaultConfig() - err := confx.Load(EnvPrefix, path, flags, &cfg, confx.WithMoved(MovedKeys)) + err := confx.Load(EnvPrefix, path, &cfg, confx.WithMoved(MovedKeys), confx.WithRemoved(RemovedKeys), confx.WithFlags(flags)) return cfg, err } @@ -241,6 +247,7 @@ func (c *Config) UseConnectionIdentity() { // violations together. 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/config_test.go b/internal/config/config_test.go index 24b9023..07e7636 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -12,6 +12,7 @@ import ( "github.com/suprbdev/pdbcore/auth" "github.com/suprbdev/pdbcore/confx" + "github.com/suprbdev/pdbcore/confx/cliflags" ) func valid() Config { @@ -355,7 +356,7 @@ roles: if err := fs.Parse([]string{"--server.addr=:5555"}); err != nil { t.Fatal(err) } - cfg, err := Load(path, confx.ChangedFlags(fs, "config")) + cfg, err := Load(path, cliflags.Changed(fs, "config")) if err != nil { t.Fatal(err) } @@ -627,7 +628,7 @@ func TestLoadRemovedKeys(t *testing.T) { } { t.Run(name, func(t *testing.T) { _, err := Load(writeConfig(t, "auth:\n mode: none\nroles:\n switch: false\n"+yaml), nil) - if err == nil || !strings.Contains(err.Error(), "unknown key "+name) { + if err == nil || !strings.Contains(err.Error(), "unknown key "+name+": removed: "+RemovedKeys[name]) { t.Fatalf("err = %v", err) } }) @@ -635,7 +636,7 @@ func TestLoadRemovedKeys(t *testing.T) { t.Setenv("PDBR_AUTH_MODE", "none") t.Setenv("PDBR_ROLES_SWITCH", "false") t.Setenv("PDBR_TRANSACTIONS_MUTATIONS", "false") - if _, err := Load("", nil); err == nil || !strings.Contains(err.Error(), "unknown environment variable PDBR_TRANSACTIONS_MUTATIONS") { + if _, err := Load("", nil); err == nil || !strings.Contains(err.Error(), "unknown environment variable PDBR_TRANSACTIONS_MUTATIONS (transactions.mutations): removed: every write runs in a transaction") { t.Fatalf("env err = %v", err) } } @@ -719,7 +720,7 @@ transactions: if err := fs.Parse([]string{"--transactions.end=commit", "--transactions.partial.max_items=9", "--openapi.enabled=true"}); err != nil { t.Fatal(err) } - cfg, err = Load("", confx.ChangedFlags(fs, "config")) + cfg, err = Load("", cliflags.Changed(fs, "config")) if err != nil { t.Fatal(err) } @@ -727,3 +728,27 @@ transactions: t.Errorf("flags = %+v %+v", cfg.TX, cfg.OpenAPI) } } + +func TestLoadDoubledUnderscoreAfterSection(t *testing.T) { + t.Setenv("PDBR_AUTH_MODE", "none") + t.Setenv("PDBR_ROLES_SWITCH", "false") + t.Setenv("PDBR_MUTATIONS__ALLOW__UNFILTERED", "true") + _, err := Load("", nil) + if want := "unknown environment variable PDBR_MUTATIONS__ALLOW__UNFILTERED (mutations_allow_unfiltered): did you mean PDBR_MUTATIONS_ALLOW__UNFILTERED?"; err == nil || !strings.Contains(err.Error(), want) { + t.Fatalf("err = %v, want %q", err, want) + } +} + +func TestValidateSharedDurations(t *testing.T) { + cfg := DefaultConfig() + cfg.UseConnectionIdentity() + cfg.Database.ConnectTimeout = 0 + cfg.Watch.Enabled = true + cfg.Watch.PollInterval = 0 + err := cfg.Validate() + for _, want := range []string{"database.connect_timeout must be > 0", "watch.poll_interval must be > 0"} { + if err == nil || !strings.Contains(err.Error(), want) { + t.Errorf("err = %v, want %q", err, want) + } + } +} diff --git a/internal/parse/parse_test.go b/internal/parse/parse_test.go index 069e439..09924e4 100644 --- a/internal/parse/parse_test.go +++ b/internal/parse/parse_test.go @@ -602,7 +602,7 @@ func TestSpatialOpsMatchPlan(t *testing.T) { if spatial != len(plan.SpatialOps)-1 { t.Errorf("parser has %d spatial operators, plan.SpatialOps %d (with the internal geometry form of bbox_intersects)", spatial, len(plan.SpatialOps)) } - if want := len(postgis.Ops) - 2; len(plan.SpatialOps) != want { + if want := len(postgis.Ops()) - 2; len(plan.SpatialOps) != want { t.Errorf("plan.SpatialOps has %d operators, pdbcore %d (excluding isNull and orderingEquals)", len(plan.SpatialOps), want) } } diff --git a/internal/plugins/postgis/postgis.go b/internal/plugins/postgis/postgis.go index 776dbb0..111cc10 100644 --- a/internal/plugins/postgis/postgis.go +++ b/internal/plugins/postgis/postgis.go @@ -167,7 +167,7 @@ func RasterFilterOps(filters bool) []string { // addRasterColumns registers the pseudo-columns of a raster column: // ~_ for each header-only metadata accessor -// (postgis.RasterAccessors: width, height, num_bands, srid, pixel_width, +// (postgis.RasterAccessors(): width, height, num_bands, srid, pixel_width, // pixel_height, envelope), ~_value(band=) (the pixel value at ~near=) // and ~_summary_stats(band=). Another pseudo-column owning a key keeps // it. @@ -184,8 +184,8 @@ func addRasterColumns(b *api.Builder, r *api.Resource, f *api.Field) { pc.Key, pc.Column = key, f.Column r.Pseudo[key] = pc } - for i := range postgis.RasterAccessors { - a := postgis.RasterAccessors[i] + for i := range postgis.RasterAccessors() { + a := postgis.RasterAccessors()[i] add(RasterAccessor(a), &api.PseudoColumn{ Raster: &api.RasterValue{Accessor: &a}, Schema: rasterSchema(a.Type, a.GeoJSON), @@ -261,7 +261,7 @@ func Omits(comment string) (skipFilter, skipOrder bool) { // addPseudoColumns registers ~_ for every derived accessor // that applies to the column's typmod (see Applies). func addPseudoColumns(r *api.Resource, f *api.Field) { - for _, d := range postgis.Deriveds { + for _, d := range postgis.Deriveds() { if !Applies(d, f.Column) { continue } @@ -349,8 +349,8 @@ func snake(suffix string) string { // Accessors lists the pseudo-column suffixes in declaration order. func Accessors() []string { - out := make([]string, len(postgis.Deriveds)) - for i, d := range postgis.Deriveds { + out := make([]string, len(postgis.Deriveds())) + for i, d := range postgis.Deriveds() { out[i] = Accessor(d) } return out @@ -422,7 +422,7 @@ func FeatureCollectionSchema() *api.Schema { // `is`, for OpenAPI x-pdbr-filter-ops. func FilterOps() []string { var out []string - for _, op := range postgis.Ops { + for _, op := range postgis.Ops() { if name := OpName(op); name != "" && op.Kind() != postgis.ArgBoolean { out = append(out, name) } diff --git a/internal/plugins/postgis/postgis_test.go b/internal/plugins/postgis/postgis_test.go index cd3ec8c..4d307ca 100644 --- a/internal/plugins/postgis/postgis_test.go +++ b/internal/plugins/postgis/postgis_test.go @@ -292,7 +292,7 @@ func TestOpenAPI(t *testing.T) { if s := built.TypeSchema("geography", "public", ""); s.Ref != "#/components/schemas/GeoJSON" { t.Errorf("TypeSchema(geography) = %+v", s) } - if ops := built.Extra.FilterOps["geometry"]; !reflect.DeepEqual(ops, FilterOps()) || len(ops) != len(corepostgis.Ops)-2 { + if ops := built.Extra.FilterOps["geometry"]; !reflect.DeepEqual(ops, FilterOps()) || len(ops) != len(corepostgis.Ops())-2 { t.Errorf("FilterOps = %v", ops) } if built.OpenAPI.Components.Schemas[api.GeoJSONFeature] == nil || built.OpenAPI.Components.Schemas[api.GeoJSONFeatureCollection] == nil { diff --git a/internal/plugins/smartcomments/smartcomments.go b/internal/plugins/smartcomments/smartcomments.go index 77f1e53..ed414a6 100644 --- a/internal/plugins/smartcomments/smartcomments.go +++ b/internal/plugins/smartcomments/smartcomments.go @@ -8,6 +8,7 @@ package smartcomments import ( "context" + "log/slog" "sort" "strings" @@ -20,10 +21,28 @@ import ( "github.com/suprbdev/pdbr/internal/inflect" ) -// Plugin embeds the shared catalog half (Name, Priority, TransformCatalog, -// Index) and adds Inflect and TransformAPI. +// Plugin embeds the shared catalog half (Name, Priority, Index) and adds +// TransformCatalog's smart-tag checks, Inflect and TransformAPI. type Plugin struct { *catalog.Hook + // findings are the smart-tag issues of the last TransformCatalog, + // logged by TransformAPI once the configured logger is known. + findings []catalog.Finding +} + +// vocabulary is what pdbr honours: the @omit actions of TransformAPI and +// the catalog hook, on top of pdbcore's omit and contract @behavior +// tokens. +var vocabulary = smarttags.Vocabulary{ + OmitActions: []string{"read", "all", "create", "update", "delete", "many", "filter", "order"}, +} + +// TransformCatalog records the unknown @omit actions and unknown or +// deprecated @behavior tokens of the catalog (see catalog.Check), then +// runs the shared catalog half. +func (p *Plugin) TransformCatalog(ctx context.Context, c *introspect.Catalog) error { + p.findings = catalog.Check(c, vocabulary) + return p.Hook.TransformCatalog(ctx, c) } // Name is the plugin name (plugins.disabled entry). It replaces the @@ -101,6 +120,13 @@ func (p *Plugin) constraintTags(in coreinflect.Input) smarttags.Tags { // backward-embed removal, deprecation marks and enum renames. func (p *Plugin) TransformAPI(_ context.Context, b *api.Builder) error { p.SetLogger(b.Options.Logger) + log := b.Options.Logger + if log == nil { + log = slog.Default() + } + for _, f := range p.findings { + log.Warn("smart_comments: "+f.Message(), f.Args()...) + } for _, key := range sortedKeys(b.Resources) { r := b.Resources[key] p.applyTableTags(b, r) diff --git a/internal/plugins/smartcomments/validate_test.go b/internal/plugins/smartcomments/validate_test.go new file mode 100644 index 0000000..7415a39 --- /dev/null +++ b/internal/plugins/smartcomments/validate_test.go @@ -0,0 +1,91 @@ +package smartcomments_test + +import ( + "bytes" + "context" + "log/slog" + "strings" + "testing" + + "github.com/suprbdev/pdbcore/introspect" + "github.com/suprbdev/pdbcore/testutil" + + "github.com/suprbdev/pdbr/internal/api" + "github.com/suprbdev/pdbr/internal/inflect" + "github.com/suprbdev/pdbr/internal/plugin" + "github.com/suprbdev/pdbr/internal/plugins/smartcomments" +) + +// buildLogged builds the fixture API with the smart_comments plugin, +// returning what the build logged at WARN. +func buildLogged(t *testing.T, edit func(*introspect.Catalog)) []string { + t.Helper() + cat := testutil.FixtureCatalog() + edit(cat) + reg := plugin.NewRegistry(smartcomments.New()) + ctx := context.Background() + if err := reg.TransformCatalog(ctx, nil, cat); err != nil { + t.Fatal(err) + } + var logs bytes.Buffer + b := api.New(cat, reg.Inflector(nil, inflect.Default), api.Options{ + FilterIndexedOnly: true, Functions: true, Schemas: []string{"public"}, MaxPageSize: 100, + Logger: slog.New(slog.NewTextHandler(&logs, nil)), + }) + if err := reg.TransformAPI(ctx, nil, b); err != nil { + t.Fatal(err) + } + if _, err := b.Build(); err != nil { + t.Fatal(err) + } + var out []string + for _, line := range strings.Split(logs.String(), "\n") { + if strings.Contains(line, "level=WARN") && strings.Contains(line, "smart_comments:") { + out = append(out, line) + } + } + return out +} + +func TestSmartTagWarnings(t *testing.T) { + got := buildLogged(t, func(c *introspect.Catalog) { + table(c, "users").Comment = "@omit reed, delete\n@behavior -filterBy +contract:public -selectt" + column(c, "users", "email").Comment = "@behavior -order -orderBy -Bogus" + function(c, "users_post_count").Comment = "@omit aggregates" + }) + want := []string{ + `msg="smart_comments: unknown @omit action ignored" table=public.users action=reed`, + `msg="smart_comments: unknown @behavior token ignored" table=public.users token=-selectt`, + `msg="smart_comments: deprecated @behavior token" column=public.users.email token=-order use=-orderBy`, + `msg="smart_comments: unknown @behavior token ignored" column=public.users.email token=-Bogus`, + `msg="smart_comments: unknown @omit action ignored" function=public.users_post_count action=aggregates`, + } + if len(got) != len(want) { + t.Fatalf("warnings = %q, want %q", got, want) + } + for i, w := range want { + if !strings.Contains(got[i], w) { + t.Errorf("warning %d = %q, want %q", i, got[i], w) + } + } +} + +func TestKnownSmartTagsDoNotWarn(t *testing.T) { + got := buildLogged(t, func(c *introspect.Catalog) { + table(c, "users").Comment = "@omit read, ALL, many, create, update, delete, filter, order\n" + + "@behavior -select -insert -update -delete -filterBy -orderBy +contract:public -contract:partner contract:internal" + }) + if len(got) != 0 { + t.Errorf("warnings: %q", got) + } +} + +func TestBehaviorV5Spellings(t *testing.T) { + for _, comment := range []string{"@behavior -filterBy -orderBy", "@behavior -filter -order"} { + b := build(t, func(c *introspect.Catalog) { table(c, "posts").Comment = comment }) + posts := b.ByPath["posts"] + if len(posts.FilterColumns) != 0 || len(posts.OrderColumns) != 0 { + t.Errorf("%q left filter %v / order %v columns", comment, keys(posts.FilterColumns), keys(posts.OrderColumns)) + } + } +} diff --git a/pdbr.go b/pdbr.go index 3e49e72..e9a56a7 100644 --- a/pdbr.go +++ b/pdbr.go @@ -348,7 +348,10 @@ func (a *App) BuildContractAPI(ctx context.Context, cat *introspect.Catalog, nam 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.buildAPI(ctx, tableKeys(cat), view, a.Config.ContractBase(ct)) @@ -427,12 +430,20 @@ func (a *App) routeHandler(built *api.Built, in instruments) *server.Handler { if a.pool != nil { db = a.pool } + 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) + } + detail, err := pgexec.ParseDetail(a.Config.Errors.Detail) + if err != nil { + a.Log.Error("invalid errors.detail; database errors are sanitized as in prod", "err", err) + } ex := exec.New(db, built, chain, execHooks, exec.Options{ - Isolation: pgexec.ParseIsolation(a.Config.TX.Isolation), + Isolation: iso, MaxRetries: a.Config.TX.MaxRetries, ClaimsPrefix: a.Config.Claims.Prefix, ClaimsJSONSetting: a.Config.Claims.JSONSetting, - Detail: pgexec.ParseDetail(a.Config.Errors.Detail), + Detail: detail, MaxCost: a.Config.Limits.MaxCost, MaxEmbedDepth: a.Config.Limits.MaxDepth, MaxPageSize: a.Config.Limits.MaxPageSize, @@ -654,7 +665,7 @@ func (a *App) buildContractServer(ctx context.Context, cat *introspect.Catalog, // calling rebuild with every changed catalog. func (a *App) startWatch(ctx context.Context, bootHash 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, @@ -662,7 +673,12 @@ func (a *App) startWatch(ctx context.Context, bootHash string, rebuild func(cont Log: a.Log, TriggerName: "pdbr_watch", InitialHash: bootHash, - 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/test/e2e_schema_order_test.go b/test/e2e_schema_order_test.go new file mode 100644 index 0000000..42addd9 --- /dev/null +++ b/test/e2e_schema_order_test.go @@ -0,0 +1,40 @@ +package e2e + +import ( + "net/http" + "os" + "slices" + "testing" + + "github.com/suprbdev/pdbr/internal/config" +) + +// TestBareAliasesFollowFirstSchema boots live with a primary schema that +// sorts after the second one: the bare paths must serve schema.schemas[0], +// and the configured slice must keep its order. +func TestBareAliasesFollowFirstSchema(t *testing.T) { + url := os.Getenv("PDBR_TEST_DATABASE_URL") + if url == "" { + t.Skip("PDBR_TEST_DATABASE_URL not set; run `make test-e2e`") + } + drop := `DROP SCHEMA IF EXISTS b15_order CASCADE` + execDDL(t, url, drop, + `CREATE SCHEMA b15_order`, + `CREATE TABLE b15_order.users (id int PRIMARY KEY, tag text NOT NULL)`, + `INSERT INTO b15_order.users VALUES (1, 'secondary')`, + ) + t.Cleanup(func() { execDDL(t, url, drop) }) + schemas := []string{"public", "b15_order"} + srv := testServer(t, func(c *config.Config) { c.Schema.Schemas = schemas }) + if !slices.Equal(schemas, []string{"public", "b15_order"}) { + t.Fatalf("schema.schemas reordered: %v", schemas) + } + base := srv.URL + "/api" + res, body := send(t, http.MethodGet, base+"/users?select=tag", "", nil) + wantProblem(t, res, body, http.StatusBadRequest, "unknown_column") + var rows []row + getJSON(t, base+"/b15_order/users?select=tag", &rows) + if len(rows) != 1 || rows[0]["tag"] != "secondary" { + t.Fatalf("b15_order rows = %v", rows) + } +}