@fabrika/platform-node 0.9.0-dev.3 → 0.9.0-dev.30

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.
@@ -11,13 +11,14 @@ import {
11
11
  legacyStatusCheckName,
12
12
  STORED_FILES_TABLE,
13
13
  } from './file-table-ddl'
14
- import { lexSql, type SqlToken, topLevelStatements, upperWord } from './migration-sql'
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
+ CTE_FORM,
19
20
  ddlForeignSchema,
20
- dmlForeignSchema,
21
+ dmlRelations,
21
22
  frameworkReference,
22
23
  functionUse,
23
24
  isFrameworkName,
@@ -28,13 +29,18 @@ import {
28
29
  nestedStatement,
29
30
  objectNameAt,
30
31
  parenthesizedTarget,
31
- refusedFunctionCall,
32
+ ReadBody,
33
+ ReadSql,
34
+ referencedForeignSchema,
35
+ refusedCall,
32
36
  skipWords,
33
37
  splitAtCommas,
34
38
  statementKind,
35
39
  unicodeIdentifier,
36
40
  wordAtDepthZero,
41
+ writeTargets,
37
42
  } from './sql-names'
43
+ import { lexSqlite, SQLITE_PARAMETER_STARTS } from './sqlite-sql'
38
44
 
39
45
  /** A database object a migration declares, named as the catalog check names it (`trigger deals.audit`). */
40
46
  export type DatabaseObjectKind = 'function' | 'procedure' | 'trigger' | 'view' | 'materialized view' | 'rule' | 'policy'
@@ -62,6 +68,58 @@ export interface MigrationDeviation {
62
68
  readonly line: number
63
69
  }
64
70
 
