@blueshed/joined 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (209) hide show
  1. package/.claude/skills/joined/SKILL.md +9 -1
  2. package/.claude/skills/joined/reference.md +270 -55
  3. package/.claude/skills/joined-door/SKILL.md +57 -0
  4. package/README.md +19 -50
  5. package/docs/design.md +76 -10
  6. package/docs/introduction.md +18 -18
  7. package/docs/light-and-shadow.svg +1 -1
  8. package/examples/README.md +20 -0
  9. package/examples/account/account.json +1 -0
  10. package/examples/account/derive.ts +41 -0
  11. package/examples/account/generated/elements.ts +52 -0
  12. package/examples/account/generated/rows.ts +22 -0
  13. package/examples/account/generated/rules.ts +32 -0
  14. package/examples/account/routes.ts +5 -0
  15. package/examples/app.css +2 -1
  16. package/examples/cafe/books.html +2 -2
  17. package/examples/cafe/cafe.css +9 -16
  18. package/examples/cafe/generated/books.rows.ts +22 -0
  19. package/examples/cafe/generated/books.rules.ts +3 -2
  20. package/examples/cafe/generated/kitchen.rows.ts +27 -0
  21. package/examples/cafe/generated/kitchen.rules.ts +11 -1
  22. package/examples/cafe/generated/menu.rows.ts +22 -0
  23. package/examples/cafe/generated/menu.rules.ts +3 -2
  24. package/examples/cafe/generated/order.rows.ts +27 -0
  25. package/examples/cafe/generated/order.rules.ts +11 -1
  26. package/examples/cafe/generated/staff.rows.ts +22 -0
  27. package/examples/cafe/generated/staff.rules.ts +6 -1
  28. package/examples/cafe/generated/supplies.queries.ts +4 -2
  29. package/examples/cafe/generated/supplies.rows.ts +22 -0
  30. package/examples/cafe/generated/supplies.rules.ts +12 -1
  31. package/examples/cafe/generated/till.queries.ts +2 -0
  32. package/examples/cafe/generated/till.rows.ts +27 -0
  33. package/examples/cafe/generated/till.rules.ts +11 -1
  34. package/examples/cafe/index.html +14 -15
  35. package/examples/cafe/kitchen.ts +1 -1
  36. package/examples/cafe/look.ts +30 -0
  37. package/examples/cafe/menu.html +10 -26
  38. package/examples/cafe/menu.ts +8 -80
  39. package/examples/cafe/order.html +6 -6
  40. package/examples/cafe/order.ts +5 -1
  41. package/examples/cafe/routes.ts +0 -1
  42. package/examples/cafe/stories.jsonl +3 -1
  43. package/examples/cafe/supplies.html +34 -34
  44. package/examples/cafe/supplies.ts +14 -11
  45. package/examples/cafe/till.ts +5 -1
  46. package/examples/chart/arches.ts +148 -0
  47. package/examples/chart/chart.css +6 -0
  48. package/examples/chart/chart.json +87 -0
  49. package/examples/chart/generated/elements.ts +105 -0
  50. package/examples/chart/generated/queries.ts +36 -0
  51. package/examples/chart/generated/rows.ts +27 -0
  52. package/examples/chart/generated/rules.ts +111 -0
  53. package/examples/chart/grid.ts +118 -0
  54. package/examples/chart/index.html +78 -0
  55. package/examples/chart/migrations/001-chart.ts +6 -0
  56. package/examples/chart/migrations/002-create-conditions.ts +6 -0
  57. package/examples/chart/page.ts +20 -0
  58. package/examples/chart/routes.ts +7 -0
  59. package/examples/chart/stories.jsonl +14 -0
  60. package/examples/chart/teeth.ts +57 -0
  61. package/examples/desk/generated/rows.ts +22 -0
  62. package/examples/desk/generated/rules.ts +34 -1
  63. package/examples/desk/index.html +9 -2
  64. package/examples/desk/routes.ts +0 -2
  65. package/examples/desk/stories.jsonl +3 -2
  66. package/examples/desk/thumbs.ts +2 -2
  67. package/examples/hello/generated/elements.ts +2 -2
  68. package/examples/hello/generated/rules.ts +3 -2
  69. package/examples/hello/hello.css +2 -4
  70. package/examples/hello/index.html +10 -3
  71. package/examples/hello/page.ts +4 -4
  72. package/examples/index.html +4 -5
  73. package/examples/notes/generated/elements.ts +112 -0
  74. package/examples/notes/generated/queries.ts +36 -0
  75. package/examples/notes/generated/rows.ts +27 -0
  76. package/examples/notes/generated/rules.ts +133 -0
  77. package/examples/notes/index.html +32 -0
  78. package/examples/notes/look.ts +41 -0
  79. package/examples/notes/migrations/001-notes.ts +7 -0
  80. package/examples/notes/notes.json +78 -0
  81. package/examples/notes/page.ts +21 -0
  82. package/examples/notes/routes.ts +6 -0
  83. package/examples/notes/stories.jsonl +21 -0
  84. package/examples/people/generated/rows.ts +22 -0
  85. package/examples/people/generated/rules.ts +11 -1
  86. package/examples/people/links.ts +2 -1
  87. package/examples/people/routes.ts +1 -3
  88. package/examples/people/stories.jsonl +1 -0
  89. package/examples/people/view.ts +5 -2
  90. package/examples/trip/generated/elements.ts +4 -2
  91. package/examples/trip/generated/queries.ts +12 -1
  92. package/examples/trip/generated/rows.ts +27 -0
  93. package/examples/trip/generated/rules.ts +56 -2
  94. package/examples/trip/index.html +58 -12
  95. package/examples/trip/line.css +186 -0
  96. package/examples/trip/line.ts +51 -40
  97. package/examples/trip/page.ts +65 -71
  98. package/examples/trip/routes.ts +9 -5
  99. package/examples/trip/stays.css +12 -12
  100. package/examples/trip/stays.ts +15 -10
  101. package/examples/trip/stories.jsonl +2 -0
  102. package/examples/trip/told.ts +3 -26
  103. package/examples/trip/trip.css +16 -0
  104. package/examples/trips/generated/rows.ts +22 -0
  105. package/examples/trips/generated/rules.ts +9 -1
  106. package/examples/trips/index.html +10 -10
  107. package/examples/trips/map.ts +3 -14
  108. package/examples/trips/new-trip.ts +14 -16
  109. package/examples/weeks/generated/elements.ts +1 -1
  110. package/examples/weeks/generated/queries.ts +11 -0
  111. package/examples/weeks/generated/rows.ts +22 -0
  112. package/examples/weeks/generated/rules.ts +11 -5
  113. package/examples/weeks/routes.ts +3 -2
  114. package/examples/weeks/stories.jsonl +1 -0
  115. package/examples/welcome.css +7 -5
  116. package/package.json +8 -2
  117. package/src/awesome.ts +103 -0
  118. package/src/board.css +75 -0
  119. package/src/board.ts +173 -0
  120. package/src/cli.ts +15 -2
  121. package/src/compile.ts +569 -35
  122. package/src/definitions.ts +53 -15
  123. package/src/draft.ts +38 -23
  124. package/src/drawer.ts +222 -0
  125. package/src/engine.ts +240 -166
  126. package/src/fields.ts +268 -0
  127. package/src/files.ts +6 -4
  128. package/src/ground.ts +110 -0
  129. package/src/icon-names.ts +15 -2
  130. package/src/kit.ts +51 -0
  131. package/src/link.ts +3 -3
  132. package/src/map.css +133 -0
  133. package/src/map.ts +200 -0
  134. package/src/mcp.ts +176 -38
  135. package/src/members/demo.ts +13 -12
  136. package/src/members/generated/rows.ts +22 -0
  137. package/src/members/generated/rules.ts +3 -2
  138. package/src/members/group.ts +65 -39
  139. package/src/members/keys.ts +93 -77
  140. package/src/members/panel.css +23 -17
  141. package/src/members/panel.ts +49 -35
  142. package/src/migrate.ts +120 -104
  143. package/src/month.css +125 -0
  144. package/src/month.ts +179 -0
  145. package/src/page.css +8 -0
  146. package/src/page.ts +11 -7
  147. package/src/parts.css +462 -170
  148. package/src/parts.ts +209 -26
  149. package/src/plane.css +56 -0
  150. package/src/plane.ts +151 -0
  151. package/src/postgres-server.ts +60 -0
  152. package/src/reading.css +77 -0
  153. package/src/reading.ts +238 -0
  154. package/src/rows.css +308 -0
  155. package/src/rows.ts +780 -0
  156. package/src/search.css +80 -0
  157. package/src/search.ts +130 -0
  158. package/src/server.ts +211 -114
  159. package/src/settings.ts +9 -4
  160. package/src/sheet.ts +114 -0
  161. package/src/skill.ts +40 -0
  162. package/src/slots.css +94 -0
  163. package/src/slots.ts +213 -0
  164. package/src/specs.ts +38 -0
  165. package/src/starter.ts +5 -2
  166. package/src/store.ts +184 -143
  167. package/src/stories.ts +43 -11
  168. package/src/surface.ts +159 -0
  169. package/src/timeline.css +111 -0
  170. package/src/timeline.ts +226 -0
  171. package/src/toast.ts +21 -48
  172. package/src/together.ts +0 -7
  173. package/src/tokens.css +78 -1
  174. package/src/tokens.json +249 -0
  175. package/src/tool.ts +211 -0
  176. package/src/upkeep.ts +18 -20
  177. package/src/views.css +44 -0
  178. package/src/views.ts +94 -0
  179. package/src/week.css +151 -0
  180. package/src/week.ts +250 -0
  181. package/src/write.ts +219 -73
  182. package/starter/CLAUDE.md +3 -3
  183. package/starter/bunfig +4 -0
  184. package/starter/prettierignore +4 -0
  185. package/starter/tests/hello.test.ts +2 -0
  186. package/docs/learning.md +0 -76
  187. package/examples/cafe/trust.ts +0 -20
  188. package/examples/desk/trust.ts +0 -24
  189. package/examples/people/trust.ts +0 -14
  190. package/examples/trip/answer-rows.ts +0 -70
  191. package/examples/trip/bar.ts +0 -89
  192. package/examples/trip/calendar-map.css +0 -711
  193. package/examples/trip/calendar-map.ts +0 -249
  194. package/examples/trip/drags.ts +0 -143
  195. package/examples/trip/drawer.ts +0 -250
  196. package/examples/trip/event-form.ts +0 -200
  197. package/examples/trip/holding.ts +0 -61
  198. package/examples/trip/map.ts +0 -234
  199. package/examples/trip/month.ts +0 -87
  200. package/examples/trip/other-weeks.ts +0 -67
  201. package/examples/trip/peek.ts +0 -71
  202. package/examples/trip/people-chips.ts +0 -74
  203. package/examples/trip/shell.ts +0 -39
  204. package/examples/trip/trust.ts +0 -51
  205. package/examples/trip/week.ts +0 -237
  206. package/examples/trip/writes.ts +0 -91
  207. package/examples/trip/zones.ts +0 -16
  208. package/examples/weeks/derive.ts +0 -23
  209. package/src/scrim.ts +0 -81
