From b7f15f8472e3d50da3e74a8a9f5ecc650cf1180b Mon Sep 17 00:00:00 2001 From: Victor Baranov Date: Thu, 31 Oct 2024 10:20:06 +0200 Subject: [PATCH] perf: Fix performance of Explorer.Counters.Transactions24hStats.consolidate/0 function (#11082) --- .../explorer/counters/transactions_24h_stats.ex | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/apps/explorer/lib/explorer/counters/transactions_24h_stats.ex b/apps/explorer/lib/explorer/counters/transactions_24h_stats.ex index e82df0530e..234a6fdeec 100644 --- a/apps/explorer/lib/explorer/counters/transactions_24h_stats.ex +++ b/apps/explorer/lib/explorer/counters/transactions_24h_stats.ex @@ -10,7 +10,7 @@ defmodule Explorer.Counters.Transactions24hStats do import Ecto.Query alias Explorer.{Chain, Repo} - alias Explorer.Chain.Transaction + alias Explorer.Chain.{DenormalizationHelper, Transaction} @transaction_count_name "transaction_count_24h" @transaction_fee_sum_name "transaction_fee_sum_24h" @@ -94,15 +94,18 @@ defmodule Explorer.Counters.Transactions24hStats do sum_query = dynamic([_, _], sum(^fee_query)) avg_query = dynamic([_, _], avg(^fee_query)) - query = + base_query = from(transaction in Transaction, join: block in assoc(transaction, :block), - where: block.timestamp >= ago(24, "hour"), select: %{count: count(transaction.hash)}, select_merge: ^%{fee_sum: sum_query}, select_merge: ^%{fee_average: avg_query} ) + query = + base_query + |> where_block_timestamp_in_last_24_hours() + %{ count: count, fee_sum: fee_sum, @@ -125,6 +128,14 @@ defmodule Explorer.Counters.Transactions24hStats do }) end + defp where_block_timestamp_in_last_24_hours(query) do + if DenormalizationHelper.transactions_denormalization_finished?() do + where(query, [transaction, _block], transaction.block_timestamp >= ago(24, "hour")) + else + where(query, [_transaction, block], block.timestamp >= ago(24, "hour")) + end + end + @doc """ Returns a boolean that indicates whether consolidation is enabled