baja-lite 1.0.27 → 1.0.30
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/boot.js +18 -0
- package/cjs/sql.d.ts +91 -24
- package/cjs/sql.js +573 -247
- package/cjs/test-postgresql.d.ts +2 -0
- package/cjs/test-postgresql.js +93 -0
- package/es/boot.js +19 -1
- package/es/sql.d.ts +91 -24
- package/es/sql.js +572 -247
- package/es/test-postgresql.d.ts +2 -0
- package/es/test-postgresql.js +90 -0
- package/package.json +14 -9
- package/src/boot.ts +22 -1
- package/src/sql.ts +613 -229
- package/src/test-postgresql.ts +79 -0
package/src/sql.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { Throw } from './error';
|
|
2
2
|
import tslib from 'tslib';
|
|
3
|
-
import Sqlstring from 'sqlstring';
|
|
4
3
|
import iterare from 'iterare';
|
|
5
4
|
import { emptyString } from './string';
|
|
6
5
|
import pino from 'pino';
|
|
@@ -8,7 +7,7 @@ import { excuteSplit, ExcuteSplitMode, sleep } from './fn';
|
|
|
8
7
|
import { add, calc, ten2Any } from './math';
|
|
9
8
|
import mustache, { PartialsOrLookupFn } from 'mustache';
|
|
10
9
|
import { C2P, C2P2, P2C } from './object';
|
|
11
|
-
import { formatDialect, sqlite, mysql,
|
|
10
|
+
import { formatDialect, sqlite, mysql, postgresql } from 'sql-formatter';
|
|
12
11
|
import HTML from 'html-parse-stringify';
|
|
13
12
|
import { XML, convert } from './convert-xml';
|
|
14
13
|
import { ArrayList } from './list';
|
|
@@ -16,7 +15,6 @@ import LGet from 'lodash.get';
|
|
|
16
15
|
import { EnumMap } from './enum';
|
|
17
16
|
import { encode, decode, ExtensionCodec, DecodeError } from "@msgpack/msgpack";
|
|
18
17
|
(BigInt.prototype as any).toJSON = function () { return this.toString() }
|
|
19
|
-
|
|
20
18
|
const BIGINT_EXT_TYPE = 0;
|
|
21
19
|
export const extensionCodec = new ExtensionCodec();
|
|
22
20
|
extensionCodec.register({
|
|
@@ -63,7 +61,6 @@ export const _sqlCache = Symbol('sqlMap');
|
|
|
63
61
|
export const _dao = Symbol('dao');
|
|
64
62
|
export const _primaryDB = '______primaryDB_______';
|
|
65
63
|
const _dbType = Symbol('dbType');
|
|
66
|
-
const _formatDialect = Symbol('FormatDialect');
|
|
67
64
|
const _sqlite_version = Symbol('sqlite_version');
|
|
68
65
|
const _daoConnection = Symbol('daoConnection');
|
|
69
66
|
const _inTransaction = Symbol('inTransaction');
|
|
@@ -89,7 +86,7 @@ globalThis[_resultMap_SQLID] = {};
|
|
|
89
86
|
// #endregion
|
|
90
87
|
|
|
91
88
|
// #region 可选配置
|
|
92
|
-
export enum DBType { Mysql, Sqlite, Mongo, SqliteRemote, Redis, RedisLock };
|
|
89
|
+
export enum DBType { Mysql, Postgresql, Sqlite, Mongo, SqliteRemote, Redis, RedisLock };
|
|
93
90
|
export enum MapperIfUndefined { Null, Skip, Zero, EmptyString };
|
|
94
91
|
export enum SyncMode {
|
|
95
92
|
/** 同步执行 */
|
|
@@ -214,19 +211,7 @@ export enum SqlType {
|
|
|
214
211
|
longblob,
|
|
215
212
|
longtext,
|
|
216
213
|
|
|
217
|
-
|
|
218
|
-
enum,
|
|
219
|
-
|
|
220
|
-
json,
|
|
221
|
-
|
|
222
|
-
geometry,
|
|
223
|
-
point,
|
|
224
|
-
linestring,
|
|
225
|
-
polygon,
|
|
226
|
-
multipoint,
|
|
227
|
-
multilinestring,
|
|
228
|
-
multipolygon,
|
|
229
|
-
geometrycollection
|
|
214
|
+
json
|
|
230
215
|
|
|
231
216
|
}
|
|
232
217
|
export enum ColumnMode {
|
|
@@ -240,6 +225,7 @@ interface MethodOption {
|
|
|
240
225
|
tableName?: string;
|
|
241
226
|
/** 数据库、连接名称,对于MYSQL、mongo,适用于多数据源,对于sqlite,适用于不同的数据库文件 */
|
|
242
227
|
dbName?: string;
|
|
228
|
+
dbType?: DBType;
|
|
243
229
|
/** 调用时,永远不需要传
|
|
244
230
|
* @deprecated
|
|
245
231
|
* */
|
|
@@ -285,7 +271,6 @@ interface ServiceOption {
|
|
|
285
271
|
}
|
|
286
272
|
/**
|
|
287
273
|
# 全局行为配置文件
|
|
288
|
-
MYSQL编码: 'utf8mb4', utf8mb4_general_ci'
|
|
289
274
|
### `sqlDir?: string;` 数据库查询语句存放目录.存放格式为 export.default 的js、ts, 存放内容满足格式:
|
|
290
275
|
|
|
291
276
|
```
|
|
@@ -310,7 +295,7 @@ export interface GlobalSqlOptionForWeb {
|
|
|
310
295
|
```
|
|
311
296
|
db: 'd:/1.db'
|
|
312
297
|
```
|
|
313
|
-
##
|
|
298
|
+
## 多数据源:传入多个连接配置
|
|
314
299
|
```
|
|
315
300
|
db: {
|
|
316
301
|
db1: 'd:/1.db',
|
|
@@ -360,6 +345,8 @@ export interface GlobalSqlOptionForWeb {
|
|
|
360
345
|
* ```
|
|
361
346
|
*/
|
|
362
347
|
columnMode?: ColumnMode;
|
|
348
|
+
/** 对于WEB模式,默认为SqliteRemote */
|
|
349
|
+
dbType?: DBType;
|
|
363
350
|
}
|
|
364
351
|
/**
|
|
365
352
|
# 全局行为配置文件
|
|
@@ -400,12 +387,70 @@ export interface GlobalSqlOption extends GlobalSqlOptionForWeb {
|
|
|
400
387
|
```
|
|
401
388
|
*/
|
|
402
389
|
Mysql?: Record<string, Record<string, any>> | Record<string, any>;
|
|
390
|
+
/**
|
|
391
|
+
初始化postgresql链接 支持多数据源
|
|
392
|
+
## 单一数据源: 直接传入postgresql的连接配置
|
|
393
|
+
[Postgresql初始化文档](https://github.com/brianc/node-postgres/tree/master/packages/pg-pool)
|
|
394
|
+
```
|
|
395
|
+
Postgresql: {
|
|
396
|
+
database: 'postgres',
|
|
397
|
+
user: 'brianc',
|
|
398
|
+
password: 'secret!',
|
|
399
|
+
port: 5432,
|
|
400
|
+
ssl: true,
|
|
401
|
+
max: 20, // set pool max size to 20
|
|
402
|
+
idleTimeoutMillis: 1000, // close idle clients after 1 second
|
|
403
|
+
connectionTimeoutMillis: 1000, // return an error after 1 second if connection could not be established
|
|
404
|
+
maxUses: 7500, // close (and replace) a connection after it has been used 7500 times (see below for discussion)
|
|
405
|
+
host?: string | undefined;
|
|
406
|
+
connectionString?: string | undefined;
|
|
407
|
+
keepAlive?: boolean | undefined;
|
|
408
|
+
stream?: () => stream.Duplex | stream.Duplex | undefined;
|
|
409
|
+
statement_timeout?: false | number | undefined;
|
|
410
|
+
query_timeout?: number | undefined;
|
|
411
|
+
keepAliveInitialDelayMillis?: number | undefined;
|
|
412
|
+
idle_in_transaction_session_timeout?: number | undefined;
|
|
413
|
+
application_name?: string | undefined;
|
|
414
|
+
types?: CustomTypesConfig | undefined;
|
|
415
|
+
options?: string | undefined;
|
|
416
|
+
}
|
|
417
|
+
```
|
|
418
|
+
## 多数据源:传入多个Postgresql的连接配置
|
|
419
|
+
```
|
|
420
|
+
Postgresql: {
|
|
421
|
+
db1: {
|
|
422
|
+
database: 'postgres',
|
|
423
|
+
user: 'brianc',
|
|
424
|
+
password: 'secret!',
|
|
425
|
+
port: 5432,
|
|
426
|
+
ssl: true,
|
|
427
|
+
max: 20, // set pool max size to 20
|
|
428
|
+
idleTimeoutMillis: 1000, // close idle clients after 1 second
|
|
429
|
+
connectionTimeoutMillis: 1000, // return an error after 1 second if connection could not be established
|
|
430
|
+
maxUses: 7500, // close (and replace) a connection after it has been used 7500 times (see below for discussion)
|
|
431
|
+
},
|
|
432
|
+
db2: {
|
|
433
|
+
database: 'postgres',
|
|
434
|
+
user: 'brianc',
|
|
435
|
+
password: 'secret!',
|
|
436
|
+
port: 5432,
|
|
437
|
+
ssl: true,
|
|
438
|
+
max: 20, // set pool max size to 20
|
|
439
|
+
idleTimeoutMillis: 1000, // close idle clients after 1 second
|
|
440
|
+
connectionTimeoutMillis: 1000, // return an error after 1 second if connection could not be established
|
|
441
|
+
maxUses: 7500, // close (and replace) a connection after it has been used 7500 times (see below for discussion)
|
|
442
|
+
},
|
|
443
|
+
...
|
|
444
|
+
}
|
|
445
|
+
```
|
|
446
|
+
*/
|
|
447
|
+
Postgresql?: Record<string, Record<string, any>> | Record<string, any>;
|
|
403
448
|
/**
|
|
404
449
|
## 单一数据源
|
|
405
450
|
```
|
|
406
451
|
Sqlite: 'd:/1.db'
|
|
407
452
|
```
|
|
408
|
-
##
|
|
453
|
+
## 多数据源:传入多个连接配置
|
|
409
454
|
```
|
|
410
455
|
Sqlite: {
|
|
411
456
|
db1: 'd:/1.db',
|
|
@@ -535,6 +580,7 @@ interface AField extends FieldOption {
|
|
|
535
580
|
/** 查询用:b_id bId */
|
|
536
581
|
C3: () => string;
|
|
537
582
|
|
|
583
|
+
[DBType.Postgresql]: () => string;
|
|
538
584
|
[DBType.Mysql]: () => string;
|
|
539
585
|
[DBType.Sqlite]: () => string;
|
|
540
586
|
[DBType.SqliteRemote]: () => string;
|
|
@@ -613,7 +659,7 @@ class MysqlConnection implements Connection {
|
|
|
613
659
|
return { affectedRows: 0, insertId: 0n };
|
|
614
660
|
};
|
|
615
661
|
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
616
|
-
logger.trace(
|
|
662
|
+
logger.trace(sql!, params);
|
|
617
663
|
}
|
|
618
664
|
return new Promise<{ affectedRows: number; insertId: bigint; }>(async (resolve, reject) => {
|
|
619
665
|
try {
|
|
@@ -644,7 +690,7 @@ class MysqlConnection implements Connection {
|
|
|
644
690
|
return null;
|
|
645
691
|
};
|
|
646
692
|
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
647
|
-
logger.trace(
|
|
693
|
+
logger.trace(sql!, params);
|
|
648
694
|
}
|
|
649
695
|
return new Promise<T | null>(async (resolve, reject) => {
|
|
650
696
|
try {
|
|
@@ -676,7 +722,7 @@ class MysqlConnection implements Connection {
|
|
|
676
722
|
return null;
|
|
677
723
|
};
|
|
678
724
|
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
679
|
-
logger.trace(
|
|
725
|
+
logger.trace(sql!, params);
|
|
680
726
|
}
|
|
681
727
|
return new Promise<T | null>(async (resolve, reject) => {
|
|
682
728
|
try {
|
|
@@ -707,7 +753,7 @@ class MysqlConnection implements Connection {
|
|
|
707
753
|
return [];
|
|
708
754
|
};
|
|
709
755
|
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
710
|
-
logger.trace(
|
|
756
|
+
logger.trace(sql!, params);
|
|
711
757
|
}
|
|
712
758
|
return new Promise<T[]>(async (resolve, reject) => {
|
|
713
759
|
try {
|
|
@@ -738,7 +784,7 @@ class MysqlConnection implements Connection {
|
|
|
738
784
|
return [];
|
|
739
785
|
};
|
|
740
786
|
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
741
|
-
logger.trace(
|
|
787
|
+
logger.trace(sql!, params);
|
|
742
788
|
}
|
|
743
789
|
return new Promise<T[]>(async (resolve, reject) => {
|
|
744
790
|
try {
|
|
@@ -776,6 +822,12 @@ export class Mysql implements Dao {
|
|
|
776
822
|
this[_daoDB] = pool;
|
|
777
823
|
}
|
|
778
824
|
|
|
825
|
+
async keepAlive() {
|
|
826
|
+
const connection = await this[_daoDB].getConnection();
|
|
827
|
+
connection.query('SELECT 1 FROM DUAL');
|
|
828
|
+
setTimeout(async () => await this.keepAlive(), 60000);
|
|
829
|
+
}
|
|
830
|
+
|
|
779
831
|
createConnection(sync: SyncMode.Sync): Connection | null;
|
|
780
832
|
createConnection(sync: SyncMode.Async): Promise<Connection | null>;
|
|
781
833
|
createConnection(sync: SyncMode): Connection | null | Promise<Connection | null> {
|
|
@@ -870,6 +922,307 @@ export class Mysql implements Dao {
|
|
|
870
922
|
restore(sync: SyncMode, name: string): Promise<void> | void {
|
|
871
923
|
}
|
|
872
924
|
}
|
|
925
|
+
|
|
926
|
+
class PostgresqlConnection implements Connection {
|
|
927
|
+
[_daoConnection]: any;
|
|
928
|
+
[_inTransaction] = false;
|
|
929
|
+
constructor(conn: any) {
|
|
930
|
+
this[_daoConnection] = conn;
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
execute(sync: SyncMode.Sync, sql?: string, params?: any): { affectedRows: number; insertId: bigint; };
|
|
934
|
+
execute(sync: SyncMode.Async, sql?: string, params?: any): Promise<{ affectedRows: number; insertId: bigint; }>;
|
|
935
|
+
execute(sync: SyncMode, sql?: string, params?: any): { affectedRows: number; insertId: bigint; } | Promise<{ affectedRows: number; insertId: bigint; }> {
|
|
936
|
+
logger.debug(sql, params ?? '');
|
|
937
|
+
if (!sql) { return { affectedRows: 0, insertId: 0n }; };
|
|
938
|
+
if (sync === SyncMode.Sync) {
|
|
939
|
+
logger.warn('Postgresql not suppouted sync mode');
|
|
940
|
+
return { affectedRows: 0, insertId: 0n };
|
|
941
|
+
};
|
|
942
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
943
|
+
logger.trace(sql!, params);
|
|
944
|
+
}
|
|
945
|
+
return new Promise<{ affectedRows: number; insertId: bigint; }>(async (resolve, reject) => {
|
|
946
|
+
try {
|
|
947
|
+
let index = 1;
|
|
948
|
+
const { rowCount } = await this[_daoConnection].query({
|
|
949
|
+
text: sql.replace(/\?/g, () => `$${index++}`),
|
|
950
|
+
values: params
|
|
951
|
+
});
|
|
952
|
+
const result = rowCount as any;
|
|
953
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
954
|
+
logger.trace(result);
|
|
955
|
+
}
|
|
956
|
+
resolve({ affectedRows: result.affectedRows, insertId: result.insertId });
|
|
957
|
+
} catch (error) {
|
|
958
|
+
logger.error(`
|
|
959
|
+
error: ${error},
|
|
960
|
+
sql: ${sql},
|
|
961
|
+
params: ${params}
|
|
962
|
+
`);
|
|
963
|
+
reject(error);
|
|
964
|
+
}
|
|
965
|
+
});
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
pluck<T = any>(sync: SyncMode.Sync, sql?: string, params?: any): T | null;
|
|
969
|
+
pluck<T = any>(sync: SyncMode.Async, sql?: string, params?: any): Promise<T | null>;
|
|
970
|
+
pluck<T = any>(sync: SyncMode, sql?: string, params?: any): T | null | Promise<T | null> {
|
|
971
|
+
logger.debug(sql, params ?? '');
|
|
972
|
+
if (!sql) { return null };
|
|
973
|
+
if (sync === SyncMode.Sync) {
|
|
974
|
+
logger.warn('Postgresql not suppouted sync mode');
|
|
975
|
+
return null;
|
|
976
|
+
};
|
|
977
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
978
|
+
logger.trace(sql!, params);
|
|
979
|
+
}
|
|
980
|
+
return new Promise<T | null>(async (resolve, reject) => {
|
|
981
|
+
try {
|
|
982
|
+
let index = 1;
|
|
983
|
+
const { rows } = await this[_daoConnection].query({
|
|
984
|
+
text: sql.replace(/\?/g, () => `$${index++}`),
|
|
985
|
+
values: params
|
|
986
|
+
});
|
|
987
|
+
if (rows && rows[0]) {
|
|
988
|
+
const r = Object.values(rows[0])[0];
|
|
989
|
+
if (r === null) resolve(r);
|
|
990
|
+
else resolve(r as T);
|
|
991
|
+
}
|
|
992
|
+
resolve(null);
|
|
993
|
+
} catch (error) {
|
|
994
|
+
logger.error(`
|
|
995
|
+
error: ${error},
|
|
996
|
+
sql: ${sql},
|
|
997
|
+
params: ${params}
|
|
998
|
+
`);
|
|
999
|
+
reject(error);
|
|
1000
|
+
}
|
|
1001
|
+
});
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
get<T = any>(sync: SyncMode.Sync, sql?: string, params?: any): T | null;
|
|
1005
|
+
get<T = any>(sync: SyncMode.Async, sql?: string, params?: any): Promise<T | null>;
|
|
1006
|
+
get<T = any>(sync: SyncMode, sql?: string, params?: any): T | null | Promise<T | null> {
|
|
1007
|
+
logger.debug(sql, params ?? '');
|
|
1008
|
+
if (!sql) { return null };
|
|
1009
|
+
if (sync === SyncMode.Sync) {
|
|
1010
|
+
logger.warn('Postgresql not suppouted sync mode');
|
|
1011
|
+
return null;
|
|
1012
|
+
};
|
|
1013
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
1014
|
+
logger.trace(sql!, params);
|
|
1015
|
+
}
|
|
1016
|
+
return new Promise<T | null>(async (resolve, reject) => {
|
|
1017
|
+
try {
|
|
1018
|
+
let index = 1;
|
|
1019
|
+
const { rows } = await this[_daoConnection].query({
|
|
1020
|
+
text: sql.replace(/\?/g, () => `$${index++}`),
|
|
1021
|
+
values: params
|
|
1022
|
+
});
|
|
1023
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
1024
|
+
logger.trace(rows);
|
|
1025
|
+
}
|
|
1026
|
+
if (rows && rows[0]) resolve(rows[0] as T);
|
|
1027
|
+
resolve(null);
|
|
1028
|
+
} catch (error) {
|
|
1029
|
+
logger.error(`
|
|
1030
|
+
error: ${error},
|
|
1031
|
+
sql: ${sql},
|
|
1032
|
+
params: ${params}
|
|
1033
|
+
`);
|
|
1034
|
+
reject(error);
|
|
1035
|
+
}
|
|
1036
|
+
});
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
raw<T = any>(sync: SyncMode.Sync, sql?: string, params?: any): T[];
|
|
1040
|
+
raw<T = any>(sync: SyncMode.Async, sql?: string, params?: any): Promise<T[]>;
|
|
1041
|
+
raw<T = any>(sync: SyncMode, sql?: string, params?: any): T[] | Promise<T[]> {
|
|
1042
|
+
logger.debug(sql, params ?? '');
|
|
1043
|
+
if (!sql) { return []; };
|
|
1044
|
+
if (sync === SyncMode.Sync) {
|
|
1045
|
+
logger.warn('Postgresql not suppouted sync mode');
|
|
1046
|
+
return [];
|
|
1047
|
+
};
|
|
1048
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
1049
|
+
logger.trace(sql!, params);
|
|
1050
|
+
}
|
|
1051
|
+
return new Promise<T[]>(async (resolve, reject) => {
|
|
1052
|
+
try {
|
|
1053
|
+
let index = 1;
|
|
1054
|
+
const { rows } = await this[_daoConnection].query({
|
|
1055
|
+
text: sql.replace(/\?/g, () => `$${index++}`),
|
|
1056
|
+
values: params
|
|
1057
|
+
});
|
|
1058
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
1059
|
+
logger.trace(rows);
|
|
1060
|
+
}
|
|
1061
|
+
if (rows) resolve(rows.map((i: any) => Object.values(i)[0]));
|
|
1062
|
+
resolve([]);
|
|
1063
|
+
} catch (error) {
|
|
1064
|
+
logger.error(`
|
|
1065
|
+
error: ${error},
|
|
1066
|
+
sql: ${sql},
|
|
1067
|
+
params: ${params}
|
|
1068
|
+
`);
|
|
1069
|
+
reject(error);
|
|
1070
|
+
}
|
|
1071
|
+
});
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
query<T = any>(sync: SyncMode.Sync, sql?: string, params?: any): T[];
|
|
1075
|
+
query<T = any>(sync: SyncMode.Async, sql?: string, params?: any): Promise<T[]>;
|
|
1076
|
+
query<T = any>(sync: SyncMode, sql?: string, params?: any): T[] | Promise<T[]> {
|
|
1077
|
+
logger.debug(sql, params ?? '');
|
|
1078
|
+
if (!sql) { return []; };
|
|
1079
|
+
if (sync === SyncMode.Sync) {
|
|
1080
|
+
logger.warn('Postgresql not suppouted sync mode');
|
|
1081
|
+
return [];
|
|
1082
|
+
};
|
|
1083
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
1084
|
+
logger.trace(sql!, params);
|
|
1085
|
+
}
|
|
1086
|
+
return new Promise<T[]>(async (resolve, reject) => {
|
|
1087
|
+
try {
|
|
1088
|
+
let index = 1;
|
|
1089
|
+
const { rows } = await this[_daoConnection].query({
|
|
1090
|
+
text: sql.replace(/\?/g, () => `$${index++}`),
|
|
1091
|
+
values: params
|
|
1092
|
+
});
|
|
1093
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
1094
|
+
logger.trace(rows);
|
|
1095
|
+
}
|
|
1096
|
+
resolve(rows);
|
|
1097
|
+
} catch (error) {
|
|
1098
|
+
logger.error(`
|
|
1099
|
+
error: ${error},
|
|
1100
|
+
sql: ${sql},
|
|
1101
|
+
params: ${params}
|
|
1102
|
+
`);
|
|
1103
|
+
reject(error);
|
|
1104
|
+
}
|
|
1105
|
+
});
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
realse(sync: SyncMode.Sync): void;
|
|
1109
|
+
realse(sync: SyncMode.Async): Promise<void>;
|
|
1110
|
+
realse(sync: SyncMode): Promise<void> | void {
|
|
1111
|
+
if (sync === SyncMode.Sync) {
|
|
1112
|
+
try {
|
|
1113
|
+
this[_daoConnection]?.release();
|
|
1114
|
+
} catch (error) {
|
|
1115
|
+
|
|
1116
|
+
}
|
|
1117
|
+
};
|
|
1118
|
+
}
|
|
1119
|
+
}
|
|
1120
|
+
export class Postgresql implements Dao {
|
|
1121
|
+
[_daoDB]: any;
|
|
1122
|
+
constructor(pool: any) {
|
|
1123
|
+
this[_daoDB] = pool;
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
async keepAlive() {
|
|
1127
|
+
const connection = await this[_daoDB].connect();
|
|
1128
|
+
connection.query('SELECT 1');
|
|
1129
|
+
setTimeout(async () => await this.keepAlive(), 60000);
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
createConnection(sync: SyncMode.Sync): Connection | null;
|
|
1133
|
+
createConnection(sync: SyncMode.Async): Promise<Connection | null>;
|
|
1134
|
+
createConnection(sync: SyncMode): Connection | null | Promise<Connection | null> {
|
|
1135
|
+
if (sync === SyncMode.Sync) {
|
|
1136
|
+
logger.error('Postgresql not suppouted sync mode');
|
|
1137
|
+
return null;
|
|
1138
|
+
};
|
|
1139
|
+
return new Promise<Connection>(async (resolve, reject) => {
|
|
1140
|
+
try {
|
|
1141
|
+
const connection = await this[_daoDB].connect();
|
|
1142
|
+
logger.debug('create new connection!');
|
|
1143
|
+
resolve(new PostgresqlConnection(connection));
|
|
1144
|
+
} catch (error) {
|
|
1145
|
+
reject(error);
|
|
1146
|
+
}
|
|
1147
|
+
});
|
|
1148
|
+
}
|
|
1149
|
+
|
|
1150
|
+
transaction<T = any>(sync: SyncMode.Sync, fn: (conn: Connection) => T, conn?: Connection | null): T | null;
|
|
1151
|
+
transaction<T = any>(sync: SyncMode.Async, fn: (conn: Connection) => Promise<T>, conn?: Connection | null): Promise<T | null>;
|
|
1152
|
+
transaction<T = any>(sync: SyncMode, fn: (conn: Connection) => T | Promise<T>, conn?: Connection | null): T | null | Promise<T | null> {
|
|
1153
|
+
if (sync === SyncMode.Sync) {
|
|
1154
|
+
logger.warn('Postgresql not suppouted sync mode');
|
|
1155
|
+
return null;
|
|
1156
|
+
};
|
|
1157
|
+
return new Promise<T>(async (resolve, reject) => {
|
|
1158
|
+
let needCommit = false;
|
|
1159
|
+
let newConn = false;
|
|
1160
|
+
if (!conn) {
|
|
1161
|
+
conn = await this.createConnection(SyncMode.Async) ?? undefined;
|
|
1162
|
+
newConn = true;
|
|
1163
|
+
}
|
|
1164
|
+
if (conn?.[_inTransaction] !== true) {
|
|
1165
|
+
needCommit = true;
|
|
1166
|
+
logger.debug('beginTransaction begin!');
|
|
1167
|
+
await conn![_daoConnection].query('BEGIN');
|
|
1168
|
+
logger.debug('beginTransaction end!');
|
|
1169
|
+
}
|
|
1170
|
+
conn![_inTransaction] = true;
|
|
1171
|
+
try {
|
|
1172
|
+
const result = await fn(conn!);
|
|
1173
|
+
if (needCommit === true) {
|
|
1174
|
+
logger.debug('commit begin!');
|
|
1175
|
+
await conn![_daoConnection].query('COMMIT');
|
|
1176
|
+
conn![_inTransaction] = false;
|
|
1177
|
+
logger.debug('commit end!');
|
|
1178
|
+
}
|
|
1179
|
+
resolve(result);
|
|
1180
|
+
} catch (error) {
|
|
1181
|
+
logger.debug('rollback begin!');
|
|
1182
|
+
await conn![_daoConnection].query('ROLLBACK');
|
|
1183
|
+
logger.debug('rollback end!');
|
|
1184
|
+
conn![_inTransaction] = false;
|
|
1185
|
+
logger.error(error);
|
|
1186
|
+
reject(error);
|
|
1187
|
+
} finally {
|
|
1188
|
+
try {
|
|
1189
|
+
if (needCommit === true) {
|
|
1190
|
+
conn![_inTransaction] = false;
|
|
1191
|
+
}
|
|
1192
|
+
if (newConn === true) {
|
|
1193
|
+
logger.debug('release begin!');
|
|
1194
|
+
conn![_daoConnection].release();
|
|
1195
|
+
logger.debug('release end!');
|
|
1196
|
+
}
|
|
1197
|
+
} catch (error) {
|
|
1198
|
+
}
|
|
1199
|
+
}
|
|
1200
|
+
});
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1203
|
+
close(sync: SyncMode.Sync): void;
|
|
1204
|
+
close(sync: SyncMode.Async): Promise<void>;
|
|
1205
|
+
close(sync: SyncMode): Promise<void> | void {
|
|
1206
|
+
if (sync === SyncMode.Sync) {
|
|
1207
|
+
this[_daoDB]?.end();
|
|
1208
|
+
};
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
backup(sync: SyncMode.Sync, name: string): void;
|
|
1212
|
+
backup(sync: SyncMode.Async, name: string): Promise<void>;
|
|
1213
|
+
backup(sync: SyncMode, name: string): Promise<void> | void {
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1216
|
+
remove(sync: SyncMode.Sync): void;
|
|
1217
|
+
remove(sync: SyncMode.Async): Promise<void>;
|
|
1218
|
+
remove(sync: SyncMode): Promise<void> | void {
|
|
1219
|
+
}
|
|
1220
|
+
|
|
1221
|
+
restore(sync: SyncMode.Sync, name: string): void;
|
|
1222
|
+
restore(sync: SyncMode.Async, name: string): Promise<void>;
|
|
1223
|
+
restore(sync: SyncMode, name: string): Promise<void> | void {
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
873
1226
|
class SqliteConnection implements Connection {
|
|
874
1227
|
[_daoConnection]: any;
|
|
875
1228
|
[_inTransaction] = false;
|
|
@@ -888,7 +1241,7 @@ class SqliteConnection implements Connection {
|
|
|
888
1241
|
return { affectedRows: 0, insertId: 0n };
|
|
889
1242
|
};
|
|
890
1243
|
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
891
|
-
logger.trace(
|
|
1244
|
+
logger.trace(sql!, params);
|
|
892
1245
|
}
|
|
893
1246
|
const result = this[_daoConnection].prepare(sql).run(params ?? {});
|
|
894
1247
|
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
@@ -917,7 +1270,7 @@ class SqliteConnection implements Connection {
|
|
|
917
1270
|
return null;
|
|
918
1271
|
};
|
|
919
1272
|
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
920
|
-
logger.trace(
|
|
1273
|
+
logger.trace(sql!, params);
|
|
921
1274
|
}
|
|
922
1275
|
return this[_daoConnection].prepare(sql).pluck().get(params ?? {});
|
|
923
1276
|
} catch (error) {
|
|
@@ -938,7 +1291,7 @@ class SqliteConnection implements Connection {
|
|
|
938
1291
|
if (!sql) { return null };
|
|
939
1292
|
if (sync === SyncMode.Async) { return null };
|
|
940
1293
|
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
941
|
-
logger.trace(
|
|
1294
|
+
logger.trace(sql!, params);
|
|
942
1295
|
}
|
|
943
1296
|
return this[_daoConnection].prepare(sql).get(params ?? {});
|
|
944
1297
|
} catch (error) {
|
|
@@ -962,7 +1315,7 @@ class SqliteConnection implements Connection {
|
|
|
962
1315
|
return [];
|
|
963
1316
|
};
|
|
964
1317
|
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
965
|
-
logger.trace(
|
|
1318
|
+
logger.trace(sql!, params);
|
|
966
1319
|
}
|
|
967
1320
|
return this[_daoConnection].prepare(sql).raw().all(params ?? {});
|
|
968
1321
|
} catch (error) {
|
|
@@ -986,7 +1339,7 @@ class SqliteConnection implements Connection {
|
|
|
986
1339
|
return [];
|
|
987
1340
|
};
|
|
988
1341
|
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
989
|
-
logger.trace(
|
|
1342
|
+
logger.trace(sql!, params);
|
|
990
1343
|
}
|
|
991
1344
|
return this[_daoConnection].prepare(sql).all(params ?? {});
|
|
992
1345
|
} catch (error) {
|
|
@@ -1101,7 +1454,7 @@ export class SqliteRemoteConnection implements Connection {
|
|
|
1101
1454
|
return { affectedRows: 0, insertId: 0n };
|
|
1102
1455
|
};
|
|
1103
1456
|
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
1104
|
-
logger.trace(
|
|
1457
|
+
logger.trace(sql!, params);
|
|
1105
1458
|
}
|
|
1106
1459
|
return new Promise<{ affectedRows: number; insertId: bigint; }>(async (resolve, reject) => {
|
|
1107
1460
|
try {
|
|
@@ -1129,7 +1482,7 @@ export class SqliteRemoteConnection implements Connection {
|
|
|
1129
1482
|
return null;
|
|
1130
1483
|
};
|
|
1131
1484
|
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
1132
|
-
logger.trace(
|
|
1485
|
+
logger.trace(sql!, params);
|
|
1133
1486
|
}
|
|
1134
1487
|
return new Promise<T | null>(async (resolve, reject) => {
|
|
1135
1488
|
try {
|
|
@@ -1157,7 +1510,7 @@ export class SqliteRemoteConnection implements Connection {
|
|
|
1157
1510
|
return null;
|
|
1158
1511
|
};
|
|
1159
1512
|
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
1160
|
-
logger.trace(
|
|
1513
|
+
logger.trace(sql!, params);
|
|
1161
1514
|
}
|
|
1162
1515
|
return new Promise<T | null>(async (resolve, reject) => {
|
|
1163
1516
|
try {
|
|
@@ -1185,7 +1538,7 @@ export class SqliteRemoteConnection implements Connection {
|
|
|
1185
1538
|
return [];
|
|
1186
1539
|
};
|
|
1187
1540
|
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
1188
|
-
logger.trace(
|
|
1541
|
+
logger.trace(sql!, params);
|
|
1189
1542
|
}
|
|
1190
1543
|
return new Promise<T[]>(async (resolve, reject) => {
|
|
1191
1544
|
try {
|
|
@@ -1213,7 +1566,7 @@ export class SqliteRemoteConnection implements Connection {
|
|
|
1213
1566
|
return [];
|
|
1214
1567
|
};
|
|
1215
1568
|
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
1216
|
-
logger.trace(
|
|
1569
|
+
logger.trace(sql!, params);
|
|
1217
1570
|
}
|
|
1218
1571
|
return new Promise<T[]>(async (resolve, reject) => {
|
|
1219
1572
|
try {
|
|
@@ -1878,17 +2231,17 @@ function P<T extends object>(skipConn = false) {
|
|
|
1878
2231
|
const option = args[0] = Object.assign({}, globalThis[_GlobalSqlOption], this[_SqlOption], args[0]) as (MethodOption & { sync?: SyncMode; });
|
|
1879
2232
|
option.sync ??= SyncMode.Async;
|
|
1880
2233
|
option!.tableName = option?.tableName ?? this[_tableName];
|
|
2234
|
+
option!.dbName = option?.dbName ?? this[_daoDBName] ?? _primaryDB;
|
|
2235
|
+
option!.dbType = this[_dbType] ?? globalThis[_GlobalSqlOption].dbType ?? DBType.Mysql;
|
|
2236
|
+
option!.dao = globalThis[_dao][option!.dbType!][option!.dbName] as Dao;
|
|
1881
2237
|
|
|
1882
|
-
|
|
1883
|
-
option!.dao = globalThis[_dao][this[_dbType]!][dbName] as Dao;
|
|
1884
|
-
|
|
1885
|
-
if (this[_dbType] === DBType.Sqlite) {
|
|
2238
|
+
if (option!.dbType === DBType.Sqlite) {
|
|
1886
2239
|
if (!option!.dao) {
|
|
1887
|
-
const db = new Sqlite(new globalThis[_GlobalSqlOption].BetterSqlite3(dbName as any, { fileMustExist: false }));
|
|
1888
|
-
if (globalThis[_dao][
|
|
1889
|
-
globalThis[_dao][
|
|
2240
|
+
const db = new Sqlite(new globalThis[_GlobalSqlOption].BetterSqlite3(option!.dbName as any, { fileMustExist: false }));
|
|
2241
|
+
if (globalThis[_dao][option!.dbType!][_primaryDB] === undefined) {
|
|
2242
|
+
globalThis[_dao][option!.dbType!][_primaryDB] = db;
|
|
1890
2243
|
}
|
|
1891
|
-
globalThis[_dao][
|
|
2244
|
+
globalThis[_dao][option!.dbType!][option!.dbName] = db;
|
|
1892
2245
|
option!.dao = db;
|
|
1893
2246
|
}
|
|
1894
2247
|
|
|
@@ -1918,14 +2271,14 @@ function P<T extends object>(skipConn = false) {
|
|
|
1918
2271
|
}
|
|
1919
2272
|
}
|
|
1920
2273
|
}
|
|
1921
|
-
} else if (
|
|
2274
|
+
} else if (option!.dbType === DBType.SqliteRemote) {
|
|
1922
2275
|
if (!option!.dao) {
|
|
1923
|
-
globalThis[_GlobalSqlOption].SqliteRemote.service.initDB(dbName);
|
|
1924
|
-
const db = new SqliteRemote(globalThis[_GlobalSqlOption].SqliteRemote.service, dbName as any);
|
|
1925
|
-
if (globalThis[_dao][
|
|
1926
|
-
globalThis[_dao][
|
|
2276
|
+
globalThis[_GlobalSqlOption].SqliteRemote.service.initDB(option!.dbName);
|
|
2277
|
+
const db = new SqliteRemote(globalThis[_GlobalSqlOption].SqliteRemote.service, option!.dbName as any);
|
|
2278
|
+
if (globalThis[_dao][option!.dbType!][_primaryDB] === undefined) {
|
|
2279
|
+
globalThis[_dao][option!.dbType!][_primaryDB] = db;
|
|
1927
2280
|
}
|
|
1928
|
-
globalThis[_dao][
|
|
2281
|
+
globalThis[_dao][option!.dbType!][option!.dbName] = db;
|
|
1929
2282
|
option!.dao = db;
|
|
1930
2283
|
}
|
|
1931
2284
|
|
|
@@ -1955,8 +2308,34 @@ function P<T extends object>(skipConn = false) {
|
|
|
1955
2308
|
}
|
|
1956
2309
|
});
|
|
1957
2310
|
|
|
1958
|
-
} else if (
|
|
1959
|
-
Throw.if(!option!.dao, `not found db:${String(dbName)}(${
|
|
2311
|
+
} else if (option!.dbType === DBType.Mysql) {
|
|
2312
|
+
Throw.if(!option!.dao, `not found db:${String(option!.dbName)}(${option!.dbType})`);
|
|
2313
|
+
return new Promise(async (resolve, reject) => {
|
|
2314
|
+
try {
|
|
2315
|
+
// 连接共享
|
|
2316
|
+
if (skipConn === false && !option!.conn) {
|
|
2317
|
+
(option!).conn = await option!.dao!.createConnection(SyncMode.Async);
|
|
2318
|
+
} else {
|
|
2319
|
+
needRealseConn = false;
|
|
2320
|
+
}
|
|
2321
|
+
const result = await fn.call(this, ...args);
|
|
2322
|
+
logger.info(`${propertyKey}:${option!.tableName}:use ${+new Date() - startTime}ms`);
|
|
2323
|
+
resolve(result);
|
|
2324
|
+
} catch (error) {
|
|
2325
|
+
console.error(`service ${propertyKey} have an error:${error}, it's argumens: ${JSON.stringify(args.filter(i => typeof i !== 'object' || (typeof i === 'object' && !i.insert)))}`)
|
|
2326
|
+
reject(error);
|
|
2327
|
+
} finally {
|
|
2328
|
+
if (needRealseConn && option && option!.conn) {
|
|
2329
|
+
try {
|
|
2330
|
+
option!.conn!.realse(SyncMode.Sync);
|
|
2331
|
+
} catch (error) {
|
|
2332
|
+
|
|
2333
|
+
}
|
|
2334
|
+
}
|
|
2335
|
+
}
|
|
2336
|
+
});
|
|
2337
|
+
} else if (option!.dbType === DBType.Postgresql) {
|
|
2338
|
+
Throw.if(!option!.dao, `not found db:${String(option!.dbName)}(${option!.dbType})`);
|
|
1960
2339
|
return new Promise(async (resolve, reject) => {
|
|
1961
2340
|
try {
|
|
1962
2341
|
// 连接共享
|
|
@@ -2024,207 +2403,183 @@ const FieldFilter = (
|
|
|
2024
2403
|
return [ret, V];
|
|
2025
2404
|
}
|
|
2026
2405
|
const MYSQLCHARSET = `CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci`;
|
|
2406
|
+
const POSTGRESCHARSET = `COLLATE "pg_catalog"."default"`;
|
|
2027
2407
|
export const Field = (config: FieldOption) => {
|
|
2028
2408
|
config.type ??= SqlType.varchar;
|
|
2029
2409
|
return (object: object, propertyName: string) => {
|
|
2030
2410
|
const field = config as AField;
|
|
2031
2411
|
field.P = propertyName;
|
|
2032
2412
|
field.C = () => P2C(propertyName, globalThis[_Hump]);
|
|
2033
|
-
field.C2 = () =>
|
|
2034
|
-
field.C3 = () => `${
|
|
2413
|
+
field.C2 = () => P2C(propertyName, globalThis[_Hump]);
|
|
2414
|
+
field.C3 = () => `${P2C(propertyName, globalThis[_Hump])} ${propertyName}`;
|
|
2035
2415
|
const hasDef = field.hasOwnProperty('def') === true;
|
|
2036
2416
|
switch (field.type) {
|
|
2037
2417
|
case SqlType.tinyint: {
|
|
2038
|
-
field[DBType.Mysql] = () => `${field.C2()} tinyint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT
|
|
2418
|
+
field[DBType.Mysql] = () => `${field.C2()} tinyint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT ${field.def}` : ''}`;
|
|
2419
|
+
field[DBType.Postgresql] = () => `${field.C2()} int2 ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT ${field.def}` : ''}`;
|
|
2039
2420
|
field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} integer`;
|
|
2040
2421
|
break;
|
|
2041
2422
|
}
|
|
2042
2423
|
case SqlType.smallint: {
|
|
2043
|
-
field[DBType.Mysql] = () => `${field.C2()} smallint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT
|
|
2424
|
+
field[DBType.Mysql] = () => `${field.C2()} smallint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT ${field.def}` : ''}`;
|
|
2425
|
+
field[DBType.Postgresql] = () => `${field.C2()} int2 ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT ${field.def}` : ''}`;
|
|
2044
2426
|
field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} integer`;
|
|
2045
2427
|
break;
|
|
2046
2428
|
}
|
|
2047
2429
|
case SqlType.mediumint: {
|
|
2048
|
-
field[DBType.Mysql] = () => `${field.C2()} smallint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT
|
|
2430
|
+
field[DBType.Mysql] = () => `${field.C2()} smallint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT ${field.def}` : ''}`;
|
|
2431
|
+
field[DBType.Postgresql] = () => `${field.C2()} int4 ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT ${field.def}` : ''}`;
|
|
2049
2432
|
field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} integer`;
|
|
2050
2433
|
break;
|
|
2051
2434
|
}
|
|
2052
2435
|
case SqlType.int: {
|
|
2053
|
-
field[DBType.Mysql] = () => `${field.C2()} int ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT
|
|
2436
|
+
field[DBType.Mysql] = () => `${field.C2()} int ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT ${field.def}` : ''}`;
|
|
2437
|
+
field[DBType.Postgresql] = () => `${field.C2()} int4 ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT ${field.def}` : ''}`;
|
|
2054
2438
|
field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} integer`;
|
|
2055
2439
|
break;
|
|
2056
2440
|
}
|
|
2057
2441
|
case SqlType.bigint: {
|
|
2058
2442
|
field[DBType.Mysql] = () => `${field.C2()} bigint ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2443
|
+
field[DBType.Postgresql] = () => `${field.C2()} int8 ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2059
2444
|
field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} integer`;
|
|
2060
2445
|
field.Data2SQL = (data: any) => BigInt(data ?? 0);
|
|
2061
2446
|
break;
|
|
2062
2447
|
}
|
|
2063
2448
|
case SqlType.float: {
|
|
2064
|
-
field[DBType.Mysql] = () => `${field.C2()}
|
|
2449
|
+
field[DBType.Mysql] = () => `${field.C2()} float4(${config.length ?? 1}, ${config.scale ?? 2}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT '${field.def}'` : ''} `;
|
|
2450
|
+
field[DBType.Postgresql] = () => `${field.C2()} float4(${config.length ?? 1}, ${config.scale ?? 2}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT '${field.def}'` : ''} `;
|
|
2065
2451
|
field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} real`;
|
|
2066
2452
|
break;
|
|
2067
2453
|
}
|
|
2068
2454
|
case SqlType.double: {
|
|
2069
2455
|
field[DBType.Mysql] = () => `${field.C2()} double(${config.length ?? 1}, ${config.scale ?? 2}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT '${field.def}'` : ''} `;
|
|
2456
|
+
field[DBType.Postgresql] = () => `${field.C2()} float8(${config.length ?? 1}, ${config.scale ?? 2}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT '${field.def}'` : ''} `;
|
|
2070
2457
|
field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} real`;
|
|
2071
2458
|
break;
|
|
2072
2459
|
}
|
|
2073
2460
|
case SqlType.decimal: {
|
|
2074
2461
|
field[DBType.Mysql] = () => `${field.C2()} decimal(${config.length ?? 1}, ${config.scale ?? 2}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT '${field.def}'` : ''} `;
|
|
2462
|
+
field[DBType.Postgresql] = () => `${field.C2()} numeric(${config.length ?? 1}, ${config.scale ?? 2}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT '${field.def}'` : ''} `;
|
|
2075
2463
|
field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} real`;
|
|
2076
2464
|
break;
|
|
2077
2465
|
}
|
|
2078
2466
|
|
|
2079
2467
|
case SqlType.longtext: {
|
|
2080
2468
|
field[DBType.Mysql] = () => `${field.C2()} longtext ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2469
|
+
field[DBType.Postgresql] = () => `${field.C2()} text ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2081
2470
|
field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
|
|
2082
2471
|
break;
|
|
2083
2472
|
}
|
|
2084
2473
|
case SqlType.mediumtext: {
|
|
2085
2474
|
field[DBType.Mysql] = () => `${field.C2()} mediumtext ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2475
|
+
field[DBType.Postgresql] = () => `${field.C2()} text ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2086
2476
|
field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
|
|
2087
2477
|
break;
|
|
2088
2478
|
}
|
|
2089
2479
|
case SqlType.text: {
|
|
2090
2480
|
field[DBType.Mysql] = () => `${field.C2()} text ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2481
|
+
field[DBType.Postgresql] = () => `${field.C2()} text ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2091
2482
|
field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
|
|
2092
2483
|
break;
|
|
2093
2484
|
}
|
|
2094
2485
|
case SqlType.date: {
|
|
2095
2486
|
field[DBType.Mysql] = () => `${field.C2()} date ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2487
|
+
field[DBType.Postgresql] = () => `${field.C2()} date ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2096
2488
|
field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
|
|
2097
2489
|
field.Data2SQL = (data: any) => typeof data === 'string' ? new Date(data) : data;
|
|
2098
2490
|
break;
|
|
2099
2491
|
}
|
|
2100
2492
|
case SqlType.time: {
|
|
2101
2493
|
field[DBType.Mysql] = () => `${field.C2()} time ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2494
|
+
field[DBType.Postgresql] = () => `${field.C2()} time ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2102
2495
|
field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
|
|
2103
2496
|
field.Data2SQL = (data: any) => typeof data === 'string' ? new Date(data) : data;
|
|
2104
2497
|
break;
|
|
2105
2498
|
}
|
|
2106
2499
|
case SqlType.year: {
|
|
2107
2500
|
field[DBType.Mysql] = () => `${field.C2()} year ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2501
|
+
field[DBType.Postgresql] = () => `${field.C2()} int4 ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2108
2502
|
field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
|
|
2109
2503
|
field.Data2SQL = (data: any) => typeof data === 'string' ? new Date(data) : data;
|
|
2110
2504
|
break;
|
|
2111
2505
|
}
|
|
2112
2506
|
case SqlType.datetime: {
|
|
2113
2507
|
field[DBType.Mysql] = () => `${field.C2()} datetime ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2508
|
+
field[DBType.Postgresql] = () => `${field.C2()} timestamp ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2114
2509
|
field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
|
|
2115
2510
|
field.Data2SQL = (data: any) => typeof data === 'string' ? new Date(data) : data;
|
|
2116
2511
|
break;
|
|
2117
2512
|
}
|
|
2118
2513
|
case SqlType.timestamp: {
|
|
2119
2514
|
field[DBType.Mysql] = () => `${field.C2()} timestamp ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2515
|
+
field[DBType.Postgresql] = () => `${field.C2()} timestamp ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2120
2516
|
field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} integer`;
|
|
2121
2517
|
field.Data2SQL = (data: any) => typeof data === 'string' ? +new Date(data) : data;
|
|
2122
2518
|
break;
|
|
2123
2519
|
}
|
|
2124
2520
|
case SqlType.char: {
|
|
2125
2521
|
field[DBType.Mysql] = () => `${field.C2()} char(${config.length ?? 1}) ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2522
|
+
field[DBType.Postgresql] = () => `${field.C2()} char(${config.length ?? 1}) ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2126
2523
|
field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
|
|
2127
2524
|
break;
|
|
2128
2525
|
}
|
|
2129
2526
|
case SqlType.varchar: {
|
|
2130
2527
|
field[DBType.Mysql] = () => `${field.C2()} varchar(${config.length ?? 1}) ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2528
|
+
field[DBType.Postgresql] = () => `${field.C2()} varchar(${config.length ?? 1}) ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2131
2529
|
field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
|
|
2132
2530
|
break;
|
|
2133
2531
|
}
|
|
2134
2532
|
case SqlType.tinyblob: {
|
|
2135
2533
|
field[DBType.Mysql] = () => `${field.C2()} tinyblob ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2534
|
+
field[DBType.Postgresql] = () => `${field.C2()} bytea ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2136
2535
|
field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
|
|
2137
2536
|
break;
|
|
2138
2537
|
}
|
|
2139
2538
|
case SqlType.tinytext: {
|
|
2140
2539
|
field[DBType.Mysql] = () => `${field.C2()} tinytext ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2540
|
+
field[DBType.Postgresql] = () => `${field.C2()} text ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2141
2541
|
field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
|
|
2142
2542
|
break;
|
|
2143
2543
|
}
|
|
2144
2544
|
case SqlType.blob: {
|
|
2145
2545
|
field[DBType.Mysql] = () => `${field.C2()} binary ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2546
|
+
field[DBType.Postgresql] = () => `${field.C2()} bytea ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2146
2547
|
field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
|
|
2147
2548
|
break;
|
|
2148
2549
|
}
|
|
2149
2550
|
case SqlType.text: {
|
|
2150
2551
|
field[DBType.Mysql] = () => `${field.C2()} text ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2552
|
+
field[DBType.Postgresql] = () => `${field.C2()} text ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2151
2553
|
field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
|
|
2152
2554
|
break;
|
|
2153
2555
|
}
|
|
2154
2556
|
case SqlType.mediumblob: {
|
|
2155
2557
|
field[DBType.Mysql] = () => `${field.C2()} mediumblob ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2558
|
+
field[DBType.Postgresql] = () => `${field.C2()} bytea ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2156
2559
|
field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
|
|
2157
2560
|
break;
|
|
2158
2561
|
}
|
|
2159
2562
|
case SqlType.mediumtext: {
|
|
2160
2563
|
field[DBType.Mysql] = () => `${field.C2()} mediumtext ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2564
|
+
field[DBType.Postgresql] = () => `${field.C2()} text ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2161
2565
|
field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
|
|
2162
2566
|
break;
|
|
2163
2567
|
}
|
|
2164
2568
|
case SqlType.longblob: {
|
|
2165
2569
|
field[DBType.Mysql] = () => `${field.C2()} longblob ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2570
|
+
field[DBType.Postgresql] = () => `${field.C2()} bytea ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2166
2571
|
field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
|
|
2167
2572
|
break;
|
|
2168
2573
|
}
|
|
2169
2574
|
case SqlType.longtext: {
|
|
2170
2575
|
field[DBType.Mysql] = () => `${field.C2()} longtext ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2171
|
-
field[DBType.
|
|
2172
|
-
break;
|
|
2173
|
-
}
|
|
2174
|
-
|
|
2175
|
-
case SqlType.set: {
|
|
2176
|
-
field[DBType.Mysql] = () => `${field.C2()} set ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2177
|
-
field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
|
|
2178
|
-
break;
|
|
2179
|
-
}
|
|
2180
|
-
case SqlType.enum: {
|
|
2181
|
-
field[DBType.Mysql] = () => `${field.C2()} enum ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2576
|
+
field[DBType.Postgresql] = () => `${field.C2()} text ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2182
2577
|
field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
|
|
2183
2578
|
break;
|
|
2184
2579
|
}
|
|
2185
2580
|
case SqlType.json: {
|
|
2186
2581
|
field[DBType.Mysql] = () => `${field.C2()} json ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2187
|
-
field[DBType.
|
|
2188
|
-
break;
|
|
2189
|
-
}
|
|
2190
|
-
|
|
2191
|
-
case SqlType.geometry: {
|
|
2192
|
-
field[DBType.Mysql] = () => `${field.C2()} geometry ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2193
|
-
field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
|
|
2194
|
-
break;
|
|
2195
|
-
}
|
|
2196
|
-
case SqlType.point: {
|
|
2197
|
-
field[DBType.Mysql] = () => `${field.C2()} point ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2198
|
-
field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
|
|
2199
|
-
break;
|
|
2200
|
-
}
|
|
2201
|
-
case SqlType.linestring: {
|
|
2202
|
-
field[DBType.Mysql] = () => `${field.C2()} linestring ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2203
|
-
field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
|
|
2204
|
-
break;
|
|
2205
|
-
}
|
|
2206
|
-
case SqlType.polygon: {
|
|
2207
|
-
field[DBType.Mysql] = () => `${field.C2()} polygon ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2208
|
-
field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
|
|
2209
|
-
break;
|
|
2210
|
-
}
|
|
2211
|
-
case SqlType.multipoint: {
|
|
2212
|
-
field[DBType.Mysql] = () => `${field.C2()} multipoint ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2213
|
-
field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
|
|
2214
|
-
break;
|
|
2215
|
-
}
|
|
2216
|
-
case SqlType.multilinestring: {
|
|
2217
|
-
field[DBType.Mysql] = () => `${field.C2()} multilinestring ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2218
|
-
field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
|
|
2219
|
-
break;
|
|
2220
|
-
}
|
|
2221
|
-
case SqlType.multipolygon: {
|
|
2222
|
-
field[DBType.Mysql] = () => `${field.C2()} multipolygon ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2223
|
-
field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
|
|
2224
|
-
break;
|
|
2225
|
-
}
|
|
2226
|
-
case SqlType.geometrycollection: {
|
|
2227
|
-
field[DBType.Mysql] = () => `${field.C2()} geometrycollection ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2582
|
+
field[DBType.Postgresql] = () => `${field.C2()} jsonb ${config.notNull === true ? 'NOT NULL' : ''} ${POSTGRESCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
|
|
2228
2583
|
field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
|
|
2229
2584
|
break;
|
|
2230
2585
|
}
|
|
@@ -2277,7 +2632,8 @@ export const Field = (config: FieldOption) => {
|
|
|
2277
2632
|
const formatDialects = {
|
|
2278
2633
|
[DBType.Mysql]: mysql,
|
|
2279
2634
|
[DBType.Sqlite]: sqlite,
|
|
2280
|
-
[DBType.SqliteRemote]: sqlite
|
|
2635
|
+
[DBType.SqliteRemote]: sqlite,
|
|
2636
|
+
[DBType.Postgresql]: postgresql,
|
|
2281
2637
|
};
|
|
2282
2638
|
export const DB = (config: ServiceOption) => {
|
|
2283
2639
|
return function <C extends { new(...args: any[]): {} }>(constructor: C) {
|
|
@@ -2290,8 +2646,7 @@ export const DB = (config: ServiceOption) => {
|
|
|
2290
2646
|
const __deleteState = Reflect.getMetadata(_deleteState, config.clz.prototype);
|
|
2291
2647
|
const __index = Reflect.getMetadata(_index, config.clz.prototype);
|
|
2292
2648
|
const __def = Reflect.getMetadata(_def, config.clz.prototype);
|
|
2293
|
-
const __dbType = config.dbType
|
|
2294
|
-
const __formatDialect = formatDialects[__dbType];
|
|
2649
|
+
const __dbType = config.dbType;
|
|
2295
2650
|
const className = config.tableName?.replace(/_(\w)/g, (a: string, b: string) => b.toUpperCase());
|
|
2296
2651
|
const ClassName = className?.replace(/\w/, (v: string) => v.toUpperCase());
|
|
2297
2652
|
const vueName = config.tableName?.replace(/_/g, '-');
|
|
@@ -2303,7 +2658,6 @@ export const DB = (config: ServiceOption) => {
|
|
|
2303
2658
|
|
|
2304
2659
|
[_daoDBName] = config.dbName;
|
|
2305
2660
|
[_dbType] = __dbType;
|
|
2306
|
-
[_formatDialect] = __formatDialect;
|
|
2307
2661
|
[_sqlite_version] = config.sqliteVersion;
|
|
2308
2662
|
[_SqlOption] = Object.assign({}, _defOption, config);
|
|
2309
2663
|
|
|
@@ -2412,7 +2766,6 @@ export class SqlService<T extends object> {
|
|
|
2412
2766
|
private [_deleteState]?: string;
|
|
2413
2767
|
private [_SqlOption]?: ServiceOption;
|
|
2414
2768
|
private [_dbType]?: DBType;
|
|
2415
|
-
private [_formatDialect]?: DialectOptions;
|
|
2416
2769
|
private [_sqlite_version]?: string;
|
|
2417
2770
|
private [_index]?: string[];
|
|
2418
2771
|
private [_def]?: Partial<T>;
|
|
@@ -2434,7 +2787,7 @@ export class SqlService<T extends object> {
|
|
|
2434
2787
|
}): { sql: string; params?: any[] }[] {
|
|
2435
2788
|
|
|
2436
2789
|
const sqls: { sql: string; params?: any[] }[] = [];
|
|
2437
|
-
const tableName =
|
|
2790
|
+
const tableName = option!.tableName;
|
|
2438
2791
|
switch (option?.mode) {
|
|
2439
2792
|
case InsertMode.InsertIfNotExists: {
|
|
2440
2793
|
const conditions = option!.existConditionOtherThanIds || this[_ids];
|
|
@@ -2457,9 +2810,28 @@ export class SqlService<T extends object> {
|
|
|
2457
2810
|
if (V === null) {
|
|
2458
2811
|
const field = this[_fields]![column];
|
|
2459
2812
|
if (field?.uuid) {
|
|
2460
|
-
|
|
2461
|
-
|
|
2462
|
-
|
|
2813
|
+
switch (option.dbType) {
|
|
2814
|
+
case DBType.Postgresql:
|
|
2815
|
+
questMark.push('gen_random_uuid()');
|
|
2816
|
+
break;
|
|
2817
|
+
default:
|
|
2818
|
+
questMark.push('UUID()');
|
|
2819
|
+
break;
|
|
2820
|
+
}
|
|
2821
|
+
} else if (field?.uuidShort) {
|
|
2822
|
+
switch (option.dbType) {
|
|
2823
|
+
case DBType.Postgresql:
|
|
2824
|
+
questMark.push(`encode(uuid_send(gen_random_uuid()::uuid),'base64')`);
|
|
2825
|
+
break;
|
|
2826
|
+
case DBType.Mysql:
|
|
2827
|
+
questMark.push('UUID_SHORT()');
|
|
2828
|
+
break;
|
|
2829
|
+
default:
|
|
2830
|
+
questMark.push('?');
|
|
2831
|
+
params.push(V);
|
|
2832
|
+
break;
|
|
2833
|
+
|
|
2834
|
+
}
|
|
2463
2835
|
} else {
|
|
2464
2836
|
questMark.push('?');
|
|
2465
2837
|
params.push(V);
|
|
@@ -2484,7 +2856,7 @@ export class SqlService<T extends object> {
|
|
|
2484
2856
|
const sql = formatDialect(`INSERT INTO
|
|
2485
2857
|
${tableName}
|
|
2486
2858
|
(${columnNames})
|
|
2487
|
-
${questMarks.join(' UNION ALL ')};`, { dialect:
|
|
2859
|
+
${questMarks.join(' UNION ALL ')};`, { dialect: formatDialects[option!.dbType!] });
|
|
2488
2860
|
sqls.push({ sql, params });
|
|
2489
2861
|
break;
|
|
2490
2862
|
}
|
|
@@ -2504,9 +2876,28 @@ export class SqlService<T extends object> {
|
|
|
2504
2876
|
if (V === null) {
|
|
2505
2877
|
const field = this[_fields]![column];
|
|
2506
2878
|
if (field?.uuid) {
|
|
2507
|
-
|
|
2508
|
-
|
|
2509
|
-
|
|
2879
|
+
switch (option.dbType) {
|
|
2880
|
+
case DBType.Postgresql:
|
|
2881
|
+
questMark.push('gen_random_uuid()');
|
|
2882
|
+
break;
|
|
2883
|
+
default:
|
|
2884
|
+
questMark.push('UUID()');
|
|
2885
|
+
break;
|
|
2886
|
+
}
|
|
2887
|
+
} else if (field?.uuidShort) {
|
|
2888
|
+
switch (option.dbType) {
|
|
2889
|
+
case DBType.Postgresql:
|
|
2890
|
+
questMark.push(`encode(uuid_send(gen_random_uuid()::uuid),'base64')`);
|
|
2891
|
+
break;
|
|
2892
|
+
case DBType.Mysql:
|
|
2893
|
+
questMark.push('UUID_SHORT()');
|
|
2894
|
+
break;
|
|
2895
|
+
default:
|
|
2896
|
+
questMark.push('?');
|
|
2897
|
+
params.push(V);
|
|
2898
|
+
break;
|
|
2899
|
+
|
|
2900
|
+
}
|
|
2510
2901
|
} else {
|
|
2511
2902
|
questMark.push('?');
|
|
2512
2903
|
params.push(V);
|
|
@@ -2520,11 +2911,11 @@ export class SqlService<T extends object> {
|
|
|
2520
2911
|
});
|
|
2521
2912
|
const columnNames = iterare(finalColumns).map(i => this[_fields]![i]?.C2()).join(',');
|
|
2522
2913
|
const sql = formatDialect(`
|
|
2523
|
-
${
|
|
2914
|
+
${option!.dbType === DBType.Mysql ? '' : 'INSERT OR'} REPLACE INTO
|
|
2524
2915
|
${tableName}
|
|
2525
2916
|
(${columnNames})
|
|
2526
2917
|
VALUES ${questMarks};
|
|
2527
|
-
`, { dialect:
|
|
2918
|
+
`, { dialect: formatDialects[option!.dbType!] });
|
|
2528
2919
|
sqls.push({ sql, params });
|
|
2529
2920
|
break;
|
|
2530
2921
|
}
|
|
@@ -2544,9 +2935,28 @@ export class SqlService<T extends object> {
|
|
|
2544
2935
|
if (V === null) {
|
|
2545
2936
|
const field = this[_fields]![column];
|
|
2546
2937
|
if (field?.uuid) {
|
|
2547
|
-
|
|
2548
|
-
|
|
2549
|
-
|
|
2938
|
+
switch (option.dbType) {
|
|
2939
|
+
case DBType.Postgresql:
|
|
2940
|
+
questMark.push('gen_random_uuid()');
|
|
2941
|
+
break;
|
|
2942
|
+
default:
|
|
2943
|
+
questMark.push('UUID()');
|
|
2944
|
+
break;
|
|
2945
|
+
}
|
|
2946
|
+
} else if (field?.uuidShort) {
|
|
2947
|
+
switch (option.dbType) {
|
|
2948
|
+
case DBType.Postgresql:
|
|
2949
|
+
questMark.push(`encode(uuid_send(gen_random_uuid()::uuid),'base64')`);
|
|
2950
|
+
break;
|
|
2951
|
+
case DBType.Mysql:
|
|
2952
|
+
questMark.push('UUID_SHORT()');
|
|
2953
|
+
break;
|
|
2954
|
+
default:
|
|
2955
|
+
questMark.push('?');
|
|
2956
|
+
params.push(V);
|
|
2957
|
+
break;
|
|
2958
|
+
|
|
2959
|
+
}
|
|
2550
2960
|
} else {
|
|
2551
2961
|
questMark.push('?');
|
|
2552
2962
|
params.push(V);
|
|
@@ -2564,14 +2974,13 @@ export class SqlService<T extends object> {
|
|
|
2564
2974
|
${tableName}
|
|
2565
2975
|
(${columnNames})
|
|
2566
2976
|
VALUES ${questMarks};
|
|
2567
|
-
`, { dialect:
|
|
2568
|
-
|
|
2977
|
+
`, { dialect: formatDialects[option!.dbType!] });
|
|
2569
2978
|
sqls.push({ sql, params });
|
|
2570
2979
|
break;
|
|
2571
2980
|
}
|
|
2572
2981
|
case InsertMode.InsertWithTempTable: {
|
|
2573
2982
|
const tableTemp = `${option?.tableName}_${Math.random()}`.replace(/\./, '');
|
|
2574
|
-
const tableTempESC =
|
|
2983
|
+
const tableTempESC = tableTemp;
|
|
2575
2984
|
sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
|
|
2576
2985
|
const finalColumns = new Set<string>();
|
|
2577
2986
|
const params: any[] = [];
|
|
@@ -2588,9 +2997,28 @@ export class SqlService<T extends object> {
|
|
|
2588
2997
|
if (V === null) {
|
|
2589
2998
|
const field = this[_fields]![column];
|
|
2590
2999
|
if (field?.uuid) {
|
|
2591
|
-
|
|
2592
|
-
|
|
2593
|
-
|
|
3000
|
+
switch (option.dbType) {
|
|
3001
|
+
case DBType.Postgresql:
|
|
3002
|
+
questMark.push('gen_random_uuid()');
|
|
3003
|
+
break;
|
|
3004
|
+
default:
|
|
3005
|
+
questMark.push('UUID()');
|
|
3006
|
+
break;
|
|
3007
|
+
}
|
|
3008
|
+
} else if (field?.uuidShort) {
|
|
3009
|
+
switch (option.dbType) {
|
|
3010
|
+
case DBType.Postgresql:
|
|
3011
|
+
questMark.push(`encode(uuid_send(gen_random_uuid()::uuid),'base64')`);
|
|
3012
|
+
break;
|
|
3013
|
+
case DBType.Mysql:
|
|
3014
|
+
questMark.push('UUID_SHORT()');
|
|
3015
|
+
break;
|
|
3016
|
+
default:
|
|
3017
|
+
questMark.push('?');
|
|
3018
|
+
params.push(V);
|
|
3019
|
+
break;
|
|
3020
|
+
|
|
3021
|
+
}
|
|
2594
3022
|
} else {
|
|
2595
3023
|
questMark.push('?');
|
|
2596
3024
|
params.push(V);
|
|
@@ -2611,16 +3039,17 @@ export class SqlService<T extends object> {
|
|
|
2611
3039
|
${tableTemp}
|
|
2612
3040
|
(${columnNames})
|
|
2613
3041
|
VALUES ${questMarks};
|
|
2614
|
-
`, { dialect:
|
|
3042
|
+
`, { dialect: formatDialects[option!.dbType!] }), params
|
|
2615
3043
|
});
|
|
2616
3044
|
sqls.push({
|
|
2617
|
-
sql: formatDialect(`INSERT INTO ${
|
|
2618
|
-
SELECT ${columnNames} FROM ${tableTemp};`, { dialect:
|
|
3045
|
+
sql: formatDialect(`INSERT INTO ${option.tableName} (${columnNames})
|
|
3046
|
+
SELECT ${columnNames} FROM ${tableTemp};`, { dialect: formatDialects[option!.dbType!] })
|
|
2619
3047
|
});
|
|
2620
3048
|
sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
|
|
2621
3049
|
break;
|
|
2622
3050
|
}
|
|
2623
3051
|
}
|
|
3052
|
+
|
|
2624
3053
|
return sqls;
|
|
2625
3054
|
}
|
|
2626
3055
|
/**
|
|
@@ -2670,7 +3099,7 @@ export class SqlService<T extends object> {
|
|
|
2670
3099
|
let result = 0n;
|
|
2671
3100
|
for (const { sql, params } of sqls) {
|
|
2672
3101
|
const dd = option!.conn!.execute(SyncMode.Sync, sql, params);
|
|
2673
|
-
if (dd.insertId) { result += dd.insertId; }
|
|
3102
|
+
if (dd.insertId) { result += BigInt(dd.insertId); }
|
|
2674
3103
|
}
|
|
2675
3104
|
return result;
|
|
2676
3105
|
},
|
|
@@ -2679,7 +3108,7 @@ export class SqlService<T extends object> {
|
|
|
2679
3108
|
if (isArray) return result;
|
|
2680
3109
|
else return result[0]!;
|
|
2681
3110
|
};
|
|
2682
|
-
if (
|
|
3111
|
+
if (option!.dbType === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
|
|
2683
3112
|
return fn();
|
|
2684
3113
|
} else {
|
|
2685
3114
|
return option?.dao?.transaction(SyncMode.Sync, fn, option?.conn)!;
|
|
@@ -2694,7 +3123,7 @@ export class SqlService<T extends object> {
|
|
|
2694
3123
|
let result = 0n;
|
|
2695
3124
|
for (const { sql, params } of sqls) {
|
|
2696
3125
|
const dd = await option!.conn!.execute(SyncMode.Async, sql, params);
|
|
2697
|
-
if (dd.insertId) { result += dd.insertId; }
|
|
3126
|
+
if (dd.insertId) { result += BigInt(dd.insertId); }
|
|
2698
3127
|
}
|
|
2699
3128
|
return result;
|
|
2700
3129
|
},
|
|
@@ -2703,22 +3132,11 @@ export class SqlService<T extends object> {
|
|
|
2703
3132
|
return result;
|
|
2704
3133
|
};
|
|
2705
3134
|
|
|
2706
|
-
if (
|
|
3135
|
+
if (option!.dbType === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
|
|
2707
3136
|
return fn();
|
|
2708
3137
|
} else {
|
|
2709
3138
|
return option?.dao?.transaction(SyncMode.Async, fn, option?.conn) as Promise<bigint[]>;
|
|
2710
3139
|
}
|
|
2711
|
-
// return new Promise<bigint[]>(async (resolve, reject) => {
|
|
2712
|
-
// try {
|
|
2713
|
-
// if (this[_dbType] === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
|
|
2714
|
-
// resolve((await fn())!);
|
|
2715
|
-
// } else {
|
|
2716
|
-
// await option?.dao?.transaction(SyncMode.Async, async () => resolve((await fn())!), option?.conn);
|
|
2717
|
-
// }
|
|
2718
|
-
// } catch (error) {
|
|
2719
|
-
// reject(error);
|
|
2720
|
-
// }
|
|
2721
|
-
// });
|
|
2722
3140
|
} else {
|
|
2723
3141
|
const fn = async () => {
|
|
2724
3142
|
const result = await excuteSplit<Partial<T>, bigint>(
|
|
@@ -2737,28 +3155,17 @@ export class SqlService<T extends object> {
|
|
|
2737
3155
|
);
|
|
2738
3156
|
return result[0]!;
|
|
2739
3157
|
};
|
|
2740
|
-
if (
|
|
3158
|
+
if (option!.dbType === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
|
|
2741
3159
|
return fn();
|
|
2742
3160
|
} else {
|
|
2743
3161
|
return option?.dao?.transaction(SyncMode.Async, fn, option?.conn) as Promise<bigint>;
|
|
2744
3162
|
}
|
|
2745
|
-
// return new Promise<bigint>(async (resolve, reject) => {
|
|
2746
|
-
// try {
|
|
2747
|
-
// if (this[_dbType] === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
|
|
2748
|
-
// resolve((await fn())!);
|
|
2749
|
-
// } else {
|
|
2750
|
-
// await option?.dao?.transaction(SyncMode.Async, async () => resolve((await fn())!), option?.conn);
|
|
2751
|
-
// }
|
|
2752
|
-
// } catch (error) {
|
|
2753
|
-
// reject(error);
|
|
2754
|
-
// }
|
|
2755
|
-
// });
|
|
2756
3163
|
}
|
|
2757
3164
|
}
|
|
2758
3165
|
|
|
2759
3166
|
private _update(datas: Array<Partial<T>>, option: MethodOption): { sql: string; params?: any[] }[] {
|
|
2760
3167
|
const sqls: { sql: string; params?: any[] }[] = [];
|
|
2761
|
-
const tableName =
|
|
3168
|
+
const tableName = option?.tableName;
|
|
2762
3169
|
const where = `WHEN ${iterare(this[_ids]!).map(c => `${this[_fields]![c]?.C2()} = ?`).join(' AND ')} THEN ?`;
|
|
2763
3170
|
const columnMaps: Record<string, {
|
|
2764
3171
|
where: string[];
|
|
@@ -2790,7 +3197,7 @@ export class SqlService<T extends object> {
|
|
|
2790
3197
|
params.push(...columnMaps[K]!.params);
|
|
2791
3198
|
return `${this[_fields]![K]?.C2()} = CASE ${columnMaps[K]!.where.join(' ')} ELSE ${this[_fields]![K]?.C2()} END`
|
|
2792
3199
|
})
|
|
2793
|
-
.join(',')};`, { dialect:
|
|
3200
|
+
.join(',')};`, { dialect: formatDialects[option!.dbType!] });
|
|
2794
3201
|
sqls.push({ sql, params });
|
|
2795
3202
|
return sqls;
|
|
2796
3203
|
}
|
|
@@ -2836,7 +3243,7 @@ export class SqlService<T extends object> {
|
|
|
2836
3243
|
);
|
|
2837
3244
|
return result.reduce((a, b) => a + b);
|
|
2838
3245
|
};
|
|
2839
|
-
if (
|
|
3246
|
+
if (option!.dbType === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
|
|
2840
3247
|
return fn();
|
|
2841
3248
|
} else {
|
|
2842
3249
|
return option?.dao?.transaction(SyncMode.Sync, fn, option?.conn)!;
|
|
@@ -2859,23 +3266,11 @@ export class SqlService<T extends object> {
|
|
|
2859
3266
|
);
|
|
2860
3267
|
return result.reduce((a, b) => a + b);
|
|
2861
3268
|
};
|
|
2862
|
-
if (
|
|
3269
|
+
if (option!.dbType === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
|
|
2863
3270
|
return fn();
|
|
2864
3271
|
} else {
|
|
2865
3272
|
return option?.dao?.transaction(SyncMode.Async, fn, option?.conn) as Promise<number>;
|
|
2866
3273
|
}
|
|
2867
|
-
|
|
2868
|
-
return new Promise<number>(async (resolve, reject) => {
|
|
2869
|
-
try {
|
|
2870
|
-
if (this[_dbType] === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
|
|
2871
|
-
resolve((await fn())!);
|
|
2872
|
-
} else {
|
|
2873
|
-
await option?.dao?.transaction(SyncMode.Async, async () => resolve((await fn())!), option?.conn);
|
|
2874
|
-
}
|
|
2875
|
-
} catch (error) {
|
|
2876
|
-
reject(error);
|
|
2877
|
-
}
|
|
2878
|
-
});
|
|
2879
3274
|
}
|
|
2880
3275
|
}
|
|
2881
3276
|
|
|
@@ -2917,8 +3312,8 @@ export class SqlService<T extends object> {
|
|
|
2917
3312
|
|
|
2918
3313
|
option.mode ??= DeleteMode.Common;
|
|
2919
3314
|
const tableTemp = `${option?.tableName}_${Math.random()}`.replace(/\./, '');
|
|
2920
|
-
const tableTempESC =
|
|
2921
|
-
const tableNameESC =
|
|
3315
|
+
const tableTempESC = tableTemp;
|
|
3316
|
+
const tableNameESC = option?.tableName;
|
|
2922
3317
|
|
|
2923
3318
|
if (option.id) {
|
|
2924
3319
|
const idName = this[_ids]![0]!;
|
|
@@ -2945,27 +3340,27 @@ export class SqlService<T extends object> {
|
|
|
2945
3340
|
sql: formatDialect(`
|
|
2946
3341
|
UPDATE ${tableNameESC} SET ${this[_fields]![this[_stateFileName]]?.C2()} = ?
|
|
2947
3342
|
WHERE ${whereSql};
|
|
2948
|
-
`, { dialect:
|
|
3343
|
+
`, { dialect: formatDialects[option!.dbType!] }), params
|
|
2949
3344
|
});
|
|
2950
3345
|
} else {
|
|
2951
|
-
sqls.push({ sql: formatDialect(`DELETE FROM ${tableNameESC} WHERE ${whereSql};`, { dialect:
|
|
3346
|
+
sqls.push({ sql: formatDialect(`DELETE FROM ${tableNameESC} WHERE ${whereSql};`, { dialect: formatDialects[option!.dbType!] }), params });
|
|
2952
3347
|
}
|
|
2953
3348
|
} else {
|
|
2954
3349
|
sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
|
|
2955
3350
|
const delWhere = Object.keys(wheres[0] as unknown as any);
|
|
2956
3351
|
const _sqls = this._createTable({ tableName: tableTemp, temp: true, columns: delWhere, data: wheres, index: 'all', id: 'none' })!;
|
|
2957
3352
|
sqls.push(..._sqls);
|
|
2958
|
-
switch (
|
|
3353
|
+
switch (option!.dbType) {
|
|
2959
3354
|
case DBType.Mysql: {
|
|
2960
3355
|
if (this[_stateFileName] !== undefined && option.forceDelete !== true) {
|
|
2961
3356
|
sqls.push({
|
|
2962
3357
|
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 ')}
|
|
2963
|
-
SET a.${this[_fields]![this[_stateFileName]]?.C2()} = ?;`, { dialect:
|
|
3358
|
+
SET a.${this[_fields]![this[_stateFileName]]?.C2()} = ?;`, { dialect: formatDialects[option!.dbType!] }),
|
|
2964
3359
|
params: [this[_deleteState]]
|
|
2965
3360
|
});
|
|
2966
3361
|
} else {
|
|
2967
3362
|
sqls.push({
|
|
2968
|
-
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:
|
|
3363
|
+
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!] })
|
|
2969
3364
|
});
|
|
2970
3365
|
}
|
|
2971
3366
|
break;
|
|
@@ -2976,11 +3371,11 @@ export class SqlService<T extends object> {
|
|
|
2976
3371
|
if (this[_stateFileName] !== undefined && option.forceDelete !== true) {
|
|
2977
3372
|
sqls.push({
|
|
2978
3373
|
sql: formatDialect(`UPDATE ${tableNameESC} SET ${this[_fields]![this[_stateFileName]]?.C2()} = ?
|
|
2979
|
-
WHERE (${columnNames}) IN (SELECT ${columnNames} FROM ${tableTempESC});`, { dialect:
|
|
3374
|
+
WHERE (${columnNames}) IN (SELECT ${columnNames} FROM ${tableTempESC});`, { dialect: formatDialects[option!.dbType!] }),
|
|
2980
3375
|
params: [this[_deleteState]]
|
|
2981
3376
|
});
|
|
2982
3377
|
} else {
|
|
2983
|
-
sqls.push({ sql: formatDialect(`DELETE FROM ${tableNameESC} WHERE (${columnNames}) IN (SELECT ${columnNames} FROM ${tableTempESC});`, { dialect:
|
|
3378
|
+
sqls.push({ sql: formatDialect(`DELETE FROM ${tableNameESC} WHERE (${columnNames}) IN (SELECT ${columnNames} FROM ${tableTempESC});`, { dialect: formatDialects[option!.dbType!] }) });
|
|
2984
3379
|
}
|
|
2985
3380
|
break;
|
|
2986
3381
|
}
|
|
@@ -2997,7 +3392,7 @@ export class SqlService<T extends object> {
|
|
|
2997
3392
|
}
|
|
2998
3393
|
return result;
|
|
2999
3394
|
};
|
|
3000
|
-
if (
|
|
3395
|
+
if (option!.dbType === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
|
|
3001
3396
|
return fn();
|
|
3002
3397
|
} else {
|
|
3003
3398
|
return option?.dao?.transaction(SyncMode.Sync, fn, option?.conn)!;
|
|
@@ -3011,22 +3406,11 @@ export class SqlService<T extends object> {
|
|
|
3011
3406
|
}
|
|
3012
3407
|
return result;
|
|
3013
3408
|
};
|
|
3014
|
-
if (
|
|
3409
|
+
if (option!.dbType === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
|
|
3015
3410
|
return fn();
|
|
3016
3411
|
} else {
|
|
3017
3412
|
return option?.dao?.transaction<number>(SyncMode.Async, fn, option?.conn) as Promise<number>;
|
|
3018
3413
|
}
|
|
3019
|
-
// return new Promise<number>(async (resolve, reject) => {
|
|
3020
|
-
// try {
|
|
3021
|
-
// if (this[_dbType] === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
|
|
3022
|
-
// resolve((await fn())!);
|
|
3023
|
-
// } else {
|
|
3024
|
-
// await option?.dao?.transaction(SyncMode.Async, async () => resolve((await fn())!), option?.conn);
|
|
3025
|
-
// }
|
|
3026
|
-
// } catch (error) {
|
|
3027
|
-
// reject(error);
|
|
3028
|
-
// }
|
|
3029
|
-
// });
|
|
3030
3414
|
}
|
|
3031
3415
|
}
|
|
3032
3416
|
|
|
@@ -3095,8 +3479,8 @@ export class SqlService<T extends object> {
|
|
|
3095
3479
|
option.templateResult ??= TemplateResult.AssertOne;
|
|
3096
3480
|
option.error ??= 'error data!';
|
|
3097
3481
|
const tableTemp = `${option?.tableName}_${Math.random()}`.replace(/\./, '');
|
|
3098
|
-
const tableTempESC =
|
|
3099
|
-
const tableNameESC =
|
|
3482
|
+
const tableTempESC = tableTemp;
|
|
3483
|
+
const tableNameESC = option?.tableName;
|
|
3100
3484
|
|
|
3101
3485
|
if (option.id) {
|
|
3102
3486
|
const idName = this[_ids]![0]!;
|
|
@@ -3115,7 +3499,7 @@ export class SqlService<T extends object> {
|
|
|
3115
3499
|
params.push(V);
|
|
3116
3500
|
return `${this[_fields]![K]?.C2()} = ?`;
|
|
3117
3501
|
}).join(' AND ')}`;
|
|
3118
|
-
}).join(' UNION ALL '), { dialect:
|
|
3502
|
+
}).join(' UNION ALL '), { dialect: formatDialects[option!.dbType!] });
|
|
3119
3503
|
sqls.push({ sql: whereSql, params });
|
|
3120
3504
|
resultIndex = 0;
|
|
3121
3505
|
} else {
|
|
@@ -3124,7 +3508,7 @@ export class SqlService<T extends object> {
|
|
|
3124
3508
|
const _sqls = this._createTable<L>({ tableName: tableTemp, temp: true, columns: delWhere, data: wheres, index: 'all', id: 'none' })!;
|
|
3125
3509
|
sqls.push(..._sqls);
|
|
3126
3510
|
resultIndex = sqls.length;
|
|
3127
|
-
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:
|
|
3511
|
+
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!] }) });
|
|
3128
3512
|
sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
|
|
3129
3513
|
}
|
|
3130
3514
|
|
|
@@ -3296,7 +3680,7 @@ export class SqlService<T extends object> {
|
|
|
3296
3680
|
return '?';
|
|
3297
3681
|
}
|
|
3298
3682
|
return txt;
|
|
3299
|
-
})!, { dialect:
|
|
3683
|
+
})!, { dialect: formatDialects[option!.dbType!] });
|
|
3300
3684
|
if (option.sync === SyncMode.Sync) {
|
|
3301
3685
|
const result = option!.conn!.query(SyncMode.Sync, sql, params);
|
|
3302
3686
|
return this._select<L>(option.selectResult, result, option.defValue, option.errorMsg, option.hump, option.mapper, option.mapperIfUndefined);
|
|
@@ -3354,7 +3738,7 @@ export class SqlService<T extends object> {
|
|
|
3354
3738
|
return '?';
|
|
3355
3739
|
}
|
|
3356
3740
|
return txt;
|
|
3357
|
-
})!, { dialect:
|
|
3741
|
+
})!, { dialect: formatDialects[option!.dbType!] });
|
|
3358
3742
|
if (option.sync === SyncMode.Sync) {
|
|
3359
3743
|
const result = option!.conn!.execute(SyncMode.Sync, sql, params);
|
|
3360
3744
|
return result.affectedRows;
|
|
@@ -3569,9 +3953,9 @@ export class SqlService<T extends object> {
|
|
|
3569
3953
|
init(option: MethodOption & { sync: SyncMode.Sync; force?: boolean }): void;
|
|
3570
3954
|
@P<T>()
|
|
3571
3955
|
init(option?: MethodOption & { sync?: SyncMode; force?: boolean }): void | Promise<void> {
|
|
3572
|
-
const tableES =
|
|
3956
|
+
const tableES = option!.tableName;
|
|
3573
3957
|
option!.force ??= false;
|
|
3574
|
-
if (
|
|
3958
|
+
if (option!.dbType === DBType.Sqlite) {
|
|
3575
3959
|
if (option?.force) {
|
|
3576
3960
|
option!.conn!.execute(SyncMode.Sync, `DROP TABLE IF EXISTS ${tableES};`);
|
|
3577
3961
|
}
|
|
@@ -3585,10 +3969,10 @@ export class SqlService<T extends object> {
|
|
|
3585
3969
|
// 更新版本
|
|
3586
3970
|
const columns = iterare<{ name: string }>(option!.conn!.query(SyncMode.Sync, `PRAGMA table_info(${tableES})`))
|
|
3587
3971
|
.filter(c => this[_fields]!.hasOwnProperty(C2P(c.name, globalThis[_Hump])))
|
|
3588
|
-
.map(c =>
|
|
3972
|
+
.map(c => c.name)
|
|
3589
3973
|
.join(',');
|
|
3590
3974
|
|
|
3591
|
-
const rtable =
|
|
3975
|
+
const rtable = `${option!.tableName}_${tableVersion.replace(/\./, '_')}`;
|
|
3592
3976
|
option!.conn!.execute(SyncMode.Sync, `DROP TABLE IF EXISTS ${rtable};`);
|
|
3593
3977
|
option!.conn!.execute(SyncMode.Sync, `ALTER TABLE ${tableES} RENAME TO ${rtable};`);
|
|
3594
3978
|
option!.conn!.execute(SyncMode.Sync, `
|
|
@@ -3599,7 +3983,7 @@ export class SqlService<T extends object> {
|
|
|
3599
3983
|
`);
|
|
3600
3984
|
if (this[_index] && this[_index].length) {
|
|
3601
3985
|
for (const index of this[_index]) {
|
|
3602
|
-
option!.conn!.execute(SyncMode.Sync, `CREATE INDEX ${
|
|
3986
|
+
option!.conn!.execute(SyncMode.Sync, `CREATE INDEX ${`${index}_${Math.random()}`.replace(/\./, '')} ON ${tableES} ("${this[_fields]![index]?.C2()}");`);
|
|
3603
3987
|
}
|
|
3604
3988
|
}
|
|
3605
3989
|
option!.conn!.execute(SyncMode.Sync, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
|
|
@@ -3621,12 +4005,12 @@ export class SqlService<T extends object> {
|
|
|
3621
4005
|
`);
|
|
3622
4006
|
if (this[_index] && this[_index].length) {
|
|
3623
4007
|
for (const index of this[_index]) {
|
|
3624
|
-
option!.conn!.execute(SyncMode.Sync, `CREATE INDEX ${
|
|
4008
|
+
option!.conn!.execute(SyncMode.Sync, `CREATE INDEX ${`${index}_${Math.random()}`.replace(/\./, '')} ON ${tableES} ("${this[_fields]![index]?.C2()}");`);
|
|
3625
4009
|
}
|
|
3626
4010
|
}
|
|
3627
4011
|
option!.conn!.execute(SyncMode.Sync, 'INSERT OR REPLACE INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option!.tableName, lastVersion]);
|
|
3628
4012
|
}
|
|
3629
|
-
} else if (
|
|
4013
|
+
} else if (option!.dbType === DBType.SqliteRemote) {
|
|
3630
4014
|
|
|
3631
4015
|
return new Promise(async (resolve, reject) => {
|
|
3632
4016
|
try {
|
|
@@ -3643,7 +4027,7 @@ export class SqlService<T extends object> {
|
|
|
3643
4027
|
// 更新版本
|
|
3644
4028
|
const columns = iterare<{ name: string }>(await option!.conn!.query(SyncMode.Async, `PRAGMA table_info(${tableES})`))
|
|
3645
4029
|
.filter(c => this[_fields]!.hasOwnProperty(C2P(c.name, globalThis[_Hump])))
|
|
3646
|
-
.map(c =>
|
|
4030
|
+
.map(c => c.name)
|
|
3647
4031
|
.join(',');
|
|
3648
4032
|
|
|
3649
4033
|
const rtable = `${option!.tableName}_${tableVersion.replace(/\./, '_')}`;
|
|
@@ -3657,7 +4041,7 @@ export class SqlService<T extends object> {
|
|
|
3657
4041
|
`);
|
|
3658
4042
|
if (this[_index] && this[_index].length) {
|
|
3659
4043
|
for (const index of this[_index]) {
|
|
3660
|
-
await option!.conn!.execute(SyncMode.Async, `CREATE INDEX ${
|
|
4044
|
+
await option!.conn!.execute(SyncMode.Async, `CREATE INDEX ${`${index}_${Math.random()}`.replace(/\./, '')} ON ${tableES} ("${this[_fields]![index]?.C2()}");`);
|
|
3661
4045
|
}
|
|
3662
4046
|
}
|
|
3663
4047
|
await option!.conn!.execute(SyncMode.Async, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
|
|
@@ -3678,7 +4062,7 @@ export class SqlService<T extends object> {
|
|
|
3678
4062
|
`);
|
|
3679
4063
|
if (this[_index] && this[_index].length) {
|
|
3680
4064
|
for (const index of this[_index]) {
|
|
3681
|
-
await option!.conn!.execute(SyncMode.Async, `CREATE INDEX ${
|
|
4065
|
+
await option!.conn!.execute(SyncMode.Async, `CREATE INDEX ${`${index}_${Math.random()}`.replace(/\./, '')} ON ${option!.tableName} ("${this[_fields]![index]?.C2()}");`);
|
|
3682
4066
|
}
|
|
3683
4067
|
}
|
|
3684
4068
|
await option!.conn!.execute(SyncMode.Async, 'INSERT OR REPLACE INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option!.tableName, lastVersion]);
|
|
@@ -3695,8 +4079,7 @@ export class SqlService<T extends object> {
|
|
|
3695
4079
|
close(option: MethodOption & { sync: SyncMode.Sync; }): void;
|
|
3696
4080
|
@P<T>()
|
|
3697
4081
|
close(option?: MethodOption & { sync?: SyncMode; force?: boolean }): void | Promise<void> {
|
|
3698
|
-
|
|
3699
|
-
delete globalThis[_dao][this[_dbType]!][dbName];
|
|
4082
|
+
delete globalThis[_dao][option!.dbType][option!.dbName];
|
|
3700
4083
|
if (option?.sync === SyncMode.Async) {
|
|
3701
4084
|
return option!.dao!.close(SyncMode.Async);
|
|
3702
4085
|
} else if (option?.sync === SyncMode.Sync) {
|
|
@@ -3716,13 +4099,14 @@ export class SqlService<T extends object> {
|
|
|
3716
4099
|
4. 自定义字段名称:字符串数组
|
|
3717
4100
|
** `index` 表的索引,设置方式同ID
|
|
3718
4101
|
*/
|
|
3719
|
-
private _createTable<L = T>({ tableName, temp = true, columns, data, id = 'auto', index = 'auto' }: {
|
|
4102
|
+
private _createTable<L = T>({ tableName, temp = true, columns, data, id = 'auto', index = 'auto', dbType }: {
|
|
3720
4103
|
tableName?: string;
|
|
3721
4104
|
temp?: boolean,
|
|
3722
4105
|
columns?: string[];
|
|
3723
4106
|
data?: Array<Partial<L>>;
|
|
3724
4107
|
id?: 'auto' | 'all' | 'none' | string[];
|
|
3725
4108
|
index?: 'auto' | 'all' | 'none' | string[];
|
|
4109
|
+
dbType?: DBType;
|
|
3726
4110
|
} = {}): { sql: string; params?: any[] }[] {
|
|
3727
4111
|
const sqls: { sql: string; params?: any[] }[] = [];
|
|
3728
4112
|
columns = columns || this[_columns]!;
|
|
@@ -3746,14 +4130,14 @@ export class SqlService<T extends object> {
|
|
|
3746
4130
|
} else {
|
|
3747
4131
|
indexs = index;
|
|
3748
4132
|
}
|
|
3749
|
-
tableName =
|
|
3750
|
-
switch (
|
|
4133
|
+
tableName = tableName ?? this[_tableName];
|
|
4134
|
+
switch (dbType) {
|
|
3751
4135
|
case DBType.Mysql: {
|
|
3752
4136
|
let sql = formatDialect(`CREATE ${temp === true ? 'TEMPORARY' : ''} TABLE IF NOT EXISTS ${tableName}(
|
|
3753
4137
|
${columns.map(K => this[_fields]![K]![DBType.Mysql]()).join(',')}
|
|
3754
4138
|
${ids && ids.length ? `,PRIMARY KEY (${ids.map(i => this[_fields]![i]?.C2()).join(',')}) USING BTREE ` : ''}
|
|
3755
4139
|
${indexs && indexs.length ? `,${indexs.map(i => `KEY ${this[_fields]![i]?.C2()} (${this[_fields]![i]?.C2()})`).join(',')} ` : ''}
|
|
3756
|
-
) ENGINE=MEMORY;`, { dialect:
|
|
4140
|
+
) ENGINE=MEMORY;`, { dialect: mysql });
|
|
3757
4141
|
sqls.push({ sql });
|
|
3758
4142
|
if (data && data.length > 0) {
|
|
3759
4143
|
const params: any[] = [];
|
|
@@ -3766,7 +4150,7 @@ export class SqlService<T extends object> {
|
|
|
3766
4150
|
}).join(',')}`;
|
|
3767
4151
|
first = false;
|
|
3768
4152
|
return r;
|
|
3769
|
-
}).join(' UNION ALL ')}`, { dialect:
|
|
4153
|
+
}).join(' UNION ALL ')}`, { dialect: mysql });
|
|
3770
4154
|
sqls.push({ sql, params });
|
|
3771
4155
|
}
|
|
3772
4156
|
break;
|
|
@@ -3776,11 +4160,11 @@ export class SqlService<T extends object> {
|
|
|
3776
4160
|
let sql = formatDialect(`CREATE ${temp === true ? 'TEMPORARY' : ''} TABLE IF NOT EXISTS ${tableName}(
|
|
3777
4161
|
${columns.map(K => this[_fields]![K]![DBType.Sqlite]()).join(',')}
|
|
3778
4162
|
${ids && ids.length ? `,PRIMARY KEY (${ids.map(i => this[_fields]![i]?.C2()).join(',')}) ` : ''}
|
|
3779
|
-
);`, { dialect:
|
|
4163
|
+
);`, { dialect: sqlite });
|
|
3780
4164
|
sqls.push({ sql });
|
|
3781
4165
|
if (indexs) {
|
|
3782
4166
|
for (const index of indexs) {
|
|
3783
|
-
sql = formatDialect(`CREATE INDEX ${
|
|
4167
|
+
sql = formatDialect(`CREATE INDEX ${`${index}_${Math.random()}`.replace(/\./, '')} ON ${tableName} (${this[_fields]![index]?.C2()});`, { dialect: sqlite });
|
|
3784
4168
|
sqls.push({ sql });
|
|
3785
4169
|
}
|
|
3786
4170
|
}
|
|
@@ -3795,7 +4179,7 @@ export class SqlService<T extends object> {
|
|
|
3795
4179
|
}).join(',')}`;
|
|
3796
4180
|
first = false;
|
|
3797
4181
|
return r;
|
|
3798
|
-
}).join(' UNION ALL ')}`, { dialect:
|
|
4182
|
+
}).join(' UNION ALL ')}`, { dialect: sqlite });
|
|
3799
4183
|
sqls.push({ sql, params });
|
|
3800
4184
|
}
|
|
3801
4185
|
break;
|