{"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":"python","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":[{"wrong":"from sqlacodegen import CodeGenerator","symbol":"CodeGenerator","correct":"import sqlacodegen"}],"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,"search_vec":"'2.0':37 '4.0.3':42 'automat':12 'cli':56 'code':2,16,52 'column':25 'command':8 'command-lin':7 'current':39 'databas':20,54 'evolv':49 'exist':19 'file':31 'generat':3,13,53 'introspect':23 'line':9 'model':15 'orm':51 'produc':29 'python':30 'readi':32 'receiv':45 'relationship':28 'schema':21 'sqlacodegen':4 'sqlalchemi':1,14,36,48,50 'tabl':24 'tool':10,55 'type':26 'updat':46 'use':34 'version':40","created_at":"2026-04-12T08:53:55.852838+00:00","updated_at":"2026-04-17T14:59:08.734927+00:00","problems":null,"ecosystem":"pypi","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":"4.0.4","cli_name":"sqlacodegen","cli_version":"4.0.3","type":"library","homepage":null,"github":"https://github.com/agronholm/sqlacodegen","docs":null,"changelog":null,"pypi":"https://pypi.org/project/sqlacodegen/","npm":null,"openapi_spec":null,"status_page":null,"smithery":null,"categories":["database","serialization"],"base_url":null,"auth_type":null,"provenance":{"verified_status":"passing","verified_at":"2026-07-03","last_verified":"2026-08-29","next_check":"2026-08-02","install_tag":null}}