-
-
Notifications
You must be signed in to change notification settings - Fork 12
upsert support and fixes about "omit" #7
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
WalkthroughThe changes introduce comprehensive support for an "omit" feature across CRUD operations, allowing fields to be excluded from query results and arguments. An "upsert" operation is implemented in both the runtime client and type system, with validation, handler logic, and tests. Existing create, update, and delete operations are updated to handle the new omit option. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant ModelOperations
participant UpdateOperationHandler
participant DB
Client->>ModelOperations: upsert(args)
ModelOperations->>UpdateOperationHandler: handle('upsert', args)
UpdateOperationHandler->>DB: update(where, update)
alt Record updated
UpdateOperationHandler->>DB: readUnique(where, select/include/omit)
else No record updated
UpdateOperationHandler->>DB: create(create)
UpdateOperationHandler->>DB: readUnique(where, select/include/omit)
end
UpdateOperationHandler->>ModelOperations: return result
ModelOperations->>Client: return result
Poem
✨ 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:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. 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: 0
🔭 Outside diff range comments (1)
packages/runtime/src/client/crud-types.ts (1)
96-141:⚠️ Potential issueFix the default type parameter to improve type safety.
The static analysis tool correctly identifies that using
{}as a default type is too permissive. Consider using a more specific default or removing it entirely.Apply this diff to fix the type safety issue:
export type ModelResult< Schema extends SchemaDef, Model extends GetModels<Schema>, - Args extends SelectIncludeOmit<Schema, Model, boolean> = {}, + Args extends SelectIncludeOmit<Schema, Model, boolean> = SelectIncludeOmit<Schema, Model, boolean>, Optional = false, Array = false > = WrapType<Alternatively, you could remove the default entirely if it's not necessary:
export type ModelResult< Schema extends SchemaDef, Model extends GetModels<Schema>, - Args extends SelectIncludeOmit<Schema, Model, boolean> = {}, + Args extends SelectIncludeOmit<Schema, Model, boolean>, Optional = false, Array = false > = WrapType<🧰 Tools
🪛 Biome (1.9.4)
[error] 99-99: Don't use '{}' as a type.
Prefer explicitly define the object shape. '{}' means "any non-nullable value".
(lint/complexity/noBannedTypes)
🧹 Nitpick comments (1)
packages/runtime/test/client-api/create.test.ts (1)
36-61: Excellent test coverage for omit functionality!The tests comprehensively verify both runtime behavior and TypeScript type safety for the omit feature. The use of
@ts-expect-errorcorrectly demonstrates that accessing omitted fields causes compilation errors.However, remove the debugging console.log statements:
- // @ts-expect-error - console.log(user2.name);- // @ts-expect-error - console.log(user3.name);
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (10)
TODO.md(1 hunks)packages/runtime/src/client/client-impl.ts(3 hunks)packages/runtime/src/client/crud-types.ts(12 hunks)packages/runtime/src/client/crud/operations/base.ts(5 hunks)packages/runtime/src/client/crud/operations/create.ts(1 hunks)packages/runtime/src/client/crud/operations/delete.ts(1 hunks)packages/runtime/src/client/crud/operations/update.ts(4 hunks)packages/runtime/src/client/crud/validator.ts(6 hunks)packages/runtime/test/client-api/create.test.ts(1 hunks)packages/runtime/test/client-api/upsert.test.ts(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
packages/runtime/src/client/client-impl.ts (1)
packages/runtime/src/client/crud/operations/update.ts (1)
UpdateOperationHandler(8-103)
packages/runtime/src/client/crud/operations/base.ts (2)
packages/runtime/src/client/crud-types.ts (1)
SelectIncludeOmit(325-333)packages/runtime/src/schema/schema.ts (1)
GetModels(104-107)
packages/runtime/src/client/crud-types.ts (2)
packages/runtime/src/utils/type-utils.ts (1)
WrapType(11-15)packages/runtime/src/schema/schema.ts (4)
NonRelationFields(171-182)SchemaDef(12-19)GetModels(104-107)GetFields(121-124)
🪛 markdownlint-cli2 (0.17.2)
TODO.md
46-46: Unordered list indentation
Expected: 2; Actual: 4
(MD007, ul-indent)
🪛 Biome (1.9.4)
packages/runtime/src/client/crud-types.ts
[error] 99-99: Don't use '{}' as a type.
Prefer explicitly define the object shape. '{}' means "any non-nullable value".
(lint/complexity/noBannedTypes)
🔇 Additional comments (26)
TODO.md (1)
46-46: LGTM!The status update correctly reflects that upsert functionality has been implemented. The indentation appears consistent with other items in the list.
🧰 Tools
🪛 markdownlint-cli2 (0.17.2)
46-46: Unordered list indentation
Expected: 2; Actual: 4(MD007, ul-indent)
packages/runtime/src/client/crud/operations/delete.ts (1)
34-34: LGTM!The addition of omit support to the readUnique call is consistent with the broader implementation across CRUD operations. The change correctly passes through the omit option from the delete arguments.
packages/runtime/src/client/crud/operations/create.ts (1)
48-48: LGTM!The addition of omit support brings consistency with the existing
runCreateManyAndReturnmethod and follows the established pattern across CRUD operations.packages/runtime/src/client/client-impl.ts (3)
269-269: Parameter rename improves clarity.The rename from
throwIfNotFoundtothrowIfNoResultbetter reflects the parameter's broader purpose across different operations.
278-278: Correctly uses the renamed parameter.The conditional check properly uses the updated parameter name.
403-410: Well-implemented upsert method integration.The upsert method follows the established pattern for CRUD operations:
- Uses the correct operation type string 'upsert'
- Delegates to UpdateOperationHandler which supports upsert operations
- Enables post-processing appropriately
- Correctly omits the throwIfNoResult parameter (defaults to false)
This integrates well with the broader upsert support implementation.
packages/runtime/test/client-api/upsert.test.ts (1)
1-77: Comprehensive and well-structured upsert test suite.The test implementation covers key upsert scenarios effectively:
- Create scenario: Verifies upsert creates a new record when none exists, with nested profile creation
- Update scenario: Verifies upsert updates existing record, preserving related data
- ID update scenario: Tests updating the primary key field itself, which is an edge case worth covering
The test structure follows best practices:
- Proper setup/teardown with schema pushing and client disconnection
- Uses
toMatchObjectfor partial matching, allowing for flexibility- Tests include/select functionality alongside upsert operations
- Each scenario builds upon the previous state logically
The ID update test case is particularly valuable as it verifies that updating a field used in the where clause works correctly.
packages/runtime/src/client/crud/validator.ts (5)
22-22: Consistent upsert validation implementation.The new
validateUpsertArgsmethod andUpsertArgstype import follow the established pattern for other CRUD operation validators, maintaining consistency across the codebase.Also applies to: 87-93
588-596: Enhanced create schema with omit support.The create schema has been properly updated to:
- Use specific schema builder methods (
makeSelectSchema,makeIncludeSchema,makeOmitSchema)- Include the new
omitfield option- Apply mutual exclusivity refinement for select/include
This maintains consistency with the broader omit feature implementation.
609-610: Consistent omit support in createManyAndReturn schema.The addition of
includeandomitoptions maintains consistency with other enhanced schemas.
911-913: Enhanced update schema with omit support.The update schema properly includes the omit option and applies the same mutual exclusivity refinement pattern used in other schemas.
Also applies to: 917-917
930-943: Well-designed upsert schema validation.The
makeUpsertSchemamethod properly defines the validation requirements:
- Required fields:
where(unique),create, andupdatedata- Optional fields:
select,include, andomitwith proper mutual exclusivity- Strict validation: Prevents extra properties
- Consistent refinement: Applies the same select/include mutual exclusivity as other schemas
This schema correctly captures the upsert operation's requirements and maintains consistency with existing validation patterns.
packages/runtime/src/client/crud/operations/update.ts (4)
4-4: Proper imports for upsert support.The addition of
UpsertArgstype import and reordering of theBaseOperationHandlerimport maintain clean import organization.Also applies to: 6-6
11-11: Correct integration of upsert operation handling.The method signature properly extends the operation union type to include 'upsert', and the pattern matching correctly dispatches to the new
runUpsertmethod with proper argument validation.Also applies to: 23-27
42-42: Enhanced update operation with omit support.The
runUpdatemethod correctly includes theomitoption when reading back the updated record, maintaining consistency with the broader omit feature implementation.
69-102: Robust upsert implementation with proper atomicity.The
runUpsertmethod implements solid upsert semantics:Atomic transaction approach: Uses
safeTransactionto ensure the update-or-create logic is atomic, preventing race conditions.Correct upsert logic:
- Attempts update first with the provided
whereandupdatedata- If no record is affected (doesn't exist), creates a new record with
createdata- Reads back the result with proper selection options
Proper error handling: Throws
RejectedByPolicyErrorif the result cannot be read back due to policy restrictions.Consistent patterns: Follows the same read-back pattern as other operations, supporting
select,include, andomitoptions.The update call parameters (
undefined, true, false) correctly specify no additional options, allow missing records, and disable throwing on no result for the initial update attempt.packages/runtime/src/client/crud/operations/base.ts (4)
32-32: LGTM! Import change aligns with the new type system.The import change from
SelectIncludetoSelectIncludeOmitcorrectly reflects the enhanced type that now includes support for theomitfield.
62-62: LGTM! Correctly adds 'upsert' to supported operations.The addition of 'upsert' to the
CrudOperationunion type properly extends the supported operations.
168-174: LGTM! Correctly implements mutual exclusivity between select and omit.The logic properly handles the mutual exclusivity between
selectandomitoptions:
- When
selectis provided, it takes precedence- When
selectis not provided, all scalar fields are included except those specified inomitThis implementation aligns with common ORM patterns for field selection.
1789-1789: LGTM! Method signatures correctly updated to use SelectIncludeOmit.The parameter type updates for
trimResultandneedReturnRelationsmethods are consistent with the broader changes to support theomitfeature throughout the codebase.Also applies to: 1802-1802
packages/runtime/src/client/crud-types.ts (6)
42-55: LGTM! DefaultModelResult correctly implements field omission.The type correctly filters out omitted fields using conditional types. Fields are excluded from the result when they are present in the
Omittype parameter with a value oftrue.
57-94: LGTM! ModelSelectResult properly handles omit with select.The type correctly filters out omitted fields even when they are explicitly selected, ensuring consistent behavior across the API.
325-333: LGTM! SelectIncludeOmit type properly extends query options.The renamed type correctly adds the
omitfield alongside existingselectandincludeoptions, using the appropriateOmitFieldstype for field mapping.
562-563: LGTM! Consistently adds omit support across all operation types.The
omitfield is correctly added to all relevant operation argument types. TheCreateManyAndReturnArgstype properly excludes theincludeoption using TypeScript'sOmitutility type, which is appropriate for batch operations.Also applies to: 574-574, 693-693, 789-789
705-715: LGTM! UpsertArgs type is well-structured.The new
UpsertArgstype correctly defines all necessary fields for an upsert operation:
createfor the insert caseupdatefor the update casewherefor identifying the record- Optional
select,include, andomitfor controlling the returned data
1133-1135: LGTM! Upsert method correctly added to ModelOperations.The
upsertmethod signature follows the established pattern of other operations in the interface, properly usingSelectSubsetfor type safety and returning the appropriateModelResulttype.
Summary by CodeRabbit
New Features
Bug Fixes
Tests
Documentation