Skip to content

Conversation

@nischitpra
Copy link
Collaborator

@nischitpra nischitpra commented Jul 25, 2025

Summary by CodeRabbit

  • Bug Fixes
    • Enhanced wallet address filtering in transaction queries by splitting into separate queries combined with UNION ALL for improved accuracy.
  • Refactor
    • Centralized and modularized query construction to streamline query building and improve maintainability.
  • Tests
    • Added tests to validate UNION query generation and behavior under different filtering and grouping conditions.

@coderabbitai
Copy link

coderabbitai bot commented Jul 25, 2025

Walkthrough

The codebase introduces a modular query builder for ClickHouse, centralizing SQL construction and adding specialized UNION query logic for wallet address filtering in the "transactions" table. The GetAggregations method now delegates query formation to these new helpers. Corresponding tests validate the new query logic, especially the UNION handling and clause correctness.

Changes

File(s) Change Summary
internal/storage/clickhouse.go Refactored GetAggregations to use new modular query builders; added buildQuery, buildStandardQuery, buildUnionQuery, addPostQueryClauses, buildWhereClauses, and TestQueryGeneration; changed wallet address filtering for "transactions" to use UNION ALL on from_address and to_address.
internal/storage/clickhouse_connector_test.go Added TestUnionQueryLogic to verify SQL generation for UNION queries and clause correctness under various filters and grouping scenarios.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant ClickHouseConnector
    participant QueryBuilder

    Caller->>ClickHouseConnector: GetAggregations(table, qf)
    ClickHouseConnector->>QueryBuilder: buildQuery(table, columns, qf)
    alt table == "transactions" and wallet address filter present
        QueryBuilder->>QueryBuilder: buildUnionQuery(table, columns, qf)
        QueryBuilder->>QueryBuilder: addPostQueryClauses(unionQuery, qf)
    else
        QueryBuilder->>QueryBuilder: buildStandardQuery(table, columns, qf)
        QueryBuilder->>QueryBuilder: addPostQueryClauses(standardQuery, qf)
    end
    ClickHouseConnector->>ClickHouseConnector: Execute built query
    ClickHouseConnector-->>Caller: Return QueryResult
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fde71d2 and c96d5f4.

