pi-cloudflare 0.10.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (293) hide show
  1. package/README.md +78 -177
  2. package/package.json +7 -42
  3. package/plugin.json +3 -3
  4. package/skills/agents-sdk/SKILL.md +17 -36
  5. package/skills/agents-sdk/references/client-sdk.md +7 -106
  6. package/skills/agents-sdk/references/human-in-the-loop.md +6 -63
  7. package/skills/agents-sdk/references/mcp.md +9 -184
  8. package/skills/agents-sdk/references/queue-retries.md +12 -73
  9. package/skills/agents-sdk/references/server-driven-messages.md +4 -60
  10. package/skills/agents-sdk/references/state-scheduling.md +10 -166
  11. package/skills/agents-sdk/references/streaming-chat.md +11 -193
  12. package/skills/agents-sdk/references/webhooks-push.md +2 -2
  13. package/skills/agents-sdk/references/workflows.md +14 -125
  14. package/skills/cloudflare/SKILL.md +135 -248
  15. package/skills/cloudflare/references/ai-gateway/README.md +17 -165
  16. package/skills/cloudflare/references/ai-gateway/configuration.md +14 -107
  17. package/skills/cloudflare/references/ai-gateway/dynamic-routing.md +12 -79
  18. package/skills/cloudflare/references/ai-gateway/features.md +22 -96
  19. package/skills/cloudflare/references/ai-gateway/sdk-integration.md +17 -112
  20. package/skills/cloudflare/references/ai-gateway/troubleshooting.md +14 -86
  21. package/skills/cloudflare/references/ai-search/README.md +17 -130
  22. package/skills/cloudflare/references/ai-search/api.md +10 -84
  23. package/skills/cloudflare/references/ai-search/configuration.md +16 -88
  24. package/skills/cloudflare/references/ai-search/gotchas.md +13 -81
  25. package/skills/cloudflare/references/ai-search/patterns.md +12 -82
  26. package/skills/cloudflare/references/analytics-engine/api.md +1 -1
  27. package/skills/cloudflare/references/api/README.md +2 -2
  28. package/skills/cloudflare/references/api/configuration.md +1 -1
  29. package/skills/cloudflare/references/bindings/README.md +11 -117
  30. package/skills/cloudflare/references/bindings/api.md +17 -201
  31. package/skills/cloudflare/references/bindings/configuration.md +20 -188
  32. package/skills/cloudflare/references/bindings/gotchas.md +16 -206
  33. package/skills/cloudflare/references/bindings/patterns.md +15 -195
  34. package/skills/cloudflare/references/bot-management/README.md +1 -1
  35. package/skills/cloudflare/references/browser-rendering/README.md +13 -73
  36. package/skills/cloudflare/references/browser-rendering/api.md +9 -105
  37. package/skills/cloudflare/references/browser-rendering/configuration.md +9 -75
  38. package/skills/cloudflare/references/browser-rendering/gotchas.md +12 -85
  39. package/skills/cloudflare/references/browser-rendering/patterns.md +9 -88
  40. package/skills/cloudflare/references/c3/README.md +6 -5
  41. package/skills/cloudflare/references/c3/api.md +3 -4
  42. package/skills/cloudflare/references/c3/patterns.md +4 -6
  43. package/skills/cloudflare/references/cache-reserve/README.md +1 -1
  44. package/skills/cloudflare/references/containers/README.md +15 -77
  45. package/skills/cloudflare/references/containers/api.md +13 -187
  46. package/skills/cloudflare/references/containers/configuration.md +15 -188
  47. package/skills/cloudflare/references/containers/gotchas.md +16 -178
  48. package/skills/cloudflare/references/containers/patterns.md +14 -198
  49. package/skills/cloudflare/references/cron-triggers/README.md +13 -92
  50. package/skills/cloudflare/references/cron-triggers/api.md +11 -191
  51. package/skills/cloudflare/references/cron-triggers/configuration.md +11 -175
  52. package/skills/cloudflare/references/cron-triggers/gotchas.md +13 -195
  53. package/skills/cloudflare/references/cron-triggers/patterns.md +12 -184
  54. package/skills/cloudflare/references/d1/README.md +9 -127
  55. package/skills/cloudflare/references/d1/api.md +16 -194
  56. package/skills/cloudflare/references/d1/configuration.md +16 -189
  57. package/skills/cloudflare/references/d1/gotchas.md +16 -96
  58. package/skills/cloudflare/references/d1/patterns.md +14 -183
  59. package/skills/cloudflare/references/do-storage/README.md +11 -70
  60. package/skills/cloudflare/references/do-storage/api.md +11 -99
  61. package/skills/cloudflare/references/do-storage/configuration.md +11 -107
  62. package/skills/cloudflare/references/do-storage/gotchas.md +12 -147
  63. package/skills/cloudflare/references/do-storage/patterns.md +11 -190
  64. package/skills/cloudflare/references/do-storage/testing.md +8 -178
  65. package/skills/cloudflare/references/email-routing/README.md +14 -84
  66. package/skills/cloudflare/references/email-routing/api.md +10 -192
  67. package/skills/cloudflare/references/email-routing/configuration.md +13 -186
  68. package/skills/cloudflare/references/email-routing/gotchas.md +12 -193
  69. package/skills/cloudflare/references/email-routing/patterns.md +10 -226
  70. package/skills/cloudflare/references/email-workers/README.md +13 -146
  71. package/skills/cloudflare/references/email-workers/api.md +12 -234
  72. package/skills/cloudflare/references/email-workers/configuration.md +14 -110
  73. package/skills/cloudflare/references/email-workers/gotchas.md +15 -125
  74. package/skills/cloudflare/references/email-workers/patterns.md +14 -100
  75. package/skills/cloudflare/references/flagship/README.md +2 -2
  76. package/skills/cloudflare/references/hyperdrive/README.md +17 -72
  77. package/skills/cloudflare/references/hyperdrive/api.md +19 -136
  78. package/skills/cloudflare/references/hyperdrive/configuration.md +27 -159
  79. package/skills/cloudflare/references/hyperdrive/gotchas.md +15 -72
  80. package/skills/cloudflare/references/hyperdrive/patterns.md +12 -187
  81. package/skills/cloudflare/references/images/README.md +9 -58
  82. package/skills/cloudflare/references/images/api.md +13 -96
  83. package/skills/cloudflare/references/images/configuration.md +17 -211
  84. package/skills/cloudflare/references/images/gotchas.md +16 -99
  85. package/skills/cloudflare/references/images/patterns.md +16 -115
  86. package/skills/cloudflare/references/kv/README.md +9 -83
  87. package/skills/cloudflare/references/kv/api.md +12 -154
  88. package/skills/cloudflare/references/kv/configuration.md +11 -139
  89. package/skills/cloudflare/references/kv/gotchas.md +15 -129
  90. package/skills/cloudflare/references/kv/patterns.md +15 -190
  91. package/skills/cloudflare/references/miniflare/README.md +15 -98
  92. package/skills/cloudflare/references/miniflare/api.md +16 -187
  93. package/skills/cloudflare/references/miniflare/configuration.md +12 -169
  94. package/skills/cloudflare/references/miniflare/gotchas.md +15 -160
  95. package/skills/cloudflare/references/miniflare/patterns.md +15 -177
  96. package/skills/cloudflare/references/network-interconnect/README.md +1 -1
  97. package/skills/cloudflare/references/network-interconnect/gotchas.md +1 -1
  98. package/skills/cloudflare/references/network-interconnect/patterns.md +1 -1
  99. package/skills/cloudflare/references/observability/README.md +20 -81
  100. package/skills/cloudflare/references/observability/api.md +20 -164
  101. package/skills/cloudflare/references/observability/configuration.md +18 -164
  102. package/skills/cloudflare/references/observability/gotchas.md +19 -109
  103. package/skills/cloudflare/references/observability/patterns.md +12 -103
  104. package/skills/cloudflare/references/pages/README.md +13 -81
  105. package/skills/cloudflare/references/pages/api.md +10 -201
  106. package/skills/cloudflare/references/pages/configuration.md +16 -201
  107. package/skills/cloudflare/references/pages/gotchas.md +13 -197
  108. package/skills/cloudflare/references/pages/patterns.md +11 -200
  109. package/skills/cloudflare/references/pages-functions/README.md +13 -91
  110. package/skills/cloudflare/references/pages-functions/api.md +10 -140
  111. package/skills/cloudflare/references/pages-functions/configuration.md +11 -119
  112. package/skills/cloudflare/references/pages-functions/gotchas.md +17 -94
  113. package/skills/cloudflare/references/pages-functions/patterns.md +12 -133
  114. package/skills/cloudflare/references/pipelines/README.md +1 -1
  115. package/skills/cloudflare/references/pulumi/README.md +2 -2
  116. package/skills/cloudflare/references/queues/README.md +15 -87
  117. package/skills/cloudflare/references/queues/api.md +10 -200
  118. package/skills/cloudflare/references/queues/configuration.md +18 -142
  119. package/skills/cloudflare/references/queues/gotchas.md +16 -204
  120. package/skills/cloudflare/references/queues/patterns.md +19 -218
  121. package/skills/cloudflare/references/r2/README.md +17 -86
  122. package/skills/cloudflare/references/r2/api.md +14 -198
  123. package/skills/cloudflare/references/r2/configuration.md +17 -163
  124. package/skills/cloudflare/references/r2/gotchas.md +15 -188
  125. package/skills/cloudflare/references/r2/patterns.md +16 -191
  126. package/skills/cloudflare/references/r2-data-catalog/README.md +11 -70
  127. package/skills/cloudflare/references/r2-data-catalog/api.md +14 -89
  128. package/skills/cloudflare/references/r2-data-catalog/configuration.md +15 -96
  129. package/skills/cloudflare/references/r2-data-catalog/gotchas.md +14 -51
  130. package/skills/cloudflare/references/r2-data-catalog/patterns.md +11 -116
  131. package/skills/cloudflare/references/realtime-sfu/README.md +1 -1
  132. package/skills/cloudflare/references/realtimekit/README.md +1 -1
  133. package/skills/cloudflare/references/secrets-store/README.md +14 -66
  134. package/skills/cloudflare/references/secrets-store/api.md +14 -193
  135. package/skills/cloudflare/references/secrets-store/configuration.md +16 -176
  136. package/skills/cloudflare/references/secrets-store/gotchas.md +14 -92
  137. package/skills/cloudflare/references/secrets-store/patterns.md +14 -194
  138. package/skills/cloudflare/references/smart-placement/README.md +2 -2
  139. package/skills/cloudflare/references/static-assets/README.md +15 -59
  140. package/skills/cloudflare/references/static-assets/api.md +12 -195
  141. package/skills/cloudflare/references/static-assets/configuration.md +16 -186
  142. package/skills/cloudflare/references/static-assets/gotchas.md +18 -162
  143. package/skills/cloudflare/references/static-assets/patterns.md +13 -185
  144. package/skills/cloudflare/references/stream/README.md +15 -107
  145. package/skills/cloudflare/references/stream/api-live.md +16 -193
  146. package/skills/cloudflare/references/stream/api.md +19 -197
  147. package/skills/cloudflare/references/stream/configuration.md +16 -139
  148. package/skills/cloudflare/references/stream/gotchas.md +16 -128
  149. package/skills/cloudflare/references/stream/patterns.md +20 -182
  150. package/skills/cloudflare/references/tail-workers/README.md +14 -82
  151. package/skills/cloudflare/references/tail-workers/api.md +10 -197
  152. package/skills/cloudflare/references/tail-workers/configuration.md +13 -174
  153. package/skills/cloudflare/references/tail-workers/gotchas.md +12 -188
  154. package/skills/cloudflare/references/tail-workers/patterns.md +11 -176
  155. package/skills/cloudflare/references/terraform/README.md +2 -2
  156. package/skills/cloudflare/references/tunnel/README.md +13 -122
  157. package/skills/cloudflare/references/tunnel/api.md +11 -190
  158. package/skills/cloudflare/references/tunnel/configuration.md +12 -155
  159. package/skills/cloudflare/references/tunnel/gotchas.md +12 -144
  160. package/skills/cloudflare/references/tunnel/networking.md +12 -166
  161. package/skills/cloudflare/references/tunnel/patterns.md +12 -189
  162. package/skills/cloudflare/references/vectorize/README.md +15 -126
  163. package/skills/cloudflare/references/vectorize/api.md +14 -84
  164. package/skills/cloudflare/references/vectorize/configuration.md +14 -83
  165. package/skills/cloudflare/references/vectorize/gotchas.md +12 -73
  166. package/skills/cloudflare/references/vectorize/patterns.md +17 -83
  167. package/skills/cloudflare/references/waf/README.md +15 -107
  168. package/skills/cloudflare/references/waf/api.md +17 -202
  169. package/skills/cloudflare/references/waf/configuration.md +14 -199
  170. package/skills/cloudflare/references/waf/gotchas.md +15 -200
  171. package/skills/cloudflare/references/waf/patterns.md +13 -193
  172. package/skills/cloudflare/references/workerd/README.md +2 -2
  173. package/skills/cloudflare/references/workers-ai/README.md +14 -187
  174. package/skills/cloudflare/references/workers-ai/api.md +10 -109
  175. package/skills/cloudflare/references/workers-ai/configuration.md +11 -92
  176. package/skills/cloudflare/references/workers-ai/gotchas.md +12 -111
  177. package/skills/cloudflare/references/workers-ai/patterns.md +9 -115
  178. package/skills/cloudflare/references/workers-for-platforms/README.md +3 -3
  179. package/skills/cloudflare/references/workers-vpc/README.md +1 -1
  180. package/skills/cloudflare/references/workflows/README.md +15 -69
  181. package/skills/cloudflare/references/workflows/api.md +12 -213
  182. package/skills/cloudflare/references/workflows/configuration.md +16 -150
  183. package/skills/cloudflare/references/workflows/gotchas.md +17 -88
  184. package/skills/cloudflare/references/workflows/patterns.md +19 -164
  185. package/skills/cloudflare-api-token/SKILL.md +1 -1
  186. package/skills/cloudflare-cf-cli/SKILL.md +44 -13
  187. package/skills/cloudflare-email-service/SKILL.md +6 -36
  188. package/skills/cloudflare-email-service/references/rest-api.md +12 -179
  189. package/skills/cloudflare-email-service/references/sending.md +17 -250
  190. package/skills/cloudflare-one/SKILL.md +4 -2
  191. package/skills/cloudflare-one-migrations/SKILL.md +1 -1
  192. package/skills/cloudflare-token-roll/SKILL.md +2 -5
  193. package/skills/durable-objects/SKILL.md +10 -16
  194. package/skills/durable-objects/references/rules.md +17 -293
  195. package/skills/durable-objects/references/testing.md +16 -257
  196. package/skills/nextjs-on-cloudflare/SKILL.md +33 -0
  197. package/skills/sandbox-migrate-to-next/SKILL.md +2 -2
  198. package/skills/sandbox-next/SKILL.md +3 -2
  199. package/skills/sandbox-next/references/api-quick-ref.md +15 -90
  200. package/skills/sandbox-stable/SKILL.md +1 -1
  201. package/skills/turnstile-spin/SKILL.md +14 -8
  202. package/skills/workers-best-practices/SKILL.md +36 -103
  203. package/skills/workers-best-practices/references/configuration.md +139 -0
  204. package/skills/workers-best-practices/references/platform-apis.md +51 -0
  205. package/skills/workers-best-practices/references/{rules.md → runtime-patterns.md} +9 -134
  206. package/skills/wrangler/SKILL.md +48 -901
  207. package/bin/setup.mjs +0 -119
  208. package/dist/api-token.d.ts +0 -12
  209. package/dist/api-token.d.ts.map +0 -1
  210. package/dist/api-token.js +0 -23
  211. package/dist/api-token.js.map +0 -1
  212. package/dist/auth-flow.d.ts +0 -15
  213. package/dist/auth-flow.d.ts.map +0 -1
  214. package/dist/auth-flow.js +0 -90
  215. package/dist/auth-flow.js.map +0 -1
  216. package/dist/client.d.ts +0 -18
  217. package/dist/client.d.ts.map +0 -1
  218. package/dist/client.js +0 -47
  219. package/dist/client.js.map +0 -1
  220. package/dist/config.d.ts +0 -20
  221. package/dist/config.d.ts.map +0 -1
  222. package/dist/config.js +0 -10
  223. package/dist/config.js.map +0 -1
  224. package/dist/index.d.ts +0 -22
  225. package/dist/index.d.ts.map +0 -1
  226. package/dist/index.js +0 -65
  227. package/dist/index.js.map +0 -1
  228. package/dist/mcp-server.d.ts +0 -2
  229. package/dist/mcp-server.d.ts.map +0 -1
  230. package/dist/mcp-server.js +0 -106
  231. package/dist/mcp-server.js.map +0 -1
  232. package/dist/oauth.d.ts +0 -44
  233. package/dist/oauth.d.ts.map +0 -1
  234. package/dist/oauth.js +0 -135
  235. package/dist/oauth.js.map +0 -1
  236. package/dist/proxy.d.ts +0 -30
  237. package/dist/proxy.d.ts.map +0 -1
  238. package/dist/proxy.js +0 -41
  239. package/dist/proxy.js.map +0 -1
  240. package/dist/result-caps.d.ts +0 -23
  241. package/dist/result-caps.d.ts.map +0 -1
  242. package/dist/result-caps.js +0 -75
  243. package/dist/result-caps.js.map +0 -1
  244. package/dist/runtime.d.ts +0 -72
  245. package/dist/runtime.d.ts.map +0 -1
  246. package/dist/runtime.js +0 -249
  247. package/dist/runtime.js.map +0 -1
  248. package/dist/servers.d.ts +0 -19
  249. package/dist/servers.d.ts.map +0 -1
  250. package/dist/servers.js +0 -40
  251. package/dist/servers.js.map +0 -1
  252. package/dist/token-store.d.ts +0 -32
  253. package/dist/token-store.d.ts.map +0 -1
  254. package/dist/token-store.js +0 -61
  255. package/dist/token-store.js.map +0 -1
  256. package/dist/tool-cache.d.ts +0 -25
  257. package/dist/tool-cache.d.ts.map +0 -1
  258. package/dist/tool-cache.js +0 -43
  259. package/dist/tool-cache.js.map +0 -1
  260. package/mcp.json +0 -15
  261. package/skills/cloudflare/references/agents-sdk/README.md +0 -89
  262. package/skills/cloudflare/references/agents-sdk/api.md +0 -190
  263. package/skills/cloudflare/references/agents-sdk/configuration.md +0 -182
  264. package/skills/cloudflare/references/agents-sdk/gotchas.md +0 -158
  265. package/skills/cloudflare/references/agents-sdk/patterns.md +0 -192
  266. package/skills/cloudflare/references/durable-objects/README.md +0 -185
  267. package/skills/cloudflare/references/durable-objects/api.md +0 -187
  268. package/skills/cloudflare/references/durable-objects/configuration.md +0 -160
  269. package/skills/cloudflare/references/durable-objects/gotchas.md +0 -197
  270. package/skills/cloudflare/references/durable-objects/patterns.md +0 -201
  271. package/skills/cloudflare/references/sandbox/README.md +0 -96
  272. package/skills/cloudflare/references/sandbox/api.md +0 -198
  273. package/skills/cloudflare/references/sandbox/configuration.md +0 -143
  274. package/skills/cloudflare/references/sandbox/gotchas.md +0 -194
  275. package/skills/cloudflare/references/sandbox/patterns.md +0 -201
  276. package/skills/cloudflare/references/turnstile/README.md +0 -99
  277. package/skills/cloudflare/references/turnstile/api.md +0 -240
  278. package/skills/cloudflare/references/turnstile/configuration.md +0 -222
  279. package/skills/cloudflare/references/turnstile/gotchas.md +0 -218
  280. package/skills/cloudflare/references/turnstile/patterns.md +0 -193
  281. package/skills/cloudflare/references/workers/README.md +0 -108
  282. package/skills/cloudflare/references/workers/api.md +0 -195
  283. package/skills/cloudflare/references/workers/configuration.md +0 -185
  284. package/skills/cloudflare/references/workers/frameworks.md +0 -197
  285. package/skills/cloudflare/references/workers/gotchas.md +0 -137
  286. package/skills/cloudflare/references/workers/patterns.md +0 -198
  287. package/skills/cloudflare/references/wrangler/README.md +0 -135
  288. package/skills/cloudflare/references/wrangler/api.md +0 -188
  289. package/skills/cloudflare/references/wrangler/configuration.md +0 -197
  290. package/skills/cloudflare/references/wrangler/gotchas.md +0 -197
  291. package/skills/cloudflare/references/wrangler/patterns.md +0 -209
  292. package/skills/cloudflare-auth-setup/SKILL.md +0 -59
  293. package/skills/workers-best-practices/references/review.md +0 -174
