def setup_mappers(cls):
        Account, Transaction, transactions, accounts, entries, Entry = (
            cls.classes.Account,
            cls.classes.Transaction,
            cls.tables.transactions,
            cls.tables.accounts,
            cls.tables.entries,
            cls.classes.Entry,
        )

        mapper(Account, accounts)

        mapper(Transaction, transactions)

        mapper(
            Entry,
            entries,
            properties=dict(
                account=relationship(
                    Account,
                    uselist=False,
                    backref=backref("entries",
                                    lazy="select",
                                    order_by=entries.c.entry_id),
                ),
                transaction=relationship(
                    Transaction,
                    uselist=False,
                    backref=backref("entries",
                                    lazy="joined",
                                    order_by=entries.c.entry_id),
                ),
            ),
        )
    def setup_mappers(cls):
        Right, Middle, middle, right, left, Left = (
            cls.classes.Right,
            cls.classes.Middle,
            cls.tables.middle,
            cls.tables.right,
            cls.tables.left,
            cls.classes.Left,
        )

        # set up bi-directional eager loads
        mapper(Left, left)
        mapper(Right, right)
        mapper(
            Middle,
            middle,
            properties=dict(
                left=relationship(
                    Left,
                    lazy="joined",
                    backref=backref("middle", lazy="joined"),
                ),
                right=relationship(
                    Right,
                    lazy="joined",
                    backref=backref("middle", lazy="joined"),
                ),
            ),
        ),
    def test_dynamic_on_backref(self):
        users, Address, addresses, User = (
            self.tables.users,
            self.classes.Address,
            self.tables.addresses,
            self.classes.User,
        )

        mapper(
            Address,
            addresses,
            properties={
                "user":
                relationship(User,
                             backref=backref("addresses", lazy="dynamic"))
            },
        )
        mapper(User, users)

        sess = create_session()
        ad = sess.query(Address).get(1)

        def go():
            ad.user = None

        self.assert_sql_count(testing.db, go, 0)
        sess.flush()
        u = sess.query(User).get(7)
        assert ad not in u.addresses
