-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathgraph_database.py
More file actions
53 lines (45 loc) · 1.7 KB
/
Copy pathgraph_database.py
File metadata and controls
53 lines (45 loc) · 1.7 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
import sqlite3
class GraphDatabaseConnection:
def __init__(self, db_path='data/graph_database.sqlite'):
if not db_path:
raise ValueError(
"Database path must be provided to initialize the DatabaseConnection.")
self.db_path = db_path
self.conn = sqlite3.connect(self.db_path)
# Use WAL mode for better performance
self.conn.execute('PRAGMA journal_mode=WAL;')
self.initialize_schema()
def initialize_schema(self):
with self.conn:
# Create nodes and edges tables if they don't exist
self.conn.execute('''
CREATE TABLE IF NOT EXISTS nodes (
id TEXT PRIMARY KEY,
properties TEXT
)
''')
self.conn.execute('''
CREATE TABLE IF NOT EXISTS edges (
source TEXT,
target TEXT,
relationship TEXT,
weight REAL,
PRIMARY KEY (source, target, relationship),
FOREIGN KEY (source) REFERENCES nodes(id),
FOREIGN KEY (target) REFERENCES nodes(id)
)
''')
self.conn.execute('''
CREATE INDEX IF NOT EXISTS source_idx ON edges(source)
''')
self.conn.execute('''
CREATE INDEX IF NOT EXISTS target_idx ON edges(target)
''')
def close(self):
self.conn.close()
def get_session(self):
return self.conn
def clear_database(self):
with self.conn:
self.conn.execute("DELETE FROM edges")
self.conn.execute("DELETE FROM nodes")