-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmigrate.py
More file actions
148 lines (113 loc) · 4.18 KB
/
migrate.py
File metadata and controls
148 lines (113 loc) · 4.18 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
"""
Database migration script for QPyth Neon database.
This script initializes the database schema and can be run:
- Automatically on PR preview branch creation
- Manually for local development
- As part of CI/CD pipeline
Usage:
python migrate.py # Run all migrations
python migrate.py --check # Check current migration status
python migrate.py --rollback # Rollback last migration
"""
import argparse
import os
import sys
from datetime import datetime
# Add project root to path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
def get_database_url() -> str:
"""Get database URL from environment."""
database_url = os.getenv("DATABASE_URL")
if not database_url:
raise ValueError(
"DATABASE_URL environment variable not set. "
"Please set it or use a .env file."
)
return database_url
def run_migration(db) -> None:
"""
Run database migrations.
This creates all required tables if they don't exist.
"""
print(f"[{datetime.now().isoformat()}] Starting database migration...")
# Import database module
from quantumpytho.modules.database import init_schema
# Run schema initialization
init_schema(db)
print(f"[{datetime.now().isoformat()}] Migration completed successfully!")
def check_migration_status(db) -> None:
"""Check current migration status."""
print(f"[{datetime.now().isoformat()}] Checking migration status...")
# Check if tables exist
tables = ["quantum_jobs", "vqe_results", "user_sessions", "api_logs"]
for table in tables:
result = db.fetch_one(
"SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = %s)",
(table,),
)
exists = result.get("exists", False) if result else False
status = "✅" if exists else "❌"
print(f" {status} {table}")
print(f"[{datetime.now().isoformat()}] Status check complete!")
def rollback_migration(db) -> None:
"""Rollback last migration (use with caution!)."""
print(f"[{datetime.now().isoformat()}] WARNING: Rolling back migrations...")
print(" This will DROP all tables!")
confirm = input(" Are you sure? Type 'YES' to confirm: ")
if confirm != "YES":
print(" Rollback cancelled.")
return
# Drop all tables
tables = ["api_logs", "user_sessions", "vqe_results", "quantum_jobs"]
for table in tables:
try:
db.execute(f"DROP TABLE IF EXISTS {table} CASCADE")
print(f" ✅ Dropped table: {table}")
except Exception as e:
print(f" ❌ Failed to drop {table}: {e}")
print(f"[{datetime.now().isoformat()}] Rollback complete!")
def main():
"""Main entry point."""
parser = argparse.ArgumentParser(description="QPyth Database Migrations")
parser.add_argument(
"--check", action="store_true", help="Check current migration status"
)
parser.add_argument(
"--rollback",
action="store_true",
help="Rollback last migration (DROPS all tables)",
)
args = parser.parse_args()
# Get database URL
try:
database_url = get_database_url()
print(f"Using database: {database_url.split('@')[1].split('/')[0]}")
except ValueError as e:
print(f"❌ Error: {e}")
print("\nSet DATABASE_URL environment variable:")
print(" export DATABASE_URL='postgresql://...'")
print("\nOr create a .env file with:")
print(" DATABASE_URL=postgresql://...")
sys.exit(1)
# Import and connect
try:
from quantumpytho.modules.database import DatabaseConfig, NeonDatabase
config = DatabaseConfig(database_url=database_url)
db = NeonDatabase(config)
print("✅ Connected to database")
# Run appropriate command
if args.rollback:
rollback_migration(db)
elif args.check:
check_migration_status(db)
else:
run_migration(db)
# Close connection
db.close()
except Exception as e:
print(f"❌ Migration failed: {e}")
import traceback
traceback.print_exc()
sys.exit(1)
if __name__ == "__main__":
main()