pauldx
pauldx

Reputation: 1004

cx_oracle with Asyncio in Python with SQLAlchemy

I am confused from different thread posted in different time for this topic. Is this feature of Asyncio available with latest version(As of Dec 2019) of cx_Oracle?

I am using below code snippets which is working but not sure if this is perfect way to do async call for Oracle? Any pointer will be helpful.

import asyncio

async def sqlalchemyoracle_fetch():
      conn_start_time = time()
      oracle_tns_conn = 'oracle+cx_oracle://{username}:{password}@{tnsname}'
      engine = create_engine(
    oracle_tns_conn.format(
        username=USERNAME,
        password=PWD,
        tnsname=TNS,
    ),
    pool_recycle=50,
)

    for x in test:
        pd.read_sql(query_randomizer(x), engine) 

!calling custom query_randomizer function which will execute oracle queries from the parameters passed through test which is a list

async def main():
        tasks = [sqlalchemyoracle_asyncfetch()]
        return await asyncio.gather(*tasks)

if __name__ == "__main__":
    result = await main()

Upvotes: 2

Views: 4248

Answers (1)

hangc
hangc

Reputation: 5473

I use the cx_Oracle library but not SQLAlchemy. As of v8.2, asyncio is not supported.

This issue tracks and confirms it - https://github.com/oracle/python-cx_Oracle/issues/178.

And no, your code block does not run asynchronously, although defined using async def there is no statement in the code block that is asynchronous. To be asynchronous, your async function either needs to await another async function (that already supports async operations) or use yield to indicate a possible context switch. None of these happens in your code block.

You can try the following package which states to have implemented async support for cx_Oracle. https://pypi.org/project/cx-Oracle-async/

Upvotes: 1

Related Questions