baja-lite 1.0.7 → 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/cjs/sql.js CHANGED
@@ -34,10 +34,10 @@ var __metadata = (this && this.__metadata) || function (k, v) {
34
34
  var __importDefault = (this && this.__importDefault) || function (mod) {
35
35
  return (mod && mod.__esModule) ? mod : { "default": mod };
36
36
  };
37
- var _a, _b, _c;
38
- var _d, _e, _f, _g;
37
+ var _b, _c, _d;
38
+ var _e, _f, _g, _h;
39
39
  Object.defineProperty(exports, "__esModule", { value: true });
40
- exports.SqlService = exports.DB = exports.Field = exports.SqlCache = exports.SqliteRemote = exports.SqliteRemoteConnection = exports.Sqlite = exports.Mysql = exports._defOption = exports.SqliteMemory = exports.ColumnMode = exports.SqlType = exports.SelectResult = exports.TemplateResult = exports.SelectMode = exports.DeleteMode = exports.InsertMode = exports.SyncMode = exports.MapperIfUndefined = exports.DBType = exports.logger = exports._fs = exports._path = exports._EventBus = exports._GlobalSqlOption = exports._Hump = exports._primaryDB = exports._dao = exports._sqlCache = void 0;
40
+ exports.SqlService = exports.DB = exports.Field = exports.SqlCache = exports.SqliteRemote = exports.SqliteRemoteConnection = exports.Sqlite = exports.Mysql = exports._defOption = exports.SqliteMemory = exports.ColumnMode = exports.SqlType = exports.SelectResult = exports.TemplateResult = exports.SelectMode = exports.DeleteMode = exports.InsertMode = exports.SyncMode = exports.MapperIfUndefined = exports.DBType = exports.logger = exports._fs = exports._path = exports._EventBus = exports._GlobalSqlOption = exports._Hump = exports._enums = exports._primaryDB = exports._dao = exports._sqlCache = void 0;
41
41
  exports.flatData = flatData;
42
42
  exports.DeclareClass = DeclareClass;
43
43
  exports.DeclareService = DeclareService;
@@ -63,6 +63,8 @@ const html_parse_stringify_1 = __importDefault(require("html-parse-stringify"));
63
63
  const convert_xml_1 = require("./convert-xml");
64
64
  const list_1 = require("./list");
65
65
  const lodash_get_1 = __importDefault(require("lodash.get"));
66
+ const msgpack_1 = require("@msgpack/msgpack");
67
+ BigInt.prototype.toJSON = function () { return this.toString(); };
66
68
  // #region 常量
67
69
  const _daoDBName = Symbol('dbName');
68
70
  const _tableName = Symbol('tableName');
@@ -70,6 +72,7 @@ const _className = Symbol('className');
70
72
  const _ClassName = Symbol('ClassName');
71
73
  const _vueName = Symbol('vueName');
72
74
  const _ids = Symbol('ids');
75
+ const _logicIds = Symbol('logicIds');
73
76
  const _columns = Symbol('columns');
74
77
  const _columnsNoId = Symbol('columnsNoId');
75
78
  const _fields = Symbol('fields');
@@ -78,10 +81,12 @@ const _deleteState = Symbol('deleteState');
78
81
  const _transformer = Symbol('transformer');
79
82
  const _index = Symbol('index');
80
83
  const _def = Symbol('def');
84
+ const _comment = Symbol('comment');
81
85
  exports._sqlCache = Symbol('sqlMap');
82
86
  exports._dao = Symbol('dao');
83
87
  exports._primaryDB = Symbol('primaryDB');
84
88
  const _dbType = Symbol('dbType');
89
+ const _formatDialect = Symbol('FormatDialect');
85
90
  const _sqlite_version = Symbol('sqlite_version');
86
91
  const _daoConnection = Symbol('daoConnection');
87
92
  const _inTransaction = Symbol('inTransaction');
@@ -90,6 +95,7 @@ const _sqliteRemoteName = Symbol('sqliteRemoteName');
90
95
  const _SqlOption = Symbol('SqlOption');
91
96
  const _resultMap = Symbol('resultMap');
92
97
  const _resultMap_SQLID = Symbol('resultMap_SQLID');
98
+ exports._enums = Symbol('_enums');
93
99
  exports._Hump = Symbol('Hump');
94
100
  exports._GlobalSqlOption = Symbol('GlobalSqlOption');
95
101
  exports._EventBus = Symbol('EventBus');
@@ -274,7 +280,7 @@ exports._defOption = {
274
280
  ;
275
281
  class MysqlConnection {
276
282
  constructor(conn) {
277
- this[_a] = false;
283
+ this[_b] = false;
278
284
  this[_daoConnection] = conn;
279
285
  }
280
286
  execute(sync, sql, params) {
@@ -457,7 +463,7 @@ class MysqlConnection {
457
463
  ;
458
464
  }
459
465
  }
460
- _a = _inTransaction;
466
+ _b = _inTransaction;
461
467
  class Mysql {
462
468
  constructor(pool) {
463
469
  this[_daoDB] = pool;
@@ -549,7 +555,7 @@ class Mysql {
549
555
  exports.Mysql = Mysql;
550
556
  class SqliteConnection {
551
557
  constructor(conn) {
552
- this[_b] = false;
558
+ this[_c] = false;
553
559
  this[_daoConnection] = conn;
554
560
  }
555
561
  execute(sync, sql, params) {
@@ -689,7 +695,7 @@ class SqliteConnection {
689
695
  realse(sync) {
690
696
  }
691
697
  }
692
- _b = _inTransaction;
698
+ _c = _inTransaction;
693
699
  class Sqlite {
694
700
  constructor(db) {
695
701
  this[_daoDB] = db;
@@ -755,7 +761,7 @@ class Sqlite {
755
761
  exports.Sqlite = Sqlite;
756
762
  class SqliteRemoteConnection {
757
763
  constructor(conn, name) {
758
- this[_c] = false;
764
+ this[_d] = false;
759
765
  this[_daoConnection] = conn;
760
766
  this[_sqliteRemoteName] = name;
761
767
  }
@@ -775,7 +781,8 @@ class SqliteRemoteConnection {
775
781
  }
776
782
  return new Promise(async (resolve, reject) => {
777
783
  try {
778
- const { affectedRows, insertId } = await this[_daoConnection].execute(this[_sqliteRemoteName], sql, params);
784
+ const data = await this[_daoConnection].execute((0, msgpack_1.encode)([this[_sqliteRemoteName], sql, params]));
785
+ const { affectedRows, insertId } = (0, msgpack_1.decode)(data);
779
786
  resolve({ affectedRows, insertId: insertId ? BigInt(insertId) : 0n });
780
787
  }
781
788
  catch (error) {
@@ -804,7 +811,8 @@ class SqliteRemoteConnection {
804
811
  }
805
812
  return new Promise(async (resolve, reject) => {
806
813
  try {
807
- const r = await this[_daoConnection].pluck(this[_sqliteRemoteName], sql, params);
814
+ const data = await this[_daoConnection].pluck((0, msgpack_1.encode)([this[_sqliteRemoteName], sql, params]));
815
+ const r = (0, msgpack_1.decode)(data);
808
816
  resolve(r);
809
817
  }
810
818
  catch (error) {
@@ -833,7 +841,8 @@ class SqliteRemoteConnection {
833
841
  }
834
842
  return new Promise(async (resolve, reject) => {
835
843
  try {
836
- const r = await this[_daoConnection].get(this[_sqliteRemoteName], sql, params);
844
+ const data = await this[_daoConnection].pluck((0, msgpack_1.encode)([this[_sqliteRemoteName], sql, params]));
845
+ const r = (0, msgpack_1.decode)(data);
837
846
  resolve(r);
838
847
  }
839
848
  catch (error) {
@@ -862,7 +871,8 @@ class SqliteRemoteConnection {
862
871
  }
863
872
  return new Promise(async (resolve, reject) => {
864
873
  try {
865
- const r = await this[_daoConnection].raw(this[_sqliteRemoteName], sql, params);
874
+ const data = await this[_daoConnection].pluck((0, msgpack_1.encode)([this[_sqliteRemoteName], sql, params]));
875
+ const r = (0, msgpack_1.decode)(data);
866
876
  resolve(r);
867
877
  }
868
878
  catch (error) {
@@ -891,7 +901,8 @@ class SqliteRemoteConnection {
891
901
  }
892
902
  return new Promise(async (resolve, reject) => {
893
903
  try {
894
- const r = await this[_daoConnection].query(this[_sqliteRemoteName], sql, params);
904
+ const data = await this[_daoConnection].pluck((0, msgpack_1.encode)([this[_sqliteRemoteName], sql, params]));
905
+ const r = (0, msgpack_1.decode)(data);
895
906
  resolve(r);
896
907
  }
897
908
  catch (error) {
@@ -908,7 +919,7 @@ class SqliteRemoteConnection {
908
919
  }
909
920
  }
910
921
  exports.SqliteRemoteConnection = SqliteRemoteConnection;
911
- _c = _inTransaction;
922
+ _d = _inTransaction;
912
923
  class SqliteRemote {
913
924
  constructor(db, name) {
914
925
  this[_daoDB] = db;
@@ -921,8 +932,11 @@ class SqliteRemote {
921
932
  }
922
933
  ;
923
934
  return new Promise(async (resolve, reject) => {
935
+ if (!this.connection) {
936
+ this.connection = new SqliteRemoteConnection(this[_daoDB], this[_sqliteRemoteName]);
937
+ }
924
938
  try {
925
- resolve(new SqliteRemoteConnection(this[_daoDB], this[_sqliteRemoteName]));
939
+ resolve(this.connection);
926
940
  }
927
941
  catch (error) {
928
942
  reject(error);
@@ -1251,6 +1265,31 @@ class Build {
1251
1265
  }
1252
1266
  };
1253
1267
  }
1268
+ /**
1269
+ * * PROBLEM_TYPE = 枚举名
1270
+ * * t.problemtype = 列名
1271
+ *
1272
+ * ```
1273
+ * {{#enumTag}} PROBLEM_TYPE(t.problemtype) {{/enumTag}}
1274
+ * ```
1275
+ */
1276
+ enum() {
1277
+ return (text) => {
1278
+ const matchs = text.match(/([a-zA-Z_]+)\(([^()]+)\)/);
1279
+ if (matchs) {
1280
+ const [_a, MapName, Column] = matchs;
1281
+ if (MapName && Column) {
1282
+ const map = globalThis[exports._enums].GlobalMap[MapName.trim()];
1283
+ if (map) {
1284
+ return ` CASE
1285
+ ${Object.entries(map).map(([k, v]) => `WHEN ${Column} = '${k}' THEN '${v}'`).join(' ')}
1286
+ END `;
1287
+ }
1288
+ }
1289
+ }
1290
+ return "''";
1291
+ };
1292
+ }
1254
1293
  }
1255
1294
  Build.page = 'COUNT(1) zccw1986 ';
1256
1295
  function replaceCdata(rawText) {
@@ -1271,10 +1310,10 @@ function replaceCdata(rawText) {
1271
1310
  return rawText;
1272
1311
  }
1273
1312
  function _flatData(result, i, length, keys, V) {
1274
- var _d;
1313
+ var _e;
1275
1314
  const key = keys[i];
1276
1315
  if (i < length) {
1277
- result[_d = key] ?? (result[_d] = {});
1316
+ result[_e = key] ?? (result[_e] = {});
1278
1317
  i++;
1279
1318
  _flatData(result[key], i, length, keys, V);
1280
1319
  }
@@ -1469,19 +1508,14 @@ class SqlCache {
1469
1508
  const buildParam = new Build(options.isCount === true, options.isSum === true, options);
1470
1509
  if (typeof sqlSource === 'function') {
1471
1510
  const _sql = sqlSource(options);
1472
- const sql = mustache_1.default.render(_sql, buildParam, this.sqlFNMap);
1473
- return (0, sql_formatter_1.format)(sql);
1511
+ return mustache_1.default.render(_sql, buildParam, this.sqlFNMap);
1474
1512
  }
1475
1513
  else if (typeof sqlSource === 'string') {
1476
- const sql = mustache_1.default.render(sqlSource, buildParam, this.sqlFNMap);
1477
- return (0, sql_formatter_1.format)(sql);
1514
+ return mustache_1.default.render(sqlSource, buildParam, this.sqlFNMap);
1478
1515
  }
1479
1516
  else if (typeof sqlSource === 'object') {
1480
1517
  const _sql = (0, convert_xml_1.convert)(sqlSource, options, matchSqlid, this.sqlMap);
1481
- console.log(_sql);
1482
- const sql = mustache_1.default.render(_sql, buildParam, this.sqlFNMap);
1483
- console.log(sql);
1484
- return (0, sql_formatter_1.format)(sql);
1518
+ return mustache_1.default.render(_sql, buildParam, this.sqlFNMap);
1485
1519
  }
1486
1520
  return '';
1487
1521
  }
@@ -1513,12 +1547,9 @@ function P(skipConn = false) {
1513
1547
  const option = args[0] = Object.assign({}, globalThis[exports._GlobalSqlOption], this[_SqlOption], args[0]);
1514
1548
  option.sync ?? (option.sync = SyncMode.Async);
1515
1549
  const dbName = option?.dbName ?? this[_daoDBName] ?? exports._primaryDB;
1516
- const dddx = this[_dbType];
1517
- exports.logger.info(dddx);
1518
1550
  option.dao = globalThis[exports._dao][this[_dbType]][dbName];
1519
1551
  error_1.Throw.if(!option.dao, `not found db:${String(dbName)}(${this[_dbType]})`);
1520
1552
  option.tableName = option?.tableName ?? this[_tableName];
1521
- const tableES = sqlstring_1.default.escapeId(option.tableName);
1522
1553
  if (this[_dbType] === DBType.Sqlite) {
1523
1554
  error_1.Throw.if(option.sync === SyncMode.Async, 'sqlite can not Async!');
1524
1555
  // 连接共享
@@ -1528,60 +1559,6 @@ function P(skipConn = false) {
1528
1559
  else {
1529
1560
  needRealseConn = false;
1530
1561
  }
1531
- if (skipConn === false) {
1532
- const lastVersion = this[_sqlite_version] ?? '0.0.1';
1533
- // 检查表
1534
- const tableCheckResult = option.conn.pluck(SyncMode.Sync, `SELECT COUNT(1) t FROM sqlite_master WHERE TYPE = 'table' AND name = ?`, [option.tableName]);
1535
- if (tableCheckResult) {
1536
- // 旧版本
1537
- const tableVersion = option.conn.pluck(SyncMode.Sync, 'SELECT ______version v from TABLE_VERSION WHERE ______tableName = ?', [option.tableName]);
1538
- if (tableVersion && tableVersion < lastVersion) { // 发现需要升级的版本
1539
- // 更新版本
1540
- const columns = (0, iterare_1.default)(option.conn.query(SyncMode.Sync, `PRAGMA table_info(${tableES})`))
1541
- .filter(c => this[_fields].hasOwnProperty((0, object_1.C2P)(c.name, globalThis[exports._Hump])))
1542
- .map(c => sqlstring_1.default.escapeId(c.name))
1543
- .join(',');
1544
- const rtable = sqlstring_1.default.escapeId(`${option.tableName}_${tableVersion.replace(/\./, '_')}`);
1545
- option.conn.execute(SyncMode.Sync, `DROP TABLE IF EXISTS ${rtable};`);
1546
- option.conn.execute(SyncMode.Sync, `ALTER TABLE ${tableES} RENAME TO ${rtable};`);
1547
- option.conn.execute(SyncMode.Sync, `
1548
- CREATE TABLE IF NOT EXISTS ${tableES}(
1549
- ${Object.values(this[_fields]).map(K => K[DBType.Sqlite]()).join(',')}
1550
- ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.C2()).join(',')})` : ''}
1551
- );
1552
- `);
1553
- if (this[_index] && this[_index].length) {
1554
- for (const index of this[_index]) {
1555
- option.conn.execute(SyncMode.Sync, `CREATE INDEX ${sqlstring_1.default.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${this[_fields][index]?.C2()}");`);
1556
- }
1557
- }
1558
- option.conn.execute(SyncMode.Sync, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
1559
- option.conn.execute(SyncMode.Sync, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
1560
- option.conn.execute(SyncMode.Sync, `DROP TABLE IF EXISTS ${rtable};`);
1561
- // 更新完毕,保存版本号
1562
- option.conn.execute(SyncMode.Sync, 'UPDATE TABLE_VERSION SET ______version = ? WHERE ______tableName = ?', [option.tableName, lastVersion]);
1563
- }
1564
- else if (!tableVersion) { // 不需要升级情况:没有旧的版本号
1565
- option.conn.execute(SyncMode.Sync, 'INSERT INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
1566
- }
1567
- }
1568
- else { // 表不存在
1569
- // 创建表
1570
- option.conn.execute(SyncMode.Sync, `
1571
- CREATE TABLE IF NOT EXISTS ${tableES} (
1572
- ${Object.values(this[_fields]).map(K => K[DBType.Sqlite]()).join(',')}
1573
- ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.C2()).join(',')})` : ''}
1574
-
1575
- );
1576
- `);
1577
- if (this[_index] && this[_index].length) {
1578
- for (const index of this[_index]) {
1579
- option.conn.execute(SyncMode.Sync, `CREATE INDEX ${sqlstring_1.default.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${this[_fields][index]?.C2()}");`);
1580
- }
1581
- }
1582
- option.conn.execute(SyncMode.Sync, 'INSERT OR REPLACE INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
1583
- }
1584
- }
1585
1562
  try {
1586
1563
  const result = fn.call(this, ...args);
1587
1564
  exports.logger.info(`${propertyKey}:${option.tableName}:use ${+new Date() - startTime}ms`);
@@ -1615,59 +1592,6 @@ function P(skipConn = false) {
1615
1592
  else {
1616
1593
  needRealseConn = false;
1617
1594
  }
1618
- if (skipConn === false) {
1619
- const lastVersion = this[_sqlite_version] ?? '0.0.1';
1620
- // 检查表
1621
- const tableCheckResult = await option.conn.pluck(SyncMode.Async, `SELECT COUNT(1) t FROM sqlite_master WHERE TYPE = 'table' AND name = ?`, [option.tableName]);
1622
- if (tableCheckResult) {
1623
- // 旧版本
1624
- const tableVersion = await option.conn.pluck(SyncMode.Async, 'SELECT ______version v from TABLE_VERSION WHERE ______tableName = ?', [option.tableName]);
1625
- if (tableVersion && tableVersion < lastVersion) { // 发现需要升级的版本
1626
- // 更新版本
1627
- const columns = (0, iterare_1.default)(await option.conn.query(SyncMode.Async, `PRAGMA table_info(${tableES})`))
1628
- .filter(c => this[_fields].hasOwnProperty((0, object_1.C2P)(c.name, globalThis[exports._Hump])))
1629
- .map(c => sqlstring_1.default.escapeId(c.name))
1630
- .join(',');
1631
- const rtable = `${option.tableName}_${tableVersion.replace(/\./, '_')}`;
1632
- await option.conn.execute(SyncMode.Async, `DROP TABLE IF EXISTS ${rtable};`);
1633
- await option.conn.execute(SyncMode.Async, `ALTER TABLE ${tableES} RENAME TO ${rtable};`);
1634
- await option.conn.execute(SyncMode.Async, `
1635
- CREATE TABLE IF NOT EXISTS ${tableES}(
1636
- ${Object.values(this[_fields]).map(K => K[DBType.Sqlite]()).join(',')}
1637
- ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.C2()).join(',')})` : ''}
1638
- );
1639
- `);
1640
- if (this[_index] && this[_index].length) {
1641
- for (const index of this[_index]) {
1642
- await option.conn.execute(SyncMode.Async, `CREATE INDEX ${sqlstring_1.default.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${this[_fields][index]?.C2()}");`);
1643
- }
1644
- }
1645
- await option.conn.execute(SyncMode.Async, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
1646
- await option.conn.execute(SyncMode.Async, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
1647
- await option.conn.execute(SyncMode.Async, `DROP TABLE IF EXISTS ${rtable};`);
1648
- // 更新完毕,保存版本号
1649
- await option.conn.execute(SyncMode.Async, 'UPDATE TABLE_VERSION SET ______version = ? WHERE ______tableName = ?', [option.tableName, lastVersion]);
1650
- }
1651
- else if (!tableVersion) { // 不需要升级情况:没有旧的版本号
1652
- await option.conn.execute(SyncMode.Async, 'INSERT INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
1653
- }
1654
- }
1655
- else { // 表不存在
1656
- // 创建表
1657
- await option.conn.execute(SyncMode.Async, `
1658
- CREATE TABLE IF NOT EXISTS ${tableES}(
1659
- ${Object.values(this[_fields]).map(K => K[DBType.Sqlite]()).join(',')}
1660
- ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.C2()).join(',')})` : ''}
1661
- );
1662
- `);
1663
- if (this[_index] && this[_index].length) {
1664
- for (const index of this[_index]) {
1665
- await option.conn.execute(SyncMode.Async, `CREATE INDEX ${sqlstring_1.default.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${sqlstring_1.default.escapeId(option.tableName)} ("${this[_fields][index]?.C2()}");`);
1666
- }
1667
- }
1668
- await option.conn.execute(SyncMode.Async, 'INSERT OR REPLACE INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
1669
- }
1670
- }
1671
1595
  try {
1672
1596
  const result = await fn.call(this, ...args);
1673
1597
  exports.logger.info(`${propertyKey}:${option.tableName}:use ${+new Date() - startTime}ms`);
@@ -1799,6 +1723,7 @@ const Field = (config) => {
1799
1723
  case SqlType.bigint: {
1800
1724
  field[DBType.Mysql] = () => `${field.C2()} bigint ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1801
1725
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} integer`;
1726
+ field.Data2SQL = (data) => BigInt(data ?? 0);
1802
1727
  break;
1803
1728
  }
1804
1729
  case SqlType.float: {
@@ -1834,26 +1759,31 @@ const Field = (config) => {
1834
1759
  case SqlType.date: {
1835
1760
  field[DBType.Mysql] = () => `${field.C2()} date ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1836
1761
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1762
+ field.Data2SQL = (data) => typeof data === 'string' ? new Date(data) : data;
1837
1763
  break;
1838
1764
  }
1839
1765
  case SqlType.time: {
1840
1766
  field[DBType.Mysql] = () => `${field.C2()} time ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1841
1767
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1768
+ field.Data2SQL = (data) => typeof data === 'string' ? new Date(data) : data;
1842
1769
  break;
1843
1770
  }
1844
1771
  case SqlType.year: {
1845
1772
  field[DBType.Mysql] = () => `${field.C2()} year ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1846
1773
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1774
+ field.Data2SQL = (data) => typeof data === 'string' ? new Date(data) : data;
1847
1775
  break;
1848
1776
  }
1849
1777
  case SqlType.datetime: {
1850
1778
  field[DBType.Mysql] = () => `${field.C2()} datetime ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1851
1779
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1780
+ field.Data2SQL = (data) => typeof data === 'string' ? new Date(data) : data;
1852
1781
  break;
1853
1782
  }
1854
1783
  case SqlType.timestamp: {
1855
1784
  field[DBType.Mysql] = () => `${field.C2()} timestamp ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1856
1785
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} integer`;
1786
+ field.Data2SQL = (data) => typeof data === 'string' ? +new Date(data) : data;
1857
1787
  break;
1858
1788
  }
1859
1789
  case SqlType.char: {
@@ -1967,6 +1897,7 @@ const Field = (config) => {
1967
1897
  let __columns = Reflect.getMetadata(_columns, object);
1968
1898
  let __columnsNoId = Reflect.getMetadata(_columnsNoId, object);
1969
1899
  let __ids = Reflect.getMetadata(_ids, object);
1900
+ let __logicIds = Reflect.getMetadata(_logicIds, object);
1970
1901
  let __index = Reflect.getMetadata(_index, object);
1971
1902
  let __def = Reflect.getMetadata(_def, object);
1972
1903
  if (!__fields) {
@@ -1985,16 +1916,23 @@ const Field = (config) => {
1985
1916
  else {
1986
1917
  __columnsNoId.push(propertyName);
1987
1918
  }
1919
+ if (field.logicId === true) {
1920
+ __logicIds.push(propertyName);
1921
+ }
1988
1922
  if (field.index === true) {
1989
1923
  __index.push(propertyName);
1990
1924
  }
1991
1925
  if (hasDef) {
1992
1926
  __def[propertyName] = field.def;
1993
1927
  }
1928
+ if (field.comment) {
1929
+ __def[propertyName] = field.comment;
1930
+ }
1994
1931
  Reflect.defineMetadata(_fields, __fields, object);
1995
1932
  Reflect.defineMetadata(_columns, __columns, object);
1996
1933
  Reflect.defineMetadata(_columnsNoId, __columnsNoId, object);
1997
1934
  Reflect.defineMetadata(_ids, __ids, object);
1935
+ Reflect.defineMetadata(_logicIds, __logicIds, object);
1998
1936
  Reflect.defineMetadata(_index, __index, object);
1999
1937
  Reflect.defineMetadata(_def, __def, object);
2000
1938
  if (field.hasOwnProperty('logicDelete')) {
@@ -2004,44 +1942,58 @@ const Field = (config) => {
2004
1942
  };
2005
1943
  };
2006
1944
  exports.Field = Field;
1945
+ const formatDialects = {
1946
+ [DBType.Mysql]: sql_formatter_1.mysql,
1947
+ [DBType.Sqlite]: sql_formatter_1.sqlite,
1948
+ [DBType.SqliteRemote]: sql_formatter_1.sqlite
1949
+ };
2007
1950
  const DB = (config) => {
2008
1951
  return function (constructor) {
2009
- var _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w;
1952
+ var _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;
2010
1953
  const __ids = Reflect.getMetadata(_ids, config.clz.prototype) || new Array;
1954
+ const __logicIds = Reflect.getMetadata(_logicIds, config.clz.prototype) || new Array;
2011
1955
  const __fields = Reflect.getMetadata(_fields, config.clz.prototype);
2012
1956
  const __columns = Reflect.getMetadata(_columns, config.clz.prototype);
2013
- const __columnsNoId = __columns.filter((c) => __ids.includes(c) === false);
1957
+ const __columnsNoId = Reflect.getMetadata(_columnsNoId, config.clz.prototype);
2014
1958
  const __stateFileName = Reflect.getMetadata(_stateFileName, config.clz.prototype);
2015
1959
  const __deleteState = Reflect.getMetadata(_deleteState, config.clz.prototype);
2016
1960
  const __index = Reflect.getMetadata(_index, config.clz.prototype);
2017
1961
  const __def = Reflect.getMetadata(_def, config.clz.prototype);
1962
+ const __dbType = config.dbType ?? DBType.Mysql;
1963
+ const __formatDialect = formatDialects[__dbType];
2018
1964
  const className = config.tableName?.replace(/_(\w)/g, (a, b) => b.toUpperCase());
2019
1965
  const ClassName = className?.replace(/\w/, (v) => v.toUpperCase());
2020
1966
  const vueName = config.tableName?.replace(/_/g, '-');
2021
- return _w = class extends constructor {
1967
+ return _0 = class extends constructor {
2022
1968
  constructor() {
2023
1969
  super(...arguments);
2024
- this[_d] = config.tableName;
2025
- this[_e] = className;
2026
- this[_f] = ClassName;
2027
- this[_g] = vueName;
2028
- this[_h] = config.dbName;
2029
- this[_j] = config.dbType ?? DBType.Mysql;
2030
- this[_k] = config.sqliteVersion;
2031
- this[_l] = Object.assign({}, exports._defOption, config);
2032
- this[_m] = __ids;
2033
- this[_o] = __fields;
2034
- this[_p] = __columns;
2035
- this[_q] = __columnsNoId;
2036
- this[_r] = __index;
2037
- this[_s] = __def;
2038
- this[_t] = __stateFileName;
2039
- this[_u] = __deleteState;
2040
- this[_v] = (data, option) => {
1970
+ this[_e] = config.tableName;
1971
+ this[_f] = className;
1972
+ this[_g] = ClassName;
1973
+ this[_h] = vueName;
1974
+ this[_j] = config.dbName;
1975
+ this[_k] = __dbType;
1976
+ this[_l] = __formatDialect;
1977
+ this[_m] = config.sqliteVersion;
1978
+ this[_o] = Object.assign({}, exports._defOption, config);
1979
+ this[_p] = __ids;
1980
+ this[_q] = __logicIds;
1981
+ this[_r] = __fields;
1982
+ this[_s] = __columns;
1983
+ this[_t] = __columnsNoId;
1984
+ this[_u] = __index;
1985
+ this[_v] = __def;
1986
+ this[_w] = config.comment;
1987
+ this[_x] = __stateFileName;
1988
+ this[_y] = __deleteState;
1989
+ this[_z] = (data, option) => {
2041
1990
  return Object.fromEntries((0, iterare_1.default)(option?.skipId === true ? __columnsNoId : __columns)
2042
1991
  .map(K => [K, FieldFilter(K, data[K], __def, __fields[K].uuid === true || __fields[K].uuidShort === true, option)])
2043
1992
  .filter(data => {
2044
1993
  if (data[1][0] === 1) {
1994
+ if (__fields[data[0]].Data2SQL) {
1995
+ data[1][1] = __fields[data[0]].Data2SQL(data[1][1]);
1996
+ }
2045
1997
  if (option?.onFieldExists) {
2046
1998
  option.onFieldExists(data[0], data[1][1]);
2047
1999
  }
@@ -2056,24 +2008,27 @@ const DB = (config) => {
2056
2008
  };
2057
2009
  }
2058
2010
  },
2059
- _d = _tableName,
2060
- _e = _className,
2061
- _f = _ClassName,
2062
- _g = _vueName,
2063
- _h = _daoDBName,
2064
- _j = _dbType,
2065
- _k = _sqlite_version,
2066
- _l = _SqlOption,
2067
- _m = _ids,
2068
- _o = _fields,
2069
- _p = _columns,
2070
- _q = _columnsNoId,
2071
- _r = _index,
2072
- _s = _def,
2073
- _t = _stateFileName,
2074
- _u = _deleteState,
2075
- _v = _transformer,
2076
- _w;
2011
+ _e = _tableName,
2012
+ _f = _className,
2013
+ _g = _ClassName,
2014
+ _h = _vueName,
2015
+ _j = _daoDBName,
2016
+ _k = _dbType,
2017
+ _l = _formatDialect,
2018
+ _m = _sqlite_version,
2019
+ _o = _SqlOption,
2020
+ _p = _ids,
2021
+ _q = _logicIds,
2022
+ _r = _fields,
2023
+ _s = _columns,
2024
+ _t = _columnsNoId,
2025
+ _u = _index,
2026
+ _v = _def,
2027
+ _w = _comment,
2028
+ _x = _stateFileName,
2029
+ _y = _deleteState,
2030
+ _z = _transformer,
2031
+ _0;
2077
2032
  };
2078
2033
  };
2079
2034
  exports.DB = DB;
@@ -2170,10 +2125,10 @@ class SqlService {
2170
2125
  return `SELECT ${questMark.join(',')} FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM ${tableName} WHERE ${where})`;
2171
2126
  });
2172
2127
  const columnNames = (0, iterare_1.default)(finalColumns).map(i => this[_fields][i]?.C2()).join(',');
2173
- const sql = (0, sql_formatter_1.format)(`INSERT INTO
2128
+ const sql = (0, sql_formatter_1.formatDialect)(`INSERT INTO
2174
2129
  ${tableName}
2175
2130
  (${columnNames})
2176
- ${questMarks.join(' UNION ALL ')};`);
2131
+ ${questMarks.join(' UNION ALL ')};`, { dialect: this[_formatDialect] });
2177
2132
  sqls.push({ sql, params });
2178
2133
  break;
2179
2134
  }
@@ -2211,12 +2166,12 @@ class SqlService {
2211
2166
  return `(${questMark.join(',')})`;
2212
2167
  });
2213
2168
  const columnNames = (0, iterare_1.default)(finalColumns).map(i => this[_fields][i]?.C2()).join(',');
2214
- const sql = (0, sql_formatter_1.format)(`
2169
+ const sql = (0, sql_formatter_1.formatDialect)(`
2215
2170
  ${this[_dbType] === DBType.Mysql ? '' : 'INSERT OR'} REPLACE INTO
2216
2171
  ${tableName}
2217
2172
  (${columnNames})
2218
2173
  VALUES ${questMarks};
2219
- `);
2174
+ `, { dialect: this[_formatDialect] });
2220
2175
  sqls.push({ sql, params });
2221
2176
  break;
2222
2177
  }
@@ -2254,12 +2209,12 @@ class SqlService {
2254
2209
  return `(${questMark.join(',')})`;
2255
2210
  });
2256
2211
  const columnNames = (0, iterare_1.default)(finalColumns).map(i => this[_fields][i]?.C2()).join(',');
2257
- const sql = (0, sql_formatter_1.format)(`
2212
+ const sql = (0, sql_formatter_1.formatDialect)(`
2258
2213
  INSERT INTO
2259
2214
  ${tableName}
2260
2215
  (${columnNames})
2261
2216
  VALUES ${questMarks};
2262
- `);
2217
+ `, { dialect: this[_formatDialect] });
2263
2218
  sqls.push({ sql, params });
2264
2219
  break;
2265
2220
  }
@@ -2303,16 +2258,16 @@ class SqlService {
2303
2258
  sqls.push(..._sqls);
2304
2259
  const columnNames = (0, iterare_1.default)(finalColumns).map(i => this[_fields][i]?.C2()).join(',');
2305
2260
  sqls.push({
2306
- sql: (0, sql_formatter_1.format)(`
2261
+ sql: (0, sql_formatter_1.formatDialect)(`
2307
2262
  INSERT INTO
2308
2263
  ${tableTemp}
2309
2264
  (${columnNames})
2310
2265
  VALUES ${questMarks};
2311
- `), params
2266
+ `, { dialect: this[_formatDialect] }), params
2312
2267
  });
2313
2268
  sqls.push({
2314
- sql: (0, sql_formatter_1.format)(`INSERT INTO ${sqlstring_1.default.escapeId(option.tableName)} (${columnNames})
2315
- SELECT ${columnNames} FROM ${tableTemp};`)
2269
+ sql: (0, sql_formatter_1.formatDialect)(`INSERT INTO ${sqlstring_1.default.escapeId(option.tableName)} (${columnNames})
2270
+ SELECT ${columnNames} FROM ${tableTemp};`, { dialect: this[_formatDialect] })
2316
2271
  });
2317
2272
  sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
2318
2273
  break;
@@ -2351,20 +2306,18 @@ class SqlService {
2351
2306
  }
2352
2307
  else if (isArray) {
2353
2308
  const fn = async () => {
2354
- return await option?.dao?.transaction(SyncMode.Async, async () => {
2355
- const result = await (0, fn_1.excuteSplit)(fn_1.ExcuteSplitMode.AsyncTrust, datas, async (_data) => {
2356
- const sqls = this._insert(_data, option);
2357
- let result = 0n;
2358
- for (const { sql, params } of sqls) {
2359
- const dd = await option?.conn.execute(SyncMode.Async, sql, params);
2360
- if (dd.insertId) {
2361
- result += dd.insertId;
2362
- }
2309
+ const result = await (0, fn_1.excuteSplit)(fn_1.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;
2363
2316
  }
2364
- return result;
2365
- }, { everyLength: option?.every === true ? 1 : option?.maxDeal });
2317
+ }
2366
2318
  return result;
2367
- }, option?.conn);
2319
+ }, { everyLength: option?.every === true ? 1 : option?.maxDeal });
2320
+ return result;
2368
2321
  };
2369
2322
  return new Promise(async (resolve, reject) => {
2370
2323
  try {
@@ -2433,13 +2386,13 @@ class SqlService {
2433
2386
  }
2434
2387
  });
2435
2388
  }
2436
- const sql = (0, sql_formatter_1.format)(`UPDATE ${tableName} SET ${(0, iterare_1.default)(this[_columnsNoId])
2389
+ const sql = (0, sql_formatter_1.formatDialect)(`UPDATE ${tableName} SET ${(0, iterare_1.default)(this[_columnsNoId])
2437
2390
  .filter(K => columnMaps[K].where.length > 0)
2438
2391
  .map(K => {
2439
2392
  params.push(...columnMaps[K].params);
2440
2393
  return `${this[_fields][K]?.C2()} = CASE ${columnMaps[K].where.join(' ')} ELSE ${this[_fields][K]?.C2()} END`;
2441
2394
  })
2442
- .join(',')};`);
2395
+ .join(',')};`, { dialect: this[_formatDialect] });
2443
2396
  sqls.push({ sql, params });
2444
2397
  return sqls;
2445
2398
  }
@@ -2528,14 +2481,14 @@ class SqlService {
2528
2481
  if (this[_stateFileName] !== undefined && option.forceDelete !== true) {
2529
2482
  params.unshift(this[_deleteState]);
2530
2483
  sqls.push({
2531
- sql: (0, sql_formatter_1.format)(`
2484
+ sql: (0, sql_formatter_1.formatDialect)(`
2532
2485
  UPDATE ${tableNameESC} SET ${this[_fields][this[_stateFileName]]?.C2()} = ?
2533
2486
  WHERE ${whereSql};
2534
- `), params
2487
+ `, { dialect: this[_formatDialect] }), params
2535
2488
  });
2536
2489
  }
2537
2490
  else {
2538
- sqls.push({ sql: (0, sql_formatter_1.format)(`DELETE FROM ${tableNameESC} WHERE ${whereSql};`), params });
2491
+ sqls.push({ sql: (0, sql_formatter_1.formatDialect)(`DELETE FROM ${tableNameESC} WHERE ${whereSql};`, { dialect: this[_formatDialect] }), params });
2539
2492
  }
2540
2493
  }
2541
2494
  else {
@@ -2547,14 +2500,14 @@ class SqlService {
2547
2500
  case DBType.Mysql: {
2548
2501
  if (this[_stateFileName] !== undefined && option.forceDelete !== true) {
2549
2502
  sqls.push({
2550
- sql: (0, sql_formatter_1.format)(`UPDATE ${tableNameESC} a INNER JOIN ${tableTempESC} b ON ${delWhere.map(K => `a.${this[_fields][K]?.C2()} = b.${this[_fields][K]?.C2()}`).join(' AND ')}
2551
- SET a.${this[_fields][this[_stateFileName]]?.C2()} = ?;`),
2503
+ sql: (0, sql_formatter_1.formatDialect)(`UPDATE ${tableNameESC} a INNER JOIN ${tableTempESC} b ON ${delWhere.map(K => `a.${this[_fields][K]?.C2()} = b.${this[_fields][K]?.C2()}`).join(' AND ')}
2504
+ SET a.${this[_fields][this[_stateFileName]]?.C2()} = ?;`, { dialect: this[_formatDialect] }),
2552
2505
  params: [this[_deleteState]]
2553
2506
  });
2554
2507
  }
2555
2508
  else {
2556
2509
  sqls.push({
2557
- sql: (0, sql_formatter_1.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 ')};`)
2510
+ sql: (0, sql_formatter_1.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] })
2558
2511
  });
2559
2512
  }
2560
2513
  break;
@@ -2564,13 +2517,13 @@ class SqlService {
2564
2517
  const columnNames = (0, iterare_1.default)(delWhere).map(K => this[_fields][K]?.C2()).join(',');
2565
2518
  if (this[_stateFileName] !== undefined && option.forceDelete !== true) {
2566
2519
  sqls.push({
2567
- sql: (0, sql_formatter_1.format)(`UPDATE ${tableNameESC} SET ${this[_fields][this[_stateFileName]]?.C2()} = ?
2568
- WHERE (${columnNames}) IN (SELECT ${columnNames} FROM ${tableTempESC});`),
2520
+ sql: (0, sql_formatter_1.formatDialect)(`UPDATE ${tableNameESC} SET ${this[_fields][this[_stateFileName]]?.C2()} = ?
2521
+ WHERE (${columnNames}) IN (SELECT ${columnNames} FROM ${tableTempESC});`, { dialect: this[_formatDialect] }),
2569
2522
  params: [this[_deleteState]]
2570
2523
  });
2571
2524
  }
2572
2525
  else {
2573
- sqls.push({ sql: (0, sql_formatter_1.format)(`DELETE FROM ${tableNameESC} WHERE (${columnNames}) IN (SELECT ${columnNames} FROM ${tableTempESC});`) });
2526
+ sqls.push({ sql: (0, sql_formatter_1.formatDialect)(`DELETE FROM ${tableNameESC} WHERE (${columnNames}) IN (SELECT ${columnNames} FROM ${tableTempESC});`, { dialect: this[_formatDialect] }) });
2574
2527
  }
2575
2528
  break;
2576
2529
  }
@@ -2661,13 +2614,13 @@ class SqlService {
2661
2614
  let resultIndex = -1;
2662
2615
  if (option.mode === SelectMode.Common) {
2663
2616
  const params = new Array();
2664
- const whereSql = (0, sql_formatter_1.format)((0, iterare_1.default)(wheres).map(where => this[_transformer](where, option)).map(where => {
2617
+ const whereSql = (0, sql_formatter_1.formatDialect)((0, iterare_1.default)(wheres).map(where => this[_transformer](where, option)).map(where => {
2665
2618
  return `SELECT ${columns} FROM ${tableNameESC} a WHERE
2666
2619
  ${Object.entries(where).map(([K, V]) => {
2667
2620
  params.push(V);
2668
2621
  return `${this[_fields][K]?.C2()} = ?`;
2669
2622
  }).join(' AND ')}`;
2670
- }).join(' UNION ALL '));
2623
+ }).join(' UNION ALL '), { dialect: this[_formatDialect] });
2671
2624
  sqls.push({ sql: whereSql, params });
2672
2625
  resultIndex = 0;
2673
2626
  }
@@ -2677,7 +2630,7 @@ class SqlService {
2677
2630
  const _sqls = this._createTable({ tableName: tableTemp, temp: true, columns: delWhere, data: wheres, index: 'all', id: 'none' });
2678
2631
  sqls.push(..._sqls);
2679
2632
  resultIndex = sqls.length;
2680
- sqls.push({ sql: (0, sql_formatter_1.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 ')};`) });
2633
+ sqls.push({ sql: (0, sql_formatter_1.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] }) });
2681
2634
  sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
2682
2635
  }
2683
2636
  if (option.sync === SyncMode.Sync) {
@@ -2806,7 +2759,7 @@ class SqlService {
2806
2759
  const _params = Object.assign({}, option.context, option.params);
2807
2760
  option.sql ?? (option.sql = globalThis[exports._sqlCache].load(this._matchSqlid(option.sqlId), { ctx: option.context, isCount: option.isCount, ..._params }));
2808
2761
  const params = [];
2809
- const sql = option.sql?.replace(/\:([A-Za-z0-9._]+)/g, (txt, key) => {
2762
+ const sql = (0, sql_formatter_1.formatDialect)(option.sql?.replace(/\:([A-Za-z0-9._]+)/g, (txt, key) => {
2810
2763
  let V = (0, lodash_get_1.default)(_params, key);
2811
2764
  if (V) {
2812
2765
  if (V !== undefined) {
@@ -2831,7 +2784,7 @@ class SqlService {
2831
2784
  return '?';
2832
2785
  }
2833
2786
  return txt;
2834
- });
2787
+ }), { dialect: this[_formatDialect] });
2835
2788
  if (option.sync === SyncMode.Sync) {
2836
2789
  const result = option.conn.query(SyncMode.Sync, sql, params);
2837
2790
  return this._select(option.selectResult, result, option.defValue, option.errorMsg, option.hump, option.mapper, option.mapperIfUndefined);
@@ -2853,7 +2806,7 @@ class SqlService {
2853
2806
  const _params = Object.assign({}, option.context, option.params);
2854
2807
  option.sql ?? (option.sql = globalThis[exports._sqlCache].load(this._matchSqlid(option.sqlId), { ctx: option.context, ..._params }));
2855
2808
  const params = [];
2856
- const sql = option.sql?.replace(/\:(\w+)/g, (txt, key) => {
2809
+ const sql = (0, sql_formatter_1.formatDialect)(option.sql?.replace(/\:(\w+)/g, (txt, key) => {
2857
2810
  let V = (0, lodash_get_1.default)(_params, key);
2858
2811
  if (V) {
2859
2812
  if (V !== undefined) {
@@ -2878,7 +2831,7 @@ class SqlService {
2878
2831
  return '?';
2879
2832
  }
2880
2833
  return txt;
2881
- });
2834
+ }), { dialect: this[_formatDialect] });
2882
2835
  if (option.sync === SyncMode.Sync) {
2883
2836
  const result = option.conn.execute(SyncMode.Sync, sql, params);
2884
2837
  return result.affectedRows;
@@ -2921,6 +2874,8 @@ class SqlService {
2921
2874
  size: 0,
2922
2875
  total: 0
2923
2876
  };
2877
+ option.pageNumber ?? (option.pageNumber = 1);
2878
+ option.pageSize ?? (option.pageSize = 0);
2924
2879
  Object.assign(option.params, {
2925
2880
  limitStart: (0, math_1.calc)(option.pageNumber).sub(1).mul(option.pageSize).over(),
2926
2881
  limitEnd: (0, math_1.calc)(option.pageSize).over(),
@@ -2993,7 +2948,7 @@ class SqlService {
2993
2948
  selectResult: SelectResult.R_C_Assert
2994
2949
  });
2995
2950
  result.size = (0, math_1.calc)(result.total)
2996
- .add(option.pageSize - 1)
2951
+ .add(option.pageSize ?? 10 - 1)
2997
2952
  .div(option.pageSize)
2998
2953
  .round(0, 2)
2999
2954
  .over();
@@ -3022,6 +2977,170 @@ class SqlService {
3022
2977
  });
3023
2978
  }
3024
2979
  }
2980
+ /**
2981
+ * 导出数据,可以为EJS-EXCEL直接使用
2982
+ * @param list
2983
+ * @returns
2984
+ */
2985
+ exp(list) {
2986
+ error_1.Throw.if(list.length === 0, 'not found data!');
2987
+ const columnTitles = new Array();
2988
+ const keys = this[_fields] ?
2989
+ (0, iterare_1.default)(Object.entries(this[_fields]))
2990
+ .filter(([K, F]) => (F.id !== true && F.exportable !== false) || (F.id === true && F.exportable === true))
2991
+ .map(([K, F]) => {
2992
+ columnTitles.push(F.comment ?? K);
2993
+ return K;
2994
+ }).toArray()
2995
+ : Object.keys(list[0]).filter(K => !this[_ids]?.includes(K));
2996
+ const title = this[_comment] ?? this[_tableName];
2997
+ const titleSpan = `A1:${(0, math_1.ten2Any)(keys.length)}1`;
2998
+ const datas = list.map(data => keys.map(k => data[k] ?? ''));
2999
+ return { title, titleSpan, columnTitles, datas };
3000
+ }
3001
+ /**
3002
+ * 导入数据的模板
3003
+ * @returns
3004
+ */
3005
+ imp() {
3006
+ error_1.Throw.if(!this[_fields], 'not set fields!');
3007
+ const columnTitles = new Array();
3008
+ const keys = (0, iterare_1.default)(Object.entries(this[_fields]))
3009
+ .filter(([K, F]) => (F.id !== true && F.exportable !== false) || (F.id === true && F.exportable === true))
3010
+ .map(([K, F]) => {
3011
+ columnTitles.push(F.comment ?? K);
3012
+ return K;
3013
+ }).toArray();
3014
+ const title = this[_comment] ?? this[_tableName];
3015
+ const titleSpan = `A1:${(0, math_1.ten2Any)(keys.length)}1`;
3016
+ return { title, titleSpan, columnTitles };
3017
+ }
3018
+ init(option) {
3019
+ var _e;
3020
+ const tableES = sqlstring_1.default.escapeId(option.tableName);
3021
+ (_e = option).force ?? (_e.force = false);
3022
+ if (this[_dbType] === DBType.Sqlite) {
3023
+ if (option?.force) {
3024
+ option.conn.execute(SyncMode.Sync, `DROP TABLE IF EXISTS ${tableES};`);
3025
+ }
3026
+ const lastVersion = this[_sqlite_version] ?? '0.0.1';
3027
+ // 检查表
3028
+ const tableCheckResult = option.conn.pluck(SyncMode.Sync, `SELECT COUNT(1) t FROM sqlite_master WHERE TYPE = 'table' AND name = ?`, [option.tableName]);
3029
+ if (tableCheckResult) {
3030
+ // 旧版本
3031
+ const tableVersion = option.conn.pluck(SyncMode.Sync, 'SELECT ______version v from TABLE_VERSION WHERE ______tableName = ?', [option.tableName]);
3032
+ if (tableVersion && tableVersion < lastVersion) { // 发现需要升级的版本
3033
+ // 更新版本
3034
+ const columns = (0, iterare_1.default)(option.conn.query(SyncMode.Sync, `PRAGMA table_info(${tableES})`))
3035
+ .filter(c => this[_fields].hasOwnProperty((0, object_1.C2P)(c.name, globalThis[exports._Hump])))
3036
+ .map(c => sqlstring_1.default.escapeId(c.name))
3037
+ .join(',');
3038
+ const rtable = sqlstring_1.default.escapeId(`${option.tableName}_${tableVersion.replace(/\./, '_')}`);
3039
+ option.conn.execute(SyncMode.Sync, `DROP TABLE IF EXISTS ${rtable};`);
3040
+ option.conn.execute(SyncMode.Sync, `ALTER TABLE ${tableES} RENAME TO ${rtable};`);
3041
+ option.conn.execute(SyncMode.Sync, `
3042
+ CREATE TABLE IF NOT EXISTS ${tableES}(
3043
+ ${Object.values(this[_fields]).map(K => K[DBType.Sqlite]()).join(',')}
3044
+ ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.C2()).join(',')})` : ''}
3045
+ );
3046
+ `);
3047
+ if (this[_index] && this[_index].length) {
3048
+ for (const index of this[_index]) {
3049
+ option.conn.execute(SyncMode.Sync, `CREATE INDEX ${sqlstring_1.default.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${this[_fields][index]?.C2()}");`);
3050
+ }
3051
+ }
3052
+ option.conn.execute(SyncMode.Sync, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
3053
+ option.conn.execute(SyncMode.Sync, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
3054
+ option.conn.execute(SyncMode.Sync, `DROP TABLE IF EXISTS ${rtable};`);
3055
+ // 更新完毕,保存版本号
3056
+ option.conn.execute(SyncMode.Sync, 'UPDATE TABLE_VERSION SET ______version = ? WHERE ______tableName = ?', [option.tableName, lastVersion]);
3057
+ }
3058
+ else if (!tableVersion) { // 不需要升级情况:没有旧的版本号
3059
+ option.conn.execute(SyncMode.Sync, 'INSERT INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
3060
+ }
3061
+ }
3062
+ else { // 表不存在
3063
+ // 创建表
3064
+ option.conn.execute(SyncMode.Sync, `
3065
+ CREATE TABLE IF NOT EXISTS ${tableES} (
3066
+ ${Object.values(this[_fields]).map(K => K[DBType.Sqlite]()).join(',')}
3067
+ ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.C2()).join(',')})` : ''}
3068
+
3069
+ );
3070
+ `);
3071
+ if (this[_index] && this[_index].length) {
3072
+ for (const index of this[_index]) {
3073
+ option.conn.execute(SyncMode.Sync, `CREATE INDEX ${sqlstring_1.default.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${this[_fields][index]?.C2()}");`);
3074
+ }
3075
+ }
3076
+ option.conn.execute(SyncMode.Sync, 'INSERT OR REPLACE INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
3077
+ }
3078
+ }
3079
+ else if (this[_dbType] === DBType.SqliteRemote) {
3080
+ return new Promise(async (resolve, reject) => {
3081
+ try {
3082
+ if (option?.force) {
3083
+ await option.conn.execute(SyncMode.Async, `DROP TABLE IF EXISTS ${tableES};`);
3084
+ }
3085
+ const lastVersion = this[_sqlite_version] ?? '0.0.1';
3086
+ // 检查表
3087
+ const tableCheckResult = await option.conn.pluck(SyncMode.Async, `SELECT COUNT(1) t FROM sqlite_master WHERE TYPE = 'table' AND name = ?`, [option.tableName]);
3088
+ if (tableCheckResult) {
3089
+ // 旧版本
3090
+ const tableVersion = await option.conn.pluck(SyncMode.Async, 'SELECT ______version v from TABLE_VERSION WHERE ______tableName = ?', [option.tableName]);
3091
+ if (tableVersion && tableVersion < lastVersion) { // 发现需要升级的版本
3092
+ // 更新版本
3093
+ const columns = (0, iterare_1.default)(await option.conn.query(SyncMode.Async, `PRAGMA table_info(${tableES})`))
3094
+ .filter(c => this[_fields].hasOwnProperty((0, object_1.C2P)(c.name, globalThis[exports._Hump])))
3095
+ .map(c => sqlstring_1.default.escapeId(c.name))
3096
+ .join(',');
3097
+ const rtable = `${option.tableName}_${tableVersion.replace(/\./, '_')}`;
3098
+ await option.conn.execute(SyncMode.Async, `DROP TABLE IF EXISTS ${rtable};`);
3099
+ await option.conn.execute(SyncMode.Async, `ALTER TABLE ${tableES} RENAME TO ${rtable};`);
3100
+ await option.conn.execute(SyncMode.Async, `
3101
+ CREATE TABLE IF NOT EXISTS ${tableES}(
3102
+ ${Object.values(this[_fields]).map(K => K[DBType.Sqlite]()).join(',')}
3103
+ ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.C2()).join(',')})` : ''}
3104
+ );
3105
+ `);
3106
+ if (this[_index] && this[_index].length) {
3107
+ for (const index of this[_index]) {
3108
+ await option.conn.execute(SyncMode.Async, `CREATE INDEX ${sqlstring_1.default.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${this[_fields][index]?.C2()}");`);
3109
+ }
3110
+ }
3111
+ await option.conn.execute(SyncMode.Async, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
3112
+ await option.conn.execute(SyncMode.Async, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
3113
+ await option.conn.execute(SyncMode.Async, `DROP TABLE IF EXISTS ${rtable};`);
3114
+ // 更新完毕,保存版本号
3115
+ await option.conn.execute(SyncMode.Async, 'UPDATE TABLE_VERSION SET ______version = ? WHERE ______tableName = ?', [option.tableName, lastVersion]);
3116
+ }
3117
+ else if (!tableVersion) { // 不需要升级情况:没有旧的版本号
3118
+ await option.conn.execute(SyncMode.Async, 'INSERT INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
3119
+ }
3120
+ }
3121
+ else { // 表不存在
3122
+ // 创建表
3123
+ await option.conn.execute(SyncMode.Async, `
3124
+ CREATE TABLE IF NOT EXISTS ${tableES}(
3125
+ ${Object.values(this[_fields]).map(K => K[DBType.Sqlite]()).join(',')}
3126
+ ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.C2()).join(',')})` : ''}
3127
+ );
3128
+ `);
3129
+ if (this[_index] && this[_index].length) {
3130
+ for (const index of this[_index]) {
3131
+ await option.conn.execute(SyncMode.Async, `CREATE INDEX ${sqlstring_1.default.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${sqlstring_1.default.escapeId(option.tableName)} ("${this[_fields][index]?.C2()}");`);
3132
+ }
3133
+ }
3134
+ await option.conn.execute(SyncMode.Async, 'INSERT OR REPLACE INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
3135
+ }
3136
+ resolve();
3137
+ }
3138
+ catch (error) {
3139
+ reject(error);
3140
+ }
3141
+ });
3142
+ }
3143
+ }
3025
3144
  /**
3026
3145
  #创建表
3027
3146
  ** `tableName` 表名称
@@ -3066,16 +3185,16 @@ class SqlService {
3066
3185
  tableName = sqlstring_1.default.escapeId(tableName ?? this[_tableName]);
3067
3186
  switch (this[_dbType]) {
3068
3187
  case DBType.Mysql: {
3069
- let sql = (0, sql_formatter_1.format)(`CREATE ${temp === true ? 'TEMPORARY' : ''} TABLE IF NOT EXISTS ${tableName}(
3188
+ let sql = (0, sql_formatter_1.formatDialect)(`CREATE ${temp === true ? 'TEMPORARY' : ''} TABLE IF NOT EXISTS ${tableName}(
3070
3189
  ${columns.map(K => this[_fields][K][DBType.Mysql]()).join(',')}
3071
3190
  ${ids && ids.length ? `,PRIMARY KEY (${ids.map(i => this[_fields][i]?.C2()).join(',')}) USING BTREE ` : ''}
3072
3191
  ${indexs && indexs.length ? `,${indexs.map(i => `KEY ${this[_fields][i]?.C2()} (${this[_fields][i]?.C2()})`).join(',')} ` : ''}
3073
- ) ENGINE=MEMORY;`);
3192
+ ) ENGINE=MEMORY;`, { dialect: this[_formatDialect] });
3074
3193
  sqls.push({ sql });
3075
3194
  if (data && data.length > 0) {
3076
3195
  const params = [];
3077
3196
  let first = true;
3078
- sql = (0, sql_formatter_1.format)(`INSERT INTO ${tableName} (${columns.map(c => this[_fields][c]?.C2()).join(',')})
3197
+ sql = (0, sql_formatter_1.formatDialect)(`INSERT INTO ${tableName} (${columns.map(c => this[_fields][c]?.C2()).join(',')})
3079
3198
  ${(data).map(d => {
3080
3199
  const r = `SELECT ${Object.entries(d).map(([K, V]) => {
3081
3200
  params.push(V);
@@ -3083,28 +3202,28 @@ class SqlService {
3083
3202
  }).join(',')}`;
3084
3203
  first = false;
3085
3204
  return r;
3086
- }).join(' UNION ALL ')}`);
3205
+ }).join(' UNION ALL ')}`, { dialect: this[_formatDialect] });
3087
3206
  sqls.push({ sql, params });
3088
3207
  }
3089
3208
  break;
3090
3209
  }
3091
3210
  case DBType.Sqlite:
3092
3211
  case DBType.SqliteRemote: {
3093
- let sql = (0, sql_formatter_1.format)(`CREATE ${temp === true ? 'TEMPORARY' : ''} TABLE IF NOT EXISTS ${tableName}(
3212
+ let sql = (0, sql_formatter_1.formatDialect)(`CREATE ${temp === true ? 'TEMPORARY' : ''} TABLE IF NOT EXISTS ${tableName}(
3094
3213
  ${columns.map(K => this[_fields][K][DBType.Sqlite]()).join(',')}
3095
3214
  ${ids && ids.length ? `,PRIMARY KEY (${ids.map(i => this[_fields][i]?.C2()).join(',')}) ` : ''}
3096
- );`);
3215
+ );`, { dialect: this[_formatDialect] });
3097
3216
  sqls.push({ sql });
3098
3217
  if (indexs) {
3099
3218
  for (const index of indexs) {
3100
- sql = (0, sql_formatter_1.format)(`CREATE INDEX ${sqlstring_1.default.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableName} (${this[_fields][index]?.C2()});`);
3219
+ sql = (0, sql_formatter_1.formatDialect)(`CREATE INDEX ${sqlstring_1.default.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableName} (${this[_fields][index]?.C2()});`, { dialect: this[_formatDialect] });
3101
3220
  sqls.push({ sql });
3102
3221
  }
3103
3222
  }
3104
3223
  if (data && data.length > 0) {
3105
3224
  const params = [];
3106
3225
  let first = true;
3107
- sql = (0, sql_formatter_1.format)(`INSERT INTO ${tableName} (${columns.map(c => this[_fields][c]?.C2()).join(',')})
3226
+ sql = (0, sql_formatter_1.formatDialect)(`INSERT INTO ${tableName} (${columns.map(c => this[_fields][c]?.C2()).join(',')})
3108
3227
  ${(data).map(d => {
3109
3228
  const r = `SELECT ${Object.entries(d).map(([K, V]) => {
3110
3229
  params.push(V);
@@ -3112,7 +3231,7 @@ class SqlService {
3112
3231
  }).join(',')}`;
3113
3232
  first = false;
3114
3233
  return r;
3115
- }).join(' UNION ALL ')}`);
3234
+ }).join(' UNION ALL ')}`, { dialect: this[_formatDialect] });
3116
3235
  sqls.push({ sql, params });
3117
3236
  }
3118
3237
  break;
@@ -3177,6 +3296,12 @@ __decorate([
3177
3296
  __metadata("design:paramtypes", [Object]),
3178
3297
  __metadata("design:returntype", Object)
3179
3298
  ], SqlService.prototype, "page", null);
3299
+ __decorate([
3300
+ P(),
3301
+ __metadata("design:type", Function),
3302
+ __metadata("design:paramtypes", [Object]),
3303
+ __metadata("design:returntype", Object)
3304
+ ], SqlService.prototype, "init", null);
3180
3305
  /** 是否进行下一个动作 */
3181
3306
  const IF_PROCEED = function () {
3182
3307
  return function (_target, _propertyKey, descriptor) {