Skip to content

Add CockroachDB support#12

Merged
bnziv merged 5 commits intomainfrom
feat/cockroachdb-support
Nov 22, 2025
Merged

Add CockroachDB support#12
bnziv merged 5 commits intomainfrom
feat/cockroachdb-support

Conversation

@bnziv
Copy link
Copy Markdown
Collaborator

@bnziv bnziv commented Nov 21, 2025

Summary by CodeRabbit

  • New Features

    • CockroachDB added to local dev scripts and package tooling (db up/down/reset and helpers).
    • CockroachDB included in generated imports and no-ORM workflows.
  • Improvements

    • Docker Compose output now includes container start command and updated CockroachDB image.
    • Initialization and readiness checks for CockroachDB improved.
    • ID generation for historical counts moved to a sequence-based approach.
  • Behavioral

    • Generated projects now target a SQL-based CockroachDB client instead of a pooled client.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Nov 21, 2025

Walkthrough

Switches CockroachDB generator output from a pg Pool to Bun SQL, changes DATABASE_URL scheme for CockroachDB to PostgreSQL-style, updates Docker init templates and image/command, replaces unique_rowid() with a sequence for uid, and adds CockroachDB lifecycle scripts to package.json.

Changes

Cohort / File(s) Summary
Env mapping
src/generators/configurations/generateEnv.ts
CockroachDB DATABASE_URL mapping changed from cockroachdb://user:password@localhost:26257/database to PostgreSQL-style postgresql://root@localhost:26257/database.
Package scripts
src/generators/configurations/generatePackageJson.ts
Adds Docker lifecycle scripts and lifecycle hooks for CockroachDB when databaseEngine is cockroachdb and no host provided (db:up, db:down, db:reset, db:cockroach plus pre/post hooks).
Docker init & templates
src/generators/db/dockerInitTemplates.ts
Replaced unique_rowid() uid with sequence-backed BIGINT (count_history_uid_seq + nextval(...)); prepends sleep 1 and adds --database=database to CLI init; readiness check now uses cockroach sql -e "select 1" instead of pg_isready.
Docker container generation
src/generators/db/generateDockerContainer.ts
Introduced command field in DB templates and emit it in Docker Compose; CockroachDB image updated to cockroachdb/cockroach:latest-v25.3, env var changed to COCKROACH_DATABASE: 'database', and command set to start-single-node --insecure. Other DB templates now include a command (empty string).
Handler templates / driver config
src/generators/db/handlerTemplates.ts
Switched CockroachDB driver configuration from Pool (pg) to SQL (bun): dbType set to SQL, import lines changed to import SQL from bun, queries switched to PostgreSQL SQL query operations, and removed Pool-specific cockroachdbPoolQueryOperations.
Project DB codegen
src/generators/project/generateDBBlock.ts, src/generators/project/generateImportsBlock.ts
When no custom host, generator now instantiates SQL for CockroachDB (instead of Pool); imports block updated to include CockroachDB alongside PostgreSQL for no-ORM paths.

Sequence Diagram

sequenceDiagram
    participant Gen as Generator
    participant CG as Codegen
    participant DB as CockroachDB

    rect rgb(245,245,255)
    Note over Gen,CG: Old flow (pg Pool / unique_rowid)
    Gen->>CG: emit DB block using Pool(DATABASE_URL)
    CG->>DB: pg.Pool connect
    DB-->>CG: unique_rowid() IDs
    end

    rect rgb(245,255,245)
    Note over Gen,CG: New flow (bun SQL / sequence)
    Gen->>CG: emit DB block using SQL(DATABASE_URL)
    CG->>DB: Bun SQL connect
    DB-->>CG: sequence-based IDs (nextval)
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Pay attention to handlerTemplates.ts (Pool→SQL migration, imports, and query compatibility).
  • Verify dockerInitTemplates.ts (sequence DDL and readiness check) and generateDockerContainer.ts (command emission and YAML formatting).
  • Confirm consistency of DATABASE_URL scheme change across codegen outputs.

Possibly related PRs

Suggested reviewers

  • absolutejs

Poem

