@blueshed/joined 0.2.2 → 0.3.1

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 (237) hide show
  1. package/.claude/skills/joined/SKILL.md +9 -1
  2. package/.claude/skills/joined/reference.md +316 -63
  3. package/.claude/skills/joined-door/SKILL.md +57 -0
  4. package/README.md +19 -50
  5. package/docs/design.md +158 -37
  6. package/docs/introduction.md +27 -27
  7. package/docs/light-and-shadow.svg +2 -1
  8. package/docs/links-and-trust.svg +1 -0
  9. package/docs/stories-to-code.svg +2 -1
  10. package/docs/wire-op.svg +1 -0
  11. package/examples/README.md +20 -0
  12. package/examples/account/account.json +1 -0
  13. package/examples/account/derive.ts +41 -0
  14. package/examples/account/generated/elements.ts +52 -0
  15. package/examples/account/generated/rows.ts +22 -0
  16. package/examples/account/generated/rules.ts +32 -0
  17. package/examples/account/routes.ts +5 -0
  18. package/examples/app.css +11 -1
  19. package/examples/cafe/books.html +2 -2
  20. package/examples/cafe/cafe.css +96 -85
  21. package/examples/cafe/generated/books.rows.ts +22 -0
  22. package/examples/cafe/generated/books.rules.ts +3 -2
  23. package/examples/cafe/generated/kitchen.rows.ts +27 -0
  24. package/examples/cafe/generated/kitchen.rules.ts +11 -1
  25. package/examples/cafe/generated/menu.rows.ts +22 -0
  26. package/examples/cafe/generated/menu.rules.ts +3 -2
  27. package/examples/cafe/generated/order.rows.ts +27 -0
  28. package/examples/cafe/generated/order.rules.ts +11 -1
  29. package/examples/cafe/generated/staff.elements.ts +7 -2
  30. package/examples/cafe/generated/staff.rows.ts +22 -0
  31. package/examples/cafe/generated/staff.rules.ts +9 -1
  32. package/examples/cafe/generated/supplies.queries.ts +4 -2
  33. package/examples/cafe/generated/supplies.rows.ts +22 -0
  34. package/examples/cafe/generated/supplies.rules.ts +17 -1
  35. package/examples/cafe/generated/till.queries.ts +2 -0
  36. package/examples/cafe/generated/till.rows.ts +27 -0
  37. package/examples/cafe/generated/till.rules.ts +11 -1
  38. package/examples/cafe/index.html +14 -15
  39. package/examples/cafe/kitchen.css +11 -19
  40. package/examples/cafe/kitchen.ts +7 -3
  41. package/examples/cafe/look.ts +30 -0
  42. package/examples/cafe/menu.html +10 -26
  43. package/examples/cafe/menu.ts +8 -80
  44. package/examples/cafe/migrations/002-guard-supplies.ts +15 -0
  45. package/examples/cafe/order.html +8 -7
  46. package/examples/cafe/order.ts +6 -2
  47. package/examples/cafe/routes.ts +0 -1
  48. package/examples/cafe/staff.json +5 -0
  49. package/examples/cafe/stories.jsonl +6 -2
  50. package/examples/cafe/supplies.html +35 -34
  51. package/examples/cafe/supplies.ts +59 -39
  52. package/examples/cafe/till.ts +19 -11
  53. package/examples/cafe/views.ts +7 -5
  54. package/examples/chart/arches.ts +150 -0
  55. package/examples/chart/chart.css +11 -0
  56. package/examples/chart/chart.json +87 -0
  57. package/examples/chart/generated/elements.ts +105 -0
  58. package/examples/chart/generated/queries.ts +36 -0
  59. package/examples/chart/generated/rows.ts +27 -0
  60. package/examples/chart/generated/rules.ts +111 -0
  61. package/examples/chart/grid.ts +118 -0
  62. package/examples/chart/index.html +78 -0
  63. package/examples/chart/migrations/001-chart.ts +6 -0
  64. package/examples/chart/migrations/002-create-conditions.ts +6 -0
  65. package/examples/chart/page.ts +20 -0
  66. package/examples/chart/routes.ts +7 -0
  67. package/examples/chart/stories.jsonl +14 -0
  68. package/examples/chart/teeth.ts +57 -0
  69. package/examples/desk/desk.css +6 -10
  70. package/examples/desk/generated/elements.ts +1 -1
  71. package/examples/desk/generated/rows.ts +22 -0
  72. package/examples/desk/generated/rules.ts +34 -1
  73. package/examples/desk/index.html +10 -3
  74. package/examples/desk/lanes.css +21 -19
  75. package/examples/desk/routes.ts +0 -2
  76. package/examples/desk/stories.jsonl +4 -3
  77. package/examples/desk/tally.css +1 -1
  78. package/examples/desk/thumbs.ts +2 -2
  79. package/examples/docs.ts +7 -4
  80. package/examples/hello/generated/elements.ts +2 -2
  81. package/examples/hello/generated/rules.ts +3 -2
  82. package/examples/hello/hello.css +2 -4
  83. package/examples/hello/index.html +10 -3
  84. package/examples/hello/page.ts +4 -4
  85. package/examples/index.html +20 -12
  86. package/examples/notes/generated/elements.ts +112 -0
  87. package/examples/notes/generated/queries.ts +42 -0
  88. package/examples/notes/generated/rows.ts +27 -0
  89. package/examples/notes/generated/rules.ts +133 -0
  90. package/examples/notes/index.html +32 -0
  91. package/examples/notes/look.ts +41 -0
  92. package/examples/notes/migrations/001-notes.ts +7 -0
  93. package/examples/notes/notes.json +78 -0
  94. package/examples/notes/page.ts +21 -0
  95. package/examples/notes/routes.ts +6 -0
  96. package/examples/notes/stories.jsonl +24 -0
  97. package/examples/page.ts +9 -2
  98. package/examples/people/generated/rows.ts +22 -0
  99. package/examples/people/generated/rules.ts +11 -1
  100. package/examples/people/links.ts +8 -9
  101. package/examples/people/people.css +1 -1
  102. package/examples/people/routes.ts +1 -3
  103. package/examples/people/stories.jsonl +1 -0
  104. package/examples/people/view.ts +5 -2
  105. package/examples/trip/generated/elements.ts +5 -3
  106. package/examples/trip/generated/queries.ts +12 -1
  107. package/examples/trip/generated/rows.ts +27 -0
  108. package/examples/trip/generated/rules.ts +56 -2
  109. package/examples/trip/index.html +58 -12
  110. package/examples/trip/line.css +186 -0
  111. package/examples/trip/line.ts +51 -40
  112. package/examples/trip/page.ts +65 -71
  113. package/examples/trip/routes.ts +9 -5
  114. package/examples/trip/stays.css +13 -13
  115. package/examples/trip/stays.ts +15 -10
  116. package/examples/trip/stories.jsonl +2 -0
  117. package/examples/trip/told.ts +3 -26
  118. package/examples/trip/trip.css +16 -0
  119. package/examples/trips/generated/elements.ts +1 -1
  120. package/examples/trips/generated/rows.ts +22 -0
  121. package/examples/trips/generated/rules.ts +9 -1
  122. package/examples/trips/index.html +10 -10
  123. package/examples/trips/map.ts +3 -14
  124. package/examples/trips/new-trip.ts +14 -16
  125. package/examples/trips/trips.css +24 -23
  126. package/examples/weeks/generated/elements.ts +1 -1
  127. package/examples/weeks/generated/queries.ts +11 -0
  128. package/examples/weeks/generated/rows.ts +22 -0
  129. package/examples/weeks/generated/rules.ts +11 -5
  130. package/examples/weeks/routes.ts +3 -2
  131. package/examples/weeks/stories.jsonl +1 -0
  132. package/examples/welcome.css +43 -33
  133. package/package.json +8 -2
  134. package/src/attachment.ts +17 -2
  135. package/src/awesome.ts +103 -0
  136. package/src/board.css +76 -0
  137. package/src/board.ts +173 -0
  138. package/src/cli.ts +28 -3
  139. package/src/compile.ts +821 -109
  140. package/src/definitions.ts +113 -27
  141. package/src/demo.css +2 -5
  142. package/src/draft.ts +48 -27
  143. package/src/drawer.ts +248 -0
  144. package/src/engine.ts +253 -170
  145. package/src/fields.ts +341 -0
  146. package/src/file-value.ts +12 -2
  147. package/src/files.ts +113 -33
  148. package/src/ground.ts +110 -0
  149. package/src/icon-names.ts +19 -2
  150. package/src/keep.ts +16 -3
  151. package/src/kit.ts +51 -0
  152. package/src/link.ts +3 -3
  153. package/src/map.css +140 -0
  154. package/src/map.ts +200 -0
  155. package/src/mcp.ts +129 -24
  156. package/src/members/demo.ts +13 -12
  157. package/src/members/generated/rows.ts +22 -0
  158. package/src/members/generated/rules.ts +3 -2
  159. package/src/members/group.ts +105 -55
  160. package/src/members/keys.ts +95 -79
  161. package/src/members/panel.css +40 -35
  162. package/src/members/panel.ts +58 -37
  163. package/src/migrate.ts +178 -125
  164. package/src/migrations/005-change-kept.ts +7 -0
  165. package/src/month.css +129 -0
  166. package/src/month.ts +179 -0
  167. package/src/ops.ts +40 -1
  168. package/src/page.css +11 -2
  169. package/src/page.ts +68 -17
  170. package/src/parts.css +614 -230
  171. package/src/parts.ts +259 -36
  172. package/src/plane.css +61 -0
  173. package/src/plane.ts +153 -0
  174. package/src/postgres-server.ts +60 -0
  175. package/src/reading.css +73 -0
  176. package/src/reading.ts +238 -0
  177. package/src/rows.css +289 -0
  178. package/src/rows.ts +864 -0
  179. package/src/search.css +80 -0
  180. package/src/search.ts +130 -0
  181. package/src/server.ts +355 -137
  182. package/src/settings.ts +9 -4
  183. package/src/sheet.ts +116 -0
  184. package/src/skill.ts +40 -0
  185. package/src/slots.css +90 -0
  186. package/src/slots.ts +213 -0
  187. package/src/specs.ts +38 -0
  188. package/src/starter.ts +19 -2
  189. package/src/store.ts +224 -161
  190. package/src/stories.ts +43 -11
  191. package/src/surface.ts +164 -0
  192. package/src/time.ts +2 -0
  193. package/src/timeline.css +111 -0
  194. package/src/timeline.ts +235 -0
  195. package/src/toast.ts +21 -48
  196. package/src/together.ts +15 -24
  197. package/src/tokens.css +89 -3
  198. package/src/tokens.json +287 -7
  199. package/src/tool.ts +210 -0
  200. package/src/upkeep.ts +47 -22
  201. package/src/views.css +43 -0
  202. package/src/views.ts +111 -0
  203. package/src/week.css +150 -0
  204. package/src/week.ts +254 -0
  205. package/src/write.ts +326 -78
  206. package/starter/CHANGELOG.md +8 -0
  207. package/starter/CLAUDE.md +9 -3
  208. package/starter/bunfig +5 -0
  209. package/starter/githooks/pre-commit +13 -0
  210. package/starter/prettierignore +5 -0
  211. package/starter/tests/hello.test.ts +2 -0
  212. package/starter/tests/records.test.ts +40 -0
  213. package/starter/todo.jsonl +0 -0
  214. package/docs/learning.md +0 -76
  215. package/examples/cafe/trust.ts +0 -20
  216. package/examples/desk/trust.ts +0 -24
  217. package/examples/people/trust.ts +0 -14
  218. package/examples/trip/answer-rows.ts +0 -70
  219. package/examples/trip/bar.ts +0 -89
  220. package/examples/trip/calendar-map.css +0 -711
  221. package/examples/trip/calendar-map.ts +0 -249
  222. package/examples/trip/drags.ts +0 -143
  223. package/examples/trip/drawer.ts +0 -250
  224. package/examples/trip/event-form.ts +0 -200
  225. package/examples/trip/holding.ts +0 -61
  226. package/examples/trip/map.ts +0 -234
  227. package/examples/trip/month.ts +0 -87
  228. package/examples/trip/other-weeks.ts +0 -67
  229. package/examples/trip/peek.ts +0 -71
  230. package/examples/trip/people-chips.ts +0 -74
  231. package/examples/trip/shell.ts +0 -39
  232. package/examples/trip/trust.ts +0 -51
  233. package/examples/trip/week.ts +0 -237
  234. package/examples/trip/writes.ts +0 -91
  235. package/examples/trip/zones.ts +0 -16
  236. package/examples/weeks/derive.ts +0 -23
  237. package/src/scrim.ts +0 -81
