Skip to content

Conversation

aidankmcalister
Copy link
Member

@aidankmcalister aidankmcalister commented Aug 28, 2025

Summary by CodeRabbit

  • New Features

    • Added --env / -e non-interactive mode: prints DATABASE_URL to stdout and claim URL to stderr; supports machine-readable JSON output.
  • Refactor

    • Unified silent/JSON and interactive flows to streamline output, spinners, and error handling.
  • Bug Fixes

    • Validates and blocks incompatible flag combinations early.
    • Ensures claim URL includes a valid source when user agent is absent.
  • Documentation

    • CLI reference, help text, and examples updated to document new flag.
  • Chores

    • Bumped related package versions to 1.0.7.
  • Analytics

    • Tracks usage of the env flag.

Copy link

coderabbitai bot commented Aug 28, 2025

Walkthrough

Adds a new --env / -e CLI flag, validates incompatible flag combinations, refactors createDatabase to use a silent mode, implements env-mode output that writes DATABASE_URL to stdout and a claim URL to stderr, and bumps package versions to 1.0.7.

Changes

Cohort / File(s) Summary
CLI flag, validation, and flow
create-db/index.js
Adds --env/-e flag; updates help/usage and argument parsing; adds validateFlagCombinations(flags) and runs it early; replaces returnJson with silent in createDatabase(name, region, userAgent, silent = false) and threads silent through control flow; implements env-mode path that prints DATABASE_URL to stdout and claim URL to stderr; integrates region resolution, prompts, health checks, analytics (adds has-env-flag), and error handling; claimUrl utm_source uses `userAgent
Documentation
README.md
Adds "CLI Reference" with available flags and examples (including --env/-e); fixes fenced code-block formatting; updates usage examples.
Version bumps
create-db/package.json, create-pg/package.json, create-postgres/package.json
Bumps package versions from 1.0.6 to 1.0.7; no other functional changes.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant U as User
    participant CLI as create-db CLI
    participant FV as validateFlagCombinations
    participant RR as Region Resolver/Prompts
    participant API as createDatabase
    participant OUT as Stdout/Stderr

    U->>CLI: run create-db [--env/-e] [--json] [--region ...]
    CLI->>FV: validateFlagCombinations(flags)
    FV-->>CLI: valid / error
    alt invalid
      CLI->>OUT: print error (stderr)
      CLI-->>U: exit non-zero
    else valid
      opt region missing and interactive allowed
        CLI->>RR: prompt/resolve region
        RR-->>CLI: region
      end
      alt env mode (silent=true)
        CLI->>API: createDatabase(name, region, userAgent, silent=true)
        API-->>CLI: success(result) or error(obj)
        alt success
          CLI->>OUT: print DATABASE_URL (stdout)
          CLI->>OUT: print claim URL (stderr)
          CLI-->>U: exit 0
        else error
          CLI->>OUT: print error (stderr)
          CLI-->>U: exit non-zero
        end
      else normal mode (silent=false)
        CLI->>API: createDatabase(name, region, userAgent, silent=false)
        API-->>CLI: result
        CLI->>OUT: spinners and user-facing messages
        CLI-->>U: exit status
      end
    end
Loading

Possibly related PRs

  • feat: --source flag added #45 — Modifies create-db/index.js and the createDatabase signature; strongly related to signature and claim URL/userAgent handling.
  • DC-4828 --json flag #43 — Introduces JSON/machine-output paths in create-db/index.js; related to the refactor from returnJson to silent.

Suggested reviewers

  • nurul3101
  • ankur-arch
  • mhessdev

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

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 69ffe5b and db27abb.

📒 Files selected for processing (2)
  • README.md (2 hunks)
  • create-db/index.js (12 hunks)
🧰 Additional context used
🪛 LanguageTool
README.md

[grammar] ~13-~13: Use correct spacing
Context: ...tooling and versioning ## CLI Reference ### Available Flags | Flag | De...

(QB_NEW_EN_OTHER_ERROR_IDS_5)


[grammar] ~15-~15: Use correct spacing
Context: ...g ## CLI Reference ### Available Flags | Flag | Description ...

(QB_NEW_EN_OTHER_ERROR_IDS_5)


[grammar] ~26-~26: Use correct spacing
Context: ...r | --env | ### Examples bash # Create database with specific region npx create-db --region eu-west-1 # List available regions npx create-db --list-regions # Interactive mode npx create-db --interactive # Output in JSON format npx create-db --json # Show help npx create-db --help # Get --env response into .env (Be careful to not use `> .env` as that will overwrite your .env) npx create-db --env >> .env # Only DATABASE_URL npx create-db --env >> .env 2>&1 # Both DATABASE_URL and Claim URL # Alternative command shorthand names work the same way npx create-pg -r us-east-1 npx create-pg -j ## Packages ### CLI Tools #### `create-db...

