okmodel 0.2.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/README.md +882 -48
  2. package/dist/contracts/catalog/document.d.ts +6 -2
  3. package/dist/contracts/catalog/enum.d.ts +31 -4
  4. package/dist/contracts/catalog/extension.d.ts +61 -0
  5. package/dist/contracts/catalog/privilege.d.ts +64 -0
  6. package/dist/contracts/catalog/routine.d.ts +56 -0
  7. package/dist/contracts/catalog/types.d.ts +164 -10
  8. package/dist/contracts/catalog/view.d.ts +73 -0
  9. package/dist/dialects/pg/column.d.ts +3 -1
  10. package/dist/dialects/pg/ddl.d.ts +65 -1
  11. package/dist/dialects/pg/enum.d.ts +10 -8
  12. package/dist/dialects/pg/ext/citext.d.ts +14 -0
  13. package/dist/dialects/pg/ext/citext.js +11 -0
  14. package/dist/dialects/pg/ext/index.d.ts +52 -0
  15. package/dist/dialects/pg/ext/index.js +6 -0
  16. package/dist/dialects/pg/ext/pg-trgm.d.ts +53 -0
  17. package/dist/dialects/pg/ext/pg-trgm.js +42 -0
  18. package/dist/dialects/pg/fn/index.d.ts +107 -0
  19. package/dist/dialects/pg/fn/index.js +175 -0
  20. package/dist/dialects/pg/fn/touch.d.ts +14 -0
  21. package/dist/dialects/pg/index.js +104 -19
  22. package/dist/dialects/pg/introspect.d.ts +10 -1
  23. package/dist/dialects/pg/operators.d.ts +8 -1
  24. package/dist/dialects/pg/role/check.d.ts +45 -0
  25. package/dist/dialects/pg/role/index.d.ts +50 -0
  26. package/dist/dialects/pg/role/sql.d.ts +51 -0
  27. package/dist/dialects/pg/table.d.ts +24 -1
  28. package/dist/dialects/pg/tenancy.d.ts +9 -0
  29. package/dist/dialects/pg/view/client.d.ts +30 -0
  30. package/dist/dialects/pg/view/depend.d.ts +35 -0
  31. package/dist/dialects/pg/view/index.d.ts +114 -0
  32. package/dist/dialects/pg/view/index.js +289 -0
  33. package/dist/dialects/pg/view/scratch.d.ts +22 -0
  34. package/dist/dialects/pg/where.d.ts +2 -2
  35. package/dist/runtime/catalog-cache.d.ts +17 -0
  36. package/dist/runtime/compat-words.d.ts +23 -0
  37. package/dist/runtime/drift-detail.d.ts +20 -4
  38. package/dist/runtime/drift.d.ts +4 -2
  39. package/dist/runtime/pg/bun.js +3 -3
  40. package/dist/runtime/pg/pg.js +3 -3
  41. package/dist/runtime/pg/pglite.js +3 -3
  42. package/dist/runtime/pg/postgresjs.js +3 -3
  43. package/dist/runtime/tenancy/index.js +6 -3
  44. package/dist/runtime/traits/index.d.ts +7 -2
  45. package/dist/runtime/traits/index.js +151 -13
  46. package/dist/runtime/types.d.ts +2 -0
  47. package/dist/runtime/validate/index.js +4 -4
  48. package/dist/shared/{xkz8g6by.js → 1g0drakv.js} +2 -2
  49. package/dist/shared/2321avmn.js +418 -0
  50. package/dist/shared/{7mht49yd.js → 3p4b1fg0.js} +57 -18
  51. package/dist/shared/41kv2xdm.js +318 -0
  52. package/dist/shared/{97g2jnrw.js → 4ef7mmqf.js} +3 -3
  53. package/dist/shared/{sacqha1y.js → 4m9fn52z.js} +2 -2
  54. package/dist/shared/5mtf6cj3.js +94 -0
  55. package/dist/shared/{1dp5knt7.js → 5vdm4sgp.js} +2 -2
  56. package/dist/shared/{a1gdp7j9.js → 6693j9rs.js} +1 -1
  57. package/dist/shared/{38crxbgn.js → 6p5k20sm.js} +3 -3
  58. package/dist/shared/7nk68fj8.js +751 -0
  59. package/dist/shared/84ptn35q.js +71 -0
  60. package/dist/shared/{d2whjz4k.js → 8jb4ymh2.js} +581 -28
  61. package/dist/shared/8ktwd3rh.js +97 -0
  62. package/dist/shared/94ez8kzh.js +19 -0
  63. package/dist/shared/{3a5ne750.js → 9m80mkac.js} +2 -2
  64. package/dist/shared/9x25fxhc.js +150 -0
  65. package/dist/shared/9yn6a2vd.js +11 -0
  66. package/dist/shared/ady1ms74.js +72 -0
  67. package/dist/shared/{4jzzghr6.js → awrsqrn7.js} +6 -6
  68. package/dist/shared/{4b9da9d7.js → axhk06q1.js} +19 -1
  69. package/dist/shared/{d04j53v8.js → c5g81ngb.js} +82 -14
  70. package/dist/shared/{n47rd821.js → c8aghh05.js} +1 -1
  71. package/dist/shared/{dd4f8mnx.js → c9z5g0fm.js} +4 -2
  72. package/dist/shared/{ps43134h.js → dyj86cmj.js} +4 -4
  73. package/dist/shared/{0qkxbm1f.js → fa9vt245.js} +1 -1
  74. package/dist/shared/{qa5dsc7z.js → fb00y8fp.js} +3 -3
  75. package/dist/shared/{qxa0yb9j.js → g7ez901n.js} +30 -1
  76. package/dist/shared/{py3nh7jy.js → gdh9mrtp.js} +2 -2
  77. package/dist/shared/{yw5c610b.js → gjthds9j.js} +2 -2
  78. package/dist/shared/hcmdtwgh.js +102 -0
  79. package/dist/shared/hqjsxnz7.js +13 -0
  80. package/dist/shared/htnaj77v.js +17 -0
  81. package/dist/shared/{v18jva5b.js → jgxzjzcz.js} +1 -1
  82. package/dist/shared/{x9v1qgeb.js → jsd07prz.js} +3 -3
  83. package/dist/shared/{g9f0zqce.js → kafaa5zv.js} +1 -1
  84. package/dist/shared/kj680nxv.js +19 -0
  85. package/dist/shared/{mxmcdsh5.js → kkzwp3d2.js} +9 -9
  86. package/dist/shared/{g1b5zzj9.js → n0dgs0pb.js} +1 -1
  87. package/dist/shared/n5y9zyj1.js +2431 -0
  88. package/dist/shared/{zt8y0wzb.js → n7mcc1gk.js} +1 -1
  89. package/dist/shared/{ge03bfca.js → nxb42q7h.js} +2 -2
  90. package/dist/shared/q6zsyh31.js +2192 -0
  91. package/dist/shared/{sfh4pk75.js → q795afwa.js} +26 -21
  92. package/dist/shared/{10tjenmd.js → qn0srwwq.js} +1 -1
  93. package/dist/shared/s4mb6a4b.js +545 -0
  94. package/dist/shared/{ytg3xf9p.js → sf8m6tfy.js} +3 -3
  95. package/dist/shared/{zd93g3rq.js → sr5ms7b3.js} +1 -1
  96. package/dist/shared/{xatfg0gn.js → tmbdywx0.js} +4 -19
  97. package/dist/shared/tny2t3sm.js +100 -0
  98. package/dist/shared/{e7a268fy.js → v7tpnhnz.js} +1 -1
  99. package/dist/shared/{ecdzej21.js → wqem4jed.js} +7 -7
  100. package/dist/shared/xghkt7a9.js +1144 -0
  101. package/dist/shared/y005b761.js +112 -0
  102. package/dist/shared/ycatkxmq.js +84 -0
  103. package/dist/shared/ygem90rn.js +900 -0
  104. package/dist/shared/{eaxwrgby.js → yjw02enp.js} +6 -3
  105. package/dist/shared/{mrq77sgw.js → zg24x0hm.js} +1 -1
  106. package/dist/shared/{cstgkzdx.js → zvbjc949.js} +1 -1
  107. package/dist/tooling/cli.js +66 -13
  108. package/dist/tooling/migrate/apply.d.ts +75 -5
  109. package/dist/tooling/migrate/backfill.d.ts +136 -0
  110. package/dist/tooling/migrate/check.d.ts +65 -0
  111. package/dist/tooling/migrate/classify.d.ts +108 -0
  112. package/dist/tooling/migrate/commands.d.ts +2 -1
  113. package/dist/tooling/migrate/config.d.ts +30 -0
  114. package/dist/tooling/migrate/doctor.d.ts +28 -0
  115. package/dist/tooling/migrate/drift.d.ts +35 -0
  116. package/dist/tooling/migrate/estimate.d.ts +50 -0
  117. package/dist/tooling/migrate/ext.d.ts +17 -0
  118. package/dist/tooling/migrate/extensions.d.ts +53 -0
  119. package/dist/tooling/migrate/files.d.ts +12 -0
  120. package/dist/tooling/migrate/index.d.ts +3 -2
  121. package/dist/tooling/migrate/index.js +67 -1
  122. package/dist/tooling/migrate/lint-rules.d.ts +51 -0
  123. package/dist/tooling/migrate/lint.d.ts +71 -0
  124. package/dist/tooling/migrate/managed.d.ts +17 -0
  125. package/dist/tooling/migrate/plan.d.ts +78 -10
  126. package/dist/tooling/migrate/project.d.ts +64 -5
  127. package/dist/tooling/migrate/provision.d.ts +18 -0
  128. package/dist/tooling/migrate/reference.d.ts +40 -0
  129. package/dist/tooling/migrate/runner.d.ts +108 -0
  130. package/dist/tooling/migrate/safe.d.ts +77 -0
  131. package/dist/tooling/migrate/seed.d.ts +20 -0
  132. package/dist/tooling/migrate/snapshot.d.ts +78 -0
  133. package/dist/tooling/migrate/status.d.ts +25 -6
  134. package/dist/tooling/migrate/type-name.d.ts +19 -0
  135. package/dist/tooling/testing/factories.d.ts +117 -0
  136. package/dist/tooling/testing/facts.d.ts +72 -0
  137. package/dist/tooling/testing/index.d.ts +89 -0
  138. package/dist/tooling/testing/index.js +8 -0
  139. package/dist/tooling/testing/isolation.d.ts +30 -0
  140. package/dist/tooling/testing/random.d.ts +40 -0
  141. package/dist/tooling/testing/record.d.ts +38 -0
  142. package/package.json +26 -2
  143. package/dist/shared/5z4q2zda.js +0 -2073
  144. package/dist/shared/eqmtn1bj.js +0 -399
  145. package/dist/shared/rtnaqre0.js +0 -37
  146. package/dist/shared/zwmqxb0g.js +0 -79
  147. package/dist/shared/{m9tv7xn7.js → radd3z4g.js} +3 -3
  148. /package/dist/shared/{9k6vetvf.js → rrstp3kb.js} +0 -0
