baja-lite 1.0.26 → 1.0.29

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,11 +7,10 @@ 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 _b, _c, _d;
11
- var _e, _f, _g, _h;
10
+ var _b, _c, _d, _e;
11
+ var _f, _g, _h, _j;
12
12
  import { Throw } from './error';
13
13
  import tslib from 'tslib';
14
- import Sqlstring from 'sqlstring';
15
14
  import iterare from 'iterare';
16
15
  import { emptyString } from './string';
17
16
  import pino from 'pino';
@@ -19,7 +18,7 @@ import { excuteSplit, ExcuteSplitMode, sleep } from './fn';
19
18
  import { add, calc, ten2Any } from './math';
20
19
  import mustache from 'mustache';
21
20
  import { C2P, C2P2, P2C } from './object';
22
- import { formatDialect, sqlite, mysql } from 'sql-formatter';
21
+ import { formatDialect, sqlite, mysql, postgresql } from 'sql-formatter';
23
22
  import HTML from 'html-parse-stringify';
24
23
  import { convert } from './convert-xml';
25
24
  import { ArrayList } from './list';
@@ -72,7 +71,6 @@ export const _sqlCache = Symbol('sqlMap');
72
71
  export const _dao = Symbol('dao');
73
72
  export const _primaryDB = '______primaryDB_______';
74
73
  const _dbType = Symbol('dbType');
75
- const _formatDialect = Symbol('FormatDialect');
76
74
  const _sqlite_version = Symbol('sqlite_version');
77
75
  const _daoConnection = Symbol('daoConnection');
78
76
  const _inTransaction = Symbol('inTransaction');
@@ -99,11 +97,12 @@ globalThis[_resultMap_SQLID] = {};
99
97
  export var DBType;
100
98
  (function (DBType) {
101
99
  DBType[DBType["Mysql"] = 0] = "Mysql";
102
- DBType[DBType["Sqlite"] = 1] = "Sqlite";
103
- DBType[DBType["Mongo"] = 2] = "Mongo";
104
- DBType[DBType["SqliteRemote"] = 3] = "SqliteRemote";
105
- DBType[DBType["Redis"] = 4] = "Redis";
106
- DBType[DBType["RedisLock"] = 5] = "RedisLock";
100
+ DBType[DBType["Postgresql"] = 1] = "Postgresql";
101
+ DBType[DBType["Sqlite"] = 2] = "Sqlite";
102
+ DBType[DBType["Mongo"] = 3] = "Mongo";
103
+ DBType[DBType["SqliteRemote"] = 4] = "SqliteRemote";
104
+ DBType[DBType["Redis"] = 5] = "Redis";
105
+ DBType[DBType["RedisLock"] = 6] = "RedisLock";
107
106
  })(DBType || (DBType = {}));
108
107
  ;
109
108
  export var MapperIfUndefined;
@@ -239,17 +238,7 @@ export var SqlType;
239
238
  SqlType[SqlType["mediumtext"] = 20] = "mediumtext";
240
239
  SqlType[SqlType["longblob"] = 21] = "longblob";
241
240
  SqlType[SqlType["longtext"] = 22] = "longtext";
242
- SqlType[SqlType["set"] = 23] = "set";
243
- SqlType[SqlType["enum"] = 24] = "enum";
244
- SqlType[SqlType["json"] = 25] = "json";
245
- SqlType[SqlType["geometry"] = 26] = "geometry";
246
- SqlType[SqlType["point"] = 27] = "point";
247
- SqlType[SqlType["linestring"] = 28] = "linestring";
248
- SqlType[SqlType["polygon"] = 29] = "polygon";
249
- SqlType[SqlType["multipoint"] = 30] = "multipoint";
250
- SqlType[SqlType["multilinestring"] = 31] = "multilinestring";
251
- SqlType[SqlType["multipolygon"] = 32] = "multipolygon";
252
- SqlType[SqlType["geometrycollection"] = 33] = "geometrycollection";
241
+ SqlType[SqlType["json"] = 23] = "json";
253
242
  })(SqlType || (SqlType = {}));
254
243
  export var ColumnMode;
