forked from CodingWithLewis/ReceiptPrinterAgent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup_database.py
More file actions
160 lines (124 loc) Β· 4.74 KB
/
setup_database.py
File metadata and controls
160 lines (124 loc) Β· 4.74 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
"""Database setup script."""
import os
import sys
from dotenv import load_dotenv
import libsql_experimental as libsql
load_dotenv()
def test_database():
"""Test database connection and functionality."""
try:
from src.database import TaskDatabase
print("\nπ§ Testing database connection...")
db = TaskDatabase()
print("β
Database connection successful")
# Test adding a sample task
from datetime import datetime
class SampleTask:
name = "Database Test Task"
priority = 2
due_date = datetime.now().isoformat()
print("\nπ§ͺ Testing task creation...")
task_record = db.add_task(SampleTask(), email_context="Database setup test")
print(f"β
Created test task with ID: {task_record.id}")
# Test similarity search
print("\nπ Testing similarity search...")
similar_tasks = db.find_similar_tasks("database test", limit=1)
if similar_tasks:
print(f"β
Found {len(similar_tasks)} similar task(s)")
db.close()
return True
except Exception as e:
print(f"β Database test failed: {str(e)}")
return False
def create_database_tables():
"""Create the required tables in Turso database."""
# Get credentials from environment
db_url = os.getenv("TURSO_DATABASE_URL")
auth_token = os.getenv("TURSO_AUTH_TOKEN")
if not db_url or not auth_token:
print("β Missing database credentials!")
print("Please set TURSO_DATABASE_URL and TURSO_AUTH_TOKEN in your .env file")
return False
print(f"π Connecting to: {db_url}")
try:
# Connect to database
conn = libsql.connect(db_url, auth_token=auth_token)
cursor = conn.cursor()
# Check if tasks table already exists
cursor.execute("""
SELECT name FROM sqlite_master
WHERE type='table' AND name='tasks'
""")
if cursor.fetchone():
print("β οΈ Tasks table already exists")
recreate = input("Drop and recreate table? (y/n): ").lower()
if recreate == 'y':
cursor.execute("DROP TABLE IF EXISTS tasks")
cursor.execute("DROP INDEX IF EXISTS tasks_embedding_idx")
print("ποΈ Dropped existing table and index")
# Create tasks table
print("π Creating tasks table...")
cursor.execute("""
CREATE TABLE IF NOT EXISTS tasks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
priority INTEGER NOT NULL,
due_date TEXT NOT NULL,
created_at TEXT NOT NULL,
email_context TEXT,
embedding F32_BLOB(1536)
)
""")
# Create vector index
print("π Creating vector index...")
cursor.execute("""
CREATE INDEX IF NOT EXISTS tasks_embedding_idx
ON tasks(libsql_vector_idx(embedding))
""")
conn.commit()
cursor.close()
conn.close()
print("β
Database tables created successfully!")
return True
except Exception as e:
print(f"β Error creating tables: {str(e)}")
return False
def main():
"""Main setup function."""
print("ποΈ Database Setup")
print("=" * 30)
# Check environment variables
db_url = os.getenv("TURSO_DATABASE_URL")
auth_token = os.getenv("TURSO_AUTH_TOKEN")
openai_key = os.getenv("OPENAI_API_KEY")
if not db_url or not auth_token or not openai_key:
print("β Missing required environment variables:")
if not db_url:
print(" - TURSO_DATABASE_URL")
if not auth_token:
print(" - TURSO_AUTH_TOKEN")
if not openai_key:
print(" - OPENAI_API_KEY")
print("\nPlease set these in your .env file")
return
print("β
Environment variables found")
# Ask about table creation
print("\n" + "=" * 30)
create_tables = input("Create/recreate database tables? (y/n): ").lower()
if create_tables == 'y':
if not create_database_tables():
return
# Test database
print("\n" + "=" * 30)
test_conn = input("Test database connection? (y/n): ").lower()
if test_conn == 'y':
if not test_database():
return
# Done
print("\n" + "=" * 30)
print("β
Database setup complete!")
print("\nYour database is ready for:")
print(" - python agent.py")
print(" - python main.py")
if __name__ == "__main__":
main()