-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathmigrate_to_postgres.py
More file actions
executable file
·212 lines (160 loc) · 6.77 KB
/
migrate_to_postgres.py
File metadata and controls
executable file
·212 lines (160 loc) · 6.77 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
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
#!/usr/bin/env python3
"""
Migration script to transfer documents from Google Cloud NDB to PostgreSQL
Note: Users are now stored in PostgreSQL only, so we only migrate documents.
"""
import os
import sys
from datetime import datetime
# Add project root to path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# Set required environment variables
project_root = os.path.dirname(os.path.abspath(__file__))
os.environ.setdefault("GOOGLE_APPLICATION_CREDENTIALS", os.path.join(project_root, "secrets/google-credentials.json"))
os.environ.setdefault("GOOGLE_CLOUD_PROJECT", "questions-346919") # Set the correct project ID
os.environ.setdefault("DATABASE_URL", "postgresql://postgres:password@localhost:5432/textgen")
def setup_logging():
"""Setup logging for the migration process"""
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s",
handlers=[logging.FileHandler("migration.log"), logging.StreamHandler(sys.stdout)],
)
return logging.getLogger(__name__)
def test_connections(logger):
"""Test both database connections"""
logger.info("Testing database connections...")
# Test PostgreSQL connection
try:
from sqlalchemy import text
from questions.db_models_postgres import SessionLocal, create_tables
db = SessionLocal()
db.execute(text("SELECT 1"))
db.close()
logger.info("✅ PostgreSQL connection successful")
# Ensure tables exist
create_tables()
logger.info("✅ PostgreSQL tables created/verified")
except Exception as e:
logger.error(f"❌ PostgreSQL connection failed: {e}")
return False
# Test Google Cloud NDB connection
try:
from questions.db_models import Document as NDBDocument
from questions.db_models import client
with client.context():
# Try to query one document to test connection
NDBDocument.query().fetch(1)
logger.info("✅ Google Cloud NDB connection successful")
except Exception as e:
logger.error(f"❌ Google Cloud NDB connection failed: {e}")
logger.error("Make sure GOOGLE_APPLICATION_CREDENTIALS is set correctly")
return False
return True
def migrate_documents(logger) -> int:
"""Migrate all documents from NDB to PostgreSQL"""
from questions.db_models import Document as NDBDocument
from questions.db_models import client
from questions.db_models_postgres import Document as PGDocument
from questions.db_models_postgres import SessionLocal
logger.info("Starting document migration...")
db = SessionLocal()
migrated_count = 0
error_count = 0
try:
with client.context():
# Fetch all documents from NDB
ndb_documents = NDBDocument.query().fetch()
logger.info(f"Found {len(ndb_documents)} documents in NDB")
for ndb_doc in ndb_documents:
try:
# Check if document already exists in PostgreSQL
# Since NDB uses auto-generated keys, we'll check by user_id, title, and created time
existing_doc = (
db.query(PGDocument)
.filter(
PGDocument.user_id == ndb_doc.user_id,
PGDocument.title == (ndb_doc.title or "Untitled Document"),
PGDocument.created == ndb_doc.created,
)
.first()
)
if existing_doc:
logger.debug(f"Document for user {ndb_doc.user_id} already exists, skipping...")
continue
# Create new PostgreSQL document
pg_doc = PGDocument(
user_id=ndb_doc.user_id,
title=ndb_doc.title or "Untitled Document",
content=ndb_doc.content,
created=ndb_doc.created,
updated=ndb_doc.updated,
)
db.add(pg_doc)
db.commit()
migrated_count += 1
if migrated_count % 100 == 0:
logger.info(f"Migrated {migrated_count} documents...")
except Exception as e:
error_count += 1
logger.error(f"Error migrating document for user {ndb_doc.user_id}: {e}")
db.rollback()
continue
finally:
db.close()
logger.info(f"Document migration completed: {migrated_count} migrated, {error_count} errors")
return migrated_count
def verify_migration(logger):
"""Verify the migration by comparing document counts"""
from questions.db_models import Document as NDBDocument
from questions.db_models import client
from questions.db_models_postgres import Document as PGDocument
from questions.db_models_postgres import SessionLocal
logger.info("Verifying migration...")
db = SessionLocal()
try:
# Count PostgreSQL records
pg_doc_count = db.query(PGDocument).count()
# Count NDB records
with client.context():
ndb_doc_count = NDBDocument.query().count()
logger.info("Migration verification:")
logger.info(f" Documents: NDB={ndb_doc_count}, PostgreSQL={pg_doc_count}")
if pg_doc_count >= ndb_doc_count:
logger.info("✅ Migration verification successful!")
return True
else:
logger.warning("⚠️ Migration may be incomplete - counts don't match")
return False
finally:
db.close()
def main():
"""Main migration function"""
logger = setup_logging()
logger.info("🚀 Starting NDB to PostgreSQL Document Migration")
logger.info("=" * 50)
# Test connections
if not test_connections(logger):
logger.error("❌ Connection tests failed. Aborting migration.")
sys.exit(1)
start_time = datetime.now()
try:
# Migrate documents only (users are now PostgreSQL-only)
doc_count = migrate_documents(logger)
# Verify migration
verify_migration(logger)
end_time = datetime.now()
duration = end_time - start_time
logger.info("🎉 Migration completed successfully!")
logger.info("📊 Summary:")
logger.info(f" Documents migrated: {doc_count}")
logger.info(f" Duration: {duration}")
logger.info(" Log file: migration.log")
except Exception as e:
logger.error(f"❌ Migration failed: {e}")
import traceback
logger.error(traceback.format_exc())
sys.exit(1)
if __name__ == "__main__":
main()