baja-lite 1.0.6 → 1.0.10

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/es/sql.js CHANGED
@@ -7,8 +7,8 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  var __metadata = (this && this.__metadata) || function (k, v) {
8
8
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
9
  };
10
- var _a, _b, _c;
11
- var _d, _e, _f, _g;
10
+ var _b, _c, _d;
11
+ var _e, _f, _g, _h;
12
12
  import { Throw } from './error';
13
13
  import tslib from 'tslib';
14
14
  import Sqlstring from 'sqlstring';
@@ -16,14 +16,16 @@ import iterare from 'iterare';
16
16
  import { emptyString } from './string';
17
17
  import pino from 'pino';
18
18
  import { excuteSplit, ExcuteSplitMode, sleep } from './fn';
19
- import { add, calc } from './math';
19
+ import { add, calc, ten2Any } from './math';
20
20
  import mustache from 'mustache';
21
21
  import { C2P, C2P2, P2C } from './object';
22
- import { format } from 'sql-formatter';
22
+ import { formatDialect, sqlite, mysql } from 'sql-formatter';
23
23
  import HTML from 'html-parse-stringify';
24
24
  import { convert } from './convert-xml';
25
25
  import { ArrayList } from './list';
26
26
  import LGet from 'lodash.get';
27
+ import { encode, decode } from "@msgpack/msgpack";
28
+ BigInt.prototype.toJSON = function () { return this.toString(); };
27
29
  // #region 常量
28
30
  const _daoDBName = Symbol('dbName');
29
31
  const _tableName = Symbol('tableName');
@@ -31,6 +33,7 @@ const _className = Symbol('className');
31
33
  const _ClassName = Symbol('ClassName');
32
34
  const _vueName = Symbol('vueName');
33
35
  const _ids = Symbol('ids');
36
+ const _logicIds = Symbol('logicIds');
34
37
  const _columns = Symbol('columns');
35
38
  const _columnsNoId = Symbol('columnsNoId');
36
39
  const _fields = Symbol('fields');
@@ -39,10 +42,12 @@ const _deleteState = Symbol('deleteState');
39
42
  const _transformer = Symbol('transformer');
40
43
  const _index = Symbol('index');
41
44
  const _def = Symbol('def');
45
+ const _comment = Symbol('comment');
42
46
  export const _sqlCache = Symbol('sqlMap');
43
47
  export const _dao = Symbol('dao');
44
48
  export const _primaryDB = Symbol('primaryDB');
45
49
  const _dbType = Symbol('dbType');
50
+ const _formatDialect = Symbol('FormatDialect');
46
51
  const _sqlite_version = Symbol('sqlite_version');
47
52
  const _daoConnection = Symbol('daoConnection');
48
53
  const _inTransaction = Symbol('inTransaction');
@@ -51,6 +56,7 @@ const _sqliteRemoteName = Symbol('sqliteRemoteName');
51
56
  const _SqlOption = Symbol('SqlOption');
52
57
  const _resultMap = Symbol('resultMap');
53
58
  const _resultMap_SQLID = Symbol('resultMap_SQLID');
59
+ export const _enums = Symbol('_enums');
54
60
  export const _Hump = Symbol('Hump');
55
61
  export const _GlobalSqlOption = Symbol('GlobalSqlOption');
56
62
  export const _EventBus = Symbol('EventBus');
