예제 #1
0
    def test_immediateload(self):
        self.assertEqual(
            str(self.db.query(Foo).immediateload('bars')),
            str(self.db.query(Foo).options(orm.immediateload('bars')))
        )

        self.assertEqual(
            str(self.db.query(Foo).immediateload('bars', 'bazs')),
            str((self.db.query(Foo)
                 .options(orm.immediateload('bars').immediateload('bazs'))))
        )

        self.assertEqual(
            str(self.db.query(Foo).immediateload(Foo.bars)),
            str(self.db.query(Foo).options(orm.immediateload(Foo.bars)))
        )

        self.assertEqual(
            str(self.db.query(Foo).immediateload(Foo.bars, Bar.bazs)),
            str((self.db.query(Foo)
                .options(orm.immediateload(Foo.bars).immediateload(Bar.bazs))))
        )

        self.assertEqual(
            str((self.db.query(Foo)
                 .immediateload('bars',
                                options=[LoadOption('immediateload',
                                                    'bazs')]))),
            str((self.db.query(Foo)
                 .options(orm.immediateload('bars').immediateload('bazs'))))
        )
    def test_basic_option(self):
        Address, addresses, users, User = (
            self.classes.Address,
            self.tables.addresses,
            self.tables.users,
            self.classes.User,
        )

        mapper(Address, addresses)
        mapper(User, users, properties={"addresses": relationship(Address)})
        sess = fixture_session()

        result = (sess.query(User).options(immediateload(
            User.addresses)).filter(users.c.id == 7).all())
        eq_(len(sess.identity_map), 2)

        sess.close()

        eq_(
            [
                User(
                    id=7,
                    addresses=[Address(id=1, email_address="*****@*****.**")],
                )
            ],
            result,
        )
예제 #3
0
    def test_basic_option(self):
        Address, addresses, users, User = (
            self.classes.Address,
            self.tables.addresses,
            self.tables.users,
            self.classes.User,
        )

        mapper(Address, addresses)
        mapper(User, users, properties={"addresses": relationship(Address)})
        sess = create_session()

        result = (
            sess.query(User)
            .options(immediateload(User.addresses))
            .filter(users.c.id == 7)
            .all()
        )
        eq_(len(sess.identity_map), 2)

        sess.close()

        eq_(
            [
                User(
                    id=7,
                    addresses=[Address(id=1, email_address="*****@*****.**")],
                )
            ],
            result,
        )
예제 #4
0
    def test_basic_option_m2o(self, default_lazy):
        Address, addresses, users, User = (
            self.classes.Address,
            self.tables.addresses,
            self.tables.users,
            self.classes.User,
        )

        mapper(
            Address,
            addresses,
            properties={"user": relationship(User, lazy=default_lazy)},
        )
        mapper(User, users)
        sess = fixture_session()

        result = (sess.query(Address).options(immediateload(
            Address.user)).filter(Address.id == 1).all())
        eq_(len(sess.identity_map), 2)

        sess.close()

        eq_(
            [Address(id=1, email_address="*****@*****.**", user=User(id=7))],
            result,
        )
예제 #5
0
    def test_no_auto_recurse_non_self_referential(self):
        users, Address, addresses, User = (
            self.tables.users,
            self.classes.Address,
            self.tables.addresses,
            self.classes.User,
        )

        self.mapper_registry.map_imperatively(
            User,
            users,
            properties={
                "addresses":
                relationship(
                    self.mapper_registry.map_imperatively(Address, addresses),
                    order_by=Address.id,
                )
            },
        )
        sess = fixture_session()

        stmt = select(User).options(
            immediateload(User.addresses, auto_recurse=True))
        with expect_raises_message(
                sa.exc.InvalidRequestError,
                "auto_recurse option on relationship User.addresses not valid",
        ):
            sess.execute(stmt).all()
예제 #6
0
 def cash_instances_to_dict(self, list_of_classes, do_make_transient = False):
     #Закрываем сессию. Открываем новую и считываем в нее все классы. Отвязываем их от сессии.
     #Возвращаем список инстансов в виде словаря. Надеюсь, это поможет работать с ними сколь угодно много..
     #Была идея оставить возможность не закрывать сесиию - отказался. В худшем случае, можно отдельную сессию создавать.
     #Но две одновременные сессии - тоже опасно.
     self.close_session()
     self.private_activate_session()
     dict_with_instances = dict()
     for cls_i in list_of_classes:  #Интересно, нужно ли как-то особо считывать взаимосвязи
         repr_cls_i = with_polymorphic(cls_i, '*')
         inst_list = []
         for inst_i in self.active_session.query(repr_cls_i).options(immediateload('*')).all():
             #if not(inst_i in inst_list):
             inst_list.append(inst_i)
         dict_with_instances[cls_i.__name__] = inst_list
     self.active_session.expunge_all() #именно поэтому закрываем сессию до запуска
     for inst_list in dict_with_instances.itervalues():
         for inst_i in inst_list:
             if hasattr(inst_i, "disconnected_from_session"):
                 raise BaseException("[c_session_handler][cash_instances_to_dict] you cannot use 'disconnected_from_session' attribute in a class here")
             inst_i.disconnected_from_session = True
             if do_make_transient:  #Без этого может пытаться обратиться к базе данных
                 make_transient(inst_i)
     self.close_session()
     return dict_with_instances