Esempio n. 4
0
    def setup_mappers(cls):
        Address, addresses, users, User = (
            cls.classes.Address,
            cls.tables.addresses,
            cls.tables.users,
            cls.classes.User,
        )

        mapper(Address, addresses)
        mapper(
            User,
            users,
            properties={
                "address":
                relationship(
                    Address,
                    uselist=False,
                    backref=backref(
                        "user",
                        single_parent=True,
                        cascade="all, delete-orphan",
                    ),
                )
            },
        )
    def test_four(self):
        """this tests the RasterDocument being attached to the Assembly, but
        *not* the Document.  this means only a "sub-class" task, i.e.
        corresponding to an inheriting mapper but not the base mapper,
        is created."""

        product_mapper = mapper(
            Product,
            products_table,
            polymorphic_on=products_table.c.product_type,
            polymorphic_identity="product",
        )
        mapper(Detail, inherits=product_mapper, polymorphic_identity="detail")
        mapper(Assembly,
               inherits=product_mapper,
               polymorphic_identity="assembly")

        document_mapper = mapper(
            Document,
            documents_table,
            polymorphic_on=documents_table.c.document_type,
            polymorphic_identity="document",
            properties=dict(
                name=documents_table.c.name,
                data=deferred(documents_table.c.data),
                product=relationship(
                    Product,
                    lazy="select",
                    backref=backref("documents", cascade="all, delete-orphan"),
                ),
            ),
        )
        mapper(
            RasterDocument,
            inherits=document_mapper,
            polymorphic_identity="raster_document",
        )

        session = create_session()

        a1 = Assembly(name="a1")
        a1.documents.append(RasterDocument("doc2"))
        session.add(a1)
        orig = repr(a1)
        session.flush()
        session.expunge_all()

        a1 = session.query(Product).filter_by(name="a1").one()
        new = repr(a1)
        print(orig)
        print(new)
        assert (orig == new == "<Assembly a1> specification=None documents="
                "[<RasterDocument doc2>]")

        del a1.documents[0]
        session.flush()
        session.expunge_all()

        a1 = session.query(Product).filter_by(name="a1").one()
        assert len(session.query(Document).all()) == 0
    def test_one(self):
        product_mapper = mapper(
            Product,
            products_table,
            polymorphic_on=products_table.c.product_type,
            polymorphic_identity="product",
        )

        mapper(Detail, inherits=product_mapper, polymorphic_identity="detail")

        mapper(Assembly,
               inherits=product_mapper,
               polymorphic_identity="assembly")

        mapper(
            SpecLine,
            specification_table,
            properties=dict(
                leader=relationship(
                    Assembly,
                    foreign_keys=[specification_table.c.leader_id],
                    primaryjoin=specification_table.c.leader_id ==
                    products_table.c.product_id,
                    lazy="select",
                    backref=backref("specification"),
                    uselist=False,
                ),
                follower=relationship(
                    Product,
                    foreign_keys=[specification_table.c.follower_id],
                    primaryjoin=specification_table.c.follower_id ==
                    products_table.c.product_id,
                    lazy="select",
                    uselist=False,
                ),
                quantity=specification_table.c.quantity,
            ),
        )

        session = create_session()

        a1 = Assembly(name="a1")

        p1 = Product(name="p1")
        a1.specification.append(SpecLine(follower=p1))

        d1 = Detail(name="d1")
        a1.specification.append(SpecLine(follower=d1))

        session.add(a1)
        orig = repr(a1)
        session.flush()
        session.expunge_all()

        a1 = session.query(Product).filter_by(name="a1").one()
        new = repr(a1)
        print(orig)
        print(new)
        assert (orig == new == "<Assembly a1> specification=[<SpecLine 1.0 "
                "<Product p1>>, <SpecLine 1.0 <Detail d1>>] documents=None")
    def test_one(self):
        (
            Part,
            inherited_part,
            design_types,
            DesignType,
            parts,
            design,
            Design,
            InheritedPart,
        ) = (
            self.classes.Part,
            self.tables.inherited_part,
            self.tables.design_types,
            self.classes.DesignType,
            self.tables.parts,
            self.tables.design,
            self.classes.Design,
            self.classes.InheritedPart,
        )

        p_m = mapper(Part, parts)

        mapper(
            InheritedPart,
            inherited_part,
            properties=dict(part=relationship(Part, lazy="joined")),
        )

        d_m = mapper(
            Design,
            design,
            properties=dict(inheritedParts=relationship(
                InheritedPart,
                cascade="all, delete-orphan",
                backref="design",
            )),
        )

        mapper(DesignType, design_types)

        d_m.add_property(
            "type", relationship(DesignType, lazy="joined", backref="designs"))

        p_m.add_property(
            "design",
            relationship(
                Design,
                lazy="joined",
                backref=backref("parts", cascade="all, delete-orphan"),
            ),
        )

        d = Design()
        sess = create_session()
        sess.add(d)
        sess.flush()
        sess.expunge_all()
        x = sess.query(Design).get(1)
        x.inheritedParts
        class Child(fixtures.ComparableEntity, Base):
            __tablename__ = "child"
            id = Column(Integer, primary_key=True)
            parent_id = Column(Integer, ForeignKey("parent.id"))
            parent = relationship("Parent", backref=backref("children"))

            type = Column(String(50), nullable=False)
            __mapper_args__ = {"polymorphic_on": type}
    def test_table_binds(self):
        Address, addresses, users, User = (
            self.classes.Address,
            self.tables.addresses,
            self.tables.users,
            self.classes.User,
        )

        # ensure tables are unbound
        m2 = sa.MetaData()
        users_unbound = users.tometadata(m2)
        addresses_unbound = addresses.tometadata(m2)

        mapper(Address, addresses_unbound)
        mapper(
            User,
            users_unbound,
            properties={
                "addresses":
                relationship(
                    Address,
                    backref=backref("user", cascade="all"),
                    cascade="all",
                )
            },
        )

        Session = sessionmaker(
            binds={
                users_unbound: self.metadata.bind,
                addresses_unbound: self.metadata.bind,
            })
        sess = Session()

        u1 = User(id=1, name="ed")
        sess.add(u1)
        eq_(
            sess.query(User).filter(User.id == 1).all(),
            [User(id=1, name="ed")],
        )

        sess.execute(users_unbound.insert(), params=dict(id=2, name="jack"))

        eq_(
            sess.execute(
                users_unbound.select(users_unbound.c.id == 2)).fetchall(),
            [(2, "jack")],
        )

        eq_(
            sess.execute(users_unbound.select(User.id == 2)).fetchall(),
            [(2, "jack")],
        )

        sess.execute(users_unbound.delete())
        eq_(sess.execute(users_unbound.select()).fetchall(), [])

        sess.close()
        class Other(fixtures.ComparableEntity, Base):
            __tablename__ = "other"

            id = Column(Integer, primary_key=True)
            child_subclass_id = Column(
                Integer, ForeignKey("child_subclass1.id")
            )
            child_subclass = relationship(
                "ChildSubclass1", backref=backref("others")
            )
    def test_backref_pop_persistent_autoflush_o2m_active_hist(self):
        u1, a1, s = self._persistent_fixture(
            addresses_args={"backref": backref("user", active_history=True)})
        u1.addresses.append(a1)
        s.flush()
        s.expire_all()

        a1.user = None

        self._assert_history(u1, ([], [], [a1]))
    def test_m2m(self):
        Order, Item = self._order_item_fixture(
            items_args={"backref": backref("orders", lazy="dynamic")})

        sess = create_session()
        o1 = Order(id=15, description="order 10")
        i1 = Item(id=10, description="item 8")
        o1.items.append(i1)
        sess.add(o1)
        sess.flush()

        assert o1 in i1.orders.all()
        assert i1 in o1.items.all()
