Complete the code to create a connection pool with asyncpg in FastAPI.
import asyncpg async def connect_db(): pool = await asyncpg.create_pool(dsn=[1]) return pool
The DSN (Data Source Name) string specifies the database connection details needed to create the pool.
Complete the code to acquire a connection from the pool in an async context.
async with pool.[1]() as connection: result = await connection.fetch('SELECT 1')
Use acquire() to get a connection from the pool safely in an async context.
Fix the error in the code to properly release the connection back to the pool.
connection = await pool.[1]() try: await connection.execute('SELECT 1') finally: await connection.release()
Use acquire() to get a connection that can be released back to the pool.
Fill both blanks to create a FastAPI dependency that provides a connection from the pool.
from fastapi import Depends async def get_connection(pool=Depends([1])): async with pool.[2]() as conn: yield conn
The dependency connect_db provides the pool, and acquire() gets a connection from it.
Fill all three blanks to create a dictionary comprehension that maps table names to their row counts using a connection.
counts = { [1]: await conn.fetchval(f'SELECT COUNT(*) FROM [2]') for [1] in [3] }We loop over tables with variable table and use it in the query string.