@somewhere-cloud/cli 0.38.154 → 0.38.155

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 (142) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/docs/adopt.md +39 -0
  3. package/dist/docs/analytics.md +161 -0
  4. package/dist/docs/api-reference.md +339 -0
  5. package/dist/docs/api-surface.md +2067 -0
  6. package/dist/docs/app-mcp.md +162 -0
  7. package/dist/docs/architecture-patterns.md +334 -0
  8. package/dist/docs/auth-client.md +531 -0
  9. package/dist/docs/billing.md +76 -0
  10. package/dist/docs/browser.md +639 -0
  11. package/dist/docs/calendar.md +298 -0
  12. package/dist/docs/changes.md +323 -0
  13. package/dist/docs/cli.md +407 -0
  14. package/dist/docs/common-mistakes.md +199 -0
  15. package/dist/docs/connect-agent.md +72 -0
  16. package/dist/docs/cors.md +114 -0
  17. package/dist/docs/cron.md +167 -0
  18. package/dist/docs/database-engine.md +167 -0
  19. package/dist/docs/declared-data.md +1656 -0
  20. package/dist/docs/declared-files.md +475 -0
  21. package/dist/docs/deploy-intelligence.md +188 -0
  22. package/dist/docs/deploy.md +733 -0
  23. package/dist/docs/design-system.md +273 -0
  24. package/dist/docs/dev-environments.md +496 -0
  25. package/dist/docs/domain-ownership.md +31 -0
  26. package/dist/docs/domains.md +370 -0
  27. package/dist/docs/feedback.md +88 -0
  28. package/dist/docs/file-tools.md +116 -0
  29. package/dist/docs/functions.md +489 -0
  30. package/dist/docs/getting-started.md +238 -0
  31. package/dist/docs/github.md +95 -0
  32. package/dist/docs/google-calendar.md +212 -0
  33. package/dist/docs/groups.md +836 -0
  34. package/dist/docs/guarantees.md +58 -0
  35. package/dist/docs/handled-for-you.md +224 -0
  36. package/dist/docs/inspect.md +171 -0
  37. package/dist/docs/limits.md +68 -0
  38. package/dist/docs/live-data.md +197 -0
  39. package/dist/docs/live.md +92 -0
  40. package/dist/docs/local-dev.md +30 -0
  41. package/dist/docs/migration-supabase.md +58 -0
  42. package/dist/docs/payments.md +1102 -0
  43. package/dist/docs/portability.md +194 -0
  44. package/dist/docs/postgres.md +301 -0
  45. package/dist/docs/pricing-comparison.md +42 -0
  46. package/dist/docs/pricing.md +39 -0
  47. package/dist/docs/project-groups.md +107 -0
  48. package/dist/docs/projects.md +380 -0
  49. package/dist/docs/recipe-ai-agent.md +112 -0
  50. package/dist/docs/recipe-ai-features.md +227 -0
  51. package/dist/docs/recipe-ai-receipts.md +783 -0
  52. package/dist/docs/recipe-background-jobs.md +369 -0
  53. package/dist/docs/recipe-booking.md +348 -0
  54. package/dist/docs/recipe-csv-import.md +390 -0
  55. package/dist/docs/recipe-ecommerce.md +127 -0
  56. package/dist/docs/recipe-email.md +282 -0
  57. package/dist/docs/recipe-escalation.md +133 -0
  58. package/dist/docs/recipe-file-uploads.md +159 -0
  59. package/dist/docs/recipe-import-app.md +110 -0
  60. package/dist/docs/recipe-login.md +457 -0
  61. package/dist/docs/recipe-multi-chat.md +198 -0
  62. package/dist/docs/recipe-paid-api.md +161 -0
  63. package/dist/docs/recipe-pdfs.md +205 -0
  64. package/dist/docs/recipe-push-notifications.md +107 -0
  65. package/dist/docs/recipe-seo.md +200 -0
  66. package/dist/docs/recipe-signed-in-app.md +330 -0
  67. package/dist/docs/render.md +99 -0
  68. package/dist/docs/rooms.md +554 -0
  69. package/dist/docs/sdk.md +287 -0
  70. package/dist/docs/sdks.md +24 -0
  71. package/dist/docs/search.md +199 -0
  72. package/dist/docs/security-model.md +168 -0
  73. package/dist/docs/setup.md +212 -0
  74. package/dist/docs/smoke.md +102 -0
  75. package/dist/docs/speed.md +298 -0
  76. package/dist/docs/sql-compatibility.md +96 -0
  77. package/dist/docs/sw.agent.md +248 -0
  78. package/dist/docs/sw.ai.md +1291 -0
  79. package/dist/docs/sw.auth.md +1811 -0
  80. package/dist/docs/sw.billing.md +171 -0
  81. package/dist/docs/sw.db.md +2128 -0
  82. package/dist/docs/sw.email.md +661 -0
  83. package/dist/docs/sw.endpoint.md +187 -0
  84. package/dist/docs/sw.env.md +303 -0
  85. package/dist/docs/sw.fetch.md +115 -0
  86. package/dist/docs/sw.fs.md +424 -0
  87. package/dist/docs/sw.groups.md +836 -0
  88. package/dist/docs/sw.image.md +69 -0
  89. package/dist/docs/sw.jobs.md +520 -0
  90. package/dist/docs/sw.logs.md +61 -0
  91. package/dist/docs/sw.mail.md +106 -0
  92. package/dist/docs/sw.notifications.md +78 -0
  93. package/dist/docs/sw.push.md +161 -0
  94. package/dist/docs/sw.rateLimit.md +67 -0
  95. package/dist/docs/sw.web.md +128 -0
  96. package/dist/docs/tasks.md +269 -0
  97. package/dist/docs/test.md +220 -0
  98. package/dist/docs/tool-reference-account.md +7 -0
  99. package/dist/docs/tool-reference-ai.md +121 -0
  100. package/dist/docs/tool-reference-analytics.md +37 -0
  101. package/dist/docs/tool-reference-api.md +19 -0
  102. package/dist/docs/tool-reference-artifacts.md +35 -0
  103. package/dist/docs/tool-reference-auth.md +163 -0
  104. package/dist/docs/tool-reference-browser.md +114 -0
  105. package/dist/docs/tool-reference-code.md +26 -0
  106. package/dist/docs/tool-reference-connect.md +21 -0
  107. package/dist/docs/tool-reference-cron.md +48 -0
  108. package/dist/docs/tool-reference-db.md +282 -0
  109. package/dist/docs/tool-reference-domains.md +107 -0
  110. package/dist/docs/tool-reference-email.md +55 -0
  111. package/dist/docs/tool-reference-env.md +19 -0
  112. package/dist/docs/tool-reference-feedback.md +56 -0
  113. package/dist/docs/tool-reference-fs.md +265 -0
  114. package/dist/docs/tool-reference-github.md +57 -0
  115. package/dist/docs/tool-reference-groups.md +85 -0
  116. package/dist/docs/tool-reference-help.md +29 -0
  117. package/dist/docs/tool-reference-jobs.md +39 -0
  118. package/dist/docs/tool-reference-live.md +48 -0
  119. package/dist/docs/tool-reference-logs.md +16 -0
  120. package/dist/docs/tool-reference-payments.md +44 -0
  121. package/dist/docs/tool-reference-project.md +706 -0
  122. package/dist/docs/tool-reference-push.md +78 -0
  123. package/dist/docs/tool-reference-rate-limit.md +18 -0
  124. package/dist/docs/tool-reference-search.md +68 -0
  125. package/dist/docs/tool-reference-security.md +42 -0
  126. package/dist/docs/tool-reference-smoke.md +17 -0
  127. package/dist/docs/tool-reference-stock-photos.md +20 -0
  128. package/dist/docs/tool-reference-tasks.md +73 -0
  129. package/dist/docs/tool-reference-telegram.md +32 -0
  130. package/dist/docs/tool-reference-usage.md +9 -0
  131. package/dist/docs/tool-reference-web.md +71 -0
  132. package/dist/docs/tool-reference-webhooks.md +9 -0
  133. package/dist/docs/troubleshooting.md +411 -0
  134. package/dist/docs/typed-functions.md +94 -0
  135. package/dist/docs/verify-before-deploy.md +67 -0
  136. package/dist/docs/vs-supabase.md +75 -0
  137. package/dist/docs/vs-vercel.md +103 -0
  138. package/dist/lib/bundle.js +303 -221
  139. package/dist/lib/bundle.js.map +3 -3
  140. package/dist/types/lib/test-session.d.ts +8 -0
  141. package/npm-shrinkwrap.json +2 -2
  142. package/package.json +3 -2