package/src/engine.ts CHANGED
@@ -1,40 +1,118 @@
1
- // The engine beneath the store: SQLite (bun:sqlite, in a file), or Postgres (PGlite, in a folder). Each answers the
2
- // same calls, as bun:sqlite's own: a statement run, its rows got, a transaction (a savepoint, within one), and each
3
- // synchronous, so a write is one transaction and nothing comes between its parts. PGlite answers at once by its
4
- // wire protocol (a query sent whole, its values written into it as literals). What each refuses, in a constraint's
5
- // name or a trigger's words, it throws as Refused; the rest as it was. Where the two say a thing differently, the
6
- // dialect says which.
1
+ // The engine beneath the store: SQLite (bun:sqlite, in a file), or Postgres (a server, by Bun.sql and the URL
2
+ // JOINED_POSTGRES gives, its password with it; or PGlite, in a folder or in memory, for the tests). Each answers the
3
+ // same calls, each a promise: a statement run, its rows got, a transaction (a savepoint, within one). One connection
4
+ // each, its statements in turn, and a transaction holds it: anything asked from outside the transaction while it's
5
+ // open waits for it to end, so nothing comes between a write's parts and nothing sees one half done. Values are sent
6
+ // as parameters (Postgres: $1, $2…), never written into the SQL. What each refuses, in a constraint's name or a
7
+ // trigger's words, it throws as Refused; the rest as it was. Where the two say a thing differently, the dialect says
8
+ // which.
7
9
 
