Skip to content

fix : handle P2002 unique constraint when re-adding deleted repository#2445

Closed
tmdeveloper007 wants to merge 1 commit into
nisshchayarathi:mainfrom
tmdeveloper007:fix/2436-prisma-p2002-repository
Closed

fix : handle P2002 unique constraint when re-adding deleted repository#2445
tmdeveloper007 wants to merge 1 commit into
nisshchayarathi:mainfrom
tmdeveloper007:fix/2436-prisma-p2002-repository

Conversation

@tmdeveloper007

@tmdeveloper007 tmdeveloper007 commented Jun 21, 2026

Copy link
Copy Markdown
Contributor

Summary

Fixes Prisma P2002 unique constraint violation when a user tries to re-add a previously deleted GitHub repository.

Changes

  • lib/services/repositoryService.ts: Catch P2002 in createRepository and return the existing record instead of throwing

Impact

Users can now safely re-add a repository after deleting it without hitting a database constraint error.

Closes #2436

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced duplicate repository name detection and handling during creation to prevent conflicts
  • New Features

    • Repository analysis now records the latest analyzed commit information for reference
    • Implemented detection system to identify when a repository's analysis is outdated relative to the latest code changes

@vercel

vercel Bot commented Jun 21, 2026

Copy link
Copy Markdown

@tmdeveloper007 is attempting to deploy a commit to the Nisshchaya's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented Jun 21, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

repositoryService.ts receives three targeted changes: createRepository adds a name-collision guard and replaces the pre-check with P2002 catch-and-recover logic; analyzeRepository persists the latest commit SHA to analyzedCommitSha after analysis; and getRepository returns null on miss and appends an isStale flag derived from analyzedCommitSha vs. the current defaultBranch commit.

Changes

Repository service: creation fix and staleness lifecycle

Layer / File(s) Summary
createRepository: name collision guard and P2002 recovery
lib/services/repositoryService.ts
Adds a pre-check that throws on a same-name/different-URL collision, then wraps prisma.repository.create to catch P2002 and return the existing (url, userId, targetDirectory) row; other errors are rethrown.
analyzeRepository SHA persistence and getRepository isStale detection
lib/services/repositoryService.ts
After the analysis transaction, fetches the latest commit hash on defaultBranch and writes it to repository.analyzedCommitSha (best-effort). getRepository returns null on miss and otherwise computes and returns an isStale flag by comparing analyzedCommitSha to the current defaultBranch commit hash.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

db

Poem

🐇 A repo once vanished, then knocked on the door,
"P2002!" cried Prisma — not welcomed before.
But now with a catch and a SHA tucked away,
We check if you're stale or as fresh as spring hay.
Hop in, little repo, you're welcome to stay! 🌿

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning Additional changes to analyzeRepository and getRepository (adding analyzedCommitSha tracking and isStale computation) extend beyond the linked issue's scope of handling P2002 constraint violations. Clarify whether the analyzedCommitSha and isStale features are part of issue #2436 or separate requirements, or split into a separate PR.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly addresses the main change: handling P2002 unique constraint violation when re-adding deleted repositories, which aligns with the primary code modifications.
Linked Issues check ✅ Passed The code changes address the core requirement from issue #2436 by catching P2002 errors and returning existing records instead of failing, allowing users to re-add previously deleted repositories.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@github-actions

Copy link
Copy Markdown

🎉 Thanks for your contribution, @tmdeveloper007!

Your PR has passed our automated GSSoC quality checks. Here's a quick summary:

Check Status
PR description ✅ Provided
PR title ✅ Meaningful
Linked issue ✅ Found
Change size ✅ Looks good (101 lines across 1 file(s))

A maintainer will review your PR soon. Please be patient and available for feedback. 💪

GSSoC'26 automation · Maintainer: @nisshchayarathi

@github-actions

Copy link
Copy Markdown

🎉 Thanks for your contribution, @tmdeveloper007!

Your PR has passed our automated GSSoC quality checks. Here's a quick summary:

Check Status
PR description ✅ Provided
PR title ✅ Meaningful
Linked issue ✅ Found
Change size ✅ Looks good (101 lines across 1 file(s))

A maintainer will review your PR soon. Please be patient and available for feedback. 💪

GSSoC'26 automation · Maintainer: @nisshchayarathi

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (1)
lib/services/repositoryService.ts (1)

645-660: 🧹 Nitpick | 🔵 Trivial | 💤 Low value

Duplicate query for headCommit can be consolidated.

The same prisma.commit.findFirst query for the latest commit on defaultBranch is executed here (lines 647-651) and again at lines 672-676 for cache invalidation. Consider querying once and reusing the result.

♻️ Suggested consolidation
+    // Fetch latest commit SHA once for both stale-detection and cache invalidation.
+    const headCommit = await prisma.commit.findFirst({
+      where: { repositoryId, branch: defaultBranch },
+      orderBy: { committedAt: "desc" },
+      select: { hash: true },
+    });
+
     // Record the analyzed commit SHA for stale-detection.