package/src/engine.ts CHANGED
@@ -1,35 +1,112 @@
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 });
@@ -54,37 +131,106 @@ export function sqlite(file: string, { readonly = false } = {}): Engine {
54
131
  ? new Date(at + (((d * 24 + h) * 60 + m) * 60 + s) * 1000).toISOString().slice(0, 19)
55
132
  : null;
56
133
  });
57
- const said = <T>(f: () => T): T => {
134
+ const exec = async (sql: string, args?: unknown[]): Promise<Answer> => {
58
135
  try {
59
- return f();
136
+ if (args === undefined) return { rows: [], changes: db.run(sql).changes };
137
+ const s = db.query(sql);
138
+ const values = args.length === 1 && args[0] && typeof args[0] === "object" ? args[0] : args;
139
+ if (!s.columnNames.length) return { rows: [], changes: s.run(...([values].flat() as never[])).changes };
140
+ return { rows: s.all(...([values].flat() as never[])) as Answer["rows"], changes: 0 };
60
141
  } catch (e) {
61
142
  if (e instanceof Error && String((e as { code?: string }).code).startsWith("SQLITE_CONSTRAINT"))
62
143
  throw new Refused(e.message.replace(/^CHECK constraint failed: /, ""));
63
144
  throw e;
64
145
  }
65
146
  };
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
- };
147
+ return engine(
148
+ "sqlite",
149
+ { exec },
150
+ {
151
+ defer: () => exec("PRAGMA defer_foreign_keys = ON"),
152
+ columns: async (table) =>
153
+ ((await exec("SELECT name FROM pragma_table_info(?)", [table])).rows as { name: string }[]).map((c) => c.name),
154
+ temp: "temp",
155
+ listen: async () => {},
156
+ notify: async () => {},
157
+ close: async () => db.close(),
75
158
  },
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(),
159
+ );
160
+ }
161
+
162
+ /** Postgres's answers as SQLite gives them: a whole number or any number as a number (Postgres's bigint and numeric
163
+ * come as text), JSON as its text. */
164
+ function typed(row: Record<string, unknown>, types: Map<string, number>) {
165
+ for (const [k, v] of Object.entries(row)) {
166
+ if (v === null || v === undefined) continue;
167
+ const t = types.get(k);
168
+ if (typeof v === "bigint" || ((t === 20 || t === 1700) && typeof v === "string")) row[k] = Number(v);
169
+ else if ((t === 114 || t === 3802) && typeof v !== "string") row[k] = JSON.stringify(v);
170
+ }
171
+ return row;
172
+ }
173
+ /** What Postgres refused, as the store says it: a CHECK named for its words, a unique set's, or a trigger's RAISE. */
174
+ function refusal(e: unknown, sql: string): never {
175
+ // Bun.sql says the SQLSTATE as errno, PGlite as code
176
+ const {
177
+ errno,
178
+ code: state,
179
+ constraint,
180
+ message: words = "",
181
+ } = e as {
182
+ errno?: string;
183
+ code?: string;
184
+ constraint?: string;
185
+ message?: string;
82
186
  };
187
+ const code = String(errno ?? (typeof state === "string" && /^[0-9A-Z]{5}$/.test(state) ? state : ""));
188
+ if (code === "P0001") throw new Refused(words);
189
+ if (code.startsWith("23")) throw new Refused(code === "23514" && constraint ? constraint : words);
190
+ if (code) throw new Error(`${words} (${code}): ${sql.slice(0, 200)}`);
191
+ throw e;
192
+ }
193
+
194
+ /** Postgres as the engine asks it, through one connection: Bun.sql's (a server) or PGlite's. */
195
+ export function postgresOf(
196
+ c: {
197
+ query(sql: string, args: unknown[]): Promise<Answer & { types: Map<string, number> }>;
198
+ many(sql: string): Promise<unknown>;
199
+ },
200
+ more: Pick<Engine, "listen" | "notify" | "close">,
201
+ ): Engine {
202
+ const exec = async (sql: string, args?: unknown[]): Promise<Answer> => {
203
+ try {
204
+ // several statements (a trigger's function and the trigger) are sent as they are, together
205
+ if (args === undefined && sql.includes(";")) return (await c.many(sql), { rows: [], changes: 0 });
206
+ const [text, values] = numbered(sql, args ?? []);
207
+ const { rows, changes, types } = await c.query(text, values);
208
+ return { rows: rows.map((r) => typed(r, types)), changes };
209
+ } catch (e) {
210
+ return refusal(e, sql);
211
+ }
212
+ };
213
+ return engine(
214
+ "postgres",
215
+ { exec },
216
+ {
217
+ defer: () => exec("SET CONSTRAINTS ALL DEFERRED"),
218
+ columns: async (table) =>
219
+ (
220
+ await exec(
221
+ "SELECT column_name AS name FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = ? ORDER BY ordinal_position",
222
+ [table],
223
+ )
224
+ ).rows.map((r) => r.name as string),
225
+ temp: "pg_temp",
226
+ ...more,
227
+ },
228
+ );
83
229
  }
