@@ -138,33 +138,23 @@ def run_migrations(conn):
138138 """Run all pending migrations"""
139139 cur = None
140140 try :
141- conn .set_session (autocommit = False )
142- cur = conn .cursor ()
143-
144- # Create schema_migrations table if it doesn't exist
145- cur .execute ("""
146- CREATE TABLE IF NOT EXISTS schema_migrations (
147- version INTEGER PRIMARY KEY,
148- description TEXT NOT NULL,
149- applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
150- )
151- """ )
152- conn .commit ()
141+ # Set autocommit to True before any operations
142+ conn .set_session (autocommit = True )
153143
144+ cur = conn .cursor ()
154145 current_version = get_current_version (cur )
155146 logger .info (f"Current database version: { current_version } " )
156147
157- # Run each migration that hasn't been applied yet
148+ # Set autocommit to False for the migration transaction
149+ conn .set_session (autocommit = False )
150+
158151 for migration in MIGRATIONS :
159152 version = migration ['version' ]
160153 if version > current_version :
161- logger .info (f"Running migration { version } : { migration ['description' ]} " )
162154 try :
163- cur .execute (migration ['up' ])
164- cur .execute (
165- "INSERT INTO schema_migrations (version, description) VALUES (%s, %s)" ,
166- (version , migration ['description' ])
167- )
155+ logger .info (f"Running migration { version } : { migration ['description' ]} " )
156+ migration ['up' ](cur )
157+ cur .execute ("UPDATE schema_version SET version = %s" , (version ,))
168158 conn .commit ()
169159 logger .info (f"Successfully applied migration { version } " )
170160 except Exception as e :
@@ -182,5 +172,7 @@ def run_migrations(conn):
182172 finally :
183173 if cur :
184174 cur .close ()
175+
176+ # Set autocommit back to True after all operations
185177 if conn and not conn .closed :
186178 conn .set_session (autocommit = True )
0 commit comments