-    // Fetched after the transaction so it reflects the newly inserted commits.
-    const headCommit = await prisma.commit.findFirst({
-      where: { repositoryId, branch: defaultBranch },
-      orderBy: { committedAt: "desc" },
-      select: { hash: true },
-    });
     if (headCommit?.hash) {
       await prisma.repository.update({
         where: { id: repositoryId },
         data: { analyzedCommitSha: headCommit.hash },
       }).catch(() => {
         // Non-critical: stale-detection metadata should not break analysis.
       });
     }

     // ... repository knowledge save ...

     // Cache invalidation (outside transaction — best-effort, non-critical)
     try {
       await invalidateExpiredCacheEntries(repositoryId);

-      const headCommit = await prisma.commit.findFirst({
-        where: { repositoryId, branch: defaultBranch },
-        orderBy: { committedAt: "desc" },
-        select: { hash: true },
-      });
-
       if (headCommit?.hash) {
         await invalidateCacheForCommit(repositoryId, headCommit.hash);
       }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/services/repositoryService.ts` around lines 645 - 660, The
prisma.commit.findFirst query for the latest commit on the defaultBranch is
being executed twice in this function - once here for updating analyzedCommitSha
and again later for cache invalidation around lines 672-676. Instead of running
this duplicate query, execute the headCommit query once and store the result in
a variable, then reuse that same headCommit variable in both places where you
need the latest commit hash. This will eliminate the redundant database call
while maintaining the same functionality.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@lib/services/repositoryService.ts`:
- Around line 653-655: The update operation in the prisma.repository.update call
is attempting to set the analyzedCommitSha field, but this field does not exist
in the Repository Prisma model. Add the analyzedCommitSha field to the
Repository model in prisma/schema.prisma as a String type field (decide on
optional vs required based on your data model), then create a new Prisma
migration by running the migration command to generate and apply the database
schema changes that will add the analyzed_commit_sha column to the repository
table.

---

Nitpick comments:
In `@lib/services/repositoryService.ts`:
- Around line 645-660: The prisma.commit.findFirst query for the latest commit
on the defaultBranch is being executed twice in this function - once here for
updating analyzedCommitSha and again later for cache invalidation around lines
672-676. Instead of running this duplicate query, execute the headCommit query
once and store the result in a variable, then reuse that same headCommit
variable in both places where you need the latest commit hash. This will
eliminate the redundant database call while maintaining the same functionality.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c9aed3ca-511d-48a5-b0d2-0613dc7c3f45

📥 Commits

Reviewing files that changed from the base of the PR and between d4e21a5 and 463a2aa.

📒 Files selected for processing (1)
  • lib/services/repositoryService.ts

Comment on lines +653 to +655
await prisma.repository.update({
where: { id: repositoryId },
data: { analyzedCommitSha: headCommit.hash },

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Verify analyzedCommitSha field exists in Repository model

# Check schema.prisma for the field definition
echo "=== Checking schema.prisma for analyzedCommitSha ==="
rg -n "analyzedCommitSha" --type-add 'prisma:*.prisma' --type prisma

# Check if there's a migration adding this column
echo ""
echo "=== Checking migrations for analyzed_commit_sha column ==="
fd -e sql . prisma/migrations --exec grep -l -i "analyzed_commit_sha" {} \; 2>/dev/null || echo "No migrations found with this column"

Repository: nisshchayarathi/gitverse-nextjs

Length of output: 225


🏁 Script executed:

# Check the Repository model definition in schema.prisma
rg -A 30 "model Repository" --type-add 'prisma:*.prisma' --type prisma

Repository: nisshchayarathi/gitverse-nextjs

Length of output: 9671


🏁 Script executed:

# Read the specific lines in repositoryService.ts to see the context
sed -n '650,660p' lib/services/repositoryService.ts

Repository: nisshchayarathi/gitverse-nextjs

Length of output: 408


Add analyzedCommitSha field to the Repository model and create migration.

The code attempts to update repository.analyzedCommitSha on lines 653-655, but this field does not exist in the Repository Prisma model. Add the field to prisma/schema.prisma and create a migration to add the corresponding analyzed_commit_sha column to the database.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/services/repositoryService.ts` around lines 653 - 655, The update
operation in the prisma.repository.update call is attempting to set the
analyzedCommitSha field, but this field does not exist in the Repository Prisma
model. Add the analyzedCommitSha field to the Repository model in
prisma/schema.prisma as a String type field (decide on optional vs required
based on your data model), then create a new Prisma migration by running the
migration command to generate and apply the database schema changes that will
add the analyzed_commit_sha column to the repository table.

@tmdeveloper007

Copy link
Copy Markdown
Contributor Author

CI Status

CI checks ran. The Type Check and verify failures are pre-existing on main (confirmed: Type Check has been failing on main since 2026-06-19; verify failures predate this PR).

PR-specific changes:

All changes are isolated to the files described in the PR body. The pre-existing CI failures require a separate investigation and are outside the scope of these fixes.

@tmdeveloper007

Copy link
Copy Markdown
Contributor Author

Closing this PR. The branch is based on an older commit of upstream/main and has drifted from the current main. The upstream repository has received significant updates since this PR was opened, causing CI type-check and test failures due to merge conflicts with the base branch. Please re-open as a fresh PR against the current main if the fix is still needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

GSSoC'26 Part of GirlScript Summer of Code 2026

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Prisma P2002 unique constraint error when re-adding a previously deleted repository

1 participant