@supalive/core 0.1.3 → 0.1.5

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