Skip to content

Conversation

@jaipaljadeja
Copy link
Member

  • Fixes main process exiting on dev reloads
  • Changes flag names on cli args
  • Adds a validation for unknown args passed in cli, now throws error and prints help message.
  • Bumps drizzle-orm version in template
  • Fix cleanup query errors before initialization when --always-reindex flag is set
  • Adds indexerId relation to KV Store
  • Adds idColumn map support for table specific id column with wildcard support.
  • Adds validation to check if all tables in schema has provided idColumns.

@coderabbitai
Copy link

coderabbitai bot commented Mar 21, 2025

📝 Walkthrough

Walkthrough

Multiple new JSON metadata files were added for prerelease versions of various Apibara packages, including plugins for Drizzle, Mongo, and SQLite, as well as the core Apibara package. Key changes include enhanced ID column mapping support, revised dependency versions, and refined transaction and cleanup flows. Additionally, the CLI commands were updated to include extra parameters and a new argument validation function, checkForUnknownArgs, improving both error handling and overall command structure.

Changes

File(s) Change Summary
change/@apibara-plugin-drizzle*.json, change/@apibara-plugin-mongo*.json, change/@apibara-plugin-sqlite*.json, change/apibara*.json Added new prerelease metadata files with comments, package names, emails, and dependent change types.
examples/cli-drizzle/indexers/2-starknet.indexer.ts
examples/cli-drizzle/package.json
Updated idColumn from a simple string to a mapping and upgraded the drizzle-orm dependency version.
packages/cli/src/cli/commands/{add,build,dev,init,prepare,start}.ts Modified command method signatures to include a new cmd parameter; added checkForUnknownArgs calls and renamed certain arguments.
packages/cli/src/cli/common.ts Introduced new asynchronous function checkForUnknownArgs for validating unknown CLI arguments.
packages/cli/src/create/constants.ts Upgraded drizzle-orm version from ^0.37.0 to ^0.40.1.
packages/plugin-drizzle/src/{index.ts,storage.ts,utils.ts} Enhanced idColumn handling by adding support for a mapping, including new type definitions and validation logic.
packages/plugin-mongo/src/index.ts Restructured transaction management and logging, consolidating reindexing operations within a single transaction.
packages/plugin-sqlite/src/{index.ts,kv.ts,persistence.ts}
packages/plugin-sqlite/tests/kv.test.ts
Added indexerId support, revised logging and cleanup strategies, and adjusted SQL statements and tests to accommodate the new field.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant C as CLI Command
    participant V as checkForUnknownArgs
    participant E as Execution Logic

    U->>C: Run command with args & cmd
    C->>V: Validate arguments (args, cmd)
    V-->>C: Return validation (or exit on error)
    C->>E: Proceed with command operations
Loading
sequenceDiagram
    participant D as DrizzleStorage
    participant M as getIdColumnForTable
    participant V as Validation

    D->>M: Request id column for table from idColumnMap
    M-->>D: Return specific id column (or fallback)
    D->>V: Validate id column against schema
    V-->>D: Confirm validity or throw error
    D->>D: Execute storage operations using mapped id columns
Loading

Possibly related PRs

  • feat: handle pending blocks #157: The changes in the main PR, which introduce a new JSON file for the @apibara/plugin-drizzle package with a focus on idColumn map support, are related to the retrieved PR that also modifies the @apibara/plugin-drizzle package to handle pending blocks.
  • example: add factory mode and pglite persistence #123: The changes in the main PR, which involve the addition of a JSON file for the @apibara/plugin-drizzle package with support for idColumn mapping, are related to the modifications in the retrieved PR that also introduce a new external dependency, @electric-sql/pglite, which is relevant for database handling and persistence.
  • add mongo sink and some fixes for drizzle sink #127: The changes in the main PR, which involve the addition of idColumn map support in the @apibara/plugin-drizzle, are related to the modifications in the retrieved PR that also involve the drizzle sink, specifically in how it handles data and integrates with the database.

Poem

