0
# Database Operations and Configuration
1
2
Core database management functionality through the Tortoise class and connection handling system. This includes database initialization, connection management, schema generation, and configuration options for multiple database backends.
3
4
## Capabilities
5
6
### Tortoise Configuration Class
7
8
Main class for configuring and managing Tortoise ORM, including database connections, model registration, and schema operations.
9
10
```python { .api }
11
class Tortoise:
12
"""Main configuration and management class for Tortoise ORM."""
13
14
apps = {} # Registry of apps and models
15
table_name_generator = None # Custom table name generator function
16
17
@classmethod
18
async def init(cls,
19
config=None,
20
config_file=None,
21
_create_db=False,
22
db_url=None,
23
modules=None,
24
use_tz=False,
25
timezone="UTC",
26
routers=None,
27
table_name_generator=None):
28
"""
29
Initialize Tortoise ORM with database connections and models.
30
31
Args:
32
config (dict, optional): Full configuration dictionary
33
config_file (str, optional): Path to JSON/YAML config file
34
db_url (str, optional): Database URL for simple setup
35
modules (dict, optional): Model modules mapping for simple setup
36
_create_db (bool): Create database if it doesn't exist
37
use_tz (bool): Use timezone-aware datetimes
38
timezone (str): Default timezone
39
routers (list, optional): Database routing classes
40
table_name_generator (callable, optional): Custom table name generator
41
42
Raises:
43
ConfigurationError: For invalid configuration
44
"""
45
46
@classmethod
47
async def generate_schemas(cls, safe=True):
48
"""
49
Generate database schemas for all registered models.
50
51
Args:
52
safe (bool): Only create tables that don't exist
53
54
Raises:
55
ConfigurationError: If not initialized
56
"""
57
58
@classmethod
59
async def close_connections(cls):
60
"""
61
Close all database connections cleanly.
62
"""
63
64
@classmethod
65
def describe_models(cls, models=None, serializable=True):
66
"""
67
Describe registered models or specific models.
68
69
Args:
70
models (list, optional): Specific models to describe
71
serializable (bool): Return JSON-serializable format
72
73
Returns:
74
dict: Model descriptions keyed by model name
75
"""
76
77
@classmethod
78
def init_models(cls, models_paths, app_label, _init_relations=True):
79
"""
80
Initialize models from module paths.
81
82
Args:
83
models_paths (iterable): Module paths containing models
84
app_label (str): Application label
85
_init_relations (bool): Initialize model relationships
86
87
Raises:
88
ConfigurationError: For invalid models or configuration
89
"""
90
91
@classmethod
92
def get_connection(cls, connection_name):
93
"""
94
Get database connection by name (deprecated).
95
96
Args:
97
connection_name (str): Connection name
98
99
Returns:
100
BaseDBAsyncClient: Database connection
101
102
Raises:
103
ConfigurationError: If connection doesn't exist
104
"""
105
```
106
107
### Connection Management
108
109
Global connection handler for managing database connections across the application.
110
111
```python { .api }
112
from tortoise import connections
113
114
# Connection handler methods
115
connections.get(alias) # Get connection by name
116
connections.all() # Get all connections
117
connections.close_all(discard=False) # Close all connections
118
connections.discard(alias) # Remove connection from registry
119
```
120
121
### Database Client Interface
122
123
Base database client providing the interface for database operations.
124
125
```python { .api }
126
class BaseDBAsyncClient:
127
"""Base async database client interface."""
128
129
async def execute_query(self, query, values=None):
130
"""
131
Execute raw SQL query.
132
133
Args:
134
query (str): SQL query string
135
values (list, optional): Query parameters
136
137
Returns:
138
Result set
139
"""
140
141
async def execute_script(self, query):
142
"""
143
Execute SQL script.
144
145
Args:
146
query (str): SQL script
147
"""
148
149
async def execute_many(self, query, values):
150
"""
151
Execute query with multiple parameter sets.
152
153
Args:
154
query (str): SQL query string
155
values (list): List of parameter sets
156
"""
157
158
async def close(self):
159
"""Close database connection."""
160
161
async def db_create(self):
162
"""Create database."""
163
164
async def db_delete(self):
165
"""Delete database."""
166
```
167
168
### Configuration Formats
169
170
#### Simple Configuration with db_url
171
172
```python
173
await Tortoise.init(
174
db_url='sqlite://db.sqlite3',
175
modules={'models': ['app.models']}
176
)
177
```
178
179
#### Full Configuration Dictionary
180
181
```python
182
config = {
183
'connections': {
184
'default': {
185
'engine': 'tortoise.backends.asyncpg',
186
'credentials': {
187
'host': 'localhost',
188
'port': '5432',
189
'user': 'tortoise',
190
'password': 'password',
191
'database': 'test',
192
}
193
}
194
},
195
'apps': {
196
'models': {
197
'models': ['app.models'],
198
'default_connection': 'default',
199
}
200
},
201
'use_tz': False,
202
'timezone': 'UTC'
203
}
204
205
await Tortoise.init(config=config)
206
```
207
208
#### JSON Configuration File
209
210
```json
211
{
212
"connections": {
213
"default": "postgres://user:pass@localhost:5432/db"
214
},
215
"apps": {
216
"models": {
217
"models": ["app.models"],
218
"default_connection": "default"
219
}
220
}
221
}
222
```
223
224
```python
225
await Tortoise.init(config_file='config.json')
226
```
227
228
### Database Backends
229
230
Supported database engines and their connection URLs.
231
232
#### SQLite
233
234
```python
235
# File-based SQLite
236
db_url = 'sqlite://db.sqlite3'
237
238
# In-memory SQLite
239
db_url = 'sqlite://:memory:'
240
```
241
242
#### PostgreSQL
243
244
```python
245
# asyncpg backend (recommended)
246
db_url = 'postgres://user:pass@host:port/database'
247
248
# psycopg backend
249
db_url = 'postgres://user:pass@host:port/database?backend=psycopg'
250
```
251
252
#### MySQL
253
254
```python
255
db_url = 'mysql://user:pass@host:port/database'
256
```
257
258
#### Microsoft SQL Server
259
260
```python
261
db_url = 'mssql://user:pass@host:port/database'
262
```
263
264
#### Oracle
265
266
```python
267
db_url = 'oracle://user:pass@host:port/database'
268
```
269
270
### Transaction Management
271
272
Context manager for database transactions.
273
274
```python { .api }
275
from tortoise.transactions import in_transaction
276
277
async def transfer_funds(from_account, to_account, amount):
278
async with in_transaction():
279
from_account.balance -= amount
280
to_account.balance += amount
281
await from_account.save()
282
await to_account.save()
283
284
# With specific connection
285
async with in_transaction("db_alias"):
286
# Transaction operations
287
pass
288
```
289
290
## Usage Examples
291
292
### Basic Setup
293
294
```python
295
from tortoise import Tortoise
296
from tortoise.models import Model
297
from tortoise import fields
298
299
class User(Model):
300
id = fields.IntField(pk=True)
301
name = fields.CharField(max_length=50)
302
303
async def init_db():
304
# Initialize with database URL
305
await Tortoise.init(
306
db_url='sqlite://db.sqlite3',
307
modules={'models': ['__main__']}
308
)
309
310
# Generate database schema
311
await Tortoise.generate_schemas()
312
313
async def close_db():
314
# Clean shutdown
315
await Tortoise.close_connections()
316
```
317
318
### Multiple Databases
319
320
```python
321
config = {
322
'connections': {
323
'default': 'sqlite://db.sqlite3',
324
'cache': 'sqlite://cache.sqlite3',
325
},
326
'apps': {
327
'models': {
328
'models': ['app.models'],
329
'default_connection': 'default',
330
},
331
'cache': {
332
'models': ['app.cache_models'],
333
'default_connection': 'cache',
334
}
335
}
336
}
337
338
await Tortoise.init(config=config)
339
```
340
341
### Custom Table Names
342
343
```python
344
def custom_table_name(model_class):
345
return f"custom_{model_class.__name__.lower()}"
346
347
await Tortoise.init(
348
db_url='sqlite://db.sqlite3',
349
modules={'models': ['app.models']},
350
table_name_generator=custom_table_name
351
)
352
```
353
354
### Schema Management
355
356
```python
357
# Generate all schemas (fails if tables exist)
358
await Tortoise.generate_schemas(safe=False)
359
360
# Generate only missing schemas
361
await Tortoise.generate_schemas(safe=True)
362
363
# Drop all schemas (for testing)
364
await Tortoise._drop_databases()
365
```
366
367
### Utility Functions
368
369
```python { .api }
370
from tortoise import run_async
371
372
def run_async(coro):
373
"""
374
Simple async runner that cleans up connections on exit.
375
376
Args:
377
coro: Coroutine to run
378
379
Usage:
380
async def main():
381
await Tortoise.init(...)
382
# Do work
383
384
run_async(main())
385
"""
386
```
387
388
### Connection Access
389
390
```python
391
from tortoise import connections
392
393
# Get specific connection
394
conn = connections.get('default')
395
396
# Execute raw SQL
397
result = await conn.execute_query("SELECT COUNT(*) FROM users")
398
399
# Get all connection names
400
connection_names = list(connections._connections.keys())
401
402
# Close specific connection
403
await connections.close_all()
404
```