electric-orm
Use Electric with Drizzle ORM or Prisma for the write path. Covers getting pg_current_xact_id() from ORM transactions using Drizzle tx.execute(sql) and Prisma $queryRaw, running migrations that preserve REPLICA IDENTITY FULL, and schema management patterns compatible with Electric shapes. Load when using Drizzle or Prisma alongside Electric for writes.
Best use case
electric-orm is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Use Electric with Drizzle ORM or Prisma for the write path. Covers getting pg_current_xact_id() from ORM transactions using Drizzle tx.execute(sql) and Prisma $queryRaw, running migrations that preserve REPLICA IDENTITY FULL, and schema management patterns compatible with Electric shapes. Load when using Drizzle or Prisma alongside Electric for writes.
Teams using electric-orm should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/electric-orm/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How electric-orm Compares
| Feature / Agent | electric-orm | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Use Electric with Drizzle ORM or Prisma for the write path. Covers getting pg_current_xact_id() from ORM transactions using Drizzle tx.execute(sql) and Prisma $queryRaw, running migrations that preserve REPLICA IDENTITY FULL, and schema management patterns compatible with Electric shapes. Load when using Drizzle or Prisma alongside Electric for writes.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
SKILL.md Source
This skill builds on electric-shapes and electric-schema-shapes. Read those first.
# Electric — ORM Integration
## Setup
### Drizzle ORM
```ts
import { drizzle } from 'drizzle-orm/node-postgres'
import { sql } from 'drizzle-orm'
import { todos } from './schema'
const db = drizzle(pool)
// Write with txid for Electric reconciliation
async function createTodo(text: string, userId: string) {
return await db.transaction(async (tx) => {
const [row] = await tx
.insert(todos)
.values({
id: crypto.randomUUID(),
text,
userId,
})
.returning()
const [{ txid }] = await tx.execute<{ txid: string }>(
sql`SELECT pg_current_xact_id()::xid::text AS txid`
)
return { id: row.id, txid: parseInt(txid) }
})
}
```
### Prisma
```ts
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
async function createTodo(text: string, userId: string) {
return await prisma.$transaction(async (tx) => {
const todo = await tx.todo.create({
data: { id: crypto.randomUUID(), text, userId },
})
const [{ txid }] = await tx.$queryRaw<[{ txid: string }]>`
SELECT pg_current_xact_id()::xid::text AS txid
`
return { id: todo.id, txid: parseInt(txid) }
})
}
```
## Core Patterns
### Drizzle migration with REPLICA IDENTITY
```ts
// In migration file
import { sql } from 'drizzle-orm'
export async function up(db) {
await db.execute(sql`
CREATE TABLE todos (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
text TEXT NOT NULL,
completed BOOLEAN DEFAULT false
)
`)
await db.execute(sql`ALTER TABLE todos REPLICA IDENTITY FULL`)
}
```
### Prisma migration with REPLICA IDENTITY
```sql
-- prisma/migrations/001_init/migration.sql
CREATE TABLE "todos" (
"id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
"text" TEXT NOT NULL,
"completed" BOOLEAN DEFAULT false
);
ALTER TABLE "todos" REPLICA IDENTITY FULL;
```
### Collection onInsert with ORM
```ts
import { createCollection } from '@tanstack/react-db'
import { electricCollectionOptions } from '@tanstack/electric-db-collection'
export const todoCollection = createCollection(
electricCollectionOptions({
id: 'todos',
schema: todoSchema,
getKey: (row) => row.id,
shapeOptions: { url: '/api/todos' },
onInsert: async ({ transaction }) => {
const newTodo = transaction.mutations[0].modified
const { txid } = await createTodo(newTodo.text, newTodo.userId)
return { txid }
},
})
)
```
## Common Mistakes
### HIGH Not returning txid from ORM write operations
Wrong:
```ts
// Drizzle — no txid returned
const [todo] = await db.insert(todos).values({ text: 'New' }).returning()
return { id: todo.id }
```
Correct:
```ts
// Drizzle — txid in same transaction
const result = await db.transaction(async (tx) => {
const [row] = await tx.insert(todos).values({ text: 'New' }).returning()
const [{ txid }] = await tx.execute<{ txid: string }>(
sql`SELECT pg_current_xact_id()::xid::text AS txid`
)
return { id: row.id, txid: parseInt(txid) }
})
```
ORMs do not return `pg_current_xact_id()` by default. Add a raw SQL query for txid within the same transaction. Without it, optimistic state may drop before the synced version arrives, causing UI flicker.
Source: `AGENTS.md:116-119`
### MEDIUM Running migrations that drop replica identity
Wrong:
```ts
// ORM migration recreates table without REPLICA IDENTITY
await db.execute(sql`DROP TABLE todos`)
await db.execute(sql`CREATE TABLE todos (...)`)
// Missing: ALTER TABLE todos REPLICA IDENTITY FULL
```
Correct:
```ts
await db.execute(sql`DROP TABLE todos`)
await db.execute(sql`CREATE TABLE todos (...)`)
await db.execute(sql`ALTER TABLE todos REPLICA IDENTITY FULL`)
```
Some migration tools reset table properties. Always ensure `REPLICA IDENTITY FULL` is set after table recreation. Without it, Electric cannot stream updates and deletes correctly.
Source: `website/docs/guides/troubleshooting.md:373`
See also: electric-new-feature/SKILL.md — Full write-path journey including txid handshake.
See also: electric-schema-shapes/SKILL.md — Schema design affects both shapes and ORM queries.
## Version
Targets @electric-sql/client v1.5.10.Related Skills
electric-yjs
Set up ElectricProvider for real-time collaborative editing with Yjs via Electric shapes. Covers ElectricProvider configuration, document updates shape with BYTEA parser (parseToDecoder), awareness shape at offset='now', LocalStorageResumeStateProvider for reconnection with stableStateVector diff, debounceMs for batching writes, sendUrl PUT endpoint, required Postgres schema (ydoc_update and ydoc_awareness tables), CORS header exposure, and sendErrorRetryHandler. Load when implementing collaborative editing with Yjs and Electric.
electric-shapes
Configure ShapeStream and Shape to sync a Postgres table to the client. Covers ShapeStreamOptions (url, table, where, columns, replica, offset, handle), custom type parsers (timestamptz, jsonb, int8), column mappers (snakeCamelMapper, createColumnMapper), onError retry semantics, backoff options, log modes (full, changes_only), requestSnapshot, fetchSnapshot, subscribe/unsubscribe, and Shape materialized view. Load when setting up sync, configuring shapes, parsing types, or handling sync errors.
electric-schema-shapes
Design Postgres schema and Electric shape definitions together for a new feature. Covers single-table shape constraint, cross-table joins using multiple shapes, WHERE clause design for tenant isolation, column selection for bandwidth optimization, replica mode choice (default vs full for old_value), enum casting in WHERE clauses, and txid handshake setup with pg_current_xact_id() for optimistic writes. Load when designing database tables for use with Electric shapes.
electric-proxy-auth
Set up a server-side proxy to forward Electric shape requests securely. Covers ELECTRIC_PROTOCOL_QUERY_PARAMS forwarding, server-side shape definition (table, where, params), content-encoding/content-length header cleanup, CORS configuration for electric-offset/electric-handle/ electric-schema/electric-cursor headers, auth token injection, ELECTRIC_SECRET/SOURCE_SECRET server-side only, tenant isolation via WHERE positional params, onError 401 token refresh, and subset security (AND semantics). Load when creating proxy routes, adding auth, or configuring CORS for Electric.
electric-postgres-security
Pre-deploy security checklist for Postgres with Electric. Checks REPLICATION role, SELECT grants, CREATE on database, table ownership, REPLICA IDENTITY FULL on all synced tables, publication management (auto vs manual with ELECTRIC_MANUAL_TABLE_PUBLISHING), connection pooler exclusion for DATABASE_URL (use direct connection), and ELECTRIC_POOLED_DATABASE_URL for pooled queries. Load before deploying Electric to production or when diagnosing Postgres permission errors.
electric-new-feature
End-to-end guide for adding a new synced feature with Electric and TanStack DB. Covers the full journey: design Postgres schema, set REPLICA IDENTITY FULL, define shape, create proxy route, set up TanStack DB collection with electricCollectionOptions, implement optimistic mutations with txid handshake (pg_current_xact_id, awaitTxId), and build live queries with useLiveQuery. Also covers migration from old ElectricSQL (electrify/db pattern does not exist), current API patterns (table as query param not path, handle not shape_id). Load when building a new feature from scratch.
electric-deployment
Deploy Electric via Docker, Docker Compose, or Electric Cloud. Covers DATABASE_URL (direct connection, not pooler), ELECTRIC_SECRET (required since v1.x), ELECTRIC_INSECURE for dev, wal_level=logical, max_replication_slots, ELECTRIC_STORAGE_DIR persistence, ELECTRIC_POOLED_DATABASE_URL for pooled queries, IPv6 with ELECTRIC_DATABASE_USE_IPV6, Kubernetes readiness probes (200 vs 202), replication slot cleanup, and Postgres v14+ requirements. Load when deploying Electric or configuring Postgres for logical replication.
electric-debugging
Troubleshoot Electric sync issues. Covers fast-loop detection from CDN/proxy cache key misconfiguration, stale cache diagnosis (StaleCacheError), MissingHeadersError from CORS misconfiguration, 409 shape expired handling, SSE proxy buffering (nginx proxy_buffering off, Caddy flush_interval -1), HTTP/1.1 6-connection limit in local dev (Caddy HTTP/2 proxy), WAL growth from replication slots (max_slot_wal_keep_size), Vercel CDN cache issues, and onError/backoff behavior. Load when shapes are not receiving updates, sync is slow, or errors appear in the console.
ElectricSQL
## Overview
Electric SQL — Sync Engine for Postgres
You are an expert in Electric SQL, the sync engine that streams Postgres data to local apps in real-time. You help developers build local-first applications where data syncs from Postgres to client-side SQLite/PGlite automatically — enabling instant reads, offline support, and real-time multi-user collaboration using Postgres as the single source of truth with Shape-based partial replication.
Daily Logs
Record the user's daily activities, progress, decisions, and learnings in a structured, chronological format.
Socratic Method: The Dialectic Engine
This skill transforms Claude into a Socratic agent — a cognitive partner who guides