Skip to content

merge dev to main (v2.14.0) #2086

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

Merged
merged 7 commits into from
Apr 15, 2025
Merged

merge dev to main (v2.14.0) #2086

merged 7 commits into from
Apr 15, 2025

Conversation

ymc9
Copy link
Member

@ymc9 ymc9 commented Apr 15, 2025

No description provided.

Copy link
Contributor

coderabbitai bot commented Apr 15, 2025

📝 Walkthrough

Walkthrough

This update introduces a series of internal refactorings and feature enhancements across multiple packages. Key changes include the introduction of a new CodeWriter abstraction and its FastWriter implementation for code generation, replacing previous reliance on ts-morph's CodeBlockWriter and direct SourceFile manipulation. Policy and model metadata generators, as well as plugin utilities, have been refactored to use this new abstraction, centralizing function collection and code writing logic. Support for JSON fields has been expanded to SQLite, and related integration tests have been updated to run against both PostgreSQL and SQLite. The REST API now supports filtering to-one relations by multiple IDs. Version numbers for dependencies and the JetBrains IDE package have also been incremented.

Changes

File(s) / Path(s) Change Summary
packages/ide/jetbrains/build.gradle.kts Updated version from "2.13.3" to "2.14.0".
script/test-scaffold.ts, tests/integration/tests/cli/plugins.test.ts Updated Prisma and @prisma/client dependency versions from 6.5.x to 6.6.x.
packages/schema/src/plugins/enhancer/enhance/index.ts Simplified Prisma client type generation: removed ReadonlyDeep import, changed file naming/saving logic, updated type annotations, and removed redundant exports.
packages/schema/src/plugins/enhancer/policy/expression-writer.ts Replaced CodeBlockWriter with new CodeWriter abstraction in ExpressionWriter constructor.
packages/schema/src/plugins/enhancer/policy/policy-guard-generator.ts Refactored to use CodeWriter and FastWriter for code generation, centralized function collection, removed direct SourceFile manipulation.
packages/schema/src/plugins/enhancer/policy/utils.ts Refactored to return function declaration structures instead of directly modifying SourceFile; replaced writer function callbacks with string accumulation.
packages/schema/src/plugins/plugin-utils.ts Added missing "default": "./models.js" entry to the "./models" export in generated package.json.
packages/schema/src/plugins/prisma/schema-generator.ts Added 'sqlite' to PROVIDERS_SUPPORTING_TYPEDEF_FIELDS, enabling JSON fields for SQLite.
packages/sdk/src/code-gen.ts Introduced CodeWriter interface and FastWriter implementation for code generation.
packages/sdk/src/model-meta-generator.ts Refactored to use CodeWriter and FastWriter, centralized extra function collection, removed direct source file mutation.
packages/server/src/api/rest/index.ts Enhanced filter logic for to-one relations to support filtering by multiple IDs using OR conditions.
packages/server/tests/api/rest.test.ts Added test for filtering to-many relation fields by multiple values.
tests/integration/tests/enhancements/json/crud.test.ts, tests/integration/tests/enhancements/json/typing.test.ts Parameterized tests to run against both SQLite and PostgreSQL providers; updated setup/teardown logic accordingly.
tests/integration/tests/enhancements/json/validation.test.ts Removed test that checked JSON field support restriction to PostgreSQL.

Sequence Diagram(s)

sequenceDiagram
    participant Generator
    participant FastWriter
    participant ExtraFunctions
    participant SourceFile

    Generator->>FastWriter: Create instance
    Generator->>ExtraFunctions: Initialize array
    Generator->>FastWriter: Write main code blocks
    loop For each extra function
        Generator->>ExtraFunctions: Push function declaration
    end
    Generator->>SourceFile: Add main variable with FastWriter.result
    Generator->>SourceFile: Add all functions from ExtraFunctions
Loading
sequenceDiagram
    participant REST API
    participant makeFilterValue
    participant Client

    Client->>REST API: GET /resource?filter[field]=id1,id2
    REST API->>makeFilterValue: Parse filter value
    makeFilterValue->>makeFilterValue: Split value by ','
    alt Multiple IDs
        makeFilterValue->>REST API: Return { OR: [id1, id2, ...] }
    else Single ID
        makeFilterValue->>REST API: Return { is: id }
    end
    REST API->>Client: Respond with filtered data