@@ -1,98 +1,18 @@
1
1
  # D1 Gotchas & Troubleshooting
2
2
 
3
- ## Common Errors
4
-
5
- ### "SQL Injection Vulnerability"
6
-
7
- **Cause:** Using string interpolation instead of prepared statements with bind()
8
- **Solution:** ALWAYS use prepared statements: `env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(userId).all()` instead of string interpolation which allows attackers to inject malicious SQL
9
-
10
- ### "no such table"
11
-
12
- **Cause:** Table doesn't exist because migrations haven't been run, or using wrong database binding
13
- **Solution:** Run migrations using `wrangler d1 migrations apply <db-name> --remote` and verify binding name in wrangler.jsonc matches code
14
-
15
- ### "UNIQUE constraint failed"
16
-
17
- **Cause:** Attempting to insert duplicate value in column with UNIQUE constraint
18
- **Solution:** Catch error and return 409 Conflict status code
19
-
20
- ### "Query Timeout (30s exceeded)"
21
-
22
- **Cause:** Query execution exceeds 30 second timeout limit
23
- **Solution:** Break into smaller queries, add indexes to speed up queries, or reduce dataset size
24
-
25
- ### "N+1 Query Problem"
26
-
27
- **Cause:** Making multiple individual queries in a loop instead of single optimized query
28
- **Solution:** Use JOIN to fetch related data in single query or use `batch()` method for multiple queries
29
-
30
- ### "Missing Indexes"
31
-
32
- **Cause:** Queries performing full table scans without indexes
33
- **Solution:** Use `EXPLAIN QUERY PLAN` to check if index is used, then create index with `CREATE INDEX idx_users_email ON users(email)`
34
-
35
- ### "Boolean Type Issues"
36
-
37
- **Cause:** SQLite uses INTEGER (0/1) not native boolean type
38
- **Solution:** Bind 1 or 0 instead of true/false when working with boolean values
39
-
40
- ### "Date/Time Type Issues"
41
-
42
- **Cause:** SQLite doesn't have native DATE/TIME types
43
- **Solution:** Use TEXT (ISO 8601 format) or INTEGER (unix timestamp) for date/time values
44
-
45
- ## Plan Tier Limits
46
-
47
- | Limit | Free Tier | Paid Plans | Notes |
48
- |-------|-----------|------------|-------|
49
- | Database size | 500 MB | 10 GB | Design for multiple DBs per tenant on paid |
50
- | Row size | 1 MB | 1 MB | Store large files in R2, not D1 |
51
- | Query timeout | 30s | 30s (900s with sessions) | Use sessions API for migrations |
52
- | Batch size | 1,000 statements | 10,000 statements | Split large batches accordingly |
53
- | Time Travel | 7 days | 30 days | Point-in-time recovery window |
54
- | Read replicas | ❌ Not available | ✅ Available | Paid add-on for lower latency |
55
- | Sessions API | ❌ Not available | ✅ Up to 15 min | For migrations and heavy operations |
56
- | Concurrent requests | 10,000/min | Higher | Contact support for custom limits |
57
-
58
- ## Production Gotchas
59
-
60
- ### "Batch size exceeded"
61
-
62
- **Cause:** Attempting to send >1,000 statements on free tier or >10,000 on paid
63
- **Solution:** Chunk batches: `for (let i = 0; i < stmts.length; i += MAX_BATCH) await env.DB.batch(stmts.slice(i, i + MAX_BATCH))`
64
-
65
- ### "Session not closed / resource leak"
66
-
67
- **Cause:** Forgot to call `session.close()` after using sessions API
68
- **Solution:** Always use try/finally block: `try { await session.prepare(...) } finally { session.close() }`
69
-
70
- ### "Replication lag causing stale reads"
71
-
72
- **Cause:** Reading from replica immediately after write - replication lag can be 100ms-2s
73
- **Solution:** Use primary for read-after-write: `await env.DB.prepare(...)` not `env.DB_REPLICA`
74
-
75
- ### "Migration applied to local but not remote"
76
-
77
- **Cause:** Forgot `--remote` flag when applying migrations
78
- **Solution:** Always run `wrangler d1 migrations apply <db-name> --remote` for production
79
-
80
- ### "Foreign key constraint failed"
81
-
82
- **Cause:** Inserting row with FK to non-existent parent, or deleting parent before children
83
- **Solution:** Enable FK enforcement: `PRAGMA foreign_keys = ON;` and use ON DELETE CASCADE in schema
84
-
85
- ### "BLOB data corrupted on export"
86
-
87
- **Cause:** D1 export may not handle BLOB correctly
88
- **Solution:** Store binary files in R2, only store R2 URLs/keys in D1
89
-
90
- ### "Database size approaching limit"
91
-
92
- **Cause:** Storing too much data in single database
93
- **Solution:** Horizontal scale-out: create per-tenant/per-user databases, archive old data, or upgrade to paid plan
94
-
95
- ### "Local dev vs production behavior differs"
96
-
97
- **Cause:** Local uses SQLite file, production uses distributed D1 - different performance/limits
98
- **Solution:** Always test migrations on remote with `--remote` flag before production rollout
3
+ Use current documentation to diagnose the failure before changing query or database configuration.
4
+
5
+ | Symptom or question | What to check |
6
+ | --- | --- |
7
+ | Missing table, query exception, or constraint error | [Debug D1](https://developers.cloudflare.com/d1/observability/debug-d1/); verify the target binding, environment, and applied [migrations](https://developers.cloudflare.com/d1/reference/migrations/) |
8
+ | Boolean, date, or other binding type mismatch | [Workers Binding API type conversion](https://developers.cloudflare.com/d1/worker-api/) and [SQL support](https://developers.cloudflare.com/d1/sql-api/sql-statements/) |
9
+ | Foreign key failure during writes or migrations | [Foreign key enforcement and deferral](https://developers.cloudflare.com/d1/sql-api/foreign-keys/) |
10
+ | Slow queries, scans, or excessive rows read | [Indexes and query plans](https://developers.cloudflare.com/d1/best-practices/use-indexes/) and [metrics](https://developers.cloudflare.com/d1/observability/metrics-analytics/) |
11
+ | Query duration, statement, storage, or account limits | [Current limits](https://developers.cloudflare.com/d1/platform/limits/) |
12
+ | Unexpected usage charges or plan assumptions | [Pricing](https://developers.cloudflare.com/d1/platform/pricing/) |
13
+ | Stale reads after a write | [Sessions, bookmarks, and read replication](https://developers.cloudflare.com/d1/best-practices/read-replication/) |
14
+ | Transient query failures | [Retry guidance](https://developers.cloudflare.com/d1/best-practices/retry-queries/); check idempotency before retrying writes |
15
+ | Import/export failure or unsupported data | [Import/export behavior and limitations](https://developers.cloudflare.com/d1/best-practices/import-export-data/) |
16
+ | Local and deployed databases differ | [Local development](https://developers.cloudflare.com/d1/best-practices/local-development/) and [environment configuration](https://developers.cloudflare.com/d1/configuration/environments/) |
17
+
18
+ Continue to bind untrusted SQL values as described in [api.md](./api.md). Do not treat SQL injection as a recoverable database error or assume retries correct invalid queries.
@@ -1,189 +1,20 @@
1
1
  # D1 Patterns & Best Practices
2
2
 
3
- ## Pagination
3
+ Use these guides to design the operation, then fetch [api.md](./api.md) for implementation references.
4
4
 
5
- ```typescript
6
- async function getUsers({ page, pageSize }: { page: number; pageSize: number }, env: Env) {
7
- const offset = (page - 1) * pageSize;
8
- const [countResult, dataResult] = await env.DB.batch([
9
- env.DB.prepare('SELECT COUNT(*) as total FROM users'),
10
- env.DB.prepare('SELECT * FROM users ORDER BY created_at DESC LIMIT ? OFFSET ?').bind(pageSize, offset)
11
- ]);
12
- return { data: dataResult.results, total: countResult.results[0].total, page, pageSize, totalPages: Math.ceil(countResult.results[0].total / pageSize) };
13
- }
14
- ```
5
+ | Task | Current documentation |
6
+ | --- | --- |
7
+ | Design pagination, filters, joins, and aggregations | [Query a database](https://developers.cloudflare.com/d1/best-practices/query-d1/) and [supported SQL](https://developers.cloudflare.com/d1/sql-api/sql-statements/) |
8
+ | Reduce scans and inspect query plans | [Use indexes](https://developers.cloudflare.com/d1/best-practices/use-indexes/) |
9
+ | Batch writes or transform data | [Database API](https://developers.cloudflare.com/d1/worker-api/d1-database/) and [limits](https://developers.cloudflare.com/d1/platform/limits/) |
10
+ | Store and query event metadata | [Query JSON](https://developers.cloudflare.com/d1/sql-api/query-json/) |
11
+ | Evaluate a cache in front of D1 | [How KV works](https://developers.cloudflare.com/kv/concepts/how-kv-works/) |
12
+ | Choose shared or per-tenant databases | [D1 FAQs](https://developers.cloudflare.com/d1/reference/faq/) and [limits](https://developers.cloudflare.com/d1/platform/limits/) |
13
+ | Reduce read latency while preserving required consistency | [Read replication](https://developers.cloudflare.com/d1/best-practices/read-replication/) |
14
+ | Plan point-in-time recovery or portable backups | [Time Travel](https://developers.cloudflare.com/d1/reference/time-travel/) and [import/export](https://developers.cloudflare.com/d1/best-practices/import-export-data/) |
15
15
 
16
- ## Conditional Queries
16
+ Keep result sets bounded and pagination ordering deterministic. Choose indexes from actual query plans. When splitting a large operation into batches, account for the loss of whole-operation atomicity across batches.
17
17
 
18
- ```typescript
19
- async function searchUsers(filters: { name?: string; email?: string; active?: boolean }, env: Env) {
20
- const conditions: string[] = [], params: (string | number | boolean | null)[] = [];
21
- if (filters.name) { conditions.push('name LIKE ?'); params.push(`%${filters.name}%`); }
22
- if (filters.email) { conditions.push('email = ?'); params.push(filters.email); }
23
- if (filters.active !== undefined) { conditions.push('active = ?'); params.push(filters.active ? 1 : 0); }
24
- const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
25
- return await env.DB.prepare(`SELECT * FROM users ${whereClause}`).bind(...params).all();
26
- }
27
- ```
18
+ Authorize a tenant before selecting its database or rows; a request header alone is not proof of tenant membership. Application login sessions stored in tables are separate from D1's Sessions API.
28
19
 
29
- ## Bulk Insert
30
-
31
- ```typescript
32
- async function bulkInsertUsers(users: Array<{ name: string; email: string }>, env: Env) {
33
- const stmt = env.DB.prepare('INSERT INTO users (name, email) VALUES (?, ?)');
34
- const batch = users.map(user => stmt.bind(user.name, user.email));
35
- return await env.DB.batch(batch);
36
- }
37
- ```
38
-
39
- ## Caching with KV
40
-
41
- ```typescript
42
- async function getCachedUser(userId: number, env: { DB: D1Database; CACHE: KVNamespace }) {
43
- const cacheKey = `user:${userId}`;
44
- const cached = await env.CACHE?.get(cacheKey, 'json');
45
- if (cached) return cached;
46
- const user = await env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(userId).first();
47
- if (user) await env.CACHE?.put(cacheKey, JSON.stringify(user), { expirationTtl: 300 });
48
- return user;
49
- }
50
- ```
51
-
52
- ## Query Optimization
53
-
54
- ```typescript
55
- // ✅ Use indexes in WHERE clauses
56
- const users = await env.DB.prepare('SELECT * FROM users WHERE email = ?').bind(email).all();
57
-
58
- // ✅ Limit result sets
59
- const recentPosts = await env.DB.prepare('SELECT * FROM posts ORDER BY created_at DESC LIMIT 100').all();
60
-
61
- // ✅ Use batch() for multiple independent queries
62
- const [user, posts, comments] = await env.DB.batch([
63
- env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(userId),
64
- env.DB.prepare('SELECT * FROM posts WHERE user_id = ?').bind(userId),
65
- env.DB.prepare('SELECT * FROM comments WHERE user_id = ?').bind(userId)
66
- ]);
67
-
68
- // ❌ Avoid N+1 queries
69
- for (const post of posts) {
70
- const author = await env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(post.user_id).first(); // Bad: multiple round trips
71
- }
72
-
73
- // ✅ Use JOINs instead
74
- const postsWithAuthors = await env.DB.prepare(`
75
- SELECT posts.*, users.name as author_name
76
- FROM posts
77
- JOIN users ON posts.user_id = users.id
78
- `).all();
79
- ```
80
-
81
- ## Multi-Tenant SaaS
82
-
83
- ```typescript
84
- // Each tenant gets own database
85
- export default {
86
- async fetch(request: Request, env: { [key: `TENANT_${string}`]: D1Database }) {
87
- const tenantId = request.headers.get('X-Tenant-ID');
88
- const data = await env[`TENANT_${tenantId}`].prepare('SELECT * FROM records').all();
89
- return Response.json(data.results);
90
- }
91
- }
92
- ```
93
-
94
- ## Session Storage
95
-
96
- ```typescript
97
- async function createSession(userId: number, token: string, env: Env) {
98
- const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString();
99
- return await env.DB.prepare('INSERT INTO sessions (user_id, token, expires_at) VALUES (?, ?, ?)').bind(userId, token, expiresAt).run();
100
- }
101
-
102
- async function validateSession(token: string, env: Env) {
103
- return await env.DB.prepare('SELECT s.*, u.email FROM sessions s JOIN users u ON s.user_id = u.id WHERE s.token = ? AND s.expires_at > CURRENT_TIMESTAMP').bind(token).first();
104
- }
105
- ```
106
-
107
- ## Analytics/Events
108
-
109
- ```typescript
110
- async function logEvent(event: { type: string; userId?: number; metadata: object }, env: Env) {
111
- return await env.DB.prepare('INSERT INTO events (type, user_id, metadata) VALUES (?, ?, ?)').bind(event.type, event.userId || null, JSON.stringify(event.metadata)).run();
112
- }
113
-
114
- async function getEventStats(startDate: string, endDate: string, env: Env) {
115
- return await env.DB.prepare('SELECT type, COUNT(*) as count FROM events WHERE timestamp BETWEEN ? AND ? GROUP BY type ORDER BY count DESC').bind(startDate, endDate).all();
116
- }
117
- ```
118
-
119
- ## Read Replication Pattern (Paid Plans)
120
-
121
- ```typescript
122
- interface Env { DB: D1Database; DB_REPLICA: D1Database; }
123
-
124
- export default {
125
- async fetch(request: Request, env: Env) {
126
- if (request.method === 'GET') {
127
- // Reads: use replica for lower latency
128
- const users = await env.DB_REPLICA.prepare('SELECT * FROM users WHERE active = 1').all();
129
- return Response.json(users.results);
130
- }
131
-
132
- if (request.method === 'POST') {
133
- const { name, email } = await request.json();
134
- const result = await env.DB.prepare('INSERT INTO users (name, email) VALUES (?, ?)').bind(name, email).run();
135
-
136
- // Read-after-write: use primary for consistency (replication lag <100ms-2s)
137
- const user = await env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(result.meta.last_row_id).first();
138
- return Response.json(user, { status: 201 });
139
- }
140
- }
141
- }
142
- ```
143
-
144
- **Use replicas for**: Analytics dashboards, search results, public queries (eventual consistency OK)
145
- **Use primary for**: Read-after-write, financial transactions, authentication (consistency required)
146
-
147
- ## Sessions API Pattern (Paid Plans)
148
-
149
- ```typescript
150
- // Migration with long-running session (up to 15 min)
151
- async function runMigration(env: Env) {
152
- const session = env.DB.withSession({ timeout: 600 }); // 10 min
153
- try {
154
- await session.prepare('CREATE INDEX idx_users_email ON users(email)').run();
155
- await session.prepare('CREATE INDEX idx_posts_user ON posts(user_id)').run();
156
- await session.prepare('ANALYZE').run();
157
- } finally {
158
- session.close(); // Always close to prevent leaks
159
- }
160
- }
161
-
162
- // Bulk transformation with batching
163
- async function transformLargeDataset(env: Env) {
164
- const session = env.DB.withSession({ timeout: 900 }); // 15 min max
165
- try {
166
- const BATCH_SIZE = 1000;
167
- let offset = 0;
168
- while (true) {
169
- const rows = await session.prepare('SELECT id, data FROM legacy LIMIT ? OFFSET ?').bind(BATCH_SIZE, offset).all();
170
- if (rows.results.length === 0) break;
171
- const updates = rows.results.map(row =>
172
- session.prepare('UPDATE legacy SET new_data = ? WHERE id = ?').bind(transform(row.data), row.id)
173
- );
174
- await session.batch(updates);
175
- offset += BATCH_SIZE;
176
- }
177
- } finally { session.close(); }
178
- }
179
- ```
180
-
181
- ## Time Travel & Backups
182
-
183
- ```bash
184
- wrangler d1 time-travel restore <db-name> --timestamp="2024-01-15T14:30:00Z" # Point-in-time
185
- wrangler d1 time-travel info <db-name> # List restore points (7 days free, 30 days paid)
186
- wrangler d1 export <db-name> --remote --output=./backup.sql # Full export
187
- wrangler d1 export <db-name> --remote --no-schema --output=./data.sql # Data only
188
- wrangler d1 execute <db-name> --remote --file=./backup.sql # Import
189
- ```
20
+ Before caching reads, decide how stale data may be and how writes invalidate cached results. For replicated reads, choose session constraints and bookmark propagation based on read-after-write requirements rather than assuming every read sees the latest primary state.
@@ -1,75 +1,16 @@
1
1
  # Cloudflare Durable Objects Storage
2
2
 
3
- Persistent storage API for Durable Objects with SQLite and KV backends, PITR, and automatic concurrency control.
3
+ Use SQLite for new classes. Existing KV-backed classes need their matching API reference; using key-value methods does not by itself identify the backend.
4
4
 
5
- ## Overview
5
+ Fetch the relevant current documentation before implementing or reviewing changes.
6
6
 
7
- DO Storage provides:
8
- - SQLite-backed (recommended) or KV-backed
9
- - SQL API + synchronous/async KV APIs
10
- - Automatic input/output gates (race-free)
11
- - 30-day point-in-time recovery (PITR)
12
- - Transactions and alarms
7
+ | Task | Documentation |
8
+ |------|---------------|
9
+ | Choose SQL, key-value access, transactions, or recovery APIs | [SQLite storage API](https://developers.cloudflare.com/durable-objects/api/sqlite-storage-api/); [Legacy KV storage API](https://developers.cloudflare.com/durable-objects/api/legacy-kv-storage-api/) |
10
+ | Configure the backend, class lifecycle, and placement | [Configuration](configuration.md) |
11
+ | Find operation semantics and storage options | [API routing](api.md) |
12
+ | Design schemas, caches, scheduled work, or cleanup | [Patterns](patterns.md) |
13
+ | Diagnose concurrency, limits, and billing | [Troubleshooting](gotchas.md) |
14
+ | Verify storage behavior in the Workers runtime | [Testing](testing.md) |
13
15
 
14
- **Use cases:** Stateful coordination, real-time collaboration, counters, sessions, rate limiters
15
-
16
- **Billing:** Charged by request, GB-month storage, and rowsRead/rowsWritten for SQL operations
17
-
18
- ## Quick Start
19
-
20
- ```typescript
21
- export class Counter extends DurableObject {
22
- sql: SqlStorage;
23
-
24
- constructor(ctx: DurableObjectState, env: Env) {
25
- super(ctx, env);
26
- this.sql = ctx.storage.sql;
27
- this.sql.exec('CREATE TABLE IF NOT EXISTS data(key TEXT PRIMARY KEY, value INTEGER)');
28
- }
29
-
30
- async increment(): Promise<number> {
31
- const result = this.sql.exec(
32
- 'INSERT INTO data VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = value + 1 RETURNING value',
33
- 'counter', 1
34
- ).one();
35
- return result?.value || 1;
36
- }
37
- }
38
- ```
39
-
40
- ## Storage Backends
41
-
42
- | Backend | Create Method | APIs | PITR |
43
- |---------|---------------|------|------|
44
- | SQLite (recommended) | `new_sqlite_classes` | SQL + sync KV + async KV | ✅ |
45
- | KV (legacy) | `new_classes` | async KV only | ❌ |
46
-
47
- ## Core APIs
48
-
49
- - **SQL API** (`ctx.storage.sql`): Full SQLite with extensions (FTS5, JSON, math)
50
- - **Sync KV** (`ctx.storage.kv`): Synchronous key-value (SQLite only)
51
- - **Async KV** (`ctx.storage`): Asynchronous key-value (both backends)
52
- - **Transactions** (`transactionSync()`, `transaction()`)
53
- - **PITR** (`getBookmarkForTime()`, `onNextSessionRestoreBookmark()`)
54
- - **Alarms** (`setAlarm()`, `alarm()` handler)
55
-
56
- ## Reading Order
57
-
58
- **New to DO storage:** configuration.md → api.md → patterns.md → gotchas.md
59
- **Building features:** patterns.md → api.md → gotchas.md
60
- **Debugging issues:** gotchas.md → api.md
61
- **Writing tests:** testing.md
62
-
63
- ## In This Reference
64
-
65
- - [configuration.md](./configuration.md) - wrangler.jsonc migrations, SQLite vs KV setup, RPC binding
66
- - [api.md](./api.md) - SQL exec/cursors, KV methods, storage options, transactions, alarms, PITR
67
- - [patterns.md](./patterns.md) - Schema migrations, caching, rate limiting, batch processing, parent-child coordination
68
- - [gotchas.md](./gotchas.md) - Concurrency gates, INTEGER precision, transaction rules, SQL limits
69
- - [testing.md](./testing.md) - vitest-pool-workers setup, testing DOs with SQL/alarms/PITR
70
-
71
- ## See Also
72
-
73
- - [durable-objects](../durable-objects/) - DO fundamentals and coordination patterns
74
- - [workers](../workers/) - Worker runtime for DO stubs
75
- - [d1](../d1/) - Shared database alternative to per-DO storage
16
+ For object routing, WebSockets, and coordination design, see the [Durable Objects skill](../../../durable-objects/SKILL.md).
@@ -1,102 +1,14 @@
1
- # DO Storage API Reference
1
+ # DO Storage API
2
2
 
3
- ## SQL API
3
+ Check the class’s backend before choosing operations; storage APIs and recovery capabilities differ.
4
4
 
5
- ```typescript
6
- const cursor = this.sql.exec('SELECT * FROM users WHERE email = ?', email);
7
- for (let row of cursor) {} // Objects: { id, name, email }
8
- cursor.toArray(); cursor.one(); // Single row (throws if != 1)
9
- for (let row of cursor.raw()) {} // Arrays: [1, "Alice", "..."]
5
+ Fetch the relevant current documentation before implementing or reviewing changes.
10
6
 
11
- // Manual iteration
12
- const iter = cursor[Symbol.iterator]();
13
- const first = iter.next(); // { value: {...}, done: false }
14
-
15
- cursor.columnNames; // ["id", "name", "email"]
16
- cursor.rowsRead; cursor.rowsWritten; // Billing
17
-
18
- type User = { id: number; name: string; email: string };
19
- const user = this.sql.exec<User>('...', userId).one();
20
- ```
21
-
22
- ## Sync KV API (SQLite only)
23
-
24
- ```typescript
25
- this.ctx.storage.kv.get("counter"); // undefined if missing
26
- this.ctx.storage.kv.put("counter", 42);
27
- this.ctx.storage.kv.put("user", { name: "Alice", age: 30 });
28
- this.ctx.storage.kv.delete("counter"); // true if existed
29
-
30
- for (let [key, value] of this.ctx.storage.kv.list()) {}
31
-
32
- // List options: start, prefix, reverse, limit
33
- this.ctx.storage.kv.list({ start: "user:", prefix: "user:", reverse: true, limit: 100 });
34
- ```
35
-
36
- ## Async KV API (Both backends)
37
-
38
- ```typescript
39
- await this.ctx.storage.get("key"); // Single
40
- await this.ctx.storage.get(["key1", "key2"]); // Multiple (max 128)
41
- await this.ctx.storage.put("key", value); // Single
42
- await this.ctx.storage.put({ "key1": "v1", "key2": { nested: true } }); // Multiple (max 128)
43
- await this.ctx.storage.delete("key");
44
- await this.ctx.storage.delete(["key1", "key2"]);
45
- await this.ctx.storage.list({ prefix: "user:", limit: 100 });
46
-
47
- // Options: allowConcurrency, noCache, allowUnconfirmed
48
- await this.ctx.storage.get("key", { allowConcurrency: true, noCache: true });
49
- await this.ctx.storage.put("key", value, { allowUnconfirmed: true, noCache: true });
50
- ```
51
-
52
- ### Storage Options
53
-
54
- | Option | Methods | Effect | Use Case |
55
- |--------|---------|--------|----------|
56
- | `allowConcurrency` | get, list | Skip input gate; allow concurrent requests during read | Read-heavy metrics that don't need strict consistency |
57
- | `noCache` | get, put, list | Skip in-memory cache; always read from disk | Rarely-accessed data or testing storage directly |
58
- | `allowUnconfirmed` | put, delete | Return before write confirms (still protected by output gate) | Non-critical writes where latency matters more than confirmation |
59
-
60
- ## Transactions
61
-
62
- ```typescript
63
- // Sync (SQL/sync KV only)
64
- this.ctx.storage.transactionSync(() => {
65
- this.sql.exec('UPDATE accounts SET balance = balance - ? WHERE id = ?', 100, 1);
66
- this.sql.exec('UPDATE accounts SET balance = balance + ? WHERE id = ?', 100, 2);
67
- return "result";
68
- });
69
-
70
- // Async
71
- await this.ctx.storage.transaction(async () => {
72
- const value = await this.ctx.storage.get("counter");
73
- await this.ctx.storage.put("counter", value + 1);
74
- if (value > 100) this.ctx.storage.rollback(); // Explicit rollback
75
- });
76
- ```
77
-
78
- ## Point-in-Time Recovery
79
-
80
- ```typescript
81
- await this.ctx.storage.getCurrentBookmark();
82
- await this.ctx.storage.getBookmarkForTime(Date.now() - 2 * 24 * 60 * 60 * 1000);
83
- await this.ctx.storage.onNextSessionRestoreBookmark(bookmark);
84
- this.ctx.abort(); // Restart to apply; bookmarks lexically comparable (earlier < later)
85
- ```
86
-
87
- ## Alarms
88
-
89
- ```typescript
90
- await this.ctx.storage.setAlarm(Date.now() + 60000); // Timestamp or Date
91
- await this.ctx.storage.getAlarm();
92
- await this.ctx.storage.deleteAlarm();
93
-
94
- async alarm() { await this.doScheduledWork(); }
95
- ```
96
-
97
- ## Misc
98
-
99
- ```typescript
100
- await this.ctx.storage.deleteAll(); // Atomic for SQLite; alarm NOT included
101
- this.ctx.storage.sql.databaseSize; // Bytes
102
- ```
7
+ | Task | Documentation |
8
+ |------|---------------|
9
+ | Use SQL cursors, bound parameters, supported SQL, or database size | [SQLite storage API](https://developers.cloudflare.com/durable-objects/api/sqlite-storage-api/) |
10
+ | Use synchronous or asynchronous key-value methods on SQLite | [SQLite storage API](https://developers.cloudflare.com/durable-objects/api/sqlite-storage-api/) |
11
+ | Maintain asynchronous KV operations on a legacy backend | [Legacy KV storage API](https://developers.cloudflare.com/durable-objects/api/legacy-kv-storage-api/) |
12
+ | Review transactions, write coalescing, storage options, or cleanup | [SQLite storage API](https://developers.cloudflare.com/durable-objects/api/sqlite-storage-api/); [Legacy KV storage API](https://developers.cloudflare.com/durable-objects/api/legacy-kv-storage-api/) |
13
+ | Create bookmarks or restore SQLite data | [SQLite storage API](https://developers.cloudflare.com/durable-objects/api/sqlite-storage-api/) |
14
+ | Schedule, inspect, or cancel an alarm | [Alarms](https://developers.cloudflare.com/durable-objects/api/alarms/) |
@@ -1,112 +1,16 @@
1
1
  # DO Storage Configuration
2
2
 
3
- ## SQLite-backed (Recommended)
3
+ Prefer SQLite for new classes. Inspect an existing class’s backend and lifecycle configuration before changing either.
4
4
 
5
- **wrangler.jsonc:**
6
- ```jsonc
7
- {
8
- "migrations": [
9
- {
10
- "tag": "v1",
11
- "new_sqlite_classes": ["Counter", "Session", "RateLimiter"]
12
- }
13
- ]
14
- }
15
- ```
5
+ Fetch the relevant current documentation before implementing or reviewing changes.
16
6
 
17
- **Migration lifecycle:** Migrations run once per deployment. Existing DO instances get new storage backend on next invocation. Renaming/removing classes requires `renamed_classes` or `deleted_classes` entries.
7
+ | Task | Documentation |
8
+ |------|---------------|
9
+ | Create a SQLite-backed class, binding, and generated types | [Getting started](https://developers.cloudflare.com/durable-objects/get-started/) |
10
+ | Choose storage and manage class exports | [Class exports](https://developers.cloudflare.com/durable-objects/reference/durable-objects-migrations/) |
11
+ | Maintain legacy migration configuration | [Legacy class migrations](https://developers.cloudflare.com/durable-objects/reference/durable-object-class-migrations-legacy/) |
12
+ | Initialize schemas or evolve application tables | [Rules of Durable Objects](https://developers.cloudflare.com/durable-objects/best-practices/rules-of-durable-objects/); [SQLite storage API](https://developers.cloudflare.com/durable-objects/api/sqlite-storage-api/) |
13
+ | Set placement hints or jurisdiction constraints | [Data location](https://developers.cloudflare.com/durable-objects/reference/data-location/) |
14
+ | Configure CPU allowances and check storage constraints | [Limits](https://developers.cloudflare.com/durable-objects/platform/limits/) |
18
15
 
19
- ## KV-backed (Legacy)
20
-
21
- **wrangler.jsonc:**
22
- ```jsonc
23
- {
24
- "migrations": [
25
- {
26
- "tag": "v1",
27
- "new_classes": ["OldCounter"]
28
- }
29
- ]
30
- }
31
- ```
32
-
33
- ## TypeScript Setup
34
-
35
- ```typescript
36
- export class MyDurableObject extends DurableObject {
37
- sql: SqlStorage;
38
-
39
- constructor(ctx: DurableObjectState, env: Env) {
40
- super(ctx, env);
41
- this.sql = ctx.storage.sql;
42
-
43
- // Initialize schema
44
- this.sql.exec(`
45
- CREATE TABLE IF NOT EXISTS users(
46
- id INTEGER PRIMARY KEY,
47
- name TEXT NOT NULL,
48
- email TEXT UNIQUE
49
- );
50
- `);
51
- }
52
- }
53
-
54
- // Binding
55
- interface Env {
56
- MY_DO: DurableObjectNamespace;
57
- }
58
-
59
- export default {
60
- async fetch(request: Request, env: Env): Promise<Response> {
61
- const id = env.MY_DO.idFromName('singleton');
62
- const stub = env.MY_DO.get(id);
63
-
64
- // Modern RPC: call methods directly (recommended)
65
- const result = await stub.someMethod();
66
- return Response.json(result);
67
-
68
- // Legacy: forward request (still works)
69
- // return stub.fetch(request);
70
- }
71
- }
72
- ```
73
-
74
- ## CPU Limits
75
-
76
- ```jsonc
77
- {
78
- "limits": {
79
- "cpu_ms": 300000 // 5 minutes (default 30s)
80
- }
81
- }
82
- ```
83
-
84
- ## Location Control
85
-
86
- ```typescript
87
- // Jurisdiction (GDPR/FedRAMP)
88
- const euNamespace = env.MY_DO.jurisdiction("eu");
89
- const id = euNamespace.newUniqueId();
90
- const stub = euNamespace.get(id);
91
-
92
- // Location hint (best effort)
93
- const stub = env.MY_DO.get(id, { locationHint: "enam" });
94
- // Hints: wnam, enam, sam, weur, eeur, apac, oc, afr, me
95
- ```
96
-
97
- ## Initialization
98
-
99
- ```typescript
100
- export class Counter extends DurableObject {
101
- value: number;
102
-
103
- constructor(ctx: DurableObjectState, env: Env) {
104
- super(ctx, env);
105
-
106
- // Block concurrent requests during init
107
- ctx.blockConcurrencyWhile(async () => {
108
- this.value = (await ctx.storage.get("value")) || 0;
109
- });
110
- }
111
- }
112
- ```
16
+ A class configuration change is not an application-data migration. Check the documented backend transition constraints in [Class exports](https://developers.cloudflare.com/durable-objects/reference/durable-objects-migrations/) before planning a backend change.