mcpField
E
electric-orm

electric-orm

github.com/electric-sqlデータ・データベース10.4k48 回インストール3 週間前に更新
リポジトリ

electric-orm について

Electric と ORM を統合する開発者向けに、Drizzle ORM または Prisma による書き込みやマイグレーションの要点を説明するスキルです。トランザクション内の txid、REPLICA IDENTITY、TanStack DB コレクションを扱います。

主な機能

  1. 01Drizzle ORM の統合
  2. 02Prisma の統合
  3. 03マイグレーションでの REPLICA IDENTITY 設定
  4. 04txid による書き込みの整合
  5. 05TanStack DB コレクションの設定

活用シーン

  1. 01ORM 経由の書き込みと Electric 同期の整合
  2. 02更新・削除のストリーミングに対応するマイグレーション
  3. 03ORM の書き込みと TanStack DB コレクションの接続

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/electric-sql/electric --skill electric-orm

インストール後、Claude Code で/electric-ormを入力して読み込まれたか確認します。

詳細

このスキルは、electric-shapes と electric-schema-shapes を基盤としています。まず、これらをお読みください。

Electric — ORM 統合

セットアップ

Drizzle ORM
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
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) }
  })
}

基本的なパターン

REPLICA IDENTITY を使用した Drizzle マイグレーション
// 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`)
}
REPLICA IDENTITY を使用した Prisma マイグレーション
-- 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;
ORM を使用した Collection の onInsert
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 }
    },
  })
)

よくある間違い

HIGH ORM の書き込み操作で txid を返さない

誤り:

// Drizzle — no txid returned
const [todo] = await db.insert(todos).values({ text: 'New' }).returning()
return { id: todo.id }

正しい例:

// 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) }
})

ORM はデフォルトでは pg_current_xact_id() を返しません。同じトランザクション内で txid を取得するための生 SQL クエリを追加してください。これを行わないと、同期されたバージョンが届く前に楽観的な状態が失われ、UI がちらつくことがあります。

出典:AGENTS.md:116-119

MEDIUM レプリカ ID を削除するマイグレーションの実行

誤り:

// 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

正しい例:

await db.execute(sql`DROP TABLE todos`)
await db.execute(sql`CREATE TABLE todos (...)`)
await db.execute(sql`ALTER TABLE todos REPLICA IDENTITY FULL`)

一部のマイグレーションツールは、テーブルのプロパティをリセットします。テーブルを再作成した後に、必ず REPLICA IDENTITY FULL が設定されていることを確認してください。設定されていない場合、Electric は更新と削除を正しくストリーミングできません。

出典:website/docs/guides/troubleshooting.md:373

関連項目:electric-new-feature/SKILL.md — txid ハンドシェイクを含む、書き込みパス全体の流れ。 関連項目:electric-schema-shapes/SKILL.md — スキーマ設計は、Shapes と ORM クエリの両方に影響します。

バージョン

@electric-sql/client v1.5.10 を対象としています。

コメント