find is now streaming large tables

This commit is contained in:
Gregor Aisch 2013-04-12 16:42:22 +02:00
parent 187ed2680f
commit 3ad013b1d1

View File

@ -5,6 +5,7 @@ from sqlalchemy.sql import and_, expression
from sqlalchemy.schema import Column, Index from sqlalchemy.schema import Column, Index
from dataset.persistence.util import guess_type from dataset.persistence.util import guess_type
from dataset.persistence.util import ResultIter
from dataset.util import DatasetException from dataset.util import DatasetException
@ -270,6 +271,13 @@ class Table(object):
args = self._args_to_clause(filter) args = self._args_to_clause(filter)
# query total number of rows first
count_query = self.table.count(whereclause=args, limit=_limit, offset=_offset)
rp = self.database.engine.execute(count_query)
total_row_count = rp.fetchone()[0]
queries = []
for i in count(): for i in count():
qoffset = _offset + (_step * i) qoffset = _offset + (_step * i)
qlimit = _step qlimit = _step
@ -277,13 +285,11 @@ class Table(object):
qlimit = min(_limit - (_step * i), _step) qlimit = min(_limit - (_step * i), _step)
if qlimit <= 0: if qlimit <= 0:
break break
q = self.table.select(whereclause=args, limit=qlimit, if qoffset > total_row_count:
offset=qoffset, order_by=order_by) break
rows = list(self.database.query(q)) queries.append(self.table.select(whereclause=args, limit=qlimit,
if not len(rows): offset=qoffset, order_by=order_by))
return return ResultIter((self.database.engine.execute(q) for q in queries))
for row in rows:
yield row
def __len__(self): def __len__(self):
""" """
@ -337,6 +343,4 @@ class Table(object):
for row in table: for row in table:
print row print row
""" """
for row in self.all(): return self.all()
yield row