SQL to SQLAlchemy models converter (PostgreSQL)

Convert SQL to SQLAlchemy 2.0: PostgreSQL CREATE TABLE statements, or a whole pg_dump, become declarative models (Mapped, mapped_column) with relationships, enums, indexes, CHECK constraints and your constraint names.

PostgreSQL

SQLAlchemy

Waiting for input

What you get

How each result is checked

  1. Your SQL is read by the real PostgreSQL parser, compiled to WebAssembly.
  2. The models are loaded with the real SQLAlchemy 2.1 in your browser (CPython in WebAssembly); every mapper and relationship must configure.
  3. SQLAlchemy is asked for the exact SQL it would run to create your database. That SQL is read with the PostgreSQL parser and compared with your input: every table, column type, NULL/NOT NULL, default, identity and generated column, primary key, unique constraint, foreign key (name, columns, ON DELETE/ON UPDATE), index (name, method, sort order, condition), CHECK constraint and enum.

What can't convert exactly

  • Tables without a primary key cannot be ORM classes; they are written as Table objects, as sqlacodegen does.
  • Types SQLAlchemy has no class for (point, int4range, ltree…) use a small SqlType class that keeps the exact database type.
  • Views, functions and triggers are not part of SQLAlchemy models and are listed as skipped.
  • The first run downloads Python and SQLAlchemy (about 6 MB compressed), once.

Questions

Is it the same as sqlacodegen?

It follows the same conventions (declarative classes, explicit constraint names, Table objects for tables without keys) and is checked by comparing the SQL SQLAlchemy would create with yours. The tests also run that SQL in a real Postgres and compare the resulting database.

Does create_all() rebuild my database?

Yes, that is what is tested: for every test schema, SQLAlchemy's CREATE statements build the same tables, keys, indexes, checks and defaults as the original SQL.

Can I turn relationships off?

Yes. Untick "Add relationship()" to get only the columns and constraints.

Can I generate SQLAlchemy models from an existing database without connecting to it?

Yes. Dump the schema with pg_dump --schema-only (or copy the CREATE TABLE statements) and paste it here. You get SQLAlchemy 2.0 declarative models from the existing database schema, checked by running SQLAlchemy in your browser.

How do I convert PostgreSQL to SQLAlchemy online?

Paste your PostgreSQL or open a file on the left (or click Example). The SQLAlchemy appears on the right as you type, already checked. Copy it, or download it as a file. Nothing is uploaded.

Can the SQLAlchemy output be wrong?

Every result is checked before it is shown (the checks are listed on this page). If a check fails, the page says "Review needed" and why, instead of presenting the output as correct, and anything that cannot convert exactly is named in the notes.