Spaces:
Paused
Paused
File size: 15,572 Bytes
d94d354 |
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 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 |
"""
D1 Database integration for OpenManus
Provides interface to Cloudflare D1 database operations
"""
from typing import Any, Dict, List, Optional, Union
from app.logger import logger
from .client import CloudflareClient, CloudflareError
class D1Database:
"""Cloudflare D1 Database client"""
def __init__(self, client: CloudflareClient, database_id: str):
self.client = client
self.database_id = database_id
self.base_endpoint = f"accounts/{client.account_id}/d1/database/{database_id}"
async def execute_query(
self, sql: str, params: Optional[List[Any]] = None, use_worker: bool = True
) -> Dict[str, Any]:
"""Execute a SQL query"""
query_data = {"sql": sql}
if params:
query_data["params"] = params
try:
if use_worker:
# Use worker endpoint for better performance
response = await self.client.post(
"api/database/query", data=query_data, use_worker=True
)
else:
# Use Cloudflare API directly
response = await self.client.post(
f"{self.base_endpoint}/query", data=query_data
)
return response
except CloudflareError as e:
logger.error(f"D1 query execution failed: {e}")
raise
async def batch_execute(
self, queries: List[Dict[str, Any]], use_worker: bool = True
) -> Dict[str, Any]:
"""Execute multiple queries in a batch"""
batch_data = {"queries": queries}
try:
if use_worker:
response = await self.client.post(
"api/database/batch", data=batch_data, use_worker=True
)
else:
response = await self.client.post(
f"{self.base_endpoint}/query", data=batch_data
)
return response
except CloudflareError as e:
logger.error(f"D1 batch execution failed: {e}")
raise
# User management methods
async def create_user(
self,
user_id: str,
username: str,
email: Optional[str] = None,
metadata: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
"""Create a new user"""
sql = """
INSERT INTO users (id, username, email, metadata)
VALUES (?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
username = excluded.username,
email = excluded.email,
metadata = excluded.metadata,
updated_at = strftime('%s', 'now')
"""
import json
params = [user_id, username, email, json.dumps(metadata or {})]
return await self.execute_query(sql, params)
async def get_user(self, user_id: str) -> Optional[Dict[str, Any]]:
"""Get user by ID"""
sql = "SELECT * FROM users WHERE id = ?"
params = [user_id]
result = await self.execute_query(sql, params)
# Parse response based on Cloudflare D1 format
if result.get("success") and result.get("result"):
rows = result["result"][0].get("results", [])
if rows:
user = rows[0]
if user.get("metadata"):
import json
user["metadata"] = json.loads(user["metadata"])
return user
return None
async def get_user_by_username(self, username: str) -> Optional[Dict[str, Any]]:
"""Get user by username"""
sql = "SELECT * FROM users WHERE username = ?"
params = [username]
result = await self.execute_query(sql, params)
if result.get("success") and result.get("result"):
rows = result["result"][0].get("results", [])
if rows:
user = rows[0]
if user.get("metadata"):
import json
user["metadata"] = json.loads(user["metadata"])
return user
return None
# Session management methods
async def create_session(
self,
session_id: str,
user_id: str,
session_data: Dict[str, Any],
expires_at: Optional[int] = None,
) -> Dict[str, Any]:
"""Create a new session"""
sql = """
INSERT INTO sessions (id, user_id, session_data, expires_at)
VALUES (?, ?, ?, ?)
"""
import json
params = [session_id, user_id, json.dumps(session_data), expires_at]
return await self.execute_query(sql, params)
async def get_session(self, session_id: str) -> Optional[Dict[str, Any]]:
"""Get session by ID"""
sql = """
SELECT * FROM sessions
WHERE id = ? AND (expires_at IS NULL OR expires_at > strftime('%s', 'now'))
"""
params = [session_id]
result = await self.execute_query(sql, params)
if result.get("success") and result.get("result"):
rows = result["result"][0].get("results", [])
if rows:
session = rows[0]
if session.get("session_data"):
import json
session["session_data"] = json.loads(session["session_data"])
return session
return None
async def delete_session(self, session_id: str) -> Dict[str, Any]:
"""Delete a session"""
sql = "DELETE FROM sessions WHERE id = ?"
params = [session_id]
return await self.execute_query(sql, params)
# Conversation methods
async def create_conversation(
self,
conversation_id: str,
user_id: str,
title: Optional[str] = None,
messages: Optional[List[Dict[str, Any]]] = None,
) -> Dict[str, Any]:
"""Create a new conversation"""
sql = """
INSERT INTO conversations (id, user_id, title, messages)
VALUES (?, ?, ?, ?)
"""
import json
params = [conversation_id, user_id, title, json.dumps(messages or [])]
return await self.execute_query(sql, params)
async def get_conversation(self, conversation_id: str) -> Optional[Dict[str, Any]]:
"""Get conversation by ID"""
sql = "SELECT * FROM conversations WHERE id = ?"
params = [conversation_id]
result = await self.execute_query(sql, params)
if result.get("success") and result.get("result"):
rows = result["result"][0].get("results", [])
if rows:
conversation = rows[0]
if conversation.get("messages"):
import json
conversation["messages"] = json.loads(conversation["messages"])
return conversation
return None
async def update_conversation_messages(
self, conversation_id: str, messages: List[Dict[str, Any]]
) -> Dict[str, Any]:
"""Update conversation messages"""
sql = """
UPDATE conversations
SET messages = ?, updated_at = strftime('%s', 'now')
WHERE id = ?
"""
import json
params = [json.dumps(messages), conversation_id]
return await self.execute_query(sql, params)
async def get_user_conversations(
self, user_id: str, limit: int = 50
) -> List[Dict[str, Any]]:
"""Get user's conversations"""
sql = """
SELECT id, user_id, title, created_at, updated_at
FROM conversations
WHERE user_id = ?
ORDER BY updated_at DESC
LIMIT ?
"""
params = [user_id, limit]
result = await self.execute_query(sql, params)
if result.get("success") and result.get("result"):
return result["result"][0].get("results", [])
return []
# Agent execution methods
async def create_agent_execution(
self,
execution_id: str,
user_id: str,
session_id: Optional[str] = None,
task_description: Optional[str] = None,
status: str = "pending",
) -> Dict[str, Any]:
"""Create a new agent execution record"""
sql = """
INSERT INTO agent_executions (id, user_id, session_id, task_description, status)
VALUES (?, ?, ?, ?, ?)
"""
params = [execution_id, user_id, session_id, task_description, status]
return await self.execute_query(sql, params)
async def update_agent_execution(
self,
execution_id: str,
status: Optional[str] = None,
result: Optional[str] = None,
execution_time: Optional[int] = None,
) -> Dict[str, Any]:
"""Update agent execution record"""
updates = []
params = []
if status:
updates.append("status = ?")
params.append(status)
if result:
updates.append("result = ?")
params.append(result)
if execution_time is not None:
updates.append("execution_time = ?")
params.append(execution_time)
if status in ["completed", "failed"]:
updates.append("completed_at = strftime('%s', 'now')")
if not updates:
return {"success": True, "message": "No updates provided"}
sql = f"""
UPDATE agent_executions
SET {', '.join(updates)}
WHERE id = ?
"""
params.append(execution_id)
return await self.execute_query(sql, params)
async def get_agent_execution(self, execution_id: str) -> Optional[Dict[str, Any]]:
"""Get agent execution by ID"""
sql = "SELECT * FROM agent_executions WHERE id = ?"
params = [execution_id]
result = await self.execute_query(sql, params)
if result.get("success") and result.get("result"):
rows = result["result"][0].get("results", [])
if rows:
return rows[0]
return None
async def get_user_executions(
self, user_id: str, limit: int = 50
) -> List[Dict[str, Any]]:
"""Get user's agent executions"""
sql = """
SELECT * FROM agent_executions
WHERE user_id = ?
ORDER BY created_at DESC
LIMIT ?
"""
params = [user_id, limit]
result = await self.execute_query(sql, params)
if result.get("success") and result.get("result"):
return result["result"][0].get("results", [])
return []
# File record methods
async def create_file_record(
self,
file_id: str,
user_id: str,
filename: str,
file_key: str,
file_size: int,
content_type: str,
bucket: str = "storage",
) -> Dict[str, Any]:
"""Create a file record"""
sql = """
INSERT INTO files (id, user_id, filename, file_key, file_size, content_type, bucket)
VALUES (?, ?, ?, ?, ?, ?, ?)
"""
params = [file_id, user_id, filename, file_key, file_size, content_type, bucket]
return await self.execute_query(sql, params)
async def get_file_record(self, file_id: str) -> Optional[Dict[str, Any]]:
"""Get file record by ID"""
sql = "SELECT * FROM files WHERE id = ?"
params = [file_id]
result = await self.execute_query(sql, params)
if result.get("success") and result.get("result"):
rows = result["result"][0].get("results", [])
if rows:
return rows[0]
return None
async def get_user_files(
self, user_id: str, limit: int = 100
) -> List[Dict[str, Any]]:
"""Get user's files"""
sql = """
SELECT * FROM files
WHERE user_id = ?
ORDER BY created_at DESC
LIMIT ?
"""
params = [user_id, limit]
result = await self.execute_query(sql, params)
if result.get("success") and result.get("result"):
return result["result"][0].get("results", [])
return []
async def delete_file_record(self, file_id: str) -> Dict[str, Any]:
"""Delete a file record"""
sql = "DELETE FROM files WHERE id = ?"
params = [file_id]
return await self.execute_query(sql, params)
# Schema initialization
async def initialize_schema(self) -> Dict[str, Any]:
"""Initialize database schema"""
schema_queries = [
{
"sql": """CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
username TEXT UNIQUE NOT NULL,
email TEXT UNIQUE,
created_at INTEGER DEFAULT (strftime('%s', 'now')),
updated_at INTEGER DEFAULT (strftime('%s', 'now')),
metadata TEXT
)"""
},
{
"sql": """CREATE TABLE IF NOT EXISTS sessions (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
session_data TEXT,
created_at INTEGER DEFAULT (strftime('%s', 'now')),
expires_at INTEGER,
FOREIGN KEY (user_id) REFERENCES users(id)
)"""
},
{
"sql": """CREATE TABLE IF NOT EXISTS conversations (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
title TEXT,
messages TEXT,
created_at INTEGER DEFAULT (strftime('%s', 'now')),
updated_at INTEGER DEFAULT (strftime('%s', 'now')),
FOREIGN KEY (user_id) REFERENCES users(id)
)"""
},
{
"sql": """CREATE TABLE IF NOT EXISTS files (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
filename TEXT NOT NULL,
file_key TEXT NOT NULL,
file_size INTEGER,
content_type TEXT,
bucket TEXT DEFAULT 'storage',
created_at INTEGER DEFAULT (strftime('%s', 'now')),
FOREIGN KEY (user_id) REFERENCES users(id)
)"""
},
{
"sql": """CREATE TABLE IF NOT EXISTS agent_executions (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
session_id TEXT,
task_description TEXT,
status TEXT DEFAULT 'pending',
result TEXT,
execution_time INTEGER,
created_at INTEGER DEFAULT (strftime('%s', 'now')),
completed_at INTEGER,
FOREIGN KEY (user_id) REFERENCES users(id)
)"""
},
]
# Add indexes
index_queries = [
{
"sql": "CREATE INDEX IF NOT EXISTS idx_sessions_user_id ON sessions(user_id)"
},
{
"sql": "CREATE INDEX IF NOT EXISTS idx_conversations_user_id ON conversations(user_id)"
},
{"sql": "CREATE INDEX IF NOT EXISTS idx_files_user_id ON files(user_id)"},
{
"sql": "CREATE INDEX IF NOT EXISTS idx_agent_executions_user_id ON agent_executions(user_id)"
},
]
all_queries = schema_queries + index_queries
return await self.batch_execute(all_queries)
|