I'm a hopping rabbit full of cheer,
Celebrating code changes far and near.
JSON files, mappings, and CLI delight,
Each little fix makes my heart take flight.
With every hop, I say, "Let's code right!" 🐇


📜 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 ad00b3d and 010e0f9.

📒 Files selected for processing (1)
  • packages/plugin-drizzle/src/index.ts (8 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
packages/plugin-drizzle/src/index.ts (2)
packages/plugin-drizzle/src/utils.ts (3)
  • IdColumnMap (52-57)
  • DrizzleStorageError (11-16)
  • getIdColumnForTable (59-69)
packages/plugin-drizzle/src/storage.ts (3)
  • cleanupStorage (342-382)
  • invalidate (186-315)
  • registerTriggers (123-159)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test
🔇 Additional comments (12)
packages/plugin-drizzle/src/index.ts (12)

35-41: Good refactoring of imports to support the new ID column mapping feature.

The updated imports properly include all necessary components for the new ID column mapping functionality, including the IdColumnMap type and getIdColumnForTable utility function.


45-46: Good addition of type export.

Exporting the IdColumnMap type makes it available for consumers of this package, which is essential for proper type checking when using the updated API.


100-125: Excellent documentation for the enhanced idColumn feature.

The documentation clearly explains both usage patterns (string for all tables vs. object mapping) with practical examples. The wildcard ("*") functionality is well-documented, making it easy for developers to understand how to use this feature for complex database schemas.


154-156: Minor change to variable naming.

The addition of the underscore in _schema indicates it might be used differently than before, likely to avoid shadowing the local schema variable defined below.


163-167: Good implementation of the ID column mapping.

The code properly handles both string and object values for idColumn, setting up a well-structured idColumnMap with appropriate defaults. This implementation supports the flexible configuration described in the documentation.


177-192: Excellent validation to prevent runtime errors.

This validation ensures that all specified ID columns actually exist in their respective tables, which prevents cryptic runtime errors that would be difficult to debug. The error message is clear and provides actionable guidance to developers.


211-212: Good addition of cleanup tracking.

Adding the cleanupApplied flag helps prevent redundant cleanup operations during reindexing.


227-241: Well-structured reindexing cleanup logic.

The updated code properly:

  1. Conditions cleanup on both alwaysReindex and !cleanupApplied
  2. Uses the cleanupApplied flag to prevent redundant operations
  3. Provides clear logging before and after the cleanup
  4. Handles both storage cleanup and persistence reset when needed

This is a significant improvement that prevents unnecessary operations.


295-296: Good update to use the idColumnMap.

The comment and code update properly reflect the use of the new idColumnMap parameter instead of a single idColumn string, ensuring that the correct ID column is used for each table during invalidation.


346-347: Consistent use of idColumnMap across invalidate calls.

This change maintains consistency with the previous update, ensuring all invalidate operations use the appropriate ID column for each table.


377-377: Consistent use of idColumnMap in pending finality handling.

This final update to the invalidate call ensures that the appropriate ID column mapping is used when handling blocks with pending finality.


381-386: Updated registerTriggers call to use idColumnMap.

The registerTriggers function call has been properly updated to use the new idColumnMap parameter, ensuring triggers are created with the correct ID column for each table.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
  • @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)
packages/cli/src/cli/commands/init.ts (1)

23-28: Replace placeholder description for create-indexer flag.