package/README.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # OKModel
2
2
 
3
- okmodel is a catalog-first TypeScript ORM, PostgreSQL first. Other SQL databases are the direction. Version 0.1 supports PostgreSQL only. The schema is the single source. Migrations and queries come from it.
3
+ okmodel is a catalog-first TypeScript ORM, PostgreSQL first. Other SQL databases are the direction. CI runs PostgreSQL 15 to 18. The schema is the single source. Migrations and queries come from it.
4
4
 
5
- Version 0.1.1. Apache-2.0.
5
+ Version 0.4.0. Apache-2.0.
6
6
 
7
7
  ## Contents
8
8
 
@@ -13,12 +13,55 @@ Version 0.1.1. Apache-2.0.
13
13
  - [Push](#push)
14
14
  - [Reviewed migrations](#reviewed-migrations)
15
15
  - [One client](#one-client)
16
+ - [Write and read](#write-and-read)
17
+ - [Core](#core)
18
+ - [Keys](#keys)
19
+ - [Identity](#identity)
20
+ - [Number](#number)
21
+ - [Uuid](#uuid)
22
+ - [Generated in the app](#generated-in-the-app)
23
+ - [Slug](#slug)
24
+ - [Two columns](#two-columns)
16
25
  - [Insert](#insert)
26
+ - [On conflict](#on-conflict)
17
27
  - [Find](#find)
28
+ - [One](#one)
29
+ - [Count](#count)
30
+ - [Exists](#exists)
31
+ - [Update](#update)
32
+ - [Delete](#delete)
18
33
  - [Errors](#errors)
19
- - [Close](#close)
20
- - [Keys](#keys)
34
+ - [What is in the box](#what-is-in-the-box)
35
+ - [Columns](#columns)
36
+ - [Hidden](#hidden)
37
+ - [Guarded](#guarded)
38
+ - [Sensitive](#sensitive)
39
+ - [Relations](#relations)
40
+ - [Operators](#operators)
41
+ - [Page and aggregate](#page-and-aggregate)
42
+ - [Request filters](#request-filters)
43
+ - [Presets](#presets)
44
+ - [Validation](#validation)
45
+ - [Transactions](#transactions)
46
+ - [Batch and locks](#batch-and-locks)
47
+ - [Traits](#traits)
48
+ - [Archive](#archive)
49
+ - [Tenancy](#tenancy)
50
+ - [Extensions](#extensions)
51
+ - [Domains](#domains)
52
+ - [Functions](#functions)
53
+ - [Triggers](#triggers)
54
+ - [Views](#views)
55
+ - [Roles and grants](#roles-and-grants)
56
+ - [okm ext and okm doctor](#okm-ext-and-okm-doctor)
57
+ - [Linter](#linter)
58
+ - [Reference data](#reference-data)
59
+ - [Backfill](#backfill)
60
+ - [Testing](#testing)
61
+ - [Startup](#startup)
62
+ - [Protected targets](#protected-targets)
21
63
  - [Commands](#commands)
64
+ - [Check a history in CI](#check-a-history-in-ci)
22
65
  - [Roadmap](#roadmap)
23
66
  - [Size](#size)
24
67
  - [Docs](#docs)
@@ -37,7 +80,7 @@ Bun.sql needs no extra package: `import { connect } from "okmodel/pg/bun"`. okmo
37
80
 
38
81
  ## Quickstart
39
82
 
40
- `DATABASE_URL` is a direct Postgres URL, not a pooler. The client, insert, find, and error blocks are one script, `run.ts`. `script.ts` is the `await using` form. The last block calls `db.close()`.
83
+ This builds two tables, applies them, and runs one script. The script writes an author and a note, then reads the note with its author. `DATABASE_URL` is a direct Postgres URL, not a pooler.
41
84
 
42
85
  ### Configure
43
86
 
@@ -53,6 +96,7 @@ if (url === undefined || url.length === 0) {
53
96
  throw new Error("DATABASE_URL is not set");
54
97
  }
55
98
 
99
+ // schema is the file. database is DATABASE_URL.
56
100
  export default defineConfig({
57
101
  schema: "./schema.ts",
58
102
  database: url,
@@ -61,9 +105,7 @@ export default defineConfig({
61
105
 
62
106
  ### Schema
63
107
 
64
- `t.identity()` is the primary key. An insert omits the id, and the row that comes back carries it. Identity ids come back as strings by default. `t.identity({ as: "number" })` returns numbers. Push and reviewed migrations are two ways to do the same job: pick one per database.
65
-
66
- Ids can also be generated in the application. Import `uuidv4`, `uuidv7`, or `okid` from `okmodel/ids` and pass one to `.default()`, or set `defaults.id` on `schema()` for every id column that does not choose its own. A column choice wins. A literal stays a database default. A generator is not stored in the catalog, so changing it does not create a migration, and an insert that bypasses okmodel has to supply the value. An OKID column is text with collation C, so a sortable id orders the same everywhere. Sortable ids include the time they were created.
108
+ `authors` has a unique name. `notes` stores a title and points at an author. `t.identity()` is the primary key. An insert omits the id, and the row that comes back carries it. Identity ids come back as strings by default. `t.identity({ as: "number" })` returns numbers. Push and reviewed migrations are two ways to do the same job: pick one per database.
67
109
 
68
110
  Tested on PostgreSQL 15 to 18.
69
111
 
@@ -82,9 +124,13 @@ const notes = table(
82
124
  {
83
125
  id: t.identity(),
84
126
  title: t.text(),
85
- authorId: t.bigint().references("authors", { columns: ["id"] }),
127
+ // Points at the authors primary key.
128
+ authorId: t.bigint().references("authors"),
129
+ },
130
+ {
131
+ // find({ include: { author: true } }) loads this.
132
+ relations: { author: one("authors") },
86
133
  },
87
- { relations: { author: one("authors") } },
88
134
  );
89
135
 
90
136
  const tables = [authors, notes];
@@ -104,16 +150,18 @@ A protected target refuses push. Production settings are in the [production chec
104
150
 
105
151
  ### Reviewed migrations
106
152
 
107
- Generate writes a SQL file and `.okm`, and apply runs that file later so you can read the migration first.
153
+ Generate writes a SQL file and `.okm`. On an empty database, apply installs that schema and any reference rows. A database that already has history runs the new file, so you can read it first.
108
154
 
109
155
  ```sh
110
156
  bunx okm generate init
111
157
  bunx okm migrate apply
112
158
  ```
113
159
 
160
+ Each step is `expand`, `contract`, or unclassified SQL. Expand is additive. Contract removes or tightens something. On an existing table the planner writes the safe form: a concurrent index, a check or foreign key as `NOT VALID` then `VALIDATE`, and `SET NOT NULL` through a validated check. A backfill step updates rows in batches and resumes after a failure. See [Backfill](#backfill).
161
+
114
162
  ### One client
115
163
 
116
- This module is cached, so the process has one client.
164
+ Import `db` from this file wherever the server handles a request. The process keeps one client.
117
165
 
118
166
  `db.ts`:
119
167
 
@@ -125,9 +173,128 @@ import schema from "./schema.ts";
125
173
  const url = process.env.DATABASE_URL;
126
174
  if (url === undefined || url.length === 0) throw new Error("DATABASE_URL is not set");
127
175
 
176
+ // Import this from the server. The process keeps one client.
128
177
  export const db = connect(url, { schema });
129
178
  ```
130
179
 
180
+ A server keeps this client for the life of the process. A script can use `await using`, which closes the pool at the end of the block. `db.close()` is that call on a line you choose. A pool opened with `ssl` still waits out the driver's 30 second idle timer.
181
+
182
+ ### Write and read
183
+
184
+ The script writes one author and one note, then reads the note with the author attached. `await using` closes the pool when the block ends.
185
+
186
+ `script.ts`:
187
+
188
+ ```ts
189
+ import { connect } from "okmodel/pg/postgresjs";
190
+
191
+ import schema from "./schema.ts";
192
+
193
+ const url = process.env.DATABASE_URL;
194
+ if (url === undefined || url.length === 0) throw new Error("DATABASE_URL is not set");
195
+
196
+ await using db = connect(url, { schema });
197
+ const author = await db.authors.insert({ name: "Lin" });
198
+ const note = await db.notes.insert({ title: "hello", authorId: author.id });
199
+ // include loads the author named on the note.
200
+ const found = await db.notes.find({
201
+ where: { id: note.id },
202
+ limit: 1,
203
+ include: { author: true },
204
+ });
205
+ const row = found[0];
206
+ if (author.name !== "Lin" || row?.title !== "hello" || row.author?.name !== "Lin") {
207
+ throw new Error("insert did not return the row");
208
+ }
209
+ ```
210
+
211
+ ## Core
212
+
213
+ The calls below use the same schema and the same client. Read them in order. Each one uses the row the previous call wrote. The last one closes the client.
214
+
215
+ ### Keys
216
+
217
+ Each kind of key is its own table.
218
+
219
+ #### Identity
220
+
221
+ The quickstart uses this. The database assigns a bigint, the insert leaves the id out, and the row comes back with that id as a string. It works on every supported Postgres version.
222
+
223
+ `identity.ts`:
224
+
225
+ ```ts
226
+ import { schema, table, t } from "okmodel/pg";
227
+
228
+ // The insert leaves id out. The row comes back with it as a string.
229
+ const authors = table("authors", { id: t.identity(), name: t.text() });
230
+ export const app = schema({ tables: [authors] });
231
+ ```
232
+
233
+ #### Number
234
+
235
+ `t.identity({ as: "number" })` is the same key, and the id comes back as a number.
236
+
237
+ `number.ts`:
238
+
239
+ ```ts
240
+ import { schema, table, t } from "okmodel/pg";
241
+
242
+ // Same identity key. The id comes back as a number.
243
+ const counts = table("counts", { id: t.identity({ as: "number" }), name: t.text() });
244
+ export const app = schema({ tables: [counts] });
245
+ ```
246
+
247
+ #### Uuid
248
+
249
+ `t.id()` is a uuid primary key. The default is `uuidv7()`, which needs Postgres 18. On an older server, `okm migrate apply` stops with OKM1812 before it runs any statement. `t.id({ default: "uuidv4" })` uses `gen_random_uuid()`, which Postgres has included since 13. `t.id({ default: "none" })` means the insert supplies the id.
250
+
251
+ #### Generated in the app
252
+
253
+ Import `uuidv4`, `uuidv7`, or `okid` from `okmodel/ids` and pass it to `.default()`. Or set `defaults.id` on `schema()` for every id column that does not choose its own. A choice on the column wins. A generator is not a database default, so changing it does not create a migration, and an insert that bypasses okmodel has to supply the value.
254
+
255
+ `generated.ts`:
256
+
257
+ ```ts
258
+ import { uuidv4 } from "okmodel/ids";
259
+ import { schema, table, t } from "okmodel/pg";
260
+
261
+ // The client fills id when the insert omits it. The database stores no default.
262
+ const sessions = table("sessions", { id: t.text().primaryKey().default(uuidv4) });
263
+ export const app = schema({ tables: [sessions] });
264
+ ```
265
+
266
+ #### Slug
267
+
268
+ `.primaryKey()` on one column is a key you supply, such as a slug. The insert includes it, and an update cannot change it.
269
+
270
+ `slug.ts`:
271
+
272
+ ```ts
273
+ import { schema, table, t } from "okmodel/pg";
274
+
275
+ // The insert supplies slug. An update cannot change it.
276
+ const slugs = table("slugs", { slug: t.text().primaryKey() });
277
+ export const app = schema({ tables: [slugs] });
278
+ ```
279
+
280
+ #### Two columns
281
+
282
+ A key of two columns is the `primaryKey` option on the table. The names are the columns, in order.
283
+
284
+ `members.ts`:
285
+
286
+ ```ts
287
+ import { schema, table, t } from "okmodel/pg";
288
+
289
+ // Both columns together are the key. The insert supplies both.
290
+ const members = table(
291
+ "members",
292
+ { userId: t.integer(), orgId: t.integer() },
293
+ { primaryKey: ["userId", "orgId"] },
294
+ );
295
+ export const app = schema({ tables: [members] });
296
+ ```
297
+
131
298
  ### Insert
132
299
 
133
300
  Insert an author, then a note that points at the author's id.
@@ -136,6 +303,7 @@ Insert an author, then a note that points at the author's id.
136
303
  import { db } from "./db.ts";
137
304
 
138
305
  const author = await db.authors.insert({ name: "Ada" });
306
+ // authorId is the id the insert just returned.
139
307
  const note = await db.notes.insert({
140
308
  title: "hello",
141
309
  authorId: author.id,
@@ -145,11 +313,21 @@ if (author.name !== "Ada" || note.title !== "hello" || author.id.length === 0) {
145
313
  }
146
314
  ```
147
315
 
316
+ ### On conflict
317
+
318
+ The name is unique, so inserting Ada again would fail. `onConflict: "ignore"` skips that second insert. The other form updates the named columns when the row is already there.
319
+
320
+ ```ts
321
+ // Ada is already there. ignore skips this insert.
322
+ await db.authors.insert({ name: "Ada" }, { onConflict: "ignore" });
323
+ ```
324
+
148
325
  ### Find
149
326
 
150
- Load that note and its author by the id the insert returned.
327
+ `find` returns a list, so it needs a `limit` (OKM1101). `include` loads the author on each note. When the relation is itself a list, that include needs its own limit (OKM1105).
151
328
 
152
329
  ```ts
330
+ // limit is required. include loads the author.
153
331
  const found = await db.notes.find({
154
332
  where: { id: note.id },
155
333
  limit: 5,
@@ -161,80 +339,731 @@ if (row?.title !== "hello" || row.author?.name !== "Ada") {
161
339
  }
162
340
  ```
163
341
 
164
- A jsonb filter uses `contains`, and the fragment stays a parameter: `{ meta: contains({ published: true }) }`. `json.set(["published"], true)` writes that path inside `update`. The column builder is `t.json()`; the `json` import is this write namespace.
342
+ ### One
343
+
344
+ `one` returns the single note for that id. More than one match throws `not_unique`.
345
+
346
+ ```ts
347
+ // One row. More than one match throws.
348
+ const single = await db.notes.one({ where: { id: note.id } });
349
+ if (single.title !== "hello") throw new Error("one did not return the note");
350
+ ```
351
+
352
+ ### Count
353
+
354
+ `count` returns how many notes match. It does not return the rows.
355
+
356
+ ```ts
357
+ // How many notes, not the rows themselves.
358
+ if ((await db.notes.count()) < 1) throw new Error("count did not see the note");
359
+ ```
360
+
361
+ ### Exists
362
+
363
+ `exists` returns true when a note matches. It does not return the row.
364
+
365
+ ```ts
366
+ // True or false. The row stays in the database.
367
+ if (!(await db.notes.exists({ where: { id: note.id } }))) {
368
+ throw new Error("exists did not see the note");
369
+ }
370
+ ```
371
+
372
+ ### Update
373
+
374
+ `update` changes the columns in `set` on the rows that match `where`. A call with no `where` is OKM1102. `.all(reason)` is the form that means every row.
165
375
 
166
- An array column uses `contains` and `overlaps` the same way. `arr.append("news")` and `arr.remove("news")` add or remove one element inside `update`.
376
+ ```ts
377
+ // where picks the row. set names the new title.
378
+ await db.notes.update({ where: { id: note.id }, set: { title: "next" } });
379
+ ```
380
+
381
+ ### Delete
382
+
383
+ `delete` removes the rows that match `where`. A call with no `where` is OKM1102. `.all(reason)` is the form that means every row.
384
+
385
+ ```ts
386
+ // where picks the row. Without it the call is refused.
387
+ await db.notes.delete({ where: { id: note.id } });
388
+ ```
167
389
 
168
390
  ### Errors
169
391
 
170
- `safe` returns the `OkmError` instead of throwing when the author name is already used.
392
+ Inserting Ada again fails because the name is unique. `safe` returns that `OkmError` instead of throwing. `kind` is `unique`.
171
393
 
172
394
  ```ts
173
395
  import { OkmError, safe } from "okmodel";
174
396
 
397
+ // safe returns the unique error instead of throwing.
175
398
  const duplicate = await safe(db.authors.insert({ name: "Ada" }));
176
399
  if (duplicate.ok || !(duplicate.error instanceof OkmError) || duplicate.error.kind !== "unique") {
177
400
  throw new Error("expected an OkmError of kind unique");
178
401
  }
402
+ await db.close();
179
403
  ```
180
404
 
181
- ### Close
405
+ ## What is in the box
182
406
 
183
- A script exits when its queries finish. It does not need `close()` for that. `await using` closes the pool at the end of the block. `db.close()` is that call on a line you choose. A server keeps the client and its connections. A pool opened with `ssl` still waits out the driver's 30 second idle timer.
407
+ Each section below is one feature you can add to the schema above.
184
408
 
185
- `script.ts`:
409
+ ### Columns
410
+
411
+ A column can allow only a fixed list of strings. `.picklist()` adds that check to a string column. `t.enum()` creates a Postgres enum, and every column that uses the same name shares the list. A value outside the list is OKM1210. See [known limits](https://github.com/omqkhafi/okmodel/blob/main/docs/known-limits.md).
412
+
413
+ `columns.ts`:
414
+
415
+ ```ts
416
+ import { schema, table, t } from "okmodel/pg";
417
+
418
+ const tasks = table("tasks", {
419
+ id: t.identity(),
420
+ // Only these three strings. Anything else is rejected.
421
+ status: t.varchar(20).picklist(["draft", "active", "done"]),
422
+ // A Postgres enum. Other columns named color share this list.
423
+ color: t.enum("color", ["red", "blue"]),
424
+ });
425
+ export const app = schema({ tables: [tasks] });
426
+ ```
427
+
428
+ ### Hidden
429
+
430
+ A password hash should not come back on an ordinary read. `.hidden()` leaves the column out of `find` and out of `include`. Name it in `select` when that call needs it.
431
+
432
+ `hidden.ts`:
186
433
 
187
434
  ```ts
435
+ import { schema, table, t } from "okmodel/pg";
436
+
437
+ const users = table("users", {
438
+ id: t.identity(),
439
+ email: t.text(),
440
+ // Left out of find and include. A named select still returns it.
441
+ passwordHash: t.text().hidden(),
442
+ });
443
+ export const app = schema({ tables: [users] });
444
+ ```
445
+
446
+ ### Guarded
447
+
448
+ A role should not be set by whatever the caller sent. `.guarded()` drops the column from insert and update. The call that is allowed to set it passes `{ allow: ["role"] }`. Any other call is OKM1190.
449
+
450
+ `guarded.ts`:
451
+
452
+ ```ts
453
+ import { schema, table, t } from "okmodel/pg";
188
454
  import { connect } from "okmodel/pg/postgresjs";
189
455
 
190
- import schema from "./schema.ts";
456
+ // role is dropped from insert and update unless the call names it in allow.
457
+ const users = table("users", { id: t.identity(), email: t.text(), role: t.text().guarded() });
458
+ const app = schema({ tables: [users] });
459
+
460
+ export async function grant(url: string): Promise<void> {
461
+ await using db = connect(url, { schema: app });
462
+ await db.users.insert({ email: "a@b.c", role: "admin" }, { allow: ["role"] });
463
+ }
464
+ ```
465
+
466
+ ### Sensitive
467
+
468
+ A token can be stored and returned, and it still must not appear in a log or an error. `.sensitive()` shows `[redacted]` in logs, errors, and `inspect()`. The value in the database stays the same.
469
+
470
+ `sensitive.ts`:
471
+
472
+ ```ts
473
+ import { schema, table, t } from "okmodel/pg";
474
+
475
+ const sessions = table("sessions", {
476
+ id: t.identity(),
477
+ // Stored as written. Logs, errors, and inspect show [redacted].
478
+ token: t.text().sensitive(),
479
+ });
480
+ export const app = schema({ tables: [sessions] });
481
+ ```
482
+
483
+ ### Relations
484
+
485
+ The quickstart note points at one author. `one` is that author on the note. `many` is the list of notes on the author. `find({ include })` loads the related rows. `manyThrough` is the case with a third table in between, such as labels on a task through `taskLabels`.
486
+
487
+ `relations.ts`:
488
+
489
+ ```ts
490
+ import { many, one, schema, table, t } from "okmodel/pg";
491
+
492
+ // notes is the list of notes on this author.
493
+ const authors = table(
494
+ "authors",
495
+ { id: t.identity() },
496
+ { relations: { notes: many("notes", "authorId") } },
497
+ );
498
+ // author is the one author this note points at.
499
+ const notes = table(
500
+ "notes",
501
+ { id: t.identity(), authorId: t.bigint().references("authors") },
502
+ { relations: { author: one("authors", "authorId") } },
503
+ );
504
+ export const app = schema({ tables: [authors, notes] });
505
+ ```
506
+
507
+ ### Operators
508
+
509
+ `where: { title: "hello" }` matches that exact title. A helper matches something else. `ilike` is a case-insensitive pattern, `contains` looks inside JSON, and `overlaps` looks for a shared array value. On update, `inc` adds to a number, `json.set` writes one JSON field, and `arr.append` adds one array value. The helper is a query parameter, so a JSON body cannot pretend to be one. `iStartsWith`, `iContains`, and `iEndsWith` are not in this version. See [known limits](https://github.com/omqkhafi/okmodel/blob/main/docs/known-limits.md).
510
+
511
+ `operators.ts`:
512
+
513
+ ```ts
514
+ import { arr, contains, eq, ilike, inc, json, overlaps, schema, table, t } from "okmodel/pg";
515
+
516
+ const docs = table("docs", {
517
+ id: t.identity(),
518
+ title: t.text(),
519
+ n: t.integer(),
520
+ tags: t.text().array(),
521
+ meta: t.jsonb<{ readonly published: boolean }>(),
522
+ });
523
+ export const app = schema({ tables: [docs] });
524
+ // Read filters. A plain value would match exactly.
525
+ export const where = {
526
+ title: ilike("%hip%"),
527
+ n: eq(1),
528
+ meta: contains({ published: true }),
529
+ tags: overlaps(["news"]),
530
+ };
531
+ // Write helpers, passed inside update.
532
+ export const set = { n: inc(1), meta: json.set(["published"], true), tags: arr.append("news") };
533
+ ```
534
+
535
+ ### Page and aggregate
536
+
537
+ `page` returns one page of rows and a `next` cursor for the page after it. Pass that cursor back as `after`, with the same `orderBy`. A cursor from a different `orderBy` is OKM1130. `aggregate` counts or groups rows instead of returning them. A group needs a `limit`, or `.all(reason)`. There is no `having`.
538
+
539
+ `page.ts`:
540
+
541
+ ```ts
542
+ import { schema, table, t } from "okmodel/pg";
543
+ import { connect } from "okmodel/pg/postgresjs";
544
+
545
+ const notes = table("notes", { id: t.identity(), title: t.text() });
546
+ const app = schema({ tables: [notes] });
547
+
548
+ export async function report(url: string): Promise<void> {
549
+ await using db = connect(url, { schema: app });
550
+ // next is the cursor for the following page. Pass it back as after.
551
+ const page = await db.notes.page({ orderBy: { title: "asc" }, limit: 20 });
552
+ // One row per title, with a count. groupBy needs a limit.
553
+ await db.notes.aggregate({ count: true, groupBy: ["title"], limit: 10 });
554
+ void page.next;
555
+ }
556
+ ```
557
+
558
+ ### Request filters
559
+
560
+ A request should not be able to filter on every column. `filters` names the columns and the comparisons you accept, and the columns a caller may sort by. `parse` turns that request into `where` and `orderBy`. Naming a hidden column there is OKM1123.
561
+
562
+ `filters.ts`:
563
+
564
+ ```ts
565
+ import { schema, table, t } from "okmodel/pg";
566
+
567
+ const users = table("users", { id: t.identity(), email: t.text() });
568
+ export const app = schema({ tables: [users] });
569
+ // A request may filter email with eq, and may sort by email. Nothing else.
570
+ export const userFilters = users.filters({ allow: { email: ["eq"] }, sort: ["email"] });
571
+ ```
572
+
573
+ ### Presets
574
+
575
+ A filter you use often can live on the table under a name. Here `pending` means the status is `"pending"`. `db.tasks.pending().find({ limit: 20 })` applies it. It is added on top of the tenant and the archive filter, and it cannot remove either.
576
+
577
+ `presets.ts`:
578
+
579
+ ```ts
580
+ import { schema, table, t } from "okmodel/pg";
581
+
582
+ const tasks = table(
583
+ "tasks",
584
+ { id: t.identity(), title: t.text(), status: t.text() },
585
+ {
586
+ // db.tasks.pending().find({ limit: 20 }) adds this filter.
587
+ presets: { pending: (q) => q.where({ status: "pending" }) },
588
+ },
589
+ );
590
+ export const app = schema({ tables: [tasks] });
591
+ ```
592
+
593
+ ### Validation
594
+
595
+ A title can be checked before it is written. `.validate()` stores the rules on the column. They run on insert and update when the schema sets `validation: true` and the file imports `okmodel/validate`. A failed check is OKM1200. `onRead` is stored and is not applied. See [known limits](https://github.com/omqkhafi/okmodel/blob/main/docs/known-limits.md).
596
+
597
+ `validation.ts`:
598
+
599
+ ```ts
600
+ import { schema, table, t } from "okmodel/pg";
601
+ import { v } from "okmodel/validate";
602
+
603
+ const tasks = table("tasks", {
604
+ id: t.identity(),
605
+ // Trim, then require one character. A failure is OKM1200.
606
+ title: t.varchar(8).validate([v.trim(), v.min(1, "title_required")]),
607
+ });
608
+ export const app = schema({ tables: [tasks], validation: true });
609
+ ```
610
+
611
+ ### Transactions
612
+
613
+ Two writes that must succeed or fail together go in `tx()`. The callback gets its own client, and every call on it shares the transaction. A `tx()` inside that callback is a savepoint. `retry` runs the callback again after a serialization failure or a deadlock.
614
+
615
+ `transactions.ts`:
616
+
617
+ ```ts
618
+ import { schema, table, t } from "okmodel/pg";
619
+ import { connect } from "okmodel/pg/postgresjs";
620
+
621
+ const notes = table("notes", { id: t.identity(), title: t.text() });
622
+ const app = schema({ tables: [notes] });
623
+
624
+ export async function save(url: string, title: string): Promise<void> {
625
+ await using db = connect(url, { schema: app });
626
+ // Both calls share one transaction. tx is the client inside it.
627
+ await db.tx(async (tx) => {
628
+ await tx.notes.insert({ title });
629
+ });
630
+ }
631
+ ```
632
+
633
+ ### Batch and locks
634
+
635
+ `batch` sends several writes as one unit. It will not run `restore`, and it will not run a write that uses `expect` (OKM1121). Inside `tx()`, `lock: "update"` makes other transactions wait to change that row, and `advisoryLock` holds a named lock until the transaction ends. A row lock outside `tx()` is OKM1830. See [known limits](https://github.com/omqkhafi/okmodel/blob/main/docs/known-limits.md).
636
+
637
+ `batch.ts`:
638
+
639
+ ```ts
640
+ import { schema, table, t } from "okmodel/pg";
641
+ import { connect } from "okmodel/pg/postgresjs";
642
+
643
+ const notes = table("notes", { id: t.identity(), title: t.text() });
644
+ const app = schema({ tables: [notes] });
645
+
646
+ export async function run(url: string, id: string): Promise<void> {
647
+ await using db = connect(url, { schema: app });
648
+ // One unit. The delete runs with the update.
649
+ await db.batch([
650
+ db.notes.update({ where: { id }, set: { title: "next" } }),
651
+ db.notes.delete({ where: { title: "old" } }),
652
+ ]);
653
+ await db.tx(async (tx) => {
654
+ // lock waits inside the transaction only.
655
+ await tx.notes.find({ where: { id }, limit: 1, lock: "update", wait: "skip" });
656
+ await tx.advisoryLock("notes");
657
+ });
658
+ }
659
+ ```
660
+
661
+ ### Traits
662
+
663
+ `timestamps()` adds `createdAt` and `updatedAt` for you. Insert fills both with the current time. Update changes `updatedAt` and leaves `createdAt`. `{ enforce: "trigger" }` does that in the database as well, so a write that skips the client still updates the time.
664
+
665
+ `traits.ts`:
666
+
667
+ ```ts
668
+ import { schema, table, t } from "okmodel/pg";
669
+ import { timestamps } from "okmodel/traits";
670
+
671
+ // Adds createdAt and updatedAt. The insert does not set them.
672
+ const notes = table("notes", { id: t.identity(), title: t.text() }, { traits: [timestamps()] });
673
+ export const app = schema({ tables: [notes] });
674
+ ```
675
+
676
+ ### Archive
677
+
678
+ `archivable()` keeps the row and hides it from ordinary reads. `archive()` marks the matching rows and returns an `archiveId`. `restore({ archiveId })` brings that set back. `withArchived()` includes hidden rows. `onlyArchived()` reads only those rows. Put `cascade` on the parent and name the child tables that should archive with it. One level of children. See [known limits](https://github.com/omqkhafi/okmodel/blob/main/docs/known-limits.md).
679
+
680
+ `archive.ts`:
681
+
682
+ ```ts
683
+ import { schema, table, t } from "okmodel/pg";
684
+ import { connect } from "okmodel/pg/postgresjs";
685
+ import { archivable } from "okmodel/traits";
686
+
687
+ // cascade is on the parent. tasks archive and restore with the list.
688
+ const lists = table(
689
+ "lists",
690
+ { id: t.identity() },
691
+ { traits: [archivable({ cascade: ["tasks"] })] },
692
+ );
693
+ const tasks = table(
694
+ "tasks",
695
+ { id: t.identity(), listId: t.bigint().references("lists") },
696
+ { traits: [archivable()] },
697
+ );
698
+ const app = schema({ tables: [lists, tasks] });
699
+
700
+ export async function hide(url: string, id: string): Promise<void> {
701
+ await using db = connect(url, { schema: app });
702
+ // archive hides the row and returns the id restore uses.
703
+ const archived = await db.lists.archive({ where: { id } });
704
+ await db.lists.onlyArchived().restore({ archiveId: archived.archiveId });
705
+ }
706
+ ```
707
+
708
+ ### Tenancy
709
+
710
+ Every note belongs to one tenant. Column tenancy adds `tenantId` and puts that tenant on every read and write. `db.for({ tenantId }).notes.find({ limit: 20 })` reads one tenant. `global("shared")` marks a table every tenant can read, such as a list of countries. Row-level security is not in this version. See [known limits](https://github.com/omqkhafi/okmodel/blob/main/docs/known-limits.md).
711
+
712
+ `tenancy.ts`:
713
+
714
+ ```ts
715
+ import { schema, table, t } from "okmodel/pg";
716
+ import { columnTenancy, global } from "okmodel/tenancy";
717
+
718
+ // Every read and write adds tenantId.
719
+ const notes = table("notes", { id: t.identity(), title: t.text() });
720
+ // Shared by every tenant. The reason is recorded on the table.
721
+ const countries = table("countries", { id: t.identity() }, { tenancy: global("shared") });
722
+ export const app = schema({
723
+ tenancy: columnTenancy({ key: "tenantId", type: "uuid" }),
724
+ tables: [notes, countries],
725
+ });
726
+ ```
727
+
728
+ ### Extensions
729
+
730
+ `citext` is case-insensitive text. `pg_trgm` searches by similar chunks of text. Declare the extension on the schema and the migration creates it before the tables that use it. `gin` stores the trigram index. `okm ext check` compares the declaration with the server. A missing extension is OKM1811, and that check runs before any statement.
731
+
732
+ `extensions.ts`:
733
+
734
+ ```ts
735
+ import { schema, table, t } from "okmodel/pg";
736
+ import { citext as citextExtension } from "okmodel/pg/citext";
737
+ import { pgTrgm } from "okmodel/pg/pg_trgm";
738
+
739
+ const trigram = pgTrgm();
740
+ const people = table(
741
+ "people",
742
+ {
743
+ email: t.citext(),
744
+ title: t.text(),
745
+ },
746
+ // gin index for similar-text search on title.
747
+ { indexes: (column) => [trigram.gin(column.title.name)] },
748
+ );
749
+ export const app = schema({ extensions: [citextExtension(), trigram], tables: [people] });
750
+ ```
751
+
752
+ ### Domains
753
+
754
+ A domain is a Postgres type with its own check. Here `pos` is an integer that must be greater than zero. TypeScript still sees a number. Changing the base type later is OKM1020. Write the check the way Postgres prints it, including the parentheses. A different spelling is a different check. See [known limits](https://github.com/omqkhafi/okmodel/blob/main/docs/known-limits.md).
755
+
756
+ `domains.ts`:
757
+
758
+ ```ts
759
+ import { schema, table, t } from "okmodel/pg";
760
+
761
+ export const app = schema({
762
+ // pos is an integer that must be greater than zero.
763
+ tables: [table("people", { n: t.domain("pos", t.integer(), "((VALUE > 0))") })],
764
+ });
765
+ ```
766
+
767
+ ### Functions
768
+
769
+ `fn()` is a function that lives in the database. This one takes a title and returns text. A plpgsql function names the tables it reads in `dependsOn`, or the declaration is OKM1824. `security: "definer"` also needs a `searchPath`, or it is OKM1823. A query cannot call it as `fn.slugify(col)` yet. See [known limits](https://github.com/omqkhafi/okmodel/blob/main/docs/known-limits.md).
770
+
771
+ `functions.ts`:
772
+
773
+ ```ts
774
+ import { fn } from "okmodel/fn";
775
+ import { schema, table, t } from "okmodel/pg";
776
+
777
+ const tasks = table("tasks", { id: t.text().primaryKey(), title: t.text() });
778
+ export const app = schema({
779
+ tables: [tasks],
780
+ functions: [
781
+ // plpgsql must name the tables it uses.
782
+ fn("slug", {
783
+ arguments: [{ name: "title", type: "text" }],
784
+ returns: "text",
785
+ language: "plpgsql",
786
+ body: "begin return title; end",
787
+ dependsOn: [tasks],
788
+ }),
789
+ ],
790
+ });
791
+ ```
792
+
793
+ ### Triggers
794
+
795
+ A trigger runs a function when a row changes. This one runs `touch` before each update of `tasks` and returns the new row. The function has to be listed on the schema. `timestamps({ enforce: "trigger" })` is the built-in form of this for `updatedAt`. See [known limits](https://github.com/omqkhafi/okmodel/blob/main/docs/known-limits.md).
796
+
797
+ `triggers.ts`:
798
+
799
+ ```ts
800
+ import { fn, trigger } from "okmodel/fn";
801
+ import { schema, table, t } from "okmodel/pg";
802
+
803
+ const tasks = table("tasks", { id: t.text().primaryKey(), title: t.text() });
804
+ const touch = fn("touch", {
805
+ returns: "trigger",
806
+ language: "plpgsql",
807
+ volatility: "volatile",
808
+ body: "begin return new; end",
809
+ dependsOn: [tasks],
810
+ });
811
+ export const app = schema({
812
+ tables: [tasks],
813
+ functions: [touch],
814
+ triggers: [
815
+ // Runs touch before each row update and returns the new row.
816
+ trigger("tasks_touch", {
817
+ on: tasks,
818
+ timing: "before",
819
+ events: ["update"],
820
+ level: "row",
821
+ calls: touch,
822
+ }),
823
+ ],
824
+ });
825
+ ```
826
+
827
+ ### Views
828
+
829
+ A view is a saved query. You give it the SQL and the columns that query returns. `db.views.active.find({ limit: 20 })` reads `active`. That handle has no insert or update. There is no query-builder form yet. `okm check` reprints the query on the connected server before it compares, so a difference that is only how that server prints the query is not drift. A materialized view that refreshes while people are reading it needs a unique index, or the declaration is OKM1822. See [known limits](https://github.com/omqkhafi/okmodel/blob/main/docs/known-limits.md).
830
+
831
+ `views.ts`:
832
+
833
+ ```ts
834
+ import { schema, table, t } from "okmodel/pg";
835
+ import { materializedView, view } from "okmodel/view";
836
+
837
+ const tasks = table("tasks", { id: t.text().primaryKey(), title: t.text() });
838
+ const columns = [
839
+ { name: "id", type: "text" },
840
+ { name: "title", type: "text" },
841
+ ];
842
+ export const app = schema({
843
+ tables: [tasks],
844
+ views: [
845
+ // A saved query. find reads it. The handle has no insert.
846
+ view("active", {
847
+ columns,
848
+ query: "SELECT id,\n title\n FROM tasks\n WHERE title IS NOT NULL",
849
+ }),
850
+ // Concurrent refresh needs the unique index.
851
+ materializedView("sums", {
852
+ columns,
853
+ query: "SELECT id,\n title\n FROM tasks",
854
+ refresh: "concurrently",
855
+ indexes: [{ columns: ["id"], unique: true }],
856
+ }),
857
+ ],
858
+ });
859
+ ```
860
+
861
+ ### Roles and grants
862
+
863
+ The migration connects as one role and the app connects as another. `roles` names both. The app role receives select, insert, update, and delete on tables and views, select on materialized views, execute on functions, and usage plus select on sequences. Apply runs as the migration role, and switches to it with `SET ROLE` when the connection is someone else. The app role is a role you already created, unless you list it in `managed`. Grants on one column, and row-level security, are not in this version. See [known limits](https://github.com/omqkhafi/okmodel/blob/main/docs/known-limits.md).
864
+
865
+ `roles.ts`:
866
+
867
+ ```ts
868
+ import { defineConfig } from "okmodel/migrate";
191
869
 
192
870
  const url = process.env.DATABASE_URL;
193
871
  if (url === undefined || url.length === 0) throw new Error("DATABASE_URL is not set");
194
872
 
195
- await using db = connect(url, { schema });
196
- const author = await db.authors.insert({ name: "Lin" });
197
- if (author.name !== "Lin" || author.id.length === 0) {
198
- throw new Error("insert did not return the row");
199
- }
873
+ export default defineConfig({
874
+ schema: "./schema.ts",
875
+ database: url,
876
+ // Apply uses the migration role. The app uses the app role.
877
+ roles: { migration: "okm_migrate", app: "okm_app", managed: [{ name: "okm_migrate" }] },
878
+ });
200
879
  ```
201
880
 
881
+ ### okm ext and okm doctor
882
+
883
+ `okm ext list` prints the extensions this server can install, and the version that is already installed. `okm ext check` compares that list with the schema. `okm doctor` lists the triggers on each table. `okm doctor OKM1811` prints what that error code means. `okm ext test` and `okm ext scaffold` are not in this version. See [known limits](https://github.com/omqkhafi/okmodel/blob/main/docs/known-limits.md).
884
+
885
+ ```text
886
+ okm ext list
887
+ okm ext check
888
+ okm doctor
889
+ okm doctor OKM1811
890
+ ```
891
+
892
+ ### Linter
893
+
894
+ A migration plan is checked before it runs. Dropping a table, renaming a column, or adding a unique constraint on a table that already exists is an error. On an existing table the planner writes the safe form: a concurrent index, a check or foreign key as `NOT VALID` then `VALIDATE`, and `SET NOT NULL` through a validated check. The same statements written by hand, without that form, are errors. A type change that rewrites the table stays a warning. `okm generate` prints the finding and still writes the file. `okm migrate plan` and `okm check` exit non-zero on an error. `okm migrate apply` refuses with OKM1510 before any statement. The linter reads the plan and the catalogs. It does not connect. See [the linter](https://github.com/omqkhafi/okmodel/blob/main/docs/linter.md).
895
+
896
+ ```text
897
+ error OKM1511 step 1: drops a table -- fix: Stop reading the table in an expand migration, then drop it in a later contract. Or allow OKM1511 with a reason.
898
+ ```
899
+
900
+ ```sql
901
+ -- okm-allow OKM1511: the table is empty and nothing reads it
902
+ drop table "public"."notes";
903
+ ```
904
+
905
+ ### Reference data
906
+
907
+ Rows the application needs are declared on the table. Apply on an empty database inserts a missing key. It does not update or delete. The rows are not part of the catalog hash, so a new key does not need a DDL migration.
908
+
909
+ `reference.ts`:
910
+
202
911
  ```ts
203
- await db.close();
912
+ import { schema, table, t } from "okmodel/pg";
913
+
914
+ const roles = table(
915
+ "roles",
916
+ { code: t.text().primaryKey(), label: t.text() },
917
+ {
918
+ reference: {
919
+ key: "code",
920
+ rows: [{ code: "admin", label: "Admin" }],
921
+ },
922
+ },
923
+ );
924
+
925
+ export default schema({ tables: [roles] });
204
926
  ```
205
927
 
206
- ## Keys
928
+ ### Backfill
929
+
930
+ A backfill is one idempotent `UPDATE` in the migration file. `$1` is the exclusive lower bound and `$2` is the inclusive upper bound. Null opens that side. Apply commits one batch at a time and resumes from `okm_backfill`. There is no `okm backfill` command. A protected target refuses the step unless that invocation passes `--allow-protected`.
207
931
 
208
- `t.identity()` is a bigint identity primary key. Insert and update omit it. It works on every supported Postgres version. The quickstart uses it.
932
+ ```sql
933
+ -- name: fill
934
+ -- class: expand
935
+
936
+ -- class: expand
937
+ -- action: backfill
938
+ -- lock: ROW EXCLUSIVE
939
+ -- transactional: false
940
+ -- backfill table="public"."notes" key="id" batch=10
941
+ update "public"."notes" set "title" = 'noted' where "title" = 'hello' and ("id" > $1 or $1 is null) and ("id" <= $2 or $2 is null);
942
+ ```
209
943
 
210
- `t.id()` is a uuid primary key. The default is `uuidv7()`, which needs Postgres 18; on an older server `okm migrate apply` stops with OKM1812 before it runs any statement. `t.id({ default: "uuidv4" })` uses `gen_random_uuid()`, built in from Postgres 13. `t.id({ default: "none" })` takes the id on insert and omits it from update.
944
+ ### Testing
211
945
 
212
- `.primaryKey()` on a column is a natural key. Insert supplies it. Update cannot change it. A composite key is the `primaryKey` option on the table, naming the columns in order.
946
+ `okmodel/testing` opens a real pool. `factories` insert rows, `expectQueries` counts statements, and `isolation()` checks that tenant A cannot see tenant B. `okm seed <file>` calls the file's default export with that harness. The target must already be migrated. A protected target is refused unless `--allow-protected`.
947
+
948
+ `factory.ts`:
949
+
950
+ ```ts
951
+ import { schema, table, t } from "okmodel/pg";
952
+ import { open } from "okmodel/pg/pglite";
953
+ import { testing } from "okmodel/testing";
954
+
955
+ const notes = table("notes", { id: t.identity(), title: t.text() });
956
+ const app = schema({ tables: [notes] });
957
+ const harness = await testing(app, { driver: open() });
958
+ const factories = harness.factories({
959
+ notes: (x) => ({ title: x.words(2) }),
960
+ });
961
+ await harness.expectQueries(1, () => factories.notes.create());
962
+ const rows = await harness.db.notes.find({ limit: 5 });
963
+ if (rows.length !== 1) throw new Error("expected one note");
964
+ await harness.close();
965
+ ```
966
+
967
+ `seed.ts`:
968
+
969
+ ```ts
970
+ export default async function seed(t: {
971
+ factories(definitions: {
972
+ authors(x: { words(count: number): string }): { name: string };
973
+ notes(x: { words(count: number): string; ref(table: string): unknown }): {
974
+ title: string;
975
+ authorId: unknown;
976
+ };
977
+ }): {
978
+ notes: { create(): Promise<unknown> };
979
+ };
980
+ }): Promise<void> {
981
+ const factories = t.factories({
982
+ authors: (x) => ({ name: x.words(2) }),
983
+ notes: (x) => ({ title: x.words(2), authorId: x.ref("authors") }),
984
+ });
985
+ await factories.notes.create();
986
+ }
987
+ ```
988
+
989
+ ```sh
990
+ bunx okm seed seed.ts
991
+ ```
992
+
993
+ ### Startup
994
+
995
+ `connect()` compares the app with `okm_history`. A database that is ahead by expand migrations still opens. Ahead by a contract migration, or behind the app, is OKM1520 and names the migration. `okm migrate status` prints the same states, plus `failed at step N (resume with okm migrate apply)`.
996
+
997
+ ### Protected targets
998
+
999
+ `protected: true` is a flag on the target, not on the name and not on `NODE_ENV`. Plan, status, check, ext check, and drift stay allowed. Expand and reference rows stay allowed. An empty protected database can be provisioned. Contract, unclassified SQL, push, backfill, and seed are OKM1850 unless that invocation passes `--allow-protected`. `okm migrate check` writes a scratch schema, so it stays refused, and the flag does not apply. Point it at a throwaway Postgres. Protection does not affect `connect()`.
213
1000
 
214
1001
  ## Commands
215
1002
 
216
- | Command | What it does |
217
- | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
218
- | `okm build` | Validates the schema and writes `.okm/` (catalog, hash, emitted row types). `okm generate` writes those files too. |
219
- | `okm check` | Reports a stale `renamedFrom` and a table file the schema does not import. |
220
- | `okm generate [name]` | Writes a SQL migration and `.okm/`. The name defaults to `migration`. Prints `no changes` when the schema matches. |
221
- | `okm dev` | Uses a target named `dev`, or creates a PGlite database in `.okm/dev-db`. It does not apply migrations or write the catalog. |
222
- | `okm push` | Applies the schema directly. Refused when the target is protected. |
223
- | `okm migrate plan <name>` | Prints the plan and its class. The name is required. |
224
- | `okm migrate apply` | Replays migration files on the database. |
225
- | `okm migrate status` | Prints version, catalog hash, and state for each target. |
226
- | `okm --version` | Prints the package version. |
1003
+ | Command | What it does |
1004
+ | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1005
+ | `okm build` | Validates the schema and writes `.okm/`. Does not connect. |
1006
+ | `okm check` | Lints the schema and, after `okm_meta` exists, compares the database. Drift is OKM1520. Allowed on a protected target. |
1007
+ | `okm generate [name]` | Writes a SQL migration and `.okm/`. Prints lint findings and still writes the file. Offline. |
1008
+ | `okm dev` | Opens a PGlite database in `.okm/dev-db`, or a target named `dev`. It does not apply migrations. |
1009
+ | `okm push` | Applies the schema directly. OKM1850 on a protected target unless `--allow-protected`. |
1010
+ | `okm migrate plan <name>` | Prints each step's class and lock, plus a row estimate when the target answers. Read-only on a protected target. An error finding exits non-zero. |
1011
+ | `okm migrate apply` | Installs the head snapshot on an empty database, or runs pending files. Expand is allowed on a protected target. Contract, unclassified SQL, and backfill need `--allow-protected`. |
1012
+ | `okm migrate check` | Replays the history in a scratch schema and checks the previous catalog, the head, and the linter. Prints `ok N migrations`. Refused on a protected target, and `--allow-protected` does not apply. |
1013
+ | `okm migrate status` | Prints version, catalog hash, and state. Read-only on a protected target. An unfinished backfill is listed under the table. |
1014
+ | `okm seed <file>` | Runs the file's default export against the migrated target. OKM1850 on a protected target unless `--allow-protected`. |
1015
+ | `okm ext list` | Prints extensions the server can install. Read-only on a protected target. |
1016
+ | `okm ext check` | Compares installed extensions with the schema. OKM1811 if one is missing, OKM1812 if the pin is not met. Read-only on a protected target. `okm ext test` and `okm ext scaffold` are not in this version. |
1017
+ | `okm doctor [code]` | Lists triggers, or explains one error code. A role check is read-only on a protected target. |
1018
+ | `okm --version` | Prints the package version. |
227
1019
 
228
1020
  `okmodel` and `okm` are the same command.
229
1021
 
1022
+ ## Check a history in CI
1023
+
1024
+ `okm migrate check` is the command for a pipeline. It applies every migration into a scratch schema, plans each result back to that file's catalog, checks the previous catalog, requires the last catalog to match the schema, and lints the history. Success prints `ok N migrations`. A failure exits non-zero.
1025
+
1026
+ Point it at a throwaway Postgres. A protected target is refused, and `--allow-protected` does not apply. `defineConfig({ lintFrom: "<migration id>" })` skips lint for files before that id, which is how a project adopts the linter without failing on old migrations. Apply still lints pending migrations only.
1027
+
1028
+ The previous-catalog check is schema-level. It does not prove application behaviour. Tenant targets are not checked.
1029
+
1030
+ ```yaml
1031
+ name: migrate
1032
+ on: [push, pull_request]
1033
+ jobs:
1034
+ check:
1035
+ runs-on: ubuntu-latest
1036
+ services:
1037
+ postgres:
1038
+ image: postgres:17
1039
+ env:
1040
+ POSTGRES_PASSWORD: postgres
1041
+ ports:
1042
+ - 5432:5432
1043
+ options: >-
1044
+ --health-cmd "pg_isready -U postgres"
1045
+ --health-interval 10s
1046
+ --health-timeout 5s
1047
+ --health-retries 5
1048
+ steps:
1049
+ - uses: actions/checkout@v5
1050
+ - uses: oven-sh/setup-bun@v2
1051
+ - run: bun install --frozen-lockfile
1052
+ - run: bunx okm migrate check
1053
+ env:
1054
+ DATABASE_URL: postgres://postgres:postgres@localhost:5432/postgres
1055
+ ```
1056
+
1057
+ The config reads `DATABASE_URL`, and that target is not protected.
1058
+
230
1059
  ## Roadmap
231
1060
 
232
1061
  Status is on the [board](https://github.com/users/omqkhafi/projects/1). Each release is a milestone.
233
1062
 
234
1063
  - [x] [0.1](https://github.com/omqkhafi/okmodel/milestone/1) — Schema, queries, and migrations on PostgreSQL, with postgres.js and PGlite.
235
- - [ ] [0.2](https://github.com/omqkhafi/okmodel/milestone/2) — Hidden and sensitive fields, validation, traits, tenancy, archive and restore, richer relations, presets, transactions, and operators for JSON, arrays, ranges, and search.
236
- - [ ] [0.3](https://github.com/omqkhafi/okmodel/milestone/3) — Extensions, domains, functions, triggers, views, roles, and grants.
237
- - [ ] [0.4](https://github.com/omqkhafi/okmodel/milestone/4) — Safer migration plans, backfill, drift checks, provisioning, reference data, and a testing package.
1064
+ - [x] [0.2](https://github.com/omqkhafi/okmodel/milestone/2) — Hidden and sensitive fields, validation, traits, tenancy, archive and restore, richer relations, presets, transactions, and operators for JSON, arrays, ranges, and search.
1065
+ - [x] [0.3](https://github.com/omqkhafi/okmodel/milestone/3) — Extensions, domains, functions, triggers, views, roles, and grants.
1066
+ - [x] [0.4](https://github.com/omqkhafi/okmodel/milestone/4) — Safer migration plans, backfill, drift checks, provisioning, reference data, and a testing package.
238
1067
  - [ ] [0.5](https://github.com/omqkhafi/okmodel/milestone/5) — A primary with replicas, read routing, and a reference app.
239
1068
 
240
1069
  `okmodel/internal` has no stability promise. Names on that subpath can change or disappear in any release.
@@ -247,11 +1076,11 @@ Measured on this release.
247
1076
 
248
1077
  | | Minified | Gzip | Cold import |
249
1078
  | -------------------------------------------- | -------: | -----: | ----------: |
250
- | Runtime entry | 5,288 | 2,026 | 1.991 ms |
251
- | App startup (10 tables, one find) | 88,938 | 29,778 | 10.380 ms |
252
- | App startup, every 0.2 feature in use (full) | 113,705 | 37,506 | 12.068 ms |
1079
+ | Runtime entry | 5,288 | 2,026 | 2.563 ms |
1080
+ | App startup (10 tables, one find) | 89,461 | 29,720 | 13.379 ms |
1081
+ | App startup, every 0.2 feature in use (full) | 119,936 | 39,121 | 13.745 ms |
253
1082
 
254
- The full app has column tenancy, `archivable()`, `timestamps()`, validation rules, `one`, `many` and `manyThrough` relations, presets, and calls `include`, `page`, `aggregate`, `tx` and `batch`. A feature costs bytes only in an app that uses it: the full app is 24,767 minified and 7,728 gzip bytes above the plain one. The runtime entry and the plain app are gated. The full app is printed, not gated.
1083
+ The full app has column tenancy, `archivable()`, `timestamps()`, validation rules, `one`, `many` and `manyThrough` relations, presets, and calls `include`, `page`, `aggregate`, `tx` and `batch`. A feature costs bytes only in an app that uses it: the full app is 30,475 minified and 9,401 gzip bytes above the plain one. The runtime entry and the plain app are gated. The full app is printed, not gated.
255
1084
 
256
1085
  The rest of the measurements are in [size](https://github.com/omqkhafi/okmodel/blob/main/docs/size.md).
257
1086
 
@@ -259,4 +1088,9 @@ The rest of the measurements are in [size](https://github.com/omqkhafi/okmodel/b
259
1088
 
260
1089
  - [Quickstart](https://github.com/omqkhafi/okmodel/blob/main/docs/quickstart.md)
261
1090
  - [Production checklist](https://github.com/omqkhafi/okmodel/blob/main/docs/production.md)
1091
+ - [Linter](https://github.com/omqkhafi/okmodel/blob/main/docs/linter.md)
1092
+ - [Backfill](https://github.com/omqkhafi/okmodel/blob/main/docs/backfill.md)
1093
+ - [Provisioning](https://github.com/omqkhafi/okmodel/blob/main/docs/provisioning.md)
1094
+ - [Testing](https://github.com/omqkhafi/okmodel/blob/main/docs/testing.md)
262
1095
  - [Known limits](https://github.com/omqkhafi/okmodel/blob/main/docs/known-limits.md)
1096
+ - [Changelog](https://github.com/omqkhafi/okmodel/blob/main/changelog.md)