python 解析sql表血缘,代码发我
时间: 2023-11-22 14:53:34 浏览: 39
下面是一个使用Python解析SQL表血缘的示例代码:
```python
import re
def parse_sql(sql_text):
# 提取所有表名和列名
tables = set(re.findall(r'FROM (\w+)', sql_text, re.IGNORECASE))
tables.update(re.findall(r'JOIN (\w+)', sql_text, re.IGNORECASE))
columns = set(re.findall(r'SELECT ([\w\*,\s]+)', sql_text, re.IGNORECASE)[0].split(','))
columns.update(re.findall(r'ON [\w\.]+ = (\w+)', sql_text, re.IGNORECASE))
columns.update(re.findall(r'JOIN [\w\.]+ ON [\w\.]+ = (\w+)', sql_text, re.IGNORECASE))
# 构建表血缘关系
table_dependency = {}
for table in tables:
table_dependency[table] = set()
for column in columns:
for table in tables:
if column.startswith(table + '.'):
for dep_table in tables:
if dep_table != table:
table_dependency[table].add(dep_table)
return table_dependency
```
该函数接受一个SQL语句字符串作为输入,返回一个字典,其中键为表名,值为该表所依赖的其他表的集合。
例如,如果 SQL 语句为:
```sql
SELECT a.col1, b.col2
FROM table1 a
JOIN table2 b
ON a.col3 = b.col4
```
则调用 `parse_sql` 函数会返回:
```python
{
'table1': {'table2'},
'table2': set()
}
```
即 `table1` 表依赖于 `table2` 表,而 `table2` 表没有依赖任何其他表。