3

With PostgreSQL, you can run this query to set a specific lock_timeout for a session:

SET lock_timeout TO '3s'

I'm wondering if there is a nice way to set this option when setting up a connection with SQLAlchemy. The way I'm instantiating SQLAlchemy sessions is the following:

engine = create_engine('postgresql+psycopg2://{user}:{pswd}@{host}:{port}/{name}')
session = scoped_session(sessionmaker(bind=engine))

I've tried passing it in connect_args but that is not supported:

engine = create_engine(
    'postgresql+psycopg2://{user}:{pswd}@{host}:{port}/{name}',
    connect_args={'lock_timeout': 3}
)

Is there a way to set this option per-session/connection with SQLAlchemy and psycopg2?

1 Answer 1

5

As it turned out, this is the right way to set lock_timeout for a session (note that the value is in milliseconds):

engine = create_engine(
    'postgresql+psycopg2://{user}:{pswd}@{host}:{port}/{name}',
    connect_args={'options': '-c lock_timeout=3000'}
)
Sign up to request clarification or add additional context in comments.

4 Comments

Does the connect_args={'lock_timeout': 3} method not work or it is not the right way to do it? Also, can you share the link to some documentation, I am not about this find this way: {'options': '-c lock_timeout=3000'} of passing arguments anywhere in the documentation.
@KshitijMittal it's somewhat tricky. No, "bare" lock_timeout: 3 is not the right way. lock_timeout is one of options as described at postgresql.org/docs/current/… (look for "options" param). So "options" is a "connection argument" that wraps another format for defining "options". "options" in general are described at postgresql.org/docs/current/runtime-config.html and lock_timeout in particular at postgresql.org/docs/current/….
... and the whole "-c" form is mentioned at postgresql.org/docs/current/config-setting.html.
Out of date. TypeError: Engine.connect() got an unexpected keyword argument 'connect_args'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.