@atscript/db-mysql 0.1.179 → 0.1.181
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.
- package/dist/index.cjs +108 -71
- package/dist/index.d.cts +8 -2
- package/dist/index.d.mts +8 -2
- package/dist/index.mjs +108 -71
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -811,6 +811,7 @@ function isServerError(error) {
|
|
|
811
811
|
}
|
|
812
812
|
/** Closes `conn` — or, for a driver without `destroy()`, rolls it back (best effort) and releases it. */
|
|
813
813
|
async function discardConnection(conn) {
|
|
814
|
+
dirtySession.delete(conn);
|
|
814
815
|
if (conn.destroy) {
|
|
815
816
|
conn.destroy();
|
|
816
817
|
return;
|
|
@@ -820,6 +821,40 @@ async function discardConnection(conn) {
|
|
|
820
821
|
} catch {}
|
|
821
822
|
conn.release();
|
|
822
823
|
}
|
|
824
|
+
/**
|
|
825
|
+
* Connections whose session state must not reach the pool's next borrower:
|
|
826
|
+
* a setting that could not be put back (see {@link withSessionRestore}), a
|
|
827
|
+
* pending one-shot isolation level. {@link releaseConnection} closes them.
|
|
828
|
+
*/
|
|
829
|
+
const dirtySession = /* @__PURE__ */ new WeakSet();
|
|
830
|
+
/**
|
|
831
|
+
* Runs `fn`, then `restoreSql` on `conn` whether `fn` failed or not; `fn`'s
|
|
832
|
+
* error is the one thrown. A failing restore marks `conn`, so
|
|
833
|
+
* {@link releaseConnection} closes it instead of handing the pool's next
|
|
834
|
+
* borrower a session that skips foreign-key checks or runs another
|
|
835
|
+
* `sql_mode` (since 0.1.180).
|
|
836
|
+
*/
|
|
837
|
+
async function withSessionRestore(conn, restoreSql, fn) {
|
|
838
|
+
let done = false;
|
|
839
|
+
try {
|
|
840
|
+
const result = await fn();
|
|
841
|
+
done = true;
|
|
842
|
+
return result;
|
|
843
|
+
} finally {
|
|
844
|
+
await conn.exec(restoreSql).catch((error) => {
|
|
845
|
+
dirtySession.add(conn);
|
|
846
|
+
if (done) throw error;
|
|
847
|
+
});
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
/**
|
|
851
|
+
* Hands `conn` back to the pool — closed instead when it is in
|
|
852
|
+
* {@link dirtySession} (a driver without `destroy()` can only release it).
|
|
853
|
+
*/
|
|
854
|
+
function releaseConnection(conn) {
|
|
855
|
+
if (dirtySession.delete(conn) && conn.destroy) conn.destroy();
|
|
856
|
+
else conn.release();
|
|
857
|
+
}
|
|
823
858
|
/** `exec` whose statements reject with the retryable `DbError` on contention (any statement can be the deadlock victim). */
|
|
824
859
|
function contentionExec(exec) {
|
|
825
860
|
const contention = (error) => {
|
|
@@ -962,8 +997,8 @@ var MysqlAdapter = class MysqlAdapter extends _atscript_db.BaseDbAdapter {
|
|
|
962
997
|
this._log("START TRANSACTION");
|
|
963
998
|
return conn;
|
|
964
999
|
} catch (err) {
|
|
965
|
-
if (levelPending
|
|
966
|
-
|
|
1000
|
+
if (levelPending) dirtySession.add(conn);
|
|
1001
|
+
releaseConnection(conn);
|
|
967
1002
|
throw err;
|
|
968
1003
|
}
|
|
969
1004
|
}
|
|
@@ -974,11 +1009,11 @@ var MysqlAdapter = class MysqlAdapter extends _atscript_db.BaseDbAdapter {
|
|
|
974
1009
|
await conn.exec("COMMIT");
|
|
975
1010
|
} catch (error) {
|
|
976
1011
|
endedTx.add(conn);
|
|
977
|
-
if (isServerError(error)) conn
|
|
1012
|
+
if (isServerError(error)) releaseConnection(conn);
|
|
978
1013
|
else await discardConnection(conn);
|
|
979
1014
|
throw mapContention(error);
|
|
980
1015
|
}
|
|
981
|
-
conn
|
|
1016
|
+
releaseConnection(conn);
|
|
982
1017
|
}
|
|
983
1018
|
async _rollbackTransaction(state) {
|
|
984
1019
|
const conn = state;
|
|
@@ -987,7 +1022,7 @@ var MysqlAdapter = class MysqlAdapter extends _atscript_db.BaseDbAdapter {
|
|
|
987
1022
|
this._log("ROLLBACK");
|
|
988
1023
|
await conn.exec("ROLLBACK");
|
|
989
1024
|
} finally {
|
|
990
|
-
conn
|
|
1025
|
+
releaseConnection(conn);
|
|
991
1026
|
}
|
|
992
1027
|
}
|
|
993
1028
|
/**
|
|
@@ -1014,15 +1049,11 @@ var MysqlAdapter = class MysqlAdapter extends _atscript_db.BaseDbAdapter {
|
|
|
1014
1049
|
const conn = tx ?? await this.driver.getConnection();
|
|
1015
1050
|
try {
|
|
1016
1051
|
await conn.exec("SET @atscript_sql_mode = @@SESSION.sql_mode, SESSION sql_mode = CONCAT_WS(',', @@SESSION.sql_mode, 'STRICT_ALL_TABLES')");
|
|
1017
|
-
|
|
1018
|
-
return await fn(conn);
|
|
1019
|
-
} finally {
|
|
1020
|
-
await conn.exec("SET SESSION sql_mode = @atscript_sql_mode");
|
|
1021
|
-
}
|
|
1052
|
+
return await withSessionRestore(conn, "SET SESSION sql_mode = @atscript_sql_mode", () => fn(conn));
|
|
1022
1053
|
} catch (error) {
|
|
1023
1054
|
throw mapContention(error);
|
|
1024
1055
|
} finally {
|
|
1025
|
-
if (!tx) conn
|
|
1056
|
+
if (!tx) releaseConnection(conn);
|
|
1026
1057
|
}
|
|
1027
1058
|
}
|
|
1028
1059
|
/**
|
|
@@ -1295,13 +1326,16 @@ var MysqlAdapter = class MysqlAdapter extends _atscript_db.BaseDbAdapter {
|
|
|
1295
1326
|
const result = await this._wrapConstraintError(() => exec.run(sql, params));
|
|
1296
1327
|
return this._groupInsertedIds(group, result.insertId, step);
|
|
1297
1328
|
}
|
|
1298
|
-
/**
|
|
1329
|
+
/**
|
|
1330
|
+
* Runs `fn` on a dedicated pool connection (one session, autocommit),
|
|
1331
|
+
* released after ({@link releaseConnection}).
|
|
1332
|
+
*/
|
|
1299
1333
|
async _onDedicatedConnection(fn) {
|
|
1300
1334
|
const conn = await this.driver.getConnection();
|
|
1301
1335
|
try {
|
|
1302
1336
|
return await fn(conn);
|
|
1303
1337
|
} finally {
|
|
1304
|
-
conn
|
|
1338
|
+
releaseConnection(conn);
|
|
1305
1339
|
}
|
|
1306
1340
|
}
|
|
1307
1341
|
/**
|
|
@@ -2214,13 +2248,14 @@ var MysqlAdapter = class MysqlAdapter extends _atscript_db.BaseDbAdapter {
|
|
|
2214
2248
|
} catch (error) {
|
|
2215
2249
|
failure = error;
|
|
2216
2250
|
}
|
|
2217
|
-
const lost = await this._restoreForeignKeys(conn, dropped);
|
|
2251
|
+
const { lost, restoreError } = await this._restoreForeignKeys(conn, dropped);
|
|
2218
2252
|
if (lost.length > 0) {
|
|
2219
2253
|
const named = lost.map((fk) => `${qi(fk.name)} on ${fk.table} (re-create it with: ${addForeignKeysSql(fk.table, [fk])})`).join("; ");
|
|
2220
2254
|
const message = failure ? `${failure.message} — and foreign keys not restored: ${named}` : `Foreign keys not restored after the type change: ${named}`;
|
|
2221
2255
|
throw new Error(message, { cause: failure });
|
|
2222
2256
|
}
|
|
2223
2257
|
if (failure) throw failure;
|
|
2258
|
+
if (restoreError) throw restoreError;
|
|
2224
2259
|
}
|
|
2225
2260
|
/**
|
|
2226
2261
|
* Re-creates `fks` (dropped by {@link _withForeignKeysLifted}) — one
|
|
@@ -2228,10 +2263,13 @@ var MysqlAdapter = class MysqlAdapter extends _atscript_db.BaseDbAdapter {
|
|
|
2228
2263
|
* so MySQL adds them in place instead of rebuilding the table (the rows
|
|
2229
2264
|
* met them before the change). A table whose statement fails has its
|
|
2230
2265
|
* constraints re-tried one by one. Returns those that could not be
|
|
2231
|
-
* re-created
|
|
2266
|
+
* re-created (`lost`) and the error of a `foreign_key_checks` restore
|
|
2267
|
+
* that failed (`restoreError`; the connection is then closed, not pooled —
|
|
2268
|
+
* see {@link withSessionRestore}). Never throws, so the caller can report
|
|
2269
|
+
* the lost constraints next to its own failure.
|
|
2232
2270
|
*/
|
|
2233
2271
|
async _restoreForeignKeys(conn, fks) {
|
|
2234
|
-
if (fks.length === 0) return [];
|
|
2272
|
+
if (fks.length === 0) return { lost: [] };
|
|
2235
2273
|
const byTable = /* @__PURE__ */ new Map();
|
|
2236
2274
|
for (const fk of fks) {
|
|
2237
2275
|
const group = byTable.get(fk.table);
|
|
@@ -2249,8 +2287,7 @@ var MysqlAdapter = class MysqlAdapter extends _atscript_db.BaseDbAdapter {
|
|
|
2249
2287
|
for (const fk of group) this.logger.info(`[mysql] foreign key ${qi(fk.name)} on ${fk.table} restored`);
|
|
2250
2288
|
};
|
|
2251
2289
|
const lost = [];
|
|
2252
|
-
|
|
2253
|
-
try {
|
|
2290
|
+
const recreate = async () => {
|
|
2254
2291
|
for (const [table, group] of byTable) {
|
|
2255
2292
|
const error = await add(table, group);
|
|
2256
2293
|
if (!error) continue;
|
|
@@ -2262,10 +2299,22 @@ var MysqlAdapter = class MysqlAdapter extends _atscript_db.BaseDbAdapter {
|
|
|
2262
2299
|
}
|
|
2263
2300
|
}
|
|
2264
2301
|
}
|
|
2265
|
-
}
|
|
2266
|
-
|
|
2302
|
+
};
|
|
2303
|
+
try {
|
|
2304
|
+
await conn.exec("SET @atscript_fk_checks = @@SESSION.foreign_key_checks, SESSION foreign_key_checks = 0");
|
|
2305
|
+
} catch {
|
|
2306
|
+
await recreate();
|
|
2307
|
+
return { lost };
|
|
2308
|
+
}
|
|
2309
|
+
try {
|
|
2310
|
+
await withSessionRestore(conn, "SET SESSION foreign_key_checks = @atscript_fk_checks", recreate);
|
|
2311
|
+
} catch (restoreError) {
|
|
2312
|
+
return {
|
|
2313
|
+
lost,
|
|
2314
|
+
restoreError
|
|
2315
|
+
};
|
|
2267
2316
|
}
|
|
2268
|
-
return lost;
|
|
2317
|
+
return { lost };
|
|
2269
2318
|
}
|
|
2270
2319
|
/**
|
|
2271
2320
|
* Whether every constraint of `fks` can be re-created once `fields` have
|
|
@@ -2457,40 +2506,40 @@ var MysqlAdapter = class MysqlAdapter extends _atscript_db.BaseDbAdapter {
|
|
|
2457
2506
|
const tempName = `${this._table.tableName}__tmp_${Date.now()}`;
|
|
2458
2507
|
return this._withStrictSession(async (conn) => {
|
|
2459
2508
|
await conn.exec("SET FOREIGN_KEY_CHECKS = 0");
|
|
2460
|
-
|
|
2461
|
-
|
|
2462
|
-
|
|
2463
|
-
|
|
2464
|
-
|
|
2465
|
-
|
|
2466
|
-
|
|
2467
|
-
|
|
2468
|
-
|
|
2469
|
-
|
|
2470
|
-
|
|
2471
|
-
|
|
2472
|
-
|
|
2473
|
-
const
|
|
2474
|
-
|
|
2475
|
-
|
|
2476
|
-
|
|
2477
|
-
|
|
2478
|
-
|
|
2479
|
-
|
|
2480
|
-
|
|
2481
|
-
|
|
2482
|
-
|
|
2509
|
+
await withSessionRestore(conn, "SET FOREIGN_KEY_CHECKS = 1", async () => {
|
|
2510
|
+
let originalDropped = false;
|
|
2511
|
+
try {
|
|
2512
|
+
const createSql = buildCreateTable(tempName, this._table.fieldDescriptors, this._table.foreignKeys, this._tableOptions());
|
|
2513
|
+
this._log(createSql);
|
|
2514
|
+
await conn.exec(createSql);
|
|
2515
|
+
const oldCols = (await this._readColumns(conn, this._table.tableName)).map((c) => c.name);
|
|
2516
|
+
const newCols = this._table.storedDescriptors.map((f) => f.physicalName);
|
|
2517
|
+
const oldColSet = new Set(oldCols);
|
|
2518
|
+
const commonCols = newCols.filter((c) => oldColSet.has(c));
|
|
2519
|
+
if (commonCols.length > 0) {
|
|
2520
|
+
const fieldsByName = new Map(this._table.fieldDescriptors.map((f) => [f.physicalName, f]));
|
|
2521
|
+
const colNames = commonCols.map((c) => qi(c)).join(", ");
|
|
2522
|
+
const selectExprs = commonCols.map((c) => {
|
|
2523
|
+
const field = fieldsByName.get(c);
|
|
2524
|
+
if (field && !field.optional && !field.isPrimaryKey) {
|
|
2525
|
+
const fallback = field.defaultValue?.kind === "value" ? mysqlValueLiteral(field.designType, field.defaultValue.value) : (0, _atscript_db_sql_tools.defaultValueForType)(field.designType);
|
|
2526
|
+
return `COALESCE(${qi(c)}, ${fallback}) AS ${qi(c)}`;
|
|
2527
|
+
}
|
|
2528
|
+
return qi(c);
|
|
2529
|
+
}).join(", ");
|
|
2530
|
+
const copySql = `INSERT INTO ${qi(tempName)} (${colNames}) SELECT ${selectExprs} FROM ${quoteTableName(tableName)}`;
|
|
2531
|
+
this._log(copySql);
|
|
2532
|
+
await conn.exec(copySql);
|
|
2533
|
+
}
|
|
2534
|
+
await conn.exec(`DROP TABLE IF EXISTS ${quoteTableName(tableName)}`);
|
|
2535
|
+
originalDropped = true;
|
|
2536
|
+
await conn.exec(`RENAME TABLE ${qi(tempName)} TO ${quoteTableName(tableName)}`);
|
|
2537
|
+
} catch (error) {
|
|
2538
|
+
if (originalDropped) throw new Error(`Recreate of "${tableName}" failed after the original table was dropped; its rows are in "${tempName}"`, { cause: error });
|
|
2539
|
+
await conn.exec(`DROP TABLE IF EXISTS ${qi(tempName)}`).catch(() => void 0);
|
|
2540
|
+
throw error;
|
|
2483
2541
|
}
|
|
2484
|
-
|
|
2485
|
-
originalDropped = true;
|
|
2486
|
-
await conn.exec(`RENAME TABLE ${qi(tempName)} TO ${quoteTableName(tableName)}`);
|
|
2487
|
-
} catch (error) {
|
|
2488
|
-
if (originalDropped) throw new Error(`Recreate of "${tableName}" failed after the original table was dropped; its rows are in "${tempName}"`, { cause: error });
|
|
2489
|
-
await conn.exec(`DROP TABLE IF EXISTS ${qi(tempName)}`).catch(() => void 0);
|
|
2490
|
-
throw error;
|
|
2491
|
-
} finally {
|
|
2492
|
-
await conn.exec("SET FOREIGN_KEY_CHECKS = 1");
|
|
2493
|
-
}
|
|
2542
|
+
});
|
|
2494
2543
|
});
|
|
2495
2544
|
}
|
|
2496
2545
|
async dropTable() {
|
|
@@ -2531,26 +2580,14 @@ var MysqlAdapter = class MysqlAdapter extends _atscript_db.BaseDbAdapter {
|
|
|
2531
2580
|
async dropTableByName(tableName) {
|
|
2532
2581
|
const ddl = `DROP TABLE IF EXISTS ${quoteTableName(tableName)}`;
|
|
2533
2582
|
this._log(ddl);
|
|
2534
|
-
const conn = await this.driver.getConnection();
|
|
2535
|
-
const exec = contentionExec(conn);
|
|
2536
|
-
let failed = false;
|
|
2537
|
-
let failure;
|
|
2538
2583
|
try {
|
|
2539
|
-
await
|
|
2540
|
-
|
|
2541
|
-
|
|
2542
|
-
|
|
2543
|
-
failure = error;
|
|
2544
|
-
}
|
|
2545
|
-
try {
|
|
2546
|
-
await exec.exec("SET FOREIGN_KEY_CHECKS = 1");
|
|
2584
|
+
await this._onDedicatedConnection((conn) => withSessionRestore(conn, "SET FOREIGN_KEY_CHECKS = 1", async () => {
|
|
2585
|
+
await conn.exec("SET FOREIGN_KEY_CHECKS = 0");
|
|
2586
|
+
await conn.exec(ddl);
|
|
2587
|
+
}));
|
|
2547
2588
|
} catch (error) {
|
|
2548
|
-
|
|
2549
|
-
else conn.release();
|
|
2550
|
-
throw failed ? failure : error;
|
|
2589
|
+
throw mapContention(error);
|
|
2551
2590
|
}
|
|
2552
|
-
conn.release();
|
|
2553
|
-
if (failed) throw failure;
|
|
2554
2591
|
}
|
|
2555
2592
|
async dropViewByName(viewName) {
|
|
2556
2593
|
const ddl = `DROP VIEW IF EXISTS ${quoteTableName(viewName)}`;
|
package/dist/index.d.cts
CHANGED
|
@@ -258,7 +258,10 @@ declare class MysqlAdapter extends BaseDbAdapter {
|
|
|
258
258
|
insertMany(data: Array<Record<string, unknown>>): Promise<TDbInsertManyResult>;
|
|
259
259
|
/** ONE multi-row INSERT of a homogeneous id group on `exec`; the rows' ids in group order. */
|
|
260
260
|
private _insertGroup;
|
|
261
|
-
/**
|
|
261
|
+
/**
|
|
262
|
+
* Runs `fn` on a dedicated pool connection (one session, autocommit),
|
|
263
|
+
* released after ({@link releaseConnection}).
|
|
264
|
+
*/
|
|
262
265
|
private _onDedicatedConnection;
|
|
263
266
|
/**
|
|
264
267
|
* `rows` as ONE {@link _idGroups} group when that needs no session read:
|
|
@@ -508,7 +511,10 @@ declare class MysqlAdapter extends BaseDbAdapter {
|
|
|
508
511
|
* so MySQL adds them in place instead of rebuilding the table (the rows
|
|
509
512
|
* met them before the change). A table whose statement fails has its
|
|
510
513
|
* constraints re-tried one by one. Returns those that could not be
|
|
511
|
-
* re-created
|
|
514
|
+
* re-created (`lost`) and the error of a `foreign_key_checks` restore
|
|
515
|
+
* that failed (`restoreError`; the connection is then closed, not pooled —
|
|
516
|
+
* see {@link withSessionRestore}). Never throws, so the caller can report
|
|
517
|
+
* the lost constraints next to its own failure.
|
|
512
518
|
*/
|
|
513
519
|
private _restoreForeignKeys;
|
|
514
520
|
/**
|
package/dist/index.d.mts
CHANGED
|
@@ -258,7 +258,10 @@ declare class MysqlAdapter extends BaseDbAdapter {
|
|
|
258
258
|
insertMany(data: Array<Record<string, unknown>>): Promise<TDbInsertManyResult>;
|
|
259
259
|
/** ONE multi-row INSERT of a homogeneous id group on `exec`; the rows' ids in group order. */
|
|
260
260
|
private _insertGroup;
|
|
261
|
-
/**
|
|
261
|
+
/**
|
|
262
|
+
* Runs `fn` on a dedicated pool connection (one session, autocommit),
|
|
263
|
+
* released after ({@link releaseConnection}).
|
|
264
|
+
*/
|
|
262
265
|
private _onDedicatedConnection;
|
|
263
266
|
/**
|
|
264
267
|
* `rows` as ONE {@link _idGroups} group when that needs no session read:
|
|
@@ -508,7 +511,10 @@ declare class MysqlAdapter extends BaseDbAdapter {
|
|
|
508
511
|
* so MySQL adds them in place instead of rebuilding the table (the rows
|
|
509
512
|
* met them before the change). A table whose statement fails has its
|
|
510
513
|
* constraints re-tried one by one. Returns those that could not be
|
|
511
|
-
* re-created
|
|
514
|
+
* re-created (`lost`) and the error of a `foreign_key_checks` restore
|
|
515
|
+
* that failed (`restoreError`; the connection is then closed, not pooled —
|
|
516
|
+
* see {@link withSessionRestore}). Never throws, so the caller can report
|
|
517
|
+
* the lost constraints next to its own failure.
|
|
512
518
|
*/
|
|
513
519
|
private _restoreForeignKeys;
|
|
514
520
|
/**
|
package/dist/index.mjs
CHANGED
|
@@ -810,6 +810,7 @@ function isServerError(error) {
|
|
|
810
810
|
}
|
|
811
811
|
/** Closes `conn` — or, for a driver without `destroy()`, rolls it back (best effort) and releases it. */
|
|
812
812
|
async function discardConnection(conn) {
|
|
813
|
+
dirtySession.delete(conn);
|
|
813
814
|
if (conn.destroy) {
|
|
814
815
|
conn.destroy();
|
|
815
816
|
return;
|
|
@@ -819,6 +820,40 @@ async function discardConnection(conn) {
|
|
|
819
820
|
} catch {}
|
|
820
821
|
conn.release();
|
|
821
822
|
}
|
|
823
|
+
/**
|
|
824
|
+
* Connections whose session state must not reach the pool's next borrower:
|
|
825
|
+
* a setting that could not be put back (see {@link withSessionRestore}), a
|
|
826
|
+
* pending one-shot isolation level. {@link releaseConnection} closes them.
|
|
827
|
+
*/
|
|
828
|
+
const dirtySession = /* @__PURE__ */ new WeakSet();
|
|
829
|
+
/**
|
|
830
|
+
* Runs `fn`, then `restoreSql` on `conn` whether `fn` failed or not; `fn`'s
|
|
831
|
+
* error is the one thrown. A failing restore marks `conn`, so
|
|
832
|
+
* {@link releaseConnection} closes it instead of handing the pool's next
|
|
833
|
+
* borrower a session that skips foreign-key checks or runs another
|
|
834
|
+
* `sql_mode` (since 0.1.180).
|
|
835
|
+
*/
|
|
836
|
+
async function withSessionRestore(conn, restoreSql, fn) {
|
|
837
|
+
let done = false;
|
|
838
|
+
try {
|
|
839
|
+
const result = await fn();
|
|
840
|
+
done = true;
|
|
841
|
+
return result;
|
|
842
|
+
} finally {
|
|
843
|
+
await conn.exec(restoreSql).catch((error) => {
|
|
844
|
+
dirtySession.add(conn);
|
|
845
|
+
if (done) throw error;
|
|
846
|
+
});
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
/**
|
|
850
|
+
* Hands `conn` back to the pool — closed instead when it is in
|
|
851
|
+
* {@link dirtySession} (a driver without `destroy()` can only release it).
|
|
852
|
+
*/
|
|
853
|
+
function releaseConnection(conn) {
|
|
854
|
+
if (dirtySession.delete(conn) && conn.destroy) conn.destroy();
|
|
855
|
+
else conn.release();
|
|
856
|
+
}
|
|
822
857
|
/** `exec` whose statements reject with the retryable `DbError` on contention (any statement can be the deadlock victim). */
|
|
823
858
|
function contentionExec(exec) {
|
|
824
859
|
const contention = (error) => {
|
|
@@ -961,8 +996,8 @@ var MysqlAdapter = class MysqlAdapter extends BaseDbAdapter {
|
|
|
961
996
|
this._log("START TRANSACTION");
|
|
962
997
|
return conn;
|
|
963
998
|
} catch (err) {
|
|
964
|
-
if (levelPending
|
|
965
|
-
|
|
999
|
+
if (levelPending) dirtySession.add(conn);
|
|
1000
|
+
releaseConnection(conn);
|
|
966
1001
|
throw err;
|
|
967
1002
|
}
|
|
968
1003
|
}
|
|
@@ -973,11 +1008,11 @@ var MysqlAdapter = class MysqlAdapter extends BaseDbAdapter {
|
|
|
973
1008
|
await conn.exec("COMMIT");
|
|
974
1009
|
} catch (error) {
|
|
975
1010
|
endedTx.add(conn);
|
|
976
|
-
if (isServerError(error)) conn
|
|
1011
|
+
if (isServerError(error)) releaseConnection(conn);
|
|
977
1012
|
else await discardConnection(conn);
|
|
978
1013
|
throw mapContention(error);
|
|
979
1014
|
}
|
|
980
|
-
conn
|
|
1015
|
+
releaseConnection(conn);
|
|
981
1016
|
}
|
|
982
1017
|
async _rollbackTransaction(state) {
|
|
983
1018
|
const conn = state;
|
|
@@ -986,7 +1021,7 @@ var MysqlAdapter = class MysqlAdapter extends BaseDbAdapter {
|
|
|
986
1021
|
this._log("ROLLBACK");
|
|
987
1022
|
await conn.exec("ROLLBACK");
|
|
988
1023
|
} finally {
|
|
989
|
-
conn
|
|
1024
|
+
releaseConnection(conn);
|
|
990
1025
|
}
|
|
991
1026
|
}
|
|
992
1027
|
/**
|
|
@@ -1013,15 +1048,11 @@ var MysqlAdapter = class MysqlAdapter extends BaseDbAdapter {
|
|
|
1013
1048
|
const conn = tx ?? await this.driver.getConnection();
|
|
1014
1049
|
try {
|
|
1015
1050
|
await conn.exec("SET @atscript_sql_mode = @@SESSION.sql_mode, SESSION sql_mode = CONCAT_WS(',', @@SESSION.sql_mode, 'STRICT_ALL_TABLES')");
|
|
1016
|
-
|
|
1017
|
-
return await fn(conn);
|
|
1018
|
-
} finally {
|
|
1019
|
-
await conn.exec("SET SESSION sql_mode = @atscript_sql_mode");
|
|
1020
|
-
}
|
|
1051
|
+
return await withSessionRestore(conn, "SET SESSION sql_mode = @atscript_sql_mode", () => fn(conn));
|
|
1021
1052
|
} catch (error) {
|
|
1022
1053
|
throw mapContention(error);
|
|
1023
1054
|
} finally {
|
|
1024
|
-
if (!tx) conn
|
|
1055
|
+
if (!tx) releaseConnection(conn);
|
|
1025
1056
|
}
|
|
1026
1057
|
}
|
|
1027
1058
|
/**
|
|
@@ -1294,13 +1325,16 @@ var MysqlAdapter = class MysqlAdapter extends BaseDbAdapter {
|
|
|
1294
1325
|
const result = await this._wrapConstraintError(() => exec.run(sql, params));
|
|
1295
1326
|
return this._groupInsertedIds(group, result.insertId, step);
|
|
1296
1327
|
}
|
|
1297
|
-
/**
|
|
1328
|
+
/**
|
|
1329
|
+
* Runs `fn` on a dedicated pool connection (one session, autocommit),
|
|
1330
|
+
* released after ({@link releaseConnection}).
|
|
1331
|
+
*/
|
|
1298
1332
|
async _onDedicatedConnection(fn) {
|
|
1299
1333
|
const conn = await this.driver.getConnection();
|
|
1300
1334
|
try {
|
|
1301
1335
|
return await fn(conn);
|
|
1302
1336
|
} finally {
|
|
1303
|
-
conn
|
|
1337
|
+
releaseConnection(conn);
|
|
1304
1338
|
}
|
|
1305
1339
|
}
|
|
1306
1340
|
/**
|
|
@@ -2213,13 +2247,14 @@ var MysqlAdapter = class MysqlAdapter extends BaseDbAdapter {
|
|
|
2213
2247
|
} catch (error) {
|
|
2214
2248
|
failure = error;
|
|
2215
2249
|
}
|
|
2216
|
-
const lost = await this._restoreForeignKeys(conn, dropped);
|
|
2250
|
+
const { lost, restoreError } = await this._restoreForeignKeys(conn, dropped);
|
|
2217
2251
|
if (lost.length > 0) {
|
|
2218
2252
|
const named = lost.map((fk) => `${qi(fk.name)} on ${fk.table} (re-create it with: ${addForeignKeysSql(fk.table, [fk])})`).join("; ");
|
|
2219
2253
|
const message = failure ? `${failure.message} — and foreign keys not restored: ${named}` : `Foreign keys not restored after the type change: ${named}`;
|
|
2220
2254
|
throw new Error(message, { cause: failure });
|
|
2221
2255
|
}
|
|
2222
2256
|
if (failure) throw failure;
|
|
2257
|
+
if (restoreError) throw restoreError;
|
|
2223
2258
|
}
|
|
2224
2259
|
/**
|
|
2225
2260
|
* Re-creates `fks` (dropped by {@link _withForeignKeysLifted}) — one
|
|
@@ -2227,10 +2262,13 @@ var MysqlAdapter = class MysqlAdapter extends BaseDbAdapter {
|
|
|
2227
2262
|
* so MySQL adds them in place instead of rebuilding the table (the rows
|
|
2228
2263
|
* met them before the change). A table whose statement fails has its
|
|
2229
2264
|
* constraints re-tried one by one. Returns those that could not be
|
|
2230
|
-
* re-created
|
|
2265
|
+
* re-created (`lost`) and the error of a `foreign_key_checks` restore
|
|
2266
|
+
* that failed (`restoreError`; the connection is then closed, not pooled —
|
|
2267
|
+
* see {@link withSessionRestore}). Never throws, so the caller can report
|
|
2268
|
+
* the lost constraints next to its own failure.
|
|
2231
2269
|
*/
|
|
2232
2270
|
async _restoreForeignKeys(conn, fks) {
|
|
2233
|
-
if (fks.length === 0) return [];
|
|
2271
|
+
if (fks.length === 0) return { lost: [] };
|
|
2234
2272
|
const byTable = /* @__PURE__ */ new Map();
|
|
2235
2273
|
for (const fk of fks) {
|
|
2236
2274
|
const group = byTable.get(fk.table);
|
|
@@ -2248,8 +2286,7 @@ var MysqlAdapter = class MysqlAdapter extends BaseDbAdapter {
|
|
|
2248
2286
|
for (const fk of group) this.logger.info(`[mysql] foreign key ${qi(fk.name)} on ${fk.table} restored`);
|
|
2249
2287
|
};
|
|
2250
2288
|
const lost = [];
|
|
2251
|
-
|
|
2252
|
-
try {
|
|
2289
|
+
const recreate = async () => {
|
|
2253
2290
|
for (const [table, group] of byTable) {
|
|
2254
2291
|
const error = await add(table, group);
|
|
2255
2292
|
if (!error) continue;
|
|
@@ -2261,10 +2298,22 @@ var MysqlAdapter = class MysqlAdapter extends BaseDbAdapter {
|
|
|
2261
2298
|
}
|
|
2262
2299
|
}
|
|
2263
2300
|
}
|
|
2264
|
-
}
|
|
2265
|
-
|
|
2301
|
+
};
|
|
2302
|
+
try {
|
|
2303
|
+
await conn.exec("SET @atscript_fk_checks = @@SESSION.foreign_key_checks, SESSION foreign_key_checks = 0");
|
|
2304
|
+
} catch {
|
|
2305
|
+
await recreate();
|
|
2306
|
+
return { lost };
|
|
2307
|
+
}
|
|
2308
|
+
try {
|
|
2309
|
+
await withSessionRestore(conn, "SET SESSION foreign_key_checks = @atscript_fk_checks", recreate);
|
|
2310
|
+
} catch (restoreError) {
|
|
2311
|
+
return {
|
|
2312
|
+
lost,
|
|
2313
|
+
restoreError
|
|
2314
|
+
};
|
|
2266
2315
|
}
|
|
2267
|
-
return lost;
|
|
2316
|
+
return { lost };
|
|
2268
2317
|
}
|
|
2269
2318
|
/**
|
|
2270
2319
|
* Whether every constraint of `fks` can be re-created once `fields` have
|
|
@@ -2456,40 +2505,40 @@ var MysqlAdapter = class MysqlAdapter extends BaseDbAdapter {
|
|
|
2456
2505
|
const tempName = `${this._table.tableName}__tmp_${Date.now()}`;
|
|
2457
2506
|
return this._withStrictSession(async (conn) => {
|
|
2458
2507
|
await conn.exec("SET FOREIGN_KEY_CHECKS = 0");
|
|
2459
|
-
|
|
2460
|
-
|
|
2461
|
-
|
|
2462
|
-
|
|
2463
|
-
|
|
2464
|
-
|
|
2465
|
-
|
|
2466
|
-
|
|
2467
|
-
|
|
2468
|
-
|
|
2469
|
-
|
|
2470
|
-
|
|
2471
|
-
|
|
2472
|
-
const
|
|
2473
|
-
|
|
2474
|
-
|
|
2475
|
-
|
|
2476
|
-
|
|
2477
|
-
|
|
2478
|
-
|
|
2479
|
-
|
|
2480
|
-
|
|
2481
|
-
|
|
2508
|
+
await withSessionRestore(conn, "SET FOREIGN_KEY_CHECKS = 1", async () => {
|
|
2509
|
+
let originalDropped = false;
|
|
2510
|
+
try {
|
|
2511
|
+
const createSql = buildCreateTable(tempName, this._table.fieldDescriptors, this._table.foreignKeys, this._tableOptions());
|
|
2512
|
+
this._log(createSql);
|
|
2513
|
+
await conn.exec(createSql);
|
|
2514
|
+
const oldCols = (await this._readColumns(conn, this._table.tableName)).map((c) => c.name);
|
|
2515
|
+
const newCols = this._table.storedDescriptors.map((f) => f.physicalName);
|
|
2516
|
+
const oldColSet = new Set(oldCols);
|
|
2517
|
+
const commonCols = newCols.filter((c) => oldColSet.has(c));
|
|
2518
|
+
if (commonCols.length > 0) {
|
|
2519
|
+
const fieldsByName = new Map(this._table.fieldDescriptors.map((f) => [f.physicalName, f]));
|
|
2520
|
+
const colNames = commonCols.map((c) => qi(c)).join(", ");
|
|
2521
|
+
const selectExprs = commonCols.map((c) => {
|
|
2522
|
+
const field = fieldsByName.get(c);
|
|
2523
|
+
if (field && !field.optional && !field.isPrimaryKey) {
|
|
2524
|
+
const fallback = field.defaultValue?.kind === "value" ? mysqlValueLiteral(field.designType, field.defaultValue.value) : defaultValueForType(field.designType);
|
|
2525
|
+
return `COALESCE(${qi(c)}, ${fallback}) AS ${qi(c)}`;
|
|
2526
|
+
}
|
|
2527
|
+
return qi(c);
|
|
2528
|
+
}).join(", ");
|
|
2529
|
+
const copySql = `INSERT INTO ${qi(tempName)} (${colNames}) SELECT ${selectExprs} FROM ${quoteTableName(tableName)}`;
|
|
2530
|
+
this._log(copySql);
|
|
2531
|
+
await conn.exec(copySql);
|
|
2532
|
+
}
|
|
2533
|
+
await conn.exec(`DROP TABLE IF EXISTS ${quoteTableName(tableName)}`);
|
|
2534
|
+
originalDropped = true;
|
|
2535
|
+
await conn.exec(`RENAME TABLE ${qi(tempName)} TO ${quoteTableName(tableName)}`);
|
|
2536
|
+
} catch (error) {
|
|
2537
|
+
if (originalDropped) throw new Error(`Recreate of "${tableName}" failed after the original table was dropped; its rows are in "${tempName}"`, { cause: error });
|
|
2538
|
+
await conn.exec(`DROP TABLE IF EXISTS ${qi(tempName)}`).catch(() => void 0);
|
|
2539
|
+
throw error;
|
|
2482
2540
|
}
|
|
2483
|
-
|
|
2484
|
-
originalDropped = true;
|
|
2485
|
-
await conn.exec(`RENAME TABLE ${qi(tempName)} TO ${quoteTableName(tableName)}`);
|
|
2486
|
-
} catch (error) {
|
|
2487
|
-
if (originalDropped) throw new Error(`Recreate of "${tableName}" failed after the original table was dropped; its rows are in "${tempName}"`, { cause: error });
|
|
2488
|
-
await conn.exec(`DROP TABLE IF EXISTS ${qi(tempName)}`).catch(() => void 0);
|
|
2489
|
-
throw error;
|
|
2490
|
-
} finally {
|
|
2491
|
-
await conn.exec("SET FOREIGN_KEY_CHECKS = 1");
|
|
2492
|
-
}
|
|
2541
|
+
});
|
|
2493
2542
|
});
|
|
2494
2543
|
}
|
|
2495
2544
|
async dropTable() {
|
|
@@ -2530,26 +2579,14 @@ var MysqlAdapter = class MysqlAdapter extends BaseDbAdapter {
|
|
|
2530
2579
|
async dropTableByName(tableName) {
|
|
2531
2580
|
const ddl = `DROP TABLE IF EXISTS ${quoteTableName(tableName)}`;
|
|
2532
2581
|
this._log(ddl);
|
|
2533
|
-
const conn = await this.driver.getConnection();
|
|
2534
|
-
const exec = contentionExec(conn);
|
|
2535
|
-
let failed = false;
|
|
2536
|
-
let failure;
|
|
2537
2582
|
try {
|
|
2538
|
-
await
|
|
2539
|
-
|
|
2540
|
-
|
|
2541
|
-
|
|
2542
|
-
failure = error;
|
|
2543
|
-
}
|
|
2544
|
-
try {
|
|
2545
|
-
await exec.exec("SET FOREIGN_KEY_CHECKS = 1");
|
|
2583
|
+
await this._onDedicatedConnection((conn) => withSessionRestore(conn, "SET FOREIGN_KEY_CHECKS = 1", async () => {
|
|
2584
|
+
await conn.exec("SET FOREIGN_KEY_CHECKS = 0");
|
|
2585
|
+
await conn.exec(ddl);
|
|
2586
|
+
}));
|
|
2546
2587
|
} catch (error) {
|
|
2547
|
-
|
|
2548
|
-
else conn.release();
|
|
2549
|
-
throw failed ? failure : error;
|
|
2588
|
+
throw mapContention(error);
|
|
2550
2589
|
}
|
|
2551
|
-
conn.release();
|
|
2552
|
-
if (failed) throw failure;
|
|
2553
2590
|
}
|
|
2554
2591
|
async dropViewByName(viewName) {
|
|
2555
2592
|
const ddl = `DROP VIEW IF EXISTS ${quoteTableName(viewName)}`;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@atscript/db-mysql",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.181",
|
|
4
4
|
"description": "MySQL adapter for @atscript/db with mysql2 driver support.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"atscript",
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
"access": "public"
|
|
42
42
|
},
|
|
43
43
|
"dependencies": {
|
|
44
|
-
"@atscript/db-sql-tools": "^0.1.
|
|
44
|
+
"@atscript/db-sql-tools": "^0.1.181"
|
|
45
45
|
},
|
|
46
46
|
"devDependencies": {
|
|
47
47
|
"@atscript/core": "^0.2.12",
|
|
@@ -55,7 +55,7 @@
|
|
|
55
55
|
"@atscript/typescript": "^0.2.12",
|
|
56
56
|
"@uniqu/core": "^0.2.2",
|
|
57
57
|
"mysql2": ">=3.0.0",
|
|
58
|
-
"@atscript/db": "^0.1.
|
|
58
|
+
"@atscript/db": "^0.1.181"
|
|
59
59
|
},
|
|
60
60
|
"peerDependenciesMeta": {
|
|
61
61
|
"mysql2": {
|