The argument has been renamed from noIndexer to create-indexer which is more intuitive (positive wording instead of negative), but the description is set to "TODO" and should be replaced with a proper description explaining what this flag does.

  "create-indexer": {
    type: "boolean",
    name: "create-indexer",
    default: true,
-   description: "TODO",
+   description: "Create an indexer as part of the project initialization | default: `true`",
  },
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5b563c6 and 754a39b.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (22)
  • change/@apibara-plugin-drizzle-fb22b1bc-f1ab-4299-a476-2ac25460956d.json (1 hunks)
  • change/@apibara-plugin-mongo-c9018c01-2b4f-4a5a-a7a7-e13eb567d66f.json (1 hunks)
  • change/@apibara-plugin-sqlite-22633833-27a0-4ae1-be3b-824b3514f5e2.json (1 hunks)
  • change/apibara-34f7f808-dcf6-45ec-bbe4-5e74b0193361.json (1 hunks)
  • examples/cli-drizzle/indexers/2-starknet.indexer.ts (1 hunks)
  • examples/cli-drizzle/package.json (1 hunks)
  • packages/cli/src/cli/commands/add.ts (2 hunks)
  • packages/cli/src/cli/commands/build.ts (2 hunks)
  • packages/cli/src/cli/commands/dev.ts (2 hunks)
  • packages/cli/src/cli/commands/init.ts (2 hunks)
  • packages/cli/src/cli/commands/prepare.ts (2 hunks)
  • packages/cli/src/cli/commands/start.ts (2 hunks)
  • packages/cli/src/cli/common.ts (1 hunks)
  • packages/cli/src/create/constants.ts (1 hunks)
  • packages/plugin-drizzle/src/index.ts (8 hunks)
  • packages/plugin-drizzle/src/storage.ts (8 hunks)
  • packages/plugin-drizzle/src/utils.ts (1 hunks)
  • packages/plugin-mongo/src/index.ts (1 hunks)
  • packages/plugin-sqlite/src/index.ts (9 hunks)
  • packages/plugin-sqlite/src/kv.ts (2 hunks)
  • packages/plugin-sqlite/src/persistence.ts (2 hunks)
  • packages/plugin-sqlite/tests/kv.test.ts (4 hunks)
🧰 Additional context used
🧬 Code Definitions (8)
packages/cli/src/cli/commands/add.ts (1)
packages/cli/src/cli/common.ts (1) (1)
  • checkForUnknownArgs (16-29)
packages/cli/src/cli/commands/build.ts (1)
packages/cli/src/cli/common.ts (1) (1)
  • checkForUnknownArgs (16-29)
packages/plugin-sqlite/src/persistence.ts (3)
packages/plugin-mongo/src/persistence.ts (1) (1)
  • resetPersistence (161-183)
packages/plugin-drizzle/src/persistence.ts (1) (1)
  • resetPersistence (322-341)
packages/plugin-sqlite/src/utils.ts (1) (1)
  • assertInTransaction (27-31)
packages/cli/src/cli/commands/start.ts (1)
packages/cli/src/cli/common.ts (1) (1)
  • checkForUnknownArgs (16-29)
packages/cli/src/cli/commands/prepare.ts (1)
packages/cli/src/cli/common.ts (1) (1)
  • checkForUnknownArgs (16-29)
packages/cli/src/cli/commands/dev.ts (1)
packages/cli/src/cli/common.ts (1) (1)
  • checkForUnknownArgs (16-29)
packages/plugin-drizzle/src/storage.ts (2)
packages/plugin-drizzle/src/utils.ts (2) (2)
  • IdColumnMap (52-57)
  • getIdColumnForTable (59-69)
packages/plugin-drizzle/src/constants.ts (1) (1)
  • SCHEMA_NAME (3-3)
packages/plugin-sqlite/src/kv.ts (2)
packages/plugin-sqlite/src/utils.ts (1) (1)
  • assertInTransaction (27-31)
packages/protocol/src/common.ts (2) (2)
  • Cursor (44-44)
  • Cursor (45-45)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test
🔇 Additional comments (60)
change/@apibara-plugin-mongo-c9018c01-2b4f-4a5a-a7a7-e13eb567d66f.json (1)

1-7: LGTM! Change metadata file correctly documents MongoDB plugin changes.

The metadata file properly documents the prerelease change for the MongoDB plugin, specifically moving the cleanup part after initialization. This aligns with the PR objective to fix cleanup query errors that occur before initialization when using the --always-reindex flag.

change/apibara-34f7f808-dcf6-45ec-bbe4-5e74b0193361.json (1)

1-7: LGTM! Change metadata covers multiple CLI improvements.

