예제 #1
0
    def test_by_pk(self):
        user = User(id=1, name="Michael Jackson")
        User.smart_insert(self.eng, user)

        assert User.by_pk(1, self.eng).name == "Michael Jackson"
        assert User.by_pk(100, self.ses) == None

        asso = Association(x_id=1, y_id=2, flag=999)
        Association.smart_insert(self.eng, asso)

        assert Association.by_pk((1, 2), self.eng).flag == 999
        assert Association.by_pk((1, 2), self.ses).flag == 999
        assert Association.by_pk(dict(x_id=1, y_id=2), self.ses).flag == 999
    def test_smart_update(self):
        # single primary key column
        User.smart_insert(self.eng, [User(id=1)])
        assert User.by_pk(1, self.eng).name == None

        # update
        row_count = User.update_all(self.eng, [
            User(id=1, name="Alice"),
            User(id=2, name="Bob"),
        ])
        assert row_count == 1
        result = self.ses.query(User).all()
        assert len(result) == 1  # User(Bob) not updated
        result[0].name == "Alice"

        # upsert
        row_count = User.upsert_all(self.eng, [
            User(id=1, name="Adam"),
            User(id=2, name="Bob"),
        ])
        assert row_count == 2

        result = self.ses.query(User).all()
        assert len(result) == 2
        result[0].name == "Adam"
        result[1].name == "Bob"

        # multiple primary key columns
        Association.smart_insert(self.ses, Association(x_id=1, y_id=1, flag=0))
        assert Association.by_pk((1, 1), self.ses).flag == 0

        # update
        row_count = Association.update_all(self.ses, [
            Association(x_id=1, y_id=1, flag=1),
            Association(x_id=1, y_id=2, flag=2),
        ])
        assert row_count == 1
        result = self.ses.query(Association).all()
        assert len(result) == 1  # User(Bob) not updated
        result[0].flag == 1

        # upsert
        row_count = Association.upsert_all(self.eng, [
            Association(x_id=1, y_id=1, flag=999),
            Association(x_id=1, y_id=2, flag=2),
        ])
        assert row_count == 2

        result = self.ses.query(Association).all()
        assert len(result) == 2
        result[0].flag == 999
        result[1].flag == 2