-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb_utils.py
More file actions
313 lines (259 loc) · 8.35 KB
/
db_utils.py
File metadata and controls
313 lines (259 loc) · 8.35 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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
"""
File name: db_utils.py
Author: Luigi Saetta
Date last modified: 2025-07-30
Python Version: 3.11
Description:
This module contains utility functions for database operations,
Usage:
Import this module into other scripts to use its functions.
Example:
import config
License:
This code is released under the MIT License.
Notes:
This is a part of a demo showing how to implement an advanced
RAG solution as a LangGraph agent.
Warnings:
This module is in development, may change in future versions.
"""
import re
from typing import List, Tuple, Optional, Any, Dict
import decimal
import datetime
import oracledb
from utils import get_console_logger
from config import DEBUG
from config_private import CONNECT_ARGS
logger = get_console_logger()
#
# Helpers
#
def get_connection():
"""
get a connection to the DB
"""
return oracledb.connect(**CONNECT_ARGS)
def read_lob(value: Any) -> Optional[str]:
"""
Return a Python string from an oracledb LOB (CLOB) or a plain value.
If value is None, returns None.
"""
if value is None:
return None
# oracledb returns CLOBs as LOB objects; read() -> str
if isinstance(value, oracledb.LOB):
return value.read()
# Sometimes drivers may already return a str
return str(value)
def normalize_sql(sql_text: str) -> str:
"""
Strip trailing semicolons and whitespace to avoid ORA-00911 in driver.
"""
return sql_text.strip().rstrip(";\n\r\t ")
def is_safe_select(sql_text: str) -> bool:
"""
Minimal safety check: only allow pure SELECT statements (no DML/DDL/PLSQL).
"""
forbidden_commands = [
"INSERT",
"UPDATE",
"DELETE",
"MERGE",
"ALTER",
"DROP",
"CREATE",
"GRANT",
"REVOKE",
"TRUNCATE",
"BEGIN",
"EXEC",
"CALL",
]
s = sql_text.strip().upper()
if not s.startswith("SELECT "):
return False
# Build regex from forbidden command list
pattern = r"\b(" + "|".join(forbidden_commands) + r")\b"
return not re.search(pattern, s)
def _to_jsonable(value: Any):
# Convert DB/native types → JSON-safe
if value is None:
return None
if isinstance(value, oracledb.LOB):
return value.read() # CLOB/BLOB → str/bytes; CLOB becomes str
if isinstance(value, (bytes, bytearray, memoryview)):
return bytes(value).hex() # or base64 if you prefer
if isinstance(value, (datetime.datetime, datetime.date, datetime.time)):
return value.isoformat()
if isinstance(value, decimal.Decimal):
# choose float or str; str preserves precision
return float(value)
# Tuples/lists/sets inside cells (rare) → list
if isinstance(value, (tuple, set)):
return list(value)
return value
def list_collections():
"""
return a list of all collections (tables) with a type vector
in the schema in use
"""
query = """
SELECT DISTINCT table_name
FROM user_tab_columns
WHERE data_type = 'VECTOR'
ORDER by table_name ASC
"""
_collections = []
with get_connection() as conn:
with conn.cursor() as cursor:
cursor.execute(query)
rows = cursor.fetchall()
for row in rows:
_collections.append(row[0])
return sorted(_collections)
def list_books_in_collection(collection_name: str) -> list:
"""
get the list of books/documents names in the collection
taken from metadata
expect metadata contains the field source
modified to return also the num. of chunks
"""
query = f"""
SELECT DISTINCT json_value(METADATA, '$.source') AS books,
count(*) as n_chunks
FROM {collection_name}
group by books
ORDER by books ASC
"""
with get_connection() as conn:
with conn.cursor() as cursor:
cursor.execute(query)
rows = cursor.fetchall()
list_books = []
for row in rows:
list_books.append((row[0], row[1]))
return sorted(list_books)
def fetch_text_by_id(id: str, collection_name: str) -> str:
"""
Given the ID of a chunk return the text
"""
sql = """
SELECT TEXT, json_value(METADATA, '$.source')
FROM {collection_name}
WHERE ID = :id
"""
with get_connection() as conn:
with conn.cursor() as cursor:
cursor.execute(
sql.format(collection_name=collection_name),
{"id": id},
)
# we expect 0 or 1 rows
row = cursor.fetchone()
if row:
clob = row[0]
text_value = clob.read() if clob is not None else None
source = row[1]
else:
source = None
text_value = None
return {"text_value": text_value, "source": source}
# ---------------------------
# Select AI utilities
# ---------------------------
def generate_sql_from_prompt(profile_name: str, prompt: str) -> str:
"""
Use DBMS_CLOUD_AI.GENERATE to get the SQL for a natural language prompt.
Returns the SQL as a Python string (CLOB -> .read()).
"""
stmt = """
SELECT DBMS_CLOUD_AI.GENERATE(
prompt => :p,
profile_name => :prof,
action => 'showsql'
)
FROM dual
"""
try:
with get_connection() as conn:
with conn.cursor() as cursor:
cursor.execute(stmt, {"p": prompt, "prof": profile_name})
# CLOB (LOB) or str
raw = cursor.fetchone()[0]
sql_text = read_lob(raw) or ""
return {"sql": normalize_sql(sql_text)}
except oracledb.DatabaseError as e:
error = e.args[0] if e.args else None
logger.error(
"[generate_sql_from_prompt] Database error: %s "
"(code=%s | prompt='%s' profile='%s'",
error.message,
error.code,
prompt,
profile_name,
)
raise
except Exception:
logger.error(
"[generate_sql_from_prompt] Unexpected error for prompt=%s, profile=%s",
prompt,
profile_name,
)
raise
def execute_generated_sql(
generated_sql: str, limit: Optional[int] = None
) -> Dict[str, Any]:
"""
Execute the SQL and return a JSON-serializable dict:
{
"columns": [ ... ],
"rows": [ [ ... ], ... ],
"sql": "..."
}
"""
try:
with get_connection() as conn:
with conn.cursor() as cursor:
cursor.execute(generated_sql)
columns: List[str] = [d[0] for d in cursor.description]
# Fetch
raw_rows = cursor.fetchmany(limit) if limit else cursor.fetchall()
# Normalize every cell to JSON-safe
rows: List[List[Any]] = [
[_to_jsonable(cell) for cell in row] for row in raw_rows
]
return {
"columns": columns,
"rows": rows, # list of lists (JSON arrays)
"sql": generated_sql, # useful for logging/debug
}
except oracledb.DatabaseError as e:
error = e.args[0] if e.args else None
logger.error(
"[execute_generated_sql] Database error: %s (code=%s) | sql='%s'",
error.message,
error.code,
generated_sql,
)
raise
except Exception:
logger.error(
"[execute_generated_sql] Unexpected error executing sql='%s'",
generated_sql,
)
raise
def run_select_ai(
prompt: str, profile_name: str, limit: Optional[int] = None
) -> Tuple[List[str], List[tuple], str]:
"""
Generate SQL via Select AI for the given prompt, execute it, and return:
(columns, rows, generated_sql)
If 'limit' is provided, fetch at most that many rows.
"""
result = generate_sql_from_prompt(profile_name, prompt)
if DEBUG:
logger.info(result)
# if not is_safe_select(generated_sql):
# raise ValueError("Refusing to execute non-SELECT SQL generated by Select AI.")
return execute_generated_sql(result["sql"], limit)