Esempio n. 13
0
    def test_misc_one(self):
        metadata = MetaData(testing.db)
        node_table = Table(
            "node",
            metadata,
            Column("node_id", Integer, primary_key=True),
            Column("name_index", Integer, nullable=True),
        )
        node_name_table = Table(
            "node_name",
            metadata,
            Column("node_name_id", Integer, primary_key=True),
            Column("node_id", Integer, ForeignKey("node.node_id")),
            Column("host_id", Integer, ForeignKey("host.host_id")),
            Column("name", String(64), nullable=False),
        )
        host_table = Table(
            "host",
            metadata,
            Column("host_id", Integer, primary_key=True),
            Column("hostname", String(64), nullable=False, unique=True),
        )
        metadata.create_all()
        try:
            node_table.insert().execute(node_id=1, node_index=5)

            class Node(object):
                pass

            class NodeName(object):
                pass

            class Host(object):
                pass

            mapper(Node, node_table)
            mapper(Host, host_table)
            mapper(
                NodeName,
                node_name_table,
                properties={
                    "node": relationship(Node, backref=backref("names")),
                    "host": relationship(Host),
                },
            )
            sess = create_session()
            assert sess.query(Node).get(1).names == []
        finally:
            metadata.drop_all()
Esempio n. 14
0
    def setup_mappers(cls):
        Address, addresses, users, User = (
            cls.classes.Address,
            cls.tables.addresses,
            cls.tables.users,
            cls.classes.User,
        )

        mapper(Address, addresses)
        mapper(
            User,
            users,
            properties={
                "address":
                relationship(Address, backref=backref("user"), uselist=False)
            },
        )
Esempio n. 15
0
    def test_useget_cancels_eager_propagated_present(self):
        """test that a one to many lazyload cancels the unnecessary
        eager many-to-one join on the other side, even when a propagated
        option is present."""

        User = self.classes.User
        Address = self.classes.Address

        mapper(User, self.tables.users)
        mapper(
            Address,
            self.tables.addresses,
            properties={
                "user":
                relationship(
                    User,
                    lazy="joined",
                    backref=backref("addresses", lazy="baked_select"),
                )
            },
        )

        from sqlalchemy_1_3.orm.interfaces import MapperOption

        class MyBogusOption(MapperOption):
            propagate_to_loaders = True

        sess = Session()
        u1 = (sess.query(User).options(
            MyBogusOption()).filter(User.id == 8).one())

        def go():
            eq_(u1.addresses[0].user, u1)

        self.assert_sql_execution(
            testing.db,
            go,
            CompiledSQL(
                "SELECT addresses.id AS addresses_id, addresses.user_id AS "
                "addresses_user_id, addresses.email_address AS "
                "addresses_email_address FROM addresses WHERE :param_1 = "
                "addresses.user_id",
                {"param_1": 8},
            ),
        )
 def _bidirectional_onescalar_fixture(self):
     left, secondary, right = (
         self.tables.left,
         self.tables.secondary,
         self.tables.right,
     )
     A, B = self.classes.A, self.classes.B
     mapper(
         A,
         left,
         properties={
             "bs":
             relationship(
                 B,
                 secondary=secondary,
                 backref=backref("a", uselist=False),
                 order_by=right.c.id,
             )
         },
     )
     mapper(B, right)
Esempio n. 17
0
    def setup_mappers(cls):
        documents, Document, User, users = (
            cls.tables.documents,
            cls.classes.Document,
            cls.classes.User,
            cls.tables.users,
        )

        mapper(User, users)
        mapper(
            Document,
            documents,
            properties={
                "user":
                relationship(
                    User,
                    lazy="joined",
                    backref=backref("documents", lazy="select"),
                )
            },
        )
Esempio n. 18
0
    def test_useget_cancels_eager(self):
        """test that a one to many lazyload cancels the unnecessary
        eager many-to-one join on the other side."""

        User = self.classes.User
        Address = self.classes.Address

        mapper(User, self.tables.users)
        mapper(
            Address,
            self.tables.addresses,
            properties={
                "user":
                relationship(
                    User,
                    lazy="joined",
                    backref=backref("addresses", lazy="baked_select"),
                )
            },
        )

        sess = Session()
        u1 = sess.query(User).filter(User.id == 8).one()

        def go():
            eq_(u1.addresses[0].user, u1)

        self.assert_sql_execution(
            testing.db,
            go,
            CompiledSQL(
                "SELECT addresses.id AS addresses_id, addresses.user_id AS "
                "addresses_user_id, addresses.email_address AS "
                "addresses_email_address FROM addresses WHERE :param_1 = "
                "addresses.user_id",
                {"param_1": 8},
            ),
        )
