SQLAlchemy Code Generator

4.0.3 · active · verified Sun Apr 12

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.

Warnings

Install

Imports

Quickstart

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

view raw JSON →