MagicStack / MagicStack/asyncpg

[BUG] Bare connections cannot be used as context managers

Open
#583 2 comments 24 reactions 0 assignees View on GitHub
Dominant language
Python
Stars
8.1k
Forks
468
PR merge metrics
No merged PRs in 30d

Description

* **asyncpg version**: 0.20.1
* **PostgreSQL version**: 10.3
* **Python version**: 3.8.2
* **Platform**: Windows
* **Do you use pgbouncer?**: No
* **Did you install asyncpg with pip?**: Yes

While under most use cases, people will want to use connection pools to manage their connections, there are times where using bare connections turns out to be more practical. However, while connection pools can be opened and closed via context managers:

```py
async with asyncpg.create_pool(user='postgres', command_timeout=60) as pool:
async with pool.acquire() as con:
await con.fetch('SELECT 1')
```

...it appears that bare connections created via `asyncpg.connect` do not support this:

```py
async with asyncpg.connect(user='postgres') as con:
await con.fetch('SELECT 1')
```

```
File "./test.py", line 120, in fetch_ip_list
async with asyncpg.connect(user="postgres") as con:
AttributeError: __aexit__
```

I personally like using `with` blocks to handle the scope of resources like this, so this is a step down for me in terms of ergonomics, not to mention rather surprising given that connections coming from connection pools do work as context managers (even though those are merely returned to the pool instead of closed).

Contributor guide

No contributing guide indexed for this repository

Research direction

Start at the asyncpg.connect entry point and compare its returned connection with the pool and pool.acquire context-manager behavior shown in the issue. Verify the expected async with lifecycle for a bare connection and add focused coverage for the reported example; done means the example enters and exits without AttributeError.

Written by the indexing model from the issue text.

Assessment

Tech stack
postgresql, python
Domain
databases
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.