Skip to content

Conversation

@erik-arne
Copy link
Collaborator

@erik-arne erik-arne commented Sep 9, 2025

Add Project model with fields for title, type, and user relation. Include ProjectType enum to categorize projects.

Summary by CodeRabbit

  • New Features
    • Adds Projects linked to your account so you can create and manage multiple projects per user.
    • Supports project types: post, article, ebook, and script.
    • Each project includes a title plus automatic creation and update timestamps.

Add Project model with fields for title, type, and user relation. Include ProjectType enum to categorize projects.
@coderabbitai
Copy link

coderabbitai bot commented Sep 9, 2025

Walkthrough

Adds a new Project model and ProjectType enum to the Prisma schema, creates a one-to-many relation from User to Project via projects, and introduces a DB migration creating the projects table, ProjectType enum, and a foreign key referencing users.id.

Changes

Cohort / File(s) Summary of changes
Prisma schema updates
prisma/schema.prisma
Added enum ProjectType (post, article, ebook, script). Added model Project with fields: id (String @id @default(uuid())), title, type (ProjectType), createdAt, updatedAt, user relation, userId, and @@map("projects"). Updated User model to include projects: Project[].
Database migration
prisma/migrations/20250909132930_added_projects/migration.sql
Created DB enum "ProjectType" and table "projects" with columns id, title, type, createdAt, updatedAt, userId; added primary key on id and foreign key projects_userId_fkey referencing public.users(id) with ON DELETE RESTRICT ON UPDATE CASCADE.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Client
  participant API as API Server
  participant P as Prisma
  participant DB as Database

  Note over C,DB #D3F9D8: Create Project flow (new)
  C->>API: POST /projects { title, type, userId }
  API->>P: prisma.project.create({ data: { title, type, user: { connect: { id: userId } } } })
  P->>DB: INSERT INTO projects (...) VALUES (..., type::ProjectType, ...)
  DB-->>P: Row inserted (FK userId validated)
  P-->>API: Project record
  API-->>C: 201 Created { project }
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

Thump-thump, I map new fields with glee,
A warren of projects under each tree.
Post, article, ebook—scripts that rhyme—
Timestamps sparkle, uuid in time.
I twitch my nose at schemas bright—🐇✨

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.

Pre-merge checks (3 passed)

✅ Passed checks (3 passed)
Check name Status Explanation
Title Check ✅ Passed The title concisely and clearly summarizes the primary change of adding a Project model and its relation to the User schema, using conventional commit style without extraneous details.
Description Check ✅ Passed The description directly corresponds to the schema updates by specifying the new Project model fields and the ProjectType enum, giving reviewers a clear summary of the changes.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/projects

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

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: 2

🧹 Nitpick comments (2)
prisma/schema.prisma (2)

36-41: Align enum casing with existing Role enum

Role uses uppercase variants; ProjectType uses lowercase. Unify for consistency (new enum → safe to change now).

-enum ProjectType {
-  post
-  article
-  ebook
-  script
-}
+enum ProjectType {
+  POST
+  ARTICLE
+  EBOOK
+  SCRIPT
+}

45-46: Optional: constrain title and avoid duplicates per user

If titles are user-facing identifiers, consider a length bound and per-user uniqueness.

-  title     String
+  title     String      @db.VarChar(200)

Add a composite unique (only if product requirements agree):

-  @@map("projects")
+  @@unique([userId, title])
+  @@map("projects")
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d87306a and a92ec3d.

📒 Files selected for processing (1)
  • prisma/schema.prisma (2 hunks)
🔇 Additional comments (1)
prisma/schema.prisma (1)

18-26: User ⇄ Project relation field looks correct

The one-to-many via projects Project[] is correctly modeled and matches Project.user/userId.

@fehranbit fehranbit self-requested a review September 9, 2025 13:35
@fehranbit fehranbit merged commit 9425e74 into main Sep 9, 2025
1 check was pending
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: 1

🧹 Nitpick comments (4)
prisma/migrations/20250909132930_added_projects/migration.sql (4)

9-10: Decide where “updatedAt” is enforced: DB vs. Prisma.

Right now it’s NOT NULL without a DB default/trigger. Prisma’s @updatedat handles app writes, but raw SQL updates/inserts will violate expectations.

