0
# Runtime Components
1
2
Core runtime classes and utilities for migration execution, context management, and revision tracking. These components provide the underlying infrastructure for Alembic's migration operations.
3
4
## Core Imports
5
6
```python
7
from alembic.runtime.migration import MigrationContext
8
from alembic.runtime.environment import EnvironmentContext
9
```
10
11
## Capabilities
12
13
### Migration Context
14
15
Core context class that manages database connections, dialect-specific behavior, and migration execution state.
16
17
```python { .api }
18
class MigrationContext:
19
def __init__(self, dialect, connection, opts, environment_context=None):
20
"""
21
Initialize migration context.
22
23
Args:
24
dialect (Dialect): SQLAlchemy dialect
25
connection (Connection): Database connection
26
opts (dict): Configuration options
27
environment_context (EnvironmentContext): Environment context
28
"""
29
30
@classmethod
31
def configure(cls, connection=None, url=None, dialect_name=None, dialect_opts=None, opts=None, environment_context=None):
32
"""
33
Configure and create migration context.
34
35
Args:
36
connection (Connection): Database connection
37
url (str): Database URL if connection not provided
38
dialect_name (str): Dialect name
39
dialect_opts (dict): Dialect options
40
opts (dict): Migration options
41
environment_context (EnvironmentContext): Environment context
42
43
Returns:
44
MigrationContext: Configured migration context
45
"""
46
47
def get_current_revision(self):
48
"""
49
Get current revision from database.
50
51
Returns:
52
str: Current revision identifier
53
"""
54
55
def stamp(self, script_directory, revision):
56
"""
57
Stamp database with revision without running migration.
58
59
Args:
60
script_directory (ScriptDirectory): Script directory
61
revision (str): Revision to stamp
62
"""
63
64
def run_migrations(self, **kw):
65
"""
66
Execute migration operations.
67
68
Args:
69
**kw: Additional migration arguments
70
"""
71
72
def execute(self, sql, execution_options=None):
73
"""
74
Execute SQL statement.
75
76
Args:
77
sql (str|ClauseElement): SQL to execute
78
execution_options (dict): Execution options
79
80
Returns:
81
Result of SQL execution
82
"""
83
84
def begin_transaction(self):
85
"""
86
Begin transaction context for migration.
87
88
Returns:
89
Transaction context manager
90
"""
91
92
# Properties
93
bind: Connection # Database connection
94
dialect: Dialect # SQLAlchemy dialect
95
script: ScriptDirectory # Script directory
96
opts: Dict[str, Any] # Configuration options
97
environment_context: EnvironmentContext # Environment context
98
```
99
100
### Environment Context
101
102
High-level context for managing migration environment configuration and execution.
103
104
```python { .api }
105
class EnvironmentContext:
106
def __init__(self, config, script, **kw):
107
"""
108
Initialize environment context.
109
110
Args:
111
config (Config): Alembic configuration
112
script (ScriptDirectory): Script directory
113
**kw: Additional context options
114
"""
115
116
def configure(self, connection=None, url=None, dialect_name=None, transactional_ddl=None, output_buffer=None, starting_rev=None, tag=None, template_args=None, render_as_batch=None, target_metadata=None, include_name=None, include_object=None, include_schemas=None, process_revision_directives=None, compare_type=None, compare_server_default=None, render_item=None, literal_binds=None, upgrade_token=None, downgrade_token=None, alembic_module_prefix=None, sqlalchemy_module_prefix=None, user_module_prefix=None, **kw):
117
"""
118
Configure the environment context for migrations.
119
120
Args:
121
connection (Connection): Database connection
122
url (str): Database URL
123
dialect_name (str): Dialect name
124
transactional_ddl (bool): Use transactional DDL
125
output_buffer (StringIO): Output buffer for offline mode
126
starting_rev (str): Starting revision
127
tag (str): Migration tag
128
template_args (dict): Template variables
129
render_as_batch (bool): Render as batch operations
130
target_metadata (MetaData): Target metadata for comparison
131
include_name (callable): Name filtering function
132
include_object (callable): Object filtering function
133
include_schemas (bool): Include schema information
134
process_revision_directives (callable): Custom revision processing
135
compare_type (bool): Enable type comparison
136
compare_server_default (bool): Enable server default comparison
137
render_item (callable): Custom rendering function
138
literal_binds (bool): Use literal parameter binds
139
upgrade_token (str): Upgrade operation token
140
downgrade_token (str): Downgrade operation token
141
alembic_module_prefix (str): Alembic module prefix
142
sqlalchemy_module_prefix (str): SQLAlchemy module prefix
143
user_module_prefix (str): User module prefix
144
**kw: Additional configuration options
145
"""
146
147
def run_migrations(self, **kw):
148
"""
149
Execute migration operations.
150
151
Args:
152
**kw: Additional migration arguments
153
"""
154
155
def get_context(self):
156
"""
157
Get the migration context.
158
159
Returns:
160
MigrationContext: Current migration context
161
"""
162
163
def get_bind(self):
164
"""
165
Get the database connection.
166
167
Returns:
168
Connection: Database connection
169
"""
170
171
# Properties
172
config: Config # Alembic configuration
173
script: ScriptDirectory # Script directory
174
context_opts: Dict[str, Any] # Context options
175
```
176
177
### Migration Tracking Classes
178
179
Classes for tracking migration steps and revision information.
180
181
```python { .api }
182
class MigrationInfo:
183
def __init__(self, revision, is_upgrade, is_stamp):
184
"""
185
Information about a migration step.
186
187
Args:
188
revision (str): Revision identifier
189
is_upgrade (bool): Whether this is an upgrade
190
is_stamp (bool): Whether this is a stamp operation
191
"""
192
193
revision: str # Revision identifier
194
is_upgrade: bool # Upgrade direction
195
is_stamp: bool # Stamp operation
196
197
class MigrationStep:
198
def __init__(self, up_revision, down_revision, is_upgrade, migration_fn):
199
"""
200
A single migration step.
201
202
Args:
203
up_revision (str): Target revision
204
down_revision (str): Source revision
205
is_upgrade (bool): Migration direction
206
migration_fn (callable): Migration function
207
"""
208
209
up_revision: str # Target revision
210
down_revision: str # Source revision
211
is_upgrade: bool # Migration direction
212
migration_fn: Callable # Migration function
213
214
class RevisionStep:
215
def __init__(self, revision_map, revision, is_upgrade):
216
"""
217
A revision step in migration path.
218
219
Args:
220
revision_map (RevisionMap): Revision map
221
revision (Script): Revision script
222
is_upgrade (bool): Migration direction
223
"""
224
225
revision: Script # Revision script
226
is_upgrade: bool # Migration direction
227
doc: str # Revision message
228
229
class StampStep:
230
def __init__(self, from_, to_, is_upgrade):
231
"""
232
A stamp step that marks revision without migration.
233
234
Args:
235
from_ (str): Source revision
236
to_ (str): Target revision
237
is_upgrade (bool): Direction
238
"""
239
240
from_: str # Source revision
241
to_: str # Target revision
242
is_upgrade: bool # Direction
243
```
244
245
### Head Maintenance
246
247
Utility for tracking and managing revision heads.
248
249
```python { .api }
250
class HeadMaintainer:
251
def __init__(self, context, heads):
252
"""
253
Initialize head maintainer.
254
255
Args:
256
context (MigrationContext): Migration context
257
heads (tuple): Current head revisions
258
"""
259
260
def update_to_step(self, step):
261
"""
262
Update heads based on migration step.
263
264
Args:
265
step (MigrationStep): Step being executed
266
"""
267
268
def heads(self):
269
"""
270
Get current heads.
271
272
Returns:
273
tuple: Current head revisions
274
"""
275
```
276
277
### Transaction Proxy
278
279
Internal transaction management for migration contexts.
280
281
```python { .api }
282
class _ProxyTransaction:
283
def __init__(self, migration_context):
284
"""
285
Initialize transaction proxy.
286
287
Args:
288
migration_context (MigrationContext): Migration context
289
"""
290
291
def rollback(self):
292
"""Rollback the transaction."""
293
294
def commit(self):
295
"""Commit the transaction."""
296
297
def __enter__(self):
298
"""Enter transaction context."""
299
return self
300
301
def __exit__(self, type_, value, traceback):
302
"""Exit transaction context."""
303
```
304
305
## Usage Patterns
306
307
### Creating Migration Context
308
309
```python
310
from alembic.runtime.migration import MigrationContext
311
from sqlalchemy import create_engine
312
313
engine = create_engine('postgresql://user:pass@localhost/db')
314
with engine.connect() as connection:
315
context = MigrationContext.configure(
316
connection=connection,
317
opts={
318
'target_metadata': target_metadata,
319
'compare_type': True,
320
'compare_server_default': True
321
}
322
)
323
324
# Get current revision
325
current = context.get_current_revision()
326
print(f"Current revision: {current}")
327
328
# Execute SQL
329
context.execute("SELECT version()")
330
```
331
332
### Environment Context Usage
333
334
```python
335
from alembic.runtime.environment import EnvironmentContext
336
from alembic.config import Config
337
from alembic.script import ScriptDirectory
338
339
config = Config('alembic.ini')
340
script_dir = ScriptDirectory.from_config(config)
341
342
env_context = EnvironmentContext(config, script_dir)
343
344
def run_migrations():
345
engine = create_engine(config.get_main_option('sqlalchemy.url'))
346
with engine.connect() as connection:
347
env_context.configure(
348
connection=connection,
349
target_metadata=target_metadata
350
)
351
352
with env_context.begin_transaction():
353
env_context.run_migrations()
354
```
355
356
### Migration Step Processing
357
358
```python
359
from alembic.runtime.migration import MigrationStep
360
361
def process_migration_steps(steps):
362
"""Process a sequence of migration steps."""
363
for step in steps:
364
print(f"{'Upgrading' if step.is_upgrade else 'Downgrading'} "
365
f"from {step.down_revision} to {step.up_revision}")
366
367
# Execute migration function
368
step.migration_fn()
369
```
370
371
## Integration Examples
372
373
### Custom Migration Context
374
375
```python
376
class CustomMigrationContext(MigrationContext):
377
def __init__(self, *args, **kwargs):
378
super().__init__(*args, **kwargs)
379
self.custom_state = {}
380
381
def execute(self, sql, execution_options=None):
382
# Add custom logging
383
print(f"Executing: {sql}")
384
return super().execute(sql, execution_options)
385
386
def custom_operation(self, data):
387
"""Custom migration operation."""
388
self.custom_state['last_operation'] = data
389
return self.execute(f"-- Custom: {data}")
390
```
391
392
### Advanced Environment Setup
393
394
```python
395
def create_advanced_environment():
396
"""Create environment with advanced configuration."""
397
config = Config('alembic.ini')
398
script_dir = ScriptDirectory.from_config(config)
399
400
def run_migrations_with_custom_context():
401
engine = create_engine(config.get_main_option('sqlalchemy.url'))
402
403
with engine.connect() as connection:
404
# Create custom migration context
405
context = CustomMigrationContext.configure(
406
connection=connection,
407
opts={
408
'target_metadata': target_metadata,
409
'process_revision_directives': custom_directive_processor,
410
'include_object': custom_object_filter,
411
'compare_type': advanced_type_comparison
412
}
413
)
414
415
with context.begin_transaction():
416
context.run_migrations()
417
418
return run_migrations_with_custom_context
419
```
420
421
## Error Handling
422
423
Runtime components may raise:
424
- `RevisionError`: Revision-related errors
425
- `EnvironmentError`: Environment configuration errors
426
- `MigrationError`: Migration execution errors
427
- Database-specific exceptions during execution
428
429
## Types
430
431
```python { .api }
432
# Runtime component types
433
class MigrationContext:
434
bind: Connection
435
dialect: Dialect
436
script: ScriptDirectory
437
opts: Dict[str, Any]
438
environment_context: EnvironmentContext
439
440
class EnvironmentContext:
441
config: Config
442
script: ScriptDirectory
443
context_opts: Dict[str, Any]
444
445
# Migration step types
446
class MigrationInfo:
447
revision: str
448
is_upgrade: bool
449
is_stamp: bool
450
451
class MigrationStep:
452
up_revision: str
453
down_revision: str
454
is_upgrade: bool
455
migration_fn: Callable
456
457
# Function type annotations
458
MigrationFunction = Callable[[], None]
459
DirectiveProcessor = Callable[[MigrationContext, Tuple, List], None]
460
ObjectFilter = Callable[[Any, str, str, bool, Any], bool]
461
```