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

Init View Filters #159

Closed
wants to merge 6 commits into from
Closed

Init View Filters #159

wants to merge 6 commits into from

Conversation

zacharyblasczyk
Copy link
Member

@zacharyblasczyk zacharyblasczyk commented Oct 22, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a TRPC router for managing target view metadata groups, including procedures for creating, updating, retrieving, and deleting groups.
    • Added new database tables for target view metadata groups and keys, enhancing metadata management capabilities.
    • Expanded permission set for managing metadata groups, allowing for more granular access control.
    • Added a new function for retrieving scope information related to target view metadata groups.
  • Bug Fixes

    • Improved error handling for metadata group operations to ensure a smoother user experience.
  • Documentation

    • Updated relevant schemas and types to reflect the new features and permissions.

Copy link
Contributor

coderabbitai bot commented Oct 22, 2024

Walkthrough

The changes in this pull request introduce a new TRPC router for managing target view metadata groups, featuring procedures for listing, retrieving, creating, updating, and deleting metadata groups. New database tables and schemas are added to support these functionalities, along with updates to the permission system to include specific permissions for managing metadata groups. Additionally, modifications to the database schema accommodate these changes while preserving existing functionalities.

Changes

File Path Change Summary
packages/api/src/router/target-view-metadata-group.ts Implemented a new TRPC router with procedures: groups, byId, create, update, and delete for managing target view metadata groups.
packages/db/drizzle/meta/_journal.json Added a new entry to the JSON structure with attributes: idx: 19, version: "7", when: 1729570934508, tag: "0019_complex_cammi", breakpoints: true.
packages/db/src/schema/target.ts Introduced new tables: target_view_metadata_group and target_view_metadata_group_key, with corresponding types and schemas for creation and updates. Modified target_metadata to include new types and schemas.
packages/validators/src/auth/index.ts Expanded the Permission enum with new entries for managing metadata groups: TargetViewMetadataGroupList, TargetViewMetadataGroupGet, TargetViewMetadataGroupCreate, TargetViewMetadataGroupUpdate, TargetViewMetadataGroupDelete. Introduced AuthorizationResourceType.
packages/db/drizzle/0019_complex_cammi.sql Altered enum type "scope_type" to include targetViewMetadataGroup. Created new tables: target_view_metadata_group and target_view_metadata_group_key, added foreign key constraints, and created unique indexes.
packages/db/src/schema/rbac.ts Added a new value targetViewMetadataGroup to the scopeType enum.
packages/auth/src/utils/rbac.ts Introduced a new function getTargetViewMetadataGroupScopes and updated scopeHandlers to include it, enhancing scope handling for the new entity type.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant TRPCRouter
    participant Database

    Client->>TRPCRouter: Call create(groupData)
    TRPCRouter->>Database: Insert new metadata group
    Database-->>TRPCRouter: Confirmation of creation
    TRPCRouter-->>Client: Return created group

    Client->>TRPCRouter: Call update(groupId, updatedData)
    TRPCRouter->>Database: Update metadata group
    Database-->>TRPCRouter: Confirmation of update
    TRPCRouter-->>Client: Return updated group

    Client->>TRPCRouter: Call delete(groupId)
    TRPCRouter->>Database: Delete metadata group
    Database-->>TRPCRouter: Confirmation of deletion
    TRPCRouter-->>Client: Return success message
Loading

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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 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.

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
Contributor

@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: 4

🧹 Outside diff range and nitpick comments (6)
packages/db/drizzle/0018_lowly_otto_octavius.sql (2)

1-5: LGTM! Consider adding an index on the view_id column.

The table structure for "target_view_metadata_group" looks good. The use of UUID for the id column and NOT NULL constraints on view_id and name ensure data integrity.

Consider adding an index on the view_id column to improve query performance when filtering or joining on this column:

CREATE INDEX idx_target_view_metadata_group_view_id ON target_view_metadata_group(view_id);

7-11: LGTM! Consider adding a unique constraint on (group_id, key).

The table structure for "target_view_metadata_group_key" looks good. The use of UUID for the id column and NOT NULL constraints on group_id and key ensure data integrity.

Consider adding a unique constraint on the combination of group_id and key to prevent duplicate keys within the same group:

ALTER TABLE target_view_metadata_group_key ADD CONSTRAINT unique_group_key UNIQUE (group_id, key);
packages/db/drizzle/meta/_journal.json (1)

