Skip to content

fix: don't set default value in nested writes when set through FK #1989

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 2 commits into from
Feb 23, 2025

Conversation

Gabrola
Copy link
Contributor

@Gabrola Gabrola commented Feb 19, 2025

const result = db.post.create({
    data: {
        likes: {
            createMany: {
                data: [{
                    userId: user.id
                }]
            }
        }
    },
    include: {
        likes: true
    }
});

// results in ↓

const result = await db[model].create({
    data: {
        likes: {
            createMany: {
                data: [
                    {
                        userId: "48a96b75-882e-48bc-92eb-2ec266067b6d",
                        tenantId: "fa9c2cd6-ae4f-457a-b556-9089f25d67d4"
                    }
                ]
            }
        },
        tenant: {
            connect: {
                id: "fa9c2cd6-ae4f-457a-b556-9089f25d67d4"
            }
        },
        author: {
            connect: {
                id: "48a96b75-882e-48bc-92eb-2ec266067b6d"
            }
        }
    },
    select: {
        tenantId: true,
        id: true,
        likes: {
            select: {
                tenantId: true,
                id: true
            }
        }
    }
})

// Prisma error: Unknown argument `tenantId`. Available options are marked with ?.]

@Gabrola Gabrola force-pushed the fix/nested-write-default branch from 49fb100 to 7cf0e98 Compare February 19, 2025 15:02
Copy link
Contributor

coderabbitai bot commented Feb 19, 2025

📝 Walkthrough

Walkthrough

The pull request updates the DefaultAuthHandler in default-auth.ts by adding a new context parameter of type NestedWriteVisitorContext to the processCreatePayload and setDefaultValueForModelData methods. This change allows the methods to check nested write conditions and adjust default value handling based on foreign key mappings. Additionally, a new regression test (issue-1997.test.ts) has been introduced to verify schema relationships and data integrity across models such as Tenant, User, Post, PostUserLikes, and Comment.

Changes

File(s) Change Summary
packages/runtime/.../default-auth.ts Updated processCreatePayload and setDefaultValueForModelData method signatures to include the context parameter; adjusted logic to handle nested write scenarios.
tests/regression/.../issue-1997.test.ts Added a regression test suite using loadSchema to validate the relationships and data integrity among Tenant, User, Post, PostUserLikes, and Comment models.

Sequence Diagram(s)

sequenceDiagram
    participant C as Caller
    participant DA as DefaultAuthHandler
    participant SD as setDefaultValueForModelData

    C->>DA: processCreatePayload(model, data, context)
    DA->>SD: setDefaultValueForModelData(fieldInfo, model, data, authDefaultValue, context)
    SD-->>DA: Return updated data
    DA-->>C: Return final write payload
Loading

Possibly related PRs

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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. (Beta)
  • @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.

@ymc9
Copy link
Member

ymc9 commented Feb 20, 2025

Thanks for making this PR @Gabrola ! I'll follow up here shortly.

@ymc9
Copy link
Member

ymc9 commented Feb 21, 2025

Hi @Gabrola , I checked the change and the location you changed is spot on. However, I think it's safer if we detect such condition by inspecting the nested creation path (and not just checking back link and foreign key mappings), because a model being created (in a nested context) may have multiple relations, and the parent context may not be the one that's related to the foreign key field with default value.

model A {
  c C?
}

model B {
  c C?
}

model C {
  a A
  aId String @default(auth().id)
  b B
  bId String @default(auth().id)
}

// "bId" should still be set
db.a.create({ data: { c: {} } });

I'm making some changes directly based on your PR. Do you mind taking a look later?

- rely on the nested create path to determine the parent model context and detect if it's implicitly set the fk field
@ymc9
Copy link
Member

ymc9 commented Feb 21, 2025

fixes #1997

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

🧹 Nitpick comments (3)
tests/regression/tests/issue-1997.test.ts (3)

82-107: Enhance test coverage for post creation with likes.

The test case could be more comprehensive. Consider:

  1. Verifying all generated fields (post.id, likes[].id)
  2. Testing error cases (e.g., duplicate likes from the same user)
  3. Testing the unique constraint @@unique([tenantId, userId, postId])

Example test for duplicate likes:

 await expect(
     db.post.create({
         data: {
             likes: {
                 createMany: {
                     data: [
                         {
                             userId: user.id,
                         },
+                        // This should fail due to unique constraint
+                        {
+                            userId: user.id,
+                        },
                     ],
                 },
             },
         },
         include: {
             likes: true,
         },
     })
-).resolves.toMatchObject({
-    authorId: user.id,
-    likes: [
-        {
-            tenantId: tenant.id,
-            userId: user.id,
-        },
-    ],
-});
+).rejects.toThrow();

109-129: Make comment creation test more realistic.

The current test creates an empty comment, which might not represent real-world usage. Consider:

  1. Adding meaningful comment data (e.g., content field)
  2. Verifying all generated fields
  3. Testing error cases

Example of a more realistic test:

 await expect(
     db.post.create({
         data: {
             comments: {
                 createMany: {
-                    data: [{}],
+                    data: [{
+                        content: 'Test comment'
+                    }],
                 },
             },
         },
         include: {
             comments: true,
         },
     })
 ).resolves.toMatchObject({
     authorId: user.id,
     comments: [
         {
             tenantId: tenant.id,
+            content: 'Test comment',
+            id: expect.any(String),
         },
     ],
 });

7-69:

❓ Verification inconclusive

Consider enhancing the schema design for better security and consistency.

  1. The @@allow('all', true) policy is overly permissive. Consider implementing more granular access control.
  2. The Comment model lacks an author relationship, unlike the Post model. This might make it difficult to track comment ownership.

Let me help you verify if there are any existing models in the codebase that follow a more secure access control pattern:


🏁 Script executed:

#!/bin/bash
# Search for models with more granular access control
rg -U "model \w+[\s\S]*?@@allow\('.*?', (?!true)[^)]+\)" --type ts

Length of output: 359


Security Model Adjustments Needed in Schema

  • The models (User, Post, PostUserLikes, and Comment) use the permissive rule @@allow('all', true), which could be a security risk. Consider implementing more granular access controls.
  • The Comment model does not include an author relationship, unlike the Post model. This omission can complicate tracking comment ownership.
  • Note: The automated regex search for more granular access control produced errors due to unsupported look-arounds. Please verify manually or re-run with adjusted tools to confirm whether any models deviate from the permissive pattern.
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7cf0e98 and 8a7755b.

📒 Files selected for processing (2)
  • packages/runtime/src/enhancements/node/default-auth.ts (4 hunks)
  • tests/regression/tests/issue-1997.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/runtime/src/enhancements/node/default-auth.ts
🔇 Additional comments (1)
tests/regression/tests/issue-1997.test.ts (1)

73-80: Well-structured test setup!

The test data preparation follows best practices by:

  • Creating parent entities (Tenant) before child entities (User)
  • Properly setting up the authentication context with both user and tenant IDs

@Gabrola
Copy link
Contributor Author

Gabrola commented Feb 22, 2025

@ymc9 this is perfect! I wasn't super confident in my approach, so thank you for making it more robust!

@ymc9
Copy link
Member

ymc9 commented Feb 23, 2025

Thanks @Gabrola . Merging it now and will include the fix in the next patch release.

@ymc9 ymc9 merged commit 721c938 into zenstackhq:dev Feb 23, 2025
11 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