@ultimat3/cli 31.15.0 → 31.17.0
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 +7 -1
- package/package.json +29 -29
- package/src/cache-graph.ts +67 -0
- package/src/cmd-cache-spec.ts +25 -0
- package/src/cmd-cache.ts +187 -0
- package/src/cmd-config-spec.ts +23 -0
- package/src/cmd-config.ts +61 -0
- package/src/cmd-doctor.ts +47 -37
- package/src/cmd-exercise.ts +42 -5
- package/src/cmd-explain-spec.ts +24 -0
- package/src/cmd-explain.ts +201 -0
- package/src/cmd-logs-spec.ts +34 -0
- package/src/cmd-logs.ts +80 -0
- package/src/cmd-planned.ts +15 -29
- package/src/cmd-token-spec.ts +54 -0
- package/src/cmd-token.ts +173 -0
- package/src/cmd-upgrade.ts +19 -2
- package/src/cmd-verify-spec.ts +13 -3
- package/src/cmd-verify.ts +2 -0
- package/src/config-redact.ts +39 -0
- package/src/coverage-floor.ts +2 -2
- package/src/dev-boot-data-dir.ts +69 -0
- package/src/dev-boot.ts +26 -13
- package/src/doctor-env-reserved.ts +111 -0
- package/src/doctor-floor.ts +62 -0
- package/src/doctor-pins.ts +101 -0
- package/src/doctor-probe.ts +21 -1
- package/src/doctor-row-security.ts +119 -4
- package/src/doctor-warnings.ts +55 -0
- package/src/error-codes-doctor.ts +24 -0
- package/src/error-codes-tooling.ts +6 -4
- package/src/error-codes.ts +7 -0
- package/src/errors.ts +8 -2
- package/src/exercise-entry-edit.ts +5 -1
- package/src/exercise-floor-report.ts +138 -0
- package/src/exercise-floor-verdict.ts +98 -0
- package/src/exercise-floor.ts +158 -0
- package/src/exercise-routes.ts +59 -0
- package/src/explain-capture.ts +38 -0
- package/src/generate-exercise.ts +2 -2
- package/src/generate-factories.ts +133 -0
- package/src/generate-files.ts +11 -0
- package/src/generate-kinds.ts +13 -0
- package/src/mcp-db-target.ts +4 -3
- package/src/mcp-errors.ts +14 -0
- package/src/messages-gate.ts +2 -0
- package/src/messages-ops.ts +32 -0
- package/src/messages-upgrade.ts +14 -0
- package/src/messages.ts +5 -0
- package/src/otlp-export.ts +16 -2
- package/src/registry.ts +10 -0
- package/src/role-start.ts +11 -5
- package/src/runtime-services.ts +35 -19
- package/src/serve-boot-phases.ts +30 -0
- package/src/serve-boot-warnings.ts +62 -0
- package/src/serve-boot.ts +30 -11
- package/src/templates/generate-cron-job.ts +90 -0
- package/src/templates/generate-purge.ts +93 -0
- package/src/templates/generate-webhook-receiver.ts +274 -0
- package/src/templates/github/ci.yml.ts +101 -36
- package/src/templates/guard-repo-raw-sql-test.ts +174 -0
- package/src/templates/guard-repo-raw-sql.ts +115 -145
- package/src/templates/guard-unbounded-fanout.ts +170 -0
- package/src/templates/scaffold-claude-commands.ts +3 -2
- package/src/templates/scaffold-docs.ts +3 -2
- package/src/templates/scaffold-guards.ts +3 -0
- package/src/templates/scaffold-verify-floor.ts +4 -0
- package/src/test-dotenv.ts +15 -2
- package/src/upgrade-coverage.ts +109 -0
- package/src/upgrade-document.ts +18 -0
- package/src/upgrade-exercise-floor.ts +53 -0
- package/src/upgrade-gate.ts +84 -29
- package/src/upgrade-guards.ts +159 -0
- package/src/upgrade-report.ts +33 -1
- package/src/verify-checks.ts +3 -1
- package/src/verify-floor.ts +13 -0
- package/src/verify-plan.ts +127 -0
- package/wiki/CI-Parallel-Gate.md +38 -1
- package/wiki/CLI-Reference.md +115 -14
- package/wiki/Caching-And-Invalidation.md +10 -10
- package/wiki/Configuration.md +20 -2
- package/wiki/Known-Gaps.md +1 -1
- package/wiki/MCP-And-AI.md +1 -1
- package/wiki/Testing.md +96 -2
- package/wiki/Troubleshooting.md +3 -2
- package/wiki/Upgrading.md +9 -0
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
// The test `x new` writes beside the `repo-raw-sql` guard: the rule's own cases, run in the app.
|
|
2
|
+
// Split from `guard-repo-raw-sql.ts` at the file ceiling; the code is handed in, never restated.
|
|
3
|
+
|
|
4
|
+
export const repoRawSqlTest = (
|
|
5
|
+
code: string,
|
|
6
|
+
): string => `// The rule, driven directly. Failure case first: a guard whose rule silently stopped matching is
|
|
7
|
+
// a green gate over the convention it was written to enforce.
|
|
8
|
+
|
|
9
|
+
import { expect, unitTest } from '@ultimat3/testing';
|
|
10
|
+
import {
|
|
11
|
+
advisoryLock,
|
|
12
|
+
handleCallFor,
|
|
13
|
+
rawRepoSql,
|
|
14
|
+
rowComparison,
|
|
15
|
+
sqlStatements,
|
|
16
|
+
truncatedOrder,
|
|
17
|
+
} from './repo-raw-sql';
|
|
18
|
+
|
|
19
|
+
const REPO = 'apps/web/app/post/repo.ts';
|
|
20
|
+
const repo = (source: string) => [{ path: REPO, source }];
|
|
21
|
+
|
|
22
|
+
/** An interpolation as SOURCE TEXT, spelled apart so this file holds no placeholder of its own. */
|
|
23
|
+
const hole = (name: string): string => ['$', '{', name, '}'].join('');
|
|
24
|
+
|
|
25
|
+
unitTest('a select the handle can express is refused, naming the call', () => {
|
|
26
|
+
const source = [
|
|
27
|
+
"import { db, sql } from '@ultimat3/db';",
|
|
28
|
+
'export const byId = (id: string) =>',
|
|
29
|
+
\` db().one(sql\\\`select * from posts where id = \${hole('id')}\\\`);\`,
|
|
30
|
+
'',
|
|
31
|
+
].join('\\n');
|
|
32
|
+
const findings = rawRepoSql(repo(source));
|
|
33
|
+
expect(findings).toHaveLength(1);
|
|
34
|
+
expect(findings[0]?.code).toBe('${code}');
|
|
35
|
+
expect(findings[0]?.at).toBe(\`\${REPO}:3\`);
|
|
36
|
+
expect(findings[0]?.fix).toStartWith('db.posts.where({ id }).one() — ');
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
unitTest('a page reads as the chain that pages it', () => {
|
|
40
|
+
const page = 'select * from posts where org_id = ? order by created_at desc limit ?';
|
|
41
|
+
expect(handleCallFor(page)).toBe(
|
|
42
|
+
"db.posts.where({ orgId }).orderBy('createdAt', 'desc').limit(limit).all()",
|
|
43
|
+
);
|
|
44
|
+
const open = 'SELECT * FROM posts WHERE deleted_at IS NULL AND created_at >= ? LIMIT 10;';
|
|
45
|
+
expect(handleCallFor(open)).toBe(
|
|
46
|
+
"db.posts.andWhere('deletedAt', 'is-null').andWhere('createdAt', 'gte', value).limit(10).all()",
|
|
47
|
+
);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
unitTest('a plain column list is the same select, projected with .select', () => {
|
|
51
|
+
expect(handleCallFor('select id, title from posts where org_id = ?')).toBe(
|
|
52
|
+
'db.posts.where({ orgId }).select({ id: true, title: true }).all()',
|
|
53
|
+
);
|
|
54
|
+
expect(handleCallFor('select id as key from posts where org_id = ?')).toBeUndefined();
|
|
55
|
+
expect(handleCallFor('select count(*) from posts where org_id = ?')).toBeUndefined();
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
unitTest('insert, update and delete on one table are the same rule', () => {
|
|
59
|
+
const insert = 'insert into short_links (id, url)\\n values (?, ?)\\n returning *';
|
|
60
|
+
expect(handleCallFor(insert)).toBe('db.shortLinks.insert({ … })');
|
|
61
|
+
expect(handleCallFor('update posts set title = ? where id = ?')).toBe(
|
|
62
|
+
'db.posts.update(id, { … })',
|
|
63
|
+
);
|
|
64
|
+
expect(handleCallFor('update posts set title = ? where org_id = ? and slug = ?')).toBe(
|
|
65
|
+
'db.posts.updateWhere({ … }, { … })',
|
|
66
|
+
);
|
|
67
|
+
expect(handleCallFor('delete from posts where id = ?')).toBe('db.posts.delete(id)');
|
|
68
|
+
expect(handleCallFor('delete from likes where post_id = ? and user_id = ?')).toBe(
|
|
69
|
+
'db.likes.deleteWhere({ … })',
|
|
70
|
+
);
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
// \`deleteWhere\`/\`updateWhere\` take equalities only: a range is the chain's one-statement write,
|
|
74
|
+
// never a filter that would drop the range and write every row of the tenant.
|
|
75
|
+
unitTest('a range in an update or delete names the chain write that keeps it', () => {
|
|
76
|
+
expect(handleCallFor('delete from run_logs where run_id = ? and seq <= ?')).toBe(
|
|
77
|
+
"db.runLogs.where({ runId }).andWhere('seq', 'lte', value).deleteAll()",
|
|
78
|
+
);
|
|
79
|
+
expect(handleCallFor('update posts set title = ? where org_id = ? and created_at < ?')).toBe(
|
|
80
|
+
"db.posts.where({ orgId }).andWhere('createdAt', 'lt', value).updateAll({ … })",
|
|
81
|
+
);
|
|
82
|
+
expect(handleCallFor("delete from run_logs where note = 'a and b' and seq <= ?")).toBe(
|
|
83
|
+
"db.runLogs.where({ note: 'a and b' }).andWhere('seq', 'lte', value).deleteAll()",
|
|
84
|
+
);
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
unitTest('a row locked by its id is the lock call, with or without its tenant', () => {
|
|
88
|
+
const locks = [
|
|
89
|
+
'select * from posts where id = ? for update',
|
|
90
|
+
'select * from posts where id = ? limit 1 for update',
|
|
91
|
+
'SELECT * FROM posts WHERE org_id = ? AND id = ? FOR UPDATE;',
|
|
92
|
+
];
|
|
93
|
+
for (const sql of locks) expect(handleCallFor(sql)).toBe('db.posts.lock(id, fn)');
|
|
94
|
+
const source = \`const row = sql\\\`select * from short_links where id = \${hole('id')} for update\\\`;\`;
|
|
95
|
+
const findings = rawRepoSql(repo(source));
|
|
96
|
+
expect(findings[0]?.fix).toStartWith('db.shortLinks.lock(id, fn) — ');
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
// The legitimate lookalikes — the reason the rule can stay switched on. Each is a statement the
|
|
100
|
+
// handle has no word for, and raw SQL in a repo is the right answer for it.
|
|
101
|
+
unitTest('a statement past what the handle says is silent', () => {
|
|
102
|
+
const silent = [
|
|
103
|
+
'select p.*, m.name from posts p join members m on m.id = p.author_id',
|
|
104
|
+
'select count(*) from posts where org_id = ?',
|
|
105
|
+
'select p.id, p.title from posts p where p.org_id = ?',
|
|
106
|
+
'select * from posts where lower(title) = ?',
|
|
107
|
+
'select * from posts where slug = ? or id = ?',
|
|
108
|
+
'with recent as (select * from posts) select * from recent',
|
|
109
|
+
'update posts set like_count = like_count + 1 where id = ?',
|
|
110
|
+
'insert into likes (post_id, user_id) values (?, ?) on conflict do nothing',
|
|
111
|
+
'select * from jobs where state = ? for update skip locked',
|
|
112
|
+
'select * from posts where id = ? for no key update',
|
|
113
|
+
'select * from posts where org_id = ? for update',
|
|
114
|
+
];
|
|
115
|
+
for (const sql of silent) expect(handleCallFor(sql)).toBeUndefined();
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
unitTest(
|
|
119
|
+
'an order by a millisecond-truncated column is refused in any statement, naming keyset()',
|
|
120
|
+
() => {
|
|
121
|
+
const join =
|
|
122
|
+
"select p.* from posts p join members m on m.id = p.author_id order by date_trunc('milliseconds', p.created_at) desc, p.id desc";
|
|
123
|
+
expect(truncatedOrder(join)).toBe(true);
|
|
124
|
+
expect(
|
|
125
|
+
truncatedOrder(
|
|
126
|
+
"select * from posts where date_trunc('day', created_at) = ? order by created_at",
|
|
127
|
+
),
|
|
128
|
+
).toBe(false);
|
|
129
|
+
expect(
|
|
130
|
+
truncatedOrder("select * from posts -- order by date_trunc('milliseconds', created_at)"),
|
|
131
|
+
).toBe(false);
|
|
132
|
+
const findings = rawRepoSql(repo(\`const q = sql\\\`\${join}\\\`;\`));
|
|
133
|
+
expect(findings[0]?.fix).toStartWith('keyset({ scope, keys: [');
|
|
134
|
+
},
|
|
135
|
+
);
|
|
136
|
+
|
|
137
|
+
unitTest('a hand row comparison is refused; a range on separate columns is not', () => {
|
|
138
|
+
const seek = 'select * from posts where (created_at, id) < (?, ?) limit 20';
|
|
139
|
+
expect(rowComparison(seek)).toBe(true);
|
|
140
|
+
expect(rowComparison('select * from posts where created_at < ? and (id < ?)')).toBe(false);
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
unitTest('an advisory lock is refused; a literal holding either shape is data', () => {
|
|
144
|
+
expect(advisoryLock('select pg_advisory_xact_lock(hashtext(?))')).toBe(true);
|
|
145
|
+
const quoted = "select * from notes where body = 'pg_advisory_xact_lock(1)'";
|
|
146
|
+
expect(advisoryLock(quoted)).toBe(false);
|
|
147
|
+
expect(rowComparison("select * from notes where body = '(a, b) < (c, d)'")).toBe(false);
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
unitTest('a quoted literal splices as its value, never as a binding', () => {
|
|
151
|
+
expect(handleCallFor("select * from posts where status = 'Draft' and org_id = ?")).toBe(
|
|
152
|
+
"db.posts.where({ status: 'Draft', orgId }).all()",
|
|
153
|
+
);
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
unitTest('a statement composed from another fragment is silent', () => {
|
|
157
|
+
const inner = \`sql\\\`and a = \${hole('a')}\\\`\`;
|
|
158
|
+
const source = \`const rows = sql\\\`select * from posts where id = \${hole('id')} \${hole(inner)}\\\`;\`;
|
|
159
|
+
expect(sqlStatements(source)).toHaveLength(1);
|
|
160
|
+
expect(rawRepoSql(repo(source))).toEqual([]);
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
unitTest('a comment, a string and an untagged template are not statements', () => {
|
|
164
|
+
const source = [
|
|
165
|
+
"// Only this file and a query's \`sql\` may touch \`db\`.",
|
|
166
|
+
\`/* sql\\\`delete from posts where id = \${hole('id')}\\\` */\`,
|
|
167
|
+
"const note = 'sql\`select * from posts\`';",
|
|
168
|
+
'const text = \`select * from posts\`;',
|
|
169
|
+
'',
|
|
170
|
+
].join('\\n');
|
|
171
|
+
expect(sqlStatements(source)).toEqual([]);
|
|
172
|
+
expect(rawRepoSql(repo(source))).toEqual([]);
|
|
173
|
+
});
|
|
174
|
+
`;
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
// back, and it reports only what the handle can say: the call it names is the repair.
|
|
5
5
|
|
|
6
6
|
import { guardCode } from './guard';
|
|
7
|
+
import { repoRawSqlTest } from './guard-repo-raw-sql-test';
|
|
7
8
|
import type { GeneratedFile } from './naming';
|
|
8
9
|
|
|
9
10
|
/** Derived from the guard's name, never a literal: an `X_*` literal here is a FRAMEWORK code. */
|
|
@@ -15,11 +16,13 @@ const source =
|
|
|
15
16
|
// \`x verify\` discovers every file in \`guards/\` and runs its \`guard\` inside the \`boundaries\`
|
|
16
17
|
// step — nothing registers this file, so nothing can forget to. Delete it to drop the rule.
|
|
17
18
|
//
|
|
18
|
-
// Only a statement the handle can express is reported: \`select
|
|
19
|
-
//
|
|
19
|
+
// Only a statement the handle can express is reported: \`select *\` or a plain column list (the fix
|
|
20
|
+
// projects it with \`.select({ … })\`), \`insert\`, \`update\` or \`delete\` on ONE table, with plain
|
|
21
|
+
// comparisons, and \`select * … where id = ? for update\`. A join, an aggregate, a CTE, a window, an \`or\`, a function
|
|
20
22
|
// call and a statement composed from another fragment are past what the handle says, and silent.
|
|
21
|
-
//
|
|
22
|
-
// whose repair is \`keyset()\` from \`@ultimat3/db
|
|
23
|
+
// Three more shapes are reported in any statement, join or not: an \`order by date_trunc('milliseconds', …)\`
|
|
24
|
+
// and a hand row comparison \`(a, b) < (?, ?)\`, whose repair is \`keyset()\` from \`@ultimat3/db\`, and a
|
|
25
|
+
// \`pg_advisory_xact_lock(…)\`, whose repair is the handle's \`lockKeys\`. A quoted literal is data, never shape.
|
|
23
26
|
|
|
24
27
|
import type { Finding, Guard } from '@ultimat3/cli';
|
|
25
28
|
|
|
@@ -134,8 +137,11 @@ const WHERE = \`(\${COMPARISON}(?: and \${COMPARISON})*)\`;
|
|
|
134
137
|
const ORDER = \`"?(\${NAME})"?(?: (asc|desc))?(?:, ?"?\${NAME}"?(?: (?:asc|desc))?)*\`;
|
|
135
138
|
const ASSIGNMENT = \`"?\${NAME}"? = \${VALUE}\`;
|
|
136
139
|
|
|
140
|
+
/** \`*\`, or plain column names: an alias, a qualified name or an expression is past the handle. */
|
|
141
|
+
const COLUMNS = \`(\\\\*|"?\${NAME}"?(?:, ?"?\${NAME}"?)*)\`;
|
|
142
|
+
|
|
137
143
|
const SELECT = new RegExp(
|
|
138
|
-
\`^select
|
|
144
|
+
\`^select \${COLUMNS} from \${TABLE}(?: where \${WHERE})?(?: order by \${ORDER})?(?: limit (\${VALUE}))?$\`,
|
|
139
145
|
);
|
|
140
146
|
const INSERT = new RegExp(
|
|
141
147
|
\`^insert into \${TABLE} \\\\([^()]*\\\\) values \\\\(\${VALUE}(?:, ?\${VALUE})*\\\\)(?: returning \\\\*)?$\`,
|
|
@@ -162,18 +168,39 @@ const OPERATORS: Readonly<Record<string, string>> = {
|
|
|
162
168
|
in: 'in',
|
|
163
169
|
};
|
|
164
170
|
|
|
165
|
-
/**
|
|
166
|
-
|
|
171
|
+
/**
|
|
172
|
+
* A quoted literal, and the value it splices as. Masked to \`'<n>'\` before the statement is
|
|
173
|
+
* lowercased and split on spaces, so its case, its spaces and an \`and\` inside it survive.
|
|
174
|
+
*/
|
|
175
|
+
const LITERAL = /'(?:[^']|'')*'/g;
|
|
176
|
+
|
|
177
|
+
const jsString = (sqlLiteral: string): string => {
|
|
178
|
+
const inner = sqlLiteral.slice(1, -1).replaceAll("''", "'");
|
|
179
|
+
return /['\\\\]/.test(inner) ? JSON.stringify(inner) : \`'\${inner}'\`;
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* The predicate as the handle spells it: equalities in one \`where({ … })\`, the rest chained. A
|
|
184
|
+
* literal is its value, never a binding: \`.where({ status })\` names a variable nobody declared.
|
|
185
|
+
*/
|
|
186
|
+
const filterCalls = (where: string | undefined, literals: readonly string[]): string => {
|
|
167
187
|
if (where === undefined) return '';
|
|
188
|
+
const spliced = (value: string): string | undefined => {
|
|
189
|
+
if (value === '?') return undefined;
|
|
190
|
+
const masked = /^'(\\d+)'$/.exec(value);
|
|
191
|
+
return masked === null ? value : jsString(literals[Number(masked[1])] ?? "''");
|
|
192
|
+
};
|
|
168
193
|
const equal: string[] = [];
|
|
169
194
|
const others: string[] = [];
|
|
170
195
|
for (const comparison of where.split(' and ')) {
|
|
171
|
-
const [column = '', operator = '',
|
|
196
|
+
const [column = '', operator = '', value = '?'] = comparison.replaceAll('"', '').split(' ');
|
|
172
197
|
const name = camel(column);
|
|
173
|
-
|
|
198
|
+
const literal = spliced(value);
|
|
199
|
+
if (operator === '=') equal.push(literal === undefined ? name : \`\${name}: \${literal}\`);
|
|
174
200
|
else if (operator !== 'is') {
|
|
175
|
-
|
|
176
|
-
|
|
201
|
+
const op = Object.hasOwn(OPERATORS, operator) ? OPERATORS[operator] : operator;
|
|
202
|
+
others.push(\`.andWhere('\${name}', '\${op}', \${literal ?? 'value'})\`);
|
|
203
|
+
} else others.push(\`.andWhere('\${name}', '\${value === 'not' ? 'is-not-null' : 'is-null'}')\`);
|
|
177
204
|
}
|
|
178
205
|
return \`\${equal.length === 0 ? '' : \`.where({ \${equal.join(', ')} })\`}\${others.join('')}\`;
|
|
179
206
|
};
|
|
@@ -181,12 +208,30 @@ const filterCalls = (where: string | undefined): string => {
|
|
|
181
208
|
/** Whether the predicate is exactly "this id" — the shape \`update(id, …)\` and \`delete(id)\` take. */
|
|
182
209
|
const byIdOnly = (where: string): boolean => /^"?id"? = \\?$/.test(where);
|
|
183
210
|
|
|
211
|
+
/**
|
|
212
|
+
* Whether every comparison is an equality: all \`updateWhere\`/\`deleteWhere\` take. A range is the
|
|
213
|
+
* chain's one-statement \`updateAll\`/\`deleteAll\` — naming the filter would drop the range.
|
|
214
|
+
*/
|
|
215
|
+
const equalitiesOnly = (where: string): boolean =>
|
|
216
|
+
where.split(' and ').every((comparison) => / = /.test(comparison));
|
|
217
|
+
|
|
218
|
+
/** \`id, created_at\` → \`.select({ id: true, createdAt: true })\`; \`*\` is the whole row, no call. */
|
|
219
|
+
const projection = (columns: string): string =>
|
|
220
|
+
columns === '*'
|
|
221
|
+
? ''
|
|
222
|
+
: \`.select({ \${columns
|
|
223
|
+
.split(',')
|
|
224
|
+
.map((column) => \`\${camel(column.trim().replaceAll('"', ''))}: true\`)
|
|
225
|
+
.join(', ')} })\`;
|
|
226
|
+
|
|
184
227
|
/**
|
|
185
228
|
* The handle call that says what \`sql\` says, or \`undefined\` when the handle cannot say it. \`sql\`
|
|
186
229
|
* is the literal's text as written; whitespace, case and a trailing \`;\` are not part of the rule.
|
|
187
230
|
*/
|
|
188
231
|
export function handleCallFor(sql: string): string | undefined {
|
|
232
|
+
const literals: string[] = [];
|
|
189
233
|
const text = sql
|
|
234
|
+
.replaceAll(LITERAL, (literal) => \`'\${literals.push(literal) - 1}'\`)
|
|
190
235
|
.toLowerCase()
|
|
191
236
|
.replaceAll(/\\s+/g, ' ')
|
|
192
237
|
.replaceAll(/\\( /g, '(')
|
|
@@ -200,30 +245,32 @@ export function handleCallFor(sql: string): string | undefined {
|
|
|
200
245
|
}
|
|
201
246
|
const select = SELECT.exec(text);
|
|
202
247
|
if (select !== null) {
|
|
203
|
-
const [, table = '', where, column, direction, limit] = select;
|
|
248
|
+
const [, columns = '*', table = '', where, column, direction, limit] = select;
|
|
204
249
|
const order =
|
|
205
250
|
column === undefined
|
|
206
251
|
? ''
|
|
207
252
|
: \`.orderBy('\${camel(column)}'\${direction === 'desc' ? ", 'desc'" : ''})\`;
|
|
208
253
|
const one = column === undefined && limit === undefined && /(^| )"?id"? = /.test(where ?? '');
|
|
209
254
|
const bound = limit === undefined ? '' : \`.limit(\${limit === '?' ? 'limit' : limit})\`;
|
|
210
|
-
return \`db.\${camel(table)}\${filterCalls(where)}\${order}\${bound}.\${one ? 'one' : 'all'}()\`;
|
|
255
|
+
return \`db.\${camel(table)}\${filterCalls(where, literals)}\${order}\${bound}\${projection(columns)}.\${one ? 'one' : 'all'}()\`;
|
|
211
256
|
}
|
|
212
257
|
const insert = INSERT.exec(text);
|
|
213
258
|
if (insert !== null) return \`db.\${camel(insert[1] ?? '')}.insert({ … })\`;
|
|
214
259
|
const update = UPDATE.exec(text);
|
|
215
260
|
if (update !== null) {
|
|
216
261
|
const [, table = '', where = ''] = update;
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
262
|
+
if (byIdOnly(where)) return \`db.\${camel(table)}.update(id, { … })\`;
|
|
263
|
+
return equalitiesOnly(where)
|
|
264
|
+
? \`db.\${camel(table)}.updateWhere({ … }, { … })\`
|
|
265
|
+
: \`db.\${camel(table)}\${filterCalls(where, literals)}.updateAll({ … })\`;
|
|
220
266
|
}
|
|
221
267
|
const remove = DELETE.exec(text);
|
|
222
268
|
if (remove !== null) {
|
|
223
269
|
const [, table = '', where = ''] = remove;
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
270
|
+
if (byIdOnly(where)) return \`db.\${camel(table)}.delete(id)\`;
|
|
271
|
+
return equalitiesOnly(where)
|
|
272
|
+
? \`db.\${camel(table)}.deleteWhere({ … })\`
|
|
273
|
+
: \`db.\${camel(table)}\${filterCalls(where, literals)}.deleteAll()\`;
|
|
227
274
|
}
|
|
228
275
|
return undefined;
|
|
229
276
|
}
|
|
@@ -251,13 +298,59 @@ const truncatedFinding = (at: string): Finding => ({
|
|
|
251
298
|
at,
|
|
252
299
|
});
|
|
253
300
|
|
|
301
|
+
/** Comments dropped and every quoted literal emptied: the words inside one are data, not shape. */
|
|
302
|
+
const shapeOf = (sql: string): string =>
|
|
303
|
+
sql
|
|
304
|
+
.replaceAll(/--[^\\n]*/g, ' ')
|
|
305
|
+
.replaceAll(LITERAL, "''")
|
|
306
|
+
.toLowerCase()
|
|
307
|
+
.replaceAll(/\\s+/g, ' ');
|
|
308
|
+
|
|
309
|
+
const COLUMN = '"?[a-z_][a-z0-9_.]*"?';
|
|
310
|
+
|
|
311
|
+
/** \`(created_at, id) < (?, ?)\`: the seek of a keyset page, written by hand. */
|
|
312
|
+
const ROW_COMPARISON = new RegExp(\`\\\\( ?\${COLUMN}(?: ?, ?\${COLUMN})+ ?\\\\) ?(?:<=|>=|<|>) ?\\\\(\`);
|
|
313
|
+
|
|
314
|
+
export const rowComparison = (sql: string): boolean => ROW_COMPARISON.test(shapeOf(sql));
|
|
315
|
+
|
|
316
|
+
/** A transaction-scoped advisory lock taken by hand, under a key only this statement knows. */
|
|
317
|
+
export const advisoryLock = (sql: string): boolean =>
|
|
318
|
+
/\\bpg_advisory_xact_lock ?\\(/.test(shapeOf(sql));
|
|
319
|
+
|
|
320
|
+
/** The shapes reported in ANY statement, join or not, each with the call that replaces it. */
|
|
321
|
+
const ANY_STATEMENT: readonly {
|
|
322
|
+
readonly matches: (sql: string) => boolean;
|
|
323
|
+
readonly finding: (at: string) => Finding;
|
|
324
|
+
}[] = [
|
|
325
|
+
{ matches: truncatedOrder, finding: (at) => truncatedFinding(at) },
|
|
326
|
+
{
|
|
327
|
+
matches: rowComparison,
|
|
328
|
+
finding: (at) => ({
|
|
329
|
+
code: CODE,
|
|
330
|
+
cause: \`\${at} pages with a hand row comparison, (a, b) < (?, ?) — the seek keyset() writes with its tie-break, its direction and its cursor codec, each one a detail a hand copy gets wrong when a key column changes\`,
|
|
331
|
+
fix: \`\${KEYSET_CALL} — from @ultimat3/db, its keys the columns of the row comparison at \${at}, then: x verify\`,
|
|
332
|
+
at,
|
|
333
|
+
}),
|
|
334
|
+
},
|
|
335
|
+
{
|
|
336
|
+
matches: advisoryLock,
|
|
337
|
+
finding: (at) => ({
|
|
338
|
+
code: CODE,
|
|
339
|
+
cause: \`\${at} takes pg_advisory_xact_lock by hand — a key hashed where nothing else can see it, and two keys taken in whatever order two callers reach them, which is a deadlock\`,
|
|
340
|
+
fix: \`db.<table>.lockKeys([key], async (tx) => …) — the typed handle of the table the lock guards, sorted keys in one transaction, in place of the sql literal at \${at}, then: x verify\`,
|
|
341
|
+
at,
|
|
342
|
+
}),
|
|
343
|
+
},
|
|
344
|
+
];
|
|
345
|
+
|
|
254
346
|
/** Pure — the caller does the I/O — so the rule is testable without a filesystem. */
|
|
255
347
|
export function rawRepoSql(files: readonly RepoFile[]): readonly Finding[] {
|
|
256
348
|
const findings: Finding[] = [];
|
|
257
349
|
for (const file of files) {
|
|
258
350
|
for (const statement of sqlStatements(file.source)) {
|
|
259
|
-
|
|
260
|
-
|
|
351
|
+
const shape = ANY_STATEMENT.find((one) => one.matches(statement.text));
|
|
352
|
+
if (shape !== undefined) {
|
|
353
|
+
findings.push(shape.finding(\`\${file.path}:\${statement.line}\`));
|
|
261
354
|
continue;
|
|
262
355
|
}
|
|
263
356
|
const call = handleCallFor(statement.text);
|
|
@@ -287,131 +380,8 @@ export const guard: Guard = {
|
|
|
287
380
|
};
|
|
288
381
|
`;
|
|
289
382
|
|
|
290
|
-
const test =
|
|
291
|
-
(): string => `// The rule, driven directly. Failure case first: a guard whose rule silently stopped matching is
|
|
292
|
-
// a green gate over the convention it was written to enforce.
|
|
293
|
-
|
|
294
|
-
import { expect, unitTest } from '@ultimat3/testing';
|
|
295
|
-
import { handleCallFor, rawRepoSql, sqlStatements, truncatedOrder } from './repo-raw-sql';
|
|
296
|
-
|
|
297
|
-
const REPO = 'apps/web/app/post/repo.ts';
|
|
298
|
-
const repo = (source: string) => [{ path: REPO, source }];
|
|
299
|
-
|
|
300
|
-
/** An interpolation as SOURCE TEXT, spelled apart so this file holds no placeholder of its own. */
|
|
301
|
-
const hole = (name: string): string => ['$', '{', name, '}'].join('');
|
|
302
|
-
|
|
303
|
-
unitTest('a select the handle can express is refused, naming the call', () => {
|
|
304
|
-
const source = [
|
|
305
|
-
"import { db, sql } from '@ultimat3/db';",
|
|
306
|
-
'export const byId = (id: string) =>',
|
|
307
|
-
\` db().one(sql\\\`select * from posts where id = \${hole('id')}\\\`);\`,
|
|
308
|
-
'',
|
|
309
|
-
].join('\\n');
|
|
310
|
-
const findings = rawRepoSql(repo(source));
|
|
311
|
-
expect(findings).toHaveLength(1);
|
|
312
|
-
expect(findings[0]?.code).toBe('${CODE}');
|
|
313
|
-
expect(findings[0]?.at).toBe(\`\${REPO}:3\`);
|
|
314
|
-
expect(findings[0]?.fix).toStartWith('db.posts.where({ id }).one() — ');
|
|
315
|
-
});
|
|
316
|
-
|
|
317
|
-
unitTest('a page reads as the chain that pages it', () => {
|
|
318
|
-
const page = 'select * from posts where org_id = ? order by created_at desc limit ?';
|
|
319
|
-
expect(handleCallFor(page)).toBe(
|
|
320
|
-
"db.posts.where({ orgId }).orderBy('createdAt', 'desc').limit(limit).all()",
|
|
321
|
-
);
|
|
322
|
-
const open = 'SELECT * FROM posts WHERE deleted_at IS NULL AND created_at >= ? LIMIT 10;';
|
|
323
|
-
expect(handleCallFor(open)).toBe(
|
|
324
|
-
"db.posts.andWhere('deletedAt', 'is-null').andWhere('createdAt', 'gte', value).limit(10).all()",
|
|
325
|
-
);
|
|
326
|
-
});
|
|
327
|
-
|
|
328
|
-
unitTest('insert, update and delete on one table are the same rule', () => {
|
|
329
|
-
const insert = 'insert into short_links (id, url)\\n values (?, ?)\\n returning *';
|
|
330
|
-
expect(handleCallFor(insert)).toBe('db.shortLinks.insert({ … })');
|
|
331
|
-
expect(handleCallFor('update posts set title = ? where id = ?')).toBe(
|
|
332
|
-
'db.posts.update(id, { … })',
|
|
333
|
-
);
|
|
334
|
-
expect(handleCallFor('update posts set title = ? where org_id = ? and slug = ?')).toBe(
|
|
335
|
-
'db.posts.updateWhere({ … }, { … })',
|
|
336
|
-
);
|
|
337
|
-
expect(handleCallFor('delete from posts where id = ?')).toBe('db.posts.delete(id)');
|
|
338
|
-
expect(handleCallFor('delete from likes where post_id = ? and user_id = ?')).toBe(
|
|
339
|
-
'db.likes.deleteWhere({ … })',
|
|
340
|
-
);
|
|
341
|
-
});
|
|
342
|
-
|
|
343
|
-
unitTest('a row locked by its id is the lock call, with or without its tenant', () => {
|
|
344
|
-
const locks = [
|
|
345
|
-
'select * from posts where id = ? for update',
|
|
346
|
-
'select * from posts where id = ? limit 1 for update',
|
|
347
|
-
'SELECT * FROM posts WHERE org_id = ? AND id = ? FOR UPDATE;',
|
|
348
|
-
];
|
|
349
|
-
for (const sql of locks) expect(handleCallFor(sql)).toBe('db.posts.lock(id, fn)');
|
|
350
|
-
const source = \`const row = sql\\\`select * from short_links where id = \${hole('id')} for update\\\`;\`;
|
|
351
|
-
const findings = rawRepoSql(repo(source));
|
|
352
|
-
expect(findings[0]?.fix).toStartWith('db.shortLinks.lock(id, fn) — ');
|
|
353
|
-
});
|
|
354
|
-
|
|
355
|
-
// The legitimate lookalikes — the reason the rule can stay switched on. Each is a statement the
|
|
356
|
-
// handle has no word for, and raw SQL in a repo is the right answer for it.
|
|
357
|
-
unitTest('a statement past what the handle says is silent', () => {
|
|
358
|
-
const silent = [
|
|
359
|
-
'select p.*, m.name from posts p join members m on m.id = p.author_id',
|
|
360
|
-
'select count(*) from posts where org_id = ?',
|
|
361
|
-
'select id, title from posts where org_id = ?',
|
|
362
|
-
'select * from posts where lower(title) = ?',
|
|
363
|
-
'select * from posts where slug = ? or id = ?',
|
|
364
|
-
'with recent as (select * from posts) select * from recent',
|
|
365
|
-
'update posts set like_count = like_count + 1 where id = ?',
|
|
366
|
-
'insert into likes (post_id, user_id) values (?, ?) on conflict do nothing',
|
|
367
|
-
'select * from jobs where state = ? for update skip locked',
|
|
368
|
-
'select * from posts where id = ? for no key update',
|
|
369
|
-
'select * from posts where org_id = ? for update',
|
|
370
|
-
];
|
|
371
|
-
for (const sql of silent) expect(handleCallFor(sql)).toBeUndefined();
|
|
372
|
-
});
|
|
373
|
-
|
|
374
|
-
unitTest(
|
|
375
|
-
'an order by a millisecond-truncated column is refused in any statement, naming keyset()',
|
|
376
|
-
() => {
|
|
377
|
-
const join =
|
|
378
|
-
"select p.* from posts p join members m on m.id = p.author_id order by date_trunc('milliseconds', p.created_at) desc, p.id desc";
|
|
379
|
-
expect(truncatedOrder(join)).toBe(true);
|
|
380
|
-
expect(
|
|
381
|
-
truncatedOrder(
|
|
382
|
-
"select * from posts where date_trunc('day', created_at) = ? order by created_at",
|
|
383
|
-
),
|
|
384
|
-
).toBe(false);
|
|
385
|
-
expect(
|
|
386
|
-
truncatedOrder("select * from posts -- order by date_trunc('milliseconds', created_at)"),
|
|
387
|
-
).toBe(false);
|
|
388
|
-
const findings = rawRepoSql(repo(\`const q = sql\\\`\${join}\\\`;\`));
|
|
389
|
-
expect(findings[0]?.fix).toStartWith('keyset({ scope, keys: [');
|
|
390
|
-
},
|
|
391
|
-
);
|
|
392
|
-
|
|
393
|
-
unitTest('a statement composed from another fragment is silent', () => {
|
|
394
|
-
const inner = \`sql\\\`and a = \${hole('a')}\\\`\`;
|
|
395
|
-
const source = \`const rows = sql\\\`select * from posts where id = \${hole('id')} \${hole(inner)}\\\`;\`;
|
|
396
|
-
expect(sqlStatements(source)).toHaveLength(1);
|
|
397
|
-
expect(rawRepoSql(repo(source))).toEqual([]);
|
|
398
|
-
});
|
|
399
|
-
|
|
400
|
-
unitTest('a comment, a string and an untagged template are not statements', () => {
|
|
401
|
-
const source = [
|
|
402
|
-
"// Only this file and a query's \`sql\` may touch \`db\`.",
|
|
403
|
-
\`/* sql\\\`delete from posts where id = \${hole('id')}\\\` */\`,
|
|
404
|
-
"const note = 'sql\`select * from posts\`';",
|
|
405
|
-
'const text = \`select * from posts\`;',
|
|
406
|
-
'',
|
|
407
|
-
].join('\\n');
|
|
408
|
-
expect(sqlStatements(source)).toEqual([]);
|
|
409
|
-
expect(rawRepoSql(repo(source))).toEqual([]);
|
|
410
|
-
});
|
|
411
|
-
`;
|
|
412
|
-
|
|
413
383
|
/** `guards/repo-raw-sql.ts` and its test. No index, no registry — the directory is the registration. */
|
|
414
384
|
export const repoRawSqlGuardFiles = (): readonly GeneratedFile[] => [
|
|
415
385
|
{ path: `guards/${NAME}.ts`, contents: source() },
|
|
416
|
-
{ path: `guards/${NAME}.test.ts`, contents:
|
|
386
|
+
{ path: `guards/${NAME}.test.ts`, contents: repoRawSqlTest(CODE) },
|
|
417
387
|
];
|