255
244
  (function (ColumnMode) {
@@ -281,7 +270,7 @@ class MysqlConnection {
281
270
  }
282
271
  ;
283
272
  if (globalThis[_GlobalSqlOption].log === 'trace') {
284
- logger.trace(Sqlstring.format(sql, params));
273
+ logger.trace(sql, params);
285
274
  }
286
275
  return new Promise(async (resolve, reject) => {
287
276
  try {
@@ -314,7 +303,7 @@ class MysqlConnection {
314
303
  }
315
304
  ;
316
305
  if (globalThis[_GlobalSqlOption].log === 'trace') {
317
- logger.trace(Sqlstring.format(sql, params));
306
+ logger.trace(sql, params);
318
307
  }
319
308
  return new Promise(async (resolve, reject) => {
320
309
  try {
@@ -350,7 +339,7 @@ class MysqlConnection {
350
339
  }
351
340
  ;
352
341
  if (globalThis[_GlobalSqlOption].log === 'trace') {
353
- logger.trace(Sqlstring.format(sql, params));
342
+ logger.trace(sql, params);
354
343
  }
355
344
  return new Promise(async (resolve, reject) => {
356
345
  try {
@@ -384,7 +373,7 @@ class MysqlConnection {
384
373
  }
385
374
  ;
386
375
  if (globalThis[_GlobalSqlOption].log === 'trace') {
387
- logger.trace(Sqlstring.format(sql, params));
376
+ logger.trace(sql, params);
388
377
  }
389
378
  return new Promise(async (resolve, reject) => {
390
379
  try {
@@ -418,7 +407,7 @@ class MysqlConnection {
418
407
  }
419
408
  ;
420
409
  if (globalThis[_GlobalSqlOption].log === 'trace') {
421
- logger.trace(Sqlstring.format(sql, params));
410
+ logger.trace(sql, params);
422
411
  }
423
412
  return new Promise(async (resolve, reject) => {
424
413
  try {
@@ -454,6 +443,11 @@ export class Mysql {
454
443
  constructor(pool) {
455
444
  this[_daoDB] = pool;
456
445
  }
446
+ async keepAlive() {
447
+ const connection = await this[_daoDB].getConnection();
448
+ connection.query('SELECT 1 FROM DUAL');
449
+ setTimeout(async () => await this.keepAlive(), 60000);
450
+ }
457
451
  createConnection(sync) {
458
452
  if (sync === SyncMode.Sync) {
459
453
  logger.error('MYSQL not suppouted sync mode');
@@ -538,11 +532,310 @@ export class Mysql {
538
532
  restore(sync, name) {
539
533
  }
540
534
  }
541
- class SqliteConnection {
535
+ class PostgresqlConnection {
542
536
  constructor(conn) {
543
537
  this[_c] = false;
544
538
  this[_daoConnection] = conn;
545
539
  }
540
+ execute(sync, sql, params) {
541
+ logger.debug(sql, params ?? '');
542
+ if (!sql) {
543
+ return { affectedRows: 0, insertId: 0n };
544
+ }
545
+ ;
546
+ if (sync === SyncMode.Sync) {
547
+ logger.warn('Postgresql not suppouted sync mode');
548
+ return { affectedRows: 0, insertId: 0n };
549
+ }
550
+ ;
551
+ if (globalThis[_GlobalSqlOption].log === 'trace') {
552
+ logger.trace(sql, params);
553
+ }
554
+ return new Promise(async (resolve, reject) => {
555
+ try {
556
+ let index = 1;
557
+ const { rowCount } = await this[_daoConnection].query({
558
+ text: sql.replace(/\?/g, () => `$${index++}`),
559
+ values: params
560
+ });
561
+ const result = rowCount;
562
+ if (globalThis[_GlobalSqlOption].log === 'trace') {
563
+ logger.trace(result);
564
+ }
565
+ resolve({ affectedRows: result.affectedRows, insertId: result.insertId });
566
+ }
567
+ catch (error) {
568
+ logger.error(`
569
+ error: ${error},
570
+ sql: ${sql},
571
+ params: ${params}
572
+ `);
573
+ reject(error);
574
+ }
575
+ });
576
+ }
577
+ pluck(sync, sql, params) {
578
+ logger.debug(sql, params ?? '');
579
+ if (!sql) {
580
+ return null;
581
+ }
582
+ ;
583
+ if (sync === SyncMode.Sync) {
584
+ logger.warn('Postgresql not suppouted sync mode');
585
+ return null;
586
+ }
587
+ ;
588
+ if (globalThis[_GlobalSqlOption].log === 'trace') {
589
+ logger.trace(sql, params);
590
+ }
591
+ return new Promise(async (resolve, reject) => {
592
+ try {
593
+ let index = 1;
594
+ const { rows } = await this[_daoConnection].query({
595
+ text: sql.replace(/\?/g, () => `$${index++}`),
596
+ values: params
597
+ });
598
+ if (rows && rows[0]) {
599
+ const r = Object.values(rows[0])[0];
600
+ if (r === null)
601
+ resolve(r);
602
+ else
603
+ resolve(r);
604
+ }
605
+ resolve(null);
606
+ }
607
+ catch (error) {
608
+ logger.error(`
609
+ error: ${error},
610
+ sql: ${sql},
611
+ params: ${params}
612
+ `);
613
+ reject(error);
614
+ }
615
+ });
616
+ }
617
+ get(sync, sql, params) {
618
+ logger.debug(sql, params ?? '');
619
+ if (!sql) {
620
+ return null;
621
+ }
622
+ ;
623
+ if (sync === SyncMode.Sync) {
624
+ logger.warn('Postgresql not suppouted sync mode');
625
+ return null;
626
+ }
627
+ ;
628
+ if (globalThis[_GlobalSqlOption].log === 'trace') {
629
+ logger.trace(sql, params);
630
+ }
631
+ return new Promise(async (resolve, reject) => {
632
+ try {
633
+ let index = 1;
634
+ const { rows } = await this[_daoConnection].query({
635
+ text: sql.replace(/\?/g, () => `$${index++}`),
636
+ values: params
637
+ });
638
+ if (globalThis[_GlobalSqlOption].log === 'trace') {
639
+ logger.trace(rows);
640
+ }
641
+ if (rows && rows[0])
642
+ resolve(rows[0]);
643
+ resolve(null);
644
+ }
645
+ catch (error) {
646
+ logger.error(`
647
+ error: ${error},
648
+ sql: ${sql},
649
+ params: ${params}
650
+ `);
651
+ reject(error);
652
+ }
653
+ });
654
+ }
655
+ raw(sync, sql, params) {
656
+ logger.debug(sql, params ?? '');
657
+ if (!sql) {
658
+ return [];
659
+ }
660
+ ;
661
+ if (sync === SyncMode.Sync) {
662
+ logger.warn('Postgresql not suppouted sync mode');
663
+ return [];
664
+ }
665
+ ;
666
+ if (globalThis[_GlobalSqlOption].log === 'trace') {
667
+ logger.trace(sql, params);
668
+ }
669
+ return new Promise(async (resolve, reject) => {
670
+ try {
671
+ let index = 1;
672
+ const { rows } = await this[_daoConnection].query({
673
+ text: sql.replace(/\?/g, () => `$${index++}`),
674
+ values: params
675
+ });
676
+ if (globalThis[_GlobalSqlOption].log === 'trace') {
677
+ logger.trace(rows);
678
+ }
679
+ if (rows)
680
+ resolve(rows.map((i) => Object.values(i)[0]));
681
+ resolve([]);
682
+ }
683
+ catch (error) {
684
+ logger.error(`
685
+ error: ${error},
686
+ sql: ${sql},
687
+ params: ${params}
688
+ `);
689
+ reject(error);
690
+ }
691
+ });
692
+ }
693
+ query(sync, sql, params) {
694
+ logger.debug(sql, params ?? '');
695
+ if (!sql) {
696
+ return [];
697
+ }
698
+ ;
699
+ if (sync === SyncMode.Sync) {
700
+ logger.warn('Postgresql not suppouted sync mode');
701
+ return [];
702
+ }
703
+ ;
704
+ if (globalThis[_GlobalSqlOption].log === 'trace') {
705
+ logger.trace(sql, params);
706
+ }
707
+ return new Promise(async (resolve, reject) => {
708
+ try {
709
+ let index = 1;
710
+ const { rows } = await this[_daoConnection].query({
711
+ text: sql.replace(/\?/g, () => `$${index++}`),
712
+ values: params
713
+ });
714
+ if (globalThis[_GlobalSqlOption].log === 'trace') {
715
+ logger.trace(rows);
716
+ }
717
+ resolve(rows);
718
+ }
719
+ catch (error) {
720
+ logger.error(`
721
+ error: ${error},
722
+ sql: ${sql},
723
+ params: ${params}
724
+ `);
725
+ reject(error);
726
+ }
727
+ });
728
+ }
729
+ realse(sync) {
730
+ if (sync === SyncMode.Sync) {
731
+ try {
732
+ this[_daoConnection]?.release();
733
+ }
734
+ catch (error) {
735
+ }
736
+ }
737
+ ;
738
+ }
739
+ }
740
+ _c = _inTransaction;
741
+ export class Postgresql {
742
+ constructor(pool) {
743
+ this[_daoDB] = pool;
744
+ }
745
+ async keepAlive() {
746
+ const connection = await this[_daoDB].connect();
747
+ connection.query('SELECT 1');
748
+ setTimeout(async () => await this.keepAlive(), 60000);
749
+ }
750
+ createConnection(sync) {
751
+ if (sync === SyncMode.Sync) {
752
+ logger.error('Postgresql not suppouted sync mode');
753
+ return null;
754
+ }
755
+ ;
756
+ return new Promise(async (resolve, reject) => {
757
+ try {
758
+ const connection = await this[_daoDB].connect();
759
+ logger.debug('create new connection!');
760
+ resolve(new PostgresqlConnection(connection));
761
+ }
762
+ catch (error) {
763
+ reject(error);
764
+ }
765
+ });
766
+ }
767
+ transaction(sync, fn, conn) {
768
+ if (sync === SyncMode.Sync) {
769
+ logger.warn('Postgresql not suppouted sync mode');
770
+ return null;
771
+ }
772
+ ;
773
+ return new Promise(async (resolve, reject) => {
774
+ let needCommit = false;
775
+ let newConn = false;
776
+ if (!conn) {
777
+ conn = await this.createConnection(SyncMode.Async) ?? undefined;
778
+ newConn = true;
779
+ }
780
+ if (conn?.[_inTransaction] !== true) {
781
+ needCommit = true;
782
+ logger.debug('beginTransaction begin!');
783
+ await conn[_daoConnection].query('BEGIN');
784
+ logger.debug('beginTransaction end!');
785
+ }
786
+ conn[_inTransaction] = true;
787
+ try {
788
+ const result = await fn(conn);
789
+ if (needCommit === true) {
790
+ logger.debug('commit begin!');
791
+ await conn[_daoConnection].query('COMMIT');
792
+ conn[_inTransaction] = false;
793
+ logger.debug('commit end!');
794
+ }
795
+ resolve(result);
796
+ }
797
+ catch (error) {
798
+ logger.debug('rollback begin!');
799
+ await conn[_daoConnection].query('ROLLBACK');
800
+ logger.debug('rollback end!');
801
+ conn[_inTransaction] = false;
802
+ logger.error(error);
803
+ reject(error);
804
+ }
805
+ finally {
806
+ try {
807
+ if (needCommit === true) {
808
+ conn[_inTransaction] = false;
809
+ }
810
+ if (newConn === true) {
811
+ logger.debug('release begin!');
812
+ conn[_daoConnection].release();
813
+ logger.debug('release end!');
814
+ }
815
+ }
816
+ catch (error) {
817
+ }
818
+ }
819
+ });
820
+ }
821
+ close(sync) {
822
+ if (sync === SyncMode.Sync) {
823
+ this[_daoDB]?.end();
824
+ }
825
+ ;
826
+ }
827
+ backup(sync, name) {
828
+ }
829
+ remove(sync) {
830
+ }
831
+ restore(sync, name) {
832
+ }
833
+ }
834
+ class SqliteConnection {
835
+ constructor(conn) {
836
+ this[_d] = false;
837
+ this[_daoConnection] = conn;
838
+ }
546
839
  execute(sync, sql, params) {
547
840
  try {
548
841
  logger.debug(sql, params ?? '');
@@ -556,7 +849,7 @@ class SqliteConnection {
556
849
  }
557
850
  ;
558
851
  if (globalThis[_GlobalSqlOption].log === 'trace') {
559
- logger.trace(Sqlstring.format(sql, params));
852
+ logger.trace(sql, params);
560
853
  }
561
854
  const result = this[_daoConnection].prepare(sql).run(params ?? {});
562
855
  if (globalThis[_GlobalSqlOption].log === 'trace') {
@@ -587,7 +880,7 @@ class SqliteConnection {
587
880
  }
588
881
  ;
589
882
  if (globalThis[_GlobalSqlOption].log === 'trace') {
590
- logger.trace(Sqlstring.format(sql, params));
883
+ logger.trace(sql, params);
591
884
  }
592
885
  return this[_daoConnection].prepare(sql).pluck().get(params ?? {});
593
886
  }
@@ -612,7 +905,7 @@ class SqliteConnection {
612
905
  }
613
906
  ;
614
907
  if (globalThis[_GlobalSqlOption].log === 'trace') {
615
- logger.trace(Sqlstring.format(sql, params));
908
+ logger.trace(sql, params);
616
909
  }
617
910
  return this[_daoConnection].prepare(sql).get(params ?? {});
618
911
  }
@@ -638,7 +931,7 @@ class SqliteConnection {
638
931
  }
639
932
  ;
640
933
  if (globalThis[_GlobalSqlOption].log === 'trace') {
641
- logger.trace(Sqlstring.format(sql, params));
934
+ logger.trace(sql, params);
642
935
  }
643
936
  return this[_daoConnection].prepare(sql).raw().all(params ?? {});
644
937
  }
@@ -664,7 +957,7 @@ class SqliteConnection {
664
957
  }
665
958
  ;
666
959
  if (globalThis[_GlobalSqlOption].log === 'trace') {
667
- logger.trace(Sqlstring.format(sql, params));
960
+ logger.trace(sql, params);
668
961
  }
669
962
  return this[_daoConnection].prepare(sql).all(params ?? {});
670
963
  }
@@ -680,7 +973,7 @@ class SqliteConnection {
680
973
  realse(sync) {
681
974
  }
682
975
  }
683
- _c = _inTransaction;
976
+ _d = _inTransaction;
684
977
  export class Sqlite {
685
978
  constructor(db) {
686
979
  this[_daoDB] = db;
@@ -745,7 +1038,7 @@ export class Sqlite {
745
1038
  }
746
1039
  export class SqliteRemoteConnection {
747
1040
  constructor(conn, name) {
748
- this[_d] = false;
1041
+ this[_e] = false;
749
1042
  this[_daoConnection] = conn;
750
1043
  this[_sqliteRemoteName] = name;
751
1044
  }
@@ -761,7 +1054,7 @@ export class SqliteRemoteConnection {
761
1054
  }
762
1055
  ;
763
1056
  if (globalThis[_GlobalSqlOption].log === 'trace') {
764
- logger.trace(Sqlstring.format(sql, params));
1057
+ logger.trace(sql, params);
765
1058
  }
766
1059
  return new Promise(async (resolve, reject) => {
767
1060
  try {
@@ -791,7 +1084,7 @@ export class SqliteRemoteConnection {
791
1084
  }
792
1085
  ;
793
1086
  if (globalThis[_GlobalSqlOption].log === 'trace') {
794
- logger.trace(Sqlstring.format(sql, params));
1087
+ logger.trace(sql, params);
795
1088
  }
796
1089
  return new Promise(async (resolve, reject) => {
797
1090
  try {
@@ -821,7 +1114,7 @@ export class SqliteRemoteConnection {
821
1114
  }
822
1115
  ;
823
1116
  if (globalThis[_GlobalSqlOption].log === 'trace') {
824
- logger.trace(Sqlstring.format(sql, params));
1117
+ logger.trace(sql, params);
825
1118
  }
826
1119
  return new Promise(async (resolve, reject) => {
827
1120
  try {
@@ -851,7 +1144,7 @@ export class SqliteRemoteConnection {
851
1144
  }
852
1145
  ;
853
1146
  if (globalThis[_GlobalSqlOption].log === 'trace') {
854
- logger.trace(Sqlstring.format(sql, params));
1147
+ logger.trace(sql, params);
855
1148
  }
856
1149
  return new Promise(async (resolve, reject) => {
857
1150
  try {
@@ -881,7 +1174,7 @@ export class SqliteRemoteConnection {
881
1174
  }
882
1175
  ;
883
1176
  if (globalThis[_GlobalSqlOption].log === 'trace') {
884
- logger.trace(Sqlstring.format(sql, params));
1177
+ logger.trace(sql, params);
885
1178
  }
886
1179
  return new Promise(async (resolve, reject) => {
887
1180
  try {
@@ -902,7 +1195,7 @@ export class SqliteRemoteConnection {
902
1195
  realse(sync) {
903
1196
  }
904
1197
  }
905
- _d = _inTransaction;
1198
+ _e = _inTransaction;
906
1199
  export class SqliteRemote {
907
1200
  constructor(db, name) {
908
1201
  this[_daoDB] = db;
@@ -1260,10 +1553,10 @@ function replaceCdata(rawText) {
1260
1553
  return rawText;
1261
1554
  }
1262
1555
  function _flatData(result, i, length, keys, V) {
1263
- var _e;
1556
+ var _f;
1264
1557
  const key = keys[i];
1265
1558
  if (i < length) {
1266
- result[_e = key] ?? (result[_e] = {});
1559
+ result[_f = key] ?? (result[_f] = {});
1267
1560
  i++;
1268
1561
  _flatData(result[key], i, length, keys, V);
1269
1562
  }
@@ -1496,15 +1789,16 @@ function P(skipConn = false) {
1496
1789
  const option = args[0] = Object.assign({}, globalThis[_GlobalSqlOption], this[_SqlOption], args[0]);
1497
1790
  option.sync ?? (option.sync = SyncMode.Async);
1498
1791
  option.tableName = option?.tableName ?? this[_tableName];
1499
- const dbName = option?.dbName ?? this[_daoDBName] ?? _primaryDB;
1500
- option.dao = globalThis[_dao][this[_dbType]][dbName];
1501
- if (this[_dbType] === DBType.Sqlite) {
1792
+ option.dbName = option?.dbName ?? this[_daoDBName] ?? _primaryDB;
1793
+ option.dbType = this[_dbType] ?? globalThis[_GlobalSqlOption].dbType ?? DBType.Mysql;
1794
+ option.dao = globalThis[_dao][option.dbType][option.dbName];
1795
+ if (option.dbType === DBType.Sqlite) {
1502
1796
  if (!option.dao) {
1503
- const db = new Sqlite(new globalThis[_GlobalSqlOption].BetterSqlite3(dbName, { fileMustExist: false }));
1504
- if (globalThis[_dao][this[_dbType]][_primaryDB] === undefined) {
1505
- globalThis[_dao][this[_dbType]][_primaryDB] = db;
1797
+ const db = new Sqlite(new globalThis[_GlobalSqlOption].BetterSqlite3(option.dbName, { fileMustExist: false }));
1798
+ if (globalThis[_dao][option.dbType][_primaryDB] === undefined) {
1799
+ globalThis[_dao][option.dbType][_primaryDB] = db;
1506
1800
  }
1507
- globalThis[_dao][this[_dbType]][dbName] = db;
1801
+ globalThis[_dao][option.dbType][option.dbName] = db;
1508
1802
  option.dao = db;
1509
1803
  }
1510
1804
  Throw.if(option.sync === SyncMode.Async, 'sqlite can not Async!');
@@ -1538,14 +1832,14 @@ function P(skipConn = false) {
1538
1832
  }
1539
1833
  }
1540
1834
  }
1541
- else if (this[_dbType] === DBType.SqliteRemote) {
1835
+ else if (option.dbType === DBType.SqliteRemote) {
1542
1836
  if (!option.dao) {
1543
- globalThis[_GlobalSqlOption].SqliteRemote.service.initDB(dbName);
1544
- const db = new SqliteRemote(globalThis[_GlobalSqlOption].SqliteRemote.service, dbName);
1545
- if (globalThis[_dao][this[_dbType]][_primaryDB] === undefined) {
1546
- globalThis[_dao][this[_dbType]][_primaryDB] = db;
1837
+ globalThis[_GlobalSqlOption].SqliteRemote.service.initDB(option.dbName);
1838
+ const db = new SqliteRemote(globalThis[_GlobalSqlOption].SqliteRemote.service, option.dbName);
1839
+ if (globalThis[_dao][option.dbType][_primaryDB] === undefined) {
1840
+ globalThis[_dao][option.dbType][_primaryDB] = db;
1547
1841
  }
1548
- globalThis[_dao][this[_dbType]][dbName] = db;
1842
+ globalThis[_dao][option.dbType][option.dbName] = db;
1549
1843
  option.dao = db;
1550
1844
  }
1551
1845
  Throw.if(option.sync === SyncMode.Sync, 'SqliteRemote remote can not sync!');
@@ -1577,8 +1871,38 @@ function P(skipConn = false) {
1577
1871
  }
1578
1872
  });
1579
1873
  }
1580
- else if (this[_dbType] === DBType.Mysql) {
1581
- Throw.if(!option.dao, `not found db:${String(dbName)}(${this[_dbType]})`);
1874
+ else if (option.dbType === DBType.Mysql) {
1875
+ Throw.if(!option.dao, `not found db:${String(option.dbName)}(${option.dbType})`);
1876
+ return new Promise(async (resolve, reject) => {
1877
+ try {
1878
+ // 连接共享
1879
+ if (skipConn === false && !option.conn) {
1880
+ (option).conn = await option.dao.createConnection(SyncMode.Async);
1881
+ }
1882
+ else {
1883
+ needRealseConn = false;
1884
+ }
1885
+ const result = await fn.call(this, ...args);
1886
+ logger.info(`${propertyKey}:${option.tableName}:use ${+new Date() - startTime}ms`);
1887
+ resolve(result);
1888
+ }
1889
+ catch (error) {
1890
+ console.error(`service ${propertyKey} have an error:${error}, it's argumens: ${JSON.stringify(args.filter(i => typeof i !== 'object' || (typeof i === 'object' && !i.insert)))}`);
1891
+ reject(error);
1892
+ }
1893
+ finally {
1894
+ if (needRealseConn && option && option.conn) {
1895
+ try {
1896
+ option.conn.realse(SyncMode.Sync);
1897
+ }
1898
+ catch (error) {
1899
+ }
1900
+ }
1901
+ }
1902
+ });
1903
+ }
1904
+ else if (option.dbType === DBType.Postgresql) {
1905
+ Throw.if(!option.dao, `not found db:${String(option.dbName)}(${option.dbType})`);
1582
1906
  return new Promise(async (resolve, reject) => {
1583
1907
  try {
1584
1908
  // 连接共享
@@ -1650,204 +1974,182 @@ const FieldFilter = (K, V, def, uuidColumn, option) => {
1650
1974
  return [ret, V];
1651
1975
  };
1652
1976
  const MYSQLCHARSET = `CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci`;
1977
+ const POSTGRESCHARSET = `COLLATE "pg_catalog"."default"`;
1653
1978
  export const Field = (config) => {
1654
1979
  config.type ?? (config.type = SqlType.varchar);
1655
1980
  return (object, propertyName) => {
1656
1981
  const field = config;
1657
1982
  field.P = propertyName;
1658
1983
  field.C = () => P2C(propertyName, globalThis[_Hump]);
1659
- field.C2 = () => Sqlstring.escapeId(P2C(propertyName, globalThis[_Hump]));
1660
- field.C3 = () => `${Sqlstring.escapeId(P2C(propertyName, globalThis[_Hump]))} ${propertyName}`;
1984
+ field.C2 = () => P2C(propertyName, globalThis[_Hump]);
1985
+ field.C3 = () => `${P2C(propertyName, globalThis[_Hump])} ${propertyName}`;
1661
1986
  const hasDef = field.hasOwnProperty('def') === true;
1662
1987
  switch (field.type) {
1663
1988
  case SqlType.tinyint: {
1664
- field[DBType.Mysql] = () => `${field.C2()} tinyint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1989
+ field[DBType.Mysql] = () => `${field.C2()} tinyint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT ${field.def}` : ''}`;
1990
+ field[DBType.Postgresql] = () => `${field.C2()} int2 ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT ${field.def}` : ''}`;
1665
1991
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} integer`;
1666
1992
  break;
1667
1993
  }
1668
1994
  case SqlType.smallint: {
1669
- field[DBType.Mysql] = () => `${field.C2()} smallint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1995
+ field[DBType.Mysql] = () => `${field.C2()} smallint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT ${field.def}` : ''}`;
1996
+ field[DBType.Postgresql] = () => `${field.C2()} int2 ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT ${field.def}` : ''}`;
1670
1997
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} integer`;
1671
1998
  break;
1672
1999
  }
1673
2000
  case SqlType.mediumint: {
1674
- field[DBType.Mysql] = () => `${field.C2()} smallint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2001
+ field[DBType.Mysql] = () => `${field.C2()} smallint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT ${field.def}` : ''}`;
2002
+ field[DBType.Postgresql] = () => `${field.C2()} int4 ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT ${field.def}` : ''}`;
1675
2003
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} integer`;
1676
2004
  break;
1677
2005
  }
1678
2006
  case SqlType.int: {
1679
- field[DBType.Mysql] = () => `${field.C2()} int ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2007
+ field[DBType.Mysql] = () => `${field.C2()} int ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT ${field.def}` : ''}`;
2008
+ field[DBType.Postgresql] = () => `${field.C2()} int4 ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT ${field.def}` : ''}`;
1680
2009
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} integer`;
1681
2010
  break;
1682
2011
  }
1683
2012
  case SqlType.bigint: {
1684
2013
  field[DBType.Mysql] = () => `${field.C2()} bigint ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2014
+ field[DBType.Postgresql] = () => `${field.C2()} int8 ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1685
2015
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} integer`;
1686
2016
  field.Data2SQL = (data) => BigInt(data ?? 0);
1687
2017
  break;
1688
2018
  }
1689
2019
  case SqlType.float: {
1690
- field[DBType.Mysql] = () => `${field.C2()} float(${config.length ?? 1}, ${config.scale ?? 2}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT '${field.def}'` : ''} `;
2020
+ field[DBType.Mysql] = () => `${field.C2()} float4(${config.length ?? 1}, ${config.scale ?? 2}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT '${field.def}'` : ''} `;
2021
+ field[DBType.Postgresql] = () => `${field.C2()} float4(${config.length ?? 1}, ${config.scale ?? 2}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT '${field.def}'` : ''} `;
1691
2022
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} real`;
1692
2023
  break;
1693
2024
  }
1694
2025
  case SqlType.double: {
1695
2026
  field[DBType.Mysql] = () => `${field.C2()} double(${config.length ?? 1}, ${config.scale ?? 2}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT '${field.def}'` : ''} `;
2027
+ field[DBType.Postgresql] = () => `${field.C2()} float8(${config.length ?? 1}, ${config.scale ?? 2}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT '${field.def}'` : ''} `;
1696
2028
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} real`;
1697
2029
  break;
1698
2030
  }
1699
2031
  case SqlType.decimal: {
1700
2032
  field[DBType.Mysql] = () => `${field.C2()} decimal(${config.length ?? 1}, ${config.scale ?? 2}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT '${field.def}'` : ''} `;
2033
+ field[DBType.Postgresql] = () => `${field.C2()} numeric(${config.length ?? 1}, ${config.scale ?? 2}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT '${field.def}'` : ''} `;
1701
2034
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} real`;
1702
2035
  break;
1703
2036
  }
1704
2037
  case SqlType.longtext: {
1705
2038
  field[DBType.Mysql] = () => `${field.C2()} longtext ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2039
+ field[DBType.Postgresql] = () => `${field.C2()} text ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1706
2040
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1707
2041
  break;
1708
2042
  }
1709
2043
  case SqlType.mediumtext: {
1710
2044
  field[DBType.Mysql] = () => `${field.C2()} mediumtext ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2045
+ field[DBType.Postgresql] = () => `${field.C2()} text ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1711
2046
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1712
2047
  break;
1713
2048
  }
1714
2049
  case SqlType.text: {
1715
2050
  field[DBType.Mysql] = () => `${field.C2()} text ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2051
+ field[DBType.Postgresql] = () => `${field.C2()} text ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1716
2052
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1717
2053
  break;
1718
2054
  }
1719
2055
  case SqlType.date: {
1720
2056
  field[DBType.Mysql] = () => `${field.C2()} date ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2057
+ field[DBType.Postgresql] = () => `${field.C2()} date ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1721
2058
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1722
2059
  field.Data2SQL = (data) => typeof data === 'string' ? new Date(data) : data;
1723
2060
  break;
1724
2061
  }
1725
2062
  case SqlType.time: {
1726
2063
  field[DBType.Mysql] = () => `${field.C2()} time ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2064
+ field[DBType.Postgresql] = () => `${field.C2()} time ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1727
2065
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1728
2066
  field.Data2SQL = (data) => typeof data === 'string' ? new Date(data) : data;
1729
2067
  break;
1730
2068
  }
1731
2069
  case SqlType.year: {
1732
2070
  field[DBType.Mysql] = () => `${field.C2()} year ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2071
+ field[DBType.Postgresql] = () => `${field.C2()} int4 ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1733
2072
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1734
2073
  field.Data2SQL = (data) => typeof data === 'string' ? new Date(data) : data;
1735
2074
  break;
1736
2075
  }
1737
2076
  case SqlType.datetime: {
1738
2077
  field[DBType.Mysql] = () => `${field.C2()} datetime ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2078
+ field[DBType.Postgresql] = () => `${field.C2()} timestamp ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1739
2079
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1740
2080
  field.Data2SQL = (data) => typeof data === 'string' ? new Date(data) : data;
1741
2081
  break;
1742
2082
  }
1743
2083
  case SqlType.timestamp: {
1744
2084
  field[DBType.Mysql] = () => `${field.C2()} timestamp ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2085
+ field[DBType.Postgresql] = () => `${field.C2()} timestamp ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1745
2086
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} integer`;
1746
2087
  field.Data2SQL = (data) => typeof data === 'string' ? +new Date(data) : data;
1747
2088
  break;
1748
2089
  }
1749
2090
  case SqlType.char: {
1750
2091
  field[DBType.Mysql] = () => `${field.C2()} char(${config.length ?? 1}) ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2092
+ field[DBType.Postgresql] = () => `${field.C2()} char(${config.length ?? 1}) ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1751
2093
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1752
2094
  break;
1753
2095
  }
1754
2096
  case SqlType.varchar: {
1755
2097
  field[DBType.Mysql] = () => `${field.C2()} varchar(${config.length ?? 1}) ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2098
+ field[DBType.Postgresql] = () => `${field.C2()} varchar(${config.length ?? 1}) ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1756
2099
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1757
2100
  break;
1758
2101
  }
1759
2102
  case SqlType.tinyblob: {
1760
2103
  field[DBType.Mysql] = () => `${field.C2()} tinyblob ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2104
+ field[DBType.Postgresql] = () => `${field.C2()} bytea ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1761
2105
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1762
2106
  break;
1763
2107
  }
1764
2108
  case SqlType.tinytext: {
1765
2109
  field[DBType.Mysql] = () => `${field.C2()} tinytext ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2110
+ field[DBType.Postgresql] = () => `${field.C2()} text ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1766
2111
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1767
2112
  break;
1768
2113
  }
1769
2114
  case SqlType.blob: {
1770
2115
  field[DBType.Mysql] = () => `${field.C2()} binary ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2116
+ field[DBType.Postgresql] = () => `${field.C2()} bytea ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1771
2117
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1772
2118
  break;
1773
2119
  }
1774
2120
  case SqlType.text: {
1775
2121
  field[DBType.Mysql] = () => `${field.C2()} text ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2122
+ field[DBType.Postgresql] = () => `${field.C2()} text ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1776
2123
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1777
2124
  break;
1778
2125
  }
1779
2126
  case SqlType.mediumblob: {
1780
2127
  field[DBType.Mysql] = () => `${field.C2()} mediumblob ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2128
+ field[DBType.Postgresql] = () => `${field.C2()} bytea ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1781
2129
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1782
2130
  break;
1783
2131
  }
1784
2132
  case SqlType.mediumtext: {
1785
2133
  field[DBType.Mysql] = () => `${field.C2()} mediumtext ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2134
+ field[DBType.Postgresql] = () => `${field.C2()} text ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1786
2135
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1787
2136
  break;
1788
2137
  }
1789
2138
  case SqlType.longblob: {
1790
2139
  field[DBType.Mysql] = () => `${field.C2()} longblob ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2140
+ field[DBType.Postgresql] = () => `${field.C2()} bytea ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1791
2141
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1792
2142
  break;
1793
2143
  }
1794
2144
  case SqlType.longtext: {
1795
2145
  field[DBType.Mysql] = () => `${field.C2()} longtext ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1796
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1797
- break;
1798
- }
1799
- case SqlType.set: {
1800
- field[DBType.Mysql] = () => `${field.C2()} set ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1801
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1802
- break;
1803
- }
1804
- case SqlType.enum: {
1805
- field[DBType.Mysql] = () => `${field.C2()} enum ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2146
+ field[DBType.Postgresql] = () => `${field.C2()} text ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1806
2147
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1807
2148
  break;
1808
2149
  }
1809
2150
  case SqlType.json: {
1810
2151
  field[DBType.Mysql] = () => `${field.C2()} json ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1811
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1812
- break;
1813
- }
1814
- case SqlType.geometry: {
1815
- field[DBType.Mysql] = () => `${field.C2()} geometry ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1816
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1817
- break;
1818
- }
1819
- case SqlType.point: {
1820
- field[DBType.Mysql] = () => `${field.C2()} point ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1821
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1822
- break;
1823
- }
1824
- case SqlType.linestring: {
1825
- field[DBType.Mysql] = () => `${field.C2()} linestring ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1826
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1827
- break;
1828
- }
1829
- case SqlType.polygon: {
1830
- field[DBType.Mysql] = () => `${field.C2()} polygon ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1831
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1832
- break;
1833
- }
1834
- case SqlType.multipoint: {
1835
- field[DBType.Mysql] = () => `${field.C2()} multipoint ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1836
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1837
- break;
1838
- }
1839
- case SqlType.multilinestring: {
1840
- field[DBType.Mysql] = () => `${field.C2()} multilinestring ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1841
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1842
- break;
1843
- }
1844
- case SqlType.multipolygon: {
1845
- field[DBType.Mysql] = () => `${field.C2()} multipolygon ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1846
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1847
- break;
1848
- }
1849
- case SqlType.geometrycollection: {
1850
- field[DBType.Mysql] = () => `${field.C2()} geometrycollection ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2152
+ field[DBType.Postgresql] = () => `${field.C2()} jsonb ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1851
2153
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1852
2154
  break;
1853
2155
  }
@@ -1901,11 +2203,12 @@ export const Field = (config) => {
1901
2203
  const formatDialects = {
1902
2204
  [DBType.Mysql]: mysql,
1903
2205
  [DBType.Sqlite]: sqlite,
1904
- [DBType.SqliteRemote]: sqlite
2206
+ [DBType.SqliteRemote]: sqlite,
2207
+ [DBType.Postgresql]: postgresql,
1905
2208
  };
1906
2209
  export const DB = (config) => {
1907
2210
  return function (constructor) {
1908
- var _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;
2211
+ var _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;
1909
2212
  const __ids = Reflect.getMetadata(_ids, config.clz.prototype) || new Array;
1910
2213
  const __logicIds = Reflect.getMetadata(_logicIds, config.clz.prototype) || new Array;
1911
2214
  const __fields = Reflect.getMetadata(_fields, config.clz.prototype);
@@ -1915,21 +2218,19 @@ export const DB = (config) => {
1915
2218
  const __deleteState = Reflect.getMetadata(_deleteState, config.clz.prototype);
1916
2219
  const __index = Reflect.getMetadata(_index, config.clz.prototype);
1917
2220
  const __def = Reflect.getMetadata(_def, config.clz.prototype);
1918
- const __dbType = config.dbType ?? DBType.Mysql;
1919
- const __formatDialect = formatDialects[__dbType];
2221
+ const __dbType = config.dbType;
1920
2222
  const className = config.tableName?.replace(/_(\w)/g, (a, b) => b.toUpperCase());
1921
2223
  const ClassName = className?.replace(/\w/, (v) => v.toUpperCase());
1922
2224
  const vueName = config.tableName?.replace(/_/g, '-');
1923
2225
  return _0 = class extends constructor {
1924
2226
  constructor() {
1925
2227
  super(...arguments);
1926
- this[_e] = config.tableName;
1927
- this[_f] = className;
1928
- this[_g] = ClassName;
1929
- this[_h] = vueName;
1930
- this[_j] = config.dbName;
1931
- this[_k] = __dbType;
1932
- this[_l] = __formatDialect;
2228
+ this[_f] = config.tableName;
2229
+ this[_g] = className;
2230
+ this[_h] = ClassName;
2231
+ this[_j] = vueName;
2232
+ this[_k] = config.dbName;
2233
+ this[_l] = __dbType;
1933
2234
  this[_m] = config.sqliteVersion;
1934
2235
  this[_o] = Object.assign({}, _defOption, config);
1935
2236
  this[_p] = __ids;
@@ -1964,13 +2265,12 @@ export const DB = (config) => {
1964
2265
  };
1965
2266
  }
1966
2267
  },
1967
- _e = _tableName,
1968
- _f = _className,
1969
- _g = _ClassName,
1970
- _h = _vueName,
1971
- _j = _daoDBName,
1972
- _k = _dbType,
1973
- _l = _formatDialect,
2268
+ _f = _tableName,
2269
+ _g = _className,
2270
+ _h = _ClassName,
2271
+ _j = _vueName,
2272
+ _k = _daoDBName,
2273
+ _l = _dbType,
1974
2274
  _m = _sqlite_version,
1975
2275
  _o = _SqlOption,
1976
2276
  _p = _ids,
@@ -2032,7 +2332,7 @@ export function DeclareService(clz, config) {
2032
2332
  export class SqlService {
2033
2333
  _insert(datas, option) {
2034
2334
  const sqls = [];
2035
- const tableName = Sqlstring.escapeId(option.tableName);
2335
+ const tableName = option.tableName;
2036
2336
  switch (option?.mode) {
2037
2337
  case InsertMode.InsertIfNotExists: {
2038
2338
  const conditions = option.existConditionOtherThanIds || this[_ids];
@@ -2055,10 +2355,28 @@ export class SqlService {
2055
2355
  if (V === null) {
2056
2356
  const field = this[_fields][column];
2057
2357
  if (field?.uuid) {
2058
- questMark.push('UUID()');
2358
+ switch (option.dbType) {
2359
+ case DBType.Postgresql:
2360
+ questMark.push('gen_random_uuid()');
2361
+ break;
2362
+ default:
2363
+ questMark.push('UUID()');
2364
+ break;
2365
+ }
2059
2366
  }
2060
- else if (field?.uuidShort && this[_dbType] === DBType.Mysql) {
2061
- questMark.push('UUID_SHORT()');
2367
+ else if (field?.uuidShort) {
2368
+ switch (option.dbType) {
2369
+ case DBType.Postgresql:
2370
+ questMark.push(`encode(uuid_send(gen_random_uuid()::uuid),'base64')`);
2371
+ break;
2372
+ case DBType.Mysql:
2373
+ questMark.push('UUID_SHORT()');
2374
+ break;
2375
+ default:
2376
+ questMark.push('?');
2377
+ params.push(V);
2378
+ break;
2379
+ }
2062
2380
  }
2063
2381
  else {
2064
2382
  questMark.push('?');
@@ -2083,7 +2401,7 @@ export class SqlService {
2083
2401
  const sql = formatDialect(`INSERT INTO
2084
2402
  ${tableName}
2085
2403
  (${columnNames})
2086
- ${questMarks.join(' UNION ALL ')};`, { dialect: this[_formatDialect] });
2404
+ ${questMarks.join(' UNION ALL ')};`, { dialect: formatDialects[option.dbType] });
2087
2405
  sqls.push({ sql, params });
2088
2406
  break;
2089
2407
  }
@@ -2103,10 +2421,28 @@ export class SqlService {
2103
2421
  if (V === null) {
2104
2422
  const field = this[_fields][column];
2105
2423
  if (field?.uuid) {
2106
- questMark.push('UUID()');
2424
+ switch (option.dbType) {
2425
+ case DBType.Postgresql:
2426
+ questMark.push('gen_random_uuid()');
2427
+ break;
2428
+ default:
2429
+ questMark.push('UUID()');
2430
+ break;
2431
+ }
2107
2432
  }
2108
- else if (field?.uuidShort && this[_dbType] === DBType.Mysql) {
2109
- questMark.push('UUID_SHORT()');
2433
+ else if (field?.uuidShort) {
2434
+ switch (option.dbType) {
2435
+ case DBType.Postgresql:
2436
+ questMark.push(`encode(uuid_send(gen_random_uuid()::uuid),'base64')`);
2437
+ break;
2438
+ case DBType.Mysql:
2439
+ questMark.push('UUID_SHORT()');
2440
+ break;
2441
+ default:
2442
+ questMark.push('?');
2443
+ params.push(V);
2444
+ break;
2445
+ }
2110
2446
  }
2111
2447
  else {
2112
2448
  questMark.push('?');
@@ -2122,11 +2458,11 @@ export class SqlService {
2122
2458
  });
2123
2459
  const columnNames = iterare(finalColumns).map(i => this[_fields][i]?.C2()).join(',');
2124
2460
  const sql = formatDialect(`
2125
- ${this[_dbType] === DBType.Mysql ? '' : 'INSERT OR'} REPLACE INTO
2461
+ ${option.dbType === DBType.Mysql ? '' : 'INSERT OR'} REPLACE INTO
2126
2462
  ${tableName}
2127
2463
  (${columnNames})
2128
2464
  VALUES ${questMarks};
2129
- `, { dialect: this[_formatDialect] });
2465
+ `, { dialect: formatDialects[option.dbType] });
2130
2466
  sqls.push({ sql, params });
2131
2467
  break;
2132
2468
  }
@@ -2146,10 +2482,28 @@ export class SqlService {
2146
2482
  if (V === null) {
2147
2483
  const field = this[_fields][column];
2148
2484
  if (field?.uuid) {
2149
- questMark.push('UUID()');
2485
+ switch (option.dbType) {
2486
+ case DBType.Postgresql:
2487
+ questMark.push('gen_random_uuid()');
2488
+ break;
2489
+ default:
2490
+ questMark.push('UUID()');
2491
+ break;
2492
+ }
2150
2493
  }
2151
- else if (field?.uuidShort && this[_dbType] === DBType.Mysql) {
2152
- questMark.push('UUID_SHORT()');
2494
+ else if (field?.uuidShort) {
2495
+ switch (option.dbType) {
2496
+ case DBType.Postgresql:
2497
+ questMark.push(`encode(uuid_send(gen_random_uuid()::uuid),'base64')`);
2498
+ break;
2499
+ case DBType.Mysql:
2500
+ questMark.push('UUID_SHORT()');
2501
+ break;
2502
+ default:
2503
+ questMark.push('?');
2504
+ params.push(V);
2505
+ break;
2506
+ }
2153
2507
  }
2154
2508
  else {
2155
2509
  questMark.push('?');
@@ -2169,13 +2523,13 @@ export class SqlService {
2169
2523
  ${tableName}
2170
2524
  (${columnNames})
2171
2525
  VALUES ${questMarks};
2172
- `, { dialect: this[_formatDialect] });
2526
+ `, { dialect: formatDialects[option.dbType] });
2173
2527
  sqls.push({ sql, params });
2174
2528
  break;
2175
2529
  }
2176
2530
  case InsertMode.InsertWithTempTable: {
2177
2531
  const tableTemp = `${option?.tableName}_${Math.random()}`.replace(/\./, '');
2178
- const tableTempESC = Sqlstring.escapeId(tableTemp);
2532
+ const tableTempESC = tableTemp;
2179
2533
  sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
2180
2534
  const finalColumns = new Set();
2181
2535
  const params = [];
@@ -2192,10 +2546,28 @@ export class SqlService {
2192
2546
  if (V === null) {
2193
2547
  const field = this[_fields][column];
2194
2548
  if (field?.uuid) {
2195
- questMark.push('UUID()');
2549
+ switch (option.dbType) {
2550
+ case DBType.Postgresql:
2551
+ questMark.push('gen_random_uuid()');
2552
+ break;
2553
+ default:
2554
+ questMark.push('UUID()');
2555
+ break;
2556
+ }
2196
2557
  }
2197
- else if (field?.uuidShort && this[_dbType] === DBType.Mysql) {
2198
- questMark.push('UUID_SHORT()');
2558
+ else if (field?.uuidShort) {
2559
+ switch (option.dbType) {
2560
+ case DBType.Postgresql:
2561
+ questMark.push(`encode(uuid_send(gen_random_uuid()::uuid),'base64')`);
2562
+ break;
2563
+ case DBType.Mysql:
2564
+ questMark.push('UUID_SHORT()');
2565
+ break;
2566
+ default:
2567
+ questMark.push('?');
2568
+ params.push(V);
2569
+ break;
2570
+ }
2199
2571
  }
2200
2572
  else {
2201
2573
  questMark.push('?');
@@ -2218,11 +2590,11 @@ export class SqlService {
2218
2590
  ${tableTemp}
2219
2591
  (${columnNames})
2220
2592
  VALUES ${questMarks};
2221
- `, { dialect: this[_formatDialect] }), params
2593
+ `, { dialect: formatDialects[option.dbType] }), params
2222
2594
  });
2223
2595
  sqls.push({
2224
- sql: formatDialect(`INSERT INTO ${Sqlstring.escapeId(option.tableName)} (${columnNames})
2225
- SELECT ${columnNames} FROM ${tableTemp};`, { dialect: this[_formatDialect] })
2596
+ sql: formatDialect(`INSERT INTO ${option.tableName} (${columnNames})
2597
+ SELECT ${columnNames} FROM ${tableTemp};`, { dialect: formatDialects[option.dbType] })
2226
2598
  });
2227
2599
  sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
2228
2600
  break;
@@ -2242,7 +2614,7 @@ export class SqlService {
2242
2614
  for (const { sql, params } of sqls) {
2243
2615
  const dd = option.conn.execute(SyncMode.Sync, sql, params);
2244
2616
  if (dd.insertId) {
2245
- result += dd.insertId;
2617
+ result += BigInt(dd.insertId);
2246
2618
  }
2247
2619
  }
2248
2620
  return result;
@@ -2252,7 +2624,7 @@ export class SqlService {
2252
2624
  else
2253
2625
  return result[0];
2254
2626
  };
2255
- if (this[_dbType] === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
2627
+ if (option.dbType === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
2256
2628
  return fn();
2257
2629
  }
2258
2630
  else {
@@ -2267,30 +2639,19 @@ export class SqlService {
2267
2639
  for (const { sql, params } of sqls) {
2268
2640
  const dd = await option.conn.execute(SyncMode.Async, sql, params);
2269
2641
  if (dd.insertId) {
2270
- result += dd.insertId;
2642
+ result += BigInt(dd.insertId);
2271
2643
  }
2272
2644
  }
2273
2645
  return result;
2274
2646
  }, { everyLength: option?.every === true ? 1 : option?.maxDeal });
2275
2647
  return result;
2276
2648
  };
2277
- if (this[_dbType] === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
2649
+ if (option.dbType === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
2278
2650
  return fn();
2279
2651
  }
2280
2652
  else {
2281
2653
  return option?.dao?.transaction(SyncMode.Async, fn, option?.conn);
2282
2654
  }
2283
- // return new Promise<bigint[]>(async (resolve, reject) => {
2284
- // try {
2285
- // if (this[_dbType] === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
2286
- // resolve((await fn())!);
2287
- // } else {
2288
- // await option?.dao?.transaction(SyncMode.Async, async () => resolve((await fn())!), option?.conn);
2289
- // }
2290
- // } catch (error) {
2291
- // reject(error);
2292
- // }
2293
- // });
2294
2655
  }
2295
2656
  else {
2296
2657
  const fn = async () => {
@@ -2307,28 +2668,17 @@ export class SqlService {
2307
2668
  }, { everyLength: 1 });
2308
2669
  return result[0];
2309
2670
  };
2310
- if (this[_dbType] === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
2671
+ if (option.dbType === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
2311
2672
  return fn();
2312
2673
  }
2313
2674
  else {
2314
2675
  return option?.dao?.transaction(SyncMode.Async, fn, option?.conn);
2315
2676
  }
2316
- // return new Promise<bigint>(async (resolve, reject) => {
2317
- // try {
2318
- // if (this[_dbType] === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
2319
- // resolve((await fn())!);
2320
- // } else {
2321
- // await option?.dao?.transaction(SyncMode.Async, async () => resolve((await fn())!), option?.conn);
2322
- // }
2323
- // } catch (error) {
2324
- // reject(error);
2325
- // }
2326
- // });
2327
2677
  }
2328
2678
  }
2329
2679
  _update(datas, option) {
2330
2680
  const sqls = [];
2331
- const tableName = Sqlstring.escapeId(option?.tableName);
2681
+ const tableName = option?.tableName;
2332
2682
  const where = `WHEN ${iterare(this[_ids]).map(c => `${this[_fields][c]?.C2()} = ?`).join(' AND ')} THEN ?`;
2333
2683
  const columnMaps = Object.fromEntries(this[_columnsNoId].map(c => [c, {
2334
2684
  where: new Array(),
@@ -2355,7 +2705,7 @@ export class SqlService {
2355
2705
  params.push(...columnMaps[K].params);
2356
2706
  return `${this[_fields][K]?.C2()} = CASE ${columnMaps[K].where.join(' ')} ELSE ${this[_fields][K]?.C2()} END`;
2357
2707
  })
2358
- .join(',')};`, { dialect: this[_formatDialect] });
2708
+ .join(',')};`, { dialect: formatDialects[option.dbType] });
2359
2709
  sqls.push({ sql, params });
2360
2710
  return sqls;
2361
2711
  }
@@ -2377,7 +2727,7 @@ export class SqlService {
2377
2727
  }, { everyLength: option?.maxDeal });
2378
2728
  return result.reduce((a, b) => a + b);
2379
2729
  };
2380
- if (this[_dbType] === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
2730
+ if (option.dbType === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
2381
2731
  return fn();
2382
2732
  }
2383
2733
  else {
@@ -2399,25 +2749,12 @@ export class SqlService {
2399
2749
  }, { everyLength: option?.maxDeal });
2400
2750
  return result.reduce((a, b) => a + b);
2401
2751
  };
2402
- if (this[_dbType] === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
2752
+ if (option.dbType === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
2403
2753
  return fn();
2404
2754
  }
2405
2755
  else {
2406
2756
  return option?.dao?.transaction(SyncMode.Async, fn, option?.conn);
2407
2757
  }
2408
- return new Promise(async (resolve, reject) => {
2409
- try {
2410
- if (this[_dbType] === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
2411
- resolve((await fn()));
2412
- }
2413
- else {
2414
- await option?.dao?.transaction(SyncMode.Async, async () => resolve((await fn())), option?.conn);
2415
- }
2416
- }
2417
- catch (error) {
2418
- reject(error);
2419
- }
2420
- });
2421
2758
  }
2422
2759
  }
2423
2760
  delete(option) {
@@ -2428,8 +2765,8 @@ export class SqlService {
2428
2765
  Throw.if(!!option.id && !!option.where, 'id and where only one can set!');
2429
2766
  option.mode ?? (option.mode = DeleteMode.Common);
2430
2767
  const tableTemp = `${option?.tableName}_${Math.random()}`.replace(/\./, '');
2431
- const tableTempESC = Sqlstring.escapeId(tableTemp);
2432
- const tableNameESC = Sqlstring.escapeId(option?.tableName);
2768
+ const tableTempESC = tableTemp;
2769
+ const tableNameESC = option?.tableName;
2433
2770
  if (option.id) {
2434
2771
  const idName = this[_ids][0];
2435
2772
  const ids = option.id instanceof Array ? option.id : [option.id];
@@ -2453,11 +2790,11 @@ export class SqlService {
2453
2790
  sql: formatDialect(`
2454
2791
  UPDATE ${tableNameESC} SET ${this[_fields][this[_stateFileName]]?.C2()} = ?
2455
2792
  WHERE ${whereSql};
2456
- `, { dialect: this[_formatDialect] }), params
2793
+ `, { dialect: formatDialects[option.dbType] }), params
2457
2794
  });
2458
2795
  }
2459
2796
  else {
2460
- sqls.push({ sql: formatDialect(`DELETE FROM ${tableNameESC} WHERE ${whereSql};`, { dialect: this[_formatDialect] }), params });
2797
+ sqls.push({ sql: formatDialect(`DELETE FROM ${tableNameESC} WHERE ${whereSql};`, { dialect: formatDialects[option.dbType] }), params });
2461
2798
  }
2462
2799
  }
2463
2800
  else {
@@ -2465,18 +2802,18 @@ export class SqlService {
2465
2802
  const delWhere = Object.keys(wheres[0]);
2466
2803
  const _sqls = this._createTable({ tableName: tableTemp, temp: true, columns: delWhere, data: wheres, index: 'all', id: 'none' });
2467
2804
  sqls.push(..._sqls);
2468
- switch (this[_dbType]) {
2805
+ switch (option.dbType) {
2469
2806
  case DBType.Mysql: {
2470
2807
  if (this[_stateFileName] !== undefined && option.forceDelete !== true) {
2471
2808
  sqls.push({
2472
2809
  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 ')}
2473
- SET a.${this[_fields][this[_stateFileName]]?.C2()} = ?;`, { dialect: this[_formatDialect] }),
2810
+ SET a.${this[_fields][this[_stateFileName]]?.C2()} = ?;`, { dialect: formatDialects[option.dbType] }),
2474
2811
  params: [this[_deleteState]]
2475
2812
  });
2476
2813
  }
2477
2814
  else {
2478
2815
  sqls.push({
2479
- 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] })
2816
+ 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: formatDialects[option.dbType] })
2480
2817
  });
2481
2818
  }
2482
2819
  break;
@@ -2487,12 +2824,12 @@ export class SqlService {
2487
2824
  if (this[_stateFileName] !== undefined && option.forceDelete !== true) {
2488
2825
  sqls.push({
2489
2826
  sql: formatDialect(`UPDATE ${tableNameESC} SET ${this[_fields][this[_stateFileName]]?.C2()} = ?
2490
- WHERE (${columnNames}) IN (SELECT ${columnNames} FROM ${tableTempESC});`, { dialect: this[_formatDialect] }),
2827
+ WHERE (${columnNames}) IN (SELECT ${columnNames} FROM ${tableTempESC});`, { dialect: formatDialects[option.dbType] }),
2491
2828
  params: [this[_deleteState]]
2492
2829
  });
2493
2830
  }
2494
2831
  else {
2495
- sqls.push({ sql: formatDialect(`DELETE FROM ${tableNameESC} WHERE (${columnNames}) IN (SELECT ${columnNames} FROM ${tableTempESC});`, { dialect: this[_formatDialect] }) });
2832
+ sqls.push({ sql: formatDialect(`DELETE FROM ${tableNameESC} WHERE (${columnNames}) IN (SELECT ${columnNames} FROM ${tableTempESC});`, { dialect: formatDialects[option.dbType] }) });
2496
2833
  }
2497
2834
  break;
2498
2835
  }
@@ -2508,7 +2845,7 @@ export class SqlService {
2508
2845
  }
2509
2846
  return result;
2510
2847
  };
2511
- if (this[_dbType] === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
2848
+ if (option.dbType === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
2512
2849
  return fn();
2513
2850
  }
2514
2851
  else {
@@ -2524,23 +2861,12 @@ export class SqlService {
2524
2861
  }
2525
2862
  return result;
2526
2863
  };
2527
- if (this[_dbType] === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
2864
+ if (option.dbType === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
2528
2865
  return fn();
2529
2866
  }
2530
2867
  else {
2531
2868
  return option?.dao?.transaction(SyncMode.Async, fn, option?.conn);
2532
2869
  }
2533
- // return new Promise<number>(async (resolve, reject) => {
2534
- // try {
2535
- // if (this[_dbType] === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
2536
- // resolve((await fn())!);
2537
- // } else {
2538
- // await option?.dao?.transaction(SyncMode.Async, async () => resolve((await fn())!), option?.conn);
2539
- // }
2540
- // } catch (error) {
2541
- // reject(error);
2542
- // }
2543
- // });
2544
2870
  }
2545
2871
  }
2546
2872
  _template(templateResult, result, error) {
@@ -2573,8 +2899,8 @@ export class SqlService {
2573
2899
  option.templateResult ?? (option.templateResult = TemplateResult.AssertOne);
2574
2900
  option.error ?? (option.error = 'error data!');
2575
2901
  const tableTemp = `${option?.tableName}_${Math.random()}`.replace(/\./, '');
2576
- const tableTempESC = Sqlstring.escapeId(tableTemp);
2577
- const tableNameESC = Sqlstring.escapeId(option?.tableName);
2902
+ const tableTempESC = tableTemp;
2903
+ const tableNameESC = option?.tableName;
2578
2904
  if (option.id) {
2579
2905
  const idName = this[_ids][0];
2580
2906
  const ids = option.id instanceof Array ? option.id : [option.id];
@@ -2592,7 +2918,7 @@ export class SqlService {
2592
2918
  params.push(V);
2593
2919
  return `${this[_fields][K]?.C2()} = ?`;
2594
2920
  }).join(' AND ')}`;
2595
- }).join(' UNION ALL '), { dialect: this[_formatDialect] });
2921
+ }).join(' UNION ALL '), { dialect: formatDialects[option.dbType] });
2596
2922
  sqls.push({ sql: whereSql, params });
2597
2923
  resultIndex = 0;
2598
2924
  }
@@ -2602,7 +2928,7 @@ export class SqlService {
2602
2928
  const _sqls = this._createTable({ tableName: tableTemp, temp: true, columns: delWhere, data: wheres, index: 'all', id: 'none' });
2603
2929
  sqls.push(..._sqls);
2604
2930
  resultIndex = sqls.length;
2605
- 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] }) });
2931
+ 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: formatDialects[option.dbType] }) });
2606
2932
  sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
2607
2933
  }
2608
2934
  if (option.sync === SyncMode.Sync) {
@@ -2750,7 +3076,7 @@ export class SqlService {
2750
3076
  return '?';
2751
3077
  }
2752
3078
  return txt;
2753
- }), { dialect: this[_formatDialect] });
3079
+ }), { dialect: formatDialects[option.dbType] });
2754
3080
  if (option.sync === SyncMode.Sync) {
2755
3081
  const result = option.conn.query(SyncMode.Sync, sql, params);
2756
3082
  return this._select(option.selectResult, result, option.defValue, option.errorMsg, option.hump, option.mapper, option.mapperIfUndefined);
@@ -2791,7 +3117,7 @@ export class SqlService {
2791
3117
  return '?';
2792
3118
  }
2793
3119
  return txt;
2794
- }), { dialect: this[_formatDialect] });
3120
+ }), { dialect: formatDialects[option.dbType] });
2795
3121
  if (option.sync === SyncMode.Sync) {
2796
3122
  const result = option.conn.execute(SyncMode.Sync, sql, params);
2797
3123
  return result.affectedRows;
@@ -2824,8 +3150,8 @@ export class SqlService {
2824
3150
  });
2825
3151
  }
2826
3152
  }
2827
- stream(option) {
2828
- return new StreamQuery(option?.tableName ?? this[_tableName], this, this[_fields], this[_columns]);
3153
+ stream() {
3154
+ return new StreamQuery(this, this[_fields], this[_columns]);
2829
3155
  }
2830
3156
  page(option) {
2831
3157
  const result = {
@@ -2976,10 +3302,10 @@ export class SqlService {
2976
3302
  return { title, titleSpan, columnTitles };
2977
3303
  }
2978
3304
  init(option) {
2979
- var _e;
2980
- const tableES = Sqlstring.escapeId(option.tableName);
2981
- (_e = option).force ?? (_e.force = false);
2982
- if (this[_dbType] === DBType.Sqlite) {
3305
+ var _f;
3306
+ const tableES = option.tableName;
3307
+ (_f = option).force ?? (_f.force = false);
3308
+ if (option.dbType === DBType.Sqlite) {
2983
3309
  if (option?.force) {
2984
3310
  option.conn.execute(SyncMode.Sync, `DROP TABLE IF EXISTS ${tableES};`);
2985
3311
  }
@@ -2993,9 +3319,9 @@ export class SqlService {
2993
3319
  // 更新版本
2994
3320
  const columns = iterare(option.conn.query(SyncMode.Sync, `PRAGMA table_info(${tableES})`))
2995
3321
  .filter(c => this[_fields].hasOwnProperty(C2P(c.name, globalThis[_Hump])))
2996
- .map(c => Sqlstring.escapeId(c.name))
3322
+ .map(c => c.name)
2997
3323
  .join(',');
2998
- const rtable = Sqlstring.escapeId(`${option.tableName}_${tableVersion.replace(/\./, '_')}`);
3324
+ const rtable = `${option.tableName}_${tableVersion.replace(/\./, '_')}`;
2999
3325
  option.conn.execute(SyncMode.Sync, `DROP TABLE IF EXISTS ${rtable};`);
3000
3326
  option.conn.execute(SyncMode.Sync, `ALTER TABLE ${tableES} RENAME TO ${rtable};`);
3001
3327
  option.conn.execute(SyncMode.Sync, `
@@ -3006,7 +3332,7 @@ export class SqlService {
3006
3332
  `);
3007
3333
  if (this[_index] && this[_index].length) {
3008
3334
  for (const index of this[_index]) {
3009
- option.conn.execute(SyncMode.Sync, `CREATE INDEX ${Sqlstring.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${this[_fields][index]?.C2()}");`);
3335
+ option.conn.execute(SyncMode.Sync, `CREATE INDEX ${`${index}_${Math.random()}`.replace(/\./, '')} ON ${tableES} ("${this[_fields][index]?.C2()}");`);
3010
3336
  }
3011
3337
  }
3012
3338
  option.conn.execute(SyncMode.Sync, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
@@ -3030,13 +3356,13 @@ export class SqlService {
3030
3356
  `);
3031
3357
  if (this[_index] && this[_index].length) {
3032
3358
  for (const index of this[_index]) {
3033
- option.conn.execute(SyncMode.Sync, `CREATE INDEX ${Sqlstring.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${this[_fields][index]?.C2()}");`);
3359
+ option.conn.execute(SyncMode.Sync, `CREATE INDEX ${`${index}_${Math.random()}`.replace(/\./, '')} ON ${tableES} ("${this[_fields][index]?.C2()}");`);
3034
3360
  }
3035
3361
  }
3036
3362
  option.conn.execute(SyncMode.Sync, 'INSERT OR REPLACE INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
3037
3363
  }
3038
3364
  }
3039
- else if (this[_dbType] === DBType.SqliteRemote) {
3365
+ else if (option.dbType === DBType.SqliteRemote) {
3040
3366
  return new Promise(async (resolve, reject) => {
3041
3367
  try {
3042
3368
  if (option?.force) {
@@ -3052,7 +3378,7 @@ export class SqlService {
3052
3378
  // 更新版本
3053
3379
  const columns = iterare(await option.conn.query(SyncMode.Async, `PRAGMA table_info(${tableES})`))
3054
3380
  .filter(c => this[_fields].hasOwnProperty(C2P(c.name, globalThis[_Hump])))
3055
- .map(c => Sqlstring.escapeId(c.name))
3381
+ .map(c => c.name)
3056
3382
  .join(',');
3057
3383
  const rtable = `${option.tableName}_${tableVersion.replace(/\./, '_')}`;
3058
3384
  await option.conn.execute(SyncMode.Async, `DROP TABLE IF EXISTS ${rtable};`);
@@ -3065,7 +3391,7 @@ export class SqlService {
3065
3391
  `);
3066
3392
  if (this[_index] && this[_index].length) {
3067
3393
  for (const index of this[_index]) {
3068
- await option.conn.execute(SyncMode.Async, `CREATE INDEX ${Sqlstring.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${this[_fields][index]?.C2()}");`);
3394
+ await option.conn.execute(SyncMode.Async, `CREATE INDEX ${`${index}_${Math.random()}`.replace(/\./, '')} ON ${tableES} ("${this[_fields][index]?.C2()}");`);
3069
3395
  }
3070
3396
  }
3071
3397
  await option.conn.execute(SyncMode.Async, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
@@ -3088,7 +3414,7 @@ export class SqlService {
3088
3414
  `);
3089
3415
  if (this[_index] && this[_index].length) {
3090
3416
  for (const index of this[_index]) {
3091
- await option.conn.execute(SyncMode.Async, `CREATE INDEX ${Sqlstring.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${Sqlstring.escapeId(option.tableName)} ("${this[_fields][index]?.C2()}");`);
3417
+ await option.conn.execute(SyncMode.Async, `CREATE INDEX ${`${index}_${Math.random()}`.replace(/\./, '')} ON ${option.tableName} ("${this[_fields][index]?.C2()}");`);
3092
3418
  }
3093
3419
  }
3094
3420
  await option.conn.execute(SyncMode.Async, 'INSERT OR REPLACE INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
@@ -3102,8 +3428,7 @@ export class SqlService {
3102
3428
  }
3103
3429
  }
3104
3430
  close(option) {
3105
- const dbName = option?.dbName ?? this[_daoDBName] ?? _primaryDB;
3106
- delete globalThis[_dao][this[_dbType]][dbName];
3431
+ delete globalThis[_dao][option.dbType][option.dbName];
3107
3432
  if (option?.sync === SyncMode.Async) {
3108
3433
  return option.dao.close(SyncMode.Async);
3109
3434
  }
@@ -3123,7 +3448,7 @@ export class SqlService {
3123
3448
  4. 自定义字段名称:字符串数组
3124
3449
  ** `index` 表的索引,设置方式同ID
3125
3450
  */
3126
- _createTable({ tableName, temp = true, columns, data, id = 'auto', index = 'auto' } = {}) {
3451
+ _createTable({ tableName, temp = true, columns, data, id = 'auto', index = 'auto', dbType } = {}) {
3127
3452
  const sqls = [];
3128
3453
  columns = columns || this[_columns];
3129
3454
  let ids;
@@ -3152,14 +3477,14 @@ export class SqlService {
3152
3477
  else {
3153
3478
  indexs = index;
3154
3479
  }
3155
- tableName = Sqlstring.escapeId(tableName ?? this[_tableName]);
3156
- switch (this[_dbType]) {
3480
+ tableName = tableName ?? this[_tableName];
3481
+ switch (dbType) {
3157
3482
  case DBType.Mysql: {
3158
3483
  let sql = formatDialect(`CREATE ${temp === true ? 'TEMPORARY' : ''} TABLE IF NOT EXISTS ${tableName}(
3159
3484
  ${columns.map(K => this[_fields][K][DBType.Mysql]()).join(',')}
3160
3485
  ${ids && ids.length ? `,PRIMARY KEY (${ids.map(i => this[_fields][i]?.C2()).join(',')}) USING BTREE ` : ''}
3161
3486
  ${indexs && indexs.length ? `,${indexs.map(i => `KEY ${this[_fields][i]?.C2()} (${this[_fields][i]?.C2()})`).join(',')} ` : ''}
3162
- ) ENGINE=MEMORY;`, { dialect: this[_formatDialect] });
3487
+ ) ENGINE=MEMORY;`, { dialect: mysql });
3163
3488
  sqls.push({ sql });
3164
3489
  if (data && data.length > 0) {
3165
3490
  const params = [];
@@ -3172,7 +3497,7 @@ export class SqlService {
3172
3497
  }).join(',')}`;
3173
3498
  first = false;
3174
3499
  return r;
3175
- }).join(' UNION ALL ')}`, { dialect: this[_formatDialect] });
3500
+ }).join(' UNION ALL ')}`, { dialect: mysql });
3176
3501
  sqls.push({ sql, params });
3177
3502
  }
3178
3503
  break;
@@ -3182,11 +3507,11 @@ export class SqlService {
3182
3507
  let sql = formatDialect(`CREATE ${temp === true ? 'TEMPORARY' : ''} TABLE IF NOT EXISTS ${tableName}(
3183
3508
  ${columns.map(K => this[_fields][K][DBType.Sqlite]()).join(',')}
3184
3509
  ${ids && ids.length ? `,PRIMARY KEY (${ids.map(i => this[_fields][i]?.C2()).join(',')}) ` : ''}
3185
- );`, { dialect: this[_formatDialect] });
3510
+ );`, { dialect: sqlite });
3186
3511
  sqls.push({ sql });
3187
3512
  if (indexs) {
3188
3513
  for (const index of indexs) {
3189
- sql = formatDialect(`CREATE INDEX ${Sqlstring.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableName} (${this[_fields][index]?.C2()});`, { dialect: this[_formatDialect] });
3514
+ sql = formatDialect(`CREATE INDEX ${`${index}_${Math.random()}`.replace(/\./, '')} ON ${tableName} (${this[_fields][index]?.C2()});`, { dialect: sqlite });
3190
3515
  sqls.push({ sql });
3191
3516
  }
3192
3517
  }
@@ -3201,7 +3526,7 @@ export class SqlService {
3201
3526
  }).join(',')}`;
3202
3527
  first = false;
3203
3528
  return r;
3204
- }).join(' UNION ALL ')}`, { dialect: this[_formatDialect] });
3529
+ }).join(' UNION ALL ')}`, { dialect: sqlite });
3205
3530
  sqls.push({ sql, params });
3206
3531
  }
3207
3532
  break;
@@ -3311,7 +3636,7 @@ const IF_EXEC = function (def) {
3311
3636
  };
3312
3637
  };
3313
3638
  class StreamQuery {
3314
- constructor(table, service, __fields, __columns) {
3639
+ constructor(service, __fields, __columns) {
3315
3640
  this._prefix = 0;
3316
3641
  this._index = 0;
3317
3642
  this._wheres = [];
@@ -3329,7 +3654,6 @@ class StreamQuery {
3329
3654
  this._startRow = 0;
3330
3655
  this._pageSize = 0;
3331
3656
  this._prefix = parseInt(`${Math.random() * 1000}`);
3332
- this._table = table;
3333
3657
  this._service = service;
3334
3658
  this[_fields] = __fields;
3335
3659
  this[_columns] = __columns;
@@ -3454,7 +3778,7 @@ class StreamQuery {
3454
3778
  this._andQuerys.push(fn);
3455
3779
  }
3456
3780
  else {
3457
- const stream = new StreamQuery(this._table, this._service, this[_fields], this[_columns]);
3781
+ const stream = new StreamQuery(this._service, this[_fields], this[_columns]);
3458
3782
  const ret = fn(stream);
3459
3783
  if (ret !== false) {
3460
3784
  this._andQuerys.push(stream);
@@ -3467,7 +3791,7 @@ class StreamQuery {
3467
3791
  this._andQuerys.push(fn);
3468
3792
  }
3469
3793
  else {
3470
- const stream = new StreamQuery(this._table, this._service, this[_fields], this[_columns]);
3794
+ const stream = new StreamQuery(this._service, this[_fields], this[_columns]);
3471
3795
  const ret = fn(stream);
3472
3796
  if (ret !== false) {
3473
3797
  this._orQuerys.push(stream);
@@ -3483,7 +3807,6 @@ class StreamQuery {
3483
3807
  desc2(...keys) { this._orders.push(...keys.map(key => `${this[_fields][String(key)]?.C2()} ASC`)); return this; }
3484
3808
  limit(startRow, pageSize) { this._startRow = startRow; this._pageSize = pageSize; return this; }
3485
3809
  page(pageNumber, pageSize) { this._startRow = ((pageNumber || 1) - 1) * pageSize; this._pageSize = pageSize; return this; }
3486
- table(_table) { this._table = _table; return this; }
3487
3810
  distinct(on = true) { this._distinct = on; return this; }
3488
3811
  countDistinct(key, countName) { this._columns.push(`COUNT(DISTINCT ${this[_fields][String(key)]?.C2()}) ${countName || `${this[_fields][String(key)]?.C2()}`}`); return this; }
3489
3812
  count(countName) { this._columns.push(`COUNT(1) ${countName ?? 'ct'}`); return this; }
@@ -3527,7 +3850,7 @@ class StreamQuery {
3527
3850
  let sql = `
3528
3851
  SELECT
3529
3852
  ${this._distinct ? 'DISTINCT' : ''} ${this._columns && this._columns.length > 0 ? this._columns.join(',') : this[_columns].map(key => this[_fields][String(key)]?.C3()).join(',')}
3530
- FROM ${this._table}
3853
+ FROM ${option.tableName ?? this._service[_tableName]}
3531
3854
  ${where ? ' WHERE ' : ''}
3532
3855
  ${where}
3533
3856
  ${this._groups.length > 0 ? `GROUP BY ${this._groups.join(',')} ` : ''}
@@ -3576,7 +3899,7 @@ class StreamQuery {
3576
3899
  let sql = `
3577
3900
  SELECT
3578
3901
  ${this._distinct ? 'DISTINCT' : ''} ${this._columns && this._columns.length > 0 ? this._columns.join(',') : this[_columns].map(key => this[_fields][String(key)]?.C3()).join(',')}
3579
- FROM ${this._table}
3902
+ FROM ${option.tableName ?? this._service[_tableName]}
3580
3903
  ${where ? ' WHERE ' : ''}
3581
3904
  ${where}
3582
3905
  ${this._groups.length > 0 ? `GROUP BY ${this._groups.join(',')} ` : ''}
@@ -3590,7 +3913,7 @@ class StreamQuery {
3590
3913
  }
3591
3914
  const sqlCount = `
3592
3915
  SELECT COUNT(1)
3593
- FROM ${this._table}
3916
+ FROM ${option.tableName ?? this._service[_tableName]}
3594
3917
  ${where ? ' WHERE ' : ''}
3595
3918
  ${where}
3596
3919
  ${this._groups.length > 0 ? `GROUP BY ${this._groups.join(',')} ` : ''}
@@ -3661,7 +3984,7 @@ class StreamQuery {
3661
3984
  }
3662
3985
  }
3663
3986
  if (sets.length > 0) {
3664
- const sql = `UPDATE ${this._table} SET ${sets.join(',')}
3987
+ const sql = `UPDATE ${option.tableName ?? this._service[_tableName]} SET ${sets.join(',')}
3665
3988
  ${where ? ' WHERE ' : ''}
3666
3989
  ${where}
3667
3990
  `;
@@ -3680,7 +4003,7 @@ class StreamQuery {
3680
4003
  option ?? (option = {});
3681
4004
  option.sync ?? (option.sync = SyncMode.Async);
3682
4005
  const { where, params } = this._where();
3683
- const sql = `DELETE FROM ${this._table}
4006
+ const sql = `DELETE FROM ${option.tableName ?? this._service[_tableName]}
3684
4007
  ${where ? ' WHERE ' : ''}
3685
4008
  ${where}
3686
4009
  `;
@@ -4277,12 +4600,6 @@ __decorate([
4277
4600
  __metadata("design:paramtypes", [Number, Number]),
4278
4601
  __metadata("design:returntype", void 0)
4279
4602
  ], StreamQuery.prototype, "page", null);
4280
- __decorate([
4281
- IF_PROCEED(),
4282
- __metadata("design:type", Function),
4283
- __metadata("design:paramtypes", [String]),
4284
- __metadata("design:returntype", void 0)
4285
- ], StreamQuery.prototype, "table", null);
4286
4603
  __decorate([
4287
4604
  IF_PROCEED(),
4288
4605
  __metadata("design:type", Function),