Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(db): Make get_expected_l1_batch_timestamp() more efficient #963

Merged
merged 1 commit into from
Jan 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

This file was deleted.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

86 changes: 61 additions & 25 deletions core/lib/dal/src/blocks_web3_dal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -258,31 +258,67 @@ impl BlocksWeb3Dal<'_, '_> {
&mut self,
l1_batch_number: &ResolvedL1BatchForMiniblock,
) -> sqlx::Result<Option<u64>> {
let timestamp = sqlx::query!(
r#"
SELECT
timestamp
FROM
miniblocks
WHERE
(
$1::BIGINT IS NULL
AND l1_batch_number IS NULL
)
OR (l1_batch_number = $1::BIGINT)
ORDER BY
number
LIMIT
1
"#,
l1_batch_number
.miniblock_l1_batch
.map(|number| i64::from(number.0))
)
.fetch_optional(self.storage.conn())
.await?
.map(|row| row.timestamp as u64);
Ok(timestamp)
if let Some(miniblock_l1_batch) = l1_batch_number.miniblock_l1_batch {
Ok(sqlx::query!(
r#"
SELECT
timestamp
FROM
miniblocks
WHERE
l1_batch_number = $1
ORDER BY
number
LIMIT
1
"#,
i64::from(miniblock_l1_batch.0)
)
.fetch_optional(self.storage.conn())
.await?
.map(|row| row.timestamp as u64))
} else {
// Got a pending miniblock. Searching the timestamp of the first pending miniblock using
// `WHERE l1_batch_number IS NULL` is slow since it potentially locks the `miniblocks` table.
// Instead, we determine its number using the previous L1 batch, taking into the account that
// it may be stored in the `snapshot_recovery` table.
let prev_l1_batch_number = if l1_batch_number.pending_l1_batch == L1BatchNumber(0) {
return Ok(None); // We haven't created the genesis miniblock yet
} else {
l1_batch_number.pending_l1_batch - 1
};
Ok(sqlx::query!(
r#"
SELECT
timestamp
FROM
miniblocks
WHERE
number = COALESCE(
(
SELECT
MAX(number) + 1
FROM
miniblocks
WHERE
l1_batch_number = $1
),
(
SELECT
MAX(miniblock_number) + 1
FROM
snapshot_recovery
WHERE
l1_batch_number = $1
)
)
"#,
i64::from(prev_l1_batch_number.0)
)
.fetch_optional(self.storage.conn())
.await?
.map(|row| row.timestamp as u64))
}
}

pub async fn get_miniblock_hash(
Expand Down
Loading