@deepagents/text2sql 4.3.0 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/CLICKHOUSE-DEPLOYMENT.md +181 -0
  2. package/README.md +33 -7
  3. package/dist/bin/sql.js +33 -51
  4. package/dist/index.js +68 -299
  5. package/dist/index.js.map +4 -4
  6. package/dist/lib/adapters/adapter.d.ts +8 -1
  7. package/dist/lib/adapters/adapter.d.ts.map +1 -1
  8. package/dist/lib/adapters/bigquery/bigquery.d.ts.map +1 -1
  9. package/dist/lib/adapters/bigquery/bigquery.sql-policy.d.ts +9 -0
  10. package/dist/lib/adapters/bigquery/bigquery.sql-policy.d.ts.map +1 -0
  11. package/dist/lib/adapters/bigquery/index.d.ts +1 -0
  12. package/dist/lib/adapters/bigquery/index.d.ts.map +1 -1
  13. package/dist/lib/adapters/bigquery/index.js +303 -259
  14. package/dist/lib/adapters/bigquery/index.js.map +4 -4
  15. package/dist/lib/adapters/clickhouse/clickhouse.d.ts +22 -0
  16. package/dist/lib/adapters/clickhouse/clickhouse.d.ts.map +1 -0
  17. package/dist/lib/adapters/clickhouse/clickhouse.sql-policy.d.ts +8 -0
  18. package/dist/lib/adapters/clickhouse/clickhouse.sql-policy.d.ts.map +1 -0
  19. package/dist/lib/adapters/clickhouse/constraint.clickhouse.grounding.d.ts +8 -0
  20. package/dist/lib/adapters/clickhouse/constraint.clickhouse.grounding.d.ts.map +1 -0
  21. package/dist/lib/adapters/clickhouse/index.d.ts +33 -0
  22. package/dist/lib/adapters/clickhouse/index.d.ts.map +1 -0
  23. package/dist/lib/adapters/clickhouse/index.js +1544 -0
  24. package/dist/lib/adapters/clickhouse/index.js.map +7 -0
  25. package/dist/lib/adapters/clickhouse/indexes.clickhouse.grounding.d.ts +8 -0
  26. package/dist/lib/adapters/clickhouse/indexes.clickhouse.grounding.d.ts.map +1 -0
  27. package/dist/lib/adapters/clickhouse/info.clickhouse.grounding.d.ts +8 -0
  28. package/dist/lib/adapters/clickhouse/info.clickhouse.grounding.d.ts.map +1 -0
  29. package/dist/lib/adapters/clickhouse/row-count.clickhouse.grounding.d.ts +8 -0
  30. package/dist/lib/adapters/clickhouse/row-count.clickhouse.grounding.d.ts.map +1 -0
  31. package/dist/lib/adapters/clickhouse/table.clickhouse.grounding.d.ts +11 -0
  32. package/dist/lib/adapters/clickhouse/table.clickhouse.grounding.d.ts.map +1 -0
  33. package/dist/lib/adapters/clickhouse/view.clickhouse.grounding.d.ts +9 -0
  34. package/dist/lib/adapters/clickhouse/view.clickhouse.grounding.d.ts.map +1 -0
  35. package/dist/lib/adapters/groundings/abstract.grounding.d.ts +11 -16
  36. package/dist/lib/adapters/groundings/abstract.grounding.d.ts.map +1 -1
  37. package/dist/lib/adapters/groundings/index.js +16 -0
  38. package/dist/lib/adapters/groundings/index.js.map +2 -2
  39. package/dist/lib/adapters/groundings/table.grounding.d.ts +1 -0
  40. package/dist/lib/adapters/groundings/table.grounding.d.ts.map +1 -1
  41. package/dist/lib/adapters/groundings/view.grounding.d.ts +1 -0
  42. package/dist/lib/adapters/groundings/view.grounding.d.ts.map +1 -1
  43. package/dist/lib/adapters/mysql/index.d.ts +1 -0
  44. package/dist/lib/adapters/mysql/index.d.ts.map +1 -1
  45. package/dist/lib/adapters/mysql/index.js +317 -259
  46. package/dist/lib/adapters/mysql/index.js.map +4 -4
  47. package/dist/lib/adapters/mysql/mysql.d.ts.map +1 -1
  48. package/dist/lib/adapters/mysql/mysql.sql-policy.d.ts +11 -0
  49. package/dist/lib/adapters/mysql/mysql.sql-policy.d.ts.map +1 -0
  50. package/dist/lib/adapters/parser-sql-policy.d.ts +23 -0
  51. package/dist/lib/adapters/parser-sql-policy.d.ts.map +1 -0
  52. package/dist/lib/adapters/postgres/index.d.ts +1 -0
  53. package/dist/lib/adapters/postgres/index.d.ts.map +1 -1
  54. package/dist/lib/adapters/postgres/index.js +323 -259
  55. package/dist/lib/adapters/postgres/index.js.map +4 -4
  56. package/dist/lib/adapters/postgres/postgres.d.ts.map +1 -1
  57. package/dist/lib/adapters/postgres/postgres.sql-policy.d.ts +10 -0
  58. package/dist/lib/adapters/postgres/postgres.sql-policy.d.ts.map +1 -0
  59. package/dist/lib/adapters/spreadsheet/index.js +301 -259
  60. package/dist/lib/adapters/spreadsheet/index.js.map +4 -4
  61. package/dist/lib/adapters/spreadsheet/parser.d.ts.map +1 -1
  62. package/dist/lib/adapters/sql-policy.d.ts +19 -0
  63. package/dist/lib/adapters/sql-policy.d.ts.map +1 -0
  64. package/dist/lib/adapters/sqlite/index.d.ts +1 -0
  65. package/dist/lib/adapters/sqlite/index.d.ts.map +1 -1
  66. package/dist/lib/adapters/sqlite/index.js +303 -259
  67. package/dist/lib/adapters/sqlite/index.js.map +4 -4
  68. package/dist/lib/adapters/sqlite/sqlite.d.ts.map +1 -1
  69. package/dist/lib/adapters/sqlite/sqlite.sql-policy.d.ts +8 -0
  70. package/dist/lib/adapters/sqlite/sqlite.sql-policy.d.ts.map +1 -0
  71. package/dist/lib/adapters/sqlserver/index.d.ts +1 -0
  72. package/dist/lib/adapters/sqlserver/index.d.ts.map +1 -1
  73. package/dist/lib/adapters/sqlserver/index.js +310 -259
  74. package/dist/lib/adapters/sqlserver/index.js.map +4 -4
  75. package/dist/lib/adapters/sqlserver/sqlserver.d.ts.map +1 -1
  76. package/dist/lib/adapters/sqlserver/sqlserver.sql-policy.d.ts +11 -0
  77. package/dist/lib/adapters/sqlserver/sqlserver.sql-policy.d.ts.map +1 -0
  78. package/dist/lib/agents/exceptions.d.ts +1 -1
  79. package/dist/lib/agents/sql-transform-plugins.d.ts +1 -2
  80. package/dist/lib/agents/sql-transform-plugins.d.ts.map +1 -1
  81. package/dist/lib/agents/sql.agent.d.ts.map +1 -1
  82. package/dist/lib/sql-command.d.ts.map +1 -1
  83. package/dist/lib/sql-hooks.d.ts +5 -1
  84. package/dist/lib/sql-hooks.d.ts.map +1 -1
  85. package/dist/lib/sql-meta-hook.d.ts +6 -2
  86. package/dist/lib/sql-meta-hook.d.ts.map +1 -1
  87. package/dist/lib/sql-scope-error.d.ts +3 -0
  88. package/dist/lib/sql-scope-error.d.ts.map +1 -0
  89. package/dist/lib/sql-validate-reminder.d.ts +3 -3
  90. package/dist/lib/sql-validate-reminder.d.ts.map +1 -1
  91. package/dist/lib/synthesis/index.js +32 -38
  92. package/dist/lib/synthesis/index.js.map +4 -4
  93. package/package.json +30 -24
  94. package/dist/lib/adapters/runtime-scope.d.ts +0 -16
  95. package/dist/lib/adapters/runtime-scope.d.ts.map +0 -1