Loading

Possibly related PRs

  • zenstackhq/zenstack#2085: Also modifies makeFilterValue in packages/server/src/api/rest/index.ts to improve filtering by multiple relation ID values.
  • zenstackhq/zenstack#2081: Enables JSON fields for SQLite by updating PROVIDERS_SUPPORTING_TYPEDEF_FIELDS in schema-generator.ts.
  • zenstackhq/zenstack#2077: Adds the missing "default": "./models.js" export entry in plugin-utils.ts, matching the same addition in this PR.
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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
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: 1

🧹 Nitpick comments (5)
packages/sdk/src/code-gen.ts (1)

73-129: Well-designed abstraction for code generation

The new CodeWriter interface and FastWriter implementation provide a clean abstraction for code generation that decouples the code writing logic from specific implementations. This approach:

  1. Provides a uniform API for code generation across the codebase
  2. Makes the code more testable by allowing mock implementations
  3. Reduces dependencies on specific libraries like ts-morph's CodeBlockWriter
  4. Centralizes indentation logic and formatting concerns

The implementation is straightforward and focused on the core responsibilities of code writing with proper indentation management.

You might consider adding a few more utility methods to the interface in the future:

  • A method for writing multiple lines at once
  • A newline method without text
  • A method for increasing/decreasing indentation directly

This could make client code even cleaner in complex generation scenarios.

packages/server/src/api/rest/index.ts (1)

1753-1758: Consider using an 'in' approach for multiple IDs.

The logic of splitting multiple IDs and returning an OR condition is correct for “to-one” relation filters. However, if users pass many IDs, enumerating them all within OR clauses might harm performance. In certain cases, using a single “in” condition (if supported) might be more efficient.

packages/schema/src/plugins/enhancer/policy/utils.ts (2)

269-285: Consider specifying a more precise return type.
This helper always produces a function returning a boolean. Yet, the returnType field is set to 'any'. A more accurate type like 'boolean' could be clearer and safer.

 export function generateConstantQueryGuardFunction(model: DataModel, kind: PolicyOperationKind, value: boolean) {
     return {
         name: getQueryGuardFunctionName(model, undefined, false, kind),
-        returnType: 'any',
+        returnType: 'boolean',
         parameters: [
             // ...
         ],
         statements: [`return ${value ? TRUE : FALSE};`],
     } as OptionalKind<FunctionDeclarationStructure>;
 }

367-413: Prisma partial query object generation.
The code conditionally maps deny/allow rules into Prisma-compatible query objects, including fallback for empty rules. This is a neat approach, though watch out for potential performance hits on large rule sets.

packages/schema/src/plugins/enhancer/policy/policy-guard-generator.ts (1)

233-253: Handling cross-model comparison with entity checkers.
Introducing an extra entity checker for cross-model references avoids complex SQL. Good separation of concerns. Watch for performance overhead if many cross-model checks are triggered.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2f69aa8 and 002e132.

⛔ Files ignored due to path filters (20)
  • package.json is excluded by !**/*.json
  • packages/ide/jetbrains/package.json is excluded by !**/*.json
  • packages/language/package.json is excluded by !**/*.json
  • packages/misc/redwood/package.json is excluded by !**/*.json
  • packages/plugins/openapi/package.json is excluded by !**/*.json
  • packages/plugins/swr/package.json is excluded by !**/*.json
  • packages/plugins/tanstack-query/package.json is excluded by !**/*.json
  • packages/plugins/trpc/package.json is excluded by !**/*.json
  • packages/plugins/trpc/tests/projects/nuxt-trpc-v10/package.json is excluded by !**/*.json
  • packages/plugins/trpc/tests/projects/nuxt-trpc-v11/package.json is excluded by !**/*.json
  • packages/plugins/trpc/tests/projects/t3-trpc-v11/package.json is excluded by !**/*.json
  • packages/runtime/package.json is excluded by !**/*.json
  • packages/schema/package.json is excluded by !**/*.json
  • packages/sdk/package.json is excluded by !**/*.json
  • packages/server/package.json is excluded by !**/*.json
  • packages/testtools/package.json is excluded by !**/*.json
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml, !**/*.yaml
  • tests/integration/test-run/package.json is excluded by !**/*.json
  • tests/integration/tests/frameworks/nextjs/test-project/package.json is excluded by !**/*.json
  • tests/integration/tests/frameworks/trpc/test-project/package.json is excluded by !**/*.json
