From 9c5733bc48eae1621d74320d07f3a9a4269dbd54 Mon Sep 17 00:00:00 2001 From: frisitano Date: Wed, 3 Dec 2025 15:22:38 +0400 Subject: [PATCH] optimise startup query --- crates/database/db/src/operations.rs | 39 +++++++++++++++++++++------- 1 file changed, 30 insertions(+), 9 deletions(-) diff --git a/crates/database/db/src/operations.rs b/crates/database/db/src/operations.rs index e700bc18..0d6cfa21 100644 --- a/crates/database/db/src/operations.rs +++ b/crates/database/db/src/operations.rs @@ -1108,25 +1108,46 @@ impl DatabaseReadOperations for T { .await? .flatten(); - let latest_batch_event = models::batch_commit::Entity::find() + // Split the following lookups into three separate queries for better index utilization. + // Each query can use its respective index efficiently instead of doing a table scan. + let max_block_number = models::batch_commit::Entity::find() + .select_only() + .filter(models::batch_commit::Column::Index.gt(0)) + .column_as(models::batch_commit::Column::BlockNumber.max(), "max_block_number") + .into_tuple::>() + .one(self.get_connection()) + .await? + .flatten(); + + let max_finalized_block_number = models::batch_commit::Entity::find() .select_only() .filter(models::batch_commit::Column::Index.gt(0)) .column_as( - Expr::col(models::batch_commit::Column::BlockNumber).max(), - "max_block_number", - ) - .column_as( - Expr::col(models::batch_commit::Column::FinalizedBlockNumber).max(), + models::batch_commit::Column::FinalizedBlockNumber.max(), "max_finalized_block_number", ) + .into_tuple::>() + .one(self.get_connection()) + .await? + .flatten(); + + let max_reverted_block_number = models::batch_commit::Entity::find() + .select_only() + .filter(models::batch_commit::Column::Index.gt(0)) .column_as( - Expr::col(models::batch_commit::Column::RevertedBlockNumber).max(), + models::batch_commit::Column::RevertedBlockNumber.max(), "max_reverted_block_number", ) - .into_tuple::<(Option, Option, Option)>() + .into_tuple::>() .one(self.get_connection()) .await? - .and_then(|tuple| <[Option; 3]>::from(tuple).into_iter().flatten().max()); + .flatten(); + + let latest_batch_event = + [max_block_number, max_finalized_block_number, max_reverted_block_number] + .into_iter() + .flatten() + .max(); let latest_l1_block_number = [latest_l1_message, latest_batch_event].into_iter().flatten().max();