MagicStack / asyncpg

A fast PostgreSQL Database Client Library for Python/asyncio.
Apache License 2.0
6.99k stars 404 forks source link

Support a Pool `before_connect` callback to be used before a connection is created #1118

Open jhinds opened 9 months ago

jhinds commented 9 months ago

Hello! This is more of a feature request but I was wondering if there could be support for having a before_connect or similar callback when creating a Pool object that would run before a new connection is created? I see there is already an init param which is run after a connection is made.

Our use case is that we use dynamic credentials to access our postgres database and want to make sure that when we create a connection we are using credentials that are not stale. Is this something that makes sense for this project? There is similar functionality in other libraries such as sqlalchemy or pgx.

I was looking at how to do this as-is and there were two currently that I was exploring. One way would be to create our own Pool class which seems like a lot of maintainance for what we'd like to do. The other looked at creating a subclass and overriding the acquire and using set_connect_args but that would run every time we get a connection from a pool which would be wasteful as opposed to just when the creation happens.

elprans commented 9 months ago

I think it makes sense to provide a way to pass a connection factory. E.g. a connector=coro or connection_factory=coro that should return an instance of asyncpg.Connection. I would accept a PR along these lines if you make one.