Sql To Sqlalchemy

SQL DDL to Python SQLAlchemy 2.0 Model Generator

Convert SQL CREATE TABLE statements into strongly-typed Python SQLAlchemy 2.0 DeclarativeBase models with Mapped annotations.

Presets:
Dialect:
Typing:
Inputpostgres
"""
SQLAlchemy 2.0 DeclarativeBase Models
Generated by ToolsAA SQL to SQLAlchemy Generator
Dialect: POSTGRES | Generated Tables: 6
"""

from typing import Any, List, Optional
import uuid
import enum

from sqlalchemy import (
    BigInteger,
    Boolean,
    Date,
    DateTime,
    Float,
    ForeignKey,
    Index,
    Integer,
    Numeric,
    SmallInteger,
    String,
    Text,
    Time,
    UniqueConstraint,
    func,
    text,
)
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship


class Base(DeclarativeBase):
    pass


class UserRole(str, enum.Enum):
    CUSTOMER = "CUSTOMER"
    ADMIN = "ADMIN"
    VENDOR = "VENDOR"


class OrderStatus(str, enum.Enum):
    PENDING = "PENDING"
    PAID = "PAID"
    PROCESSING = "PROCESSING"
    SHIPPED = "SHIPPED"
    DELIVERED = "DELIVERED"
    CANCELLED = "CANCELLED"


class User(Base):
    __tablename__ = "users"

    id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default="gen_random_uuid(")

    def __repr__(self) -> str:
        return f"<User(id={self.id!r})>"


class UserProfile(Base):
    __tablename__ = "user_profiles"

    id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default="gen_random_uuid(")

    def __repr__(self) -> str:
        return f"<UserProfile(id={self.id!r})>"


class Product(Base):
    __tablename__ = "products"

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    sku: Mapped[Optional[str]] = mapped_column(nullable=True)

    def __repr__(self) -> str:
        return f"<Product(id={self.id!r}, sku={self.sku!r})>"


class Order(Base):
    __tablename__ = "orders"

    __table_args__ = (
        Index("idx_orders_customer", "customer_id"),
    )

    id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default="gen_random_uuid(")

    # Relationships
    order_items: Mapped[List["OrderItem"]] = relationship(back_populates="order", cascade="all, delete-orphan")

    def __repr__(self) -> str:
        return f"<Order(id={self.id!r})>"


class OrderItem(Base):
    __tablename__ = "order_items"

    __table_args__ = (
        Index("idx_order_items_order", "order_id"),
    )

    id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
    order_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("orders.id"), nullable=False)

    # Relationships
    order: Mapped["Order"] = relationship(back_populates="order_items")

    def __repr__(self) -> str:
        return f"<OrderItem(id={self.id!r}, order_id={self.order_id!r})>"


class AuditLog(Base):
    __tablename__ = "audit_logs"

    id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
    action: Mapped[Optional[str]] = mapped_column(nullable=True)

    def __repr__(self) -> str:
        return f"<AuditLog(id={self.id!r}, action={self.action!r})>"
Tables Parsed6DeclarativeBase model entities
Mapped Attributes9Type-annotated mapped_column fields
Relational Foreign Keyspostgres
1Foreign keys and relationship links

Zero-Knowledge Local Execution

All data processing, parsing, and compilation execute strictly inside your local browser memory. Zero external server uploads.

Sub-Millisecond AST Engine

All data payloads remain strictly local with zero external server communication.

Production Ready Export

Clean, optimized output formats ready for immediate deployment.

Technical Reference & Architecture Guide

SQL DDL to Python SQLAlchemy 2.0 Model Generator — Reference Guide

Convert SQL CREATE TABLE statements into strongly-typed Python SQLAlchemy 2.0 DeclarativeBase models with modern Mapped and mapped_column annotations.

Key Parameters & Controls

SQL DialectEnum (postgresql | mysql | sqlite | mssql | oracle)

Target SQL dialect used to parse engine-specific types such as SERIAL, ENUM, JSONB, and UUID.

Default: postgresql
Annotation SyntaxEnum (mapped_column | legacy_column)

Generate modern SQLAlchemy 2.0 Mapped[T] type annotations or backward-compatible 1.4 Column() syntax.

Default: mapped_column
Nullable StyleEnum (union_pipe | optional)

Python type hinting for nullable fields: Python 3.10+ union pipe (Mapped[str | None]) or typing.Optional (Mapped[Optional[str]]).

Default: union_pipe
Generate RelationshipsBoolean (true | false)

Automatically detect foreign key constraints and construct bidirectional relationship() ORM properties.

Default: true
Base Class DeclarationString

Name of the parent declarative base class inheriting from SQLAlchemy 2.0 DeclarativeBase.

Default: Base

Pro Tips & Best Practices

Using modern Mapped[int]

Using modern Mapped[int] and mapped_column() provides full static typing support in Mypy, Pyright, and modern IDEs with zero plugins required.

Automatic Relationship Back-Populates

When parsing tables linked with FOREIGN KEY references, both the child ForeignKey and the parent back_populates relationship attributes are scaffolded automatically.

PostgreSQL JSONB and Array Support

PostgreSQL-specific types like JSONB, ARRAY, and UUID are mapped directly to sqlalchemy.dialects.postgresql types rather than generic fallbacks.

Alembic and FastAPI Schema Ready

Generated models export Base.metadata for immediate integration with Alembic migrations and Pydantic v2 from_attributes mode.

Common Gotchas & Troubleshooting

Parse errors on multi-line table constraints or triggers

Strip custom vendor triggers, stored procedures, or proprietary ALTER TABLE commands, retaining standard CREATE TABLE DDL syntax.

Composite primary keys marked incorrectly

Ensure composite keys defined at the bottom of the DDL (PRIMARY KEY (col1, col2)) are preserved; the parser assigns primary_key=True to all constituent mapped_column definitions.

Circular foreign key references in ORM relationships

Specify string-based target class names inside relationship('TargetModel') to allow Python runtime forward-reference evaluation.

Frequently Asked Questions

Does this generator support SQLAlchemy 2.0 syntax?▼

Yes. It defaults to SQLAlchemy 2.0 standard DeclarativeBase, Mapped[T], and mapped_column() syntax instead of legacy 1.x Column() definitions.

How are nullable and default column values handled?▼

Columns without NOT NULL constraints are wrapped in Mapped[T | None] with nullable=True. SQL DEFAULT expressions are translated into server_default or default parameters.

Is my SQL schema uploaded to an external server?▼

No. The entire SQL lexing, AST construction, and Python code generation runs 100% locally in your browser using pure client-side JavaScript.

Can I convert multiple CREATE TABLE statements at once?▼

Yes. You can paste an entire DDL schema file containing multiple tables; the generator resolves dependencies and orders model definitions accordingly.

How are database ENUM types converted?▼

Database ENUM types are automatically generated as standard Python Enum classes inheriting from enum.Enum alongside the SQLAlchemy Enum column mapping.

Related Tools & Utilities

All Tools →