This metadata file correctly documents several core improvements mentioned in the PR objectives:

  • Fixing dev reload issues
  • Changing flag names in CLI
  • Adding arguments validation
  • Updating drizzle-orm version

The prerelease designation with patch change type is appropriate for these types of improvements.

packages/cli/src/create/constants.ts (1)

82-82: LGTM! Drizzle-orm version updated appropriately.

The drizzle-orm dependency has been updated from ^0.37.0 to ^0.40.1. This version bump matches one of the stated objectives in the PR and should provide the latest features and bug fixes from the drizzle-orm library.

examples/cli-drizzle/package.json (1)

34-34: LGTM! Version update is consistent with template definition.

The drizzle-orm version update to ^0.40.1 in the example project matches the same update made in the template constants file. This consistency ensures that generated projects will use the same dependency version as the examples.

packages/cli/src/cli/commands/add.ts (2)

3-3: Added import for argument validation

This import brings in the validation function that will check for unknown CLI arguments.


39-41: Implemented unknown argument validation

Added proper validation for unknown CLI arguments, which fulfills the PR objective about handling unknown arguments. The implementation checks arguments against the command definition, showing an error and usage information when unknown arguments are provided.

packages/cli/src/cli/commands/build.ts (2)

5-5: Import for argument validation added

The new import checkForUnknownArgs from "../common" enables validation of command-line arguments, which aligns with the PR objective of handling unknown arguments in the CLI.


15-17: Command validation implementation

The run method now accepts the command context and validates arguments before execution, providing better error handling and user feedback when invalid arguments are passed. This addresses the PR objective of validating unknown CLI arguments.

packages/cli/src/cli/commands/prepare.ts (2)

5-5: Import for argument validation added

The checkForUnknownArgs import enables the same validation pattern seen in other commands, maintaining consistency across the CLI interface.


15-17: Command validation implementation in prepare command

Added argument validation before main command execution, consistent with the pattern implemented in other commands. This ensures that invalid arguments trigger helpful error messages rather than unexpected failures.

packages/cli/src/cli/commands/start.ts (3)

7-7: Import for argument validation added

Adding the checkForUnknownArgs import to enable consistent argument validation across commands.


26-26: Fix for process exiting issue and argument validation

Two important changes here:

  1. The cmd parameter addition enables argument validation
  2. The validation is performed before executing the command logic

This implementation, combined with the removal of the explicit process.exit() call in the child process close handler (based on the PR objectives), addresses the main process exiting issue during development reloads mentioned in the PR description.

Also applies to: 30-31


65-72: Fixed process exit handling

The removal of the explicit process.exit() call (previously after line 71) resolves the issue with the main process exiting during development reloads, as mentioned in the PR objectives. The process will now continue running even after child processes exit, which is especially important during development with hot reloading.

packages/plugin-sqlite/tests/kv.test.ts (1)

55-55: Added indexerId to KV Store records

The test cases have been updated to include the id field with value "indexer_testing_default" in all key-value store records. This change validates that the indexerId relation has been correctly implemented in the KV Store as mentioned in the PR objectives.

Also applies to: 62-62, 69-69, 76-76, 83-83, 90-90, 276-276, 283-283, 290-290, 461-461, 468-468, 475-475, 482-482, 566-566, 573-573

packages/cli/src/cli/commands/init.ts (2)

3-3: Good addition of validation for unknown arguments.

Adding the import for checkForUnknownArgs is a positive improvement that allows the command to validate and handle unknown arguments, which aligns with the PR objectives for better CLI argument handling.


30-38: Good update to method signature and logic inversion.

The changes correctly:

  1. Update the method signature to include the cmd parameter
  2. Add validation for unknown arguments
  3. Update the destructuring to use the renamed parameter
  4. Invert the logic to match the renamed parameter (from noIndexer to !createIndexer)

This implementation aligns with the PR objectives to improve CLI argument handling.

packages/plugin-drizzle/src/utils.ts (2)

52-57: Good implementation of the IdColumnMap interface.

