Skip to content

Commit 75cb852

Browse files
Set autocommit to True by default for database connections and streamline migration handling
1 parent 1c75b30 commit 75cb852

File tree

2 files changed

+14
-19
lines changed

2 files changed

+14
-19
lines changed

main.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,9 @@ def create_database_connection():
160160
connect_timeout=DB_CONNECT_TIMEOUT
161161
)
162162

163+
# Set autocommit to True by default
164+
conn.set_session(autocommit=True)
165+
163166
# Check if there's a lingering transaction and roll it back
164167
if conn.get_transaction_status() != psycopg2.extensions.TRANSACTION_STATUS_IDLE:
165168
conn.rollback()

migrations.py

Lines changed: 11 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)