{"id":4395,"library":"sqlacodegen","title":"SQLAlchemy Code Generator","description":"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.","status":"active","version":"4.0.3","language":"en","source_language":"en","source_url":"https://github.com/agronholm/sqlacodegen","tags":["SQLAlchemy","ORM","code generation","database tools","CLI"],"install":[{"cmd":"pip install sqlacodegen","lang":"bash","label":"Install sqlacodegen"}],"dependencies":[{"reason":"Core dependency for database introspection and model generation. Requires SQLAlchemy 2.0.0b1 or newer.","package":"SQLAlchemy","optional":false},{"reason":"Used for templating the generated Python code.","package":"Jinja2","optional":false}],"imports":[{"note":"sqlacodegen is primarily a command-line tool. Direct programmatic import of internal classes like CodeGenerator is generally for advanced use cases or integration, not typical model generation. Most users execute it via the 'sqlacodegen' CLI command.","symbol":"CodeGenerator","correct":"from sqlacodegen.codegen import CodeGenerator"}],"quickstart":{"code":"import subprocess\nimport os\nfrom sqlalchemy import create_engine, Column, Integer, String, MetaData, Table\n\n# Create a dummy SQLite database in memory\ndb_url = 'sqlite:///test.db'\nengine = create_engine(db_url)\nmetadata = MetaData()\n\n# Define a simple table\ntable_name = 'users'\nusers_table = Table(\n    table_name,\n    metadata,\n    Column('id', Integer, primary_key=True),\n    Column('name', String(50), nullable=False),\n    Column('email', String(100), unique=True)\n)\n\n# Create the table in the database\nmetadata.create_all(engine)\n\n# Run sqlacodegen as a subprocess\n# For demonstration, we'll print to stdout. Use --outfile to save to a file.\ntry:\n    result = subprocess.run(\n        ['sqlacodegen', db_url],\n        capture_output=True,\n        text=True,\n        check=True\n    )\n    print(\"\\n--- Generated SQLAlchemy Models ---\")\n    print(result.stdout)\n    print(\"-----------------------------------\")\nexcept subprocess.CalledProcessError as e:\n    print(f\"Error running sqlacodegen: {e}\\nStdout: {e.stdout}\\nStderr: {e.stderr}\")\nexcept FileNotFoundError:\n    print(\"Error: sqlacodegen command not found. Please ensure it's installed and in your PATH.\")\nfinally:\n    # Clean up the dummy database file\n    if os.path.exists('test.db'):\n        os.remove('test.db')\n","lang":"python","description":"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."},"warnings":[{"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.","message":"Breaking 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).","severity":"breaking","affected_versions":"3.0.0 and later"},{"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.","message":"By 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.","severity":"gotcha","affected_versions":"All versions"},{"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.","message":"sqlacodegen 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.","severity":"gotcha","affected_versions":"All versions"},{"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.","message":"Generated 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.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-12T00:00:00.000Z","next_check":"2026-07-11T00:00:00.000Z"}