hekireki 0.52.0 → 0.52.2

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.
Files changed (66) hide show
  1. package/README.md +8 -0
  2. package/dist/bin/activerecord.js +1 -1
  3. package/dist/bin/ajv.js +1 -1
  4. package/dist/bin/arktype.js +1 -1
  5. package/dist/bin/atlas.js +1 -1
  6. package/dist/bin/django.js +1 -1
  7. package/dist/bin/docs.js +1 -1
  8. package/dist/bin/drizzle.js +1 -1
  9. package/dist/bin/ecto.js +1 -1
  10. package/dist/bin/efcore.js +1 -1
  11. package/dist/bin/effect.js +1 -1
  12. package/dist/bin/eloquent.js +1 -1
  13. package/dist/bin/er.js +1 -1
  14. package/dist/bin/exposed.js +1 -1
  15. package/dist/bin/gorm.js +1 -1
  16. package/dist/bin/hekireki.js +5 -5
  17. package/dist/bin/kysely.js +1 -1
  18. package/dist/bin/openapi.js +1 -1
  19. package/dist/bin/pydantic.js +1 -1
  20. package/dist/bin/sea-orm.js +1 -1
  21. package/dist/bin/seed.js +1 -1
  22. package/dist/bin/sqlalchemy.js +1 -1
  23. package/dist/bin/typebox.js +1 -1
  24. package/dist/bin/valibot.js +1 -1
  25. package/dist/bin/zod-openapi-hono.js +1 -1
  26. package/dist/bin/zod.js +1 -1
  27. package/dist/{bin-BcqPhgiX.js → bin-i7iQQ-V-.js} +3295 -2428
  28. package/dist/case-D3JCqTLI.js +54 -0
  29. package/dist/{discover-BKlX-LLS.js → discover-CLLycWcR.js} +3 -3
  30. package/dist/{emit-BSQAIFiF.js → emit-DsCT5gLu.js} +5 -2
  31. package/dist/{errors-fAN1Og-7.js → errors-CRIxtr-P.js} +88 -26
  32. package/dist/index.d.ts +1 -1
  33. package/dist/index.js +1 -1
  34. package/dist/{migrate-BS6d_8aA.js → migrate-1xVrRUlb.js} +77 -21
  35. package/dist/{native-engine-DcZUEqO8.js → native-engine-DeQEnJxi.js} +145 -30
  36. package/dist/{plan-BMypogKp.js → plan-8rsBBJcs.js} +1294 -768
  37. package/dist/{run-BYq7BEVd.js → run-DbZYkHVI.js} +235 -128
  38. package/dist/{schema-B7beUJic.js → schema-CyJTUCF1.js} +54 -182
  39. package/dist/{sql-BwL2BncN.js → sql-LMMCiAlf.js} +48 -19
  40. package/dist/{start-s1j4PqUM.js → start-Ba8wQAD1.js} +1304 -929
  41. package/dist/studio/assets/client-8R97eV42.js +2 -0
  42. package/dist/studio/assets/{confirm-dialog-CKCkchiq.js → confirm-dialog-BfMzwGyk.js} +1 -1
  43. package/dist/studio/assets/docs-C7FtC4KG.js +1 -0
  44. package/dist/studio/assets/enums._name-DLAiEdMc.js +1 -0
  45. package/dist/studio/assets/{field-icon-C1wSRFKO.js → field-icon-LVK7vIIn.js} +1 -1
  46. package/dist/studio/assets/index-T46k2NyA.js +15 -0
  47. package/dist/studio/assets/{labels-B5gZ2suK.js → labels-Bn-KWaMa.js} +2 -2
  48. package/dist/studio/assets/{marked-text-B27DfhKS.js → marked-text-BdU5_qSK.js} +1 -1
  49. package/dist/studio/assets/models._name-BKzAVcW3.js +1 -0
  50. package/dist/studio/assets/{monaco-DRYJTcJl.js → monaco-33yj-p0X.js} +1 -1
  51. package/dist/studio/assets/prisma-DqpMbUwJ.js +2 -0
  52. package/dist/studio/assets/result-table-PN64JbsN.js +1 -0
  53. package/dist/studio/assets/{routes-Bl7HRpBJ.js → routes-C1Aze5QM.js} +1 -1
  54. package/dist/studio/assets/{schema-view-BEdx0cC2.js → schema-view-Bq2_9B5a.js} +4 -4
  55. package/dist/studio/assets/sql-FZV6GAdV.js +6 -0
  56. package/dist/studio/assets/{tabs-BpZ0hh1V.js → tabs-GBri63Xo.js} +1 -1
  57. package/dist/studio/index.html +2 -2
  58. package/package.json +12 -5
  59. package/dist/studio/assets/client-C-v3Paav.js +0 -2
  60. package/dist/studio/assets/docs-CXORFY0Y.js +0 -1
  61. package/dist/studio/assets/enums._name-BUBU_WMt.js +0 -1
  62. package/dist/studio/assets/index-DzCcMC-d.js +0 -15
  63. package/dist/studio/assets/models._name-CQFgPD0T.js +0 -1
  64. package/dist/studio/assets/prisma-1nDx08Wb.js +0 -2
  65. package/dist/studio/assets/result-table-0P18Nywh.js +0 -1
  66. package/dist/studio/assets/sql-GBZZtEKI.js +0 -6
@@ -1,11 +1,12 @@
1
1
  import { c as removePath, i as makeDirectory, l as watch, n as fileStamp, o as readDirectory, r as isDirectory, s as readFile, t as exists, u as writeFile$1 } from "./file-DOGnu_Q2.js";
2
2
  import { _ as STUDIO_HOSTNAME, a as InvalidInputError, b as readPrismaConfig, c as ServerListenError, d as DatabaseError, g as SSE_PING_MS, h as PRISMA_FILE_URI, i as FormatError, l as UnknownFileError, m as MIGRATIONS_POLL_MS, n as ClientUnavailableError, o as SchemaLoadError, p as FORBIDDEN_HOST_MESSAGE, r as FileWriteError, s as SchemaParseError, t as ClientQueryError, u as UnknownModelError } from "./bin/hekireki.js";
3
- import { G as isLoopbackHostname, d as makePostgresSchema, et as fmt, i as readSchemaFiles$1, m as formatSql, n as parseSchema, q as lowerFirst, r as readConfig } from "./schema-B7beUJic.js";
4
- import { c as makeSchema, i as openSchemaEngine, n as openNativeSchemaEngine, o as makeSchemaEngineAdapter, r as engineCommand, s as makeAnalysisSchema, t as findSchemaEngineBinary } from "./native-engine-DcZUEqO8.js";
5
- import { a as splitStatements, i as MigrationNotFoundError, l as toTsType, n as MigrateDatabaseError, s as literalDataType, t as MigrateConfigError } from "./errors-fAN1Og-7.js";
6
- import { f as placeholder, h as stringLiteral, i as withTypeScriptImports, m as quoteIdentifier, o as readConfigUrl, p as qualifiedName } from "./sql-BwL2BncN.js";
7
- import { _ as openSqliteCopy, a as makePlan$1, c as checkOpened, d as DECISIONS_FILE, f as readDecisions, g as openShadowDatabase, h as openMysqlCopy, m as connectDatabase, p as writeDecisions, u as introspectDatabase } from "./plan-BMypogKp.js";
8
- import { n as discoverClient, r as adapterOf, t as clientSource } from "./discover-BKlX-LLS.js";
3
+ import { R as fmt, d as makePostgresSchema, i as readSchemaFiles$1, m as formatSql, n as parseSchema, r as readConfig } from "./schema-CyJTUCF1.js";
4
+ import { c as makeSchema, i as openSchemaEngine, n as openNativeSchemaEngine, o as makeSchemaEngineAdapter, r as engineCommand, s as makeAnalysisSchema, t as findSchemaEngineBinary } from "./native-engine-DeQEnJxi.js";
5
+ import { r as lowerFirst } from "./case-D3JCqTLI.js";
6
+ import { a as splitStatements, i as MigrationNotFoundError, l as toTsType, n as MigrateDatabaseError, s as literalDataType, t as MigrateConfigError } from "./errors-CRIxtr-P.js";
7
+ import { f as placeholder, h as stringLiteral, i as withTypeScriptImports, m as quoteIdentifier, o as readConfigUrl, p as qualifiedName } from "./sql-LMMCiAlf.js";
8
+ import { _ as openSqliteCopy, a as makePlan$1, c as checkOpened, d as DECISIONS_FILE, f as readDecisions, g as openShadowDatabase, h as openMysqlCopy, m as connectDatabase, p as writeDecisions, u as introspectDatabase } from "./plan-8rsBBJcs.js";
9
+ import { n as discoverClient, r as adapterOf, t as clientSource } from "./discover-CLLycWcR.js";
9
10
  import { createRequire } from "node:module";
10
11
  import { Clock, Duration, Effect, Match, Option, Ref, Schedule, Semaphore, Stream } from "effect";
11
12
  import path from "node:path";
@@ -130,6 +131,10 @@ function token(kind, raw, text, start, end) {
130
131
  };
131
132
  }
132
133
  function step(text, at, previous) {
134
+ return skipStep(text, at) ?? quotedStep(text, at, previous) ?? paramStep(text, at, previous) ?? plainStep(text, at);
135
+ }
136
+ /** Whitespace and comments, which leave no token. */
137
+ function skipStep(text, at) {
133
138
  const char = text[at] ?? "";
134
139
  if (isSpace(char)) return { skip: at + 1 };
135
140
  if (char === "-" && text[at + 1] === "-") {
@@ -144,6 +149,11 @@ function step(text, at, previous) {
144
149
  } };
145
150
  return { skip: end + 2 };
146
151
  }
