From 38e2c34a53f9bf6571eb3941194e4fc164485cdc Mon Sep 17 00:00:00 2001 From: Frederik Jaeckel Date: Fri, 23 Jun 2023 16:02:31 +0200 Subject: [PATCH] asset/rate: speed up percent-queries --- asset.py | 48 ++++++++++++++++++++++-------------------------- rate.py | 7 +++++++ 2 files changed, 29 insertions(+), 26 deletions(-) diff --git a/asset.py b/asset.py index 06bade6..9d4ca63 100644 --- a/asset.py +++ b/asset.py @@ -473,8 +473,6 @@ class Asset(SymbolMixin, ModelSQL, ModelView): """ pool = Pool() Rate = pool.get('investment.rate') - Asset2 = pool.get('investment.asset') - tab_asset = Asset2.__table__() tab_rate1 = Rate.__table__() tab_rate2 = Rate.__table__() context = Transaction().context @@ -482,17 +480,14 @@ class Asset(SymbolMixin, ModelSQL, ModelView): query_date = context.get('qdate', CurrentDate()) where_asset = tab_rate1.date <= query_date if isinstance(asset_ids, list): - where_asset &= tab_asset.id.in_(asset_ids) + where_asset &= tab_rate1.asset.in_(asset_ids) - tab_today = tab_asset.join( - tab_rate1, - condition=tab_asset.id == tab_rate1.asset, - ).select( - tab_asset.id, + tab_today = tab_rate1.select( + tab_rate1.asset.as_('id'), tab_rate1.date, tab_rate1.rate, - distinct_on=[tab_asset.id], - order_by=[tab_asset.id, tab_rate1.date.desc], + distinct_on=[tab_rate1.asset], + order_by=[tab_rate1.asset, tab_rate1.date.desc], where=where_asset, ) @@ -613,23 +608,24 @@ class Asset(SymbolMixin, ModelSQL, ModelView): exp = Decimal(Decimal(1) / 10 ** digits_percent) asset_id_lst = [x.id for x in assets] - for x in names: - tab_percent = cls.get_percentage_sql( - days={ - 'change_day1': 0, - 'change_month1': 30, - 'change_month3': 90, - 'change_month6': 180, - 'change_month12': 365, - }[x], - asset_ids=asset_id_lst, - ) - cursor.execute(*tab_percent) - records = cursor.fetchall() + if asset_id_lst and names: + for x in names: + tab_percent = cls.get_percentage_sql( + days={ + 'change_day1': 0, + 'change_month1': 30, + 'change_month3': 90, + 'change_month6': 180, + 'change_month12': 365, + }[x], + asset_ids=asset_id_lst, + ) + cursor.execute(*tab_percent) + records = cursor.fetchall() - for record in records: - result[x][record[0]] = record[3].quantize(exp) \ - if record[3] is not None else None + for record in records: + result[x][record[0]] = record[3].quantize(exp) \ + if record[3] is not None else None return result @classmethod diff --git a/rate.py b/rate.py index eef697c..6379e6b 100644 --- a/rate.py +++ b/rate.py @@ -53,6 +53,13 @@ class Rate(SymbolMixin, ModelSQL, ModelView): Index( t, (t.rate, Index.Range())), + Index( + t, + (t.asset, Index.Equality())), + Index( + t, + (t.asset, Index.Equality()), + (t.date, Index.Range(order='DESC'))), }) @classmethod