Skip to content

Commit ee6740b

Browse files
committed
[FIX] orm: in recompute_fields, avoid memory error from postgresql
improves 13adede Queries run through client-side cursors will make postgresql materialze the whole of the result immediately (which is actually, why `cr.rowcount` is always available right after `execute` in this case). With server side cursors (named cursors) on the other hand, tuples are materialized when they are fetched. This is why running the `query` for ids through the client-side cursor just to be able to access `cr.rowcount`, can cause an out-of-memory exception from PostgreSQL. We fix this by wrapping the query as a subquery into a `SLEECT count(*)`, which allows PostgreSQL to materialze just a single tuple. Also, there is no need to fetch a million ids at once, so to go ligth on memory on the python side as well, we reduce teh `itersize` to 100k.
1 parent fd578e3 commit ee6740b

File tree

1 file changed

+6
-4
lines changed

1 file changed

+6
-4
lines changed

src/util/orm.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -289,14 +289,16 @@ def recompute_fields(cr, model, fields, ids=None, logger=_logger, chunk_size=256
289289

290290
if ids is None:
291291
query = format_query(cr, "SELECT id FROM {} ORDER BY id", table_of_model(cr, model)) if query is None else query
292-
cr.execute(query)
293-
count = cr.rowcount
294-
if count < 2**21: # avoid the overhead of a named cursor unless we have at least two chunks
292+
count_query = "SELECT count(*) FROM ({query}) AS count".format(query=query)
293+
cr.execute(count_query)
294+
count = cr.fetchone()[0]
295+
itersize = BIG_TABLE_THRESHOLD
296+
if count < 2 * itersize: # avoid the overhead of a named cursor unless we have at least two chunks
295297
ids_ = (id_ for (id_,) in cr.fetchall())
296298
else:
297299

298300
def get_ids():
299-
with named_cursor(cr, itersize=2**20) as ncr:
301+
with named_cursor(cr, itersize=itersize) as ncr:
300302
ncr.execute(query)
301303
for (id_,) in ncr:
302304
yield id_

0 commit comments

Comments
 (0)