8
10
  import { Database } from "bun:sqlite";
11
+ import { AsyncLocalStorage } from "node:async_hooks";
9
12
 
10
13
  export type Dialect = "sqlite" | "postgres";
11
14
  type Args = unknown[] | Record<string, unknown>;
12
15
  /** A statement, as both engines prepare one: its first row, or all of them. */
13
- export type Statement = { get(...args: unknown[]): any; all(...args: unknown[]): any[] };
16
+ export type Statement = { get(...args: unknown[]): Promise<any>; all(...args: unknown[]): Promise<any[]> };
14
17
  export type Engine = {
15
18
  dialect: Dialect;
16
- run(sql: string, args?: Args): { changes: number };
19
+ run(sql: string, args?: Args): Promise<{ changes: number }>;
17
20
  query(sql: string): Statement;
18
21
  /** fn in a transaction (a savepoint, inside one): its value, or what it threw, all of it undone. */
19
- transaction<T>(fn: () => T): (() => T) & { immediate(): T };
22
+ transaction<T>(fn: () => Promise<T> | T): Promise<T>;
20
23
  /** The transaction's foreign keys held to at its commit, not each statement: rows that link to each other, put in
21
24
  * together. */
22
- defer(): void;
25
+ defer(): Promise<unknown>;
23
26
  /** A table's columns, by name (none: no table). */
24
- columns(table: string): string[];
27
+ columns(table: string): Promise<string[]>;
25
28
  /** The schema a connection's own tables are in (the rows a write changed). */
26
29
  temp: string;
27
- /** Let go: Postgres's once its folder is written (awaited, to open it again). */
28
- close(): void | Promise<void>;
30
+ /** Each payload said on a channel, by any server on the same database, heard (Postgres's LISTEN); SQLite's one
31
+ * server hears none. */
32
+ listen(channel: string, heard: (payload: string) => void): Promise<void>;
33
+ /** A payload said on a channel, as the transaction it's in commits (Postgres's NOTIFY); SQLite's says nothing. */
34
+ notify(channel: string, payload: string): Promise<unknown>;
35
+ /** Let go. */
36
+ close(): Promise<void>;
29
37
  };
