@deepagents/text2sql 7.12.0 → 7.13.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 (91) hide show
  1. package/README.md +57 -1
  2. package/dist/bin/sql.js +10 -13
  3. package/dist/index.js +31 -15
  4. package/dist/index.js.map +2 -2
  5. package/dist/lib/adapters/adapter.d.ts +17 -0
  6. package/dist/lib/adapters/adapter.d.ts.map +1 -1
  7. package/dist/lib/adapters/bigquery/bigquery.d.ts +2 -2
  8. package/dist/lib/adapters/bigquery/bigquery.d.ts.map +1 -1
  9. package/dist/lib/adapters/bigquery/bigquery.sql-policy.d.ts +3 -8
  10. package/dist/lib/adapters/bigquery/bigquery.sql-policy.d.ts.map +1 -1
  11. package/dist/lib/adapters/bigquery/index.d.ts +1 -1
  12. package/dist/lib/adapters/bigquery/index.d.ts.map +1 -1
  13. package/dist/lib/adapters/bigquery/index.js +230 -207
  14. package/dist/lib/adapters/bigquery/index.js.map +4 -4
  15. package/dist/lib/adapters/clickhouse/clickhouse.d.ts +2 -2
  16. package/dist/lib/adapters/clickhouse/clickhouse.d.ts.map +1 -1
  17. package/dist/lib/adapters/clickhouse/clickhouse.sql-policy.d.ts.map +1 -1
  18. package/dist/lib/adapters/clickhouse/index.js +32 -8
  19. package/dist/lib/adapters/clickhouse/index.js.map +3 -3
  20. package/dist/lib/adapters/duckdb/duckdb.d.ts +2 -2
  21. package/dist/lib/adapters/duckdb/duckdb.d.ts.map +1 -1
  22. package/dist/lib/adapters/duckdb/duckdb.sql-policy.d.ts.map +1 -1
  23. package/dist/lib/adapters/duckdb/index.js +32 -8
  24. package/dist/lib/adapters/duckdb/index.js.map +3 -3
  25. package/dist/lib/adapters/mysql/index.d.ts +1 -1
  26. package/dist/lib/adapters/mysql/index.d.ts.map +1 -1
  27. package/dist/lib/adapters/mysql/index.js +256 -221
  28. package/dist/lib/adapters/mysql/index.js.map +4 -4
  29. package/dist/lib/adapters/mysql/mysql.d.ts +2 -2
  30. package/dist/lib/adapters/mysql/mysql.d.ts.map +1 -1
  31. package/dist/lib/adapters/mysql/mysql.sql-policy.d.ts +3 -10
  32. package/dist/lib/adapters/mysql/mysql.sql-policy.d.ts.map +1 -1
  33. package/dist/lib/adapters/policy/denied-calls.d.ts +17 -0
  34. package/dist/lib/adapters/policy/denied-calls.d.ts.map +1 -0
  35. package/dist/lib/adapters/policy/facts.d.ts +24 -0
  36. package/dist/lib/adapters/policy/facts.d.ts.map +1 -0
  37. package/dist/lib/adapters/policy/forbid.d.ts +9 -0
  38. package/dist/lib/adapters/policy/forbid.d.ts.map +1 -0
  39. package/dist/lib/adapters/policy/in-scope.d.ts +25 -0
  40. package/dist/lib/adapters/policy/in-scope.d.ts.map +1 -0
  41. package/dist/lib/adapters/policy/index.d.ts +8 -0
  42. package/dist/lib/adapters/policy/index.d.ts.map +1 -0
  43. package/dist/lib/adapters/policy/index.js +368 -0
  44. package/dist/lib/adapters/policy/index.js.map +7 -0
  45. package/dist/lib/adapters/policy/one-select.d.ts +7 -0
  46. package/dist/lib/adapters/policy/one-select.d.ts.map +1 -0
  47. package/dist/lib/adapters/policy/read-only.d.ts +4 -0
  48. package/dist/lib/adapters/policy/read-only.d.ts.map +1 -0
  49. package/dist/lib/adapters/policy/source-policy.d.ts +45 -0
  50. package/dist/lib/adapters/policy/source-policy.d.ts.map +1 -0
  51. package/dist/lib/adapters/policy/sql-text.d.ts +43 -0
  52. package/dist/lib/adapters/policy/sql-text.d.ts.map +1 -0
  53. package/dist/lib/adapters/postgres/index.d.ts +1 -1
  54. package/dist/lib/adapters/postgres/index.d.ts.map +1 -1
  55. package/dist/lib/adapters/postgres/index.js +318 -223
  56. package/dist/lib/adapters/postgres/index.js.map +4 -4
  57. package/dist/lib/adapters/postgres/postgres.d.ts +2 -2
  58. package/dist/lib/adapters/postgres/postgres.d.ts.map +1 -1
  59. package/dist/lib/adapters/postgres/postgres.sql-policy.d.ts +3 -9
  60. package/dist/lib/adapters/postgres/postgres.sql-policy.d.ts.map +1 -1
  61. package/dist/lib/adapters/posthog/index.js +24 -5
  62. package/dist/lib/adapters/posthog/index.js.map +2 -2
  63. package/dist/lib/adapters/posthog/posthog.d.ts +2 -2
  64. package/dist/lib/adapters/posthog/posthog.d.ts.map +1 -1
  65. package/dist/lib/adapters/spreadsheet/index.js +237 -207
  66. package/dist/lib/adapters/spreadsheet/index.js.map +4 -4
  67. package/dist/lib/adapters/spreadsheet/spreadsheet.d.ts +2 -2
  68. package/dist/lib/adapters/spreadsheet/spreadsheet.d.ts.map +1 -1
  69. package/dist/lib/adapters/sqlite/index.d.ts +1 -1
  70. package/dist/lib/adapters/sqlite/index.d.ts.map +1 -1
  71. package/dist/lib/adapters/sqlite/index.js +236 -207
  72. package/dist/lib/adapters/sqlite/index.js.map +4 -4
  73. package/dist/lib/adapters/sqlite/sqlite.d.ts +2 -2
  74. package/dist/lib/adapters/sqlite/sqlite.d.ts.map +1 -1
  75. package/dist/lib/adapters/sqlite/sqlite.sql-policy.d.ts +3 -7
  76. package/dist/lib/adapters/sqlite/sqlite.sql-policy.d.ts.map +1 -1
  77. package/dist/lib/adapters/sqlserver/index.d.ts +1 -1
  78. package/dist/lib/adapters/sqlserver/index.d.ts.map +1 -1
  79. package/dist/lib/adapters/sqlserver/index.js +244 -214
  80. package/dist/lib/adapters/sqlserver/index.js.map +4 -4
  81. package/dist/lib/adapters/sqlserver/sqlserver.d.ts +2 -2
  82. package/dist/lib/adapters/sqlserver/sqlserver.d.ts.map +1 -1
  83. package/dist/lib/adapters/sqlserver/sqlserver.sql-policy.d.ts +6 -10
  84. package/dist/lib/adapters/sqlserver/sqlserver.sql-policy.d.ts.map +1 -1
  85. package/dist/lib/sql-scope-error.d.ts +1 -0
  86. package/dist/lib/sql-scope-error.d.ts.map +1 -1
  87. package/dist/lib/sql.d.ts.map +1 -1
  88. package/dist/lib/synthesis/index.js.map +1 -1
  89. package/package.json +10 -4
  90. package/dist/lib/adapters/parser-sql-policy.d.ts +0 -23
  91. package/dist/lib/adapters/parser-sql-policy.d.ts.map +0 -1
