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

configuration.mddocs/

0

# Configuration

1

2

Configuration classes and utilities for managing Alembic settings, database connections, and migration environments. The main configuration is handled through the `Config` class and associated utilities.

3

4

## Core Imports

5

6

```python

7

from alembic.config import Config, CommandLine

8

from alembic import command

9

```

10

11

## Capabilities

12

13

### Configuration Class

14

15

Main configuration class for Alembic that manages settings from INI files and command-line options.

16

17

```python { .api }

18

class Config:

19

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

20

"""

21

Initialize Alembic configuration.

22

23

Args:

24

file_ (str): Path to configuration file (alembic.ini)

25

toml_file (str): Path to TOML configuration file (pyproject.toml) (v1.16.0+)

26

ini_section (str): INI section name to read from

27

output_buffer (StringIO): Buffer for output capture

28

stdout (file): Standard output stream

29

cmd_opts (Namespace): Command-line options from argparse

30

config_args (dict): Additional configuration arguments

31

attributes (dict): Custom attributes dictionary

32

"""

33

34

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

35

"""

36

Get a main configuration option.

37

38

Args:

39

name (str): Option name

40

default: Default value if option not found

41

42

Returns:

43

str|None: Option value

44

"""

45

46

def set_main_option(self, name, value):

47

"""

48

Set a main configuration option.

49

50

Args:

51

name (str): Option name

52

value (str): Option value

53

"""

54

55

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

56

"""

57

Get a configuration section as dictionary.

58

59

Args:

60

name (str): Section name

61

default (dict): Default dictionary if section not found

62

63

Returns:

64

dict: Section as key-value pairs

65

"""

66

67

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

68

"""

69

Set an option within a specific section.

70

71

Args:

72

section (str): Section name

73

name (str): Option name

74

value (str): Option value

75

"""

76

77

def remove_main_option(self, name):

78

"""

79

Remove a main configuration option.

80

81

Args:

82

name (str): Option name to remove

83

"""

84

85

def get_template_directory(self):

86

"""

87

Get the template directory path.

88

89

Returns:

90

str: Path to template directory

91

"""

92

93

def print_stdout(self, text, *arg):

94

"""

95

Print text to configured stdout.

96

97

Args:

98

text (str): Text to print

99

*arg: Additional arguments for string formatting

100

"""

101

102

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

103

"""

104

Get an option from a specific section.

105

106

Args:

107

section (str): Section name

108

name (str): Option name

109

default: Default value if not found

110

111

Returns:

112

Optional[str]: Option value

113

"""

114

115

def get_alembic_option(self, name, default=None):

116

"""

117

Get option from TOML alembic configuration (v1.16.0+).

118

119

Args:

120

name (str): Option name

121

default: Default value if not found

122

123

Returns:

124

Union[None, str, list[str], dict[str, str], list[dict[str, str]], int]: Option value

125

"""

126

127

def get_alembic_boolean_option(self, name):

128

"""

129

Get boolean option from TOML alembic configuration (v1.16.0+).

130

131

Args:

132

name (str): Option name

133

134

Returns:

135

bool: Boolean option value

136

"""

137

138

def get_version_locations_list(self):

139

"""

140

Get list of version locations from configuration.

141

142

Returns:

143

Optional[list[str]]: List of version location paths

144

"""

145

146

def get_prepend_sys_paths_list(self):

147

"""

148

Get list of paths to prepend to sys.path.

149

150

Returns:

151

Optional[list[str]]: List of paths to prepend

152

"""

153

154

def get_hooks_list(self):

155

"""

156

Get list of configured post-write hooks.

157

158

Returns:

159

list[PostWriteHookConfig]: List of hook configurations

160

"""

161

```

162

163

**Usage Examples**:

164

```python

165

# Create configuration from file

166

config = Config('alembic.ini')

167

168

# Create programmatic configuration

169

config = Config()

170

config.set_main_option('script_location', 'migrations')

171

config.set_main_option('sqlalchemy.url', 'postgresql://user:pass@localhost/db')

172

173

# Get database URL

174

db_url = config.get_main_option('sqlalchemy.url')

175

176

# Get section for engine configuration

177

db_config = config.get_section('sqlalchemy')

178

```

179

180

### Command Line Interface

181

182

