@pgxsinkit/pgwasm 0.5.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/LICENSE +21 -0
  2. package/LICENSE-APACHE-2.0 +202 -0
  3. package/NOTICE +111 -0
  4. package/README.md +56 -0
  5. package/dist/build/index.d.ts +8 -0
  6. package/dist/build/index.d.ts.map +1 -0
  7. package/dist/build/index.js +21 -0
  8. package/dist/build/index.js.map +9 -0
  9. package/dist/build/seam.d.ts +174 -0
  10. package/dist/build/seam.d.ts.map +1 -0
  11. package/dist/chunk-0w227vw2.js +233 -0
  12. package/dist/chunk-0w227vw2.js.map +11 -0
  13. package/dist/chunk-74gcrk47.js +563 -0
  14. package/dist/chunk-74gcrk47.js.map +14 -0
  15. package/dist/chunk-at1py5s5.js +373 -0
  16. package/dist/chunk-at1py5s5.js.map +12 -0
  17. package/dist/chunk-cpsnmzrf.js +126 -0
  18. package/dist/chunk-cpsnmzrf.js.map +10 -0
  19. package/dist/chunk-d82gg1hx.js +306 -0
  20. package/dist/chunk-d82gg1hx.js.map +10 -0
  21. package/dist/chunk-gjf102c9.js +1005 -0
  22. package/dist/chunk-gjf102c9.js.map +16 -0
  23. package/dist/chunk-kb3rsr7n.js +19 -0
  24. package/dist/chunk-kb3rsr7n.js.map +9 -0
  25. package/dist/chunk-tdvrvgt5.js +83 -0
  26. package/dist/chunk-tdvrvgt5.js.map +11 -0
  27. package/dist/chunk-z0c40tja.js +50 -0
  28. package/dist/chunk-z0c40tja.js.map +10 -0
  29. package/dist/core/data-dir-archive.d.ts +17 -0
  30. package/dist/core/data-dir-archive.d.ts.map +1 -0
  31. package/dist/core/internals.d.ts +59 -0
  32. package/dist/core/internals.d.ts.map +1 -0
  33. package/dist/core/marker.d.ts +35 -0
  34. package/dist/core/marker.d.ts.map +1 -0
  35. package/dist/core/mutex.d.ts +9 -0
  36. package/dist/core/mutex.d.ts.map +1 -0
  37. package/dist/core/names.d.ts +11 -0
  38. package/dist/core/names.d.ts.map +1 -0
  39. package/dist/core/parse.d.ts +11 -0
  40. package/dist/core/parse.d.ts.map +1 -0
  41. package/dist/core/pgwasm.d.ts +53 -0
  42. package/dist/core/pgwasm.d.ts.map +1 -0
  43. package/dist/core/storage.d.ts +14 -0
  44. package/dist/core/storage.d.ts.map +1 -0
  45. package/dist/create.d.ts +10 -0
  46. package/dist/create.d.ts.map +1 -0
  47. package/dist/drizzle/codecs.d.ts +9 -0
  48. package/dist/drizzle/codecs.d.ts.map +1 -0
  49. package/dist/drizzle/driver.d.ts +50 -0
  50. package/dist/drizzle/driver.d.ts.map +1 -0
  51. package/dist/drizzle/index.d.ts +4 -0
  52. package/dist/drizzle/index.d.ts.map +1 -0
  53. package/dist/drizzle/index.js +261 -0
  54. package/dist/drizzle/index.js.map +12 -0
  55. package/dist/drizzle/session.d.ts +39 -0
  56. package/dist/drizzle/session.d.ts.map +1 -0
  57. package/dist/errors.d.ts +115 -0
  58. package/dist/errors.d.ts.map +1 -0
  59. package/dist/fs/base-filesystem.d.ts +118 -0
  60. package/dist/fs/base-filesystem.d.ts.map +1 -0
  61. package/dist/fs/index.d.ts +2 -0
  62. package/dist/fs/index.d.ts.map +1 -0
  63. package/dist/fs/index.js +11 -0
  64. package/dist/fs/index.js.map +9 -0
  65. package/dist/index.d.ts +8 -0
  66. package/dist/index.d.ts.map +1 -0
  67. package/dist/index.js +53 -0
  68. package/dist/index.js.map +9 -0
  69. package/dist/interface.d.ts +165 -0
  70. package/dist/interface.d.ts.map +1 -0
  71. package/dist/live/debounce-mutex.d.ts +6 -0
  72. package/dist/live/debounce-mutex.d.ts.map +1 -0
  73. package/dist/live/format-query.d.ts +8 -0
  74. package/dist/live/format-query.d.ts.map +1 -0
  75. package/dist/live/index.d.ts +9 -0
  76. package/dist/live/index.d.ts.map +1 -0
  77. package/dist/live/index.js +601 -0
  78. package/dist/live/index.js.map +12 -0
  79. package/dist/live/interface.d.ts +86 -0
  80. package/dist/live/interface.d.ts.map +1 -0
  81. package/dist/opfs/broker/client.d.ts +163 -0
  82. package/dist/opfs/broker/client.d.ts.map +1 -0
  83. package/dist/opfs/broker/protocol.d.ts +326 -0
  84. package/dist/opfs/broker/protocol.d.ts.map +1 -0
  85. package/dist/opfs/broker/server.d.ts +84 -0
  86. package/dist/opfs/broker/server.d.ts.map +1 -0
  87. package/dist/opfs/core/checksum.d.ts +3 -0
  88. package/dist/opfs/core/checksum.d.ts.map +1 -0
  89. package/dist/opfs/core/codec.d.ts +73 -0
  90. package/dist/opfs/core/codec.d.ts.map +1 -0
  91. package/dist/opfs/core/errors.d.ts +80 -0
  92. package/dist/opfs/core/errors.d.ts.map +1 -0
  93. package/dist/opfs/core/limits.d.ts +35 -0
  94. package/dist/opfs/core/limits.d.ts.map +1 -0
  95. package/dist/opfs/core/memory-port.d.ts +51 -0
  96. package/dist/opfs/core/memory-port.d.ts.map +1 -0
  97. package/dist/opfs/core/metadata-store.d.ts +19 -0
  98. package/dist/opfs/core/metadata-store.d.ts.map +1 -0
  99. package/dist/opfs/core/mounted-vfs.d.ts +119 -0
  100. package/dist/opfs/core/mounted-vfs.d.ts.map +1 -0
  101. package/dist/opfs/core/path.d.ts +14 -0
  102. package/dist/opfs/core/path.d.ts.map +1 -0
  103. package/dist/opfs/core/port.d.ts +30 -0
  104. package/dist/opfs/core/port.d.ts.map +1 -0
  105. package/dist/opfs/core/repacked-vfs.d.ts +138 -0
  106. package/dist/opfs/core/repacked-vfs.d.ts.map +1 -0
  107. package/dist/opfs/core/state-machine.d.ts +296 -0
  108. package/dist/opfs/core/state-machine.d.ts.map +1 -0
  109. package/dist/opfs/create.d.ts +50 -0
  110. package/dist/opfs/create.d.ts.map +1 -0
  111. package/dist/opfs/file-port.d.ts +14 -0
  112. package/dist/opfs/file-port.d.ts.map +1 -0
  113. package/dist/opfs/index.d.ts +37 -0
  114. package/dist/opfs/index.d.ts.map +1 -0
  115. package/dist/opfs/index.js +6671 -0
  116. package/dist/opfs/index.js.map +28 -0
  117. package/dist/opfs/opfs-port.d.ts +34 -0
  118. package/dist/opfs/opfs-port.d.ts.map +1 -0
  119. package/dist/opfs/opfs-repacked-fs.d.ts +55 -0
  120. package/dist/opfs/opfs-repacked-fs.d.ts.map +1 -0
  121. package/dist/opfs/wasi/preview1.d.ts +228 -0
  122. package/dist/opfs/wasi/preview1.d.ts.map +1 -0
  123. package/dist/protocol/index.d.ts +15 -0
  124. package/dist/protocol/index.d.ts.map +1 -0
  125. package/dist/protocol/index.js +23 -0
  126. package/dist/protocol/index.js.map +10 -0
  127. package/dist/protocol/wire/buffer-reader.d.ts +13 -0
  128. package/dist/protocol/wire/buffer-reader.d.ts.map +1 -0
  129. package/dist/protocol/wire/buffer-writer.d.ts +12 -0
  130. package/dist/protocol/wire/buffer-writer.d.ts.map +1 -0
  131. package/dist/protocol/wire/index.d.ts +5 -0
  132. package/dist/protocol/wire/index.d.ts.map +1 -0
  133. package/dist/protocol/wire/messages.d.ts +194 -0
  134. package/dist/protocol/wire/messages.d.ts.map +1 -0
  135. package/dist/protocol/wire/parser.d.ts +12 -0
  136. package/dist/protocol/wire/parser.d.ts.map +1 -0
  137. package/dist/protocol/wire/serializer.d.ts +61 -0
  138. package/dist/protocol/wire/serializer.d.ts.map +1 -0
  139. package/dist/protocol/wire/string-utils.d.ts +6 -0
  140. package/dist/protocol/wire/string-utils.d.ts.map +1 -0
  141. package/dist/protocol/wire/types.d.ts +7 -0
  142. package/dist/protocol/wire/types.d.ts.map +1 -0
  143. package/dist/tar/gzip.d.ts +7 -0
  144. package/dist/tar/gzip.d.ts.map +1 -0
  145. package/dist/tar/tar.d.ts +39 -0
  146. package/dist/tar/tar.d.ts.map +1 -0
  147. package/dist/templating.d.ts +42 -0
  148. package/dist/templating.d.ts.map +1 -0
  149. package/dist/types.d.ts +76 -0
  150. package/dist/types.d.ts.map +1 -0
  151. package/package.json +69 -0
  152. package/skills/opfs/SKILL.md +138 -0
  153. package/src/build/index.ts +23 -0
  154. package/src/build/seam.ts +179 -0
  155. package/src/core/data-dir-archive.ts +68 -0
  156. package/src/core/internals.ts +87 -0
  157. package/src/core/marker.ts +94 -0
  158. package/src/core/mutex.ts +16 -0
  159. package/src/core/names.ts +26 -0
  160. package/src/core/parse.ts +79 -0
  161. package/src/core/pgwasm.ts +876 -0
  162. package/src/core/storage.ts +70 -0
  163. package/src/create.ts +134 -0
  164. package/src/drizzle/codecs.ts +114 -0
  165. package/src/drizzle/driver.ts +141 -0
  166. package/src/drizzle/index.ts +15 -0
  167. package/src/drizzle/session.ts +133 -0
  168. package/src/errors.ts +201 -0
  169. package/src/fs/base-filesystem.ts +149 -0
  170. package/src/fs/index.ts +7 -0
  171. package/src/index.ts +44 -0
  172. package/src/interface.ts +186 -0
  173. package/src/live/debounce-mutex.ts +45 -0
  174. package/src/live/format-query.ts +47 -0
  175. package/src/live/index.ts +707 -0
  176. package/src/live/interface.ts +109 -0
  177. package/src/opfs/broker/client.ts +482 -0
  178. package/src/opfs/broker/protocol.ts +624 -0
  179. package/src/opfs/broker/server.ts +522 -0
  180. package/src/opfs/core/checksum.ts +85 -0
  181. package/src/opfs/core/codec.ts +1051 -0
  182. package/src/opfs/core/errors.ts +134 -0
  183. package/src/opfs/core/limits.ts +68 -0
  184. package/src/opfs/core/memory-port.ts +459 -0
  185. package/src/opfs/core/metadata-store.ts +512 -0
  186. package/src/opfs/core/mounted-vfs.ts +407 -0
  187. package/src/opfs/core/path.ts +82 -0
  188. package/src/opfs/core/port.ts +114 -0
  189. package/src/opfs/core/repacked-vfs.ts +1464 -0
  190. package/src/opfs/core/state-machine.ts +1699 -0
  191. package/src/opfs/create.ts +125 -0
  192. package/src/opfs/file-port.ts +183 -0
  193. package/src/opfs/index.ts +113 -0
  194. package/src/opfs/opfs-port.ts +90 -0
  195. package/src/opfs/opfs-repacked-fs.ts +210 -0
  196. package/src/opfs/wasi/preview1.ts +1016 -0
  197. package/src/protocol/index.ts +24 -0
  198. package/src/protocol/wire/buffer-reader.ts +60 -0
  199. package/src/protocol/wire/buffer-writer.ts +93 -0
  200. package/src/protocol/wire/index.ts +15 -0
  201. package/src/protocol/wire/messages.ts +332 -0
  202. package/src/protocol/wire/parser.ts +373 -0
  203. package/src/protocol/wire/serializer.ts +233 -0
  204. package/src/protocol/wire/string-utils.ts +18 -0
  205. package/src/protocol/wire/types.ts +12 -0
  206. package/src/tar/gzip.ts +36 -0
  207. package/src/tar/tar.ts +253 -0
  208. package/src/templating.ts +103 -0
  209. package/src/types.ts +283 -0
