MCPcopy Create free account
hub / github.com/TextGeneratorio/text-generator.io / migrate_documents

Function migrate_documents

migrate_to_postgres.py:74–137  ·  view source on GitHub ↗

Migrate all documents from NDB to PostgreSQL

(logger)

Source from the content-addressed store, hash-verified

72
73
74def migrate_documents(logger) -> int:
75 """Migrate all documents from NDB to PostgreSQL"""
76 from questions.db_models import Document as NDBDocument
77 from questions.db_models import client
78 from questions.db_models_postgres import Document as PGDocument
79 from questions.db_models_postgres import SessionLocal
80
81 logger.info("Starting document migration...")
82
83 db = SessionLocal()
84 migrated_count = 0
85 error_count = 0
86
87 try:
88 with client.context():
89 # Fetch all documents from NDB
90 ndb_documents = NDBDocument.query().fetch()
91 logger.info(f"Found {len(ndb_documents)} documents in NDB")
92
93 for ndb_doc in ndb_documents:
94 try:
95 # Check if document already exists in PostgreSQL
96 # Since NDB uses auto-generated keys, we'll check by user_id, title, and created time
97 existing_doc = (
98 db.query(PGDocument)
99 .filter(
100 PGDocument.user_id == ndb_doc.user_id,
101 PGDocument.title == (ndb_doc.title or "Untitled Document"),
102 PGDocument.created == ndb_doc.created,
103 )
104 .first()
105 )
106
107 if existing_doc:
108 logger.debug(f"Document for user {ndb_doc.user_id} already exists, skipping...")
109 continue
110
111 # Create new PostgreSQL document
112 pg_doc = PGDocument(
113 user_id=ndb_doc.user_id,
114 title=ndb_doc.title or "Untitled Document",
115 content=ndb_doc.content,
116 created=ndb_doc.created,
117 updated=ndb_doc.updated,
118 )
119
120 db.add(pg_doc)
121 db.commit()
122 migrated_count += 1
123
124 if migrated_count % 100 == 0:
125 logger.info(f"Migrated {migrated_count} documents...")
126
127 except Exception as e:
128 error_count += 1
129 logger.error(f"Error migrating document for user {ndb_doc.user_id}: {e}")
130 db.rollback()
131 continue

Callers 1

mainFunction · 0.85

Calls 1

closeMethod · 0.45

Tested by

no test coverage detected