Skip to content

Conversation

@avirajsingh7
Copy link
Collaborator

@avirajsingh7 avirajsingh7 commented Aug 27, 2025

Summary

This PR implements a unique constraint to prevent duplicate project names within the same organization and reduces the minimum project name length requirement from 3 to 1 character.

Explain the motivation for making this change. What existing problem does the pull request solve?

Checklist

Before submitting a pull request, please ensure that you mark these task.

  • Ran fastapi run --reload app/main.py or docker compose up in the repository root and test.
  • If you've fixed a bug or added code that is tested and has test cases.

Notes

Please add here if any other information is required for the reviewer.

Summary by CodeRabbit

  • New Features

    • You can now use single-character project names during onboarding.
  • Bug Fixes

    • Project names are now enforced to be unique within each organization. Attempts to create a duplicate project name return a clear conflict error, preventing accidental duplicates and ensuring consistent project lists across the app.

@coderabbitai
Copy link

coderabbitai bot commented Aug 27, 2025

Walkthrough

Adds a composite unique constraint on project name per organization at the DB/model level, introduces a pre-create duplicate check in project CRUD, relaxes onboarding project_name min length, adds Alembic migration for the constraint, and adds a unit test asserting duplicate-name conflict handling.

Changes

Cohort / File(s) Summary of Changes
DB uniqueness constraint
backend/app/models/project.py, backend/app/alembic/versions/8725df286943_unique_constraint_on_project_name_and_.py
Adds UniqueConstraint("name", "organization_id", name="uq_project_name_org_id") to Project model and corresponding Alembic migration with upgrade/downgrade to create/drop the constraint.
CRUD duplicate check
backend/app/crud/project.py
Before creating a project, queries by organization and name; if found, logs and raises HTTP 409 "Project already exists"; otherwise proceeds with creation.
Onboarding validation tweak
backend/app/models/onboarding.py
Lowers project_name min_length from 3 to 1 in OnboardingRequest.
Tests for duplicates
backend/app/tests/crud/test_project.py
Adds test creating a project then asserting a second with same name/org raises HTTPException with "Project already exists".

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Client
  participant API as API (create_project)
  participant DB as Database

  Client->>API: POST /projects (name, organization_id, ...)
  API->>DB: SELECT project WHERE name+organization_id
  alt Found duplicate
    API-->>Client: 409 Conflict ("Project already exists")
  else Not found
    API->>DB: INSERT project
    DB-->>API: New project row
    API-->>Client: 201 Created (project)
  end
  note over DB,API: DB also enforces UniqueConstraint(name, organization_id)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

I thump my paws: “No double names!”
One warren, one project—so decree frames.
Migrations hop, constraints take root,
CRUD sniffs twice before the recruit.
Tests nibble bugs, ears held high—
A tidy burrow, unique as the sky. 🐇✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch onboardapi/reduce_project_name_limit

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@avirajsingh7 avirajsingh7 linked an issue Aug 27, 2025 that may be closed by this pull request
@codecov
Copy link

codecov bot commented Aug 27, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@avirajsingh7 avirajsingh7 linked an issue Aug 27, 2025 that may be closed by this pull request
Copy link

@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 (1)
backend/app/crud/project.py (1)

14-33: Handle race with DB unique constraint; translate IntegrityError to HTTP 409.

Pre-check is necessary but not sufficient under concurrency. Two requests can pass the check and one will hit a DB unique violation on commit, currently surfacing as a 500. Catch and map to 409.

Apply this refactor:

 def create_project(*, session: Session, project_create: ProjectCreate) -> Project:
     project = get_project_by_name(
         session=session,
         organization_id=project_create.organization_id,
         project_name=project_create.name,
     )
     if project:
         logger.error(
             f"[create_project] Project already exists | 'project_id': {project.id}, 'name': {project.name}"
         )
         raise HTTPException(409, "Project already exists")

     db_project = Project.model_validate(project_create)
     db_project.inserted_at = now()
     db_project.updated_at = now()
-    session.add(db_project)
-    session.commit()
-    session.refresh(db_project)
+    session.add(db_project)
+    try:
+        session.commit()
+    except IntegrityError as e:
+        session.rollback()
+        # Best-effort check to ensure we only map the unique constraint violation
+        if "uq_project_name_org_id" in str(e.orig):
+            logger.error(
+                "[create_project] Unique constraint violated on (name, organization_id)"
+            )
+            raise HTTPException(409, "Project already exists")
+        raise
+    session.refresh(db_project)
     logger.info(
         f"[create_project] Project Created Successfully | 'project_id': {db_project.id}, 'name': {db_project.name}"
     )
     return db_project

And add the import:

from sqlalchemy.exc import IntegrityError
🧹 Nitpick comments (7)
backend/app/models/onboarding.py (1)

32-34: Guard against whitespace-only project names.

Min length 1 allows " " (space) to pass. Add a validator to enforce at least one non-whitespace character to avoid junk names while honoring the 1-char requirement.

Example validator to add:

# Add alongside other validators
@model_validator(mode="after")
def _validate_project_name(self):
    if not (self.project_name and self.project_name.strip()):
        raise ValueError("project_name must contain at least one non-whitespace character")
    return self

Would you like me to add an API/CRUD test for a single-character name and a whitespace-only rejection?

backend/app/models/project.py (2)

