0
# CLI Commands
1
2
Complete command-line interface for Alembic migration management. All commands are accessible through the `alembic` CLI tool and can also be called programmatically through the `alembic.command` module.
3
4
## Capabilities
5
6
### Environment Initialization
7
8
Initialize a new Alembic migration environment with configuration files and directory structure.
9
10
```python { .api }
11
def init(config, directory, template='generic', package=False):
12
"""
13
Initialize a new migration environment.
14
15
Args:
16
config (Config): Alembic configuration object
17
directory (str): Target directory for migration environment
18
template (str): Template to use ('generic', 'multidb', 'async')
19
package (bool): Generate __init__.py files for package structure
20
"""
21
```
22
23
**CLI Usage**: `alembic init migrations`
24
25
### Revision Management
26
27
Create and manage migration revisions with automatic or manual generation.
28
29
```python { .api }
30
def revision(config, message=None, autogenerate=False, sql=False, head='head', splice=False, branch_label=None, version_path=None, rev_id=None, depends_on=None, process_revision_directives=None):
31
"""
32
Create a new revision file.
33
34
Args:
35
config (Config): Alembic configuration object
36
message (str): Revision message/description
37
autogenerate (bool): Auto-generate migration operations
38
sql (bool): Generate SQL output instead of Python code
39
head (str): Head revision to base new revision on
40
splice (bool): Allow revision to be spliced into existing history
41
branch_label (str): Label for new branch
42
version_path (str): Path for version files
43
rev_id (str): Custom revision identifier
44
depends_on (str): Revision dependencies
45
process_revision_directives (ProcessRevisionDirectiveFn): Custom revision processing
46
47
Returns:
48
Union[Optional[Script], List[Optional[Script]]]: Generated script object(s)
49
"""
50
51
def merge(config, revisions, message=None, branch_label=None, rev_id=None):
52
"""
53
Merge multiple revisions into a single new revision.
54
55
Args:
56
config (Config): Alembic configuration object
57
revisions (str): Comma-separated revision identifiers to merge
58
message (str): Message for merge revision
59
branch_label (str): Branch label for merge revision
60
rev_id (str): Custom revision identifier
61
62
Returns:
63
Optional[Script]: Generated merge script
64
"""
65
66
def edit(config, rev):
67
"""
68
Edit a revision file in configured editor.
69
70
Args:
71
config (Config): Alembic configuration object
72
rev (str): Revision identifier to edit
73
74
Returns:
75
None
76
"""
77
```
78
79
**CLI Usage**:
80
- `alembic revision -m "Create user table"`
81
- `alembic revision --autogenerate -m "Auto-generate changes"`
82
- `alembic merge -m "Merge branches" head1 head2`
83
- `alembic edit abc123`
84
85
### Database Operations
86
87
Upgrade and downgrade database schema to specific revisions.
88
89
```python { .api }
90
def upgrade(config, revision, sql=False, tag=None):
91
"""
92
Upgrade to a later revision.
93
94
Args:
95
config (Config): Alembic configuration object
96
revision (str): Target revision ('head', 'base', or specific rev)
97
sql (bool): Output SQL instead of executing
98
tag (str): Tag to apply to revision
99
100
Returns:
101
None
102
"""
103
104
def downgrade(config, revision, sql=False, tag=None):
105
"""
106
Revert to a previous revision.
107
108
Args:
109
config (Config): Alembic configuration object
110
revision (str): Target revision ('base', '-1', or specific rev)
111
sql (bool): Output SQL instead of executing
112
tag (str): Tag to apply to revision
113
"""
114
115
def stamp(config, revision, sql=False, tag=None, purge=False):
116
"""
117
Mark revision as current without running migrations.
118
119
Args:
120
config (Config): Alembic configuration object
121
revision (str): Revision to stamp as current
122
sql (bool): Output SQL instead of executing
123
tag (str): Tag to apply
124
purge (bool): Delete all existing revision entries first
125
"""
126
```
127
128
**CLI Usage**:
129
- `alembic upgrade head` - Upgrade to latest
130
- `alembic upgrade +2` - Upgrade 2 revisions forward
131
- `alembic downgrade base` - Downgrade to initial state
132
- `alembic downgrade -1` - Downgrade 1 revision back
133
- `alembic stamp head` - Mark as current without running
134
135
### Status and Information
136
137
Check migration status and browse revision history.
138
139
```python { .api }
140
def current(config, verbose=False):
141
"""
142
Display current revision.
143
144
Args:
145
config (Config): Alembic configuration object
146
verbose (bool): Show detailed information
147
"""
148
149
def history(config, rev_range=None, verbose=False, indicate_current=False):
150
"""
151
List revision history.
152
153
Args:
154
config (Config): Alembic configuration object
155
rev_range (str): Range of revisions to show (e.g., 'base:head')
156
verbose (bool): Show detailed information
157
indicate_current (bool): Mark current revision
158
"""
159
160
def heads(config, verbose=False, resolve_dependencies=False):
161
"""
162
Show current head revisions.
163
164
Args:
165
config (Config): Alembic configuration object
166
verbose (bool): Show detailed information
167
resolve_dependencies (bool): Show dependency resolution
168
"""
169
170
def branches(config, verbose=False):
171
"""
172
Show branch points in revision history.
173
174
Args:
175
config (Config): Alembic configuration object
176
verbose (bool): Show detailed information
177
"""
178
179
def show(config, rev):
180
"""
181
Show information about a revision.
182
183
Args:
184
config (Config): Alembic configuration object
185
rev (str): Revision identifier to show
186
"""
187
188
def check(config):
189
"""
190
Check if revision command is pending.
191
192
Args:
193
config (Config): Alembic configuration object
194
195
Raises:
196
CommandError: If autogenerate changes are detected
197
"""
198
```
199
200
**CLI Usage**:
201
- `alembic current` - Show current revision
202
- `alembic history` - Show all revisions
203
- `alembic history -r base:head` - Show range
204
- `alembic heads` - Show head revisions
205
- `alembic branches` - Show branch points
206
- `alembic show abc123` - Show specific revision
207
- `alembic check` - Check for pending changes
208
209
### Utility Commands
210
211
Additional utility functions for migration management.
212
213
```python { .api }
214
def list_templates(config):
215
"""
216
List available migration templates.
217
218
Args:
219
config (Config): Alembic configuration object
220
221
Returns:
222
None: Prints template list to stdout
223
"""
224
225
def ensure_version(config, sql=False):
226
"""
227
Create alembic_version table in target database.
228
229
Args:
230
config (Config): Alembic configuration object
231
sql (bool): Output SQL instead of executing
232
"""
233
```
234
235
**CLI Usage**:
236
- `alembic list_templates` - Show available templates
237
- `alembic ensure_version` - Create version table
238
239
## Command Line Examples
240
241
### Basic Workflow
242
```bash
243
# Initialize environment
244
alembic init migrations
245
246
# Create first migration
247
alembic revision -m "Initial migration"
248
249
# Auto-generate migration from models
250
alembic revision --autogenerate -m "Add user table"
251
252
# Apply migrations
253
alembic upgrade head
254
255
# Check current status
256
alembic current
257
258
# View history
259
alembic history --verbose
260
261
# Rollback one revision
262
alembic downgrade -1
263
```
264
265
### Advanced Usage
266
```bash
267
# Create branch
268
alembic revision -m "Feature branch" --branch-label=feature
269
270
# Merge branches
271
alembic merge -m "Merge feature" head feature
272
273
# Generate SQL without executing
274
alembic upgrade head --sql
275
276
# Stamp without running migrations
277
alembic stamp head
278
279
# Check for pending autogenerate changes
280
alembic check
281
```
282
283
## Environment Variables and Configuration
284
285
Commands respect configuration from `alembic.ini` and can be overridden:
286
287
```bash
288
# Use different config file
289
alembic -c custom.ini upgrade head
290
291
# Override database URL
292
alembic -x dbname=testdb upgrade head
293
294
# Use different script location
295
alembic -x script_location=custom/migrations current
296
```
297
298
## Return Values
299
300
All command functions return relevant objects:
301
- `revision()`, `merge()`: Return `Script` objects
302
- `list_templates()`: Returns list of template names
303
- Status commands (`current`, `history`, etc.): Print to stdout/configured output
304
- Database operations (`upgrade`, `downgrade`): No return value, raise exceptions on error
305
306
## Error Handling
307
308
Commands raise specific exceptions:
309
- `CommandError`: General command execution errors
310
- `RevisionError`: Revision-related errors
311
- SQLAlchemy exceptions: Database connection/execution errors
312
313
## Types
314
315
```python { .api }
316
# Command function protocol
317
class CommandFunction(Protocol):
318
def __call__(self, config: Config, *args, **kwargs): ...
319
320
# Script object returned by revision commands
321
class Script:
322
revision: str
323
down_revision: Optional[str]
324
branch_labels: Optional[Set[str]]
325
depends_on: Optional[Set[str]]
326
path: str
327
```