Claude Code for CockroachDB: Distributed SQL at Global Scale — Claude Skills 360 Blog
Blog / AI / Claude Code for CockroachDB: Distributed SQL at Global Scale
AI

Claude Code for CockroachDB: Distributed SQL at Global Scale

Published: July 29, 2027
Read time: 5 min read
By: Claude Skills 360

CockroachDB is a distributed SQL database with PostgreSQL wire compatibility — DATABASE_URL=postgresql://user:password@host:26257/mydb?sslmode=verify-full connects via the standard Postgres protocol. Prisma: provider = "cockroachdb" in schema.prisma — all standard Prisma models work. Node.js: new Pool({ connectionString: process.env.DATABASE_URL, ssl: { rejectUnauthorized: true } }) using pg. Multi-region: ALTER TABLE orders SET LOCALITY REGIONAL BY ROW partitions rows by the crdb_region column — queries from us-east-1 read from the nearest replica automatically. ALTER TABLE config SET LOCALITY GLOBAL replicates a table to every region with serializable reads. ALTER TABLE sessions SET LOCALITY REGIONAL BY TABLE IN PRIMARY REGION pins the whole table to one region. UPSERT INTO users (id, email) VALUES ($1, $2) handles insert-or-update atomically. INSERT INTO items VALUES (...) ON CONFLICT (id) DO UPDATE SET ... is the standard SQL equivalent. Changefeeds: CREATE CHANGEFEED FOR TABLE orders INTO 'kafka://...' WITH updated,resolved streams CDC events. Serverless: CockroachDB Serverless auto-scales to zero with per-RU billing. SHOW JOBS monitors schema change jobs (DDL is async in CRDB). Claude Code generates CockroachDB Prisma schemas, multi-region configurations, and Node.js connection pools.

CLAUDE.md for CockroachDB

## CockroachDB Stack
- Prisma provider: cockroachdb (use instead of postgresql — required for CRDB-specific types)
- Connection: DATABASE_URL=postgresql://user:pass@HOST:26257/DBNAME?sslmode=verify-full
- SSL: always needed for Serverless — ssl: { rejectUnauthorized: true } in pg Pool
- UPSERT: supported natively — UPSERT INTO table (id, col) VALUES ($1, $2)
- Serial/sequences: use gen_random_uuid() for UUIDs or @default(sequence()) for int IDs
- Prisma IDs: @default(cuid()) or @default(uuid()) — avoid autoincrement() (prefer UUID for distribution)
- DDL async: schema changes run as jobs — SHOW JOBS to check progress
- Multi-region: requires Dedicated/Serverless multi-region plan

Prisma Schema for CockroachDB

// prisma/schema.prisma — CockroachDB Prisma configuration
generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "cockroachdb"
  url      = env("DATABASE_URL")
}

model User {
  id        String   @id @default(cuid())
  email     String   @unique
  name      String?
  plan      String   @default("free")
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  orders    Order[]
}

model Order {
  id         String      @id @default(cuid())
  userId     String
  user       User        @relation(fields: [userId], references: [id])
  status     OrderStatus @default(PENDING)
  amount     Decimal     @db.Decimal(10, 2)
  currency   String      @default("USD")
  createdAt  DateTime    @default(now())
  updatedAt  DateTime    @updatedAt

  @@index([userId])
  @@index([status])
}

enum OrderStatus {
  PENDING
  PROCESSING
  COMPLETED
  CANCELLED
}

model Product {
  id          String   @id @default(cuid())
  sku         String   @unique
  name        String
  description String?
  price       Decimal  @db.Decimal(10, 2)
  stock       Int      @default(0)
  createdAt   DateTime @default(now())

  @@index([sku])
}

Database Client

// lib/db/cockroach.ts — CockroachDB with pg and Prisma
import { Pool, type PoolConfig } from "pg"
import { PrismaClient } from "@prisma/client"

// Raw pg Pool for transactions or bulk operations
const poolConfig: PoolConfig = {
  connectionString: process.env.DATABASE_URL!,
  ssl: { rejectUnauthorized: true },
  max: 10,
  idleTimeoutMillis: 30_000,
  connectionTimeoutMillis: 5_000,
}

export const pool = new Pool(poolConfig)

// Prisma client (singleton)
const globalForPrisma = globalThis as unknown as { prisma?: PrismaClient }

export const db =
  globalForPrisma.prisma ??
  new PrismaClient({
    log: process.env.NODE_ENV === "development" ? ["query"] : ["error"],
  })

if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = db

// ── CRDB-specific helpers ──────────────────────────────────────────────────

/** UPSERT — faster than INSERT + ON CONFLICT for known-conflict scenarios */
export async function upsertUser(
  id: string,
  email: string,
  name: string,
): Promise<void> {
  await pool.query(
    `UPSERT INTO "User" (id, email, name, "createdAt", "updatedAt")
     VALUES ($1, $2, $3, now(), now())`,
    [id, email, name],
  )
}