@@ -2,10 +2,10 @@
2
2
  import { format as formatSql } from "sql-formatter";
3
3
 
4
4
  // packages/text2sql/src/lib/agents/exceptions.ts
5
- var sqlValidationMarker = Symbol("SQLValidationError");
6
- var unanswerableSqlMarker = Symbol("UnanswerableSQLError");
7
- var sqlScopeMarker = Symbol("SQLScopeError");
8
- var sqlReadOnlyMarker = Symbol("SQLReadOnlyError");
5
+ var sqlValidationMarker = /* @__PURE__ */ Symbol("SQLValidationError");
6
+ var unanswerableSqlMarker = /* @__PURE__ */ Symbol("UnanswerableSQLError");
7
+ var sqlScopeMarker = /* @__PURE__ */ Symbol("SQLScopeError");
8
+ var sqlReadOnlyMarker = /* @__PURE__ */ Symbol("SQLReadOnlyError");
9
9
  var SQLValidationError = class _SQLValidationError extends Error {
10
10
  [sqlValidationMarker];
11
11
  constructor(message) {
@@ -170,159 +170,15 @@ function createGroundingContext(options = {}) {
170
170
  };
171
171
  }
172
172
 
173
- // packages/text2sql/src/lib/adapters/runtime-scope.ts
174
- import nodeSqlParser from "node-sql-parser";
175
- var { Parser } = nodeSqlParser;
176
- var parser = new Parser();
177
- function parseStatementTypes(sql, dialect) {
178
- const ast = parser.astify(sql, { database: dialect });
179
- const statements = Array.isArray(ast) ? ast : [ast];
180
- return statements.flatMap(
181
- (statement) => isAstLike(statement) && typeof statement.type === "string" ? [statement.type] : []
182
- );
183
- }
184
- function extractBaseEntityReferences(sql, dialect) {
185
- const ast = parser.astify(sql, { database: dialect });
186
- const state = {
187
- cteNames: /* @__PURE__ */ new Set(),
188
- references: /* @__PURE__ */ new Map()
189
- };
190
- visitNode(ast, state);
191
- return Array.from(state.references.values());
192
- }
193
- function buildOutOfScopePayload(sql, referencedEntities, allowedEntities) {
194
- return {
195
- error: `Query references entities outside grounded scope: ${referencedEntities.join(", ")}`,
196
- error_type: "OUT_OF_SCOPE",
197
- suggestion: "Restrict the query to grounded tables/views or expand grounding to include the referenced entities.",
198
- sql_attempted: sql,
199
- referenced_entities: referencedEntities,
200
- allowed_entities: allowedEntities
201
- };
202
- }
203
- function buildScopeParseErrorPayload(sql, dialect, error) {
204
- const parserError = error instanceof Error ? error.message : String(error ?? "Unknown error");
205
- return {
206
- error: `SQL scope analysis failed before validation/execution: ${parserError}`,
207
- error_type: "SQL_SCOPE_PARSE_ERROR",
208
- suggestion: "Rewrite the query into simpler SQL that can be analyzed safely, or extend parser coverage for this dialect feature.",
209
- sql_attempted: sql,
210
- parser_dialect: dialect,
211
- parser_error: parserError
212
- };
213
- }
214
- function visitNode(node, state) {
215
- if (Array.isArray(node)) {
216
- for (const item of node) {
217
- visitNode(item, state);
218
- }
219
- return;
220
- }
221
- if (!isAstLike(node)) {
222
- return;
223
- }
224
- if (isStatementNode(node)) {
225
- visitStatement(node, state);
226
- return;
227
- }
228
- if (isTableReferenceNode(node)) {
229
- addReference(node, state);
230
- }
231
- for (const value of Object.values(node)) {
232
- visitNode(value, state);
233
- }
234
- }
235
- function visitStatement(node, parentState) {
236
- const localState = {
237
- cteNames: new Set(parentState.cteNames),
238
- references: parentState.references
239
- };
240
- const withItems = Array.isArray(node.with) ? node.with : [];
241
- for (const item of withItems) {
242
- if (!isAstLike(item)) {
243
- continue;
244
- }
245
- const cteName = readCteName(item);
246
- if (cteName) {
247
- localState.cteNames.add(caseFold(cteName));
248
- }
249
- }
250
- for (const item of withItems) {
251
- if (!isAstLike(item)) {
252
- continue;
253
- }
254
- visitNode(item.stmt, localState);
255
- }
256
- for (const [key, value] of Object.entries(node)) {
257
- if (key === "with") {
258
- continue;
259
- }
260
- visitNode(value, localState);
261
- }
262
- }
263
- function addReference(node, state) {
264
- const table2 = typeof node.table === "string" ? node.table : null;
265
- if (!table2) {
266
- return;
267
- }
268
- if (state.cteNames.has(caseFold(table2))) {
269
- return;
270
- }
271
- const db = typeof node.db === "string" ? node.db : null;
272
- const key = db ? `${db}.${table2}` : table2;
273
- if (!state.references.has(key)) {
274
- state.references.set(key, { db, table: table2 });
275
- }
276
- }
277
- function readCteName(node) {
278
- const name = node.name;
279
- if (typeof name === "string") {
280
- return name;
281
- }
282
- if (!isAstLike(name)) {
283
- return void 0;
284
- }
285
- const value = name.value;
286
- return typeof value === "string" ? value : void 0;
287
- }
288
- function isStatementNode(node) {
289
- const type = node.type;
290
- return typeof type === "string" && ["delete", "insert", "replace", "select", "update"].includes(type);
291
- }
292
- function isTableReferenceNode(node) {
293
- if (node.type === "column_ref") {
294
- return false;
295
- }
296
- if (typeof node.table !== "string") {
297
- return false;
298
- }
299
- return "addition" in node || "as" in node || "db" in node || "join" in node || "operator" in node || "surround" in node || "table_hint" in node || "temporal_table" in node;
300
- }
301
- function isAstLike(value) {
302
- return typeof value === "object" && value !== null;
303
- }
304
- function caseFold(value) {
305
- return value.toLowerCase();
306
- }
307
-
308
173
  // packages/text2sql/src/lib/adapters/adapter.ts
309
- var PARSER_DIALECTS_BY_FORMATTER_LANGUAGE = {
310
- sqlite: ["sqlite", "mysql"],
311
- postgresql: ["postgresql"],
312
- bigquery: ["bigquery"],
313
- transactsql: ["transactsql"],
314
- mysql: ["mysql"]
315
- };
316
- function parserDialectsFor(formatterLanguage) {
317
- const candidates = PARSER_DIALECTS_BY_FORMATTER_LANGUAGE[formatterLanguage];
318
- if (!candidates) {
319
- throw new TypeError(
320
- `No scope dialect mapping for formatter language "${formatterLanguage}". Add it to PARSER_DIALECTS_BY_FORMATTER_LANGUAGE in adapter.ts.`
321
- );
322
- }
323
- return candidates;
324
- }
325
174
  var Adapter = class {
175
+ #policyAnalyzer;
176
+ /**
177
+ * Injects the strategy that guards validate() and execute().
178
+ */
179
+ constructor(policyAnalyzer) {
180
+ this.#policyAnalyzer = policyAnalyzer;
181
+ }
326
182
  /**
327
183
  * Introspect the database schema and return context fragments.
328
184
  *
@@ -358,14 +214,14 @@ var Adapter = class {
358
214
  }
359
215
  /**
360
216
  * Resolve the allowed entity names (tables + views) from grounding config.
361
- * Runs all configured groundings and returns the resolved set of names.
217
+ * Asks each grounding to contribute its entities; annotators contribute
218
+ * nothing, so their metadata scans are skipped.
362
219
  * Results are NOT cached — call once and store the result.
363
220
  */
364
221
  async resolveAllowedEntities() {
365
222
  const ctx = createGroundingContext();
366
223
  for (const fn of this.grounding) {
367
- const grounding = fn(this);
368
- await grounding.execute(ctx);
224
+ await fn(this).contributeEntities(ctx);
369
225
  }
370
226
  return [...ctx.tables.map((t) => t.name), ...ctx.views.map((v) => v.name)];
371
227
  }
@@ -542,120 +398,33 @@ var Adapter = class {
542
398
  #decodeShellEscapes(sql) {
543
399
  return sql.replace(/\\n/g, "\n").replace(/\\t/g, " ").replace(/\\([().*])/g, "$1").replace(/\\(?=$)/gm, "");
544
400
  }
545
- #checkReadOnly(sql) {
546
- const statementTypes = this.#readParsedStatementTypes(sql);
547
- if (statementTypes) {
548
- if (statementTypes.length === 1 && statementTypes[0] === "select") {
549
- return null;
550
- }
551
- return "only SELECT or WITH queries allowed";
552
- }
553
- const keyword = this.#firstStatementKeyword(sql);
554
- if (keyword === "SELECT" || keyword === "WITH") return null;
555
- return "only SELECT or WITH queries allowed";
556
- }
557
- #readParsedStatementTypes(sql) {
558
- for (const dialect of parserDialectsFor(this.formatterLanguage)) {
559
- try {
560
- return parseStatementTypes(sql, dialect);
561
- } catch {
562
- }
563
- }
564
- return null;
565
- }
566
- #firstStatementKeyword(sql) {
567
- let offset = 0;
568
- while (offset < sql.length) {
569
- if (/\s/.test(sql[offset])) {
570
- offset++;
571
- continue;
572
- }
573
- if (sql.startsWith("--", offset)) {
574
- offset += 2;
575
- while (offset < sql.length && sql[offset] !== "\n" && sql[offset] !== "\r") {
576
- offset++;
577
- }
578
- continue;
579
- }
580
- if (sql.startsWith("/*", offset)) {
581
- const commentEnd = sql.indexOf("*/", offset + 2);
582
- if (commentEnd === -1) return null;
583
- offset = commentEnd + 2;
584
- continue;
585
- }
586
- const keyword = /^[A-Za-z]+/.exec(sql.slice(offset));
587
- return keyword ? keyword[0].toUpperCase() : null;
588
- }
589
- return null;
590
- }
591
401
  #cachedAllowedEntities = null;
