@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.
@@ -29764,7 +29764,7 @@ var import_docsResourceBuilder = __toESM(require_docsResourceBuilder());
29764
29764
 
29765
29765
  // src/mcp/serverVersion.ts
29766
29766
  init_define_KSQL_DOCS();
29767
- var SERVER_VERSION = true ? "3.66.0" : "0.0.0-dev";
29767
+ var SERVER_VERSION = true ? "3.67.0" : "0.0.0-dev";
29768
29768
 
29769
29769
  // src/mcp/docsResources.ts
29770
29770
  function loadFromRepoDocs() {
@@ -39333,15 +39333,15 @@ function selectScalarExtreme(values, extreme) {
39333
39333
  }
39334
39334
 
39335
39335
  // src/engine/evalFunc.ts
39336
- function evalArithExpr(expr, row) {
39336
+ function evalArithExpr(expr, row, context = {}) {
39337
39337
  if (expr.type === "VARIABLE") throw new Error(
39338
39338
  `InternalError: unresolved arithmetic variable @${expr.name} reached arithmetic evaluation.`
39339
39339
  );
39340
39340
  if (expr.type === "NUMBER") return expr.value;
39341
39341
  if (expr.type === "FIELD_REF") return Number(resolveFieldRef(row, expr.field));
39342
- if (expr.type === "STRING_FUNC") return Number(evalStringFunc(expr, row));
39343
- const l = evalArithExpr(expr.left, row);
39344
- const r = evalArithExpr(expr.right, row);
39342
+ if (expr.type === "STRING_FUNC") return Number(evalStringFunc(expr, row, void 0, void 0, context));
39343
+ const l = evalArithExpr(expr.left, row, context);
39344
+ const r = evalArithExpr(expr.right, row, context);
39345
39345
  switch (expr.op) {
39346
39346
  case "+":
39347
39347
  return l + r;
@@ -39355,7 +39355,7 @@ function evalArithExpr(expr, row) {
39355
39355
  return r !== 0 ? l % r : NaN;
39356
39356
  }
39357
39357
  }
39358
- function evalScalarValueExpr(expr, row, resolveFieldType, resolveFieldSemantics2) {
39358
+ function evalScalarValueExpr(expr, row, resolveFieldType, resolveFieldSemantics2, context = {}) {
39359
39359
  switch (expr.type) {
39360
39360
  case "STRING":
39361
39361
  return expr.value;
@@ -39366,19 +39366,19 @@ function evalScalarValueExpr(expr, row, resolveFieldType, resolveFieldSemantics2
39366
39366
  case "VARIABLE":
39367
39367
  throw new Error(`ArgumentError: unresolved variable @${expr.name} reached scalar evaluator.`);
39368
39368
  case "STRING_FUNC":
39369
- return evalStringFunc(expr, row, resolveFieldType, resolveFieldSemantics2);
39369
+ return evalStringFunc(expr, row, resolveFieldType, resolveFieldSemantics2, context);
39370
39370
  case "CASE_WHEN":
39371
- return evalCaseWhen(expr, row, resolveFieldType, resolveFieldSemantics2);
39371
+ return evalCaseWhen(expr, row, resolveFieldType, resolveFieldSemantics2, context);
39372
39372
  case "CONCAT_OP": {
39373
39373
  return evalStringFunc({
39374
39374
  type: "STRING_FUNC",
39375
39375
  func: "CONCAT",
39376
39376
  args: [expr.left, expr.right]
39377
- }, row, resolveFieldType, resolveFieldSemantics2);
39377
+ }, row, resolveFieldType, resolveFieldSemantics2, context);
39378
39378
  }
39379
39379
  case "SCALAR_ARITH": {
39380
- const left = Number(evalScalarValueExpr(expr.left, row, resolveFieldType, resolveFieldSemantics2));
39381
- const right = Number(evalScalarValueExpr(expr.right, row, resolveFieldType, resolveFieldSemantics2));
39380
+ const left = Number(evalScalarValueExpr(expr.left, row, resolveFieldType, resolveFieldSemantics2, context));
39381
+ const right = Number(evalScalarValueExpr(expr.right, row, resolveFieldType, resolveFieldSemantics2, context));
39382
39382
  switch (expr.op) {
39383
39383
  case "+":
39384
39384
  return left + right;
@@ -39394,13 +39394,13 @@ function evalScalarValueExpr(expr, row, resolveFieldType, resolveFieldSemantics2
39394
39394
  }
39395
39395
  }
39396
39396
  }
39397
- function evalScalarValueExprNullable(expr, row, resolveFieldType, resolveFieldSemantics2) {
39397
+ function evalScalarValueExprNullable(expr, row, resolveFieldType, resolveFieldSemantics2, context = {}) {
39398
39398
  switch (expr.type) {
39399
39399
  case "CASE_WHEN":
39400
- return evalCaseWhenNullable(expr, row, resolveFieldType, resolveFieldSemantics2);
39400
+ return evalCaseWhenNullable(expr, row, resolveFieldType, resolveFieldSemantics2, context);
39401
39401
  case "SCALAR_ARITH": {
39402
- const left = evalScalarValueExprNullable(expr.left, row, resolveFieldType, resolveFieldSemantics2);
39403
- const right = evalScalarValueExprNullable(expr.right, row, resolveFieldType, resolveFieldSemantics2);
39402
+ const left = evalScalarValueExprNullable(expr.left, row, resolveFieldType, resolveFieldSemantics2, context);
39403
+ const right = evalScalarValueExprNullable(expr.right, row, resolveFieldType, resolveFieldSemantics2, context);
39404
39404
  if (left === null || right === null) return null;
39405
39405
  const l = Number(left);
39406
39406
  const r = Number(right);
@@ -39418,12 +39418,12 @@ function evalScalarValueExprNullable(expr, row, resolveFieldType, resolveFieldSe
39418
39418
  }
39419
39419
  }
39420
39420
  case "CONCAT_OP": {
39421
- const left = evalScalarValueExprNullable(expr.left, row, resolveFieldType, resolveFieldSemantics2);
39422
- const right = evalScalarValueExprNullable(expr.right, row, resolveFieldType, resolveFieldSemantics2);
39421
+ const left = evalScalarValueExprNullable(expr.left, row, resolveFieldType, resolveFieldSemantics2, context);
39422
+ const right = evalScalarValueExprNullable(expr.right, row, resolveFieldType, resolveFieldSemantics2, context);
39423
39423
  return `${left ?? ""}${right ?? ""}`;
39424
39424
  }
39425
39425
  default:
39426
- return evalScalarValueExpr(expr, row, resolveFieldType, resolveFieldSemantics2);
39426
+ return evalScalarValueExpr(expr, row, resolveFieldType, resolveFieldSemantics2, context);
39427
39427
  }
39428
39428
  }
39429
39429
  function applyRoundOp(op, num, digits) {
@@ -39575,9 +39575,9 @@ function replaceNthMatch(input, globalRe, replacement, n) {
39575
39575
  return expandRegexpReplacement(replacement, match, captures, namedGroups);
39576
39576
  });
39577
39577
  }
39578
- function evalStringFunc(expr, row, resolveFieldType, resolveFieldSemantics2) {
39578
+ function evalStringFunc(expr, row, resolveFieldType, resolveFieldSemantics2, context = {}) {
39579
39579
  assertStringFunctionArity(expr.func, expr.args);
39580
- const args = expr.args.map((a) => evalStringFuncArg(a, row, resolveFieldType, resolveFieldSemantics2));
39580
+ const args = expr.args.map((a) => evalStringFuncArg(a, row, resolveFieldType, resolveFieldSemantics2, context));
39581
39581
  switch (expr.func) {
39582
39582
  case "UPPER":
39583
39583
  return (args[0] ?? "").toUpperCase();
@@ -39725,14 +39725,14 @@ function evalStringFunc(expr, row, resolveFieldType, resolveFieldSemantics2) {
39725
39725
  case "SQRT":
39726
39726
  return String(Math.sqrt(Number(args[0] ?? "0")));
39727
39727
  case "CURRENT_DATE": {
39728
- const now = /* @__PURE__ */ new Date();
39728
+ const now = context.statementInstant ?? /* @__PURE__ */ new Date();
39729
39729
  const y = now.getFullYear();
39730
39730
  const m = String(now.getMonth() + 1).padStart(2, "0");
39731
39731
  const d = String(now.getDate()).padStart(2, "0");
39732
39732
  return `${y}-${m}-${d}`;
39733
39733
  }
39734
39734
  case "CURRENT_TIMESTAMP":
39735
- return (/* @__PURE__ */ new Date()).toISOString();
39735
+ return (context.statementInstant ?? /* @__PURE__ */ new Date()).toISOString();
39736
39736
  }
39737
39737
  }
39738
39738
  function parseDateParts(s) {
@@ -39894,12 +39894,12 @@ function formatWithComma(num, digits) {
39894
39894
  const intFmt = intStr.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
39895
39895
  return decStr ? `${intFmt}.${decStr}` : intFmt;
39896
39896
  }
39897
- function evalStringFuncArg(arg, row, resolveFieldType, resolveFieldSemantics2) {
39897
+ function evalStringFuncArg(arg, row, resolveFieldType, resolveFieldSemantics2, context = {}) {
39898
39898
  if (arg.type === "AGG_REF" || arg.type === "AGG_ARITH" || arg.type === "AGG_GROUP_KEY") {
39899
39899
  return String(evalMaterializedAggregateOperand(arg, row));
39900
39900
  }
39901
39901
  if (arg.type === "NUMBER") return numberLiteralText(arg);
39902
- return String(evalScalarValueExpr(arg, row, resolveFieldType, resolveFieldSemantics2));
39902
+ return String(evalScalarValueExpr(arg, row, resolveFieldType, resolveFieldSemantics2, context));
39903
39903
  }
39904
39904
  function evalMaterializedAggregateOperand(node, row) {
39905
39905
  if (node.type === "NUMBER") return node.value;
@@ -39940,37 +39940,37 @@ function resolveFieldRef(row, field) {
39940
39940
  }
39941
39941
 
39942
39942
  // src/engine/evalWhere.ts
39943
- function evalWhere(expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2) {
39943
+ function evalWhere(expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2, context = {}) {
39944
39944
  switch (expr.type) {
39945
39945
  case "BOOLEAN":
39946
39946
  return expr.value;
39947
39947
  case "BINARY":
39948
- return evalBinary(expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2);
39948
+ return evalBinary(expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2, context);
39949
39949
  case "NULL_CHECK":
39950
39950
  return evalNullCheck(expr, row);
39951
39951
  case "LOGICAL":
39952
- return evalLogical(expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2);
39952
+ return evalLogical(expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2, context);
39953
39953
  case "NOT":
39954
- return !evalWhere(expr.expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2);
39954
+ return !evalWhere(expr.expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2, context);
39955
39955
  case "GROUP":
39956
- return evalWhere(expr.expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2);
39956
+ return evalWhere(expr.expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2, context);
39957
39957
  case "EXISTS": {
39958
39958
  const exists = expr.resolved;
39959
39959
  return expr.not ? !exists : exists;
39960
39960
  }
39961
39961
  }
39962
39962
  }
39963
- function evalBinary(expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2) {
39963
+ function evalBinary(expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2, context = {}) {
39964
39964
  if (expr.op === "KLIKE" || expr.op === "NOT_KLIKE") {
39965
39965
  if (appliedKlikes?.has(expr)) return true;
39966
39966
  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");
39967
39967
  }
39968
- const left = resolveField(expr.left, row, resolveFieldType, resolveFieldSemantics2);
39968
+ const left = resolveField(expr.left, row, resolveFieldType, resolveFieldSemantics2, context);
39969
39969
  const fieldType = expr.left.type === "FIELD" ? resolveFieldType?.(expr.left) : void 0;
39970
39970
  const semantics = semanticsForLeft(expr.left, fieldType, resolveFieldSemantics2);
39971
- return evalOp(expr.op, left, expr.right, row, fieldType, resolveFieldType, semantics, resolveFieldSemantics2);
39971
+ return evalOp(expr.op, left, expr.right, row, fieldType, resolveFieldType, semantics, resolveFieldSemantics2, context);
39972
39972
  }
39973
- function evalOp(op, leftStr, right, row, fieldType, resolveFieldType, semantics = syntheticSemantics("string"), resolveFieldSemantics2) {
39973
+ function evalOp(op, leftStr, right, row, fieldType, resolveFieldType, semantics = syntheticSemantics("string"), resolveFieldSemantics2, context = {}) {
39974
39974
  if (op === "IN" || op === "NOT_IN") {
39975
39975
  let values = null;
39976
39976
  if (right.type === "IN_LIST") {
@@ -39985,17 +39985,17 @@ function evalOp(op, leftStr, right, row, fieldType, resolveFieldType, semantics
39985
39985
  return op === "IN" ? contains : !contains;
39986
39986
  }
39987
39987
  if (op === "LIKE") {
39988
- const pattern = resolveValue(right, row, resolveFieldType);
39988
+ const pattern = resolveValue(right, row, resolveFieldType, void 0, context);
39989
39989
  return matchLike(leftStr, pattern);
39990
39990
  }
39991
39991
  if (op === "NOT_LIKE") {
39992
- const pattern = resolveValue(right, row, resolveFieldType);
39992
+ const pattern = resolveValue(right, row, resolveFieldType, void 0, context);
39993
39993
  return !matchLike(leftStr, pattern);
39994
39994
  }
39995
39995
  if (op === "KLIKE" || op === "NOT_KLIKE") {
39996
39996
  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");
39997
39997
  }
39998
- const rightStr = resolveValue(right, row, resolveFieldType, resolveFieldSemantics2);
39998
+ const rightStr = resolveValue(right, row, resolveFieldType, resolveFieldSemantics2, context);
39999
39999
  return compareScalarValues(op, leftStr, rightStr, semantics);
40000
40000
  }
40001
40001
  var NUMERIC_STRING_FUNCTIONS = /* @__PURE__ */ new Set([
@@ -40107,17 +40107,17 @@ function evalNullCheck(expr, row) {
40107
40107
  const val = resolveField(expr.field, row);
40108
40108
  return expr.not ? val !== "" : val === "";
40109
40109
  }
40110
- function evalLogical(expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2) {
40110
+ function evalLogical(expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2, context = {}) {
40111
40111
  if (expr.op === "AND") {
40112
- return evalWhere(expr.left, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2) && evalWhere(expr.right, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2);
40112
+ return evalWhere(expr.left, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2, context) && evalWhere(expr.right, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2, context);
40113
40113
  }
40114
- return evalWhere(expr.left, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2) || evalWhere(expr.right, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2);
40114
+ return evalWhere(expr.left, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2, context) || evalWhere(expr.right, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2, context);
40115
40115
  }
40116
- function resolveField(field, row, resolveFieldType, resolveFieldSemantics2) {
40117
- if (field.type === "FUNC_FIELD") return evalStringFunc(field.expr, row);
40116
+ function resolveField(field, row, resolveFieldType, resolveFieldSemantics2, context = {}) {
40117
+ if (field.type === "FUNC_FIELD") return evalStringFunc(field.expr, row, void 0, void 0, context);
40118
40118
  if (field.type === "AGG_FIELD") return String(evalMaterializedAggregateOperand(field.expr, row));
40119
- if (field.type === "ARITH_FIELD") return String(evalArithExpr(field.expr, row));
40120
- if (field.type === "CASE_FIELD") return evalCaseWhen(field.expr, row, resolveFieldType, resolveFieldSemantics2);
40119
+ if (field.type === "ARITH_FIELD") return String(evalArithExpr(field.expr, row, context));
40120
+ if (field.type === "CASE_FIELD") return evalCaseWhen(field.expr, row, resolveFieldType, resolveFieldSemantics2, context);
40121
40121
  if (field.type === "GROUPING_FIELD") return evalGroupingRef(field.ref, row);
40122
40122
  if (field.aggregateRef) {
40123
40123
  const ref = field.aggregateRef;
@@ -40126,7 +40126,7 @@ function resolveField(field, row, resolveFieldType, resolveFieldSemantics2) {
40126
40126
  const key = field.tableAlias ? `${field.tableAlias}.${field.field}` : field.field;
40127
40127
  return resolveFieldRef(row, key);
40128
40128
  }
40129
- function resolveValue(value, row, resolveFieldType, resolveFieldSemantics2) {
40129
+ function resolveValue(value, row, resolveFieldType, resolveFieldSemantics2, context = {}) {
40130
40130
  switch (value.type) {
40131
40131
  case "VARIABLE":
40132
40132
  throw new Error(`ParseError: unresolved batch variable @${value.name}.`);
@@ -40148,44 +40148,44 @@ function resolveValue(value, row, resolveFieldType, resolveFieldSemantics2) {
40148
40148
  return value.resolved;
40149
40149
  case "ARITH_VALUE":
40150
40150
  if (value.expr.type === "FIELD_REF") return resolveFieldRef(row, value.expr.field);
40151
- if (value.expr.type === "STRING_FUNC") return evalStringFunc(value.expr, row);
40152
- return String(evalArithExpr(value.expr, row));
40151
+ if (value.expr.type === "STRING_FUNC") return evalStringFunc(value.expr, row, void 0, void 0, context);
40152
+ return String(evalArithExpr(value.expr, row, context));
40153
40153
  case "CASE_VALUE":
40154
- return evalCaseWhen(value.expr, row, resolveFieldType, resolveFieldSemantics2);
40154
+ return evalCaseWhen(value.expr, row, resolveFieldType, resolveFieldSemantics2, context);
40155
40155
  case "ARRAY":
40156
40156
  return value.elements.map((e) => e.value).join(",");
40157
40157
  }
40158
40158
  }
40159
- function evalCaseWhen(expr, row, resolveFieldType, resolveFieldSemantics2) {
40159
+ function evalCaseWhen(expr, row, resolveFieldType, resolveFieldSemantics2, context = {}) {
40160
40160
  for (const branch of expr.branches) {
40161
- if (evalWhere(branch.condition, row, resolveFieldType, void 0, resolveFieldSemantics2)) {
40162
- return evalCaseResult(branch.result, row, resolveFieldType, resolveFieldSemantics2);
40161
+ if (evalWhere(branch.condition, row, resolveFieldType, void 0, resolveFieldSemantics2, context)) {
40162
+ return evalCaseResult(branch.result, row, resolveFieldType, resolveFieldSemantics2, context);
40163
40163
  }
40164
40164
  }
40165
40165
  if (expr.elseResult !== null) {
40166
- return evalCaseResult(expr.elseResult, row, resolveFieldType, resolveFieldSemantics2);
40166
+ return evalCaseResult(expr.elseResult, row, resolveFieldType, resolveFieldSemantics2, context);
40167
40167
  }
40168
40168
  return "";
40169
40169
  }
40170
- function evalCaseWhenNullable(expr, row, resolveFieldType, resolveFieldSemantics2) {
40170
+ function evalCaseWhenNullable(expr, row, resolveFieldType, resolveFieldSemantics2, context = {}) {
40171
40171
  for (const branch of expr.branches) {
40172
- if (evalWhere(branch.condition, row, resolveFieldType, void 0, resolveFieldSemantics2)) {
40173
- return evalCaseResultNullable(branch.result, row, resolveFieldType, resolveFieldSemantics2);
40172
+ if (evalWhere(branch.condition, row, resolveFieldType, void 0, resolveFieldSemantics2, context)) {
40173
+ return evalCaseResultNullable(branch.result, row, resolveFieldType, resolveFieldSemantics2, context);
40174
40174
  }
40175
40175
  }
40176
- return expr.elseResult === null ? null : evalCaseResultNullable(expr.elseResult, row, resolveFieldType, resolveFieldSemantics2);
40176
+ return expr.elseResult === null ? null : evalCaseResultNullable(expr.elseResult, row, resolveFieldType, resolveFieldSemantics2, context);
40177
40177
  }
40178
- function evalCaseResultNullable(result, row, resolveFieldType, resolveFieldSemantics2) {
40178
+ function evalCaseResultNullable(result, row, resolveFieldType, resolveFieldSemantics2, context = {}) {
40179
40179
  if (result.type === "ARRAY") return result.elements.map((entry) => entry.value).join(",");
40180
40180
  if (result.type === "AGG_REF") {
40181
40181
  return row[aggregateSyntheticName(result.func, result.distinct, result.arg)] ?? "";
40182
40182
  }
40183
40183
  if (result.type === "AGG_ARITH") return row[aggregateOperandLabel(result)] ?? "";
40184
40184
  if (result.type === "FIELD_REF") return row[result.field] ?? "";
40185
- if (result.type === "ARITH") return evalArithExpr(result, row);
40186
- return evalScalarValueExprNullable(result, row, resolveFieldType, resolveFieldSemantics2);
40185
+ if (result.type === "ARITH") return evalArithExpr(result, row, context);
40186
+ return evalScalarValueExprNullable(result, row, resolveFieldType, resolveFieldSemantics2, context);
40187
40187
  }
40188
- function evalCaseResult(result, row, resolveFieldType, resolveFieldSemantics2) {
40188
+ function evalCaseResult(result, row, resolveFieldType, resolveFieldSemantics2, context = {}) {
40189
40189
  if (result.type === "ARRAY") return result.elements.map((e) => e.value).join(",");
40190
40190
  if (result.type === "AGG_REF") {
40191
40191
  return row[aggregateSyntheticName(result.func, result.distinct, result.arg)] ?? "";
@@ -40195,12 +40195,12 @@ function evalCaseResult(result, row, resolveFieldType, resolveFieldSemantics2) {
40195
40195
  return row[result.field] ?? "";
40196
40196
  }
40197
40197
  if (result.type === "ARITH") {
40198
- return String(evalArithExpr(result, row));
40198
+ return String(evalArithExpr(result, row, context));
40199
40199
  }
40200
- return String(evalScalarValueExpr(result, row, resolveFieldType, resolveFieldSemantics2));
40200
+ return String(evalScalarValueExpr(result, row, resolveFieldType, resolveFieldSemantics2, context));
40201
40201
  }
40202
- function resolveKintoneFunc(name) {
40203
- const now = /* @__PURE__ */ new Date();
40202
+ function resolveKintoneFunc(name, context = {}) {
40203
+ const now = context.statementInstant ?? /* @__PURE__ */ new Date();
40204
40204
  switch (name) {
40205
40205
  case "TODAY": {
40206
40206
  const y = now.getFullYear();
@@ -40324,21 +40324,21 @@ function assertDmlWhereIsSafe(where) {
40324
40324
  }
40325
40325
  var USER_TYPES = /* @__PURE__ */ new Set(["USER_SELECT", "ORGANIZATION_SELECT", "GROUP_SELECT"]);
40326
40326
  var ARRAY_TYPES = /* @__PURE__ */ new Set(["CHECK_BOX", "MULTI_SELECT"]);
40327
- function insertToPostBatches(stmt, fieldTypes = /* @__PURE__ */ new Map()) {
40327
+ function insertToPostBatches(stmt, fieldTypes = /* @__PURE__ */ new Map(), evaluationContext = {}) {
40328
40328
  const allRecords = stmt.values.map(
40329
- (row) => buildInsertRecord(stmt.fields, row, fieldTypes)
40329
+ (row) => buildInsertRecord(stmt.fields, row, fieldTypes, evaluationContext)
40330
40330
  );
40331
40331
  return chunk(allRecords, 100).map((records) => ({
40332
40332
  app: stmt.appId,
40333
40333
  records
40334
40334
  }));
40335
40335
  }
40336
- function buildInsertRecord(fields, row, fieldTypes) {
40336
+ function buildInsertRecord(fields, row, fieldTypes, evaluationContext) {
40337
40337
  const record2 = {};
40338
40338
  fields.forEach((field, i) => {
40339
40339
  const val = row[i];
40340
40340
  if (val.type === "CASE_VALUE") {
40341
- record2[field] = { value: evalCaseWhenValue(val.expr, {}, fieldTypes.get(field)) };
40341
+ record2[field] = { value: evalCaseWhenValue(val.expr, {}, fieldTypes.get(field), evaluationContext) };
40342
40342
  } else {
40343
40343
  record2[field] = { value: toKintoneValue(val, fieldTypes.get(field)) };
40344
40344
  }
@@ -40498,14 +40498,14 @@ function collectConditionFields(expr, out) {
40498
40498
  break;
40499
40499
  }
40500
40500
  }
40501
- function updateToPutBatchesArith(stmt, records, fieldTypes = /* @__PURE__ */ new Map()) {
40501
+ function updateToPutBatchesArith(stmt, records, fieldTypes = /* @__PURE__ */ new Map(), evaluationContext = {}) {
40502
40502
  const updateRecords = records.map((raw) => {
40503
40503
  const id = Number(raw["$id"].value);
40504
40504
  const row = kintoneRecordToProcessRow(raw);
40505
40505
  const record2 = {};
40506
40506
  for (const { field, value } of stmt.assignments) {
40507
40507
  record2[field] = {
40508
- value: evaluateUpdateAssignmentValue(value, row, fieldTypes.get(field), raw)
40508
+ value: evaluateUpdateAssignmentValue(value, row, fieldTypes.get(field), raw, evaluationContext)
40509
40509
  };
40510
40510
  }
40511
40511
  return { id, record: record2 };
@@ -40515,25 +40515,31 @@ function updateToPutBatchesArith(stmt, records, fieldTypes = /* @__PURE__ */ new
40515
40515
  records: batch
40516
40516
  }));
40517
40517
  }
40518
- function evaluateUpdateAssignmentValue(value, row, fieldType, raw) {
40518
+ function evaluateUpdateAssignmentValue(value, row, fieldType, raw, evaluationContext = {}) {
40519
40519
  if (value.type === "ARITH") {
40520
- return String(raw ? evalArith(value, raw) : evalArithExpr(value, row));
40520
+ return String(raw ? evalArith(value, raw) : evalArithExpr(value, row, evaluationContext));
40521
40521
  }
40522
40522
  if (value.type === "SCALAR_ARITH" || value.type === "CONCAT_OP") {
40523
- return String(evalScalarValueExpr(value, row));
40523
+ return String(evalScalarValueExpr(value, row, void 0, void 0, evaluationContext));
40524
40524
  }
40525
- if (value.type === "STRING_FUNC") return evalStringFunc(value, row);
40526
- if (value.type === "CASE_VALUE") return evalCaseWhenValue(value.expr, row, fieldType);
40525
+ if (value.type === "STRING_FUNC") return evalStringFunc(value, row, void 0, void 0, evaluationContext);
40526
+ if (value.type === "CASE_VALUE") return evalCaseWhenValue(value.expr, row, fieldType, evaluationContext);
40527
40527
  if (value.type === "SOURCE_FIELD") {
40528
40528
  throw new DmlConvertError("SOURCE_FIELD \u306F UPDATE ... FROM \u5C02\u7528\u3067\u3059");
40529
40529
  }
40530
40530
  return toKintoneValue(value, fieldType);
40531
40531
  }
40532
- function evaluateSubtableAssignmentValue(value, row, resolveFieldType) {
40532
+ function evaluateSubtableAssignmentValue(value, row, resolveFieldType, evaluationContext = {}) {
40533
40533
  if (value.type === "STRING") return value.value;
40534
40534
  if (value.type === "NUMBER") return numberLiteralText(value);
40535
- if (value.type === "ARITH") return String(evalArithExpr(value, row));
40536
- if (value.type === "CASE_VALUE") return evalCaseWhen(value.expr, row, resolveFieldType);
40535
+ if (value.type === "ARITH") return String(evalArithExpr(value, row, evaluationContext));
40536
+ if (value.type === "CASE_VALUE") return evalCaseWhen(
40537
+ value.expr,
40538
+ row,
40539
+ resolveFieldType,
40540
+ void 0,
40541
+ evaluationContext
40542
+ );
40537
40543
  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`);
40538
40544
  }
40539
40545
  var UPDATE_FROM_UNSUPPORTED_TYPES = /* @__PURE__ */ new Set([
@@ -40544,7 +40550,7 @@ var UPDATE_FROM_UNSUPPORTED_TYPES = /* @__PURE__ */ new Set([
40544
40550
  "GROUP_SELECT",
40545
40551
  "FILE"
40546
40552
  ]);
40547
- function updateFromToPutBatches(stmt, matched, fieldTypes = /* @__PURE__ */ new Map()) {
40553
+ function updateFromToPutBatches(stmt, matched, fieldTypes = /* @__PURE__ */ new Map(), evaluationContext = {}) {
40548
40554
  const updateRecords = matched.map(({ target, source }) => {
40549
40555
  const id = Number(target["$id"]?.value);
40550
40556
  if (!Number.isSafeInteger(id) || id <= 0) {
@@ -40574,9 +40580,20 @@ function updateFromToPutBatches(stmt, matched, fieldTypes = /* @__PURE__ */ new
40574
40580
  } else if (value.type === "ARITH") {
40575
40581
  record2[field] = { value: String(evalArith(value, target)) };
40576
40582
  } else if (value.type === "SCALAR_ARITH" || value.type === "CONCAT_OP") {
40577
- record2[field] = { value: String(evalScalarValueExpr(value, targetRow)) };
40583
+ record2[field] = { value: String(evalScalarValueExpr(
40584
+ value,
40585
+ targetRow,
40586
+ void 0,
40587
+ void 0,
40588
+ evaluationContext
40589
+ )) };
40578
40590
  } else if (value.type === "CASE_VALUE") {
40579
- record2[field] = { value: evalCaseWhenValue(value.expr, targetRow, fieldType) };
40591
+ record2[field] = { value: evalCaseWhenValue(
40592
+ value.expr,
40593
+ targetRow,
40594
+ fieldType,
40595
+ evaluationContext
40596
+ ) };
40580
40597
  } else {
40581
40598
  record2[field] = { value: toKintoneValue(value, fieldType) };
40582
40599
  }
@@ -40678,7 +40695,7 @@ function convertArray(elements, fieldType) {
40678
40695
  if (isUserType(fieldType)) return elements.map((c) => ({ code: c }));
40679
40696
  return elements;
40680
40697
  }
40681
- function evalCaseResultValue(result, row, fieldType) {
40698
+ function evalCaseResultValue(result, row, fieldType, evaluationContext) {
40682
40699
  if (result.type === "ARRAY") {
40683
40700
  return convertArray(result.elements.map((e) => e.value), fieldType);
40684
40701
  }
@@ -40689,26 +40706,26 @@ function evalCaseResultValue(result, row, fieldType) {
40689
40706
  return convertString2(result.value, fieldType);
40690
40707
  }
40691
40708
  if (result.type === "STRING_FUNC") {
40692
- return evalStringFunc(result, row);
40709
+ return evalStringFunc(result, row, void 0, void 0, evaluationContext);
40693
40710
  }
40694
40711
  if (result.type === "FIELD_REF" || result.type === "ARITH") {
40695
- return String(evalArithExpr(result, row));
40712
+ return String(evalArithExpr(result, row, evaluationContext));
40696
40713
  }
40697
- return String(evalScalarValueExpr(result, row));
40714
+ return String(evalScalarValueExpr(result, row, void 0, void 0, evaluationContext));
40698
40715
  }
40699
40716
  function collectUpdateCheckTargetFields(stmt) {
40700
40717
  if (!stmt.checkGroups) return [];
40701
40718
  const targetAlias = `app${stmt.appId}`.toLowerCase();
40702
40719
  return [...new Set(collectCheckFieldRefs(stmt.checkGroups).filter((ref) => ref.tableAlias === null || ref.tableAlias.toLowerCase() === targetAlias).map((ref) => ref.field).filter((field) => field !== "$id"))];
40703
40720
  }
40704
- function evalCaseWhenValue(expr, row, fieldType) {
40721
+ function evalCaseWhenValue(expr, row, fieldType, evaluationContext = {}) {
40705
40722
  for (const branch of expr.branches) {
40706
- if (evalWhere(branch.condition, row)) {
40707
- return evalCaseResultValue(branch.result, row, fieldType);
40723
+ if (evalWhere(branch.condition, row, void 0, void 0, void 0, evaluationContext)) {
40724
+ return evalCaseResultValue(branch.result, row, fieldType, evaluationContext);
40708
40725
  }
40709
40726
  }
40710
40727
  if (expr.elseResult !== null) {
40711
- return evalCaseResultValue(expr.elseResult, row, fieldType);
40728
+ return evalCaseResultValue(expr.elseResult, row, fieldType, evaluationContext);
40712
40729
  }
40713
40730
  return "";
40714
40731
  }
@@ -40987,18 +41004,30 @@ function buildApplyPatchPlan(input) {
40987
41004
  const parentId = requirePositiveInteger(snapshot["$id"]?.value, "APPLY snapshot $id");
40988
41005
  const expectedParentId = getApplyParentId(statement);
40989
41006
  if (parentId !== expectedParentId) argument2(`APPLY snapshot $id ${parentId} does not match requested $id ${expectedParentId}.`);
40990
- return buildApplyPatchPlanForSnapshot(statement, snapshot, metadata, parentId);
41007
+ return buildApplyPatchPlanForSnapshot(
41008
+ statement,
41009
+ snapshot,
41010
+ metadata,
41011
+ parentId,
41012
+ input.evaluationContext
41013
+ );
40991
41014
  }
40992
- function buildApplyPatchPlans(statement, snapshots, fieldInfos, metadata = resolveApplyPatchMetadata(statement, fieldInfos)) {
41015
+ function buildApplyPatchPlans(statement, snapshots, fieldInfos, metadata = resolveApplyPatchMetadata(statement, fieldInfos), evaluationContext = {}) {
40993
41016
  const parentIds = /* @__PURE__ */ new Set();
40994
41017
  return snapshots.map((snapshot) => {
40995
41018
  const parentId = requirePositiveInteger(snapshot["$id"]?.value, "APPLY snapshot $id");
40996
41019
  if (parentIds.has(parentId)) argument2(`APPLY snapshots contain duplicate parentId ${parentId}.`);
40997
41020
  parentIds.add(parentId);
40998
- return buildApplyPatchPlanForSnapshot(statement, snapshot, metadata, parentId);
41021
+ return buildApplyPatchPlanForSnapshot(
41022
+ statement,
41023
+ snapshot,
41024
+ metadata,
41025
+ parentId,
41026
+ evaluationContext
41027
+ );
40999
41028
  });
41000
41029
  }
41001
- function buildApplyPatchPlanForSnapshot(statement, snapshot, metadata, parentId) {
41030
+ function buildApplyPatchPlanForSnapshot(statement, snapshot, metadata, parentId, evaluationContext = {}) {
41002
41031
  const revision = requirePositiveInteger(snapshot["$revision"]?.value, "APPLY snapshot $revision");
41003
41032
  const tablePlans = [];
41004
41033
  const multiValuePlans = [];
@@ -41027,13 +41056,24 @@ function buildApplyPatchPlanForSnapshot(statement, snapshot, metadata, parentId)
41027
41056
  const hasRemove = block.operations.some((operation) => operation.kind === "REMOVE");
41028
41057
  for (const [operationIndex, operation] of block.operations.entries()) {
41029
41058
  if (operation.kind === "APPEND") {
41030
- const rows = buildApplyAppendRows(operation, targetChildren, block.field);
41059
+ const rows = buildApplyAppendRows(
41060
+ operation,
41061
+ targetChildren,
41062
+ block.field,
41063
+ evaluationContext
41064
+ );
41031
41065
  operationPlans.push({ kind: "APPEND", addedRows: rows.length });
41032
41066
  appended.push(...rows);
41033
41067
  continue;
41034
41068
  }
41035
41069
  if (operation.kind === "REMOVE") {
41036
- const indices2 = resolveRemoveTargets(operation, snapshotRows, childTypeResolver, block.field);
41070
+ const indices2 = resolveRemoveTargets(
41071
+ operation,
41072
+ snapshotRows,
41073
+ childTypeResolver,
41074
+ block.field,
41075
+ evaluationContext
41076
+ );
41037
41077
  if (operation.expectRows) {
41038
41078
  assertExpectRows(operation.expectRows, indices2.length, parentId, block.field, operationIndex, operation.kind);
41039
41079
  }
@@ -41051,7 +41091,13 @@ function buildApplyPatchPlanForSnapshot(statement, snapshot, metadata, parentId)
41051
41091
  continue;
41052
41092
  }
41053
41093
  if (operation.kind !== "PATCH") continue;
41054
- const indices = resolvePatchTargets(operation, snapshotRows, childTypeResolver, block.field);
41094
+ const indices = resolvePatchTargets(
41095
+ operation,
41096
+ snapshotRows,
41097
+ childTypeResolver,
41098
+ block.field,
41099
+ evaluationContext
41100
+ );
41055
41101
  if (operation.expectRows) {
41056
41102
  assertExpectRows(operation.expectRows, indices.length, parentId, block.field, operationIndex, operation.kind);
41057
41103
  }
@@ -41070,7 +41116,12 @@ function buildApplyPatchPlanForSnapshot(statement, snapshot, metadata, parentId)
41070
41116
  resolved.push({
41071
41117
  rowIndex,
41072
41118
  field: assignment.field,
41073
- value: evaluateSubtableAssignmentValue(assignment.value, flat, childTypeResolver)
41119
+ value: evaluateSubtableAssignmentValue(
41120
+ assignment.value,
41121
+ flat,
41122
+ childTypeResolver,
41123
+ evaluationContext
41124
+ )
41074
41125
  });
41075
41126
  }
41076
41127
  }
@@ -41122,7 +41173,13 @@ function buildApplyPatchPlanForSnapshot(statement, snapshot, metadata, parentId)
41122
41173
  for (const assignment of statement.assignments) {
41123
41174
  const fieldType = metadata.fieldsByCode.get(assignment.field)?.fieldType;
41124
41175
  parentValues[assignment.field] = {
41125
- value: evaluateUpdateAssignmentValue(assignment.value, parentRow, fieldType, snapshot)
41176
+ value: evaluateUpdateAssignmentValue(
41177
+ assignment.value,
41178
+ parentRow,
41179
+ fieldType,
41180
+ snapshot,
41181
+ evaluationContext
41182
+ )
41126
41183
  };
41127
41184
  }
41128
41185
  const postImage = { ...snapshot };
@@ -41192,12 +41249,12 @@ function normalizeApplyPatchPlan(plan, normalizedRecord) {
41192
41249
  postImage: normalizedRecord
41193
41250
  };
41194
41251
  }
41195
- function buildApplyAppendRows(operation, children, table) {
41252
+ function buildApplyAppendRows(operation, children, table, evaluationContext = {}) {
41196
41253
  return operation.values.map((row) => ({
41197
- value: buildAppendValue(operation, row, children, table)
41254
+ value: buildAppendValue(operation, row, children, table, evaluationContext)
41198
41255
  }));
41199
41256
  }
41200
- function buildAppendValue(operation, row, children, table) {
41257
+ function buildAppendValue(operation, row, children, table, evaluationContext) {
41201
41258
  if (row.length !== operation.fields.length) {
41202
41259
  return argument2(`APPLY APPEND for ${table} has ${row.length} values for ${operation.fields.length} fields.`);
41203
41260
  }
@@ -41206,7 +41263,7 @@ function buildAppendValue(operation, row, children, table) {
41206
41263
  for (const field of children.values()) {
41207
41264
  if (field.fieldType === "FILE" || field.writable === false) continue;
41208
41265
  const sqlValue = specified.get(field.code);
41209
- value[field.code] = { value: sqlValue === void 0 ? appendDefaultValue(field) : sqlValue.type === "CASE_VALUE" ? evalCaseWhenValue(sqlValue.expr, {}, field.fieldType) : toKintoneValue(sqlValue, field.fieldType) };
41266
+ value[field.code] = { value: sqlValue === void 0 ? appendDefaultValue(field) : sqlValue.type === "CASE_VALUE" ? evalCaseWhenValue(sqlValue.expr, {}, field.fieldType, evaluationContext) : toKintoneValue(sqlValue, field.fieldType) };
41210
41267
  }
41211
41268
  return value;
41212
41269
  }
@@ -41214,17 +41271,36 @@ function appendDefaultValue(field) {
41214
41271
  if (field.defaultValue !== void 0 && field.defaultValue !== null) return field.defaultValue;
41215
41272
  return ["CHECK_BOX", "MULTI_SELECT", "USER_SELECT", "ORGANIZATION_SELECT", "GROUP_SELECT"].includes(field.fieldType) ? [] : "";
41216
41273
  }
41217
- function resolvePatchTargets(operation, rows, resolveFieldType, table) {
41218
- return resolveSelectorTargets(operation.selector, rows, resolveFieldType, table);
41274
+ function resolvePatchTargets(operation, rows, resolveFieldType, table, evaluationContext = {}) {
41275
+ return resolveSelectorTargets(
41276
+ operation.selector,
41277
+ rows,
41278
+ resolveFieldType,
41279
+ table,
41280
+ evaluationContext
41281
+ );
41219
41282
  }
41220
- function resolveRemoveTargets(operation, rows, resolveFieldType, table) {
41221
- return resolveSelectorTargets(operation.selector, rows, resolveFieldType, table);
41283
+ function resolveRemoveTargets(operation, rows, resolveFieldType, table, evaluationContext = {}) {
41284
+ return resolveSelectorTargets(
41285
+ operation.selector,
41286
+ rows,
41287
+ resolveFieldType,
41288
+ table,
41289
+ evaluationContext
41290
+ );
41222
41291
  }
41223
- function resolveSelectorTargets(selector, rows, resolveFieldType, table) {
41292
+ function resolveSelectorTargets(selector, rows, resolveFieldType, table, evaluationContext = {}) {
41224
41293
  if (selector.kind === "ALL_ROWS") return rows.map((_, index) => index);
41225
41294
  const where = selector.where;
41226
41295
  const indices = rows.flatMap(
41227
- (row, index) => evalWhere(where, flattenSubtableSnapshotRow(row, index), resolveFieldType) ? [index] : []
41296
+ (row, index) => evalWhere(
41297
+ where,
41298
+ flattenSubtableSnapshotRow(row, index),
41299
+ resolveFieldType,
41300
+ void 0,
41301
+ void 0,
41302
+ evaluationContext
41303
+ ) ? [index] : []
41228
41304
  );
41229
41305
  const requestedRid = exactRidSelectorValue(where);
41230
41306
  if (requestedRid !== null && indices.length === 0) {
@@ -44557,9 +44633,16 @@ function assertJoinKeyAvailable(rows, key, savedColumns) {
44557
44633
  throw new Error(`ArgumentError: JOIN key ${key} is not available in the materialized table.`);
44558
44634
  }
44559
44635
  }
44560
- function applyFilter(rows, where, resolveFieldType, appliedKlikes, resolveFieldSemantics2) {
44636
+ function applyFilter(rows, where, resolveFieldType, appliedKlikes, resolveFieldSemantics2, evaluationContext = {}) {
44561
44637
  if (where === null) return rows;
44562
- return rows.filter((row) => evalWhere(where, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2));
44638
+ return rows.filter((row) => evalWhere(
44639
+ where,
44640
+ row,
44641
+ resolveFieldType,
44642
+ appliedKlikes,
44643
+ resolveFieldSemantics2,
44644
+ evaluationContext
44645
+ ));
44563
44646
  }
44564
44647
  function hasAggregateColumns(columns) {
44565
44648
  return columns.some(
@@ -44593,12 +44676,28 @@ function applyGroupBy(rows, groupByKeys, columns, resolveAggSortKind, resolution
44593
44676
  const outRow = asProcessingRow({ ...groupRows[0] });
44594
44677
  for (const k of groupByKeys) {
44595
44678
  if (k.type === "ARITH_KEY") {
44596
- outRow[arithColDefaultKey(k.expr)] = String(evalArithExpr(k.expr, groupRows[0]));
44679
+ outRow[arithColDefaultKey(k.expr)] = String(evalArithExpr(
44680
+ k.expr,
44681
+ groupRows[0],
44682
+ aliasEvaluationContext.evaluationContext
44683
+ ));
44597
44684
  } else if (k.type === "FUNC_KEY") {
44598
- outRow[stringFuncDefaultKey(k.expr)] = evalStringFunc(k.expr, groupRows[0]);
44685
+ outRow[stringFuncDefaultKey(k.expr)] = evalStringFunc(
44686
+ k.expr,
44687
+ groupRows[0],
44688
+ void 0,
44689
+ void 0,
44690
+ aliasEvaluationContext.evaluationContext
44691
+ );
44599
44692
  }
44600
44693
  }
44601
- materializeAggregateColumns(outRow, groupRows, columns, resolveAggSortKind);
44694
+ materializeAggregateColumns(
44695
+ outRow,
44696
+ groupRows,
44697
+ columns,
44698
+ resolveAggSortKind,
44699
+ aliasEvaluationContext.evaluationContext
44700
+ );
44602
44701
  result.push(outRow);
44603
44702
  }
44604
44703
  return result;
@@ -44656,7 +44755,13 @@ function applyGroupingSets(rows, spec, columns, resolveAggSortKind, limits = {})
44656
44755
  outRow[item.unqualifiedBridgeKey] = value;
44657
44756
  }
44658
44757
  }
44659
- materializeAggregateColumns(outRow, groupRows, columns, resolveAggSortKind);
44758
+ materializeAggregateColumns(
44759
+ outRow,
44760
+ groupRows,
44761
+ columns,
44762
+ resolveAggSortKind,
44763
+ limits.evaluationContext
44764
+ );
44660
44765
  attachGroupingRowMeta(outRow, includedCanonicalIds);
44661
44766
  result.push(outRow);
44662
44767
  }
@@ -44667,11 +44772,19 @@ function groupingItemValue(item, row) {
44667
44772
  if (!row) return "";
44668
44773
  return row[item.directKey] ?? (item.unqualifiedBridgeKey === null ? void 0 : row[item.unqualifiedBridgeKey]) ?? "";
44669
44774
  }
44670
- function materializeAggregateColumns(outRow, groupRows, columns, resolveAggSortKind) {
44775
+ function materializeAggregateColumns(outRow, groupRows, columns, resolveAggSortKind, evaluationContext = {}) {
44671
44776
  for (const [columnIndex, col] of columns.entries()) {
44672
44777
  if (col.type === "AGGREGATE") {
44673
44778
  const syntheticKey = aggregateSyntheticName(col.func, col.distinct, col.arg);
44674
- const value = String(evalAggregate(col.func, col.distinct, col.arg, col.separator, groupRows, resolveAggSortKind));
44779
+ const value = String(evalAggregate(
44780
+ col.func,
44781
+ col.distinct,
44782
+ col.arg,
44783
+ col.separator,
44784
+ groupRows,
44785
+ resolveAggSortKind,
44786
+ evaluationContext
44787
+ ));
44675
44788
  setMaterializedSelectValue(
44676
44789
  outRow,
44677
44790
  columnIndex,
@@ -44679,38 +44792,44 @@ function materializeAggregateColumns(outRow, groupRows, columns, resolveAggSortK
44679
44792
  col.alias ? [col.alias, syntheticKey] : [syntheticKey]
44680
44793
  );
44681
44794
  } else if (col.type === "ARITH_AGG_COL") {
44682
- materializeAggregateDependencies(outRow, groupRows, col.expr, resolveAggSortKind);
44795
+ materializeAggregateDependencies(outRow, groupRows, col.expr, resolveAggSortKind, evaluationContext);
44683
44796
  const outputKey = col.alias ?? aggArithDefaultKey(col.expr);
44684
44797
  setMaterializedSelectValue(
44685
44798
  outRow,
44686
44799
  columnIndex,
44687
- String(evalAggArithExpr(col.expr, groupRows, resolveAggSortKind)),
44800
+ String(evalAggArithExpr(col.expr, groupRows, resolveAggSortKind, evaluationContext)),
44688
44801
  [outputKey]
44689
44802
  );
44690
44803
  } else if (col.type === "STRFUNC_COL" && hasAggregateInStringFuncExpr2(col.expr)) {
44691
- materializeAggregateDependencies(outRow, groupRows, col.expr, resolveAggSortKind);
44804
+ materializeAggregateDependencies(outRow, groupRows, col.expr, resolveAggSortKind, evaluationContext);
44692
44805
  const outputKey = col.alias ?? stringFuncDefaultKey(col.expr);
44693
44806
  const resolvedExpr = resolveAggInStringFuncExpr(col.expr, groupRows, resolveAggSortKind);
44694
- setMaterializedSelectValue(outRow, columnIndex, evalStringFunc(resolvedExpr, outRow), [outputKey]);
44807
+ setMaterializedSelectValue(
44808
+ outRow,
44809
+ columnIndex,
44810
+ evalStringFunc(resolvedExpr, outRow, void 0, void 0, evaluationContext),
44811
+ [outputKey]
44812
+ );
44695
44813
  } else if (col.type === "SCALAR_VALUE_COL" && scalarValueHasAggregate2(col.expr)) {
44696
- materializeAggregateDependencies(outRow, groupRows, col.expr, resolveAggSortKind);
44814
+ materializeAggregateDependencies(outRow, groupRows, col.expr, resolveAggSortKind, evaluationContext);
44697
44815
  const outputKey = col.alias ?? scalarValueDefaultKey(col.expr);
44698
44816
  const resolvedExpr = resolveAggInScalarValue(col.expr, groupRows, resolveAggSortKind);
44699
44817
  setMaterializedSelectValue(
44700
44818
  outRow,
44701
44819
  columnIndex,
44702
- String(evalScalarValueExpr(resolvedExpr, outRow)),
44820
+ String(evalScalarValueExpr(resolvedExpr, outRow, void 0, void 0, evaluationContext)),
44703
44821
  [outputKey]
44704
44822
  );
44705
44823
  } else if (col.type === "CASE_COL" && containsAggregate2(col.expr)) {
44706
- materializeAggregateDependencies(outRow, groupRows, col.expr, resolveAggSortKind);
44824
+ materializeAggregateDependencies(outRow, groupRows, col.expr, resolveAggSortKind, evaluationContext);
44707
44825
  const resolvedExpr = resolveAggInCaseExpr(col.expr, groupRows, resolveAggSortKind);
44708
44826
  const resolveAggregateSemantics = (field) => field.aggregateRef ? aggregateResultSemantics(field.aggregateRef, resolveAggSortKind) : void 0;
44709
44827
  const value = evalCaseWhen(
44710
44828
  resolvedExpr,
44711
44829
  outRow,
44712
44830
  void 0,
44713
- resolveAggregateSemantics
44831
+ resolveAggregateSemantics,
44832
+ evaluationContext
44714
44833
  );
44715
44834
  setMaterializedSelectValue(
44716
44835
  outRow,
@@ -44738,7 +44857,7 @@ function collectAggregateRefs(node, out) {
44738
44857
  if (value["type"] === "SELECT" || value["type"] === "SCALAR_SUBQUERY") return;
44739
44858
  Object.values(value).forEach((child) => collectAggregateRefs(child, out));
44740
44859
  }
44741
- function materializeAggregateDependencies(outRow, rows, node, resolveAggSortKind) {
44860
+ function materializeAggregateDependencies(outRow, rows, node, resolveAggSortKind, evaluationContext = {}) {
44742
44861
  const refs = [];
44743
44862
  collectAggregateRefs(node, refs);
44744
44863
  for (const ref of refs) {
@@ -44750,7 +44869,8 @@ function materializeAggregateDependencies(outRow, rows, node, resolveAggSortKind
44750
44869
  ref.arg,
44751
44870
  ref.separator,
44752
44871
  rows,
44753
- resolveAggSortKind
44872
+ resolveAggSortKind,
44873
+ evaluationContext
44754
44874
  ));
44755
44875
  materializedValuesFor(outRow).byLookupKey.set(key, value);
44756
44876
  }
@@ -44781,14 +44901,20 @@ function evalGroupByKey(key, row, resolution, columns, aliasEvaluationContext) {
44781
44901
  `InternalError: unresolved plain GROUP BY item ${resolution.kind} reached evaluation.`
44782
44902
  );
44783
44903
  }
44784
- if (key.type === "FUNC_KEY") return evalStringFunc(key.expr, row);
44785
- return String(evalArithExpr(key.expr, row));
44904
+ if (key.type === "FUNC_KEY") return evalStringFunc(
44905
+ key.expr,
44906
+ row,
44907
+ void 0,
44908
+ void 0,
44909
+ aliasEvaluationContext.evaluationContext
44910
+ );
44911
+ return String(evalArithExpr(key.expr, row, aliasEvaluationContext.evaluationContext));
44786
44912
  }
44787
- function evalAggregate(func, distinct, arg, separator, rows, resolveAggSortKind) {
44913
+ function evalAggregate(func, distinct, arg, separator, rows, resolveAggSortKind, evaluationContext = {}) {
44788
44914
  if (arg.type === "WILDCARD") {
44789
44915
  return func === "COUNT" ? rows.length : 0;
44790
44916
  }
44791
- const strValues = aggregateRowValues(func, arg, rows).filter((value) => value !== null);
44917
+ const strValues = aggregateRowValues(func, arg, rows, evaluationContext).filter((value) => value !== null);
44792
44918
  const statistical = func === "STDDEV_POP" || func === "STDDEV_SAMP" || func === "VAR_POP" || func === "VAR_SAMP" || func === "MEDIAN";
44793
44919
  const numericValues = statistical ? strValues.map((value) => {
44794
44920
  const numeric = Number(value);
@@ -44866,7 +44992,7 @@ function evalAggregate(func, distinct, arg, separator, rows, resolveAggSortKind)
44866
44992
  }
44867
44993
  }
44868
44994
  }
44869
- function aggregateRowValues(func, arg, rows) {
44995
+ function aggregateRowValues(func, arg, rows, evaluationContext = {}) {
44870
44996
  return rows.map((processingRow) => {
44871
44997
  const row = sourceRowForEvaluation(processingRow);
44872
44998
  let strVal;
@@ -44875,11 +45001,11 @@ function aggregateRowValues(func, arg, rows) {
44875
45001
  if (raw === void 0 || raw === "" && func !== "MIN" && func !== "MAX") return null;
44876
45002
  strVal = raw;
44877
45003
  } else if (arg.type === "ARITH" || arg.type === "NUMBER") {
44878
- const n = evalArithExpr(arg, row);
45004
+ const n = evalArithExpr(arg, row, evaluationContext);
44879
45005
  if (isNaN(n)) return null;
44880
45006
  strVal = String(n);
44881
45007
  } else {
44882
- const value = evalScalarValueExprNullable(arg, row);
45008
+ const value = evalScalarValueExprNullable(arg, row, void 0, void 0, evaluationContext);
44883
45009
  if (value === null) return null;
44884
45010
  if (value === "" && func !== "MIN" && func !== "MAX") return null;
44885
45011
  if (typeof value === "number" && Number.isNaN(value)) return null;
@@ -44892,9 +45018,17 @@ function toAggregateFieldRef(field) {
44892
45018
  const dot = field.indexOf(".");
44893
45019
  return dot > 0 ? { type: "FIELD", tableAlias: field.slice(0, dot), field: field.slice(dot + 1) } : { type: "FIELD", tableAlias: null, field };
44894
45020
  }
44895
- function evalAggArithExpr(node, rows, resolveAggSortKind) {
45021
+ function evalAggArithExpr(node, rows, resolveAggSortKind, evaluationContext = {}) {
44896
45022
  if (node.type === "NUMBER") return node.value;
44897
- if (node.type === "AGG_REF") return Number(evalAggregate(node.func, node.distinct, node.arg, node.separator, rows, resolveAggSortKind));
45023
+ if (node.type === "AGG_REF") return Number(evalAggregate(
45024
+ node.func,
45025
+ node.distinct,
45026
+ node.arg,
45027
+ node.separator,
45028
+ rows,
45029
+ resolveAggSortKind,
45030
+ evaluationContext
45031
+ ));
44898
45032
  if (node.type === "AGG_GROUP_KEY") {
44899
45033
  const field = node.tableAlias ? `${node.tableAlias}.${node.field}` : node.field;
44900
45034
  return Number(resolveFieldRef(rows[0] ?? {}, field));
@@ -44902,8 +45036,8 @@ function evalAggArithExpr(node, rows, resolveAggSortKind) {
44902
45036
  if (node.type === "VARIABLE") {
44903
45037
  throw new Error(`InternalError: unresolved aggregate arithmetic variable @${node.name}.`);
44904
45038
  }
44905
- const l = evalAggArithExpr(node.left, rows, resolveAggSortKind);
44906
- const r = evalAggArithExpr(node.right, rows, resolveAggSortKind);
45039
+ const l = evalAggArithExpr(node.left, rows, resolveAggSortKind, evaluationContext);
45040
+ const r = evalAggArithExpr(node.right, rows, resolveAggSortKind, evaluationContext);
44907
45041
  switch (node.op) {
44908
45042
  case "+":
44909
45043
  return l + r;
@@ -44947,22 +45081,24 @@ function aggregateResultSemantics(ref, resolver) {
44947
45081
  const semantics = ref.arg.type === "WILDCARD" ? "string" : resolveAggregateArgSemantics(ref.arg, resolver) ?? "string";
44948
45082
  return typeof semantics === "string" ? syntheticSemantics(semantics) : semantics;
44949
45083
  }
44950
- function applyHaving(rows, having, resolveFieldType, resolveFieldSemantics2) {
45084
+ function applyHaving(rows, having, resolveFieldType, resolveFieldSemantics2, evaluationContext = {}) {
44951
45085
  if (having === null) return rows;
44952
45086
  return rows.filter((row) => evalWhere(
44953
45087
  having,
44954
45088
  havingEvaluationRow(row),
44955
45089
  resolveFieldType,
44956
45090
  void 0,
44957
- resolveFieldSemantics2
45091
+ resolveFieldSemantics2,
45092
+ evaluationContext
44958
45093
  ));
44959
45094
  }
44960
- function applyDistinct(rows, columns, scalarCache, resolveFieldType, resolveFieldSemantics2) {
45095
+ function applyDistinct(rows, columns, scalarCache, resolveFieldType, resolveFieldSemantics2, evaluationContext = {}) {
44961
45096
  if (rows.length === 0) return rows;
44962
45097
  const keyFor = buildDistinctKeyBuilder(rows, columns, {
44963
45098
  scalarCache,
44964
45099
  resolveFieldType,
44965
- resolveFieldSemantics: resolveFieldSemantics2
45100
+ resolveFieldSemantics: resolveFieldSemantics2,
45101
+ evaluationContext
44966
45102
  });
44967
45103
  const seen = /* @__PURE__ */ new Set();
44968
45104
  return rows.filter((row) => {
@@ -44998,11 +45134,19 @@ function buildDistinctKeyBuilder(rows, columns, context) {
44998
45134
  };
44999
45135
  return (row) => JSON.stringify(buildDistinctTuple(columns, row, distinctContext));
45000
45136
  }
45001
- function applyOrderBy(rows, orderBy, optionOrders, sortKinds, fieldSemantics2, aliasEvaluator) {
45137
+ function applyOrderBy(rows, orderBy, optionOrders, sortKinds, fieldSemantics2, aliasEvaluator, evaluationContext = {}) {
45002
45138
  if (orderBy.length === 0) return rows;
45003
- return sortDecoratedRows(rows, orderBy, optionOrders, sortKinds, fieldSemantics2, aliasEvaluator).rows.map((item) => item.row);
45139
+ return sortDecoratedRows(
45140
+ rows,
45141
+ orderBy,
45142
+ optionOrders,
45143
+ sortKinds,
45144
+ fieldSemantics2,
45145
+ aliasEvaluator,
45146
+ evaluationContext
45147
+ ).rows.map((item) => item.row);
45004
45148
  }
45005
- function sortDecoratedRows(rows, orderBy, optionOrders, sortKinds, fieldSemantics2, aliasEvaluator) {
45149
+ function sortDecoratedRows(rows, orderBy, optionOrders, sortKinds, fieldSemantics2, aliasEvaluator, evaluationContext = {}) {
45006
45150
  const keyMeta = orderBy.map(({ key }) => {
45007
45151
  if (key.type === "ARITH_KEY") return { semantics: syntheticSemantics("number") };
45008
45152
  if (key.type === "FUNC_KEY") {
@@ -45028,7 +45172,7 @@ function sortDecoratedRows(rows, orderBy, optionOrders, sortKinds, fieldSemantic
45028
45172
  const decorated = rows.map((row) => ({
45029
45173
  row,
45030
45174
  keys: orderBy.map(({ key }, i) => {
45031
- const s = evalOrderKey(key, row, aliasEvaluator);
45175
+ const s = evalOrderKey(key, row, aliasEvaluator, evaluationContext);
45032
45176
  return { s };
45033
45177
  })
45034
45178
  }));
@@ -45066,20 +45210,20 @@ var NUMERIC_ORDER_FUNCTIONS = /* @__PURE__ */ new Set([
45066
45210
  "QUARTER",
45067
45211
  "WEEK"
45068
45212
  ]);
45069
- function evalOrderKey(key, row, aliasEvaluator) {
45213
+ function evalOrderKey(key, row, aliasEvaluator, evaluationContext = {}) {
45070
45214
  const sourceRow = sourceRowForEvaluation(row);
45071
45215
  switch (key.type) {
45072
45216
  case "FIELD_NAME":
45073
45217
  return aliasEvaluator?.(key.name, row) ?? getMaterializedLookupValue(row, key.name) ?? sourceRow[key.name] ?? "";
45074
45218
  case "ARITH_KEY":
45075
- return String(evalArithExpr(key.expr, sourceRow));
45219
+ return String(evalArithExpr(key.expr, sourceRow, evaluationContext));
45076
45220
  case "FUNC_KEY":
45077
- return evalStringFunc(key.expr, sourceRow);
45221
+ return evalStringFunc(key.expr, sourceRow, void 0, void 0, evaluationContext);
45078
45222
  case "GROUPING_KEY":
45079
45223
  return evalGroupingRef(key.ref, row);
45080
45224
  }
45081
45225
  }
45082
- function buildOrderByAliasEvaluator(columns, scalarCache, resolveFieldType, resolveFieldSemantics2) {
45226
+ function buildOrderByAliasEvaluator(columns, scalarCache, resolveFieldType, resolveFieldSemantics2, evaluationContext = {}) {
45083
45227
  const evaluators = /* @__PURE__ */ new Map();
45084
45228
  for (const [columnIndex, column] of columns.entries()) {
45085
45229
  if (!("alias" in column) || column.alias === null) continue;
@@ -45103,15 +45247,37 @@ function buildOrderByAliasEvaluator(columns, scalarCache, resolveFieldType, reso
45103
45247
  evaluators.set(alias, (row) => getMaterializedSelectValue(row, columnIndex) ?? "");
45104
45248
  break;
45105
45249
  case "ARITH_COL":
45106
- evaluators.set(alias, (row) => String(evalArithExpr(column.expr, sourceRowForEvaluation(row))));
45250
+ evaluators.set(alias, (row) => String(evalArithExpr(
45251
+ column.expr,
45252
+ sourceRowForEvaluation(row),
45253
+ evaluationContext
45254
+ )));
45107
45255
  break;
45108
45256
  case "STRFUNC_COL": {
45109
45257
  const source = stringFuncDefaultKey(column.expr);
45110
- 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));
45258
+ evaluators.set(alias, (row) => hasAggregateInStringFuncExpr2(column.expr) ? getMaterializedSelectValue(row, columnIndex) ?? getMaterializedLookupValue(row, source) ?? evalStringFunc(
45259
+ column.expr,
45260
+ sourceRowForEvaluation(row),
45261
+ resolveFieldType,
45262
+ resolveFieldSemantics2,
45263
+ evaluationContext
45264
+ ) : evalStringFunc(
45265
+ column.expr,
45266
+ sourceRowForEvaluation(row),
45267
+ resolveFieldType,
45268
+ resolveFieldSemantics2,
45269
+ evaluationContext
45270
+ ));
45111
45271
  break;
45112
45272
  }
45113
45273
  case "CASE_COL":
45114
- evaluators.set(alias, (row) => containsAggregate2(column.expr) ? getMaterializedSelectValue(row, columnIndex) ?? "" : evalCaseWhen(column.expr, sourceRowForEvaluation(row), resolveFieldType, resolveFieldSemantics2));
45274
+ evaluators.set(alias, (row) => containsAggregate2(column.expr) ? getMaterializedSelectValue(row, columnIndex) ?? "" : evalCaseWhen(
45275
+ column.expr,
45276
+ sourceRowForEvaluation(row),
45277
+ resolveFieldType,
45278
+ resolveFieldSemantics2,
45279
+ evaluationContext
45280
+ ));
45115
45281
  break;
45116
45282
  case "SCALAR_VALUE_COL": {
45117
45283
  const source = scalarValueDefaultKey(column.expr);
@@ -45119,7 +45285,8 @@ function buildOrderByAliasEvaluator(columns, scalarCache, resolveFieldType, reso
45119
45285
  column.expr,
45120
45286
  sourceRowForEvaluation(row),
45121
45287
  resolveFieldType,
45122
- resolveFieldSemantics2
45288
+ resolveFieldSemantics2,
45289
+ evaluationContext
45123
45290
  )));
45124
45291
  break;
45125
45292
  }
@@ -45135,7 +45302,7 @@ function buildOrderByAliasEvaluator(columns, scalarCache, resolveFieldType, reso
45135
45302
  }
45136
45303
  return (name, row) => evaluators.get(name)?.(row);
45137
45304
  }
45138
- function applyWindow(rows, columns, optionOrders, sortKinds, fieldSemantics2, resolveAggSortKind) {
45305
+ function applyWindow(rows, columns, optionOrders, sortKinds, fieldSemantics2, resolveAggSortKind, evaluationContext = {}) {
45139
45306
  const windows = columns.map((column, columnIndex) => ({ column, columnIndex })).filter((item) => item.column.type === "WINDOW_COL");
45140
45307
  if (rows.length === 0 || windows.length === 0) return rows;
45141
45308
  for (let index = 0; index < rows.length; index++) rows[index] = asProcessingRow(rows[index]);
@@ -45148,14 +45315,28 @@ function applyWindow(rows, columns, optionOrders, sortKinds, fieldSemantics2, re
45148
45315
  else partitions.set(key, [row]);
45149
45316
  }
45150
45317
  for (const partition of partitions.values()) {
45151
- const sortedResult = sortDecoratedRows(partition, window.orderBy, optionOrders, sortKinds, fieldSemantics2);
45318
+ const sortedResult = sortDecoratedRows(
45319
+ partition,
45320
+ window.orderBy,
45321
+ optionOrders,
45322
+ sortKinds,
45323
+ fieldSemantics2,
45324
+ void 0,
45325
+ evaluationContext
45326
+ );
45152
45327
  const sorted = sortedResult.rows;
45153
45328
  if (isAggregateWindow(window)) {
45154
- applyAggregateWindow(window, columnIndex, sortedResult, resolveAggSortKind);
45329
+ applyAggregateWindow(
45330
+ window,
45331
+ columnIndex,
45332
+ sortedResult,
45333
+ resolveAggSortKind,
45334
+ evaluationContext
45335
+ );
45155
45336
  continue;
45156
45337
  }
45157
45338
  if (isValueWindow(window)) {
45158
- applyValueWindow(window, columnIndex, sorted);
45339
+ applyValueWindow(window, columnIndex, sorted, evaluationContext);
45159
45340
  continue;
45160
45341
  }
45161
45342
  if (!isRankingWindow(window)) {
@@ -45175,14 +45356,24 @@ function applyWindow(rows, columns, optionOrders, sortKinds, fieldSemantics2, re
45175
45356
  }
45176
45357
  return rows;
45177
45358
  }
45178
- function evaluateValueWindowArg(arg, row) {
45179
- const value = evalScalarValueExprNullable(arg, sourceRowForEvaluation(row));
45359
+ function evaluateValueWindowArg(arg, row, evaluationContext = {}) {
45360
+ const value = evalScalarValueExprNullable(
45361
+ arg,
45362
+ sourceRowForEvaluation(row),
45363
+ void 0,
45364
+ void 0,
45365
+ evaluationContext
45366
+ );
45180
45367
  if (value === null || value === void 0) return "";
45181
45368
  if (typeof value === "number" && !Number.isFinite(value)) return "";
45182
45369
  return String(value);
45183
45370
  }
45184
- function applyValueWindow(window, columnIndex, sorted) {
45185
- const values = sorted.map((item) => evaluateValueWindowArg(window.arg, item.row));
45371
+ function applyValueWindow(window, columnIndex, sorted, evaluationContext = {}) {
45372
+ const values = sorted.map((item) => evaluateValueWindowArg(
45373
+ window.arg,
45374
+ item.row,
45375
+ evaluationContext
45376
+ ));
45186
45377
  const direction = window.valueFunc === "LAG" ? -1 : 1;
45187
45378
  for (let index = 0; index < sorted.length; index++) {
45188
45379
  const target = index + direction * window.offset;
@@ -45194,9 +45385,14 @@ function applyValueWindow(window, columnIndex, sorted) {
45194
45385
  );
45195
45386
  }
45196
45387
  }
45197
- function applyAggregateWindow(window, columnIndex, sortedResult, resolveAggSortKind) {
45388
+ function applyAggregateWindow(window, columnIndex, sortedResult, resolveAggSortKind, evaluationContext = {}) {
45198
45389
  const sorted = sortedResult.rows;
45199
- const values = window.arg.type === "WILDCARD" ? null : aggregateRowValues(window.aggFunc, window.arg, sorted.map((item) => item.row));
45390
+ const values = window.arg.type === "WILDCARD" ? null : aggregateRowValues(
45391
+ window.aggFunc,
45392
+ window.arg,
45393
+ sorted.map((item) => item.row),
45394
+ evaluationContext
45395
+ );
45200
45396
  const comparison = window.arg.type === "WILDCARD" ? void 0 : resolveAggregateArgSemantics(window.arg, resolveAggSortKind);
45201
45397
  const semantics = typeof comparison === "string" ? syntheticSemantics(comparison) : comparison ?? syntheticSemantics("string");
45202
45398
  const output = [];
@@ -45288,13 +45484,14 @@ function evaluateSelectColumnValue(column, row, columnIndex, context = {}) {
45288
45484
  return getMaterializedSelectValue(row, columnIndex) ?? getMaterializedLookupValue(row, source) ?? getLegacyMaterializedValue(row, source) ?? "0";
45289
45485
  }
45290
45486
  case "ARITH_COL":
45291
- return String(evalArithExpr(column.expr, sourceRow));
45487
+ return String(evalArithExpr(column.expr, sourceRow, context.evaluationContext));
45292
45488
  case "CASE_COL":
45293
45489
  return containsAggregate2(column.expr) ? getMaterializedSelectValue(row, columnIndex) ?? getMaterializedLookupValue(row, caseMaterializedKey(column.alias, columnIndex)) ?? getLegacyMaterializedValue(row, caseMaterializedKey(column.alias, columnIndex)) ?? "" : evalCaseWhen(
45294
45490
  column.expr,
45295
45491
  sourceRow,
45296
45492
  context.resolveFieldType,
45297
- context.resolveFieldSemantics
45493
+ context.resolveFieldSemantics,
45494
+ context.evaluationContext
45298
45495
  );
45299
45496
  case "GROUPING_COL":
45300
45497
  return evalGroupingRef(column.ref, row);
@@ -45304,12 +45501,14 @@ function evaluateSelectColumnValue(column, row, columnIndex, context = {}) {
45304
45501
  column.expr,
45305
45502
  sourceRow,
45306
45503
  context.resolveFieldType,
45307
- context.resolveFieldSemantics
45504
+ context.resolveFieldSemantics,
45505
+ context.evaluationContext
45308
45506
  ) : evalStringFunc(
45309
45507
  column.expr,
45310
45508
  sourceRow,
45311
45509
  context.resolveFieldType,
45312
- context.resolveFieldSemantics
45510
+ context.resolveFieldSemantics,
45511
+ context.evaluationContext
45313
45512
  );
45314
45513
  }
45315
45514
  case "SCALAR_VALUE_COL": {
@@ -45318,7 +45517,8 @@ function evaluateSelectColumnValue(column, row, columnIndex, context = {}) {
45318
45517
  column.expr,
45319
45518
  sourceRow,
45320
45519
  context.resolveFieldType,
45321
- context.resolveFieldSemantics
45520
+ context.resolveFieldSemantics,
45521
+ context.evaluationContext
45322
45522
  ));
45323
45523
  }
45324
45524
  case "SCALAR_SUBQUERY_COL":
@@ -45333,7 +45533,7 @@ function buildDistinctTuple(columns, row, context = {}) {
45333
45533
  return typeof value === "string" ? value : value.entries.map(([, entryValue]) => entryValue);
45334
45534
  });
45335
45535
  }
45336
- function project(rows, columns, scalarCache, resolveFieldType, sourceColumns2, resolveFieldSemantics2, hiddenQualifiedAliases) {
45536
+ function project(rows, columns, scalarCache, resolveFieldType, sourceColumns2, resolveFieldSemantics2, hiddenQualifiedAliases, evaluationContext = {}) {
45337
45537
  if (columns.length === 1 && columns[0].type === "WILDCARD") {
45338
45538
  const projected2 = rows.map((row) => {
45339
45539
  const visible = stripHiddenQualifiedColumns(
@@ -45366,10 +45566,11 @@ function project(rows, columns, scalarCache, resolveFieldType, sourceColumns2, r
45366
45566
  }
45367
45567
  const projected = rows.map((row, rowIdx) => {
45368
45568
  const out = {};
45369
- const evaluationContext = {
45569
+ const columnEvaluationContext = {
45370
45570
  scalarCache,
45371
45571
  resolveFieldType,
45372
45572
  resolveFieldSemantics: resolveFieldSemantics2,
45573
+ evaluationContext,
45373
45574
  wildcardKeys: Object.keys(stripHiddenQualifiedColumns(
45374
45575
  stripParentShortcutColumns(row),
45375
45576
  hiddenQualifiedAliases
@@ -45377,7 +45578,7 @@ function project(rows, columns, scalarCache, resolveFieldType, sourceColumns2, r
45377
45578
  parentWildcardKeys: Object.keys(row).filter((key) => key.startsWith("_p.")).sort()
45378
45579
  };
45379
45580
  for (const [colIdx, col] of columns.entries()) {
45380
- const value = evaluateSelectColumnValue(col, row, colIdx, evaluationContext);
45581
+ const value = evaluateSelectColumnValue(col, row, colIdx, columnEvaluationContext);
45381
45582
  switch (col.type) {
45382
45583
  case "VARIABLE_COL":
45383
45584
  break;
@@ -45769,7 +45970,8 @@ function runFullScan(input) {
45769
45970
  hiddenQualifiedAliases,
45770
45971
  resolvedGroupingSpec,
45771
45972
  plainGroupByPlan,
45772
- warnings
45973
+ warnings,
45974
+ evaluationContext
45773
45975
  } = input;
45774
45976
  const effectiveOrderSemantics = deriveOutputOrderSemantics(stmt.columns, aggregateSortKindResolver);
45775
45977
  for (const [key, value] of orderSemantics ?? []) effectiveOrderSemantics.set(key, value);
@@ -45798,7 +46000,14 @@ function runFullScan(input) {
45798
46000
  knownColumns = mergeKnownColumns(knownColumns, rightColumns, rows);
45799
46001
  }
45800
46002
  const filterWhere = input.residualWhere !== void 0 ? input.residualWhere : stmt.where;
45801
- rows = applyFilter(rows, filterWhere, fieldTypeResolver, appliedKlikes, fieldSemanticsResolver);
46003
+ rows = applyFilter(
46004
+ rows,
46005
+ filterWhere,
46006
+ fieldTypeResolver,
46007
+ appliedKlikes,
46008
+ fieldSemanticsResolver,
46009
+ evaluationContext
46010
+ );
45802
46011
  const grouping = normalizeGroupingSpec(stmt);
45803
46012
  if (grouping.type === "GROUPING_SETS") {
45804
46013
  if (!resolvedGroupingSpec) {
@@ -45809,7 +46018,7 @@ function runFullScan(input) {
45809
46018
  resolvedGroupingSpec,
45810
46019
  stmt.columns,
45811
46020
  aggregateSortKindResolver,
45812
- { maxGeneratedRows: B65_MAX_GENERATED_ROWS }
46021
+ { maxGeneratedRows: B65_MAX_GENERATED_ROWS, evaluationContext }
45813
46022
  );
45814
46023
  } else if (grouping.type === "PLAIN" || hasAggregateColumns(stmt.columns)) {
45815
46024
  rows = applyGroupBy(
@@ -45821,21 +46030,29 @@ function runFullScan(input) {
45821
46030
  {
45822
46031
  scalarCache,
45823
46032
  resolveFieldType: fieldTypeResolver,
45824
- resolveFieldSemantics: fieldSemanticsResolver
46033
+ resolveFieldSemantics: fieldSemanticsResolver,
46034
+ evaluationContext
45825
46035
  }
45826
46036
  );
45827
46037
  }
45828
46038
  warnOnUnresolvedAggregateComparisons(stmt.columns, rows, warnings);
45829
46039
  const resolveHavingSemantics = (field) => field.aggregateRef ? aggregateResultSemantics(field.aggregateRef, aggregateSortKindResolver) : havingFieldSemanticsResolver?.(field);
45830
46040
  warnOnUnresolvedAggregateComparisons(stmt.having, rows, warnings);
45831
- rows = applyHaving(rows, stmt.having, havingFieldTypeResolver, resolveHavingSemantics);
46041
+ rows = applyHaving(
46042
+ rows,
46043
+ stmt.having,
46044
+ havingFieldTypeResolver,
46045
+ resolveHavingSemantics,
46046
+ evaluationContext
46047
+ );
45832
46048
  rows = applyWindow(
45833
46049
  rows,
45834
46050
  stmt.columns,
45835
46051
  optionOrders,
45836
46052
  sortKinds,
45837
46053
  effectiveOrderSemantics,
45838
- aggregateSortKindResolver
46054
+ aggregateSortKindResolver,
46055
+ evaluationContext
45839
46056
  );
45840
46057
  if (stmt.distinct) {
45841
46058
  rows = applyDistinct(
@@ -45843,7 +46060,8 @@ function runFullScan(input) {
45843
46060
  stmt.columns,
45844
46061
  scalarCache,
45845
46062
  fieldTypeResolver,
45846
- fieldSemanticsResolver
46063
+ fieldSemanticsResolver,
46064
+ evaluationContext
45847
46065
  );
45848
46066
  }
45849
46067
  rows = applyOrderBy(
@@ -45852,7 +46070,14 @@ function runFullScan(input) {
45852
46070
  optionOrders,
45853
46071
  sortKinds,
45854
46072
  effectiveOrderSemantics,
45855
- buildOrderByAliasEvaluator(stmt.columns, scalarCache, fieldTypeResolver, fieldSemanticsResolver)
46073
+ buildOrderByAliasEvaluator(
46074
+ stmt.columns,
46075
+ scalarCache,
46076
+ fieldTypeResolver,
46077
+ fieldSemanticsResolver,
46078
+ evaluationContext
46079
+ ),
46080
+ evaluationContext
45856
46081
  );
45857
46082
  rows = applyLimit(rows, stmt.limit, stmt.offset);
45858
46083
  return project(
@@ -45862,7 +46087,8 @@ function runFullScan(input) {
45862
46087
  fieldTypeResolver,
45863
46088
  sourceColumns2,
45864
46089
  fieldSemanticsResolver,
45865
- hiddenQualifiedAliases
46090
+ hiddenQualifiedAliases,
46091
+ evaluationContext
45866
46092
  );
45867
46093
  }
45868
46094
 
@@ -47592,6 +47818,18 @@ var SearchAbortedError = class extends Error {
47592
47818
  var materializedMetaBySelectResult = /* @__PURE__ */ new WeakMap();
47593
47819
  var materializedMetaByValidationResult = /* @__PURE__ */ new WeakMap();
47594
47820
  var importSourceByDmlStatement = /* @__PURE__ */ new WeakMap();
47821
+ var statementEvaluationContextKey = /* @__PURE__ */ Symbol("statementEvaluationContext");
47822
+ function bindStatementEvaluationContext(options) {
47823
+ const internal = options;
47824
+ if (internal[statementEvaluationContextKey]) return options;
47825
+ return {
47826
+ ...options,
47827
+ [statementEvaluationContextKey]: { statementInstant: /* @__PURE__ */ new Date() }
47828
+ };
47829
+ }
47830
+ function statementEvaluationContext(options) {
47831
+ return options[statementEvaluationContextKey] ?? {};
47832
+ }
47595
47833
  var defaultCacheContextByClient = /* @__PURE__ */ new WeakMap();
47596
47834
  var nextDefaultCacheContextId = 1;
47597
47835
  var nextCacheInvocationId = 1;
@@ -47841,6 +48079,7 @@ async function resolveRelativeDateExecutionPlan(stmt, client, cacheContext) {
47841
48079
  });
47842
48080
  }
47843
48081
  async function executeParsedStatement(stmt, client, options, cacheContext) {
48082
+ options = bindStatementEvaluationContext(options);
47844
48083
  const relativeDatePlan = await resolveRelativeDateExecutionPlan(stmt, client, cacheContext);
47845
48084
  if (stmt.type !== "EXPLAIN") assertRelativeDatePushdownPlan(relativeDatePlan);
47846
48085
  const unresolved = findVariableRef(stmt);
@@ -48055,7 +48294,14 @@ async function executeExistingRecordValidationCore(stmt, client, options, cacheC
48055
48294
  id: String(record2["$id"]?.value ?? ""),
48056
48295
  record: record2,
48057
48296
  flat: flatten(record2, null)
48058
- })).filter((row) => stmt.where === null || evalWhere(stmt.where, row.flat, (field) => evaluationTypes.get(field.field)));
48297
+ })).filter((row) => stmt.where === null || evalWhere(
48298
+ stmt.where,
48299
+ row.flat,
48300
+ (field) => evaluationTypes.get(field.field),
48301
+ void 0,
48302
+ void 0,
48303
+ statementEvaluationContext(options)
48304
+ ));
48059
48305
  const rows = [];
48060
48306
  const detailRows = /* @__PURE__ */ new Map();
48061
48307
  const summaryRows = /* @__PURE__ */ new Map();
@@ -48332,6 +48578,7 @@ function statementHasApplyMutation(statement) {
48332
48578
  return statement.type === "UPSERT" && statement.validateOnly !== true && Boolean(statement.onInsertApplyBlocks?.length || statement.onUpdateApplyBlocks?.length);
48333
48579
  }
48334
48580
  async function executeBatchStatement(stmt, info, client, options, cacheContext, tempTables, variables, relativeDateVariables) {
48581
+ options = bindStatementEvaluationContext(options);
48335
48582
  if (stmt.type === "SET_VARIABLE") {
48336
48583
  const resolvedStmt2 = resolveBatchVariableReferences(stmt, variables);
48337
48584
  validateStatementStatic(resolvedStmt2);
@@ -48371,7 +48618,7 @@ async function executeBatchStatement(stmt, info, client, options, cacheContext,
48371
48618
  throw e;
48372
48619
  }
48373
48620
  } else {
48374
- variables.set(stmt.name, evaluateScalarExpr(resolvedStmt2.expr));
48621
+ variables.set(stmt.name, evaluateScalarExpr(resolvedStmt2.expr, statementEvaluationContext(options)));
48375
48622
  }
48376
48623
  return {};
48377
48624
  }
@@ -48387,7 +48634,10 @@ async function executeBatchStatement(stmt, info, client, options, cacheContext,
48387
48634
  if (Object.prototype.hasOwnProperty.call(injected, stmt.name)) {
48388
48635
  variables.set(stmt.name, { type: "string", value: injected[stmt.name] });
48389
48636
  } else {
48390
- const value = evaluateScalarExpr(stmt.default);
48637
+ const value = evaluateScalarExpr(
48638
+ stmt.default,
48639
+ statementEvaluationContext(options)
48640
+ );
48391
48641
  variables.set(stmt.name, {
48392
48642
  type: "string",
48393
48643
  value: value.type === "number" ? value.raw ?? String(value.value) : value.value
@@ -48638,18 +48888,18 @@ function prepareRelativeDateVariables(statements, injectedVariables) {
48638
48888
  }
48639
48889
  return prepared;
48640
48890
  }
48641
- function evaluateScalarExpr(expr) {
48891
+ function evaluateScalarExpr(expr, evaluationContext = {}) {
48642
48892
  switch (expr.type) {
48643
48893
  case "STRING":
48644
48894
  return { type: "string", value: expr.value };
48645
48895
  case "NUMBER":
48646
48896
  return { type: "number", value: expr.value, raw: numberLiteralText(expr) };
48647
48897
  case "KINTONE_FUNC":
48648
- return { type: "string", value: resolveKintoneFunc(expr.name) };
48898
+ return { type: "string", value: resolveKintoneFunc(expr.name, evaluationContext) };
48649
48899
  case "STRING_FUNC":
48650
- return { type: "string", value: evalStringFunc(expr, {}) };
48900
+ return { type: "string", value: evalStringFunc(expr, {}, void 0, void 0, evaluationContext) };
48651
48901
  case "ARITH": {
48652
- const value = evalArithExpr(expr, {});
48902
+ const value = evalArithExpr(expr, {}, evaluationContext);
48653
48903
  if (!Number.isFinite(value)) {
48654
48904
  throw new Error("ArgumentError: SET scalar arithmetic produced a non-finite number.");
48655
48905
  }
@@ -49156,7 +49406,7 @@ async function executeSelect(stmt, client, options, cacheContext, cteCache, capt
49156
49406
  const subqueryWarnings = /* @__PURE__ */ new Set();
49157
49407
  await validateSelectGroupingPlanning(stmt, client, cacheContext, cteCache);
49158
49408
  if (isNoFromSelect(stmt)) {
49159
- result = executeNoFromSelect(stmt);
49409
+ result = executeNoFromSelect(stmt, options);
49160
49410
  if (captureColumnMeta) {
49161
49411
  materializedMetaBySelectResult.set(
49162
49412
  result,
@@ -49637,13 +49887,30 @@ function validateNoFromColumns(stmt) {
49637
49887
  }
49638
49888
  }
49639
49889
  }
49640
- function executeNoFromSelect(stmt) {
49890
+ function executeNoFromSelect(stmt, options) {
49641
49891
  if (stmt.joins.length > 0 || stmt.where || normalizeGroupingSpec(stmt).type !== "NONE" || stmt.having || stmt.orderBy.length > 0 || stmt.distinct) {
49642
49892
  throw new Error("ArgumentError: JOIN/WHERE/GROUP BY/HAVING/ORDER BY/DISTINCT are not supported without FROM.");
49643
49893
  }
49644
49894
  validateNoFromColumns(stmt);
49645
- const windowed = applyWindow([{}], stmt.columns);
49646
- const { rows: projected, columns } = project(windowed, stmt.columns);
49895
+ const windowed = applyWindow(
49896
+ [{}],
49897
+ stmt.columns,
49898
+ void 0,
49899
+ void 0,
49900
+ void 0,
49901
+ void 0,
49902
+ statementEvaluationContext(options)
49903
+ );
49904
+ const { rows: projected, columns } = project(
49905
+ windowed,
49906
+ stmt.columns,
49907
+ void 0,
49908
+ void 0,
49909
+ void 0,
49910
+ void 0,
49911
+ void 0,
49912
+ statementEvaluationContext(options)
49913
+ );
49647
49914
  const rows = applyLimit(projected, stmt.limit, stmt.offset);
49648
49915
  return { type: "SELECT", rows, columns, rowCount: rows.length, warnings: [] };
49649
49916
  }
@@ -49719,8 +49986,10 @@ async function executeSimpleSelect(stmt, client, options, cacheContext, orderPla
49719
49986
  stmt.columns,
49720
49987
  void 0,
49721
49988
  fieldTypeResolvers.row,
49722
- projectionSemanticsResolver
49723
- )
49989
+ projectionSemanticsResolver,
49990
+ statementEvaluationContext(options)
49991
+ ),
49992
+ statementEvaluationContext(options)
49724
49993
  );
49725
49994
  rows = applyLimit(rows, stmt.limit, stmt.offset);
49726
49995
  }
@@ -49730,7 +49999,9 @@ async function executeSimpleSelect(stmt, client, options, cacheContext, orderPla
49730
49999
  void 0,
49731
50000
  fieldTypeResolvers.row,
49732
50001
  void 0,
49733
- projectionSemanticsResolver
50002
+ projectionSemanticsResolver,
50003
+ void 0,
50004
+ statementEvaluationContext(options)
49734
50005
  );
49735
50006
  const columns = await restoreEmptyWildcardColumns(
49736
50007
  stmt,
@@ -50893,7 +51164,8 @@ async function executeFullScanSelect(stmt, client, options, cacheContext, cteCac
50893
51164
  ...prefilterPlan ? { residualWhere: prefilterPlan.residualWhere } : boundServerFunctionPlan ? { residualWhere: boundServerFunctionPlan.joinPlan.residualWhere } : {},
50894
51165
  resolvedGroupingSpec: resolvedGroupingSpecs.get(stmt),
50895
51166
  plainGroupByPlan,
50896
- warnings
51167
+ warnings,
51168
+ evaluationContext: statementEvaluationContext(options)
50897
51169
  });
50898
51170
  const columns = await restoreEmptyWildcardColumns(
50899
51171
  stmt,
@@ -51720,7 +51992,8 @@ async function executeFullScanWithCte(stmt, client, options, cteCache, cacheCont
51720
51992
  tableColumns,
51721
51993
  hiddenQualifiedAliases,
51722
51994
  resolvedGroupingSpec,
51723
- plainGroupByPlan
51995
+ plainGroupByPlan,
51996
+ evaluationContext: statementEvaluationContext(options)
51724
51997
  });
51725
51998
  const columns = await restoreEmptyWildcardColumns(
51726
51999
  stmt,
@@ -52846,7 +53119,12 @@ async function materializeValidationCandidates(stmt, operation, client, options,
52846
53119
  evaluationTypes = new Map(stmt.fields.map((field) => [field, infoByCode.get(field)?.fieldType ?? ""]));
52847
53120
  assertCheckComparisonTypes(stmt, evaluationTypes);
52848
53121
  rows = stmt.values.map((row) => row.map(
52849
- (value, i) => value.type === "CASE_VALUE" ? evalCaseWhenValue(value.expr, {}, infoByCode.get(stmt.fields[i])?.fieldType) : value
53122
+ (value, i) => value.type === "CASE_VALUE" ? evalCaseWhenValue(
53123
+ value.expr,
53124
+ {},
53125
+ infoByCode.get(stmt.fields[i])?.fieldType,
53126
+ statementEvaluationContext(options)
53127
+ ) : value
52850
53128
  ));
52851
53129
  } else {
52852
53130
  const selectResult = await dmlSourceMaterializer.materialize(stmt, client, options, cacheContext, tempTables, [...infoByCode.values()]);
@@ -52977,7 +53255,12 @@ async function materializeUpdateValidationCandidates(stmt, client, options, cach
52977
53255
  });
52978
53256
  snapshotsById = indexDmlUpdateSnapshots(resolved.records);
52979
53257
  evaluationById = snapshotsById;
52980
- records = updateToPutBatchesArith(stmt, resolved.records, fieldTypes).flatMap((batch) => batch.records);
53258
+ records = updateToPutBatchesArith(
53259
+ stmt,
53260
+ resolved.records,
53261
+ fieldTypes,
53262
+ statementEvaluationContext(options)
53263
+ ).flatMap((batch) => batch.records);
52981
53264
  } else {
52982
53265
  const getParams = updateToGetQuery(stmt);
52983
53266
  if (checkTargetFields.length > 0) {
@@ -53145,7 +53428,12 @@ async function materializeUpdateFromValidationCandidates(stmt, from, client, opt
53145
53428
  snapshotFields
53146
53429
  );
53147
53430
  const fieldTypes = await getFieldTypeMap(stmt.appId, client, cacheContext);
53148
- const records = updateFromToPutBatches(stmt, matched, fieldTypes).flatMap((batch) => batch.records);
53431
+ const records = updateFromToPutBatches(
53432
+ stmt,
53433
+ matched,
53434
+ fieldTypes,
53435
+ statementEvaluationContext(options)
53436
+ ).flatMap((batch) => batch.records);
53149
53437
  const matchedById = new Map(matched.map((pair) => [Number(pair.target["$id"]?.value), pair]));
53150
53438
  const snapshotsById = snapshotFields ? indexDmlUpdateSnapshots(matched.map((pair) => pair.target)) : /* @__PURE__ */ new Map();
53151
53439
  return records.sort((a, b) => a.id - b.id).map((entry, index) => ({
@@ -53377,7 +53665,7 @@ async function executeInsert(stmt, client, options, cacheContext) {
53377
53665
  const fieldInfos = await loadWritableTopLevelDmlFields(stmt.appId, stmt.fields, client, cacheContext);
53378
53666
  const numberPrecision = await loadNumberPrecisionForTargets(stmt.appId, stmt.fields, fieldInfos, client, cacheContext);
53379
53667
  const fieldTypes = await getFieldTypeMap(stmt.appId, client, cacheContext);
53380
- const batches = insertToPostBatches(stmt, fieldTypes);
53668
+ const batches = insertToPostBatches(stmt, fieldTypes, statementEvaluationContext(options));
53381
53669
  assertValidDmlRecords(batches.flatMap((batch) => batch.records), stmt.fields, fieldInfos, numberPrecision);
53382
53670
  const createdIds = [];
53383
53671
  for (const batch of batches) {
@@ -53986,7 +54274,12 @@ async function executeUpdate(stmt, client, options, cacheContext, tempTables) {
53986
54274
  { maxRecords: maxRecords2, parallel: options.fetchParallel ?? 1 }
53987
54275
  );
53988
54276
  const records = resolved2.records;
53989
- const batches2 = updateToPutBatchesArith(stmt, records, fieldTypes);
54277
+ const batches2 = updateToPutBatchesArith(
54278
+ stmt,
54279
+ records,
54280
+ fieldTypes,
54281
+ statementEvaluationContext(options)
54282
+ );
53990
54283
  assertValidDmlRecords(batches2.flatMap((batch) => batch.records.map((entry) => entry.record)), targetFields, fieldInfos, numberPrecision);
53991
54284
  if (options.confirm) {
53992
54285
  const ok = await options.confirm(records.length, "UPDATE");
@@ -54043,7 +54336,13 @@ async function executeApplyPatchUpdate(stmt, client, options, cacheContext, stat
54043
54336
  throw new Error(`ArgumentError: APPLY snapshot $id ${actualId} does not match requested $id ${requestedId}.`);
54044
54337
  }
54045
54338
  requireRevision(response.records[0]);
54046
- const plan = buildApplyPatchPlan({ statement: stmt, snapshot: response.records[0], fieldInfos, metadata });
54339
+ const plan = buildApplyPatchPlan({
54340
+ statement: stmt,
54341
+ snapshot: response.records[0],
54342
+ fieldInfos,
54343
+ metadata,
54344
+ evaluationContext: statementEvaluationContext(options)
54345
+ });
54047
54346
  const fieldIndex = buildPostImageFieldIndex(
54048
54347
  fieldInfos,
54049
54348
  stmt.assignments.map((assignment) => assignment.field)
@@ -54242,7 +54541,8 @@ async function selectApplyParentSnapshots(stmt, client, options, fieldInfos, cac
54242
54541
  row,
54243
54542
  resolvers.fieldTypeResolver,
54244
54543
  selectionPlan.appliedKlikes,
54245
- resolvers.fieldSemanticsResolver
54544
+ resolvers.fieldSemanticsResolver,
54545
+ statementEvaluationContext(options)
54246
54546
  )).map(({ snapshot }) => snapshot);
54247
54547
  }
54248
54548
  function collectApplyParentWhereFields(where) {
@@ -54483,7 +54783,12 @@ function applyValidationColumnMeta(columns, fieldInfos, appId) {
54483
54783
  async function executeUpdateFrom(stmt, from, client, options, cacheContext, tempTables) {
54484
54784
  const matched = await resolveUpdateFromMatchedRecords(stmt, from, client, options, cacheContext, tempTables);
54485
54785
  const fieldTypes = await getFieldTypeMap(stmt.appId, client, cacheContext);
54486
- const batches = updateFromToPutBatches(stmt, matched, fieldTypes);
54786
+ const batches = updateFromToPutBatches(
54787
+ stmt,
54788
+ matched,
54789
+ fieldTypes,
54790
+ statementEvaluationContext(options)
54791
+ );
54487
54792
  const targetFields = stmt.assignments.map((assignment) => assignment.field);
54488
54793
  const fieldInfos = await getFieldsCached(stmt.appId, client, cacheContext);
54489
54794
  const numberPrecision = await loadNumberPrecisionForTargets(stmt.appId, targetFields, fieldInfos, client, cacheContext);
@@ -54557,7 +54862,12 @@ async function executeUpsert(stmt, client, options, cacheContext) {
54557
54862
  stmt.fields.forEach((field, i) => {
54558
54863
  const val = row[i];
54559
54864
  if (val.type === "CASE_VALUE") {
54560
- record2[field] = { value: evalCaseWhenValue(val.expr, {}, fieldTypes.get(field)) };
54865
+ record2[field] = { value: evalCaseWhenValue(
54866
+ val.expr,
54867
+ {},
54868
+ fieldTypes.get(field),
54869
+ statementEvaluationContext(options)
54870
+ ) };
54561
54871
  } else {
54562
54872
  record2[field] = { value: toKintoneValue(val, fieldTypes.get(field)) };
54563
54873
  }
@@ -54678,7 +54988,14 @@ async function executeUpdateSubtable(stmt, client, options, cacheContext) {
54678
54988
  { maxRecords: options.maxRecords ?? 1e4, parallel: options.fetchParallel ?? 1 }
54679
54989
  );
54680
54990
  const expanded = expandRowsForSubtableDml(parents, subtableCode);
54681
- const targets = expanded.filter((r) => evalWhere(stmt.where, r.flat, resolveFieldType));
54991
+ const targets = expanded.filter((r) => evalWhere(
54992
+ stmt.where,
54993
+ r.flat,
54994
+ resolveFieldType,
54995
+ void 0,
54996
+ void 0,
54997
+ statementEvaluationContext(options)
54998
+ ));
54682
54999
  if (options.confirm) {
54683
55000
  const ok = await options.confirm(targets.length, "UPDATE");
54684
55001
  if (!ok) throw new OperationCancelledError("UPDATE", targets.length);
@@ -54698,7 +55015,12 @@ async function executeUpdateSubtable(stmt, client, options, cacheContext) {
54698
55015
  if (a.field.startsWith("_")) {
54699
55016
  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`);
54700
55017
  }
54701
- updates[a.field] = { value: evaluateSubtableAssignmentValue(a.value, t.flat, resolveFieldType) };
55018
+ updates[a.field] = { value: evaluateSubtableAssignmentValue(
55019
+ a.value,
55020
+ t.flat,
55021
+ resolveFieldType,
55022
+ statementEvaluationContext(options)
55023
+ ) };
54702
55024
  }
54703
55025
  byRid.set(t.rowId, updates);
54704
55026
  }
@@ -54741,7 +55063,14 @@ async function executeDeleteSubtable(stmt, client, options, cacheContext) {
54741
55063
  { maxRecords: options.maxRecords ?? 1e4, parallel: options.fetchParallel ?? 1 }
54742
55064
  );
54743
55065
  const expanded = expandRowsForSubtableDml(parents, subtableCode);
54744
- const targets = expanded.filter((r) => evalWhere(stmt.where, r.flat, resolveFieldType));
55066
+ const targets = expanded.filter((r) => evalWhere(
55067
+ stmt.where,
55068
+ r.flat,
55069
+ resolveFieldType,
55070
+ void 0,
55071
+ void 0,
55072
+ statementEvaluationContext(options)
55073
+ ));
54745
55074
  if (options.confirm) {
54746
55075
  const ok = await options.confirm(targets.length, "DELETE");
54747
55076
  if (!ok) throw new OperationCancelledError("DELETE", targets.length);
@@ -54916,7 +55245,8 @@ async function executeReorder(stmt, client, options, cacheContext) {
54916
55245
  r.flat,
54917
55246
  resolveFieldType,
54918
55247
  void 0,
54919
- resolveReorderSemantics
55248
+ resolveReorderSemantics,
55249
+ statementEvaluationContext(options)
54920
55250
  )).map((r) => r.parentId));
54921
55251
  if (options.confirm) {
54922
55252
  const ok = await options.confirm(targetParentIds.size, "UPDATE");
@@ -54928,7 +55258,13 @@ async function executeReorder(stmt, client, options, cacheContext) {
54928
55258
  if (!parent) continue;
54929
55259
  const rows = getMutableTableRows(parent, stmt.subtableCode);
54930
55260
  const sortable = rows.map((row, i) => ({ row, i, flat: buildFlatRowForSort(parent, stmt.subtableCode, row, i) }));
54931
- sortable.sort((a, b) => compareByOrder(a.flat, b.flat, stmt.by, resolveReorderSemantics));
55261
+ sortable.sort((a, b) => compareByOrder(
55262
+ a.flat,
55263
+ b.flat,
55264
+ stmt.by,
55265
+ resolveReorderSemantics,
55266
+ statementEvaluationContext(options)
55267
+ ));
54932
55268
  const orderedRowIds = sortable.map((x) => x.row.id ?? "");
54933
55269
  await client.putRecords(buildSubtableReorderPutParams(stmt.appId, pid, getRevision(parent), stmt.subtableCode, orderedRowIds));
54934
55270
  }
@@ -54949,24 +55285,24 @@ function buildFlatRowForSort(parent, subtableCode, row, idx) {
54949
55285
  }
54950
55286
  return flat;
54951
55287
  }
54952
- function compareByOrder(a, b, orderBy, resolveSemantics) {
55288
+ function compareByOrder(a, b, orderBy, resolveSemantics, evaluationContext = {}) {
54953
55289
  for (const item of orderBy) {
54954
- const av = evalOrderKeyForRow(item.key, a);
54955
- const bv = evalOrderKeyForRow(item.key, b);
55290
+ const av = evalOrderKeyForRow(item.key, a, evaluationContext);
55291
+ const bv = evalOrderKeyForRow(item.key, b, evaluationContext);
54956
55292
  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");
54957
55293
  const cmp = compareCanonicalValues(av, bv, semantics ?? syntheticSemantics("string"));
54958
55294
  if (cmp !== 0) return item.direction === "ASC" ? cmp : -cmp;
54959
55295
  }
54960
55296
  return 0;
54961
55297
  }
54962
- function evalOrderKeyForRow(key, row) {
55298
+ function evalOrderKeyForRow(key, row, evaluationContext = {}) {
54963
55299
  switch (key.type) {
54964
55300
  case "FIELD_NAME":
54965
55301
  return row[key.name] ?? "";
54966
55302
  case "ARITH_KEY":
54967
- return String(evalArithExpr(key.expr, row));
55303
+ return String(evalArithExpr(key.expr, row, evaluationContext));
54968
55304
  case "FUNC_KEY":
54969
- return evalStringFunc(key.expr, row);
55305
+ return evalStringFunc(key.expr, row, void 0, void 0, evaluationContext);
54970
55306
  case "GROUPING_KEY":
54971
55307
  throw new Error("ArgumentError: GROUPING() is not supported in REORDER BY.");
54972
55308
  }
@@ -55481,9 +55817,13 @@ async function buildExplainWhereAnalysis(query, client, cacheContext, maxRecords
55481
55817
  const joinField = leftAlias === joinAlias ? join.on.left.field : join.on.right.field;
55482
55818
  if (!sourceAlias) continue;
55483
55819
  const sourceTable = [select.from, ...select.joins.map((candidate) => candidate.table)].find((table) => effectiveTableAlias(table) === sourceAlias);
55484
- const targetInfos = await getFieldsCached(join.table.appId, tracedClient, cacheContext);
55485
- const targetInfo = targetInfos.find((info) => info.code === fieldCodeForTypeLookup(join.table, joinField));
55486
- const targetMeta = targetInfo ? materializedMetaFromFieldInfo(targetInfo, join.table.appId) : systemColumnMeta(joinField);
55820
+ let targetMeta;
55821
+ if (join.table.cteName !== null) {
55822
+ targetMeta = explainRelations.get(join.table.cteName)?.columnMeta?.get(joinField);
55823
+ } else {
55824
+ const targetInfo = (await getFieldsCached(join.table.appId, tracedClient, cacheContext)).find((info) => info.code === fieldCodeForTypeLookup(join.table, joinField));
55825
+ targetMeta = targetInfo ? materializedMetaFromFieldInfo(targetInfo, join.table.appId) : systemColumnMeta(joinField);
55826
+ }
55487
55827
  let sourceMeta;
55488
55828
  let values;
55489
55829
  let sourceRowCount;