Skip to content

⚡ Bolt: [performance improvement] Optimize SQL statement generation in D1ExportContext#307

Open
bashandbone wants to merge 1 commit into
mainfrom
bolt/optimize-d1-statement-generation-7526701624554838168
Open

⚡ Bolt: [performance improvement] Optimize SQL statement generation in D1ExportContext#307
bashandbone wants to merge 1 commit into
mainfrom
bolt/optimize-d1-statement-generation-7526701624554838168

Conversation

@bashandbone

@bashandbone bashandbone commented Jun 11, 2026

Copy link
Copy Markdown
Contributor

💡 What:
Replaced intermediate Vec<String> allocations and format!() usage with a pre-allocated String and std::fmt::Write operations for constructing upsert and delete SQL statements in D1ExportContext.

🎯 Why:
Generating SQL dynamically with vectors and string joining causes unnecessary memory churn and heap allocations in performance-critical code paths, which degrades statement construction speed inside the caching layer. By shifting to a pre-allocated capacity String with incremental write!() calls, we prevent these multiple allocations.

📊 Impact:
Running cargo bench --bench d1_profiling statement_generation showed that the statement generation times reduced significantly:

  • build_upsert_statement time went from ~1.77 µs down to ~617 ns (a ~65% reduction).
  • build_delete_statement time went from ~501 ns down to ~209 ns (a ~58% reduction).

🔬 Measurement:

  1. Run cargo bench --bench d1_profiling statement_generation.
  2. Inspect the benchmark times before and after this optimization to see the measured reductions.

PR created automatically by Jules for task 7526701624554838168 started by @bashandbone

Summary by Sourcery

Optimize dynamic SQL statement construction in D1ExportContext for better performance when generating upsert and delete statements.

Enhancements:

  • Rewrite D1ExportContext upsert and delete SQL generation to use pre-allocated strings and formatted writes to reduce allocations and improve throughput.

Documentation:

  • Document the SQL string generation optimization and its rationale in the Bolt performance notes.

Co-authored-by: bashandbone <89049923+bashandbone@users.noreply.github.com>
@google-labs-jules

Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@sourcery-ai

sourcery-ai Bot commented Jun 11, 2026

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Optimizes SQL statement generation in D1ExportContext by replacing intermediate Vec-based string assembly and format! calls with preallocated String buffers and incremental std::fmt::Write usage for upsert and delete queries, and documents the performance learning in the Bolt guide.

Flow diagram for optimized SQL upsert statement generation

flowchart TD
    A["D1ExportContext::build_upsert_statement"]
    B["Compute num_keys, num_values, total_cols"]
    C["Init params Vec with_capacity(total_cols)"]
    D["Init sql String::with_capacity(...)"]
    E["Write INSERT INTO and opening parenthesis"]
    F["Iterate key_fields_schema and key.0"]
    G["Append column names for keys to sql"]
    H["Push key params via key_part_to_json"]
    I["Iterate value_fields_schema and values.fields"]
    J["Append column names for values to sql"]
    K["Push value params via value_to_json"]
    L["Append VALUES clause and ? placeholders to sql"]
    M["Append ON CONFLICT DO UPDATE SET"]
    N["Iterate value_fields_schema for update_clauses"]
    O["Write name = excluded.name into sql"]
    P["Return (sql, params)"]

    A --> B
    B --> C
    C --> D
    D --> E
    E --> F
    F --> G
    G --> H
    H --> I
    I --> J
    J --> K
    K --> L
    L --> M
    M --> N
    N --> O
    O --> P
Loading

File-Level Changes

Change Details Files
Optimize upsert SQL generation to avoid intermediate allocations and improve performance.
  • Replace Vec-based collection of column names, placeholders, and update clauses with direct writes into a single String buffer using std::fmt::Write and push_str.
  • Precompute counts of key and value fields to size the params Vec and SQL String capacity up front.
  • Iterate key and value schemas to append column names and construct the VALUES placeholder list directly into the SQL string while building the params vector.
  • Generate ON CONFLICT DO UPDATE SET clause via direct formatted writes over value fields instead of building and joining an update_clauses vector.
crates/flow/src/targets/d1.rs
Optimize delete SQL generation by constructing the WHERE clause directly into a preallocated String.
  • Precompute the number of key fields to size params and SQL String capacity.
  • Write the DELETE FROM ... WHERE prefix and append each key comparison with write! and push_str, joining via AND logic without an intermediate vector.
  • Accumulate bound parameter values while iterating the key fields, matching the constructed predicates.
crates/flow/src/targets/d1.rs
Document the SQL string generation performance optimization in the Bolt engineering notes.
  • Add a dated performance note describing the overhead of vector-based SQL construction in D1ExportContext.
  • Record the recommended practice of using preallocated String and write! macros for performance-critical SQL construction paths.
.jules/bolt.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've left some high level feedback:

  • The new write! calls all use unwrap(), which will panic on unexpected formatting errors; consider either propagating fmt::Error or using a helper function that safely writes to String to avoid panics in these hot paths.
  • The preallocation formulas for sql (64 + total_cols * 15 + num_values * 30, 32 + num_keys * 20) are a bit opaque; extracting these into named constants or documenting the rationale would make future tuning and maintenance easier.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The new `write!` calls all use `unwrap()`, which will panic on unexpected formatting errors; consider either propagating `fmt::Error` or using a helper function that safely writes to `String` to avoid panics in these hot paths.
- The preallocation formulas for `sql` (`64 + total_cols * 15 + num_values * 30`, `32 + num_keys * 20`) are a bit opaque; extracting these into named constants or documenting the rationale would make future tuning and maintenance easier.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant