Skip to content

fix(orm): enforce at most one key per orderBy array element#2563

Merged
ymc9 merged 2 commits into
devfrom
fix/orderby-array-single-key-validation
Apr 7, 2026
Merged

fix(orm): enforce at most one key per orderBy array element#2563
ymc9 merged 2 commits into
devfrom
fix/orderby-array-single-key-validation

Conversation

@ymc9

@ymc9 ymc9 commented Apr 7, 2026

Copy link
Copy Markdown
Member

Summary

  • Adds a Zod refinement to makeOrderBySchema that rejects objects with more than one key, enforcing Prisma's convention that each element in an orderBy array should specify exactly one sort field
  • Uses safeExtend() (instead of extend()) when adding _count to array-relation orderBy schemas, since Zod v4 disallows extending refined schemas
  • Adds an E2E test verifying that orderBy array elements with multiple keys are rejected

Test plan

  • tests/e2e/orm/client-api/find.test.ts — new test: 'rejects orderBy array elements with multiple keys'

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Updated orderBy parameter validation to enforce single-key constraint. The ORM now rejects orderBy objects containing multiple sort keys, allowing only one sort field per query.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@claude

claude Bot commented Apr 7, 2026

Copy link
Copy Markdown
Contributor

Claude finished @ymc9's task —— View job


PR Review: OrderBy Array Validation Fix

Review Tasks

  • Analyze the core implementation in factory.ts
  • Review the test coverage in find.test.ts
  • Check for potential bugs and edge cases
  • Evaluate performance implications
  • Assess security considerations
  • Provide overall feedback and recommendations

Analysis of Changes

Core Implementation (packages/orm/src/client/zod/factory.ts):

  • Lines 1129-1132: Added refineAtMostOneKey function that validates orderBy objects have at most one key
  • Line 1147: Uses safeExtend() instead of extend() when adding _count to array relation orderBy schemas
  • Line 1178: Applies the refinement to the main orderBy schema

Test Coverage (tests/e2e/orm/client-api/find.test.ts):

  • Lines 1192-1205: New test 'rejects orderBy array elements with multiple keys'
  • Tests empty object (valid), single key (valid), and multiple keys (should be rejected)
  • Properly uses toBeRejectedByValidation() for the expected failure case

Code Quality Assessment ✅

Strengths:

  • Clean, focused implementation that addresses the specific issue
  • Proper use of Zod refinement for validation
  • Good error message: "Each orderBy element must have at most one key"
  • Correctly handles the Zod v4 compatibility issue with safeExtend()
  • Comprehensive test coverage covering edge cases

Implementation Quality:

  • The refineAtMostOneKey helper function is well-designed and reusable
  • Proper application of refinement after extending schema (line 1147)
  • Good separation of concerns - validation logic is isolated

Potential Issues & Edge Cases ✅

No significant issues found:

  • Empty objects {} are correctly allowed (common in Prisma for default sorting)
  • Single key objects work as expected
  • Multiple key objects are properly rejected
  • The refinement is applied consistently across the schema

Performance Considerations ✅

  • Minimal impact: The validation adds minimal overhead - just an Object.keys().length check
  • Runtime cost: The refinement runs only during input validation, not on every query
  • Schema caching: The factory uses caching (@cache() decorator), so schemas are built once

Security Considerations ✅

  • No security concerns: This is purely a validation enhancement
  • Input sanitization: Improves input validation by enforcing stricter rules
  • Error handling: Provides clear error messages without exposing internals

Test Coverage Assessment ✅

The test coverage is solid and covers key scenarios:

  • ✅ Empty object (valid case)
  • ✅ Single key object (valid case)
  • ✅ Multiple keys object (invalid case)
  • ✅ Uses proper test assertion toBeRejectedByValidation()

Suggestion: Consider adding a test for nested orderBy scenarios to ensure the refinement works correctly in relation contexts.

Overall Recommendation ✅

APPROVE - This is a well-implemented fix that:

  1. Correctly addresses the issue: Enforces Prisma's orderBy conventions
  2. Maintains backward compatibility: Valid use cases continue to work
  3. Includes comprehensive tests: Good coverage of edge cases
  4. Follows best practices: Clean code with proper error handling
  5. Handles Zod v4 compatibility: Uses safeExtend() appropriately

The implementation is production-ready and adds valuable input validation without any significant drawbacks.


@claude

claude Bot commented Apr 7, 2026

Copy link
Copy Markdown
Contributor

Claude finished @ymc9's task —— View job


PR Review: OrderBy Array Validation Fix

Review Tasks

  • Analyze the core implementation in factory.ts
  • Review the test coverage in find.test.ts
  • Check for potential bugs and edge cases
  • Evaluate performance implications
  • Assess security considerations
  • Provide overall feedback and recommendations