The IdColumnMap interface provides a flexible way to map table names to their respective ID column names, with the wildcard property ("*") serving as a fallback mechanism. This is a well-designed type that supports the PR objective of adding "Support for a specific idColumn map for tables... including wildcard support."


59-69: Clean implementation of the getIdColumnForTable function.

The function follows a simple and effective pattern:

  1. Check for a specific mapping for the provided table name
  2. Fall back to the wildcard mapping if no specific mapping exists

This correctly implements the feature mentioned in the PR objectives about specific idColumn map support with wildcard capability.

packages/plugin-sqlite/src/persistence.ts (2)

103-111: Robust implementation of resetPersistence function.

The resetPersistence function correctly:

  1. Accepts a database and indexer ID as parameters
  2. Asserts that the database is in a transaction (important for data integrity)
  3. Uses prepared statements to delete checkpoints and filters for the specific indexer

This implementation matches similar functions in other plugins (Mongo, Drizzle) and supports the PR objective of fixing "cleanup query errors that occur before initialization when the --always-reindex flag is activated."


181-186: Appropriate SQL statements for persistence reset.

The SQL statements are correctly defined to delete records from the checkpoints and filters tables based on the indexer ID. These statements are essential for the resetPersistence function to work properly.

packages/cli/src/cli/commands/dev.ts (5)

8-8: Comprehensive import update.

The updated import now includes both checkForUnknownArgs and commonArgs, which facilitates argument validation and reuse of common argument definitions, supporting the PR objectives for improved CLI argument handling.


29-34: Good renaming of always-reindex flag for consistency.

The argument has been renamed from alwaysReindex to always-reindex for consistency with other hyphenated argument names, and the description has been slightly refined for clarity.


36-38: Proper method signature update and validation addition.

The method signature now includes additional parameters (data, cmd, and rawArgs) that provide more context and enable argument validation. The added validation with checkForUnknownArgs checks for unknown arguments and displays a help message, fulfilling the PR objective for handling unknown CLI arguments.


41-43: Correctly updated conditional check.

The condition has been updated to use args["always-reindex"] instead of args.alwaysReindex, reflecting the argument renaming.


103-131: Fixed main process exiting issue during development reloads.

The removal of process.exit(code ?? 0) from the dev:reload hook prevents the main process from exiting unexpectedly during development reloads, addressing one of the key objectives mentioned in the PR description.

packages/plugin-mongo/src/index.ts (1)

73-92: Well-structured transaction flow for dealing with initialization and cleanup

The code now properly handles initialization and cleanup inside a single transaction. This change ensures that everything happens in the correct order, preventing the issue where cleanup queries could fail before initialization when --always-reindex is activated.

The transaction now:

  1. Initializes the persistent state first (if enabled)
  2. Performs cleanup operations after initialization
  3. Ensures all related operations are atomic
packages/cli/src/cli/common.ts (2)

1-7: Good addition of required imports for the new validation functionality

The imports have been updated to include the necessary types and functions from citty and consola libraries that will be used for argument validation.


16-29: Excellent implementation of CLI argument validation

This new function adds robust validation for unknown CLI arguments. It will:

  1. Compare provided arguments against defined arguments
  2. Show a meaningful error message for unknown arguments
  3. Display the usage information to guide the user
  4. Exit the process to prevent incorrect operation

This implementation aligns with the PR objective to "handle unknown arguments passed in the CLI" and provides a better developer experience.

packages/plugin-sqlite/src/index.ts (3)

2-2: Proper import updates for the new functionality

The imports have been updated to include:

  1. useLogger - for logging cleanup operations
  2. cleanupKV - for cleaning up the key-value store
  3. resetPersistence - for resetting the persistence state

These additions support the new cleanup and reindexing functionality.

Also applies to: 10-10, 21-21


82-82: Well-implemented cleanup logic for reindexing

The implementation now properly handles the --always-reindex flag by:

  1. Correctly determining if reindexing is needed
  2. Using a logger to inform users about the cleanup process
  3. Cleaning up the key-value store based on the indexerId
  4. Resetting the persistence state
  5. Using a flag to ensure cleanup is only applied once
  6. Providing clear success messages

