このページは「plasma で X はできる?」を source を grep せずに docs
で発見できるようにする ためのものです。v1.0 で使える全ての機能を、
一度だけ、カテゴリ別に、対応する guide へのリンク付きで並べています。
| 機能 |
方法 |
| Table を宣言 |
table("name", { id: id(), ... }) — Schema |
| Table を schema にまとめる |
defineSchema({ users, todos, ... }) |
| Nullable column |
.nullable() |
| Default 値 |
.default(value) |
| Unique 制約 |
.unique() |
| At-rest 暗号化 |
.encrypted() — Encryption |
| 外部キー |
ref(() => users.id, { onDelete }) — cascade / restrict / setNull / noAction |
| 自動 UUID 主キー |
id() — 名前は id 固定、1 table に 1 つ |
| 文字列 column |
text() |
| 整数 column |
int(), bigint() |
| Boolean |
boolean() |
| インライン binary |
blob() (行内に格納する小サイズバイト) |
| JSON |
json() |
| Content-addressable file (R2) |
file({ maxSize?, mimeAllowList?, immutable?, upload? }) — Files |
| G-Counter (grow-only) |
crdtCounter() — CRDT |
| PN-Counter (signed) |
crdtPnCounter() |
| Last-writer-wins register |
crdtLwwRegister<T>() |
| Observed-remove set |
crdtOrSet<T>() |
| 行レベル auth (read/write) |
TableOptions.auth: { read, write } — Auth |
| カスタム conflict merge |
TableOptions.resolveConflict — Conflict resolution |
| ローカル専用 cache table |
TableOptions.changeLogSuppressed: true — Offline |
| Table 単位 storage adapter (schema 宣言) |
TableOptions.blobs: storageRef("name") — v1.0 note: sync handler は default のみ honour、他は起動時 throw |
read 側は drizzle 風です。上記の operator を組み合わせて
db.select().from(...).where(...).orderBy(...).limit(...).offset(...)
のように書けます。
| 機能 |
方法 |
| 比較 |
eq, ne, gt, gte, lt, lte |
| 論理 |
and, or, not |
| 集合 |
inArray |
| Null |
isNull, isNotNull |
| パターン |
like |
| ソート |
asc, desc |
| 集約 |
count, sum, avg, max, min |
| GROUP BY |
.groupBy(col) |
| HAVING |
.having(expr) |
| Inner join |
.innerJoin(table, on) |
| Left join |
.leftJoin(table, on) |
| Live 購読 |
.live() → LiveQuery<T> — Live queries |
| React バインディング |
useLiveQuery(factory, deps) |
Column projection (select({ x: todos.title })) にも対応、型は
projection 通りに流れます。
| 機能 |
方法 |
| Mutator を定義 |
defineMutators<S, Ctx>()({ name: async ({db, args, ctx}) => ... }) — Mutators |
| Args validation |
Standard Schema — Zod / Valibot / ArkType / Effect が動作 |
| 1 transaction で複数 table 書き込み |
1 つの mutator 内で複数 table に db.insert/update/delete |
| Mutation origin にアクセス |
destructure に clientID, mutationID |
| React バインディング |
useMutation<M, K>(name) → { mutate, isPending, error, reset } |
| サーバー専用の mutator 実行 |
invokeMutator(mutators, name, {db, ctx, args}) — cron 用 |
| クライアント 1 shot mutate |
client.mutate("name", args) — IDB へ即座に反映、outbox にキュー |
| キュー済み mutation を破棄 |
client.discardMutation(id) |
| 機能 |
方法 |
| Sync 開始 |
client.start() — poll / WS / upload worker を起動 |
| Sync 停止 |
client.stop() |
| Outbox drain 待機 |
await client.flush() |
| 手動 push |
client.pushOnce() |
| 手動 pull |
client.pullOnce() |
| Poll 間隔 |
PlasmaClientOptions.pollIntervalMs |
| Retry ポリシー |
PlasmaClientOptions.retry: { maxAttempts, initialDelayMs, maxDelayMs } |
| WebSocket 購読 |
subscribe: createWebSocketSubscription({ url }) |
| Offline モード |
PlasmaClientOptions.offline: true — Offline |
| Auth header 生成 |
authHeaders: async () => ({ authorization: ... }) |
| Custom fetch |
fetcher: async (input, init) => Response |
| Context provider |
getContext: async () => ({ ...ctx }) |
| Schema mismatch handler |
onSchemaMismatch: async ({ phase }) => "reset" | "stay" |
| Error hook |
onError: (err: SyncClientError) => void |
| ローカル state を wipe |
client.resetLocalState() — IDB 全消去 + clientID を rotate |
| 機能 |
方法 |
File / Blob から upload |
args に渡すだけ、outbox 前に desugar。Uint8Array / ArrayBuffer は 受け付けない (blob() column との衝突回避)、new Blob([bytes]) で包む |
FileRef から bytes を読む |
client.readFile(ref) または usePlasmaFile(ref) hook |
| Blob upload retry ポリシー |
blobUploadRetry: { maxAttempts, initialDelayMs, maxDelayMs } |
| 失敗した upload を retry |
client.retryBlobUpload(hash) |
| Orphan blob GC |
gcOrphanedBlobs({ executor, storage, minOrphanAgeMs, limit }) — scheduled から |
Raw driver writes 後の _plasma_blob_refs 再構築 |
reconcileBlobRefs({ schema, executor, dialect }) |
| Table 単位の storage adapter (server 側 blobs map) |
blobs: { default: r2Storage({ bucket }) } — v1.0 note: default のみ、storageRef("other") 使うと startup で throw |
| サーバー側 blob adapter |
blobs: { default: r2Storage({ bucket }) } on SyncHandlerOptions |
| Blob read auth の fan-out cap |
SyncHandlerOptions.readAuthMaxRefs (default 128) |
| 機能 |
方法 |
| Snapshot を購読 |
live.subscribe((rows) => ...) |
| Diff を購読 |
live.subscribeDelta?.((delta) => ...) — { added, removed, changed } |
| 初回配送を待つ |
await live.whenReady?.() |
| IVM 対応判定 |
classifyIvm(ast) → "select" | "aggregate" | "none" |
| サーバー側 live |
serverLiveSelect({ executor, fetch, onChange, tables?, pollIntervalMs? }) — サーバーサイド操作 |
Read helper (行の格納値に対して呼ぶ):
| Column |
Read |
Merge |
crdtCounter |
sumCrdtCounter(map) |
mergeCrdtCounter(a, b) |
crdtPnCounter |
pnRead(map) |
mergePnCounter(a, b) |
crdtLwwRegister<T> |
lwwRead(reg, fallback) |
mergeLwwRegister(a, b) |
crdtOrSet<T> |
orSetValues(set), orSetHas(set, v) |
mergeOrSet(a, b) |
Write helper (mutator 内で新しい格納値を組み立てる):
| Column |
Helper |
crdtCounter |
crdtIncrement(clientID, delta, current) |
crdtPnCounter |
pnIncrement(clientID, delta, current), pnDecrement(clientID, delta, current) |
crdtLwwRegister |
lwwSet(clientID, value, ts, current) |
crdtOrSet |
orSetAdd(clientID, seq, value, current), orSetRemove(value, current) |
| 機能 |
方法 |
| Column marker |
column に .encrypted() |
| At-rest ローカル暗号化 |
PlasmaClientOptions.encryption: { dek, keyId } |
| Mutator 内で手動暗号化 (E2EE) |
encryptField(dek, aad, value) / decryptField(dek, aad, envelope) |
| Envelope wire format |
Envelope — AES-GCM-256、keyId タグ、AAD は (table, rowId, column, keyId) |
| 受信時 envelope 検証 |
validateEnvelope(env, { maxCiphertextBytes, allowedKeyIds }) |
| PQ hybrid ラップ |
encryptFieldPq(provider, aad, value) / decryptFieldPq(provider, aad, env) |
| PQ envelope |
PqEnvelope, isPqEnvelope |
| KEM provider interface |
PqHybridProvider |
| Staging 用 insecure provider |
insecurePlaceholderProvider({ acceptInsecure: true }) — opt-in 無しなら throw |
| 機能 |
方法 |
| Handler を mount |
createSyncHandler({ schema, mutators, executor, schemaVersion, auth, ... }) — Deployment |
| Request auth |
auth: async (req) => ({ ok, clientGroupID, clientID, ctx }) |
| Blob storage をアタッチ |
blobs: { default: r2Storage({ bucket }) } |
| Blob read auth の fan-out 上限 |
readAuthMaxRefs: 128 |
| Handler 外で server-side db |
createServerDb({ schema, executor, ctx }) |
| Authorization policy |
AuthorizePolicy — ctx から read/write を bind |
| Mutator 内で auth error |
throw new PlasmaAuthorizationError(...) |
| サーバー error hook |
onError: (err: SyncServerError) => void |
| 機能 |
方法 |
| 初回 DDL (idempotent) |
ensureSchema({ schema, executor }) — 全 request で呼んで OK |
| Deploy 時 reconcile |
runMigrations({ schema, executor }) — Migrations |
| 破壊的変更を refuse |
MigrationRefused — drop / rename / kind 変更で throw |
| Diff を introspect |
返り値の SchemaDiff |
| Schema version bump |
共有 schema file の SCHEMA_VERSION 文字列 |
| Handshake の挙動 |
Mismatch で 409、client の onSchemaMismatch が "reset" or "stay" を選ぶ |
| 機能 |
方法 |
| WebSocket ファンアウト用 DO |
SyncCoordinator を Worker から export |
| WebSocket poke をトリガ |
pokeCoordinator(env.COORDINATOR, clientGroupID) (@sh1n4ps/plasma-server/coordinator) |
| クライアント側 WS transport |
createWebSocketSubscription({ url, protocols? }) |
| 機能 |
方法 |
Client の userInfo を broadcast |
createWebSocketSubscription({ userInfo, onPresence }) — Presence |
| Presence の変化を受信 |
onPresence: (entries) => ... — 毎回 full snapshot |
| Presence entry の shape |
{ clientID, userInfo } — userInfo は任意の JSON |
| Room の scope |
デフォルトは clientGroupID、WebSocket URL の ?room= で override |
| 自分の userInfo を更新 |
新 payload で reconnect (カーソル系は throttle) |
| 機能 |
方法 |
| Region 別 monotonic id source |
SequencerDO |
| ID range を予約 |
stub.reserve(count) → { start, end } (bigint 安全な文字列) |
| DO の storage backend |
SequencerStorage interface, テスト用 MemorySequencerStorage |
| テスト時 simulator |
SequencerDoSimulator |
| サーバー側 version 予約 |
reserveRegionVersions({ executor, regionId, count }) |
_plasma_region_versions の DDL |
ensureRegionVersionsTable({ executor }) |
| Causal cookie codec |
encodeCookie, decodeCookie, mergeCookie, cookieCovers |
| Change batch から cookie 更新 |
advanceCookieFromChanges(cookie, rows) |
| Cookie から pull predicate |
pullPredicate(cookie) — SQL WHERE fragment |
| Region+version の pack/unpack |
packRegionVersion, unpackRegionVersion |
| 定数 |
REGION_VERSIONS_TABLE, CHANGES_TABLE |
| 機能 |
方法 |
| 中間 put / del ペアを圧縮 |
compactChangeLog(executor, safeUpToVersion) — scheduled worker |
| 結果統計 |
CompactionResult |
| 機能 |
方法 |
| Fake IDB でクライアント engine |
createIdbEngine({ schema, dbName }) + fake-indexeddb/auto — Testing |
| SQLite executor (テスト用) |
fromBetterSqlite3(sqlite) |
| Worker 側 テスト |
@cloudflare/vitest-pool-workers + Miniflare |
| 初回 live 配送を await |
await live.whenReady?.() |
| Sequencer テスト stub |
SequencerDoSimulator + MemorySequencerStorage |
| 隔離書き込み用 server-side db |
createServerDb({ schema, executor, ctx }) |
| 機能 |
方法 |
| ツリーを wrap |
<PlasmaProvider client={plasma}> |
| 現在の client を取得 |
usePlasma() |
| Live query |
useLiveQuery(factory, deps) |
| State 付き mutation |
useMutation<M, K>(name) → { mutate, isPending, error, reset } |
| File 解決 + Blob URL |
usePlasmaFile(ref) → FileHandle (pending / local / uploading / ready / missing / error) |
| 機能 |
方法 |
| ページ内パネル |
<PlasmaDevtools client={plasma} dbName="..." schema={schema} /> |
| Snapshot hook |
useDevtoolsSnapshot(client, options) |
| postMessage bridge |
attachDevtoolsBridge(client, { dbName, schema, targetOrigin, allowedOrigins, ... }) |
| Message discriminant |
PLASMA_DEVTOOLS_SOURCE = "plasma-devtools" |
| Type guard |
isDevtoolsMessage(evt.data) |
| Command 種類 |
flush, pull, reset-local-state, ping |
| 機能 |
方法 |
| Cloudflare D1 |
fromD1(env.DB) |
| better-sqlite3 (Node) |
fromBetterSqlite3(sqlite) |
| SQLite dialect |
sqliteDialect |
| Postgres dialect |
postgresDialect |
| SQL executor interface |
SqlExecutor — 独自 driver を持ち込み可 |
| SQL dialect interface |
SqlDialect — 独自 dialect を持ち込み可 |
| R2 storage adapter |
r2Storage({ bucket }) |
| Storage interface |
Storage — 独自 backend を持ち込み可 |
- Nested-relational query sugar (
db.query.x.findMany({ with }))
db.increment(col, delta) の高レベル CRDT counter API
- Args 境界の envelope walker (
.encrypted() E2EE で mutator に
encryptField() を書かなくてよくなる)
- Runtime
client.setOffline(bool) toggle
- Per-table blob storage adapter (今は宣言可だが runtime で refuse)
- Region 別 pull predicate の完全配線 (v1.0 handler は
hi = max(cursors) に単純化、heterogeneous multi-region で
drop window あり)
トラッキングは Roadmap を参照。