Skip to content

Commit a900ec4

Browse files
authored
optimise startup query (#450)
1 parent 9af4eef commit a900ec4

File tree

1 file changed

+30
-9
lines changed

1 file changed

+30
-9
lines changed

crates/database/db/src/operations.rs

Lines changed: 30 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1108,25 +1108,46 @@ impl<T: ReadConnectionProvider + Sync + ?Sized> DatabaseReadOperations for T {
11081108
.await?
11091109
.flatten();
11101110

1111-
let latest_batch_event = models::batch_commit::Entity::find()
1111+
// Split the following lookups into three separate queries for better index utilization.
1112+
// Each query can use its respective index efficiently instead of doing a table scan.
1113+
let max_block_number = models::batch_commit::Entity::find()
1114+
.select_only()
1115+
.filter(models::batch_commit::Column::Index.gt(0))
1116+
.column_as(models::batch_commit::Column::BlockNumber.max(), "max_block_number")
1117+
.into_tuple::<Option<i64>>()
1118+
.one(self.get_connection())
1119+
.await?
1120+
.flatten();
1121+
1122+
let max_finalized_block_number = models::batch_commit::Entity::find()
11121123
.select_only()
11131124
.filter(models::batch_commit::Column::Index.gt(0))
11141125
.column_as(
1115-
Expr::col(models::batch_commit::Column::BlockNumber).max(),
1116-
"max_block_number",
1117-
)
1118-
.column_as(
1119-
Expr::col(models::batch_commit::Column::FinalizedBlockNumber).max(),
1126+
models::batch_commit::Column::FinalizedBlockNumber.max(),
11201127
"max_finalized_block_number",
11211128
)
1129+
.into_tuple::<Option<i64>>()
1130+
.one(self.get_connection())
1131+
.await?
1132+
.flatten();
1133+
1134+
let max_reverted_block_number = models::batch_commit::Entity::find()
1135+
.select_only()
1136+
.filter(models::batch_commit::Column::Index.gt(0))
11221137
.column_as(
1123-
Expr::col(models::batch_commit::Column::RevertedBlockNumber).max(),
1138+
models::batch_commit::Column::RevertedBlockNumber.max(),
11241139
"max_reverted_block_number",
11251140
)
1126-
.into_tuple::<(Option<i64>, Option<i64>, Option<i64>)>()
1141+
.into_tuple::<Option<i64>>()
11271142
.one(self.get_connection())
11281143
.await?
1129-
.and_then(|tuple| <[Option<i64>; 3]>::from(tuple).into_iter().flatten().max());
1144+
.flatten();
1145+
1146+
let latest_batch_event =
1147+
[max_block_number, max_finalized_block_number, max_reverted_block_number]
1148+
.into_iter()
1149+
.flatten()
1150+
.max();
11301151

11311152
let latest_l1_block_number =
11321153
[latest_l1_message, latest_batch_event].into_iter().flatten().max();

0 commit comments

Comments
 (0)