Skip to main content

PSQL TO MODELS

Use regex patterns to match PostgreSQL schemas and output SQLAlchemy and Pydantic Models.

Designed for FastAPI.

Install

Requires Python 3.10.

git clone git@github.com:AlbertoV5/psql-to-models.git
cd psql-to-models

Install in editable mode.

pip install -e .

Usage

python -m psql-to-models -i ./example/schema.sql -a ./example/models_alchemy.py -p ./example/models_pydantic.py

Before.

schema.sql

After.

models_alchemy.py	schema.sql
models_pydantic.py

Results Example

SQL Input

DROP TABLE IF EXISTS DATETIMEEVENTS CASCADE;
CREATE TABLE DATETIMEEVENTS
(
  ROW_ID INT NOT NULL,
	SUBJECT_ID INT NOT NULL,
	HADM_ID INT,
	ICUSTAY_ID INT,
	ITEMID INT NOT NULL,
	CHARTTIME TIMESTAMP(0) NOT NULL,
	STORETIME TIMESTAMP(0) NOT NULL,
	CGID INT NOT NULL,
	VALUE TIMESTAMP(0),
	VALUEUOM VARCHAR(50) NOT NULL,
	WARNING SMALLINT,
	ERROR SMALLINT,
	RESULTSTATUS VARCHAR(50),
	STOPPED VARCHAR(50),
	CONSTRAINT datetime_rowid_pk PRIMARY KEY (ROW_ID)
) ;

DROP TABLE IF EXISTS DIAGNOSES_ICD CASCADE;
CREATE TABLE DIAGNOSES_ICD
(
  ROW_ID INT NOT NULL,
	SUBJECT_ID INT NOT NULL,
	HADM_ID INT NOT NULL,
	SEQ_NUM INT,
	ICD9_CODE VARCHAR(10),
	CONSTRAINT diagnosesicd_rowid_pk PRIMARY KEY (ROW_ID)
) ;

SQLALchemy Output

class Datetimeevents(Base):

    __tablename__ = "datetimeevents"

    row_id = Column(Integer, nullable=False, primary_key=True)
    subject_id = Column(Integer, nullable=False)
    hadm_id = Column(Integer)
    icustay_id = Column(Integer)
    itemid = Column(Integer, nullable=False)
    charttime = Column(TIMESTAMP(0), nullable=False)
    storetime = Column(TIMESTAMP(0), nullable=False)
    cgid = Column(Integer, nullable=False)
    value = Column(TIMESTAMP(0))
    valueuom = Column(String(50), nullable=False)
    warning = Column(SmallInteger)
    error = Column(SmallInteger)
    resultstatus = Column(String(50))
    stopped = Column(String(50))


class Diagnoses_icd(Base):

    __tablename__ = "diagnoses_icd"

    row_id = Column(Integer, nullable=False, primary_key=True)
    subject_id = Column(Integer, nullable=False)
    hadm_id = Column(Integer, nullable=False)
    seq_num = Column(Integer)
    icd9_code = Column(String(10))

Pydantic Output

class Datetimeevents(BaseModel):

    row_id: int
    subject_id: int
    hadm_id: int | None
    icustay_id: int | None
    itemid: int
    charttime: datetime
    storetime: datetime
    cgid: int
    value: datetime | None
    valueuom: str
    warning: int | None
    error: int | None
    resultstatus: str | None
    stopped: str | None

    class Config:
        orm_mode = True


class Diagnoses_icd(BaseModel):

    row_id: int
    subject_id: int
    hadm_id: int
    seq_num: int | None
    icd9_code: str | None

    class Config:
        orm_mode = True

Supported Queries

CREATE TABLE *
NOT NULL
CONSTRAINT UNIQUE
CONSTRAINT PRIMARY KEY

Constants

Make sure to edit the header constants under __ main __.py

ALCHEMY_HEADER = '''"""
SQLAlchemy Models
"""
from sqlalchemy import Column, Integer, String, CHAR, TIMESTAMP, SmallInteger
from sqlalchemy.dialects.postgresql import DOUBLE_PRECISION
from db.setup import Base

'''

You can always extend the supported types by editing the TYPE_LOOKUP dict in the types.py file.

TYPE_LOOKUP: dict[str, tuple[str, str]] = {
    "INT": ("Integer", "int"),
    "SMALLINT": ("SmallInteger", "int"),
    "VARCHAR": ("String", "str"),
    "TIMESTAMP": ("TIMESTAMP", "datetime"),
    "DOUBLE": ("DOUBLE_PRECISION", "float"),
    "CHAR": ("CHAR", "str"),
    "TEXT": ("String", "str"),
}
"""Values are tuples of SQLAlchemy Model Type and Pydantic/Python Type."""

Notes

  • This utility is meant to be modified to match every case that's why the installation is in editable mode.
  • The __ main __ .py file contains all the necessary logic and header configs.
  • The types.py file contains a lookup table for the postgresql -> models type lookup.
  • The header assumes a path for the SQLAlchemy Base so make sure to change it to match yours, etc.

Plans

  • A more robust tool can be created which uses .toml files (or whatever) for configuration instead of python files so there is no need for editable installation.
  • The applications are Postgresql schemas with FastAPI but the tool can be generalized even further to support different types for other RDMS and frameworks.
  • I'll add support for more queries as I find them in my day-to-day work but feel free to contribute!

Changelog

  • 0.1.2 - added ForeignKey Support
  • 0.1.1 - added REAL -> Float support
  • 0.1.0 - initial release

Metadata

Release files for psql-to-models 0.1.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for psql-to-models 0.1.2
File Size Uploaded
psql_to_models-0.1.2.tar.gz 6.7 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for psql-to-models 0.1.2
File Interpreter ABI Platform
psql_to_models-0.1.2-py3-none-any.whl Python 3 none any Details

Total release size: 14.1 kB

Release files / psql_to_models-0.1.2.tar.gz

Download URL psql_to_models-0.1.2.tar.gz
Size 6.7 kB
Tags Source
SHA-256 checksum
How to use checksums
cc5c2da94e92cd9902d72279d6759e5c68df4111c2bc87ccd1ea1763cd3d53d3
BLAKE2b-256 checksum
How to use checksums
ca71f31418947ab6bf8616e097eca4e7fbbf9b069d5e3ca52623ed1da98666d1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.2.2 CPython/3.10.8 Darwin/19.6.0

Release files / psql_to_models-0.1.2-py3-none-any.whl

Download URL psql_to_models-0.1.2-py3-none-any.whl
Size 7.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
91fec2d4c2bb1306dc3816aa507c7ccc10bd5098e8e24033291022f53017fc9b
BLAKE2b-256 checksum
How to use checksums
0081440b0676b2491f2243bcb882b3acd916b5214a2e85eb37f0a15dda3fe75b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.2.2 CPython/3.10.8 Darwin/19.6.0

Release history Release notifications | RSS feed

This release

0.1.2 This release

2 release files

0.1.1

2 release files

0.1.0

2 release 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