effect-qb 0.20.0 → 0.22.0

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 (58) hide show
  1. package/dist/index.js +663 -261
  2. package/dist/mysql.js +2840 -492
  3. package/dist/postgres/metadata.js +113 -14
  4. package/dist/postgres.js +2596 -285
  5. package/dist/sqlite.js +2783 -450
  6. package/dist/standard.js +663 -261
  7. package/package.json +2 -3
  8. package/src/internal/analytics.ts +264 -0
  9. package/src/internal/coercion/errors.d.ts +1 -1
  10. package/src/internal/coercion/errors.ts +1 -1
  11. package/src/internal/custom-sql-renderer.ts +20 -0
  12. package/src/internal/dialect-numeric.ts +332 -0
  13. package/src/internal/dialect-renderers/mysql.ts +68 -13
  14. package/src/internal/dialect-renderers/postgres.ts +83 -13
  15. package/src/internal/dialect-renderers/sqlite.ts +57 -13
  16. package/src/internal/dynamic.ts +131 -0
  17. package/src/internal/executor.ts +198 -7
  18. package/src/internal/expression-ast.ts +62 -1
  19. package/src/internal/fragment.ts +120 -0
  20. package/src/internal/function-constraints.ts +105 -0
  21. package/src/internal/grouping-key.ts +26 -0
  22. package/src/internal/numeric.ts +204 -0
  23. package/src/internal/query.ts +13 -1
  24. package/src/internal/runtime/normalize.ts +5 -2
  25. package/src/internal/runtime/schema.ts +2 -1
  26. package/src/internal/standard-dsl.ts +43 -20
  27. package/src/internal/window-frame.ts +30 -0
  28. package/src/internal/window-renderer.ts +25 -0
  29. package/src/mysql/executor.ts +126 -45
  30. package/src/mysql/function/aggregate.ts +87 -1
  31. package/src/mysql/function/index.ts +5 -2
  32. package/src/mysql/function/numeric.ts +185 -0
  33. package/src/mysql/function/temporal.ts +6 -6
  34. package/src/mysql/function/window.ts +12 -0
  35. package/src/mysql/internal/dsl.ts +38 -20
  36. package/src/mysql.ts +2 -0
  37. package/src/postgres/executor.ts +111 -45
  38. package/src/postgres/function/aggregate.ts +124 -1
  39. package/src/postgres/function/core.ts +2 -1
  40. package/src/postgres/function/index.ts +19 -1
  41. package/src/postgres/function/numeric.ts +246 -0
  42. package/src/postgres/function/window.ts +12 -0
  43. package/src/postgres/internal/dsl.ts +38 -20
  44. package/src/sqlite/executor.ts +96 -45
  45. package/src/sqlite/function/aggregate.ts +90 -1
  46. package/src/sqlite/function/index.ts +5 -2
  47. package/src/sqlite/function/numeric.ts +139 -0
  48. package/src/sqlite/function/window.ts +12 -0
  49. package/src/sqlite/internal/dsl.ts +38 -20
  50. package/src/sqlite.ts +2 -0
  51. package/src/standard/function/core.ts +8 -1
  52. package/src/standard/function/index.ts +18 -11
  53. package/src/standard/function/string.ts +1 -1
  54. package/src/standard/function/window.ts +10 -1
  55. package/src/standard/query.ts +19 -7
  56. package/src/standard/type.ts +16 -0
  57. package/src/standard.ts +4 -0
  58. package/src/standard/function/temporal.ts +0 -78
package/dist/mysql.js CHANGED
@@ -110647,13 +110647,46 @@ var narrowMysqlDriverErrorForReadQuery = (error) => {
110647
110647
  cause: error
110648
110648
  };
110649
110649
  };
