@fabrika/platform-node 0.9.0-dev.1 → 0.9.0-dev.11

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/platform-node",
3
- "version": "0.9.0-dev.1",
3
+ "version": "0.9.0-dev.11",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -13,22 +13,23 @@
13
13
  "files": [
14
14
  "src",
15
15
  "migrations",
16
- "!src/**/__tests__/**"
16
+ "!src/**/__tests__/**",
17
+ "types"
17
18
  ],
18
19
  "exports": {
19
20
  ".": {
20
21
  "bun": "./src/index.ts",
21
- "types": "./src/index.ts",
22
+ "types": "./types/src/index.d.ts",
22
23
  "default": "./src/index.ts"
23
24
  },
24
25
  "./postgres-migrations": {
25
26
  "bun": "./src/postgres-migrations.ts",
26
- "types": "./src/postgres-migrations.ts",
27
+ "types": "./types/src/postgres-migrations.d.ts",
27
28
  "default": "./src/postgres-migrations.ts"
28
29
  },
29
30
  "./sql": {
30
31
  "bun": "./src/sql.ts",
31
- "types": "./src/sql.ts",
32
+ "types": "./types/src/sql.d.ts",
32
33
  "default": "./src/sql.ts"
33
34
  }
34
35
  },
@@ -37,6 +38,6 @@
37
38
  "test": "bun test"
38
39
  },
39
40
  "dependencies": {
40
- "@fabrika/platform": "0.9.0-dev.1"
41
+ "@fabrika/platform": "0.9.0-dev.11"
41
42
  }
42
43
  }
@@ -16,8 +16,8 @@ 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
21
  frameworkReference,
22
22
  functionUse,
23
23
  isFrameworkName,