(QB_NEW_EN_OTHER_ERROR_IDS_5)

⏰ 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). (2)
  • GitHub Check: Workers Builds: create-db-worker
  • GitHub Check: Workers Builds: claim-db-worker
🔇 Additional comments (6)
create-db/index.js (6)

221-229: Flag parsing: good addition for --env/-e.

Allowed flags and shorthand mapping look correct.


301-310: Good: disallow interactive with env/json and list-regions combos.

Prevents ambiguous UX in automation contexts.


520-536: Silent success payload: LGTM.

Shape is clear and includes both Prisma and direct strings plus metadata.


539-546: Good: include HTTP status fallback in silent error.

Ensures callers always receive a status.


626-627: Good: validate flag combinations early.

Prevents wasted work before network checks.


643-644: Analytics: has-env-flag metric added.

Useful for adoption tracking.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch DC-4933-env-flag

🪧 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 @coderabbit in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbit 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:
    • @coderabbit gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbit 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 @coderabbit help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbit ignore or @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbit summary or @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbit or @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.

Copy link

cloudflare-workers-and-pages bot commented Aug 28, 2025

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Preview URL Updated (UTC)
✅ Deployment successful!
View logs
claim-db-worker db27abb Commit Preview URL

Branch Preview URL
Aug 28 2025, 03:45 PM

Copy link

Preview CLIs & Workers are live!

Test the CLIs locally under tag pr51-DC-4933-env-flag-17282129083:

npx create-db@pr51
npx create-pg@pr51
npx create-postgres@$pr51

Worker URLs
• Create-DB Worker:
• Claim-DB Worker:

These will live as long as this PR exists under tag pr51-DC-4933-env-flag-17282129083.

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

Caution

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

⚠️ Outside diff range comments (3)
create-db/index.js (3)

197-205: Clarify --env behavior in help text.

Make it explicit that DATABASE_URL goes to stdout and the claim link to stderr.

-  ${chalk.yellow("--env, -e")}                       Outputs DATABASE_URL to the terminal
+  ${chalk.yellow("--env, -e")}                       Print DATABASE_URL to stdout (claim URL to stderr)

Optionally add examples:

  • npx ${CLI_NAME} --env
  • npx ${CLI_NAME} --env --region us-east-1

435-459: Emit analytics in silent mode too (success and failure).