🐰
I hopped through templates at dawn’s first light,
Swapped Pools for SQL with nimble delight,
Sequences hum where rowids once played,
Docker commands ready, containers arrayed,
A tiny rabbit cheer for the migration's flight!

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title clearly and concisely summarizes the main objective of the changeset: adding CockroachDB support across multiple generator modules.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/cockroachdb-support

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7aab873 and 6e9312f.

📒 Files selected for processing (1)
  • src/generators/db/dockerInitTemplates.ts (2 hunks)
🔇 Additional comments (2)
src/generators/db/dockerInitTemplates.ts (2)

55-60: LGTM! Sequence-based primary key is now idempotent.

The critical issue from the previous review has been resolved. The CREATE SEQUENCE IF NOT EXISTS clause ensures the initialization can be safely re-run, and the sequence-backed BIGINT primary key is a solid approach for CockroachDB.


114-115: LGTM! CLI and wait commands are now correct.

The major issue from the previous review has been addressed. The --database=database flag correctly targets the database in a single session, and the wait command appropriately performs a health check using CockroachDB's native cockroach sql command.


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.

Copy link
Copy Markdown

@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)
src/generators/db/dockerInitTemplates.ts (1)

114-114: Clarify the purpose of sleep 1 in the CLI command.

The sleep 1 prefix in the CockroachDB CLI command suggests a timing-related workaround. If this addresses a known race condition, consider adding a comment explaining why it's needed.

src/generators/db/generateDockerContainer.ts (1)

8-8: Pin to a specific patch version instead of using the moving latest-v25.3 tag.

Using latest-v25.3 prevents reproducible builds as it's a moving target. Pin to the latest stable patch version v25.3.5 (released November 14, 2025):

image: 'cockroachdb/cockroach:v25.3.5',
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 619969c and d348387.

📒 Files selected for processing (7)
  • src/generators/configurations/generateEnv.ts (1 hunks)
  • src/generators/configurations/generatePackageJson.ts (1 hunks)
  • src/generators/db/dockerInitTemplates.ts (2 hunks)
  • src/generators/db/generateDockerContainer.ts (9 hunks)
  • src/generators/db/handlerTemplates.ts (1 hunks)
  • src/generators/project/generateDBBlock.ts (1 hunks)
  • src/generators/project/generateImportsBlock.ts (1 hunks)
🔇 Additional comments (8)
src/generators/db/generateDockerContainer.ts (2)

11-11: Verify the command field implementation for empty strings.

The command field is emitted for all database templates, including those with empty strings. In Docker Compose, an empty command: directive may override the default container command, potentially breaking databases that rely on default startup behavior.

Consider either:

  1. Conditionally omitting the command field when it's empty
  2. Verifying that empty command strings don't affect other database containers

Apply this diff to conditionally emit the command:

 	const { image, port, env, volumePath, command } = templates[databaseEngine];
 	const envLines = Object.entries(env)
 		.map(([key, value]) => `            ${key}: ${value}`)
 		.join('\n');
