Fix Aggregate IndexError on a SQL query that matched nothing across shards (#1139)

This commit is contained in:
Andrew Chen
2026-07-21 11:19:28 -04:00
committed by GitHub
parent d8ae6776f8
commit d6f696d795
2 changed files with 19 additions and 2 deletions
+16
View File
@@ -5,6 +5,7 @@ SQL module tests
import unittest
from txtai.database import DatabaseFactory, SQL, SQLError
from txtai.database.sql import Aggregate
class TestSQL(unittest.TestCase):
@@ -312,6 +313,21 @@ class TestSQL(unittest.TestCase):
self.assertSql("where", prefix + "where f(id) = b(id)", "f(s.id) = b(s.id)")
self.assertSql("where", prefix + "WHERE f(id)", "f(s.id)")
def testAggregateEmptyResults(self):
"""
Test Aggregate returns empty results for a SQL query that matched nothing
(e.g. a sharded query with zero hits across all shards) instead of crashing.
"""
aggregate = Aggregate()
# SQL query, no results across shards - must not raise IndexError
self.assertEqual(aggregate("select id, text, score from txtai where similar('x')", []), [])
# Non-SQL query with no results stays consistent
self.assertEqual(aggregate("plain text query", []), [])
# SQL query with results still aggregates as before
self.assertEqual(aggregate("select count(*) from txtai", [{"count(*)": 1}, {"count(*)": 2}]), [{"count(*)": 3}])
def assertSql(self, clause, query, expected):
"""
Helper method to assert a query clause is as expected.