5 Non-blocking database drivers
This chapter covers
- Running asyncio friendly database queries with asyncpg
- Running multiple SQL queries concurrently
- Creating database connection pools
- Managing asynchronous database transactions
- Using asynchronous generators to stream query results
Last chapter we learned how to make non-blocking web requests with the aiohttp library. We also learned several different asyncio API methods for running these requests concurrently. With the combination of the asyncio APIs and the aiohttp library we are able to run multiple long-running web requests concurrently leading to an improvement in our application’s run time. The concepts we learned in the last chapter do not just apply to web requests, they also apply to running SQL queries as well and can improve the performance of database-intensive applications.
Much like web requests, we’ll need to use an asyncio friendly library since our typical SQL libraries block the main thread, and therefore the event loop, until a result comes back. In this chapter we’ll learn more about an asynchronous database access with the asyncpg library. We’ll first create a simple schema to keep track of products for an e-commerce storefront that we’ll then use to run queries against asynchronously. We’ll then take a look at how to manage transactions and rollbacks within our database as well as set up connection pooling.