@@ -28,7 +28,10 @@ import {
28
28
  nestedStatement,
29
29
  objectNameAt,
30
30
  parenthesizedTarget,
31
- refusedFunctionCall,
31
+ ReadBody,
32
+ ReadSql,
33
+ referencedForeignSchema,
34
+ refusedCall,
32
35
  skipWords,
33
36
  splitAtCommas,
34
37
  statementKind,
@@ -62,6 +65,19 @@ export interface MigrationDeviation {
62
65
  readonly line: number
63
66
  }
64
67
 
68
+ /**
69
+ * A step of a file collection's adoption into a file column (ADR-0061): the `INSERT … SELECT` that copies the
70
+ * collection's files into a table, and the call that releases the collection. Paved, and shown to the approver: an
71
+ * adopted file is read under its table's policy from then on, and a release deletes every file no column adopted.
72
+ */
73
+ export type FileAdoption =
74
+ | { readonly step: 'adopt'; readonly collection: string; readonly table: string; readonly file: string; readonly line: number }
75
+ | { readonly step: 'release'; readonly collection: string; readonly file: string; readonly line: number }
76
+
77
+ /** A file adoption step before the file it lies in is known. */
78
+ type AdoptionStep = WithoutFile<FileAdoption>
79
+ type WithoutFile<T> = T extends unknown ? Omit<T, 'file'> : never
80
+
65
81
  export interface MigrationRefusal {
66
82
  /** What is refused, phrased to precede "is not allowed". */
67
83
  readonly reason: string
@@ -84,6 +100,8 @@ export interface MigrationClassification {
84
100
  /** One per refused statement, in order. A file with a refusal does not run. */
85
101
  readonly refused: readonly MigrationRefusal[]
86
102
  readonly deviations: readonly MigrationDeviation[]
103
+ /** The file's adoption steps, in order. */
104
+ readonly adoptions: readonly FileAdoption[]
87
105
  /** The objects the file creates. */
88
106
  readonly objects: readonly DatabaseObject[]
89
107
  readonly changes: readonly ManifestChange[]
@@ -206,6 +224,7 @@ class Refused extends Error {
206
224
  /** What one statement adds when it is not refused. */
207
225
  interface Collected {
208
226
  readonly deviations: { readonly kind: DeviationKind; readonly object: string; readonly line: number }[]
227
+ readonly adoptions: AdoptionStep[]
209
228
  readonly changes: ManifestChange[]
210
229
  }
211
230
 
@@ -232,21 +251,27 @@ function refuseForeignDdl(tokens: readonly SqlToken[], context: Context, label:
232
251
  if (reached !== undefined) throw new Refused(`${label} naming the schema ${reached}`, tokens[0]?.line ?? 1)
233
252
  }
234
253
 
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)
254
+ /**
255
+ * 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.
257
+ */
258
+ function checkQuery(read: ReadSql, context: Context, label: string): void {
259
+ const { tokens } = read
260
+ if (read.ctes.unread !== undefined) throw new Refused(`a WITH list that cannot be read as ${CTE_FORM}`, read.ctes.unread)
261
+ const nested = nestedStatement(read)
238
262
  if (nested !== undefined) throw new Refused(`${nested.statement} nested in a statement`, nested.line)
239
263
  const target = parenthesizedTarget(tokens)
240
264
  if (target !== undefined) throw new Refused(`a parenthesized ${target.statement} target`, target.line)
241
- const reached = dmlForeignSchema(tokens, context.schema)
265
+ const references = nameReferences(read)
266
+ const reached = referencedForeignSchema(references, context.schema)
242
267
  if (reached !== undefined) throw new Refused(`${label} reaching the schema ${reached}`, tokens[0]?.line ?? 1)
243
- const call = refusedFunctionCall(tokens, context.schema, context.functions)
268
+ const call = refusedCall(references, context.schema, context.functions)
244
269
  if (call !== undefined) throw new Refused(`a call of ${call.name}`, call.line)
245
270
  }
246
271
 
247
272
  /** A stored expression's calls: a paved built-in is plain, a reviewed or declared function a deviation, anything else refused. */
248
273
  function checkExpression(tokens: readonly SqlToken[], where: string, context: Context, out: Collected): void {
249
- for (const reference of nameReferences(tokens)) {
274
+ for (const reference of nameReferences(ReadSql.expression(tokens))) {
250
275
  if (reference.role !== 'call') continue
251
276
  const use = functionUse(reference, context.schema, context.functions)
252
277
  if (use === undefined) throw new Refused(`a call of ${reference.name}`, reference.line)
@@ -270,48 +295,16 @@ function isAssignment(tokens: readonly SqlToken[], index: number): boolean {
270
295
  }
271
296
 
272
297
  /**
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.
298
+ * The first statement of a function or `DO` body (`ReadBody`) that does not begin with an allowlisted word or an
299
+ * assignment; a declaration section holds declarations.
276
300
  */
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++) {
301
+ function refusedBodyStatement({ tokens, statements }: ReadBody): { readonly statement: string; readonly line: number } | undefined {
302
+ for (const { index, declaring } of statements) {
282
303
  const token = tokens[index]
283
304
  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
- }
305
+ const allowed = (declaring && word !== 'BEGIN') || (word !== undefined && BODY_STATEMENTS.has(word))
306
+ || (isName(token) && isAssignment(tokens, index))
307
+ if (!allowed) return { statement: word ?? statementKind(tokens.slice(index)), line: token?.line ?? 1 }
315
308
  }
316
309
  return undefined
317
310
  }
@@ -342,9 +335,10 @@ function checkBody(tokens: readonly SqlToken[], context: Context): void {
342
335
  if (framework !== undefined) throw new Refused(`a reference to the framework's ${framework.name}`, framework.line)
343
336
  const execute = tokens.find((token) => upperWord(token) === 'EXECUTE')
344
337
  if (execute !== undefined) throw new Refused('a dynamic EXECUTE in a body', execute.line)
345
- const statement = refusedBodyStatement(tokens)
338
+ const read = ReadBody.of(tokens)
339
+ const statement = refusedBodyStatement(read)
346
340
  if (statement !== undefined) throw new Refused(`${statement.statement} in a body`, statement.line)
347
- checkQuery(tokens, context, 'a body')
341
+ checkQuery(read, context, 'a body')
348
342
  refuseForeignDdl(declarations(tokens), context, 'a declaration')
349
343
  }
350
344
 
@@ -419,7 +413,7 @@ function createFunction(tokens: readonly SqlToken[], at: number, kind: 'function
419
413
  refuseForeignDdl(header, context, label)
420
414
  // An argument default runs at every call that omits the argument, so it is a query like the body.
421
415
  const args = tokens.slice(named + 1, close)
422
- checkQuery(args, context, 'an argument default')
416
+ checkQuery(ReadSql.clause(args), context, 'an argument default')
423
417
  checkBody(body, context)
424
418
  deviate(out, kind, name, line)
425
419
  out.changes.push({ change: 'create routine', object: { kind, name }, args: `${kind} (${argumentText(args)})`, line })
@@ -458,7 +452,7 @@ function createTrigger(tokens: readonly SqlToken[], at: number, context: Context
458
452
  const whenClose = when === undefined || !isPunct(tokens[when + 1], '(') ? undefined : closingParenthesis(tokens, when + 1)
459
453
  const header = when === undefined || whenClose === undefined ? tokens : [...tokens.slice(0, when), ...tokens.slice(whenClose + 1)]
460
454
  refuseForeignDdl(header, context, 'CREATE TRIGGER')
461
- if (when !== undefined && whenClose !== undefined) checkQuery(tokens.slice(when + 2, whenClose), context, 'a trigger condition')
455
+ if (when !== undefined && whenClose !== undefined) checkQuery(ReadSql.clause(tokens.slice(when + 2, whenClose)), context, 'a trigger condition')
462
456
  const execute = wordAtDepthZero(tokens, 'EXECUTE', on)
463
457
  const fn = execute === undefined ? undefined : objectNameAt(tokens, execute + 2)
464
458
  if (execute === undefined || fn === undefined) throw new Refused('CREATE TRIGGER without EXECUTE FUNCTION', line)
@@ -500,7 +494,7 @@ function createView(tokens: readonly SqlToken[], at: number, kind: 'view' | 'mat
500
494
  if (!(first === 'SELECT' || first === 'WITH' || first === 'VALUES' || isPunct(query[0], '('))) {
501
495
  throw new Refused(`${label} … AS ${statementKind(query)}`, line)
502
496
  }
503
- checkQuery(query, context, 'a view')
497
+ checkQuery(ReadSql.query(query), context, 'a view')
504
498
  declareObject(out, kind, name, line)
505
499
  }
506
500
 
@@ -519,7 +513,7 @@ function createRule(tokens: readonly SqlToken[], at: number, context: Context, o
519
513
  if (isPunct(tokens[action], '(')) action++
520
514
  const first = upperWord(tokens[action])
521
515
  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')
516
+ checkQuery(ReadSql.clause(tokens.slice(headerEnd)), context, 'a rule')
523
517
  declareObject(out, 'rule', `${table}.${name}`, line)
524
518
  }
525
519
 
@@ -534,7 +528,7 @@ function createPolicy(tokens: readonly SqlToken[], at: number, context: Context,
534
528
  const starts = [using, withCheck].filter((index) => index !== undefined)
535
529
  const expressions = starts.length === 0 ? tokens.length : Math.min(...starts)
536
530
  refuseForeignDdl(tokens.slice(0, expressions), context, 'CREATE POLICY')
537
- checkQuery(tokens.slice(expressions), context, 'a policy')
531
+ checkQuery(ReadSql.clause(tokens.slice(expressions)), context, 'a policy')
538
532
  declareObject(out, 'policy', `${table}.${name}`, line)
539
533
  }
540
534
 
@@ -643,7 +637,7 @@ function alterClause(clause: readonly SqlToken[], table: string, context: Contex
643
637
  const rest = clause.slice(actionAt + columnAction.length)
644
638
  // A default persists in the schema; `TYPE … USING` runs once over the rows, as a backfill does.
645
639
  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')
640
+ else if (columnAction[0] === 'TYPE' || columnAction[1] === 'DATA') checkQuery(ReadSql.clause(rest), context, 'ALTER TABLE … USING')
647
641
  return
648
642
  }
649
643
  throw new Refused(`ALTER TABLE … ${action ?? 'an action'}`, line)
@@ -916,26 +910,46 @@ function adoptedTableNames(tokens: readonly SqlToken[]): ReadonlySet<string> {
916
910
 
917
911
  /**
918
912
  * `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.
913
+ * calls of a framework function an application migration makes, each a statement of its own. Answers the function and
914
+ * the collection, or `undefined` for any other statement.
920
915
  */
921
- function isFileAdoptionCall(tokens: readonly SqlToken[]): boolean {
916
+ function fileAdoptionCall(tokens: readonly SqlToken[]): { readonly called: string; readonly collection: string } | undefined {
922
917
  const [select, name, open, collection, close] = tokens
923
918
  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, ')')
919
+ const value = collection?.kind === 'string' ? collection.text : undefined
920
+ const matches = tokens.length === 5 && upperWord(select) === 'SELECT' && (called === FILES_COPY_FUNCTION || called === FILES_RELEASE_FUNCTION)
921
+ && isPunct(open, '(') && value !== undefined && /^[a-z_][a-z0-9_]*$/.test(value) && isPunct(close, ')')
922
+ return matches ? { called, collection: value } : undefined
923
+ }
924
+
925
+ /** The adoption an `INSERT … SELECT` from collection tables makes: each collection's files into the target table. */
926
+ function adoptionSteps(tokens: readonly SqlToken[], adopted: ReadonlySet<string>): AdoptionStep[] {
927
+ // `checkQuery` refused a schema other than the application's, so a qualified target is its own table.
928
+ const table = objectNameAt(tokens, skipWords(tokens, 1, 'INTO'))?.name
929
+ const line = tokens[0]?.line ?? 1
930
+ if (table === undefined) return []
931
+ return [...adopted].sort().map((name) => ({ step: 'adopt', collection: name.slice(FILE_TABLE_PREFIX.length), table, line }))
927
932
  }
928
933
 
929
934
  function classifyStatement(tokens: readonly SqlToken[], context: Context, out: Collected): void {
930
935
  const line = tokens[0]?.line ?? 1
931
936
  const unicode = unicodeIdentifier(tokens)
932
937
  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)])
938
+ const call = context.framework ? undefined : fileAdoptionCall(tokens)
939
+ if (call !== undefined) {
940
+ if (call.called === FILES_RELEASE_FUNCTION) out.adoptions.push({ step: 'release', collection: call.collection, line: tokens[0]?.line ?? 1 })
941
+ return
942
+ }
943
+ const adopted = adoptedTableNames(tokens)
944
+ const allowed = new Set([...fileTableNames(tokens), ...adopted])
935
945
  const framework = context.framework ? undefined : frameworkReference(withoutFileReferences(tokens), allowed)
936
946
  if (framework !== undefined) throw new Refused(`a reference to the framework's ${framework.name}`, framework.line)
937
947
  const first = upperWord(tokens[0])
938
- if (first === 'INSERT' || first === 'UPDATE' || first === 'DELETE') return checkQuery(tokens, context, first)
948
+ if (first === 'INSERT' || first === 'UPDATE' || first === 'DELETE') {
949
+ checkQuery(ReadSql.query(tokens), context, first)
950
+ if (!context.framework) out.adoptions.push(...adoptionSteps(tokens, adopted))
951
+ return
952
+ }
939
953
  if (first === 'COMMENT' && upperWord(tokens[1]) === 'ON') return classifyComment(tokens, context)
940
954
  if (first === 'DO') return classifyDo(tokens, context, out)
941
955
  if (first === 'CREATE') return classifyCreate(tokens, context, out)
@@ -967,6 +981,7 @@ export function classifyMigration(sql: string, schema: string, options: Classify
967
981
  const context: Context = { schema, functions: options.functions ?? new Set(), framework: options.framework === true, doBlocks: 0 }
968
982
  const refused: MigrationRefusal[] = []
969
983
  const deviations: MigrationDeviation[] = []
984
+ const adoptions: FileAdoption[] = []
970
985
  const changes: ManifestChange[] = []
971
986
  const keys = new Set<string>()
972
987
  const { unterminated } = lexSql(sql)
@@ -974,7 +989,7 @@ export function classifyMigration(sql: string, schema: string, options: Classify
974
989
  refused.push({ reason: 'a literal, a quoted name or a comment that never closes', file: options.file, line: unterminated })
975
990
  }
976
991
  for (const { tokens, line } of topLevelStatements(sql)) {
977
- const out: Collected = { deviations: [], changes: [] }
992
+ const out: Collected = { deviations: [], adoptions: [], changes: [] }
978
993
  try {
979
994
  classifyStatement(tokens, context, out)
980
995
  } catch (error) {
@@ -988,10 +1003,11 @@ export function classifyMigration(sql: string, schema: string, options: Classify
988
1003
  keys.add(key)
989
1004
  deviations.push({ ...deviation, file: options.file })
990
1005
  }
1006
+ adoptions.push(...out.adoptions.map((step) => ({ ...step, file: options.file })))
991
1007
  changes.push(...out.changes)
992
1008
  }
993
1009
  const objects = changes.flatMap((change) => (change.change === 'create' || change.change === 'create routine' ? [change.object] : []))
994
- return { file: options.file, refused, deviations, objects, changes }
1010
+ return { file: options.file, refused, deviations, adoptions, objects, changes }
995
1011
  }
996
1012
 
997
1013
  /** The names of the functions and procedures a migration creates or renames to in `schema`, read without classifying them. */
@@ -165,9 +165,14 @@ export interface Statement {
165
165
  * makes a check stricter.
166
166
  */
167
167
  export function topLevelStatements(sql: string): Statement[] {
168
+ return statementsOf(sqlTokens(sql))
169
+ }
170
+
171
+ /** Splits lexed text into its statements at every `;` token: `topLevelStatements` over any lexer's tokens. */
172
+ export function statementsOf(all: readonly SqlToken[]): Statement[] {
168
173
  const statements: Statement[] = []
169
174
  let tokens: SqlToken[] = []
170
- for (const token of sqlTokens(sql)) {
175
+ for (const token of all) {
171
176
  if (token.kind === 'punct' && token.char === ';') {
172
177
  if (tokens[0] !== undefined) statements.push({ tokens, line: tokens[0].line })
173
178
  tokens = []