forked from eosphoros-ai/DB-GPT
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgdbms_db_summary.py
More file actions
144 lines (121 loc) · 4.76 KB
/
Copy pathgdbms_db_summary.py
File metadata and controls
144 lines (121 loc) · 4.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
"""Summary for rdbms database."""
from typing import TYPE_CHECKING, Dict, List, Optional
from dbgpt._private.config import Config
from dbgpt.datasource.base import BaseConnector
from dbgpt.rag.summary.db_summary import DBSummary
from dbgpt_ext.datasource.conn_tugraph import TuGraphConnector
if TYPE_CHECKING:
from dbgpt.datasource.manages import ConnectorManager
CFG = Config()
class GdbmsSummary(DBSummary):
"""Get graph db table summary template."""
def __init__(
self, name: str, type: str, manager: Optional["ConnectorManager"] = None
):
"""Create a new RdbmsSummary."""
self.name = name
self.type = type
self.summary_template = "{table_name}({columns})"
# self.v_summary_template = "{table_name}({columns})"
self.tables = {}
# self.tables_info = []
# self.vector_tables_info = []
# TODO: Don't use the global variable.
db_manager = manager or CFG.local_db_manager
if not db_manager:
raise ValueError("Local db manage is not initialized.")
self.db = db_manager.get_connector(name)
self.metadata = """user info :{users}, grant info:{grant}, charset:{charset},
collation:{collation}""".format(
users=self.db.get_users(),
grant=self.db.get_grants(),
charset=self.db.get_charset(),
collation=self.db.get_collation(),
)
tables = self.db.get_table_names()
self.table_info_summaries = {
"vertex_tables": [
self.get_table_summary(table_name.split("_")[0], "vertex")
for table_name in tables
if table_name.endswith("_vertex")
],
"edge_tables": [
self.get_table_summary(table_name.split("_")[0], "edge")
for table_name in tables
if table_name.endswith("_edge")
],
}
def get_table_summary(self, table_name, table_type):
"""Get table summary for table.
example:
table_name(column1(column1 comment),column2(column2 comment),
column3(column3 comment) and index keys, and table comment: {table_comment})
"""
return _parse_table_summary(
self.db, self.summary_template, table_name, table_type
)
def table_summaries(self):
"""Get table summaries."""
return self.table_info_summaries
def _parse_db_summary(
conn: BaseConnector, summary_template: str = "{table_name}({columns})"
) -> List[str]:
"""Get db summary for database."""
table_info_summaries = None
if isinstance(conn, TuGraphConnector):
table_names = conn.get_table_names()
v_tables = [
table_name.split("_")[0]
for table_name in table_names
if table_name.endswith("_vertex")
]
e_tables = [
table_name.split("_")[0]
for table_name in table_names
if table_name.endswith("_edge")
]
table_info_summaries = [
_parse_table_summary(conn, summary_template, table_name, "vertex")
for table_name in v_tables
] + [
_parse_table_summary(conn, summary_template, table_name, "edge")
for table_name in e_tables
]
else:
table_info_summaries = []
return table_info_summaries
def _format_column(column: Dict) -> str:
"""Format a single column's summary."""
comment = column.get("comment", "")
if column.get("is_in_primary_key"):
comment += " Primary Key" if comment else "Primary Key"
return f"{column['name']} ({comment})" if comment else column["name"]
def _format_indexes(indexes: List[Dict]) -> str:
"""Format index keys for table summary."""
return ", ".join(
f"{index['name']}(`{', '.join(index['column_names'])}`)" for index in indexes
)
def _parse_table_summary(
conn: TuGraphConnector, summary_template: str, table_name: str, table_type: str
) -> str:
"""Enhanced table summary function."""
columns = [
_format_column(column) for column in conn.get_columns(table_name, table_type)
]
column_str = ", ".join(columns)
indexes = conn.get_indexes(table_name, table_type)
index_str = _format_indexes(indexes) if indexes else ""
table_str = summary_template.format(table_name=table_name, columns=column_str)
if index_str:
table_str += f", and index keys: {index_str}"
try:
comment = conn.get_table_comment(table_name)
except Exception:
comment = dict(text=None)
if comment.get("text"):
table_str += (
f", and table comment: {comment.get('text')}, this is a {table_type} table"
)
else:
table_str += f", and table comment: this is a {table_type} table"
return table_str