MagicStack / asyncpg

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

Add support for PGOPTIONS environment variable #1070

Open dfuhry opened 1 year ago

dfuhry commented 1 year ago

asyncpg supports an explicit server_options=... dict connection method parameter, but does not seem to populate its value from the PGOPTIONS environment variable. This is a feature request for it to do so.

Specifically, asyncpg/connect_utils.py reads user, host, port, database, password, and SSL information with calls like os.getenv('PGUSER'), os.environ.get('PGHOST'), etc. There is no corresponding call for reading PGOPTIONS.

I would like to set the environment variable PGOPTIONS='-c default_transaction_read_only=on -c statement_timeout=120s' and have asyncpg interpret its values as server_settings the way libpq does. For instance, the below works for psql:

PGOPTIONS='-c statement_timeout=1s' psql -c "SELECT pg_sleep(2)"
ERROR:  canceling statement due to statement timeout

but a simple asyncpg script running the same ignores the statement_timeout since it never reads the value of PGOPTIONS.

$ PGOPTIONS='-c statement_timeout=1s' ./test_asyncpg_timeout.py 
SELECT 1

https://www.postgresql.org/docs/current/libpq-envars.html