3-3: Import UniqueConstraint from sqlalchemy for consistency and portability.

UniqueConstraint is typically sourced from sqlalchemy, and other modules in many codebases follow that. Aligning imports avoids surprises across SQLModel/SQLAlchemy versions.

-from sqlmodel import Field, Relationship, SQLModel, UniqueConstraint
+from sqlmodel import Field, Relationship, SQLModel
+from sqlalchemy import UniqueConstraint

29-31: DB-level uniqueness looks good; consider index hygiene.

The composite unique constraint will create a unique index on (name, organization_id). If you don’t query by name alone, consider dropping the legacy single-column index on project.name in a follow-up migration to reduce write overhead.

backend/app/alembic/versions/8725df286943_unique_constraint_on_project_name_and_.py (2)

9-11: Remove unused imports to satisfy linters and keep migration lean.

-from alembic import op
-import sqlalchemy as sa
-import sqlmodel.sql.sqltypes
+from alembic import op

20-25: Consider a zero-downtime path for large tables (Postgres).

Creating a unique constraint can take an exclusive lock. If the table is large or write-heavy, prefer:

  1. create unique index concurrently on (name, organization_id),
  2. attach it as a constraint via ALTER TABLE ... ADD CONSTRAINT ... UNIQUE USING INDEX ....

Alembic example (optional, Postgres-only):

op.create_index(
    "uqidx_project_name_org_id", "project", ["name", "organization_id"],
    unique=True, postgresql_concurrently=True
)
op.execute(
    "ALTER TABLE project ADD CONSTRAINT uq_project_name_org_id UNIQUE USING INDEX uqidx_project_name_org_id"
)
backend/app/tests/crud/test_project.py (2)

37-50: Drop unused variable to satisfy Ruff F841 and keep test clean.

-    project = create_project(session=db, project_create=project_data)
+    create_project(session=db, project_create=project_data)

37-50: Add a test to assert same-name projects are allowed across different organizations.

This complements the duplicate-in-org test and guards against accidental global uniqueness.

Proposed test:

def test_create_project_same_name_different_orgs(db: Session) -> None:
    org1 = create_test_organization(db)
    org2 = create_test_organization(db)
    name = "shared-name"

    p1 = create_project(session=db, project_create=ProjectCreate(
        name=name, description="p1", is_active=True, organization_id=org1.id
    ))
    p2 = create_project(session=db, project_create=ProjectCreate(
        name=name, description="p2", is_active=True, organization_id=org2.id
    ))

    assert p1.name == p2.name
    assert p1.organization_id != p2.organization_id
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between f187606 and 2b01b08.

📒 Files selected for processing (5)
  • backend/app/alembic/versions/8725df286943_unique_constraint_on_project_name_and_.py (1 hunks)
  • backend/app/crud/project.py (1 hunks)
  • backend/app/models/onboarding.py (1 hunks)
  • backend/app/models/project.py (2 hunks)
  • backend/app/tests/crud/test_project.py (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (5)
backend/app/models/onboarding.py (2)
backend/app/tests/api/routes/test_onboarding.py (1)
  • test_onboard_project_with_auto_generated_defaults (131-160)
backend/app/tests/crud/test_onboarding.py (2)
  • test_onboard_project_new_organization_project_user (26-90)
  • test_onboard_project_response_data_integrity (235-264)
backend/app/tests/crud/test_project.py (4)
backend/app/tests/utils/test_data.py (1)
  • create_test_organization (23-31)
backend/app/tests/utils/utils.py (1)
  • random_lower_string (21-22)
backend/app/models/project.py (1)
  • ProjectCreate (16-17)
backend/app/crud/project.py (1)
  • create_project (13-34)
backend/app/crud/project.py (2)
backend/app/tests/crud/test_onboarding.py (1)
  • test_onboard_project_duplicate_project_name (154-174)
backend/app/tests/api/routes/test_onboarding.py (1)
  • test_onboard_project_duplicate_project_in_organization (91-128)
backend/app/alembic/versions/8725df286943_unique_constraint_on_project_name_and_.py (1)
backend/app/alembic/versions/99f4fc325617_add_organization_project_setup.py (1)
  • upgrade (20-72)
backend/app/models/project.py (2)
backend/app/alembic/versions/99f4fc325617_add_organization_project_setup.py (1)
  • upgrade (20-72)
backend/app/models/assistants.py (1)
  • AssistantBase (11-30)
🪛 Ruff (0.12.2)
backend/app/tests/crud/test_project.py

48-48: Local variable project is assigned to but never used

Remove assignment to unused variable project

(F841)

backend/app/alembic/versions/8725df286943_unique_constraint_on_project_name_and_.py

9-9: sqlalchemy imported but unused

Remove unused import: sqlalchemy

(F401)


10-10: sqlmodel.sql.sqltypes imported but unused

Remove unused import: sqlmodel.sql.sqltypes

(F401)

⏰ 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). (1)
  • GitHub Check: checks (3.11.7, 6)

@AkhileshNegi AkhileshNegi merged commit 721d120 into main Aug 27, 2025
3 checks passed
@AkhileshNegi AkhileshNegi deleted the onboardapi/reduce_project_name_limit branch August 27, 2025 15:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add unique constraint for project names within organization scope Reduce minimum project name length requirement below 3 characters

3 participants