atomhouse-skill 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,390 @@
1
+ # atomhouse — identity, access and errors
2
+
3
+ ## The app's own identity
4
+
5
+ **`machine_credential` gives the app an identity of its own** — for calls the app makes as
6
+ itself: from a server you host, or a job that talks to REST or MCP. The name is the point: it is
7
+ for a machine, and it is not how a person's request is evaluated.
8
+
9
+ It is **not** how a signed-in user's requests are evaluated. Those run as that user's cookie, and
10
+ that is what makes an `{user_id}` row filter mean anything. A static page cannot keep this secret,
11
+ and a function cannot read it, so **if there is no server-side consumer, do not mint one.**
12
+
13
+ Inside `create_app`'s arguments:
14
+
15
+ ```json
16
+ "machine_credential": { "name": "runtime", "role": "member" }
17
+ ```
18
+
19
+ `role` is `member` — the only role a credential may hold; `ttl_secs` is optional. The response carries
20
+ `machine_credential.secret`, an `atomhouse_app_…` value **shown once and never again**. It is scoped to this one app: another app's
21
+ data is refused rather than redirected, and it can never create apps.
22
+
23
+ **Roles do not narrow it.** Measured on this build: a table whose role filtered one person's rows
24
+ returned that person's row and **both rows to the app credential**. The credential *is* the app, so
25
+ it is exempt by design — and that is why an app-credential read never proves a filter works.
26
+
27
+ **What it can do, measured:** it reads and writes rows (`insert_rows`, `update_rows` both
28
+ succeed). It cannot change the schema — `create_table` answers `role member cannot perform ddl`.
29
+ So a credential is bounded by *not owning the shape of the data*, not by being read-only.
30
+
31
+ That combination — writes, and no row filter it can fail — is why it belongs on a server and
32
+ nowhere a page or a browser can reach.
33
+
34
+ ## Permissions
35
+
36
+ Accounts are global. Your role comes from `bootstrap`, not from this document.
37
+
38
+ | Workspace role | Use apps | Write rows | Change an app's schema | Grant access | Audit |
39
+ |---|---|---|---|---|---|
40
+ | member | only with an app role | **yes** | no | no | no |
41
+ | admin | only with an app role | yes | **yes** | yes | yes |
42
+ | owner | only with an app role | yes | **yes** | yes | yes |
43
+ | disabled | no | no | no | no | no |
44
+
45
+ Four roles, and that is the whole list. An unknown name is treated as `member`.
46
+
47
+ **Nobody reaches an app without an app role — administrators included.** Creating an app puts you
48
+ in its `admin` role, which is how the creator can open it. If an app is misconfigured, the way back
49
+ is to change somebody's *workspace* role, not to rely on an override that no longer exists.
50
+
51
+ `disabled` is a switch, not a deletion: the person stays in the workspace, keeps their history, and
52
+ every call answers `403`. They cannot ask for access again until an admin re-enables them.
53
+
54
+ ### Roles inside one app
55
+
56
+ Being in a role is the **only** way into an app. There is no separate grant: two answers to "may
57
+ this person use this app" meant one could say yes and the other no. Every app starts with two
58
+ roles:
59
+
60
+ - **`admin`** — reads and writes every table. It cannot be deleted or narrowed: it is the one role
61
+ that must keep working, or an app's shape becomes unchangeable. Every table you create is added
62
+ to it, so it stays complete. You can add and remove people freely.
63
+ - **`member`** — starts able to read and write everything, and is meant to be **narrowed**. Each
64
+ table you create is added to it automatically, so the default keeps working as the app grows.
65
+
66
+ **No role grants a table it does not list** — not even `admin`. One rule, and "not listed" always
67
+ means "not allowed", which is easier to reason about than an implicit "everything" that a role's
68
+ list silently overrides.
69
+
70
+ An app role governs **tables and data only**. To express something finer, create a role:
71
+
72
+ ```
73
+ set_app_role { app, name: "borrower", tables: [
74
+ { table: "books", can_read: true, can_write: false },
75
+ { table: "loans", can_read: true, can_write: true,
76
+ write_filter: "borrower_id = {user_id}" } ] }
77
+ assign_app_role { app, email, role: "borrower" }
78
+ list_app_roles { app }
79
+ ```
80
+
81
+ - **A table not listed is a table the role cannot touch.** A custom role therefore does not
82
+ silently gain tables created later — unlike `member`, whose list is maintained for you.
83
+ - **Read and write filters are separate** (`read_filter`, `write_filter`), and `{user_id}`,
84
+ `{email}`, `{role}`, `{workspace}` are substituted per caller. A write filter applies to newly
85
+ created rows too, not only edits.
86
+
87
+ | Placeholder | Resolves to |
88
+ |---|---|
89
+ | `{user_id}` | the caller's account id — **prefer this** |
90
+ | `{email}` | the caller's address |
91
+ | `{role}` | the caller's role **identifier** in this app (the slug, not the human-readable label) |
92
+ | `{workspace}` | the workspace slug |
93
+
94
+ `{role}` is the identifier, never the label: a filter compares stored data, and a translated
95
+ label would change with the reader's language — two readers of the same row would disagree about
96
+ what it says. Use it to make a row visible to one role only: `audience = {role}`.
97
+ - **Use `{user_id}`, not `{email}`.** The id is the account's permanent identity; an address can
98
+ be changed or reassigned, and a stored email in an owning column would then point at a different
99
+ person. Filter on an id column — `owner_id`, `borrower_id` — and store the caller's id there.
100
+ `{email}` still works, and is easier to read in a table you are inspecting by hand.
101
+ - **Write needs read.** A role that may change a table must be able to see it.
102
+ - **One role serves everybody with their own rows.** The placeholders are per caller, so a single
103
+ role using `owner_id = {user_id}` gives each holder their own slice. Do not create a role per
104
+ person — that is what the filter is for.
105
+ - **Assigning a role admits to the app, not to the workspace.** The account must already be a
106
+ member; `assign_app_role` refuses one that is not.
107
+
108
+ ### Who may grant access
109
+
110
+ Creating a role and assigning people to it needs **manage access** — workspace `owner` or `admin`.
111
+ A plain `member` gets `403 role member cannot perform manage_access`.
112
+
113
+ That is the wall a page runs into: a page served to an ordinary member cannot create roles or
114
+ assign them, no matter which endpoints it calls. Two ways through, and the first is the one to
115
+ build:
116
+
117
+ ### Deciding what to draw: `GET …/apps/{app}/access`
118
+
119
+ The failure this prevents is a white screen. A page that loads data first and handles `403` after
120
+ has nothing to draw when the answer is "you are signed in and you are not allowed here" — and that
121
+ is the common case, not the rare one: every new member of a workspace has no app role until an
122
+ administrator assigns one.
123
+
124
+ Call this first, before loading anything else:
125
+
126
+ ```
127
+ GET /api/v1/workspaces/{ws}/apps/{app}/access (session cookie or bearer)
128
+ ```
129
+
130
+ ```json
131
+ { "workspace_role": "member",
132
+ "app": "shop",
133
+ "capability": null, ← null means: no access to this app
134
+ "error": "this account has no role in this app; an admin assigns one",
135
+ "role": null,
136
+ "tables": [] }
137
+ ```
138
+
139
+ It answers **200 even when the caller has no access** — the refusal is the body, not the status.
140
+ Three states, three screens:
141
+
142
+ | `capability` | What it means | What to draw |
143
+ |---|---|---|
144
+ | `null` | signed in, no role in this app | ask-for-access, with the `error` text shown |
145
+ | `"read"` | may read | the app, without write controls |
146
+ | `"write"` / `"ddl"` | may write / manage | the full app |
147
+
148
+ The same call distinguishes the anonymous case: with no session at all it answers
149
+ `401 unauthenticated`, which is the sign-in prompt. So one request covers all four outcomes —
150
+ anonymous, no access, read-only, full — and the page never has to guess from a failed query.
151
+
152
+ `tables` carries the per-table limits (read/write, row filter, column allowlist), which is what a
153
+ page needs to hide a column it would otherwise render empty.
154
+
155
+ 1. **The visitor asks, an administrator approves.** The page posts to `…/access-requests`; an
156
+ administrator reviews it with `review_access_request` (MCP) or the console. The page can offer
157
+ this button to anybody, because asking needs no privilege.
158
+ 2. **The page is used by an administrator.** Then `POST …/roles` and
159
+ `POST …/roles/{id}/members` work from the page — same origin, same cookie.
160
+
161
+ Do not build a "manage users" screen for members and assume the calls will work; they answer `403`
162
+ and the failure is in the middle of onboarding, which is the worst place for it.
163
+
164
+ ### Finding somebody's user id
165
+
166
+ A filter or a role assignment takes a `user_id`, and there is no way to look one up by guessing. The
167
+ two calls that return ids:
168
+
169
+ | Call | Returns |
170
+ |---|---|
171
+ | `GET /auth/me` | your own account — the only id you get for free |
172
+ | `GET /workspaces/{ws}/members` | every member: `user_id`, `email`, `display_name`, `role` |
173
+ | `GET …/apps/{app}/roles/{role_id}/members` | the holders of one role, with `user_id` and `email` |
174
+
175
+ **You cannot read the users table**, and you do not need to: `/workspaces/{ws}/members` is the
176
+ directory. Use the `email` to recognise a person and the `user_id` to write.
177
+
178
+ ### Adding somebody to the workspace
179
+
180
+ Three ways to name one person, and one way to name nobody in particular.
181
+
182
+ | You have | Send |
183
+ |---|---|
184
+ | an email address | `{"email": "…", "role": "member"}` |
185
+ | a `user_id` from the directory | `{"user_id": "…", "role": "member"}` |
186
+ | a phone number | `{"phone": "…", "role": "member"}` |
187
+ | nothing — you want to hand out a link | `{"role": "member"}` |
188
+
189
+ All four are `POST /workspaces/{ws}/invitations`. `email` is the only handle that may refer to
190
+ somebody who has not signed up yet: the invitation waits, and they redeem it after registering. A
191
+ `user_id` or `phone` that matches no account is a `404`, not a pending invitation — an address has
192
+ a sign-up path behind it and a stray id does not.
193
+
194
+ The response carries `token`. For an email that already has an account there is no token and the
195
+ person is already a member; `email` in the response tells you which happened (`null` means a code).
196
+
197
+ **A request with none of the three is a code.** Eight characters, upper case, without the five
198
+ characters that get confused for one another — `0`/`O`, `1`, `I`, `L` — read aloud and retyped
199
+ without a lookup table. It is **single use**: the first
200
+ caller to redeem it joins, everybody after that gets `409`. That is what makes an eight-character
201
+ secret safe; it is not a password.
202
+
203
+ ```bash
204
+ # make one
205
+ POST /workspaces/quiet-bridge/invitations {"role": "member"}
206
+ # -> {"token": "A3KF9M2P", "email": null, "expires_at": "...", ...}
207
+
208
+ # redeem it — no workspace in the path, the code knows which one
209
+ POST /invitations/accept {"token": "a3kf9m2p"}
210
+ # -> {"ok": true, "workspace_id": "...", "role": "member"}
211
+ ```
212
+
213
+ The token is accepted in either case. `POST /workspaces/{ws}/invitations/accept` does the same
214
+ thing when you already have the slug.
215
+
216
+ **Nothing sends email here.** `token` in that response is the only copy: if an agent creates a
217
+ code and does not return it to the person, the code is lost. Put it in your reply.
218
+
219
+ #### Granting an app role at the same time
220
+
221
+ `app: {"app": "notes", "role": "reader"}` on the invitation applies that app role when it is
222
+ redeemed, in the same transaction as the membership. Use it when the point of inviting somebody is
223
+ that they should read one app — otherwise they arrive as a workspace member with no data access
224
+ and an admin has to remember the second step.
225
+
226
+ The role name must already exist — see `GET /workspaces/{ws}/apps/{app}/roles`. A name that does
227
+ not is a validation error at creation, not a silent no-op at redemption.
228
+
229
+ #### An app can refuse to be asked
230
+
231
+ An app with `requests_open: false` (the console's own switch, `PATCH /workspaces/{ws}/apps/{app}`
232
+ with `{"requests_open": false}`) does not appear in the request list and refuses
233
+ `POST …/apps/{app}/requests` with `403`. It is still reachable: an admin grants it directly, by the
234
+ calls in this document or by an invitation carrying an app role. So "closed" means "no new people
235
+ by asking", not "nobody new".
236
+
237
+ ### Moving a column from email to id
238
+
239
+ An app built before this rule stores addresses where it should store ids. There is no automatic
240
+ migration — the server does not know which column means "owner" — so pick one of two approaches:
241
+
242
+ **Add a column and write both.** Least disruptive, and works while people are using the app:
243
+
244
+ 1. `ALTER TABLE … ADD COLUMN owner_id VARCHAR` (or create the table with both columns).
245
+ 2. Write `owner_id` on every new row, from the caller's `{user_id}`.
246
+ 3. Change the role's filter to `owner_id = {user_id}`. Rows written before step 2 have a null
247
+ `owner_id` and become invisible to their owner — check the count first.
248
+ 4. Backfill from `/workspaces/{ws}/members`, matching `email` to `user_id`:
249
+
250
+ ```sql
251
+ UPDATE loans SET owner_id = '<the id for old@example.com>' WHERE member_email = 'old@example.com'
252
+ ```
253
+
254
+ One statement per person, or a `CASE` over the directory. Do this only for the rows you must keep.
255
+
256
+ **Start over.** If the rows are seed data or an import, `DROP` and re-create with the id column and
257
+ re-import through the API — a row inserted by the API is stamped with the caller's id for you.
258
+
259
+ ### Taking access away
260
+
261
+ There is no revoke call **for app access**: access *is* the role assignment, so removing somebody
262
+ from their role is the same act as closing the app to them.
263
+
264
+ That is not the same operation as ending a session token. That one does have a call —
265
+ `POST /auth/logout` — and it is documented under *Ending a token* in `SKILL.md`. Confusing the two
266
+ is how a token you meant to retire stays live: a role change does nothing to a bearer token already
267
+ on disk.
268
+
269
+ ```
270
+ DELETE /api/v1/workspaces/{ws}/apps/{app}/role-members/{user_id}
271
+ ```
272
+
273
+ That removes them from the app. It does **not** remove them from the workspace, and does not
274
+ touch any other app — which is the distinction that matters when the reason for removing them is
275
+ "this person should not be here". Ending workspace membership is a separate act with its own
276
+ consequences for anything else they own.
277
+
278
+ `list_app_roles` shows who holds what, which is how you find the account first.
279
+
280
+ ## Cleaning up
281
+
282
+ Some things can only be removed over REST — there is no MCP tool for them, and guessing at tool
283
+ names wastes calls. All of these need the same `Authorization` header.
284
+
285
+ | To remove | Call |
286
+ |---|---|
287
+ | A table | `drop_table` (MCP) |
288
+ | Rows | `delete_rows` (MCP, by primary key) |
289
+ | An object | `delete_object` (MCP) |
290
+ | A trigger | `delete_trigger` (MCP) |
291
+ | **An app** | `DELETE …/apps/{app}` with a confirmation token |
292
+ | **A model** | `DELETE …/apps/{app}/models/{name}` |
293
+ | **A site** | `unpublish_site` (MCP) keeps the files; `DELETE …/apps/{app}/sites/{site}` removes it |
294
+ | **A role** | `DELETE …/apps/{app}/roles/{id}` — **read the note below first** |
295
+ | **Your own session** | `POST …/auth/logout` — ends it server-side; see below |
296
+
297
+ **A session token ends with `POST …/auth/logout`**, and that call works for a bearer token as well
298
+ as a cookie. It deletes the session row, so the token stops answering immediately — a revoked token
299
+ returns `401` on the next call, not at its expiry.
300
+
301
+ Two things it is not. It ends *this* session and no other: signing out one machine does not sign out
302
+ the account elsewhere. And it does not touch the file the token came from — that is still a live
303
+ value in a plain text file until somebody deletes it. When a token is the wrong one, do both:
304
+
305
+ ```bash
306
+ curl -s -X POST https://your-instance/api/v1/auth/logout -H "Authorization: Bearer $OLD"
307
+ rm -f ~/.atomhouse/credentials/atomhouse.token
308
+ ```
309
+
310
+ There is no refresh token, so nothing re-issues a credential after this; the device flow is how a new
311
+ one is obtained. Losing a token — as opposed to ending one — is not something this platform can help
312
+ with: until the account's password changes, a copy that left the machine remains valid.
313
+
314
+ **Deleting a role takes its holders with it**, so it is not a way to tidy up without consequences.
315
+ Anyone who was in that role is moved to the app's `member` role and keeps their access — but `member`
316
+ may see more than the role you deleted did. Check what `member` grants before removing a narrow role,
317
+ and move the holders to the role you actually want them in:
318
+
319
+ ```
320
+ assign_app_role { app, email, role: "the-role-they-should-have" }
321
+ ```
322
+
323
+ Assign first, delete second. A role with holders is never deleted silently into nothing: if the app
324
+ has no `member` role to fall back to, the delete is refused rather than locking people out.
325
+
326
+ Deleting an app is guarded, because it takes its schema and data with it. Ask for a challenge, then
327
+ send it back:
328
+
329
+ ```bash
330
+ # 1. what to confirm
331
+ curl -s -X POST "https://atomhouse.cn/api/v1/workspaces/{ws}/apps/{app}/delete-challenge" \
332
+ -H "Authorization: Bearer <token>"
333
+ # -> { "confirmation": "delete-app:<ws>:<app>:<nonce>", ... }
334
+
335
+ # 2. send it back verbatim
336
+ curl -s -X DELETE "https://atomhouse.cn/api/v1/workspaces/{ws}/apps/{app}" \
337
+ -H "Authorization: Bearer <token>" -H 'content-type: application/json' \
338
+ -d '{"confirmation": "delete-app:<ws>:<app>:<nonce>"}'
339
+ ```
340
+
341
+ A confirmation that does not start with `delete-app:<ws>:<app>:` is refused with the expected
342
+ prefix, so a wrong guess tells you the shape. **Confirm with the user before deleting an app** —
343
+ unlike publishing, this does not reverse.
344
+
345
+ ## Errors
346
+
347
+ A workspace has one database connection, so queries run in order. If a long query is ahead of yours, the request fails with `504 timeout` and the message says the workspace is busy — retry shortly rather than treating it as a broken query. Once a statement starts, it is interrupted at the configured timeout.
348
+
349
+ | Code | HTTP | What to do |
350
+ |---|---|---|
351
+ | `unauthenticated` | 401 | sign in again |
352
+ | `forbidden` | 403 | report the limit; do not retry |
353
+ | `not_found` | 404 | list first |
354
+ | `validation` | 422 | fix the request |
355
+ | `conflict` | 409 | a name is taken, or a request is already pending — pick another, or wait for the answer |
356
+ | `timeout` | 504 | the workspace was busy; retry shortly rather than reworking the query |
357
+ | `limit_exceeded` | 413 | narrow the query |
358
+
359
+ **A `403` about `x-csrf-token` has two causes, and the message now says which.** "no such header
360
+ at all" means the request never carried it — a code path that forgot to set it. "its value is
361
+ empty" means the header was there but the token variable was empty: `undefined` from a response
362
+ field that is not named what you thought (`csrf_token`, not `csrf`), or a `sessionStorage` read
363
+ that ran before the write. Print the value before the request rather than adding the header
364
+ twice.
365
+
366
+ ## Verifying the work
367
+
368
+ "Finished" is a claim to check, not a feeling. Five calls, all cheap, and each catches the class of
369
+ mistake that produces something that looks complete and is not:
370
+
371
+ | Check | Catches |
372
+ |---|---|
373
+ | `describe_table` on each table you created | a column that was silently not created |
374
+ | `read_rows` after your last write | a write that returned 200 and stored a different value |
375
+ | `site_status` → open the URL | a page that shipped a 404 or an error page |
376
+ | `list_app_roles` | a role you meant to save and did not, or a table you forgot to add |
377
+ | `GET …/auth/me` with the app credential | a credential scoped to the wrong app: `actor_kind` is `app` and the email names the app |
378
+
379
+ Then open the published URL in a browser with **no session** — that is what a visitor sees. An app
380
+ whose page renders and whose data does not load is the most common way this looks done and is not.
381
+
382
+ **What none of these can check is a row filter from the user's side.** A filter containing
383
+ `{user_id}` is only meaningful for the person it resolves to, and the two credentials you hold are
384
+ yours and the app's — an app credential carries no user, so `{user_id}` matches nothing and it reads
385
+ the whole table. An app credential is also exempt from roles entirely, so it sees every row no
386
+ matter what the role says.
387
+
388
+ To see what a restricted user sees, that user has to sign in: read the role back with
389
+ `list_app_roles` and confirm it says what you meant, then ask the person to glance at the app. Do
390
+ not conclude from an app-credential read that a filter works.
@@ -0,0 +1,166 @@
1
+ # atomhouse — working with data
2
+
3
+ ## Dates
4
+
5
+ This build refuses to load DuckDB extensions — loading one is network access plus code execution —
6
+ so the functions that ship inside `icu` are absent. Before a query reaches the engine, four exact
7
+ idioms are rewritten:
8
+
9
+ | Written | Becomes |
10
+ |---|---|
11
+ | `current_date` | `CAST(strftime(now(), '%Y-%m-%d') AS DATE)` |
12
+ | `today()` | same |
13
+ | `CAST(now() AS DATE)` | `CAST(CAST(now() AS TIMESTAMP) AS DATE)` |
14
+ | `date_trunc('day', now())` | `date_trunc('day', CAST(now() AS TIMESTAMP))` |
15
+
16
+ **It matches those four spellings, not expressions.** `CAST(now() - INTERVAL 30 DAY AS DATE)` is
17
+ not rewritten and fails. The rewrite is also skipped inside string literals and comments, so a
18
+ column named `today` is left alone.
19
+
20
+ The underlying problem the rewrite works around is a type: `now()` is `TIMESTAMP WITH TIME ZONE`,
21
+ which supports neither arithmetic nor a cast to DATE. Cast it to `TIMESTAMP` first:
22
+
23
+ ```sql
24
+ SELECT CAST(now() AS TIMESTAMP) - INTERVAL 1 DAY -- yesterday, same time
25
+ SELECT date_diff('day', CAST('2026-10-01' AS DATE), CAST(now() AS TIMESTAMP)) -- days since
26
+ SELECT strftime(now(), '%Y-%m-%d') -- today as text
27
+ ```
28
+
29
+ Passing a zoned timestamp straight to `date_diff` gives **`500 internal error`**, not a wrong
30
+ number — it reaches for the missing `icu` overload. The `CAST(... AS TIMESTAMP)` above is what
31
+ avoids it.
32
+
33
+ If you store a date, store it as `DATE` or as text `YYYY-MM-DD`, not as `now()`. A zoned timestamp
34
+ in a column cannot be compared with a literal date, and that failure appears at read time, far from
35
+ the insert that caused it.
36
+
37
+ ## SQL
38
+
39
+ `POST /query` runs in DuckDB, which does not coerce types for you. Two mistakes it will not
40
+ forgive:
41
+
42
+ **Types.** Formatting a timestamp as if it were text is the usual form:
43
+
44
+ ```sql
45
+ -- no: substr() has no TIMESTAMP overload
46
+ SELECT substr(created_at, 1, 10) FROM t;
47
+
48
+ -- yes
49
+ SELECT CAST(created_at AS DATE) AS day FROM t;
50
+ SELECT strftime(created_at, '%Y-%m-%d') AS day FROM t;
51
+ ```
52
+
53
+ **An aggregate can come back as a string.** DuckDB's `SUM` over an integer column is a `HUGEINT`,
54
+ wider than JSON's number type, so it is serialised as text — while `COUNT` is a plain integer:
55
+
56
+ ```json
57
+ { "columns": [{"name":"total","type_name":"Hugeint"},{"name":"n","type_name":"Bigint"}],
58
+ "rows": [["21", 2]] }
59
+ ```
60
+
61
+ `total + 1` in JavaScript is `"211"`, not `22`. The page does not error and the number is wrong on
62
+ screen, which is the worst combination. Either cast in SQL (`CAST(SUM(x) AS BIGINT)`) or convert on
63
+ arrival (`Number(row.total)`); do not add two aggregate values without one of them.
64
+
65
+ Read the column list before writing aggregates, and join only through columns that exist — `GET /tables/{table}` (or `describe_table`) names every column and its type. The live schema is not inlined in these documents, so fetch it before writing SQL.
66
+
67
+ **Grouping.** Every column you select must either be aggregated or named in `GROUP BY` — DuckDB refuses the query rather than picking a value for you:
68
+
69
+ ```sql
70
+ -- no: `name` is neither grouped nor aggregated
71
+ SELECT w.name, COUNT(*) c FROM bottles b
72
+ JOIN wines w ON w.id = b.wine_id GROUP BY b.wine_id;
73
+
74
+ -- yes: group by what you select
75
+ SELECT w.name, COUNT(*) c FROM bottles b
76
+ JOIN wines w ON w.id = b.wine_id GROUP BY w.name;
77
+
78
+ -- also fine: `c` is an alias for an aggregate
79
+ SELECT w.name, COUNT(*) AS c FROM bottles b
80
+ JOIN wines w ON w.id = b.wine_id GROUP BY w.name HAVING COUNT(*) <= 2;
81
+ ```
82
+
83
+ Two things that catch people here:
84
+
85
+ - Grouping by an id is not the same as grouping by the columns you selected. `GROUP BY b.wine_id` with `SELECT w.name` fails even though the id is unique.
86
+ - A `HAVING` clause filters groups, so it may use an aggregate or a grouped column — not an ungrouped one.
87
+
88
+ ## Models: a saved view over one or more tables
89
+
90
+ When a shape is used more than once — a filtered subset, a join with a computed column — save it as a model instead of repeating the SQL. A model is a read-only view, queried exactly like a table.
91
+
92
+ ```http
93
+ POST /api/v1/workspaces/{ws}/apps/{app}/models
94
+ {"name": "in_stock", "title": "In-stock bottles",
95
+ "definition": "SELECT id, wine_id FROM bottles WHERE status = 'in_stock'"}
96
+ ```
97
+
98
+ Then `SELECT * FROM in_stock` works in `/query`, and `GET /tables/in_stock` describes it.
99
+
100
+ - The `definition` must be **one SELECT** over this app's tables. Anything else is refused; a model is not a place to run DDL.
101
+ - The **tables it reads are recorded** when it is created. That is what lets row and column policies still apply: a caller whose access is restricted on a base table is refused the model, rather than shown rows the policy hid. A view is opaque to the SQL rewriter, so this refusal is the protection.
102
+ - Models are read-only. Writes go to the table, never to the model.
103
+
104
+ ## Reading rows: sorting and filtering
105
+
106
+ The two interfaces name these differently, and both have been guessed wrong:
107
+
108
+ | | MCP `read_rows` | REST `GET .../rows` |
109
+ |---|---|---|
110
+ | sort | `sort`, an array of objects | `order`, a string |
111
+ | filter | `filters`, an array of objects | `filter`, a string |
112
+
113
+ **MCP** — structured, one object per condition:
114
+
115
+ ```json
116
+ {"app": "shop", "table": "orders",
117
+ "sort": [{"column": "created_at", "desc": true}],
118
+ "filters": [{"column": "status", "op": "eq", "value": "open"},
119
+ {"column": "total", "op": "gte", "value": 100}],
120
+ "limit": 50}
121
+ ```
122
+
123
+ `op` is one of `eq ne gt gte lt lte contains starts_with in is_null is_not_null`.
124
+ There is no `order` argument and no `filter` (singular) argument; passing either is silently
125
+ ignored, which is why a wrong sort looks like a wrong result set rather than an error.
126
+
127
+ **REST** — one string each:
128
+
129
+ ```
130
+ GET /api/v1/workspaces/{ws}/apps/{app}/tables/{table}/rows
131
+ ?order=created_at:desc,name:asc
132
+ &filter=status:eq:open,total:gte:100
133
+ &limit=50&offset=0
134
+ ```
135
+
136
+ `order` is `column:asc|desc`, comma-separated for several. `filter` is `column:op:value`,
137
+ comma-separated for several; a value containing a comma is fine when it is inside brackets —
138
+ `id:in:(1,2,3)` is one condition, not two.
139
+
140
+ `count=true` returns the total alongside the page, which is what a pager needs.
141
+
142
+ ## CSV: bulk load, and what it will not do
143
+
144
+ For a few hundred rows use `insert_rows`. For a file a person hands you, use CSV import — it is one multipart request instead of a thousand JSON ones.
145
+
146
+ ```
147
+ # Preview first: it parses and reports without writing anything.
148
+ POST /apps/{app}/import/preview?table=entries (multipart, field `file`)
149
+ -> { "columns": ["mood","note"], "rows": [["happy","…"]], "total_lines": 2 }
150
+
151
+ # Then import into an existing table.
152
+ POST /apps/{app}/import?table=entries (multipart, field `file`)
153
+ -> { "table": "entries", "rows_imported": 1, "created": false }
154
+
155
+ # Or create the table from the header row.
156
+ POST /apps/{app}/import?table=students&create=true
157
+ -> { "table": "students", "rows_imported": 2, "created": true }
158
+ ```
159
+
160
+
161
+ 1. **Both endpoints are multipart**, with the table in the query string and the file in a field named `file`. Sending JSON gets you "missing field table".
162
+ 2. **A missing table is refused**, not created. The error says so — `pass create=true to create it` — and `create=true` infers column types from the values.
163
+ 3. **It appends.** Importing the same file twice inserts it twice; there is no dedupe. If a re-run is possible, delete the rows first or import into a temp table and merge.
164
+ 4. **Column names come from the header row** and must match the table's columns. A typo is a validation error naming the column, not a silent null.
165
+
166
+ Export is the mirror: `GET /apps/{app}/tables/{table}/export?format=csv` streams the table back. It obeys row policies, so a restricted caller exports only what they can see, and it refuses rather than truncating when the result would exceed the response limit.