@rex0220/kintone-sql-tools 3.66.1 → 3.68.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.1" : "0.0.0-dev";
29767
+ var SERVER_VERSION = true ? "3.68.0" : "0.0.0-dev";
29768
29768
 
29769
29769
  // src/mcp/docsResources.ts
29770
29770
  function loadFromRepoDocs() {
@@ -30370,7 +30370,7 @@ var Lexer = class {
30370
30370
  // ヘルパー
30371
30371
  // ----------------------------------------------------------
30372
30372
  makeToken(kind, value, pos) {
30373
- return { kind, value, pos };
30373
+ return { kind, value, pos, end: this.pos };
30374
30374
  }
30375
30375
  };
30376
30376
  function isIdentStart(ch) {
@@ -30987,6 +30987,8 @@ var Parser = class {
30987
30987
  this.allowRelativeDateFunctions = false;
30988
30988
  /** WITH 句で定義された CTE 名のセット(parseTableRef で参照) */
30989
30989
  this.cteNames = /* @__PURE__ */ new Set();
30990
+ /** dialect 1 の裸名で宣言された一時テーブル名(参照時に # 付きへ正規化) */
30991
+ this.bareTempTableNames = /* @__PURE__ */ new Set();
30990
30992
  /** パース中に出現した一時テーブル参照(#name)のトークン。単文 API での拒否に使う */
30991
30993
  this.tempTableRefs = [];
30992
30994
  /** GROUP BY を読む前に作る B124 候補 leaf の診断位置。AST 公開型へ位置情報を足さない。 */
@@ -31025,7 +31027,12 @@ var Parser = class {
31025
31027
  }
31026
31028
  /** 複文(`;` 区切り)をパースする。空文はスキップする */
31027
31029
  parseStatements() {
31030
+ return this.parseStatementsWithRanges().statements;
31031
+ }
31032
+ /** 複文と、原文上の文ごとの文字範囲を同時に返す。 */
31033
+ parseStatementsWithRanges() {
31028
31034
  const stmts = [];
31035
+ const statementRanges = [];
31029
31036
  while (true) {
31030
31037
  while (this.peek().kind === ";" /* SEMICOLON */) this.advance();
31031
31038
  if (this.peek().kind === "EOF" /* EOF */) break;
@@ -31041,9 +31048,11 @@ var Parser = class {
31041
31048
  if (after.kind !== ";" /* SEMICOLON */ && after.kind !== "EOF" /* EOF */) {
31042
31049
  throw new ParseError("\u6587\u306E\u533A\u5207\u308A\u306B\u306F ; \u304C\u5FC5\u8981\u3067\u3059", after);
31043
31050
  }
31051
+ const lastTok = this.prev();
31052
+ statementRanges.push({ start: startTok.pos, end: lastTok.end ?? after.pos });
31044
31053
  }
31045
31054
  this.expect("EOF" /* EOF */);
31046
- return stmts;
31055
+ return { statements: stmts, statementRanges };
31047
31056
  }
31048
31057
  // ----------------------------------------------------------
31049
31058
  // Statement ディスパッチ
@@ -31082,6 +31091,13 @@ var Parser = class {
31082
31091
  if (upper === "DROP") return this.parseDropTempTable();
31083
31092
  if (upper === "DECLARE") return this.parseDeclareVariable();
31084
31093
  if (upper === "VALIDATE") return this.parseValidate();
31094
+ if (upper === "EXIT") return this.parseExit();
31095
+ if (upper === "MERGE") {
31096
+ if (!this.capabilities.dialect1) {
31097
+ throw new ParseError("MERGE \u306B\u306F -- @ksql dialect: 1 \u306E\u5BA3\u8A00\u304C\u5FC5\u8981\u3067\u3059", tok);
31098
+ }
31099
+ return this.parseMergeAsUpsert();
31100
+ }
31085
31101
  if (upper === "GENERATE_SERIES") {
31086
31102
  throw new ParseError(
31087
31103
  "GENERATE_SERIES \u306F WITH \u306E CTE \u672C\u4F53\u306B\u66F8\u3044\u3066\u304F\u3060\u3055\u3044\u3002\u4F8B: WITH s AS (GENERATE_SERIES(1, 5)) SELECT generate_series FROM s",
@@ -31100,7 +31116,7 @@ var Parser = class {
31100
31116
  break;
31101
31117
  }
31102
31118
  throw new ParseError(
31103
- "SELECT / INSERT / UPDATE / DELETE / REORDER / VALIDATE / WITH / SHOW / DESCRIBE / EXPLAIN / CREATE TEMP TABLE / DROP TEMP TABLE / SET / DECLARE / ASSERT \u306E\u3044\u305A\u308C\u304B\u3067\u59CB\u307E\u308B SQL \u6587\u304C\u5FC5\u8981\u3067\u3059",
31119
+ "SELECT / INSERT / UPDATE / DELETE / REORDER / VALIDATE / WITH / SHOW / DESCRIBE / EXPLAIN / CREATE TEMP TABLE / DROP TEMP TABLE / SET / DECLARE / ASSERT / EXIT \u306E\u3044\u305A\u308C\u304B\u3067\u59CB\u307E\u308B SQL \u6587\u304C\u5FC5\u8981\u3067\u3059",
31104
31120
  tok
31105
31121
  );
31106
31122
  }
@@ -31228,6 +31244,7 @@ var Parser = class {
31228
31244
  this.advance();
31229
31245
  this.expectSoftKeyword("TEMP", "CREATE \u306E\u5F8C\u306B\u306F TEMP TABLE \u304C\u5FC5\u8981\u3067\u3059\uFF08\u4F8B: CREATE TEMP TABLE #temp AS SELECT ...\uFF09");
31230
31246
  this.expectSoftKeyword("TABLE", "CREATE TEMP \u306E\u5F8C\u306B\u306F TABLE \u304C\u5FC5\u8981\u3067\u3059");
31247
+ const bareName = this.isDialect1BareTempTableName();
31231
31248
  const name = this.parseTempTableName();
31232
31249
  this.expect("AS" /* AS */, "CREATE TEMP TABLE \u306B\u306F AS SELECT \u304C\u5FC5\u8981\u3067\u3059");
31233
31250
  const tok = this.peek();
@@ -31239,13 +31256,16 @@ var Parser = class {
31239
31256
  } else {
31240
31257
  throw new ParseError("CREATE TEMP TABLE ... AS \u306E\u5F8C\u306B\u306F SELECT / WITH \u304C\u5FC5\u8981\u3067\u3059", tok);
31241
31258
  }
31259
+ if (bareName !== null) this.bareTempTableNames.add(bareName);
31242
31260
  return { type: "CREATE_TEMP_TABLE", name, query };
31243
31261
  }
31244
31262
  parseDropTempTable() {
31245
31263
  this.advance();
31246
31264
  this.expectSoftKeyword("TEMP", "DROP \u306E\u5F8C\u306B\u306F TEMP TABLE \u304C\u5FC5\u8981\u3067\u3059\uFF08\u4F8B: DROP TEMP TABLE #temp\uFF09");
31247
31265
  this.expectSoftKeyword("TABLE", "DROP TEMP \u306E\u5F8C\u306B\u306F TABLE \u304C\u5FC5\u8981\u3067\u3059");
31266
+ const bareName = this.isDialect1BareTempTableName();
31248
31267
  const name = this.parseTempTableName();
31268
+ if (bareName !== null) this.bareTempTableNames.delete(bareName);
31249
31269
  return { type: "DROP_TEMP_TABLE", name };
31250
31270
  }
31251
31271
  expectSoftKeyword(word, msg) {
@@ -31267,8 +31287,16 @@ var Parser = class {
31267
31287
  this.advance();
31268
31288
  return tok.value;
31269
31289
  }
31290
+ if (this.capabilities.dialect1 && (tok.kind === "IDENT" /* IDENT */ || tok.kind === "BIDENT" /* BIDENT */)) {
31291
+ this.advance();
31292
+ return `#${tok.value}`;
31293
+ }
31270
31294
  throw new ParseError("\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u540D\u306F # \u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\uFF08\u4F8B: #temp\uFF09", tok);
31271
31295
  }
31296
+ isDialect1BareTempTableName() {
31297
+ const tok = this.peek();
31298
+ return this.capabilities.dialect1 && (tok.kind === "IDENT" /* IDENT */ || tok.kind === "BIDENT" /* BIDENT */) && !tok.value.startsWith("#") ? tok.value : null;
31299
+ }
31272
31300
  parseShow() {
31273
31301
  this.advance();
31274
31302
  if (!this.consume("APPS" /* APPS */)) {
@@ -31596,6 +31624,41 @@ var Parser = class {
31596
31624
  // ----------------------------------------------------------
31597
31625
  parseAssert() {
31598
31626
  this.expect("ASSERT" /* ASSERT */);
31627
+ const warnTok = this.peek();
31628
+ const warn = this.isSoftKeyword("WARN");
31629
+ if (warn) {
31630
+ this.requireDialect1(warnTok);
31631
+ this.advance();
31632
+ }
31633
+ const condition = this.parseAssertCondition();
31634
+ const message = this.parseFlowMessage();
31635
+ return {
31636
+ type: "ASSERT",
31637
+ ...condition,
31638
+ ...warn ? { warn: true } : {},
31639
+ ...message !== void 0 ? { message } : {}
31640
+ };
31641
+ }
31642
+ /** EXIT SUCCESS IF <ASSERT と同じ条件>, '<message>' */
31643
+ parseExit() {
31644
+ const exitTok = this.advance();
31645
+ this.requireDialect1(exitTok);
31646
+ if (!this.isSoftKeyword("SUCCESS")) {
31647
+ throw new ParseError("EXIT \u306E\u5F8C\u306B\u306F SUCCESS \u304C\u5FC5\u8981\u3067\u3059", this.peek());
31648
+ }
31649
+ this.advance();
31650
+ if (this.peek().kind !== "IF" /* IF */ && !this.isSoftKeyword("IF")) {
31651
+ throw new ParseError("EXIT SUCCESS \u306E\u5F8C\u306B\u306F IF \u304C\u5FC5\u8981\u3067\u3059", this.peek());
31652
+ }
31653
+ this.advance();
31654
+ const condition = this.parseAssertCondition();
31655
+ if (!this.consume("," /* COMMA */)) {
31656
+ throw new ParseError("EXIT SUCCESS IF \u306B\u306F\u672B\u5C3E\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u6587\u5B57\u5217\u304C\u5FC5\u8981\u3067\u3059", this.peek());
31657
+ }
31658
+ const message = this.expect("STRING" /* STRING */, "EXIT SUCCESS IF \u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u306B\u306F\u6587\u5B57\u5217\u30EA\u30C6\u30E9\u30EB\u304C\u5FC5\u8981\u3067\u3059");
31659
+ return { type: "EXIT", ...condition, message: message.value };
31660
+ }
31661
+ parseAssertCondition() {
31599
31662
  const condStart = this.pos;
31600
31663
  const left = this.parseAssertOperand();
31601
31664
  const opTok = this.peek();
@@ -31608,7 +31671,6 @@ var Parser = class {
31608
31671
  const high = this.parseAssertOperand();
31609
31672
  this.rejectAssertCompound();
31610
31673
  return {
31611
- type: "ASSERT",
31612
31674
  left,
31613
31675
  op: "BETWEEN",
31614
31676
  right: null,
@@ -31627,7 +31689,6 @@ var Parser = class {
31627
31689
  const right = this.parseAssertOperand();
31628
31690
  this.rejectAssertCompound();
31629
31691
  return {
31630
- type: "ASSERT",
31631
31692
  left,
31632
31693
  op,
31633
31694
  right,
@@ -31636,6 +31697,17 @@ var Parser = class {
31636
31697
  text: this.renderTokenRange(condStart, this.pos)
31637
31698
  };
31638
31699
  }
31700
+ /** ASSERT の dialect 1 メッセージ。カンマが無ければ既存形式。 */
31701
+ parseFlowMessage() {
31702
+ if (!this.consume("," /* COMMA */)) return void 0;
31703
+ this.requireDialect1(this.prev());
31704
+ return this.expect("STRING" /* STRING */, "ASSERT \u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u306B\u306F\u6587\u5B57\u5217\u30EA\u30C6\u30E9\u30EB\u304C\u5FC5\u8981\u3067\u3059").value;
31705
+ }
31706
+ requireDialect1(tok) {
31707
+ if (!this.capabilities.dialect1) {
31708
+ throw new ParseError("\u3053\u306E\u69CB\u6587\u306B\u306F -- @ksql dialect: 1 \u306E\u5BA3\u8A00\u304C\u5FC5\u8981\u3067\u3059", tok);
31709
+ }
31710
+ }
31639
31711
  /** ASSERT のオペランド: 文字列 / スカラーサブクエリ / 数値算術式 */
31640
31712
  parseAssertOperand() {
31641
31713
  const tok = this.peek();
@@ -33026,6 +33098,12 @@ var Parser = class {
33026
33098
  );
33027
33099
  }
33028
33100
  const name = this.parseTableName();
33101
+ if (this.capabilities.dialect1 && this.bareTempTableNames.has(name)) {
33102
+ const normalizedName = `#${name}`;
33103
+ this.tempTableRefs.push({ ...this.prev(), value: normalizedName });
33104
+ const alias2 = this.consume("AS" /* AS */) ? this.parseTableAliasName() : this.tryParseImplicitAlias();
33105
+ return { appId: 0, alias: alias2, cteName: normalizedName };
33106
+ }
33029
33107
  if (nameTok.kind === "IDENT" /* IDENT */ && name.startsWith("#")) {
33030
33108
  this.tempTableRefs.push(this.prev());
33031
33109
  const alias2 = this.consume("AS" /* AS */) ? this.parseTableAliasName() : this.tryParseImplicitAlias();
@@ -33066,6 +33144,7 @@ var Parser = class {
33066
33144
  if (k === "IDENT" /* IDENT */ || k === "BIDENT" /* BIDENT */) {
33067
33145
  if (k === "IDENT" /* IDENT */ && this.peek().value.toUpperCase() === "VALIDATE" && this.peekAt(1).kind === "IDENT" /* IDENT */ && this.peekAt(1).value.toUpperCase() === "ONLY") return null;
33068
33146
  if (k === "IDENT" /* IDENT */ && this.peek().value.toUpperCase() === "CHECK" && this.peekAt(1).kind === "WHEN" /* WHEN */) return null;
33147
+ if (k === "IDENT" /* IDENT */ && this.peek().value.toUpperCase() === "KEY" && this.peekAt(1).kind === "(" /* LPAREN */) return null;
33069
33148
  return this.parseTableAliasName();
33070
33149
  }
33071
33150
  return null;
@@ -33966,6 +34045,15 @@ var Parser = class {
33966
34045
  };
33967
34046
  }
33968
34047
  parseOnDuplicate() {
34048
+ if (this.capabilities.dialect1 && this.consumeSoftKeyword("KEY")) {
34049
+ this.expect("(" /* LPAREN */, "KEY \u306E\u5F8C\u306B\u306F (\u30AD\u30FC\u30D5\u30A3\u30FC\u30EB\u30C9) \u304C\u5FC5\u8981\u3067\u3059");
34050
+ const keyFields2 = this.parseIdentList();
34051
+ this.expect(")" /* RPAREN */);
34052
+ if (keyFields2.length === 0) {
34053
+ throw new ParseError("KEY \u306B\u306F\u30AD\u30FC\u30D5\u30A3\u30FC\u30EB\u30C9\u304C\u6700\u4F4E 1 \u3064\u5FC5\u8981\u3067\u3059", this.prev());
34054
+ }
34055
+ return keyFields2;
34056
+ }
33969
34057
  this.expectKeyword("ON" /* ON */, "UPSERT \u306B\u306F ON DUPLICATE (\u30AD\u30FC\u30D5\u30A3\u30FC\u30EB\u30C9) \u304C\u5FC5\u8981\u3067\u3059");
33970
34058
  if (!this.consume("DUPLICATE" /* DUPLICATE */)) {
33971
34059
  throw new ParseError("ON \u306E\u5F8C\u306B\u306F DUPLICATE \u304C\u5FC5\u8981\u3067\u3059", this.peek());
@@ -33978,6 +34066,238 @@ var Parser = class {
33978
34066
  }
33979
34067
  return keyFields;
33980
34068
  }
34069
+ parseMergeAsUpsert() {
34070
+ const mergeToken = this.advance();
34071
+ this.expect("INTO" /* INTO */, "MERGE \u306E\u5F8C\u306B\u306F INTO \u304C\u5FC5\u8981\u3067\u3059");
34072
+ this.rejectTempTableDml();
34073
+ const targetName = this.parseIdentifier();
34074
+ const { appId, subtableCode } = extractTableRef(targetName, this.prev());
34075
+ if (subtableCode) {
34076
+ throw new ParseError("MERGE \u306F\u307E\u3060\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u4EEE\u60F3\u30C6\u30FC\u30D6\u30EB\u306B\u5BFE\u5FDC\u3057\u3066\u3044\u307E\u305B\u3093", this.prev());
34077
+ }
34078
+ this.expect("AS" /* AS */, "MERGE \u306E\u30BF\u30FC\u30B2\u30C3\u30C8\u306B\u306F AS alias \u304C\u5FC5\u8981\u3067\u3059");
34079
+ const targetAlias = this.parseTableAliasName();
34080
+ this.expectSoftKeyword("USING", "MERGE \u306B\u306F USING <source> AS alias \u304C\u5FC5\u8981\u3067\u3059");
34081
+ const sourceStart = this.pos;
34082
+ const source = this.parseTableRef();
34083
+ const explicitSourceAlias = this.tokens.slice(sourceStart, this.pos).some((token) => token.kind === "AS" /* AS */);
34084
+ if (!explicitSourceAlias || source.alias === null) {
34085
+ throw new ParseError("MERGE \u306E USING \u30BD\u30FC\u30B9\u306B\u306F AS alias \u304C\u5FC5\u8981\u3067\u3059", this.peek());
34086
+ }
34087
+ const sourceAlias = source.alias;
34088
+ this.expect("ON" /* ON */, "MERGE \u306B\u306F ON t.key = s.key \u306E\u5358\u4E00\u30AD\u30FC\u7B49\u5024\u304C\u5FC5\u8981\u3067\u3059");
34089
+ const left = this.parseMergeQualifiedField("MERGE \u306E ON \u5DE6\u8FBA\u306F targetAlias.key \u306E\u5F62\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
34090
+ if (!this.consume("=" /* EQ */)) {
34091
+ throw new ParseError(
34092
+ "MERGE \u306E ON \u306F\u5358\u4E00\u30AD\u30FC\u306E\u7B49\u5024\uFF08t.key = s.key\uFF09\u306E\u307F\u5BFE\u5FDC\u3057\u3066\u3044\u307E\u3059\u3002\u8907\u6570\u6761\u4EF6\u3084\u975E\u7B49\u5024\u306F\u9023\u7D50\u30AD\u30FC\u30D5\u30A3\u30FC\u30EB\u30C9\u3067\u7F6E\u304D\u63DB\u3048\u3066\u304F\u3060\u3055\u3044",
34093
+ this.peek()
34094
+ );
34095
+ }
34096
+ const right = this.parseMergeQualifiedField("MERGE \u306E ON \u53F3\u8FBA\u306F sourceAlias.key \u306E\u5F62\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
34097
+ if (left.alias.toLowerCase() !== targetAlias.toLowerCase() || right.alias.toLowerCase() !== sourceAlias.toLowerCase()) {
34098
+ throw new ParseError(
34099
+ `MERGE \u306E ON \u306F ${targetAlias}.key = ${sourceAlias}.key \u306E\u5225\u540D\u4FEE\u98FE\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044`,
34100
+ mergeToken
34101
+ );
34102
+ }
34103
+ if (this.peek().kind === "AND" /* AND */ || this.peek().kind === "OR" /* OR */) {
34104
+ throw new ParseError(
34105
+ "MERGE \u306E ON \u306F\u5358\u4E00\u30AD\u30FC\u306E\u7B49\u5024\u306E\u307F\u5BFE\u5FDC\u3057\u3066\u3044\u307E\u3059\u3002\u8907\u6570\u6761\u4EF6\u306F\u9023\u7D50\u30AD\u30FC\u30D5\u30A3\u30FC\u30EB\u30C9\u3067\u7F6E\u304D\u63DB\u3048\u3066\u304F\u3060\u3055\u3044",
34106
+ this.peek()
34107
+ );
34108
+ }
34109
+ let matched = null;
34110
+ let insertFields = null;
34111
+ let insertValues = null;
34112
+ while (this.peek().kind === "WHEN" /* WHEN */) {
34113
+ const whenToken = this.advance();
34114
+ if (this.consume("NOT" /* NOT */)) {
34115
+ this.expectSoftKeyword("MATCHED", "WHEN NOT \u306E\u5F8C\u306B\u306F MATCHED \u304C\u5FC5\u8981\u3067\u3059");
34116
+ if (insertFields !== null) throw new ParseError("WHEN NOT MATCHED \u53E5\u304C\u91CD\u8907\u3057\u3066\u3044\u307E\u3059", whenToken);
34117
+ this.expect("THEN" /* THEN */, "WHEN NOT MATCHED \u306E\u5F8C\u306B\u306F THEN \u304C\u5FC5\u8981\u3067\u3059");
34118
+ this.expect("INSERT" /* INSERT */, "WHEN NOT MATCHED THEN \u306E\u5F8C\u306B\u306F INSERT \u304C\u5FC5\u8981\u3067\u3059");
34119
+ this.expect("(" /* LPAREN */, "MERGE INSERT \u306B\u306F\u5217\u30EA\u30B9\u30C8\u304C\u5FC5\u8981\u3067\u3059");
34120
+ insertFields = this.parseIdentList();
34121
+ this.expect(")" /* RPAREN */);
34122
+ this.expect("VALUES" /* VALUES */, "MERGE INSERT \u306E\u5217\u30EA\u30B9\u30C8\u306E\u5F8C\u306B\u306F VALUES \u304C\u5FC5\u8981\u3067\u3059");
34123
+ this.expect("(" /* LPAREN */, "MERGE INSERT VALUES \u306F ( \u3067\u59CB\u3081\u3066\u304F\u3060\u3055\u3044");
34124
+ insertValues = this.parseMergeValueList();
34125
+ this.expect(")" /* RPAREN */);
34126
+ if (insertFields.length !== insertValues.length) {
34127
+ throw new ParseError("MERGE INSERT \u306E\u5217\u6570\u3068 VALUES \u306E\u5024\u6570\u304C\u4E00\u81F4\u3057\u307E\u305B\u3093", whenToken);
34128
+ }
34129
+ } else {
34130
+ this.expectSoftKeyword("MATCHED", "WHEN \u306E\u5F8C\u306B\u306F MATCHED \u307E\u305F\u306F NOT MATCHED \u304C\u5FC5\u8981\u3067\u3059");
34131
+ if (matched !== null) throw new ParseError("WHEN MATCHED \u53E5\u304C\u91CD\u8907\u3057\u3066\u3044\u307E\u3059", whenToken);
34132
+ this.expect("THEN" /* THEN */, "WHEN MATCHED \u306E\u5F8C\u306B\u306F THEN \u304C\u5FC5\u8981\u3067\u3059");
34133
+ this.expect("UPDATE" /* UPDATE */, "WHEN MATCHED THEN \u306E\u5F8C\u306B\u306F UPDATE \u304C\u5FC5\u8981\u3067\u3059");
34134
+ this.expect("SET" /* SET */, "WHEN MATCHED THEN UPDATE \u306E\u5F8C\u306B\u306F SET \u304C\u5FC5\u8981\u3067\u3059");
34135
+ matched = this.parseMergeAssignments(targetAlias);
34136
+ }
34137
+ }
34138
+ if (matched === null || insertFields === null || insertValues === null) {
34139
+ throw new ParseError(
34140
+ "WHEN MATCHED / WHEN NOT MATCHED \u306E\u4E21\u53E5\u304C\u5FC5\u8981\u3067\u3059\uFF08\u66F4\u65B0\u306E\u307F\u306F UPDATE ... FROM\u3001\u633F\u5165\u306E\u307F\u306F INSERT ... SELECT \u3092\u4F7F\u7528\u3057\u3066\u304F\u3060\u3055\u3044\uFF09",
34141
+ this.peek()
34142
+ );
34143
+ }
34144
+ if (!insertFields.some((field) => field.toLowerCase() === left.field.toLowerCase())) {
34145
+ throw new ParseError(
34146
+ `MERGE \u306E ON \u30AD\u30FC ${left.field} \u306F INSERT \u5217\u30EA\u30B9\u30C8\u306B\u542B\u3081\u3066\u304F\u3060\u3055\u3044`,
34147
+ mergeToken
34148
+ );
34149
+ }
34150
+ const expressions = /* @__PURE__ */ new Map();
34151
+ insertFields.forEach((field, index) => expressions.set(field.toLowerCase(), insertValues[index]));
34152
+ for (const assignment of matched) {
34153
+ const key = assignment.field.toLowerCase();
34154
+ const existing = expressions.get(key);
34155
+ if (existing !== void 0 && !this.mergeExpressionsEqual(existing, assignment.value, sourceAlias)) {
34156
+ throw new ParseError(
34157
+ `MERGE \u306E\u5217 ${assignment.field} \u306F\u4E21\u53E5\u306E\u5F0F\u304C\u4E00\u81F4\u3059\u308B\u5834\u5408\u306E\u307F MERGE \u3092 UPSERT \u3078\u6B63\u898F\u5316\u3067\u304D\u307E\u3059`,
34158
+ mergeToken
34159
+ );
34160
+ }
34161
+ if (existing === void 0) {
34162
+ insertFields.push(assignment.field);
34163
+ insertValues.push(assignment.value);
34164
+ expressions.set(key, assignment.value);
34165
+ }
34166
+ }
34167
+ const columns = insertValues.map((value) => this.mergeValueToSelectColumn(value, sourceAlias, mergeToken));
34168
+ const normalizedSource = source.cteName !== null ? { ...source, alias: null } : { ...source, alias: `APP${source.appId}${source.subtableCode ? `$${source.subtableCode}` : ""}` };
34169
+ const select = {
34170
+ type: "SELECT",
34171
+ distinct: false,
34172
+ columns,
34173
+ from: normalizedSource,
34174
+ joins: [],
34175
+ where: null,
34176
+ groupBy: [],
34177
+ having: null,
34178
+ orderMode: "CANONICAL",
34179
+ orderBy: [],
34180
+ limit: null,
34181
+ offset: null
34182
+ };
34183
+ const checkGroups = this.parseCheckGroups();
34184
+ const validation = this.parseDmlControlSuffix();
34185
+ return {
34186
+ type: "UPSERT_SELECT",
34187
+ appId,
34188
+ fields: insertFields,
34189
+ select,
34190
+ keyFields: [left.field],
34191
+ ...checkGroups,
34192
+ ...validation
34193
+ };
34194
+ }
34195
+ parseMergeQualifiedField(message) {
34196
+ const token = this.peek();
34197
+ const path = this.parseFieldPath();
34198
+ const ref = this.splitQualifiedField(path);
34199
+ if (ref.alias === null) throw new ParseError(message, token);
34200
+ return { alias: ref.alias, field: ref.field };
34201
+ }
34202
+ parseMergeAssignments(targetAlias) {
34203
+ const assignments = [];
34204
+ do {
34205
+ const token = this.peek();
34206
+ const path = this.parseFieldPath();
34207
+ const ref = this.splitQualifiedField(path);
34208
+ if (ref.alias !== null && ref.alias.toLowerCase() !== targetAlias.toLowerCase()) {
34209
+ throw new ParseError(`MERGE UPDATE SET \u306E\u5DE6\u8FBA\u306F target alias ${targetAlias} \u3067\u4FEE\u98FE\u3057\u3066\u304F\u3060\u3055\u3044`, token);
34210
+ }
34211
+ this.expect("=" /* EQ */);
34212
+ assignments.push({ field: ref.field, value: this.parseAssignmentValue() });
34213
+ } while (this.consume("," /* COMMA */));
34214
+ return assignments;
34215
+ }
34216
+ parseMergeValueList() {
34217
+ const values = [];
34218
+ if (this.peek().kind === ")" /* RPAREN */) return values;
34219
+ do
34220
+ values.push(this.parseAssignmentValue());
34221
+ while (this.consume("," /* COMMA */));
34222
+ return values;
34223
+ }
34224
+ mergeExpressionsEqual(left, right, sourceAlias) {
34225
+ return this.mergeNormalizedValueEqual(
34226
+ this.normalizeMergeValue(left, sourceAlias, true),
34227
+ this.normalizeMergeValue(right, sourceAlias, true)
34228
+ );
34229
+ }
34230
+ normalizeMergeValue(value, sourceAlias, compareLiteralValues = false) {
34231
+ if (Array.isArray(value)) {
34232
+ return value.map((item) => this.normalizeMergeValue(item, sourceAlias, compareLiteralValues));
34233
+ }
34234
+ if (value === null || typeof value !== "object") return value;
34235
+ const obj = value;
34236
+ if (compareLiteralValues && obj["type"] === "NUMBER") {
34237
+ return { type: "NUMBER", value: obj["value"] };
34238
+ }
34239
+ if (obj["type"] === "SOURCE_FIELD") {
34240
+ if (String(obj["alias"]).toLowerCase() !== sourceAlias.toLowerCase()) return { type: "INVALID_SOURCE" };
34241
+ return { type: "FIELD_REF", field: obj["field"] };
34242
+ }
34243
+ if (obj["type"] === "FIELD_REF" && typeof obj["field"] === "string") {
34244
+ const ref = this.splitQualifiedField(obj["field"]);
34245
+ if (ref.alias !== null && ref.alias.toLowerCase() !== sourceAlias.toLowerCase()) return { type: "INVALID_SOURCE" };
34246
+ return { ...obj, field: ref.field };
34247
+ }
34248
+ if (obj["type"] === "FIELD" && typeof obj["tableAlias"] === "string") {
34249
+ if (obj["tableAlias"].toLowerCase() !== sourceAlias.toLowerCase()) return { type: "INVALID_SOURCE" };
34250
+ return { ...obj, tableAlias: null };
34251
+ }
34252
+ return Object.fromEntries(Object.entries(obj).map(([key, child]) => [
34253
+ key,
34254
+ this.normalizeMergeValue(child, sourceAlias, compareLiteralValues)
34255
+ ]));
34256
+ }
34257
+ mergeNormalizedValueEqual(left, right) {
34258
+ if (left === right) return true;
34259
+ if (Array.isArray(left) || Array.isArray(right)) {
34260
+ return Array.isArray(left) && Array.isArray(right) && left.length === right.length && left.every((item, index) => this.mergeNormalizedValueEqual(item, right[index]));
34261
+ }
34262
+ if (left === null || right === null || typeof left !== "object" || typeof right !== "object") return false;
34263
+ const leftObj = left;
34264
+ const rightObj = right;
34265
+ const leftKeys = Object.keys(leftObj);
34266
+ const rightKeys = Object.keys(rightObj);
34267
+ return leftKeys.length === rightKeys.length && leftKeys.every((key) => Object.prototype.hasOwnProperty.call(rightObj, key) && this.mergeNormalizedValueEqual(leftObj[key], rightObj[key]));
34268
+ }
34269
+ mergeValueToSelectColumn(value, sourceAlias, token) {
34270
+ const normalized = this.normalizeMergeValue(value, sourceAlias);
34271
+ if (this.mergeValueContainsInvalidSource(normalized)) {
34272
+ throw new ParseError(`MERGE \u306E\u5F0F\u306F source alias ${sourceAlias} \u306E\u30D5\u30A3\u30FC\u30EB\u30C9\u3060\u3051\u3092\u53C2\u7167\u3057\u3066\u304F\u3060\u3055\u3044`, token);
34273
+ }
34274
+ const expr = normalized;
34275
+ switch (expr["type"]) {
34276
+ case "FIELD_REF":
34277
+ return { type: "FIELD", field: String(expr["field"]), alias: null };
34278
+ case "STRING":
34279
+ return { type: "LITERAL_COL", value: String(expr["value"]), alias: null };
34280
+ case "NUMBER":
34281
+ return { type: "ARITH_COL", expr, alias: null };
34282
+ case "ARITH":
34283
+ return { type: "ARITH_COL", expr, alias: null };
34284
+ case "STRING_FUNC":
34285
+ return { type: "STRFUNC_COL", expr, alias: null };
34286
+ case "CASE_VALUE":
34287
+ return { type: "CASE_COL", expr: expr["expr"], alias: null };
34288
+ default:
34289
+ throw new ParseError(
34290
+ "MERGE \u306E\u4EE3\u5165\u5F0F\u306F\u30BD\u30FC\u30B9\u30D5\u30A3\u30FC\u30EB\u30C9\u30FB\u30EA\u30C6\u30E9\u30EB\u30FB\u7B97\u8853\u5F0F\u30FB\u6587\u5B57\u5217\u95A2\u6570\u30FBCASE \u306E\u3044\u305A\u308C\u304B\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044",
34291
+ token
34292
+ );
34293
+ }
34294
+ }
34295
+ mergeValueContainsInvalidSource(value) {
34296
+ if (Array.isArray(value)) return value.some((item) => this.mergeValueContainsInvalidSource(item));
34297
+ if (value === null || typeof value !== "object") return false;
34298
+ const obj = value;
34299
+ return obj["type"] === "INVALID_SOURCE" || Object.values(obj).some((item) => this.mergeValueContainsInvalidSource(item));
34300
+ }
33981
34301
  isUpsertApplyBranchStart() {
33982
34302
  return this.peek().kind === "ON" /* ON */ && (this.peekAt(1).kind === "INSERT" /* INSERT */ || this.peekAt(1).kind === "UPDATE" /* UPDATE */);
33983
34303
  }
@@ -34798,7 +35118,7 @@ function isDmlType(type) {
34798
35118
  return type === "INSERT" || type === "INSERT_SELECT" || type === "UPDATE" || type === "DELETE" || type === "UPSERT" || type === "UPSERT_SELECT" || type === "REORDER" || type === "IMPORT";
34799
35119
  }
34800
35120
  function isReadOnlyType(type) {
34801
- return type === "SELECT" || type === "VALIDATE" || type === "UNION" || type === "WITH" || type === "EXPLAIN" || type === "SHOW_APPS" || type === "DESCRIBE" || type === "CREATE_TEMP_TABLE" || type === "DROP_TEMP_TABLE" || type === "SET_VARIABLE" || type === "DECLARE_VARIABLE" || type === "ASSERT";
35121
+ return type === "SELECT" || type === "VALIDATE" || type === "UNION" || type === "WITH" || type === "EXPLAIN" || type === "SHOW_APPS" || type === "DESCRIBE" || type === "CREATE_TEMP_TABLE" || type === "DROP_TEMP_TABLE" || type === "SET_VARIABLE" || type === "DECLARE_VARIABLE" || type === "ASSERT" || type === "EXIT";
34802
35122
  }
34803
35123
  function writesKintone(stmt) {
34804
35124
  return isDmlType(stmt.type) && !("validateOnly" in stmt && stmt.validateOnly === true);
@@ -38194,6 +38514,7 @@ function validateStatement(stmt) {
38194
38514
  case "SET_VARIABLE":
38195
38515
  case "DECLARE_VARIABLE":
38196
38516
  case "ASSERT":
38517
+ case "EXIT":
38197
38518
  validateNestedSelects(stmt);
38198
38519
  return;
38199
38520
  case "UPDATE":
@@ -39333,15 +39654,15 @@ function selectScalarExtreme(values, extreme) {
39333
39654
  }
39334
39655
 
39335
39656
  // src/engine/evalFunc.ts
39336
- function evalArithExpr(expr, row) {
39657
+ function evalArithExpr(expr, row, context = {}) {
39337
39658
  if (expr.type === "VARIABLE") throw new Error(
39338
39659
  `InternalError: unresolved arithmetic variable @${expr.name} reached arithmetic evaluation.`
39339
39660
  );
39340
39661
  if (expr.type === "NUMBER") return expr.value;
39341
39662
  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);
39663
+ if (expr.type === "STRING_FUNC") return Number(evalStringFunc(expr, row, void 0, void 0, context));
39664
+ const l = evalArithExpr(expr.left, row, context);
39665
+ const r = evalArithExpr(expr.right, row, context);
39345
39666
  switch (expr.op) {
39346
39667
  case "+":
39347
39668
  return l + r;
@@ -39355,7 +39676,7 @@ function evalArithExpr(expr, row) {
39355
39676
  return r !== 0 ? l % r : NaN;
39356
39677
  }
39357
39678
  }
39358
- function evalScalarValueExpr(expr, row, resolveFieldType, resolveFieldSemantics2) {
39679
+ function evalScalarValueExpr(expr, row, resolveFieldType, resolveFieldSemantics2, context = {}) {
39359
39680
  switch (expr.type) {
39360
39681
  case "STRING":
39361
39682
  return expr.value;
@@ -39366,19 +39687,19 @@ function evalScalarValueExpr(expr, row, resolveFieldType, resolveFieldSemantics2
39366
39687
  case "VARIABLE":
39367
39688
  throw new Error(`ArgumentError: unresolved variable @${expr.name} reached scalar evaluator.`);
39368
39689
  case "STRING_FUNC":
39369
- return evalStringFunc(expr, row, resolveFieldType, resolveFieldSemantics2);
39690
+ return evalStringFunc(expr, row, resolveFieldType, resolveFieldSemantics2, context);
39370
39691
  case "CASE_WHEN":
39371
- return evalCaseWhen(expr, row, resolveFieldType, resolveFieldSemantics2);
39692
+ return evalCaseWhen(expr, row, resolveFieldType, resolveFieldSemantics2, context);
39372
39693
  case "CONCAT_OP": {
39373
39694
  return evalStringFunc({
39374
39695
  type: "STRING_FUNC",
39375
39696
  func: "CONCAT",
39376
39697
  args: [expr.left, expr.right]
39377
- }, row, resolveFieldType, resolveFieldSemantics2);
39698
+ }, row, resolveFieldType, resolveFieldSemantics2, context);
39378
39699
  }
39379
39700
  case "SCALAR_ARITH": {
39380
- const left = Number(evalScalarValueExpr(expr.left, row, resolveFieldType, resolveFieldSemantics2));
39381
- const right = Number(evalScalarValueExpr(expr.right, row, resolveFieldType, resolveFieldSemantics2));
39701
+ const left = Number(evalScalarValueExpr(expr.left, row, resolveFieldType, resolveFieldSemantics2, context));
39702
+ const right = Number(evalScalarValueExpr(expr.right, row, resolveFieldType, resolveFieldSemantics2, context));
39382
39703
  switch (expr.op) {
39383
39704
  case "+":
39384
39705
  return left + right;
@@ -39394,13 +39715,13 @@ function evalScalarValueExpr(expr, row, resolveFieldType, resolveFieldSemantics2
39394
39715
  }
39395
39716
  }
39396
39717
  }
39397
- function evalScalarValueExprNullable(expr, row, resolveFieldType, resolveFieldSemantics2) {
39718
+ function evalScalarValueExprNullable(expr, row, resolveFieldType, resolveFieldSemantics2, context = {}) {
39398
39719
  switch (expr.type) {
39399
39720
  case "CASE_WHEN":
39400
- return evalCaseWhenNullable(expr, row, resolveFieldType, resolveFieldSemantics2);
39721
+ return evalCaseWhenNullable(expr, row, resolveFieldType, resolveFieldSemantics2, context);
39401
39722
  case "SCALAR_ARITH": {
39402
- const left = evalScalarValueExprNullable(expr.left, row, resolveFieldType, resolveFieldSemantics2);
39403
- const right = evalScalarValueExprNullable(expr.right, row, resolveFieldType, resolveFieldSemantics2);
39723
+ const left = evalScalarValueExprNullable(expr.left, row, resolveFieldType, resolveFieldSemantics2, context);
39724
+ const right = evalScalarValueExprNullable(expr.right, row, resolveFieldType, resolveFieldSemantics2, context);
39404
39725
  if (left === null || right === null) return null;
39405
39726
  const l = Number(left);
39406
39727
  const r = Number(right);
@@ -39418,12 +39739,12 @@ function evalScalarValueExprNullable(expr, row, resolveFieldType, resolveFieldSe
39418
39739
  }
39419
39740
  }
39420
39741
  case "CONCAT_OP": {
39421
- const left = evalScalarValueExprNullable(expr.left, row, resolveFieldType, resolveFieldSemantics2);
39422
- const right = evalScalarValueExprNullable(expr.right, row, resolveFieldType, resolveFieldSemantics2);
39742
+ const left = evalScalarValueExprNullable(expr.left, row, resolveFieldType, resolveFieldSemantics2, context);
39743
+ const right = evalScalarValueExprNullable(expr.right, row, resolveFieldType, resolveFieldSemantics2, context);
39423
39744
  return `${left ?? ""}${right ?? ""}`;
39424
39745
  }
39425
39746
  default:
39426
- return evalScalarValueExpr(expr, row, resolveFieldType, resolveFieldSemantics2);
39747
+ return evalScalarValueExpr(expr, row, resolveFieldType, resolveFieldSemantics2, context);
39427
39748
  }
39428
39749
  }
39429
39750
  function applyRoundOp(op, num, digits) {
@@ -39575,9 +39896,9 @@ function replaceNthMatch(input, globalRe, replacement, n) {
39575
39896
  return expandRegexpReplacement(replacement, match, captures, namedGroups);
39576
39897
  });
39577
39898
  }
39578
- function evalStringFunc(expr, row, resolveFieldType, resolveFieldSemantics2) {
39899
+ function evalStringFunc(expr, row, resolveFieldType, resolveFieldSemantics2, context = {}) {
39579
39900
  assertStringFunctionArity(expr.func, expr.args);
39580
- const args = expr.args.map((a) => evalStringFuncArg(a, row, resolveFieldType, resolveFieldSemantics2));
39901
+ const args = expr.args.map((a) => evalStringFuncArg(a, row, resolveFieldType, resolveFieldSemantics2, context));
39581
39902
  switch (expr.func) {
39582
39903
  case "UPPER":
39583
39904
  return (args[0] ?? "").toUpperCase();
@@ -39725,14 +40046,14 @@ function evalStringFunc(expr, row, resolveFieldType, resolveFieldSemantics2) {
39725
40046
  case "SQRT":
39726
40047
  return String(Math.sqrt(Number(args[0] ?? "0")));
39727
40048
  case "CURRENT_DATE": {
39728
- const now = /* @__PURE__ */ new Date();
40049
+ const now = context.statementInstant ?? /* @__PURE__ */ new Date();
39729
40050
  const y = now.getFullYear();
39730
40051
  const m = String(now.getMonth() + 1).padStart(2, "0");
39731
40052
  const d = String(now.getDate()).padStart(2, "0");
39732
40053
  return `${y}-${m}-${d}`;
39733
40054
  }
39734
40055
  case "CURRENT_TIMESTAMP":
39735
- return (/* @__PURE__ */ new Date()).toISOString();
40056
+ return (context.statementInstant ?? /* @__PURE__ */ new Date()).toISOString();
39736
40057
  }
39737
40058
  }
39738
40059
  function parseDateParts(s) {
@@ -39894,12 +40215,12 @@ function formatWithComma(num, digits) {
39894
40215
  const intFmt = intStr.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
39895
40216
  return decStr ? `${intFmt}.${decStr}` : intFmt;
39896
40217
  }
39897
- function evalStringFuncArg(arg, row, resolveFieldType, resolveFieldSemantics2) {
40218
+ function evalStringFuncArg(arg, row, resolveFieldType, resolveFieldSemantics2, context = {}) {
39898
40219
  if (arg.type === "AGG_REF" || arg.type === "AGG_ARITH" || arg.type === "AGG_GROUP_KEY") {
39899
40220
  return String(evalMaterializedAggregateOperand(arg, row));
39900
40221
  }
39901
40222
  if (arg.type === "NUMBER") return numberLiteralText(arg);
39902
- return String(evalScalarValueExpr(arg, row, resolveFieldType, resolveFieldSemantics2));
40223
+ return String(evalScalarValueExpr(arg, row, resolveFieldType, resolveFieldSemantics2, context));
39903
40224
  }
39904
40225
  function evalMaterializedAggregateOperand(node, row) {
39905
40226
  if (node.type === "NUMBER") return node.value;
@@ -39940,37 +40261,37 @@ function resolveFieldRef(row, field) {
39940
40261
  }
39941
40262
 
39942
40263
  // src/engine/evalWhere.ts
39943
- function evalWhere(expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2) {
40264
+ function evalWhere(expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2, context = {}) {
39944
40265
  switch (expr.type) {
39945
40266
  case "BOOLEAN":
39946
40267
  return expr.value;
39947
40268
  case "BINARY":
39948
- return evalBinary(expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2);
40269
+ return evalBinary(expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2, context);
39949
40270
  case "NULL_CHECK":
39950
40271
  return evalNullCheck(expr, row);
39951
40272
  case "LOGICAL":
39952
- return evalLogical(expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2);
40273
+ return evalLogical(expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2, context);
39953
40274
  case "NOT":
39954
- return !evalWhere(expr.expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2);
40275
+ return !evalWhere(expr.expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2, context);
39955
40276
  case "GROUP":
39956
- return evalWhere(expr.expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2);
40277
+ return evalWhere(expr.expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2, context);
39957
40278
  case "EXISTS": {
39958
40279
  const exists = expr.resolved;
39959
40280
  return expr.not ? !exists : exists;
39960
40281
  }
39961
40282
  }
39962
40283
  }
39963
- function evalBinary(expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2) {
40284
+ function evalBinary(expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2, context = {}) {
39964
40285
  if (expr.op === "KLIKE" || expr.op === "NOT_KLIKE") {
39965
40286
  if (appliedKlikes?.has(expr)) return true;
39966
40287
  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
40288
  }
39968
- const left = resolveField(expr.left, row, resolveFieldType, resolveFieldSemantics2);
40289
+ const left = resolveField(expr.left, row, resolveFieldType, resolveFieldSemantics2, context);
39969
40290
  const fieldType = expr.left.type === "FIELD" ? resolveFieldType?.(expr.left) : void 0;
39970
40291
  const semantics = semanticsForLeft(expr.left, fieldType, resolveFieldSemantics2);
39971
- return evalOp(expr.op, left, expr.right, row, fieldType, resolveFieldType, semantics, resolveFieldSemantics2);
40292
+ return evalOp(expr.op, left, expr.right, row, fieldType, resolveFieldType, semantics, resolveFieldSemantics2, context);
39972
40293
  }
39973
- function evalOp(op, leftStr, right, row, fieldType, resolveFieldType, semantics = syntheticSemantics("string"), resolveFieldSemantics2) {
40294
+ function evalOp(op, leftStr, right, row, fieldType, resolveFieldType, semantics = syntheticSemantics("string"), resolveFieldSemantics2, context = {}) {
39974
40295
  if (op === "IN" || op === "NOT_IN") {
39975
40296
  let values = null;
39976
40297
  if (right.type === "IN_LIST") {
@@ -39985,17 +40306,17 @@ function evalOp(op, leftStr, right, row, fieldType, resolveFieldType, semantics
39985
40306
  return op === "IN" ? contains : !contains;
39986
40307
  }
39987
40308
  if (op === "LIKE") {
39988
- const pattern = resolveValue(right, row, resolveFieldType);
40309
+ const pattern = resolveValue(right, row, resolveFieldType, void 0, context);
39989
40310
  return matchLike(leftStr, pattern);
39990
40311
  }
39991
40312
  if (op === "NOT_LIKE") {
39992
- const pattern = resolveValue(right, row, resolveFieldType);
40313
+ const pattern = resolveValue(right, row, resolveFieldType, void 0, context);
39993
40314
  return !matchLike(leftStr, pattern);
39994
40315
  }
39995
40316
  if (op === "KLIKE" || op === "NOT_KLIKE") {
39996
40317
  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
40318
  }
39998
- const rightStr = resolveValue(right, row, resolveFieldType, resolveFieldSemantics2);
40319
+ const rightStr = resolveValue(right, row, resolveFieldType, resolveFieldSemantics2, context);
39999
40320
  return compareScalarValues(op, leftStr, rightStr, semantics);
40000
40321
  }
40001
40322
  var NUMERIC_STRING_FUNCTIONS = /* @__PURE__ */ new Set([
@@ -40107,17 +40428,17 @@ function evalNullCheck(expr, row) {
40107
40428
  const val = resolveField(expr.field, row);
40108
40429
  return expr.not ? val !== "" : val === "";
40109
40430
  }
40110
- function evalLogical(expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2) {
40431
+ function evalLogical(expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2, context = {}) {
40111
40432
  if (expr.op === "AND") {
40112
- return evalWhere(expr.left, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2) && evalWhere(expr.right, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2);
40433
+ return evalWhere(expr.left, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2, context) && evalWhere(expr.right, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2, context);
40113
40434
  }
40114
- return evalWhere(expr.left, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2) || evalWhere(expr.right, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2);
40435
+ return evalWhere(expr.left, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2, context) || evalWhere(expr.right, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2, context);
40115
40436
  }
40116
- function resolveField(field, row, resolveFieldType, resolveFieldSemantics2) {
40117
- if (field.type === "FUNC_FIELD") return evalStringFunc(field.expr, row);
40437
+ function resolveField(field, row, resolveFieldType, resolveFieldSemantics2, context = {}) {
40438
+ if (field.type === "FUNC_FIELD") return evalStringFunc(field.expr, row, void 0, void 0, context);
40118
40439
  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);
40440
+ if (field.type === "ARITH_FIELD") return String(evalArithExpr(field.expr, row, context));
40441
+ if (field.type === "CASE_FIELD") return evalCaseWhen(field.expr, row, resolveFieldType, resolveFieldSemantics2, context);
40121
40442
  if (field.type === "GROUPING_FIELD") return evalGroupingRef(field.ref, row);
40122
40443
  if (field.aggregateRef) {
40123
40444
  const ref = field.aggregateRef;
@@ -40126,7 +40447,7 @@ function resolveField(field, row, resolveFieldType, resolveFieldSemantics2) {
40126
40447
  const key = field.tableAlias ? `${field.tableAlias}.${field.field}` : field.field;
40127
40448
  return resolveFieldRef(row, key);
40128
40449
  }
40129
- function resolveValue(value, row, resolveFieldType, resolveFieldSemantics2) {
40450
+ function resolveValue(value, row, resolveFieldType, resolveFieldSemantics2, context = {}) {
40130
40451
  switch (value.type) {
40131
40452
  case "VARIABLE":
40132
40453
  throw new Error(`ParseError: unresolved batch variable @${value.name}.`);
@@ -40148,44 +40469,44 @@ function resolveValue(value, row, resolveFieldType, resolveFieldSemantics2) {
40148
40469
  return value.resolved;
40149
40470
  case "ARITH_VALUE":
40150
40471
  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));
40472
+ if (value.expr.type === "STRING_FUNC") return evalStringFunc(value.expr, row, void 0, void 0, context);
40473
+ return String(evalArithExpr(value.expr, row, context));
40153
40474
  case "CASE_VALUE":
40154
- return evalCaseWhen(value.expr, row, resolveFieldType, resolveFieldSemantics2);
40475
+ return evalCaseWhen(value.expr, row, resolveFieldType, resolveFieldSemantics2, context);
40155
40476
  case "ARRAY":
40156
40477
  return value.elements.map((e) => e.value).join(",");
40157
40478
  }
40158
40479
  }
40159
- function evalCaseWhen(expr, row, resolveFieldType, resolveFieldSemantics2) {
40480
+ function evalCaseWhen(expr, row, resolveFieldType, resolveFieldSemantics2, context = {}) {
40160
40481
  for (const branch of expr.branches) {
40161
- if (evalWhere(branch.condition, row, resolveFieldType, void 0, resolveFieldSemantics2)) {
40162
- return evalCaseResult(branch.result, row, resolveFieldType, resolveFieldSemantics2);
40482
+ if (evalWhere(branch.condition, row, resolveFieldType, void 0, resolveFieldSemantics2, context)) {
40483
+ return evalCaseResult(branch.result, row, resolveFieldType, resolveFieldSemantics2, context);
40163
40484
  }
40164
40485
  }
40165
40486
  if (expr.elseResult !== null) {
40166
- return evalCaseResult(expr.elseResult, row, resolveFieldType, resolveFieldSemantics2);
40487
+ return evalCaseResult(expr.elseResult, row, resolveFieldType, resolveFieldSemantics2, context);
40167
40488
  }
40168
40489
  return "";
40169
40490
  }
40170
- function evalCaseWhenNullable(expr, row, resolveFieldType, resolveFieldSemantics2) {
40491
+ function evalCaseWhenNullable(expr, row, resolveFieldType, resolveFieldSemantics2, context = {}) {
40171
40492
  for (const branch of expr.branches) {
40172
- if (evalWhere(branch.condition, row, resolveFieldType, void 0, resolveFieldSemantics2)) {
40173
- return evalCaseResultNullable(branch.result, row, resolveFieldType, resolveFieldSemantics2);
40493
+ if (evalWhere(branch.condition, row, resolveFieldType, void 0, resolveFieldSemantics2, context)) {
40494
+ return evalCaseResultNullable(branch.result, row, resolveFieldType, resolveFieldSemantics2, context);
40174
40495
  }
40175
40496
  }
40176
- return expr.elseResult === null ? null : evalCaseResultNullable(expr.elseResult, row, resolveFieldType, resolveFieldSemantics2);
40497
+ return expr.elseResult === null ? null : evalCaseResultNullable(expr.elseResult, row, resolveFieldType, resolveFieldSemantics2, context);
40177
40498
  }
40178
- function evalCaseResultNullable(result, row, resolveFieldType, resolveFieldSemantics2) {
40499
+ function evalCaseResultNullable(result, row, resolveFieldType, resolveFieldSemantics2, context = {}) {
40179
40500
  if (result.type === "ARRAY") return result.elements.map((entry) => entry.value).join(",");
40180
40501
  if (result.type === "AGG_REF") {
40181
40502
  return row[aggregateSyntheticName(result.func, result.distinct, result.arg)] ?? "";
40182
40503
  }
40183
40504
  if (result.type === "AGG_ARITH") return row[aggregateOperandLabel(result)] ?? "";
40184
40505
  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);
40506
+ if (result.type === "ARITH") return evalArithExpr(result, row, context);
40507
+ return evalScalarValueExprNullable(result, row, resolveFieldType, resolveFieldSemantics2, context);
40187
40508
  }
40188
- function evalCaseResult(result, row, resolveFieldType, resolveFieldSemantics2) {
40509
+ function evalCaseResult(result, row, resolveFieldType, resolveFieldSemantics2, context = {}) {
40189
40510
  if (result.type === "ARRAY") return result.elements.map((e) => e.value).join(",");
40190
40511
  if (result.type === "AGG_REF") {
40191
40512
  return row[aggregateSyntheticName(result.func, result.distinct, result.arg)] ?? "";
@@ -40195,12 +40516,12 @@ function evalCaseResult(result, row, resolveFieldType, resolveFieldSemantics2) {
40195
40516
  return row[result.field] ?? "";
40196
40517
  }
40197
40518
  if (result.type === "ARITH") {
40198
- return String(evalArithExpr(result, row));
40519
+ return String(evalArithExpr(result, row, context));
40199
40520
  }
40200
- return String(evalScalarValueExpr(result, row, resolveFieldType, resolveFieldSemantics2));
40521
+ return String(evalScalarValueExpr(result, row, resolveFieldType, resolveFieldSemantics2, context));
40201
40522
  }
40202
- function resolveKintoneFunc(name) {
40203
- const now = /* @__PURE__ */ new Date();
40523
+ function resolveKintoneFunc(name, context = {}) {
40524
+ const now = context.statementInstant ?? /* @__PURE__ */ new Date();
40204
40525
  switch (name) {
40205
40526
  case "TODAY": {
40206
40527
  const y = now.getFullYear();
@@ -40324,21 +40645,21 @@ function assertDmlWhereIsSafe(where) {
40324
40645
  }
40325
40646
  var USER_TYPES = /* @__PURE__ */ new Set(["USER_SELECT", "ORGANIZATION_SELECT", "GROUP_SELECT"]);
40326
40647
  var ARRAY_TYPES = /* @__PURE__ */ new Set(["CHECK_BOX", "MULTI_SELECT"]);
40327
- function insertToPostBatches(stmt, fieldTypes = /* @__PURE__ */ new Map()) {
40648
+ function insertToPostBatches(stmt, fieldTypes = /* @__PURE__ */ new Map(), evaluationContext = {}) {
40328
40649
  const allRecords = stmt.values.map(
40329
- (row) => buildInsertRecord(stmt.fields, row, fieldTypes)
40650
+ (row) => buildInsertRecord(stmt.fields, row, fieldTypes, evaluationContext)
40330
40651
  );
40331
40652
  return chunk(allRecords, 100).map((records) => ({
40332
40653
  app: stmt.appId,
40333
40654
  records
40334
40655
  }));
40335
40656
  }
40336
- function buildInsertRecord(fields, row, fieldTypes) {
40657
+ function buildInsertRecord(fields, row, fieldTypes, evaluationContext) {
40337
40658
  const record2 = {};
40338
40659
  fields.forEach((field, i) => {
40339
40660
  const val = row[i];
40340
40661
  if (val.type === "CASE_VALUE") {
40341
- record2[field] = { value: evalCaseWhenValue(val.expr, {}, fieldTypes.get(field)) };
40662
+ record2[field] = { value: evalCaseWhenValue(val.expr, {}, fieldTypes.get(field), evaluationContext) };
40342
40663
  } else {
40343
40664
  record2[field] = { value: toKintoneValue(val, fieldTypes.get(field)) };
40344
40665
  }
@@ -40498,14 +40819,14 @@ function collectConditionFields(expr, out) {
40498
40819
  break;
40499
40820
  }
40500
40821
  }
40501
- function updateToPutBatchesArith(stmt, records, fieldTypes = /* @__PURE__ */ new Map()) {
40822
+ function updateToPutBatchesArith(stmt, records, fieldTypes = /* @__PURE__ */ new Map(), evaluationContext = {}) {
40502
40823
  const updateRecords = records.map((raw) => {
40503
40824
  const id = Number(raw["$id"].value);
40504
40825
  const row = kintoneRecordToProcessRow(raw);
40505
40826
  const record2 = {};
40506
40827
  for (const { field, value } of stmt.assignments) {
40507
40828
  record2[field] = {
40508
- value: evaluateUpdateAssignmentValue(value, row, fieldTypes.get(field), raw)
40829
+ value: evaluateUpdateAssignmentValue(value, row, fieldTypes.get(field), raw, evaluationContext)
40509
40830
  };
40510
40831
  }
40511
40832
  return { id, record: record2 };
@@ -40515,25 +40836,31 @@ function updateToPutBatchesArith(stmt, records, fieldTypes = /* @__PURE__ */ new
40515
40836
  records: batch
40516
40837
  }));
40517
40838
  }
40518
- function evaluateUpdateAssignmentValue(value, row, fieldType, raw) {
40839
+ function evaluateUpdateAssignmentValue(value, row, fieldType, raw, evaluationContext = {}) {
40519
40840
  if (value.type === "ARITH") {
40520
- return String(raw ? evalArith(value, raw) : evalArithExpr(value, row));
40841
+ return String(raw ? evalArith(value, raw) : evalArithExpr(value, row, evaluationContext));
40521
40842
  }
40522
40843
  if (value.type === "SCALAR_ARITH" || value.type === "CONCAT_OP") {
40523
- return String(evalScalarValueExpr(value, row));
40844
+ return String(evalScalarValueExpr(value, row, void 0, void 0, evaluationContext));
40524
40845
  }
40525
- if (value.type === "STRING_FUNC") return evalStringFunc(value, row);
40526
- if (value.type === "CASE_VALUE") return evalCaseWhenValue(value.expr, row, fieldType);
40846
+ if (value.type === "STRING_FUNC") return evalStringFunc(value, row, void 0, void 0, evaluationContext);
40847
+ if (value.type === "CASE_VALUE") return evalCaseWhenValue(value.expr, row, fieldType, evaluationContext);
40527
40848
  if (value.type === "SOURCE_FIELD") {
40528
40849
  throw new DmlConvertError("SOURCE_FIELD \u306F UPDATE ... FROM \u5C02\u7528\u3067\u3059");
40529
40850
  }
40530
40851
  return toKintoneValue(value, fieldType);
40531
40852
  }
40532
- function evaluateSubtableAssignmentValue(value, row, resolveFieldType) {
40853
+ function evaluateSubtableAssignmentValue(value, row, resolveFieldType, evaluationContext = {}) {
40533
40854
  if (value.type === "STRING") return value.value;
40534
40855
  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);
40856
+ if (value.type === "ARITH") return String(evalArithExpr(value, row, evaluationContext));
40857
+ if (value.type === "CASE_VALUE") return evalCaseWhen(
40858
+ value.expr,
40859
+ row,
40860
+ resolveFieldType,
40861
+ void 0,
40862
+ evaluationContext
40863
+ );
40537
40864
  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
40865
  }
40539
40866
  var UPDATE_FROM_UNSUPPORTED_TYPES = /* @__PURE__ */ new Set([
@@ -40544,7 +40871,7 @@ var UPDATE_FROM_UNSUPPORTED_TYPES = /* @__PURE__ */ new Set([
40544
40871
  "GROUP_SELECT",
40545
40872
  "FILE"
40546
40873
  ]);
40547
- function updateFromToPutBatches(stmt, matched, fieldTypes = /* @__PURE__ */ new Map()) {
40874
+ function updateFromToPutBatches(stmt, matched, fieldTypes = /* @__PURE__ */ new Map(), evaluationContext = {}) {
40548
40875
  const updateRecords = matched.map(({ target, source }) => {
40549
40876
  const id = Number(target["$id"]?.value);
40550
40877
  if (!Number.isSafeInteger(id) || id <= 0) {
@@ -40574,9 +40901,20 @@ function updateFromToPutBatches(stmt, matched, fieldTypes = /* @__PURE__ */ new
40574
40901
  } else if (value.type === "ARITH") {
40575
40902
  record2[field] = { value: String(evalArith(value, target)) };
40576
40903
  } else if (value.type === "SCALAR_ARITH" || value.type === "CONCAT_OP") {
40577
- record2[field] = { value: String(evalScalarValueExpr(value, targetRow)) };
40904
+ record2[field] = { value: String(evalScalarValueExpr(
40905
+ value,
40906
+ targetRow,
40907
+ void 0,
40908
+ void 0,
40909
+ evaluationContext
40910
+ )) };
40578
40911
  } else if (value.type === "CASE_VALUE") {
40579
- record2[field] = { value: evalCaseWhenValue(value.expr, targetRow, fieldType) };
40912
+ record2[field] = { value: evalCaseWhenValue(
40913
+ value.expr,
40914
+ targetRow,
40915
+ fieldType,
40916
+ evaluationContext
40917
+ ) };
40580
40918
  } else {
40581
40919
  record2[field] = { value: toKintoneValue(value, fieldType) };
40582
40920
  }
@@ -40678,7 +41016,7 @@ function convertArray(elements, fieldType) {
40678
41016
  if (isUserType(fieldType)) return elements.map((c) => ({ code: c }));
40679
41017
  return elements;
40680
41018
  }
40681
- function evalCaseResultValue(result, row, fieldType) {
41019
+ function evalCaseResultValue(result, row, fieldType, evaluationContext) {
40682
41020
  if (result.type === "ARRAY") {
40683
41021
  return convertArray(result.elements.map((e) => e.value), fieldType);
40684
41022
  }
@@ -40689,26 +41027,26 @@ function evalCaseResultValue(result, row, fieldType) {
40689
41027
  return convertString2(result.value, fieldType);
40690
41028
  }
40691
41029
  if (result.type === "STRING_FUNC") {
40692
- return evalStringFunc(result, row);
41030
+ return evalStringFunc(result, row, void 0, void 0, evaluationContext);
40693
41031
  }
40694
41032
  if (result.type === "FIELD_REF" || result.type === "ARITH") {
40695
- return String(evalArithExpr(result, row));
41033
+ return String(evalArithExpr(result, row, evaluationContext));
40696
41034
  }
40697
- return String(evalScalarValueExpr(result, row));
41035
+ return String(evalScalarValueExpr(result, row, void 0, void 0, evaluationContext));
40698
41036
  }
40699
41037
  function collectUpdateCheckTargetFields(stmt) {
40700
41038
  if (!stmt.checkGroups) return [];
40701
41039
  const targetAlias = `app${stmt.appId}`.toLowerCase();
40702
41040
  return [...new Set(collectCheckFieldRefs(stmt.checkGroups).filter((ref) => ref.tableAlias === null || ref.tableAlias.toLowerCase() === targetAlias).map((ref) => ref.field).filter((field) => field !== "$id"))];
40703
41041
  }
40704
- function evalCaseWhenValue(expr, row, fieldType) {
41042
+ function evalCaseWhenValue(expr, row, fieldType, evaluationContext = {}) {
40705
41043
  for (const branch of expr.branches) {
40706
- if (evalWhere(branch.condition, row)) {
40707
- return evalCaseResultValue(branch.result, row, fieldType);
41044
+ if (evalWhere(branch.condition, row, void 0, void 0, void 0, evaluationContext)) {
41045
+ return evalCaseResultValue(branch.result, row, fieldType, evaluationContext);
40708
41046
  }
40709
41047
  }
40710
41048
  if (expr.elseResult !== null) {
40711
- return evalCaseResultValue(expr.elseResult, row, fieldType);
41049
+ return evalCaseResultValue(expr.elseResult, row, fieldType, evaluationContext);
40712
41050
  }
40713
41051
  return "";
40714
41052
  }
@@ -40987,18 +41325,30 @@ function buildApplyPatchPlan(input) {
40987
41325
  const parentId = requirePositiveInteger(snapshot["$id"]?.value, "APPLY snapshot $id");
40988
41326
  const expectedParentId = getApplyParentId(statement);
40989
41327
  if (parentId !== expectedParentId) argument2(`APPLY snapshot $id ${parentId} does not match requested $id ${expectedParentId}.`);
40990
- return buildApplyPatchPlanForSnapshot(statement, snapshot, metadata, parentId);
41328
+ return buildApplyPatchPlanForSnapshot(
41329
+ statement,
41330
+ snapshot,
41331
+ metadata,
41332
+ parentId,
41333
+ input.evaluationContext
41334
+ );
40991
41335
  }
40992
- function buildApplyPatchPlans(statement, snapshots, fieldInfos, metadata = resolveApplyPatchMetadata(statement, fieldInfos)) {
41336
+ function buildApplyPatchPlans(statement, snapshots, fieldInfos, metadata = resolveApplyPatchMetadata(statement, fieldInfos), evaluationContext = {}) {
40993
41337
  const parentIds = /* @__PURE__ */ new Set();
40994
41338
  return snapshots.map((snapshot) => {
40995
41339
  const parentId = requirePositiveInteger(snapshot["$id"]?.value, "APPLY snapshot $id");
40996
41340
  if (parentIds.has(parentId)) argument2(`APPLY snapshots contain duplicate parentId ${parentId}.`);
40997
41341
  parentIds.add(parentId);
40998
- return buildApplyPatchPlanForSnapshot(statement, snapshot, metadata, parentId);
41342
+ return buildApplyPatchPlanForSnapshot(
41343
+ statement,
41344
+ snapshot,
41345
+ metadata,
41346
+ parentId,
41347
+ evaluationContext
41348
+ );
40999
41349
  });
41000
41350
  }
41001
- function buildApplyPatchPlanForSnapshot(statement, snapshot, metadata, parentId) {
41351
+ function buildApplyPatchPlanForSnapshot(statement, snapshot, metadata, parentId, evaluationContext = {}) {
41002
41352
  const revision = requirePositiveInteger(snapshot["$revision"]?.value, "APPLY snapshot $revision");
41003
41353
  const tablePlans = [];
41004
41354
  const multiValuePlans = [];
@@ -41027,13 +41377,24 @@ function buildApplyPatchPlanForSnapshot(statement, snapshot, metadata, parentId)
41027
41377
  const hasRemove = block.operations.some((operation) => operation.kind === "REMOVE");
41028
41378
  for (const [operationIndex, operation] of block.operations.entries()) {
41029
41379
  if (operation.kind === "APPEND") {
41030
- const rows = buildApplyAppendRows(operation, targetChildren, block.field);
41380
+ const rows = buildApplyAppendRows(
41381
+ operation,
41382
+ targetChildren,
41383
+ block.field,
41384
+ evaluationContext
41385
+ );
41031
41386
  operationPlans.push({ kind: "APPEND", addedRows: rows.length });
41032
41387
  appended.push(...rows);
41033
41388
  continue;
41034
41389
  }
41035
41390
  if (operation.kind === "REMOVE") {
41036
- const indices2 = resolveRemoveTargets(operation, snapshotRows, childTypeResolver, block.field);
41391
+ const indices2 = resolveRemoveTargets(
41392
+ operation,
41393
+ snapshotRows,
41394
+ childTypeResolver,
41395
+ block.field,
41396
+ evaluationContext
41397
+ );
41037
41398
  if (operation.expectRows) {
41038
41399
  assertExpectRows(operation.expectRows, indices2.length, parentId, block.field, operationIndex, operation.kind);
41039
41400
  }
@@ -41051,7 +41412,13 @@ function buildApplyPatchPlanForSnapshot(statement, snapshot, metadata, parentId)
41051
41412
  continue;
41052
41413
  }
41053
41414
  if (operation.kind !== "PATCH") continue;
41054
- const indices = resolvePatchTargets(operation, snapshotRows, childTypeResolver, block.field);
41415
+ const indices = resolvePatchTargets(
41416
+ operation,
41417
+ snapshotRows,
41418
+ childTypeResolver,
41419
+ block.field,
41420
+ evaluationContext
41421
+ );
41055
41422
  if (operation.expectRows) {
41056
41423
  assertExpectRows(operation.expectRows, indices.length, parentId, block.field, operationIndex, operation.kind);
41057
41424
  }
@@ -41070,7 +41437,12 @@ function buildApplyPatchPlanForSnapshot(statement, snapshot, metadata, parentId)
41070
41437
  resolved.push({
41071
41438
  rowIndex,
41072
41439
  field: assignment.field,
41073
- value: evaluateSubtableAssignmentValue(assignment.value, flat, childTypeResolver)
41440
+ value: evaluateSubtableAssignmentValue(
41441
+ assignment.value,
41442
+ flat,
41443
+ childTypeResolver,
41444
+ evaluationContext
41445
+ )
41074
41446
  });
41075
41447
  }
41076
41448
  }
@@ -41122,7 +41494,13 @@ function buildApplyPatchPlanForSnapshot(statement, snapshot, metadata, parentId)
41122
41494
  for (const assignment of statement.assignments) {
41123
41495
  const fieldType = metadata.fieldsByCode.get(assignment.field)?.fieldType;
41124
41496
  parentValues[assignment.field] = {
41125
- value: evaluateUpdateAssignmentValue(assignment.value, parentRow, fieldType, snapshot)
41497
+ value: evaluateUpdateAssignmentValue(
41498
+ assignment.value,
41499
+ parentRow,
41500
+ fieldType,
41501
+ snapshot,
41502
+ evaluationContext
41503
+ )
41126
41504
  };
41127
41505
  }
41128
41506
  const postImage = { ...snapshot };
@@ -41192,12 +41570,12 @@ function normalizeApplyPatchPlan(plan, normalizedRecord) {
41192
41570
  postImage: normalizedRecord
41193
41571
  };
41194
41572
  }
41195
- function buildApplyAppendRows(operation, children, table) {
41573
+ function buildApplyAppendRows(operation, children, table, evaluationContext = {}) {
41196
41574
  return operation.values.map((row) => ({
41197
- value: buildAppendValue(operation, row, children, table)
41575
+ value: buildAppendValue(operation, row, children, table, evaluationContext)
41198
41576
  }));
41199
41577
  }
41200
- function buildAppendValue(operation, row, children, table) {
41578
+ function buildAppendValue(operation, row, children, table, evaluationContext) {
41201
41579
  if (row.length !== operation.fields.length) {
41202
41580
  return argument2(`APPLY APPEND for ${table} has ${row.length} values for ${operation.fields.length} fields.`);
41203
41581
  }
@@ -41206,7 +41584,7 @@ function buildAppendValue(operation, row, children, table) {
41206
41584
  for (const field of children.values()) {
41207
41585
  if (field.fieldType === "FILE" || field.writable === false) continue;
41208
41586
  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) };
41587
+ value[field.code] = { value: sqlValue === void 0 ? appendDefaultValue(field) : sqlValue.type === "CASE_VALUE" ? evalCaseWhenValue(sqlValue.expr, {}, field.fieldType, evaluationContext) : toKintoneValue(sqlValue, field.fieldType) };
41210
41588
  }
41211
41589
  return value;
41212
41590
  }
@@ -41214,17 +41592,36 @@ function appendDefaultValue(field) {
41214
41592
  if (field.defaultValue !== void 0 && field.defaultValue !== null) return field.defaultValue;
41215
41593
  return ["CHECK_BOX", "MULTI_SELECT", "USER_SELECT", "ORGANIZATION_SELECT", "GROUP_SELECT"].includes(field.fieldType) ? [] : "";
41216
41594
  }
41217
- function resolvePatchTargets(operation, rows, resolveFieldType, table) {
41218
- return resolveSelectorTargets(operation.selector, rows, resolveFieldType, table);
41595
+ function resolvePatchTargets(operation, rows, resolveFieldType, table, evaluationContext = {}) {
41596
+ return resolveSelectorTargets(
41597
+ operation.selector,
41598
+ rows,
41599
+ resolveFieldType,
41600
+ table,
41601
+ evaluationContext
41602
+ );
41219
41603
  }
41220
- function resolveRemoveTargets(operation, rows, resolveFieldType, table) {
41221
- return resolveSelectorTargets(operation.selector, rows, resolveFieldType, table);
41604
+ function resolveRemoveTargets(operation, rows, resolveFieldType, table, evaluationContext = {}) {
41605
+ return resolveSelectorTargets(
41606
+ operation.selector,
41607
+ rows,
41608
+ resolveFieldType,
41609
+ table,
41610
+ evaluationContext
41611
+ );
41222
41612
  }
41223
- function resolveSelectorTargets(selector, rows, resolveFieldType, table) {
41613
+ function resolveSelectorTargets(selector, rows, resolveFieldType, table, evaluationContext = {}) {
41224
41614
  if (selector.kind === "ALL_ROWS") return rows.map((_, index) => index);
41225
41615
  const where = selector.where;
41226
41616
  const indices = rows.flatMap(
41227
- (row, index) => evalWhere(where, flattenSubtableSnapshotRow(row, index), resolveFieldType) ? [index] : []
41617
+ (row, index) => evalWhere(
41618
+ where,
41619
+ flattenSubtableSnapshotRow(row, index),
41620
+ resolveFieldType,
41621
+ void 0,
41622
+ void 0,
41623
+ evaluationContext
41624
+ ) ? [index] : []
41228
41625
  );
41229
41626
  const requestedRid = exactRidSelectorValue(where);
41230
41627
  if (requestedRid !== null && indices.length === 0) {
@@ -44557,9 +44954,16 @@ function assertJoinKeyAvailable(rows, key, savedColumns) {
44557
44954
  throw new Error(`ArgumentError: JOIN key ${key} is not available in the materialized table.`);
44558
44955
  }
44559
44956
  }
44560
- function applyFilter(rows, where, resolveFieldType, appliedKlikes, resolveFieldSemantics2) {
44957
+ function applyFilter(rows, where, resolveFieldType, appliedKlikes, resolveFieldSemantics2, evaluationContext = {}) {
44561
44958
  if (where === null) return rows;
44562
- return rows.filter((row) => evalWhere(where, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2));
44959
+ return rows.filter((row) => evalWhere(
44960
+ where,
44961
+ row,
44962
+ resolveFieldType,
44963
+ appliedKlikes,
44964
+ resolveFieldSemantics2,
44965
+ evaluationContext
44966
+ ));
44563
44967
  }
44564
44968
  function hasAggregateColumns(columns) {
44565
44969
  return columns.some(
@@ -44593,12 +44997,28 @@ function applyGroupBy(rows, groupByKeys, columns, resolveAggSortKind, resolution
44593
44997
  const outRow = asProcessingRow({ ...groupRows[0] });
44594
44998
  for (const k of groupByKeys) {
44595
44999
  if (k.type === "ARITH_KEY") {
44596
- outRow[arithColDefaultKey(k.expr)] = String(evalArithExpr(k.expr, groupRows[0]));
45000
+ outRow[arithColDefaultKey(k.expr)] = String(evalArithExpr(
45001
+ k.expr,
45002
+ groupRows[0],
45003
+ aliasEvaluationContext.evaluationContext
45004
+ ));
44597
45005
  } else if (k.type === "FUNC_KEY") {
44598
- outRow[stringFuncDefaultKey(k.expr)] = evalStringFunc(k.expr, groupRows[0]);
45006
+ outRow[stringFuncDefaultKey(k.expr)] = evalStringFunc(
45007
+ k.expr,
45008
+ groupRows[0],
45009
+ void 0,
45010
+ void 0,
45011
+ aliasEvaluationContext.evaluationContext
45012
+ );
44599
45013
  }
44600
45014
  }
44601
- materializeAggregateColumns(outRow, groupRows, columns, resolveAggSortKind);
45015
+ materializeAggregateColumns(
45016
+ outRow,
45017
+ groupRows,
45018
+ columns,
45019
+ resolveAggSortKind,
45020
+ aliasEvaluationContext.evaluationContext
45021
+ );
44602
45022
  result.push(outRow);
44603
45023
  }
44604
45024
  return result;
@@ -44656,7 +45076,13 @@ function applyGroupingSets(rows, spec, columns, resolveAggSortKind, limits = {})
44656
45076
  outRow[item.unqualifiedBridgeKey] = value;
44657
45077
  }
44658
45078
  }
44659
- materializeAggregateColumns(outRow, groupRows, columns, resolveAggSortKind);
45079
+ materializeAggregateColumns(
45080
+ outRow,
45081
+ groupRows,
45082
+ columns,
45083
+ resolveAggSortKind,
45084
+ limits.evaluationContext
45085
+ );
44660
45086
  attachGroupingRowMeta(outRow, includedCanonicalIds);
44661
45087
  result.push(outRow);
44662
45088
  }
@@ -44667,11 +45093,19 @@ function groupingItemValue(item, row) {
44667
45093
  if (!row) return "";
44668
45094
  return row[item.directKey] ?? (item.unqualifiedBridgeKey === null ? void 0 : row[item.unqualifiedBridgeKey]) ?? "";
44669
45095
  }
44670
- function materializeAggregateColumns(outRow, groupRows, columns, resolveAggSortKind) {
45096
+ function materializeAggregateColumns(outRow, groupRows, columns, resolveAggSortKind, evaluationContext = {}) {
44671
45097
  for (const [columnIndex, col] of columns.entries()) {
44672
45098
  if (col.type === "AGGREGATE") {
44673
45099
  const syntheticKey = aggregateSyntheticName(col.func, col.distinct, col.arg);
44674
- const value = String(evalAggregate(col.func, col.distinct, col.arg, col.separator, groupRows, resolveAggSortKind));
45100
+ const value = String(evalAggregate(
45101
+ col.func,
45102
+ col.distinct,
45103
+ col.arg,
45104
+ col.separator,
45105
+ groupRows,
45106
+ resolveAggSortKind,
45107
+ evaluationContext
45108
+ ));
44675
45109
  setMaterializedSelectValue(
44676
45110
  outRow,
44677
45111
  columnIndex,
@@ -44679,38 +45113,44 @@ function materializeAggregateColumns(outRow, groupRows, columns, resolveAggSortK
44679
45113
  col.alias ? [col.alias, syntheticKey] : [syntheticKey]
44680
45114
  );
44681
45115
  } else if (col.type === "ARITH_AGG_COL") {
44682
- materializeAggregateDependencies(outRow, groupRows, col.expr, resolveAggSortKind);
45116
+ materializeAggregateDependencies(outRow, groupRows, col.expr, resolveAggSortKind, evaluationContext);
44683
45117
  const outputKey = col.alias ?? aggArithDefaultKey(col.expr);
44684
45118
  setMaterializedSelectValue(
44685
45119
  outRow,
44686
45120
  columnIndex,
44687
- String(evalAggArithExpr(col.expr, groupRows, resolveAggSortKind)),
45121
+ String(evalAggArithExpr(col.expr, groupRows, resolveAggSortKind, evaluationContext)),
44688
45122
  [outputKey]
44689
45123
  );
44690
45124
  } else if (col.type === "STRFUNC_COL" && hasAggregateInStringFuncExpr2(col.expr)) {
44691
- materializeAggregateDependencies(outRow, groupRows, col.expr, resolveAggSortKind);
45125
+ materializeAggregateDependencies(outRow, groupRows, col.expr, resolveAggSortKind, evaluationContext);
44692
45126
  const outputKey = col.alias ?? stringFuncDefaultKey(col.expr);
44693
45127
  const resolvedExpr = resolveAggInStringFuncExpr(col.expr, groupRows, resolveAggSortKind);
44694
- setMaterializedSelectValue(outRow, columnIndex, evalStringFunc(resolvedExpr, outRow), [outputKey]);
45128
+ setMaterializedSelectValue(
45129
+ outRow,
45130
+ columnIndex,
45131
+ evalStringFunc(resolvedExpr, outRow, void 0, void 0, evaluationContext),
45132
+ [outputKey]
45133
+ );
44695
45134
  } else if (col.type === "SCALAR_VALUE_COL" && scalarValueHasAggregate2(col.expr)) {
44696
- materializeAggregateDependencies(outRow, groupRows, col.expr, resolveAggSortKind);
45135
+ materializeAggregateDependencies(outRow, groupRows, col.expr, resolveAggSortKind, evaluationContext);
44697
45136
  const outputKey = col.alias ?? scalarValueDefaultKey(col.expr);
44698
45137
  const resolvedExpr = resolveAggInScalarValue(col.expr, groupRows, resolveAggSortKind);
44699
45138
  setMaterializedSelectValue(
44700
45139
  outRow,
44701
45140
  columnIndex,
44702
- String(evalScalarValueExpr(resolvedExpr, outRow)),
45141
+ String(evalScalarValueExpr(resolvedExpr, outRow, void 0, void 0, evaluationContext)),
44703
45142
  [outputKey]
44704
45143
  );
44705
45144
  } else if (col.type === "CASE_COL" && containsAggregate2(col.expr)) {
44706
- materializeAggregateDependencies(outRow, groupRows, col.expr, resolveAggSortKind);
45145
+ materializeAggregateDependencies(outRow, groupRows, col.expr, resolveAggSortKind, evaluationContext);
44707
45146
  const resolvedExpr = resolveAggInCaseExpr(col.expr, groupRows, resolveAggSortKind);
44708
45147
  const resolveAggregateSemantics = (field) => field.aggregateRef ? aggregateResultSemantics(field.aggregateRef, resolveAggSortKind) : void 0;
44709
45148
  const value = evalCaseWhen(
44710
45149
  resolvedExpr,
44711
45150
  outRow,
44712
45151
  void 0,
44713
- resolveAggregateSemantics
45152
+ resolveAggregateSemantics,
45153
+ evaluationContext
44714
45154
  );
44715
45155
  setMaterializedSelectValue(
44716
45156
  outRow,
@@ -44738,7 +45178,7 @@ function collectAggregateRefs(node, out) {
44738
45178
  if (value["type"] === "SELECT" || value["type"] === "SCALAR_SUBQUERY") return;
44739
45179
  Object.values(value).forEach((child) => collectAggregateRefs(child, out));
44740
45180
  }
44741
- function materializeAggregateDependencies(outRow, rows, node, resolveAggSortKind) {
45181
+ function materializeAggregateDependencies(outRow, rows, node, resolveAggSortKind, evaluationContext = {}) {
44742
45182
  const refs = [];
44743
45183
  collectAggregateRefs(node, refs);
44744
45184
  for (const ref of refs) {
@@ -44750,7 +45190,8 @@ function materializeAggregateDependencies(outRow, rows, node, resolveAggSortKind
44750
45190
  ref.arg,
44751
45191
  ref.separator,
44752
45192
  rows,
44753
- resolveAggSortKind
45193
+ resolveAggSortKind,
45194
+ evaluationContext
44754
45195
  ));
44755
45196
  materializedValuesFor(outRow).byLookupKey.set(key, value);
44756
45197
  }
@@ -44781,14 +45222,20 @@ function evalGroupByKey(key, row, resolution, columns, aliasEvaluationContext) {
44781
45222
  `InternalError: unresolved plain GROUP BY item ${resolution.kind} reached evaluation.`
44782
45223
  );
44783
45224
  }
44784
- if (key.type === "FUNC_KEY") return evalStringFunc(key.expr, row);
44785
- return String(evalArithExpr(key.expr, row));
45225
+ if (key.type === "FUNC_KEY") return evalStringFunc(
45226
+ key.expr,
45227
+ row,
45228
+ void 0,
45229
+ void 0,
45230
+ aliasEvaluationContext.evaluationContext
45231
+ );
45232
+ return String(evalArithExpr(key.expr, row, aliasEvaluationContext.evaluationContext));
44786
45233
  }
44787
- function evalAggregate(func, distinct, arg, separator, rows, resolveAggSortKind) {
45234
+ function evalAggregate(func, distinct, arg, separator, rows, resolveAggSortKind, evaluationContext = {}) {
44788
45235
  if (arg.type === "WILDCARD") {
44789
45236
  return func === "COUNT" ? rows.length : 0;
44790
45237
  }
44791
- const strValues = aggregateRowValues(func, arg, rows).filter((value) => value !== null);
45238
+ const strValues = aggregateRowValues(func, arg, rows, evaluationContext).filter((value) => value !== null);
44792
45239
  const statistical = func === "STDDEV_POP" || func === "STDDEV_SAMP" || func === "VAR_POP" || func === "VAR_SAMP" || func === "MEDIAN";
44793
45240
  const numericValues = statistical ? strValues.map((value) => {
44794
45241
  const numeric = Number(value);
@@ -44866,7 +45313,7 @@ function evalAggregate(func, distinct, arg, separator, rows, resolveAggSortKind)
44866
45313
  }
44867
45314
  }
44868
45315
  }
44869
- function aggregateRowValues(func, arg, rows) {
45316
+ function aggregateRowValues(func, arg, rows, evaluationContext = {}) {
44870
45317
  return rows.map((processingRow) => {
44871
45318
  const row = sourceRowForEvaluation(processingRow);
44872
45319
  let strVal;
@@ -44875,11 +45322,11 @@ function aggregateRowValues(func, arg, rows) {
44875
45322
  if (raw === void 0 || raw === "" && func !== "MIN" && func !== "MAX") return null;
44876
45323
  strVal = raw;
44877
45324
  } else if (arg.type === "ARITH" || arg.type === "NUMBER") {
44878
- const n = evalArithExpr(arg, row);
45325
+ const n = evalArithExpr(arg, row, evaluationContext);
44879
45326
  if (isNaN(n)) return null;
44880
45327
  strVal = String(n);
44881
45328
  } else {
44882
- const value = evalScalarValueExprNullable(arg, row);
45329
+ const value = evalScalarValueExprNullable(arg, row, void 0, void 0, evaluationContext);
44883
45330
  if (value === null) return null;
44884
45331
  if (value === "" && func !== "MIN" && func !== "MAX") return null;
44885
45332
  if (typeof value === "number" && Number.isNaN(value)) return null;
@@ -44892,9 +45339,17 @@ function toAggregateFieldRef(field) {
44892
45339
  const dot = field.indexOf(".");
44893
45340
  return dot > 0 ? { type: "FIELD", tableAlias: field.slice(0, dot), field: field.slice(dot + 1) } : { type: "FIELD", tableAlias: null, field };
44894
45341
  }
44895
- function evalAggArithExpr(node, rows, resolveAggSortKind) {
45342
+ function evalAggArithExpr(node, rows, resolveAggSortKind, evaluationContext = {}) {
44896
45343
  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));
45344
+ if (node.type === "AGG_REF") return Number(evalAggregate(
45345
+ node.func,
45346
+ node.distinct,
45347
+ node.arg,
45348
+ node.separator,
45349
+ rows,
45350
+ resolveAggSortKind,
45351
+ evaluationContext
45352
+ ));
44898
45353
  if (node.type === "AGG_GROUP_KEY") {
44899
45354
  const field = node.tableAlias ? `${node.tableAlias}.${node.field}` : node.field;
44900
45355
  return Number(resolveFieldRef(rows[0] ?? {}, field));
@@ -44902,8 +45357,8 @@ function evalAggArithExpr(node, rows, resolveAggSortKind) {
44902
45357
  if (node.type === "VARIABLE") {
44903
45358
  throw new Error(`InternalError: unresolved aggregate arithmetic variable @${node.name}.`);
44904
45359
  }
44905
- const l = evalAggArithExpr(node.left, rows, resolveAggSortKind);
44906
- const r = evalAggArithExpr(node.right, rows, resolveAggSortKind);
45360
+ const l = evalAggArithExpr(node.left, rows, resolveAggSortKind, evaluationContext);
45361
+ const r = evalAggArithExpr(node.right, rows, resolveAggSortKind, evaluationContext);
44907
45362
  switch (node.op) {
44908
45363
  case "+":
44909
45364
  return l + r;
@@ -44947,22 +45402,24 @@ function aggregateResultSemantics(ref, resolver) {
44947
45402
  const semantics = ref.arg.type === "WILDCARD" ? "string" : resolveAggregateArgSemantics(ref.arg, resolver) ?? "string";
44948
45403
  return typeof semantics === "string" ? syntheticSemantics(semantics) : semantics;
44949
45404
  }
44950
- function applyHaving(rows, having, resolveFieldType, resolveFieldSemantics2) {
45405
+ function applyHaving(rows, having, resolveFieldType, resolveFieldSemantics2, evaluationContext = {}) {
44951
45406
  if (having === null) return rows;
44952
45407
  return rows.filter((row) => evalWhere(
44953
45408
  having,
44954
45409
  havingEvaluationRow(row),
44955
45410
  resolveFieldType,
44956
45411
  void 0,
44957
- resolveFieldSemantics2
45412
+ resolveFieldSemantics2,
45413
+ evaluationContext
44958
45414
  ));
44959
45415
  }
44960
- function applyDistinct(rows, columns, scalarCache, resolveFieldType, resolveFieldSemantics2) {
45416
+ function applyDistinct(rows, columns, scalarCache, resolveFieldType, resolveFieldSemantics2, evaluationContext = {}) {
44961
45417
  if (rows.length === 0) return rows;
44962
45418
  const keyFor = buildDistinctKeyBuilder(rows, columns, {
44963
45419
  scalarCache,
44964
45420
  resolveFieldType,
44965
- resolveFieldSemantics: resolveFieldSemantics2
45421
+ resolveFieldSemantics: resolveFieldSemantics2,
45422
+ evaluationContext
44966
45423
  });
44967
45424
  const seen = /* @__PURE__ */ new Set();
44968
45425
  return rows.filter((row) => {
@@ -44998,11 +45455,19 @@ function buildDistinctKeyBuilder(rows, columns, context) {
44998
45455
  };
44999
45456
  return (row) => JSON.stringify(buildDistinctTuple(columns, row, distinctContext));
45000
45457
  }
45001
- function applyOrderBy(rows, orderBy, optionOrders, sortKinds, fieldSemantics2, aliasEvaluator) {
45458
+ function applyOrderBy(rows, orderBy, optionOrders, sortKinds, fieldSemantics2, aliasEvaluator, evaluationContext = {}) {
45002
45459
  if (orderBy.length === 0) return rows;
45003
- return sortDecoratedRows(rows, orderBy, optionOrders, sortKinds, fieldSemantics2, aliasEvaluator).rows.map((item) => item.row);
45460
+ return sortDecoratedRows(
45461
+ rows,
45462
+ orderBy,
45463
+ optionOrders,
45464
+ sortKinds,
45465
+ fieldSemantics2,
45466
+ aliasEvaluator,
45467
+ evaluationContext
45468
+ ).rows.map((item) => item.row);
45004
45469
  }
45005
- function sortDecoratedRows(rows, orderBy, optionOrders, sortKinds, fieldSemantics2, aliasEvaluator) {
45470
+ function sortDecoratedRows(rows, orderBy, optionOrders, sortKinds, fieldSemantics2, aliasEvaluator, evaluationContext = {}) {
45006
45471
  const keyMeta = orderBy.map(({ key }) => {
45007
45472
  if (key.type === "ARITH_KEY") return { semantics: syntheticSemantics("number") };
45008
45473
  if (key.type === "FUNC_KEY") {
@@ -45028,7 +45493,7 @@ function sortDecoratedRows(rows, orderBy, optionOrders, sortKinds, fieldSemantic
45028
45493
  const decorated = rows.map((row) => ({
45029
45494
  row,
45030
45495
  keys: orderBy.map(({ key }, i) => {
45031
- const s = evalOrderKey(key, row, aliasEvaluator);
45496
+ const s = evalOrderKey(key, row, aliasEvaluator, evaluationContext);
45032
45497
  return { s };
45033
45498
  })
45034
45499
  }));
@@ -45066,20 +45531,20 @@ var NUMERIC_ORDER_FUNCTIONS = /* @__PURE__ */ new Set([
45066
45531
  "QUARTER",
45067
45532
  "WEEK"
45068
45533
  ]);
45069
- function evalOrderKey(key, row, aliasEvaluator) {
45534
+ function evalOrderKey(key, row, aliasEvaluator, evaluationContext = {}) {
45070
45535
  const sourceRow = sourceRowForEvaluation(row);
45071
45536
  switch (key.type) {
45072
45537
  case "FIELD_NAME":
45073
45538
  return aliasEvaluator?.(key.name, row) ?? getMaterializedLookupValue(row, key.name) ?? sourceRow[key.name] ?? "";
45074
45539
  case "ARITH_KEY":
45075
- return String(evalArithExpr(key.expr, sourceRow));
45540
+ return String(evalArithExpr(key.expr, sourceRow, evaluationContext));
45076
45541
  case "FUNC_KEY":
45077
- return evalStringFunc(key.expr, sourceRow);
45542
+ return evalStringFunc(key.expr, sourceRow, void 0, void 0, evaluationContext);
45078
45543
  case "GROUPING_KEY":
45079
45544
  return evalGroupingRef(key.ref, row);
45080
45545
  }
45081
45546
  }
45082
- function buildOrderByAliasEvaluator(columns, scalarCache, resolveFieldType, resolveFieldSemantics2) {
45547
+ function buildOrderByAliasEvaluator(columns, scalarCache, resolveFieldType, resolveFieldSemantics2, evaluationContext = {}) {
45083
45548
  const evaluators = /* @__PURE__ */ new Map();
45084
45549
  for (const [columnIndex, column] of columns.entries()) {
45085
45550
  if (!("alias" in column) || column.alias === null) continue;
@@ -45103,15 +45568,37 @@ function buildOrderByAliasEvaluator(columns, scalarCache, resolveFieldType, reso
45103
45568
  evaluators.set(alias, (row) => getMaterializedSelectValue(row, columnIndex) ?? "");
45104
45569
  break;
45105
45570
  case "ARITH_COL":
45106
- evaluators.set(alias, (row) => String(evalArithExpr(column.expr, sourceRowForEvaluation(row))));
45571
+ evaluators.set(alias, (row) => String(evalArithExpr(
45572
+ column.expr,
45573
+ sourceRowForEvaluation(row),
45574
+ evaluationContext
45575
+ )));
45107
45576
  break;
45108
45577
  case "STRFUNC_COL": {
45109
45578
  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));
45579
+ evaluators.set(alias, (row) => hasAggregateInStringFuncExpr2(column.expr) ? getMaterializedSelectValue(row, columnIndex) ?? getMaterializedLookupValue(row, source) ?? evalStringFunc(
45580
+ column.expr,
45581
+ sourceRowForEvaluation(row),
45582
+ resolveFieldType,
45583
+ resolveFieldSemantics2,
45584
+ evaluationContext
45585
+ ) : evalStringFunc(
45586
+ column.expr,
45587
+ sourceRowForEvaluation(row),
45588
+ resolveFieldType,
45589
+ resolveFieldSemantics2,
45590
+ evaluationContext
45591
+ ));
45111
45592
  break;
45112
45593
  }
45113
45594
  case "CASE_COL":
45114
- evaluators.set(alias, (row) => containsAggregate2(column.expr) ? getMaterializedSelectValue(row, columnIndex) ?? "" : evalCaseWhen(column.expr, sourceRowForEvaluation(row), resolveFieldType, resolveFieldSemantics2));
45595
+ evaluators.set(alias, (row) => containsAggregate2(column.expr) ? getMaterializedSelectValue(row, columnIndex) ?? "" : evalCaseWhen(
45596
+ column.expr,
45597
+ sourceRowForEvaluation(row),
45598
+ resolveFieldType,
45599
+ resolveFieldSemantics2,
45600
+ evaluationContext
45601
+ ));
45115
45602
  break;
45116
45603
  case "SCALAR_VALUE_COL": {
45117
45604
  const source = scalarValueDefaultKey(column.expr);
@@ -45119,7 +45606,8 @@ function buildOrderByAliasEvaluator(columns, scalarCache, resolveFieldType, reso
45119
45606
  column.expr,
45120
45607
  sourceRowForEvaluation(row),
45121
45608
  resolveFieldType,
45122
- resolveFieldSemantics2
45609
+ resolveFieldSemantics2,
45610
+ evaluationContext
45123
45611
  )));
45124
45612
  break;
45125
45613
  }
@@ -45135,7 +45623,7 @@ function buildOrderByAliasEvaluator(columns, scalarCache, resolveFieldType, reso
45135
45623
  }
45136
45624
  return (name, row) => evaluators.get(name)?.(row);
45137
45625
  }
45138
- function applyWindow(rows, columns, optionOrders, sortKinds, fieldSemantics2, resolveAggSortKind) {
45626
+ function applyWindow(rows, columns, optionOrders, sortKinds, fieldSemantics2, resolveAggSortKind, evaluationContext = {}) {
45139
45627
  const windows = columns.map((column, columnIndex) => ({ column, columnIndex })).filter((item) => item.column.type === "WINDOW_COL");
45140
45628
  if (rows.length === 0 || windows.length === 0) return rows;
45141
45629
  for (let index = 0; index < rows.length; index++) rows[index] = asProcessingRow(rows[index]);
@@ -45148,14 +45636,28 @@ function applyWindow(rows, columns, optionOrders, sortKinds, fieldSemantics2, re
45148
45636
  else partitions.set(key, [row]);
45149
45637
  }
45150
45638
  for (const partition of partitions.values()) {
45151
- const sortedResult = sortDecoratedRows(partition, window.orderBy, optionOrders, sortKinds, fieldSemantics2);
45639
+ const sortedResult = sortDecoratedRows(
45640
+ partition,
45641
+ window.orderBy,
45642
+ optionOrders,
45643
+ sortKinds,
45644
+ fieldSemantics2,
45645
+ void 0,
45646
+ evaluationContext
45647
+ );
45152
45648
  const sorted = sortedResult.rows;
45153
45649
  if (isAggregateWindow(window)) {
45154
- applyAggregateWindow(window, columnIndex, sortedResult, resolveAggSortKind);
45650
+ applyAggregateWindow(
45651
+ window,
45652
+ columnIndex,
45653
+ sortedResult,
45654
+ resolveAggSortKind,
45655
+ evaluationContext
45656
+ );
45155
45657
  continue;
45156
45658
  }
45157
45659
  if (isValueWindow(window)) {
45158
- applyValueWindow(window, columnIndex, sorted);
45660
+ applyValueWindow(window, columnIndex, sorted, evaluationContext);
45159
45661
  continue;
45160
45662
  }
45161
45663
  if (!isRankingWindow(window)) {
@@ -45175,14 +45677,24 @@ function applyWindow(rows, columns, optionOrders, sortKinds, fieldSemantics2, re
45175
45677
  }
45176
45678
  return rows;
45177
45679
  }
45178
- function evaluateValueWindowArg(arg, row) {
45179
- const value = evalScalarValueExprNullable(arg, sourceRowForEvaluation(row));
45680
+ function evaluateValueWindowArg(arg, row, evaluationContext = {}) {
45681
+ const value = evalScalarValueExprNullable(
45682
+ arg,
45683
+ sourceRowForEvaluation(row),
45684
+ void 0,
45685
+ void 0,
45686
+ evaluationContext
45687
+ );
45180
45688
  if (value === null || value === void 0) return "";
45181
45689
  if (typeof value === "number" && !Number.isFinite(value)) return "";
45182
45690
  return String(value);
45183
45691
  }
45184
- function applyValueWindow(window, columnIndex, sorted) {
45185
- const values = sorted.map((item) => evaluateValueWindowArg(window.arg, item.row));
45692
+ function applyValueWindow(window, columnIndex, sorted, evaluationContext = {}) {
45693
+ const values = sorted.map((item) => evaluateValueWindowArg(
45694
+ window.arg,
45695
+ item.row,
45696
+ evaluationContext
45697
+ ));
45186
45698
  const direction = window.valueFunc === "LAG" ? -1 : 1;
45187
45699
  for (let index = 0; index < sorted.length; index++) {
45188
45700
  const target = index + direction * window.offset;
@@ -45194,9 +45706,14 @@ function applyValueWindow(window, columnIndex, sorted) {
45194
45706
  );
45195
45707
  }
45196
45708
  }
45197
- function applyAggregateWindow(window, columnIndex, sortedResult, resolveAggSortKind) {
45709
+ function applyAggregateWindow(window, columnIndex, sortedResult, resolveAggSortKind, evaluationContext = {}) {
45198
45710
  const sorted = sortedResult.rows;
45199
- const values = window.arg.type === "WILDCARD" ? null : aggregateRowValues(window.aggFunc, window.arg, sorted.map((item) => item.row));
45711
+ const values = window.arg.type === "WILDCARD" ? null : aggregateRowValues(
45712
+ window.aggFunc,
45713
+ window.arg,
45714
+ sorted.map((item) => item.row),
45715
+ evaluationContext
45716
+ );
45200
45717
  const comparison = window.arg.type === "WILDCARD" ? void 0 : resolveAggregateArgSemantics(window.arg, resolveAggSortKind);
45201
45718
  const semantics = typeof comparison === "string" ? syntheticSemantics(comparison) : comparison ?? syntheticSemantics("string");
45202
45719
  const output = [];
@@ -45288,13 +45805,14 @@ function evaluateSelectColumnValue(column, row, columnIndex, context = {}) {
45288
45805
  return getMaterializedSelectValue(row, columnIndex) ?? getMaterializedLookupValue(row, source) ?? getLegacyMaterializedValue(row, source) ?? "0";
45289
45806
  }
45290
45807
  case "ARITH_COL":
45291
- return String(evalArithExpr(column.expr, sourceRow));
45808
+ return String(evalArithExpr(column.expr, sourceRow, context.evaluationContext));
45292
45809
  case "CASE_COL":
45293
45810
  return containsAggregate2(column.expr) ? getMaterializedSelectValue(row, columnIndex) ?? getMaterializedLookupValue(row, caseMaterializedKey(column.alias, columnIndex)) ?? getLegacyMaterializedValue(row, caseMaterializedKey(column.alias, columnIndex)) ?? "" : evalCaseWhen(
45294
45811
  column.expr,
45295
45812
  sourceRow,
45296
45813
  context.resolveFieldType,
45297
- context.resolveFieldSemantics
45814
+ context.resolveFieldSemantics,
45815
+ context.evaluationContext
45298
45816
  );
45299
45817
  case "GROUPING_COL":
45300
45818
  return evalGroupingRef(column.ref, row);
@@ -45304,12 +45822,14 @@ function evaluateSelectColumnValue(column, row, columnIndex, context = {}) {
45304
45822
  column.expr,
45305
45823
  sourceRow,
45306
45824
  context.resolveFieldType,
45307
- context.resolveFieldSemantics
45825
+ context.resolveFieldSemantics,
45826
+ context.evaluationContext
45308
45827
  ) : evalStringFunc(
45309
45828
  column.expr,
45310
45829
  sourceRow,
45311
45830
  context.resolveFieldType,
45312
- context.resolveFieldSemantics
45831
+ context.resolveFieldSemantics,
45832
+ context.evaluationContext
45313
45833
  );
45314
45834
  }
45315
45835
  case "SCALAR_VALUE_COL": {
@@ -45318,7 +45838,8 @@ function evaluateSelectColumnValue(column, row, columnIndex, context = {}) {
45318
45838
  column.expr,
45319
45839
  sourceRow,
45320
45840
  context.resolveFieldType,
45321
- context.resolveFieldSemantics
45841
+ context.resolveFieldSemantics,
45842
+ context.evaluationContext
45322
45843
  ));
45323
45844
  }
45324
45845
  case "SCALAR_SUBQUERY_COL":
@@ -45333,7 +45854,7 @@ function buildDistinctTuple(columns, row, context = {}) {
45333
45854
  return typeof value === "string" ? value : value.entries.map(([, entryValue]) => entryValue);
45334
45855
  });
45335
45856
  }
45336
- function project(rows, columns, scalarCache, resolveFieldType, sourceColumns2, resolveFieldSemantics2, hiddenQualifiedAliases) {
45857
+ function project(rows, columns, scalarCache, resolveFieldType, sourceColumns2, resolveFieldSemantics2, hiddenQualifiedAliases, evaluationContext = {}) {
45337
45858
  if (columns.length === 1 && columns[0].type === "WILDCARD") {
45338
45859
  const projected2 = rows.map((row) => {
45339
45860
  const visible = stripHiddenQualifiedColumns(
@@ -45366,10 +45887,11 @@ function project(rows, columns, scalarCache, resolveFieldType, sourceColumns2, r
45366
45887
  }
45367
45888
  const projected = rows.map((row, rowIdx) => {
45368
45889
  const out = {};
45369
- const evaluationContext = {
45890
+ const columnEvaluationContext = {
45370
45891
  scalarCache,
45371
45892
  resolveFieldType,
45372
45893
  resolveFieldSemantics: resolveFieldSemantics2,
45894
+ evaluationContext,
45373
45895
  wildcardKeys: Object.keys(stripHiddenQualifiedColumns(
45374
45896
  stripParentShortcutColumns(row),
45375
45897
  hiddenQualifiedAliases
@@ -45377,7 +45899,7 @@ function project(rows, columns, scalarCache, resolveFieldType, sourceColumns2, r
45377
45899
  parentWildcardKeys: Object.keys(row).filter((key) => key.startsWith("_p.")).sort()
45378
45900
  };
45379
45901
  for (const [colIdx, col] of columns.entries()) {
45380
- const value = evaluateSelectColumnValue(col, row, colIdx, evaluationContext);
45902
+ const value = evaluateSelectColumnValue(col, row, colIdx, columnEvaluationContext);
45381
45903
  switch (col.type) {
45382
45904
  case "VARIABLE_COL":
45383
45905
  break;
@@ -45769,7 +46291,8 @@ function runFullScan(input) {
45769
46291
  hiddenQualifiedAliases,
45770
46292
  resolvedGroupingSpec,
45771
46293
  plainGroupByPlan,
45772
- warnings
46294
+ warnings,
46295
+ evaluationContext
45773
46296
  } = input;
45774
46297
  const effectiveOrderSemantics = deriveOutputOrderSemantics(stmt.columns, aggregateSortKindResolver);
45775
46298
  for (const [key, value] of orderSemantics ?? []) effectiveOrderSemantics.set(key, value);
@@ -45798,7 +46321,14 @@ function runFullScan(input) {
45798
46321
  knownColumns = mergeKnownColumns(knownColumns, rightColumns, rows);
45799
46322
  }
45800
46323
  const filterWhere = input.residualWhere !== void 0 ? input.residualWhere : stmt.where;
45801
- rows = applyFilter(rows, filterWhere, fieldTypeResolver, appliedKlikes, fieldSemanticsResolver);
46324
+ rows = applyFilter(
46325
+ rows,
46326
+ filterWhere,
46327
+ fieldTypeResolver,
46328
+ appliedKlikes,
46329
+ fieldSemanticsResolver,
46330
+ evaluationContext
46331
+ );
45802
46332
  const grouping = normalizeGroupingSpec(stmt);
45803
46333
  if (grouping.type === "GROUPING_SETS") {
45804
46334
  if (!resolvedGroupingSpec) {
@@ -45809,7 +46339,7 @@ function runFullScan(input) {
45809
46339
  resolvedGroupingSpec,
45810
46340
  stmt.columns,
45811
46341
  aggregateSortKindResolver,
45812
- { maxGeneratedRows: B65_MAX_GENERATED_ROWS }
46342
+ { maxGeneratedRows: B65_MAX_GENERATED_ROWS, evaluationContext }
45813
46343
  );
45814
46344
  } else if (grouping.type === "PLAIN" || hasAggregateColumns(stmt.columns)) {
45815
46345
  rows = applyGroupBy(
@@ -45821,21 +46351,29 @@ function runFullScan(input) {
45821
46351
  {
45822
46352
  scalarCache,
45823
46353
  resolveFieldType: fieldTypeResolver,
45824
- resolveFieldSemantics: fieldSemanticsResolver
46354
+ resolveFieldSemantics: fieldSemanticsResolver,
46355
+ evaluationContext
45825
46356
  }
45826
46357
  );
45827
46358
  }
45828
46359
  warnOnUnresolvedAggregateComparisons(stmt.columns, rows, warnings);
45829
46360
  const resolveHavingSemantics = (field) => field.aggregateRef ? aggregateResultSemantics(field.aggregateRef, aggregateSortKindResolver) : havingFieldSemanticsResolver?.(field);
45830
46361
  warnOnUnresolvedAggregateComparisons(stmt.having, rows, warnings);
45831
- rows = applyHaving(rows, stmt.having, havingFieldTypeResolver, resolveHavingSemantics);
46362
+ rows = applyHaving(
46363
+ rows,
46364
+ stmt.having,
46365
+ havingFieldTypeResolver,
46366
+ resolveHavingSemantics,
46367
+ evaluationContext
46368
+ );
45832
46369
  rows = applyWindow(
45833
46370
  rows,
45834
46371
  stmt.columns,
45835
46372
  optionOrders,
45836
46373
  sortKinds,
45837
46374
  effectiveOrderSemantics,
45838
- aggregateSortKindResolver
46375
+ aggregateSortKindResolver,
46376
+ evaluationContext
45839
46377
  );
45840
46378
  if (stmt.distinct) {
45841
46379
  rows = applyDistinct(
@@ -45843,7 +46381,8 @@ function runFullScan(input) {
45843
46381
  stmt.columns,
45844
46382
  scalarCache,
45845
46383
  fieldTypeResolver,
45846
- fieldSemanticsResolver
46384
+ fieldSemanticsResolver,
46385
+ evaluationContext
45847
46386
  );
45848
46387
  }
45849
46388
  rows = applyOrderBy(
@@ -45852,7 +46391,14 @@ function runFullScan(input) {
45852
46391
  optionOrders,
45853
46392
  sortKinds,
45854
46393
  effectiveOrderSemantics,
45855
- buildOrderByAliasEvaluator(stmt.columns, scalarCache, fieldTypeResolver, fieldSemanticsResolver)
46394
+ buildOrderByAliasEvaluator(
46395
+ stmt.columns,
46396
+ scalarCache,
46397
+ fieldTypeResolver,
46398
+ fieldSemanticsResolver,
46399
+ evaluationContext
46400
+ ),
46401
+ evaluationContext
45856
46402
  );
45857
46403
  rows = applyLimit(rows, stmt.limit, stmt.offset);
45858
46404
  return project(
@@ -45862,7 +46408,8 @@ function runFullScan(input) {
45862
46408
  fieldTypeResolver,
45863
46409
  sourceColumns2,
45864
46410
  fieldSemanticsResolver,
45865
- hiddenQualifiedAliases
46411
+ hiddenQualifiedAliases,
46412
+ evaluationContext
45866
46413
  );
45867
46414
  }
45868
46415
 
@@ -45909,6 +46456,151 @@ function toFlatString(value) {
45909
46456
  }
45910
46457
  }
45911
46458
 
46459
+ // src/core/scriptHeader.ts
46460
+ init_define_KSQL_DOCS();
46461
+
46462
+ // src/core/diagnostics.ts
46463
+ init_define_KSQL_DOCS();
46464
+ var DiagnosticCodes = {
46465
+ HEADER_UNKNOWN_KEY: "KSQL1001",
46466
+ HEADER_DUPLICATE_KEY: "KSQL1002",
46467
+ HEADER_INVALID_NAME: "KSQL1003",
46468
+ HEADER_INVALID_DEPENDS_ON: "KSQL1004",
46469
+ HEADER_INVALID_TIMEOUT: "KSQL1005",
46470
+ HEADER_INVALID_DIALECT: "KSQL1006",
46471
+ LOGICAL_APP_UNRESOLVED: "KSQL1101",
46472
+ LEX_ERROR: "KSQL1201",
46473
+ PARSE_ERROR: "KSQL1202"
46474
+ };
46475
+ function sourceLocationAt(source, offset) {
46476
+ const target = Math.max(0, Math.min(offset, source.length));
46477
+ let line = 1;
46478
+ let column = 1;
46479
+ for (let i = 0; i < target; i++) {
46480
+ const ch = source[i];
46481
+ if (ch === "\r") {
46482
+ if (source[i + 1] === "\n" && i + 1 < target) i++;
46483
+ line++;
46484
+ column = 1;
46485
+ } else if (ch === "\n") {
46486
+ line++;
46487
+ column = 1;
46488
+ } else {
46489
+ column++;
46490
+ }
46491
+ }
46492
+ return { line, column };
46493
+ }
46494
+ function diagnosticAt(source, offset, diagnostic2) {
46495
+ return { ...diagnostic2, ...sourceLocationAt(source, offset) };
46496
+ }
46497
+
46498
+ // src/core/scriptHeader.ts
46499
+ var HEADER_LINE_RE = /^(\s*)--\s*@ksql\s+([^:\s]+)\s*:\s*(.*)$/i;
46500
+ function parseScriptHeader(source) {
46501
+ const meta3 = { name: null, dependsOn: [], timeout: null, dialect: 0 };
46502
+ const diagnostics = [];
46503
+ const seen = /* @__PURE__ */ new Set();
46504
+ let hasDirectives = false;
46505
+ let offset = source.charCodeAt(0) === 65279 ? 1 : 0;
46506
+ let headerEnd = offset;
46507
+ while (offset < source.length) {
46508
+ const lineEnd = findLineEnd(source, offset);
46509
+ const line = source.slice(offset, lineEnd.contentEnd);
46510
+ if (!/^\s*--/.test(line)) break;
46511
+ headerEnd = lineEnd.next;
46512
+ const match = HEADER_LINE_RE.exec(line);
46513
+ if (match) {
46514
+ hasDirectives = true;
46515
+ const rawKey = match[2];
46516
+ const key = rawKey.toLowerCase();
46517
+ const rawValue = match[3];
46518
+ const commentAt = rawValue.indexOf("#");
46519
+ const valuePart = commentAt < 0 ? rawValue : rawValue.slice(0, commentAt);
46520
+ const leading = valuePart.match(/^\s*/)?.[0].length ?? 0;
46521
+ const value = valuePart.trim();
46522
+ const valueOffset = offset + match.index + match[0].length - rawValue.length + leading;
46523
+ if (!isHeaderKey(key)) {
46524
+ diagnostics.push(diagnosticAt(source, valueOffset, {
46525
+ severity: "warning",
46526
+ code: DiagnosticCodes.HEADER_UNKNOWN_KEY,
46527
+ message: `Unknown @ksql header key "${rawKey}" was ignored.`
46528
+ }));
46529
+ } else if (seen.has(key)) {
46530
+ diagnostics.push(diagnosticAt(source, valueOffset, {
46531
+ severity: "warning",
46532
+ code: DiagnosticCodes.HEADER_DUPLICATE_KEY,
46533
+ message: `Duplicate @ksql header key "${key}" was ignored; the first value is retained.`
46534
+ }));
46535
+ } else {
46536
+ seen.add(key);
46537
+ applyHeaderValue(meta3, key, value, source, valueOffset, diagnostics);
46538
+ }
46539
+ }
46540
+ offset = lineEnd.next;
46541
+ }
46542
+ return { meta: meta3, diagnostics, hasDirectives, headerEnd };
46543
+ }
46544
+ function isHeaderKey(value) {
46545
+ return value === "name" || value === "depends_on" || value === "timeout" || value === "dialect";
46546
+ }
46547
+ function applyHeaderValue(meta3, key, value, source, valueOffset, diagnostics) {
46548
+ if (key === "name") {
46549
+ if (!value) {
46550
+ diagnostics.push(diagnosticAt(source, valueOffset, {
46551
+ severity: "error",
46552
+ code: DiagnosticCodes.HEADER_INVALID_NAME,
46553
+ message: "@ksql name must not be empty."
46554
+ }));
46555
+ } else {
46556
+ meta3.name = value;
46557
+ }
46558
+ return;
46559
+ }
46560
+ if (key === "depends_on") {
46561
+ const dependencies = value.split(",").map((item) => item.trim());
46562
+ if (!value || dependencies.some((item) => !item)) {
46563
+ diagnostics.push(diagnosticAt(source, valueOffset, {
46564
+ severity: "error",
46565
+ code: DiagnosticCodes.HEADER_INVALID_DEPENDS_ON,
46566
+ message: "@ksql depends_on must be a comma-separated list without empty items."
46567
+ }));
46568
+ } else {
46569
+ meta3.dependsOn = dependencies;
46570
+ }
46571
+ return;
46572
+ }
46573
+ if (key === "timeout") {
46574
+ if (!/^[1-9]\d*$/.test(value) || !Number.isSafeInteger(Number(value))) {
46575
+ diagnostics.push(diagnosticAt(source, valueOffset, {
46576
+ severity: "error",
46577
+ code: DiagnosticCodes.HEADER_INVALID_TIMEOUT,
46578
+ message: "@ksql timeout must be a positive integer."
46579
+ }));
46580
+ } else {
46581
+ meta3.timeout = Number(value);
46582
+ }
46583
+ return;
46584
+ }
46585
+ if (value !== "0" && value !== "1") {
46586
+ diagnostics.push(diagnosticAt(source, valueOffset, {
46587
+ severity: "error",
46588
+ code: DiagnosticCodes.HEADER_INVALID_DIALECT,
46589
+ message: "@ksql dialect must be 0 or 1."
46590
+ }));
46591
+ } else {
46592
+ meta3.dialect = Number(value);
46593
+ }
46594
+ }
46595
+ function findLineEnd(source, start) {
46596
+ let i = start;
46597
+ while (i < source.length && source[i] !== "\r" && source[i] !== "\n") i++;
46598
+ const contentEnd = i;
46599
+ if (source[i] === "\r" && source[i + 1] === "\n") i += 2;
46600
+ else if (i < source.length) i++;
46601
+ return { contentEnd, next: i };
46602
+ }
46603
+
45912
46604
  // src/core/dmlPrevalidation.ts
45913
46605
  init_define_KSQL_DOCS();
45914
46606
  function collectDmlPrevalidationSnapshotFields(fieldIndex) {
@@ -47592,6 +48284,18 @@ var SearchAbortedError = class extends Error {
47592
48284
  var materializedMetaBySelectResult = /* @__PURE__ */ new WeakMap();
47593
48285
  var materializedMetaByValidationResult = /* @__PURE__ */ new WeakMap();
47594
48286
  var importSourceByDmlStatement = /* @__PURE__ */ new WeakMap();
48287
+ var statementEvaluationContextKey = /* @__PURE__ */ Symbol("statementEvaluationContext");
48288
+ function bindStatementEvaluationContext(options) {
48289
+ const internal = options;
48290
+ if (internal[statementEvaluationContextKey]) return options;
48291
+ return {
48292
+ ...options,
48293
+ [statementEvaluationContextKey]: { statementInstant: /* @__PURE__ */ new Date() }
48294
+ };
48295
+ }
48296
+ function statementEvaluationContext(options) {
48297
+ return options[statementEvaluationContextKey] ?? {};
48298
+ }
47595
48299
  var defaultCacheContextByClient = /* @__PURE__ */ new WeakMap();
47596
48300
  var nextDefaultCacheContextId = 1;
47597
48301
  var nextCacheInvocationId = 1;
@@ -47841,6 +48545,7 @@ async function resolveRelativeDateExecutionPlan(stmt, client, cacheContext) {
47841
48545
  });
47842
48546
  }
47843
48547
  async function executeParsedStatement(stmt, client, options, cacheContext) {
48548
+ options = bindStatementEvaluationContext(options);
47844
48549
  const relativeDatePlan = await resolveRelativeDateExecutionPlan(stmt, client, cacheContext);
47845
48550
  if (stmt.type !== "EXPLAIN") assertRelativeDatePushdownPlan(relativeDatePlan);
47846
48551
  const unresolved = findVariableRef(stmt);
@@ -47936,6 +48641,8 @@ async function executeParsedStatement(stmt, client, options, cacheContext) {
47936
48641
  throw new Error("ArgumentError: DECLARE variable requires a batch.");
47937
48642
  case "ASSERT":
47938
48643
  return executeAssert(stmt, client, options, cacheContext);
48644
+ case "EXIT":
48645
+ throw new Error("ArgumentError: EXIT SUCCESS IF \u306F\u30D0\u30C3\u30C1\u5C02\u7528\u3067\u3059");
47939
48646
  }
47940
48647
  }
47941
48648
  var EXISTING_VALIDATION_COLUMNS = [
@@ -48055,7 +48762,14 @@ async function executeExistingRecordValidationCore(stmt, client, options, cacheC
48055
48762
  id: String(record2["$id"]?.value ?? ""),
48056
48763
  record: record2,
48057
48764
  flat: flatten(record2, null)
48058
- })).filter((row) => stmt.where === null || evalWhere(stmt.where, row.flat, (field) => evaluationTypes.get(field.field)));
48765
+ })).filter((row) => stmt.where === null || evalWhere(
48766
+ stmt.where,
48767
+ row.flat,
48768
+ (field) => evaluationTypes.get(field.field),
48769
+ void 0,
48770
+ void 0,
48771
+ statementEvaluationContext(options)
48772
+ ));
48059
48773
  const rows = [];
48060
48774
  const detailRows = /* @__PURE__ */ new Map();
48061
48775
  const summaryRows = /* @__PURE__ */ new Map();
@@ -48196,7 +48910,16 @@ var BatchTimeoutError = class extends Error {
48196
48910
  };
48197
48911
  async function executeBatch(sql, client, options = {}) {
48198
48912
  resolveRecursiveCteLimits(options);
48199
- const statements = parseSqlBatch(sql, options.enableImport === true);
48913
+ const header = parseScriptHeader(sql);
48914
+ const headerError = header.diagnostics.find((diagnostic2) => diagnostic2.severity === "error");
48915
+ if (header.hasDirectives && headerError) {
48916
+ throw new Error(`${headerError.code}: ${headerError.message} (${headerError.line}:${headerError.column})`);
48917
+ }
48918
+ const statements = parseSqlBatch(
48919
+ header.hasDirectives ? sql.slice(header.headerEnd) : sql,
48920
+ options.enableImport === true,
48921
+ header.hasDirectives && header.meta.dialect === 1
48922
+ );
48200
48923
  const analysis = analyzeBatch(statements);
48201
48924
  statements.forEach((statement) => assertApplyExecutionScope("phase15b", statement));
48202
48925
  if (options.allowApplyMutation !== true && statements.some(
@@ -48238,7 +48961,7 @@ async function executeBatch(sql, client, options = {}) {
48238
48961
  const base = { index: i, type: info.statementType };
48239
48962
  if (aborted2) {
48240
48963
  results.push({ ...base, status: "skipped", skippedReason: aborted2 });
48241
- failed.add(i);
48964
+ if (aborted2 !== "exit") failed.add(i);
48242
48965
  continue;
48243
48966
  }
48244
48967
  const brokenDep = info.dependsOn.find((d) => failed.has(d));
@@ -48276,24 +48999,29 @@ async function executeBatch(sql, client, options = {}) {
48276
48999
  info.statementType !== "SELECT" && info.statementType !== "UNION" && info.statementType !== "WITH" || statementContainsOuterJoin(statements[i])
48277
49000
  );
48278
49001
  const cursorScope = wrapClientWithCursorScope(statementClient);
49002
+ const boundOptions = bindStatementEvaluationContext(stmtOptions);
49003
+ const statementContext = {
49004
+ stmt: statements[i],
49005
+ info,
49006
+ client: cursorScope.client,
49007
+ options: boundOptions,
49008
+ cacheContext,
49009
+ tempTables,
49010
+ variables,
49011
+ relativeDateVariables,
49012
+ clock: statementEvaluationContext(boundOptions)
49013
+ };
48279
49014
  const outcome = await runWithDeadline(
48280
- executeBatchStatement(
48281
- statements[i],
48282
- info,
48283
- cursorScope.client,
48284
- stmtOptions,
48285
- cacheContext,
48286
- tempTables,
48287
- variables,
48288
- relativeDateVariables
48289
- ),
49015
+ executeBatchStatement(statementContext),
48290
49016
  remaining,
48291
49017
  cursorScope.closeActive
48292
49018
  );
48293
49019
  if (outcome.result) {
48294
49020
  outcome.result = attachSearchAbortWarning(outcome.result, searchAbortCollector);
48295
49021
  }
48296
- results.push({ ...base, status: "success", ...outcome });
49022
+ const { exitTriggered, ...statementOutcome } = outcome;
49023
+ results.push({ ...base, status: "success", ...statementOutcome });
49024
+ if (exitTriggered) aborted2 = "exit";
48297
49025
  } catch (e) {
48298
49026
  results.push({
48299
49027
  ...base,
@@ -48315,7 +49043,7 @@ async function executeBatch(sql, client, options = {}) {
48315
49043
  }
48316
49044
  metrics.elapsedMs = Date.now() - startedAt;
48317
49045
  return {
48318
- ok: results.every((r) => r.status === "success"),
49046
+ ok: results.every((r) => r.status === "success" || r.skippedReason === "exit"),
48319
49047
  statementCount: statements.length,
48320
49048
  statements: results,
48321
49049
  analysis,
@@ -48331,7 +49059,18 @@ function statementHasApplyMutation(statement) {
48331
49059
  }
48332
49060
  return statement.type === "UPSERT" && statement.validateOnly !== true && Boolean(statement.onInsertApplyBlocks?.length || statement.onUpdateApplyBlocks?.length);
48333
49061
  }
48334
- async function executeBatchStatement(stmt, info, client, options, cacheContext, tempTables, variables, relativeDateVariables) {
49062
+ async function executeBatchStatement(context) {
49063
+ const {
49064
+ stmt,
49065
+ info,
49066
+ client,
49067
+ options,
49068
+ cacheContext,
49069
+ tempTables,
49070
+ variables,
49071
+ relativeDateVariables,
49072
+ clock
49073
+ } = context;
48335
49074
  if (stmt.type === "SET_VARIABLE") {
48336
49075
  const resolvedStmt2 = resolveBatchVariableReferences(stmt, variables);
48337
49076
  validateStatementStatic(resolvedStmt2);
@@ -48371,7 +49110,7 @@ async function executeBatchStatement(stmt, info, client, options, cacheContext,
48371
49110
  throw e;
48372
49111
  }
48373
49112
  } else {
48374
- variables.set(stmt.name, evaluateScalarExpr(resolvedStmt2.expr));
49113
+ variables.set(stmt.name, evaluateScalarExpr(resolvedStmt2.expr, clock));
48375
49114
  }
48376
49115
  return {};
48377
49116
  }
@@ -48387,7 +49126,10 @@ async function executeBatchStatement(stmt, info, client, options, cacheContext,
48387
49126
  if (Object.prototype.hasOwnProperty.call(injected, stmt.name)) {
48388
49127
  variables.set(stmt.name, { type: "string", value: injected[stmt.name] });
48389
49128
  } else {
48390
- const value = evaluateScalarExpr(stmt.default);
49129
+ const value = evaluateScalarExpr(
49130
+ stmt.default,
49131
+ clock
49132
+ );
48391
49133
  variables.set(stmt.name, {
48392
49134
  type: "string",
48393
49135
  value: value.type === "number" ? value.raw ?? String(value.value) : value.value
@@ -48483,8 +49225,12 @@ async function executeBatchStatement(stmt, info, client, options, cacheContext,
48483
49225
  }
48484
49226
  }
48485
49227
  if (resolvedStmt.type === "ASSERT") {
48486
- await executeAssert(resolvedStmt, client, options, cacheContext, tempTables);
48487
- return {};
49228
+ const result = await executeAssert(resolvedStmt, client, options, cacheContext, tempTables);
49229
+ return result.warning !== void 0 ? { result } : {};
49230
+ }
49231
+ if (resolvedStmt.type === "EXIT") {
49232
+ const result = await executeExit(resolvedStmt, client, options, cacheContext, tempTables);
49233
+ return { result, ...result.exited ? { exitTriggered: true } : {} };
48488
49234
  }
48489
49235
  if (info.tempTablesReferenced.length > 0) {
48490
49236
  if (resolvedStmt.type === "SELECT" || resolvedStmt.type === "UNION") {
@@ -48608,9 +49354,9 @@ function safeJsonStringify(v) {
48608
49354
  return String(v);
48609
49355
  }
48610
49356
  }
48611
- function parseSqlBatch(sql, enableImport = false) {
49357
+ function parseSqlBatch(sql, enableImport = false, dialect1 = false) {
48612
49358
  const tokens = new Lexer(sql).tokenize();
48613
- return new Parser(tokens, { import: enableImport }).parseStatements();
49359
+ return new Parser(tokens, { import: enableImport, dialect1 }).parseStatements();
48614
49360
  }
48615
49361
  function parseRelativeDateVariableValue(name, value) {
48616
49362
  try {
@@ -48638,18 +49384,18 @@ function prepareRelativeDateVariables(statements, injectedVariables) {
48638
49384
  }
48639
49385
  return prepared;
48640
49386
  }
48641
- function evaluateScalarExpr(expr) {
49387
+ function evaluateScalarExpr(expr, evaluationContext = {}) {
48642
49388
  switch (expr.type) {
48643
49389
  case "STRING":
48644
49390
  return { type: "string", value: expr.value };
48645
49391
  case "NUMBER":
48646
49392
  return { type: "number", value: expr.value, raw: numberLiteralText(expr) };
48647
49393
  case "KINTONE_FUNC":
48648
- return { type: "string", value: resolveKintoneFunc(expr.name) };
49394
+ return { type: "string", value: resolveKintoneFunc(expr.name, evaluationContext) };
48649
49395
  case "STRING_FUNC":
48650
- return { type: "string", value: evalStringFunc(expr, {}) };
49396
+ return { type: "string", value: evalStringFunc(expr, {}, void 0, void 0, evaluationContext) };
48651
49397
  case "ARITH": {
48652
- const value = evalArithExpr(expr, {});
49398
+ const value = evalArithExpr(expr, {}, evaluationContext);
48653
49399
  if (!Number.isFinite(value)) {
48654
49400
  throw new Error("ArgumentError: SET scalar arithmetic produced a non-finite number.");
48655
49401
  }
@@ -48796,6 +49542,31 @@ var ScalarSubqueryError = class extends Error {
48796
49542
  }
48797
49543
  };
48798
49544
  async function executeAssert(stmt, client, options, cacheContext, tempTables) {
49545
+ const evaluation = await evaluateAssertCondition(stmt, client, options, cacheContext, tempTables);
49546
+ if (!evaluation.passed) {
49547
+ if (stmt.warn === true) {
49548
+ return {
49549
+ type: "ASSERT",
49550
+ condition: stmt.text,
49551
+ passed: false,
49552
+ warning: stmt.message ?? `assertion failed: ${stmt.text} (actual: ${evaluation.actual}).`
49553
+ };
49554
+ }
49555
+ const suffix = stmt.message !== void 0 ? ` ${stmt.message}` : "";
49556
+ throw new AssertError(`assertion failed: ${stmt.text} (actual: ${evaluation.actual}).${suffix}`);
49557
+ }
49558
+ return { type: "ASSERT", condition: stmt.text };
49559
+ }
49560
+ async function executeExit(stmt, client, options, cacheContext, tempTables) {
49561
+ const evaluation = await evaluateAssertCondition(stmt, client, options, cacheContext, tempTables);
49562
+ return {
49563
+ type: "EXIT",
49564
+ condition: stmt.text,
49565
+ exited: evaluation.passed,
49566
+ message: stmt.message
49567
+ };
49568
+ }
49569
+ async function evaluateAssertCondition(stmt, client, options, cacheContext, tempTables) {
48799
49570
  const left = await evalAssertOperand(stmt.left, client, options, cacheContext, tempTables);
48800
49571
  const semantics = stmt.left.type === "NUMBER" || stmt.left.type === "ARITH" ? syntheticSemantics("number") : syntheticSemantics("string");
48801
49572
  if (stmt.op === "BETWEEN") {
@@ -48804,19 +49575,16 @@ async function executeAssert(stmt, client, options, cacheContext, tempTables) {
48804
49575
  }
48805
49576
  const low = await evalAssertOperand(stmt.low, client, options, cacheContext, tempTables);
48806
49577
  const high = await evalAssertOperand(stmt.high, client, options, cacheContext, tempTables);
48807
- if (!compareScalarValues(">=", left, low, semantics) || !compareScalarValues("<=", left, high, semantics)) {
48808
- throw new AssertError(`assertion failed: ${stmt.text} (actual: ${left}).`);
48809
- }
48810
- return { type: "ASSERT", condition: stmt.text };
49578
+ return {
49579
+ passed: compareScalarValues(">=", left, low, semantics) && compareScalarValues("<=", left, high, semantics),
49580
+ actual: left
49581
+ };
48811
49582
  }
48812
49583
  if (stmt.right === null) {
48813
49584
  throw new Error("ArgumentError: malformed ASSERT statement.");
48814
49585
  }
48815
49586
  const right = await evalAssertOperand(stmt.right, client, options, cacheContext, tempTables);
48816
- if (!compareScalarValues(stmt.op, left, right, semantics)) {
48817
- throw new AssertError(`assertion failed: ${stmt.text} (actual: ${left}).`);
48818
- }
48819
- return { type: "ASSERT", condition: stmt.text };
49587
+ return { passed: compareScalarValues(stmt.op, left, right, semantics), actual: left };
48820
49588
  }
48821
49589
  async function evalAssertOperand(operand, client, options, cacheContext, tempTables) {
48822
49590
  switch (operand.type) {
@@ -49156,7 +49924,7 @@ async function executeSelect(stmt, client, options, cacheContext, cteCache, capt
49156
49924
  const subqueryWarnings = /* @__PURE__ */ new Set();
49157
49925
  await validateSelectGroupingPlanning(stmt, client, cacheContext, cteCache);
49158
49926
  if (isNoFromSelect(stmt)) {
49159
- result = executeNoFromSelect(stmt);
49927
+ result = executeNoFromSelect(stmt, options);
49160
49928
  if (captureColumnMeta) {
49161
49929
  materializedMetaBySelectResult.set(
49162
49930
  result,
@@ -49637,13 +50405,30 @@ function validateNoFromColumns(stmt) {
49637
50405
  }
49638
50406
  }
49639
50407
  }
49640
- function executeNoFromSelect(stmt) {
50408
+ function executeNoFromSelect(stmt, options) {
49641
50409
  if (stmt.joins.length > 0 || stmt.where || normalizeGroupingSpec(stmt).type !== "NONE" || stmt.having || stmt.orderBy.length > 0 || stmt.distinct) {
49642
50410
  throw new Error("ArgumentError: JOIN/WHERE/GROUP BY/HAVING/ORDER BY/DISTINCT are not supported without FROM.");
49643
50411
  }
49644
50412
  validateNoFromColumns(stmt);
49645
- const windowed = applyWindow([{}], stmt.columns);
49646
- const { rows: projected, columns } = project(windowed, stmt.columns);
50413
+ const windowed = applyWindow(
50414
+ [{}],
50415
+ stmt.columns,
50416
+ void 0,
50417
+ void 0,
50418
+ void 0,
50419
+ void 0,
50420
+ statementEvaluationContext(options)
50421
+ );
50422
+ const { rows: projected, columns } = project(
50423
+ windowed,
50424
+ stmt.columns,
50425
+ void 0,
50426
+ void 0,
50427
+ void 0,
50428
+ void 0,
50429
+ void 0,
50430
+ statementEvaluationContext(options)
50431
+ );
49647
50432
  const rows = applyLimit(projected, stmt.limit, stmt.offset);
49648
50433
  return { type: "SELECT", rows, columns, rowCount: rows.length, warnings: [] };
49649
50434
  }
@@ -49719,8 +50504,10 @@ async function executeSimpleSelect(stmt, client, options, cacheContext, orderPla
49719
50504
  stmt.columns,
49720
50505
  void 0,
49721
50506
  fieldTypeResolvers.row,
49722
- projectionSemanticsResolver
49723
- )
50507
+ projectionSemanticsResolver,
50508
+ statementEvaluationContext(options)
50509
+ ),
50510
+ statementEvaluationContext(options)
49724
50511
  );
49725
50512
  rows = applyLimit(rows, stmt.limit, stmt.offset);
49726
50513
  }
@@ -49730,7 +50517,9 @@ async function executeSimpleSelect(stmt, client, options, cacheContext, orderPla
49730
50517
  void 0,
49731
50518
  fieldTypeResolvers.row,
49732
50519
  void 0,
49733
- projectionSemanticsResolver
50520
+ projectionSemanticsResolver,
50521
+ void 0,
50522
+ statementEvaluationContext(options)
49734
50523
  );
49735
50524
  const columns = await restoreEmptyWildcardColumns(
49736
50525
  stmt,
@@ -50893,7 +51682,8 @@ async function executeFullScanSelect(stmt, client, options, cacheContext, cteCac
50893
51682
  ...prefilterPlan ? { residualWhere: prefilterPlan.residualWhere } : boundServerFunctionPlan ? { residualWhere: boundServerFunctionPlan.joinPlan.residualWhere } : {},
50894
51683
  resolvedGroupingSpec: resolvedGroupingSpecs.get(stmt),
50895
51684
  plainGroupByPlan,
50896
- warnings
51685
+ warnings,
51686
+ evaluationContext: statementEvaluationContext(options)
50897
51687
  });
50898
51688
  const columns = await restoreEmptyWildcardColumns(
50899
51689
  stmt,
@@ -51720,7 +52510,8 @@ async function executeFullScanWithCte(stmt, client, options, cteCache, cacheCont
51720
52510
  tableColumns,
51721
52511
  hiddenQualifiedAliases,
51722
52512
  resolvedGroupingSpec,
51723
- plainGroupByPlan
52513
+ plainGroupByPlan,
52514
+ evaluationContext: statementEvaluationContext(options)
51724
52515
  });
51725
52516
  const columns = await restoreEmptyWildcardColumns(
51726
52517
  stmt,
@@ -52846,7 +53637,12 @@ async function materializeValidationCandidates(stmt, operation, client, options,
52846
53637
  evaluationTypes = new Map(stmt.fields.map((field) => [field, infoByCode.get(field)?.fieldType ?? ""]));
52847
53638
  assertCheckComparisonTypes(stmt, evaluationTypes);
52848
53639
  rows = stmt.values.map((row) => row.map(
52849
- (value, i) => value.type === "CASE_VALUE" ? evalCaseWhenValue(value.expr, {}, infoByCode.get(stmt.fields[i])?.fieldType) : value
53640
+ (value, i) => value.type === "CASE_VALUE" ? evalCaseWhenValue(
53641
+ value.expr,
53642
+ {},
53643
+ infoByCode.get(stmt.fields[i])?.fieldType,
53644
+ statementEvaluationContext(options)
53645
+ ) : value
52850
53646
  ));
52851
53647
  } else {
52852
53648
  const selectResult = await dmlSourceMaterializer.materialize(stmt, client, options, cacheContext, tempTables, [...infoByCode.values()]);
@@ -52977,7 +53773,12 @@ async function materializeUpdateValidationCandidates(stmt, client, options, cach
52977
53773
  });
52978
53774
  snapshotsById = indexDmlUpdateSnapshots(resolved.records);
52979
53775
  evaluationById = snapshotsById;
52980
- records = updateToPutBatchesArith(stmt, resolved.records, fieldTypes).flatMap((batch) => batch.records);
53776
+ records = updateToPutBatchesArith(
53777
+ stmt,
53778
+ resolved.records,
53779
+ fieldTypes,
53780
+ statementEvaluationContext(options)
53781
+ ).flatMap((batch) => batch.records);
52981
53782
  } else {
52982
53783
  const getParams = updateToGetQuery(stmt);
52983
53784
  if (checkTargetFields.length > 0) {
@@ -53145,7 +53946,12 @@ async function materializeUpdateFromValidationCandidates(stmt, from, client, opt
53145
53946
  snapshotFields
53146
53947
  );
53147
53948
  const fieldTypes = await getFieldTypeMap(stmt.appId, client, cacheContext);
53148
- const records = updateFromToPutBatches(stmt, matched, fieldTypes).flatMap((batch) => batch.records);
53949
+ const records = updateFromToPutBatches(
53950
+ stmt,
53951
+ matched,
53952
+ fieldTypes,
53953
+ statementEvaluationContext(options)
53954
+ ).flatMap((batch) => batch.records);
53149
53955
  const matchedById = new Map(matched.map((pair) => [Number(pair.target["$id"]?.value), pair]));
53150
53956
  const snapshotsById = snapshotFields ? indexDmlUpdateSnapshots(matched.map((pair) => pair.target)) : /* @__PURE__ */ new Map();
53151
53957
  return records.sort((a, b) => a.id - b.id).map((entry, index) => ({
@@ -53377,7 +54183,7 @@ async function executeInsert(stmt, client, options, cacheContext) {
53377
54183
  const fieldInfos = await loadWritableTopLevelDmlFields(stmt.appId, stmt.fields, client, cacheContext);
53378
54184
  const numberPrecision = await loadNumberPrecisionForTargets(stmt.appId, stmt.fields, fieldInfos, client, cacheContext);
53379
54185
  const fieldTypes = await getFieldTypeMap(stmt.appId, client, cacheContext);
53380
- const batches = insertToPostBatches(stmt, fieldTypes);
54186
+ const batches = insertToPostBatches(stmt, fieldTypes, statementEvaluationContext(options));
53381
54187
  assertValidDmlRecords(batches.flatMap((batch) => batch.records), stmt.fields, fieldInfos, numberPrecision);
53382
54188
  const createdIds = [];
53383
54189
  for (const batch of batches) {
@@ -53986,7 +54792,12 @@ async function executeUpdate(stmt, client, options, cacheContext, tempTables) {
53986
54792
  { maxRecords: maxRecords2, parallel: options.fetchParallel ?? 1 }
53987
54793
  );
53988
54794
  const records = resolved2.records;
53989
- const batches2 = updateToPutBatchesArith(stmt, records, fieldTypes);
54795
+ const batches2 = updateToPutBatchesArith(
54796
+ stmt,
54797
+ records,
54798
+ fieldTypes,
54799
+ statementEvaluationContext(options)
54800
+ );
53990
54801
  assertValidDmlRecords(batches2.flatMap((batch) => batch.records.map((entry) => entry.record)), targetFields, fieldInfos, numberPrecision);
53991
54802
  if (options.confirm) {
53992
54803
  const ok = await options.confirm(records.length, "UPDATE");
@@ -54043,7 +54854,13 @@ async function executeApplyPatchUpdate(stmt, client, options, cacheContext, stat
54043
54854
  throw new Error(`ArgumentError: APPLY snapshot $id ${actualId} does not match requested $id ${requestedId}.`);
54044
54855
  }
54045
54856
  requireRevision(response.records[0]);
54046
- const plan = buildApplyPatchPlan({ statement: stmt, snapshot: response.records[0], fieldInfos, metadata });
54857
+ const plan = buildApplyPatchPlan({
54858
+ statement: stmt,
54859
+ snapshot: response.records[0],
54860
+ fieldInfos,
54861
+ metadata,
54862
+ evaluationContext: statementEvaluationContext(options)
54863
+ });
54047
54864
  const fieldIndex = buildPostImageFieldIndex(
54048
54865
  fieldInfos,
54049
54866
  stmt.assignments.map((assignment) => assignment.field)
@@ -54242,7 +55059,8 @@ async function selectApplyParentSnapshots(stmt, client, options, fieldInfos, cac
54242
55059
  row,
54243
55060
  resolvers.fieldTypeResolver,
54244
55061
  selectionPlan.appliedKlikes,
54245
- resolvers.fieldSemanticsResolver
55062
+ resolvers.fieldSemanticsResolver,
55063
+ statementEvaluationContext(options)
54246
55064
  )).map(({ snapshot }) => snapshot);
54247
55065
  }
54248
55066
  function collectApplyParentWhereFields(where) {
@@ -54483,7 +55301,12 @@ function applyValidationColumnMeta(columns, fieldInfos, appId) {
54483
55301
  async function executeUpdateFrom(stmt, from, client, options, cacheContext, tempTables) {
54484
55302
  const matched = await resolveUpdateFromMatchedRecords(stmt, from, client, options, cacheContext, tempTables);
54485
55303
  const fieldTypes = await getFieldTypeMap(stmt.appId, client, cacheContext);
54486
- const batches = updateFromToPutBatches(stmt, matched, fieldTypes);
55304
+ const batches = updateFromToPutBatches(
55305
+ stmt,
55306
+ matched,
55307
+ fieldTypes,
55308
+ statementEvaluationContext(options)
55309
+ );
54487
55310
  const targetFields = stmt.assignments.map((assignment) => assignment.field);
54488
55311
  const fieldInfos = await getFieldsCached(stmt.appId, client, cacheContext);
54489
55312
  const numberPrecision = await loadNumberPrecisionForTargets(stmt.appId, targetFields, fieldInfos, client, cacheContext);
@@ -54557,7 +55380,12 @@ async function executeUpsert(stmt, client, options, cacheContext) {
54557
55380
  stmt.fields.forEach((field, i) => {
54558
55381
  const val = row[i];
54559
55382
  if (val.type === "CASE_VALUE") {
54560
- record2[field] = { value: evalCaseWhenValue(val.expr, {}, fieldTypes.get(field)) };
55383
+ record2[field] = { value: evalCaseWhenValue(
55384
+ val.expr,
55385
+ {},
55386
+ fieldTypes.get(field),
55387
+ statementEvaluationContext(options)
55388
+ ) };
54561
55389
  } else {
54562
55390
  record2[field] = { value: toKintoneValue(val, fieldTypes.get(field)) };
54563
55391
  }
@@ -54678,7 +55506,14 @@ async function executeUpdateSubtable(stmt, client, options, cacheContext) {
54678
55506
  { maxRecords: options.maxRecords ?? 1e4, parallel: options.fetchParallel ?? 1 }
54679
55507
  );
54680
55508
  const expanded = expandRowsForSubtableDml(parents, subtableCode);
54681
- const targets = expanded.filter((r) => evalWhere(stmt.where, r.flat, resolveFieldType));
55509
+ const targets = expanded.filter((r) => evalWhere(
55510
+ stmt.where,
55511
+ r.flat,
55512
+ resolveFieldType,
55513
+ void 0,
55514
+ void 0,
55515
+ statementEvaluationContext(options)
55516
+ ));
54682
55517
  if (options.confirm) {
54683
55518
  const ok = await options.confirm(targets.length, "UPDATE");
54684
55519
  if (!ok) throw new OperationCancelledError("UPDATE", targets.length);
@@ -54698,7 +55533,12 @@ async function executeUpdateSubtable(stmt, client, options, cacheContext) {
54698
55533
  if (a.field.startsWith("_")) {
54699
55534
  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
55535
  }
54701
- updates[a.field] = { value: evaluateSubtableAssignmentValue(a.value, t.flat, resolveFieldType) };
55536
+ updates[a.field] = { value: evaluateSubtableAssignmentValue(
55537
+ a.value,
55538
+ t.flat,
55539
+ resolveFieldType,
55540
+ statementEvaluationContext(options)
55541
+ ) };
54702
55542
  }
54703
55543
  byRid.set(t.rowId, updates);
54704
55544
  }
@@ -54741,7 +55581,14 @@ async function executeDeleteSubtable(stmt, client, options, cacheContext) {
54741
55581
  { maxRecords: options.maxRecords ?? 1e4, parallel: options.fetchParallel ?? 1 }
54742
55582
  );
54743
55583
  const expanded = expandRowsForSubtableDml(parents, subtableCode);
54744
- const targets = expanded.filter((r) => evalWhere(stmt.where, r.flat, resolveFieldType));
55584
+ const targets = expanded.filter((r) => evalWhere(
55585
+ stmt.where,
55586
+ r.flat,
55587
+ resolveFieldType,
55588
+ void 0,
55589
+ void 0,
55590
+ statementEvaluationContext(options)
55591
+ ));
54745
55592
  if (options.confirm) {
54746
55593
  const ok = await options.confirm(targets.length, "DELETE");
54747
55594
  if (!ok) throw new OperationCancelledError("DELETE", targets.length);
@@ -54916,7 +55763,8 @@ async function executeReorder(stmt, client, options, cacheContext) {
54916
55763
  r.flat,
54917
55764
  resolveFieldType,
54918
55765
  void 0,
54919
- resolveReorderSemantics
55766
+ resolveReorderSemantics,
55767
+ statementEvaluationContext(options)
54920
55768
  )).map((r) => r.parentId));
54921
55769
  if (options.confirm) {
54922
55770
  const ok = await options.confirm(targetParentIds.size, "UPDATE");
@@ -54928,7 +55776,13 @@ async function executeReorder(stmt, client, options, cacheContext) {
54928
55776
  if (!parent) continue;
54929
55777
  const rows = getMutableTableRows(parent, stmt.subtableCode);
54930
55778
  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));
55779
+ sortable.sort((a, b) => compareByOrder(
55780
+ a.flat,
55781
+ b.flat,
55782
+ stmt.by,
55783
+ resolveReorderSemantics,
55784
+ statementEvaluationContext(options)
55785
+ ));
54932
55786
  const orderedRowIds = sortable.map((x) => x.row.id ?? "");
54933
55787
  await client.putRecords(buildSubtableReorderPutParams(stmt.appId, pid, getRevision(parent), stmt.subtableCode, orderedRowIds));
54934
55788
  }
@@ -54949,24 +55803,24 @@ function buildFlatRowForSort(parent, subtableCode, row, idx) {
54949
55803
  }
54950
55804
  return flat;
54951
55805
  }
54952
- function compareByOrder(a, b, orderBy, resolveSemantics) {
55806
+ function compareByOrder(a, b, orderBy, resolveSemantics, evaluationContext = {}) {
54953
55807
  for (const item of orderBy) {
54954
- const av = evalOrderKeyForRow(item.key, a);
54955
- const bv = evalOrderKeyForRow(item.key, b);
55808
+ const av = evalOrderKeyForRow(item.key, a, evaluationContext);
55809
+ const bv = evalOrderKeyForRow(item.key, b, evaluationContext);
54956
55810
  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
55811
  const cmp = compareCanonicalValues(av, bv, semantics ?? syntheticSemantics("string"));
54958
55812
  if (cmp !== 0) return item.direction === "ASC" ? cmp : -cmp;
54959
55813
  }
54960
55814
  return 0;
54961
55815
  }
54962
- function evalOrderKeyForRow(key, row) {
55816
+ function evalOrderKeyForRow(key, row, evaluationContext = {}) {
54963
55817
  switch (key.type) {
54964
55818
  case "FIELD_NAME":
54965
55819
  return row[key.name] ?? "";
54966
55820
  case "ARITH_KEY":
54967
- return String(evalArithExpr(key.expr, row));
55821
+ return String(evalArithExpr(key.expr, row, evaluationContext));
54968
55822
  case "FUNC_KEY":
54969
- return evalStringFunc(key.expr, row);
55823
+ return evalStringFunc(key.expr, row, void 0, void 0, evaluationContext);
54970
55824
  case "GROUPING_KEY":
54971
55825
  throw new Error("ArgumentError: GROUPING() is not supported in REORDER BY.");
54972
55826
  }
@@ -56064,7 +56918,16 @@ async function buildBatchExplainPlans(sql, client, injectedVariables, cacheConte
56064
56918
  });
56065
56919
  const invocationCacheContext = createInvocationCacheContext(cacheContext);
56066
56920
  try {
56067
- const statements = parseSqlBatch(sql, enableImport);
56921
+ const header = parseScriptHeader(sql);
56922
+ const headerError = header.diagnostics.find((diagnostic2) => diagnostic2.severity === "error");
56923
+ if (header.hasDirectives && headerError) {
56924
+ throw new Error(`${headerError.code}: ${headerError.message} (${headerError.line}:${headerError.column})`);
56925
+ }
56926
+ const statements = parseSqlBatch(
56927
+ header.hasDirectives ? sql.slice(header.headerEnd) : sql,
56928
+ enableImport,
56929
+ header.hasDirectives && header.meta.dialect === 1
56930
+ );
56068
56931
  const analysis = analyzeBatch(statements);
56069
56932
  const normalizedInjectedVariables = validateDeclaredBatchVariables(statements, injectedVariables);
56070
56933
  const relativeDateVariables = prepareRelativeDateVariables(statements, normalizedInjectedVariables);
@@ -56259,8 +57122,8 @@ function buildBatchStatementPlan(stmt, info, capabilities, orderPlans, plainGrou
56259
57122
  }
56260
57123
  if (stmt.type === "ASSERT") {
56261
57124
  const lines = [
56262
- `ASSERT ${stmt.text}`,
56263
- " check: \u5B9F\u884C\u6642\u306B\u6761\u4EF6\u8A55\u4FA1\uFF08\u4E0D\u6210\u7ACB\u306F AssertError \u3067\u30D0\u30C3\u30C1\u505C\u6B62\u3001\u4EE5\u964D\u306E\u6587\u306F skipped\uFF09"
57125
+ `ASSERT${stmt.warn === true ? " WARN" : ""} ${stmt.text}${stmt.message !== void 0 ? `, '${stmt.message.replace(/'/g, "''")}'` : ""}`,
57126
+ stmt.warn === true ? " check: \u5B9F\u884C\u6642\u306B\u6761\u4EF6\u8A55\u4FA1\uFF08\u4E0D\u6210\u7ACB\u306F\u8B66\u544A\u3068\u3057\u3066\u8A18\u9332\u3057\u3001\u5F8C\u7D9A\u6587\u3092\u7D9A\u884C\uFF09" : " check: \u5B9F\u884C\u6642\u306B\u6761\u4EF6\u8A55\u4FA1\uFF08\u4E0D\u6210\u7ACB\u306F AssertError \u3067\u30D0\u30C3\u30C1\u505C\u6B62\u3001\u4EE5\u964D\u306E\u6587\u306F skipped\uFF09"
56264
57127
  ];
56265
57128
  const subqueries = [stmt.left, stmt.right, stmt.low, stmt.high].filter(
56266
57129
  (o) => o !== null && o.type === "SCALAR_SUBQUERY"
@@ -56282,6 +57145,31 @@ function buildBatchStatementPlan(stmt, info, capabilities, orderPlans, plainGrou
56282
57145
  });
56283
57146
  return lines;
56284
57147
  }
57148
+ if (stmt.type === "EXIT") {
57149
+ const lines = [
57150
+ `EXIT SUCCESS IF ${stmt.text}, '${stmt.message.replace(/'/g, "''")}'`,
57151
+ " check: \u5B9F\u884C\u6642\u306B\u6761\u4EF6\u8A55\u4FA1\uFF08\u6210\u7ACB\u6642\u306F\u6B63\u5E38\u7D42\u4E86\u3057\u3001\u4EE5\u964D\u306E\u6587\u306F skippedReason: exit\uFF09"
57152
+ ];
57153
+ const subqueries = [stmt.left, stmt.right, stmt.low, stmt.high].filter(
57154
+ (o) => o !== null && o.type === "SCALAR_SUBQUERY"
57155
+ );
57156
+ subqueries.forEach((sq, i) => {
57157
+ lines.push(subqueries.length > 1 ? ` subquery[${i + 1}]:` : " subquery:");
57158
+ const subInfo = hasTempTableRef(sq.query) ? info : { ...info, tempTablesReferenced: [] };
57159
+ lines.push(...buildPlanForBatchQuery(
57160
+ sq.query,
57161
+ subInfo,
57162
+ capabilities,
57163
+ orderPlans,
57164
+ plainGroupByPlans,
57165
+ collector,
57166
+ "main",
57167
+ tempSchemaLedger,
57168
+ explainContext
57169
+ ).map((line) => ` ${line}`));
57170
+ });
57171
+ return lines;
57172
+ }
56285
57173
  if (stmt.type === "UPDATE" && (stmt.applyBlocks?.length ?? 0) > 0) {
56286
57174
  return buildExplainPlan(
56287
57175
  stmt,
@@ -57699,6 +58587,9 @@ function toMutationSummary(result) {
57699
58587
  ...result.errTable !== void 0 ? { errTable: result.errTable } : {}
57700
58588
  };
57701
58589
  }
58590
+ if (result.type === "EXIT") {
58591
+ return { condition: result.condition, exited: result.exited, message: result.message };
58592
+ }
57702
58593
  return { reorderedParentCount: result.reorderedParentCount };
57703
58594
  }
57704
58595
  function buildBatchEnvelope(batch, options = {}) {
@@ -57756,6 +58647,10 @@ function buildBatchEnvelope(batch, options = {}) {
57756
58647
  ...s.result.deletedRows ? { deletedRows: s.result.deletedRows } : {},
57757
58648
  ...s.result.diagnostic ? { diagnostic: s.result.diagnostic } : {}
57758
58649
  });
58650
+ } else if (s.status === "success" && s.result?.type === "ASSERT") {
58651
+ entry.condition = s.result.condition;
58652
+ if (s.result.passed !== void 0) entry.passed = s.result.passed;
58653
+ if (s.result.warning !== void 0) entry.warning = s.result.warning;
57759
58654
  } else if (s.status === "success" && s.result && s.result.type !== "SELECT" && s.result.type !== "ASSERT") {
57760
58655
  Object.assign(entry, toMutationSummary(s.result));
57761
58656
  }
@@ -60203,7 +61098,9 @@ function toAssertPayload(result) {
60203
61098
  return {
60204
61099
  ok: true,
60205
61100
  type: result.type,
60206
- condition: result.condition
61101
+ condition: result.condition,
61102
+ ...result.passed !== void 0 ? { passed: result.passed } : {},
61103
+ ...result.warning !== void 0 ? { warning: result.warning } : {}
60207
61104
  };
60208
61105
  }
60209
61106
  function toDmlValidationPayload(result) {
@@ -60276,6 +61173,9 @@ function toMutationPayload(result) {
60276
61173
  ...result.errTable !== void 0 ? { errTable: result.errTable } : {}
60277
61174
  };
60278
61175
  }
61176
+ if (result.type === "EXIT") {
61177
+ return { ok: true, type: result.type, condition: result.condition, exited: result.exited, message: result.message };
61178
+ }
60279
61179
  return {
60280
61180
  ok: true,
60281
61181
  type: result.type,