Skip to content

Conversation

@jakeloo
Copy link
Member

@jakeloo jakeloo commented Aug 7, 2025

Summary by CodeRabbit

  • Refactor
    • Improved efficiency of database operations by batching multiple inserts and deletes into single queries, resulting in faster and more reliable data handling. No changes to user-facing features or functionality.

@jakeloo jakeloo marked this pull request as ready for review August 7, 2025 15:03
@coderabbitai
Copy link

coderabbitai bot commented Aug 7, 2025

Walkthrough

The code refactors several database write methods in the PostgresConnector by replacing explicit transaction handling and per-row prepared statements with single, dynamically constructed multi-row SQL queries. These changes affect insert and delete operations for block failures and staging data, consolidating multiple operations into single batched queries and simplifying control flow.

Changes

Cohort / File(s) Change Summary
PostgresConnector Batched Write Refactor
internal/storage/postgres.go
Refactored multiple methods to remove explicit transactions and prepared statements. Now constructs and executes single multi-row SQL queries for batched inserts (INSERT ... ON CONFLICT ... DO UPDATE) and deletes, dynamically generating parameter placeholders. Simplified control flow and error handling.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch jl/postgres-multirows

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
internal/storage/postgres.go (1)

238-263: Consider error handling for JSON marshaling in batch context.

While the individual JSON marshaling error handling is correct, a single marshaling failure will cause the entire batch to fail. Consider whether partial success handling would be beneficial.

If partial success is desired, consider pre-validating JSON marshaling:

+	// Pre-validate all JSON marshaling to avoid partial failures
+	jsonData := make([]string, len(data))
 	for i, blockData := range data {
 		blockDataJSON, err := json.Marshal(blockData)
 		if err != nil {
-			return err
+			return fmt.Errorf("failed to marshal block data at index %d: %w", i, err)
 		}
+		jsonData[i] = string(blockDataJSON)
+	}
+
+	for i, blockData := range data {
 		valueStrings = append(valueStrings, fmt.Sprintf("($%d, $%d, $%d)",
 			i*3+1, i*3+2, i*3+3))
 		valueArgs = append(valueArgs,
 			blockData.Block.ChainId.String(),
 			blockData.Block.Number.String(),
-			string(blockDataJSON),
+			jsonData[i],
 		)
 	}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 86675ea and 1a67ed3.

📒 Files selected for processing (1)
  • internal/storage/postgres.go (3 hunks)
🔇 Additional comments (5)
internal/storage/postgres.go (5)

154-167: LGTM! Efficient parameter placeholder generation.

The dynamic SQL construction with numbered placeholders ($1, $2, etc.) correctly prevents SQL injection while building efficient multi-row INSERT statements. The parameter indexing logic i*5+1 through i*5+5 is accurate for the 5 columns per row.


187-200: LGTM! Clean tuple-based DELETE implementation.

The multi-row DELETE using tuple syntax (chain_id, block_number) IN (($1, $2), ($3, $4), ...) is efficient and properly parameterized. The indexing logic i*2+1, i*2+2 correctly handles the 2 parameters per tuple.


331-344: LGTM! Consistent DELETE pattern implementation.

The implementation follows the same efficient pattern as DeleteBlockFailures, using tuple-based deletion with proper parameter indexing. The code is clean and SQL injection-safe.


153-179: Ensure batch size stays within PostgreSQL’s 65,535-parameter limit

PostgreSQL permits at most 65,535 parameters per statement. Since you’re using 5 parameters per failure row, each batch must contain at most 13,107 entries. Otherwise you’ll hit a “too many parameters” error.

Suggested fixes:

  • File: internal/storage/postgres.go (lines ~153–179)
    • Before building valueStrings/valueArgs, split failures into chunks of maxRows = 65535/5 = 13107.
    • Loop over each chunk and execute an INSERT … ON CONFLICT for that subset.

Example patch:

@@ internal/storage/postgres.go:150
-   // Build multi-row INSERT without transaction for better performance
-   valueStrings := make([]string, 0, len(failures))
-   valueArgs := make([]interface{}, 0, len(failures)*5)
-
-   for i, failure := range failures {
+const (
+   maxParams     = 65535
+   paramsPerRow  = 5
+   maxRowsPerBatch = maxParams / paramsPerRow // 13107
+)
+
+// Split failures into batches to avoid exceeding PostgreSQL’s parameter limit
+for start := 0; start < len(failures); start += maxRowsPerBatch {
+   end := start + maxRowsPerBatch
+   if end > len(failures) {
+       end = len(failures)
+   }
+   batch := failures[start:end]
+   valueStrings := make([]string, 0, len(batch))
+   valueArgs := make([]interface{}, 0, len(batch)*paramsPerRow)
+
+   for i, failure := range batch {
        valueStrings = append(valueStrings, fmt.Sprintf("($%d, $%d, $%d, $%d, $%d)",
            i*5+1, i*5+2, i*5+3, i*5+4, i*5+5))
        valueArgs = append(valueArgs,
            failure.ChainId.String(),
            failure.BlockNumber.String(),
            failure.FailureTime.Unix(),
            failure.FailureCount,
            failure.FailureReason,
        )
    }
+
+   query := fmt.Sprintf(`INSERT INTO block_failures (chain_id, block_number, last_error_timestamp, failure_count, reason)
+            VALUES %s
+            ON CONFLICT (chain_id, block_number) 
+            DO UPDATE SET 
+                last_error_timestamp = EXCLUDED.last_error_timestamp,
+                failure_count = EXCLUDED.failure_count,
+                reason = EXCLUDED.reason,
+                updated_at = NOW()`, strings.Join(valueStrings, ","))
+
+   if _, err := p.db.Exec(query, valueArgs...); err != nil {
+       return err
+   }
+}
+return nil

[f​ix_required]


153-179: StoreBlockFailures remains atomic without explicit transaction

  • A search for StoreBlockFailures usages found no callers grouping multiple methods into one transaction.
  • PostgreSQL guarantees per-statement atomicity for INSERT … ON CONFLICT, so removing the explicit transaction wrapper does not weaken consistency here.

@jakeloo jakeloo merged commit 0381b98 into main Aug 7, 2025
5 checks passed
@jakeloo jakeloo deleted the jl/postgres-multirows branch August 7, 2025 15:27
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.

3 participants