Search code examples
pythonsqlitepeewee

Why does the .count() return the wrong number on a peewee query with | (union)?


The first three queries below return the correct number, while the last one returns the wrong number. It should return 153, instead it returns 8193. I have no clue where that number comes from.

Iterating through the query correctly returns 153 records.

>>> Project.select().where(Project.number.between('2012-01', '2012-02')).count()
75
>>> Project.select().where(Project.number.between('2012-02', '2012-03')).count()
78
>>> Project.select().where(Project.number.between('2012-01', '2012-03')).count()
153
>>> (Project.select().where(Project.number.between('2012-01', '2012-02')) | 
     Project.select().where(Project.number.between('2012-01', '2012-03'))).count()
8193

EDIT

Here is a function that reproduces the problem starting from an empty database.

def test(self):

    db = peewee.SqliteDatabase('test.db', check_same_thread=False)

    class Test(peewee.Model):
        num = peewee.IntegerField()
        class Meta:
            database = db

    Test.drop_table(True)
    Test.create_table(True)

    for i in range(1, 11):
        Test.create(num=i)

    q = Test.select().where(Test.num > 6) | Test.select().where(Test.num > 7)

    print(q)

    print('Count =', q.count())

    for i in q:
        print(i.num)

And here is its output. It shows that the iteration correctly returns 4 items, but the count is wrong:

<class 'DocFinder.DocFinder.DocFinder.test.<locals>.Test'> SELECT t2."id", t2."num" FROM "test" AS t2 WHERE (t2."num" > ?) UNION SELECT t3."id", t3."num" FROM "test" AS t3 WHERE (t3."num" > ?) [6, 7]
Count = 7
7
8
9
10

Solution

  • Try using .wrapped_count() instead.