📒 Files selected for processing (16)
  • packages/ide/jetbrains/build.gradle.kts (1 hunks)
  • packages/schema/src/plugins/enhancer/enhance/index.ts (6 hunks)
  • packages/schema/src/plugins/enhancer/policy/expression-writer.ts (2 hunks)
  • packages/schema/src/plugins/enhancer/policy/policy-guard-generator.ts (24 hunks)
  • packages/schema/src/plugins/enhancer/policy/utils.ts (9 hunks)
  • packages/schema/src/plugins/plugin-utils.ts (1 hunks)
  • packages/schema/src/plugins/prisma/schema-generator.ts (1 hunks)
  • packages/sdk/src/code-gen.ts (1 hunks)
  • packages/sdk/src/model-meta-generator.ts (14 hunks)
  • packages/server/src/api/rest/index.ts (1 hunks)
  • packages/server/tests/api/rest.test.ts (1 hunks)
  • script/test-scaffold.ts (1 hunks)
  • tests/integration/tests/cli/plugins.test.ts (2 hunks)
  • tests/integration/tests/enhancements/json/crud.test.ts (11 hunks)
  • tests/integration/tests/enhancements/json/typing.test.ts (9 hunks)
  • tests/integration/tests/enhancements/json/validation.test.ts (0 hunks)
💤 Files with no reviewable changes (1)
  • tests/integration/tests/enhancements/json/validation.test.ts
🧰 Additional context used
🧬 Code Graph Analysis (3)
script/test-scaffold.ts (1)
packages/testtools/src/schema.ts (1)
  • run (45-57)
packages/schema/src/plugins/enhancer/policy/expression-writer.ts (1)
packages/sdk/src/code-gen.ts (1)
  • CodeWriter (77-83)
tests/integration/tests/enhancements/json/crud.test.ts (1)
packages/testtools/src/db.ts (2)
  • createPostgresDb (19-25)
  • dropPostgresDb (27-31)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: build-test (20.x)
  • GitHub Check: OSSAR-Scan
  • GitHub Check: build-test (20.x)
  • GitHub Check: build-test (20.x)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: OSSAR-Scan
🔇 Additional comments (60)
script/test-scaffold.ts (1)

22-22: Prisma dependency versions updated to 6.6.x

The Prisma package versions have been updated from 6.5.x to 6.6.x, which aligns with similar version updates in the integration tests. This ensures consistency across the codebase.

packages/ide/jetbrains/build.gradle.kts (1)

12-12: Version bump for JetBrains IDE package

The version has been incremented from 2.13.3 to 2.14.0, which aligns with the broader updates in this PR that include significant refactoring and improvements in code generation infrastructure.

tests/integration/tests/cli/plugins.test.ts (2)

78-78: Runtime dependency '@prisma/client' updated to 6.6.x

This version update matches the Prisma update in the test-scaffold.ts script, maintaining consistency across the codebase.


88-88: Development dependency 'prisma' updated to 6.6.x

This version update aligns with the runtime dependency update and maintains version consistency with the test-scaffold.ts script.

packages/schema/src/plugins/prisma/schema-generator.ts (1)

85-85: Great addition - SQLite now supports JSON fields!

Adding SQLite to the list of providers supporting type definition fields is an excellent improvement that expands JSON field support beyond PostgreSQL. This change increases database flexibility for users who prefer lighter-weight database options.

packages/server/tests/api/rest.test.ts (1)

667-675: Nice enhancement: Multi-value filtering for to-one relations

This test verifies the new capability to filter posts by multiple authors using a comma-separated list in the filter[author] parameter. This is a valuable enhancement to the REST API's filtering capabilities, allowing more complex queries while maintaining a clean API.

tests/integration/tests/enhancements/json/typing.test.ts (2)

3-3: Great test improvement: Parameterized provider testing

Refactoring the test suite to run against both SQLite and PostgreSQL using describe.each is a clean approach to verify the newly added SQLite JSON field support. This ensures the same type system behaviors work consistently across database providers.


26-26: Consistently applied test parameterization

Using the dynamically provided provider parameter across all test configurations ensures proper test execution against multiple database systems. This is a necessary companion change to the describe.each refactoring.