152
+ return null;
153
+ }
154
+ /** A string literal or a quoted identifier. */
155
+ function quotedStep(text, at, previous) {
156
+ const char = text[at] ?? "";
147
157
  if (char === "'") {
148
158
  const end = readDelimited(text, at, "'", true);
149
159
  if (end === null) return { error: {
@@ -171,6 +181,11 @@ function step(text, at, previous) {
171
181
  const raw = text.slice(at, end);
172
182
  return token("quoted", raw, unquote(raw, "]", false), at, end);
173
183
  }
184
+ return null;
185
+ }
186
+ /** A placeholder (`$1`, `?`, `:name`, `@name`), or a dollar-quoted string. */
187
+ function paramStep(text, at, previous) {
188
+ const char = text[at] ?? "";
174
189
  if (char === "$") {
175
190
  const dollar = readDollarQuoted(text, at);
176
191
  if (dollar !== null) {
@@ -178,7 +193,7 @@ function step(text, at, previous) {
178
193
  return token("string", raw, raw.slice(dollar.tag.length, -dollar.tag.length), at, dollar.end);
179
194
  }
180
195
  const end = readWord(text, at + 1);
181
- if (end > at + 1) return token("param", text.slice(at, end), text.slice(at, end), at, end);
196
+ return end > at + 1 ? token("param", text.slice(at, end), text.slice(at, end), at, end) : null;
182
197
  }
183
198
  if (char === "?") {
184
199
  const end = readWord(text, at + 1);
@@ -188,6 +203,11 @@ function step(text, at, previous) {
188
203
  const end = readWord(text, at + 1);
189
204
  return token("param", text.slice(at, end), text.slice(at, end), at, end);
190
205
  }
206
+ return null;
207
+ }
208
+ /** A number, a word, punctuation or an operator; anything else is an error. */
209
+ function plainStep(text, at) {
210
+ const char = text[at] ?? "";
191
211
  if (isDigit(char) || char === "." && isDigit(text[at + 1] ?? "")) {
192
212
  const end = readNumber(text, at);
193
213
  return token("number", text.slice(at, end), text.slice(at, end), at, end);
@@ -465,104 +485,80 @@ function parseComparison(p) {
465
485
  }
466
486
  /** The predicates that follow a value: comparison operators, IS, IN, BETWEEN, LIKE and friends. */
467
487
  function parsePredicate(p, start, left) {
488
+ const next = parseComparisonPredicate(p, start, left) ?? parseIsPredicate(p, start, left) ?? parseNegatablePredicate(p, start, left);
489
+ return next === null ? left : parsePredicate(p, start, next);
490
+ }
491
+ function parseComparisonPredicate(p, start, left) {
468
492
  const token = peek(p);
469
- if (token.kind === "op" && COMPARISON.has(token.text)) {
470
- advance(p);
471
- if (atWord(p, "ANY") || atWord(p, "ALL") || atWord(p, "SOME")) advance(p);
493
+ if (token.kind !== "op" || !COMPARISON.has(token.text)) return null;
494
+ advance(p);
495
+ if (atWord(p, "ANY") || atWord(p, "ALL") || atWord(p, "SOME")) advance(p);
496
+ const right = parseConcat(p);
497
+ return {
498
+ type: "binary",
499
+ op: token.text,
500
+ left,
501
+ right,
502
+ range: rangeFrom(p, start)
503
+ };
504
+ }
505
+ const IS_VALUES = /* @__PURE__ */ new Map([
506
+ ["NULL", "NULL"],
507
+ ["TRUE", "TRUE"],
508
+ ["FALSE", "FALSE"],
509
+ ["UNKNOWN", "UNKNOWN"]
510
+ ]);
511
+ /** `IS [NOT] NULL` and the like, `IS [NOT] DISTINCT FROM`, and `ISNULL` / `NOTNULL`. */
512
+ function parseIsPredicate(p, start, left) {
513
+ if (atWord(p, "ISNULL") || atWord(p, "NOTNULL")) return {
514
+ type: "is",
515
+ expr: left,
516
+ not: advance(p).text === "NOTNULL",
517
+ value: "NULL",
518
+ range: rangeFrom(p, start)
519
+ };
520
+ if (!atWord(p, "IS")) return null;
521
+ advance(p);
522
+ const not = acceptWord(p, "NOT");
523
+ if (acceptWords(p, "DISTINCT", "FROM")) {
472
524
  const right = parseConcat(p);
473
- return parsePredicate(p, start, {
525
+ return {
474
526
  type: "binary",
475
- op: token.text,
527
+ op: not ? "IS NOT DISTINCT FROM" : "IS DISTINCT FROM",
476
528
  left,
477
529
  right,
478
530
  range: rangeFrom(p, start)
479
- });
480
- }
481
- if (atWord(p, "IS")) {
482
- advance(p);
483
- const not = acceptWord(p, "NOT");
484
- if (acceptWords(p, "DISTINCT", "FROM")) {
485
- const right = parseConcat(p);
486
- return parsePredicate(p, start, {
487
- type: "binary",
488
- op: not ? "IS NOT DISTINCT FROM" : "IS DISTINCT FROM",
489
- left,
490
- right,
491
- range: rangeFrom(p, start)
492
- });
493
- }
494
- const value = advance(p);
495
- if (![
496
- "NULL",
497
- "TRUE",
498
- "FALSE",
499
- "UNKNOWN"
500
- ].includes(value.text) || value.kind !== "word") fail$1(p, "Expected NULL, TRUE, FALSE or UNKNOWN after IS");
501
- return parsePredicate(p, start, {
502
- type: "is",
503
- expr: left,
504
- not,
505
- value: value.text === "NULL" ? "NULL" : value.text === "TRUE" ? "TRUE" : value.text === "FALSE" ? "FALSE" : "UNKNOWN",
506
- range: rangeFrom(p, start)
507
- });
531
+ };
508
532
  }
509
- if (atWord(p, "ISNULL") || atWord(p, "NOTNULL")) return parsePredicate(p, start, {
533
+ const value = advance(p);
534
+ const literal = IS_VALUES.get(value.text);
535
+ if (literal === void 0 || value.kind !== "word") fail$1(p, "Expected NULL, TRUE, FALSE or UNKNOWN after IS");
536
+ return {
510
537
  type: "is",
511
538
  expr: left,
512
- not: advance(p).text === "NOTNULL",
513
- value: "NULL",
539
+ not,
540
+ value: literal,
514
541
  range: rangeFrom(p, start)
515
- });
542
+ };
543
+ }
544
+ /** IN, BETWEEN and LIKE, each of which NOT may come before. */
545
+ function parseNegatablePredicate(p, start, left) {
516
546
  const negated = atWord(p, "NOT") && (atWord(p, "IN", 1) || atWord(p, "BETWEEN", 1) || LIKE_WORDS.has(peek(p, 1).text));
517
547
  if (negated) advance(p);
518
- if (atWord(p, "IN")) {
519
- advance(p);
520
- if (acceptPunct(p, "(")) {
521
- if (atQueryStart(p)) {
522
- const query = parseQuery(p);
523
- expectPunct(p, ")");
524
- return parsePredicate(p, start, {
525
- type: "in",
526
- expr: left,
527
- not: negated,
528
- list: null,
529
- subquery: query,
530
- range: rangeFrom(p, start)
531
- });
532
- }
533
- const list = atPunct(p, ")") ? [] : parseExprList(p);
534
- expectPunct(p, ")");
535
- return parsePredicate(p, start, {
536
- type: "in",
537
- expr: left,
538
- not: negated,
539
- list,
540
- subquery: null,
541
- range: rangeFrom(p, start)
542
- });
543
- }
544
- return parsePredicate(p, start, {
545
- type: "in",
546
- expr: left,
547
- not: negated,
548
- list: [parseConcat(p)],
549
- subquery: null,
550
- range: rangeFrom(p, start)
551
- });
552
- }
548
+ if (atWord(p, "IN")) return parseInPredicate(p, start, left, negated);
553
549
  if (atWord(p, "BETWEEN")) {
554
550
  advance(p);
555
551
  acceptWord(p, "SYMMETRIC");
556
552
  const low = parseConcat(p);
557
553
  expectWord(p, "AND");
558
- return parsePredicate(p, start, {
554
+ return {
559
555
  type: "between",
560
556
  expr: left,
561
557
  not: negated,
562
558
  low,
563
559
  high: parseConcat(p),
564
560
  range: rangeFrom(p, start)
565
- });
561
+ };
566
562
  }
567
563
  const like = peek(p);
568
564
  if (LIKE_WORDS.has(like.text) && like.kind === "word") {
@@ -570,17 +566,52 @@ function parsePredicate(p, start, left) {
570
566
  if (like.text === "SIMILAR") expectWord(p, "TO");
571
567
  const pattern = parseConcat(p);
572
568
  if (acceptWord(p, "ESCAPE")) parseConcat(p);
573
- return parsePredicate(p, start, {
569
+ return {
574
570
  type: "like",
575
571
  op: like.text,
576
572
  expr: left,
577
573
  not: negated,
578
574
  pattern,
579
575
  range: rangeFrom(p, start)
580
- });
576
+ };
581
577
  }
582
578
  if (negated) fail$1(p, "Expected IN, BETWEEN or LIKE after NOT");
583
- return left;
579
+ return null;
580
+ }
581
+ function parseInPredicate(p, start, left, negated) {
582
+ advance(p);
583
+ if (acceptPunct(p, "(")) {
584
+ if (atQueryStart(p)) {
585
+ const query = parseQuery(p);
586
+ expectPunct(p, ")");
587
+ return {
588
+ type: "in",
589
+ expr: left,
590
+ not: negated,
591
+ list: null,
592
+ subquery: query,
593
+ range: rangeFrom(p, start)
594
+ };
595
+ }
596
+ const list = atPunct(p, ")") ? [] : parseExprList(p);
597
+ expectPunct(p, ")");
598
+ return {
599
+ type: "in",
600
+ expr: left,
601
+ not: negated,
602
+ list,
603
+ subquery: null,
604
+ range: rangeFrom(p, start)
605
+ };
606
+ }
607
+ return {
608
+ type: "in",
609
+ expr: left,
610
+ not: negated,
611
+ list: [parseConcat(p)],
612
+ subquery: null,
613
+ range: rangeFrom(p, start)
614
+ };
584
615
  }
585
616
  function parseConcat(p) {
586
617
  const start = peek(p).start;
@@ -673,21 +704,19 @@ function atQueryStartAt(p, ahead) {
673
704
  }
674
705
  function parsePrimary(p) {
675
706
  const token = peek(p);
707
+ const parsed = parseLiteralPrimary(p, token) ?? parseGroupPrimary(p, token) ?? (token.kind === "word" ? parseKeywordPrimary(p, token) : null);
708
+ if (parsed !== null) return parsed;
709
+ if (isNameToken(token) || token.kind === "word" && !RESERVED.has(token.text)) return parseNameExpr(p);
710
+ return fail$1(p, `Unexpected ${token.kind === "eof" ? "end of statement" : `"${token.raw}"`}`);
711
+ }
712
+ /** A string, a number, a placeholder or `*`. */
713
+ function parseLiteralPrimary(p, token) {
676
714
  const start = token.start;
677
- if (token.kind === "string") {
678
- advance(p);
679
- return {
680
- type: "literal",
681
- kind: "string",
682
- value: token.text,
683
- range: rangeFrom(p, start)
684
- };
685
- }
686
- if (token.kind === "number") {
715
+ if (token.kind === "string" || token.kind === "number") {
687
716
  advance(p);
688
717
  return {
689
718
  type: "literal",
690
- kind: "number",
719
+ kind: token.kind,
691
720
  value: token.text,
692
721
  range: rangeFrom(p, start)
693
722
  };
@@ -700,26 +729,6 @@ function parsePrimary(p) {
700
729
  range: rangeFrom(p, start)
701
730
  };
702
731
  }
703
- if (token.kind === "punct" && token.text === "(") {
704
- advance(p);
705
- if (atQueryStart(p)) {
706
- const query = parseQuery(p);
707
- expectPunct(p, ")");
708
- return {
709
- type: "subquery",
710
- query,
711
- range: rangeFrom(p, start)
712
- };
713
- }
714
- const items = parseExprList(p);
715
- expectPunct(p, ")");
716
- const single = items[0];
717
- return items.length === 1 && single !== void 0 ? single : {
718
- type: "list",
719
- items,
720
- range: rangeFrom(p, start)
721
- };
722
- }
723
732
  if (token.kind === "op" && token.text === "*") {
724
733
  advance(p);
725
734
  return {
@@ -728,7 +737,35 @@ function parsePrimary(p) {
728
737
  range: rangeFrom(p, start)
729
738
  };
730
739
  }
731
- if (token.kind === "word") switch (token.text) {
740
+ return null;
741
+ }
742
+ /** `(...)`: a subquery, one expression in parentheses, or a list of them. */
743
+ function parseGroupPrimary(p, token) {
744
+ if (token.kind !== "punct" || token.text !== "(") return null;
745
+ const start = token.start;
746
+ advance(p);
747
+ if (atQueryStart(p)) {
748
+ const query = parseQuery(p);
749
+ expectPunct(p, ")");
750
+ return {
751
+ type: "subquery",
752
+ query,
753
+ range: rangeFrom(p, start)
754
+ };
755
+ }
756
+ const items = parseExprList(p);
757
+ expectPunct(p, ")");
758
+ const single = items[0];
759
+ return items.length === 1 && single !== void 0 ? single : {
760
+ type: "list",
761
+ items,
762
+ range: rangeFrom(p, start)
763
+ };
764
+ }
765
+ /** What a keyword starts: NULL, TRUE, CASE, CAST, EXISTS, NOT, a typed literal, an ARRAY[...]. */
766
+ function parseKeywordPrimary(p, token) {
767
+ const start = token.start;
768
+ switch (token.text) {
732
769
  case "NULL":
733
770
  advance(p);
734
771
  return {
@@ -771,43 +808,46 @@ function parsePrimary(p) {
771
808
  case "INTERVAL":
772
809
  case "DATE":
773
810
  case "TIME":
774
- case "TIMESTAMP":
775
- if (peek(p, 1).kind === "string") {
776
- advance(p);
777
- const literal = advance(p);
778
- return {
779
- type: "cast",
780
- expr: {
781
- type: "literal",
782
- kind: "string",
783
- value: literal.text,
784
- range: {
785
- start: literal.start,
786
- end: literal.end
787
- }
788
- },
789
- to: token.raw,
790
- range: rangeFrom(p, start)
791
- };
792
- }
793
- break;
794
- case "ARRAY": if (atPunct(p, "[", 1)) {
795
- advance(p);
796
- advance(p);
797
- const items = atPunct(p, "]") ? [] : parseExprList(p);
798
- expectPunct(p, "]");
799
- return {
800
- type: "call",
801
- name: "array",
802
- args: items,
803
- distinct: false,
804
- over: null,
805
- range: rangeFrom(p, start)
806
- };
807
- }
811
+ case "TIMESTAMP": return parseTypedLiteral(p, token);
812
+ case "ARRAY": return parseArrayLiteral(p, token);
813
+ default: return null;
808
814
  }
809
- if (isNameToken(token) || token.kind === "word" && !RESERVED.has(token.text)) return parseNameExpr(p);
810
- return fail$1(p, `Unexpected ${token.kind === "eof" ? "end of statement" : `"${token.raw}"`}`);
815
+ }
816
+ /** `DATE '2024-01-01'`, `INTERVAL '1 day'`: a typed literal. */
817
+ function parseTypedLiteral(p, token) {
818
+ if (peek(p, 1).kind !== "string") return null;
819
+ advance(p);
820
+ const literal = advance(p);
821
+ return {
822
+ type: "cast",
823
+ expr: {
824
+ type: "literal",
825
+ kind: "string",
826
+ value: literal.text,
827
+ range: {
828
+ start: literal.start,
829
+ end: literal.end
830
+ }
831
+ },
832
+ to: token.raw,
833
+ range: rangeFrom(p, token.start)
834
+ };
835
+ }
836
+ /** `ARRAY[1, 2]`. */
837
+ function parseArrayLiteral(p, token) {
838
+ if (!atPunct(p, "[", 1)) return null;
839
+ advance(p);
840
+ advance(p);
841
+ const items = atPunct(p, "]") ? [] : parseExprList(p);
842
+ expectPunct(p, "]");
843
+ return {
844
+ type: "call",
845
+ name: "array",
846
+ args: items,
847
+ distinct: false,
848
+ over: null,
849
+ range: rangeFrom(p, token.start)
850
+ };
811
851
  }
812
852
  /** `a`, `a.b`, `a.b.c`, `a.*` or a function call `f(...)`. */
813
853
  function parseNameExpr(p) {
@@ -836,26 +876,30 @@ function parseNameExpr(p) {
836
876
  range: rangeFrom(p, start)
837
877
  };
838
878
  }
879
+ /** The arguments of a call up to its `ORDER BY` / `SEPARATOR` / `)`: `*`, or expressions. */
880
+ function parseCallArguments(p, start) {
881
+ if (atOp(p, "*")) {
882
+ advance(p);
883
+ return [{
884
+ type: "star",
885
+ table: null,
886
+ range: rangeFrom(p, start)
887
+ }];
888
+ }
889
+ const args = [parseOr(p)];
890
+ while (acceptPunct(p, ",") || atWord(p, "FROM") || atWord(p, "FOR")) {
891
+ if (atWord(p, "FROM") || atWord(p, "FOR")) advance(p);
892
+ args.push(parseOr(p));
893
+ }
894
+ return args;
895
+ }
839
896
  function parseCall(p, start, name) {
840
897
  expectPunct(p, "(");
841
898
  const distinct = acceptWord(p, "DISTINCT");
842
899
  if (!distinct) acceptWord(p, "ALL");
843
900
  const args = [];
844
901
  if (!atPunct(p, ")")) {
845
- if (atOp(p, "*")) {
846
- advance(p);
847
- args.push({
848
- type: "star",
849
- table: null,
850
- range: rangeFrom(p, start)
851
- });
852
- } else {
853
- args.push(parseOr(p));
854
- while (acceptPunct(p, ",") || atWord(p, "FROM") || atWord(p, "FOR")) {
855
- if (atWord(p, "FROM") || atWord(p, "FOR")) advance(p);
856
- args.push(parseOr(p));
857
- }
858
- }
902
+ args.push(...parseCallArguments(p, start));
859
903
  if (acceptWords(p, "ORDER", "BY")) parseOrderItems(p);
860
904
  if (acceptWord(p, "SEPARATOR")) parseOr(p);
861
905
  }
@@ -951,12 +995,16 @@ function parseCast(p) {
951
995
  range: rangeFrom(p, start)
952
996
  };
953
997
  }
998
+ function parseDirection(p) {
999
+ if (acceptWord(p, "ASC")) return "ASC";
1000
+ return acceptWord(p, "DESC") ? "DESC" : null;
1001
+ }
954
1002
  function parseOrderItems(p) {
955
1003
  const items = [];
956
1004
  do {
957
1005
  const start = peek(p).start;
958
1006
  const expr = parseOr(p);
959
- const direction = acceptWord(p, "ASC") ? "ASC" : acceptWord(p, "DESC") ? "DESC" : null;
1007
+ const direction = parseDirection(p);
960
1008
  if (acceptWord(p, "NULLS") && !acceptWord(p, "FIRST") && !acceptWord(p, "LAST")) fail$1(p, "Expected FIRST or LAST");
961
1009
  items.push({
962
1010
  expr,
@@ -1033,41 +1081,38 @@ function parseLimit(p) {
1033
1081
  }
1034
1082
  if (acceptWord(p, "OFFSET")) {
1035
1083
  const offset = parseOffsetValue(p);
1036
- if (acceptWord(p, "FETCH")) {
1037
- if (!acceptWord(p, "FIRST") && !acceptWord(p, "NEXT")) fail$1(p, "Expected FIRST or NEXT");
1038
- const limit = atWord(p, "ROW") || atWord(p, "ROWS") ? null : parseOr(p);
1039
- if (!acceptWord(p, "ROWS") && !acceptWord(p, "ROW")) fail$1(p, "Expected ROWS");
1040
- expectWord(p, "ONLY");
1041
- return {
1042
- limit,
1043
- offset
1044
- };
1045
- }
1046
- return {
1047
- limit: acceptWord(p, "LIMIT") ? parseOr(p) : null,
1084
+ if (acceptWord(p, "FETCH")) return {
1085
+ limit: parseFetchCount(p),
1048
1086
  offset
1049
1087
  };
1050
- }
1051
- if (acceptWord(p, "FETCH")) {
1052
- if (!acceptWord(p, "FIRST") && !acceptWord(p, "NEXT")) fail$1(p, "Expected FIRST or NEXT");
1053
- const limit = atWord(p, "ROW") || atWord(p, "ROWS") ? null : parseOr(p);
1054
- if (!acceptWord(p, "ROWS") && !acceptWord(p, "ROW")) fail$1(p, "Expected ROWS");
1055
- expectWord(p, "ONLY");
1056
1088
  return {
1057
- limit,
1058
- offset: null
1089
+ limit: acceptWord(p, "LIMIT") ? parseOr(p) : null,
1090
+ offset
1059
1091
  };
1060
1092
  }
1093
+ if (acceptWord(p, "FETCH")) return {
1094
+ limit: parseFetchCount(p),
1095
+ offset: null
1096
+ };
1061
1097
  return {
1062
1098
  limit: null,
1063
1099
  offset: null
1064
1100
  };
1065
1101
  }
1102
+ /** `FETCH FIRST n ROWS ONLY`, after FETCH: the count, null when it is left out. */
1103
+ function parseFetchCount(p) {
1104
+ if (!acceptWord(p, "FIRST") && !acceptWord(p, "NEXT")) fail$1(p, "Expected FIRST or NEXT");
1105
+ const limit = atWord(p, "ROW") || atWord(p, "ROWS") ? null : parseOr(p);
1106
+ if (!acceptWord(p, "ROWS") && !acceptWord(p, "ROW")) fail$1(p, "Expected ROWS");
1107
+ expectWord(p, "ONLY");
1108
+ return limit;
1109
+ }
1066
1110
  function parseOffsetValue(p) {
1067
1111
  const value = parseOr(p);
1068
1112
  if (!acceptWord(p, "ROWS")) acceptWord(p, "ROW");
1069
1113
  return value;
1070
1114
  }
1115
+ const SET_OPERATOR_OF = /* @__PURE__ */ new Map([["UNION", "UNION"], ["INTERSECT", "INTERSECT"]]);
1071
1116
  function parseSetOperation(p) {
1072
1117
  const start = peek(p).start;
1073
1118
  const left = parseQueryTerm(p);
@@ -1078,7 +1123,7 @@ function parseSetOperation(p) {
1078
1123
  if (!all) acceptWord(p, "DISTINCT");
1079
1124
  return {
1080
1125
  type: "setop",
1081
- op: token.text === "UNION" ? "UNION" : token.text === "INTERSECT" ? "INTERSECT" : "EXCEPT",
1126
+ op: SET_OPERATOR_OF.get(token.text) ?? "EXCEPT",
1082
1127
  all,
1083
1128
  left,
1084
1129
  right: parseSetOperation(p),
@@ -1204,10 +1249,16 @@ function parseJoinTail(p, start, left) {
1204
1249
  range: rangeFrom(p, start)
1205
1250
  });
1206
1251
  }
1252
+ const JOIN_TYPE_OF = /* @__PURE__ */ new Map([
1253
+ ["LEFT", "LEFT"],
1254
+ ["RIGHT", "RIGHT"],
1255
+ ["FULL", "FULL"],
1256
+ ["CROSS", "CROSS"]
1257
+ ]);
1207
1258
  function parseJoinType(p) {
1208
1259
  if (acceptWord(p, "JOIN")) return "INNER";
1209
1260
  const word = advance(p);
1210
- const type = word.text === "LEFT" ? "LEFT" : word.text === "RIGHT" ? "RIGHT" : word.text === "FULL" ? "FULL" : word.text === "CROSS" ? "CROSS" : "INNER";
1261
+ const type = JOIN_TYPE_OF.get(word.text) ?? "INNER";
1211
1262
  if (word.text !== "INNER" && word.text !== "CROSS" && word.text !== "LEFT" && word.text !== "RIGHT" && word.text !== "FULL") fail$1(p, "Expected JOIN");
1212
1263
  acceptWord(p, "OUTER");
1213
1264
  expectWord(p, "JOIN");
@@ -1326,17 +1377,20 @@ function parseInsert(p, start, ctes) {
1326
1377
  }
1327
1378
  /** `ON CONFLICT ... DO NOTHING | DO UPDATE SET ...` and MySQL's `ON DUPLICATE KEY UPDATE ...`, kept as a range. */
1328
1379
  function skipConflictClause(p, start) {
1329
- while (!atWord(p, "RETURNING") && !atPunct(p, ";") && peek(p).kind !== "eof") if (atPunct(p, "(")) {
1330
- advance(p);
1331
- let depth = 1;
1332
- while (depth > 0 && peek(p).kind !== "eof") {
1333
- if (atPunct(p, "(")) depth += 1;
1334
- if (atPunct(p, ")")) depth -= 1;
1335
- advance(p);
1336
- }
1337
- } else advance(p);
1380
+ while (!atWord(p, "RETURNING") && !atPunct(p, ";") && peek(p).kind !== "eof") if (atPunct(p, "(")) skipParenthesized(p);
1381
+ else advance(p);
1338
1382
  return rangeFrom(p, start);
1339
1383
  }
1384
+ /** From an opening `(` past its matching `)`, whatever it holds. */
1385
+ function skipParenthesized(p) {
1386
+ advance(p);
1387
+ let depth = 1;
1388
+ while (depth > 0 && peek(p).kind !== "eof") {
1389
+ if (atPunct(p, "(")) depth += 1;
1390
+ if (atPunct(p, ")")) depth -= 1;
1391
+ advance(p);
1392
+ }
1393
+ }
1340
1394
  function parseUpdate(p, start, ctes) {
1341
1395
  advance(p);
1342
1396
  if (acceptWord(p, "OR")) advance(p);
@@ -1405,29 +1459,7 @@ function parseDelete(p, start, ctes) {
1405
1459
  function parseStatement(p) {
1406
1460
  const start = peek(p).start;
1407
1461
  const first = peek(p);
1408
- if (isWord(first, "WITH") || isWord(first, "SELECT") || isWord(first, "VALUES") || atPunct(p, "(")) {
1409
- const { ctes, recursive } = parseWith(p);
1410
- if (ctes.length > 0 && (atWord(p, "INSERT") || atWord(p, "REPLACE"))) return parseInsert(p, start, ctes);
1411
- if (ctes.length > 0 && atWord(p, "UPDATE")) return parseUpdate(p, start, ctes);
1412
- if (ctes.length > 0 && atWord(p, "DELETE")) return parseDelete(p, start, ctes);
1413
- const body = parseSetOperation(p);
1414
- const orderBy = acceptWords(p, "ORDER", "BY") ? parseOrderItems(p) : [];
1415
- const { limit, offset } = parseLimit(p);
1416
- return {
1417
- type: "select",
1418
- query: {
1419
- type: "query",
1420
- ctes,
1421
- recursive,
1422
- body,
1423
- orderBy,
1424
- limit,
1425
- offset,
1426
- range: rangeFrom(p, start)
1427
- },
1428
- range: rangeFrom(p, start)
1429
- };
1430
- }
1462
+ if (isWord(first, "WITH") || isWord(first, "SELECT") || isWord(first, "VALUES") || atPunct(p, "(")) return parseQueryStatement(p, start);
1431
1463
  if (isWord(first, "INSERT") || isWord(first, "REPLACE")) return parseInsert(p, start, []);
1432
1464
  if (isWord(first, "UPDATE")) return parseUpdate(p, start, []);
1433
1465
  if (isWord(first, "DELETE")) return parseDelete(p, start, []);
@@ -1439,6 +1471,32 @@ function parseStatement(p) {
1439
1471
  range: rangeFrom(p, start)
1440
1472
  };
1441
1473
  }
1474
+ /** A SELECT, or a DML statement after a WITH. */
1475
+ function parseQueryStatement(p, start) {
1476
+ const { ctes, recursive } = parseWith(p);
1477
+ if (ctes.length > 0) {
1478
+ if (atWord(p, "INSERT") || atWord(p, "REPLACE")) return parseInsert(p, start, ctes);
1479
+ if (atWord(p, "UPDATE")) return parseUpdate(p, start, ctes);
1480
+ if (atWord(p, "DELETE")) return parseDelete(p, start, ctes);
1481
+ }
1482
+ const body = parseSetOperation(p);
1483
+ const orderBy = acceptWords(p, "ORDER", "BY") ? parseOrderItems(p) : [];
1484
+ const { limit, offset } = parseLimit(p);
1485
+ return {
1486
+ type: "select",
1487
+ query: {
1488
+ type: "query",
1489
+ ctes,
1490
+ recursive,
1491
+ body,
1492
+ orderBy,
1493
+ limit,
1494
+ offset,
1495
+ range: rangeFrom(p, start)
1496
+ },
1497
+ range: rangeFrom(p, start)
1498
+ };
1499
+ }
1442
1500
  function skipToStatementEnd(p) {
1443
1501
  let depth = 0;
1444
1502
  while (peek(p).kind !== "eof" && !(depth === 0 && atPunct(p, ";"))) {
@@ -1905,8 +1963,18 @@ const DATE_FUNCTIONS = /* @__PURE__ */ new Set([
1905
1963
  "last_day",
1906
1964
  "makedate"
1907
1965
  ]);
1966
+ const DATE_TYPES = {
1967
+ sqlite: "TEXT",
1968
+ mysql: "datetime",
1969
+ postgresql: "timestamp"
1970
+ };
1971
+ const JSON_TYPES = {
1972
+ sqlite: "TEXT",
1973
+ mysql: "json",
1974
+ postgresql: "jsonb"
1975
+ };
1908
1976
  function dateType(ctx, nullable, sources) {
1909
- const dataType = ctx.dialect === "sqlite" ? "TEXT" : ctx.dialect === "mysql" ? "datetime" : "timestamp";
1977
+ const dataType = DATE_TYPES[ctx.dialect];
1910
1978
  return {
1911
1979
  dataType,
1912
1980
  tsType: toTsType(ctx.dialect, dataType),
@@ -1923,172 +1991,113 @@ function hasAggregate(expr) {
1923
1991
  if (isAggregateCall(expr)) return true;
1924
1992
  return childExpressions(expr).some(hasAggregate);
1925
1993
  }
1994
+ const LEAVES = /* @__PURE__ */ new Set([
1995
+ "column",
1996
+ "star",
1997
+ "literal",
1998
+ "param",
1999
+ "exists",
2000
+ "subquery",
2001
+ "raw"
2002
+ ]);
2003
+ function isLeaf(expr) {
2004
+ return LEAVES.has(expr.type);
2005
+ }
2006
+ const PREDICATES = /* @__PURE__ */ new Set([
2007
+ "in",
2008
+ "between",
2009
+ "like",
2010
+ "is",
2011
+ "exists"
2012
+ ]);
2013
+ function isPredicate(expr) {
2014
+ return PREDICATES.has(expr.type);
2015
+ }
2016
+ const OPAQUE = /* @__PURE__ */ new Set([
2017
+ "star",
2018
+ "param",
2019
+ "raw"
2020
+ ]);
2021
+ function isOpaque(expr) {
2022
+ return OPAQUE.has(expr.type);
2023
+ }
1926
2024
  function childExpressions(expr) {
1927
- switch (expr.type) {
1928
- case "binary": return [expr.left, expr.right];
1929
- case "unary": return [expr.operand];
1930
- case "call": return [
1931
- ...expr.args,
1932
- ...expr.over?.partitionBy ?? [],
1933
- ...expr.over?.orderBy.map((item) => item.expr) ?? []
1934
- ];
1935
- case "cast": return [expr.expr];
1936
- case "case": return [
1937
- ...expr.operand === null ? [] : [expr.operand],
1938
- ...expr.whens.flatMap((branch) => [branch.when, branch.result]),
1939
- ...expr.otherwise === null ? [] : [expr.otherwise]
1940
- ];
1941
- case "in": return [expr.expr, ...expr.list ?? []];
1942
- case "between": return [
1943
- expr.expr,
1944
- expr.low,
1945
- expr.high
1946
- ];
1947
- case "like": return [expr.expr, expr.pattern];
1948
- case "is": return [expr.expr];
1949
- case "list": return expr.items;
1950
- case "column":
1951
- case "star":
1952
- case "literal":
1953
- case "param":
1954
- case "exists":
1955
- case "subquery":
1956
- case "raw": return [];
1957
- default: return [];
1958
- }
2025
+ return isLeaf(expr) ? [] : branchChildren(expr);
2026
+ }
2027
+ function branchChildren(expr) {
2028
+ if (expr.type === "binary") return [expr.left, expr.right];
2029
+ if (expr.type === "unary") return [expr.operand];
2030
+ if (expr.type === "call") return callChildren(expr);
2031
+ if (expr.type === "cast" || expr.type === "is") return [expr.expr];
2032
+ if (expr.type === "case") return caseChildren(expr);
2033
+ if (expr.type === "in") return [expr.expr, ...expr.list ?? []];
2034
+ if (expr.type === "between") return [
2035
+ expr.expr,
2036
+ expr.low,
2037
+ expr.high
2038
+ ];
2039
+ if (expr.type === "like") return [expr.expr, expr.pattern];
2040
+ return expr.items;
2041
+ }
2042
+ function callChildren(expr) {
2043
+ return [
2044
+ ...expr.args,
2045
+ ...expr.over?.partitionBy ?? [],
2046
+ ...expr.over?.orderBy.map((item) => item.expr) ?? []
2047
+ ];
2048
+ }
2049
+ function caseChildren(expr) {
2050
+ return [
2051
+ ...expr.operand === null ? [] : [expr.operand],
2052
+ ...expr.whens.flatMap((branch) => [branch.when, branch.result]),
2053
+ ...expr.otherwise === null ? [] : [expr.otherwise]
2054
+ ];
1959
2055
  }
1960
2056
  /** The subqueries nested directly in an expression (not those inside deeper subqueries). */
1961
2057
  function subqueriesOf(expr) {
1962
- switch (expr.type) {
1963
- case "exists": return [expr.query];
1964
- case "subquery": return [expr.query];
1965
- case "in": return [
1966
- ...expr.subquery === null ? [] : [expr.subquery],
1967
- ...expr.expr.type === "column" ? [] : subqueriesOf(expr.expr),
1968
- ...(expr.list ?? []).flatMap(subqueriesOf)
1969
- ];
1970
- case "column":
1971
- case "star":
1972
- case "literal":
1973
- case "param":
1974
- case "binary":
1975
- case "unary":
1976
- case "call":
1977
- case "cast":
1978
- case "case":
1979
- case "between":
1980
- case "like":
1981
- case "is":
1982
- case "list":
1983
- case "raw": return childExpressions(expr).flatMap(subqueriesOf);
1984
- default: return [];
1985
- }
2058
+ if (expr.type === "exists" || expr.type === "subquery") return [expr.query];
2059
+ if (expr.type === "in") return [
2060
+ ...expr.subquery === null ? [] : [expr.subquery],
2061
+ ...expr.expr.type === "column" ? [] : subqueriesOf(expr.expr),
2062
+ ...(expr.list ?? []).flatMap(subqueriesOf)
2063
+ ];
2064
+ return childExpressions(expr).flatMap(subqueriesOf);
1986
2065
  }
1987
2066
  function typeOf(t, expr) {
1988
- const { ctx } = t;
2067
+ if (isPredicate(expr)) return typeOfPredicate(t, expr);
2068
+ if (isOpaque(expr)) return UNKNOWN;
1989
2069
  switch (expr.type) {
1990
- case "column": return resolveColumn(ctx, t.scope, expr.table, expr.name, expr.range, t.aliases);
1991
- case "star": return UNKNOWN;
1992
- case "literal":
1993
- if (expr.kind === "null") return {
1994
- dataType: null,
1995
- tsType: "null",
1996
- nullable: true,
1997
- sources: []
1998
- };
1999
- return {
2000
- dataType: literalDataType(ctx.dialect, expr.kind),
2001
- tsType: expr.kind === "boolean" ? toTsType(ctx.dialect, literalDataType(ctx.dialect, "boolean")) : expr.kind,
2002
- nullable: false,
2003
- sources: []
2004
- };
2005
- case "param": return UNKNOWN;
2006
- case "binary": {
2007
- const left = typeOf(t, expr.left);
2008
- const right = typeOf(t, expr.right);
2009
- const sources = sourcesOf(left, right);
2010
- const nullable = nullableOr(left, right);
2011
- if (expr.op === "AND" || expr.op === "OR" || expr.op.startsWith("IS ")) return booleanType(ctx, nullable, sources);
2012
- if ([
2013
- "=",
2014
- "<>",
2015
- "!=",
2016
- "<",
2017
- ">",
2018
- "<=",
2019
- ">=",
2020
- "<=>",
2021
- "~",
2022
- "!~",
2023
- "~*",
2024
- "!~*",
2025
- "@>",
2026
- "<@"
2027
- ].includes(expr.op)) return booleanType(ctx, nullable, sources);
2028
- if (expr.op === "||") return stringType(ctx, nullable, sources);
2029
- if (expr.op === "->" || expr.op === "#>") return {
2030
- ...UNKNOWN,
2031
- nullable: true,
2032
- sources
2033
- };
2034
- if (expr.op === "->>" || expr.op === "#>>") return stringType(ctx, true, sources);
2035
- if (expr.op === "[]") return {
2036
- ...UNKNOWN,
2037
- nullable: true,
2038
- sources
2039
- };
2040
- if ([
2041
- "+",
2042
- "-",
2043
- "*",
2044
- "/",
2045
- "%",
2046
- "^",
2047
- "**"
2048
- ].includes(expr.op)) {
2049
- const dated = [left, right].find((side) => side.tsType === "Date");
2050
- return dated === void 0 ? numberType(ctx, nullable, sources) : {
2051
- ...dated,
2052
- nullable,
2053
- sources
2054
- };
2055
- }
2056
- return {
2057
- ...UNKNOWN,
2058
- nullable,
2059
- sources
2060
- };
2061
- }
2062
- case "unary": {
2063
- const operand = typeOf(t, expr.operand);
2064
- if (expr.op === "NOT" || expr.op === "!") return booleanType(ctx, operand.nullable, operand.sources);
2065
- return {
2066
- ...operand,
2067
- tsType: operand.tsType === "unknown" ? "number" : operand.tsType
2068
- };
2069
- }
2070
+ case "column": return resolveColumn(t.ctx, t.scope, expr.table, expr.name, expr.range, t.aliases);
2071
+ case "literal": return typeOfLiteral(t.ctx, expr);
2072
+ case "binary": return typeOfBinary(t, expr);
2073
+ case "unary": return typeOfUnary(t, expr);
2070
2074
  case "call": return typeOfCall(t, expr);
2071
2075
  case "cast": {
2072
2076
  const inner = typeOf(t, expr.expr);
2073
2077
  return {
2074
2078
  dataType: expr.to,
2075
- tsType: toTsType(ctx.dialect, expr.to),
2079
+ tsType: toTsType(t.ctx.dialect, expr.to),
2076
2080
  nullable: inner.nullable,
2077
2081
  sources: inner.sources
2078
2082
  };
2079
2083
  }
2080
- case "case": {
2081
- const branches = expr.whens.map((branch) => typeOf(t, branch.result));
2082
- const otherwise = expr.otherwise === null ? null : typeOf(t, expr.otherwise);
2083
- const all = [...branches, ...otherwise === null ? [] : [otherwise]];
2084
- const typed = all.find((branch) => branch.tsType !== "null" && branch.tsType !== "unknown") ?? all[0] ?? UNKNOWN;
2085
- const conditions = [...expr.operand === null ? [] : [typeOf(t, expr.operand)], ...expr.whens.map((branch) => typeOf(t, branch.when))];
2084
+ case "case": return typeOfCase(t, expr);
2085
+ case "subquery": return typeOfSubquery(t, expr);
2086
+ case "list": {
2087
+ const items = expr.items.map((item) => typeOf(t, item));
2086
2088
  return {
2087
- ...typed,
2088
- nullable: otherwise === null ? true : nullableOr(...all),
2089
- sources: sourcesOf(...all, ...conditions)
2089
+ ...UNKNOWN,
2090
+ nullable: nullableOr(...items),
2091
+ sources: sourcesOf(...items)
2090
2092
  };
2091
2093
  }
2094
+ default: return UNKNOWN;
2095
+ }
2096
+ }
2097
+ /** IN, BETWEEN, LIKE, IS and EXISTS, which are booleans. */
2098
+ function typeOfPredicate(t, expr) {
2099
+ const { ctx } = t;
2100
+ switch (expr.type) {
2092
2101
  case "in": {
2093
2102
  const left = typeOf(t, expr.expr);
2094
2103
  const items = (expr.list ?? []).map((item) => typeOf(t, item));
@@ -2108,66 +2117,200 @@ function typeOf(t, expr) {
2108
2117
  }
2109
2118
  case "is": return booleanType(ctx, false, typeOf(t, expr.expr).sources);
2110
2119
  case "exists": return booleanType(ctx, false, []);
2111
- case "subquery": {
2112
- const built = buildQuery(ctx, expr.query, t.scope, "subquery");
2113
- const target = t.lookups.get(expr.query);
2114
- if (target !== void 0) addEdge(ctx, built.nodeId, target, "scalar", "lookup");
2115
- const first = built.columns[0];
2116
- return first === void 0 ? UNKNOWN : {
2117
- ...first,
2118
- nullable: true
2119
- };
2120
- }
2121
- case "list": {
2122
- const items = expr.items.map((item) => typeOf(t, item));
2123
- return {
2124
- ...UNKNOWN,
2125
- nullable: nullableOr(...items),
2126
- sources: sourcesOf(...items)
2127
- };
2128
- }
2129
- case "raw": return UNKNOWN;
2130
2120
  default: return UNKNOWN;
2131
2121
  }
2132
2122
  }
2133
- function typeOfCall(t, expr) {
2123
+ function typeOfLiteral(ctx, expr) {
2124
+ if (expr.kind === "null") return {
2125
+ dataType: null,
2126
+ tsType: "null",
2127
+ nullable: true,
2128
+ sources: []
2129
+ };
2130
+ return {
2131
+ dataType: literalDataType(ctx.dialect, expr.kind),
2132
+ tsType: expr.kind === "boolean" ? toTsType(ctx.dialect, literalDataType(ctx.dialect, "boolean")) : expr.kind,
2133
+ nullable: false,
2134
+ sources: []
2135
+ };
2136
+ }
2137
+ const COMPARISON_OPERATORS = /* @__PURE__ */ new Set([
2138
+ "=",
2139
+ "<>",
2140
+ "!=",
2141
+ "<",
2142
+ ">",
2143
+ "<=",
2144
+ ">=",
2145
+ "<=>",
2146
+ "~",
2147
+ "!~",
2148
+ "~*",
2149
+ "!~*",
2150
+ "@>",
2151
+ "<@"
2152
+ ]);
2153
+ const ARITHMETIC_OPERATORS = /* @__PURE__ */ new Set([
2154
+ "+",
2155
+ "-",
2156
+ "*",
2157
+ "/",
2158
+ "%",
2159
+ "^",
2160
+ "**"
2161
+ ]);
2162
+ function typeOfBinary(t, expr) {
2134
2163
  const { ctx } = t;
2135
- const name = expr.name.toLowerCase().split(".").at(-1) ?? "";
2136
- const args = expr.args.filter((arg) => arg.type !== "star").map((arg) => typeOf(t, arg));
2137
- const sources = sourcesOf(...args);
2138
- const argNullable = nullableOr(...args);
2139
- if (name === "count") return numberType(ctx, false, sources);
2140
- if (name === "coalesce" || name === "ifnull" || name === "nvl" || name === "isnull" && args.length === 2) {
2141
- const typed = args.find((arg) => arg.tsType !== "null" && arg.tsType !== "unknown") ?? args[0] ?? UNKNOWN;
2142
- const nullable = args.length === 0 ? null : args.every((arg) => arg.nullable === true) ? true : args.some((arg) => arg.nullable === false) ? false : null;
2143
- return {
2144
- ...typed,
2164
+ const left = typeOf(t, expr.left);
2165
+ const right = typeOf(t, expr.right);
2166
+ const sources = sourcesOf(left, right);
2167
+ const nullable = nullableOr(left, right);
2168
+ if (expr.op === "AND" || expr.op === "OR" || expr.op.startsWith("IS ")) return booleanType(ctx, nullable, sources);
2169
+ if (COMPARISON_OPERATORS.has(expr.op)) return booleanType(ctx, nullable, sources);
2170
+ if (expr.op === "||") return stringType(ctx, nullable, sources);
2171
+ if (expr.op === "->" || expr.op === "#>") return {
2172
+ ...UNKNOWN,
2173
+ nullable: true,
2174
+ sources
2175
+ };
2176
+ if (expr.op === "->>" || expr.op === "#>>") return stringType(ctx, true, sources);
2177
+ if (expr.op === "[]") return {
2178
+ ...UNKNOWN,
2179
+ nullable: true,
2180
+ sources
2181
+ };
2182
+ if (ARITHMETIC_OPERATORS.has(expr.op)) {
2183
+ const dated = [left, right].find((side) => side.tsType === "Date");
2184
+ return dated === void 0 ? numberType(ctx, nullable, sources) : {
2185
+ ...dated,
2145
2186
  nullable,
2146
2187
  sources
2147
2188
  };
2148
2189
  }
2190
+ return {
2191
+ ...UNKNOWN,
2192
+ nullable,
2193
+ sources
2194
+ };
2195
+ }
2196
+ function typeOfUnary(t, expr) {
2197
+ const operand = typeOf(t, expr.operand);
2198
+ if (expr.op === "NOT" || expr.op === "!") return booleanType(t.ctx, operand.nullable, operand.sources);
2199
+ return {
2200
+ ...operand,
2201
+ tsType: operand.tsType === "unknown" ? "number" : operand.tsType
2202
+ };
2203
+ }
2204
+ function typeOfCase(t, expr) {
2205
+ const branches = expr.whens.map((branch) => typeOf(t, branch.result));
2206
+ const otherwise = expr.otherwise === null ? null : typeOf(t, expr.otherwise);
2207
+ const all = [...branches, ...otherwise === null ? [] : [otherwise]];
2208
+ const typed = all.find((branch) => branch.tsType !== "null" && branch.tsType !== "unknown") ?? all[0] ?? UNKNOWN;
2209
+ const conditions = [...expr.operand === null ? [] : [typeOf(t, expr.operand)], ...expr.whens.map((branch) => typeOf(t, branch.when))];
2210
+ return {
2211
+ ...typed,
2212
+ nullable: otherwise === null ? true : nullableOr(...all),
2213
+ sources: sourcesOf(...all, ...conditions)
2214
+ };
2215
+ }
2216
+ function typeOfSubquery(t, expr) {
2217
+ const built = buildQuery(t.ctx, expr.query, t.scope, "subquery");
2218
+ const target = t.lookups.get(expr.query);
2219
+ if (target !== void 0) addEdge(t.ctx, built.nodeId, target, "scalar", "lookup");
2220
+ const first = built.columns[0];
2221
+ return first === void 0 ? UNKNOWN : {
2222
+ ...first,
2223
+ nullable: true
2224
+ };
2225
+ }
2226
+ function typeOfCall(t, expr) {
2227
+ const name = expr.name.toLowerCase().split(".").at(-1) ?? "";
2228
+ const args = expr.args.filter((arg) => arg.type !== "star").map((arg) => typeOf(t, arg));
2229
+ const call = {
2230
+ ctx: t.ctx,
2231
+ name,
2232
+ args,
2233
+ sources: sourcesOf(...args),
2234
+ argNullable: nullableOr(...args),
2235
+ windowed: expr.over !== null
2236
+ };
2237
+ return coalescedType(call) ?? conditionalType(call) ?? pickedType(call) ?? aggregatedType(call) ?? arrayType(call) ?? jsonType(call) ?? familyType(call);
2238
+ }
2239
+ const COALESCING = /* @__PURE__ */ new Set([
2240
+ "coalesce",
2241
+ "ifnull",
2242
+ "nvl"
2243
+ ]);
2244
+ /** Whether some, all or none of the arguments may be NULL, for COALESCE: null when unknown. */
2245
+ function coalescedNullable(args) {
2246
+ if (args.length === 0) return null;
2247
+ if (args.every((arg) => arg.nullable === true)) return true;
2248
+ return args.some((arg) => arg.nullable === false) ? false : null;
2249
+ }
2250
+ /** COUNT, COALESCE and its kin, NULLIF. */
2251
+ function coalescedType(call) {
2252
+ const { ctx, name, args, sources } = call;
2253
+ if (name === "count") return numberType(ctx, false, sources);
2254
+ if (COALESCING.has(name) || name === "isnull" && args.length === 2) return {
2255
+ ...args.find((arg) => arg.tsType !== "null" && arg.tsType !== "unknown") ?? args[0] ?? UNKNOWN,
2256
+ nullable: coalescedNullable(args),
2257
+ sources
2258
+ };
2149
2259
  if (name === "nullif") return {
2150
2260
  ...args[0] ?? UNKNOWN,
2151
2261
  nullable: true,
2152
2262
  sources
2153
2263
  };
2154
- if (name === "iif" || name === "if") {
2155
- const [, then, otherwise] = args;
2156
- return {
2157
- ...[then, otherwise].find((arg) => arg !== void 0 && arg.tsType !== "null" && arg.tsType !== "unknown") ?? then ?? UNKNOWN,
2158
- nullable: nullableOr(...[then, otherwise].filter((arg) => arg !== void 0)),
2159
- sources
2160
- };
2161
- }
2162
- if (name === "min" || name === "max" || name === "first_value" || name === "last_value" || name === "lag" || name === "lead" || name === "nth_value" || name === "any_value") {
2163
- const first = args[0] ?? UNKNOWN;
2164
- return {
2165
- ...first,
2166
- nullable: expr.over === null || name === "lag" || name === "lead" ? true : first.nullable,
2167
- sources
2168
- };
2169
- }
2170
- if (name === "sum" || name === "avg" || name === "stddev" || name === "variance") {
2264
+ return null;
2265
+ }
2266
+ /** IIF and IF: the type of the branch that has one. */
2267
+ function conditionalType(call) {
2268
+ const { name, args, sources } = call;
2269
+ if (name !== "iif" && name !== "if") return null;
2270
+ const [, then, otherwise] = args;
2271
+ return {
2272
+ ...[then, otherwise].find((arg) => arg !== void 0 && arg.tsType !== "null" && arg.tsType !== "unknown") ?? then ?? UNKNOWN,
2273
+ nullable: nullableOr(...[then, otherwise].filter((arg) => arg !== void 0)),
2274
+ sources
2275
+ };
2276
+ }
2277
+ const PICKING = /* @__PURE__ */ new Set([
2278
+ "min",
2279
+ "max",
2280
+ "first_value",
2281
+ "last_value",
2282
+ "lag",
2283
+ "lead",
2284
+ "nth_value",
2285
+ "any_value"
2286
+ ]);
2287
+ /** MIN, MAX and the window functions that pick one of the values: the type of the value. */
2288
+ function pickedType(call) {
2289
+ const { name, args, sources, windowed } = call;
2290
+ if (!PICKING.has(name)) return null;
2291
+ const first = args[0] ?? UNKNOWN;
2292
+ return {
2293
+ ...first,
2294
+ nullable: !windowed || name === "lag" || name === "lead" ? true : first.nullable,
2295
+ sources
2296
+ };
2297
+ }
2298
+ const AVERAGING = /* @__PURE__ */ new Set([
2299
+ "sum",
2300
+ "avg",
2301
+ "stddev",
2302
+ "variance"
2303
+ ]);
2304
+ const RANKING = /* @__PURE__ */ new Set([
2305
+ "row_number",
2306
+ "rank",
2307
+ "dense_rank",
2308
+ "ntile"
2309
+ ]);
2310
+ /** SUM, AVG and the like, and the ranking window functions. */
2311
+ function aggregatedType(call) {
2312
+ const { ctx, name, args, sources } = call;
2313
+ if (AVERAGING.has(name)) {
2171
2314
  const first = args[0] ?? UNKNOWN;
2172
2315
  return {
2173
2316
  ...first.tsType === "string" && ctx.dialect !== "sqlite" ? first : numberType(ctx, true, sources),
@@ -2175,26 +2318,49 @@ function typeOfCall(t, expr) {
2175
2318
  sources
2176
2319
  };
2177
2320
  }
2178
- if (name === "row_number" || name === "rank" || name === "dense_rank" || name === "ntile") return numberType(ctx, false, sources);
2179
- if (name === "array_agg" || name === "array") {
2180
- const first = args[0] ?? UNKNOWN;
2181
- return {
2182
- dataType: first.dataType === null ? null : `${first.dataType}[]`,
2183
- tsType: `${first.tsType === "unknown" ? "unknown" : first.tsType}[]`,
2184
- nullable: name === "array_agg",
2185
- sources
2186
- };
2187
- }
2188
- if (name === "json_agg" || name === "jsonb_agg" || name === "json_object" || name === "json_build_object" || name === "jsonb_build_object" || name === "to_json" || name === "to_jsonb" || name === "row_to_json" || name === "json_extract" || name === "json") return {
2189
- dataType: ctx.dialect === "sqlite" ? "TEXT" : ctx.dialect === "mysql" ? "json" : "jsonb",
2321
+ return RANKING.has(name) ? numberType(ctx, false, sources) : null;
2322
+ }
2323
+ function arrayType(call) {
2324
+ const { name, args, sources } = call;
2325
+ if (name !== "array_agg" && name !== "array") return null;
2326
+ const first = args[0] ?? UNKNOWN;
2327
+ return {
2328
+ dataType: first.dataType === null ? null : `${first.dataType}[]`,
2329
+ tsType: `${first.tsType === "unknown" ? "unknown" : first.tsType}[]`,
2330
+ nullable: name === "array_agg",
2331
+ sources
2332
+ };
2333
+ }
2334
+ const JSON_FUNCTIONS = /* @__PURE__ */ new Set([
2335
+ "json_agg",
2336
+ "jsonb_agg",
2337
+ "json_object",
2338
+ "json_build_object",
2339
+ "jsonb_build_object",
2340
+ "to_json",
2341
+ "to_jsonb",
2342
+ "row_to_json",
2343
+ "json_extract",
2344
+ "json"
2345
+ ]);
2346
+ function jsonType(call) {
2347
+ const { ctx, name, sources, argNullable } = call;
2348
+ if (!JSON_FUNCTIONS.has(name)) return null;
2349
+ return {
2350
+ dataType: JSON_TYPES[ctx.dialect],
2190
2351
  tsType: ctx.dialect === "sqlite" ? "string" : "unknown",
2191
2352
  nullable: argNullable,
2192
2353
  sources
2193
2354
  };
2355
+ }
2356
+ /** A function of a known family: numbers, booleans, dates, strings; anything else is unknown. */
2357
+ function familyType(call) {
2358
+ const { ctx, name, args, sources, argNullable } = call;
2194
2359
  if (NUMBER_FUNCTIONS.has(name)) return numberType(ctx, argNullable, sources);
2195
2360
  if (BOOLEAN_FUNCTIONS.has(name)) return booleanType(ctx, argNullable, sources);
2196
- if (DATE_FUNCTIONS.has(name)) return dateType(ctx, args.length === 0 ? false : argNullable, sources);
2197
- if (STRING_FUNCTIONS.has(name)) return stringType(ctx, args.length === 0 ? false : argNullable, sources);
2361
+ const nullable = args.length === 0 ? false : argNullable;
2362
+ if (DATE_FUNCTIONS.has(name)) return dateType(ctx, nullable, sources);
2363
+ if (STRING_FUNCTIONS.has(name)) return stringType(ctx, nullable, sources);
2198
2364
  return {
2199
2365
  ...UNKNOWN,
2200
2366
  nullable: argNullable,
@@ -2204,75 +2370,22 @@ function typeOfCall(t, expr) {
2204
2370
  /** Records every placeholder with the type of what it stands beside. */
2205
2371
  function collectParams(t, expr, expected, context) {
2206
2372
  const { ctx } = t;
2207
- const quietTyping = {
2208
- ...t,
2209
- ctx: {
2210
- ...ctx,
2211
- diagnostics: [],
2212
- nodes: [],
2213
- edges: [],
2214
- refs: [],
2215
- params: []
2216
- }
2217
- };
2218
- const typeQuietly = (candidate) => candidate.type === "param" || candidate.type === "subquery" || candidate.type === "exists" ? null : typeOf(quietTyping, candidate);
2373
+ if (expr.type === "param") {
2374
+ recordParam(ctx, expr, expected, context);
2375
+ return;
2376
+ }
2377
+ if (isLeaf(expr)) return;
2378
+ const typeQuietly = quietTyper(t);
2219
2379
  switch (expr.type) {
2220
- case "param":
2221
- ctx.params.push({
2222
- placeholder: expr.placeholder,
2223
- type: expected ?? UNKNOWN,
2224
- context,
2225
- range: expr.range
2226
- });
2227
- return;
2228
- case "binary": {
2229
- const comparison = [
2230
- "=",
2231
- "<>",
2232
- "!=",
2233
- "<",
2234
- ">",
2235
- "<=",
2236
- ">=",
2237
- "<=>"
2238
- ].includes(expr.op);
2239
- const arithmetic = [
2240
- "+",
2241
- "-",
2242
- "*",
2243
- "/",
2244
- "%",
2245
- "^",
2246
- "**"
2247
- ].includes(expr.op);
2248
- const leftType = expr.right.type === "param" || expr.left.type === "param" ? typeQuietly(expr.left) : null;
2249
- const rightType = expr.left.type === "param" || expr.right.type === "param" ? typeQuietly(expr.right) : null;
2250
- const text = snippet(ctx, expr.range);
2251
- const sideType = (other) => {
2252
- if (comparison) return other === null ? null : withNullable(other, expr.op === "<=>" ? other.nullable : false);
2253
- if (arithmetic) return other === null || other.tsType === "unknown" ? numberType(ctx, false, []) : other;
2254
- if (expr.op === "||") return stringType(ctx, false, []);
2255
- return other;
2256
- };
2257
- collectParams(t, expr.left, sideType(rightType), text);
2258
- collectParams(t, expr.right, sideType(leftType), text);
2380
+ case "binary":
2381
+ collectBinaryParams(t, expr, typeQuietly);
2259
2382
  return;
2260
- }
2261
- case "in": {
2262
- const left = expr.expr.type === "param" ? null : typeQuietly(expr.expr);
2263
- const text = snippet(ctx, expr.range);
2264
- collectParams(t, expr.expr, null, text);
2265
- for (const item of expr.list ?? []) collectParams(t, item, left === null ? null : withNullable(left, false), text);
2383
+ case "in":
2384
+ collectInParams(t, expr, typeQuietly);
2266
2385
  return;
2267
- }
2268
- case "between": {
2269
- const left = typeQuietly(expr.expr);
2270
- const text = snippet(ctx, expr.range);
2271
- collectParams(t, expr.expr, null, text);
2272
- collectParams(t, expr.low, left === null ? null : withNullable(left, false), text);
2273
- collectParams(t, expr.high, left === null ? null : withNullable(left, false), text);
2386
+ case "between":
2387
+ collectBetweenParams(t, expr, typeQuietly);
2274
2388
  return;
2275
- }
2276
2389
  case "like": {
2277
2390
  const text = snippet(ctx, expr.range);
2278
2391
  collectParams(t, expr.expr, stringType(ctx, false, []), text);
@@ -2292,19 +2405,11 @@ function collectParams(t, expr, expected, context) {
2292
2405
  sources: []
2293
2406
  }, snippet(ctx, expr.range));
2294
2407
  return;
2295
- case "case": {
2296
- const text = snippet(ctx, expr.range, 60);
2297
- const operand = expr.operand === null ? null : typeQuietly(expr.operand);
2298
- if (expr.operand !== null) collectParams(t, expr.operand, null, text);
2299
- for (const branch of expr.whens) {
2300
- collectParams(t, branch.when, operand === null ? booleanType(ctx, false, []) : withNullable(operand, false), text);
2301
- collectParams(t, branch.result, null, text);
2302
- }
2303
- if (expr.otherwise !== null) collectParams(t, expr.otherwise, null, text);
2408
+ case "case":
2409
+ collectCaseParams(t, expr, typeQuietly);
2304
2410
  return;
2305
- }
2306
2411
  case "unary":
2307
- collectParams(t, expr.operand, expr.op === "NOT" ? booleanType(ctx, false, []) : numberType(ctx, false, []), snippet(ctx, expr.range));
2412
+ collectUnaryParams(t, expr);
2308
2413
  return;
2309
2414
  case "is":
2310
2415
  collectParams(t, expr.expr, null, snippet(ctx, expr.range));
@@ -2312,6 +2417,87 @@ function collectParams(t, expr, expected, context) {
2312
2417
  case "list": for (const item of expr.items) collectParams(t, item, null, context);
2313
2418
  }
2314
2419
  }
2420
+ function recordParam(ctx, expr, expected, context) {
2421
+ ctx.params.push({
2422
+ placeholder: expr.placeholder,
2423
+ type: expected ?? UNKNOWN,
2424
+ context,
2425
+ range: expr.range
2426
+ });
2427
+ }
2428
+ function collectUnaryParams(t, expr) {
2429
+ const { ctx } = t;
2430
+ collectParams(t, expr.operand, expr.op === "NOT" ? booleanType(ctx, false, []) : numberType(ctx, false, []), snippet(ctx, expr.range));
2431
+ }
2432
+ /**
2433
+ * Types the other side of a placeholder. Typing it draws nothing and records nothing: a subquery
2434
+ * there is built again on the quiet context, and its own placeholders are collected where it stands.
2435
+ */
2436
+ function quietTyper(t) {
2437
+ const quietTyping = {
2438
+ ...t,
2439
+ ctx: {
2440
+ ...t.ctx,
2441
+ diagnostics: [],
2442
+ nodes: [],
2443
+ edges: [],
2444
+ refs: [],
2445
+ params: []
2446
+ }
2447
+ };
2448
+ return (candidate) => candidate.type === "param" || candidate.type === "subquery" || candidate.type === "exists" ? null : typeOf(quietTyping, candidate);
2449
+ }
2450
+ const PARAM_COMPARISONS = /* @__PURE__ */ new Set([
2451
+ "=",
2452
+ "<>",
2453
+ "!=",
2454
+ "<",
2455
+ ">",
2456
+ "<=",
2457
+ ">=",
2458
+ "<=>"
2459
+ ]);
2460
+ function collectBinaryParams(t, expr, typeQuietly) {
2461
+ const { ctx } = t;
2462
+ const placeholder = expr.left.type === "param" || expr.right.type === "param";
2463
+ const leftType = placeholder ? typeQuietly(expr.left) : null;
2464
+ const rightType = placeholder ? typeQuietly(expr.right) : null;
2465
+ const text = snippet(ctx, expr.range);
2466
+ collectParams(t, expr.left, besideType(ctx, expr.op, rightType), text);
2467
+ collectParams(t, expr.right, besideType(ctx, expr.op, leftType), text);
2468
+ }
2469
+ /** The type a placeholder takes from the other side of an operator. */
2470
+ function besideType(ctx, op, other) {
2471
+ if (PARAM_COMPARISONS.has(op)) return other === null ? null : withNullable(other, op === "<=>" ? other.nullable : false);
2472
+ if (ARITHMETIC_OPERATORS.has(op)) return other === null || other.tsType === "unknown" ? numberType(ctx, false, []) : other;
2473
+ if (op === "||") return stringType(ctx, false, []);
2474
+ return other;
2475
+ }
2476
+ function collectInParams(t, expr, typeQuietly) {
2477
+ const left = expr.expr.type === "param" ? null : typeQuietly(expr.expr);
2478
+ const text = snippet(t.ctx, expr.range);
2479
+ collectParams(t, expr.expr, null, text);
2480
+ for (const item of expr.list ?? []) collectParams(t, item, left === null ? null : withNullable(left, false), text);
2481
+ }
2482
+ function collectBetweenParams(t, expr, typeQuietly) {
2483
+ const left = typeQuietly(expr.expr);
2484
+ const bound = left === null ? null : withNullable(left, false);
2485
+ const text = snippet(t.ctx, expr.range);
2486
+ collectParams(t, expr.expr, null, text);
2487
+ collectParams(t, expr.low, bound, text);
2488
+ collectParams(t, expr.high, bound, text);
2489
+ }
2490
+ function collectCaseParams(t, expr, typeQuietly) {
2491
+ const { ctx } = t;
2492
+ const text = snippet(ctx, expr.range, 60);
2493
+ const operand = expr.operand === null ? null : typeQuietly(expr.operand);
2494
+ if (expr.operand !== null) collectParams(t, expr.operand, null, text);
2495
+ for (const branch of expr.whens) {
2496
+ collectParams(t, branch.when, operand === null ? booleanType(ctx, false, []) : withNullable(operand, false), text);
2497
+ collectParams(t, branch.result, null, text);
2498
+ }
2499
+ if (expr.otherwise !== null) collectParams(t, expr.otherwise, null, text);
2500
+ }
2315
2501
  function lookupTable(ctx, name) {
2316
2502
  return ctx.tables.get(name.name.toLowerCase()) ?? null;
2317
2503
  }
@@ -2338,14 +2524,16 @@ function tableRelation(ctx, item, scope, scopeName) {
2338
2524
  const known = table !== null;
2339
2525
  const display = item.table.schema === null ? item.table.name : `${item.table.schema}.${item.table.name}`;
2340
2526
  if (!known) warn(ctx, `Unknown table "${display}"`, item.table.range, ctx.tables.size === 0 ? "info" : "warning");
2341
- const columns = (table?.columns ?? []).map((column) => ({
2527
+ const tableName = table?.name ?? item.table.name;
2528
+ const schemaColumns = table?.columns ?? [];
2529
+ const columns = schemaColumns.map((column) => ({
2342
2530
  dataType: column.dataType,
2343
2531
  tsType: toTsType(ctx.dialect, column.dataType),
2344
2532
  nullable: column.nullable,
2345
2533
  name: column.name,
2346
2534
  expression: column.name,
2347
2535
  sources: [{
2348
- table: table?.name ?? item.table.name,
2536
+ table: tableName,
2349
2537
  column: column.name
2350
2538
  }]
2351
2539
  }));
@@ -2364,13 +2552,13 @@ function tableRelation(ctx, item, scope, scopeName) {
2364
2552
  const used = /* @__PURE__ */ new Set();
2365
2553
  ctx.refs.push({
2366
2554
  nodeId,
2367
- name: table?.name ?? item.table.name,
2555
+ name: tableName,
2368
2556
  alias: item.alias,
2369
2557
  scope: scopeName,
2370
2558
  known,
2371
2559
  range: item.table.range,
2372
2560
  used,
2373
- schemaColumns: table?.columns ?? []
2561
+ schemaColumns
2374
2562
  });
2375
2563
  return {
2376
2564
  nodeId,
@@ -2380,130 +2568,138 @@ function tableRelation(ctx, item, scope, scopeName) {
2380
2568
  nodeId,
2381
2569
  columns,
2382
2570
  known,
2383
- tableName: table?.name ?? item.table.name,
2571
+ tableName,
2384
2572
  outerNullable: false,
2385
2573
  used
2386
2574
  }]
2387
2575
  };
2388
2576
  }
2389
- function findCte(scope, name) {
2390
- if (scope === null) return null;
2391
- return scope.ctes.get(name.toLowerCase()) ?? findCte(scope.outer, name);
2392
- }
2393
- function buildFromItem(ctx, item, scope, scopeName) {
2394
- switch (item.type) {
2395
- case "table": return tableRelation(ctx, item, scope, scopeName);
2396
- case "subquery": {
2397
- const alias = item.alias ?? "subquery";
2398
- const built = buildQuery(ctx, item.query, item.lateral ? scope : {
2399
- relations: [],
2400
- outer: scope,
2401
- ctes: /* @__PURE__ */ new Map()
2402
- }, alias);
2403
- const nodeId = addNode(ctx, {
2404
- kind: "subquery",
2405
- label: alias,
2406
- details: [],
2407
- range: item.range,
2408
- scope: scopeName,
2409
- columns: built.columns.map((column) => ({
2410
- name: column.name,
2411
- dataType: column.dataType,
2412
- used: false
2413
- }))
2414
- });
2415
- addEdge(ctx, built.nodeId, nodeId);
2416
- return {
2417
- nodeId,
2418
- relations: [{
2419
- key: alias.toLowerCase(),
2420
- display: alias,
2421
- nodeId,
2422
- columns: built.columns,
2423
- known: built.known,
2424
- tableName: null,
2425
- outerNullable: false,
2426
- used: /* @__PURE__ */ new Set()
2427
- }]
2428
- };
2429
- }
2430
- case "function": {
2431
- const alias = item.alias ?? (item.call.type === "call" ? item.call.name : "function");
2432
- const nodeId = addNode(ctx, {
2433
- kind: "function",
2434
- label: snippet(ctx, item.call.range, 60),
2435
- details: [],
2436
- range: item.range,
2437
- scope: scopeName,
2438
- columns: []
2439
- });
2440
- return {
2441
- nodeId,
2442
- relations: [{
2443
- key: alias.toLowerCase(),
2444
- display: alias,
2445
- nodeId,
2446
- columns: [],
2447
- known: false,
2448
- tableName: null,
2449
- outerNullable: false,
2450
- used: /* @__PURE__ */ new Set()
2451
- }]
2452
- };
2453
- }
2454
- case "join": {
2455
- const left = buildFromItem(ctx, item.left, scope, scopeName);
2456
- const right = buildFromItem(ctx, item.right, {
2457
- relations: left.relations,
2458
- outer: scope,
2459
- ctes: /* @__PURE__ */ new Map()
2460
- }, scopeName);
2461
- const leftRelations = item.joinType === "RIGHT" || item.joinType === "FULL" ? left.relations.map((relation) => ({
2462
- ...relation,
2463
- outerNullable: true
2464
- })) : left.relations;
2465
- const rightRelations = item.joinType === "LEFT" || item.joinType === "FULL" ? right.relations.map((relation) => ({
2466
- ...relation,
2467
- outerNullable: true
2468
- })) : right.relations;
2469
- const relations = [...leftRelations, ...rightRelations];
2470
- const typing = {
2471
- ctx,
2472
- scope: {
2473
- relations,
2474
- outer: scope,
2475
- ctes: /* @__PURE__ */ new Map()
2476
- },
2477
- aliases: null,
2478
- lookups: /* @__PURE__ */ new Map()
2479
- };
2480
- const label = `${item.natural ? "NATURAL " : ""}${item.joinType} JOIN`;
2481
- const details = item.on !== null ? [`ON ${snippet(ctx, item.on.range)}`] : item.using !== null ? [`USING (${item.using.join(", ")})`] : [];
2482
- if (item.on !== null) {
2483
- typeOf(typing, item.on);
2484
- collectParams(typing, item.on, null, snippet(ctx, item.on.range));
2485
- }
2486
- for (const name of item.using ?? []) for (const relation of [...left.relations, ...right.relations]) relation.used.add(name);
2487
- const nodeId = addNode(ctx, {
2488
- kind: "join",
2489
- label,
2490
- details,
2491
- range: item.on?.range ?? item.range,
2492
- scope: scopeName,
2493
- columns: []
2494
- });
2495
- addEdge(ctx, left.nodeId, nodeId, item.joinType === "RIGHT" ? "optional" : null);
2496
- addEdge(ctx, right.nodeId, nodeId, item.joinType === "LEFT" ? "optional" : null);
2497
- return {
2498
- nodeId,
2499
- relations
2500
- };
2501
- }
2502
- default: return {
2503
- nodeId: "",
2504
- relations: []
2505
- };
2506
- }
2577
+ function findCte(scope, name) {
2578
+ if (scope === null) return null;
2579
+ return scope.ctes.get(name.toLowerCase()) ?? findCte(scope.outer, name);
2580
+ }
2581
+ function buildFromItem(ctx, item, scope, scopeName) {
2582
+ switch (item.type) {
2583
+ case "table": return tableRelation(ctx, item, scope, scopeName);
2584
+ case "subquery": return subqueryRelation(ctx, item, scope, scopeName);
2585
+ case "function": return functionRelation(ctx, item, scopeName);
2586
+ case "join": return joinRelation(ctx, item, scope, scopeName);
2587
+ default: return {
2588
+ nodeId: "",
2589
+ relations: []
2590
+ };
2591
+ }
2592
+ }
2593
+ function subqueryRelation(ctx, item, scope, scopeName) {
2594
+ const alias = item.alias ?? "subquery";
2595
+ const built = buildQuery(ctx, item.query, item.lateral ? scope : {
2596
+ relations: [],
2597
+ outer: scope,
2598
+ ctes: /* @__PURE__ */ new Map()
2599
+ }, alias);
2600
+ const nodeId = addNode(ctx, {
2601
+ kind: "subquery",
2602
+ label: alias,
2603
+ details: [],
2604
+ range: item.range,
2605
+ scope: scopeName,
2606
+ columns: built.columns.map((column) => ({
2607
+ name: column.name,
2608
+ dataType: column.dataType,
2609
+ used: false
2610
+ }))
2611
+ });
2612
+ addEdge(ctx, built.nodeId, nodeId);
2613
+ return {
2614
+ nodeId,
2615
+ relations: [{
2616
+ key: alias.toLowerCase(),
2617
+ display: alias,
2618
+ nodeId,
2619
+ columns: built.columns,
2620
+ known: built.known,
2621
+ tableName: null,
2622
+ outerNullable: false,
2623
+ used: /* @__PURE__ */ new Set()
2624
+ }]
2625
+ };
2626
+ }
2627
+ function functionRelation(ctx, item, scopeName) {
2628
+ const alias = item.alias ?? (item.call.type === "call" ? item.call.name : "function");
2629
+ const nodeId = addNode(ctx, {
2630
+ kind: "function",
2631
+ label: snippet(ctx, item.call.range, 60),
2632
+ details: [],
2633
+ range: item.range,
2634
+ scope: scopeName,
2635
+ columns: []
2636
+ });
2637
+ return {
2638
+ nodeId,
2639
+ relations: [{
2640
+ key: alias.toLowerCase(),
2641
+ display: alias,
2642
+ nodeId,
2643
+ columns: [],
2644
+ known: false,
2645
+ tableName: null,
2646
+ outerNullable: false,
2647
+ used: /* @__PURE__ */ new Set()
2648
+ }]
2649
+ };
2650
+ }
2651
+ function joinRelation(ctx, item, scope, scopeName) {
2652
+ const left = buildFromItem(ctx, item.left, scope, scopeName);
2653
+ const right = buildFromItem(ctx, item.right, {
2654
+ relations: left.relations,
2655
+ outer: scope,
2656
+ ctes: /* @__PURE__ */ new Map()
2657
+ }, scopeName);
2658
+ const leftRelations = item.joinType === "RIGHT" || item.joinType === "FULL" ? left.relations.map((relation) => ({
2659
+ ...relation,
2660
+ outerNullable: true
2661
+ })) : left.relations;
2662
+ const rightRelations = item.joinType === "LEFT" || item.joinType === "FULL" ? right.relations.map((relation) => ({
2663
+ ...relation,
2664
+ outerNullable: true
2665
+ })) : right.relations;
2666
+ const relations = [...leftRelations, ...rightRelations];
2667
+ const typing = {
2668
+ ctx,
2669
+ scope: {
2670
+ relations,
2671
+ outer: scope,
2672
+ ctes: /* @__PURE__ */ new Map()
2673
+ },
2674
+ aliases: null,
2675
+ lookups: /* @__PURE__ */ new Map()
2676
+ };
2677
+ const label = `${item.natural ? "NATURAL " : ""}${item.joinType} JOIN`;
2678
+ const details = joinDetails(ctx, item);
2679
+ if (item.on !== null) {
2680
+ typeOf(typing, item.on);
2681
+ collectParams(typing, item.on, null, snippet(ctx, item.on.range));
2682
+ }
2683
+ for (const name of item.using ?? []) for (const relation of [...left.relations, ...right.relations]) relation.used.add(name);
2684
+ const nodeId = addNode(ctx, {
2685
+ kind: "join",
2686
+ label,
2687
+ details,
2688
+ range: item.on?.range ?? item.range,
2689
+ scope: scopeName,
2690
+ columns: []
2691
+ });
2692
+ addEdge(ctx, left.nodeId, nodeId, item.joinType === "RIGHT" ? "optional" : null);
2693
+ addEdge(ctx, right.nodeId, nodeId, item.joinType === "LEFT" ? "optional" : null);
2694
+ return {
2695
+ nodeId,
2696
+ relations
2697
+ };
2698
+ }
2699
+ /** What a join is on, for its node: `ON ...`, `USING (...)`, or nothing. */
2700
+ function joinDetails(ctx, item) {
2701
+ if (item.on !== null) return [`ON ${snippet(ctx, item.on.range)}`];
2702
+ return item.using === null ? [] : [`USING (${item.using.join(", ")})`];
2507
2703
  }
2508
2704
  function buildFrom(ctx, items, scope, scopeName) {
2509
2705
  if (items[0] === void 0) return null;
@@ -2643,52 +2839,8 @@ function buildSelect(ctx, core, outer, scopeName) {
2643
2839
  if (chain.current !== null) addEdge(ctx, chain.current, nodeId);
2644
2840
  chain.current = nodeId;
2645
2841
  };
2646
- if (core.where !== null) {
2647
- const nodeId = nextId(ctx);
2648
- const typing = {
2649
- ctx,
2650
- scope,
2651
- aliases: null,
2652
- lookups: new Map(subqueriesOf(core.where).map((query) => [query, nodeId]))
2653
- };
2654
- const condition = typeOf(typing, core.where);
2655
- collectParams(typing, core.where, null, snippet(ctx, core.where.range));
2656
- ctx.nodes.push({
2657
- id: nodeId,
2658
- kind: "filter",
2659
- label: "WHERE",
2660
- details: [snippet(ctx, core.where.range)],
2661
- range: core.where.range,
2662
- scope: scopeName,
2663
- columns: []
2664
- });
2665
- if (condition.tsType !== "unknown" && condition.tsType !== "boolean" && condition.tsType !== "number" && ctx.dialect === "postgresql") warn(ctx, `WHERE expects a boolean, this condition is ${condition.tsType}`, core.where.range);
2666
- link(nodeId);
2667
- }
2668
- if (core.groupBy.length > 0 || core.having !== null || core.columns.some((item) => hasAggregate(item.expr))) {
2669
- const typing = {
2670
- ctx,
2671
- scope,
2672
- aliases: null,
2673
- lookups: /* @__PURE__ */ new Map()
2674
- };
2675
- for (const key of core.groupBy) {
2676
- typeOf(typing, key);
2677
- collectParams(typing, key, null, snippet(ctx, key.range));
2678
- }
2679
- const aggregates = core.columns.flatMap((item) => aggregateCalls(item.expr)).map((call) => snippet(ctx, call.range, 60));
2680
- link(addNode(ctx, {
2681
- kind: "aggregate",
2682
- label: "GROUP BY",
2683
- details: [...core.groupBy.length === 0 ? ["whole result as one group"] : [`BY ${core.groupBy.map((key) => snippet(ctx, key.range, 60)).join(", ")}`], ...aggregates],
2684
- range: core.groupBy.length === 0 ? null : {
2685
- start: core.groupBy[0]?.range.start ?? 0,
2686
- end: core.groupBy.at(-1)?.range.end ?? 0
2687
- },
2688
- scope: scopeName,
2689
- columns: []
2690
- }));
2691
- }
2842
+ if (core.where !== null) link(filterNode(ctx, scope, core.where, scopeName));
2843
+ if (isAggregated(core)) link(aggregateNode(ctx, scope, core, scopeName));
2692
2844
  const projectId = nextId(ctx);
2693
2845
  const typing = {
2694
2846
  ctx,
@@ -2717,32 +2869,12 @@ function buildSelect(ctx, core, outer, scopeName) {
2717
2869
  });
2718
2870
  const columns = expanded.map((entry) => entry.resolved);
2719
2871
  const aliases = new Map(core.columns.flatMap((item, index) => item.alias === null ? [] : [[item.alias.toLowerCase(), columns[index] ?? UNKNOWN]]));
2720
- if (core.having !== null) {
2721
- const havingId = nextId(ctx);
2722
- const havingTyping = {
2723
- ctx,
2724
- scope,
2725
- aliases,
2726
- lookups: new Map(subqueriesOf(core.having).map((query) => [query, havingId]))
2727
- };
2728
- typeOf(havingTyping, core.having);
2729
- collectParams(havingTyping, core.having, null, snippet(ctx, core.having.range));
2730
- ctx.nodes.push({
2731
- id: havingId,
2732
- kind: "having",
2733
- label: "HAVING",
2734
- details: [snippet(ctx, core.having.range)],
2735
- range: core.having.range,
2736
- scope: scopeName,
2737
- columns: []
2738
- });
2739
- link(havingId);
2740
- }
2872
+ if (core.having !== null) link(havingNode(ctx, scope, aliases, core.having, scopeName));
2741
2873
  ctx.nodes.push({
2742
2874
  id: projectId,
2743
2875
  kind: "project",
2744
2876
  label: core.distinct ? "SELECT DISTINCT" : "SELECT",
2745
- details: columns.length > 12 ? [...columns.slice(0, 12).map((column) => column.name), `… ${columns.length - 12} more`] : columns.map((column) => column.name),
2877
+ details: projectDetails(columns),
2746
2878
  range: selectRange(core.columns),
2747
2879
  scope: scopeName,
2748
2880
  columns: columns.map((column) => ({
@@ -2762,6 +2894,80 @@ function buildSelect(ctx, core, outer, scopeName) {
2762
2894
  aliases
2763
2895
  };
2764
2896
  }
2897
+ function filterNode(ctx, scope, where, scopeName) {
2898
+ const nodeId = nextId(ctx);
2899
+ const typing = {
2900
+ ctx,
2901
+ scope,
2902
+ aliases: null,
2903
+ lookups: new Map(subqueriesOf(where).map((query) => [query, nodeId]))
2904
+ };
2905
+ const condition = typeOf(typing, where);
2906
+ collectParams(typing, where, null, snippet(ctx, where.range));
2907
+ ctx.nodes.push({
2908
+ id: nodeId,
2909
+ kind: "filter",
2910
+ label: "WHERE",
2911
+ details: [snippet(ctx, where.range)],
2912
+ range: where.range,
2913
+ scope: scopeName,
2914
+ columns: []
2915
+ });
2916
+ if (condition.tsType !== "unknown" && condition.tsType !== "boolean" && condition.tsType !== "number" && ctx.dialect === "postgresql") warn(ctx, `WHERE expects a boolean, this condition is ${condition.tsType}`, where.range);
2917
+ return nodeId;
2918
+ }
2919
+ function isAggregated(core) {
2920
+ return core.groupBy.length > 0 || core.having !== null || core.columns.some((item) => hasAggregate(item.expr));
2921
+ }
2922
+ function aggregateNode(ctx, scope, core, scopeName) {
2923
+ const typing = {
2924
+ ctx,
2925
+ scope,
2926
+ aliases: null,
2927
+ lookups: /* @__PURE__ */ new Map()
2928
+ };
2929
+ for (const key of core.groupBy) {
2930
+ typeOf(typing, key);
2931
+ collectParams(typing, key, null, snippet(ctx, key.range));
2932
+ }
2933
+ const aggregates = core.columns.flatMap((item) => aggregateCalls(item.expr)).map((call) => snippet(ctx, call.range, 60));
2934
+ return addNode(ctx, {
2935
+ kind: "aggregate",
2936
+ label: "GROUP BY",
2937
+ details: [...core.groupBy.length === 0 ? ["whole result as one group"] : [`BY ${core.groupBy.map((key) => snippet(ctx, key.range, 60)).join(", ")}`], ...aggregates],
2938
+ range: core.groupBy.length === 0 ? null : {
2939
+ start: core.groupBy[0]?.range.start ?? 0,
2940
+ end: core.groupBy.at(-1)?.range.end ?? 0
2941
+ },
2942
+ scope: scopeName,
2943
+ columns: []
2944
+ });
2945
+ }
2946
+ function havingNode(ctx, scope, aliases, having, scopeName) {
2947
+ const havingId = nextId(ctx);
2948
+ const havingTyping = {
2949
+ ctx,
2950
+ scope,
2951
+ aliases,
2952
+ lookups: new Map(subqueriesOf(having).map((query) => [query, havingId]))
2953
+ };
2954
+ typeOf(havingTyping, having);
2955
+ collectParams(havingTyping, having, null, snippet(ctx, having.range));
2956
+ ctx.nodes.push({
2957
+ id: havingId,
2958
+ kind: "having",
2959
+ label: "HAVING",
2960
+ details: [snippet(ctx, having.range)],
2961
+ range: having.range,
2962
+ scope: scopeName,
2963
+ columns: []
2964
+ });
2965
+ return havingId;
2966
+ }
2967
+ /** The output columns, for the node: the first twelve and how many more. */
2968
+ function projectDetails(columns) {
2969
+ return columns.length > 12 ? [...columns.slice(0, 12).map((column) => column.name), `… ${columns.length - 12} more`] : columns.map((column) => column.name);
2970
+ }
2765
2971
  function aggregateCalls(expr) {
2766
2972
  if (expr.type === "call" && isAggregateCall(expr)) return [expr];
2767
2973
  return childExpressions(expr).flatMap(aggregateCalls);
@@ -2963,13 +3169,14 @@ function buildInsert(ctx, statement) {
2963
3169
  };
2964
3170
  const scope = statement.ctes.length === 0 ? root : buildCtes(ctx, statement.ctes, false, root);
2965
3171
  const table = lookupTable(ctx, statement.table);
2966
- const targetColumns = statement.columns === null ? table?.columns ?? [] : statement.columns.map((name) => table?.columns.find((column) => column.name.toLowerCase() === name.toLowerCase()) ?? {
3172
+ const columnByName = new Map((table?.columns ?? []).toReversed().map((column) => [column.name.toLowerCase(), column]));
3173
+ const targetColumns = statement.columns === null ? table?.columns ?? [] : statement.columns.map((name) => columnByName.get(name.toLowerCase()) ?? {
2967
3174
  name,
2968
3175
  dataType: "",
2969
3176
  nullable: true
2970
3177
  });
2971
3178
  if (table !== null && statement.columns !== null) {
2972
- for (const name of statement.columns) if (!table.columns.some((column) => column.name.toLowerCase() === name.toLowerCase())) warn(ctx, `"${table.name}" has no column "${name}"`, statement.range);
3179
+ for (const name of statement.columns) if (!columnByName.has(name.toLowerCase())) warn(ctx, `"${table.name}" has no column "${name}"`, statement.range);
2973
3180
  }
2974
3181
  const expectedTypes = targetColumns.map((column) => column.dataType === "" ? null : typeOfColumn(ctx, column));
2975
3182
  const insertScope = {
@@ -3101,7 +3308,7 @@ function buildUpdate(ctx, statement) {
3101
3308
  const targetTable = target.relations[0];
3102
3309
  for (const item of statement.set) {
3103
3310
  const column = targetTable === void 0 ? null : columnOf(targetTable, item.column);
3104
- if (targetTable?.known && column === null) warn(ctx, `"${targetTable.display}" has no column "${item.column}"`, item.range);
3311
+ if (targetTable?.known === true && column === null) warn(ctx, `"${targetTable.display}" has no column "${item.column}"`, item.range);
3105
3312
  targetTable?.used.add(item.column);
3106
3313
  if (item.value.type !== "raw") {
3107
3314
  typeOf(typing, item.value);
@@ -3256,8 +3463,9 @@ function paramsTypeOf(params) {
3256
3463
  }
3257
3464
  function finish(ctx, kind, range, columns) {
3258
3465
  const parameters = orderParams(ctx);
3466
+ const refByNode = new Map(ctx.refs.toReversed().map((ref) => [ref.nodeId, ref]));
3259
3467
  const nodes = ctx.nodes.map((node) => {
3260
- const ref = ctx.refs.find((candidate) => candidate.nodeId === node.id);
3468
+ const ref = refByNode.get(node.id);
3261
3469
  if (ref === void 0) return node;
3262
3470
  const used = new Set([...ref.used].map((name) => name.toLowerCase()));
3263
3471
  return {
@@ -3345,6 +3553,11 @@ function analyze(text, schema) {
3345
3553
  const tables = new Map(schema.tables.map((table) => [table.name.toLowerCase(), table]));
3346
3554
  return { statements: statements.map((statement) => analyzeStatement(text, statement, schema, tables)) };
3347
3555
  }
3556
+ // src/network/index.ts
3557
+ function isLoopbackHostname(hostname) {
3558
+ const bare = hostname.replace(/^\[(.*)\]$/u, "$1").toLowerCase();
3559
+ return bare === "localhost" || bare.endsWith(".localhost") || bare === "127.0.0.1" || bare === "::1";
3560
+ }
3348
3561
  // src/studio/server/routes/index.ts
3349
3562
  const StatementKindSchema = z.enum([
3350
3563
  "select",
@@ -3607,7 +3820,23 @@ const StatementAnalysisSchema = z.object({
3607
3820
  "rowType",
3608
3821
  "paramsType"
3609
3822
  ],
3610
- description: "The analysis of one statement."
3823
+ description: "The analysis of one statement.",
3824
+ example: {
3825
+ kind: "select",
3826
+ text: "SELECT id FROM users",
3827
+ range: {
3828
+ start: 0,
3829
+ end: 20
3830
+ },
3831
+ nodes: [],
3832
+ edges: [],
3833
+ tables: [],
3834
+ columns: [],
3835
+ parameters: [],
3836
+ diagnostics: [],
3837
+ rowType: "{ id: number }",
3838
+ paramsType: "[]"
3839
+ }
3611
3840
  }).openapi("StatementAnalysis");
3612
3841
  const SchemaFileSchema = z.object({
3613
3842
  path: z.string().openapi({ description: "The file path as Studio loaded it (the value to send back as `FileWrite.path`)" }),
@@ -4376,7 +4605,8 @@ const PlanSchema = z.object({
4376
4605
  }).openapi("Plan");
4377
4606
  const AnalysisSchema = z.lazy(() => z.object({ statements: z.array(StatementAnalysisSchema).readonly().openapi({ description: "One entry per statement, in order" }) }).readonly().brand().openapi({
4378
4607
  required: ["statements"],
4379
- description: "The analysis of every statement in the text."
4608
+ description: "The analysis of every statement in the text.",
4609
+ example: { statements: [] }
4380
4610
  })).openapi("Analysis");
4381
4611
  const AnalyzeBodySchema = z.object({ sql: SqlSchema.openapi({ description: "The statements" }) }).readonly().openapi({
4382
4612
  required: ["sql"],
@@ -6011,7 +6241,7 @@ const getSchemaEventsRoute = createRoute({
6011
6241
  description: "Server-sent events: `ready` (data: the current `updatedAt`) on connect, `change` (data: the\nnew `updatedAt`) after every reload, `migrations` (data: when it was seen) after the\nmigrations directory changes, and `ping` every 15 seconds to keep the connection open.",
6012
6242
  operationId: "readSchemaEvents",
6013
6243
  responses: { 200: {
6014
- description: "The request has succeeded.",
6244
+ description: "The event stream, open until the client closes it",
6015
6245
  content: { "text/event-stream": { schema: z.string() } }
6016
6246
  } }
6017
6247
  });
@@ -6064,6 +6294,7 @@ const getDbRowsModelNameRoute = createRoute({
6064
6294
  name: "modelName",
6065
6295
  in: "path",
6066
6296
  required: true,
6297
+ description: "The model whose table is read or written, as the schema declares it",
6067
6298
  schema: { $ref: "#/components/schemas/modelName" }
6068
6299
  } }) }),
6069
6300
  query: z.object({
@@ -6106,6 +6337,7 @@ const postDbRowsModelNameRoute = createRoute({
6106
6337
  name: "modelName",
6107
6338
  in: "path",
6108
6339
  required: true,
6340
+ description: "The model whose table is read or written, as the schema declares it",
6109
6341
  schema: { $ref: "#/components/schemas/modelName" }
6110
6342
  } }) }),
6111
6343
  body: {
@@ -6147,6 +6379,7 @@ const deleteDbRowsModelNameRoute = createRoute({
6147
6379
  name: "modelName",
6148
6380
  in: "path",
6149
6381
  required: true,
6382
+ description: "The model whose table is read or written, as the schema declares it",
6150
6383
  schema: { $ref: "#/components/schemas/modelName" }
6151
6384
  } }) }),
6152
6385
  body: {
@@ -6188,6 +6421,7 @@ const patchDbRowsModelNameRoute = createRoute({
6188
6421
  name: "modelName",
6189
6422
  in: "path",
6190
6423
  required: true,
6424
+ description: "The model whose table is read or written, as the schema declares it",
6191
6425
  schema: { $ref: "#/components/schemas/modelName" }
6192
6426
  } }) }),
6193
6427
  body: {
@@ -7081,6 +7315,7 @@ const getMigrateMigrationsMigrationNameRoute = createRoute({
7081
7315
  name: "migrationName",
7082
7316
  in: "path",
7083
7317
  required: true,
7318
+ description: "The directory name of the migration, as `MigrationRecord.name` gives it",
7084
7319
  schema: { type: "string" }
7085
7320
  } }) }) },
7086
7321
  responses: {
@@ -7330,69 +7565,101 @@ function nameOf(node) {
7330
7565
  /** A literal read as the value it spells; anything that would need evaluating is refused. */
7331
7566
  function valueOf(node, depth, now) {
7332
7567
  if (depth > MAX_DEPTH) return fail(node, `The arguments nest deeper than ${MAX_DEPTH} levels`);
7333
- if (node.type === "Literal") {
7334
- if (node.bigint !== void 0) return done(BigInt(node.bigint));
7335
- const { value } = node;
7336
- return typeof value === "string" || typeof value === "number" || typeof value === "boolean" ? done(value) : value === null ? done(null) : fail(node, "A regular expression is not a value");
7337
- }
7568
+ if (node.type === "Literal") return literalValue(node);
7338
7569
  if (node.type === "TemplateLiteral") {
7339
7570
  const cooked = node.quasis[0]?.value.cooked;
7340
7571
  return node.expressions.length > 0 || cooked === null || cooked === void 0 ? fail(node, "Template literals that interpolate are not supported") : done(cooked);
7341
7572
  }
7342
7573
  if (node.type === "Identifier") return node.name === "undefined" ? done(void 0) : fail(node, `"${node.name}" is not a literal. Arguments are read, not evaluated: write strings, numbers, booleans, null, objects, arrays or new Date(...).`);
7343
- if (node.type === "UnaryExpression") {
7344
- const inner = node.argument;
7345
- if (node.operator === "-" && inner.type === "Literal") return inner.bigint === void 0 ? typeof inner.value === "number" ? done(-inner.value) : fail(inner, "Expected a number after \"-\"") : done(-BigInt(inner.bigint));
7346
- return fail(node, `"${node.operator}" is not supported: write the value out`);
7347
- }
7348
- if (node.type === "ArrayExpression") return node.elements.reduce((items, element) => {
7574
+ if (node.type === "UnaryExpression") return negatedValue(node);
7575
+ if (node.type === "ArrayExpression") return arrayValue(node, depth, now);
7576
+ if (node.type === "ObjectExpression") return objectValue(node, depth, now);
7577
+ if (node.type === "NewExpression") return dateValue(node, now);
7578
+ return fail(node, "Only literals are read: strings, numbers, booleans, null, objects, arrays and new Date(...).");
7579
+ }
7580
+ function literalValue(node) {
7581
+ if (node.bigint !== void 0) return done(BigInt(node.bigint));
7582
+ const { value } = node;
7583
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return done(value);
7584
+ return value === null ? done(null) : fail(node, "A regular expression is not a value");
7585
+ }
7586
+ /** `-1` and `-1n`: the one operator a literal is written with. */
7587
+ function negatedValue(node) {
7588
+ const inner = node.argument;
7589
+ if (node.operator !== "-" || inner.type !== "Literal") return fail(node, `"${node.operator}" is not supported: write the value out`);
7590
+ if (inner.bigint !== void 0) return done(-BigInt(inner.bigint));
7591
+ return typeof inner.value === "number" ? done(-inner.value) : fail(inner, "Expected a number after \"-\"");
7592
+ }
7593
+ function arrayValue(node, depth, now) {
7594
+ return node.elements.reduce((items, element) => {
7349
7595
  if (!items.ok) return items;
7350
7596
  if (element === null) return fail(node, "An array cannot have a hole");
7351
7597
  if (element.type === "SpreadElement") return fail(element, "Spread is not supported: write the items out");
7352
7598
  const item = valueOf(element, depth + 1, now);
7353
7599
  return item.ok ? done([...items.value, item.value]) : item;
7354
7600
  }, done([]));
7355
- if (node.type === "ObjectExpression") return node.properties.reduce((entries, property) => {
7601
+ }
7602
+ function objectValue(node, depth, now) {
7603
+ return node.properties.reduce((entries, property) => {
7356
7604
  if (!entries.ok) return entries;
7357
- if (property.type === "SpreadElement") return fail(property, "Spread is not supported: write the fields out");
7358
- if (property.computed) return fail(property.key, "Computed keys are not supported");
7359
- if (property.shorthand) return fail(property.key, `"${nameOf(property.key) ?? ""}" is a variable: write "${nameOf(property.key) ?? ""}: <value>"`);
7360
- if (property.kind !== "init" || property.method) return fail(property, "A method is not a value");
7361
- const key = property.key.type === "Literal" ? String(property.key.value) : nameOf(property.key);
7362
- if (key === null) return fail(property.key, "Expected a key");
7363
- const value = valueOf(property.value, depth + 1, now);
7364
- return value.ok ? done({
7605
+ const entry = entryOf(property, depth, now);
7606
+ return entry.ok ? done({
7365
7607
  ...entries.value,
7366
- [key]: value.value
7367
- }) : value;
7608
+ [entry.value.key]: entry.value.value
7609
+ }) : entry;
7368
7610
  }, done({}));
7369
- if (node.type === "NewExpression") {
7370
- if (nameOf(node.callee) !== "Date") return fail(node, `Only new Date(...) is supported, not new ${node.callee.type === "Identifier" ? node.callee.name : "…"}`);
7371
- const [argument, second] = node.arguments;
7372
- if (argument === void 0) return done(new Date(now));
7373
- if (second !== void 0) return fail(second, "new Date takes one string or number");
7374
- if (argument.type !== "Literal" || argument.bigint !== void 0 || typeof argument.value !== "string" && typeof argument.value !== "number") return fail(argument, "new Date takes one string or number");
7375
- const date = new Date(argument.value);
7376
- return Number.isNaN(date.getTime()) ? fail(node, `Invalid date: ${argument.raw ?? ""}`) : done(date);
7377
- }
7378
- return fail(node, "Only literals are read: strings, numbers, booleans, null, objects, arrays and new Date(...).");
7611
+ }
7612
+ /** One `key: value` of an object literal; spread, computed keys, shorthand and methods are refused. */
7613
+ function entryOf(property, depth, now) {
7614
+ if (property.type === "SpreadElement") return fail(property, "Spread is not supported: write the fields out");
7615
+ if (property.computed) return fail(property.key, "Computed keys are not supported");
7616
+ if (property.shorthand) return fail(property.key, `"${nameOf(property.key) ?? ""}" is a variable: write "${nameOf(property.key) ?? ""}: <value>"`);
7617
+ if (property.kind !== "init" || property.method) return fail(property, "A method is not a value");
7618
+ const key = property.key.type === "Literal" ? String(property.key.value) : nameOf(property.key);
7619
+ if (key === null) return fail(property.key, "Expected a key");
7620
+ const value = valueOf(property.value, depth + 1, now);
7621
+ return value.ok ? done({
7622
+ key,
7623
+ value: value.value
7624
+ }) : value;
7625
+ }
7626
+ /** `new Date()` (the time of the run) and `new Date(<string or number>)`. */
7627
+ function dateValue(node, now) {
7628
+ if (nameOf(node.callee) !== "Date") return fail(node, `Only new Date(...) is supported, not new ${node.callee.type === "Identifier" ? node.callee.name : "…"}`);
7629
+ const [argument, second] = node.arguments;
7630
+ if (argument === void 0) return done(new Date(now));
7631
+ if (second !== void 0) return fail(second, "new Date takes one string or number");
7632
+ if (argument.type !== "Literal" || argument.bigint !== void 0 || typeof argument.value !== "string" && typeof argument.value !== "number") return fail(argument, "new Date takes one string or number");
7633
+ const date = new Date(argument.value);
7634
+ return Number.isNaN(date.getTime()) ? fail(node, `Invalid date: ${argument.raw ?? ""}`) : done(date);
7635
+ }
7636
+ /** A `$` tag on a template (`prisma.$queryRaw\`...\``) is raw SQL, which runs on the SQL page. */
7637
+ function rawTagRefusal(node) {
7638
+ if (node.type !== "TaggedTemplateExpression" || node.tag.type !== "MemberExpression") return null;
7639
+ const tag = nameOf(node.tag.property);
7640
+ if (tag?.startsWith("$") !== true) return null;
7641
+ return fail(node.tag.property, `${tag} is not supported here: run raw SQL on the SQL page`);
7642
+ }
7643
+ /** The client's own methods (`$transaction`, `$queryRaw`) where a delegate or an operation goes. */
7644
+ function clientMethodRefusal(name, node) {
7645
+ if (name?.startsWith("$") !== true) return null;
7646
+ return fail(node, name === "$transaction" ? "$transaction cannot be nested" : `${name} is not supported here: run raw SQL on the SQL page`);
7379
7647
  }
7380
7648
  /** `prisma.user.findMany({ ... })`: whatever the client is called, a delegate, an operation, one argument. */
7381
7649
  function callOf(node, now) {
7382
- if (node.type === "TaggedTemplateExpression" && node.tag.type === "MemberExpression") {
7383
- const tag = nameOf(node.tag.property);
7384
- if (tag?.startsWith("$")) return fail(node.tag.property, `${tag} is not supported here: run raw SQL on the SQL page`);
7385
- }
7650
+ const tagged = rawTagRefusal(node);
7651
+ if (tagged !== null) return tagged;
7386
7652
  if (node.type !== "CallExpression") return fail(node, "Expected a call such as prisma.user.findMany()");
7387
7653
  const { callee } = node;
7388
7654
  if (callee.type !== "MemberExpression") return fail(callee, "Expected a call such as prisma.user.findMany()");
7389
- const own = nameOf(callee.property);
7390
- if (own?.startsWith("$")) return fail(callee.property, own === "$transaction" ? "$transaction cannot be nested" : `${own} is not supported here: run raw SQL on the SQL page`);
7655
+ const own = clientMethodRefusal(nameOf(callee.property), callee.property);
7656
+ if (own !== null) return own;
7391
7657
  if (callee.object.type !== "MemberExpression") return fail(callee, "Expected a call such as prisma.user.findMany()");
7392
7658
  const delegate = nameOf(callee.object.property);
7393
7659
  const operation = nameOf(callee.property);
7394
7660
  if (delegate === null || callee.object.computed) return fail(callee.object.property, "Expected a model delegate such as \"user\"");
7395
- if (delegate.startsWith("$")) return fail(callee.object.property, delegate === "$transaction" ? "$transaction cannot be nested" : `${delegate} is not supported here: run raw SQL on the SQL page`);
7661
+ const method = clientMethodRefusal(delegate, callee.object.property);
7662
+ if (method !== null) return method;
7396
7663
  if (operation === null || callee.computed) return fail(callee.property, "Expected an operation such as \"findMany\"");
7397
7664
  const [argument, second] = node.arguments;
7398
7665
  if (second !== void 0) return fail(second, "A model operation takes one argument");
@@ -7412,6 +7679,30 @@ function callOf(node, now) {
7412
7679
  end: node.end
7413
7680
  });
7414
7681
  }
7682
+ /** `prisma.$transaction([...calls], options?)`: each call read, and the options as a value. */
7683
+ function transactionOf(expression, now) {
7684
+ const [batch, options, extra] = expression.arguments;
7685
+ if (batch?.type !== "ArrayExpression") return fail(batch ?? expression, "$transaction takes an array of calls here: prisma.$transaction([prisma.user.count(), ...])");
7686
+ if (batch.elements.length === 0) return fail(batch, "$transaction needs at least one call");
7687
+ if (extra !== void 0) return fail(extra, "$transaction takes the calls and, at most, options");
7688
+ const calls = batch.elements.map((element) => element === null || element.type === "SpreadElement" ? fail(element ?? batch, "Expected a call such as prisma.user.count()") : callOf(element, now));
7689
+ const refused = calls.find((call) => !call.ok);
7690
+ if (refused !== void 0 && !refused.ok) return refused;
7691
+ const read = options === void 0 ? done(void 0) : valueOf(options, 1, now);
7692
+ return read.ok ? done({
7693
+ calls: calls.flatMap((call) => call.ok ? [call.value] : []),
7694
+ transaction: true,
7695
+ options: read.value
7696
+ }) : read;
7697
+ }
7698
+ /** The failure for text acorn cannot parse, at the place it stopped. */
7699
+ function syntaxFailure(e, text) {
7700
+ const at = e instanceof SyntaxError && "pos" in e && typeof e.pos === "number" ? e.pos : text.length;
7701
+ return fail({
7702
+ start: Math.min(at, text.length),
7703
+ end: Math.min(at + 1, text.length)
7704
+ }, e instanceof Error ? e.message.replace(/ \(\d+:\d+\)$/u, "") : "The text could not be read");
7705
+ }
7415
7706
  /** The one statement of the text: a call, or a batch `$transaction` over several. */
7416
7707
  function programOf(text, now) {
7417
7708
  try {
@@ -7430,33 +7721,15 @@ function programOf(text, now) {
7430
7721
  }, "Only one call runs at a time: batch several in prisma.$transaction([...])");
7431
7722
  if (statement.type !== "ExpressionStatement") return fail(statement, "Expected a call such as prisma.user.findMany()");
7432
7723
  const expression = statement.expression.type === "AwaitExpression" ? statement.expression.argument : statement.expression;
7433
- if (!(expression.type === "CallExpression" && expression.callee.type === "MemberExpression" && nameOf(expression.callee.property) === "$transaction")) {
7434
- const call = callOf(expression, now);
7435
- return call.ok ? done({
7436
- calls: [call.value],
7437
- transaction: false,
7438
- options: void 0
7439
- }) : call;
7440
- }
7441
- const [batch, options, extra] = expression.arguments;
7442
- if (batch?.type !== "ArrayExpression") return fail(batch ?? expression, "$transaction takes an array of calls here: prisma.$transaction([prisma.user.count(), ...])");
7443
- if (batch.elements.length === 0) return fail(batch, "$transaction needs at least one call");
7444
- if (extra !== void 0) return fail(extra, "$transaction takes the calls and, at most, options");
7445
- const calls = batch.elements.map((element) => element === null || element.type === "SpreadElement" ? fail(element ?? batch, "Expected a call such as prisma.user.count()") : callOf(element, now));
7446
- const refused = calls.find((call) => !call.ok);
7447
- if (refused !== void 0 && !refused.ok) return refused;
7448
- const read = options === void 0 ? done(void 0) : valueOf(options, 1, now);
7449
- return read.ok ? done({
7450
- calls: calls.flatMap((call) => call.ok ? [call.value] : []),
7451
- transaction: true,
7452
- options: read.value
7453
- }) : read;
7724
+ if (expression.type === "CallExpression" && expression.callee.type === "MemberExpression" && nameOf(expression.callee.property) === "$transaction") return transactionOf(expression, now);
7725
+ const call = callOf(expression, now);
7726
+ return call.ok ? done({
7727
+ calls: [call.value],
7728
+ transaction: false,
7729
+ options: void 0
7730
+ }) : call;
7454
7731
  } catch (e) {
7455
- const at = e instanceof SyntaxError && "pos" in e && typeof e.pos === "number" ? e.pos : text.length;
7456
- return fail({
7457
- start: Math.min(at, text.length),
7458
- end: Math.min(at + 1, text.length)
7459
- }, e instanceof Error ? e.message.replace(/ \(\d+:\d+\)$/u, "") : "The text could not be read");
7732
+ return syntaxFailure(e, text);
7460
7733
  }
7461
7734
  }
7462
7735
  z$1.object({
@@ -7573,13 +7846,19 @@ function isWriteOperation(input) {
7573
7846
  // src/studio/server/domain/client-result.ts
7574
7847
  function jsonOf(value) {
7575
7848
  if (value === null || value === void 0) return null;
7576
- if (typeof value === "string" || typeof value === "boolean") return value;
7577
- if (typeof value === "number") return Number.isFinite(value) ? value : null;
7578
- if (typeof value === "bigint") return value.toString();
7849
+ if (typeof value !== "object") return primitiveJsonOf(value);
7579
7850
  if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value.toISOString();
7580
7851
  if (value instanceof Uint8Array) return Buffer.from(value).toString("base64");
7581
7852
  if (Array.isArray(value)) return value.map((item) => jsonOf(item));
7582
- if (typeof value !== "object") return null;
7853
+ return objectJsonOf(value);
7854
+ }
7855
+ function primitiveJsonOf(value) {
7856
+ if (typeof value === "string" || typeof value === "boolean") return value;
7857
+ if (typeof value === "number") return Number.isFinite(value) ? value : null;
7858
+ if (typeof value === "bigint") return value.toString();
7859
+ return null;
7860
+ }
7861
+ function objectJsonOf(value) {
7583
7862
  const prototype = Object.getPrototypeOf(value);
7584
7863
  if (prototype === Object.prototype || prototype === null) return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, jsonOf(item)]));
7585
7864
  const toJson = Reflect.get(value, "toJSON");
@@ -7693,6 +7972,11 @@ z$1.object({
7693
7972
  }
7694
7973
  });
7695
7974
  const FIELD_LISTS = /* @__PURE__ */ new Set(["by", "distinct"]);
7975
+ function namedHere(entry, fields) {
7976
+ if (entry.field !== void 0) return [entry.key];
7977
+ if (!FIELD_LISTS.has(entry.key)) return [];
7978
+ return (Array.isArray(entry.inner) ? entry.inner : [entry.inner]).filter((name) => typeof name === "string" && fields.has(name));
7979
+ }
7696
7980
  /**
7697
7981
  * The model and field pairs the value names, read as arguments of `model`; a model a relation
7698
7982
  * reaches comes with no field, so it is touched even when nothing of it is named.
@@ -7707,8 +7991,11 @@ function namedIn(value, model, models) {
7707
7991
  inner,
7708
7992
  field: fields.get(key)
7709
7993
  }));
7710
- const own = entries.flatMap(({ key, inner, field }) => field !== void 0 ? [key] : FIELD_LISTS.has(key) ? (Array.isArray(inner) ? inner : [inner]).filter((name) => typeof name === "string" && fields.has(name)) : []);
7711
- const deeper = entries.flatMap(({ key, inner, field }) => field === void 0 ? FIELD_LISTS.has(key) ? [] : namedIn(inner, model, models) : field.kind === "object" ? namedIn(inner, field.type, models) : []);
7994
+ const own = entries.flatMap((entry) => namedHere(entry, fields));
7995
+ const deeper = entries.flatMap(({ key, inner, field }) => {
7996
+ if (field !== void 0) return field.kind === "object" ? namedIn(inner, field.type, models) : [];
7997
+ return FIELD_LISTS.has(key) ? [] : namedIn(inner, model, models);
7998
+ });
7712
7999
  const reached = entries.flatMap(({ field }) => field?.kind === "object" && modelNames.has(field.type) ? [[field.type, null]] : []);
7713
8000
  return [
7714
8001
  ...own.map((name) => [model, name]),
@@ -7828,28 +8115,45 @@ function makeGeneratedFields(input) {
7828
8115
  return input.model.fields.flatMap((field) => {
7829
8116
  if (field.kind === "object" || field.kind === "unsupported") return [];
7830
8117
  if (field.name in input.row) return [];
7831
- const generated = /^(?<name>uuid|cuid|nanoid|ulid|now)\((?<argument>[^)]*)\)$/u.exec(field.default ?? "")?.groups;
7832
- const argument = generated?.argument?.trim() ?? "";
7833
- const length = Number(argument);
7834
- const generator = generated?.name === "uuid" ? {
7835
- kind: "uuid",
7836
- version: argument === "7" ? 7 : 4
7837
- } : generated?.name === "cuid" ? {
7838
- kind: "cuid",
7839
- version: argument === "2" ? 2 : 1
7840
- } : generated?.name === "nanoid" ? {
7841
- kind: "nanoid",
7842
- length: Number.isInteger(length) && length > 0 ? length : null
7843
- } : generated?.name === "ulid" ? { kind: "ulid" } : generated?.name === "now" || field.isUpdatedAt ? { kind: "now" } : field.isList && field.isRequired && field.default === null ? {
7844
- kind: "literal",
7845
- value: "[]"
7846
- } : null;
8118
+ const generator = generatorOf(field);
7847
8119
  return generator === null ? [] : [{
7848
8120
  name: field.name,
7849
8121
  generator
7850
8122
  }];
7851
8123
  });
7852
8124
  }
8125
+ const GENERATED_DEFAULT = /^(?<name>uuid|cuid|nanoid|ulid|now)\((?<argument>[^)]*)\)$/u;
8126
+ function generatorOf(field) {
8127
+ const generated = GENERATED_DEFAULT.exec(field.default ?? "")?.groups;
8128
+ if (generated !== void 0) return generatorCalled(generated["name"] ?? "", generated["argument"]?.trim() ?? "");
8129
+ if (field.isUpdatedAt) return { kind: "now" };
8130
+ if (field.isList && field.isRequired && field.default === null) return {
8131
+ kind: "literal",
8132
+ value: "[]"
8133
+ };
8134
+ return null;
8135
+ }
8136
+ function generatorCalled(name, argument) {
8137
+ switch (name) {
8138
+ case "uuid": return {
8139
+ kind: "uuid",
8140
+ version: argument === "7" ? 7 : 4
8141
+ };
8142
+ case "cuid": return {
8143
+ kind: "cuid",
8144
+ version: argument === "2" ? 2 : 1
8145
+ };
8146
+ case "nanoid": {
8147
+ const length = Number(argument);
8148
+ return {
8149
+ kind: "nanoid",
8150
+ length: Number.isInteger(length) && length > 0 ? length : null
8151
+ };
8152
+ }
8153
+ case "ulid": return { kind: "ulid" };
8154
+ default: return { kind: "now" };
8155
+ }
8156
+ }
7853
8157
  // src/studio/server/domain/docs.ts
7854
8158
  z$1.object({ dmmf: z$1.custom().meta({ description: "The document Prisma parsed: datamodel, client schema and mappings." }) }).readonly().meta({ description: "The DMMF the documentation is built from" });
7855
8159
  const LegacyMapping = z$1.object({
@@ -7988,7 +8292,7 @@ function defaultText(value) {
7988
8292
  function fieldDirectives(field) {
7989
8293
  return Object.entries(field).flatMap(([key, set]) => {
7990
8294
  const directive = FIELD_DIRECTIVES.get(key);
7991
- if (!set || directive === void 0) return [];
8295
+ if (directive === void 0 || set !== true) return [];
7992
8296
  if (key !== "hasDefaultValue" || field.default === void 0) return [directive];
7993
8297
  const text = defaultText(field.default);
7994
8298
  return text === null ? [] : [text];
@@ -8005,6 +8309,42 @@ function typeRef(ref) {
8005
8309
  location: ref.location
8006
8310
  };
8007
8311
  }
8312
+ function clientNames(mapping) {
8313
+ const result = LegacyMapping.safeParse(mapping ?? {});
8314
+ const legacy = result.success ? result.data : {};
8315
+ const current = mapping ?? {};
8316
+ return {
8317
+ findUnique: legacy.findSingle ?? legacy.findOne ?? current.findUnique,
8318
+ findFirst: current.findFirst,
8319
+ findMany: current.findMany,
8320
+ create: legacy.createOne ?? legacy.createSingle ?? current.create,
8321
+ update: legacy.updateOne ?? legacy.updateSingle ?? current.update,
8322
+ updateMany: current.updateMany,
8323
+ upsert: legacy.upsertOne ?? legacy.upsertSingle ?? current.upsert,
8324
+ delete: legacy.deleteOne ?? legacy.deleteSingle ?? current.delete,
8325
+ deleteMany: current.deleteMany
8326
+ };
8327
+ }
8328
+ function operationDoc(input) {
8329
+ const { dmmf, model, name, clientName, singular, plural } = input;
8330
+ const { description, queryType } = describeOperation(name, singular, plural);
8331
+ const field = (dmmf.schema.outputObjectTypes.prisma ?? []).find((t) => t.name === queryType)?.fields.find((f) => f.name === clientName);
8332
+ return {
8333
+ name,
8334
+ description,
8335
+ usage: usageOf(name, singular, plural, `prisma.${lowerFirst(model)}.${name}`),
8336
+ inputs: field?.args.map((arg) => ({
8337
+ name: arg.name,
8338
+ types: arg.inputTypes.map(typeRef),
8339
+ required: arg.isRequired
8340
+ })) ?? null,
8341
+ output: {
8342
+ type: field ? field.outputType.type : null,
8343
+ required: field?.isNullable !== true,
8344
+ list: field?.outputType.isList ?? false
8345
+ }
8346
+ };
8347
+ }
8008
8348
  /**
8009
8349
  * The documentation data of a parsed schema: models with their client operations, and the client API types.
8010
8350
  *
@@ -8024,19 +8364,7 @@ function makeDocs(input) {
8024
8364
  models: dmmf.datamodel.models.map((model) => {
8025
8365
  const singular = capitalize(model.name);
8026
8366
  const plural = capitalize(singular);
8027
- const mapping = operationsOf.get(model.name);
8028
- const result = LegacyMapping.safeParse(mapping ?? {});
8029
- const names = {
8030
- findUnique: result.success ? result.data.findSingle ?? result.data.findOne ?? mapping?.findUnique : mapping?.findUnique,
8031
- findFirst: mapping?.findFirst,
8032
- findMany: mapping?.findMany,
8033
- create: result.success ? result.data.createOne ?? result.data.createSingle ?? mapping?.create : mapping?.create,
8034
- update: result.success ? result.data.updateOne ?? result.data.updateSingle ?? mapping?.update : mapping?.update,
8035
- updateMany: mapping?.updateMany,
8036
- upsert: result.success ? result.data.upsertOne ?? result.data.upsertSingle ?? mapping?.upsert : mapping?.upsert,
8037
- delete: result.success ? result.data.deleteOne ?? result.data.deleteSingle ?? mapping?.delete : mapping?.delete,
8038
- deleteMany: mapping?.deleteMany
8039
- };
8367
+ const names = clientNames(operationsOf.get(model.name));
8040
8368
  return {
8041
8369
  name: model.name,
8042
8370
  documentation: model.documentation ?? null,
@@ -8063,25 +8391,14 @@ function makeDocs(input) {
8063
8391
  documentation: field.documentation ?? null,
8064
8392
  required: field.isRequired
8065
8393
  })),
8066
- operations: OPERATIONS.map((name) => {
8067
- const { description, queryType } = describeOperation(name, singular, plural);
8068
- const field = (dmmf.schema.outputObjectTypes.prisma ?? []).find((t) => t.name === queryType)?.fields.find((f) => f.name === names[name]);
8069
- return {
8070
- name,
8071
- description,
8072
- usage: usageOf(name, singular, plural, `prisma.${lowerFirst(model.name)}.${name}`),
8073
- inputs: field?.args.map((arg) => ({
8074
- name: arg.name,
8075
- types: arg.inputTypes.map(typeRef),
8076
- required: arg.isRequired
8077
- })) ?? null,
8078
- output: {
8079
- type: field ? field.outputType.type : null,
8080
- required: !field?.isNullable,
8081
- list: field?.outputType.isList ?? false
8082
- }
8083
- };
8084
- })
8394
+ operations: OPERATIONS.map((name) => operationDoc({
8395
+ dmmf,
8396
+ model: model.name,
8397
+ name,
8398
+ clientName: names[name],
8399
+ singular,
8400
+ plural
8401
+ }))
8085
8402
  };
8086
8403
  }),
8087
8404
  inputTypes: (dmmf.schema.inputObjectTypes.prisma ?? []).map((type) => ({
@@ -8097,7 +8414,7 @@ function makeDocs(input) {
8097
8414
  fields: type.fields.map((field) => ({
8098
8415
  name: field.name,
8099
8416
  types: [typeRef(field.outputType)],
8100
- nullable: !field.isNullable
8417
+ nullable: field.isNullable !== true
8101
8418
  }))
8102
8419
  })),
8103
8420
  enumTypes: [...dmmf.schema.enumTypes.model ?? [], ...dmmf.schema.enumTypes.prisma ?? []].map((type) => ({
@@ -8172,34 +8489,42 @@ z$1.object({
8172
8489
  function makeDbValue(input) {
8173
8490
  const { dialect, field, value } = input;
8174
8491
  if (value === null) return null;
8175
- if (field.isList) {
8176
- if (dialect !== "postgresql") return typeof value === "string" ? value : JSON.stringify(value);
8177
- try {
8178
- return typeof value === "string" ? JSON.parse(value) : value;
8179
- } catch {
8180
- return value;
8181
- }
8182
- }
8492
+ if (field.isList) return listDbValue(dialect, value);
8183
8493
  if (field.kind === "enum") return String(value);
8184
8494
  switch (field.type) {
8185
8495
  case "Int":
8186
- case "Float": {
8187
- if (typeof value === "number") return value;
8188
- if (typeof value === "boolean") return value ? 1 : 0;
8189
- const result = Number(value);
8190
- return Number.isNaN(result) ? value : result;
8191
- }
8496
+ case "Float": return numberDbValue(value);
8192
8497
  case "BigInt":
8193
8498
  case "Decimal": return String(value);
8194
8499
  case "Boolean": {
8195
- const flag = typeof value === "boolean" ? value : typeof value === "number" ? value !== 0 : value === "true" || value === "1";
8196
- return dialect === "sqlite" ? flag ? 1 : 0 : flag;
8500
+ const flag = flagOf(value);
8501
+ if (dialect !== "sqlite") return flag;
8502
+ return flag ? 1 : 0;
8197
8503
  }
8198
8504
  case "DateTime": return dialect === "sqlite" ? String(value) : new Date(String(value));
8199
8505
  case "Bytes": return Buffer.from(String(value), "base64");
8200
8506
  default: return String(value);
8201
8507
  }
8202
8508
  }
8509
+ function listDbValue(dialect, value) {
8510
+ if (dialect !== "postgresql") return typeof value === "string" ? value : JSON.stringify(value);
8511
+ try {
8512
+ return typeof value === "string" ? JSON.parse(value) : value;
8513
+ } catch {
8514
+ return value;
8515
+ }
8516
+ }
8517
+ function numberDbValue(value) {
8518
+ if (typeof value === "number") return value;
8519
+ if (typeof value === "boolean") return value ? 1 : 0;
8520
+ const result = Number(value);
8521
+ return Number.isNaN(result) ? value : result;
8522
+ }
8523
+ function flagOf(value) {
8524
+ if (typeof value === "boolean") return value;
8525
+ if (typeof value === "number") return value !== 0;
8526
+ return value === "true" || value === "1";
8527
+ }
8203
8528
  z$1.object({
8204
8529
  row: z$1.record(z$1.string(), z$1.unknown()).readonly().meta({ description: "The driver row keyed by column." }),
8205
8530
  columnToField: z$1.map(z$1.string(), z$1.string()).meta({ description: "Column name to Prisma field name." }),
@@ -8768,48 +9093,60 @@ const MYSQL_OPERATIONS = /* @__PURE__ */ new Set([
8768
9093
  "buffer_result"
8769
9094
  ]);
8770
9095
  function flattenMysql(value, parent, id, key) {
8771
- if (Array.isArray(value)) return [{
9096
+ if (Array.isArray(value)) return [mysqlOperationNode(id, parent, key), ...value.flatMap((item, index) => childrenOfMysql(item, id, `${id}.${index + 1}`))];
9097
+ if (typeof value !== "object" || value === null) return [];
9098
+ if (key === "table") {
9099
+ const node = mysqlTableNode(value, parent, id);
9100
+ return node === null ? [] : [node, ...childrenOfMysql(value, id, id)];
9101
+ }
9102
+ if (key === "query_block") return [mysqlBlockNode(value, parent, id), ...childrenOfMysql(value, id, id)];
9103
+ if (MYSQL_OPERATIONS.has(key)) return [mysqlOperationNode(id, parent, key), ...childrenOfMysql(value, id, id)];
9104
+ return childrenOfMysql(value, parent, id);
9105
+ }
9106
+ /** An operation MySQL names by its key (`nested_loop`, `ordering_operation`), with nothing of its own. */
9107
+ function mysqlOperationNode(id, parent, key) {
9108
+ return {
8772
9109
  id,
8773
9110
  parent,
8774
9111
  label: key.replaceAll("_", " "),
8775
9112
  detail: null,
8776
9113
  cost: null,
8777
9114
  rows: null
8778
- }, ...value.flatMap((item, index) => childrenOfMysql(item, id, `${id}.${index + 1}`))];
8779
- if (typeof value !== "object" || value === null) return [];
8780
- if (key === "table") {
8781
- const result = MysqlTable.safeParse(value);
8782
- if (!result.success) return [];
8783
- const parts = [result.data.key === void 0 ? null : `key ${result.data.key}`, result.data.attached_condition ?? null].filter((part) => part !== null);
8784
- return [{
8785
- id,
8786
- parent,
8787
- label: `${result.data.access_type ?? "scan"} ${result.data.table_name}`,
8788
- detail: parts.length === 0 ? null : parts.join(" · "),
8789
- cost: Number(result.data.cost_info?.prefix_cost ?? result.data.cost_info?.read_cost ?? NaN) || null,
8790
- rows: result.data.rows_produced_per_join ?? result.data.rows_examined_per_scan ?? null
8791
- }, ...childrenOfMysql(value, id, id)];
8792
- }
8793
- if (key === "query_block") {
8794
- const result = MysqlBlock.safeParse(value);
8795
- return [{
8796
- id,
8797
- parent,
8798
- label: result.success && result.data.select_id !== void 0 ? `query block #${result.data.select_id}` : "query block",
8799
- detail: result.success ? result.data.message ?? null : null,
8800
- cost: result.success ? Number(result.data.cost_info?.query_cost ?? NaN) || null : null,
8801
- rows: null
8802
- }, ...childrenOfMysql(value, id, id)];
8803
- }
8804
- if (MYSQL_OPERATIONS.has(key)) return [{
9115
+ };
9116
+ }
9117
+ /** A table MySQL reads: how, by which key and condition, at what cost; null where it is not one. */
9118
+ function mysqlTableNode(value, parent, id) {
9119
+ const result = MysqlTable.safeParse(value);
9120
+ if (!result.success) return null;
9121
+ const parts = [result.data.key === void 0 ? null : `key ${result.data.key}`, result.data.attached_condition ?? null].filter((part) => part !== null);
9122
+ return {
8805
9123
  id,
8806
9124
  parent,
8807
- label: key.replaceAll("_", " "),
9125
+ label: `${result.data.access_type ?? "scan"} ${result.data.table_name}`,
9126
+ detail: parts.length === 0 ? null : parts.join(" · "),
9127
+ cost: Number(result.data.cost_info?.prefix_cost ?? result.data.cost_info?.read_cost ?? NaN) || null,
9128
+ rows: result.data.rows_produced_per_join ?? result.data.rows_examined_per_scan ?? null
9129
+ };
9130
+ }
9131
+ /** A query block: its number, MySQL's note on it and its cost, where it reads as one. */
9132
+ function mysqlBlockNode(value, parent, id) {
9133
+ const result = MysqlBlock.safeParse(value);
9134
+ if (!result.success) return {
9135
+ id,
9136
+ parent,
9137
+ label: "query block",
8808
9138
  detail: null,
8809
9139
  cost: null,
8810
9140
  rows: null
8811
- }, ...childrenOfMysql(value, id, id)];
8812
- return childrenOfMysql(value, parent, id);
9141
+ };
9142
+ return {
9143
+ id,
9144
+ parent,
9145
+ label: result.data.select_id === void 0 ? "query block" : `query block #${result.data.select_id}`,
9146
+ detail: result.data.message ?? null,
9147
+ cost: Number(result.data.cost_info?.query_cost ?? NaN) || null,
9148
+ rows: null
9149
+ };
8813
9150
  }
8814
9151
  /** The operations nested in an object, numbered under `base` (`1.2` → `1.2.1`, `1.2.2`, ...). */
8815
9152
  function childrenOfMysql(value, parent, base) {
@@ -8873,7 +9210,7 @@ function makePlan(input) {
8873
9210
  switch (input.dialect) {
8874
9211
  case "sqlite": return makeSqlitePlan({ rows: input.rows });
8875
9212
  case "postgresql": return makePostgresPlan({ document: input.rows[0]?.["QUERY PLAN"] ?? null });
8876
- case "mysql": return makeMysqlPlan({ document: input.rows[0]?.EXPLAIN ?? null });
9213
+ case "mysql": return makeMysqlPlan({ document: input.rows[0]?.["EXPLAIN"] ?? null });
8877
9214
  default: return input.dialect;
8878
9215
  }
8879
9216
  }
@@ -9567,9 +9904,17 @@ z$1.object({ fields: z$1.array(z$1.object({
9567
9904
  function generateDefaults(input) {
9568
9905
  return Effect.gen(function* () {
9569
9906
  const now = yield* Clock.currentTimeMillis;
9570
- return yield* Effect.sync(() => Object.fromEntries(input.fields.map(({ name, generator }) => [name, generator.kind === "uuid" ? generator.version === 7 ? v7({ msecs: now }) : randomUUID() : generator.kind === "cuid" ? generator.version === 2 ? createId() : cuid() : generator.kind === "nanoid" ? generator.length === null ? nanoid() : nanoid(generator.length) : generator.kind === "ulid" ? ulid(now) : generator.kind === "now" ? new Date(now).toISOString() : generator.value])));
9907
+ return yield* Effect.sync(() => Object.fromEntries(input.fields.map(({ name, generator }) => [name, generatedValue(generator, now)])));
9571
9908
  });
9572
9909
  }
9910
+ function generatedValue(generator, now) {
9911
+ if (generator.kind === "uuid") return generator.version === 7 ? v7({ msecs: now }) : randomUUID();
9912
+ if (generator.kind === "cuid") return generator.version === 2 ? createId() : cuid();
9913
+ if (generator.kind === "nanoid") return generator.length === null ? nanoid() : nanoid(generator.length);
9914
+ if (generator.kind === "ulid") return ulid(now);
9915
+ if (generator.kind === "now") return new Date(now).toISOString();
9916
+ return generator.value;
9917
+ }
9573
9918
  // src/studio/server/services/language.ts
9574
9919
  function exportOf(description) {
9575
9920
  return z$1.custom((value) => typeof value === "function").meta({ description });
@@ -10430,7 +10775,7 @@ function readMigrationsList(baseDir) {
10430
10775
  }
10431
10776
  }
10432
10777
  })
10433
- })));
10778
+ })), { concurrency: 1 });
10434
10779
  const lock = yield* readFile(path.join(baseDir, LOCK_FILE)).pipe(Effect.orElseSucceed(() => null));
10435
10780
  return {
10436
10781
  baseDir,
@@ -10453,7 +10798,7 @@ function readMigrationsList(baseDir) {
10453
10798
  */
10454
10799
  function resolveMigrationsDir(input) {
10455
10800
  return Effect.gen(function* () {
10456
- const found = (yield* Effect.forEach([.../* @__PURE__ */ new Set([input.cwd, input.schemaDir])], (dir) => readPrismaConfig(dir))).find((config) => config !== null) ?? null;
10801
+ const found = (yield* Effect.forEach([.../* @__PURE__ */ new Set([input.cwd, input.schemaDir])], (dir) => readPrismaConfig(dir), { concurrency: 1 })).find((config) => config !== null) ?? null;
10457
10802
  const configured = found === null ? null : makeMigrationsPath(found.text);
10458
10803
  return found === null || configured === null ? path.join(input.schemaDir, "migrations") : path.resolve(path.dirname(found.file), configured);
10459
10804
  });
@@ -10469,7 +10814,7 @@ function resolveMigrationsDir(input) {
10469
10814
  function migrationsStamp(baseDir) {
10470
10815
  return Effect.gen(function* () {
10471
10816
  const names = (yield* readDirectory(baseDir).pipe(Effect.orElseSucceed(() => []))).filter((name) => MIGRATION_DIRECTORY.test(name)).toSorted();
10472
- const stamps = yield* Effect.forEach(names, (name) => fileStamp(path.join(baseDir, name, MIGRATION_FILE)).pipe(Effect.map((stamp) => `${name}=${stamp ?? ""}`)));
10817
+ const stamps = yield* Effect.forEach(names, (name) => fileStamp(path.join(baseDir, name, MIGRATION_FILE)).pipe(Effect.map((stamp) => `${name}=${stamp ?? ""}`)), { concurrency: 1 });
10473
10818
  const lock = yield* fileStamp(path.join(baseDir, LOCK_FILE));
10474
10819
  return [...stamps, `${LOCK_FILE}=${lock ?? ""}`].join("\n");
10475
10820
  });
@@ -10610,23 +10955,28 @@ function findMigrateEngine(input) {
10610
10955
  url: input.url ?? "",
10611
10956
  cwd: input.schemaDir
10612
10957
  })),
10613
- /**
10614
- * The engine to ask of the database a rehearsal leaves: the wasm engine on the rehearsal's own
10615
- * connection, or the native one on the URL of the copy it ran on. Null where neither can read
10616
- * it: a rehearsal inside a transaction of Studio's connection, which another process cannot see.
10617
- */
10618
- rehearsalEngine: binary !== null && input.driver.dialect !== "mysql" ? null : binary !== null ? (target) => Effect.succeed(openNativeSchemaEngine({
10619
- binary,
10620
- files: input.files,
10621
- url: target.url ?? "",
10622
- cwd: input.schemaDir
10623
- })) : (target) => openSchemaEngine({
10624
- files: input.files,
10625
- adapter: makeSchemaEngineAdapter(target)
10626
- })
10958
+ rehearsalEngine: rehearsalEngineOf(binary, input)
10627
10959
  };
10628
10960
  });
10629
10961
  }
10962
+ /**
10963
+ * The engine to ask of the database a rehearsal leaves: the wasm engine on the rehearsal's own
10964
+ * connection, or the native one on the URL of the copy it ran on. Null where neither can read
10965
+ * it: a rehearsal inside a transaction of Studio's connection, which another process cannot see.
10966
+ */
10967
+ function rehearsalEngineOf(binary, input) {
10968
+ if (binary === null) return (target) => openSchemaEngine({
10969
+ files: input.files,
10970
+ adapter: makeSchemaEngineAdapter(target)
10971
+ });
10972
+ if (input.driver.dialect !== "mysql") return null;
10973
+ return (target) => Effect.succeed(openNativeSchemaEngine({
10974
+ binary,
10975
+ files: input.files,
10976
+ url: target.url ?? "",
10977
+ cwd: input.schemaDir
10978
+ }));
10979
+ }
10630
10980
  // src/studio/server/services/schema.ts
10631
10981
  z$1.object({
10632
10982
  path: z$1.string().meta({
@@ -11089,7 +11439,7 @@ function createTypeChecker(input) {
11089
11439
  return [...service.getSyntacticDiagnostics(file), ...service.getSemanticDiagnostics(file)].flatMap((diagnostic) => {
11090
11440
  const start = diagnostic.start;
11091
11441
  if (start === void 0 || start < base) return [];
11092
- const severity = diagnostic.category === typescript.DiagnosticCategory.Error ? "error" : diagnostic.category === typescript.DiagnosticCategory.Warning ? "warning" : "info";
11442
+ const severity = severityOf(typescript, diagnostic.category);
11093
11443
  return [{
11094
11444
  message: typescript.flattenDiagnosticMessageText(diagnostic.messageText, "\n"),
11095
11445
  severity,
@@ -11103,6 +11453,10 @@ function createTypeChecker(input) {
11103
11453
  }
11104
11454
  };
11105
11455
  }
11456
+ function severityOf(typescript, category) {
11457
+ if (category === typescript.DiagnosticCategory.Error) return "error";
11458
+ return category === typescript.DiagnosticCategory.Warning ? "warning" : "info";
11459
+ }
11106
11460
  // src/studio/server/services/watch.ts
11107
11461
  z$1.object({
11108
11462
  onChange: z$1.custom((value) => typeof value === "function").meta({ description: "What runs after a burst of changes: the reload." }),
@@ -11684,7 +12038,7 @@ function readCounts() {
11684
12038
  })).pipe(Effect.option), { concurrency: 4 });
11685
12039
  return { counts: Object.fromEntries(models.flatMap((model, index) => {
11686
12040
  const count = counted[index];
11687
- return count !== void 0 && Option.isSome(count) ? [[model.name, Number(count.value.rows[0]?.count ?? 0) || 0]] : [];
12041
+ return count !== void 0 && Option.isSome(count) ? [[model.name, Number(count.value.rows[0]?.["count"] ?? 0) || 0]] : [];
11688
12042
  })) };
11689
12043
  });
11690
12044
  }
@@ -11796,7 +12150,7 @@ function readRows(input) {
11796
12150
  columnToField,
11797
12151
  columnToEnum
11798
12152
  })),
11799
- total: Number(counted.rows[0]?.count ?? 0) || 0,
12153
+ total: Number(counted.rows[0]?.["count"] ?? 0) || 0,
11800
12154
  skip: page.skip,
11801
12155
  take: page.take,
11802
12156
  key,
@@ -12316,9 +12670,10 @@ const POSTGRES_ENUM_COLUMNS = {
12316
12670
  */
12317
12671
  function postgresBackupStatements(input) {
12318
12672
  const backup = quoteIdentifier("postgresql", input.name);
12673
+ const enumColumnOf = new Map(input.enumColumns.toReversed().map((one) => [JSON.stringify([one.table, one.column]), one]));
12319
12674
  return [`CREATE SCHEMA ${backup}`, ...input.tables.map((table) => {
12320
12675
  const columns = table.columns.map((column) => {
12321
- const found = input.enumColumns.find((one) => one.table === table.table && one.column === column);
12676
+ const found = enumColumnOf.get(JSON.stringify([table.table, column]));
12322
12677
  const name = quoteIdentifier("postgresql", column);
12323
12678
  return found === void 0 ? name : `${name}::text${found.array ? "[]" : ""} AS ${name}`;
12324
12679
  });
@@ -12387,20 +12742,22 @@ function postgresRestoreStatements(input) {
12387
12742
  const schema = quoteIdentifier("postgresql", input.schema);
12388
12743
  const backup = quoteIdentifier("postgresql", input.name);
12389
12744
  const tables = [...new Set(input.columns.map((column) => column.table))];
12745
+ const columnsOf = Map.groupBy(input.columns, (column) => column.table);
12746
+ const labelsOf = Map.groupBy(input.enums, (one) => one.name);
12390
12747
  const named = (name) => `${schema}.${quoteIdentifier("postgresql", name)}`;
12391
12748
  const constraint = (one) => `ALTER TABLE ${named(one.table)} ADD CONSTRAINT ${quoteIdentifier("postgresql", one.name)} ${one.definition}`;
12392
12749
  return [
12393
- ...[...new Set(input.enums.map((one) => one.name))].map((name) => `CREATE TYPE ${named(name)} AS ENUM (${input.enums.filter((one) => one.name === name).map((one) => stringLiteral("postgresql", one.label)).join(", ")})`),
12750
+ ...[...new Set(input.enums.map((one) => one.name))].map((name) => `CREATE TYPE ${named(name)} AS ENUM (${(labelsOf.get(name) ?? []).map((one) => stringLiteral("postgresql", one.label)).join(", ")})`),
12394
12751
  ...input.sequences.filter((sequence) => !sequence.identity).map((sequence) => `CREATE SEQUENCE ${named(sequence.name)} AS ${sequence.type} START WITH ${sequence.start} INCREMENT BY ${sequence.increment} MINVALUE ${sequence.min} MAXVALUE ${sequence.max} CACHE ${sequence.cache}${sequence.cycle ? " CYCLE" : ""}`),
12395
12752
  ...tables.map((table) => {
12396
- const definitions = input.columns.filter((column) => column.table === table).map((column) => {
12397
- const value = column.generated === "s" ? ` GENERATED ALWAYS AS (${column.default ?? "NULL"}) STORED` : column.identity === "" ? column.default === null ? "" : ` DEFAULT ${column.default}` : ` GENERATED ${column.identity === "a" ? "ALWAYS" : "BY DEFAULT"} AS IDENTITY`;
12753
+ const definitions = (columnsOf.get(table) ?? []).map((column) => {
12754
+ const value = columnValueClause(column);
12398
12755
  return `${quoteIdentifier("postgresql", column.column)} ${column.type}${column.collation === null ? "" : ` COLLATE ${column.collation}`}${value}${column.notNull ? " NOT NULL" : ""}`;
12399
12756
  });
12400
12757
  return `CREATE TABLE ${named(table)} (${definitions.join(", ")})`;
12401
12758
  }),
12402
12759
  ...tables.map((table) => {
12403
- const columns = input.columns.filter((column) => column.table === table && column.generated === "");
12760
+ const columns = (columnsOf.get(table) ?? []).filter((column) => column.generated === "");
12404
12761
  const names = columns.map((column) => quoteIdentifier("postgresql", column.column));
12405
12762
  const values = columns.map((column) => column.isEnum ? `${quoteIdentifier("postgresql", column.column)}::${column.type}` : quoteIdentifier("postgresql", column.column));
12406
12763
  const overriding = columns.some((column) => column.identity === "a") ? " OVERRIDING SYSTEM VALUE" : "";
@@ -12436,6 +12793,21 @@ function postgresClearStatements(input) {
12436
12793
  ...input.enums.map((name) => `DROP TYPE ${schema}.${quoteIdentifier("postgresql", name)}`)
12437
12794
  ];
12438
12795
  }
12796
+ /**
12797
+ * Where a column's value comes from, as its definition says it after the type.
12798
+ *
12799
+ * @example
12800
+ * ```sql
12801
+ * GENERATED ALWAYS AS (price * quantity) STORED
12802
+ * DEFAULT now()
12803
+ * GENERATED BY DEFAULT AS IDENTITY
12804
+ * ```
12805
+ */
12806
+ function columnValueClause(column) {
12807
+ if (column.generated === "s") return ` GENERATED ALWAYS AS (${column.default ?? "NULL"}) STORED`;
12808
+ if (column.identity === "") return column.default === null ? "" : ` DEFAULT ${column.default}`;
12809
+ return ` GENERATED ${column.identity === "a" ? "ALWAYS" : "BY DEFAULT"} AS IDENTITY`;
12810
+ }
12439
12811
  // src/migrate/adapter/commands.ts
12440
12812
  /** The table Prisma Migrate records what it has applied in. */
12441
12813
  const MIGRATIONS_TABLE = "_prisma_migrations";
@@ -12509,7 +12881,7 @@ function readAppliedMigrations(driver) {
12509
12881
  startedAt: instantOf(row, "started_at"),
12510
12882
  finishedAt: instantOf(row, "finished_at"),
12511
12883
  rolledBackAt: instantOf(row, "rolled_back_at"),
12512
- appliedStepsCount: Number(row.applied_steps_count ?? 0),
12884
+ appliedStepsCount: Number(row["applied_steps_count"] ?? 0),
12513
12885
  checksum: textOf(row, "checksum") ?? ""
12514
12886
  }))
12515
12887
  })
@@ -12544,6 +12916,7 @@ function migrationStatus(input) {
12544
12916
  configDir: input.configDir
12545
12917
  });
12546
12918
  const appliedNames = new Set(applied.migrations.map((migration) => migration.name));
12919
+ const directories = new Set(input.migrations.migrationDirectories.map((directory) => directory.path));
12547
12920
  const history = diagnosed.history;
12548
12921
  const empty = yield* engineCommand(() => input.engine.diff({
12549
12922
  from: { tag: "empty" },
@@ -12565,7 +12938,7 @@ function migrationStatus(input) {
12565
12938
  /** `databaseIsBehind`, `migrationsDirectoryIsBehind` or `historiesDiverge`; null when in step. */
12566
12939
  divergence: history === null ? null : history.diagnostic,
12567
12940
  drift: diff.drift,
12568
- missingFiles: applied.migrations.map((migration) => migration.name).filter((name) => !input.migrations.migrationDirectories.some((directory) => directory.path === name)),
12941
+ missingFiles: applied.migrations.map((migration) => migration.name).filter((name) => !directories.has(name)),
12569
12942
  baselineNeeded: applied.migrations.length === 0 && input.migrations.migrationDirectories.length > 0 && empty.exitCode === 2
12570
12943
  };
12571
12944
  });
@@ -12606,7 +12979,7 @@ function baselineCandidates(input) {
12606
12979
  name: directory.path,
12607
12980
  matches: result.exitCode === 0,
12608
12981
  difference: result.exitCode === 0 ? "" : result.stdout ?? ""
12609
- }))));
12982
+ }))), { concurrency: 1 });
12610
12983
  }
12611
12984
  /**
12612
12985
  * Baselines the database at a migration: records it and every migration before it as applied
@@ -12643,7 +13016,7 @@ function baselineMigrations(input) {
12643
13016
  migrations: input.migrations,
12644
13017
  name,
12645
13018
  tablePresent: index > 0
12646
- }));
13019
+ }), { concurrency: 1 });
12647
13020
  return names;
12648
13021
  });
12649
13022
  }
@@ -12751,11 +13124,11 @@ function countTables(driver, tables) {
12751
13124
  params: []
12752
13125
  }).pipe(Effect.map((result) => ({
12753
13126
  table: table.table,
12754
- rows: Number(result.rows[0]?.count ?? 0)
13127
+ rows: Number(result.rows[0]?.["count"] ?? 0)
12755
13128
  })), Effect.orElseSucceed(() => ({
12756
13129
  table: table.table,
12757
13130
  rows: null
12758
- }))));
13131
+ }))), { concurrency: 1 });
12759
13132
  });
12760
13133
  }
12761
13134
  /**
@@ -12803,8 +13176,10 @@ function rehearseOn(input) {
12803
13176
  target,
12804
13177
  statements,
12805
13178
  failedYet
12806
- }));
13179
+ }), { concurrency: 1 });
12807
13180
  const after = yield* countTables(target);
13181
+ const rowsBefore = new Map(before.toReversed().map((one) => [one.table, one.rows]));
13182
+ const rowsAfter = new Map(after.toReversed().map((one) => [one.table, one.rows]));
12808
13183
  const ok = results.every((step) => step.ok);
12809
13184
  const diff = input.compareWith === null ? null : yield* migrationDiff({
12810
13185
  engine: yield* input.compareWith(target),
@@ -12816,8 +13191,8 @@ function rehearseOn(input) {
12816
13191
  steps: results,
12817
13192
  tables: [...new Set([...before, ...after].map((one) => one.table))].map((table) => ({
12818
13193
  table,
12819
- before: before.find((one) => one.table === table)?.rows ?? null,
12820
- after: after.find((one) => one.table === table)?.rows ?? null
13194
+ before: rowsBefore.get(table) ?? null,
13195
+ after: rowsAfter.get(table) ?? null
12821
13196
  })),
12822
13197
  /** Null when the engine cannot be asked: the result is not compared with the schema. */
12823
13198
  schemaMatches: diff === null ? null : !diff.drift,
@@ -13002,10 +13377,10 @@ function stateOf(driver) {
13002
13377
  const history = (yield* driver.query({
13003
13378
  sql: `SELECT to_regclass('"_prisma_migrations"') IS NOT NULL AS "there"`,
13004
13379
  params: []
13005
- })).rows[0]?.there === true ? (yield* driver.query({
13380
+ })).rows[0]?.["there"] === true ? (yield* driver.query({
13006
13381
  sql: "SELECT COUNT(*)::int AS \"count\" FROM \"_prisma_migrations\"",
13007
13382
  params: []
13008
- })).rows[0]?.count : null;
13383
+ })).rows[0]?.["count"] : null;
13009
13384
  return JSON.stringify({
13010
13385
  tables: introspected.tables,
13011
13386
  rows,
@@ -13026,7 +13401,7 @@ function createPostgresBackup(driver, name) {
13026
13401
  sql: "SELECT current_schema() AS \"name\"",
13027
13402
  params: []
13028
13403
  })).rows;
13029
- const current = typeof schema[0]?.name === "string" ? schema[0].name : "public";
13404
+ const current = typeof schema[0]?.["name"] === "string" ? schema[0]["name"] : "public";
13030
13405
  const columns = CatalogueColumns.safeParse((yield* driver.query(POSTGRES_RESTORE_CATALOGUE.columns)).rows);
13031
13406
  const enums = CatalogueEnums.safeParse((yield* driver.query(POSTGRES_RESTORE_CATALOGUE.enums)).rows);
13032
13407
  const sequences = CatalogueSequences.safeParse((yield* driver.query(POSTGRES_RESTORE_CATALOGUE.sequences)).rows);
@@ -13038,14 +13413,14 @@ function createPostgresBackup(driver, name) {
13038
13413
  const copies = postgresBackupStatements({
13039
13414
  name,
13040
13415
  schema: current,
13041
- tables: [...new Set(columns.data.map((column) => column.table))].map((table) => ({
13416
+ tables: [...Map.groupBy(columns.data, (column) => column.table)].map(([table, ofTable]) => ({
13042
13417
  table,
13043
- columns: columns.data.filter((one) => one.table === table).map((one) => one.column)
13418
+ columns: ofTable.map((one) => one.column)
13044
13419
  })),
13045
13420
  enumColumns: enumColumns.map((row) => ({
13046
- table: String(row.table),
13047
- column: String(row.column),
13048
- array: row.array === true
13421
+ table: String(row["table"]),
13422
+ column: String(row["column"]),
13423
+ array: row["array"] === true
13049
13424
  }))
13050
13425
  });
13051
13426
  const restore = postgresRestoreStatements({
@@ -13069,7 +13444,7 @@ function createPostgresBackup(driver, name) {
13069
13444
  yield* Effect.forEach(restore, (statement, position) => driver.executeRaw({
13070
13445
  sql: `INSERT INTO ${quoted}."${RESTORE_TABLE}" ("position", "statement") VALUES ($1, $2)`,
13071
13446
  params: [position, statement]
13072
- }));
13447
+ }), { concurrency: 1 });
13073
13448
  yield* driver.executeRaw({
13074
13449
  sql: `INSERT INTO ${quoted}."${STATE_TABLE}" ("state") VALUES ($1)`,
13075
13450
  params: [state]
@@ -13116,7 +13491,7 @@ function restorePostgresBackup(driver, name) {
13116
13491
  })).rows);
13117
13492
  if (!tables.success || !foreignKeys.success || !enums.success) return yield* new MigrateConfigError({ message: "The backup could not be restored: the catalogue of the database did not read." });
13118
13493
  const clear = postgresClearStatements({
13119
- schema: typeof schema[0]?.name === "string" ? schema[0].name : "public",
13494
+ schema: typeof schema[0]?.["name"] === "string" ? schema[0]["name"] : "public",
13120
13495
  tables: tables.data.map((one) => one.name),
13121
13496
  foreignKeys: foreignKeys.data.map((one) => ({
13122
13497
  table: one.table ?? "",
@@ -13127,9 +13502,9 @@ function restorePostgresBackup(driver, name) {
13127
13502
  yield* driver.executeScript([
13128
13503
  "BEGIN",
13129
13504
  ...clear,
13130
- ...stored.rows.map((row) => String(row.statement))
13505
+ ...stored.rows.map((row) => String(row["statement"]))
13131
13506
  ].join(";\n"));
13132
- if ((yield* stateOf(driver)) !== kept[0]?.state) return yield* new MigrateConfigError({ message: `The backup could not be restored: the database ${name} makes again is not the one it was taken of, so nothing was changed. Its rows are in the schema of that name.` });
13507
+ if ((yield* stateOf(driver)) !== kept[0]?.["state"]) return yield* new MigrateConfigError({ message: `The backup could not be restored: the database ${name} makes again is not the one it was taken of, so nothing was changed. Its rows are in the schema of that name.` });
13133
13508
  yield* driver.query({
13134
13509
  sql: "SELECT 1",
13135
13510
  params: []
@@ -13203,16 +13578,16 @@ function listBackups(input) {
13203
13578
  location: path.join(directory, file),
13204
13579
  size: Number(stamp?.split(":")[1] ?? 0),
13205
13580
  restorable: true
13206
- }))));
13581
+ }))), { concurrency: 1 });
13207
13582
  }
13208
13583
  return (yield* driver.query({
13209
13584
  sql: "SELECT n.nspname AS name, EXISTS (SELECT 1 FROM pg_class c WHERE c.relnamespace = n.oid AND c.relname = '_hekireki_restore') AS restorable FROM pg_namespace n WHERE n.nspname LIKE 'backup\\_%' ORDER BY n.nspname DESC",
13210
13585
  params: []
13211
13586
  }).pipe(Effect.orElseSucceed(() => ({ rows: [] })))).rows.map((row) => ({
13212
- name: String(row.name),
13213
- location: `schema ${String(row.name)}`,
13587
+ name: String(row["name"]),
13588
+ location: `schema ${String(row["name"])}`,
13214
13589
  size: null,
13215
- restorable: row.restorable === true
13590
+ restorable: row["restorable"] === true
13216
13591
  }));
13217
13592
  });
13218
13593
  }
@@ -13264,13 +13639,13 @@ function replaceWithAttached(driver) {
13264
13639
  return Effect.gen(function* () {
13265
13640
  const current = yield* backupObjects(driver, "main");
13266
13641
  const saved = yield* backupObjects(driver, "hekireki_backup");
13267
- const drops = current.rows.filter((row) => row.type === "table" || row.type === "view").map((row) => `DROP ${row.type === "view" ? "VIEW" : "TABLE"} IF EXISTS main.${quoteIdentifier("sqlite", String(row.name))}`);
13268
- const creates = saved.rows.map((row) => String(row.sql));
13269
- const copies = saved.rows.filter((row) => row.type === "table").map((row) => `INSERT INTO main.${quoteIdentifier("sqlite", String(row.name))} SELECT * FROM hekireki_backup.${quoteIdentifier("sqlite", String(row.name))}`);
13642
+ const drops = current.rows.filter((row) => row["type"] === "table" || row["type"] === "view").map((row) => `DROP ${row["type"] === "view" ? "VIEW" : "TABLE"} IF EXISTS main.${quoteIdentifier("sqlite", String(row["name"]))}`);
13643
+ const creates = saved.rows.map((row) => String(row["sql"]));
13644
+ const copies = saved.rows.filter((row) => row["type"] === "table").map((row) => `INSERT INTO main.${quoteIdentifier("sqlite", String(row["name"]))} SELECT * FROM hekireki_backup.${quoteIdentifier("sqlite", String(row["name"]))}`);
13270
13645
  const sequence = (yield* driver.query({
13271
13646
  sql: "SELECT COUNT(*) AS count FROM hekireki_backup.sqlite_master WHERE name = 'sqlite_sequence'",
13272
13647
  params: []
13273
- })).rows[0]?.count;
13648
+ })).rows[0]?.["count"];
13274
13649
  yield* driver.executeScript([
13275
13650
  "PRAGMA foreign_keys=OFF",
13276
13651
  "BEGIN",