-
-
Notifications
You must be signed in to change notification settings - Fork 104
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
Conversation
Co-authored-by: Yiming <[email protected]> Co-authored-by: ymc9 <[email protected]>
📝 WalkthroughWalkthroughThis update introduces a series of internal refactorings and feature enhancements across multiple packages. Key changes include the introduction of a new Changes
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
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
Possibly related PRs
✨ Finishing Touches
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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 generationThe new
CodeWriter
interface andFastWriter
implementation provide a clean abstraction for code generation that decouples the code writing logic from specific implementations. This approach:
- Provides a uniform API for code generation across the codebase
- Makes the code more testable by allowing mock implementations
- Reduces dependencies on specific libraries like
ts-morph
'sCodeBlockWriter
- 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, thereturnType
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
⛔ 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.xThe 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 packageThe 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.xThis 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.xThis 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 relationsThis 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 testingRefactoring 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 parameterizationUsing 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 newCodeWriter
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 usingLOGICAL_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
overindex.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 ofFastWriter
is consistent with the new code generation approach.
No issues found with this import statement.
43-43
: Importing function declaration structures.
The addition ofFunctionDeclarationStructure
andOptionalKind
is aligned with the refactoring to generate and store function declarations separately.
299-299
: Initialization of statements array.
Definingstatements: 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 viaTypeScriptExpressionTransformer
, 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 inthis.extraFunctions
helps modularize code generation. No issues.
65-70
: Begin writing main policy block.
UsingFastWriter
and a scopedblock()
method to accumulate source contents is consistent with the new code generation approach.
84-85
: Deferred function addition to source file.
Callingsf.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 undermodelLevel
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, andthis
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 intofieldLevel
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 anoverrideGuard
, 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 allauth()
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.
ImportingFunctionDeclarationStructure
andOptionalKind
is consistent with the refactoring.
24-27
: Migration toCodeWriter
andFastWriter
.
ReplacingCodeBlockWriter
withCodeWriter
/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 ifgenerateAttributes
is false. This pattern is well-structured for partial metadata generation.
166-172
: Write base types for inheritance.
CapturingsuperTypes
underbaseTypes
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 ifoptions.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 aroundauth()
usage helps manage dynamic defaults. This pattern neatly avoids referencing user context at compile time.
509-544
: Building a default function forauth()
references.
This carefully transforms@default
expressions containingauth()
. 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.
No description provided.