@fabrika/platform-node 0.9.0-dev.12 → 0.9.0-dev.13

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.12",
3
+ "version": "0.9.0-dev.13",
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.12"
41
+ "@fabrika/platform": "0.9.0-dev.13"
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, DML on every table but the ledger, EXECUTE on the schema's
50
- * routines and USAGE on its types. One transaction, so a live runtime never sees a gap. Then the effective privileges
51
- * are verified, PUBLIC included, and anything beyond that stops the deploy.
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, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA ${schema} TO ${role}`),
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
  }
@@ -18,6 +18,7 @@ import {
18
18
  closingParenthesis,
19
19
  CTE_FORM,
20
20
  ddlForeignSchema,
21
+ dmlRelations,
21
22
  frameworkReference,
22
23
  functionUse,
23
24
  isFrameworkName,
@@ -37,6 +38,7 @@ import {
37
38
  statementKind,
38
39
  unicodeIdentifier,
39
40
  wordAtDepthZero,
41
+ writeTargets,
40
42
  } from './sql-names'
41
43
 
42
44
  /** A database object a migration declares, named as the catalog check names it (`trigger deals.audit`). */
@@ -113,6 +115,16 @@ export interface ClassifyMigrationOptions {
113
115
  readonly functions?: ReadonlySet<string>
114
116
  /** The framework's own bundle, which alone may name the framework's `fabrika_*` tables. */
115
117
  readonly framework?: boolean
118
+ /** The application's access tables, lowercased (`accessTables` of `@fabrika/db/tables`): no stored code writes one. */
119
+ readonly accessTables?: ReadonlySet<string>
120
+ /** The views the migration set declares over an access table, lowercased (`accessViews`): written like one. */
121
+ readonly accessViews?: ReadonlySet<string>
122
+ }
123
+
124
+ /** What the whole migration set is classified against besides its schema. */
125
+ export interface ClassifyMigrationsOptions {
126
+ /** The application's access tables, lowercased (`accessTables` of `@fabrika/db/tables`): no stored code writes one. */
127
+ readonly accessTables?: ReadonlySet<string>
116
128
  }
117
129
 
118
130
  export interface MigrationFile {
@@ -211,6 +223,8 @@ interface Context {
211
223
  readonly schema: string
212
224
  readonly functions: ReadonlySet<string>
213
225
  readonly framework: boolean
226
+ readonly accessTables: ReadonlySet<string>
227
+ readonly accessViews: ReadonlySet<string>
214
228
  doBlocks: number
215
229
  }
216
230
 
@@ -251,6 +265,34 @@ function refuseForeignDdl(tokens: readonly SqlToken[], context: Context, label:
251
265
  if (reached !== undefined) throw new Refused(`${label} naming the schema ${reached}`, tokens[0]?.line ?? 1)
252
266
  }
253
267
 
268
+ /**
269
+ * Access tables are written only by the platform: the data layer bounds who writes a row that hands out access. A
270
+ * function body or a rule action runs again after the migration, so neither may write one; a `DO` block runs once.
271
+ */
272
+ function refuseAccessWrite(tokens: readonly SqlToken[], context: Context, label: string): void {
273
+ for (const target of writeTargets(tokens)) {
274
+ const name = target.name.toLowerCase()
275
+ if (context.accessTables.has(name)) throw new Refused(`a write of the access table ${name} in ${label}`, target.line)
276
+ if (context.accessViews.has(name)) throw new Refused(`a write of the view ${name} over an access table in ${label}`, target.line)
277
+ }
278
+ }
279
+
280
+ /** `access table <name>` or `view <name> over an access table` when `name` is one, else `undefined`. */
281
+ function accessRelation(name: string, context: Context): string | undefined {
282
+ const lower = name.toLowerCase()
283
+ if (context.accessTables.has(lower)) return `the access table ${lower}`
284
+ if (context.accessViews.has(lower)) return `the view ${lower} over an access table`
285
+ return undefined
286
+ }
287
+
288
+ /** Renaming a relation to an access table's name, or to a view's over one, would bind its code and views to it. */
289
+ function refuseAccessRename(from: string, to: string, context: Context, line: number): void {
290
+ const target = to.toLowerCase()
291
+ const isView = context.accessViews.has(target) && !context.accessViews.has(from.toLowerCase())
292
+ const access = context.accessTables.has(target) || isView ? accessRelation(target, context) : undefined
293
+ if (access !== undefined) throw new Refused(`a rename of ${from.toLowerCase()} to ${access}`, line)
294
+ }
295
+
254
296
  /**
255
297
  * A query, a condition or a backfill, read as one (`ReadSql`): no schema but the application's, only allowlisted calls
256
298
  * and nested statements, and no CTE list it cannot read.
@@ -415,6 +457,7 @@ function createFunction(tokens: readonly SqlToken[], at: number, kind: 'function
415
457
  const args = tokens.slice(named + 1, close)
416
458
  checkQuery(ReadSql.clause(args), context, 'an argument default')
417
459
  checkBody(body, context)
460
+ refuseAccessWrite(body, context, `a ${kind} body`)
418
461
  deviate(out, kind, name, line)
419
462
  out.changes.push({ change: 'create routine', object: { kind, name }, args: `${kind} (${argumentText(args)})`, line })
420
463
  }
@@ -448,6 +491,13 @@ function createTrigger(tokens: readonly SqlToken[], at: number, context: Context
448
491
  const on = wordAtDepthZero(tokens, 'ON', at + 1)
449
492
  if (name === undefined || on === undefined) throw new Refused('CREATE TRIGGER', line)
450
493
  const table = ownName(tokens, on + 1, context, 'CREATE TRIGGER')
494
+ // A BEFORE or INSTEAD OF trigger changes or replaces the row an access table stores without any write; an AFTER
495
+ // trigger can only refuse the statement, and stays a deviation.
496
+ const timing = tokens.slice(at + 1, on).map((token) => upperWord(token)).find((word) => word === 'BEFORE' || word === 'INSTEAD')
497
+ const access = accessRelation(table, context)
498
+ if (timing !== undefined && access !== undefined) {
499
+ throw new Refused(`${timing === 'BEFORE' ? 'a BEFORE' : 'an INSTEAD OF'} trigger on ${access}`, line)
500
+ }
451
501
  const when = wordAtDepthZero(tokens, 'WHEN', on)
452
502
  const whenClose = when === undefined || !isPunct(tokens[when + 1], '(') ? undefined : closingParenthesis(tokens, when + 1)
453
503
  const header = when === undefined || whenClose === undefined ? tokens : [...tokens.slice(0, when), ...tokens.slice(whenClose + 1)]
@@ -506,14 +556,21 @@ function createRule(tokens: readonly SqlToken[], at: number, context: Context, o
506
556
  const doIndex = to === undefined ? undefined : wordAtDepthZero(tokens, 'DO', to)
507
557
  if (name === undefined || to === undefined || doIndex === undefined) throw new Refused('CREATE RULE', line)
508
558
  const table = ownName(tokens, to + 1, context, 'CREATE RULE')
559
+ const access = accessRelation(table, context)
560
+ if (access !== undefined) throw new Refused(`a rule on ${access}`, line)
509
561
  const where = wordAtDepthZero(tokens, 'WHERE', to)
510
562
  const headerEnd = where !== undefined && where < doIndex ? where : doIndex
511
563
  refuseForeignDdl(tokens.slice(0, headerEnd), context, 'CREATE RULE')
512
564
  let action = skipWords(tokens, skipWords(tokens, doIndex + 1, 'ALSO'), 'INSTEAD')
513
- if (isPunct(tokens[action], '(')) action++
565
+ if (isPunct(tokens[action], '(')) {
566
+ // The statement splitter cuts `(a; b)` at its `;`, so the actions after the first would be read as statements of their own.
567
+ if (closingParenthesis(tokens, action) === undefined) throw new Refused('a rule with several actions; write one rule per action', line)
568
+ action++
569
+ }
514
570
  const first = upperWord(tokens[action])
515
571
  if (first === undefined || !RULE_ACTIONS.has(first)) throw new Refused(`${first ?? statementKind(tokens.slice(action))} in a rule action`, line)
516
572
  checkQuery(ReadSql.clause(tokens.slice(headerEnd)), context, 'a rule')
573
+ refuseAccessWrite(tokens.slice(action), context, 'a rule action')
517
574
  declareObject(out, 'rule', `${table}.${name}`, line)
518
575
  }
519
576
 
@@ -655,7 +712,10 @@ function alterTable(tokens: readonly SqlToken[], context: Context, out: Collecte
655
712
  // RENAME TO, RENAME [COLUMN] a TO b and RENAME CONSTRAINT a TO b each stand alone.
656
713
  if (upperWord(rest[0]) === 'RENAME') {
657
714
  const to = upperWord(rest[1]) === 'TO' ? nameText(rest[2]) : undefined
658
- if (to !== undefined) out.changes.push({ change: 'rename table', from: table, to })
715
+ if (to !== undefined) {
716
+ refuseAccessRename(table, to, context, line)
717
+ out.changes.push({ change: 'rename table', from: table, to })
718
+ }
659
719
  return
660
720
  }
661
721
  for (const clause of splitAtCommas(rest)) alterClause(clause, table, context, out)
@@ -726,6 +786,7 @@ function alterRename(tokens: readonly SqlToken[], context: Context, out: Collect
726
786
  deviate(out, kinds[0] ?? 'trigger', renamed, line)
727
787
  return
728
788
  }
789
+ if (kind === 'VIEW') refuseAccessRename(name, target, context, line)
729
790
  for (const objectKind of kinds) {
730
791
  if (objectKind === 'function' || objectKind === 'procedure') refuseShadowing(target, objectKind, line)
731
792
  out.changes.push({ change: 'rename', from: { kind: objectKind, name }, to: { kind: objectKind, name: target } })
@@ -978,7 +1039,14 @@ function classifyStatement(tokens: readonly SqlToken[], context: Context, out: C
978
1039
  * `SET`/`RESET` are refused for every plan before this runs (`refusedStatement`).
979
1040
  */
980
1041
  export function classifyMigration(sql: string, schema: string, options: ClassifyMigrationOptions): MigrationClassification {
981
- const context: Context = { schema, functions: options.functions ?? new Set(), framework: options.framework === true, doBlocks: 0 }
1042
+ const context: Context = {
1043
+ schema,
1044
+ functions: options.functions ?? new Set(),
1045
+ framework: options.framework === true,
1046
+ accessTables: options.accessTables ?? new Set(),
1047
+ accessViews: options.accessViews ?? new Set(),
1048
+ doBlocks: 0,
1049
+ }
982
1050
  const refused: MigrationRefusal[] = []
983
1051
  const deviations: MigrationDeviation[] = []
984
1052
  const adoptions: FileAdoption[] = []
@@ -1010,6 +1078,54 @@ export function classifyMigration(sql: string, schema: string, options: Classify
1010
1078
  return { file: options.file, refused, deviations, adoptions, objects, changes }
1011
1079
  }
1012
1080
 
1081
+ /**
1082
+ * Every view the migration set declares over an access table, lowercased: one whose query names an access table or such
1083
+ * a view, and the names those views are renamed to. A rule action writes through a view with its owner's privileges.
1084
+ * Read across the whole set and in no order, so a view counts whichever file creates or renames it.
1085
+ */
1086
+ function accessViews(files: readonly MigrationFile[], schema: string, accessTables: ReadonlySet<string>): ReadonlySet<string> {
1087
+ const views: { readonly name: string; readonly reads: readonly string[] }[] = []
1088
+ const renames: { readonly from: string; readonly to: string }[] = []
1089
+ for (const file of files) {
1090
+ for (const { tokens } of topLevelStatements(file.sql)) {
1091
+ const first = upperWord(tokens[0])
1092
+ if (first === 'CREATE') {
1093
+ const at = skipWords(tokens, skipWords(tokens, skipWords(tokens, skipWords(tokens, 1, 'OR', 'REPLACE'), 'TEMP'), 'TEMPORARY'), 'RECURSIVE')
1094
+ if (upperWord(tokens[at]) !== 'VIEW') continue
1095
+ const named = skipWords(tokens, at + 1, 'IF', 'NOT', 'EXISTS')
1096
+ const object = objectNameAt(tokens, named)
1097
+ const as = wordAtDepthZero(tokens, 'AS', named)
1098
+ if (object === undefined || (object.qualifier !== undefined && object.qualifier !== schema) || as === undefined) continue
1099
+ const reads = dmlRelations(ReadSql.query(viewQuery(tokens.slice(as + 1)))).map((reference) => reference.name.toLowerCase())
1100
+ views.push({ name: object.name.toLowerCase(), reads })
1101
+ } else if (first === 'ALTER' && (upperWord(tokens[1]) === 'VIEW' || upperWord(tokens[1]) === 'TABLE')) {
1102
+ const from = objectNameAt(tokens, skipWords(tokens, 2, 'IF', 'EXISTS'))
1103
+ const rename = tokens.findIndex((token, index) => upperWord(token) === 'RENAME' && upperWord(tokens[index + 1]) === 'TO')
1104
+ const to = rename === -1 ? undefined : nameText(tokens[rename + 2])
1105
+ if (from !== undefined && to !== undefined) renames.push({ from: from.name.toLowerCase(), to: to.toLowerCase() })
1106
+ }
1107
+ }
1108
+ }
1109
+ const reached = new Set(accessTables)
1110
+ const found = new Set<string>()
1111
+ for (let grown = true; grown;) {
1112
+ grown = false
1113
+ for (const view of views) {
1114
+ if (reached.has(view.name) || !view.reads.some((read) => reached.has(read))) continue
1115
+ reached.add(view.name)
1116
+ found.add(view.name)
1117
+ grown = true
1118
+ }
1119
+ for (const rename of renames) {
1120
+ if (!found.has(rename.from) || reached.has(rename.to)) continue
1121
+ reached.add(rename.to)
1122
+ found.add(rename.to)
1123
+ grown = true
1124
+ }
1125
+ }
1126
+ return found
1127
+ }
1128
+
1013
1129
  /** The names of the functions and procedures a migration creates or renames to in `schema`, read without classifying them. */
1014
1130
  export function declaredFunctions(sql: string, schema: string): string[] {
1015
1131
  const names: string[] = []
@@ -1069,9 +1185,18 @@ export function migrationManifest(classifications: readonly MigrationClassificat
1069
1185
  * Classifies a whole migration set in order. A body or an expression may call a function any file of the set
1070
1186
  * declares; the manifest is what the catalog check admits.
1071
1187
  */
1072
- export function classifyMigrations(files: readonly MigrationFile[], schema: string): MigrationSetClassification {
1188
+ export function classifyMigrations(
1189
+ files: readonly MigrationFile[],
1190
+ schema: string,
1191
+ options: ClassifyMigrationsOptions = {},
1192
+ ): MigrationSetClassification {
1073
1193
  const functions = new Set(files.flatMap((file) => declaredFunctions(file.sql, schema)))
1074
- const classified = files.map((file) => classifyMigration(file.sql, schema, { file: file.name, functions, framework: file.framework === true }))
1194
+ const access = options.accessTables === undefined
1195
+ ? {}
1196
+ : { accessTables: options.accessTables, accessViews: accessViews(files, schema, options.accessTables) }
1197
+ const classified = files.map((file) =>
1198
+ classifyMigration(file.sql, schema, { file: file.name, functions, framework: file.framework === true, ...access })
1199
+ )
1075
1200
  const withOverloads = refuseOverloads(classified)
1076
1201
  return { files: withOverloads, objects: migrationManifest(withOverloads) }
1077
1202
  }
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,6 +18,7 @@ export {
18
18
  classifyMigration,
19
19
  type ClassifyMigrationOptions,
20
20
  classifyMigrations,
21
+ type ClassifyMigrationsOptions,
21
22
  type DatabaseObject,
22
23
  type DatabaseObjectKind,
23
24
  declaredFunctions,
@@ -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, DML on every table but the ledger, EXECUTE on the schema's
16
- * routines and USAGE on its types. One transaction, so a live runtime never sees a gap. Then the effective privileges
17
- * are verified, PUBLIC included, and anything beyond that stops the deploy.
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>;
@@ -84,6 +84,15 @@ export interface ClassifyMigrationOptions {
84
84
  readonly functions?: ReadonlySet<string>;
85
85
  /** The framework's own bundle, which alone may name the framework's `fabrika_*` tables. */
86
86
  readonly framework?: boolean;
87
+ /** The application's access tables, lowercased (`accessTables` of `@fabrika/db/tables`): no stored code writes one. */
88
+ readonly accessTables?: ReadonlySet<string>;
89
+ /** The views the migration set declares over an access table, lowercased (`accessViews`): written like one. */
90
+ readonly accessViews?: ReadonlySet<string>;
91
+ }
92
+ /** What the whole migration set is classified against besides its schema. */
93
+ export interface ClassifyMigrationsOptions {
94
+ /** The application's access tables, lowercased (`accessTables` of `@fabrika/db/tables`): no stored code writes one. */
95
+ readonly accessTables?: ReadonlySet<string>;
87
96
  }
88
97
  export interface MigrationFile {
89
98
  readonly name: string;
@@ -121,4 +130,4 @@ export declare function migrationManifest(classifications: readonly MigrationCla
121
130
  * Classifies a whole migration set in order. A body or an expression may call a function any file of the set
122
131
  * declares; the manifest is what the catalog check admits.
123
132
  */
124
- export declare function classifyMigrations(files: readonly MigrationFile[], schema: string): MigrationSetClassification;
133
+ export declare function classifyMigrations(files: readonly MigrationFile[], schema: string, options?: ClassifyMigrationsOptions): MigrationSetClassification;
@@ -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
  /**
@@ -1,6 +1,6 @@
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, declaredFunctions, type DeviationKind, type FileAdoption, type ManifestChange, type MigrationClassification, type MigrationDeviation, 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';