-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase_manager.py
More file actions
83 lines (69 loc) · 2.66 KB
/
database_manager.py
File metadata and controls
83 lines (69 loc) · 2.66 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
import sqlite3
from typing import Dict, List, Optional
import pandas as pd
from pathlib import Path
class DatabaseManager:
"""Manages SQLite database connections and queries."""
def __init__(self, db_path: str):
"""Initialize database manager.
Args:
db_path: Path to SQLite database
"""
self.db_path = Path(db_path)
self._test_connection()
def _test_connection(self) -> None:
"""Test database connection and verify file exists."""
if not self.db_path.exists():
raise FileNotFoundError(f"Database not found at {self.db_path}")
try:
with sqlite3.connect(self.db_path) as conn:
conn.execute("SELECT 1")
except sqlite3.Error as e:
raise ConnectionError(f"Failed to connect to database: {e}")
def get_tables(self) -> List[str]:
"""Get list of all user tables in database."""
with sqlite3.connect(self.db_path) as conn:
tables = pd.read_sql("""
SELECT name
FROM sqlite_master
WHERE type='table'
AND name NOT LIKE 'sqlite_%'
ORDER BY name
""", conn)
return tables['name'].tolist()
def get_table_info(self, table_name: str) -> Dict:
"""Get detailed information about a specific table."""
with sqlite3.connect(self.db_path) as conn:
# Get column information
columns = pd.read_sql(f"PRAGMA table_info({table_name})", conn)
# Get row count
row_count = pd.read_sql(
f"SELECT COUNT(*) as count FROM {table_name}",
conn
).iloc[0]['count']
# Get foreign key information
foreign_keys = pd.read_sql(
f"PRAGMA foreign_key_list({table_name})",
conn
)
return {
'columns': columns.to_dict('records'),
'row_count': row_count,
'foreign_keys': foreign_keys.to_dict('records')
}
def get_database_summary(self) -> Dict:
"""Get summary of entire database structure."""
tables = self.get_tables()
return {
table: self.get_table_info(table)
for table in tables
}
def execute_query(self, query: str):
"""Execute a SQL query and return results.
Args:
query: SQL query string
Returns:
sqlite3.Cursor: Query results
"""
with sqlite3.connect(self.db_path) as conn:
return conn.execute(query)