@@ -418,16 +418,35 @@ var Adapter = class {
418
418
  resolveAllowedEntities: () => this.#resolveScope()
419
419
  });
420
420
  }
421
- async validate(sql) {
421
+ /** The decoded SQL when the policy allows it, or the policy's message. */
422
+ async #admit(sql) {
422
423
  const decoded = this.#decodeShellEscapes(sql);
423
424
  const violation = await this.#analyzePolicy(decoded);
424
- if (violation?.kind === "read-only") return violation.message;
425
- if (violation?.kind === "scope") return JSON.stringify(violation.payload);
426
- return this.validateImpl(decoded);
425
+ if (violation?.kind === "read-only") return { error: violation.message };
426
+ if (violation?.kind === "scope") {
427
+ return { error: JSON.stringify(violation.payload) };
428
+ }
429
+ return { sql: decoded };
430
+ }
431
+ async validate(sql) {
432
+ const admitted = await this.#admit(sql);
433
+ if ("error" in admitted) return admitted.error;
434
+ return this.validateImpl(admitted.sql);
427
435
  }
428
436
  async execute(sql) {
429
437
  return this.executeImpl(await this.enforceExecutionPolicy(sql));
430
438
  }
439
+ /**
440
+ * Validates and then executes SQL, checking it against the policy once.
441
+ * Gives the policy's or the validator's error in place of a result.
442
+ */
443
+ async run(sql) {
444
+ const admitted = await this.#admit(sql);
445
+ if ("error" in admitted) return admitted;
446
+ const error = await this.validateImpl(admitted.sql);
447
+ if (error) return { error };
448
+ return { result: await this.executeImpl(admitted.sql) };
449
+ }
431
450
  async enforceExecutionPolicy(sql) {
432
451
  const decoded = this.#decodeShellEscapes(sql);
433
452
  const violation = await this.#analyzePolicy(decoded);
@@ -1541,8 +1560,33 @@ var PostgresInfoGrounding = class extends InfoGrounding {
1541
1560
  }
1542
1561
  };
1543
1562
 