📒 Files selected for processing (1)
  • internal/storage/clickhouse.go (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
internal/storage/clickhouse.go (1)
internal/storage/connector.go (1)
  • QueryFilter (11-27)
🔇 Additional comments (6)
internal/storage/clickhouse.go (6)

473-474: LGTM! Good refactoring to centralize query building logic.

The delegation to the new buildQuery method improves code organization and maintainability by centralizing SQL construction logic.


555-569: Well-structured query routing logic.

The method correctly routes between standard and UNION query strategies based on table type and wallet address presence, ensuring consistent post-query clause application.


571-586: Clean implementation of standard query building.

The method properly constructs standard queries with good separation of concerns by delegating WHERE clause construction to buildWhereClauses.


639-684: Well-handled complexity of post-query clause application.

The method correctly handles the different syntax requirements between UNION and standard queries, properly wrapping UNION queries in subqueries for GROUP BY and applying appropriate ORDER BY and LIMIT logic.


686-727: Good refactoring of WHERE clause construction.

The method properly modularizes WHERE clause building and correctly skips wallet address handling for transactions table when UNION queries are used, as this is handled separately in the UNION logic.


2123-2126: Good testing practice to expose query building logic.

This helper method enables comprehensive unit testing of the query generation logic, which is essential for verifying the correctness of the complex UNION query handling.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch np/wallet_address_query_split

🪧 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.
    • @coderabbitai modularize this function.
  • 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.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

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.

@nischitpra nischitpra changed the title wallet address query spelit wallet address query split Jul 25, 2025
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: 1

🧹 Nitpick comments (3)
internal/storage/clickhouse.go (2)

555-569: Consider validating wallet address format.

The method checks if qf.WalletAddress != "" but doesn't validate if it's a valid Ethereum address format. Consider adding validation to prevent potential SQL injection or invalid queries.

 func (c *ClickHouseConnector) buildQuery(table, columns string, qf QueryFilter) string {
 	var query string
 
 	// Check if we need to handle wallet address with UNION for transactions
-	if table == "transactions" && qf.WalletAddress != "" {
+	if table == "transactions" && qf.WalletAddress != "" && ethereum.IsHexAddress(qf.WalletAddress) {
 		query = c.buildUnionQuery(table, columns, qf)
 	} else {
 		query = c.buildStandardQuery(table, columns, qf)
 	}

2092-2095: Consider alternative testing approach.

Exposing internal methods for testing can lead to maintenance issues. Consider testing through the public API or using a test-specific interface.

Instead of exposing internal methods, you could:

  1. Test through the public GetAggregations or GetTransactions methods
  2. Create a separate test helper that doesn't pollute the production code
  3. Use dependency injection to make the query builder testable

If you must keep this approach, consider adding a build tag to exclude it from production builds:

// +build test

// TestQueryGeneration is only available in test builds
func (c *ClickHouseConnector) TestQueryGeneration(table, columns string, qf QueryFilter) string {
    return c.buildQuery(table, columns, qf)
}
internal/storage/clickhouse_connector_test.go (1)

111-249: Comprehensive test coverage for UNION query logic.

Good test coverage for the new query building functionality. Consider these improvements:

  1. The hardcoded connection details might fail in different environments
  2. String-based assertions are fragile - consider parsing the SQL or using a SQL parser library
  3. Add test cases for edge cases like empty wallet address or special characters

Consider adding these test cases:

// Test case 5: Empty wallet address should use standard query
t.Run("Empty wallet address", func(t *testing.T) {
    qf := QueryFilter{
        ChainId:       big.NewInt(8453),
        WalletAddress: "",
        Limit:         5,
    }
    
    query := connector.TestQueryGeneration("transactions", "*", qf)
    
    if strings.Contains(query, "UNION ALL") {
        t.Errorf("Empty wallet address should not trigger UNION query: %s", query)
    }
})

// Test case 6: Special characters in wallet address (to verify escaping)
t.Run("Wallet address with special characters", func(t *testing.T) {
    qf := QueryFilter{
        ChainId:       big.NewInt(8453),
        WalletAddress: "0x'; DROP TABLE transactions; --",
        Limit:         5,
    }
    
    query := connector.TestQueryGeneration("transactions", "*", qf)
    
    // Verify the address is properly handled (though this would still be vulnerable with current implementation)
    if strings.Contains(query, "DROP TABLE") {
        t.Errorf("SQL injection attempt should be escaped: %s", query)
    }
})
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8d15fa9 and 5cbdeee.

📒 Files selected for processing (2)
  • internal/storage/clickhouse.go (3 hunks)
  • internal/storage/clickhouse_connector_test.go (5 hunks)
🔇 Additional comments (4)
internal/storage/clickhouse.go (3)

469-526: Clean refactoring of query construction logic.

The delegation to buildQuery improves code organization and maintainability by centralizing the SQL construction logic.


655-696: Well-structured WHERE clause building.

Good separation of concerns by extracting WHERE clause logic and correctly handling the special case for wallet address in transactions table.


621-653: Verify GROUP BY behavior with UNION ALL subqueries

When wrapping a UNION ALL query in a subquery, the current code does:

SELECT * FROM (<union-query>) GROUP BY …

Using SELECT * can break if the union’s columns don’t exactly match those listed in the GROUP BY (or aren’t aggregated), leading to SQL errors. Please:

  • Manually verify any existing UNION ALL + GROUP BY use cases to ensure the returned columns align.
  • Add or update tests covering UNION ALL queries with GROUP BY to catch mismatches.
  • Consider replacing SELECT * with an explicit column list (only grouping keys and aggregated columns) or validating the column set before wrapping.
internal/storage/clickhouse_connector_test.go (1)

14-109: Test updates correctly reflect the type mapping changes.

The updated test cases properly validate the pointer-based type mapping, including double pointers for nullable types.

@nischitpra nischitpra merged commit c0d6438 into main Jul 25, 2025
6 checks passed
@nischitpra nischitpra deleted the np/wallet_address_query_split branch July 25, 2025 21:39
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