592
402
  async #resolveScope() {
593
403
  if (this.#cachedAllowedEntities) return this.#cachedAllowedEntities;
594
404
  this.#cachedAllowedEntities = await this.resolveAllowedEntities();
595
405
  return this.#cachedAllowedEntities;
596
406
  }
597
- async #checkScope(sql, allowedEntities) {
598
- const candidates = parserDialectsFor(this.formatterLanguage);
599
- let references = null;
600
- let lastError;
601
- let lastDialect = candidates[0];
602
- for (const candidate of candidates) {
603
- try {
604
- references = extractBaseEntityReferences(sql, candidate);
605
- break;
606
- } catch (error) {
607
- lastDialect = candidate;
608
- lastError = error;
609
- }
610
- }
611
- if (references === null) {
612
- return buildScopeParseErrorPayload(sql, lastDialect, lastError);
613
- }
614
- if (references.length === 0) return null;
615
- const allowedQualified = new Set(
616
- allowedEntities.map((e) => e.toLowerCase())
617
- );
618
- const allowedUnqualified = /* @__PURE__ */ new Set();
619
- for (const entity of allowedEntities) {
620
- const dot = entity.lastIndexOf(".");
621
- if (dot !== -1) {
622
- allowedUnqualified.add(entity.slice(dot + 1).toLowerCase());
623
- } else {
624
- allowedUnqualified.add(entity.toLowerCase());
625
- }
626
- }
627
- const outOfScope = references.map((ref) => ref.db ? `${ref.db}.${ref.table}` : ref.table).filter((name) => {
628
- const lower = name.toLowerCase();
629
- if (name.includes(".")) {
630
- if (allowedQualified.has(lower)) return false;
631
- const parts = lower.split(".");
632
- if (parts.length >= 3) {
633
- const datasetTable = parts.slice(-2).join(".");
634
- if (allowedQualified.has(datasetTable)) return false;
635
- }
636
- return true;
637
- }
638
- return !allowedQualified.has(lower) && !allowedUnqualified.has(lower);
407
+ async #analyzePolicy(sql) {
408
+ return this.#policyAnalyzer.analyze(sql, {
409
+ resolveAllowedEntities: () => this.#resolveScope()
639
410
  });
