Python sqlalchemy.orm.class_mapper() Examples

The following are 30 code examples of sqlalchemy.orm.class_mapper(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sqlalchemy.orm , or try the search function .
Example #1
Source File: test_basic.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_plain(self):
        # control case
        class Base(object):
            pass

        class Sub(Base):
            pass

        mapper(Base, base)
        mapper(Sub, subtable, inherits=Base)

        # Sub gets a "base_id" property using the "base_id"
        # column of both tables.
        eq_(
            class_mapper(Sub).get_property("base_id").columns,
            [subtable.c.base_id, base.c.base_id],
        ) 
Example #2
Source File: test_sync.py    From sqlalchemy with MIT License 6 votes vote down vote up
def _fixture(self):
        A, B = self.classes.A, self.classes.B
        session = create_session()
        uowcommit = self._get_test_uow(session)
        a_mapper = class_mapper(A)
        b_mapper = class_mapper(B)
        self.a1 = a1 = A()
        self.b1 = b1 = B()
        uowcommit = self._get_test_uow(session)
        return (
            uowcommit,
            attributes.instance_state(a1),
            attributes.instance_state(b1),
            a_mapper,
            b_mapper,
        ) 
Example #3
Source File: test_mapper.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_attribute_error_raised_class_mapper(self):
        users = self.tables.users
        addresses = self.tables.addresses
        User = self.classes.User
        Address = self.classes.Address

        mapper(
            User,
            users,
            properties={
                "addresses": relationship(
                    Address,
                    primaryjoin=lambda: users.c.id == addresses.wrong.user_id,
                )
            },
        )
        mapper(Address, addresses)
        assert_raises_message(
            AttributeError,
            "'Table' object has no attribute 'wrong'",
            class_mapper,
            Address,
        ) 
Example #4
Source File: indicator.py    From bearded-avenger with Mozilla Public License 2.0 6 votes vote down vote up
def to_dict(self, obj):
        d = {}
        for col in class_mapper(obj.__class__).mapped_table.c:
            d[col.name] = getattr(obj, col.name)
            if d[col.name] and col.name.endswith('time'):
                d[col.name] = getattr(obj, col.name).strftime("%Y-%m-%dT%H:%M:%S.%fZ")

        try:
            d['tags'] = [t.tag for t in obj.tags]
        except AttributeError:
            pass

        try:
            d['message'] = [b64encode(m.message) for m in obj.messages]
        except AttributeError:
            pass

        return d 
Example #5
Source File: test_manytomany.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_get(self):
        class Foo(object):
            def __init__(self, data=None):
                self.data = data

        class Bar(Foo):
            pass

        mapper(Foo, foo)
        mapper(Bar, bar, inherits=Foo)
        print(foo.join(bar).primary_key)
        print(class_mapper(Bar).primary_key)
        b = Bar("somedata")
        sess = create_session()
        sess.add(b)
        sess.flush()
        sess.expunge_all()

        # test that "bar.bid" does not need to be referenced in a get
        # (ticket 185)
        assert sess.query(Bar).get(b.id).id == b.id 
Example #6
Source File: test_mapper.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_key_error_raised_class_mapper(self):
        users = self.tables.users
        addresses = self.tables.addresses
        User = self.classes.User
        Address = self.classes.Address

        mapper(
            User,
            users,
            properties={
                "addresses": relationship(
                    Address,
                    primaryjoin=lambda: users.c.id
                    == addresses.__dict__["wrong"].user_id,
                )
            },
        )
        mapper(Address, addresses)
        assert_raises_message(KeyError, "wrong", class_mapper, Address) 
Example #7
Source File: test_instrumentation.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_partially_mapped_inheritance(self):
        class A(object):
            pass

        class B(A):
            pass

        class C(B):
            def __init__(self, x):
                pass

        mapper(A, self.fixture())

        # B is not mapped in the current implementation
        assert_raises(sa.orm.exc.UnmappedClassError, class_mapper, B)

        # C is not mapped in the current implementation
        assert_raises(sa.orm.exc.UnmappedClassError, class_mapper, C) 
Example #8
Source File: test_mixin.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_mapper_args_declared_attr(self):
        class ComputedMapperArgs:
            @declared_attr
            def __mapper_args__(cls):
                if cls.__name__ == "Person":
                    return {"polymorphic_on": cls.discriminator}
                else:
                    return {"polymorphic_identity": cls.__name__}

        class Person(Base, ComputedMapperArgs):
            __tablename__ = "people"
            id = Column(Integer, primary_key=True)
            discriminator = Column("type", String(50))

        class Engineer(Person):
            pass

        configure_mappers()
        assert class_mapper(Person).polymorphic_on is Person.__table__.c.type
        eq_(class_mapper(Engineer).polymorphic_identity, "Engineer") 
Example #9
Source File: test_inheritance.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_subclass_mixin(self):
        class Person(Base, fixtures.ComparableEntity):

            __tablename__ = "people"
            id = Column("id", Integer, primary_key=True)
            name = Column("name", String(50))
            discriminator = Column("type", String(50))
            __mapper_args__ = {"polymorphic_on": discriminator}

        class MyMixin(object):

            pass

        class Engineer(MyMixin, Person):

            __tablename__ = "engineers"
            __mapper_args__ = {"polymorphic_identity": "engineer"}
            id = Column(
                "id", Integer, ForeignKey("people.id"), primary_key=True
            )
            primary_language = Column("primary_language", String(50))

        assert class_mapper(Engineer).inherits is class_mapper(Person) 
Example #10
Source File: test_inheritance.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_we_must_only_copy_column_mapper_args(self):
        class Person(Base):

            __tablename__ = "people"
            id = Column(Integer, primary_key=True)
            a = Column(Integer)
            b = Column(Integer)
            c = Column(Integer)
            d = Column(Integer)
            discriminator = Column("type", String(50))
            __mapper_args__ = {
                "polymorphic_on": discriminator,
                "polymorphic_identity": "person",
                "version_id_col": "a",
                "column_prefix": "bar",
                "include_properties": ["id", "a", "b"],
            }

        assert class_mapper(Person).version_id_col == "a"
        assert class_mapper(Person).include_properties == set(["id", "a", "b"]) 
Example #11
Source File: test_mixin.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_mapper_args_declared_attr_two(self):

        # same as test_mapper_args_declared_attr, but we repeat
        # ComputedMapperArgs on both classes for no apparent reason.

        class ComputedMapperArgs:
            @declared_attr
            def __mapper_args__(cls):
                if cls.__name__ == "Person":
                    return {"polymorphic_on": cls.discriminator}
                else:
                    return {"polymorphic_identity": cls.__name__}

        class Person(Base, ComputedMapperArgs):

            __tablename__ = "people"
            id = Column(Integer, primary_key=True)
            discriminator = Column("type", String(50))

        class Engineer(Person, ComputedMapperArgs):
            pass

        configure_mappers()
        assert class_mapper(Person).polymorphic_on is Person.__table__.c.type
        eq_(class_mapper(Engineer).polymorphic_identity, "Engineer") 
Example #12
Source File: test_mixin.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_single_table_no_propagation(self):
        class IdColumn:

            id = Column(Integer, primary_key=True)

        class Generic(Base, IdColumn):

            __tablename__ = "base"
            discriminator = Column("type", String(50))
            __mapper_args__ = dict(polymorphic_on=discriminator)
            value = Column(Integer())

        class Specific(Generic):

            __mapper_args__ = dict(polymorphic_identity="specific")

        assert Specific.__table__ is Generic.__table__
        eq_(list(Generic.__table__.c.keys()), ["id", "type", "value"])
        assert (
            class_mapper(Specific).polymorphic_on is Generic.__table__.c.type
        )
        eq_(class_mapper(Specific).polymorphic_identity, "specific") 
Example #13
Source File: domain.py    From codo-dns with GNU General Public License v3.0 5 votes vote down vote up
def model_to_dict(model):
    model_dict = {}
    for key, column in class_mapper(model.__class__).c.items():
        model_dict[column.name] = getattr(model, key, None)
    return model_dict 
Example #14
Source File: test_inspect.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_insp_aliased_column_prop(self):
        User = self.classes.User
        ua = aliased(User)
        prop = inspect(ua.name)
        is_(prop, ua.name)

        is_(prop.property.parent.mapper, class_mapper(User))
        assert not hasattr(prop.property, "mapper")
        is_(prop.parent.entity, ua)
        is_(prop.parent.class_, User)
        is_(prop._parentmapper, class_mapper(User))

        assert not hasattr(prop, "mapper")

        is_(prop._parententity, inspect(ua)) 
Example #15
Source File: spatialtoolz.py    From spandex with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def geom_duplicate(table):
    """
    Return DataFrame with all records that have identical, stacked geometry.

    Parameters
    ----------
    table : sqlalchemy.ext.declarative.DeclarativeMeta
        Table ORM class to diagnose.

    Returns
    -------
    df : pandas.DataFrame

    """
    # Create table aliases to cross join table to self.
    table_a = aliased(table)
    table_b = aliased(table)

    # Get primary key of table and table aliases.
    pk = class_mapper(table).primary_key[0]
    table_a_pk = getattr(table_a, pk.name)
    table_b_pk = getattr(table_b, pk.name)

    # Query rows with duplicate geometries.
    with db.session() as sess:
        dups = sess.query(
            table_a_pk.label('a'), table_b_pk.label('b')
        ).filter(
            table_a_pk < table_b_pk,
            func.ST_Equals(table_a.geom, table_b.geom)
        )
        rows = sess.query(table).filter(
            or_(
                pk.in_(dups.selectable.with_only_columns([table_a_pk])),
                pk.in_(dups.selectable.with_only_columns([table_b_pk]))
            )
        )

    # Convert query to DataFrame.
    df = io.db_to_df(rows)
    return df 
Example #16
Source File: token.py    From bearded-avenger with Mozilla Public License 2.0 5 votes vote down vote up
def to_dict(self, obj):
        d = {}
        for col in class_mapper(obj.__class__).mapped_table.c:
            d[col.name] = getattr(obj, col.name)

        try:
            d['groups'] = [g.group for g in obj.groups]
        except AttributeError:
            pass

        return d 
Example #17
Source File: kerrigan.py    From kerrigan with GNU General Public License v3.0 5 votes vote down vote up
def model_to_dict(model):
    model_dict = {}
    for key, column in class_mapper(model.__class__).c.items():
        model_dict[column.name] = getattr(model, key, None)
    return model_dict 
Example #18
Source File: test_serializer.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_mapper(self):
        user_mapper = class_mapper(User)
        assert (
            serializer.loads(serializer.dumps(user_mapper, -1), None, None)
            is user_mapper
        ) 
Example #19
Source File: test_basic.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_string_dependency_resolution_schemas(self):
        Base = decl.declarative_base()

        class User(Base):

            __tablename__ = "users"
            __table_args__ = {"schema": "fooschema"}

            id = Column(Integer, primary_key=True)
            name = Column(String(50))
            props = relationship(
                "Prop",
                secondary="fooschema.user_to_prop",
                primaryjoin="User.id==fooschema.user_to_prop.c.user_id",
                secondaryjoin="fooschema.user_to_prop.c.prop_id==Prop.id",
                backref="users",
            )

        class Prop(Base):

            __tablename__ = "props"
            __table_args__ = {"schema": "fooschema"}

            id = Column(Integer, primary_key=True)
            name = Column(String(50))

        user_to_prop = Table(
            "user_to_prop",
            Base.metadata,
            Column("user_id", Integer, ForeignKey("fooschema.users.id")),
            Column("prop_id", Integer, ForeignKey("fooschema.props.id")),
            schema="fooschema",
        )
        configure_mappers()

        assert (
            class_mapper(User).get_property("props").secondary is user_to_prop
        ) 
Example #20
Source File: test_basic.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_cant_add_columns(self):
        t = Table(
            "t",
            Base.metadata,
            Column("id", Integer, primary_key=True),
            Column("data", String),
        )

        def go():
            class User(Base):
                __table__ = t
                foo = Column(Integer, primary_key=True)

        # can't specify new columns not already in the table

        assert_raises_message(
            sa.exc.ArgumentError,
            "Can't add additional column 'foo' when " "specifying __table__",
            go,
        )

        # regular re-mapping works tho

        class Bar(Base):
            __table__ = t
            some_data = t.c.data

        assert (
            class_mapper(Bar).get_property("some_data").columns[0] is t.c.data
        ) 
Example #21
Source File: test_basic.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_string_dependency_resolution_tables(self):
        class User(Base, fixtures.ComparableEntity):

            __tablename__ = "users"
            id = Column(Integer, primary_key=True)
            name = Column(String(50))
            props = relationship(
                "Prop",
                secondary="user_to_prop",
                primaryjoin="User.id==user_to_prop.c.u" "ser_id",
                secondaryjoin="user_to_prop.c.prop_id=" "=Prop.id",
                backref="users",
            )

        class Prop(Base, fixtures.ComparableEntity):

            __tablename__ = "props"
            id = Column(Integer, primary_key=True)
            name = Column(String(50))

        user_to_prop = Table(
            "user_to_prop",
            Base.metadata,
            Column("user_id", Integer, ForeignKey("users.id")),
            Column("prop_id", Integer, ForeignKey("props.id")),
        )

        configure_mappers()
        assert (
            class_mapper(User).get_property("props").secondary is user_to_prop
        ) 
Example #22
Source File: cron.py    From codo-cron with GNU General Public License v3.0 5 votes vote down vote up
def model_to_dict(model):
    model_dict = {}
    for key, column in class_mapper(model.__class__).c.items():
        model_dict[column.name] = getattr(model, key, None)
    return model_dict 
Example #23
Source File: test_inheritance.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_intermediate_unmapped_class_on_classical(self):
        class Person(object):
            pass

        person_table = Table(
            "people",
            Base.metadata,
            Column("id", Integer, primary_key=True),
            Column("kind", String(50)),
        )

        mapper(
            Person,
            person_table,
            polymorphic_on="kind",
            polymorphic_identity="person",
        )

        class SpecialPerson(Person):
            pass

        class Manager(SpecialPerson, Base):
            __tablename__ = "managers"
            id = Column(Integer, ForeignKey(Person.id), primary_key=True)
            __mapper_args__ = {"polymorphic_identity": "manager"}

        from sqlalchemy import inspect

        assert inspect(Manager).inherits is inspect(Person)

        eq_(set(class_mapper(Person).class_manager), {"id", "kind"})
        eq_(set(class_mapper(Manager).class_manager), {"id", "kind"}) 
Example #24
Source File: __init__.py    From jbox with MIT License 5 votes vote down vote up
def __get__(self, obj, type):
        try:
            mapper = orm.class_mapper(type)
            if mapper:
                return type.query_class(mapper, session=self.sa.session())
        except UnmappedClassError:
            return None 
Example #25
Source File: test_inspect.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_insp_column_prop(self):
        User = self.classes.User
        prop = inspect(User.name)
        is_(prop, User.name)

        is_(prop.parent, class_mapper(User))
        assert not hasattr(prop, "mapper") 
Example #26
Source File: test_inspect.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_insp_aliased_relationship_prop(self):
        User = self.classes.User
        Address = self.classes.Address
        ua = aliased(User)
        prop = inspect(ua.addresses)
        is_(prop, ua.addresses)

        is_(prop.property.parent.mapper, class_mapper(User))
        is_(prop.property.mapper, class_mapper(Address))
        is_(prop.parent.entity, ua)
        is_(prop.parent.class_, User)
        is_(prop._parentmapper, class_mapper(User))
        is_(prop.mapper, class_mapper(Address))

        is_(prop._parententity, inspect(ua)) 
Example #27
Source File: test_inspect.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_insp_relationship_prop(self):
        User = self.classes.User
        Address = self.classes.Address
        prop = inspect(User.addresses)
        is_(prop, User.addresses)
        is_(prop.parent, class_mapper(User))
        is_(prop._parentmapper, class_mapper(User))
        is_(prop.mapper, class_mapper(Address)) 
Example #28
Source File: test_inspect.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_property(self):
        User = self.classes.User
        insp = inspect(User)
        is_(insp.attrs.id, class_mapper(User).get_property("id")) 
Example #29
Source File: test_mapper.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_unmapped_not_type_error_iter_ok(self):
        assert_raises_message(
            sa.exc.ArgumentError,
            r"Class object expected, got '\(5, 6\)'.",
            class_mapper,
            (5, 6),
        ) 
Example #30
Source File: test_assorted_poly.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_parent_refs_descendant(self):
        Person, Manager = self.classes("Person", "Manager")

        mapper(
            Person,
            people,
            properties={
                "manager": relationship(
                    Manager,
                    primaryjoin=(people.c.manager_id == managers.c.person_id),
                    uselist=False,
                    post_update=True,
                )
            },
        )
        mapper(
            Manager,
            managers,
            inherits=Person,
            inherit_condition=people.c.person_id == managers.c.person_id,
        )

        eq_(
            class_mapper(Person).get_property("manager").synchronize_pairs,
            [(managers.c.person_id, people.c.manager_id)],
        )

        session = create_session()
        p = Person(name="some person")
        m = Manager(name="some manager")
        p.manager = m
        session.add(p)
        session.flush()
        session.expunge_all()

        p = session.query(Person).get(p.person_id)
        m = session.query(Manager).get(m.person_id)
        assert p.manager is m