@@ -0,0 +1,2128 @@
1
+ # sw.db — Database (inside deployed functions)
2
+
3
+ For teams with verified email invitations, use built-in groups
4
+ (`somewhere docs sw.groups --section team-example`). Without verification, use
5
+ an app-managed roster (`somewhere docs declared-data --section teams-without-email-verification`).
6
+ Server query shapes: from(table, { where, order, limit, offset, columns }),
7
+ insert(table, values), update(table, { where, set }), remove(table, { where });
8
+ tx takes an array of write intents. where supports { id: { in: ids } }.
9
+
10
+ Available inside any deployed function via the `sw` argument.
11
+
12
+ sw.db uses the function's project binding — no developer API key or
13
+ application-level HTTP call. Each project's data is isolated.
14
+ End-to-end time can still include first-use activation, placement, transport,
15
+ database scheduling, and engine execution. Use sw.db inside functions; the
16
+ REST surface is for code running outside the platform.
17
+
18
+ Read first: the normal data path — declare a table, use the generated client, and the same table in a function — is `declared-data` → `data`.
19
+
20
+ ## Start with declared tables
21
+
22
+ Application tables are declared in db/schema.ts. sw.db.from reads them with caller-scoped access, and sw.db.server.from reads them once the caller is authorized for server access. The corresponding structured methods, such as sw.db.server.insert, change them. Raw query and batch go to the separate raw SQL database on current projects.
23
+
24
+ New projects define tables in `db/schema.ts` and deploy raw source. Pages
25
+ read and write those tables through the generated `somewhere:data` client, with
26
+ no function (`docs({ topic: 'declared-data', section: 'declare-a-table-and-use-it' })`).
27
+ Public enquiries to a published profile use declared `client.intake`
28
+ (`docs({ topic: 'declared-data', section: 'send-an-enquiry-to-a-public-profile' })`).
29
+ Booking and help-desk access: read `provider-or-booker-and-owner-or-staff-recipes`
30
+ below before choosing server-only tables; it opens with the three shapes a
31
+ table can take, and a function on a declared table reads with the caller's
32
+ rule, so it keeps its validation and loses its access checks. Sharing your
33
+ own rows with specific people (read-only sharing, co-authors):
34
+ `anyOf(owner(), grant(...))`. That change widens every existing caller-scoped
35
+ read. Keep an owner-only read scoped with `where: { user_id: me.id }` in your
36
+ function after resolving the signed-in user. See
37
+ `docs({ topic: 'declared-data', section: 'per-owner-sharing' })` for the deploy
38
+ warning.
39
+
40
+ Keep `owner()`/`member()`/`group()` and the generated client when one operation needs
41
+ a function. Use `sw.db.server` only for that authorized exceptional write,
42
+ or add a function for a side effect (`recipe-signed-in-app`).
43
+ Do not mark data people read or change through your app serverOnly() and
44
+ hand-write its access checks. Declare who may read and write it; the platform
45
+ enforces that for you.
46
+
47
+ Server-only is right for:
48
+ - Tables only server code touches: job state, import staging, audit records, counters.
49
+ - Membership/grant ledgers: never grant browser writes. grant() ledgers retain the
50
+ owner() scope required by that policy, with no client write grants.
51
+ - A rule the declarations cannot express; keep other operations declared:
52
+ - Arbitrary predicates (such as checking the current time): use a checked endpoint.
53
+ - Different writable fields by role on one table: split tables or check that write.
54
+ Server-assigned roles and role-filtered member() operations are declarable; they
55
+ are not reasons to make app data server-only.
56
+
57
+ An unverified email suffix is not a declared identity rule; use verified identity
58
+ or trusted role assignment, not server-only tables for the whole app.
59
+
60
+ Only when every operation needs a rule no declaration can express, use the fallback:
61
+ `docs({ topic: 'architecture-patterns', section: 'minimal-server-only-app' })`.
62
+
63
+ ```ts
64
+ const { data: [note] } = await sw.db.insert('notes', { title: 'Hello' });
65
+ if (typeof note?.id !== 'string') throw new Error('Expected the new note to have a text ID.');
66
+ const { data: rows } = await sw.db.from('notes', { limit: 20 });
67
+ const { data: count } = await sw.db.count('notes');
68
+ await sw.db.update('notes', { where: { id: note.id }, set: { title: 'Updated' } });
69
+ ```
70
+
71
+ These calls apply the caller's declared row permissions. For a serverOnly()
72
+ table or authorized cross-user work, use `sw.db.server.insert/from/count/update`
73
+ with the same argument shapes. Server calls bypass row permissions; authorize
74
+ private operations yourself. Raw `sw.db.query` never reaches declared tables
75
+ and runs unscoped: authorize first.
76
+
77
+ ## Server read paging
78
+
79
+ sw.db.from and sw.db.server.from accept { where, columns, order, limit, offset,
80
+ include, has }. limit and offset are non-negative integers; null/omitted means
81
+ unset. Server reads have no browser-style after cursor and no 100-row cap.
82
+ Use a deterministic order (including a unique key), advance offset by the rows
83
+ received, and stop when data.length is less than the page size. Concurrent writes
84
+ can shift offsets; for a stable traversal of an increasing key, filter on that
85
+ key instead. The result count describes the returned rows, not the total;
86
+ use count(table, { where }) for a separate total. Authorize before server reads.
87
+
88
+ ```ts
89
+ async function readServerPage(sw: SomewhereRuntimeContext, offset: number) {
90
+ return sw.db.server.from('notes', {
91
+ columns: ['id', 'title'], order: [['id', 'asc']], limit: 100, offset,
92
+ });
93
+ }
94
+ ```
95
+
96
+ ## Start with the schema file — db/schema.ts
97
+
98
+ Declare your tables in one file, `db/schema.ts`, deployed with the rest of
99
+ your source. On every live deploy the platform reads the file (it is a
100
+ declaration the platform reads — never code that runs), compares it with the
101
+ real database, creates whatever is missing, and records each table's access
102
+ scope in the same step. No migration calls, no separate scope declarations,
103
+ no schema SQL.
104
+
105
+ **On a new project, deploy the file before you test the database.** A
106
+ managed schema changes only with a release: `somewhere deploy` applies
107
+ `db/schema.ts` to production, and a preview release applies it to the
108
+ preview's isolated copy, with the same planner and safety rules. Additive
109
+ changes apply. A deployed table is removed with its `removedTable()` marker
110
+ (below); deleting its declaration without the marker, or removing or renaming
111
+ a column, is refused on production (explore it on a preview). A later deploy with the same file is a
112
+ no-op. There
113
+ is no separate schema-apply command. Until a deploy runs,
114
+ `sw.db.from('your_table')` fails with `TABLE_INTENT_REQUIRED` because a file
115
+ on disk cannot declare the table to the platform by itself.
116
+
117
+ The file is parsed as a declaration, not executed: use literal values and
118
+ supported declaration helpers. Imports from `somewhere/db` are recommended
119
+ for editor tooling, but the schema reader does not resolve imports. A missing
120
+ `owner` import alone does not invalidate an otherwise valid declaration.
121
+ Trailing commas are accepted, inside option objects and after the final
122
+ argument of a call. Top-level `const NAME = …;` declarations between the
123
+ imports and `export default schema(…)` are accepted and expanded in place,
124
+ never evaluated: a constant may hold any part of the declaration (an access
125
+ rule, a column, a column group, table options, a whole table), later code
126
+ refers to it by name, and an object-literal constant may be spread inside an
127
+ object literal (`...sharedColumns`). Anything else — `let`/`var`,
128
+ computed values, calls to anything but the schema helpers, a spread of a
129
+ non-object constant, a reference to a constant declared below — is refused
130
+ with the construct and its line named.
131
+
132
+ ```ts
133
+ // db/schema.ts
134
+ import { schema, table, id, text, integer, boolean, timestamp, json, owner, member, shared, serverOnly } from 'somewhere/db';
135
+
136
+ export default schema({
137
+ todos: table({
138
+ id: id(), // random text key (id({ uuid: false }) for an integer key)
139
+ title: text(), // required by default
140
+ done: boolean({ default: false }),
141
+ created_at: timestamp({ default: 'now' }), // stamped on insert
142
+ meta: json({ nullable: true }),
143
+ }, {
144
+ scope: owner(), // per-user rows; owner column is platform-managed
145
+ indexes: [['done']],
146
+ }),
147
+ org_invites: table({
148
+ id: id(), org_id: integer(), email: text(),
149
+ }, {
150
+ scope: serverOnly(),
151
+ unique: [['org_id', 'email']], // composite uniqueness (junction-table idiom)
152
+ }),
153
+ catalog: table({ id: id(), name: text() }, { scope: shared() }),
154
+ });
155
+ ```
156
+
157
+ Table and column names start with a letter and use letters, digits and
158
+ underscores. Reserved prefixes ignore case:
159
+ `app_`, `sqlite_`, `d1_`, and any leading `_` (including `__sw_`)
160
+ are reserved. Use `customer_user_id` for an app user reference.
161
+
162
+ Column types: `id`, `text`, `number`, `integer`, `boolean`, `timestamp`,
163
+ `json`, `blob`. Columns are required unless `nullable: true`. Defaults
164
+ are literals or `timestamp({ default: 'now' })`. Columns also accept
165
+ `unique` and `references: 'other_table'` with `onDelete: 'cascade' | 'restrict'`.
166
+ The database applies foreign-key actions to `sw.db.server.remove` and
167
+ `remove` intents in `sw.db.server.tx` too.
168
+
169
+ Table options include required `scope`, `indexes` and `unique`. Indexes
170
+ and unique groups are lists of column lists. A one-column unique group on
171
+ a non-key column is equivalent to `unique: true`. The platform manages the
172
+ owner column and refuses standalone uniqueness on it. For one row per user,
173
+ use `kind: text({ default: 'profile' })` with `unique: [['user_id', 'kind']]`.
174
+ Keep `kind` out of browser writes and omit it in functions to use the default.
175
+ Use `unique: [['user_id', 'key']]` for one row per user and key. Schema values
176
+ must be literals or references to earlier top-level constants. A deploy error
177
+ names the unsupported construct and its line.
178
+
179
+ Choose a scope for each table:
180
+
181
+ - `owner()` — per-user rows. The platform creates and manages the owner
182
+ column (`user_id` by default; `owner({ column: 'other_name' })` names
183
+ it differently at creation), sets it on insert, and scopes every structured
184
+ query to the request's VERIFIED SIGNED-IN USER. A request without a signed-in
185
+ user is refused before transport: `AUTH_REQUIRED` (401). Send the request
186
+ signed in — a session cookie or `Authorization: Bearer <app-user token>`.
187
+ For signed-out ownership, explicitly declare `owner({ visitors: true })`;
188
+ the platform can then use a verified visitor cookie. This is per browser,
189
+ not protection against someone discarding their cookie. For an intentional
190
+ cross-user operation, authorize the caller in your function before using
191
+ `sw.db.server`; it is not a remedy for a missing user session. In a
192
+ function, caller-scoped `sw.db.insert` stamps the owner column from the
193
+ request's signed-in user and refuses it in `values`
194
+ (`OWNER_COLUMN_NOT_ASSIGNABLE`); it may set any other declared column,
195
+ since `client.create` limits only the browser's generated client.
196
+ `sw.db.server.insert` never stamps an owner: the row holds exactly the
197
+ columns you pass, so name the owner in the owner column yourself (the
198
+ column is required on a table born with `owner()`).
199
+ - `shared()` — cross-user rows with a recorded author. Structured calls need
200
+ a verified app user: reads return every row to any signed-in user, writes
201
+ stamp the platform's managed author column (`_sw_author_id`, added on
202
+ deploy) with the caller. Browser reads through `somewhere:data` or
203
+ `/__sw/data` never return it, even with `read: true`; `sw.db` reads
204
+ and writes in your functions do, so leave it out of a function's response
205
+ when readers should not see who wrote each row. A request with no signed-in
206
+ user is refused `401 AUTH_REQUIRED` ("Shared tables require a signed-in user."). For
207
+ anonymous browser reads declare `client: { read: ['id', 'title'], publicRead: true }`.
208
+ Anonymous results can be cached for up to 120
209
+ seconds. For fresh pages, read published rows and only public fields with
210
+ `sw.db.server.from` in a page handler returning `Cache-Control: no-store`.
211
+ For a trusted server read pass `{ asServer: true }`. Use
212
+ `sw.db.server.insert` for app-owned rows: omit `_sw_author_id` or set it
213
+ to `null`. Supply a verified user's ID to attribute a server-created row
214
+ to that user. Rows without an author remain readable under the table's read
215
+ rules; ordinary caller writes cannot change or delete them.
216
+ - `serverOnly()` — trusted server and developer access only; direct
217
+ app-user access is rejected.
218
+ - `member()` — per-group rows, shared through a membership table. Declare
219
+ `member({ group, membership, member_user, member_group })`: `group` is the
220
+ group-key column(s) on this table, `membership` names a sibling managed
221
+ table that lists who belongs to which group, `member_user` is that table's
222
+ user column, and `member_group` is its matching group-key column(s). A group
223
+ key can be a single column or a same-arity list (a composite or polymorphic
224
+ key). The platform scopes every structured query to the groups the signed-in
225
+ user belongs to; an `insert` lands only if the user belongs to the group the
226
+ row names, otherwise `403 MEMBERSHIP_REQUIRED` (`403 POLICY_AUTHORITY_REQUIRED`
227
+ when `member()` is inside `anyOf()` or `allOf()`). A request without a signed-in
228
+ user is refused with `401 AUTH_REQUIRED`. Declare both the scoped table
229
+ and its membership table.
230
+
231
+ What happens on deploy:
232
+
233
+ - **First deploy** creates tables and enables access rules together.
234
+ The deploy response's `warnings` list what was created.
235
+ - **Additive changes apply**: a new table, a new nullable-or-defaulted
236
+ column, a new index, a new unique group. Unchanged schema is a no-op.
237
+ - **Unmarked removals and shape changes refuse** with `409
238
+ SCHEMA_DEPLOY_REFUSED` and a message naming the change.
239
+ - **Access-rule changes apply in place**: a later deploy can change an
240
+ existing table's scope, and its rows stay. "Two worlds" below lists what
241
+ the deploy reports and what it still refuses.
242
+ - **Removing a table** is `old_table: removedTable()`. The deploy keeps the
243
+ table while your previous version is still serving; once the new version is
244
+ live it retires the table and keeps its data for 30 days. The deploy
245
+ response's `warnings` name the table and the date its data is deleted, and
246
+ `somewhere deploy --dry-run` and `somewhere deploy-check` show the same
247
+ line first. To restore it within the 30 days, declare the table again with
248
+ the same scope and deploy — it comes back with its data. Leave the marker in
249
+ the file; it is a no-op once the table is gone.
250
+ Delete a never-deployed starter table's declaration and references.
251
+ A `removedTable()` marker for it is a no-op.
252
+ - **Column removals and renames do not apply to a live database**:
253
+ `removed()` and `renamedFrom` are accepted by the schema file and can be
254
+ explored on a preview copy, but a production deploy or a promotion that
255
+ would remove or rename a column is refused before anything changes, so a
256
+ running release never loses a column it uses. Keep the column declared and
257
+ leave its data in place. Your data download and export are unaffected.
258
+ - **Leaving schema management** is `old_table: exported()`: the declaration
259
+ is removed and the table + data stay untouched (structured queries on it then
260
+ need a declared scope again).
261
+ - Declaring a table that **already exists** brings it under schema management
262
+ (**adoption**) when the declared entry matches the live table and the table
263
+ is eligible — a base table, no triggers, and (for `owner()`) the owner
264
+ column present. A clean match applies zero DDL, arms scoping, and locks the
265
+ table to the file; an ineligible or mismatched declaration is refused with the
266
+ reason. Use `db_import` to generate the matching entry from a table you
267
+ already have, review it, and deploy. Tables not named in the file are
268
+ untouched.
269
+ - A `db/schema.ts` that isn't a somewhere schema declaration (another
270
+ tool's file) deploys as plain source with a warning, as long as the
271
+ project has no managed tables.
272
+ - A preview release applies managed `db/schema.ts` to the preview's own
273
+ isolated copy; a production deploy applies it to production. Both use the
274
+ same planner. For raw SQL, see the preview database limits below.
275
+
276
+ Run `somewhere typecheck` before deploying schema changes.
277
+
278
+ ## Browser list limits
279
+
280
+ The schema-generated browser client accepts `list({ limit: 100, after: page.next })`:
281
+ limit is 1–100; continue while `page.has_more`. There is no `order` option.
282
+ Sort the returned rows in the client, or use a server endpoint for ordered queries.
283
+ Include the primary key in `client.read`.
284
+
285
+ ## Update shape
286
+
287
+ `await sw.db.update('notes', { where: { id }, set: { title } })` takes two
288
+ arguments. `sw.db.server.update` uses the same shape after server authorization.
289
+
290
+ ## Transaction intents
291
+
292
+ `await sw.db.server.tx([{ op: 'insert', table: 'notes', values }])` takes an
293
+ array of write intents, never a callback. Pre-generate related IDs. Authorize
294
+ cross-user writes first. See `swdbservertxintents-authorized-cross-user-writes`
295
+ for limits and outcome semantics.
296
+
297
+ ## Browser contracts and constraint errors
298
+
299
+ A schema with no table `client` block has no browser data contract. Inspect
300
+ `data.client.status` in the app description: `not_declared` means there
301
+ is no client digest to send, and the app data client's endpoint refuses every
302
+ request with 403 `DATA_ACCESS_DENIED`. Add explicit client grants only for the
303
+ operations you want a browser to call; ordinary `sw.db` calls in a function do
304
+ not need a browser contract digest.
305
+
306
+ A write that violates a unique column, unique group or primary key
307
+ (including a value held by another owner) is a
308
+ duplicate, and nothing is written. A declared browser write returns HTTP 409
309
+ with `error: 'DATA_CONFLICT'` and the message “A record with these values
310
+ already exists.” A function's `sw.db` insert, update or transaction throws
311
+ the same: `err.code === 'DATA_CONFLICT'`, `err.status === 409`, with that
312
+ message. Catch it and answer as a duplicate (for example "slot taken") rather
313
+ than retrying the same write. Other constraint failures, such as a missing
314
+ required value or a failed check, keep their own codes.
315
+
316
+ For typed queries, keep literal keys and column names: `const columns =
317
+ ['id', 'title'] as const` preserves the selected-column type. A broad
318
+ `Record<string, unknown>` discards a table's known columns and value types;
319
+ use the generated row/write/where shape or an inferred object literal instead
320
+ of casting the whole request to that record type.
321
+
322
+ ## Provider-or-booker and owner-or-staff recipes
323
+
324
+ Match each table to one of three shapes, then take the recipe for it:
325
+
326
+ 1. **Personal rows.** One person owns the row: `owner()`. Sharing a row with
327
+ named people keeps it `owner()` and adds a grant:
328
+ `anyOf(owner(), grant(...))`
329
+ (`docs({ topic: 'declared-data', section: 'per-owner-sharing' })`).
330
+ 2. **Team rows.** Everyone in a group reads the row: `member()` over your own
331
+ membership table, `group()` for the built-in groups, `appRole()` for a role
332
+ held across the app, `anyOf(owner(), ...)` when the author keeps extra
333
+ rights (`owner-or-member-and-parent-access` below).
334
+ 3. **Two parties on one row.** A booking has a booker and a provider; a
335
+ ticket has a customer and staff. One row has one owner, and a rule cannot
336
+ show one reader a column it hides from another. So when two people need
337
+ different rights or different columns on the same row, it is two rows:
338
+ the row each party owns, plus a grant, access row or role for the other
339
+ party. The two recipes below are this shape.
340
+
341
+ `serverOnly()` is for a table no caller should ever read under their own
342
+ name: a membership or access ledger your functions fill, trusted
343
+ configuration. It is not the answer to "this needs a function": a function
344
+ on a declared table reads with the caller's rule, so the function keeps its
345
+ validation and loses its access checks (shown under "Owner or staff" below).
346
+ When your brief fixes the JSON routes, that is still what declared rules buy:
347
+ the function shrinks to validation, revocation and tests come from the
348
+ platform, and the deploy report says who can read what.
349
+
350
+ **Provider or booker, for one booking.** The booker is the managed owner;
351
+ a separate access table grants that booking's provider read access. The group
352
+ key is the booking row's `id`, not a provider-wide key that would expose
353
+ other bookings. This recipe is for several independent providers, each of
354
+ whom may see only their own bookings; there, do not replace it with an
355
+ app-wide provider role. One business whose staff all see every booking uses
356
+ `appRole()` instead (`declared-data`; `sw.groups` → `app-wide-roles`),
357
+ with `anyOf(owner(), appRole(...))` for "my bookings or staff".
358
+
359
+ ```ts
360
+ // db/schema.ts
361
+ import { anyOf, id, member, owner, schema, serverOnly, table, text } from 'somewhere/db';
362
+
363
+ export default schema({
364
+ bookings: table({ id: id({ uuid: true }), slot: text() }, {
365
+ scope: anyOf(owner({ column: 'booker_id' }), member({
366
+ group: 'id', membership: 'booking_access',
367
+ member_user: 'user_id', member_group: 'booking_id', operations: ['read'],
368
+ })),
369
+ client: { read: ['id', 'slot'] },
370
+ }),
371
+ booking_access: table({ id: id(), booking_id: text(), user_id: text() }, {
372
+ scope: serverOnly(), unique: [['booking_id', 'user_id']],
373
+ }),
374
+ });
375
+ ```
376
+
377
+ The booking function verifies the signed-in booker and availability, resolves
378
+ the provider from the selected slot (never a caller-supplied owner), then
379
+ atomically creates the booking with `booker_id` and two access rows, one for
380
+ the booker and one for the provider, using `sw.db.server.tx` (see
381
+ `swdbservertxintents-authorized-cross-user-writes` below). The booker needs
382
+ their own row: `bookings` is a team table, so its owner keeps a booking only
383
+ while also in that booking's group, and the deploy reports this. The browser
384
+ cannot create access rows or grant itself membership. Keep booker email out of the shared booking fields: return it only
385
+ from a function that verifies the caller is that booking's provider. This scope
386
+ does not itself implement availability or prevent double booking; enforce the
387
+ slot's unique/transactional rule when creating the booking.
388
+
389
+ **Provider publishes slots, customers book one.** The same shape when the
390
+ app starts from the provider's calendar: a public page lists a provider's free
391
+ slots, a signed-in customer books one, and only that customer and the provider
392
+ see the booking. Do not book by writing the customer onto the provider's slot
393
+ row; that puts two parties with different rights on one row. The slot stays
394
+ the provider's and the booking is the customer's:
395
+
396
+ ```ts
397
+ // Slots belong to the provider; each booking belongs to its customer.
398
+ import { anyOf, boolean, id, integer, member, owner, schema, serverOnly, table, text } from 'somewhere/db';
399
+
400
+ export default schema({
401
+ // The provider's rows. Visitors read the free ones, with no booker data.
402
+ slots: table({ id: id(), start_ms: integer(), booked: boolean({ default: false }) }, {
403
+ scope: owner(),
404
+ client: { read: ['id', 'start_ms', 'booked'], delete: true, publicRead: { where: { booked: false } } },
405
+ }),
406
+ // The customer's row; the provider reads it through the access row.
407
+ bookings: table({ id: id({ uuid: true }), slot_id: text({ unique: true }), message: text({ default: '' }) }, {
408
+ scope: anyOf(owner({ column: 'booker_id' }), member({
409
+ group: 'id', membership: 'booking_access',
410
+ member_user: 'user_id', member_group: 'booking_id', operations: ['read'],
411
+ })),
412
+ client: { read: ['id', 'slot_id', 'message'] },
413
+ }),
414
+ booking_access: table({ id: id(), booking_id: text(), user_id: text() }, {
415
+ scope: serverOnly(), unique: [['booking_id', 'user_id']],
416
+ }),
417
+ });
418
+ ```
419
+
420
+ `booked` is the publication field, so the browser cannot create or write it:
421
+ a function of the provider's adds slots, and `api/book.ts` verifies the
422
+ caller, reads the slot with server authority to
423
+ find its provider, then in one `sw.db.server.tx` inserts the booking with
424
+ `booker_id`, the two access rows, and sets the slot's `booked`. `slot_id` is
425
+ unique, so of two concurrent bookers exactly one succeeds; the other sees the
426
+ constraint error. Cancelling is the mirror: delete the booking and clear
427
+ `booked` in one transaction. The customer's `message` is read by the customer
428
+ and that booking's provider and no one else; the public slot list never
429
+ carries booking data.
430
+
431
+ **Owner or staff.** Staff can read and update tickets; only their owner can
432
+ delete them. The customer's email and the assignee stay on the ticket row and
433
+ reach staff only: the owner branch lists the columns it reads, and a column
434
+ outside a reader's branch is absent from the row (`declared-data` →
435
+ `one-row-two-readers-different-columns`). Internal notes use a separate
436
+ staff-only table so a customer never reads them at all. Staff replies the customer
437
+ reads go in a `parent({ via: 'ticket_id' })` child table instead; then add
438
+ `create: ['staff']` to the ticket's `appRole` roles, because creating a child row
439
+ needs `create` on its parent (`owner-or-member-and-parent-access` below).
440
+
441
+ ```ts
442
+ // db/schema.ts
443
+ import { anyOf, appRole, id, owner, schema, table, text } from 'somewhere/db';
444
+
445
+ export default schema({
446
+ tickets: table({ id: id(), subject: text(), body: text(), status: text({ default: 'open' }), customer_email: text(), assignee_email: text({ nullable: true }) }, {
447
+ scope: anyOf(owner({ read: ['id', 'subject', 'body', 'status'] }), appRole({ roles: { read: ['staff'], update: ['staff'] } })),
448
+ client: { read: ['id', 'subject', 'body', 'status', 'customer_email', 'assignee_email'], create: ['subject', 'body', 'customer_email'], update: ['subject', 'body', 'status', 'assignee_email'], delete: true },
449
+ }),
450
+ internal_notes: table({ id: id(), ticket_id: text(), body: text() }, {
451
+ scope: appRole({ roles: { read: ['staff'], create: ['staff'], update: ['staff'], delete: ['staff'] } }),
452
+ client: { read: ['id', 'ticket_id', 'body'], create: ['ticket_id', 'body'], update: ['body'], delete: true },
453
+ }),
454
+ }, { appRoles: { staff: { grantableBy: [] } } });
455
+ ```
456
+
457
+ The same shape serves the booking row when the provider and the booker see
458
+ different columns: `anyOf(owner(), grant({ ..., read: ['id', 'start'] }))`
459
+ keeps `booker_email` with the provider. Filters, ordering and aggregates may
460
+ name only the columns every branch reads.
461
+
462
+ A function on these tables keeps its validation and drops its access checks.
463
+ With `serverOnly()` tables, listing tickets is a role check, a caller-scoped
464
+ filter, and a per-row check on every detail route:
465
+
466
+ ```ts
467
+ const user = await sw.auth.requireUser(request, { appRoles: true });
468
+ const staff = user.appRoles?.includes('staff') ?? false;
469
+ const { data } = await sw.db.server.from('tickets', { where: staff ? {} : { customer_id: user.id } });
470
+ ```
471
+
472
+ With the rule declared, the same route is the read itself, and so is every
473
+ other route on the table:
474
+
475
+ ```ts
476
+ const { data } = await sw.db.from('tickets', { order: [['created_at', 'desc']] }); // the caller's own, or all of them for staff
477
+ ```
478
+
479
+ Seed staff with your developer key once they have signed up: `somewhere auth
480
+ roles grant <address> staff` (MCP `app_role_grant`, REST `POST /v1/auth/app-roles/grant`);
481
+ the address need not be verified, you vouch for the person. Never assign staff
482
+ from a public form. The in-app path stays: an app admin (made with
483
+ `auth_user_update({ project_id, user_id, role: 'admin' })`) calls your endpoint
484
+ that runs `sw.groups.appRoles.grant(request, userId, 'staff')`, and holders of a
485
+ role named in `grantableBy` grant it onward (`sw.groups` → `app-wide-roles`,
486
+ "The first staff member"). To make everyone at your company's domain staff instead, declare
487
+ `appRoles: { staff: { emailDomain: 'example.com' } }` (`sw.groups` →
488
+ `app-wide-roles`). That role holds only while the address is verified, which
489
+ happens when the user enters the sign-up code, follows a magic link, or signs
490
+ in with Google, GitHub or Discord. An app whose staff skip verification gives
491
+ them no staff role: keep a verification step for staff, or grant staff
492
+ explicitly. Do not check an unverified address's domain in a function
493
+ instead; anyone can sign up with an address they do not own. Verify as the owner, the intended provider/staff member, an
494
+ unrelated signed-in user and signed out. The allowed readers must succeed;
495
+ other readers must not receive the row, and a ticket owner must not receive
496
+ internal notes. Removing the provider access row or staff role must remove
497
+ that branch's access; removing the booker's access row removes the booker's
498
+ access too. Run these app tests separately from typechecking.
499
+
500
+ ## Owner-or-member and parent access
501
+
502
+ ### Teams
503
+
504
+ A team people join is a built-in group: `group()` on its rows and `sw.groups`
505
+ calls in small endpoints. The complete app, with its spec, is
506
+ `somewhere docs sw.groups --section team-example`. `member()` over your own
507
+ server-only membership table, below, is for relationships your app records
508
+ itself (`sw.groups` → `relationships-that-are-not-teams`).
509
+
510
+ ### Membership and parent examples
511
+
512
+ **Sharing your own rows with specific people.** When the rows stay the
513
+ owner's and the owner invites specific people (sharing contacts read-only,
514
+ co-authors, a shared folder), use `anyOf(owner(), grant({ table: 'shares',
515
+ grantee: 'grantee_id', operations: ['read'] }))` with an `owner()` shares
516
+ table the owner fills: `docs({ topic: 'declared-data', section: 'per-owner-sharing' })`.
517
+ `member()` and `group()` need a group key on every row, with the owner in
518
+ that group; `grant()` adds nothing to existing rows, and the owner keeps
519
+ access without inviting themselves. Adding the grant widens every existing
520
+ caller-scoped read of that table to "mine plus shared with me"; a list that
521
+ must stay owner-only filters `where: { user_id: me.id }` in a function
522
+ (same section).
523
+
524
+ Import the helpers you use from `somewhere/db`.
525
+
526
+ **Owner or moderator** keeps personal rows private while letting an app-wide
527
+ moderator help. Declare `moderator` in the schema's `appRoles` and grant it
528
+ with your developer key (`somewhere auth roles grant <address> moderator`, or
529
+ MCP `app_role_grant`); from inside the app, an app admin grants it through
530
+ `sw.groups.appRoles.grant(request, userId, role)`:
531
+
532
+ ```ts
533
+ scope: anyOf(owner(), appRole({ roles: {
534
+ read: ['moderator'], update: ['moderator'],
535
+ } }))
536
+ ```
537
+
538
+ For **owner or team admin**, use the built-in group carried by the row's
539
+ `group_id: text()` column:
540
+
541
+ ```ts
542
+ scope: anyOf(owner(), group({ roles: {
543
+ read: ['admin'], update: ['admin'],
544
+ } }))
545
+ ```
546
+
547
+ For **creator or team owner can delete**, list only `owner` under `delete`:
548
+
549
+ ```ts
550
+ scope: anyOf(owner(), group({ roles: {
551
+ read: ['owner', 'admin', 'member'], delete: ['owner'],
552
+ } }))
553
+ ```
554
+
555
+ Every member of the row's group reads it; the creator updates and deletes
556
+ their own rows; a group owner deletes any row in the group. The platform
557
+ records the creator, so no `created_by` column is needed. A creator who leaves
558
+ the group loses access to the rows they created. For app-owned teams, keep member reads/creates/updates declared; a team-owner
559
+ delete can use one checked server operation without moving all data to server-only.
560
+
561
+ The role branch grants only the operations you list. In these examples,
562
+ moderators or admins may read and update, while only the owner may delete.
563
+ Inside `anyOf`, an omitted group operation grants nobody; standalone
564
+ `group()` keeps its usual defaults. Browser `client` grants still decide
565
+ which operations and fields are exposed.
566
+
567
+ An owner-or-group insert requires current membership in the supplied group,
568
+ then stamps the signed-in user as owner. An owner-or-app-role insert stamps
569
+ any signed-in user as owner. Neither lets the caller choose another owner.
570
+ The group column cannot be updated, even to the same value. Removing a role
571
+ removes that branch's access. Removing someone from the group removes their
572
+ access to its rows, including the rows they own: team rows belong to the team.
573
+ Under `anyOf(owner(), appRole())` owners keep their own rows.
574
+ For a child using `parent()`, creating a child row needs `create` on the parent
575
+ for that person: the parent's owner branch, or a role listed under the parent's
576
+ `create`. Read or update roles alone do not let anyone add a child; the insert
577
+ is refused with 403 `POLICY_AUTHORITY_REQUIRED`.
578
+
579
+ **Existing app-owned membership tables** can use `member()` instead:
580
+
581
+
582
+ Use `anyOf(owner(), member({ group: 'team_id', membership: 'team_members',
583
+ member_user: 'user_id', member_group: 'team_id' }))` when both a row's
584
+ creator and its team members should be able to read, update, and delete the
585
+ row. This is collaborative editing, including deletion by other team members.
586
+ The membership table is declared separately. Ownership is set by the platform
587
+ on create. Team rows belong to the team: the creator keeps their rows only
588
+ while a member of the row's group, so leaving the team ends their access to
589
+ every team row, the ones they wrote included.
590
+
591
+ For **team reading with author-only editing**, use
592
+ `anyOf(owner(), member({ ..., operations: ['read'] }))` (teammates read,
593
+ the author edits their own row while still in the team), or
594
+ `allOf(gate, who)` when the gate's own operations must be spelled out:
595
+
596
+ ```ts
597
+ scope: allOf(
598
+ member({
599
+ group: 'team_id', membership: 'team_members',
600
+ member_user: 'user_id', member_group: 'team_id',
601
+ operations: ['read', 'create', 'update', 'delete'],
602
+ }),
603
+ anyOf(owner(), member({
604
+ group: 'team_id', membership: 'team_members',
605
+ member_user: 'user_id', member_group: 'team_id',
606
+ operations: ['read'],
607
+ })),
608
+ )
609
+ ```
610
+
611
+ Both must hold, in the same database statement:
612
+
613
+ - **read:** any current team member reads every row of the team;
614
+ - **create:** any current member adds a row to their team, recorded as its
615
+ author;
616
+ - **update / delete:** only the row's author, and only while still a member;
617
+ - **leaving the team** removes access to every team row on the next request,
618
+ the author's own rows and their `parent()` children included. Rejoining
619
+ restores it.
620
+
621
+ The gate is current membership: `member()` with its `operations` listed,
622
+ `group({ roles })`, or `appRole({ roles })`. Who is `owner()` (the
623
+ author) or `anyOf(owner(), …)`, whose second branch is `appRole()` or the
624
+ gate's own membership: the same `group()` column, or the same `member()`
625
+ table, keys and member user. With `group()`, for example
626
+ `allOf(group({ roles: { read: ['member', 'admin'], create: ['member', 'admin'], update: ['member', 'admin'], delete: ['member', 'admin'] } }), anyOf(owner(), group({ roles: { read: ['member', 'admin'], update: ['admin'], delete: ['admin'] } })))`
627
+ lets a group admin edit any team row, and an author edit their own. Inside
628
+ `allOf`, every role list and `operations` list must be written out; an
629
+ operation left out of a written list grants nobody. Creating a row needs the
630
+ gate's create permission. The group key and the author are fixed for the row's
631
+ life. Not yet supported on `allOf` tables: live subscriptions,
632
+ `client.publicRead`, `client.links`, `client.intake`, payment bindings and
633
+ file collections.
634
+
635
+ `anyOf(owner(), member({ ..., operations: ['read'] }))` is the owner (while
636
+ still in the row's group) OR a member: teammates read, only the owner edits,
637
+ and someone removed from the team loses every team row, their own included.
638
+
639
+ `operations` restricts what membership grants: `read`, `create`,
640
+ `update`, and `delete`. Omit it for all four. Reading includes list,
641
+ get, counts, and related-row reads. The owner's authority does not depend on
642
+ `operations` (an owner still in the group edits their own row); a read-only
643
+ teammate cannot edit or delete someone else's row. A standalone
644
+ `member({ ..., operations: ['read'] })` table is also read-only for members.
645
+ An empty list grants members nothing. Create-only membership is supported;
646
+ update or delete must also include `read`, because those operations return
647
+ row data. Upserts remain unsupported for member and policy scopes.
648
+ Browser `client` grants still control exposed operations and fields; they
649
+ cannot grant authority that the scope denies. A later deploy can change an
650
+ existing table's rule, rows in place; "Two worlds" below lists what that does.
651
+
652
+ Creating a row requires an explicitly supplied, complete, non-null group key
653
+ and membership in that group. Ownership alone cannot authorize placing new
654
+ content in someone else's team. The membership check and insert are one
655
+ database statement. Group keys cannot be changed or incremented on update.
656
+ Creating a new group together with its initial memberships is application
657
+ logic in an authenticated function; it is not bootstrapped through an
658
+ owner-or-member browser insert.
659
+
660
+ For existing rows, owner-or-member access is the owner while a member of the
661
+ row's group, OR a member: removing the creator's membership removes their
662
+ permission to read, edit or delete their own rows on their next request
663
+ (team rows belong to the team). The rows stay where they are, with the same
664
+ owner and group; adding the person back restores their access. Share links
665
+ the person made to those rows stop working too. Three consequences to plan for:
666
+
667
+ - A row with no group (for example one written before the table gained its
668
+ team rule) stays with its owner only. Teammates see it once your server
669
+ code sets its group.
670
+ - A row whose group has no members left, or whose built-in group was deleted,
671
+ is reachable only by your server code until someone is added to that group.
672
+ - Rows and their `parent()` children are checked inside the database
673
+ statement; files in a team file collection are checked on each request,
674
+ before the file is served.
675
+
676
+ For a task that follows its project, declare
677
+ `project_id: text({ references: 'projects' })` and
678
+ `scope: parent({ via: 'project_id' })`. Use `integer` instead of `text` when
679
+ the parent declares an integer key, `id({ uuid: false })`. Access is checked against the referenced
680
+ parent's private owner, member, group, app-role, or supported owner-or-role
681
+ scope. A parent's public
682
+ read grant does not propagate to its tasks. A policy-scoped child declares its
683
+ own browser operations and readable fields, and cannot declare `publicRead`.
684
+
685
+ A create supplies the parent ID explicitly and needs `create` on the parent
686
+ for that person: its owner, or a role listed under the parent's `create`.
687
+ Read or update authority on the parent is not enough. A staff reply to a
688
+ customer's ticket is a child insert, so the ticket's rule lists
689
+ `create: ['staff']`; without it the reply is refused with 403
690
+ `POLICY_AUTHORITY_REQUIRED`.
691
+ A move requires access to both the current and proposed parent, checked in the same database statement;
692
+ browser moves also require the linking field in `client.update`. An ordinary
693
+ field update keeps the current parent. Use `set` to change the parent ID;
694
+ incrementing that linking field is refused. Each child operation checks the
695
+ parent's authority for that operation. Browser operation grants can narrow it
696
+ further.
697
+
698
+ This contract supports one parent hop through one scalar foreign key to an
699
+ `id()` column. It does not support parent chains, arbitrary policy expressions,
700
+ visitor policies, or arbitrary per-operation policy expressions. Live subscriptions
701
+ over these policy scopes are refused. `onConflict` inserts follow the same
702
+ rule (see Upserts below). `sw.db.tx` works
703
+ on them: a child insert the parent does not authorize rolls the whole
704
+ transaction back with 403 `POLICY_AUTHORITY_REQUIRED`, and an update reaches
705
+ only rows the caller may write. A relationship
706
+ declaration alone never inherits access; `parent({ via })` is the explicit
707
+ authorization declaration.
708
+
709
+ ## Two worlds: your database and the SQL database
710
+
711
+ Every table lives in exactly one world.
712
+
713
+ Tables declared in `db/schema.ts` are **your database** — managed. The
714
+ schema file is the only schema writer: schema ships with your code, scoping
715
+ is armed the moment a table exists, and destructive surprises are refused at
716
+ deploy. Managed tables are locked to the file — `db_migrate` on them
717
+ returns `409 SCHEMA_MANAGED`, and raw DDL on them
718
+ is refused at query time (`SCHEMA_LOCKED`) — edit `db/schema.ts` and
719
+ deploy instead.
720
+
721
+ An existing managed table can change its access rule in a later deploy, rows
722
+ in place: between `owner()`, `shared()`, `serverOnly()`, `member()` and the
723
+ composed rules (`anyOf`, `allOf`, `parent`), in production or a preview. The
724
+ new rule applies to every request admitted after the release activates, and
725
+ admission under the previous release ends within 60 seconds; a request already
726
+ running finishes under the rule it started with. A column the new rule needs is added in the same deploy, empty: existing rows
727
+ with no owner stay readable only by server code until one is set, and the
728
+ deploy says how many there are. The platform never guesses an owner, and an
729
+ existing column cannot become the owner column. Group keys and parent links
730
+ that rows already hold do decide access under the new rule, and the deploy
731
+ says so. A table that stops using its owner column keeps it, declared as an
732
+ ordinary column. A `member()` rule cannot rely on a membership table that
733
+ accepted browser writes in an earlier version: declare a new `serverOnly()`
734
+ membership table and fill it from server code.
735
+
736
+ On a rule that uses `group()` or `appRole()`, a deploy can change which roles
737
+ may read, create, update or delete on a `group()` or `appRole()` the rule
738
+ already has: staff gains create, a team owner gains delete, a member loses
739
+ update. That is the only change such a rule takes in a deploy. Such a deploy
740
+ changes one table's rule (a table that inherits it through `parent()` follows)
741
+ and nothing else that decides who may read or write it: the rule's shape (its
742
+ `anyOf`/`allOf` branches, group column, owner column and `parent()` links), the
743
+ table's columns and `client` permissions, the app's file collections, and the
744
+ app's role declarations (the roles, who may grant them, their email domains
745
+ and how they are assigned) all stay as deployed. Change those in their own
746
+ deploy first, then the roles; to add a role, deploy the role first and use it
747
+ in a rule after; to remove one, first deploy the rules without it. A role
748
+ change is available only when the app's stored roles and its live version
749
+ already carry complete role meaning (the generation, its full history, how
750
+ each role is acquired and which email domain holds it, all agreeing). An app
751
+ whose stored roles predate that format is refused with
752
+ `409 ACCESS_RULE_EDIT_ROLES_NOT_MODERN`: change the rule in a new table, or
753
+ handle the operation in a server endpoint. The change is judged against the
754
+ rule the live version serves, never against an earlier deploy that failed.
755
+ The deploy's `warnings` list, per table, which role gains or loses which
756
+ operation, widening first, and the file and room actions that follow: reading
757
+ files and joining rooms follow read; uploading, replacing, deleting and moving
758
+ files and changing room state follow update. `--json` carries the same entries
759
+ as `access_changes` (a `--dry-run` returns them too). The list names roles, not
760
+ people: someone whose role loses an operation may still reach a row as its
761
+ owner or through another role. In `allOf()`, a role removed from one condition
762
+ can deny someone the other condition admits, since both must hold.
763
+ Requests admitted under the new release use the new rule; a room ticket keeps
764
+ what it was issued with until it expires (at most 5 minutes). If the app's
765
+ roles change later, the changed role branch stops granting until a deploy built
766
+ for the new roles; other branches of the rule keep working. If the roles
767
+ change while the deploy is being built, it is refused with
768
+ `409 ACCESS_RULE_EDIT_STALE` before it goes live; deploy again. A preview is
769
+ its own copy: a production rule change does not reach a preview that already
770
+ exists. Any other change to such a rule, and a table with a checkout that has
771
+ not settled, are refused with `409 SCHEMA_DEPLOY_REFUSED` and a message naming
772
+ what changed and what to do; nothing changes. Rolling back across an
773
+ access-rule change is refused; deploy the previous rule as a new release
774
+ instead.
775
+ `409 SCOPE_CHANGE_BLOCKED_BY_RELEASE` still protects a takeover or
776
+ restoration that would change the posture of retained code.
777
+
778
+ Everything else is the **SQL database** — you write the SQL. `db_migrate`
779
+ applies schema changes (a production target is bookmarked first — a marker
780
+ in the database's 30-day history, not an undo, since restoring in place is
781
+ not available; keep dumps and exports for recovery). Access rules are set in
782
+ `db/schema.ts` and take effect on deploy. On a SQL-mode project, ordinary
783
+ `sw.db.query` / `sw.db.batch` run whatever you write. This is a sibling of
784
+ the managed database: it is the right world for hand-tuned schemas and external
785
+ identity models. A managed project reads and writes its declared tables through
786
+ structured operations; cross-user reads of them use `sw.db.server.from`,
787
+ `count` and `aggregate`. Raw SQL through the explicit
788
+ `sw.db.server.query` / `sw.db.server.batch` namespace reads the SQL
789
+ database. Every project created today keeps the two worlds in separate
790
+ databases, so its raw SQL never sees a table declared in `db/schema.ts`;
791
+ only an older project whose declared and SQL tables share one database can
792
+ raw-read declared tables.
793
+
794
+ Where raw SQL is available, it stays trusted-as-written and unscoped. Managed
795
+ projects make that choice explicit through the `sw.db.server` read namespace.
796
+
797
+ ## Managed mode — what a db/schema.ts does to raw SQL
798
+
799
+ Deploying a `db/schema.ts` that declares at least one table puts the whole
800
+ PROJECT into managed mode, not just the declared tables. From that deploy on,
801
+ inside deployed function code:
802
+
803
+ - On an older shared database, ordinary `sw.db.query` / `sw.db.batch` are
804
+ refused with `MANAGED_RAW_SQL_REQUIRES_SERVER_AUTHORITY` (403). With a
805
+ separate SQL database they run there like the server forms, unscoped.
806
+ - For a deliberate raw read, authorize the caller first and use
807
+ `sw.db.server.query(sql, params?)` or
808
+ `sw.db.server.batch(statements)`. These calls run as explicit server
809
+ authority, read as written, and do not apply declared row permissions. On a
810
+ project created today they read only the separate SQL database, so a table
811
+ declared in `db/schema.ts` is not found there; read declared tables with
812
+ `sw.db.server.from`, `count` or `aggregate`.
813
+ - Raw SQL never writes declared tables. With a separate SQL database, server
814
+ raw writes go to that database; on an older shared database every raw write
815
+ is refused with `MANAGED_RAW_WRITE_FORBIDDEN` (403).
816
+ - Writes go through the composed builder: `sw.db.insert`,
817
+ `sw.db.update`, `sw.db.remove`. A composed write needs a declared
818
+ intent, so a table your functions write must be in `db/schema.ts` (or,
819
+ on an older SQL-mode project, carry an access declaration recorded
820
+ through the former scope API).
821
+ - It applies to EVERY function, including job, queue, and cron handlers. A
822
+ background handler whose body is a raw INSERT starts returning 403 the
823
+ moment the schema file lands, and on the cron surface the only visible
824
+ symptom is `last_run_status: "failed"` — read the failed run with
825
+ `job_get` to see the code.
826
+
827
+ An older project that keeps one shared database and runs its own SQL moves to
828
+ separate databases with its first `db/schema.ts`, in that deploy. Its existing
829
+ database becomes its SQL database, so raw SQL keeps reaching every table it
830
+ created; a new managed database holds the declared tables, which start empty,
831
+ and the platform's own data (tasks, email history, file search, conversations,
832
+ user memory, visitor sessions), copied in the same deploy. Notifications move
833
+ to the app's notification inbox. The platform's tables left in the SQL database
834
+ are renamed with the prefix `_sw_moved_`, so a raw query that still names one
835
+ fails instead of reading old rows. The deploy (and its dry run) refuses, before
836
+ anything is created:
837
+ - raw SQL in a function that names one of the platform's tables, such as
838
+ `auth_users`: `409 SCHEMA_MIGRATION_RAW_SQL_PLATFORM_TABLE`, naming the file
839
+ and the query. Read app users through `sw.auth` instead.
840
+ - a structured call (`sw.db.from`, `insert`, `update`, `remove`, `count`,
841
+ `aggregate`) on a table `db/schema.ts` does not declare, which would answer
842
+ `TABLE_NOT_MANAGED` once the project has moved:
843
+ `409 SCHEMA_MIGRATION_UNDECLARED_TABLE`, naming the file and the call.
844
+ - a declared table whose name an existing table with rows already has:
845
+ `409 SCHEMA_MIGRATION_TABLE_EXISTS`. Declare another name, or keep reaching
846
+ the existing table with raw SQL.
847
+ - a `_notifications` table with rows that `sw.notifications` did not write:
848
+ `409 SCHEMA_MIGRATION_NOTIFICATIONS_UNSUPPORTED`.
849
+ - an open preview: `409 SCHEMA_MIGRATION_PREVIEW_OPEN`, until it is closed.
850
+
851
+ The check reads the deploy's built function code. It does not see a table name
852
+ built at run time, or SQL text assembled from pieces; such a query fails when
853
+ it runs, on the renamed table. Versions from before that deploy can no longer
854
+ be rolled back to.
855
+
856
+ Developer authority is untouched: `db_query`, `db_batch`,
857
+ `db_migrate`, `db_dump`, the CLI, and the dashboard keep
858
+ full raw SQL against the project's raw SQL database. A project that keeps its
859
+ tables in the managed database has no raw SQL database, so raw SQL and dumps
860
+ answer `RAW_DATABASE_NOT_READY`; read its managed rows with `db_browse`
861
+ (`plane: "managed"`) or `somewhere db rows <table>`, and their schema and
862
+ row counts with `db_describe`.
863
+
864
+ Leaving managed mode is possible. There is no flag that flips a project back,
865
+ because the transition is deliberate: the owner authorizes it by email FIRST,
866
+ and the release that exports every managed table then completes it.
867
+
868
+ 1. `POST /v1/projects/:id/managed-exit/request` — a developer credential for the
869
+ project OWNER. You can request this with managed tables still present; that
870
+ is the point. The platform emails that account's current verified address the
871
+ exact plan: every managed table it would export, and the retained releases
872
+ the exit would override. An account whose email is unverified, or that is
873
+ anonymous, temporary or merged away, is refused. 3 requests per project per
874
+ 10 minutes.
875
+ 2. `GET /v1/managed-exit/review?token=…` — the plan, its digest, the base
876
+ release, the warning, and which stage it is at. Review-only: opening it
877
+ approves nothing and changes nothing.
878
+ 3. `POST /v1/projects/:id/managed-exit/approve` — the owner submits the token.
879
+ **This records authorization and nothing else.** Your project is exactly as
880
+ managed after approving as before: no authority moves, no table changes, no
881
+ rollback boundary moves. The link is single-use and expires 10 minutes after
882
+ the request.
883
+ 4. **Deploy the release that marks every managed table `exported()`.** That
884
+ release consumes the authorization and completes the transition. It must
885
+ export exactly the approved set — a partial export, an extra table the
886
+ approval never covered, or a release that adds new managed tables is refused
887
+ and changes nothing.
888
+
889
+ The dashboard drives the same calls at `/dashboard/managed-exit`.
890
+
891
+ What the completing deploy does, stated as the warning states it:
892
+
893
+ - **Your data is preserved.** Existing rows and tables stay as they are.
894
+ - The platform **stops enforcing** declared table access and schema-safe composed
895
+ writes. SQL migrations, authorization, validation, and rollback compatibility
896
+ become yours.
897
+ - Developer tools, including developer-authorized `run_code`, receive direct SQL
898
+ authority once the transition completes.
899
+ - **Already-deployed managed handlers do not change.** They keep their baked
900
+ managed/read-only behavior until you remove the marker-only `db/schema.ts` and
901
+ deploy reviewed SQL source.
902
+ - Managed clients for exported tables become unavailable.
903
+ - Releases older than the completing release are no longer eligible for rollback.
904
+
905
+ The completing release therefore ships a marker-only declaration — every
906
+ managed table marked, and nothing else in the file:
907
+
908
+ ```ts
909
+ import { schema, exported } from 'somewhere/db';
910
+
911
+ export default schema({
912
+ readings: exported(),
913
+ field_notes: exported(),
914
+ audit_log: exported(),
915
+ });
916
+ ```
917
+
918
+ `exported()` takes no options, and managed search must be removed too.
919
+ Downloading a backup does **not** substitute for any of this: `db_dump` or a
920
+ data export leaves the declaration exactly as it was, and the transition is
921
+ about what the live declaration claims, not about whether you hold a copy.
922
+
923
+ **Two limits to plan around.** Without an approved exit, `exported()` is refused
924
+ while a retained release in the rollback window still queries that table's
925
+ declared scope — an approved exit is what authorizes overriding exactly the
926
+ releases you were shown. And your app code is not migrated for you: the
927
+ `somewhere:data` client is generated from the declaration, so browser code
928
+ calling an exported table must change in the SAME release that exports it.
929
+
930
+ Exiting is a considered migration, not an undo button. If your functions need
931
+ raw SQL writes, keep the project in SQL mode. A managed project uses structured
932
+ writes, including `sw.db.server.insert / update / remove / tx` after application
933
+ authorization for deliberate server-authority writes.
934
+
935
+ ## Managed-schema error codes
936
+
937
+ - `SCHEMA_READ_FAILED` (503, retryable, at deploy) — the platform could not
938
+ read the project’s prior managed-schema state. Nothing was applied; retry.
939
+ - `SCHEMA_APPLY_FAILED` (503, retryable, at deploy) — the declaration was
940
+ valid but its plan could not be applied safely. Nothing changed; retry after
941
+ the message’s rollout or availability condition clears.
942
+ - `SCHEMA_DEPLOY_REFUSED` (409, at deploy) — `db/schema.ts` asked for
943
+ something the deploy will not do silently: removing or renaming a column,
944
+ removing a table without its `removedTable()` marker, or changing a
945
+ column's shape. It is also the answer when the database itself refuses the
946
+ declaration: a table with more columns than the database allows (at most
947
+ 100 per table, counting the columns the platform keeps), or a rule the rows
948
+ already stored break (a `unique` column over duplicate values). Nothing was
949
+ applied; the message names the exact fix. It is never retried
950
+ automatically: the same declaration is refused the same way.
951
+ - `SCHEMA_DECLARATION_INVALID` (400) — on every deploy path (fresh, full,
952
+ patch, deploy-check, preview) the upload's `db/schema.ts` must read as a
953
+ valid declaration and be sent in `files` as text: a syntax error, or the
954
+ file sent under `functions` or as a binary file, is refused before
955
+ anything is published. A full schema application additionally refuses a
956
+ declaration of a platform-reserved table. The message explains the
957
+ problem, with the line for syntax errors. A deploy with no `db/schema.ts`
958
+ is unaffected.
959
+ - `SCHEMA_MANAGED` (409) — `db_migrate` targeted a
960
+ managed table. The schema file is that table's only schema writer: edit
961
+ `db/schema.ts` and deploy. Nothing was changed.
962
+ - `SCHEMA_LOCKED` (409, at query time) — raw DDL (ALTER / DROP / …)
963
+ targeted a managed table. Same rule, enforced at the query boundary: edit
964
+ `db/schema.ts` and deploy.
965
+ - `MANAGED_RAW_SQL_REQUIRES_SERVER_AUTHORITY` (403, before transport) —
966
+ ordinary `sw.db.query` / `sw.db.batch` on an older shared database. Use declared
967
+ structured operations, or authorize the caller and use the matching
968
+ `sw.db.server.query` / `sw.db.server.batch` read.
969
+ - `MANAGED_RAW_WRITE_FORBIDDEN` (403, at query time) — raw SQL attempted a
970
+ write on an older shared database, including through `sw.db.server.query` /
971
+ `sw.db.server.batch`. Use structured writes, or run the statement with
972
+ developer authority (`db_query` / `db_batch`).
973
+
974
+ ## What you get out of the box (the industry-standard checklist)
975
+
976
+ - **Multi-tenant isolation** — one database per project, bindings
977
+ baked at deploy time, no shared schema.
978
+ - **Per-user scoping** — the structured builder
979
+ (`sw.db.from/count/insert/update/remove`) auto-scopes a table declared
980
+ user-owned to the request's verified user, with no user argument.
981
+ Explicit `sw.db.server` calls bypass that scope only when chosen. See
982
+ "Per-user scoping" below.
983
+ - **ACID transactions** — `sw.db.tx([…])` runs declared operations
984
+ atomically. If statement 3 fails, 1 and 2 roll back. Same shape
985
+ as Postgres `BEGIN; …; COMMIT;`.
986
+ - **A documented Postgres-flavored syntax subset** — `$1` placeholders,
987
+ `ILIKE`, `NOW()`, `col->>'key'`, `RETURNING *`, `SERIAL` and
988
+ `BOOLEAN` are translated, outside literals and comments. To move to
989
+ Postgres, `db_dump`, convert the database file and switch clients; a
990
+ managed Postgres adapter is not a selectable backend or migration service.
991
+ - **Direct writes** — writes go straight to the project's database, one at a
992
+ time per project, with no extra platform queue. Use `sw.db.tx` for related
993
+ declared operations (`sw.db.batch` for raw SQL in SQL mode). Transient
994
+ backpressure can still be retried.
995
+ - **Recovery evidence and exports** — `db_bookmark_create({ project_id, label })` records
996
+ a named marker around a production migration. Projects with SQL tables in a
997
+ separate database get `SPLIT_RESTORE_UNSUPPORTED`. A bookmark records
998
+ operational evidence. In-place database restore is unavailable. Use
999
+ `db_dump` or `db_export` to create a recoverable copy outside the live
1000
+ database.
1001
+ - **Schema introspection** — `db_describe` returns tables +
1002
+ columns + row counts + foreign keys in one call.
1003
+ - **Runaway-query detection** — a query that monopolizes
1004
+ database resources is detected and surfaced automatically.
1005
+
1006
+ ## sw.db.query(sql, params?, options?)
1007
+ Run raw SQL from a deployed function in a SQL-mode project. In managed mode,
1008
+ ordinary `sw.db.query` is refused with
1009
+ `MANAGED_RAW_SQL_REQUIRES_SERVER_AUTHORITY`; use declared structured calls
1010
+ for ordinary access. The result shape is:
1011
+
1012
+ {
1013
+ data: rows[], // array of row objects (READ + RETURNING)
1014
+ error: null, // never thrown; errors propagate as exceptions
1015
+ count: number, // rows.length
1016
+ last_row_id: null, // use the inserted row in data for its ID
1017
+ changes: number, // every row written, incl. cascades and triggers; test > 0
1018
+ }
1019
+
1020
+ `changes` counts every row the statement wrote, including child rows removed or cleared by a
1021
+ foreign key's `ON DELETE CASCADE` / `SET NULL` and rows written by triggers, so a one-row
1022
+ `UPDATE` or `DELETE` can report more than 1. Test `changes > 0` to know the statement
1023
+ changed something, never an exact number; use `RETURNING` and `r.data` to know which rows.
1024
+
1025
+ Use `r.data` for the rows. The MCP `db_query` tool returns a different
1026
+ shape (`{ data: { columns, rows, meta } }`) because it surfaces the
1027
+ raw platform response — don't confuse them. Inside functions it's
1028
+ always `r.data`.
1029
+
1030
+ Raw SQL is never scoped to the caller: authorize in your function. Both
1031
+ handlers below are in a SQL-mode project and admit only admins.
1032
+
1033
+ ```ts
1034
+ // api/admin/active-users.ts — SQL-mode project: raw read
1035
+ export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
1036
+ await sw.auth.requireUser(req, { role: 'admin' }) // signed out → 401, not an admin → 403
1037
+ const users = await sw.db.query(
1038
+ 'SELECT id, email FROM users WHERE active = ? ORDER BY created_at DESC LIMIT ?',
1039
+ [1, 20]
1040
+ )
1041
+ // users.data = [{ id: 1, email: "alice@test.com" }, ...]
1042
+ // users.count = users.data.length
1043
+ return Response.json(users.data)
1044
+ }
1045
+ ```
1046
+
1047
+ ```ts
1048
+ // api/admin/create-user.ts — writes an app table, not a sign-in account; body { email, name }
1049
+ export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
1050
+ if (req.method !== 'POST') return new Response('Method not allowed', { status: 405 })
1051
+ await sw.auth.requireUser(req, { role: 'admin' }) // signed out → 401, not an admin → 403
1052
+ const { email, name } = await req.json() as { email?: unknown; name?: unknown }
1053
+ if (typeof email !== 'string' || typeof name !== 'string') return Response.json({ error: 'email and name' }, { status: 400 })
1054
+ const result = await sw.db.query(
1055
+ 'INSERT INTO users (email, name) VALUES (?, ?) RETURNING *',
1056
+ [email, name]
1057
+ )
1058
+ // result.data = [{ id: 3, email: "bob@test.com", name: "Bob" }]
1059
+ // result.data[0].id = 3, result.changes = 1; result.last_row_id = null
1060
+ return Response.json(result.data[0])
1061
+ }
1062
+ ```
1063
+
1064
+ ## sw.db.server.query(sql, params?) / sw.db.server.batch(statements)
1065
+
1066
+ These are the explicit raw-read escape hatch for managed functions. Authorize
1067
+ the caller before invoking them: the platform does not apply declared owner or
1068
+ member permissions to the SQL and does not infer your business rule.
1069
+
1070
+ They read the SQL database. On every project created today that is a separate
1071
+ database from your declared tables, so `SELECT … FROM emails` on a table
1072
+ declared in `db/schema.ts` fails because the table is not there. A report over
1073
+ declared tables uses the structured server verbs instead:
1074
+
1075
+ ```ts
1076
+ // api/admin/email-report.ts — on the emails table from "Per-user scoping" below
1077
+ export default async function emailReport(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
1078
+ await sw.auth.requireUser(req, { role: 'admin' });
1079
+ // Every user's emails, counted together: exactly one row, { count }.
1080
+ const report = await sw.db.server.aggregate('emails', { count: true });
1081
+ return Response.json(report.data[0]);
1082
+ }
1083
+ ```
1084
+
1085
+ Signatures:
1086
+
1087
+ sw.db.server.query(sql: string, params?: readonly unknown[]): Promise<SomewhereDbResult>
1088
+ sw.db.server.batch(statements: readonly SomewhereRawDbStatement[]): Promise<SomewhereRawBatchResult[]>
1089
+ type SomewhereRawDbStatement = { sql: string; params?: readonly unknown[] }
1090
+
1091
+ Server raw calls accept no options. With a separate SQL database (every
1092
+ project created today) they read and write that database, never declared
1093
+ tables; on an older shared database they are read-only. DDL is refused
1094
+ (`DDL_NOT_ALLOWED_IN_FUNCTION`). Use
1095
+ `sw.db.server.insert / update / remove / tx` for deliberate server-authority
1096
+ writes against declared tables.
1097
+
1098
+ ## Whole numbers wider than JavaScript
1099
+
1100
+ Declare ordinary whole numbers, such as counts and cents, with `integer()`.
1101
+ Generated clients return JavaScript numbers, so arithmetic works directly.
1102
+ For wider identifiers, declare `bigint()`: values are exact decimal strings
1103
+ on reads and writes, including the row returned by a structured write.
1104
+
1105
+ ```ts
1106
+ // db/schema.ts
1107
+ import { schema, table, id, bigint, boolean, owner } from 'somewhere/db';
1108
+
1109
+ export default schema({
1110
+ events: table({ id: id(), snowflake_id: bigint(), seen: boolean({ default: false }) }, { scope: owner() }),
1111
+ });
1112
+ ```
1113
+
1114
+ ```ts
1115
+ // api/events/by-snowflake.ts — find the signed-in user's event by its 64-bit id
1116
+ export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
1117
+ await sw.auth.requireUser(req) // signed out → 401 AUTH_REQUIRED
1118
+ const r = await sw.db.from('events', { where: { snowflake_id: '1804000000000000000' } })
1119
+ // r.data[0].snowflake_id === "1804000000000000000" (a string, exactly)
1120
+ return Response.json(r.data)
1121
+ }
1122
+ ```
1123
+
1124
+ An `integer()` value outside JavaScript's safe whole-number range is refused
1125
+ with `DATABASE_VALUE_TOO_LARGE`; use `bigint()` for that column. Safe numeric
1126
+ strings from URL parameters work as keys and filters. Values written to an
1127
+ ordinary integer column must be numbers.
1128
+
1129
+ For `bigint()`, use canonical decimal text such as `'42'`, without a plus
1130
+ sign or leading zeros. `min` and `max` work; `sum`, `avg` and
1131
+ `increment` are refused to prevent overflow. Changing between `integer()`
1132
+ and `bigint()` leaves stored values unchanged. Changing back to `integer()`
1133
+ requires those values to fit its range before structured reads can return them.
1134
+
1135
+ On a SQL-mode project, raw `sw.db.query` runs exactly as written and is never
1136
+ rewritten, so cast the column yourself in your own RETURNING clause:
1137
+
1138
+ ```ts
1139
+ // api/admin/mark-event-seen.ts — SQL-mode project; body { id }, admins only
1140
+ export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
1141
+ if (req.method !== 'POST') return new Response('Method not allowed', { status: 405 })
1142
+ await sw.auth.requireUser(req, { role: 'admin' }) // signed out → 401, not an admin → 403
1143
+ const { id } = await req.json() as { id?: unknown }
1144
+ if (typeof id !== 'string' || id === '') return Response.json({ error: 'id' }, { status: 400 })
1145
+ // RETURNING * over a 64-bit column applies the change, then reports
1146
+ // DATABASE_VALUE_TOO_LARGE. The write DID happen — do not retry it. Cast it:
1147
+ const marked = await sw.db.query('UPDATE events SET seen = 1 WHERE id = ? RETURNING id, CAST(snowflake_id AS TEXT) AS snowflake_id', [id])
1148
+ return Response.json(marked.data)
1149
+ }
1150
+ ```
1151
+
1152
+ A structured write of a number outside the whole-number range the database
1153
+ stores — below `-9223372036854775808` or above `9223372036854775807` — is
1154
+ refused before the row is written, naming the column and the range, because the
1155
+ database cannot hold it as a whole number at all. Store such a value as text.
1156
+ A whole number past that range bound into a batch statement is refused the same
1157
+ way, before the batch runs.
1158
+
1159
+ That is reading one. WRITING one back has the mirror constraint: a whole number
1160
+ that wide cannot travel as a JSON number at all, because JSON parsing rounds it
1161
+ before any platform code runs. A request body
1162
+ carrying `"params": [9223372036854775807]` is refused with
1163
+ `NUMBER_PRECISION_LOST` before anything is written, naming the field, the digits
1164
+ sent and the number that arrived. Send it as a STRING, the same form a read
1165
+ returns, and the round trip is lossless:
1166
+
1167
+ ```ts
1168
+ // api/admin/import-event.ts — SQL-mode project: the raw insert, admins only
1169
+ export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
1170
+ if (req.method !== 'POST') return new Response('Method not allowed', { status: 405 })
1171
+ await sw.auth.requireUser(req, { role: 'admin' }) // signed out → 401, not an admin → 403
1172
+ // exact: the 64-bit id travels as a string
1173
+ await sw.db.query('INSERT INTO events (snowflake_id) VALUES (?)', ['1804000000000000000'])
1174
+ return Response.json({ imported: true })
1175
+ }
1176
+ ```
1177
+
1178
+ The structured write in a managed project, on the same `events` schema as the read above:
1179
+
1180
+ ```ts
1181
+ // api/events/record.ts — record the signed-in user's event
1182
+ export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
1183
+ if (req.method !== 'POST') return new Response('Method not allowed', { status: 405 })
1184
+ await sw.auth.requireUser(req) // signed out → 401 AUTH_REQUIRED
1185
+ const created = await sw.db.insert('events', { snowflake_id: '1804000000000000000' })
1186
+ return Response.json(created.data)
1187
+ }
1188
+ ```
1189
+
1190
+ And from a developer tool call:
1191
+
1192
+ ```text
1193
+ db_query({ project_id, sql: 'UPDATE events SET snowflake_id = ? WHERE id = ?', params: ['1804000000000000000', 7] })
1194
+ ```
1195
+
1196
+ The column converts the digits on the way in because it is an integer column, so
1197
+ the row holds a whole number, not text. A column declared with no type at all
1198
+ has no affinity to convert it and would keep the text — declare such a column
1199
+ `INTEGER`, or write it as `CAST(? AS INTEGER)`. A declared `integer` column in
1200
+ `db/schema.ts` accepts that string too; text that is not a whole number is
1201
+ still a `TYPE_MISMATCH`, and digits past the storable range are still
1202
+ `DATABASE_VALUE_TOO_LARGE`.
1203
+
1204
+ A request that sends such a value as a bare JSON number is refused before
1205
+ anything is written, with `NUMBER_PRECISION_LOST` naming the field, the
1206
+ digits sent and the number that arrived (changed 2026-09-02 — before that it was
1207
+ stored rounded, silently). Whole numbers up to 9007199254740991, decimals, and
1208
+ larger whole numbers a JSON number happens to carry exactly are all unaffected.
1209
+
1210
+ In JavaScript itself — a deployed function, an SDK call, your own client — the
1211
+ same limit is the language's: a numeric literal like `9223372036854775807` in
1212
+ your source is already rounded before any platform code runs, and nothing can
1213
+ recover it from there. That is why the refusal above can only catch a value
1214
+ written as JSON text; keep ids of that size in strings end to end.
1215
+
1216
+ A database dump writes a value the database stores as a whole number as a bare
1217
+ numeric literal, so restoring it produces a whole number again whatever the
1218
+ destination column is declared as — including a column with no declared type.
1219
+ A text column holding digits stays quoted (changed 2026-09-02 — before that
1220
+ every wide whole number was quoted, and restored as text into a column with no
1221
+ type to convert it).
1222
+
1223
+ A batch — `db_batch`, `sw.db.batch`, or statements sent together — returns
1224
+ 64-bit whole numbers in the same exact string form as a single query, so the two
1225
+ paths agree on the same row.
1226
+
1227
+ One case a batch cannot return exactly: a batch that WRITES has already
1228
+ committed every statement by the time its rows are read, so a `RETURNING` row
1229
+ holding a 64-bit whole number is reported as `DATABASE_VALUE_TOO_LARGE` rather
1230
+ than rounded. The message says the changes were applied — do not retry the
1231
+ batch. Cast the column in that statement's own RETURNING list, or read the row
1232
+ back afterwards:
1233
+
1234
+ // exact, in a batch that writes
1235
+ { sql: 'INSERT INTO events (name, snowflake_id) VALUES (?, ?) RETURNING id, CAST(snowflake_id AS TEXT) AS snowflake_id', params: [name, id] }
1236
+
1237
+ ## Size boundaries
1238
+
1239
+ - SQL text is limited to 100,000 bytes per statement. Bound parameter values
1240
+ are separate from that SQL-text count; value, row and request limits still
1241
+ apply. Put data in bound parameters instead of expanding it into SQL literals.
1242
+ A larger statement returns `STATEMENT_TOO_LARGE`; split bulk statements into batches.
1243
+ - Treat 2,000,000 bytes as the documented portable maximum for a single string,
1244
+ binary value, or complete resulting row. Keep each request within that
1245
+ supported maximum: a larger value may be accepted or rejected depending on
1246
+ the encoded row, and a rejection returns `DATABASE_VALUE_TOO_LARGE`.
1247
+ - Large TEXT/BLOB values belong in `sw.fs`, with a path or URL stored in the
1248
+ row, before they approach the supported maximum.
1249
+ ## How database storage is measured
1250
+
1251
+ - Managed data grows with your app. Somewhere handles storage as it grows.
1252
+ Database storage is measured across your account under your plan: the plan
1253
+ allowance is your total database storage summed across all of your
1254
+ projects, and it scales with the plan.
1255
+ - Growth handling covers data read and written through the managed API. Very
1256
+ large tables queried with raw SQL stay in one database; use the managed API
1257
+ for datasets that need to grow.
1258
+ - **Database storage is not total app storage.** File contents
1259
+ use file storage; platform-collected application logs, analytics events,
1260
+ sign-in credentials/sessions, and search vectors use separate stores. They
1261
+ do not consume this project's database storage and have their own limits.
1262
+ Files, logs or events that your code explicitly inserts into an app table
1263
+ still count as database storage.
1264
+ - **What does count:** app rows and indexes, plus internal data kept alongside
1265
+ them. Depending on the features used, this includes the sign-in profile
1266
+ mirror, anonymous visitor sessions, persisted AI conversations/memory, and
1267
+ file-search text indexes. These count toward the project's database size.
1268
+ Keep relational records together for joins and transactions; use the file,
1269
+ logging, analytics and search primitives for their respective workloads.
1270
+ - Database usage reporting is warning-only. Successful writes through the
1271
+ public database API and deployed functions refresh the byte snapshot when
1272
+ post-write size metadata is available. Some internal maintenance writes do
1273
+ not refresh usage in the same operation; a complete paginated database
1274
+ inventory reconciles every attached project database and remains
1275
+ authoritative. An accounting refresh failure never changes an
1276
+ already-committed write into an error.
1277
+
1278
+ ## Per-user scoping — the structured builder, not raw SQL
1279
+
1280
+ Per-user scoping lives on the structured builder, never on raw SQL. There is
1281
+ no `{ user }` option — the platform derives the user from the request's
1282
+ verified credential and scopes automatically.
1283
+
1284
+ On a managed project, ordinary `sw.db.query` / `sw.db.batch` are refused.
1285
+ When a read must bypass the automatic scoping, choose server authority
1286
+ explicitly and enforce the caller policy in the function. The examples here use
1287
+ one `owner()` table, whose owner column is `user_id` (the default):
1288
+
1289
+ ```ts
1290
+ // db/schema.ts
1291
+ import { schema, table, id, text, timestamp, owner } from 'somewhere/db';
1292
+
1293
+ export default schema({
1294
+ emails: table({
1295
+ id: id(), subject: text(), created_at: timestamp({ default: 'now' }),
1296
+ }, { scope: owner() }),
1297
+ });
1298
+ ```
1299
+
1300
+ ```ts
1301
+ // api/emails/recent.ts — the caller's newest emails, as a server read scoped by hand
1302
+ export default async function recentEmails(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
1303
+ const me = await sw.auth.requireUser(req); // signed out → 401 AUTH_REQUIRED
1304
+ // Server authority skips the automatic scoping, so the function names the user itself.
1305
+ const emails = await sw.db.server.from('emails', {
1306
+ where: { user_id: me.id }, order: [['created_at', 'desc']], limit: 20,
1307
+ });
1308
+ return Response.json(emails.data);
1309
+ }
1310
+ ```
1311
+
1312
+ Passing `{ user }` to ordinary raw SQL is an error
1313
+ (`RAW_SQL_CANNOT_BE_PLATFORM_SCOPED`, 403 before transport). Passing
1314
+ `{ unscoped: true }` or `{ asServer: true }` does not opt an ordinary raw
1315
+ call into server authority; use the `sw.db.server` namespace.
1316
+
1317
+ For automatic scoping, use the structured builder on a table declared
1318
+ user-owned (an `owner()` table in `db/schema.ts`; on an older SQL-mode
1319
+ project, a `scoped` declaration recorded through the former scope API):
1320
+
1321
+ ```ts
1322
+ // api/emails.ts — auto-scoped to the request's verified user; no user argument
1323
+ export default async function emails(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
1324
+ await sw.auth.requireUser(req);
1325
+ if (req.method === 'POST') {
1326
+ await sw.db.insert('emails', { subject: 'hi' }); // owner column set by the platform
1327
+ }
1328
+ const mine = await sw.db.from('emails', { order: [['created_at', 'desc']], limit: 20 });
1329
+ return Response.json(mine.data);
1330
+ }
1331
+ ```
1332
+
1333
+ The builder composes the SQL, binds every value, and injects the owner filter
1334
+ from the verified request identity. Fail-closed:
1335
+
1336
+ - A structured query on a table with no declared intent throws
1337
+ `TABLE_INTENT_REQUIRED` before transport — declare it `scoped` (owner
1338
+ column), `shared`, or `server_only` first.
1339
+ - A scoped INSERT/UPSERT sets the owner column to the request user; a scoped
1340
+ UPDATE cannot reassign it.
1341
+ - Browser app-user database access uses the structured table API. Raw SQL at
1342
+ `/v1/db/query` and `/v1/db/batch` is refused for browser sessions.
1343
+ - There is no grace interval. Once a serving bundle carries the scope,
1344
+ violations are blocked.
1345
+
1346
+ `intent: 'server_only'` marks a table for trusted server and developer access
1347
+ only. Use `{ asServer: true }` for structured reads and `sw.db.server.*` for
1348
+ structured writes or deliberate raw reads; direct app-user access is rejected.
1349
+ Platform-managed tables such as `auth_users` are always treated as
1350
+ `server_only` and cannot be declared `scoped` or `shared`.
1351
+
1352
+ ### Builder verbs and where-shapes
1353
+
1354
+ Verbs take plain objects, not fluent chains. `from(table, options?)` and
1355
+ `count(table, options?)` take one options object. A signed-in `from` may add
1356
+ `can: true`: each row then carries `mine` (this caller created it) and
1357
+ `can.update` / `can.delete` (what this caller may change), never the owner
1358
+ column itself: `declared-data` → `which-rows-belong-to-the-signed-in-user`. Writes use
1359
+ `update(table, { set?, increment?, where? })`, `remove(table, { where })`,
1360
+ and `insert(table, values, { onConflict: 'ignore' | 'update' }?)`.
1361
+ `sw.db.update(...).set(...).where(...)` does not exist.
1362
+
1363
+ Tables for the examples:
1364
+
1365
+ ```ts
1366
+ // db/schema.ts
1367
+ import { schema, table, id, text, integer, boolean, timestamp, owner, shared, serverOnly } from 'somewhere/db';
1368
+
1369
+ export default schema({
1370
+ notes: table({
1371
+ id: id(), title: text(), done: boolean({ default: false }), created_at: timestamp({ default: 'now' }),
1372
+ }, { scope: owner() }),
1373
+ events: table({ id: id(), name: text(), starts_at: timestamp() }, { scope: shared() }),
1374
+ signups: table({ id: id(), email: text({ unique: true }) }, { scope: owner() }),
1375
+ profiles: table({ id: id(), handle: text({ unique: true }), bio: text({ default: '' }) }, { scope: owner() }),
1376
+ counters: table({ id: id(), count: integer({ default: 0 }) }, { scope: owner() }),
1377
+ inventory: table({ id: id(), name: text(), stock: integer() }, { scope: serverOnly() }),
1378
+ });
1379
+ ```
1380
+
1381
+ ```ts
1382
+ // src/db-verbs.ts — call these from a handler that has run sw.auth.requireUser(req)
1383
+ // Call write helpers only from POST handlers. Cookie-authenticated database requests
1384
+ // (sign-in or visitor) need the app origin or an origin its CORS settings allow.
1385
+ // Public write handlers still need authorization or abuse controls.
1386
+
1387
+ // reads — a bare value in where is equals, so a numeric id is { id: 42 }
1388
+ export async function readNotes(sw: SomewhereRuntimeContext) {
1389
+ const one = await sw.db.from('notes', { where: { id: 42 }, limit: 1 });
1390
+ const open = await sw.db.from('notes', {
1391
+ where: { done: false, title: { contains: 'launch' } },
1392
+ order: [['created_at', 'desc']], limit: 20,
1393
+ });
1394
+ const { data: remaining } = await sw.db.count('notes', { where: { done: false } }); // Result<number>: the count is .data
1395
+ return { one: one.data[0] ?? null, open: open.data, remaining };
1396
+ }
1397
+
1398
+ // date/number ranges — an array of single-operator conditions, AND-ed
1399
+ export async function eventsBetween(sw: SomewhereRuntimeContext, fromIso: string, toIso: string) {
1400
+ const week = await sw.db.from('events', {
1401
+ where: { starts_at: [{ gte: fromIso }, { lte: toIso }] },
1402
+ });
1403
+ return week.data;
1404
+ }
1405
+
1406
+ // idempotent writes — upsert on the table's unique column
1407
+ export async function saveSignup(sw: SomewhereRuntimeContext, email: string, handle: string, bio: string) {
1408
+ await sw.db.insert('signups', { email }, { onConflict: 'ignore' }); // keep the existing row
1409
+ await sw.db.insert('profiles', { handle, bio }, { onConflict: 'update' }); // update it with these values
1410
+ }
1411
+
1412
+ // update — set values, atomically add signed numeric deltas, or both
1413
+ export async function renameAndCount(sw: SomewhereRuntimeContext) {
1414
+ await sw.db.update('notes', { where: { id: 1 }, set: { title: 'renamed' } });
1415
+ const bumped = await sw.db.update('counters', { increment: { count: 1 }, where: { id: 1 } });
1416
+ return bumped.data[0]?.count ?? null;
1417
+ }
1418
+
1419
+ // Stock belongs to no single user (serverOnly), so the reservation runs with
1420
+ // server authority, from a handler that has already authorized the buyer.
1421
+ export async function reserve(sw: SomewhereRuntimeContext, itemId: string, qty: number): Promise<Response | null> {
1422
+ if (!Number.isSafeInteger(qty) || qty <= 0) return Response.json({ error: 'Quantity must be a positive whole number.' }, { status: 400 });
1423
+ const reserved = await sw.db.server.update('inventory', {
1424
+ increment: { stock: -qty }, where: { id: itemId, stock: { gte: qty } },
1425
+ });
1426
+ if (reserved.changes === 0) return Response.json({ error: 'not available' }, { status: 409 });
1427
+ return null;
1428
+ }
1429
+
1430
+ // remove — ONE options object: { where }
1431
+ export async function clearDone(sw: SomewhereRuntimeContext) {
1432
+ return sw.db.remove('notes', { where: { done: true } });
1433
+ // → { data: [<removed rows>], count: 2, changes: 2 }
1434
+ }
1435
+ ```
1436
+
1437
+ Updates need `set`, `increment`, or both, with no column in both.
1438
+ Increment deltas are finite, non-zero signed numbers on declared numeric
1439
+ columns. Addition happens in the scoped UPDATE: don't read then write or
1440
+ retry an unknown outcome. NULL or integer overflow leaves the row unchanged;
1441
+ `changes: 0` means scope, `where`, NULL, or overflow excluded it. One case
1442
+ differs: an ordinary caller's `update` whose only `where` is the primary key
1443
+ throws `DATA_NOT_FOUND` (404) when no row in their access matches, the answer
1444
+ a missing row gets. A caller `remove` that matches nothing returns
1445
+ `changes: 0` like any other zero-change write, the same for a missing row and
1446
+ one outside the caller's access. Server-authority calls and broader `where`
1447
+ filters return `changes: 0` too.
1448
+ `where` uses the same operators as `from`. Omitting it updates every row
1449
+ in scope. On `shared()` tables, signed-in users read all rows but update
1450
+ only their own. On `owner()` tables, reads and writes use the signed-in
1451
+ user's rows; the owner column cannot be reassigned. Update and remove return
1452
+ `{ data, count, changes }`: `data` contains the touched rows.
1453
+
1454
+ Row values from `from`, `insert`, `update`, `remove`, `tx`, and
1455
+ `aggregate` group keys come back in the types `db/schema.ts` declares: a
1456
+ `boolean()` column is `true`/`false`, a `json()` column is its parsed value,
1457
+ a `blob()` column is an array of bytes — the same values the generated
1458
+ `somewhere:data` client gets for that row, so no conversion code is needed.
1459
+ Aggregate group keys are typed as `string | number | boolean | null` in
1460
+ TypeScript. Narrow a text key with `typeof row.link_id === 'string'` before
1461
+ using it as a string key, for example in `Map<string, string>.get()`.
1462
+ `sw.db.query` / `sw.db.server.query` rows are exactly as stored (0/1, JSON
1463
+ text). A stored value that is not its declared type is refused with
1464
+ `DATA_VALUE_INVALID` naming the column.
1465
+
1466
+ <!-- BEGIN START PLATFORM CARD -->
1467
+ ## Database rows and app responses
1468
+
1469
+ Function-side `sw.db` results hold rows in `.data` (an insert's row is `.data[0]`);
1470
+ handlers choose their JSON shape. A caller's primary-key update raises
1471
+ `DATA_NOT_FOUND` (404) for a missing or denied row; remove returns `changes: 0`.
1472
+ Broader or server-authority writes can return empty `.data`.
1473
+
1474
+ For ordinary calls on `owner()` tables, ownership comes from the request,
1475
+ never browser-supplied `user_id`. Cookie helpers establish browser sessions.
1476
+ `sw.auth.requireUser(req)` checks sign-in; enforce any additional endpoint
1477
+ rule separately.
1478
+ <!-- END START PLATFORM CARD -->
1479
+
1480
+ Two argument mistakes are worth naming, because the errors read differently
1481
+ than the mistake:
1482
+
1483
+ - A THIRD argument — the `update(table, values, { where })` shape other
1484
+ query builders use — throws `SCOPE_ARGUMENT_REMOVED` (400). Despite the
1485
+ wording, it does not mean you passed a scope: it means the verb takes
1486
+ exactly two arguments now. Merge your values into `set` and your filter
1487
+ into `where` in the ONE options object; do not just delete the extra
1488
+ argument, which would leave a table-wide update.
1489
+ - A wrong option NAME throws `VALIDATION_ERROR` naming the accepted set,
1490
+ e.g. `sw.db.update: unknown option "values". Allowed: set, increment, where.`
1491
+
1492
+ Where operators, per column: a bare value (equals), `null` (IS NULL),
1493
+ `{ not: null }` (IS NOT NULL), or a single-operator object — `eq`,
1494
+ `ne`, `lt`, `lte`, `gt`, `gte`, `like`, `in`, `contains`,
1495
+ `startsWith`, `endsWith`. One operator per condition object; an array of
1496
+ condition objects on one column AND-s them (the range form above).
1497
+
1498
+ `contains` / `startsWith` / `endsWith` compose the search pattern for
1499
+ you: the value is data, so `%` and `_` inside it match literally — a
1500
+ user-typed search string is safe to pass as-is, at any length. `like` takes a
1501
+ caller-authored pattern instead (its wildcards are your own); the value is
1502
+ still bound, never spliced into the SQL, and a `like` pattern is limited to
1503
+ 50 bytes (the database refuses longer patterns): search for a text with
1504
+ `contains`, `startsWith` or `endsWith` instead.
1505
+
1506
+ ### Related rows in server functions
1507
+
1508
+ Two directions, both declared in `db/schema.ts` and both proven at deploy
1509
+ against a real foreign key:
1510
+
1511
+ ```ts
1512
+ // db/schema.ts
1513
+ import { schema, table, id, text, boolean, owner, hasMany, belongsTo } from 'somewhere/db';
1514
+
1515
+ export default schema({
1516
+ projects: table({ id: id(), name: text(), archived: boolean({ default: false }) }, {
1517
+ scope: owner(),
1518
+ relations: { tasks: hasMany('tasks', 'project_id') },
1519
+ }),
1520
+ tasks: table({ id: id(), title: text(), done: boolean({ default: false }),
1521
+ project_id: text({ references: 'projects' }) }, {
1522
+ scope: owner(),
1523
+ relations: { project: belongsTo('projects', 'project_id') },
1524
+ }),
1525
+ });
1526
+ ```
1527
+
1528
+ `hasMany(childTable, foreignKey)` goes on the parent: the child's
1529
+ `foreignKey` column must declare `references` to the parent, and the
1530
+ parent must have an `id()` column. `belongsTo(parentTable, foreignKey)`
1531
+ is the inverse and goes on the table that holds the key. A relation name
1532
+ cannot be a column name on the same table. Then:
1533
+
1534
+ ```ts
1535
+ // api/projects.ts — the signed-in user's projects and tasks, with relations
1536
+ export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
1537
+ await sw.auth.requireUser(req) // signed out → 401 AUTH_REQUIRED
1538
+ const projects = await sw.db.from('projects', { include: ['tasks'], limit: 20 });
1539
+ // Each project in projects.data has a tasks array (possibly empty).
1540
+ const tasks = await sw.db.from('tasks', { include: ['project'], limit: 20 });
1541
+ // Each task in tasks.data has a flat project row — or null.
1542
+ const withOpenTasks = await sw.db.from('projects', { has: { tasks: { done: false } }, limit: 20 });
1543
+ // Only projects with at least one accessible matching task.
1544
+ const inActive = await sw.db.from('tasks', { has: { project: { archived: false } } });
1545
+ // Only tasks whose parent the caller can read and that matches.
1546
+ return Response.json({ projects: projects.data, tasks: tasks.data, withOpenTasks: withOpenTasks.data, inActive: inActive.data });
1547
+ }
1548
+ ```
1549
+
1550
+ The platform composes the relationship and separately applies each table's
1551
+ scope, including membership: a relation key shapes the relationship and is
1552
+ never trusted for access. A `hasMany` include nests an array; a
1553
+ `belongsTo` include nests the single parent row, and a parent the caller
1554
+ may not read — or a null key — nests `null`: the root row is never dropped
1555
+ and no parent column leaks. A related row the caller cannot access cannot
1556
+ make `has` match. With explicit `columns`, include the key column
1557
+ (`project_id` for `belongsTo`, `id` for `hasMany`) so rows can be
1558
+ matched; the call refuses otherwise. `include` fetches related rows
1559
+ separately after reading the root rows; it does not promise a single
1560
+ snapshot. There is no caller-authored join condition, and a name that is not
1561
+ declared fails with `RELATION_NOT_DECLARED`. In a browser use the
1562
+ paginated `data.projects.relations.tasks.list(projectId)` operation for
1563
+ children and an ordinary `data.projects.get(task.project_id)` for a parent.
1564
+
1565
+ ### Aggregates — sw.db.aggregate
1566
+
1567
+ Count, sum, average, minimum and maximum, optionally grouped, composed by the
1568
+ platform with the same row permissions an ordinary read gets — so the numbers
1569
+ describe exactly the rows the caller may read, never the whole table:
1570
+
1571
+ ```ts
1572
+ // db/schema.ts
1573
+ import { schema, table, id, text, integer, boolean, timestamp, owner } from 'somewhere/db';
1574
+
1575
+ export default schema({
1576
+ orders: table({
1577
+ id: id(), amount: integer(), status: text(), archived: boolean({ default: false }),
1578
+ created_at: timestamp({ default: 'now' }),
1579
+ }, { scope: owner() }),
1580
+ });
1581
+ ```
1582
+
1583
+ ```ts
1584
+ // api/orders/summary.ts — the signed-in user's order totals
1585
+ export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
1586
+ await sw.auth.requireUser(req) // signed out → 401 AUTH_REQUIRED
1587
+ const totals = await sw.db.aggregate('orders', { count: true, sum: 'amount' });
1588
+ // totals.data = [{ count: 12, sum_amount: 4800 }] — ungrouped is always exactly one row
1589
+ const byStatus = await sw.db.aggregate('orders', {
1590
+ count: true, avg: 'amount', max: 'created_at',
1591
+ groupBy: ['status'],
1592
+ where: { archived: false },
1593
+ having: { count: { gte: 2 } },
1594
+ order: [['count', 'desc']],
1595
+ limit: 20,
1596
+ });
1597
+ // byStatus.data = [{ status: 'paid', count: 9, avg_amount: 410, max_created_at: '…' }, …]
1598
+ // byStatus.count = the number of groups returned
1599
+ return Response.json({ totals: totals.data[0], byStatus: byStatus.data });
1600
+ }
1601
+ ```
1602
+
1603
+ Signature:
1604
+
1605
+ sw.db.aggregate(table, { count?: true, sum?, avg?, min?, max?, groupBy?, where?, has?, having?, order?, limit?, asServer? })
1606
+ sw.db.server.aggregate(table, { …the same options, without asServer })
1607
+
1608
+ - `count: true` counts rows and takes no column; `sum` / `avg` /
1609
+ `min` / `max` each name ONE column. At least one is required.
1610
+ - Result keys are composed by the platform, never by the caller: `count`,
1611
+ `sum_<column>`, `avg_<column>`, `min_<column>`, `max_<column>`.
1612
+ The result is always `{ data: rows, count }` — `data` is an array of
1613
+ group rows even when ungrouped, and the envelope's `count` is the number
1614
+ of rows RETURNED (groups); the row count you asked for lives inside each
1615
+ row under `count`.
1616
+ - `sum` and `avg` need a column declared `integer` or `number` in
1617
+ `db/schema.ts` — another type is refused with `TYPE_MISMATCH`, and a
1618
+ table outside the schema file cannot be summed or averaged
1619
+ (`TABLE_NOT_MANAGED`). `json` and `blob` columns cannot be
1620
+ aggregated or grouped.
1621
+ - `groupBy` takes up to 4 declared columns, including a managed owner column
1622
+ such as `user_id`; do not redeclare that column. For example,
1623
+ `sw.db.server.aggregate('notes', { count: true, groupBy: ['user_id'] })`
1624
+ counts by owner after server authorization. On an `owner()` table, ordinary `sw.db.aggregate` applies the caller's scope
1625
+ first, so it does not count other users' rows.
1626
+ A grouped column cannot share a name with a result key.
1627
+ - `having` filters result keys, not columns, with one of `eq`, `ne`,
1628
+ `lt`, `lte`, `gt`, `gte` per condition (`{ count: { gte: 2 } }`).
1629
+ - `order` may name only a `groupBy` column or a result key. `where`
1630
+ and `has` take the same shapes as `from`, so a relation filter
1631
+ composes the related table's own scope into the summary.
1632
+ - Row permissions compose as for `from`: an `owner()` table needs a
1633
+ signed-in request (`AUTH_REQUIRED` otherwise); `{ asServer: true }` or
1634
+ `sw.db.server.aggregate` reads across users after you authorize the
1635
+ caller. The generated browser client offers `aggregate` on every table
1636
+ with a `read` grant (`docs({ topic: 'declared-data' })`).
1637
+
1638
+ ### Live lists — sw.rooms.live
1639
+
1640
+ A list that stays fresh in open tabs is declared with
1641
+ `sw.rooms.live(name, sw.db.from(...))` and followed in the browser with
1642
+ `watchLive` from `/__sw/rooms/client.js`. The rows come from this same
1643
+ structured read, under the same access rules. The contract (accepted shapes,
1644
+ delivery, recovery and `live_delivery`) is in `docs({ topic: 'rooms' })`
1645
+ under "Live lists".
1646
+
1647
+ ### Upserts — insert with onConflict
1648
+
1649
+ `insert(table, values, { onConflict: 'ignore' | 'update' })` makes a write
1650
+ idempotent against the table's declared unique keys (`id()` and `unique`):
1651
+ `'ignore'` keeps an existing row untouched, `'update'` updates it with exactly
1652
+ the values you passed. You never name the key; whichever declared unique key
1653
+ matches picks the row. `sw.db.tx` insert intents take the same `options`.
1654
+
1655
+ An upsert follows the table's access rule as one insert-or-update, checked in
1656
+ the same database statement as the write. It works on every table a signed-in
1657
+ caller writes: `owner()`, `shared()`, `member()`, `group()`, `parent()`,
1658
+ `anyOf(owner(), …)` including `grant()`, and `allOf()`.
1659
+
1660
+ - A new row is placed exactly as `insert` places it: the owner is filled by
1661
+ the platform, and the group, membership key or parent you name must be one
1662
+ you may create rows in.
1663
+ - `'update'` also needs update rights on the existing row: your own row, a
1664
+ team row your membership or role may update, or a row a
1665
+ `['read', 'update']` grant shares with you. Any other existing row (another
1666
+ user's, one in a group you are not in, one shared read-only) refuses the
1667
+ whole call with 403 `POLICY_AUTHORITY_REQUIRED` and writes nothing. In
1668
+ `sw.db.tx` the whole transaction rolls back. This is an update permission
1669
+ check. An ordinary insert that hits a duplicate returns 409 `DATA_CONFLICT`.
1670
+ - The owner, group, membership key, parent link and a shared row's `id` never
1671
+ change through an upsert. Naming a different one from the existing row's is
1672
+ refused the same way; use `update` to move a row.
1673
+ - `'update'` on a table whose rule never grants update, such as
1674
+ `member({ ..., operations: ['read', 'create'] })`, is refused with 403
1675
+ `POLICY_OPERATION_NOT_ALLOWED` or `MEMBER_OPERATION_NOT_ALLOWED` before
1676
+ anything runs. `'ignore'` needs create rights only.
1677
+ - A per-row `grant()` shares table accepts `'ignore'` only, a table named
1678
+ `excluded` cannot take `'update'`, and an insert with `idempotencyKey`
1679
+ takes no `onConflict`. Generated function types report
1680
+ both, and `'update'` on a table without update rights, as type errors.
1681
+ - The browser data client has no upsert: `create` takes only values, and a
1682
+ request with `onConflict` is refused with 400 `DATA_INPUT_INVALID`.
1683
+ De-duplicating imports run in a function, with `sw.db` or `sw.db.tx` as the
1684
+ signed-in user (`docs({ topic: 'recipe-csv-import' })`), or in a job with
1685
+ `sw.db.server`.
1686
+ - `sw.db.server.insert` and `sw.db.server.tx` write with server authority:
1687
+ the rule is not applied, so authorize the caller yourself.
1688
+
1689
+ ### Cross-user reads — explicit server authority
1690
+
1691
+ `sw.db.from`, `sw.db.count` and `sw.db.aggregate` with
1692
+ `{ asServer: true }` — or `sw.db.server.from / count / aggregate` —
1693
+ are the sanctioned way for trusted server code to read across users on a
1694
+ user-owned table — admin screens, aggregates, background jobs. Server mode never impersonates a request user. It deliberately bypasses
1695
+ per-row ownership but does not bypass the intent requirement (an undeclared
1696
+ table still refuses). It exists only on the read verbs and is not a browser
1697
+ operation. Without it, an owner-table read with no verified
1698
+ signed-in user fails `AUTH_REQUIRED` (401) with an error naming
1699
+ `{ asServer: true }` as the sanctioned server-mode path.
1700
+
1701
+ For an admin report or leaderboard over declared tables, authorize the caller
1702
+ and use the server read verbs: `sw.db.server.aggregate` for counts, sums and
1703
+ groups, and `include` on declared relations for related rows. Raw SQL through
1704
+ `sw.db.server.query` reads only the separate SQL database on a project created
1705
+ today, not these tables.
1706
+
1707
+ ```ts
1708
+ // api/admin/email-counts.ts — admin endpoint: emails across every user
1709
+ export default async function emailCounts(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
1710
+ await sw.auth.requireRole(req, 'admin'); // signed out → 401; anyone else → 403 FORBIDDEN
1711
+ // Server authority reads across users; without it this owner() table counts only the caller's rows.
1712
+ const allCounts = await sw.db.server.aggregate('emails', { count: true });
1713
+ return Response.json(allCounts.data[0]);
1714
+ }
1715
+ ```
1716
+
1717
+ The platform never scopes or rewrites server-authority SQL. Ordinary raw calls
1718
+ cannot be upgraded with an option; `{ unscoped: true }` and
1719
+ `{ asServer: true }` are refused in managed mode. Raw SQL is also refused for
1720
+ app-user browser requests; place it in an authorized server function.
1721
+
1722
+ ## Access rules for SQL-mode tables
1723
+
1724
+ Access rules are set in `db/schema.ts` and take effect on deploy.
1725
+ `POST /v1/db/scopes`, `DELETE /v1/db/scopes/:table` and
1726
+ `sw.db.scope(table, opts)` return HTTP 410 `SCOPE_API_WITHDRAWN`.
1727
+ `DELETE /v1/db/scopes` returns HTTP 405 `METHOD_NOT_ALLOWED`. An existing SQL-mode
1728
+ project that cannot adopt a schema file is told it needs a migration by
1729
+ Somewhere. `db_scope_list` / `sw.db.scope.list()` still return the recorded
1730
+ declarations, beside `live_rules`, the rules the live version serves.
1731
+
1732
+ Scope declarations recorded earlier stay baked into the function bundles that
1733
+ carry them; what a release serves comes from its own verified rules.
1734
+
1735
+ ## Placeholders: ? (positional) or $1, $2, ... (numbered)
1736
+ Both styles work — pick one per statement, don't mix them.
1737
+
1738
+ ```ts
1739
+ // api/admin/rename-user.ts — SQL-mode project; body { id, name }, admins only
1740
+ export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
1741
+ if (req.method !== 'POST') return new Response('Method not allowed', { status: 405 })
1742
+ await sw.auth.requireUser(req, { role: 'admin' }) // signed out → 401, not an admin → 403
1743
+ const { id, name } = await req.json() as { id?: unknown; name?: unknown }
1744
+ if (typeof id !== 'string' || typeof name !== 'string') return Response.json({ error: 'id and name' }, { status: 400 })
1745
+ // Numbered placeholders — params are reordered to match the $N indexes.
1746
+ // Useful when the same value appears in multiple positions.
1747
+ const updated = await sw.db.query(
1748
+ 'UPDATE users SET name = $2, updated_by = $2 WHERE id = $1',
1749
+ [id, name]
1750
+ )
1751
+ return Response.json({ changes: updated.changes })
1752
+ }
1753
+ ```
1754
+
1755
+ Mixing `?` and `$N` in one statement is rejected with `VALIDATION_ERROR`.
1756
+
1757
+ ## sw.db.tx(intents) — all-or-nothing composed writes
1758
+
1759
+ One call, one to one hundred closed write intents, applied as a single atomic
1760
+ batch: every intent is validated and rendered before anything is written, and
1761
+ either all of them commit or none do. Each intent is exactly one of the
1762
+ existing composed writes with the same table, value and `where` rules, and
1763
+ the same ownership binding from the request:
1764
+
1765
+ ```ts
1766
+ // Caller-supplied ids: nothing inside a batch can read another intent's result.
1767
+ const orderId = crypto.randomUUID();
1768
+ const r = await sw.db.tx([
1769
+ { op: 'insert', table: 'orders', values: { id: orderId, status: 'pending', amount_cents: 4200 } },
1770
+ { op: 'insert', table: 'order_items', values: { id: crypto.randomUUID(), order_id: orderId, sku: 'tee-m', qty: 1 } },
1771
+ { op: 'update', table: 'carts', set: { status: 'converted' }, where: { id: cartId, status: 'open' } },
1772
+ { op: 'remove', table: 'cart_items', where: { cart_id: cartId } },
1773
+ ]);
1774
+ // r is index-aligned with the intents; each entry is the ordinary write result:
1775
+ // { data, error: null, count, changes, last_row_id } (+ live_delivery when a live view is affected; see docs({ topic: 'live' }))
1776
+ ```
1777
+
1778
+ What it is not:
1779
+
1780
+ - **Not conditional fulfilment.** A zero-match `update` or `remove` is a
1781
+ successful no-op and the rest of the batch still commits. Read the returned
1782
+ rows per entry afterwards if you need to know (`data` / `count` are the
1783
+ matched-row receipt; `changes` is the execution-wide count and can exceed
1784
+ the matched rows when a trigger fires, so use it as diagnostic only). A
1785
+ batch never guarantees that a guarded transition matched. For "move the order to paid only if it is
1786
+ still pending, and record that", use the single guarded statement on the
1787
+ order row (docs({ topic: 'payments' })) — not a batch that would commit the
1788
+ record even when the transition matched nothing.
1789
+ - **No reads, no result references.** Intents cannot read, and a later intent
1790
+ cannot use an earlier one's generated id. Supply stable ids yourself, as
1791
+ above; defaults and returned rows are still the database's.
1792
+ - **Closed shapes only.** `insert` takes `values` and optional
1793
+ `options: { onConflict: 'ignore' | 'update' }`; `update` takes `set` and
1794
+ `where`; `remove` takes `where`. No raw SQL, no callback, no
1795
+ `asServer`, no project id inside an intent, no expected-change assertions.
1796
+ Anything else is a `VALIDATION_ERROR` before any write.
1797
+ - **Membership is checked inside the batch.** An insert into a `member()`
1798
+ table is allowed only when the signed-in user belongs to the row's group as
1799
+ the transaction sees it, including a membership row an earlier intent in the
1800
+ same batch wrote. Otherwise the whole batch rolls back with 403
1801
+ `MEMBERSHIP_REQUIRED` (`POLICY_AUTHORITY_REQUIRED` for `anyOf` and
1802
+ `parent` tables). Updates and removes reach only rows the caller may write,
1803
+ as single writes do: one that targets rows the caller may not change, or a
1804
+ move to a parent the caller may not write, matches no rows. It reports
1805
+ `changes: 0`, raises no error and does not roll back the other intents.
1806
+ Check each entry's `changes` when that matters.
1807
+ - **Ownership binds the same way as single writes.** Plain `owner()`
1808
+ requires a signed-in user; without one, the batch refuses with
1809
+ `AUTH_REQUIRED` before any write. Only a table declaring
1810
+ `owner({ visitors: true })` also accepts a verified visitor identity.
1811
+ Each intent checks its own table's declaration: enabling visitors on one
1812
+ table does not grant anonymous access to another. Project creation or
1813
+ claiming does not opt tables into visitor access. For an authorized write on
1814
+ behalf of another owner, keep the declared scope and use `sw.db.server.tx`.
1815
+ Do not move app-read/write data to serverOnly() and hand-write its access: declare
1816
+ who may read/write it. Reserve server-only tables for server-touched state,
1817
+ protected ledgers, or the undeclarable-rule cases listed above.
1818
+
1819
+ Outcomes, four distinguishable cases:
1820
+
1821
+ - **Refused before execution — nothing written.** Shape or value validation
1822
+ (`VALIDATION_ERROR`), and isolation or readiness refusals
1823
+ (`DRAFT_DB_NOT_ISOLATED`, `DEV_DB_NOT_ISOLATED`, `DB_CONNECTION_NOT_READY`)
1824
+ happen before the batch is sent. Fix the cause and send again.
1825
+ - **Rolled back — nothing kept.** A confirmed `CONSTRAINT_VIOLATION` inside
1826
+ the batch rolls every intent back; the error names the constraint. So does
1827
+ a refused member insert (`MEMBERSHIP_REQUIRED`, 403).
1828
+ - **Committed, then refused on the way back — do not replay.**
1829
+ `DATABASE_VALUE_TOO_LARGE` can also arrive AFTER the batch committed: a
1830
+ returned row holds an integer wider than JavaScript can carry exactly. Its
1831
+ message says the changes were applied. Honour it: never send the batch
1832
+ again; read the column back as text (`CAST(... AS TEXT)`) instead.
1833
+ - **Unknown — not a rollback.** If the platform cannot confirm what happened,
1834
+ it answers `DB_BATCH_OUTCOME_UNKNOWN`. That is neither a rollback receipt
1835
+ nor an invitation to replay; check state before deciding.
1836
+
1837
+ A batch is reported successful only with a complete receipt for every
1838
+ intent; zero-match writes are legitimate successes, missing or partial
1839
+ provider results never are.
1840
+
1841
+ ## sw.db.server.tx(intents) — authorized cross-user writes
1842
+
1843
+ Use the same closed insert, update and remove intents as `sw.db.tx`, with
1844
+ server authority for the entire batch. Authorize the caller or verify the
1845
+ scheduled invocation before calling it. This bypasses declared row permissions;
1846
+ it does not require changing an `owner()` table into `serverOnly()`.
1847
+
1848
+ For an owner-scoped insert, explicitly supply the managed owner column
1849
+ (`user_id`, or the column named by `owner({ column })`) from a trusted identity
1850
+ or an authorized lookup. Caller-scoped `sw.db.tx` binds ownership from the
1851
+ request instead. Server authority never makes an untrusted owner ID safe.
1852
+
1853
+ Build a mutable list as `const intents: SomewhereDbWriteIntent[] = []`, then
1854
+ push `{ op: 'insert', table, values }`, `{ op: 'update', table, set, where }`
1855
+ or `{ op: 'remove', table, where }` before `await sw.db.server.tx(intents)`.
1856
+ `SomewhereDbWriteIntent` is available in the generated runtime declarations;
1857
+ no package import is needed. Each step is checked against `db/schema.ts` like
1858
+ the matching single call: a declared table name, its columns and value types,
1859
+ and its required columns. For caller-scoped `sw.db.tx`, type the list as
1860
+ `SomewhereDbCallerWriteIntent[]`, which never names the owner column. With no
1861
+ declared tables, any table name and values are accepted. The parameter accepts
1862
+ a readonly list, so `Parameters<typeof sw.db.server.tx>[0]` is a readonly
1863
+ input type, not the mutable accumulator type.
1864
+
1865
+ Insert accepts `options: { onConflict: 'ignore' | 'update' }`; update also
1866
+ accepts `increment`. The batch has no callback, reads, result references,
1867
+ per-intent authority switch or conditional-success assertion. Supply IDs
1868
+ up front for linked rows. A zero-match update still commits the batch.
1869
+ Assert the matching receipt's `count` after the call to check whether it
1870
+ matched. To make the write conditional before commit, express the invariant
1871
+ as a database constraint, or express the whole transition in one guarded
1872
+ update. Throwing after inspecting a receipt cannot roll the batch back.
1873
+
1874
+ ## sw.db.batch(statements)
1875
+ Run multiple statements as one atomic transaction.
1876
+ If ANY statement fails, ALL roll back. All-or-nothing.
1877
+
1878
+ This ordinary raw batch is for SQL-mode projects. On an older shared database it is refused
1879
+ with `MANAGED_RAW_SQL_REQUIRES_SERVER_AUTHORITY`. Use `sw.db.tx` or
1880
+ `sw.db.server.tx` for declared operations. `sw.db.server.batch` is the
1881
+ server raw batch: with a separate SQL database it writes only that database;
1882
+ on an older shared database it is read-only (`MANAGED_RAW_WRITE_FORBIDDEN`).
1883
+
1884
+ ```ts
1885
+ // api/account/delete.ts — SQL-mode project: remove the signed-in user's data in one transaction
1886
+ export default async function deleteAccountData(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
1887
+ if (req.method !== 'POST') return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
1888
+ const me = await sw.auth.requireUser(req);
1889
+ const results = await sw.db.batch([
1890
+ { sql: 'DELETE FROM sessions WHERE user_id = ?', params: [me.id] },
1891
+ { sql: 'DELETE FROM posts WHERE author_id = ?', params: [me.id] },
1892
+ { sql: 'DELETE FROM users WHERE id = ?', params: [me.id] },
1893
+ ]);
1894
+ // results = [{ data: [], changes: 3, … }, { data: [], changes: 12, … }, { data: [], changes: 1, … }]
1895
+ // If the third DELETE failed, the first two would also roll back.
1896
+ return Response.json({ deleted: results.map((r) => r.changes) });
1897
+ }
1898
+ ```
1899
+
1900
+ ## sw.db.migrate — removed from functions; migrate as the developer
1901
+ Run DDL (CREATE TABLE, ALTER TABLE, CREATE INDEX) with DEVELOPER credentials —
1902
+ NOT from inside a deployed function. `sw.db.migrate(...)` was removed from the
1903
+ function runtime: a handler that calls it gets an error. Runtime DDL would
1904
+ run on every request, leave no migration history, and create tables the
1905
+ per-user protections don't cover until declared scoped. Migrate once, outside
1906
+ the request path, with
1907
+ `somewhere call db_migrate '<json>'` from a shell, the `db_migrate` MCP
1908
+ tool without a shell. Functions then read and write rows with `sw.db.query`. A CREATE TABLE inside a handler throws `DDL_NOT_ALLOWED_IN_FUNCTION`.
1909
+
1910
+ For tables declared in `db/schema.ts` there is no migration step at all —
1911
+ edit the file and deploy; `db_migrate` on a managed table returns
1912
+ `SCHEMA_MANAGED` (migrations on tables not declared in the file are
1913
+ unaffected).
1914
+
1915
+ // developer-side — db_migrate MCP tool (NOT inside a function):
1916
+ db_migrate({ project_id, sql: `
1917
+ CREATE TABLE IF NOT EXISTS users (
1918
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1919
+ email TEXT NOT NULL UNIQUE,
1920
+ name TEXT,
1921
+ created_at TEXT DEFAULT (datetime('now'))
1922
+ );
1923
+ CREATE INDEX IF NOT EXISTS idx_users_email ON users(email);
1924
+ ` })
1925
+
1926
+ When a project keeps raw SQL tables in a separate database, preview migrations
1927
+ return `RAW_PREVIEW_DATABASE_NOT_READY`. Rehearse raw SQL DDL on a separate
1928
+ test project. On projects with a raw SQL preview copy, target that copy
1929
+ explicitly:
1930
+
1931
+ db_migrate({ project_id, target: "preview",
1932
+ preview_session_id: "draft_...", preview_id: "rel_...", sql: `
1933
+ CREATE TABLE IF NOT EXISTS rehearsal (id INTEGER PRIMARY KEY);
1934
+ ` })
1935
+
1936
+ Omit target fields to use production. A preview target requires
1937
+ `preview_session_id`; `preview_id` is an optional exact-candidate guard.
1938
+ Conflicting target names return `DATABASE_TARGET_AMBIGUOUS`; an unknown,
1939
+ closed, expired, or mismatched preview returns `PREVIEW_TARGET_INVALID`.
1940
+ Neither case falls back to production. Preview-targeted DDL persists across
1941
+ candidates in that preview session, never merges into production, and is
1942
+ discarded when the session is closed, promoted, or expires.
1943
+
1944
+ ## sw.db.tables()
1945
+ List all tables in the database. Returns string[].
1946
+
1947
+ ```ts
1948
+ // api/admin/tables.ts — list the database's tables (SQL-mode project, admins only)
1949
+ export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
1950
+ await sw.auth.requireUser(req, { role: 'admin' }) // signed out → 401, not an admin → 403
1951
+ const tables = await sw.db.tables()
1952
+ // tables = ['users', 'posts', 'sessions']
1953
+ return Response.json(tables)
1954
+ }
1955
+ ```
1956
+
1957
+ ## SQL dialect
1958
+ The default database keeps its own documented engine semantics. A documented
1959
+ Postgres-flavored syntax subset is auto-translated:
1960
+ NOW() → datetime('now')
1961
+ TRUE/FALSE → 1/0
1962
+ ILIKE → LIKE (case-insensitive by default)
1963
+ SERIAL → INTEGER PRIMARY KEY AUTOINCREMENT
1964
+ BOOLEAN → INTEGER
1965
+ RETURNING * → supported
1966
+
1967
+ Translation changes syntax, not engine semantics. In particular:
1968
+
1969
+ - `SELECT 1 / 0` returns `NULL` rather than a division-by-zero error.
1970
+ - Ascending order places `NULL` first unless `NULLS LAST` is explicit.
1971
+ - `LIKE` is case-insensitive for ASCII by default.
1972
+ - `UPDATE … RETURNING` and `DELETE … RETURNING` are supported.
1973
+
1974
+ ## Common patterns
1975
+
1976
+ Structured calls work on every project, including new (managed) ones:
1977
+
1978
+ The examples use this schema:
1979
+
1980
+ ```ts
1981
+ // db/schema.ts
1982
+ import { schema, table, id, text, boolean, timestamp, owner, shared, belongsTo } from 'somewhere/db';
1983
+
1984
+ export default schema({
1985
+ authors: table({ id: id(), name: text() }, { scope: shared() }),
1986
+ posts: table({
1987
+ id: id(), title: text(), published: boolean({ default: false }),
1988
+ author_id: text({ references: 'authors' }), created_at: timestamp({ default: 'now' }),
1989
+ }, { scope: shared(), relations: { author: belongsTo('authors', 'author_id') } }),
1990
+ // Each user has one row per key: the owner column pairs with key.
1991
+ settings: table({ id: id(), key: text(), value: text() }, { scope: owner(), unique: [['user_id', 'key']] }),
1992
+ });
1993
+ ```
1994
+
1995
+ ```ts
1996
+ // api/posts.ts — a page of posts and the total (signed-in readers)
1997
+ export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
1998
+ await sw.auth.requireUser(req) // signed out → 401 AUTH_REQUIRED
1999
+ const pageSize = 20
2000
+ const raw = new URL(req.url).searchParams.get('page') ?? '1'
2001
+ const offset = (Number(raw) - 1) * pageSize
2002
+ if (!/^[1-9][0-9]*$/.test(raw) || !Number.isSafeInteger(offset)) return Response.json({ error: 'page must be a positive whole number' }, { status: 400 })
2003
+ // Paginated list
2004
+ const page = await sw.db.from('posts', {
2005
+ where: { published: true }, order: [['created_at', 'desc']], limit: pageSize, offset,
2006
+ })
2007
+ // Count — the number is .data
2008
+ const { data: total } = await sw.db.count('posts', { where: { published: true } })
2009
+ return Response.json({ posts: page.data, total })
2010
+ }
2011
+ ```
2012
+
2013
+ ```ts
2014
+ // api/settings/theme.ts — save the signed-in user's theme
2015
+ export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
2016
+ if (req.method !== 'POST') return new Response('Method not allowed', { status: 405 })
2017
+ await sw.auth.requireUser(req) // signed out → 401 AUTH_REQUIRED
2018
+ // Upsert on the (user_id, key) unique group
2019
+ await sw.db.insert('settings', { key: 'theme', value: 'dark' }, { onConflict: 'update' })
2020
+ return Response.json({ saved: true })
2021
+ }
2022
+ ```
2023
+
2024
+ ```ts
2025
+ // api/admin/posts-with-authors.ts — published posts with their author, for admins only
2026
+ export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
2027
+ await sw.auth.requireUser(req, { role: 'admin' }) // signed out → 401, not an admin → 403
2028
+ // The declared belongsTo relation replaces a raw JOIN: each post carries its
2029
+ // author row (or null) under author.
2030
+ const postsWithAuthors = await sw.db.from('posts', {
2031
+ where: { published: true }, include: ['author'], order: [['created_at', 'desc']], limit: 50,
2032
+ })
2033
+ return Response.json(postsWithAuthors.data)
2034
+ }
2035
+ ```
2036
+
2037
+ ## After a successful write — fan out instead of hand-rolling infrastructure
2038
+
2039
+ The database is the durable source of truth. Once a write commits, reach for
2040
+ the built-in that matches the next moment:
2041
+
2042
+ - A composed, bounded list should update while users are watching → declare it
2043
+ server-side with `sw.rooms.live(name, sw.db.from(...))` and follow it with
2044
+ `watchLive` (`docs({ topic: 'rooms' })`, "Live lists"); raw SQL writes do
2045
+ not notify it.
2046
+ - The action is a product event you will want to count →
2047
+ `sw.analytics.track(...)` or `analytics_track(...)`.
2048
+ - Searchable content was created or edited → `sw.search.upsert(...)`
2049
+ or `search_upsert(...)`; the platform generates embeddings. Use
2050
+ `ai_embed` only when you need custom vectors for clustering or your own
2051
+ similarity math.
2052
+ - Follow-up work runs in the background, with or without a status you read
2053
+ back → `sw.jobs.create(...)` or `job_create(...)`.
2054
+
2055
+ Keep the database commit separate from these downstream calls and make the
2056
+ downstream handler idempotent. Related topics: `live`, `analytics`,
2057
+ `search`, and `sw.jobs`.
2058
+
2059
+ ## Performance and query duration
2060
+ Composed calls — `sw.db.from` / `count` / `aggregate` / `insert` /
2061
+ `update` / `remove` / `tx` — run on the project's own database
2062
+ connection and are the ordinary path. `sw.db.server.query` and
2063
+ `sw.db.server.batch` reach the database over a separate read-only route and
2064
+ take more network requests per statement, so reach for a composed call first and keep
2065
+ raw SQL for what it cannot express. Independent raw reads belong in ONE
2066
+ `sw.db.server.batch` rather than several awaited `sw.db.server.query`
2067
+ calls; dependent ones stay sequential. Independent COMPOSED reads started
2068
+ without an await between them are already sent as one round trip.
2069
+ `docs({ topic: 'speed' })` has the whole picture.
2070
+
2071
+ Per-query latency is not fixed. Total time can include first-touch
2072
+ activation, placement/transport, database scheduling, elapsed retry backoff, and SQL
2073
+ engine time. Slow-query logs separate `total_ms`, provider-reported
2074
+ `engine_ms`, residual `non_engine_ms`, execution path, placement, and retry
2075
+ evidence. Engine and residual fields stay null when provider duration evidence
2076
+ is missing or partial, and logs contain only a bounded statement kind rather
2077
+ than SQL text or values. Requested retry backoff is identified as a configured
2078
+ wait budget, separate from measured time. To judge whether the SQL itself was
2079
+ slow, read the measured `engine_ms`; residual time also covers the other
2080
+ stages above.
2081
+
2082
+ The database enforces a 30-second hard query ceiling. `sw.db.query` does not
2083
+ offer a shorter cancellation option. The external `db_query timeout_ms`
2084
+ stops the caller waiting and returns `QUERY_TIMEOUT`, but does not promise
2085
+ that work already accepted by the database was cancelled. Bound recursive
2086
+ queries in SQL and use `LIMIT`; group writes to declared tables in one
2087
+ `sw.db.tx` (raw `batch` never writes them).
2088
+
2089
+ When the database is briefly overloaded, a read rejects with `DB_UNAVAILABLE`
2090
+ (503). Only a read — a call that sent no write, in a request with no earlier
2091
+ saved write — carries `err.retry === true`, `err.retryable === true` and
2092
+ `err.retry_after_ms`; wait that long before retrying the read if you choose.
2093
+ Nothing retries for you. Writes and every other error keep `retry: false`;
2094
+ check `outcome` and `write_committed` instead. Functions get this on their
2095
+ next deploy.
2096
+
2097
+ ## Change webhooks — developer-side registration
2098
+
2099
+ Get notified after every successful INSERT / UPDATE / UPSERT / DELETE.
2100
+ One webhook per project. Payload is small and predictable; no row
2101
+ contents are sent, so your webhook handler can't accidentally leak
2102
+ sensitive data:
2103
+
2104
+ { project_id, table, op, rows_affected, ts }
2105
+
2106
+ Register, read, or remove the webhook with developer credentials through
2107
+ `db_webhook_set`, `db_webhook_get`, and `db_webhook_delete`, or the REST
2108
+ surface below. `sw.db.onchange` is not available inside a deployed function.
2109
+
2110
+ Every POST carries:
2111
+
2112
+ X-Somewhere-Signature: t={ms},v1={hmac-sha256-hex}
2113
+
2114
+ where the signed string is `${ms}.${rawBody}`. Verify with a
2115
+ constant-time compare and reject requests where `Math.abs(Date.now() - ms)`
2116
+ is over your replay tolerance (5 minutes is typical).
2117
+
2118
+ The webhook fires from waitUntil after the write commits, so your
2119
+ handler's latency never blocks the developer's query. There is no
2120
+ automatic retry — keep your endpoint idempotent and fast. The
2121
+ registration row tracks last_status / last_error so you can see the
2122
+ most recent delivery outcome via `db_webhook_get`.
2123
+
2124
+ Equivalent REST surface (developer key only):
2125
+
2126
+ PUT /v1/db/webhook { project_id, url, events? }
2127
+ GET /v1/db/webhook?project_id=…
2128
+ DELETE /v1/db/webhook?project_id=…