@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,569 @@
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 mysql from "mysql2/promise";
5
+ //#region src/db/mysql.ts
6
+ function toBufferView(bytes) {
7
+ if (Buffer.isBuffer(bytes)) return bytes;
8
+ return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
9
+ }
10
+ /**
11
+ * mysql2 returns `ResultSetHeader` for non-SELECT queries (carrying
12
+ * `affectedRows`) and `RowDataPacket[]` for SELECTs. The previous shim
13
+ * blindly cast to T[] which made `rowCount` zero for UPDATE/DELETE, breaking
14
+ * CAS detection. This helper picks the right shape.
15
+ */
16
+ function normalizeMysqlResult(raw) {
17
+ if (Array.isArray(raw)) return {
18
+ rows: raw,
19
+ rowCount: raw.length
20
+ };
21
+ if (raw && typeof raw === "object" && "affectedRows" in raw) return {
22
+ rows: [],
23
+ rowCount: Number(raw.affectedRows) || 0
24
+ };
25
+ return {
26
+ rows: [],
27
+ rowCount: 0
28
+ };
29
+ }
30
+ var MySqlDatabase = class {
31
+ constructor(logger, config, pool = void 0) {
32
+ this.logger = logger;
33
+ const { queryTimeoutMs, ...poolConfig } = config;
34
+ this.queryTimeoutMs = queryTimeoutMs ?? 0;
35
+ this.config = poolConfig;
36
+ if (pool) this.pool = pool;
37
+ else this.pool = mysql.createPool(poolConfig);
38
+ }
39
+ logger;
40
+ config;
41
+ queryTimeoutMs;
42
+ pool;
43
+ dbType = "mysql";
44
+ sqlBuilder = mysqlSql;
45
+ columnTypes = /* @__PURE__ */ new Map();
46
+ sqlCache = /* @__PURE__ */ new Map();
47
+ /**
48
+ * Fetches actual column types from MySQL for `table` and returns a
49
+ * map of DB column name → MySQL type string (as produced by `COLUMN_TYPE`,
50
+ * e.g. `bigint`, `integer`, `varchar(32)`, `text`, `json`).
51
+ * No caching here — see {@link getColumnTypes} for the cached path.
52
+ */
53
+ async loadColumnTypesFromMySql(table) {
54
+ const result = await this.query(`SELECT COLUMN_NAME AS column_name, COLUMN_TYPE AS mysql_type
55
+ FROM INFORMATION_SCHEMA.COLUMNS
56
+ WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?
57
+ ORDER BY ORDINAL_POSITION`, [table]);
58
+ const out = /* @__PURE__ */ new Map();
59
+ for (const row of result.rows) out.set(row.column_name.toLowerCase(), row.mysql_type);
60
+ return out;
61
+ }
62
+ /**
63
+ * Synchronous column-type lookup. The apply path calls this on every
64
+ * batched write, so it can't await — populate the cache via
65
+ * {@link bootstrapColumnTypes} at server start. Throws if `table` is
66
+ * missing (programmer error / bootstrap skipped).
67
+ */
68
+ getColumnTypes(table) {
69
+ const hit = this.columnTypes.get(table);
70
+ if (!hit) {
71
+ this.logger.warn({ table }, "MySqlDatabase: no cached column types fallback to non-batched writes");
72
+ return null;
73
+ }
74
+ return hit;
75
+ }
76
+ /**
77
+ * Eagerly load column types into the in-memory cache. With a Redis
78
+ * client supplied, attempts the cache key first and falls through to
79
+ * MySQL on miss (writing the result back to Redis). This is the
80
+ * "one server queries MySQL, the rest read from Redis" pattern for cold
81
+ * starts in a multi-instance deploy. Without Redis, always queries MySQL.
82
+ *
83
+ * Pass `tables` to limit the load to a specific list; otherwise every
84
+ * user table in the connected database is loaded.
85
+ *
86
+ * The Redis cache key should encode whatever invalidates types in your
87
+ * environment (typically a schema version / deploy version). The
88
+ * subscriber in supalive-server.ts is expected to publish a reload
89
+ * signal after migrations and invoke {@link invalidateColumnTypes}.
90
+ */
91
+ async bootstrapColumnTypes(opts) {
92
+ this.invalidateColumnTypes();
93
+ const { redis, cacheKey, tables } = opts;
94
+ if (redis) {
95
+ const cached = await redis.getCachedTableColumnTypes(cacheKey);
96
+ if (cached) {
97
+ for (const [table, cols] of Object.entries(cached)) this.columnTypes.set(table, new Map(Object.entries(cols)));
98
+ return;
99
+ }
100
+ }
101
+ const names = tables ?? await this.listUserTables();
102
+ for (const t of names) {
103
+ if (this.columnTypes.has(t)) continue;
104
+ const fresh = await this.loadColumnTypesFromMySql(t);
105
+ this.columnTypes.set(t, fresh);
106
+ }
107
+ if (redis) {
108
+ const dump = {};
109
+ for (const [table, cols] of this.columnTypes) dump[table] = Object.fromEntries(Object.entries(cols).sort());
110
+ await redis.setCachedTableColumnsTypes(cacheKey, dump);
111
+ }
112
+ }
113
+ /**
114
+ * Invalidate cached types (and dependent SQL) for `table`, or the entire
115
+ * cache if `table` is omitted. The Redis-pubsub reload signal in
116
+ * supalive-server.ts is expected to call this on schema changes.
117
+ */
118
+ invalidateColumnTypes(table) {
119
+ if (table) {
120
+ this.columnTypes.delete(table);
121
+ for (const k of [...this.sqlCache.keys()]) if (k.includes(`:${table}:`) || k === `d:${table}`) this.sqlCache.delete(k);
122
+ } else {
123
+ this.columnTypes.clear();
124
+ this.sqlCache.clear();
125
+ }
126
+ }
127
+ /** Replace this instance's caches with shared references from a parent.
128
+ * Used by getTransactionClient so types loaded once at startup are
129
+ * visible inside transactions. */
130
+ adoptCaches(columnTypes, sqlCache) {
131
+ this.columnTypes = columnTypes;
132
+ this.sqlCache = sqlCache;
133
+ }
134
+ /** Enumerate the user-defined tables in the connected database for mysql — used
135
+ * by bootstrapColumnTypes() when no explicit list is provided. */
136
+ async listUserTables() {
137
+ return (await this.query(`SELECT table_name FROM information_schema.tables
138
+ WHERE table_schema = DATABASE() AND table_type = 'BASE TABLE'
139
+ AND table_name NOT IN ('commit_logs', 'metadata', 'sequence')`)).rows.map((r) => r.table_name);
140
+ }
141
+ migrationSql = [
142
+ `CREATE TABLE IF NOT EXISTS commit_logs (
143
+ id BINARY(16) NOT NULL,
144
+ ts BIGINT NOT NULL,
145
+ table_id BINARY(16) NOT NULL,
146
+ data LONGBLOB NOT NULL,
147
+ PRIMARY KEY (ts, table_id, id),
148
+ INDEX commit_logs_by_table_and_id (table_id, id, ts)
149
+ ) ENGINE=InnoDB ROW_FORMAT=DYNAMIC`,
150
+ `CREATE TABLE IF NOT EXISTS sequence (id INT NOT NULL)`,
151
+ `INSERT IGNORE INTO sequence VALUES (0)`,
152
+ `CREATE TABLE IF NOT EXISTS metadata (
153
+ meta_key VARCHAR(255) PRIMARY KEY,
154
+ meta_value BIGINT NOT NULL
155
+ ) ENGINE=InnoDB;`,
156
+ `INSERT IGNORE INTO metadata (meta_key, meta_value) VALUES ('latest_committed_ts', 0);`
157
+ ];
158
+ async query(sql, params = []) {
159
+ const client = await this.pool.getConnection();
160
+ try {
161
+ const [rows] = this.queryTimeoutMs > 0 ? await client.query({
162
+ sql,
163
+ values: params,
164
+ timeout: this.queryTimeoutMs
165
+ }) : await client.query(sql, params);
166
+ return normalizeMysqlResult(rows);
167
+ } catch (err) {
168
+ throw translateMysqlError(err);
169
+ } finally {
170
+ client.release();
171
+ }
172
+ }
173
+ async getClient() {
174
+ return await this.pool.getConnection();
175
+ }
176
+ async getTransactionClient() {
177
+ const client = await this.pool.getConnection();
178
+ const tx = new MySqlTxDatabase(this.logger, {
179
+ ...this.config,
180
+ queryTimeoutMs: this.queryTimeoutMs
181
+ }, this.pool, client);
182
+ tx.adoptCaches(this.columnTypes, this.sqlCache);
183
+ return tx;
184
+ }
185
+ async getLatestSnapshotTimestamp() {
186
+ const result = await this.query("SELECT meta_value FROM metadata WHERE meta_key = 'latest_committed_ts'");
187
+ return BigInt(result.rows[0]?.meta_value ?? 0) || -1n;
188
+ }
189
+ async updateLatestSnapshotTimestamp(commitTs) {
190
+ await this.query(`UPDATE metadata SET meta_value = ? WHERE meta_key = 'latest_committed_ts' AND meta_value < ?`, [commitTs, commitTs]);
191
+ }
192
+ async getNextTimestamp() {
193
+ const result = await this.query("UPDATE sequence SET id = LAST_INSERT_ID(id + 1); SELECT LAST_INSERT_ID() AS id");
194
+ return BigInt(result.rows[0]?.id ?? 0) || -1n;
195
+ }
196
+ async attachPrevDataToWriteSet(writeSet, readSet) {
197
+ const readTsByKey = /* @__PURE__ */ new Map();
198
+ for (let i = readSet.length - 1; i >= 0; i--) {
199
+ const r = readSet[i];
200
+ if (r.kind !== "point" || r.expectedCommitTs === void 0) continue;
201
+ const key = `${r.table} ${r.id}`;
202
+ if (!readTsByKey.has(key)) readTsByKey.set(key, r.expectedCommitTs);
203
+ }
204
+ const byTable = /* @__PURE__ */ new Map();
205
+ for (const entry of writeSet) {
206
+ if (entry.op !== "update" && entry.op !== "delete") continue;
207
+ const bucket = byTable.get(entry.table);
208
+ if (bucket) bucket.push(entry);
209
+ else byTable.set(entry.table, [entry]);
210
+ }
211
+ if (byTable.size === 0) return;
212
+ for (const [table, entries] of byTable) {
213
+ const ids = entries.map((e) => e.id);
214
+ const sql = `SELECT * FROM ${table} WHERE id IN (${ids.map(() => "?").join(", ")})`;
215
+ const result = await this.query(sql, ids);
216
+ const byId = /* @__PURE__ */ new Map();
217
+ for (const row of result.rows) byId.set(String(row.id), row);
218
+ for (const entry of entries) {
219
+ const row = byId.get(String(entry.id));
220
+ const key = `${entry.table} ${entry.id}`;
221
+ const priorReadTs = readTsByKey.get(key);
222
+ if (row) {
223
+ entry.prevData = row;
224
+ entry.expectedCommitTs = priorReadTs !== void 0 ? priorReadTs : BigInt(row.commit_ts);
225
+ } else if (priorReadTs !== void 0) entry.expectedCommitTs = priorReadTs;
226
+ }
227
+ }
228
+ }
229
+ async prepareCommitWrites(readSet, writeSet, commitTs) {
230
+ const result = [];
231
+ await this.mysqlPrepareBatchWrites(result, writeSet, commitTs);
232
+ await this.mysqlPrepareCommitLogs(result, writeSet, commitTs);
233
+ if (!readSet.some((r) => r.kind === "range")) return {
234
+ commits: result,
235
+ validateReadPoints: this.mysqlPrepareValidatePointReadsByCommitTs(readSet, writeSet),
236
+ hasRangeRead: false
237
+ };
238
+ return {
239
+ commits: result,
240
+ hasRangeRead: true,
241
+ tableIds: [...new Set(readSet.map((r) => r.tableId))],
242
+ rawReadSet: mapReadSetToRaw(readSet)
243
+ };
244
+ }
245
+ async mysqlPrepareBatchWrites(result, writeSet, commitTs) {
246
+ let i = 0;
247
+ let counter = 0;
248
+ while (i < writeSet.length) {
249
+ counter++;
250
+ const { table, op } = writeSet[i];
251
+ let j = i + 1;
252
+ while (j < writeSet.length && writeSet[j].table === table && writeSet[j].op === op) j++;
253
+ const batch = writeSet.slice(i, j);
254
+ if (op === "insert") await this.mysqlPrepareInsertBatch(result, table, batch, commitTs);
255
+ else if (op === "update") await this.mysqlPrepareUpdateSingle(result, table, batch, commitTs);
256
+ else await this.mysqlPrepareDeleteBatch(result, table, batch);
257
+ i = j;
258
+ if (counter % 50 == 0) await new Promise((resolve) => setImmediate(resolve));
259
+ }
260
+ }
261
+ async mysqlPrepareInsertBatch(result, table, entries, commitTs) {
262
+ if (entries.length === 0) return;
263
+ const groups = /* @__PURE__ */ new Map();
264
+ for (const entry of entries) {
265
+ const cols = [...Object.keys(entry.data ?? {}), "commit_ts"].sort();
266
+ const key = cols.join("|");
267
+ let g = groups.get(key);
268
+ if (!g) {
269
+ g = {
270
+ cols,
271
+ rows: []
272
+ };
273
+ groups.set(key, g);
274
+ }
275
+ g.rows.push(entry);
276
+ }
277
+ let counter = 0;
278
+ for (const { cols, rows } of groups.values()) {
279
+ counter++;
280
+ const values = [];
281
+ const tuples = [];
282
+ for (const entry of rows) {
283
+ const data = {
284
+ ...entry.data ?? {},
285
+ commit_ts: commitTs
286
+ };
287
+ tuples.push(`(${cols.map(() => "?").join(", ")})`);
288
+ for (const col of cols) values.push(data[col]);
289
+ }
290
+ if (counter % 50 == 0) await new Promise((resolve) => setImmediate(resolve));
291
+ result.push({
292
+ sql: `INSERT INTO ${table} (${cols.join(", ")}) VALUES ${tuples.join(", ")}`,
293
+ params: values,
294
+ operation: "insertBatch",
295
+ table
296
+ });
297
+ }
298
+ }
299
+ async mysqlPrepareUpdateSingle(result, table, entries, commitTs) {
300
+ if (entries.length === 0) return;
301
+ let counter = 0;
302
+ for (const entry of entries) {
303
+ counter++;
304
+ const data = {
305
+ ...entry.data ?? {},
306
+ commit_ts: commitTs
307
+ };
308
+ const sets = Object.keys(data).map((c) => `${c} = ?`);
309
+ const values = Object.values(data);
310
+ const expected = entry.expectedCommitTs ?? -1n;
311
+ if (counter % 50 == 0) await new Promise((resolve) => setImmediate(resolve));
312
+ result.push({
313
+ sql: `UPDATE ${table} SET ${sets.join(", ")} WHERE id = ? AND commit_ts = ?`,
314
+ params: [
315
+ ...values,
316
+ entry.id,
317
+ expected
318
+ ],
319
+ operation: "updateSingle",
320
+ table,
321
+ entryId: entry.id,
322
+ expectedTs: expected
323
+ });
324
+ }
325
+ }
326
+ async mysqlPrepareDeleteBatch(result, table, entries) {
327
+ if (entries.length === 0) return;
328
+ let counter = 0;
329
+ for (const entry of entries) {
330
+ counter++;
331
+ const expected = entry.expectedCommitTs ?? -1n;
332
+ if (counter % 50 == 0) await new Promise((resolve) => setImmediate(resolve));
333
+ result.push({
334
+ sql: `DELETE FROM ${table} WHERE id = ? AND commit_ts = ?`,
335
+ params: [entry.id, expected],
336
+ table,
337
+ operation: "deleteSingle",
338
+ entryId: entry.id,
339
+ expectedTs: expected
340
+ });
341
+ }
342
+ }
343
+ async mysqlPrepareCommitLogs(result, writeEntries, commitTs) {
344
+ if (writeEntries.length === 0) return;
345
+ const values = [];
346
+ const tuples = [];
347
+ let counter = 0;
348
+ for (const entry of writeEntries) {
349
+ counter++;
350
+ tuples.push(`(?, ?, ?, ?)`);
351
+ values.push(toBufferView(normalizeIdToBytes(entry.id)), commitTs, toBufferView(entry.tableId), toBufferView(utf8Encode(supaliveStringify(entry))));
352
+ if (counter % 50 == 0) await new Promise((resolve) => setImmediate(resolve));
353
+ }
354
+ result.push({
355
+ sql: `INSERT INTO commit_logs (id, ts, table_id, data) VALUES ${tuples.join(", ")}`,
356
+ params: values,
357
+ table: "commit_logs",
358
+ operation: "commit_logs"
359
+ });
360
+ }
361
+ /**
362
+ * Point-only OCC check. For each genuine point read, compare the row's
363
+ * current commit_ts against the value captured at read time. A `null`
364
+ * expectedCommitTs means "row didn't exist when we read"; any row found
365
+ * now is a conflict. Reads whose row is being written in this same txn
366
+ * are skipped — the CAS UPDATE/DELETE already validated those.
367
+ */
368
+ mysqlPrepareValidatePointReadsByCommitTs(readSet, writeSet) {
369
+ const result = [];
370
+ const writeKeys = /* @__PURE__ */ new Set();
371
+ for (const w of writeSet) writeKeys.add(`${w.table} ${w.id}`);
372
+ const byTable = /* @__PURE__ */ new Map();
373
+ const seen = /* @__PURE__ */ new Set();
374
+ for (const entry of readSet) {
375
+ if (entry.kind !== "point") continue;
376
+ const key = `${entry.table} ${entry.id}`;
377
+ if (writeKeys.has(key) || seen.has(key)) continue;
378
+ seen.add(key);
379
+ if (entry.expectedCommitTs === void 0) continue;
380
+ const bucket = byTable.get(entry.table);
381
+ if (bucket) bucket.push({
382
+ entry,
383
+ key
384
+ });
385
+ else byTable.set(entry.table, [{
386
+ entry,
387
+ key
388
+ }]);
389
+ }
390
+ for (const [table, pendings] of byTable) {
391
+ const ids = pendings.map((p) => p.entry.id);
392
+ const placeholders = ids.map(() => "?").join(", ");
393
+ result.push({
394
+ sql: `SELECT id, commit_ts FROM ${table} WHERE id IN (${placeholders})`,
395
+ params: ids,
396
+ table,
397
+ operation: "pointReadValidation",
398
+ pendingsEntry: pendings
399
+ });
400
+ }
401
+ return result;
402
+ }
403
+ async commitWrites(beginTs, queries, commitTs) {
404
+ await this.mysqlApplyWrites(queries.commits);
405
+ if (!queries.hasRangeRead) {
406
+ if ((queries.validateReadPoints?.length ?? 0) > 0) await this.validatePointReadsByCommitTs(queries.validateReadPoints ?? []);
407
+ return { success: true };
408
+ }
409
+ const logs = await this.getCommitLogsSinceTs(beginTs, commitTs, queries.tableIds ?? []);
410
+ if (checkLogsAffectReadSet(logs, queries.rawReadSet ?? [])) throw new OccConflictError(`Conflict detected: overlapping commit logs since ${beginTs}`, { logs });
411
+ return { success: true };
412
+ }
413
+ async mysqlApplyWrites(result) {
414
+ for (const q of result) switch (q.operation) {
415
+ case "insertBatch":
416
+ try {
417
+ await this.query(q.sql, q.params);
418
+ } catch (err) {
419
+ if (err && typeof err === "object" && (err.errno === 1062 || err.code === "ER_DUP_ENTRY")) {
420
+ const failedId = (err.message ?? "").match(/key '[^']+'.*?\(.*?\)=\(?([^,\)]+)/)?.[1];
421
+ 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);
422
+ }
423
+ throw err;
424
+ }
425
+ break;
426
+ case "updateSingle":
427
+ 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`, {
428
+ table: q.table,
429
+ id: q.entryId,
430
+ expected: q.expectedTs
431
+ });
432
+ break;
433
+ case "deleteBatch":
434
+ 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`, {
435
+ table: q.table,
436
+ id: q.entryId,
437
+ expected: q.expectedTs
438
+ });
439
+ break;
440
+ case "commit_logs":
441
+ await this.query(q.sql, q.params);
442
+ break;
443
+ default: throw new Error("Unhandled MySQL Operation: " + q.operation);
444
+ }
445
+ }
446
+ async validatePointReadsByCommitTs(queries) {
447
+ for (const q of queries) {
448
+ const result = await this.query(q.sql, q.params);
449
+ const currentById = /* @__PURE__ */ new Map();
450
+ for (const row of result.rows) currentById.set(String(row.id), BigInt(row.commit_ts));
451
+ for (const { entry } of q.pendingsEntry ?? []) {
452
+ const current = currentById.get(String(entry.id));
453
+ const expected = entry.expectedCommitTs;
454
+ if (expected === null) {
455
+ if (current !== void 0) throw new OccConflictError(`Conflict: row ${entry.table}/${entry.id} was inserted concurrently`, {
456
+ table: entry.table,
457
+ id: entry.id
458
+ });
459
+ } else {
460
+ if (current === void 0) throw new OccConflictError(`Conflict: row ${entry.table}/${entry.id} was deleted concurrently`, {
461
+ table: entry.table,
462
+ id: entry.id,
463
+ expected
464
+ });
465
+ if (current !== expected) throw new OccConflictError(`Conflict: row ${entry.table}/${entry.id} changed from ts=${expected} to ts=${current}`, {
466
+ table: entry.table,
467
+ id: entry.id,
468
+ expected,
469
+ current
470
+ });
471
+ }
472
+ }
473
+ }
474
+ }
475
+ async pruneCommitLogsBefore(ts) {
476
+ const result = await this.query(`DELETE FROM commit_logs WHERE ts < ?`, [ts]);
477
+ return BigInt(result.rowCount ?? 0);
478
+ }
479
+ async getCommitLogsBetweenTs(beginTs, endTs, tableIds) {
480
+ if (tableIds.length === 0) return [];
481
+ const sql = `SELECT id, ts, table_id, data FROM commit_logs WHERE ts >= ? AND ts < ? AND table_id IN (${tableIds.map(() => "?").join(", ")})`;
482
+ return (await this.query(sql, [
483
+ beginTs,
484
+ endTs,
485
+ ...tableIds.map(toBufferView)
486
+ ])).rows.map((row) => ({
487
+ id: normalizeToBytes(row.id),
488
+ ts: BigInt(row.ts),
489
+ tableId: normalizeToBytes(row.table_id),
490
+ data: normalizeToBytes(row.data)
491
+ }));
492
+ }
493
+ async getCommitLogsSinceTs(sinceTs, excludeTs, tableIds) {
494
+ if (tableIds.length === 0) return [];
495
+ const sql = `SELECT id, ts, table_id, data FROM commit_logs WHERE ts >= ? AND ts <> ? AND table_id IN (${tableIds.map(() => "?").join(", ")})`;
496
+ return (await this.query(sql, [
497
+ sinceTs,
498
+ excludeTs,
499
+ ...tableIds.map(toBufferView)
500
+ ])).rows.map((row) => ({
501
+ id: normalizeToBytes(row.id),
502
+ ts: BigInt(row.ts),
503
+ tableId: normalizeToBytes(row.table_id),
504
+ data: normalizeToBytes(row.data)
505
+ }));
506
+ }
507
+ async close() {
508
+ await this.pool.end();
509
+ }
510
+ };
511
+ var MySqlTxDatabase = class extends MySqlDatabase {
512
+ constructor(logger, config, pool, client) {
513
+ super(logger, config, pool);
514
+ this.client = client;
515
+ }
516
+ client;
517
+ async query(sql, params = []) {
518
+ try {
519
+ const [rows] = this.queryTimeoutMs > 0 ? await this.client.query({
520
+ sql,
521
+ values: params,
522
+ timeout: this.queryTimeoutMs
523
+ }) : await this.client.query(sql, params);
524
+ return normalizeMysqlResult(rows);
525
+ } catch (err) {
526
+ throw translateMysqlError(err);
527
+ }
528
+ }
529
+ async begin() {
530
+ await this.client.beginTransaction();
531
+ }
532
+ async commit() {
533
+ await this.client.commit();
534
+ }
535
+ async rollback() {
536
+ await this.client.rollback();
537
+ }
538
+ release() {
539
+ this.client.release();
540
+ }
541
+ };
542
+ /**
543
+ * MySQL InnoDB deadlock (errno 1213 / SQLSTATE 40001) is transient and
544
+ * semantically equivalent to an OCC conflict from the mutation runner's
545
+ * perspective: re-execute the handler with a fresh snapshot. Wrapping
546
+ * here lets realtime_db.ts stay driver-agnostic — its retry loop already
547
+ * handles OccConflictError.
548
+ */
549
+ function translateMysqlError(err) {
550
+ if (err && typeof err === "object" && (err.errno === 1213 || err.code === "ER_LOCK_DEADLOCK")) return new OccConflictError("deadlock detected", err);
551
+ return err;
552
+ }
553
+ const mysqlSql = {
554
+ placeholder: (i) => `?`,
555
+ like: (col, i) => `${col} LIKE ?`,
556
+ ilike: (col, i) => `${col} LIKE ?`,
557
+ icontains: (col, i) => `${col} LIKE ?`,
558
+ jsonContains: (col, _i, opts) => opts?.pathIndex !== void 0 ? `JSON_CONTAINS(${col}, CAST(? AS JSON), ?)` : `JSON_CONTAINS(${col}, CAST(? AS JSON))`,
559
+ jsonContainedBy: (col, _i, opts) => opts?.pathIndex !== void 0 ? `JSON_CONTAINS(CAST(? AS JSON), JSON_EXTRACT(${col}, ?))` : `JSON_CONTAINS(CAST(? AS JSON), ${col})`,
560
+ jsonHasKey: (col, _i, opts) => {
561
+ if (opts?.pathCount && opts.pathCount > 0) return `JSON_CONTAINS_PATH(${col}, ${opts.mode === "all" ? "'all'" : "'one'"}, ${new Array(opts.pathCount).fill("?").join(", ")})`;
562
+ return opts?.raw ? `JSON_CONTAINS_PATH(${col}, 'one', ?)` : `JSON_CONTAINS_PATH(${col}, 'one', CONCAT('$."', REPLACE(?, '"', '\\\\"'), '"'))`;
563
+ },
564
+ jsonArrayContains: (col, _i, opts) => opts?.pathIndex !== void 0 ? `JSON_CONTAINS(${col}, JSON_ARRAY(CAST(? AS JSON)), ?)` : `JSON_CONTAINS(${col}, JSON_ARRAY(CAST(? AS JSON)))`
565
+ };
566
+ //#endregion
567
+ export { MySqlDatabase as t };
568
+
569
+ //# sourceMappingURL=mysql-DELSRrpY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mysql-DELSRrpY.js","names":[],"sources":["../src/db/mysql.ts"],"sourcesContent":["import mysql, { Pool, PoolConnection, PoolOptions } from \"mysql2/promise\";\nimport { Database, DbQueryResult, DbType, LazyCommitTsParam, PendingPointEntry, PooledClient, PreparedQueries, PreparedQuery, SqlBuilder, TxDatabase } from \"./db\";\nimport { CommitLogEntry, normalizeIdToBytes, normalizeToBytes, OccConflictError, PointRead, ReadEntry, WriteEntry } from \"./types_db\";\nimport { utf8Encode } from \"./bytes\";\n\n// mysql2 expects Buffer (not plain Uint8Array) for binary params.\nfunction toBufferView(bytes: Uint8Array): Buffer {\n if (Buffer.isBuffer(bytes)) return bytes;\n return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n}\nimport { checkLogsAffectReadSet, mapReadSetToRaw } from \"../server/overlap-checker\";\nimport { supaliveStringify } from \"../helper\";\nimport { CacheLayer } from \"./cache\";\nimport { Logger } from \"pino\";\n\n/**\n * mysql2 returns `ResultSetHeader` for non-SELECT queries (carrying\n * `affectedRows`) and `RowDataPacket[]` for SELECTs. The previous shim\n * blindly cast to T[] which made `rowCount` zero for UPDATE/DELETE, breaking\n * CAS detection. This helper picks the right shape.\n */\nfunction normalizeMysqlResult<T>(raw: unknown): DbQueryResult<T> {\n if (Array.isArray(raw)) {\n return { rows: raw as T[], rowCount: raw.length };\n }\n if (raw && typeof raw === \"object\" && \"affectedRows\" in raw) {\n return { rows: [], rowCount: Number((raw as { affectedRows: number }).affectedRows) || 0 };\n }\n return { rows: [], rowCount: 0 };\n}\n\ninterface QueryConnection {\n query(opts: { sql: string; timeout?: number; values?: unknown[] }): Promise<[any[], unknown]>;\n query(sql: string, params?: unknown[]): Promise<[any[], unknown]>;\n}\n\n/**\n * mysql2's PoolOptions does not have a per-statement timeout field; we\n * carry our own. Set 0 to disable.\n */\nexport type MySqlPoolOptions = PoolOptions & { queryTimeoutMs?: number };\n\nexport class MySqlDatabase implements Database {\n constructor(\n logger: Logger,\n config: MySqlPoolOptions,\n pool: Pool | undefined = undefined,\n ) {\n this.logger = logger;\n const { queryTimeoutMs, ...poolConfig } = config;\n this.queryTimeoutMs = queryTimeoutMs ?? 0;\n this.config = poolConfig;\n if (pool) {\n this.pool = pool;\n } else {\n this.pool = mysql.createPool(poolConfig);\n }\n }\n\n private logger: Logger;\n public config: PoolOptions;\n protected queryTimeoutMs: number;\n private pool: Pool;\n readonly dbType: DbType = \"mysql\";\n readonly sqlBuilder: SqlBuilder = mysqlSql;\n // Lazy per-table column-type cache. The apply path consults this for\n // unnest carriers/casts in batched writes; we never re-query pg_attribute\n // for a table we've already seen unless the cache is explicitly\n // invalidated (e.g. after a migration). Shared with tx clients via\n // adoptRegistries so a single startup load services all transactions.\n public columnTypes: Map<string, Map<string, string>> = new Map();\n // Compiled-SQL cache keyed by (op, table, sorted column signature).\n // Mirrors columnTypes — invalidated together when types change.\n protected sqlCache: Map<string, string> = new Map();\n\n /**\n * Fetches actual column types from MySQL for `table` and returns a\n * map of DB column name → MySQL type string (as produced by `COLUMN_TYPE`,\n * e.g. `bigint`, `integer`, `varchar(32)`, `text`, `json`).\n * No caching here — see {@link getColumnTypes} for the cached path.\n */\n async loadColumnTypesFromMySql(table: string): Promise<Map<string, string>> {\n const result = await this.query<{ column_name: string; mysql_type: string }>(\n `SELECT COLUMN_NAME AS column_name, COLUMN_TYPE AS mysql_type\n FROM INFORMATION_SCHEMA.COLUMNS\n WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?\n ORDER BY ORDINAL_POSITION`,\n [table],\n );\n // MySQL folds unquoted identifiers to lowercase on the server side, so\n // COLUMN_NAME comes back lowercase. JS-side column keys\n // (`entry.data`) often arrive in camelCase from the schema layer; we\n // lookup via lowercase to bridge the two cases without making callers\n // worry about it.\n const out = new Map<string, string>();\n for (const row of result.rows) out.set(row.column_name.toLowerCase(), row.mysql_type);\n return out;\n }\n\n /**\n * Synchronous column-type lookup. The apply path calls this on every\n * batched write, so it can't await — populate the cache via\n * {@link bootstrapColumnTypes} at server start. Throws if `table` is\n * missing (programmer error / bootstrap skipped).\n */\n getColumnTypes(table: string): Map<string, string> | null {\n const hit = this.columnTypes.get(table);\n if (!hit) {\n this.logger.warn({ table }, \"MySqlDatabase: no cached column types fallback to non-batched writes\");\n return null;\n }\n return hit;\n }\n\n /**\n * Eagerly load column types into the in-memory cache. With a Redis\n * client supplied, attempts the cache key first and falls through to\n * MySQL on miss (writing the result back to Redis). This is the\n * \"one server queries MySQL, the rest read from Redis\" pattern for cold\n * starts in a multi-instance deploy. Without Redis, always queries MySQL.\n *\n * Pass `tables` to limit the load to a specific list; otherwise every\n * user table in the connected database is loaded.\n *\n * The Redis cache key should encode whatever invalidates types in your\n * environment (typically a schema version / deploy version). The\n * subscriber in supalive-server.ts is expected to publish a reload\n * signal after migrations and invoke {@link invalidateColumnTypes}.\n */\n async bootstrapColumnTypes(opts: {\n redis?: CacheLayer;\n cacheKey: string;\n tables?: string[];\n }): Promise<void> {\n this.invalidateColumnTypes();\n\n const { redis, cacheKey, tables } = opts;\n\n // Redis hit path: deserialize the full table → column → mysqlType map\n // and populate in one shot, skipping any INFORMATION_SCHEMA round-trips.\n if (redis) {\n const cached = await redis.getCachedTableColumnTypes(cacheKey);\n if (cached) {\n for (const [table, cols] of Object.entries(cached)) {\n this.columnTypes.set(table, new Map(Object.entries(cols)));\n }\n return;\n }\n }\n\n // Cache miss (or no Redis): query MySQL for the listed tables\n // (or enumerate all user tables) and populate.\n const names = tables ?? await this.listUserTables();\n for (const t of names) {\n if (this.columnTypes.has(t)) continue;\n\n const fresh = await this.loadColumnTypesFromMySql(t);\n this.columnTypes.set(t, fresh);\n }\n\n // Write back to Redis so subsequent server instances skip the MySQL hop.\n if (redis) {\n const dump: Record<string, Record<string, string>> = {};\n for (const [table, cols] of this.columnTypes) {\n dump[table] = Object.fromEntries(Object.entries(cols).sort());\n }\n await redis.setCachedTableColumnsTypes(cacheKey, dump);\n }\n }\n\n /**\n * Invalidate cached types (and dependent SQL) for `table`, or the entire\n * cache if `table` is omitted. The Redis-pubsub reload signal in\n * supalive-server.ts is expected to call this on schema changes.\n */\n invalidateColumnTypes(table?: string): void {\n if (table) {\n this.columnTypes.delete(table);\n for (const k of [...this.sqlCache.keys()]) {\n if (k.includes(`:${table}:`) || k === `d:${table}`) this.sqlCache.delete(k);\n }\n } else {\n this.columnTypes.clear();\n this.sqlCache.clear();\n }\n }\n\n /** Replace this instance's caches with shared references from a parent.\n * Used by getTransactionClient so types loaded once at startup are\n * visible inside transactions. */\n adoptCaches(\n columnTypes: Map<string, Map<string, string>>,\n sqlCache: Map<string, string>,\n ): void {\n this.columnTypes = columnTypes;\n this.sqlCache = sqlCache;\n }\n\n /** Enumerate the user-defined tables in the connected database for mysql — used\n * by bootstrapColumnTypes() when no explicit list is provided. */\n private async listUserTables(): Promise<string[]> {\n const result = await this.query<{ table_name: string }>(\n `SELECT table_name FROM information_schema.tables\n WHERE table_schema = DATABASE() AND table_type = 'BASE TABLE'\n AND table_name NOT IN ('commit_logs', 'metadata', 'sequence')`\n );\n return result.rows.map(r => r.table_name);\n }\n\n migrationSql = [\n // Commit logs table (per-entry inserts, note 8)\n `CREATE TABLE IF NOT EXISTS commit_logs (\n id BINARY(16) NOT NULL,\n ts BIGINT NOT NULL,\n table_id BINARY(16) NOT NULL,\n data LONGBLOB NOT NULL,\n PRIMARY KEY (ts, table_id, id),\n INDEX commit_logs_by_table_and_id (table_id, id, ts)\n ) ENGINE=InnoDB ROW_FORMAT=DYNAMIC`,\n // `CREATE INDEX IF NOT EXISTS commit_logs_by_table_ts_and_id ON commit_logs (table_id, ts, id)`,\n\n // Timestamp sequence table for MySQL\n `CREATE TABLE IF NOT EXISTS sequence (id INT NOT NULL)`,\n `INSERT IGNORE INTO sequence VALUES (0)`,\n\n // Metadata table\n `CREATE TABLE IF NOT EXISTS metadata (\n meta_key VARCHAR(255) PRIMARY KEY,\n meta_value BIGINT NOT NULL\n ) ENGINE=InnoDB;`,\n `INSERT IGNORE INTO metadata (meta_key, meta_value) VALUES ('latest_committed_ts', 0);`\n ];\n\n async query<T = any>(sql: string, params: unknown[] = []): Promise<DbQueryResult<T>> {\n const client = await this.pool.getConnection() as PoolConnection & QueryConnection;\n try {\n const [rows] = this.queryTimeoutMs > 0\n ? await client.query({ sql, values: params, timeout: this.queryTimeoutMs })\n : await client.query(sql, params);\n return normalizeMysqlResult<T>(rows);\n } catch (err) {\n throw translateMysqlError(err);\n } finally {\n client.release();\n }\n }\n\n async getClient(): Promise<PooledClient> {\n const client = await this.pool.getConnection();\n return client as unknown as PooledClient;\n }\n\n async getTransactionClient(): Promise<TxDatabase> {\n const client = await this.pool.getConnection();\n const tx = new MySqlTxDatabase(this.logger, { ...this.config, queryTimeoutMs: this.queryTimeoutMs }, this.pool, client as PoolConnection & QueryConnection);\n tx.adoptCaches(this.columnTypes, this.sqlCache);\n return tx;\n }\n\n async getLatestSnapshotTimestamp(): Promise<bigint> {\n const result = await this.query<{ meta_value: string | number }>(\"SELECT meta_value FROM metadata WHERE meta_key = 'latest_committed_ts'\");\n return BigInt(result.rows[0]?.meta_value ?? 0) || -1n;\n }\n\n async updateLatestSnapshotTimestamp(commitTs: bigint): Promise<void> {\n await this.query(\n `UPDATE metadata SET meta_value = ? WHERE meta_key = 'latest_committed_ts' AND meta_value < ?`,\n [commitTs, commitTs]\n );\n }\n\n async getNextTimestamp(): Promise<bigint> {\n const result = await this.query<{ id: string | number | bigint }>(\n \"UPDATE sequence SET id = LAST_INSERT_ID(id + 1); SELECT LAST_INSERT_ID() AS id\"\n );\n return BigInt(result.rows[0]?.id ?? 0) || -1n;\n }\n\n // Runs on the pool, not the tx client — intentionally. This keeps the\n // transaction window short, but it means `prevData` is not snapshot-\n // consistent with the eventual commitTs (a peer may have moved the row\n // between beginTs and this SELECT). That's safe because:\n // 1. The per-row CAS in pgApplyWrites is the real snapshot fence. If a\n // peer committed in our staleness window, the CAS sees a moved\n // commit_ts and throws OccConflictError → retry.\n // 2. The only window where CAS passes with \"stale\" prevData is when\n // the current row at our SELECT moment matches `expectedCommitTs`;\n // by construction nobody committed between our captured ts and now,\n // so prevData IS consistent with the ts we're CAS-ing against.\n // 3. The downstream consumer (overlap-checker.checkRowWriteAffectsRange)\n // is conservative on missing/odd prevData — \"unknown\" verdicts still\n // invalidate, so the worst case here is a spurious invalidation,\n // never a missed one.\n // Locked in by mysql.attach-prev-data.test.ts.\n async attachPrevDataToWriteSet(writeSet: WriteEntry[], readSet: ReadEntry[]): Promise<void> {\n const readTsByKey = new Map<string, bigint | null>();\n for (let i = readSet.length - 1; i >= 0; i--) {\n const r = readSet[i]!;\n if (r.kind !== \"point\" || r.expectedCommitTs === undefined) continue;\n\n const key = `${r.table} ${r.id}`;\n if (!readTsByKey.has(key)) readTsByKey.set(key, r.expectedCommitTs);\n }\n\n const byTable = new Map<string, WriteEntry[]>();\n for (const entry of writeSet) {\n if (entry.op !== \"update\" && entry.op !== \"delete\") continue;\n\n const bucket = byTable.get(entry.table);\n if (bucket) bucket.push(entry);\n else byTable.set(entry.table, [entry]);\n }\n if (byTable.size === 0) return;\n\n for (const [table, entries] of byTable) {\n const ids = entries.map((e) => e.id);\n const placeholders = ids.map(() => \"?\").join(\", \");\n // No FOR UPDATE — the per-row CAS on the subsequent UPDATE/DELETE is\n // the fence. If a peer mutated the row since our read, the CAS will\n // see a stale expected commit_ts and throw OCC.\n const sql = `SELECT * FROM ${table} WHERE id IN (${placeholders})`;\n const result = await this.query<Record<string, unknown>>(sql, ids);\n\n const byId = new Map<string, Record<string, unknown>>();\n for (const row of result.rows) {\n byId.set(String(row.id), row);\n }\n for (const entry of entries) {\n const row = byId.get(String(entry.id));\n const key = `${entry.table} ${entry.id}`;\n const priorReadTs = readTsByKey.get(key);\n\n if (row) {\n entry.prevData = row;\n // Prefer the read-time ts so read-then-update patterns get\n // beginTs-level isolation; fall back to current row ts for\n // blind writes (no prior read).\n entry.expectedCommitTs = priorReadTs !== undefined\n ? priorReadTs\n : BigInt(row.commit_ts as string | number | bigint);\n } else if (priorReadTs !== undefined) {\n // Row gone now, but we had read it earlier: carry the read ts —\n // the CAS will then mismatch (row deleted) and throw OCC.\n entry.expectedCommitTs = priorReadTs;\n }\n // else: neither a prior read nor a current row → leave undefined\n // so CAS misses and surfaces OCC.\n }\n }\n }\n\n // Prepare BEFORE the conflict scan: each write is a CAS against the row's\n // commit_ts, so any concurrent peer that touched the row produces a\n // 0-row-affected UPDATE/DELETE → OccConflictError. Inserts surface as\n // PK violations, also translated to OCC.\n async prepareCommitWrites(\n readSet: ReadEntry[],\n writeSet: WriteEntry[],\n commitTs: LazyCommitTsParam,\n ): Promise<PreparedQueries> {\n const result: PreparedQuery[] = [];\n\n await this.mysqlPrepareBatchWrites(result, writeSet, commitTs);\n await this.mysqlPrepareCommitLogs(result, writeSet, commitTs);\n\n const hasRangeRead = readSet.some(r => r.kind === \"range\");\n if (!hasRangeRead) {\n const validateReads = this.mysqlPrepareValidatePointReadsByCommitTs(readSet, writeSet);\n return { commits: result, validateReadPoints: validateReads, hasRangeRead: false };\n }\n\n // has atleast one range read so use scan, prepare data\n const tableIds = [...new Set(readSet.map(r => r.tableId))];\n const rawReadSet = mapReadSetToRaw(readSet);\n\n return { commits: result, hasRangeRead: true, tableIds: tableIds, rawReadSet: rawReadSet };\n }\n\n private async mysqlPrepareBatchWrites(\n result: PreparedQuery[],\n writeSet: WriteEntry[],\n commitTs: LazyCommitTsParam,\n ) {\n let i = 0;\n let counter = 0;\n while (i < writeSet.length) {\n counter++;\n const { table, op } = writeSet[i];\n let j = i + 1;\n while (j < writeSet.length && writeSet[j].table === table && writeSet[j].op === op) j++;\n\n const batch = writeSet.slice(i, j);\n if (op === \"insert\") await this.mysqlPrepareInsertBatch(result, table, batch, commitTs);\n else if (op === \"update\") await this.mysqlPrepareUpdateSingle(result, table, batch, commitTs);\n else await this.mysqlPrepareDeleteBatch(result, table, batch);\n i = j;\n\n if (counter % 50 == 0) {\n await new Promise<void>((resolve) => setImmediate(resolve));\n }\n }\n }\n\n private async mysqlPrepareInsertBatch(\n result: PreparedQuery[],\n table: string,\n entries: WriteEntry[],\n commitTs: LazyCommitTsParam,\n ) {\n if (entries.length === 0) return;\n\n const groups = new Map<string, { cols: string[]; rows: WriteEntry[] }>();\n for (const entry of entries) {\n const cols = [...Object.keys(entry.data ?? {}), 'commit_ts'].sort();\n const key = cols.join(\"|\");\n let g = groups.get(key);\n if (!g) { g = { cols, rows: [] }; groups.set(key, g); }\n g.rows.push(entry);\n }\n\n let counter = 0;\n for (const { cols, rows } of groups.values()) {\n counter++;\n\n const values: unknown[] = [];\n const tuples: string[] = [];\n for (const entry of rows) {\n const data = { ...(entry.data ?? {}), commit_ts: commitTs } as Record<string, unknown>;\n tuples.push(`(${cols.map(() => \"?\").join(\", \")})`);\n for (const col of cols) {\n values.push(data[col]);\n }\n }\n if (counter % 50 == 0) {\n await new Promise<void>((resolve) => setImmediate(resolve));\n }\n\n result.push({\n sql: `INSERT INTO ${table} (${cols.join(\", \")}) VALUES ${tuples.join(\", \")}`,\n params: values,\n operation: \"insertBatch\",\n table: table,\n })\n }\n }\n\n private async mysqlPrepareUpdateSingle(\n result: PreparedQuery[],\n table: string,\n entries: WriteEntry[],\n commitTs: LazyCommitTsParam,\n ) {\n if (entries.length === 0) return;\n\n let counter = 0;\n for (const entry of entries) {\n counter++;\n\n const data = { ...(entry.data ?? {}), commit_ts: commitTs };\n const columns = Object.keys(data);\n const sets = columns.map((c) => `${c} = ?`);\n const values = Object.values(data);\n const expected = entry.expectedCommitTs ?? -1n;\n\n if (counter % 50 == 0) {\n await new Promise<void>((resolve) => setImmediate(resolve));\n }\n\n result.push({\n sql: `UPDATE ${table} SET ${sets.join(\", \")} WHERE id = ? AND commit_ts = ?`,\n params: [...values, entry.id, expected],\n operation: 'updateSingle',\n table: table,\n entryId: entry.id,\n expectedTs: expected,\n })\n }\n }\n\n private async mysqlPrepareDeleteBatch(\n result: PreparedQuery[],\n table: string,\n entries: WriteEntry[],\n ) {\n if (entries.length === 0) return;\n\n let counter = 0;\n for (const entry of entries) {\n counter++;\n\n const expected = entry.expectedCommitTs ?? -1n;\n\n if (counter % 50 == 0) {\n await new Promise<void>((resolve) => setImmediate(resolve));\n }\n\n result.push({\n sql: `DELETE FROM ${table} WHERE id = ? AND commit_ts = ?`,\n params: [entry.id, expected],\n table: table,\n operation: 'deleteSingle',\n entryId: entry.id,\n expectedTs: expected,\n });\n }\n }\n\n private async mysqlPrepareCommitLogs(\n result: PreparedQuery[],\n writeEntries: WriteEntry[],\n commitTs: LazyCommitTsParam,\n ) {\n if (writeEntries.length === 0) return;\n\n const values: unknown[] = [];\n const tuples: string[] = [];\n let counter = 0;\n\n for (const entry of writeEntries) {\n counter++;\n\n tuples.push(`(?, ?, ?, ?)`);\n values.push(\n toBufferView(normalizeIdToBytes(entry.id)),\n commitTs,\n toBufferView(entry.tableId),\n toBufferView(utf8Encode(supaliveStringify(entry))),\n );\n\n if (counter % 50 == 0) {\n await new Promise<void>((resolve) => setImmediate(resolve));\n }\n }\n\n result.push({\n sql: `INSERT INTO commit_logs (id, ts, table_id, data) VALUES ${tuples.join(\", \")}`,\n params: values,\n table: 'commit_logs',\n operation: 'commit_logs',\n })\n }\n\n /**\n * Point-only OCC check. For each genuine point read, compare the row's\n * current commit_ts against the value captured at read time. A `null`\n * expectedCommitTs means \"row didn't exist when we read\"; any row found\n * now is a conflict. Reads whose row is being written in this same txn\n * are skipped — the CAS UPDATE/DELETE already validated those.\n */\n private mysqlPrepareValidatePointReadsByCommitTs(\n readSet: ReadEntry[],\n writeSet: WriteEntry[],\n ): PreparedQuery[] {\n const result: PreparedQuery[] = [];\n\n // Skip reads whose row is being mutated in this same tx — CAS already\n // fenced them. We dedupe per (table, id) so duplicate reads of the same\n // row don't cause extra fetches.\n const writeKeys = new Set<string>();\n for (const w of writeSet) writeKeys.add(`${w.table} ${w.id}`);\n\n const byTable = new Map<string, PendingPointEntry[]>();\n const seen = new Set<string>();\n\n for (const entry of readSet) {\n if (entry.kind !== \"point\") continue;\n\n const key = `${entry.table} ${entry.id}`;\n if (writeKeys.has(key) || seen.has(key)) continue;\n\n seen.add(key);\n // expectedCommitTs === undefined → no commit_ts captured at read time\n // (synthetic or pre-migration). Skip — we cannot CAS-validate it. This\n // path should only fire when callers construct PointReads externally.\n if (entry.expectedCommitTs === undefined) continue;\n\n const bucket = byTable.get(entry.table);\n if (bucket) bucket.push({ entry, key });\n else byTable.set(entry.table, [{ entry, key }]);\n }\n\n for (const [table, pendings] of byTable) {\n const ids = pendings.map((p) => p.entry.id);\n const placeholders = ids.map(() => \"?\").join(\", \");\n\n result.push({\n sql: `SELECT id, commit_ts FROM ${table} WHERE id IN (${placeholders})`,\n params: ids,\n table: table,\n operation: 'pointReadValidation',\n pendingsEntry: pendings,\n });\n }\n\n return result;\n }\n\n async commitWrites(\n beginTs: bigint,\n queries: PreparedQueries,\n commitTs: bigint,\n ): Promise<{ success: boolean }> {\n await this.mysqlApplyWrites(queries.commits);\n\n // Fast path: when the readSet has no range reads, we don't need a\n // commit-log scan at all — point reads validate via per-row commit_ts,\n // and writes already self-validated via CAS above. This is the dominant\n // shape (most mutations target known ids) and eliminates the heaviest\n // OCC cost in the previous design.\n if (!queries.hasRangeRead) {\n if ((queries.validateReadPoints?.length ?? 0) > 0) {\n await this.validatePointReadsByCommitTs(queries.validateReadPoints ?? []);\n }\n return { success: true };\n }\n\n // Slow path: at least one range read present. Fall back to the\n // commit-log scan so phantom inserts and predicate transitions-in are\n // still caught. Point reads in the same set are covered by the same\n // scan, so no separate validation is needed.\n const logs = await this.getCommitLogsSinceTs(beginTs, commitTs, queries.tableIds ?? []);\n const hasConflict = checkLogsAffectReadSet(logs, queries.rawReadSet ?? []);\n if (hasConflict) {\n throw new OccConflictError(\n `Conflict detected: overlapping commit logs since ${beginTs}`,\n { logs }\n );\n }\n\n return { success: true };\n }\n\n // Walks the writeSet in order and coalesces consecutive entries with the\n // same (table, op) into one batched statement. Order is preserved across\n // batch boundaries so replace-patterns (delete-then-insert of the same\n // id) behave identically to the per-row code path. Single-row batches\n // take a direct INSERT/UPDATE/DELETE fast-path to avoid the unnest+join\n // overhead, which matters under high contention.\n private async mysqlApplyWrites(result: PreparedQuery[]): Promise<void> {\n for (const q of result) {\n switch (q.operation) {\n case 'insertBatch': {\n try {\n await this.query(q.sql, q.params);\n } catch (err) {\n if (\n err && typeof err === \"object\" &&\n ((err as { errno?: number }).errno === 1062 ||\n (err as { code?: string }).code === \"ER_DUP_ENTRY\")\n ) {\n const msg = (err as { message?: string }).message ?? \"\";\n const idMatch = msg.match(/key '[^']+'.*?\\(.*?\\)=\\(?([^,\\)]+)/);\n const failedId = idMatch?.[1];\n throw new OccConflictError(\n failedId !== undefined\n ? `Conflict: insert into ${q.table}/${failedId} hit duplicate key`\n : `Conflict: batch insert into ${q.table} hit duplicate key`,\n err,\n );\n }\n throw err;\n }\n break;\n }\n case 'updateSingle': {\n const result = await this.query(q.sql, q.params);\n if ((result.rowCount ?? 0) === 0) {\n throw new OccConflictError(\n `Conflict: CAS update of ${q.table}/${q.entryId} (expected commit_ts=${q.expectedTs}) matched no rows`,\n { table: q.table, id: q.entryId, expected: q.expectedTs },\n );\n }\n break;\n }\n case 'deleteBatch': {\n const result = await this.query(q.sql, q.params);\n if ((result.rowCount ?? 0) === 0) {\n throw new OccConflictError(\n `Conflict: CAS delete of ${q.table}/${q.entryId} (expected commit_ts=${q.expectedTs}) matched no rows`,\n { table: q.table, id: q.entryId, expected: q.expectedTs },\n );\n }\n break;\n }\n case 'commit_logs': {\n await this.query(q.sql, q.params);\n break;\n }\n default:\n throw new Error(\"Unhandled MySQL Operation: \" + q.operation);\n\n }\n }\n }\n\n private async validatePointReadsByCommitTs(queries: PreparedQuery[]): Promise<void> {\n\n for (const q of queries) {\n const result = await this.query<{ id: string; commit_ts: string | number | bigint }>(q.sql, q.params);\n\n const currentById = new Map<string, bigint>();\n for (const row of result.rows) {\n currentById.set(String(row.id), BigInt(row.commit_ts));\n }\n\n for (const { entry } of q.pendingsEntry ?? []) {\n const current = currentById.get(String(entry.id));\n const expected = entry.expectedCommitTs;\n\n if (expected === null) {\n // We read \"no row\"; conflict if a row now exists.\n if (current !== undefined) {\n throw new OccConflictError(\n `Conflict: row ${entry.table}/${entry.id} was inserted concurrently`,\n { table: entry.table, id: entry.id }\n );\n }\n } else {\n if (current === undefined) {\n throw new OccConflictError(\n `Conflict: row ${entry.table}/${entry.id} was deleted concurrently`,\n { table: entry.table, id: entry.id, expected }\n );\n }\n if (current !== expected) {\n throw new OccConflictError(\n `Conflict: row ${entry.table}/${entry.id} changed from ts=${expected} to ts=${current}`,\n { table: entry.table, id: entry.id, expected, current }\n );\n }\n }\n }\n }\n }\n\n async pruneCommitLogsBefore(ts: bigint): Promise<bigint> {\n const result = await this.query(\n `DELETE FROM commit_logs WHERE ts < ?`,\n [ts]\n );\n return BigInt(result.rowCount ?? 0);\n }\n\n async getCommitLogsBetweenTs(beginTs: bigint, endTs: bigint, tableIds: Uint8Array[]): Promise<CommitLogEntry[]> {\n if (tableIds.length === 0) return [];\n\n const placeholders = tableIds.map(() => '?').join(\", \");\n const sql = `SELECT id, ts, table_id, data FROM commit_logs WHERE ts >= ? AND ts < ? AND table_id IN (${placeholders})`;\n\n const result = await this.query<{ id: unknown; ts: string | number | bigint; table_id: unknown; data: unknown }>(\n sql,\n [beginTs, endTs, ...tableIds.map(toBufferView)]\n );\n\n return result.rows.map((row) => ({\n id: normalizeToBytes(row.id),\n ts: BigInt(row.ts),\n tableId: normalizeToBytes(row.table_id),\n data: normalizeToBytes(row.data),\n }));\n }\n\n async getCommitLogsSinceTs(sinceTs: bigint, excludeTs: bigint, tableIds: Uint8Array[]): Promise<CommitLogEntry[]> {\n if (tableIds.length === 0) return [];\n\n const placeholders = tableIds.map(() => '?').join(\", \");\n const sql = `SELECT id, ts, table_id, data FROM commit_logs WHERE ts >= ? AND ts <> ? AND table_id IN (${placeholders})`;\n\n const result = await this.query<{ id: unknown; ts: string | number | bigint; table_id: unknown; data: unknown }>(\n sql,\n [sinceTs, excludeTs, ...tableIds.map(toBufferView)]\n );\n\n return result.rows.map((row) => ({\n id: normalizeToBytes(row.id),\n ts: BigInt(row.ts),\n tableId: normalizeToBytes(row.table_id),\n data: normalizeToBytes(row.data),\n }));\n }\n\n async close(): Promise<void> {\n await this.pool.end();\n }\n}\n\nexport class MySqlTxDatabase extends MySqlDatabase {\n constructor(logger: Logger, config: MySqlPoolOptions, pool: Pool, client: PoolConnection & QueryConnection) {\n super(logger, config, pool);\n this.client = client;\n }\n\n private client: PoolConnection & QueryConnection;\n\n async query<T = any>(sql: string, params: unknown[] = []): Promise<DbQueryResult<T>> {\n try {\n const [rows] = this.queryTimeoutMs > 0\n ? await this.client.query({ sql, values: params as any[], timeout: this.queryTimeoutMs })\n : await this.client.query(sql, params as any[]);\n return normalizeMysqlResult<T>(rows);\n } catch (err) {\n throw translateMysqlError(err);\n }\n }\n\n async begin(): Promise<void> {\n await this.client.beginTransaction();\n }\n\n async commit(): Promise<void> {\n await this.client.commit();\n }\n\n async rollback(): Promise<void> {\n await this.client.rollback();\n }\n\n release(): void {\n this.client.release();\n }\n}\n\n/**\n * MySQL InnoDB deadlock (errno 1213 / SQLSTATE 40001) is transient and\n * semantically equivalent to an OCC conflict from the mutation runner's\n * perspective: re-execute the handler with a fresh snapshot. Wrapping\n * here lets realtime_db.ts stay driver-agnostic — its retry loop already\n * handles OccConflictError.\n */\nfunction translateMysqlError(err: unknown): unknown {\n if (\n err && typeof err === \"object\" &&\n ((err as { errno?: number }).errno === 1213 ||\n (err as { code?: string }).code === \"ER_LOCK_DEADLOCK\")\n ) {\n return new OccConflictError(\"deadlock detected\", err);\n }\n return err;\n}\n\nconst mysqlSql: SqlBuilder = {\n placeholder: (i) => `?`,\n like: (col, i) => `${col} LIKE ?`,\n ilike: (col, i) => `${col} LIKE ?`, // MySQL doesn't have ILIKE\n icontains: (col, i) => `${col} LIKE ?`,\n // CAST(? AS JSON) lets the driver bind the param as a regular string\n // (JSON-serialized client-side) and MySQL re-parses it into a JSON value\n // for containment comparison. When a sub-path is set, JSON_CONTAINS takes\n // the path as its third argument.\n jsonContains: (col, _i, opts) => opts?.pathIndex !== undefined\n ? `JSON_CONTAINS(${col}, CAST(? AS JSON), ?)`\n : `JSON_CONTAINS(${col}, CAST(? AS JSON))`,\n jsonContainedBy: (col, _i, opts) => opts?.pathIndex !== undefined\n // For \"is the column contained in the candidate at this sub-path of the\n // column\" we still need to extract the sub-path from the column side.\n // JSON_CONTAINS's path arg is on the TARGET position, so we flip and use\n // JSON_EXTRACT for the column side instead.\n ? `JSON_CONTAINS(CAST(? AS JSON), JSON_EXTRACT(${col}, ?))`\n : `JSON_CONTAINS(CAST(? AS JSON), ${col})`,\n jsonHasKey: (col, _i, opts) => {\n if (opts?.pathCount && opts.pathCount > 0) {\n const mode = opts.mode === \"all\" ? \"'all'\" : \"'one'\";\n const places = new Array(opts.pathCount).fill(\"?\").join(\", \");\n return `JSON_CONTAINS_PATH(${col}, ${mode}, ${places})`;\n }\n return opts?.raw\n // Param is already a JSON path expression like `$.foo.bar` or `$.\"a\".\"b\"`.\n ? `JSON_CONTAINS_PATH(${col}, 'one', ?)`\n // Param is a literal top-level key. Wrap it in `$.\"<key>\"` server-side\n // and escape any embedded double-quotes so dotted keys behave as keys\n // and not nested paths.\n : `JSON_CONTAINS_PATH(${col}, 'one', CONCAT('$.\"', REPLACE(?, '\"', '\\\\\\\\\"'), '\"'))`;\n },\n jsonArrayContains: (col, _i, opts) => opts?.pathIndex !== undefined\n ? `JSON_CONTAINS(${col}, JSON_ARRAY(CAST(? AS JSON)), ?)`\n : `JSON_CONTAINS(${col}, JSON_ARRAY(CAST(? AS JSON)))`,\n};\n"],"mappings":";;;;;AAMA,SAAS,aAAa,OAA2B;CAC/C,IAAI,OAAO,SAAS,KAAK,GAAG,OAAO;CACnC,OAAO,OAAO,KAAK,MAAM,QAAQ,MAAM,YAAY,MAAM,UAAU;AACrE;;;;;;;AAYA,SAAS,qBAAwB,KAAgC;CAC/D,IAAI,MAAM,QAAQ,GAA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