or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

autogeneration.mdcli-commands.mdconfiguration.mdindex.mdmigration-context.mdmigration-operations.mdruntime.mdscript-management.md

index.mddocs/

0

# Alembic

1

2

A comprehensive database migration tool specifically designed for SQLAlchemy applications. Alembic enables developers to manage database schema changes through version-controlled migration scripts with advanced features including ALTER statement generation, sequential migration execution with upgrade/downgrade capabilities, auto-generation of migration candidates, and full support for transactional DDL operations.

3

4

## Package Information

5

6

- **Package Name**: alembic

7

- **Package Type**: pypi

8

- **Language**: Python

9

- **Installation**: `pip install alembic`

10

- **Documentation**: https://alembic.sqlalchemy.org/en/latest/

11

12

## Core Imports

13

14

```python

15

import alembic

16

from alembic import context, op

17

```

18

19

For command-line operations:

20

```python

21

from alembic.config import Config

22

from alembic import command

23

```

24

25

For programmatic migration execution:

26

```python

27

from alembic.runtime.environment import EnvironmentContext

28

from alembic.runtime.migration import MigrationContext

29

```

30

31

## Basic Usage

32

33

### Initialize Migration Environment

34

```python

35

from alembic.config import Config

36

from alembic import command

37

38

# Initialize new migration environment

39

config = Config("alembic.ini")

40

command.init(config, "migrations")

41

```

42

43

### Create Migration Revision

44

```python

45

# Create new migration revision

46

command.revision(config, message="Create user table", autogenerate=True)

47

48

# Run migration

49

command.upgrade(config, "head")

50

```

51

52

### Migration Script Example

53

```python

54

"""Create user table

55

56

Revision ID: 001

57

Create Date: 2023-01-01 10:00:00.000000

58

59

"""

60

from alembic import op

61

import sqlalchemy as sa

62

63

# revision identifiers

64

revision = '001'

65

down_revision = None

66

67

def upgrade():

68

op.create_table('user',

69

sa.Column('id', sa.Integer, primary_key=True),

70

sa.Column('name', sa.String(50), nullable=False),

71

sa.Column('email', sa.String(120), unique=True)

72

)

73

74

def downgrade():

75

op.drop_table('user')

76

```

77

78

## Architecture

79

80

Alembic is built around several key components:

81

82

- **Configuration System**: `Config` class manages connection strings, script locations, and environment settings

83

- **Migration Context**: Provides database connection and transaction management during migrations

84

- **Operations API**: High-level interface for schema changes (create_table, add_column, etc.)

85

- **Script Management**: Handles migration file generation, versioning, and dependency tracking

86

- **Autogeneration**: Compares database schema with SQLAlchemy models to generate migrations

87

- **Command Interface**: CLI and programmatic interfaces for migration management

88

89

## Capabilities

90

91

### CLI Commands

92

93

Complete command-line interface for migration management including environment initialization, revision creation, database upgrades/downgrades, and status checking.

94

95

```python { .api }

96

# Key command functions

97

def init(config, directory, template='generic', package=False): ...

98

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): ...

99

def upgrade(config, revision, sql=False, tag=None): ...

100

def downgrade(config, revision, sql=False, tag=None): ...

101

def current(config, verbose=False): ...

102

def history(config, rev_range=None, verbose=False, indicate_current=False): ...

103

def check(config): ... # v1.9.0+

104

def ensure_version(config, sql=False): ... # v1.7.6+

105

def merge(config, revisions, message=None, branch_label=None, rev_id=None): ...

106

def stamp(config, revision, sql=False, tag=None, purge=False): ...

107

```

108

109

[CLI Commands](./cli-commands.md)

110

111

### Migration Operations

112

113

Schema modification operations available in migration scripts through the `op` module, including table and column operations, constraints, indexes, and data manipulation.

114

115

