@supalive/core 1.18.0 → 1.19.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 (81) hide show
  1. package/dist/index-BuWa503L.d.ts +2445 -0
  2. package/dist/index-BuWa503L.d.ts.map +1 -0
  3. package/dist/index-CBIjmPUS.d.ts +2444 -0
  4. package/dist/index-CBIjmPUS.d.ts.map +1 -0
  5. package/dist/index-CKo6HvJc.d.ts +2455 -0
  6. package/dist/index-CKo6HvJc.d.ts.map +1 -0
  7. package/dist/index-DShKjpzF.d.ts +2453 -0
  8. package/dist/index-DShKjpzF.d.ts.map +1 -0
  9. package/dist/index-Dcxf_Gm-.d.ts +2454 -0
  10. package/dist/index-Dcxf_Gm-.d.ts.map +1 -0
  11. package/dist/logger-DrXccWFZ.js +346 -0
  12. package/dist/logger-DrXccWFZ.js.map +1 -0
  13. package/dist/mysql-B2u0Ye4x.d.ts +114 -0
  14. package/dist/mysql-B2u0Ye4x.d.ts.map +1 -0
  15. package/dist/mysql-BHW-tAqt.d.ts +114 -0
  16. package/dist/mysql-BHW-tAqt.d.ts.map +1 -0
  17. package/dist/mysql-C_TTCZ8j.d.ts +114 -0
  18. package/dist/mysql-C_TTCZ8j.d.ts.map +1 -0
  19. package/dist/mysql-CyzJqrvO.d.ts +114 -0
  20. package/dist/mysql-CyzJqrvO.d.ts.map +1 -0
  21. package/dist/mysql-ygH2EMGn.js +622 -0
  22. package/dist/mysql-ygH2EMGn.js.map +1 -0
  23. package/dist/mysql-z9Jefhd6.d.ts +114 -0
  24. package/dist/mysql-z9Jefhd6.d.ts.map +1 -0
  25. package/dist/one-shot-query-9mCboWaB.js +565 -0
  26. package/dist/one-shot-query-9mCboWaB.js.map +1 -0
  27. package/dist/one-shot-query-B9SjfcCD.js +550 -0
  28. package/dist/one-shot-query-B9SjfcCD.js.map +1 -0
  29. package/dist/one-shot-query-BBiv9LGP.js +565 -0
  30. package/dist/one-shot-query-BBiv9LGP.js.map +1 -0
  31. package/dist/one-shot-query-Bxz_N-NE.js +563 -0
  32. package/dist/one-shot-query-Bxz_N-NE.js.map +1 -0
  33. package/dist/one-shot-query-DE9oQU40.js +550 -0
  34. package/dist/one-shot-query-DE9oQU40.js.map +1 -0
  35. package/dist/one-shot-query-adoWqGLs.js +565 -0
  36. package/dist/one-shot-query-adoWqGLs.js.map +1 -0
  37. package/dist/overlap-checker-CCgq_Tpa.js +284 -0
  38. package/dist/overlap-checker-CCgq_Tpa.js.map +1 -0
  39. package/dist/postgres-B2FLN1Kw.d.ts +118 -0
  40. package/dist/postgres-B2FLN1Kw.d.ts.map +1 -0
  41. package/dist/postgres-C7xHWbij.d.ts +118 -0
  42. package/dist/postgres-C7xHWbij.d.ts.map +1 -0
  43. package/dist/postgres-DBMAv_dq.d.ts +118 -0
  44. package/dist/postgres-DBMAv_dq.d.ts.map +1 -0
  45. package/dist/postgres-DBuP9ON_.d.ts +118 -0
  46. package/dist/postgres-DBuP9ON_.d.ts.map +1 -0
  47. package/dist/postgres-DwiUT_A6.js +867 -0
  48. package/dist/postgres-DwiUT_A6.js.map +1 -0
  49. package/dist/postgres-I4sgdBnG.d.ts +118 -0
  50. package/dist/postgres-I4sgdBnG.d.ts.map +1 -0
  51. package/dist/router-DP2ThAwh.js.map +1 -1
  52. package/dist/src/client/index.d.ts +1 -1
  53. package/dist/src/client/index.js +45 -50
  54. package/dist/src/client/index.js.map +1 -1
  55. package/dist/src/exports/mysql.d.ts +1 -1
  56. package/dist/src/exports/mysql.js +1 -1
  57. package/dist/src/exports/postgres.d.ts +1 -1
  58. package/dist/src/exports/postgres.js +1 -1
  59. package/dist/src/exports/procedure.d.ts +1 -1
  60. package/dist/src/exports/schema-sql.d.ts +1 -1
  61. package/dist/src/exports/server.d.ts +11 -4
  62. package/dist/src/exports/server.d.ts.map +1 -1
  63. package/dist/src/exports/server.js +29 -410
  64. package/dist/src/exports/server.js.map +1 -1
  65. package/dist/src/exports/sub-manager-worker-entry.js +1 -1
  66. package/dist/src/exports/types.d.ts +2 -2
  67. package/dist/sub-worker-dispatch-BLujn13f.js +792 -0
  68. package/dist/sub-worker-dispatch-BLujn13f.js.map +1 -0
  69. package/dist/types_server-BCst4TfZ.d.ts +703 -0
  70. package/dist/types_server-BCst4TfZ.d.ts.map +1 -0
  71. package/dist/types_server-BYwLkwbC.d.ts +691 -0
  72. package/dist/types_server-BYwLkwbC.d.ts.map +1 -0
  73. package/dist/types_server-Bvrohyc8.d.ts +691 -0
  74. package/dist/types_server-Bvrohyc8.d.ts.map +1 -0
  75. package/dist/types_server-C6oCm9oC.d.ts +691 -0
  76. package/dist/types_server-C6oCm9oC.d.ts.map +1 -0
  77. package/dist/types_server-CHJLfdxb.d.ts +691 -0
  78. package/dist/types_server-CHJLfdxb.d.ts.map +1 -0
  79. package/dist/types_server-DnO_fp-F.d.ts +691 -0
  80. package/dist/types_server-DnO_fp-F.d.ts.map +1 -0
  81. package/package.json +3 -1
