effect-qb 0.21.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 +1 -1
  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/postgres.js CHANGED
@@ -2639,6 +2639,33 @@ var sqliteSpecificDatatypeKeys = [
2639
2639
  ];
2640
2640
  var pickDatatypeConstructors = (module, keys) => Object.fromEntries(keys.map((key2) => [key2, module[key2]]));
2641
2641
 
2642
+ // src/internal/custom-sql-renderer.ts
2643
+ var renderCustomSql = (node, state, dialect, renderExpression2) => node.strings.map((part, index3) => {
2644
+ const value = node.values[index3];
2645
+ if (value === undefined) {
2646
+ return part;
2647
+ }
2648
+ return part + (TypeId2 in value ? renderExpression2(value, state, dialect) : value.parts.map((segment) => dialect.quoteIdentifier(segment)).join("."));
2649
+ }).join("");
2650
+
2651
+ // src/internal/window-renderer.ts
2652
+ var renderBoundary = (boundary) => {
2653
+ if (boundary === "unboundedPreceding") {
2654
+ return "unbounded preceding";
2655
+ }
2656
+ if (boundary === "currentRow") {
2657
+ return "current row";
2658
+ }
2659
+ if (boundary === "unboundedFollowing") {
2660
+ return "unbounded following";
2661
+ }
2662
+ if ("preceding" in boundary) {
2663
+ return `${boundary.preceding} preceding`;
2664
+ }
2665
+ return `${boundary.following} following`;
2666
+ };
2667
+ var renderWindowFrame = (frame) => frame.end === undefined ? `${frame.unit} ${renderBoundary(frame.start)}` : `${frame.unit} between ${renderBoundary(frame.start)} and ${renderBoundary(frame.end)}`;
2668
+
2642
2669
  // src/internal/dsl-plan-runtime.ts
2643
2670
  var renderSelectLockMode = (mode) => mode === "update" ? "for update" : "for share";
