Closed wolfthom closed 2 months ago
The async interface of the Cloud SQL Python Connector is through the AsyncConnector
class as outlined in our README's Async Driver Usage section. Using the synchronous Connector
interface on the async driver will result in the error you are seeing.
import asyncio
import asyncpg
import sqlalchemy
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
from google.cloud.alloydb.connector import AsyncConnector
async def init_connection_pool(connector: AsyncConnector) -> AsyncEngine:
# initialize Connector object for connections to AlloyDB
async def getconn() -> asyncpg.Connection:
conn: asyncpg.Connection = await connector.connect(
"projects/<YOUR_PROJECT>/locations/<YOUR_REGION>/clusters/<YOUR_CLUSTER>/instances/<YOUR_INSTANCE>",
"asyncpg",
user="my-user",
password="my-password",
db="my-db-name"
# ... additional database driver args
)
return conn
# The AlloyDB Python Connector can be used along with SQLAlchemy using the
# 'async_creator' argument to 'create_async_engine'
pool = create_async_engine(
"postgresql+asyncpg://",
async_creator=getconn,
)
return pool
async def main():
# initialize Connector object for connections to AlloyDB
async with AsyncConnector() as connector:
# initialize connection pool
pool = await init_connection_pool(connector)
# example query
async with pool.connect() as conn:
await conn.execute(sqlalchemy.text("SELECT NOW()"))
# dispose of connection pool
await pool.dispose()```
Bug Description
When I try to connect to alloydb using the python connector and asyncpg as database driver, I get the following error:
Command used to install alloydb-python-connector: pip install alloydb-python-connector["asyncpg"]
Example code (or command)
Stacktrace
Steps to reproduce?
Environment
Additional Details
No response