110650
- // src/mysql/json.ts
110651
- var exports_json = {};
110652
- __export(exports_json, {
110653
- typeOf: () => typeOf,
110654
- stripNulls: () => stripNulls,
110655
- pathMatch: () => pathMatch,
110656
- length: () => length
110650
+ // src/mysql/function/index.ts
110651
+ var exports_function = {};
110652
+ __export(exports_function, {
110653
+ window: () => exports_window,
110654
+ upper: () => upper,
110655
+ temporal: () => exports_temporal,
110656
+ sum: () => sum,
110657
+ string: () => exports_string,
110658
+ rowNumber: () => rowNumber,
110659
+ round: () => round2,
110660
+ rank: () => rank,
110661
+ over: () => over,
110662
+ numeric: () => exports_numeric,
110663
+ now: () => now,
110664
+ modulo: () => modulo2,
110665
+ min: () => min,
110666
+ max: () => max,
110667
+ lower: () => lower,
110668
+ localTimestamp: () => localTimestamp,
110669
+ localTime: () => localTime,
110670
+ lastValue: () => lastValue2,
110671
+ firstValue: () => firstValue2,
110672
+ denseRank: () => denseRank,
110673
+ currentTimestamp: () => currentTimestamp,
110674
+ currentTime: () => currentTime,
110675
+ currentDate: () => currentDate,
110676
+ count: () => count,
110677
+ core: () => exports_core,
110678
+ concat: () => concat,
110679
+ coalesce: () => coalesce,
110680
+ call: () => call,
110681
+ avg: () => avg,
110682
+ aggregate: () => exports_aggregate
110683
+ });
110684
+
110685
+ // src/mysql/function/core.ts
110686
+ var exports_core = {};
110687
+ __export(exports_core, {
110688
+ coalesce: () => coalesce,
110689
+ call: () => call
110657
110690
  });
110658
110691
 
110659
110692
  // src/mysql/internal/dsl.ts
@@ -111487,8 +111520,9 @@ var normalizeOffsetTime = (value) => {
111487
111520
  return `${formatLocalTime(validDate(value))}Z`;
111488
111521
  }
111489
111522
  const raw = expectString(value, "offset time").trim();
111490
- if (isValidOffsetTimeString(raw)) {
111491
- return raw;
111523
+ const canonical = raw.replace(/([+-]\d{2})$/, "$1:00").replace(/([+-]\d{2})(\d{2})$/, "$1:$2");
111524
+ if (isValidOffsetTimeString(canonical)) {
111525
+ return canonical;
111492
111526
  }
111493
111527
  throw new Error("Expected an offset-time value");
111494
111528
  };
@@ -112546,6 +112580,14 @@ var castTargetGroupingKey = (target) => {
112546
112580
  };
112547
112581
  var escapeGroupingText = (value) => value.replace(/\\/g, "\\\\").replace(/,/g, "\\,").replace(/\|/g, "\\|").replace(/=/g, "\\=").replace(/>/g, "\\>");
112548
112582
  var functionCallNameGroupingKey = (name) => escapeGroupingText(name);
112583
+ var customSqlGroupingKey = (strings, values) => strings.map((part, index4) => {
112584
+ const value = values[index4];
112585
+ if (value === undefined) {
112586
+ return escapeGroupingText(part);
112587
+ }
112588
+ const rendered = isExpression2(value) ? groupingKeyOfExpression(value) : `identifier:${value.parts.map(escapeGroupingText).join(".")}`;
112589
+ return `${escapeGroupingText(part)}${rendered}`;
112590
+ }).join("|");
112549
112591
  var quantifiedComparisonGroupingName = (kind) => kind === "comparisonAny" ? "compareAny" : "compareAll";
112550
112592
  var caseGroupingKey = (branches, fallback) => {
112551
112593
  const typedBranches = branches;
@@ -112627,12 +112669,19 @@ var groupingKeyOfExpression = (expression) => {
112627
112669
  return `collate(${requiredExpressionGroupingKey("collate", ast.value)},${collationGroupingKey(ast.collation)})`;
112628
112670
  case "function":
112629
112671
  return `function(${functionCallNameGroupingKey(ast.name)},${functionCallArgsGroupingKey(ast.args)})`;
112672
+ case "customSql":
112673
+ return `customSql(${customSqlGroupingKey(ast.strings, ast.values)})`;
112630
112674
  case "isNull":
112631
112675
  case "isNotNull":
112632
112676
  case "not":
112633
112677
  case "upper":
112634
112678
  case "lower":
112635
112679
  case "count":
112680
+ case "sum":
112681
+ case "avg":
112682
+ case "abs":
112683
+ case "round":
112684
+ case "negate":
112636
112685
  case "max":
112637
112686
  case "min":
112638
112687
  return `${ast.kind}(${requiredExpressionGroupingKey(ast.kind, ast.value)})`;
@@ -112653,6 +112702,11 @@ var groupingKeyOfExpression = (expression) => {
112653
112702
  case "contains":
112654
112703
  case "containedBy":
112655
112704
  case "overlaps":
112705
+ case "add":
112706
+ case "subtract":
112707
+ case "multiply":
112708
+ case "divide":
112709
+ case "modulo":
112656
112710
  return `${ast.kind}(${requiredBinaryExpressionGroupingKey(ast.kind, ast.left, ast.right)})`;
112657
112711
  case "and":
112658
112712
  case "or":
@@ -112728,6 +112782,31 @@ var dedupeGroupedExpressions = (values) => {
112728
112782
  });
112729
112783
  };
112730
112784
 
112785
+ // src/internal/window-frame.ts
112786
+ var validateBoundary = (boundary) => {
112787
+ if (typeof boundary === "object") {
112788
+ const value = "preceding" in boundary ? boundary.preceding : boundary.following;
112789
+ if (!Number.isSafeInteger(value) || value < 0) {
112790
+ throw new Error("window frame offsets must be non-negative safe integers");
112791
+ }
112792
+ }
112793
+ };
112794
+ var validateWindowFrame = (frame) => {
112795
+ if (frame === undefined) {
112796
+ return;
112797
+ }
112798
+ validateBoundary(frame.start);
112799
+ if (frame.end !== undefined) {
112800
+ validateBoundary(frame.end);
112801
+ }
112802
+ if (frame.start === "unboundedFollowing") {
112803
+ throw new Error("window frame cannot start with unbounded following");
112804
+ }
112805
+ if (frame.end === "unboundedPreceding") {
112806
+ throw new Error("window frame cannot end with unbounded preceding");
112807
+ }
112808
+ };
112809
+
112731
112810
  // src/internal/dsl-transaction-ddl-runtime.ts
112732
112811
  var renderTransactionIsolationLevel = (isolationLevel) => {
112733
112812
  if (isolationLevel === undefined) {
@@ -113982,6 +114061,23 @@ var extractRequiredFromDialectInputRuntime = (value) => {
113982
114061
  const expression = toDialectExpression(value);
113983
114062
  return Object.keys(expression[TypeId].dependencies);
113984
114063
  };
114064
+ var normalizeWindowSpec = (spec) => {
114065
+ validateWindowFrame(spec?.frame);
114066
+ const partitionBy = [...spec?.partitionBy ?? []];
114067
+ const orderBy = (spec?.orderBy ?? []).map((term) => {
114068
+ const direction = term.direction ?? "asc";
114069
+ return {
114070
+ value: term.value,
114071
+ direction
114072
+ };
114073
+ });
114074
+ return {
114075
+ partitionBy,
114076
+ orderBy,
114077
+ frame: spec?.frame
114078
+ };
114079
+ };
114080
+ var mergeWindowExpressions = (value, partitionBy, orderBy) => value === undefined ? [...partitionBy, ...orderBy.map((term) => term.value)] : [value, ...partitionBy, ...orderBy.map((term) => term.value)];
113985
114081
  var extractRequiredFromDialectNumericInputRuntime = (value) => {
113986
114082
  const expression = toDialectNumericExpression(value);
113987
114083
  return Object.keys(expression[TypeId].dependencies);
@@ -114001,6 +114097,34 @@ var buildBinaryPredicate = (left, right, kind, nullability = "maybe") => {
114001
114097
  right: rightExpression
114002
114098
  });
114003
114099
  };
114100
+ var upper = (value) => {
114101
+ const expression = toDialectStringExpression(value);
114102
+ return makeExpression2({
114103
+ runtime: "",
114104
+ dbType: profile.textDb,
114105
+ nullability: expression[TypeId].nullability,
114106
+ dialect: profile.dialect,
114107
+ kind: expression[TypeId].kind,
114108
+ dependencies: expression[TypeId].dependencies
114109
+ }, {
114110
+ kind: "upper",
114111
+ value: expression
114112
+ });
114113
+ };
114114
+ var lower = (value) => {
114115
+ const expression = toDialectStringExpression(value);
114116
+ return makeExpression2({
114117
+ runtime: "",
114118
+ dbType: profile.textDb,
114119
+ nullability: expression[TypeId].nullability,
114120
+ dialect: profile.dialect,
114121
+ kind: expression[TypeId].kind,
114122
+ dependencies: expression[TypeId].dependencies
114123
+ }, {
114124
+ kind: "lower",
114125
+ value: expression
114126
+ });
114127
+ };
114004
114128
  var array2 = (element) => ({
114005
114129
  dialect: profile.dialect,
114006
114130
  kind: `${element.kind}[]`,
@@ -114486,6 +114610,127 @@ var jsonb = {
114486
114610
  pathExists: jsonPathExists,
114487
114611
  pathMatch: jsonPathMatch
114488
114612
  };
114613
+ var concat = (...values) => {
114614
+ const expressions = values.map((value) => toDialectStringExpression(value));
114615
+ return makeExpression2({
114616
+ runtime: "",
114617
+ dbType: profile.textDb,
114618
+ nullability: mergeNullabilityManyRuntime(expressions),
114619
+ dialect: expressions.find((value) => value[TypeId].dialect !== undefined)?.[TypeId].dialect ?? profile.dialect,
114620
+ kind: mergeAggregationManyRuntime(expressions),
114621
+ dependencies: mergeManyDependencies(expressions)
114622
+ }, {
114623
+ kind: "concat",
114624
+ values: expressions
114625
+ });
114626
+ };
114627
+ var count = (value) => {
114628
+ const expression = toDialectExpression(value);
114629
+ return makeExpression2({
114630
+ runtime: undefined,
114631
+ dbType: mysqlDatatypes.bigint(),
114632
+ nullability: "never",
114633
+ dialect: expression[TypeId].dialect,
114634
+ kind: "aggregate",
114635
+ dependencies: expression[TypeId].dependencies
114636
+ }, {
114637
+ kind: "count",
114638
+ value: expression
114639
+ });
114640
+ };
114641
+ var over = (value, spec = {}) => {
114642
+ const normalized = normalizeWindowSpec(spec);
114643
+ const expressions = mergeWindowExpressions(value, normalized.partitionBy, normalized.orderBy);
114644
+ return makeExpression2({
114645
+ runtime: undefined,
114646
+ dbType: value[TypeId].dbType,
114647
+ nullability: value[TypeId].nullability,
114648
+ dialect: expressions.find((expression) => expression[TypeId].dialect !== undefined)?.[TypeId].dialect ?? profile.dialect,
114649
+ kind: "window",
114650
+ dependencies: mergeManyDependencies(expressions)
114651
+ }, {
114652
+ kind: "window",
114653
+ function: "over",
114654
+ value,
114655
+ partitionBy: normalized.partitionBy,
114656
+ orderBy: normalized.orderBy,
114657
+ frame: normalized.frame
114658
+ });
114659
+ };
114660
+ var buildNumberWindow = (kind, spec) => {
114661
+ const normalized = normalizeWindowSpec(spec);
114662
+ const expressions = mergeWindowExpressions(undefined, normalized.partitionBy, normalized.orderBy);
114663
+ return makeExpression2({
114664
+ runtime: undefined,
114665
+ dbType: mysqlDatatypes.bigint(),
114666
+ nullability: "never",
114667
+ dialect: expressions.find((expression) => expression[TypeId].dialect !== undefined)?.[TypeId].dialect ?? profile.dialect,
114668
+ kind: "window",
114669
+ dependencies: mergeManyDependencies(expressions)
114670
+ }, {
114671
+ kind: "window",
114672
+ function: kind,
114673
+ partitionBy: normalized.partitionBy,
114674
+ orderBy: normalized.orderBy,
114675
+ frame: normalized.frame
114676
+ });
114677
+ };
114678
+ var rowNumber = (spec) => buildNumberWindow("rowNumber", spec);
114679
+ var rank = (spec) => buildNumberWindow("rank", spec);
114680
+ var denseRank = (spec) => buildNumberWindow("denseRank", spec);
114681
+ var max = (value) => makeExpression2({
114682
+ runtime: undefined,
114683
+ dbType: value[TypeId].dbType,
114684
+ nullability: "maybe",
114685
+ dialect: value[TypeId].dialect,
114686
+ kind: "aggregate",
114687
+ dependencies: value[TypeId].dependencies
114688
+ }, {
114689
+ kind: "max",
114690
+ value
114691
+ });
114692
+ var min = (value) => makeExpression2({
114693
+ runtime: undefined,
114694
+ dbType: value[TypeId].dbType,
114695
+ nullability: "maybe",
114696
+ dialect: value[TypeId].dialect,
114697
+ kind: "aggregate",
114698
+ dependencies: value[TypeId].dependencies
114699
+ }, {
114700
+ kind: "min",
114701
+ value
114702
+ });
114703
+ var resolveCoalesceNullabilityRuntime = (values) => values.some((value) => value[TypeId].nullability === "never") ? "never" : values.some((value) => value[TypeId].nullability === "maybe") ? "maybe" : "always";
114704
+ var coalesce = (...values) => {
114705
+ const expressions = values.map((value) => toDialectExpression(value));
114706
+ const representative = expressions.find((value) => value[TypeId].nullability !== "always") ?? expressions[0];
114707
+ return makeExpression2({
114708
+ runtime: undefined,
114709
+ dbType: representative[TypeId].dbType,
114710
+ nullability: resolveCoalesceNullabilityRuntime(expressions),
114711
+ dialect: expressions.find((value) => value[TypeId].dialect !== undefined)?.[TypeId].dialect ?? profile.dialect,
114712
+ kind: mergeAggregationManyRuntime(expressions),
114713
+ dependencies: mergeManyDependencies(expressions)
114714
+ }, {
114715
+ kind: "coalesce",
114716
+ values: expressions
114717
+ });
114718
+ };
114719
+ var call = (name, ...args) => {
114720
+ const expressions = args.map((value) => toDialectExpression(value));
114721
+ return makeExpression2({
114722
+ runtime: undefined,
114723
+ dbType: profile.textDb,
114724
+ nullability: "maybe",
114725
+ dialect: expressions.find((value) => value[TypeId].dialect !== undefined)?.[TypeId].dialect ?? profile.dialect,
114726
+ kind: mergeAggregationManyRuntime(expressions),
114727
+ dependencies: mergeManyDependencies(expressions)
114728
+ }, {
114729
+ kind: "function",
114730
+ name,
114731
+ args: expressions
114732
+ });
114733
+ };
114489
114734
  var toMutationValueExpression = (value, column) => {
114490
114735
  const columnState = column[TypeId];
114491
114736
  const normalizeMutationValue = (candidate) => {
@@ -114777,175 +115022,2027 @@ var {
114777
115022
  normalizeColumnList,
114778
115023
  defaultIndexName
114779
115024
  });
114780
-
114781
- // src/mysql/json.ts
114782
- var typeOf = json.typeOf;
114783
- var length = json.length;
114784
- var stripNulls = json.stripNulls;
114785
- var pathMatch = json.pathMatch;
114786
- // src/mysql/executor.ts
114787
- var exports_executor2 = {};
114788
- __export(exports_executor2, {
114789
- withTransaction: () => withTransaction2,
114790
- make: () => make4,
114791
- driver: () => driver2,
114792
- custom: () => custom3
115025
+ // src/mysql/function/string.ts
115026
+ var exports_string = {};
115027
+ __export(exports_string, {
115028
+ upper: () => upper,
115029
+ lower: () => lower,
115030
+ concat: () => concat
114793
115031
  });
114794
- import * as Effect2 from "effect/Effect";
114795
- import * as SqlClient3 from "effect/unstable/sql/SqlClient";
114796
- import * as Stream2 from "effect/Stream";
114797
-
114798
- // src/internal/executor.ts
114799
- var exports_executor = {};
114800
- __export(exports_executor, {
114801
- withTransaction: () => withTransaction,
114802
- streamFromSqlClient: () => streamFromSqlClient,
114803
- remapRows: () => remapRows,
114804
- makeRowDecoder: () => makeRowDecoder,
114805
- make: () => make3,
114806
- hasWriteCapability: () => hasWriteCapability,
114807
- fromSqlClient: () => fromSqlClient,
114808
- fromDriver: () => fromDriver,
114809
- driver: () => driver,
114810
- decodeRows: () => decodeRows,
114811
- decodeChunk: () => decodeChunk
115032
+ // src/mysql/function/aggregate.ts
115033
+ var exports_aggregate = {};
115034
+ __export(exports_aggregate, {
115035
+ sum: () => sum,
115036
+ min: () => min,
115037
+ max: () => max,
115038
+ count: () => count,
115039
+ avg: () => avg
114812
115040
  });
114813
- import * as Chunk from "effect/Chunk";
114814
- import * as Effect from "effect/Effect";
114815
- import * as Exit from "effect/Exit";
114816
- import * as Option from "effect/Option";
114817
- import * as Schema9 from "effect/Schema";
114818
- import * as SqlClient from "effect/unstable/sql/SqlClient";
114819
- import * as Stream from "effect/Stream";
114820
115041
 
114821
- // src/internal/runtime/driver-value-mapping.ts
114822
- import * as Schema7 from "effect/Schema";
114823
- var runtimeTagOfDbType = (dbType) => {
114824
- if (dbType === undefined) {
114825
- return;
114826
- }
114827
- if ("base" in dbType) {
114828
- return runtimeTagOfDbType(dbType.base);
114829
- }
114830
- if ("element" in dbType) {
114831
- return "array";
114832
- }
114833
- if ("fields" in dbType) {
114834
- return "record";
114835
- }
114836
- if ("variant" in dbType && dbType.variant === "json") {
114837
- return "json";
114838
- }
114839
- if ("variant" in dbType && (dbType.variant === "enum" || dbType.variant === "set")) {
114840
- return "string";
114841
- }
114842
- return dbType.runtime;
115042
+ // src/internal/dialect-numeric.ts
115043
+ var literal2 = (value, dbType, dialect) => makeExpression2({
115044
+ runtime: value,
115045
+ dbType,
115046
+ driverValueMapping: dbType.driverValueMapping,
115047
+ nullability: "never",
115048
+ dialect,
115049
+ kind: "scalar",
115050
+ dependencies: {}
115051
+ }, {
115052
+ kind: "literal",
115053
+ value
115054
+ });
115055
+ var asExpression = (value, literalDb, dialect) => typeof value === "number" ? literal2(value, literalDb, dialect) : value;
115056
+ var modulo = (left, right, options2) => {
115057
+ const leftExpression = asExpression(left, options2.literalDb, options2.dialect);
115058
+ const rightExpression = asExpression(right, options2.literalDb, options2.dialect);
115059
+ const values2 = [leftExpression, rightExpression];
115060
+ return makeExpression2({
115061
+ runtime: undefined,
115062
+ dbType: options2.resultDb,
115063
+ driverValueMapping: options2.resultDb.driverValueMapping,
115064
+ nullability: options2.nullability,
115065
+ dialect: options2.dialect,
115066
+ kind: mergeAggregationManyRuntime(values2),
115067
+ dependencies: mergeManyDependencies(values2)
115068
+ }, {
115069
+ kind: "modulo",
115070
+ left: leftExpression,
115071
+ right: rightExpression
115072
+ });
114843
115073
  };
114844
- var familyOfDbType = (dbType) => {
114845
- if (dbType === undefined) {
114846
- return;
115074
+ var round = (value, scale, options2) => {
115075
+ const expression = asExpression(value, options2.literalDb, options2.dialect);
115076
+ if (scale === undefined) {
115077
+ return makeExpression2({
115078
+ runtime: undefined,
115079
+ dbType: options2.resultDb,
115080
+ driverValueMapping: options2.resultDb.driverValueMapping,
115081
+ nullability: options2.nullability,
115082
+ dialect: options2.dialect,
115083
+ kind: expression[TypeId].kind,
115084
+ dependencies: expression[TypeId].dependencies
115085
+ }, {
115086
+ kind: "round",
115087
+ value: expression
115088
+ });
114847
115089
  }
114848
- if ("base" in dbType) {
114849
- return familyOfDbType(dbType.base);
115090
+ if (!Number.isSafeInteger(scale)) {
115091
+ throw new Error("round scale must be a safe integer");
114850
115092
  }
114851
- return dbType.family;
115093
+ const scaleExpression = literal2(scale, options2.scaleDb, options2.dialect);
115094
+ return makeExpression2({
115095
+ runtime: undefined,
115096
+ dbType: options2.resultDb,
115097
+ driverValueMapping: options2.resultDb.driverValueMapping,
115098
+ nullability: options2.nullability,
115099
+ dialect: options2.dialect,
115100
+ kind: expression[TypeId].kind,
115101
+ dependencies: expression[TypeId].dependencies
115102
+ }, {
115103
+ kind: "function",
115104
+ name: "round",
115105
+ args: [expression, scaleExpression]
115106
+ });
114852
115107
  };
114853
- var mappingCandidates = (context) => {
114854
- const dbType = context.dbType;
114855
- const runtimeTag = runtimeTagOfDbType(dbType);
114856
- const family = familyOfDbType(dbType);
114857
- return [
114858
- context.driverValueMapping,
114859
- dbType?.driverValueMapping,
114860
- dbType === undefined ? undefined : context.valueMappings?.[dbType.kind],
114861
- family === undefined ? undefined : context.valueMappings?.[family],
114862
- runtimeTag === undefined ? undefined : context.valueMappings?.[runtimeTag]
114863
- ];
115108
+ var aggregate = (kind, value, options2) => {
115109
+ const expression = asExpression(value, options2.literalDb, options2.dialect);
115110
+ return makeExpression2({
115111
+ runtime: undefined,
115112
+ dbType: options2.resultDb,
115113
+ driverValueMapping: options2.resultDb.driverValueMapping,
115114
+ nullability: "maybe",
115115
+ dialect: options2.dialect,
115116
+ kind: "aggregate",
115117
+ dependencies: expression[TypeId].dependencies
115118
+ }, {
115119
+ kind,
115120
+ value: expression
115121
+ });
114864
115122
  };
114865
- var findMapping = (context, key2) => {
114866
- for (const candidate of mappingCandidates(context)) {
114867
- const value = candidate?.[key2];
114868
- if (value !== undefined) {
114869
- return value;
114870
- }
115123
+ var inputNullability = (value) => typeof value === "number" ? "never" : value[TypeId].nullability;
115124
+ var binaryInputNullability = (left, right) => {
115125
+ const leftNullability = inputNullability(left);
115126
+ const rightNullability = inputNullability(right);
115127
+ if (leftNullability === "always" || rightNullability === "always") {
115128
+ return "always";
114871
115129
  }
114872
- return;
115130
+ return leftNullability === "maybe" || rightNullability === "maybe" ? "maybe" : "never";
114873
115131
  };
114874
- var isJsonDbType = (dbType) => {
114875
- if (dbType === undefined) {
114876
- return false;
114877
- }
114878
- if ("base" in dbType) {
114879
- return isJsonDbType(dbType.base);
115132
+ var nullableForZeroDivisor = (left, right) => {
115133
+ const merged = binaryInputNullability(left, right);
115134
+ if (merged === "always") {
115135
+ return "always";
114880
115136
  }
114881
- if (!("variant" in dbType)) {
114882
- return false;
115137
+ if (typeof right === "number") {
115138
+ return right === 0 ? "always" : merged;
114883
115139
  }
114884
- const variant = dbType.variant;
114885
- return variant === "json" || variant === "jsonb";
115140
+ return "maybe";
114886
115141
  };
114887
- var schemaAccepts = (schema2, value) => schema2 !== undefined && Schema7.is(schema2)(value);
114888
- var encodeWithSchema = (schema2, value) => {
114889
- if (schema2 === undefined) {
114890
- return { value, encoded: false };
114891
- }
114892
- if (!Schema7.is(schema2)(value)) {
114893
- return { value, encoded: false };
114894
- }
114895
- return {
114896
- value: Schema7.encodeUnknownSync(schema2)(value),
114897
- encoded: true
114898
- };
115142
+
115143
+ // src/mysql/function/aggregate.ts
115144
+ var baseDb = (db) => ("base" in db) ? baseDb(db.base) : db;
115145
+ var resultDb = (value) => {
115146
+ if (typeof value === "number")
115147
+ return mysqlDatatypes.double();
115148
+ const db = baseDb(value[TypeId].dbType);
115149
+ const approximate = db.kind === "real" || db.kind === "float" || db.kind === "double";
115150
+ return approximate ? mysqlDatatypes.double() : mysqlDatatypes.decimal();
114899
115151
  };
114900
- var normalizeJsonDriverString = (value, context) => {
114901
- if (!isJsonDbType(context.dbType) || context.runtimeSchema === undefined) {
114902
- return;
115152
+ var sum = (value) => aggregate("sum", value, {
115153
+ dialect: "mysql",
115154
+ literalDb: mysqlDatatypes.double(),
115155
+ resultDb: resultDb(value)
115156
+ });
115157
+ var avg = (value) => aggregate("avg", value, {
115158
+ dialect: "mysql",
115159
+ literalDb: mysqlDatatypes.double(),
115160
+ resultDb: resultDb(value)
115161
+ });
115162
+ // src/mysql/function/numeric.ts
115163
+ var exports_numeric = {};
115164
+ __export(exports_numeric, {
115165
+ round: () => round2,
115166
+ modulo: () => modulo2
115167
+ });
115168
+ var baseDb2 = (db) => ("base" in db) ? baseDb2(db.base) : db;
115169
+ var category = (value) => {
115170
+ if (typeof value === "number")
115171
+ return "approximate";
115172
+ const db = baseDb2(value[TypeId].dbType);
115173
+ if (db.kind === "int" || db.kind === "integer" || db.kind === "bigint" || db.kind === "tinyint" || db.kind === "smallint" || db.kind === "mediumint") {
115174
+ return "integer";
114903
115175
  }
114904
- try {
114905
- const parsed = JSON.parse(value);
114906
- if (value.trimStart().startsWith('"') && schemaAccepts(context.runtimeSchema, parsed)) {
114907
- return parsed;
114908
- }
114909
- if (schemaAccepts(context.runtimeSchema, value) && !schemaAccepts(context.runtimeSchema, parsed)) {
114910
- return value;
114911
- }
114912
- } catch (error) {
114913
- if (error instanceof SyntaxError && schemaAccepts(context.runtimeSchema, value)) {
114914
- return value;
114915
- }
114916
- if (!(error instanceof SyntaxError)) {
114917
- throw error;
114918
- }
115176
+ if (db.kind === "numeric" || db.kind === "decimal" || db.kind === "dec" || db.kind === "fixed") {
115177
+ return "exact";
114919
115178
  }
114920
- return;
115179
+ return "approximate";
114921
115180
  };
114922
- var toDriverValue = (value, context) => {
114923
- if (value === null) {
114924
- return null;
114925
- }
114926
- if (value instanceof Date && Number.isNaN(value.getTime())) {
114927
- throw new Error("Expected a valid Date value");
114928
- }
114929
- const dbType = context.dbType;
114930
- const encoded = encodeWithSchema(context.runtimeSchema, value);
114931
- let current = encoded.value;
114932
- const custom3 = findMapping(context, "toDriver");
114933
- if (custom3 !== undefined && dbType !== undefined) {
114934
- return custom3(current, dbType);
114935
- }
114936
- if (encoded.encoded && typeof current === "string" && isJsonDbType(dbType)) {
114937
- return current;
114938
- }
114939
- return dbType === undefined || !encoded.encoded ? current : normalizeDbValue(dbType, current);
115181
+ var resultDb2 = (categoryValue) => {
115182
+ if (categoryValue === "integer")
115183
+ return mysqlDatatypes.bigint();
115184
+ if (categoryValue === "exact")
115185
+ return mysqlDatatypes.decimal();
115186
+ return mysqlDatatypes.double();
114940
115187
  };
114941
- var fromDriverValue = (value, context) => {
114942
- if (value === null) {
114943
- return null;
114944
- }
115188
+ var mergedCategory = (left, right) => {
115189
+ const categories = [category(left), category(right)];
115190
+ return categories.includes("approximate") ? "approximate" : categories.includes("exact") ? "exact" : "integer";
115191
+ };
115192
+ var modulo2 = (left, right) => modulo(left, right, {
115193
+ dialect: "mysql",
115194
+ literalDb: mysqlDatatypes.double(),
115195
+ resultDb: resultDb2(mergedCategory(left, right)),
115196
+ nullability: nullableForZeroDivisor(left, right)
115197
+ });
115198
+ var roundRuntime = (value, scale) => {
115199
+ return round(value, scale, {
115200
+ dialect: "mysql",
115201
+ literalDb: mysqlDatatypes.double(),
115202
+ scaleDb: mysqlDatatypes.bigint(),
115203
+ resultDb: resultDb2(category(value)),
115204
+ nullability: typeof value === "number" ? "never" : value[TypeId].nullability
115205
+ });
115206
+ };
115207
+ var round2 = roundRuntime;
115208
+ // src/mysql/function/window.ts
115209
+ var exports_window = {};
115210
+ __export(exports_window, {
115211
+ rowNumber: () => rowNumber,
115212
+ rank: () => rank,
115213
+ over: () => over,
115214
+ lastValue: () => lastValue2,
115215
+ firstValue: () => firstValue2,
115216
+ denseRank: () => denseRank
115217
+ });
115218
+
115219
+ // src/internal/standard-dsl.ts
115220
+ import { pipeArguments as pipeArguments8 } from "effect/Pipeable";
115221
+ import * as Schema7 from "effect/Schema";
115222
+
115223
+ // src/standard/datatypes/index.ts
115224
+ var exports_datatypes2 = {};
115225
+ __export(exports_datatypes2, {
115226
+ standardDatatypes: () => standardDatatypes
115227
+ });
115228
+
115229
+ // src/standard/datatypes/spec.ts
115230
+ var standardDatatypeFamilies = portableDatatypeFamilies;
115231
+ var standardDatatypeKinds = portableDatatypeKinds;
115232
+
115233
+ // src/standard/datatypes/index.ts
115234
+ var withMetadata2 = (kind) => {
115235
+ const kindSpec = standardDatatypeKinds[kind];
115236
+ const familySpec = standardDatatypeFamilies[kindSpec.family];
115237
+ return {
115238
+ dialect: "standard",
115239
+ kind,
115240
+ family: kindSpec.family,
115241
+ runtime: kindSpec.runtime,
115242
+ compareGroup: familySpec?.compareGroup,
115243
+ castTargets: familySpec?.castTargets,
115244
+ implicitTargets: familySpec.implicitTargets,
115245
+ traits: familySpec?.traits
115246
+ };
115247
+ };
115248
+ var standardDatatypeModule = {
115249
+ custom: (kind) => ({
115250
+ dialect: "standard",
115251
+ kind
115252
+ }),
115253
+ uuid: () => ({
115254
+ dialect: "standard",
115255
+ kind: "uuid",
115256
+ family: "uuid",
115257
+ runtime: "string",
115258
+ compareGroup: "uuid",
115259
+ castTargets: ["uuid", "char", "varchar", "text"],
115260
+ traits: {
115261
+ textual: true
115262
+ }
115263
+ })
115264
+ };
115265
+ for (const kind of Object.keys(standardDatatypeKinds)) {
115266
+ standardDatatypeModule[kind] = () => withMetadata2(kind);
115267
+ }
115268
+ standardDatatypeModule.json = () => ({
115269
+ ...withMetadata2("json"),
115270
+ driverValueMapping: {
115271
+ toDriver: (value) => JSON.stringify(value)
115272
+ }
115273
+ });
115274
+ var standardDatatypes = {
115275
+ ...standardDatatypeModule
115276
+ };
115277
+
115278
+ // src/internal/standard-dsl.ts
115279
+ var profile2 = {
115280
+ dialect: "standard",
115281
+ textDb: standardDatatypes.text(),
115282
+ numericDb: standardDatatypes.real(),
115283
+ boolDb: standardDatatypes.boolean(),
115284
+ timestampDb: standardDatatypes.timestamp(),
115285
+ nullDb: {
115286
+ dialect: "standard",
115287
+ kind: "null",
115288
+ family: "null",
115289
+ runtime: "unknown",
115290
+ compareGroup: "null",
115291
+ traits: {}
115292
+ },
115293
+ type: standardDatatypes
115294
+ };
115295
+ var ValuesInputProto2 = {
115296
+ pipe() {
115297
+ return pipeArguments8(this, arguments);
115298
+ }
115299
+ };
115300
+ var literalSchemaOf2 = (value) => {
115301
+ if (value === null || value instanceof Date) {
115302
+ return;
115303
+ }
115304
+ if (typeof value === "number" && !Number.isFinite(value)) {
115305
+ return;
115306
+ }
115307
+ return Schema7.Literal(value);
115308
+ };
115309
+ var literal3 = (value) => makeExpression2({
115310
+ runtime: undefined,
115311
+ dbType: value === null ? profile2.nullDb : value instanceof Date ? profile2.timestampDb : typeof value === "string" ? profile2.textDb : typeof value === "number" ? profile2.numericDb : profile2.boolDb,
115312
+ runtimeSchema: literalSchemaOf2(value),
115313
+ nullability: value === null ? "always" : "never",
115314
+ dialect: profile2.dialect,
115315
+ kind: "scalar",
115316
+ dependencies: {}
115317
+ }, {
115318
+ kind: "literal",
115319
+ value
115320
+ });
115321
+ var column = (name, dbType, nullable2 = false) => makeExpression2({
115322
+ runtime: undefined,
115323
+ dbType,
115324
+ nullability: nullable2 ? "maybe" : "never",
115325
+ dialect: profile2.dialect,
115326
+ kind: "scalar",
115327
+ dependencies: {}
115328
+ }, {
115329
+ kind: "column",
115330
+ tableName: "",
115331
+ columnName: name
115332
+ });
115333
+ var toDialectExpression2 = (value) => {
115334
+ if (value !== null && typeof value === "object" && TypeId in value) {
115335
+ return value;
115336
+ }
115337
+ return literal3(value);
115338
+ };
115339
+ var retargetLiteralExpression2 = (value, target) => {
115340
+ const ast = value[TypeId2];
115341
+ if (ast.kind !== "literal") {
115342
+ return value;
115343
+ }
115344
+ const targetState = target[TypeId];
115345
+ return makeExpression2({
115346
+ runtime: value[TypeId].runtime,
115347
+ dbType: targetState.dbType,
115348
+ runtimeSchema: targetState.runtimeSchema,
115349
+ driverValueMapping: targetState.driverValueMapping,
115350
+ nullability: value[TypeId].nullability,
115351
+ dialect: targetState.dialect,
115352
+ kind: "scalar",
115353
+ dependencies: {}
115354
+ }, ast);
115355
+ };
115356
+ var alignBinaryPredicateExpressions2 = (left, right) => {
115357
+ const leftAst = left[TypeId2];
115358
+ const rightAst = right[TypeId2];
115359
+ if (leftAst.kind === "literal" && rightAst.kind !== "literal") {
115360
+ return [retargetLiteralExpression2(left, right), right];
115361
+ }
115362
+ if (rightAst.kind === "literal" && leftAst.kind !== "literal") {
115363
+ return [left, retargetLiteralExpression2(right, left)];
115364
+ }
115365
+ return [left, right];
115366
+ };
115367
+ var toDialectStringExpression2 = (value) => typeof value === "string" ? literal3(value) : value;
115368
+ var toDialectNumericExpression2 = (value) => typeof value === "number" ? literal3(value) : value;
115369
+ var flattenVariadicBooleanExpressions = (kind, values2) => {
115370
+ const flattened = [];
115371
+ for (const value of values2) {
115372
+ const ast = value[TypeId2];
115373
+ if (ast.kind === kind) {
115374
+ flattened.push(...ast.values);
115375
+ } else {
115376
+ flattened.push(value);
115377
+ }
115378
+ }
115379
+ return flattened;
115380
+ };
115381
+ var makeVariadicBooleanExpression = (kind, values2) => {
115382
+ const expressions = flattenVariadicBooleanExpressions(kind, values2);
115383
+ const expression = makeExpression2({
115384
+ runtime: true,
115385
+ dbType: profile2.boolDb,
115386
+ nullability: mergeNullabilityManyRuntime(expressions),
115387
+ dialect: expressions.find((value) => value[TypeId].dialect !== undefined)?.[TypeId].dialect ?? profile2.dialect,
115388
+ kind: "scalar",
115389
+ dependencies: mergeManyDependencies(expressions)
115390
+ }, {
115391
+ kind,
115392
+ values: expressions
115393
+ });
115394
+ Object.defineProperty(expression, "pipe", {
115395
+ configurable: true,
115396
+ writable: true,
115397
+ value() {
115398
+ if (arguments.length === 0) {
115399
+ return this;
115400
+ }
115401
+ const operations = Array.from(arguments);
115402
+ if (operations.every((operation) => typeof operation !== "function")) {
115403
+ const appended = operations.map((operation) => toDialectExpression2(operation));
115404
+ return makeVariadicBooleanExpression(kind, [...expressions, ...appended]);
115405
+ }
115406
+ if (operations.every((operation) => typeof operation === "function")) {
115407
+ return pipeArguments8(this, arguments);
115408
+ }
115409
+ const valuesForMixedPipe = (value) => {
115410
+ if (typeof value !== "object" || value === null || !(TypeId in value)) {
115411
+ return [];
115412
+ }
115413
+ const expression2 = value;
115414
+ const ast = expression2[TypeId2];
115415
+ if (ast.kind === kind) {
115416
+ return ast.values;
115417
+ }
115418
+ return [expression2];
115419
+ };
115420
+ let current = this;
115421
+ for (const operation of operations) {
115422
+ if (typeof operation === "function") {
115423
+ current = operation(current);
115424
+ continue;
115425
+ }
115426
+ current = makeVariadicBooleanExpression(kind, [...valuesForMixedPipe(current), toDialectExpression2(operation)]);
115427
+ }
115428
+ return current;
115429
+ }
115430
+ });
115431
+ return expression;
115432
+ };
115433
+ var extractRequiredFromDialectInputRuntime2 = (value) => {
115434
+ const expression = toDialectExpression2(value);
115435
+ return Object.keys(expression[TypeId].dependencies);
115436
+ };
115437
+ var normalizeWindowSpec2 = (spec) => {
115438
+ if (spec?.frame !== undefined) {
115439
+ throw new Error("over does not accept an explicit frame on the portable Function API; use a dialect Function.over helper");
115440
+ }
115441
+ validateWindowFrame(spec?.frame);
115442
+ const partitionBy = [...spec?.partitionBy ?? []];
115443
+ const orderBy2 = (spec?.orderBy ?? []).map((term) => {
115444
+ const direction = term.direction ?? "asc";
115445
+ return {
115446
+ value: term.value,
115447
+ direction
115448
+ };
115449
+ });
115450
+ return {
115451
+ partitionBy,
115452
+ orderBy: orderBy2,
115453
+ frame: spec?.frame
115454
+ };
115455
+ };
115456
+ var mergeWindowExpressions2 = (value, partitionBy, orderBy2) => value === undefined ? [...partitionBy, ...orderBy2.map((term) => term.value)] : [value, ...partitionBy, ...orderBy2.map((term) => term.value)];
115457
+ var extractRequiredFromDialectNumericInputRuntime2 = (value) => {
115458
+ const expression = toDialectNumericExpression2(value);
115459
+ return Object.keys(expression[TypeId].dependencies);
115460
+ };
115461
+ var buildBinaryPredicate2 = (left, right, kind, nullability = "maybe") => {
115462
+ const [leftExpression, rightExpression] = alignBinaryPredicateExpressions2(toDialectExpression2(left), toDialectExpression2(right));
115463
+ return makeExpression2({
115464
+ runtime: true,
115465
+ dbType: profile2.boolDb,
115466
+ nullability,
115467
+ dialect: leftExpression[TypeId].dialect ?? rightExpression[TypeId].dialect,
115468
+ kind: "scalar",
115469
+ dependencies: mergeDependencies(leftExpression[TypeId].dependencies, rightExpression[TypeId].dependencies)
115470
+ }, {
115471
+ kind,
115472
+ left: leftExpression,
115473
+ right: rightExpression
115474
+ });
115475
+ };
115476
+ var buildVariadicPredicate = (values2, kind) => {
115477
+ const expressions = values2.map((value) => toDialectExpression2(value));
115478
+ const [head, ...tail] = expressions;
115479
+ const alignedExpressions = head !== undefined && (kind === "in" || kind === "notIn" || kind === "between") ? [head, ...tail.map((value) => retargetLiteralExpression2(value, head))] : expressions;
115480
+ return makeExpression2({
115481
+ runtime: true,
115482
+ dbType: profile2.boolDb,
115483
+ nullability: "maybe",
115484
+ dialect: alignedExpressions.find((value) => value[TypeId].dialect !== undefined)?.[TypeId].dialect ?? profile2.dialect,
115485
+ kind: "scalar",
115486
+ dependencies: mergeManyDependencies(alignedExpressions)
115487
+ }, {
115488
+ kind,
115489
+ values: alignedExpressions
115490
+ });
115491
+ };
115492
+ var eq = (...args) => {
115493
+ const left = args[0];
115494
+ const right = args[1];
115495
+ return buildBinaryPredicate2(left, right, "eq");
115496
+ };
115497
+ var neq = (...args) => {
115498
+ const left = args[0];
115499
+ const right = args[1];
115500
+ return buildBinaryPredicate2(left, right, "neq");
115501
+ };
115502
+ var lt = (...args) => {
115503
+ const left = args[0];
115504
+ const right = args[1];
115505
+ return buildBinaryPredicate2(left, right, "lt");
115506
+ };
115507
+ var lte = (...args) => {
115508
+ const left = args[0];
115509
+ const right = args[1];
115510
+ return buildBinaryPredicate2(left, right, "lte");
115511
+ };
115512
+ var gt = (...args) => {
115513
+ const left = args[0];
115514
+ const right = args[1];
115515
+ return buildBinaryPredicate2(left, right, "gt");
115516
+ };
115517
+ var gte = (...args) => {
115518
+ const left = args[0];
115519
+ const right = args[1];
115520
+ return buildBinaryPredicate2(left, right, "gte");
115521
+ };
115522
+ var like = (...args) => {
115523
+ const left = args[0];
115524
+ const right = args[1];
115525
+ return buildBinaryPredicate2(left, right, "like");
115526
+ };
115527
+ var ilike = (...args) => {
115528
+ const left = args[0];
115529
+ const right = args[1];
115530
+ return buildBinaryPredicate2(left, right, "ilike");
115531
+ };
115532
+ var regexMatch = (...args) => {
115533
+ const left = args[0];
115534
+ const right = args[1];
115535
+ return buildBinaryPredicate2(left, right, "regexMatch");
115536
+ };
115537
+ var regexIMatch = (...args) => {
115538
+ const left = args[0];
115539
+ const right = args[1];
115540
+ return buildBinaryPredicate2(left, right, "regexIMatch");
115541
+ };
115542
+ var regexNotMatch = (...args) => {
115543
+ const left = args[0];
115544
+ const right = args[1];
115545
+ return buildBinaryPredicate2(left, right, "regexNotMatch");
115546
+ };
115547
+ var regexNotIMatch = (...args) => {
115548
+ const left = args[0];
115549
+ const right = args[1];
115550
+ return buildBinaryPredicate2(left, right, "regexNotIMatch");
115551
+ };
115552
+ var isDistinctFrom = (...args) => {
115553
+ const left = args[0];
115554
+ const right = args[1];
115555
+ return buildBinaryPredicate2(left, right, "isDistinctFrom", "never");
115556
+ };
115557
+ var isNotDistinctFrom = (...args) => {
115558
+ const left = args[0];
115559
+ const right = args[1];
115560
+ return buildBinaryPredicate2(left, right, "isNotDistinctFrom", "never");
115561
+ };
115562
+ var isNull = (value) => {
115563
+ const expression = toDialectExpression2(value);
115564
+ return makeExpression2({
115565
+ runtime: true,
115566
+ dbType: profile2.boolDb,
115567
+ nullability: "never",
115568
+ dialect: expression[TypeId].dialect,
115569
+ kind: "scalar",
115570
+ dependencies: expression[TypeId].dependencies
115571
+ }, {
115572
+ kind: "isNull",
115573
+ value: expression
115574
+ });
115575
+ };
115576
+ var isNotNull = (value) => {
115577
+ const expression = toDialectExpression2(value);
115578
+ return makeExpression2({
115579
+ runtime: true,
115580
+ dbType: profile2.boolDb,
115581
+ nullability: "never",
115582
+ dialect: expression[TypeId].dialect,
115583
+ kind: "scalar",
115584
+ dependencies: expression[TypeId].dependencies
115585
+ }, {
115586
+ kind: "isNotNull",
115587
+ value: expression
115588
+ });
115589
+ };
115590
+ var collate = (value, collation) => {
115591
+ const expression = toDialectStringExpression2(value);
115592
+ const normalizedCollation = typeof collation === "string" ? [collation] : collation;
115593
+ return makeExpression2({
115594
+ runtime: expression[TypeId].runtime,
115595
+ dbType: expression[TypeId].dbType,
115596
+ nullability: expression[TypeId].nullability,
115597
+ dialect: expression[TypeId].dialect,
115598
+ kind: expression[TypeId].kind,
115599
+ dependencies: expression[TypeId].dependencies
115600
+ }, {
115601
+ kind: "collate",
115602
+ value: expression,
115603
+ collation: normalizedCollation
115604
+ });
115605
+ };
115606
+ var cast = (value, target) => {
115607
+ const expression = toDialectExpression2(value);
115608
+ return makeExpression2({
115609
+ runtime: undefined,
115610
+ dbType: target,
115611
+ runtimeSchema: undefined,
115612
+ driverValueMapping: target.driverValueMapping,
115613
+ nullability: expression[TypeId].nullability,
115614
+ dialect: expression[TypeId].dialect,
115615
+ kind: expression[TypeId].kind,
115616
+ dependencies: expression[TypeId].dependencies
115617
+ }, {
115618
+ kind: "cast",
115619
+ value: expression,
115620
+ target
115621
+ });
115622
+ };
115623
+ var custom3 = (kind) => ({
115624
+ dialect: profile2.dialect,
115625
+ kind
115626
+ });
115627
+ var driverValueMapping3 = (dbType, mapping) => ({
115628
+ ...dbType,
115629
+ driverValueMapping: mapping
115630
+ });
115631
+ var type2 = {
115632
+ ...profile2.type,
115633
+ custom: custom3,
115634
+ driverValueMapping: driverValueMapping3
115635
+ };
115636
+ var makeJsonDb2 = (kind) => ({
115637
+ dialect: profile2.dialect,
115638
+ kind,
115639
+ variant: kind === "jsonb" ? "jsonb" : "json"
115640
+ });
115641
+ var jsonDb2 = makeJsonDb2("json");
115642
+ var jsonbDb2 = makeJsonDb2("jsonb");
115643
+ var isExpressionValue2 = (value) => value !== null && typeof value === "object" && (TypeId in value);
115644
+ var isJsonExpressionValue2 = (value) => isExpressionValue2(value) && (() => {
115645
+ const dbType = value[TypeId].dbType;
115646
+ return dbType.variant === "json" || dbType.kind === "json" || dbType.kind === "jsonb";
115647
+ })();
115648
+ var isJsonPathValue2 = (value) => value !== null && typeof value === "object" && (TypeId3 in value);
115649
+ var normalizeJsonPathInput2 = (value) => isJsonPathValue2(value) ? value.segments : [value];
115650
+ var isExactJsonSegmentValue2 = (segment) => segment.kind === "key" || segment.kind === "index";
115651
+ var isExactJsonPathValue2 = (segments) => segments.every(isExactJsonSegmentValue2);
115652
+ var buildJsonNodeExpression2 = (expressions, state, ast) => withJsonPathAccess(makeExpression2({
115653
+ runtime: state.runtime,
115654
+ dbType: state.dbType,
115655
+ nullability: state.nullability,
115656
+ dialect: expressions.find((expression) => expression[TypeId].dialect !== undefined)?.[TypeId].dialect ?? profile2.dialect,
115657
+ kind: mergeAggregationManyRuntime(expressions),
115658
+ dependencies: mergeManyDependencies(expressions)
115659
+ }, ast));
115660
+ var jsonDbTypeOf2 = (base) => base[TypeId].dbType;
115661
+ var resolveJsonMergeDbType2 = (..._values) => jsonbDb2;
115662
+ var makeJsonLiteralExpression2 = (value, dbType = jsonDb2) => withJsonPathAccess(makeExpression2({
115663
+ runtime: value,
115664
+ dbType,
115665
+ nullability: value === null ? "always" : "never",
115666
+ dialect: profile2.dialect,
115667
+ kind: "scalar",
115668
+ dependencies: {}
115669
+ }, {
115670
+ kind: "literal",
115671
+ value
115672
+ }));
115673
+ var wrapJsonExpression2 = (value, kind, dbType) => buildJsonNodeExpression2([value], {
115674
+ runtime: undefined,
115675
+ dbType,
115676
+ nullability: value[TypeId].nullability
115677
+ }, {
115678
+ kind,
115679
+ value
115680
+ });
115681
+ var toJsonValueExpression2 = (value, kind = "jsonToJson", dbType = jsonDb2) => {
115682
+ if (isJsonExpressionValue2(value)) {
115683
+ return value;
115684
+ }
115685
+ if (isExpressionValue2(value)) {
115686
+ return wrapJsonExpression2(value, kind, dbType);
115687
+ }
115688
+ return makeJsonLiteralExpression2(value, dbType);
115689
+ };
115690
+ var jsonQueryExpression2 = (query) => toDialectStringExpression2(query);
115691
+ var jsonGet2 = (base, target) => {
115692
+ const segments = normalizeJsonPathInput2(target);
115693
+ const kind = isJsonPathValue2(target) ? isExactJsonPathValue2(segments) ? "jsonPath" : "jsonTraverse" : isExactJsonSegmentValue2(target) ? "jsonGet" : "jsonAccess";
115694
+ return buildJsonNodeExpression2([base], {
115695
+ runtime: undefined,
115696
+ dbType: jsonDbTypeOf2(base),
115697
+ nullability: undefined
115698
+ }, {
115699
+ kind,
115700
+ base,
115701
+ segments
115702
+ });
115703
+ };
115704
+ var jsonText2 = (base, target) => {
115705
+ const segments = normalizeJsonPathInput2(target);
115706
+ const kind = isJsonPathValue2(target) ? isExactJsonPathValue2(segments) ? "jsonPathText" : "jsonTraverseText" : isExactJsonSegmentValue2(target) ? "jsonGetText" : "jsonAccessText";
115707
+ return buildJsonNodeExpression2([base], {
115708
+ runtime: undefined,
115709
+ dbType: profile2.textDb,
115710
+ nullability: undefined
115711
+ }, {
115712
+ kind,
115713
+ base,
115714
+ segments
115715
+ });
115716
+ };
115717
+ var jsonAccess2 = (base, target) => {
115718
+ const segments = normalizeJsonPathInput2(target);
115719
+ return buildJsonNodeExpression2([base], {
115720
+ runtime: undefined,
115721
+ dbType: jsonDbTypeOf2(base),
115722
+ nullability: undefined
115723
+ }, {
115724
+ kind: isJsonPathValue2(target) || segments.length > 1 ? "jsonTraverse" : "jsonAccess",
115725
+ base,
115726
+ segments
115727
+ });
115728
+ };
115729
+ var jsonTraverse2 = (base, target) => {
115730
+ const segments = normalizeJsonPathInput2(target);
115731
+ return buildJsonNodeExpression2([base], {
115732
+ runtime: undefined,
115733
+ dbType: jsonDbTypeOf2(base),
115734
+ nullability: undefined
115735
+ }, {
115736
+ kind: "jsonTraverse",
115737
+ base,
115738
+ segments
115739
+ });
115740
+ };
115741
+ var jsonAccessText2 = (base, target) => {
115742
+ const segments = normalizeJsonPathInput2(target);
115743
+ return buildJsonNodeExpression2([base], {
115744
+ runtime: undefined,
115745
+ dbType: profile2.textDb,
115746
+ nullability: undefined
115747
+ }, {
115748
+ kind: isJsonPathValue2(target) || segments.length > 1 ? "jsonTraverseText" : "jsonAccessText",
115749
+ base,
115750
+ segments
115751
+ });
115752
+ };
115753
+ var jsonTraverseText2 = (base, target) => {
115754
+ const segments = normalizeJsonPathInput2(target);
115755
+ return buildJsonNodeExpression2([base], {
115756
+ runtime: undefined,
115757
+ dbType: profile2.textDb,
115758
+ nullability: undefined
115759
+ }, {
115760
+ kind: "jsonTraverseText",
115761
+ base,
115762
+ segments
115763
+ });
115764
+ };
115765
+ var jsonContains2 = (left, right) => buildBinaryPredicate2(left, toJsonValueExpression2(right), "contains");
115766
+ var jsonContainedBy2 = (left, right) => buildBinaryPredicate2(left, toJsonValueExpression2(right), "containedBy");
115767
+ var jsonHasKey2 = (base, key2) => buildJsonNodeExpression2([base], {
115768
+ runtime: true,
115769
+ dbType: profile2.boolDb,
115770
+ nullability: "never"
115771
+ }, {
115772
+ kind: "jsonHasKey",
115773
+ base,
115774
+ keys: [key2]
115775
+ });
115776
+ var jsonHasAnyKeys2 = (base, ...keys) => buildJsonNodeExpression2([base], {
115777
+ runtime: true,
115778
+ dbType: profile2.boolDb,
115779
+ nullability: "never"
115780
+ }, {
115781
+ kind: "jsonHasAnyKeys",
115782
+ base,
115783
+ keys
115784
+ });
115785
+ var jsonHasAllKeys2 = (base, ...keys) => buildJsonNodeExpression2([base], {
115786
+ runtime: true,
115787
+ dbType: profile2.boolDb,
115788
+ nullability: "never"
115789
+ }, {
115790
+ kind: "jsonHasAllKeys",
115791
+ base,
115792
+ keys
115793
+ });
115794
+ var jsonDelete2 = (base, target) => {
115795
+ const segments = normalizeJsonPathInput2(target);
115796
+ return buildJsonNodeExpression2([base], {
115797
+ runtime: undefined,
115798
+ dbType: jsonDbTypeOf2(base),
115799
+ nullability: undefined
115800
+ }, {
115801
+ kind: isJsonPathValue2(target) ? "jsonDeletePath" : "jsonDelete",
115802
+ base,
115803
+ segments
115804
+ });
115805
+ };
115806
+ var jsonRemove2 = (base, target) => {
115807
+ const segments = normalizeJsonPathInput2(target);
115808
+ return buildJsonNodeExpression2([base], {
115809
+ runtime: undefined,
115810
+ dbType: jsonDbTypeOf2(base),
115811
+ nullability: undefined
115812
+ }, {
115813
+ kind: "jsonRemove",
115814
+ base,
115815
+ segments
115816
+ });
115817
+ };
115818
+ var jsonSet2 = (base, target, next, options2 = {}) => {
115819
+ const segments = normalizeJsonPathInput2(target);
115820
+ const newValue = toJsonValueExpression2(next);
115821
+ return buildJsonNodeExpression2([base, newValue], {
115822
+ runtime: undefined,
115823
+ dbType: jsonDbTypeOf2(base),
115824
+ nullability: undefined
115825
+ }, {
115826
+ kind: "jsonSet",
115827
+ base,
115828
+ segments,
115829
+ newValue,
115830
+ createMissing: options2.createMissing ?? true
115831
+ });
115832
+ };
115833
+ var jsonInsert2 = (base, target, next, options2 = {}) => {
115834
+ const segments = normalizeJsonPathInput2(target);
115835
+ const insert = toJsonValueExpression2(next);
115836
+ const insertAfter = options2.insertAfter ?? false;
115837
+ return buildJsonNodeExpression2([base, insert], {
115838
+ runtime: undefined,
115839
+ dbType: jsonDbTypeOf2(base),
115840
+ nullability: undefined
115841
+ }, {
115842
+ kind: "jsonInsert",
115843
+ base,
115844
+ segments,
115845
+ insert,
115846
+ insertAfter
115847
+ });
115848
+ };
115849
+ var jsonConcatAs2 = (dbType) => (left, right) => {
115850
+ const leftExpression = toJsonValueExpression2(left);
115851
+ const rightExpression = toJsonValueExpression2(right);
115852
+ return buildJsonNodeExpression2([leftExpression, rightExpression], {
115853
+ runtime: undefined,
115854
+ dbType,
115855
+ nullability: "maybe"
115856
+ }, {
115857
+ kind: "jsonConcat",
115858
+ left: leftExpression,
115859
+ right: rightExpression
115860
+ });
115861
+ };
115862
+ var jsonMergeAs2 = (dbType) => (left, right) => {
115863
+ const leftExpression = toJsonValueExpression2(left);
115864
+ const rightExpression = toJsonValueExpression2(right);
115865
+ return buildJsonNodeExpression2([leftExpression, rightExpression], {
115866
+ runtime: undefined,
115867
+ dbType,
115868
+ nullability: "maybe"
115869
+ }, {
115870
+ kind: "jsonMerge",
115871
+ left: leftExpression,
115872
+ right: rightExpression
115873
+ });
115874
+ };
115875
+ var jsonConcat2 = jsonConcatAs2(resolveJsonMergeDbType2());
115876
+ var jsonMerge2 = jsonMergeAs2(resolveJsonMergeDbType2());
115877
+ var jsonKeyExists2 = (base, key2) => buildJsonNodeExpression2([base], {
115878
+ runtime: true,
115879
+ dbType: profile2.boolDb,
115880
+ nullability: "never"
115881
+ }, {
115882
+ kind: "jsonKeyExists",
115883
+ base,
115884
+ keys: [key2]
115885
+ });
115886
+ var jsonBuildObjectAs2 = (dbType) => (shape) => {
115887
+ const entries = Object.entries(shape).map(([key2, value]) => ({
115888
+ key: key2,
115889
+ value: toJsonValueExpression2(value)
115890
+ }));
115891
+ return buildJsonNodeExpression2(entries.map((entry) => entry.value), {
115892
+ runtime: {},
115893
+ dbType,
115894
+ nullability: "never"
115895
+ }, {
115896
+ kind: "jsonBuildObject",
115897
+ entries
115898
+ });
115899
+ };
115900
+ var jsonBuildArrayAs2 = (dbType) => (...values2) => {
115901
+ const expressions = values2.map((value) => toJsonValueExpression2(value));
115902
+ return buildJsonNodeExpression2(expressions, {
115903
+ runtime: [],
115904
+ dbType,
115905
+ nullability: "never"
115906
+ }, {
115907
+ kind: "jsonBuildArray",
115908
+ values: expressions
115909
+ });
115910
+ };
115911
+ var jsonBuildObject2 = jsonBuildObjectAs2(jsonDb2);
115912
+ var jsonBuildArray2 = jsonBuildArrayAs2(jsonDb2);
115913
+ var jsonbBuildObject2 = jsonBuildObjectAs2(jsonbDb2);
115914
+ var jsonbBuildArray2 = jsonBuildArrayAs2(jsonbDb2);
115915
+ var jsonToJson2 = (value) => toJsonValueExpression2(value, "jsonToJson", jsonDb2);
115916
+ var jsonToJsonb2 = (value) => toJsonValueExpression2(value, "jsonToJsonb", jsonbDb2);
115917
+ var jsonTypeOf2 = (base) => buildJsonNodeExpression2([base], {
115918
+ runtime: undefined,
115919
+ dbType: profile2.textDb,
115920
+ nullability: base[TypeId].nullability
115921
+ }, {
115922
+ kind: "jsonTypeOf",
115923
+ value: base
115924
+ });
115925
+ var jsonLength2 = (base) => buildJsonNodeExpression2([base], {
115926
+ runtime: undefined,
115927
+ dbType: profile2.numericDb,
115928
+ nullability: undefined
115929
+ }, {
115930
+ kind: "jsonLength",
115931
+ value: base
115932
+ });
115933
+ var jsonKeys2 = (base) => buildJsonNodeExpression2([base], {
115934
+ runtime: undefined,
115935
+ dbType: jsonDb2,
115936
+ nullability: undefined
115937
+ }, {
115938
+ kind: "jsonKeys",
115939
+ value: base
115940
+ });
115941
+ var jsonPathExists2 = (base, query) => {
115942
+ if (isJsonPathValue2(query)) {
115943
+ return buildJsonNodeExpression2([base], {
115944
+ runtime: true,
115945
+ dbType: profile2.boolDb,
115946
+ nullability: "never"
115947
+ }, {
115948
+ kind: "jsonPathExists",
115949
+ base,
115950
+ query
115951
+ });
115952
+ }
115953
+ const queryExpression = jsonQueryExpression2(query);
115954
+ return buildJsonNodeExpression2([base, queryExpression], {
115955
+ runtime: true,
115956
+ dbType: profile2.boolDb,
115957
+ nullability: "never"
115958
+ }, {
115959
+ kind: "jsonPathExists",
115960
+ base,
115961
+ query: queryExpression
115962
+ });
115963
+ };
115964
+ var jsonStripNulls2 = (base) => buildJsonNodeExpression2([base], {
115965
+ runtime: undefined,
115966
+ dbType: jsonDbTypeOf2(base),
115967
+ nullability: undefined
115968
+ }, {
115969
+ kind: "jsonStripNulls",
115970
+ value: base
115971
+ });
115972
+ var jsonPathMatch2 = (base, query) => {
115973
+ if (isJsonPathValue2(query)) {
115974
+ return buildJsonNodeExpression2([base], {
115975
+ runtime: true,
115976
+ dbType: profile2.boolDb,
115977
+ nullability: "never"
115978
+ }, {
115979
+ kind: "jsonPathMatch",
115980
+ base,
115981
+ query
115982
+ });
115983
+ }
115984
+ const queryExpression = jsonQueryExpression2(query);
115985
+ return buildJsonNodeExpression2([base, queryExpression], {
115986
+ runtime: true,
115987
+ dbType: profile2.boolDb,
115988
+ nullability: "never"
115989
+ }, {
115990
+ kind: "jsonPathMatch",
115991
+ base,
115992
+ query: queryExpression
115993
+ });
115994
+ };
115995
+ var json2 = {
115996
+ key,
115997
+ index,
115998
+ wildcard,
115999
+ slice,
116000
+ descend,
116001
+ path,
116002
+ get: jsonGet2,
116003
+ access: jsonAccess2,
116004
+ traverse: jsonTraverse2,
116005
+ text: jsonText2,
116006
+ accessText: jsonAccessText2,
116007
+ traverseText: jsonTraverseText2,
116008
+ contains: jsonContains2,
116009
+ containedBy: jsonContainedBy2,
116010
+ hasKey: jsonHasKey2,
116011
+ keyExists: jsonKeyExists2,
116012
+ hasAnyKeys: jsonHasAnyKeys2,
116013
+ hasAllKeys: jsonHasAllKeys2,
116014
+ delete: jsonDelete2,
116015
+ remove: jsonRemove2,
116016
+ set: jsonSet2,
116017
+ insert: jsonInsert2,
116018
+ concat: jsonConcat2,
116019
+ merge: jsonMerge2,
116020
+ buildObject: jsonBuildObject2,
116021
+ buildArray: jsonBuildArray2,
116022
+ toJson: jsonToJson2,
116023
+ toJsonb: jsonToJsonb2,
116024
+ typeOf: jsonTypeOf2,
116025
+ length: jsonLength2,
116026
+ keys: jsonKeys2,
116027
+ stripNulls: jsonStripNulls2,
116028
+ pathExists: jsonPathExists2,
116029
+ pathMatch: jsonPathMatch2
116030
+ };
116031
+ var jsonb2 = {
116032
+ key,
116033
+ index,
116034
+ wildcard,
116035
+ slice,
116036
+ descend,
116037
+ path,
116038
+ get: jsonGet2,
116039
+ access: jsonAccess2,
116040
+ traverse: jsonTraverse2,
116041
+ text: jsonText2,
116042
+ accessText: jsonAccessText2,
116043
+ traverseText: jsonTraverseText2,
116044
+ contains: jsonContains2,
116045
+ containedBy: jsonContainedBy2,
116046
+ hasKey: jsonHasKey2,
116047
+ keyExists: jsonKeyExists2,
116048
+ hasAnyKeys: jsonHasAnyKeys2,
116049
+ hasAllKeys: jsonHasAllKeys2,
116050
+ delete: jsonDelete2,
116051
+ remove: jsonRemove2,
116052
+ set: jsonSet2,
116053
+ insert: jsonInsert2,
116054
+ concat: jsonConcatAs2(jsonbDb2),
116055
+ merge: jsonMergeAs2(jsonbDb2),
116056
+ buildObject: jsonbBuildObject2,
116057
+ buildArray: jsonbBuildArray2,
116058
+ toJsonb: jsonToJsonb2,
116059
+ typeOf: jsonTypeOf2,
116060
+ length: jsonLength2,
116061
+ keys: jsonKeys2,
116062
+ stripNulls: jsonStripNulls2,
116063
+ pathExists: jsonPathExists2,
116064
+ pathMatch: jsonPathMatch2
116065
+ };
116066
+ var and = (...values2) => makeVariadicBooleanExpression("and", values2.map((value) => toDialectExpression2(value)));
116067
+ var or = (...values2) => makeVariadicBooleanExpression("or", values2.map((value) => toDialectExpression2(value)));
116068
+ var not = (value) => {
116069
+ const expression = toDialectExpression2(value);
116070
+ return makeExpression2({
116071
+ runtime: true,
116072
+ dbType: profile2.boolDb,
116073
+ nullability: expression[TypeId].nullability,
116074
+ dialect: expression[TypeId].dialect,
116075
+ kind: expression[TypeId].kind,
116076
+ dependencies: expression[TypeId].dependencies
116077
+ }, {
116078
+ kind: "not",
116079
+ value: expression
116080
+ });
116081
+ };
116082
+ var in_ = (head, ...tail) => buildVariadicPredicate([head, ...tail], "in");
116083
+ var notIn = (head, ...tail) => buildVariadicPredicate([head, ...tail], "notIn");
116084
+ var between = (...values2) => buildVariadicPredicate(values2, "between");
116085
+ var contains = (...args) => {
116086
+ const left = args[0];
116087
+ const right = args[1];
116088
+ return buildBinaryPredicate2(left, right, "contains");
116089
+ };
116090
+ var containedBy = (...args) => {
116091
+ const left = args[0];
116092
+ const right = args[1];
116093
+ return buildBinaryPredicate2(left, right, "containedBy");
116094
+ };
116095
+ var overlaps = (...args) => {
116096
+ const left = args[0];
116097
+ const right = args[1];
116098
+ return buildBinaryPredicate2(left, right, "overlaps");
116099
+ };
116100
+ var concat2 = (...values2) => {
116101
+ const expressions = values2.map((value) => toDialectStringExpression2(value));
116102
+ return makeExpression2({
116103
+ runtime: "",
116104
+ dbType: profile2.textDb,
116105
+ nullability: mergeNullabilityManyRuntime(expressions),
116106
+ dialect: expressions.find((value) => value[TypeId].dialect !== undefined)?.[TypeId].dialect ?? profile2.dialect,
116107
+ kind: mergeAggregationManyRuntime(expressions),
116108
+ dependencies: mergeManyDependencies(expressions)
116109
+ }, {
116110
+ kind: "concat",
116111
+ values: expressions
116112
+ });
116113
+ };
116114
+ var all_ = (...values2) => and(...values2);
116115
+ var any_ = (...values2) => or(...values2);
116116
+ var count2 = (value) => {
116117
+ const expression = toDialectExpression2(value);
116118
+ return makeExpression2({
116119
+ runtime: undefined,
116120
+ dbType: standardDatatypes.bigint(),
116121
+ nullability: "never",
116122
+ dialect: expression[TypeId].dialect,
116123
+ kind: "aggregate",
116124
+ dependencies: expression[TypeId].dependencies
116125
+ }, {
116126
+ kind: "count",
116127
+ value: expression
116128
+ });
116129
+ };
116130
+ var exists = (plan) => {
116131
+ const dependencies = Object.fromEntries(currentRequiredList(plan[TypeId4].required).map((name) => [name, true]));
116132
+ return makeExpression2({
116133
+ runtime: true,
116134
+ dbType: profile2.boolDb,
116135
+ nullability: "never",
116136
+ dialect: profile2.dialect,
116137
+ kind: "scalar",
116138
+ dependencies
116139
+ }, {
116140
+ kind: "exists",
116141
+ plan
116142
+ });
116143
+ };
116144
+ var scalar = (plan) => {
116145
+ const dependencies = Object.fromEntries(currentRequiredList(plan[TypeId4].required).map((name) => [name, true]));
116146
+ const expression = extractSingleSelectedExpressionRuntime(plan[TypeId4].selection);
116147
+ return makeExpression2({
116148
+ runtime: undefined,
116149
+ dbType: expression[TypeId].dbType,
116150
+ runtimeSchema: expression[TypeId].runtimeSchema,
116151
+ driverValueMapping: expression[TypeId].driverValueMapping,
116152
+ nullability: "maybe",
116153
+ dialect: profile2.dialect,
116154
+ kind: "scalar",
116155
+ dependencies
116156
+ }, {
116157
+ kind: "scalarSubquery",
116158
+ plan
116159
+ });
116160
+ };
116161
+ var inSubquery = (left, plan) => {
116162
+ const leftExpression = toDialectExpression2(left);
116163
+ const dependencies = Object.fromEntries(currentRequiredList(plan[TypeId4].required).map((name) => [name, true]));
116164
+ return makeExpression2({
116165
+ runtime: true,
116166
+ dbType: profile2.boolDb,
116167
+ nullability: "maybe",
116168
+ dialect: leftExpression[TypeId].dialect ?? profile2.dialect,
116169
+ kind: leftExpression[TypeId].kind,
116170
+ dependencies: mergeDependencies(leftExpression[TypeId].dependencies, dependencies)
116171
+ }, {
116172
+ kind: "inSubquery",
116173
+ left: leftExpression,
116174
+ plan
116175
+ });
116176
+ };
116177
+ var quantifiedComparison = (left, plan, operator, quantifier) => {
116178
+ const leftExpression = toDialectExpression2(left);
116179
+ const dependencies = Object.fromEntries(currentRequiredList(plan[TypeId4].required).map((name) => [name, true]));
116180
+ return makeExpression2({
116181
+ runtime: true,
116182
+ dbType: profile2.boolDb,
116183
+ nullability: "maybe",
116184
+ dialect: leftExpression[TypeId].dialect ?? profile2.dialect,
116185
+ kind: leftExpression[TypeId].kind,
116186
+ dependencies: mergeDependencies(leftExpression[TypeId].dependencies, dependencies)
116187
+ }, renderQuantifiedComparisonAst(leftExpression, plan, operator, quantifier));
116188
+ };
116189
+ var compareAny = (left, plan, operator) => quantifiedComparison(left, plan, operator, "any");
116190
+ var compareAll = (left, plan, operator) => quantifiedComparison(left, plan, operator, "all");
116191
+ var over2 = (value, spec = {}) => {
116192
+ const normalized = normalizeWindowSpec2(spec);
116193
+ const expressions = mergeWindowExpressions2(value, normalized.partitionBy, normalized.orderBy);
116194
+ return makeExpression2({
116195
+ runtime: undefined,
116196
+ dbType: value[TypeId].dbType,
116197
+ nullability: value[TypeId].nullability,
116198
+ dialect: expressions.find((expression) => expression[TypeId].dialect !== undefined)?.[TypeId].dialect ?? profile2.dialect,
116199
+ kind: "window",
116200
+ dependencies: mergeManyDependencies(expressions)
116201
+ }, {
116202
+ kind: "window",
116203
+ function: "over",
116204
+ value,
116205
+ partitionBy: normalized.partitionBy,
116206
+ orderBy: normalized.orderBy,
116207
+ frame: normalized.frame
116208
+ });
116209
+ };
116210
+ var buildNumberWindow2 = (kind, spec) => {
116211
+ const normalized = normalizeWindowSpec2(spec);
116212
+ const expressions = mergeWindowExpressions2(undefined, normalized.partitionBy, normalized.orderBy);
116213
+ return makeExpression2({
116214
+ runtime: undefined,
116215
+ dbType: standardDatatypes.bigint(),
116216
+ nullability: "never",
116217
+ dialect: expressions.find((expression) => expression[TypeId].dialect !== undefined)?.[TypeId].dialect ?? profile2.dialect,
116218
+ kind: "window",
116219
+ dependencies: mergeManyDependencies(expressions)
116220
+ }, {
116221
+ kind: "window",
116222
+ function: kind,
116223
+ partitionBy: normalized.partitionBy,
116224
+ orderBy: normalized.orderBy,
116225
+ frame: normalized.frame
116226
+ });
116227
+ };
116228
+ var rowNumber2 = (spec) => buildNumberWindow2("rowNumber", spec);
116229
+ var rank2 = (spec) => buildNumberWindow2("rank", spec);
116230
+ var denseRank2 = (spec) => buildNumberWindow2("denseRank", spec);
116231
+ var max2 = (value) => makeExpression2({
116232
+ runtime: undefined,
116233
+ dbType: value[TypeId].dbType,
116234
+ nullability: "maybe",
116235
+ dialect: value[TypeId].dialect,
116236
+ kind: "aggregate",
116237
+ dependencies: value[TypeId].dependencies
116238
+ }, {
116239
+ kind: "max",
116240
+ value
116241
+ });
116242
+ var min2 = (value) => makeExpression2({
116243
+ runtime: undefined,
116244
+ dbType: value[TypeId].dbType,
116245
+ nullability: "maybe",
116246
+ dialect: value[TypeId].dialect,
116247
+ kind: "aggregate",
116248
+ dependencies: value[TypeId].dependencies
116249
+ }, {
116250
+ kind: "min",
116251
+ value
116252
+ });
116253
+ var resolveCoalesceNullabilityRuntime2 = (values2) => values2.some((value) => value[TypeId].nullability === "never") ? "never" : values2.some((value) => value[TypeId].nullability === "maybe") ? "maybe" : "always";
116254
+ var coalesce2 = (...values2) => {
116255
+ const expressions = values2.map((value) => toDialectExpression2(value));
116256
+ const representative = expressions.find((value) => value[TypeId].nullability !== "always") ?? expressions[0];
116257
+ return makeExpression2({
116258
+ runtime: undefined,
116259
+ dbType: representative[TypeId].dbType,
116260
+ nullability: resolveCoalesceNullabilityRuntime2(expressions),
116261
+ dialect: expressions.find((value) => value[TypeId].dialect !== undefined)?.[TypeId].dialect ?? profile2.dialect,
116262
+ kind: mergeAggregationManyRuntime(expressions),
116263
+ dependencies: mergeManyDependencies(expressions)
116264
+ }, {
116265
+ kind: "coalesce",
116266
+ values: expressions
116267
+ });
116268
+ };
116269
+ var resolveCaseNullabilityRuntime = (values2) => {
116270
+ let sawNever = false;
116271
+ let sawMaybe = false;
116272
+ let sawAlways = false;
116273
+ for (const value of values2) {
116274
+ switch (value[TypeId].nullability) {
116275
+ case "never":
116276
+ sawNever = true;
116277
+ break;
116278
+ case "maybe":
116279
+ sawMaybe = true;
116280
+ break;
116281
+ case "always":
116282
+ sawAlways = true;
116283
+ break;
116284
+ }
116285
+ }
116286
+ return sawNever ? sawMaybe || sawAlways ? "maybe" : "never" : sawMaybe ? "maybe" : "always";
116287
+ };
116288
+ var finalizeCase = (branches, fallback) => {
116289
+ const resultExpressions = [...branches.map((branch) => branch.then), fallback];
116290
+ const allExpressions = [...branches.flatMap((branch) => [branch.when, branch.then]), fallback];
116291
+ const representative = resultExpressions.find((value) => value[TypeId].nullability !== "always") ?? fallback;
116292
+ return makeExpression2({
116293
+ runtime: undefined,
116294
+ dbType: representative[TypeId].dbType,
116295
+ nullability: resolveCaseNullabilityRuntime(resultExpressions),
116296
+ dialect: allExpressions.find((value) => value[TypeId].dialect !== undefined)?.[TypeId].dialect ?? profile2.dialect,
116297
+ kind: mergeAggregationManyRuntime(allExpressions),
116298
+ dependencies: mergeManyDependencies(allExpressions)
116299
+ }, {
116300
+ kind: "case",
116301
+ branches: branches.map((branch) => ({
116302
+ when: branch.when,
116303
+ then: branch.then
116304
+ })),
116305
+ else: fallback
116306
+ });
116307
+ };
116308
+ var case_ = () => {
116309
+ const build = (branches) => ({
116310
+ when(predicate, result) {
116311
+ return build([
116312
+ ...branches,
116313
+ {
116314
+ when: toDialectExpression2(predicate),
116315
+ then: toDialectExpression2(result)
116316
+ }
116317
+ ]);
116318
+ },
116319
+ else(fallback) {
116320
+ return finalizeCase(branches, toDialectExpression2(fallback));
116321
+ }
116322
+ });
116323
+ return {
116324
+ when(predicate, result) {
116325
+ return build([{
116326
+ when: toDialectExpression2(predicate),
116327
+ then: toDialectExpression2(result)
116328
+ }]);
116329
+ }
116330
+ };
116331
+ };
116332
+ var match = (value) => {
116333
+ const subject = toDialectExpression2(value);
116334
+ const build = (branches) => ({
116335
+ when(compare, result) {
116336
+ return build([
116337
+ ...branches,
116338
+ {
116339
+ when: buildBinaryPredicate2(subject, compare, "eq"),
116340
+ then: toDialectExpression2(result)
116341
+ }
116342
+ ]);
116343
+ },
116344
+ else(fallback) {
116345
+ return finalizeCase(branches, toDialectExpression2(fallback));
116346
+ }
116347
+ });
116348
+ return {
116349
+ when(compare, result) {
116350
+ const predicate = buildBinaryPredicate2(subject, compare, "eq");
116351
+ return build([{
116352
+ when: predicate,
116353
+ then: toDialectExpression2(result)
116354
+ }]);
116355
+ }
116356
+ };
116357
+ };
116358
+ var excluded = (value) => {
116359
+ const ast = value[TypeId2];
116360
+ return makeExpression2({
116361
+ runtime: undefined,
116362
+ dbType: value[TypeId].dbType,
116363
+ runtimeSchema: value[TypeId].runtimeSchema,
116364
+ driverValueMapping: value[TypeId].driverValueMapping,
116365
+ nullability: value[TypeId].nullability,
116366
+ dialect: profile2.dialect,
116367
+ kind: "scalar",
116368
+ dependencies: {}
116369
+ }, {
116370
+ kind: "excluded",
116371
+ columnName: ast.columnName
116372
+ });
116373
+ };
116374
+ var toMutationValueExpression2 = (value, column2) => {
116375
+ const columnState = column2[TypeId];
116376
+ const normalizeMutationValue = (candidate) => {
116377
+ if (candidate === null && columnState.nullability !== "never") {
116378
+ return null;
116379
+ }
116380
+ const runtimeSchemaAccepts = columnState.runtimeSchema !== undefined && Schema7.is(columnState.runtimeSchema)(candidate);
116381
+ if (runtimeSchemaAccepts) {
116382
+ return candidate;
116383
+ }
116384
+ const normalized = normalizeDbValue(columnState.dbType, candidate);
116385
+ return columnState.runtimeSchema === undefined ? normalized : Schema7.decodeUnknownSync(columnState.runtimeSchema)(normalized);
116386
+ };
116387
+ if (value !== null && typeof value === "object" && TypeId in value) {
116388
+ const expression = value;
116389
+ const ast = expression[TypeId2];
116390
+ if (ast.kind === "literal") {
116391
+ const normalizedValue2 = normalizeMutationValue(ast.value);
116392
+ return makeExpression2({
116393
+ runtime: normalizedValue2,
116394
+ dbType: columnState.dbType,
116395
+ runtimeSchema: columnState.runtimeSchema,
116396
+ driverValueMapping: columnState.driverValueMapping,
116397
+ nullability: normalizedValue2 === null ? "always" : "never",
116398
+ dialect: columnState.dialect,
116399
+ kind: "scalar",
116400
+ dependencies: {}
116401
+ }, {
116402
+ kind: "literal",
116403
+ value: normalizedValue2
116404
+ });
116405
+ }
116406
+ return retargetLiteralExpression2(value, column2);
116407
+ }
116408
+ const normalizedValue = normalizeMutationValue(value);
116409
+ return makeExpression2({
116410
+ runtime: normalizedValue,
116411
+ dbType: columnState.dbType,
116412
+ runtimeSchema: columnState.runtimeSchema,
116413
+ driverValueMapping: columnState.driverValueMapping,
116414
+ nullability: normalizedValue === null ? "always" : "never",
116415
+ dialect: columnState.dialect,
116416
+ kind: "scalar",
116417
+ dependencies: {}
116418
+ }, {
116419
+ kind: "literal",
116420
+ value: normalizedValue
116421
+ });
116422
+ };
116423
+ var renderQuantifiedComparisonAst = (left, plan, operator, quantifier) => ({
116424
+ kind: quantifier === "any" ? "comparisonAny" : "comparisonAll",
116425
+ operator,
116426
+ left,
116427
+ plan
116428
+ });
116429
+ var targetSourceDetails2 = (table) => {
116430
+ const sourceName = table[TypeId7].name;
116431
+ const sourceBaseName = table[TypeId7].baseName;
116432
+ return {
116433
+ sourceName,
116434
+ sourceBaseName
116435
+ };
116436
+ };
116437
+ var sourceDetails2 = (source) => {
116438
+ if (TypeId7 in source) {
116439
+ return targetSourceDetails2(source);
116440
+ }
116441
+ const record2 = source;
116442
+ return {
116443
+ sourceName: record2.name,
116444
+ sourceBaseName: record2.baseName
116445
+ };
116446
+ };
116447
+ var makeColumnReferenceSelection2 = (alias2, selection) => {
116448
+ const columns = {};
116449
+ for (const [columnName, expression] of Object.entries(selection)) {
116450
+ const state = expression[TypeId];
116451
+ columns[columnName] = makeExpression2({
116452
+ runtime: undefined,
116453
+ dbType: state.dbType,
116454
+ runtimeSchema: state.runtimeSchema,
116455
+ driverValueMapping: state.driverValueMapping,
116456
+ nullability: state.nullability,
116457
+ dialect: state.dialect,
116458
+ kind: "scalar",
116459
+ dependencies: {
116460
+ [alias2]: true
116461
+ }
116462
+ }, {
116463
+ kind: "column",
116464
+ tableName: alias2,
116465
+ columnName
116466
+ });
116467
+ }
116468
+ return columns;
116469
+ };
116470
+ var makeAliasedValuesSource = (rows, selection, alias2) => {
116471
+ const columns = makeColumnReferenceSelection2(alias2, selection);
116472
+ const source = {
116473
+ kind: "values",
116474
+ name: alias2,
116475
+ baseName: alias2,
116476
+ dialect: profile2.dialect,
116477
+ rows,
116478
+ columns
116479
+ };
116480
+ return Object.assign(source, columns);
116481
+ };
116482
+ var normalizeValuesRow2 = (row) => Object.fromEntries(Object.entries(row).map(([key2, value]) => [key2, toDialectExpression2(value)]));
116483
+ var normalizeUnnestColumns2 = (columns) => Object.fromEntries(Object.entries(columns).map(([key2, values2]) => [key2, values2.map((value) => toDialectExpression2(value))]));
116484
+ var normalizeMutationTargets2 = (target) => Array.isArray(target) ? target : [target];
116485
+ var mutationTargetClauses2 = (target) => normalizeMutationTargets2(target).map((table) => {
116486
+ const { sourceName, sourceBaseName } = targetSourceDetails2(table);
116487
+ return {
116488
+ kind: "from",
116489
+ tableName: sourceName,
116490
+ baseTableName: sourceBaseName,
116491
+ source: table
116492
+ };
116493
+ });
116494
+ var mutationAvailableSources2 = (target, mode = "required") => Object.fromEntries(normalizeMutationTargets2(target).map((table) => {
116495
+ const { sourceName, sourceBaseName } = targetSourceDetails2(table);
116496
+ return [
116497
+ sourceName,
116498
+ {
116499
+ name: sourceName,
116500
+ mode,
116501
+ baseName: sourceBaseName
116502
+ }
116503
+ ];
116504
+ }));
116505
+ var getMutationColumn2 = (columns, columnName) => columns[columnName];
116506
+ var buildMutationAssignments2 = (target, values2) => {
116507
+ const targets = normalizeMutationTargets2(target);
116508
+ if (targets.length === 1 && !Array.isArray(target)) {
116509
+ const columns = target;
116510
+ return Object.entries(values2).map(([columnName, value]) => ({
116511
+ columnName,
116512
+ value: toMutationValueExpression2(value, getMutationColumn2(columns, columnName))
116513
+ }));
116514
+ }
116515
+ const valueMap = values2;
116516
+ return targets.flatMap((table) => {
116517
+ const targetName = table[TypeId7].name;
116518
+ const scopedValues = valueMap[targetName] ?? {};
116519
+ const columns = table;
116520
+ return Object.entries(scopedValues).map(([columnName, value]) => ({
116521
+ tableName: targetName,
116522
+ columnName,
116523
+ value: toMutationValueExpression2(value, getMutationColumn2(columns, columnName))
116524
+ }));
116525
+ });
116526
+ };
116527
+ var buildInsertValuesRows2 = (target, rows) => {
116528
+ const firstRow = rows[0];
116529
+ const firstColumns = Object.keys(firstRow);
116530
+ const columns = firstColumns;
116531
+ const normalizeRow = (row) => {
116532
+ const assignments = buildMutationAssignments2(target, row);
116533
+ return {
116534
+ values: columns.map((columnName) => assignments.find((assignment) => assignment.columnName === columnName))
116535
+ };
116536
+ };
116537
+ const normalizedRows = [
116538
+ normalizeRow(rows[0]),
116539
+ ...rows.slice(1).map(normalizeRow)
116540
+ ];
116541
+ const required = normalizedRows.flatMap((row) => row.values.flatMap((entry) => Object.keys(entry.value[TypeId].dependencies)));
116542
+ return {
116543
+ columns,
116544
+ rows: normalizedRows,
116545
+ required: required.filter((name, index4, list) => list.indexOf(name) === index4)
116546
+ };
116547
+ };
116548
+ var normalizeInsertSelectColumns2 = (selection) => {
116549
+ const columns = Object.keys(selection);
116550
+ return columns;
116551
+ };
116552
+ var normalizeInsertUnnestValues2 = (target, values2) => {
116553
+ const entries = Object.entries(values2);
116554
+ const columns = entries.map(([columnName]) => columnName);
116555
+ const normalized = entries.map(([columnName, items]) => ({
116556
+ columnName,
116557
+ values: items
116558
+ }));
116559
+ return {
116560
+ columns,
116561
+ values: normalized
116562
+ };
116563
+ };
116564
+ var normalizeConflictColumns2 = (target, columnsInput) => {
116565
+ const columns = normalizeColumnList(columnsInput);
116566
+ return columns;
116567
+ };
116568
+ var buildConflictTarget2 = (target, input) => {
116569
+ if (typeof input === "string" || Array.isArray(input)) {
116570
+ return {
116571
+ kind: "columns",
116572
+ columns: normalizeConflictColumns2(target, input)
116573
+ };
116574
+ }
116575
+ if (!Array.isArray(input) && "constraint" in input) {
116576
+ return {
116577
+ kind: "constraint",
116578
+ name: input.constraint
116579
+ };
116580
+ }
116581
+ const columnTarget = input;
116582
+ return {
116583
+ kind: "columns",
116584
+ columns: normalizeConflictColumns2(target, columnTarget.columns),
116585
+ where: columnTarget.where === undefined ? undefined : toDialectExpression2(columnTarget.where)
116586
+ };
116587
+ };
116588
+ var defaultIndexName2 = (tableName, columns, unique3) => `${tableName}_${columns.join("_")}_${unique3 ? "uniq" : "idx"}`;
116589
+ function as(valueOrAlias, alias2) {
116590
+ if (alias2 === undefined) {
116591
+ return (value2) => as(value2, valueOrAlias);
116592
+ }
116593
+ const resolvedAlias = alias2;
116594
+ const value = valueOrAlias;
116595
+ if (typeof value !== "object" || value === null || TypeId in value) {
116596
+ const expression = toDialectExpression2(value);
116597
+ const projected = Object.create(Object.getPrototypeOf(expression));
116598
+ const runtimeExpression = expression;
116599
+ projected[TypeId] = runtimeExpression[TypeId];
116600
+ projected[TypeId2] = runtimeExpression[TypeId2];
116601
+ if ("schema" in runtimeExpression) {
116602
+ projected.schema = runtimeExpression.schema;
116603
+ }
116604
+ projected[TypeId9] = {
116605
+ alias: resolvedAlias
116606
+ };
116607
+ return projected;
116608
+ }
116609
+ if ("kind" in value && value.kind === "values" && !("name" in value)) {
116610
+ const valuesInput = value;
116611
+ return makeAliasedValuesSource(valuesInput.rows, valuesInput.selection, resolvedAlias);
116612
+ }
116613
+ return makeDerivedSource(value, resolvedAlias);
116614
+ }
116615
+ function with_(valueOrAlias, alias2) {
116616
+ if (alias2 === undefined) {
116617
+ return (value) => with_(value, valueOrAlias);
116618
+ }
116619
+ return makeCteSource(valueOrAlias, alias2);
116620
+ }
116621
+ function withRecursive_(valueOrAlias, alias2) {
116622
+ if (alias2 === undefined) {
116623
+ return (value) => withRecursive_(value, valueOrAlias);
116624
+ }
116625
+ return makeCteSource(valueOrAlias, alias2, true);
116626
+ }
116627
+ function lateral(valueOrAlias, alias2) {
116628
+ if (alias2 === undefined) {
116629
+ return (value) => lateral(value, valueOrAlias);
116630
+ }
116631
+ return makeLateralSource(valueOrAlias, alias2);
116632
+ }
116633
+ var {
116634
+ values: values2,
116635
+ unnest: unnest2,
116636
+ generateSeries: generateSeries2,
116637
+ select: select2,
116638
+ groupBy: groupBy2,
116639
+ returning: returning2
116640
+ } = makeDslQueryRuntime({
116641
+ profile: profile2,
116642
+ ValuesInputProto: ValuesInputProto2,
116643
+ normalizeValuesRow: normalizeValuesRow2,
116644
+ normalizeUnnestColumns: normalizeUnnestColumns2,
116645
+ makeColumnReferenceSelection: makeColumnReferenceSelection2,
116646
+ toDialectNumericExpression: toDialectNumericExpression2,
116647
+ extractRequiredRuntime,
116648
+ makePlan,
116649
+ getAst,
116650
+ getQueryState,
116651
+ currentRequiredList,
116652
+ dedupeGroupedExpressions
116653
+ });
116654
+ var {
116655
+ buildSetOperation: buildSetOperation2,
116656
+ where: where2,
116657
+ from: from2,
116658
+ having: having2,
116659
+ crossJoin: crossJoin2,
116660
+ join: join2,
116661
+ orderBy: orderBy2,
116662
+ lock: lock2,
116663
+ distinct: distinct2,
116664
+ limit: limit2,
116665
+ offset: offset2
116666
+ } = makeDslPlanRuntime({
116667
+ profile: profile2,
116668
+ makePlan,
116669
+ getAst,
116670
+ getQueryState,
116671
+ currentRequiredList,
116672
+ toDialectExpression: toDialectExpression2,
116673
+ toDialectNumericExpression: toDialectNumericExpression2,
116674
+ extractRequiredFromDialectInputRuntime: extractRequiredFromDialectInputRuntime2,
116675
+ extractRequiredFromDialectNumericInputRuntime: extractRequiredFromDialectNumericInputRuntime2,
116676
+ formulaOfExpressionRuntime: formulaOfExpression,
116677
+ assumeFormulaTrue,
116678
+ trueFormula,
116679
+ sourceDetails: sourceDetails2,
116680
+ presenceWitnessesOfSourceLike,
116681
+ attachInsertSource: (...args) => attachInsertSource2(args[0], args[1])
116682
+ });
116683
+ var union = (left, right) => buildSetOperation2("union", false, left, right);
116684
+ var unionAll = (left, right) => buildSetOperation2("union", true, left, right);
116685
+ var intersect = (left, right) => buildSetOperation2("intersect", false, left, right);
116686
+ var intersectAll = (left, right) => buildSetOperation2("intersect", true, left, right);
116687
+ var except = (left, right) => buildSetOperation2("except", false, left, right);
116688
+ var exceptAll = (left, right) => buildSetOperation2("except", true, left, right);
116689
+ var innerJoin = (table, on) => join2("inner", table, on);
116690
+ var leftJoin = (table, on) => join2("left", table, on);
116691
+ var rightJoin = (table, on) => join2("right", table, on);
116692
+ var fullJoin = (table, on) => join2("full", table, on);
116693
+ var distinctOn2 = {
116694
+ __effect_qb_error__: "effect-qb: distinctOn(...) is only supported by the postgres dialect",
116695
+ __effect_qb_dialect__: profile2.dialect,
116696
+ __effect_qb_hint__: "Use postgres.Query.distinctOn(...) or regular distinct()/grouping logic"
116697
+ };
116698
+ var mutationRuntime2 = makeDslMutationRuntime({
116699
+ profile: profile2,
116700
+ makePlan,
116701
+ getAst,
116702
+ getQueryState,
116703
+ currentRequiredList,
116704
+ toDialectExpression: toDialectExpression2,
116705
+ buildMutationAssignments: buildMutationAssignments2,
116706
+ buildInsertValuesRows: buildInsertValuesRows2,
116707
+ normalizeInsertUnnestValues: normalizeInsertUnnestValues2,
116708
+ normalizeInsertSelectColumns: normalizeInsertSelectColumns2,
116709
+ buildConflictTarget: buildConflictTarget2,
116710
+ mutationTargetClauses: mutationTargetClauses2,
116711
+ mutationAvailableSources: mutationAvailableSources2,
116712
+ normalizeConflictColumns: normalizeConflictColumns2,
116713
+ targetSourceDetails: targetSourceDetails2,
116714
+ sourceDetails: sourceDetails2
116715
+ });
116716
+ var insert = (target, values3) => mutationRuntime2.insert(target, values3);
116717
+ var attachInsertSource2 = (plan, source) => mutationRuntime2.attachInsertSource(plan, source);
116718
+ var onConflict = (target, options2 = {}) => (plan) => mutationRuntime2.onConflict(target, options2)(plan);
116719
+ var update2 = (target, values3) => mutationRuntime2.update(target, values3);
116720
+ var upsert = (target, values3, conflictColumns, updateValues) => mutationRuntime2.upsert(target, values3, conflictColumns, updateValues);
116721
+ var delete_2 = (target) => mutationRuntime2.delete_(target);
116722
+ var truncate = (target, options2 = {}) => mutationRuntime2.truncate(target, options2);
116723
+ var merge2 = (target, source, on, options2) => mutationRuntime2.merge(target, source, on, options2);
116724
+ var {
116725
+ transaction: transaction2,
116726
+ commit: commit2,
116727
+ rollback: rollback2,
116728
+ savepoint: savepoint2,
116729
+ rollbackTo: rollbackTo2,
116730
+ releaseSavepoint: releaseSavepoint2,
116731
+ createTable: createTable2,
116732
+ dropTable: dropTable2,
116733
+ createIndex: createIndex2,
116734
+ dropIndex: dropIndex2
116735
+ } = makeDslTransactionDdlRuntime({
116736
+ profile: profile2,
116737
+ makePlan,
116738
+ targetSourceDetails: targetSourceDetails2,
116739
+ normalizeColumnList,
116740
+ defaultIndexName: defaultIndexName2
116741
+ });
116742
+ var {
116743
+ values: exportedValues,
116744
+ unnest: exportedUnnest,
116745
+ select: exportedSelect,
116746
+ from: exportedFrom,
116747
+ insert: exportedInsert
116748
+ } = {
116749
+ values: values2,
116750
+ unnest: unnest2,
116751
+ select: select2,
116752
+ from: from2,
116753
+ insert
116754
+ };
116755
+
116756
+ // src/internal/analytics.ts
116757
+ var normalizeSpec = (spec) => {
116758
+ validateWindowFrame(spec.frame);
116759
+ return {
116760
+ partitionBy: spec.partitionBy ?? [],
116761
+ orderBy: spec.orderBy.map((term) => ({
116762
+ value: term.value,
116763
+ direction: term.direction ?? "asc"
116764
+ })),
116765
+ frame: spec.frame
116766
+ };
116767
+ };
116768
+ var rejectExplicitPortableFrame = (functionName, spec) => {
116769
+ if (spec.frame !== undefined) {
116770
+ throw new Error(`${functionName} does not accept an explicit frame on the portable Function API; use a dialect Function helper`);
116771
+ }
116772
+ };
116773
+ var windowExpression = (kind, value, spec, nullability, options2 = {}) => {
116774
+ const normalized = normalizeSpec(spec);
116775
+ const { fallbackDialect, ...astOptions } = options2;
116776
+ const expressions = [
116777
+ value,
116778
+ ...normalized.partitionBy,
116779
+ ...normalized.orderBy.map((term) => term.value),
116780
+ ...options2.offset === undefined ? [] : [options2.offset],
116781
+ ...options2.defaultValue === undefined ? [] : [options2.defaultValue]
116782
+ ];
116783
+ return makeExpression2({
116784
+ runtime: undefined,
116785
+ dbType: value[TypeId].dbType,
116786
+ runtimeSchema: value[TypeId].runtimeSchema,
116787
+ driverValueMapping: value[TypeId].driverValueMapping,
116788
+ nullability,
116789
+ dialect: expressions.find((entry) => entry[TypeId].dialect !== "standard")?.[TypeId].dialect ?? fallbackDialect ?? value[TypeId].dialect,
116790
+ kind: "window",
116791
+ dependencies: mergeManyDependencies(expressions)
116792
+ }, {
116793
+ kind: "window",
116794
+ function: kind,
116795
+ value,
116796
+ ...astOptions,
116797
+ ...normalized
116798
+ });
116799
+ };
116800
+ var lag = (value, options2) => {
116801
+ rejectExplicitPortableFrame("lag", options2.spec);
116802
+ if (options2.offset !== undefined && (!Number.isSafeInteger(options2.offset) || options2.offset < 0)) {
116803
+ throw new Error("lag offset must be a non-negative safe integer");
116804
+ }
116805
+ return windowExpression("lag", value, options2.spec, "maybe", {
116806
+ ...options2.offset === undefined && options2.default === undefined ? {} : { offset: literal3(options2.offset ?? 1) },
116807
+ ...options2.default === undefined ? {} : { defaultValue: literal3(options2.default) }
116808
+ });
116809
+ };
116810
+ var lead = (value, options2) => {
116811
+ rejectExplicitPortableFrame("lead", options2.spec);
116812
+ if (options2.offset !== undefined && (!Number.isSafeInteger(options2.offset) || options2.offset < 0)) {
116813
+ throw new Error("lead offset must be a non-negative safe integer");
116814
+ }
116815
+ return windowExpression("lead", value, options2.spec, "maybe", {
116816
+ ...options2.offset === undefined && options2.default === undefined ? {} : { offset: literal3(options2.offset ?? 1) },
116817
+ ...options2.default === undefined ? {} : { defaultValue: literal3(options2.default) }
116818
+ });
116819
+ };
116820
+ var firstValue = (value, spec) => {
116821
+ rejectExplicitPortableFrame("firstValue", spec);
116822
+ return windowExpression("firstValue", value, spec, value[TypeId].nullability);
116823
+ };
116824
+ var lastValue = (value, spec) => {
116825
+ rejectExplicitPortableFrame("lastValue", spec);
116826
+ return windowExpression("lastValue", value, spec, value[TypeId].nullability);
116827
+ };
116828
+ var makeDialectFirstValue = (dialect) => (value, spec) => windowExpression("firstValue", value, spec, "maybe", { fallbackDialect: dialect });
116829
+ var makeDialectLastValue = (dialect) => (value, spec) => windowExpression("lastValue", value, spec, "maybe", { fallbackDialect: dialect });
116830
+
116831
+ // src/mysql/function/window.ts
116832
+ var firstValue2 = makeDialectFirstValue("mysql");
116833
+ var lastValue2 = makeDialectLastValue("mysql");
116834
+ // src/mysql/function/temporal.ts
116835
+ var exports_temporal = {};
116836
+ __export(exports_temporal, {
116837
+ now: () => now,
116838
+ localTimestamp: () => localTimestamp,
116839
+ localTime: () => localTime,
116840
+ currentTimestamp: () => currentTimestamp,
116841
+ currentTime: () => currentTime,
116842
+ currentDate: () => currentDate
116843
+ });
116844
+ var makeTemporal = (name, dbType, runtimeSchema) => makeExpression2({
116845
+ runtime: undefined,
116846
+ dbType,
116847
+ runtimeSchema,
116848
+ nullability: "never",
116849
+ dialect: "mysql",
116850
+ kind: "scalar",
116851
+ dependencies: {}
116852
+ }, {
116853
+ kind: "function",
116854
+ name,
116855
+ args: []
116856
+ });
116857
+ var currentDate = () => makeTemporal("current_date", mysqlDatatypes.date(), LocalDateStringSchema);
116858
+ var currentTime = () => makeTemporal("current_time", mysqlDatatypes.time(), LocalTimeStringSchema);
116859
+ var currentTimestamp = () => makeTemporal("current_timestamp", mysqlDatatypes.datetime(), LocalDateTimeStringSchema);
116860
+ var localTime = () => makeTemporal("localtime", mysqlDatatypes.datetime(), LocalDateTimeStringSchema);
116861
+ var localTimestamp = () => makeTemporal("localtimestamp", mysqlDatatypes.datetime(), LocalDateTimeStringSchema);
116862
+ var now = () => makeTemporal("now", mysqlDatatypes.datetime(), LocalDateTimeStringSchema);
116863
+ // src/mysql/json.ts
116864
+ var exports_json = {};
116865
+ __export(exports_json, {
116866
+ typeOf: () => typeOf,
116867
+ stripNulls: () => stripNulls,
116868
+ pathMatch: () => pathMatch,
116869
+ length: () => length
116870
+ });
116871
+ var typeOf = json.typeOf;
116872
+ var length = json.length;
116873
+ var stripNulls = json.stripNulls;
116874
+ var pathMatch = json.pathMatch;
116875
+ // src/mysql/executor.ts
116876
+ var exports_executor2 = {};
116877
+ __export(exports_executor2, {
116878
+ withTransaction: () => withTransaction2,
116879
+ nonEmpty: () => nonEmpty2,
116880
+ make: () => make4,
116881
+ exactlyOne: () => exactlyOne2,
116882
+ driver: () => driver2,
116883
+ custom: () => custom4,
116884
+ atMostOne: () => atMostOne2
116885
+ });
116886
+ import * as Effect2 from "effect/Effect";
116887
+ import * as SqlClient3 from "effect/unstable/sql/SqlClient";
116888
+ import * as Stream2 from "effect/Stream";
116889
+
116890
+ // src/internal/executor.ts
116891
+ var exports_executor = {};
116892
+ __export(exports_executor, {
116893
+ withTransaction: () => withTransaction,
116894
+ withResultContracts: () => withResultContracts,
116895
+ streamFromSqlClient: () => streamFromSqlClient,
116896
+ remapRows: () => remapRows,
116897
+ nonEmpty: () => nonEmpty,
116898
+ makeRowDecoder: () => makeRowDecoder,
116899
+ make: () => make3,
116900
+ hasWriteCapability: () => hasWriteCapability,
116901
+ fromSqlClient: () => fromSqlClient,
116902
+ fromDriver: () => fromDriver,
116903
+ explainQuery: () => explainQuery,
116904
+ exactlyOne: () => exactlyOne,
116905
+ driver: () => driver,
116906
+ decodeRows: () => decodeRows,
116907
+ decodeChunk: () => decodeChunk,
116908
+ atMostOne: () => atMostOne
116909
+ });
116910
+ import * as Chunk from "effect/Chunk";
116911
+ import * as Effect from "effect/Effect";
116912
+ import * as Exit from "effect/Exit";
116913
+ import * as Option from "effect/Option";
116914
+ import * as Schema10 from "effect/Schema";
116915
+ import * as SqlClient from "effect/unstable/sql/SqlClient";
116916
+ import * as Stream from "effect/Stream";
116917
+
116918
+ // src/internal/runtime/driver-value-mapping.ts
116919
+ import * as Schema8 from "effect/Schema";
116920
+ var runtimeTagOfDbType = (dbType) => {
116921
+ if (dbType === undefined) {
116922
+ return;
116923
+ }
116924
+ if ("base" in dbType) {
116925
+ return runtimeTagOfDbType(dbType.base);
116926
+ }
116927
+ if ("element" in dbType) {
116928
+ return "array";
116929
+ }
116930
+ if ("fields" in dbType) {
116931
+ return "record";
116932
+ }
116933
+ if ("variant" in dbType && dbType.variant === "json") {
116934
+ return "json";
116935
+ }
116936
+ if ("variant" in dbType && (dbType.variant === "enum" || dbType.variant === "set")) {
116937
+ return "string";
116938
+ }
116939
+ return dbType.runtime;
116940
+ };
116941
+ var familyOfDbType = (dbType) => {
116942
+ if (dbType === undefined) {
116943
+ return;
116944
+ }
116945
+ if ("base" in dbType) {
116946
+ return familyOfDbType(dbType.base);
116947
+ }
116948
+ return dbType.family;
116949
+ };
116950
+ var mappingCandidates = (context) => {
116951
+ const dbType = context.dbType;
116952
+ const runtimeTag = runtimeTagOfDbType(dbType);
116953
+ const family = familyOfDbType(dbType);
116954
+ return [
116955
+ context.driverValueMapping,
116956
+ dbType?.driverValueMapping,
116957
+ dbType === undefined ? undefined : context.valueMappings?.[dbType.kind],
116958
+ family === undefined ? undefined : context.valueMappings?.[family],
116959
+ runtimeTag === undefined ? undefined : context.valueMappings?.[runtimeTag]
116960
+ ];
116961
+ };
116962
+ var findMapping = (context, key2) => {
116963
+ for (const candidate of mappingCandidates(context)) {
116964
+ const value = candidate?.[key2];
116965
+ if (value !== undefined) {
116966
+ return value;
116967
+ }
116968
+ }
116969
+ return;
116970
+ };
116971
+ var isJsonDbType = (dbType) => {
116972
+ if (dbType === undefined) {
116973
+ return false;
116974
+ }
116975
+ if ("base" in dbType) {
116976
+ return isJsonDbType(dbType.base);
116977
+ }
116978
+ if (!("variant" in dbType)) {
116979
+ return false;
116980
+ }
116981
+ const variant = dbType.variant;
116982
+ return variant === "json" || variant === "jsonb";
116983
+ };
116984
+ var schemaAccepts = (schema2, value) => schema2 !== undefined && Schema8.is(schema2)(value);
116985
+ var encodeWithSchema = (schema2, value) => {
116986
+ if (schema2 === undefined) {
116987
+ return { value, encoded: false };
116988
+ }
116989
+ if (!Schema8.is(schema2)(value)) {
116990
+ return { value, encoded: false };
116991
+ }
116992
+ return {
116993
+ value: Schema8.encodeUnknownSync(schema2)(value),
116994
+ encoded: true
116995
+ };
116996
+ };
116997
+ var normalizeJsonDriverString = (value, context) => {
116998
+ if (!isJsonDbType(context.dbType) || context.runtimeSchema === undefined) {
116999
+ return;
117000
+ }
117001
+ try {
117002
+ const parsed = JSON.parse(value);
117003
+ if (value.trimStart().startsWith('"') && schemaAccepts(context.runtimeSchema, parsed)) {
117004
+ return parsed;
117005
+ }
117006
+ if (schemaAccepts(context.runtimeSchema, value) && !schemaAccepts(context.runtimeSchema, parsed)) {
117007
+ return value;
117008
+ }
117009
+ } catch (error) {
117010
+ if (error instanceof SyntaxError && schemaAccepts(context.runtimeSchema, value)) {
117011
+ return value;
117012
+ }
117013
+ if (!(error instanceof SyntaxError)) {
117014
+ throw error;
117015
+ }
117016
+ }
117017
+ return;
117018
+ };
117019
+ var toDriverValue = (value, context) => {
117020
+ if (value === null) {
117021
+ return null;
117022
+ }
117023
+ if (value instanceof Date && Number.isNaN(value.getTime())) {
117024
+ throw new Error("Expected a valid Date value");
117025
+ }
117026
+ const dbType = context.dbType;
117027
+ const encoded = encodeWithSchema(context.runtimeSchema, value);
117028
+ let current = encoded.value;
117029
+ const custom4 = findMapping(context, "toDriver");
117030
+ if (custom4 !== undefined && dbType !== undefined) {
117031
+ return custom4(current, dbType);
117032
+ }
117033
+ if (encoded.encoded && typeof current === "string" && isJsonDbType(dbType)) {
117034
+ return current;
117035
+ }
117036
+ return dbType === undefined || !encoded.encoded ? current : normalizeDbValue(dbType, current);
117037
+ };
117038
+ var fromDriverValue = (value, context) => {
117039
+ if (value === null) {
117040
+ return null;
117041
+ }
114945
117042
  const dbType = context.dbType;
114946
- const custom3 = findMapping(context, "fromDriver");
114947
- if (custom3 !== undefined && dbType !== undefined) {
114948
- return custom3(value, dbType);
117043
+ const custom4 = findMapping(context, "fromDriver");
117044
+ if (custom4 !== undefined && dbType !== undefined) {
117045
+ return custom4(value, dbType);
114949
117046
  }
114950
117047
  if (typeof value === "string") {
114951
117048
  const normalizedJsonString = normalizeJsonDriverString(value, context);
@@ -114976,33 +117073,33 @@ var postgresJsonSql = (sql, dbType) => {
114976
117073
  };
114977
117074
  var renderSelectSql = (sql, context) => {
114978
117075
  const dbType = context.dbType;
114979
- const custom3 = findMapping(context, "selectSql");
114980
- return custom3 !== undefined && dbType !== undefined ? custom3(sql, dbType) : sql;
117076
+ const custom4 = findMapping(context, "selectSql");
117077
+ return custom4 !== undefined && dbType !== undefined ? custom4(sql, dbType) : sql;
114981
117078
  };
114982
117079
  var renderJsonSelectSql = (sql, context) => {
114983
117080
  const dbType = context.dbType;
114984
- const custom3 = findMapping(context, "jsonSelectSql");
114985
- if (custom3 !== undefined && dbType !== undefined) {
114986
- return custom3(sql, dbType);
117081
+ const custom4 = findMapping(context, "jsonSelectSql");
117082
+ if (custom4 !== undefined && dbType !== undefined) {
117083
+ return custom4(sql, dbType);
114987
117084
  }
114988
117085
  return context.dialect === "postgres" && dbType !== undefined ? postgresJsonSql(sql, dbType) : sql;
114989
117086
  };
114990
117087
 
114991
117088
  // src/internal/runtime/schema.ts
114992
- import * as Schema8 from "effect/Schema";
117089
+ import * as Schema9 from "effect/Schema";
114993
117090
  import * as SchemaAST from "effect/SchemaAST";
114994
117091
  var schemaCache = new WeakMap;
114995
- var FiniteNumberSchema = Schema8.Number.check(Schema8.isFinite());
117092
+ var FiniteNumberSchema = Schema9.Number.check(Schema9.isFinite());
114996
117093
  var runtimeSchemaForTag = (tag) => {
114997
117094
  switch (tag) {
114998
117095
  case "string":
114999
- return Schema8.String;
117096
+ return Schema9.String;
115000
117097
  case "number":
115001
117098
  return FiniteNumberSchema;
115002
117099
  case "bigintString":
115003
117100
  return BigIntStringSchema;
115004
117101
  case "boolean":
115005
- return Schema8.Boolean;
117102
+ return Schema9.Boolean;
115006
117103
  case "json":
115007
117104
  return JsonValueSchema;
115008
117105
  case "localDate":
@@ -115020,13 +117117,13 @@ var runtimeSchemaForTag = (tag) => {
115020
117117
  case "decimalString":
115021
117118
  return DecimalStringSchema;
115022
117119
  case "bytes":
115023
- return Schema8.Uint8Array;
117120
+ return Schema9.Uint8Array;
115024
117121
  case "array":
115025
- return Schema8.Array(Schema8.Unknown);
117122
+ return Schema9.Array(Schema9.Unknown);
115026
117123
  case "record":
115027
- return Schema8.Record(Schema8.String, Schema8.Unknown);
117124
+ return Schema9.Record(Schema9.String, Schema9.Unknown);
115028
117125
  case "null":
115029
- return Schema8.Null;
117126
+ return Schema9.Null;
115030
117127
  case "unknown":
115031
117128
  return;
115032
117129
  }
@@ -115039,22 +117136,22 @@ var runtimeSchemaForDbType = (dbType) => {
115039
117136
  return runtimeSchemaForDbType(dbType.base);
115040
117137
  }
115041
117138
  if ("element" in dbType) {
115042
- return Schema8.Array(runtimeSchemaForDbType(dbType.element) ?? Schema8.Unknown);
117139
+ return Schema9.Array(runtimeSchemaForDbType(dbType.element) ?? Schema9.Unknown);
115043
117140
  }
115044
117141
  if ("fields" in dbType) {
115045
- const fields2 = Object.fromEntries(Object.entries(dbType.fields).map(([key2, field]) => [key2, runtimeSchemaForDbType(field) ?? Schema8.Unknown]));
115046
- return Schema8.Struct(fields2);
117142
+ const fields2 = Object.fromEntries(Object.entries(dbType.fields).map(([key2, field]) => [key2, runtimeSchemaForDbType(field) ?? Schema9.Unknown]));
117143
+ return Schema9.Struct(fields2);
115047
117144
  }
115048
117145
  if ("variant" in dbType && dbType.variant === "json") {
115049
117146
  return JsonValueSchema;
115050
117147
  }
115051
117148
  if ("variant" in dbType && (dbType.variant === "enum" || dbType.variant === "set")) {
115052
- return Schema8.String;
117149
+ return Schema9.String;
115053
117150
  }
115054
117151
  const runtimeTag = runtimeTagOfBaseDbType2(dbType);
115055
117152
  return runtimeTag === undefined ? undefined : runtimeSchemaForTag(runtimeTag);
115056
117153
  };
115057
- var makeSchemaFromAst = (ast) => Schema8.make(ast);
117154
+ var makeSchemaFromAst = (ast) => Schema9.make(ast);
115058
117155
  var unionAst = (asts) => {
115059
117156
  if (asts.length === 0) {
115060
117157
  return;
@@ -115077,11 +117174,11 @@ var propertyAstOf = (ast, key2) => {
115077
117174
  return index4?.type;
115078
117175
  }
115079
117176
  case "Union": {
115080
- const values2 = ast.types.flatMap((member) => {
117177
+ const values3 = ast.types.flatMap((member) => {
115081
117178
  const next = propertyAstOf(member, key2);
115082
117179
  return next === undefined ? [] : [next];
115083
117180
  });
115084
- return unionAst(values2);
117181
+ return unionAst(values3);
115085
117182
  }
115086
117183
  default:
115087
117184
  return;
@@ -115102,11 +117199,11 @@ var numberAstOf = (ast, index4) => {
115102
117199
  return unionAst(ast.rest);
115103
117200
  }
115104
117201
  case "Union": {
115105
- const values2 = ast.types.flatMap((member) => {
117202
+ const values3 = ast.types.flatMap((member) => {
115106
117203
  const next = numberAstOf(member, index4);
115107
117204
  return next === undefined ? [] : [next];
115108
117205
  });
115109
- return unionAst(values2);
117206
+ return unionAst(values3);
115110
117207
  }
115111
117208
  default:
115112
117209
  return;
@@ -115144,7 +117241,7 @@ var unionSchemas = (schemas) => {
115144
117241
  if (resolved.length === 1) {
115145
117242
  return resolved[0];
115146
117243
  }
115147
- return Schema8.Union(resolved);
117244
+ return Schema9.Union(resolved);
115148
117245
  };
115149
117246
  var firstSelectedExpression = (plan) => {
115150
117247
  const selection = getAst(plan).select;
@@ -115179,9 +117276,9 @@ var jsonCompatibleSchema = (schema2) => {
115179
117276
  };
115180
117277
  var buildStructSchema = (entries, context) => {
115181
117278
  const fields2 = Object.fromEntries(entries.map((entry) => [entry.key, expressionRuntimeSchema(entry.value, context) ?? JsonValueSchema]));
115182
- return Schema8.Struct(fields2);
117279
+ return Schema9.Struct(fields2);
115183
117280
  };
115184
- var buildTupleSchema = (values2, context) => Schema8.Tuple(values2.map((value) => expressionRuntimeSchema(value, context) ?? JsonValueSchema));
117281
+ var buildTupleSchema = (values3, context) => Schema9.Tuple(values3.map((value) => expressionRuntimeSchema(value, context) ?? JsonValueSchema));
115185
117282
  var deriveCaseSchema = (ast, context) => {
115186
117283
  if (context === undefined) {
115187
117284
  return unionSchemas([
@@ -115221,10 +117318,10 @@ var deriveRuntimeSchema = (expression, context) => {
115221
117318
  return state.runtimeSchema;
115222
117319
  case "literal":
115223
117320
  if (ast.value === null) {
115224
- return Schema8.Null;
117321
+ return Schema9.Null;
115225
117322
  }
115226
117323
  if (typeof ast.value === "string" || typeof ast.value === "number" || typeof ast.value === "boolean") {
115227
- return Schema8.Literal(ast.value);
117324
+ return Schema9.Literal(ast.value);
115228
117325
  }
115229
117326
  return runtimeSchemaForDbType(state.dbType);
115230
117327
  case "cast":
@@ -115260,7 +117357,7 @@ var deriveRuntimeSchema = (expression, context) => {
115260
117357
  case "jsonHasAllKeys":
115261
117358
  case "jsonPathExists":
115262
117359
  case "jsonPathMatch":
115263
- return Schema8.Boolean;
117360
+ return Schema9.Boolean;
115264
117361
  case "upper":
115265
117362
  case "lower":
115266
117363
  case "concat":
@@ -115269,8 +117366,9 @@ var deriveRuntimeSchema = (expression, context) => {
115269
117366
  case "jsonAccessText":
115270
117367
  case "jsonTraverseText":
115271
117368
  case "jsonTypeOf":
115272
- return Schema8.String;
117369
+ return Schema9.String;
115273
117370
  case "count":
117371
+ return runtimeSchemaForDbType(state.dbType);
115274
117372
  case "jsonLength":
115275
117373
  return FiniteNumberSchema;
115276
117374
  case "max":
@@ -115285,7 +117383,7 @@ var deriveRuntimeSchema = (expression, context) => {
115285
117383
  return selection === undefined ? undefined : expressionRuntimeSchema(selection, context);
115286
117384
  }
115287
117385
  case "window":
115288
- return ast.function === "over" && ast.value !== undefined ? expressionRuntimeSchema(ast.value, context) : FiniteNumberSchema;
117386
+ return ast.function === "over" && ast.value !== undefined ? expressionRuntimeSchema(ast.value, context) : runtimeSchemaForDbType(state.dbType);
115289
117387
  case "jsonGet":
115290
117388
  case "jsonPath":
115291
117389
  case "jsonAccess":
@@ -115317,7 +117415,7 @@ var deriveRuntimeSchema = (expression, context) => {
115317
117415
  case "jsonToJsonb":
115318
117416
  return jsonCompatibleSchema(expressionRuntimeSchema(ast.value, context));
115319
117417
  case "jsonKeys":
115320
- return Schema8.Array(Schema8.String);
117418
+ return Schema9.Array(Schema9.String);
115321
117419
  }
115322
117420
  };
115323
117421
  var expressionRuntimeSchema = (expression, context) => {
@@ -115333,7 +117431,86 @@ var expressionRuntimeSchema = (expression, context) => {
115333
117431
  return resolved;
115334
117432
  };
115335
117433
 
117434
+ // src/internal/renderer.ts
117435
+ var TypeId10 = Symbol.for("effect-qb/Renderer");
117436
+ var projectionPathKey = (path2) => JSON.stringify(path2);
117437
+ var formatProjectionPath2 = (path2) => path2.join(".");
117438
+ var validateProjectionPathsMatchSelection = (plan, projections) => {
117439
+ const expected = flattenSelection(getAst(plan).select);
117440
+ const expectedPaths = new Set(expected.map((projection) => projectionPathKey(projection.path)));
117441
+ const actualPaths = new Set(projections.map((projection) => projectionPathKey(projection.path)));
117442
+ for (const projection of projections) {
117443
+ if (!expectedPaths.has(projectionPathKey(projection.path))) {
117444
+ throw new Error(`Projection path ${formatProjectionPath2(projection.path)} does not exist in the query selection`);
117445
+ }
117446
+ }
117447
+ for (const projection of expected) {
117448
+ if (!actualPaths.has(projectionPathKey(projection.path))) {
117449
+ throw new Error(`Projection path ${formatProjectionPath2(projection.path)} is missing from rendered projections`);
117450
+ }
117451
+ }
117452
+ };
117453
+ function makeTrusted(dialect, render2) {
117454
+ return makeRenderer(dialect, render2, false);
117455
+ }
117456
+ var makeRenderer = (dialect, render2, validate) => {
117457
+ if (typeof render2 !== "function") {
117458
+ throw new Error(`Renderer.make requires an explicit render implementation for dialect: ${dialect}`);
117459
+ }
117460
+ return {
117461
+ dialect,
117462
+ render(plan) {
117463
+ const rendered = render2(plan);
117464
+ const projections = rendered.projections ?? [];
117465
+ if (validate) {
117466
+ validateProjections(projections);
117467
+ validateProjectionPathsMatchSelection(plan, projections);
117468
+ }
117469
+ return {
117470
+ sql: rendered.sql,
117471
+ params: rendered.params ?? [],
117472
+ projections,
117473
+ valueMappings: rendered.valueMappings,
117474
+ dialect,
117475
+ [TypeId10]: {
117476
+ row: undefined,
117477
+ dialect
117478
+ }
117479
+ };
117480
+ }
117481
+ };
117482
+ };
117483
+
115336
117484
  // src/internal/executor.ts
117485
+ var atMostOne = (self) => Effect.flatMap(self, (rows) => rows.length <= 1 ? Effect.succeed(rows.length === 0 ? Option.none() : Option.some(rows[0])) : Effect.fail({
117486
+ _tag: "ResultCardinalityError",
117487
+ expected: "zeroOrOne",
117488
+ actual: rows.length
117489
+ }));
117490
+ var exactlyOne = (self) => Effect.flatMap(self, (rows) => rows.length === 1 ? Effect.succeed(rows[0]) : Effect.fail({
117491
+ _tag: "ResultCardinalityError",
117492
+ expected: "exactlyOne",
117493
+ actual: rows.length
117494
+ }));
117495
+ var nonEmpty = (self) => Effect.flatMap(self, (rows) => rows.length > 0 ? Effect.succeed(rows) : Effect.fail({
117496
+ _tag: "ResultCardinalityError",
117497
+ expected: "nonEmpty",
117498
+ actual: 0
117499
+ }));
117500
+ var withResultContracts = (base) => {
117501
+ const executeResult = base.executeResult ?? ((plan) => Effect.map(base.execute(plan), (rows) => ({ rows })));
117502
+ return {
117503
+ ...base,
117504
+ executeResult,
117505
+ prepare(plan) {
117506
+ return {
117507
+ execute: base.execute(plan),
117508
+ executeResult: executeResult(plan),
117509
+ stream: base.stream(plan)
117510
+ };
117511
+ }
117512
+ };
117513
+ };
115337
117514
  var setPath2 = (target, path2, value) => {
115338
117515
  let current = target;
115339
117516
  for (let index4 = 0;index4 < path2.length - 1; index4++) {
@@ -115373,7 +117550,7 @@ var hasWriteCapability = (plan) => {
115373
117550
  if (ast.target && hasWriteCapabilityInSource(ast.target.source)) {
115374
117551
  return true;
115375
117552
  }
115376
- if ((ast.joins ?? []).some((join2) => hasWriteCapabilityInSource(join2.source))) {
117553
+ if ((ast.joins ?? []).some((join3) => hasWriteCapabilityInSource(join3.source))) {
115377
117554
  return true;
115378
117555
  }
115379
117556
  return false;
@@ -115388,7 +117565,7 @@ var remapRows = (query, rows) => rows.map((row) => {
115388
117565
  return decoded;
115389
117566
  });
115390
117567
  var makeRowDecodeError = (rendered, projection, expression, raw, stage, cause, normalized) => {
115391
- const schemaError = Schema9.isSchemaError(cause) ? {
117568
+ const schemaError = Schema10.isSchemaError(cause) ? {
115392
117569
  message: cause.message,
115393
117570
  issue: cause.issue
115394
117571
  } : undefined;
@@ -115442,7 +117619,7 @@ var dbTypeAllowsTopLevelJsonNull = (dbType) => {
115442
117619
  }
115443
117620
  return "variant" in dbType && dbType.variant === "json" || dbType.runtime === "json";
115444
117621
  };
115445
- var schemaAcceptsNull = (schema2) => schema2 !== undefined && Schema9.is(schema2)(null);
117622
+ var schemaAcceptsNull = (schema2) => schema2 !== undefined && Schema10.is(schema2)(null);
115446
117623
  var decodeProjectionValue = (rendered, projection, expression, raw, scope, driverMode, valueMappings) => {
115447
117624
  let normalized = raw;
115448
117625
  if (driverMode === "raw") {
@@ -115478,10 +117655,10 @@ var decodeProjectionValue = (rendered, projection, expression, raw, scope, drive
115478
117655
  if (schema2 === undefined) {
115479
117656
  return normalized;
115480
117657
  }
115481
- if (Schema9.is(schema2)(normalized)) {
117658
+ if (Schema10.is(schema2)(normalized)) {
115482
117659
  return normalized;
115483
117660
  }
115484
- const decoded = Schema9.decodeUnknownExit(schema2)(normalized);
117661
+ const decoded = Schema10.decodeUnknownExit(schema2)(normalized);
115485
117662
  if (Exit.isSuccess(decoded)) {
115486
117663
  return decoded.value;
115487
117664
  }
@@ -115520,7 +117697,7 @@ var decodeRows = (rendered, plan, rows, options2 = {}) => {
115520
117697
  const decodeRow = makeRowDecoder(rendered, plan, options2);
115521
117698
  return rows.map((row) => decodeRow(row));
115522
117699
  };
115523
- var make3 = (dialect, execute) => ({
117700
+ var make3 = (dialect, execute) => withResultContracts({
115524
117701
  dialect,
115525
117702
  execute(plan) {
115526
117703
  return execute(plan);
@@ -115540,23 +117717,81 @@ function driver(dialect, executeOrHandlers) {
115540
117717
  return Stream.unwrap(Effect.map(executeOrHandlers(query), (rows) => Stream.fromIterable(rows)));
115541
117718
  }
115542
117719
  return executeOrHandlers.stream(query);
115543
- }
117720
+ },
117721
+ ...typeof executeOrHandlers === "function" || executeOrHandlers.executeResult === undefined ? {} : { executeResult: executeOrHandlers.executeResult }
115544
117722
  };
115545
117723
  }
115546
117724
  var fromDriver = (renderer, sqlDriver) => {
115547
- const executor = {
117725
+ const renderedCache = new WeakMap;
117726
+ const render2 = (plan) => {
117727
+ const cached = renderedCache.get(plan);
117728
+ if (cached !== undefined) {
117729
+ return cached;
117730
+ }
117731
+ const rendered = renderer.render(plan);
117732
+ renderedCache.set(plan, rendered);
117733
+ return rendered;
117734
+ };
117735
+ const executor = withResultContracts({
115548
117736
  dialect: renderer.dialect,
115549
117737
  execute(plan) {
115550
- const rendered = renderer.render(plan);
117738
+ const rendered = render2(plan);
115551
117739
  return Effect.map(sqlDriver.execute(rendered), (rows) => remapRows(rendered, rows));
115552
117740
  },
117741
+ executeResult(plan) {
117742
+ const rendered = render2(plan);
117743
+ const result = sqlDriver.executeResult ? sqlDriver.executeResult(rendered) : Effect.map(sqlDriver.execute(rendered), (rows) => ({ rows }));
117744
+ return Effect.map(result, ({ rows, ...metadata }) => ({
117745
+ ...metadata,
117746
+ rows: remapRows(rendered, rows)
117747
+ }));
117748
+ },
115553
117749
  stream(plan) {
115554
- const rendered = renderer.render(plan);
117750
+ const rendered = render2(plan);
115555
117751
  return Stream.mapArray(sqlDriver.stream(rendered), (rows) => remapRows(rendered, rows));
115556
117752
  }
115557
- };
117753
+ });
115558
117754
  return executor;
115559
117755
  };
117756
+ var explainQuery = (query, options2 = {}) => {
117757
+ const analyze = options2.analyze ?? false;
117758
+ const format = options2.format ?? "text";
117759
+ let prefix;
117760
+ switch (query.dialect) {
117761
+ case "postgres":
117762
+ prefix = `explain (${[
117763
+ ...analyze ? ["analyze true"] : [],
117764
+ `format ${format}`
117765
+ ].join(", ")}) `;
117766
+ break;
117767
+ case "mysql":
117768
+ if (analyze && format === "json") {
117769
+ throw new Error("MySQL EXPLAIN ANALYZE cannot be combined with JSON format");
117770
+ }
117771
+ prefix = analyze ? "explain analyze " : format === "json" ? "explain format=json " : "explain ";
117772
+ break;
117773
+ case "sqlite":
117774
+ if (analyze || format === "json") {
117775
+ throw new Error("SQLite EXPLAIN QUERY PLAN does not support analyze or JSON format");
117776
+ }
117777
+ prefix = "explain query plan ";
117778
+ break;
117779
+ default:
117780
+ if (analyze || format === "json") {
117781
+ throw new Error("Portable EXPLAIN only supports text plans without analyze");
117782
+ }
117783
+ prefix = "explain ";
117784
+ }
117785
+ return {
117786
+ ...query,
117787
+ sql: prefix + query.sql,
117788
+ projections: [],
117789
+ [TypeId10]: {
117790
+ row: undefined,
117791
+ dialect: query.dialect
117792
+ }
117793
+ };
117794
+ };
115560
117795
  var streamFromSqlClient = (query) => Stream.unwrap(Effect.flatMap(SqlClient.SqlClient, (sql) => Effect.flatMap(Effect.serviceOption(sql.transactionService), Option.match({
115561
117796
  onNone: () => sql.reserve,
115562
117797
  onSome: ([connection]) => Effect.succeed(connection)
@@ -115567,56 +117802,6 @@ var fromSqlClient = (renderer) => fromDriver(renderer, driver(renderer.dialect,
115567
117802
  }));
115568
117803
  var withTransaction = (effect) => Effect.flatMap(SqlClient.SqlClient, (sql) => sql.withTransaction(effect));
115569
117804
 
115570
- // src/internal/renderer.ts
115571
- var TypeId10 = Symbol.for("effect-qb/Renderer");
115572
- var projectionPathKey = (path2) => JSON.stringify(path2);
115573
- var formatProjectionPath2 = (path2) => path2.join(".");
115574
- var validateProjectionPathsMatchSelection = (plan, projections) => {
115575
- const expected = flattenSelection(getAst(plan).select);
115576
- const expectedPaths = new Set(expected.map((projection) => projectionPathKey(projection.path)));
115577
- const actualPaths = new Set(projections.map((projection) => projectionPathKey(projection.path)));
115578
- for (const projection of projections) {
115579
- if (!expectedPaths.has(projectionPathKey(projection.path))) {
115580
- throw new Error(`Projection path ${formatProjectionPath2(projection.path)} does not exist in the query selection`);
115581
- }
115582
- }
115583
- for (const projection of expected) {
115584
- if (!actualPaths.has(projectionPathKey(projection.path))) {
115585
- throw new Error(`Projection path ${formatProjectionPath2(projection.path)} is missing from rendered projections`);
115586
- }
115587
- }
115588
- };
115589
- function makeTrusted(dialect, render2) {
115590
- return makeRenderer(dialect, render2, false);
115591
- }
115592
- var makeRenderer = (dialect, render2, validate) => {
115593
- if (typeof render2 !== "function") {
115594
- throw new Error(`Renderer.make requires an explicit render implementation for dialect: ${dialect}`);
115595
- }
115596
- return {
115597
- dialect,
115598
- render(plan) {
115599
- const rendered = render2(plan);
115600
- const projections = rendered.projections ?? [];
115601
- if (validate) {
115602
- validateProjections(projections);
115603
- validateProjectionPathsMatchSelection(plan, projections);
115604
- }
115605
- return {
115606
- sql: rendered.sql,
115607
- params: rendered.params ?? [],
115608
- projections,
115609
- valueMappings: rendered.valueMappings,
115610
- dialect,
115611
- [TypeId10]: {
115612
- row: undefined,
115613
- dialect
115614
- }
115615
- };
115616
- }
115617
- };
115618
- };
115619
-
115620
117805
  // src/internal/dialect.ts
115621
117806
  var quoteDoubleQuotedIdentifier = (value) => {
115622
117807
  return `"${value.replaceAll('"', '""')}"`;
@@ -115627,7 +117812,36 @@ var quoteBacktickIdentifier = (value) => {
115627
117812
  var renderDbTypeName = (value) => value;
115628
117813
 
115629
117814
  // src/internal/dialect-renderers/mysql.ts
115630
- import * as Schema10 from "effect/Schema";
117815
+ import * as Schema11 from "effect/Schema";
117816
+
117817
+ // src/internal/custom-sql-renderer.ts
117818
+ var renderCustomSql = (node, state, dialect, renderExpression) => node.strings.map((part, index4) => {
117819
+ const value = node.values[index4];
117820
+ if (value === undefined) {
117821
+ return part;
117822
+ }
117823
+ return part + (TypeId in value ? renderExpression(value, state, dialect) : value.parts.map((segment) => dialect.quoteIdentifier(segment)).join("."));
117824
+ }).join("");
117825
+
117826
+ // src/internal/window-renderer.ts
117827
+ var renderBoundary = (boundary) => {
117828
+ if (boundary === "unboundedPreceding") {
117829
+ return "unbounded preceding";
117830
+ }
117831
+ if (boundary === "currentRow") {
117832
+ return "current row";
117833
+ }
117834
+ if (boundary === "unboundedFollowing") {
117835
+ return "unbounded following";
117836
+ }
117837
+ if ("preceding" in boundary) {
117838
+ return `${boundary.preceding} preceding`;
117839
+ }
117840
+ return `${boundary.following} following`;
117841
+ };
117842
+ var renderWindowFrame = (frame) => frame.end === undefined ? `${frame.unit} ${renderBoundary(frame.start)}` : `${frame.unit} between ${renderBoundary(frame.start)} and ${renderBoundary(frame.end)}`;
117843
+
117844
+ // src/internal/dialect-renderers/mysql.ts
115631
117845
  var renderDbType = (dialect, dbType) => {
115632
117846
  return renderDbTypeName(renderPortableDatatypeDdlType(dialect.name, dbType.kind) ?? dbType.kind);
115633
117847
  };
@@ -115760,8 +117974,8 @@ var registerQuerySources = (ast, state) => {
115760
117974
  for (const source of ast.fromSources ?? []) {
115761
117975
  registerSourceReference(source.source, source.tableName, state);
115762
117976
  }
115763
- for (const join2 of ast.joins) {
115764
- registerSourceReference(join2.source, join2.tableName, state);
117977
+ for (const join3 of ast.joins) {
117978
+ registerSourceReference(join3.source, join3.tableName, state);
115765
117979
  }
115766
117980
  if (ast.into !== undefined) {
115767
117981
  registerSourceReference(ast.into.source, ast.into.tableName, state);
@@ -115776,23 +117990,23 @@ var registerQuerySources = (ast, state) => {
115776
117990
  registerSourceReference(ast.using.source, ast.using.tableName, state);
115777
117991
  }
115778
117992
  };
115779
- var renderColumnDefinition = (dialect, state, columnName, column, tableName, casing) => {
117993
+ var renderColumnDefinition = (dialect, state, columnName, column2, tableName, casing) => {
115780
117994
  const expressionState = { ...state, casing, rowLocalColumns: true };
115781
- if (isArrayDbType(column.metadata.dbType)) {
117995
+ if (isArrayDbType(column2.metadata.dbType)) {
115782
117996
  throw new Error("Unsupported mysql array column options");
115783
117997
  }
115784
117998
  const clauses = [
115785
117999
  quoteColumn(columnName, state, dialect, tableName),
115786
- column.metadata.ddlType === undefined ? renderDbType(dialect, column.metadata.dbType) : renderDbTypeName(column.metadata.ddlType)
118000
+ column2.metadata.ddlType === undefined ? renderDbType(dialect, column2.metadata.dbType) : renderDbTypeName(column2.metadata.ddlType)
115787
118001
  ];
115788
- if (column.metadata.identity) {
118002
+ if (column2.metadata.identity) {
115789
118003
  throw new Error("Unsupported mysql identity column options");
115790
- } else if (column.metadata.generatedValue) {
115791
- clauses.push(`generated always as (${renderDdlExpression(column.metadata.generatedValue, expressionState, dialect)}) stored`);
115792
- } else if (column.metadata.defaultValue) {
115793
- clauses.push(`default ${renderDdlExpression(column.metadata.defaultValue, expressionState, dialect)}`);
118004
+ } else if (column2.metadata.generatedValue) {
118005
+ clauses.push(`generated always as (${renderDdlExpression(column2.metadata.generatedValue, expressionState, dialect)}) stored`);
118006
+ } else if (column2.metadata.defaultValue) {
118007
+ clauses.push(`default ${renderDdlExpression(column2.metadata.defaultValue, expressionState, dialect)}`);
115794
118008
  }
115795
- if (!column.metadata.nullable) {
118009
+ if (!column2.metadata.nullable) {
115796
118010
  clauses.push("not null");
115797
118011
  }
115798
118012
  return clauses.join(" ");
@@ -115802,7 +118016,7 @@ var renderCreateTableSql = (targetSource, state, dialect, ifNotExists) => {
115802
118016
  const table = targetSource.source;
115803
118017
  const tableCasing = casingForTable(table, state);
115804
118018
  const fields2 = table[TypeId7].fields;
115805
- const definitions = Object.entries(fields2).map(([columnName, column]) => renderColumnDefinition(dialect, state, columnName, column, targetSource.tableName, tableCasing));
118019
+ const definitions = Object.entries(fields2).map(([columnName, column2]) => renderColumnDefinition(dialect, state, columnName, column2, targetSource.tableName, tableCasing));
115806
118020
  const options2 = table[OptionsSymbol];
115807
118021
  const tableOptions = Array.isArray(options2) ? options2 : [options2];
115808
118022
  validateOptions(table[TypeId7].name, fields2, tableOptions);
@@ -115815,20 +118029,20 @@ var renderCreateTableSql = (targetSource, state, dialect, ifNotExists) => {
115815
118029
  if (option2.deferrable || option2.initiallyDeferred) {
115816
118030
  throw new Error("Unsupported mysql primary key constraint options");
115817
118031
  }
115818
- definitions.push(`${option2.name ? `constraint ${dialect.quoteIdentifier(applyCategory(tableCasing, "constraints", option2.name))} ` : ""}primary key (${option2.columns.map((column) => quoteColumn(column, state, dialect, targetSource.tableName)).join(", ")})${option2.deferrable ? ` deferrable${option2.initiallyDeferred ? " initially deferred" : ""}` : ""}`);
118032
+ definitions.push(`${option2.name ? `constraint ${dialect.quoteIdentifier(applyCategory(tableCasing, "constraints", option2.name))} ` : ""}primary key (${option2.columns.map((column2) => quoteColumn(column2, state, dialect, targetSource.tableName)).join(", ")})${option2.deferrable ? ` deferrable${option2.initiallyDeferred ? " initially deferred" : ""}` : ""}`);
115819
118033
  break;
115820
118034
  case "unique":
115821
118035
  if (option2.nullsNotDistinct || option2.deferrable || option2.initiallyDeferred) {
115822
118036
  throw new Error("Unsupported mysql unique constraint options");
115823
118037
  }
115824
- definitions.push(`${option2.name ? `constraint ${dialect.quoteIdentifier(applyCategory(tableCasing, "constraints", option2.name))} ` : ""}unique${option2.nullsNotDistinct ? " nulls not distinct" : ""} (${option2.columns.map((column) => quoteColumn(column, state, dialect, targetSource.tableName)).join(", ")})${option2.deferrable ? ` deferrable${option2.initiallyDeferred ? " initially deferred" : ""}` : ""}`);
118038
+ definitions.push(`${option2.name ? `constraint ${dialect.quoteIdentifier(applyCategory(tableCasing, "constraints", option2.name))} ` : ""}unique${option2.nullsNotDistinct ? " nulls not distinct" : ""} (${option2.columns.map((column2) => quoteColumn(column2, state, dialect, targetSource.tableName)).join(", ")})${option2.deferrable ? ` deferrable${option2.initiallyDeferred ? " initially deferred" : ""}` : ""}`);
115825
118039
  break;
115826
118040
  case "foreignKey": {
115827
118041
  if (option2.deferrable || option2.initiallyDeferred) {
115828
118042
  throw new Error("Unsupported mysql foreign key constraint options");
115829
118043
  }
115830
118044
  const reference = typeof option2.references === "function" ? option2.references() : option2.references;
115831
- definitions.push(`${option2.name ? `constraint ${dialect.quoteIdentifier(applyCategory(tableCasing, "constraints", option2.name))} ` : ""}foreign key (${option2.columns.map((column) => quoteColumn(column, state, dialect, targetSource.tableName)).join(", ")}) references ${renderReferenceTable(reference, state, dialect)} (${reference.columns.map((column) => quoteReferenceColumn(column, reference, state, dialect)).join(", ")})${option2.onDelete !== undefined ? ` on delete ${renderReferentialAction(option2.onDelete)}` : ""}${option2.onUpdate !== undefined ? ` on update ${renderReferentialAction(option2.onUpdate)}` : ""}${option2.deferrable ? ` deferrable${option2.initiallyDeferred ? " initially deferred" : ""}` : ""}`);
118045
+ definitions.push(`${option2.name ? `constraint ${dialect.quoteIdentifier(applyCategory(tableCasing, "constraints", option2.name))} ` : ""}foreign key (${option2.columns.map((column2) => quoteColumn(column2, state, dialect, targetSource.tableName)).join(", ")}) references ${renderReferenceTable(reference, state, dialect)} (${reference.columns.map((column2) => quoteReferenceColumn(column2, reference, state, dialect)).join(", ")})${option2.onDelete !== undefined ? ` on delete ${renderReferentialAction(option2.onDelete)}` : ""}${option2.onUpdate !== undefined ? ` on update ${renderReferentialAction(option2.onUpdate)}` : ""}${option2.deferrable ? ` deferrable${option2.initiallyDeferred ? " initially deferred" : ""}` : ""}`);
115832
118046
  break;
115833
118047
  }
115834
118048
  case "check":
@@ -115855,7 +118069,7 @@ var renderCreateIndexSql = (targetSource, ddl, state, dialect) => {
115855
118069
  const maybeIfNotExists = dialect.name === "postgres" && ifNotExists ? " if not exists" : "";
115856
118070
  const table = targetSource.source;
115857
118071
  const tableCasing = casingForTable(table, state);
115858
- return `create${unique3 ? " unique" : ""} index${maybeIfNotExists} ${dialect.quoteIdentifier(applyCategory(tableCasing, "indexes", name))} on ${renderSourceReference(targetSource.source, targetSource.tableName, targetSource.baseTableName, state, dialect)} (${ddl.columns.map((column) => quoteColumn(column, state, dialect, targetSource.tableName)).join(", ")})`;
118072
+ return `create${unique3 ? " unique" : ""} index${maybeIfNotExists} ${dialect.quoteIdentifier(applyCategory(tableCasing, "indexes", name))} on ${renderSourceReference(targetSource.source, targetSource.tableName, targetSource.baseTableName, state, dialect)} (${ddl.columns.map((column2) => quoteColumn(column2, state, dialect, targetSource.tableName)).join(", ")})`;
115859
118073
  };
115860
118074
  var renderDropIndexSql = (targetSource, ddl, state, dialect) => {
115861
118075
  const ifExists = normalizeStatementFlag(ddl.ifExists);
@@ -115895,7 +118109,7 @@ var unsupportedJsonFeature = (dialect, feature) => {
115895
118109
  throw error;
115896
118110
  };
115897
118111
  var extractJsonBase = (node) => node.value ?? node.base ?? node.input ?? node.left ?? node.target;
115898
- var isJsonPathValue2 = (value) => value !== null && typeof value === "object" && (TypeId3 in value);
118112
+ var isJsonPathValue3 = (value) => value !== null && typeof value === "object" && (TypeId3 in value);
115899
118113
  var isOptionalJsonPathNumber = (value) => value === undefined || typeof value === "number" && Number.isFinite(value);
115900
118114
  var isJsonPathSegment = (segment) => {
115901
118115
  if (typeof segment === "string") {
@@ -115934,7 +118148,7 @@ var validateJsonPathSegments = (segments) => {
115934
118148
  };
115935
118149
  var extractJsonPathSegments = (node) => {
115936
118150
  const path2 = node.path ?? node.segments ?? node.keys;
115937
- if (isJsonPathValue2(path2)) {
118151
+ if (isJsonPathValue3(path2)) {
115938
118152
  return validateJsonPathSegments(path2.segments);
115939
118153
  }
115940
118154
  if (Array.isArray(path2)) {
@@ -115959,7 +118173,7 @@ var extractJsonPathSegments = (node) => {
115959
118173
  }
115960
118174
  return [];
115961
118175
  }
115962
- if ("right" in node && isJsonPathValue2(node.right)) {
118176
+ if ("right" in node && isJsonPathValue3(node.right)) {
115963
118177
  return validateJsonPathSegments(node.right.segments);
115964
118178
  }
115965
118179
  return [];
@@ -116092,24 +118306,24 @@ var renderJsonInputExpression = (expression, state, dialect) => {
116092
118306
  }
116093
118307
  return renderJsonSelectSql(renderExpression(expression, state, dialect), expressionDriverContext(expression, state, dialect));
116094
118308
  };
116095
- var encodeArrayValues = (values2, column, state, dialect) => values2.map((value) => {
116096
- if (value === null && column.metadata.nullable) {
118309
+ var encodeArrayValues = (values3, column2, state, dialect) => values3.map((value) => {
118310
+ if (value === null && column2.metadata.nullable) {
116097
118311
  return null;
116098
118312
  }
116099
- const runtimeSchemaAccepts = column.schema !== undefined && Schema10.is(column.schema)(value);
116100
- const normalizedValue = runtimeSchemaAccepts ? value : normalizeDbValue(column.metadata.dbType, value);
116101
- const encodedValue = column.schema === undefined || runtimeSchemaAccepts ? normalizedValue : Schema10.decodeUnknownSync(column.schema)(normalizedValue);
118313
+ const runtimeSchemaAccepts = column2.schema !== undefined && Schema11.is(column2.schema)(value);
118314
+ const normalizedValue = runtimeSchemaAccepts ? value : normalizeDbValue(column2.metadata.dbType, value);
118315
+ const encodedValue = column2.schema === undefined || runtimeSchemaAccepts ? normalizedValue : Schema11.decodeUnknownSync(column2.schema)(normalizedValue);
116102
118316
  return toDriverValue(encodedValue, {
116103
118317
  dialect: dialect.name,
116104
118318
  valueMappings: state.valueMappings,
116105
- dbType: column.metadata.dbType,
116106
- runtimeSchema: column.schema,
116107
- driverValueMapping: column.metadata.driverValueMapping
118319
+ dbType: column2.metadata.dbType,
118320
+ runtimeSchema: column2.schema,
118321
+ driverValueMapping: column2.metadata.driverValueMapping
116108
118322
  });
116109
118323
  });
116110
118324
  var renderPostgresJsonKind = (value) => value[TypeId].dbType.kind === "jsonb" ? "jsonb" : "json";
116111
118325
  var renderJsonOpaquePath = (value, state, dialect) => {
116112
- if (isJsonPathValue2(value)) {
118326
+ if (isJsonPathValue3(value)) {
116113
118327
  const renderSegment = dialect.name === "mysql" ? renderMySqlJsonPathSegment : renderJsonPathSegment;
116114
118328
  return dialect.renderLiteral(renderJsonPathStringLiteral(value.segments, renderSegment), state);
116115
118329
  }
@@ -116260,8 +118474,8 @@ var renderJsonExpression = (expression, ast, state, dialect) => {
116260
118474
  return;
116261
118475
  }
116262
118476
  case "jsonBuildArray": {
116263
- const values2 = ast.values;
116264
- const renderedValues = values2.map((value) => renderJsonInputExpression(value, state, dialect)).join(", ");
118477
+ const values3 = ast.values;
118478
+ const renderedValues = values3.map((value) => renderJsonInputExpression(value, state, dialect)).join(", ");
116265
118479
  if (dialect.name === "postgres") {
116266
118480
  return `${postgresExpressionKind === "jsonb" ? "jsonb" : "json"}_build_array(${renderedValues})`;
116267
118481
  }
@@ -116430,18 +118644,18 @@ var selectionProjections = (selection) => flattenSelection(selection).map(({ pat
116430
118644
  alias: alias2
116431
118645
  }));
116432
118646
  var renderMutationAssignment = (entry, state, dialect, targetTableName) => {
116433
- const column = entry.tableName && dialect.name === "mysql" ? `${dialect.quoteIdentifier(casedTableReferenceName(entry.tableName, state))}.${quoteColumn(entry.columnName, state, dialect, entry.tableName)}` : quoteColumn(entry.columnName, state, dialect, targetTableName);
116434
- return `${column} = ${renderExpression(entry.value, state, dialect)}`;
118647
+ const column2 = entry.tableName && dialect.name === "mysql" ? `${dialect.quoteIdentifier(casedTableReferenceName(entry.tableName, state))}.${quoteColumn(entry.columnName, state, dialect, entry.tableName)}` : quoteColumn(entry.columnName, state, dialect, targetTableName);
118648
+ return `${column2} = ${renderExpression(entry.value, state, dialect)}`;
116435
118649
  };
116436
- var renderJoinSourcesForMutation = (joins, state, dialect) => joins.map((join2) => renderSourceReference(join2.source, join2.tableName, join2.baseTableName, state, dialect)).join(", ");
118650
+ var renderJoinSourcesForMutation = (joins, state, dialect) => joins.map((join3) => renderSourceReference(join3.source, join3.tableName, join3.baseTableName, state, dialect)).join(", ");
116437
118651
  var renderFromSources = (sources, state, dialect) => sources.map((source) => renderSourceReference(source.source, source.tableName, source.baseTableName, state, dialect)).join(", ");
116438
- var renderJoinPredicatesForMutation = (joins, state, dialect) => joins.flatMap((join2) => join2.kind === "cross" || !join2.on ? [] : [renderExpression(join2.on, state, dialect)]);
118652
+ var renderJoinPredicatesForMutation = (joins, state, dialect) => joins.flatMap((join3) => join3.kind === "cross" || !join3.on ? [] : [renderExpression(join3.on, state, dialect)]);
116439
118653
  var renderDeleteTargets = (targets, state, dialect) => targets.map((target) => dialect.quoteIdentifier(casedTableReferenceName(target.tableName, state))).join(", ");
116440
- var renderMysqlMutationLock = (lock2, statement) => {
116441
- if (!lock2) {
118654
+ var renderMysqlMutationLock = (lock3, statement) => {
118655
+ if (!lock3) {
116442
118656
  return "";
116443
118657
  }
116444
- return renderMysqlMutationLockMode(lock2.mode, statement);
118658
+ return renderMysqlMutationLockMode(lock3.mode, statement);
116445
118659
  };
116446
118660
  var renderTransactionClause = (clause, dialect) => {
116447
118661
  switch (clause.kind) {
@@ -116502,12 +118716,12 @@ var renderQueryAst = (ast, state, dialect, options2 = {}) => {
116502
118716
  if (ast.from) {
116503
118717
  clauses.push(`from ${renderSourceReference(ast.from.source, ast.from.tableName, ast.from.baseTableName, state, dialect)}`);
116504
118718
  }
116505
- for (const join2 of ast.joins) {
116506
- if (dialect.name === "mysql" && join2.kind === "full") {
118719
+ for (const join3 of ast.joins) {
118720
+ if (dialect.name === "mysql" && join3.kind === "full") {
116507
118721
  throw new Error("Unsupported mysql full join");
116508
118722
  }
116509
- const source = renderSourceReference(join2.source, join2.tableName, join2.baseTableName, state, dialect);
116510
- clauses.push(join2.kind === "cross" ? `cross join ${source}` : `${join2.kind} join ${source} on ${renderExpression(join2.on, state, dialect)}`);
118723
+ const source = renderSourceReference(join3.source, join3.tableName, join3.baseTableName, state, dialect);
118724
+ clauses.push(join3.kind === "cross" ? `cross join ${source}` : `${join3.kind} join ${source} on ${renderExpression(join3.on, state, dialect)}`);
116511
118725
  }
116512
118726
  if (ast.where.length > 0) {
116513
118727
  clauses.push(`where ${ast.where.map((entry) => renderExpression(entry.predicate, state, dialect)).join(" and ")}`);
@@ -116555,15 +118769,15 @@ var renderQueryAst = (ast, state, dialect, options2 = {}) => {
116555
118769
  const conflict = expectConflictClause(insertAst.conflict);
116556
118770
  sql = `insert into ${target}`;
116557
118771
  if (insertSource?.kind === "values") {
116558
- const columns = insertSource.columns.map((column) => quoteColumn(column, state, dialect, targetSource.tableName)).join(", ");
118772
+ const columns = insertSource.columns.map((column2) => quoteColumn(column2, state, dialect, targetSource.tableName)).join(", ");
116559
118773
  const rows = insertSource.rows.map((row) => `(${row.values.map((entry) => renderExpression(entry.value, targetCasingState, dialect)).join(", ")})`).join(", ");
116560
118774
  sql += ` (${columns}) values ${rows}`;
116561
118775
  } else if (insertSource?.kind === "query") {
116562
- const columns = insertSource.columns.map((column) => quoteColumn(column, state, dialect, targetSource.tableName)).join(", ");
118776
+ const columns = insertSource.columns.map((column2) => quoteColumn(column2, state, dialect, targetSource.tableName)).join(", ");
116563
118777
  const renderedQuery = renderQueryAst(getAst(insertSource.query), state, dialect);
116564
118778
  sql += ` (${columns}) ${renderedQuery.sql}`;
116565
118779
  } else if (insertSource?.kind === "unnest") {
116566
- const columns = insertSource.columns.map((column) => quoteColumn(column, state, dialect, targetSource.tableName)).join(", ");
118780
+ const columns = insertSource.columns.map((column2) => quoteColumn(column2, state, dialect, targetSource.tableName)).join(", ");
116567
118781
  if (dialect.name === "postgres") {
116568
118782
  const table = targetSource.source;
116569
118783
  const fields2 = table[TypeId7].fields;
@@ -116583,9 +118797,9 @@ var renderQueryAst = (ast, state, dialect, options2 = {}) => {
116583
118797
  } else {
116584
118798
  const insertValues = insertAst.values ?? [];
116585
118799
  const columns = insertValues.map((entry) => quoteColumn(entry.columnName, state, dialect, targetSource.tableName)).join(", ");
116586
- const values2 = insertValues.map((entry) => renderExpression(entry.value, targetCasingState, dialect)).join(", ");
118800
+ const values3 = insertValues.map((entry) => renderExpression(entry.value, targetCasingState, dialect)).join(", ");
116587
118801
  if (insertValues.length > 0) {
116588
- sql += ` (${columns}) values (${values2})`;
118802
+ sql += ` (${columns}) values (${values3})`;
116589
118803
  } else {
116590
118804
  sql += " () values ()";
116591
118805
  }
@@ -116594,7 +118808,7 @@ var renderQueryAst = (ast, state, dialect, options2 = {}) => {
116594
118808
  const conflictValueState = { ...targetCasingState, allowExcluded: true };
116595
118809
  const updateValues = (conflict.values ?? []).map((entry) => `${quoteColumn(entry.columnName, state, dialect, targetSource.tableName)} = ${renderExpression(entry.value, conflictValueState, dialect)}`).join(", ");
116596
118810
  if (dialect.name === "postgres") {
116597
- const targetSql = conflict.target?.kind === "constraint" ? ` on conflict on constraint ${dialect.quoteIdentifier(applyCategory(targetCasingState.casing, "constraints", conflict.target.name))}` : conflict.target?.kind === "columns" ? ` on conflict (${conflict.target.columns.map((column) => quoteColumn(column, state, dialect, targetSource.tableName)).join(", ")})${conflict.target.where ? ` where ${renderExpression(conflict.target.where, targetCasingState, dialect)}` : ""}` : " on conflict";
118811
+ const targetSql = conflict.target?.kind === "constraint" ? ` on conflict on constraint ${dialect.quoteIdentifier(applyCategory(targetCasingState.casing, "constraints", conflict.target.name))}` : conflict.target?.kind === "columns" ? ` on conflict (${conflict.target.columns.map((column2) => quoteColumn(column2, state, dialect, targetSource.tableName)).join(", ")})${conflict.target.where ? ` where ${renderExpression(conflict.target.where, targetCasingState, dialect)}` : ""}` : " on conflict";
116598
118812
  sql += targetSql;
116599
118813
  sql += conflict.action === "doNothing" ? " do nothing" : ` do update set ${updateValues}${conflict.where ? ` where ${renderExpression(conflict.where, conflictValueState, dialect)}` : ""}`;
116600
118814
  } else if (conflict.action === "doNothing") {
@@ -116604,13 +118818,13 @@ var renderQueryAst = (ast, state, dialect, options2 = {}) => {
116604
118818
  }
116605
118819
  }
116606
118820
  const hasReturning = Object.keys(insertAst.select).length > 0;
116607
- const returning2 = hasReturning ? renderSelectionList(insertAst.select, state, dialect) : { sql: "", projections: [] };
116608
- if (dialect.name === "mysql" && returning2.sql.length > 0) {
118821
+ const returning3 = hasReturning ? renderSelectionList(insertAst.select, state, dialect) : { sql: "", projections: [] };
118822
+ if (dialect.name === "mysql" && returning3.sql.length > 0) {
116609
118823
  throw new Error("Unsupported mysql returning");
116610
118824
  }
116611
- projections = returning2.projections;
116612
- if (returning2.sql.length > 0) {
116613
- sql += ` returning ${returning2.sql}`;
118825
+ projections = returning3.projections;
118826
+ if (returning3.sql.length > 0) {
118827
+ sql += ` returning ${returning3.sql}`;
116614
118828
  }
116615
118829
  break;
116616
118830
  }
@@ -116624,9 +118838,9 @@ var renderQueryAst = (ast, state, dialect, options2 = {}) => {
116624
118838
  if (dialect.name === "mysql") {
116625
118839
  const modifiers = renderMysqlMutationLock(updateAst.lock, "update");
116626
118840
  const extraSources = renderFromSources(fromSources, state, dialect);
116627
- const joinSources = updateAst.joins.map((join2) => join2.kind === "full" ? (() => {
118841
+ const joinSources = updateAst.joins.map((join3) => join3.kind === "full" ? (() => {
116628
118842
  throw new Error("Unsupported mysql full join");
116629
- })() : join2.kind === "cross" ? `cross join ${renderSourceReference(join2.source, join2.tableName, join2.baseTableName, state, dialect)}` : `${join2.kind} join ${renderSourceReference(join2.source, join2.tableName, join2.baseTableName, state, dialect)} on ${renderExpression(join2.on, state, dialect)}`).join(" ");
118843
+ })() : join3.kind === "cross" ? `cross join ${renderSourceReference(join3.source, join3.tableName, join3.baseTableName, state, dialect)}` : `${join3.kind} join ${renderSourceReference(join3.source, join3.tableName, join3.baseTableName, state, dialect)} on ${renderExpression(join3.on, state, dialect)}`).join(" ");
116630
118844
  const targetList = [
116631
118845
  ...targets.map((entry) => renderSourceReference(entry.source, entry.tableName, entry.baseTableName, state, dialect)),
116632
118846
  ...extraSources.length > 0 ? [extraSources] : []
@@ -116656,13 +118870,13 @@ var renderQueryAst = (ast, state, dialect, options2 = {}) => {
116656
118870
  sql += ` limit ${renderMysqlMutationLimit(updateAst.limit, state, dialect)}`;
116657
118871
  }
116658
118872
  const hasReturning = Object.keys(updateAst.select).length > 0;
116659
- const returning2 = hasReturning ? renderSelectionList(updateAst.select, state, dialect) : { sql: "", projections: [] };
116660
- if (dialect.name === "mysql" && returning2.sql.length > 0) {
118873
+ const returning3 = hasReturning ? renderSelectionList(updateAst.select, state, dialect) : { sql: "", projections: [] };
118874
+ if (dialect.name === "mysql" && returning3.sql.length > 0) {
116661
118875
  throw new Error("Unsupported mysql returning");
116662
118876
  }
116663
- projections = returning2.projections;
116664
- if (returning2.sql.length > 0) {
116665
- sql += ` returning ${returning2.sql}`;
118877
+ projections = returning3.projections;
118878
+ if (returning3.sql.length > 0) {
118879
+ sql += ` returning ${returning3.sql}`;
116666
118880
  }
116667
118881
  break;
116668
118882
  }
@@ -116676,9 +118890,9 @@ var renderQueryAst = (ast, state, dialect, options2 = {}) => {
116676
118890
  const hasJoinedSources = deleteAst.joins.length > 0 || targets.length > 1;
116677
118891
  const targetList = renderDeleteTargets(targets, state, dialect);
116678
118892
  const fromSources = targets.map((entry) => renderSourceReference(entry.source, entry.tableName, entry.baseTableName, state, dialect)).join(", ");
116679
- const joinSources = deleteAst.joins.map((join2) => join2.kind === "full" ? (() => {
118893
+ const joinSources = deleteAst.joins.map((join3) => join3.kind === "full" ? (() => {
116680
118894
  throw new Error("Unsupported mysql full join");
116681
- })() : join2.kind === "cross" ? `cross join ${renderSourceReference(join2.source, join2.tableName, join2.baseTableName, state, dialect)}` : `${join2.kind} join ${renderSourceReference(join2.source, join2.tableName, join2.baseTableName, state, dialect)} on ${renderExpression(join2.on, state, dialect)}`).join(" ");
118895
+ })() : join3.kind === "cross" ? `cross join ${renderSourceReference(join3.source, join3.tableName, join3.baseTableName, state, dialect)}` : `${join3.kind} join ${renderSourceReference(join3.source, join3.tableName, join3.baseTableName, state, dialect)} on ${renderExpression(join3.on, state, dialect)}`).join(" ");
116682
118896
  sql = hasJoinedSources ? `delete${modifiers} ${targetList} from ${fromSources}${joinSources.length > 0 ? ` ${joinSources}` : ""}` : `delete${modifiers} from ${fromSources}`;
116683
118897
  } else {
116684
118898
  sql = `delete from ${target}`;
@@ -116700,22 +118914,22 @@ var renderQueryAst = (ast, state, dialect, options2 = {}) => {
116700
118914
  sql += ` limit ${renderMysqlMutationLimit(deleteAst.limit, state, dialect)}`;
116701
118915
  }
116702
118916
  const hasReturning = Object.keys(deleteAst.select).length > 0;
116703
- const returning2 = hasReturning ? renderSelectionList(deleteAst.select, state, dialect) : { sql: "", projections: [] };
116704
- if (dialect.name === "mysql" && returning2.sql.length > 0) {
118917
+ const returning3 = hasReturning ? renderSelectionList(deleteAst.select, state, dialect) : { sql: "", projections: [] };
118918
+ if (dialect.name === "mysql" && returning3.sql.length > 0) {
116705
118919
  throw new Error("Unsupported mysql returning");
116706
118920
  }
116707
- projections = returning2.projections;
116708
- if (returning2.sql.length > 0) {
116709
- sql += ` returning ${returning2.sql}`;
118921
+ projections = returning3.projections;
118922
+ if (returning3.sql.length > 0) {
118923
+ sql += ` returning ${returning3.sql}`;
116710
118924
  }
116711
118925
  break;
116712
118926
  }
116713
118927
  case "truncate": {
116714
118928
  const truncateAst = ast;
116715
- const truncate = expectTruncateClause(truncateAst.truncate);
118929
+ const truncate2 = expectTruncateClause(truncateAst.truncate);
116716
118930
  const targetSource = truncateAst.target;
116717
- const restartIdentity = truncate.restartIdentity;
116718
- const cascade = truncate.cascade;
118931
+ const restartIdentity = truncate2.restartIdentity;
118932
+ const cascade = truncate2.cascade;
116719
118933
  if (dialect.name === "mysql" && (restartIdentity || cascade)) {
116720
118934
  throw new Error("Unsupported mysql truncate options");
116721
118935
  }
@@ -116735,25 +118949,25 @@ var renderQueryAst = (ast, state, dialect, options2 = {}) => {
116735
118949
  const mergeAst = ast;
116736
118950
  const targetSource = mergeAst.target;
116737
118951
  const usingSource = mergeAst.using;
116738
- const merge2 = mergeAst.merge;
116739
- sql = `merge into ${renderSourceReference(targetSource.source, targetSource.tableName, targetSource.baseTableName, state, dialect)} using ${renderSourceReference(usingSource.source, usingSource.tableName, usingSource.baseTableName, state, dialect)} on ${renderExpression(merge2.on, state, dialect)}`;
116740
- if (merge2.whenMatched) {
118952
+ const merge3 = mergeAst.merge;
118953
+ sql = `merge into ${renderSourceReference(targetSource.source, targetSource.tableName, targetSource.baseTableName, state, dialect)} using ${renderSourceReference(usingSource.source, usingSource.tableName, usingSource.baseTableName, state, dialect)} on ${renderExpression(merge3.on, state, dialect)}`;
118954
+ if (merge3.whenMatched) {
116741
118955
  sql += " when matched";
116742
- if (merge2.whenMatched.predicate) {
116743
- sql += ` and ${renderExpression(merge2.whenMatched.predicate, state, dialect)}`;
118956
+ if (merge3.whenMatched.predicate) {
118957
+ sql += ` and ${renderExpression(merge3.whenMatched.predicate, state, dialect)}`;
116744
118958
  }
116745
- if (merge2.whenMatched.kind === "delete") {
118959
+ if (merge3.whenMatched.kind === "delete") {
116746
118960
  sql += " then delete";
116747
118961
  } else {
116748
- sql += ` then update set ${merge2.whenMatched.values.map((entry) => `${dialect.quoteIdentifier(entry.columnName)} = ${renderExpression(entry.value, state, dialect)}`).join(", ")}`;
118962
+ sql += ` then update set ${merge3.whenMatched.values.map((entry) => `${dialect.quoteIdentifier(entry.columnName)} = ${renderExpression(entry.value, state, dialect)}`).join(", ")}`;
116749
118963
  }
116750
118964
  }
116751
- if (merge2.whenNotMatched) {
118965
+ if (merge3.whenNotMatched) {
116752
118966
  sql += " when not matched";
116753
- if (merge2.whenNotMatched.predicate) {
116754
- sql += ` and ${renderExpression(merge2.whenNotMatched.predicate, state, dialect)}`;
118967
+ if (merge3.whenNotMatched.predicate) {
118968
+ sql += ` and ${renderExpression(merge3.whenNotMatched.predicate, state, dialect)}`;
116755
118969
  }
116756
- sql += ` then insert (${merge2.whenNotMatched.values.map((entry) => dialect.quoteIdentifier(entry.columnName)).join(", ")}) values (${merge2.whenNotMatched.values.map((entry) => renderExpression(entry.value, state, dialect)).join(", ")})`;
118970
+ sql += ` then insert (${merge3.whenNotMatched.values.map((entry) => dialect.quoteIdentifier(entry.columnName)).join(", ")}) values (${merge3.whenNotMatched.values.map((entry) => renderExpression(entry.value, state, dialect)).join(", ")})`;
116757
118971
  }
116758
118972
  break;
116759
118973
  }
@@ -116849,16 +119063,16 @@ var renderSourceReference = (source, tableName, baseTableName, state, dialect) =
116849
119063
  return `(${renderQueryAst(getAst(derived.plan), nestedRenderState(state), dialect).sql}) as ${dialect.quoteIdentifier(derived.name)}`;
116850
119064
  }
116851
119065
  if (typeof source === "object" && source !== null && "kind" in source && source.kind === "lateral") {
116852
- const lateral = source;
116853
- return `lateral (${renderQueryAst(getAst(lateral.plan), nestedRenderState(state), dialect).sql}) as ${dialect.quoteIdentifier(lateral.name)}`;
119066
+ const lateral2 = source;
119067
+ return `lateral (${renderQueryAst(getAst(lateral2.plan), nestedRenderState(state), dialect).sql}) as ${dialect.quoteIdentifier(lateral2.name)}`;
116854
119068
  }
116855
119069
  if (typeof source === "object" && source !== null && source.kind === "values") {
116856
- const values2 = source;
116857
- return renderSelectRows(values2.rows, Object.keys(values2.columns));
119070
+ const values3 = source;
119071
+ return renderSelectRows(values3.rows, Object.keys(values3.columns));
116858
119072
  }
116859
119073
  if (typeof source === "object" && source !== null && source.kind === "unnest") {
116860
- const unnest2 = source;
116861
- return renderUnnestRows(unnest2.arrays, Object.keys(unnest2.columns));
119074
+ const unnest3 = source;
119075
+ return renderUnnestRows(unnest3.arrays, Object.keys(unnest3.columns));
116862
119076
  }
116863
119077
  if (typeof source === "object" && source !== null && source.kind === "tableFunction") {
116864
119078
  const tableFunction = source;
@@ -116920,6 +119134,8 @@ var renderExpression = (expression, state, dialect) => {
116920
119134
  return `cast(${renderExpression(expectValueExpression("cast", ast.value), state, dialect)} as ${renderCastType(dialect, ast.target)})`;
116921
119135
  case "function":
116922
119136
  return renderFunctionCall(ast.name, ast.args, state, dialect);
119137
+ case "customSql":
119138
+ return renderCustomSql(ast, state, dialect, renderExpression);
116923
119139
  case "eq":
116924
119140
  return renderBinaryExpression("eq", "=", ast.left, ast.right, state, dialect);
116925
119141
  case "neq":
@@ -116932,6 +119148,16 @@ var renderExpression = (expression, state, dialect) => {
116932
119148
  return renderBinaryExpression("gt", ">", ast.left, ast.right, state, dialect);
116933
119149
  case "gte":
116934
119150
  return renderBinaryExpression("gte", ">=", ast.left, ast.right, state, dialect);
119151
+ case "add":
119152
+ return renderBinaryExpression("add", "+", ast.left, ast.right, state, dialect);
119153
+ case "subtract":
119154
+ return renderBinaryExpression("subtract", "-", ast.left, ast.right, state, dialect);
119155
+ case "multiply":
119156
+ return renderBinaryExpression("multiply", "*", ast.left, ast.right, state, dialect);
119157
+ case "divide":
119158
+ return renderBinaryExpression("divide", "/", ast.left, ast.right, state, dialect);
119159
+ case "modulo":
119160
+ return renderBinaryExpression("modulo", "%", ast.left, ast.right, state, dialect);
116935
119161
  case "like":
116936
119162
  return renderBinaryExpression("like", "like", ast.left, ast.right, state, dialect);
116937
119163
  case "ilike": {
@@ -117010,6 +119236,16 @@ var renderExpression = (expression, state, dialect) => {
117010
119236
  return `lower(${renderExpression(expectValueExpression("lower", ast.value), state, dialect)})`;
117011
119237
  case "count":
117012
119238
  return `count(${renderExpression(expectValueExpression("count", ast.value), state, dialect)})`;
119239
+ case "sum":
119240
+ return `sum(${renderExpression(expectValueExpression("sum", ast.value), state, dialect)})`;
119241
+ case "avg":
119242
+ return `avg(${renderExpression(expectValueExpression("avg", ast.value), state, dialect)})`;
119243
+ case "abs":
119244
+ return `abs(${renderExpression(expectValueExpression("abs", ast.value), state, dialect)})`;
119245
+ case "round":
119246
+ return `round(${renderExpression(expectValueExpression("round", ast.value), state, dialect)})`;
119247
+ case "negate":
119248
+ return `(-${renderExpression(expectValueExpression("negate", ast.value), state, dialect)})`;
117013
119249
  case "max":
117014
119250
  return `max(${renderExpression(expectValueExpression("max", ast.value), state, dialect)})`;
117015
119251
  case "min":
@@ -117042,24 +119278,48 @@ var renderExpression = (expression, state, dialect) => {
117042
119278
  return `(${renderExpression(expectValueExpression("compareAll", ast.left), state, dialect)} ${renderComparisonOperator(ast.operator)} all (${renderSubqueryExpressionPlan(ast.plan, state, dialect)}))`;
117043
119279
  case "window": {
117044
119280
  const partitionBy = ast.partitionBy;
117045
- const orderBy2 = ast.orderBy;
117046
- const clauses = [];
117047
- if (partitionBy.length > 0) {
117048
- clauses.push(`partition by ${partitionBy.map((value) => renderExpression(value, state, dialect)).join(", ")}`);
117049
- }
117050
- if (orderBy2.length > 0) {
117051
- clauses.push(`order by ${orderBy2.map((entry) => `${renderExpression(entry.value, state, dialect)} ${entry.direction}`).join(", ")}`);
117052
- }
117053
- const specification = clauses.join(" ");
119281
+ const orderBy3 = ast.orderBy;
119282
+ const renderSpecification = () => {
119283
+ const clauses = [];
119284
+ if (partitionBy.length > 0) {
119285
+ clauses.push(`partition by ${partitionBy.map((value) => renderExpression(value, state, dialect)).join(", ")}`);
119286
+ }
119287
+ if (orderBy3.length > 0) {
119288
+ clauses.push(`order by ${orderBy3.map((entry) => `${renderExpression(entry.value, state, dialect)} ${entry.direction}`).join(", ")}`);
119289
+ }
119290
+ if (ast.frame !== undefined) {
119291
+ clauses.push(renderWindowFrame(ast.frame));
119292
+ }
119293
+ return clauses.join(" ");
119294
+ };
117054
119295
  switch (ast.function) {
117055
119296
  case "rowNumber":
117056
- return `row_number() over (${specification})`;
119297
+ return `row_number() over (${renderSpecification()})`;
117057
119298
  case "rank":
117058
- return `rank() over (${specification})`;
119299
+ return `rank() over (${renderSpecification()})`;
117059
119300
  case "denseRank":
117060
- return `dense_rank() over (${specification})`;
119301
+ return `dense_rank() over (${renderSpecification()})`;
117061
119302
  case "over":
117062
- return `${renderExpression(ast.value, state, dialect)} over (${specification})`;
119303
+ return `${renderExpression(ast.value, state, dialect)} over (${renderSpecification()})`;
119304
+ case "lag":
119305
+ case "lead": {
119306
+ const args = [renderExpression(ast.value, state, dialect)];
119307
+ if (ast.offset !== undefined) {
119308
+ const offsetAst = ast.offset[TypeId2];
119309
+ if (offsetAst.kind !== "literal" || typeof offsetAst.value !== "number" || !Number.isSafeInteger(offsetAst.value) || offsetAst.value < 0) {
119310
+ throw new Error(`${ast.function} offset must be a non-negative integer literal in MySQL`);
119311
+ }
119312
+ args.push(String(offsetAst.value));
119313
+ }
119314
+ if (ast.defaultValue !== undefined) {
119315
+ args.push(renderExpression(ast.defaultValue, state, dialect));
119316
+ }
119317
+ return `${ast.function}(${args.join(", ")}) over (${renderSpecification()})`;
119318
+ }
119319
+ case "firstValue":
119320
+ return `first_value(${renderExpression(ast.value, state, dialect)}) over (${renderSpecification()})`;
119321
+ case "lastValue":
119322
+ return `last_value(${renderExpression(ast.value, state, dialect)}) over (${renderSpecification()})`;
117063
119323
  }
117064
119324
  break;
117065
119325
  }
@@ -117068,7 +119328,7 @@ var renderExpression = (expression, state, dialect) => {
117068
119328
  };
117069
119329
 
117070
119330
  // src/internal/dialect-renderers/postgres.ts
117071
- import * as Schema11 from "effect/Schema";
119331
+ import * as Schema12 from "effect/Schema";
117072
119332
  var renderDbType2 = (dialect, dbType) => {
117073
119333
  return renderDbTypeName(renderPortableDatatypeDdlType(dialect.name, dbType.kind) ?? dbType.kind);
117074
119334
  };
@@ -117162,8 +119422,8 @@ var registerQuerySources2 = (ast, state) => {
117162
119422
  for (const source of ast.fromSources ?? []) {
117163
119423
  registerSourceReference2(source.source, source.tableName, state);
117164
119424
  }
117165
- for (const join2 of ast.joins) {
117166
- registerSourceReference2(join2.source, join2.tableName, state);
119425
+ for (const join3 of ast.joins) {
119426
+ registerSourceReference2(join3.source, join3.tableName, state);
117167
119427
  }
117168
119428
  if (ast.into !== undefined) {
117169
119429
  registerSourceReference2(ast.into.source, ast.into.tableName, state);
@@ -117218,26 +119478,26 @@ var renderDdlExpression2 = (expression, state, dialect) => {
117218
119478
  renderLiteral: renderPostgresDdlLiteral
117219
119479
  });
117220
119480
  };
117221
- var renderColumnDefinition2 = (dialect, state, columnName, column, tableName, casing) => {
119481
+ var renderColumnDefinition2 = (dialect, state, columnName, column2, tableName, casing) => {
117222
119482
  const expressionState = { ...state, casing, rowLocalColumns: true };
117223
- if (dialect.name !== "postgres" && isArrayDbType2(column.metadata.dbType)) {
119483
+ if (dialect.name !== "postgres" && isArrayDbType2(column2.metadata.dbType)) {
117224
119484
  throw new Error(`Unsupported ${dialect.name} array column options`);
117225
119485
  }
117226
119486
  const clauses = [
117227
119487
  quoteColumn2(columnName, state, dialect, tableName),
117228
- column.metadata.ddlType === undefined ? renderDbType2(dialect, column.metadata.dbType) : renderDbTypeName(column.metadata.ddlType)
119488
+ column2.metadata.ddlType === undefined ? renderDbType2(dialect, column2.metadata.dbType) : renderDbTypeName(column2.metadata.ddlType)
117229
119489
  ];
117230
- if (column.metadata.identity) {
119490
+ if (column2.metadata.identity) {
117231
119491
  if (dialect.name !== "postgres") {
117232
119492
  throw new Error(`Unsupported ${dialect.name} identity column options`);
117233
119493
  }
117234
- clauses.push(`generated ${column.metadata.identity.generation === "byDefault" ? "by default" : "always"} as identity`);
117235
- } else if (column.metadata.generatedValue) {
117236
- clauses.push(`generated always as (${renderDdlExpression2(column.metadata.generatedValue, expressionState, dialect)}) stored`);
117237
- } else if (column.metadata.defaultValue) {
117238
- clauses.push(`default ${renderDdlExpression2(column.metadata.defaultValue, expressionState, dialect)}`);
119494
+ clauses.push(`generated ${column2.metadata.identity.generation === "byDefault" ? "by default" : "always"} as identity`);
119495
+ } else if (column2.metadata.generatedValue) {
119496
+ clauses.push(`generated always as (${renderDdlExpression2(column2.metadata.generatedValue, expressionState, dialect)}) stored`);
119497
+ } else if (column2.metadata.defaultValue) {
119498
+ clauses.push(`default ${renderDdlExpression2(column2.metadata.defaultValue, expressionState, dialect)}`);
117239
119499
  }
117240
- if (!column.metadata.nullable) {
119500
+ if (!column2.metadata.nullable) {
117241
119501
  clauses.push("not null");
117242
119502
  }
117243
119503
  return clauses.join(" ");
@@ -117250,7 +119510,7 @@ var renderCreateTableSql2 = (targetSource, state, dialect, ifNotExists) => {
117250
119510
  const table = targetSource.source;
117251
119511
  const tableCasing = casingForTable2(table, state);
117252
119512
  const fields2 = table[TypeId7].fields;
117253
- const definitions = Object.entries(fields2).map(([columnName, column]) => renderColumnDefinition2(dialect, state, columnName, column, targetSource.tableName, tableCasing));
119513
+ const definitions = Object.entries(fields2).map(([columnName, column2]) => renderColumnDefinition2(dialect, state, columnName, column2, targetSource.tableName, tableCasing));
117254
119514
  const options2 = table[OptionsSymbol];
117255
119515
  const tableOptions = Array.isArray(options2) ? options2 : [options2];
117256
119516
  validateOptions(table[TypeId7].name, fields2, tableOptions);
@@ -117263,20 +119523,20 @@ var renderCreateTableSql2 = (targetSource, state, dialect, ifNotExists) => {
117263
119523
  if (dialect.name !== "postgres" && (option2.deferrable || option2.initiallyDeferred)) {
117264
119524
  throw new Error(`Unsupported ${dialect.name} primary key constraint options`);
117265
119525
  }
117266
- definitions.push(`${option2.name ? `constraint ${dialect.quoteIdentifier(applyCategory(tableCasing, "constraints", option2.name))} ` : ""}primary key (${option2.columns.map((column) => quoteColumn2(column, state, dialect, targetSource.tableName)).join(", ")})${option2.deferrable ? ` deferrable${option2.initiallyDeferred ? " initially deferred" : ""}` : ""}`);
119526
+ definitions.push(`${option2.name ? `constraint ${dialect.quoteIdentifier(applyCategory(tableCasing, "constraints", option2.name))} ` : ""}primary key (${option2.columns.map((column2) => quoteColumn2(column2, state, dialect, targetSource.tableName)).join(", ")})${option2.deferrable ? ` deferrable${option2.initiallyDeferred ? " initially deferred" : ""}` : ""}`);
117267
119527
  break;
117268
119528
  case "unique":
117269
119529
  if (dialect.name !== "postgres" && (option2.nullsNotDistinct || option2.deferrable || option2.initiallyDeferred)) {
117270
119530
  throw new Error(`Unsupported ${dialect.name} unique constraint options`);
117271
119531
  }
117272
- definitions.push(`${option2.name ? `constraint ${dialect.quoteIdentifier(applyCategory(tableCasing, "constraints", option2.name))} ` : ""}unique${option2.nullsNotDistinct ? " nulls not distinct" : ""} (${option2.columns.map((column) => quoteColumn2(column, state, dialect, targetSource.tableName)).join(", ")})${option2.deferrable ? ` deferrable${option2.initiallyDeferred ? " initially deferred" : ""}` : ""}`);
119532
+ definitions.push(`${option2.name ? `constraint ${dialect.quoteIdentifier(applyCategory(tableCasing, "constraints", option2.name))} ` : ""}unique${option2.nullsNotDistinct ? " nulls not distinct" : ""} (${option2.columns.map((column2) => quoteColumn2(column2, state, dialect, targetSource.tableName)).join(", ")})${option2.deferrable ? ` deferrable${option2.initiallyDeferred ? " initially deferred" : ""}` : ""}`);
117273
119533
  break;
117274
119534
  case "foreignKey": {
117275
119535
  if (dialect.name !== "postgres" && (option2.deferrable || option2.initiallyDeferred)) {
117276
119536
  throw new Error(`Unsupported ${dialect.name} foreign key constraint options`);
117277
119537
  }
117278
119538
  const reference = typeof option2.references === "function" ? option2.references() : option2.references;
117279
- definitions.push(`${option2.name ? `constraint ${dialect.quoteIdentifier(applyCategory(tableCasing, "constraints", option2.name))} ` : ""}foreign key (${option2.columns.map((column) => quoteColumn2(column, state, dialect, targetSource.tableName)).join(", ")}) references ${renderReferenceTable2(reference, state, dialect)} (${reference.columns.map((column) => quoteReferenceColumn2(column, reference, state, dialect)).join(", ")})${option2.onDelete !== undefined ? ` on delete ${renderReferentialAction(option2.onDelete)}` : ""}${option2.onUpdate !== undefined ? ` on update ${renderReferentialAction(option2.onUpdate)}` : ""}${option2.deferrable ? ` deferrable${option2.initiallyDeferred ? " initially deferred" : ""}` : ""}`);
119539
+ definitions.push(`${option2.name ? `constraint ${dialect.quoteIdentifier(applyCategory(tableCasing, "constraints", option2.name))} ` : ""}foreign key (${option2.columns.map((column2) => quoteColumn2(column2, state, dialect, targetSource.tableName)).join(", ")}) references ${renderReferenceTable2(reference, state, dialect)} (${reference.columns.map((column2) => quoteReferenceColumn2(column2, reference, state, dialect)).join(", ")})${option2.onDelete !== undefined ? ` on delete ${renderReferentialAction(option2.onDelete)}` : ""}${option2.onUpdate !== undefined ? ` on update ${renderReferentialAction(option2.onUpdate)}` : ""}${option2.deferrable ? ` deferrable${option2.initiallyDeferred ? " initially deferred" : ""}` : ""}`);
117280
119540
  break;
117281
119541
  }
117282
119542
  case "check":
@@ -117303,7 +119563,7 @@ var renderCreateIndexSql2 = (targetSource, ddl, state, dialect) => {
117303
119563
  const maybeIfNotExists = dialect.name === "postgres" && ifNotExists ? " if not exists" : "";
117304
119564
  const table = targetSource.source;
117305
119565
  const tableCasing = casingForTable2(table, state);
117306
- return `create${unique3 ? " unique" : ""} index${maybeIfNotExists} ${dialect.quoteIdentifier(applyCategory(tableCasing, "indexes", name))} on ${renderSourceReference2(targetSource.source, targetSource.tableName, targetSource.baseTableName, state, dialect)} (${ddl.columns.map((column) => quoteColumn2(column, state, dialect, targetSource.tableName)).join(", ")})`;
119566
+ return `create${unique3 ? " unique" : ""} index${maybeIfNotExists} ${dialect.quoteIdentifier(applyCategory(tableCasing, "indexes", name))} on ${renderSourceReference2(targetSource.source, targetSource.tableName, targetSource.baseTableName, state, dialect)} (${ddl.columns.map((column2) => quoteColumn2(column2, state, dialect, targetSource.tableName)).join(", ")})`;
117307
119567
  };
117308
119568
  var renderDropIndexSql2 = (targetSource, ddl, state, dialect) => {
117309
119569
  const ifExists = normalizeStatementFlag(ddl.ifExists);
@@ -117342,6 +119602,15 @@ var renderBinaryExpression2 = (functionName, operator, left, right, state, diale
117342
119602
  const [leftExpression, rightExpression] = expectBinaryExpressions2(functionName, left, right);
117343
119603
  return `(${renderExpression2(leftExpression, state, dialect)} ${operator} ${renderExpression2(rightExpression, state, dialect)})`;
117344
119604
  };
119605
+ var renderNumericExpression = (expression, state, dialect) => {
119606
+ const rendered = renderExpression2(expression, state, dialect);
119607
+ const ast = expression[TypeId2];
119608
+ return dialect.name === "postgres" && ast.kind === "literal" ? `cast(${rendered} as ${renderCastType2(dialect, expression[TypeId].dbType)})` : rendered;
119609
+ };
119610
+ var renderNumericBinaryExpression = (functionName, operator, left, right, state, dialect) => {
119611
+ const [leftExpression, rightExpression] = expectBinaryExpressions2(functionName, left, right);
119612
+ return `(${renderNumericExpression(leftExpression, state, dialect)} ${operator} ${renderNumericExpression(rightExpression, state, dialect)})`;
119613
+ };
117345
119614
  var postgresRangeSubtypeByKind = {
117346
119615
  int4range: "int4",
117347
119616
  int8range: "int8",
@@ -117382,7 +119651,7 @@ var unsupportedJsonFeature2 = (dialect, feature) => {
117382
119651
  throw error;
117383
119652
  };
117384
119653
  var extractJsonBase2 = (node) => node.value ?? node.base ?? node.input ?? node.left ?? node.target;
117385
- var isJsonPathValue3 = (value) => value !== null && typeof value === "object" && (TypeId3 in value);
119654
+ var isJsonPathValue4 = (value) => value !== null && typeof value === "object" && (TypeId3 in value);
117386
119655
  var isOptionalJsonPathNumber2 = (value) => value === undefined || typeof value === "number" && Number.isFinite(value);
117387
119656
  var isJsonPathSegment2 = (segment) => {
117388
119657
  if (typeof segment === "string") {
@@ -117421,7 +119690,7 @@ var validateJsonPathSegments2 = (segments) => {
117421
119690
  };
117422
119691
  var extractJsonPathSegments2 = (node) => {
117423
119692
  const path2 = node.path ?? node.segments ?? node.keys;
117424
- if (isJsonPathValue3(path2)) {
119693
+ if (isJsonPathValue4(path2)) {
117425
119694
  return validateJsonPathSegments2(path2.segments);
117426
119695
  }
117427
119696
  if (Array.isArray(path2)) {
@@ -117446,7 +119715,7 @@ var extractJsonPathSegments2 = (node) => {
117446
119715
  }
117447
119716
  return [];
117448
119717
  }
117449
- if ("right" in node && isJsonPathValue3(node.right)) {
119718
+ if ("right" in node && isJsonPathValue4(node.right)) {
117450
119719
  return validateJsonPathSegments2(node.right.segments);
117451
119720
  }
117452
119721
  return [];
@@ -117530,24 +119799,24 @@ var expressionDriverContext2 = (expression, state, dialect) => ({
117530
119799
  driverValueMapping: expression[TypeId].driverValueMapping
117531
119800
  });
117532
119801
  var renderJsonInputExpression2 = (expression, state, dialect) => renderJsonSelectSql(renderExpression2(expression, state, dialect), expressionDriverContext2(expression, state, dialect));
117533
- var encodeArrayValues2 = (values2, column, state, dialect) => values2.map((value) => {
117534
- if (value === null && column.metadata.nullable) {
119802
+ var encodeArrayValues2 = (values3, column2, state, dialect) => values3.map((value) => {
119803
+ if (value === null && column2.metadata.nullable) {
117535
119804
  return null;
117536
119805
  }
117537
- const runtimeSchemaAccepts = column.schema !== undefined && Schema11.is(column.schema)(value);
117538
- const normalizedValue = runtimeSchemaAccepts ? value : normalizeDbValue(column.metadata.dbType, value);
117539
- const encodedValue = column.schema === undefined || runtimeSchemaAccepts ? normalizedValue : Schema11.decodeUnknownSync(column.schema)(normalizedValue);
119806
+ const runtimeSchemaAccepts = column2.schema !== undefined && Schema12.is(column2.schema)(value);
119807
+ const normalizedValue = runtimeSchemaAccepts ? value : normalizeDbValue(column2.metadata.dbType, value);
119808
+ const encodedValue = column2.schema === undefined || runtimeSchemaAccepts ? normalizedValue : Schema12.decodeUnknownSync(column2.schema)(normalizedValue);
117540
119809
  return toDriverValue(encodedValue, {
117541
119810
  dialect: dialect.name,
117542
119811
  valueMappings: state.valueMappings,
117543
- dbType: column.metadata.dbType,
117544
- runtimeSchema: column.schema,
117545
- driverValueMapping: column.metadata.driverValueMapping
119812
+ dbType: column2.metadata.dbType,
119813
+ runtimeSchema: column2.schema,
119814
+ driverValueMapping: column2.metadata.driverValueMapping
117546
119815
  });
117547
119816
  });
117548
119817
  var renderPostgresJsonKind2 = (value) => value[TypeId].dbType.kind === "jsonb" ? "jsonb" : "json";
117549
119818
  var renderJsonOpaquePath2 = (value, state, dialect) => {
117550
- if (isJsonPathValue3(value)) {
119819
+ if (isJsonPathValue4(value)) {
117551
119820
  return dialect.renderLiteral(renderJsonPathStringLiteral2(value.segments), state);
117552
119821
  }
117553
119822
  if (typeof value === "string") {
@@ -117696,8 +119965,8 @@ var renderJsonExpression2 = (expression, ast, state, dialect) => {
117696
119965
  return;
117697
119966
  }
117698
119967
  case "jsonBuildArray": {
117699
- const values2 = ast.values;
117700
- const renderedValues = values2.map((value) => renderJsonInputExpression2(value, state, dialect)).join(", ");
119968
+ const values3 = ast.values;
119969
+ const renderedValues = values3.map((value) => renderJsonInputExpression2(value, state, dialect)).join(", ");
117701
119970
  if (dialect.name === "postgres") {
117702
119971
  return `${postgresExpressionKind === "jsonb" ? "jsonb" : "json"}_build_array(${renderedValues})`;
117703
119972
  }
@@ -117856,18 +120125,18 @@ var selectionProjections2 = (selection) => flattenSelection(selection).map(({ pa
117856
120125
  alias: alias2
117857
120126
  }));
117858
120127
  var renderMutationAssignment2 = (entry, state, dialect, targetTableName) => {
117859
- const column = entry.tableName && dialect.name === "mysql" ? `${dialect.quoteIdentifier(casedTableReferenceName2(entry.tableName, state))}.${quoteColumn2(entry.columnName, state, dialect, entry.tableName)}` : quoteColumn2(entry.columnName, state, dialect, targetTableName);
117860
- return `${column} = ${renderExpression2(entry.value, state, dialect)}`;
120128
+ const column2 = entry.tableName && dialect.name === "mysql" ? `${dialect.quoteIdentifier(casedTableReferenceName2(entry.tableName, state))}.${quoteColumn2(entry.columnName, state, dialect, entry.tableName)}` : quoteColumn2(entry.columnName, state, dialect, targetTableName);
120129
+ return `${column2} = ${renderExpression2(entry.value, state, dialect)}`;
117861
120130
  };
117862
- var renderJoinSourcesForMutation2 = (joins, state, dialect) => joins.map((join2) => renderSourceReference2(join2.source, join2.tableName, join2.baseTableName, state, dialect)).join(", ");
120131
+ var renderJoinSourcesForMutation2 = (joins, state, dialect) => joins.map((join3) => renderSourceReference2(join3.source, join3.tableName, join3.baseTableName, state, dialect)).join(", ");
117863
120132
  var renderFromSources2 = (sources, state, dialect) => sources.map((source) => renderSourceReference2(source.source, source.tableName, source.baseTableName, state, dialect)).join(", ");
117864
- var renderJoinPredicatesForMutation2 = (joins, state, dialect) => joins.flatMap((join2) => join2.kind === "cross" || !join2.on ? [] : [renderExpression2(join2.on, state, dialect)]);
120133
+ var renderJoinPredicatesForMutation2 = (joins, state, dialect) => joins.flatMap((join3) => join3.kind === "cross" || !join3.on ? [] : [renderExpression2(join3.on, state, dialect)]);
117865
120134
  var renderDeleteTargets2 = (targets, dialect) => targets.map((target) => dialect.quoteIdentifier(target.tableName)).join(", ");
117866
- var renderMysqlMutationLock2 = (lock2, statement) => {
117867
- if (!lock2) {
120135
+ var renderMysqlMutationLock2 = (lock3, statement) => {
120136
+ if (!lock3) {
117868
120137
  return "";
117869
120138
  }
117870
- switch (lock2.mode) {
120139
+ switch (lock3.mode) {
117871
120140
  case "lowPriority":
117872
120141
  return " low_priority";
117873
120142
  case "ignore":
@@ -117927,12 +120196,12 @@ var assertSupportedMutationReturning = (dialect, selection) => {
117927
120196
  throw new Error("Unsupported standard returning");
117928
120197
  }
117929
120198
  };
117930
- var validateDistinctOnOrdering = (distinctOn2, orderBy2) => {
117931
- if (distinctOn2 === undefined || distinctOn2.length === 0 || orderBy2.length === 0) {
120199
+ var validateDistinctOnOrdering = (distinctOn3, orderBy3) => {
120200
+ if (distinctOn3 === undefined || distinctOn3.length === 0 || orderBy3.length === 0) {
117932
120201
  return;
117933
120202
  }
117934
- const remainingDistinctKeys = new Set(distinctOn2.map(groupingKeyOfExpression));
117935
- for (const order of orderBy2) {
120203
+ const remainingDistinctKeys = new Set(distinctOn3.map(groupingKeyOfExpression));
120204
+ for (const order of orderBy3) {
117936
120205
  const key2 = groupingKeyOfExpression(order.value);
117937
120206
  if (remainingDistinctKeys.has(key2)) {
117938
120207
  remainingDistinctKeys.delete(key2);
@@ -117960,12 +120229,12 @@ var renderQueryAst2 = (ast, state, dialect, options2 = {}) => {
117960
120229
  if (ast.from) {
117961
120230
  clauses.push(`from ${renderSourceReference2(ast.from.source, ast.from.tableName, ast.from.baseTableName, state, dialect)}`);
117962
120231
  }
117963
- for (const join2 of ast.joins) {
117964
- if (dialect.name === "standard" && join2.kind === "full") {
120232
+ for (const join3 of ast.joins) {
120233
+ if (dialect.name === "standard" && join3.kind === "full") {
117965
120234
  throw new Error("Unsupported standard full join");
117966
120235
  }
117967
- const source = renderSourceReference2(join2.source, join2.tableName, join2.baseTableName, state, dialect);
117968
- clauses.push(join2.kind === "cross" ? `cross join ${source}` : `${join2.kind} join ${source} on ${renderExpression2(join2.on, state, dialect)}`);
120236
+ const source = renderSourceReference2(join3.source, join3.tableName, join3.baseTableName, state, dialect);
120237
+ clauses.push(join3.kind === "cross" ? `cross join ${source}` : `${join3.kind} join ${source} on ${renderExpression2(join3.on, state, dialect)}`);
117969
120238
  }
117970
120239
  if (ast.where.length > 0) {
117971
120240
  clauses.push(`where ${ast.where.map((entry) => renderExpression2(entry.predicate, state, dialect)).join(" and ")}`);
@@ -118019,15 +120288,15 @@ var renderQueryAst2 = (ast, state, dialect, options2 = {}) => {
118019
120288
  const conflict = expectConflictClause(insertAst.conflict);
118020
120289
  sql = `insert into ${target}`;
118021
120290
  if (insertSource?.kind === "values") {
118022
- const columns = insertSource.columns.map((column) => quoteColumn2(column, state, dialect, targetSource.tableName)).join(", ");
120291
+ const columns = insertSource.columns.map((column2) => quoteColumn2(column2, state, dialect, targetSource.tableName)).join(", ");
118023
120292
  const rows = insertSource.rows.map((row) => `(${row.values.map((entry) => renderExpression2(entry.value, targetCasingState, dialect)).join(", ")})`).join(", ");
118024
120293
  sql += ` (${columns}) values ${rows}`;
118025
120294
  } else if (insertSource?.kind === "query") {
118026
- const columns = insertSource.columns.map((column) => quoteColumn2(column, state, dialect, targetSource.tableName)).join(", ");
120295
+ const columns = insertSource.columns.map((column2) => quoteColumn2(column2, state, dialect, targetSource.tableName)).join(", ");
118027
120296
  const renderedQuery = renderQueryAst2(getAst(insertSource.query), state, dialect);
118028
120297
  sql += ` (${columns}) ${renderedQuery.sql}`;
118029
120298
  } else if (insertSource?.kind === "unnest") {
118030
- const columns = insertSource.columns.map((column) => quoteColumn2(column, state, dialect, targetSource.tableName)).join(", ");
120299
+ const columns = insertSource.columns.map((column2) => quoteColumn2(column2, state, dialect, targetSource.tableName)).join(", ");
118031
120300
  if (dialect.name === "postgres") {
118032
120301
  const table = targetSource.source;
118033
120302
  const fields2 = table[TypeId7].fields;
@@ -118041,9 +120310,9 @@ var renderQueryAst2 = (ast, state, dialect, options2 = {}) => {
118041
120310
  } else {
118042
120311
  const insertValues = insertAst.values ?? [];
118043
120312
  const columns = insertValues.map((entry) => quoteColumn2(entry.columnName, state, dialect, targetSource.tableName)).join(", ");
118044
- const values2 = insertValues.map((entry) => renderExpression2(entry.value, targetCasingState, dialect)).join(", ");
120313
+ const values3 = insertValues.map((entry) => renderExpression2(entry.value, targetCasingState, dialect)).join(", ");
118045
120314
  if (insertValues.length > 0) {
118046
- sql += ` (${columns}) values (${values2})`;
120315
+ sql += ` (${columns}) values (${values3})`;
118047
120316
  } else {
118048
120317
  sql += " default values";
118049
120318
  }
@@ -118055,7 +120324,7 @@ var renderQueryAst2 = (ast, state, dialect, options2 = {}) => {
118055
120324
  const conflictValueState = { ...targetCasingState, allowExcluded: true };
118056
120325
  const updateValues = (conflict.values ?? []).map((entry) => `${quoteColumn2(entry.columnName, state, dialect, targetSource.tableName)} = ${renderExpression2(entry.value, conflictValueState, dialect)}`).join(", ");
118057
120326
  if (dialect.name === "postgres") {
118058
- const targetSql = conflict.target?.kind === "constraint" ? ` on conflict on constraint ${dialect.quoteIdentifier(applyCategory(targetCasingState.casing, "constraints", conflict.target.name))}` : conflict.target?.kind === "columns" ? ` on conflict (${conflict.target.columns.map((column) => quoteColumn2(column, state, dialect, targetSource.tableName)).join(", ")})${conflict.target.where ? ` where ${renderExpression2(conflict.target.where, targetCasingState, dialect)}` : ""}` : " on conflict";
120327
+ const targetSql = conflict.target?.kind === "constraint" ? ` on conflict on constraint ${dialect.quoteIdentifier(applyCategory(targetCasingState.casing, "constraints", conflict.target.name))}` : conflict.target?.kind === "columns" ? ` on conflict (${conflict.target.columns.map((column2) => quoteColumn2(column2, state, dialect, targetSource.tableName)).join(", ")})${conflict.target.where ? ` where ${renderExpression2(conflict.target.where, targetCasingState, dialect)}` : ""}` : " on conflict";
118059
120328
  sql += targetSql;
118060
120329
  sql += conflict.action === "doNothing" ? " do nothing" : ` do update set ${updateValues}${conflict.where ? ` where ${renderExpression2(conflict.where, conflictValueState, dialect)}` : ""}`;
118061
120330
  } else if (conflict.action === "doNothing") {
@@ -118065,10 +120334,10 @@ var renderQueryAst2 = (ast, state, dialect, options2 = {}) => {
118065
120334
  }
118066
120335
  }
118067
120336
  assertSupportedMutationReturning(dialect, insertAst.select);
118068
- const returning2 = renderSelectionList2(insertAst.select, state, dialect);
118069
- projections = returning2.projections;
118070
- if (returning2.sql.length > 0) {
118071
- sql += ` returning ${returning2.sql}`;
120337
+ const returning3 = renderSelectionList2(insertAst.select, state, dialect);
120338
+ projections = returning3.projections;
120339
+ if (returning3.sql.length > 0) {
120340
+ sql += ` returning ${returning3.sql}`;
118072
120341
  }
118073
120342
  break;
118074
120343
  }
@@ -118085,7 +120354,7 @@ var renderQueryAst2 = (ast, state, dialect, options2 = {}) => {
118085
120354
  if (dialect.name === "mysql") {
118086
120355
  const modifiers = renderMysqlMutationLock2(updateAst.lock, "update");
118087
120356
  const extraSources = renderFromSources2(fromSources, state, dialect);
118088
- const joinSources = updateAst.joins.map((join2) => join2.kind === "cross" ? `cross join ${renderSourceReference2(join2.source, join2.tableName, join2.baseTableName, state, dialect)}` : `${join2.kind} join ${renderSourceReference2(join2.source, join2.tableName, join2.baseTableName, state, dialect)} on ${renderExpression2(join2.on, state, dialect)}`).join(" ");
120357
+ const joinSources = updateAst.joins.map((join3) => join3.kind === "cross" ? `cross join ${renderSourceReference2(join3.source, join3.tableName, join3.baseTableName, state, dialect)}` : `${join3.kind} join ${renderSourceReference2(join3.source, join3.tableName, join3.baseTableName, state, dialect)} on ${renderExpression2(join3.on, state, dialect)}`).join(" ");
118089
120358
  const targetList = [
118090
120359
  ...targets.map((entry) => renderSourceReference2(entry.source, entry.tableName, entry.baseTableName, state, dialect)),
118091
120360
  ...extraSources.length > 0 ? [extraSources] : []
@@ -118115,10 +120384,10 @@ var renderQueryAst2 = (ast, state, dialect, options2 = {}) => {
118115
120384
  sql += ` limit ${renderExpression2(updateAst.limit, state, dialect)}`;
118116
120385
  }
118117
120386
  assertSupportedMutationReturning(dialect, updateAst.select);
118118
- const returning2 = renderSelectionList2(updateAst.select, state, dialect);
118119
- projections = returning2.projections;
118120
- if (returning2.sql.length > 0) {
118121
- sql += ` returning ${returning2.sql}`;
120387
+ const returning3 = renderSelectionList2(updateAst.select, state, dialect);
120388
+ projections = returning3.projections;
120389
+ if (returning3.sql.length > 0) {
120390
+ sql += ` returning ${returning3.sql}`;
118122
120391
  }
118123
120392
  break;
118124
120393
  }
@@ -118135,7 +120404,7 @@ var renderQueryAst2 = (ast, state, dialect, options2 = {}) => {
118135
120404
  const hasJoinedSources = deleteAst.joins.length > 0 || targets.length > 1;
118136
120405
  const targetList = renderDeleteTargets2(targets, dialect);
118137
120406
  const fromSources = targets.map((entry) => renderSourceReference2(entry.source, entry.tableName, entry.baseTableName, state, dialect)).join(", ");
118138
- const joinSources = deleteAst.joins.map((join2) => join2.kind === "cross" ? `cross join ${renderSourceReference2(join2.source, join2.tableName, join2.baseTableName, state, dialect)}` : `${join2.kind} join ${renderSourceReference2(join2.source, join2.tableName, join2.baseTableName, state, dialect)} on ${renderExpression2(join2.on, state, dialect)}`).join(" ");
120407
+ const joinSources = deleteAst.joins.map((join3) => join3.kind === "cross" ? `cross join ${renderSourceReference2(join3.source, join3.tableName, join3.baseTableName, state, dialect)}` : `${join3.kind} join ${renderSourceReference2(join3.source, join3.tableName, join3.baseTableName, state, dialect)} on ${renderExpression2(join3.on, state, dialect)}`).join(" ");
118139
120408
  sql = hasJoinedSources ? `delete${modifiers} ${targetList} from ${fromSources}${joinSources.length > 0 ? ` ${joinSources}` : ""}` : `delete${modifiers} from ${fromSources}`;
118140
120409
  } else {
118141
120410
  sql = `delete from ${target}`;
@@ -118157,10 +120426,10 @@ var renderQueryAst2 = (ast, state, dialect, options2 = {}) => {
118157
120426
  sql += ` limit ${renderExpression2(deleteAst.limit, state, dialect)}`;
118158
120427
  }
118159
120428
  assertSupportedMutationReturning(dialect, deleteAst.select);
118160
- const returning2 = renderSelectionList2(deleteAst.select, state, dialect);
118161
- projections = returning2.projections;
118162
- if (returning2.sql.length > 0) {
118163
- sql += ` returning ${returning2.sql}`;
120429
+ const returning3 = renderSelectionList2(deleteAst.select, state, dialect);
120430
+ projections = returning3.projections;
120431
+ if (returning3.sql.length > 0) {
120432
+ sql += ` returning ${returning3.sql}`;
118164
120433
  }
118165
120434
  break;
118166
120435
  }
@@ -118169,10 +120438,10 @@ var renderQueryAst2 = (ast, state, dialect, options2 = {}) => {
118169
120438
  if (dialect.name === "standard") {
118170
120439
  throw new Error("Unsupported standard truncate statement");
118171
120440
  }
118172
- const truncate = expectTruncateClause(truncateAst.truncate);
120441
+ const truncate2 = expectTruncateClause(truncateAst.truncate);
118173
120442
  const targetSource = truncateAst.target;
118174
- const restartIdentity = truncate.restartIdentity;
118175
- const cascade = truncate.cascade;
120443
+ const restartIdentity = truncate2.restartIdentity;
120444
+ const cascade = truncate2.cascade;
118176
120445
  sql = `truncate table ${renderSourceReference2(targetSource.source, targetSource.tableName, targetSource.baseTableName, state, dialect)}`;
118177
120446
  if (restartIdentity) {
118178
120447
  sql += " restart identity";
@@ -118189,27 +120458,27 @@ var renderQueryAst2 = (ast, state, dialect, options2 = {}) => {
118189
120458
  const mergeAst = ast;
118190
120459
  const targetSource = mergeAst.target;
118191
120460
  const usingSource = mergeAst.using;
118192
- const merge2 = mergeAst.merge;
118193
- sql = `merge into ${renderSourceReference2(targetSource.source, targetSource.tableName, targetSource.baseTableName, state, dialect)} using ${renderSourceReference2(usingSource.source, usingSource.tableName, usingSource.baseTableName, state, dialect)} on ${renderExpression2(merge2.on, state, dialect)}`;
118194
- if (merge2.whenMatched) {
118195
- const matchedKind = merge2.whenMatched.kind === "delete" ? "delete" : "update";
120461
+ const merge3 = mergeAst.merge;
120462
+ sql = `merge into ${renderSourceReference2(targetSource.source, targetSource.tableName, targetSource.baseTableName, state, dialect)} using ${renderSourceReference2(usingSource.source, usingSource.tableName, usingSource.baseTableName, state, dialect)} on ${renderExpression2(merge3.on, state, dialect)}`;
120463
+ if (merge3.whenMatched) {
120464
+ const matchedKind = merge3.whenMatched.kind === "delete" ? "delete" : "update";
118196
120465
  sql += " when matched";
118197
- if (merge2.whenMatched.predicate) {
118198
- sql += ` and ${renderExpression2(merge2.whenMatched.predicate, state, dialect)}`;
120466
+ if (merge3.whenMatched.predicate) {
120467
+ sql += ` and ${renderExpression2(merge3.whenMatched.predicate, state, dialect)}`;
118199
120468
  }
118200
120469
  if (matchedKind === "delete") {
118201
120470
  sql += " then delete";
118202
120471
  } else {
118203
- const matchedUpdate = merge2.whenMatched;
120472
+ const matchedUpdate = merge3.whenMatched;
118204
120473
  sql += ` then update set ${matchedUpdate.values.map((entry) => `${quoteColumn2(entry.columnName, state, dialect, targetSource.tableName)} = ${renderExpression2(entry.value, state, dialect)}`).join(", ")}`;
118205
120474
  }
118206
120475
  }
118207
- if (merge2.whenNotMatched) {
120476
+ if (merge3.whenNotMatched) {
118208
120477
  sql += " when not matched";
118209
- if (merge2.whenNotMatched.predicate) {
118210
- sql += ` and ${renderExpression2(merge2.whenNotMatched.predicate, state, dialect)}`;
120478
+ if (merge3.whenNotMatched.predicate) {
120479
+ sql += ` and ${renderExpression2(merge3.whenNotMatched.predicate, state, dialect)}`;
118211
120480
  }
118212
- sql += ` then insert (${merge2.whenNotMatched.values.map((entry) => quoteColumn2(entry.columnName, state, dialect, targetSource.tableName)).join(", ")}) values (${merge2.whenNotMatched.values.map((entry) => renderExpression2(entry.value, state, dialect)).join(", ")})`;
120481
+ sql += ` then insert (${merge3.whenNotMatched.values.map((entry) => quoteColumn2(entry.columnName, state, dialect, targetSource.tableName)).join(", ")}) values (${merge3.whenNotMatched.values.map((entry) => renderExpression2(entry.value, state, dialect)).join(", ")})`;
118213
120482
  }
118214
120483
  break;
118215
120484
  }
@@ -118300,19 +120569,19 @@ var renderSourceReference2 = (source, tableName, baseTableName, state, dialect)
118300
120569
  return `(${renderQueryAst2(getAst(derived.plan), nestedRenderState2(state), dialect).sql}) as ${dialect.quoteIdentifier(derived.name)}`;
118301
120570
  }
118302
120571
  if (typeof source === "object" && source !== null && "kind" in source && source.kind === "lateral") {
118303
- const lateral = source;
120572
+ const lateral2 = source;
118304
120573
  if (dialect.name === "standard") {
118305
120574
  throw new Error("Unsupported standard lateral source");
118306
120575
  }
118307
- return `lateral (${renderQueryAst2(getAst(lateral.plan), nestedRenderState2(state), dialect).sql}) as ${dialect.quoteIdentifier(lateral.name)}`;
120576
+ return `lateral (${renderQueryAst2(getAst(lateral2.plan), nestedRenderState2(state), dialect).sql}) as ${dialect.quoteIdentifier(lateral2.name)}`;
118308
120577
  }
118309
120578
  if (typeof source === "object" && source !== null && source.kind === "values") {
118310
- const values2 = source;
118311
- return renderSelectRows(values2.rows, Object.keys(values2.columns));
120579
+ const values3 = source;
120580
+ return renderSelectRows(values3.rows, Object.keys(values3.columns));
118312
120581
  }
118313
120582
  if (typeof source === "object" && source !== null && source.kind === "unnest") {
118314
- const unnest2 = source;
118315
- return renderUnnestRows(unnest2.arrays, Object.keys(unnest2.columns));
120583
+ const unnest3 = source;
120584
+ return renderUnnestRows(unnest3.arrays, Object.keys(unnest3.columns));
118316
120585
  }
118317
120586
  if (typeof source === "object" && source !== null && source.kind === "tableFunction") {
118318
120587
  const tableFunction = source;
@@ -118376,6 +120645,8 @@ var renderExpression2 = (expression, state, dialect) => {
118376
120645
  return `(${renderExpression2(expectValueExpression2("collate", ast.value), state, dialect)} collate ${renderCollation(ast.collation)})`;
118377
120646
  case "function":
118378
120647
  return renderFunctionCall2(ast.name, ast.args, state, dialect);
120648
+ case "customSql":
120649
+ return renderCustomSql(ast, state, dialect, renderExpression2);
118379
120650
  case "eq":
118380
120651
  return renderBinaryExpression2("eq", "=", ast.left, ast.right, state, dialect);
118381
120652
  case "neq":
@@ -118388,6 +120659,16 @@ var renderExpression2 = (expression, state, dialect) => {
118388
120659
  return renderBinaryExpression2("gt", ">", ast.left, ast.right, state, dialect);
118389
120660
  case "gte":
118390
120661
  return renderBinaryExpression2("gte", ">=", ast.left, ast.right, state, dialect);
120662
+ case "add":
120663
+ return renderNumericBinaryExpression("add", "+", ast.left, ast.right, state, dialect);
120664
+ case "subtract":
120665
+ return renderNumericBinaryExpression("subtract", "-", ast.left, ast.right, state, dialect);
120666
+ case "multiply":
120667
+ return renderNumericBinaryExpression("multiply", "*", ast.left, ast.right, state, dialect);
120668
+ case "divide":
120669
+ return renderNumericBinaryExpression("divide", "/", ast.left, ast.right, state, dialect);
120670
+ case "modulo":
120671
+ return renderNumericBinaryExpression("modulo", "%", ast.left, ast.right, state, dialect);
118391
120672
  case "like":
118392
120673
  return renderBinaryExpression2("like", "like", ast.left, ast.right, state, dialect);
118393
120674
  case "ilike": {
@@ -118481,6 +120762,16 @@ var renderExpression2 = (expression, state, dialect) => {
118481
120762
  return `lower(${renderExpression2(expectValueExpression2("lower", ast.value), state, dialect)})`;
118482
120763
  case "count":
118483
120764
  return `count(${renderExpression2(expectValueExpression2("count", ast.value), state, dialect)})`;
120765
+ case "sum":
120766
+ return `sum(${renderNumericExpression(expectValueExpression2("sum", ast.value), state, dialect)})`;
120767
+ case "avg":
120768
+ return `avg(${renderNumericExpression(expectValueExpression2("avg", ast.value), state, dialect)})`;
120769
+ case "abs":
120770
+ return `abs(${renderNumericExpression(expectValueExpression2("abs", ast.value), state, dialect)})`;
120771
+ case "round":
120772
+ return `round(${renderNumericExpression(expectValueExpression2("round", ast.value), state, dialect)})`;
120773
+ case "negate":
120774
+ return `(-${renderNumericExpression(expectValueExpression2("negate", ast.value), state, dialect)})`;
118484
120775
  case "max":
118485
120776
  return `max(${renderExpression2(expectValueExpression2("max", ast.value), state, dialect)})`;
118486
120777
  case "min":
@@ -118525,24 +120816,44 @@ var renderExpression2 = (expression, state, dialect) => {
118525
120816
  }
118526
120817
  case "window": {
118527
120818
  const partitionBy = ast.partitionBy;
118528
- const orderBy2 = ast.orderBy;
118529
- const clauses = [];
118530
- if (partitionBy.length > 0) {
118531
- clauses.push(`partition by ${partitionBy.map((value) => renderExpression2(value, state, dialect)).join(", ")}`);
118532
- }
118533
- if (orderBy2.length > 0) {
118534
- clauses.push(`order by ${orderBy2.map((entry) => `${renderExpression2(entry.value, state, dialect)} ${entry.direction}`).join(", ")}`);
118535
- }
118536
- const specification = clauses.join(" ");
120819
+ const orderBy3 = ast.orderBy;
120820
+ const renderSpecification = () => {
120821
+ const clauses = [];
120822
+ if (partitionBy.length > 0) {
120823
+ clauses.push(`partition by ${partitionBy.map((value) => renderExpression2(value, state, dialect)).join(", ")}`);
120824
+ }
120825
+ if (orderBy3.length > 0) {
120826
+ clauses.push(`order by ${orderBy3.map((entry) => `${renderExpression2(entry.value, state, dialect)} ${entry.direction}`).join(", ")}`);
120827
+ }
120828
+ if (ast.frame !== undefined) {
120829
+ clauses.push(renderWindowFrame(ast.frame));
120830
+ }
120831
+ return clauses.join(" ");
120832
+ };
118537
120833
  switch (ast.function) {
118538
120834
  case "rowNumber":
118539
- return `row_number() over (${specification})`;
120835
+ return `row_number() over (${renderSpecification()})`;
118540
120836
  case "rank":
118541
- return `rank() over (${specification})`;
120837
+ return `rank() over (${renderSpecification()})`;
118542
120838
  case "denseRank":
118543
- return `dense_rank() over (${specification})`;
120839
+ return `dense_rank() over (${renderSpecification()})`;
118544
120840
  case "over":
118545
- return `${renderExpression2(ast.value, state, dialect)} over (${specification})`;
120841
+ return `${renderExpression2(ast.value, state, dialect)} over (${renderSpecification()})`;
120842
+ case "lag":
120843
+ case "lead": {
120844
+ const args = [renderExpression2(ast.value, state, dialect)];
120845
+ if (ast.offset !== undefined) {
120846
+ args.push(renderExpression2(ast.offset, state, dialect));
120847
+ }
120848
+ if (ast.defaultValue !== undefined) {
120849
+ args.push(renderExpression2(ast.defaultValue, state, dialect));
120850
+ }
120851
+ return `${ast.function}(${args.join(", ")}) over (${renderSpecification()})`;
120852
+ }
120853
+ case "firstValue":
120854
+ return `first_value(${renderExpression2(ast.value, state, dialect)}) over (${renderSpecification()})`;
120855
+ case "lastValue":
120856
+ return `last_value(${renderExpression2(ast.value, state, dialect)}) over (${renderSpecification()})`;
118546
120857
  }
118547
120858
  break;
118548
120859
  }
@@ -118575,8 +120886,8 @@ var standardDialect = {
118575
120886
  const renderedBase = schemaName && schemaName !== "public" ? `${quoteIdentifier(schemaName)}.${quoteIdentifier(baseTableName)}` : quoteIdentifier(baseTableName);
118576
120887
  return tableName === baseTableName ? renderedBase : `${renderedBase} as ${quoteIdentifier(tableName)}`;
118577
120888
  },
118578
- renderConcat(values2) {
118579
- return `(${values2.join(" || ")})`;
120889
+ renderConcat(values3) {
120890
+ return `(${values3.join(" || ")})`;
118580
120891
  },
118581
120892
  renderQueryAst: renderQueryAst2,
118582
120893
  renderExpression: renderExpression2
@@ -118608,8 +120919,8 @@ var mysqlDialect = {
118608
120919
  const renderedBase = schemaName && schemaName !== "public" ? `${quoteIdentifier2(schemaName)}.${quoteIdentifier2(baseTableName)}` : quoteIdentifier2(baseTableName);
118609
120920
  return tableName === baseTableName ? renderedBase : `${renderedBase} as ${quoteIdentifier2(tableName)}`;
118610
120921
  },
118611
- renderConcat(values2) {
118612
- return `concat(${values2.join(", ")})`;
120922
+ renderConcat(values3) {
120923
+ return `concat(${values3.join(", ")})`;
118613
120924
  },
118614
120925
  renderQueryAst,
118615
120926
  renderExpression
@@ -118644,41 +120955,77 @@ var renderMysqlPlan = (plan, options2 = {}) => {
118644
120955
  };
118645
120956
 
118646
120957
  // src/mysql/executor.ts
120958
+ var atMostOne2 = atMostOne;
120959
+ var exactlyOne2 = exactlyOne;
120960
+ var nonEmpty2 = nonEmpty;
118647
120961
  var withTransaction2 = withTransaction;
118648
120962
  function driver2(executeOrHandlers) {
118649
120963
  return driver("mysql", executeOrHandlers);
118650
120964
  }
118651
- var fromDriver2 = (renderer, sqlDriver, driverMode = "raw", valueMappings) => ({
118652
- dialect: "mysql",
118653
- execute(plan) {
118654
- const rendered = renderer.render(plan);
118655
- return Effect2.mapError(Effect2.flatMap(sqlDriver.execute(rendered), (rows) => Effect2.try({
118656
- try: () => decodeRows(rendered, plan, rows, { driverMode, valueMappings }),
118657
- catch: (error) => error
118658
- })), (error) => {
118659
- if (typeof error === "object" && error !== null && "_tag" in error && error._tag === "RowDecodeError") {
118660
- return error;
118661
- }
118662
- const normalized = normalizeMysqlDriverError(error, rendered);
118663
- return hasWriteCapability(plan) ? normalized : narrowMysqlDriverErrorForReadQuery(normalized);
118664
- });
118665
- },
118666
- stream(plan) {
120965
+ var fromDriver2 = (renderer, sqlDriver, driverMode = "raw", valueMappings) => {
120966
+ const renderedCache = new WeakMap;
120967
+ const render2 = (plan) => {
120968
+ const cached = renderedCache.get(plan);
120969
+ if (cached !== undefined) {
120970
+ return cached;
120971
+ }
118667
120972
  const rendered = renderer.render(plan);
118668
- return Stream2.mapError(Stream2.mapArrayEffect(sqlDriver.stream(rendered), (rows) => Effect2.try({
118669
- try: () => decodeRows(rendered, plan, rows, { driverMode, valueMappings }),
118670
- catch: (error) => error
118671
- })), (error) => {
118672
- if (typeof error === "object" && error !== null && "_tag" in error && error._tag === "RowDecodeError") {
118673
- return error;
118674
- }
118675
- const normalized = normalizeMysqlDriverError(error, rendered);
118676
- return hasWriteCapability(plan) ? normalized : narrowMysqlDriverErrorForReadQuery(normalized);
118677
- });
118678
- }
118679
- });
120973
+ renderedCache.set(plan, rendered);
120974
+ return rendered;
120975
+ };
120976
+ const mapExecutionError = (error, rendered, plan) => {
120977
+ if (typeof error === "object" && error !== null && "_tag" in error && error._tag === "RowDecodeError") {
120978
+ return error;
120979
+ }
120980
+ const normalized = normalizeMysqlDriverError(error, rendered);
120981
+ return hasWriteCapability(plan) ? normalized : narrowMysqlDriverErrorForReadQuery(normalized);
120982
+ };
120983
+ return withResultContracts({
120984
+ dialect: "mysql",
120985
+ execute(plan) {
120986
+ const rendered = render2(plan);
120987
+ return Effect2.mapError(Effect2.flatMap(sqlDriver.execute(rendered), (rows) => Effect2.try({
120988
+ try: () => decodeRows(rendered, plan, rows, { driverMode, valueMappings }),
120989
+ catch: (error) => error
120990
+ })), (error) => mapExecutionError(error, rendered, plan));
120991
+ },
120992
+ executeResult(plan) {
120993
+ const rendered = render2(plan);
120994
+ const result = sqlDriver.executeResult ? sqlDriver.executeResult(rendered) : Effect2.map(sqlDriver.execute(rendered), (rows) => ({ rows }));
120995
+ return Effect2.mapError(Effect2.flatMap(result, ({ rows, ...metadata }) => Effect2.try({
120996
+ try: () => ({
120997
+ ...metadata,
120998
+ rows: decodeRows(rendered, plan, rows, { driverMode, valueMappings })
120999
+ }),
121000
+ catch: (error) => error
121001
+ })), (error) => mapExecutionError(error, rendered, plan));
121002
+ },
121003
+ stream(plan) {
121004
+ const rendered = render2(plan);
121005
+ return Stream2.mapError(Stream2.mapArrayEffect(sqlDriver.stream(rendered), (rows) => Effect2.try({
121006
+ try: () => decodeRows(rendered, plan, rows, { driverMode, valueMappings }),
121007
+ catch: (error) => error
121008
+ })), (error) => mapExecutionError(error, rendered, plan));
121009
+ },
121010
+ explain(plan, options2) {
121011
+ const rendered = explainQuery(render2(plan), options2);
121012
+ return Effect2.mapError(sqlDriver.execute(rendered), (error) => mapExecutionError(error, rendered, plan));
121013
+ }
121014
+ });
121015
+ };
118680
121016
  var sqlClientDriver = () => driver2({
118681
121017
  execute: (query) => Effect2.flatMap(SqlClient3.SqlClient, (sql) => sql.unsafe(query.sql, [...query.params])),
121018
+ executeResult: (query) => Effect2.flatMap(SqlClient3.SqlClient, (sql) => Effect2.map(sql.unsafe(query.sql, [...query.params]).raw, (raw) => {
121019
+ if (Array.isArray(raw)) {
121020
+ return { rows: raw };
121021
+ }
121022
+ const header = raw;
121023
+ return {
121024
+ rows: [],
121025
+ ...typeof header?.affectedRows === "number" ? { affectedRows: header.affectedRows } : {},
121026
+ ...header?.insertId === undefined ? {} : { insertId: header.insertId }
121027
+ };
121028
+ })),
118682
121029
  stream: (query) => streamFromSqlClient(query)
118683
121030
  });
118684
121031
  function make4(options2 = {}) {
@@ -118687,7 +121034,7 @@ function make4(options2 = {}) {
118687
121034
  }
118688
121035
  return fromDriver2(options2.renderer ?? makeTrusted("mysql", (plan) => renderMysqlPlan(plan, { valueMappings: options2.valueMappings })), sqlClientDriver(), options2.driverMode, options2.valueMappings);
118689
121036
  }
118690
- var custom3 = (execute) => make3("mysql", execute);
121037
+ var custom4 = (execute) => make3("mysql", execute);
118691
121038
  // src/mysql/query-extension.ts
118692
121039
  var exports_query_extension = {};
118693
121040
  __export(exports_query_extension, {
@@ -118713,20 +121060,20 @@ var set2 = (kind) => ({
118713
121060
  kind,
118714
121061
  variant: "set"
118715
121062
  });
118716
- var custom4 = (kind) => ({
121063
+ var custom5 = (kind) => ({
118717
121064
  dialect: "mysql",
118718
121065
  kind
118719
121066
  });
118720
- var driverValueMapping3 = (dbType, mapping) => ({
121067
+ var driverValueMapping4 = (dbType, mapping) => ({
118721
121068
  ...dbType,
118722
121069
  driverValueMapping: mapping
118723
121070
  });
118724
- var type2 = {
121071
+ var type3 = {
118725
121072
  ...pickDatatypeConstructors(mysqlDatatypes, mysqlSpecificDatatypeKeys),
118726
121073
  enum: enum_2,
118727
121074
  set: set2,
118728
- custom: custom4,
118729
- driverValueMapping: driverValueMapping3
121075
+ custom: custom5,
121076
+ driverValueMapping: driverValueMapping4
118730
121077
  };
118731
121078
  // src/mysql/renderer.ts
118732
121079
  var exports_renderer2 = {};
@@ -118735,10 +121082,10 @@ __export(exports_renderer2, {
118735
121082
  make: () => make5,
118736
121083
  TypeId: () => TypeId10
118737
121084
  });
118738
- import { pipeArguments as pipeArguments8 } from "effect/Pipeable";
121085
+ import { pipeArguments as pipeArguments9 } from "effect/Pipeable";
118739
121086
  var RendererProto = {
118740
121087
  pipe() {
118741
- return pipeArguments8(this, arguments);
121088
+ return pipeArguments9(this, arguments);
118742
121089
  }
118743
121090
  };
118744
121091
  var makeWithState = (state = {}) => {
@@ -118756,10 +121103,11 @@ var makeWithState = (state = {}) => {
118756
121103
  var make5 = (options2 = {}) => makeWithState({ valueMappings: options2.valueMappings });
118757
121104
  var mysql = make5();
118758
121105
  export {
118759
- type2 as Type,
121106
+ type3 as Type,
118760
121107
  exports_renderer2 as Renderer,
118761
121108
  exports_query_extension as Query,
118762
121109
  exports_json as Json,
121110
+ exports_function as Function,
118763
121111
  exports_executor2 as Executor,
118764
121112
  exports_errors as Errors,
118765
121113
  exports_datatypes as Datatypes,