84
230
 
85
231
  /** An empty database, as PGlite's files: each one in memory begun from it, not made anew (a fifth of the time). */
86
232
  let blank: Promise<Blob> | undefined;
87
- /** Postgres: PGlite in a folder (none: in memory), answered at once by its wire protocol. */
233
+ /** Postgres: PGlite in a folder (none: in memory), the tests' Postgres with no server. Its LISTEN is its own. */
88
234
  export async function postgres(dir?: string): Promise<Engine> {
89
235
  const { PGlite } = await import("@electric-sql/pglite");
90
236
  const pg = dir
@@ -96,60 +242,34 @@ export async function postgres(dir?: string): Promise<Engine> {
96
242
  return files;
97
243
  })),
98
244
  });
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 });
245
+ return postgresOf(
246
+ {
247
+ async query(text, values) {
248
+ const r = await pg.query<Record<string, unknown>>(text, values);
249
+ return {
250
+ rows: r.rows,
251
+ changes: r.affectedRows ?? 0,
252
+ types: new Map(r.fields.map((f) => [f.name, f.dataTypeID])),
253
+ };
254
+ },
255
+ many: (text) => pg.exec(text),
138
256
  },
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
- };
257
+ {
258
+ listen: async (channel, heard) => void (await pg.listen(channel, heard)),
259
+ notify: (channel, payload) => pg.query("SELECT pg_notify($1, $2)", [channel, payload]),
260
+ close: () => pg.close(),
261
+ },
262
+ );
148
263
  }
