Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 12 additions & 8 deletions backend/apps/chat/task/llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
from sqlbot_xpack.custom_prompt.models.custom_prompt_model import CustomPromptTypeEnum
from sqlbot_xpack.license.license_manage import SQLBotLicenseUtil
from sqlglot import exp
from sqlglot.optimizer.scope import traverse_scope
from sqlmodel import Session

from apps.ai_model.model_factory import LLMConfig, LLMFactory, get_default_config
Expand Down Expand Up @@ -75,23 +76,26 @@


def extract_tables_from_sql(sql: str, ds_type: str = None) -> set:
"""从 SQL 中提取真实表名(排除 CTE 别名)"""
"""从 SQL 中提取真实表名(排除 CTE 引用)"""
tables = set()
dialect = get_sqlglot_dialect(ds_type)
try:
statements = sqlglot.parse(sql, dialect=dialect)
for stmt in statements:
if stmt:
# 收集 CTE 别名,排除嵌套 CTE
cte_names = set()
for cte in stmt.find_all(exp.CTE):
if cte.alias:
cte_names.add(cte.alias)
# 只排除在所在作用域内可见的 CTE 引用;带 schema/catalog 的表名不会是 CTE,
# 同名的 CTE 不能遮蔽真实表
cte_refs = set()
for scope in traverse_scope(stmt):
for table in scope.tables:
if not table.db and not table.catalog and table.name in scope.cte_sources:
cte_refs.add(id(table))
for table in stmt.find_all(exp.Table):
if table.name and table.name not in cte_names:
if table.name and id(table) not in cte_refs:
tables.add(table.name)
except Exception:
pass
# 解析失败时不返回部分结果,调用方会拒绝执行
return set()
return tables


Expand Down
34 changes: 34 additions & 0 deletions backend/tests/test_table_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import pytest
import sqlbot_xpack # noqa: F401 # Initialize the published wheel before app imports.
from pydantic import ValidationError
from sqlglot.errors import OptimizeError

from apps.chat.models.chat_model import ChatFinishStep
from apps.chat.task import llm
Expand Down Expand Up @@ -74,6 +75,11 @@ def run(task, sql, reported_tables=None):
[
"SELECT id FROM sales",
"WITH totals AS (SELECT id FROM sales) SELECT * FROM totals",
"WITH a AS (SELECT id FROM sales), b AS (SELECT id FROM a) SELECT * FROM b",
"SELECT * FROM (WITH totals AS (SELECT id FROM sales) SELECT * FROM totals) t",
"WITH t AS (SELECT id FROM sales) SELECT * FROM sales WHERE id IN (SELECT id FROM t)",
"WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 3) "
"SELECT * FROM n JOIN sales ON true",
],
)
def test_default_allows_known_tables_and_cte_aliases(task, sql):
Expand All @@ -92,6 +98,22 @@ def test_default_allows_known_tables_and_cte_aliases(task, sql):
"SELECT id FROM sales UNION ALL SELECT id FROM secret_payroll",
"unauthorized tables: secret_payroll",
),
# A CTE must not hide a real table with the same name (#1543).
(
"WITH secret_payroll AS (SELECT 1) "
"SELECT * FROM public.secret_payroll JOIN sales ON true",
"unauthorized tables: secret_payroll",
),
(
"SELECT * FROM (WITH secret_payroll AS (SELECT 1) SELECT * FROM secret_payroll) t "
"CROSS JOIN secret_payroll JOIN sales ON true",
"unauthorized tables: secret_payroll",
),
(
"WITH secret_payroll AS (SELECT * FROM secret_payroll) "
"SELECT * FROM secret_payroll JOIN sales ON true",
"unauthorized tables: secret_payroll",
),
],
)
def test_default_rejects_invalid_or_unknown_tables_before_save_and_execute(
Expand Down Expand Up @@ -120,6 +142,18 @@ def test_missing_tables_are_rejected_even_when_whitelist_check_is_skipped(
task.execute_sql.assert_not_called()


def test_extraction_error_does_not_return_partial_tables(task, monkeypatch):
# The second statement fails after the first one has already been collected.
traverse = Mock(side_effect=[[], OptimizeError("scope error")])
monkeypatch.setattr(llm, "traverse_scope", traverse)
result = run(task, "SELECT id FROM sales; SELECT id FROM secret_payroll")
assert result["success"] is False
assert "unable to extract table names" in result["message"]
assert traverse.call_count == 2
task.check_save_sql.assert_not_called()
task.execute_sql.assert_not_called()


@pytest.mark.parametrize(
"sql",
[
Expand Down
Loading