From 33d42238184de647dea736cf9a1c30d39a3f8a69 Mon Sep 17 00:00:00 2001 From: Jairo Llopis Date: Thu, 15 Jul 2021 13:00:39 +0100 Subject: [PATCH] [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 --- .../models/reconciliation_widget.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/account_reconciliation_widget/models/reconciliation_widget.py b/account_reconciliation_widget/models/reconciliation_widget.py index 8161b3f4..da75c8b2 100644 --- a/account_reconciliation_widget/models/reconciliation_widget.py +++ b/account_reconciliation_widget/models/reconciliation_widget.py @@ -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