149
264
 
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));
265
+ /** The store's engine: SQLite in a file, or Postgres: the server JOINED_POSTGRES names (postgres://…; ":memory:", a
266
+ * database of its own, made for it and dropped as it closes), else PGlite in a folder; either in memory (":memory:"). */
267
+ export const open = async (db: string, kind: Dialect): Promise<Engine> =>
268
+ kind === "sqlite"
269
+ ? sqlite(db)
270
+ : Bun.env.JOINED_POSTGRES
271
+ ? (await import("./postgres-server.ts")).server(Bun.env.JOINED_POSTGRES, { fresh: db === ":memory:" })
272
+ : postgres(db === ":memory:" ? undefined : db);
153
273
 
154
274
  /** A trigger: before or after an event on a table, its body run where `when` holds; SQLite's a connection's own
155
275
  * (`temp`: made again as it opens). */
@@ -170,6 +290,18 @@ export function triggerSql(dialect: Dialect, t: Trigger) {
170
290
  const body = t.when ? `IF ${t.when} THEN ${t.body} END IF;` : t.body;
171
291
  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`)}()`;
172
292
  }
293
+ /** Postgres's trigger that waits for the end of a write (a constraint trigger, deferred): its body run for each row
294
+ * 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
295
+ * settles it (`SET CONSTRAINTS … IMMEDIATE`), or at the commit. Made anew, never replaced: the store drops it first. */
296
+ export function constraintSql(t: { name: string; on: { table: string; event: string }[]; item: string; body: string }) {
297
+ const q = (n: string) => `"${n.replaceAll('"', '""')}"`;
298
+ const fn = q(`${t.name}_fn`);
299
+ // each table's a statement of its own (its function made again with each), as the store makes and drops them
300
+ return t.on.map(
301
+ ({ table, event }, n) =>
302
+ `CREATE OR REPLACE FUNCTION ${fn}() RETURNS trigger LANGUAGE plpgsql AS $joined$ 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 $joined$; CREATE CONSTRAINT TRIGGER ${q(`${t.name}_${n}`)} AFTER ${event} ON ${q(table)} DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION ${fn}()`,
303
+ );
304
+ }
173
305
  /** A trigger's statement refusing a change where `cond` holds, in its words (SQL of a string). */