30
38
  /** A refusal of the database's, in the words it was given: a constraint's name, or a trigger's message. */
31
39
  export class Refused extends Error {}
32
40
 
41
+ /** What a connection answers: the rows of the last statement, and how many it changed. */
42
+ type Answer = { rows: Record<string, unknown>[]; changes: number };
43
+ /** A connection as the engine asks it: a statement with its values (none: it may be several, in turn). */
44
+ type Connection = { exec(sql: string, args?: unknown[]): Promise<Answer> };
45
+
46
+ /** An engine over one connection: its statements in turn, a transaction holding it (a savepoint within one), and
47
+ * anything asked from outside an open transaction waiting until it ends. */
48
+ function engine(
49
+ dialect: Dialect,
50
+ c: Connection,
51
+ more: Pick<Engine, "defer" | "columns" | "temp" | "listen" | "notify" | "close">,
52
+ ): Engine {
53
+ const inside = new AsyncLocalStorage<{ depth: number }>();
54
+ /** The last transaction asked for: each waits for the one before, and what's outside waits for them all. */
55
+ let last: Promise<unknown> = Promise.resolve();
56
+ const exec = async (sql: string, args?: unknown[]) => {
57
+ if (!inside.getStore()) await last;
58
+ return c.exec(sql, args);
59
+ };
60
+ const flat = (args: unknown[]) => (args.length === 1 && Array.isArray(args[0]) ? (args[0] as unknown[]) : args);
61
+ return {
62
+ dialect,
63
+ run: async (sql, args) => ({ changes: (await exec(sql, args === undefined ? undefined : [args].flat())).changes }),
64
+ query: (sql) => ({
65
+ get: async (...args) => (await exec(sql, flat(args))).rows[0] ?? null,
66
+ all: async (...args) => (await exec(sql, flat(args))).rows,
67
+ }),
68
+ async transaction<T>(fn: () => Promise<T> | T): Promise<T> {
69
+ const at = inside.getStore();
70
+ if (at) {
71
+ const name = `joined_${at.depth}`;
72
+ await c.exec(`SAVEPOINT ${name}`);
73
+ try {
74
+ const done = await inside.run({ depth: at.depth + 1 }, fn);
75
+ await c.exec(`RELEASE SAVEPOINT ${name}`);
76
+ return done;
77
+ } catch (e) {
78
+ await c.exec(`ROLLBACK TO SAVEPOINT ${name}`);
79
+ throw e;
80
+ }
81
+ }
82
+ const before = last;
83
+ let done!: () => void;
84
+ last = new Promise<void>((r) => (done = r));
85
+ await before;
86
+ try {
87
+ await c.exec(dialect === "sqlite" ? "BEGIN IMMEDIATE" : "BEGIN");
88
+ // one write at a time on Postgres too, whichever server makes it: what a write's rules read stays as they read
89
+ // it until it commits (SQLite's BEGIN IMMEDIATE holds the file the same way)
90
+ if (dialect === "postgres") await c.exec(`SELECT pg_advisory_xact_lock(${WRITING})`);
91
+ try {
92
+ const value = await inside.run({ depth: 1 }, fn);
93
+ await c.exec("COMMIT");
94
+ return value;
95
+ } catch (e) {
96
+ await c.exec("ROLLBACK");
97
+ throw e;
98
+ }
99
+ } finally {
100
+ done();
101
+ }
102
+ },
103
+ ...more,
104
+ };
105
+ }
106
+
107
+ /** The lock every server on one Postgres database takes for a write: its number, any one joined's alone. */
108
+ const WRITING = 0x6a6f696e; // "join"
109
+
33
110
  /** SQLite: bun:sqlite's Database, as it is, its constraint failures thrown as Refused. */
34
111
  export function sqlite(file: string, { readonly = false } = {}): Engine {
35
112
  const db = new Database(file, readonly ? { readonly, strict: true } : { create: true, strict: true });
36
- if (!readonly) db.run("PRAGMA journal_mode = WAL");
113
+ // another's write waited for from the first: a store opened by two processes at once (its log recovered by one)
37
114
  db.run("PRAGMA busy_timeout = 5000");
115
+ if (!readonly) db.run("PRAGMA journal_mode = WAL");
38
116
  // a link is a foreign key: what it points at is there, and isn't removed from under it
39
117
  db.run("PRAGMA foreign_keys = ON");
40
118
  // a value's form, as a guard asks it: a regular expression, matched (SQLite has no REGEXP of its own)
@@ -54,37 +132,106 @@ export function sqlite(file: string, { readonly = false } = {}): Engine {
54
132
  ? new Date(at + (((d * 24 + h) * 60 + m) * 60 + s) * 1000).toISOString().slice(0, 19)
55
133
  : null;
56
134
  });