/** Bulk upsert with COPY-like INSERT */
export async function bulkUpsertProducts(
  products: Array<{ id: string; sku: string; name: string; price: number }>,
): Promise<void> {
  if (products.length === 0) return

  const values = products.flatMap((p) => [p.id, p.sku, p.name, p.price])
  const placeholders = products
    .map((_, i) => `($${i * 4 + 1}, $${i * 4 + 2}, $${i * 4 + 3}, $${i * 4 + 4}, now())`)
    .join(", ")

  await pool.query(
    `INSERT INTO "Product" (id, sku, name, price, "createdAt")
     VALUES ${placeholders}
     ON CONFLICT (sku) DO UPDATE SET
       name  = EXCLUDED.name,
       price = EXCLUDED.price`,
    values,
  )
}

/** Transaction with retry logic (CRDB recommends retrying serialization errors) */
export async function withRetry<T>(
  fn: () => Promise<T>,
  maxRetries = 3,
): Promise<T> {
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    try {
      return await fn()
    } catch (err: any) {
      // CRDB serialization error: code 40001
      if (err?.code === "40001" && attempt < maxRetries) {
        await new Promise((r) => setTimeout(r, 2 ** attempt * 50))
        continue
      }
      throw err
    }
  }
  throw new Error("Max retries exceeded")
}

export async function trasnsact<T>(
  fn: (client: import("pg").PoolClient) => Promise<T>,
): Promise<T> {
  const client = await pool.connect()
  try {
    await client.query("BEGIN")
    const result = await fn(client)
    await client.query("COMMIT")
    return result
  } catch (err) {
    await client.query("ROLLBACK")
    throw err
  } finally {
    client.release()
  }
}

Multi-Region Setup SQL

-- Multi-region CockroachDB setup (Dedicated / Multi-Region Serverless)
-- 1. Add regions to the database
ALTER DATABASE mydb PRIMARY REGION "us-east1";
ALTER DATABASE mydb ADD REGION "eu-west1";
ALTER DATABASE mydb ADD REGION "ap-southeast1";

-- 2. Pin global reference data to all regions (low-latency reads everywhere)
ALTER TABLE "Product" SET LOCALITY GLOBAL;

-- 3. Partition user-rooted data by region (rows live near their users)
ALTER TABLE "User"  SET LOCALITY REGIONAL BY ROW;
ALTER TABLE "Order" SET LOCALITY REGIONAL BY ROW;

-- The crdb_region column is added automatically
-- INSERT INTO "User" (id, email, crdb_region) VALUES (..., 'us-east1')

Next.js API Route

// app/api/orders/route.ts — create order with CockroachDB transaction
import { NextResponse } from "next/server"
import { z } from "zod"
import { db, withRetry } from "@/lib/db/cockroach"
import { auth } from "@/lib/auth"

const OrderSchema = z.object({
  items: z.array(z.object({ productId: z.string(), quantity: z.number().int().positive() })),
})

export async function POST(req: Request) {
  const session = await auth()
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })

  const { items } = OrderSchema.parse(await req.json())

  const order = await withRetry(async () => {
    return db.$transaction(async (tx) => {
      // Calculate total
      const products = await tx.product.findMany({
        where: { id: { in: items.map((i) => i.productId) } },
        select: { id: true, price: true, stock: true },
      })

      const total = items.reduce((sum, item) => {
        const product = products.find((p) => p.id === item.productId)
        if (!product) throw new Error(`Product ${item.productId} not found`)
        if (product.stock < item.quantity) throw new Error(`Insufficient stock for ${item.productId}`)
        return sum + Number(product.price) * item.quantity
      }, 0)

      // Create order
      const newOrder = await tx.order.create({
        data: { userId: session.user.id, amount: total, status: "PENDING" },
      })

      return newOrder
    })
  })

  return NextResponse.json(order, { status: 201 })
}

For the Neon alternative when needing a PostgreSQL-compatible serverless database that scales to zero, has branching for preview environments, and connect via the standard pg or Prisma PostgreSQL provider without any CRDB-specific schema changes — Neon is a serverless PostgreSQL-as-a-service while CockroachDB is the better choice for truly distributed multi-region workloads that need geographic data partitioning, see the Neon guide. For the PlanetScale alternative when needing a serverless MySQL-compatible database with schema branching, deploy requests as a database migration workflow, and Vitess-based horizontal sharding — PlanetScale uses MySQL wire protocol while CockroachDB uses PostgreSQL wire protocol with stronger ACID guarantees and native multi-region support, see the PlanetScale guide. The Claude Skills 360 bundle includes CockroachDB skill sets covering Prisma setup, UPSERT patterns, and multi-region configuration. Start with the free tier to try distributed SQL generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free