@rex0220/kintone-sql-tools 3.66.0 → 3.67.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.
package/dist-cli/ksql.js CHANGED
@@ -9376,15 +9376,15 @@ function selectScalarExtreme(values, extreme) {
9376
9376
  }
9377
9377
 
9378
9378
  // src/engine/evalFunc.ts
9379
- function evalArithExpr(expr, row) {
9379
+ function evalArithExpr(expr, row, context = {}) {
9380
9380
  if (expr.type === "VARIABLE") throw new Error(
9381
9381
  `InternalError: unresolved arithmetic variable @${expr.name} reached arithmetic evaluation.`
9382
9382
  );
9383
9383
  if (expr.type === "NUMBER") return expr.value;
9384
9384
  if (expr.type === "FIELD_REF") return Number(resolveFieldRef(row, expr.field));
9385
- if (expr.type === "STRING_FUNC") return Number(evalStringFunc(expr, row));
9386
- const l = evalArithExpr(expr.left, row);
9387
- const r = evalArithExpr(expr.right, row);
9385
+ if (expr.type === "STRING_FUNC") return Number(evalStringFunc(expr, row, void 0, void 0, context));
9386
+ const l = evalArithExpr(expr.left, row, context);
9387
+ const r = evalArithExpr(expr.right, row, context);
9388
9388
  switch (expr.op) {
9389
9389
  case "+":
9390
9390
  return l + r;
@@ -9398,7 +9398,7 @@ function evalArithExpr(expr, row) {
9398
9398
  return r !== 0 ? l % r : NaN;
9399
9399
  }
9400
9400
  }
9401
- function evalScalarValueExpr(expr, row, resolveFieldType, resolveFieldSemantics2) {
9401
+ function evalScalarValueExpr(expr, row, resolveFieldType, resolveFieldSemantics2, context = {}) {
9402
9402
  switch (expr.type) {
9403
9403
  case "STRING":
9404
9404
  return expr.value;
@@ -9409,19 +9409,19 @@ function evalScalarValueExpr(expr, row, resolveFieldType, resolveFieldSemantics2
9409
9409
  case "VARIABLE":
9410
9410
  throw new Error(`ArgumentError: unresolved variable @${expr.name} reached scalar evaluator.`);
9411
9411
  case "STRING_FUNC":
9412
- return evalStringFunc(expr, row, resolveFieldType, resolveFieldSemantics2);
9412
+ return evalStringFunc(expr, row, resolveFieldType, resolveFieldSemantics2, context);
9413
9413
  case "CASE_WHEN":
9414
- return evalCaseWhen(expr, row, resolveFieldType, resolveFieldSemantics2);
9414
+ return evalCaseWhen(expr, row, resolveFieldType, resolveFieldSemantics2, context);
9415
9415
  case "CONCAT_OP": {
9416
9416
  return evalStringFunc({
9417
9417
  type: "STRING_FUNC",
9418
9418
  func: "CONCAT",
9419
9419
  args: [expr.left, expr.right]
9420
- }, row, resolveFieldType, resolveFieldSemantics2);
9420
+ }, row, resolveFieldType, resolveFieldSemantics2, context);
9421
9421
  }
9422
9422
  case "SCALAR_ARITH": {
9423
- const left = Number(evalScalarValueExpr(expr.left, row, resolveFieldType, resolveFieldSemantics2));
9424
- const right = Number(evalScalarValueExpr(expr.right, row, resolveFieldType, resolveFieldSemantics2));
9423
+ const left = Number(evalScalarValueExpr(expr.left, row, resolveFieldType, resolveFieldSemantics2, context));
9424
+ const right = Number(evalScalarValueExpr(expr.right, row, resolveFieldType, resolveFieldSemantics2, context));
9425
9425
  switch (expr.op) {
9426
9426
  case "+":
9427
9427
  return left + right;
@@ -9437,13 +9437,13 @@ function evalScalarValueExpr(expr, row, resolveFieldType, resolveFieldSemantics2
9437
9437
  }
9438
9438
  }
9439
9439
  }
9440
- function evalScalarValueExprNullable(expr, row, resolveFieldType, resolveFieldSemantics2) {
9440
+ function evalScalarValueExprNullable(expr, row, resolveFieldType, resolveFieldSemantics2, context = {}) {
9441
9441
  switch (expr.type) {
9442
9442
  case "CASE_WHEN":
9443
- return evalCaseWhenNullable(expr, row, resolveFieldType, resolveFieldSemantics2);
9443
+ return evalCaseWhenNullable(expr, row, resolveFieldType, resolveFieldSemantics2, context);
9444
9444
  case "SCALAR_ARITH": {
9445
- const left = evalScalarValueExprNullable(expr.left, row, resolveFieldType, resolveFieldSemantics2);
9446
- const right = evalScalarValueExprNullable(expr.right, row, resolveFieldType, resolveFieldSemantics2);
9445
+ const left = evalScalarValueExprNullable(expr.left, row, resolveFieldType, resolveFieldSemantics2, context);
9446
+ const right = evalScalarValueExprNullable(expr.right, row, resolveFieldType, resolveFieldSemantics2, context);
9447
9447
  if (left === null || right === null) return null;
9448
9448
  const l = Number(left);
9449
9449
  const r = Number(right);
@@ -9461,12 +9461,12 @@ function evalScalarValueExprNullable(expr, row, resolveFieldType, resolveFieldSe
9461
9461
  }
9462
9462
  }
9463
9463
  case "CONCAT_OP": {
9464
- const left = evalScalarValueExprNullable(expr.left, row, resolveFieldType, resolveFieldSemantics2);
9465
- const right = evalScalarValueExprNullable(expr.right, row, resolveFieldType, resolveFieldSemantics2);
9464
+ const left = evalScalarValueExprNullable(expr.left, row, resolveFieldType, resolveFieldSemantics2, context);
9465
+ const right = evalScalarValueExprNullable(expr.right, row, resolveFieldType, resolveFieldSemantics2, context);
9466
9466
  return `${left ?? ""}${right ?? ""}`;
9467
9467
  }
9468
9468
  default:
9469
- return evalScalarValueExpr(expr, row, resolveFieldType, resolveFieldSemantics2);
9469
+ return evalScalarValueExpr(expr, row, resolveFieldType, resolveFieldSemantics2, context);
9470
9470
  }
9471
9471
  }
9472
9472
  function applyRoundOp(op, num, digits) {
@@ -9618,9 +9618,9 @@ function replaceNthMatch(input, globalRe, replacement, n) {
9618
9618
  return expandRegexpReplacement(replacement, match, captures, namedGroups);
9619
9619
  });
9620
9620
  }
9621
- function evalStringFunc(expr, row, resolveFieldType, resolveFieldSemantics2) {
9621
+ function evalStringFunc(expr, row, resolveFieldType, resolveFieldSemantics2, context = {}) {
9622
9622
  assertStringFunctionArity(expr.func, expr.args);
9623
- const args = expr.args.map((a) => evalStringFuncArg(a, row, resolveFieldType, resolveFieldSemantics2));
9623
+ const args = expr.args.map((a) => evalStringFuncArg(a, row, resolveFieldType, resolveFieldSemantics2, context));
9624
9624
  switch (expr.func) {
9625
9625
  case "UPPER":
9626
9626
  return (args[0] ?? "").toUpperCase();
@@ -9768,14 +9768,14 @@ function evalStringFunc(expr, row, resolveFieldType, resolveFieldSemantics2) {
9768
9768
  case "SQRT":
9769
9769
  return String(Math.sqrt(Number(args[0] ?? "0")));
9770
9770
  case "CURRENT_DATE": {
9771
- const now = /* @__PURE__ */ new Date();
9771
+ const now = context.statementInstant ?? /* @__PURE__ */ new Date();
9772
9772
  const y = now.getFullYear();
9773
9773
  const m = String(now.getMonth() + 1).padStart(2, "0");
9774
9774
  const d = String(now.getDate()).padStart(2, "0");
9775
9775
  return `${y}-${m}-${d}`;
9776
9776
  }
9777
9777
  case "CURRENT_TIMESTAMP":
9778
- return (/* @__PURE__ */ new Date()).toISOString();
9778
+ return (context.statementInstant ?? /* @__PURE__ */ new Date()).toISOString();
9779
9779
  }
9780
9780
  }
9781
9781
  function parseDateParts(s) {
@@ -9937,12 +9937,12 @@ function formatWithComma(num, digits) {
9937
9937
  const intFmt = intStr.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
9938
9938
  return decStr ? `${intFmt}.${decStr}` : intFmt;
9939
9939
  }
9940
- function evalStringFuncArg(arg, row, resolveFieldType, resolveFieldSemantics2) {
9940
+ function evalStringFuncArg(arg, row, resolveFieldType, resolveFieldSemantics2, context = {}) {
9941
9941
  if (arg.type === "AGG_REF" || arg.type === "AGG_ARITH" || arg.type === "AGG_GROUP_KEY") {
9942
9942
  return String(evalMaterializedAggregateOperand(arg, row));
9943
9943
  }
9944
9944
  if (arg.type === "NUMBER") return numberLiteralText(arg);
9945
- return String(evalScalarValueExpr(arg, row, resolveFieldType, resolveFieldSemantics2));
9945
+ return String(evalScalarValueExpr(arg, row, resolveFieldType, resolveFieldSemantics2, context));
9946
9946
  }
9947
9947
  function evalMaterializedAggregateOperand(node, row) {
9948
9948
  if (node.type === "NUMBER") return node.value;
@@ -9983,37 +9983,37 @@ function resolveFieldRef(row, field) {
9983
9983
  }
9984
9984
 
9985
9985
  // src/engine/evalWhere.ts
9986
- function evalWhere(expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2) {
9986
+ function evalWhere(expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2, context = {}) {
9987
9987
  switch (expr.type) {
9988
9988
  case "BOOLEAN":
9989
9989
  return expr.value;
9990
9990
  case "BINARY":
9991
- return evalBinary(expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2);
9991
+ return evalBinary(expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2, context);
9992
9992
  case "NULL_CHECK":
9993
9993
  return evalNullCheck(expr, row);
9994
9994
  case "LOGICAL":
9995
- return evalLogical(expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2);
9995
+ return evalLogical(expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2, context);
9996
9996
  case "NOT":
9997
- return !evalWhere(expr.expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2);
9997
+ return !evalWhere(expr.expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2, context);
9998
9998
  case "GROUP":
9999
- return evalWhere(expr.expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2);
9999
+ return evalWhere(expr.expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2, context);
10000
10000
  case "EXISTS": {
10001
10001
  const exists = expr.resolved;
10002
10002
  return expr.not ? !exists : exists;
10003
10003
  }
10004
10004
  }
10005
10005
  }
10006
- function evalBinary(expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2) {
10006
+ function evalBinary(expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2, context = {}) {
10007
10007
  if (expr.op === "KLIKE" || expr.op === "NOT_KLIKE") {
10008
10008
  if (appliedKlikes?.has(expr)) return true;
10009
10009
  throw new Error("KLIKE / NOT KLIKE \u306F\u62BC\u3057\u4E0B\u3052\u6E08\u307F\u96C6\u5408\u306B\u542B\u307E\u308C\u306A\u3044\u305F\u3081 JavaScript \u5074\u3067\u306F\u8A55\u4FA1\u3067\u304D\u307E\u305B\u3093");
10010
10010
  }
10011
- const left = resolveField(expr.left, row, resolveFieldType, resolveFieldSemantics2);
10011
+ const left = resolveField(expr.left, row, resolveFieldType, resolveFieldSemantics2, context);
10012
10012
  const fieldType = expr.left.type === "FIELD" ? resolveFieldType?.(expr.left) : void 0;
10013
10013
  const semantics = semanticsForLeft(expr.left, fieldType, resolveFieldSemantics2);
10014
- return evalOp(expr.op, left, expr.right, row, fieldType, resolveFieldType, semantics, resolveFieldSemantics2);
10014
+ return evalOp(expr.op, left, expr.right, row, fieldType, resolveFieldType, semantics, resolveFieldSemantics2, context);
10015
10015
  }
10016
- function evalOp(op, leftStr, right, row, fieldType, resolveFieldType, semantics = syntheticSemantics("string"), resolveFieldSemantics2) {
10016
+ function evalOp(op, leftStr, right, row, fieldType, resolveFieldType, semantics = syntheticSemantics("string"), resolveFieldSemantics2, context = {}) {
10017
10017
  if (op === "IN" || op === "NOT_IN") {
10018
10018
  let values = null;
10019
10019
  if (right.type === "IN_LIST") {
@@ -10028,17 +10028,17 @@ function evalOp(op, leftStr, right, row, fieldType, resolveFieldType, semantics
10028
10028
  return op === "IN" ? contains : !contains;
10029
10029
  }
10030
10030
  if (op === "LIKE") {
10031
- const pattern = resolveValue(right, row, resolveFieldType);
10031
+ const pattern = resolveValue(right, row, resolveFieldType, void 0, context);
10032
10032
  return matchLike(leftStr, pattern);
10033
10033
  }
10034
10034
  if (op === "NOT_LIKE") {
10035
- const pattern = resolveValue(right, row, resolveFieldType);
10035
+ const pattern = resolveValue(right, row, resolveFieldType, void 0, context);
10036
10036
  return !matchLike(leftStr, pattern);
10037
10037
  }
10038
10038
  if (op === "KLIKE" || op === "NOT_KLIKE") {
10039
10039
  throw new Error("KLIKE / NOT KLIKE \u306F JavaScript \u5074\u3067\u306F\u8A55\u4FA1\u3067\u304D\u307E\u305B\u3093\uFF08SIMPLE SELECT \u3067\u306E\u307F\u4F7F\u7528\u3067\u304D\u307E\u3059\uFF09");
10040
10040
  }
10041
- const rightStr = resolveValue(right, row, resolveFieldType, resolveFieldSemantics2);
10041
+ const rightStr = resolveValue(right, row, resolveFieldType, resolveFieldSemantics2, context);
10042
10042
  return compareScalarValues(op, leftStr, rightStr, semantics);
10043
10043
  }
10044
10044
  var NUMERIC_STRING_FUNCTIONS = /* @__PURE__ */ new Set([
@@ -10150,17 +10150,17 @@ function evalNullCheck(expr, row) {
10150
10150
  const val = resolveField(expr.field, row);
10151
10151
  return expr.not ? val !== "" : val === "";
10152
10152
  }
10153
- function evalLogical(expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2) {
10153
+ function evalLogical(expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2, context = {}) {
10154
10154
  if (expr.op === "AND") {
10155
- return evalWhere(expr.left, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2) && evalWhere(expr.right, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2);
10155
+ return evalWhere(expr.left, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2, context) && evalWhere(expr.right, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2, context);
10156
10156
  }
10157
- return evalWhere(expr.left, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2) || evalWhere(expr.right, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2);
10157
+ return evalWhere(expr.left, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2, context) || evalWhere(expr.right, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2, context);
10158
10158
  }
10159
- function resolveField(field, row, resolveFieldType, resolveFieldSemantics2) {
10160
- if (field.type === "FUNC_FIELD") return evalStringFunc(field.expr, row);
10159
+ function resolveField(field, row, resolveFieldType, resolveFieldSemantics2, context = {}) {
10160
+ if (field.type === "FUNC_FIELD") return evalStringFunc(field.expr, row, void 0, void 0, context);
10161
10161
  if (field.type === "AGG_FIELD") return String(evalMaterializedAggregateOperand(field.expr, row));
10162
- if (field.type === "ARITH_FIELD") return String(evalArithExpr(field.expr, row));
10163
- if (field.type === "CASE_FIELD") return evalCaseWhen(field.expr, row, resolveFieldType, resolveFieldSemantics2);
10162
+ if (field.type === "ARITH_FIELD") return String(evalArithExpr(field.expr, row, context));
10163
+ if (field.type === "CASE_FIELD") return evalCaseWhen(field.expr, row, resolveFieldType, resolveFieldSemantics2, context);
10164
10164
  if (field.type === "GROUPING_FIELD") return evalGroupingRef(field.ref, row);
10165
10165
  if (field.aggregateRef) {
10166
10166
  const ref = field.aggregateRef;
@@ -10169,7 +10169,7 @@ function resolveField(field, row, resolveFieldType, resolveFieldSemantics2) {
10169
10169
  const key = field.tableAlias ? `${field.tableAlias}.${field.field}` : field.field;
10170
10170
  return resolveFieldRef(row, key);
10171
10171
  }
10172
- function resolveValue(value, row, resolveFieldType, resolveFieldSemantics2) {
10172
+ function resolveValue(value, row, resolveFieldType, resolveFieldSemantics2, context = {}) {
10173
10173
  switch (value.type) {
10174
10174
  case "VARIABLE":
10175
10175
  throw new Error(`ParseError: unresolved batch variable @${value.name}.`);
@@ -10191,44 +10191,44 @@ function resolveValue(value, row, resolveFieldType, resolveFieldSemantics2) {
10191
10191
  return value.resolved;
10192
10192
  case "ARITH_VALUE":
10193
10193
  if (value.expr.type === "FIELD_REF") return resolveFieldRef(row, value.expr.field);
10194
- if (value.expr.type === "STRING_FUNC") return evalStringFunc(value.expr, row);
10195
- return String(evalArithExpr(value.expr, row));
10194
+ if (value.expr.type === "STRING_FUNC") return evalStringFunc(value.expr, row, void 0, void 0, context);
10195
+ return String(evalArithExpr(value.expr, row, context));
10196
10196
  case "CASE_VALUE":
10197
- return evalCaseWhen(value.expr, row, resolveFieldType, resolveFieldSemantics2);
10197
+ return evalCaseWhen(value.expr, row, resolveFieldType, resolveFieldSemantics2, context);
10198
10198
  case "ARRAY":
10199
10199
  return value.elements.map((e) => e.value).join(",");
10200
10200
  }
10201
10201
  }
10202
- function evalCaseWhen(expr, row, resolveFieldType, resolveFieldSemantics2) {
10202
+ function evalCaseWhen(expr, row, resolveFieldType, resolveFieldSemantics2, context = {}) {
10203
10203
  for (const branch of expr.branches) {
10204
- if (evalWhere(branch.condition, row, resolveFieldType, void 0, resolveFieldSemantics2)) {
10205
- return evalCaseResult(branch.result, row, resolveFieldType, resolveFieldSemantics2);
10204
+ if (evalWhere(branch.condition, row, resolveFieldType, void 0, resolveFieldSemantics2, context)) {
10205
+ return evalCaseResult(branch.result, row, resolveFieldType, resolveFieldSemantics2, context);
10206
10206
  }
10207
10207
  }
10208
10208
  if (expr.elseResult !== null) {
10209
- return evalCaseResult(expr.elseResult, row, resolveFieldType, resolveFieldSemantics2);
10209
+ return evalCaseResult(expr.elseResult, row, resolveFieldType, resolveFieldSemantics2, context);
10210
10210
  }
10211
10211
  return "";
10212
10212
  }
10213
- function evalCaseWhenNullable(expr, row, resolveFieldType, resolveFieldSemantics2) {
10213
+ function evalCaseWhenNullable(expr, row, resolveFieldType, resolveFieldSemantics2, context = {}) {
10214
10214
  for (const branch of expr.branches) {
10215
- if (evalWhere(branch.condition, row, resolveFieldType, void 0, resolveFieldSemantics2)) {
10216
- return evalCaseResultNullable(branch.result, row, resolveFieldType, resolveFieldSemantics2);
10215
+ if (evalWhere(branch.condition, row, resolveFieldType, void 0, resolveFieldSemantics2, context)) {
10216
+ return evalCaseResultNullable(branch.result, row, resolveFieldType, resolveFieldSemantics2, context);
10217
10217
  }
10218
10218
  }
10219
- return expr.elseResult === null ? null : evalCaseResultNullable(expr.elseResult, row, resolveFieldType, resolveFieldSemantics2);
10219
+ return expr.elseResult === null ? null : evalCaseResultNullable(expr.elseResult, row, resolveFieldType, resolveFieldSemantics2, context);
10220
10220
  }
10221
- function evalCaseResultNullable(result, row, resolveFieldType, resolveFieldSemantics2) {
10221
+ function evalCaseResultNullable(result, row, resolveFieldType, resolveFieldSemantics2, context = {}) {
10222
10222
  if (result.type === "ARRAY") return result.elements.map((entry) => entry.value).join(",");
10223
10223
  if (result.type === "AGG_REF") {
10224
10224
  return row[aggregateSyntheticName(result.func, result.distinct, result.arg)] ?? "";
10225
10225
  }
10226
10226
  if (result.type === "AGG_ARITH") return row[aggregateOperandLabel(result)] ?? "";
10227
10227
  if (result.type === "FIELD_REF") return row[result.field] ?? "";
10228
- if (result.type === "ARITH") return evalArithExpr(result, row);
10229
- return evalScalarValueExprNullable(result, row, resolveFieldType, resolveFieldSemantics2);
10228
+ if (result.type === "ARITH") return evalArithExpr(result, row, context);
10229
+ return evalScalarValueExprNullable(result, row, resolveFieldType, resolveFieldSemantics2, context);
10230
10230
  }
10231
- function evalCaseResult(result, row, resolveFieldType, resolveFieldSemantics2) {
10231
+ function evalCaseResult(result, row, resolveFieldType, resolveFieldSemantics2, context = {}) {
10232
10232
  if (result.type === "ARRAY") return result.elements.map((e) => e.value).join(",");
10233
10233
  if (result.type === "AGG_REF") {
10234
10234
  return row[aggregateSyntheticName(result.func, result.distinct, result.arg)] ?? "";
@@ -10238,12 +10238,12 @@ function evalCaseResult(result, row, resolveFieldType, resolveFieldSemantics2) {
10238
10238
  return row[result.field] ?? "";
10239
10239
  }
10240
10240
  if (result.type === "ARITH") {
10241
- return String(evalArithExpr(result, row));
10241
+ return String(evalArithExpr(result, row, context));
10242
10242
  }
10243
- return String(evalScalarValueExpr(result, row, resolveFieldType, resolveFieldSemantics2));
10243
+ return String(evalScalarValueExpr(result, row, resolveFieldType, resolveFieldSemantics2, context));
10244
10244
  }
10245
- function resolveKintoneFunc(name) {
10246
- const now = /* @__PURE__ */ new Date();
10245
+ function resolveKintoneFunc(name, context = {}) {
10246
+ const now = context.statementInstant ?? /* @__PURE__ */ new Date();
10247
10247
  switch (name) {
10248
10248
  case "TODAY": {
10249
10249
  const y = now.getFullYear();
@@ -10367,21 +10367,21 @@ function assertDmlWhereIsSafe(where) {
10367
10367
  }
10368
10368
  var USER_TYPES = /* @__PURE__ */ new Set(["USER_SELECT", "ORGANIZATION_SELECT", "GROUP_SELECT"]);
10369
10369
  var ARRAY_TYPES = /* @__PURE__ */ new Set(["CHECK_BOX", "MULTI_SELECT"]);
10370
- function insertToPostBatches(stmt, fieldTypes = /* @__PURE__ */ new Map()) {
10370
+ function insertToPostBatches(stmt, fieldTypes = /* @__PURE__ */ new Map(), evaluationContext = {}) {
10371
10371
  const allRecords = stmt.values.map(
10372
- (row) => buildInsertRecord(stmt.fields, row, fieldTypes)
10372
+ (row) => buildInsertRecord(stmt.fields, row, fieldTypes, evaluationContext)
10373
10373
  );
10374
10374
  return chunk(allRecords, 100).map((records) => ({
10375
10375
  app: stmt.appId,
10376
10376
  records
10377
10377
  }));
10378
10378
  }
10379
- function buildInsertRecord(fields, row, fieldTypes) {
10379
+ function buildInsertRecord(fields, row, fieldTypes, evaluationContext) {
10380
10380
  const record = {};
10381
10381
  fields.forEach((field, i) => {
10382
10382
  const val = row[i];
10383
10383
  if (val.type === "CASE_VALUE") {
10384
- record[field] = { value: evalCaseWhenValue(val.expr, {}, fieldTypes.get(field)) };
10384
+ record[field] = { value: evalCaseWhenValue(val.expr, {}, fieldTypes.get(field), evaluationContext) };
10385
10385
  } else {
10386
10386
  record[field] = { value: toKintoneValue(val, fieldTypes.get(field)) };
10387
10387
  }
@@ -10541,14 +10541,14 @@ function collectConditionFields(expr, out) {
10541
10541
  break;
10542
10542
  }
10543
10543
  }
10544
- function updateToPutBatchesArith(stmt, records, fieldTypes = /* @__PURE__ */ new Map()) {
10544
+ function updateToPutBatchesArith(stmt, records, fieldTypes = /* @__PURE__ */ new Map(), evaluationContext = {}) {
10545
10545
  const updateRecords = records.map((raw) => {
10546
10546
  const id = Number(raw["$id"].value);
10547
10547
  const row = kintoneRecordToProcessRow(raw);
10548
10548
  const record = {};
10549
10549
  for (const { field, value } of stmt.assignments) {
10550
10550
  record[field] = {
10551
- value: evaluateUpdateAssignmentValue(value, row, fieldTypes.get(field), raw)
10551
+ value: evaluateUpdateAssignmentValue(value, row, fieldTypes.get(field), raw, evaluationContext)
10552
10552
  };
10553
10553
  }
10554
10554
  return { id, record };
@@ -10558,25 +10558,31 @@ function updateToPutBatchesArith(stmt, records, fieldTypes = /* @__PURE__ */ new
10558
10558
  records: batch
10559
10559
  }));
10560
10560
  }
10561
- function evaluateUpdateAssignmentValue(value, row, fieldType, raw) {
10561
+ function evaluateUpdateAssignmentValue(value, row, fieldType, raw, evaluationContext = {}) {
10562
10562
  if (value.type === "ARITH") {
10563
- return String(raw ? evalArith(value, raw) : evalArithExpr(value, row));
10563
+ return String(raw ? evalArith(value, raw) : evalArithExpr(value, row, evaluationContext));
10564
10564
  }
10565
10565
  if (value.type === "SCALAR_ARITH" || value.type === "CONCAT_OP") {
10566
- return String(evalScalarValueExpr(value, row));
10566
+ return String(evalScalarValueExpr(value, row, void 0, void 0, evaluationContext));
10567
10567
  }
10568
- if (value.type === "STRING_FUNC") return evalStringFunc(value, row);
10569
- if (value.type === "CASE_VALUE") return evalCaseWhenValue(value.expr, row, fieldType);
10568
+ if (value.type === "STRING_FUNC") return evalStringFunc(value, row, void 0, void 0, evaluationContext);
10569
+ if (value.type === "CASE_VALUE") return evalCaseWhenValue(value.expr, row, fieldType, evaluationContext);
10570
10570
  if (value.type === "SOURCE_FIELD") {
10571
10571
  throw new DmlConvertError("SOURCE_FIELD \u306F UPDATE ... FROM \u5C02\u7528\u3067\u3059");
10572
10572
  }
10573
10573
  return toKintoneValue(value, fieldType);
10574
10574
  }
10575
- function evaluateSubtableAssignmentValue(value, row, resolveFieldType) {
10575
+ function evaluateSubtableAssignmentValue(value, row, resolveFieldType, evaluationContext = {}) {
10576
10576
  if (value.type === "STRING") return value.value;
10577
10577
  if (value.type === "NUMBER") return numberLiteralText(value);
10578
- if (value.type === "ARITH") return String(evalArithExpr(value, row));
10579
- if (value.type === "CASE_VALUE") return evalCaseWhen(value.expr, row, resolveFieldType);
10578
+ if (value.type === "ARITH") return String(evalArithExpr(value, row, evaluationContext));
10579
+ if (value.type === "CASE_VALUE") return evalCaseWhen(
10580
+ value.expr,
10581
+ row,
10582
+ resolveFieldType,
10583
+ void 0,
10584
+ evaluationContext
10585
+ );
10580
10586
  throw new Error(`${value.type} \u306F\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB UPDATE \u306E\u5024\u3068\u3057\u3066\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093`);
10581
10587
  }
10582
10588
  var UPDATE_FROM_UNSUPPORTED_TYPES = /* @__PURE__ */ new Set([
@@ -10587,7 +10593,7 @@ var UPDATE_FROM_UNSUPPORTED_TYPES = /* @__PURE__ */ new Set([
10587
10593
  "GROUP_SELECT",
10588
10594
  "FILE"
10589
10595
  ]);
10590
- function updateFromToPutBatches(stmt, matched, fieldTypes = /* @__PURE__ */ new Map()) {
10596
+ function updateFromToPutBatches(stmt, matched, fieldTypes = /* @__PURE__ */ new Map(), evaluationContext = {}) {
10591
10597
  const updateRecords = matched.map(({ target, source }) => {
10592
10598
  const id = Number(target["$id"]?.value);
10593
10599
  if (!Number.isSafeInteger(id) || id <= 0) {
@@ -10617,9 +10623,20 @@ function updateFromToPutBatches(stmt, matched, fieldTypes = /* @__PURE__ */ new
10617
10623
  } else if (value.type === "ARITH") {
10618
10624
  record[field] = { value: String(evalArith(value, target)) };
10619
10625
  } else if (value.type === "SCALAR_ARITH" || value.type === "CONCAT_OP") {
10620
- record[field] = { value: String(evalScalarValueExpr(value, targetRow)) };
10626
+ record[field] = { value: String(evalScalarValueExpr(
10627
+ value,
10628
+ targetRow,
10629
+ void 0,
10630
+ void 0,
10631
+ evaluationContext
10632
+ )) };
10621
10633
  } else if (value.type === "CASE_VALUE") {
10622
- record[field] = { value: evalCaseWhenValue(value.expr, targetRow, fieldType) };
10634
+ record[field] = { value: evalCaseWhenValue(
10635
+ value.expr,
10636
+ targetRow,
10637
+ fieldType,
10638
+ evaluationContext
10639
+ ) };
10623
10640
  } else {
10624
10641
  record[field] = { value: toKintoneValue(value, fieldType) };
10625
10642
  }
@@ -10721,7 +10738,7 @@ function convertArray(elements, fieldType) {
10721
10738
  if (isUserType(fieldType)) return elements.map((c) => ({ code: c }));
10722
10739
  return elements;
10723
10740
  }
10724
- function evalCaseResultValue(result, row, fieldType) {
10741
+ function evalCaseResultValue(result, row, fieldType, evaluationContext) {
10725
10742
  if (result.type === "ARRAY") {
10726
10743
  return convertArray(result.elements.map((e) => e.value), fieldType);
10727
10744
  }
@@ -10732,26 +10749,26 @@ function evalCaseResultValue(result, row, fieldType) {
10732
10749
  return convertString2(result.value, fieldType);
10733
10750
  }
10734
10751
  if (result.type === "STRING_FUNC") {
10735
- return evalStringFunc(result, row);
10752
+ return evalStringFunc(result, row, void 0, void 0, evaluationContext);
10736
10753
  }
10737
10754
  if (result.type === "FIELD_REF" || result.type === "ARITH") {
10738
- return String(evalArithExpr(result, row));
10755
+ return String(evalArithExpr(result, row, evaluationContext));
10739
10756
  }
10740
- return String(evalScalarValueExpr(result, row));
10757
+ return String(evalScalarValueExpr(result, row, void 0, void 0, evaluationContext));
10741
10758
  }
10742
10759
  function collectUpdateCheckTargetFields(stmt) {
10743
10760
  if (!stmt.checkGroups) return [];
10744
10761
  const targetAlias = `app${stmt.appId}`.toLowerCase();
10745
10762
  return [...new Set(collectCheckFieldRefs(stmt.checkGroups).filter((ref) => ref.tableAlias === null || ref.tableAlias.toLowerCase() === targetAlias).map((ref) => ref.field).filter((field) => field !== "$id"))];
10746
10763
  }
10747
- function evalCaseWhenValue(expr, row, fieldType) {
10764
+ function evalCaseWhenValue(expr, row, fieldType, evaluationContext = {}) {
10748
10765
  for (const branch of expr.branches) {
10749
- if (evalWhere(branch.condition, row)) {
10750
- return evalCaseResultValue(branch.result, row, fieldType);
10766
+ if (evalWhere(branch.condition, row, void 0, void 0, void 0, evaluationContext)) {
10767
+ return evalCaseResultValue(branch.result, row, fieldType, evaluationContext);
10751
10768
  }
10752
10769
  }
10753
10770
  if (expr.elseResult !== null) {
10754
- return evalCaseResultValue(expr.elseResult, row, fieldType);
10771
+ return evalCaseResultValue(expr.elseResult, row, fieldType, evaluationContext);
10755
10772
  }
10756
10773
  return "";
10757
10774
  }
@@ -11029,18 +11046,30 @@ function buildApplyPatchPlan(input) {
11029
11046
  const parentId = requirePositiveInteger(snapshot["$id"]?.value, "APPLY snapshot $id");
11030
11047
  const expectedParentId = getApplyParentId(statement);
11031
11048
  if (parentId !== expectedParentId) argument2(`APPLY snapshot $id ${parentId} does not match requested $id ${expectedParentId}.`);
11032
- return buildApplyPatchPlanForSnapshot(statement, snapshot, metadata, parentId);
11049
+ return buildApplyPatchPlanForSnapshot(
11050
+ statement,
11051
+ snapshot,
11052
+ metadata,
11053
+ parentId,
11054
+ input.evaluationContext
11055
+ );
11033
11056
  }
11034
- function buildApplyPatchPlans(statement, snapshots, fieldInfos, metadata = resolveApplyPatchMetadata(statement, fieldInfos)) {
11057
+ function buildApplyPatchPlans(statement, snapshots, fieldInfos, metadata = resolveApplyPatchMetadata(statement, fieldInfos), evaluationContext = {}) {
11035
11058
  const parentIds = /* @__PURE__ */ new Set();
11036
11059
  return snapshots.map((snapshot) => {
11037
11060
  const parentId = requirePositiveInteger(snapshot["$id"]?.value, "APPLY snapshot $id");
11038
11061
  if (parentIds.has(parentId)) argument2(`APPLY snapshots contain duplicate parentId ${parentId}.`);
11039
11062
  parentIds.add(parentId);
11040
- return buildApplyPatchPlanForSnapshot(statement, snapshot, metadata, parentId);
11063
+ return buildApplyPatchPlanForSnapshot(
11064
+ statement,
11065
+ snapshot,
11066
+ metadata,
11067
+ parentId,
11068
+ evaluationContext
11069
+ );
11041
11070
  });
11042
11071
  }
11043
- function buildApplyPatchPlanForSnapshot(statement, snapshot, metadata, parentId) {
11072
+ function buildApplyPatchPlanForSnapshot(statement, snapshot, metadata, parentId, evaluationContext = {}) {
11044
11073
  const revision = requirePositiveInteger(snapshot["$revision"]?.value, "APPLY snapshot $revision");
11045
11074
  const tablePlans = [];
11046
11075
  const multiValuePlans = [];
@@ -11069,13 +11098,24 @@ function buildApplyPatchPlanForSnapshot(statement, snapshot, metadata, parentId)
11069
11098
  const hasRemove = block.operations.some((operation) => operation.kind === "REMOVE");
11070
11099
  for (const [operationIndex, operation] of block.operations.entries()) {
11071
11100
  if (operation.kind === "APPEND") {
11072
- const rows = buildApplyAppendRows(operation, targetChildren, block.field);
11101
+ const rows = buildApplyAppendRows(
11102
+ operation,
11103
+ targetChildren,
11104
+ block.field,
11105
+ evaluationContext
11106
+ );
11073
11107
  operationPlans.push({ kind: "APPEND", addedRows: rows.length });
11074
11108
  appended.push(...rows);
11075
11109
  continue;
11076
11110
  }
11077
11111
  if (operation.kind === "REMOVE") {
11078
- const indices2 = resolveRemoveTargets(operation, snapshotRows, childTypeResolver, block.field);
11112
+ const indices2 = resolveRemoveTargets(
11113
+ operation,
11114
+ snapshotRows,
11115
+ childTypeResolver,
11116
+ block.field,
11117
+ evaluationContext
11118
+ );
11079
11119
  if (operation.expectRows) {
11080
11120
  assertExpectRows(operation.expectRows, indices2.length, parentId, block.field, operationIndex, operation.kind);
11081
11121
  }
@@ -11093,7 +11133,13 @@ function buildApplyPatchPlanForSnapshot(statement, snapshot, metadata, parentId)
11093
11133
  continue;
11094
11134
  }
11095
11135
  if (operation.kind !== "PATCH") continue;
11096
- const indices = resolvePatchTargets(operation, snapshotRows, childTypeResolver, block.field);
11136
+ const indices = resolvePatchTargets(
11137
+ operation,
11138
+ snapshotRows,
11139
+ childTypeResolver,
11140
+ block.field,
11141
+ evaluationContext
11142
+ );
11097
11143
  if (operation.expectRows) {
11098
11144
  assertExpectRows(operation.expectRows, indices.length, parentId, block.field, operationIndex, operation.kind);
11099
11145
  }
@@ -11112,7 +11158,12 @@ function buildApplyPatchPlanForSnapshot(statement, snapshot, metadata, parentId)
11112
11158
  resolved.push({
11113
11159
  rowIndex,
11114
11160
  field: assignment.field,
11115
- value: evaluateSubtableAssignmentValue(assignment.value, flat, childTypeResolver)
11161
+ value: evaluateSubtableAssignmentValue(
11162
+ assignment.value,
11163
+ flat,
11164
+ childTypeResolver,
11165
+ evaluationContext
11166
+ )
11116
11167
  });
11117
11168
  }
11118
11169
  }
@@ -11164,7 +11215,13 @@ function buildApplyPatchPlanForSnapshot(statement, snapshot, metadata, parentId)
11164
11215
  for (const assignment of statement.assignments) {
11165
11216
  const fieldType = metadata.fieldsByCode.get(assignment.field)?.fieldType;
11166
11217
  parentValues[assignment.field] = {
11167
- value: evaluateUpdateAssignmentValue(assignment.value, parentRow, fieldType, snapshot)
11218
+ value: evaluateUpdateAssignmentValue(
11219
+ assignment.value,
11220
+ parentRow,
11221
+ fieldType,
11222
+ snapshot,
11223
+ evaluationContext
11224
+ )
11168
11225
  };
11169
11226
  }
11170
11227
  const postImage = { ...snapshot };
@@ -11234,12 +11291,12 @@ function normalizeApplyPatchPlan(plan, normalizedRecord) {
11234
11291
  postImage: normalizedRecord
11235
11292
  };
11236
11293
  }
11237
- function buildApplyAppendRows(operation, children, table) {
11294
+ function buildApplyAppendRows(operation, children, table, evaluationContext = {}) {
11238
11295
  return operation.values.map((row) => ({
11239
- value: buildAppendValue(operation, row, children, table)
11296
+ value: buildAppendValue(operation, row, children, table, evaluationContext)
11240
11297
  }));
11241
11298
  }
11242
- function buildAppendValue(operation, row, children, table) {
11299
+ function buildAppendValue(operation, row, children, table, evaluationContext) {
11243
11300
  if (row.length !== operation.fields.length) {
11244
11301
  return argument2(`APPLY APPEND for ${table} has ${row.length} values for ${operation.fields.length} fields.`);
11245
11302
  }
@@ -11248,7 +11305,7 @@ function buildAppendValue(operation, row, children, table) {
11248
11305
  for (const field of children.values()) {
11249
11306
  if (field.fieldType === "FILE" || field.writable === false) continue;
11250
11307
  const sqlValue = specified.get(field.code);
11251
- value[field.code] = { value: sqlValue === void 0 ? appendDefaultValue(field) : sqlValue.type === "CASE_VALUE" ? evalCaseWhenValue(sqlValue.expr, {}, field.fieldType) : toKintoneValue(sqlValue, field.fieldType) };
11308
+ value[field.code] = { value: sqlValue === void 0 ? appendDefaultValue(field) : sqlValue.type === "CASE_VALUE" ? evalCaseWhenValue(sqlValue.expr, {}, field.fieldType, evaluationContext) : toKintoneValue(sqlValue, field.fieldType) };
11252
11309
  }
11253
11310
  return value;
11254
11311
  }
@@ -11256,17 +11313,36 @@ function appendDefaultValue(field) {
11256
11313
  if (field.defaultValue !== void 0 && field.defaultValue !== null) return field.defaultValue;
11257
11314
  return ["CHECK_BOX", "MULTI_SELECT", "USER_SELECT", "ORGANIZATION_SELECT", "GROUP_SELECT"].includes(field.fieldType) ? [] : "";
11258
11315
  }
11259
- function resolvePatchTargets(operation, rows, resolveFieldType, table) {
11260
- return resolveSelectorTargets(operation.selector, rows, resolveFieldType, table);
11316
+ function resolvePatchTargets(operation, rows, resolveFieldType, table, evaluationContext = {}) {
11317
+ return resolveSelectorTargets(
11318
+ operation.selector,
11319
+ rows,
11320
+ resolveFieldType,
11321
+ table,
11322
+ evaluationContext
11323
+ );
11261
11324
  }
11262
- function resolveRemoveTargets(operation, rows, resolveFieldType, table) {
11263
- return resolveSelectorTargets(operation.selector, rows, resolveFieldType, table);
11325
+ function resolveRemoveTargets(operation, rows, resolveFieldType, table, evaluationContext = {}) {
11326
+ return resolveSelectorTargets(
11327
+ operation.selector,
11328
+ rows,
11329
+ resolveFieldType,
11330
+ table,
11331
+ evaluationContext
11332
+ );
11264
11333
  }
11265
- function resolveSelectorTargets(selector, rows, resolveFieldType, table) {
11334
+ function resolveSelectorTargets(selector, rows, resolveFieldType, table, evaluationContext = {}) {
11266
11335
  if (selector.kind === "ALL_ROWS") return rows.map((_, index) => index);
11267
11336
  const where = selector.where;
11268
11337
  const indices = rows.flatMap(
11269
- (row, index) => evalWhere(where, flattenSubtableSnapshotRow(row, index), resolveFieldType) ? [index] : []
11338
+ (row, index) => evalWhere(
11339
+ where,
11340
+ flattenSubtableSnapshotRow(row, index),
11341
+ resolveFieldType,
11342
+ void 0,
11343
+ void 0,
11344
+ evaluationContext
11345
+ ) ? [index] : []
11270
11346
  );
11271
11347
  const requestedRid = exactRidSelectorValue(where);
11272
11348
  if (requestedRid !== null && indices.length === 0) {
@@ -14557,9 +14633,16 @@ function assertJoinKeyAvailable(rows, key, savedColumns) {
14557
14633
  throw new Error(`ArgumentError: JOIN key ${key} is not available in the materialized table.`);
14558
14634
  }
14559
14635
  }
14560
- function applyFilter(rows, where, resolveFieldType, appliedKlikes, resolveFieldSemantics2) {
14636
+ function applyFilter(rows, where, resolveFieldType, appliedKlikes, resolveFieldSemantics2, evaluationContext = {}) {
14561
14637
  if (where === null) return rows;
14562
- return rows.filter((row) => evalWhere(where, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2));
14638
+ return rows.filter((row) => evalWhere(
14639
+ where,
14640
+ row,
14641
+ resolveFieldType,
14642
+ appliedKlikes,
14643
+ resolveFieldSemantics2,
14644
+ evaluationContext
14645
+ ));
14563
14646
  }
14564
14647
  function hasAggregateColumns(columns) {
14565
14648
  return columns.some(
@@ -14593,12 +14676,28 @@ function applyGroupBy(rows, groupByKeys, columns, resolveAggSortKind, resolution
14593
14676
  const outRow = asProcessingRow({ ...groupRows[0] });
14594
14677
  for (const k of groupByKeys) {
14595
14678
  if (k.type === "ARITH_KEY") {
14596
- outRow[arithColDefaultKey(k.expr)] = String(evalArithExpr(k.expr, groupRows[0]));
14679
+ outRow[arithColDefaultKey(k.expr)] = String(evalArithExpr(
14680
+ k.expr,
14681
+ groupRows[0],
14682
+ aliasEvaluationContext.evaluationContext
14683
+ ));
14597
14684
  } else if (k.type === "FUNC_KEY") {
14598
- outRow[stringFuncDefaultKey(k.expr)] = evalStringFunc(k.expr, groupRows[0]);
14685
+ outRow[stringFuncDefaultKey(k.expr)] = evalStringFunc(
14686
+ k.expr,
14687
+ groupRows[0],
14688
+ void 0,
14689
+ void 0,
14690
+ aliasEvaluationContext.evaluationContext
14691
+ );
14599
14692
  }
14600
14693
  }
14601
- materializeAggregateColumns(outRow, groupRows, columns, resolveAggSortKind);
14694
+ materializeAggregateColumns(
14695
+ outRow,
14696
+ groupRows,
14697
+ columns,
14698
+ resolveAggSortKind,
14699
+ aliasEvaluationContext.evaluationContext
14700
+ );
14602
14701
  result.push(outRow);
14603
14702
  }
14604
14703
  return result;
@@ -14656,7 +14755,13 @@ function applyGroupingSets(rows, spec, columns, resolveAggSortKind, limits = {})
14656
14755
  outRow[item.unqualifiedBridgeKey] = value;
14657
14756
  }
14658
14757
  }
14659
- materializeAggregateColumns(outRow, groupRows, columns, resolveAggSortKind);
14758
+ materializeAggregateColumns(
14759
+ outRow,
14760
+ groupRows,
14761
+ columns,
14762
+ resolveAggSortKind,
14763
+ limits.evaluationContext
14764
+ );
14660
14765
  attachGroupingRowMeta(outRow, includedCanonicalIds);
14661
14766
  result.push(outRow);
14662
14767
  }
@@ -14667,11 +14772,19 @@ function groupingItemValue(item, row) {
14667
14772
  if (!row) return "";
14668
14773
  return row[item.directKey] ?? (item.unqualifiedBridgeKey === null ? void 0 : row[item.unqualifiedBridgeKey]) ?? "";
14669
14774
  }
14670
- function materializeAggregateColumns(outRow, groupRows, columns, resolveAggSortKind) {
14775
+ function materializeAggregateColumns(outRow, groupRows, columns, resolveAggSortKind, evaluationContext = {}) {
14671
14776
  for (const [columnIndex, col] of columns.entries()) {
14672
14777
  if (col.type === "AGGREGATE") {
14673
14778
  const syntheticKey = aggregateSyntheticName(col.func, col.distinct, col.arg);
14674
- const value = String(evalAggregate(col.func, col.distinct, col.arg, col.separator, groupRows, resolveAggSortKind));
14779
+ const value = String(evalAggregate(
14780
+ col.func,
14781
+ col.distinct,
14782
+ col.arg,
14783
+ col.separator,
14784
+ groupRows,
14785
+ resolveAggSortKind,
14786
+ evaluationContext
14787
+ ));
14675
14788
  setMaterializedSelectValue(
14676
14789
  outRow,
14677
14790
  columnIndex,
@@ -14679,38 +14792,44 @@ function materializeAggregateColumns(outRow, groupRows, columns, resolveAggSortK
14679
14792
  col.alias ? [col.alias, syntheticKey] : [syntheticKey]
14680
14793
  );
14681
14794
  } else if (col.type === "ARITH_AGG_COL") {
14682
- materializeAggregateDependencies(outRow, groupRows, col.expr, resolveAggSortKind);
14795
+ materializeAggregateDependencies(outRow, groupRows, col.expr, resolveAggSortKind, evaluationContext);
14683
14796
  const outputKey = col.alias ?? aggArithDefaultKey(col.expr);
14684
14797
  setMaterializedSelectValue(
14685
14798
  outRow,
14686
14799
  columnIndex,
14687
- String(evalAggArithExpr(col.expr, groupRows, resolveAggSortKind)),
14800
+ String(evalAggArithExpr(col.expr, groupRows, resolveAggSortKind, evaluationContext)),
14688
14801
  [outputKey]
14689
14802
  );
14690
14803
  } else if (col.type === "STRFUNC_COL" && hasAggregateInStringFuncExpr2(col.expr)) {
14691
- materializeAggregateDependencies(outRow, groupRows, col.expr, resolveAggSortKind);
14804
+ materializeAggregateDependencies(outRow, groupRows, col.expr, resolveAggSortKind, evaluationContext);
14692
14805
  const outputKey = col.alias ?? stringFuncDefaultKey(col.expr);
14693
14806
  const resolvedExpr = resolveAggInStringFuncExpr(col.expr, groupRows, resolveAggSortKind);
14694
- setMaterializedSelectValue(outRow, columnIndex, evalStringFunc(resolvedExpr, outRow), [outputKey]);
14807
+ setMaterializedSelectValue(
14808
+ outRow,
14809
+ columnIndex,
14810
+ evalStringFunc(resolvedExpr, outRow, void 0, void 0, evaluationContext),
14811
+ [outputKey]
14812
+ );
14695
14813
  } else if (col.type === "SCALAR_VALUE_COL" && scalarValueHasAggregate2(col.expr)) {
14696
- materializeAggregateDependencies(outRow, groupRows, col.expr, resolveAggSortKind);
14814
+ materializeAggregateDependencies(outRow, groupRows, col.expr, resolveAggSortKind, evaluationContext);
14697
14815
  const outputKey = col.alias ?? scalarValueDefaultKey(col.expr);
14698
14816
  const resolvedExpr = resolveAggInScalarValue(col.expr, groupRows, resolveAggSortKind);
14699
14817
  setMaterializedSelectValue(
14700
14818
  outRow,
14701
14819
  columnIndex,
14702
- String(evalScalarValueExpr(resolvedExpr, outRow)),
14820
+ String(evalScalarValueExpr(resolvedExpr, outRow, void 0, void 0, evaluationContext)),
14703
14821
  [outputKey]
14704
14822
  );
14705
14823
  } else if (col.type === "CASE_COL" && containsAggregate2(col.expr)) {
14706
- materializeAggregateDependencies(outRow, groupRows, col.expr, resolveAggSortKind);
14824
+ materializeAggregateDependencies(outRow, groupRows, col.expr, resolveAggSortKind, evaluationContext);
14707
14825
  const resolvedExpr = resolveAggInCaseExpr(col.expr, groupRows, resolveAggSortKind);
14708
14826
  const resolveAggregateSemantics = (field) => field.aggregateRef ? aggregateResultSemantics(field.aggregateRef, resolveAggSortKind) : void 0;
14709
14827
  const value = evalCaseWhen(
14710
14828
  resolvedExpr,
14711
14829
  outRow,
14712
14830
  void 0,
14713
- resolveAggregateSemantics
14831
+ resolveAggregateSemantics,
14832
+ evaluationContext
14714
14833
  );
14715
14834
  setMaterializedSelectValue(
14716
14835
  outRow,
@@ -14738,7 +14857,7 @@ function collectAggregateRefs(node, out) {
14738
14857
  if (value["type"] === "SELECT" || value["type"] === "SCALAR_SUBQUERY") return;
14739
14858
  Object.values(value).forEach((child) => collectAggregateRefs(child, out));
14740
14859
  }
14741
- function materializeAggregateDependencies(outRow, rows, node, resolveAggSortKind) {
14860
+ function materializeAggregateDependencies(outRow, rows, node, resolveAggSortKind, evaluationContext = {}) {
14742
14861
  const refs = [];
14743
14862
  collectAggregateRefs(node, refs);
14744
14863
  for (const ref of refs) {
@@ -14750,7 +14869,8 @@ function materializeAggregateDependencies(outRow, rows, node, resolveAggSortKind
14750
14869
  ref.arg,
14751
14870
  ref.separator,
14752
14871
  rows,
14753
- resolveAggSortKind
14872
+ resolveAggSortKind,
14873
+ evaluationContext
14754
14874
  ));
14755
14875
  materializedValuesFor(outRow).byLookupKey.set(key, value);
14756
14876
  }
@@ -14781,14 +14901,20 @@ function evalGroupByKey(key, row, resolution, columns, aliasEvaluationContext) {
14781
14901
  `InternalError: unresolved plain GROUP BY item ${resolution.kind} reached evaluation.`
14782
14902
  );
14783
14903
  }
14784
- if (key.type === "FUNC_KEY") return evalStringFunc(key.expr, row);
14785
- return String(evalArithExpr(key.expr, row));
14904
+ if (key.type === "FUNC_KEY") return evalStringFunc(
14905
+ key.expr,
14906
+ row,
14907
+ void 0,
14908
+ void 0,
14909
+ aliasEvaluationContext.evaluationContext
14910
+ );
14911
+ return String(evalArithExpr(key.expr, row, aliasEvaluationContext.evaluationContext));
14786
14912
  }
14787
- function evalAggregate(func, distinct, arg, separator, rows, resolveAggSortKind) {
14913
+ function evalAggregate(func, distinct, arg, separator, rows, resolveAggSortKind, evaluationContext = {}) {
14788
14914
  if (arg.type === "WILDCARD") {
14789
14915
  return func === "COUNT" ? rows.length : 0;
14790
14916
  }
14791
- const strValues = aggregateRowValues(func, arg, rows).filter((value) => value !== null);
14917
+ const strValues = aggregateRowValues(func, arg, rows, evaluationContext).filter((value) => value !== null);
14792
14918
  const statistical = func === "STDDEV_POP" || func === "STDDEV_SAMP" || func === "VAR_POP" || func === "VAR_SAMP" || func === "MEDIAN";
14793
14919
  const numericValues = statistical ? strValues.map((value) => {
14794
14920
  const numeric = Number(value);
@@ -14866,7 +14992,7 @@ function evalAggregate(func, distinct, arg, separator, rows, resolveAggSortKind)
14866
14992
  }
14867
14993
  }
14868
14994
  }
14869
- function aggregateRowValues(func, arg, rows) {
14995
+ function aggregateRowValues(func, arg, rows, evaluationContext = {}) {
14870
14996
  return rows.map((processingRow) => {
14871
14997
  const row = sourceRowForEvaluation(processingRow);
14872
14998
  let strVal;
@@ -14875,11 +15001,11 @@ function aggregateRowValues(func, arg, rows) {
14875
15001
  if (raw === void 0 || raw === "" && func !== "MIN" && func !== "MAX") return null;
14876
15002
  strVal = raw;
14877
15003
  } else if (arg.type === "ARITH" || arg.type === "NUMBER") {
14878
- const n = evalArithExpr(arg, row);
15004
+ const n = evalArithExpr(arg, row, evaluationContext);
14879
15005
  if (isNaN(n)) return null;
14880
15006
  strVal = String(n);
14881
15007
  } else {
14882
- const value = evalScalarValueExprNullable(arg, row);
15008
+ const value = evalScalarValueExprNullable(arg, row, void 0, void 0, evaluationContext);
14883
15009
  if (value === null) return null;
14884
15010
  if (value === "" && func !== "MIN" && func !== "MAX") return null;
14885
15011
  if (typeof value === "number" && Number.isNaN(value)) return null;
@@ -14892,9 +15018,17 @@ function toAggregateFieldRef(field) {
14892
15018
  const dot = field.indexOf(".");
14893
15019
  return dot > 0 ? { type: "FIELD", tableAlias: field.slice(0, dot), field: field.slice(dot + 1) } : { type: "FIELD", tableAlias: null, field };
14894
15020
  }
14895
- function evalAggArithExpr(node, rows, resolveAggSortKind) {
15021
+ function evalAggArithExpr(node, rows, resolveAggSortKind, evaluationContext = {}) {
14896
15022
  if (node.type === "NUMBER") return node.value;
14897
- if (node.type === "AGG_REF") return Number(evalAggregate(node.func, node.distinct, node.arg, node.separator, rows, resolveAggSortKind));
15023
+ if (node.type === "AGG_REF") return Number(evalAggregate(
15024
+ node.func,
15025
+ node.distinct,
15026
+ node.arg,
15027
+ node.separator,
15028
+ rows,
15029
+ resolveAggSortKind,
15030
+ evaluationContext
15031
+ ));
14898
15032
  if (node.type === "AGG_GROUP_KEY") {
14899
15033
  const field = node.tableAlias ? `${node.tableAlias}.${node.field}` : node.field;
14900
15034
  return Number(resolveFieldRef(rows[0] ?? {}, field));
@@ -14902,8 +15036,8 @@ function evalAggArithExpr(node, rows, resolveAggSortKind) {
14902
15036
  if (node.type === "VARIABLE") {
14903
15037
  throw new Error(`InternalError: unresolved aggregate arithmetic variable @${node.name}.`);
14904
15038
  }
14905
- const l = evalAggArithExpr(node.left, rows, resolveAggSortKind);
14906
- const r = evalAggArithExpr(node.right, rows, resolveAggSortKind);
15039
+ const l = evalAggArithExpr(node.left, rows, resolveAggSortKind, evaluationContext);
15040
+ const r = evalAggArithExpr(node.right, rows, resolveAggSortKind, evaluationContext);
14907
15041
  switch (node.op) {
14908
15042
  case "+":
14909
15043
  return l + r;
@@ -14947,22 +15081,24 @@ function aggregateResultSemantics(ref, resolver) {
14947
15081
  const semantics = ref.arg.type === "WILDCARD" ? "string" : resolveAggregateArgSemantics(ref.arg, resolver) ?? "string";
14948
15082
  return typeof semantics === "string" ? syntheticSemantics(semantics) : semantics;
14949
15083
  }
14950
- function applyHaving(rows, having, resolveFieldType, resolveFieldSemantics2) {
15084
+ function applyHaving(rows, having, resolveFieldType, resolveFieldSemantics2, evaluationContext = {}) {
14951
15085
  if (having === null) return rows;
14952
15086
  return rows.filter((row) => evalWhere(
14953
15087
  having,
14954
15088
  havingEvaluationRow(row),
14955
15089
  resolveFieldType,
14956
15090
  void 0,
14957
- resolveFieldSemantics2
15091
+ resolveFieldSemantics2,
15092
+ evaluationContext
14958
15093
  ));
14959
15094
  }
14960
- function applyDistinct(rows, columns, scalarCache, resolveFieldType, resolveFieldSemantics2) {
15095
+ function applyDistinct(rows, columns, scalarCache, resolveFieldType, resolveFieldSemantics2, evaluationContext = {}) {
14961
15096
  if (rows.length === 0) return rows;
14962
15097
  const keyFor = buildDistinctKeyBuilder(rows, columns, {
14963
15098
  scalarCache,
14964
15099
  resolveFieldType,
14965
- resolveFieldSemantics: resolveFieldSemantics2
15100
+ resolveFieldSemantics: resolveFieldSemantics2,
15101
+ evaluationContext
14966
15102
  });
14967
15103
  const seen = /* @__PURE__ */ new Set();
14968
15104
  return rows.filter((row) => {
@@ -14998,11 +15134,19 @@ function buildDistinctKeyBuilder(rows, columns, context) {
14998
15134
  };
14999
15135
  return (row) => JSON.stringify(buildDistinctTuple(columns, row, distinctContext));
15000
15136
  }
15001
- function applyOrderBy(rows, orderBy, optionOrders, sortKinds, fieldSemantics2, aliasEvaluator) {
15137
+ function applyOrderBy(rows, orderBy, optionOrders, sortKinds, fieldSemantics2, aliasEvaluator, evaluationContext = {}) {
15002
15138
  if (orderBy.length === 0) return rows;
15003
- return sortDecoratedRows(rows, orderBy, optionOrders, sortKinds, fieldSemantics2, aliasEvaluator).rows.map((item) => item.row);
15139
+ return sortDecoratedRows(
15140
+ rows,
15141
+ orderBy,
15142
+ optionOrders,
15143
+ sortKinds,
15144
+ fieldSemantics2,
15145
+ aliasEvaluator,
15146
+ evaluationContext
15147
+ ).rows.map((item) => item.row);
15004
15148
  }
15005
- function sortDecoratedRows(rows, orderBy, optionOrders, sortKinds, fieldSemantics2, aliasEvaluator) {
15149
+ function sortDecoratedRows(rows, orderBy, optionOrders, sortKinds, fieldSemantics2, aliasEvaluator, evaluationContext = {}) {
15006
15150
  const keyMeta = orderBy.map(({ key }) => {
15007
15151
  if (key.type === "ARITH_KEY") return { semantics: syntheticSemantics("number") };
15008
15152
  if (key.type === "FUNC_KEY") {
@@ -15028,7 +15172,7 @@ function sortDecoratedRows(rows, orderBy, optionOrders, sortKinds, fieldSemantic
15028
15172
  const decorated = rows.map((row) => ({
15029
15173
  row,
15030
15174
  keys: orderBy.map(({ key }, i) => {
15031
- const s = evalOrderKey(key, row, aliasEvaluator);
15175
+ const s = evalOrderKey(key, row, aliasEvaluator, evaluationContext);
15032
15176
  return { s };
15033
15177
  })
15034
15178
  }));
@@ -15066,20 +15210,20 @@ var NUMERIC_ORDER_FUNCTIONS = /* @__PURE__ */ new Set([
15066
15210
  "QUARTER",
15067
15211
  "WEEK"
15068
15212
  ]);
15069
- function evalOrderKey(key, row, aliasEvaluator) {
15213
+ function evalOrderKey(key, row, aliasEvaluator, evaluationContext = {}) {
15070
15214
  const sourceRow = sourceRowForEvaluation(row);
15071
15215
  switch (key.type) {
15072
15216
  case "FIELD_NAME":
15073
15217
  return aliasEvaluator?.(key.name, row) ?? getMaterializedLookupValue(row, key.name) ?? sourceRow[key.name] ?? "";
15074
15218
  case "ARITH_KEY":
15075
- return String(evalArithExpr(key.expr, sourceRow));
15219
+ return String(evalArithExpr(key.expr, sourceRow, evaluationContext));
15076
15220
  case "FUNC_KEY":
15077
- return evalStringFunc(key.expr, sourceRow);
15221
+ return evalStringFunc(key.expr, sourceRow, void 0, void 0, evaluationContext);
15078
15222
  case "GROUPING_KEY":
15079
15223
  return evalGroupingRef(key.ref, row);
15080
15224
  }
15081
15225
  }
15082
- function buildOrderByAliasEvaluator(columns, scalarCache, resolveFieldType, resolveFieldSemantics2) {
15226
+ function buildOrderByAliasEvaluator(columns, scalarCache, resolveFieldType, resolveFieldSemantics2, evaluationContext = {}) {
15083
15227
  const evaluators = /* @__PURE__ */ new Map();
15084
15228
  for (const [columnIndex, column] of columns.entries()) {
15085
15229
  if (!("alias" in column) || column.alias === null) continue;
@@ -15103,15 +15247,37 @@ function buildOrderByAliasEvaluator(columns, scalarCache, resolveFieldType, reso
15103
15247
  evaluators.set(alias, (row) => getMaterializedSelectValue(row, columnIndex) ?? "");
15104
15248
  break;
15105
15249
  case "ARITH_COL":
15106
- evaluators.set(alias, (row) => String(evalArithExpr(column.expr, sourceRowForEvaluation(row))));
15250
+ evaluators.set(alias, (row) => String(evalArithExpr(
15251
+ column.expr,
15252
+ sourceRowForEvaluation(row),
15253
+ evaluationContext
15254
+ )));
15107
15255
  break;
15108
15256
  case "STRFUNC_COL": {
15109
15257
  const source = stringFuncDefaultKey(column.expr);
15110
- evaluators.set(alias, (row) => hasAggregateInStringFuncExpr2(column.expr) ? getMaterializedSelectValue(row, columnIndex) ?? getMaterializedLookupValue(row, source) ?? evalStringFunc(column.expr, sourceRowForEvaluation(row), resolveFieldType, resolveFieldSemantics2) : evalStringFunc(column.expr, sourceRowForEvaluation(row), resolveFieldType, resolveFieldSemantics2));
15258
+ evaluators.set(alias, (row) => hasAggregateInStringFuncExpr2(column.expr) ? getMaterializedSelectValue(row, columnIndex) ?? getMaterializedLookupValue(row, source) ?? evalStringFunc(
15259
+ column.expr,
15260
+ sourceRowForEvaluation(row),
15261
+ resolveFieldType,
15262
+ resolveFieldSemantics2,
15263
+ evaluationContext
15264
+ ) : evalStringFunc(
15265
+ column.expr,
15266
+ sourceRowForEvaluation(row),
15267
+ resolveFieldType,
15268
+ resolveFieldSemantics2,
15269
+ evaluationContext
15270
+ ));
15111
15271
  break;
15112
15272
  }
15113
15273
  case "CASE_COL":
15114
- evaluators.set(alias, (row) => containsAggregate2(column.expr) ? getMaterializedSelectValue(row, columnIndex) ?? "" : evalCaseWhen(column.expr, sourceRowForEvaluation(row), resolveFieldType, resolveFieldSemantics2));
15274
+ evaluators.set(alias, (row) => containsAggregate2(column.expr) ? getMaterializedSelectValue(row, columnIndex) ?? "" : evalCaseWhen(
15275
+ column.expr,
15276
+ sourceRowForEvaluation(row),
15277
+ resolveFieldType,
15278
+ resolveFieldSemantics2,
15279
+ evaluationContext
15280
+ ));
15115
15281
  break;
15116
15282
  case "SCALAR_VALUE_COL": {
15117
15283
  const source = scalarValueDefaultKey(column.expr);
@@ -15119,7 +15285,8 @@ function buildOrderByAliasEvaluator(columns, scalarCache, resolveFieldType, reso
15119
15285
  column.expr,
15120
15286
  sourceRowForEvaluation(row),
15121
15287
  resolveFieldType,
15122
- resolveFieldSemantics2
15288
+ resolveFieldSemantics2,
15289
+ evaluationContext
15123
15290
  )));
15124
15291
  break;
15125
15292
  }
@@ -15135,7 +15302,7 @@ function buildOrderByAliasEvaluator(columns, scalarCache, resolveFieldType, reso
15135
15302
  }
15136
15303
  return (name, row) => evaluators.get(name)?.(row);
15137
15304
  }
15138
- function applyWindow(rows, columns, optionOrders, sortKinds, fieldSemantics2, resolveAggSortKind) {
15305
+ function applyWindow(rows, columns, optionOrders, sortKinds, fieldSemantics2, resolveAggSortKind, evaluationContext = {}) {
15139
15306
  const windows = columns.map((column, columnIndex) => ({ column, columnIndex })).filter((item) => item.column.type === "WINDOW_COL");
15140
15307
  if (rows.length === 0 || windows.length === 0) return rows;
15141
15308
  for (let index = 0; index < rows.length; index++) rows[index] = asProcessingRow(rows[index]);
@@ -15148,14 +15315,28 @@ function applyWindow(rows, columns, optionOrders, sortKinds, fieldSemantics2, re
15148
15315
  else partitions.set(key, [row]);
15149
15316
  }
15150
15317
  for (const partition of partitions.values()) {
15151
- const sortedResult = sortDecoratedRows(partition, window.orderBy, optionOrders, sortKinds, fieldSemantics2);
15318
+ const sortedResult = sortDecoratedRows(
15319
+ partition,
15320
+ window.orderBy,
15321
+ optionOrders,
15322
+ sortKinds,
15323
+ fieldSemantics2,
15324
+ void 0,
15325
+ evaluationContext
15326
+ );
15152
15327
  const sorted = sortedResult.rows;
15153
15328
  if (isAggregateWindow(window)) {
15154
- applyAggregateWindow(window, columnIndex, sortedResult, resolveAggSortKind);
15329
+ applyAggregateWindow(
15330
+ window,
15331
+ columnIndex,
15332
+ sortedResult,
15333
+ resolveAggSortKind,
15334
+ evaluationContext
15335
+ );
15155
15336
  continue;
15156
15337
  }
15157
15338
  if (isValueWindow(window)) {
15158
- applyValueWindow(window, columnIndex, sorted);
15339
+ applyValueWindow(window, columnIndex, sorted, evaluationContext);
15159
15340
  continue;
15160
15341
  }
15161
15342
  if (!isRankingWindow(window)) {
@@ -15175,14 +15356,24 @@ function applyWindow(rows, columns, optionOrders, sortKinds, fieldSemantics2, re
15175
15356
  }
15176
15357
  return rows;
15177
15358
  }
15178
- function evaluateValueWindowArg(arg, row) {
15179
- const value = evalScalarValueExprNullable(arg, sourceRowForEvaluation(row));
15359
+ function evaluateValueWindowArg(arg, row, evaluationContext = {}) {
15360
+ const value = evalScalarValueExprNullable(
15361
+ arg,
15362
+ sourceRowForEvaluation(row),
15363
+ void 0,
15364
+ void 0,
15365
+ evaluationContext
15366
+ );
15180
15367
  if (value === null || value === void 0) return "";
15181
15368
  if (typeof value === "number" && !Number.isFinite(value)) return "";
15182
15369
  return String(value);
15183
15370
  }
15184
- function applyValueWindow(window, columnIndex, sorted) {
15185
- const values = sorted.map((item) => evaluateValueWindowArg(window.arg, item.row));
15371
+ function applyValueWindow(window, columnIndex, sorted, evaluationContext = {}) {
15372
+ const values = sorted.map((item) => evaluateValueWindowArg(
15373
+ window.arg,
15374
+ item.row,
15375
+ evaluationContext
15376
+ ));
15186
15377
  const direction = window.valueFunc === "LAG" ? -1 : 1;
15187
15378
  for (let index = 0; index < sorted.length; index++) {
15188
15379
  const target = index + direction * window.offset;
@@ -15194,9 +15385,14 @@ function applyValueWindow(window, columnIndex, sorted) {
15194
15385
  );
15195
15386
  }
15196
15387
  }
15197
- function applyAggregateWindow(window, columnIndex, sortedResult, resolveAggSortKind) {
15388
+ function applyAggregateWindow(window, columnIndex, sortedResult, resolveAggSortKind, evaluationContext = {}) {
15198
15389
  const sorted = sortedResult.rows;
15199
- const values = window.arg.type === "WILDCARD" ? null : aggregateRowValues(window.aggFunc, window.arg, sorted.map((item) => item.row));
15390
+ const values = window.arg.type === "WILDCARD" ? null : aggregateRowValues(
15391
+ window.aggFunc,
15392
+ window.arg,
15393
+ sorted.map((item) => item.row),
15394
+ evaluationContext
15395
+ );
15200
15396
  const comparison = window.arg.type === "WILDCARD" ? void 0 : resolveAggregateArgSemantics(window.arg, resolveAggSortKind);
15201
15397
  const semantics = typeof comparison === "string" ? syntheticSemantics(comparison) : comparison ?? syntheticSemantics("string");
15202
15398
  const output = [];
@@ -15288,13 +15484,14 @@ function evaluateSelectColumnValue(column, row, columnIndex, context = {}) {
15288
15484
  return getMaterializedSelectValue(row, columnIndex) ?? getMaterializedLookupValue(row, source) ?? getLegacyMaterializedValue(row, source) ?? "0";
15289
15485
  }
15290
15486
  case "ARITH_COL":
15291
- return String(evalArithExpr(column.expr, sourceRow));
15487
+ return String(evalArithExpr(column.expr, sourceRow, context.evaluationContext));
15292
15488
  case "CASE_COL":
15293
15489
  return containsAggregate2(column.expr) ? getMaterializedSelectValue(row, columnIndex) ?? getMaterializedLookupValue(row, caseMaterializedKey(column.alias, columnIndex)) ?? getLegacyMaterializedValue(row, caseMaterializedKey(column.alias, columnIndex)) ?? "" : evalCaseWhen(
15294
15490
  column.expr,
15295
15491
  sourceRow,
15296
15492
  context.resolveFieldType,
15297
- context.resolveFieldSemantics
15493
+ context.resolveFieldSemantics,
15494
+ context.evaluationContext
15298
15495
  );
15299
15496
  case "GROUPING_COL":
15300
15497
  return evalGroupingRef(column.ref, row);
@@ -15304,12 +15501,14 @@ function evaluateSelectColumnValue(column, row, columnIndex, context = {}) {
15304
15501
  column.expr,
15305
15502
  sourceRow,
15306
15503
  context.resolveFieldType,
15307
- context.resolveFieldSemantics
15504
+ context.resolveFieldSemantics,
15505
+ context.evaluationContext
15308
15506
  ) : evalStringFunc(
15309
15507
  column.expr,
15310
15508
  sourceRow,
15311
15509
  context.resolveFieldType,
15312
- context.resolveFieldSemantics
15510
+ context.resolveFieldSemantics,
15511
+ context.evaluationContext
15313
15512
  );
15314
15513
  }
15315
15514
  case "SCALAR_VALUE_COL": {
@@ -15318,7 +15517,8 @@ function evaluateSelectColumnValue(column, row, columnIndex, context = {}) {
15318
15517
  column.expr,
15319
15518
  sourceRow,
15320
15519
  context.resolveFieldType,
15321
- context.resolveFieldSemantics
15520
+ context.resolveFieldSemantics,
15521
+ context.evaluationContext
15322
15522
  ));
15323
15523
  }
15324
15524
  case "SCALAR_SUBQUERY_COL":
@@ -15333,7 +15533,7 @@ function buildDistinctTuple(columns, row, context = {}) {
15333
15533
  return typeof value === "string" ? value : value.entries.map(([, entryValue]) => entryValue);
15334
15534
  });
15335
15535
  }
15336
- function project(rows, columns, scalarCache, resolveFieldType, sourceColumns2, resolveFieldSemantics2, hiddenQualifiedAliases) {
15536
+ function project(rows, columns, scalarCache, resolveFieldType, sourceColumns2, resolveFieldSemantics2, hiddenQualifiedAliases, evaluationContext = {}) {
15337
15537
  if (columns.length === 1 && columns[0].type === "WILDCARD") {
15338
15538
  const projected2 = rows.map((row) => {
15339
15539
  const visible = stripHiddenQualifiedColumns(
@@ -15366,10 +15566,11 @@ function project(rows, columns, scalarCache, resolveFieldType, sourceColumns2, r
15366
15566
  }
15367
15567
  const projected = rows.map((row, rowIdx) => {
15368
15568
  const out = {};
15369
- const evaluationContext = {
15569
+ const columnEvaluationContext = {
15370
15570
  scalarCache,
15371
15571
  resolveFieldType,
15372
15572
  resolveFieldSemantics: resolveFieldSemantics2,
15573
+ evaluationContext,
15373
15574
  wildcardKeys: Object.keys(stripHiddenQualifiedColumns(
15374
15575
  stripParentShortcutColumns(row),
15375
15576
  hiddenQualifiedAliases
@@ -15377,7 +15578,7 @@ function project(rows, columns, scalarCache, resolveFieldType, sourceColumns2, r
15377
15578
  parentWildcardKeys: Object.keys(row).filter((key) => key.startsWith("_p.")).sort()
15378
15579
  };
15379
15580
  for (const [colIdx, col] of columns.entries()) {
15380
- const value = evaluateSelectColumnValue(col, row, colIdx, evaluationContext);
15581
+ const value = evaluateSelectColumnValue(col, row, colIdx, columnEvaluationContext);
15381
15582
  switch (col.type) {
15382
15583
  case "VARIABLE_COL":
15383
15584
  break;
@@ -15769,7 +15970,8 @@ function runFullScan(input) {
15769
15970
  hiddenQualifiedAliases,
15770
15971
  resolvedGroupingSpec,
15771
15972
  plainGroupByPlan,
15772
- warnings
15973
+ warnings,
15974
+ evaluationContext
15773
15975
  } = input;
15774
15976
  const effectiveOrderSemantics = deriveOutputOrderSemantics(stmt.columns, aggregateSortKindResolver);
15775
15977
  for (const [key, value] of orderSemantics ?? []) effectiveOrderSemantics.set(key, value);
@@ -15798,7 +16000,14 @@ function runFullScan(input) {
15798
16000
  knownColumns = mergeKnownColumns(knownColumns, rightColumns, rows);
15799
16001
  }
15800
16002
  const filterWhere = input.residualWhere !== void 0 ? input.residualWhere : stmt.where;
15801
- rows = applyFilter(rows, filterWhere, fieldTypeResolver, appliedKlikes, fieldSemanticsResolver);
16003
+ rows = applyFilter(
16004
+ rows,
16005
+ filterWhere,
16006
+ fieldTypeResolver,
16007
+ appliedKlikes,
16008
+ fieldSemanticsResolver,
16009
+ evaluationContext
16010
+ );
15802
16011
  const grouping = normalizeGroupingSpec(stmt);
15803
16012
  if (grouping.type === "GROUPING_SETS") {
15804
16013
  if (!resolvedGroupingSpec) {
@@ -15809,7 +16018,7 @@ function runFullScan(input) {
15809
16018
  resolvedGroupingSpec,
15810
16019
  stmt.columns,
15811
16020
  aggregateSortKindResolver,
15812
- { maxGeneratedRows: B65_MAX_GENERATED_ROWS }
16021
+ { maxGeneratedRows: B65_MAX_GENERATED_ROWS, evaluationContext }
15813
16022
  );
15814
16023
  } else if (grouping.type === "PLAIN" || hasAggregateColumns(stmt.columns)) {
15815
16024
  rows = applyGroupBy(
@@ -15821,21 +16030,29 @@ function runFullScan(input) {
15821
16030
  {
15822
16031
  scalarCache,
15823
16032
  resolveFieldType: fieldTypeResolver,
15824
- resolveFieldSemantics: fieldSemanticsResolver
16033
+ resolveFieldSemantics: fieldSemanticsResolver,
16034
+ evaluationContext
15825
16035
  }
15826
16036
  );
15827
16037
  }
15828
16038
  warnOnUnresolvedAggregateComparisons(stmt.columns, rows, warnings);
15829
16039
  const resolveHavingSemantics = (field) => field.aggregateRef ? aggregateResultSemantics(field.aggregateRef, aggregateSortKindResolver) : havingFieldSemanticsResolver?.(field);
15830
16040
  warnOnUnresolvedAggregateComparisons(stmt.having, rows, warnings);
15831
- rows = applyHaving(rows, stmt.having, havingFieldTypeResolver, resolveHavingSemantics);
16041
+ rows = applyHaving(
16042
+ rows,
16043
+ stmt.having,
16044
+ havingFieldTypeResolver,
16045
+ resolveHavingSemantics,
16046
+ evaluationContext
16047
+ );
15832
16048
  rows = applyWindow(
15833
16049
  rows,
15834
16050
  stmt.columns,
15835
16051
  optionOrders,
15836
16052
  sortKinds,
15837
16053
  effectiveOrderSemantics,
15838
- aggregateSortKindResolver
16054
+ aggregateSortKindResolver,
16055
+ evaluationContext
15839
16056
  );
15840
16057
  if (stmt.distinct) {
15841
16058
  rows = applyDistinct(
@@ -15843,7 +16060,8 @@ function runFullScan(input) {
15843
16060
  stmt.columns,
15844
16061
  scalarCache,
15845
16062
  fieldTypeResolver,
15846
- fieldSemanticsResolver
16063
+ fieldSemanticsResolver,
16064
+ evaluationContext
15847
16065
  );
15848
16066
  }
15849
16067
  rows = applyOrderBy(
@@ -15852,7 +16070,14 @@ function runFullScan(input) {
15852
16070
  optionOrders,
15853
16071
  sortKinds,
15854
16072
  effectiveOrderSemantics,
15855
- buildOrderByAliasEvaluator(stmt.columns, scalarCache, fieldTypeResolver, fieldSemanticsResolver)
16073
+ buildOrderByAliasEvaluator(
16074
+ stmt.columns,
16075
+ scalarCache,
16076
+ fieldTypeResolver,
16077
+ fieldSemanticsResolver,
16078
+ evaluationContext
16079
+ ),
16080
+ evaluationContext
15856
16081
  );
15857
16082
  rows = applyLimit(rows, stmt.limit, stmt.offset);
15858
16083
  return project(
@@ -15862,7 +16087,8 @@ function runFullScan(input) {
15862
16087
  fieldTypeResolver,
15863
16088
  sourceColumns2,
15864
16089
  fieldSemanticsResolver,
15865
- hiddenQualifiedAliases
16090
+ hiddenQualifiedAliases,
16091
+ evaluationContext
15866
16092
  );
15867
16093
  }
15868
16094
 
@@ -17572,6 +17798,18 @@ var SearchAbortedError = class extends Error {
17572
17798
  var materializedMetaBySelectResult = /* @__PURE__ */ new WeakMap();
17573
17799
  var materializedMetaByValidationResult = /* @__PURE__ */ new WeakMap();
17574
17800
  var importSourceByDmlStatement = /* @__PURE__ */ new WeakMap();
17801
+ var statementEvaluationContextKey = /* @__PURE__ */ Symbol("statementEvaluationContext");
17802
+ function bindStatementEvaluationContext(options) {
17803
+ const internal = options;
17804
+ if (internal[statementEvaluationContextKey]) return options;
17805
+ return {
17806
+ ...options,
17807
+ [statementEvaluationContextKey]: { statementInstant: /* @__PURE__ */ new Date() }
17808
+ };
17809
+ }
17810
+ function statementEvaluationContext(options) {
17811
+ return options[statementEvaluationContextKey] ?? {};
17812
+ }
17575
17813
  var defaultCacheContextByClient = /* @__PURE__ */ new WeakMap();
17576
17814
  var nextDefaultCacheContextId = 1;
17577
17815
  var nextCacheInvocationId = 1;
@@ -17821,6 +18059,7 @@ async function resolveRelativeDateExecutionPlan(stmt, client, cacheContext) {
17821
18059
  });
17822
18060
  }
17823
18061
  async function executeParsedStatement(stmt, client, options, cacheContext) {
18062
+ options = bindStatementEvaluationContext(options);
17824
18063
  const relativeDatePlan = await resolveRelativeDateExecutionPlan(stmt, client, cacheContext);
17825
18064
  if (stmt.type !== "EXPLAIN") assertRelativeDatePushdownPlan(relativeDatePlan);
17826
18065
  const unresolved = findVariableRef(stmt);
@@ -18035,7 +18274,14 @@ async function executeExistingRecordValidationCore(stmt, client, options, cacheC
18035
18274
  id: String(record["$id"]?.value ?? ""),
18036
18275
  record,
18037
18276
  flat: flatten(record, null)
18038
- })).filter((row) => stmt.where === null || evalWhere(stmt.where, row.flat, (field) => evaluationTypes.get(field.field)));
18277
+ })).filter((row) => stmt.where === null || evalWhere(
18278
+ stmt.where,
18279
+ row.flat,
18280
+ (field) => evaluationTypes.get(field.field),
18281
+ void 0,
18282
+ void 0,
18283
+ statementEvaluationContext(options)
18284
+ ));
18039
18285
  const rows = [];
18040
18286
  const detailRows = /* @__PURE__ */ new Map();
18041
18287
  const summaryRows = /* @__PURE__ */ new Map();
@@ -18312,6 +18558,7 @@ function statementHasApplyMutation(statement) {
18312
18558
  return statement.type === "UPSERT" && statement.validateOnly !== true && Boolean(statement.onInsertApplyBlocks?.length || statement.onUpdateApplyBlocks?.length);
18313
18559
  }
18314
18560
  async function executeBatchStatement(stmt, info, client, options, cacheContext, tempTables, variables, relativeDateVariables) {
18561
+ options = bindStatementEvaluationContext(options);
18315
18562
  if (stmt.type === "SET_VARIABLE") {
18316
18563
  const resolvedStmt2 = resolveBatchVariableReferences(stmt, variables);
18317
18564
  validateStatementStatic(resolvedStmt2);
@@ -18351,7 +18598,7 @@ async function executeBatchStatement(stmt, info, client, options, cacheContext,
18351
18598
  throw e;
18352
18599
  }
18353
18600
  } else {
18354
- variables.set(stmt.name, evaluateScalarExpr(resolvedStmt2.expr));
18601
+ variables.set(stmt.name, evaluateScalarExpr(resolvedStmt2.expr, statementEvaluationContext(options)));
18355
18602
  }
18356
18603
  return {};
18357
18604
  }
@@ -18367,7 +18614,10 @@ async function executeBatchStatement(stmt, info, client, options, cacheContext,
18367
18614
  if (Object.prototype.hasOwnProperty.call(injected, stmt.name)) {
18368
18615
  variables.set(stmt.name, { type: "string", value: injected[stmt.name] });
18369
18616
  } else {
18370
- const value = evaluateScalarExpr(stmt.default);
18617
+ const value = evaluateScalarExpr(
18618
+ stmt.default,
18619
+ statementEvaluationContext(options)
18620
+ );
18371
18621
  variables.set(stmt.name, {
18372
18622
  type: "string",
18373
18623
  value: value.type === "number" ? value.raw ?? String(value.value) : value.value
@@ -18618,18 +18868,18 @@ function prepareRelativeDateVariables(statements, injectedVariables) {
18618
18868
  }
18619
18869
  return prepared;
18620
18870
  }
18621
- function evaluateScalarExpr(expr) {
18871
+ function evaluateScalarExpr(expr, evaluationContext = {}) {
18622
18872
  switch (expr.type) {
18623
18873
  case "STRING":
18624
18874
  return { type: "string", value: expr.value };
18625
18875
  case "NUMBER":
18626
18876
  return { type: "number", value: expr.value, raw: numberLiteralText(expr) };
18627
18877
  case "KINTONE_FUNC":
18628
- return { type: "string", value: resolveKintoneFunc(expr.name) };
18878
+ return { type: "string", value: resolveKintoneFunc(expr.name, evaluationContext) };
18629
18879
  case "STRING_FUNC":
18630
- return { type: "string", value: evalStringFunc(expr, {}) };
18880
+ return { type: "string", value: evalStringFunc(expr, {}, void 0, void 0, evaluationContext) };
18631
18881
  case "ARITH": {
18632
- const value = evalArithExpr(expr, {});
18882
+ const value = evalArithExpr(expr, {}, evaluationContext);
18633
18883
  if (!Number.isFinite(value)) {
18634
18884
  throw new Error("ArgumentError: SET scalar arithmetic produced a non-finite number.");
18635
18885
  }
@@ -19136,7 +19386,7 @@ async function executeSelect(stmt, client, options, cacheContext, cteCache, capt
19136
19386
  const subqueryWarnings = /* @__PURE__ */ new Set();
19137
19387
  await validateSelectGroupingPlanning(stmt, client, cacheContext, cteCache);
19138
19388
  if (isNoFromSelect(stmt)) {
19139
- result = executeNoFromSelect(stmt);
19389
+ result = executeNoFromSelect(stmt, options);
19140
19390
  if (captureColumnMeta) {
19141
19391
  materializedMetaBySelectResult.set(
19142
19392
  result,
@@ -19617,13 +19867,30 @@ function validateNoFromColumns(stmt) {
19617
19867
  }
19618
19868
  }
19619
19869
  }
19620
- function executeNoFromSelect(stmt) {
19870
+ function executeNoFromSelect(stmt, options) {
19621
19871
  if (stmt.joins.length > 0 || stmt.where || normalizeGroupingSpec(stmt).type !== "NONE" || stmt.having || stmt.orderBy.length > 0 || stmt.distinct) {
19622
19872
  throw new Error("ArgumentError: JOIN/WHERE/GROUP BY/HAVING/ORDER BY/DISTINCT are not supported without FROM.");
19623
19873
  }
19624
19874
  validateNoFromColumns(stmt);
19625
- const windowed = applyWindow([{}], stmt.columns);
19626
- const { rows: projected, columns } = project(windowed, stmt.columns);
19875
+ const windowed = applyWindow(
19876
+ [{}],
19877
+ stmt.columns,
19878
+ void 0,
19879
+ void 0,
19880
+ void 0,
19881
+ void 0,
19882
+ statementEvaluationContext(options)
19883
+ );
19884
+ const { rows: projected, columns } = project(
19885
+ windowed,
19886
+ stmt.columns,
19887
+ void 0,
19888
+ void 0,
19889
+ void 0,
19890
+ void 0,
19891
+ void 0,
19892
+ statementEvaluationContext(options)
19893
+ );
19627
19894
  const rows = applyLimit(projected, stmt.limit, stmt.offset);
19628
19895
  return { type: "SELECT", rows, columns, rowCount: rows.length, warnings: [] };
19629
19896
  }
@@ -19699,8 +19966,10 @@ async function executeSimpleSelect(stmt, client, options, cacheContext, orderPla
19699
19966
  stmt.columns,
19700
19967
  void 0,
19701
19968
  fieldTypeResolvers.row,
19702
- projectionSemanticsResolver
19703
- )
19969
+ projectionSemanticsResolver,
19970
+ statementEvaluationContext(options)
19971
+ ),
19972
+ statementEvaluationContext(options)
19704
19973
  );
19705
19974
  rows = applyLimit(rows, stmt.limit, stmt.offset);
19706
19975
  }
@@ -19710,7 +19979,9 @@ async function executeSimpleSelect(stmt, client, options, cacheContext, orderPla
19710
19979
  void 0,
19711
19980
  fieldTypeResolvers.row,
19712
19981
  void 0,
19713
- projectionSemanticsResolver
19982
+ projectionSemanticsResolver,
19983
+ void 0,
19984
+ statementEvaluationContext(options)
19714
19985
  );
19715
19986
  const columns = await restoreEmptyWildcardColumns(
19716
19987
  stmt,
@@ -20873,7 +21144,8 @@ async function executeFullScanSelect(stmt, client, options, cacheContext, cteCac
20873
21144
  ...prefilterPlan ? { residualWhere: prefilterPlan.residualWhere } : boundServerFunctionPlan ? { residualWhere: boundServerFunctionPlan.joinPlan.residualWhere } : {},
20874
21145
  resolvedGroupingSpec: resolvedGroupingSpecs.get(stmt),
20875
21146
  plainGroupByPlan,
20876
- warnings
21147
+ warnings,
21148
+ evaluationContext: statementEvaluationContext(options)
20877
21149
  });
20878
21150
  const columns = await restoreEmptyWildcardColumns(
20879
21151
  stmt,
@@ -21700,7 +21972,8 @@ async function executeFullScanWithCte(stmt, client, options, cteCache, cacheCont
21700
21972
  tableColumns,
21701
21973
  hiddenQualifiedAliases,
21702
21974
  resolvedGroupingSpec,
21703
- plainGroupByPlan
21975
+ plainGroupByPlan,
21976
+ evaluationContext: statementEvaluationContext(options)
21704
21977
  });
21705
21978
  const columns = await restoreEmptyWildcardColumns(
21706
21979
  stmt,
@@ -22826,7 +23099,12 @@ async function materializeValidationCandidates(stmt, operation, client, options,
22826
23099
  evaluationTypes = new Map(stmt.fields.map((field) => [field, infoByCode.get(field)?.fieldType ?? ""]));
22827
23100
  assertCheckComparisonTypes(stmt, evaluationTypes);
22828
23101
  rows = stmt.values.map((row) => row.map(
22829
- (value, i) => value.type === "CASE_VALUE" ? evalCaseWhenValue(value.expr, {}, infoByCode.get(stmt.fields[i])?.fieldType) : value
23102
+ (value, i) => value.type === "CASE_VALUE" ? evalCaseWhenValue(
23103
+ value.expr,
23104
+ {},
23105
+ infoByCode.get(stmt.fields[i])?.fieldType,
23106
+ statementEvaluationContext(options)
23107
+ ) : value
22830
23108
  ));
22831
23109
  } else {
22832
23110
  const selectResult = await dmlSourceMaterializer.materialize(stmt, client, options, cacheContext, tempTables, [...infoByCode.values()]);
@@ -22957,7 +23235,12 @@ async function materializeUpdateValidationCandidates(stmt, client, options, cach
22957
23235
  });
22958
23236
  snapshotsById = indexDmlUpdateSnapshots(resolved.records);
22959
23237
  evaluationById = snapshotsById;
22960
- records = updateToPutBatchesArith(stmt, resolved.records, fieldTypes).flatMap((batch) => batch.records);
23238
+ records = updateToPutBatchesArith(
23239
+ stmt,
23240
+ resolved.records,
23241
+ fieldTypes,
23242
+ statementEvaluationContext(options)
23243
+ ).flatMap((batch) => batch.records);
22961
23244
  } else {
22962
23245
  const getParams = updateToGetQuery(stmt);
22963
23246
  if (checkTargetFields.length > 0) {
@@ -23125,7 +23408,12 @@ async function materializeUpdateFromValidationCandidates(stmt, from, client, opt
23125
23408
  snapshotFields
23126
23409
  );
23127
23410
  const fieldTypes = await getFieldTypeMap(stmt.appId, client, cacheContext);
23128
- const records = updateFromToPutBatches(stmt, matched, fieldTypes).flatMap((batch) => batch.records);
23411
+ const records = updateFromToPutBatches(
23412
+ stmt,
23413
+ matched,
23414
+ fieldTypes,
23415
+ statementEvaluationContext(options)
23416
+ ).flatMap((batch) => batch.records);
23129
23417
  const matchedById = new Map(matched.map((pair) => [Number(pair.target["$id"]?.value), pair]));
23130
23418
  const snapshotsById = snapshotFields ? indexDmlUpdateSnapshots(matched.map((pair) => pair.target)) : /* @__PURE__ */ new Map();
23131
23419
  return records.sort((a, b) => a.id - b.id).map((entry, index) => ({
@@ -23357,7 +23645,7 @@ async function executeInsert(stmt, client, options, cacheContext) {
23357
23645
  const fieldInfos = await loadWritableTopLevelDmlFields(stmt.appId, stmt.fields, client, cacheContext);
23358
23646
  const numberPrecision = await loadNumberPrecisionForTargets(stmt.appId, stmt.fields, fieldInfos, client, cacheContext);
23359
23647
  const fieldTypes = await getFieldTypeMap(stmt.appId, client, cacheContext);
23360
- const batches = insertToPostBatches(stmt, fieldTypes);
23648
+ const batches = insertToPostBatches(stmt, fieldTypes, statementEvaluationContext(options));
23361
23649
  assertValidDmlRecords(batches.flatMap((batch) => batch.records), stmt.fields, fieldInfos, numberPrecision);
23362
23650
  const createdIds = [];
23363
23651
  for (const batch of batches) {
@@ -23966,7 +24254,12 @@ async function executeUpdate(stmt, client, options, cacheContext, tempTables) {
23966
24254
  { maxRecords, parallel: options.fetchParallel ?? 1 }
23967
24255
  );
23968
24256
  const records = resolved2.records;
23969
- const batches2 = updateToPutBatchesArith(stmt, records, fieldTypes);
24257
+ const batches2 = updateToPutBatchesArith(
24258
+ stmt,
24259
+ records,
24260
+ fieldTypes,
24261
+ statementEvaluationContext(options)
24262
+ );
23970
24263
  assertValidDmlRecords(batches2.flatMap((batch) => batch.records.map((entry) => entry.record)), targetFields, fieldInfos, numberPrecision);
23971
24264
  if (options.confirm) {
23972
24265
  const ok = await options.confirm(records.length, "UPDATE");
@@ -24023,7 +24316,13 @@ async function executeApplyPatchUpdate(stmt, client, options, cacheContext, stat
24023
24316
  throw new Error(`ArgumentError: APPLY snapshot $id ${actualId} does not match requested $id ${requestedId}.`);
24024
24317
  }
24025
24318
  requireRevision(response.records[0]);
24026
- const plan = buildApplyPatchPlan({ statement: stmt, snapshot: response.records[0], fieldInfos, metadata });
24319
+ const plan = buildApplyPatchPlan({
24320
+ statement: stmt,
24321
+ snapshot: response.records[0],
24322
+ fieldInfos,
24323
+ metadata,
24324
+ evaluationContext: statementEvaluationContext(options)
24325
+ });
24027
24326
  const fieldIndex = buildPostImageFieldIndex(
24028
24327
  fieldInfos,
24029
24328
  stmt.assignments.map((assignment) => assignment.field)
@@ -24222,7 +24521,8 @@ async function selectApplyParentSnapshots(stmt, client, options, fieldInfos, cac
24222
24521
  row,
24223
24522
  resolvers.fieldTypeResolver,
24224
24523
  selectionPlan.appliedKlikes,
24225
- resolvers.fieldSemanticsResolver
24524
+ resolvers.fieldSemanticsResolver,
24525
+ statementEvaluationContext(options)
24226
24526
  )).map(({ snapshot }) => snapshot);
24227
24527
  }
24228
24528
  function collectApplyParentWhereFields(where) {
@@ -24463,7 +24763,12 @@ function applyValidationColumnMeta(columns, fieldInfos, appId) {
24463
24763
  async function executeUpdateFrom(stmt, from, client, options, cacheContext, tempTables) {
24464
24764
  const matched = await resolveUpdateFromMatchedRecords(stmt, from, client, options, cacheContext, tempTables);
24465
24765
  const fieldTypes = await getFieldTypeMap(stmt.appId, client, cacheContext);
24466
- const batches = updateFromToPutBatches(stmt, matched, fieldTypes);
24766
+ const batches = updateFromToPutBatches(
24767
+ stmt,
24768
+ matched,
24769
+ fieldTypes,
24770
+ statementEvaluationContext(options)
24771
+ );
24467
24772
  const targetFields = stmt.assignments.map((assignment) => assignment.field);
24468
24773
  const fieldInfos = await getFieldsCached(stmt.appId, client, cacheContext);
24469
24774
  const numberPrecision = await loadNumberPrecisionForTargets(stmt.appId, targetFields, fieldInfos, client, cacheContext);
@@ -24537,7 +24842,12 @@ async function executeUpsert(stmt, client, options, cacheContext) {
24537
24842
  stmt.fields.forEach((field, i) => {
24538
24843
  const val = row[i];
24539
24844
  if (val.type === "CASE_VALUE") {
24540
- record[field] = { value: evalCaseWhenValue(val.expr, {}, fieldTypes.get(field)) };
24845
+ record[field] = { value: evalCaseWhenValue(
24846
+ val.expr,
24847
+ {},
24848
+ fieldTypes.get(field),
24849
+ statementEvaluationContext(options)
24850
+ ) };
24541
24851
  } else {
24542
24852
  record[field] = { value: toKintoneValue(val, fieldTypes.get(field)) };
24543
24853
  }
@@ -24658,7 +24968,14 @@ async function executeUpdateSubtable(stmt, client, options, cacheContext) {
24658
24968
  { maxRecords: options.maxRecords ?? 1e4, parallel: options.fetchParallel ?? 1 }
24659
24969
  );
24660
24970
  const expanded = expandRowsForSubtableDml(parents, subtableCode);
24661
- const targets = expanded.filter((r) => evalWhere(stmt.where, r.flat, resolveFieldType));
24971
+ const targets = expanded.filter((r) => evalWhere(
24972
+ stmt.where,
24973
+ r.flat,
24974
+ resolveFieldType,
24975
+ void 0,
24976
+ void 0,
24977
+ statementEvaluationContext(options)
24978
+ ));
24662
24979
  if (options.confirm) {
24663
24980
  const ok = await options.confirm(targets.length, "UPDATE");
24664
24981
  if (!ok) throw new OperationCancelledError("UPDATE", targets.length);
@@ -24678,7 +24995,12 @@ async function executeUpdateSubtable(stmt, client, options, cacheContext) {
24678
24995
  if (a.field.startsWith("_")) {
24679
24996
  throw new Error(`\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB UPDATE \u3067\u30B7\u30B9\u30C6\u30E0\u5217\u300C${a.field}\u300D\u306F\u66F4\u65B0\u3067\u304D\u307E\u305B\u3093`);
24680
24997
  }
24681
- updates[a.field] = { value: evaluateSubtableAssignmentValue(a.value, t.flat, resolveFieldType) };
24998
+ updates[a.field] = { value: evaluateSubtableAssignmentValue(
24999
+ a.value,
25000
+ t.flat,
25001
+ resolveFieldType,
25002
+ statementEvaluationContext(options)
25003
+ ) };
24682
25004
  }
24683
25005
  byRid.set(t.rowId, updates);
24684
25006
  }
@@ -24721,7 +25043,14 @@ async function executeDeleteSubtable(stmt, client, options, cacheContext) {
24721
25043
  { maxRecords: options.maxRecords ?? 1e4, parallel: options.fetchParallel ?? 1 }
24722
25044
  );
24723
25045
  const expanded = expandRowsForSubtableDml(parents, subtableCode);
24724
- const targets = expanded.filter((r) => evalWhere(stmt.where, r.flat, resolveFieldType));
25046
+ const targets = expanded.filter((r) => evalWhere(
25047
+ stmt.where,
25048
+ r.flat,
25049
+ resolveFieldType,
25050
+ void 0,
25051
+ void 0,
25052
+ statementEvaluationContext(options)
25053
+ ));
24725
25054
  if (options.confirm) {
24726
25055
  const ok = await options.confirm(targets.length, "DELETE");
24727
25056
  if (!ok) throw new OperationCancelledError("DELETE", targets.length);
@@ -24896,7 +25225,8 @@ async function executeReorder(stmt, client, options, cacheContext) {
24896
25225
  r.flat,
24897
25226
  resolveFieldType,
24898
25227
  void 0,
24899
- resolveReorderSemantics
25228
+ resolveReorderSemantics,
25229
+ statementEvaluationContext(options)
24900
25230
  )).map((r) => r.parentId));
24901
25231
  if (options.confirm) {
24902
25232
  const ok = await options.confirm(targetParentIds.size, "UPDATE");
@@ -24908,7 +25238,13 @@ async function executeReorder(stmt, client, options, cacheContext) {
24908
25238
  if (!parent) continue;
24909
25239
  const rows = getMutableTableRows(parent, stmt.subtableCode);
24910
25240
  const sortable = rows.map((row, i) => ({ row, i, flat: buildFlatRowForSort(parent, stmt.subtableCode, row, i) }));
24911
- sortable.sort((a, b) => compareByOrder(a.flat, b.flat, stmt.by, resolveReorderSemantics));
25241
+ sortable.sort((a, b) => compareByOrder(
25242
+ a.flat,
25243
+ b.flat,
25244
+ stmt.by,
25245
+ resolveReorderSemantics,
25246
+ statementEvaluationContext(options)
25247
+ ));
24912
25248
  const orderedRowIds = sortable.map((x) => x.row.id ?? "");
24913
25249
  await client.putRecords(buildSubtableReorderPutParams(stmt.appId, pid, getRevision(parent), stmt.subtableCode, orderedRowIds));
24914
25250
  }
@@ -24929,24 +25265,24 @@ function buildFlatRowForSort(parent, subtableCode, row, idx) {
24929
25265
  }
24930
25266
  return flat;
24931
25267
  }
24932
- function compareByOrder(a, b, orderBy, resolveSemantics) {
25268
+ function compareByOrder(a, b, orderBy, resolveSemantics, evaluationContext = {}) {
24933
25269
  for (const item of orderBy) {
24934
- const av = evalOrderKeyForRow(item.key, a);
24935
- const bv = evalOrderKeyForRow(item.key, b);
25270
+ const av = evalOrderKeyForRow(item.key, a, evaluationContext);
25271
+ const bv = evalOrderKeyForRow(item.key, b, evaluationContext);
24936
25272
  const semantics = item.key.type === "FIELD_NAME" ? resolveSemantics(aggregateFieldRef(item.key.name)) : item.key.type === "ARITH_KEY" ? syntheticSemantics("number") : item.key.type === "FUNC_KEY" ? stringFunctionColumnMeta(item.key.expr).semantics ?? syntheticSemantics("string") : syntheticSemantics("number");
24937
25273
  const cmp = compareCanonicalValues(av, bv, semantics ?? syntheticSemantics("string"));
24938
25274
  if (cmp !== 0) return item.direction === "ASC" ? cmp : -cmp;
24939
25275
  }
24940
25276
  return 0;
24941
25277
  }
24942
- function evalOrderKeyForRow(key, row) {
25278
+ function evalOrderKeyForRow(key, row, evaluationContext = {}) {
24943
25279
  switch (key.type) {
24944
25280
  case "FIELD_NAME":
24945
25281
  return row[key.name] ?? "";
24946
25282
  case "ARITH_KEY":
24947
- return String(evalArithExpr(key.expr, row));
25283
+ return String(evalArithExpr(key.expr, row, evaluationContext));
24948
25284
  case "FUNC_KEY":
24949
- return evalStringFunc(key.expr, row);
25285
+ return evalStringFunc(key.expr, row, void 0, void 0, evaluationContext);
24950
25286
  case "GROUPING_KEY":
24951
25287
  throw new Error("ArgumentError: GROUPING() is not supported in REORDER BY.");
24952
25288
  }
@@ -25461,9 +25797,13 @@ async function buildExplainWhereAnalysis(query, client, cacheContext, maxRecords
25461
25797
  const joinField = leftAlias === joinAlias ? join2.on.left.field : join2.on.right.field;
25462
25798
  if (!sourceAlias) continue;
25463
25799
  const sourceTable = [select.from, ...select.joins.map((candidate) => candidate.table)].find((table) => effectiveTableAlias(table) === sourceAlias);
25464
- const targetInfos = await getFieldsCached(join2.table.appId, tracedClient, cacheContext);
25465
- const targetInfo = targetInfos.find((info) => info.code === fieldCodeForTypeLookup(join2.table, joinField));
25466
- const targetMeta = targetInfo ? materializedMetaFromFieldInfo(targetInfo, join2.table.appId) : systemColumnMeta(joinField);
25800
+ let targetMeta;
25801
+ if (join2.table.cteName !== null) {
25802
+ targetMeta = explainRelations.get(join2.table.cteName)?.columnMeta?.get(joinField);
25803
+ } else {
25804
+ const targetInfo = (await getFieldsCached(join2.table.appId, tracedClient, cacheContext)).find((info) => info.code === fieldCodeForTypeLookup(join2.table, joinField));
25805
+ targetMeta = targetInfo ? materializedMetaFromFieldInfo(targetInfo, join2.table.appId) : systemColumnMeta(joinField);
25806
+ }
25467
25807
  let sourceMeta;
25468
25808
  let values;
25469
25809
  let sourceRowCount;