57
- const said = <T>(f: () => T): T => {
135
+ const exec = async (sql: string, args?: unknown[]): Promise<Answer> => {
58
136
  try {
59
- return f();
137
+ if (args === undefined) return { rows: [], changes: db.run(sql).changes };
138
+ const s = db.query(sql);
139
+ const values = args.length === 1 && args[0] && typeof args[0] === "object" ? args[0] : args;
140
+ if (!s.columnNames.length) return { rows: [], changes: s.run(...([values].flat() as never[])).changes };
141
+ return { rows: s.all(...([values].flat() as never[])) as Answer["rows"], changes: 0 };
60
142
  } catch (e) {
61
143
  if (e instanceof Error && String((e as { code?: string }).code).startsWith("SQLITE_CONSTRAINT"))
62
144
  throw new Refused(e.message.replace(/^CHECK constraint failed: /, ""));
63
145
  throw e;
64
146
  }
65
147
  };
66
- return {
67
- dialect: "sqlite",
68
- run: (sql, args) => said(() => (args === undefined ? db.run(sql) : db.run(sql, args as never))),
69
- query(sql) {
70
- const s = db.query(sql);
71
- return {
72
- get: (...args) => said(() => s.get(...(args as never[]))),
73
- all: (...args) => said(() => s.all(...(args as never[]))),
74
- };
148
+ return engine(
149
+ "sqlite",
150
+ { exec },
151
+ {
152
+ defer: () => exec("PRAGMA defer_foreign_keys = ON"),
153
+ columns: async (table) =>
154
+ ((await exec("SELECT name FROM pragma_table_info(?)", [table])).rows as { name: string }[]).map((c) => c.name),
155
+ temp: "temp",
156
+ listen: async () => {},
157
+ notify: async () => {},
158
+ close: async () => db.close(),
75
159
  },
76
- transaction: (fn) => db.transaction(fn) as never,
77
- defer: () => db.run("PRAGMA defer_foreign_keys = ON"),
78
- columns: (table) =>
79
- (db.query("SELECT name FROM pragma_table_info(?)").all(table) as { name: string }[]).map((c) => c.name),
80
- temp: "temp",
81
- close: () => db.close(),
160
+ );
161
+ }
162
+
163
+ /** Postgres's answers as SQLite gives them: a whole number or any number as a number (Postgres's bigint and numeric
164
+ * come as text), JSON as its text. */
165
+ function typed(row: Record<string, unknown>, types: Map<string, number>) {
166
+ for (const [k, v] of Object.entries(row)) {
167
+ if (v === null || v === undefined) continue;
168
+ const t = types.get(k);
169
+ if (typeof v === "bigint" || ((t === 20 || t === 1700) && typeof v === "string")) row[k] = Number(v);
170
+ else if ((t === 114 || t === 3802) && typeof v !== "string") row[k] = JSON.stringify(v);
171
+ }
172
+ return row;
173
+ }
174
+ /** What Postgres refused, as the store says it: a CHECK named for its words, a unique set's, or a trigger's RAISE. */
175
+ function refusal(e: unknown, sql: string): never {
176
+ // Bun.sql says the SQLSTATE as errno, PGlite as code
177
+ const {
178
+ errno,
179
+ code: state,
180
+ constraint,
181
+ message: words = "",
182
+ } = e as {
183
+ errno?: string;
184
+ code?: string;
185
+ constraint?: string;
186
+ message?: string;
187
+ };
188
+ const code = String(errno ?? (typeof state === "string" && /^[0-9A-Z]{5}$/.test(state) ? state : ""));
189
+ if (code === "P0001") throw new Refused(words);
190
+ if (code.startsWith("23")) throw new Refused(code === "23514" && constraint ? constraint : words);
191
+ if (code) throw new Error(`${words} (${code}): ${sql.slice(0, 200)}`);
192
+ throw e;
193
+ }
194
+
195
+ /** Postgres as the engine asks it, through one connection: Bun.sql's (a server) or PGlite's. */
196
+ export function postgresOf(
197
+ c: {
198
+ query(sql: string, args: unknown[]): Promise<Answer & { types: Map<string, number> }>;
199
+ many(sql: string): Promise<unknown>;
200
+ },
201
+ more: Pick<Engine, "listen" | "notify" | "close">,
202
+ ): Engine {
203
+ const exec = async (sql: string, args?: unknown[]): Promise<Answer> => {
204
+ try {
205
+ // several statements (a trigger's function and the trigger) are sent as they are, together
206
+ if (args === undefined && sql.includes(";")) return (await c.many(sql), { rows: [], changes: 0 });
207
+ const [text, values] = numbered(sql, args ?? []);
208
+ const { rows, changes, types } = await c.query(text, values);
209
+ return { rows: rows.map((r) => typed(r, types)), changes };
210
+ } catch (e) {
211
+ return refusal(e, sql);
212
+ }
82
213
  };
214
+ return engine(
215
+ "postgres",
216
+ { exec },
217
+ {
218
+ defer: () => exec("SET CONSTRAINTS ALL DEFERRED"),
219
+ columns: async (table) =>
220
+ (
221
+ await exec(
222
+ "SELECT column_name AS name FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = ? ORDER BY ordinal_position",
223
+ [table],
224
+ )
225
+ ).rows.map((r) => r.name as string),
226
+ temp: "pg_temp",
227
+ ...more,
228
+ },
229
+ );
83
230
  }
84
231
 
85
232
  /** An empty database, as PGlite's files: each one in memory begun from it, not made anew (a fifth of the time). */
86
233
  let blank: Promise<Blob> | undefined;
87
- /** Postgres: PGlite in a folder (none: in memory), answered at once by its wire protocol. */
234
+ /** Postgres: PGlite in a folder (none: in memory), the tests' Postgres with no server. Its LISTEN is its own. */
88
235
  export async function postgres(dir?: string): Promise<Engine> {
89
236
  const { PGlite } = await import("@electric-sql/pglite");
90
237
  const pg = dir
@@ -96,60 +243,34 @@ export async function postgres(dir?: string): Promise<Engine> {
96
243
  return files;
97
244
  })),
98
245
  });
