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에서 | 모델에서 |
|---|---|
BIGINT | BigInteger |
VARCHAR(255) | String(255) |
BOOLEAN | Boolean |
TIMESTAMP | DateTime |
DECIMAL(12,2) | Numeric |
TEXT | Text |
- 널 허용 필드
Mapped[str | None]- 컬럼 이름
full_name- 관계
ForeignKey("users.id")