Skip to content

Conversation

@ymc9
Copy link
Member

@ymc9 ymc9 commented Sep 8, 2025

No description provided.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 8, 2025

📝 Walkthrough

Walkthrough

Refactors Zod schema generation by introducing a centralized createModelBaseSchema that controls default inclusion via makeFieldSchema(field, addDefaults). Updates generator paths to use baseSchemaWithoutDefaults for create/update. Adjusts makeFieldSchema signature to accept addDefaults. Loosens typings in getZodErrorMessage by casting to any instead of Zod-specific error types.

Changes

Cohort / File(s) Summary
Zod schema generation refactor
packages/schema/src/plugins/zod/generator.ts, packages/schema/src/plugins/zod/utils/schema-gen.ts
Added createModelBaseSchema to build base Zod object schemas. Extended makeFieldSchema to accept addDefaults (default true). Replaced inlined schemas with createModelBaseSchema usages, introducing baseSchemaWithoutDefaults for create/update paths and wiring addDefaults accordingly. Cleaned duplicate import.
Runtime Zod error handling typing
packages/runtime/src/local-helpers/zod-utils.ts
Removed ZodError-type imports and casts; now casts err as any when formatting via fromZodErrorV3/V4. Added ESLint disable for any usage. Control flow unchanged.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Dev as Generator
  participant G as generator.ts
  participant B as createModelBaseSchema
  participant F as makeFieldSchema(addDefaults)
  participant Z as z.object(...)

  Dev->>G: generateModelSchema / generateTypeDefSchema
  G->>B: createModelBaseSchema(fields, mode=strip|passthrough|strict, addDefaults=true)
  loop For each field
    B->>F: makeFieldSchema(field, addDefaults=true)
    F-->>B: field Zod schema (with defaults)
  end
  B->>Z: z.object({ ...fields }).mode(...)
  Z-->>G: baseSchema

  note over G,B: Create/Update paths
  G->>B: createModelBaseSchema(fields, mode=..., addDefaults=false)
  loop For each field
    B->>F: makeFieldSchema(field, addDefaults=false)
    F-->>B: field Zod schema (no defaults)
  end
  B->>Z: z.object({ ...fields }).mode(...)
  Z-->>G: baseSchemaWithoutDefaults
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/zod4-compatibility

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.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
packages/schema/src/plugins/zod/utils/schema-gen.ts (1)

37-44: Bug: min/max checks drop 0 due to truthy test

@length(min: 0) or @length(max: 0) are ignored. Use explicit undefined checks.

-                const min = getAttrLiteralArg<number>(attr, 'min');
-                if (min) {
+                const min = getAttrLiteralArg<number>(attr, 'min');
+                if (min !== undefined) {
                     schema += `.min(${min}${messageArg})`;
                 }
-                const max = getAttrLiteralArg<number>(attr, 'max');
-                if (max) {
+                const max = getAttrLiteralArg<number>(attr, 'max');
+                if (max !== undefined) {
                     schema += `.max(${max}${messageArg})`;
                 }
packages/schema/src/plugins/zod/generator.ts (1)

551-559: Support atomic operations for BigInt and Decimal too

Prisma exposes atomic update inputs for BigInt/Decimal; currently only Int/Float are handled.

-                        if (field.type.type === 'Int' || field.type.type === 'Float') {
+                        if (
+                            field.type.type === 'Int' ||
+                            field.type.type === 'Float' ||
+                            field.type.type === 'BigInt' ||
+                            field.type.type === 'Decimal'
+                        ) {
                             fieldSchema = `z.union([${fieldSchema}, z.record(z.unknown())])`;
                         }
🧹 Nitpick comments (3)
packages/runtime/src/local-helpers/zod-utils.ts (2)

1-1: Scope down the ESLint any-disable to the casts instead of the whole file

Avoid blanket disables; keep the file type-safe and silence only the necessary lines.

Apply:

-/* eslint-disable @typescript-eslint/no-explicit-any */

9-21: Handle string errors and localize the any-casts

Small robustness win and narrower lint suppression.

 export function getZodErrorMessage(err: unknown): string {
-    if (!(err instanceof Error)) {
+    if (typeof err === 'string') {
+        return err;
+    }
+    if (!(err instanceof Error)) {
         return 'Unknown error';
     }
 
     try {
         if ('_zod' in err) {
-            return fromZodErrorV4(err as any).message;
+            return fromZodErrorV4(err as any).message; // eslint-disable-line @typescript-eslint/no-explicit-any
         } else {
-            return fromZodErrorV3(err as any).message;
+            return fromZodErrorV3(err as any).message; // eslint-disable-line @typescript-eslint/no-explicit-any
         }
     } catch {
         return err.message;
     }
 }
packages/schema/src/plugins/zod/generator.ts (1)

673-698: Add a brief JSDoc for createModelBaseSchema to document addDefaults semantics

Helps future contributors understand when defaults are injected.

-    private createModelBaseSchema(
+    /**
+     * Emits `const <name> = z.object({...})` for scalar fields.
+     * When `addDefaults` is true, per-field `.default(...)` is appended; otherwise omitted.
+     */
+    private createModelBaseSchema(
         name: string,
         writer: CodeBlockWriter,
         scalarFields: DataModelField[],
         addDefaults: boolean
     ) {
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8bbe219 and bc16e35.

📒 Files selected for processing (3)
  • packages/runtime/src/local-helpers/zod-utils.ts (2 hunks)
  • packages/schema/src/plugins/zod/generator.ts (8 hunks)
  • packages/schema/src/plugins/zod/utils/schema-gen.ts (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
packages/schema/src/plugins/zod/generator.ts (1)
packages/schema/src/plugins/zod/utils/schema-gen.ts (1)
  • makeFieldSchema (17-163)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: dependency-review
  • GitHub Check: build-test (20.x)
  • GitHub Check: build-test (20.x)
  • GitHub Check: build-test (20.x)
  • GitHub Check: OSSAR-Scan
🔇 Additional comments (5)
packages/schema/src/plugins/zod/utils/schema-gen.ts (2)

144-156: Correct gating of .default(...) application

Skipping .default(...) when addDefaults is false solves the Zod v4 compatibility concern for create/update paths.


17-17: No remaining call sites need addDefaults: false
All three calls in packages/schema/src/plugins/zod/generator.ts (lines 325, 446, 457) intentionally rely on the default addDefaults: true.

packages/schema/src/plugins/zod/generator.ts (3)

431-435: Nice centralization via createModelBaseSchema

Reducing duplication and threading addDefaults improves maintainability.


533-537: Prisma create now based on baseSchemaWithoutDefaults — correct

This prevents generator-inserted defaults from masking DB defaults.


577-586: Create schema correctly derives from baseSchemaWithoutDefaults and marks defaulted fields optional

Matches Prisma behavior for @default, @updatedAt, and list fields.

@ymc9 ymc9 merged commit b004868 into dev Sep 8, 2025
12 checks passed
@ymc9 ymc9 deleted the fix/zod4-compatibility branch September 8, 2025 06:47
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