99
- let depth = 0;
100
- const exec = (sql: string) => {
101
- const out = parse(pg.execProtocolRawSync(message(sql)));
102
- if (out.error) {
103
- const { C: code = "", M: words = "", n: constraint } = out.error;
104
- // a CHECK named for its words, a unique set's, or a trigger's RAISE: refused, in those words
105
- if (code === "P0001") throw new Refused(words);
106
- if (code.startsWith("23")) throw new Refused(code === "23514" && constraint ? constraint : words);
107
- throw new Error(`${words} (${code}): ${sql.slice(0, 200)}`);
108
- }
109
- return out;
110
- };
111
- const rows = (sql: string, args: unknown[]) => {
112
- const { fields, types, rows } = exec(bind(sql, args));
113
- return rows.map((r) => Object.fromEntries(r.map((v, i) => [fields[i]!, typed(types[i]!, v)])));
114
- };
115
- return {
116
- dialect: "postgres",
117
- run: (sql, args) => ({ changes: exec(bind(sql, args === undefined ? [] : [args].flat())).changes }),
118
- query: (sql) => ({
119
- get: (...args) => rows(sql, args)[0] ?? null,
120
- all: (...args) => rows(sql, args),
121
- }),
122
- transaction(fn) {
123
- const run = () => {
124
- const at = depth++;
125
- exec(at ? `SAVEPOINT joined_${at}` : "BEGIN");
126
- try {
127
- const done = fn();
128
- exec(at ? `RELEASE SAVEPOINT joined_${at}` : "COMMIT");
129
- return done;
130
- } catch (e) {
131
- exec(at ? `ROLLBACK TO SAVEPOINT joined_${at}` : "ROLLBACK");
132
- throw e;
133
- } finally {
134
- depth--;
135
- }
136
- };
137
- return Object.assign(run, { immediate: run });
246
+ return postgresOf(
247
+ {
248
+ async query(text, values) {
249
+ const r = await pg.query<Record<string, unknown>>(text, values);
250
+ return {
251
+ rows: r.rows,
252
+ changes: r.affectedRows ?? 0,
253
+ types: new Map(r.fields.map((f) => [f.name, f.dataTypeID])),
254
+ };
255
+ },
256
+ many: (text) => pg.exec(text),
138
257
  },
139
- defer: () => void exec("SET CONSTRAINTS ALL DEFERRED"),
140
- columns: (table) =>
141
- rows(
142
- "SELECT column_name AS name FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = ? ORDER BY ordinal_position",
143
- [table],
144
- ).map((c) => c.name as string),
145
- temp: "pg_temp",
146
- close: () => pg.close(),
147
- };
258
+ {
259
+ listen: async (channel, heard) => void (await pg.listen(channel, heard)),
260
+ notify: (channel, payload) => pg.query("SELECT pg_notify($1, $2)", [channel, payload]),
261
+ close: () => pg.close(),
262
+ },
263
+ );
148
264
  }
149
265
 
150
- /** The store's engine: Postgres (PGlite) in a folder, or SQLite in a file; either in memory (":memory:"). */
151
- export const open = (db: string, kind: Dialect) =>
152
- kind === "postgres" ? postgres(db === ":memory:" ? undefined : db) : Promise.resolve(sqlite(db));
266
+ /** The store's engine: SQLite in a file, or Postgres: the server JOINED_POSTGRES names (postgres://…; ":memory:", a
267
+ * database of its own, made for it and dropped as it closes), else PGlite in a folder; either in memory (":memory:"). */
268
+ export const open = async (db: string, kind: Dialect): Promise<Engine> =>
269
+ kind === "sqlite"
270
+ ? sqlite(db)
271
+ : Bun.env.JOINED_POSTGRES
272
+ ? (await import("./postgres-server.ts")).server(Bun.env.JOINED_POSTGRES, { fresh: db === ":memory:" })
273
+ : postgres(db === ":memory:" ? undefined : db);
153
274
 
154
275
  /** A trigger: before or after an event on a table, its body run where `when` holds; SQLite's a connection's own
155
276
  * (`temp`: made again as it opens). */
@@ -162,13 +283,32 @@ export type Trigger = {
162
283
  body: string;
163
284
  temp?: boolean;
164
285
  };
286
+ /** A function's body as Postgres quotes it: between dollar tags its words don't hold ($joined$, else $joined1$…), so
287
+ * no word of a refusal ends it. */
288
+ const dollared = (body: string) => {
289
+ let tag = "$joined$";
290
+ for (let n = 1; body.includes(tag); n++) tag = `$joined${n}$`;
291
+ return `${tag} ${body} ${tag}`;
292
+ };
165
293
  /** A trigger, as each says it: SQLite's a statement, Postgres's a function, made again in place. */