+	const commandLine = command ? `        command: ${command}\n` : '';

 	return `services:
     db:
         image: ${image}
         restart: always
         environment:
 ${envLines}
         ports:
             - "${port}"
-        command: ${command}
+${commandLine}        volumes:
             - db_data:${volumePath}

6-6: No issues found — COCKROACH_DATABASE is the correct environment variable.

COCKROACH_DATABASE is a documented CockroachDB Docker environment variable that creates a database automatically at first startup when using the start-single-node command. The current implementation with COCKROACH_DATABASE: 'database' and the command start-single-node --insecure is correct. The variable name and value align with CockroachDB's official Docker configuration requirements and are consistent with the database initialization pattern used for other engines in this file (e.g., MONGO_INITDB_DATABASE, POSTGRES_DB, MYSQL_DATABASE).

src/generators/project/generateDBBlock.ts (1)

7-9: LGTM! CockroachDB correctly uses Bun SQL.

The switch from Pool to SQL-based connection for CockroachDB is appropriate and aligns with PostgreSQL's implementation, leveraging CockroachDB's PostgreSQL wire protocol compatibility.

src/generators/project/generateImportsBlock.ts (1)

148-154: LGTM! CockroachDB correctly included in no-ORM PostgreSQL path.

The extension of the import logic to include CockroachDB alongside PostgreSQL is appropriate, given their wire protocol compatibility. This ensures proper imports for both local (Bun SQL) and remote (Neon) configurations.

src/generators/configurations/generatePackageJson.ts (1)

183-199: LGTM! CockroachDB lifecycle scripts follow established patterns.

The script block correctly mirrors the PostgreSQL pattern with appropriate adjustments for CockroachDB's CLI tools and project naming.

src/generators/configurations/generateEnv.ts (1)

13-13: No issues found—CockroachDB configuration is consistent.

The DATABASE_URL and Docker environment are properly aligned:

  • Database name matches: both use 'database'
  • Connection string correctly uses root@localhost:26257/database with no password (appropriate for insecure mode)
  • Docker startup command includes --insecure, aligning with the passwordless root user connection
  • CockroachDB's default behavior in insecure mode allows root to connect without authentication
src/generators/db/dockerInitTemplates.ts (1)

55-60: No issues found; code is correct.

CockroachDB supports PostgreSQL-style CREATE SEQUENCE and the sequence functions nextval(), confirming the syntax is valid. The choice of BIGINT for the CockroachDB implementation is intentional and differs from other databases in the file (PostgreSQL uses INTEGER, MySQL/MariaDB/SingleStore use INT), which is appropriate for CockroachDB's distributed architecture. The sequence name count_history_uid_seq follows standard SQL naming conventions.

src/generators/db/handlerTemplates.ts (1)

317-321: Verify Bun SQL integration with CockroachDB at runtime.

The configuration correctly reuses postgresSqlQueryOperations for CockroachDB, which is sound because CockroachDB implements the PostgreSQL wire protocol. Bun's built-in SQL can connect to CockroachDB by using Bun's PostgreSQL adapter/connection string. However, expect possible SQL-dialect or feature differences since CockroachDB does not implement all Postgres extensions/behaviors, so test the queries, transactions, and any Postgres-specific features before deployment.

Comment thread src/generators/configurations/generatePackageJson.ts Outdated
Comment thread src/generators/db/dockerInitTemplates.ts Outdated
Copy link
Copy Markdown

@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 (1)
src/generators/db/dockerInitTemplates.ts (1)

55-60: Consider using IDENTITY columns instead of manual sequences.

CockroachDB supports GENERATED ALWAYS AS IDENTITY syntax (similar to PostgreSQL on line 8), which is cleaner, more maintainable, and automatically idempotent compared to manually creating sequences.

Apply this diff to align with PostgreSQL's approach:

-const cockroachdbCountHistory = `CREATE SEQUENCE count_history_uid_seq START WITH 1 INCREMENT BY 1;
-CREATE TABLE IF NOT EXISTS count_history (
-  uid         BIGINT PRIMARY KEY DEFAULT nextval('count_history_uid_seq'),
+const cockroachdbCountHistory = `CREATE TABLE IF NOT EXISTS count_history (
+  uid         BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
   count       INT      NOT NULL,
   created_at  TIMESTAMP NOT NULL DEFAULT NOW()
 );`;
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d348387 and 7aab873.

📒 Files selected for processing (2)
  • src/generators/configurations/generatePackageJson.ts (1 hunks)
  • src/generators/db/dockerInitTemplates.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/generators/configurations/generatePackageJson.ts
🔇 Additional comments (1)
src/generators/db/dockerInitTemplates.ts (1)

114-115: CockroachDB CLI syntax verified—no issues found.

The cockroach sql command supports both --database and --insecure flags. The implementation correctly uses these flags for local development without TLS, and the wait condition adequately tests server readiness with a select 1 check. The code properly addresses the previous review feedback about database session context.

Comment thread src/generators/db/dockerInitTemplates.ts Outdated
Copy link
Copy Markdown
Owner

@absolutejs absolutejs left a comment

Choose a reason for hiding this comment

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

Just fix the code rabbit suggestion

@bnziv bnziv merged commit 0152b58 into main Nov 22, 2025
1 check passed
@bnziv bnziv deleted the feat/cockroachdb-support branch November 23, 2025 08:45
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.

2 participants