174
306
  export const refuseSql = (dialect: Dialect, cond: string, words: string) =>
175
307
  dialect === "sqlite"
@@ -181,75 +313,15 @@ export function dropTriggerSql(dialect: Dialect, sql: string) {
181
313
  return dialect === "sqlite" ? `DROP TRIGGER IF EXISTS ${name}` : `DROP TRIGGER IF EXISTS ${name} ON ${table}`;
182
314
  }
183
315
 
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 {
316
+ /** SQL with its values as Postgres's parameters: each ? the next of a list, each $name an object's ($1, $2…, in the
317
+ * order first met), never inside quotes, quoted names or dollar-quoted bodies. A boolean is 1 or 0, as SQLite keeps
318
+ * one. */
319
+ export function numbered(sql: string, args: unknown[]): [string, unknown[]] {
251
320
  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;
321
+ const given = named ? (args[0] as Record<string, unknown>) : null;
322
+ const values: unknown[] = [],
323
+ names = new Map<string, number>();
324
+ const value = (v: unknown) => (typeof v === "boolean" ? Number(v) : v === undefined ? null : v);
253
325
  let n = 0,
254
326
  out = "";
255
327
  for (let i = 0; i < sql.length;) {
@@ -259,30 +331,32 @@ export function bind(sql: string, args: unknown[]): string {
259
331
  let j = sql.indexOf(c, i + 1);
260
332
  while (sql[j + 1] === c) j = sql.indexOf(c, j + 2);
261
333
  out += sql.slice(i, j + 1);
262
- i = j + 1;
334
+ i = j < 0 ? sql.length : j + 1;
263
335
  } else if (c === "$") {
264
336
  const tag = /^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(sql.slice(i));
265
337
  if (tag) {
266
- const end = sql.indexOf(tag[0], i + tag[0].length) + tag[0].length;
338
+ const close = sql.indexOf(tag[0], i + tag[0].length);
339
+ const end = close < 0 ? sql.length : close + tag[0].length;
267
340
  out += sql.slice(i, end);
268
341
  i = end;
269
342
  continue;
270
343
  }
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);
344
+ const name = /^\$([A-Za-z_][A-Za-z0-9_]*)(\s+IS\s+(NOT\s+)?NULL\b)?/i.exec(sql.slice(i));
345
+ // whether a parameter is none is said as it's sent: Postgres can't tell a parameter's type from that alone
346
+ if (name?.[2] && given) {
347
+ out += String((value(given[name[1]!]) === null) !== !!name[3]).toUpperCase();
348
+ i += name[0].length;
349
+ } else if (name && given) {
350
+ name[0] = `$${name[1]}`;
351
+ if (!names.has(name[1]!)) names.set(name[1]!, values.push(value(given[name[1]!])));
352
+ out += `$${names.get(name[1]!)}`;
274
353
  i += name[0].length;
275
354
  } else ((out += c), i++);
276
- } else if (c === "?" && !values) ((out += literal(args[n++] ?? null)), i++);
277
- else ((out += c), i++);
355
+ } else if (c === "?" && !given) {
356
+ values.push(value(args[n++]));
357
+ out += `$${values.length}`;
358
+ i++;
359
+ } else ((out += c), i++);
278
360
  }
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("'", "''")}'`;
361
+ return [out, values];
288
362
  }