Handle command-line parsing and execution.

183

184

```python { .api }

185

class CommandLine:

186

def __init__(self, prog=None):

187

"""

188

Initialize command-line interface.

189

190

Args:

191

prog (str): Program name for help text

192

"""

193

194

def main(self, argv=None):

195

"""

196

Main entry point for command-line interface.

197

198

Args:

199

argv (list): Command-line arguments (sys.argv if None)

200

"""

201

202

def run_cmd(self, config, options):

203

"""

204

Execute a command with given configuration and options.

205

206

Args:

207

config (Config): Alembic configuration

208

options (Namespace): Parsed command-line options

209

"""

210

```

211

212

### Console Entry Point

213

214

Main entry point function for the `alembic` command.

215

216

```python { .api }

217

def main(argv=None, prog=None, **kwargs):

218

"""

219

Console runner for Alembic.

220

221

Args:

222

argv (list): Command-line arguments

223

prog (str): Program name

224

**kwargs: Additional keyword arguments

225

"""

226

```

227

228

**Usage Example**:

229

```python

230

# Programmatic CLI execution

231

from alembic.config import main

232

main(['upgrade', 'head'])

233

```

234

235

### Configuration File Format

236

237

Standard `alembic.ini` configuration file structure:

238

239

```ini

240

# alembic.ini example

241

[alembic]

242

# Path to migration scripts

243

script_location = migrations

244

245

# Template used to generate migration files

246

file_template = %%(rev)s_%%(slug)s

247

248

# Timezone for revision timestamps

249

timezone = UTC

250

251

# Maximum length of revision slug

252

truncate_slug_length = 40

253

254

# SQLAlchemy logging levels

255

sqlalchemy.warn_20 = 1

256

257

# Database connection

258

sqlalchemy.url = postgresql://user:password@localhost/dbname

259

260

# Logging configuration

261

[loggers]

262

keys = root,sqlalchemy,alembic

263

264

[handlers]

265

keys = console

266

267

[formatters]

268

keys = generic

269

270

[logger_root]

271

level = WARN

272

handlers = console

273

qualname =

274

275

[logger_sqlalchemy]

276

level = WARN

277

handlers =

278

qualname = sqlalchemy.engine

279

280

[logger_alembic]

281

level = INFO

282

handlers =

283

qualname = alembic

284

285

[handler_console]

286

class = StreamHandler

287

args = (sys.stderr,)

288

level = NOTSET

289

formatter = generic

290

291

[formatter_generic]

292

format = %(levelname)-5.5s [%(name)s] %(message)s

293

datefmt = %H:%M:%S

294

```

295

296

### Messaging Configuration

297

298

Configuration for output and messaging formatting.

299

300

```python { .api }

301

class MessagingOptions(TypedDict):

302

"""

303

Type definition for messaging configuration options.

304

"""

305

message_format: str

306

color: bool

307

308

# Example messaging configuration

309

messaging_opts = {

310

'message_format': '%(levelname)s: %(message)s',

311

'color': True

312

}

313

```

314

315

## Configuration Options

316

317

### Main Section Options

318

319

Standard options in the `[alembic]` section:

320

321

- `script_location`: Directory containing migration scripts

322

- `file_template`: Template for migration file names

323

- `timezone`: Timezone for revision timestamps

324

- `truncate_slug_length`: Maximum length for revision slugs

325

- `sourceless`: Whether to run migrations from .pyc files

326

- `version_locations`: Additional directories for version files

327

- `version_path_separator`: Separator for version paths

328

- `output_encoding`: Encoding for output files

329

330

### SQLAlchemy Options

331

332

Database connection and SQLAlchemy configuration:

333

334

- `sqlalchemy.url`: Database connection URL

335

- `sqlalchemy.echo`: Enable SQL logging

336

- `sqlalchemy.echo_pool`: Enable connection pool logging

337

- `sqlalchemy.pool_pre_ping`: Enable connection health checks

338

- `sqlalchemy.pool_recycle`: Connection recycling interval

339

340

### Template Variables

341

342

Variables available in migration templates:

343

344

- `${revision}`: Revision identifier

345

- `${down_revision}`: Previous revision identifier

346

- `${branch_labels}`: Branch labels

347

- `${depends_on}`: Dependencies

348

- `${create_date}`: Creation timestamp

