We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent deff40b commit da84d2cCopy full SHA for da84d2c
1 file changed
backend/apps/chat/task/llm.py
@@ -69,15 +69,20 @@
69
70
71
def extract_tables_from_sql(sql: str, ds_type: str = None) -> set:
72
- """从 SQL 中提取表名(使用 sqlglot 解析,可信)"""
+ """从 SQL 中提取真实表名(排除 CTE 别名)"""
73
tables = set()
74
dialect = get_sqlglot_dialect(ds_type)
75
try:
76
statements = sqlglot.parse(sql, dialect=dialect)
77
for stmt in statements:
78
if stmt:
79
+ # 收集 CTE 别名,排除嵌套 CTE
80
+ cte_names = set()
81
+ for cte in stmt.find_all(exp.CTE):
82
+ if cte.alias:
83
+ cte_names.add(cte.alias)
84
for table in stmt.find_all(exp.Table):
- if table.name:
85
+ if table.name and table.name not in cte_names:
86
tables.add(table.name)
87
except Exception:
88
pass
0 commit comments