Missing PoolListener in 1.4 and sql_mode

34 views
Skip to first unread message

••

unread,
Oct 29, 2022, 1:00:00 AM10/29/22
to sqlalchemy
Hi, I'm trying to move from 1.3 to 1.4 and immediately hit the issue with sqlalchemy.interfaces being removed.

Basically, we have a wrapper around create_engine() that looks something like this:

from sqlalchemy.engine import create_engine as _create_engine
from sqlalchemy.engine.interfaces import PoolListener

class StrictPoolListener(PoolListener):
    def connect(self, dbapi_connection, connection_record):
        cursor = dbapi_connection.cursor()
        cursor.execute("SET sql_mode='TRADITIONAL'")

def create_engine(database_url, **kwargs):
    if kwargs:
        engine = _create_engine(database_url, **kwargs)
    else:
        engine = _create_engine(database_url,
                                pool_pre_ping=True,
                                pool_recycle=3600,
                                listeners=[StrictPoolListener()])
    return engine


Which now fails. It sounds like with 1.4 (and before) we could use something like this:

from sqlalchemy import create_engine, event

eng = create_engine("mysql://scott:tiger@localhost/test", echo='debug')

@event.listens_for(eng, "connect", insert=True)
def connect(dbapi_connection, connection_record):
    cursor = dbapi_connection.cursor()
    cursor.execute("SET sql_mode = 'STRICT_ALL_TABLES'")


Maybe I'm missing something, but I don't see how that's going to work. "eng" would need to be defined and in scope before I could set a listener on it. With our existing code, someone gets back an engine object that automatically sets the correct sql_mode.

Is there any workaround that lets us continue to use the first pattern? Thanks.

••

unread,
Oct 29, 2022, 8:50:10 AM10/29/22
to sqlalchemy
Sorry this seems to work!

def create_engine(database_url, **kwargs):
    if kwargs:
        engine = _create_engine(database_url, **kwargs)
    else:
        engine = _create_engine(database_url, pool_pre_ping=True, pool_recycle=3600)

    @event.listens_for(engine, 'connect', insert=True)
    def connect(dbapi_connection, connection_record):
        cursor = dbapi_connection.cursor()
    
    cursor.execute("SET sql_mode = 'TRADITIONAL'")

    return engine

Thanks.
Reply all
Reply to author
Forward
0 new messages