349

350

## Programmatic Configuration

351

352

### Creating Configuration Objects

353

354

```python

355

# From file

356

config = Config('alembic.ini')

357

358

# From specific section

359

config = Config('alembic.ini', ini_section='custom_section')

360

361

# Programmatic configuration

362

config = Config()

363

config.set_main_option('script_location', 'db/migrations')

364

config.set_main_option('sqlalchemy.url', database_url)

365

366

# With command-line options

367

import argparse

368

parser = argparse.ArgumentParser()

369

parser.add_argument('--sql', action='store_true')

370

args = parser.parse_args()

371

config = Config('alembic.ini', cmd_opts=args)

372

```

373

374

### Dynamic Configuration

375

376

```python

377

def get_database_url():

378

# Dynamic URL resolution

379

import os

380

return os.environ.get('DATABASE_URL', 'sqlite:///alembic.db')

381

382

config = Config('alembic.ini')

383

config.set_main_option('sqlalchemy.url', get_database_url())

384

385

# Environment-specific configuration

386

env = os.environ.get('ENV', 'development')

387

config.set_main_option('script_location', f'migrations/{env}')

388

```

389

390

### Multi-Database Configuration

391

392

```python

393

# Multiple database sections

394

config = Config('alembic.ini')

395

396

# Primary database

397

primary_config = config.get_section('primary')

398

primary_url = primary_config['url']

399

400

# Secondary database

401

secondary_config = config.get_section('secondary')

402

secondary_url = secondary_config['url']

403

404

# Use with commands

405

command.upgrade(config, 'head', sql=False)

406

```

407

408

## Integration Patterns

409

410

### Flask Integration

411

412

```python

413

from flask import Flask

414

from alembic.config import Config

415

from alembic import command

416

417

app = Flask(__name__)

418

419

def get_alembic_config():

420

config = Config()

421

config.set_main_option('script_location', 'migrations')

422

config.set_main_option('sqlalchemy.url', app.config['SQLALCHEMY_DATABASE_URI'])

423

return config

424

425

@app.cli.command()

426

def db_upgrade():

427

"""Run database migrations."""

428

config = get_alembic_config()

429

command.upgrade(config, 'head')

430

431

@app.cli.command()

432

def db_migrate():

433

"""Generate migration."""

434

config = get_alembic_config()

435

command.revision(config, autogenerate=True)

436

```

437

438

### Django Integration

439

440

```python

441

from django.conf import settings

442

from alembic.config import Config

443

from alembic import command

444

445

def get_alembic_config():

446

config = Config()

447

config.set_main_option('script_location', 'alembic')

448

config.set_main_option('sqlalchemy.url', get_django_database_url())

449

return config

450

451

def get_django_database_url():

452

db = settings.DATABASES['default']

453

return f"{db['ENGINE']}://{db['USER']}:{db['PASSWORD']}@{db['HOST']}/{db['NAME']}"

454

```

455

456

### Testing Configuration

457

458

```python

459

import tempfile

460

import os

461

462

def create_test_config():

463

"""Create configuration for testing."""

464

temp_dir = tempfile.mkdtemp()

465

config = Config()

466

config.set_main_option('script_location', os.path.join(temp_dir, 'migrations'))

467

config.set_main_option('sqlalchemy.url', 'sqlite:///:memory:')

468

return config, temp_dir

469

470

# Use in tests

471

config, temp_dir = create_test_config()

472

command.init(config, config.get_main_option('script_location'))

473

```

474

475

## Error Handling

476

477

Configuration errors may include:

478

- `CommandError`: Invalid configuration or missing files

479

- `ConfigParser` exceptions: INI file parsing errors

480

- `AttributeError`: Missing required configuration options

481

482

## Types

483

484

```python { .api }

485

# Configuration types

486

class Config:

487

config_file_name: Optional[str]

488

config_ini_section: str

489

cmd_opts: Optional[Namespace]

490

491

attributes: Dict[str, Any]

492

config_args: Dict[str, Any]

493

494

# Command function protocol

495

class CommandFunction(Protocol):

496

def __call__(self, config: Config, *args, **kwargs): ...

497

498

# Messaging configuration

499

class MessagingOptions(TypedDict, total=False):

500

message_format: str

501

color: bool

502

```