@@ -235,7 +241,7 @@ export const _defOption = {
235
241
  ;
236
242
  class MysqlConnection {
237
243
  constructor(conn) {
238
- this[_a] = false;
244
+ this[_b] = false;
239
245
  this[_daoConnection] = conn;
240
246
  }
241
247
  execute(sync, sql, params) {
@@ -418,7 +424,7 @@ class MysqlConnection {
418
424
  ;
419
425
  }
420
426
  }
421
- _a = _inTransaction;
427
+ _b = _inTransaction;
422
428
  export class Mysql {
423
429
  constructor(pool) {
424
430
  this[_daoDB] = pool;
@@ -509,7 +515,7 @@ export class Mysql {
509
515
  }
510
516
  class SqliteConnection {
511
517
  constructor(conn) {
512
- this[_b] = false;
518
+ this[_c] = false;
513
519
  this[_daoConnection] = conn;
514
520
  }
515
521
  execute(sync, sql, params) {
@@ -649,7 +655,7 @@ class SqliteConnection {
649
655
  realse(sync) {
650
656
  }
651
657
  }
652
- _b = _inTransaction;
658
+ _c = _inTransaction;
653
659
  export class Sqlite {
654
660
  constructor(db) {
655
661
  this[_daoDB] = db;
@@ -714,7 +720,7 @@ export class Sqlite {
714
720
  }
715
721
  export class SqliteRemoteConnection {
716
722
  constructor(conn, name) {
717
- this[_c] = false;
723
+ this[_d] = false;
718
724
  this[_daoConnection] = conn;
719
725
  this[_sqliteRemoteName] = name;
720
726
  }
@@ -734,7 +740,8 @@ export class SqliteRemoteConnection {
734
740
  }
735
741
  return new Promise(async (resolve, reject) => {
736
742
  try {
737
- const { affectedRows, insertId } = await this[_daoConnection].execute(this[_sqliteRemoteName], sql, params);
743
+ const data = await this[_daoConnection].execute(encode([this[_sqliteRemoteName], sql, params]));
744
+ const { affectedRows, insertId } = decode(data);
738
745
  resolve({ affectedRows, insertId: insertId ? BigInt(insertId) : 0n });
739
746
  }
740
747
  catch (error) {
@@ -763,7 +770,8 @@ export class SqliteRemoteConnection {
763
770
  }
764
771
  return new Promise(async (resolve, reject) => {
765
772
  try {
766
- const r = await this[_daoConnection].pluck(this[_sqliteRemoteName], sql, params);
773
+ const data = await this[_daoConnection].pluck(encode([this[_sqliteRemoteName], sql, params]));
774
+ const r = decode(data);
767
775
  resolve(r);
768
776
  }
769
777
  catch (error) {
@@ -792,7 +800,8 @@ export class SqliteRemoteConnection {
792
800
  }
793
801
  return new Promise(async (resolve, reject) => {
794
802
  try {
795
- const r = await this[_daoConnection].get(this[_sqliteRemoteName], sql, params);
803
+ const data = await this[_daoConnection].pluck(encode([this[_sqliteRemoteName], sql, params]));
804
+ const r = decode(data);
796
805
  resolve(r);
797
806
  }
798
807
  catch (error) {
@@ -821,7 +830,8 @@ export class SqliteRemoteConnection {
821
830
  }
822
831
  return new Promise(async (resolve, reject) => {
823
832
  try {
824
- const r = await this[_daoConnection].raw(this[_sqliteRemoteName], sql, params);
833
+ const data = await this[_daoConnection].pluck(encode([this[_sqliteRemoteName], sql, params]));
834
+ const r = decode(data);
825
835
  resolve(r);
826
836
  }
827
837
  catch (error) {
@@ -850,7 +860,8 @@ export class SqliteRemoteConnection {
850
860
  }
851
861
  return new Promise(async (resolve, reject) => {
852
862
  try {
853
- const r = await this[_daoConnection].query(this[_sqliteRemoteName], sql, params);
863
+ const data = await this[_daoConnection].pluck(encode([this[_sqliteRemoteName], sql, params]));
864
+ const r = decode(data);
854
865
  resolve(r);
855
866
  }
856
867
  catch (error) {
@@ -866,7 +877,7 @@ export class SqliteRemoteConnection {
866
877
  realse(sync) {
867
878
  }
868
879
  }
869
- _c = _inTransaction;
880
+ _d = _inTransaction;
870
881
  export class SqliteRemote {
871
882
  constructor(db, name) {
872
883
  this[_daoDB] = db;
@@ -879,8 +890,11 @@ export class SqliteRemote {
879
890
  }
880
891
  ;
881
892
  return new Promise(async (resolve, reject) => {
893
+ if (!this.connection) {
894
+ this.connection = new SqliteRemoteConnection(this[_daoDB], this[_sqliteRemoteName]);
895
+ }
882
896
  try {
883
- resolve(new SqliteRemoteConnection(this[_daoDB], this[_sqliteRemoteName]));
897
+ resolve(this.connection);
884
898
  }
885
899
  catch (error) {
886
900
  reject(error);
@@ -1208,6 +1222,31 @@ class Build {
1208
1222
  }
1209
1223
  };
1210
1224
  }
1225
+ /**
1226
+ * * PROBLEM_TYPE = 枚举名
1227
+ * * t.problemtype = 列名
1228
+ *
1229
+ * ```
1230
+ * {{#enumTag}} PROBLEM_TYPE(t.problemtype) {{/enumTag}}
1231
+ * ```
1232
+ */
1233
+ enum() {
1234
+ return (text) => {
1235
+ const matchs = text.match(/([a-zA-Z_]+)\(([^()]+)\)/);
1236
+ if (matchs) {
1237
+ const [_a, MapName, Column] = matchs;
1238
+ if (MapName && Column) {
1239
+ const map = globalThis[_enums].GlobalMap[MapName.trim()];
1240
+ if (map) {
1241
+ return ` CASE
1242
+ ${Object.entries(map).map(([k, v]) => `WHEN ${Column} = '${k}' THEN '${v}'`).join(' ')}
1243
+ END `;
1244
+ }
1245
+ }
1246
+ }
1247
+ return "''";
1248
+ };
1249
+ }
1211
1250
  }
1212
1251
  Build.page = 'COUNT(1) zccw1986 ';
1213
1252
  function replaceCdata(rawText) {
@@ -1228,10 +1267,10 @@ function replaceCdata(rawText) {
1228
1267
  return rawText;
1229
1268
  }
1230
1269
  function _flatData(result, i, length, keys, V) {
1231
- var _d;
1270
+ var _e;
1232
1271
  const key = keys[i];
1233
1272
  if (i < length) {
1234
- result[_d = key] ?? (result[_d] = {});
1273
+ result[_e = key] ?? (result[_e] = {});
1235
1274
  i++;
1236
1275
  _flatData(result[key], i, length, keys, V);
1237
1276
  }
@@ -1426,19 +1465,14 @@ export class SqlCache {
1426
1465
  const buildParam = new Build(options.isCount === true, options.isSum === true, options);
1427
1466
  if (typeof sqlSource === 'function') {
1428
1467
  const _sql = sqlSource(options);
1429
- const sql = mustache.render(_sql, buildParam, this.sqlFNMap);
1430
- return format(sql);
1468
+ return mustache.render(_sql, buildParam, this.sqlFNMap);
1431
1469
  }
1432
1470
  else if (typeof sqlSource === 'string') {
1433
- const sql = mustache.render(sqlSource, buildParam, this.sqlFNMap);
1434
- return format(sql);
1471
+ return mustache.render(sqlSource, buildParam, this.sqlFNMap);
1435
1472
  }
1436
1473
  else if (typeof sqlSource === 'object') {
1437
1474
  const _sql = convert(sqlSource, options, matchSqlid, this.sqlMap);
1438
- console.log(_sql);
1439
- const sql = mustache.render(_sql, buildParam, this.sqlFNMap);
1440
- console.log(sql);
1441
- return format(sql);
1475
+ return mustache.render(_sql, buildParam, this.sqlFNMap);
1442
1476
  }
1443
1477
  return '';
1444
1478
  }
@@ -1469,12 +1503,9 @@ function P(skipConn = false) {
1469
1503
  const option = args[0] = Object.assign({}, globalThis[_GlobalSqlOption], this[_SqlOption], args[0]);
1470
1504
  option.sync ?? (option.sync = SyncMode.Async);
1471
1505
  const dbName = option?.dbName ?? this[_daoDBName] ?? _primaryDB;
1472
- const dddx = this[_dbType];
1473
- logger.info(dddx);
1474
1506
  option.dao = globalThis[_dao][this[_dbType]][dbName];
1475
1507
  Throw.if(!option.dao, `not found db:${String(dbName)}(${this[_dbType]})`);
1476
1508
  option.tableName = option?.tableName ?? this[_tableName];
1477
- const tableES = Sqlstring.escapeId(option.tableName);
1478
1509
  if (this[_dbType] === DBType.Sqlite) {
1479
1510
  Throw.if(option.sync === SyncMode.Async, 'sqlite can not Async!');
1480
1511
  // 连接共享
@@ -1484,60 +1515,6 @@ function P(skipConn = false) {
1484
1515
  else {
1485
1516
  needRealseConn = false;
1486
1517
  }
1487
- if (skipConn === false) {
1488
- const lastVersion = this[_sqlite_version] ?? '0.0.1';
1489
- // 检查表
1490
- const tableCheckResult = option.conn.pluck(SyncMode.Sync, `SELECT COUNT(1) t FROM sqlite_master WHERE TYPE = 'table' AND name = ?`, [option.tableName]);
1491
- if (tableCheckResult) {
1492
- // 旧版本
1493
- const tableVersion = option.conn.pluck(SyncMode.Sync, 'SELECT ______version v from TABLE_VERSION WHERE ______tableName = ?', [option.tableName]);
1494
- if (tableVersion && tableVersion < lastVersion) { // 发现需要升级的版本
1495
- // 更新版本
1496
- const columns = iterare(option.conn.query(SyncMode.Sync, `PRAGMA table_info(${tableES})`))
1497
- .filter(c => this[_fields].hasOwnProperty(C2P(c.name, globalThis[_Hump])))
1498
- .map(c => Sqlstring.escapeId(c.name))
1499
- .join(',');
1500
- const rtable = Sqlstring.escapeId(`${option.tableName}_${tableVersion.replace(/\./, '_')}`);
1501
- option.conn.execute(SyncMode.Sync, `DROP TABLE IF EXISTS ${rtable};`);
1502
- option.conn.execute(SyncMode.Sync, `ALTER TABLE ${tableES} RENAME TO ${rtable};`);
1503
- option.conn.execute(SyncMode.Sync, `
1504
- CREATE TABLE IF NOT EXISTS ${tableES}(
1505
- ${Object.values(this[_fields]).map(K => K[DBType.Sqlite]()).join(',')}
1506
- ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.C2()).join(',')})` : ''}
1507
- );
1508
- `);
1509
- if (this[_index] && this[_index].length) {
1510
- for (const index of this[_index]) {
1511
- option.conn.execute(SyncMode.Sync, `CREATE INDEX ${Sqlstring.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${this[_fields][index]?.C2()}");`);
1512
- }
1513
- }
1514
- option.conn.execute(SyncMode.Sync, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
1515
- option.conn.execute(SyncMode.Sync, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
1516
- option.conn.execute(SyncMode.Sync, `DROP TABLE IF EXISTS ${rtable};`);
1517
- // 更新完毕,保存版本号
1518
- option.conn.execute(SyncMode.Sync, 'UPDATE TABLE_VERSION SET ______version = ? WHERE ______tableName = ?', [option.tableName, lastVersion]);
1519
- }
1520
- else if (!tableVersion) { // 不需要升级情况:没有旧的版本号
1521
- option.conn.execute(SyncMode.Sync, 'INSERT INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
1522
- }
1523
- }
1524
- else { // 表不存在
1525
- // 创建表
1526
- option.conn.execute(SyncMode.Sync, `
1527
- CREATE TABLE IF NOT EXISTS ${tableES} (
1528
- ${Object.values(this[_fields]).map(K => K[DBType.Sqlite]()).join(',')}
1529
- ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.C2()).join(',')})` : ''}
1530
-
1531
- );
1532
- `);
1533
- if (this[_index] && this[_index].length) {
1534
- for (const index of this[_index]) {
1535
- option.conn.execute(SyncMode.Sync, `CREATE INDEX ${Sqlstring.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${this[_fields][index]?.C2()}");`);
1536
- }
1537
- }
1538
- option.conn.execute(SyncMode.Sync, 'INSERT OR REPLACE INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
1539
- }
1540
- }
1541
1518
  try {
1542
1519
  const result = fn.call(this, ...args);
1543
1520
  logger.info(`${propertyKey}:${option.tableName}:use ${+new Date() - startTime}ms`);
@@ -1571,59 +1548,6 @@ function P(skipConn = false) {
1571
1548
  else {
1572
1549
  needRealseConn = false;
1573
1550
  }
1574
- if (skipConn === false) {
1575
- const lastVersion = this[_sqlite_version] ?? '0.0.1';
1576
- // 检查表
1577
- const tableCheckResult = await option.conn.pluck(SyncMode.Async, `SELECT COUNT(1) t FROM sqlite_master WHERE TYPE = 'table' AND name = ?`, [option.tableName]);
1578
- if (tableCheckResult) {
1579
- // 旧版本
1580
- const tableVersion = await option.conn.pluck(SyncMode.Async, 'SELECT ______version v from TABLE_VERSION WHERE ______tableName = ?', [option.tableName]);
1581
- if (tableVersion && tableVersion < lastVersion) { // 发现需要升级的版本
1582
- // 更新版本
1583
- const columns = iterare(await option.conn.query(SyncMode.Async, `PRAGMA table_info(${tableES})`))
1584
- .filter(c => this[_fields].hasOwnProperty(C2P(c.name, globalThis[_Hump])))
1585
- .map(c => Sqlstring.escapeId(c.name))
1586
- .join(',');
1587
- const rtable = `${option.tableName}_${tableVersion.replace(/\./, '_')}`;
1588
- await option.conn.execute(SyncMode.Async, `DROP TABLE IF EXISTS ${rtable};`);
1589
- await option.conn.execute(SyncMode.Async, `ALTER TABLE ${tableES} RENAME TO ${rtable};`);
1590
- await option.conn.execute(SyncMode.Async, `
1591
- CREATE TABLE IF NOT EXISTS ${tableES}(
1592
- ${Object.values(this[_fields]).map(K => K[DBType.Sqlite]()).join(',')}
1593
- ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.C2()).join(',')})` : ''}
1594
- );
1595
- `);
1596
- if (this[_index] && this[_index].length) {
1597
- for (const index of this[_index]) {
1598
- await option.conn.execute(SyncMode.Async, `CREATE INDEX ${Sqlstring.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${this[_fields][index]?.C2()}");`);
1599
- }
1600
- }
1601
- await option.conn.execute(SyncMode.Async, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
1602
- await option.conn.execute(SyncMode.Async, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
1603
- await option.conn.execute(SyncMode.Async, `DROP TABLE IF EXISTS ${rtable};`);
1604
- // 更新完毕,保存版本号
1605
- await option.conn.execute(SyncMode.Async, 'UPDATE TABLE_VERSION SET ______version = ? WHERE ______tableName = ?', [option.tableName, lastVersion]);
1606
- }
1607
- else if (!tableVersion) { // 不需要升级情况:没有旧的版本号
1608
- await option.conn.execute(SyncMode.Async, 'INSERT INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
1609
- }
1610
- }
1611
- else { // 表不存在
1612
- // 创建表
1613
- await option.conn.execute(SyncMode.Async, `
1614
- CREATE TABLE IF NOT EXISTS ${tableES}(
1615
- ${Object.values(this[_fields]).map(K => K[DBType.Sqlite]()).join(',')}
1616
- ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.C2()).join(',')})` : ''}
1617
- );
1618
- `);
1619
- if (this[_index] && this[_index].length) {
1620
- for (const index of this[_index]) {
1621
- await option.conn.execute(SyncMode.Async, `CREATE INDEX ${Sqlstring.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${Sqlstring.escapeId(option.tableName)} ("${this[_fields][index]?.C2()}");`);
1622
- }
1623
- }
1624
- await option.conn.execute(SyncMode.Async, 'INSERT OR REPLACE INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
1625
- }
1626
- }
1627
1551
  try {
1628
1552
  const result = await fn.call(this, ...args);
1629
1553
  logger.info(`${propertyKey}:${option.tableName}:use ${+new Date() - startTime}ms`);
@@ -1755,6 +1679,7 @@ export const Field = (config) => {
1755
1679
  case SqlType.bigint: {
1756
1680
  field[DBType.Mysql] = () => `${field.C2()} bigint ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1757
1681
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} integer`;
1682
+ field.Data2SQL = (data) => BigInt(data ?? 0);
1758
1683
  break;
1759
1684
  }
1760
1685
  case SqlType.float: {
@@ -1790,26 +1715,31 @@ export const Field = (config) => {
1790
1715
  case SqlType.date: {
1791
1716
  field[DBType.Mysql] = () => `${field.C2()} date ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1792
1717
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1718
+ field.Data2SQL = (data) => typeof data === 'string' ? new Date(data) : data;
1793
1719
  break;
1794
1720
  }
1795
1721
  case SqlType.time: {
1796
1722
  field[DBType.Mysql] = () => `${field.C2()} time ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1797
1723
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1724
+ field.Data2SQL = (data) => typeof data === 'string' ? new Date(data) : data;
1798
1725
  break;
1799
1726
  }
1800
1727
  case SqlType.year: {
1801
1728
  field[DBType.Mysql] = () => `${field.C2()} year ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1802
1729
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1730
+ field.Data2SQL = (data) => typeof data === 'string' ? new Date(data) : data;
1803
1731
  break;
1804
1732
  }
1805
1733
  case SqlType.datetime: {
1806
1734
  field[DBType.Mysql] = () => `${field.C2()} datetime ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1807
1735
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1736
+ field.Data2SQL = (data) => typeof data === 'string' ? new Date(data) : data;
1808
1737
  break;
1809
1738
  }
1810
1739
  case SqlType.timestamp: {
1811
1740
  field[DBType.Mysql] = () => `${field.C2()} timestamp ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1812
1741
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} integer`;
1742
+ field.Data2SQL = (data) => typeof data === 'string' ? +new Date(data) : data;
1813
1743
  break;
1814
1744
  }
1815
1745
  case SqlType.char: {
@@ -1923,6 +1853,7 @@ export const Field = (config) => {
1923
1853
  let __columns = Reflect.getMetadata(_columns, object);
1924
1854
  let __columnsNoId = Reflect.getMetadata(_columnsNoId, object);
1925
1855
  let __ids = Reflect.getMetadata(_ids, object);
1856
+ let __logicIds = Reflect.getMetadata(_logicIds, object);
1926
1857
  let __index = Reflect.getMetadata(_index, object);
1927
1858
  let __def = Reflect.getMetadata(_def, object);
1928
1859
  if (!__fields) {
@@ -1941,16 +1872,23 @@ export const Field = (config) => {
1941
1872
  else {
1942
1873
  __columnsNoId.push(propertyName);
1943
1874
  }
1875
+ if (field.logicId === true) {
1876
+ __logicIds.push(propertyName);
1877
+ }
1944
1878
  if (field.index === true) {
1945
1879
  __index.push(propertyName);
1946
1880
  }
1947
1881
  if (hasDef) {
1948
1882
  __def[propertyName] = field.def;
1949
1883
  }
1884
+ if (field.comment) {
1885
+ __def[propertyName] = field.comment;
1886
+ }
1950
1887
  Reflect.defineMetadata(_fields, __fields, object);
1951
1888
  Reflect.defineMetadata(_columns, __columns, object);
1952
1889
  Reflect.defineMetadata(_columnsNoId, __columnsNoId, object);
1953
1890
  Reflect.defineMetadata(_ids, __ids, object);
1891
+ Reflect.defineMetadata(_logicIds, __logicIds, object);
1954
1892
  Reflect.defineMetadata(_index, __index, object);
1955
1893
  Reflect.defineMetadata(_def, __def, object);
1956
1894
  if (field.hasOwnProperty('logicDelete')) {
@@ -1959,44 +1897,58 @@ export const Field = (config) => {
1959
1897
  }
1960
1898
  };
1961
1899
  };
1900
+ const formatDialects = {
1901
+ [DBType.Mysql]: mysql,
1902
+ [DBType.Sqlite]: sqlite,
1903
+ [DBType.SqliteRemote]: sqlite
1904
+ };
1962
1905
  export const DB = (config) => {
1963
1906
  return function (constructor) {
1964
- var _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w;
1907
+ var _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;
1965
1908
  const __ids = Reflect.getMetadata(_ids, config.clz.prototype) || new Array;
1909
+ const __logicIds = Reflect.getMetadata(_logicIds, config.clz.prototype) || new Array;
1966
1910
  const __fields = Reflect.getMetadata(_fields, config.clz.prototype);
1967
1911
  const __columns = Reflect.getMetadata(_columns, config.clz.prototype);
1968
- const __columnsNoId = __columns.filter((c) => __ids.includes(c) === false);
1912
+ const __columnsNoId = Reflect.getMetadata(_columnsNoId, config.clz.prototype);
1969
1913
  const __stateFileName = Reflect.getMetadata(_stateFileName, config.clz.prototype);
1970
1914
  const __deleteState = Reflect.getMetadata(_deleteState, config.clz.prototype);
1971
1915
  const __index = Reflect.getMetadata(_index, config.clz.prototype);
1972
1916
  const __def = Reflect.getMetadata(_def, config.clz.prototype);
1917
+ const __dbType = config.dbType ?? DBType.Mysql;
1918
+ const __formatDialect = formatDialects[__dbType];
1973
1919
  const className = config.tableName?.replace(/_(\w)/g, (a, b) => b.toUpperCase());
1974
1920
  const ClassName = className?.replace(/\w/, (v) => v.toUpperCase());
1975
1921
  const vueName = config.tableName?.replace(/_/g, '-');
1976
- return _w = class extends constructor {
1922
+ return _0 = class extends constructor {
1977
1923
  constructor() {
1978
1924
  super(...arguments);
1979
- this[_d] = config.tableName;
1980
- this[_e] = className;
1981
- this[_f] = ClassName;
1982
- this[_g] = vueName;
1983
- this[_h] = config.dbName;
1984
- this[_j] = config.dbType ?? DBType.Mysql;
1985
- this[_k] = config.sqliteVersion;
1986
- this[_l] = Object.assign({}, _defOption, config);
1987
- this[_m] = __ids;
1988
- this[_o] = __fields;
1989
- this[_p] = __columns;
1990
- this[_q] = __columnsNoId;
1991
- this[_r] = __index;
1992
- this[_s] = __def;
1993
- this[_t] = __stateFileName;
1994
- this[_u] = __deleteState;
1995
- this[_v] = (data, option) => {
1925
+ this[_e] = config.tableName;
1926
+ this[_f] = className;
1927
+ this[_g] = ClassName;
1928
+ this[_h] = vueName;
1929
+ this[_j] = config.dbName;
1930
+ this[_k] = __dbType;
1931
+ this[_l] = __formatDialect;
1932
+ this[_m] = config.sqliteVersion;
1933
+ this[_o] = Object.assign({}, _defOption, config);
1934
+ this[_p] = __ids;
1935
+ this[_q] = __logicIds;
1936
+ this[_r] = __fields;
1937
+ this[_s] = __columns;
1938
+ this[_t] = __columnsNoId;
1939
+ this[_u] = __index;
1940
+ this[_v] = __def;
1941
+ this[_w] = config.comment;
1942
+ this[_x] = __stateFileName;
1943
+ this[_y] = __deleteState;
1944
+ this[_z] = (data, option) => {
1996
1945
  return Object.fromEntries(iterare(option?.skipId === true ? __columnsNoId : __columns)
1997
1946
  .map(K => [K, FieldFilter(K, data[K], __def, __fields[K].uuid === true || __fields[K].uuidShort === true, option)])
1998
1947
  .filter(data => {
1999
1948
  if (data[1][0] === 1) {
1949
+ if (__fields[data[0]].Data2SQL) {
1950
+ data[1][1] = __fields[data[0]].Data2SQL(data[1][1]);
1951
+ }
2000
1952
  if (option?.onFieldExists) {
2001
1953
  option.onFieldExists(data[0], data[1][1]);
2002
1954
  }
@@ -2011,24 +1963,27 @@ export const DB = (config) => {
2011
1963
  };
2012
1964
  }
2013
1965
  },
2014
- _d = _tableName,
2015
- _e = _className,
2016
- _f = _ClassName,
2017
- _g = _vueName,
2018
- _h = _daoDBName,
2019
- _j = _dbType,
2020
- _k = _sqlite_version,
2021
- _l = _SqlOption,
2022
- _m = _ids,
2023
- _o = _fields,
2024
- _p = _columns,
2025
- _q = _columnsNoId,
2026
- _r = _index,
2027
- _s = _def,
2028
- _t = _stateFileName,
2029
- _u = _deleteState,
2030
- _v = _transformer,
2031
- _w;
1966
+ _e = _tableName,
1967
+ _f = _className,
1968
+ _g = _ClassName,
1969
+ _h = _vueName,
1970
+ _j = _daoDBName,
1971
+ _k = _dbType,
1972
+ _l = _formatDialect,
1973
+ _m = _sqlite_version,
1974
+ _o = _SqlOption,
1975
+ _p = _ids,
1976
+ _q = _logicIds,
1977
+ _r = _fields,
1978
+ _s = _columns,
1979
+ _t = _columnsNoId,
1980
+ _u = _index,
1981
+ _v = _def,
1982
+ _w = _comment,
1983
+ _x = _stateFileName,
1984
+ _y = _deleteState,
1985
+ _z = _transformer,
1986
+ _0;
2032
1987
  };
2033
1988
  };
2034
1989
  /**
@@ -2124,10 +2079,10 @@ export class SqlService {
2124
2079
  return `SELECT ${questMark.join(',')} FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM ${tableName} WHERE ${where})`;
2125
2080
  });
2126
2081
  const columnNames = iterare(finalColumns).map(i => this[_fields][i]?.C2()).join(',');
2127
- const sql = format(`INSERT INTO
2082
+ const sql = formatDialect(`INSERT INTO
2128
2083
  ${tableName}
2129
2084
  (${columnNames})
2130
- ${questMarks.join(' UNION ALL ')};`);
2085
+ ${questMarks.join(' UNION ALL ')};`, { dialect: this[_formatDialect] });
2131
2086
  sqls.push({ sql, params });
2132
2087
  break;
2133
2088
  }
@@ -2165,12 +2120,12 @@ export class SqlService {
2165
2120
  return `(${questMark.join(',')})`;
2166
2121
  });
2167
2122
  const columnNames = iterare(finalColumns).map(i => this[_fields][i]?.C2()).join(',');
2168
- const sql = format(`
2123
+ const sql = formatDialect(`
2169
2124
  ${this[_dbType] === DBType.Mysql ? '' : 'INSERT OR'} REPLACE INTO
2170
2125
  ${tableName}
2171
2126
  (${columnNames})
2172
2127
  VALUES ${questMarks};
2173
- `);
2128
+ `, { dialect: this[_formatDialect] });
2174
2129
  sqls.push({ sql, params });
2175
2130
  break;
2176
2131
  }
@@ -2208,12 +2163,12 @@ export class SqlService {
2208
2163
  return `(${questMark.join(',')})`;
2209
2164
  });
2210
2165
  const columnNames = iterare(finalColumns).map(i => this[_fields][i]?.C2()).join(',');
2211
- const sql = format(`
2166
+ const sql = formatDialect(`
2212
2167
  INSERT INTO
2213
2168
  ${tableName}
2214
2169
  (${columnNames})
2215
2170
  VALUES ${questMarks};
2216
- `);
2171
+ `, { dialect: this[_formatDialect] });
2217
2172
  sqls.push({ sql, params });
2218
2173
  break;
2219
2174
  }
@@ -2257,16 +2212,16 @@ export class SqlService {
2257
2212
  sqls.push(..._sqls);
2258
2213
  const columnNames = iterare(finalColumns).map(i => this[_fields][i]?.C2()).join(',');
2259
2214
  sqls.push({
2260
- sql: format(`
2215
+ sql: formatDialect(`
2261
2216
  INSERT INTO
2262
2217
  ${tableTemp}
2263
2218
  (${columnNames})
2264
2219
  VALUES ${questMarks};
2265
- `), params
2220
+ `, { dialect: this[_formatDialect] }), params
2266
2221
  });
2267
2222
  sqls.push({
2268
- sql: format(`INSERT INTO ${Sqlstring.escapeId(option.tableName)} (${columnNames})
2269
- SELECT ${columnNames} FROM ${tableTemp};`)
2223
+ sql: formatDialect(`INSERT INTO ${Sqlstring.escapeId(option.tableName)} (${columnNames})
2224
+ SELECT ${columnNames} FROM ${tableTemp};`, { dialect: this[_formatDialect] })
2270
2225
  });
2271
2226
  sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
2272
2227
  break;
@@ -2305,20 +2260,18 @@ export class SqlService {
2305
2260
  }
2306
2261
  else if (isArray) {
2307
2262
  const fn = async () => {
2308
- return await option?.dao?.transaction(SyncMode.Async, async () => {
2309
- const result = await excuteSplit(ExcuteSplitMode.AsyncTrust, datas, async (_data) => {
2310
- const sqls = this._insert(_data, option);
2311
- let result = 0n;
2312
- for (const { sql, params } of sqls) {
2313
- const dd = await option?.conn.execute(SyncMode.Async, sql, params);
2314
- if (dd.insertId) {
2315
- result += dd.insertId;
2316
- }
2263
+ const result = await excuteSplit(ExcuteSplitMode.AsyncTrust, datas, async (_data) => {
2264
+ const sqls = this._insert(_data, option);
2265
+ let result = 0n;
2266
+ for (const { sql, params } of sqls) {
2267
+ const dd = await option.conn.execute(SyncMode.Async, sql, params);
2268
+ if (dd.insertId) {
2269
+ result += dd.insertId;
2317
2270
  }
2318
- return result;
2319
- }, { everyLength: option?.every === true ? 1 : option?.maxDeal });
2271
+ }
2320
2272
  return result;
2321
- }, option?.conn);
2273
+ }, { everyLength: option?.every === true ? 1 : option?.maxDeal });
2274
+ return result;
2322
2275
  };
2323
2276
  return new Promise(async (resolve, reject) => {
2324
2277
  try {
@@ -2387,13 +2340,13 @@ export class SqlService {
2387
2340
  }
2388
2341
  });
2389
2342
  }
2390
- const sql = format(`UPDATE ${tableName} SET ${iterare(this[_columnsNoId])
2343
+ const sql = formatDialect(`UPDATE ${tableName} SET ${iterare(this[_columnsNoId])
2391
2344
  .filter(K => columnMaps[K].where.length > 0)
2392
2345
  .map(K => {
2393
2346
  params.push(...columnMaps[K].params);
2394
2347
  return `${this[_fields][K]?.C2()} = CASE ${columnMaps[K].where.join(' ')} ELSE ${this[_fields][K]?.C2()} END`;
2395
2348
  })
2396
- .join(',')};`);
2349
+ .join(',')};`, { dialect: this[_formatDialect] });
2397
2350
  sqls.push({ sql, params });
2398
2351
  return sqls;
2399
2352
  }
@@ -2482,14 +2435,14 @@ export class SqlService {
2482
2435
  if (this[_stateFileName] !== undefined && option.forceDelete !== true) {
2483
2436
  params.unshift(this[_deleteState]);
2484
2437
  sqls.push({
2485
- sql: format(`
2438
+ sql: formatDialect(`
2486
2439
  UPDATE ${tableNameESC} SET ${this[_fields][this[_stateFileName]]?.C2()} = ?
2487
2440
  WHERE ${whereSql};
2488
- `), params
2441
+ `, { dialect: this[_formatDialect] }), params
2489
2442
  });
2490
2443
  }
2491
2444
  else {
2492
- sqls.push({ sql: format(`DELETE FROM ${tableNameESC} WHERE ${whereSql};`), params });
2445
+ sqls.push({ sql: formatDialect(`DELETE FROM ${tableNameESC} WHERE ${whereSql};`, { dialect: this[_formatDialect] }), params });
2493
2446
  }
2494
2447
  }
2495
2448
  else {
@@ -2501,14 +2454,14 @@ export class SqlService {
2501
2454
  case DBType.Mysql: {
2502
2455
  if (this[_stateFileName] !== undefined && option.forceDelete !== true) {
2503
2456
  sqls.push({
2504
- sql: format(`UPDATE ${tableNameESC} a INNER JOIN ${tableTempESC} b ON ${delWhere.map(K => `a.${this[_fields][K]?.C2()} = b.${this[_fields][K]?.C2()}`).join(' AND ')}
2505
- SET a.${this[_fields][this[_stateFileName]]?.C2()} = ?;`),
2457
+ sql: formatDialect(`UPDATE ${tableNameESC} a INNER JOIN ${tableTempESC} b ON ${delWhere.map(K => `a.${this[_fields][K]?.C2()} = b.${this[_fields][K]?.C2()}`).join(' AND ')}
2458
+ SET a.${this[_fields][this[_stateFileName]]?.C2()} = ?;`, { dialect: this[_formatDialect] }),
2506
2459
  params: [this[_deleteState]]
2507
2460
  });
2508
2461
  }
2509
2462
  else {
2510
2463
  sqls.push({
2511
- sql: format(`DELETE a.* FROM ${tableNameESC} a INNER JOIN ${tableTempESC} b ON ${delWhere.map(K => `a.${this[_fields][K]?.C2()} = b.${this[_fields][K]?.C2()}`).join(' AND ')};`)
2464
+ sql: formatDialect(`DELETE a.* FROM ${tableNameESC} a INNER JOIN ${tableTempESC} b ON ${delWhere.map(K => `a.${this[_fields][K]?.C2()} = b.${this[_fields][K]?.C2()}`).join(' AND ')};`, { dialect: this[_formatDialect] })
2512
2465
  });
2513
2466
  }
2514
2467
  break;
@@ -2518,13 +2471,13 @@ export class SqlService {
2518
2471
  const columnNames = iterare(delWhere).map(K => this[_fields][K]?.C2()).join(',');
2519
2472
  if (this[_stateFileName] !== undefined && option.forceDelete !== true) {
2520
2473
  sqls.push({
2521
- sql: format(`UPDATE ${tableNameESC} SET ${this[_fields][this[_stateFileName]]?.C2()} = ?
2522
- WHERE (${columnNames}) IN (SELECT ${columnNames} FROM ${tableTempESC});`),
2474
+ sql: formatDialect(`UPDATE ${tableNameESC} SET ${this[_fields][this[_stateFileName]]?.C2()} = ?
2475
+ WHERE (${columnNames}) IN (SELECT ${columnNames} FROM ${tableTempESC});`, { dialect: this[_formatDialect] }),
2523
2476
  params: [this[_deleteState]]
2524
2477
  });
2525
2478
  }
2526
2479
  else {
2527
- sqls.push({ sql: format(`DELETE FROM ${tableNameESC} WHERE (${columnNames}) IN (SELECT ${columnNames} FROM ${tableTempESC});`) });
2480
+ sqls.push({ sql: formatDialect(`DELETE FROM ${tableNameESC} WHERE (${columnNames}) IN (SELECT ${columnNames} FROM ${tableTempESC});`, { dialect: this[_formatDialect] }) });
2528
2481
  }
2529
2482
  break;
2530
2483
  }
@@ -2615,13 +2568,13 @@ export class SqlService {
2615
2568
  let resultIndex = -1;
2616
2569
  if (option.mode === SelectMode.Common) {
2617
2570
  const params = new Array();
2618
- const whereSql = format(iterare(wheres).map(where => this[_transformer](where, option)).map(where => {
2571
+ const whereSql = formatDialect(iterare(wheres).map(where => this[_transformer](where, option)).map(where => {
2619
2572
  return `SELECT ${columns} FROM ${tableNameESC} a WHERE
2620
2573
  ${Object.entries(where).map(([K, V]) => {
2621
2574
  params.push(V);
2622
2575
  return `${this[_fields][K]?.C2()} = ?`;
2623
2576
  }).join(' AND ')}`;
2624
- }).join(' UNION ALL '));
2577
+ }).join(' UNION ALL '), { dialect: this[_formatDialect] });
2625
2578
  sqls.push({ sql: whereSql, params });
2626
2579
  resultIndex = 0;
2627
2580
  }
@@ -2631,7 +2584,7 @@ export class SqlService {
2631
2584
  const _sqls = this._createTable({ tableName: tableTemp, temp: true, columns: delWhere, data: wheres, index: 'all', id: 'none' });
2632
2585
  sqls.push(..._sqls);
2633
2586
  resultIndex = sqls.length;
2634
- sqls.push({ sql: format(`SELECT ${columns} FROM ${tableNameESC} a INNER JOIN ${tableTempESC} b ON ${delWhere.map(K => `a.${this[_fields][K]?.C2()} = b.${this[_fields][K]?.C2()}`).join(' AND ')};`) });
2587
+ sqls.push({ sql: formatDialect(`SELECT ${columns} FROM ${tableNameESC} a INNER JOIN ${tableTempESC} b ON ${delWhere.map(K => `a.${this[_fields][K]?.C2()} = b.${this[_fields][K]?.C2()}`).join(' AND ')};`, { dialect: this[_formatDialect] }) });
2635
2588
  sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
2636
2589
  }
2637
2590
  if (option.sync === SyncMode.Sync) {
@@ -2760,7 +2713,7 @@ export class SqlService {
2760
2713
  const _params = Object.assign({}, option.context, option.params);
2761
2714
  option.sql ?? (option.sql = globalThis[_sqlCache].load(this._matchSqlid(option.sqlId), { ctx: option.context, isCount: option.isCount, ..._params }));
2762
2715
  const params = [];
2763
- const sql = option.sql?.replace(/\:([A-Za-z0-9._]+)/g, (txt, key) => {
2716
+ const sql = formatDialect(option.sql?.replace(/\:([A-Za-z0-9._]+)/g, (txt, key) => {
2764
2717
  let V = LGet(_params, key);
2765
2718
  if (V) {
2766
2719
  if (V !== undefined) {
@@ -2785,7 +2738,7 @@ export class SqlService {
2785
2738
  return '?';
2786
2739
  }
2787
2740
  return txt;
2788
- });
2741
+ }), { dialect: this[_formatDialect] });
2789
2742
  if (option.sync === SyncMode.Sync) {
2790
2743
  const result = option.conn.query(SyncMode.Sync, sql, params);
2791
2744
  return this._select(option.selectResult, result, option.defValue, option.errorMsg, option.hump, option.mapper, option.mapperIfUndefined);
@@ -2807,7 +2760,7 @@ export class SqlService {
2807
2760
  const _params = Object.assign({}, option.context, option.params);
2808
2761
  option.sql ?? (option.sql = globalThis[_sqlCache].load(this._matchSqlid(option.sqlId), { ctx: option.context, ..._params }));
2809
2762
  const params = [];
2810
- const sql = option.sql?.replace(/\:(\w+)/g, (txt, key) => {
2763
+ const sql = formatDialect(option.sql?.replace(/\:(\w+)/g, (txt, key) => {
2811
2764
  let V = LGet(_params, key);
2812
2765
  if (V) {
2813
2766
  if (V !== undefined) {
@@ -2832,7 +2785,7 @@ export class SqlService {
2832
2785
  return '?';
2833
2786
  }
2834
2787
  return txt;
2835
- });
2788
+ }), { dialect: this[_formatDialect] });
2836
2789
  if (option.sync === SyncMode.Sync) {
2837
2790
  const result = option.conn.execute(SyncMode.Sync, sql, params);
2838
2791
  return result.affectedRows;
@@ -2875,6 +2828,8 @@ export class SqlService {
2875
2828
  size: 0,
2876
2829
  total: 0
2877
2830
  };
2831
+ option.pageNumber ?? (option.pageNumber = 1);
2832
+ option.pageSize ?? (option.pageSize = 0);
2878
2833
  Object.assign(option.params, {
2879
2834
  limitStart: calc(option.pageNumber).sub(1).mul(option.pageSize).over(),
2880
2835
  limitEnd: calc(option.pageSize).over(),
@@ -2947,7 +2902,7 @@ export class SqlService {
2947
2902
  selectResult: SelectResult.R_C_Assert
2948
2903
  });
2949
2904
  result.size = calc(result.total)
2950
- .add(option.pageSize - 1)
2905
+ .add(option.pageSize ?? 10 - 1)
2951
2906
  .div(option.pageSize)
2952
2907
  .round(0, 2)
2953
2908
  .over();
@@ -2976,6 +2931,170 @@ export class SqlService {
2976
2931
  });
2977
2932
  }
2978
2933
  }
2934
+ /**
2935
+ * 导出数据,可以为EJS-EXCEL直接使用
2936
+ * @param list
2937
+ * @returns
2938
+ */
2939
+ exp(list) {
2940
+ Throw.if(list.length === 0, 'not found data!');
2941
+ const columnTitles = new Array();
2942
+ const keys = this[_fields] ?
2943
+ iterare(Object.entries(this[_fields]))
2944
+ .filter(([K, F]) => (F.id !== true && F.exportable !== false) || (F.id === true && F.exportable === true))
2945
+ .map(([K, F]) => {
2946
+ columnTitles.push(F.comment ?? K);
2947
+ return K;
2948
+ }).toArray()
2949
+ : Object.keys(list[0]).filter(K => !this[_ids]?.includes(K));
2950
+ const title = this[_comment] ?? this[_tableName];
2951
+ const titleSpan = `A1:${ten2Any(keys.length)}1`;
2952
+ const datas = list.map(data => keys.map(k => data[k] ?? ''));
2953
+ return { title, titleSpan, columnTitles, datas };
2954
+ }
2955
+ /**
2956
+ * 导入数据的模板
2957
+ * @returns
2958
+ */
2959
+ imp() {
2960
+ Throw.if(!this[_fields], 'not set fields!');
2961
+ const columnTitles = new Array();
2962
+ const keys = iterare(Object.entries(this[_fields]))
2963
+ .filter(([K, F]) => (F.id !== true && F.exportable !== false) || (F.id === true && F.exportable === true))
2964
+ .map(([K, F]) => {
2965
+ columnTitles.push(F.comment ?? K);
2966
+ return K;
2967
+ }).toArray();
2968
+ const title = this[_comment] ?? this[_tableName];
2969
+ const titleSpan = `A1:${ten2Any(keys.length)}1`;
2970
+ return { title, titleSpan, columnTitles };
2971
+ }
2972
+ init(option) {
2973
+ var _e;
2974
+ const tableES = Sqlstring.escapeId(option.tableName);
2975
+ (_e = option).force ?? (_e.force = false);
2976
+ if (this[_dbType] === DBType.Sqlite) {
2977
+ if (option?.force) {
2978
+ option.conn.execute(SyncMode.Sync, `DROP TABLE IF EXISTS ${tableES};`);
2979
+ }
2980
+ const lastVersion = this[_sqlite_version] ?? '0.0.1';
2981
+ // 检查表
2982
+ const tableCheckResult = option.conn.pluck(SyncMode.Sync, `SELECT COUNT(1) t FROM sqlite_master WHERE TYPE = 'table' AND name = ?`, [option.tableName]);
2983
+ if (tableCheckResult) {
2984
+ // 旧版本
2985
+ const tableVersion = option.conn.pluck(SyncMode.Sync, 'SELECT ______version v from TABLE_VERSION WHERE ______tableName = ?', [option.tableName]);
2986
+ if (tableVersion && tableVersion < lastVersion) { // 发现需要升级的版本
2987
+ // 更新版本
2988
+ const columns = iterare(option.conn.query(SyncMode.Sync, `PRAGMA table_info(${tableES})`))
2989
+ .filter(c => this[_fields].hasOwnProperty(C2P(c.name, globalThis[_Hump])))
2990
+ .map(c => Sqlstring.escapeId(c.name))
2991
+ .join(',');
2992
+ const rtable = Sqlstring.escapeId(`${option.tableName}_${tableVersion.replace(/\./, '_')}`);
2993
+ option.conn.execute(SyncMode.Sync, `DROP TABLE IF EXISTS ${rtable};`);
2994
+ option.conn.execute(SyncMode.Sync, `ALTER TABLE ${tableES} RENAME TO ${rtable};`);
2995
+ option.conn.execute(SyncMode.Sync, `
2996
+ CREATE TABLE IF NOT EXISTS ${tableES}(
2997
+ ${Object.values(this[_fields]).map(K => K[DBType.Sqlite]()).join(',')}
2998
+ ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.C2()).join(',')})` : ''}
2999
+ );
3000
+ `);
3001
+ if (this[_index] && this[_index].length) {
3002
+ for (const index of this[_index]) {
3003
+ option.conn.execute(SyncMode.Sync, `CREATE INDEX ${Sqlstring.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${this[_fields][index]?.C2()}");`);
3004
+ }
3005
+ }
3006
+ option.conn.execute(SyncMode.Sync, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
3007
+ option.conn.execute(SyncMode.Sync, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
3008
+ option.conn.execute(SyncMode.Sync, `DROP TABLE IF EXISTS ${rtable};`);
3009
+ // 更新完毕,保存版本号
3010
+ option.conn.execute(SyncMode.Sync, 'UPDATE TABLE_VERSION SET ______version = ? WHERE ______tableName = ?', [option.tableName, lastVersion]);
3011
+ }
3012
+ else if (!tableVersion) { // 不需要升级情况:没有旧的版本号
3013
+ option.conn.execute(SyncMode.Sync, 'INSERT INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
3014
+ }
3015
+ }
3016
+ else { // 表不存在
3017
+ // 创建表
3018
+ option.conn.execute(SyncMode.Sync, `
3019
+ CREATE TABLE IF NOT EXISTS ${tableES} (
3020
+ ${Object.values(this[_fields]).map(K => K[DBType.Sqlite]()).join(',')}
3021
+ ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.C2()).join(',')})` : ''}
3022
+
3023
+ );
3024
+ `);
3025
+ if (this[_index] && this[_index].length) {
3026
+ for (const index of this[_index]) {
3027
+ option.conn.execute(SyncMode.Sync, `CREATE INDEX ${Sqlstring.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${this[_fields][index]?.C2()}");`);
3028
+ }
3029
+ }
3030
+ option.conn.execute(SyncMode.Sync, 'INSERT OR REPLACE INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
3031
+ }
3032
+ }
3033
+ else if (this[_dbType] === DBType.SqliteRemote) {
3034
+ return new Promise(async (resolve, reject) => {
3035
+ try {
3036
+ if (option?.force) {
3037
+ await option.conn.execute(SyncMode.Async, `DROP TABLE IF EXISTS ${tableES};`);
3038
+ }
3039
+ const lastVersion = this[_sqlite_version] ?? '0.0.1';
3040
+ // 检查表
3041
+ const tableCheckResult = await option.conn.pluck(SyncMode.Async, `SELECT COUNT(1) t FROM sqlite_master WHERE TYPE = 'table' AND name = ?`, [option.tableName]);
3042
+ if (tableCheckResult) {
3043
+ // 旧版本
3044
+ const tableVersion = await option.conn.pluck(SyncMode.Async, 'SELECT ______version v from TABLE_VERSION WHERE ______tableName = ?', [option.tableName]);
3045
+ if (tableVersion && tableVersion < lastVersion) { // 发现需要升级的版本
3046
+ // 更新版本
3047
+ const columns = iterare(await option.conn.query(SyncMode.Async, `PRAGMA table_info(${tableES})`))
3048
+ .filter(c => this[_fields].hasOwnProperty(C2P(c.name, globalThis[_Hump])))
3049
+ .map(c => Sqlstring.escapeId(c.name))
3050
+ .join(',');
3051
+ const rtable = `${option.tableName}_${tableVersion.replace(/\./, '_')}`;
3052
+ await option.conn.execute(SyncMode.Async, `DROP TABLE IF EXISTS ${rtable};`);
3053
+ await option.conn.execute(SyncMode.Async, `ALTER TABLE ${tableES} RENAME TO ${rtable};`);
3054
+ await option.conn.execute(SyncMode.Async, `
3055
+ CREATE TABLE IF NOT EXISTS ${tableES}(
3056
+ ${Object.values(this[_fields]).map(K => K[DBType.Sqlite]()).join(',')}
3057
+ ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.C2()).join(',')})` : ''}
3058
+ );
3059
+ `);
3060
+ if (this[_index] && this[_index].length) {
3061
+ for (const index of this[_index]) {
3062
+ await option.conn.execute(SyncMode.Async, `CREATE INDEX ${Sqlstring.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${this[_fields][index]?.C2()}");`);
3063
+ }
3064
+ }
3065
+ await option.conn.execute(SyncMode.Async, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
3066
+ await option.conn.execute(SyncMode.Async, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
3067
+ await option.conn.execute(SyncMode.Async, `DROP TABLE IF EXISTS ${rtable};`);
3068
+ // 更新完毕,保存版本号
3069
+ await option.conn.execute(SyncMode.Async, 'UPDATE TABLE_VERSION SET ______version = ? WHERE ______tableName = ?', [option.tableName, lastVersion]);
3070
+ }
3071
+ else if (!tableVersion) { // 不需要升级情况:没有旧的版本号
3072
+ await option.conn.execute(SyncMode.Async, 'INSERT INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
3073
+ }
3074
+ }
3075
+ else { // 表不存在
3076
+ // 创建表
3077
+ await option.conn.execute(SyncMode.Async, `
3078
+ CREATE TABLE IF NOT EXISTS ${tableES}(
3079
+ ${Object.values(this[_fields]).map(K => K[DBType.Sqlite]()).join(',')}
3080
+ ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.C2()).join(',')})` : ''}
3081
+ );
3082
+ `);
3083
+ if (this[_index] && this[_index].length) {
3084
+ for (const index of this[_index]) {
3085
+ await option.conn.execute(SyncMode.Async, `CREATE INDEX ${Sqlstring.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${Sqlstring.escapeId(option.tableName)} ("${this[_fields][index]?.C2()}");`);
3086
+ }
3087
+ }
3088
+ await option.conn.execute(SyncMode.Async, 'INSERT OR REPLACE INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
3089
+ }
3090
+ resolve();
3091
+ }
3092
+ catch (error) {
3093
+ reject(error);
3094
+ }
3095
+ });
3096
+ }
3097
+ }
2979
3098
  /**
2980
3099
  #创建表
2981
3100
  ** `tableName` 表名称
@@ -3020,16 +3139,16 @@ export class SqlService {
3020
3139
  tableName = Sqlstring.escapeId(tableName ?? this[_tableName]);
3021
3140
  switch (this[_dbType]) {
3022
3141
  case DBType.Mysql: {
3023
- let sql = format(`CREATE ${temp === true ? 'TEMPORARY' : ''} TABLE IF NOT EXISTS ${tableName}(
3142
+ let sql = formatDialect(`CREATE ${temp === true ? 'TEMPORARY' : ''} TABLE IF NOT EXISTS ${tableName}(
3024
3143
  ${columns.map(K => this[_fields][K][DBType.Mysql]()).join(',')}
3025
3144
  ${ids && ids.length ? `,PRIMARY KEY (${ids.map(i => this[_fields][i]?.C2()).join(',')}) USING BTREE ` : ''}
3026
3145
  ${indexs && indexs.length ? `,${indexs.map(i => `KEY ${this[_fields][i]?.C2()} (${this[_fields][i]?.C2()})`).join(',')} ` : ''}
3027
- ) ENGINE=MEMORY;`);
3146
+ ) ENGINE=MEMORY;`, { dialect: this[_formatDialect] });
3028
3147
  sqls.push({ sql });
3029
3148
  if (data && data.length > 0) {
3030
3149
  const params = [];
3031
3150
  let first = true;
3032
- sql = format(`INSERT INTO ${tableName} (${columns.map(c => this[_fields][c]?.C2()).join(',')})
3151
+ sql = formatDialect(`INSERT INTO ${tableName} (${columns.map(c => this[_fields][c]?.C2()).join(',')})
3033
3152
  ${(data).map(d => {
3034
3153
  const r = `SELECT ${Object.entries(d).map(([K, V]) => {
3035
3154
  params.push(V);
@@ -3037,28 +3156,28 @@ export class SqlService {
3037
3156
  }).join(',')}`;
3038
3157
  first = false;
3039
3158
  return r;
3040
- }).join(' UNION ALL ')}`);
3159
+ }).join(' UNION ALL ')}`, { dialect: this[_formatDialect] });
3041
3160
  sqls.push({ sql, params });
3042
3161
  }
3043
3162
  break;
3044
3163
  }
3045
3164
  case DBType.Sqlite:
3046
3165
  case DBType.SqliteRemote: {
3047
- let sql = format(`CREATE ${temp === true ? 'TEMPORARY' : ''} TABLE IF NOT EXISTS ${tableName}(
3166
+ let sql = formatDialect(`CREATE ${temp === true ? 'TEMPORARY' : ''} TABLE IF NOT EXISTS ${tableName}(
3048
3167
  ${columns.map(K => this[_fields][K][DBType.Sqlite]()).join(',')}
3049
3168
  ${ids && ids.length ? `,PRIMARY KEY (${ids.map(i => this[_fields][i]?.C2()).join(',')}) ` : ''}
3050
- );`);
3169
+ );`, { dialect: this[_formatDialect] });
3051
3170
  sqls.push({ sql });
3052
3171
  if (indexs) {
3053
3172
  for (const index of indexs) {
3054
- sql = format(`CREATE INDEX ${Sqlstring.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableName} (${this[_fields][index]?.C2()});`);
3173
+ sql = formatDialect(`CREATE INDEX ${Sqlstring.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableName} (${this[_fields][index]?.C2()});`, { dialect: this[_formatDialect] });
3055
3174
  sqls.push({ sql });
3056
3175
  }
3057
3176
  }
3058
3177
  if (data && data.length > 0) {
3059
3178
  const params = [];
3060
3179
  let first = true;
3061
- sql = format(`INSERT INTO ${tableName} (${columns.map(c => this[_fields][c]?.C2()).join(',')})
3180
+ sql = formatDialect(`INSERT INTO ${tableName} (${columns.map(c => this[_fields][c]?.C2()).join(',')})
3062
3181
  ${(data).map(d => {
3063
3182
  const r = `SELECT ${Object.entries(d).map(([K, V]) => {
3064
3183
  params.push(V);
@@ -3066,7 +3185,7 @@ export class SqlService {
3066
3185
  }).join(',')}`;
3067
3186
  first = false;
3068
3187
  return r;
3069
- }).join(' UNION ALL ')}`);
3188
+ }).join(' UNION ALL ')}`, { dialect: this[_formatDialect] });
3070
3189
  sqls.push({ sql, params });
3071
3190
  }
3072
3191
  break;
@@ -3130,6 +3249,12 @@ __decorate([
3130
3249
  __metadata("design:paramtypes", [Object]),
3131
3250
  __metadata("design:returntype", Object)
3132
3251
  ], SqlService.prototype, "page", null);
3252
+ __decorate([
3253
+ P(),
3254
+ __metadata("design:type", Function),
3255
+ __metadata("design:paramtypes", [Object]),
3256
+ __metadata("design:returntype", Object)
3257
+ ], SqlService.prototype, "init", null);
3133
3258
  /** 是否进行下一个动作 */
3134
3259
  const IF_PROCEED = function () {
3135
3260
  return function (_target, _propertyKey, descriptor) {