```python { .api }

116

# Core operation functions

117

def create_table(table_name, *columns, if_not_exists=None, **kw): ...

118

def drop_table(table_name, if_exists=None, **kw): ... # v1.16.0+

119

def add_column(table_name, column, if_not_exists=None, **kw): ... # v1.16.0+

120

def drop_column(table_name, column_name, if_exists=None, **kw): ... # v1.16.0+

121

def alter_column(table_name, column_name, **kw): ...

122

def create_index(index_name, table_name, columns, if_not_exists=None, **kw): ... # v1.12.0+

123

def drop_index(index_name, table_name=None, if_exists=None, **kw): ... # v1.12.0+

124

def create_foreign_key(constraint_name, source_table, referent_table, local_cols, remote_cols, **kw): ...

125

def drop_constraint(constraint_name, table_name, type_=None, if_exists=None): ... # v1.16.0+

126

def batch_alter_table(table_name, schema=None, **kw): ... # Context manager

127

def run_async(async_function, *args, **kw_args): ... # v1.11+

128

def f(name): ... # Naming convention support

129

```

130

131

[Migration Operations](./migration-operations.md)

132

133

### Migration Context

134

135

Environment context functions for accessing database connections, configuration, and migration state within migration scripts.

136

137

```python { .api }

138

# Core context functions

139

def configure(connection=None, url=None, dialect_name=None, **kw): ...

140

def get_bind(): ...

141

def get_context(): ...

142

def execute(sql, execution_options=None): ...

143

def is_offline_mode(): ...

144

def is_transactional_ddl(): ...

145

def run_migrations(): ...

146

def begin_transaction(): ... # Context manager

147

def get_head_revision(): ...

148

def get_head_revisions(): ...

149

def get_revision_argument(): ...

150

def get_starting_revision_argument(): ...

151

def get_tag_argument(): ...

152

def get_x_argument(as_dictionary=False): ...

153

def static_output(text): ... # Offline mode output

154

```

155

156

[Migration Context](./migration-context.md)

157

158

### Configuration Management

159

160

Configuration classes and utilities for managing Alembic settings, database connections, and migration environments.

161

162

```python { .api }

163

class Config:

164

def __init__(self, file_=None, toml_file=None, ini_section='alembic', output_buffer=None, stdout=sys.stdout, cmd_opts=None, config_args=None, attributes=None): ...

165

def get_main_option(self, name, default=None): ...

166

def set_main_option(self, name, value): ...

167

def get_section_option(self, section, name, default=None): ...

168

def set_section_option(self, section, name, value): ...

169

def get_section(self, name, default=None): ...

170

def get_alembic_option(self, name, default=None): ... # v1.16.0+

171

def get_alembic_boolean_option(self, name): ... # v1.16.0+

172

def get_version_locations_list(self): ...

173

def get_hooks_list(self): ...

174

def print_stdout(self, text, *arg): ...

175

```

176

177

[Configuration](./configuration.md)

178

179

### Autogeneration

180

181

Automatic migration generation by comparing database schema with SQLAlchemy model definitions, including customizable comparison and rendering systems.

182

183

```python { .api }

184

def compare_metadata(context, metadata): ...

185

def produce_migrations(context, metadata): ...

186

def render_python_code(up_ops, down_ops, migration_context, **kwargs): ...

187

def render_op_text(autogen_context, op): ...

188

189

# Customization support

190

class AutogenContext: ...

191

class RevisionContext: ...

192

class Rewriter: ... # Operation rewriting

193

194

# Registries for extensibility

195

comparators: Registry # Custom comparison functions

196

renderers: Registry # Custom rendering functions

197

```

198

199

[Autogeneration](./autogeneration.md)

200

201

### Script Management

202

203

Classes and utilities for managing migration scripts, revision tracking, and dependency graphs.

204

205

