marshmallow-sqlalchemy icon indicating copy to clipboard operation
marshmallow-sqlalchemy copied to clipboard

Question: using SQL Expression Language table definitions

Open meshantz opened this issue 5 years ago • 2 comments

Is this a sane pattern to follow to make use of SQLAlchemyAutoSchema with a non-orm (SQL Expression Language) table definition?

from sqlalchemy import Table, Column, Integer, String, MetaData
from sqlalchemy.orm import mapper
from marshmallow_sqlalchemy import SQLAlchemyAutoSchema

meta = MetaData()

example_table = Table('example', meta,
    Column('id', Integer, primary_key=True),
    Column('some_field', String),
)

def make_orm(table):
    class TableRedef:
        pass

    mapped = mapper(TableRedef, table)
    TableRedef.__mapper__ = mapped

    return TableRedef

class ExampleSchema(SQLAlchemyAutoSchema):
    class Meta:
        model = make_orm(example_table)

If there's a better pattern, please let me know. If this is good, I can make a PR to include it in the examples documentation.

meshantz avatar Nov 24 '20 22:11 meshantz

Hey, I'm not a maintainer but only came across your question today, I know it's a bit of a late response!

There isn't any prose section of the docs that addresses this but in the api reference for SQLAlchemyAutoSchema this example exists:

from marshmallow_sqlalchemy import SQLAlchemyAutoSchema, auto_field

from mymodels import User

class UserSchema(SQLAlchemyAutoSchema):
    class Meta:
        model = User
        # OR
        # table = User.__table__

    created_at = auto_field(dump_only=True)

Notice the commented out part table = User.__table__, which looks to me like you could do this:

class ExampleSchema(SQLAlchemyAutoSchema):
    class Meta:
        table = example_table

...I haven't tested it but if that didn't work it would be a bug IMO.

Support for generating schemas directly from tables comes from here:

https://github.com/marshmallow-code/marshmallow-sqlalchemy/blob/36c403f9b5dfaee7d04e222cc362ce7a52facb29/src/marshmallow_sqlalchemy/convert.py#L116-L141

peterschutt avatar Jan 10 '21 06:01 peterschutt

Better late than never! Thanks for the reply.

I'll have to take a look and see if that works. I'll follow up when I get the chance. If it does, it would be nice if it were more prominent in the docs.

meshantz avatar Jan 11 '21 19:01 meshantz