2644
2671
  var renderMysqlMutationLockMode = (mode, _statement) => {
@@ -3804,8 +3831,9 @@ var normalizeOffsetTime = (value) => {
3804
3831
  return `${formatLocalTime(validDate(value))}Z`;
3805
3832
  }
3806
3833
  const raw = expectString(value, "offset time").trim();
3807
- if (isValidOffsetTimeString(raw)) {
3808
- return raw;
3834
+ const canonical = raw.replace(/([+-]\d{2})$/, "$1:00").replace(/([+-]\d{2})(\d{2})$/, "$1:$2");
3835
+ if (isValidOffsetTimeString(canonical)) {
3836
+ return canonical;
3809
3837
  }
3810
3838
  throw new Error("Expected an offset-time value");
3811
3839
  };
@@ -4245,6 +4273,14 @@ var castTargetGroupingKey = (target) => {
4245
4273
  };
4246
4274
  var escapeGroupingText = (value) => value.replace(/\\/g, "\\\\").replace(/,/g, "\\,").replace(/\|/g, "\\|").replace(/=/g, "\\=").replace(/>/g, "\\>");
4247
4275
  var functionCallNameGroupingKey = (name) => escapeGroupingText(name);
4276
+ var customSqlGroupingKey = (strings, values) => strings.map((part, index3) => {
4277
+ const value = values[index3];
4278
+ if (value === undefined) {
4279
+ return escapeGroupingText(part);
4280
+ }
4281
+ const rendered = isExpression3(value) ? groupingKeyOfExpression(value) : `identifier:${value.parts.map(escapeGroupingText).join(".")}`;
4282
+ return `${escapeGroupingText(part)}${rendered}`;
4283
+ }).join("|");
4248
4284
  var quantifiedComparisonGroupingName = (kind) => kind === "comparisonAny" ? "compareAny" : "compareAll";
4249
4285
  var caseGroupingKey = (branches, fallback) => {
4250
4286
  const typedBranches = branches;
@@ -4326,12 +4362,19 @@ var groupingKeyOfExpression = (expression) => {
4326
4362
  return `collate(${requiredExpressionGroupingKey("collate", ast.value)},${collationGroupingKey(ast.collation)})`;
4327
4363
  case "function":
4328
4364
  return `function(${functionCallNameGroupingKey(ast.name)},${functionCallArgsGroupingKey(ast.args)})`;
4365
+ case "customSql":
4366
+ return `customSql(${customSqlGroupingKey(ast.strings, ast.values)})`;
4329
4367
  case "isNull":
4330
4368
  case "isNotNull":
4331
4369
  case "not":
4332
4370
  case "upper":
4333
4371
  case "lower":
4334
4372
  case "count":
4373
+ case "sum":
4374
+ case "avg":
4375
+ case "abs":
4376
+ case "round":
4377
+ case "negate":
4335
4378
  case "max":
4336
4379
  case "min":
4337
4380
  return `${ast.kind}(${requiredExpressionGroupingKey(ast.kind, ast.value)})`;
@@ -4352,6 +4395,11 @@ var groupingKeyOfExpression = (expression) => {
4352
4395
  case "contains":
4353
4396
  case "containedBy":
4354
4397
  case "overlaps":
4398
+ case "add":
4399
+ case "subtract":
4400
+ case "multiply":
4401
+ case "divide":
4402
+ case "modulo":
4355
4403
  return `${ast.kind}(${requiredBinaryExpressionGroupingKey(ast.kind, ast.left, ast.right)})`;
4356
4404
  case "and":
4357
4405
  case "or":
@@ -4701,6 +4749,15 @@ var renderBinaryExpression = (functionName, operator, left, right, state, dialec
4701
4749
  const [leftExpression, rightExpression] = expectBinaryExpressions(functionName, left, right);
4702
4750
  return `(${renderExpression2(leftExpression, state, dialect)} ${operator} ${renderExpression2(rightExpression, state, dialect)})`;
4703
4751
  };
4752
+ var renderNumericExpression = (expression, state, dialect) => {
4753
+ const rendered = renderExpression2(expression, state, dialect);
4754
+ const ast = expression[TypeId3];
4755
+ return dialect.name === "postgres" && ast.kind === "literal" ? `cast(${rendered} as ${renderCastType(dialect, expression[TypeId2].dbType)})` : rendered;
4756
+ };
4757
+ var renderNumericBinaryExpression = (functionName, operator, left, right, state, dialect) => {
4758
+ const [leftExpression, rightExpression] = expectBinaryExpressions(functionName, left, right);
4759
+ return `(${renderNumericExpression(leftExpression, state, dialect)} ${operator} ${renderNumericExpression(rightExpression, state, dialect)})`;
4760
+ };
4704
4761
  var postgresRangeSubtypeByKind = {
4705
4762
  int4range: "int4",
4706
4763
  int8range: "int8",
@@ -5735,6 +5792,8 @@ var renderExpression2 = (expression, state, dialect) => {
5735
5792
  return `(${renderExpression2(expectValueExpression("collate", ast.value), state, dialect)} collate ${renderCollation(ast.collation)})`;
5736
5793
  case "function":
5737
5794
  return renderFunctionCall(ast.name, ast.args, state, dialect);
5795
+ case "customSql":
5796
+ return renderCustomSql(ast, state, dialect, renderExpression2);
5738
5797
  case "eq":
5739
5798
  return renderBinaryExpression("eq", "=", ast.left, ast.right, state, dialect);
5740
5799
  case "neq":
@@ -5747,6 +5806,16 @@ var renderExpression2 = (expression, state, dialect) => {
5747
5806
  return renderBinaryExpression("gt", ">", ast.left, ast.right, state, dialect);
5748
5807
  case "gte":
5749
5808
  return renderBinaryExpression("gte", ">=", ast.left, ast.right, state, dialect);
5809
+ case "add":
5810
+ return renderNumericBinaryExpression("add", "+", ast.left, ast.right, state, dialect);
5811
+ case "subtract":
5812
+ return renderNumericBinaryExpression("subtract", "-", ast.left, ast.right, state, dialect);
5813
+ case "multiply":
5814
+ return renderNumericBinaryExpression("multiply", "*", ast.left, ast.right, state, dialect);
5815
+ case "divide":
5816
+ return renderNumericBinaryExpression("divide", "/", ast.left, ast.right, state, dialect);
5817
+ case "modulo":
5818
+ return renderNumericBinaryExpression("modulo", "%", ast.left, ast.right, state, dialect);
5750
5819
  case "like":
5751
5820
  return renderBinaryExpression("like", "like", ast.left, ast.right, state, dialect);
5752
5821
  case "ilike": {
@@ -5840,6 +5909,16 @@ var renderExpression2 = (expression, state, dialect) => {
5840
5909
  return `lower(${renderExpression2(expectValueExpression("lower", ast.value), state, dialect)})`;
5841
5910
  case "count":
5842
5911
  return `count(${renderExpression2(expectValueExpression("count", ast.value), state, dialect)})`;
5912
+ case "sum":
5913
+ return `sum(${renderNumericExpression(expectValueExpression("sum", ast.value), state, dialect)})`;
5914
+ case "avg":
5915
+ return `avg(${renderNumericExpression(expectValueExpression("avg", ast.value), state, dialect)})`;
5916
+ case "abs":
5917
+ return `abs(${renderNumericExpression(expectValueExpression("abs", ast.value), state, dialect)})`;
5918
+ case "round":
5919
+ return `round(${renderNumericExpression(expectValueExpression("round", ast.value), state, dialect)})`;
5920
+ case "negate":
5921
+ return `(-${renderNumericExpression(expectValueExpression("negate", ast.value), state, dialect)})`;
5843
5922
  case "max":
5844
5923
  return `max(${renderExpression2(expectValueExpression("max", ast.value), state, dialect)})`;
5845
5924
  case "min":
@@ -5885,23 +5964,43 @@ var renderExpression2 = (expression, state, dialect) => {
5885
5964
  case "window": {
5886
5965
  const partitionBy = ast.partitionBy;
5887
5966
  const orderBy = ast.orderBy;
5888
- const clauses = [];
5889
- if (partitionBy.length > 0) {
5890
- clauses.push(`partition by ${partitionBy.map((value) => renderExpression2(value, state, dialect)).join(", ")}`);
5891
- }
5892
- if (orderBy.length > 0) {
5893
- clauses.push(`order by ${orderBy.map((entry) => `${renderExpression2(entry.value, state, dialect)} ${entry.direction}`).join(", ")}`);
5894
- }
5895
- const specification = clauses.join(" ");
5967
+ const renderSpecification = () => {
5968
+ const clauses = [];
5969
+ if (partitionBy.length > 0) {
5970
+ clauses.push(`partition by ${partitionBy.map((value) => renderExpression2(value, state, dialect)).join(", ")}`);
5971
+ }
5972
+ if (orderBy.length > 0) {
5973
+ clauses.push(`order by ${orderBy.map((entry) => `${renderExpression2(entry.value, state, dialect)} ${entry.direction}`).join(", ")}`);
5974
+ }
5975
+ if (ast.frame !== undefined) {
5976
+ clauses.push(renderWindowFrame(ast.frame));
5977
+ }
5978
+ return clauses.join(" ");
5979
+ };
5896
5980
  switch (ast.function) {
5897
5981
  case "rowNumber":
5898
- return `row_number() over (${specification})`;
5982
+ return `row_number() over (${renderSpecification()})`;
5899
5983
  case "rank":
5900
- return `rank() over (${specification})`;
5984
+ return `rank() over (${renderSpecification()})`;
5901
5985
  case "denseRank":
5902
- return `dense_rank() over (${specification})`;
5986
+ return `dense_rank() over (${renderSpecification()})`;
5903
5987
  case "over":
5904
- return `${renderExpression2(ast.value, state, dialect)} over (${specification})`;
5988
+ return `${renderExpression2(ast.value, state, dialect)} over (${renderSpecification()})`;
5989
+ case "lag":
5990
+ case "lead": {
5991
+ const args = [renderExpression2(ast.value, state, dialect)];
5992
+ if (ast.offset !== undefined) {
5993
+ args.push(renderExpression2(ast.offset, state, dialect));
5994
+ }
5995
+ if (ast.defaultValue !== undefined) {
5996
+ args.push(renderExpression2(ast.defaultValue, state, dialect));
5997
+ }
5998
+ return `${ast.function}(${args.join(", ")}) over (${renderSpecification()})`;
5999
+ }
6000
+ case "firstValue":
6001
+ return `first_value(${renderExpression2(ast.value, state, dialect)}) over (${renderSpecification()})`;
6002
+ case "lastValue":
6003
+ return `last_value(${renderExpression2(ast.value, state, dialect)}) over (${renderSpecification()})`;
5905
6004
  }
5906
6005
  break;
5907
6006
  }
@@ -9822,16 +9921,45 @@ var narrowPostgresDriverErrorForReadQuery = (error) => {
9822
9921
  // src/postgres/function/index.ts
9823
9922
  var exports_function = {};
9824
9923
  __export(exports_function, {
9924
+ window: () => exports_window,
9825
9925
  uuidGenerateV4: () => uuidGenerateV4,
9926
+ upper: () => upper,
9927
+ temporal: () => exports_temporal,
9928
+ sum: () => sum,
9929
+ string: () => exports_string,
9930
+ rowNumber: () => rowNumber,
9931
+ round: () => round2,
9932
+ rank: () => rank,
9933
+ over: () => over,
9934
+ numeric: () => exports_numeric,
9935
+ now: () => now,
9826
9936
  nextVal: () => nextVal2,
9827
- core: () => exports_core
9937
+ modulo: () => modulo2,
9938
+ min: () => min,
9939
+ max: () => max,
9940
+ lower: () => lower,
9941
+ localTimestamp: () => localTimestamp,
9942
+ localTime: () => localTime,
9943
+ lastValue: () => lastValue2,
9944
+ firstValue: () => firstValue2,
9945
+ denseRank: () => denseRank,
9946
+ currentTimestamp: () => currentTimestamp,
9947
+ currentTime: () => currentTime,
9948
+ currentDate: () => currentDate,
9949
+ count: () => count,
9950
+ core: () => exports_core,
9951
+ concat: () => concat,
9952
+ call: () => call,
9953
+ avg: () => avg,
9954
+ aggregate: () => exports_aggregate
9828
9955
  });
9829
9956
 
9830
9957
  // src/postgres/function/core.ts
9831
9958
  var exports_core = {};
9832
9959
  __export(exports_core, {
9833
9960
  uuidGenerateV4: () => uuidGenerateV4,
9834
- nextVal: () => nextVal2
9961
+ nextVal: () => nextVal2,
9962
+ call: () => call
9835
9963
  });
9836
9964
 
9837
9965
  // src/postgres/internal/dsl.ts
@@ -9951,6 +10079,31 @@ var resolveImplicationScope = (available, initialAssumptions) => {
9951
10079
  };
9952
10080
  };
9953
10081
 
10082
+ // src/internal/window-frame.ts
10083
+ var validateBoundary = (boundary) => {
10084
+ if (typeof boundary === "object") {
10085
+ const value = "preceding" in boundary ? boundary.preceding : boundary.following;
10086
+ if (!Number.isSafeInteger(value) || value < 0) {
10087
+ throw new Error("window frame offsets must be non-negative safe integers");
10088
+ }
10089
+ }
10090
+ };
10091
+ var validateWindowFrame = (frame) => {
10092
+ if (frame === undefined) {
10093
+ return;
10094
+ }
10095
+ validateBoundary(frame.start);
10096
+ if (frame.end !== undefined) {
10097
+ validateBoundary(frame.end);
10098
+ }
10099
+ if (frame.start === "unboundedFollowing") {
10100
+ throw new Error("window frame cannot start with unbounded following");
10101
+ }
10102
+ if (frame.end === "unboundedPreceding") {
10103
+ throw new Error("window frame cannot end with unbounded preceding");
10104
+ }
10105
+ };
10106
+
9954
10107
  // src/internal/dsl-query-runtime.ts
9955
10108
  var makeDslQueryRuntime = (ctx) => {
9956
10109
  const values = (rows) => {
@@ -10239,6 +10392,23 @@ var extractRequiredFromDialectInputRuntime = (value) => {
10239
10392
  const expression = toDialectExpression(value);
10240
10393
  return Object.keys(expression[TypeId2].dependencies);
10241
10394
  };
10395
+ var normalizeWindowSpec = (spec) => {
10396
+ validateWindowFrame(spec?.frame);
10397
+ const partitionBy = [...spec?.partitionBy ?? []];
10398
+ const orderBy = (spec?.orderBy ?? []).map((term) => {
10399
+ const direction = term.direction ?? "asc";
10400
+ return {
10401
+ value: term.value,
10402
+ direction
10403
+ };
10404
+ });
10405
+ return {
10406
+ partitionBy,
10407
+ orderBy,
10408
+ frame: spec?.frame
10409
+ };
10410
+ };
10411
+ var mergeWindowExpressions = (value, partitionBy, orderBy) => value === undefined ? [...partitionBy, ...orderBy.map((term) => term.value)] : [value, ...partitionBy, ...orderBy.map((term) => term.value)];
10242
10412
  var extractRequiredFromDialectNumericInputRuntime = (value) => {
10243
10413
  const expression = toDialectNumericExpression(value);
10244
10414
  return Object.keys(expression[TypeId2].dependencies);
@@ -10258,6 +10428,34 @@ var buildBinaryPredicate = (left, right, kind, nullability = "maybe") => {
10258
10428
  right: rightExpression
10259
10429
  });
10260
10430
  };
10431
+ var upper = (value) => {
10432
+ const expression = toDialectStringExpression(value);
10433
+ return makeExpression2({
10434
+ runtime: "",
10435
+ dbType: profile.textDb,
10436
+ nullability: expression[TypeId2].nullability,
10437
+ dialect: profile.dialect,
10438
+ kind: expression[TypeId2].kind,
10439
+ dependencies: expression[TypeId2].dependencies
10440
+ }, {
10441
+ kind: "upper",
10442
+ value: expression
10443
+ });
10444
+ };
10445
+ var lower = (value) => {
10446
+ const expression = toDialectStringExpression(value);
10447
+ return makeExpression2({
10448
+ runtime: "",
10449
+ dbType: profile.textDb,
10450
+ nullability: expression[TypeId2].nullability,
10451
+ dialect: profile.dialect,
10452
+ kind: expression[TypeId2].kind,
10453
+ dependencies: expression[TypeId2].dependencies
10454
+ }, {
10455
+ kind: "lower",
10456
+ value: expression
10457
+ });
10458
+ };
10261
10459
  var cast = (value, target) => {
10262
10460
  const expression = toDialectExpression(value);
10263
10461
  return makeExpression2({
@@ -10760,6 +10958,111 @@ var jsonb2 = {
10760
10958
  pathExists: jsonPathExists,
10761
10959
  pathMatch: jsonPathMatch
10762
10960
  };
10961
+ var concat = (...values) => {
10962
+ const expressions = values.map((value) => toDialectStringExpression(value));
10963
+ return makeExpression2({
10964
+ runtime: "",
10965
+ dbType: profile.textDb,
10966
+ nullability: mergeNullabilityManyRuntime(expressions),
10967
+ dialect: expressions.find((value) => value[TypeId2].dialect !== undefined)?.[TypeId2].dialect ?? profile.dialect,
10968
+ kind: mergeAggregationManyRuntime(expressions),
10969
+ dependencies: mergeManyDependencies(expressions)
10970
+ }, {
10971
+ kind: "concat",
10972
+ values: expressions
10973
+ });
10974
+ };
10975
+ var count = (value) => {
10976
+ const expression = toDialectExpression(value);
10977
+ return makeExpression2({
10978
+ runtime: undefined,
10979
+ dbType: postgresDatatypes.int8(),
10980
+ nullability: "never",
10981
+ dialect: expression[TypeId2].dialect,
10982
+ kind: "aggregate",
10983
+ dependencies: expression[TypeId2].dependencies
10984
+ }, {
10985
+ kind: "count",
10986
+ value: expression
10987
+ });
10988
+ };
10989
+ var over = (value, spec = {}) => {
10990
+ const normalized = normalizeWindowSpec(spec);
10991
+ const expressions = mergeWindowExpressions(value, normalized.partitionBy, normalized.orderBy);
10992
+ return makeExpression2({
10993
+ runtime: undefined,
10994
+ dbType: value[TypeId2].dbType,
10995
+ nullability: value[TypeId2].nullability,
10996
+ dialect: expressions.find((expression) => expression[TypeId2].dialect !== undefined)?.[TypeId2].dialect ?? profile.dialect,
10997
+ kind: "window",
10998
+ dependencies: mergeManyDependencies(expressions)
10999
+ }, {
11000
+ kind: "window",
11001
+ function: "over",
11002
+ value,
11003
+ partitionBy: normalized.partitionBy,
11004
+ orderBy: normalized.orderBy,
11005
+ frame: normalized.frame
11006
+ });
11007
+ };
11008
+ var buildNumberWindow = (kind, spec) => {
11009
+ const normalized = normalizeWindowSpec(spec);
11010
+ const expressions = mergeWindowExpressions(undefined, normalized.partitionBy, normalized.orderBy);
11011
+ return makeExpression2({
11012
+ runtime: undefined,
11013
+ dbType: postgresDatatypes.int8(),
11014
+ nullability: "never",
11015
+ dialect: expressions.find((expression) => expression[TypeId2].dialect !== undefined)?.[TypeId2].dialect ?? profile.dialect,
11016
+ kind: "window",
11017
+ dependencies: mergeManyDependencies(expressions)
11018
+ }, {
11019
+ kind: "window",
11020
+ function: kind,
11021
+ partitionBy: normalized.partitionBy,
11022
+ orderBy: normalized.orderBy,
11023
+ frame: normalized.frame
11024
+ });
11025
+ };
11026
+ var rowNumber = (spec) => buildNumberWindow("rowNumber", spec);
11027
+ var rank = (spec) => buildNumberWindow("rank", spec);
11028
+ var denseRank = (spec) => buildNumberWindow("denseRank", spec);
11029
+ var max = (value) => makeExpression2({
11030
+ runtime: undefined,
11031
+ dbType: value[TypeId2].dbType,
11032
+ nullability: "maybe",
11033
+ dialect: value[TypeId2].dialect,
11034
+ kind: "aggregate",
11035
+ dependencies: value[TypeId2].dependencies
11036
+ }, {
11037
+ kind: "max",
11038
+ value
11039
+ });
11040
+ var min = (value) => makeExpression2({
11041
+ runtime: undefined,
11042
+ dbType: value[TypeId2].dbType,
11043
+ nullability: "maybe",
11044
+ dialect: value[TypeId2].dialect,
11045
+ kind: "aggregate",
11046
+ dependencies: value[TypeId2].dependencies
11047
+ }, {
11048
+ kind: "min",
11049
+ value
11050
+ });
11051
+ var call = (name2, ...args) => {
11052
+ const expressions = args.map((value) => toDialectExpression(value));
11053
+ return makeExpression2({
11054
+ runtime: undefined,
11055
+ dbType: profile.textDb,
11056
+ nullability: "maybe",
11057
+ dialect: expressions.find((value) => value[TypeId2].dialect !== undefined)?.[TypeId2].dialect ?? profile.dialect,
11058
+ kind: mergeAggregationManyRuntime(expressions),
11059
+ dependencies: mergeManyDependencies(expressions)
11060
+ }, {
11061
+ kind: "function",
11062
+ name: name2,
11063
+ args: expressions
11064
+ });
11065
+ };
10763
11066
  var uuidGenerateV4 = () => makeExpression2({
10764
11067
  runtime: undefined,
10765
11068
  dbType: postgresDatatypes.uuid(),
@@ -11095,87 +11398,1967 @@ var quoteIdentifier4 = (value) => `"${value.replaceAll('"', '""')}"`;
11095
11398
  var renderIdentifier2 = (value) => safeUnquotedIdentifier2.test(value) ? value : quoteIdentifier4(value);
11096
11399
  var renderQualifiedSequenceName = (value) => value.schemaName === undefined || value.schemaName === "public" ? renderIdentifier2(value.name) : `${renderIdentifier2(value.schemaName)}.${renderIdentifier2(value.name)}`;
11097
11400
  var nextVal2 = (value) => nextVal(isSequenceDefinition(value) ? cast(literal(renderQualifiedSequenceName(value)), type.regclass()) : value);
11098
- // src/postgres/json-extension.ts
11099
- var exports_json_extension = {};
11100
- __export(exports_json_extension, {
11101
- stripNulls: () => stripNulls2,
11102
- pathMatch: () => pathMatch2
11401
+ // src/postgres/function/string.ts
11402
+ var exports_string = {};
11403
+ __export(exports_string, {
11404
+ upper: () => upper,
11405
+ lower: () => lower,
11406
+ concat: () => concat
11407
+ });
11408
+ // src/postgres/function/aggregate.ts
11409
+ var exports_aggregate = {};
11410
+ __export(exports_aggregate, {
11411
+ sum: () => sum,
11412
+ min: () => min,
11413
+ max: () => max,
11414
+ count: () => count,
11415
+ avg: () => avg
11103
11416
  });
11104
11417
 
11105
- // src/postgres/json.ts
11106
- var emptyPath = path();
11107
- var isObjectLike2 = (value) => (typeof value === "object" || typeof value === "function") && value !== null;
11108
- var isExpression5 = (value) => isObjectLike2(value) && (TypeId2 in value);
11109
- var isPath = (value) => isObjectLike2(value) && (TypeId4 in value);
11110
- var isSegment = (value) => isObjectLike2(value) && (SegmentTypeId in value);
11111
- var isTarget = (value) => isPath(value) || isSegment(value);
11112
- var normalizeSegment2 = (segment) => {
11113
- switch (segment.kind) {
11114
- case "key":
11115
- return key(segment.key);
11116
- case "index":
11117
- return index(segment.index);
11118
- case "wildcard":
11119
- return wildcard();
11120
- case "slice":
11121
- return slice(segment.start, segment.end);
11122
- case "descend":
11123
- return descend();
11418
+ // src/internal/dialect-numeric.ts
11419
+ var literal2 = (value, dbType, dialect) => makeExpression2({
11420
+ runtime: value,
11421
+ dbType,
11422
+ driverValueMapping: dbType.driverValueMapping,
11423
+ nullability: "never",
11424
+ dialect,
11425
+ kind: "scalar",
11426
+ dependencies: {}
11427
+ }, {
11428
+ kind: "literal",
11429
+ value
11430
+ });
11431
+ var asExpression = (value, literalDb, dialect) => typeof value === "number" ? literal2(value, literalDb, dialect) : value;
11432
+ var modulo = (left, right, options2) => {
11433
+ const leftExpression = asExpression(left, options2.literalDb, options2.dialect);
11434
+ const rightExpression = asExpression(right, options2.literalDb, options2.dialect);
11435
+ const values2 = [leftExpression, rightExpression];
11436
+ return makeExpression2({
11437
+ runtime: undefined,
11438
+ dbType: options2.resultDb,
11439
+ driverValueMapping: options2.resultDb.driverValueMapping,
11440
+ nullability: options2.nullability,
11441
+ dialect: options2.dialect,
11442
+ kind: mergeAggregationManyRuntime(values2),
11443
+ dependencies: mergeManyDependencies(values2)
11444
+ }, {
11445
+ kind: "modulo",
11446
+ left: leftExpression,
11447
+ right: rightExpression
11448
+ });
11449
+ };
11450
+ var round = (value, scale, options2) => {
11451
+ const expression = asExpression(value, options2.literalDb, options2.dialect);
11452
+ if (scale === undefined) {
11453
+ return makeExpression2({
11454
+ runtime: undefined,
11455
+ dbType: options2.resultDb,
11456
+ driverValueMapping: options2.resultDb.driverValueMapping,
11457
+ nullability: options2.nullability,
11458
+ dialect: options2.dialect,
11459
+ kind: expression[TypeId2].kind,
11460
+ dependencies: expression[TypeId2].dependencies
11461
+ }, {
11462
+ kind: "round",
11463
+ value: expression
11464
+ });
11465
+ }
11466
+ if (!Number.isSafeInteger(scale)) {
11467
+ throw new Error("round scale must be a safe integer");
11124
11468
  }
11469
+ const scaleExpression = literal2(scale, options2.scaleDb, options2.dialect);
11470
+ return makeExpression2({
11471
+ runtime: undefined,
11472
+ dbType: options2.resultDb,
11473
+ driverValueMapping: options2.resultDb.driverValueMapping,
11474
+ nullability: options2.nullability,
11475
+ dialect: options2.dialect,
11476
+ kind: expression[TypeId2].kind,
11477
+ dependencies: expression[TypeId2].dependencies
11478
+ }, {
11479
+ kind: "function",
11480
+ name: "round",
11481
+ args: [expression, scaleExpression]
11482
+ });
11125
11483
  };
11126
- var normalizeTarget = (target) => isPath(target) ? path(...target.segments.map(normalizeSegment2)) : normalizeSegment2(target);
11127
- var accessKinds2 = new Set([
11128
- "jsonGet",
11129
- "jsonPath",
11130
- "jsonAccess",
11131
- "jsonTraverse",
11132
- "jsonGetText",
11133
- "jsonPathText",
11134
- "jsonAccessText",
11135
- "jsonTraverseText"
11136
- ]);
11137
- var accessPathOf2 = (value) => {
11138
- const segments = [];
11139
- let base = value;
11140
- while (isExpression5(base)) {
11141
- const ast = base[TypeId3];
11142
- if (typeof ast.kind !== "string" || !accessKinds2.has(ast.kind) || !isExpression5(ast.base) || !Array.isArray(ast.segments)) {
11143
- break;
11144
- }
11145
- segments.unshift(...ast.segments.map(normalizeSegment2));
11146
- base = ast.base;
11484
+ var aggregate = (kind, value, options2) => {
11485
+ const expression = asExpression(value, options2.literalDb, options2.dialect);
11486
+ return makeExpression2({
11487
+ runtime: undefined,
11488
+ dbType: options2.resultDb,
11489
+ driverValueMapping: options2.resultDb.driverValueMapping,
11490
+ nullability: "maybe",
11491
+ dialect: options2.dialect,
11492
+ kind: "aggregate",
11493
+ dependencies: expression[TypeId2].dependencies
11494
+ }, {
11495
+ kind,
11496
+ value: expression
11497
+ });
11498
+ };
11499
+ var inputNullability = (value) => typeof value === "number" ? "never" : value[TypeId2].nullability;
11500
+ var binaryInputNullability = (left, right) => {
11501
+ const leftNullability = inputNullability(left);
11502
+ const rightNullability = inputNullability(right);
11503
+ if (leftNullability === "always" || rightNullability === "always") {
11504
+ return "always";
11147
11505
  }
11148
- return segments.length === 0 ? undefined : {
11149
- base,
11150
- path: path(...segments)
11506
+ return leftNullability === "maybe" || rightNullability === "maybe" ? "maybe" : "never";
11507
+ };
11508
+ var nullableForZeroDivisor = (left, right) => {
11509
+ const merged = binaryInputNullability(left, right);
11510
+ if (merged === "always") {
11511
+ return "always";
11512
+ }
11513
+ if (typeof right === "number") {
11514
+ return right === 0 ? "always" : merged;
11515
+ }
11516
+ return "maybe";
11517
+ };
11518
+
11519
+ // src/postgres/function/aggregate.ts
11520
+ var baseDb = (db) => ("base" in db) ? baseDb(db.base) : db;
11521
+ var category = (value) => {
11522
+ if (typeof value === "number")
11523
+ return "float8";
11524
+ const db = baseDb(value[TypeId2].dbType);
11525
+ if (db.dialect === "standard") {
11526
+ if (db.kind === "int" || db.kind === "integer")
11527
+ return "int4";
11528
+ if (db.kind === "bigint")
11529
+ return "int8";
11530
+ if (db.kind === "numeric" || db.kind === "decimal")
11531
+ return "numeric";
11532
+ return "float4";
11533
+ }
11534
+ return db.kind;
11535
+ };
11536
+ var sumResultDb = (value) => {
11537
+ const valueCategory = category(value);
11538
+ if (valueCategory === "int2" || valueCategory === "int4") {
11539
+ return postgresDatatypes.int8();
11540
+ }
11541
+ if (valueCategory === "int8" || valueCategory === "numeric") {
11542
+ return postgresDatatypes.numeric();
11543
+ }
11544
+ return valueCategory === "float4" ? postgresDatatypes.float4() : postgresDatatypes.float8();
11545
+ };
11546
+ var avgResultDb = (value) => {
11547
+ const valueCategory = category(value);
11548
+ return valueCategory === "float4" || valueCategory === "float8" ? postgresDatatypes.float8() : postgresDatatypes.numeric();
11549
+ };
11550
+ var sum = (value) => aggregate("sum", value, {
11551
+ dialect: "postgres",
11552
+ literalDb: postgresDatatypes.float8(),
11553
+ resultDb: sumResultDb(value)
11554
+ });
11555
+ var avg = (value) => aggregate("avg", value, {
11556
+ dialect: "postgres",
11557
+ literalDb: postgresDatatypes.float8(),
11558
+ resultDb: avgResultDb(value)
11559
+ });
11560
+ // src/postgres/function/numeric.ts
11561
+ var exports_numeric = {};
11562
+ __export(exports_numeric, {
11563
+ round: () => round2,
11564
+ modulo: () => modulo2
11565
+ });
11566
+ var baseDb2 = (db) => ("base" in db) ? baseDb2(db.base) : db;
11567
+ var moduloCategory = (value) => {
11568
+ if (typeof value === "number") {
11569
+ if (!Number.isSafeInteger(value) || value < -2147483648 || value > 2147483647) {
11570
+ throw new Error("postgres modulo number literals must fit a signed int4");
11571
+ }
11572
+ return "int4";
11573
+ }
11574
+ const db = baseDb2(value[TypeId2].dbType);
11575
+ if (db.dialect === "standard") {
11576
+ if (db.kind === "bigint")
11577
+ return "int8";
11578
+ if (db.kind === "numeric" || db.kind === "decimal")
11579
+ return "numeric";
11580
+ return "int4";
11581
+ }
11582
+ return db.kind;
11583
+ };
11584
+ var moduloResultDb = (left, right) => {
11585
+ const categories = [moduloCategory(left), moduloCategory(right)];
11586
+ if (categories.includes("numeric"))
11587
+ return postgresDatatypes.numeric();
11588
+ if (categories.includes("int8"))
11589
+ return postgresDatatypes.int8();
11590
+ if (categories.includes("int4"))
11591
+ return postgresDatatypes.int4();
11592
+ return postgresDatatypes.int2();
11593
+ };
11594
+ var roundCategory = (value) => {
11595
+ if (typeof value === "number")
11596
+ return "approximate";
11597
+ const db = baseDb2(value[TypeId2].dbType);
11598
+ if (db.kind === "numeric" || db.kind === "decimal")
11599
+ return "exact";
11600
+ if (db.kind === "int" || db.kind === "integer" || db.kind === "bigint" || db.kind === "int2" || db.kind === "int4" || db.kind === "int8") {
11601
+ return "integer";
11602
+ }
11603
+ return "approximate";
11604
+ };
11605
+ var modulo2 = (left, right) => modulo(left, right, {
11606
+ dialect: "postgres",
11607
+ literalDb: postgresDatatypes.int4(),
11608
+ resultDb: moduloResultDb(left, right),
11609
+ nullability: binaryInputNullability(left, right)
11610
+ });
11611
+ var roundRuntime = (value, scale) => {
11612
+ const category2 = roundCategory(value);
11613
+ if (scale !== undefined && category2 === "approximate") {
11614
+ throw new Error("postgres round with a scale requires a numeric or integer input");
11615
+ }
11616
+ const resultDb = scale !== undefined || category2 === "exact" ? postgresDatatypes.numeric() : postgresDatatypes.float8();
11617
+ return round(value, scale, {
11618
+ dialect: "postgres",
11619
+ literalDb: postgresDatatypes.float8(),
11620
+ scaleDb: postgresDatatypes.int4(),
11621
+ resultDb,
11622
+ nullability: typeof value === "number" ? "never" : value[TypeId2].nullability
11623
+ });
11624
+ };
11625
+ var round2 = roundRuntime;
11626
+ // src/postgres/function/window.ts
11627
+ var exports_window = {};
11628
+ __export(exports_window, {
11629
+ rowNumber: () => rowNumber,
11630
+ rank: () => rank,
11631
+ over: () => over,
11632
+ lastValue: () => lastValue2,
11633
+ firstValue: () => firstValue2,
11634
+ denseRank: () => denseRank
11635
+ });
11636
+
11637
+ // src/internal/standard-dsl.ts
11638
+ import { pipeArguments as pipeArguments9 } from "effect/Pipeable";
11639
+ import * as Schema10 from "effect/Schema";
11640
+
11641
+ // src/standard/datatypes/index.ts
11642
+ var exports_datatypes2 = {};
11643
+ __export(exports_datatypes2, {
11644
+ standardDatatypes: () => standardDatatypes
11645
+ });
11646
+
11647
+ // src/standard/datatypes/spec.ts
11648
+ var standardDatatypeFamilies = portableDatatypeFamilies;
11649
+ var standardDatatypeKinds = portableDatatypeKinds;
11650
+
11651
+ // src/standard/datatypes/index.ts
11652
+ var withMetadata2 = (kind) => {
11653
+ const kindSpec = standardDatatypeKinds[kind];
11654
+ const familySpec = standardDatatypeFamilies[kindSpec.family];
11655
+ return {
11656
+ dialect: "standard",
11657
+ kind,
11658
+ family: kindSpec.family,
11659
+ runtime: kindSpec.runtime,
11660
+ compareGroup: familySpec?.compareGroup,
11661
+ castTargets: familySpec?.castTargets,
11662
+ implicitTargets: familySpec.implicitTargets,
11663
+ traits: familySpec?.traits
11151
11664
  };
11152
11665
  };
11153
- var jsonGetDirect = (base, target) => json.get(base, normalizeTarget(target));
11154
- var jsonTextDirect = (base, target) => json.text(base, normalizeTarget(target));
11155
- var jsonbGetDirect = (base, target) => jsonb2.get(base, normalizeTarget(target));
11156
- var jsonbTextDirect = (base, target) => jsonb2.text(base, normalizeTarget(target));
11157
- var jsonbSegmentOperation = (segment) => Object.assign((base) => jsonbGetDirect(base, segment), segment);
11158
- var json2 = {
11159
- get: (...args) => {
11160
- if (args.length === 1) {
11161
- const [first] = args;
11162
- if (isTarget(first)) {
11163
- return (base) => jsonGetDirect(base, first);
11164
- }
11165
- return first;
11166
- }
11167
- return jsonGetDirect(args[0], args[1]);
11168
- },
11169
- access: (base, target) => json.access(base, normalizeTarget(target)),
11170
- traverse: (base, target) => json.traverse(base, normalizeTarget(target)),
11171
- text: (...args) => {
11172
- if (args.length === 1) {
11173
- const [first] = args;
11174
- if (isTarget(first)) {
11175
- return (base) => jsonTextDirect(base, first);
11176
- }
11177
- const access = isExpression5(first) ? accessPathOf2(first) : undefined;
11178
- return access === undefined ? json.text(first, emptyPath) : jsonTextDirect(access.base, access.path);
11666
+ var standardDatatypeModule = {
11667
+ custom: (kind) => ({
11668
+ dialect: "standard",
11669
+ kind
11670
+ }),
11671
+ uuid: () => ({
11672
+ dialect: "standard",
11673
+ kind: "uuid",
11674
+ family: "uuid",
11675
+ runtime: "string",
11676
+ compareGroup: "uuid",
11677
+ castTargets: ["uuid", "char", "varchar", "text"],
11678
+ traits: {
11679
+ textual: true
11680
+ }
11681
+ })
11682
+ };
11683
+ for (const kind of Object.keys(standardDatatypeKinds)) {
11684
+ standardDatatypeModule[kind] = () => withMetadata2(kind);
11685
+ }
11686
+ standardDatatypeModule.json = () => ({
11687
+ ...withMetadata2("json"),
11688
+ driverValueMapping: {
11689
+ toDriver: (value) => JSON.stringify(value)
11690
+ }
11691
+ });
11692
+ var standardDatatypes = {
11693
+ ...standardDatatypeModule
11694
+ };
11695
+
11696
+ // src/internal/standard-dsl.ts
11697
+ var profile2 = {
11698
+ dialect: "standard",
11699
+ textDb: standardDatatypes.text(),
11700
+ numericDb: standardDatatypes.real(),
11701
+ boolDb: standardDatatypes.boolean(),
11702
+ timestampDb: standardDatatypes.timestamp(),
11703
+ nullDb: {
11704
+ dialect: "standard",
11705
+ kind: "null",
11706
+ family: "null",
11707
+ runtime: "unknown",
11708
+ compareGroup: "null",
11709
+ traits: {}
11710
+ },
11711
+ type: standardDatatypes
11712
+ };
11713
+ var ValuesInputProto2 = {
11714
+ pipe() {
11715
+ return pipeArguments9(this, arguments);
11716
+ }
11717
+ };
11718
+ var literalSchemaOf2 = (value) => {
11719
+ if (value === null || value instanceof Date) {
11720
+ return;
11721
+ }
11722
+ if (typeof value === "number" && !Number.isFinite(value)) {
11723
+ return;
11724
+ }
11725
+ return Schema10.Literal(value);
11726
+ };
11727
+ var literal3 = (value) => makeExpression2({
11728
+ runtime: undefined,
11729
+ dbType: value === null ? profile2.nullDb : value instanceof Date ? profile2.timestampDb : typeof value === "string" ? profile2.textDb : typeof value === "number" ? profile2.numericDb : profile2.boolDb,
11730
+ runtimeSchema: literalSchemaOf2(value),
11731
+ nullability: value === null ? "always" : "never",
11732
+ dialect: profile2.dialect,
11733
+ kind: "scalar",
11734
+ dependencies: {}
11735
+ }, {
11736
+ kind: "literal",
11737
+ value
11738
+ });
11739
+ var column = (name2, dbType, nullable2 = false) => makeExpression2({
11740
+ runtime: undefined,
11741
+ dbType,
11742
+ nullability: nullable2 ? "maybe" : "never",
11743
+ dialect: profile2.dialect,
11744
+ kind: "scalar",
11745
+ dependencies: {}
11746
+ }, {
11747
+ kind: "column",
11748
+ tableName: "",
11749
+ columnName: name2
11750
+ });
11751
+ var toDialectExpression2 = (value) => {
11752
+ if (value !== null && typeof value === "object" && TypeId2 in value) {
11753
+ return value;
11754
+ }
11755
+ return literal3(value);
11756
+ };
11757
+ var retargetLiteralExpression2 = (value, target) => {
11758
+ const ast = value[TypeId3];
11759
+ if (ast.kind !== "literal") {
11760
+ return value;
11761
+ }
11762
+ const targetState = target[TypeId2];
11763
+ return makeExpression2({
11764
+ runtime: value[TypeId2].runtime,
11765
+ dbType: targetState.dbType,
11766
+ runtimeSchema: targetState.runtimeSchema,
11767
+ driverValueMapping: targetState.driverValueMapping,
11768
+ nullability: value[TypeId2].nullability,
11769
+ dialect: targetState.dialect,
11770
+ kind: "scalar",
11771
+ dependencies: {}
11772
+ }, ast);
11773
+ };
11774
+ var alignBinaryPredicateExpressions2 = (left, right) => {
11775
+ const leftAst = left[TypeId3];
11776
+ const rightAst = right[TypeId3];
11777
+ if (leftAst.kind === "literal" && rightAst.kind !== "literal") {
11778
+ return [retargetLiteralExpression2(left, right), right];
11779
+ }
11780
+ if (rightAst.kind === "literal" && leftAst.kind !== "literal") {
11781
+ return [left, retargetLiteralExpression2(right, left)];
11782
+ }
11783
+ return [left, right];
11784
+ };
11785
+ var toDialectStringExpression2 = (value) => typeof value === "string" ? literal3(value) : value;
11786
+ var toDialectNumericExpression2 = (value) => typeof value === "number" ? literal3(value) : value;
11787
+ var flattenVariadicBooleanExpressions = (kind, values2) => {
11788
+ const flattened = [];
11789
+ for (const value of values2) {
11790
+ const ast = value[TypeId3];
11791
+ if (ast.kind === kind) {
11792
+ flattened.push(...ast.values);
11793
+ } else {
11794
+ flattened.push(value);
11795
+ }
11796
+ }
11797
+ return flattened;
11798
+ };
11799
+ var makeVariadicBooleanExpression = (kind, values2) => {
11800
+ const expressions = flattenVariadicBooleanExpressions(kind, values2);
11801
+ const expression = makeExpression2({
11802
+ runtime: true,
11803
+ dbType: profile2.boolDb,
11804
+ nullability: mergeNullabilityManyRuntime(expressions),
11805
+ dialect: expressions.find((value) => value[TypeId2].dialect !== undefined)?.[TypeId2].dialect ?? profile2.dialect,
11806
+ kind: "scalar",
11807
+ dependencies: mergeManyDependencies(expressions)
11808
+ }, {
11809
+ kind,
11810
+ values: expressions
11811
+ });
11812
+ Object.defineProperty(expression, "pipe", {
11813
+ configurable: true,
11814
+ writable: true,
11815
+ value() {
11816
+ if (arguments.length === 0) {
11817
+ return this;
11818
+ }
11819
+ const operations = Array.from(arguments);
11820
+ if (operations.every((operation) => typeof operation !== "function")) {
11821
+ const appended = operations.map((operation) => toDialectExpression2(operation));
11822
+ return makeVariadicBooleanExpression(kind, [...expressions, ...appended]);
11823
+ }
11824
+ if (operations.every((operation) => typeof operation === "function")) {
11825
+ return pipeArguments9(this, arguments);
11826
+ }
11827
+ const valuesForMixedPipe = (value) => {
11828
+ if (typeof value !== "object" || value === null || !(TypeId2 in value)) {
11829
+ return [];
11830
+ }
11831
+ const expression2 = value;
11832
+ const ast = expression2[TypeId3];
11833
+ if (ast.kind === kind) {
11834
+ return ast.values;
11835
+ }
11836
+ return [expression2];
11837
+ };
11838
+ let current = this;
11839
+ for (const operation of operations) {
11840
+ if (typeof operation === "function") {
11841
+ current = operation(current);
11842
+ continue;
11843
+ }
11844
+ current = makeVariadicBooleanExpression(kind, [...valuesForMixedPipe(current), toDialectExpression2(operation)]);
11845
+ }
11846
+ return current;
11847
+ }
11848
+ });
11849
+ return expression;
11850
+ };
11851
+ var extractRequiredFromDialectInputRuntime2 = (value) => {
11852
+ const expression = toDialectExpression2(value);
11853
+ return Object.keys(expression[TypeId2].dependencies);
11854
+ };
11855
+ var normalizeWindowSpec2 = (spec) => {
11856
+ if (spec?.frame !== undefined) {
11857
+ throw new Error("over does not accept an explicit frame on the portable Function API; use a dialect Function.over helper");
11858
+ }
11859
+ validateWindowFrame(spec?.frame);
11860
+ const partitionBy = [...spec?.partitionBy ?? []];
11861
+ const orderBy2 = (spec?.orderBy ?? []).map((term) => {
11862
+ const direction = term.direction ?? "asc";
11863
+ return {
11864
+ value: term.value,
11865
+ direction
11866
+ };
11867
+ });
11868
+ return {
11869
+ partitionBy,
11870
+ orderBy: orderBy2,
11871
+ frame: spec?.frame
11872
+ };
11873
+ };
11874
+ var mergeWindowExpressions2 = (value, partitionBy, orderBy2) => value === undefined ? [...partitionBy, ...orderBy2.map((term) => term.value)] : [value, ...partitionBy, ...orderBy2.map((term) => term.value)];
11875
+ var extractRequiredFromDialectNumericInputRuntime2 = (value) => {
11876
+ const expression = toDialectNumericExpression2(value);
11877
+ return Object.keys(expression[TypeId2].dependencies);
11878
+ };
11879
+ var buildBinaryPredicate2 = (left, right, kind, nullability = "maybe") => {
11880
+ const [leftExpression, rightExpression] = alignBinaryPredicateExpressions2(toDialectExpression2(left), toDialectExpression2(right));
11881
+ return makeExpression2({
11882
+ runtime: true,
11883
+ dbType: profile2.boolDb,
11884
+ nullability,
11885
+ dialect: leftExpression[TypeId2].dialect ?? rightExpression[TypeId2].dialect,
11886
+ kind: "scalar",
11887
+ dependencies: mergeDependencies(leftExpression[TypeId2].dependencies, rightExpression[TypeId2].dependencies)
11888
+ }, {
11889
+ kind,
11890
+ left: leftExpression,
11891
+ right: rightExpression
11892
+ });
11893
+ };
11894
+ var buildVariadicPredicate = (values2, kind) => {
11895
+ const expressions = values2.map((value) => toDialectExpression2(value));
11896
+ const [head, ...tail] = expressions;
11897
+ const alignedExpressions = head !== undefined && (kind === "in" || kind === "notIn" || kind === "between") ? [head, ...tail.map((value) => retargetLiteralExpression2(value, head))] : expressions;
11898
+ return makeExpression2({
11899
+ runtime: true,
11900
+ dbType: profile2.boolDb,
11901
+ nullability: "maybe",
11902
+ dialect: alignedExpressions.find((value) => value[TypeId2].dialect !== undefined)?.[TypeId2].dialect ?? profile2.dialect,
11903
+ kind: "scalar",
11904
+ dependencies: mergeManyDependencies(alignedExpressions)
11905
+ }, {
11906
+ kind,
11907
+ values: alignedExpressions
11908
+ });
11909
+ };
11910
+ var eq = (...args) => {
11911
+ const left = args[0];
11912
+ const right = args[1];
11913
+ return buildBinaryPredicate2(left, right, "eq");
11914
+ };
11915
+ var neq = (...args) => {
11916
+ const left = args[0];
11917
+ const right = args[1];
11918
+ return buildBinaryPredicate2(left, right, "neq");
11919
+ };
11920
+ var lt = (...args) => {
11921
+ const left = args[0];
11922
+ const right = args[1];
11923
+ return buildBinaryPredicate2(left, right, "lt");
11924
+ };
11925
+ var lte = (...args) => {
11926
+ const left = args[0];
11927
+ const right = args[1];
11928
+ return buildBinaryPredicate2(left, right, "lte");
11929
+ };
11930
+ var gt = (...args) => {
11931
+ const left = args[0];
11932
+ const right = args[1];
11933
+ return buildBinaryPredicate2(left, right, "gt");
11934
+ };
11935
+ var gte = (...args) => {
11936
+ const left = args[0];
11937
+ const right = args[1];
11938
+ return buildBinaryPredicate2(left, right, "gte");
11939
+ };
11940
+ var like = (...args) => {
11941
+ const left = args[0];
11942
+ const right = args[1];
11943
+ return buildBinaryPredicate2(left, right, "like");
11944
+ };
11945
+ var ilike = (...args) => {
11946
+ const left = args[0];
11947
+ const right = args[1];
11948
+ return buildBinaryPredicate2(left, right, "ilike");
11949
+ };
11950
+ var regexMatch = (...args) => {
11951
+ const left = args[0];
11952
+ const right = args[1];
11953
+ return buildBinaryPredicate2(left, right, "regexMatch");
11954
+ };
11955
+ var regexIMatch = (...args) => {
11956
+ const left = args[0];
11957
+ const right = args[1];
11958
+ return buildBinaryPredicate2(left, right, "regexIMatch");
11959
+ };
11960
+ var regexNotMatch = (...args) => {
11961
+ const left = args[0];
11962
+ const right = args[1];
11963
+ return buildBinaryPredicate2(left, right, "regexNotMatch");
11964
+ };
11965
+ var regexNotIMatch = (...args) => {
11966
+ const left = args[0];
11967
+ const right = args[1];
11968
+ return buildBinaryPredicate2(left, right, "regexNotIMatch");
11969
+ };
11970
+ var isDistinctFrom = (...args) => {
11971
+ const left = args[0];
11972
+ const right = args[1];
11973
+ return buildBinaryPredicate2(left, right, "isDistinctFrom", "never");
11974
+ };
11975
+ var isNotDistinctFrom = (...args) => {
11976
+ const left = args[0];
11977
+ const right = args[1];
11978
+ return buildBinaryPredicate2(left, right, "isNotDistinctFrom", "never");
11979
+ };
11980
+ var isNull = (value) => {
11981
+ const expression = toDialectExpression2(value);
11982
+ return makeExpression2({
11983
+ runtime: true,
11984
+ dbType: profile2.boolDb,
11985
+ nullability: "never",
11986
+ dialect: expression[TypeId2].dialect,
11987
+ kind: "scalar",
11988
+ dependencies: expression[TypeId2].dependencies
11989
+ }, {
11990
+ kind: "isNull",
11991
+ value: expression
11992
+ });
11993
+ };
11994
+ var isNotNull = (value) => {
11995
+ const expression = toDialectExpression2(value);
11996
+ return makeExpression2({
11997
+ runtime: true,
11998
+ dbType: profile2.boolDb,
11999
+ nullability: "never",
12000
+ dialect: expression[TypeId2].dialect,
12001
+ kind: "scalar",
12002
+ dependencies: expression[TypeId2].dependencies
12003
+ }, {
12004
+ kind: "isNotNull",
12005
+ value: expression
12006
+ });
12007
+ };
12008
+ var collate = (value, collation) => {
12009
+ const expression = toDialectStringExpression2(value);
12010
+ const normalizedCollation = typeof collation === "string" ? [collation] : collation;
12011
+ return makeExpression2({
12012
+ runtime: expression[TypeId2].runtime,
12013
+ dbType: expression[TypeId2].dbType,
12014
+ nullability: expression[TypeId2].nullability,
12015
+ dialect: expression[TypeId2].dialect,
12016
+ kind: expression[TypeId2].kind,
12017
+ dependencies: expression[TypeId2].dependencies
12018
+ }, {
12019
+ kind: "collate",
12020
+ value: expression,
12021
+ collation: normalizedCollation
12022
+ });
12023
+ };
12024
+ var cast2 = (value, target) => {
12025
+ const expression = toDialectExpression2(value);
12026
+ return makeExpression2({
12027
+ runtime: undefined,
12028
+ dbType: target,
12029
+ runtimeSchema: undefined,
12030
+ driverValueMapping: target.driverValueMapping,
12031
+ nullability: expression[TypeId2].nullability,
12032
+ dialect: expression[TypeId2].dialect,
12033
+ kind: expression[TypeId2].kind,
12034
+ dependencies: expression[TypeId2].dependencies
12035
+ }, {
12036
+ kind: "cast",
12037
+ value: expression,
12038
+ target
12039
+ });
12040
+ };
12041
+ var custom3 = (kind) => ({
12042
+ dialect: profile2.dialect,
12043
+ kind
12044
+ });
12045
+ var driverValueMapping3 = (dbType, mapping) => ({
12046
+ ...dbType,
12047
+ driverValueMapping: mapping
12048
+ });
12049
+ var type2 = {
12050
+ ...profile2.type,
12051
+ custom: custom3,
12052
+ driverValueMapping: driverValueMapping3
12053
+ };
12054
+ var makeJsonDb2 = (kind) => ({
12055
+ dialect: profile2.dialect,
12056
+ kind,
12057
+ variant: kind === "jsonb" ? "jsonb" : "json"
12058
+ });
12059
+ var jsonDb2 = makeJsonDb2("json");
12060
+ var jsonbDb2 = makeJsonDb2("jsonb");
12061
+ var isExpressionValue2 = (value) => value !== null && typeof value === "object" && (TypeId2 in value);
12062
+ var isJsonExpressionValue2 = (value) => isExpressionValue2(value) && (() => {
12063
+ const dbType = value[TypeId2].dbType;
12064
+ return dbType.variant === "json" || dbType.kind === "json" || dbType.kind === "jsonb";
12065
+ })();
12066
+ var isJsonPathValue3 = (value) => value !== null && typeof value === "object" && (TypeId4 in value);
12067
+ var normalizeJsonPathInput2 = (value) => isJsonPathValue3(value) ? value.segments : [value];
12068
+ var isExactJsonSegmentValue2 = (segment) => segment.kind === "key" || segment.kind === "index";
12069
+ var isExactJsonPathValue2 = (segments) => segments.every(isExactJsonSegmentValue2);
12070
+ var buildJsonNodeExpression2 = (expressions, state, ast) => withJsonPathAccess(makeExpression2({
12071
+ runtime: state.runtime,
12072
+ dbType: state.dbType,
12073
+ nullability: state.nullability,
12074
+ dialect: expressions.find((expression) => expression[TypeId2].dialect !== undefined)?.[TypeId2].dialect ?? profile2.dialect,
12075
+ kind: mergeAggregationManyRuntime(expressions),
12076
+ dependencies: mergeManyDependencies(expressions)
12077
+ }, ast));
12078
+ var jsonDbTypeOf2 = (base) => base[TypeId2].dbType;
12079
+ var resolveJsonMergeDbType2 = (..._values) => jsonbDb2;
12080
+ var makeJsonLiteralExpression2 = (value, dbType = jsonDb2) => withJsonPathAccess(makeExpression2({
12081
+ runtime: value,
12082
+ dbType,
12083
+ nullability: value === null ? "always" : "never",
12084
+ dialect: profile2.dialect,
12085
+ kind: "scalar",
12086
+ dependencies: {}
12087
+ }, {
12088
+ kind: "literal",
12089
+ value
12090
+ }));
12091
+ var wrapJsonExpression2 = (value, kind, dbType) => buildJsonNodeExpression2([value], {
12092
+ runtime: undefined,
12093
+ dbType,
12094
+ nullability: value[TypeId2].nullability
12095
+ }, {
12096
+ kind,
12097
+ value
12098
+ });
12099
+ var toJsonValueExpression2 = (value, kind = "jsonToJson", dbType = jsonDb2) => {
12100
+ if (isJsonExpressionValue2(value)) {
12101
+ return value;
12102
+ }
12103
+ if (isExpressionValue2(value)) {
12104
+ return wrapJsonExpression2(value, kind, dbType);
12105
+ }
12106
+ return makeJsonLiteralExpression2(value, dbType);
12107
+ };
12108
+ var jsonQueryExpression2 = (query) => toDialectStringExpression2(query);
12109
+ var jsonGet2 = (base, target) => {
12110
+ const segments = normalizeJsonPathInput2(target);
12111
+ const kind = isJsonPathValue3(target) ? isExactJsonPathValue2(segments) ? "jsonPath" : "jsonTraverse" : isExactJsonSegmentValue2(target) ? "jsonGet" : "jsonAccess";
12112
+ return buildJsonNodeExpression2([base], {
12113
+ runtime: undefined,
12114
+ dbType: jsonDbTypeOf2(base),
12115
+ nullability: undefined
12116
+ }, {
12117
+ kind,
12118
+ base,
12119
+ segments
12120
+ });
12121
+ };
12122
+ var jsonText2 = (base, target) => {
12123
+ const segments = normalizeJsonPathInput2(target);
12124
+ const kind = isJsonPathValue3(target) ? isExactJsonPathValue2(segments) ? "jsonPathText" : "jsonTraverseText" : isExactJsonSegmentValue2(target) ? "jsonGetText" : "jsonAccessText";
12125
+ return buildJsonNodeExpression2([base], {
12126
+ runtime: undefined,
12127
+ dbType: profile2.textDb,
12128
+ nullability: undefined
12129
+ }, {
12130
+ kind,
12131
+ base,
12132
+ segments
12133
+ });
12134
+ };
12135
+ var jsonAccess2 = (base, target) => {
12136
+ const segments = normalizeJsonPathInput2(target);
12137
+ return buildJsonNodeExpression2([base], {
12138
+ runtime: undefined,
12139
+ dbType: jsonDbTypeOf2(base),
12140
+ nullability: undefined
12141
+ }, {
12142
+ kind: isJsonPathValue3(target) || segments.length > 1 ? "jsonTraverse" : "jsonAccess",
12143
+ base,
12144
+ segments
12145
+ });
12146
+ };
12147
+ var jsonTraverse2 = (base, target) => {
12148
+ const segments = normalizeJsonPathInput2(target);
12149
+ return buildJsonNodeExpression2([base], {
12150
+ runtime: undefined,
12151
+ dbType: jsonDbTypeOf2(base),
12152
+ nullability: undefined
12153
+ }, {
12154
+ kind: "jsonTraverse",
12155
+ base,
12156
+ segments
12157
+ });
12158
+ };
12159
+ var jsonAccessText2 = (base, target) => {
12160
+ const segments = normalizeJsonPathInput2(target);
12161
+ return buildJsonNodeExpression2([base], {
12162
+ runtime: undefined,
12163
+ dbType: profile2.textDb,
12164
+ nullability: undefined
12165
+ }, {
12166
+ kind: isJsonPathValue3(target) || segments.length > 1 ? "jsonTraverseText" : "jsonAccessText",
12167
+ base,
12168
+ segments
12169
+ });
12170
+ };
12171
+ var jsonTraverseText2 = (base, target) => {
12172
+ const segments = normalizeJsonPathInput2(target);
12173
+ return buildJsonNodeExpression2([base], {
12174
+ runtime: undefined,
12175
+ dbType: profile2.textDb,
12176
+ nullability: undefined
12177
+ }, {
12178
+ kind: "jsonTraverseText",
12179
+ base,
12180
+ segments
12181
+ });
12182
+ };
12183
+ var jsonContains2 = (left, right) => buildBinaryPredicate2(left, toJsonValueExpression2(right), "contains");
12184
+ var jsonContainedBy2 = (left, right) => buildBinaryPredicate2(left, toJsonValueExpression2(right), "containedBy");
12185
+ var jsonHasKey2 = (base, key2) => buildJsonNodeExpression2([base], {
12186
+ runtime: true,
12187
+ dbType: profile2.boolDb,
12188
+ nullability: "never"
12189
+ }, {
12190
+ kind: "jsonHasKey",
12191
+ base,
12192
+ keys: [key2]
12193
+ });
12194
+ var jsonHasAnyKeys2 = (base, ...keys) => buildJsonNodeExpression2([base], {
12195
+ runtime: true,
12196
+ dbType: profile2.boolDb,
12197
+ nullability: "never"
12198
+ }, {
12199
+ kind: "jsonHasAnyKeys",
12200
+ base,
12201
+ keys
12202
+ });
12203
+ var jsonHasAllKeys2 = (base, ...keys) => buildJsonNodeExpression2([base], {
12204
+ runtime: true,
12205
+ dbType: profile2.boolDb,
12206
+ nullability: "never"
12207
+ }, {
12208
+ kind: "jsonHasAllKeys",
12209
+ base,
12210
+ keys
12211
+ });
12212
+ var jsonDelete2 = (base, target) => {
12213
+ const segments = normalizeJsonPathInput2(target);
12214
+ return buildJsonNodeExpression2([base], {
12215
+ runtime: undefined,
12216
+ dbType: jsonDbTypeOf2(base),
12217
+ nullability: undefined
12218
+ }, {
12219
+ kind: isJsonPathValue3(target) ? "jsonDeletePath" : "jsonDelete",
12220
+ base,
12221
+ segments
12222
+ });
12223
+ };
12224
+ var jsonRemove2 = (base, target) => {
12225
+ const segments = normalizeJsonPathInput2(target);
12226
+ return buildJsonNodeExpression2([base], {
12227
+ runtime: undefined,
12228
+ dbType: jsonDbTypeOf2(base),
12229
+ nullability: undefined
12230
+ }, {
12231
+ kind: "jsonRemove",
12232
+ base,
12233
+ segments
12234
+ });
12235
+ };
12236
+ var jsonSet2 = (base, target, next, options2 = {}) => {
12237
+ const segments = normalizeJsonPathInput2(target);
12238
+ const newValue = toJsonValueExpression2(next);
12239
+ return buildJsonNodeExpression2([base, newValue], {
12240
+ runtime: undefined,
12241
+ dbType: jsonDbTypeOf2(base),
12242
+ nullability: undefined
12243
+ }, {
12244
+ kind: "jsonSet",
12245
+ base,
12246
+ segments,
12247
+ newValue,
12248
+ createMissing: options2.createMissing ?? true
12249
+ });
12250
+ };
12251
+ var jsonInsert2 = (base, target, next, options2 = {}) => {
12252
+ const segments = normalizeJsonPathInput2(target);
12253
+ const insert = toJsonValueExpression2(next);
12254
+ const insertAfter = options2.insertAfter ?? false;
12255
+ return buildJsonNodeExpression2([base, insert], {
12256
+ runtime: undefined,
12257
+ dbType: jsonDbTypeOf2(base),
12258
+ nullability: undefined
12259
+ }, {
12260
+ kind: "jsonInsert",
12261
+ base,
12262
+ segments,
12263
+ insert,
12264
+ insertAfter
12265
+ });
12266
+ };
12267
+ var jsonConcatAs2 = (dbType) => (left, right) => {
12268
+ const leftExpression = toJsonValueExpression2(left);
12269
+ const rightExpression = toJsonValueExpression2(right);
12270
+ return buildJsonNodeExpression2([leftExpression, rightExpression], {
12271
+ runtime: undefined,
12272
+ dbType,
12273
+ nullability: "maybe"
12274
+ }, {
12275
+ kind: "jsonConcat",
12276
+ left: leftExpression,
12277
+ right: rightExpression
12278
+ });
12279
+ };
12280
+ var jsonMergeAs2 = (dbType) => (left, right) => {
12281
+ const leftExpression = toJsonValueExpression2(left);
12282
+ const rightExpression = toJsonValueExpression2(right);
12283
+ return buildJsonNodeExpression2([leftExpression, rightExpression], {
12284
+ runtime: undefined,
12285
+ dbType,
12286
+ nullability: "maybe"
12287
+ }, {
12288
+ kind: "jsonMerge",
12289
+ left: leftExpression,
12290
+ right: rightExpression
12291
+ });
12292
+ };
12293
+ var jsonConcat2 = jsonConcatAs2(resolveJsonMergeDbType2());
12294
+ var jsonMerge2 = jsonMergeAs2(resolveJsonMergeDbType2());
12295
+ var jsonKeyExists2 = (base, key2) => buildJsonNodeExpression2([base], {
12296
+ runtime: true,
12297
+ dbType: profile2.boolDb,
12298
+ nullability: "never"
12299
+ }, {
12300
+ kind: "jsonKeyExists",
12301
+ base,
12302
+ keys: [key2]
12303
+ });
12304
+ var jsonBuildObjectAs2 = (dbType) => (shape) => {
12305
+ const entries = Object.entries(shape).map(([key2, value]) => ({
12306
+ key: key2,
12307
+ value: toJsonValueExpression2(value)
12308
+ }));
12309
+ return buildJsonNodeExpression2(entries.map((entry) => entry.value), {
12310
+ runtime: {},
12311
+ dbType,
12312
+ nullability: "never"
12313
+ }, {
12314
+ kind: "jsonBuildObject",
12315
+ entries
12316
+ });
12317
+ };
12318
+ var jsonBuildArrayAs2 = (dbType) => (...values2) => {
12319
+ const expressions = values2.map((value) => toJsonValueExpression2(value));
12320
+ return buildJsonNodeExpression2(expressions, {
12321
+ runtime: [],
12322
+ dbType,
12323
+ nullability: "never"
12324
+ }, {
12325
+ kind: "jsonBuildArray",
12326
+ values: expressions
12327
+ });
12328
+ };
12329
+ var jsonBuildObject2 = jsonBuildObjectAs2(jsonDb2);
12330
+ var jsonBuildArray2 = jsonBuildArrayAs2(jsonDb2);
12331
+ var jsonbBuildObject2 = jsonBuildObjectAs2(jsonbDb2);
12332
+ var jsonbBuildArray2 = jsonBuildArrayAs2(jsonbDb2);
12333
+ var jsonToJson2 = (value) => toJsonValueExpression2(value, "jsonToJson", jsonDb2);
12334
+ var jsonToJsonb2 = (value) => toJsonValueExpression2(value, "jsonToJsonb", jsonbDb2);
12335
+ var jsonTypeOf2 = (base) => buildJsonNodeExpression2([base], {
12336
+ runtime: undefined,
12337
+ dbType: profile2.textDb,
12338
+ nullability: base[TypeId2].nullability
12339
+ }, {
12340
+ kind: "jsonTypeOf",
12341
+ value: base
12342
+ });
12343
+ var jsonLength2 = (base) => buildJsonNodeExpression2([base], {
12344
+ runtime: undefined,
12345
+ dbType: profile2.numericDb,
12346
+ nullability: undefined
12347
+ }, {
12348
+ kind: "jsonLength",
12349
+ value: base
12350
+ });
12351
+ var jsonKeys2 = (base) => buildJsonNodeExpression2([base], {
12352
+ runtime: undefined,
12353
+ dbType: jsonDb2,
12354
+ nullability: undefined
12355
+ }, {
12356
+ kind: "jsonKeys",
12357
+ value: base
12358
+ });
12359
+ var jsonPathExists2 = (base, query) => {
12360
+ if (isJsonPathValue3(query)) {
12361
+ return buildJsonNodeExpression2([base], {
12362
+ runtime: true,
12363
+ dbType: profile2.boolDb,
12364
+ nullability: "never"
12365
+ }, {
12366
+ kind: "jsonPathExists",
12367
+ base,
12368
+ query
12369
+ });
12370
+ }
12371
+ const queryExpression = jsonQueryExpression2(query);
12372
+ return buildJsonNodeExpression2([base, queryExpression], {
12373
+ runtime: true,
12374
+ dbType: profile2.boolDb,
12375
+ nullability: "never"
12376
+ }, {
12377
+ kind: "jsonPathExists",
12378
+ base,
12379
+ query: queryExpression
12380
+ });
12381
+ };
12382
+ var jsonStripNulls2 = (base) => buildJsonNodeExpression2([base], {
12383
+ runtime: undefined,
12384
+ dbType: jsonDbTypeOf2(base),
12385
+ nullability: undefined
12386
+ }, {
12387
+ kind: "jsonStripNulls",
12388
+ value: base
12389
+ });
12390
+ var jsonPathMatch2 = (base, query) => {
12391
+ if (isJsonPathValue3(query)) {
12392
+ return buildJsonNodeExpression2([base], {
12393
+ runtime: true,
12394
+ dbType: profile2.boolDb,
12395
+ nullability: "never"
12396
+ }, {
12397
+ kind: "jsonPathMatch",
12398
+ base,
12399
+ query
12400
+ });
12401
+ }
12402
+ const queryExpression = jsonQueryExpression2(query);
12403
+ return buildJsonNodeExpression2([base, queryExpression], {
12404
+ runtime: true,
12405
+ dbType: profile2.boolDb,
12406
+ nullability: "never"
12407
+ }, {
12408
+ kind: "jsonPathMatch",
12409
+ base,
12410
+ query: queryExpression
12411
+ });
12412
+ };
12413
+ var json2 = {
12414
+ key,
12415
+ index,
12416
+ wildcard,
12417
+ slice,
12418
+ descend,
12419
+ path,
12420
+ get: jsonGet2,
12421
+ access: jsonAccess2,
12422
+ traverse: jsonTraverse2,
12423
+ text: jsonText2,
12424
+ accessText: jsonAccessText2,
12425
+ traverseText: jsonTraverseText2,
12426
+ contains: jsonContains2,
12427
+ containedBy: jsonContainedBy2,
12428
+ hasKey: jsonHasKey2,
12429
+ keyExists: jsonKeyExists2,
12430
+ hasAnyKeys: jsonHasAnyKeys2,
12431
+ hasAllKeys: jsonHasAllKeys2,
12432
+ delete: jsonDelete2,
12433
+ remove: jsonRemove2,
12434
+ set: jsonSet2,
12435
+ insert: jsonInsert2,
12436
+ concat: jsonConcat2,
12437
+ merge: jsonMerge2,
12438
+ buildObject: jsonBuildObject2,
12439
+ buildArray: jsonBuildArray2,
12440
+ toJson: jsonToJson2,
12441
+ toJsonb: jsonToJsonb2,
12442
+ typeOf: jsonTypeOf2,
12443
+ length: jsonLength2,
12444
+ keys: jsonKeys2,
12445
+ stripNulls: jsonStripNulls2,
12446
+ pathExists: jsonPathExists2,
12447
+ pathMatch: jsonPathMatch2
12448
+ };
12449
+ var jsonb3 = {
12450
+ key,
12451
+ index,
12452
+ wildcard,
12453
+ slice,
12454
+ descend,
12455
+ path,
12456
+ get: jsonGet2,
12457
+ access: jsonAccess2,
12458
+ traverse: jsonTraverse2,
12459
+ text: jsonText2,
12460
+ accessText: jsonAccessText2,
12461
+ traverseText: jsonTraverseText2,
12462
+ contains: jsonContains2,
12463
+ containedBy: jsonContainedBy2,
12464
+ hasKey: jsonHasKey2,
12465
+ keyExists: jsonKeyExists2,
12466
+ hasAnyKeys: jsonHasAnyKeys2,
12467
+ hasAllKeys: jsonHasAllKeys2,
12468
+ delete: jsonDelete2,
12469
+ remove: jsonRemove2,
12470
+ set: jsonSet2,
12471
+ insert: jsonInsert2,
12472
+ concat: jsonConcatAs2(jsonbDb2),
12473
+ merge: jsonMergeAs2(jsonbDb2),
12474
+ buildObject: jsonbBuildObject2,
12475
+ buildArray: jsonbBuildArray2,
12476
+ toJsonb: jsonToJsonb2,
12477
+ typeOf: jsonTypeOf2,
12478
+ length: jsonLength2,
12479
+ keys: jsonKeys2,
12480
+ stripNulls: jsonStripNulls2,
12481
+ pathExists: jsonPathExists2,
12482
+ pathMatch: jsonPathMatch2
12483
+ };
12484
+ var and = (...values2) => makeVariadicBooleanExpression("and", values2.map((value) => toDialectExpression2(value)));
12485
+ var or = (...values2) => makeVariadicBooleanExpression("or", values2.map((value) => toDialectExpression2(value)));
12486
+ var not = (value) => {
12487
+ const expression = toDialectExpression2(value);
12488
+ return makeExpression2({
12489
+ runtime: true,
12490
+ dbType: profile2.boolDb,
12491
+ nullability: expression[TypeId2].nullability,
12492
+ dialect: expression[TypeId2].dialect,
12493
+ kind: expression[TypeId2].kind,
12494
+ dependencies: expression[TypeId2].dependencies
12495
+ }, {
12496
+ kind: "not",
12497
+ value: expression
12498
+ });
12499
+ };
12500
+ var in_ = (head, ...tail) => buildVariadicPredicate([head, ...tail], "in");
12501
+ var notIn = (head, ...tail) => buildVariadicPredicate([head, ...tail], "notIn");
12502
+ var between = (...values2) => buildVariadicPredicate(values2, "between");
12503
+ var contains = (...args) => {
12504
+ const left = args[0];
12505
+ const right = args[1];
12506
+ return buildBinaryPredicate2(left, right, "contains");
12507
+ };
12508
+ var containedBy = (...args) => {
12509
+ const left = args[0];
12510
+ const right = args[1];
12511
+ return buildBinaryPredicate2(left, right, "containedBy");
12512
+ };
12513
+ var overlaps = (...args) => {
12514
+ const left = args[0];
12515
+ const right = args[1];
12516
+ return buildBinaryPredicate2(left, right, "overlaps");
12517
+ };
12518
+ var concat2 = (...values2) => {
12519
+ const expressions = values2.map((value) => toDialectStringExpression2(value));
12520
+ return makeExpression2({
12521
+ runtime: "",
12522
+ dbType: profile2.textDb,
12523
+ nullability: mergeNullabilityManyRuntime(expressions),
12524
+ dialect: expressions.find((value) => value[TypeId2].dialect !== undefined)?.[TypeId2].dialect ?? profile2.dialect,
12525
+ kind: mergeAggregationManyRuntime(expressions),
12526
+ dependencies: mergeManyDependencies(expressions)
12527
+ }, {
12528
+ kind: "concat",
12529
+ values: expressions
12530
+ });
12531
+ };
12532
+ var all_ = (...values2) => and(...values2);
12533
+ var any_ = (...values2) => or(...values2);
12534
+ var count2 = (value) => {
12535
+ const expression = toDialectExpression2(value);
12536
+ return makeExpression2({
12537
+ runtime: undefined,
12538
+ dbType: standardDatatypes.bigint(),
12539
+ nullability: "never",
12540
+ dialect: expression[TypeId2].dialect,
12541
+ kind: "aggregate",
12542
+ dependencies: expression[TypeId2].dependencies
12543
+ }, {
12544
+ kind: "count",
12545
+ value: expression
12546
+ });
12547
+ };
12548
+ var exists = (plan) => {
12549
+ const dependencies = Object.fromEntries(currentRequiredList(plan[TypeId].required).map((name2) => [name2, true]));
12550
+ return makeExpression2({
12551
+ runtime: true,
12552
+ dbType: profile2.boolDb,
12553
+ nullability: "never",
12554
+ dialect: profile2.dialect,
12555
+ kind: "scalar",
12556
+ dependencies
12557
+ }, {
12558
+ kind: "exists",
12559
+ plan
12560
+ });
12561
+ };
12562
+ var scalar = (plan) => {
12563
+ const dependencies = Object.fromEntries(currentRequiredList(plan[TypeId].required).map((name2) => [name2, true]));
12564
+ const expression = extractSingleSelectedExpressionRuntime(plan[TypeId].selection);
12565
+ return makeExpression2({
12566
+ runtime: undefined,
12567
+ dbType: expression[TypeId2].dbType,
12568
+ runtimeSchema: expression[TypeId2].runtimeSchema,
12569
+ driverValueMapping: expression[TypeId2].driverValueMapping,
12570
+ nullability: "maybe",
12571
+ dialect: profile2.dialect,
12572
+ kind: "scalar",
12573
+ dependencies
12574
+ }, {
12575
+ kind: "scalarSubquery",
12576
+ plan
12577
+ });
12578
+ };
12579
+ var inSubquery = (left, plan) => {
12580
+ const leftExpression = toDialectExpression2(left);
12581
+ const dependencies = Object.fromEntries(currentRequiredList(plan[TypeId].required).map((name2) => [name2, true]));
12582
+ return makeExpression2({
12583
+ runtime: true,
12584
+ dbType: profile2.boolDb,
12585
+ nullability: "maybe",
12586
+ dialect: leftExpression[TypeId2].dialect ?? profile2.dialect,
12587
+ kind: leftExpression[TypeId2].kind,
12588
+ dependencies: mergeDependencies(leftExpression[TypeId2].dependencies, dependencies)
12589
+ }, {
12590
+ kind: "inSubquery",
12591
+ left: leftExpression,
12592
+ plan
12593
+ });
12594
+ };
12595
+ var quantifiedComparison = (left, plan, operator, quantifier) => {
12596
+ const leftExpression = toDialectExpression2(left);
12597
+ const dependencies = Object.fromEntries(currentRequiredList(plan[TypeId].required).map((name2) => [name2, true]));
12598
+ return makeExpression2({
12599
+ runtime: true,
12600
+ dbType: profile2.boolDb,
12601
+ nullability: "maybe",
12602
+ dialect: leftExpression[TypeId2].dialect ?? profile2.dialect,
12603
+ kind: leftExpression[TypeId2].kind,
12604
+ dependencies: mergeDependencies(leftExpression[TypeId2].dependencies, dependencies)
12605
+ }, renderQuantifiedComparisonAst(leftExpression, plan, operator, quantifier));
12606
+ };
12607
+ var compareAny = (left, plan, operator) => quantifiedComparison(left, plan, operator, "any");
12608
+ var compareAll = (left, plan, operator) => quantifiedComparison(left, plan, operator, "all");
12609
+ var over2 = (value, spec = {}) => {
12610
+ const normalized = normalizeWindowSpec2(spec);
12611
+ const expressions = mergeWindowExpressions2(value, normalized.partitionBy, normalized.orderBy);
12612
+ return makeExpression2({
12613
+ runtime: undefined,
12614
+ dbType: value[TypeId2].dbType,
12615
+ nullability: value[TypeId2].nullability,
12616
+ dialect: expressions.find((expression) => expression[TypeId2].dialect !== undefined)?.[TypeId2].dialect ?? profile2.dialect,
12617
+ kind: "window",
12618
+ dependencies: mergeManyDependencies(expressions)
12619
+ }, {
12620
+ kind: "window",
12621
+ function: "over",
12622
+ value,
12623
+ partitionBy: normalized.partitionBy,
12624
+ orderBy: normalized.orderBy,
12625
+ frame: normalized.frame
12626
+ });
12627
+ };
12628
+ var buildNumberWindow2 = (kind, spec) => {
12629
+ const normalized = normalizeWindowSpec2(spec);
12630
+ const expressions = mergeWindowExpressions2(undefined, normalized.partitionBy, normalized.orderBy);
12631
+ return makeExpression2({
12632
+ runtime: undefined,
12633
+ dbType: standardDatatypes.bigint(),
12634
+ nullability: "never",
12635
+ dialect: expressions.find((expression) => expression[TypeId2].dialect !== undefined)?.[TypeId2].dialect ?? profile2.dialect,
12636
+ kind: "window",
12637
+ dependencies: mergeManyDependencies(expressions)
12638
+ }, {
12639
+ kind: "window",
12640
+ function: kind,
12641
+ partitionBy: normalized.partitionBy,
12642
+ orderBy: normalized.orderBy,
12643
+ frame: normalized.frame
12644
+ });
12645
+ };
12646
+ var rowNumber2 = (spec) => buildNumberWindow2("rowNumber", spec);
12647
+ var rank2 = (spec) => buildNumberWindow2("rank", spec);
12648
+ var denseRank2 = (spec) => buildNumberWindow2("denseRank", spec);
12649
+ var max2 = (value) => makeExpression2({
12650
+ runtime: undefined,
12651
+ dbType: value[TypeId2].dbType,
12652
+ nullability: "maybe",
12653
+ dialect: value[TypeId2].dialect,
12654
+ kind: "aggregate",
12655
+ dependencies: value[TypeId2].dependencies
12656
+ }, {
12657
+ kind: "max",
12658
+ value
12659
+ });
12660
+ var min2 = (value) => makeExpression2({
12661
+ runtime: undefined,
12662
+ dbType: value[TypeId2].dbType,
12663
+ nullability: "maybe",
12664
+ dialect: value[TypeId2].dialect,
12665
+ kind: "aggregate",
12666
+ dependencies: value[TypeId2].dependencies
12667
+ }, {
12668
+ kind: "min",
12669
+ value
12670
+ });
12671
+ var resolveCoalesceNullabilityRuntime = (values2) => values2.some((value) => value[TypeId2].nullability === "never") ? "never" : values2.some((value) => value[TypeId2].nullability === "maybe") ? "maybe" : "always";
12672
+ var coalesce = (...values2) => {
12673
+ const expressions = values2.map((value) => toDialectExpression2(value));
12674
+ const representative = expressions.find((value) => value[TypeId2].nullability !== "always") ?? expressions[0];
12675
+ return makeExpression2({
12676
+ runtime: undefined,
12677
+ dbType: representative[TypeId2].dbType,
12678
+ nullability: resolveCoalesceNullabilityRuntime(expressions),
12679
+ dialect: expressions.find((value) => value[TypeId2].dialect !== undefined)?.[TypeId2].dialect ?? profile2.dialect,
12680
+ kind: mergeAggregationManyRuntime(expressions),
12681
+ dependencies: mergeManyDependencies(expressions)
12682
+ }, {
12683
+ kind: "coalesce",
12684
+ values: expressions
12685
+ });
12686
+ };
12687
+ var resolveCaseNullabilityRuntime = (values2) => {
12688
+ let sawNever = false;
12689
+ let sawMaybe = false;
12690
+ let sawAlways = false;
12691
+ for (const value of values2) {
12692
+ switch (value[TypeId2].nullability) {
12693
+ case "never":
12694
+ sawNever = true;
12695
+ break;
12696
+ case "maybe":
12697
+ sawMaybe = true;
12698
+ break;
12699
+ case "always":
12700
+ sawAlways = true;
12701
+ break;
12702
+ }
12703
+ }
12704
+ return sawNever ? sawMaybe || sawAlways ? "maybe" : "never" : sawMaybe ? "maybe" : "always";
12705
+ };
12706
+ var finalizeCase = (branches, fallback) => {
12707
+ const resultExpressions = [...branches.map((branch) => branch.then), fallback];
12708
+ const allExpressions = [...branches.flatMap((branch) => [branch.when, branch.then]), fallback];
12709
+ const representative = resultExpressions.find((value) => value[TypeId2].nullability !== "always") ?? fallback;
12710
+ return makeExpression2({
12711
+ runtime: undefined,
12712
+ dbType: representative[TypeId2].dbType,
12713
+ nullability: resolveCaseNullabilityRuntime(resultExpressions),
12714
+ dialect: allExpressions.find((value) => value[TypeId2].dialect !== undefined)?.[TypeId2].dialect ?? profile2.dialect,
12715
+ kind: mergeAggregationManyRuntime(allExpressions),
12716
+ dependencies: mergeManyDependencies(allExpressions)
12717
+ }, {
12718
+ kind: "case",
12719
+ branches: branches.map((branch) => ({
12720
+ when: branch.when,
12721
+ then: branch.then
12722
+ })),
12723
+ else: fallback
12724
+ });
12725
+ };
12726
+ var case_ = () => {
12727
+ const build = (branches) => ({
12728
+ when(predicate, result) {
12729
+ return build([
12730
+ ...branches,
12731
+ {
12732
+ when: toDialectExpression2(predicate),
12733
+ then: toDialectExpression2(result)
12734
+ }
12735
+ ]);
12736
+ },
12737
+ else(fallback) {
12738
+ return finalizeCase(branches, toDialectExpression2(fallback));
12739
+ }
12740
+ });
12741
+ return {
12742
+ when(predicate, result) {
12743
+ return build([{
12744
+ when: toDialectExpression2(predicate),
12745
+ then: toDialectExpression2(result)
12746
+ }]);
12747
+ }
12748
+ };
12749
+ };
12750
+ var match = (value) => {
12751
+ const subject = toDialectExpression2(value);
12752
+ const build = (branches) => ({
12753
+ when(compare, result) {
12754
+ return build([
12755
+ ...branches,
12756
+ {
12757
+ when: buildBinaryPredicate2(subject, compare, "eq"),
12758
+ then: toDialectExpression2(result)
12759
+ }
12760
+ ]);
12761
+ },
12762
+ else(fallback) {
12763
+ return finalizeCase(branches, toDialectExpression2(fallback));
12764
+ }
12765
+ });
12766
+ return {
12767
+ when(compare, result) {
12768
+ const predicate = buildBinaryPredicate2(subject, compare, "eq");
12769
+ return build([{
12770
+ when: predicate,
12771
+ then: toDialectExpression2(result)
12772
+ }]);
12773
+ }
12774
+ };
12775
+ };
12776
+ var excluded = (value) => {
12777
+ const ast = value[TypeId3];
12778
+ return makeExpression2({
12779
+ runtime: undefined,
12780
+ dbType: value[TypeId2].dbType,
12781
+ runtimeSchema: value[TypeId2].runtimeSchema,
12782
+ driverValueMapping: value[TypeId2].driverValueMapping,
12783
+ nullability: value[TypeId2].nullability,
12784
+ dialect: profile2.dialect,
12785
+ kind: "scalar",
12786
+ dependencies: {}
12787
+ }, {
12788
+ kind: "excluded",
12789
+ columnName: ast.columnName
12790
+ });
12791
+ };
12792
+ var toMutationValueExpression2 = (value, column2) => {
12793
+ const columnState = column2[TypeId2];
12794
+ const normalizeMutationValue = (candidate) => {
12795
+ if (candidate === null && columnState.nullability !== "never") {
12796
+ return null;
12797
+ }
12798
+ const runtimeSchemaAccepts = columnState.runtimeSchema !== undefined && Schema10.is(columnState.runtimeSchema)(candidate);
12799
+ if (runtimeSchemaAccepts) {
12800
+ return candidate;
12801
+ }
12802
+ const normalized = normalizeDbValue(columnState.dbType, candidate);
12803
+ return columnState.runtimeSchema === undefined ? normalized : Schema10.decodeUnknownSync(columnState.runtimeSchema)(normalized);
12804
+ };
12805
+ if (value !== null && typeof value === "object" && TypeId2 in value) {
12806
+ const expression = value;
12807
+ const ast = expression[TypeId3];
12808
+ if (ast.kind === "literal") {
12809
+ const normalizedValue2 = normalizeMutationValue(ast.value);
12810
+ return makeExpression2({
12811
+ runtime: normalizedValue2,
12812
+ dbType: columnState.dbType,
12813
+ runtimeSchema: columnState.runtimeSchema,
12814
+ driverValueMapping: columnState.driverValueMapping,
12815
+ nullability: normalizedValue2 === null ? "always" : "never",
12816
+ dialect: columnState.dialect,
12817
+ kind: "scalar",
12818
+ dependencies: {}
12819
+ }, {
12820
+ kind: "literal",
12821
+ value: normalizedValue2
12822
+ });
12823
+ }
12824
+ return retargetLiteralExpression2(value, column2);
12825
+ }
12826
+ const normalizedValue = normalizeMutationValue(value);
12827
+ return makeExpression2({
12828
+ runtime: normalizedValue,
12829
+ dbType: columnState.dbType,
12830
+ runtimeSchema: columnState.runtimeSchema,
12831
+ driverValueMapping: columnState.driverValueMapping,
12832
+ nullability: normalizedValue === null ? "always" : "never",
12833
+ dialect: columnState.dialect,
12834
+ kind: "scalar",
12835
+ dependencies: {}
12836
+ }, {
12837
+ kind: "literal",
12838
+ value: normalizedValue
12839
+ });
12840
+ };
12841
+ var renderQuantifiedComparisonAst = (left, plan, operator, quantifier) => ({
12842
+ kind: quantifier === "any" ? "comparisonAny" : "comparisonAll",
12843
+ operator,
12844
+ left,
12845
+ plan
12846
+ });
12847
+ var targetSourceDetails2 = (table) => {
12848
+ const sourceName = table[TypeId7].name;
12849
+ const sourceBaseName = table[TypeId7].baseName;
12850
+ return {
12851
+ sourceName,
12852
+ sourceBaseName
12853
+ };
12854
+ };
12855
+ var sourceDetails2 = (source) => {
12856
+ if (TypeId7 in source) {
12857
+ return targetSourceDetails2(source);
12858
+ }
12859
+ const record2 = source;
12860
+ return {
12861
+ sourceName: record2.name,
12862
+ sourceBaseName: record2.baseName
12863
+ };
12864
+ };
12865
+ var makeColumnReferenceSelection2 = (alias2, selection) => {
12866
+ const columns = {};
12867
+ for (const [columnName, expression] of Object.entries(selection)) {
12868
+ const state = expression[TypeId2];
12869
+ columns[columnName] = makeExpression2({
12870
+ runtime: undefined,
12871
+ dbType: state.dbType,
12872
+ runtimeSchema: state.runtimeSchema,
12873
+ driverValueMapping: state.driverValueMapping,
12874
+ nullability: state.nullability,
12875
+ dialect: state.dialect,
12876
+ kind: "scalar",
12877
+ dependencies: {
12878
+ [alias2]: true
12879
+ }
12880
+ }, {
12881
+ kind: "column",
12882
+ tableName: alias2,
12883
+ columnName
12884
+ });
12885
+ }
12886
+ return columns;
12887
+ };
12888
+ var makeAliasedValuesSource = (rows, selection, alias2) => {
12889
+ const columns = makeColumnReferenceSelection2(alias2, selection);
12890
+ const source = {
12891
+ kind: "values",
12892
+ name: alias2,
12893
+ baseName: alias2,
12894
+ dialect: profile2.dialect,
12895
+ rows,
12896
+ columns
12897
+ };
12898
+ return Object.assign(source, columns);
12899
+ };
12900
+ var normalizeValuesRow2 = (row) => Object.fromEntries(Object.entries(row).map(([key2, value]) => [key2, toDialectExpression2(value)]));
12901
+ var normalizeUnnestColumns2 = (columns) => Object.fromEntries(Object.entries(columns).map(([key2, values2]) => [key2, values2.map((value) => toDialectExpression2(value))]));
12902
+ var normalizeMutationTargets2 = (target) => Array.isArray(target) ? target : [target];
12903
+ var mutationTargetClauses2 = (target) => normalizeMutationTargets2(target).map((table) => {
12904
+ const { sourceName, sourceBaseName } = targetSourceDetails2(table);
12905
+ return {
12906
+ kind: "from",
12907
+ tableName: sourceName,
12908
+ baseTableName: sourceBaseName,
12909
+ source: table
12910
+ };
12911
+ });
12912
+ var mutationAvailableSources2 = (target, mode = "required") => Object.fromEntries(normalizeMutationTargets2(target).map((table) => {
12913
+ const { sourceName, sourceBaseName } = targetSourceDetails2(table);
12914
+ return [
12915
+ sourceName,
12916
+ {
12917
+ name: sourceName,
12918
+ mode,
12919
+ baseName: sourceBaseName
12920
+ }
12921
+ ];
12922
+ }));
12923
+ var getMutationColumn2 = (columns, columnName) => columns[columnName];
12924
+ var buildMutationAssignments2 = (target, values2) => {
12925
+ const targets = normalizeMutationTargets2(target);
12926
+ if (targets.length === 1 && !Array.isArray(target)) {
12927
+ const columns = target;
12928
+ return Object.entries(values2).map(([columnName, value]) => ({
12929
+ columnName,
12930
+ value: toMutationValueExpression2(value, getMutationColumn2(columns, columnName))
12931
+ }));
12932
+ }
12933
+ const valueMap = values2;
12934
+ return targets.flatMap((table) => {
12935
+ const targetName = table[TypeId7].name;
12936
+ const scopedValues = valueMap[targetName] ?? {};
12937
+ const columns = table;
12938
+ return Object.entries(scopedValues).map(([columnName, value]) => ({
12939
+ tableName: targetName,
12940
+ columnName,
12941
+ value: toMutationValueExpression2(value, getMutationColumn2(columns, columnName))
12942
+ }));
12943
+ });
12944
+ };
12945
+ var buildInsertValuesRows2 = (target, rows) => {
12946
+ const firstRow = rows[0];
12947
+ const firstColumns = Object.keys(firstRow);
12948
+ const columns = firstColumns;
12949
+ const normalizeRow = (row) => {
12950
+ const assignments = buildMutationAssignments2(target, row);
12951
+ return {
12952
+ values: columns.map((columnName) => assignments.find((assignment) => assignment.columnName === columnName))
12953
+ };
12954
+ };
12955
+ const normalizedRows = [
12956
+ normalizeRow(rows[0]),
12957
+ ...rows.slice(1).map(normalizeRow)
12958
+ ];
12959
+ const required = normalizedRows.flatMap((row) => row.values.flatMap((entry) => Object.keys(entry.value[TypeId2].dependencies)));
12960
+ return {
12961
+ columns,
12962
+ rows: normalizedRows,
12963
+ required: required.filter((name2, index5, list) => list.indexOf(name2) === index5)
12964
+ };
12965
+ };
12966
+ var normalizeInsertSelectColumns2 = (selection) => {
12967
+ const columns = Object.keys(selection);
12968
+ return columns;
12969
+ };
12970
+ var normalizeInsertUnnestValues2 = (target, values2) => {
12971
+ const entries = Object.entries(values2);
12972
+ const columns = entries.map(([columnName]) => columnName);
12973
+ const normalized = entries.map(([columnName, items]) => ({
12974
+ columnName,
12975
+ values: items
12976
+ }));
12977
+ return {
12978
+ columns,
12979
+ values: normalized
12980
+ };
12981
+ };
12982
+ var normalizeConflictColumns2 = (target, columnsInput) => {
12983
+ const columns = normalizeColumnList(columnsInput);
12984
+ return columns;
12985
+ };
12986
+ var buildConflictTarget2 = (target, input) => {
12987
+ if (typeof input === "string" || Array.isArray(input)) {
12988
+ return {
12989
+ kind: "columns",
12990
+ columns: normalizeConflictColumns2(target, input)
12991
+ };
12992
+ }
12993
+ if (!Array.isArray(input) && "constraint" in input) {
12994
+ return {
12995
+ kind: "constraint",
12996
+ name: input.constraint
12997
+ };
12998
+ }
12999
+ const columnTarget = input;
13000
+ return {
13001
+ kind: "columns",
13002
+ columns: normalizeConflictColumns2(target, columnTarget.columns),
13003
+ where: columnTarget.where === undefined ? undefined : toDialectExpression2(columnTarget.where)
13004
+ };
13005
+ };
13006
+ var defaultIndexName2 = (tableName, columns, unique4) => `${tableName}_${columns.join("_")}_${unique4 ? "uniq" : "idx"}`;
13007
+ function as(valueOrAlias, alias2) {
13008
+ if (alias2 === undefined) {
13009
+ return (value2) => as(value2, valueOrAlias);
13010
+ }
13011
+ const resolvedAlias = alias2;
13012
+ const value = valueOrAlias;
13013
+ if (typeof value !== "object" || value === null || TypeId2 in value) {
13014
+ const expression = toDialectExpression2(value);
13015
+ const projected = Object.create(Object.getPrototypeOf(expression));
13016
+ const runtimeExpression = expression;
13017
+ projected[TypeId2] = runtimeExpression[TypeId2];
13018
+ projected[TypeId3] = runtimeExpression[TypeId3];
13019
+ if ("schema" in runtimeExpression) {
13020
+ projected.schema = runtimeExpression.schema;
13021
+ }
13022
+ projected[TypeId9] = {
13023
+ alias: resolvedAlias
13024
+ };
13025
+ return projected;
13026
+ }
13027
+ if ("kind" in value && value.kind === "values" && !("name" in value)) {
13028
+ const valuesInput = value;
13029
+ return makeAliasedValuesSource(valuesInput.rows, valuesInput.selection, resolvedAlias);
13030
+ }
13031
+ return makeDerivedSource(value, resolvedAlias);
13032
+ }
13033
+ function with_(valueOrAlias, alias2) {
13034
+ if (alias2 === undefined) {
13035
+ return (value) => with_(value, valueOrAlias);
13036
+ }
13037
+ return makeCteSource(valueOrAlias, alias2);
13038
+ }
13039
+ function withRecursive_(valueOrAlias, alias2) {
13040
+ if (alias2 === undefined) {
13041
+ return (value) => withRecursive_(value, valueOrAlias);
13042
+ }
13043
+ return makeCteSource(valueOrAlias, alias2, true);
13044
+ }
13045
+ function lateral(valueOrAlias, alias2) {
13046
+ if (alias2 === undefined) {
13047
+ return (value) => lateral(value, valueOrAlias);
13048
+ }
13049
+ return makeLateralSource(valueOrAlias, alias2);
13050
+ }
13051
+ var {
13052
+ values: values2,
13053
+ unnest: unnest2,
13054
+ generateSeries: generateSeries2,
13055
+ select: select2,
13056
+ groupBy: groupBy2,
13057
+ returning: returning2
13058
+ } = makeDslQueryRuntime({
13059
+ profile: profile2,
13060
+ ValuesInputProto: ValuesInputProto2,
13061
+ normalizeValuesRow: normalizeValuesRow2,
13062
+ normalizeUnnestColumns: normalizeUnnestColumns2,
13063
+ makeColumnReferenceSelection: makeColumnReferenceSelection2,
13064
+ toDialectNumericExpression: toDialectNumericExpression2,
13065
+ extractRequiredRuntime,
13066
+ makePlan,
13067
+ getAst,
13068
+ getQueryState,
13069
+ currentRequiredList,
13070
+ dedupeGroupedExpressions
13071
+ });
13072
+ var {
13073
+ buildSetOperation: buildSetOperation2,
13074
+ where: where2,
13075
+ from: from2,
13076
+ having: having2,
13077
+ crossJoin: crossJoin2,
13078
+ join: join2,
13079
+ orderBy: orderBy2,
13080
+ lock: lock2,
13081
+ distinct: distinct2,
13082
+ limit: limit2,
13083
+ offset: offset2
13084
+ } = makeDslPlanRuntime({
13085
+ profile: profile2,
13086
+ makePlan,
13087
+ getAst,
13088
+ getQueryState,
13089
+ currentRequiredList,
13090
+ toDialectExpression: toDialectExpression2,
13091
+ toDialectNumericExpression: toDialectNumericExpression2,
13092
+ extractRequiredFromDialectInputRuntime: extractRequiredFromDialectInputRuntime2,
13093
+ extractRequiredFromDialectNumericInputRuntime: extractRequiredFromDialectNumericInputRuntime2,
13094
+ formulaOfExpressionRuntime: formulaOfExpression,
13095
+ assumeFormulaTrue,
13096
+ trueFormula,
13097
+ sourceDetails: sourceDetails2,
13098
+ presenceWitnessesOfSourceLike,
13099
+ attachInsertSource: (...args) => attachInsertSource2(args[0], args[1])
13100
+ });
13101
+ var union = (left, right) => buildSetOperation2("union", false, left, right);
13102
+ var unionAll = (left, right) => buildSetOperation2("union", true, left, right);
13103
+ var intersect = (left, right) => buildSetOperation2("intersect", false, left, right);
13104
+ var intersectAll = (left, right) => buildSetOperation2("intersect", true, left, right);
13105
+ var except = (left, right) => buildSetOperation2("except", false, left, right);
13106
+ var exceptAll = (left, right) => buildSetOperation2("except", true, left, right);
13107
+ var innerJoin = (table, on) => join2("inner", table, on);
13108
+ var leftJoin = (table, on) => join2("left", table, on);
13109
+ var rightJoin = (table, on) => join2("right", table, on);
13110
+ var fullJoin = (table, on) => join2("full", table, on);
13111
+ var distinctOn2 = {
13112
+ __effect_qb_error__: "effect-qb: distinctOn(...) is only supported by the postgres dialect",
13113
+ __effect_qb_dialect__: profile2.dialect,
13114
+ __effect_qb_hint__: "Use postgres.Query.distinctOn(...) or regular distinct()/grouping logic"
13115
+ };
13116
+ var mutationRuntime2 = makeDslMutationRuntime({
13117
+ profile: profile2,
13118
+ makePlan,
13119
+ getAst,
13120
+ getQueryState,
13121
+ currentRequiredList,
13122
+ toDialectExpression: toDialectExpression2,
13123
+ buildMutationAssignments: buildMutationAssignments2,
13124
+ buildInsertValuesRows: buildInsertValuesRows2,
13125
+ normalizeInsertUnnestValues: normalizeInsertUnnestValues2,
13126
+ normalizeInsertSelectColumns: normalizeInsertSelectColumns2,
13127
+ buildConflictTarget: buildConflictTarget2,
13128
+ mutationTargetClauses: mutationTargetClauses2,
13129
+ mutationAvailableSources: mutationAvailableSources2,
13130
+ normalizeConflictColumns: normalizeConflictColumns2,
13131
+ targetSourceDetails: targetSourceDetails2,
13132
+ sourceDetails: sourceDetails2
13133
+ });
13134
+ var insert = (target, values3) => mutationRuntime2.insert(target, values3);
13135
+ var attachInsertSource2 = (plan, source) => mutationRuntime2.attachInsertSource(plan, source);
13136
+ var onConflict2 = (target, options2 = {}) => (plan) => mutationRuntime2.onConflict(target, options2)(plan);
13137
+ var update = (target, values3) => mutationRuntime2.update(target, values3);
13138
+ var upsert = (target, values3, conflictColumns, updateValues) => mutationRuntime2.upsert(target, values3, conflictColumns, updateValues);
13139
+ var delete_ = (target) => mutationRuntime2.delete_(target);
13140
+ var truncate = (target, options2 = {}) => mutationRuntime2.truncate(target, options2);
13141
+ var merge2 = (target, source, on, options2) => mutationRuntime2.merge(target, source, on, options2);
13142
+ var {
13143
+ transaction: transaction2,
13144
+ commit: commit2,
13145
+ rollback: rollback2,
13146
+ savepoint: savepoint2,
13147
+ rollbackTo: rollbackTo2,
13148
+ releaseSavepoint: releaseSavepoint2,
13149
+ createTable: createTable2,
13150
+ dropTable: dropTable2,
13151
+ createIndex: createIndex2,
13152
+ dropIndex: dropIndex2
13153
+ } = makeDslTransactionDdlRuntime({
13154
+ profile: profile2,
13155
+ makePlan,
13156
+ targetSourceDetails: targetSourceDetails2,
13157
+ normalizeColumnList,
13158
+ defaultIndexName: defaultIndexName2
13159
+ });
13160
+ var {
13161
+ values: exportedValues,
13162
+ unnest: exportedUnnest,
13163
+ select: exportedSelect,
13164
+ from: exportedFrom,
13165
+ insert: exportedInsert
13166
+ } = {
13167
+ values: values2,
13168
+ unnest: unnest2,
13169
+ select: select2,
13170
+ from: from2,
13171
+ insert
13172
+ };
13173
+
13174
+ // src/internal/analytics.ts
13175
+ var normalizeSpec = (spec) => {
13176
+ validateWindowFrame(spec.frame);
13177
+ return {
13178
+ partitionBy: spec.partitionBy ?? [],
13179
+ orderBy: spec.orderBy.map((term) => ({
13180
+ value: term.value,
13181
+ direction: term.direction ?? "asc"
13182
+ })),
13183
+ frame: spec.frame
13184
+ };
13185
+ };
13186
+ var rejectExplicitPortableFrame = (functionName, spec) => {
13187
+ if (spec.frame !== undefined) {
13188
+ throw new Error(`${functionName} does not accept an explicit frame on the portable Function API; use a dialect Function helper`);
13189
+ }
13190
+ };
13191
+ var windowExpression = (kind, value, spec, nullability, options2 = {}) => {
13192
+ const normalized = normalizeSpec(spec);
13193
+ const { fallbackDialect, ...astOptions } = options2;
13194
+ const expressions = [
13195
+ value,
13196
+ ...normalized.partitionBy,
13197
+ ...normalized.orderBy.map((term) => term.value),
13198
+ ...options2.offset === undefined ? [] : [options2.offset],
13199
+ ...options2.defaultValue === undefined ? [] : [options2.defaultValue]
13200
+ ];
13201
+ return makeExpression2({
13202
+ runtime: undefined,
13203
+ dbType: value[TypeId2].dbType,
13204
+ runtimeSchema: value[TypeId2].runtimeSchema,
13205
+ driverValueMapping: value[TypeId2].driverValueMapping,
13206
+ nullability,
13207
+ dialect: expressions.find((entry) => entry[TypeId2].dialect !== "standard")?.[TypeId2].dialect ?? fallbackDialect ?? value[TypeId2].dialect,
13208
+ kind: "window",
13209
+ dependencies: mergeManyDependencies(expressions)
13210
+ }, {
13211
+ kind: "window",
13212
+ function: kind,
13213
+ value,
13214
+ ...astOptions,
13215
+ ...normalized
13216
+ });
13217
+ };
13218
+ var lag = (value, options2) => {
13219
+ rejectExplicitPortableFrame("lag", options2.spec);
13220
+ if (options2.offset !== undefined && (!Number.isSafeInteger(options2.offset) || options2.offset < 0)) {
13221
+ throw new Error("lag offset must be a non-negative safe integer");
13222
+ }
13223
+ return windowExpression("lag", value, options2.spec, "maybe", {
13224
+ ...options2.offset === undefined && options2.default === undefined ? {} : { offset: literal3(options2.offset ?? 1) },
13225
+ ...options2.default === undefined ? {} : { defaultValue: literal3(options2.default) }
13226
+ });
13227
+ };
13228
+ var lead = (value, options2) => {
13229
+ rejectExplicitPortableFrame("lead", options2.spec);
13230
+ if (options2.offset !== undefined && (!Number.isSafeInteger(options2.offset) || options2.offset < 0)) {
13231
+ throw new Error("lead offset must be a non-negative safe integer");
13232
+ }
13233
+ return windowExpression("lead", value, options2.spec, "maybe", {
13234
+ ...options2.offset === undefined && options2.default === undefined ? {} : { offset: literal3(options2.offset ?? 1) },
13235
+ ...options2.default === undefined ? {} : { defaultValue: literal3(options2.default) }
13236
+ });
13237
+ };
13238
+ var firstValue = (value, spec) => {
13239
+ rejectExplicitPortableFrame("firstValue", spec);
13240
+ return windowExpression("firstValue", value, spec, value[TypeId2].nullability);
13241
+ };
13242
+ var lastValue = (value, spec) => {
13243
+ rejectExplicitPortableFrame("lastValue", spec);
13244
+ return windowExpression("lastValue", value, spec, value[TypeId2].nullability);
13245
+ };
13246
+ var makeDialectFirstValue = (dialect) => (value, spec) => windowExpression("firstValue", value, spec, "maybe", { fallbackDialect: dialect });
13247
+ var makeDialectLastValue = (dialect) => (value, spec) => windowExpression("lastValue", value, spec, "maybe", { fallbackDialect: dialect });
13248
+
13249
+ // src/postgres/function/window.ts
13250
+ var firstValue2 = makeDialectFirstValue("postgres");
13251
+ var lastValue2 = makeDialectLastValue("postgres");
13252
+ // src/postgres/function/temporal.ts
13253
+ var exports_temporal = {};
13254
+ __export(exports_temporal, {
13255
+ now: () => now,
13256
+ localTimestamp: () => localTimestamp,
13257
+ localTime: () => localTime,
13258
+ currentTimestamp: () => currentTimestamp,
13259
+ currentTime: () => currentTime,
13260
+ currentDate: () => currentDate
13261
+ });
13262
+ var makeTemporal = (name2, dbType, runtimeSchema) => makeExpression2({
13263
+ runtime: undefined,
13264
+ dbType,
13265
+ runtimeSchema,
13266
+ nullability: "never",
13267
+ dialect: "postgres",
13268
+ kind: "scalar",
13269
+ dependencies: {}
13270
+ }, {
13271
+ kind: "function",
13272
+ name: name2,
13273
+ args: []
13274
+ });
13275
+ var now = () => makeTemporal("now", postgresDatatypes.timestamptz(), InstantStringSchema);
13276
+ var currentDate = () => makeTemporal("current_date", postgresDatatypes.date(), LocalDateStringSchema);
13277
+ var currentTime = () => makeTemporal("current_time", postgresDatatypes.timetz(), OffsetTimeStringSchema);
13278
+ var currentTimestamp = () => makeTemporal("current_timestamp", postgresDatatypes.timestamptz(), InstantStringSchema);
13279
+ var localTime = () => makeTemporal("localtime", postgresDatatypes.time(), LocalTimeStringSchema);
13280
+ var localTimestamp = () => makeTemporal("localtimestamp", postgresDatatypes.timestamp(), LocalDateTimeStringSchema);
13281
+ // src/postgres/json-extension.ts
13282
+ var exports_json_extension = {};
13283
+ __export(exports_json_extension, {
13284
+ stripNulls: () => stripNulls2,
13285
+ pathMatch: () => pathMatch2
13286
+ });
13287
+
13288
+ // src/postgres/json.ts
13289
+ var emptyPath = path();
13290
+ var isObjectLike2 = (value) => (typeof value === "object" || typeof value === "function") && value !== null;
13291
+ var isExpression5 = (value) => isObjectLike2(value) && (TypeId2 in value);
13292
+ var isPath = (value) => isObjectLike2(value) && (TypeId4 in value);
13293
+ var isSegment = (value) => isObjectLike2(value) && (SegmentTypeId in value);
13294
+ var isTarget = (value) => isPath(value) || isSegment(value);
13295
+ var normalizeSegment2 = (segment) => {
13296
+ switch (segment.kind) {
13297
+ case "key":
13298
+ return key(segment.key);
13299
+ case "index":
13300
+ return index(segment.index);
13301
+ case "wildcard":
13302
+ return wildcard();
13303
+ case "slice":
13304
+ return slice(segment.start, segment.end);
13305
+ case "descend":
13306
+ return descend();
13307
+ }
13308
+ };
13309
+ var normalizeTarget = (target) => isPath(target) ? path(...target.segments.map(normalizeSegment2)) : normalizeSegment2(target);
13310
+ var accessKinds2 = new Set([
13311
+ "jsonGet",
13312
+ "jsonPath",
13313
+ "jsonAccess",
13314
+ "jsonTraverse",
13315
+ "jsonGetText",
13316
+ "jsonPathText",
13317
+ "jsonAccessText",
13318
+ "jsonTraverseText"
13319
+ ]);
13320
+ var accessPathOf2 = (value) => {
13321
+ const segments = [];
13322
+ let base = value;
13323
+ while (isExpression5(base)) {
13324
+ const ast = base[TypeId3];
13325
+ if (typeof ast.kind !== "string" || !accessKinds2.has(ast.kind) || !isExpression5(ast.base) || !Array.isArray(ast.segments)) {
13326
+ break;
13327
+ }
13328
+ segments.unshift(...ast.segments.map(normalizeSegment2));
13329
+ base = ast.base;
13330
+ }
13331
+ return segments.length === 0 ? undefined : {
13332
+ base,
13333
+ path: path(...segments)
13334
+ };
13335
+ };
13336
+ var jsonGetDirect = (base, target) => json.get(base, normalizeTarget(target));
13337
+ var jsonTextDirect = (base, target) => json.text(base, normalizeTarget(target));
13338
+ var jsonbGetDirect = (base, target) => jsonb2.get(base, normalizeTarget(target));
13339
+ var jsonbTextDirect = (base, target) => jsonb2.text(base, normalizeTarget(target));
13340
+ var jsonbSegmentOperation = (segment) => Object.assign((base) => jsonbGetDirect(base, segment), segment);
13341
+ var json3 = {
13342
+ get: (...args) => {
13343
+ if (args.length === 1) {
13344
+ const [first] = args;
13345
+ if (isTarget(first)) {
13346
+ return (base) => jsonGetDirect(base, first);
13347
+ }
13348
+ return first;
13349
+ }
13350
+ return jsonGetDirect(args[0], args[1]);
13351
+ },
13352
+ access: (base, target) => json.access(base, normalizeTarget(target)),
13353
+ traverse: (base, target) => json.traverse(base, normalizeTarget(target)),
13354
+ text: (...args) => {
13355
+ if (args.length === 1) {
13356
+ const [first] = args;
13357
+ if (isTarget(first)) {
13358
+ return (base) => jsonTextDirect(base, first);
13359
+ }
13360
+ const access = isExpression5(first) ? accessPathOf2(first) : undefined;
13361
+ return access === undefined ? json.text(first, emptyPath) : jsonTextDirect(access.base, access.path);
11179
13362
  }
11180
13363
  return jsonTextDirect(args[0], args[1]);
11181
13364
  },
@@ -11192,7 +13375,7 @@ var json2 = {
11192
13375
  delete: (base, target) => json.delete(base, normalizeTarget(target)),
11193
13376
  remove: (base, target) => json.remove(base, normalizeTarget(target))
11194
13377
  };
11195
- var jsonb3 = {
13378
+ var jsonb4 = {
11196
13379
  key: (value) => jsonbSegmentOperation(key(value)),
11197
13380
  index: (value) => jsonbSegmentOperation(index(value)),
11198
13381
  wildcard: () => jsonbSegmentOperation(wildcard()),
@@ -11342,26 +13525,26 @@ var jsonb3 = {
11342
13525
  },
11343
13526
  pathMatch: (base, query) => jsonb2.pathMatch(base, query)
11344
13527
  };
11345
- var get = json2.get;
11346
- var access = json2.access;
11347
- var traverse = json2.traverse;
11348
- var text = json2.text;
11349
- var accessText = json2.accessText;
11350
- var traverseText = json2.traverseText;
11351
- var buildObject = json2.buildObject;
11352
- var buildArray = json2.buildArray;
11353
- var toJson = json2.toJson;
11354
- var typeOf = json2.typeOf;
11355
- var length = json2.length;
11356
- var keys = json2.keys;
11357
- var stripNulls = json2.stripNulls;
11358
- var pathMatch = json2.pathMatch;
11359
- var delete_ = json2.delete;
11360
- var remove = json2.remove;
13528
+ var get = json3.get;
13529
+ var access = json3.access;
13530
+ var traverse = json3.traverse;
13531
+ var text = json3.text;
13532
+ var accessText = json3.accessText;
13533
+ var traverseText = json3.traverseText;
13534
+ var buildObject = json3.buildObject;
13535
+ var buildArray = json3.buildArray;
13536
+ var toJson = json3.toJson;
13537
+ var typeOf = json3.typeOf;
13538
+ var length = json3.length;
13539
+ var keys = json3.keys;
13540
+ var stripNulls = json3.stripNulls;
13541
+ var pathMatch = json3.pathMatch;
13542
+ var delete_2 = json3.delete;
13543
+ var remove = json3.remove;
11361
13544
 
11362
13545
  // src/postgres/json-extension.ts
11363
- var stripNulls2 = json2.stripNulls;
11364
- var pathMatch2 = json2.pathMatch;
13546
+ var stripNulls2 = json3.stripNulls;
13547
+ var pathMatch2 = json3.pathMatch;
11365
13548
  // src/postgres/jsonb.ts
11366
13549
  var exports_jsonb = {};
11367
13550
  __export(exports_jsonb, {
@@ -11377,68 +13560,71 @@ __export(exports_jsonb, {
11377
13560
  remove: () => remove2,
11378
13561
  pathMatch: () => pathMatch3,
11379
13562
  pathExists: () => pathExists,
11380
- merge: () => merge2,
13563
+ merge: () => merge3,
11381
13564
  length: () => length2,
11382
13565
  keys: () => keys2,
11383
13566
  keyExists: () => keyExists,
11384
13567
  key: () => key2,
11385
- jsonb: () => jsonb3,
11386
- insert: () => insert,
13568
+ jsonb: () => jsonb4,
13569
+ insert: () => insert2,
11387
13570
  index: () => index5,
11388
13571
  hasKey: () => hasKey,
11389
13572
  hasAnyKeys: () => hasAnyKeys,
11390
13573
  hasAllKeys: () => hasAllKeys,
11391
13574
  get: () => get2,
11392
13575
  descend: () => descend2,
11393
- delete_: () => delete_2,
11394
- delete: () => delete_2,
11395
- contains: () => contains,
11396
- containedBy: () => containedBy,
11397
- concat: () => concat,
13576
+ delete_: () => delete_3,
13577
+ delete: () => delete_3,
13578
+ contains: () => contains2,
13579
+ containedBy: () => containedBy2,
13580
+ concat: () => concat3,
11398
13581
  buildObject: () => buildObject2,
11399
13582
  buildArray: () => buildArray2,
11400
13583
  accessText: () => accessText2,
11401
13584
  access: () => access2
11402
13585
  });
11403
- var key2 = jsonb3.key;
11404
- var index5 = jsonb3.index;
11405
- var wildcard2 = jsonb3.wildcard;
11406
- var slice2 = jsonb3.slice;
11407
- var descend2 = jsonb3.descend;
11408
- var get2 = jsonb3.get;
11409
- var access2 = jsonb3.access;
11410
- var traverse2 = jsonb3.traverse;
11411
- var text2 = jsonb3.text;
11412
- var accessText2 = jsonb3.accessText;
11413
- var traverseText2 = jsonb3.traverseText;
11414
- var contains = jsonb3.contains;
11415
- var containedBy = jsonb3.containedBy;
11416
- var hasKey = jsonb3.hasKey;
11417
- var keyExists = jsonb3.keyExists;
11418
- var hasAnyKeys = jsonb3.hasAnyKeys;
11419
- var hasAllKeys = jsonb3.hasAllKeys;
11420
- var delete_2 = jsonb3.delete;
11421
- var remove2 = jsonb3.remove;
11422
- var set2 = jsonb3.set;
11423
- var insert = jsonb3.insert;
11424
- var concat = jsonb3.concat;
11425
- var merge2 = jsonb3.merge;
11426
- var buildObject2 = jsonb3.buildObject;
11427
- var buildArray2 = jsonb3.buildArray;
11428
- var toJsonb = jsonb3.toJsonb;
11429
- var typeOf2 = jsonb3.typeOf;
11430
- var length2 = jsonb3.length;
11431
- var keys2 = jsonb3.keys;
11432
- var stripNulls3 = jsonb3.stripNulls;
11433
- var pathExists = jsonb3.pathExists;
11434
- var pathMatch3 = jsonb3.pathMatch;
13586
+ var key2 = jsonb4.key;
13587
+ var index5 = jsonb4.index;
13588
+ var wildcard2 = jsonb4.wildcard;
13589
+ var slice2 = jsonb4.slice;
13590
+ var descend2 = jsonb4.descend;
13591
+ var get2 = jsonb4.get;
13592
+ var access2 = jsonb4.access;
13593
+ var traverse2 = jsonb4.traverse;
13594
+ var text2 = jsonb4.text;
13595
+ var accessText2 = jsonb4.accessText;
13596
+ var traverseText2 = jsonb4.traverseText;
13597
+ var contains2 = jsonb4.contains;
13598
+ var containedBy2 = jsonb4.containedBy;
13599
+ var hasKey = jsonb4.hasKey;
13600
+ var keyExists = jsonb4.keyExists;
13601
+ var hasAnyKeys = jsonb4.hasAnyKeys;
13602
+ var hasAllKeys = jsonb4.hasAllKeys;
13603
+ var delete_3 = jsonb4.delete;
13604
+ var remove2 = jsonb4.remove;
13605
+ var set2 = jsonb4.set;
13606
+ var insert2 = jsonb4.insert;
13607
+ var concat3 = jsonb4.concat;
13608
+ var merge3 = jsonb4.merge;
13609
+ var buildObject2 = jsonb4.buildObject;
13610
+ var buildArray2 = jsonb4.buildArray;
13611
+ var toJsonb = jsonb4.toJsonb;
13612
+ var typeOf2 = jsonb4.typeOf;
13613
+ var length2 = jsonb4.length;
13614
+ var keys2 = jsonb4.keys;
13615
+ var stripNulls3 = jsonb4.stripNulls;
13616
+ var pathExists = jsonb4.pathExists;
13617
+ var pathMatch3 = jsonb4.pathMatch;
11435
13618
  // src/postgres/executor.ts
11436
13619
  var exports_executor2 = {};
11437
13620
  __export(exports_executor2, {
11438
13621
  withTransaction: () => withTransaction2,
13622
+ nonEmpty: () => nonEmpty2,
11439
13623
  make: () => make4,
13624
+ exactlyOne: () => exactlyOne2,
11440
13625
  driver: () => driver2,
11441
- custom: () => custom3
13626
+ custom: () => custom4,
13627
+ atMostOne: () => atMostOne2
11442
13628
  });
11443
13629
  import * as Effect2 from "effect/Effect";
11444
13630
  import * as SqlClient3 from "effect/unstable/sql/SqlClient";
@@ -11448,40 +13634,45 @@ import * as Stream2 from "effect/Stream";
11448
13634
  var exports_executor = {};
11449
13635
  __export(exports_executor, {
11450
13636
  withTransaction: () => withTransaction,
13637
+ withResultContracts: () => withResultContracts,
11451
13638
  streamFromSqlClient: () => streamFromSqlClient,
11452
13639
  remapRows: () => remapRows,
13640
+ nonEmpty: () => nonEmpty,
11453
13641
  makeRowDecoder: () => makeRowDecoder,
11454
13642
  make: () => make3,
11455
13643
  hasWriteCapability: () => hasWriteCapability,
11456
13644
  fromSqlClient: () => fromSqlClient,
11457
13645
  fromDriver: () => fromDriver,
13646
+ explainQuery: () => explainQuery,
13647
+ exactlyOne: () => exactlyOne,
11458
13648
  driver: () => driver,
11459
13649
  decodeRows: () => decodeRows,
11460
- decodeChunk: () => decodeChunk
13650
+ decodeChunk: () => decodeChunk,
13651
+ atMostOne: () => atMostOne
11461
13652
  });
11462
13653
  import * as Chunk from "effect/Chunk";
11463
13654
  import * as Effect from "effect/Effect";
11464
13655
  import * as Exit from "effect/Exit";
11465
13656
  import * as Option from "effect/Option";
11466
- import * as Schema11 from "effect/Schema";
13657
+ import * as Schema12 from "effect/Schema";
11467
13658
  import * as SqlClient from "effect/unstable/sql/SqlClient";
11468
13659
  import * as Stream from "effect/Stream";
11469
13660
 
11470
13661
  // src/internal/runtime/schema.ts
11471
- import * as Schema10 from "effect/Schema";
13662
+ import * as Schema11 from "effect/Schema";
11472
13663
  import * as SchemaAST from "effect/SchemaAST";
11473
13664
  var schemaCache = new WeakMap;
11474
- var FiniteNumberSchema = Schema10.Number.check(Schema10.isFinite());
13665
+ var FiniteNumberSchema = Schema11.Number.check(Schema11.isFinite());
11475
13666
  var runtimeSchemaForTag = (tag) => {
11476
13667
  switch (tag) {
11477
13668
  case "string":
11478
- return Schema10.String;
13669
+ return Schema11.String;
11479
13670
  case "number":
11480
13671
  return FiniteNumberSchema;
11481
13672
  case "bigintString":
11482
13673
  return BigIntStringSchema;
11483
13674
  case "boolean":
11484
- return Schema10.Boolean;
13675
+ return Schema11.Boolean;
11485
13676
  case "json":
11486
13677
  return JsonValueSchema;
11487
13678
  case "localDate":
@@ -11499,13 +13690,13 @@ var runtimeSchemaForTag = (tag) => {
11499
13690
  case "decimalString":
11500
13691
  return DecimalStringSchema;
11501
13692
  case "bytes":
11502
- return Schema10.Uint8Array;
13693
+ return Schema11.Uint8Array;
11503
13694
  case "array":
11504
- return Schema10.Array(Schema10.Unknown);
13695
+ return Schema11.Array(Schema11.Unknown);
11505
13696
  case "record":
11506
- return Schema10.Record(Schema10.String, Schema10.Unknown);
13697
+ return Schema11.Record(Schema11.String, Schema11.Unknown);
11507
13698
  case "null":
11508
- return Schema10.Null;
13699
+ return Schema11.Null;
11509
13700
  case "unknown":
11510
13701
  return;
11511
13702
  }
@@ -11518,22 +13709,22 @@ var runtimeSchemaForDbType = (dbType) => {
11518
13709
  return runtimeSchemaForDbType(dbType.base);
11519
13710
  }
11520
13711
  if ("element" in dbType) {
11521
- return Schema10.Array(runtimeSchemaForDbType(dbType.element) ?? Schema10.Unknown);
13712
+ return Schema11.Array(runtimeSchemaForDbType(dbType.element) ?? Schema11.Unknown);
11522
13713
  }
11523
13714
  if ("fields" in dbType) {
11524
- const fields2 = Object.fromEntries(Object.entries(dbType.fields).map(([key3, field]) => [key3, runtimeSchemaForDbType(field) ?? Schema10.Unknown]));
11525
- return Schema10.Struct(fields2);
13715
+ const fields2 = Object.fromEntries(Object.entries(dbType.fields).map(([key3, field]) => [key3, runtimeSchemaForDbType(field) ?? Schema11.Unknown]));
13716
+ return Schema11.Struct(fields2);
11526
13717
  }
11527
13718
  if ("variant" in dbType && dbType.variant === "json") {
11528
13719
  return JsonValueSchema;
11529
13720
  }
11530
13721
  if ("variant" in dbType && (dbType.variant === "enum" || dbType.variant === "set")) {
11531
- return Schema10.String;
13722
+ return Schema11.String;
11532
13723
  }
11533
13724
  const runtimeTag = runtimeTagOfBaseDbType2(dbType);
11534
13725
  return runtimeTag === undefined ? undefined : runtimeSchemaForTag(runtimeTag);
11535
13726
  };
11536
- var makeSchemaFromAst = (ast) => Schema10.make(ast);
13727
+ var makeSchemaFromAst = (ast) => Schema11.make(ast);
11537
13728
  var unionAst = (asts) => {
11538
13729
  if (asts.length === 0) {
11539
13730
  return;
@@ -11556,11 +13747,11 @@ var propertyAstOf = (ast, key3) => {
11556
13747
  return index6?.type;
11557
13748
  }
11558
13749
  case "Union": {
11559
- const values2 = ast.types.flatMap((member) => {
13750
+ const values3 = ast.types.flatMap((member) => {
11560
13751
  const next = propertyAstOf(member, key3);
11561
13752
  return next === undefined ? [] : [next];
11562
13753
  });
11563
- return unionAst(values2);
13754
+ return unionAst(values3);
11564
13755
  }
11565
13756
  default:
11566
13757
  return;
@@ -11581,11 +13772,11 @@ var numberAstOf = (ast, index6) => {
11581
13772
  return unionAst(ast.rest);
11582
13773
  }
11583
13774
  case "Union": {
11584
- const values2 = ast.types.flatMap((member) => {
13775
+ const values3 = ast.types.flatMap((member) => {
11585
13776
  const next = numberAstOf(member, index6);
11586
13777
  return next === undefined ? [] : [next];
11587
13778
  });
11588
- return unionAst(values2);
13779
+ return unionAst(values3);
11589
13780
  }
11590
13781
  default:
11591
13782
  return;
@@ -11623,7 +13814,7 @@ var unionSchemas = (schemas) => {
11623
13814
  if (resolved.length === 1) {
11624
13815
  return resolved[0];
11625
13816
  }
11626
- return Schema10.Union(resolved);
13817
+ return Schema11.Union(resolved);
11627
13818
  };
11628
13819
  var firstSelectedExpression = (plan) => {
11629
13820
  const selection = getAst(plan).select;
@@ -11658,9 +13849,9 @@ var jsonCompatibleSchema = (schema2) => {
11658
13849
  };
11659
13850
  var buildStructSchema = (entries, context) => {
11660
13851
  const fields2 = Object.fromEntries(entries.map((entry) => [entry.key, expressionRuntimeSchema(entry.value, context) ?? JsonValueSchema]));
11661
- return Schema10.Struct(fields2);
13852
+ return Schema11.Struct(fields2);
11662
13853
  };
11663
- var buildTupleSchema = (values2, context) => Schema10.Tuple(values2.map((value) => expressionRuntimeSchema(value, context) ?? JsonValueSchema));
13854
+ var buildTupleSchema = (values3, context) => Schema11.Tuple(values3.map((value) => expressionRuntimeSchema(value, context) ?? JsonValueSchema));
11664
13855
  var deriveCaseSchema = (ast, context) => {
11665
13856
  if (context === undefined) {
11666
13857
  return unionSchemas([
@@ -11700,10 +13891,10 @@ var deriveRuntimeSchema = (expression, context) => {
11700
13891
  return state.runtimeSchema;
11701
13892
  case "literal":
11702
13893
  if (ast.value === null) {
11703
- return Schema10.Null;
13894
+ return Schema11.Null;
11704
13895
  }
11705
13896
  if (typeof ast.value === "string" || typeof ast.value === "number" || typeof ast.value === "boolean") {
11706
- return Schema10.Literal(ast.value);
13897
+ return Schema11.Literal(ast.value);
11707
13898
  }
11708
13899
  return runtimeSchemaForDbType(state.dbType);
11709
13900
  case "cast":
@@ -11739,7 +13930,7 @@ var deriveRuntimeSchema = (expression, context) => {
11739
13930
  case "jsonHasAllKeys":
11740
13931
  case "jsonPathExists":
11741
13932
  case "jsonPathMatch":
11742
- return Schema10.Boolean;
13933
+ return Schema11.Boolean;
11743
13934
  case "upper":
11744
13935
  case "lower":
11745
13936
  case "concat":
@@ -11748,8 +13939,9 @@ var deriveRuntimeSchema = (expression, context) => {
11748
13939
  case "jsonAccessText":
11749
13940
  case "jsonTraverseText":
11750
13941
  case "jsonTypeOf":
11751
- return Schema10.String;
13942
+ return Schema11.String;
11752
13943
  case "count":
13944
+ return runtimeSchemaForDbType(state.dbType);
11753
13945
  case "jsonLength":
11754
13946
  return FiniteNumberSchema;
11755
13947
  case "max":
@@ -11764,7 +13956,7 @@ var deriveRuntimeSchema = (expression, context) => {
11764
13956
  return selection === undefined ? undefined : expressionRuntimeSchema(selection, context);
11765
13957
  }
11766
13958
  case "window":
11767
- return ast.function === "over" && ast.value !== undefined ? expressionRuntimeSchema(ast.value, context) : FiniteNumberSchema;
13959
+ return ast.function === "over" && ast.value !== undefined ? expressionRuntimeSchema(ast.value, context) : runtimeSchemaForDbType(state.dbType);
11768
13960
  case "jsonGet":
11769
13961
  case "jsonPath":
11770
13962
  case "jsonAccess":
@@ -11796,7 +13988,7 @@ var deriveRuntimeSchema = (expression, context) => {
11796
13988
  case "jsonToJsonb":
11797
13989
  return jsonCompatibleSchema(expressionRuntimeSchema(ast.value, context));
11798
13990
  case "jsonKeys":
11799
- return Schema10.Array(Schema10.String);
13991
+ return Schema11.Array(Schema11.String);
11800
13992
  }
11801
13993
  };
11802
13994
  var expressionRuntimeSchema = (expression, context) => {
@@ -11812,7 +14004,86 @@ var expressionRuntimeSchema = (expression, context) => {
11812
14004
  return resolved;
11813
14005
  };
11814
14006
 
14007
+ // src/internal/renderer.ts
14008
+ var TypeId10 = Symbol.for("effect-qb/Renderer");
14009
+ var projectionPathKey = (path2) => JSON.stringify(path2);
14010
+ var formatProjectionPath2 = (path2) => path2.join(".");
14011
+ var validateProjectionPathsMatchSelection = (plan, projections) => {
14012
+ const expected = flattenSelection(getAst(plan).select);
14013
+ const expectedPaths = new Set(expected.map((projection) => projectionPathKey(projection.path)));
14014
+ const actualPaths = new Set(projections.map((projection) => projectionPathKey(projection.path)));
14015
+ for (const projection of projections) {
14016
+ if (!expectedPaths.has(projectionPathKey(projection.path))) {
14017
+ throw new Error(`Projection path ${formatProjectionPath2(projection.path)} does not exist in the query selection`);
14018
+ }
14019
+ }
14020
+ for (const projection of expected) {
14021
+ if (!actualPaths.has(projectionPathKey(projection.path))) {
14022
+ throw new Error(`Projection path ${formatProjectionPath2(projection.path)} is missing from rendered projections`);
14023
+ }
14024
+ }
14025
+ };
14026
+ function makeTrusted(dialect, render2) {
14027
+ return makeRenderer(dialect, render2, false);
14028
+ }
14029
+ var makeRenderer = (dialect, render2, validate) => {
14030
+ if (typeof render2 !== "function") {
14031
+ throw new Error(`Renderer.make requires an explicit render implementation for dialect: ${dialect}`);
14032
+ }
14033
+ return {
14034
+ dialect,
14035
+ render(plan) {
14036
+ const rendered = render2(plan);
14037
+ const projections = rendered.projections ?? [];
14038
+ if (validate) {
14039
+ validateProjections(projections);
14040
+ validateProjectionPathsMatchSelection(plan, projections);
14041
+ }
14042
+ return {
14043
+ sql: rendered.sql,
14044
+ params: rendered.params ?? [],
14045
+ projections,
14046
+ valueMappings: rendered.valueMappings,
14047
+ dialect,
14048
+ [TypeId10]: {
14049
+ row: undefined,
14050
+ dialect
14051
+ }
14052
+ };
14053
+ }
14054
+ };
14055
+ };
14056
+
11815
14057
  // src/internal/executor.ts
14058
+ var atMostOne = (self) => Effect.flatMap(self, (rows) => rows.length <= 1 ? Effect.succeed(rows.length === 0 ? Option.none() : Option.some(rows[0])) : Effect.fail({
14059
+ _tag: "ResultCardinalityError",
14060
+ expected: "zeroOrOne",
14061
+ actual: rows.length
14062
+ }));
14063
+ var exactlyOne = (self) => Effect.flatMap(self, (rows) => rows.length === 1 ? Effect.succeed(rows[0]) : Effect.fail({
14064
+ _tag: "ResultCardinalityError",
14065
+ expected: "exactlyOne",
14066
+ actual: rows.length
14067
+ }));
14068
+ var nonEmpty = (self) => Effect.flatMap(self, (rows) => rows.length > 0 ? Effect.succeed(rows) : Effect.fail({
14069
+ _tag: "ResultCardinalityError",
14070
+ expected: "nonEmpty",
14071
+ actual: 0
14072
+ }));
14073
+ var withResultContracts = (base) => {
14074
+ const executeResult = base.executeResult ?? ((plan) => Effect.map(base.execute(plan), (rows) => ({ rows })));
14075
+ return {
14076
+ ...base,
14077
+ executeResult,
14078
+ prepare(plan) {
14079
+ return {
14080
+ execute: base.execute(plan),
14081
+ executeResult: executeResult(plan),
14082
+ stream: base.stream(plan)
14083
+ };
14084
+ }
14085
+ };
14086
+ };
11816
14087
  var setPath2 = (target, path2, value) => {
11817
14088
  let current = target;
11818
14089
  for (let index6 = 0;index6 < path2.length - 1; index6++) {
@@ -11852,7 +14123,7 @@ var hasWriteCapability = (plan) => {
11852
14123
  if (ast.target && hasWriteCapabilityInSource(ast.target.source)) {
11853
14124
  return true;
11854
14125
  }
11855
- if ((ast.joins ?? []).some((join2) => hasWriteCapabilityInSource(join2.source))) {
14126
+ if ((ast.joins ?? []).some((join3) => hasWriteCapabilityInSource(join3.source))) {
11856
14127
  return true;
11857
14128
  }
11858
14129
  return false;
@@ -11867,7 +14138,7 @@ var remapRows = (query, rows) => rows.map((row) => {
11867
14138
  return decoded;
11868
14139
  });
11869
14140
  var makeRowDecodeError = (rendered, projection, expression, raw, stage, cause, normalized) => {
11870
- const schemaError = Schema11.isSchemaError(cause) ? {
14141
+ const schemaError = Schema12.isSchemaError(cause) ? {
11871
14142
  message: cause.message,
11872
14143
  issue: cause.issue
11873
14144
  } : undefined;
@@ -11921,7 +14192,7 @@ var dbTypeAllowsTopLevelJsonNull = (dbType) => {
11921
14192
  }
11922
14193
  return "variant" in dbType && dbType.variant === "json" || dbType.runtime === "json";
11923
14194
  };
11924
- var schemaAcceptsNull = (schema2) => schema2 !== undefined && Schema11.is(schema2)(null);
14195
+ var schemaAcceptsNull = (schema2) => schema2 !== undefined && Schema12.is(schema2)(null);
11925
14196
  var decodeProjectionValue = (rendered, projection, expression, raw, scope, driverMode, valueMappings) => {
11926
14197
  let normalized = raw;
11927
14198
  if (driverMode === "raw") {
@@ -11957,10 +14228,10 @@ var decodeProjectionValue = (rendered, projection, expression, raw, scope, drive
11957
14228
  if (schema2 === undefined) {
11958
14229
  return normalized;
11959
14230
  }
11960
- if (Schema11.is(schema2)(normalized)) {
14231
+ if (Schema12.is(schema2)(normalized)) {
11961
14232
  return normalized;
11962
14233
  }
11963
- const decoded = Schema11.decodeUnknownExit(schema2)(normalized);
14234
+ const decoded = Schema12.decodeUnknownExit(schema2)(normalized);
11964
14235
  if (Exit.isSuccess(decoded)) {
11965
14236
  return decoded.value;
11966
14237
  }
@@ -11999,7 +14270,7 @@ var decodeRows = (rendered, plan, rows, options2 = {}) => {
11999
14270
  const decodeRow = makeRowDecoder(rendered, plan, options2);
12000
14271
  return rows.map((row) => decodeRow(row));
12001
14272
  };
12002
- var make3 = (dialect, execute) => ({
14273
+ var make3 = (dialect, execute) => withResultContracts({
12003
14274
  dialect,
12004
14275
  execute(plan) {
12005
14276
  return execute(plan);
@@ -12019,23 +14290,81 @@ function driver(dialect, executeOrHandlers) {
12019
14290
  return Stream.unwrap(Effect.map(executeOrHandlers(query), (rows) => Stream.fromIterable(rows)));
12020
14291
  }
12021
14292
  return executeOrHandlers.stream(query);
12022
- }
14293
+ },
14294
+ ...typeof executeOrHandlers === "function" || executeOrHandlers.executeResult === undefined ? {} : { executeResult: executeOrHandlers.executeResult }
12023
14295
  };
12024
14296
  }
12025
14297
  var fromDriver = (renderer, sqlDriver) => {
12026
- const executor = {
14298
+ const renderedCache = new WeakMap;
14299
+ const render2 = (plan) => {
14300
+ const cached = renderedCache.get(plan);
14301
+ if (cached !== undefined) {
14302
+ return cached;
14303
+ }
14304
+ const rendered = renderer.render(plan);
14305
+ renderedCache.set(plan, rendered);
14306
+ return rendered;
14307
+ };
14308
+ const executor = withResultContracts({
12027
14309
  dialect: renderer.dialect,
12028
14310
  execute(plan) {
12029
- const rendered = renderer.render(plan);
14311
+ const rendered = render2(plan);
12030
14312
  return Effect.map(sqlDriver.execute(rendered), (rows) => remapRows(rendered, rows));
12031
14313
  },
14314
+ executeResult(plan) {
14315
+ const rendered = render2(plan);
14316
+ const result = sqlDriver.executeResult ? sqlDriver.executeResult(rendered) : Effect.map(sqlDriver.execute(rendered), (rows) => ({ rows }));
14317
+ return Effect.map(result, ({ rows, ...metadata }) => ({
14318
+ ...metadata,
14319
+ rows: remapRows(rendered, rows)
14320
+ }));
14321
+ },
12032
14322
  stream(plan) {
12033
- const rendered = renderer.render(plan);
14323
+ const rendered = render2(plan);
12034
14324
  return Stream.mapArray(sqlDriver.stream(rendered), (rows) => remapRows(rendered, rows));
12035
14325
  }
12036
- };
14326
+ });
12037
14327
  return executor;
12038
14328
  };
14329
+ var explainQuery = (query, options2 = {}) => {
14330
+ const analyze = options2.analyze ?? false;
14331
+ const format = options2.format ?? "text";
14332
+ let prefix;
14333
+ switch (query.dialect) {
14334
+ case "postgres":
14335
+ prefix = `explain (${[
14336
+ ...analyze ? ["analyze true"] : [],
14337
+ `format ${format}`
14338
+ ].join(", ")}) `;
14339
+ break;
14340
+ case "mysql":
14341
+ if (analyze && format === "json") {
14342
+ throw new Error("MySQL EXPLAIN ANALYZE cannot be combined with JSON format");
14343
+ }
14344
+ prefix = analyze ? "explain analyze " : format === "json" ? "explain format=json " : "explain ";
14345
+ break;
14346
+ case "sqlite":
14347
+ if (analyze || format === "json") {
14348
+ throw new Error("SQLite EXPLAIN QUERY PLAN does not support analyze or JSON format");
14349
+ }
14350
+ prefix = "explain query plan ";
14351
+ break;
14352
+ default:
14353
+ if (analyze || format === "json") {
14354
+ throw new Error("Portable EXPLAIN only supports text plans without analyze");
14355
+ }
14356
+ prefix = "explain ";
14357
+ }
14358
+ return {
14359
+ ...query,
14360
+ sql: prefix + query.sql,
14361
+ projections: [],
14362
+ [TypeId10]: {
14363
+ row: undefined,
14364
+ dialect: query.dialect
14365
+ }
14366
+ };
14367
+ };
12039
14368
  var streamFromSqlClient = (query) => Stream.unwrap(Effect.flatMap(SqlClient.SqlClient, (sql) => Effect.flatMap(Effect.serviceOption(sql.transactionService), Option.match({
12040
14369
  onNone: () => sql.reserve,
12041
14370
  onSome: ([connection]) => Effect.succeed(connection)
@@ -12046,56 +14375,6 @@ var fromSqlClient = (renderer) => fromDriver(renderer, driver(renderer.dialect,
12046
14375
  }));
12047
14376
  var withTransaction = (effect) => Effect.flatMap(SqlClient.SqlClient, (sql) => sql.withTransaction(effect));
12048
14377
 
12049
- // src/internal/renderer.ts
12050
- var TypeId10 = Symbol.for("effect-qb/Renderer");
12051
- var projectionPathKey = (path2) => JSON.stringify(path2);
12052
- var formatProjectionPath2 = (path2) => path2.join(".");
12053
- var validateProjectionPathsMatchSelection = (plan, projections) => {
12054
- const expected = flattenSelection(getAst(plan).select);
12055
- const expectedPaths = new Set(expected.map((projection) => projectionPathKey(projection.path)));
12056
- const actualPaths = new Set(projections.map((projection) => projectionPathKey(projection.path)));
12057
- for (const projection of projections) {
12058
- if (!expectedPaths.has(projectionPathKey(projection.path))) {
12059
- throw new Error(`Projection path ${formatProjectionPath2(projection.path)} does not exist in the query selection`);
12060
- }
12061
- }
12062
- for (const projection of expected) {
12063
- if (!actualPaths.has(projectionPathKey(projection.path))) {
12064
- throw new Error(`Projection path ${formatProjectionPath2(projection.path)} is missing from rendered projections`);
12065
- }
12066
- }
12067
- };
12068
- function makeTrusted(dialect, render2) {
12069
- return makeRenderer(dialect, render2, false);
12070
- }
12071
- var makeRenderer = (dialect, render2, validate) => {
12072
- if (typeof render2 !== "function") {
12073
- throw new Error(`Renderer.make requires an explicit render implementation for dialect: ${dialect}`);
12074
- }
12075
- return {
12076
- dialect,
12077
- render(plan) {
12078
- const rendered = render2(plan);
12079
- const projections = rendered.projections ?? [];
12080
- if (validate) {
12081
- validateProjections(projections);
12082
- validateProjectionPathsMatchSelection(plan, projections);
12083
- }
12084
- return {
12085
- sql: rendered.sql,
12086
- params: rendered.params ?? [],
12087
- projections,
12088
- valueMappings: rendered.valueMappings,
12089
- dialect,
12090
- [TypeId10]: {
12091
- row: undefined,
12092
- dialect
12093
- }
12094
- };
12095
- }
12096
- };
12097
- };
12098
-
12099
14378
  // src/postgres/internal/renderer.ts
12100
14379
  var renderPostgresPlan = (plan, options2 = {}) => {
12101
14380
  const state = {
@@ -12117,42 +14396,74 @@ var renderPostgresPlan = (plan, options2 = {}) => {
12117
14396
  };
12118
14397
 
12119
14398
  // src/postgres/executor.ts
14399
+ var atMostOne2 = atMostOne;
14400
+ var exactlyOne2 = exactlyOne;
14401
+ var nonEmpty2 = nonEmpty;
12120
14402
  var withTransaction2 = withTransaction;
12121
14403
  function driver2(dialectOrExecute, maybeExecute) {
12122
14404
  const executeOrHandlers = typeof dialectOrExecute === "string" ? maybeExecute : dialectOrExecute;
12123
14405
  return typeof executeOrHandlers === "function" ? driver("postgres", executeOrHandlers) : driver("postgres", executeOrHandlers);
12124
14406
  }
12125
- var fromDriver2 = (renderer, sqlDriver, driverMode = "raw", valueMappings) => ({
12126
- dialect: "postgres",
12127
- execute(plan) {
12128
- const rendered = renderer.render(plan);
12129
- return Effect2.mapError(Effect2.flatMap(sqlDriver.execute(rendered), (rows) => Effect2.try({
12130
- try: () => decodeRows(rendered, plan, rows, { driverMode, valueMappings }),
12131
- catch: (error) => error
12132
- })), (error) => {
12133
- if (typeof error === "object" && error !== null && "_tag" in error && error._tag === "RowDecodeError") {
12134
- return error;
12135
- }
12136
- const normalized = normalizePostgresDriverError(error, rendered);
12137
- return hasWriteCapability(plan) ? normalized : narrowPostgresDriverErrorForReadQuery(normalized);
12138
- });
12139
- },
12140
- stream(plan) {
14407
+ var fromDriver2 = (renderer, sqlDriver, driverMode = "raw", valueMappings) => {
14408
+ const renderedCache = new WeakMap;
14409
+ const render2 = (plan) => {
14410
+ const cached = renderedCache.get(plan);
14411
+ if (cached !== undefined) {
14412
+ return cached;
14413
+ }
12141
14414
  const rendered = renderer.render(plan);
12142
- return Stream2.mapError(Stream2.mapArrayEffect(sqlDriver.stream(rendered), (rows) => Effect2.try({
12143
- try: () => decodeRows(rendered, plan, rows, { driverMode, valueMappings }),
12144
- catch: (error) => error
12145
- })), (error) => {
12146
- if (typeof error === "object" && error !== null && "_tag" in error && error._tag === "RowDecodeError") {
12147
- return error;
12148
- }
12149
- const normalized = normalizePostgresDriverError(error, rendered);
12150
- return hasWriteCapability(plan) ? normalized : narrowPostgresDriverErrorForReadQuery(normalized);
12151
- });
12152
- }
12153
- });
14415
+ renderedCache.set(plan, rendered);
14416
+ return rendered;
14417
+ };
14418
+ const mapExecutionError = (error, rendered, plan) => {
14419
+ if (typeof error === "object" && error !== null && "_tag" in error && error._tag === "RowDecodeError") {
14420
+ return error;
14421
+ }
14422
+ const normalized = normalizePostgresDriverError(error, rendered);
14423
+ return hasWriteCapability(plan) ? normalized : narrowPostgresDriverErrorForReadQuery(normalized);
14424
+ };
14425
+ return withResultContracts({
14426
+ dialect: "postgres",
14427
+ execute(plan) {
14428
+ const rendered = render2(plan);
14429
+ return Effect2.mapError(Effect2.flatMap(sqlDriver.execute(rendered), (rows) => Effect2.try({
14430
+ try: () => decodeRows(rendered, plan, rows, { driverMode, valueMappings }),
14431
+ catch: (error) => error
14432
+ })), (error) => mapExecutionError(error, rendered, plan));
14433
+ },
14434
+ executeResult(plan) {
14435
+ const rendered = render2(plan);
14436
+ const result = sqlDriver.executeResult ? sqlDriver.executeResult(rendered) : Effect2.map(sqlDriver.execute(rendered), (rows) => ({ rows }));
14437
+ return Effect2.mapError(Effect2.flatMap(result, ({ rows, ...metadata }) => Effect2.try({
14438
+ try: () => ({
14439
+ ...metadata,
14440
+ rows: decodeRows(rendered, plan, rows, { driverMode, valueMappings })
14441
+ }),
14442
+ catch: (error) => error
14443
+ })), (error) => mapExecutionError(error, rendered, plan));
14444
+ },
14445
+ stream(plan) {
14446
+ const rendered = render2(plan);
14447
+ return Stream2.mapError(Stream2.mapArrayEffect(sqlDriver.stream(rendered), (rows) => Effect2.try({
14448
+ try: () => decodeRows(rendered, plan, rows, { driverMode, valueMappings }),
14449
+ catch: (error) => error
14450
+ })), (error) => mapExecutionError(error, rendered, plan));
14451
+ },
14452
+ explain(plan, options2) {
14453
+ const rendered = explainQuery(render2(plan), options2);
14454
+ return Effect2.mapError(sqlDriver.execute(rendered), (error) => mapExecutionError(error, rendered, plan));
14455
+ }
14456
+ });
14457
+ };
12154
14458
  var sqlClientDriver = () => driver2({
12155
14459
  execute: (query) => Effect2.flatMap(SqlClient3.SqlClient, (sql) => sql.unsafe(query.sql, [...query.params])),
14460
+ executeResult: (query) => Effect2.flatMap(SqlClient3.SqlClient, (sql) => Effect2.map(sql.unsafe(query.sql, [...query.params]).raw, (raw) => {
14461
+ const result = raw;
14462
+ return {
14463
+ rows: result.rows ?? [],
14464
+ ...typeof result.rowCount === "number" ? { affectedRows: result.rowCount } : {}
14465
+ };
14466
+ })),
12156
14467
  stream: (query) => streamFromSqlClient(query)
12157
14468
  });
12158
14469
  function make4(options2 = {}) {
@@ -12161,16 +14472,16 @@ function make4(options2 = {}) {
12161
14472
  }
12162
14473
  return fromDriver2(options2.renderer ?? makeTrusted("postgres", (plan) => renderPostgresPlan(plan, { valueMappings: options2.valueMappings })), sqlClientDriver(), options2.driverMode, options2.valueMappings);
12163
14474
  }
12164
- var custom3 = (execute) => make3("postgres", execute);
14475
+ var custom4 = (execute) => make3("postgres", execute);
12165
14476
  // src/postgres/query-extension.ts
12166
14477
  var exports_query_extension = {};
12167
14478
  __export(exports_query_extension, {
12168
14479
  onConflict: () => onConflict,
12169
- generateSeries: () => generateSeries2,
14480
+ generateSeries: () => generateSeries3,
12170
14481
  distinctOn: () => distinctOn
12171
14482
  });
12172
14483
  // src/postgres/query.ts
12173
- var generateSeries2 = generateSeries;
14484
+ var generateSeries3 = generateSeries;
12174
14485
  // src/postgres/type.ts
12175
14486
  var array4 = (element) => ({
12176
14487
  dialect: "postgres",
@@ -12202,15 +14513,15 @@ var enum_2 = (kind) => ({
12202
14513
  kind,
12203
14514
  variant: "enum"
12204
14515
  });
12205
- var custom4 = (kind) => ({
14516
+ var custom5 = (kind) => ({
12206
14517
  dialect: "postgres",
12207
14518
  kind
12208
14519
  });
12209
- var driverValueMapping3 = (dbType, mapping) => ({
14520
+ var driverValueMapping4 = (dbType, mapping) => ({
12210
14521
  ...dbType,
12211
14522
  driverValueMapping: mapping
12212
14523
  });
12213
- var type2 = {
14524
+ var type3 = {
12214
14525
  ...pickDatatypeConstructors(postgresDatatypes, postgresSpecificDatatypeKeys),
12215
14526
  array: array4,
12216
14527
  range: range2,
@@ -12218,8 +14529,8 @@ var type2 = {
12218
14529
  record: record2,
12219
14530
  domain: domain2,
12220
14531
  enum: enum_2,
12221
- custom: custom4,
12222
- driverValueMapping: driverValueMapping3
14532
+ custom: custom5,
14533
+ driverValueMapping: driverValueMapping4
12223
14534
  };
12224
14535
  // src/postgres/schema-expression.ts
12225
14536
  var exports_schema_expression2 = {};
@@ -12240,7 +14551,7 @@ var exports_schema = {};
12240
14551
  __export(exports_schema, {
12241
14552
  make: () => make6
12242
14553
  });
12243
- import { pipeArguments as pipeArguments9 } from "effect/Pipeable";
14554
+ import { pipeArguments as pipeArguments10 } from "effect/Pipeable";
12244
14555
 
12245
14556
  // src/standard/table.ts
12246
14557
  var exports_table2 = {};
@@ -12285,7 +14596,7 @@ var updateSchema3 = updateSchema2;
12285
14596
  // src/postgres/schema.ts
12286
14597
  var SchemaProto = {
12287
14598
  pipe() {
12288
- return pipeArguments9(this, arguments);
14599
+ return pipeArguments10(this, arguments);
12289
14600
  }
12290
14601
  };
12291
14602
  var make6 = (schemaName, options3 = {}) => {
@@ -12299,7 +14610,7 @@ var make6 = (schemaName, options3 = {}) => {
12299
14610
  }
12300
14611
  return options3.casing === undefined ? table : withCasing(table, options3.casing);
12301
14612
  };
12302
- namespace.enum = (name2, values3) => enumType(applyCategory(options3.casing, "types", name2), values3, physicalSchemaName);
14613
+ namespace.enum = (name2, values4) => enumType(applyCategory(options3.casing, "types", name2), values4, physicalSchemaName);
12303
14614
  namespace.sequence = (name2) => sequence(applyCategory(options3.casing, "sequences", name2), physicalSchemaName);
12304
14615
  namespace.withSchema = (table) => withSchema(table, schemaName, options3.casing);
12305
14616
  namespace[TypeId6] = {
@@ -12346,7 +14657,7 @@ var nullsNotDistinct = (option3) => mapOption(option3, (spec) => ({
12346
14657
  // src/postgres/index.ts
12347
14658
  var exports_postgres = {};
12348
14659
  __export(exports_postgres, {
12349
- where: () => where2,
14660
+ where: () => where3,
12350
14661
  using: () => using,
12351
14662
  uniqueIndex: () => uniqueIndex,
12352
14663
  keys: () => keys3,
@@ -12385,18 +14696,18 @@ var include = (columns) => (option3) => optionFromTable({
12385
14696
  ...resolveOption(option3, table),
12386
14697
  include: selectedColumnList(columns(table))
12387
14698
  }));
12388
- var where2 = (predicate) => (option3) => mapOption(option3, (spec) => ({
14699
+ var where3 = (predicate) => (option3) => mapOption(option3, (spec) => ({
12389
14700
  ...spec,
12390
14701
  predicate
12391
14702
  }));
12392
- var key3 = (column2, options3) => (option3) => optionFromTable({
14703
+ var key3 = (column3, options3) => (option3) => optionFromTable({
12393
14704
  ...option3.option,
12394
14705
  columns: undefined,
12395
14706
  keys: []
12396
14707
  }, (table) => ({
12397
14708
  ...resolveOption(option3, table),
12398
14709
  columns: undefined,
12399
- keys: [normalizeIndexKey({ column: column2(table), ...options3 })]
14710
+ keys: [normalizeIndexKey({ column: column3(table), ...options3 })]
12400
14711
  }));
12401
14712
  var keys3 = (keys4) => (option3) => optionFromTable({
12402
14713
  ...option3.option,
@@ -12441,10 +14752,10 @@ __export(exports_renderer2, {
12441
14752
  make: () => make7,
12442
14753
  TypeId: () => TypeId10
12443
14754
  });
12444
- import { pipeArguments as pipeArguments10 } from "effect/Pipeable";
14755
+ import { pipeArguments as pipeArguments11 } from "effect/Pipeable";
12445
14756
  var RendererProto = {
12446
14757
  pipe() {
12447
- return pipeArguments10(this, arguments);
14758
+ return pipeArguments11(this, arguments);
12448
14759
  }
12449
14760
  };
12450
14761
  var makeWithState = (state = {}) => {
@@ -12465,7 +14776,7 @@ export {
12465
14776
  sequence,
12466
14777
  enumType as enum,
12467
14778
  exports_unique as Unique,
12468
- type2 as Type,
14779
+ type3 as Type,
12469
14780
  exports_schema_expression2 as SchemaExpression,
12470
14781
  exports_schema as Schema,
12471
14782
  exports_renderer2 as Renderer,