131-136: LGTM! Consider adding a brief comment for the migration.

The new entry is correctly structured and consistent with previous entries. It accurately reflects the addition of new SQL tables and functionalities for managing target view metadata groups.

To improve documentation, consider adding a brief comment in the migration file (0018_lowly_otto_octavius.sql) describing the purpose of this migration, such as:

-- Migration: Add tables and functionalities for target view metadata groups

This will make it easier for developers to understand the purpose of each migration at a glance.

packages/validators/src/auth/index.ts (1)

65-70: LGTM! Consider minor adjustment for consistency.

The new permissions for target view metadata group operations are well-structured and align with the existing permission scheme. They provide granular control over the new functionality, which is excellent for security and access management.

For consistency with other permission groups, consider moving these new permissions next to the existing TargetView permissions (around line 40). This would improve readability and make it easier to manage related permissions.

packages/api/src/router/target-view-metadata-group.ts (1)

156-156: Improve error handling in create procedure

The error thrown when group creation fails is a generic "Group creation failed". To aid in debugging and provide more context, consider using a more descriptive error message or a custom error class.

For example:

 if (!group) throw new Error("Group creation failed");
+// Consider providing additional details or using a custom error class
packages/db/src/schema/target.ts (1)

151-157: Consider moving TargetMetadata type definition closer to targetMetadata table definition for consistency.

For better maintainability and readability, it's recommended to define the TargetMetadata type immediately after the targetMetadata table definition, as done with other schemas in this file.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 2da5458 and 7d65102.

📒 Files selected for processing (5)
  • packages/api/src/router/target-view-metadata-group.ts (1 hunks)
  • packages/db/drizzle/0018_lowly_otto_octavius.sql (1 hunks)
  • packages/db/drizzle/meta/_journal.json (1 hunks)
  • packages/db/src/schema/target.ts (2 hunks)
  • packages/validators/src/auth/index.ts (1 hunks)
🧰 Additional context used
🔇 Additional comments (5)
packages/db/drizzle/0018_lowly_otto_octavius.sql (3)

13-17: LGTM! Foreign key constraint looks good.

The foreign key constraint for the "target_view_metadata_group" table is well-implemented. The use of a DO block with exception handling prevents errors if the constraint already exists. The cascade on delete and no action on update are appropriate for maintaining referential integrity.


19-23: LGTM! Foreign key constraint is well-implemented.

The foreign key constraint for the "target_view_metadata_group_key" table is correctly implemented. The use of a DO block with exception handling is consistent with the previous constraint. The cascade on delete and no action on update maintain referential integrity between the metadata group and its keys.


1-23: Overall, excellent migration script with room for minor enhancements.

This migration script creates a solid foundation for managing target view metadata groups and their associated keys. The table structures, primary keys, and foreign key constraints are well-implemented, ensuring data integrity.

To further improve the migration, consider the following suggestions:

  1. Add an index on the view_id column in the target_view_metadata_group table.
  2. Add a unique constraint on the combination of group_id and key in the target_view_metadata_group_key table.

These enhancements will improve query performance and prevent data duplication, respectively.

packages/validators/src/auth/index.ts (1)

65-70: Verify usage of new permissions across the application.

The new permissions have been correctly added and will be automatically included in the predefined roles. However, it's important to ensure that these permissions are properly utilized in other parts of the application, such as the TRPC router mentioned in the PR summary.

Please run the following script to verify the usage of the new permissions:

This will help confirm that the new permissions are being correctly applied in the authorization checks for the relevant operations.

✅ Verification successful

New permissions are properly utilized in the application.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of new target view metadata group permissions across the application.

# Test: Search for the usage of new permissions in TRPC routers and other relevant files.
rg -i "TargetViewMetadataGroup(List|Get|Create|Update|Delete)"

Length of output: 1154

packages/api/src/router/target-view-metadata-group.ts (1)

224-225: ⚠️ Potential issue

Ensure cascading deletes for associated keys in delete procedure

When deleting a targetViewMetadataGroup, associated keys in targetViewMetadataGroupKey may remain in the database, leading to orphaned records. Ensure that the database schema has cascading delete or that the code explicitly deletes associated keys.

Run the following script to check for foreign key constraints with cascading deletes:

✅ Verification successful

Cascading Deletes Verified