640
- if (outOfScope.length === 0) return null;
641
- return buildOutOfScopePayload(sql, outOfScope, allowedEntities);
642
411
  }
643
412
  async validate(sql) {
644
413
  const decoded = this.#decodeShellEscapes(sql);
645
- const readOnlyError = this.#checkReadOnly(decoded);
646
- if (readOnlyError) return readOnlyError;
647
- const allowed = await this.#resolveScope();
648
- const scopeError = await this.#checkScope(decoded, allowed);
649
- if (scopeError) return JSON.stringify(scopeError);
414
+ const violation = await this.#analyzePolicy(decoded);
415
+ if (violation?.kind === "read-only") return violation.message;
416
+ if (violation?.kind === "scope") return JSON.stringify(violation.payload);
650
417
  return this.validateImpl(decoded);
651
418
  }
652
419
  async execute(sql) {
653
420
  const decoded = this.#decodeShellEscapes(sql);
654
- const readOnlyError = this.#checkReadOnly(decoded);
655
- if (readOnlyError) throw new SQLReadOnlyError(readOnlyError);
656
- const allowed = await this.#resolveScope();
657
- const scopeError = await this.#checkScope(decoded, allowed);
658
- if (scopeError) throw new SQLScopeError(scopeError);
421
+ const violation = await this.#analyzePolicy(decoded);
422
+ if (violation?.kind === "read-only") {
423
+ throw new SQLReadOnlyError(violation.message);
424
+ }
425
+ if (violation?.kind === "scope") {
426
+ throw new SQLScopeError(violation.payload);
427
+ }
659
428
  return this.executeImpl(decoded);
660
429
  }
