示例#1
0
    def test_aggregate_unselected_join_backref(self):
        cat_1 = Category.create(name='category 1')
        cat_2 = Category.create(name='category 2')
        with test_db.transaction():
            for i, user in enumerate(User.select().order_by(User.username)):
                if i % 2 == 0:
                    category = cat_2
                else:
                    category = cat_1
                UserCategory.create(user=user, category=category)

        with self.assertQueryCount(1):
            # The join on UserCategory is a backref join (since the FK is on
            # UserCategory). Additionally, UserCategory/Category are not
            # selected and are only used for filtering the result set.
            query = (User
                     .select(User, Blog)
                     .join(Blog, JOIN_LEFT_OUTER)
                     .switch(User)
                     .join(UserCategory)
                     .join(Category)
                     .where(Category.name == cat_1.name)
                     .order_by(User.username, Blog.title)
                     .aggregate_rows())

            results = []
            for user in query:
                results.append((
                    user.username,
                    [blog.title for blog in user.blog_set]))

        self.assertEqual(results, [
            ('u2', []),
            ('u4', ['b5', 'b6']),
        ])
示例#2
0
 def test_failure(self):
     with test_db.transaction():
         self.assertRaises(ValueError,
                           self._outer,
                           fail_outer=True,
                           fail_inner=True)
         self.assertEqual(User.select().count(), 0)
示例#3
0
    def test_constraint_creation(self):
        class FKC_a(TestModel):
            name = CharField()

        fkc_proxy = Proxy()

        class FKC_b(TestModel):
            fkc_a = ForeignKeyField(fkc_proxy)

        fkc_proxy.initialize(FKC_a)

        with test_db.transaction() as txn:
            FKC_b.drop_table(True)
            FKC_a.drop_table(True)
            FKC_a.create_table()
            FKC_b.create_table()

            # Foreign key constraint is not enforced.
            fb = FKC_b.create(fkc_a=-1000)
            fb.delete_instance()

            # Add constraint.
            test_db.create_foreign_key(FKC_b, FKC_b.fkc_a)

            def _trigger_exc():
                with test_db.savepoint() as s1:
                    fb = FKC_b.create(fkc_a=-1000)

            self.assertRaises(IntegrityError, _trigger_exc)

            fa = FKC_a.create(name='fa')
            fb = FKC_b.create(fkc_a=fa)
            txn.rollback()
示例#4
0
    def test_aggregate_unselected_join_backref(self):
        cat_1 = Category.create(name='category 1')
        cat_2 = Category.create(name='category 2')
        with test_db.transaction():
            for i, user in enumerate(User.select().order_by(User.username)):
                if i % 2 == 0:
                    category = cat_2
                else:
                    category = cat_1
                UserCategory.create(user=user, category=category)

        with self.assertQueryCount(1):
            # The join on UserCategory is a backref join (since the FK is on
            # UserCategory). Additionally, UserCategory/Category are not
            # selected and are only used for filtering the result set.
            query = (User
                     .select(User, Blog)
                     .join(Blog, JOIN.LEFT_OUTER)
                     .switch(User)
                     .join(UserCategory)
                     .join(Category)
                     .where(Category.name == cat_1.name)
                     .order_by(User.username, Blog.title)
                     .aggregate_rows())

            results = []
            for user in query:
                results.append((
                    user.username,
                    [blog.title for blog in user.blog_set]))

        self.assertEqual(results, [
            ('u2', []),
            ('u4', ['b5', 'b6']),
        ])
示例#5
0
 def test_check_constraint(self):
     CheckModel.create(value=1)
     if isinstance(test_db, MySQLDatabase):
         # MySQL silently ignores all check constraints.
         CheckModel.create(value=0)
     else:
         with test_db.transaction() as txn:
             self.assertRaises(IntegrityError, CheckModel.create, value=0)
             txn.rollback()
示例#6
0
 def test_check_constraint(self):
     CheckModel.create(value=1)
     if isinstance(test_db, MySQLDatabase):
         # MySQL silently ignores all check constraints.
         CheckModel.create(value=0)
     else:
         with test_db.transaction() as txn:
             self.assertRaises(IntegrityError, CheckModel.create, value=0)
             txn.rollback()
示例#7
0
    def test_manual_commit_rollback(self):
        def assertUsers(expected):
            query = User.select(User.username).order_by(User.username)
            self.assertEqual([username for username, in query.tuples()], expected)

        with test_db.transaction() as txn:
            User.create(username="******")
            txn.commit()
            User.create(username="******")
            txn.rollback()

        assertUsers(["charlie"])

        with test_db.transaction() as txn:
            User.create(username="******")
            txn.rollback()
            User.create(username="******")

        assertUsers(["charlie", "zaizee"])
示例#8
0
    def test_count_transaction(self):
        for i in range(10):
            User.create(username='******' % i)

        with test_db.transaction():
            for user in User.select():
                for i in range(20):
                    Blog.create(user=user, title='b-%d-%d' % (user.id, i))

        count = Blog.select().count()
        self.assertEqual(count, 200)
