@supalive/core 1.13.1 → 1.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +1 -2
  2. package/dist/helper-CUSGbt2A.d.ts +15 -0
  3. package/dist/helper-CUSGbt2A.d.ts.map +1 -0
  4. package/dist/helper-CVcjwD3k.js +73 -0
  5. package/dist/helper-CVcjwD3k.js.map +1 -0
  6. package/dist/index-Ddr4NiPf.d.ts +2295 -0
  7. package/dist/index-Ddr4NiPf.d.ts.map +1 -0
  8. package/dist/index-f7mNbMhq.d.ts +2301 -0
  9. package/dist/index-f7mNbMhq.d.ts.map +1 -0
  10. package/dist/mysql-BX5hfgfE.d.ts +114 -0
  11. package/dist/mysql-BX5hfgfE.d.ts.map +1 -0
  12. package/dist/mysql-DWj2q3qR.d.ts +114 -0
  13. package/dist/mysql-DWj2q3qR.d.ts.map +1 -0
  14. package/dist/mysql-v_0U0NU4.js +623 -0
  15. package/dist/mysql-v_0U0NU4.js.map +1 -0
  16. package/dist/overlap-checker-DVbh0YC4.js +259 -0
  17. package/dist/overlap-checker-DVbh0YC4.js.map +1 -0
  18. package/dist/postgres-D0M1ri-C.d.ts +118 -0
  19. package/dist/postgres-D0M1ri-C.d.ts.map +1 -0
  20. package/dist/postgres-EUz8TYFn.d.ts +118 -0
  21. package/dist/postgres-EUz8TYFn.d.ts.map +1 -0
  22. package/dist/postgres-vYRyZJZd.js +868 -0
  23. package/dist/postgres-vYRyZJZd.js.map +1 -0
  24. package/dist/query-Bk2W-ynQ.js +730 -0
  25. package/dist/query-Bk2W-ynQ.js.map +1 -0
  26. package/dist/realtime_db-DnZKn_FZ.js +312 -0
  27. package/dist/realtime_db-DnZKn_FZ.js.map +1 -0
  28. package/dist/router-DP2ThAwh.js +274 -0
  29. package/dist/router-DP2ThAwh.js.map +1 -0
  30. package/dist/router-Dfnwka7K.js +337 -0
  31. package/dist/router-Dfnwka7K.js.map +1 -0
  32. package/dist/schema-DRtz5h5l.js +131 -0
  33. package/dist/schema-DRtz5h5l.js.map +1 -0
  34. package/dist/src/client/index.d.ts +1 -1
  35. package/dist/src/client/index.js +2 -2
  36. package/dist/src/exports/mysql.d.ts +1 -1
  37. package/dist/src/exports/postgres.d.ts +1 -1
  38. package/dist/src/exports/procedure.d.ts +12 -9
  39. package/dist/src/exports/procedure.d.ts.map +1 -1
  40. package/dist/src/exports/procedure.js +65 -6
  41. package/dist/src/exports/procedure.js.map +1 -1
  42. package/dist/src/exports/schema-sql.d.ts +2 -2
  43. package/dist/src/exports/schema-sql.js +3 -3
  44. package/dist/src/exports/schema-sql.js.map +1 -1
  45. package/dist/src/exports/server.d.ts +4 -4
  46. package/dist/src/exports/server.d.ts.map +1 -1
  47. package/dist/src/exports/server.js +4 -4
  48. package/dist/src/exports/server.js.map +1 -1
  49. package/dist/src/exports/sub-manager-worker-entry.js +1 -1
  50. package/dist/src/exports/types.d.ts +8 -3
  51. package/dist/src/exports/types.d.ts.map +1 -0
  52. package/dist/src/exports/types.js +20 -1
  53. package/dist/src/exports/types.js.map +1 -0
  54. package/dist/sub-worker-dispatch-CC0w_sx0.js +826 -0
  55. package/dist/sub-worker-dispatch-CC0w_sx0.js.map +1 -0
  56. package/dist/sub-worker-dispatch-UGC9vwQJ.js +826 -0
  57. package/dist/sub-worker-dispatch-UGC9vwQJ.js.map +1 -0
  58. package/dist/types_db-Dw2RHWrd.js +172 -0
  59. package/dist/types_db-Dw2RHWrd.js.map +1 -0
  60. package/dist/types_server-B7elBQyz.d.ts +523 -0
  61. package/dist/types_server-B7elBQyz.d.ts.map +1 -0
  62. package/dist/types_server-BSiGxbqb.d.ts +523 -0
  63. package/dist/types_server-BSiGxbqb.d.ts.map +1 -0
  64. package/package.json +1 -1
