@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/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 or a type with a modifier; a name after `::` or `AS` is a type. A
280
- * two-part name anywhere else is a column of a table or an alias (`d.note`, `NEW.stage`).
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(tokens: readonly SqlToken[]): NameReference[] {
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 reaches other than `schema`, `pg_catalog` included: a
386
- * qualified relation, call or type, or a three-part name. An unqualified relation whose name starts with `pg_`
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 dmlForeignSchema(tokens: readonly SqlToken[], schema: string): string | undefined {
390
- for (const reference of nameReferences(tokens)) {
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
- /** The statement a `WITH name [(…)] AS [[NOT] MATERIALIZED] (…), …` at `index` ends in, or `undefined` if it is no CTE list. */
454
- function withTerminal(tokens: readonly SqlToken[], index: number): SqlToken | undefined {
455
- let at = skipWords(tokens, index + 1, 'RECURSIVE')
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
- if (!isName(tokens[at])) return undefined
458
- at++
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
- at = (closingParenthesis(tokens, at) ?? tokens.length) + 1
464
- if (!isPunct(tokens[at], ',')) return tokens[at]
465
- at++
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(tokens: readonly SqlToken[]): { readonly statement: string; readonly line: number } | undefined {
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' ? withTerminal(tokens, index) : undefined
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(tokens: readonly SqlToken[]): NameReference[] {
502
- return nameReferences(tokens).filter((reference) => reference.role === 'relation')
894
+ export function dmlRelations(read: ReadSql): NameReference[] {
895
+ return nameReferences(read).filter((reference) => reference.role === 'relation')
503
896
  }
504
897
 
505
898
  /**
@@ -539,6 +932,9 @@ export function unicodeIdentifier(tokens: readonly SqlToken[]): { readonly line:
539
932
  */
540
933
  const PAVED_FUNCTIONS: ReadonlySet<string> = new Set([
541
934
  'now',
935
+ // SQLite's clock in a Cloudflare application's DEFAULT, the form the checker's `cloudflare-current-timestamp` rule
936
+ // prescribes (`strftime('%Y-%m-%dT%H:%M:%fZ', 'now')`); no side effect, no other row.
937
+ 'strftime',
542
938
  'gen_random_uuid',
543
939
  'lower',
544
940
  'upper',
@@ -585,7 +981,8 @@ const PAVED_FUNCTIONS: ReadonlySet<string> = new Set([
585
981
  * Reviewed `pg_catalog` functions a function body, a view or a backfill may call, and a stored expression may call as
586
982
  * a deviation: pure string, number, date, JSON, array, text-search and aggregate functions, `pg_sleep`, and the
587
983
  * built-in trigger function. None runs SQL from a string, touches a file, a large object, a lock, a setting, another
588
- * 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.
589
986
  */
590
987
  const REVIEWED_FUNCTIONS: ReadonlySet<string> = new Set([
591
988
  'concat',
@@ -627,6 +1024,8 @@ const REVIEWED_FUNCTIONS: ReadonlySet<string> = new Set([
627
1024
  'sign',
628
1025
  'div',
629
1026
  'random',
1027
+ 'randomblob',
1028
+ 'hex',
630
1029
  'age',
631
1030
  'clock_timestamp',
632
1031
  'statement_timestamp',
@@ -726,12 +1125,12 @@ export function functionUse(call: NameReference, schema: string, functions: Read
726
1125
  }
727
1126
 
728
1127
  /**
729
- * The first call among `tokens` that a body, a query or a backfill may not make: anything but a paved or reviewed
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
730
1129
  * built-in, or a function the migrations declare in `schema`. An allowlist, because a built-in such as
731
1130
  * `query_to_xml`, `dblink` or `lo_import` runs SQL from a string or reaches past the schema, which no name rule sees.
732
1131
  */
733
- export function refusedFunctionCall(tokens: readonly SqlToken[], schema: string, functions: ReadonlySet<string>): NameReference | undefined {
734
- for (const reference of nameReferences(tokens)) {
1132
+ export function refusedCall(references: readonly NameReference[], schema: string, functions: ReadonlySet<string>): NameReference | undefined {
1133
+ for (const reference of references) {
735
1134
  if (reference.role !== 'call') continue
736
1135
  const use = functionUse(reference, schema, functions)
737
1136
  if (use === undefined) return reference
@@ -26,8 +26,11 @@
26
26
  // already coerce `undefined` → null, so this matches what the services are tested against.
27
27
  // * SQLite-only SQL still fails, obviously: `unixepoch()` does not exist in Postgres. Several
28
28
  // statements in `@fabrika/control` and `@fabrika/iam` use it today.
29
- // * Prepared statements are cached per connection by default. Behind a transaction-mode pooler
30
- // (pgbouncer) construct the client with `{ prepare: false }`.
29
+ // * NO NAMED PREPARED STATEMENTS. A Zerops PostgreSQL service hands one server session to the IAM, Control and
30
+ // Operations processes in turn, so a statement prepared before a migration's ADD COLUMN outlives the
31
+ // process that prepared it, and `SELECT *` then fails with `cached plan must not change result type`
32
+ // (0A000). The same happens to one client that runs a migration between two reads. `connect` therefore
33
+ // defaults to `{ prepare: false }`: every statement is parsed where it runs.
31
34
 
32
35
  import type { SqlDatabase, SqlQueryResult, SqlRunResult, SqlStatement } from '@fabrika/platform'
33
36
  import { rewritePlaceholders, type RewrittenSql } from './placeholders'
@@ -36,7 +39,7 @@ import { rewritePlaceholders, type RewrittenSql } from './placeholders'
36
39
  const MUTATING_COMMANDS = new Set(['INSERT', 'UPDATE', 'DELETE', 'MERGE'])
37
40
 
38
41
  /** What a bound value may be. Anything else is a programming error and throws at bind time, as D1 does. */
39
- export type SqlBindValue = string | number | bigint | boolean | Date | Uint8Array | null
42
+ export type SqlBindValue = string | number | bigint | boolean | Uint8Array | null
40
43
 
41
44
  /**
42
45
  * One prepared statement. IMMUTABLE: `bind()` returns a NEW statement carrying the values and leaves
@@ -99,11 +102,11 @@ export class PostgresDatabase implements SqlDatabase {
99
102
  constructor(private readonly sql: Bun.SQL) {}
100
103
 
101
104
  /**
102
- * Open a pooled client. The URL is a CREDENTIAL — it is never logged, and never included in an
103
- * error message raised here.
105
+ * Open a pooled client that prepares no named statement (see the header). The URL is a CREDENTIAL — it is
106
+ * never logged, and never included in an error message raised here.
104
107
  */
105
- static connect(url: string, options: Omit<Bun.SQL.PostgresOrMySQLOptions, 'url' | 'adapter'> = {}): PostgresDatabase {
106
- return new PostgresDatabase(new Bun.SQL({ ...options, url, adapter: 'postgres' }))
108
+ static connect(url: string, options: Omit<Bun.SQL.PostgresOrMySQLOptions, 'url' | 'adapter' | 'prepare'> = {}): PostgresDatabase {
109
+ return new PostgresDatabase(new Bun.SQL({ ...options, prepare: false, url, adapter: 'postgres' }))
107
110
  }
108
111
 
109
112
  prepare(sql: string): SqlStatement {
@@ -198,11 +201,14 @@ function toBindValue(value: unknown): SqlBindValue {
198
201
  || typeof value === 'number'
199
202
  || typeof value === 'bigint'
200
203
  || typeof value === 'boolean'
201
- || value instanceof Date
202
204
  || value instanceof Uint8Array
203
205
  ) {
204
206
  return value
205
207
  }
208
+ // Without a prepared statement Bun sends a parameter as text, and a Date as `Date#toString()`, which Postgres refuses.
209
+ if (value instanceof Date) {
210
+ return value.toISOString()
211
+ }
206
212
  if (value instanceof ArrayBuffer) {
207
213
  return new Uint8Array(value)
208
214
  }
package/src/sql.ts CHANGED
@@ -1,4 +1,4 @@
1
- // @fabrika/platform-node/sql — the SQL lexer and the migration classifier, RUNTIME-NEUTRAL: no Bun, no Node, no
1
+ // @fabrika/platform-node/sql — the SQL lexers (Postgres, SQLite) and the migration classifier, RUNTIME-NEUTRAL: no Bun, no Node, no
2
2
  // driver, so a Cloudflare Worker (Control reading a commit) loads it as the runner does. `sql-subpath.test.ts` holds
3
3
  // the import graph to that.
4
4
 
@@ -22,6 +22,7 @@ export {
22
22
  type DatabaseObjectKind,
23
23
  declaredFunctions,
24
24
  type DeviationKind,
25
+ type FileAdoption,
25
26
  type ManifestChange,
26
27
  type MigrationClassification,
27
28
  type MigrationDeviation,
@@ -30,13 +31,15 @@ export {
30
31
  type MigrationRefusal,
31
32
  type MigrationSetClassification,
32
33
  } from './migration-classify'
33
- export { lexSql, type SqlToken, sqlTokens, type Statement, topLevelStatements, upperWord } from './migration-sql'
34
+ export { lexSql, type SqlToken, sqlTokens, type Statement, statementsOf, topLevelStatements, upperWord } from './migration-sql'
34
35
  export { PG_CATALOG_FUNCTIONS, SQL_KEYWORDS } from './pg-catalog-names'
35
36
  export {
36
37
  afterName,
38
+ type BodyStatement,
37
39
  closingParenthesis,
40
+ CTE_FORM,
41
+ type CteLists,
38
42
  ddlForeignSchema,
39
- dmlForeignSchema,
40
43
  dmlRelations,
41
44
  frameworkReference,
42
45
  type FunctionUse,
@@ -50,9 +53,13 @@ export {
50
53
  nestedStatement,
51
54
  objectNameAt,
52
55
  parenthesizedTarget,
53
- refusedFunctionCall,
56
+ ReadBody,
57
+ ReadSql,
58
+ referencedForeignSchema,
59
+ refusedCall,
54
60
  skipWords,
55
61
  splitAtCommas,
56
62
  statementKind,
57
63
  unicodeIdentifier,
58
64
  } from './sql-names'
65
+ export { lexSqlite } from './sqlite-sql'