[IMP] account_reconciliation_widget: reduce heavy queries count

This specific query is quite expensive, and what's worse, it's also done twice: once to count records and once to get them.

By using a window function, we can get the count and results in one query, thus almost doubling performance in this operation.

Related resources:

- [Explanation](https://stackoverflow.com/a/22353886/1468388).
- [Explain of the 1st SELECT COUNT(*), before the patch](https://explain.dalibo.com/plan/TgL).
- [Explain of the 2nd SELECT, before the patch](https://explain.dalibo.com/plan/Yc9).
- [Explain of the new, unified SELECT, after the patch](https://explain.dalibo.com/plan/9MA).

@Tecnativa TT28595 TT29916 https://github.com/odoo/odoo/pull/73765
This commit is contained in:
Jairo Llopis
2021-07-15 13:00:39 +01:00
committed by kelvzxu
parent 8ef8a73ba4
commit 33d4223818

View File

@@ -102,14 +102,13 @@ class AccountReconciliation(models.AbstractModel):
search_str=search_str,
mode=mode,
)
recs_count = self.env["account.move.line"].search_count(domain)
from_clause, where_clause, where_clause_params = (
self.env["account.move.line"]._where_calc(domain).get_sql()
)
query_str = sql.SQL(
"""
SELECT "account_move_line".id FROM {from_clause}
SELECT "account_move_line".id, COUNT(*) OVER() FROM {from_clause}
{where_str}
ORDER BY ("account_move_line".debit -
"account_move_line".credit) = {amount} DESC,
@@ -129,7 +128,11 @@ class AccountReconciliation(models.AbstractModel):
self.env["account.bank.statement"].flush()
self._cr.execute(query_str, params)
res = self._cr.fetchall()
try:
# All records will have the same count value, just get the 1st one
recs_count = res[0][1]
except IndexError:
recs_count = 0
aml_recs = self.env["account.move.line"].browse([i[0] for i in res])
target_currency = (
st_line.currency_id