sqlathanor icon indicating copy to clipboard operation
sqlathanor copied to clipboard

Serialization with Mixins

Open digitalkaoz opened this issue 5 years ago • 3 comments

Currently it seems serialization with attributes defined in mixins wont work:

# mixin
from sqlalchemy import BigInteger
from sqlathanor import Column


class PrimaryMixin(object):
    """
    Mixin for adding a autoincrementing PK
    """

    id: int = Column(BigInteger, primary_key=True, autoincrement=True, supports_dict=True)
#concrete class
from sqlalchemy import UnicodeText, BigInteger, ForeignKey
from sqlathanor import Column, relationship

from model import deferred_reflection, base
from model.mixins.primary import PrimaryMixin


class Example(PrimaryMixin, base, deferred_reflection):
    """
    Example Table
    """
    __tablename__ = "example"

    name: str = Column(UnicodeText, comment="name", supports_dict=True)
#test case
class ExampleTestCase(unittest.TestCase):
    def test_serialize_to_dict(self):
        m = Example(name="Test", id=4711)

        self.assertEqual(m.to_dict(), {
            'id': 4711,
            'name': 'Test'
        })

what am i doing wrong here? The id is correctly filled and setup by SQLAlchemy itself, but the serialization definition isnt respected. i just followed the working/common https://docs.sqlalchemy.org/en/13/orm/extensions/declarative/mixins.html#mixing-in-columns to keep my models dry

digitalkaoz avatar Nov 06 '20 10:11 digitalkaoz

Sorry you're running into this, @digitalkaoz ! Thanks for providing the example code and the test case - I'll run some tests and see what's happening here. This should work properly, I would expect, so it's likely a bug somewhere causing an issue. With luck, I'll be able to debug it over this weekend and if necessary do a new release with a bug fix.

insightindustry avatar Nov 06 '20 12:11 insightindustry

Yeah, No worries! Thanks for your awesome piece of software :) i tried all kinds of (de)serialization libraries and found yours the best. It could be a little more performant in large entities / list, but maybe i have time to dig into this

digitalkaoz avatar Nov 06 '20 13:11 digitalkaoz

@insightindustry it works like this:

class PrimaryMixin(object):

    @declared_attr
    def id(cls):
        return Column(BigInteger, primary_key=True, autoincrement=True, **serialize)

but the original approach seems a bit clearer to me, so i still suggest its a bug

digitalkaoz avatar Nov 10 '20 15:11 digitalkaoz