@@ -0,0 +1,867 @@
1
+ import { o as utf8Encode, r as supaliveStringify } from "./helper-zdJT5FUc.js";
2
+ import { i as mapReadSetToRaw, o as CORE_INIT_LOCK_KEY, t as checkLogsAffectReadSet } from "./overlap-checker-CCgq_Tpa.js";
3
+ import { C as normalizeIdToBytes, l as OccConflictError, w as normalizeToBytes } from "./types_db-OUou3o2Z.js";
4
+ import { Pool } from "pg";
5
+ //#region src/db/postgres.ts
6
+ function toBufferView(bytes) {
7
+ if (Buffer.isBuffer(bytes)) return bytes;
8
+ return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
9
+ }
10
+ var PgDatabase = class {
11
+ constructor(logger, config, pool = void 0) {
12
+ this.logger = logger;
13
+ this.config = config;
14
+ if (pool) this.pool = pool;
15
+ else this.pool = new Pool(config);
16
+ }
17
+ logger;
18
+ config;
19
+ pool;
20
+ sqlBuilder = pgSql;
21
+ dbType = "postgres";
22
+ columnTypes = /* @__PURE__ */ new Map();
23
+ sqlCache = /* @__PURE__ */ new Map();
24
+ /**
25
+ * Fetches actual column types from Postgres for `table` and returns a
26
+ * map of DB column name → PG type string (as produced by `format_type`,
27
+ * e.g. `bigint`, `integer`, `character varying(32)`, `text[]`, `jsonb`).
28
+ * No caching here — see {@link getColumnTypes} for the cached path.
29
+ */
30
+ async loadColumnTypesFromPg(table) {
31
+ const result = await this.query(`SELECT a.attname AS column_name, format_type(a.atttypid, a.atttypmod) AS pg_type
32
+ FROM pg_attribute a
33
+ WHERE a.attrelid = $1::regclass AND a.attnum > 0 AND NOT a.attisdropped
34
+ ORDER BY a.attnum`, [table]);
35
+ const out = /* @__PURE__ */ new Map();
36
+ for (const row of result.rows) out.set(row.column_name.toLowerCase(), row.pg_type);
37
+ return out;
38
+ }
39
+ /**
40
+ * Synchronous column-type lookup. The apply path calls this on every
41
+ * batched write, so it can't await — populate the cache via
42
+ * {@link bootstrapColumnTypes} at server start. Throws if `table` is
43
+ * missing (programmer error / bootstrap skipped).
44
+ */
45
+ getColumnTypes(table) {
46
+ const hit = this.columnTypes.get(table);
47
+ if (!hit) {
48
+ this.logger.warn({ table }, "PgDatabase: no cached column types fallback to non-batched writes");
49
+ return null;
50
+ }
51
+ return hit;
52
+ }
53
+ /**
54
+ * Eagerly load column types into the in-memory cache. With a Redis
55
+ * client supplied, attempts the cache key first and falls through to
56
+ * Postgres on miss (writing the result back to Redis). This is the
57
+ * "one server queries PG, the rest read from Redis" pattern for cold
58
+ * starts in a multi-instance deploy. Without Redis, always queries PG.
59
+ *
60
+ * Pass `tables` to limit the load to a specific list; otherwise every
61
+ * user table in the connected database is loaded.
62
+ *
63
+ * The Redis cache key should encode whatever invalidates types in your
64
+ * environment (typically a schema version / deploy version). The
65
+ * subscriber in supalive-server.ts is expected to publish a reload
66
+ * signal after migrations and invoke {@link invalidateColumnTypes}.
67
+ */
68
+ async bootstrapColumnTypes(opts) {
69
+ this.invalidateColumnTypes();
70
+ const { redis, cacheKey, tables } = opts;
71
+ if (redis) {
72
+ const cached = await redis.getCachedTableColumnTypes(cacheKey);
73
+ if (cached) {
74
+ for (const [table, cols] of Object.entries(cached)) this.columnTypes.set(table, new Map(Object.entries(cols)));
75
+ return;
76
+ }
77
+ }
78
+ const names = tables ?? await this.listUserTables();
79
+ for (const t of names) {
80
+ if (this.columnTypes.has(t)) continue;
81
+ const fresh = await this.loadColumnTypesFromPg(t);
82
+ this.columnTypes.set(t, fresh);
83
+ }
84
+ if (redis) {
85
+ const dump = {};
86
+ for (const [table, cols] of this.columnTypes) dump[table] = Object.fromEntries([...cols.entries()].sort());
87
+ await redis.setCachedTableColumnsTypes(cacheKey, dump);
88
+ }
89
+ }
90
+ /**
91
+ * Invalidate cached types (and dependent SQL) for `table`, or the entire
92
+ * cache if `table` is omitted. The Redis-pubsub reload signal in
93
+ * supalive-server.ts is expected to call this on schema changes.
94
+ */
95
+ invalidateColumnTypes(table) {
96
+ if (table) {
97
+ this.columnTypes.delete(table);
98
+ for (const k of [...this.sqlCache.keys()]) if (k.includes(`:${table}:`) || k === `d:${table}`) this.sqlCache.delete(k);
99
+ } else {
100
+ this.columnTypes.clear();
101
+ this.sqlCache.clear();
102
+ }
103
+ }
104
+ /** Enumerate the user-defined tables in the connected database — used
105
+ * by bootstrapColumnTypes() when no explicit list is provided. */
106
+ async listUserTables() {
107
+ return (await this.query(`SELECT c.relname FROM pg_class c
108
+ JOIN pg_namespace n ON n.oid = c.relnamespace
109
+ WHERE c.relkind = 'r' AND n.nspname = ANY (current_schemas(false))
110
+ AND c.relname NOT IN ('commit_logs','metadata')`)).rows.map((r) => r.relname);
111
+ }
112
+ async getCoreVersion() {
113
+ const result = await this.query("SELECT meta_value FROM metadata WHERE meta_key = 'core_version'");
114
+ return BigInt(result.rows[0]?.meta_value ?? 0);
115
+ }
116
+ async getAppMigration() {
117
+ const result = await this.query("SELECT meta_value FROM metadata WHERE meta_key = 'app_migration'");
118
+ return BigInt(result.rows[0]?.meta_value ?? 0);
119
+ }
120
+ coreMigrationStatements(toVersion) {
121
+ if (toVersion === 1n) return [`INSERT INTO metadata (meta_key, meta_value) VALUES ('latest_committed_ts', 0) ON CONFLICT (meta_key) DO NOTHING;`, `INSERT INTO metadata (meta_key, meta_value) VALUES ('min_retained_ts', 0) ON CONFLICT (meta_key) DO NOTHING;`];
122
+ return [];
123
+ }
124
+ async withCoreInitLock(fn) {
125
+ const client = await this.pool.connect();
126
+ try {
127
+ await client.query("BEGIN");
128
+ await client.query("SELECT pg_advisory_xact_lock($1)", [CORE_INIT_LOCK_KEY]);
129
+ await fn({
130
+ exec: async (sql, params = []) => {
131
+ const r = await client.query(sql, params);
132
+ return {
133
+ rows: r.rows,
134
+ rowCount: r.rowCount
135
+ };
136
+ },
137
+ getVersion: async () => {
138
+ const r = await client.query("SELECT meta_value FROM metadata WHERE meta_key = 'core_version'");
139
+ return BigInt(r.rows[0]?.meta_value ?? 0);
140
+ },
141
+ setVersion: async (version) => {
142
+ await client.query(`INSERT INTO metadata (meta_key, meta_value) VALUES ('core_version', $1)
143
+ ON CONFLICT (meta_key) DO UPDATE SET meta_value = EXCLUDED.meta_value`, [version.toString()]);
144
+ }
145
+ });
146
+ await client.query("COMMIT");
147
+ } catch (err) {
148
+ await client.query("ROLLBACK").catch(() => {});
149
+ throw translatePgError(err);
150
+ } finally {
151
+ client.release();
152
+ }
153
+ }
154
+ async query(sql, params = []) {
155
+ const client = await this.pool.connect();
156
+ try {
157
+ const result = await client.query(sql, params);
158
+ return {
159
+ rows: result.rows,
160
+ rowCount: result.rowCount
161
+ };
162
+ } catch (err) {
163
+ throw translatePgError(err);
164
+ } finally {
165
+ client.release();
166
+ }
167
+ }
168
+ async getClient() {
169
+ return await this.pool.connect();
170
+ }
171
+ async getTransactionClient() {
172
+ const client = await this.pool.connect();
173
+ const tx = new PgTxDatabase(this.logger, this.config, this.pool, client);
174
+ tx.adoptCaches(this.columnTypes, this.sqlCache);
175
+ return tx;
176
+ }
177
+ /** Internal: replace this instance's caches with shared references from
178
+ * a parent. Used by PgDatabase.getTransactionClient. */
179
+ adoptCaches(columnTypes, sqlCache) {
180
+ this.columnTypes = columnTypes;
181
+ this.sqlCache = sqlCache;
182
+ }
183
+ async getLatestSnapshotTimestamp() {
184
+ const result = await this.query("SELECT meta_value FROM metadata WHERE meta_key = 'latest_committed_ts'");
185
+ return BigInt(result.rows[0]?.meta_value ?? 0);
186
+ }
187
+ async updateLatestSnapshotTimestamp(commitTs) {
188
+ await this.query("UPDATE metadata SET meta_value = $1 WHERE meta_key = 'latest_committed_ts' AND meta_value < $1", [commitTs]);
189
+ }
190
+ async getMinSnapshotTimestamp() {
191
+ const result = await this.query("SELECT meta_value FROM metadata WHERE meta_key = 'min_retained_ts'");
192
+ return BigInt(result.rows[0]?.meta_value ?? 0);
193
+ }
194
+ async updateMinSnapshotTimestamp(ts) {
195
+ await this.query("UPDATE metadata SET meta_value = $1 WHERE meta_key = 'min_retained_ts' AND meta_value < $1", [ts]);
196
+ }
197
+ async getNextTimestamp() {
198
+ const result = await this.query("SELECT nextval('global_commit_ts') as nextval");
199
+ return BigInt(result.rows[0]?.nextval ?? "0");
200
+ }
201
+ async attachPrevDataToWriteSet(writeSet, readSet) {
202
+ const readTsByKey = /* @__PURE__ */ new Map();
203
+ for (let i = readSet.length - 1; i >= 0; i--) {
204
+ const r = readSet[i];
205
+ if (r.kind !== "point" || r.expectedCommitTs === void 0) continue;
206
+ const key = `${r.table} ${r.id}`;
207
+ if (!readTsByKey.has(key)) readTsByKey.set(key, r.expectedCommitTs);
208
+ }
209
+ const byTable = /* @__PURE__ */ new Map();
210
+ for (const entry of writeSet) {
211
+ if (entry.op !== "update" && entry.op !== "delete") continue;
212
+ const bucket = byTable.get(entry.table);
213
+ if (bucket) bucket.push(entry);
214
+ else byTable.set(entry.table, [entry]);
215
+ }
216
+ if (byTable.size === 0) return;
217
+ for (const [table, entries] of byTable) {
218
+ const ids = entries.map((e) => e.id);
219
+ const sql = `SELECT * FROM ${table} WHERE id IN (${ids.map((_, i) => `$${i + 1}`).join(", ")})`;
220
+ const result = await this.query(sql, ids);
221
+ const byId = /* @__PURE__ */ new Map();
222
+ for (const row of result.rows) byId.set(String(row.id), row);
223
+ for (const entry of entries) {
224
+ const row = byId.get(entry.id);
225
+ const key = `${entry.table} ${entry.id}`;
226
+ const priorReadTs = readTsByKey.get(key);
227
+ if (row) {
228
+ entry.prevData = row;
229
+ entry.expectedCommitTs = priorReadTs !== void 0 ? priorReadTs : BigInt(row.commit_ts);
230
+ } else if (priorReadTs !== void 0) entry.expectedCommitTs = priorReadTs;
231
+ }
232
+ }
233
+ }
234
+ async prepareCommitWrites(readSet, writeSet, commitTs) {
235
+ const result = [];
236
+ await this.pgPrepareBatchWrites(result, writeSet, commitTs);
237
+ await this.pgPrepareCommitLogs(result, writeSet, commitTs);
238
+ if (!readSet.some((r) => r.kind === "range")) return {
239
+ commits: result,
240
+ validateReadPoints: this.pgPrepareValidatePointReadsByCommitTs(readSet, writeSet),
241
+ hasRangeRead: false
242
+ };
243
+ const rawReadSet = mapReadSetToRaw(readSet);
244
+ return {
245
+ commits: result,
246
+ hasRangeRead: true,
247
+ tableIds: [...new Set(rawReadSet.map((r) => r.tableId))],
248
+ rawReadSet
249
+ };
250
+ }
251
+ async pgPrepareBatchWrites(result, writeSet, commitTs) {
252
+ let i = 0;
253
+ let counter = 0;
254
+ while (i < writeSet.length) {
255
+ counter++;
256
+ const { table, op } = writeSet[i];
257
+ let j = i + 1;
258
+ while (j < writeSet.length && writeSet[j].table === table && writeSet[j].op === op) j++;
259
+ const batch = writeSet.slice(i, j);
260
+ if (op === "insert") await this.pgPrepareInsertBatch(result, table, batch, commitTs);
261
+ else if (op === "update") await this.pgPrepareUpdateBatch(result, table, batch, commitTs);
262
+ else await this.pgPrepareDeleteBatch(result, table, batch);
263
+ i = j;
264
+ if (counter % 50 == 0) await new Promise((resolve) => setImmediate(resolve));
265
+ }
266
+ }
267
+ pgPrepareInsertSingle(result, table, entry, commitTs) {
268
+ const data = {
269
+ ...entry.data ?? {},
270
+ commit_ts: commitTs
271
+ };
272
+ const cols = Object.keys(data);
273
+ const placeholders = cols.map((_, i) => `$${i + 1}`);
274
+ result.push({
275
+ sql: `INSERT INTO ${table} (${cols.join(", ")}) VALUES (${placeholders.join(", ")})`,
276
+ params: Object.values(data),
277
+ operation: "insertSingle",
278
+ table,
279
+ entryId: entry.id
280
+ });
281
+ }
282
+ async pgPrepareInsertBatch(result, table, entries, commitTs) {
283
+ if (entries.length === 0) return;
284
+ const types = this.getColumnTypes(table);
285
+ if (!types) {
286
+ this.logger.warn({ table }, "No column types found, falling back to non-batched writes for insert");
287
+ let counter = 0;
288
+ for (const entry of entries) {
289
+ counter++;
290
+ this.pgPrepareInsertSingle(result, table, entry, commitTs);
291
+ if (counter % 50 == 0) await new Promise((resolve) => setImmediate(resolve));
292
+ }
293
+ return;
294
+ }
295
+ const groups = /* @__PURE__ */ new Map();
296
+ for (const entry of entries) {
297
+ const cols = [...Object.keys(entry.data ?? {}), "commit_ts"].sort();
298
+ const key = cols.join("|");
299
+ let g = groups.get(key);
300
+ if (!g) {
301
+ g = {
302
+ cols,
303
+ rows: []
304
+ };
305
+ groups.set(key, g);
306
+ }
307
+ g.rows.push(entry);
308
+ }
309
+ let counter = 0;
310
+ for (const { cols, rows } of groups.values()) {
311
+ counter++;
312
+ const sql = this.buildOrGetInsertSql(table, types, cols);
313
+ const params = cols.map(() => new Array(rows.length));
314
+ for (let r = 0; r < rows.length; r++) {
315
+ const data = {
316
+ ...rows[r].data ?? {},
317
+ commit_ts: commitTs
318
+ };
319
+ for (let c = 0; c < cols.length; c++) {
320
+ const pgType = types.get(cols[c].toLowerCase()) ?? "text";
321
+ params[c][r] = encodeForCarrier(data[cols[c]], pgType);
322
+ }
323
+ }
324
+ if (counter % 50 == 0) await new Promise((resolve) => setImmediate(resolve));
325
+ result.push({
326
+ sql,
327
+ params,
328
+ operation: "insertBatch",
329
+ table
330
+ });
331
+ }
332
+ }
333
+ pgPrepareUpdateSingle(result, table, entry, commitTs) {
334
+ const data = {
335
+ ...entry.data ?? {},
336
+ commit_ts: commitTs
337
+ };
338
+ const sets = Object.keys(data).map((col, i) => `${col} = $${i + 1}`);
339
+ const values = Object.values(data);
340
+ const idP = `$${values.length + 1}`;
341
+ const tsP = `$${values.length + 2}`;
342
+ const expected = entry.expectedCommitTs ?? -1n;
343
+ result.push({
344
+ sql: `UPDATE ${table} SET ${sets.join(", ")} WHERE id = ${idP} AND commit_ts = ${tsP}`,
345
+ params: [
346
+ ...values,
347
+ entry.id,
348
+ expected
349
+ ],
350
+ operation: "updateSingle",
351
+ table,
352
+ entryId: entry.id,
353
+ expectedTs: expected
354
+ });
355
+ }
356
+ async pgPrepareUpdateBatch(result, table, entries, commitTs) {
357
+ if (entries.length === 0) return;
358
+ const types = this.getColumnTypes(table);
359
+ if (!types) {
360
+ this.logger.warn({ table }, "No column types found, falling back to non-batched writes for update");
361
+ let counter = 0;
362
+ for (const entry of entries) {
363
+ counter++;
364
+ this.pgPrepareUpdateSingle(result, table, entry, commitTs);
365
+ if (counter % 50 == 0) await new Promise((resolve) => setImmediate(resolve));
366
+ }
367
+ return;
368
+ }
369
+ const groups = /* @__PURE__ */ new Map();
370
+ for (const entry of entries) {
371
+ const cols = [...Object.keys(entry.data ?? {}), "commit_ts"].sort();
372
+ const key = cols.join("|");
373
+ let g = groups.get(key);
374
+ if (!g) {
375
+ g = {
376
+ cols,
377
+ rows: []
378
+ };
379
+ groups.set(key, g);
380
+ }
381
+ g.rows.push(entry);
382
+ }
383
+ let counter = 0;
384
+ for (const { cols, rows } of groups.values()) {
385
+ counter++;
386
+ const sql = this.buildOrGetUpdateSql(table, types, cols);
387
+ const idType = types.get("id") ?? "text";
388
+ const idArr = new Array(rows.length);
389
+ const expArr = new Array(rows.length);
390
+ const colArrs = cols.map(() => new Array(rows.length));
391
+ for (let r = 0; r < rows.length; r++) {
392
+ const entry = rows[r];
393
+ const data = {
394
+ ...entry.data ?? {},
395
+ commit_ts: commitTs
396
+ };
397
+ const expected = entry.expectedCommitTs ?? -1n;
398
+ idArr[r] = encodeForCarrier(entry.id, idType);
399
+ expArr[r] = encodeForCarrier(expected, "bigint");
400
+ for (let c = 0; c < cols.length; c++) {
401
+ const pgType = types.get(cols[c].toLowerCase()) ?? "text";
402
+ colArrs[c][r] = encodeForCarrier(data[cols[c]], pgType);
403
+ }
404
+ }
405
+ if (counter % 50 == 0) await new Promise((resolve) => setImmediate(resolve));
406
+ const params = [
407
+ idArr,
408
+ expArr,
409
+ ...colArrs
410
+ ];
411
+ result.push({
412
+ sql,
413
+ params,
414
+ operation: "updateBatch",
415
+ table,
416
+ entries: rows
417
+ });
418
+ }
419
+ }
420
+ pgPrepareDeleteSingle(result, table, entry) {
421
+ const expected = entry.expectedCommitTs ?? -1n;
422
+ result.push({
423
+ sql: `DELETE FROM ${table} WHERE id = $1 AND commit_ts = $2`,
424
+ params: [entry.id, expected],
425
+ operation: "deleteSingle",
426
+ table,
427
+ entryId: entry.id,
428
+ expectedTs: expected
429
+ });
430
+ }
431
+ async pgPrepareDeleteBatch(result, table, entries) {
432
+ if (entries.length === 0) return;
433
+ const types = this.getColumnTypes(table);
434
+ if (!types) {
435
+ this.logger.warn({ table }, "No column types found, falling back to non-batched writes for delete");
436
+ let counter = 0;
437
+ for (const entry of entries) {
438
+ counter++;
439
+ this.pgPrepareDeleteSingle(result, table, entry);
440
+ if (counter % 50 == 0) await new Promise((resolve) => setImmediate(resolve));
441
+ }
442
+ return;
443
+ }
444
+ const sql = this.buildOrGetDeleteSql(table, types);
445
+ const idType = types.get("id") ?? "text";
446
+ const idArr = new Array(entries.length);
447
+ const expArr = new Array(entries.length);
448
+ let counter = 0;
449
+ for (let i = 0; i < entries.length; i++) {
450
+ counter++;
451
+ const entry = entries[i];
452
+ const expected = entry.expectedCommitTs ?? -1n;
453
+ idArr[i] = encodeForCarrier(entry.id, idType);
454
+ expArr[i] = encodeForCarrier(expected, "bigint");
455
+ if (counter % 50 == 0) await new Promise((resolve) => setImmediate(resolve));
456
+ }
457
+ result.push({
458
+ sql,
459
+ params: [idArr, expArr],
460
+ operation: "deleteBatch",
461
+ table,
462
+ entries
463
+ });
464
+ }
465
+ buildOrGetInsertSql(table, types, cols) {
466
+ const key = `i:${table}:${cols.join(",")}`;
467
+ let sql = this.sqlCache.get(key);
468
+ if (sql) return sql;
469
+ const placeholders = cols.map((c, i) => {
470
+ const pgType = types.get(c.toLowerCase()) ?? "text";
471
+ return `$${i + 1}::${pgCarrierType(pgType)}`;
472
+ });
473
+ const aliases = cols.map((_, i) => `c${i}`);
474
+ const selectExprs = cols.map((c, i) => {
475
+ const pgType = types.get(c.toLowerCase()) ?? "text";
476
+ return pgSelectExpr(aliases[i], pgType);
477
+ });
478
+ sql = `INSERT INTO ${table} (${cols.join(", ")}) SELECT ${selectExprs.join(", ")} FROM unnest(${placeholders.join(", ")}) AS u(${aliases.join(", ")})`;
479
+ this.sqlCache.set(key, sql);
480
+ return sql;
481
+ }
482
+ buildOrGetUpdateSql(table, types, cols) {
483
+ const key = `u:${table}:${cols.join(",")}`;
484
+ let sql = this.sqlCache.get(key);
485
+ if (sql) return sql;
486
+ const idCarrier = `$1::${pgCarrierType(types.get("id") ?? "text")}`;
487
+ const expCarrier = `$2::bigint[]`;
488
+ const dataCarriers = cols.map((c, i) => {
489
+ const pgType = types.get(c.toLowerCase()) ?? "text";
490
+ return `$${i + 3}::${pgCarrierType(pgType)}`;
491
+ });
492
+ const aliases = [
493
+ "id_c",
494
+ "exp_c",
495
+ ...cols.map((_, i) => `c${i}`)
496
+ ];
497
+ sql = `UPDATE ${table} AS t SET ${cols.map((c, i) => {
498
+ const pgType = types.get(c.toLowerCase()) ?? "text";
499
+ return `${c} = ${pgSelectExpr(`u.${aliases[i + 2]}`, pgType)}`;
500
+ }).join(", ")} FROM unnest(${idCarrier}, ${expCarrier}, ${dataCarriers.join(", ")}) AS u(${aliases.join(", ")}) WHERE t.id = u.id_c AND t.commit_ts = u.exp_c RETURNING t.id AS id`;
501
+ this.sqlCache.set(key, sql);
502
+ return sql;
503
+ }
504
+ buildOrGetDeleteSql(table, types) {
505
+ const key = `d:${table}`;
506
+ let sql = this.sqlCache.get(key);
507
+ if (sql) return sql;
508
+ sql = `DELETE FROM ${table} AS t USING unnest($1::${pgCarrierType(types.get("id") ?? "text")}, $2::bigint[]) AS u(id_c, exp_c) WHERE t.id = u.id_c AND t.commit_ts = u.exp_c RETURNING t.id AS id`;
509
+ this.sqlCache.set(key, sql);
510
+ return sql;
511
+ }
512
+ async pgPrepareCommitLogs(result, writeEntries, commitTs) {
513
+ if (writeEntries.length === 0) return;
514
+ const ids = new Array(writeEntries.length);
515
+ const tss = new Array(writeEntries.length);
516
+ const tableIds = new Array(writeEntries.length);
517
+ const datas = new Array(writeEntries.length);
518
+ let counter = 0;
519
+ for (let i = 0; i < writeEntries.length; i++) {
520
+ counter++;
521
+ const entry = writeEntries[i];
522
+ ids[i] = toBufferView(normalizeIdToBytes(entry.id));
523
+ tss[i] = commitTs;
524
+ tableIds[i] = toBufferView(entry.tableId);
525
+ datas[i] = toBufferView(utf8Encode(supaliveStringify(entry)));
526
+ if (counter % 50 == 0) await new Promise((resolve) => setImmediate(resolve));
527
+ }
528
+ result.push({
529
+ sql: "INSERT INTO commit_logs (id, ts, table_id, data) SELECT * FROM unnest($1::bytea[], $2::bigint[], $3::bytea[], $4::bytea[])",
530
+ params: [
531
+ ids,
532
+ tss,
533
+ tableIds,
534
+ datas
535
+ ],
536
+ table: "commit_logs",
537
+ operation: "commit_logs"
538
+ });
539
+ }
540
+ /**
541
+ * Point-only OCC check. For each genuine point read, compare the row's
542
+ * current commit_ts against the value captured at read time. A `null`
543
+ * expectedCommitTs means "row didn't exist when we read"; any row found
544
+ * now is a conflict. Reads whose row is being written in this same txn
545
+ * are skipped — the CAS UPDATE/DELETE already validated those.
546
+ */
547
+ pgPrepareValidatePointReadsByCommitTs(readSet, writeSet) {
548
+ const result = [];
549
+ const writeKeys = /* @__PURE__ */ new Set();
550
+ for (const w of writeSet) writeKeys.add(`${w.table} ${w.id}`);
551
+ const byTable = /* @__PURE__ */ new Map();
552
+ const seen = /* @__PURE__ */ new Set();
553
+ for (const entry of readSet) {
554
+ if (entry.kind !== "point") continue;
555
+ const key = `${entry.table} ${entry.id}`;
556
+ if (writeKeys.has(key) || seen.has(key)) continue;
557
+ seen.add(key);
558
+ if (entry.expectedCommitTs === void 0) continue;
559
+ const bucket = byTable.get(entry.table);
560
+ if (bucket) bucket.push({
561
+ entry,
562
+ key
563
+ });
564
+ else byTable.set(entry.table, [{
565
+ entry,
566
+ key
567
+ }]);
568
+ }
569
+ for (const [table, pendings] of byTable) {
570
+ const ids = pendings.map((p) => p.entry.id);
571
+ const placeholders = ids.map((_, i) => `$${i + 1}`).join(", ");
572
+ result.push({
573
+ sql: `SELECT id, commit_ts FROM ${table} WHERE id IN (${placeholders})`,
574
+ params: ids,
575
+ table,
576
+ operation: "pointReadValidation",
577
+ pendingsEntry: pendings
578
+ });
579
+ }
580
+ return result;
581
+ }
582
+ async commitWrites(beginTs, queries, commitTs) {
583
+ await this.pgApplyWrites(queries.commits);
584
+ if (!queries.hasRangeRead) {
585
+ if ((queries.validateReadPoints?.length ?? 0) > 0) await this.validatePointReadsByCommitTs(queries.validateReadPoints ?? []);
586
+ return { success: true };
587
+ }
588
+ const logs = await this.getCommitLogsSinceTs(beginTs, commitTs, queries.tableIds ?? []);
589
+ if (checkLogsAffectReadSet(logs, queries.rawReadSet ?? [])) throw new OccConflictError(`Conflict detected: overlapping commit logs since ${beginTs}`, { logs });
590
+ return { success: true };
591
+ }
592
+ async pgApplyWrites(result) {
593
+ for (const q of result) switch (q.operation) {
594
+ case "insertSingle":
595
+ try {
596
+ await this.query(q.sql, q.params);
597
+ } catch (err) {
598
+ if (err && typeof err === "object" && err.code === "23505") throw new OccConflictError(`Conflict: insert into ${q.table}/${q.entryId} hit duplicate key`, err);
599
+ throw err;
600
+ }
601
+ break;
602
+ case "insertBatch":
603
+ try {
604
+ await this.query(q.sql, q.params);
605
+ } catch (err) {
606
+ if (err && typeof err === "object" && err.code === "23505") {
607
+ const failedId = (err.detail?.match(/Key \([^)]+\)=\(([^)]+)\)/))?.[1];
608
+ throw new OccConflictError(failedId !== void 0 ? `Conflict: insert into ${q.table}/${failedId} hit duplicate key` : `Conflict: batch insert into ${q.table} hit duplicate key`, err);
609
+ }
610
+ throw err;
611
+ }
612
+ break;
613
+ case "updateSingle":
614
+ if (((await this.query(q.sql, q.params)).rowCount ?? 0) === 0) throw new OccConflictError(`Conflict: CAS update of ${q.table}/${q.entryId} (expected commit_ts=${q.expectedTs}) matched no rows`, {
615
+ table: q.table,
616
+ id: q.entryId,
617
+ expectedTs: q.expectedTs
618
+ });
619
+ break;
620
+ case "updateBatch": {
621
+ const result = await this.query(q.sql, q.params);
622
+ const returned = /* @__PURE__ */ new Set();
623
+ for (const r of result.rows) returned.add(r.id);
624
+ for (const entry of q.entries) if (!returned.has(entry.id)) {
625
+ const expected = entry.expectedCommitTs ?? -1n;
626
+ throw new OccConflictError(`Conflict: CAS update of ${q.table}/${entry.id} (expected commit_ts=${expected}) matched no rows`, {
627
+ table: q.table,
628
+ id: q.entryId,
629
+ expectedTs: q.expectedTs
630
+ });
631
+ }
632
+ break;
633
+ }
634
+ case "deleteSingle":
635
+ if (((await this.query(q.sql, q.params)).rowCount ?? 0) === 0) throw new OccConflictError(`Conflict: CAS delete of ${q.table}/${q.entryId} (expected commit_ts=${q.expectedTs}) matched no rows`, {
636
+ table: q.table,
637
+ id: q.entryId,
638
+ expectedTs: q.expectedTs
639
+ });
640
+ break;
641
+ case "deleteBatch": {
642
+ const result = await this.query(q.sql, q.params);
643
+ const returned = /* @__PURE__ */ new Set();
644
+ for (const r of result.rows) returned.add(r.id);
645
+ for (const entry of q.entries) if (!returned.has(entry.id)) {
646
+ const expected = entry.expectedCommitTs ?? -1n;
647
+ throw new OccConflictError(`Conflict: CAS delete of ${q.table}/${entry.id} (expected commit_ts=${expected}) matched no rows`, {
648
+ table: q.table,
649
+ id: entry.id,
650
+ expected
651
+ });
652
+ }
653
+ break;
654
+ }
655
+ case "commit_logs":
656
+ await this.query(q.sql, q.params);
657
+ break;
658
+ default: throw new Error("Unhandled Postgres Operation: " + q.operation);
659
+ }
660
+ }
661
+ /**
662
+ * Point-only OCC check. For each genuine point read, compare the row's
663
+ * current commit_ts against the value captured at read time. A `null`
664
+ * expectedCommitTs means "row didn't exist when we read"; any row found
665
+ * now is a conflict. Reads whose row is being written in this same txn
666
+ * are skipped — the CAS UPDATE/DELETE already validated those.
667
+ */
668
+ async validatePointReadsByCommitTs(queries) {
669
+ for (const q of queries) {
670
+ const result = await this.query(q.sql, q.params);
671
+ const currentById = /* @__PURE__ */ new Map();
672
+ for (const row of result.rows) currentById.set(row.id, BigInt(row.commit_ts));
673
+ for (const { entry } of q.pendingsEntry ?? []) {
674
+ const current = currentById.get(entry.id);
675
+ const expected = entry.expectedCommitTs;
676
+ if (expected === null) {
677
+ if (current !== void 0) throw new OccConflictError(`Conflict: row ${entry.table}/${entry.id} was inserted concurrently`, {
678
+ table: entry.table,
679
+ id: entry.id
680
+ });
681
+ } else {
682
+ if (current === void 0) throw new OccConflictError(`Conflict: row ${entry.table}/${entry.id} was deleted concurrently`, {
683
+ table: entry.table,
684
+ id: entry.id,
685
+ expected
686
+ });
687
+ if (current !== expected) throw new OccConflictError(`Conflict: row ${entry.table}/${entry.id} changed from ts=${expected} to ts=${current}`, {
688
+ table: entry.table,
689
+ id: entry.id,
690
+ expected,
691
+ current
692
+ });
693
+ }
694
+ }
695
+ }
696
+ }
697
+ async pruneCommitLogsBefore(ts) {
698
+ const result = await this.query(`DELETE FROM commit_logs WHERE ts < $1`, [ts]);
699
+ return BigInt(result.rowCount ?? 0);
700
+ }
701
+ async getMinCommitLogTs() {
702
+ const min = (await this.query(`SELECT min(ts) AS min FROM commit_logs`)).rows[0]?.min;
703
+ return min === null || min === void 0 ? null : BigInt(min);
704
+ }
705
+ async getCommitLogsBetweenTs(beginTs, endTs, tableIds) {
706
+ if (tableIds.length === 0) return [];
707
+ const sql = `SELECT id, ts, table_id, data FROM commit_logs WHERE ts >= $1 AND ts < $2 AND table_id IN (${tableIds.map((_, i) => `$${i + 3}`).join(", ")})`;
708
+ return (await this.query(sql, [
709
+ beginTs,
710
+ endTs,
711
+ ...tableIds.map(toBufferView)
712
+ ])).rows.map((row) => ({
713
+ id: normalizeToBytes(row.id),
714
+ ts: BigInt(row.ts),
715
+ tableId: normalizeToBytes(row.table_id),
716
+ data: normalizeToBytes(row.data)
717
+ }));
718
+ }
719
+ async hasCommitForPoints(beginTs, endTs, points) {
720
+ if (points.length === 0) return false;
721
+ const sql = `SELECT 1 FROM commit_logs WHERE ts >= $1 AND ts < $2 AND (table_id, id) IN (${points.map((_, i) => `($${i * 2 + 3}, $${i * 2 + 4})`).join(", ")}) LIMIT 1`;
722
+ const params = [beginTs, endTs];
723
+ for (const p of points) params.push(toBufferView(p.tableId), toBufferView(p.id));
724
+ return (await this.query(sql, params)).rows.length > 0;
725
+ }
726
+ async getCommitLogsSinceTs(sinceTs, excludeTs, tableIds) {
727
+ if (tableIds.length === 0) return [];
728
+ const sql = `SELECT id, ts, table_id, data FROM commit_logs WHERE ts >= $1 AND ts <> $2 AND table_id IN (${tableIds.map((_, i) => `$${i + 3}`).join(", ")})`;
729
+ return (await this.query(sql, [
730
+ sinceTs,
731
+ excludeTs,
732
+ ...tableIds.map(toBufferView)
733
+ ])).rows.map((row) => ({
734
+ id: normalizeToBytes(row.id),
735
+ ts: BigInt(row.ts),
736
+ tableId: normalizeToBytes(row.table_id),
737
+ data: normalizeToBytes(row.data)
738
+ }));
739
+ }
740
+ async close() {
741
+ await this.pool.end();
742
+ }
743
+ };
744
+ var PgTxDatabase = class extends PgDatabase {
745
+ constructor(logger, config, pool, client) {
746
+ super(logger, config, pool);
747
+ this.client = client;
748
+ }
749
+ client;
750
+ async query(sql, params = []) {
751
+ try {
752
+ const result = await this.client.query(sql, params);
753
+ return {
754
+ rows: result.rows,
755
+ rowCount: result.rowCount
756
+ };
757
+ } catch (err) {
758
+ throw translatePgError(err);
759
+ }
760
+ }
761
+ async begin() {
762
+ await this.client.query("BEGIN");
763
+ }
764
+ async commit() {
765
+ await this.client.query("COMMIT");
766
+ }
767
+ async rollback() {
768
+ await this.client.query("ROLLBACK");
769
+ }
770
+ release() {
771
+ this.client.release();
772
+ }
773
+ };
774
+ /**
775
+ * Returns the unnest carrier array type for a column of `pgType`.
776
+ * Scalars ride as their own array type so PG infers cleanly without an
777
+ * extra cast on the SELECT/SET side. Array and jsonb columns can't ride
778
+ * as their own array type (ragged 2D arrays aren't permitted, and the
779
+ * driver can't tag jsonb sub-elements correctly inside a typed array),
780
+ * so they get the universal `text[]` carrier with an explicit cast in
781
+ * the SELECT/SET clause. Bytea rides natively as `bytea[]`.
782
+ */
783
+ function pgCarrierType(pgType) {
784
+ const base = pgType.trim().toLowerCase();
785
+ if (base === "bytea") return "bytea[]";
786
+ if (base === "jsonb" || base === "json") return "text[]";
787
+ if (base.endsWith("[]")) return "text[]";
788
+ return `${pgType}[]`;
789
+ }
790
+ /** SELECT/SET expression for an unnest alias of a column with `pgType`.
791
+ * When the carrier matches the column type (scalar / bytea), no cast is
792
+ * needed and the alias passes through. When the carrier is text[] (jsonb
793
+ * or array column), we cast back to the declared type. */
794
+ function pgSelectExpr(alias, pgType) {
795
+ const base = pgType.trim().toLowerCase();
796
+ if (base === "jsonb" || base === "json" || base.endsWith("[]")) return `(${alias})::${pgType}`;
797
+ return alias;
798
+ }
799
+ /**
800
+ * Encodes a JS runtime value for transport via the chosen unnest carrier.
801
+ * For scalar columns the pg driver handles type coercion directly (bigint,
802
+ * number, boolean, Date, etc. all serialize cleanly). For jsonb columns we
803
+ * stringify; for array columns we build a PG array literal. For bytea
804
+ * columns we forward the bytes.
805
+ *
806
+ * Codecs declared by the upstream schema layer run before this point, so
807
+ * `value` is already in the driver-side shape for its declared column.
808
+ */
809
+ function encodeForCarrier(value, pgTypeBase) {
810
+ if (value === null || value === void 0) return null;
811
+ if (pgTypeBase === "bytea") return toBufferView(normalizeToBytes(value));
812
+ if (pgTypeBase === "jsonb" || pgTypeBase === "json") return typeof value === "string" ? value : supaliveStringify(value);
813
+ if (pgTypeBase.endsWith("[]")) {
814
+ if (!Array.isArray(value)) throw new Error(`Expected array for column of type ${pgTypeBase}, got ${typeof value}`);
815
+ return pgArrayLiteral(value);
816
+ }
817
+ return value;
818
+ }
819
+ /** Serializes a JS array to a Postgres array literal `{a,b,c}`. Strings
820
+ * are double-quoted with backslash/quote escaping; primitives stringify
821
+ * directly; null becomes the literal NULL. */
822
+ function pgArrayLiteral(arr) {
823
+ const parts = new Array(arr.length);
824
+ for (let i = 0; i < arr.length; i++) {
825
+ const v = arr[i];
826
+ if (v === null || v === void 0) parts[i] = "NULL";
827
+ else if (typeof v === "string") parts[i] = `"${v.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`;
828
+ else if (typeof v === "number" || typeof v === "bigint" || typeof v === "boolean") parts[i] = String(v);
829
+ else parts[i] = `"${supaliveStringify(v).replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`;
830
+ }
831
+ return `{${parts.join(",")}}`;
832
+ }
833
+ /**
834
+ * Postgres deadlock_detected (40P01) is transient and semantically equivalent
835
+ * to an OCC conflict from the mutation runner's perspective: re-execute the
836
+ * handler with a fresh snapshot. Wrapping here lets realtime_db.ts stay
837
+ * driver-agnostic — its retry loop already handles OccConflictError.
838
+ */
839
+ function translatePgError(err) {
840
+ if (err && typeof err === "object" && err.code === "40P01") return new OccConflictError("deadlock detected", err);
841
+ return err;
842
+ }
843
+ function pgScopedTarget(col, pathIndex) {
844
+ return pathIndex === void 0 ? col : `jsonb_path_query_first(${col}::jsonb, $${pathIndex}::jsonpath)`;
845
+ }
846
+ const pgSql = {
847
+ placeholder: (i) => `$${i}`,
848
+ like: (col, i) => `${col} LIKE $${i}`,
849
+ ilike: (col, i) => `${col} ILIKE $${i}`,
850
+ icontains: (col, i) => `${col} ILIKE $${i}`,
851
+ jsonContains: (col, i, opts) => `${pgScopedTarget(col, opts?.pathIndex)} @> $${i}::jsonb`,
852
+ jsonContainedBy: (col, i, opts) => `${pgScopedTarget(col, opts?.pathIndex)} <@ $${i}::jsonb`,
853
+ jsonHasKey: (col, i, opts) => {
854
+ if (opts?.pathCount && opts.pathCount > 0) {
855
+ const joiner = opts.mode === "all" ? " AND " : " OR ";
856
+ const parts = [];
857
+ for (let k = 0; k < opts.pathCount; k++) parts.push(`jsonb_path_exists(${col}, $${i + k}::jsonpath)`);
858
+ return `(${parts.join(joiner)})`;
859
+ }
860
+ return opts?.raw ? `jsonb_path_exists(${col}, $${i}::jsonpath)` : `${col} ? $${i}`;
861
+ },
862
+ jsonArrayContains: (col, i, opts) => `${pgScopedTarget(col, opts?.pathIndex)} @> jsonb_build_array($${i}::jsonb)`
863
+ };
864
+ //#endregion
865
+ export { PgDatabase as t };
866
+
867
+ //# sourceMappingURL=postgres-DwiUT_A6.js.map