Search code examples
sqlalchemyasyncpg

connect_args in SQLAlchemy's create_async_engine


I'm attempting to add connect_args to create_async_engine, the asynchronous version of the create_engine. In the past, I've been able to specify my schema with the following synchronous engine creation:

sync_engine = create_engine(SYNC_URL, \
              connect_args={'options': '-csearch_path={}'.format(dbschema)}, echo=False)

I was under the impression that I could do the same thing with create_async_engine, appending {"options": csearch_path={...}} to the connect_args to detail my schema. However, I received the following error message:

TypeError: connect() got an unexpected keyword argument 'options'

that results from the following code:

async_engine = create_engine(ASYNC_URL, \
              connect_args={'options': '-csearch_path={}'.format(dbschema)}, echo=False)

The only difference between the two URLs is that ASYNC_URL includes asyncpg at `postgresql+asyncpg://.

This leads me to believe that adding connect_args to create_async_engine is possible, but that using options as I had in create_engine is certainly incorrect. Is there an alternative way to detail the options that I want to pass?

Edit:

On removing the options from connect_args, I see that I'm able to make successfully connect to my postgres instance, I just can't read the tables due to the lack of the schema definition.


Solution

  • I've found a fix that works in my case, and it has to do with the key/value expectations for connect_args. Rather than using options, I've used server_settings as follows:

    async_engine = create_async_engine(db_url, 
                  connect_args={'server_settings': {'search_path': dbschema}}, echo=False)
    

    This is referenced in this issue discussion, tangential to the issue I was having. We just replace the create_pool with the create_async_engine, which results in each session inheriting the search_path as opposed to creating sessions alone. This falls directly in line with the asyncpg dialect.