661
430
  /**
@@ -736,6 +505,16 @@ var AbstractGrounding = class {
736
505
  this.name = name;
737
506
  this.phase = phase;
738
507
  }
508
+ /**
509
+ * Populate ctx with the tables/views this grounding makes available for scope
510
+ * resolution. Annotators decorate entities other groundings produced and add
511
+ * no membership, so the default is a no-op; entity-producing groundings
512
+ * override it. This lets scope resolution skip the annotators' metadata scans.
513
+ *
514
+ * @param _ctx - Shared context for accumulating entity membership
515
+ */
516
+ async contributeEntities(_ctx) {
517
+ }
739
518
  };
740
519
 
741
520
  // packages/text2sql/src/lib/adapters/groundings/constraint.grounding.ts
@@ -869,6 +648,9 @@ var TableGrounding = class extends AbstractGrounding {
869
648
  this.#forward = config.forward;
870
649
  this.#backward = config.backward;
871
650
  }
651
+ async contributeEntities(ctx) {
652
+ await this.execute(ctx);
653
+ }
872
654
  /**
873
655
  * Execute the grounding process.
874
656
  * Writes discovered tables and relationships to the context.
@@ -1014,6 +796,264 @@ var TableGrounding = class extends AbstractGrounding {
1014
796
  }
1015
797
  };
1016
798
 
799
+ // packages/text2sql/src/lib/adapters/parser-sql-policy.ts
800
+ import nodeSqlParser from "node-sql-parser";
801
+
802
+ // packages/text2sql/src/lib/sql-scope-error.ts
803
+ function buildScopeParseErrorPayload(sql, parserDialect, error) {
804
+ const parserError = error instanceof Error ? error.message : String(error ?? "Unknown error");
805
+ return {
806
+ error: `SQL scope analysis failed before validation/execution: ${parserError}`,
807
+ error_type: "SQL_SCOPE_PARSE_ERROR",
808
+ suggestion: "Rewrite the query into simpler SQL that can be analyzed safely, or extend parser coverage for this dialect feature.",
809
+ sql_attempted: sql,
810
+ parser_dialect: parserDialect,
811
+ parser_error: parserError
812
+ };
813
+ }
814
+
815
+ // packages/text2sql/src/lib/adapters/parser-sql-policy.ts
816
+ var READ_ONLY_MESSAGE = "only SELECT or WITH queries allowed";
817
+ var { Parser } = nodeSqlParser;
818
+ var parser = new Parser();
819
+ var ParserSqlPolicyAnalyzer = class {
820
+ readOnlyPolicy = {};
821
+ async analyze(sql, context) {
822
+ if (!this.#isReadOnly(sql)) {
823
+ return { kind: "read-only", message: READ_ONLY_MESSAGE };
824
+ }
825
+ const scopeError = await this.#checkScope(sql, context);
826
+ return scopeError ? { kind: "scope", payload: scopeError } : null;
827
+ }
828
+ #isReadOnly(sql) {
829
+ const statements = this.#readParsedStatements(sql);
830
+ if (statements) {
831
+ return statements.length === 1 && statements[0]?.type === "select" && !containsBlockedOperation(statements[0], this.readOnlyPolicy);
832
+ }
833
+ const keyword = firstStatementKeyword(sql);
834
+ return keyword === "SELECT" || keyword === "WITH";
835
+ }
836
+ #readParsedStatements(sql) {
837
+ for (const dialect of this.dialects) {
838
+ try {
839
+ return parseStatements(sql, dialect);
840
+ } catch {
841
+ }
842
+ }
843
+ return null;
844
+ }
845
+ async #checkScope(sql, context) {
846
+ let references = null;
847
+ let lastError;
848
+ let lastDialect = this.dialects[0];
849
+ for (const dialect of this.dialects) {
850
+ try {
851
+ references = extractBaseEntityReferences(sql, dialect);
852
+ break;
853
+ } catch (error) {
854
+ lastDialect = dialect;
855
+ lastError = error;
856
+ }
857
+ }
858
+ if (references === null) {
859
+ return buildScopeParseErrorPayload(sql, lastDialect, lastError);
860
+ }
861
+ if (references.length === 0) return null;
862
+ const allowedEntities = await context.resolveAllowedEntities();
863
+ const allowedQualified = new Set(
864
+ allowedEntities.map((entity) => entity.toLowerCase())
865
+ );
866
+ const allowedUnqualified = /* @__PURE__ */ new Set();
867
+ for (const entity of allowedEntities) {
868
+ const dot = entity.lastIndexOf(".");
869
+ allowedUnqualified.add(
870
+ (dot === -1 ? entity : entity.slice(dot + 1)).toLowerCase()
871
+ );
872
+ }
873
+ const outOfScope = references.map(
874
+ (reference) => reference.db ? `${reference.db}.${reference.table}` : reference.table
875
+ ).filter((name) => {
876
+ const lower = name.toLowerCase();
877
+ if (!name.includes(".")) {
878
+ return !allowedQualified.has(lower) && !allowedUnqualified.has(lower);
879
+ }
880
+ if (allowedQualified.has(lower)) return false;
881
+ const parts = lower.split(".");
882
+ return parts.length < 3 || !allowedQualified.has(parts.slice(-2).join("."));
883
+ });
884
+ return outOfScope.length === 0 ? null : buildOutOfScopePayload(sql, outOfScope, [...allowedEntities]);
885
+ }
886
+ };
887
+ function parseStatements(sql, dialect) {
888
+ const ast = parser.astify(sql, { database: dialect });
889
+ const statements = Array.isArray(ast) ? ast : [ast];
890
+ return statements.filter(isAstLike);
891
+ }
892
+ function containsBlockedOperation(node, policy) {
893
+ if (Array.isArray(node)) {
894
+ return node.some((item) => containsBlockedOperation(item, policy));
895
+ }
896
+ if (!isAstLike(node)) return false;
897
+ if (policy.blockSelectInto && node.type === "select" && isAstLike(node.into) && node.into.type === "into") {
898
+ return true;
899
+ }
900
+ if (policy.blockLockingReads && node.locking_read != null) return true;
901
+ if (policy.blockAssignments && node.type === "assign") return true;
902
+ if (policy.blockServerQualifiedRelations && isTableReferenceNode(node) && typeof node.server === "string") {
903
+ return true;
904
+ }
905
+ if (policy.blockTableHints && node.table_hint != null) return true;
906
+ if (node.type === "function") {
907
+ const functionIdentifier = readFunctionIdentifier(node);
908
+ if (functionIdentifier && policy.blockQualifiedFunctions && functionIdentifier.parts.length > 1) {
909
+ return true;
910
+ }
911
+ if (functionIdentifier && policy.blockedFunctions?.some(
912
+ (blocked) => blocked.toLowerCase() === functionIdentifier.parts.at(-1)
913
+ )) {
914
+ return true;
915
+ }
916
+ if (functionIdentifier && policy.blockedFunctionPrefixes?.some(
917
+ (prefix) => functionIdentifier.parts.at(-1)?.startsWith(prefix.toLowerCase())
918
+ )) {
919
+ return true;
920
+ }
921
+ }
922
+ return Object.values(node).some(
923
+ (value) => containsBlockedOperation(value, policy)
924
+ );
925
+ }
926
+ function readFunctionIdentifier(node) {
927
+ if (!isAstLike(node.name)) return null;
928
+ const parts = [];
929
+ if (isAstLike(node.name.schema) && typeof node.name.schema.value === "string") {
930
+ appendIdentifierParts(parts, node.name.schema.value);
931
+ }
932
+ const names = Array.isArray(node.name.name) ? node.name.name : [];
933
+ for (const name of names) {
934
+ if (isAstLike(name) && typeof name.value === "string") {
935
+ appendIdentifierParts(parts, name.value);
936
+ }
937
+ }
938
+ return parts.length > 0 ? { parts } : null;
939
+ }
940
+ function appendIdentifierParts(parts, value) {
941
+ parts.push(
942
+ ...value.toLowerCase().split(".").filter((part) => part.length > 0)
943
+ );
944
+ }
945
+ function extractBaseEntityReferences(sql, dialect) {
946
+ const ast = parser.astify(sql, { database: dialect });
947
+ const state = {
948
+ cteNames: /* @__PURE__ */ new Set(),
949
+ references: /* @__PURE__ */ new Map()
950
+ };
951
+ visitNode(ast, state);
952
+ return Array.from(state.references.values());
953
+ }
954
+ function firstStatementKeyword(sql) {
955
+ let offset = 0;
956
+ while (offset < sql.length) {
957
+ if (/\s/.test(sql[offset])) {
958
+ offset++;
959
+ continue;
960
+ }
961
+ if (sql.startsWith("--", offset)) {
962
+ offset += 2;
963
+ while (offset < sql.length && sql[offset] !== "\n" && sql[offset] !== "\r") {
964
+ offset++;
965
+ }
966
+ continue;
967
+ }
968
+ if (sql.startsWith("/*", offset)) {
969
+ const commentEnd = sql.indexOf("*/", offset + 2);
970
+ if (commentEnd === -1) return null;
971
+ offset = commentEnd + 2;
972
+ continue;
973
+ }
974
+ const keyword = /^[A-Za-z]+/.exec(sql.slice(offset));
975
+ return keyword ? keyword[0].toUpperCase() : null;
976
+ }
977
+ return null;
978
+ }
979
+ function buildOutOfScopePayload(sql, referencedEntities, allowedEntities) {
980
+ return {
981
+ error: `Query references entities outside grounded scope: ${referencedEntities.join(", ")}`,
982
+ error_type: "OUT_OF_SCOPE",
983
+ suggestion: "Restrict the query to grounded tables/views or expand grounding to include the referenced entities.",
984
+ sql_attempted: sql,
985
+ referenced_entities: referencedEntities,
986
+ allowed_entities: allowedEntities
987
+ };
988
+ }
989
+ function visitNode(node, state) {
990
+ if (Array.isArray(node)) {
991
+ for (const item of node) visitNode(item, state);
992
+ return;
993
+ }
994
+ if (!isAstLike(node)) return;
995
+ if (isStatementNode(node)) {
996
+ visitStatement(node, state);
997
+ return;
998
+ }
999
+ if (isTableReferenceNode(node)) addReference(node, state);
1000
+ for (const value of Object.values(node)) visitNode(value, state);
1001
+ }
1002
+ function visitStatement(node, parentState) {
1003
+ const localState = {
1004
+ cteNames: new Set(parentState.cteNames),
1005
+ references: parentState.references
1006
+ };
1007
+ const withItems = Array.isArray(node.with) ? node.with : [];
1008
+ for (const item of withItems) {
1009
+ if (!isAstLike(item)) continue;
1010
+ const cteName = readCteName(item);
1011
+ if (cteName) localState.cteNames.add(caseFold(cteName));
1012
+ }
1013
+ for (const item of withItems) {
1014
+ if (isAstLike(item)) visitNode(item.stmt, localState);
1015
+ }
1016
+ for (const [key, value] of Object.entries(node)) {
1017
+ if (key !== "with") visitNode(value, localState);
1018
+ }
1019
+ }
1020
+ function addReference(node, state) {
1021
+ const table2 = typeof node.table === "string" ? node.table : null;
1022
+ if (!table2 || state.cteNames.has(caseFold(table2))) return;
1023
+ const db = typeof node.db === "string" ? node.db : null;
1024
+ const key = db ? `${db}.${table2}` : table2;
1025
+ if (!state.references.has(key)) state.references.set(key, { db, table: table2 });
1026
+ }
1027
+ function readCteName(node) {
1028
+ const name = node.name;
1029
+ if (typeof name === "string") return name;
1030
+ if (!isAstLike(name)) return void 0;
1031
+ return typeof name.value === "string" ? name.value : void 0;
1032
+ }
1033
+ function isStatementNode(node) {
1034
+ return typeof node.type === "string" && ["delete", "insert", "replace", "select", "update"].includes(node.type);
1035
+ }
1036
+ function isTableReferenceNode(node) {
1037
+ if (node.type === "column_ref" || typeof node.table !== "string")
1038
+ return false;
1039
+ return "addition" in node || "as" in node || "db" in node || "join" in node || "operator" in node || "surround" in node || "table_hint" in node || "temporal_table" in node;
1040
+ }
1041
+ function isAstLike(value) {
1042
+ return typeof value === "object" && value !== null;
1043
+ }
1044
+ function caseFold(value) {
1045
+ return value.toLowerCase();
1046
+ }
1047
+
1048
+ // packages/text2sql/src/lib/adapters/bigquery/bigquery.sql-policy.ts
1049
+ var BigQuerySqlPolicyAnalyzer = class extends ParserSqlPolicyAnalyzer {
1050
+ dialects = ["bigquery"];
1051
+ readOnlyPolicy = {
1052
+ blockQualifiedFunctions: true,
1053
+ blockedFunctions: ["EXTERNAL_QUERY"]
1054
+ };
1055
+ };
1056
+
1017
1057
  // packages/text2sql/src/lib/adapters/bigquery/bigquery.ts
