Skip to content

feat(cli): improve prisma postgres create db setup - #558

Merged
AmanVarshney01 merged 1 commit into
mainfrom
prisma-create-db-json
Sep 1, 2025
Merged

AmanVarshney01 merged 1 commit into
mainfrom
prisma-create-db-json

Conversation

@AmanVarshney01

@AmanVarshney01 AmanVarshney01 commented Sep 1, 2025 •

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • New Features

    • Interactive region selection for Postgres database creation.
    • Progress spinner during database provisioning.
    • Automatic parsing of JSON output to derive the correct database URL (direct vs Accelerate based on ORM).
    • Persists optional claim URL to environment and surfaces it in logs.
    • Clearer success messaging, including connection type and claim URL details.
  • Style

    • Added repository-wide coding standards: functional programming, normal function syntax (no arrows), no emojis, and prefer type over interface.
  • Chores

    • Updated CLI setup flow to use JSON-based database creation with region awareness.

@coderabbitai

coderabbitai Bot commented Sep 1, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds a repository-wide Cursor rules file and refactors the Prisma Postgres CLI setup to use a JSON/region-driven create-db flow with a spinner, structured output parsing, and optional CLAIM_URL persistence and logging.

Changes

Cohort / File(s) Summary
Repo rules configuration
\.cursor/rules/better-t-stack-repo.mdc
Adds a Cursor rules file with alwaysApply: true and guidelines: prefer functional programming, normal function syntax (no arrow functions), no emojis, and use type syntax instead of interface syntax.
Prisma Postgres setup refactor
apps/cli/src/helpers/database-providers/prisma-postgres-setup.ts
Reworks setup to run create-db@latest with --json and region selection, shows a spinner, parses JSON output (connection/claim URLs), chooses connection string based on ORM, writes optional CLAIM_URL to apps/server/.env, and updates success messaging.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor U as User
  participant C as CLI Prisma Postgres Setup
  participant R as Region Selector
  participant D as create-db@latest
  participant P as JSON Parser
  participant E as Env Writer
  participant L as Logger

  U->>C: Run setup
  C->>R: Prompt for region
  R-->>C: Selected region
  C->>D: Execute create-db --json --region <region>
  activate C
  D-->>C: JSON stdout (CreateDbResponse)
  C->>P: Parse JSON output
  alt Parse OK
    P-->>C: connectionString(s), claimUrl?
    C->>C: Choose DB URL (direct vs standard) based on ORM
    opt claimUrl present
      C->>E: Write CLAIM_URL to apps/server/.env
      E-->>C: Done
    end
    C->>L: Log success and optional claim URL info
  else Parse error
    P-->>C: Error
    C->>L: Log parse/creation error
  end
  deactivate C
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

I thump my foot—new regions bloom,
A spinner whirls, dispelling gloom.
JSON whispers where to go,
A claim URL in tidy tow.
Env gets ink, the logs chime bright—
Postgres ready, nibble-night. 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch prisma-create-db-json

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 or @coderabbit 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.

@AmanVarshney01
AmanVarshney01 merged commit b2b9050 into main Sep 1, 2025
@AmanVarshney01
AmanVarshney01 deleted the prisma-create-db-json branch September 1, 2025 10:38

@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

Caution

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

⚠️ Outside diff range comments (1)
apps/cli/src/helpers/database-providers/prisma-postgres-setup.ts (1)

174-186: Remove dotenv injection; violates repo guidelines (Bun auto-loads .env)

Guidelines: “Do not use dotenv; Bun auto-loads .env”. Drop the import insertion and its call.

-async function addDotenvImportToPrismaConfig(projectDir: string) {
-  try {
-    const prismaConfigPath = path.join(
-      projectDir,
-      "apps/server/prisma.config.ts",
-    );
-    let content = await fs.readFile(prismaConfigPath, "utf8");
-    content = `import "dotenv/config";\n${content}`;
-    await fs.writeFile(prismaConfigPath, content);
-  } catch (_error) {
-    consola.error("Failed to update prisma.config.ts");
-  }
-}
@@
-      if (orm === "prisma") {
-        await addDotenvImportToPrismaConfig(projectDir);
-        await addPrismaAccelerateExtension(serverDir);
-      }
+      if (orm === "prisma") {
+        await addPrismaAccelerateExtension(serverDir);
+      }

Also applies to: 283-286

🧹 Nitpick comments (10)
.cursor/rules/better-t-stack-repo.mdc (2)

6-8: Tighten wording and fix typos in rules list

Clarify and correct grammar to avoid ambiguity.

- use normal function syntax for functions do not use arrow functions
+ use normal function syntax for functions (do not use arrow functions)
- use type syntax, dont use interface syntax for types
+ use type syntax; don't use interface syntax for types

5-5: Be explicit about “functional programming” scope