示例#9
0
    def test_count_transaction(self):
        for i in range(10):
            User.create(username='******' % i)

        with test_db.transaction():
            for user in User.select():
                for i in range(20):
                    Blog.create(user=user, title='b-%d-%d' % (user.id, i))

        count = Blog.select().count()
        self.assertEqual(count, 200)
示例#10
0
    def test_manual_commit_rollback(self):
        def assertUsers(expected):
            query = User.select(User.username).order_by(User.username)
            self.assertEqual([username for username, in query.tuples()],
                             expected)

        with test_db.transaction() as txn:
            User.create(username='******')
            txn.commit()
            User.create(username='******')
            txn.rollback()

        assertUsers(['charlie'])

        with test_db.transaction() as txn:
            User.create(username='******')
            txn.rollback()
            User.create(username='******')

        assertUsers(['charlie', 'zaizee'])
示例#11
0
    def test_transaction_ctx_mgr(self):
        'Only auto-rollback when autocommit is enabled.'
        def create_error():
            self.assertRaises(IntegrityError, Blog.create)

        # autocommit is disabled in a transaction ctx manager.
        with test_db.transaction():
            # Error occurs, but exception is caught, leaving the current txn
            # in a bad state.
            create_error()

            try:
                create_error()
            except Exception as exc:
                # Subsequent call will raise an InternalError with postgres.
                self.assertTrue(isinstance(exc, InternalError))
            else:
                self.assertFalse(database_class is PostgresqlDatabase)

        # New transactions are not affected.
        self.test_auto_rollback()
    def test_transaction_ctx_mgr(self):
        'Only auto-rollback when autocommit is enabled.'
        def create_error():
            self.assertRaises(IntegrityError, Blog.create)

        # autocommit is disabled in a transaction ctx manager.
        with test_db.transaction():
            # Error occurs, but exception is caught, leaving the current txn
            # in a bad state.
            create_error()

            try:
                create_error()
            except Exception as exc:
                # Subsequent call will raise an InternalError with postgres.
                self.assertTrue(isinstance(exc, InternalError))
            else:
                self.assertFalse(
                    issubclass(database_class, PostgresqlDatabase))

        # New transactions are not affected.
        self.test_auto_rollback()
示例#13
0
 def will_fail():
     with test_db.transaction() as txn:
         Blog.create(user=max_id + 1, title='testing')
示例#14
0
 def test_failure(self):
     with test_db.transaction():
         self.assertRaises(
             ValueError, self._outer, fail_outer=True, fail_inner=True)
         self.assertEqual(User.select().count(), 0)
示例#15
0
 def test_outer_failure(self):
     # Because the outer savepoint is rolled back, we'll lose the
     # inner savepoint as well.
     with test_db.transaction():
         self.assertRaises(ValueError, self._outer, fail_outer=True)
         self.assertEqual(User.select().count(), 0)
示例#16
0
 def test_inner_failure(self):
     with test_db.transaction():
         self._outer(fail_inner=True)
         self.assertEqual(User.select().count(), 1)
     self.assertNames(['outer'])
示例#17
0
 def test_success(self):
     with test_db.transaction():
         self._outer()
         self.assertEqual(User.select().count(), 2)
     self.assertNames(['inner', 'outer'])
示例#18
0
 def do_manual_rollback():
     with test_db.transaction() as txn:
         User.create(username='******')
         txn.rollback()
示例#19
0
 def do_will_fail():
     with test_db.transaction():
         User.create(username='******')
         Blog.create() # no blog, will raise an error
示例#20
0
 def transaction_generator():
     with test_db.transaction():
         User.create(username='******')
         yield
         User.create(username='******')
 def do_will_fail():
     with test_db.transaction():
         User.create(username='******')
         Blog.create() # no blog, will raise an error
示例#22
0
 def transaction_generator():
     with test_db.transaction():
         User.create(username="******")
         yield
         User.create(username="******")
 def transaction_generator():
     with test_db.transaction():
         User.create(username='******')
         yield
         User.create(username='******')
 def do_manual_rollback():
     with test_db.transaction() as txn:
         User.create(username='******')
         txn.rollback()
 def test_success(self):
     with test_db.transaction():
         self._outer()
         self.assertEqual(User.select().count(), 2)
     self.assertNames(['inner', 'outer'])
 def test_outer_failure(self):
     # Because the outer savepoint is rolled back, we'll lose the
     # inner savepoint as well.
     with test_db.transaction():
         self.assertRaises(ValueError, self._outer, fail_outer=True)
         self.assertEqual(User.select().count(), 0)
 def test_inner_failure(self):
     with test_db.transaction():
         self._outer(fail_inner=True)
         self.assertEqual(User.select().count(), 1)
     self.assertNames(['outer'])