Skip to main content

sqlalchemy-pydantic-mapper library for mapping SQLAlchemy models to Pydantic

Project description

sqlalchemy-pydantic-mapper

sqlalchemy-pydantic-mapper simplifies converting SQLAlchemy instances (subclasses of sqlalchemy.orm.DeclarativeBase) into Pydantic models (pydantic.BaseModel).

It supports:

  • registering custom synchronous and asynchronous mappers;
  • registration via decorator or by passing func= directly;
  • automatic mapping via Pydantic if the model has model_config = ConfigDict(from_attributes=True);
  • map(...) — an async method returning the target Pydantic model instance (must await it).

Usage Examples (Full Code Snippets)

  1. Simple registration via func= and checking _mappers:
from sqlalchemy_pydantic_mapper import ObjectMapper

def mapper(db: UserDB) -> UserSchema:
    return UserSchema(id=db.id, name=db.name)

ObjectMapper.register(UserDB, UserSchema, func=mapper)
assert ObjectMapper._mappers[UserDB][UserSchema] is mapper
  1. Registration via decorator:
@ObjectMapper.register(UserDB, UserSchema)
def mapper2(db: UserDB) -> UserSchema:
    return UserSchema(id=db.id, name=db.name)
  1. Async mapper (registration + usage):
@ObjectMapper.register(UserDB, UserSchema)
async def async_mapper(db: UserDB) -> UserSchema:
    # e.g., async call or await something
    return UserSchema(id=db.id, name=db.name.upper())

import asyncio

async def main():
    user = UserDB()
    user.id = 1
    user.name = "alice"
    res = await ObjectMapper.map(user, UserSchema)
    print(res)  # UserSchema(id=1, name='ALICE')

asyncio.run(main())
  1. Auto-mapping via Pydantic (from_attributes=True):
class UserSchema(BaseModel):
    model_config = ConfigDict(from_attributes=True)
    id: int
    name: str

If no custom mapper is registered for the from_class -> to_class pair, ObjectMapper.map(instance, UserSchema) automatically calls:

UserSchema.model_validate(instance, from_attributes=True)
  1. Example in a test (synthetic):
async def test_auto_mapping():
    stud = StudentDB()
    stud.id = 2
    stud.name = "Bob"

    result = await ObjectMapper.map(stud, UserSchema)
    assert result.id == 2
    assert result.name == "Bob"
  1. Example for manual mapping (different names / logic):
def stud_to_studschema(db: StudentDB) -> StudSchema:
    return StudSchema(id=db.id, name=db.name)

ObjectMapper.register(StudentDB, StudSchema, func=stud_to_studschema)

Errors and Behavior on Incorrect Usage

  • TypeError if from_ does not inherit DeclarativeBase:
class NotABase: pass
ObjectMapper.register(NotABase, UserSchema)  # -> TypeError
  • TypeError if to_ does not inherit BaseModel:
class NotABaseModel: pass
ObjectMapper.register(UserDB, NotABaseModel)  # -> TypeError
  • ValueError if func is missing and to_ does not have model_config = ConfigDict(from_attributes=True):
class BadSchema(BaseModel):
    id: int
    name: str

ObjectMapper.register(UserDB, BadSchema)  # -> ValueError

Project details


Download files

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

Source Distribution

sqlalchemy_pydantic_mapper-0.2.0.tar.gz (7.4 kB view details)

Uploaded Source

Built Distribution

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

sqlalchemy_pydantic_mapper-0.2.0-py3-none-any.whl (6.1 kB view details)

Uploaded Python 3

File details

Details for the file sqlalchemy_pydantic_mapper-0.2.0.tar.gz.

File metadata

File hashes

Hashes for sqlalchemy_pydantic_mapper-0.2.0.tar.gz
Algorithm Hash digest
SHA256 dc8e4c86f375734beb91b053f6482c9ec23d19aa9236858dc72aea8e597068cb
MD5 8255690437b122221fd2aef8951c9d20
BLAKE2b-256 82e088d0e072d017a28b0609eea6d71a435967084fdb47e9f547a0aca83b5671

See more details on using hashes here.

Provenance

The following attestation bundles were made for sqlalchemy_pydantic_mapper-0.2.0.tar.gz:

Publisher: publish.yml on ItzSkyReed/sqlalchemy-pydantic-mapper

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file sqlalchemy_pydantic_mapper-0.2.0-py3-none-any.whl.

File metadata

File hashes

Hashes for sqlalchemy_pydantic_mapper-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 1395e073e8f1a00cfad6bbc69eed9d8004f5234f98e508ac9ea8d55394e409b5
MD5 9bee16c8986f81384297e7180e5a570d
BLAKE2b-256 991d47d04156b29cf811ec9e40978392e19c48c9ddce1155c955523dd9261b7b

See more details on using hashes here.

Provenance

The following attestation bundles were made for sqlalchemy_pydantic_mapper-0.2.0-py3-none-any.whl:

Publisher: publish.yml on ItzSkyReed/sqlalchemy-pydantic-mapper

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page