@hublo/sentinel 1.7.0-alpha.7 → 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/dist/index.d.ts CHANGED
@@ -32,7 +32,7 @@ declare function registerAdapters(): void;
32
32
  declare const VERBS: readonly ["run", "inspect", "init", "migrate", "validate", "report", "status"];
33
33
  type Verb = (typeof VERBS)[number];
34
34
  /** Targets: the kind of check. The CLI `--<target>` flags map 1:1 to these. */
35
- declare const TARGETS: readonly ["lint", "format", "typescript", "build", "dev", "test", "static-analysis", "env", "runtime-analysis", "arch"];
35
+ declare const TARGETS: readonly ["lint", "format", "typescript", "build", "dev", "test", "static-analysis", "sql", "env", "runtime-analysis", "arch"];
36
36
  type Target = (typeof TARGETS)[number];
37
37
  /** Presets: the stack preset a project resolves to (strict by default). */
38
38
  declare const PRESET_NAMES: readonly ["react", "nest", "svelte", "node", "tools"];
package/dist/index.js CHANGED
@@ -6,12 +6,14 @@ import {
6
6
  registerAdapters,
7
7
  resolve,
8
8
  setDefaultRunner
9
- } from "./chunk-NSILXJWF.js";
9
+ } from "./chunk-4TVJXM64.js";
10
10
  import {
11
11
  BaseAdapter
12
- } from "./chunk-2LLRSWG2.js";
13
- import "./chunk-ZNANJEMK.js";
14
- import "./chunk-7E6YTTAK.js";
12
+ } from "./chunk-ZASD5YPF.js";
13
+ import "./chunk-JT7ZMH44.js";
14
+ import "./chunk-LX7EG6PJ.js";
15
+ import "./chunk-LU4E4TVD.js";
16
+ import "./chunk-PXTU5MPW.js";
15
17
  import "./chunk-4EIY7TTR.js";
16
18
  import "./chunk-O7REVMOC.js";
17
19
  import "./chunk-QXFCZON7.js";
@@ -0,0 +1,68 @@
1
+ /** A rule's level. `off` is a module's decision, and the report prints it as one. */
2
+ type Severity = 'off' | 'warn' | 'error';
3
+ interface SqlDefaults {
4
+ /** The migration files squawk reads, as globs relative to the module. */
5
+ migrations: {
6
+ /**
7
+ * ⛔ `migration.sql` BY NAME, and that is what keeps the rollback scripts out. Beside the 871
8
+ * migrations sit 385 `down.sql`, 2 `drop.sql` and one `donw.sql`: scripts a human runs by hand,
9
+ * which Prisma never applies. Reading them would report every `DROP` they are made of, for a
10
+ * file that never reaches production through a deploy. Naming the file Prisma applies, rather
11
+ * than excluding the others, also keeps out the misspelling nobody would think to exclude.
12
+ */
13
+ include: string[];
14
+ /** Migrations a module chooses not to read. Empty by default. */
15
+ exclude: string[];
16
+ };
17
+ /** What the `Unsafe` rule reads. */
18
+ unsafe: {
19
+ /**
20
+ * Read the tests too. ON by default: 203 of the 226 `Unsafe` calls are in tests, and a call
21
+ * that is safe today is not safe by construction tomorrow. A module that decides otherwise sets
22
+ * it to false, and the report says so; the decision is the team's.
23
+ */
24
+ includeTests: boolean;
25
+ /**
26
+ * What counts as a test, by PATH. Measured on the monorepo before it was written: the filter
27
+ * `*.spec.*` alone let 149 test calls through as production, because `*.integration-spec.ts`,
28
+ * `*.steps.ts`, `tests/database/` and `*.test-util.ts` are all test code and none of them
29
+ * matches it.
30
+ */
31
+ tests: string[];
32
+ };
33
+ /** Directories never read, whatever the includes say. */
34
+ ignore: string[];
35
+ /**
36
+ * The PostgreSQL version squawk checks against, since some rules depend on it.
37
+ *
38
+ * 16.8 is the version the monorepo pins (`postgres:16.8`, in its integration tests and its
39
+ * database tooling). The role reads what the repository declares and never asks production.
40
+ */
41
+ pgVersion: string;
42
+ /**
43
+ * Each rule's level, by name. Empty means every rule at its default, `warn` in this version: the
44
+ * role refuses nothing while its adoption runs.
45
+ */
46
+ rules: Record<string, Severity>;
47
+ }
48
+
49
+ type DeepPartial<T> = {
50
+ [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K];
51
+ };
52
+ /** What a module's config file passes. Everything is optional, including the file itself. */
53
+ interface SqlInput {
54
+ /** The module's own directory, normally `import.meta.dirname`. */
55
+ root?: string;
56
+ /** The seam. Replaces whatever it names, and every path it sets lands in `moved`. */
57
+ overrides?: DeepPartial<SqlDefaults>;
58
+ }
59
+ interface ResolvedSqlConfig extends SqlDefaults {
60
+ /** The module's directory, or null when its config file did not say. */
61
+ root: string | null;
62
+ /** Dotted paths the module set through `overrides`, sorted so two runs print the same report. */
63
+ moved: string[];
64
+ }
65
+ /** Resolve a module's declaration against this role's defaults. */
66
+ declare function defineSql(input?: SqlInput): ResolvedSqlConfig;
67
+
68
+ export { type ResolvedSqlConfig, type SqlInput, defineSql };
@@ -0,0 +1,8 @@
1
+ import {
2
+ defineSql
3
+ } from "../../chunk-LU4E4TVD.js";
4
+ import "../../chunk-PXTU5MPW.js";
5
+ export {
6
+ defineSql
7
+ };
8
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  defineStaticAnalysis
3
- } from "../../chunk-7E6YTTAK.js";
3
+ } from "../../chunk-LX7EG6PJ.js";
4
+ import "../../chunk-PXTU5MPW.js";
4
5
  export {
5
6
  defineStaticAnalysis
6
7
  };
