Skip to content

Commit b2f5a3c

Browse files
committed
feat: add mysql and redis part
1 parent a8f44a9 commit b2f5a3c

File tree

3 files changed

+146
-8
lines changed

3 files changed

+146
-8
lines changed

veadk/database/database_adapter.py

Lines changed: 45 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -54,11 +54,32 @@ def query(self, query: str, index: str, top_k: int = 0) -> list:
5454
logger.error(f"Failed to search from Redis: index={index} error={e}")
5555
raise e
5656

57-
def delete_docs(self, index: str, ids: list[int]): ...
57+
def delete_doc(self, index: str, id: str) -> bool:
58+
logger.debug(f"Deleting document from Redis database: index={index} id={id}")
59+
try:
60+
# For Redis, we need to handle deletion differently since RedisDatabase.delete_doc
61+
# takes a key and a single id
62+
result = self.client.delete_doc(key=index, id=id)
63+
return result
64+
except Exception as e:
65+
logger.error(
66+
f"Failed to delete document from Redis database: index={index} id={id} error={e}"
67+
)
68+
return False
5869

59-
def list_docs(
60-
self, index: str, offset: int = 0, limit: int = 100
61-
) -> list[dict]: ...
70+
def list_docs(self, index: str, offset: int = 0, limit: int = 100) -> list[dict]:
71+
logger.debug(f"Listing documents from Redis database: index={index}")
72+
try:
73+
# Get all documents from Redis
74+
docs = self.client.list_docs(key=index)
75+
76+
# Apply offset and limit for pagination
77+
return docs[offset : offset + limit]
78+
except Exception as e:
79+
logger.error(
80+
f"Failed to list documents from Redis database: index={index} error={e}"
81+
)
82+
return []
6283

6384

6485
class RelationalDatabaseAdapter:
@@ -114,11 +135,27 @@ def query(self, query: str, index: str, top_k: int) -> list[str]:
114135

115136
return [item["data"] for item in results]
116137

117-
def delete_docs(self, index: str, ids: list[int]): ...
138+
def delete_doc(self, index: str, id: str) -> bool:
139+
logger.debug(f"Deleting document from SQL database: table_name={index} id={id}")
140+
try:
141+
# Convert single id to list for the client method
142+
result = self.client.delete_doc(table=index, ids=[int(id)])
143+
return result
144+
except Exception as e:
145+
logger.error(
146+
f"Failed to delete document from SQL database: table_name={index} id={id} error={e}"
147+
)
148+
return False
118149

119-
def list_docs(
120-
self, index: str, offset: int = 0, limit: int = 100
121-
) -> list[dict]: ...
150+
def list_docs(self, index: str, offset: int = 0, limit: int = 100) -> list[dict]:
151+
logger.debug(f"Listing documents from SQL database: table_name={index}")
152+
try:
153+
return self.client.list_docs(table=index, offset=offset, limit=limit)
154+
except Exception as e:
155+
logger.error(
156+
f"Failed to list documents from SQL database: table_name={index} error={e}"
157+
)
158+
return []
122159

123160

124161
class VectorDatabaseAdapter:

veadk/database/kv/redis_database.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,3 +110,47 @@ def delete(self, **kwargs):
110110
except Exception as e:
111111
logger.error(f"Failed to delete key `{key}`: {e}")
112112
raise e
113+
114+
def delete_doc(self, key: str, id: str) -> bool:
115+
"""Delete a specific document by ID from a Redis list.
116+
117+
Args:
118+
key: The Redis key (list) to delete from
119+
id: The ID of the document to delete
120+
121+
Returns:
122+
bool: True if deletion was successful, False otherwise
123+
"""
124+
try:
125+
# Get all items in the list
126+
items = self._client.lrange(key, 0, -1)
127+
128+
# Find the index of the item to delete
129+
for i, item in enumerate(items):
130+
# Assuming the item is stored as a JSON string with an 'id' field
131+
# If it's just the content, we'll use the list index as ID
132+
if str(i) == id:
133+
self._client.lrem(key, 1, item)
134+
return True
135+
136+
logger.warning(f"Document with id {id} not found in key {key}")
137+
return False
138+
except Exception as e:
139+
logger.error(f"Failed to delete document with id {id} from key {key}: {e}")
140+
return False
141+
142+
def list_docs(self, key: str) -> list[dict]:
143+
"""List all documents in a Redis list.
144+
145+
Args:
146+
key: The Redis key (list) to list documents from
147+
148+
Returns:
149+
list[dict]: List of documents with id and content
150+
"""
151+
try:
152+
items = self._client.lrange(key, 0, -1)
153+
return [{"id": str(i), "content": item} for i, item in enumerate(items)]
154+
except Exception as e:
155+
logger.error(f"Failed to list documents from key {key}: {e}")
156+
return []

veadk/database/relational/mysql_database.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,5 +111,62 @@ def delete(self, **kwargs):
111111
logger.error(f"Failed to drop table {table}: {e}")
112112
raise e
113113

114+
def delete_doc(self, table: str, ids: list[int]) -> bool:
115+
"""Delete documents by IDs from a MySQL table.
116+
117+
Args:
118+
table: The table name to delete from
119+
ids: List of document IDs to delete
120+
121+
Returns:
122+
bool: True if deletion was successful, False otherwise
123+
"""
124+
if not self.table_exists(table):
125+
logger.warning(f"Table {table} does not exist. Skipping delete operation.")
126+
return False
127+
128+
if not ids:
129+
return True # Nothing to delete
130+
131+
try:
132+
with self._connection.cursor() as cursor:
133+
# Create placeholders for the IDs
134+
placeholders = ",".join(["%s"] * len(ids))
135+
sql = f"DELETE FROM `{table}` WHERE id IN ({placeholders})"
136+
cursor.execute(sql, ids)
137+
self._connection.commit()
138+
logger.info(f"Deleted {cursor.rowcount} documents from table {table}")
139+
return True
140+
except Exception as e:
141+
logger.error(f"Failed to delete documents from table {table}: {e}")
142+
return False
143+
144+
def list_docs(self, table: str, offset: int = 0, limit: int = 100) -> list[dict]:
145+
"""List documents from a MySQL table.
146+
147+
Args:
148+
table: The table name to list documents from
149+
offset: Offset for pagination
150+
limit: Limit for pagination
151+
152+
Returns:
153+
list[dict]: List of documents with id and content
154+
"""
155+
if not self.table_exists(table):
156+
logger.warning(f"Table {table} does not exist. Returning empty list.")
157+
return []
158+
159+
try:
160+
with self._connection.cursor() as cursor:
161+
sql = f"SELECT id, data FROM `{table}` ORDER BY created_at DESC LIMIT %s OFFSET %s"
162+
cursor.execute(sql, (limit, offset))
163+
results = cursor.fetchall()
164+
return [
165+
{"id": str(row["id"]), "content": row["data"]} for row in results
166+
]
167+
except Exception as e:
168+
logger.error(f"Failed to list documents from table {table}: {e}")
169+
return []
170+
114171
def is_empty(self):
115172
pass

0 commit comments

Comments
 (0)