0
# Connection Management
1
2
Database connection functionality including connection creation, lifecycle management, and resource cleanup. Provides async context managers for automatic resource management and configuration of connection properties.
3
4
## Capabilities
5
6
### Connection Creation
7
8
Creates an async database connection using a connector function that runs in a separate thread.
9
10
```python { .api }
11
def connect(
12
database: Union[str, Path],
13
*,
14
iter_chunk_size: int = 64,
15
loop: Optional[asyncio.AbstractEventLoop] = None,
16
**kwargs: Any
17
) -> Connection:
18
"""
19
Create and return a connection proxy to the sqlite database.
20
21
Parameters:
22
- database: Path to the database file (str or pathlib.Path)
23
- iter_chunk_size: Number of rows to fetch at once during iteration (default: 64)
24
- loop: Deprecated, ignored for compatibility
25
- **kwargs: Additional arguments passed to sqlite3.connect()
26
27
Returns:
28
Connection: Async database connection object
29
"""
30
```
31
32
Usage example:
33
34
```python
35
import aiosqlite
36
37
# Basic connection
38
conn = aiosqlite.connect("database.db")
39
40
# With connection parameters
41
conn = aiosqlite.connect(
42
"database.db",
43
iter_chunk_size=100,
44
timeout=10.0,
45
check_same_thread=False
46
)
47
48
# Using context manager (recommended)
49
async with aiosqlite.connect("database.db") as db:
50
# Database operations here
51
pass
52
```
53
54
### Connection Lifecycle
55
56
The Connection class manages the database connection lifecycle and thread communication.
57
58
```python { .api }
59
class Connection:
60
"""
61
Async SQLite database connection running in separate thread.
62
"""
63
64
def __init__(
65
self,
66
connector: Callable[[], sqlite3.Connection],
67
iter_chunk_size: int,
68
loop: Optional[asyncio.AbstractEventLoop] = None
69
) -> None: ...
70
71
async def __aenter__(self) -> "Connection":
72
"""Async context manager entry."""
73
74
async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
75
"""Async context manager exit with automatic cleanup."""
76
77
def __await__(self) -> Generator[Any, None, "Connection"]:
78
"""Enable awaiting the connection directly."""
79
```
80
81
### Connection Control
82
83
Methods for controlling connection state and lifecycle.
84
85
```python { .api }
86
async def close(self) -> None:
87
"""
88
Complete queued queries/cursors and close the connection.
89
90
Ensures all pending operations complete before closing.
91
After calling close(), the connection cannot be used for new operations.
92
"""
93
94
async def interrupt(self) -> None:
95
"""
96
Interrupt pending queries.
97
98
Calls sqlite3.Connection.interrupt() to cancel long-running operations.
99
Operations may still complete normally if interruption occurs too late.
100
"""
101
```
102
103
Usage example:
104
105
```python
106
# Manual connection management
107
conn = await aiosqlite.connect("database.db")
108
try:
109
# Database operations
110
await conn.execute("SELECT * FROM large_table")
111
# Interrupt if needed
112
await conn.interrupt()
113
finally:
114
await conn.close()
115
```
116
117
### Connection Properties
118
119
Properties for accessing connection state and configuration.
120
121
```python { .api }
122
@property
123
def in_transaction(self) -> bool:
124
"""
125
True if connection has an uncommitted transaction.
126
127
Returns:
128
bool: Transaction state
129
"""
130
131
@property
132
def isolation_level(self) -> Optional[str]:
133
"""
134
Current isolation level setting.
135
136
Returns:
137
Optional[str]: 'DEFERRED', 'IMMEDIATE', 'EXCLUSIVE', or None for autocommit
138
"""
139
140
@isolation_level.setter
141
def isolation_level(self, value: IsolationLevel) -> None:
142
"""
143
Set isolation level for transactions.
144
145
Parameters:
146
- value: 'DEFERRED', 'IMMEDIATE', 'EXCLUSIVE', or None for autocommit
147
"""
148
149
@property
150
def row_factory(self) -> Optional[type]:
151
"""
152
Current row factory for query results.
153
154
Returns:
155
Optional[type]: Row factory class or None for default tuple rows
156
"""
157
158
@row_factory.setter
159
def row_factory(self, factory: Optional[type]) -> None:
160
"""
161
Set row factory for query results.
162
163
Parameters:
164
- factory: Row factory class (e.g., sqlite3.Row) or None for tuples
165
"""
166
167
@property
168
def text_factory(self) -> Callable[[bytes], Any]:
169
"""
170
Current text factory for handling TEXT columns.
171
172
Returns:
173
Callable: Function to convert bytes to text
174
"""
175
176
@text_factory.setter
177
def text_factory(self, factory: Callable[[bytes], Any]) -> None:
178
"""
179
Set text factory for TEXT column handling.
180
181
Parameters:
182
- factory: Function to convert bytes to desired text type
183
"""
184
185
@property
186
def total_changes(self) -> int:
187
"""
188
Total number of database changes since connection opened.
189
190
Returns:
191
int: Total change count
192
"""
193
```
194
195
Usage example:
196
197
```python
198
async with aiosqlite.connect("database.db") as db:
199
# Configure connection
200
db.row_factory = aiosqlite.Row # Get rows as dict-like objects
201
db.isolation_level = "IMMEDIATE" # Set transaction isolation
202
203
# Check connection state
204
print(f"In transaction: {db.in_transaction}")
205
print(f"Total changes: {db.total_changes}")
206
```
207
208