This change resolves the issue with cleanup query errors that could occur before initialization.

Also applies to: 88-89, 94-121


171-172: Proper indexerId integration with KV Store operations

The indexerId parameter has been added to:

  1. invalidateKV calls
  2. finalizeKV calls
  3. The KeyValueStore constructor

This change ensures proper data isolation between different indexers sharing the same database, allowing for more robust multi-indexer setups.

Also applies to: 208-209, 226-227, 264-265

packages/plugin-drizzle/src/storage.ts (3)

19-23: Updated imports to support idColumn mapping

The import section has been properly updated to include IdColumnMap type and getIdColumnForTable function, which are essential for the new table-specific ID column functionality.


123-151: Enhanced flexibility with table-specific ID column mapping

The registerTriggers function now accepts an idColumnMap instead of a single idColumn string, enabling support for different ID columns per table. The implementation:

  1. Uses getIdColumnForTable to find the correct ID column for each table
  2. Properly applies the table-specific ID column in the trigger SQL statement
  3. Maintains compatibility with the previous behavior through the wildcard mapping

This change aligns with the PR objective to add "support for a specific idColumn map for tables" with wildcard support.


186-220: Consistent application of table-specific ID columns in invalidation logic

The invalidate function has been updated to use the idColumnMap parameter consistently:

  1. The function signature correctly uses idColumnMap: IdColumnMap
  2. Table-specific ID columns are determined for each operation using getIdColumnForTable
  3. The determined column is consistently used in SQL queries for DELETE statements
  4. The update logic properly filters non-ID keys based on the table-specific ID column

This implementation ensures that invalidation operations work correctly with the flexible ID column mapping system.

Also applies to: 284-286, 295-297

packages/plugin-drizzle/src/index.ts (12)

35-41: Imports appear correct and comprehensive.
Importing DrizzleStorageError, IdColumnMap, getIdColumnForTable, sleep, and withTransaction from "./utils" is a good organizational choice, centralizing utility logic and custom errors.


45-45: Exporting IdColumnMap is beneficial for external use.
This export helps consumers define or validate custom ID column mappings in their own code.


100-125: Doc comment enhancements provide clear usage instructions.
Allowing a single string or a mapping object for idColumn accommodates more complex schema setups. The detailed documentation and code examples are very helpful.


154-155: Assigning _schema and idColumn for internal use is straightforward.
No issues found with this parameter passing.


163-167: Logical fallback when constructing idColumnMap.
Using "*" as the default wildcard is consistent with documentation, and layering user-supplied mappings on top ensures each table’s ID column is found.


170-170: Fetching table names from the schema.
Collecting dbName values is a common approach. The surrounding try-catch ensures robust error handling.


178-192: Validation of the ID column’s existence in each table.
Throwing DrizzleStorageError when columns do not match prevents runtime inconsistencies. This is a sound approach that ensures correctness.


211-211: Introducing cleanupApplied flag improves reindexing logic.
This boolean gate helps avoid repeated cleanup for subsequent hooks, mitigating accidental data loss.


226-241: Cleanup flow on reindexing appears well-structured.
Deleting existing table data and resetting persistence once ensures a consistent fresh start. The warnings and logs are clear.


295-296: Utilizing invalidate with idColumnMap.
Passing an explicit mapping ensures each table’s primary key is accurately invalidated.


346-347: Consistent usage of the invalidate function.
Mirrors the pattern above to ensure correct rollback of pending data.


385-385: Registering triggers with idColumnMap fosters table-specific tracking.
Providing the map here ensures that triggers are correctly keyed to each table’s identifier.

packages/plugin-sqlite/src/kv.ts (11)

22-22: Storing indexerId strengthens scoping of key-value operations.
This allows multiple indexers to share the same table without overlapping data.


28-30: Retrieving rows now scoped by indexerId.
Ensuring the indexerId is included in the selection query prevents accidental data mixing.


37-38: Updating the to_block column conditionally by indexerId.
This helps ensure an indexer only affects its own rows during block updates.


