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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:<name>` 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:<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` |
| `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 |
Expand Down
81 changes: 81 additions & 0 deletions smartcomments/catalog/check.go
Original file line number Diff line number Diff line change
@@ -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
}
48 changes: 48 additions & 0 deletions smartcomments/catalog/check_test.go
Original file line number Diff line number Diff line change
@@ -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
}
167 changes: 153 additions & 14 deletions smarttags/smarttags.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"] {
Expand All @@ -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:<name>,
// -contract:<name> or contract:<name>.
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
Expand Down Expand Up @@ -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
}
Expand Down
Loading
Loading