sqlite-schema-design
Qué hace
Esta guía cubre el diseño de tablas para SQLite Sync, un sistema que mantiene sincronizadas las bases de datos SQLite entre dispositivos. Está pensada para desarrolladores de apps sincronizadas que necesitan las reglas de sincronización, no consejos generales de bases de datos.
Cuándo usarla
- ✓Cuando añades una nueva tabla que debe sincronizarse entre dispositivos.
- ✓Cuando cambias una columna de una tabla que ya se sincroniza.
- ✓Cuando planificas una migración de base de datos que debe funcionar con SQLite Sync.
Link de la skill
https://github.com/fastrepl/anarlog/blob/main/.agents/skills/sqlite-schema-design/SKILL.mdCópialo y pégalo en tu IA (Claude, ChatGPT o Cursor) pidiéndole que siga las instrucciones.
Cómo usar
La forma más fácil: copia el mensaje y pégalo en tu IA. Ella lee la skill y sigue las instrucciones.
Mensaje listo para pegar
Para Claude Code, Codex o Cursor: ejecútalo en la carpeta del proyecto y la skill queda instalada.
Descarga el SKILL.md y ponlo en la carpeta de skills de tu agente.
Ejemplo de qué pedirle a la IA
“Diseña una tabla de notas que se sincronice entre los dispositivos de mis usuarios con SQLite Sync.”
5 skills nuevas por semana. 1 minuto de lectura.
Cómo funciona
La habilidad comprueba primero si una tabla debe sincronizarse y después aplica las reglas de sincronización. Entre ellas están una clave primaria de texto estable creada con la utilidad UUID de sincronización, nada de ids enteros autoincrementales y los cambios de esquema hechos mediante los pasos de alteración de la sincronización. Las bases de datos locales y las de la nube deben mantener el mismo esquema.
Contenido técnico (SKILL.md original)
Texto original del autor, en inglés, directo de GitHub.
Goal
Design tables that behave correctly under SQLite Sync's CRDT replication model.
This skill is specifically for CloudSync-backed schemas:
- tables are initialized through
cloudsync_init(...) - sync is enabled with
cloudsync_enable(...) - identifiers should be generated with
cloudsync_uuid() - schema changes must go through
cloudsync_begin_alter(...)andcloudsync_commit_alter(...) - local and cloud databases must keep the same schema
Do not treat this as ordinary SQLite schema design. SQLite Sync imposes extra rules around keys, defaults, foreign keys, and schema evolution.
Workflow
1. Decide Whether The Table Is Synced
Before proposing DDL, classify the table:
- synced application data: must satisfy SQLite Sync constraints
- local-only cache or ephemeral state: should usually stay out of CloudSync
Only apply this skill to synced tables or to tables that may become synced soon.
2. Require A Stable, Globally Unique Primary Key
For synced tables:
- always declare an explicit primary key
- prefer
TEXT PRIMARY KEY NOT NULL - generate ids with
cloudsync_uuid() - do not use auto-incrementing integer ids
SQLite Sync docs explicitly recommend UUIDv7-style globally unique ids for CRDT workloads. Integer autoincrement ids are a bad fit because multiple devices can create rows independently.
CREATE TABLE document (
id TEXT PRIMARY KEY NOT NULL DEFAULT (cloudsync_uuid()),
workspace_id TEXT NOT NULL,
title TEXT NOT NULL DEFAULT '',
body TEXT NOT NULL DEFAULT '',
archived INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL DEFAULT (unixepoch()),
updated_at INTEGER NOT NULL DEFAULT (unixepoch())
) STRICT;
If the environment cannot use a function call in DEFAULT, generate the id in application code, but still use cloudsync_uuid() as the canonical id strategy.
3. Make Inserts Merge-Safe With Real Defaults
SQLite Sync best practices call out a non-obvious CRDT constraint: merges can happen column-by-column, so missing values are much more dangerous than in a single-node SQLite app.
For synced tables:
- every non-primary-key
NOT NULLcolumn should have a meaningfulDEFAULT - avoid required columns that only application code knows how to populate
- prefer simple scalar defaults over nullable columns when the field is logically always present
Good:
title TEXT NOT NULL DEFAULT ''
archived INTEGER NOT NULL DEFAULT 0
sort_order INTEGER NOT NULL DEFAULT 0
Bad:
title TEXT NOT NULL
archived INTEGER NOT NULL
without defaults on a synced table.
4. Keep The Local And Cloud Schemas Identical
The getting-started docs require the local synced database and the SQLite Cloud database to share the same schema.
When designing or reviewing a schema:
- treat local and remote DDL as one contract
- do not introduce "client-only" columns on synced tables
- do not rely on drift being harmless
- ensure migrations are applied consistently before sync resumes
If a field is only needed locally, it likely belongs in a separate non-synced table.
5. Be Conservative With Foreign Keys
SQLite Sync best practices explicitly warn that foreign keys can interact poorly with CRDT replication.
Use foreign keys on synced tables only when the integrity guarantee is worth the operational cost.
If you keep them:
- make child foreign key columns nullable when the relationship is optional
- if a foreign key column has a
DEFAULT, that default must beNULLor reference an actually valid parent row - avoid fake sentinel ids such as
'root'unless that parent row is guaranteed to exist everywhere - index the child foreign key columns
Prefer ownership patterns that tolerate out-of-order arrival between related rows.
6. Avoid Triggers And Implicit Write Logic On Synced Tables
SQLite Sync best practices advise minimizing triggers because they make replicated writes harder to reason about.
For synced tables:
- avoid triggers that mutate synced columns
- avoid hidden side effects on insert or update
- prefer explicit application writes
- keep derived or bookkeeping writes in non-synced tables if possible
If a trigger is unavoidable, review it as part of the replication design, not as a local SQLite convenience.
7. Scope Uniqueness For RLS And Multi-Tenant Sync
The introduction docs emphasize row-level security and multi-tenant access patterns.
That changes uniqueness design:
- if the real rule is "unique per workspace/user/team", enc
Preguntas frecuentes
¿Por qué no usar ids autoincrementales?
Varios dispositivos pueden crear filas al mismo tiempo, así que los contadores enteros chocarían. La guía pide ids globalmente únicos.
¿Se aplica a todas las tablas?
No. Solo las tablas sincronizadas necesitan estas reglas, y las tablas de caché solo locales normalmente quedan fuera de la sincronización.
¿Cómo cambio una tabla sincronizada?
Los cambios pasan por los pasos de alteración de inicio y confirmación, así que el esquema se mantiene igual en todas partes.
Detalles
Descripción original del autor
Design or review schemas for `crates/cloudsync` using SQLite Sync constraints, not generic SQLite advice. Use when adding synced tables, changing synced columns, or planning CloudSync-safe migrations.
repo: fastrepl/anarlog
Popularidad
- Estrellas en GitHub
- 9,7 mil
- Posición en el ranking
- #12214
- Licencia
- MIT
- Actualizada
- 1/11/2026
Comentarios
- …
Más skills de este repositorio
no-use-effect
9,7 milEnseña a tu agente a evitar useEffect en el código de React y a usar patrones más sencillos, como valores derivados, hooks de consulta y manejadores de eventos.
anarlog
9,7 milAyuda a tu agente a buscar en tus notas de reuniones de Anarlog, sus resúmenes, transcripciones, participantes y tareas pendientes, o a importar una grabación local.
Skills parecidas
discrawl
394 milPermite que tu agente busque y resuma un archivo local guardado de mensajes de Discord, revise qué tan actual es y lea mensajes directos.
clickhouse-io
280 milAyuda a tu agente a optimizar consultas y esquemas en ClickHouse con buenas prácticas para cargas analíticas de alto rendimiento. Úsalo si las consultas son muy lentas.
scientific-db-pubmed-database
280 milAyuda a tu agente a buscar artículos científicos del ámbito biomédico. Es útil para investigaciones que necesitan información médica específica.