okmodel 0.6.0 → 0.7.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 (157) hide show
  1. package/README.md +100 -1131
  2. package/dist/adapters/capabilities.d.ts +3 -0
  3. package/dist/adapters/failure.d.ts +13 -2
  4. package/dist/adapters/lazy-errors.d.ts +22 -0
  5. package/dist/adapters/pg/bunsql-extra.d.ts +54 -3
  6. package/dist/adapters/pg/bunsql.d.ts +14 -1
  7. package/dist/adapters/pg/cursor.d.ts +17 -0
  8. package/dist/adapters/pg/no-inflight-timeout.d.ts +11 -8
  9. package/dist/adapters/pg/nodepostgres-extra.d.ts +22 -1
  10. package/dist/adapters/pg/nodepostgres.d.ts +12 -0
  11. package/dist/adapters/pg/pglite-wire.d.ts +24 -0
  12. package/dist/adapters/pg/pglite.d.ts +10 -0
  13. package/dist/adapters/pg/postgres-extra.d.ts +27 -11
  14. package/dist/adapters/pg/reserved.d.ts +42 -0
  15. package/dist/adapters/pg/session.d.ts +0 -18
  16. package/dist/contracts/connection.d.ts +7 -6
  17. package/dist/dialects/pg/floor.d.ts +68 -0
  18. package/dist/dialects/pg/index.d.ts +6 -1
  19. package/dist/dialects/pg/index.js +49 -159
  20. package/dist/dialects/pg/keys.d.ts +11 -8
  21. package/dist/dialects/pg/model.d.ts +40 -0
  22. package/dist/dialects/pg/morph.d.ts +43 -0
  23. package/dist/dialects/pg/operator-fit.d.ts +2 -2
  24. package/dist/dialects/pg/operators.d.ts +14 -7
  25. package/dist/dialects/pg/ops/bucket.d.ts +65 -0
  26. package/dist/dialects/pg/ops/inc.d.ts +2 -2
  27. package/dist/dialects/pg/ops/matches.d.ts +9 -12
  28. package/dist/dialects/pg/ops/relevance.d.ts +13 -0
  29. package/dist/dialects/pg/ops/search-query.d.ts +22 -0
  30. package/dist/dialects/pg/ops/window.d.ts +103 -0
  31. package/dist/dialects/pg/preset.d.ts +1 -1
  32. package/dist/dialects/pg/relations.d.ts +100 -3
  33. package/dist/dialects/pg/schema.d.ts +31 -3
  34. package/dist/dialects/pg/view/index.js +1 -1
  35. package/dist/runtime/aggregate.d.ts +8 -2
  36. package/dist/runtime/bucket-group.d.ts +70 -0
  37. package/dist/runtime/conflict.d.ts +22 -4
  38. package/dist/runtime/include.d.ts +0 -8
  39. package/dist/runtime/inflight.d.ts +1 -1
  40. package/dist/runtime/page.d.ts +4 -1
  41. package/dist/runtime/pg/bun.js +12 -6
  42. package/dist/runtime/pg/pg.js +5 -5
  43. package/dist/runtime/pg/pglite.d.ts +1 -0
  44. package/dist/runtime/pg/pglite.js +9 -9
  45. package/dist/runtime/pg/postgresjs.js +5 -5
  46. package/dist/runtime/plan.d.ts +95 -5
  47. package/dist/runtime/read-stream.d.ts +13 -16
  48. package/dist/runtime/result-name.d.ts +17 -0
  49. package/dist/runtime/server-check.d.ts +3 -3
  50. package/dist/runtime/sort-bind.d.ts +21 -0
  51. package/dist/runtime/sort.d.ts +56 -0
  52. package/dist/runtime/sync.d.ts +70 -0
  53. package/dist/runtime/tenancy/index.js +7 -5
  54. package/dist/runtime/text-search.d.ts +20 -0
  55. package/dist/runtime/traits/index.d.ts +80 -0
  56. package/dist/runtime/traits/index.js +175 -11
  57. package/dist/runtime/tree.d.ts +38 -0
  58. package/dist/runtime/types.d.ts +218 -22
  59. package/dist/runtime/validate/index.js +2 -2
  60. package/dist/runtime/version.d.ts +39 -0
  61. package/dist/runtime/window.d.ts +21 -0
  62. package/dist/runtime/write.d.ts +54 -2
  63. package/dist/shared/{wkme6tep.js → 14vx95q4.js} +8 -16
  64. package/dist/shared/1est4ezg.js +313 -0
  65. package/dist/shared/{4az561fn.js → 1qa0qajz.js} +8 -23
  66. package/dist/shared/{2cg3wnxc.js → 1w508jbr.js} +593 -130
  67. package/dist/shared/2c13q96h.js +18 -0
  68. package/dist/shared/{b4v57v3x.js → 2d3xq4ps.js} +2 -2
  69. package/dist/shared/{1nw1f3vs.js → 2shdbn8q.js} +7 -7
  70. package/dist/shared/3v7t1yrv.js +208 -0
  71. package/dist/shared/{x3jc53kg.js → 5e3tf63j.js} +2 -2
  72. package/dist/shared/5fe3kbsh.js +10 -0
  73. package/dist/shared/5v3xf80k.js +37 -0
  74. package/dist/shared/{c58secgj.js → 63qtkrca.js} +38 -4
  75. package/dist/shared/{2z7wv5tj.js → 67txcrcw.js} +55 -34
  76. package/dist/shared/79dt02vc.js +12 -0
  77. package/dist/shared/{8x72s86k.js → 7k9grvf6.js} +10 -4
  78. package/dist/shared/7kms6fvj.js +20 -0
  79. package/dist/shared/7mnme5tn.js +8 -0
  80. package/dist/shared/7n7ddwt4.js +6 -0
  81. package/dist/shared/{5j36z8dn.js → 81ebdx9p.js} +39 -70
  82. package/dist/shared/{knmes2kh.js → 8skf0cam.js} +1 -1
  83. package/dist/shared/9a4ae4p8.js +31 -0
  84. package/dist/shared/9y3mmmh1.js +436 -0
  85. package/dist/shared/ab9gmbwy.js +213 -0
  86. package/dist/shared/{f0f1n281.js → ax7qv55k.js} +2 -2
  87. package/dist/shared/{g90m9b0g.js → aytqh5y2.js} +6 -5
  88. package/dist/shared/{vjpnzwjz.js → b5pftnn2.js} +1 -1
  89. package/dist/shared/{ag4c7516.js → b76b8d95.js} +2 -2
  90. package/dist/shared/{vmfkhszw.js → bg3rym3g.js} +33 -26
  91. package/dist/shared/{mb2ycs1p.js → bm22fvzr.js} +15 -15
  92. package/dist/shared/{q3j1tq7a.js → bz84tkzm.js} +148 -23
  93. package/dist/shared/{31vm914h.js → cm3w0ywp.js} +15 -16
  94. package/dist/shared/cn957f8d.js +179 -0
  95. package/dist/shared/{gwn6v667.js → cnkky55j.js} +25 -14
  96. package/dist/shared/{ys0xzyaj.js → dkxgzaqd.js} +224 -19
  97. package/dist/shared/dzj09cye.js +10 -0
  98. package/dist/shared/exn3sd90.js +359 -0
  99. package/dist/shared/g6evj1j3.js +66 -0
  100. package/dist/shared/ga9j92qj.js +25 -0
  101. package/dist/shared/{t3g0k88x.js → gs74dbj5.js} +16 -12
  102. package/dist/shared/gzaveazc.js +285 -0
  103. package/dist/shared/{2jd1sn0e.js → hyh73qk6.js} +1 -1
  104. package/dist/shared/{r1fdd0f6.js → je4axnm8.js} +5 -2
  105. package/dist/shared/{1f0xa3cb.js → jvd0mqag.js} +3 -3
  106. package/dist/shared/jznfax0y.js +155 -0
  107. package/dist/shared/{cgbamx3e.js → kb2sdhfb.js} +7 -4
  108. package/dist/shared/{wt5rzv1h.js → kr0jzbw2.js} +5 -5
  109. package/dist/shared/{p6bjzq9q.js → ktz42yez.js} +12 -4
  110. package/dist/shared/{p248q79y.js → m6p12kbr.js} +2 -2
  111. package/dist/shared/{r6nwkxnt.js → m7n9h2a5.js} +4 -4
  112. package/dist/shared/{672t5vym.js → mss6ctgv.js} +2 -2
  113. package/dist/shared/{929h19xp.js → mtaszv5a.js} +40 -10
  114. package/dist/shared/{b3awxn7h.js → n816peh1.js} +1 -1
  115. package/dist/shared/nbw1z4yd.js +18 -0
  116. package/dist/shared/{nx9hh281.js → p6qc5gcp.js} +12 -11
  117. package/dist/shared/{pjr6xrm5.js → pbp1ss85.js} +20 -17
  118. package/dist/shared/pt94kz7f.js +6 -0
  119. package/dist/shared/q5c6ngn3.js +13 -0
  120. package/dist/shared/{xq0mvhts.js → rs73fca9.js} +4 -4
  121. package/dist/shared/{r11n8grd.js → sfz1ksn6.js} +7 -4
  122. package/dist/shared/{wynzeggs.js → svncdeh5.js} +6 -6
  123. package/dist/shared/{j60w0dvr.js → tbrvgw6z.js} +57 -38
  124. package/dist/shared/te5as7z7.js +622 -0
  125. package/dist/shared/{ttmg09vd.js → tsvww22q.js} +1 -1
  126. package/dist/shared/{y2t3jktd.js → ttsqgp4p.js} +19 -12
  127. package/dist/shared/{x72jb7ad.js → v8g1vgv8.js} +1 -1
  128. package/dist/shared/{sbdme3vy.js → vb6qfyve.js} +60 -10
  129. package/dist/shared/{5d8t84hg.js → vczs8gd4.js} +14 -14
  130. package/dist/shared/{5yv4k6a6.js → vqrjpcqn.js} +144 -2
  131. package/dist/shared/{3fqwmr09.js → w72kgg4q.js} +4 -4
  132. package/dist/shared/{1z04fa85.js → w79hsckn.js} +12 -57
  133. package/dist/shared/{09p049xa.js → wa07eas9.js} +42 -14
  134. package/dist/shared/{32cnm7kn.js → x933k9a3.js} +74 -38
  135. package/dist/shared/{n076ydsc.js → xhfsfkgk.js} +62 -28
  136. package/dist/shared/xjk7hnn5.js +272 -0
  137. package/dist/shared/{hazqqecq.js → xnxsed62.js} +50 -21
  138. package/dist/shared/y6njgyda.js +249 -0
  139. package/dist/shared/{8etn7d8w.js → z7s6fpxv.js} +1 -1
  140. package/dist/shared/{n7mcc1gk.js → zchaghkf.js} +4 -3
  141. package/dist/shared/zm0ptry0.js +40 -0
  142. package/dist/shared/{nsva2a6b.js → znm0bpp5.js} +3 -0
  143. package/dist/shared/zp9fmend.js +145 -0
  144. package/dist/tooling/cli.js +11 -11
  145. package/dist/tooling/migrate/engine.d.ts +3 -2
  146. package/dist/tooling/migrate/index.js +7 -7
  147. package/dist/tooling/testing/index.js +1 -1
  148. package/package.json +4 -2
  149. package/dist/shared/3qnhc7w5.js +0 -38
  150. package/dist/shared/7m88x3e9.js +0 -45
  151. package/dist/shared/8dqhth8c.js +0 -12
  152. package/dist/shared/d5azex6s.js +0 -6
  153. package/dist/shared/j3rkk835.js +0 -99
  154. package/dist/shared/k68eedmy.js +0 -85
  155. package/dist/shared/venqrjna.js +0 -216
  156. package/dist/shared/wxr8cwns.js +0 -6
  157. package/dist/shared/zm0mafk4.js +0 -92
