Skip to main content

sqlmodelgen

Coverage badge PyPI version

sqlmodelgen is a library to generate models for the sqlmodel library (repo, official docs).

It accepts in input the following sources:

  • direct CREATE TABLE sql statements
  • sqlite file path
  • postgres connection string
  • mysql connection from the mysql-connector-python library

Installation

Available on PyPi, just run pip install sqlmodelgen

Code generation from Postgres requires the separate postgres extension, installable with pip install sqlmodelgen[postgres], while code generation from MySQL requires the separate mysql extension, installable with pip install sqlmodelgen[mysql]

Usage

sqlmodelgen can be used both as a command line tool and as a library providing functions that can be invoked in python.

Generating from CREATE TABLE

from sqlmodelgen import gen_code_from_sql

sql_code = '''
CREATE TABLE Hero (
	id INTEGER NOT NULL, 
	name VARCHAR NOT NULL, 
	secret_name VARCHAR NOT NULL, 
	age INTEGER, 
	PRIMARY KEY (id)
);
'''
print(gen_code_from_sql(sql_code))

generates:

from sqlmodel import SQLModel, Field

class Hero(SQLModel, table = True):
    __tablename__ = 'Hero'
    id: int = Field(primary_key=True)
    name: str
    secret_name: str
    age: int | None

Generating from SQLite

from sqlmodelgen import gen_code_from_sqlite

code = gen_code_from_sqlite('/home/my_user/my_database.sqlite')

Generating from Postgres

The separate postgres extension is required, it can be installed with pip install sqlmodelgen[postgres].

from sqlmodelgen import gen_code_from_postgres

code = gen_code_from_postgres('postgres://USER:PASSWORD@HOST:PORT/DBNAME')

Generating from MYSQL

The separate mysql extension is required, it can be installed with pip install sqlmodelgen[mysql].

import mysql.connector
from sqlmodelgen import gen_code_from_mysql

# instantiate your connection
conn = mysql.connector.connect(host='YOURHOST', port=3306, user='YOURUSER', password='YOURPASSWORD')

code = gen_code_from_mysql(conn, 'YOURDBNAME')

Relationships

sqlmodelgen allows to build relationships by passing the argument generate_relationships=True to the functions:

  • gen_code_from_sql
  • gen_code_from_sqlite
  • gen_code_from_postgres
  • gen_code_from_mysql

In such case sqlmodelgen is going to generate relationships between classes based on the foreign keys retrieved. The following example

schema = '''CREATE TABLE nations(
    id BIGSERIAL PRIMARY KEY,
    name TEXT NOT NULL
);

CREATE TABLE athletes(
    id BIGSERIAL PRIMARY KEY,
    name TEXT NOT NULL,
    nation_id BIGSERIAL,
    FOREIGN KEY (nation_id) REFERENCES nations(id)
);'''

sqlmodel_code = gen_code_from_sql(schema, generate_relationships=True)

will generate:

from sqlmodel import SQLModel, Field, Relationship

class Nations(SQLModel, table = True):
    __tablename__ = 'nations'

    id: int | None = Field(primary_key=True)
    name: str
    athletess: list['Athletes'] = Relationship(back_populates='nation')
                                                                             
class Athletes(SQLModel, table = True):
    __tablename__ = 'athletes'

    id: int | None = Field(primary_key=True)
    name: str
    nation_id: int | None = Field(foreign_key="nations.id")
    nation: Nations | None = Relationship(back_populates='athletess')

CLI usage

CLI usage is supported, for example one can invokem with:

sqlmodelgen -f /my/path/to/file.sql -o /my/path/to/output.py

help description for input arguments:

usage: sqlmodelgen [-h] (-f FILE | -s SQLITE | -p POSTGRES | -m MYSQL)
                   [-o OUTPUT] [-r] [--schema SCHEMA] [--dbname DBNAME]
                   [--no-header]

sqlmodel classes code generation

options:
  -h, --help            show this help message and exit
  -f, --file FILE       SQL file path
  -s, --sqlite SQLITE   SQLite database path
  -p, --postgres POSTGRES
                        PostgreSQL connection URL, requires postgres extension to be installed with "pip install
                        sqlmodelgen[postgres]"
  -m, --mysql MYSQL     MySQL connection URL, requires mysql extension to be installed with "pip install
                        sqlmodelgen[mysql]"
  -o, --output OUTPUT   Output file (default: stdout)
  -r, --relationships   Generate relationships
  --schema SCHEMA       PostgreSQL schema (default: public)
  --dbname DBNAME       MySQL database name (required with --mysql)
  --no-header            Don't include the `# Generated by: ` header in the output

Internal functioning

The library relies on sqloxide to parse SQL code, then generates sqlmodel classes accordingly.

Contributions

The project is small but contributions are really welcome. Feel free to post issues or provide PRs. In general it is preferred to provide PRs as "atomic" as possible, in order to ease reviews.

Contributors

Some people helped improve the tool in several ways:

  • matthaigh27 provided functionality for attributes with custom names and the usage of Any as a type.
  • s-weigand added useful types.
  • Zer0AlmostNull improved the documentation.
  • JoaquimEsteves set up script in the pyproject.toml and added a header for the code generated.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

sqlmodelgen-0.0.22.tar.gz (88.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

sqlmodelgen-0.0.22-py3-none-any.whl (25.2 kB view details)

Uploaded Python 3

File details

Details for the file sqlmodelgen-0.0.22.tar.gz.

File metadata

  • Download URL: sqlmodelgen-0.0.22.tar.gz
  • Upload date:
  • Size: 88.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.9 {"installer":{"name":"uv","version":"0.10.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Fedora Linux","version":"41","id":"","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for sqlmodelgen-0.0.22.tar.gz
Algorithm Hash digest
SHA256 cc67d8bc809c4b2c81acfff994336ef5dc0770a634faf60d9bf7b5873cbc2405
MD5 86d86d0062048bbb96a39d6b3e81e974
BLAKE2b-256 30ebae22a13d87d84b929a4f24fc3834210ea7f6a06a5987e54741ca0ad832af

See more details on using hashes here.

File details

Details for the file sqlmodelgen-0.0.22-py3-none-any.whl.

File metadata

  • Download URL: sqlmodelgen-0.0.22-py3-none-any.whl
  • Upload date:
  • Size: 25.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.9 {"installer":{"name":"uv","version":"0.10.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Fedora Linux","version":"41","id":"","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for sqlmodelgen-0.0.22-py3-none-any.whl
Algorithm Hash digest
SHA256 06a11d51feec491532310bafc55a2e4d6fd96daba1121435905a0a0c5cc5ad59
MD5 69925eb9d65e72a6fa70606c3d484b25
BLAKE2b-256 471efbcf076b12bb5920c01459a339bf21f734341ae30ea5bdb76efefe96b7bf

See more details on using hashes here.

Release history Release notifications | RSS feed

This release

0.0.22 This release

2 files

0.0.21

2 files

0.0.20

2 files

0.0.19

2 files

0.0.18

2 files

0.0.17

2 files

0.0.16

2 files

0.0.15

2 files

0.0.14

2 files

0.0.13

2 files

0.0.12

2 files

0.0.11

2 files

0.0.5

2 files

0.0.4

2 files

0.0.3

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page