erd.sketch

SQL 转 SQLAlchemy:从 DDL 脚本生成模型

下面不是示意图:这是生成器对左边脚本的真实输出。在编辑器里点「Codegen → SQLAlchemy」得到的就是同一份代码。

输入schema.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
);
输出models.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()
打开编辑器

脚本留在浏览器里:解析和生成都在您的机器上进行,不会上传到服务器。

类型如何对应

在 SQL 里在模型里
BIGINTBigInteger
VARCHAR(255)String(255)
BOOLEANBoolean
TIMESTAMPDateTime
DECIMAL(12,2)Numeric
TEXTText
可空字段
Mapped[str | None]
列名
full_name
关系
ForeignKey("users.id")