Silent mode currently bypasses analytics for rate-limit, invalid-json, API errors, and success.

   if (resp.status === 429) {
     if (silent) {
+      void sendAnalyticsToWorker("create_db:database_creation_failed", {
+        command: CLI_NAME,
+        region,
+        "error-type": "rate_limit",
+        "status-code": 429,
+        "user-agent": userAgent,
+      });
       return {
         error: "rate_limit_exceeded",
         message:
           "We're experiencing a high volume of requests. Please try again later.",
         status: 429,
       };
     }
   } catch (e) {
     if (silent) {
+      void sendAnalyticsToWorker("create_db:database_creation_failed", {
+        command: CLI_NAME,
+        region,
+        "error-type": "invalid_json",
+        "status-code": resp.status,
+        "user-agent": userAgent,
+      });
       return {
         error: "invalid_json",
         message: "Unexpected response from create service.",
         raw,
         status: resp.status,
       };
     }
   if (silent && !result.error) {
     const jsonResponse = {
       connectionString: prismaConn,
       directConnectionString: directConn,
       claimUrl: claimUrl,
       deletionDate: expiryDate.toISOString(),
       region: database?.region?.id || region,
       name: database?.name,
       projectId: projectId,
     };
     if (userAgent) {
       jsonResponse.userAgent = userAgent;
     }
+    void sendAnalyticsToWorker("create_db:database_created", {
+      command: CLI_NAME,
+      region,
+      utm_source: CLI_NAME,
+    });
     return jsonResponse;
   }
   if (result.error) {
     if (silent) {
+      void sendAnalyticsToWorker("create_db:database_creation_failed", {
+        command: CLI_NAME,
+        region: region,
+        "error-type": "api_error",
+        "error-message": result.error.message,
+        "user-agent": userAgent,
+      });
       return {
         error: "api_error",
         message: result.error.message || "Unknown error",
         details: result.error,
       };
     }

Also applies to: 467-488, 534-558


197-205: Doc follow-up (optional): README usage for --env.

Add a brief section showing how to capture the value (e.g., eval or $(...)).

I can draft the README snippet if helpful.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

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 08d3135 and 0a00cd1.

📒 Files selected for processing (4)
  • create-db/index.js (10 hunks)
  • create-db/package.json (1 hunks)
  • create-pg/package.json (1 hunks)
  • create-postgres/package.json (1 hunks)
⏰ 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). (2)
  • GitHub Check: Workers Builds: create-db-worker
  • GitHub Check: Workers Builds: claim-db-worker
🔇 Additional comments (6)
create-pg/package.json (1)

3-3: Version bump looks good.

Version aligns with the coordinated release.

create-db/package.json (1)

3-3: All package versions synchronized at 1.0.7 and no leftover references found

  • Verified that create-pg, create-postgres, and create-db all specify "version": "1.0.7" in their package.json.
  • Scanned all Markdown files for any remaining "1.0.6" references (e.g., README badges) and found none.
create-postgres/package.json (1)

3-3: Version bump looks good.

Consistent with create-db and create-pg.

create-db/index.js (3)

219-227: Arg parsing for --env/-e looks correct.

Flag is added to allowedFlags and shorthand map.


621-622: Nice: central flag-conflict validation.

Good placement immediately after parsing.


197-197: Action Needed: Manual Verification of --env Help Text, Flag Conflicts, URL Encoding, and DATABASE_URL Construction

I wasn’t able to locate any of the following in create-db/index.js based on the automated searches. Please double-check these areas across lines 197, 299–319, 513–514, and 700–721:

  • Help text for the --env, -e flag indicating it writes the URL to stdout (and/or stderr).
  • Any mention of conflicting flags (env vs. interactive, json vs. interactive) in your option definitions.
  • Usage of encodeURIComponent (or similar) when building the CLAIM_DB_WORKER_URL.
  • Construction of DATABASE_URL using connectionString (or fallback to directConnectionString) followed by a newline.

Without matches from the scripts, I can’t confirm the intended behavior. Please verify these expectations are implemented correctly.

Copy link

Preview CLIs & Workers are live!

Test the CLIs locally under tag pr51-DC-4933-env-flag-17282359601:

npx create-db@pr51
npx create-pg@pr51
npx create-postgres@$pr51

Worker URLs
• Create-DB Worker:
• Claim-DB Worker:

These will live as long as this PR exists under tag pr51-DC-4933-env-flag-17282359601.

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

Caution

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

⚠️ Outside diff range comments (4)
create-db/index.js (4)

191-205: Clarify --env semantics in help and add an example.

Make it explicit that --env is non-interactive, writes DATABASE_URL to stdout, and the claim URL to stderr. Add a usage example.

   Options:
@@
-  ${chalk.yellow("--env, -e")}                       Outputs DATABASE_URL to the terminal
+  ${chalk.yellow("--env, -e")}                       Print DATABASE_URL (Prisma) to stdout; claim URL to stderr (non-interactive)
@@
   Examples:
@@
   ${chalk.gray(`npx ${CLI_NAME} --json --region us-east-1`)}
+  ${chalk.gray(`npx ${CLI_NAME} --env --region us-east-1`)}

536-560: Include HTTP status in api_error silent payload.

Parity with other error branches improves downstream handling.

-      return {
+      return {
         error: "api_error",
         message: result.error.message || "Unknown error",
-        details: result.error,
+        details: result.error,
+        status: resp.status,
       };

680-700: JSON mode exits 0 even on API errors; set non-zero on error.

createDatabase(silent=true) returns an error object; handle it to set exit code.

-        const result = await createDatabase(name, region, userAgent, true);
-        console.log(JSON.stringify(result, null, 2));
-        process.exit(0);
+        const result = await createDatabase(name, region, userAgent, true);
+        const isErr = result && typeof result === "object" && "error" in result;
+        console.log(JSON.stringify(result, null, 2));
+        process.exit(isErr ? 1 : 0);

631-645: Track --env usage in analytics telemetry.

Add a boolean to the initial event similar to other flags.

       "has-json-flag": rawArgs.includes("--json") || rawArgs.includes("-j"),
+      "has-env-flag": rawArgs.includes("--env") || rawArgs.includes("-e"),
       "has-user-agent-from-env": !!userAgent,
♻️ Duplicate comments (3)
create-db/index.js (3)

299-321: Good validation; interactive now disallowed with env/json.

This addresses the non-interactive requirement for automation.


515-516: URL-encode claimUrl parameters and add fallback for userAgent.

Prevent malformed URLs if projectId/userAgent contain reserved characters.

-  const claimUrl = `${CLAIM_DB_WORKER_URL}?projectID=${projectId}&utm_source=${userAgent}&utm_medium=cli`;
+  const claimUrl =
+    `${CLAIM_DB_WORKER_URL}?projectID=${encodeURIComponent(projectId)}` +
+    `&utm_source=${encodeURIComponent(userAgent || CLI_NAME)}&utm_medium=cli`;

702-724: Prefer Prisma connection string; add trailing newlines and guard for missing URL.

DATABASE_URL should prefer result.connectionString, fall back to direct; print a final newline; print claim URL with newline; exit non-zero if missing.

-        if (result.error) {
+        if (result.error) {
           console.error(result.message || "Unknown error");
           process.exit(1);
         }
-        process.stdout.write(`DATABASE_URL="${result.directConnectionString}"`);
-        process.stderr.write(
-          "\n\n# Claim your database at: " + result.claimUrl
-        );
+        const envUrl = result.connectionString || result.directConnectionString;
+        if (!envUrl) {
+          console.error("Connection string not available in API response.");
+          process.exit(1);
+        }
+        process.stdout.write(`DATABASE_URL="${envUrl}"\n`);
+        process.stderr.write(
+          "\n\n# Claim your database at: " + result.claimUrl + "\n"
+        );
         process.exit(0);
📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

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 0a00cd1 and 7d0f22f.

📒 Files selected for processing (1)
  • create-db/index.js (10 hunks)
⏰ 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). (2)
  • GitHub Check: Workers Builds: create-db-worker
  • GitHub Check: Workers Builds: claim-db-worker
🔇 Additional comments (4)
create-db/index.js (4)

219-220: Flag wiring for --env/-e looks correct.

Allowed flags and shorthand mapping are properly updated.

Also applies to: 226-227


436-461: Graceful 429 handling in silent and interactive modes.

The rate-limit branch and analytics look good.


469-490: Robust invalid JSON handling.

Returning a structured error in silent mode is correct; interactive flow properly exits.


623-624: Correct placement of flag-combination validation.

Early exit before doing network work. Good.

Copy link

Preview CLIs & Workers are live!

Test the CLIs locally under tag pr51-DC-4933-env-flag-17283424880:

npx create-db@pr51
npx create-pg@pr51
npx create-postgres@$pr51

Worker URLs
• Create-DB Worker:
• Claim-DB Worker:

These will live as long as this PR exists under tag pr51-DC-4933-env-flag-17283424880.

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

Caution

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

⚠️ Outside diff range comments (2)
create-db/index.js (2)

497-514: Build direct connection URL robustly when user/pass are missing.

Avoid producing postgresql://:@... by conditioning auth segment.

-  const directUser = directConnDetails?.user
-    ? encodeURIComponent(directConnDetails.user)
-    : "";
-  const directPass = directConnDetails?.pass
-    ? encodeURIComponent(directConnDetails.pass)
-    : "";
+  const directUser = directConnDetails?.user
+    ? encodeURIComponent(directConnDetails.user)
+    : "";
+  const directPass = directConnDetails?.pass
+    ? encodeURIComponent(directConnDetails.pass)
+    : "";
   const directHost = directConnDetails?.host;
   const directPort = directConnDetails?.port
     ? `:${directConnDetails.port}`
     : "";
   const directDbName = directConnDetails?.database || "postgres";
+  const directAuth =
+    directUser || directPass ? `${directUser}:${directPass}@` : "";
   const directConn =
     directConnDetails && directHost
-      ? `postgresql://${directUser}:${directPass}@${directHost}${directPort}/${directDbName}?sslmode=require`
+      ? `postgresql://${directAuth}${directHost}${directPort}/${directDbName}?sslmode=require`
       : null;

654-657: Avoid IP geolocation when region is provided (privacy/latency).

Skip detectUserLocation if --region is set.

-    let name = new Date().toISOString();
-    let userLocation = await detectUserLocation();
-    let region = getRegionClosestToLocation(userLocation) || "us-east-1";
+    let name = new Date().toISOString();
+    let region = flags.region || "us-east-1";
+    if (!flags.region) {
+      const userLocation = await detectUserLocation();
+      region = getRegionClosestToLocation(userLocation) || region;
+    }
♻️ Duplicate comments (3)
create-db/index.js (3)

420-426: Document silent mode return shape with JSDoc.

Add JSDoc so callers know the dual return types in silent vs. non-silent.

+/**
+ * Create a database.
+ * @param {string} name
+ * @param {string} region
+ * @param {string|undefined} userAgent
+ * @param {boolean} silent - When true, returns a JSON-friendly object or error object instead of logging/exiting.
+ * @returns {Promise<
+ *   | { connectionString?: string, directConnectionString?: string, claimUrl: string, deletionDate: string, region: string, name?: string, projectId: string, userAgent?: string }
+ *   | { error: string, message: string, status?: number, details?: unknown, raw?: string }
+ *   | void
+ * >}
+ */
 async function createDatabase(name, region, userAgent, silent = false) {

516-516: URL-encode claimUrl parameters and provide userAgent fallback.

userAgent/projectId may contain reserved characters.

-  const claimUrl = `${CLAIM_DB_WORKER_URL}?projectID=${projectId}&utm_source=${userAgent}&utm_medium=cli`;
+  const claimUrl =
+    `${CLAIM_DB_WORKER_URL}?projectID=${encodeURIComponent(projectId)}` +
+    `&utm_source=${encodeURIComponent(userAgent || CLI_NAME)}&utm_medium=cli`;

705-726: Env mode: prefer Prisma connection string, add newlines, and guard missing value.

Print Prisma-optimized URL when available, fall back to direct, and end lines with newline.

-        if (result.error) {
+        if (result.error) {
           console.error(result.message || "Unknown error");
           process.exit(1);
         }
-        process.stdout.write(`DATABASE_URL="${result.directConnectionString}"`);
-        process.stderr.write(
-          "\n\n# Claim your database at: " + result.claimUrl
-        );
+        const envUrl = result.connectionString || result.directConnectionString;
+        if (!envUrl) {
+          console.error("Connection string not available in API response.");
+          process.exit(1);
+        }
+        process.stdout.write(`DATABASE_URL="${envUrl}"\n`);
+        process.stderr.write(`\n\n# Claim your database at: ${result.claimUrl}\n`);
         process.exit(0);
📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

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 7d0f22f and 7edd860.

📒 Files selected for processing (1)
  • create-db/index.js (11 hunks)
⏰ 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). (2)
  • GitHub Check: Workers Builds: claim-db-worker
  • GitHub Check: Workers Builds: create-db-worker
🔇 Additional comments (5)
create-db/index.js (5)

220-228: Flag and shorthand wiring for --env look good.


300-322: Good: conflicts now block --interactive with --env/--json.


519-535: Silent success payload is coherent.


619-626: Validating flag combinations early is correct.


642-643: Analytics flag tracking updated for --env.

Copy link

Preview CLIs & Workers are live!

Test the CLIs locally under tag pr51-DC-4933-env-flag-17293580791:

npx create-db@pr51
npx create-pg@pr51
npx create-postgres@$pr51

Worker URLs
• Create-DB Worker:
• Claim-DB Worker:

These will live as long as this PR exists under tag pr51-DC-4933-env-flag-17293580791.

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

♻️ Duplicate comments (4)
create-db/index.js (4)

197-206: Clarify --env help to specify stdout/stderr.

Make it explicit for scripting/redirects.

-  ${chalk.yellow("--env, -e")}                       Prints DATABASE_URL to the terminal
+  ${chalk.yellow("--env, -e")}                       Prints DATABASE_URL to stdout (claim URL to stderr)

420-423: Document the silent return shape for createDatabase.

Add JSDoc so callers know the dual-mode contract.

+/**
+ * Create a database.
+ * @param {string} name
+ * @param {string} region
+ * @param {string|undefined} userAgent
+ * @param {boolean} silent - When true, returns a JSON-friendly object instead of logging/exiting.
+ * @returns {Promise<
+ *   | { connectionString?: string, directConnectionString?: string, claimUrl: string, deletionDate: string, region: string, name?: string, projectId: string, userAgent?: string }
+ *   | { error: string, message: string, status?: number, details?: unknown }
+ *   | void
+ * >}
+ */
 async function createDatabase(name, region, userAgent, silent = false) {

516-516: URL-encode claimUrl parameters.

userAgent/projectId can contain reserved characters; encode them.

-  const claimUrl = `${CLAIM_DB_WORKER_URL}?projectID=${projectId}&utm_source=${userAgent}&utm_medium=cli`;
+  const claimUrl =
+    `${CLAIM_DB_WORKER_URL}?projectID=${encodeURIComponent(projectId)}` +
+    `&utm_source=${encodeURIComponent(userAgent || CLI_NAME)}&utm_medium=cli`;

708-729: Env-mode output: prefer Prisma connection string; add newlines and guard.

Prisma tools expect the Prisma-optimized URL. Also terminate lines with newline and handle missing values.

-        if (result.error) {
+        if (result.error) {
           console.error(result.message || "Unknown error");
           process.exit(1);
         }
-        process.stdout.write(`DATABASE_URL="${result.directConnectionString}"`);
-        process.stderr.write(
-          "\n\n# Claim your database at: " + result.claimUrl
-        );
+        const envUrl = result.connectionString || result.directConnectionString;
+        if (!envUrl) {
+          console.error("Connection string not available in API response.");
+          process.exit(1);
+        }
+        process.stdout.write(`DATABASE_URL="${envUrl}"\n`);
+        process.stderr.write(
+          "\n\n# Claim your database at: " + result.claimUrl + "\n"
+        );
         process.exit(0);
📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

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 7edd860 and 8cabcd8.

📒 Files selected for processing (1)
  • create-db/index.js (12 hunks)
⏰ 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). (2)
  • GitHub Check: Workers Builds: create-db-worker
  • GitHub Check: Workers Builds: claim-db-worker
🔇 Additional comments (8)
create-db/index.js (8)

214-229: Arg parsing exposes --env/-e correctly.

Allowed flags and shorthand mapping look good.


300-322: Good: conflicting flag validation covers env/json and interactive combos.

This addresses non-interactive requirements for env/json modes.


438-445: Good: 429 handling returns structured silent error.

Clear message and status for rate limiting.


470-477: Good: robust silent error on invalid JSON.

Includes raw payload and HTTP status.


519-535: Silent success payload shape looks good.

Includes both Prisma and direct connection strings plus metadata.


538-545: Nice: include HTTP status fallback in silent error.

Using result.error.status ?? resp.status is correct.


625-626: Good: early validation of flag combinations.

Prevents entering invalid execution paths.


642-643: Good: analytics captures --env usage.

Helpful for telemetry.

Copy link

Preview CLIs & Workers are live!

Test the CLIs locally under tag pr51-DC-4933-env-flag-17293927997:

npx create-db@pr51
npx create-pg@pr51
npx create-postgres@$pr51

Worker URLs
• Create-DB Worker:
• Claim-DB Worker:

These will live as long as this PR exists under tag pr51-DC-4933-env-flag-17293927997.

Copy link

Preview CLIs & Workers are live!

Test the CLIs locally under tag pr51-DC-4933-env-flag-17298069185:

npx create-db@pr51
npx create-pg@pr51
npx create-postgres@$pr51

Worker URLs
• Create-DB Worker:
• Claim-DB Worker:

These will live as long as this PR exists under tag pr51-DC-4933-env-flag-17298069185.

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

Caution

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

⚠️ Outside diff range comments (1)
README.md (1)

145-166: Fix broken code fences in README.md
Headings under “Local Development” are rendered as code because the four-backtick bash fence isn’t closed before the nested env block. Split into separate triple-backtick blocks: close the bash block after the install steps, then reopen for the markdown and env snippet.

Apply:

-````bash
+```bash
 # Clone the repository
 git clone https://github.com/prisma/create-db.git
 cd create-db

 # Install dependencies
 pnpm install

 # Install dependencies for each package
 cd create-db-worker && pnpm install
 cd ../claim-db-worker && pnpm install
 cd ../create-db && pnpm install
-### Local Development
-
-#### 1. Configure Environment Variables
-
-**Create DB Worker** (`create-db-worker/.dev.vars`):
-
-```env
-INTEGRATION_TOKEN=your_prisma_integration_token
-````
+```
+
+### Local Development
+
+#### 1. Configure Environment Variables
+
+**Create DB Worker** (`create-db-worker/.dev.vars`):
+
+```env
+INTEGRATION_TOKEN=your_prisma_integration_token
+```
📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

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 a7e9b5f and a1e6a4c.

📒 Files selected for processing (1)
  • README.md (3 hunks)
🧰 Additional context used
🪛 LanguageTool
README.md

[grammar] ~13-~13: Use correct spacing
Context: ...tooling and versioning ## CLI Reference ### Available Flags | Flag | De...

(QB_NEW_EN_OTHER_ERROR_IDS_5)


[grammar] ~15-~15: Use correct spacing
Context: ...g ## CLI Reference ### Available Flags | Flag | Description ...

(QB_NEW_EN_OTHER_ERROR_IDS_5)


[grammar] ~17-~17: There might be a mistake here.
Context: ... | Example | | ---------------- | -------------------...

(QB_NEW_EN)


[grammar] ~18-~18: There might be a mistake here.
Context: ...--------------- | -------------------- | | --region | Specify database re...

(QB_NEW_EN)


[grammar] ~19-~19: There might be a mistake here.
Context: ...ion | --region us-east-1 | | --list-regions | List available regi...

(QB_NEW_EN)


[grammar] ~20-~20: There might be a mistake here.
Context: ...ns | --list-regions | | --interactive | Enable interactive ...

(QB_NEW_EN)


[grammar] ~21-~21: There might be a mistake here.
Context: ...egion selection | --interactive | | --help | Show help informati...

(QB_NEW_EN)


[grammar] ~22-~22: There might be a mistake here.
Context: ...n | --help | | --json | Output the info in ...

(QB_NEW_EN)


[grammar] ~23-~23: Use correct spacing
Context: ... JSON format | --json | ### Examples ```bash # Create database with...

(QB_NEW_EN_OTHER_ERROR_IDS_5)


[grammar] ~25-~25: Use correct spacing
Context: ... | --json | ### Examples bash # Create database with specific region npx create-db --region eu-west-1 # List available regions npx create-db --list-regions # Interactive mode npx create-db --interactive # Output in JSON format npx create-db --json # Show help npx create-db --help # Alternative command shorthand names work the same way npx create-pg -r us-east-1 npx create-pg -j ## Packages ### CLI Tools #### `create-db...

(QB_NEW_EN_OTHER_ERROR_IDS_5)

⏰ 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). (2)
  • GitHub Check: Workers Builds: create-db-worker
  • GitHub Check: Workers Builds: claim-db-worker
🔇 Additional comments (1)
README.md (1)

25-46: Remove or postpone --env examples until the flag is implemented
The CLI currently has no --env/-e option, so examples can’t be added.

Likely an incorrect or invalid review comment.

Copy link

Preview CLIs & Workers are live!

Test the CLIs locally under tag pr51-DC-4933-env-flag-17298495170:

npx create-db@pr51
npx create-pg@pr51
npx create-postgres@$pr51

Worker URLs
• Create-DB Worker:
• Claim-DB Worker:

These will live as long as this PR exists under tag pr51-DC-4933-env-flag-17298495170.

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

Caution

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

⚠️ Outside diff range comments (1)
README.md (1)

150-171: Fix broken code fences (mismatched triple/quad backticks).

The block opened at Line 150 (````bash) isn’t closed until Line 171, swallowing intervening prose and the nested env fence. Close the install block before “### Local Development” and use matching triple backticks for the env snippet.

Apply:

-````bash
+```bash
 # Clone the repository
 git clone https://github.com/prisma/create-db.git
 cd create-db
@@
 cd ../create-db && pnpm install
-
-### Local Development
+```
+
+### Local Development
@@
-```env
+```env
 INTEGRATION_TOKEN=your_prisma_integration_token
-````
+```
♻️ Duplicate comments (1)
README.md (1)

17-25: Tighten flag descriptions, add short aliases, and document env incompatibilities.

  • Make --json phrasing concise.
  • Show short flags -r, -j that are used in Examples.
  • Note --env’s non-interactive behavior and incompatibilities (--json, --interactive, --list-regions) directly in the table.

Apply:

-| `--region`       | Specify database region                           | `--region us-east-1` |
+| `--region`, `-r` | Specify database region                           | `--region us-east-1` |
 | `--list-regions` | List available regions                            | `--list-regions`     |
 | `--interactive`  | Enable interactive region selection               | `--interactive`      |
 | `--help`         | Show help information                             | `--help`             |
-| `--json`         | Output the info in a JSON format                  | `--json`             |
-| `--env`, `-e`    | Print DATABASE_URL to stdout; claim URL to stderr | `--env`              |
+| `--json`, `-j`   | Output in JSON format                             | `--json`             |
+| `--env`, `-e`    | Print DATABASE_URL to stdout; claim URL to stderr. Non-interactive. Incompatible with `--json`, `--interactive`, and `--list-regions`. | `--env`              |

Run to confirm short flags exist in the CLI definition:

#!/bin/bash
# Validate aliases in create-db CLI (yargs/commander style)
rg -nP --type=js --type=ts -C2 "(alias\\(['\"][rj]['\"]|\\balias:\\s*\\{[^}]*['\"]r['\"][^}]*\\}|\\balias:\\s*\\{[^}]*['\"]j['\"][^}]*\\})" create-db
rg -nP --type=js --type=ts -C2 "\\b(--env|--json|--interactive|--list-regions|--region)\\b" create-db
📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

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 a1e6a4c and 327abc2.

📒 Files selected for processing (1)
  • README.md (3 hunks)
🧰 Additional context used
🪛 LanguageTool
README.md

[grammar] ~13-~13: Use correct spacing
Context: ...tooling and versioning ## CLI Reference ### Available Flags | Flag | De...

(QB_NEW_EN_OTHER_ERROR_IDS_5)


[grammar] ~15-~15: Use correct spacing
Context: ...g ## CLI Reference ### Available Flags | Flag | Description ...

(QB_NEW_EN_OTHER_ERROR_IDS_5)


[grammar] ~26-~26: Use correct spacing
Context: ...r | --env | ### Examples bash # Create database with specific region npx create-db --region eu-west-1 # List available regions npx create-db --list-regions # Interactive mode npx create-db --interactive # Output in JSON format npx create-db --json # Show help npx create-db --help # Get --env response into .env npx create-db --env > .env # Only DATABASE_URL npx create-db --env > .env 2>&1 # Both DATABASE_URL and Claim URL # Alternative command shorthand names work the same way npx create-pg -r us-east-1 npx create-pg -j ## Packages ### CLI Tools #### `create-db...

(QB_NEW_EN_OTHER_ERROR_IDS_5)

⏰ 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). (2)
  • GitHub Check: Workers Builds: claim-db-worker
  • GitHub Check: Workers Builds: create-db-worker

Copy link

Preview CLIs & Workers are live!

Test the CLIs locally under tag pr51-DC-4933-env-flag-17298727080:

npx create-db@pr51
npx create-pg@pr51
npx create-postgres@$pr51

Worker URLs
• Create-DB Worker:
• Claim-DB Worker:

These will live as long as this PR exists under tag pr51-DC-4933-env-flag-17298727080.

mhessdev
mhessdev previously approved these changes Aug 28, 2025
Copy link

Preview CLIs & Workers are live!

Test the CLIs locally under tag pr51-DC-4933-env-flag-17300940667:

npx create-db@pr51
npx create-pg@pr51
npx create-postgres@$pr51

Worker URLs
• Create-DB Worker:
• Claim-DB Worker:

These will live as long as this PR exists under tag pr51-DC-4933-env-flag-17300940667.

@aidankmcalister aidankmcalister merged commit 1b633e4 into main Aug 28, 2025
4 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