166
294
  export function triggerSql(dialect: Dialect, t: Trigger) {
167
295
  const q = (n: string) => `"${n.replaceAll('"', '""')}"`;
168
296
  if (dialect === "sqlite")
169
297
  return `CREATE ${t.temp ? "TEMP " : ""}TRIGGER IF NOT EXISTS ${q(t.name)} ${t.at} ${t.event} ON ${t.temp ? "main." : ""}${q(t.table)}${t.when ? ` WHEN ${t.when}` : ""} BEGIN ${t.body} END`;
170
298
  const body = t.when ? `IF ${t.when} THEN ${t.body} END IF;` : t.body;
171
- return `CREATE OR REPLACE FUNCTION ${q(`${t.name}_fn`)}() RETURNS trigger LANGUAGE plpgsql AS $joined$ BEGIN ${body} IF TG_OP = 'DELETE' THEN RETURN OLD; END IF; RETURN NEW; END $joined$; CREATE OR REPLACE TRIGGER ${q(t.name)} ${t.at} ${t.event} ON ${q(t.table)} FOR EACH ROW EXECUTE FUNCTION ${q(`${t.name}_fn`)}()`;
299
+ return `CREATE OR REPLACE FUNCTION ${q(`${t.name}_fn`)}() RETURNS trigger LANGUAGE plpgsql AS ${dollared(`BEGIN ${body} IF TG_OP = 'DELETE' THEN RETURN OLD; END IF; RETURN NEW; END`)}; CREATE OR REPLACE TRIGGER ${q(t.name)} ${t.at} ${t.event} ON ${q(t.table)} FOR EACH ROW EXECUTE FUNCTION ${q(`${t.name}_fn`)}()`;
300
+ }
301
+ /** Postgres's trigger that waits for the end of a write (a constraint trigger, deferred): its body run for each row
302
+ * changed on any of its tables, `item` the row's column naming the item it's of; held at the write's end, as the store
303
+ * settles it (`SET CONSTRAINTS … IMMEDIATE`), or at the commit. Made anew, never replaced: the store drops it first. */
304
+ export function constraintSql(t: { name: string; on: { table: string; event: string }[]; item: string; body: string }) {
305
+ const q = (n: string) => `"${n.replaceAll('"', '""')}"`;
306
+ const fn = q(`${t.name}_fn`);
307
+ // each table's a statement of its own (its function made again with each), as the store makes and drops them
308
+ return t.on.map(
309
+ ({ table, event }, n) =>
310
+ `CREATE OR REPLACE FUNCTION ${fn}() RETURNS trigger LANGUAGE plpgsql AS ${dollared(`DECLARE item INTEGER; BEGIN IF TG_OP = 'DELETE' THEN item := OLD.${t.item}; ELSE item := NEW.${t.item}; END IF; ${t.body} RETURN NULL; END`)}; CREATE CONSTRAINT TRIGGER ${q(`${t.name}_${n}`)} AFTER ${event} ON ${q(table)} DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION ${fn}()`,
311
+ );
172
312
  }
173
313
  /** A trigger's statement refusing a change where `cond` holds, in its words (SQL of a string). */
174
314
  export const refuseSql = (dialect: Dialect, cond: string, words: string) =>
@@ -181,108 +321,51 @@ export function dropTriggerSql(dialect: Dialect, sql: string) {
181
321
  return dialect === "sqlite" ? `DROP TRIGGER IF EXISTS ${name}` : `DROP TRIGGER IF EXISTS ${name} ON ${table}`;
182
322
  }
183
323
 
