erd.sketch

SQL to SQLAlchemy: models from a DDL script

What follows is not a mock-up: it is the real output of the generator for the script on the left. You get the same code in the editor under “Codegen → SQLAlchemy”.

The inputschema.sql
CREATE TABLE users (
    id BIGINT NOT NULL PRIMARY KEY,
    email       VARCHAR(255) NOT NULL UNIQUE,
    full_name   VARCHAR(120),
    is_active   BOOLEAN NOT NULL,
    created_at  TIMESTAMP NOT NULL
);

CREATE TABLE orders (
    id BIGINT NOT NULL PRIMARY KEY,
    user_id     BIGINT NOT NULL REFERENCES users(id),
    total       DECIMAL(12,2) NOT NULL,
    note        TEXT,
    placed_at   TIMESTAMP NOT NULL
);
What comes outmodels.py
from datetime import datetime
from sqlalchemy import BigInteger, Boolean, DateTime, ForeignKey, Numeric, String, Text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from decimal import Decimal

class Users(Base):
    __tablename__ = "users"

    id: Mapped[int] = mapped_column(BigInteger, primary_key=True, nullable=False)
    email: Mapped[str] = mapped_column(String(255), unique=True, nullable=False)
    full_name: Mapped[str | None] = mapped_column(String(120), nullable=True)
    is_active: Mapped[bool] = mapped_column(Boolean, nullable=False)
    created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)

class Orders(Base):
    __tablename__ = "orders"

    id: Mapped[int] = mapped_column(BigInteger, primary_key=True, nullable=False)
    user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
    total: Mapped[Decimal] = mapped_column(Numeric, nullable=False)
    note: Mapped[str | None] = mapped_column(Text, nullable=True)
    placed_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
    users: Mapped["Users"] = relationship()
Open the editor

The script stays in the browser: both parsing and generation run on your machine, nothing goes to a server.

How the types land

in SQLin the model
BIGINTBigInteger
VARCHAR(255)String(255)
BOOLEANBoolean
TIMESTAMPDateTime
DECIMAL(12,2)Numeric
TEXTText
Optional field
Mapped[str | None]
Column name
full_name
Relation
ForeignKey("users.id")