From eefd272164fc77d6359e82390598dd615b38468a Mon Sep 17 00:00:00 2001 From: Randolf Jung Date: Thu, 19 Nov 2026 20:49:01 -0800 Subject: [PATCH 1/7] chore: extend the mathematic-inc ToolConfig policy Why: mathematic-inc repositories share one ToolConfig policy. This repository kept its own copy of each tool setting. - Extend toolconfig-config at a pinned commit. Keep only the buf module path, one buf exception and one cargo-deny advisory exception. - Delete the settings files that ToolConfig now writes. - Amend the hk steps of the organization. Keep the lockfile step. Set the cargo-deny directory and the kingfisher skip for the test database. - Pin ToolConfig 2026.11.6, hk 2.13.0 and the other tools of the policy. - Add the mise tasks generate, fix and check. --- .editorconfig | 23 ++++ .gitignore | 22 ++++ .hk/org.pkl | 231 ++++++++++++++++++++++++++++++++++++ .pinact.yaml | 3 +- .rumdl.toml | 5 +- .ryl.toml | 20 ++-- .toolconfig.lock | 25 ++++ .toolconfig.pkl | 35 ++++++ buf.yaml | 10 +- deny.toml | 24 +--- hk.pkl | 281 ++------------------------------------------ mise.toml | 38 ++++-- rust-toolchain.toml | 2 +- 13 files changed, 400 insertions(+), 319 deletions(-) create mode 100644 .editorconfig create mode 100644 .hk/org.pkl create mode 100644 .toolconfig.lock create mode 100644 .toolconfig.pkl diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..3122b97 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,23 @@ +# Generated by ToolConfig from .toolconfig.pkl. Edit that file instead. +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 100 + +[*.{rs,py,pyi}] +indent_size = 4 + +[*.go] +indent_style = tab + +[{Makefile,*.mk}] +indent_style = tab + +[*.{md,markdown}] +max_line_length = 80 diff --git a/.gitignore b/.gitignore index 3002281..de5a37e 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,25 @@ _sqlc_dev.yaml .memsearch /dist/ + +# BEGIN TOOLCONFIG GENERATED FILES +.toolconfig-stage-* +/.github/actionlint.yaml +/.gitleaks.toml +/.hadolint.yaml +/.oxfmtrc.json +/.oxlintrc.json +/.pinact.yaml +/.rumdl.toml +/.ryl.toml +/.shellcheckrc +/buf.yaml +/deny.toml +/knip.json +/lychee.toml +/ruff.toml +/rustfmt.toml +/tombi.toml +/ty.toml +/typos.toml +# END TOOLCONFIG GENERATED FILES diff --git a/.hk/org.pkl b/.hk/org.pkl new file mode 100644 index 0000000..fb64ea8 --- /dev/null +++ b/.hk/org.pkl @@ -0,0 +1,231 @@ +// ToolConfig writes this file to `.hk/org.pkl` from `hk/org.pkl` in +// mathematic-inc/toolconfig-config. Make changes in that repository. +amends "package://github.com/jdx/hk/releases/download/v2.13.0/hk@2.13.0#/Config.pkl" + +import "package://github.com/jdx/hk/releases/download/v2.13.0/hk@2.13.0#/Builtins.pkl" + +min_hk_version = "2.13.0" +hide_warnings = List("missing-profiles") +exclude = + List( + "**/CHANGELOG.md", + "**/dist/**", + "**/gen/**", + "**/generated/**", + "**/node_modules/**", + "**/target/**", + "**/vendor/**", + ) + +local oxfmtFiles = + List( + "**/*.astro", + "**/*.cjs", + "**/*.css", + "**/*.cts", + "**/*.graphql", + "**/*.hbs", + "**/*.html", + "**/*.js", + "**/*.json", + "**/*.jsonc", + "**/*.jsx", + "**/*.mjs", + "**/*.mts", + "**/*.scss", + "**/*.svelte", + "**/*.ts", + "**/*.tsx", + "**/*.vue", + ) + +local rustFiles = List("Cargo.toml", "Cargo.lock", "**/Cargo.toml", "**/*.rs") +local goFiles = List("go.mod", "go.sum", "**/*.go") +local slow = List("slow") + +steps { + // The other steps read the tool settings that ToolConfig writes. Git ignores those files, so a + // fresh clone does not have them. + ["toolconfig"] { + glob = "**/*" + exclusive = true + check = "toolconfig generate --strict" + } + + ["bom"] = Builtins.byte_order_marker + ["case-conflicts"] = Builtins.check_case_conflict + ["executables-have-shebangs"] = Builtins.check_executables_have_shebangs + ["large-files"] = Builtins.check_added_large_files + ["merge-conflicts"] = Builtins.check_merge_conflict + ["mixed-line-endings"] = Builtins.mixed_line_ending + ["newlines"] = Builtins.newlines + ["private-keys"] = Builtins.detect_private_key + ["symlinks"] = Builtins.check_symlinks + ["trailing-whitespace"] = Builtins.trailing_whitespace + ["typos"] = (Builtins.typos) { + check = "typos --force-exclude {{ files }} || exit 1" + } + + ["ryl-markdown"] = (Builtins.ryl_markdown) { + depends = "typos" + } + ["rumdl-format"] = (Builtins.rumdl_format) { + depends = "ryl-markdown" + } + ["rumdl"] = (Builtins.rumdl) { + depends = "rumdl-format" + } + ["harper"] = (Builtins.harper) { + types = List("markdown") + check = + "harper-cli --no-color lint --quiet --format compact --ignore SpellCheck,UseTitleCase,SplitWords,SentenceCapitalization,OxfordComma,OrthographicConsistency,NumericRangeEnDash,MissingTo,MassNouns,DisjointPrefixes,PhrasalVerbAsCompoundNoun,ExpandConfiguration,ExpandControl,ExpandMemoryShorthands,WrongNegative {{ files }}" + output_summary = "hide" + depends = "rumdl" + } + ["lychee"] = (Builtins.lychee) { + types = List("markdown", "html") + depends = "rumdl" + } + + ["pkl-format"] = (Builtins.pkl_format) { + shell = null + fix = "pkl format --write {{ files }}" + } + ["pkl"] = (Builtins.pkl) { + check = new Script { + windows = "pkl eval {{ files }} >NUL" + other = "pkl eval {{ files }} >/dev/null" + } + depends = "pkl-format" + } + ["tombi-format"] = (Builtins.tombi_format) { + depends = "typos" + } + ["tombi"] = (Builtins.tombi) { + depends = "tombi-format" + } + ["mise"] = (Builtins.mise) { + check = "mise -C {{workspace}} fmt --check" + fix = "mise -C {{workspace}} fmt" + workspace_indicator = "mise.toml" + depends = "tombi" + } + ["jq"] = (Builtins.jq) { + check = "jq empty {{ files }}" + check_diff = null + fix = null + } + + ["jactionlint"] = (Builtins.jactionlint) { + check = "jactionlint {{ files }}" + check_diff = null + fix = "jactionlint --fix {{ files }}" + } + ["ghalint"] = (Builtins.ghalint_workflow) { + depends = "jactionlint" + } + ["pinact"] = (Builtins.pinact) { + check = "pinact run --fix=false --no-api {{ files }}" + check_diff = null + } + ["zizmor"] = (Builtins.zizmor) { + check = "zizmor --no-progress {{ files }}" + check_diff = null + fix = "zizmor --no-progress --fix {{ files }}" + depends = "pinact" + } + + ["hadolint"] = Builtins.hadolint + ["ruff-format"] = Builtins.ruff_format + ["ruff"] = (Builtins.ruff) { + depends = "ruff-format" + } + ["ty"] = (Builtins.ty) { + depends = "ruff" + } + ["python-ast"] = Builtins.python_check_ast + ["python-debug-statements"] = Builtins.python_debug_statements + ["shellharden"] = Builtins.shellharden + ["shellcheck"] = (Builtins.shellcheck) { + depends = "shellharden" + } + ["shfmt"] = (Builtins.shfmt) { + depends = "shellcheck" + } + ["ryl"] = Builtins.ryl + + // rumdl, tombi and sort-package-json own Markdown, TOML and package.json. YAML is not here, + // because oxfmt writes `{ bar: 0 }` in a flow mapping and the braces rule of ryl rejects it. + ["oxfmt"] = (Builtins.oxfmt) { + glob = oxfmtFiles + exclude = super.exclude + List("**/package.json") + } + ["oxlint"] = (Builtins.ox_lint) { + depends = "oxfmt" + } + ["sort-package-json"] = Builtins.sort_package_json + + ["buf-format"] = Builtins.buf_format + ["buf-lint"] = (Builtins.buf_lint) { + depends = "buf-format" + } + + ["cargo-fmt"] = (Builtins.cargo_fmt) { + glob = rustFiles + workspace_indicator = null + check = "cargo fmt --all --check" + fix = "cargo fmt --all" + } + ["cargo-clippy"] = (Builtins.cargo_clippy) { + glob = rustFiles + workspace_indicator = null + check = "cargo clippy --workspace --all-features --all-targets -- -D warnings" + fix = + "cargo clippy --fix --workspace --all-features --all-targets --allow-dirty --allow-staged -- -D warnings" + profiles = slow + } + ["cargo-deny"] = (Builtins.cargo_deny) { + glob = List("Cargo.toml", "Cargo.lock", "deny.toml", "**/Cargo.toml") + workspace_indicator = null + check = "cargo-deny --locked --workspace check" + profiles = slow + } + + ["go-fmt"] = (Builtins.go_fmt) { + glob = goFiles + } + ["go-mod-tidy"] = (Builtins.gomod_tidy) { + depends = "go-fmt" + } + ["go-vet"] = (Builtins.go_vet) { + depends = "go-mod-tidy" + profiles = slow + } + + ["gitleaks"] = (Builtins.gitleaks) { + glob = "**/*" + check = "gitleaks git --redact --verbose --no-banner --timeout 60 --log-opts=--all ." + profiles = slow + } + ["kingfisher"] = (Builtins.kingfisher) { + glob = "**/*" + check = "kingfisher scan {{ files }} --no-update-check --no-validate --quiet --redact" + profiles = slow + } +} + +hooks { + ["commit-msg"] { + steps { + ["conventional-commit"] = Builtins.check_conventional_commit + } + } + ["pre-push"] { + steps { + ["checks"] { + glob = "**/*" + check = "hk check --all --slow" + } + } + } +} diff --git a/.pinact.yaml b/.pinact.yaml index b156d0f..b807d7a 100644 --- a/.pinact.yaml +++ b/.pinact.yaml @@ -1,6 +1,5 @@ version: 3 - rules: - ignore: true conditions: - - expr: ActionName == "dtolnay/rust-toolchain" + - expr: ActionName == "dtolnay/rust-toolchain" && ActionVersion matches "^[0-9a-f]{40}$" diff --git a/.rumdl.toml b/.rumdl.toml index 84e0d63..13a3b31 100644 --- a/.rumdl.toml +++ b/.rumdl.toml @@ -1,2 +1,5 @@ +[MD013] +line-length = 80 + [global] -disable = ["MD013", "MD057"] +exclude = ["**/dist/**", "**/gen/**", "**/generated/**", "**/node_modules/**", "**/target/**", "**/vendor/**", "**/CHANGELOG.md"] diff --git a/.ryl.toml b/.ryl.toml index 3ac61e2..6d95be8 100644 --- a/.ryl.toml +++ b/.ryl.toml @@ -1,10 +1,8 @@ -[files] -yaml = [ - "*.yaml", - "*.yml", -] +[lint] +strict = true [lint.rules] +key-duplicates = "enable" anchors = "enable" braces = "enable" brackets = "enable" @@ -16,16 +14,19 @@ empty-lines = "enable" empty-values = "disable" float-values = "disable" hyphens = "enable" -indentation = "enable" -key-duplicates = "enable" key-ordering = "disable" line-length = "disable" new-line-at-end-of-file = "enable" -new-lines = "enable" octal-values = "disable" quoted-strings = "disable" trailing-spaces = "enable" +[lint.rules.indentation] +spaces = 2 + +[lint.rules.new-lines] +type = "unix" + [lint.rules.comments] level = "warning" min-spaces-from-content = 1 @@ -37,5 +38,8 @@ level = "warning" check-keys = false level = "warning" +[files] +yaml = ["*.yaml", "*.yml"] + [format] quote-style = "preserve" diff --git a/.toolconfig.lock b/.toolconfig.lock new file mode 100644 index 0000000..0a71913 --- /dev/null +++ b/.toolconfig.lock @@ -0,0 +1,25 @@ +# Written by ToolConfig. Commit this file and do not edit it. + +version = 1 + +[outputs] +".editorconfig" = { hash = "6b7d26a6082816abc56ec9cecc31d80a4711c93bb1774da560418a1fff11fefe" } +".github/actionlint.yaml" = { hash = "0507e6dc7d7cc47356f687482bcece95784d98c83917ea840a23c6102732fb92" } +".gitleaks.toml" = { hash = "27630a96d6c55755cc37620f3933d5cab94b1eb78a726a32e11212972525d76e" } +".hadolint.yaml" = { hash = "ca3d163bab055381827226140568f3bef7eaac187cebd76878e0b63e9e442356" } +".hk/org.pkl" = { hash = "639f1a12f3a3444b7ab233d3290a703bd4d9300d9e2b1254743ed70adbbbef62" } +".oxfmtrc.json" = { hash = "f59efc861a4a3ad6b2db387705dc1329edb8850fad0d46ef173c295bd770ac41" } +".oxlintrc.json" = { hash = "c5c77e9ea2a51d81bd8c78123d958c88c48879dd6d9055e02aa48410ebbb577a" } +".pinact.yaml" = { hash = "bafc506f9dfb5214895180e4ce7a62e4db843502a633c61866872c0c5c6bc75f" } +".rumdl.toml" = { hash = "9046b5658bc1f2bd03a7a64abc60749174c47fdebc27bff25057bb002ff65672" } +".ryl.toml" = { hash = "a861e9522e782f99166df23360a7461eb1825657b29e51ebce84fb3d87317fdc" } +".shellcheckrc" = { hash = "d85f8e905e21c014b7d7383dc6d7ac9db3195db4ec39996e371cf5435b2f5b97" } +"buf.yaml" = { hash = "7d20e4624b296e9a0714a538185077aeeba33315b5f15b13c15df17ae85c7398" } +"deny.toml" = { hash = "90651efacbdc29c5de3e462a8318d57bc7ac8c34f6f69f18c1922efdf60d327b" } +"knip.json" = { hash = "80c332d1847a9358b6745924f2ddbea5f6393e2b5ec32609110ca736f4fcafaa" } +"lychee.toml" = { hash = "71d5396838b84d318464c52cf5a0b764e261b905194accff13b9579f338b1d6c" } +"ruff.toml" = { hash = "5a273f6c11ed5cc4a2c59b29127253812bbeec930952a8d1585875dccdfc11b0" } +"rustfmt.toml" = { hash = "a03255602b79b6dc6e1501ac0e5a34db4d140fac679c623215144ef3302acbc4" } +"tombi.toml" = { hash = "4b98c138ebef6ce7ef5e926b90abb65558302093b57a451ebbadb4ff1600ac47" } +"ty.toml" = { hash = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" } +"typos.toml" = { hash = "997a269dd06e43337ab3e6c433c7fe510f40b9e8c63d35b2691ad1102db82fd7" } diff --git a/.toolconfig.pkl b/.toolconfig.pkl new file mode 100644 index 0000000..9a3a73d --- /dev/null +++ b/.toolconfig.pkl @@ -0,0 +1,35 @@ +amends + "package://github.com/mathematic-inc/toolconfig/releases/download/v2026.11.6/toolconfig@2026.11.6#/ToolConfig.pkl" + +root = true + +toolconfig { + `extends` = + List(new Repository { + git = "https://github.com/mathematic-inc/toolconfig-config.git" + rev = "fc76ddad46c14a7b7fe03bf117a92ede11ea0dfb" + path = "profiles/org/.toolconfig.pkl" + }) +} + +sections { + ["*"] { + `cargo-deny` { + advisories { + ignore { + new { + id = "RUSTSEC-2026-0543" + reason = "chrono is unmaintained and has no fix; sqlx and the generated code use it" + } + } + } + } + } + ["*.proto"] { + buf { + modules { new { path = "proto" } } + // sqlc-dev/sqlc owns this copy of its plugin protocol. + lint { ignore_only { ["PACKAGE_VERSION_SUFFIX"] = List("proto/plugin/codegen.proto") } } + } + } +} diff --git a/buf.yaml b/buf.yaml index bd5236d..71e51d2 100644 --- a/buf.yaml +++ b/buf.yaml @@ -2,10 +2,6 @@ version: v2 modules: - path: proto lint: - use: - - STANDARD - except: - - PACKAGE_VERSION_SUFFIX -breaking: - use: - - FILE + ignore_only: + PACKAGE_VERSION_SUFFIX: + - proto/plugin/codegen.proto diff --git a/deny.toml b/deny.toml index 9e2228e..f8940dd 100644 --- a/deny.toml +++ b/deny.toml @@ -1,27 +1,13 @@ -[advisories] -ignore = [] - [licenses] -allow = [ - "Apache-2.0", - "Apache-2.0 WITH LLVM-exception", - "BSL-1.0", - "MIT", - "Unicode-3.0", - "Zlib", -] -confidence-threshold = 0.8 - -[licenses.private] -ignore = true +allow = ["Apache-2.0", "MIT", "Unicode-3.0", "Zlib"] [bans] -multiple-versions = "warn" wildcards = "deny" -allow-workspace = true [sources] unknown-registry = "deny" unknown-git = "deny" -allow-registry = ["https://github.com/rust-lang/crates.io-index"] -allow-git = [] + +[[advisories.ignore]] +id = "RUSTSEC-2026-0543" +reason = "chrono is unmaintained and has no fix; sqlx and the generated code use it" diff --git a/hk.pkl b/hk.pkl index 61fae61..98e5224 100644 --- a/hk.pkl +++ b/hk.pkl @@ -1,276 +1,17 @@ -amends "package://github.com/jdx/hk/releases/download/v2.11.1/hk@2.11.1#/Config.pkl" - -import "package://github.com/jdx/hk/releases/download/v2.11.1/hk@2.11.1#/Builtins.pkl" - -min_hk_version = "2.11.1" -hide_warnings = List("missing-profiles") -exclude = List("**/CHANGELOG.md") - -local generatedFiles = - List( - "**/dist/**", - "**/gen/**", - "**/generated/**", - "**/node_modules/**", - "**/target/**", - "**/vendor/**", - ) - -local javascriptFiles = - List( - "**/*.astro", - "**/*.cjs", - "**/*.css", - "**/*.graphql", - "**/*.hbs", - "**/*.html", - "**/*.js", - "**/*.jsx", - "**/*.mjs", - "**/*.mts", - "**/*.scss", - "**/*.svelte", - "**/*.ts", - "**/*.tsx", - "**/*.vue", - ) - -local rustFiles = List("Cargo.toml", "Cargo.lock", "**/Cargo.toml", "**/*.rs") -local goFiles = List("go.mod", "go.sum", "**/*.go") -local slow = List("slow") - -local checks = new Mapping { - // Repository hygiene. - ["bom"] = Builtins.byte_order_marker - ["case-conflicts"] = Builtins.check_case_conflict - ["executables-have-shebangs"] = Builtins.check_executables_have_shebangs - ["large-files"] = (Builtins.check_added_large_files) { - exclude = generatedFiles - } - ["merge-conflicts"] = Builtins.check_merge_conflict - ["mixed-line-endings"] = Builtins.mixed_line_ending - ["newlines"] = (Builtins.newlines) { - exclude = generatedFiles - } - ["private-keys"] = Builtins.detect_private_key - ["symlinks"] = Builtins.check_symlinks - ["trailing-whitespace"] = (Builtins.trailing_whitespace) { - exclude = generatedFiles - } - ["typos"] = (Builtins.typos) { - check = "typos --force-exclude {{ files }} || exit 1" - } - - // Prose and links. - ["ryl-markdown"] = (Builtins.ryl_markdown) { - check_diff = "ryl check --strict --diff --markdown {{ files }}" - fix = "ryl check --strict --fix --markdown {{ files }}" - exclude = generatedFiles - depends = "typos" - } - ["rumdl-format"] = (Builtins.rumdl_format) { - exclude = generatedFiles - depends = "ryl-markdown" - } - ["rumdl"] = (Builtins.rumdl) { - exclude = generatedFiles - depends = "rumdl-format" - } - ["harper"] = (Builtins.harper) { - types = List("markdown") - exclude = generatedFiles +amends ".hk/org.pkl" + +steps { + // The step of the organization sets no `workspace_indicator`, so hk cannot render the `dir` of + // the builtin step. + ["cargo-deny"] { dir = "{{root}}" } + // The test database has the user and the password `sqlc`. kingfisher reports its URI. + ["kingfisher"] { check = - "harper-cli --no-color lint --quiet --format compact --ignore SpellCheck,UseTitleCase,SplitWords,SentenceCapitalization,OxfordComma,OrthographicConsistency,NumericRangeEnDash,MissingTo,MassNouns,DisjointPrefixes,PhrasalVerbAsCompoundNoun,ExpandConfiguration,ExpandControl,ExpandMemoryShorthands,ExpandParameter,WrongNegative,CompoundNouns {{ files }}" - output_summary = "hide" - depends = "rumdl" - } - ["lychee"] = (Builtins.lychee) { - types = List("markdown", "html") - check = "lychee --offline --no-progress --exclude '^file://.*/discussions/new$' {{ files }}" - exclude = generatedFiles - depends = "rumdl" - } - - // Structured configuration. - ["pkl-format"] = (Builtins.pkl_format) { - shell = null - fix = "pkl format --write {{ files }}" - } - ["pkl"] = (Builtins.pkl) { - check = new Script { - windows = "pkl eval {{ files }} >NUL" - other = "pkl eval {{ files }} >/dev/null" - } - depends = "pkl-format" - } - ["tombi-format"] = (Builtins.tombi_format) { - depends = "typos" - } - ["tombi"] = (Builtins.tombi) { - depends = "tombi-format" - } - ["mise"] = (Builtins.mise) { - check = "mise -C {{workspace}} fmt --check" - fix = "mise -C {{workspace}} fmt" - workspace_indicator = "mise.toml" - depends = "tombi" - } - ["jq"] = (Builtins.jq) { - check = "jq empty {{ files }}" - check_diff = null - fix = null - } - - // GitHub Actions. - ["actionlint"] = (Builtins.jactionlint) { - check = "jactionlint --profile correctness {{ files }}" - check_diff = null - fix = "jactionlint --profile correctness --fix {{ files }}" - } - ["ghalint"] = (Builtins.ghalint_workflow) { - depends = "actionlint" - } - ["pinact"] = (Builtins.pinact) { - check = "pinact run --fix=false --no-api {{ files }}" - check_diff = null - } - ["zizmor"] = (Builtins.zizmor) { - check = "zizmor --no-progress --min-severity low {{ files }}" - check_diff = null - fix = "zizmor --no-progress --min-severity low --fix {{ files }}" - depends = "pinact" - } - - // Containers, Python, and shell. - ["hadolint"] = Builtins.hadolint - ["ruff-format"] = Builtins.ruff_format - ["ruff"] = (Builtins.ruff) { - depends = "ruff-format" + "kingfisher scan {{ files }} --no-update-check --no-validate --quiet --redact --skip-regex 'postgres://sqlc:sqlc@'" } - ["ty"] = (Builtins.ty) { - depends = "ruff" - } - ["python-ast"] = Builtins.python_check_ast - ["python-debug-statements"] = Builtins.python_debug_statements - ["shellharden"] = Builtins.shellharden - ["shellcheck"] = (Builtins.shellcheck) { - depends = "shellharden" - } - ["shfmt"] = (Builtins.shfmt) { - depends = "shellcheck" - } - ["ryl"] = (Builtins.ryl) { - check_diff = "ryl check --strict --diff {{ files }}" - fix = "ryl check --strict --fix {{ files }}" - exclude = generatedFiles - } - - // JavaScript and TypeScript. TOML, YAML, Markdown, JSON package manifests, - // and generated sources are owned by their dedicated tools. - ["oxfmt"] = (Builtins.oxfmt) { - glob = javascriptFiles - exclude = generatedFiles - } - ["oxlint"] = (Builtins.ox_lint) { - glob = javascriptFiles - exclude = generatedFiles - depends = "oxfmt" - } - ["sort-package-json"] = Builtins.sort_package_json - - // Protobuf. - ["buf-format"] = Builtins.buf_format - ["buf-lint"] = (Builtins.buf_lint) { - depends = "buf-format" - } - - // Rust. - ["cargo-lockfile"] = new Step { + ["cargo-lockfile"] { glob = List("Cargo.toml", "Cargo.lock", "**/Cargo.toml") check = "cargo metadata --locked --format-version 1 --all-features > /dev/null" - profiles = slow - } - ["cargo-fmt"] = (Builtins.cargo_fmt) { - glob = rustFiles - exclude = generatedFiles - workspace_indicator = null - check = "cargo fmt --all --check" - fix = "cargo fmt --all" - } - ["cargo-check"] = (Builtins.cargo_check) { - glob = rustFiles - workspace_indicator = null - check = "cargo check --workspace --all-features --all-targets" - fix = null - profiles = slow - } - ["cargo-clippy"] = (Builtins.cargo_clippy) { - glob = rustFiles - workspace_indicator = null - check = "cargo clippy --workspace --all-features --all-targets -- -D warnings" - fix = - "cargo clippy --fix --workspace --all-features --all-targets --allow-dirty --allow-staged -- -D warnings" - profiles = slow - } - ["cargo-deny"] = (Builtins.cargo_deny) { - glob = List("Cargo.toml", "Cargo.lock", "deny.toml", "**/Cargo.toml") - workspace_indicator = null - dir = "{{root}}" - check = "cargo-deny --locked --workspace check" - profiles = slow - } - - // Go. - ["go-fmt"] = (Builtins.go_fmt) { - glob = goFiles - } - ["go-mod-tidy"] = (Builtins.gomod_tidy) { - depends = "go-fmt" - } - ["go-vet"] = (Builtins.go_vet) { - depends = "go-mod-tidy" - profiles = slow - } - - // Full-history and layered secret scans are kept out of the commit-time - // fast path but are mandatory at pre-push and in CI. - ["gitleaks"] = (Builtins.gitleaks) { - glob = "**/*" - check = - "gitleaks git --redact --verbose --no-banner --timeout 60 --log-opts=--all . && gitleaks git --redact --verbose --no-banner --pre-commit --staged ." - profiles = slow - } - ["kingfisher"] = (Builtins.kingfisher) { - glob = "**/*" - check = "kingfisher scan {{ files }} --no-update-check --no-validate --quiet --redact" - profiles = slow - } -} - -hooks { - ["commit-msg"] { - steps { - ["conventional-commit"] = Builtins.check_conventional_commit - } - } - ["pre-commit"] { - fix = true - stash = "git" - steps = checks - } - ["pre-push"] { - steps { - ["checks"] { - glob = "**/*" - check = "hk check --all --slow" - } - } - } - ["fix"] { - fix = true - steps = checks - } - ["check"] { - steps = checks + profiles = List("slow") } } diff --git a/mise.toml b/mise.toml index 2efc1f2..1bd72b8 100644 --- a/mise.toml +++ b/mise.toml @@ -4,34 +4,38 @@ cargo.binstall_native = true idiomatic_version_file_enable_tools = ["node", "pnpm", "python", "ruff", "rust"] npm.package_manager = "npm" +[tool_alias] +toolconfig = "github:mathematic-inc/toolconfig" + [tools] -jactionlint = "2.5.0" cargo-binstall = "1.26.2" buf = "1.75.0" ghalint = "1.6.0" gitleaks = "8.30.1" -harper-cli = "3.0.0" -hk = "2.11.1" +harper-cli = "3.3.0" +hk = "2.13.0" +jactionlint = "2.6.0" jq = "1.8.2" lychee = "0.24.2" pinact = "5.0.2" protoc = "36.2" python = "3.15.2" -rumdl = "0.3.2" -rust = { version = "1.99.1", profile = "minimal", components = [ +rumdl = "0.3.5" +rust = { version = "1.100.0", profile = "minimal", components = [ "clippy", "rustfmt", ] } shellcheck = "0.11.0" shfmt = "3.14.1" -tombi = "1.10.0" -typos = "1.52.0" +tombi = "1.11.3" +toolconfig = "2026.11.6" +typos = "1.52.2" uv = "0.13.7" zizmor = "1.32.0" -"aqua:EmbarkStudios/cargo-deny" = { version = "0.20.2", depends = ["rust"] } +"aqua:EmbarkStudios/cargo-deny" = { version = "0.21.0", depends = ["rust"] } "aqua:anordal/shellharden" = "4.3.2" -"aqua:apple/pkl" = "0.33.0" -"aqua:owenlamont/ryl" = "0.29.0" +"aqua:apple/pkl" = "0.33.1" +"aqua:owenlamont/ryl" = "0.30.0" "aqua:sqlc" = "1.31.1" # Compile generators from source so codegen and runtime stay in lockstep. "cargo:protoc-gen-buffa" = { version = "0.9.2", default-features = false, depends = [ @@ -41,4 +45,16 @@ zizmor = "1.32.0" "rust", "cargo:protoc-gen-buffa", ] } -"github:mongodb/kingfisher" = "2.17.0" +"github:mongodb/kingfisher" = "2.19.1" + +[tasks.generate] +description = "Write the files that ToolConfig generates" +run = "toolconfig generate --strict" + +[tasks.fix] +description = "Fix the files that tools can fix" +run = "hk fix --all --slow" + +[tasks.check] +description = "Check the repository" +run = "hk check --all --slow" diff --git a/rust-toolchain.toml b/rust-toolchain.toml index 7c906de..4648003 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,5 +1,5 @@ [toolchain] -channel = "1.99.1" +channel = "1.100.0" profile = "minimal" components = ["clippy", "rustfmt"] targets = ["wasm32-wasip1"] From 295bc8d155f8a442f73689fee10da54883101dd0 Mon Sep 17 00:00:00 2001 From: Randolf Jung Date: Thu, 19 Nov 2026 20:49:02 -0800 Subject: [PATCH 2/7] ci: run ToolConfig through toolconfig-action Why: the policy needs the generated settings files before each tool runs. - Run toolconfig-action in each job that runs a tool, after mise. - Run hk with --skip-step toolconfig in the hk workflow. - Add a concurrency group to the workflows that had none. - Pin the postgres image of the services by digest. - Turn off the mise cache in the release job that publishes artifacts. --- .github/workflows/ci.yml | 10 +++++++++- .github/workflows/codeql.yml | 4 ++++ .github/workflows/dependabot-automerge.yml | 4 ++++ .github/workflows/hk.yml | 6 ++++-- .github/workflows/release-please.yml | 4 ++++ .github/workflows/release.yml | 11 ++++++++++- 6 files changed, 35 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6a52432..bd9844e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,7 +43,7 @@ jobs: contents: read services: postgres: - image: postgres:18.6-alpine + image: postgres:18.6-alpine@sha256:9ba53c7d41ea093baf5c1ba635ba5434c4f979880527d49bb7d9237d3193085b env: POSTGRES_USER: sqlc POSTGRES_PASSWORD: sqlc @@ -97,6 +97,14 @@ jobs: with: persist-credentials: false + - name: Install ToolConfig + uses: jdx/mise-action@90f833d396d0cc3674b631d2d225e306476c303a # v5.2.10 + with: + install_args: toolconfig + + - name: Check and generate the ToolConfig files + uses: mathematic-inc/toolconfig-action@1baf7b021e8bf6f0e20737753c13af0fc93c8570 # v2026.11.0 + - name: Install buf uses: bufbuild/buf-action@37ac33d8960807670a6e9719080e885197b09cc6 # v1.7.0 with: diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 447633b..97274c3 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -11,6 +11,10 @@ on: permissions: contents: read +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + jobs: analyze: name: Analyze (${{ matrix.language }}) diff --git a/.github/workflows/dependabot-automerge.yml b/.github/workflows/dependabot-automerge.yml index 070c1f6..c3f0876 100644 --- a/.github/workflows/dependabot-automerge.yml +++ b/.github/workflows/dependabot-automerge.yml @@ -8,6 +8,10 @@ on: permissions: {} +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + jobs: strict-gate: name: Strict Dependabot gate diff --git a/.github/workflows/hk.yml b/.github/workflows/hk.yml index dea3ceb..18666ef 100644 --- a/.github/workflows/hk.yml +++ b/.github/workflows/hk.yml @@ -28,10 +28,12 @@ jobs: fetch-depth: 0 persist-credentials: false - name: Install tools - uses: jdx/mise-action@b44d12e7d0d8ee7461bb893e1b1993500433185b # v5.2.7 + uses: jdx/mise-action@90f833d396d0cc3674b631d2d225e306476c303a # v5.2.10 + - name: Check and generate the ToolConfig files + uses: mathematic-inc/toolconfig-action@1baf7b021e8bf6f0e20737753c13af0fc93c8570 # v2026.11.0 - name: Audit dependencies if: github.event_name == 'schedule' run: cargo-deny --locked --workspace check - name: Run checks if: github.event_name != 'schedule' - run: hk check --all --slow + run: hk check --all --slow --skip-step toolconfig diff --git a/.github/workflows/release-please.yml b/.github/workflows/release-please.yml index 7aab9ba..bc36610 100644 --- a/.github/workflows/release-please.yml +++ b/.github/workflows/release-please.yml @@ -7,6 +7,10 @@ on: permissions: contents: read +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: false + jobs: release-please: environment: release diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ffd7291..03dbd91 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -26,7 +26,7 @@ jobs: contents: read services: postgres: - image: postgres:18.6-alpine + image: postgres:18.6-alpine@sha256:9ba53c7d41ea093baf5c1ba635ba5434c4f979880527d49bb7d9237d3193085b env: POSTGRES_USER: sqlc POSTGRES_PASSWORD: sqlc @@ -55,6 +55,15 @@ jobs: with: targets: wasm32-wasip1 + - name: Install ToolConfig + uses: jdx/mise-action@90f833d396d0cc3674b631d2d225e306476c303a # v5.2.10 + with: + install_args: toolconfig + cache: false + + - name: Check and generate the ToolConfig files + uses: mathematic-inc/toolconfig-action@1baf7b021e8bf6f0e20737753c13af0fc93c8570 # v2026.11.0 + - name: Format check run: cargo fmt --all --check From 3f98647a78833c9452a18b3b9ef26f0661ef5965 Mon Sep 17 00:00:00 2001 From: Randolf Jung Date: Thu, 19 Nov 2026 20:49:02 -0800 Subject: [PATCH 3/7] fix: pass Clippy and cargo-deny with the organization policy - Add the organization lint table and enable it in each crate. - Add the docs, `#[must_use]` and `# Errors` sections that the lints need. - Derive Debug for the public types. Narrow the visibility of the code generators to the crate. - Move the PostgreSQL type defaults into one table. - Move the array dimension rule into one function. - Allow the lints on the generated modules, which `buf generate` and `sqlc generate` write. - Add a license to the example crates. --- Cargo.toml | 33 ++- examples/advanced-types/Cargo.toml | 4 + examples/advanced-types/src/main.rs | 8 +- examples/basic/Cargo.toml | 4 + examples/basic/src/main.rs | 6 +- examples/batch/Cargo.toml | 4 + examples/batch/src/main.rs | 6 +- examples/borrowed/Cargo.toml | 4 + examples/borrowed/src/main.rs | 6 +- examples/enums/Cargo.toml | 4 + examples/enums/src/main.rs | 6 +- src/catalog.rs | 62 +++-- src/codegen/batch.rs | 14 +- src/codegen/composites.rs | 5 +- src/codegen/copyfrom.rs | 2 +- src/codegen/enums.rs | 2 +- src/codegen/lifetimes.rs | 7 +- src/codegen/mod.rs | 7 +- src/codegen/query.rs | 49 ++-- src/config.rs | 21 +- src/emit.rs | 7 + src/error.rs | 21 +- src/ident.rs | 32 ++- src/lib.rs | 30 ++- src/main.rs | 2 + src/types.rs | 310 ++++++++++++++----------- tests/codegen.rs | 2 + tests/e2e.rs | 2 + tests/e2e/support/mod.rs | 22 +- tests/plugin_owned_view_auto_traits.rs | 2 +- 30 files changed, 429 insertions(+), 255 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index df7293d..1504bcb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,15 +24,6 @@ pkg-fmt = "zip" pkg-url = "{ repo }/releases/download/v{ version }/{ name }-{ version }-{ target }.zip" pkg-fmt = "zip" -[workspace] -resolver = "2" -members = [".", "examples/*"] - -[workspace.dependencies] -serde_json = "1.0.154" -sqlx = { version = "0.9.0", features = ["bigdecimal", "bit-vec", "chrono", "ipnetwork", "mac_address", "postgres", "runtime-tokio", "uuid"] } -tokio = { version = "1.54.1", features = ["full"] } - [lib] name = "sqlc_gen_sqlx" path = "src/lib.rs" @@ -56,6 +47,30 @@ insta = { version = "1.49.0", features = ["filters"] } tempfile = "3.27.0" tokio = { workspace = true } +[lints] +workspace = true + +[workspace] +resolver = "2" +members = [".", "examples/*"] + +[workspace.dependencies] +serde_json = "1.0.154" +sqlx = { version = "0.9.0", features = ["bigdecimal", "bit-vec", "chrono", "ipnetwork", "mac_address", "postgres", "runtime-tokio", "uuid"] } +tokio = { version = "1.54.1", features = ["full"] } + +[workspace.lints.clippy] +all = { level = "deny", priority = -1 } +nursery = { level = "deny", priority = -1 } +pedantic = { level = "deny", priority = -1 } +redundant_pub_crate = "allow" + +[workspace.lints.rust] +missing_debug_implementations = "deny" +missing_docs = "deny" +rust_2018_idioms = { level = "deny", priority = -1 } +unreachable_pub = "deny" + [profile.release] opt-level = "z" strip = "symbols" diff --git a/examples/advanced-types/Cargo.toml b/examples/advanced-types/Cargo.toml index d5862a6..f46a651 100644 --- a/examples/advanced-types/Cargo.toml +++ b/examples/advanced-types/Cargo.toml @@ -2,6 +2,7 @@ name = "advanced-types" version = "0.1.0" edition = "2024" +license = "MIT OR Apache-2.0" publish = false [dependencies] @@ -9,3 +10,6 @@ bigdecimal = "0.4.11" chrono = "0.4.45" sqlx = { workspace = true } tokio = { workspace = true } + +[lints] +workspace = true diff --git a/examples/advanced-types/src/main.rs b/examples/advanced-types/src/main.rs index d893f2a..5bb3e20 100644 --- a/examples/advanced-types/src/main.rs +++ b/examples/advanced-types/src/main.rs @@ -1,3 +1,7 @@ +//! Example of the code that sqlc-gen-sqlx generates for advanced PostgreSQL types. + +// `sqlc generate` writes this module. +#[allow(missing_docs, unreachable_pub)] #[path = "queries.rs"] #[cfg(test)] mod queries; @@ -23,7 +27,7 @@ async fn test_advanced_types_roundtrip() { .await .unwrap(); - let flags = sqlx::types::BitVec::from_bytes(&[0b10101010]); + let flags = sqlx::types::BitVec::from_bytes(&[0b1010_1010]); let now = chrono::Utc::now(); let later = now + chrono::Duration::hours(1); let window = sqlx::postgres::types::PgRange::from(( @@ -43,4 +47,4 @@ async fn test_advanced_types_roundtrip() { assert_eq!(event.name, "conference"); } -fn main() {} +const fn main() {} diff --git a/examples/basic/Cargo.toml b/examples/basic/Cargo.toml index 42d5d47..64ac3f0 100644 --- a/examples/basic/Cargo.toml +++ b/examples/basic/Cargo.toml @@ -2,9 +2,13 @@ name = "basic" version = "0.1.0" edition = "2024" +license = "MIT OR Apache-2.0" publish = false [dependencies] serde_json = { workspace = true } sqlx = { workspace = true } tokio = { workspace = true } + +[lints] +workspace = true diff --git a/examples/basic/src/main.rs b/examples/basic/src/main.rs index 005425f..97d60fe 100644 --- a/examples/basic/src/main.rs +++ b/examples/basic/src/main.rs @@ -1,6 +1,10 @@ +//! Example of the code that sqlc-gen-sqlx generates for basic queries. + #[cfg(test)] use sqlx::{Connection as _, PgConnection}; +// `sqlc generate` writes this module. +#[allow(missing_docs, unreachable_pub)] #[path = "queries.rs"] #[cfg(test)] mod queries; @@ -49,4 +53,4 @@ async fn test_author_roundtrip() { assert_eq!(rows, 1); } -fn main() {} +const fn main() {} diff --git a/examples/batch/Cargo.toml b/examples/batch/Cargo.toml index 4207f64..d3f6e1b 100644 --- a/examples/batch/Cargo.toml +++ b/examples/batch/Cargo.toml @@ -2,6 +2,7 @@ name = "batch" version = "0.1.0" edition = "2024" +license = "MIT OR Apache-2.0" publish = false [dependencies] @@ -9,3 +10,6 @@ futures-core = "0.3.34" futures-util = "0.3.34" sqlx = { workspace = true } tokio = { workspace = true } + +[lints] +workspace = true diff --git a/examples/batch/src/main.rs b/examples/batch/src/main.rs index df85322..bc42076 100644 --- a/examples/batch/src/main.rs +++ b/examples/batch/src/main.rs @@ -1,3 +1,7 @@ +//! Example of the code that sqlc-gen-sqlx generates for batch queries. + +// `sqlc generate` writes this module. +#[allow(missing_docs, unreachable_pub)] #[cfg(test)] #[path = "queries.rs"] mod queries; @@ -53,4 +57,4 @@ async fn test_batch_roundtrip() { assert_eq!(count.0, 0); } -fn main() {} +const fn main() {} diff --git a/examples/borrowed/Cargo.toml b/examples/borrowed/Cargo.toml index 9ae9fe9..350beed 100644 --- a/examples/borrowed/Cargo.toml +++ b/examples/borrowed/Cargo.toml @@ -2,8 +2,12 @@ name = "borrowed" version = "0.1.0" edition = "2024" +license = "MIT OR Apache-2.0" publish = false [dependencies] sqlx = { workspace = true } tokio = { workspace = true } + +[lints] +workspace = true diff --git a/examples/borrowed/src/main.rs b/examples/borrowed/src/main.rs index 8254807..8496dd8 100644 --- a/examples/borrowed/src/main.rs +++ b/examples/borrowed/src/main.rs @@ -1,6 +1,10 @@ +//! Example of the code that sqlc-gen-sqlx generates with borrowed parameter types. + #[cfg(test)] use sqlx::{Connection as _, PgConnection}; +// `sqlc generate` writes this module. +#[allow(missing_docs, unreachable_pub)] #[path = "queries.rs"] #[cfg(test)] mod queries; @@ -48,4 +52,4 @@ async fn test_borrowed_author_roundtrip() { .expect("delete"); } -fn main() {} +const fn main() {} diff --git a/examples/enums/Cargo.toml b/examples/enums/Cargo.toml index 7cf44a9..8529343 100644 --- a/examples/enums/Cargo.toml +++ b/examples/enums/Cargo.toml @@ -2,8 +2,12 @@ name = "enums" version = "0.1.0" edition = "2024" +license = "MIT OR Apache-2.0" publish = false [dependencies] sqlx = { workspace = true } tokio = { workspace = true } + +[lints] +workspace = true diff --git a/examples/enums/src/main.rs b/examples/enums/src/main.rs index e165566..3683a93 100644 --- a/examples/enums/src/main.rs +++ b/examples/enums/src/main.rs @@ -1,3 +1,7 @@ +//! Example of the code that sqlc-gen-sqlx generates for enum types. + +// `sqlc generate` writes this module. +#[allow(missing_docs, unreachable_pub)] #[path = "queries.rs"] #[cfg(test)] mod queries; @@ -60,4 +64,4 @@ async fn test_enum_roundtrip() { assert_eq!(active.len(), 1); } -fn main() {} +const fn main() {} diff --git a/src/catalog.rs b/src/catalog.rs index cc593be..23eae23 100644 --- a/src/catalog.rs +++ b/src/catalog.rs @@ -3,12 +3,17 @@ use crate::{ error::Error, ident::{field_ident, to_pascal_case}, plugin::GenerateRequestView, - types::TypeMap, + types::{TypeMap, array_dimensions}, }; +/// An enum type of the catalog. +#[derive(Debug)] pub struct EnumInfo { + /// Schema of the type. pub schema: String, + /// Name of the type in PostgreSQL. pub pg_name: String, + /// Name of the generated Rust enum. pub rust_name: String, /// Used for `#[sqlx(type_name = "...")]`: "status" in public schema, /// "myschema.status" in non-default schemas. @@ -17,27 +22,46 @@ pub struct EnumInfo { pub vals: Vec, } +/// A field of a composite type. +#[derive(Debug)] pub struct CompositeField { + /// Name of the column in PostgreSQL. pub pg_name: String, + /// Name of the generated Rust field. pub rust_ident: proc_macro2::Ident, /// Always `Option` — composite fields are always nullable on the wire. pub rust_type: String, } +/// A composite type of the catalog. +#[derive(Debug)] pub struct CompositeInfo { + /// Schema of the type. pub schema: String, + /// Name of the type in PostgreSQL. pub pg_name: String, + /// Name of the generated Rust struct. pub rust_name: String, + /// Name for `#[sqlx(type_name = "...")]`, as for [`EnumInfo::type_name`]. pub type_name: String, + /// Fields of the type, in column order. pub fields: Vec, } +/// The custom types of the catalog. +#[derive(Debug)] pub struct CatalogInfo { + /// Enum types. pub enums: Vec, + /// Composite types. pub composites: Vec, } /// Walk the catalog, register discovered custom types into `type_map`, return info for codegen. +/// +/// # Errors +/// +/// Returns an error when a field of a composite type has a PostgreSQL type that is not known. pub fn walk( request: &GenerateRequestView<'_>, type_map: &mut TypeMap, @@ -45,20 +69,23 @@ pub fn walk( let mut enums = Vec::new(); let mut composites = Vec::new(); - let catalog = match request.catalog.as_option() { - Some(c) => c, - None => return Ok(CatalogInfo { enums, composites }), + let Some(catalog) = request.catalog.as_option() else { + return Ok(CatalogInfo { enums, composites }); }; let default_schema = catalog.default_schema; // Phase 1: enums — must be registered before composite fields can reference them. - for schema in catalog.schemas.iter() { - for e in schema.enums.iter() { + for schema in &catalog.schemas { + for e in &schema.enums { let rust_name = make_rust_name(schema.name, e.name, default_schema); let type_name = sqlx_type_name(schema.name, e.name, default_schema); // EnumView.vals is RepeatedView<'a, &'a str> — each item is &str. - let vals: Vec = e.vals.iter().map(|v| v.to_string()).collect(); + let vals: Vec = e + .vals + .iter() + .map(std::string::ToString::to_string) + .collect(); let pg_key = if schema.name == default_schema || schema.name.is_empty() { e.name.to_string() } else { @@ -80,17 +107,16 @@ pub fn walk( // table.rel.name == composite_type.name. If sqlc does not populate tables // for composite types, Task 7 will catch this and the walk logic must be // revised. - for schema in catalog.schemas.iter() { + for schema in &catalog.schemas { let composite_names: std::collections::HashSet<&str> = schema.composite_types.iter().map(|c| c.name).collect(); if composite_names.is_empty() { continue; } - for table in schema.tables.iter() { - let rel = match table.rel.as_option() { - Some(r) => r, - None => continue, + for table in &schema.tables { + let Some(rel) = table.rel.as_option() else { + continue; }; if !composite_names.contains(rel.name) { continue; @@ -100,13 +126,9 @@ pub fn walk( let type_name = sqlx_type_name(schema.name, rel.name, default_schema); let mut fields = Vec::new(); - for col in table.columns.iter() { - let pg_type = col.r#type.as_option().map(|t| t.name).unwrap_or(""); - let array_dims = if col.array_dims > 0 { - col.array_dims as usize - } else { - usize::from(col.is_array) - }; + for col in &table.columns { + let pg_type = col.r#type.as_option().map_or("", |t| t.name); + let array_dims = array_dimensions(col.array_dims, col.is_array); // Intentionally force nullable=true: sqlx deserializes composite // type fields as Option regardless of the NOT NULL constraint. let rust_type = type_map @@ -155,7 +177,7 @@ fn sqlx_type_name(schema: &str, name: &str, default_schema: &str) -> String { if schema == default_schema || schema.is_empty() { name.to_string() } else { - format!("{}.{}", schema, name) + format!("{schema}.{name}") } } diff --git a/src/codegen/batch.rs b/src/codegen/batch.rs index c40e18d..80e207d 100644 --- a/src/codegen/batch.rs +++ b/src/codegen/batch.rs @@ -59,7 +59,7 @@ fn batch_stream_method( fn_name: &proc_macro2::Ident, items_ty: &TokenStream, result_ty: &TokenStream, - next_body: TokenStream, + next_body: &TokenStream, ) -> TokenStream { quote! { pub fn #fn_name<'a, E, I>( @@ -86,7 +86,7 @@ fn batch_stream_method( } /// `:batchexec` → `fn foo(items) -> impl Stream>` -pub fn gen_batchexec( +pub(super) fn gen_batchexec( query: &QueryView<'_>, type_map: &TypeMap, config: &Config, @@ -138,12 +138,12 @@ pub fn gen_batchexec( } }; - let method = batch_stream_method(&fn_name, &items_ty, "e! { () }, next_body); + let method = batch_stream_method(&fn_name, &items_ty, "e! { () }, &next_body); Ok(quote! { #params_struct #const_tokens #method }) } /// `:batchone` → `fn foo(items) -> impl Stream>` -pub fn gen_batchone( +pub(super) fn gen_batchone( query: &QueryView<'_>, type_map: &TypeMap, config: &Config, @@ -198,12 +198,12 @@ pub fn gen_batchone( } }; - let method = batch_stream_method(&fn_name, &items_ty, "e! { #row_name }, next_body); + let method = batch_stream_method(&fn_name, &items_ty, "e! { #row_name }, &next_body); Ok(quote! { #params_struct #const_tokens #row_tokens #method }) } /// `:batchmany` → `fn foo(items) -> impl Stream, Error>>` -pub fn gen_batchmany( +pub(super) fn gen_batchmany( query: &QueryView<'_>, type_map: &TypeMap, config: &Config, @@ -258,6 +258,6 @@ pub fn gen_batchmany( } }; - let method = batch_stream_method(&fn_name, &items_ty, "e! { Vec<#row_name> }, next_body); + let method = batch_stream_method(&fn_name, &items_ty, "e! { Vec<#row_name> }, &next_body); Ok(quote! { #params_struct #const_tokens #row_tokens #method }) } diff --git a/src/codegen/composites.rs b/src/codegen/composites.rs index cc0c9f2..45f2deb 100644 --- a/src/codegen/composites.rs +++ b/src/codegen/composites.rs @@ -17,7 +17,10 @@ use crate::{catalog::CompositeInfo, error::Error, ident::type_ident}; /// pub zip: Option, /// } /// ``` -pub fn gen_composite(info: &CompositeInfo, extra_derives: &[String]) -> Result { +pub(super) fn gen_composite( + info: &CompositeInfo, + extra_derives: &[String], +) -> Result { let rust_name = type_ident(&info.rust_name); let type_name = &info.type_name; diff --git a/src/codegen/copyfrom.rs b/src/codegen/copyfrom.rs index 46b04cf..572d866 100644 --- a/src/codegen/copyfrom.rs +++ b/src/codegen/copyfrom.rs @@ -13,7 +13,7 @@ use crate::{ use super::query::{Param, any_borrowed, maybe_params_struct, resolve_params, sql_const}; -pub fn gen_copyfrom( +pub(super) fn gen_copyfrom( query: &QueryView<'_>, type_map: &TypeMap, config: &Config, diff --git a/src/codegen/enums.rs b/src/codegen/enums.rs index 24edf1b..d7ed5a1 100644 --- a/src/codegen/enums.rs +++ b/src/codegen/enums.rs @@ -22,7 +22,7 @@ use crate::{ /// Inactive, /// } /// ``` -pub fn gen_enum(info: &EnumInfo, extra_derives: &[String]) -> Result { +pub(super) fn gen_enum(info: &EnumInfo, extra_derives: &[String]) -> Result { let rust_name = type_ident(&info.rust_name); let type_name = &info.type_name; diff --git a/src/codegen/lifetimes.rs b/src/codegen/lifetimes.rs index 77492f2..768e048 100644 --- a/src/codegen/lifetimes.rs +++ b/src/codegen/lifetimes.rs @@ -7,7 +7,7 @@ use syn::visit_mut::VisitMut; /// /// Used when emitting borrowed types into positions that cannot rely on /// elision: struct field types and `where Item = ...` clauses. -pub fn inject_lifetime(rust_type: &str, lifetime: &str) -> Result { +pub(crate) fn inject_lifetime(rust_type: &str, lifetime: &str) -> Result { let mut ty: syn::Type = syn::parse_str(rust_type) .map_err(|e| Error::Codegen(format!("invalid Rust type '{rust_type}': {e}")))?; let mut visitor = LifetimeInjector { @@ -23,10 +23,7 @@ struct LifetimeInjector { impl VisitMut for LifetimeInjector { fn visit_type_reference_mut(&mut self, node: &mut syn::TypeReference) { - let needs_inject = match &node.lifetime { - None => true, - Some(lt) => lt.ident == "_", - }; + let needs_inject = node.lifetime.as_ref().is_none_or(|lt| lt.ident == "_"); if needs_inject { node.lifetime = Some(self.lifetime.clone()); } diff --git a/src/codegen/mod.rs b/src/codegen/mod.rs index 1c4cb1f..86445e9 100644 --- a/src/codegen/mod.rs +++ b/src/codegen/mod.rs @@ -10,6 +10,11 @@ mod enums; pub(crate) mod lifetimes; mod query; +/// Generate the Rust source of the output file for a request. +/// +/// # Errors +/// +/// Returns an error when a query, a type or the formatting of the output is not valid. pub fn generate(request: &GenerateRequestView<'_>, config: &Config) -> Result { let mut type_map = TypeMap::new(&config.overrides, &config.copy_cheap_types); let catalog_info = catalog::walk(request, &mut type_map)?; @@ -67,7 +72,7 @@ pub fn generate(request: &GenerateRequestView<'_>, config: &Config) -> Result query::gen_exec(q, &type_map, config, &col_overrides)?, ":execrows" => query::gen_execrows(q, &type_map, config, &col_overrides)?, diff --git a/src/codegen/query.rs b/src/codegen/query.rs index 3d7e339..fe1eae0 100644 --- a/src/codegen/query.rs +++ b/src/codegen/query.rs @@ -8,7 +8,7 @@ use crate::{ error::Error, ident::{field_ident, query_params_name, to_pascal_case, to_snake_case, type_ident}, plugin::{ColumnView, ParameterView, QueryView}, - types::{ColumnOverride, ResolvedType, TypeMap}, + types::{ColumnOverride, ResolvedType, TypeMap, array_dimensions}, }; /// Resolved parameter: Rust identifier + type. @@ -30,16 +30,16 @@ impl Param { .unwrap_or(&self.resolved.rust_type) } - pub(crate) fn is_borrowed(&self) -> bool { + pub(crate) const fn is_borrowed(&self) -> bool { self.resolved.borrowed_rust_type.is_some() } } /// Columns from an embedded table (`sqlc.embed(table)`), grouped together. pub(crate) struct EmbeddedGroup { - /// snake_case field name in the parent struct, e.g. `author` + /// `snake_case` field name in the parent struct, e.g. `author` pub(crate) embed_field_ident: proc_macro2::Ident, - /// PascalCase struct name for the sub-struct, e.g. `AuthorEmbed` + /// `PascalCase` struct name for the sub-struct, e.g. `AuthorEmbed` pub(crate) struct_ident: proc_macro2::Ident, /// Fields of the sub-struct in declaration order pub(crate) fields: Vec<(proc_macro2::Ident, ResolvedType)>, @@ -64,14 +64,12 @@ pub(crate) fn resolve_params<'a>( .column .as_option() .ok_or_else(|| Error::Codegen("parameter missing column".into()))?; - let pg_type = col.r#type.as_option().map(|t| t.name).unwrap_or(""); + let pg_type = col.r#type.as_option().map_or("", |t| t.name); let nullable = !col.not_null; let array_dims = if col.is_sqlc_slice { 1usize - } else if col.array_dims > 0 { - col.array_dims as usize } else { - usize::from(col.is_array) + array_dimensions(col.array_dims, col.is_array) }; let col_key = col .table @@ -157,12 +155,7 @@ pub(crate) fn bind_calls(params: &[Param], use_arg: Option<&proc_macro2::Ident>) params .iter() .map(|p| { - let ident = &p.ident; - let value = if let Some(arg) = use_arg { - quote! { #arg.#ident } - } else { - quote! { #ident } - }; + let value = param_value_expr(p, use_arg); quote! { .bind(#value) } }) .collect() @@ -170,11 +163,7 @@ pub(crate) fn bind_calls(params: &[Param], use_arg: Option<&proc_macro2::Ident>) fn param_value_expr(param: &Param, use_arg: Option<&proc_macro2::Ident>) -> TokenStream { let ident = ¶m.ident; - if let Some(arg) = use_arg { - quote! { #arg.#ident } - } else { - quote! { #ident } - } + use_arg.map_or_else(|| quote! { #ident }, |arg| quote! { #arg.#ident }) } fn ordered_params(params: &[Param]) -> Vec<&Param> { @@ -239,7 +228,7 @@ pub(crate) fn dynamic_sql_setup( let last_idx = ordered.len().saturating_sub(1); for (idx, param) in ordered.iter().enumerate() { let is_last = idx == last_idx; - let placeholder_ident = format_ident!("placeholder_{}", param.number as usize); + let placeholder_ident = format_ident!("placeholder_{}", param.number.unsigned_abs()); tokens.push(quote! { let #placeholder_ident = next_placeholder; }); @@ -337,16 +326,12 @@ pub(crate) fn resolve_columns<'a>( let mut embedded_groups: Vec<(String, Vec<(proc_macro2::Ident, ResolvedType)>)> = Vec::new(); for col in cols { - let pg_type = col.r#type.as_option().map(|t| t.name).unwrap_or(""); + let pg_type = col.r#type.as_option().map_or("", |t| t.name); if pg_type.is_empty() { return Err(Error::Codegen(format!("column '{}' has no type", col.name))); } let nullable = !col.not_null; - let array_dims = if col.array_dims > 0 { - col.array_dims as usize - } else { - usize::from(col.is_array) - }; + let array_dims = array_dimensions(col.array_dims, col.is_array); let col_key = col .table .as_option() @@ -481,7 +466,7 @@ pub(crate) fn build_fn_params( } /// `:one` → `async fn foo(mut db: E, [params]) -> Result` -pub fn gen_one( +pub(super) fn gen_one( query: &QueryView<'_>, type_map: &TypeMap, config: &Config, @@ -533,7 +518,7 @@ pub fn gen_one( } /// `:many` → `async fn foo(mut db: E, [params]) -> Result, sqlx::Error>` -pub fn gen_many( +pub(super) fn gen_many( query: &QueryView<'_>, type_map: &TypeMap, config: &Config, @@ -583,7 +568,7 @@ pub fn gen_many( } /// `:execrows` → `async fn foo(mut db: E, [params]) -> Result` -pub fn gen_execrows( +pub(super) fn gen_execrows( query: &QueryView<'_>, type_map: &TypeMap, config: &Config, @@ -623,7 +608,7 @@ pub fn gen_execrows( } /// `:execresult` → `async fn foo(mut db: E, [params]) -> Result` -pub fn gen_execresult( +pub(super) fn gen_execresult( query: &QueryView<'_>, type_map: &TypeMap, config: &Config, @@ -661,7 +646,7 @@ pub fn gen_execresult( } /// `:exec` → `async fn foo(mut db: E, [params]) -> Result<(), sqlx::Error>` -pub fn gen_exec( +pub(super) fn gen_exec( query: &QueryView<'_>, type_map: &TypeMap, config: &Config, @@ -711,7 +696,7 @@ pub fn gen_exec( /// `:execlastid` → `async fn foo(mut db: E, [params]) -> Result` /// where T is the type of the single RETURNING column. -pub fn gen_execlastid( +pub(super) fn gen_execlastid( query: &QueryView<'_>, type_map: &TypeMap, config: &Config, diff --git a/src/config.rs b/src/config.rs index b3cccda..48c9094 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,13 +1,20 @@ use crate::error::Error; +/// Plugin options, from `options` in `sqlc.yaml`. #[derive(Debug, serde::Deserialize)] #[serde(default)] pub struct Config { + /// Name of the output file. pub output: String, + /// Type overrides, for PostgreSQL types and for columns. pub overrides: Vec, + /// Extra derives for row and params structs. pub row_derives: Vec, + /// Extra derives for generated enum types. pub enum_derives: Vec, + /// Extra derives for generated composite types. pub composite_derives: Vec, + /// Type names to mark as cheap to copy. pub copy_cheap_types: Vec, } @@ -25,8 +32,14 @@ impl Default for Config { } impl Config { + /// Parse the plugin options from JSON. + /// + /// # Errors + /// + /// Returns an error when the JSON is not valid, or when an override sets no Rust type or an + /// invalid `borrowed_rs_type`. pub fn from_bytes(bytes: &[u8]) -> Result { - let cfg: Config = serde_json::from_slice(bytes)?; + let cfg: Self = serde_json::from_slice(bytes)?; for o in &cfg.overrides { let target = || { o.db_type @@ -68,9 +81,12 @@ fn validate_borrowed_type(rs_type: &str, target: &str) -> Result<(), Error> { Ok(()) } +/// An override of the Rust type of a PostgreSQL type or of one column. #[derive(Debug, serde::Deserialize)] pub struct TypeOverride { + /// PostgreSQL type that the override applies to. pub db_type: Option, + /// Column, as `table.column`, that the override applies to. pub column: Option, /// Owned Rust type for rows and array contents. Optional when /// `borrowed_rs_type` is set; missing values fall back to the built-in @@ -82,6 +98,7 @@ pub struct TypeOverride { /// lifetime), while rows and array contents continue to use the owned /// form. pub borrowed_rs_type: Option, + /// Whether the type is cheap to copy. #[serde(default)] pub copy_cheap: bool, } @@ -95,7 +112,7 @@ mod tests { let c = Config::from_bytes(b"{}").unwrap(); assert_eq!(c.output, "queries.rs"); assert!(c.overrides.is_empty()); - assert!(c.row_derives.is_empty()); + assert_eq!(c.row_derives, Vec::::new()); } #[test] diff --git a/src/emit.rs b/src/emit.rs index 3089637..79a00eb 100644 --- a/src/emit.rs +++ b/src/emit.rs @@ -2,6 +2,7 @@ use crate::error::Error; /// Collects `TokenStream` fragments and formats them into a Rust source file /// using `prettyplease`. +#[derive(Debug)] pub struct FileEmitter { sqlc_version: String, plugin_version: String, @@ -9,6 +10,8 @@ pub struct FileEmitter { } impl FileEmitter { + /// Start an empty file. The versions go into the header. + #[must_use] pub fn new(sqlc_version: &str, plugin_version: &str) -> Self { Self { sqlc_version: sqlc_version.to_string(), @@ -23,6 +26,10 @@ impl FileEmitter { } /// Render all items into a formatted Rust source string. + /// + /// # Errors + /// + /// Returns an error when the items are not valid Rust. pub fn finish(self) -> Result { use quote::quote; diff --git a/src/error.rs b/src/error.rs index cc34281..f9c4c9a 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,18 +1,23 @@ +/// An error of the plugin. #[derive(Debug)] pub enum Error { + /// Reading stdin or writing stdout failed. Io(std::io::Error), + /// The request is not valid protobuf. Decode(buffa::DecodeError), + /// The plugin options are not valid JSON. Json(serde_json::Error), + /// The code generation failed. The text says why. Codegen(String), } impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Error::Io(e) => write!(f, "io error: {e}"), - Error::Decode(e) => write!(f, "proto decode error: {e}"), - Error::Json(e) => write!(f, "json error: {e}"), - Error::Codegen(msg) => write!(f, "codegen error: {msg}"), + Self::Io(e) => write!(f, "io error: {e}"), + Self::Decode(e) => write!(f, "proto decode error: {e}"), + Self::Json(e) => write!(f, "json error: {e}"), + Self::Codegen(msg) => write!(f, "codegen error: {msg}"), } } } @@ -20,10 +25,10 @@ impl std::fmt::Display for Error { impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { - Error::Io(e) => Some(e), - Error::Decode(e) => Some(e), - Error::Json(e) => Some(e), - Error::Codegen(_) => None, + Self::Io(e) => Some(e), + Self::Decode(e) => Some(e), + Self::Json(e) => Some(e), + Self::Codegen(_) => None, } } } diff --git a/src/ident.rs b/src/ident.rs index be4a71e..a05ef81 100644 --- a/src/ident.rs +++ b/src/ident.rs @@ -8,6 +8,8 @@ const KEYWORDS: &[&str] = &[ "override", "priv", "try", "typeof", "unsized", "virtual", "yield", ]; +/// Replace each character that is not alphanumeric or `_` with `_`. +#[must_use] pub fn normalize_ident(s: &str) -> String { s.chars() .map(|c| { @@ -20,14 +22,20 @@ pub fn normalize_ident(s: &str) -> String { .collect() } +/// Convert a name to `snake_case`. +#[must_use] pub fn to_snake_case(s: &str) -> String { normalize_ident(s).to_case(Case::Snake) } +/// Convert a name to `PascalCase`. +#[must_use] pub fn to_pascal_case(s: &str) -> String { normalize_ident(s).to_case(Case::Pascal) } +/// Make a field name in `snake_case`, with `r#` for a keyword. +#[must_use] pub fn field_ident(name: &str) -> proc_macro2::Ident { let snake = to_snake_case(name); if KEYWORDS.contains(&snake.as_str()) { @@ -37,15 +45,19 @@ pub fn field_ident(name: &str) -> proc_macro2::Ident { } } +/// Make a type name in `PascalCase`. +#[must_use] pub fn type_ident(name: &str) -> proc_macro2::Ident { quote::format_ident!("{}", to_pascal_case(name)) } -/// For enum variants: PascalCase with keyword escaping. -/// Converts `val` to PascalCase, then checks whether the result would -/// collide with a Rust keyword by checking both the PascalCase form and -/// its snake_case equivalent against the keyword list. -/// Example: "type" → PascalCase "Type" → snake "type" → keyword → emits `r#Type`. +/// For enum variants: `PascalCase` with keyword escaping. +/// +/// Converts `val` to `PascalCase`, then checks whether the result would +/// collide with a Rust keyword by checking both the `PascalCase` form and +/// its `snake_case` equivalent against the keyword list. +/// Example: "type" → `PascalCase` "Type" → snake "type" → keyword → emits `r#Type`. +#[must_use] pub fn variant_ident(name: &str) -> proc_macro2::Ident { let pascal = to_pascal_case(name); let snake = to_snake_case(&pascal); @@ -53,20 +65,24 @@ pub fn variant_ident(name: &str) -> proc_macro2::Ident { // Only use raw identifier if the pascal form itself can be raw-escaped. // Some keywords like `Self` cannot appear as raw identifiers, so we // append an underscore as a fallback. - if !["Self", "true", "false"].contains(&pascal.as_str()) { - quote::format_ident!("r#{}", pascal) - } else { + if ["Self", "true", "false"].contains(&pascal.as_str()) { quote::format_ident!("{}_", pascal) + } else { + quote::format_ident!("r#{}", pascal) } } else { quote::format_ident!("{}", pascal) } } +/// Name of the params struct of a query. +#[must_use] pub fn query_params_name(query_name: &str) -> String { format!("{}Params", to_pascal_case(query_name)) } +/// Name of the row struct of a query. +#[must_use] pub fn query_row_name(query_name: &str) -> String { format!("{}Row", to_pascal_case(query_name)) } diff --git a/src/lib.rs b/src/lib.rs index c190995..7477942 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,11 +1,30 @@ +//! A sqlc plugin that generates type-safe sqlx Rust code from SQL queries. + +/// Enum and composite types of the sqlc catalog. pub mod catalog; +/// Rust code for the queries and types of a sqlc request. pub mod codegen; +/// Plugin options. pub mod config; +/// Formatted Rust source of the output file. pub mod emit; +/// Errors of the plugin. pub mod error; +/// Rust identifiers made from PostgreSQL names. pub mod ident; +/// Rust types for PostgreSQL types. pub mod types; +// `buf generate` writes this module. +#[allow( + clippy::all, + clippy::nursery, + clippy::pedantic, + missing_debug_implementations, + missing_docs, + rust_2018_idioms, + unreachable_pub +)] #[path = "mod.rs"] mod generated; pub use generated::plugin; @@ -16,6 +35,10 @@ use buffa::{Message as _, MessageView as _}; use plugin::{GenerateRequestView, GenerateResponse}; /// WASI binary entry: read stdin → process → write stdout. +/// +/// # Errors +/// +/// Returns an error when stdin or stdout fails, or when [`run_with_bytes`] fails. pub fn run() -> Result<(), Error> { use std::io::{Read, Write}; let mut buf = Vec::new(); @@ -26,6 +49,11 @@ pub fn run() -> Result<(), Error> { } /// Testable core: bytes in, bytes out. +/// +/// # Errors +/// +/// Returns an error when the request or the plugin options are not valid, or when the code +/// generation fails. pub fn run_with_bytes(buf: &[u8]) -> Result, Error> { let request = GenerateRequestView::decode_view(buf)?; let config = if request.plugin_options.is_empty() { @@ -36,7 +64,7 @@ pub fn run_with_bytes(buf: &[u8]) -> Result, Error> { let code = codegen::generate(&request, &config)?; let response = GenerateResponse { files: vec![plugin::File { - name: config.output.clone(), + name: config.output, contents: code.into_bytes(), ..Default::default() }], diff --git a/src/main.rs b/src/main.rs index b2559af..bafaa60 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,5 @@ +//! The `sqlc-gen-sqlx` plugin executable. + fn main() { if let Err(e) = sqlc_gen_sqlx::run() { eprintln!("sqlc-gen-sqlx: {e}"); diff --git a/src/types.rs b/src/types.rs index e9bc370..21f5f6a 100644 --- a/src/types.rs +++ b/src/types.rs @@ -1,6 +1,7 @@ use crate::config::TypeOverride; use std::collections::HashMap; +/// A Rust type that a PostgreSQL type resolved to. #[derive(Debug, Clone)] pub struct ResolvedType { /// Owned Rust type used for row struct fields, array contents, and any @@ -14,6 +15,7 @@ pub struct ResolvedType { /// codegen runs a lifetime-injection pass when emitting into positions /// that require a named lifetime (struct field, where clause). pub borrowed_rust_type: Option, + /// Whether the value is cheap to copy. A nullable or array type is never cheap to copy. pub copy_cheap: bool, } @@ -29,33 +31,24 @@ struct OverrideEntry { copy_cheap: bool, } -pub struct TypeMap { - defaults: HashMap<&'static str, (&'static str, bool)>, - type_overrides: HashMap, - custom_types: HashMap, -} - -impl TypeMap { - pub fn new(overrides: &[TypeOverride], copy_cheap_types: &[String]) -> Self { - let mut defaults: HashMap<&'static str, (&'static str, bool)> = HashMap::new(); - - // Boolean - for n in ["bool", "boolean", "pg_catalog.bool"] { - defaults.insert(n, ("bool", true)); - } - - // Integer types - for n in [ +/// Built-in PostgreSQL type names. Each row gives the names of one type, its Rust type, and +/// whether the Rust type is cheap to copy. +const DEFAULT_TYPES: &[(&[&str], &str, bool)] = &[ + (&["bool", "boolean", "pg_catalog.bool"], "bool", true), + ( + &[ "int2", "smallint", "pg_catalog.int2", "smallserial", "serial2", "pg_catalog.serial2", - ] { - defaults.insert(n, ("i16", true)); - } - for n in [ + ], + "i16", + true, + ), + ( + &[ "int4", "integer", "int", @@ -63,35 +56,35 @@ impl TypeMap { "serial", "serial4", "pg_catalog.serial4", - ] { - defaults.insert(n, ("i32", true)); - } - for n in [ + ], + "i32", + true, + ), + ( + &[ "int8", "bigint", "pg_catalog.int8", "bigserial", "serial8", "pg_catalog.serial8", - ] { - defaults.insert(n, ("i64", true)); - } - - // Float types - for n in ["float4", "real", "pg_catalog.float4"] { - defaults.insert(n, ("f32", true)); - } - for n in ["float8", "float", "double precision", "pg_catalog.float8"] { - defaults.insert(n, ("f64", true)); - } - - // Decimal / numeric types - for n in ["numeric", "decimal", "pg_catalog.numeric"] { - defaults.insert(n, ("bigdecimal::BigDecimal", false)); - } - - // String types - for n in [ + ], + "i64", + true, + ), + (&["float4", "real", "pg_catalog.float4"], "f32", true), + ( + &["float8", "float", "double precision", "pg_catalog.float8"], + "f64", + true, + ), + ( + &["numeric", "decimal", "pg_catalog.numeric"], + "bigdecimal::BigDecimal", + false, + ), + ( + &[ "text", "varchar", "pg_catalog.varchar", @@ -101,109 +94,113 @@ impl TypeMap { "citext", "name", "pg_catalog.name", - ] { - defaults.insert(n, ("String", false)); - } - - // Bytes - for n in ["bytea", "blob", "pg_catalog.bytea"] { - defaults.insert(n, ("Vec", false)); - } - - // UUID - defaults.insert("uuid", ("uuid::Uuid", true)); - - // JSON - for n in ["json", "jsonb"] { - defaults.insert(n, ("serde_json::Value", false)); - } - - // Timestamps - for n in [ + ], + "String", + false, + ), + (&["bytea", "blob", "pg_catalog.bytea"], "Vec", false), + (&["uuid"], "uuid::Uuid", true), + (&["json", "jsonb"], "serde_json::Value", false), + ( + &[ "timestamptz", "pg_catalog.timestamptz", "timestamp with time zone", - ] { - defaults.insert(n, ("chrono::DateTime", false)); - } - for n in [ + ], + "chrono::DateTime", + false, + ), + ( + &[ "timestamp", "pg_catalog.timestamp", "timestamp without time zone", - ] { - defaults.insert(n, ("chrono::NaiveDateTime", false)); - } - defaults.insert("date", ("chrono::NaiveDate", true)); - for n in ["time", "pg_catalog.time", "time without time zone"] { - defaults.insert(n, ("chrono::NaiveTime", false)); - } - - // Network - for n in ["inet", "cidr"] { - defaults.insert(n, ("ipnetwork::IpNetwork", false)); - } - defaults.insert("macaddr", ("mac_address::MacAddress", true)); - - // Misc - defaults.insert( - "hstore", - ("std::collections::HashMap>", false), - ); - for n in ["interval", "pg_catalog.interval"] { - defaults.insert(n, ("sqlx::postgres::types::PgInterval", false)); - } - defaults.insert("money", ("sqlx::postgres::types::PgMoney", true)); - defaults.insert("oid", ("sqlx::postgres::types::Oid", true)); - defaults.insert("pg_catalog.oid", ("sqlx::postgres::types::Oid", true)); - for n in ["ltree", "lquery"] { - defaults.insert(n, ("String", false)); - } - - // Range types - for n in ["int4range", "pg_catalog.int4range"] { - defaults.insert(n, ("sqlx::postgres::types::PgRange", false)); - } - for n in ["int8range", "pg_catalog.int8range"] { - defaults.insert(n, ("sqlx::postgres::types::PgRange", false)); - } - for n in ["numrange", "pg_catalog.numrange"] { - defaults.insert( - n, - ( - "sqlx::postgres::types::PgRange", - false, - ), - ); - } - for n in ["tsrange", "pg_catalog.tsrange"] { - defaults.insert( - n, - ( - "sqlx::postgres::types::PgRange", - false, - ), - ); - } - for n in ["tstzrange", "pg_catalog.tstzrange"] { - defaults.insert( - n, - ( - "sqlx::postgres::types::PgRange>", - false, - ), - ); - } - for n in ["daterange", "pg_catalog.daterange"] { - defaults.insert( - n, - ("sqlx::postgres::types::PgRange", false), - ); - } + ], + "chrono::NaiveDateTime", + false, + ), + (&["date"], "chrono::NaiveDate", true), + ( + &["time", "pg_catalog.time", "time without time zone"], + "chrono::NaiveTime", + false, + ), + (&["inet", "cidr"], "ipnetwork::IpNetwork", false), + (&["macaddr"], "mac_address::MacAddress", true), + ( + &["hstore"], + "std::collections::HashMap>", + false, + ), + ( + &["interval", "pg_catalog.interval"], + "sqlx::postgres::types::PgInterval", + false, + ), + (&["money"], "sqlx::postgres::types::PgMoney", true), + ( + &["oid", "pg_catalog.oid"], + "sqlx::postgres::types::Oid", + true, + ), + (&["ltree", "lquery"], "String", false), + ( + &["int4range", "pg_catalog.int4range"], + "sqlx::postgres::types::PgRange", + false, + ), + ( + &["int8range", "pg_catalog.int8range"], + "sqlx::postgres::types::PgRange", + false, + ), + ( + &["numrange", "pg_catalog.numrange"], + "sqlx::postgres::types::PgRange", + false, + ), + ( + &["tsrange", "pg_catalog.tsrange"], + "sqlx::postgres::types::PgRange", + false, + ), + ( + &["tstzrange", "pg_catalog.tstzrange"], + "sqlx::postgres::types::PgRange>", + false, + ), + ( + &["daterange", "pg_catalog.daterange"], + "sqlx::postgres::types::PgRange", + false, + ), + ( + &["bit", "varbit", "pg_catalog.varbit"], + "sqlx::types::BitVec", + false, + ), +]; + +/// Map from PostgreSQL type names to Rust types. +#[derive(Debug)] +pub struct TypeMap { + defaults: HashMap<&'static str, (&'static str, bool)>, + type_overrides: HashMap, + custom_types: HashMap, +} - // Bit types - for n in ["bit", "varbit", "pg_catalog.varbit"] { - defaults.insert(n, ("sqlx::types::BitVec", false)); - } +impl TypeMap { + /// Make the map of the built-in types, with the user overrides and cheap-to-copy types applied. + #[must_use] + pub fn new(overrides: &[TypeOverride], copy_cheap_types: &[String]) -> Self { + let defaults: HashMap<&'static str, (&'static str, bool)> = DEFAULT_TYPES + .iter() + .flat_map(|&(names, rust_type, copy_cheap)| { + names + .iter() + .map(move |&name| (name, (rust_type, copy_cheap))) + }) + .collect(); let mut type_overrides: HashMap = HashMap::new(); for o in overrides { @@ -250,6 +247,10 @@ impl TypeMap { .insert(pg_name.to_lowercase(), (rust_name.to_string(), copy_cheap)); } + /// Resolve a PostgreSQL type, with at most one array dimension. + /// + /// Returns `None` when the type is not known. + #[must_use] pub fn resolve_pg_type( &self, pg_type: &str, @@ -259,6 +260,10 @@ impl TypeMap { self.resolve_pg_type_dims(pg_type, nullable, usize::from(is_array)) } + /// Resolve a PostgreSQL type with a number of array dimensions. + /// + /// Returns `None` when the type is not known. + #[must_use] pub fn resolve_pg_type_dims( &self, pg_type: &str, @@ -302,6 +307,11 @@ impl TypeMap { }) } + /// Resolve the type of a column, with at most one array dimension. A column override wins over + /// the type. + /// + /// Returns `None` when the type is not known. + #[must_use] pub fn resolve_column( &self, pg_type: &str, @@ -319,6 +329,11 @@ impl TypeMap { ) } + /// Resolve the type of a column with a number of array dimensions. A column override wins over + /// the type. + /// + /// Returns `None` when the type is not known. + #[must_use] pub fn resolve_column_dims( &self, pg_type: &str, @@ -358,12 +373,16 @@ impl TypeMap { /// Per-column override stored separately from the type-level map. #[derive(Debug, Clone)] pub struct ColumnOverride { + /// Owned Rust type. `None` means the type of the PostgreSQL type. pub owned: Option, + /// Borrowed Rust type. `None` means the override did not opt into borrowed mode. pub borrowed: Option, + /// Whether the value is cheap to copy. pub copy_cheap: bool, } impl ColumnOverride { + /// Make an override that has only an owned type. #[cfg(test)] pub fn owned_form(rust_type: impl Into, copy_cheap: bool) -> Self { Self { @@ -374,6 +393,15 @@ impl ColumnOverride { } } +/// Number of array dimensions of a column. `declared` is the count that sqlc gives. It is 0 when +/// sqlc only sets `is_array`. +pub(crate) fn array_dimensions(declared: i32, is_array: bool) -> usize { + usize::try_from(declared) + .ok() + .filter(|&dims| dims > 0) + .unwrap_or_else(|| usize::from(is_array)) +} + fn wrap_owned(inner: &str, nullable: bool, array_dims: usize) -> String { let mut t = inner.to_string(); for _ in 0..array_dims { @@ -406,6 +434,8 @@ fn wrap_borrowed( } } +/// Collect the overrides that name a column, by column. +#[must_use] pub fn build_column_overrides(overrides: &[TypeOverride]) -> HashMap { overrides .iter() diff --git a/tests/codegen.rs b/tests/codegen.rs index ec58059..b8f2d53 100644 --- a/tests/codegen.rs +++ b/tests/codegen.rs @@ -1,3 +1,5 @@ +//! Snapshot tests of the code that the plugin generates. + use buffa::Message as _; use sqlc_gen_sqlx::plugin::{ Catalog, Column, GenerateRequest, Identifier, Parameter, Query, Schema, Table, diff --git a/tests/e2e.rs b/tests/e2e.rs index ad1aec9..1193de9 100644 --- a/tests/e2e.rs +++ b/tests/e2e.rs @@ -1,3 +1,5 @@ +//! End-to-end test: the generated code compiles and runs against PostgreSQL. + #[path = "e2e/support/mod.rs"] mod support; diff --git a/tests/e2e/support/mod.rs b/tests/e2e/support/mod.rs index cbf43de..3e67ffe 100644 --- a/tests/e2e/support/mod.rs +++ b/tests/e2e/support/mod.rs @@ -10,7 +10,7 @@ use serde_json::json; use tempfile::TempDir; #[derive(Debug)] -pub struct Postgres { +pub(crate) struct Postgres { id: String, } @@ -23,7 +23,7 @@ impl Drop for Postgres { } #[derive(Debug, Clone)] -pub struct Case { +pub(crate) struct Case { pub name: String, pub dir: PathBuf, pub config_name: String, @@ -31,7 +31,7 @@ pub struct Case { pub expected_stderr: Option, } -pub async fn start_postgres() -> Result> { +pub(crate) async fn start_postgres() -> Result> { let id = docker(&[ "run", "--detach", @@ -73,7 +73,7 @@ pub async fn start_postgres() -> Result> { } } -pub fn database_url(postgres: &Postgres) -> Result> { +pub(crate) fn database_url(postgres: &Postgres) -> Result> { let binding = docker(&["port", &postgres.id, "5432/tcp"])?; let port: u16 = binding .rsplit(':') @@ -91,7 +91,7 @@ fn docker(args: &[&str]) -> Result> { Ok(String::from_utf8(output.stdout)?.trim().to_owned()) } -pub fn load_cases() -> Result, Box> { +pub(crate) fn load_cases() -> Result, Box> { let root = cases_root(); let mut cases = Vec::new(); collect_cases(&root, &root, &mut cases)?; @@ -104,7 +104,7 @@ pub fn load_cases() -> Result, Box> { Ok(cases) } -pub fn write_generated_crate(dir: &TempDir, case: &Case) -> Result> { +pub(crate) fn write_generated_crate(dir: &TempDir, case: &Case) -> Result> { let root = dir.path().to_path_buf(); write_file(&root.join("Cargo.toml"), &crate_manifest(&case.name))?; write_file(&root.join("src/lib.rs"), "")?; @@ -117,7 +117,7 @@ pub fn write_generated_crate(dir: &TempDir, case: &Case) -> Result Date: Thu, 19 Nov 2026 20:49:02 -0800 Subject: [PATCH 4/7] docs: fix the rumdl and harper findings - Wrap the Markdown at 80 columns. - Link the discussion form by its full URL. - Write "parameters" in place of "params". --- CONTRIBUTING.md | 15 +++++++++---- README.md | 56 ++++++++++++++++++++++++++++++++++--------------- 2 files changed, 50 insertions(+), 21 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 990492d..1c0240a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,15 +1,22 @@ # Contributing -Mathematic's AI agents handle implementation and maintenance in this repository. Please propose changes in a GitHub Discussion before writing code. +Mathematic's AI agents handle implementation and maintenance in this repository. +Please propose changes in a GitHub Discussion before writing code. ## Propose a change -1. [Start a Discussion](../../discussions/new). +1. [Start a Discussion](https://github.com/mathematic-inc/sqlc-gen-sqlx/discussions/new). 2. Explain the problem and the result you want. 3. Wait for a Mathematic maintainer to review the proposal. -If we accept the proposal, a Mathematic maintainer or one of our agents will implement it and open the pull request. When Mathematic implements a proposal, the implementation PR will link to the Discussion and credit its original author. Reviewing an unsolicited pull request often takes longer than building a reviewed proposal with our agents, so we review the idea first. +If we accept the proposal, a Mathematic maintainer or one of our agents will +implement it and open the pull request. When Mathematic implements a proposal, +the implementation PR will link to the Discussion and credit its original +author. Reviewing an unsolicited pull request often takes longer than building a +reviewed proposal with our agents, so we review the idea first. ## Pull requests -GitHub limits pull request creation to Mathematic maintainers and repository collaborators with write, maintain, or admin access, plus authorized maintenance agents. +GitHub limits pull request creation to Mathematic maintainers and repository +collaborators with write, maintain, or admin access, plus authorized maintenance +agents. diff --git a/README.md b/README.md index 29b8af5..f6652d5 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@ # sqlc-gen-sqlx -A [sqlc](https://sqlc.dev) plugin that generates type-safe [sqlx](https://github.com/transact-rs/sqlx) Rust code from SQL queries. +A [sqlc](https://sqlc.dev) plugin that generates type-safe +[sqlx](https://github.com/transact-rs/sqlx) Rust code from SQL queries. Generated code targets **sqlx 0.9 or newer**. Queries that rewrite their SQL at run time — `sqlc.slice()` parameters that cannot use `= ANY($1)` — pass the @@ -22,9 +23,9 @@ Or declare the GitHub release directly in `mise.toml`: "github:mathematic-inc/sqlc-gen-sqlx" = "latest" ``` -Run `mise install` to download and activate the executable. No custom mise plugin -is required. The Cargo backend (`cargo:sqlc-gen-sqlx`) also supports these releases; -set `cargo.binstall_only = true` to reject source compilation. +Run `mise install` to download and activate the executable. No custom mise +plugin is required. The Cargo backend (`cargo:sqlc-gen-sqlx`) also supports +these releases; set `cargo.binstall_only = true` to reject source compilation. | Platform | Architectures | Archive | | --- | --- | --- | @@ -33,10 +34,11 @@ set `cargo.binstall_only = true` to reject source compilation. | Linux musl | x64, ARM64 | `.tar.gz` | | Windows MSVC | x64, ARM64 | `.zip` | -Every archive includes SHA-256 checksums and GitHub build provenance. CI builds all -eight targets and runs the extracted executables on the matching architecture. -After publication, the release workflow installs through cargo-binstall and mise -and runs both installations. A missing prebuilt binary fails the release checks. +Every archive includes SHA-256 checksums and GitHub build provenance. CI builds +all eight targets and runs the extracted executables on the matching +architecture. After publication, the release workflow installs through +cargo-binstall and mise and runs both installations. A missing prebuilt binary +fails the release checks. The release also includes `sqlc-gen-sqlx.wasm`. Continue using `plugins[].wasm` with its URL and checksum for sqlc's WASM plugin mode. The native executable @@ -48,10 +50,14 @@ For each SQL query annotated with a sqlc command, the plugin emits: - A `const SQL: &str` holding the query text. - A strongly-typed row struct (`QueryNameRow`) for `:one` / `:many`. -- An optional params struct (`QueryNameParams`) when a query has 2+ parameters. -- A free `pub async fn` (or `pub fn` for batch streams) that executes the query, taking the executor as its first argument. +- An optional parameters struct (`QueryNameParams`) when a query has 2+ parameters. +- A free `pub async fn` (or `pub fn` for batch streams) that executes the query, + taking the executor as its first argument. -The executor argument is generic over the `AsExecutor` trait emitted in the same file. `AsExecutor` is implemented for `&PgPool`, `&mut PgConnection`, `&mut Transaction<'_, Postgres>`, `&mut PoolConnection`, and `&mut T` of each — i.e. the natural sqlx reference types: +The executor argument is generic over the `AsExecutor` trait emitted in the same +file. `AsExecutor` is implemented for `&PgPool`, `&mut PgConnection`, +`&mut Transaction<'_, Postgres>`, `&mut PoolConnection`, and `&mut T` +of each — i.e. the natural sqlx reference types: ```rust // From a pool: @@ -97,7 +103,7 @@ All options are passed in `codegen[*].options`: |---|---|---|---| | `output` | string | `queries.rs` | Output filename | | `overrides` | array | `[]` | Type overrides (`rs_type`, optional `borrowed_rs_type`; see below) | -| `row_derives` | array | `[]` | Extra derives for row and params structs | +| `row_derives` | array | `[]` | Extra derives for row and parameters structs | | `enum_derives` | array | `[]` | Extra derives for generated enum types | | `composite_derives` | array | `[]` | Extra derives for generated composite types | | `copy_cheap_types` | array | `[]` | Type names to mark as copy-cheap | @@ -218,18 +224,34 @@ Array types (`type[]`) become `Vec`. Nullable columns become `Option`. | `:batchmany` | `impl Stream, sqlx::Error>>` | Lazily fetch all rows per item | | `:copyfrom` | `Result` | Chunked bulk insert from any `IntoIterator` | -All functions are free `pub async fn` (or `pub fn` for batch streams) at module scope, taking the executor as their first argument. The bound is `E: AsExecutor`, where `AsExecutor` is the trait emitted in each generated file. Impls cover `&PgPool`, `&mut PgConnection`, `&mut Transaction<'_, Postgres>`, `&mut PoolConnection`, and `&mut T` of each. +All functions are free `pub async fn` (or `pub fn` for batch streams) at module +scope, taking the executor as their first argument. The bound is +`E: AsExecutor`, where `AsExecutor` is the trait emitted in each generated file. +Impls cover `&PgPool`, `&mut PgConnection`, `&mut Transaction<'_, Postgres>`, +`&mut PoolConnection`, and `&mut T` of each. -Batch methods generate `Stream`-returning APIs and reference `futures_core` and `futures_util` directly. Consumer crates should include those dependencies alongside `sqlx`. +Batch methods generate `Stream`-returning APIs and reference `futures_core` and +`futures_util` directly. Consumer crates should include those dependencies +alongside `sqlx`. ## sqlc extensions -- **`sqlc.slice()`**: Parameters marked as slice expand to `Vec` and support runtime placeholder expansion for `IN (sqlc.slice(...))`-style queries. -- **`sqlc.embed(table)`**: Result columns from an embedded table become a nested struct with `#[sqlx(flatten)]`. +- **`sqlc.slice()`**: Parameters marked as slice expand to `Vec` and support + runtime placeholder expansion for `IN (sqlc.slice(...))`-style queries. +- **`sqlc.embed(table)`**: Result columns from an embedded table become a nested + struct with `#[sqlx(flatten)]`. ## Contributing -We review change proposals in Discussions before code. [Start a Discussion](https://github.com/mathematic-inc/sqlc-gen-sqlx/discussions/new) and wait for a maintainer's review. If we accept the proposal, a Mathematic maintainer or agent will implement it and open the pull request. When Mathematic implements a proposal, the implementation PR will link to the Discussion and credit its original author. GitHub limits pull request creation to Mathematic maintainers and repository collaborators with write, maintain, or admin access, plus authorized maintenance agents. See [CONTRIBUTING.md](./CONTRIBUTING.md) for the full process. +We review change proposals in Discussions before code. +[Start a Discussion](https://github.com/mathematic-inc/sqlc-gen-sqlx/discussions/new) +and wait for a maintainer's review. If we accept the proposal, a Mathematic +maintainer or agent will implement it and open the pull request. When Mathematic +implements a proposal, the implementation PR will link to the Discussion and +credit its original author. GitHub limits pull request creation to Mathematic +maintainers and repository collaborators with write, maintain, or admin access, +plus authorized maintenance agents. See [CONTRIBUTING.md](./CONTRIBUTING.md) for +the full process. ## License From 6ca00d1ddc432cc9f80211b47a086a446cd447be Mon Sep 17 00:00:00 2001 From: Randolf Jung Date: Thu, 19 Nov 2026 20:49:02 -0800 Subject: [PATCH 5/7] style: format the shell script and the JSON file Format scripts/proto-sync.sh with shfmt and release-please-config.json with oxfmt, at the settings of the policy. --- release-please-config.json | 4 +--- scripts/proto-sync.sh | 10 +++++----- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/release-please-config.json b/release-please-config.json index cf0de8a..29766c9 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -9,7 +9,5 @@ "include-component-in-tag": false } }, - "plugins": [ - "sentence-case" - ] + "plugins": ["sentence-case"] } diff --git a/scripts/proto-sync.sh b/scripts/proto-sync.sh index 1e8ad50..4885807 100755 --- a/scripts/proto-sync.sh +++ b/scripts/proto-sync.sh @@ -8,14 +8,14 @@ OUT_DIR="proto/plugin" LOCK_FILE="proto/UPSTREAM.lock" SHA=$(curl -sSL \ - -H "Accept: application/vnd.github.v3+json" \ - "https://api.github.com/repos/${UPSTREAM_REPO}/commits?path=${PROTO_PATH}&sha=${UPSTREAM_BRANCH}&per_page=1" | - python3 -c "import sys,json; print(json.load(sys.stdin)[0]['sha'])") + -H "Accept: application/vnd.github.v3+json" \ + "https://api.github.com/repos/${UPSTREAM_REPO}/commits?path=${PROTO_PATH}&sha=${UPSTREAM_BRANCH}&per_page=1" | + python3 -c "import sys,json; print(json.load(sys.stdin)[0]['sha'])") mkdir -p "$OUT_DIR" curl -sSL \ - "https://raw.githubusercontent.com/${UPSTREAM_REPO}/${SHA}/${PROTO_PATH}" \ - -o "${OUT_DIR}/codegen.proto" + "https://raw.githubusercontent.com/${UPSTREAM_REPO}/${SHA}/${PROTO_PATH}" \ + -o "${OUT_DIR}/codegen.proto" echo "$SHA" >"$LOCK_FILE" echo "Synced ${PROTO_PATH} at commit ${SHA}" From dd7cb16b061c3dd6004bd521e15a531d9f80ae8e Mon Sep 17 00:00:00 2001 From: Randolf Jung Date: Thu, 19 Nov 2026 20:51:15 -0800 Subject: [PATCH 6/7] chore: pin oxfmt hk runs oxfmt on release-please-config.json. CI had no oxfmt. --- mise.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/mise.toml b/mise.toml index 1bd72b8..dba11d7 100644 --- a/mise.toml +++ b/mise.toml @@ -35,6 +35,7 @@ zizmor = "1.32.0" "aqua:EmbarkStudios/cargo-deny" = { version = "0.21.0", depends = ["rust"] } "aqua:anordal/shellharden" = "4.3.2" "aqua:apple/pkl" = "0.33.1" +"aqua:oxc-project/oxc/oxfmt" = "0.79.0" "aqua:owenlamont/ryl" = "0.30.0" "aqua:sqlc" = "1.31.1" # Compile generators from source so codegen and runtime stay in lockstep. From d81881007bfd4f6aba148f86a00d25fbbe7f4449 Mon Sep 17 00:00:00 2001 From: Randolf Jung Date: Thu, 19 Nov 2026 21:03:27 -0800 Subject: [PATCH 7/7] chore: remove comments that restate the code --- hk.pkl | 5 ++--- src/ident.rs | 5 ----- src/types.rs | 18 ++++-------------- 3 files changed, 6 insertions(+), 22 deletions(-) diff --git a/hk.pkl b/hk.pkl index 98e5224..60eb0a0 100644 --- a/hk.pkl +++ b/hk.pkl @@ -1,10 +1,9 @@ amends ".hk/org.pkl" steps { - // The step of the organization sets no `workspace_indicator`, so hk cannot render the `dir` of - // the builtin step. + // The organization step sets no `workspace_indicator`, so hk cannot render the builtin `dir`. ["cargo-deny"] { dir = "{{root}}" } - // The test database has the user and the password `sqlc`. kingfisher reports its URI. + // kingfisher reports the URI of the test database (user and password `sqlc`). ["kingfisher"] { check = "kingfisher scan {{ files }} --no-update-check --no-validate --quiet --redact --skip-regex 'postgres://sqlc:sqlc@'" diff --git a/src/ident.rs b/src/ident.rs index a05ef81..0d3e204 100644 --- a/src/ident.rs +++ b/src/ident.rs @@ -52,11 +52,6 @@ pub fn type_ident(name: &str) -> proc_macro2::Ident { } /// For enum variants: `PascalCase` with keyword escaping. -/// -/// Converts `val` to `PascalCase`, then checks whether the result would -/// collide with a Rust keyword by checking both the `PascalCase` form and -/// its `snake_case` equivalent against the keyword list. -/// Example: "type" → `PascalCase` "Type" → snake "type" → keyword → emits `r#Type`. #[must_use] pub fn variant_ident(name: &str) -> proc_macro2::Ident { let pascal = to_pascal_case(name); diff --git a/src/types.rs b/src/types.rs index 21f5f6a..c35b09d 100644 --- a/src/types.rs +++ b/src/types.rs @@ -15,7 +15,7 @@ pub struct ResolvedType { /// codegen runs a lifetime-injection pass when emitting into positions /// that require a named lifetime (struct field, where clause). pub borrowed_rust_type: Option, - /// Whether the value is cheap to copy. A nullable or array type is never cheap to copy. + /// Whether the value is cheap to copy. Never true for a nullable or array type. pub copy_cheap: bool, } @@ -31,8 +31,7 @@ struct OverrideEntry { copy_cheap: bool, } -/// Built-in PostgreSQL type names. Each row gives the names of one type, its Rust type, and -/// whether the Rust type is cheap to copy. +/// Each row: the names of one PostgreSQL type, its Rust type, and whether it is cheap to copy. const DEFAULT_TYPES: &[(&[&str], &str, bool)] = &[ (&["bool", "boolean", "pg_catalog.bool"], "bool", true), ( @@ -190,7 +189,7 @@ pub struct TypeMap { } impl TypeMap { - /// Make the map of the built-in types, with the user overrides and cheap-to-copy types applied. + /// Make the map of the built-in types. #[must_use] pub fn new(overrides: &[TypeOverride], copy_cheap_types: &[String]) -> Self { let defaults: HashMap<&'static str, (&'static str, bool)> = DEFAULT_TYPES @@ -248,8 +247,6 @@ impl TypeMap { } /// Resolve a PostgreSQL type, with at most one array dimension. - /// - /// Returns `None` when the type is not known. #[must_use] pub fn resolve_pg_type( &self, @@ -261,8 +258,6 @@ impl TypeMap { } /// Resolve a PostgreSQL type with a number of array dimensions. - /// - /// Returns `None` when the type is not known. #[must_use] pub fn resolve_pg_type_dims( &self, @@ -309,8 +304,6 @@ impl TypeMap { /// Resolve the type of a column, with at most one array dimension. A column override wins over /// the type. - /// - /// Returns `None` when the type is not known. #[must_use] pub fn resolve_column( &self, @@ -331,8 +324,6 @@ impl TypeMap { /// Resolve the type of a column with a number of array dimensions. A column override wins over /// the type. - /// - /// Returns `None` when the type is not known. #[must_use] pub fn resolve_column_dims( &self, @@ -393,8 +384,7 @@ impl ColumnOverride { } } -/// Number of array dimensions of a column. `declared` is the count that sqlc gives. It is 0 when -/// sqlc only sets `is_array`. +/// `declared` is 0 when sqlc only sets `is_array`. pub(crate) fn array_dimensions(declared: i32, is_array: bool) -> usize { usize::try_from(declared) .ok()