@maiyunnet/kebab 10.0.0 → 10.1.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.
package/sys/mod.js CHANGED
@@ -82,6 +82,8 @@ export default class Mod {
82
82
  _ctr = undefined;
83
83
  /** --- 主表筛选前缀,优先 alias,其次表名 --- */
84
84
  _fieldPrefix = '';
85
+ /** --- 当前查询是否优先使用只读从库 --- */
86
+ _read = false;
85
87
  /**
86
88
  * --- 构造函数 ---
87
89
  * @param opt 选项
@@ -91,6 +93,7 @@ export default class Mod {
91
93
  this._ctr = opt.ctr;
92
94
  /** --- 导入数据库连接 --- */
93
95
  this._db = opt.db;
96
+ this._read = Boolean(opt.read);
94
97
  /** --- 新建 sql 对象 --- */
95
98
  this._sql = lSql.get({
96
99
  'service': this._db.getService() ?? lDb.ESERVICE.PGSQL,
@@ -411,6 +414,7 @@ export default class Mod {
411
414
  'alias': opt.alias,
412
415
  'contain': opt.contain,
413
416
  'hint': opt.hint,
417
+ 'read': opt.read,
414
418
  });
415
419
  }
416
420
  /**
@@ -429,6 +433,7 @@ export default class Mod {
429
433
  'contain': opt.contain,
430
434
  'alias': opt.alias,
431
435
  'hint': opt.hint,
436
+ 'read': opt.read,
432
437
  });
433
438
  }
434
439
  /**
@@ -464,6 +469,7 @@ export default class Mod {
464
469
  }],
465
470
  'index': opt.index,
466
471
  'hint': opt.hint,
472
+ 'read': opt.read,
467
473
  }).first(opt.lock);
468
474
  }
469
475
  static async one(db, s, opt = {}) {
@@ -476,6 +482,7 @@ export default class Mod {
476
482
  'pre': opt.pre,
477
483
  'where': s,
478
484
  'hint': opt.hint,
485
+ 'read': opt.read,
479
486
  });
480
487
  if (opt.by) {
481
488
  o.by(opt.by[0], opt.by[1]);
@@ -492,6 +499,7 @@ export default class Mod {
492
499
  'where': s,
493
500
  'index': item,
494
501
  'hint': opt.hint,
502
+ 'read': opt.read,
495
503
  });
496
504
  if (opt.by) {
497
505
  row.by(opt.by[0], opt.by[1]);
@@ -523,7 +531,7 @@ export default class Mod {
523
531
  'pre': opt.pre ?? this._$pre,
524
532
  });
525
533
  sq.select(this._$primary, this._$table + (opt.index ? ('_' + opt.index) : '')).where(where);
526
- const r = await db.query(sq.getSql(), sq.getData());
534
+ const r = await db.query(sq.getSql(), sq.getData(), { 'read': opt.read });
527
535
  if (r.rows === null) {
528
536
  lCore.log(opt.ctr ?? {}, '[MOD][PRIMARYS] ' + (lText.stringifyJson(r.error?.message ?? '').slice(1, -1) + ' - ' + sq.format()).replaceAll('"', '""'), '-error');
529
537
  return false;
@@ -883,12 +891,20 @@ export default class Mod {
883
891
  return false;
884
892
  }
885
893
  }
894
+ /**
895
+ * --- 设置当前查询是否优先使用只读从库(加锁查询或事务内仍走主库) ---
896
+ * @param enable 是否使用只读从库,默认 true
897
+ */
898
+ read(enable = true) {
899
+ this._read = enable;
900
+ return this;
901
+ }
886
902
  async first(lock = false, array = false) {
887
903
  this._sql.limit(1);
888
904
  if (lock) {
889
905
  this._sql.lock();
890
906
  }
891
- const r = await this._db.query(this._sql.getSql(), this._sql.getData());
907
+ const r = await this._db.query(this._sql.getSql(), this._sql.getData(), { 'read': !lock && this._read });
892
908
  if (r.rows === null) {
893
909
  lCore.log(this._ctr ?? {}, '[MOD][first] ' + (lText.stringifyJson(r.error?.message ?? '').slice(1, -1) + ' - ' + this._sql.format()).replaceAll('"', '""'), '-error');
894
910
  return false;
@@ -904,6 +920,8 @@ export default class Mod {
904
920
  this._data[k] = v;
905
921
  this[k] = v;
906
922
  }
923
+ // --- 返回实体后清除只读查询标记,避免后续实例操作沿用 ---
924
+ this._read = false;
907
925
  return this;
908
926
  }
909
927
  async firstArray(lock = false) {
@@ -987,7 +1005,7 @@ export default class Mod {
987
1005
  sql = sql.replace(/(FROM [a-zA-Z0-9`"_.]+?_)[\w]+/, '$1' + this._index[i]);
988
1006
  }
989
1007
  const tsql = this._formatTotal(sql);
990
- const tr = await this._db.query(tsql, this._sql.getData());
1008
+ const tr = await this._db.query(tsql, this._sql.getData(), { 'read': this._read });
991
1009
  if (tr.rows === null) {
992
1010
  return false;
993
1011
  }
@@ -1012,7 +1030,7 @@ export default class Mod {
1012
1030
  offset = -1;
1013
1031
  }
1014
1032
  const lsql = sql.replace(/ LIMIT [0-9 ,]+(OFFSET [0-9]+)?/g, ` LIMIT ${remain} OFFSET ${cz}`);
1015
- const r = await this._db.query(lsql, this._sql.getData());
1033
+ const r = await this._db.query(lsql, this._sql.getData(), { 'read': this._read });
1016
1034
  if (r.rows === null) {
1017
1035
  lCore.log(this._ctr ?? {}, '[MOD][all] ' + (lText.stringifyJson(r.error?.message ?? '').slice(1, -1) + ' - ' + this._sql.format()).replaceAll('"', '""'), '-error');
1018
1036
  return false;
@@ -1049,7 +1067,7 @@ export default class Mod {
1049
1067
  // --- 单表 ---
1050
1068
  /** --- 要追加的 values --- */
1051
1069
  const contain = this._contain ? lCore.clone(this._contain.list) : null;
1052
- const r = await this._db.query(this._sql.getSql(), this._sql.getData());
1070
+ const r = await this._db.query(this._sql.getSql(), this._sql.getData(), { 'read': this._read });
1053
1071
  if (r.rows === null) {
1054
1072
  lCore.log(this._ctr ?? {}, '[MOD][all] ' + (lText.stringifyJson(r.error?.message ?? '').slice(1, -1) + ' - ' + this._sql.format()).replaceAll('"', '""'), '-error');
1055
1073
  return false;
@@ -1071,7 +1089,7 @@ export default class Mod {
1071
1089
  [this._getContainWhereKey()]: contain,
1072
1090
  }
1073
1091
  });
1074
- cr = await this._db.query(csql.getSql(), csql.getData());
1092
+ cr = await this._db.query(csql.getSql(), csql.getData(), { 'read': this._read });
1075
1093
  if (cr.rows === null) {
1076
1094
  lCore.log(this._ctr ?? {}, '[MOD][all] ' + (lText.stringifyJson(cr.error?.message ?? '').slice(1, -1) + ' - ' + csql.format()).replaceAll('"', '""'), '-error');
1077
1095
  }
@@ -1148,7 +1166,7 @@ export default class Mod {
1148
1166
  sql = sql.replace(/(FROM [a-zA-Z0-9`"_.]+?_)[\w]+/, '$1' + this._index[i]);
1149
1167
  }
1150
1168
  const tsql = this._formatTotal(sql);
1151
- const tr = await this._db.query(tsql, this._sql.getData());
1169
+ const tr = await this._db.query(tsql, this._sql.getData(), { 'read': this._read });
1152
1170
  if (tr.rows === null) {
1153
1171
  return false;
1154
1172
  }
@@ -1174,7 +1192,7 @@ export default class Mod {
1174
1192
  offset = -1;
1175
1193
  }
1176
1194
  const lsql = sql.replace(/ LIMIT [0-9 ,]+(OFFSET [0-9]+)?/g, ` LIMIT ${remain} OFFSET ${cz}`);
1177
- const r = await this._db.query(lsql, this._sql.getData());
1195
+ const r = await this._db.query(lsql, this._sql.getData(), { 'read': this._read });
1178
1196
  if (r.rows === null) {
1179
1197
  lCore.log(this._ctr ?? {}, '[MOD][allArray] ' + (lText.stringifyJson(r.error?.message ?? '').slice(1, -1) + ' - ' + this._sql.format()).replaceAll('"', '""'), '-error');
1180
1198
  return false;
@@ -1196,7 +1214,7 @@ export default class Mod {
1196
1214
  }
1197
1215
  // --- 单表 ---
1198
1216
  const contain = this._contain ? lCore.clone(this._contain.list) : null;
1199
- const r = await this._db.query(this._sql.getSql(), this._sql.getData());
1217
+ const r = await this._db.query(this._sql.getSql(), this._sql.getData(), { 'read': this._read });
1200
1218
  if (r.rows === null) {
1201
1219
  lCore.log(this._ctr ?? {}, '[MOD][allArray] ' + (lText.stringifyJson(r.error?.message ?? '').slice(1, -1) + ' - ' + this._sql.format()).replaceAll('"', '""'), '-error');
1202
1220
  return false;
@@ -1218,7 +1236,7 @@ export default class Mod {
1218
1236
  [this._getContainWhereKey()]: contain,
1219
1237
  }
1220
1238
  });
1221
- cr = await this._db.query(csql.getSql(), csql.getData());
1239
+ cr = await this._db.query(csql.getSql(), csql.getData(), { 'read': this._read });
1222
1240
  if (cr.rows === null) {
1223
1241
  lCore.log(this._ctr ?? {}, '[MOD][allArray] ' + (lText.stringifyJson(cr.error?.message ?? '').slice(1, -1) + ' - ' + csql.format()).replaceAll('"', '""'), '-error');
1224
1242
  }
@@ -1249,7 +1267,7 @@ export default class Mod {
1249
1267
  * @param all 是否获取完全的情况,默认不获取,只返回扫描情况
1250
1268
  */
1251
1269
  async explain(all = false) {
1252
- const r = await this._db.query('EXPLAIN ' + this._sql.getSql(), this._sql.getData());
1270
+ const r = await this._db.query('EXPLAIN ' + this._sql.getSql(), this._sql.getData(), { 'read': this._read });
1253
1271
  if (r.rows === null) {
1254
1272
  lCore.log(this._ctr ?? {}, '[MOD][explain] ' + (lText.stringifyJson(r.error?.message ?? '').slice(1, -1) + ' - ' + this._sql.format()).replaceAll('"', '""'), '-error');
1255
1273
  return false;
@@ -1306,7 +1324,7 @@ export default class Mod {
1306
1324
  return count;
1307
1325
  }
1308
1326
  const sql = this._formatTotal(this._sql.getSql(), f);
1309
- const r = await this._db.query(sql, this._sql.getData());
1327
+ const r = await this._db.query(sql, this._sql.getData(), { 'read': this._read });
1310
1328
  if (r.rows === null) {
1311
1329
  lCore.log(this._ctr ?? {}, '[MOD][total] ' + (lText.stringifyJson(r.error?.message ?? '').slice(1, -1) + ' - ' + this._sql.format()).replaceAll('"', '""'), '-error');
1312
1330
  return 0;
@@ -1327,7 +1345,7 @@ export default class Mod {
1327
1345
  return false;
1328
1346
  }
1329
1347
  const sql = this._sql.copy(undefined, { 'order': false, 'limit': false });
1330
- const result = await this._db.query('EXPLAIN (FORMAT JSON) ' + sql.getSql(), sql.getData());
1348
+ const result = await this._db.query('EXPLAIN (FORMAT JSON) ' + sql.getSql(), sql.getData(), { 'read': this._read });
1331
1349
  if (result.rows === null) {
1332
1350
  lCore.log(this._ctr ?? {}, '[MOD][totalEstimate] Query failed', '-error');
1333
1351
  return false;
@@ -1377,7 +1395,7 @@ export default class Mod {
1377
1395
  const direction = opt.before ? (order === 'DESC' ? 'ASC' : 'DESC') : order;
1378
1396
  const sql = this._sql.copy(undefined, { 'order': false, 'limit': false });
1379
1397
  sql.seek(fields, opt.cursor, direction).limit(count + 1);
1380
- const result = await this._db.query(sql.getSql(), sql.getData());
1398
+ const result = await this._db.query(sql.getSql(), sql.getData(), { 'read': this._read });
1381
1399
  if (result.rows === null) {
1382
1400
  lCore.log(this._ctr ?? {}, '[MOD][allCursor] Query failed', '-error');
1383
1401
  return false;
@@ -1411,7 +1429,7 @@ export default class Mod {
1411
1429
  .replace(/SELECT .+? FROM/is, this._db.getService() === lDb.ESERVICE.MYSQL ?
1412
1430
  'SELECT COUNT(0) AS `count` FROM' :
1413
1431
  'SELECT COUNT(0) AS "count" FROM');
1414
- const r = await this._db.query(sql, this._sql.getData());
1432
+ const r = await this._db.query(sql, this._sql.getData(), { 'read': this._read });
1415
1433
  if (r.rows === null) {
1416
1434
  lCore.log(this._ctr ?? {}, '[MOD][count] ' + (lText.stringifyJson(r.error?.message ?? '').slice(1, -1) + ' - ' + this._sql.format()).replaceAll('"', '""'), '-error');
1417
1435
  return 0;
@@ -72,7 +72,7 @@ export default class extends sCtr.Ctr {
72
72
  /**
73
73
  * --- 数据库读写分离测试 ---
74
74
  */
75
- dbRead(): string;
75
+ dbRead(): Promise<string>;
76
76
  private _dbTable;
77
77
  vector(): Promise<any>;
78
78
  kv(): Promise<kebab.Json>;
@@ -197,7 +197,7 @@ export default class extends sCtr.Ctr {
197
197
  `<br><br><a href="${this._config.const.urlBase}test/crypto">View "test/crypto"</a>`,
198
198
  '<br><br><b>Db:</b>',
199
199
  `<br><br><a href="${this._config.const.urlBase}test/db">View "test/db"</a> <a href="${this._config.const.urlBase}test/db?s=pgsql">pgsql</a>`,
200
- `<br><a href="${this._config.const.urlBase}test/db-read">View "test/db-read"</a>`,
200
+ `<br><a href="${this._config.const.urlBase}test/db-read">View "test/db-read"</a> <a href="${this._config.const.urlBase}test/db-read?s=pgsql">pgsql</a>`,
201
201
  `<br><br><b>Vector:</b>`,
202
202
  `<br><br><a href="${this._config.const.urlBase}test/vector">View "test/vector"</a>`,
203
203
  '<br><br><b>Kv:</b>',
@@ -1916,16 +1916,35 @@ exec: ${JSON.stringify(exec)}<br><br>`);
1916
1916
  /**
1917
1917
  * --- 数据库读写分离测试 ---
1918
1918
  */
1919
- dbRead() {
1919
+ async dbRead() {
1920
1920
  const echo = [];
1921
- echo.push('<b>DB Read Separation Test</b><hr>');
1922
- echo.push('<pre>const db = lDb.get(this);\nconst dbRead = lDb.get(this, { \'read\': true });</pre>');
1921
+ const isPgsql = this._get['s'] === 'pgsql';
1922
+ const service = isPgsql ? 'PGSQL' : 'MYSQL';
1923
+ const db = lDb.get(this, {
1924
+ 'service': isPgsql ? lDb.ESERVICE.PGSQL : lDb.ESERVICE.MYSQL,
1925
+ });
1926
+ const sql = isPgsql ?
1927
+ 'SELECT * FROM "m"."test" ORDER BY "id" DESC LIMIT 10;' :
1928
+ 'SELECT * FROM `m_test` ORDER BY `id` DESC LIMIT 10;';
1923
1929
  const config = this._config;
1924
- const service = config.db.default;
1930
+ const readCfg = config.db[service]?.read;
1931
+ const readHosts = (Array.isArray(readCfg) ? readCfg : (readCfg ? [readCfg] : []))
1932
+ .map(item => item.host)
1933
+ .filter((host) => Boolean(host));
1934
+ echo.push('<b>DB Read Separation Test</b><hr>');
1935
+ echo.push(`<pre>const db = lDb.get(this, { 'service': lDb.ESERVICE.${service} });
1936
+ const stmt = await db.query('${sql}', [], { 'read': true });</pre>`);
1925
1937
  echo.push(`Service: ${service}`);
1926
1938
  echo.push(`<br>Default host: ${config.db[service]?.default?.host ?? '(not configured)'}`);
1927
- echo.push(`<br>Read host: ${config.db[service]?.read?.host ?? '(not configured, will fallback to default)'}`);
1928
- return echo.join('') + '<br><br>' + this._getEnd();
1939
+ echo.push(`<br>Read host: ${readHosts.length ? readHosts.join(', ') : '(not configured, will fallback to default)'}<br><br>`);
1940
+ const stmt = await db.query(sql, [], { 'read': true });
1941
+ if (stmt.rows) {
1942
+ this._dbTable(stmt, echo);
1943
+ }
1944
+ else {
1945
+ echo.push(`Query error: ${lText.htmlescape(stmt.error ? `${stmt.error.message} (${stmt.error.errno})` : 'Failed')}<br>`);
1946
+ }
1947
+ return echo.join('') + `<br>queries: ${db.getQueries()}<br><br>` + this._getEnd();
1929
1948
  }
1930
1949
  _dbTable(stmt, echo) {
1931
1950
  echo.push('<table style="width: 100%;"><tr>');
@@ -42,7 +42,6 @@ export default class default_1 extends sMod {
42
42
  static _$primary = 'id';
43
43
  static _$key = 'token';
44
44
  static _$index = 'token';
45
- /* eslint-enable */
46
45
  _keyGenerator() {
47
46
  return 'test_' + lCore.rand(0, 3).toString();
48
47
  }