Skip to content

⚡ Bolt: [performance improvement] Optimize D1 query generation#236

Open
bashandbone wants to merge 1 commit into
mainfrom
bolt/optimize-d1-query-generation-12786738793941327599
Open

⚡ Bolt: [performance improvement] Optimize D1 query generation#236
bashandbone wants to merge 1 commit into
mainfrom
bolt/optimize-d1-query-generation-12786738793941327599

Conversation

@bashandbone
Copy link
Copy Markdown
Contributor

@bashandbone bashandbone commented May 16, 2026

💡 What: Replaced intermediate vector allocations (columns, placeholders, update_clauses, where_clauses) in D1 query builders (build_upsert_stmt, build_delete_stmt) with a pre-allocated String using String::with_capacity and std::fmt::Write.

🎯 Why: SQL query generation happens frequently during D1 target synchronization. The previous implementation used multiple Vec<String> allocations and format! / join operations per query, causing unnecessary memory allocation and string copying overhead.

📊 Impact: Significantly reduces heap allocations and string formatting overhead for every D1 upsert and delete statement generated, leading to faster execution and less GC/memory churn during export operations.

🔬 Measurement: Verified by running formatting, linting, and targeted D1 target tests (cargo test -p thread-flow --test d1_target_tests --test d1_minimal_tests --test d1_cache_integration), ensuring no regressions and that the generated SQL exactly matches the previous logic.


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

Summary by Sourcery

Optimize D1 SQL upsert and delete statement generation to reduce allocations and improve performance during target synchronization.

Enhancements:

  • Replace intermediate vectors with preallocated SQL strings and direct writes in D1 upsert and delete builders to minimize memory allocations.
  • Tidy up string handling and formatting in AST and rule engine modules for clearer, more consistent code.

This replaces intermediate `Vec<String>` allocations with `String::with_capacity` and `write!` macro in the `build_upsert_stmt` and `build_delete_stmt` functions within `crates/flow/src/targets/d1.rs`.

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.

Copilot AI review requested due to automatic review settings May 16, 2026 17:45
@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented May 16, 2026

Reviewer's Guide

Refactors D1 upsert/delete SQL generation to build queries directly into pre-allocated Strings using fmt::Write, reducing intermediate allocations, and makes a few minor formatting/closure-style cleanups elsewhere in the codebase.

File-Level Changes

Change Details Files
Optimize D1 upsert SQL generation to avoid intermediate vector allocations and string joins.
  • Replace separate vectors for column names, placeholders, and update clauses with a single String buffer built via String::with_capacity and write!/push_str
  • Append key column names and value column names directly into the SQL buffer while simultaneously building the params vector
  • Generate the VALUES placeholder list by iterating over params and pushing '?' with comma separators
  • Generate ON CONFLICT DO UPDATE SET clause in-place by iterating value_fields_schema and writing assignments into the same buffer
crates/flow/src/targets/d1.rs
Optimize D1 delete SQL generation by building the WHERE clause directly into a pre-allocated String.
  • Introduce a single SQL buffer initialized with DELETE FROM ... WHERE and write!/push_str for subsequent fragments
  • Pre-allocate params vector based on key_fields_schema length
  • Iterate key_fields_schema and append name = ? conditions directly, joining with AND using a first-element flag
crates/flow/src/targets/d1.rs
Apply minor formatting and style cleanups in AST and rule engine modules.
  • Reformat a from_utf8 unwrap_or_else call onto fewer lines without changing behavior
  • Split a long assert_eq! into multiple lines for readability
  • Expand Rule::Pattern branch in defined_vars into a multi-line iterator chain for clarity
  • Condense a Registration::read lock/unwrap_or_else chain into a single line
crates/ast-engine/src/tree_sitter/mod.rs
crates/rule-engine/src/rule/mod.rs
crates/rule-engine/src/rule/referent_rule.rs

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

Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

Hey - I've found 1 issue, and left some high level feedback:

  • In build_upsert_stmt, the number of VALUES placeholders is derived from params.len(), which implicitly assumes all params are for the insert columns only; consider tracking a dedicated placeholder count so this logic remains correct if additional parameters (e.g., for WHERE/RETURNING) are introduced in the future.
  • The write! calls on a String cannot realistically fail except for formatting issues; if you don't expect dynamic formatting errors, using expect or an internal helper to avoid repetitive map_err(|e| RecocoError::internal_msg(e.to_string())) boilerplate could simplify the control flow.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `build_upsert_stmt`, the number of `VALUES` placeholders is derived from `params.len()`, which implicitly assumes all params are for the insert columns only; consider tracking a dedicated placeholder count so this logic remains correct if additional parameters (e.g., for WHERE/RETURNING) are introduced in the future.
- The `write!` calls on a `String` cannot realistically fail except for formatting issues; if you don't expect dynamic formatting errors, using `expect` or an internal helper to avoid repetitive `map_err(|e| RecocoError::internal_msg(e.to_string()))` boilerplate could simplify the control flow.

## Individual Comments

### Comment 1
<location path="crates/flow/src/targets/d1.rs" line_range="347-350" />
<code_context>
+            sql.push('?');
+        }
+
+        sql.push_str(") ON CONFLICT DO UPDATE SET ");
+
+        first = true;
+        for (idx, _value) in values.fields.iter().enumerate() {
+            if let Some(value_field) = self.value_fields_schema.get(idx) {
+                if !first {
</code_context>
<issue_to_address>
**issue (bug_risk):** Handle the case where there are no value fields to update in the `ON CONFLICT` clause

If `values.fields` contains no `value_field`s (e.g. only key columns or an empty payload), this will emit `... ON CONFLICT DO UPDATE SET ` with nothing after `SET`, which is invalid SQL. Since you’re already refactoring, consider guarding this case by falling back to `ON CONFLICT DO NOTHING` or omitting the `ON CONFLICT` clause when there are no updatable columns.
</issue_to_address>

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.

Comment on lines +347 to +350
sql.push_str(") ON CONFLICT DO UPDATE SET ");

first = true;
for (idx, _value) in values.fields.iter().enumerate() {
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.

issue (bug_risk): Handle the case where there are no value fields to update in the ON CONFLICT clause

If values.fields contains no value_fields (e.g. only key columns or an empty payload), this will emit ... ON CONFLICT DO UPDATE SET with nothing after SET, which is invalid SQL. Since you’re already refactoring, consider guarding this case by falling back to ON CONFLICT DO NOTHING or omitting the ON CONFLICT clause when there are no updatable columns.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR optimizes D1 SQL statement generation by replacing temporary vector/string joins with direct preallocated String construction while preserving positional parameter ordering.

Changes:

  • Builds D1 upsert/delete SQL using String::with_capacity and write!.
  • Preallocates parameter vectors based on schema/value sizes.
  • Applies rustfmt-only formatting changes in unrelated rule/tree-sitter files.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated no comments.

File Description
crates/flow/src/targets/d1.rs Optimizes D1 upsert and delete SQL builders.
crates/rule-engine/src/rule/referent_rule.rs Formatting-only change.
crates/rule-engine/src/rule/mod.rs Formatting-only change.
crates/ast-engine/src/tree_sitter/mod.rs Formatting-only changes in string handling and a test assertion.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

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.

2 participants