@atscript/db-mysql 0.1.174 → 0.1.175

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 CHANGED
@@ -771,6 +771,64 @@ const nonStrictChecked = /* @__PURE__ */ new WeakSet();
771
771
  * loading the time zone tables fixes a running server without a restart.
772
772
  */
773
773
  const convertibleZones = /* @__PURE__ */ new WeakMap();
774
+ /** Connections whose COMMIT failed: the transaction is over, no ROLLBACK may follow. */
775
+ const endedTx = /* @__PURE__ */ new WeakSet();
776
+ /**
777
+ * ER_LOCK_DEADLOCK rolled the whole transaction back; ER_LOCK_WAIT_TIMEOUT /
778
+ * ER_LOCK_NOWAIT (3572, a `NOWAIT` locking read) failed the statement.
779
+ */
780
+ const MYSQL_CONTENTION_CODES = {
781
+ 1213: "DEADLOCK",
782
+ 1205: "LOCK_TIMEOUT",
783
+ 3572: "LOCK_TIMEOUT"
784
+ };
785
+ /**
786
+ * `error` as the retryable `DbError` of its contention errno (deadlock,
787
+ * lock wait timeout, `NOWAIT` lock refusal), else `error` as is; the driver
788
+ * error is kept as `cause`. Applied to every statement and to COMMIT.
789
+ */
790
+ function mapContention(error) {
791
+ if (!error || typeof error !== "object") return error;
792
+ const err = error;
793
+ const code = typeof err.errno === "number" ? MYSQL_CONTENTION_CODES[err.errno] : void 0;
794
+ if (!code) return error;
795
+ return new _atscript_db.DbError(code, [{
796
+ path: "",
797
+ message: err.sqlMessage ?? err.message
798
+ }], void 0, { cause: error });
799
+ }
800
+ /**
801
+ * Whether the server reported `error` (a positive `errno`), as opposed to a
802
+ * client-side failure — a timeout, a lost socket — after which the server's
803
+ * transaction state is unknown.
804
+ */
805
+ function isServerError(error) {
806
+ const errno = error && typeof error === "object" ? error.errno : void 0;
807
+ return typeof errno === "number" && errno > 0;
808
+ }
809
+ /** Closes `conn` — or, for a driver without `destroy()`, rolls it back (best effort) and releases it. */
810
+ async function discardConnection(conn) {
811
+ if (conn.destroy) {
812
+ conn.destroy();
813
+ return;
814
+ }
815
+ try {
816
+ await conn.exec("ROLLBACK");
817
+ } catch {}
818
+ conn.release();
819
+ }
820
+ /** `exec` whose statements reject with the retryable `DbError` on contention (any statement can be the deadlock victim). */
821
+ function contentionExec(exec) {
822
+ const contention = (error) => {
823
+ throw mapContention(error);
824
+ };
825
+ return {
826
+ run: (sql, params) => exec.run(sql, params).catch(contention),
827
+ all: (sql, params) => exec.all(sql, params).catch(contention),
828
+ get: (sql, params) => exec.get(sql, params).catch(contention),
829
+ exec: (sql) => exec.exec(sql).catch(contention)
830
+ };
831
+ }
774
832
  /** The `ALTER TABLE` that re-creates `fks`, all on `table`, as they were. */