Esempio n. 19
0
    def setup_mappers(cls):
        keywords, items, item_keywords, Keyword, Item = (
            cls.tables.keywords,
            cls.tables.items,
            cls.tables.item_keywords,
            cls.classes.Keyword,
            cls.classes.Item,
        )

        mapper(
            Item,
            items,
            properties={
                "keyword":
                relationship(
                    Keyword,
                    secondary=item_keywords,
                    uselist=False,
                    backref=backref("item", uselist=False),
                )
            },
        )
        mapper(Keyword, keywords)
    def _setup_mapping(self, use_unions, use_joins):
        (
            Publication,
            Issue,
            Location,
            LocationName,
            PageSize,
            Magazine,
            Page,
            MagazinePage,
            ClassifiedPage,
        ) = self.classes(
            "Publication",
            "Issue",
            "Location",
            "LocationName",
            "PageSize",
            "Magazine",
            "Page",
            "MagazinePage",
            "ClassifiedPage",
        )
        mapper(Publication, self.tables.publication)

        mapper(
            Issue,
            self.tables.issue,
            properties={
                "publication": relationship(
                    Publication,
                    backref=backref("issues", cascade="all, delete-orphan"),
                )
            },
        )

        mapper(LocationName, self.tables.location_name)

        mapper(
            Location,
            self.tables.location,
            properties={
                "issue": relationship(
                    Issue,
                    backref=backref(
                        "locations",
                        lazy="joined",
                        cascade="all, delete-orphan",
                    ),
                ),
                "name": relationship(LocationName),
            },
        )

        mapper(PageSize, self.tables.page_size)

        mapper(
            Magazine,
            self.tables.magazine,
            properties={
                "location": relationship(
                    Location, backref=backref("magazine", uselist=False)
                ),
                "size": relationship(PageSize),
            },
        )

        if use_unions:
            page_join = polymorphic_union(
                {
                    "m": self.tables.page.join(self.tables.magazine_page),
                    "c": self.tables.page.join(self.tables.magazine_page).join(
                        self.tables.classified_page
                    ),
                    "p": self.tables.page.select(
                        self.tables.page.c.type == "p"
                    ),
                },
                None,
                "page_join",
            )
            page_mapper = mapper(
                Page,
                self.tables.page,
                with_polymorphic=("*", page_join),
                polymorphic_on=page_join.c.type,
                polymorphic_identity="p",
            )
        elif use_joins:
            page_join = self.tables.page.outerjoin(
                self.tables.magazine_page
            ).outerjoin(self.tables.classified_page)
            page_mapper = mapper(
                Page,
                self.tables.page,
                with_polymorphic=("*", page_join),
                polymorphic_on=self.tables.page.c.type,
                polymorphic_identity="p",
            )
        else:
            page_mapper = mapper(
                Page,
                self.tables.page,
                polymorphic_on=self.tables.page.c.type,
                polymorphic_identity="p",
            )

        if use_unions:
            magazine_join = polymorphic_union(
                {
                    "m": self.tables.page.join(self.tables.magazine_page),
                    "c": self.tables.page.join(self.tables.magazine_page).join(
                        self.tables.classified_page
                    ),
                },
                None,
                "page_join",
            )
            magazine_page_mapper = mapper(
                MagazinePage,
                self.tables.magazine_page,
                with_polymorphic=("*", magazine_join),
                inherits=page_mapper,
                polymorphic_identity="m",
                properties={
                    "magazine": relationship(
                        Magazine,
                        backref=backref(
                            "pages", order_by=magazine_join.c.page_no
                        ),
                    )
                },
            )
        elif use_joins:
            magazine_join = self.tables.page.join(
                self.tables.magazine_page
            ).outerjoin(self.tables.classified_page)
            magazine_page_mapper = mapper(
                MagazinePage,
                self.tables.magazine_page,
                with_polymorphic=("*", magazine_join),
                inherits=page_mapper,
                polymorphic_identity="m",
                properties={
                    "magazine": relationship(
                        Magazine,
                        backref=backref(
                            "pages", order_by=self.tables.page.c.page_no
                        ),
                    )
                },
            )
        else:
            magazine_page_mapper = mapper(
                MagazinePage,
                self.tables.magazine_page,
                inherits=page_mapper,
                polymorphic_identity="m",
                properties={
                    "magazine": relationship(
                        Magazine,
                        backref=backref(
                            "pages", order_by=self.tables.page.c.page_no
                        ),
                    )
                },
            )

        mapper(
            ClassifiedPage,
            self.tables.classified_page,
            inherits=magazine_page_mapper,
            polymorphic_identity="c",
            primary_key=[self.tables.page.c.id],
        )
    def test_five(self):
        """tests the late compilation of mappers"""

        mapper(
            SpecLine,
            specification_table,
            properties=dict(
                leader=relationship(
                    Assembly,
                    lazy="joined",
                    uselist=False,
                    foreign_keys=[specification_table.c.leader_id],
                    primaryjoin=specification_table.c.leader_id ==
                    products_table.c.product_id,
                    backref=backref("specification"),
                ),
                follower=relationship(
                    Product,
                    lazy="joined",
                    uselist=False,
                    foreign_keys=[specification_table.c.follower_id],
                    primaryjoin=specification_table.c.follower_id ==
                    products_table.c.product_id,
                ),
                quantity=specification_table.c.quantity,
            ),
        )

        mapper(
            Product,
            products_table,
            polymorphic_on=products_table.c.product_type,
            polymorphic_identity="product",
            properties={
                "documents":
                relationship(
                    Document,
                    lazy="select",
                    backref="product",
                    cascade="all, delete-orphan",
                )
            },
        )

        mapper(Detail, inherits=Product, polymorphic_identity="detail")

        mapper(
            Document,
            documents_table,
            polymorphic_on=documents_table.c.document_type,
            polymorphic_identity="document",
            properties=dict(
                name=documents_table.c.name,
                data=deferred(documents_table.c.data),
            ),
        )

        mapper(
            RasterDocument,
            inherits=Document,
            polymorphic_identity="raster_document",
        )

        mapper(Assembly, inherits=Product, polymorphic_identity="assembly")

        session = create_session()

        a1 = Assembly(name="a1")
        a1.specification.append(SpecLine(follower=Detail(name="d1")))
        a1.documents.append(Document("doc1"))
        a1.documents.append(RasterDocument("doc2"))
        session.add(a1)
        orig = repr(a1)
        session.flush()
        session.expunge_all()

        a1 = session.query(Product).filter_by(name="a1").one()
        new = repr(a1)
        print(orig)
        print(new)
        assert (orig == new == "<Assembly a1> specification="
                "[<SpecLine 1.0 <Detail d1>>] documents=[<Document doc1>, "
                "<RasterDocument doc2>]")