The ON DELETE CASCADE constraint is correctly implemented in packages/db/src/schema/target.ts, ensuring that associated targetViewMetadataGroupKey records are deleted when a targetViewMetadataGroup is removed.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if there is an ON DELETE CASCADE constraint between targetViewMetadataGroup and targetViewMetadataGroupKey

# Expected result: The foreign key constraint should have ON DELETE CASCADE action.

sqlite3 mydatabase.db "PRAGMA foreign_key_list('targetViewMetadataGroupKey');"

Length of output: 161


Script:

#!/bin/bash
# Description: Search for FOREIGN KEY constraints between targetViewMetadataGroup and targetViewMetadataGroupKey with ON DELETE CASCADE in migration and schema files.

# Search in common schema directories
rg -i "FOREIGN KEY.*targetViewMetadataGroupKey.*ON DELETE CASCADE" ./migrations ./schemas

Length of output: 194


Script:

#!/bin/bash
# Description: List all foreign key constraints for targetViewMetadataGroupKey to verify cascading deletes.

rg -i "FOREIGN KEY.*targetViewMetadataGroupKey" ./migrations ./schemas | grep -i "ON DELETE CASCADE"

Length of output: 205


Script:

#!/bin/bash
# Description: Search for FOREIGN KEY constraints between targetViewMetadataGroup and targetViewMetadataGroupKey with ON DELETE CASCADE across the entire codebase.

rg -i "FOREIGN KEY.*targetViewMetadataGroupKey.*ON DELETE CASCADE" .

Length of output: 70


Script:

#!/bin/bash
# Description: Search for any references to targetViewMetadataGroup and targetViewMetadataGroupKey to identify schema definitions.

rg -i "targetViewMetadataGroup" .

Length of output: 6458

Comment on lines +96 to +118
const targetMetadataAgg = ctx.db
.select({
id: target.id,
metadata: sql<Record<string, string>>`jsonb_object_agg(
${targetMetadata.key},
${targetMetadata.value}
)`.as("metadata"),
})
.from(target)
.innerJoin(targetView, eq(target.workspaceId, targetView.workspaceId))
.innerJoin(
targetMetadata,
and(
eq(target.id, targetMetadata.targetId),
inArray(targetMetadata.key, group.keys),
),
)
.where(eq(targetView.id, group.group.viewId))
.groupBy(target.id)
.having(
sql<number>`COUNT(DISTINCT ${targetMetadata.key}) = ${group.keys.length}`,
)
.as("target_metadata_agg");
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Review the complex query in the byId procedure for performance

The query in the byId procedure (lines 96-118) includes multiple joins and aggregations, which could affect performance on large datasets. Consider analyzing the query execution plan and optimizing it if necessary, perhaps by adding appropriate indexes or simplifying the query.

[performance]

packages/api/src/router/target-view-metadata-group.ts Outdated Show resolved Hide resolved
packages/db/src/schema/target.ts Outdated Show resolved Hide resolved
packages/db/src/schema/target.ts Outdated Show resolved Hide resolved
Copy link
Contributor

@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

🧹 Outside diff range and nitpick comments (1)
packages/auth/src/utils/rbac.ts (1)

348-368: LGTM: New function getTargetViewMetadataGroupScopes added

The new function correctly fetches the scope hierarchy for a targetViewMetadataGroup. It follows the established pattern of other scope-fetching functions in this file.

Consider handling the case where the query might return no results:

-    .then(takeFirst);
+    .then(takeFirstOrNull);

+  if (result == null) {
+    throw new Error(`No targetViewMetadataGroup found with id: ${id}`);
+  }

  return [
    // ...
  ];

This change would make the function more robust against potential database inconsistencies or invalid ids.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 08d9403 and 62697ce.

📒 Files selected for processing (1)
  • packages/auth/src/utils/rbac.ts (3 hunks)
🧰 Additional context used
🔇 Additional comments (2)
packages/auth/src/utils/rbac.ts (2)

24-24: LGTM: New import added for targetViewMetadataGroup

The addition of targetViewMetadataGroup to the imports is consistent with the new functionality being introduced in this file.


391-391: LGTM: scopeHandlers updated with new targetViewMetadataGroup entry

The addition of targetViewMetadataGroup to the scopeHandlers object is correct and necessary for integrating the new scope type into the existing RBAC system.

@jsbroks jsbroks closed this Oct 25, 2024
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