@hublo/sentinel 1.7.0-alpha.8 → 1.7.0-alpha.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -256,6 +256,7 @@ The rules live in `sentinel`. Each module keeps a **thin, generated stub** per t
256
256
  - **Rules in sentinel** — one source of truth, versioned.
257
257
  - **Thin stubs per module** — the stub is what keeps the **editor working** (VS Code discovers config by file, real-time lint/type/format stay live) and what **nx** uses to infer targets. Stubs are **generated by `sentinel --init`**, never hand-written; swapping a runner regenerates them.
258
258
  - **Drift guard** — sentinel validates that each stub is _only_ the sanctioned `extends`, with nothing of the preset's overridden. Unsanctioned drift is flagged in CI; a genuine exception must be **declared in an allowlist** (visible, reviewed), never silent. One addition is sanctioned, in lint: what the preset does not govern (a rule it does not name, a plugin, jsPlugin or setting it does not set) is the module's own, kept by `--init`, not drift, and listed by `--inspect`; a rule the preset names, set to another value, or an entry that collides with the preset's, is drift ([lint-adoption.md](docs/lint-adoption.md#what---inspect-calls-drift-and-what-it-lists-as-yours)).
259
+ - **Adopt first, then run the module's own** — every analysis tool starts with an adoption (`--init`: its config file, its scripts, the pinned devDependency); after it, the developer, the CI and an AI run the module's script, so all three use the same version. `static-analysis` and `sql` are the reference implementations ([CONTRIBUTING.md](CONTRIBUTING.md#an-analysis-role-adopt-first-then-everyone-runs-the-modules-own)).
259
260
  - **Per-module install** — `@hublo/sentinel` is added per module, so adoption is **gradual** (migrate lot by lot; a module can adopt sentinel while its neighbour still uses the old config). Root configs are removed only once the **last** module has migrated.
260
261
  - **Runner binaries** (`eslint`, `typescript`, `vite`, `vitest`, …) are **resolved from the adopting module** at run time (sentinel looks for the tool in the module, then falls back to `PATH`), so the editor and nx keep using the exact binary the project already installs. sentinel does **not** declare them as dependencies today, so it does not pin their versions: the module still owns its own `typescript`. Having sentinel dictate those versions (as peer dependencies, so the whole toolchain rides the sentinel version) is the intended end state, and it lands with the tool tickets that actually bundle a runner.
261
262
 
@@ -12,7 +12,7 @@ import {
12
12
  presetNotInstalledYet,
13
13
  registerAdapters,
14
14
  resolve
15
- } from "../chunk-VZZ3DOC3.js";
15
+ } from "../chunk-4TVJXM64.js";
16
16
  import {
17
17
  resolveContext,
18
18
  separateToolArgs
@@ -4556,20 +4556,23 @@ function checkUnsafeCalls(cwd, file, text, readFile, checking = BOTH) {
4556
4556
  let rawCalls = 0;
4557
4557
  const files = new FileCache(readFile);
4558
4558
  files.set(parsed.file);
4559
- const prisma = prismaNames(parsed.file.bindings);
4559
+ const imports = {
4560
+ prisma: prismaNames(parsed.file.bindings),
4561
+ ...driversImported(parsed.file.program)
4562
+ };
4560
4563
  walk(parsed.file.program, (node) => {
4561
- const method = unsafeMethod(node) ?? rawFragment(node, prisma);
4562
- if (method === void 0) return;
4563
- const raw = method === RAW_FRAGMENT;
4564
+ const call = sqlTextCall(node, imports, text);
4565
+ if (call === void 0) return;
4566
+ const raw = call.rule === RAW_FRAGMENT_RULE;
4564
4567
  if (raw ? !checking.raw : !checking.methods) return;
4565
- const sql = node.arguments?.[0];
4566
- if (sql === void 0 || sql.type === "SpreadElement") return;
4568
+ if (call.texts.length === 0) return;
4567
4569
  if (raw) rawCalls++;
4568
4570
  else calls++;
4569
- const pasted = unsafeParts(sql, { file: parsed.file, files, depth: 0, local: /* @__PURE__ */ new Map() });
4571
+ const context2 = { file: parsed.file, files, depth: 0, local: /* @__PURE__ */ new Map() };
4572
+ const pasted = call.texts.flatMap((sql) => unsafeParts(sql, context2));
4570
4573
  const [first] = pasted;
4571
4574
  if (first === void 0) return;
4572
- findings.push(findingOf(file, text, method, sql, first, pasted));
4575
+ findings.push(findingOf(file, text, call, first, pasted));
4573
4576
  });
4574
4577
  return { ok: true, calls, rawCalls, findings };
4575
4578
  }
@@ -4700,15 +4703,94 @@ function candidatesFor(base) {
4700
4703
  ...RESOLVABLE_EXTENSIONS.map((extension) => join22(base, `index${extension}`))
4701
4704
  ];
4702
4705
  }
4703
- function unsafeMethod(node) {
4704
- if (node.type !== "CallExpression") return void 0;
4705
- const callee = unwrap(node.callee);
4706
+ function driversImported(program) {
4707
+ const sources = /* @__PURE__ */ new Set();
4708
+ walk(program, (node) => {
4709
+ if (node.type === "ImportDeclaration" && node.importKind !== "type") {
4710
+ sources.add(node.source.value);
4711
+ } else if (node.type === "CallExpression") {
4712
+ const callee = node.callee;
4713
+ const [first] = node.arguments ?? [];
4714
+ if (callee.type === "Identifier" && callee.name === "require" && first?.type === "Literal" && typeof first.value === "string") {
4715
+ sources.add(first.value);
4716
+ }
4717
+ }
4718
+ });
4719
+ return { pg: sources.has("pg"), postgres: sources.has("postgres") };
4720
+ }
4721
+ function memberName(callee) {
4706
4722
  if (!MEMBER_TYPES.has(callee.type)) return void 0;
4707
4723
  const property = callee.property;
4708
- const name = callee.computed ? property.type === "Literal" && typeof property.value === "string" ? property.value : void 0 : property.name;
4709
- return name !== void 0 && UNSAFE_METHODS.includes(name) ? name : void 0;
4724
+ if (!callee.computed) return property.name;
4725
+ return property.type === "Literal" && typeof property.value === "string" ? property.value : void 0;
4726
+ }
4727
+ function argumentsOf(node) {
4728
+ return (node.arguments ?? []).filter(
4729
+ (argument) => argument.type !== "SpreadElement"
4730
+ );
4731
+ }
4732
+ function sqlTextCall(node, imports, text) {
4733
+ if (node.type !== "CallExpression") return void 0;
4734
+ const callee = unwrap(node.callee);
4735
+ const name = memberName(callee);
4736
+ if (name === void 0) return void 0;
4737
+ const args = argumentsOf(node);
4738
+ const object = unwrap(callee.object);
4739
+ const onPrisma = object.type === "Identifier" && imports.prisma.has(object.name);
4740
+ if (UNSAFE_METHODS.includes(name)) {
4741
+ return {
4742
+ label: name,
4743
+ rule: UNSAFE_RULE,
4744
+ texts: args.slice(0, 1),
4745
+ help: `pass a value as a parameter (\`$1\` in the text, the value after it), or use the tagged ${name.replace("Unsafe", "")}\`\u2026\`, which binds each \`\${}\`; a table or column name cannot be a parameter: take it from a \`const\` of this file`
4746
+ };
4747
+ }
4748
+ if (onPrisma && name === "raw") {
4749
+ return {
4750
+ label: "Prisma.raw",
4751
+ rule: RAW_FRAGMENT_RULE,
4752
+ texts: args.slice(0, 1),
4753
+ help: `Prisma.raw puts its text in the query as SQL, never as a parameter: pass a value as \`\${value}\` in Prisma.sql\`\u2026\`, which binds it; for a keyword or a column name, write each choice as a literal, \`order === 'DESC' ? Prisma.raw('DESC') : Prisma.raw('ASC')\`, or take it from a \`const\` of this file`
4754
+ };
4755
+ }
4756
+ if (onPrisma && name === "join") {
4757
+ return {
4758
+ label: "Prisma.join",
4759
+ rule: RAW_FRAGMENT_RULE,
4760
+ // The list is bound; the separator, prefix and suffix are SQL text.
4761
+ texts: args.slice(1, 4),
4762
+ help: `Prisma.join binds the values of its list, but its separator, prefix and suffix are SQL text: write them as literals (\`Prisma.join(conditions, ' AND ')\`)`
4763
+ };
4764
+ }
4765
+ const shown = sourceOf(text, callee);
4766
+ if (imports.pg && name === "query") {
4767
+ const [first] = args;
4768
+ const sql = first?.type === "ObjectExpression" ? propertyValue(first, "text") : first;
4769
+ return {
4770
+ label: `${shown} (pg)`,
4771
+ rule: UNSAFE_RULE,
4772
+ texts: sql === void 0 ? [] : [sql],
4773
+ help: `pass a value as a parameter: \`$1\` in the text, the value in the array after it (\`client.query(text, [value])\`); a table or column name cannot be a parameter: take it from a \`const\` of this file`
4774
+ };
4775
+ }
4776
+ if (imports.postgres && name === "unsafe") {
4777
+ return {
4778
+ label: `${shown} (postgres)`,
4779
+ rule: UNSAFE_RULE,
4780
+ texts: args.slice(0, 1),
4781
+ help: `use the tagged sql\`\u2026\${value}\u2026\`, which binds each value; for a table or column name, \`sql(name)\` quotes it as an identifier`
4782
+ };
4783
+ }
4784
+ return void 0;
4785
+ }
4786
+ function propertyValue(object, key) {
4787
+ for (const property of object.properties) {
4788
+ if (property.type !== "Property" || property.computed) continue;
4789
+ const name = property.key.name ?? property.key.value;
4790
+ if (name === key) return property.value;
4791
+ }
4792
+ return void 0;
4710
4793
  }
4711
- var RAW_FRAGMENT = "Prisma.raw";
4712
4794
  function prismaNames(bindings) {
4713
4795
  const names = /* @__PURE__ */ new Set();
4714
4796
  for (const [name, bound] of bindings) {
@@ -4719,15 +4801,6 @@ function prismaNames(bindings) {
4719
4801
  }
4720
4802
  return names;
4721
4803
  }
4722
- function rawFragment(node, prisma) {
4723
- if (node.type !== "CallExpression" || prisma.size === 0) return void 0;
4724
- const callee = unwrap(node.callee);
4725
- if (!MEMBER_TYPES.has(callee.type)) return void 0;
4726
- const object = unwrap(callee.object);
4727
- const property = callee.property;
4728
- const name = callee.computed ? property.value : property.name;
4729
- return object.type === "Identifier" && prisma.has(object.name) && name === "raw" ? RAW_FRAGMENT : void 0;
4730
- }
4731
4804
  function unwrap(node) {
4732
4805
  let current = node;
4733
4806
  while ([
@@ -4859,24 +4932,24 @@ function returnedExpression(callback) {
4859
4932
  const [only] = statements;
4860
4933
  return statements.length === 1 && only?.type === "ReturnStatement" && only.argument ? only.argument : void 0;
4861
4934
  }
4862
- function findingOf(file, text, method, sql, first, pasted) {
4935
+ function findingOf(file, text, call, first, pasted) {
4863
4936
  const start = positionOf(text, first.start);
4864
4937
  const end = positionOf(text, Math.max(first.end - 1, first.start));
4865
4938
  const shown = pasted.slice(0, 3).map((part) => `\`${sourceOf(text, part)}\``);
4866
4939
  const more = pasted.length > 3 ? ` and ${pasted.length - 3} more` : "";
4867
- const whole = unwrap(sql) === first;
4868
- const raw = method === RAW_FRAGMENT;
4940
+ const whole = call.texts.some((sql) => unwrap(sql) === first);
4941
+ const method = call.label;
4869
4942
  return {
4870
4943
  file,
4871
4944
  line: start.line,
4872
4945
  column: start.column,
4873
4946
  endLine: end.line,
4874
4947
  endColumn: end.column,
4875
- rule: raw ? RAW_FRAGMENT_RULE : UNSAFE_RULE,
4948
+ rule: call.rule,
4876
4949
  squawkLevel: "Warning",
4877
4950
  message: whole ? `the SQL text of ${method} is ${shown[0]}, which sentinel cannot show is a constant: whatever was pasted into it, wherever it was built, runs as SQL` : `${shown.join(", ")}${more} ${pasted.length === 1 ? "is" : "are"} pasted into the SQL text of ${method}, and sentinel cannot show ${pasted.length === 1 ? "it is" : "they are"} constant: a quote in ${pasted.length === 1 ? "it" : "them"} would end the string and run the rest as SQL`,
4878
4951
  note: null,
4879
- help: raw ? `Prisma.raw puts its text in the query as SQL, never as a parameter: pass a value as \`\${value}\` in Prisma.sql\`\u2026\`, which binds it; for a keyword or a column name, write each choice as a literal, \`order === 'DESC' ? Prisma.raw('DESC') : Prisma.raw('ASC')\`, or take it from a \`const\` of this file` : `pass a value as a parameter (\`$1\` in the text, the value after it), or use the tagged ${method.replace("Unsafe", "")}\`\u2026\`, which binds each \`\${}\`; a table or column name cannot be a parameter: take it from a \`const\` of this file`
4952
+ help: call.help
4880
4953
  };
4881
4954
  }
4882
4955
  function sourceOf(text, node) {
@@ -6633,13 +6706,12 @@ var PLAIN = { count: String, name: (name) => name };
6633
6706
  function checkedCalls({ calls, rawCalls }, rulesOff2, mark = PLAIN) {
6634
6707
  const methods = !rulesOff2.includes(UNSAFE_RULE);
6635
6708
  const raw = !rulesOff2.includes(RAW_FRAGMENT_RULE);
6636
- const unsafe = `${mark.name("$queryRawUnsafe")} / ${mark.name("$executeRawUnsafe")}`;
6637
- if (methods && raw) {
6638
- return `${mark.count(calls)} call(s) to ${unsafe} and ${mark.count(rawCalls)} to ${mark.name("Prisma.raw")}`;
6639
- }
6640
- return methods ? `${mark.count(calls)} call(s) to ${unsafe}` : `${mark.count(rawCalls)} call(s) to ${mark.name("Prisma.raw")}`;
6709
+ const text = `${mark.count(calls)} call(s) taking SQL text (${mark.name("$queryRawUnsafe")} / ${mark.name("$executeRawUnsafe")}, ${mark.name("pg")}, ${mark.name("postgres")})`;
6710
+ const fragments = `${mark.count(rawCalls)} Prisma fragment(s) (${mark.name("Prisma.raw")}, ${mark.name("Prisma.join")})`;
6711
+ if (methods && raw) return `${text} and ${fragments}`;
6712
+ return methods ? text : fragments;
6641
6713
  }
6642
- var CALLED = "$queryRawUnsafe / $executeRawUnsafe / Prisma.raw";
6714
+ var CALLED = "raw SQL ($queryRawUnsafe / $executeRawUnsafe, pg, postgres, Prisma.raw, Prisma.join)";
6643
6715
  function summariseMigrations(outcome) {
6644
6716
  return [
6645
6717
  whatWasRead(outcome),
@@ -6781,7 +6853,7 @@ function counts(report) {
6781
6853
  ${errors === 0 ? "" : cell2(errors, "errors, from rules set to error", true)}
6782
6854
  ${cell2(report.unread.length, "could not be opened", true)}
6783
6855
  ${cell2(syntax, "syntax errors", true)}
6784
- ${cell2(report.unsafe.files.length, "files with an Unsafe or Prisma.raw call")}
6856
+ ${cell2(report.unsafe.files.length, "files with a raw SQL call")}
6785
6857
  </section>`;
6786
6858
  }
6787
6859
  function offSection(report) {
@@ -6870,7 +6942,7 @@ function readSection(report) {
6870
6942
  }
6871
6943
  function unsafeSection(report) {
6872
6944
  const { files, read, unparsed } = report.unsafe;
6873
- const methods = "<code>$queryRawUnsafe</code> / <code>$executeRawUnsafe</code> / <code>Prisma.raw</code>";
6945
+ const methods = "raw SQL (<code>$queryRawUnsafe</code> / <code>$executeRawUnsafe</code>, <code>pg</code>, <code>postgres</code>, <code>Prisma.raw</code>, <code>Prisma.join</code>)";
6874
6946
  const checked = checkedCalls(report.unsafe, report.rulesOff, {
6875
6947
  count: grouped,
6876
6948
  name: (name) => `<code>${escape(name)}</code>`
@@ -6978,18 +7050,17 @@ function renderMarkdown3(report) {
6978
7050
  ].join("\n");
6979
7051
  }
6980
7052
  function headline2(report) {
6981
- if (report.base === null)
6982
- return "No migration and no `Unsafe` or `Prisma.raw` call in this module.";
7053
+ if (report.base === null) return "No migration and no raw SQL call in this module.";
6983
7054
  const against = `compared with \`${report.base.ref}\` at \`${report.base.commit}\``;
6984
7055
  const migrations = report.read.length;
6985
7056
  const files = report.unsafe.read.length;
6986
7057
  if (migrations === 0 && files === 0) {
6987
- return `No migration, \`Unsafe\` or \`Prisma.raw\` call added or changed by this branch, ${against}: nothing to check.`;
7058
+ return `No migration or raw SQL call added or changed by this branch, ${against}: nothing to check.`;
6988
7059
  }
6989
- const counts2 = (count, what) => `**${count}** ${what} call${count === 1 ? "" : "s"}`;
7060
+ const counts2 = (count, what, noun) => `**${count}** ${what} ${noun}${count === 1 ? "" : "s"}`;
6990
7061
  const calls = [
6991
- ...report.rulesOff.includes(UNSAFE_RULE) ? [] : [counts2(report.unsafe.calls, "`Unsafe`")],
6992
- ...report.rulesOff.includes(RAW_FRAGMENT_RULE) ? [] : [counts2(report.unsafe.rawCalls, "`Prisma.raw`")]
7062
+ ...report.rulesOff.includes(UNSAFE_RULE) ? [] : [counts2(report.unsafe.calls, "raw SQL", "call")],
7063
+ ...report.rulesOff.includes(RAW_FRAGMENT_RULE) ? [] : [counts2(report.unsafe.rawCalls, "Prisma", "fragment")]
6993
7064
  ];
6994
7065
  const items = [
6995
7066
  ...migrations > 0 ? [`**${migrations}** migration${migrations === 1 ? "" : "s"}`] : [],
@@ -7057,7 +7128,7 @@ function unsafeBlock(report) {
7057
7128
  if (unparsed.length === 0) return [];
7058
7129
  return [
7059
7130
  "",
7060
- `\u2717 **${unparsed.length} TypeScript file(s) could not be read**, so their \`Unsafe\` and \`Prisma.raw\` calls are not checked:`,
7131
+ `\u2717 **${unparsed.length} TypeScript file(s) could not be read**, so their raw SQL calls are not checked:`,
7061
7132
  ...unparsed.map(({ file, reason }) => `- \`${file}\`: ${reason}`)
7062
7133
  ];
7063
7134
  }
@@ -7132,11 +7203,15 @@ function codeFiles(cwd, settings) {
7132
7203
  }
7133
7204
  var UNSAFE_CALL = /\$(?:queryRaw|executeRaw)Unsafe\b/;
7134
7205
  var PRISMA_IMPORT = /from\s*['"]@prisma\//;
7135
- var RAW_CALL = /\.raw\s*\(/;
7206
+ var RAW_CALL = /\.raw\s*\(|Prisma\.join\s*\(/;
7207
+ var PG_IMPORT = /from\s*['"]pg['"]|require\(\s*['"]pg['"]\s*\)/;
7208
+ var PG_CALL = /\.query\s*\(/;
7209
+ var POSTGRES_IMPORT = /from\s*['"]postgres['"]|require\(\s*['"]postgres['"]\s*\)/;
7210
+ var POSTGRES_CALL = /\.unsafe\s*\(/;
7136
7211
  function callsUnsafe(cwd, file) {
7137
7212
  try {
7138
7213
  const text = readFileSync16(join26(cwd, file), "utf8");
7139
- return UNSAFE_CALL.test(text) || PRISMA_IMPORT.test(text) && RAW_CALL.test(text);
7214
+ return UNSAFE_CALL.test(text) || PRISMA_IMPORT.test(text) && RAW_CALL.test(text) || PG_IMPORT.test(text) && PG_CALL.test(text) || POSTGRES_IMPORT.test(text) && POSTGRES_CALL.test(text);
7140
7215
  } catch {
7141
7216
  return false;
7142
7217
  }
@@ -7398,7 +7473,7 @@ var SquawkAdapter = class extends BaseAdapter {
7398
7473
  if (!holdsSql(context2.cwd, defaults)) {
7399
7474
  return {
7400
7475
  operations: [],
7401
- skipped: `no migration (${defaults.migrations.include.join(", ")}) and no $queryRawUnsafe / $executeRawUnsafe / Prisma.raw call in this module: nothing for the ${TARGET} role to read.`
7476
+ skipped: `no migration (${defaults.migrations.include.join(", ")}) and no raw SQL call in this module: nothing for the ${TARGET} role to read.`
7402
7477
  };
7403
7478
  }
7404
7479
  const hasConfig = existsSync17(join29(context2.cwd, SQL_CONFIG_FILE));
@@ -7597,7 +7672,7 @@ function initNote(hasConfig, missingScripts) {
7597
7672
  function describeRun(outcome, reading, config) {
7598
7673
  if (outcome.total === 0 && reading.unsafeFiles === 0) {
7599
7674
  return [
7600
- `nothing to read here: no migration (${config.migrations.include.join(", ")}) and no $queryRawUnsafe / $executeRawUnsafe / Prisma.raw call in ${reading.codeFiles} TypeScript file(s).`
7675
+ `nothing to read here: no migration (${config.migrations.include.join(", ")}) and no raw SQL call in ${reading.codeFiles} TypeScript file(s).`
7601
7676
  ];
7602
7677
  }
7603
7678
  return summariseMigrations(outcome);
package/dist/index.js CHANGED
@@ -6,7 +6,7 @@ import {
6
6
  registerAdapters,
7
7
  resolve,
8
8
  setDefaultRunner
9
- } from "./chunk-VZZ3DOC3.js";
9
+ } from "./chunk-4TVJXM64.js";
10
10
  import {
11
11
  BaseAdapter
12
12
  } from "./chunk-ZASD5YPF.js";
@@ -9,10 +9,11 @@ The role reads what a branch adds or changes:
9
9
 
10
10
  - **the Prisma migrations** (`**/migrations/*/migration.sql`), checked by
11
11
  [squawk](https://squawkhq.com) 2.72.0 against PostgreSQL 16.8;
12
- - **the calls to `$queryRawUnsafe` / `$executeRawUnsafe`** in the module's TypeScript, checked by
13
- sentinel's own rule, `unsafe-sql-pasted-value`;
14
- - **the calls to `Prisma.raw`**, checked the same way under a rule of their own,
15
- `unsafe-sql-raw-fragment`.
12
+ - **every call that takes SQL text** in the module's TypeScript, checked by sentinel's own rules:
13
+ `$queryRawUnsafe` / `$executeRawUnsafe`, a `pg` `query` and a postgres.js `unsafe` under
14
+ `unsafe-sql-pasted-value`; the `Prisma.raw` and `Prisma.join` fragments under
15
+ `unsafe-sql-raw-fragment`. The table of [every entry point](#every-way-to-send-sql-text-and-what-reads-it)
16
+ says which are read and why the others need not be.
16
17
 
17
18
  **Every finding is a warning until the module decides otherwise.** Nothing fails a run by default,
18
19
  so adopting the role, or a sentinel upgrade that brings a new squawk rule, never turns a module red.
@@ -41,7 +42,7 @@ module's `package.json`, and pins `@hublo/sentinel` into its `devDependencies`.
41
42
  added sql.config.mjs; added the 3 `sql` scripts; every finding is a warning while the role is being adopted
42
43
  ```
43
44
 
44
- A module that holds no migration and no `Unsafe` or `Prisma.raw` call is skipped by name: there is nothing for the
45
+ A module that holds no migration and no raw SQL call is skipped by name: there is nothing for the
45
46
  role to read. An existing `sql.config.mjs` is the team's and is never rewritten by a re-init.
46
47
 
47
48
  ## Everyday use
@@ -69,7 +70,7 @@ was not:
69
70
 
70
71
  ```
71
72
  read 1 migration(s) this branch adds or changes, compared with origin/main at 63d1ee7. The 1 other(s) in this module are unchanged and not read.
72
- checked 1 call(s) to $queryRawUnsafe / $executeRawUnsafe and 2 to Prisma.raw in the 2 file(s) this branch adds or changes.
73
+ checked 1 call(s) taking SQL text ($queryRawUnsafe / $executeRawUnsafe, pg, postgres) and 2 Prisma fragment(s) (Prisma.raw, Prisma.join) in the 2 file(s) this branch adds or changes.
73
74
  ```
74
75
 
75
76
  This is how the role reads, not a setting.
@@ -87,42 +88,7 @@ no squawk rule off and turns no opt-in rule on: the choice of what runs by defau
87
88
  a module moves it in its own config. `pnpm exec sentinel --inspect --sql --json` lists all 78 rules
88
89
  with the level each has in this module.
89
90
 
90
- <details>
91
- <summary>The 50 squawk rules on by default</summary>
92
-
93
- `adding-field-with-default`, `adding-foreign-key-constraint`, `adding-not-nullable-field`,
94
- `adding-required-field`, `adding-serial-primary-key-field`, `ban-alter-domain-with-add-constraint`,
95
- `ban-alter-identity`, `ban-char-field`, `ban-concurrent-index-creation-in-transaction`,
96
- `ban-create-domain-with-constraint`, `ban-drop-column`, `ban-drop-constraint`, `ban-drop-database`,
97
- `ban-drop-default`, `ban-drop-domain`, `ban-drop-extension`, `ban-drop-function`,
98
- `ban-drop-generated-expression`, `ban-drop-not-null`, `ban-drop-schema`, `ban-drop-sequence`,
99
- `ban-drop-table`, `ban-drop-type`, `ban-drop-view`, `ban-duplicate-column-assignments`,
100
- `ban-set-schema`, `ban-truncate-cascade`, `ban-uncommitted-transaction`, `changing-column-type`,
101
- `constraint-missing-not-valid`, `disallowed-unique-constraint`, `identifier-too-long`,
102
- `prefer-bigint-over-int`, `prefer-bigint-over-smallint`, `prefer-identity`, `prefer-repack`,
103
- `prefer-robust-stmts`, `prefer-text-field`, `prefer-timestamp-tz`, `renaming-column`,
104
- `renaming-object`, `renaming-table`, `require-concurrent-index-creation`,
105
- `require-concurrent-index-deletion`, `require-concurrent-partition-detach`,
106
- `require-concurrent-reindex`, `require-enum-value-ordering`, `require-lock-timeout`,
107
- `require-statement-timeout`, `transaction-nesting`.
108
-
109
- </details>
110
-
111
- <details>
112
- <summary>The 26 opt-in squawk rules, off until given a level</summary>
113
-
114
- `ban-add-column`, `ban-add-composite-attribute`, `ban-add-enum-value`, `ban-alter-database-options`,
115
- `ban-alter-extension`, `ban-alter-function-options`, `ban-alter-generated-expression`,
116
- `ban-alter-policy-condition`, `ban-alter-policy-roles`, `ban-alter-role-options`,
117
- `ban-alter-row-level-security`, `ban-alter-sequence-values`, `ban-alter-system-options`,
118
- `ban-alter-view-options`, `ban-create-policy`, `ban-detach-inheritance`, `ban-disable-trigger`,
119
- `ban-drop-index`, `ban-drop-policy`, `ban-drop-trigger`, `ban-new-write-restriction`,
120
- `ban-replace-view-function`, `ban-replica-identity`, `ban-revoke`, `ban-set-default`,
121
- `require-table-schema`.
122
-
123
- </details>
124
-
125
- The rule pages are squawk's: `https://squawkhq.com/docs/<rule>`.
91
+ Every rule, what it catches and why it matters, is in [What each squawk rule catches](#what-each-squawk-rule-catches) below.
126
92
 
127
93
  ## Rule levels
128
94
 
@@ -192,6 +158,111 @@ sql.config.mjs: `rules['prefer-robust-stmt']` is not a rule of squawk 2.72.0 or
192
158
  An older name squawk still accepts, such as `prefer-timestamptz`, is refused too, with the name to
193
159
  write: squawk reports the rule under its new name, so a level on the old one would never apply.
194
160
 
161
+ ## What each squawk rule catches
162
+
163
+ One line per rule of squawk 2.72.0, written from the rule's own page at that version (`https://squawkhq.com/docs/<rule>`, which has the examples and the safe way to write the change). **On** runs by default; **opt-in** runs once the module gives it a level in `sql.config.mjs`.
164
+
165
+ ### Locks the table: reads or writes wait while it runs
166
+
167
+ | Rule | Runs | What it catches | The risk in production |
168
+ | -------------------------------------- | ------ | ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
169
+ | `adding-field-with-default` | **on** | a column added with a volatile default | the table is rewritten under `ACCESS EXCLUSIVE` (a non-volatile default is free since PostgreSQL 11) |
170
+ | `adding-foreign-key-constraint` | **on** | a foreign key added and validated at once | both tables are scanned under `SHARE ROW EXCLUSIVE`: no write to either while it runs |
171
+ | `adding-serial-primary-key-field` | **on** | a primary key added to an existing table | the index is built under `ACCESS EXCLUSIVE`: no read, no write |
172
+ | `changing-column-type` | **on** | a column type changed | `ACCESS EXCLUSIVE`, the table rewritten for most changes (not for a varchar widening, see sentinel's note), and readers of the old type may break |
173
+ | `constraint-missing-not-valid` | **on** | a constraint added without `NOT VALID` | the whole table is scanned while writes are blocked |
174
+ | `disallowed-unique-constraint` | **on** | a `UNIQUE` constraint added directly | its index is built under `ACCESS EXCLUSIVE`; build it `CONCURRENTLY` first |
175
+ | `prefer-repack` | **on** | `VACUUM FULL` or `CLUSTER` | `ACCESS EXCLUSIVE` for the whole run |
176
+ | `prefer-text-field` | **on** | a `varchar(n)` | changing its size later takes `ACCESS EXCLUSIVE`; `text` needs no such change |
177
+ | `require-concurrent-index-creation` | **on** | an index built without `CONCURRENTLY` | writes are blocked while it builds (sentinel's note: alone in its migration under Prisma) |
178
+ | `require-concurrent-index-deletion` | **on** | an index dropped without `CONCURRENTLY` | `ACCESS EXCLUSIVE` until the drop ends |
179
+ | `require-concurrent-partition-detach` | **on** | a partition detached without `CONCURRENTLY` | `ACCESS EXCLUSIVE` on the table |
180
+ | `require-concurrent-reindex` | **on** | `REINDEX` without `CONCURRENTLY` | `ACCESS EXCLUSIVE` on the index's table |
181
+ | `require-lock-timeout` | **on** | no `lock_timeout` before a statement that locks | a statement waiting for its lock makes every query behind it wait, with no limit |
182
+ | `require-statement-timeout` | **on** | no `statement_timeout` | a long migration holds its locks and resources with no limit |
183
+ | `ban-alter-domain-with-add-constraint` | **on** | a check constraint added to a domain | domains have poor support for online migrations: every column of the domain is checked |
184
+ | `ban-create-domain-with-constraint` | **on** | a domain created with a check constraint | the same poor support, from its creation |
185
+
186
+ ### Breaks the application still running: a deploy runs old and new code side by side, and a rollback does not undo the migration
187
+
188
+ | Rule | Runs | What it catches | The risk in production |
189
+ | -------------------------------- | ------ | -------------------------------------------------- | ------------------------------------------------------------------------ |
190
+ | `ban-drop-column` | **on** | a column dropped | the running version still reads or writes it |
191
+ | `ban-drop-table` | **on** | a table dropped | its queries fail |
192
+ | `ban-drop-view` | **on** | a view or materialized view dropped | its queries fail (`42P01`) |
193
+ | `ban-drop-schema` | **on** | a schema dropped | its queries fail; `CASCADE` drops everything in it |
194
+ | `ban-drop-sequence` | **on** | a sequence dropped | `nextval` fails; `CASCADE` removes the defaults using it |
195
+ | `ban-drop-function` | **on** | a function, procedure or aggregate dropped | its calls fail (`42883`) |
196
+ | `ban-drop-type` | **on** | a type, cast or operator dropped | casts naming it fail (`42704`); `CASCADE` drops its columns |
197
+ | `ban-drop-domain` | **on** | a domain dropped | casts and parameters using it fail |
198
+ | `ban-drop-extension` | **on** | an extension dropped | the objects it provides disappear |
199
+ | `ban-drop-database` | **on** | a database dropped | everything in it is gone |
200
+ | `ban-drop-constraint` | **on** | a constraint dropped, or set `NOT ENFORCED` | a guarantee disappears; `ON CONFLICT ON CONSTRAINT` inserts fail at once |
201
+ | `ban-drop-default` | **on** | a default dropped | inserts omitting the column fail (`23502`) or write `NULL` |
202
+ | `ban-drop-not-null` | **on** | a `NOT NULL` dropped | code that never expected `NULL` receives it |
203
+ | `ban-drop-generated-expression` | **on** | a generated column's expression dropped | new rows are no longer computed; inserts omitting it get `NULL` |
204
+ | `ban-alter-identity` | **on** | an identity column changed | inserts with or without an explicit value can fail |
205
+ | `renaming-column` | **on** | a column renamed | the running version uses the old name |
206
+ | `renaming-table` | **on** | a table renamed | the running version uses the old name |
207
+ | `renaming-object` | **on** | another object, or an enum value, renamed | clients using the old name fail |
208
+ | `ban-set-schema` | **on** | an object moved to another schema | its old qualified name fails |
209
+ | `adding-required-field` | **on** | a `NOT NULL` column added with no default | fails at once on a table with rows, and old code cannot insert |
210
+ | `adding-not-nullable-field` | **on** | a column set `NOT NULL` | fails if a row holds `NULL` |
211
+ | `ban-add-column` | opt-in | a column added | `SELECT *` changes shape and positional inserts break |
212
+ | `ban-add-composite-attribute` | opt-in | a composite type attribute added | clients reading the composite get another shape |
213
+ | `ban-add-enum-value` | opt-in | an enum value added | clients that do not know it receive it |
214
+ | `ban-alter-generated-expression` | opt-in | a generated column added or its expression changed | results change shape or value; stored ones are rewritten |
215
+ | `ban-alter-sequence-values` | opt-in | sequence options changed | identifiers may be reissued or go out of range |
216
+ | `ban-set-default` | opt-in | a default changed | clients omitting the column write another value |
217
+ | `ban-new-write-restriction` | opt-in | any new constraint, `NOT NULL` or unique index | writes the running version makes may be rejected |
218
+ | `ban-replace-view-function` | opt-in | `CREATE OR REPLACE` on a view, function or trigger | results or side effects change for unchanged SQL |
219
+ | `ban-drop-index` | opt-in | an index dropped | a unique guarantee or a query plan disappears |
220
+ | `ban-drop-trigger` | opt-in | a trigger dropped | its effects stop silently (`updated_at`, audit rows) |
221
+ | `ban-disable-trigger` | opt-in | a trigger or rule disabled or re-enabled | data written differently, or access refused |
222
+ | `ban-detach-inheritance` | opt-in | `DETACH PARTITION` or `NO INHERIT` | the parent table returns other rows |
223
+ | `ban-alter-view-options` | opt-in | view options changed | e.g. `security_invoker` changes who sees what; a rollback keeps it |
224
+ | `ban-alter-function-options` | opt-in | function options changed | execution or security changes, `search_path` included |
225
+ | `ban-alter-extension` | opt-in | `ALTER EXTENSION … UPDATE` or `DROP` | upgrade scripts can remove or change functions |
226
+
227
+ ### Loses data, or fails to apply
228
+
229
+ | Rule | Runs | What it catches | The risk in production |
230
+ | ---------------------------------------------- | ------ | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
231
+ | `ban-truncate-cascade` | **on** | `TRUNCATE … CASCADE` | every table referencing it by foreign key is emptied too |
232
+ | `ban-uncommitted-transaction` | **on** | a `BEGIN` with no `COMMIT` | the migration reports success and applies nothing |
233
+ | `transaction-nesting` | **on** | a `BEGIN` or `COMMIT` inside a transaction | PostgreSQL has one transaction per session: a repeated `BEGIN` or `COMMIT` only warns, and does not do what it says |
234
+ | `ban-concurrent-index-creation-in-transaction` | **on** | `CONCURRENTLY` inside a transaction | PostgreSQL refuses it (`25001`): under Prisma, any file of several statements |
235
+ | `ban-duplicate-column-assignments` | **on** | a column assigned twice in one statement | PostgreSQL raises an error at run time |
236
+ | `prefer-robust-stmts` | **on** | a statement that fails when run twice (no `IF NOT EXISTS`) | a migration that failed halfway fails again when retried |
237
+
238
+ ### Types and names that cause trouble later
239
+
240
+ | Rule | Runs | What it catches | The risk in production |
241
+ | ----------------------------- | ------ | ----------------------------------------------- | ----------------------------------------------------------------------------- |
242
+ | `prefer-bigint-over-int` | **on** | an `int` (32-bit) key or counter | reaches its maximum, 2 147 483 647 |
243
+ | `prefer-bigint-over-smallint` | **on** | a `smallint` (16-bit) | reaches its maximum, 32 767 |
244
+ | `prefer-identity` | **on** | a `serial` column | permissions and schema changes are harder than with `GENERATED … AS IDENTITY` |
245
+ | `prefer-timestamp-tz` | **on** | a `timestamp` without time zone | the UTC offset is dropped: two instants 8 hours apart are stored the same |
246
+ | `ban-char-field` | **on** | a `char(n)` | blank-padded and almost always a mistake for `text` or `varchar` |
247
+ | `identifier-too-long` | **on** | a name over 63 bytes | PostgreSQL truncates it, and the real name differs from the one written |
248
+ | `require-enum-value-ordering` | **on** | an enum value added without `BEFORE` or `AFTER` | it lands last, which breaks an order that means something (status, priority) |
249
+ | `require-table-schema` | opt-in | a table named without its schema | resolved by `search_path`, which may not be the one meant |
250
+
251
+ ### Access, configuration and replication (opt-in)
252
+
253
+ | Rule | Runs | What it catches | The risk in production |
254
+ | ------------------------------ | ------ | ---------------------------------------------- | ----------------------------------------------------------------------- |
255
+ | `ban-alter-database-options` | opt-in | `ALTER DATABASE` options | connection behaviour or results change for every client of the database |
256
+ | `ban-alter-system-options` | opt-in | `ALTER SYSTEM` | server settings change for every database and client |
257
+ | `ban-alter-role-options` | opt-in | `ALTER ROLE` / `ALTER USER` options | access or behaviour changes for clients using the role |
258
+ | `ban-revoke` | opt-in | `REVOKE`, a dropped role, an owner change | queries of existing clients fail; `DROP OWNED` removes objects |
259
+ | `ban-create-policy` | opt-in | `CREATE POLICY` | with row level security on, access changes |
260
+ | `ban-alter-policy-condition` | opt-in | `ALTER POLICY` with `USING` / `WITH CHECK` | clients read or write other rows |
261
+ | `ban-alter-policy-roles` | opt-in | `ALTER POLICY … TO` | the policy applies to other roles |
262
+ | `ban-drop-policy` | opt-in | a policy or rule dropped | access or rewrite behaviour changes |
263
+ | `ban-alter-row-level-security` | opt-in | row level security enabled, disabled or forced | access changes for existing clients |
264
+ | `ban-replica-identity` | opt-in | replica identity or a publication changed | logical replication consumers get stale, missing or changed data |
265
+
195
266
  ## sentinel's notes
196
267
 
197
268
  squawk's advice is written for PostgreSQL in general. Under two rules, sentinel adds a note where
@@ -239,6 +310,21 @@ be a parameter, so take it from a `const` of the file.
239
310
  Measured on the monorepo's 219 calls before the rule was written: the 23 production calls match a
240
311
  classification made by hand, one of them a real injection pasting data into a `VALUES` list.
241
312
 
313
+ **The same rule reads the two drivers the monorepo also uses**, each only in a file that imports
314
+ it (`import … from 'pg'` or `require('pg')`, `import … from 'postgres'`), so a `query` or an
315
+ `unsafe` of anything else is not read:
316
+
317
+ | Driver | The call whose text is SQL | Its safe form | The fix printed |
318
+ | ------------------------ | ----------------------------------------------------------------- | -------------------------------------------------------- | ---------------------------------------------- |
319
+ | `pg` (node-postgres) | `client.query(text, values)`, or `client.query({ text, values })` | `$1` in the text, the value in the array | the parameter |
320
+ | `postgres` (postgres.js) | `sql.unsafe(text)` | the tagged `` sql`…${value}…` ``, which binds each value | the tagged form; `sql(name)` for an identifier |
321
+
322
+ Measured on `main` (f12da701121): 38 calls, 15 reported, none injectable. One is in production,
323
+ `apps/cloud/interop`: a `SET` list built by `.map` from a `const` list of column names, safe by
324
+ construction and reported because the rule does not follow the element of a `.map`. Six are in a
325
+ `mission` integration test (schema and table names the test makes). Eight are in `tools/scripts`,
326
+ outside any module.
327
+
242
328
  ## The `Prisma.raw` rule, `unsafe-sql-raw-fragment`
243
329
 
244
330
  `Prisma.raw(text)` puts its text into a tagged query **as SQL, never as a parameter**: the same
@@ -271,12 +357,35 @@ reported. None of the 77 was found injectable, and none can be proven safe where
271
357
  That is the rule's purpose: on a branch that changes one of these files, the reviewer is told that
272
358
  the safety of the text rests on code the call does not show.
273
359
 
360
+ **`Prisma.join(list, separator, prefix, suffix)`** is read too: Prisma binds the values of its
361
+ list, but its separator, prefix and suffix are SQL text. Measured on `main`: 88 calls with a
362
+ separator, every one a literal (`' AND '`, `' OR '`, `'\n'`), so none is reported.
363
+
364
+ ## Every way to send SQL text, and what reads it
365
+
366
+ Measured on the monorepo (`main` f12da701121), every call that can send text to a database:
367
+
368
+ | Entry point | Calls | Its text is | Read by |
369
+ | ---------------------------------------------------------------------- | ------------: | -------------------------------------------------------- | --------------------------------------- |
370
+ | `` $queryRaw`…` ``, `` $executeRaw`…` ``, `` Prisma.sql`…` `` (tagged) | 332 and 1 079 | a template whose every `${}` Prisma binds | nothing to report: safe by construction |
371
+ | `$queryRaw(sql)` called as a function | 30 | a `Prisma.Sql` object; TypeScript refuses a plain string | nothing to report |
372
+ | `$queryRawUnsafe` / `$executeRawUnsafe` | 219 | SQL | `unsafe-sql-pasted-value` |
373
+ | `pg` `query` | 37 | SQL | `unsafe-sql-pasted-value` |
374
+ | postgres.js `unsafe` | 1 | SQL | `unsafe-sql-pasted-value` |
375
+ | `Prisma.raw` | 97 | SQL, pasted as is | `unsafe-sql-raw-fragment` |
376
+ | `Prisma.join` separator, prefix, suffix | 88 | SQL | `unsafe-sql-raw-fragment` |
377
+ | postgres.js tagged `` sql`…` `` | | a template whose every `${}` the driver binds | nothing to report |
378
+ | knex, TypeORM, Sequelize, mysql | 0 | | not used |
379
+ | MongoDB (35 imports) | | not SQL | outside this role |
380
+
274
381
  ## What the role does not read yet
275
382
 
276
383
  Said here so that a clean report is not read as more than it is:
277
384
 
278
385
  - **The SQL text itself** of a raw query is not parsed: a tagged `$queryRaw` with only parameters is
279
- safe from injection, and its SQL is not checked against any rule.
386
+ safe from injection, and its SQL is not checked against any rule. A syntax error inside it is not
387
+ seen. That is the next step, with libpg-query.
388
+ - **JavaScript files** (`.js`, `.mjs`): the role reads TypeScript (`.ts`, `.mts`, `.cts`).
280
389
  - **Files outside a module.** The role runs on a module; a script at the repository's root that
281
390
  belongs to no module is read by no role.
282
391
  - **What the ORM generates** (`findMany`, `update`, …) is not seen: there is no SQL text to read.
@@ -1433,7 +1433,7 @@ $ sentinel --init --dry-run
1433
1433
  + }
1434
1434
  + }
1435
1435
  + }
1436
- sql: no migration (**/migrations/*/migration.sql) and no $queryRawUnsafe / $executeRawUnsafe / Prisma.raw call in this module: nothing for the sql role to read.
1436
+ sql: no migration (**/migrations/*/migration.sql) and no raw SQL call in this module: nothing for the sql role to read.
1437
1437
  dry run: no files written
1438
1438
  materialized the nest format preset into .oxfmtrc.json (@hublo/sentinel@<version>). oxfmt has no `extends`, so the values live here; `sentinel --status --format` reports modules left behind by a preset change
1439
1439
 
@@ -1673,7 +1673,7 @@ $ sentinel --init --dry-run --rehearse
1673
1673
  + }
1674
1674
  + }
1675
1675
  + }
1676
- sql: no migration (**/migrations/*/migration.sql) and no $queryRawUnsafe / $executeRawUnsafe / Prisma.raw call in this module: nothing for the sql role to read.
1676
+ sql: no migration (**/migrations/*/migration.sql) and no raw SQL call in this module: nothing for the sql role to read.
1677
1677
  dry run: no files written
1678
1678
  materialized the nest format preset into .oxfmtrc.json (@hublo/sentinel@<version>). oxfmt has no `extends`, so the values live here; `sentinel --status --format` reports modules left behind by a preset change
1679
1679
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hublo/sentinel",
3
- "version": "1.7.0-alpha.8",
3
+ "version": "1.7.0-alpha.9",
4
4
  "description": "One CLI that guards code health across Hublo repos: shared lint/typescript/build/test presets, static & dynamic analysis, and architecture checks.",
5
5
  "type": "module",
6
6
  "license": "MIT",