@fabrika/platform-node 0.9.0-dev.12 → 0.9.0-dev.14
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/package.json +2 -2
- package/src/application-postgres-grants.ts +23 -6
- package/src/migration-classify.ts +595 -32
- package/src/pg-catalog-names.ts +2 -2
- package/src/sql-names.ts +20 -0
- package/src/sql.ts +5 -1
- package/src/sqlite-sql.ts +7 -0
- package/types/src/application-postgres-grants.d.ts +4 -3
- package/types/src/migration-classify.d.ts +50 -4
- package/types/src/sql-names.d.ts +9 -0
- package/types/src/sql.d.ts +2 -2
- package/types/src/sqlite-sql.d.ts +6 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fabrika/platform-node",
|
|
3
|
-
"version": "0.9.0-dev.
|
|
3
|
+
"version": "0.9.0-dev.14",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -38,6 +38,6 @@
|
|
|
38
38
|
"test": "bun test"
|
|
39
39
|
},
|
|
40
40
|
"dependencies": {
|
|
41
|
-
"@fabrika/platform": "0.9.0-dev.
|
|
41
|
+
"@fabrika/platform": "0.9.0-dev.14"
|
|
42
42
|
}
|
|
43
43
|
}
|
|
@@ -46,9 +46,10 @@ export async function normalizeDefaultPrivileges(db: SqlDatabase, schema: string
|
|
|
46
46
|
|
|
47
47
|
/**
|
|
48
48
|
* Resets the schema's privileges to what the runtime role needs: PUBLIC and the runtime role lose everything on the
|
|
49
|
-
* schema and its objects, then the runtime role gets USAGE,
|
|
50
|
-
* routines and USAGE on its types. One transaction, so a live
|
|
51
|
-
* are verified, PUBLIC included, and anything beyond that
|
|
49
|
+
* schema and its objects, then the runtime role gets USAGE, SELECT on every relation, DML on every table but the
|
|
50
|
+
* ledger (never on a view), EXECUTE on the schema's routines and USAGE on its types. One transaction, so a live
|
|
51
|
+
* runtime never sees a gap. Then the effective privileges are verified, PUBLIC included, and anything beyond that
|
|
52
|
+
* stops the deploy.
|
|
52
53
|
*/
|
|
53
54
|
export async function grantRuntimeRole(db: SqlDatabase, schema: string, ledgerTable: string, role: string): Promise<void> {
|
|
54
55
|
try {
|
|
@@ -69,7 +70,17 @@ export async function grantRuntimeRole(db: SqlDatabase, schema: string, ledgerTa
|
|
|
69
70
|
END LOOP;
|
|
70
71
|
END $types$`),
|
|
71
72
|
db.prepare(`GRANT USAGE ON SCHEMA ${schema} TO ${role}`),
|
|
72
|
-
db.prepare(`GRANT SELECT
|
|
73
|
+
db.prepare(`GRANT SELECT ON ALL TABLES IN SCHEMA ${schema} TO ${role}`),
|
|
74
|
+
// DML only on plain and partitioned tables: a view, a materialized view and a foreign table stay read-only.
|
|
75
|
+
db.prepare(`DO $tables$
|
|
76
|
+
DECLARE t pg_catalog.regclass;
|
|
77
|
+
BEGIN
|
|
78
|
+
FOR t IN SELECT c.oid::pg_catalog.regclass FROM pg_catalog.pg_class c
|
|
79
|
+
WHERE c.relnamespace = '${schema}'::pg_catalog.regnamespace AND c.relkind IN ('r', 'p')
|
|
80
|
+
LOOP
|
|
81
|
+
EXECUTE pg_catalog.format('GRANT INSERT, UPDATE, DELETE ON TABLE %s TO ${role}', t);
|
|
82
|
+
END LOOP;
|
|
83
|
+
END $tables$`),
|
|
73
84
|
db.prepare(`REVOKE ALL ON TABLE ${ledgerTable} FROM ${role}`),
|
|
74
85
|
db.prepare(`GRANT EXECUTE ON ALL ROUTINES IN SCHEMA ${schema} TO ${role}`),
|
|
75
86
|
])
|
|
@@ -98,6 +109,12 @@ async function verifyRuntimeRole(db: SqlDatabase, schema: string, ledgerTable: s
|
|
|
98
109
|
WHERE c.relnamespace OPERATOR(pg_catalog.=) ?::pg_catalog.regnamespace AND c.relkind OPERATOR(pg_catalog.=) ANY (ARRAY['r', 'p', 'v', 'm', 'f']::"char"[])
|
|
99
110
|
AND pg_catalog.has_table_privilege(runtime.oid, c.oid, p.privilege)
|
|
100
111
|
UNION ALL
|
|
112
|
+
SELECT pg_catalog.format('%s may %s %s, which is not a table', runtime.rolname, p.privilege, c.oid::pg_catalog.regclass)
|
|
113
|
+
FROM runtime, pg_catalog.unnest(ARRAY['INSERT', 'UPDATE', 'DELETE']) AS p(privilege), pg_catalog.pg_class c
|
|
114
|
+
WHERE c.relnamespace OPERATOR(pg_catalog.=) ?::pg_catalog.regnamespace AND c.relkind OPERATOR(pg_catalog.=) ANY (ARRAY['v', 'm', 'f']::"char"[])
|
|
115
|
+
AND (pg_catalog.has_table_privilege(runtime.oid, c.oid, p.privilege)
|
|
116
|
+
OR (p.privilege OPERATOR(pg_catalog.<>) 'DELETE' AND pg_catalog.has_any_column_privilege(runtime.oid, c.oid, p.privilege)))
|
|
117
|
+
UNION ALL
|
|
101
118
|
SELECT pg_catalog.format('%s may %s the migration ledger', runtime.rolname, p.privilege) FROM runtime, ledger, pg_catalog.unnest(ARRAY['SELECT', 'INSERT', 'UPDATE', 'DELETE']) AS p(privilege)
|
|
102
119
|
WHERE pg_catalog.has_table_privilege(runtime.oid, ledger.oid, p.privilege)
|
|
103
120
|
OR (p.privilege OPERATOR(pg_catalog.<>) 'DELETE' AND pg_catalog.has_any_column_privilege(runtime.oid, ledger.oid, p.privilege))
|
|
@@ -106,12 +123,12 @@ async function verifyRuntimeRole(db: SqlDatabase, schema: string, ledgerTable: s
|
|
|
106
123
|
a.privilege_type, d.defaclobjtype, CASE WHEN a.grantee OPERATOR(pg_catalog.=) 0 THEN 'PUBLIC' ELSE pg_catalog.pg_get_userbyid(a.grantee) END)
|
|
107
124
|
FROM pg_catalog.pg_default_acl d, pg_catalog.aclexplode(d.defaclacl) a
|
|
108
125
|
WHERE d.defaclrole OPERATOR(pg_catalog.=) (SELECT oid FROM pg_catalog.pg_roles WHERE rolname OPERATOR(pg_catalog.=) current_user)
|
|
109
|
-
AND a.grantee OPERATOR(pg_catalog.<>) d.defaclrole`).bind(role, ledgerTable, schema, schema, schema).all<Problem>()
|
|
126
|
+
AND a.grantee OPERATOR(pg_catalog.<>) d.defaclrole`).bind(role, ledgerTable, schema, schema, schema, schema).all<Problem>()
|
|
110
127
|
if (results.length > 0) {
|
|
111
128
|
throw new PostgresMigrationError(
|
|
112
129
|
`${
|
|
113
130
|
results.map((row) => row.problem).join('; ')
|
|
114
|
-
}; the deploy stops, because the runtime role ${role} has DML on its tables and nothing else (ADR-0017)`,
|
|
131
|
+
}; the deploy stops, because the runtime role ${role} reads its relations, has DML on its tables and nothing else (ADR-0017)`,
|
|
115
132
|
)
|
|
116
133
|
}
|
|
117
134
|
}
|
|
@@ -11,13 +11,14 @@ import {
|
|
|
11
11
|
legacyStatusCheckName,
|
|
12
12
|
STORED_FILES_TABLE,
|
|
13
13
|
} from './file-table-ddl'
|
|
14
|
-
import { lexSql, type SqlToken,
|
|
14
|
+
import { lexSql, type SqlToken, type Statement, statementsOf, upperWord } from './migration-sql'
|
|
15
15
|
import { PG_CATALOG_FUNCTIONS, SQL_KEYWORDS } from './pg-catalog-names'
|
|
16
16
|
import {
|
|
17
17
|
afterName,
|
|
18
18
|
closingParenthesis,
|
|
19
19
|
CTE_FORM,
|
|
20
20
|
ddlForeignSchema,
|
|
21
|
+
dmlRelations,
|
|
21
22
|
frameworkReference,
|
|
22
23
|
functionUse,
|
|
23
24
|
isFrameworkName,
|
|
@@ -37,7 +38,9 @@ import {
|
|
|
37
38
|
statementKind,
|
|
38
39
|
unicodeIdentifier,
|
|
39
40
|
wordAtDepthZero,
|
|
41
|
+
writeTargets,
|
|
40
42
|
} from './sql-names'
|
|
43
|
+
import { lexSqlite, SQLITE_PARAMETER_STARTS } from './sqlite-sql'
|
|
41
44
|
|
|
42
45
|
/** A database object a migration declares, named as the catalog check names it (`trigger deals.audit`). */
|
|
43
46
|
export type DatabaseObjectKind = 'function' | 'procedure' | 'trigger' | 'view' | 'materialized view' | 'rule' | 'policy'
|
|
@@ -74,6 +77,45 @@ export type FileAdoption =
|
|
|
74
77
|
| { readonly step: 'adopt'; readonly collection: string; readonly table: string; readonly file: string; readonly line: number }
|
|
75
78
|
| { readonly step: 'release'; readonly collection: string; readonly file: string; readonly line: number }
|
|
76
79
|
|
|
80
|
+
/**
|
|
81
|
+
* A statement that deletes or overwrites stored data in the application's own schema, or that the classifier cannot show
|
|
82
|
+
* keeps every stored value: allowed, and shown to the approver on its own, because no later deploy brings the data back.
|
|
83
|
+
*/
|
|
84
|
+
export interface MigrationDataLoss {
|
|
85
|
+
readonly statement: DataLossStatement
|
|
86
|
+
/**
|
|
87
|
+
* `<table>`; `<table>.<column>` for a dropped or converted column; `<kind> <name>` for a `DROP … CASCADE`; the
|
|
88
|
+
* function's name for a call of database code; the statement's first keywords for `UNPROVEN`.
|
|
89
|
+
*/
|
|
90
|
+
readonly object: string
|
|
91
|
+
/** The columns an `UPDATE` sets, when the classifier could read every one. */
|
|
92
|
+
readonly columns?: readonly string[]
|
|
93
|
+
readonly file: string
|
|
94
|
+
readonly line: number
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* What a statement does to stored data. It deletes: `DROP TABLE`, `DROP COLUMN`, any `DROP … CASCADE` (it also drops
|
|
99
|
+
* the columns of a dropped type or domain), `TRUNCATE` (`TRUNCATE CASCADE` empties every table that references one too)
|
|
100
|
+
* and `DELETE`. It overwrites: `UPDATE` (`UPDATE OR REPLACE` also deletes the rows it conflicts with),
|
|
101
|
+
* `INSERT … ON CONFLICT … DO UPDATE` (`UPSERT`) and `ALTER COLUMN … TYPE`, whose cast may change a value. It may change
|
|
102
|
+
* data: `CALL`, a migration statement that calls a function the migration set declares, whose body may write anything;
|
|
103
|
+
* `UNPROVEN`, any other statement that is not known to keep every stored value (`classifyStatement`).
|
|
104
|
+
*/
|
|
105
|
+
export type DataLossStatement =
|
|
106
|
+
| 'DROP TABLE'
|
|
107
|
+
| 'DROP COLUMN'
|
|
108
|
+
| 'DROP CASCADE'
|
|
109
|
+
| 'TRUNCATE'
|
|
110
|
+
| 'TRUNCATE CASCADE'
|
|
111
|
+
| 'DELETE'
|
|
112
|
+
| 'UPDATE'
|
|
113
|
+
| 'UPDATE OR REPLACE'
|
|
114
|
+
| 'UPSERT'
|
|
115
|
+
| 'ALTER COLUMN TYPE'
|
|
116
|
+
| 'CALL'
|
|
117
|
+
| 'UNPROVEN'
|
|
118
|
+
|
|
77
119
|
/** A file adoption step before the file it lies in is known. */
|
|
78
120
|
type AdoptionStep = WithoutFile<FileAdoption>
|
|
79
121
|
type WithoutFile<T> = T extends unknown ? Omit<T, 'file'> : never
|
|
@@ -102,17 +144,38 @@ export interface MigrationClassification {
|
|
|
102
144
|
readonly deviations: readonly MigrationDeviation[]
|
|
103
145
|
/** The file's adoption steps, in order. */
|
|
104
146
|
readonly adoptions: readonly FileAdoption[]
|
|
147
|
+
/** The file's statements that delete or overwrite stored data, or call database code that may, in order. */
|
|
148
|
+
readonly dataLoss: readonly MigrationDataLoss[]
|
|
105
149
|
/** The objects the file creates. */
|
|
106
150
|
readonly objects: readonly DatabaseObject[]
|
|
107
151
|
readonly changes: readonly ManifestChange[]
|
|
108
152
|
}
|
|
109
153
|
|
|
154
|
+
/** The database an application's migrations run on: Postgres, or SQLite in its Durable Object on Cloudflare (ADR-0065). */
|
|
155
|
+
export type MigrationDialect = 'postgres' | 'sqlite'
|
|
156
|
+
|
|
110
157
|
export interface ClassifyMigrationOptions {
|
|
111
158
|
readonly file: string
|
|
159
|
+
/** Postgres when absent. SQLite only adds the table options SQLite has (`STRICT`, `WITHOUT ROWID`). */
|
|
160
|
+
readonly dialect?: MigrationDialect
|
|
112
161
|
/** The functions and procedures the whole migration set declares in the schema: a body or an expression may call them. */
|
|
113
162
|
readonly functions?: ReadonlySet<string>
|
|
163
|
+
/** The views and materialized views the whole migration set declares in the schema: reading one may run database code. */
|
|
164
|
+
readonly views?: ReadonlySet<string>
|
|
114
165
|
/** The framework's own bundle, which alone may name the framework's `fabrika_*` tables. */
|
|
115
166
|
readonly framework?: boolean
|
|
167
|
+
/** The application's access tables, lowercased (`accessTables` of `@fabrika/db/tables`): no stored code writes one. */
|
|
168
|
+
readonly accessTables?: ReadonlySet<string>
|
|
169
|
+
/** The views the migration set declares over an access table, lowercased (`accessViews`): written like one. */
|
|
170
|
+
readonly accessViews?: ReadonlySet<string>
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** What the whole migration set is classified against besides its schema. */
|
|
174
|
+
export interface ClassifyMigrationsOptions {
|
|
175
|
+
/** Postgres when absent. */
|
|
176
|
+
readonly dialect?: MigrationDialect
|
|
177
|
+
/** The application's access tables, lowercased (`accessTables` of `@fabrika/db/tables`): no stored code writes one. */
|
|
178
|
+
readonly accessTables?: ReadonlySet<string>
|
|
116
179
|
}
|
|
117
180
|
|
|
118
181
|
export interface MigrationFile {
|
|
@@ -209,9 +272,20 @@ const RULE_ACTIONS: ReadonlySet<string> = new Set(['NOTHING', 'SELECT', 'INSERT'
|
|
|
209
272
|
|
|
210
273
|
interface Context {
|
|
211
274
|
readonly schema: string
|
|
275
|
+
readonly dialect: MigrationDialect
|
|
212
276
|
readonly functions: ReadonlySet<string>
|
|
277
|
+
readonly views: ReadonlySet<string>
|
|
213
278
|
readonly framework: boolean
|
|
279
|
+
readonly accessTables: ReadonlySet<string>
|
|
280
|
+
readonly accessViews: ReadonlySet<string>
|
|
214
281
|
doBlocks: number
|
|
282
|
+
/**
|
|
283
|
+
* What this file created: each table a `CREATE TABLE` created (`<table>`), and each column an `ADD COLUMN` added to
|
|
284
|
+
* another table (`<table>.<column>`). Neither holds a value stored before the file ran, until a rename
|
|
285
|
+
* (`renamed`) could give another table or column its name.
|
|
286
|
+
*/
|
|
287
|
+
readonly created: { readonly tables: Set<string>; readonly columns: Set<string> }
|
|
288
|
+
renamed: boolean
|
|
215
289
|
}
|
|
216
290
|
|
|
217
291
|
/** Thrown inside one statement's classification; the statement then contributes only its refusal. */
|
|
@@ -225,7 +299,25 @@ class Refused extends Error {
|
|
|
225
299
|
interface Collected {
|
|
226
300
|
readonly deviations: { readonly kind: DeviationKind; readonly object: string; readonly line: number }[]
|
|
227
301
|
readonly adoptions: AdoptionStep[]
|
|
302
|
+
readonly dataLoss: WithoutFile<MigrationDataLoss>[]
|
|
228
303
|
readonly changes: ManifestChange[]
|
|
304
|
+
/**
|
|
305
|
+
* Whether the statement is not shown to keep every stored value, nor worded by a data line or a closer-review line of
|
|
306
|
+
* its own. True until a path of `classifyStatement` proves otherwise, so a form nobody judged waits for a person.
|
|
307
|
+
*/
|
|
308
|
+
unproven: boolean
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** A table, or a column of one, that this file created and no rename may have swapped since. */
|
|
312
|
+
function isFresh(context: Context, table: string, column?: string): boolean {
|
|
313
|
+
if (context.renamed) return false
|
|
314
|
+
return context.created.tables.has(table) || (column !== undefined && context.created.columns.has(`${table}.${column}`))
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** A rename may bring another table's or column's values under a created name: no later statement of the file is fresh. */
|
|
318
|
+
function voidFresh(context: Context, out: Collected): void {
|
|
319
|
+
context.renamed = true
|
|
320
|
+
out.unproven = true
|
|
229
321
|
}
|
|
230
322
|
|
|
231
323
|
function deviate(out: Collected, kind: DeviationKind, object: string, line: number): void {
|
|
@@ -251,11 +343,39 @@ function refuseForeignDdl(tokens: readonly SqlToken[], context: Context, label:
|
|
|
251
343
|
if (reached !== undefined) throw new Refused(`${label} naming the schema ${reached}`, tokens[0]?.line ?? 1)
|
|
252
344
|
}
|
|
253
345
|
|
|
346
|
+
/**
|
|
347
|
+
* Access tables are written only by the platform: the data layer bounds who writes a row that hands out access. A
|
|
348
|
+
* function body or a rule action runs again after the migration, so neither may write one; a `DO` block runs once.
|
|
349
|
+
*/
|
|
350
|
+
function refuseAccessWrite(tokens: readonly SqlToken[], context: Context, label: string): void {
|
|
351
|
+
for (const target of writeTargets(tokens)) {
|
|
352
|
+
const name = target.name.toLowerCase()
|
|
353
|
+
if (context.accessTables.has(name)) throw new Refused(`a write of the access table ${name} in ${label}`, target.line)
|
|
354
|
+
if (context.accessViews.has(name)) throw new Refused(`a write of the view ${name} over an access table in ${label}`, target.line)
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/** `access table <name>` or `view <name> over an access table` when `name` is one, else `undefined`. */
|
|
359
|
+
function accessRelation(name: string, context: Context): string | undefined {
|
|
360
|
+
const lower = name.toLowerCase()
|
|
361
|
+
if (context.accessTables.has(lower)) return `the access table ${lower}`
|
|
362
|
+
if (context.accessViews.has(lower)) return `the view ${lower} over an access table`
|
|
363
|
+
return undefined
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/** Renaming a relation to an access table's name, or to a view's over one, would bind its code and views to it. */
|
|
367
|
+
function refuseAccessRename(from: string, to: string, context: Context, line: number): void {
|
|
368
|
+
const target = to.toLowerCase()
|
|
369
|
+
const isView = context.accessViews.has(target) && !context.accessViews.has(from.toLowerCase())
|
|
370
|
+
const access = context.accessTables.has(target) || isView ? accessRelation(target, context) : undefined
|
|
371
|
+
if (access !== undefined) throw new Refused(`a rename of ${from.toLowerCase()} to ${access}`, line)
|
|
372
|
+
}
|
|
373
|
+
|
|
254
374
|
/**
|
|
255
375
|
* A query, a condition or a backfill, read as one (`ReadSql`): no schema but the application's, only allowlisted calls
|
|
256
|
-
* and nested statements, and no CTE list it cannot read.
|
|
376
|
+
* and nested statements, and no CTE list it cannot read. Answers the functions of the migration set it calls, each once.
|
|
257
377
|
*/
|
|
258
|
-
function checkQuery(read: ReadSql, context: Context, label: string):
|
|
378
|
+
function checkQuery(read: ReadSql, context: Context, label: string): string[] {
|
|
259
379
|
const { tokens } = read
|
|
260
380
|
if (read.ctes.unread !== undefined) throw new Refused(`a WITH list that cannot be read as ${CTE_FORM}`, read.ctes.unread)
|
|
261
381
|
const nested = nestedStatement(read)
|
|
@@ -267,6 +387,17 @@ function checkQuery(read: ReadSql, context: Context, label: string): void {
|
|
|
267
387
|
if (reached !== undefined) throw new Refused(`${label} reaching the schema ${reached}`, tokens[0]?.line ?? 1)
|
|
268
388
|
const call = refusedCall(references, context.schema, context.functions)
|
|
269
389
|
if (call !== undefined) throw new Refused(`a call of ${call.name}`, call.line)
|
|
390
|
+
const declared = references.filter((reference) =>
|
|
391
|
+
reference.role === 'call' && functionUse(reference, context.schema, context.functions) === 'declared'
|
|
392
|
+
)
|
|
393
|
+
return [...new Set(declared.map((reference) => reference.name))]
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/** A migration statement runs the database code it calls now: each function it calls may change data, once per statement. */
|
|
397
|
+
function recordCalls(out: Collected, functions: readonly string[], line: number): void {
|
|
398
|
+
for (const name of functions) {
|
|
399
|
+
if (!out.dataLoss.some((loss) => loss.statement === 'CALL' && loss.object === name)) out.dataLoss.push({ statement: 'CALL', object: name, line })
|
|
400
|
+
}
|
|
270
401
|
}
|
|
271
402
|
|
|
272
403
|
/** A stored expression's calls: a paved built-in is plain, a reviewed or declared function a deviation, anything else refused. */
|
|
@@ -415,6 +546,7 @@ function createFunction(tokens: readonly SqlToken[], at: number, kind: 'function
|
|
|
415
546
|
const args = tokens.slice(named + 1, close)
|
|
416
547
|
checkQuery(ReadSql.clause(args), context, 'an argument default')
|
|
417
548
|
checkBody(body, context)
|
|
549
|
+
refuseAccessWrite(body, context, `a ${kind} body`)
|
|
418
550
|
deviate(out, kind, name, line)
|
|
419
551
|
out.changes.push({ change: 'create routine', object: { kind, name }, args: `${kind} (${argumentText(args)})`, line })
|
|
420
552
|
}
|
|
@@ -448,6 +580,13 @@ function createTrigger(tokens: readonly SqlToken[], at: number, context: Context
|
|
|
448
580
|
const on = wordAtDepthZero(tokens, 'ON', at + 1)
|
|
449
581
|
if (name === undefined || on === undefined) throw new Refused('CREATE TRIGGER', line)
|
|
450
582
|
const table = ownName(tokens, on + 1, context, 'CREATE TRIGGER')
|
|
583
|
+
// A BEFORE or INSTEAD OF trigger changes or replaces the row an access table stores without any write; an AFTER
|
|
584
|
+
// trigger can only refuse the statement, and stays a deviation.
|
|
585
|
+
const timing = tokens.slice(at + 1, on).map((token) => upperWord(token)).find((word) => word === 'BEFORE' || word === 'INSTEAD')
|
|
586
|
+
const access = accessRelation(table, context)
|
|
587
|
+
if (timing !== undefined && access !== undefined) {
|
|
588
|
+
throw new Refused(`${timing === 'BEFORE' ? 'a BEFORE' : 'an INSTEAD OF'} trigger on ${access}`, line)
|
|
589
|
+
}
|
|
451
590
|
const when = wordAtDepthZero(tokens, 'WHEN', on)
|
|
452
591
|
const whenClose = when === undefined || !isPunct(tokens[when + 1], '(') ? undefined : closingParenthesis(tokens, when + 1)
|
|
453
592
|
const header = when === undefined || whenClose === undefined ? tokens : [...tokens.slice(0, when), ...tokens.slice(whenClose + 1)]
|
|
@@ -506,14 +645,21 @@ function createRule(tokens: readonly SqlToken[], at: number, context: Context, o
|
|
|
506
645
|
const doIndex = to === undefined ? undefined : wordAtDepthZero(tokens, 'DO', to)
|
|
507
646
|
if (name === undefined || to === undefined || doIndex === undefined) throw new Refused('CREATE RULE', line)
|
|
508
647
|
const table = ownName(tokens, to + 1, context, 'CREATE RULE')
|
|
648
|
+
const access = accessRelation(table, context)
|
|
649
|
+
if (access !== undefined) throw new Refused(`a rule on ${access}`, line)
|
|
509
650
|
const where = wordAtDepthZero(tokens, 'WHERE', to)
|
|
510
651
|
const headerEnd = where !== undefined && where < doIndex ? where : doIndex
|
|
511
652
|
refuseForeignDdl(tokens.slice(0, headerEnd), context, 'CREATE RULE')
|
|
512
653
|
let action = skipWords(tokens, skipWords(tokens, doIndex + 1, 'ALSO'), 'INSTEAD')
|
|
513
|
-
if (isPunct(tokens[action], '('))
|
|
654
|
+
if (isPunct(tokens[action], '(')) {
|
|
655
|
+
// The statement splitter cuts `(a; b)` at its `;`, so the actions after the first would be read as statements of their own.
|
|
656
|
+
if (closingParenthesis(tokens, action) === undefined) throw new Refused('a rule with several actions; write one rule per action', line)
|
|
657
|
+
action++
|
|
658
|
+
}
|
|
514
659
|
const first = upperWord(tokens[action])
|
|
515
660
|
if (first === undefined || !RULE_ACTIONS.has(first)) throw new Refused(`${first ?? statementKind(tokens.slice(action))} in a rule action`, line)
|
|
516
661
|
checkQuery(ReadSql.clause(tokens.slice(headerEnd)), context, 'a rule')
|
|
662
|
+
refuseAccessWrite(tokens.slice(action), context, 'a rule action')
|
|
517
663
|
declareObject(out, 'rule', `${table}.${name}`, line)
|
|
518
664
|
}
|
|
519
665
|
|
|
@@ -569,18 +715,41 @@ function classifyElement(element: readonly SqlToken[], table: string, context: C
|
|
|
569
715
|
checkExpression(element.slice(1), `${table}.${column}`, context, out)
|
|
570
716
|
}
|
|
571
717
|
|
|
572
|
-
/**
|
|
718
|
+
/**
|
|
719
|
+
* The tokens of a migration as its database reads it. A comment, a literal or a quoted name ends where that database
|
|
720
|
+
* ends it, so every statement the database runs is one the classifier reads.
|
|
721
|
+
*/
|
|
722
|
+
function lexMigration(sql: string, dialect: MigrationDialect): { readonly tokens: SqlToken[]; readonly unterminated: number | undefined } {
|
|
723
|
+
return dialect === 'sqlite' ? lexSqlite(sql) : lexSql(sql)
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
const migrationStatements = (sql: string, dialect: MigrationDialect): Statement[] => statementsOf(lexMigration(sql, dialect).tokens)
|
|
727
|
+
|
|
728
|
+
/** Whether `options` is SQLite's table-options list: `STRICT` and `WITHOUT ROWID`, separated by commas. */
|
|
729
|
+
function isSqliteTableOptions(options: readonly SqlToken[]): boolean {
|
|
730
|
+
return splitAtCommas(options).every((option) =>
|
|
731
|
+
(option.length === 1 && upperWord(option[0]) === 'STRICT')
|
|
732
|
+
|| (option.length === 2 && upperWord(option[0]) === 'WITHOUT' && upperWord(option[1]) === 'ROWID')
|
|
733
|
+
)
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
/**
|
|
737
|
+
* `CREATE TABLE [IF NOT EXISTS] <name> (<columns and constraints>)` and nothing after it, but SQLite's table options on
|
|
738
|
+
* SQLite; `LIKE` without `INCLUDING`.
|
|
739
|
+
*/
|
|
573
740
|
function createTable(tokens: readonly SqlToken[], context: Context, out: Collected): void {
|
|
574
741
|
const line = tokens[0]?.line ?? 1
|
|
575
742
|
const nameAt = skipWords(tokens, 2, 'IF', 'NOT', 'EXISTS')
|
|
576
743
|
const named = afterName(tokens, nameAt)
|
|
577
744
|
const close = named === undefined || !isPunct(tokens[named], '(') ? undefined : closingParenthesis(tokens, named)
|
|
578
745
|
if (named === undefined || close === undefined) throw new Refused('CREATE TABLE other than a column list', line)
|
|
579
|
-
|
|
746
|
+
const sqliteOptions = context.dialect === 'sqlite' && isSqliteTableOptions(tokens.slice(close + 1))
|
|
747
|
+
if (close !== tokens.length - 1 && !sqliteOptions) {
|
|
580
748
|
const after = tokens[close + 1]
|
|
581
749
|
throw new Refused(`CREATE TABLE … ${upperWord(after) ?? statementKind(tokens.slice(close + 1))}`, line)
|
|
582
750
|
}
|
|
583
751
|
refuseForeignDdl(tokens, context, 'CREATE TABLE')
|
|
752
|
+
refuseConflictClause(tokens, 'CREATE TABLE')
|
|
584
753
|
const table = ownName(tokens, nameAt, context, 'CREATE TABLE')
|
|
585
754
|
for (const element of splitAtCommas(tokens.slice(named + 1, close))) {
|
|
586
755
|
// `LIKE … INCLUDING` copies defaults, constraints and indexes from a table the classifier has not read.
|
|
@@ -589,6 +758,17 @@ function createTable(tokens: readonly SqlToken[], context: Context, out: Collect
|
|
|
589
758
|
}
|
|
590
759
|
classifyElement(element, table, context, out)
|
|
591
760
|
}
|
|
761
|
+
// `IF NOT EXISTS` may find the table already there, with its rows.
|
|
762
|
+
if (nameAt === 2) context.created.tables.add(table)
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
/**
|
|
766
|
+
* SQLite's conflict clause on a constraint (`PRIMARY KEY ON CONFLICT REPLACE`): every later plain `INSERT` that meets a
|
|
767
|
+
* stored row deletes it. Postgres has no such clause, so the form is refused rather than followed into each statement.
|
|
768
|
+
*/
|
|
769
|
+
function refuseConflictClause(tokens: readonly SqlToken[], label: string): void {
|
|
770
|
+
const clause = tokens.findIndex((token, index) => upperWord(token) === 'ON' && upperWord(tokens[index + 1]) === 'CONFLICT')
|
|
771
|
+
if (clause !== -1) throw new Refused(`${label} … ON CONFLICT, a conflict clause on a constraint`, tokens[clause]?.line ?? 1)
|
|
592
772
|
}
|
|
593
773
|
|
|
594
774
|
/** `CREATE [UNIQUE] INDEX [IF NOT EXISTS] [name] ON [ONLY] table [USING method] (…) …`. */
|
|
@@ -610,7 +790,10 @@ function createIndex(tokens: readonly SqlToken[], context: Context, out: Collect
|
|
|
610
790
|
checkExpression(tokens.slice(index), name ?? table, context, out)
|
|
611
791
|
}
|
|
612
792
|
|
|
613
|
-
/**
|
|
793
|
+
/**
|
|
794
|
+
* Why one `ALTER TABLE` clause is outside the allowlist; its expressions are classified as a column's or a table's. A
|
|
795
|
+
* clause not known to keep every stored value, nor worded by a data line, marks the statement `unproven`.
|
|
796
|
+
*/
|
|
614
797
|
function alterClause(clause: readonly SqlToken[], table: string, context: Context, out: Collected): void {
|
|
615
798
|
const line = clause[0]?.line ?? 1
|
|
616
799
|
const [action, next] = [upperWord(clause[0]), upperWord(clause[1])]
|
|
@@ -619,11 +802,29 @@ function alterClause(clause: readonly SqlToken[], table: string, context: Contex
|
|
|
619
802
|
classifyElement(clause.slice(1), table, context, out)
|
|
620
803
|
return
|
|
621
804
|
}
|
|
622
|
-
|
|
805
|
+
const named = skipWords(clause, 1, 'COLUMN')
|
|
806
|
+
const element = clause.slice(skipWords(clause, named, 'IF', 'NOT', 'EXISTS'))
|
|
807
|
+
classifyElement(element, table, context, out)
|
|
808
|
+
// `IF NOT EXISTS` may find the column already there, with its values.
|
|
809
|
+
const column = nameText(element[0])
|
|
810
|
+
if (column !== undefined && upperWord(clause[named]) !== 'IF') context.created.columns.add(`${table}.${column}`)
|
|
811
|
+
return
|
|
812
|
+
}
|
|
813
|
+
if (action === 'DROP') {
|
|
814
|
+
if (next === 'CONSTRAINT') return
|
|
815
|
+
const column = nameText(clause[skipWords(clause, skipWords(clause, 1, 'COLUMN'), 'IF', 'EXISTS')])
|
|
816
|
+
if (column === undefined) out.unproven = true
|
|
817
|
+
else {
|
|
818
|
+
out.dataLoss.push({ statement: 'DROP COLUMN', object: `${table}.${column}`, line })
|
|
819
|
+
context.created.columns.delete(`${table}.${column}`)
|
|
820
|
+
}
|
|
821
|
+
return
|
|
822
|
+
}
|
|
823
|
+
// A validation runs the constraint's check, which may call database code, over every stored row.
|
|
824
|
+
if (action === 'VALIDATE' && next === 'CONSTRAINT') {
|
|
825
|
+
out.unproven = true
|
|
623
826
|
return
|
|
624
827
|
}
|
|
625
|
-
if (action === 'DROP') return
|
|
626
|
-
if (action === 'VALIDATE' && next === 'CONSTRAINT') return
|
|
627
828
|
if (action === 'ALTER' && next !== 'CONSTRAINT') {
|
|
628
829
|
const columnAt = next === 'COLUMN' ? 2 : 1
|
|
629
830
|
const column = nameText(clause[columnAt])
|
|
@@ -637,7 +838,12 @@ function alterClause(clause: readonly SqlToken[], table: string, context: Contex
|
|
|
637
838
|
const rest = clause.slice(actionAt + columnAction.length)
|
|
638
839
|
// A default persists in the schema; `TYPE … USING` runs once over the rows, as a backfill does.
|
|
639
840
|
if (columnAction[1] === 'DEFAULT' && columnAction[0] === 'SET') checkExpression(rest, `${table}.${column}`, context, out)
|
|
640
|
-
else if (columnAction[0] === 'TYPE' || columnAction[1] === 'DATA')
|
|
841
|
+
else if (columnAction[0] === 'TYPE' || columnAction[1] === 'DATA') {
|
|
842
|
+
// Even without `USING`, an implicit cast rewrites every value: a numeric may round, a text may be cut.
|
|
843
|
+
if (!isFresh(context, table, column)) out.dataLoss.push({ statement: 'ALTER COLUMN TYPE', object: `${table}.${column}`, line })
|
|
844
|
+
recordCalls(out, checkQuery(ReadSql.clause(rest), context, 'ALTER TABLE … USING'), line)
|
|
845
|
+
} // A default or a NOT NULL changes no stored value; an identity's sequence and counter are stored state.
|
|
846
|
+
else if (columnAction[1] !== 'DEFAULT' && columnAction[1] !== 'NOT') out.unproven = true
|
|
641
847
|
return
|
|
642
848
|
}
|
|
643
849
|
throw new Refused(`ALTER TABLE … ${action ?? 'an action'}`, line)
|
|
@@ -652,17 +858,25 @@ function alterTable(tokens: readonly SqlToken[], context: Context, out: Collecte
|
|
|
652
858
|
if (named === undefined) throw new Refused('ALTER TABLE', line)
|
|
653
859
|
const table = ownName(tokens, start, context, 'ALTER TABLE')
|
|
654
860
|
const rest = tokens.slice(isPunct(tokens[named], '*') ? named + 1 : named)
|
|
861
|
+
refuseConflictClause(rest, 'ALTER TABLE')
|
|
655
862
|
// RENAME TO, RENAME [COLUMN] a TO b and RENAME CONSTRAINT a TO b each stand alone.
|
|
656
863
|
if (upperWord(rest[0]) === 'RENAME') {
|
|
657
864
|
const to = upperWord(rest[1]) === 'TO' ? nameText(rest[2]) : undefined
|
|
658
|
-
|
|
865
|
+
voidFresh(context, out)
|
|
866
|
+
if (to !== undefined) {
|
|
867
|
+
refuseAccessRename(table, to, context, line)
|
|
868
|
+
out.changes.push({ change: 'rename table', from: table, to })
|
|
869
|
+
}
|
|
659
870
|
return
|
|
660
871
|
}
|
|
872
|
+
out.unproven = false
|
|
661
873
|
for (const clause of splitAtCommas(rest)) alterClause(clause, table, context, out)
|
|
662
874
|
}
|
|
663
875
|
|
|
664
|
-
|
|
876
|
+
/** `ALTER INDEX … RENAME TO` (Postgres renames a table this way too) and `ALTER TYPE … ADD|RENAME VALUE`. */
|
|
877
|
+
function alterIndexOrType(tokens: readonly SqlToken[], kind: string, context: Context, out: Collected): void {
|
|
665
878
|
const line = tokens[0]?.line ?? 1
|
|
879
|
+
let rename = true
|
|
666
880
|
if (kind === 'INDEX') {
|
|
667
881
|
const named = afterName(tokens, skipWords(tokens, 2, 'IF', 'EXISTS'))
|
|
668
882
|
const isRename = named !== undefined && upperWord(tokens[named]) === 'RENAME' && upperWord(tokens[named + 1]) === 'TO'
|
|
@@ -672,8 +886,12 @@ function alterIndexOrType(tokens: readonly SqlToken[], kind: string, context: Co
|
|
|
672
886
|
const action = named === undefined ? undefined : upperWord(tokens[named])
|
|
673
887
|
const isValue = named !== undefined && (action === 'ADD' || action === 'RENAME') && upperWord(tokens[named + 1]) === 'VALUE'
|
|
674
888
|
if (!isValue) throw new Refused('ALTER TYPE other than ADD VALUE or RENAME VALUE', line)
|
|
889
|
+
rename = action === 'RENAME'
|
|
675
890
|
}
|
|
676
891
|
refuseForeignDdl(tokens, context, `ALTER ${kind}`)
|
|
892
|
+
// A renamed value changes what every stored value of it means; an added one changes none.
|
|
893
|
+
if (rename) voidFresh(context, out)
|
|
894
|
+
else out.unproven = false
|
|
677
895
|
}
|
|
678
896
|
|
|
679
897
|
/** The kinds of database code `ALTER … RENAME TO` may rename, and what each names in the manifest. */
|
|
@@ -694,6 +912,7 @@ const RENAMEABLE: Readonly<Record<string, readonly DatabaseObjectKind[]>> = {
|
|
|
694
912
|
*/
|
|
695
913
|
function alterRename(tokens: readonly SqlToken[], context: Context, out: Collected): void {
|
|
696
914
|
const line = tokens[0]?.line ?? 1
|
|
915
|
+
voidFresh(context, out)
|
|
697
916
|
const materialized = upperWord(tokens[1]) === 'MATERIALIZED' && upperWord(tokens[2]) === 'VIEW'
|
|
698
917
|
const kind = materialized ? 'VIEW' : (upperWord(tokens[1]) ?? '')
|
|
699
918
|
const kinds: readonly DatabaseObjectKind[] = materialized ? ['materialized view'] : Object.hasOwn(RENAMEABLE, kind) ? (RENAMEABLE[kind] ?? []) : []
|
|
@@ -726,6 +945,7 @@ function alterRename(tokens: readonly SqlToken[], context: Context, out: Collect
|
|
|
726
945
|
deviate(out, kinds[0] ?? 'trigger', renamed, line)
|
|
727
946
|
return
|
|
728
947
|
}
|
|
948
|
+
if (kind === 'VIEW') refuseAccessRename(name, target, context, line)
|
|
729
949
|
for (const objectKind of kinds) {
|
|
730
950
|
if (objectKind === 'function' || objectKind === 'procedure') refuseShadowing(target, objectKind, line)
|
|
731
951
|
out.changes.push({ change: 'rename', from: { kind: objectKind, name }, to: { kind: objectKind, name: target } })
|
|
@@ -768,7 +988,172 @@ function classifyDrop(tokens: readonly SqlToken[], context: Context, out: Collec
|
|
|
768
988
|
// An extension may live in another schema; CASCADE would drop what other schemas built on it.
|
|
769
989
|
if (kind === 'EXTENSION' && tokens.some((token) => upperWord(token) === 'CASCADE')) throw new Refused('DROP EXTENSION … CASCADE', line)
|
|
770
990
|
refuseForeignDdl(tokens, context, statementKind(tokens))
|
|
771
|
-
|
|
991
|
+
const changes = dropChanges(tokens, kind, context)
|
|
992
|
+
out.changes.push(...changes)
|
|
993
|
+
for (const change of changes) {
|
|
994
|
+
if (change.change === 'drop table') out.dataLoss.push({ statement: 'DROP TABLE', object: change.table, line })
|
|
995
|
+
}
|
|
996
|
+
// CASCADE drops what depends on the object: a column of a dropped type or domain goes with its values.
|
|
997
|
+
if (hasCascade(tokens)) {
|
|
998
|
+
const label = kind === 'MATERIALIZED' ? 'materialized view' : kind.toLowerCase()
|
|
999
|
+
const names = dropNames(tokens, kind)
|
|
1000
|
+
for (const name of names.length === 0 ? [undefined] : names) {
|
|
1001
|
+
out.dataLoss.push({ statement: 'DROP CASCADE', object: name === undefined ? label : `${label} ${name}`, line })
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
out.unproven = out.dataLoss.length === 0 && !DROP_KEEPS_EVERY_VALUE.has(kind)
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
/**
|
|
1008
|
+
* What a `DROP` without `CASCADE` removes while every stored value stays: Postgres refuses it while a column, a default
|
|
1009
|
+
* or a constraint depends on it, and a materialized view's rows are derived from its tables. A sequence keeps a counter
|
|
1010
|
+
* and an extension may own tables, so those are not among them.
|
|
1011
|
+
*/
|
|
1012
|
+
const DROP_KEEPS_EVERY_VALUE: ReadonlySet<string> = new Set([
|
|
1013
|
+
'INDEX',
|
|
1014
|
+
'TYPE',
|
|
1015
|
+
'DOMAIN',
|
|
1016
|
+
'TRIGGER',
|
|
1017
|
+
'FUNCTION',
|
|
1018
|
+
'PROCEDURE',
|
|
1019
|
+
'ROUTINE',
|
|
1020
|
+
'AGGREGATE',
|
|
1021
|
+
'RULE',
|
|
1022
|
+
'VIEW',
|
|
1023
|
+
'MATERIALIZED',
|
|
1024
|
+
'POLICY',
|
|
1025
|
+
'OPERATOR',
|
|
1026
|
+
'STATISTICS',
|
|
1027
|
+
])
|
|
1028
|
+
|
|
1029
|
+
const hasCascade = (tokens: readonly SqlToken[]): boolean => tokens.some((token) => upperWord(token) === 'CASCADE')
|
|
1030
|
+
|
|
1031
|
+
/** The names a `DROP` lists: `<table>.<name>` for a trigger, a rule and a policy. Empty when none reads as a name. */
|
|
1032
|
+
function dropNames(tokens: readonly SqlToken[], kind: string): string[] {
|
|
1033
|
+
const names = skipWords(tokens, kind === 'MATERIALIZED' ? 3 : 2, 'IF', 'EXISTS')
|
|
1034
|
+
if (kind === 'TRIGGER' || kind === 'RULE' || kind === 'POLICY') {
|
|
1035
|
+
const name = nameText(tokens[names])
|
|
1036
|
+
const table = upperWord(tokens[names + 1]) === 'ON' ? objectNameAt(tokens, names + 2) : undefined
|
|
1037
|
+
return name === undefined || table === undefined ? [] : [`${table.name}.${name}`]
|
|
1038
|
+
}
|
|
1039
|
+
return splitAtCommas(tokens.slice(names)).flatMap((part) => {
|
|
1040
|
+
const object = objectNameAt(part, 0)
|
|
1041
|
+
return object === undefined ? [] : [object.name]
|
|
1042
|
+
})
|
|
1043
|
+
}
|
|
1044
|
+
|
|
1045
|
+
/** `TRUNCATE [TABLE] [ONLY] name [*], … [CASCADE]`: each table it empties. */
|
|
1046
|
+
function classifyTruncate(tokens: readonly SqlToken[], context: Context, out: Collected): void {
|
|
1047
|
+
refuseForeignDdl(tokens, context, 'TRUNCATE')
|
|
1048
|
+
const line = tokens[0]?.line ?? 1
|
|
1049
|
+
const statement = hasCascade(tokens) ? 'TRUNCATE CASCADE' : 'TRUNCATE'
|
|
1050
|
+
const names = skipWords(tokens, 1, 'TABLE')
|
|
1051
|
+
for (const part of splitAtCommas(tokens.slice(names))) {
|
|
1052
|
+
const object = objectNameAt(part, skipWords(part, 0, 'ONLY'))
|
|
1053
|
+
if (object !== undefined) out.dataLoss.push({ statement, object: object.name, line })
|
|
1054
|
+
}
|
|
1055
|
+
out.unproven = out.dataLoss.length === 0
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
/**
|
|
1059
|
+
* `UPDATE [OR action] [ONLY] table [*] [[AS] alias] SET …`: the table, SQLite's conflict action, and the columns it sets
|
|
1060
|
+
* when every assignment reads as `column [.field | [subscript]] = …` or `(column, …) = …`.
|
|
1061
|
+
*/
|
|
1062
|
+
function updateTarget(
|
|
1063
|
+
tokens: readonly SqlToken[],
|
|
1064
|
+
): { readonly table: string; readonly or: string | undefined; readonly columns: readonly string[] | undefined } | undefined {
|
|
1065
|
+
const or = upperWord(tokens[1]) === 'OR' ? upperWord(tokens[2]) : undefined
|
|
1066
|
+
const at = skipWords(tokens, or === undefined ? 1 : 3, 'ONLY')
|
|
1067
|
+
const table = objectNameAt(tokens, at)?.name
|
|
1068
|
+
if (table === undefined) return undefined
|
|
1069
|
+
const set = wordAtDepthZero(tokens, 'SET', at)
|
|
1070
|
+
if (set === undefined) return { table, or, columns: undefined }
|
|
1071
|
+
let end = tokens.length
|
|
1072
|
+
for (let index = set + 1, depth = 0; index < tokens.length; index++) {
|
|
1073
|
+
if (isPunct(tokens[index], '(')) depth++
|
|
1074
|
+
else if (isPunct(tokens[index], ')')) depth--
|
|
1075
|
+
const word = depth === 0 ? upperWord(tokens[index]) : undefined
|
|
1076
|
+
// `a IS DISTINCT FROM b` is an expression, not the start of a FROM list.
|
|
1077
|
+
if ((word === 'FROM' && upperWord(tokens[index - 1]) !== 'DISTINCT') || word === 'WHERE' || word === 'RETURNING') {
|
|
1078
|
+
end = index
|
|
1079
|
+
break
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
return { table, or, columns: assignedColumns(tokens.slice(set + 1, end)) }
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
/** The columns of an assignment list, or `undefined` when one does not read as a column name (an empty one included). */
|
|
1086
|
+
function assignedColumns(assignments: readonly SqlToken[]): string[] | undefined {
|
|
1087
|
+
const columns: string[] = []
|
|
1088
|
+
for (const part of splitAtCommas(assignments)) {
|
|
1089
|
+
if (isPunct(part[0], '(')) {
|
|
1090
|
+
const close = closingParenthesis(part, 0)
|
|
1091
|
+
if (close === undefined || !isPunct(part[close + 1], '=')) return undefined
|
|
1092
|
+
for (const name of splitAtCommas(part.slice(1, close))) {
|
|
1093
|
+
const column = name.length === 1 ? nameText(name[0]) : undefined
|
|
1094
|
+
if (column === undefined || column === '') return undefined
|
|
1095
|
+
columns.push(column)
|
|
1096
|
+
}
|
|
1097
|
+
continue
|
|
1098
|
+
}
|
|
1099
|
+
const column = nameText(part[0])
|
|
1100
|
+
const next = part[1]
|
|
1101
|
+
if (column === undefined || column === '' || !(isPunct(next, '=') || isPunct(next, '.') || isPunct(next, '['))) return undefined
|
|
1102
|
+
columns.push(column)
|
|
1103
|
+
}
|
|
1104
|
+
return [...new Set(columns)]
|
|
1105
|
+
}
|
|
1106
|
+
|
|
1107
|
+
/**
|
|
1108
|
+
* An `INSERT`'s conflict clause: `none` without one, `nothing` for `ON CONFLICT … DO NOTHING`, `update` for `ON CONFLICT
|
|
1109
|
+
* … DO UPDATE`, and `unread` for any other. Found as the words `ON CONFLICT` at depth 0, so an alias named `conflict`
|
|
1110
|
+
* is not taken for it.
|
|
1111
|
+
*/
|
|
1112
|
+
function conflictAction(tokens: readonly SqlToken[]): 'none' | 'nothing' | 'update' | 'unread' {
|
|
1113
|
+
let clause: number | undefined
|
|
1114
|
+
for (let index = 0, depth = 0; index < tokens.length && clause === undefined; index++) {
|
|
1115
|
+
if (isPunct(tokens[index], '(')) depth++
|
|
1116
|
+
else if (isPunct(tokens[index], ')')) depth--
|
|
1117
|
+
else if (depth === 0 && upperWord(tokens[index]) === 'ON' && upperWord(tokens[index + 1]) === 'CONFLICT') clause = index
|
|
1118
|
+
}
|
|
1119
|
+
if (clause === undefined) return 'none'
|
|
1120
|
+
const action = wordAtDepthZero(tokens, 'DO', clause)
|
|
1121
|
+
const word = action === undefined ? undefined : upperWord(tokens[action + 1])
|
|
1122
|
+
return word === 'NOTHING' ? 'nothing' : word === 'UPDATE' ? 'update' : 'unread'
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
/**
|
|
1126
|
+
* What a backfill deletes or overwrites, or whether it keeps every stored value: a plain `INSERT` (`ON CONFLICT DO
|
|
1127
|
+
* NOTHING` included) and an `UPDATE` or upsert of what this file created do, unless they read a view the migration set
|
|
1128
|
+
* declares, which may run database code. A call of the set's own functions is recorded by its caller.
|
|
1129
|
+
*/
|
|
1130
|
+
function backfillLoss(tokens: readonly SqlToken[], first: string, context: Context, out: Collected, line: number): void {
|
|
1131
|
+
const readsView = dmlRelations(ReadSql.query(tokens)).some((reference) => context.views.has(reference.name))
|
|
1132
|
+
if (first === 'DELETE') {
|
|
1133
|
+
const object = upperWord(tokens[1]) === 'FROM' ? objectNameAt(tokens, skipWords(tokens, 2, 'ONLY')) : undefined
|
|
1134
|
+
if (object === undefined) return
|
|
1135
|
+
out.dataLoss.push({ statement: 'DELETE', object: object.name, line })
|
|
1136
|
+
} else if (first === 'UPDATE') {
|
|
1137
|
+
const target = updateTarget(tokens)
|
|
1138
|
+
if (target === undefined) return
|
|
1139
|
+
const { table, or, columns } = target
|
|
1140
|
+
const replace = or === 'REPLACE'
|
|
1141
|
+
const fresh = isFresh(context, table) || (columns !== undefined && columns.every((column) => isFresh(context, table, column)))
|
|
1142
|
+
if (!(fresh && !readsView && !replace)) {
|
|
1143
|
+
out.dataLoss.push({ statement: replace ? 'UPDATE OR REPLACE' : 'UPDATE', object: table, ...(columns === undefined ? {} : { columns }), line })
|
|
1144
|
+
}
|
|
1145
|
+
} else {
|
|
1146
|
+
// SQLite's `INSERT OR <action>`: `OR REPLACE` deletes the stored rows it conflicts with.
|
|
1147
|
+
if (upperWord(tokens[1]) === 'OR') return
|
|
1148
|
+
const action = conflictAction(tokens)
|
|
1149
|
+
if (action === 'unread') return
|
|
1150
|
+
const table = objectNameAt(tokens, skipWords(tokens, 1, 'INTO'))?.name
|
|
1151
|
+
if (action === 'update') {
|
|
1152
|
+
if (table === undefined) return
|
|
1153
|
+
if (!isFresh(context, table) || readsView) out.dataLoss.push({ statement: 'UPSERT', object: table, line })
|
|
1154
|
+
} else if (readsView) return
|
|
1155
|
+
}
|
|
1156
|
+
out.unproven = false
|
|
772
1157
|
}
|
|
773
1158
|
|
|
774
1159
|
function classifyCreate(tokens: readonly SqlToken[], context: Context, out: Collected): void {
|
|
@@ -931,6 +1316,43 @@ function adoptionSteps(tokens: readonly SqlToken[], adopted: ReadonlySet<string>
|
|
|
931
1316
|
return [...adopted].sort().map((name) => ({ step: 'adopt', collection: name.slice(FILE_TABLE_PREFIX.length), table, line }))
|
|
932
1317
|
}
|
|
933
1318
|
|
|
1319
|
+
/** The keywords a statement begins with (`INSERT OR REPLACE INTO`, `ALTER INDEX`), at most four, to name it on a data line. */
|
|
1320
|
+
function leadingKeywords(tokens: readonly SqlToken[]): string {
|
|
1321
|
+
const words: string[] = []
|
|
1322
|
+
for (const token of tokens.slice(0, 4)) {
|
|
1323
|
+
const word = upperWord(token)
|
|
1324
|
+
// SQLite's conflict actions (`OR IGNORE`) are no Postgres keywords.
|
|
1325
|
+
if (word === undefined || !(SQL_KEYWORDS.has(word.toLowerCase()) || words.at(-1) === 'OR')) break
|
|
1326
|
+
words.push(word)
|
|
1327
|
+
}
|
|
1328
|
+
return words.length === 0 ? statementKind(tokens) : words.join(' ')
|
|
1329
|
+
}
|
|
1330
|
+
|
|
1331
|
+
/**
|
|
1332
|
+
* The statements a migration may run without a data line, because each keeps every stored value or
|
|
1333
|
+
* already has a closer-review line of its own. Every other statement records one: worded when the classifier knows what
|
|
1334
|
+
* it deletes or overwrites, `UNPROVEN` otherwise, so a form nobody judged waits for a person.
|
|
1335
|
+
*
|
|
1336
|
+
* - `CREATE …`: a new table, index or enum holds nothing yet; database code is a deviation, a closer-review line.
|
|
1337
|
+
* - `DO`: a deviation, a closer-review line.
|
|
1338
|
+
* - `COMMENT ON`: metadata only.
|
|
1339
|
+
* - `ALTER TABLE … ADD [COLUMN]` and `ADD CONSTRAINT`: a new column holds its default; a constraint refuses, never rewrites.
|
|
1340
|
+
* - `ALTER TABLE … DROP CONSTRAINT`: removes a rule, no value.
|
|
1341
|
+
* - `ALTER COLUMN … SET|DROP DEFAULT` and `SET|DROP NOT NULL`: change what a later write gets, or refuse, never a value.
|
|
1342
|
+
* - `ALTER TYPE … ADD VALUE`: no stored value changes meaning.
|
|
1343
|
+
* - `DROP` of an index, a type, a domain, database code, a view or a materialized view without `CASCADE`
|
|
1344
|
+
* (`DROP_KEEPS_EVERY_VALUE`).
|
|
1345
|
+
* - `INSERT … VALUES|SELECT` with no conflict clause or `ON CONFLICT DO NOTHING`, no `OR <action>`, and no read of a view
|
|
1346
|
+
* the migration set declares.
|
|
1347
|
+
* - an `UPDATE` or upsert of a table this file created, an `UPDATE` that sets only columns this file added, and an
|
|
1348
|
+
* `ALTER COLUMN … TYPE` of either, with no rename anywhere before it in the file and no read of a declared view.
|
|
1349
|
+
* - `SELECT fabrika_files_copy_legacy(…)`: inserts the rows an older instance wrote, `ON CONFLICT DO NOTHING`;
|
|
1350
|
+
* `SELECT fabrika_files_release(…)`: its own closer-review adoption line.
|
|
1351
|
+
*
|
|
1352
|
+
* Not among them, so each records a line: every rename (`ALTER TABLE|INDEX … RENAME`, `RENAME COLUMN`, `ALTER TYPE …
|
|
1353
|
+
* RENAME VALUE`, a rename of database code), `VALIDATE CONSTRAINT`, an identity change, `UPDATE OR <action>`, `INSERT
|
|
1354
|
+
* OR <action>`, a `DROP` of a sequence or an extension, and every form not listed.
|
|
1355
|
+
*/
|
|
934
1356
|
function classifyStatement(tokens: readonly SqlToken[], context: Context, out: Collected): void {
|
|
935
1357
|
const line = tokens[0]?.line ?? 1
|
|
936
1358
|
const unicode = unicodeIdentifier(tokens)
|
|
@@ -938,6 +1360,7 @@ function classifyStatement(tokens: readonly SqlToken[], context: Context, out: C
|
|
|
938
1360
|
const call = context.framework ? undefined : fileAdoptionCall(tokens)
|
|
939
1361
|
if (call !== undefined) {
|
|
940
1362
|
if (call.called === FILES_RELEASE_FUNCTION) out.adoptions.push({ step: 'release', collection: call.collection, line: tokens[0]?.line ?? 1 })
|
|
1363
|
+
out.unproven = false
|
|
941
1364
|
return
|
|
942
1365
|
}
|
|
943
1366
|
const adopted = adoptedTableNames(tokens)
|
|
@@ -946,18 +1369,28 @@ function classifyStatement(tokens: readonly SqlToken[], context: Context, out: C
|
|
|
946
1369
|
if (framework !== undefined) throw new Refused(`a reference to the framework's ${framework.name}`, framework.line)
|
|
947
1370
|
const first = upperWord(tokens[0])
|
|
948
1371
|
if (first === 'INSERT' || first === 'UPDATE' || first === 'DELETE') {
|
|
949
|
-
checkQuery(ReadSql.query(tokens), context, first)
|
|
1372
|
+
const calls = checkQuery(ReadSql.query(tokens), context, first)
|
|
950
1373
|
if (!context.framework) out.adoptions.push(...adoptionSteps(tokens, adopted))
|
|
1374
|
+
backfillLoss(tokens, first, context, out, line)
|
|
1375
|
+
recordCalls(out, calls, line)
|
|
1376
|
+
return
|
|
1377
|
+
}
|
|
1378
|
+
if (first === 'COMMENT' && upperWord(tokens[1]) === 'ON') {
|
|
1379
|
+
classifyComment(tokens, context)
|
|
1380
|
+
out.unproven = false
|
|
1381
|
+
return
|
|
1382
|
+
}
|
|
1383
|
+
if (first === 'DO' || first === 'CREATE') {
|
|
1384
|
+
if (first === 'DO') classifyDo(tokens, context, out)
|
|
1385
|
+
else classifyCreate(tokens, context, out)
|
|
1386
|
+
out.unproven = false
|
|
951
1387
|
return
|
|
952
1388
|
}
|
|
953
|
-
if (first === 'COMMENT' && upperWord(tokens[1]) === 'ON') return classifyComment(tokens, context)
|
|
954
|
-
if (first === 'DO') return classifyDo(tokens, context, out)
|
|
955
|
-
if (first === 'CREATE') return classifyCreate(tokens, context, out)
|
|
956
1389
|
if (first === 'DROP') return classifyDrop(tokens, context, out)
|
|
957
|
-
if (first === 'TRUNCATE') return
|
|
1390
|
+
if (first === 'TRUNCATE') return classifyTruncate(tokens, context, out)
|
|
958
1391
|
const second = upperWord(tokens[1])
|
|
959
1392
|
if (first === 'ALTER' && second === 'TABLE') return alterTable(tokens, context, out)
|
|
960
|
-
if (first === 'ALTER' && (second === 'INDEX' || second === 'TYPE')) return alterIndexOrType(tokens, second, context)
|
|
1393
|
+
if (first === 'ALTER' && (second === 'INDEX' || second === 'TYPE')) return alterIndexOrType(tokens, second, context, out)
|
|
961
1394
|
if (first === 'ALTER' && second !== undefined && (Object.hasOwn(RENAMEABLE, second) || second === 'MATERIALIZED')) {
|
|
962
1395
|
return alterRename(tokens, context, out)
|
|
963
1396
|
}
|
|
@@ -972,24 +1405,43 @@ function classifyStatement(tokens: readonly SqlToken[], context: Context, out: C
|
|
|
972
1405
|
* `ALTER … RENAME TO`, `DO`, and a stored expression that calls anything but a paved built-in. Refused: a schema
|
|
973
1406
|
* other than `schema` (`pg_catalog` relations included), a framework `fabrika_*` name, `SECURITY DEFINER`, a function
|
|
974
1407
|
* `SET` clause, a language other than `sql` and `plpgsql`, a body that is not literal or that holds dynamic `EXECUTE`
|
|
975
|
-
* or a statement outside its allowlist, a call outside the function allowlist,
|
|
1408
|
+
* or a statement outside its allowlist, a call outside the function allowlist, a conflict clause on a constraint
|
|
1409
|
+
* (SQLite's `ON CONFLICT REPLACE`, which turns a plain `INSERT` into a delete), and every form not named here:
|
|
976
1410
|
* `COPY`, `GRANT`, `REVOKE`, roles, extensions, event triggers, domains (codegen cannot bind one), `SELECT`, `WITH`
|
|
977
1411
|
* and `MERGE` among them. Transaction control and
|
|
978
|
-
* `SET`/`RESET` are refused for every plan before this runs (`refusedStatement`).
|
|
1412
|
+
* `SET`/`RESET` are refused for every plan before this runs (`refusedStatement`). Apart from all three, a statement not
|
|
1413
|
+
* known to keep every stored value records a data line (`dataLoss`, `classifyStatement`).
|
|
979
1414
|
*/
|
|
980
1415
|
export function classifyMigration(sql: string, schema: string, options: ClassifyMigrationOptions): MigrationClassification {
|
|
981
|
-
const context: Context = {
|
|
1416
|
+
const context: Context = {
|
|
1417
|
+
schema,
|
|
1418
|
+
dialect: options.dialect ?? 'postgres',
|
|
1419
|
+
functions: options.functions ?? new Set(),
|
|
1420
|
+
views: options.views ?? new Set(),
|
|
1421
|
+
framework: options.framework === true,
|
|
1422
|
+
accessTables: options.accessTables ?? new Set(),
|
|
1423
|
+
accessViews: options.accessViews ?? new Set(),
|
|
1424
|
+
doBlocks: 0,
|
|
1425
|
+
created: { tables: new Set(), columns: new Set() },
|
|
1426
|
+
renamed: false,
|
|
1427
|
+
}
|
|
982
1428
|
const refused: MigrationRefusal[] = []
|
|
983
1429
|
const deviations: MigrationDeviation[] = []
|
|
984
1430
|
const adoptions: FileAdoption[] = []
|
|
1431
|
+
const dataLoss: MigrationDataLoss[] = []
|
|
985
1432
|
const changes: ManifestChange[] = []
|
|
986
1433
|
const keys = new Set<string>()
|
|
987
|
-
const { unterminated } =
|
|
1434
|
+
const { tokens: all, unterminated } = lexMigration(sql, context.dialect)
|
|
988
1435
|
if (unterminated !== undefined) {
|
|
989
1436
|
refused.push({ reason: 'a literal, a quoted name or a comment that never closes', file: options.file, line: unterminated })
|
|
990
1437
|
}
|
|
991
|
-
|
|
992
|
-
|
|
1438
|
+
// A migration runs without bindings, and what follows a SQLite parameter may lex otherwise than SQLite reads it.
|
|
1439
|
+
const parameter = context.dialect === 'sqlite' ? all.find((token) => token.kind === 'punct' && SQLITE_PARAMETER_STARTS.has(token.char)) : undefined
|
|
1440
|
+
if (parameter !== undefined) {
|
|
1441
|
+
refused.push({ reason: 'a parameter (?, :, @, $ or #), which a migration cannot bind', file: options.file, line: parameter.line })
|
|
1442
|
+
}
|
|
1443
|
+
for (const { tokens, line } of statementsOf(all)) {
|
|
1444
|
+
const out: Collected = { deviations: [], adoptions: [], dataLoss: [], changes: [], unproven: true }
|
|
993
1445
|
try {
|
|
994
1446
|
classifyStatement(tokens, context, out)
|
|
995
1447
|
} catch (error) {
|
|
@@ -997,6 +1449,7 @@ export function classifyMigration(sql: string, schema: string, options: Classify
|
|
|
997
1449
|
refused.push({ reason: error.reason, file: options.file, line: error.line || line })
|
|
998
1450
|
continue
|
|
999
1451
|
}
|
|
1452
|
+
if (out.unproven) out.dataLoss.push({ statement: 'UNPROVEN', object: leadingKeywords(tokens), line: tokens[0]?.line ?? line })
|
|
1000
1453
|
for (const deviation of out.deviations) {
|
|
1001
1454
|
const key = `${deviation.kind} ${deviation.object}`
|
|
1002
1455
|
if (keys.has(key)) continue
|
|
@@ -1004,16 +1457,70 @@ export function classifyMigration(sql: string, schema: string, options: Classify
|
|
|
1004
1457
|
deviations.push({ ...deviation, file: options.file })
|
|
1005
1458
|
}
|
|
1006
1459
|
adoptions.push(...out.adoptions.map((step) => ({ ...step, file: options.file })))
|
|
1460
|
+
dataLoss.push(...out.dataLoss.map((loss) => ({ ...loss, file: options.file })))
|
|
1007
1461
|
changes.push(...out.changes)
|
|
1008
1462
|
}
|
|
1009
1463
|
const objects = changes.flatMap((change) => (change.change === 'create' || change.change === 'create routine' ? [change.object] : []))
|
|
1010
|
-
return { file: options.file, refused, deviations, adoptions, objects, changes }
|
|
1464
|
+
return { file: options.file, refused, deviations, adoptions, dataLoss, objects, changes }
|
|
1465
|
+
}
|
|
1466
|
+
|
|
1467
|
+
/**
|
|
1468
|
+
* Every view the migration set declares over an access table, lowercased: one whose query names an access table or such
|
|
1469
|
+
* a view, and the names those views are renamed to. A rule action writes through a view with its owner's privileges.
|
|
1470
|
+
* Read across the whole set and in no order, so a view counts whichever file creates or renames it.
|
|
1471
|
+
*/
|
|
1472
|
+
function accessViews(
|
|
1473
|
+
files: readonly MigrationFile[],
|
|
1474
|
+
schema: string,
|
|
1475
|
+
accessTables: ReadonlySet<string>,
|
|
1476
|
+
dialect: MigrationDialect,
|
|
1477
|
+
): ReadonlySet<string> {
|
|
1478
|
+
const views: { readonly name: string; readonly reads: readonly string[] }[] = []
|
|
1479
|
+
const renames: { readonly from: string; readonly to: string }[] = []
|
|
1480
|
+
for (const file of files) {
|
|
1481
|
+
for (const { tokens } of migrationStatements(file.sql, dialect)) {
|
|
1482
|
+
const first = upperWord(tokens[0])
|
|
1483
|
+
if (first === 'CREATE') {
|
|
1484
|
+
const at = skipWords(tokens, skipWords(tokens, skipWords(tokens, skipWords(tokens, 1, 'OR', 'REPLACE'), 'TEMP'), 'TEMPORARY'), 'RECURSIVE')
|
|
1485
|
+
if (upperWord(tokens[at]) !== 'VIEW') continue
|
|
1486
|
+
const named = skipWords(tokens, at + 1, 'IF', 'NOT', 'EXISTS')
|
|
1487
|
+
const object = objectNameAt(tokens, named)
|
|
1488
|
+
const as = wordAtDepthZero(tokens, 'AS', named)
|
|
1489
|
+
if (object === undefined || (object.qualifier !== undefined && object.qualifier !== schema) || as === undefined) continue
|
|
1490
|
+
const reads = dmlRelations(ReadSql.query(viewQuery(tokens.slice(as + 1)))).map((reference) => reference.name.toLowerCase())
|
|
1491
|
+
views.push({ name: object.name.toLowerCase(), reads })
|
|
1492
|
+
} else if (first === 'ALTER' && (upperWord(tokens[1]) === 'VIEW' || upperWord(tokens[1]) === 'TABLE')) {
|
|
1493
|
+
const from = objectNameAt(tokens, skipWords(tokens, 2, 'IF', 'EXISTS'))
|
|
1494
|
+
const rename = tokens.findIndex((token, index) => upperWord(token) === 'RENAME' && upperWord(tokens[index + 1]) === 'TO')
|
|
1495
|
+
const to = rename === -1 ? undefined : nameText(tokens[rename + 2])
|
|
1496
|
+
if (from !== undefined && to !== undefined) renames.push({ from: from.name.toLowerCase(), to: to.toLowerCase() })
|
|
1497
|
+
}
|
|
1498
|
+
}
|
|
1499
|
+
}
|
|
1500
|
+
const reached = new Set(accessTables)
|
|
1501
|
+
const found = new Set<string>()
|
|
1502
|
+
for (let grown = true; grown;) {
|
|
1503
|
+
grown = false
|
|
1504
|
+
for (const view of views) {
|
|
1505
|
+
if (reached.has(view.name) || !view.reads.some((read) => reached.has(read))) continue
|
|
1506
|
+
reached.add(view.name)
|
|
1507
|
+
found.add(view.name)
|
|
1508
|
+
grown = true
|
|
1509
|
+
}
|
|
1510
|
+
for (const rename of renames) {
|
|
1511
|
+
if (!found.has(rename.from) || reached.has(rename.to)) continue
|
|
1512
|
+
reached.add(rename.to)
|
|
1513
|
+
found.add(rename.to)
|
|
1514
|
+
grown = true
|
|
1515
|
+
}
|
|
1516
|
+
}
|
|
1517
|
+
return found
|
|
1011
1518
|
}
|
|
1012
1519
|
|
|
1013
1520
|
/** The names of the functions and procedures a migration creates or renames to in `schema`, read without classifying them. */
|
|
1014
|
-
export function declaredFunctions(sql: string, schema: string): string[] {
|
|
1521
|
+
export function declaredFunctions(sql: string, schema: string, dialect: MigrationDialect = 'postgres'): string[] {
|
|
1015
1522
|
const names: string[] = []
|
|
1016
|
-
for (const { tokens } of
|
|
1523
|
+
for (const { tokens } of migrationStatements(sql, dialect)) {
|
|
1017
1524
|
const first = upperWord(tokens[0])
|
|
1018
1525
|
const at = first === 'CREATE' ? skipWords(tokens, 1, 'OR', 'REPLACE') : 1
|
|
1019
1526
|
const kind = upperWord(tokens[at])
|
|
@@ -1034,6 +1541,44 @@ export function declaredFunctions(sql: string, schema: string): string[] {
|
|
|
1034
1541
|
return names.filter((name) => !shadows(name))
|
|
1035
1542
|
}
|
|
1036
1543
|
|
|
1544
|
+
/**
|
|
1545
|
+
* The views and materialized views the migration set declares in `schema`, and every name one is renamed to (by `ALTER
|
|
1546
|
+
* VIEW` or `ALTER TABLE`), read without classifying them and in no order: a read of any may run database code.
|
|
1547
|
+
*/
|
|
1548
|
+
function declaredViews(files: readonly MigrationFile[], schema: string, dialect: MigrationDialect): ReadonlySet<string> {
|
|
1549
|
+
const views = new Set<string>()
|
|
1550
|
+
const renames: { readonly from: string; readonly to: string }[] = []
|
|
1551
|
+
for (const file of files) {
|
|
1552
|
+
for (const { tokens } of migrationStatements(file.sql, dialect)) {
|
|
1553
|
+
const first = upperWord(tokens[0])
|
|
1554
|
+
if (first === 'CREATE') {
|
|
1555
|
+
const at = skipWords(tokens, skipWords(tokens, skipWords(tokens, 1, 'OR', 'REPLACE'), 'RECURSIVE'), 'MATERIALIZED')
|
|
1556
|
+
if (upperWord(tokens[at]) !== 'VIEW') continue
|
|
1557
|
+
const object = objectNameAt(tokens, skipWords(tokens, at + 1, 'IF', 'NOT', 'EXISTS'))
|
|
1558
|
+
if (object !== undefined && (object.qualifier === undefined || object.qualifier === schema)) views.add(object.name)
|
|
1559
|
+
} else if (first === 'ALTER') {
|
|
1560
|
+
const kindAt = skipWords(tokens, 1, 'MATERIALIZED')
|
|
1561
|
+
const kind = upperWord(tokens[kindAt])
|
|
1562
|
+
if (kind !== 'VIEW' && kind !== 'TABLE') continue
|
|
1563
|
+
const from = objectNameAt(tokens, skipWords(tokens, kindAt + 1, 'IF', 'EXISTS'))
|
|
1564
|
+
const rename = tokens.findIndex((token, index) => upperWord(token) === 'RENAME' && upperWord(tokens[index + 1]) === 'TO')
|
|
1565
|
+
const to = rename === -1 ? undefined : nameText(tokens[rename + 2])
|
|
1566
|
+
if (from !== undefined && to !== undefined) renames.push({ from: from.name, to })
|
|
1567
|
+
}
|
|
1568
|
+
}
|
|
1569
|
+
}
|
|
1570
|
+
for (let grown = true; grown;) {
|
|
1571
|
+
grown = false
|
|
1572
|
+
for (const { from, to } of renames) {
|
|
1573
|
+
if (views.has(from) && !views.has(to)) {
|
|
1574
|
+
views.add(to)
|
|
1575
|
+
grown = true
|
|
1576
|
+
}
|
|
1577
|
+
}
|
|
1578
|
+
}
|
|
1579
|
+
return views
|
|
1580
|
+
}
|
|
1581
|
+
|
|
1037
1582
|
const objectKey = (object: DatabaseObject): string => `${object.kind} ${object.name}`
|
|
1038
1583
|
const ON_TABLE: ReadonlySet<DatabaseObjectKind> = new Set(['trigger', 'rule', 'policy'])
|
|
1039
1584
|
|
|
@@ -1069,9 +1614,27 @@ export function migrationManifest(classifications: readonly MigrationClassificat
|
|
|
1069
1614
|
* Classifies a whole migration set in order. A body or an expression may call a function any file of the set
|
|
1070
1615
|
* declares; the manifest is what the catalog check admits.
|
|
1071
1616
|
*/
|
|
1072
|
-
export function classifyMigrations(
|
|
1073
|
-
|
|
1074
|
-
|
|
1617
|
+
export function classifyMigrations(
|
|
1618
|
+
files: readonly MigrationFile[],
|
|
1619
|
+
schema: string,
|
|
1620
|
+
options: ClassifyMigrationsOptions = {},
|
|
1621
|
+
): MigrationSetClassification {
|
|
1622
|
+
const dialect = options.dialect ?? 'postgres'
|
|
1623
|
+
const functions = new Set(files.flatMap((file) => declaredFunctions(file.sql, schema, dialect)))
|
|
1624
|
+
const views = declaredViews(files, schema, dialect)
|
|
1625
|
+
const access = options.accessTables === undefined
|
|
1626
|
+
? {}
|
|
1627
|
+
: { accessTables: options.accessTables, accessViews: accessViews(files, schema, options.accessTables, dialect) }
|
|
1628
|
+
const classified = files.map((file) =>
|
|
1629
|
+
classifyMigration(file.sql, schema, {
|
|
1630
|
+
file: file.name,
|
|
1631
|
+
functions,
|
|
1632
|
+
views,
|
|
1633
|
+
framework: file.framework === true,
|
|
1634
|
+
dialect,
|
|
1635
|
+
...access,
|
|
1636
|
+
})
|
|
1637
|
+
)
|
|
1075
1638
|
const withOverloads = refuseOverloads(classified)
|
|
1076
1639
|
return { files: withOverloads, objects: migrationManifest(withOverloads) }
|
|
1077
1640
|
}
|
package/src/pg-catalog-names.ts
CHANGED
|
@@ -27,8 +27,8 @@ array_to_string array_to_tsvector array_typanalyze array_unnest_support array_up
|
|
|
27
27
|
arraycontsel arrayoverlap ascii asin asind asinh atan atan2 atan2d atand atanh avg bernoulli big5_to_euc_tw big5_to_mic big5_to_utf8
|
|
28
28
|
binary_upgrade_add_sub_rel_state binary_upgrade_create_empty_extension binary_upgrade_logical_slot_has_caught_up
|
|
29
29
|
binary_upgrade_replorigin_advance binary_upgrade_set_missing_value binary_upgrade_set_next_array_pg_type_oid
|
|
30
|
-
binary_upgrade_set_next_heap_pg_class_oid binary_upgrade_set_next_heap_relfilenode
|
|
31
|
-
binary_upgrade_set_next_index_relfilenode binary_upgrade_set_next_multirange_array_pg_type_oid
|
|
30
|
+
binary_upgrade_set_next_attribute_versions binary_upgrade_set_next_heap_pg_class_oid binary_upgrade_set_next_heap_relfilenode
|
|
31
|
+
binary_upgrade_set_next_index_pg_class_oid binary_upgrade_set_next_index_relfilenode binary_upgrade_set_next_multirange_array_pg_type_oid
|
|
32
32
|
binary_upgrade_set_next_multirange_pg_type_oid binary_upgrade_set_next_pg_authid_oid binary_upgrade_set_next_pg_enum_oid
|
|
33
33
|
binary_upgrade_set_next_pg_tablespace_oid binary_upgrade_set_next_pg_type_oid binary_upgrade_set_next_toast_pg_class_oid
|
|
34
34
|
binary_upgrade_set_next_toast_relfilenode binary_upgrade_set_record_init_privs bit bit_and bit_count bit_in bit_length bit_or bit_out
|
package/src/sql-names.ts
CHANGED
|
@@ -890,6 +890,26 @@ export function parenthesizedTarget(tokens: readonly SqlToken[]): { readonly sta
|
|
|
890
890
|
return undefined
|
|
891
891
|
}
|
|
892
892
|
|
|
893
|
+
/**
|
|
894
|
+
* The relations the data-changing statements among `tokens` write, in order: the name after `INSERT INTO`,
|
|
895
|
+
* `MERGE INTO`, `UPDATE [ONLY]` and `DELETE FROM [ONLY]`. A parenthesized target is `parenthesizedTarget`'s to refuse;
|
|
896
|
+
* `MERGE` is refused before a body or a rule action is read, and is listed so no write form depends on that.
|
|
897
|
+
*/
|
|
898
|
+
export function writeTargets(tokens: readonly SqlToken[]): { readonly name: string; readonly line: number }[] {
|
|
899
|
+
const targets: { readonly name: string; readonly line: number }[] = []
|
|
900
|
+
for (let index = 0; index < tokens.length; index++) {
|
|
901
|
+
const word = upperWord(tokens[index])
|
|
902
|
+
let at: number
|
|
903
|
+
if (word === 'INTO' && (upperWord(tokens[index - 1]) === 'INSERT' || upperWord(tokens[index - 1]) === 'MERGE')) at = index + 1
|
|
904
|
+
else if (word === 'UPDATE') at = skipWords(tokens, index + 1, 'ONLY')
|
|
905
|
+
else if (word === 'DELETE' && upperWord(tokens[index + 1]) === 'FROM') at = skipWords(tokens, index + 2, 'ONLY')
|
|
906
|
+
else continue
|
|
907
|
+
const target = objectNameAt(tokens, at)
|
|
908
|
+
if (target !== undefined) targets.push({ name: target.name, line: tokens[at]?.line ?? 1 })
|
|
909
|
+
}
|
|
910
|
+
return targets
|
|
911
|
+
}
|
|
912
|
+
|
|
893
913
|
/** The relations a DML statement or a query names, in order: what its static text reads or writes. */
|
|
894
914
|
export function dmlRelations(read: ReadSql): NameReference[] {
|
|
895
915
|
return nameReferences(read).filter((reference) => reference.role === 'relation')
|
package/src/sql.ts
CHANGED
|
@@ -18,14 +18,18 @@ export {
|
|
|
18
18
|
classifyMigration,
|
|
19
19
|
type ClassifyMigrationOptions,
|
|
20
20
|
classifyMigrations,
|
|
21
|
+
type ClassifyMigrationsOptions,
|
|
21
22
|
type DatabaseObject,
|
|
22
23
|
type DatabaseObjectKind,
|
|
24
|
+
type DataLossStatement,
|
|
23
25
|
declaredFunctions,
|
|
24
26
|
type DeviationKind,
|
|
25
27
|
type FileAdoption,
|
|
26
28
|
type ManifestChange,
|
|
27
29
|
type MigrationClassification,
|
|
30
|
+
type MigrationDataLoss,
|
|
28
31
|
type MigrationDeviation,
|
|
32
|
+
type MigrationDialect,
|
|
29
33
|
type MigrationFile,
|
|
30
34
|
migrationManifest,
|
|
31
35
|
type MigrationRefusal,
|
|
@@ -62,4 +66,4 @@ export {
|
|
|
62
66
|
statementKind,
|
|
63
67
|
unicodeIdentifier,
|
|
64
68
|
} from './sql-names'
|
|
65
|
-
export { lexSqlite } from './sqlite-sql'
|
|
69
|
+
export { lexSqlite, SQLITE_PARAMETER_STARTS } from './sqlite-sql'
|
package/src/sqlite-sql.ts
CHANGED
|
@@ -3,6 +3,13 @@
|
|
|
3
3
|
|
|
4
4
|
import type { SqlToken } from './migration-sql'
|
|
5
5
|
|
|
6
|
+
/**
|
|
7
|
+
* What starts a parameter SQLite binds by name or by position (`?`, `:x`, `@x`, `$x`, `#x`), each a `punct` token here.
|
|
8
|
+
* SQLite reads `$x(…)` up to a space or `)` as one parameter, a quote included, so the tokens after one may not be what
|
|
9
|
+
* SQLite reads: a reader of SQLite text refuses it at the first.
|
|
10
|
+
*/
|
|
11
|
+
export const SQLITE_PARAMETER_STARTS: ReadonlySet<string> = new Set(['?', ':', '@', '$', '#'])
|
|
12
|
+
|
|
6
13
|
/** SQLite's space (`sqlite3Isspace`), and the UTF-8 byte-order mark, which its tokenizer skips as space anywhere. */
|
|
7
14
|
const isSpace = (char: string): boolean => /[ \t\n\r\f\v]/.test(char)
|
|
8
15
|
/** Every character from U+0080 up but the byte-order mark is part of a name, as SQLite reads any byte from 0x80. */
|
|
@@ -12,8 +12,9 @@ export declare function acquireMigrationLock(db: SqlDatabase, lockKey: number, t
|
|
|
12
12
|
export declare function normalizeDefaultPrivileges(db: SqlDatabase, schema: string): Promise<void>;
|
|
13
13
|
/**
|
|
14
14
|
* Resets the schema's privileges to what the runtime role needs: PUBLIC and the runtime role lose everything on the
|
|
15
|
-
* schema and its objects, then the runtime role gets USAGE,
|
|
16
|
-
* routines and USAGE on its types. One transaction, so a live
|
|
17
|
-
* are verified, PUBLIC included, and anything beyond that
|
|
15
|
+
* schema and its objects, then the runtime role gets USAGE, SELECT on every relation, DML on every table but the
|
|
16
|
+
* ledger (never on a view), EXECUTE on the schema's routines and USAGE on its types. One transaction, so a live
|
|
17
|
+
* runtime never sees a gap. Then the effective privileges are verified, PUBLIC included, and anything beyond that
|
|
18
|
+
* stops the deploy.
|
|
18
19
|
*/
|
|
19
20
|
export declare function grantRuntimeRole(db: SqlDatabase, schema: string, ledgerTable: string, role: string): Promise<void>;
|
|
@@ -35,6 +35,31 @@ export type FileAdoption = {
|
|
|
35
35
|
readonly file: string;
|
|
36
36
|
readonly line: number;
|
|
37
37
|
};
|
|
38
|
+
/**
|
|
39
|
+
* A statement that deletes or overwrites stored data in the application's own schema, or that the classifier cannot show
|
|
40
|
+
* keeps every stored value: allowed, and shown to the approver on its own, because no later deploy brings the data back.
|
|
41
|
+
*/
|
|
42
|
+
export interface MigrationDataLoss {
|
|
43
|
+
readonly statement: DataLossStatement;
|
|
44
|
+
/**
|
|
45
|
+
* `<table>`; `<table>.<column>` for a dropped or converted column; `<kind> <name>` for a `DROP … CASCADE`; the
|
|
46
|
+
* function's name for a call of database code; the statement's first keywords for `UNPROVEN`.
|
|
47
|
+
*/
|
|
48
|
+
readonly object: string;
|
|
49
|
+
/** The columns an `UPDATE` sets, when the classifier could read every one. */
|
|
50
|
+
readonly columns?: readonly string[];
|
|
51
|
+
readonly file: string;
|
|
52
|
+
readonly line: number;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* What a statement does to stored data. It deletes: `DROP TABLE`, `DROP COLUMN`, any `DROP … CASCADE` (it also drops
|
|
56
|
+
* the columns of a dropped type or domain), `TRUNCATE` (`TRUNCATE CASCADE` empties every table that references one too)
|
|
57
|
+
* and `DELETE`. It overwrites: `UPDATE` (`UPDATE OR REPLACE` also deletes the rows it conflicts with),
|
|
58
|
+
* `INSERT … ON CONFLICT … DO UPDATE` (`UPSERT`) and `ALTER COLUMN … TYPE`, whose cast may change a value. It may change
|
|
59
|
+
* data: `CALL`, a migration statement that calls a function the migration set declares, whose body may write anything;
|
|
60
|
+
* `UNPROVEN`, any other statement that is not known to keep every stored value (`classifyStatement`).
|
|
61
|
+
*/
|
|
62
|
+
export type DataLossStatement = 'DROP TABLE' | 'DROP COLUMN' | 'DROP CASCADE' | 'TRUNCATE' | 'TRUNCATE CASCADE' | 'DELETE' | 'UPDATE' | 'UPDATE OR REPLACE' | 'UPSERT' | 'ALTER COLUMN TYPE' | 'CALL' | 'UNPROVEN';
|
|
38
63
|
export interface MigrationRefusal {
|
|
39
64
|
/** What is refused, phrased to precede "is not allowed". */
|
|
40
65
|
readonly reason: string;
|
|
@@ -74,16 +99,35 @@ export interface MigrationClassification {
|
|
|
74
99
|
readonly deviations: readonly MigrationDeviation[];
|
|
75
100
|
/** The file's adoption steps, in order. */
|
|
76
101
|
readonly adoptions: readonly FileAdoption[];
|
|
102
|
+
/** The file's statements that delete or overwrite stored data, or call database code that may, in order. */
|
|
103
|
+
readonly dataLoss: readonly MigrationDataLoss[];
|
|
77
104
|
/** The objects the file creates. */
|
|
78
105
|
readonly objects: readonly DatabaseObject[];
|
|
79
106
|
readonly changes: readonly ManifestChange[];
|
|
80
107
|
}
|
|
108
|
+
/** The database an application's migrations run on: Postgres, or SQLite in its Durable Object on Cloudflare (ADR-0065). */
|
|
109
|
+
export type MigrationDialect = 'postgres' | 'sqlite';
|
|
81
110
|
export interface ClassifyMigrationOptions {
|
|
82
111
|
readonly file: string;
|
|
112
|
+
/** Postgres when absent. SQLite only adds the table options SQLite has (`STRICT`, `WITHOUT ROWID`). */
|
|
113
|
+
readonly dialect?: MigrationDialect;
|
|
83
114
|
/** The functions and procedures the whole migration set declares in the schema: a body or an expression may call them. */
|
|
84
115
|
readonly functions?: ReadonlySet<string>;
|
|
116
|
+
/** The views and materialized views the whole migration set declares in the schema: reading one may run database code. */
|
|
117
|
+
readonly views?: ReadonlySet<string>;
|
|
85
118
|
/** The framework's own bundle, which alone may name the framework's `fabrika_*` tables. */
|
|
86
119
|
readonly framework?: boolean;
|
|
120
|
+
/** The application's access tables, lowercased (`accessTables` of `@fabrika/db/tables`): no stored code writes one. */
|
|
121
|
+
readonly accessTables?: ReadonlySet<string>;
|
|
122
|
+
/** The views the migration set declares over an access table, lowercased (`accessViews`): written like one. */
|
|
123
|
+
readonly accessViews?: ReadonlySet<string>;
|
|
124
|
+
}
|
|
125
|
+
/** What the whole migration set is classified against besides its schema. */
|
|
126
|
+
export interface ClassifyMigrationsOptions {
|
|
127
|
+
/** Postgres when absent. */
|
|
128
|
+
readonly dialect?: MigrationDialect;
|
|
129
|
+
/** The application's access tables, lowercased (`accessTables` of `@fabrika/db/tables`): no stored code writes one. */
|
|
130
|
+
readonly accessTables?: ReadonlySet<string>;
|
|
87
131
|
}
|
|
88
132
|
export interface MigrationFile {
|
|
89
133
|
readonly name: string;
|
|
@@ -103,14 +147,16 @@ export interface MigrationSetClassification {
|
|
|
103
147
|
* `ALTER … RENAME TO`, `DO`, and a stored expression that calls anything but a paved built-in. Refused: a schema
|
|
104
148
|
* other than `schema` (`pg_catalog` relations included), a framework `fabrika_*` name, `SECURITY DEFINER`, a function
|
|
105
149
|
* `SET` clause, a language other than `sql` and `plpgsql`, a body that is not literal or that holds dynamic `EXECUTE`
|
|
106
|
-
* or a statement outside its allowlist, a call outside the function allowlist,
|
|
150
|
+
* or a statement outside its allowlist, a call outside the function allowlist, a conflict clause on a constraint
|
|
151
|
+
* (SQLite's `ON CONFLICT REPLACE`, which turns a plain `INSERT` into a delete), and every form not named here:
|
|
107
152
|
* `COPY`, `GRANT`, `REVOKE`, roles, extensions, event triggers, domains (codegen cannot bind one), `SELECT`, `WITH`
|
|
108
153
|
* and `MERGE` among them. Transaction control and
|
|
109
|
-
* `SET`/`RESET` are refused for every plan before this runs (`refusedStatement`).
|
|
154
|
+
* `SET`/`RESET` are refused for every plan before this runs (`refusedStatement`). Apart from all three, a statement not
|
|
155
|
+
* known to keep every stored value records a data line (`dataLoss`, `classifyStatement`).
|
|
110
156
|
*/
|
|
111
157
|
export declare function classifyMigration(sql: string, schema: string, options: ClassifyMigrationOptions): MigrationClassification;
|
|
112
158
|
/** The names of the functions and procedures a migration creates or renames to in `schema`, read without classifying them. */
|
|
113
|
-
export declare function declaredFunctions(sql: string, schema: string): string[];
|
|
159
|
+
export declare function declaredFunctions(sql: string, schema: string, dialect?: MigrationDialect): string[];
|
|
114
160
|
/**
|
|
115
161
|
* The manifest of a migration set, folded in file order: a create adds an object (a replace keeps it), a drop removes
|
|
116
162
|
* it, dropping a table removes its triggers, rules and policies, and renaming a table renames them. A `CASCADE` may
|
|
@@ -121,4 +167,4 @@ export declare function migrationManifest(classifications: readonly MigrationCla
|
|
|
121
167
|
* Classifies a whole migration set in order. A body or an expression may call a function any file of the set
|
|
122
168
|
* declares; the manifest is what the catalog check admits.
|
|
123
169
|
*/
|
|
124
|
-
export declare function classifyMigrations(files: readonly MigrationFile[], schema: string): MigrationSetClassification;
|
|
170
|
+
export declare function classifyMigrations(files: readonly MigrationFile[], schema: string, options?: ClassifyMigrationsOptions): MigrationSetClassification;
|
package/types/src/sql-names.d.ts
CHANGED
|
@@ -113,6 +113,15 @@ export declare function parenthesizedTarget(tokens: readonly SqlToken[]): {
|
|
|
113
113
|
readonly statement: string;
|
|
114
114
|
readonly line: number;
|
|
115
115
|
} | undefined;
|
|
116
|
+
/**
|
|
117
|
+
* The relations the data-changing statements among `tokens` write, in order: the name after `INSERT INTO`,
|
|
118
|
+
* `MERGE INTO`, `UPDATE [ONLY]` and `DELETE FROM [ONLY]`. A parenthesized target is `parenthesizedTarget`'s to refuse;
|
|
119
|
+
* `MERGE` is refused before a body or a rule action is read, and is listed so no write form depends on that.
|
|
120
|
+
*/
|
|
121
|
+
export declare function writeTargets(tokens: readonly SqlToken[]): {
|
|
122
|
+
readonly name: string;
|
|
123
|
+
readonly line: number;
|
|
124
|
+
}[];
|
|
116
125
|
/** The relations a DML statement or a query names, in order: what its static text reads or writes. */
|
|
117
126
|
export declare function dmlRelations(read: ReadSql): NameReference[];
|
|
118
127
|
/**
|
package/types/src/sql.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export { applicationDatabaseSchema } from './application-schema';
|
|
2
2
|
export { FILE_SCAN_COLUMNS, FILE_STATUSES, FILE_TABLE_PREFIX, fileScanAlter, fileScanAlterTable, fileScanIndex, fileStatusCheck, fileTableScanReady, legacyStatusCheckName, } from './file-table-ddl';
|
|
3
|
-
export { classifyMigration, type ClassifyMigrationOptions, classifyMigrations, type DatabaseObject, type DatabaseObjectKind, declaredFunctions, type DeviationKind, type FileAdoption, type ManifestChange, type MigrationClassification, type MigrationDeviation, type MigrationFile, migrationManifest, type MigrationRefusal, type MigrationSetClassification, } from './migration-classify';
|
|
3
|
+
export { classifyMigration, type ClassifyMigrationOptions, classifyMigrations, type ClassifyMigrationsOptions, type DatabaseObject, type DatabaseObjectKind, type DataLossStatement, declaredFunctions, type DeviationKind, type FileAdoption, type ManifestChange, type MigrationClassification, type MigrationDataLoss, type MigrationDeviation, type MigrationDialect, type MigrationFile, migrationManifest, type MigrationRefusal, type MigrationSetClassification, } from './migration-classify';
|
|
4
4
|
export { lexSql, type SqlToken, sqlTokens, type Statement, statementsOf, topLevelStatements, upperWord } from './migration-sql';
|
|
5
5
|
export { PG_CATALOG_FUNCTIONS, SQL_KEYWORDS } from './pg-catalog-names';
|
|
6
6
|
export { afterName, type BodyStatement, closingParenthesis, CTE_FORM, type CteLists, ddlForeignSchema, dmlRelations, frameworkReference, type FunctionUse, functionUse, isFrameworkName, isPunct, type NameReference, nameReferences, type NameRole, nameText, nestedStatement, objectNameAt, parenthesizedTarget, ReadBody, ReadSql, referencedForeignSchema, refusedCall, skipWords, splitAtCommas, statementKind, unicodeIdentifier, } from './sql-names';
|
|
7
|
-
export { lexSqlite } from './sqlite-sql';
|
|
7
|
+
export { lexSqlite, SQLITE_PARAMETER_STARTS } from './sqlite-sql';
|
|
@@ -1,4 +1,10 @@
|
|
|
1
1
|
import type { SqlToken } from './migration-sql';
|
|
2
|
+
/**
|
|
3
|
+
* What starts a parameter SQLite binds by name or by position (`?`, `:x`, `@x`, `$x`, `#x`), each a `punct` token here.
|
|
4
|
+
* SQLite reads `$x(…)` up to a space or `)` as one parameter, a quote included, so the tokens after one may not be what
|
|
5
|
+
* SQLite reads: a reader of SQLite text refuses it at the first.
|
|
6
|
+
*/
|
|
7
|
+
export declare const SQLITE_PARAMETER_STARTS: ReadonlySet<string>;
|
|
2
8
|
/**
|
|
3
9
|
* The tokens of `sql` as SQLite reads it, and the line of the first string, quoted name or block comment that never
|
|
4
10
|
* closes. `'…'` (with `''`) is a string; `"…"`, `` `…` `` (each with its doubled quote) and `[…]` (no escape) are quoted
|