[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6C57QBHJQM3P52W7JC12BG5":3,"skill-same:01M6C57QBHJQM3P52W7JC12BG5":167},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":28,"publishedAt":49,"linkOnly":50,"markdownContent":51,"markdownBody":52,"frontMatter":53,"refName":54,"commitSha":55,"skillDirectory":56,"forksCount":14,"repositoryHtmlUrl":57,"repositoryHomepageUrl":58,"ownerHtmlUrl":59,"ownerBlogUrl":60,"ownerDescription":61,"updatedAt":62,"install":63,"resources":76},"01M6C57QBHJQM3P52W7JC12BG5","data-modeling",null,"Designs CRDT-safe Ditto documents, covering merge behavior, maps vs arrays, SET and ON ID CONFLICT upserts that merge, DQL_STRICT_MODE and REGISTER, MAP, or COUNTER declarations, relationships and JOIN, counters, document IDs, document size, and timestamps. Use when designing or reviewing a Ditto schema or collection, or when Ditto documents need arrays edited on several devices, counters or totals, document IDs, or timestamps.","ditto-examples\u002Fditto-cookbook","ditto-examples","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F192611150?v=4","01M6C57F0Y1W6S5D9RD8GHE3YB","Ditto Examples","01M6C57F52Z11DDMBC0ZJ7FJPG",0,"MIT","https:\u002F\u002Fgithub.com\u002Fditto-examples\u002Fditto-cookbook\u002Fblob\u002Fmain\u002Fplugins\u002Fditto\u002Fskills\u002Fdata-modeling\u002FSKILL.md",[18,23],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000002","文档处理","SCENARIO","使用场景",{"categoryNo":24,"categoryName":25,"taxonomyType":26,"taxonomyTypeDesc":27},"01JBSEEDCAT000000000000033","数据分析师","PROFESSION","适用职业",[29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48],"data","data modeling","modeling","safe","merge","timestamps","when","mode","maps","map","join","arrays","register","conflict","collection","documents","devices","editing","ids","SET","2026-11-10 10:12:30",false,"---\nname: data-modeling\ndescription: \"Designs CRDT-safe Ditto documents, covering merge behavior, maps vs arrays, SET and ON ID CONFLICT upserts that merge, DQL_STRICT_MODE and REGISTER, MAP, or COUNTER declarations, relationships and JOIN, counters, document IDs, document size, and timestamps. Use when designing or reviewing a Ditto schema or collection, or when Ditto documents need arrays edited on several devices, counters or totals, document IDs, or timestamps.\"\n---\n\n# Ditto Data Modeling\n\nHow to shape Ditto documents so concurrent offline edits merge correctly. Targets Ditto SDK 5.2.0 with the default `DQL_STRICT_MODE = false`; the rules are the same in every SDK.\n\n## Before You Apply\n\n- Identify the project's SDK and version: Flutter (`ditto_live` in `pubspec.yaml` \u002F `pubspec.lock`), JavaScript (`@dittolive\u002Fditto` in `package.json`), Kotlin (`com.ditto:ditto-kotlin` in Gradle files), or Swift (`DittoSwift` in `Package.swift`, `Package.resolved`, or the Xcode project). These rules target SDK 5.2.0; for devices that still run 5.1.0, also apply `§ Known Issues in SDK 5.1.0`. **Note (SDK 5.1.0 and 5.2.0)** and **Note (SDK 5.1.0)** mark easy-to-miss behavior seen on those releases, with the safe pattern; **(SDK 5.1+)** \u002F **(SDK 5.2+)** mark features introduced in that release.\n- For API calls, Grep the outline of that SDK's page, `${CLAUDE_SKILL_DIR}\u002F..\u002Fguide\u002Freference\u002Fbest-practices\u002Fplatforms\u002F\u003Csdk>.md` (`flutter`, `javascript`, `kotlin`, `swift`), with `^#{1,3} ` and read only the section you need, not the whole page; sections are named `\u003CTopic> in \u003CSDK>`. DQL examples: `examples\u002F*.sql` (every SDK); API examples: `examples\u002F\u003Csdk>\u002F`, with the same base names in every SDK.\n- `§ \u003CHeading>` cites the full guide: Grep the heading as a fixed string in `best-practices\u002F` and `knowledge\u002F` under `${CLAUDE_SKILL_DIR}\u002F..\u002Fguide\u002Freference\u002F`, then read that section.\n- Report each finding at the severity of its item in `§ Anti-Pattern Checklist` (the checklist decides; Grep a phrase of the item there). The labels below rank the rules, not each item in them.\n- **Is the app deployed?** Older app versions keep writing your documents. Mark each change to stored data, fixes included, as additive or breaking (`§ Breaking and additive changes`). In a deployed app, a field that replaces another needs `§ A field that replaces another`; only an unreleased app, or a demo sharing no database with a released app, changes in place.\n\n## Prevents\n\n- Lost edits in arrays changed on several devices (an array is one last-writer-wins register)\n- Keys that never go away because `SET obj = {...}` and `DO UPDATE` merge into maps\n- Values that seem to vanish when type declarations differ between statements\n- Lost increments from read-modify-write instead of `COUNTER`; derived totals that diverge\n- ID collisions from sequential or timestamp-only IDs; documents over the size limits\n- Zone-less timestamps that make DQL date functions return `MISSING`\n\n## Workflow\n\n```\nSchema Design Progress:\n- [ ] 1. For each field, decide the merge you need: REGISTER, MAP, COUNTER, or ATTACHMENT\n- [ ] 2. Replace arrays that several devices edit with maps keyed by a stable ID\n- [ ] 3. Keep DQL_STRICT_MODE = false; declare REGISTER only for objects that must never mix\n- [ ] 4. Embed by default; split into a collection only per the decision guide, then JOIN locally\n- [ ] 5. Remove stored derived values; keep snapshot values (price at time of sale)\n- [ ] 6. Use COUNTER (declared consistently) for tallies changed concurrently\n- [ ] 7. Generate collision-free IDs (UUID v4); keep display numbers separate from _id\n- [ ] 8. Keep documents well under 256 KiB; move unbounded data and binaries out\n- [ ] 9. Store timestamps in UTC with a zone designator\n```\n\n## Rules\n\n### 1. Model every field for its merge (CRITICAL)\n\nEvery value is stored as a CRDT. With the default settings the type is inferred:\n\n| You write | Stored as | Concurrent writes |\n|---|---|---|\n| Scalar (string, number, boolean, null) | `REGISTER` | Last writer wins (Hybrid Logical Clock); the loser is discarded silently |\n| Array | `REGISTER` | The **whole array** is one value; one version wins |\n| Object | `MAP` | Each key merges independently (add-wins); nested objects are nested maps |\n| `APPLY f INCREMENT BY n` \u002F `RESTART` | `COUNTER` | Increments from all devices are added together |\n| Attachment | `ATTACHMENT` | Last writer wins |\n\nLocal write semantics on an existing object `{\"a\": 1, \"b\": 2}`:\n\n| Statement | Result |\n|---|---|\n| `SET obj.a = 10` | `{\"a\": 10, \"b\": 2}` |\n| `SET obj = {'c': 3}` | `{\"a\": 1, \"b\": 2, \"c\": 3}`: assigning an object **merges** |\n| `SET obj = {}` | `{\"a\": 1, \"b\": 2}`: clears nothing |\n| `UNSET obj.b` | `{\"a\": 1}`: `UNSET` is the only way to remove a key |\n| `ON ID CONFLICT DO UPDATE` with `{\"obj\": {\"c\": 3}}` | `{\"a\": 1, \"b\": 2, \"c\": 3}`: upserts merge too |\n\n**✅ DO**:\n- Update individual fields (`UPDATE ... SET obj.field = :value`), only the ones the user changed.\n- Use `ON ID CONFLICT DO UPDATE_LOCAL_DIFF` for upserts and re-imports of data another system owns (it skips equal fields).\n- Remove keys with `UNSET`. To replace an object, run `UNSET` then `SET` in one transaction, or declare it `REGISTER` (Rule 3). Only `REGISTER` keeps concurrent edits from mixing: after `UNSET` and `SET` the field is still a map.\n\n**❌ DON'T**:\n- Assume `SET obj = {...}` or `DO UPDATE` removes keys you left out, or clear a map with `SET obj = {}` or a scalar (`SET obj = 5`).\n- Write back a stale in-memory copy with `DO UPDATE` or `DO UPDATE_LOCAL_DIFF` (it writes every field that differs locally, old values included): either overrides a concurrent change.\n\n`§ CRDT Types and Merge Behavior`, `§ Local Write Semantics You Must Know`, `§ Document Structure` · Example: [examples\u002Ffield-level-updates.sql](examples\u002Ffield-level-updates.sql) · More: [reference\u002Fcommon-patterns.md](reference\u002Fcommon-patterns.md) (conflict policies, replacing an object, `UNSET` metadata)\n\n### 2. Use maps keyed by ID, not arrays, for data several devices edit (CRITICAL)\n\n| Use a **map keyed by ID** when | Use an **array** when |\n|---|---|\n| Several devices may add, edit, or remove items | Only one device writes; others read |\n| Items have a natural or synthetic unique ID | Order matters and the list is never edited concurrently |\n| You update or index individual items | It is a list of scalars replaced wholesale |\n\n```json\n\u002F\u002F ❌ BAD: concurrent edits to different items: one device's change is lost\n{ \"_id\": \"order-1\", \"items\": [ { \"productId\": \"p1\", \"quantity\": 2 } ] }\n\u002F\u002F ✅ GOOD: entries merge independently; display order is a field\n{ \"_id\": \"order-1\", \"items\": { \"\u003Citem uuid>\": { \"productId\": \"p1\", \"quantity\": 2, \"position\": 0 } } }\n```\n\n**✅ DO**:\n- Pass a variable key as data: `INSERT INTO orders DOCUMENTS (:patch) ON ID CONFLICT DO UPDATE_LOCAL_DIFF` with `patch = {'_id': orderId, 'items': {itemId: item}}`. Parameters bind values, not paths (`items[:key]` is a parser error).\n- Remove an entry with ``UNSET items.`\u003Ckey>` `` only after validating the key against a strict pattern (for example, a UUID).\n- Mark entries removed (`removed = true`) when concurrent edits are likely; readers skip entries whose required fields are missing or `null`. **Note (SDK 5.1.0 and 5.2.0)**: a removal does not win over a concurrent edit; the entry stays with only the edited fields (removal first) or with them `null` (removal later).\n- Move an entry by writing only its `position`, between its new neighbors; renumbering all entries loses a concurrent reorder.\n- Convert an array to a map as soon as more than one device writes it, into a **new field** (`lineItems` next to `items`, in stages).\n\n**❌ DON'T**: splice unchecked input into a query; write the map under the array's name (both then share one key).\n\n`§ Arrays and Maps` · Example: [examples\u002Farray-to-map.sql](examples\u002Farray-to-map.sql)\n\n### 3. Keep the default strict mode and declare types consistently (CRITICAL)\n\n**The default is `DQL_STRICT_MODE = false`.**\n\n| Behavior | `false` (default) | `true` |\n|---|---|---|\n| Undeclared objects | `MAP` (field-level merge) | `REGISTER` (whole-object replacement) |\n| `SET obj.a = 1` on an undeclared object | Merges the field | Fails: `Unsupported DML operation on REGISTER field` |\n| MAP \u002F COUNTER \u002F ATTACHMENT fields | Inferred | Must be declared in every statement |\n| `SELECT` \u002F `WHERE` on undeclared MAP \u002F COUNTER \u002F ATTACHMENT fields | Visible | **Invisible** |\n| Secondary index use | Used | Not used (see the note) |\n\n**Note (SDK 5.1.0 and 5.2.0)**: with `DQL_STRICT_MODE = true` the planner does not use secondary indexes (`EXPLAIN` shows a collection scan); ID lookups and full-collection `COUNT(*)` are not affected.\n\nChoose `true` only if nearly every object needs replacement and you will declare every MAP, COUNTER, and ATTACHMENT field. Set it on every open in `DittoConfig.systemParameters` (SDK 5.2+; on 5.1, `ALTER SYSTEM` after `Ditto.open`, before sync, queries, and observers), with the same value on every peer (each peer interprets synced data with its own setting).\n\n**✅ DO**: for a few replace-as-a-whole objects, keep the default and declare `REGISTER` **in every statement** on the field, reads included: `UPDATE COLLECTION customers (shippingAddress REGISTER) SET shippingAddress = :address WHERE _id = :id` and `SELECT * FROM COLLECTION customers (shippingAddress REGISTER) WHERE _id = :id`.\n\n**❌ DON'T**: mix declarations for one field. Each statement reads or writes the value of its declared type, so values seem to vanish even on one device: a `REGISTER` insert followed by an undeclared `SET obj.a = 11` makes an undeclared `SELECT` return `\"obj\": {\"a\": 11}`.\n\n`§ Strict Mode`, `§ Keep type declarations consistent` · Example: [examples\u002Fstrict-mode-and-declarations.sql](examples\u002Fstrict-mode-and-declarations.sql)\n\n### 4. Use COUNTER with APPLY for concurrent tallies (CRITICAL)\n\nCounters (`COUNTER`, and the legacy `PN_COUNTER`) are the only types that add concurrent changes together. Use `APPLY`, not `SET`, and the `COLLECTION` keyword for declarations: `APPLY f INCREMENT BY n` (integer `n`; negative to decrement), `APPLY f RESTART WITH n` (concurrent `RESTART`s: last writer wins), `APPLY f RESTART` (zero).\n\n**✅ DO**: initialize with `INSERT INTO COLLECTION products (viewCount COUNTER) DOCUMENTS (:product)` (`INITIAL DOCUMENTS` if every device creates it) and increment with `UPDATE COLLECTION products (viewCount COUNTER) APPLY viewCount INCREMENT BY 1 WHERE _id = :id`.\n\n**❌ DON'T**:\n- `SET stock = stock - 1` (two devices both write 9 from 10; one decrement is lost).\n- Initialize with an undeclared `INSERT` (stored as a REGISTER; the first `INCREMENT` starts a new counter at 0), or overwrite with `SET` (use `RESTART WITH`).\n- Write a counter value while devices hold unsynced increments: `RESTART WITH`, an upsert (even `DO UPDATE_LOCAL_DIFF`), or a plain `INSERT` of another device's document discards them, even later ones (**Note (SDK 5.1.0 and 5.2.0)**). Recount only while every device is in sync, or derive the value from events.\n- Use counters for unique sequence numbers, values a `COUNT(*)` can derive, or fractional amounts (integer-only; count in cents). A counter adds every change but enforces no rule (\"never below zero\").\n- Mix `COUNTER` and `PN_INCREMENT` on one field.\n\n**A check before a write holds on this device only.** A conditional `UPDATE`, a query before an `INSERT`, `COUNT(*) + 1`, or a transaction is not a lock, uniqueness check, or sequence across devices: both devices pass, and one claim is lost without an error. Record claims per device; a value is `_id` only for one shared entity.\n\n`§ Counters`, `§ Checks and Claims across Devices` · Example: [examples\u002Fcounter-patterns.sql](examples\u002Fcounter-patterns.sql) · More: [reference\u002Fcommon-patterns.md](reference\u002Fcommon-patterns.md) (Pattern 5)\n\n### 5. Generate collision-free document IDs (CRITICAL)\n\n| Strategy | Use when |\n|---|---|\n| **UUID v4** (primary) | Almost always |\n| ULID \u002F time-ordered random ID | Rough creation-time ordering (device clocks make it approximate) |\n| Composite object `{\"storeId\": ..., \"orderId\": \"\u003Cuuid>\"}` | Permissions or subscriptions scoped by owner, location, or tenant |\n| Natural key (SKU) | Globally unique, immutable domain key |\n| Generated by Ditto (omit `_id`) | Nothing needs the ID before insert; read the result's mutated document IDs |\n\n- **Never** use sequential or timestamp-only IDs: two offline devices produce the same ID, and the documents merge into one.\n- `_id` is immutable: copy to a new `_id` and remove the old document in one transaction, declaring `COUNTER`, `ATTACHMENT`, and `REGISTER` fields in both the `SELECT` and the `INSERT` (see the reference).\n- Put only immutable attributes into a composite `_id`; filter and index its subfields (`_id.storeId`).\n- Keep human-readable numbers (`#A-0042`) in a separate field: labels, not keys.\n\n`§ Document IDs` · Examples: [examples\u002Fid-generation-patterns.sql](examples\u002Fid-generation-patterns.sql), `ids-and-timestamps` in `examples\u002F\u003Csdk>\u002F`, [examples\u002Fcomposite-id-patterns.sql](examples\u002Fcomposite-id-patterns.sql), [examples\u002Fid-immutability-workaround.sql](examples\u002Fid-immutability-workaround.sql) · More: [reference\u002Fadvanced-patterns.md](reference\u002Fadvanced-patterns.md) (ID types, changing an ID, composite IDs, display numbers)\n\n### 6. Embed by default; JOIN separate collections locally (CRITICAL)\n\nEmbed sub-entities as maps keyed by ID. `JOIN` **(SDK 5.1+)** removes the main read-side cost of separate collections, but each collection is still a separate sync unit with its own subscription, and the join key needs an index.\n\n| Embed when the data is... | Use a separate collection when the data is... |\n|---|---|\n| Read together with the parent | Accessed independently of the parent |\n| Owned by exactly one parent | Shared by many parents (products in many orders) |\n| Small and bounded (tens of entries) | Unbounded (events, readings, messages) |\n| Covered by the parent's permissions | Governed by different permissions |\n\nConcurrent edits alone are **not** a reason to split: map entries merge.\n\n**JOIN rules (SDK 5.1+)**: local data only (never fetches from peers); not in subscriptions (`Unsupported feature: Joining`) or on Ditto Server; qualify every field with its alias; index the inner collection's join key, or join on its `_id`, or the JOIN fails (`disallowed without appropriate index support`).\n\n**✅ DO**:\n- Subscribe to every joined collection; copy the filter key (`storeId`) into children, since subscriptions filter only on their own fields.\n- Treat a missing joined document as normal (not synced yet); use `LEFT JOIN` when the parent must appear without children.\n- Write a parent and children created together in one transaction; check plans with `EXPLAIN` and `ADVISE`.\n- Copy a value only when it is a snapshot (price at time of sale) or a subscription filter key; otherwise reference by ID and JOIN at read time.\n\n**❌ DON'T**: silence the index error with `USE INDEX ''` on a large collection; split a small sub-entity only because JOIN exists.\n\n`§ Relationships: Embedding, Separate Collections, and JOIN`, `§ Joining Collections (SDK 5.1+)` · Examples: [examples\u002Fembedded-relationship.sql](examples\u002Fembedded-relationship.sql), [examples\u002Fforeign-key-join.sql](examples\u002Fforeign-key-join.sql) · More: [reference\u002Fadvanced-patterns.md](reference\u002Fadvanced-patterns.md) (JOIN queries, index error)\n\n### 7. Keep documents well under the size limits (CRITICAL)\n\n| Threshold | Default | Behavior |\n|---|---|---|\n| Soft limit | 256 KiB | Write succeeds; warning `exceeds recommended limit` is logged |\n| Hard limit | 5 MiB | A local `INSERT` \u002F `UPDATE` fails with the SDK's error; the stored document is unchanged |\n\n**Note (SDK 5.1.0)**: merges are not checked against the hard limit; concurrent offline additions can produce a larger document everywhere, after which every `UPDATE` fails until `UNSET` removes data. On 5.2.0, receivers drop them; copies diverge until one is evicted, losing its changes (see the reference).\n\n**✅ DO**: stay well below 256 KiB per stored document; store binaries as attachments; move unbounded data (history, readings, comments) to its own collection; keep the default limits. `object_size()` is approximate.\n\n`§ Document Size Limits` · Example: [examples\u002Fdocument-size.sql](examples\u002Fdocument-size.sql) · More: [reference\u002Fcommon-patterns.md](reference\u002Fcommon-patterns.md) (causes of growth, system parameters)\n\n### 8. Store timestamps in UTC with a zone designator and fixed precision (CRITICAL)\n\nStore UTC with a zone designator (an ISO-8601 string ending in `Z`) or epoch milliseconds, consistently per field. Zone-less ISO strings make every DQL date function return `MISSING` silently. Clocks drift: never resolve conflicting writes with your own timestamp fields.\n\nISO strings sort as text only at one precision; some formatters vary it even on one device (native Dart omits zero microseconds). Write every sorted or compared timestamp with one helper that writes UTC with exactly millisecond precision (`2026-10-08T10:30:00.123Z`): `ids-and-timestamps` in `examples\u002F\u003Csdk>\u002F`.\n\n`§ Timestamps` · Examples: [examples\u002Ftimestamps.sql](examples\u002Ftimestamps.sql), `ids-and-timestamps` in `examples\u002F\u003Csdk>\u002F`\n\n### 9. Do not store derived values (MEDIUM)\n\nA stored total is a separate register that devices recompute from partial views; after the merge it can match neither. Compute it at read time, in app code or DQL.\n\n**✅ DO**: copy snapshot values, which are facts, not derivations (`unitPriceCents` into the line item when it is added); initialize flags you filter on (`isDeleted: false`) or filter with `coalesce(isDeleted, false) = false`.\n\n**❌ DON'T**: store UI state, progress flags, or device-local paths in synced documents.\n\n`§ Document Structure` · Example: [examples\u002Fderived-values.sql](examples\u002Fderived-values.sql) · More: [reference\u002Fcommon-patterns.md](reference\u002Fcommon-patterns.md) (document structure, field names)\n\n## Checklist\n\n- [ ] Each change to stored data marked additive or breaking; breaking ones versioned and rolled out in stages (deployed apps)\n- [ ] Items edited by several devices live in maps keyed by stable IDs, not arrays\n- [ ] No reliance on `SET obj = {...}` \u002F `DO UPDATE` to remove keys; `UNSET` used\n- [ ] User edits are field-level `UPDATE`s; upserts and re-imports use `DO UPDATE_LOCAL_DIFF`\n- [ ] `DQL_STRICT_MODE` left at `false`, or applied on every launch and identical on every peer\n- [ ] Each declared field (`REGISTER`, `MAP`, `COUNTER`, `ATTACHMENT`) declared the same way in every statement\n- [ ] Embedded by default; separate collections justified by the decision guide\n- [ ] JOINs: inner join key indexed (or `_id`), each joined collection subscribed, no JOIN in subscriptions\n- [ ] No stored derived values; snapshot values copied deliberately\n- [ ] Concurrent tallies use `COUNTER` with `APPLY`; `RESTART WITH` only while every device is in sync\n- [ ] No lock, uniqueness check, or sequence number resting on a local check\n- [ ] UUID (or composite \u002F natural) IDs; display numbers separate from `_id`\n- [ ] Shared defaults seeded with `INITIAL DOCUMENTS` (not `INSERT` or `DO UPDATE`), identical in every app version\n- [ ] Documents well under 256 KiB; binaries as attachments\n- [ ] Timestamps in UTC with a zone designator, written by one fixed-precision helper\n\n## More\n\n- Reference: [reference\u002Fcommon-patterns.md](reference\u002Fcommon-patterns.md) (conflict policies, audit logs, document structure, size), [reference\u002Fadvanced-patterns.md](reference\u002Fadvanced-patterns.md) (history, `INITIAL DOCUMENTS`, schema evolution, IDs, JOIN)\n- Examples: [examples\u002F](examples\u002F) - DQL files linked from each rule; `examples\u002F\u003Csdk>\u002F` for the ID and timestamp helpers\n- Related skills: `query-sync` (DQL, subscriptions, observers), `storage-lifecycle` (deletion), `transactions-attachments`, `performance-observability` (indexes, EXPLAIN, ADVISE)\n","# Ditto Data Modeling\n\nHow to shape Ditto documents so concurrent offline edits merge correctly. Targets Ditto SDK 5.2.0 with the default `DQL_STRICT_MODE = false`; the rules are the same in every SDK.\n\n## Before You Apply\n\n- Identify the project's SDK and version: Flutter (`ditto_live` in `pubspec.yaml` \u002F `pubspec.lock`), JavaScript (`@dittolive\u002Fditto` in `package.json`), Kotlin (`com.ditto:ditto-kotlin` in Gradle files), or Swift (`DittoSwift` in `Package.swift`, `Package.resolved`, or the Xcode project). These rules target SDK 5.2.0; for devices that still run 5.1.0, also apply `§ Known Issues in SDK 5.1.0`. **Note (SDK 5.1.0 and 5.2.0)** and **Note (SDK 5.1.0)** mark easy-to-miss behavior seen on those releases, with the safe pattern; **(SDK 5.1+)** \u002F **(SDK 5.2+)** mark features introduced in that release.\n- For API calls, Grep the outline of that SDK's page, `${CLAUDE_SKILL_DIR}\u002F..\u002Fguide\u002Freference\u002Fbest-practices\u002Fplatforms\u002F\u003Csdk>.md` (`flutter`, `javascript`, `kotlin`, `swift`), with `^#{1,3} ` and read only the section you need, not the whole page; sections are named `\u003CTopic> in \u003CSDK>`. DQL examples: `examples\u002F*.sql` (every SDK); API examples: `examples\u002F\u003Csdk>\u002F`, with the same base names in every SDK.\n- `§ \u003CHeading>` cites the full guide: Grep the heading as a fixed string in `best-practices\u002F` and `knowledge\u002F` under `${CLAUDE_SKILL_DIR}\u002F..\u002Fguide\u002Freference\u002F`, then read that section.\n- Report each finding at the severity of its item in `§ Anti-Pattern Checklist` (the checklist decides; Grep a phrase of the item there). The labels below rank the rules, not each item in them.\n- **Is the app deployed?** Older app versions keep writing your documents. Mark each change to stored data, fixes included, as additive or breaking (`§ Breaking and additive changes`). In a deployed app, a field that replaces another needs `§ A field that replaces another`; only an unreleased app, or a demo sharing no database with a released app, changes in place.\n\n## Prevents\n\n- Lost edits in arrays changed on several devices (an array is one last-writer-wins register)\n- Keys that never go away because `SET obj = {...}` and `DO UPDATE` merge into maps\n- Values that seem to vanish when type declarations differ between statements\n- Lost increments from read-modify-write instead of `COUNTER`; derived totals that diverge\n- ID collisions from sequential or timestamp-only IDs; documents over the size limits\n- Zone-less timestamps that make DQL date functions return `MISSING`\n\n## Workflow\n\n```\nSchema Design Progress:\n- [ ] 1. For each field, decide the merge you need: REGISTER, MAP, COUNTER, or ATTACHMENT\n- [ ] 2. Replace arrays that several devices edit with maps keyed by a stable ID\n- [ ] 3. Keep DQL_STRICT_MODE = false; declare REGISTER only for objects that must never mix\n- [ ] 4. Embed by default; split into a collection only per the decision guide, then JOIN locally\n- [ ] 5. Remove stored derived values; keep snapshot values (price at time of sale)\n- [ ] 6. Use COUNTER (declared consistently) for tallies changed concurrently\n- [ ] 7. Generate collision-free IDs (UUID v4); keep display numbers separate from _id\n- [ ] 8. Keep documents well under 256 KiB; move unbounded data and binaries out\n- [ ] 9. Store timestamps in UTC with a zone designator\n```\n\n## Rules\n\n### 1. Model every field for its merge (CRITICAL)\n\nEvery value is stored as a CRDT. With the default settings the type is inferred:\n\n| You write | Stored as | Concurrent writes |\n|---|---|---|\n| Scalar (string, number, boolean, null) | `REGISTER` | Last writer wins (Hybrid Logical Clock); the loser is discarded silently |\n| Array | `REGISTER` | The **whole array** is one value; one version wins |\n| Object | `MAP` | Each key merges independently (add-wins); nested objects are nested maps |\n| `APPLY f INCREMENT BY n` \u002F `RESTART` | `COUNTER` | Increments from all devices are added together |\n| Attachment | `ATTACHMENT` | Last writer wins |\n\nLocal write semantics on an existing object `{\"a\": 1, \"b\": 2}`:\n\n| Statement | Result |\n|---|---|\n| `SET obj.a = 10` | `{\"a\": 10, \"b\": 2}` |\n| `SET obj = {'c': 3}` | `{\"a\": 1, \"b\": 2, \"c\": 3}`: assigning an object **merges** |\n| `SET obj = {}` | `{\"a\": 1, \"b\": 2}`: clears nothing |\n| `UNSET obj.b` | `{\"a\": 1}`: `UNSET` is the only way to remove a key |\n| `ON ID CONFLICT DO UPDATE` with `{\"obj\": {\"c\": 3}}` | `{\"a\": 1, \"b\": 2, \"c\": 3}`: upserts merge too |\n\n**✅ DO**:\n- Update individual fields (`UPDATE ... SET obj.field = :value`), only the ones the user changed.\n- Use `ON ID CONFLICT DO UPDATE_LOCAL_DIFF` for upserts and re-imports of data another system owns (it skips equal fields).\n- Remove keys with `UNSET`. To replace an object, run `UNSET` then `SET` in one transaction, or declare it `REGISTER` (Rule 3). Only `REGISTER` keeps concurrent edits from mixing: after `UNSET` and `SET` the field is still a map.\n\n**❌ DON'T**:\n- Assume `SET obj = {...}` or `DO UPDATE` removes keys you left out, or clear a map with `SET obj = {}` or a scalar (`SET obj = 5`).\n- Write back a stale in-memory copy with `DO UPDATE` or `DO UPDATE_LOCAL_DIFF` (it writes every field that differs locally, old values included): either overrides a concurrent change.\n\n`§ CRDT Types and Merge Behavior`, `§ Local Write Semantics You Must Know`, `§ Document Structure` · Example: [examples\u002Ffield-level-updates.sql](examples\u002Ffield-level-updates.sql) · More: [reference\u002Fcommon-patterns.md](reference\u002Fcommon-patterns.md) (conflict policies, replacing an object, `UNSET` metadata)\n\n### 2. Use maps keyed by ID, not arrays, for data several devices edit (CRITICAL)\n\n| Use a **map keyed by ID** when | Use an **array** when |\n|---|---|\n| Several devices may add, edit, or remove items | Only one device writes; others read |\n| Items have a natural or synthetic unique ID | Order matters and the list is never edited concurrently |\n| You update or index individual items | It is a list of scalars replaced wholesale |\n\n```json\n\u002F\u002F ❌ BAD: concurrent edits to different items: one device's change is lost\n{ \"_id\": \"order-1\", \"items\": [ { \"productId\": \"p1\", \"quantity\": 2 } ] }\n\u002F\u002F ✅ GOOD: entries merge independently; display order is a field\n{ \"_id\": \"order-1\", \"items\": { \"\u003Citem uuid>\": { \"productId\": \"p1\", \"quantity\": 2, \"position\": 0 } } }\n```\n\n**✅ DO**:\n- Pass a variable key as data: `INSERT INTO orders DOCUMENTS (:patch) ON ID CONFLICT DO UPDATE_LOCAL_DIFF` with `patch = {'_id': orderId, 'items': {itemId: item}}`. Parameters bind values, not paths (`items[:key]` is a parser error).\n- Remove an entry with ``UNSET items.`\u003Ckey>` `` only after validating the key against a strict pattern (for example, a UUID).\n- Mark entries removed (`removed = true`) when concurrent edits are likely; readers skip entries whose required fields are missing or `null`. **Note (SDK 5.1.0 and 5.2.0)**: a removal does not win over a concurrent edit; the entry stays with only the edited fields (removal first) or with them `null` (removal later).\n- Move an entry by writing only its `position`, between its new neighbors; renumbering all entries loses a concurrent reorder.\n- Convert an array to a map as soon as more than one device writes it, into a **new field** (`lineItems` next to `items`, in stages).\n\n**❌ DON'T**: splice unchecked input into a query; write the map under the array's name (both then share one key).\n\n`§ Arrays and Maps` · Example: [examples\u002Farray-to-map.sql](examples\u002Farray-to-map.sql)\n\n### 3. Keep the default strict mode and declare types consistently (CRITICAL)\n\n**The default is `DQL_STRICT_MODE = false`.**\n\n| Behavior | `false` (default) | `true` |\n|---|---|---|\n| Undeclared objects | `MAP` (field-level merge) | `REGISTER` (whole-object replacement) |\n| `SET obj.a = 1` on an undeclared object | Merges the field | Fails: `Unsupported DML operation on REGISTER field` |\n| MAP \u002F COUNTER \u002F ATTACHMENT fields | Inferred | Must be declared in every statement |\n| `SELECT` \u002F `WHERE` on undeclared MAP \u002F COUNTER \u002F ATTACHMENT fields | Visible | **Invisible** |\n| Secondary index use | Used | Not used (see the note) |\n\n**Note (SDK 5.1.0 and 5.2.0)**: with `DQL_STRICT_MODE = true` the planner does not use secondary indexes (`EXPLAIN` shows a collection scan); ID lookups and full-collection `COUNT(*)` are not affected.\n\nChoose `true` only if nearly every object needs replacement and you will declare every MAP, COUNTER, and ATTACHMENT field. Set it on every open in `DittoConfig.systemParameters` (SDK 5.2+; on 5.1, `ALTER SYSTEM` after `Ditto.open`, before sync, queries, and observers), with the same value on every peer (each peer interprets synced data with its own setting).\n\n**✅ DO**: for a few replace-as-a-whole objects, keep the default and declare `REGISTER` **in every statement** on the field, reads included: `UPDATE COLLECTION customers (shippingAddress REGISTER) SET shippingAddress = :address WHERE _id = :id` and `SELECT * FROM COLLECTION customers (shippingAddress REGISTER) WHERE _id = :id`.\n\n**❌ DON'T**: mix declarations for one field. Each statement reads or writes the value of its declared type, so values seem to vanish even on one device: a `REGISTER` insert followed by an undeclared `SET obj.a = 11` makes an undeclared `SELECT` return `\"obj\": {\"a\": 11}`.\n\n`§ Strict Mode`, `§ Keep type declarations consistent` · Example: [examples\u002Fstrict-mode-and-declarations.sql](examples\u002Fstrict-mode-and-declarations.sql)\n\n### 4. Use COUNTER with APPLY for concurrent tallies (CRITICAL)\n\nCounters (`COUNTER`, and the legacy `PN_COUNTER`) are the only types that add concurrent changes together. Use `APPLY`, not `SET`, and the `COLLECTION` keyword for declarations: `APPLY f INCREMENT BY n` (integer `n`; negative to decrement), `APPLY f RESTART WITH n` (concurrent `RESTART`s: last writer wins), `APPLY f RESTART` (zero).\n\n**✅ DO**: initialize with `INSERT INTO COLLECTION products (viewCount COUNTER) DOCUMENTS (:product)` (`INITIAL DOCUMENTS` if every device creates it) and increment with `UPDATE COLLECTION products (viewCount COUNTER) APPLY viewCount INCREMENT BY 1 WHERE _id = :id`.\n\n**❌ DON'T**:\n- `SET stock = stock - 1` (two devices both write 9 from 10; one decrement is lost).\n- Initialize with an undeclared `INSERT` (stored as a REGISTER; the first `INCREMENT` starts a new counter at 0), or overwrite with `SET` (use `RESTART WITH`).\n- Write a counter value while devices hold unsynced increments: `RESTART WITH`, an upsert (even `DO UPDATE_LOCAL_DIFF`), or a plain `INSERT` of another device's document discards them, even later ones (**Note (SDK 5.1.0 and 5.2.0)**). Recount only while every device is in sync, or derive the value from events.\n- Use counters for unique sequence numbers, values a `COUNT(*)` can derive, or fractional amounts (integer-only; count in cents). A counter adds every change but enforces no rule (\"never below zero\").\n- Mix `COUNTER` and `PN_INCREMENT` on one field.\n\n**A check before a write holds on this device only.** A conditional `UPDATE`, a query before an `INSERT`, `COUNT(*) + 1`, or a transaction is not a lock, uniqueness check, or sequence across devices: both devices pass, and one claim is lost without an error. Record claims per device; a value is `_id` only for one shared entity.\n\n`§ Counters`, `§ Checks and Claims across Devices` · Example: [examples\u002Fcounter-patterns.sql](examples\u002Fcounter-patterns.sql) · More: [reference\u002Fcommon-patterns.md](reference\u002Fcommon-patterns.md) (Pattern 5)\n\n### 5. Generate collision-free document IDs (CRITICAL)\n\n| Strategy | Use when |\n|---|---|\n| **UUID v4** (primary) | Almost always |\n| ULID \u002F time-ordered random ID | Rough creation-time ordering (device clocks make it approximate) |\n| Composite object `{\"storeId\": ..., \"orderId\": \"\u003Cuuid>\"}` | Permissions or subscriptions scoped by owner, location, or tenant |\n| Natural key (SKU) | Globally unique, immutable domain key |\n| Generated by Ditto (omit `_id`) | Nothing needs the ID before insert; read the result's mutated document IDs |\n\n- **Never** use sequential or timestamp-only IDs: two offline devices produce the same ID, and the documents merge into one.\n- `_id` is immutable: copy to a new `_id` and remove the old document in one transaction, declaring `COUNTER`, `ATTACHMENT`, and `REGISTER` fields in both the `SELECT` and the `INSERT` (see the reference).\n- Put only immutable attributes into a composite `_id`; filter and index its subfields (`_id.storeId`).\n- Keep human-readable numbers (`#A-0042`) in a separate field: labels, not keys.\n\n`§ Document IDs` · Examples: [examples\u002Fid-generation-patterns.sql](examples\u002Fid-generation-patterns.sql), `ids-and-timestamps` in `examples\u002F\u003Csdk>\u002F`, [examples\u002Fcomposite-id-patterns.sql](examples\u002Fcomposite-id-patterns.sql), [examples\u002Fid-immutability-workaround.sql](examples\u002Fid-immutability-workaround.sql) · More: [reference\u002Fadvanced-patterns.md](reference\u002Fadvanced-patterns.md) (ID types, changing an ID, composite IDs, display numbers)\n\n### 6. Embed by default; JOIN separate collections locally (CRITICAL)\n\nEmbed sub-entities as maps keyed by ID. `JOIN` **(SDK 5.1+)** removes the main read-side cost of separate collections, but each collection is still a separate sync unit with its own subscription, and the join key needs an index.\n\n| Embed when the data is... | Use a separate collection when the data is... |\n|---|---|\n| Read together with the parent | Accessed independently of the parent |\n| Owned by exactly one parent | Shared by many parents (products in many orders) |\n| Small and bounded (tens of entries) | Unbounded (events, readings, messages) |\n| Covered by the parent's permissions | Governed by different permissions |\n\nConcurrent edits alone are **not** a reason to split: map entries merge.\n\n**JOIN rules (SDK 5.1+)**: local data only (never fetches from peers); not in subscriptions (`Unsupported feature: Joining`) or on Ditto Server; qualify every field with its alias; index the inner collection's join key, or join on its `_id`, or the JOIN fails (`disallowed without appropriate index support`).\n\n**✅ DO**:\n- Subscribe to every joined collection; copy the filter key (`storeId`) into children, since subscriptions filter only on their own fields.\n- Treat a missing joined document as normal (not synced yet); use `LEFT JOIN` when the parent must appear without children.\n- Write a parent and children created together in one transaction; check plans with `EXPLAIN` and `ADVISE`.\n- Copy a value only when it is a snapshot (price at time of sale) or a subscription filter key; otherwise reference by ID and JOIN at read time.\n\n**❌ DON'T**: silence the index error with `USE INDEX ''` on a large collection; split a small sub-entity only because JOIN exists.\n\n`§ Relationships: Embedding, Separate Collections, and JOIN`, `§ Joining Collections (SDK 5.1+)` · Examples: [examples\u002Fembedded-relationship.sql](examples\u002Fembedded-relationship.sql), [examples\u002Fforeign-key-join.sql](examples\u002Fforeign-key-join.sql) · More: [reference\u002Fadvanced-patterns.md](reference\u002Fadvanced-patterns.md) (JOIN queries, index error)\n\n### 7. Keep documents well under the size limits (CRITICAL)\n\n| Threshold | Default | Behavior |\n|---|---|---|\n| Soft limit | 256 KiB | Write succeeds; warning `exceeds recommended limit` is logged |\n| Hard limit | 5 MiB | A local `INSERT` \u002F `UPDATE` fails with the SDK's error; the stored document is unchanged |\n\n**Note (SDK 5.1.0)**: merges are not checked against the hard limit; concurrent offline additions can produce a larger document everywhere, after which every `UPDATE` fails until `UNSET` removes data. On 5.2.0, receivers drop them; copies diverge until one is evicted, losing its changes (see the reference).\n\n**✅ DO**: stay well below 256 KiB per stored document; store binaries as attachments; move unbounded data (history, readings, comments) to its own collection; keep the default limits. `object_size()` is approximate.\n\n`§ Document Size Limits` · Example: [examples\u002Fdocument-size.sql](examples\u002Fdocument-size.sql) · More: [reference\u002Fcommon-patterns.md](reference\u002Fcommon-patterns.md) (causes of growth, system parameters)\n\n### 8. Store timestamps in UTC with a zone designator and fixed precision (CRITICAL)\n\nStore UTC with a zone designator (an ISO-8601 string ending in `Z`) or epoch milliseconds, consistently per field. Zone-less ISO strings make every DQL date function return `MISSING` silently. Clocks drift: never resolve conflicting writes with your own timestamp fields.\n\nISO strings sort as text only at one precision; some formatters vary it even on one device (native Dart omits zero microseconds). Write every sorted or compared timestamp with one helper that writes UTC with exactly millisecond precision (`2026-10-08T10:30:00.123Z`): `ids-and-timestamps` in `examples\u002F\u003Csdk>\u002F`.\n\n`§ Timestamps` · Examples: [examples\u002Ftimestamps.sql](examples\u002Ftimestamps.sql), `ids-and-timestamps` in `examples\u002F\u003Csdk>\u002F`\n\n### 9. Do not store derived values (MEDIUM)\n\nA stored total is a separate register that devices recompute from partial views; after the merge it can match neither. Compute it at read time, in app code or DQL.\n\n**✅ DO**: copy snapshot values, which are facts, not derivations (`unitPriceCents` into the line item when it is added); initialize flags you filter on (`isDeleted: false`) or filter with `coalesce(isDeleted, false) = false`.\n\n**❌ DON'T**: store UI state, progress flags, or device-local paths in synced documents.\n\n`§ Document Structure` · Example: [examples\u002Fderived-values.sql](examples\u002Fderived-values.sql) · More: [reference\u002Fcommon-patterns.md](reference\u002Fcommon-patterns.md) (document structure, field names)\n\n## Checklist\n\n- [ ] Each change to stored data marked additive or breaking; breaking ones versioned and rolled out in stages (deployed apps)\n- [ ] Items edited by several devices live in maps keyed by stable IDs, not arrays\n- [ ] No reliance on `SET obj = {...}` \u002F `DO UPDATE` to remove keys; `UNSET` used\n- [ ] User edits are field-level `UPDATE`s; upserts and re-imports use `DO UPDATE_LOCAL_DIFF`\n- [ ] `DQL_STRICT_MODE` left at `false`, or applied on every launch and identical on every peer\n- [ ] Each declared field (`REGISTER`, `MAP`, `COUNTER`, `ATTACHMENT`) declared the same way in every statement\n- [ ] Embedded by default; separate collections justified by the decision guide\n- [ ] JOINs: inner join key indexed (or `_id`), each joined collection subscribed, no JOIN in subscriptions\n- [ ] No stored derived values; snapshot values copied deliberately\n- [ ] Concurrent tallies use `COUNTER` with `APPLY`; `RESTART WITH` only while every device is in sync\n- [ ] No lock, uniqueness check, or sequence number resting on a local check\n- [ ] UUID (or composite \u002F natural) IDs; display numbers separate from `_id`\n- [ ] Shared defaults seeded with `INITIAL DOCUMENTS` (not `INSERT` or `DO UPDATE`), identical in every app version\n- [ ] Documents well under 256 KiB; binaries as attachments\n- [ ] Timestamps in UTC with a zone designator, written by one fixed-precision helper\n\n## More\n\n- Reference: [reference\u002Fcommon-patterns.md](reference\u002Fcommon-patterns.md) (conflict policies, audit logs, document structure, size), [reference\u002Fadvanced-patterns.md](reference\u002Fadvanced-patterns.md) (history, `INITIAL DOCUMENTS`, schema evolution, IDs, JOIN)\n- Examples: [examples\u002F](examples\u002F) - DQL files linked from each rule; `examples\u002F\u003Csdk>\u002F` for the ID and timestamp helpers\n- Related skills: `query-sync` (DQL, subscriptions, observers), `storage-lifecycle` (deletion), `transactions-attachments`, `performance-observability` (indexes, EXPLAIN, ADVISE)\n",{"name":5,"description":7},"main","b67d1a0bc891c9b2a952f8beb0a6dce7d449717c","plugins\u002Fditto\u002Fskills\u002Fdata-modeling","https:\u002F\u002Fgithub.com\u002Fditto-examples\u002Fditto-cookbook","https:\u002F\u002Fdocs.ditto.live\u002Fhome\u002Fintroduction","https:\u002F\u002Fgithub.com\u002Fditto-examples","https:\u002F\u002Fdocs.ditto.live","Example Apps and Information for Ditto","2026-11-13 17:08:48",{"source":8,"skillName":5,"commands":64,"prompt":74,"zipAvailable":75},[65,68,71],{"tool":66,"command":67},"npx","npx skills add ditto-examples\u002Fditto-cookbook --skill data-modeling",{"tool":69,"command":70},"bunx","bunx skills add ditto-examples\u002Fditto-cookbook --skill data-modeling",{"tool":72,"command":73},"pnpm","pnpm dlx skills add ditto-examples\u002Fditto-cookbook --skill data-modeling","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fditto-examples\u002Fditto-cookbook\u002Fblob\u002Fmain\u002Fplugins\u002Fditto\u002Fskills\u002Fdata-modeling\u002FSKILL.md",true,[77,83,87,91,95,99,103,107,111,115,119,123,127,131,137,141,145,149,153,157,163],{"path":78,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":81,"sourceHtmlUrl":82},"examples\u002Farray-to-map.sql","OTHER","其他",5249,"https:\u002F\u002Fgithub.com\u002Fditto-examples\u002Fditto-cookbook\u002Fblob\u002Fmain\u002Fplugins\u002Fditto\u002Fskills\u002Fdata-modeling\u002Fexamples\u002Farray-to-map.sql",{"path":84,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":85,"sourceHtmlUrl":86},"examples\u002Fcomposite-id-patterns.sql",2666,"https:\u002F\u002Fgithub.com\u002Fditto-examples\u002Fditto-cookbook\u002Fblob\u002Fmain\u002Fplugins\u002Fditto\u002Fskills\u002Fdata-modeling\u002Fexamples\u002Fcomposite-id-patterns.sql",{"path":88,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":89,"sourceHtmlUrl":90},"examples\u002Fcounter-patterns.sql",5108,"https:\u002F\u002Fgithub.com\u002Fditto-examples\u002Fditto-cookbook\u002Fblob\u002Fmain\u002Fplugins\u002Fditto\u002Fskills\u002Fdata-modeling\u002Fexamples\u002Fcounter-patterns.sql",{"path":92,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":93,"sourceHtmlUrl":94},"examples\u002Fderived-values.sql",3088,"https:\u002F\u002Fgithub.com\u002Fditto-examples\u002Fditto-cookbook\u002Fblob\u002Fmain\u002Fplugins\u002Fditto\u002Fskills\u002Fdata-modeling\u002Fexamples\u002Fderived-values.sql",{"path":96,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":97,"sourceHtmlUrl":98},"examples\u002Fdocument-size.sql",4058,"https:\u002F\u002Fgithub.com\u002Fditto-examples\u002Fditto-cookbook\u002Fblob\u002Fmain\u002Fplugins\u002Fditto\u002Fskills\u002Fdata-modeling\u002Fexamples\u002Fdocument-size.sql",{"path":100,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":101,"sourceHtmlUrl":102},"examples\u002Fembedded-relationship.sql",2261,"https:\u002F\u002Fgithub.com\u002Fditto-examples\u002Fditto-cookbook\u002Fblob\u002Fmain\u002Fplugins\u002Fditto\u002Fskills\u002Fdata-modeling\u002Fexamples\u002Fembedded-relationship.sql",{"path":104,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":105,"sourceHtmlUrl":106},"examples\u002Fevent-history.sql",3873,"https:\u002F\u002Fgithub.com\u002Fditto-examples\u002Fditto-cookbook\u002Fblob\u002Fmain\u002Fplugins\u002Fditto\u002Fskills\u002Fdata-modeling\u002Fexamples\u002Fevent-history.sql",{"path":108,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":109,"sourceHtmlUrl":110},"examples\u002Ffield-level-updates.sql",3837,"https:\u002F\u002Fgithub.com\u002Fditto-examples\u002Fditto-cookbook\u002Fblob\u002Fmain\u002Fplugins\u002Fditto\u002Fskills\u002Fdata-modeling\u002Fexamples\u002Ffield-level-updates.sql",{"path":112,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":113,"sourceHtmlUrl":114},"examples\u002Fflutter\u002Fids-and-timestamps.dart",3071,"https:\u002F\u002Fgithub.com\u002Fditto-examples\u002Fditto-cookbook\u002Fblob\u002Fmain\u002Fplugins\u002Fditto\u002Fskills\u002Fdata-modeling\u002Fexamples\u002Fflutter\u002Fids-and-timestamps.dart",{"path":116,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":117,"sourceHtmlUrl":118},"examples\u002Fforeign-key-join.sql",5174,"https:\u002F\u002Fgithub.com\u002Fditto-examples\u002Fditto-cookbook\u002Fblob\u002Fmain\u002Fplugins\u002Fditto\u002Fskills\u002Fdata-modeling\u002Fexamples\u002Fforeign-key-join.sql",{"path":120,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":121,"sourceHtmlUrl":122},"examples\u002Fid-generation-patterns.sql",3255,"https:\u002F\u002Fgithub.com\u002Fditto-examples\u002Fditto-cookbook\u002Fblob\u002Fmain\u002Fplugins\u002Fditto\u002Fskills\u002Fdata-modeling\u002Fexamples\u002Fid-generation-patterns.sql",{"path":124,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":125,"sourceHtmlUrl":126},"examples\u002Fid-immutability-workaround.sql",2610,"https:\u002F\u002Fgithub.com\u002Fditto-examples\u002Fditto-cookbook\u002Fblob\u002Fmain\u002Fplugins\u002Fditto\u002Fskills\u002Fdata-modeling\u002Fexamples\u002Fid-immutability-workaround.sql",{"path":128,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":129,"sourceHtmlUrl":130},"examples\u002Finitial-documents.sql",3746,"https:\u002F\u002Fgithub.com\u002Fditto-examples\u002Fditto-cookbook\u002Fblob\u002Fmain\u002Fplugins\u002Fditto\u002Fskills\u002Fdata-modeling\u002Fexamples\u002Finitial-documents.sql",{"path":132,"resourceType":133,"resourceTypeDesc":134,"sizeBytes":135,"sourceHtmlUrl":136},"examples\u002Fjavascript\u002Fids-and-timestamps.js","SCRIPT","脚本",2625,"https:\u002F\u002Fgithub.com\u002Fditto-examples\u002Fditto-cookbook\u002Fblob\u002Fmain\u002Fplugins\u002Fditto\u002Fskills\u002Fdata-modeling\u002Fexamples\u002Fjavascript\u002Fids-and-timestamps.js",{"path":138,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":139,"sourceHtmlUrl":140},"examples\u002Fkotlin\u002Fids-and-timestamps.kt",4251,"https:\u002F\u002Fgithub.com\u002Fditto-examples\u002Fditto-cookbook\u002Fblob\u002Fmain\u002Fplugins\u002Fditto\u002Fskills\u002Fdata-modeling\u002Fexamples\u002Fkotlin\u002Fids-and-timestamps.kt",{"path":142,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":143,"sourceHtmlUrl":144},"examples\u002Fstrict-mode-and-declarations.sql",3840,"https:\u002F\u002Fgithub.com\u002Fditto-examples\u002Fditto-cookbook\u002Fblob\u002Fmain\u002Fplugins\u002Fditto\u002Fskills\u002Fdata-modeling\u002Fexamples\u002Fstrict-mode-and-declarations.sql",{"path":146,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":147,"sourceHtmlUrl":148},"examples\u002Fswift\u002Fids-and-timestamps.swift",3485,"https:\u002F\u002Fgithub.com\u002Fditto-examples\u002Fditto-cookbook\u002Fblob\u002Fmain\u002Fplugins\u002Fditto\u002Fskills\u002Fdata-modeling\u002Fexamples\u002Fswift\u002Fids-and-timestamps.swift",{"path":150,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":151,"sourceHtmlUrl":152},"examples\u002Ftimestamps.sql",2223,"https:\u002F\u002Fgithub.com\u002Fditto-examples\u002Fditto-cookbook\u002Fblob\u002Fmain\u002Fplugins\u002Fditto\u002Fskills\u002Fdata-modeling\u002Fexamples\u002Ftimestamps.sql",{"path":154,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":155,"sourceHtmlUrl":156},"examples\u002Ftwo-collection-pattern.sql",2693,"https:\u002F\u002Fgithub.com\u002Fditto-examples\u002Fditto-cookbook\u002Fblob\u002Fmain\u002Fplugins\u002Fditto\u002Fskills\u002Fdata-modeling\u002Fexamples\u002Ftwo-collection-pattern.sql",{"path":158,"resourceType":159,"resourceTypeDesc":160,"sizeBytes":161,"sourceHtmlUrl":162},"reference\u002Fadvanced-patterns.md","REFERENCE","参考文档",13468,"https:\u002F\u002Fgithub.com\u002Fditto-examples\u002Fditto-cookbook\u002Fblob\u002Fmain\u002Fplugins\u002Fditto\u002Fskills\u002Fdata-modeling\u002Freference\u002Fadvanced-patterns.md",{"path":164,"resourceType":159,"resourceTypeDesc":160,"sizeBytes":165,"sourceHtmlUrl":166},"reference\u002Fcommon-patterns.md",15229,"https:\u002F\u002Fgithub.com\u002Fditto-examples\u002Fditto-cookbook\u002Fblob\u002Fmain\u002Fplugins\u002Fditto\u002Fskills\u002Fdata-modeling\u002Freference\u002Fcommon-patterns.md",[168,178,205,225,234,243],{"skillNo":169,"name":170,"nameZh":6,"description":171,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":172,"categories":173,"keywords":174,"publishedAt":49},"01M6C58EAD92WQKNE74549PXEW","transactions-attachments","Ditto SDK transactions and attachments (Flutter, JavaScript, Kotlin, Swift): ditto.store.transaction with tx.execute only, no nesting, short scopes, rollback, close(); newAttachment, ATTACHMENT declarations, lazy fetchAttachment with a stall timeout, immutability, thumbnails, and blob availability. Use when writing or reviewing ditto.store.transaction, newAttachment, or fetchAttachment code, or when displaying photos or files stored in Ditto.","https:\u002F\u002Fgithub.com\u002Fditto-examples\u002Fditto-cookbook\u002Fblob\u002Fmain\u002Fplugins\u002Fditto\u002Fskills\u002Ftransactions-attachments\u002FSKILL.md",[],[175,176,177],"transactions attachments","attachments","transactions",{"skillNo":179,"name":180,"nameZh":6,"description":181,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":182,"categories":183,"keywords":187,"publishedAt":49},"01M6C58B0PQHV5WXMQRP9DEPX1","testing","Ditto SDK testing strategies in Flutter, JavaScript, Kotlin, or Swift: local-store test helper, tests for DQL statements, MISSING\u002FNULL filters, merge-sensitive writes, soft delete, observer lifecycle, subscription rules, and multi-peer sync tests in one process. Use when writing or reviewing tests for code that uses Ditto, setting up a Ditto test harness, or reproducing a Ditto sync or merge bug.","https:\u002F\u002Fgithub.com\u002Fditto-examples\u002Fditto-cookbook\u002Fblob\u002Fmain\u002Fplugins\u002Fditto\u002Fskills\u002Ftesting\u002FSKILL.md",[184],{"categoryNo":185,"categoryName":186,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000008","测试与质量",[180,188,189,190,191,192,33,193,194,195,196,197,198,199,35,200,201,202,203,204],"writing","up","filters","code","delete","sync","local","strategies","bug","missing","tests","testing strategies","test harness","swift","for","harness","lifecycle",{"skillNo":206,"name":207,"nameZh":6,"description":208,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":209,"categories":210,"keywords":211,"publishedAt":49},"01M6C587HJC1SVAPYEZHJBV1C7","storage-lifecycle","Ditto SDK data removal and local storage management covering DELETE vs soft delete vs EVICT, tombstones and their TTL, husk documents, eviction with complementary subscriptions, retention cleanup, and storage monitoring. Use when writing Ditto DELETE or EVICT statements, soft-delete flags or retention cleanup for Ditto documents, or TOMBSTONE_TTL_HOURS, or when deleted Ditto data came back or evicted documents sync back.","https:\u002F\u002Fgithub.com\u002Fditto-examples\u002Fditto-cookbook\u002Fblob\u002Fmain\u002Fplugins\u002Fditto\u002Fskills\u002Fstorage-lifecycle\u002FSKILL.md",[],[204,212,213,194,193,214,188,215,44,216,217,218,219,220,221,222,35,223,224,192],"storage","storage lifecycle","cleanup","use","monitoring","back","evict","retention","sdk","with","subscriptions","ttl","ditto",{"skillNo":226,"name":227,"nameZh":6,"description":228,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":229,"categories":230,"keywords":231,"publishedAt":49},"01M6C5845MAD3AEBNSN3BT61WH","sdk-setup","Ditto SDK setup, lifecycle, and production security (Flutter, JavaScript, Kotlin, Swift): DittoConfig, the authentication expiration handler, system parameters, sync start and stop, close, transports, presence, keys, permissions, revocation. Use when initializing Ditto, writing Ditto login, startup, shutdown, or background code, configuring Ditto transports, reviewing Ditto security, or when Ditto sync never starts or devices do not connect.","https:\u002F\u002Fgithub.com\u002Fditto-examples\u002Fditto-cookbook\u002Fblob\u002Fmain\u002Fplugins\u002Fditto\u002Fskills\u002Fsdk-setup\u002FSKILL.md",[],[232,233,220],"setup","sdk setup",{"skillNo":235,"name":236,"nameZh":6,"description":237,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":238,"categories":239,"keywords":240,"publishedAt":49},"01M6C580SCSJK0E5Z54AJTV242","query-sync","Ditto SDK DQL reads and writes, subscriptions, and store observers (Flutter, JavaScript, Kotlin, Swift): query parameters, MISSING vs NULL, membership filters, subscription and observer lifecycle, ON ID CONFLICT upserts, JOIN, RETURNING. Use when writing or reviewing ditto.store.execute, ditto.sync.registerSubscription, registerObserver, or DQL in an app that uses Ditto, or when Ditto data does not sync or a Ditto query returns nothing.","https:\u002F\u002Fgithub.com\u002Fditto-examples\u002Fditto-cookbook\u002Fblob\u002Fmain\u002Fplugins\u002Fditto\u002Fskills\u002Fquery-sync\u002FSKILL.md",[],[193,241,242],"query sync","query",{"skillNo":244,"name":245,"nameZh":6,"description":246,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":247,"categories":248,"keywords":249,"publishedAt":49},"01M6C57X4C3TQSWZJC882ECQV2","performance-observability","Ditto SDK store observer performance and diagnostics (Flutter, JavaScript, Kotlin, Swift): observer lifecycle, backpressure (registerObserverV2, signalNext, suspending handlers), narrow UI updates, differs, redundant writes, indexes, ADVISE, EXPLAIN, PROFILE, logging, and system: collections. Use when a Ditto query is slow, a screen showing Ditto data janks, Ditto observers grow memory, Ditto upserts repeat, or when setting up Ditto logging.","https:\u002F\u002Fgithub.com\u002Fditto-examples\u002Fditto-cookbook\u002Fblob\u002Fmain\u002Fplugins\u002Fditto\u002Fskills\u002Fperformance-observability\u002FSKILL.md",[],[250,251,252],"performance","observability","performance observability"]