Esempio n. 22
0
    def define_tables(cls, metadata):
        global Table1, Table1B, Table2, Table3, Data
        table1 = Table(
            "table1",
            metadata,
            Column("id",
                   Integer,
                   primary_key=True,
                   test_needs_autoincrement=True),
            Column("related_id",
                   Integer,
                   ForeignKey("table1.id"),
                   nullable=True),
            Column("type", String(30)),
            Column("name", String(30)),
        )

        table2 = Table(
            "table2",
            metadata,
            Column("id", Integer, ForeignKey("table1.id"), primary_key=True),
        )

        table3 = Table(
            "table3",
            metadata,
            Column("id", Integer, ForeignKey("table1.id"), primary_key=True),
        )

        data = Table(
            "data",
            metadata,
            Column("id",
                   Integer,
                   primary_key=True,
                   test_needs_autoincrement=True),
            Column("node_id", Integer, ForeignKey("table1.id")),
            Column("data", String(30)),
        )

        # join = polymorphic_union(
        #   {
        #   'table3' : table1.join(table3),
        #   'table2' : table1.join(table2),
        #   'table1' : table1.select(table1.c.type.in_(['table1', 'table1b'])),
        #   }, None, 'pjoin')

        join = table1.outerjoin(table2).outerjoin(table3).alias("pjoin")

        # join = None

        class Table1(object):
            def __init__(self, name, data=None):
                self.name = name
                if data is not None:
                    self.data = data

            def __repr__(self):
                return "%s(%s, %s, %s)" % (
                    self.__class__.__name__,
                    self.id,
                    repr(str(self.name)),
                    repr(self.data),
                )

        class Table1B(Table1):
            pass

        class Table2(Table1):
            pass

        class Table3(Table1):
            pass

        class Data(object):
            def __init__(self, data):
                self.data = data

            def __repr__(self):
                return "%s(%s, %s)" % (
                    self.__class__.__name__,
                    self.id,
                    repr(str(self.data)),
                )

        try:
            # this is how the mapping used to work.  ensure that this raises an
            # error now
            table1_mapper = mapper(
                Table1,
                table1,
                select_table=join,
                polymorphic_on=table1.c.type,
                polymorphic_identity="table1",
                properties={
                    "nxt":
                    relationship(
                        Table1,
                        backref=backref("prev",
                                        foreignkey=join.c.id,
                                        uselist=False),
                        uselist=False,
                        primaryjoin=join.c.id == join.c.related_id,
                    ),
                    "data":
                    relationship(mapper(Data, data)),
                },
            )
            configure_mappers()
            assert False
        except Exception:
            assert True
            clear_mappers()

        # currently, the "eager" relationships degrade to lazy relationships
        # due to the polymorphic load.
        # the "nxt" relationship used to have a "lazy='joined'" on it, but the
        # EagerLoader raises the "self-referential"
        # exception now.  since eager loading would never work for that
        # relationship anyway, its better that the user
        # gets an exception instead of it silently not eager loading.
        # NOTE: using "nxt" instead of "next" to avoid 2to3 turning it into
        # __next__() for some reason.
        table1_mapper = mapper(
            Table1,
            table1,
            # select_table=join,
            polymorphic_on=table1.c.type,
            polymorphic_identity="table1",
            properties={
                "nxt":
                relationship(
                    Table1,
                    backref=backref("prev",
                                    remote_side=table1.c.id,
                                    uselist=False),
                    uselist=False,
                    primaryjoin=table1.c.id == table1.c.related_id,
                ),
                "data":
                relationship(mapper(Data, data),
                             lazy="joined",
                             order_by=data.c.id),
            },
        )

        mapper(Table1B, inherits=table1_mapper, polymorphic_identity="table1b")

        mapper(
            Table2,
            table2,
            inherits=table1_mapper,
            polymorphic_identity="table2",
        )

        mapper(
            Table3,
            table3,
            inherits=table1_mapper,
            polymorphic_identity="table3",
        )

        configure_mappers()
        assert table1_mapper.primary_key == (
            table1.c.id, ), table1_mapper.primary_key
