Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create interface for valid tables #14

Merged
merged 2 commits into from
Jan 13, 2025
Merged

Conversation

traviolus
Copy link
Collaborator

@traviolus traviolus commented Jan 13, 2025

Instead of keep adding if-else for each table we add. We introduce the ValidTablesMap to keep track of valid table names and their corresponding struct. Therefore we do not have to repeat adding table names in multiple files and occasions, also making it easier to add and unmarshalling new tables.

Summary by CodeRabbit

  • Refactor

    • Introduced a new ValidTable interface to improve type mapping and table handling.
    • Simplified row fetching and pruning logic across database-related functions.
    • Enhanced code maintainability by centralizing table type management.
  • Bug Fixes

    • Improved error handling for invalid table names during row pruning operations.

@traviolus traviolus requested a review from SeUkKim January 13, 2025 09:05
Copy link

coderabbitai bot commented Jan 13, 2025

Walkthrough

The pull request refactors the row pruning mechanism in the informative indexer. It introduces a ValidTablesMap and a ValidTable interface to streamline the handling of different table types. The previous conditional logic for determining table types has been replaced with a more flexible mapping system, enhancing maintainability and clarity in the code. The changes also improve error handling and centralize the unmarshalling logic for database rows.

Changes

File Change Summary
informative-indexer/db/valid_tables.go - Added ValidTable interface with Unmarshal method
- Created ValidTablesMap to map table names to their corresponding types
- Updated isValidTableName and GetValidTableNames functions
informative-indexer/db/db.go - Simplified GetRowsToPruneByBlockHeight function
- Replaced conditional type assignment with direct mapping from ValidTablesMap
informative-indexer/prunner/prunner.go - Refactored fetchRowsToPrune function
- Implemented generic row unmarshalling using ValidTablesMap
- Improved error handling for table type retrieval

Sequence Diagram

sequenceDiagram
    participant Prunner
    participant ValidTablesMap
    participant Database
    
    Prunner->>ValidTablesMap: Check table type
    ValidTablesMap-->>Prunner: Return table interface
    Prunner->>Database: Fetch rows to prune
    Database-->>Prunner: Return database rows
    Prunner->>ValidTablesMap: Unmarshal rows using table interface
    ValidTablesMap-->>Prunner: Return unmarshalled data
Loading

Poem

🐰 A Rabbit's Ode to Code Refactoring 🥕

With maps and interfaces so neat,
Our pruning logic now looks sweet.
No more branches, just one clear way
To handle tables day by day.
Refactoring, oh what a delight! 🎉

Finishing Touches

  • 📝 Generate Docstrings (Beta)

🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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: 1

🧹 Nitpick comments (4)
informative-indexer/db/valid_tables.go (3)

9-12: Consider using constants for table names.

Table names are used as string literals in multiple places. Consider defining them as constants to prevent typos and enable compile-time checks.

+const (
+    TableTransactionEvents    = "transaction_events"
+    TableFinalizeBlockEvents = "finalize_block_events"
+    TableMoveEvents          = "move_events"
+)

 var ValidTablesMap = map[string]ValidTable{
-    "transaction_events":    &TransactionEvent{},
-    "finalize_block_events": &FinalizeBlockEvent{},
-    "move_events":           &MoveEvent{},
+    TableTransactionEvents:    &TransactionEvent{},
+    TableFinalizeBlockEvents: &FinalizeBlockEvent{},
+    TableMoveEvents:          &MoveEvent{},
 }

Line range hint 16-21: Optimize table name validation.

The current implementation iterates through the map keys. Consider using direct map lookup for better performance.

 func isValidTableName(tableName string) bool {
-    for validTable, _ := range ValidTablesMap {
-        if tableName == validTable {
-            return true
-        }
-    }
-    return false
+    _, ok := ValidTablesMap[tableName]
+    return ok
 }

25-29: Optimize slice allocation in GetValidTableNames.

Preallocate the slice with the known capacity to avoid reallocation during append.

 func GetValidTableNames() []string {
-    var keys []string
+    keys := make([]string, 0, len(ValidTablesMap))
     for key := range ValidTablesMap {
         keys = append(keys, key)
     }
     return keys
 }
informative-indexer/prunner/prunner.go (1)

130-137: Consider batch processing for better performance.

Processing rows one at a time might be inefficient for large datasets. Consider implementing batch processing if supported by the underlying implementations.

Additionally, preallocate the result slice if the number of rows can be determined:

-    var result []interface{}
+    result := make([]interface{}, 0, estimatedSize) // if rows.CommandTag().RowsAffected() is available
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1683881 and c896406.

📒 Files selected for processing (3)
  • informative-indexer/db/db.go (1 hunks)
  • informative-indexer/db/valid_tables.go (2 hunks)
  • informative-indexer/prunner/prunner.go (1 hunks)
🔇 Additional comments (2)
informative-indexer/db/valid_tables.go (1)

5-7: LGTM! Well-designed interface.

The ValidTable interface is well-defined with a single responsibility of unmarshalling rows.

informative-indexer/prunner/prunner.go (1)

134-137: LGTM! Proper error handling.

The implementation correctly checks for errors during unmarshalling and provides clear error messages.

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)
informative-indexer/db/valid_tables.go (3)

5-7: Add documentation and consider type safety improvements.

The ValidTable interface would benefit from:

  1. GoDoc comments explaining its purpose and usage
  2. Documentation about expected map keys and values
  3. Consider using a more type-safe approach instead of map[string]interface{}
+// ValidTable defines the interface for database tables that can unmarshal their rows
+// into a structured format. Implementers should document the expected keys and values
+// in the returned map.
 type ValidTable interface {
 	Unmarshal(pgx.Rows) (map[string]interface{}, error)
 }

15-18: Add documentation for public functions.

The isValidTableName function should have GoDoc comments explaining its purpose and parameters.

+// isValidTableName checks if the given table name exists in the ValidTablesMap.
+// It returns true if the table name is valid, false otherwise.
 func isValidTableName(tableName string) bool {
 	_, ok := ValidTablesMap[tableName]
 	return ok
 }

20-25: Consider caching the table names slice.

Since the table names are static, consider caching the slice to avoid allocations on every call to GetValidTableNames().

+var validTableNamesCache []string
+
+func init() {
+	validTableNamesCache = make([]string, 0, len(ValidTablesMap))
+	for key := range ValidTablesMap {
+		validTableNamesCache = append(validTableNamesCache, key)
+	}
+}
+
+// GetValidTableNames returns a slice of all valid table names.
 func GetValidTableNames() []string {
-	var keys []string
-	for key := range ValidTablesMap {
-		keys = append(keys, key)
-	}
-	return keys
+	return append([]string{}, validTableNamesCache...)
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c896406 and ea305f6.

📒 Files selected for processing (2)
  • informative-indexer/db/db.go (1 hunks)
  • informative-indexer/db/valid_tables.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • informative-indexer/db/db.go
🔇 Additional comments (1)
informative-indexer/db/valid_tables.go (1)

1-25: Overall implementation looks good!

The new design successfully achieves the PR objectives by:

  1. Centralizing table definitions
  2. Providing a clean interface for table operations
  3. Eliminating the need for multiple if-else statements

The suggested improvements are mostly for optimization and documentation, but the core implementation is solid.

@SeUkKim SeUkKim merged commit 558c132 into main Jan 13, 2025
1 check passed
@SeUkKim SeUkKim deleted the feat/valid-table-interface branch January 13, 2025 09:30
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