1018
1058
  function formatBigQueryError(sql, error) {
1019
1059
  const errorMessage = error instanceof Error ? error.message : typeof error === "string" ? error : typeof error === "object" && error !== null ? error.message ?? JSON.stringify(error) : "Unknown error occurred";
@@ -1032,7 +1072,7 @@ var BigQuery = class extends Adapter {
1032
1072
  systemSchemas = [];
1033
1073
  formatterLanguage = "bigquery";
1034
1074
  constructor(options) {
1035
- super();
1075
+ super(new BigQuerySqlPolicyAnalyzer());
1036
1076
  if (!options || typeof options.execute !== "function") {
1037
1077
  throw new Error("BigQuery adapter requires an execute(sql) function.");
1038
1078
  }
@@ -1770,6 +1810,9 @@ var ViewGrounding = class extends AbstractGrounding {
1770
1810
  this.#columns = config.columns;
1771
1811
  this.includeDefinition = config.includeDefinition ?? true;
1772
1812
  }
1813
+ async contributeEntities(ctx) {
1814
+ await this.execute(ctx);
1815
+ }
1773
1816
  /**
1774
1817
  * Execute the grounding process.
1775
1818
  * Writes discovered views to the context.
@@ -1904,6 +1947,7 @@ var bigquery_default = {
1904
1947
  };
1905
1948
  export {
1906
1949
  BigQuery,
1950
+ BigQuerySqlPolicyAnalyzer,
1907
1951
  constraints,
1908
1952
  bigquery_default as default,
1909
1953
  indexes,