Changeset 527c097 for db.py


Ignore:
Timestamp:
04/05/26 20:02:04 (3 months ago)
Author:
teo <teodorbogoeski@…>
Branches:
main
Parents:
95cf703
Message:

Add connection pooling and transaction management

File:
1 edited

Legend:

Unmodified
Added
Removed
  • db.py

    r95cf703 r527c097  
    11import datetime
    22import psycopg2
     3from psycopg2 import pool
     4from contextlib import contextmanager
    35
    46DB_CONFIG = {
     
    1113}
    1214
     15# -- Connection Pool ----------------------------------------------------------
     16# Reuses database connections instead of opening a new one per query.
     17# SimpleConnectionPool maintains between minconn and maxconn connections.
    1318
     19_pool = None
     20
     21
     22def _get_pool():
     23    global _pool
     24    if _pool is None:
     25        _pool = pool.SimpleConnectionPool(minconn=2, maxconn=10, **DB_CONFIG)
     26    return _pool
     27
     28
     29@contextmanager
    1430def get_connection():
    15     return psycopg2.connect(**DB_CONFIG)
     31    """Get a read-only connection from the pool.
     32    Autocommit is enabled so SELECTs don't need explicit commit.
     33    Connection is returned to the pool on exit."""
     34    p = _get_pool()
     35    conn = p.getconn()
     36    try:
     37        conn.autocommit = True
     38        yield conn
     39    finally:
     40        conn.autocommit = False
     41        p.putconn(conn)
     42
     43
     44@contextmanager
     45def get_transaction():
     46    """Get a connection with explicit transaction management.
     47    Commits on successful exit, rolls back on exception.
     48    Connection is returned to the pool in both cases."""
     49    p = _get_pool()
     50    conn = p.getconn()
     51    try:
     52        conn.autocommit = False
     53        yield conn
     54        conn.commit()
     55    except Exception:
     56        conn.rollback()
     57        raise
     58    finally:
     59        p.putconn(conn)
     60
     61
     62def close_pool():
     63    """Close all connections in the pool."""
     64    global _pool
     65    if _pool is not None:
     66        _pool.closeall()
     67        _pool = None
     68
     69
     70# -- UI Helpers ---------------------------------------------------------------
    1671
    1772
Note: See TracChangeset for help on using the changeset viewer.