If this is an enforcement signal for Cursor, consider clarifying “prefer functional style (pure functions, immutability where practical)” to reduce subjective interpretations.

apps/cli/src/helpers/database-providers/prisma-postgres-setup.ts (8)

60-76: Stop spinner after successful JSON parse; show failure on parse error

Currently it prints “success” even when JSON parsing fails.

-    s.start("Creating Prisma Postgres database...");
+    s.start("Creating Prisma Postgres database...");
@@
-    s.stop("Database created successfully!");
-
-    let createDbResponse: CreateDbResponse;
-    try {
-      createDbResponse = JSON.parse(stdout) as CreateDbResponse;
-    } catch {
-      consola.error("Failed to parse create-db response");
-      return null;
-    }
+    let createDbResponse: CreateDbResponse;
+    try {
+      createDbResponse = JSON.parse(stdout) as CreateDbResponse;
+      s.stop("Database created successfully!");
+    } catch {
+      s.stop("Failed to create database");
+      consola.error("Failed to parse create-db response");
+      return null;
+    }

28-35: Literal-type AVAILABLE_REGIONS and type-safe select value

Strengthen types; avoid any/string leaks.

-const AVAILABLE_REGIONS = [
+const AVAILABLE_REGIONS = [
   { value: "ap-southeast-1", label: "Asia Pacific (Singapore)" },
   { value: "ap-northeast-1", label: "Asia Pacific (Tokyo)" },
   { value: "eu-central-1", label: "Europe (Frankfurt)" },
   { value: "eu-west-3", label: "Europe (Paris)" },
   { value: "us-east-1", label: "US East (N. Virginia)" },
   { value: "us-west-1", label: "US West (N. California)" },
-];
+] as const;
@@
-const selectedRegion = await select({
+type Region = typeof AVAILABLE_REGIONS[number]["value"];
+const selectedRegion = await select<Region>({
   message: "Select your preferred region:",
   options: AVAILABLE_REGIONS,
   initialValue: "ap-southeast-1",
 });

Also applies to: 47-51


18-26: Loosen CreateDbResponse for resilience and future-proofing

Some fields may be absent depending on CLI/version. Make optional where safe.

 type CreateDbResponse = {
-  connectionString: string;
-  directConnectionString: string;
-  claimUrl: string;
-  deletionDate: string;
-  region: string;
-  name: string;
-  projectId: string;
+  connectionString?: string;
+  directConnectionString?: string;
+  claimUrl?: string;
+  deletionDate?: string;
+  region?: string;
+  name?: string;
+  projectId?: string;
 };

Also guard when deriving databaseUrl (e.g., throw if missing).


78-82: Guard against missing connection strings

Avoid undefined DATABASE_URL on schema changes.

-const databaseUrl =
-  orm === "drizzle"
-    ? createDbResponse.directConnectionString
-    : createDbResponse.connectionString;
+const databaseUrl =
+  orm === "drizzle"
+    ? createDbResponse.directConnectionString
+    : createDbResponse.connectionString;
+if (!databaseUrl) {
+  consola.error("create-db response missing connection string");
+  return null;
+}

124-131: Validation may be too strict for future Prisma URLs

If Prisma changes the scheme, this will block valid inputs. Consider a looser validator that still ensures Prisma Accelerate usage.

- if (!value.startsWith("prisma+postgres://")) {
-   return "URL should start with prisma+postgres://";
- }
+ const valid = /^prisma\+postgres:\/\//.test(value);
+ if (!valid) return "Expected Prisma Accelerate URL (prisma+postgres://...)";

199-215: Avoid overwriting files; make replacement more robust

  • Only create prisma/index.ts if absent.
  • Use regex to replace PrismaClient construction to handle formatting variants.
-const prismaIndexPath = path.join(serverDir, "prisma/index.ts");
-const prismaIndexContent = `
+const prismaIndexPath = path.join(serverDir, "prisma/index.ts");
+const prismaIndexContent = `
 import { PrismaClient } from "./generated/client";
 import { withAccelerate } from "@prisma/extension-accelerate";
 
 const prisma = new PrismaClient().$extends(withAccelerate());
 
 export default prisma;
 `;
-await fs.writeFile(prismaIndexPath, prismaIndexContent.trim());
+if (!(await fs.pathExists(prismaIndexPath))) {
+  await fs.writeFile(prismaIndexPath, prismaIndexContent.trim());
+}
@@
-dbFileContent = dbFileContent.replace(
-  "export const db = new PrismaClient();",
-  "export const db = new PrismaClient().$extends(withAccelerate());",
-);
+dbFileContent = dbFileContent.replace(
+  /export\s+const\s+db\s*=\s*new\s+PrismaClient\(\)\s*;/,
+  "export const db = new PrismaClient().$extends(withAccelerate());",
+);

Also applies to: 217-231


296-298: Avoid echoing sensitive claim URLs to console

Treat claimUrl as sensitive. Point users to .env instead of printing the value.

-if (prismaConfig.claimUrl) {
-  log.info(pc.blue(`Claim URL saved to .env: ${prismaConfig.claimUrl}`));
-}
+if (prismaConfig.claimUrl) {
+  log.info(pc.blue("Claim URL saved to apps/server/.env (CLAIM_URL)."));
+}

149-166: CLAIM_URL isn’t consumed
Defined only in apps/cli/src/helpers/database-providers/prisma-postgres-setup.ts (lines 160–166) and never referenced elsewhere; remove it from the generated .env to avoid unnecessary secrets.

📜 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 0fbb7ef and 39e0d6a.

📒 Files selected for processing (2)
  • .cursor/rules/better-t-stack-repo.mdc (1 hunks)
  • apps/cli/src/helpers/database-providers/prisma-postgres-setup.ts (4 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/convex_rules.mdc)

**/*.{ts,tsx}: Use Id from './_generated/dataModel' to type document ids (e.g., Id<'users'>)
Ensure Record key/value types align with validators (e.g., v.record(v.id('users'), v.string()) => Record<Id<'users'>, string>)
Be strict with types for document ids; prefer Id<'table'> over string
Use 'as const' for string literals in discriminated unions
When using Array and Record types, declare with explicit generic types (e.g., const arr: Array = ...)

Files:

  • apps/cli/src/helpers/database-providers/prisma-postgres-setup.ts
**/*.{js,jsx,ts,tsx,mjs,cjs}

📄 CodeRabbit inference engine (.cursor/rules/use-bun-instead-of-node-vite-npm-pnpm.mdc)

**/*.{js,jsx,ts,tsx,mjs,cjs}: Do not use dotenv; Bun auto-loads .env
Use Bun.serve() for HTTP/WebSockets; do not use express
Use bun:sqlite for SQLite; do not use better-sqlite3
Use Bun.redis for Redis; do not use ioredis
Use Bun.sql for Postgres; do not use pg or postgres.js
Use built-in WebSocket; do not use ws
Prefer Bun.file over node:fs readFile/writeFile
Use Bun.$ instead of execa for shelling out

Files:

  • apps/cli/src/helpers/database-providers/prisma-postgres-setup.ts
🧠 Learnings (1)
📚 Learning: 2025-08-24T18:00:39.152Z
Learnt from: CR
PR: AmanVarshney01/create-better-t-stack#0
File: .cursor/rules/convex_rules.mdc:0-0
Timestamp: 2025-08-24T18:00:39.152Z
Learning: Applies to convex/**/*.ts : Always use the new Convex function syntax (query/mutation/action/internal*) with args/returns/handler

Applied to files:

  • .cursor/rules/better-t-stack-repo.mdc
🧬 Code graph analysis (1)
apps/cli/src/helpers/database-providers/prisma-postgres-setup.ts (2)
apps/cli/src/types.ts (2)
  • PackageManager (64-64)
  • ORM (11-11)
apps/cli/src/utils/package-runner.ts (1)
  • getPackageExecutionCommand (11-23)

import { isCancel, log, select, text } from "@clack/prompts";
import { isCancel, log, select, spinner, text } from "@clack/prompts";
import { consola } from "consola";
import { execa } from "execa";

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.

🛠️ Refactor suggestion

Use Bun.$ for subprocesses instead of execa

Guidelines require Bun.$. Replace execa calls accordingly.

-import { execa } from "execa";
+import { $ } from "bun";
@@
-    const { stdout } = await execa(createDbCommand, {
-      cwd: serverDir,
-      shell: true,
-    });
+    const stdout = await $`bash -lc "cd ${serverDir} && ${createDbCommand}"`.text();
@@
-    await execa(prismaInitCommand, {
-      cwd: serverDir,
-      stdio: "inherit",
-      shell: true,
-    });
+    await $`bash -lc "cd ${serverDir} && ${prismaInitCommand}"`;

If you prefer avoiding bash -lc, split args and use $ with a cwd-scoped variant.

Also applies to: 63-66, 112-116

🤖 Prompt for AI Agents
In apps/cli/src/helpers/database-providers/prisma-postgres-setup.ts around line
4 (also apply changes at lines 63-66 and 112-116), replace usage of execa
imports and calls with Bun.$ subprocess calls; remove the import of execa and
convert each execa invocation to Bun.$ by passing the command and args without
relying on "bash -lc" (or if you must use a shell, use Bun.spawn or Bun.$ with
proper shell flag), and prefer passing argv as separate elements and using the
cwd option when needed to avoid shell quoting issues; ensure exit codes/errors
are handled similarly (await the Bun.$ promise or catch errors) so behavior and
logging remain consistent.

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.

1 participant