Also applies to: 67-67, 108-108, 154-154, 206-206, 255-255, 306-306, 351-351

packages/schema/src/plugins/enhancer/policy/expression-writer.ts (1)

80-80: Constructor updated to accept a CodeWriter instance.

Switching from a ts-morph CodeBlockWriter to the new CodeWriter interface is consistent with the broader refactor. This helps streamline code generation logic without direct source-file manipulation.

tests/integration/tests/enhancements/json/crud.test.ts (10)

3-3: Enabling multi-database testing.

Adopting describe.each(['sqlite', 'postgresql']) broadens coverage and ensures JSON CRUD tests run on multiple providers, enhancing reliability.


8-10: Conditional Postgres database creation.

Creating the database only if provider === 'postgresql' prevents conflicts when testing with SQLite and simplifies local test setup.


14-18: Conditional teardown logic.

Ensuring the database is dropped and the Prisma client is disconnected only for Postgres. This avoids unnecessary teardown steps for SQLite.


48-49: Passing provider and dbUrl to loadSchema.

Including the chosen provider and the dynamically created DB URL in the schema loading process ensures that tests run with the correct configuration.


97-97: Consistent provider parameter usage.

Referencing provider on line 97 maintains alignment with prior changes for multi-DB testing.


144-145: Dynamic provider and dbUrl in loadSchema.

This further extends the multi-provider approach, letting the same schema adapt to different backends.


218-219: Provider and dbUrl injection.

Ensures that each test block accurately references the correct DB environment for JSON CRUD validations.


262-263: Continued multi-provider support.

Applies the same logic to another test scenario, ensuring it runs on both SQLite and Postgres.


335-336: Maintaining consistent test environments.

Repeats the pattern to handle the SQLite/Postgres distinction for further JSON field tests.


375-376: Final multi-provider extension.

Completes the pattern of conditionally assigning dbUrl based on provider type, ensuring a single test suite covers both databases.

packages/schema/src/plugins/enhancer/enhance/index.ts (9)

116-117: Flagging logical Prisma scenario.

Setting prismaTypesFixed = true and using LOGICAL_CLIENT_GENERATION_PATH indicates a switch to a “logical” Prisma client generation flow for delegate models or other advanced features.


122-123: Replacing 'models.d.ts' with 'models.ts'.

Creating a models.ts source file aligns with the simplified handling of generated files. It avoids confusion about .d.ts vs. .ts usage.


127-127: Ensuring file persistence.

this.saveSourceFile(modelsTs); respects the user setting to preserve TypeScript artifacts, letting developers refer back to them.


176-176: Conditionally resolving the new Prisma client typings.

Provides a path to index.d.ts when logical Prisma is used, but avoids altering the path if normal Prisma usage suffices.


183-183: Dynamically finding the Prisma client generator.

Looking up the prisma-client-js generator ensures the correct generator is invoked for specialized logical schema output.


348-348: Custom Prisma generation command.

Includes the generator name in the command to consistently produce the logical Prisma client. Allows for customized generation steps (e.g., no-engine).


457-457: Preparing for index.d.ts transformations.

A top-level note clarifies that the upcoming logic modifies the automatically generated Prisma client typings to handle logical features.


471-472: Creating an intermediate file.

Writing transformations to index-fixed.d.ts first helps reduce complexity and in-line editing issues, improving performance of the transform.


482-483: Replacing original generated file post-transformation.

Finalizing the step by moving index-fixed.d.ts over index.d.ts ensures that the user interacts with a logically corrected Prisma client definition.

packages/schema/src/plugins/enhancer/policy/utils.ts (6)

5-5: Use of FastWriter is consistent with the new code generation approach.
No issues found with this import statement.


43-43: Importing function declaration structures.
The addition of FunctionDeclarationStructure and OptionalKind is aligned with the refactoring to generate and store function declarations separately.


299-299: Initialization of statements array.
Defining statements: string[] = [] is straightforward; no concerns here.


322-340: Refactored conditional check with transformer logic.
The new block properly generates inline checks for deny/allow rules and rethrows transformation errors. Consider logging or decorating errors if you anticipate user-facing messages, but otherwise this is fine.


342-366: Conditional branches for field-level vs. model-level checks.
This logic nicely handles corner cases where no allow rules exist, defaulting to either true or false appropriately. No issues observed.


