0
# Connection Management
1
2
Comprehensive database connection functionality including establishment, authentication, configuration, and lifecycle management. AsyncPG provides both single connections and connection pooling with full PostgreSQL feature support.
3
4
## Capabilities
5
6
### Connection Establishment
7
8
Create database connections with extensive configuration options including authentication, SSL/TLS, timeouts, and PostgreSQL-specific settings.
9
10
```python { .api }
11
async def connect(
12
dsn: str = None,
13
*,
14
host: str = None,
15
port: int = None,
16
user: str = None,
17
password: typing.Union[str, typing.Callable[[], str]] = None,
18
passfile: str = None,
19
database: str = None,
20
loop: asyncio.AbstractEventLoop = None,
21
timeout: float = 60,
22
statement_cache_size: int = 100,
23
max_cached_statement_lifetime: float = 300,
24
max_cacheable_statement_size: int = 15360,
25
command_timeout: float = None,
26
ssl: typing.Union[bool, ssl.SSLContext] = None,
27
direct_tls: bool = None,
28
connection_class: type = Connection,
29
record_class: type = Record,
30
server_settings: typing.Dict[str, str] = None,
31
target_session_attrs: str = None,
32
krbsrvname: str = None,
33
gsslib: str = None
34
) -> Connection
35
"""
36
Establish a connection to a PostgreSQL server.
37
38
Parameters:
39
dsn: PostgreSQL connection string (postgresql://user:pass@host:port/database)
40
host: Database server host name or IP address
41
port: Database server port number (default: 5432)
42
user: Database user name
43
password: Database password
44
passfile: Path to password file (.pgpass format)
45
database: Database name to connect to
46
timeout: Connection timeout in seconds
47
statement_cache_size: Maximum number of prepared statements to cache
48
max_cached_statement_lifetime: Maximum lifetime of cached statements
49
max_cacheable_statement_size: Maximum size of statements to cache
50
command_timeout: Default timeout for commands
51
ssl: SSL/TLS configuration (True, False, or SSLContext)
52
direct_tls: Use direct TLS connection (without STARTTLS)
53
connection_class: Custom connection class to use
54
record_class: Custom record class for query results
55
server_settings: PostgreSQL server parameters to set on connection
56
target_session_attrs: Required server attributes ('read-write', 'read-only', etc.)
57
krbsrvname: Kerberos service name for GSSAPI authentication
58
gsslib: GSSAPI library to use ('gssapi' or 'sspi')
59
60
Returns:
61
Connection instance
62
"""
63
```
64
65
#### Example Usage
66
67
```python
68
# Basic connection
69
conn = await asyncpg.connect('postgresql://user:pass@localhost/mydb')
70
71
# Connection with SSL
72
conn = await asyncpg.connect(
73
host='localhost',
74
user='postgres',
75
password='secret',
76
database='mydb',
77
ssl=True
78
)
79
80
# Advanced configuration
81
conn = await asyncpg.connect(
82
'postgresql://user:pass@localhost/mydb',
83
statement_cache_size=200,
84
command_timeout=30.0,
85
server_settings={
86
'application_name': 'my_app',
87
'timezone': 'UTC'
88
}
89
)
90
```
91
92
### Connection State Management
93
94
Monitor and control connection state including closure detection, server information, and connection reset.
95
96
```python { .api }
97
def is_closed(self) -> bool:
98
"""Return True if the connection is closed."""
99
100
def is_in_transaction(self) -> bool:
101
"""Return True if the connection is currently in a transaction."""
102
103
async def close(self, *, timeout: float = None) -> None:
104
"""
105
Close the connection gracefully.
106
107
Parameters:
108
timeout: Maximum time to wait for graceful closure
109
"""
110
111
def terminate(self) -> None:
112
"""Terminate the connection immediately without waiting."""
113
114
async def reset(self, *, timeout: float = None) -> None:
115
"""
116
Reset the connection state.
117
118
Resets all connection state including:
119
- Aborts current transaction
120
- Closes all cursors
121
- Resets session state
122
- Clears statement cache
123
124
Parameters:
125
timeout: Maximum time to wait for reset
126
"""
127
```
128
129
### Server Information
130
131
Access PostgreSQL server details including version, process ID, and connection settings.
132
133
```python { .api }
134
def get_server_pid(self) -> int:
135
"""Return the process ID of the PostgreSQL server."""
136
137
def get_server_version(self) -> ServerVersion:
138
"""Return the version of the connected PostgreSQL server."""
139
140
def get_settings(self) -> ConnectionSettings:
141
"""Return current connection settings and codec information."""
142
143
def get_reset_query(self) -> str:
144
"""Return the query that will be sent to reset connection state."""
145
```
146
147
### Connection Authentication
148
149
AsyncPG supports all PostgreSQL authentication methods:
150
151
- **Password Authentication**: Plain text and MD5
152
- **SCRAM-SHA-256**: Modern secure authentication
153
- **GSSAPI/Kerberos**: Enterprise authentication
154
- **SSPI**: Windows integrated authentication
155
- **Certificate Authentication**: Client SSL certificates
156
- **Peer Authentication**: Unix socket authentication
157
158
#### GSSAPI/Kerberos Example
159
160
```python
161
# Install with GSSAPI support
162
# pip install asyncpg[gssauth]
163
164
conn = await asyncpg.connect(
165
host='database.company.com',
166
user='user@COMPANY.COM',
167
database='mydb',
168
krbsrvname='postgres',
169
gsslib='gssapi'
170
)
171
```
172
173
### SSL/TLS Configuration
174
175
Comprehensive SSL/TLS support with various security levels and certificate validation.
176
177
```python
178
import ssl
179
180
# Simple SSL
181
conn = await asyncpg.connect(dsn, ssl=True)
182
183
# SSL with verification disabled (testing only)
184
conn = await asyncpg.connect(dsn, ssl='prefer')
185
186
# Custom SSL context
187
ssl_context = ssl.create_default_context()
188
ssl_context.check_hostname = False
189
ssl_context.verify_mode = ssl.CERT_REQUIRED
190
191
conn = await asyncpg.connect(dsn, ssl=ssl_context)
192
193
# Client certificate authentication
194
ssl_context = ssl.create_default_context()
195
ssl_context.load_cert_chain('/path/to/client.crt', '/path/to/client.key')
196
conn = await asyncpg.connect(dsn, ssl=ssl_context)
197
```
198
199
### Connection Error Handling
200
201
Handle various connection-related errors with appropriate recovery strategies.
202
203
```python
204
try:
205
conn = await asyncpg.connect(dsn, timeout=10.0)
206
except asyncpg.ConnectionFailureError:
207
# Network connectivity issues
208
print("Cannot reach database server")
209
except asyncpg.InvalidAuthorizationSpecificationError:
210
# Authentication failed
211
print("Invalid credentials")
212
except asyncpg.PostgresConnectionError:
213
# General connection problems
214
print("Connection error occurred")
215
except asyncio.TimeoutError:
216
# Connection timeout
217
print("Connection timed out")
218
```
219
220
## Types
221
222
```python { .api }
223
class Connection:
224
"""A representation of a database session."""
225
226
def is_closed(self) -> bool
227
def is_in_transaction(self) -> bool
228
def get_server_pid(self) -> int
229
def get_server_version(self) -> ServerVersion
230
def get_settings(self) -> ConnectionSettings
231
def get_reset_query(self) -> str
232
def terminate(self) -> None
233
234
async def close(self, *, timeout: float = None) -> None
235
async def reset(self, *, timeout: float = None) -> None
236
237
class ServerVersion:
238
"""PostgreSQL server version information."""
239
major: int
240
minor: int
241
micro: int
242
releaselevel: str
243
serial: int
244
245
class ConnectionSettings:
246
"""Connection configuration and codec information."""
247
...
248
```