Option A (simple): set a default so inserts without Prisma don’t fail:

-    "updatedAt" TIMESTAMP(3) NOT NULL,
+    "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

Option B (robust): DB trigger to auto-update on UPDATE:

CREATE OR REPLACE FUNCTION set_updated_at() RETURNS trigger AS $$
BEGIN NEW."updatedAt" = CURRENT_TIMESTAMP; RETURN NEW; END; $$ LANGUAGE plpgsql;
CREATE TRIGGER projects_set_updated_at BEFORE UPDATE ON "public"."projects"
FOR EACH ROW EXECUTE PROCEDURE set_updated_at();

Also confirm this timestamp precision/type matches existing tables (TIMESTAMP vs TIMESTAMPTZ).


6-6: Consider a DB-side default for id (optional).

You’re storing UUIDs as TEXT; Prisma’s @default(uuid()) will generate ids client-side. Add a DB default to support non-Prisma inserts.

-    "id" TEXT NOT NULL,
+    "id" TEXT NOT NULL DEFAULT gen_random_uuid(),

Note: requires pgcrypto. If unavailable, use uuid-ossp’s uuid_generate_v4(). Keep as TEXT to stay aligned with schema.prisma.


7-7: Guard title quality with a lightweight CHECK (and optional uniqueness).

Prevents blank/whitespace-only titles and overly long values; optionally ensure per-user uniqueness.

     "title" TEXT NOT NULL,
+    CONSTRAINT "projects_title_len_check" CHECK (char_length(btrim("title")) BETWEEN 1 AND 200),

Optionally:

CREATE UNIQUE INDEX "projects_userId_title_uq" ON "public"."projects" ( "userId", lower(btrim("title")) );

If you prefer model-driven control, mirror this as @@index/@@unique in schema.prisma.


17-17: Confirm delete semantics (RESTRICT vs CASCADE).

RESTRICT preserves projects when a user is deleted; many domains prefer CASCADE for dependent rows.

If you want automatic cleanup:

-ALTER TABLE "public"."projects" ADD CONSTRAINT "projects_userId_fkey" FOREIGN KEY ("userId") REFERENCES "public"."users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+ALTER TABLE "public"."projects" ADD CONSTRAINT "projects_userId_fkey" FOREIGN KEY ("userId") REFERENCES "public"."users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a92ec3d and c654a58.

📒 Files selected for processing (1)
  • prisma/migrations/20250909132930_added_projects/migration.sql (1 hunks)
🔇 Additional comments (2)
prisma/migrations/20250909132930_added_projects/migration.sql (2)

1-17: Solid, minimal migration.

Enum + table + FK look consistent with the Prisma summary. No blockers from a DDL standpoint.


1-14: Types and timestamp conventions are consistent
userId is TEXT matching User.id, and createdAt/updatedAt use TIMESTAMP(3) consistently with existing migrations.

Comment on lines +11 to +17
"userId" TEXT NOT NULL,

CONSTRAINT "projects_pkey" PRIMARY KEY ("id")
);

-- AddForeignKey
ALTER TABLE "public"."projects" ADD CONSTRAINT "projects_userId_fkey" FOREIGN KEY ("userId") REFERENCES "public"."users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add an index on the foreign key for performance.

FK columns are common join/filter predicates; indexing avoids full scans and helps FK checks.

Apply after the table creation:

 ALTER TABLE "public"."projects" ADD CONSTRAINT "projects_userId_fkey" FOREIGN KEY ("userId") REFERENCES "public"."users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+
+-- Indexes
+CREATE INDEX "projects_userId_idx" ON "public"."projects" ("userId");

If you frequently filter by user + type, consider a composite:

CREATE INDEX "projects_userId_type_idx" ON "public"."projects" ("userId","type");
🤖 Prompt for AI Agents
In prisma/migrations/20250909132930_added_projects/migration.sql around lines 11
to 17, the migration adds a foreign key on "userId" but does not create an index
for that FK; add a CREATE INDEX statement after the ALTER TABLE to index
"userId" (e.g. name it projects_userId_idx) to speed joins and FK checks, and if
you commonly query by user and type create a composite index
projects_userId_type_idx on ("userId","type") instead; ensure the statements are
added after the table creation/ALTER so the migration applies the indexes.

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