184
- /** A simple query, as Postgres's wire protocol says it: Q, its length, the SQL, a nul. */
185
- function message(sql: string) {
186
- const body = new TextEncoder().encode(`${sql}\0`);
187
- const m = new Uint8Array(5 + body.length);
188
- m[0] = 81;
189
- new DataView(m.buffer).setInt32(1, 4 + body.length);
190
- m.set(body, 5);
191
- return m;
192
- }
193
-
194
- /** What Postgres answered: the last statement's fields, their types and rows (text, or null), how many it changed, and
195
- * an error's fields (C its code, M its message, n its constraint). */
196
- function parse(b: Uint8Array) {
197
- const v = new DataView(b.buffer, b.byteOffset, b.byteLength),
198
- text = new TextDecoder();
199
- const out = { fields: [] as string[], types: [] as number[], rows: [] as (string | null)[][], changes: 0 } as {
200
- fields: string[];
201
- types: number[];
202
- rows: (string | null)[][];
203
- changes: number;
204
- error?: Record<string, string>;
205
- };
206
- for (let i = 0; i < b.length;) {
207
- const kind = String.fromCharCode(b[i]!),
208
- at = i + 5;
209
- i += 1 + v.getInt32(i + 1);
210
- if (kind === "T") {
211
- ((out.fields = []), (out.types = []), (out.rows = []));
212
- for (let n = v.getInt16(at), p = at + 2; n > 0; n--) {
213
- const z = b.indexOf(0, p);
214
- out.fields.push(text.decode(b.subarray(p, z)));
215
- out.types.push(v.getInt32(z + 7));
216
- p = z + 19;
217
- }
218
- } else if (kind === "D") {
219
- const row: (string | null)[] = [];
220
- for (let n = v.getInt16(at), p = at + 2; n > 0; n--) {
221
- const len = v.getInt32(p);
222
- p += 4;
223
- row.push(len < 0 ? null : text.decode(b.subarray(p, (p += len))));
224
- }
225
- out.rows.push(row);
226
- } else if (kind === "C") out.changes = Number(/ (\d+)$/.exec(text.decode(b.subarray(at, i - 1)))?.[1] ?? 0);
227
- else if (kind === "E") {
228
- const error: Record<string, string> = {};
229
- for (let p = at; b[p] !== 0;) {
230
- const z = b.indexOf(0, p + 1);
231
- error[String.fromCharCode(b[p]!)] = text.decode(b.subarray(p + 1, z));
232
- p = z + 1;
233
- }
234
- out.error ??= error;
235
- }
236
- }
237
- return out;
238
- }
239
-
240
- /** A value as its type says: a whole number or any number as a number, a boolean as one; anything else its text. */
241
- function typed(type: number, v: string | null) {
242
- if (v === null) return null;
243
- if ([20, 21, 23, 700, 701, 1700].includes(type)) return Number(v);
244
- if (type === 16) return v === "t";
245
- return v;
246
- }
247
-
248
- /** SQL with its values written into it as literals: each ? the next of a list, each $name an object's, outside
249
- * quotes, quoted names and dollar-quoted bodies. */
250
- export function bind(sql: string, args: unknown[]): string {
324
+ /** SQL with its values as Postgres's parameters: each ? the next of a list, each $name an object's ($1, $2…, in the
325
+ * order first met), never inside quotes, quoted names or dollar-quoted bodies. A boolean is 1 or 0, as SQLite keeps
326
+ * one. */
327
+ export function numbered(sql: string, args: unknown[]): [string, unknown[]] {
251
328
  const named = args.length === 1 && args[0] && typeof args[0] === "object" && !Array.isArray(args[0]);
252
- const values = named ? (args[0] as Record<string, unknown>) : null;
329
+ const given = named ? (args[0] as Record<string, unknown>) : null;
330
+ const values: unknown[] = [],
331
+ names = new Map<string, number>();
332
+ const value = (v: unknown) => (typeof v === "boolean" ? Number(v) : v === undefined ? null : v);
253
333
  let n = 0,
254
334
  out = "";
255
335
  for (let i = 0; i < sql.length;) {
256
336
  const c = sql[i]!;
257
337
  if (c === "'" || c === '"') {
258
- // a quote doubled is one, inside
338
+ // a quote doubled is one, inside; one never closed, the rest (for the database to refuse)
259
339
  let j = sql.indexOf(c, i + 1);
260
- while (sql[j + 1] === c) j = sql.indexOf(c, j + 2);
340
+ while (j >= 0 && sql[j + 1] === c) j = sql.indexOf(c, j + 2);
341
+ if (j < 0) j = sql.length;
261
342
  out += sql.slice(i, j + 1);
262
- i = j + 1;
343
+ i = j < 0 ? sql.length : j + 1;
263
344
  } else if (c === "$") {
264
345
  const tag = /^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(sql.slice(i));
265
346
  if (tag) {
266
- const end = sql.indexOf(tag[0], i + tag[0].length) + tag[0].length;
347
+ const close = sql.indexOf(tag[0], i + tag[0].length);
348
+ const end = close < 0 ? sql.length : close + tag[0].length;
267
349
  out += sql.slice(i, end);
268
350
  i = end;
269
351
  continue;
270
352
  }
271
- const name = /^\$([A-Za-z_][A-Za-z0-9_]*)/.exec(sql.slice(i));
272
- if (name && values) {
273
- out += literal(values[name[1]!] ?? null);
353
+ const name = /^\$([A-Za-z_][A-Za-z0-9_]*)(\s+IS\s+(NOT\s+)?NULL\b)?/i.exec(sql.slice(i));
354
+ // whether a parameter is none is said as it's sent: Postgres can't tell a parameter's type from that alone
355
+ if (name?.[2] && given) {
356
+ out += String((value(given[name[1]!]) === null) !== !!name[3]).toUpperCase();
357
+ i += name[0].length;
358
+ } else if (name && given) {
359
+ name[0] = `$${name[1]}`;
360
+ if (!names.has(name[1]!)) names.set(name[1]!, values.push(value(given[name[1]!])));
361
+ out += `$${names.get(name[1]!)}`;
274
362
  i += name[0].length;
275
363
  } else ((out += c), i++);
276
- } else if (c === "?" && !values) ((out += literal(args[n++] ?? null)), i++);
277
- else ((out += c), i++);
364
+ } else if (c === "?" && !given) {
365
+ values.push(value(args[n++]));
366
+ out += `$${values.length}`;
367
+ i++;
368
+ } else ((out += c), i++);
278
369
  }
279
- return out;
280
- }
281
-
282
- /** A value as a literal: a number as it is, a boolean as 1 or 0 (as SQLite keeps one), a string quoted. */
283
- function literal(v: unknown): string {
284
- if (v === null || v === undefined) return "NULL";
285
- if (typeof v === "number") return Number.isFinite(v) ? String(v) : "NULL";
286
- if (typeof v === "boolean") return v ? "1" : "0";
287
- return `'${String(v).replaceAll("'", "''")}'`;
370
+ return [out, values];
288
371
  }