1544
- // packages/text2sql/src/lib/adapters/parser-sql-policy.ts
1545
- import nodeSqlParser from "node-sql-parser";
1563
+ // packages/text2sql/src/lib/adapters/policy/read-only.ts
1564
+ var readOnly = Object.freeze({
1565
+ kind: "read-only",
1566
+ message: "only SELECT or WITH queries allowed"
1567
+ });
1568
+
1569
+ // packages/text2sql/src/lib/adapters/policy/denied-calls.ts
1570
+ var DeniedCalls = class {
1571
+ #names;
1572
+ #prefixes;
1573
+ #qualified;
1574
+ constructor(denials) {
1575
+ this.#names = new Set(denials.names?.map((name) => name.toLowerCase()));
1576
+ this.#prefixes = denials.prefixes?.map((prefix) => prefix.toLowerCase()) ?? [];
1577
+ this.#qualified = denials.qualified === true;
1578
+ }
1579
+ check = async (facts) => {
1580
+ const calls2 = await facts.calls();
1581
+ return calls2.some((parts) => this.#denies(parts)) ? readOnly : null;
1582
+ };
1583
+ #denies(parts) {
1584
+ if (this.#qualified && parts.length > 1) return true;
1585
+ const name = parts.at(-1)?.toLowerCase();
1586
+ if (name === void 0) return false;
1587
+ return this.#names.has(name) || this.#prefixes.some((prefix) => name.startsWith(prefix));
1588
+ }
1589
+ };
1546
1590
 
1547
1591
  // packages/text2sql/src/lib/sql-scope-error.ts
1548
1592
  function buildScopeParseErrorPayload(sql, parserDialect, error) {
@@ -1556,154 +1600,152 @@ function buildScopeParseErrorPayload(sql, parserDialect, error) {
1556
1600
  parser_error: parserError
1557
1601
  };
1558
1602
  }
1603
+ function buildOutOfScopePayload(sql, referencedEntities, allowedEntities) {
1604
+ return {
1605
+ error: `Query references entities outside grounded scope: ${referencedEntities.join(", ")}`,
1606
+ error_type: "OUT_OF_SCOPE",
1607
+ suggestion: "Restrict the query to grounded tables/views or expand grounding to include the referenced entities.",
1608
+ sql_attempted: sql,
1609
+ referenced_entities: referencedEntities,
1610
+ allowed_entities: allowedEntities
1611
+ };
1612
+ }
1559
1613
 
1560
- // packages/text2sql/src/lib/adapters/postgres/postgres-parser-workaround.ts
1561
- var TYPE_BEFORE_LITERAL = /(?<type>(?:pg_catalog\.)?[A-Za-z_][A-Za-z0-9_$]*(?:\s+(?:varying|precision))?(?:\s*\(\s*\d+(?:\s*,\s*\d+)?\s*\))?(?:\s+(?:with|without)\s+time\s+zone)?)\s*$/i;
1562
- var TIME_ZONE_SUFFIX = /^\s+time\s+zone\s+/i;
1563
- var TIME_BEFORE_SUFFIX = /(?<type>time(?:stamp)?(?:\s*\(\s*\d+\s*\))?)\s+(?<qualifier>with|without)$/i;
1564
- function recoverPostgresTypedLiteralParserGap(sql, error) {
1565
- const errorOffset = parserErrorOffset(error);
1566
- if (errorOffset === null) return null;
1567
- const prefix = sql.slice(0, errorOffset);
1568
- let literalStart = errorOffset;
1569
- let literalEnd = findLiteralEnd(sql, literalStart);
1570
- let typeMatch = TYPE_BEFORE_LITERAL.exec(prefix);
1571
- let type = typeMatch?.groups?.type;
1572
- if (literalEnd === null) {
1573
- const suffixMatch = TIME_ZONE_SUFFIX.exec(sql.slice(errorOffset));
1574
- typeMatch = TIME_BEFORE_SUFFIX.exec(prefix);
1575
- type = typeMatch?.groups?.type && typeMatch.groups.qualifier && suffixMatch ? `${typeMatch.groups.type} ${typeMatch.groups.qualifier} TIME ZONE` : void 0;
1576
- literalStart = errorOffset + (suffixMatch?.[0].length ?? 0);
1577
- literalEnd = findLiteralEnd(sql, literalStart);
1614
+ // packages/text2sql/src/lib/adapters/policy/in-scope.ts
1615
+ var InScope = class {
1616
+ #names;
1617
+ constructor(names) {
1618
+ this.#names = names;
1619
+ }
1620
+ check = async (facts, check) => {
1621
+ const relations = await facts.relations();
1622
+ if (relations.length === 0) return null;
1623
+ const allowed = await check.resolveAllowedEntities();
1624
+ const isAllowed = await this.#names.allowing(allowed);
1625
+ const outOfScope = relations.filter((relation) => !isAllowed(relation));
1626
+ return outOfScope.length === 0 ? null : {
1627
+ kind: "scope",
1628
+ payload: buildOutOfScopePayload(check.sql, outOfScope, [...allowed])
1629
+ };
1630
+ };
1631
+ };
1632
+ var GroundedNames = class {
1633
+ async allowing(allowed) {
1634
+ const qualified = new Set(allowed.map((entity) => entity.toLowerCase()));
1635
+ const unqualified = new Set(
1636
+ allowed.map(
1637
+ (entity) => entity.slice(entity.lastIndexOf(".") + 1).toLowerCase()
1638
+ )
1639
+ );
1640
+ return (relation) => {
1641
+ const name = relation.toLowerCase();
1642
+ if (qualified.has(name)) return true;
1643
+ if (!name.includes(".")) return unqualified.has(name);
1644
+ const parts = name.split(".");
1645
+ return parts.length >= 3 && qualified.has(parts.slice(-2).join("."));
1646
+ };
1578
1647
  }
1579
- if (!type || typeMatch?.index === void 0 || literalEnd === null)
1580
- return null;
1581
- return prefix.slice(0, typeMatch.index) + `CAST(${sql.slice(literalStart, literalEnd)} AS ${parserType(type)})` + sql.slice(literalEnd);
1582
- }
1583
- function parserErrorOffset(error) {
1584
- if (typeof error !== "object" || error === null) return null;
1585
- const location = Reflect.get(error, "location");
1586
- if (typeof location !== "object" || location === null) return null;
1587
- const start = Reflect.get(location, "start");
1588
- if (typeof start !== "object" || start === null) return null;
1589
- const offset = Reflect.get(start, "offset");
1590
- return typeof offset === "number" ? offset : null;
1591
- }
1592
- function findLiteralEnd(sql, start) {
1593
- if (sql[start] !== "'") {
1594
- const delimiter = /^\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$/.exec(
1595
- sql.slice(start)
1596
- )?.[0];
1597
- if (!delimiter) return null;
1598
- const end = sql.indexOf(delimiter, start + delimiter.length);
1599
- return end === -1 ? null : end + delimiter.length;
1648
+ };
1649
+
1650
+ // packages/text2sql/src/lib/adapters/policy/one-select.ts
1651
+ var OneSelect = class {
1652
+ check = async (facts) => {
1653
+ const statements = await facts.statements();
1654
+ return statements.length === 1 && statements[0]?.kind === "select" ? null : readOnly;
1655
+ };
1656
+ };
1657
+
1658
+ // packages/text2sql/src/lib/adapters/policy/source-policy.ts
1659
+ var UnreadableSql = class extends Error {
1660
+ name = "UnreadableSql";
1661
+ };
1662
+ var SourcePolicy = class {
1663
+ #source;
1664
+ #rules;
1665
+ constructor(source, rules) {
1666
+ this.#source = source;
1667
+ this.#rules = rules;
1600
1668
  }
1601
- let offset = start + 1;
1602
- while (offset < sql.length) {
1603
- if (sql[offset] === "\\") {
1604
- offset += 2;
1605
- continue;
1606
- }
1607
- if (sql[offset] !== "'") {
1608
- offset++;
1609
- continue;
1610
- }
1611
- if (sql[offset + 1] === "'") {
1612
- offset += 2;
1613
- continue;
1669
+ async analyze(sql, context) {
1670
+ const check = {
1671
+ sql,
1672
+ resolveAllowedEntities: () => context.resolveAllowedEntities()
1673
+ };
1674
+ try {
1675
+ const facts = this.#source.read(sql);
1676
+ for (const rule of this.#rules) {
1677
+ const violation = await rule.check(facts, check);
1678
+ if (violation) return violation;
1679
+ }
1680
+ return null;
1681
+ } catch (error) {
1682
+ if (!(error instanceof UnreadableSql)) throw error;
1683
+ return {
1684
+ kind: "scope",
1685
+ payload: buildScopeParseErrorPayload(sql, this.#source.dialect, error)
1686
+ };
1614
1687
  }
1615
- return offset + 1;
1616
1688
  }
1617
- return null;
1618
- }
1619
- function parserType(type) {
1620
- const unqualified = type.replace(/^pg_catalog\./i, "");
1621
- const timetz = /^timetz(\s*\([^)]*\))?$/i.exec(unqualified);
1622
- return timetz ? `TIME${timetz[1] ?? ""} WITH TIME ZONE` : unqualified;
1623
- }
1689
+ };
1624
1690
 
1625
- // packages/text2sql/src/lib/adapters/parser-sql-policy.ts
1626
- var READ_ONLY_MESSAGE = "only SELECT or WITH queries allowed";
1691
+ // packages/text2sql/src/lib/adapters/policy/sql-text.ts
1692
+ import nodeSqlParser from "node-sql-parser";
1627
1693
  var { Parser } = nodeSqlParser;
1628
1694
  var parser = new Parser();
1629
- var ParserSqlPolicyAnalyzer = class {
1630
- readOnlyPolicy = {};
1631
- async analyze(sql, context) {
1632
- if (!this.#isReadOnly(sql)) {
1633
- return { kind: "read-only", message: READ_ONLY_MESSAGE };
1634
- }
1635
- const scopeError = await this.#checkScope(sql, context);
1636
- return scopeError ? { kind: "scope", payload: scopeError } : null;
1637
- }
1638
- #isReadOnly(sql) {
1639
- const statements = this.#readParsedStatements(sql);
1640
- if (statements) {
1641
- return statements.length === 1 && statements[0]?.type === "select" && !containsBlockedOperation(statements[0], this.readOnlyPolicy);
1642
- }
1643
- const keyword = firstStatementKeyword(sql);
1644
- return keyword === "SELECT" || keyword === "WITH";
1645
- }
1646
- #readParsedStatements(sql) {
1647
- for (const dialect of this.dialects) {
1648
- try {
1649
- return this.#parseStatements(sql, dialect);
1650
- } catch {
1651
- }
1652
- }
1653
- return null;
1695
+ var SqlText = class {
1696
+ dialect;
1697
+ #dialects;
1698
+ #recover;
1699
+ constructor(options) {
1700
+ this.#dialects = options.dialects;
1701
+ this.#recover = options.recover;
1702
+ [this.dialect] = options.dialects.slice(-1);
1703
+ }
1704
+ read(sql) {
1705
+ let parsed;
1706
+ const parse = () => parsed ??= this.#parse(sql);
1707
+ const ast = () => {
1708
+ const result = parse();
1709
+ if ("error" in result) throw result.error;
1710
+ return result.ast;
1711
+ };
1712
+ return {
1713
+ statements: async () => {
1714
+ const result = parse();
1715
+ if ("ast" in result) return statementNodes(result.ast).map(toStatement);
1716
+ const keyword = firstStatementKeyword(sql);
1717
+ if (keyword === "SELECT" || keyword === "WITH") throw result.error;
1718
+ return keyword === null ? [] : [{ kind: "other", name: keyword }];
1719
+ },
1720
+ relations: async () => baseRelations(ast()),
1721
+ calls: async () => calls(ast()),
1722
+ constructs: async () => constructs(ast())
1723
+ };
1654
1724
  }
1655
- async #checkScope(sql, context) {
1656
- let references = null;
1725
+ #parse(sql) {
1657
1726
  let lastError;
1658
- let lastDialect = this.dialects[0];
1659
- for (const dialect of this.dialects) {
1727
+ for (const dialect of this.#dialects) {
1660
1728
  try {
1661
- references = extractBaseEntityReferences(this.#parseAst(sql, dialect));
1662
- break;
1729
+ return { ast: this.#astify(sql, dialect) };
1663
1730
  } catch (error) {
1664
- lastDialect = dialect;
1665
1731
  lastError = error;
1666
1732
  }
1667
1733
  }
1668
- if (references === null) {
1669
- return buildScopeParseErrorPayload(sql, lastDialect, lastError);
1670
- }
1671
- if (references.length === 0) return null;
1672
- const allowedEntities = await context.resolveAllowedEntities();
1673
- const allowedQualified = new Set(
1674
- allowedEntities.map((entity) => entity.toLowerCase())
1675
- );
1676
- const allowedUnqualified = /* @__PURE__ */ new Set();
1677
- for (const entity of allowedEntities) {
1678
- const dot = entity.lastIndexOf(".");
1679
- allowedUnqualified.add(
1680
- (dot === -1 ? entity : entity.slice(dot + 1)).toLowerCase()
1681
- );
1682
- }
1683
- const outOfScope = references.map(
1684
- (reference) => reference.db ? `${reference.db}.${reference.table}` : reference.table
1685
- ).filter((name) => {
1686
- const lower = name.toLowerCase();
1687
- if (!name.includes(".")) {
1688
- return !allowedQualified.has(lower) && !allowedUnqualified.has(lower);
1689
- }
1690
- if (allowedQualified.has(lower)) return false;
1691
- const parts = lower.split(".");
1692
- return parts.length < 3 || !allowedQualified.has(parts.slice(-2).join("."));
1693
- });
1694
- return outOfScope.length === 0 ? null : buildOutOfScopePayload(sql, outOfScope, [...allowedEntities]);
1695
- }
1696
- #parseStatements(sql, dialect) {
1697
- return parseStatements(this.#parseAst(sql, dialect));
1734
+ return {
1735
+ error: new UnreadableSql(
1736
+ Error.isError(lastError) ? lastError.message : String(lastError),
1737
+ { cause: lastError }
1738
+ )
1739
+ };
1698
1740
  }
1699
- #parseAst(sql, dialect) {
1741
+ #astify(sql, dialect) {
1700
1742
  let parserSql = sql;
1701
1743
  const attempted = /* @__PURE__ */ new Set([sql]);
1702
1744
  while (true) {
1703
1745
  try {
1704
1746
  return parser.astify(parserSql, { database: dialect });
1705
1747
  } catch (error) {
1706
- const recovered = dialect === "postgresql" ? recoverPostgresTypedLiteralParserGap(parserSql, error) : null;
1748
+ const recovered = this.#recover?.(parserSql, error);
1707
1749
  if (!recovered || attempted.has(recovered)) throw error;
1708
1750
  attempted.add(recovered);
1709
1751
  parserSql = recovered;
@@ -1711,70 +1753,56 @@ var ParserSqlPolicyAnalyzer = class {
1711
1753
  }
1712
1754
  }
1713
1755
  };
1714
- function parseStatements(ast) {
1756
+ function statementNodes(ast) {
1715
1757
  const statements = Array.isArray(ast) ? ast : [ast];
1716
1758
  return statements.filter(isAstLike);
1717
1759
  }
1718
- function containsBlockedOperation(node, policy) {
1719
- if (Array.isArray(node)) {
1720
- return node.some((item) => containsBlockedOperation(item, policy));
1721
- }
1722
- if (!isAstLike(node)) return false;
1723
- if (policy.blockSelectInto && node.type === "select" && isAstLike(node.into) && node.into.type === "into") {
1724
- return true;
1725
- }
1726
- if (policy.blockLockingReads && node.locking_read != null) return true;
1727
- if (policy.blockAssignments && node.type === "assign") return true;
1728
- if (policy.blockServerQualifiedRelations && isTableReferenceNode(node) && typeof node.server === "string") {
1729
- return true;
1730
- }
1731
- if (policy.blockTableHints && node.table_hint != null) return true;
1732
- if (node.type === "function") {
1733
- const functionIdentifier = readFunctionIdentifier(node);
1734
- if (functionIdentifier && policy.blockQualifiedFunctions && functionIdentifier.parts.length > 1) {
1735
- return true;
1736
- }
1737
- if (functionIdentifier && policy.blockedFunctions?.some(
1738
- (blocked) => blocked.toLowerCase() === functionIdentifier.parts.at(-1)
1739
- )) {
1740
- return true;
1741
- }
1742
- if (functionIdentifier && policy.blockedFunctionPrefixes?.some(
1743
- (prefix) => functionIdentifier.parts.at(-1)?.startsWith(prefix.toLowerCase())
1744
- )) {
1745
- return true;
1760
+ function toStatement(node) {
1761
+ if (node.type !== "select") return { kind: "other", name: String(node.type) };
1762
+ return nodes(node).some(
1763
+ (child) => child.type === "select" && isAstLike(child.into) && child.into.type === "into"
1764
+ ) ? { kind: "select-into" } : { kind: "select" };
1765
+ }
1766
+ function calls(ast) {
1767
+ return nodes(ast).filter((node) => node.type === "function").map(functionNameParts).filter((parts) => parts.length > 0).toArray();
1768
+ }
1769
+ function constructs(ast) {
1770
+ const found = /* @__PURE__ */ new Set();
1771
+ for (const node of nodes(ast)) {
1772
+ if (node.table_hint != null) found.add("table-hint");
1773
+ if (node.locking_read != null) found.add("locking-read");
1774
+ if (node.type === "assign") found.add("assignment");
1775
+ if (isTableReferenceNode(node) && typeof node.server === "string") {
1776
+ found.add("server-relation");
1746
1777
  }
1747
1778
  }
1748
- return Object.values(node).some(
1749
- (value) => containsBlockedOperation(value, policy)
1750
- );
1779
+ return found;
1780
+ }
1781
+ function* nodes(node) {
1782
+ if (Array.isArray(node)) {
1783
+ for (const item of node) yield* nodes(item);
1784
+ return;
1785
+ }
1786
+ if (!isAstLike(node)) return;
1787
+ yield node;
1788
+ for (const value of Object.values(node)) yield* nodes(value);
1751
1789
  }
1752
- function readFunctionIdentifier(node) {
1753
- if (!isAstLike(node.name)) return null;
1790
+ function functionNameParts(node) {
1791
+ if (!isAstLike(node.name)) return [];
1754
1792
  const parts = [];
1755
1793
  if (isAstLike(node.name.schema) && typeof node.name.schema.value === "string") {
1756
- appendIdentifierParts(parts, node.name.schema.value);
1794
+ parts.push(...identifierParts(node.name.schema.value));
1757
1795
  }
1758
1796
  const names = Array.isArray(node.name.name) ? node.name.name : [];
1759
1797
  for (const name of names) {
1760
1798
  if (isAstLike(name) && typeof name.value === "string") {
1761
- appendIdentifierParts(parts, name.value);
1799
+ parts.push(...identifierParts(name.value));
1762
1800
  }
1763
1801
  }
1764
- return parts.length > 0 ? { parts } : null;
1765
- }
1766
- function appendIdentifierParts(parts, value) {
1767
- parts.push(
1768
- ...value.toLowerCase().split(".").filter((part) => part.length > 0)
1769
- );
1802
+ return parts;
1770
1803
  }
1771
- function extractBaseEntityReferences(ast) {
1772
- const state = {
1773
- cteNames: /* @__PURE__ */ new Set(),
1774
- references: /* @__PURE__ */ new Map()
1775
- };
1776
- visitNode(ast, state);
1777
- return Array.from(state.references.values());
1804
+ function identifierParts(value) {
1805
+ return value.split(".").filter((part) => part.length > 0);
1778
1806
  }
1779
1807
  function firstStatementKeyword(sql) {
1780
1808
  let offset = 0;
@@ -1801,15 +1829,13 @@ function firstStatementKeyword(sql) {
1801
1829
  }
1802
1830
  return null;
1803
1831
  }
1804
- function buildOutOfScopePayload(sql, referencedEntities, allowedEntities) {
1805
- return {
1806
- error: `Query references entities outside grounded scope: ${referencedEntities.join(", ")}`,
1807
- error_type: "OUT_OF_SCOPE",
1808
- suggestion: "Restrict the query to grounded tables/views or expand grounding to include the referenced entities.",
1809
- sql_attempted: sql,
1810
- referenced_entities: referencedEntities,
1811
- allowed_entities: allowedEntities
1832
+ function baseRelations(ast) {
1833
+ const state = {
1834
+ cteNames: /* @__PURE__ */ new Set(),
1835
+ references: /* @__PURE__ */ new Set()
1812
1836
  };
1837
+ visitNode(ast, state);
1838
+ return [...state.references];
1813
1839
  }
1814
1840
  function visitNode(node, state) {
1815
1841
  if (Array.isArray(node)) {
@@ -1833,7 +1859,7 @@ function visitStatement(node, parentState) {
1833
1859
  for (const item of withItems) {
1834
1860
  if (!isAstLike(item)) continue;
1835
1861
  const cteName = readCteName(item);
1836
- if (cteName) localState.cteNames.add(caseFold(cteName));
1862
+ if (cteName) localState.cteNames.add(cteName.toLowerCase());
1837
1863
  }
1838
1864
  for (const item of withItems) {
1839
1865
  if (isAstLike(item)) visitNode(item.stmt, localState);
@@ -1844,10 +1870,9 @@ function visitStatement(node, parentState) {
1844
1870
  }
1845
1871
  function addReference(node, state) {
1846
1872
  const table2 = typeof node.table === "string" ? node.table : null;
1847
- if (!table2 || state.cteNames.has(caseFold(table2))) return;
1873
+ if (!table2 || state.cteNames.has(table2.toLowerCase())) return;
1848
1874
  const db = typeof node.db === "string" ? node.db : null;
1849
- const key = db ? `${db}.${table2}` : table2;
1850
- if (!state.references.has(key)) state.references.set(key, { db, table: table2 });
1875
+ state.references.add(db ? `${db}.${table2}` : table2);
1851
1876
  }
1852
1877
  function readCteName(node) {
1853
1878
  const name = node.name;
@@ -1866,38 +1891,108 @@ function isTableReferenceNode(node) {
1866
1891
  function isAstLike(value) {
1867
1892
  return typeof value === "object" && value !== null;
1868
1893
  }
1869
- function caseFold(value) {
1870
- return value.toLowerCase();
1894
+
1895
+ // packages/text2sql/src/lib/adapters/postgres/postgres-parser-workaround.ts
1896
+ var TYPE_BEFORE_LITERAL = /(?<type>(?:pg_catalog\.)?[A-Za-z_][A-Za-z0-9_$]*(?:\s+(?:varying|precision))?(?:\s*\(\s*\d+(?:\s*,\s*\d+)?\s*\))?(?:\s+(?:with|without)\s+time\s+zone)?)\s*$/i;
1897
+ var TIME_ZONE_SUFFIX = /^\s+time\s+zone\s+/i;
1898
+ var TIME_BEFORE_SUFFIX = /(?<type>time(?:stamp)?(?:\s*\(\s*\d+\s*\))?)\s+(?<qualifier>with|without)$/i;
1899
+ function recoverPostgresTypedLiteralParserGap(sql, error) {
1900
+ const errorOffset = parserErrorOffset(error);
1901
+ if (errorOffset === null) return null;
1902
+ const prefix = sql.slice(0, errorOffset);
1903
+ let literalStart = errorOffset;
1904
+ let literalEnd = findLiteralEnd(sql, literalStart);
1905
+ let typeMatch = TYPE_BEFORE_LITERAL.exec(prefix);
1906
+ let type = typeMatch?.groups?.type;
1907
+ if (literalEnd === null) {
1908
+ const suffixMatch = TIME_ZONE_SUFFIX.exec(sql.slice(errorOffset));
1909
+ typeMatch = TIME_BEFORE_SUFFIX.exec(prefix);
1910
+ type = typeMatch?.groups?.type && typeMatch.groups.qualifier && suffixMatch ? `${typeMatch.groups.type} ${typeMatch.groups.qualifier} TIME ZONE` : void 0;
1911
+ literalStart = errorOffset + (suffixMatch?.[0].length ?? 0);
1912
+ literalEnd = findLiteralEnd(sql, literalStart);
1913
+ }
1914
+ if (!type || typeMatch?.index === void 0 || literalEnd === null)
1915
+ return null;
1916
+ return prefix.slice(0, typeMatch.index) + `CAST(${sql.slice(literalStart, literalEnd)} AS ${parserType(type)})` + sql.slice(literalEnd);
1917
+ }
1918
+ function parserErrorOffset(error) {
1919
+ if (typeof error !== "object" || error === null) return null;
1920
+ const location = Reflect.get(error, "location");
1921
+ if (typeof location !== "object" || location === null) return null;
1922
+ const start = Reflect.get(location, "start");
1923
+ if (typeof start !== "object" || start === null) return null;
1924
+ const offset = Reflect.get(start, "offset");
1925
+ return typeof offset === "number" ? offset : null;
1926
+ }
1927
+ function findLiteralEnd(sql, start) {
1928
+ if (sql[start] !== "'") {
1929
+ const delimiter = /^\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$/.exec(
1930
+ sql.slice(start)
1931
+ )?.[0];
1932
+ if (!delimiter) return null;
1933
+ const end = sql.indexOf(delimiter, start + delimiter.length);
1934
+ return end === -1 ? null : end + delimiter.length;
1935
+ }
1936
+ let offset = start + 1;
1937
+ while (offset < sql.length) {
1938
+ if (sql[offset] === "\\") {
1939
+ offset += 2;
1940
+ continue;
1941
+ }
1942
+ if (sql[offset] !== "'") {
1943
+ offset++;
1944
+ continue;
1945
+ }
1946
+ if (sql[offset + 1] === "'") {
1947
+ offset += 2;
1948
+ continue;
1949
+ }
1950
+ return offset + 1;
1951
+ }
1952
+ return null;
1953
+ }
1954
+ function parserType(type) {
1955
+ const unqualified = type.replace(/^pg_catalog\./i, "");
1956
+ const timetz = /^timetz(\s*\([^)]*\))?$/i.exec(unqualified);
1957
+ return timetz ? `TIME${timetz[1] ?? ""} WITH TIME ZONE` : unqualified;
1871
1958
  }
1872
1959
 
1873
1960
  // packages/text2sql/src/lib/adapters/postgres/postgres.sql-policy.ts
1874
- var PostgresSqlPolicyAnalyzer = class extends ParserSqlPolicyAnalyzer {
1875
- dialects = ["postgresql"];
1876
- readOnlyPolicy = {
1877
- blockSelectInto: true,
1878
- blockedFunctionPrefixes: [
1879
- "DBLINK_",
1880
- "LO_",
1881
- "PG_ADVISORY_",
1882
- "PG_LS_",
1883
- "PG_TRY_ADVISORY_"
1884
- ],
1885
- blockedFunctions: [
1886
- "NEXTVAL",
1887
- "PG_CANCEL_BACKEND",
1888
- "PG_READ_BINARY_FILE",
1889
- "PG_READ_FILE",
1890
- "PG_RELOAD_CONF",
1891
- "PG_NOTIFY",
1892
- "PG_ROTATE_LOGFILE",
1893
- "PG_SLEEP",
1894
- "PG_STAT_FILE",
1895
- "PG_TERMINATE_BACKEND",
1896
- "SET_CONFIG",
1897
- "SETVAL"
1961
+ function policy() {
1962
+ return new SourcePolicy(
1963
+ new SqlText({
1964
+ dialects: ["postgresql"],
1965
+ recover: recoverPostgresTypedLiteralParserGap
1966
+ }),
1967
+ [
1968
+ new OneSelect(),
1969
+ new DeniedCalls({
1970
+ names: [
1971
+ "NEXTVAL",
1972
+ "PG_CANCEL_BACKEND",
1973
+ "PG_READ_BINARY_FILE",
1974
+ "PG_READ_FILE",
1975
+ "PG_RELOAD_CONF",
1976
+ "PG_NOTIFY",
1977
+ "PG_ROTATE_LOGFILE",
1978
+ "PG_SLEEP",
1979
+ "PG_STAT_FILE",
1980
+ "PG_TERMINATE_BACKEND",
1981
+ "SET_CONFIG",
1982
+ "SETVAL"
1983
+ ],
1984
+ prefixes: [
1985
+ "DBLINK_",
1986
+ "LO_",
1987
+ "PG_ADVISORY_",
1988
+ "PG_LS_",
1989
+ "PG_TRY_ADVISORY_"
1990
+ ]
1991
+ }),
1992
+ new InScope(new GroundedNames())
1898
1993
  ]
1899
- };
1900
- };
1994
+ );
1995
+ }
1901
1996
 
1902
1997
  // packages/text2sql/src/lib/adapters/postgres/postgres.ts
1903
1998
  var POSTGRES_ERROR_MAP = {
@@ -1952,10 +2047,10 @@ var Postgres = class extends Adapter {
1952
2047
  systemSchemas = ["pg_catalog", "information_schema"];
1953
2048
  formatterLanguage = "postgresql";
1954
2049
  constructor(options) {
1955
- super(new PostgresSqlPolicyAnalyzer());
1956
2050
  if (!options || typeof options.execute !== "function") {
1957
2051
  throw new Error("Postgres adapter requires an execute function.");
1958
2052
  }
2053
+ super(options.policy ?? policy());
1959
2054
  this.#options = {
1960
2055
  ...options,
1961
2056
  schemas: options.schemas?.length ? options.schemas : void 0
@@ -2339,7 +2434,6 @@ var postgres_default = {
2339
2434
  };
2340
2435
  export {
2341
2436
  Postgres,
2342
- PostgresSqlPolicyAnalyzer,
2343
2437
  columnStats,
2344
2438
  columnValues,
2345
2439
  constraints,
@@ -2347,6 +2441,7 @@ export {
2347
2441
  formatPostgresError,
2348
2442
  indexes,
2349
2443
  info,
2444
+ policy,
2350
2445
  rowCount,
2351
2446
  tables,
2352
2447
  views