Spaces:
Running
Running
Ali Hashhash
refactor: update migration script to add userId field to existing analytics documents
ed63cf1 | """ | |
| Migration: Add userId field to all existing analytics documents. | |
| Sets userId = document ID for every document in the analytics collection. | |
| """ | |
| import firebase_admin | |
| from firebase_admin import credentials, firestore | |
| def main(): | |
| cred = credentials.Certificate("firebase-service-account.json") | |
| firebase_admin.initialize_app(cred) | |
| db = firestore.client() | |
| print("=" * 60) | |
| print(" Migration: Add userId field to analytics documents") | |
| print("=" * 60) | |
| analytics_ref = db.collection("analytics") | |
| docs = list(analytics_ref.stream()) | |
| print(f"\nFound {len(docs)} analytics documents") | |
| if not docs: | |
| print("No documents to migrate.") | |
| return | |
| # Use batched writes for efficiency | |
| batch = db.batch() | |
| count = 0 | |
| for doc in docs: | |
| data = doc.to_dict() | |
| if data.get("userId") == doc.id: | |
| print(f" SKIP analytics/{doc.id} (userId already set)") | |
| continue | |
| doc_ref = analytics_ref.document(doc.id) | |
| batch.update(doc_ref, {"userId": doc.id}) | |
| count += 1 | |
| print(f" UPDATE analytics/{doc.id} -> userId={doc.id}") | |
| if count % 500 == 0: | |
| batch.commit() | |
| print(f" Committed batch ({count} updates so far)") | |
| batch = db.batch() | |
| if count > 0: | |
| batch.commit() | |
| print(f"\nCommitted {count} updates") | |
| else: | |
| print("\nNo updates needed") | |
| # Verify | |
| print("\n" + "=" * 60) | |
| print(" Verification") | |
| print("=" * 60) | |
| verified = 0 | |
| for doc in analytics_ref.stream(): | |
| data = doc.to_dict() | |
| uid_field = data.get("userId", "MISSING") | |
| match = "OK" if uid_field == doc.id else "MISMATCH" | |
| print(f" {match} analytics/{doc.id} -> userId={uid_field}") | |
| if match == "OK": | |
| verified += 1 | |
| print(f"\nVerified: {verified}/{len(docs)} documents have correct userId field") | |
| print("Migration complete!") | |
| if __name__ == "__main__": | |
| main() | |