@@ -7,9 +7,9 @@ import {
7
7
  } from "../../../chunk-NUOQXAYR.js";
8
8
  import {
9
9
  installWorkspaceSetup
10
- } from "../../../chunk-4YQXLPJ5.js";
10
+ } from "../../../chunk-PMRL4MH6.js";
11
11
  import "../../../chunk-ELZHIN6E.js";
12
- import "../../../chunk-ZNANJEMK.js";
12
+ import "../../../chunk-JT7ZMH44.js";
13
13
 
14
14
  // src/roles/test/setup/jest-parity.ts
15
15
  import { expect, vi } from "vitest";
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  pinWorkspaceTimezone
3
- } from "../../../chunk-4YQXLPJ5.js";
3
+ } from "../../../chunk-PMRL4MH6.js";
4
4
  import "../../../chunk-ELZHIN6E.js";
5
- import "../../../chunk-ZNANJEMK.js";
5
+ import "../../../chunk-JT7ZMH44.js";
6
6
 
7
7
  // src/roles/test/setup/workspace-entry.ts
8
8
  await pinWorkspaceTimezone();
@@ -7,8 +7,8 @@ import {
7
7
  readTestAdoption,
8
8
  resolveVitest,
9
9
  suiteOf
10
- } from "./chunk-2LLRSWG2.js";
11
- import "./chunk-ZNANJEMK.js";
10
+ } from "./chunk-ZASD5YPF.js";
11
+ import "./chunk-JT7ZMH44.js";
12
12
  import "./chunk-O7REVMOC.js";
13
13
  import "./chunk-QXFCZON7.js";
14
14
 
