@fabrika/platform-node 0.9.0-cloudflare.3 → 0.9.0-dev.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/src/migration-classify.ts +34 -56
- package/src/sql-names.ts +421 -25
- package/src/sql.ts +7 -2
- package/types/src/sql-names.d.ts +54 -11
- package/types/src/sql.d.ts +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fabrika/platform-node",
|
|
3
|
-
"version": "0.9.0-
|
|
3
|
+
"version": "0.9.0-dev.10",
|
|
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-
|
|
41
|
+
"@fabrika/platform": "0.9.0-dev.10"
|
|
42
42
|
}
|
|
43
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
|
-
|
|
31
|
+
ReadBody,
|
|
32
|
+
ReadSql,
|
|
33
|
+
referencedForeignSchema,
|
|
34
|
+
refusedCall,
|
|
32
35
|
skipWords,
|
|
33
36
|
splitAtCommas,
|
|
34
37
|
statementKind,
|
|
@@ -248,21 +251,27 @@ function refuseForeignDdl(tokens: readonly SqlToken[], context: Context, label:
|
|
|
248
251
|
if (reached !== undefined) throw new Refused(`${label} naming the schema ${reached}`, tokens[0]?.line ?? 1)
|
|
249
252
|
}
|
|
250
253
|
|
|
251
|
-
/**
|
|
252
|
-
|
|
253
|
-
|
|
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)
|
|
254
262
|
if (nested !== undefined) throw new Refused(`${nested.statement} nested in a statement`, nested.line)
|
|
255
263
|
const target = parenthesizedTarget(tokens)
|
|
256
264
|
if (target !== undefined) throw new Refused(`a parenthesized ${target.statement} target`, target.line)
|
|
257
|
-
const
|
|
265
|
+
const references = nameReferences(read)
|
|
266
|
+
const reached = referencedForeignSchema(references, context.schema)
|
|
258
267
|
if (reached !== undefined) throw new Refused(`${label} reaching the schema ${reached}`, tokens[0]?.line ?? 1)
|
|
259
|
-
const call =
|
|
268
|
+
const call = refusedCall(references, context.schema, context.functions)
|
|
260
269
|
if (call !== undefined) throw new Refused(`a call of ${call.name}`, call.line)
|
|
261
270
|
}
|
|
262
271
|
|
|
263
272
|
/** A stored expression's calls: a paved built-in is plain, a reviewed or declared function a deviation, anything else refused. */
|
|
264
273
|
function checkExpression(tokens: readonly SqlToken[], where: string, context: Context, out: Collected): void {
|
|
265
|
-
for (const reference of nameReferences(tokens)) {
|
|
274
|
+
for (const reference of nameReferences(ReadSql.expression(tokens))) {
|
|
266
275
|
if (reference.role !== 'call') continue
|
|
267
276
|
const use = functionUse(reference, context.schema, context.functions)
|
|
268
277
|
if (use === undefined) throw new Refused(`a call of ${reference.name}`, reference.line)
|
|
@@ -286,48 +295,16 @@ function isAssignment(tokens: readonly SqlToken[], index: number): boolean {
|
|
|
286
295
|
}
|
|
287
296
|
|
|
288
297
|
/**
|
|
289
|
-
* The first statement of a function or `DO` body that does not begin with an allowlisted word or an
|
|
290
|
-
* declaration section
|
|
291
|
-
* `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.
|
|
292
300
|
*/
|
|
293
|
-
function refusedBodyStatement(tokens:
|
|
294
|
-
|
|
295
|
-
let declaring = false
|
|
296
|
-
const cases: ('statement' | 'expression')[] = []
|
|
297
|
-
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) {
|
|
298
303
|
const token = tokens[index]
|
|
299
304
|
const word = upperWord(token)
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
if (isPunct(token, '<') && isPunct(tokens[index + 1], '<')) {
|
|
304
|
-
while (index < tokens.length && !(isPunct(tokens[index], '>') && isPunct(tokens[index + 1], '>'))) index++
|
|
305
|
-
index++
|
|
306
|
-
start = true
|
|
307
|
-
continue
|
|
308
|
-
}
|
|
309
|
-
const allowed = (declaring && word !== 'BEGIN') || (word !== undefined && BODY_STATEMENTS.has(word))
|
|
310
|
-
|| (isName(token) && isAssignment(tokens, index))
|
|
311
|
-
if (!allowed) return { statement: word ?? statementKind(tokens.slice(index)), line: token?.line ?? 1 }
|
|
312
|
-
if (word === 'CASE') {
|
|
313
|
-
cases.push('statement')
|
|
314
|
-
continue
|
|
315
|
-
}
|
|
316
|
-
} else if (word === 'CASE') {
|
|
317
|
-
cases.push('expression')
|
|
318
|
-
continue
|
|
319
|
-
}
|
|
320
|
-
const innermost = cases[cases.length - 1]
|
|
321
|
-
if (word === 'DECLARE') declaring = true
|
|
322
|
-
if (word === 'BEGIN') declaring = false
|
|
323
|
-
if (isPunct(token, ';') || word === 'BEGIN' || word === 'DECLARE') start = true
|
|
324
|
-
else if (word === 'LOOP') start = upperWord(tokens[index - 1]) !== 'END'
|
|
325
|
-
else if (word === 'THEN' || word === 'ELSE') start = innermost !== 'expression'
|
|
326
|
-
else if (word === 'END' && innermost === 'expression') cases.pop()
|
|
327
|
-
else if (word === 'END' && upperWord(tokens[index + 1]) === 'CASE') {
|
|
328
|
-
cases.pop()
|
|
329
|
-
index++
|
|
330
|
-
}
|
|
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 }
|
|
331
308
|
}
|
|
332
309
|
return undefined
|
|
333
310
|
}
|
|
@@ -358,9 +335,10 @@ function checkBody(tokens: readonly SqlToken[], context: Context): void {
|
|
|
358
335
|
if (framework !== undefined) throw new Refused(`a reference to the framework's ${framework.name}`, framework.line)
|
|
359
336
|
const execute = tokens.find((token) => upperWord(token) === 'EXECUTE')
|
|
360
337
|
if (execute !== undefined) throw new Refused('a dynamic EXECUTE in a body', execute.line)
|
|
361
|
-
const
|
|
338
|
+
const read = ReadBody.of(tokens)
|
|
339
|
+
const statement = refusedBodyStatement(read)
|
|
362
340
|
if (statement !== undefined) throw new Refused(`${statement.statement} in a body`, statement.line)
|
|
363
|
-
checkQuery(
|
|
341
|
+
checkQuery(read, context, 'a body')
|
|
364
342
|
refuseForeignDdl(declarations(tokens), context, 'a declaration')
|
|
365
343
|
}
|
|
366
344
|
|
|
@@ -435,7 +413,7 @@ function createFunction(tokens: readonly SqlToken[], at: number, kind: 'function
|
|
|
435
413
|
refuseForeignDdl(header, context, label)
|
|
436
414
|
// An argument default runs at every call that omits the argument, so it is a query like the body.
|
|
437
415
|
const args = tokens.slice(named + 1, close)
|
|
438
|
-
checkQuery(args, context, 'an argument default')
|
|
416
|
+
checkQuery(ReadSql.clause(args), context, 'an argument default')
|
|
439
417
|
checkBody(body, context)
|
|
440
418
|
deviate(out, kind, name, line)
|
|
441
419
|
out.changes.push({ change: 'create routine', object: { kind, name }, args: `${kind} (${argumentText(args)})`, line })
|
|
@@ -474,7 +452,7 @@ function createTrigger(tokens: readonly SqlToken[], at: number, context: Context
|
|
|
474
452
|
const whenClose = when === undefined || !isPunct(tokens[when + 1], '(') ? undefined : closingParenthesis(tokens, when + 1)
|
|
475
453
|
const header = when === undefined || whenClose === undefined ? tokens : [...tokens.slice(0, when), ...tokens.slice(whenClose + 1)]
|
|
476
454
|
refuseForeignDdl(header, context, 'CREATE TRIGGER')
|
|
477
|
-
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')
|
|
478
456
|
const execute = wordAtDepthZero(tokens, 'EXECUTE', on)
|
|
479
457
|
const fn = execute === undefined ? undefined : objectNameAt(tokens, execute + 2)
|
|
480
458
|
if (execute === undefined || fn === undefined) throw new Refused('CREATE TRIGGER without EXECUTE FUNCTION', line)
|
|
@@ -516,7 +494,7 @@ function createView(tokens: readonly SqlToken[], at: number, kind: 'view' | 'mat
|
|
|
516
494
|
if (!(first === 'SELECT' || first === 'WITH' || first === 'VALUES' || isPunct(query[0], '('))) {
|
|
517
495
|
throw new Refused(`${label} … AS ${statementKind(query)}`, line)
|
|
518
496
|
}
|
|
519
|
-
checkQuery(query, context, 'a view')
|
|
497
|
+
checkQuery(ReadSql.query(query), context, 'a view')
|
|
520
498
|
declareObject(out, kind, name, line)
|
|
521
499
|
}
|
|
522
500
|
|
|
@@ -535,7 +513,7 @@ function createRule(tokens: readonly SqlToken[], at: number, context: Context, o
|
|
|
535
513
|
if (isPunct(tokens[action], '(')) action++
|
|
536
514
|
const first = upperWord(tokens[action])
|
|
537
515
|
if (first === undefined || !RULE_ACTIONS.has(first)) throw new Refused(`${first ?? statementKind(tokens.slice(action))} in a rule action`, line)
|
|
538
|
-
checkQuery(tokens.slice(headerEnd), context, 'a rule')
|
|
516
|
+
checkQuery(ReadSql.clause(tokens.slice(headerEnd)), context, 'a rule')
|
|
539
517
|
declareObject(out, 'rule', `${table}.${name}`, line)
|
|
540
518
|
}
|
|
541
519
|
|
|
@@ -550,7 +528,7 @@ function createPolicy(tokens: readonly SqlToken[], at: number, context: Context,
|
|
|
550
528
|
const starts = [using, withCheck].filter((index) => index !== undefined)
|
|
551
529
|
const expressions = starts.length === 0 ? tokens.length : Math.min(...starts)
|
|
552
530
|
refuseForeignDdl(tokens.slice(0, expressions), context, 'CREATE POLICY')
|
|
553
|
-
checkQuery(tokens.slice(expressions), context, 'a policy')
|
|
531
|
+
checkQuery(ReadSql.clause(tokens.slice(expressions)), context, 'a policy')
|
|
554
532
|
declareObject(out, 'policy', `${table}.${name}`, line)
|
|
555
533
|
}
|
|
556
534
|
|
|
@@ -659,7 +637,7 @@ function alterClause(clause: readonly SqlToken[], table: string, context: Contex
|
|
|
659
637
|
const rest = clause.slice(actionAt + columnAction.length)
|
|
660
638
|
// A default persists in the schema; `TYPE … USING` runs once over the rows, as a backfill does.
|
|
661
639
|
if (columnAction[1] === 'DEFAULT' && columnAction[0] === 'SET') checkExpression(rest, `${table}.${column}`, context, out)
|
|
662
|
-
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')
|
|
663
641
|
return
|
|
664
642
|
}
|
|
665
643
|
throw new Refused(`ALTER TABLE … ${action ?? 'an action'}`, line)
|
|
@@ -968,7 +946,7 @@ function classifyStatement(tokens: readonly SqlToken[], context: Context, out: C
|
|
|
968
946
|
if (framework !== undefined) throw new Refused(`a reference to the framework's ${framework.name}`, framework.line)
|
|
969
947
|
const first = upperWord(tokens[0])
|
|
970
948
|
if (first === 'INSERT' || first === 'UPDATE' || first === 'DELETE') {
|
|
971
|
-
checkQuery(tokens, context, first)
|
|
949
|
+
checkQuery(ReadSql.query(tokens), context, first)
|
|
972
950
|
if (!context.framework) out.adoptions.push(...adoptionSteps(tokens, adopted))
|
|
973
951
|
return
|
|
974
952
|
}
|
package/src/sql-names.ts
CHANGED
|
@@ -276,10 +276,12 @@ type RelationSlot = 'columns' | 'function' | 'list' | undefined
|
|
|
276
276
|
/**
|
|
277
277
|
* Every name of a DML statement, a query or an expression, with its role. A name in a relation position (after
|
|
278
278
|
* `FROM`, `JOIN`, `USING`, `INTO`, `UPDATE`, `TABLE`, `REFERENCES`, or a `,` of a `FROM` list) is a relation; a name
|
|
279
|
-
* that `(` follows is a call, unless it is syntax
|
|
280
|
-
*
|
|
279
|
+
* that `(` follows is a call, unless it is syntax, a type with a modifier or a CTE's name before its column list
|
|
280
|
+
* (`WITH RECURSIVE tree (id, depth) AS`); a name after `::` or `AS` is a type. A two-part name anywhere else is a
|
|
281
|
+
* column of a table or an alias (`d.note`, `NEW.stage`).
|
|
281
282
|
*/
|
|
282
|
-
export function nameReferences(
|
|
283
|
+
export function nameReferences(read: ReadSql): NameReference[] {
|
|
284
|
+
const { tokens, ctes } = read
|
|
283
285
|
const references: NameReference[] = []
|
|
284
286
|
const lists: { fromList: boolean; opener: string | undefined }[] = [{ fromList: false, opener: undefined }]
|
|
285
287
|
let slot: RelationSlot
|
|
@@ -367,7 +369,7 @@ export function nameReferences(tokens: readonly SqlToken[]): NameReference[] {
|
|
|
367
369
|
let role: NameRole = 'other'
|
|
368
370
|
if (castTarget || typedLiteral) role = 'type'
|
|
369
371
|
else if (percentType) role = 'relation'
|
|
370
|
-
else if (followedByParenthesis && !syntax && inSlot !== 'columns') role = 'call'
|
|
372
|
+
else if (followedByParenthesis && !syntax && inSlot !== 'columns' && !ctes.names.has(index)) role = 'call'
|
|
371
373
|
else if (inSlot !== undefined) role = 'relation'
|
|
372
374
|
references.push({
|
|
373
375
|
qualifier: parts.length > 1 ? parts[0] : undefined,
|
|
@@ -382,12 +384,12 @@ export function nameReferences(tokens: readonly SqlToken[]): NameReference[] {
|
|
|
382
384
|
}
|
|
383
385
|
|
|
384
386
|
/**
|
|
385
|
-
* The first schema a DML statement, a query or a function body
|
|
386
|
-
* qualified relation, call or type, or a three-part name. An unqualified
|
|
387
|
-
* resolves to the catalog and counts as `pg_catalog`.
|
|
387
|
+
* The first schema the `references` of a DML statement, a query or a function body (`nameReferences`) reach other
|
|
388
|
+
* than `schema`, `pg_catalog` included: a qualified relation, call or type, or a three-part name. An unqualified
|
|
389
|
+
* relation whose name starts with `pg_` resolves to the catalog and counts as `pg_catalog`.
|
|
388
390
|
*/
|
|
389
|
-
export function
|
|
390
|
-
for (const reference of
|
|
391
|
+
export function referencedForeignSchema(references: readonly NameReference[], schema: string): string | undefined {
|
|
392
|
+
for (const reference of references) {
|
|
391
393
|
if (reference.qualifier === undefined) {
|
|
392
394
|
if (reference.role === 'relation' && reference.name.startsWith('pg_')) return 'pg_catalog'
|
|
393
395
|
continue
|
|
@@ -450,19 +452,409 @@ const STATEMENT_WORDS: ReadonlySet<string> = new Set([
|
|
|
450
452
|
])
|
|
451
453
|
const NESTED_STATEMENTS: ReadonlySet<string> = new Set(['SELECT', 'VALUES', 'WITH', 'TABLE', 'INSERT', 'UPDATE', 'DELETE'])
|
|
452
454
|
|
|
453
|
-
/**
|
|
454
|
-
|
|
455
|
-
|
|
455
|
+
/**
|
|
456
|
+
* The form of a CTE that a list must take to be read, for a refusal to name: a `CYCLE` mark is a constant, as Postgres
|
|
457
|
+
* requires, never a bound value.
|
|
458
|
+
*/
|
|
459
|
+
export const CTE_FORM =
|
|
460
|
+
'name [(columns)] AS [[NOT] MATERIALIZED] (query) [SEARCH {BREADTH | DEPTH} FIRST BY columns SET column] [CYCLE columns SET column [TO constant DEFAULT constant] USING column]'
|
|
461
|
+
|
|
462
|
+
/** A CTE list: the index of each CTE's name and the token after the list, the statement it ends in. */
|
|
463
|
+
interface CteList {
|
|
464
|
+
readonly names: readonly number[]
|
|
465
|
+
readonly terminal: SqlToken | undefined
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/** Postgres' reserved and type-or-function-name keywords: none names a CTE unquoted (`WITH CHECK OPTION`). */
|
|
469
|
+
const NOT_CTE_NAMES: ReadonlySet<string> = new Set([
|
|
470
|
+
'ALL',
|
|
471
|
+
'ANALYSE',
|
|
472
|
+
'ANALYZE',
|
|
473
|
+
'AND',
|
|
474
|
+
'ANY',
|
|
475
|
+
'ARRAY',
|
|
476
|
+
'AS',
|
|
477
|
+
'ASC',
|
|
478
|
+
'ASYMMETRIC',
|
|
479
|
+
'AUTHORIZATION',
|
|
480
|
+
'BINARY',
|
|
481
|
+
'BOTH',
|
|
482
|
+
'CASE',
|
|
483
|
+
'CAST',
|
|
484
|
+
'CHECK',
|
|
485
|
+
'COLLATE',
|
|
486
|
+
'COLLATION',
|
|
487
|
+
'COLUMN',
|
|
488
|
+
'CONCURRENTLY',
|
|
489
|
+
'CONSTRAINT',
|
|
490
|
+
'CREATE',
|
|
491
|
+
'CROSS',
|
|
492
|
+
'CURRENT_CATALOG',
|
|
493
|
+
'CURRENT_DATE',
|
|
494
|
+
'CURRENT_ROLE',
|
|
495
|
+
'CURRENT_SCHEMA',
|
|
496
|
+
'CURRENT_TIME',
|
|
497
|
+
'CURRENT_TIMESTAMP',
|
|
498
|
+
'CURRENT_USER',
|
|
499
|
+
'DEFAULT',
|
|
500
|
+
'DEFERRABLE',
|
|
501
|
+
'DESC',
|
|
502
|
+
'DISTINCT',
|
|
503
|
+
'DO',
|
|
504
|
+
'ELSE',
|
|
505
|
+
'END',
|
|
506
|
+
'EXCEPT',
|
|
507
|
+
'FALSE',
|
|
508
|
+
'FETCH',
|
|
509
|
+
'FOR',
|
|
510
|
+
'FOREIGN',
|
|
511
|
+
'FREEZE',
|
|
512
|
+
'FROM',
|
|
513
|
+
'FULL',
|
|
514
|
+
'GRANT',
|
|
515
|
+
'GROUP',
|
|
516
|
+
'HAVING',
|
|
517
|
+
'ILIKE',
|
|
518
|
+
'IN',
|
|
519
|
+
'INITIALLY',
|
|
520
|
+
'INNER',
|
|
521
|
+
'INTERSECT',
|
|
522
|
+
'INTO',
|
|
523
|
+
'IS',
|
|
524
|
+
'ISNULL',
|
|
525
|
+
'JOIN',
|
|
526
|
+
'LATERAL',
|
|
527
|
+
'LEADING',
|
|
528
|
+
'LEFT',
|
|
529
|
+
'LIKE',
|
|
530
|
+
'LIMIT',
|
|
531
|
+
'LOCALTIME',
|
|
532
|
+
'LOCALTIMESTAMP',
|
|
533
|
+
'NATURAL',
|
|
534
|
+
'NOT',
|
|
535
|
+
'NOTNULL',
|
|
536
|
+
'NULL',
|
|
537
|
+
'OFFSET',
|
|
538
|
+
'ON',
|
|
539
|
+
'ONLY',
|
|
540
|
+
'OR',
|
|
541
|
+
'ORDER',
|
|
542
|
+
'OUTER',
|
|
543
|
+
'OVERLAPS',
|
|
544
|
+
'PLACING',
|
|
545
|
+
'PRIMARY',
|
|
546
|
+
'REFERENCES',
|
|
547
|
+
'RETURNING',
|
|
548
|
+
'RIGHT',
|
|
549
|
+
'SELECT',
|
|
550
|
+
'SESSION_USER',
|
|
551
|
+
'SIMILAR',
|
|
552
|
+
'SOME',
|
|
553
|
+
'SYMMETRIC',
|
|
554
|
+
'SYSTEM_USER',
|
|
555
|
+
'TABLE',
|
|
556
|
+
'TABLESAMPLE',
|
|
557
|
+
'THEN',
|
|
558
|
+
'TO',
|
|
559
|
+
'TRAILING',
|
|
560
|
+
'TRUE',
|
|
561
|
+
'UNION',
|
|
562
|
+
'UNIQUE',
|
|
563
|
+
'USER',
|
|
564
|
+
'USING',
|
|
565
|
+
'VARIADIC',
|
|
566
|
+
'VERBOSE',
|
|
567
|
+
'WHEN',
|
|
568
|
+
'WHERE',
|
|
569
|
+
'WINDOW',
|
|
570
|
+
'WITH',
|
|
571
|
+
])
|
|
572
|
+
|
|
573
|
+
/** The index of the CTE's name at `index`, or `undefined` when no name a CTE may take is there. */
|
|
574
|
+
function cteName(tokens: readonly SqlToken[], index: number): number | undefined {
|
|
575
|
+
const word = upperWord(tokens[index])
|
|
576
|
+
return isName(tokens[index]) && (word === undefined || !NOT_CTE_NAMES.has(word)) ? index : undefined
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
/** The index past `c, … SET c` at `at`, as a recursive CTE's `SEARCH` and `CYCLE` clauses write it, or `undefined`. */
|
|
580
|
+
function afterColumnsSet(tokens: readonly SqlToken[], at: number): number | undefined {
|
|
581
|
+
let next = at
|
|
582
|
+
while (isName(tokens[next]) && isPunct(tokens[next + 1], ',')) next += 2
|
|
583
|
+
if (!isName(tokens[next]) || upperWord(tokens[next + 1]) !== 'SET' || !isName(tokens[next + 2])) return undefined
|
|
584
|
+
return next + 3
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
const isString = (token: SqlToken | undefined): boolean => token?.kind === 'string' || token?.kind === 'dollar'
|
|
588
|
+
const isDigit = (token: SqlToken | undefined): boolean => token?.kind === 'punct' && /^[0-9.]$/.test(token.char)
|
|
589
|
+
|
|
590
|
+
/** An interval literal's fields (`'1' DAY`, `'1:30' HOUR TO MINUTE`, `'1.5' SECOND(3)`). */
|
|
591
|
+
const INTERVAL_FIELDS: ReadonlySet<string> = new Set(['YEAR', 'MONTH', 'DAY', 'HOUR', 'MINUTE', 'SECOND'])
|
|
592
|
+
|
|
593
|
+
/** The index past the parenthesized group at `at`, or `at` itself when none is there. */
|
|
594
|
+
function afterGroup(tokens: readonly SqlToken[], at: number): number {
|
|
595
|
+
return isPunct(tokens[at], '(') ? (closingParenthesis(tokens, at) ?? tokens.length) + 1 : at
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/**
|
|
599
|
+
* The index past the type name of a typed literal at `at`: a name, qualified or not and no reserved word, and the keyword forms of the
|
|
600
|
+
* standard types (`double precision`, `character varying`, `national char`, `bit varying`, `timestamp(3) with time
|
|
601
|
+
* zone`), each with its modifier or arguments in parentheses, or `undefined`.
|
|
602
|
+
*/
|
|
603
|
+
function afterTypeName(tokens: readonly SqlToken[], at: number): number | undefined {
|
|
604
|
+
const word = upperWord(tokens[at])
|
|
605
|
+
let next = cteName(tokens, at) === undefined ? undefined : afterName(tokens, at)
|
|
606
|
+
if (next === undefined) return undefined
|
|
607
|
+
if (word === 'DOUBLE') next = skipWords(tokens, next, 'PRECISION')
|
|
608
|
+
if (word === 'NATIONAL') next = Math.max(skipWords(tokens, next, 'CHARACTER'), skipWords(tokens, next, 'CHAR'))
|
|
609
|
+
if (word === 'NATIONAL' || word === 'CHARACTER' || word === 'CHAR' || word === 'NCHAR' || word === 'BIT') next = skipWords(tokens, next, 'VARYING')
|
|
610
|
+
next = afterGroup(tokens, next)
|
|
611
|
+
if (word === 'TIMESTAMP' || word === 'TIME') {
|
|
612
|
+
next = Math.max(skipWords(tokens, next, 'WITH', 'TIME', 'ZONE'), skipWords(tokens, next, 'WITHOUT', 'TIME', 'ZONE'))
|
|
613
|
+
}
|
|
614
|
+
return next
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/**
|
|
618
|
+
* The index past a `CYCLE` mark value at `at`, which Postgres takes only as a constant (`AexprConst`): `TRUE`, `FALSE`,
|
|
619
|
+
* `NULL`, a number, a string (`'Y'`, `E'…'`, `$$…$$`, `U&'…' [UESCAPE '…']`), or a typed literal: a type name and a
|
|
620
|
+
* string (`varchar(1) 'Y'`, `func(args) 'lit'`, `timestamp with time zone '…'`, `interval '1' day`). Anything else is
|
|
621
|
+
* `undefined`, so no word but these stands between `TO`, `DEFAULT` and `USING`.
|
|
622
|
+
*/
|
|
623
|
+
function afterMark(tokens: readonly SqlToken[], at: number): number | undefined {
|
|
624
|
+
const word = upperWord(tokens[at])
|
|
625
|
+
if (word === 'TRUE' || word === 'FALSE' || word === 'NULL') return at + 1
|
|
626
|
+
if (isString(tokens[at])) return at + 1
|
|
627
|
+
if (isDigit(tokens[at])) {
|
|
628
|
+
let next = at
|
|
629
|
+
while (isDigit(tokens[next])) next++
|
|
630
|
+
return next
|
|
631
|
+
}
|
|
632
|
+
if (word === 'U' && isPunct(tokens[at + 1], '&') && isString(tokens[at + 2])) {
|
|
633
|
+
return upperWord(tokens[at + 3]) === 'UESCAPE' && isString(tokens[at + 4]) ? at + 5 : at + 3
|
|
634
|
+
}
|
|
635
|
+
const type = afterTypeName(tokens, at)
|
|
636
|
+
if (type === undefined || !isString(tokens[type])) return undefined
|
|
637
|
+
let next = type + 1
|
|
638
|
+
if (word !== 'INTERVAL') return next
|
|
639
|
+
if (INTERVAL_FIELDS.has(upperWord(tokens[next]) ?? '')) {
|
|
640
|
+
next = afterGroup(tokens, next + 1)
|
|
641
|
+
if (upperWord(tokens[next]) === 'TO' && INTERVAL_FIELDS.has(upperWord(tokens[next + 1]) ?? '')) next = afterGroup(tokens, next + 2)
|
|
642
|
+
}
|
|
643
|
+
return next
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/**
|
|
647
|
+
* The index past a recursive CTE's `SEARCH {BREADTH | DEPTH} FIRST BY c, … SET c` and `CYCLE c, … SET c [TO v DEFAULT
|
|
648
|
+
* v] USING c` at `at` (`at` itself when it has neither), or `undefined` when one of them is not in that form.
|
|
649
|
+
*/
|
|
650
|
+
function afterSearchAndCycle(tokens: readonly SqlToken[], at: number): number | undefined {
|
|
651
|
+
let next: number | undefined = at
|
|
652
|
+
if (upperWord(tokens[next]) === 'SEARCH') {
|
|
653
|
+
const order = upperWord(tokens[next + 1])
|
|
654
|
+
if ((order !== 'BREADTH' && order !== 'DEPTH') || skipWords(tokens, next + 2, 'FIRST', 'BY') !== next + 4) return undefined
|
|
655
|
+
next = afterColumnsSet(tokens, next + 4)
|
|
656
|
+
}
|
|
657
|
+
if (next !== undefined && upperWord(tokens[next]) === 'CYCLE') {
|
|
658
|
+
next = afterColumnsSet(tokens, next + 1)
|
|
659
|
+
if (next !== undefined && upperWord(tokens[next]) === 'TO') {
|
|
660
|
+
const mark = afterMark(tokens, next + 1)
|
|
661
|
+
next = mark !== undefined && upperWord(tokens[mark]) === 'DEFAULT' ? afterMark(tokens, mark + 1) : undefined
|
|
662
|
+
}
|
|
663
|
+
if (next === undefined || upperWord(tokens[next]) !== 'USING' || !isName(tokens[next + 1])) return undefined
|
|
664
|
+
next += 2
|
|
665
|
+
}
|
|
666
|
+
return next
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
/**
|
|
670
|
+
* The `WITH [RECURSIVE] name [(…)] AS [[NOT] MATERIALIZED] (…) [SEARCH …] [CYCLE …], …` at `index`, or `undefined` if
|
|
671
|
+
* it is no CTE list.
|
|
672
|
+
*/
|
|
673
|
+
function cteList(tokens: readonly SqlToken[], index: number): CteList | undefined {
|
|
674
|
+
const names: number[] = []
|
|
675
|
+
// `WITH RECURSIVE AS (…)` and `WITH recursive (a) AS (…)` name a CTE `recursive`.
|
|
676
|
+
let at = upperWord(tokens[index + 1]) === 'RECURSIVE' && cteName(tokens, index + 2) !== undefined ? index + 2 : index + 1
|
|
456
677
|
for (;;) {
|
|
457
|
-
|
|
458
|
-
|
|
678
|
+
const name = cteName(tokens, at)
|
|
679
|
+
if (name === undefined) return undefined
|
|
680
|
+
names.push(name)
|
|
681
|
+
at = name + 1
|
|
459
682
|
if (isPunct(tokens[at], '(')) at = (closingParenthesis(tokens, at) ?? tokens.length) + 1
|
|
460
683
|
if (upperWord(tokens[at]) !== 'AS') return undefined
|
|
461
684
|
at = skipWords(tokens, skipWords(tokens, at + 1, 'NOT'), 'MATERIALIZED')
|
|
462
685
|
if (!isPunct(tokens[at], '(')) return undefined
|
|
463
|
-
|
|
464
|
-
if (
|
|
465
|
-
|
|
686
|
+
const after = afterSearchAndCycle(tokens, (closingParenthesis(tokens, at) ?? tokens.length) + 1)
|
|
687
|
+
if (after === undefined) return undefined
|
|
688
|
+
if (!isPunct(tokens[after], ',')) return { names, terminal: tokens[after] }
|
|
689
|
+
at = after + 1
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
/** The index where the query of `INSERT INTO name [AS alias] [(…)] [OVERRIDING … VALUE]` begins, the name at `at`. */
|
|
694
|
+
function insertQuery(tokens: readonly SqlToken[], at: number): number | undefined {
|
|
695
|
+
let next = afterName(tokens, at)
|
|
696
|
+
if (next === undefined) return undefined
|
|
697
|
+
if (upperWord(tokens[next]) === 'AS' && isName(tokens[next + 1])) next += 2
|
|
698
|
+
if (isPunct(tokens[next], '(')) next = (closingParenthesis(tokens, next) ?? tokens.length) + 1
|
|
699
|
+
if (upperWord(tokens[next]) === 'OVERRIDING' && upperWord(tokens[next + 2]) === 'VALUE') next += 3
|
|
700
|
+
return next
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
/** The CTE lists of a statement, a query or a body. */
|
|
704
|
+
export interface CteLists {
|
|
705
|
+
/** The statement each list ends in, by the index of its `WITH`, wherever that stands: a nested statement is refused there too. */
|
|
706
|
+
readonly terminals: ReadonlyMap<number, SqlToken | undefined>
|
|
707
|
+
/** The index of each CTE's name in a list whose `WITH` begins a query: a `(` after one opens its column list. */
|
|
708
|
+
readonly names: ReadonlySet<number>
|
|
709
|
+
/** The line of the first `WITH` that begins a query and whose list does not read as one; the entry refuses it. */
|
|
710
|
+
readonly unread: number | undefined
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
/**
|
|
714
|
+
* The CTE lists of `tokens`, nested ones too. A query begins at each of `queries`, after `(` and after an `INSERT`
|
|
715
|
+
* target. A list's names count only where a query begins, and there a `WITH` whose list does not read is `unread`.
|
|
716
|
+
* Elsewhere a `WITH` is another clause (`unnest(…) WITH ORDINALITY AS …`, `WITH TIES`, a policy's `WITH CHECK`),
|
|
717
|
+
* whose `name (` stays a call.
|
|
718
|
+
*/
|
|
719
|
+
function cteLists(tokens: readonly SqlToken[], queries: readonly number[]): CteLists {
|
|
720
|
+
const starts = new Set(queries)
|
|
721
|
+
const terminals = new Map<number, SqlToken | undefined>()
|
|
722
|
+
const names = new Set<number>()
|
|
723
|
+
let unread: number | undefined
|
|
724
|
+
for (let index = 0; index < tokens.length; index++) {
|
|
725
|
+
const token = tokens[index]
|
|
726
|
+
const word = upperWord(token)
|
|
727
|
+
if (isPunct(token, '(')) starts.add(index + 1)
|
|
728
|
+
if (word === 'INTO' && upperWord(tokens[index - 1]) === 'INSERT') {
|
|
729
|
+
const query = insertQuery(tokens, index + 1)
|
|
730
|
+
if (query !== undefined) starts.add(query)
|
|
731
|
+
}
|
|
732
|
+
if (word !== 'WITH') continue
|
|
733
|
+
const list = cteList(tokens, index)
|
|
734
|
+
const query = starts.has(index)
|
|
735
|
+
if (list === undefined) {
|
|
736
|
+
if (query) unread ??= token?.line ?? 1
|
|
737
|
+
continue
|
|
738
|
+
}
|
|
739
|
+
terminals.set(index, list.terminal)
|
|
740
|
+
if (!query) continue
|
|
741
|
+
for (const name of list.names) names.add(name)
|
|
742
|
+
}
|
|
743
|
+
return { terminals, names, unread }
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
/** A statement of a PL/pgSQL body: the index of its first token, and whether it stands in a declaration section. */
|
|
747
|
+
export interface BodyStatement {
|
|
748
|
+
readonly index: number
|
|
749
|
+
readonly declaring: boolean
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
/**
|
|
753
|
+
* Where each statement of a function or `DO` body begins, past `;` and a `<<label>>`: after `BEGIN`, `DECLARE` and
|
|
754
|
+
* `LOOP` (not `END LOOP`), and after `THEN` and `ELSE` except inside a `CASE` expression. A declaration section
|
|
755
|
+
* (`DECLARE` … `BEGIN`) holds declarations. And where a query begins: at each statement, and after its `RETURN QUERY`,
|
|
756
|
+
* `FOR … IN`, `OPEN … FOR`, and a declared cursor's `CURSOR [(…)] FOR` (or `IS`).
|
|
757
|
+
*/
|
|
758
|
+
function bodyOf(tokens: readonly SqlToken[]): { readonly statements: readonly BodyStatement[]; readonly queries: readonly number[] } {
|
|
759
|
+
const statements: BodyStatement[] = []
|
|
760
|
+
const queries: number[] = []
|
|
761
|
+
let start = true
|
|
762
|
+
let declaring = false
|
|
763
|
+
let depth = 0
|
|
764
|
+
// The word after which the statement's query begins; a cursor may write `IS` for `FOR`.
|
|
765
|
+
let opens: 'IN' | 'FOR' | undefined
|
|
766
|
+
const cases: ('statement' | 'expression')[] = []
|
|
767
|
+
for (let index = 0; index < tokens.length; index++) {
|
|
768
|
+
const token = tokens[index]
|
|
769
|
+
const word = upperWord(token)
|
|
770
|
+
if (start) {
|
|
771
|
+
if (isPunct(token, ';')) continue
|
|
772
|
+
start = false
|
|
773
|
+
if (isPunct(token, '<') && isPunct(tokens[index + 1], '<')) {
|
|
774
|
+
while (index < tokens.length && !(isPunct(tokens[index], '>') && isPunct(tokens[index + 1], '>'))) index++
|
|
775
|
+
index++
|
|
776
|
+
start = true
|
|
777
|
+
continue
|
|
778
|
+
}
|
|
779
|
+
statements.push({ index, declaring })
|
|
780
|
+
queries.push(index)
|
|
781
|
+
depth = 0
|
|
782
|
+
opens = word === 'FOR' ? 'IN' : word === 'OPEN' ? 'FOR' : undefined
|
|
783
|
+
if (word === 'RETURN' && upperWord(tokens[index + 1]) === 'QUERY') queries.push(index + 2)
|
|
784
|
+
if (word === 'CASE') {
|
|
785
|
+
cases.push('statement')
|
|
786
|
+
continue
|
|
787
|
+
}
|
|
788
|
+
} else if (word === 'CASE') {
|
|
789
|
+
cases.push('expression')
|
|
790
|
+
continue
|
|
791
|
+
}
|
|
792
|
+
if (isPunct(token, '(')) depth++
|
|
793
|
+
else if (isPunct(token, ')')) depth--
|
|
794
|
+
else if (depth === 0 && opens !== undefined && (word === opens || (opens === 'FOR' && word === 'IS'))) {
|
|
795
|
+
queries.push(index + 1)
|
|
796
|
+
opens = undefined
|
|
797
|
+
} else if (depth === 0 && declaring && word === 'CURSOR') opens = 'FOR'
|
|
798
|
+
const innermost = cases[cases.length - 1]
|
|
799
|
+
if (word === 'DECLARE') declaring = true
|
|
800
|
+
if (word === 'BEGIN') declaring = false
|
|
801
|
+
if (isPunct(token, ';') || word === 'BEGIN' || word === 'DECLARE') start = true
|
|
802
|
+
else if (word === 'LOOP') start = upperWord(tokens[index - 1]) !== 'END'
|
|
803
|
+
else if (word === 'THEN' || word === 'ELSE') start = innermost !== 'expression'
|
|
804
|
+
else if (word === 'END' && innermost === 'expression') cases.pop()
|
|
805
|
+
else if (word === 'END' && upperWord(tokens[index + 1]) === 'CASE') {
|
|
806
|
+
cases.pop()
|
|
807
|
+
index++
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
return { statements, queries }
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
const NO_CTE_LISTS: CteLists = { terminals: new Map(), names: new Set(), unread: undefined }
|
|
814
|
+
|
|
815
|
+
/**
|
|
816
|
+
* The tokens of a query, a statement, a clause or an expression, read once with their CTE lists. The name checks take
|
|
817
|
+
* the tokens and their lists as this one value, which only its factories build: its private member makes it nominal,
|
|
818
|
+
* so an object that merely has its fields is none, and a list is never read against tokens it was not read from.
|
|
819
|
+
*/
|
|
820
|
+
export class ReadSql {
|
|
821
|
+
readonly #read = true
|
|
822
|
+
readonly tokens: readonly SqlToken[]
|
|
823
|
+
readonly ctes: CteLists
|
|
824
|
+
|
|
825
|
+
protected constructor(tokens: readonly SqlToken[], ctes: CteLists) {
|
|
826
|
+
this.tokens = tokens
|
|
827
|
+
this.ctes = ctes
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
/** A query or a data-changing statement: a query begins at its first token. */
|
|
831
|
+
static query(tokens: readonly SqlToken[]): ReadSql {
|
|
832
|
+
return new ReadSql(tokens, cteLists(tokens, [0]))
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
/** A clause or a condition (a policy's expressions, a rule, a trigger's `WHEN`): a query begins only in parentheses. */
|
|
836
|
+
static clause(tokens: readonly SqlToken[]): ReadSql {
|
|
837
|
+
return new ReadSql(tokens, cteLists(tokens, []))
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
/** A stored expression, which Postgres lets hold no subquery: no CTE list is read, so every `name (` is a call. */
|
|
841
|
+
static expression(tokens: readonly SqlToken[]): ReadSql {
|
|
842
|
+
return new ReadSql(tokens, NO_CTE_LISTS)
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
/** A function or `DO` body read once: its statements (`bodyOf`), and its CTE lists with a query wherever one begins. */
|
|
847
|
+
export class ReadBody extends ReadSql {
|
|
848
|
+
readonly statements: readonly BodyStatement[]
|
|
849
|
+
|
|
850
|
+
private constructor(tokens: readonly SqlToken[], statements: readonly BodyStatement[], ctes: CteLists) {
|
|
851
|
+
super(tokens, ctes)
|
|
852
|
+
this.statements = statements
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
static of(tokens: readonly SqlToken[]): ReadBody {
|
|
856
|
+
const { statements, queries } = bodyOf(tokens)
|
|
857
|
+
return new ReadBody(tokens, statements, cteLists(tokens, queries))
|
|
466
858
|
}
|
|
467
859
|
}
|
|
468
860
|
|
|
@@ -470,9 +862,10 @@ function withTerminal(tokens: readonly SqlToken[], index: number): SqlToken | un
|
|
|
470
862
|
* The first nested statement a nested position may not hold: in parentheses (a CTE body, a subquery) and after a
|
|
471
863
|
* CTE list, anything but a query or `INSERT`/`UPDATE`/`DELETE`, whose names the same checks read. `MERGE` among them.
|
|
472
864
|
*/
|
|
473
|
-
export function nestedStatement(
|
|
865
|
+
export function nestedStatement(read: ReadSql): { readonly statement: string; readonly line: number } | undefined {
|
|
866
|
+
const { tokens, ctes: { terminals } } = read
|
|
474
867
|
for (let index = 0; index + 1 < tokens.length; index++) {
|
|
475
|
-
const next = isPunct(tokens[index], '(') ? tokens[index + 1] : upperWord(tokens[index]) === 'WITH' ?
|
|
868
|
+
const next = isPunct(tokens[index], '(') ? tokens[index + 1] : upperWord(tokens[index]) === 'WITH' ? terminals.get(index) : undefined
|
|
476
869
|
const word = next?.kind === 'word' ? upperWord(next) : undefined
|
|
477
870
|
if (word !== undefined && STATEMENT_WORDS.has(word) && !NESTED_STATEMENTS.has(word)) return { statement: word, line: next?.line ?? 1 }
|
|
478
871
|
if (upperWord(tokens[index]) === 'WITH' && next !== undefined && word === undefined) return { statement: 'WITH', line: next.line }
|
|
@@ -498,8 +891,8 @@ export function parenthesizedTarget(tokens: readonly SqlToken[]): { readonly sta
|
|
|
498
891
|
}
|
|
499
892
|
|
|
500
893
|
/** The relations a DML statement or a query names, in order: what its static text reads or writes. */
|
|
501
|
-
export function dmlRelations(
|
|
502
|
-
return nameReferences(
|
|
894
|
+
export function dmlRelations(read: ReadSql): NameReference[] {
|
|
895
|
+
return nameReferences(read).filter((reference) => reference.role === 'relation')
|
|
503
896
|
}
|
|
504
897
|
|
|
505
898
|
/**
|
|
@@ -588,7 +981,8 @@ const PAVED_FUNCTIONS: ReadonlySet<string> = new Set([
|
|
|
588
981
|
* Reviewed `pg_catalog` functions a function body, a view or a backfill may call, and a stored expression may call as
|
|
589
982
|
* a deviation: pure string, number, date, JSON, array, text-search and aggregate functions, `pg_sleep`, and the
|
|
590
983
|
* built-in trigger function. None runs SQL from a string, touches a file, a large object, a lock, a setting, another
|
|
591
|
-
* database or a sequence named by a string.
|
|
984
|
+
* database or a sequence named by a string. SQLite's `randomblob` and `hex` are here beside `random`: SQLite has no
|
|
985
|
+
* `gen_random_uuid`, and a Cloudflare backfill builds a key from them.
|
|
592
986
|
*/
|
|
593
987
|
const REVIEWED_FUNCTIONS: ReadonlySet<string> = new Set([
|
|
594
988
|
'concat',
|
|
@@ -630,6 +1024,8 @@ const REVIEWED_FUNCTIONS: ReadonlySet<string> = new Set([
|
|
|
630
1024
|
'sign',
|
|
631
1025
|
'div',
|
|
632
1026
|
'random',
|
|
1027
|
+
'randomblob',
|
|
1028
|
+
'hex',
|
|
633
1029
|
'age',
|
|
634
1030
|
'clock_timestamp',
|
|
635
1031
|
'statement_timestamp',
|
|
@@ -729,12 +1125,12 @@ export function functionUse(call: NameReference, schema: string, functions: Read
|
|
|
729
1125
|
}
|
|
730
1126
|
|
|
731
1127
|
/**
|
|
732
|
-
* The first call among `
|
|
1128
|
+
* The first call among the `references` of a body, a query or a backfill (`nameReferences`) that it may not make: anything but a paved or reviewed
|
|
733
1129
|
* built-in, or a function the migrations declare in `schema`. An allowlist, because a built-in such as
|
|
734
1130
|
* `query_to_xml`, `dblink` or `lo_import` runs SQL from a string or reaches past the schema, which no name rule sees.
|
|
735
1131
|
*/
|
|
736
|
-
export function
|
|
737
|
-
for (const reference of
|
|
1132
|
+
export function refusedCall(references: readonly NameReference[], schema: string, functions: ReadonlySet<string>): NameReference | undefined {
|
|
1133
|
+
for (const reference of references) {
|
|
738
1134
|
if (reference.role !== 'call') continue
|
|
739
1135
|
const use = functionUse(reference, schema, functions)
|
|
740
1136
|
if (use === undefined) return reference
|
package/src/sql.ts
CHANGED
|
@@ -35,9 +35,11 @@ export { lexSql, type SqlToken, sqlTokens, type Statement, statementsOf, topLeve
|
|
|
35
35
|
export { PG_CATALOG_FUNCTIONS, SQL_KEYWORDS } from './pg-catalog-names'
|
|
36
36
|
export {
|
|
37
37
|
afterName,
|
|
38
|
+
type BodyStatement,
|
|
38
39
|
closingParenthesis,
|
|
40
|
+
CTE_FORM,
|
|
41
|
+
type CteLists,
|
|
39
42
|
ddlForeignSchema,
|
|
40
|
-
dmlForeignSchema,
|
|
41
43
|
dmlRelations,
|
|
42
44
|
frameworkReference,
|
|
43
45
|
type FunctionUse,
|
|
@@ -51,7 +53,10 @@ export {
|
|
|
51
53
|
nestedStatement,
|
|
52
54
|
objectNameAt,
|
|
53
55
|
parenthesizedTarget,
|
|
54
|
-
|
|
56
|
+
ReadBody,
|
|
57
|
+
ReadSql,
|
|
58
|
+
referencedForeignSchema,
|
|
59
|
+
refusedCall,
|
|
55
60
|
skipWords,
|
|
56
61
|
splitAtCommas,
|
|
57
62
|
statementKind,
|
package/types/src/sql-names.d.ts
CHANGED
|
@@ -44,21 +44,64 @@ export interface NameReference {
|
|
|
44
44
|
/**
|
|
45
45
|
* Every name of a DML statement, a query or an expression, with its role. A name in a relation position (after
|
|
46
46
|
* `FROM`, `JOIN`, `USING`, `INTO`, `UPDATE`, `TABLE`, `REFERENCES`, or a `,` of a `FROM` list) is a relation; a name
|
|
47
|
-
* that `(` follows is a call, unless it is syntax
|
|
48
|
-
*
|
|
47
|
+
* that `(` follows is a call, unless it is syntax, a type with a modifier or a CTE's name before its column list
|
|
48
|
+
* (`WITH RECURSIVE tree (id, depth) AS`); a name after `::` or `AS` is a type. A two-part name anywhere else is a
|
|
49
|
+
* column of a table or an alias (`d.note`, `NEW.stage`).
|
|
49
50
|
*/
|
|
50
|
-
export declare function nameReferences(
|
|
51
|
+
export declare function nameReferences(read: ReadSql): NameReference[];
|
|
51
52
|
/**
|
|
52
|
-
* The first schema a DML statement, a query or a function body
|
|
53
|
-
* qualified relation, call or type, or a three-part name. An unqualified
|
|
54
|
-
* resolves to the catalog and counts as `pg_catalog`.
|
|
53
|
+
* The first schema the `references` of a DML statement, a query or a function body (`nameReferences`) reach other
|
|
54
|
+
* than `schema`, `pg_catalog` included: a qualified relation, call or type, or a three-part name. An unqualified
|
|
55
|
+
* relation whose name starts with `pg_` resolves to the catalog and counts as `pg_catalog`.
|
|
55
56
|
*/
|
|
56
|
-
export declare function
|
|
57
|
+
export declare function referencedForeignSchema(references: readonly NameReference[], schema: string): string | undefined;
|
|
58
|
+
/**
|
|
59
|
+
* The form of a CTE that a list must take to be read, for a refusal to name: a `CYCLE` mark is a constant, as Postgres
|
|
60
|
+
* requires, never a bound value.
|
|
61
|
+
*/
|
|
62
|
+
export declare const CTE_FORM = "name [(columns)] AS [[NOT] MATERIALIZED] (query) [SEARCH {BREADTH | DEPTH} FIRST BY columns SET column] [CYCLE columns SET column [TO constant DEFAULT constant] USING column]";
|
|
63
|
+
/** The CTE lists of a statement, a query or a body. */
|
|
64
|
+
export interface CteLists {
|
|
65
|
+
/** The statement each list ends in, by the index of its `WITH`, wherever that stands: a nested statement is refused there too. */
|
|
66
|
+
readonly terminals: ReadonlyMap<number, SqlToken | undefined>;
|
|
67
|
+
/** The index of each CTE's name in a list whose `WITH` begins a query: a `(` after one opens its column list. */
|
|
68
|
+
readonly names: ReadonlySet<number>;
|
|
69
|
+
/** The line of the first `WITH` that begins a query and whose list does not read as one; the entry refuses it. */
|
|
70
|
+
readonly unread: number | undefined;
|
|
71
|
+
}
|
|
72
|
+
/** A statement of a PL/pgSQL body: the index of its first token, and whether it stands in a declaration section. */
|
|
73
|
+
export interface BodyStatement {
|
|
74
|
+
readonly index: number;
|
|
75
|
+
readonly declaring: boolean;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* The tokens of a query, a statement, a clause or an expression, read once with their CTE lists. The name checks take
|
|
79
|
+
* the tokens and their lists as this one value, which only its factories build: its private member makes it nominal,
|
|
80
|
+
* so an object that merely has its fields is none, and a list is never read against tokens it was not read from.
|
|
81
|
+
*/
|
|
82
|
+
export declare class ReadSql {
|
|
83
|
+
#private;
|
|
84
|
+
readonly tokens: readonly SqlToken[];
|
|
85
|
+
readonly ctes: CteLists;
|
|
86
|
+
protected constructor(tokens: readonly SqlToken[], ctes: CteLists);
|
|
87
|
+
/** A query or a data-changing statement: a query begins at its first token. */
|
|
88
|
+
static query(tokens: readonly SqlToken[]): ReadSql;
|
|
89
|
+
/** A clause or a condition (a policy's expressions, a rule, a trigger's `WHEN`): a query begins only in parentheses. */
|
|
90
|
+
static clause(tokens: readonly SqlToken[]): ReadSql;
|
|
91
|
+
/** A stored expression, which Postgres lets hold no subquery: no CTE list is read, so every `name (` is a call. */
|
|
92
|
+
static expression(tokens: readonly SqlToken[]): ReadSql;
|
|
93
|
+
}
|
|
94
|
+
/** A function or `DO` body read once: its statements (`bodyOf`), and its CTE lists with a query wherever one begins. */
|
|
95
|
+
export declare class ReadBody extends ReadSql {
|
|
96
|
+
readonly statements: readonly BodyStatement[];
|
|
97
|
+
private constructor();
|
|
98
|
+
static of(tokens: readonly SqlToken[]): ReadBody;
|
|
99
|
+
}
|
|
57
100
|
/**
|
|
58
101
|
* The first nested statement a nested position may not hold: in parentheses (a CTE body, a subquery) and after a
|
|
59
102
|
* CTE list, anything but a query or `INSERT`/`UPDATE`/`DELETE`, whose names the same checks read. `MERGE` among them.
|
|
60
103
|
*/
|
|
61
|
-
export declare function nestedStatement(
|
|
104
|
+
export declare function nestedStatement(read: ReadSql): {
|
|
62
105
|
readonly statement: string;
|
|
63
106
|
readonly line: number;
|
|
64
107
|
} | undefined;
|
|
@@ -71,7 +114,7 @@ export declare function parenthesizedTarget(tokens: readonly SqlToken[]): {
|
|
|
71
114
|
readonly line: number;
|
|
72
115
|
} | undefined;
|
|
73
116
|
/** The relations a DML statement or a query names, in order: what its static text reads or writes. */
|
|
74
|
-
export declare function dmlRelations(
|
|
117
|
+
export declare function dmlRelations(read: ReadSql): NameReference[];
|
|
75
118
|
/**
|
|
76
119
|
* Whether a name is the framework's (`fabrika_…`): its tables share the application's schema and hold its secrets,
|
|
77
120
|
* leases and deliveries. Case-insensitive, so a quoted `"FABRIKA_x"` counts too.
|
|
@@ -94,8 +137,8 @@ export type FunctionUse = 'paved' | 'reviewed' | 'declared';
|
|
|
94
137
|
*/
|
|
95
138
|
export declare function functionUse(call: NameReference, schema: string, functions: ReadonlySet<string>): FunctionUse | undefined;
|
|
96
139
|
/**
|
|
97
|
-
* The first call among `
|
|
140
|
+
* The first call among the `references` of a body, a query or a backfill (`nameReferences`) that it may not make: anything but a paved or reviewed
|
|
98
141
|
* built-in, or a function the migrations declare in `schema`. An allowlist, because a built-in such as
|
|
99
142
|
* `query_to_xml`, `dblink` or `lo_import` runs SQL from a string or reaches past the schema, which no name rule sees.
|
|
100
143
|
*/
|
|
101
|
-
export declare function
|
|
144
|
+
export declare function refusedCall(references: readonly NameReference[], schema: string, functions: ReadonlySet<string>): NameReference | undefined;
|
package/types/src/sql.d.ts
CHANGED
|
@@ -3,5 +3,5 @@ export { FILE_SCAN_COLUMNS, FILE_STATUSES, FILE_TABLE_PREFIX, fileScanAlter, fil
|
|
|
3
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';
|
|
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
|
-
export { afterName, closingParenthesis,
|
|
6
|
+
export { afterName, type BodyStatement, closingParenthesis, CTE_FORM, type CteLists, ddlForeignSchema, dmlRelations, frameworkReference, type FunctionUse, functionUse, isFrameworkName, isPunct, type NameReference, nameReferences, type NameRole, nameText, nestedStatement, objectNameAt, parenthesizedTarget, ReadBody, ReadSql, referencedForeignSchema, refusedCall, skipWords, splitAtCommas, statementKind, unicodeIdentifier, } from './sql-names';
|
|
7
7
|
export { lexSqlite } from './sqlite-sql';
|