Search code examples
postgresqltransactionssqlalchemyreadonly

How to use READ ONLY transaction mode in SQLAlchemy?


In PostgreSQL transaction access mode can be changed to READ ONLY (docs). In SQLAlchemy, isolation level can be changed for an engine, but no parameter is provided for read-only access mode (docs).

How to make an engine with READ ONLY access mode on connections?


Solution

  • One solution is to execute a statement on every transaction:

    engine = create_engine('postgresql+psycopg2://postgres:pass@127.0.0.1:5432/')
    @event.listens_for(engine, 'begin')
    def receive_begin(conn):
        conn.execute('SET TRANSACTION READ ONLY')
    

    But it's better to set mode in BEGIN TRANSACTION line an not a separate statement.