Analysis of Changes

Core Implementation (packages/orm/src/client/zod/factory.ts):

  • Lines 1129-1132: Added refineAtMostOneKey function that validates orderBy objects have at most one key
  • Line 1147: Uses safeExtend() instead of extend() when adding _count to array relation orderBy schemas
  • Line 1178: Applies the refinement to the main orderBy schema

Test Coverage (tests/e2e/orm/client-api/find.test.ts):

  • Lines 1185-1198: New test 'rejects orderBy array elements with multiple keys'
  • Tests empty object (valid), single key (valid), and multiple keys (should be rejected)
  • Properly uses toBeRejectedByValidation() for the expected failure case

Code Quality Assessment ✅

Strengths:

  • Clean, focused implementation that addresses the specific issue
  • Proper use of Zod refinement for validation
  • Good error message: "Each orderBy element must have at most one key"
  • Correctly handles the Zod v4 compatibility issue with safeExtend()
  • Comprehensive test coverage covering edge cases

Implementation Quality:

  • The refineAtMostOneKey helper function is well-designed and reusable
  • Proper application of refinement after extending schema (line 1147)
  • Good separation of concerns - validation logic is isolated

Potential Issues & Edge Cases ✅

No significant issues found:

  • Empty objects {} are correctly allowed (common in Prisma for default sorting)
  • Single key objects work as expected
  • Multiple key objects are properly rejected
  • The refinement is applied consistently across the schema

Performance Considerations ✅

  • Minimal impact: The validation adds minimal overhead - just an Object.keys().length check
  • Runtime cost: The refinement runs only during input validation, not on every query
  • Schema caching: The factory uses caching (@cache() decorator), so schemas are built once

Security Considerations ✅

  • No security concerns: This is purely a validation enhancement
  • Input sanitization: Improves input validation by enforcing stricter rules
  • Error handling: Provides clear error messages without exposing internals

Test Coverage Assessment ✅

The test coverage is solid and covers key scenarios:

  • ✅ Empty object (valid case)
  • ✅ Single key object (valid case)
  • ✅ Multiple keys object (invalid case)
  • ✅ Uses proper test assertion toBeRejectedByValidation()

Suggestion: Consider adding a test for nested orderBy scenarios to ensure the refinement works correctly in relation contexts.

Overall Recommendation ✅

APPROVE - This is a well-implemented fix that:

  1. Correctly addresses the issue: Enforces Prisma's orderBy conventions
  2. Maintains backward compatibility: Valid use cases continue to work
  3. Includes comprehensive tests: Good coverage of edge cases
  4. Follows best practices: Clean code with proper error handling
  5. Handles Zod v4 compatibility: Uses safeExtend() appropriately

The implementation is production-ready and adds valuable input validation without any significant drawbacks.


@ymc9 ymc9 merged commit 39a0a28 into dev Apr 7, 2026
7 checks passed
@ymc9 ymc9 deleted the fix/orderby-array-single-key-validation branch April 7, 2026 02:16
@coderabbitai

coderabbitai Bot commented Apr 7, 2026

Copy link
Copy Markdown
Contributor

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: d59a6859-390f-4905-b199-ee7b82ba79e8

📥 Commits

Reviewing files that changed from the base of the PR and between f137525 and 548be25.

📒 Files selected for processing (2)
  • packages/orm/src/client/zod/factory.ts
  • tests/e2e/orm/client-api/find.test.ts

📝 Walkthrough

Walkthrough

Prisma ORM's orderBy schema now enforces a constraint allowing at most one key per object through a Zod refinement rule applied to field-level and top-level schema validation. Relation array handling was updated to reapply refinements post-extension. Tests were updated to reflect this stricter validation.

Changes

Cohort / File(s) Summary
Order-by Schema Validation
packages/orm/src/client/zod/factory.ts
Added refineAtMostOneKey helper enforcing max one key constraint (Object.keys(v).length <= 1). Updated array relation handling to use safeExtend with re-applied refinements. Applied constraint to top-level orderBy object schema via return value modification.
Order-by Constraint Tests
tests/e2e/orm/client-api/find.test.ts
Removed assertion allowing multiple sort keys in single orderBy object. Added validation test confirming findMany rejects array elements with multiple keys while accepting empty objects and single-key elements.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 One key per order, sorted with care,
No tangled pairs floating in the air!
The schema now whispers its gentle refrain:
"One sort at a time keeps logic sane!"

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/orderby-array-single-key-validation

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

Comment @coderabbitai help to get the list of available commands and usage tips.

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.

1 participant