Esempio n. 23
0
    def _setup_stock_mapping(cls):
        (
            Node,
            composite_pk_table,
            users,
            Keyword,
            items,
            Dingaling,
            order_items,
            item_keywords,
            Item,
            User,
            dingalings,
            Address,
            keywords,
            CompositePk,
            nodes,
            Order,
            orders,
            addresses,
        ) = (
            cls.classes.Node,
            cls.tables.composite_pk_table,
            cls.tables.users,
            cls.classes.Keyword,
            cls.tables.items,
            cls.classes.Dingaling,
            cls.tables.order_items,
            cls.tables.item_keywords,
            cls.classes.Item,
            cls.classes.User,
            cls.tables.dingalings,
            cls.classes.Address,
            cls.tables.keywords,
            cls.classes.CompositePk,
            cls.tables.nodes,
            cls.classes.Order,
            cls.tables.orders,
            cls.tables.addresses,
        )

        # use OrderedDict on this one to support some tests that
        # assert the order of attributes (e.g. orm/test_inspect)
        mapper(
            User,
            users,
            properties=util.OrderedDict([
                (
                    "addresses",
                    relationship(Address,
                                 backref="user",
                                 order_by=addresses.c.id),
                ),
                (
                    "orders",
                    relationship(Order, backref="user", order_by=orders.c.id),
                ),  # o2m, m2o
            ]),
        )
        mapper(
            Address,
            addresses,
            properties={
                # o2o
                "dingaling":
                relationship(Dingaling, uselist=False, backref="address")
            },
        )
        mapper(Dingaling, dingalings)
        mapper(
            Order,
            orders,
            properties={
                # m2m
                "items":
                relationship(Item, secondary=order_items, order_by=items.c.id),
                "address":
                relationship(Address),  # m2o
            },
        )
        mapper(
            Item,
            items,
            properties={
                "keywords": relationship(Keyword,
                                         secondary=item_keywords)  # m2m
            },
        )
        mapper(Keyword, keywords)

        mapper(
            Node,
            nodes,
            properties={
                "children":
                relationship(Node,
                             backref=backref("parent",
                                             remote_side=[nodes.c.id]))
            },
        )

        mapper(CompositePk, composite_pk_table)

        configure_mappers()
    def test_nesting_with_functions(self):
        Stat, Foo, stats, foo, Data, datas = (
            self.classes.Stat,
            self.classes.Foo,
            self.tables.stats,
            self.tables.foo,
            self.classes.Data,
            self.tables.datas,
        )

        mapper(Data, datas)
        mapper(
            Foo,
            foo,
            properties={
                "data": relationship(Data,
                                     backref=backref("foo", uselist=False))
            },
        )

        mapper(Stat, stats, properties={"data": relationship(Data)})

        session = create_session()

        data = [Data(a=x) for x in range(5)]
        session.add_all(data)

        session.add_all((
            Stat(data=data[0], somedata=1),
            Stat(data=data[1], somedata=2),
            Stat(data=data[2], somedata=3),
            Stat(data=data[3], somedata=4),
            Stat(data=data[4], somedata=5),
            Stat(data=data[0], somedata=6),
            Stat(data=data[1], somedata=7),
            Stat(data=data[2], somedata=8),
            Stat(data=data[3], somedata=9),
            Stat(data=data[4], somedata=10),
        ))
        session.flush()

        arb_data = sa.select(
            [stats.c.data_id,
             sa.func.max(stats.c.somedata).label("max")],
            stats.c.data_id <= 5,
            group_by=[stats.c.data_id],
        )

        arb_result = arb_data.execute().fetchall()

        # order the result list descending based on 'max'
        arb_result.sort(key=lambda a: a["max"], reverse=True)

        # extract just the "data_id" from it
        arb_result = [row["data_id"] for row in arb_result]

        arb_data = arb_data.alias("arb")

        # now query for Data objects using that above select, adding the
        # "order by max desc" separately
        q = (session.query(Data).options(sa.orm.joinedload("foo")).select_from(
            datas.join(arb_data, arb_data.c.data_id == datas.c.id)).order_by(
                sa.desc(arb_data.c.max)).limit(10))

        # extract "data_id" from the list of result objects
        verify_result = [d.id for d in q]

        eq_(verify_result, arb_result)
    def test_bidirectional(self):
        place_input, transition, Transition, Place, place, place_output = (
            self.tables.place_input,
            self.tables.transition,
            self.classes.Transition,
            self.classes.Place,
            self.tables.place,
            self.tables.place_output,
        )

        mapper(Place, place)
        mapper(
            Transition,
            transition,
            properties=dict(
                inputs=relationship(
                    Place,
                    place_output,
                    backref=backref("inputs",
                                    order_by=transition.c.transition_id),
                    order_by=Place.place_id,
                ),
                outputs=relationship(
                    Place,
                    place_input,
                    backref=backref("outputs",
                                    order_by=transition.c.transition_id),
                    order_by=Place.place_id,
                ),
            ),
        )

        t1 = Transition("transition1")
        t2 = Transition("transition2")
        t3 = Transition("transition3")
        p1 = Place("place1")
        p2 = Place("place2")
        p3 = Place("place3")

        sess = Session()
        sess.add_all([p3, p1, t1, t2, p2, t3])

        t1.inputs.append(p1)
        t1.inputs.append(p2)
        t1.outputs.append(p3)
        t2.inputs.append(p1)
        p2.inputs.append(t2)
        p3.inputs.append(t2)
        p1.outputs.append(t1)
        sess.commit()

        self.assert_result(
            [t1],
            Transition,
            {"outputs": (Place, [{
                "name": "place3"
            }, {
                "name": "place1"
            }])},
        )
        self.assert_result(
            [p2],
            Place,
            {
                "inputs": (
                    Transition,
                    [{
                        "name": "transition1"
                    }, {
                        "name": "transition2"
                    }],
                )
            },
        )