perf: wrap SQL queries in transaction #3670
Merged
+28
−2
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fixes #3669
Problem
During development,
processCollectionItemsexecutes SQL INSERT queries one at a time in a loop. SQLite by default wraps each statement in an implicit transaction with fsync to disk. With 300+ queries, this causes ~3.8 seconds of overhead.Solution
Wrap the SQL execution loop in an explicit transaction (
BEGIN TRANSACTION/COMMIT). This batches all queries into a single transaction with one fsync at the end.Important: D1 doesn't support transactions, so we conditionally skip the transaction wrapper for D1 databases by adding a
supportsTransactionsflag to the database interface.Benchmark
StackBlitz
CLI Reproduction
Verify fix
The
-fixedfolder uses pnpm patch to apply the fix locally.Changes
supportsTransactionsproperty toLocalDevelopmentDatabaseinterfacesupportsTransactions: database.type === 'sqlite'ingetLocalDatabasesupportsTransactionsis trueWhy this works
SQLite by default wraps each statement in an implicit transaction. When you run 323 INSERT statements individually, SQLite does 323 separate transactions (with fsync to disk each time). Wrapping them in a single explicit transaction does one fsync at the end.
Discovered in: https://github.com/nimiq/nimiq-website/tree/nuxt-content