diff --git a/CHANGELOG.md b/CHANGELOG.md index 2d726f1..63d607b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,13 @@ becomes the release notes of the next tag. pdbr, with no external compatibility promise. - A CI job builds and tests pdbq and pdbr at their `main` against the pull request. +- `smarttags`: `Omits` maps the PostGraphile V5 `@behavior` spellings + `-filterBy` and `-orderBy` onto the `filter` and `order` actions; the old + `-filter` and `-order` stay as deprecated aliases. +- `smarttags.Tags.Check` reports unknown `@omit` actions, unknown `@behavior` + tokens and deprecated `@behavior` tokens against a product's + `smarttags.Vocabulary`; `smartcomments/catalog.Check` runs it over every + commented object of a catalog. ## [0.18.0] - 2026-11-23 diff --git a/README.md b/README.md index 6ec2e01..2e0d988 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ fixture both products are tested against. | Package | What it holds | |---|---| | `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`, `@behavior`, `Contracts` (`@contract` / `@behavior ±contract:` membership), list splitting | +| `smarttags` | PostGraphile-style smart-comment parser: `Parse`, `Strip`, `Tags`, `Omits` (`@omit` and the omit tokens of `@behavior`: `-select`, `-insert`, `-update`, `-delete`, the PostGraphile V5 `-filterBy` / `-orderBy` and their deprecated forms `-filter` / `-order`), `Contracts` (`@contract` / `@behavior ±contract:` membership), `Check` (unknown `@omit` actions, unknown and deprecated `@behavior` tokens against a product's `Vocabulary`), list splitting | | `contract` | schema contracts (see [Schema contracts](#schema-contracts)): `Contract{Name, Default}` with the `Include`/`Exclude` policies, `View` (clone + filter), `Apply`, `OmitAll`; also a `CatalogHook` | | `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 | diff --git a/smartcomments/catalog/check.go b/smartcomments/catalog/check.go new file mode 100644 index 0000000..3e13dd7 --- /dev/null +++ b/smartcomments/catalog/check.go @@ -0,0 +1,81 @@ +package catalog + +import ( + "strings" + + "github.com/suprbdev/pdbcore/introspect" + "github.com/suprbdev/pdbcore/smarttags" +) + +// Finding is a [smarttags.Issue] in the comment of a catalog object. +type Finding struct { + // Kind is the object's kind: table, view, column, constraint, + // function, enum or domain. + Kind string + // Object is the object's qualified name: schema.table, + // schema.table.column (also for composite type fields), + // schema.table.constraint, schema.function, schema.enum or + // schema.domain. + Object string + smarttags.Issue +} + +// Args returns the finding as slog key-value pairs: Kind=Object followed +// by the issue's [smarttags.Issue.Attrs]. +func (f Finding) Args() []any { + return append([]any{f.Kind, f.Object}, f.Attrs()...) +} + +// Check reports the smart-tag issues (see [smarttags.Tags.Check]) in the +// comments of c's objects against v: tables and views with their columns, +// foreign keys, primary keys and unique constraints, then composite type +// fields, functions, enums and domains. Run it before the [Hook] removes +// omitted objects so their comments are checked too. +func Check(c *introspect.Catalog, v smarttags.Vocabulary) []Finding { + var out []Finding + check := func(kind, object, comment string) { + if !strings.Contains(comment, "@") { + return + } + tags, _ := smarttags.Parse(comment) + for _, i := range tags.Check(v) { + out = append(out, Finding{Kind: kind, Object: object, Issue: i}) + } + } + for _, t := range c.Tables { + kind := "table" + if t.Kind == introspect.RelView || t.Kind == introspect.RelMaterializedView { + kind = "view" + } + key := tableKey(t.Schema, t.Name) + check(kind, key, t.Comment) + for _, col := range t.Columns { + check("column", key+"."+col.Name, col.Comment) + } + for _, fk := range t.ForeignKeys { + check("constraint", key+"."+fk.Name, fk.Comment) + } + if t.PrimaryKey != nil { + check("constraint", key+"."+t.PrimaryKey.Name, t.PrimaryKey.Comment) + } + for _, u := range t.Uniques { + check("constraint", key+"."+u.Name, u.Comment) + } + } + for _, ct := range c.Composites { + key := tableKey(ct.Schema, ct.Name) + for _, f := range ct.Fields { + check("column", key+"."+f.Name, f.Comment) + } + } + for _, f := range c.Functions { + check("function", tableKey(f.Schema, f.Name), f.Comment) + } + for _, e := range c.Enums { + check("enum", tableKey(e.Schema, e.Name), e.Comment) + } + for _, d := range c.Domains { + check("domain", tableKey(d.Schema, d.Name), d.Comment) + } + return out +} diff --git a/smartcomments/catalog/check_test.go b/smartcomments/catalog/check_test.go new file mode 100644 index 0000000..1cd3190 --- /dev/null +++ b/smartcomments/catalog/check_test.go @@ -0,0 +1,48 @@ +package catalog_test + +import ( + "reflect" + "testing" + + "github.com/suprbdev/pdbcore/smartcomments/catalog" + "github.com/suprbdev/pdbcore/smarttags" + "github.com/suprbdev/pdbcore/testutil" +) + +func TestCheck(t *testing.T) { + c := testutil.FixtureCatalog() + users := c.Table("public", "users") + users.Comment = "@omit reed\n@behavior -filterBy -selectt" + users.Column("email").Comment = "@behavior -order\nThe address." + c.Table("public", "posts").ForeignKeys[0].Comment = "@omit many,fliter" + c.Functions[0].Comment = "@behavior +nothing" + vocab := smarttags.Vocabulary{OmitActions: []string{"read", "many", "filter", "order"}} + + var got []string + for _, f := range catalog.Check(c, vocab) { + got = append(got, f.Message()+" "+formatArgs(f.Args())) + } + fk := c.Table("public", "posts").ForeignKeys[0].Name + fn := c.Functions[0] + want := []string{ + "unknown @omit action ignored constraint=public.posts." + fk + " action=fliter", + "unknown @omit action ignored table=public.users action=reed", + "unknown @behavior token ignored table=public.users token=-selectt", + "deprecated @behavior token column=public.users.email token=-order use=-orderBy", + "unknown @behavior token ignored function=" + fn.Schema + "." + fn.Name + " token=+nothing", + } + if !reflect.DeepEqual(got, want) { + t.Errorf("Check =\n%q\nwant\n%q", got, want) + } +} + +func formatArgs(args []any) string { + var s string + for i := 0; i+1 < len(args); i += 2 { + if s != "" { + s += " " + } + s += args[i].(string) + "=" + args[i+1].(string) + } + return s +} diff --git a/smarttags/smarttags.go b/smarttags/smarttags.go index b9796dc..824d0fb 100644 --- a/smarttags/smarttags.go +++ b/smarttags/smarttags.go @@ -75,8 +75,9 @@ func (t Tags) All(name string) []string { return t[name] } // // PostGraphile-V5-style @behavior tags contribute too: their negative tokens // map onto omit actions (-insert -> create, -update -> update, -delete -> -// delete, -select -> read, -filter -> filter, -order -> order); other tokens -// are ignored. +// delete, -select -> read, -filterBy -> filter, -orderBy -> order, matched +// case-insensitively). The deprecated -filter and -order still map to +// filter and order (see [Tags.Check]); other tokens are ignored. func (t Tags) Omits() (actions map[string]bool, everything bool) { actions = map[string]bool{} for _, v := range t["omit"] { @@ -98,14 +99,156 @@ func (t Tags) Omits() (actions map[string]bool, everything bool) { return actions, everything } -// behaviorOmits maps negative @behavior tokens to @omit actions. +// behaviorOmits maps negative @behavior tokens, lowercased, to @omit +// actions. var behaviorOmits = map[string]string{ - "-insert": "create", - "-update": "update", - "-delete": "delete", - "-select": "read", - "-filter": "filter", - "-order": "order", + "-insert": "create", + "-update": "update", + "-delete": "delete", + "-select": "read", + "-filterby": "filter", + "-orderby": "order", + "-filter": "filter", + "-order": "order", +} + +// deprecatedBehaviors maps deprecated @behavior tokens, lowercased, to the +// PostGraphile V5 token replacing them. +var deprecatedBehaviors = map[string]string{ + "-filter": "-filterBy", + "-order": "-orderBy", +} + +// Vocabulary is the set of @omit actions and @behavior tokens a product +// honours, against which [Tags.Check] reports unknown ones. The omit +// tokens of @behavior (see [Tags.Omits]) and the contract tokens (see +// [Tags.Contracts]) are always known. +type Vocabulary struct { + // OmitActions lists the @omit actions honoured, matched + // case-insensitively. + OmitActions []string + // Behavior reports whether a product-specific @behavior token is + // honoured; it receives the token as written, sign included. Nil knows + // no product-specific tokens. + Behavior func(token string) bool +} + +// IssueKind classifies an [Issue]. +type IssueKind int + +// The issue kinds. +const ( + // UnknownOmit is an @omit action outside [Vocabulary.OmitActions]. + UnknownOmit IssueKind = iota + 1 + // UnknownBehavior is an @behavior token nothing honours. + UnknownBehavior + // DeprecatedBehavior is an @behavior token still honoured under an old + // spelling; [Issue.Use] names the replacement. + DeprecatedBehavior +) + +// Issue is a token [Tags.Check] reports. +type Issue struct { + Kind IssueKind + // Token is the @omit action or @behavior token as written. + Token string + // Use is the replacement of a [DeprecatedBehavior] token, "" otherwise. + Use string +} + +// Message is a short description of the issue for a log line: +// "unknown @omit action ignored", "unknown @behavior token ignored" or +// "deprecated @behavior token". +func (i Issue) Message() string { + switch i.Kind { + case UnknownOmit: + return "unknown @omit action ignored" + case UnknownBehavior: + return "unknown @behavior token ignored" + case DeprecatedBehavior: + return "deprecated @behavior token" + } + return "smart tag issue" +} + +// Attrs returns the issue's details as slog key-value pairs: "action" for +// an @omit action, "token" (and "use" for a deprecated one) for an +// @behavior token. +func (i Issue) Attrs() []any { + switch i.Kind { + case UnknownOmit: + return []any{"action", i.Token} + case DeprecatedBehavior: + return []any{"token", i.Token, "use", i.Use} + } + return []any{"token", i.Token} +} + +// Check reports the unknown @omit actions, unknown @behavior tokens and +// deprecated @behavior tokens of t against v, in tag order and once per +// distinct token. +func (t Tags) Check(v Vocabulary) []Issue { + var issues []Issue + seen := map[string]bool{} + add := func(key string, i Issue) { + if !seen[key] { + seen[key] = true + issues = append(issues, i) + } + } + for _, val := range t["omit"] { + for _, a := range SplitList(val) { + if !containsFold(v.OmitActions, a) { + add("omit "+a, Issue{Kind: UnknownOmit, Token: a}) + } + } + } + for _, val := range t["behavior"] { + for _, tok := range SplitList(val) { + if use := deprecatedBehaviors[strings.ToLower(tok)]; use != "" { + add("behavior "+tok, Issue{Kind: DeprecatedBehavior, Token: tok, Use: use}) + } else if !v.knows(tok) { + add("behavior "+tok, Issue{Kind: UnknownBehavior, Token: tok}) + } + } + } + return issues +} + +// knows reports whether the @behavior token tok is honoured: an omit or +// contract token, or one v.Behavior accepts. +func (v Vocabulary) knows(tok string) bool { + if _, ok := behaviorOmits[strings.ToLower(tok)]; ok || isContractToken(tok) { + return true + } + return v.Behavior != nil && v.Behavior(tok) +} + +func containsFold(list []string, s string) bool { + for _, v := range list { + if strings.EqualFold(v, s) { + return true + } + } + return false +} + +// isContractToken reports whether tok is +contract:, +// -contract: or contract:. +func isContractToken(tok string) bool { + _, name, ok := contractToken(tok) + return ok && name != "" +} + +// contractToken splits a contract @behavior token into its sign ('+', '-' +// or 0) and lowercased contract name. +func contractToken(tok string) (sign byte, name string, ok bool) { + rest := tok + if rest != "" && (rest[0] == '+' || rest[0] == '-') { + sign, rest = rest[0], rest[1:] + } + name, ok = strings.CutPrefix(strings.ToLower(rest), "contract:") + return sign, name, ok } // Membership is an object's schema-contract membership, read by @@ -145,11 +288,7 @@ func (t Tags) Contracts() Membership { } for _, v := range t["behavior"] { for _, tok := range SplitList(v) { - sign, rest := tok[0], tok - if sign == '+' || sign == '-' { - rest = tok[1:] - } - name, ok := strings.CutPrefix(strings.ToLower(rest), "contract:") + sign, name, ok := contractToken(tok) if !ok || name == "" { continue } diff --git a/smarttags/smarttags_test.go b/smarttags/smarttags_test.go index 2705bc3..dd89015 100644 --- a/smarttags/smarttags_test.go +++ b/smarttags/smarttags_test.go @@ -97,6 +97,17 @@ func TestOmits(t *testing.T) { t.Error("+select must not omit read") } + tags, _ = Parse("@behavior -filterBy -ORDERBY") + actions, _ = tags.Omits() + if want := map[string]bool{"filter": true, "order": true}; !reflect.DeepEqual(actions, want) { + t.Errorf("v5 spellings: actions = %v, want %v", actions, want) + } + tags, _ = Parse("@behavior -filter -order") + actions, _ = tags.Omits() + if want := map[string]bool{"filter": true, "order": true}; !reflect.DeepEqual(actions, want) { + t.Errorf("deprecated spellings: actions = %v, want %v", actions, want) + } + var nilTags Tags if actions, everything := nilTags.Omits(); everything || len(actions) != 0 { t.Error("nil Tags must omit nothing") @@ -153,3 +164,55 @@ func TestContracts(t *testing.T) { t.Errorf("contract tokens must not count as omits: %v %v", actions, everything) } } + +func TestCheck(t *testing.T) { + vocab := Vocabulary{ + OmitActions: []string{"read", "create", "filter", "order"}, + Behavior: func(tok string) bool { return tok == "+aggregates" }, + } + tags, _ := Parse("@omit reed, CREATE\n@omit reed, fliter\n" + + "@behavior -filterBy -orderby -select -insert -update -delete +aggregates\n" + + "@behavior +contract:public -contract:partner contract:internal\n" + + "@behavior -filter -Order -filter -aggregates -contract: +nothing") + got := tags.Check(vocab) + want := []Issue{ + {Kind: UnknownOmit, Token: "reed"}, + {Kind: UnknownOmit, Token: "fliter"}, + {Kind: DeprecatedBehavior, Token: "-filter", Use: "-filterBy"}, + {Kind: DeprecatedBehavior, Token: "-Order", Use: "-orderBy"}, + {Kind: UnknownBehavior, Token: "-aggregates"}, + {Kind: UnknownBehavior, Token: "-contract:"}, + {Kind: UnknownBehavior, Token: "+nothing"}, + } + if !reflect.DeepEqual(got, want) { + t.Errorf("Check = %+v\nwant %+v", got, want) + } + if issues := Tags(nil).Check(Vocabulary{}); issues != nil { + t.Errorf("nil Tags: %v", issues) + } + tags, _ = Parse("@omit read\n@behavior +aggregates") + if issues := tags.Check(Vocabulary{}); len(issues) != 2 { + t.Errorf("empty vocabulary: %v", issues) + } +} + +func TestIssueMessage(t *testing.T) { + cases := []struct { + issue Issue + msg string + attrs []any + }{ + {Issue{Kind: UnknownOmit, Token: "reed"}, "unknown @omit action ignored", []any{"action", "reed"}}, + {Issue{Kind: UnknownBehavior, Token: "-x"}, "unknown @behavior token ignored", []any{"token", "-x"}}, + {Issue{Kind: DeprecatedBehavior, Token: "-order", Use: "-orderBy"}, "deprecated @behavior token", + []any{"token", "-order", "use", "-orderBy"}}, + } + for _, tc := range cases { + if got := tc.issue.Message(); got != tc.msg { + t.Errorf("%+v: Message = %q, want %q", tc.issue, got, tc.msg) + } + if got := tc.issue.Attrs(); !reflect.DeepEqual(got, tc.attrs) { + t.Errorf("%+v: Attrs = %v, want %v", tc.issue, got, tc.attrs) + } + } +}