@@ -0,0 +1,623 @@
1
+ import { i as supaliveStringify, s as utf8Encode } from "./helper-CVcjwD3k.js";
2
+ import { n as CORE_INIT_LOCK_NAME } from "./db-ClCicssQ.js";
3
+ import { C as normalizeIdToBytes, l as OccConflictError, w as normalizeToBytes } from "./types_db-Dw2RHWrd.js";
4
+ import { i as mapReadSetToRaw, t as checkLogsAffectReadSet } from "./overlap-checker-DVbh0YC4.js";
5
+ import mysql from "mysql2/promise";
6
+ //#region src/db/mysql.ts
7
+ function toBufferView(bytes) {
8
+ if (Buffer.isBuffer(bytes)) return bytes;
9
+ return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
10
+ }
11
+ function encodeMysqlWriteParam(value) {
12
+ if (value == null) return value;
13
+ if (value instanceof Map) return JSON.stringify(Object.fromEntries(value));
14
+ if (Array.isArray(value) || Object.getPrototypeOf(value) === Object.prototype) return JSON.stringify(value);
15
+ return value;
16
+ }
17
+ /**
18
+ * mysql2 returns `ResultSetHeader` for non-SELECT queries (carrying
19
+ * `affectedRows`) and `RowDataPacket[]` for SELECTs. The previous shim
20
+ * blindly cast to T[] which made `rowCount` zero for UPDATE/DELETE, breaking
21
+ * CAS detection. This helper picks the right shape.
22
+ */
23
+ function normalizeMysqlResult(raw) {
24
+ if (Array.isArray(raw)) return {
25
+ rows: raw,
26
+ rowCount: raw.length
27
+ };
28
+ if (raw && typeof raw === "object" && "affectedRows" in raw) {
29
+ const header = raw;
30
+ return {
31
+ rows: [],
32
+ rowCount: Number(header.affectedRows) || 0,
33
+ insertId: header.insertId
34
+ };
35
+ }
36
+ return {
37
+ rows: [],
38
+ rowCount: 0
39
+ };
40
+ }
41
+ var MySqlDatabase = class {
42
+ constructor(logger, config, pool = void 0) {
43
+ this.logger = logger;
44
+ const { queryTimeoutMs, ...poolConfig } = config;
45
+ this.queryTimeoutMs = queryTimeoutMs ?? 0;
46
+ this.config = poolConfig;
47
+ if (pool) this.pool = pool;
48
+ else this.pool = mysql.createPool(poolConfig);
49
+ }
50
+ logger;
51
+ config;
52
+ queryTimeoutMs;
53
+ pool;
54
+ dbType = "mysql";
55
+ sqlBuilder = mysqlSql;
56
+ columnTypes = /* @__PURE__ */ new Map();
57
+ sqlCache = /* @__PURE__ */ new Map();
58
+ /**
59
+ * Fetches actual column types from MySQL for `table` and returns a
60
+ * map of DB column name → MySQL type string (as produced by `COLUMN_TYPE`,
61
+ * e.g. `bigint`, `integer`, `varchar(32)`, `text`, `json`).
62
+ * No caching here — see {@link getColumnTypes} for the cached path.
63
+ */
64
+ async loadColumnTypesFromMySql(table) {
65
+ const result = await this.query(`SELECT COLUMN_NAME AS column_name, COLUMN_TYPE AS mysql_type
66
+ FROM INFORMATION_SCHEMA.COLUMNS
67
+ WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?
68
+ ORDER BY ORDINAL_POSITION`, [table]);
69
+ const out = /* @__PURE__ */ new Map();
70
+ for (const row of result.rows) out.set(row.column_name.toLowerCase(), row.mysql_type);
71
+ return out;
72
+ }
73
+ /**
74
+ * Synchronous column-type lookup. The apply path calls this on every
75
+ * batched write, so it can't await — populate the cache via
76
+ * {@link bootstrapColumnTypes} at server start. Throws if `table` is
77
+ * missing (programmer error / bootstrap skipped).
78
+ */
79
+ getColumnTypes(table) {
80
+ const hit = this.columnTypes.get(table);
81
+ if (!hit) {
82
+ this.logger.warn({ table }, "MySqlDatabase: no cached column types fallback to non-batched writes");
83
+ return null;
84
+ }
85
+ return hit;
86
+ }
87
+ /**
88
+ * Eagerly load column types into the in-memory cache. With a Redis
89
+ * client supplied, attempts the cache key first and falls through to
90
+ * MySQL on miss (writing the result back to Redis). This is the
91
+ * "one server queries MySQL, the rest read from Redis" pattern for cold
92
+ * starts in a multi-instance deploy. Without Redis, always queries MySQL.
93
+ *
94
+ * Pass `tables` to limit the load to a specific list; otherwise every
95
+ * user table in the connected database is loaded.
96
+ *
97
+ * The Redis cache key should encode whatever invalidates types in your
98
+ * environment (typically a schema version / deploy version). The
99
+ * subscriber in supalive-server.ts is expected to publish a reload
100
+ * signal after migrations and invoke {@link invalidateColumnTypes}.
101
+ */
102
+ async bootstrapColumnTypes(opts) {
103
+ this.invalidateColumnTypes();
104
+ const { redis, cacheKey, tables } = opts;
105
+ if (redis) {
106
+ const cached = await redis.getCachedTableColumnTypes(cacheKey);
107
+ if (cached) {
108
+ for (const [table, cols] of Object.entries(cached)) this.columnTypes.set(table, new Map(Object.entries(cols)));
109
+ return;
110
+ }
111
+ }
112
+ const names = tables ?? await this.listUserTables();
113
+ for (const t of names) {
114
+ if (this.columnTypes.has(t)) continue;
115
+ const fresh = await this.loadColumnTypesFromMySql(t);
116
+ this.columnTypes.set(t, fresh);
117
+ }
118
+ if (redis) {
119
+ const dump = {};
120
+ for (const [table, cols] of this.columnTypes) dump[table] = Object.fromEntries(Object.entries(cols).sort());
121
+ await redis.setCachedTableColumnsTypes(cacheKey, dump);
122
+ }
123
+ }
124
+ /**
125
+ * Invalidate cached types (and dependent SQL) for `table`, or the entire
126
+ * cache if `table` is omitted. The Redis-pubsub reload signal in
127
+ * supalive-server.ts is expected to call this on schema changes.
128
+ */
129
+ invalidateColumnTypes(table) {
130
+ if (table) {
131
+ this.columnTypes.delete(table);
132
+ for (const k of [...this.sqlCache.keys()]) if (k.includes(`:${table}:`) || k === `d:${table}`) this.sqlCache.delete(k);
133
+ } else {
134
+ this.columnTypes.clear();
135
+ this.sqlCache.clear();
136
+ }
137
+ }
138
+ /** Replace this instance's caches with shared references from a parent.
139
+ * Used by getTransactionClient so types loaded once at startup are
140
+ * visible inside transactions. */
141
+ adoptCaches(columnTypes, sqlCache) {
142
+ this.columnTypes = columnTypes;
143
+ this.sqlCache = sqlCache;
144
+ }
145
+ /** Enumerate the user-defined tables in the connected database for mysql — used
146
+ * by bootstrapColumnTypes() when no explicit list is provided. */
147
+ async listUserTables() {
148
+ return (await this.query(`SELECT table_name FROM information_schema.tables
149
+ WHERE table_schema = DATABASE() AND table_type = 'BASE TABLE'
150
+ AND table_name NOT IN ('commit_logs', 'metadata', 'global_commit_ts')`)).rows.map((r) => r.table_name);
151
+ }
152
+ async getCoreVersion() {
153
+ const result = await this.query("SELECT meta_value FROM metadata WHERE meta_key = 'core_version'");
154
+ return BigInt(result.rows[0]?.meta_value ?? 0);
155
+ }
156
+ async getAppMigration() {
157
+ const result = await this.query("SELECT meta_value FROM metadata WHERE meta_key = 'app_migration'");
158
+ return BigInt(result.rows[0]?.meta_value ?? 0);
159
+ }
160
+ coreMigrationStatements(toVersion) {
161
+ if (toVersion === 1n) return [
162
+ `INSERT IGNORE INTO global_commit_ts VALUES (0)`,
163
+ `INSERT IGNORE INTO metadata (meta_key, meta_value) VALUES ('latest_committed_ts', 0)`,
164
+ `INSERT IGNORE INTO metadata (meta_key, meta_value) VALUES ('min_retained_ts', 0)`
165
+ ];
166
+ return [];
167
+ }
168
+ async withCoreInitLock(fn) {
169
+ const conn = await this.pool.getConnection();
170
+ try {
171
+ const [rows] = await conn.query("SELECT GET_LOCK(?, 30) AS locked", [CORE_INIT_LOCK_NAME]);
172
+ if ((Array.isArray(rows) ? rows[0]?.locked : void 0) !== 1) throw new Error(`Failed to acquire core-init lock '${CORE_INIT_LOCK_NAME}'`);
173
+ await fn({
174
+ exec: async (sql, params = []) => {
175
+ const [r] = await conn.query(sql, params);
176
+ return normalizeMysqlResult(r);
177
+ },
178
+ getVersion: async () => {
179
+ const [r] = await conn.query("SELECT meta_value FROM metadata WHERE meta_key = 'core_version'");
180
+ const row = Array.isArray(r) ? r[0] : void 0;
181
+ return BigInt(row?.meta_value ?? 0);
182
+ },
183
+ setVersion: async (version) => {
184
+ await conn.query(`INSERT INTO metadata (meta_key, meta_value) VALUES ('core_version', ?)
185
+ ON DUPLICATE KEY UPDATE meta_value = VALUES(meta_value)`, [version.toString()]);
186
+ }
187
+ });
188
+ } finally {
189
+ await conn.query("SELECT RELEASE_LOCK(?)", [CORE_INIT_LOCK_NAME]).catch(() => {});
190
+ conn.release();
191
+ }
192
+ }
193
+ async query(sql, params = []) {
194
+ const client = await this.pool.getConnection();
195
+ try {
196
+ const [rows] = this.queryTimeoutMs > 0 ? await client.query({
197
+ sql,
198
+ values: params,
199
+ timeout: this.queryTimeoutMs
200
+ }) : await client.query(sql, params);
201
+ return normalizeMysqlResult(rows);
202
+ } catch (err) {
203
+ throw translateMysqlError(err);
204
+ } finally {
205
+ client.release();
206
+ }
207
+ }
208
+ async getClient() {
209
+ return await this.pool.getConnection();
210
+ }
211
+ async getTransactionClient() {
212
+ const client = await this.pool.getConnection();
213
+ const tx = new MySqlTxDatabase(this.logger, {
214
+ ...this.config,
215
+ queryTimeoutMs: this.queryTimeoutMs
216
+ }, this.pool, client);
217
+ tx.adoptCaches(this.columnTypes, this.sqlCache);
218
+ return tx;
219
+ }
220
+ async getLatestSnapshotTimestamp() {
221
+ const result = await this.query("SELECT meta_value FROM metadata WHERE meta_key = 'latest_committed_ts'");
222
+ return BigInt(result.rows[0]?.meta_value ?? 0);
223
+ }
224
+ async updateLatestSnapshotTimestamp(commitTs) {
225
+ await this.query(`UPDATE metadata SET meta_value = ? WHERE meta_key = 'latest_committed_ts' AND meta_value < ?`, [commitTs, commitTs]);
226
+ }
227
+ async getMinSnapshotTimestamp() {
228
+ const result = await this.query("SELECT meta_value FROM metadata WHERE meta_key = 'min_retained_ts'");
229
+ return BigInt(result.rows[0]?.meta_value ?? 0);
230
+ }
231
+ async updateMinSnapshotTimestamp(ts) {
232
+ await this.query(`UPDATE metadata SET meta_value = ? WHERE meta_key = 'min_retained_ts' AND meta_value < ?`, [ts, ts]);
233
+ }
234
+ async getNextTimestamp() {
235
+ const result = await this.query("UPDATE global_commit_ts SET id = LAST_INSERT_ID(id + 1)");
236
+ return BigInt(result.insertId ?? 0);
237
+ }
238
+ async attachPrevDataToWriteSet(writeSet, readSet) {
239
+ const readTsByKey = /* @__PURE__ */ new Map();
240
+ for (let i = readSet.length - 1; i >= 0; i--) {
241
+ const r = readSet[i];
242
+ if (r.kind !== "point" || r.expectedCommitTs === void 0) continue;
243
+ const key = `${r.table} ${r.id}`;
244
+ if (!readTsByKey.has(key)) readTsByKey.set(key, r.expectedCommitTs);
245
+ }
246
+ const byTable = /* @__PURE__ */ new Map();
247
+ for (const entry of writeSet) {
248
+ if (entry.op !== "update" && entry.op !== "delete") continue;
249
+ const bucket = byTable.get(entry.table);
250
+ if (bucket) bucket.push(entry);
251
+ else byTable.set(entry.table, [entry]);
252
+ }
253
+ if (byTable.size === 0) return;
254
+ for (const [table, entries] of byTable) {
255
+ const ids = entries.map((e) => e.id);
256
+ const sql = `SELECT * FROM ${table} WHERE id IN (${ids.map(() => "?").join(", ")})`;
257
+ const result = await this.query(sql, ids);
258
+ const byId = /* @__PURE__ */ new Map();
259
+ for (const row of result.rows) byId.set(String(row.id), row);
260
+ for (const entry of entries) {
261
+ const row = byId.get(String(entry.id));
262
+ const key = `${entry.table} ${entry.id}`;
263
+ const priorReadTs = readTsByKey.get(key);
264
+ if (row) {
265
+ entry.prevData = row;
266
+ entry.expectedCommitTs = priorReadTs !== void 0 ? priorReadTs : BigInt(row.commit_ts);
267
+ } else if (priorReadTs !== void 0) entry.expectedCommitTs = priorReadTs;
268
+ }
269
+ }
270
+ }
271
+ async prepareCommitWrites(readSet, writeSet, commitTs) {
272
+ const result = [];
273
+ await this.mysqlPrepareBatchWrites(result, writeSet, commitTs);
274
+ await this.mysqlPrepareCommitLogs(result, writeSet, commitTs);
275
+ if (!readSet.some((r) => r.kind === "range")) return {
276
+ commits: result,
277
+ validateReadPoints: this.mysqlPrepareValidatePointReadsByCommitTs(readSet, writeSet),
278
+ hasRangeRead: false
279
+ };
280
+ const rawReadSet = mapReadSetToRaw(readSet);
281
+ return {
282
+ commits: result,
283
+ hasRangeRead: true,
284
+ tableIds: [...new Set(rawReadSet.map((r) => r.tableId))],
285
+ rawReadSet
286
+ };
287
+ }
288
+ async mysqlPrepareBatchWrites(result, writeSet, commitTs) {
289
+ let i = 0;
290
+ let counter = 0;
291
+ while (i < writeSet.length) {
292
+ counter++;
293
+ const { table, op } = writeSet[i];
294
+ let j = i + 1;
295
+ while (j < writeSet.length && writeSet[j].table === table && writeSet[j].op === op) j++;
296
+ const batch = writeSet.slice(i, j);
297
+ if (op === "insert") await this.mysqlPrepareInsertBatch(result, table, batch, commitTs);
298
+ else if (op === "update") await this.mysqlPrepareUpdateSingle(result, table, batch, commitTs);
299
+ else await this.mysqlPrepareDeleteBatch(result, table, batch);
300
+ i = j;
301
+ if (counter % 50 == 0) await new Promise((resolve) => setImmediate(resolve));
302
+ }
303
+ }
304
+ async mysqlPrepareInsertBatch(result, table, entries, commitTs) {
305
+ if (entries.length === 0) return;
306
+ const groups = /* @__PURE__ */ new Map();
307
+ for (const entry of entries) {
308
+ const cols = [...Object.keys(entry.data ?? {}), "commit_ts"].sort();
309
+ const key = cols.join("|");
310
+ let g = groups.get(key);
311
+ if (!g) {
312
+ g = {
313
+ cols,
314
+ rows: []
315
+ };
316
+ groups.set(key, g);
317
+ }
318
+ g.rows.push(entry);
319
+ }
320
+ let counter = 0;
321
+ for (const { cols, rows } of groups.values()) {
322
+ counter++;
323
+ const values = [];
324
+ const tuples = [];
325
+ for (const entry of rows) {
326
+ const data = {
327
+ ...entry.data ?? {},
328
+ commit_ts: commitTs
329
+ };
330
+ tuples.push(`(${cols.map(() => "?").join(", ")})`);
331
+ for (const col of cols) values.push(encodeMysqlWriteParam(data[col]));
332
+ }
333
+ if (counter % 50 == 0) await new Promise((resolve) => setImmediate(resolve));
334
+ result.push({
335
+ sql: `INSERT INTO ${table} (${cols.join(", ")}) VALUES ${tuples.join(", ")}`,
336
+ params: values,
337
+ operation: "insertBatch",
338
+ table
339
+ });
340
+ }
341
+ }
342
+ async mysqlPrepareUpdateSingle(result, table, entries, commitTs) {
343
+ if (entries.length === 0) return;
344
+ let counter = 0;
345
+ for (const entry of entries) {
346
+ counter++;
347
+ const data = {
348
+ ...entry.data ?? {},
349
+ commit_ts: commitTs
350
+ };
351
+ const sets = Object.keys(data).map((c) => `${c} = ?`);
352
+ const values = Object.values(data).map(encodeMysqlWriteParam);
353
+ const expected = entry.expectedCommitTs ?? -1n;
354
+ if (counter % 50 == 0) await new Promise((resolve) => setImmediate(resolve));
355
+ result.push({
356
+ sql: `UPDATE ${table} SET ${sets.join(", ")} WHERE id = ? AND commit_ts = ?`,
357
+ params: [
358
+ ...values,
359
+ entry.id,
360
+ expected
361
+ ],
362
+ operation: "updateSingle",
363
+ table,
364
+ entryId: entry.id,
365
+ expectedTs: expected
366
+ });
367
+ }
368
+ }
369
+ async mysqlPrepareDeleteBatch(result, table, entries) {
370
+ if (entries.length === 0) return;
371
+ let counter = 0;
372
+ for (const entry of entries) {
373
+ counter++;
374
+ const expected = entry.expectedCommitTs ?? -1n;
375
+ if (counter % 50 == 0) await new Promise((resolve) => setImmediate(resolve));
376
+ result.push({
377
+ sql: `DELETE FROM ${table} WHERE id = ? AND commit_ts = ?`,
378
+ params: [entry.id, expected],
379
+ table,
380
+ operation: "deleteSingle",
381
+ entryId: entry.id,
382
+ expectedTs: expected
383
+ });
384
+ }
385
+ }
386
+ async mysqlPrepareCommitLogs(result, writeEntries, commitTs) {
387
+ if (writeEntries.length === 0) return;
388
+ const values = [];
389
+ const tuples = [];
390
+ let counter = 0;
391
+ for (const entry of writeEntries) {
392
+ counter++;
393
+ tuples.push(`(?, ?, ?, ?)`);
394
+ values.push(toBufferView(normalizeIdToBytes(entry.id)), commitTs, toBufferView(entry.tableId), toBufferView(utf8Encode(supaliveStringify(entry))));
395
+ if (counter % 50 == 0) await new Promise((resolve) => setImmediate(resolve));
396
+ }
397
+ result.push({
398
+ sql: `INSERT INTO commit_logs (id, ts, table_id, data) VALUES ${tuples.join(", ")}`,
399
+ params: values,
400
+ table: "commit_logs",
401
+ operation: "commit_logs"
402
+ });
403
+ }
404
+ /**
405
+ * Point-only OCC check. For each genuine point read, compare the row's
406
+ * current commit_ts against the value captured at read time. A `null`
407
+ * expectedCommitTs means "row didn't exist when we read"; any row found
408
+ * now is a conflict. Reads whose row is being written in this same txn
409
+ * are skipped — the CAS UPDATE/DELETE already validated those.
410
+ */
411
+ mysqlPrepareValidatePointReadsByCommitTs(readSet, writeSet) {
412
+ const result = [];
413
+ const writeKeys = /* @__PURE__ */ new Set();
414
+ for (const w of writeSet) writeKeys.add(`${w.table} ${w.id}`);
415
+ const byTable = /* @__PURE__ */ new Map();
416
+ const seen = /* @__PURE__ */ new Set();
417
+ for (const entry of readSet) {
418
+ if (entry.kind !== "point") continue;
419
+ const key = `${entry.table} ${entry.id}`;
420
+ if (writeKeys.has(key) || seen.has(key)) continue;
421
+ seen.add(key);
422
+ if (entry.expectedCommitTs === void 0) continue;
423
+ const bucket = byTable.get(entry.table);
424
+ if (bucket) bucket.push({
425
+ entry,
426
+ key
427
+ });
428
+ else byTable.set(entry.table, [{
429
+ entry,
430
+ key
431
+ }]);
432
+ }
433
+ for (const [table, pendings] of byTable) {
434
+ const ids = pendings.map((p) => p.entry.id);
435
+ const placeholders = ids.map(() => "?").join(", ");
436
+ result.push({
437
+ sql: `SELECT id, commit_ts FROM ${table} WHERE id IN (${placeholders})`,
438
+ params: ids,
439
+ table,
440
+ operation: "pointReadValidation",
441
+ pendingsEntry: pendings
442
+ });
443
+ }
444
+ return result;
445
+ }
446
+ async commitWrites(beginTs, queries, commitTs) {
447
+ await this.mysqlApplyWrites(queries.commits);
448
+ if (!queries.hasRangeRead) {
449
+ if ((queries.validateReadPoints?.length ?? 0) > 0) await this.validatePointReadsByCommitTs(queries.validateReadPoints ?? []);
450
+ return { success: true };
451
+ }
452
+ const logs = await this.getCommitLogsSinceTs(beginTs, commitTs, queries.tableIds ?? []);
453
+ if (checkLogsAffectReadSet(logs, queries.rawReadSet ?? [])) throw new OccConflictError(`Conflict detected: overlapping commit logs since ${beginTs}`, { logs });
454
+ return { success: true };
455
+ }
456
+ async mysqlApplyWrites(result) {
457
+ for (const q of result) switch (q.operation) {
458
+ case "insertBatch":
459
+ try {
460
+ await this.query(q.sql, q.params);
461
+ } catch (err) {
462
+ if (err && typeof err === "object" && (err.errno === 1062 || err.code === "ER_DUP_ENTRY")) {
463
+ const failedId = (err.message ?? "").match(/key '[^']+'.*?\(.*?\)=\(?([^,\)]+)/)?.[1];
464
+ 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);
465
+ }
466
+ throw err;
467
+ }
468
+ break;
469
+ case "updateSingle":
470
+ 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`, {
471
+ table: q.table,
472
+ id: q.entryId,
473
+ expected: q.expectedTs
474
+ });
475
+ break;
476
+ case "deleteSingle":
477
+ 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`, {
478
+ table: q.table,
479
+ id: q.entryId,
480
+ expected: q.expectedTs
481
+ });
482
+ break;
483
+ case "commit_logs":
484
+ await this.query(q.sql, q.params);
485
+ break;
486
+ default: throw new Error("Unhandled MySQL Operation: " + q.operation);
487
+ }
488
+ }
489
+ async validatePointReadsByCommitTs(queries) {
490
+ for (const q of queries) {
491
+ const result = await this.query(q.sql, q.params);
492
+ const currentById = /* @__PURE__ */ new Map();
493
+ for (const row of result.rows) currentById.set(String(row.id), BigInt(row.commit_ts));
494
+ for (const { entry } of q.pendingsEntry ?? []) {
495
+ const current = currentById.get(String(entry.id));
496
+ const expected = entry.expectedCommitTs;
497
+ if (expected === null) {
498
+ if (current !== void 0) throw new OccConflictError(`Conflict: row ${entry.table}/${entry.id} was inserted concurrently`, {
499
+ table: entry.table,
500
+ id: entry.id
501
+ });
502
+ } else {
503
+ if (current === void 0) throw new OccConflictError(`Conflict: row ${entry.table}/${entry.id} was deleted concurrently`, {
504
+ table: entry.table,
505
+ id: entry.id,
506
+ expected
507
+ });
508
+ if (current !== expected) throw new OccConflictError(`Conflict: row ${entry.table}/${entry.id} changed from ts=${expected} to ts=${current}`, {
509
+ table: entry.table,
510
+ id: entry.id,
511
+ expected,
512
+ current
513
+ });
514
+ }
515
+ }
516
+ }
517
+ }
518
+ async pruneCommitLogsBefore(ts) {
519
+ const result = await this.query(`DELETE FROM commit_logs WHERE ts < ?`, [ts]);
520
+ return BigInt(result.rowCount ?? 0);
521
+ }
522
+ async getMinCommitLogTs() {
523
+ const min = (await this.query(`SELECT min(ts) AS min FROM commit_logs`)).rows[0]?.min;
524
+ return min === null || min === void 0 ? null : BigInt(min);
525
+ }
526
+ async getCommitLogsBetweenTs(beginTs, endTs, tableIds) {
527
+ if (tableIds.length === 0) return [];
528
+ const sql = `SELECT id, ts, table_id, data FROM commit_logs WHERE ts >= ? AND ts < ? AND table_id IN (${tableIds.map(() => "?").join(", ")})`;
529
+ return (await this.query(sql, [
530
+ beginTs,
531
+ endTs,
532
+ ...tableIds.map(toBufferView)
533
+ ])).rows.map((row) => ({
534
+ id: normalizeToBytes(row.id),
535
+ ts: BigInt(row.ts),
536
+ tableId: normalizeToBytes(row.table_id),
537
+ data: normalizeToBytes(row.data)
538
+ }));
539
+ }
540
+ async hasCommitForPoints(beginTs, endTs, points) {
541
+ if (points.length === 0) return false;
542
+ const sql = `SELECT 1 FROM commit_logs WHERE ts >= ? AND ts < ? AND (table_id, id) IN (${points.map(() => "(?, ?)").join(", ")}) LIMIT 1`;
543
+ const params = [beginTs, endTs];
544
+ for (const p of points) params.push(toBufferView(p.tableId), toBufferView(p.id));
545
+ return (await this.query(sql, params)).rows.length > 0;
546
+ }
547
+ async getCommitLogsSinceTs(sinceTs, excludeTs, tableIds) {
548
+ if (tableIds.length === 0) return [];
549
+ const sql = `SELECT id, ts, table_id, data FROM commit_logs WHERE ts >= ? AND ts <> ? AND table_id IN (${tableIds.map(() => "?").join(", ")})`;
550
+ return (await this.query(sql, [
551
+ sinceTs,
552
+ excludeTs,
553
+ ...tableIds.map(toBufferView)
554
+ ])).rows.map((row) => ({
555
+ id: normalizeToBytes(row.id),
556
+ ts: BigInt(row.ts),
557
+ tableId: normalizeToBytes(row.table_id),
558
+ data: normalizeToBytes(row.data)
559
+ }));
560
+ }
561
+ async close() {
562
+ await this.pool.end();
563
+ }
564
+ };
565
+ var MySqlTxDatabase = class extends MySqlDatabase {
566
+ constructor(logger, config, pool, client) {
567
+ super(logger, config, pool);
568
+ this.client = client;
569
+ }
570
+ client;
571
+ async query(sql, params = []) {
572
+ try {
573
+ const [rows] = this.queryTimeoutMs > 0 ? await this.client.query({
574
+ sql,
575
+ values: params,
576
+ timeout: this.queryTimeoutMs
577
+ }) : await this.client.query(sql, params);
578
+ return normalizeMysqlResult(rows);
579
+ } catch (err) {
580
+ throw translateMysqlError(err);
581
+ }
582
+ }
583
+ async begin() {
584
+ await this.client.beginTransaction();
585
+ }
586
+ async commit() {
587
+ await this.client.commit();
588
+ }
589
+ async rollback() {
590
+ await this.client.rollback();
591
+ }
592
+ release() {
593
+ this.client.release();
594
+ }
595
+ };
596
+ /**
597
+ * MySQL InnoDB deadlock (errno 1213 / SQLSTATE 40001) is transient and
598
+ * semantically equivalent to an OCC conflict from the mutation runner's
599
+ * perspective: re-execute the handler with a fresh snapshot. Wrapping
600
+ * here lets realtime_db.ts stay driver-agnostic — its retry loop already
601
+ * handles OccConflictError.
602
+ */
603
+ function translateMysqlError(err) {
604
+ if (err && typeof err === "object" && (err.errno === 1213 || err.code === "ER_LOCK_DEADLOCK")) return new OccConflictError("deadlock detected", err);
605
+ return err;
606
+ }
607
+ const mysqlSql = {
608
+ placeholder: (i) => `?`,
609
+ like: (col, i) => `${col} LIKE ?`,
610
+ ilike: (col, i) => `${col} LIKE ?`,
611
+ icontains: (col, i) => `${col} LIKE ?`,
612
+ jsonContains: (col, _i, opts) => opts?.pathIndex !== void 0 ? `JSON_CONTAINS(${col}, CAST(? AS JSON), ?)` : `JSON_CONTAINS(${col}, CAST(? AS JSON))`,
613
+ jsonContainedBy: (col, _i, opts) => opts?.pathIndex !== void 0 ? `JSON_CONTAINS(CAST(? AS JSON), JSON_EXTRACT(${col}, ?))` : `JSON_CONTAINS(CAST(? AS JSON), ${col})`,
614
+ jsonHasKey: (col, _i, opts) => {
615
+ if (opts?.pathCount && opts.pathCount > 0) return `JSON_CONTAINS_PATH(${col}, ${opts.mode === "all" ? "'all'" : "'one'"}, ${new Array(opts.pathCount).fill("?").join(", ")})`;
616
+ return opts?.raw ? `JSON_CONTAINS_PATH(${col}, 'one', ?)` : `JSON_CONTAINS_PATH(${col}, 'one', CONCAT('$."', REPLACE(?, '"', '\\\\"'), '"'))`;
617
+ },
618
+ jsonArrayContains: (col, _i, opts) => opts?.pathIndex !== void 0 ? `JSON_CONTAINS(${col}, JSON_ARRAY(CAST(? AS JSON)), ?)` : `JSON_CONTAINS(${col}, JSON_ARRAY(CAST(? AS JSON)))`
619
+ };
620
+ //#endregion
621
+ export { MySqlDatabase as t };
622
+
623
+ //# sourceMappingURL=mysql-v_0U0NU4.js.map