package/README.md CHANGED
@@ -1,172 +1,93 @@
1
- # OKModel
2
-
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
-
5
- Apache-2.0. The published version is [okmodel on npm](https://www.npmjs.com/package/okmodel).
6
-
7
- ## Contents
8
-
9
- - [Install](#install)
10
- - [Quickstart](#quickstart)
11
- - [Configure](#configure)
12
- - [Schema](#schema)
13
- - [Push](#push)
14
- - [Reviewed migrations](#reviewed-migrations)
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)
25
- - [Insert](#insert)
26
- - [On conflict](#on-conflict)
27
- - [Find](#find)
28
- - [One](#one)
29
- - [Count](#count)
30
- - [Exists](#exists)
31
- - [Update](#update)
32
- - [Delete](#delete)
33
- - [Errors](#errors)
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
- - [Topology](#topology)
62
- - [Reference app](#reference-app)
63
- - [Startup](#startup)
64
- - [Protected targets](#protected-targets)
65
- - [Commands](#commands)
66
- - [Check a history in CI](#check-a-history-in-ci)
67
- - [Roadmap](#roadmap)
68
- - [Size](#size)
69
- - [Docs](#docs)
1
+ <p align="center">
2
+ <picture>
3
+ <source
4
+ media="(prefers-color-scheme: dark)"
5
+ srcset="https://raw.githubusercontent.com/omqkhafi/okmodel/main/site/public/okm-white.svg"
6
+ />
7
+ <img
8
+ alt="OKModel"
9
+ src="https://raw.githubusercontent.com/omqkhafi/okmodel/main/site/public/okm.svg"
10
+ width="240"
11
+ />
12
+ </picture>
13
+ </p>
14
+
15
+ <p align="center">
16
+ <em>okmodel is a catalog-first TypeScript ORM, PostgreSQL first. The schema is the single source. Migrations and queries come from it.</em>
17
+ </p>
18
+
19
+ <p align="center">
20
+ <a href="https://www.npmjs.com/package/okmodel"><img alt="npm" src="https://img.shields.io/npm/v/okmodel?style=flat-square" /></a>
21
+ <a href="https://www.apache.org/licenses/LICENSE-2.0"><img alt="Apache-2.0" src="https://img.shields.io/npm/l/okmodel?style=flat-square" /></a>
22
+ <a href="https://www.postgresql.org"><img alt="PostgreSQL 15 to 18" src="https://img.shields.io/badge/PostgreSQL-15%E2%80%9318-336791?style=flat-square&logo=postgresql&logoColor=white" /></a>
23
+ <a href="https://github.com/omqkhafi/okmodel/actions/workflows/ci.yml"><img alt="CI" src="https://img.shields.io/github/actions/workflow/status/omqkhafi/okmodel/ci.yml?branch=main&label=CI&style=flat-square" /></a>
24
+ <a href="https://github.com/omqkhafi/okmodel/commits"><img alt="last commit" src="https://img.shields.io/github/last-commit/omqkhafi/okmodel?style=flat-square" /></a>
25
+ </p>
26
+
27
+ <p align="center">
28
+ <a href="https://okm.omqkhafi.dev"><strong>Docs</strong></a> ·
29
+ <a href="https://okm.omqkhafi.dev/docs"><strong>Handbook</strong></a> ·
30
+ <a href="https://okm.omqkhafi.dev/llms.txt"><code>llms.txt</code></a> ·
31
+ <a href="https://www.npmjs.com/package/okmodel"><code>okmodel</code></a>
32
+ </p>
33
+
34
+ CI runs PostgreSQL 15 to 18. Other SQL databases are the direction. Apache-2.0.
70
35
 
71
36
  ## Install
72
37
 
73
- Four Postgres drivers. Pick the one the runtime already has. postgres.js is the default, on Node and Bun. node-postgres is the other choice on Node and Bun when `pg` is already installed. Bun.sql is built into Bun and runs only there. PGlite is in-process, on Node and Bun.
38
+ `okmodel` has no runtime dependencies. Each driver is an optional peer. Pick the one the runtime already has.
74
39
 
75
40
  ```sh
76
41
  bun add okmodel postgres
77
- bun add okmodel pg
78
- bun add okmodel @electric-sql/pglite
79
42
  ```
80
43
 
81
- Bun.sql needs no extra package: `import { connect } from "okmodel/pg/bun"`. okmodel has no runtime dependencies. Each installed driver is an optional peer.
82
-
83
- The `okm` bin's shebang is node, so `bunx okm` runs it with Node even inside a Bun project. Run `bun --bun okm` when the command must use the Bun runtime (Bun.sql runs only there). A `.ts` config file under plain Node needs Node 22.18 or newer for type stripping.
44
+ The other drivers:
84
45
 
85
- ## Quickstart
46
+ ```sh
47
+ bun add okmodel pg
48
+ bun add -D @types/pg
49
+ bun add okmodel @electric-sql/pglite
50
+ bun add okmodel
51
+ ```
86
52
 
87
- 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. Port `6432` and port `6543` count as a pooler. Apply, seed, and check also refuse when the backend pid changes between two statements (OKM1854), unless `--allow-pooler` is set.
53
+ postgres.js is the default on Node and Bun. node-postgres is for a project that already has `pg`. PGlite runs Postgres in the process. The last line is Bun.sql, built into Bun, and it runs only there.
88
54
 
89
- ### Configure
55
+ ## Quick start
90
56
 
91
- Point the CLI at the schema and at that URL.
57
+ Define the table, compile the schema, point the config at it, push, then connect. The same steps are on [Let's start](https://okm.omqkhafi.dev/docs/start).
92
58
 
93
- `okmodel.config.ts`:
59
+ `schema.ts`:
94
60
 
95
61
  ```ts
96
- import { defineConfig } from "okmodel/migrate";
97
-
98
- const url = process.env.DATABASE_URL;
99
- if (url === undefined || url.length === 0) {
100
- throw new Error("DATABASE_URL is not set");
101
- }
62
+ import { schema, table, t } from "okmodel/pg";
102
63
 
103
- // schema is the file. database is DATABASE_URL.
104
- export default defineConfig({
105
- schema: "./schema.ts",
106
- database: url,
64
+ export const notes = table("notes", {
65
+ id: t.id(),
66
+ title: t.text(),
107
67
  });
108
- ```
109
68
 
110
- ### Schema
111
-
112
- `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.
69
+ export default schema({ tables: [notes] });
70
+ ```
113
71
 
114
- Tested on PostgreSQL 15 to 18.
72
+ `t.id()` stores `gen_random_uuid()`, which works on Postgres 15 to 18. For a large write-heavy table, `defaults: { id: "uuidv7" }` keeps the ids time-ordered and the index local. That choice needs Postgres 18 and `minPostgres: 18`. Omit `minPostgres` unless you need a newer major. `requires: { postgres: ">=18" }` is the same floor and is deprecated.
115
73
 
116
- `schema.ts`:
74
+ `okmodel.config.ts`:
117
75
 
118
76
  ```ts
119
- import { one, schema, table, t } from "okmodel/pg";
77
+ import { defineConfig } from "okmodel/migrate";
120
78
 
121
- const authors = table("authors", {
122
- id: t.identity(),
123
- name: t.text().unique(),
79
+ export default defineConfig({
80
+ schema: "./schema.ts",
81
+ database: process.env.DATABASE_URL!,
124
82
  });
125
-
126
- const notes = table(
127
- "notes",
128
- {
129
- id: t.identity(),
130
- title: t.text(),
131
- // Points at the authors primary key.
132
- authorId: t.bigint().references("authors"),
133
- },
134
- {
135
- // find({ include: { author: true } }) loads this.
136
- relations: { author: one("authors") },
137
- },
138
- );
139
-
140
- const tables = [authors, notes];
141
-
142
- export default schema({ tables });
143
83
  ```
144
84
 
145
- ### Push
146
-
147
- Create the tables with push, which is allowed because this target is not protected.
85
+ `okm push` connects and creates the tables. It does not write a SQL file. A protected target refuses it (OKM1850).
148
86
 
149
87
  ```sh
150
88
  bunx okm push
151
89
  ```
152
90
 
153
- A protected target refuses push. Production settings are in the [production checklist](https://github.com/omqkhafi/okmodel/blob/main/docs/production.md).
154
-
155
- ### Reviewed migrations
156
-
157
- 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.
158
-
159
- ```sh
160
- bunx okm generate init
161
- bunx okm migrate apply
162
- ```
163
-
164
- 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).
165
-
166
- ### One client
167
-
168
- Import `db` from this file wherever the server handles a request. The process keeps one client.
169
-
170
91
  `db.ts`:
171
92
 
172
93
  ```ts
@@ -174,1021 +95,69 @@ import { connect } from "okmodel/pg/postgresjs";
174
95
 
175
96
  import schema from "./schema.ts";
176
97
 
177
- const url = process.env.DATABASE_URL;
178
- if (url === undefined || url.length === 0) throw new Error("DATABASE_URL is not set");
179
-
180
- // Import this from the server. The process keeps one client.
181
- export const db = connect(url, { schema });
182
- ```
183
-
184
- 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.
185
-
186
- ### Write and read
187
-
188
- 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.
189
-
190
- `script.ts`:
191
-
192
- ```ts
193
- import { connect } from "okmodel/pg/postgresjs";
194
-
195
- import schema from "./schema.ts";
196
-
197
- const url = process.env.DATABASE_URL;
198
- if (url === undefined || url.length === 0) throw new Error("DATABASE_URL is not set");
199
-
200
- await using db = connect(url, { schema });
201
- const author = await db.authors.insert({ name: "Lin" });
202
- const note = await db.notes.insert({ title: "hello", authorId: author.id });
203
- // include loads the author named on the note.
204
- const found = await db.notes.find({
205
- where: { id: note.id },
206
- limit: 1,
207
- include: { author: true },
208
- });
209
- const row = found[0];
210
- if (author.name !== "Lin" || row?.title !== "hello" || row.author?.name !== "Lin") {
211
- throw new Error("insert did not return the row");
212
- }
213
- ```
214
-
215
- ## Core
216
-
217
- 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.
218
-
219
- ### Keys
220
-
221
- Each kind of key is its own table.
222
-
223
- #### Identity
224
-
225
- 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.
226
-
227
- `identity.ts`:
228
-
229
- ```ts
230
- import { schema, table, t } from "okmodel/pg";
231
-
232
- // The insert leaves id out. The row comes back with it as a string.
233
- const authors = table("authors", { id: t.identity(), name: t.text() });
234
- export const app = schema({ tables: [authors] });
235
- ```
236
-
237
- #### Number
238
-
239
- `t.identity({ as: "number" })` is the same key, and the id comes back as a number.
240
-
241
- `number.ts`:
242
-
243
- ```ts
244
- import { schema, table, t } from "okmodel/pg";
245
-
246
- // Same identity key. The id comes back as a number.
247
- const counts = table("counts", { id: t.identity({ as: "number" }), name: t.text() });
248
- export const app = schema({ tables: [counts] });
249
- ```
250
-
251
- #### Uuid
252
-
253
- `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.
254
-
255
- #### Generated in the app
256
-
257
- 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.
258
-
259
- `generated.ts`:
260
-
261
- ```ts
262
- import { uuidv4 } from "okmodel/ids";
263
- import { schema, table, t } from "okmodel/pg";
264
-
265
- // The client fills id when the insert omits it. The database stores no default.
266
- const sessions = table("sessions", { id: t.text().primaryKey().default(uuidv4) });
267
- export const app = schema({ tables: [sessions] });
268
- ```
269
-
270
- #### Slug
271
-
272
- `.primaryKey()` on one column is a key you supply, such as a slug. The insert includes it, and an update cannot change it.
273
-
274
- `slug.ts`:
275
-
276
- ```ts
277
- import { schema, table, t } from "okmodel/pg";
278
-
279
- // The insert supplies slug. An update cannot change it.
280
- const slugs = table("slugs", { slug: t.text().primaryKey() });
281
- export const app = schema({ tables: [slugs] });
98
+ export const db = connect(process.env.DATABASE_URL!, { schema });
282
99
  ```
283
100
 
284
- #### Two columns
101
+ ## Basic usage
285
102
 
286
- A key of two columns is the `primaryKey` option on the table. The names are the columns, in order.
103
+ Each call on `db`. [Basic Usage](https://okm.omqkhafi.dev/docs/start/basic-usage) has one example per call.
287
104
 
288
- `members.ts`:
289
-
290
- ```ts
291
- import { schema, table, t } from "okmodel/pg";
292
-
293
- // Both columns together are the key. The insert supplies both.
294
- const members = table(
295
- "members",
296
- { userId: t.integer(), orgId: t.integer() },
297
- { primaryKey: ["userId", "orgId"] },
298
- );
299
- export const app = schema({ tables: [members] });
300
- ```
301
-
302
- ### Insert
303
-
304
- Insert an author, then a note that points at the author's id.
105
+ `notes.ts`:
305
106
 
306
107
  ```ts
307
108
  import { db } from "./db.ts";
308
109
 
309
- const author = await db.authors.insert({ name: "Ada" });
310
- // authorId is the id the insert just returned.
311
- const note = await db.notes.insert({
312
- title: "hello",
313
- authorId: author.id,
314
- });
315
- if (author.name !== "Ada" || note.title !== "hello" || author.id.length === 0) {
316
- throw new Error("insert did not return the row");
317
- }
318
- ```
319
-
320
- ### On conflict
321
-
322
- 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.
323
-
324
- ```ts
325
- // Ada is already there. ignore skips this insert.
326
- await db.authors.insert({ name: "Ada" }, { onConflict: "ignore" });
327
- ```
328
-
329
- ### Find
330
-
331
- `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).
332
-
333
- ```ts
334
- // limit is required. include loads the author.
335
- const found = await db.notes.find({
336
- where: { id: note.id },
337
- limit: 5,
338
- include: { author: true },
339
- });
340
- const row = found[0];
341
- if (row?.title !== "hello" || row.author?.name !== "Ada") {
342
- throw new Error("find did not return the note and its author");
343
- }
344
- ```
345
-
346
- ### One
347
-
348
- `one` returns the note for that id, or null when none matches. More than one match throws `not_unique`.
349
-
350
- ```ts
351
- // One row, or null. More than one match throws.
352
- const single = await db.notes.one({ where: { id: note.id } });
353
- if (single === null || single.title !== "hello") throw new Error("one did not return the note");
354
- ```
355
-
356
- ### Count
357
-
358
- `count` returns how many notes match. It does not return the rows.
359
-
360
- ```ts
361
- // How many notes, not the rows themselves.
362
- if ((await db.notes.count()) < 1) throw new Error("count did not see the note");
363
- ```
364
-
365
- ### Exists
366
-
367
- `exists` returns true when a note matches. It does not return the row.
368
-
369
- ```ts
370
- // True or false. The row stays in the database.
371
- if (!(await db.notes.exists({ where: { id: note.id } }))) {
372
- throw new Error("exists did not see the note");
373
- }
374
- ```
375
-
376
- ### Update
377
-
378
- `update` changes the columns in `set` on the rows that match `where`. A write with no effective predicate, including undefined values, is OKM1102. An empty `or()` branch is OKM1121. `.all(reason)` is the form that means every row.
379
-
380
- ```ts
381
- // where picks the row. set names the new title.
382
- await db.notes.update({ where: { id: note.id }, set: { title: "next" } });
383
- ```
384
-
385
- ### Delete
386
-
387
- `delete` removes the rows that match `where`. A write with no effective predicate, including undefined values, is OKM1102. An empty `or()` branch is OKM1121. `.all(reason)` is the form that means every row.
388
-
389
- ```ts
390
- // where picks the row. Without it the call is refused.
391
- await db.notes.delete({ where: { id: note.id } });
392
- ```
393
-
394
- ### Errors
395
-
396
- Inserting Ada again fails because the name is unique. `safe` returns that `OkmError` instead of throwing. `kind` is `unique`.
397
-
398
- ```ts
399
- import { OkmError, safe } from "okmodel";
400
-
401
- import { db } from "./db.ts";
402
-
403
- // safe returns the unique error instead of throwing.
404
- const duplicate = await safe(db.authors.insert({ name: "Ada" }));
405
- if (duplicate.ok || !(duplicate.error instanceof OkmError) || duplicate.error.kind !== "unique") {
406
- throw new Error("expected an OkmError of kind unique");
407
- }
408
- await db.close();
409
- ```
410
-
411
- ## What is in the box
412
-
413
- Each section below is one feature you can add to the schema above.
414
-
415
- ### Columns
416
-
417
- 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).
418
-
419
- `columns.ts`:
420
-
421
- ```ts
422
- import { schema, table, t } from "okmodel/pg";
423
-
424
- const tasks = table("tasks", {
425
- id: t.identity(),
426
- // Only these three strings. Anything else is rejected.
427
- status: t.varchar(20).picklist(["draft", "active", "done"]),
428
- // A Postgres enum. Other columns named color share this list.
429
- color: t.enum("color", ["red", "blue"]),
430
- });
431
- export const app = schema({ tables: [tasks] });
432
- ```
433
-
434
- ### Hidden
435
-
436
- A password hash should not come back on an ordinary read, and a caller should not be able to filter on it. `.hidden()` leaves the column out of `find` and out of `include`, and `where` and `orderBy` refuse it (OKM1120). Name it in `select` when that call needs it. `hidden({ filterable: true })` allows `where` and `orderBy` and still leaves it out of the default row. `filters()` still refuses a hidden column.
437
-
438
- `hidden.ts`:
439
-
440
- ```ts
441
- import { schema, table, t } from "okmodel/pg";
442
-
443
- const users = table("users", {
444
- id: t.identity(),
445
- email: t.text(),
446
- // Left out of find and include. A named select still returns it.
447
- passwordHash: t.text().hidden(),
448
- });
449
- export const app = schema({ tables: [users] });
450
- ```
451
-
452
- ### Guarded
453
-
454
- 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.
455
-
456
- `guarded.ts`:
457
-
458
- ```ts
459
- import { schema, table, t } from "okmodel/pg";
460
- import { connect } from "okmodel/pg/postgresjs";
461
-
462
- // role is dropped from insert and update unless the call names it in allow.
463
- const users = table("users", { id: t.identity(), email: t.text(), role: t.text().guarded() });
464
- const app = schema({ tables: [users] });
465
-
466
- export async function grant(url: string): Promise<void> {
467
- await using db = connect(url, { schema: app });
468
- await db.users.insert({ email: "a@b.c", role: "admin" }, { allow: ["role"] });
469
- }
470
- ```
471
-
472
- ### Sensitive
473
-
474
- 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.
475
-
476
- `sensitive.ts`:
477
-
478
- ```ts
479
- import { schema, table, t } from "okmodel/pg";
480
-
481
- const sessions = table("sessions", {
482
- id: t.identity(),
483
- // Stored as written. Logs, errors, and inspect show [redacted].
484
- token: t.text().sensitive(),
485
- });
486
- export const app = schema({ tables: [sessions] });
487
- ```
488
-
489
- ### Relations
490
-
491
- 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`.
492
-
493
- `relations.ts`:
494
-
495
- ```ts
496
- import { many, one, schema, table, t } from "okmodel/pg";
497
-
498
- // notes is the list of notes on this author.
499
- const authors = table(
500
- "authors",
501
- { id: t.identity() },
502
- { relations: { notes: many("notes", "authorId") } },
503
- );
504
- // author is the one author this note points at.
505
- const notes = table(
506
- "notes",
507
- { id: t.identity(), authorId: t.bigint().references("authors") },
508
- { relations: { author: one("authors", "authorId") } },
509
- );
510
- export const app = schema({ tables: [authors, notes] });
511
- ```
512
-
513
- ### Operators
514
-
515
- `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).
516
-
517
- `operators.ts`:
518
-
519
- ```ts
520
- import { arr, contains, eq, ilike, inc, json, overlaps, schema, table, t } from "okmodel/pg";
521
-
522
- const docs = table("docs", {
523
- id: t.identity(),
524
- title: t.text(),
525
- n: t.integer(),
526
- tags: t.text().array(),
527
- meta: t.jsonb<{ readonly published: boolean }>(),
528
- });
529
- export const app = schema({ tables: [docs] });
530
- // Read filters. A plain value would match exactly.
531
- export const where = {
532
- title: ilike("%hip%"),
533
- n: eq(1),
534
- meta: contains({ published: true }),
535
- tags: overlaps(["news"]),
536
- };
537
- // Write helpers, passed inside update.
538
- export const set = { n: inc(1), meta: json.set(["published"], true), tags: arr.append("news") };
539
- ```
540
-
541
- ### Page and aggregate
542
-
543
- `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`.
544
-
545
- `page.ts`:
546
-
547
- ```ts
548
- import { schema, table, t } from "okmodel/pg";
549
- import { connect } from "okmodel/pg/postgresjs";
550
-
551
- const notes = table("notes", { id: t.identity(), title: t.text() });
552
- const app = schema({ tables: [notes] });
553
-
554
- export async function report(url: string): Promise<void> {
555
- await using db = connect(url, { schema: app });
556
- // next is the cursor for the following page. Pass it back as after.
557
- const page = await db.notes.page({ orderBy: { title: "asc" }, limit: 20 });
558
- // One row per title, with a count. groupBy needs a limit.
559
- await db.notes.aggregate({ count: true, groupBy: ["title"], limit: 10 });
560
- void page.next;
110
+ // insert omits id. The row that comes back has it.
111
+ export async function createNote(title: string) {
112
+ return db.notes.insert({ title });
561
113
  }
562
- ```
563
-
564
- ### Request filters
565
-
566
- 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.
567
-
568
- `filters.ts`:
569
-
570
- ```ts
571
- import { schema, table, t } from "okmodel/pg";
572
-
573
- const users = table("users", { id: t.identity(), email: t.text() });
574
- export const app = schema({ tables: [users] });
575
- // A request may filter email with eq, and may sort by email. Nothing else.
576
- export const userFilters = users.filters({ allow: { email: ["eq"] }, sort: ["email"] });
577
- ```
578
-
579
- ### Presets
580
-
581
- 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.
582
-
583
- `presets.ts`:
584
-
585
- ```ts
586
- import { schema, table, t } from "okmodel/pg";
587
-
588
- const tasks = table(
589
- "tasks",
590
- { id: t.identity(), title: t.text(), status: t.text() },
591
- {
592
- // db.tasks.pending().find({ limit: 20 }) adds this filter.
593
- presets: { pending: (q) => q.where({ status: "pending" }) },
594
- },
595
- );
596
- export const app = schema({ tables: [tasks] });
597
- ```
598
-
599
- ### Validation
600
-
601
- 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).
602
-
603
- `validation.ts`:
604
-
605
- ```ts
606
- import { schema, table, t } from "okmodel/pg";
607
- import { v } from "okmodel/validate";
608
-
609
- const tasks = table("tasks", {
610
- id: t.identity(),
611
- // Trim, then require one character. A failure is OKM1200.
612
- title: t.varchar(8).validate([v.trim(), v.min(1, "title_required")]),
613
- });
614
- export const app = schema({ tables: [tasks], validation: true });
615
- ```
616
114
 
617
- ### Transactions
618
-
619
- 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.
620
-
621
- `transactions.ts`:
622
-
623
- ```ts
624
- import { schema, table, t } from "okmodel/pg";
625
- import { connect } from "okmodel/pg/postgresjs";
626
-
627
- const notes = table("notes", { id: t.identity(), title: t.text() });
628
- const app = schema({ tables: [notes] });
629
-
630
- export async function save(url: string, title: string): Promise<void> {
631
- await using db = connect(url, { schema: app });
632
- // Both calls share one transaction. tx is the client inside it.
633
- await db.tx(async (tx) => {
634
- await tx.notes.insert({ title });
635
- });
115
+ // find returns a list and needs a limit. [0] is undefined when nothing matched.
116
+ export async function readNote(id: string) {
117
+ const found = await db.notes.find({ where: { id }, limit: 1 });
118
+ return found[0];
636
119
  }
637
- ```
638
-
639
- ### Batch and locks
640
-
641
- `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).
642
120
 
643
- `batch.ts`:
644
-
645
- ```ts
646
- import { schema, table, t } from "okmodel/pg";
647
- import { connect } from "okmodel/pg/postgresjs";
648
-
649
- const notes = table("notes", { id: t.identity(), title: t.text() });
650
- const app = schema({ tables: [notes] });
651
-
652
- export async function run(url: string, id: string): Promise<void> {
653
- await using db = connect(url, { schema: app });
654
- // One unit. The delete runs with the update.
655
- await db.batch([
656
- db.notes.update({ where: { id }, set: { title: "next" } }),
657
- db.notes.delete({ where: { title: "old" } }),
658
- ]);
659
- await db.tx(async (tx) => {
660
- // lock waits inside the transaction only.
661
- await tx.notes.find({ where: { id }, limit: 1, lock: "update", wait: "skip" });
662
- await tx.advisoryLock("notes");
663
- });
121
+ // one returns the row, or null. More than one match throws not_unique.
122
+ export async function readOne(id: string) {
123
+ return db.notes.one({ where: { id } });
664
124
  }
665
- ```
666
-
667
- ### Traits
668
-
669
- `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.
670
-
671
- `traits.ts`:
672
-
673
- ```ts
674
- import { schema, table, t } from "okmodel/pg";
675
- import { timestamps } from "okmodel/traits";
676
-
677
- // Adds createdAt and updatedAt. The insert does not set them.
678
- const notes = table("notes", { id: t.identity(), title: t.text() }, { traits: [timestamps()] });
679
- export const app = schema({ tables: [notes] });
680
- ```
681
-
682
- ### Archive
683
125
 
684
- `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).
685
-
686
- `archive.ts`:
687
-
688
- ```ts
689
- import { schema, table, t } from "okmodel/pg";
690
- import { connect } from "okmodel/pg/postgresjs";
691
- import { archivable } from "okmodel/traits";
692
-
693
- // cascade is on the parent. tasks archive and restore with the list.
694
- const lists = table(
695
- "lists",
696
- { id: t.identity() },
697
- { traits: [archivable({ cascade: ["tasks"] })] },
698
- );
699
- const tasks = table(
700
- "tasks",
701
- { id: t.identity(), listId: t.bigint().references("lists") },
702
- { traits: [archivable()] },
703
- );
704
- const app = schema({ tables: [lists, tasks] });
705
-
706
- export async function hide(url: string, id: string): Promise<void> {
707
- await using db = connect(url, { schema: app });
708
- // archive hides the row and returns the id restore uses.
709
- const archived = await db.lists.archive({ where: { id } });
710
- await db.lists.onlyArchived().restore({ archiveId: archived.archiveId });
126
+ // where picks the row. A write with no where is OKM1102.
127
+ export async function renameNote(id: string, title: string) {
128
+ await db.notes.update({ where: { id }, set: { title } });
711
129
  }
712
- ```
713
-
714
- ### Tenancy
715
-
716
- 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. Composite tenancy passes every key, `compositeTenancy({ key: ["organizationId", "workspaceId"], type: "uuid" })` and `db.for({ organizationId, workspaceId })`. A table without its own key uses `tenancy: via("project.organization")`, up to three relations, and reads and writes follow that path. `global("shared")` marks a table every tenant can read, such as a list of countries. `rlsTenancy({ key: "tenantId", type: "uuid" })` keeps that predicate and adds row-level security policies. A role that owns the tables, a superuser, or `BYPASSRLS` is refused on the first scoped call. See [known limits](https://github.com/omqkhafi/okmodel/blob/main/docs/known-limits.md).
717
-
718
- `tenancy.ts`:
719
-
720
- ```ts
721
- import { schema, table, t } from "okmodel/pg";
722
- import { columnTenancy, global } from "okmodel/tenancy";
723
-
724
- // Every read and write adds tenantId.
725
- const notes = table("notes", { id: t.identity(), title: t.text() });
726
- // Shared by every tenant. The reason is recorded on the table.
727
- const countries = table("countries", { id: t.identity() }, { tenancy: global("shared") });
728
- export const app = schema({
729
- tenancy: columnTenancy({ key: "tenantId", type: "uuid" }),
730
- tables: [notes, countries],
731
- });
732
- ```
733
-
734
- ### Extensions
735
-
736
- `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.
737
-
738
- `extensions.ts`:
739
-
740
- ```ts
741
- import { schema, table, t } from "okmodel/pg";
742
- import { citext as citextExtension } from "okmodel/pg/citext";
743
- import { pgTrgm } from "okmodel/pg/pg_trgm";
744
-
745
- const trigram = pgTrgm();
746
- const people = table(
747
- "people",
748
- {
749
- email: t.citext(),
750
- title: t.text(),
751
- },
752
- // gin index for similar-text search on title.
753
- { indexes: (column) => [trigram.gin(column.title.name)] },
754
- );
755
- export const app = schema({ extensions: [citextExtension(), trigram], tables: [people] });
756
- ```
757
-
758
- ### Domains
759
-
760
- 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).
761
-
762
- `domains.ts`:
763
-
764
- ```ts
765
- import { schema, table, t } from "okmodel/pg";
766
-
767
- export const app = schema({
768
- // pos is an integer that must be greater than zero.
769
- tables: [table("people", { n: t.domain("pos", t.integer(), "((VALUE > 0))") })],
770
- });
771
- ```
772
-
773
- ### Functions
774
-
775
- `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).
776
-
777
- `functions.ts`:
778
-
779
- ```ts
780
- import { fn } from "okmodel/fn";
781
- import { schema, table, t } from "okmodel/pg";
782
-
783
- const tasks = table("tasks", { id: t.text().primaryKey(), title: t.text() });
784
- export const app = schema({
785
- tables: [tasks],
786
- functions: [
787
- // plpgsql must name the tables it uses.
788
- fn("slug", {
789
- arguments: [{ name: "title", type: "text" }],
790
- returns: "text",
791
- language: "plpgsql",
792
- body: "begin return title; end",
793
- dependsOn: [tasks],
794
- }),
795
- ],
796
- });
797
- ```
798
-
799
- ### Triggers
800
-
801
- 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).
802
-
803
- `triggers.ts`:
804
-
805
- ```ts
806
- import { fn, trigger } from "okmodel/fn";
807
- import { schema, table, t } from "okmodel/pg";
808
-
809
- const tasks = table("tasks", { id: t.text().primaryKey(), title: t.text() });
810
- const touch = fn("touch", {
811
- returns: "trigger",
812
- language: "plpgsql",
813
- volatility: "volatile",
814
- body: "begin return new; end",
815
- dependsOn: [tasks],
816
- });
817
- export const app = schema({
818
- tables: [tasks],
819
- functions: [touch],
820
- triggers: [
821
- // Runs touch before each row update and returns the new row.
822
- trigger("tasks_touch", {
823
- on: tasks,
824
- timing: "before",
825
- events: ["update"],
826
- level: "row",
827
- calls: touch,
828
- }),
829
- ],
830
- });
831
- ```
832
-
833
- ### Views
834
130
 
835
- 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. View handles are camelCased: a view named `active_projects` reads as `db.views.activeProjects`. 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 refreshes with `REFRESH MATERIALIZED VIEW`: the plan populates it with a plain refresh first (Postgres rejects `CONCURRENTLY` on an empty view), then refreshes concurrently when the declaration sets `refresh: "concurrently"`. 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).
836
-
837
- `views.ts`:
838
-
839
- ```ts
840
- import { schema, table, t } from "okmodel/pg";
841
- import { materializedView, view } from "okmodel/view";
842
-
843
- const tasks = table("tasks", { id: t.text().primaryKey(), title: t.text() });
844
- const columns = [
845
- { name: "id", type: "text" },
846
- { name: "title", type: "text" },
847
- ];
848
- export const app = schema({
849
- tables: [tasks],
850
- views: [
851
- // A saved query. find reads it. The handle has no insert.
852
- view("active", {
853
- columns,
854
- query: "SELECT id,\n title\n FROM tasks\n WHERE title IS NOT NULL",
855
- }),
856
- // Concurrent refresh needs the unique index.
857
- materializedView("sums", {
858
- columns,
859
- query: "SELECT id,\n title\n FROM tasks",
860
- refresh: "concurrently",
861
- indexes: [{ columns: ["id"], unique: true }],
862
- }),
863
- ],
864
- });
865
- ```
866
-
867
- ### Roles and grants
868
-
869
- 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 also grants that role select on `okm_meta`, and nothing else there, so `connect()` can read the stored hash. Apply runs as the migration role, and switches to it with `SET ROLE` when the connection is someone else. A role you already created is external, unless you list it in `managed`.
870
-
871
- `roles.reporting` is a third role that can only select. It gets select on tables, views, and materialized views, usage on schemas, and the same select on tables created later. It does not get insert, update, delete, or execute. A hidden column is left out unless `roles.columns` names it. Under `rlsTenancy()` this role is not `BYPASSRLS` and it is not tenant-safe against its own SQL: it sees no tenant rows until the session sets `app.tenant`, and it can set `app.unscoped` itself and then read every tenant. `unscoped()` is the application client's read escape and is not given to this role.
872
-
873
- `roles.columns` grants select or update on named columns: `{ role, on, select, update }`. `on` is the table or view. A listed column grant on a view replaces select on the whole view for the reporting role.
874
-
875
- `withOwner(table(...), "ignored")` keeps a table out of diffs, plans, and `okm check`. `"external"` is known and never created, altered, or dropped. A managed table that becomes either stays in the database. Drop it while it is still managed if it should go away. See [known limits](https://github.com/omqkhafi/okmodel/blob/main/docs/known-limits.md).
876
-
877
- `roles.ts`:
878
-
879
- ```ts
880
- import { defineConfig } from "okmodel/migrate";
881
-
882
- const url = process.env.DATABASE_URL;
883
- if (url === undefined || url.length === 0) throw new Error("DATABASE_URL is not set");
884
-
885
- export default defineConfig({
886
- schema: "./schema.ts",
887
- database: url,
888
- // Apply uses the migration role. The app uses the app role.
889
- roles: {
890
- migration: "okm_migrate",
891
- app: "okm_app",
892
- reporting: "okm_report",
893
- managed: [{ name: "okm_migrate" }, { name: "okm_report", login: true }],
894
- columns: [{ role: "okm_report", on: "tasks", select: ["title"] }],
895
- },
896
- });
897
- ```
898
-
899
- ### okm ext and okm doctor
900
-
901
- `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).
902
-
903
- ```text
904
- okm ext list
905
- okm ext check
906
- okm doctor
907
- okm doctor OKM1811
908
- ```
909
-
910
- ### Linter
911
-
912
- 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).
913
-
914
- ```text
915
- 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.
916
- ```
917
-
918
- ```sql
919
- -- okm-allow OKM1511: the table is empty and nothing reads it
920
- drop table "public"."notes";
921
- ```
922
-
923
- ### Reference data
924
-
925
- 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.
926
-
927
- `reference.ts`:
928
-
929
- ```ts
930
- import { schema, table, t } from "okmodel/pg";
931
-
932
- const roles = table(
933
- "roles",
934
- { code: t.text().primaryKey(), label: t.text() },
935
- {
936
- reference: {
937
- key: "code",
938
- rows: [{ code: "admin", label: "Admin" }],
939
- },
940
- },
941
- );
942
-
943
- export default schema({ tables: [roles] });
944
- ```
945
-
946
- ### Backfill
947
-
948
- 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`.
949
-
950
- ```sql
951
- -- name: fill
952
- -- class: expand
953
-
954
- -- class: expand
955
- -- action: backfill
956
- -- lock: ROW EXCLUSIVE
957
- -- transactional: false
958
- -- backfill table="public"."notes" key="id" batch=10
959
- update "public"."notes" set "title" = 'noted' where "title" = 'hello' and ("id" > $1 or $1 is null) and ("id" <= $2 or $2 is null);
960
- ```
961
-
962
- ### Testing
963
-
964
- `okmodel/testing` opens a real pool. `factories` insert rows, `expectQueries` counts statements, and `isolation()` checks that tenant A cannot see the row it inserted for tenant B, including through a tenant view or materialized view. Each call uses a new pair of tenant ids, deletes what it inserted, and names a factory that is missing. A global table or view is skipped and listed. `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`.
965
-
966
- `factory.ts`:
967
-
968
- ```ts
969
- import { schema, table, t } from "okmodel/pg";
970
- import { open } from "okmodel/pg/pglite";
971
- import { testing } from "okmodel/testing";
972
-
973
- const notes = table("notes", { id: t.identity(), title: t.text() });
974
- const app = schema({ tables: [notes] });
975
- const harness = await testing(app, { driver: open() });
976
- const factories = harness.factories({
977
- notes: (x) => ({ title: x.words(2) }),
978
- });
979
- await harness.expectQueries(1, () => factories.notes.create());
980
- const rows = await harness.db.notes.find({ limit: 5 });
981
- if (rows.length !== 1) throw new Error("expected one note");
982
- await harness.close();
983
- ```
984
-
985
- `seed.ts`:
986
-
987
- ```ts
988
- export default async function seed(t: {
989
- factories(definitions: {
990
- authors(x: { words(count: number): string }): { name: string };
991
- notes(x: { words(count: number): string; ref(table: string): unknown }): {
992
- title: string;
993
- authorId: unknown;
994
- };
995
- }): {
996
- notes: { create(): Promise<unknown> };
997
- };
998
- }): Promise<void> {
999
- const factories = t.factories({
1000
- authors: (x) => ({ name: x.words(2) }),
1001
- notes: (x) => ({ title: x.words(2), authorId: x.ref("authors") }),
1002
- });
1003
- await factories.notes.create();
131
+ export async function removeNote(id: string) {
132
+ await db.notes.delete({ where: { id } });
1004
133
  }
1005
134
  ```
1006
135
 
1007
- ```sh
1008
- bunx okm seed seed.ts
1009
- ```
1010
-
1011
- ### Topology
1012
-
1013
- `connect({ primary, replicas }, options)` opens one pool per endpoint. An automatic read chooses a replica that has replayed at least as far as this client's last committed write. `routing.consistency` is `"session"` by default. `"eventual"` does not keep that watermark. `routing.maxLag` is a duration (`"5s"`, `"500ms"`, `"2m"`) or a size (`"16MB"`, `"512KB"`, `"1GB"`, `"4096B"`). A bare number is rejected. `find({ route: "primary" })` reads the primary. `find({ route: "replica" })` requires a replica that satisfies the same watermark and lag, and it does not fall back to the primary. `db.using("primary")` or `db.using("replica")` returns a client that forces that route. That client has no `close` and no `using`. `onRoute` receives `{ op, endpoint, reason }`. A throw from it is ignored. A string or an existing pool is one endpoint and serves either `route` from it, and it has no `using`.
1014
-
1015
- The watermark is one value for the whole `connect()`. The root, `for()`, `unscoped()`, `using()`, and `reserve()` share it. A write through any of them moves it for the others. A watermark per `for()` client is not in this version.
1016
-
1017
- When replicas are configured and consistency is `"session"`, a committed write reads `pg_current_wal_insert_lsn()` before its promise resolves. That is one extra round trip: on the primary pool after an autocommit `execute` or `batch`, and on the reserved connection after a successful `COMMIT`. A rollback does not read it. `"eventual"`, and a connect with no replicas, do not read it either.
1018
-
1019
- `routing.select` picks among the replicas that passed health, the watermark, and `maxLag`. The default is `"weighted"`. `weighted` is smooth weighted round-robin. Equal weights take turns. A weight of `0` is rejected. `roundRobin` ignores weights and rotates through the eligible replicas. `leastConnections` uses the replica with the fewest statements already in flight on this client. A tie follows configuration order. `latencyAware` uses the replica with the lowest moving average of round-trip time. A function receives each candidate as `{ name, weight, inflight, latencyMs, lag }` and `{ op: "read" }`. `lag` is the number of bytes the replica is behind the primary, or `null` when that distance is unknown. The function returns one of those objects or its `name`. It runs only when an automatic read has two or more candidates.
1020
-
1021
- A write, a batch, a transaction, or a locking read on a replica route is OKM1840. `route: "replica"` or `using("replica")` with no eligible replica is OKM1843, including a topology with no replicas. An automatic read with `routing.fallback: "error"` and no eligible replica is OKM1844. A migrate target that carries `primary`, `replicas`, `weight`, or `pool` is OKM1845. Waiting for a connection past `timeouts.acquire` is OKM1846, and that wait stays on the endpoint's own pool. The rules are in [topology](https://github.com/omqkhafi/okmodel/blob/main/docs/topology.md).
1022
-
1023
- A replica whose pool is at its maximum, with no idle connection and callers waiting, is skipped. If every replica that can serve the read is in that state, the read uses the primary and `onRoute` reports `fallback:saturated`. When healthy replicas exist and none has caught up, or none is inside `maxLag`, the reason is `fallback:behind`. `route: "replica"` still uses a saturated replica, and it still requires the watermark and `maxLag`.
1024
-
1025
- `replicas.ts`:
1026
-
1027
- ```ts
1028
- import { connect } from "okmodel/pg/postgresjs";
1029
-
1030
- import schema from "./schema.ts";
1031
-
1032
- const url = process.env.DATABASE_URL;
1033
- if (url === undefined || url.length === 0) throw new Error("DATABASE_URL is not set");
1034
- const east = process.env.REPLICA_URL;
1035
- if (east === undefined || east.length === 0) throw new Error("REPLICA_URL is not set");
1036
- const west = process.env.REPLICA_URL_WEST ?? east;
1037
-
1038
- const endpoints = {
1039
- primary: url,
1040
- replicas: [{ url: east, weight: 2, name: "east" }, west],
1041
- };
1042
-
1043
- const db = await connect(endpoints, {
1044
- schema,
1045
- routing: { probe: "1s", fallback: "primary", consistency: "session", select: "weighted" },
1046
- onRoute(event) {
1047
- // { op: "read", endpoint: "east", reason: "auto:east" }
1048
- void event;
1049
- },
1050
- });
1051
-
1052
- await db.notes.find({ limit: 50 });
1053
- await db.notes.find({ limit: 50, route: "primary" });
1054
- await db.notes.find({ limit: 50, route: "replica" });
1055
- const replica = db.using("replica");
1056
- await replica.notes.find({ limit: 50 });
1057
- await db.close();
1058
-
1059
- const eventual = await connect(endpoints, {
1060
- schema,
1061
- routing: { consistency: "eventual" },
1062
- });
1063
- await eventual.notes.find({ limit: 50 });
1064
- await eventual.close();
1065
-
1066
- for (const select of ["roundRobin", "leastConnections", "latencyAware"] as const) {
1067
- const client = await connect(endpoints, { schema, routing: { select } });
1068
- await client.notes.find({ limit: 1 });
1069
- await client.close();
1070
- }
1071
-
1072
- const custom = await connect(endpoints, {
1073
- schema,
1074
- routing: {
1075
- select(candidates) {
1076
- return candidates[0] ?? "east";
1077
- },
1078
- },
1079
- });
1080
- await custom.notes.find({ limit: 1 });
1081
- await custom.close();
1082
- ```
1083
-
1084
- ### Reference app
1085
-
1086
- The worked example is a project tracker: workspaces as tenants, archive, a function, two views, three generated migrations, and this topology. It is a private package in the repository, not on npm. CI runs it on the primary and two standbys. Board reads go to a replica. A read just after a write, with replay paused, comes back from the primary. The report uses `route: "replica"`. See the [example app](https://github.com/omqkhafi/okmodel/blob/main/docs/example-app.md) and the [reference app notes](https://github.com/omqkhafi/okmodel/blob/main/packages/reference-app/README.md).
1087
-
1088
- ### Startup
1089
-
1090
- `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)`, where N is the stored step index. Apply's own `failed at step N` counts from 1, the same number the linter prints.
1091
-
1092
- ### Protected targets
1093
-
1094
- `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()`.
1095
-
1096
- ## Commands
1097
-
1098
- | Command | What it does |
1099
- | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1100
- | `okm build` | Validates the schema and writes `.okm/`. Does not connect. |
1101
- | `okm check` | Lints the schema and, after `okm_meta` exists, compares the database. Drift is OKM1520. Allowed on a protected target. |
1102
- | `okm generate [name]` | Writes a SQL migration and `.okm/`. Prints lint findings and still writes the file. Offline. |
1103
- | `okm dev` | Opens a PGlite database in `.okm/dev-db`, or a target named `dev`. It does not apply migrations. |
1104
- | `okm push` | Applies the schema directly. OKM1850 on a protected target unless `--allow-protected`. |
1105
- | `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. |
1106
- | `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`. |
1107
- | `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. |
1108
- | `okm migrate status` | Prints version, catalog hash, and state. Read-only on a protected target. An unfinished backfill is listed under the table. |
1109
- | `okm seed <file>` | Runs the file's default export against the migrated target. OKM1850 on a protected target unless `--allow-protected`. |
1110
- | `okm ext list` | Prints extensions the server can install. Read-only on a protected target. |
1111
- | `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. |
1112
- | `okm doctor [code]` | Lists triggers, or explains one error code. A role check is read-only on a protected target. |
1113
- | `okm --version` | Prints the package version. |
1114
-
1115
- `okmodel` and `okm` are the same command.
1116
-
1117
- ## Check a history in CI
1118
-
1119
- `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.
1120
-
1121
- 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.
1122
-
1123
- The previous-catalog check is schema-level. It does not prove application behaviour. Tenant targets are not checked.
1124
-
1125
- ```yaml
1126
- name: migrate
1127
- on: [push, pull_request]
1128
- jobs:
1129
- check:
1130
- runs-on: ubuntu-latest
1131
- services:
1132
- postgres:
1133
- image: postgres:17
1134
- env:
1135
- POSTGRES_PASSWORD: postgres
1136
- ports:
1137
- - 5432:5432
1138
- options: >-
1139
- --health-cmd "pg_isready -U postgres"
1140
- --health-interval 10s
1141
- --health-timeout 5s
1142
- --health-retries 5
1143
- steps:
1144
- - uses: actions/checkout@v5
1145
- - uses: oven-sh/setup-bun@v2
1146
- - run: bun install --frozen-lockfile
1147
- - run: bunx okm migrate check
1148
- env:
1149
- DATABASE_URL: postgres://postgres:postgres@localhost:5432/postgres
1150
- ```
1151
-
1152
- The config reads `DATABASE_URL`, and that target is not protected.
1153
-
1154
- ## Roadmap
1155
-
1156
- Status is on the [board](https://github.com/users/omqkhafi/projects/1). Each release is a milestone.
1157
-
1158
- - [x] [0.1](https://github.com/omqkhafi/okmodel/milestone/1) — Schema, queries, and migrations on PostgreSQL, with postgres.js and PGlite.
1159
- - [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.
1160
- - [x] [0.3](https://github.com/omqkhafi/okmodel/milestone/3) — Extensions, domains, functions, triggers, views, roles, and grants.
1161
- - [x] [0.4](https://github.com/omqkhafi/okmodel/milestone/4) — Safer migration plans, backfill, drift checks, provisioning, reference data, and a testing package.
1162
- - [x] [0.5](https://github.com/omqkhafi/okmodel/milestone/5) — A primary with replicas, read routing, and a reference app.
1163
- - [x] [0.5.1](https://github.com/omqkhafi/okmodel/milestone/7) — QA fixes for 0.5.0.
1164
- - [x] [0.6](https://github.com/omqkhafi/okmodel/milestone/8) — Composite, path, and row-level tenancy, column grants, a reporting role, and SQL constraint names.
1165
-
1166
- `okmodel/internal` has no stability promise. Names on that subpath can change or disappear in any release.
1167
-
1168
- Each limit, with the version that lifts it, is in [known limits](https://github.com/omqkhafi/okmodel/blob/main/docs/known-limits.md).
1169
-
1170
- ## Size
136
+ `okm push` is for a database you can recreate. A shared database uses reviewed migrations: `okm generate init`, then `okm migrate apply`.
1171
137
 
1172
- Measured on this release.
138
+ ## Next
1173
139
 
1174
- | | Minified | Gzip | Cold import |
1175
- | -------------------------------------------- | -------: | -----: | ----------: |
1176
- | Runtime entry | 5,288 | 2,026 | 1.790 ms |
1177
- | App startup (10 tables, one find) | 90,762 | 30,139 | 10.490 ms |
1178
- | App startup, every 0.2 feature in use (full) | 121,506 | 39,741 | 12.455 ms |
140
+ | Want… | Go to |
141
+ | --------------------------- | ---------------------------------------------------------------------------------------- |
142
+ | One example per client call | [Basic usage](https://okm.omqkhafi.dev/docs/start/basic-usage) |
143
+ | Tables, keys, and relations | [Define](https://okm.omqkhafi.dev/docs/define) |
144
+ | Every feature in one file | [Guide](https://github.com/omqkhafi/okmodel/blob/main/docs/guide.md) |
145
+ | Run it in production | [Production checklist](https://github.com/omqkhafi/okmodel/blob/main/docs/production.md) |
146
+ | What is not built yet | [Known limits](https://github.com/omqkhafi/okmodel/blob/main/docs/known-limits.md) |
1179
147
 
1180
- 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,744 minified and 9,602 gzip bytes above the plain one. The runtime entry and the plain app are gated. The full app is printed, not gated. The plain app's cold import on this sample is under the 15 ms local reference. That figure is printed and is not a gate.
148
+ ## Documentation
1181
149
 
1182
- The rest of the measurements are in [size](https://github.com/omqkhafi/okmodel/blob/main/docs/size.md).
150
+ | Resource | Link |
151
+ | ------------ | ---------------------------------------------------------------------------------- |
152
+ | Docs site | [okm.omqkhafi.dev](https://okm.omqkhafi.dev) |
153
+ | Get started | [/docs/start](https://okm.omqkhafi.dev/docs/start) |
154
+ | Handbook | [/docs](https://okm.omqkhafi.dev/docs) |
155
+ | Changelog | [/changelog](https://okm.omqkhafi.dev/changelog) |
156
+ | Agents index | [/llms.txt](https://okm.omqkhafi.dev/llms.txt) |
157
+ | Size | [`docs/size.md`](https://github.com/omqkhafi/okmodel/blob/main/docs/size.md) |
158
+ | Security | [`SECURITY.md`](https://github.com/omqkhafi/okmodel/blob/main/SECURITY.md) |
159
+ | Contributing | [`CONTRIBUTING.md`](https://github.com/omqkhafi/okmodel/blob/main/CONTRIBUTING.md) |
1183
160
 
1184
- ## Docs
161
+ ## License
1185
162
 
1186
- - [Quickstart](https://github.com/omqkhafi/okmodel/blob/main/docs/quickstart.md)
1187
- - [Production checklist](https://github.com/omqkhafi/okmodel/blob/main/docs/production.md)
1188
- - [Linter](https://github.com/omqkhafi/okmodel/blob/main/docs/linter.md)
1189
- - [Backfill](https://github.com/omqkhafi/okmodel/blob/main/docs/backfill.md)
1190
- - [Provisioning](https://github.com/omqkhafi/okmodel/blob/main/docs/provisioning.md)
1191
- - [Testing](https://github.com/omqkhafi/okmodel/blob/main/docs/testing.md)
1192
- - [Topology](https://github.com/omqkhafi/okmodel/blob/main/docs/topology.md)
1193
- - [Known limits](https://github.com/omqkhafi/okmodel/blob/main/docs/known-limits.md)
1194
- - [Changelog](https://github.com/omqkhafi/okmodel/blob/main/changelog.md)
163
+ Published on [npm](https://www.npmjs.com/package/okmodel). [Apache-2.0](https://www.apache.org/licenses/LICENSE-2.0).