예제 #7
0
def get_security_groups():
    session = db.get_reader_session()
    with session.begin():
        sg_model = sg_models.SecurityGroup
        # We do an immediate load to prevent the need for the sync worker
        # to issue subqueries
        security_groups = (session.query(sg_model)
                           .options(immediateload(sg_model.rules)))
    return security_groups
예제 #8
0
    def test_immediateload(self):
        self.assertEqual(
            str(self.db.query(Foo).immediateload('bars')),
            str(self.db.query(Foo).options(orm.immediateload('bars'))))

        self.assertEqual(
            str(self.db.query(Foo).immediateload('bars', 'bazs')),
            str((self.db.query(Foo).options(
                orm.immediateload('bars').immediateload('bazs')))))

        self.assertEqual(
            str(self.db.query(Foo).immediateload(Foo.bars)),
            str(self.db.query(Foo).options(orm.immediateload(Foo.bars))))

        self.assertEqual(
            str(self.db.query(Foo).immediateload(Foo.bars, Bar.bazs)),
            str((self.db.query(Foo).options(
                orm.immediateload(Foo.bars).immediateload(Bar.bazs)))))

        self.assertEqual(
            str((self.db.query(Foo).immediateload(
                'bars', options=[LoadOption('immediateload', 'bazs')]))),
            str((self.db.query(Foo).options(
                orm.immediateload('bars').immediateload('bazs')))))
예제 #9
0
    def test_basic_option(self):
        mapper(Address, addresses)
        mapper(User, users, properties={
            'addresses':relationship(Address)
        })
        sess = create_session()

        l = sess.query(User).options(immediateload(User.addresses)).filter(users.c.id==7).all()
        eq_(len(sess.identity_map), 2)

        sess.close()

        eq_(
            [User(id=7, addresses=[Address(id=1, email_address='*****@*****.**')])],
            l
        )
    def test_refresh_collection(self):
        Customer = self.classes.Customer

        s = Session()
        customers = s.query(Customer).options(immediateload(Customer.orders)).filter(Customer.id == 1).all()
        orders = customers[0].orders

        # expire...
        for ord_ in orders:
            s.expire(ord_)

        # + load again, should refresh Orders on Customer
        s.query(Customer).options(orm.nestedload(Customer.orders)).filter(Customer.id == 1).all()

        # covers the "exec" loader
        with self.assert_statement_count(0):
            eq_(customers, [self._orm_fixture(orders=True)])
예제 #11
0
    def test_refresh_collection(self):
        Customer = self.classes.Customer

        s = Session()
        customers = s.query(Customer).options(immediateload(Customer.orders)).\
                            filter(Customer.id == 1).all()
        orders = customers[0].orders

        # expire...
        for ord_ in orders:
            s.expire(ord_)

        # + load again, should refresh Orders on Customer
        s.query(Customer).options(orm.nestedload(Customer.orders)).\
                            filter(Customer.id == 1).all()

        # covers the "exec" loader
        with self.assert_statement_count(0):
            eq_(customers, [self._orm_fixture(orders=True)])
예제 #12
0
    logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)

    print '-------------Lazy--------------'
    books = session.query(Book).all()
    print books[0].author.name
    session.commit()
    print '-------------Subquery----------'
    books = session.query(Book).options(subqueryload(Book.author)).all()
    print books[0].author.name
    session.commit()
    print '-------------Joined------------'
    books = session.query(Book).options(joinedload(Book.author)).all()
    print books[0].author.name
    session.commit()
    print '-------------Immediate---------'
    books = session.query(Book).options(immediateload(Book.author)).all()
    print books[0].author.name
    session.commit()
    print '-------------IN----------------'
    books = session.query(Book).all()
    ids = set()
    for b in books:
        ids.add(b.author_id)
    authors = session.query(Author).filter(Author.id.in_(ids)).all()
    print books[0].author.name
    print books[1].author.name
    print books[2].author.name
    print books[3].author.name

    # session.commit()
예제 #13
0
 def go():
     return (sess.query(Node).filter(Node.data.in_([
         "n1", "n2"
     ])).options(immediateload(
         Node.children, auto_recurse=True)).order_by(Node.data).all())
예제 #14
0
    logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)

    print '-------------Lazy--------------'
    books = session.query(Book).all()
    print books[0].author.name
    session.commit()
    print '-------------Subquery----------'
    books = session.query(Book).options(subqueryload(Book.author)).all()
    print books[0].author.name
    session.commit()
    print '-------------Joined------------'
    books = session.query(Book).options(joinedload(Book.author)).all()
    print books[0].author.name
    session.commit()
    print '-------------Immediate---------'
    books = session.query(Book).options(immediateload(Book.author)).all()
    print books[0].author.name
    session.commit()
    print '-------------IN----------------'
    books = session.query(Book).all()
    ids = set()
    for b in books:
        ids.add(b.author_id)
    authors = session.query(Author).filter(Author.id.in_(ids)).all()
    print books[0].author.name
    print books[1].author.name
    print books[2].author.name
    print books[3].author.name

    # session.commit()