@@ -0,0 +1,707 @@
1
+ // Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL
2
+ // — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.
3
+
4
+ import { randomId } from "../core/names";
5
+ import type { Extension, Pgwasm, Results, Row, Transaction } from "../interface";
6
+ import { debounceMutex } from "./debounce-mutex";
7
+ import { formatQuery } from "./format-query";
8
+ import type {
9
+ Change,
10
+ LiveChanges,
11
+ LiveChangesOptions,
12
+ LiveIncrementalQueryOptions,
13
+ LiveNamespace,
14
+ LiveQuery,
15
+ LiveQueryOptions,
16
+ LiveQueryResults,
17
+ } from "./interface";
18
+
19
+ export type {
20
+ Change,
21
+ ChangeDelete,
22
+ ChangeInsert,
23
+ ChangeReset,
24
+ ChangeUpdate,
25
+ LiveChanges,
26
+ LiveChangesOptions,
27
+ LiveIncrementalQueryOptions,
28
+ LiveNamespace,
29
+ LiveQuery,
30
+ LiveQueryOptions,
31
+ LiveQueryResults,
32
+ PgwasmWithLive,
33
+ } from "./interface";
34
+
35
+ const MAX_RETRIES = 5;
36
+
37
+ interface ViewTable {
38
+ table_name: string;
39
+ schema_name: string;
40
+ table_oid: number;
41
+ schema_oid: number;
42
+ }
43
+
44
+ type Unlisten = (tx?: Transaction) => Promise<void>;
45
+
46
+ function runResultCallbacks<T>(callbacks: readonly ((results: Results<T>) => void)[], results: Results<T>): void {
47
+ for (const callback of callbacks) callback(results);
48
+ }
49
+
50
+ function runChangeCallbacks<T>(callbacks: readonly ((changes: Change<T>[]) => void)[], changes: Change<T>[]): void {
51
+ for (const callback of callbacks) callback(changes);
52
+ }
53
+
54
+ /**
55
+ * Every table a view reads, following views it reads recursively.
56
+ */
57
+ async function getTablesForView(tx: Transaction, viewName: string): Promise<ViewTable[]> {
58
+ const result = await tx.query<ViewTable>(
59
+ `
60
+ WITH RECURSIVE view_dependencies AS (
61
+ -- Base case: the view's own dependencies
62
+ SELECT DISTINCT
63
+ cl.relname AS dependent_name,
64
+ n.nspname AS schema_name,
65
+ cl.oid AS dependent_oid,
66
+ n.oid AS schema_oid,
67
+ cl.relkind = 'v' AS is_view
68
+ FROM pg_rewrite r
69
+ JOIN pg_depend d ON r.oid = d.objid
70
+ JOIN pg_class cl ON d.refobjid = cl.oid
71
+ JOIN pg_namespace n ON cl.relnamespace = n.oid
72
+ WHERE
73
+ r.ev_class = (
74
+ SELECT oid FROM pg_class WHERE relname = $1 AND relkind = 'v'
75
+ )
76
+ AND d.deptype = 'n'
77
+
78
+ UNION ALL
79
+
80
+ -- Recursive case: the dependencies of the views found so far
81
+ SELECT DISTINCT
82
+ cl.relname AS dependent_name,
83
+ n.nspname AS schema_name,
84
+ cl.oid AS dependent_oid,
85
+ n.oid AS schema_oid,
86
+ cl.relkind = 'v' AS is_view
87
+ FROM view_dependencies vd
88
+ JOIN pg_rewrite r ON vd.dependent_name = (
89
+ SELECT relname FROM pg_class WHERE oid = r.ev_class AND relkind = 'v'
90
+ )
91
+ JOIN pg_depend d ON r.oid = d.objid
92
+ JOIN pg_class cl ON d.refobjid = cl.oid
93
+ JOIN pg_namespace n ON cl.relnamespace = n.oid
94
+ WHERE d.deptype = 'n'
95
+ )
96
+ SELECT DISTINCT
97
+ dependent_name AS table_name,
98
+ schema_name,
99
+ dependent_oid AS table_oid,
100
+ schema_oid
101
+ FROM view_dependencies
102
+ WHERE NOT is_view; -- only tables, not the views in between
103
+ `,
104
+ [viewName],
105
+ );
106
+ return result.rows.map((row) => ({
107
+ table_name: row.table_name,
108
+ schema_name: row.schema_name,
109
+ table_oid: row.table_oid,
110
+ schema_oid: row.schema_oid,
111
+ }));
112
+ }
113
+
114
+ /** A statement-level NOTIFY trigger on each table, created once per table per database. */
115
+ async function addNotifyTriggersToTables(
116
+ tx: Transaction,
117
+ tables: readonly ViewTable[],
118
+ tableNotifyTriggersAdded: Set<string>,
119
+ ): Promise<void> {
120
+ const triggers = tables
121
+ .filter((table) => !tableNotifyTriggersAdded.has(`${table.schema_oid}_${table.table_oid}`))
122
+ .map(
123
+ (table) => `
124
+ CREATE OR REPLACE FUNCTION "_notify_${table.schema_oid}_${table.table_oid}"() RETURNS TRIGGER AS $$
125
+ BEGIN
126
+ PERFORM pg_notify('table_change__${table.schema_oid}__${table.table_oid}', '');
127
+ RETURN NULL;
128
+ END;
129
+ $$ LANGUAGE plpgsql;
130
+ CREATE OR REPLACE TRIGGER "_notify_trigger_${table.schema_oid}_${table.table_oid}"
131
+ AFTER INSERT OR UPDATE OR DELETE ON "${table.schema_name}"."${table.table_name}"
132
+ FOR EACH STATEMENT EXECUTE FUNCTION "_notify_${table.schema_oid}_${table.table_oid}"();
133
+ `,
134
+ )
135
+ .join("\n");
136
+ if (triggers.trim() !== "") {
137
+ await tx.exec(triggers);
138
+ }
139
+ for (const table of tables) tableNotifyTriggersAdded.add(`${table.schema_oid}_${table.table_oid}`);
140
+ }
141
+
142
+ function listenToTables(tx: Transaction, tables: readonly ViewTable[], onChange: () => void): Promise<Unlisten[]> {
143
+ return Promise.all(
144
+ tables.map((table) =>
145
+ tx.listen(`"table_change__${table.schema_oid}__${table.table_oid}"`, () => {
146
+ onChange();
147
+ }),
148
+ ),
149
+ );
150
+ }
151
+
152
+ function unsubscribeOnAbort(signal: AbortSignal | undefined, unsubscribe: () => Promise<void>): Promise<void> | void {
153
+ if (signal?.aborted) return unsubscribe();
154
+ signal?.addEventListener(
155
+ "abort",
156
+ () => {
157
+ void unsubscribe();
158
+ },
159
+ { once: true },
160
+ );
161
+ }
162
+
163
+ function createNamespace(pg: Pgwasm): LiveNamespace {
164
+ // The notify triggers are only ever added, never removed: remember which tables have one.
165
+ const tableNotifyTriggersAdded = new Set<string>();
166
+
167
+ async function query<T>(
168
+ queryOrOptions: string | LiveQueryOptions<T>,
169
+ paramsArg?: readonly unknown[] | null,
170
+ callbackArg?: (results: Results<T>) => void,
171
+ ): Promise<LiveQuery<T>> {
172
+ let signal: AbortSignal | undefined;
173
+ let offset: number | undefined;
174
+ let limit: number | undefined;
175
+ let query: string;
176
+ let params: readonly unknown[] | null | undefined = paramsArg;
177
+ let callback = callbackArg;
178
+ if (typeof queryOrOptions === "string") {
179
+ query = queryOrOptions;
180
+ } else {
181
+ signal = queryOrOptions.signal;
182
+ params = queryOrOptions.params;
183
+ callback = queryOrOptions.callback;
184
+ offset = queryOrOptions.offset;
185
+ limit = queryOrOptions.limit;
186
+ query = queryOrOptions.query;
187
+ }
188
+
189
+ if ((offset === undefined) !== (limit === undefined)) {
190
+ throw new Error("offset and limit must be provided together");
191
+ }
192
+ const isWindowed = offset !== undefined && limit !== undefined;
193
+ if (
194
+ isWindowed &&
195
+ (typeof offset !== "number" || Number.isNaN(offset) || typeof limit !== "number" || Number.isNaN(limit))
196
+ ) {
197
+ throw new Error("offset and limit must be numbers");
198
+ }
199
+
200
+ let callbacks: ((results: Results<T>) => void)[] = callback ? [callback] : [];
201
+ const id = randomId();
202
+ let dead = false;
203
+ let totalCount: number | undefined;
204
+ let results: LiveQueryResults<T> = { rows: [], fields: [] };
205
+ let unsubList: Unlisten[] = [];
206
+
207
+ // `refresh` is created after `init()` completes, but init registers the listeners that call it: a
208
+ // notification during init is recorded and replayed once `refresh` exists.
209
+ let refreshReady = false;
210
+ let refreshPending = false;
211
+ const notifyRefresh = () => {
212
+ if (!refreshReady) {
213
+ refreshPending = true;
214
+ return;
215
+ }
216
+ void refresh();
217
+ };
218
+
219
+ const init = async () => {
220
+ await pg.transaction(async (tx) => {
221
+ const formattedQuery = params && params.length > 0 ? await formatQuery(pg, query, params, tx) : query;
222
+ await tx.exec(`CREATE OR REPLACE TEMP VIEW live_query_${id}_view AS ${formattedQuery}`);
223
+
224
+ const tables = await getTablesForView(tx, `live_query_${id}_view`);
225
+ await addNotifyTriggersToTables(tx, tables, tableNotifyTriggersAdded);
226
+
227
+ if (isWindowed) {
228
+ await tx.exec(`
229
+ PREPARE live_query_${id}_get(int, int) AS
230
+ SELECT * FROM live_query_${id}_view
231
+ LIMIT $1 OFFSET $2;
232
+ `);
233
+ await tx.exec(`
234
+ PREPARE live_query_${id}_get_total_count AS
235
+ SELECT COUNT(*) FROM live_query_${id}_view;
236
+ `);
237
+ totalCount = (await tx.query<{ count: number }>(`EXECUTE live_query_${id}_get_total_count;`)).rows[0]?.count;
238
+ results = {
239
+ ...(await tx.query<T>(`EXECUTE live_query_${id}_get(${limit}, ${offset});`)),
240
+ ...(offset === undefined ? {} : { offset }),
241
+ ...(limit === undefined ? {} : { limit }),
242
+ ...(totalCount === undefined ? {} : { totalCount }),
243
+ };
244
+ } else {
245
+ await tx.exec(`
246
+ PREPARE live_query_${id}_get AS
247
+ SELECT * FROM live_query_${id}_view;
248
+ `);
249
+ results = await tx.query<T>(`EXECUTE live_query_${id}_get;`);
250
+ }
251
+ unsubList = await listenToTables(tx, tables, notifyRefresh);
252
+ });
253
+ };
254
+ await init();
255
+
256
+ const refresh = debounceMutex(
257
+ async ({ offset: newOffset, limit: newLimit }: { offset?: number; limit?: number } = {}) => {
258
+ // A windowed query can be refreshed onto another window.
259
+ if (!isWindowed && (newOffset !== undefined || newLimit !== undefined)) {
260
+ throw new Error("offset and limit cannot be provided for non-windowed queries");
261
+ }
262
+ if (
263
+ (newOffset && (typeof newOffset !== "number" || Number.isNaN(newOffset))) ||
264
+ (newLimit && (typeof newLimit !== "number" || Number.isNaN(newLimit)))
265
+ ) {
266
+ throw new Error("offset and limit must be numbers");
267
+ }
268
+ offset = newOffset ?? offset;
269
+ limit = newLimit ?? limit;
270
+
271
+ const run = async (count = 0): Promise<void> => {
272
+ if (callbacks.length === 0) return;
273
+ try {
274
+ if (isWindowed) {
275
+ // The rows first, with the old total count: count(*) is slow, and the rows on screen should
276
+ // update as quickly as possible. The count follows below.
277
+ results = {
278
+ ...(await pg.query<T>(`EXECUTE live_query_${id}_get(${limit}, ${offset});`)),
279
+ ...(offset === undefined ? {} : { offset }),
280
+ ...(limit === undefined ? {} : { limit }),
281
+ ...(totalCount === undefined ? {} : { totalCount }),
282
+ };
283
+ } else {
284
+ results = await pg.query<T>(`EXECUTE live_query_${id}_get;`);
285
+ }
286
+ } catch (error) {
287
+ const msg = error instanceof Error ? error.message : String(error);
288
+ if (msg.startsWith(`prepared statement "live_query_${id}`) && msg.endsWith("does not exist")) {
289
+ // The prepared statement is gone (the session was reset): set up again and retry.
290
+ if (count > MAX_RETRIES) throw error;
291
+ await init();
292
+ await run(count + 1);
293
+ return;
294
+ }
295
+ throw error;
296
+ }
297
+
298
+ runResultCallbacks(callbacks, results);
299
+
300
+ if (isWindowed) {
301
+ const newTotalCount = (await pg.query<{ count: number }>(`EXECUTE live_query_${id}_get_total_count;`))
302
+ .rows[0]?.count;
303
+ if (newTotalCount !== totalCount) {
304
+ totalCount = newTotalCount;
305
+ void refresh();
306
+ }
307
+ }
308
+ };
309
+ await run();
310
+ },
311
+ );
312
+
313
+ refreshReady = true;
314
+ if (refreshPending) {
315
+ refreshPending = false;
316
+ void refresh();
317
+ }
318
+
319
+ const subscribe = (subscriber: (results: Results<T>) => void) => {
320
+ if (dead) {
321
+ throw new Error("Live query is no longer active and cannot be subscribed to");
322
+ }
323
+ callbacks.push(subscriber);
324
+ };
325
+
326
+ // Unsubscribe one callback, or all when none is given; with none left, drop the view and listeners.
327
+ const unsubscribe = async (subscriber?: (results: Results<T>) => void) => {
328
+ callbacks = subscriber ? callbacks.filter((cb) => cb !== subscriber) : [];
329
+ if (callbacks.length === 0 && !dead) {
330
+ dead = true;
331
+ await pg.transaction(async (tx) => {
332
+ await Promise.all(unsubList.map((unsub) => unsub(tx)));
333
+ await tx.exec(`
334
+ DROP VIEW IF EXISTS live_query_${id}_view;
335
+ DEALLOCATE live_query_${id}_get;
336
+ `);
337
+ });
338
+ }
339
+ };
340
+
341
+ await unsubscribeOnAbort(signal, unsubscribe);
342
+
343
+ runResultCallbacks(callbacks, results);
344
+
345
+ return {
346
+ initialResults: results,
347
+ subscribe,
348
+ unsubscribe,
349
+ refresh: async (options) => {
350
+ await refresh(options);
351
+ },
352
+ };
353
+ }
354
+
355
+ async function changes<T>(
356
+ queryOrOptions: string | LiveChangesOptions<T>,
357
+ paramsArg?: readonly unknown[] | null,
358
+ keyArg?: string,
359
+ callbackArg?: (changes: Change<T>[]) => void,
360
+ ): Promise<LiveChanges<T>> {
361
+ let signal: AbortSignal | undefined;
362
+ let query: string;
363
+ let params: readonly unknown[] | null | undefined = paramsArg;
364
+ let key = keyArg;
365
+ let callback = callbackArg;
366
+ if (typeof queryOrOptions === "string") {
367
+ query = queryOrOptions;
368
+ } else {
369
+ signal = queryOrOptions.signal;
370
+ params = queryOrOptions.params;
371
+ key = queryOrOptions.key;
372
+ callback = queryOrOptions.callback;
373
+ query = queryOrOptions.query;
374
+ }
375
+ if (!key) {
376
+ throw new Error("key is required for changes queries");
377
+ }
378
+ const keyColumn = key;
379
+ let callbacks: ((changes: Change<T>[]) => void)[] = callback ? [callback] : [];
380
+ const id = randomId();
381
+ let dead = false;
382
+ let stateSwitch: 1 | 2 = 1;
383
+ let changesResult: Results<Change<T>> | undefined;
384
+ let unsubList: Unlisten[] = [];
385
+
386
+ let refreshReady = false;
387
+ let refreshPending = false;
388
+ const notifyRefresh = () => {
389
+ if (!refreshReady) {
390
+ refreshPending = true;
391
+ return;
392
+ }
393
+ void refresh();
394
+ };
395
+
396
+ const init = async () => {
397
+ await pg.transaction(async (tx) => {
398
+ const formattedQuery = await formatQuery(pg, query, params, tx);
399
+ await tx.query(`CREATE OR REPLACE TEMP VIEW live_query_${id}_view AS ${formattedQuery}`);
400
+
401
+ const tables = await getTablesForView(tx, `live_query_${id}_view`);
402
+ await addNotifyTriggersToTables(tx, tables, tableNotifyTriggersAdded);
403
+
404
+ const columns: { column_name: string; data_type: string; udt_name?: string }[] = [
405
+ ...(
406
+ await tx.query<{ column_name: string; data_type: string; udt_name: string }>(`
407
+ SELECT column_name, data_type, udt_name
408
+ FROM information_schema.columns
409
+ WHERE table_name = 'live_query_${id}_view'
410
+ `)
411
+ ).rows,
412
+ { column_name: "__after__", data_type: "integer" },
413
+ ];
414
+
415
+ // Two state tables, alternately holding the previous and the current result.
416
+ await tx.exec(`
417
+ CREATE TEMP TABLE live_query_${id}_state1 (LIKE live_query_${id}_view INCLUDING ALL);
418
+ CREATE TEMP TABLE live_query_${id}_state2 (LIKE live_query_${id}_view INCLUDING ALL);
419
+ `);
420
+
421
+ const nullOf = (column: { data_type: string; udt_name?: string }) =>
422
+ `NULL${column.data_type === "USER-DEFINED" ? `::${column.udt_name ?? ""}` : ""}`;
423
+
424
+ // A diff statement per direction: INSERTs carry every column, DELETEs only the key, UPDATEs only
425
+ // the changed columns (and their names).
426
+ for (const curr of [1, 2] as const) {
427
+ const prev = curr === 1 ? 2 : 1;
428
+ await tx.exec(`
429
+ PREPARE live_query_${id}_diff${curr} AS
430
+ WITH
431
+ prev AS (SELECT LAG("${keyColumn}") OVER () as __after__, * FROM live_query_${id}_state${prev}),
432
+ curr AS (SELECT LAG("${keyColumn}") OVER () as __after__, * FROM live_query_${id}_state${curr}),
433
+ data_diff AS (
434
+ SELECT
435
+ 'INSERT' AS __op__,
436
+ ${columns.map(({ column_name }) => `curr."${column_name}" AS "${column_name}"`).join(",\n")},
437
+ ARRAY[]::text[] AS __changed_columns__
438
+ FROM curr
439
+ LEFT JOIN prev ON curr."${keyColumn}" = prev."${keyColumn}"
440
+ WHERE prev."${keyColumn}" IS NULL
441
+ UNION ALL
442
+ SELECT
443
+ 'DELETE' AS __op__,
444
+ ${columns
445
+ .map((column) =>
446
+ column.column_name === keyColumn
447
+ ? `prev."${column.column_name}" AS "${column.column_name}"`
448
+ : `${nullOf(column)} AS "${column.column_name}"`,
449
+ )
450
+ .join(",\n")},
451
+ ARRAY[]::text[] AS __changed_columns__
452
+ FROM prev
453
+ LEFT JOIN curr ON prev."${keyColumn}" = curr."${keyColumn}"
454
+ WHERE curr."${keyColumn}" IS NULL
455
+ UNION ALL
456
+ SELECT
457
+ 'UPDATE' AS __op__,
458
+ ${columns
459
+ .map((column) =>
460
+ column.column_name === keyColumn
461
+ ? `curr."${column.column_name}" AS "${column.column_name}"`
462
+ : `CASE
463
+ WHEN curr."${column.column_name}" IS DISTINCT FROM prev."${column.column_name}"
464
+ THEN curr."${column.column_name}"
465
+ ELSE ${nullOf(column)}
466
+ END AS "${column.column_name}"`,
467
+ )
468
+ .join(",\n")},
469
+ ARRAY(SELECT unnest FROM unnest(ARRAY[${columns
470
+ .filter(({ column_name }) => column_name !== keyColumn)
471
+ .map(
472
+ ({ column_name }) =>
473
+ `CASE
474
+ WHEN curr."${column_name}" IS DISTINCT FROM prev."${column_name}"
475
+ THEN '${column_name}'
476
+ ELSE NULL
477
+ END`,
478
+ )
479
+ .join(", ")}]) WHERE unnest IS NOT NULL) AS __changed_columns__
480
+ FROM curr
481
+ INNER JOIN prev ON curr."${keyColumn}" = prev."${keyColumn}"
482
+ WHERE NOT (curr IS NOT DISTINCT FROM prev)
483
+ )
484
+ SELECT * FROM data_diff;
485
+ `);
486
+ }
487
+
488
+ unsubList = await listenToTables(tx, tables, notifyRefresh);
489
+ });
490
+ };
491
+
492
+ await init();
493
+
494
+ const refresh = debounceMutex(async () => {
495
+ if (callbacks.length === 0 && changesResult) return;
496
+ let reset = false;
497
+ for (let i = 0; i < 5; i++) {
498
+ try {
499
+ await pg.transaction(async (tx) => {
500
+ await tx.exec(`
501
+ INSERT INTO live_query_${id}_state${stateSwitch}
502
+ SELECT * FROM live_query_${id}_view;
503
+ `);
504
+ changesResult = await tx.query<Change<T>>(`EXECUTE live_query_${id}_diff${stateSwitch};`);
505
+ stateSwitch = stateSwitch === 1 ? 2 : 1;
506
+ await tx.exec(`
507
+ TRUNCATE live_query_${id}_state${stateSwitch};
508
+ `);
509
+ });
510
+ break;
511
+ } catch (error) {
512
+ const msg = error instanceof Error ? error.message : String(error);
513
+ if (msg === `relation "live_query_${id}_state${stateSwitch}" does not exist`) {
514
+ // The state table is gone (the session was reset): set up again and retry.
515
+ reset = true;
516
+ await init();
517
+ continue;
518
+ }
519
+ throw error;
520
+ }
521
+ }
522
+ const resetChange = { __op__: "RESET" } as Change<T>;
523
+ runChangeCallbacks(callbacks, [...(reset ? [resetChange] : []), ...(changesResult?.rows ?? [])]);
524
+ });
525
+
526
+ refreshReady = true;
527
+
528
+ const subscribe = (subscriber: (changes: Change<T>[]) => void) => {
529
+ if (dead) {
530
+ throw new Error("Live query is no longer active and cannot be subscribed to");
531
+ }
532
+ callbacks.push(subscriber);
533
+ };
534
+
535
+ const unsubscribe = async (subscriber?: (changes: Change<T>[]) => void) => {
536
+ callbacks = subscriber ? callbacks.filter((cb) => cb !== subscriber) : [];
537
+ if (callbacks.length === 0 && !dead) {
538
+ dead = true;
539
+ await pg.transaction(async (tx) => {
540
+ await Promise.all(unsubList.map((unsub) => unsub(tx)));
541
+ await tx.exec(`
542
+ DROP VIEW IF EXISTS live_query_${id}_view;
543
+ DROP TABLE IF EXISTS live_query_${id}_state1;
544
+ DROP TABLE IF EXISTS live_query_${id}_state2;
545
+ DEALLOCATE live_query_${id}_diff1;
546
+ DEALLOCATE live_query_${id}_diff2;
547
+ `);
548
+ });
549
+ }
550
+ };
551
+
552
+ await unsubscribeOnAbort(signal, unsubscribe);
553
+
554
+ // The initial changes.
555
+ await refresh();
556
+
557
+ if (refreshPending) {
558
+ // A notification arrived during init. It is replayed after the initial refresh, which would
559
+ // otherwise consume the initial changes.
560
+ refreshPending = false;
561
+ void refresh();
562
+ }
563
+
564
+ const fields = (changesResult?.fields ?? []).filter(
565
+ (field) => !["__after__", "__op__", "__changed_columns__"].includes(field.name),
566
+ );
567
+
568
+ return {
569
+ fields,
570
+ initialChanges: changesResult?.rows ?? [],
571
+ subscribe,
572
+ unsubscribe,
573
+ refresh: async () => {
574
+ await refresh();
575
+ },
576
+ };
577
+ }
578
+
579
+ async function incrementalQuery<T>(
580
+ queryOrOptions: string | LiveIncrementalQueryOptions<T>,
581
+ paramsArg?: readonly unknown[] | null,
582
+ keyArg?: string,
583
+ callbackArg?: (results: Results<T>) => void,
584
+ ): Promise<LiveQuery<T>> {
585
+ let signal: AbortSignal | undefined;
586
+ let query: string;
587
+ let params: readonly unknown[] | null | undefined = paramsArg;
588
+ let key = keyArg;
589
+ let callback = callbackArg;
590
+ if (typeof queryOrOptions === "string") {
591
+ query = queryOrOptions;
592
+ } else {
593
+ signal = queryOrOptions.signal;
594
+ params = queryOrOptions.params;
595
+ key = queryOrOptions.key;
596
+ callback = queryOrOptions.callback;
597
+ query = queryOrOptions.query;
598
+ }
599
+ if (!key) {
600
+ throw new Error("key is required for incremental queries");
601
+ }
602
+ const keyColumn = key;
603
+ let callbacks: ((results: Results<T>) => void)[] = callback ? [callback] : [];
604
+ const rowsMap = new Map<unknown, Row>();
605
+ const afterMap = new Map<unknown, unknown>();
606
+ let lastRows: T[] = [];
607
+ let firstRun = true;
608
+
609
+ const {
610
+ fields,
611
+ unsubscribe: unsubscribeChanges,
612
+ refresh,
613
+ } = await changes<Row>(query, params, keyColumn, (changeList) => {
614
+ for (const change of changeList) {
615
+ const {
616
+ __op__: op,
617
+ __changed_columns__: changedColumns,
618
+ ...obj
619
+ } = change as Row & {
620
+ __op__: Change<Row>["__op__"];
621
+ __changed_columns__?: string[];
622
+ };
623
+ switch (op) {
624
+ case "RESET":
625
+ rowsMap.clear();
626
+ afterMap.clear();
627
+ break;
628
+ case "INSERT":
629
+ rowsMap.set(obj[keyColumn], obj);
630
+ afterMap.set(obj["__after__"], obj[keyColumn]);
631
+ break;
632
+ case "DELETE": {
633
+ const oldObj = rowsMap.get(obj[keyColumn]);
634
+ rowsMap.delete(obj[keyColumn]);
635
+ // null is the starting point: another insert may already have taken its place.
636
+ if (oldObj && oldObj["__after__"] !== null) {
637
+ afterMap.delete(oldObj["__after__"]);
638
+ }
639
+ break;
640
+ }
641
+ case "UPDATE": {
642
+ const newObj: Row = { ...rowsMap.get(obj[keyColumn]) };
643
+ for (const columnName of changedColumns ?? []) {
644
+ newObj[columnName] = obj[columnName];
645
+ if (columnName === "__after__") {
646
+ afterMap.set(obj["__after__"], obj[keyColumn]);
647
+ }
648
+ }
649
+ rowsMap.set(obj[keyColumn], newObj);
650
+ break;
651
+ }
652
+ }
653
+ }
654
+
655
+ // The rows in order, following each row's predecessor link.
656
+ const rows: T[] = [];
657
+ let lastKey: unknown = null;
658
+ for (let i = 0; i < rowsMap.size; i++) {
659
+ const nextKey = afterMap.get(lastKey);
660
+ const obj = rowsMap.get(nextKey);
661
+ if (!obj) break;
662
+ const { __after__: _after, ...cleanObj } = obj;
663
+ rows.push(cleanObj as T);
664
+ lastKey = nextKey;
665
+ }
666
+ lastRows = rows;
667
+
668
+ if (!firstRun) {
669
+ runResultCallbacks(callbacks, { rows, fields });
670
+ }
671
+ });
672
+
673
+ firstRun = false;
674
+ runResultCallbacks(callbacks, { rows: lastRows, fields });
675
+
676
+ const subscribe = (subscriber: (results: Results<T>) => void) => {
677
+ callbacks.push(subscriber);
678
+ };
679
+
680
+ const unsubscribe = async (subscriber?: (results: Results<T>) => void) => {
681
+ callbacks = subscriber ? callbacks.filter((cb) => cb !== subscriber) : [];
682
+ if (callbacks.length === 0) {
683
+ await unsubscribeChanges();
684
+ }
685
+ };
686
+
687
+ await unsubscribeOnAbort(signal, unsubscribe);
688
+
689
+ return {
690
+ initialResults: { rows: lastRows, fields },
691
+ subscribe,
692
+ unsubscribe,
693
+ refresh,
694
+ };
695
+ }
696
+
697
+ return { query, changes, incrementalQuery } as LiveNamespace;
698
+ }
699
+
700
+ /**
701
+ * Live queries: `live.query`, `live.changes` and `live.incrementalQuery`, re-run when a table they read
702
+ * changes (statement-level NOTIFY triggers, created once per table).
703
+ */
704
+ export const live: Extension<LiveNamespace> = {
705
+ name: "Live Queries",
706
+ setup: async (pg: Pgwasm) => ({ namespace: createNamespace(pg) }),
707
+ };