```python { .api }

206

class ScriptDirectory:

207

def __init__(self, dir, file_template=None, truncate_slug_length=40, version_locations=None, sourceless=False, output_encoding='utf-8', timezone=None, hooks=None, recursive_version_locations=False, messaging_opts=None): ...

208

def from_config(cls, config): ... # Class method

209

def generate_revision(self, revid, message, **kw): ...

210

def get_revision(self, id_): ...

211

def get_current_head(self): ...

212

def get_heads(self): ...

213

def get_base(self): ...

214

def walk_revisions(self, head='heads', base='base'): ...

215

def iterate_revisions(self, upper, lower): ...

216

def run_env(self): ...

217

```

218

219

[Script Management](./script-management.md)

220

221

### Runtime Components

222

223

Core runtime classes for migration execution context management, revision tracking, and transaction handling.

224

225

```python { .api }

226

class MigrationContext:

227

def configure(cls, connection=None, url=None, **opts): ... # Class method

228

def get_current_revision(self): ...

229

def get_current_heads(self): ...

230

def execute(self, sql, execution_options=None): ...

231

def stamp(self, script_directory, revision): ...

232

def run_migrations(self): ...

233

234

class EnvironmentContext:

235

def configure(self, connection=None, target_metadata=None, **kw): ...

236

def run_migrations(self, **kw): ...

237

# Properties

238

config: Config

239

script: ScriptDirectory

240

```

241

242

[Runtime Components](./runtime.md)

243

244

## Common Patterns

245

246

### Environment Setup

247

```python

248

# alembic/env.py template structure

249

from alembic import context

250

from sqlalchemy import engine_from_config

251

252

config = context.config

253

target_metadata = None

254

255

def run_migrations_offline():

256

context.configure(url=url, target_metadata=target_metadata)

257

with context.begin_transaction():

258

context.run_migrations()

259

260

def run_migrations_online():

261

connectable = engine_from_config(config.get_section(config.config_ini_section))

262

with connectable.connect() as connection:

263

context.configure(connection=connection, target_metadata=target_metadata)

264

with context.begin_transaction():

265

context.run_migrations()

266

```

267

268

### Batch Operations for SQLite

269

```python

270

def upgrade():

271

with op.batch_alter_table("user") as batch_op:

272

batch_op.add_column(sa.Column('created_at', sa.DateTime))

273

batch_op.alter_column('name', nullable=True)

274

```

275

276

## Types

277

278

```python { .api }

279

# Type imports

280

from typing import Union, List, Optional, Set, Any, Dict, Tuple, Callable, Iterator, ContextManager

281

from sqlalchemy import Connection, Dialect, Table, Column

282

from sqlalchemy.sql.schema import Constraint, Index

283

from argparse import Namespace

284

285

# Type aliases

286

_RevIdType = Union[str, List[str], Tuple[str, ...]]

287

ProcessRevisionDirectiveFn = Callable[..., Any]

288

289

# Configuration types

290

class Config:

291

cmd_opts: Optional[Namespace]

292

config_args: Dict[str, Any]

293

config_file_name: Optional[str]

294

toml_file_name: Optional[str] # v1.16.0+

295

attributes: Dict[str, Any]

296

297

# Context types

298

class MigrationContext:

299

bind: Connection

300

dialect: Dialect

301

302

class EnvironmentContext:

303

config: Config

304

script: ScriptDirectory

305

306

# Script types

307

class Script:

308

revision: str

309

down_revision: Optional[str]

310

branch_labels: Optional[Set[str]]

311

depends_on: Optional[Set[str]]

312

path: str

313

314

class ScriptDirectory:

315

dir: str

316

versions: str

317

revision_map: RevisionMap

318

319

# Operation types

320

class Operations:

321

migration_context: MigrationContext

322

323

class BatchOperations(Operations):

324

table: Table

325

326

# Messaging configuration (v1.15.3+)

327

class MessagingOptions:

328

file_template: str

329

truncate_slug_length: int

330

timezone: Optional[str]

331

332

# Post-write hook configuration

333

class PostWriteHookConfig:

334

type: str

335

entrypoint: str

336

options: Dict[str, Any]

337

338

# Exception types

339

class CommandError(Exception): ...

340

class AutogenerateDiffsDetected(Exception): ...

341

class RevisionError(Exception): ...

342

```