71
+ /**
72
+ * A step of a file collection's adoption into a file column (ADR-0061): the `INSERT … SELECT` that copies the
73
+ * collection's files into a table, and the call that releases the collection. Paved, and shown to the approver: an
74
+ * adopted file is read under its table's policy from then on, and a release deletes every file no column adopted.
75
+ */
76
+ export type FileAdoption =
77
+ | { readonly step: 'adopt'; readonly collection: string; readonly table: string; readonly file: string; readonly line: number }
78
+ | { readonly step: 'release'; readonly collection: string; readonly file: string; readonly line: number }
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
+
119
+ /** A file adoption step before the file it lies in is known. */
120
+ type AdoptionStep = WithoutFile<FileAdoption>
121
+ type WithoutFile<T> = T extends unknown ? Omit<T, 'file'> : never
122
+
65
123
  export interface MigrationRefusal {
66
124
  /** What is refused, phrased to precede "is not allowed". */
67
125
  readonly reason: string
@@ -84,17 +142,40 @@ export interface MigrationClassification {
84
142
  /** One per refused statement, in order. A file with a refusal does not run. */
85
143
  readonly refused: readonly MigrationRefusal[]
86
144
  readonly deviations: readonly MigrationDeviation[]
145
+ /** The file's adoption steps, in order. */
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[]
87
149
  /** The objects the file creates. */
88
150
  readonly objects: readonly DatabaseObject[]
89
151
  readonly changes: readonly ManifestChange[]
90
152
  }
91
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
+
92
157
  export interface ClassifyMigrationOptions {
93
158
  readonly file: string
159
+ /** Postgres when absent. SQLite only adds the table options SQLite has (`STRICT`, `WITHOUT ROWID`). */
160
+ readonly dialect?: MigrationDialect
94
161
  /** The functions and procedures the whole migration set declares in the schema: a body or an expression may call them. */
95
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>
96
165
  /** The framework's own bundle, which alone may name the framework's `fabrika_*` tables. */
97
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>
98
179
  }
99
180
 
100
181
  export interface MigrationFile {
@@ -191,9 +272,20 @@ const RULE_ACTIONS: ReadonlySet<string> = new Set(['NOTHING', 'SELECT', 'INSERT'
191
272
 
192
273
  interface Context {
193
274
  readonly schema: string
275
+ readonly dialect: MigrationDialect
194
276
  readonly functions: ReadonlySet<string>
277
+ readonly views: ReadonlySet<string>
195
278
  readonly framework: boolean
279
+ readonly accessTables: ReadonlySet<string>
280
+ readonly accessViews: ReadonlySet<string>
196
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
197
289
  }
198
290
 
199
291
  /** Thrown inside one statement's classification; the statement then contributes only its refusal. */
@@ -206,7 +298,26 @@ class Refused extends Error {
206
298
  /** What one statement adds when it is not refused. */
207
299
  interface Collected {
208
300
  readonly deviations: { readonly kind: DeviationKind; readonly object: string; readonly line: number }[]
301
+ readonly adoptions: AdoptionStep[]
302
+ readonly dataLoss: WithoutFile<MigrationDataLoss>[]
209
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
210
321
  }
211
322
 
212
323
  function deviate(out: Collected, kind: DeviationKind, object: string, line: number): void {
@@ -232,21 +343,66 @@ function refuseForeignDdl(tokens: readonly SqlToken[], context: Context, label:
232
343
  if (reached !== undefined) throw new Refused(`${label} naming the schema ${reached}`, tokens[0]?.line ?? 1)
233
344
  }
234
345
 
235
- /** A query, a condition or a backfill: no schema but the application's, only allowlisted calls and nested statements. */
236
- function checkQuery(tokens: readonly SqlToken[], context: Context, label: string): void {
237
- const nested = nestedStatement(tokens)
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
+
374
+ /**
375
+ * A query, a condition or a backfill, read as one (`ReadSql`): no schema but the application's, only allowlisted calls
376
+ * and nested statements, and no CTE list it cannot read. Answers the functions of the migration set it calls, each once.
377
+ */
378
+ function checkQuery(read: ReadSql, context: Context, label: string): string[] {
379
+ const { tokens } = read
380
+ if (read.ctes.unread !== undefined) throw new Refused(`a WITH list that cannot be read as ${CTE_FORM}`, read.ctes.unread)
381
+ const nested = nestedStatement(read)
238
382
  if (nested !== undefined) throw new Refused(`${nested.statement} nested in a statement`, nested.line)
239
383
  const target = parenthesizedTarget(tokens)
240
384
  if (target !== undefined) throw new Refused(`a parenthesized ${target.statement} target`, target.line)
241
- const reached = dmlForeignSchema(tokens, context.schema)
385
+ const references = nameReferences(read)
386
+ const reached = referencedForeignSchema(references, context.schema)
242
387
  if (reached !== undefined) throw new Refused(`${label} reaching the schema ${reached}`, tokens[0]?.line ?? 1)
243
- const call = refusedFunctionCall(tokens, context.schema, context.functions)
388
+ const call = refusedCall(references, context.schema, context.functions)
244
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
+ }
245
401
  }
246
402
 
247
403
  /** A stored expression's calls: a paved built-in is plain, a reviewed or declared function a deviation, anything else refused. */
248
404
  function checkExpression(tokens: readonly SqlToken[], where: string, context: Context, out: Collected): void {
249
- for (const reference of nameReferences(tokens)) {
405
+ for (const reference of nameReferences(ReadSql.expression(tokens))) {
250
406
  if (reference.role !== 'call') continue
251
407
  const use = functionUse(reference, context.schema, context.functions)
252
408
  if (use === undefined) throw new Refused(`a call of ${reference.name}`, reference.line)
@@ -270,48 +426,16 @@ function isAssignment(tokens: readonly SqlToken[], index: number): boolean {
270
426
  }
271
427
 
272
428
  /**
273
- * The first statement of a function or `DO` body that does not begin with an allowlisted word or an assignment. A
274
- * declaration section (`DECLARE` … `BEGIN`) holds declarations; `THEN` and `ELSE` begin a statement except inside a
275
- * `CASE` expression.
429
+ * The first statement of a function or `DO` body (`ReadBody`) that does not begin with an allowlisted word or an
430
+ * assignment; a declaration section holds declarations.
276
431
  */
277
- function refusedBodyStatement(tokens: readonly SqlToken[]): { readonly statement: string; readonly line: number } | undefined {
278
- let start = true
279
- let declaring = false
280
- const cases: ('statement' | 'expression')[] = []
281
- for (let index = 0; index < tokens.length; index++) {
432
+ function refusedBodyStatement({ tokens, statements }: ReadBody): { readonly statement: string; readonly line: number } | undefined {
433
+ for (const { index, declaring } of statements) {
282
434
  const token = tokens[index]
283
435
  const word = upperWord(token)
284
- if (start) {
285
- if (isPunct(token, ';')) continue
286
- start = false
287
- if (isPunct(token, '<') && isPunct(tokens[index + 1], '<')) {
288
- while (index < tokens.length && !(isPunct(tokens[index], '>') && isPunct(tokens[index + 1], '>'))) index++
289
- index++
290
- start = true
291
- continue
292
- }
293
- const allowed = (declaring && word !== 'BEGIN') || (word !== undefined && BODY_STATEMENTS.has(word))
294
- || (isName(token) && isAssignment(tokens, index))
295
- if (!allowed) return { statement: word ?? statementKind(tokens.slice(index)), line: token?.line ?? 1 }
296
- if (word === 'CASE') {
297
- cases.push('statement')
298
- continue
299
- }
300
- } else if (word === 'CASE') {
301
- cases.push('expression')
302
- continue
303
- }
304
- const innermost = cases[cases.length - 1]
305
- if (word === 'DECLARE') declaring = true
306
- if (word === 'BEGIN') declaring = false
307
- if (isPunct(token, ';') || word === 'BEGIN' || word === 'DECLARE') start = true
308
- else if (word === 'LOOP') start = upperWord(tokens[index - 1]) !== 'END'
309
- else if (word === 'THEN' || word === 'ELSE') start = innermost !== 'expression'
310
- else if (word === 'END' && innermost === 'expression') cases.pop()
311
- else if (word === 'END' && upperWord(tokens[index + 1]) === 'CASE') {
312
- cases.pop()
313
- index++
314
- }
436
+ const allowed = (declaring && word !== 'BEGIN') || (word !== undefined && BODY_STATEMENTS.has(word))
437
+ || (isName(token) && isAssignment(tokens, index))
438
+ if (!allowed) return { statement: word ?? statementKind(tokens.slice(index)), line: token?.line ?? 1 }
315
439
  }
316
440
  return undefined
317
441
  }
@@ -342,9 +466,10 @@ function checkBody(tokens: readonly SqlToken[], context: Context): void {
342
466
  if (framework !== undefined) throw new Refused(`a reference to the framework's ${framework.name}`, framework.line)
343
467
  const execute = tokens.find((token) => upperWord(token) === 'EXECUTE')
344
468
  if (execute !== undefined) throw new Refused('a dynamic EXECUTE in a body', execute.line)
345
- const statement = refusedBodyStatement(tokens)
469
+ const read = ReadBody.of(tokens)
470
+ const statement = refusedBodyStatement(read)
346
471
  if (statement !== undefined) throw new Refused(`${statement.statement} in a body`, statement.line)
347
- checkQuery(tokens, context, 'a body')
472
+ checkQuery(read, context, 'a body')
348
473
  refuseForeignDdl(declarations(tokens), context, 'a declaration')
349
474
  }
350
475
 
@@ -419,8 +544,9 @@ function createFunction(tokens: readonly SqlToken[], at: number, kind: 'function
419
544
  refuseForeignDdl(header, context, label)
420
545
  // An argument default runs at every call that omits the argument, so it is a query like the body.
421
546
  const args = tokens.slice(named + 1, close)
422
- checkQuery(args, context, 'an argument default')
547
+ checkQuery(ReadSql.clause(args), context, 'an argument default')
423
548
  checkBody(body, context)
549
+ refuseAccessWrite(body, context, `a ${kind} body`)
424
550
  deviate(out, kind, name, line)
425
551
  out.changes.push({ change: 'create routine', object: { kind, name }, args: `${kind} (${argumentText(args)})`, line })
426
552
  }
@@ -454,11 +580,18 @@ function createTrigger(tokens: readonly SqlToken[], at: number, context: Context
454
580
  const on = wordAtDepthZero(tokens, 'ON', at + 1)
455
581
  if (name === undefined || on === undefined) throw new Refused('CREATE TRIGGER', line)
456
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
+ }
457
590
  const when = wordAtDepthZero(tokens, 'WHEN', on)
458
591
  const whenClose = when === undefined || !isPunct(tokens[when + 1], '(') ? undefined : closingParenthesis(tokens, when + 1)
459
592
  const header = when === undefined || whenClose === undefined ? tokens : [...tokens.slice(0, when), ...tokens.slice(whenClose + 1)]
460
593
  refuseForeignDdl(header, context, 'CREATE TRIGGER')
461
- if (when !== undefined && whenClose !== undefined) checkQuery(tokens.slice(when + 2, whenClose), context, 'a trigger condition')
594
+ if (when !== undefined && whenClose !== undefined) checkQuery(ReadSql.clause(tokens.slice(when + 2, whenClose)), context, 'a trigger condition')
462
595
  const execute = wordAtDepthZero(tokens, 'EXECUTE', on)
463
596
  const fn = execute === undefined ? undefined : objectNameAt(tokens, execute + 2)
464
597
  if (execute === undefined || fn === undefined) throw new Refused('CREATE TRIGGER without EXECUTE FUNCTION', line)
@@ -500,7 +633,7 @@ function createView(tokens: readonly SqlToken[], at: number, kind: 'view' | 'mat
500
633
  if (!(first === 'SELECT' || first === 'WITH' || first === 'VALUES' || isPunct(query[0], '('))) {
501
634
  throw new Refused(`${label} … AS ${statementKind(query)}`, line)
502
635
  }
503
- checkQuery(query, context, 'a view')
636
+ checkQuery(ReadSql.query(query), context, 'a view')
504
637
  declareObject(out, kind, name, line)
505
638
  }
506
639
 
@@ -512,14 +645,21 @@ function createRule(tokens: readonly SqlToken[], at: number, context: Context, o
512
645
  const doIndex = to === undefined ? undefined : wordAtDepthZero(tokens, 'DO', to)
513
646
  if (name === undefined || to === undefined || doIndex === undefined) throw new Refused('CREATE RULE', line)
514
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)
515
650
  const where = wordAtDepthZero(tokens, 'WHERE', to)
516
651
  const headerEnd = where !== undefined && where < doIndex ? where : doIndex
517
652
  refuseForeignDdl(tokens.slice(0, headerEnd), context, 'CREATE RULE')
518
653
  let action = skipWords(tokens, skipWords(tokens, doIndex + 1, 'ALSO'), 'INSTEAD')
519
- if (isPunct(tokens[action], '(')) 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
+ }
520
659
  const first = upperWord(tokens[action])
521
660
  if (first === undefined || !RULE_ACTIONS.has(first)) throw new Refused(`${first ?? statementKind(tokens.slice(action))} in a rule action`, line)
522
- checkQuery(tokens.slice(headerEnd), context, 'a rule')
661
+ checkQuery(ReadSql.clause(tokens.slice(headerEnd)), context, 'a rule')
662
+ refuseAccessWrite(tokens.slice(action), context, 'a rule action')
523
663
  declareObject(out, 'rule', `${table}.${name}`, line)
524
664
  }
525
665
 
@@ -534,7 +674,7 @@ function createPolicy(tokens: readonly SqlToken[], at: number, context: Context,
534
674
  const starts = [using, withCheck].filter((index) => index !== undefined)
535
675
  const expressions = starts.length === 0 ? tokens.length : Math.min(...starts)
536
676
  refuseForeignDdl(tokens.slice(0, expressions), context, 'CREATE POLICY')
537
- checkQuery(tokens.slice(expressions), context, 'a policy')
677
+ checkQuery(ReadSql.clause(tokens.slice(expressions)), context, 'a policy')
538
678
  declareObject(out, 'policy', `${table}.${name}`, line)
539
679
  }
540
680
 
@@ -575,18 +715,41 @@ function classifyElement(element: readonly SqlToken[], table: string, context: C
575
715
  checkExpression(element.slice(1), `${table}.${column}`, context, out)
576
716
  }
577
717
 
578
- /** `CREATE TABLE [IF NOT EXISTS] <name> (<columns and constraints>)` and nothing after it; `LIKE` without `INCLUDING`. */
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
+ */
579
740
  function createTable(tokens: readonly SqlToken[], context: Context, out: Collected): void {
580
741
  const line = tokens[0]?.line ?? 1
581
742
  const nameAt = skipWords(tokens, 2, 'IF', 'NOT', 'EXISTS')
582
743
  const named = afterName(tokens, nameAt)
583
744
  const close = named === undefined || !isPunct(tokens[named], '(') ? undefined : closingParenthesis(tokens, named)
584
745
  if (named === undefined || close === undefined) throw new Refused('CREATE TABLE other than a column list', line)
585
- if (close !== tokens.length - 1) {
746
+ const sqliteOptions = context.dialect === 'sqlite' && isSqliteTableOptions(tokens.slice(close + 1))
747
+ if (close !== tokens.length - 1 && !sqliteOptions) {
586
748
  const after = tokens[close + 1]
587
749
  throw new Refused(`CREATE TABLE … ${upperWord(after) ?? statementKind(tokens.slice(close + 1))}`, line)
588
750
  }
589
751
  refuseForeignDdl(tokens, context, 'CREATE TABLE')
752
+ refuseConflictClause(tokens, 'CREATE TABLE')
590
753
  const table = ownName(tokens, nameAt, context, 'CREATE TABLE')
591
754
  for (const element of splitAtCommas(tokens.slice(named + 1, close))) {
592
755
  // `LIKE … INCLUDING` copies defaults, constraints and indexes from a table the classifier has not read.
@@ -595,6 +758,17 @@ function createTable(tokens: readonly SqlToken[], context: Context, out: Collect
595
758
  }
596
759
  classifyElement(element, table, context, out)
597
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)
598
772
  }
599
773
 
600
774
  /** `CREATE [UNIQUE] INDEX [IF NOT EXISTS] [name] ON [ONLY] table [USING method] (…) …`. */
@@ -616,7 +790,10 @@ function createIndex(tokens: readonly SqlToken[], context: Context, out: Collect
616
790
  checkExpression(tokens.slice(index), name ?? table, context, out)
617
791
  }
618
792
 
619
- /** Why one `ALTER TABLE` clause is outside the allowlist; its expressions are classified as a column's or a table's. */
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
+ */
620
797
  function alterClause(clause: readonly SqlToken[], table: string, context: Context, out: Collected): void {
621
798
  const line = clause[0]?.line ?? 1
622
799
  const [action, next] = [upperWord(clause[0]), upperWord(clause[1])]
@@ -625,11 +802,29 @@ function alterClause(clause: readonly SqlToken[], table: string, context: Contex
625
802
  classifyElement(clause.slice(1), table, context, out)
626
803
  return
627
804
  }
628
- classifyElement(clause.slice(skipWords(clause, skipWords(clause, 1, 'COLUMN'), 'IF', 'NOT', 'EXISTS')), table, context, out)
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
629
826
  return
630
827
  }
631
- if (action === 'DROP') return
632
- if (action === 'VALIDATE' && next === 'CONSTRAINT') return
633
828
  if (action === 'ALTER' && next !== 'CONSTRAINT') {
634
829
  const columnAt = next === 'COLUMN' ? 2 : 1
635
830
  const column = nameText(clause[columnAt])
@@ -643,7 +838,12 @@ function alterClause(clause: readonly SqlToken[], table: string, context: Contex
643
838
  const rest = clause.slice(actionAt + columnAction.length)
644
839
  // A default persists in the schema; `TYPE … USING` runs once over the rows, as a backfill does.
645
840
  if (columnAction[1] === 'DEFAULT' && columnAction[0] === 'SET') checkExpression(rest, `${table}.${column}`, context, out)
646
- else if (columnAction[0] === 'TYPE' || columnAction[1] === 'DATA') checkQuery(rest, context, 'ALTER TABLE … USING')
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
647
847
  return
648
848
  }
649
849
  throw new Refused(`ALTER TABLE … ${action ?? 'an action'}`, line)
@@ -658,17 +858,25 @@ function alterTable(tokens: readonly SqlToken[], context: Context, out: Collecte
658
858
  if (named === undefined) throw new Refused('ALTER TABLE', line)
659
859
  const table = ownName(tokens, start, context, 'ALTER TABLE')
660
860
  const rest = tokens.slice(isPunct(tokens[named], '*') ? named + 1 : named)
861
+ refuseConflictClause(rest, 'ALTER TABLE')
661
862
  // RENAME TO, RENAME [COLUMN] a TO b and RENAME CONSTRAINT a TO b each stand alone.
662
863
  if (upperWord(rest[0]) === 'RENAME') {
663
864
  const to = upperWord(rest[1]) === 'TO' ? nameText(rest[2]) : undefined
664
- if (to !== undefined) out.changes.push({ change: 'rename table', from: table, to })
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
+ }
665
870
  return
666
871
  }
872
+ out.unproven = false
667
873
  for (const clause of splitAtCommas(rest)) alterClause(clause, table, context, out)
668
874
  }
669
875
 
670
- function alterIndexOrType(tokens: readonly SqlToken[], kind: string, context: Context): void {
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 {
671
878
  const line = tokens[0]?.line ?? 1
879
+ let rename = true
672
880
  if (kind === 'INDEX') {
673
881
  const named = afterName(tokens, skipWords(tokens, 2, 'IF', 'EXISTS'))
674
882
  const isRename = named !== undefined && upperWord(tokens[named]) === 'RENAME' && upperWord(tokens[named + 1]) === 'TO'
@@ -678,8 +886,12 @@ function alterIndexOrType(tokens: readonly SqlToken[], kind: string, context: Co
678
886
  const action = named === undefined ? undefined : upperWord(tokens[named])
679
887
  const isValue = named !== undefined && (action === 'ADD' || action === 'RENAME') && upperWord(tokens[named + 1]) === 'VALUE'
680
888
  if (!isValue) throw new Refused('ALTER TYPE other than ADD VALUE or RENAME VALUE', line)
889
+ rename = action === 'RENAME'
681
890
  }
682
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
683
895
  }
684
896
 
685
897
  /** The kinds of database code `ALTER … RENAME TO` may rename, and what each names in the manifest. */
@@ -700,6 +912,7 @@ const RENAMEABLE: Readonly<Record<string, readonly DatabaseObjectKind[]>> = {
700
912
  */
701
913
  function alterRename(tokens: readonly SqlToken[], context: Context, out: Collected): void {
702
914
  const line = tokens[0]?.line ?? 1
915
+ voidFresh(context, out)
703
916
  const materialized = upperWord(tokens[1]) === 'MATERIALIZED' && upperWord(tokens[2]) === 'VIEW'
704
917
  const kind = materialized ? 'VIEW' : (upperWord(tokens[1]) ?? '')
705
918
  const kinds: readonly DatabaseObjectKind[] = materialized ? ['materialized view'] : Object.hasOwn(RENAMEABLE, kind) ? (RENAMEABLE[kind] ?? []) : []
@@ -732,6 +945,7 @@ function alterRename(tokens: readonly SqlToken[], context: Context, out: Collect
732
945
  deviate(out, kinds[0] ?? 'trigger', renamed, line)
733
946
  return
734
947
  }
948
+ if (kind === 'VIEW') refuseAccessRename(name, target, context, line)
735
949
  for (const objectKind of kinds) {
736
950
  if (objectKind === 'function' || objectKind === 'procedure') refuseShadowing(target, objectKind, line)
737
951
  out.changes.push({ change: 'rename', from: { kind: objectKind, name }, to: { kind: objectKind, name: target } })
@@ -774,7 +988,172 @@ function classifyDrop(tokens: readonly SqlToken[], context: Context, out: Collec
774
988
  // An extension may live in another schema; CASCADE would drop what other schemas built on it.
775
989
  if (kind === 'EXTENSION' && tokens.some((token) => upperWord(token) === 'CASCADE')) throw new Refused('DROP EXTENSION … CASCADE', line)
776
990
  refuseForeignDdl(tokens, context, statementKind(tokens))
777
- out.changes.push(...dropChanges(tokens, kind, context))
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
778
1157
  }
779
1158
 
780
1159
  function classifyCreate(tokens: readonly SqlToken[], context: Context, out: Collected): void {
@@ -916,34 +1295,102 @@ function adoptedTableNames(tokens: readonly SqlToken[]): ReadonlySet<string> {
916
1295
 
917
1296
  /**
918
1297
  * `SELECT fabrika_files_copy_legacy('<collection>');` and `SELECT fabrika_files_release('<collection>');`: the only
919
- * calls of a framework function an application migration makes, each a statement of its own.
1298
+ * calls of a framework function an application migration makes, each a statement of its own. Answers the function and
1299
+ * the collection, or `undefined` for any other statement.
920
1300
  */
921
- function isFileAdoptionCall(tokens: readonly SqlToken[]): boolean {
1301
+ function fileAdoptionCall(tokens: readonly SqlToken[]): { readonly called: string; readonly collection: string } | undefined {
922
1302
  const [select, name, open, collection, close] = tokens
923
1303
  const called = nameText(name)
924
- return tokens.length === 5 && upperWord(select) === 'SELECT' && (called === FILES_COPY_FUNCTION || called === FILES_RELEASE_FUNCTION)
925
- && isPunct(open, '(')
926
- && collection?.kind === 'string' && /^[a-z_][a-z0-9_]*$/.test(collection.text ?? '') && isPunct(close, ')')
1304
+ const value = collection?.kind === 'string' ? collection.text : undefined
1305
+ const matches = tokens.length === 5 && upperWord(select) === 'SELECT' && (called === FILES_COPY_FUNCTION || called === FILES_RELEASE_FUNCTION)
1306
+ && isPunct(open, '(') && value !== undefined && /^[a-z_][a-z0-9_]*$/.test(value) && isPunct(close, ')')
1307
+ return matches ? { called, collection: value } : undefined
1308
+ }
1309
+
1310
+ /** The adoption an `INSERT … SELECT` from collection tables makes: each collection's files into the target table. */
1311
+ function adoptionSteps(tokens: readonly SqlToken[], adopted: ReadonlySet<string>): AdoptionStep[] {
1312
+ // `checkQuery` refused a schema other than the application's, so a qualified target is its own table.
1313
+ const table = objectNameAt(tokens, skipWords(tokens, 1, 'INTO'))?.name
1314
+ const line = tokens[0]?.line ?? 1
1315
+ if (table === undefined) return []
1316
+ return [...adopted].sort().map((name) => ({ step: 'adopt', collection: name.slice(FILE_TABLE_PREFIX.length), table, line }))
927
1317
  }
928
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
+ */
929
1356
  function classifyStatement(tokens: readonly SqlToken[], context: Context, out: Collected): void {
930
1357
  const line = tokens[0]?.line ?? 1
931
1358
  const unicode = unicodeIdentifier(tokens)
932
1359
  if (unicode !== undefined) throw new Refused('a Unicode-escaped identifier (U&"…")', unicode.line)
933
- if (!context.framework && isFileAdoptionCall(tokens)) return
934
- const allowed = new Set([...fileTableNames(tokens), ...adoptedTableNames(tokens)])
1360
+ const call = context.framework ? undefined : fileAdoptionCall(tokens)
1361
+ if (call !== undefined) {
1362
+ if (call.called === FILES_RELEASE_FUNCTION) out.adoptions.push({ step: 'release', collection: call.collection, line: tokens[0]?.line ?? 1 })
1363
+ out.unproven = false
1364
+ return
1365
+ }
1366
+ const adopted = adoptedTableNames(tokens)
1367
+ const allowed = new Set([...fileTableNames(tokens), ...adopted])
935
1368
  const framework = context.framework ? undefined : frameworkReference(withoutFileReferences(tokens), allowed)
936
1369
  if (framework !== undefined) throw new Refused(`a reference to the framework's ${framework.name}`, framework.line)
937
1370
  const first = upperWord(tokens[0])
938
- if (first === 'INSERT' || first === 'UPDATE' || first === 'DELETE') return checkQuery(tokens, context, first)
939
- if (first === 'COMMENT' && upperWord(tokens[1]) === 'ON') return classifyComment(tokens, context)
940
- if (first === 'DO') return classifyDo(tokens, context, out)
941
- if (first === 'CREATE') return classifyCreate(tokens, context, out)
1371
+ if (first === 'INSERT' || first === 'UPDATE' || first === 'DELETE') {
1372
+ const calls = checkQuery(ReadSql.query(tokens), context, first)
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
1387
+ return
1388
+ }
942
1389
  if (first === 'DROP') return classifyDrop(tokens, context, out)
943
- if (first === 'TRUNCATE') return refuseForeignDdl(tokens, context, 'TRUNCATE')
1390
+ if (first === 'TRUNCATE') return classifyTruncate(tokens, context, out)
944
1391
  const second = upperWord(tokens[1])
945
1392
  if (first === 'ALTER' && second === 'TABLE') return alterTable(tokens, context, out)
946
- 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)
947
1394
  if (first === 'ALTER' && second !== undefined && (Object.hasOwn(RENAMEABLE, second) || second === 'MATERIALIZED')) {
948
1395
  return alterRename(tokens, context, out)
949
1396
  }
@@ -958,23 +1405,43 @@ function classifyStatement(tokens: readonly SqlToken[], context: Context, out: C
958
1405
  * `ALTER … RENAME TO`, `DO`, and a stored expression that calls anything but a paved built-in. Refused: a schema
959
1406
  * other than `schema` (`pg_catalog` relations included), a framework `fabrika_*` name, `SECURITY DEFINER`, a function
960
1407
  * `SET` clause, a language other than `sql` and `plpgsql`, a body that is not literal or that holds dynamic `EXECUTE`
961
- * or a statement outside its allowlist, a call outside the function allowlist, and every form not named here:
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:
962
1410
  * `COPY`, `GRANT`, `REVOKE`, roles, extensions, event triggers, domains (codegen cannot bind one), `SELECT`, `WITH`
963
1411
  * and `MERGE` among them. Transaction control and
964
- * `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`).
965
1414
  */
966
1415
  export function classifyMigration(sql: string, schema: string, options: ClassifyMigrationOptions): MigrationClassification {
967
- const context: Context = { schema, functions: options.functions ?? new Set(), framework: options.framework === true, doBlocks: 0 }
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
+ }
968
1428
  const refused: MigrationRefusal[] = []
969
1429
  const deviations: MigrationDeviation[] = []
1430
+ const adoptions: FileAdoption[] = []
1431
+ const dataLoss: MigrationDataLoss[] = []
970
1432
  const changes: ManifestChange[] = []
971
1433
  const keys = new Set<string>()
972
- const { unterminated } = lexSql(sql)
1434
+ const { tokens: all, unterminated } = lexMigration(sql, context.dialect)
973
1435
  if (unterminated !== undefined) {
974
1436
  refused.push({ reason: 'a literal, a quoted name or a comment that never closes', file: options.file, line: unterminated })
975
1437
  }
976
- for (const { tokens, line } of topLevelStatements(sql)) {
977
- const out: Collected = { deviations: [], changes: [] }
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 }
978
1445
  try {
979
1446
  classifyStatement(tokens, context, out)
980
1447
  } catch (error) {
@@ -982,22 +1449,78 @@ export function classifyMigration(sql: string, schema: string, options: Classify
982
1449
  refused.push({ reason: error.reason, file: options.file, line: error.line || line })
983
1450
  continue
984
1451
  }
1452
+ if (out.unproven) out.dataLoss.push({ statement: 'UNPROVEN', object: leadingKeywords(tokens), line: tokens[0]?.line ?? line })
985
1453
  for (const deviation of out.deviations) {
986
1454
  const key = `${deviation.kind} ${deviation.object}`
987
1455
  if (keys.has(key)) continue
988
1456
  keys.add(key)
989
1457
  deviations.push({ ...deviation, file: options.file })
990
1458
  }
1459
+ adoptions.push(...out.adoptions.map((step) => ({ ...step, file: options.file })))
1460
+ dataLoss.push(...out.dataLoss.map((loss) => ({ ...loss, file: options.file })))
991
1461
  changes.push(...out.changes)
992
1462
  }
993
1463
  const objects = changes.flatMap((change) => (change.change === 'create' || change.change === 'create routine' ? [change.object] : []))
994
- return { file: options.file, refused, deviations, 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
995
1518
  }
996
1519
 
997
1520
  /** The names of the functions and procedures a migration creates or renames to in `schema`, read without classifying them. */
998
- export function declaredFunctions(sql: string, schema: string): string[] {
1521
+ export function declaredFunctions(sql: string, schema: string, dialect: MigrationDialect = 'postgres'): string[] {
999
1522
  const names: string[] = []
1000
- for (const { tokens } of topLevelStatements(sql)) {
1523
+ for (const { tokens } of migrationStatements(sql, dialect)) {
1001
1524
  const first = upperWord(tokens[0])
1002
1525
  const at = first === 'CREATE' ? skipWords(tokens, 1, 'OR', 'REPLACE') : 1
1003
1526
  const kind = upperWord(tokens[at])
@@ -1018,6 +1541,44 @@ export function declaredFunctions(sql: string, schema: string): string[] {
1018
1541
  return names.filter((name) => !shadows(name))
1019
1542
  }
1020
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
+
1021
1582
  const objectKey = (object: DatabaseObject): string => `${object.kind} ${object.name}`
1022
1583
  const ON_TABLE: ReadonlySet<DatabaseObjectKind> = new Set(['trigger', 'rule', 'policy'])
1023
1584
 
@@ -1053,9 +1614,27 @@ export function migrationManifest(classifications: readonly MigrationClassificat
1053
1614
  * Classifies a whole migration set in order. A body or an expression may call a function any file of the set
1054
1615
  * declares; the manifest is what the catalog check admits.
1055
1616
  */
1056
- export function classifyMigrations(files: readonly MigrationFile[], schema: string): MigrationSetClassification {
1057
- const functions = new Set(files.flatMap((file) => declaredFunctions(file.sql, schema)))
1058
- const classified = files.map((file) => classifyMigration(file.sql, schema, { file: file.name, functions, framework: file.framework === true }))
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
+ )
1059
1638
  const withOverloads = refuseOverloads(classified)
1060
1639
  return { files: withOverloads, objects: migrationManifest(withOverloads) }
1061
1640
  }