41-43: Insert statement expanded to handle indexerId.
Inserting id allows for clearly partitioned data, and adding indexerId here is consistent with the new scoping mechanism.

Also applies to: 48-48


54-55: Delete operation (del) also scoped by indexerId.
This extends the same data isolation principles to record deletion.


59-59: finalizeKV narrowing deletes based on indexerId.
The updated function signature and query ensure finalization only applies to the relevant indexer’s records.

Also applies to: 62-64


68-68: invalidateKV updated to require indexerId.
The function signature improvement is consistent with the new scoping approach in KeyValueStore.


84-88: cleanupKV introduced to remove a single indexer’s data.
Good functionality for fully clearing stored states, especially for reindex scenarios.


95-95: id property in KeyValueRow.
Integrating id (an indexer-specific identifier) aligns with the new primary key arrangement.


105-106: Amending schema for id column and primary key.
This ensures each record is now uniquely identified by (from_block, k, id), supporting multi-indexer data separation.


111-111: SQL statements updated to incorporate id in all operations.
All queries now condition on id for retrieval, updates, and cleanup, providing proper isolation across indexers.

Also applies to: 115-115, 117-118, 122-122, 125-125, 128-128, 132-132, 133-136

change/@apibara-plugin-sqlite-22633833-27a0-4ae1-be3b-824b3514f5e2.json (1)

1-7: Metadata for SQLite plugin changes looks good

The new change file correctly documents the nature of the changes to the SQLite plugin, specifically the addition of cleanup logic and indexerId relation to KV Store. This aligns with the PR objectives mentioned.

change/@apibara-plugin-drizzle-fb22b1bc-f1ab-4299-a476-2ac25460956d.json (1)

1-7: Metadata for Drizzle plugin changes is properly documented

The change file accurately reflects the additions of idColumn map support with validation and the fix for cleanup errors, which matches the PR description. Good job documenting the specific changes.

examples/cli-drizzle/indexers/2-starknet.indexer.ts (1)

31-33: Implementation of the new idColumn map using wildcard looks correct

The change from a simple string "_id" to a map with a wildcard key "*" matches the new functionality described in the PR. This demonstrates the new support for idColumn mapping with wildcard support.

Note that this change maintains backward compatibility while adding flexibility for specifying different ID columns per table if needed in the future.

@jaipaljadeja jaipaljadeja requested a review from fracek March 21, 2025 22:50
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 (2)
packages/cli/src/cli/common.ts (2)

16-19: Provide clarity on async usage.
Since this function relies on await renderUsage(cmd), having it be async is consistent. However, consider confirming whether any additional asynchronous operations may occur in the future, or if a synchronous approach would suffice.


35-40: Avoid forcing process termination inside a utility function.
While terminating the process on unknown arguments is valid for a CLI, consider surfacing an error or throwing an exception instead. This approach allows the caller to decide whether to exit or handle errors differently, improving reusability and testability.

-    process.exit(1);
+    throw new Error(`Unknown arguments: ${wrongArgs.join(", ")}`);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 754a39b and ad00b3d.

📒 Files selected for processing (1)
  • packages/cli/src/cli/common.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test
🔇 Additional comments (3)
packages/cli/src/cli/common.ts (3)

1-7: Good organization of imports.
The imports from "citty" and consola are neatly structured and make it clear which utilities are being used.


20-31: Well-defined logic for collecting defined arguments.
This loop cleanly accounts for both main argument names and aliases. Ensure that any future additions to cmd.args remain fully compatible with this approach.


32-34: Ensure underscore key usage is consistent.
Filtering out _ is a common practice since libraries like minimist often store positional args under _. Confirm that no other special keys need to be excluded.

Would you like me to run a quick command to verify the usage of _ or other special keys across the CLI?

Copy link
Contributor

@fracek fracek left a comment

Choose a reason for hiding this comment

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

Only a couple of tiny things to change.

@fracek fracek merged commit 75b7f0e into apibara:main Mar 24, 2025
2 checks passed
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