@@ -0,0 +1,391 @@
1
+ # SQL adoption cheat sheet
2
+
3
+ A quick reference for adopting the sentinel `sql` role on a module, for knowing what it checks, and
4
+ for moving a rule's level in `sql.config.mjs`. Why the role exists, and the measurements behind
5
+ its scope, are in [`sql-verification-study.md`](sql-verification-study.md); this page is what you
6
+ need to run it.
7
+
8
+ The role reads what a branch adds or changes:
9
+
10
+ - **the Prisma migrations** (`**/migrations/*/migration.sql`), checked by
11
+ [squawk](https://squawkhq.com) 2.72.0 against PostgreSQL 16.8;
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.
17
+
18
+ **Every finding is a warning until the module decides otherwise.** Nothing fails a run by default,
19
+ so adopting the role, or a sentinel upgrade that brings a new squawk rule, never turns a module red.
20
+ A module that wants a rule to block sets it to `error` (see [Rule levels](#rule-levels)).
21
+
22
+ ## Adopt a module in two steps
23
+
24
+ Run from the **module's own directory**, the one that holds `prisma/migrations` or the raw SQL
25
+ calls. You do not need to install sentinel first: use `npx --yes` for a one-off.
26
+
27
+ ```bash
28
+ # 1. write the module's config + the pinned devDependency
29
+ cd apps/.../<module>
30
+ npx --yes @hublo/sentinel@<version> --init --sql
31
+
32
+ # 2. fetch what step 1 declared
33
+ pnpm install
34
+ ```
35
+
36
+ `--init` writes `sql.config.mjs`, adds the three scripts below and the `sql` nx target to the
37
+ module's `package.json`, and pins `@hublo/sentinel` into its `devDependencies`. It prints:
38
+
39
+ ```
40
+ wrote sql.config.mjs
41
+ wrote package.json
42
+ added sql.config.mjs; added the 3 `sql` scripts; every finding is a warning while the role is being adopted
43
+ ```
44
+
45
+ A module that holds no migration and no raw SQL call is skipped by name: there is nothing for the
46
+ role to read. An existing `sql.config.mjs` is the team's and is never rewritten by a re-init.
47
+
48
+ ## Everyday use
49
+
50
+ ```bash
51
+ pnpm run sql # the summary, in your terminal. Writes nothing
52
+ pnpm run sql:json # sql-report/sql.json, for a machine
53
+ pnpm run sql:html # sql-report/sql.html, for a reader
54
+ ```
55
+
56
+ Or without the scripts:
57
+
58
+ ```bash
59
+ sentinel --run --sql # same as the first script
60
+ sentinel --run --sql --output markdown # sql-report/sql.md, the pull-request recap
61
+ sentinel --inspect --sql --json # every setting and every rule's level, without running
62
+ ```
63
+
64
+ ## What it reads: only what the branch adds or changes
65
+
66
+ The role compares the branch with `origin/main` and reads the migrations and the TypeScript files
67
+ the branch **adds or modifies**. An old migration has already run in production; reporting it again
68
+ on every pull request would bury the one that has not. The console says what was read and what
69
+ was not:
70
+
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.
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.
74
+ ```
75
+
76
+ This is how the role reads, not a setting.
77
+
78
+ ## What is checked, out of the box
79
+
80
+ | Source | Rules | On by default |
81
+ | ----------------------------------------------------------------- | ----- | --------------------------------------------- |
82
+ | squawk 2.72.0, its default rules | 50 | **yes**, at `warn` |
83
+ | squawk 2.72.0, its opt-in rules | 26 | no: one runs once the module gives it a level |
84
+ | sentinel, `unsafe-sql-pasted-value` and `unsafe-sql-raw-fragment` | 2 | **yes**, at `warn` |
85
+
86
+ **52 rules run on every module**, the set squawk itself runs, plus sentinel's two. sentinel turns
87
+ no squawk rule off and turns no opt-in rule on: the choice of what runs by default is squawk's, and
88
+ a module moves it in its own config. `pnpm exec sentinel --inspect --sql --json` lists all 78 rules
89
+ with the level each has in this module.
90
+
91
+ Every rule, what it catches and why it matters, is in [What each squawk rule catches](#what-each-squawk-rule-catches) below.
92
+
93
+ ## Rule levels
94
+
95
+ A rule has one of three levels, the meanings lint already uses:
96
+
97
+ | Level | The rule runs? | A finding fails the run? | In the report |
98
+ | ---------------- | -------------- | ------------------------ | ---------------------------------------------------------------- |
99
+ | `warn` (default) | yes | no | listed |
100
+ | `error` | yes | **yes**, exit code 1 | listed first, marked `error` |
101
+ | `off` | no | no | named in a line of its own, so a reviewer sees it was turned off |
102
+
103
+ ## The config file, `sql.config.mjs`
104
+
105
+ The one file a module writes, the shape of `static-analysis.config.mjs`. `--init` writes it with
106
+ every setting the module can move and the role's value today, generated from the defaults so it
107
+ cannot drift from them. A setting the module leaves out keeps the role's value; a setting it writes
108
+ **replaces** it, including inside a list, and the html report shows it as overridden by this module.
109
+
110
+ | Setting | Default | What it moves |
111
+ | --------------------- | ------------------------------------------ | ------------------------------------------------------ |
112
+ | `migrations.include` | `["**/migrations/*/migration.sql"]` | which files are migrations |
113
+ | `migrations.exclude` | `[]` | migrations never read |
114
+ | `unsafe.includeTests` | `true` | whether calls in test files are checked, by both rules |
115
+ | `unsafe.tests` | test folders and `*.spec`/`*.test`/… files | what counts as a test file |
116
+ | `ignore` | `node_modules`, `dist`, `coverage` | never read, by either check |
117
+ | `pgVersion` | `"16.8"` | the PostgreSQL version squawk checks against |
118
+ | `rules` | `{}`, every rule at its default | a level per rule, by its name |
119
+
120
+ An example that blocks two rules, silences one and turns an opt-in rule on:
121
+
122
+ ```js
123
+ // sql.config.mjs
124
+ import { defineSql } from '@hublo/sentinel/sql'
125
+
126
+ export default defineSql({
127
+ root: import.meta.dirname,
128
+ overrides: {
129
+ rules: {
130
+ 'require-concurrent-index-creation': 'error',
131
+ 'unsafe-sql-pasted-value': 'error',
132
+ 'prefer-robust-stmts': 'off',
133
+ 'ban-drop-index': 'warn',
134
+ },
135
+ },
136
+ })
137
+ ```
138
+
139
+ What the run prints with it:
140
+
141
+ ```
142
+ this module turns off 1 rule(s) in sql.config.mjs, so squawk does not check them: prefer-robust-stmts.
143
+ ✗ 6 finding(s): 2 error(s), from the rule(s) this module sets to "error" in sql.config.mjs, which fail this run, and 4 warning(s):
144
+ require-concurrent-index-creation 1 error
145
+ sentinel's note: Prisma runs a multi-statement file in a transaction, where CONCURRENTLY fails: give the statement its own migration.
146
+ unsafe-sql-pasted-value 1 error
147
+ changing-column-type 1
148
+ ...
149
+ ```
150
+
151
+ `rules` names a rule by **squawk's name for it**, the name the report prints. A name that is not a
152
+ rule is refused in the module's own file, before anything runs, with the closest name:
153
+
154
+ ```
155
+ sql.config.mjs: `rules['prefer-robust-stmt']` is not a rule of squawk 2.72.0 or of sentinel. Did you mean 'prefer-robust-stmts'? The names are listed by `pnpm exec sentinel --inspect --sql --json`.
156
+ ```
157
+
158
+ An older name squawk still accepts, such as `prefer-timestamptz`, is refused too, with the name to
159
+ write: squawk reports the rule under its new name, so a level on the old one would never apply.
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
+
266
+ ## sentinel's notes
267
+
268
+ squawk's advice is written for PostgreSQL in general. Under two rules, sentinel adds a note where
269
+ that advice meets the way Prisma runs a migration, each proven on PostgreSQL 16.8 with Prisma
270
+ 6.19.3. **A note is added beside a finding; it never removes or changes one.**
271
+
272
+ - **`require-concurrent-index-creation` / `-deletion`.** Prisma runs a file of several statements
273
+ inside a transaction, where `CONCURRENTLY` fails (`25001`), nothing is applied and the next deploy
274
+ is refused (`P3009`). The note says to give the statement a migration of its own, alone in its
275
+ file, which applies.
276
+ - **`changing-column-type`, to `varchar` or `text`.** Widening a `varchar`, or changing it to
277
+ `text`, rewrites neither the table nor its index (under 4 ms on 2 million rows), but still waits
278
+ for the table's lock and makes every query behind it wait. The note says to put
279
+ `SET lock_timeout` before the `ALTER`. The statement does not say the type before it, so the
280
+ finding stays for every type change: narrowing a `varchar`, or leaving a `uuid`, does rewrite the
281
+ table.
282
+
283
+ ## The `Unsafe` rule, `unsafe-sql-pasted-value`
284
+
285
+ Prisma's tagged `` $queryRaw`…${value}…` `` sends each `${}` as a parameter. `$queryRawUnsafe` and
286
+ `$executeRawUnsafe` take a plain string: whatever is pasted into it runs as SQL. The rule reports a
287
+ call whose SQL text holds a part sentinel **cannot show** is a constant.
288
+
289
+ It clears what cannot carry text a caller chose:
290
+
291
+ - a string literal, or a template without a value;
292
+ - a template, `+`, ternary, `??`, `||` or `&&` built only of safe parts;
293
+ - arithmetic and comparisons, whose result is a number or a boolean;
294
+ - a `const` of the file, declared once under that name, whose value is safe;
295
+ - a name imported from a relative path, from a file that says `export const NAME = <safe>`;
296
+ - generated placeholders, ``list.map((_, index) => `$${index + 1}`).join(', ')``.
297
+
298
+ It reports everything else, and names the part it could not see:
299
+
300
+ ```
301
+ `table` is pasted into the SQL text of $queryRawUnsafe, and sentinel cannot show it is constant: a quote in it would end the string and run the rest as SQL
302
+ ```
303
+
304
+ That includes a function parameter (the SQL arrives from a caller, unchecked where it is used), a
305
+ `let`, an object property, an enum member, a call, a name declared twice in the file, and an import
306
+ from a package. The rule never guesses: when it cannot see, it reports. The fix it prints is a
307
+ parameter (`$1` in the text, the value after it), or the tagged form; a table or column name cannot
308
+ be a parameter, so take it from a `const` of the file.
309
+
310
+ Measured on the monorepo's 219 calls before the rule was written: the 23 production calls match a
311
+ classification made by hand, one of them a real injection pasting data into a `VALUES` list.
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
+
328
+ ## The `Prisma.raw` rule, `unsafe-sql-raw-fragment`
329
+
330
+ `Prisma.raw(text)` puts its text into a tagged query **as SQL, never as a parameter**: the same
331
+ hazard as the `Unsafe` methods, inside the safe form. Its argument is checked exactly like theirs,
332
+ with the same list of what is cleared, and reported under its own rule, so a module can set the two
333
+ levels apart. `Prisma` is recognised by its import from a `@prisma/` package, under any name
334
+ (`import { Prisma as AgencyPrisma }` included); a `raw` of anything else, `String.raw` among them,
335
+ is not read.
336
+
337
+ ```
338
+ the SQL text of Prisma.raw is `sortOrder`, which sentinel cannot show is a constant: whatever was pasted into it, wherever it was built, runs as SQL
339
+ ```
340
+
341
+ The fix it prints: a value goes into `` Prisma.sql`…` `` as `${value}`, which binds it. A keyword or
342
+ a column name cannot be bound, so write each choice as a literal, which the rule clears:
343
+
344
+ ```ts
345
+ Prisma.sql`ORDER BY "lastName" ${order === 'DESC' ? Prisma.raw('DESC') : Prisma.raw('ASC')}`
346
+ ```
347
+
348
+ Measured on `main` (f12da701121): 97 calls, 20 cleared (all literals or ternaries of literals) and 77
349
+ reported. None of the 77 was found injectable, and none can be proven safe where it is written:
350
+
351
+ | What the call receives | Calls | Why the rule cannot clear it |
352
+ | --------------------------------------------------------------------------------------------------------------- | ----: | ------------------------------------------------------------ |
353
+ | a value validated elsewhere: an enum checked by the HTTP DTO, a key of a column map, a filtered list of numbers | 37 | the proof is a type or a validator, files away from the call |
354
+ | an alias or a column name, a parameter of a SQL helper | 19 | the callers pass literals, in other files |
355
+ | a fragment of SQL built elsewhere, by a query builder or a helper | 21 | the text is made in another function |
356
+
357
+ That is the rule's purpose: on a branch that changes one of these files, the reviewer is told that
358
+ the safety of the text rests on code the call does not show.
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
+
381
+ ## What the role does not read yet
382
+
383
+ Said here so that a clean report is not read as more than it is:
384
+
385
+ - **The SQL text itself** of a raw query is not parsed: a tagged `$queryRaw` with only parameters is
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`).
389
+ - **Files outside a module.** The role runs on a module; a script at the repository's root that
390
+ belongs to no module is read by no role.
391
+ - **What the ORM generates** (`findMany`, `update`, …) is not seen: there is no SQL text to read.