775
833
  function addForeignKeysSql(table, fks) {
776
834
  return `ALTER TABLE ${table} ${fks.map((fk) => `ADD CONSTRAINT ${qi(fk.name)} FOREIGN KEY (${fk.columns.map(qi).join(", ")}) REFERENCES ${fk.refTable} (${fk.refColumns.map(qi).join(", ")}) ON DELETE ${fk.onDelete} ON UPDATE ${fk.onUpdate}`).join(", ")}`;
@@ -840,6 +898,8 @@ var MysqlAdapter = class MysqlAdapter extends _atscript_db.BaseDbAdapter {
840
898
  /** Field path → `@db.mysql.charset` of the column. */
841
899
  _charsetFields = /* @__PURE__ */ new Map();
842
900
  _space;
901
+ _poolExec;
902
+ _txExecs = /* @__PURE__ */ new WeakMap();
843
903
  /** Memo of {@link _keyTableCharsets} — it also makes its warning fire once. */
844
904
  _keyTableCharsetsMemo;
845
905
  /** Whether the connected MySQL instance supports native VECTOR type (MySQL 9.0+). */
@@ -909,12 +969,17 @@ var MysqlAdapter = class MysqlAdapter extends _atscript_db.BaseDbAdapter {
909
969
  try {
910
970
  this._log("COMMIT");
911
971
  await conn.exec("COMMIT");
912
- } finally {
913
- conn.release();
972
+ } catch (error) {
973
+ endedTx.add(conn);
974
+ if (isServerError(error)) conn.release();
975
+ else await discardConnection(conn);
976
+ throw mapContention(error);
914
977
  }
978
+ conn.release();
915
979
  }
916
980
  async _rollbackTransaction(state) {
917
981
  const conn = state;
982
+ if (endedTx.delete(conn)) return;
918
983
  try {
919
984
  this._log("ROLLBACK");
920
985
  await conn.exec("ROLLBACK");
@@ -927,7 +992,11 @@ var MysqlAdapter = class MysqlAdapter extends _atscript_db.BaseDbAdapter {
927
992
  * otherwise the pool-based driver.
928
993
  */
929
994
  _exec() {
930
- return this._txConnection() ?? this.driver;
995
+ const conn = this._txConnection();
996
+ if (!conn) return this._poolExec ??= contentionExec(this.driver);
997
+ let exec = this._txExecs.get(conn);
998
+ if (!exec) this._txExecs.set(conn, exec = contentionExec(conn));
999
+ return exec;
931
1000
  }
932
1001
  /**
933
1002
  * Runs `fn` on one connection (the transaction's, or a dedicated one) with
@@ -1168,10 +1237,7 @@ var MysqlAdapter = class MysqlAdapter extends _atscript_db.BaseDbAdapter {
1168
1237
  const columns = (message.match(/FOREIGN KEY \(([^)]+)\)/)?.[1])?.split(",").map((c) => c.trim().replace(/^`|`$/g, ""));
1169
1238
  throw (0, _atscript_db.constraintViolation)("FK_VIOLATION", err.errno === 1451 ? { referencedBy: referencing } : { columns }, message);
1170
1239
  }
1171
- if (err.errno === 1213 || err.errno === 1205 || err.errno === 3572) throw new _atscript_db.DbError(err.errno === 1213 ? "DEADLOCK" : "LOCK_TIMEOUT", [{
1172
- path: "",
1173
- message: err.sqlMessage ?? err.message
1174
- }]);
1240
+ throw mapContention(error);
1175
1241
  }
1176
1242
  throw error;
1177
1243
  }
@@ -2691,7 +2757,8 @@ var MysqlAdapter = class MysqlAdapter extends _atscript_db.BaseDbAdapter {
2691
2757
  * The search predicate (AND the request filter) and its relevance order
2692
2758
  * (`rank`, since 0.1.165) — used as the ORDER BY when the read has no
2693
2759
  * `$sort`: exact-number hits first, then `MATCH … AGAINST` relevance, then
2694
- * the primary key. Grouped searches use only the predicate.
2760
+ * the primary key; the primary key alone under `$rank: false`. Grouped
2761
+ * searches use only the predicate.
2695
2762
  */
2696
2763
  _buildSearchWhere(text, query, indexName) {
2697
2764
  const fulltextIndex = this._getFulltextIndex(indexName);
@@ -2703,10 +2770,11 @@ var MysqlAdapter = class MysqlAdapter extends _atscript_db.BaseDbAdapter {
2703
2770
  const all = fulltextIndex.match === "all";
2704
2771
  const matchClause = `MATCH(${matchCols}) AGAINST(? IN ${all ? "BOOLEAN" : "NATURAL LANGUAGE"} MODE)`;
2705
2772
  const term = all ? mysqlRequireEveryTerm(text) : text;
2773
+ const ranked = textFields.length > 0 && query.controls?.$rank !== false;
2706
2774
  const rank = (0, _atscript_db_sql_tools.searchRankOrder)(mysqlDialect, {
2707
2775
  exactEqualities: n === void 0 ? [] : integerFields.map((f) => `${qi(f.name)} = ?`),
2708
2776
  n,
2709
- textRank: textFields.length > 0 ? {
2777
+ textRank: ranked ? {
2710
2778
  sql: `${matchClause} DESC`,
2711
2779
  params: [term]
2712
2780
  } : void 0,
package/dist/index.d.cts CHANGED
@@ -136,6 +136,8 @@ declare class MysqlAdapter extends BaseDbAdapter {
136
136
  /** Field path → `@db.mysql.charset` of the column. */
137
137
  private _charsetFields;
138
138
  private _space?;
139
+ private _poolExec?;
140
+ private _txExecs;
139
141
  /** Memo of {@link _keyTableCharsets} — it also makes its warning fire once. */
140
142
  private _keyTableCharsetsMemo?;
141
143
  /** Whether the connected MySQL instance supports native VECTOR type (MySQL 9.0+). */
@@ -581,7 +583,8 @@ declare class MysqlAdapter extends BaseDbAdapter {
581
583
  * The search predicate (AND the request filter) and its relevance order
582
584
  * (`rank`, since 0.1.165) — used as the ORDER BY when the read has no
583
585
  * `$sort`: exact-number hits first, then `MATCH … AGAINST` relevance, then
584
- * the primary key. Grouped searches use only the predicate.
586
+ * the primary key; the primary key alone under `$rank: false`. Grouped
587
+ * searches use only the predicate.
585
588
  */
586
589
  private _buildSearchWhere;
587
590
  private _getFulltextIndex;
package/dist/index.d.mts CHANGED
@@ -136,6 +136,8 @@ declare class MysqlAdapter extends BaseDbAdapter {
136
136
  /** Field path → `@db.mysql.charset` of the column. */
137
137
  private _charsetFields;
138
138
  private _space?;
139
+ private _poolExec?;
140
+ private _txExecs;
139
141
  /** Memo of {@link _keyTableCharsets} — it also makes its warning fire once. */
140
142
  private _keyTableCharsetsMemo?;
141
143
  /** Whether the connected MySQL instance supports native VECTOR type (MySQL 9.0+). */
@@ -581,7 +583,8 @@ declare class MysqlAdapter extends BaseDbAdapter {
581
583
  * The search predicate (AND the request filter) and its relevance order
582
584
  * (`rank`, since 0.1.165) — used as the ORDER BY when the read has no
583
585
  * `$sort`: exact-number hits first, then `MATCH … AGAINST` relevance, then
584
- * the primary key. Grouped searches use only the predicate.
586
+ * the primary key; the primary key alone under `$rank: false`. Grouped
587
+ * searches use only the predicate.
585
588
  */
586
589
  private _buildSearchWhere;
587
590
  private _getFulltextIndex;
package/dist/index.mjs CHANGED
@@ -770,6 +770,64 @@ const nonStrictChecked = /* @__PURE__ */ new WeakSet();
770
770
  * loading the time zone tables fixes a running server without a restart.
771
771
  */
772
772
  const convertibleZones = /* @__PURE__ */ new WeakMap();
773
+ /** Connections whose COMMIT failed: the transaction is over, no ROLLBACK may follow. */
774
+ const endedTx = /* @__PURE__ */ new WeakSet();
775
+ /**
776
+ * ER_LOCK_DEADLOCK rolled the whole transaction back; ER_LOCK_WAIT_TIMEOUT /
777
+ * ER_LOCK_NOWAIT (3572, a `NOWAIT` locking read) failed the statement.
778
+ */
779
+ const MYSQL_CONTENTION_CODES = {
780
+ 1213: "DEADLOCK",
781
+ 1205: "LOCK_TIMEOUT",
782
+ 3572: "LOCK_TIMEOUT"
783
+ };
784
+ /**
785
+ * `error` as the retryable `DbError` of its contention errno (deadlock,
786
+ * lock wait timeout, `NOWAIT` lock refusal), else `error` as is; the driver
787
+ * error is kept as `cause`. Applied to every statement and to COMMIT.
788
+ */
789
+ function mapContention(error) {
790
+ if (!error || typeof error !== "object") return error;
791
+ const err = error;
792
+ const code = typeof err.errno === "number" ? MYSQL_CONTENTION_CODES[err.errno] : void 0;
793
+ if (!code) return error;
794
+ return new DbError(code, [{
795
+ path: "",
796
+ message: err.sqlMessage ?? err.message
797
+ }], void 0, { cause: error });
798
+ }
799
+ /**
800
+ * Whether the server reported `error` (a positive `errno`), as opposed to a
801
+ * client-side failure — a timeout, a lost socket — after which the server's
802
+ * transaction state is unknown.
803
+ */
804
+ function isServerError(error) {
805
+ const errno = error && typeof error === "object" ? error.errno : void 0;
806
+ return typeof errno === "number" && errno > 0;
807
+ }
808
+ /** Closes `conn` — or, for a driver without `destroy()`, rolls it back (best effort) and releases it. */
809
+ async function discardConnection(conn) {
810
+ if (conn.destroy) {
811
+ conn.destroy();
812
+ return;
813
+ }
814
+ try {
815
+ await conn.exec("ROLLBACK");
816
+ } catch {}
817
+ conn.release();
818
+ }
819
+ /** `exec` whose statements reject with the retryable `DbError` on contention (any statement can be the deadlock victim). */
820
+ function contentionExec(exec) {
821
+ const contention = (error) => {
822
+ throw mapContention(error);
823
+ };
824
+ return {
825
+ run: (sql, params) => exec.run(sql, params).catch(contention),
826
+ all: (sql, params) => exec.all(sql, params).catch(contention),
827
+ get: (sql, params) => exec.get(sql, params).catch(contention),
828
+ exec: (sql) => exec.exec(sql).catch(contention)
829
+ };
830
+ }
773
831
  /** The `ALTER TABLE` that re-creates `fks`, all on `table`, as they were. */
774
832
  function addForeignKeysSql(table, fks) {
775
833
  return `ALTER TABLE ${table} ${fks.map((fk) => `ADD CONSTRAINT ${qi(fk.name)} FOREIGN KEY (${fk.columns.map(qi).join(", ")}) REFERENCES ${fk.refTable} (${fk.refColumns.map(qi).join(", ")}) ON DELETE ${fk.onDelete} ON UPDATE ${fk.onUpdate}`).join(", ")}`;
@@ -839,6 +897,8 @@ var MysqlAdapter = class MysqlAdapter extends BaseDbAdapter {
839
897
  /** Field path → `@db.mysql.charset` of the column. */
840
898
  _charsetFields = /* @__PURE__ */ new Map();
841
899
  _space;
900
+ _poolExec;
901
+ _txExecs = /* @__PURE__ */ new WeakMap();
842
902
  /** Memo of {@link _keyTableCharsets} — it also makes its warning fire once. */
843
903
  _keyTableCharsetsMemo;
844
904
  /** Whether the connected MySQL instance supports native VECTOR type (MySQL 9.0+). */
@@ -908,12 +968,17 @@ var MysqlAdapter = class MysqlAdapter extends BaseDbAdapter {
908
968
  try {
909
969
  this._log("COMMIT");
910
970
  await conn.exec("COMMIT");
911
- } finally {
912
- conn.release();
971
+ } catch (error) {
972
+ endedTx.add(conn);
973
+ if (isServerError(error)) conn.release();
974
+ else await discardConnection(conn);
975
+ throw mapContention(error);
913
976
  }
977
+ conn.release();
914
978
  }
915
979
  async _rollbackTransaction(state) {
916
980
  const conn = state;
981
+ if (endedTx.delete(conn)) return;
917
982
  try {
918
983
  this._log("ROLLBACK");
919
984
  await conn.exec("ROLLBACK");
@@ -926,7 +991,11 @@ var MysqlAdapter = class MysqlAdapter extends BaseDbAdapter {
926
991
  * otherwise the pool-based driver.
927
992
  */
928
993
  _exec() {
929
- return this._txConnection() ?? this.driver;
994
+ const conn = this._txConnection();
995
+ if (!conn) return this._poolExec ??= contentionExec(this.driver);
996
+ let exec = this._txExecs.get(conn);
997
+ if (!exec) this._txExecs.set(conn, exec = contentionExec(conn));
998
+ return exec;
930
999
  }
931
1000
  /**
932
1001
  * Runs `fn` on one connection (the transaction's, or a dedicated one) with
@@ -1167,10 +1236,7 @@ var MysqlAdapter = class MysqlAdapter extends BaseDbAdapter {
1167
1236
  const columns = (message.match(/FOREIGN KEY \(([^)]+)\)/)?.[1])?.split(",").map((c) => c.trim().replace(/^`|`$/g, ""));
1168
1237
  throw constraintViolation("FK_VIOLATION", err.errno === 1451 ? { referencedBy: referencing } : { columns }, message);
1169
1238
  }
1170
- if (err.errno === 1213 || err.errno === 1205 || err.errno === 3572) throw new DbError(err.errno === 1213 ? "DEADLOCK" : "LOCK_TIMEOUT", [{
1171
- path: "",
1172
- message: err.sqlMessage ?? err.message
1173
- }]);
1239
+ throw mapContention(error);
1174
1240
  }
1175
1241
  throw error;
1176
1242
  }
@@ -2690,7 +2756,8 @@ var MysqlAdapter = class MysqlAdapter extends BaseDbAdapter {
2690
2756
  * The search predicate (AND the request filter) and its relevance order
2691
2757
  * (`rank`, since 0.1.165) — used as the ORDER BY when the read has no
2692
2758
  * `$sort`: exact-number hits first, then `MATCH … AGAINST` relevance, then
2693
- * the primary key. Grouped searches use only the predicate.
2759
+ * the primary key; the primary key alone under `$rank: false`. Grouped
2760
+ * searches use only the predicate.
2694
2761
  */
2695
2762
  _buildSearchWhere(text, query, indexName) {
2696
2763
  const fulltextIndex = this._getFulltextIndex(indexName);
@@ -2702,10 +2769,11 @@ var MysqlAdapter = class MysqlAdapter extends BaseDbAdapter {
2702
2769
  const all = fulltextIndex.match === "all";
2703
2770
  const matchClause = `MATCH(${matchCols}) AGAINST(? IN ${all ? "BOOLEAN" : "NATURAL LANGUAGE"} MODE)`;
2704
2771
  const term = all ? mysqlRequireEveryTerm(text) : text;
2772
+ const ranked = textFields.length > 0 && query.controls?.$rank !== false;
2705
2773
  const rank = searchRankOrder(mysqlDialect, {
2706
2774
  exactEqualities: n === void 0 ? [] : integerFields.map((f) => `${qi(f.name)} = ?`),
2707
2775
  n,
2708
- textRank: textFields.length > 0 ? {
2776
+ textRank: ranked ? {
2709
2777
  sql: `${matchClause} DESC`,
2710
2778
  params: [term]
2711
2779
  } : void 0,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atscript/db-mysql",
3
- "version": "0.1.174",
3
+ "version": "0.1.175",
4
4
  "description": "MySQL adapter for @atscript/db with mysql2 driver support.",
5
5
  "keywords": [
6
6
  "atscript",
@@ -41,21 +41,21 @@
41
41
  "access": "public"
42
42
  },
43
43
  "dependencies": {
44
- "@atscript/db-sql-tools": "^0.1.174"
44
+ "@atscript/db-sql-tools": "^0.1.175"
45
45
  },
46
46
  "devDependencies": {
47
- "@atscript/core": "^0.2.9",
48
- "@atscript/typescript": "^0.2.9",
49
- "@uniqu/core": "^0.2.1",
47
+ "@atscript/core": "^0.2.11",
48
+ "@atscript/typescript": "^0.2.11",
49
+ "@uniqu/core": "^0.2.2",
50
50
  "mysql2": "^3.11.0",
51
- "unplugin-atscript": "^0.2.9"
51
+ "unplugin-atscript": "^0.2.11"
52
52
  },
53
53
  "peerDependencies": {
54
- "@atscript/core": "^0.2.9",
55
- "@atscript/typescript": "^0.2.9",
56
- "@uniqu/core": "^0.2.1",
54
+ "@atscript/core": "^0.2.11",
55
+ "@atscript/typescript": "^0.2.11",
56
+ "@uniqu/core": "^0.2.2",
57
57
  "mysql2": ">=3.0.0",
58
- "@atscript/db": "^0.1.174"
58
+ "@atscript/db": "^0.1.175"
59
59
  },
60
60
  "peerDependenciesMeta": {
61
61
  "mysql2": {