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 sqlacodegenVerified import paths — ran on the pinned version, not inferred.
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.
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.
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.
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.
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.