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