441-496: Entity checker function generation.
The function and its return structure look correct. It collects statements, transforms them via TypeScriptExpressionTransformer, and defaults for post-update vs. other operations. Implementation seems consistent with the rest of the refactor.

packages/schema/src/plugins/enhancer/policy/policy-guard-generator.ts (11)

54-55: Maintaining a list of extra functions for deferred insertion.
Storing generated functions in this.extraFunctions helps modularize code generation. No issues.


65-70: Begin writing main policy block.
Using FastWriter and a scoped block() method to accumulate source contents is consistent with the new code generation approach.


84-85: Deferred function addition to source file.
Calling sf.addFunctions(this.extraFunctions) after building them is a solid approach, ensuring decoupled code generation.


151-160: Model-level policy definitions.
Grouping read/create/update/postUpdate/delete policies under modelLevel is clear. The repeated pattern for each operation fosters code consistency.


185-189: Conditionally generating the create input checker.
The logic for determining whether create rules can be evaluated on input alone is well-reasoned. Carefully excludes fields with default values, foreign keys, and this references. Nicely done.


506-509: Generating permissionChecker or returning a constant boolean.
The fallback to a constant boolean if no rules exist is a pragmatic approach. This covers policy states with minimal overhead.


521-534: Constructing permission checker function.
Transforms allow/deny rules into a single constraint expression. Implementation looks consistent; watch out for large expansions if many rules are combined.


540-545: Field-level definitions.
Splitting the policy into fieldLevel read/update blocks is coherent. This grouping clarifies the difference between model-level and field-level concerns.


550-608: Field read guards and override.
The logic for standard vs. override read rules, plus the generation of an overrideGuard, is well-structured. The override entity checker usage matches the new approach.


610-668: Field update guards and override.
Parallel to field read logic, the update guard creation is similarly robust. The override scenario is also handled. This consistent pattern improves maintainability.


674-679: Auth selector generation.
This method collects all auth() references across model and field-level rules into a single Prisma select object. Good approach for ensuring minimal data fetching.

packages/sdk/src/model-meta-generator.ts (15)

22-22: Function declaration imports.
Importing FunctionDeclarationStructure and OptionalKind is consistent with the refactoring.


24-27: Migration to CodeWriter and FastWriter.
Replacing CodeBlockWriter with CodeWriter/FastWriter centralizes code generation logic, making it more flexible and consistent across the codebase.


80-81: Accumulate extra functions for deferred insertion.
Collecting function declarations separately before appending to the source file mirrors the pattern in policy generation. This ensures a cohesive build step.


105-107: Grouping model and type definition writes in a single block.
Combining the generation for models and type defs improves clarity. No issues noted.


110-110: Unified approach for writing model data.
writeModels uses the new writer abstraction effectively, ensuring consistent structure.


120-131: Generating fields with extended metadata.
Fields are enumerated, with default attribute filtering if generateAttributes is false. This pattern is well-structured for partial metadata generation.


166-172: Write base types for inheritance.
Capturing superTypes under baseTypes fosters clarity for conceptual inheritance or polymorphism.


178-179: Auth model reference.
Identifying the auth model earlier helps separate concerns about user identity checks. Good approach.


182-192: Deletion cascade metadata.
Capturing arrays of cascading deletes can be critical for advanced usage. Implementation is straightforward.


194-208: Unique constraints listing.
Aggregating constraints from field-level and model-level is robust. This synergy ensures important DB definitions are not overlooked.


210-216: Conditional model attributes.
Processing attributes only if options.generateAttributes is set keeps metadata generation flexible.


224-230: Storing discriminator fields.
Identifying a @@delegate discriminator is helpful for multi-tenant or polymorphic data designs. Code is straightforward.


292-296: Injecting default value provider.
Generating a closure around auth() usage helps manage dynamic defaults. This pattern neatly avoids referencing user context at compile time.


509-544: Building a default function for auth() references.
This carefully transforms @default expressions containing auth(). Good approach to separate user context from static definitions.


560-570: Short name mapping support.
Maintaining a mapping for synthetic or shortened names is a nice feature for codebase cleanliness.

@ymc9 ymc9 merged commit bf9be5c into main Apr 15, 2025
13 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.

3 participants