Registry / database / sqlacodegen

sqlacodegen

JSON →
library4.0.4pypypi✓ verified 22d ago

sqlacodegen is a command-line tool that automatically generates SQLAlchemy model code from an existing database schema. It introspects tables, columns, types, and relationships, producing Python files ready for use with SQLAlchemy 2.0+. The current version is 4.0.3, and it receives updates as SQLAlchemy evolves.

pip install sqlacodegen
INSTALL
IMPORT
SIG · SQLACODEGEN
S
sqlacodegen
databasepythonv4.0.4
Install
3.6s avg
Import
Disk
43MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v4.0.4 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.000s · 44.3MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 3.6s · import 0.000s · 42MB
43MB installed
● package 43MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

CodeGenerator
import sqlacodegen
from sqlacodegen import CodeGenerator

This quickstart demonstrates how to use `sqlacodegen` to generate SQLAlchemy models from a simple SQLite database. It first creates a dummy database with a 'users' table, then executes the `sqlacodegen` command-line tool via `subprocess`, printing the generated models to the console. For real-world use, you would direct the output to a Python file using the `--outfile` flag.

import subprocess import os from sqlalchemy import create_engine, Column, Integer, String, MetaData, Table # Create a dummy SQLite database in memory db_url = 'sqlite:///test.db' engine = create_engine(db_url) metadata = MetaData() # Define a simple table table_name = 'users' users_table = Table( table_name, metadata, Column('id', Integer, primary_key=True), Column('name', String(50), nullable=False), Column('email', String(100), unique=True) ) # Create the table in the database metadata.create_all(engine) # Run sqlacodegen as a subprocess # For demonstration, we'll print to stdout. Use --outfile to save to a file. try: result = subprocess.run( ['sqlacodegen', db_url], capture_output=True, text=True, check=True ) print("\n--- Generated SQLAlchemy Models ---") print(result.stdout) print("-----------------------------------") except subprocess.CalledProcessError as e: print(f"Error running sqlacodegen: {e}\nStdout: {e.stdout}\nStderr: {e.stderr}") except FileNotFoundError: print("Error: sqlacodegen command not found. Please ensure it's installed and in your PATH.") finally: # Clean up the dummy database file if os.path.exists('test.db'): os.remove('test.db')
sqlacodegen --version
Debug
Known issues
breakingBreaking change in generated model syntax between SQLAlchemy 1.x and 2.x. `sqlacodegen` versions 3.0+ (including 4.x) generate models compatible with SQLAlchemy 2.0+ (e.g., using `Mapped` and `Column` as a function). Older `sqlacodegen` 2.x versions generated SQLAlchemy 1.x style models (e.g., `Column` as a class attribute).
fix
Ensure you are using `sqlacodegen` version 3.0 or higher for SQLAlchemy 2.0+ projects. If migrating, review the generated code for 2.0 idioms and adapt existing 1.x code manually.
affects: 3.0.0 and later
gotchaBy default, `sqlacodegen` overwrites existing files if you use the `--outfile` flag without additional safeguards. It does not perform intelligent merging or incremental updates, treating each run as a fresh generation.
fix
Always use a version control system (e.g., Git) and review changes (`git diff`) before committing. Consider piping the output to `diff` or a temporary file first, or integrating `sqlacodegen` into a script that handles file comparison and merging.
affects: All versions
gotchasqlacodegen strictly reflects the existing database schema. It does not infer ORM-specific features like back-references, complex relationships not explicitly defined by foreign keys, or custom business logic/methods often added to ORM models.
fix
After generating the initial models, you will need to manually add ORM-specific relationships (e.g., `relationship()`, `backref`), methods, and other custom logic to enhance your models beyond the raw schema reflection. Treat the generated code as a starting point.
affects: All versions
gotchaGenerated Python class and attribute names might not always conform to Python's `snake_case` or project-specific naming conventions, especially for multi-word table or column names, or in environments where `CamelCase` is prevalent in the database.
fix
Manually refactor names in the generated models to match your project's Python naming conventions. For consistent transformations, consider creating a custom Jinja2 template for `sqlacodegen` (an advanced option) or using a post-processing script.
affects: All versions
Upgrade
Version history
4.0.4latest on PyPI · released Jun 19, 2026
Audit
Dependencies
SQLAlchemyrequiredCore dependency for database introspection and model generation. Requires SQLAlchemy 2.0.0b1 or newer.
Jinja2requiredUsed for templating the generated Python code.
Agent activity
20 hits · last 30 days
node
18
OpenAI (training)
1
Resources
sqlacodegen — pip install sqlacodegen · libregistry