@rws-framework/db 3.2.0 → 3.3.1
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/dist/decorators/IdType.js +6 -0
- package/dist/decorators/InverseRelation.js +3 -4
- package/dist/decorators/Relation.js +2 -2
- package/dist/decorators/TrackType.js +2 -2
- package/dist/helper/DbHelper.d.ts +1 -1
- package/dist/helper/DbHelper.js +5 -5
- package/dist/helper/db/relation-manager.js +1 -1
- package/dist/helper/db/schema-generator.js +52 -21
- package/dist/helper/db/type-converter.d.ts +2 -1
- package/dist/helper/db/type-converter.js +10 -7
- package/dist/helper/db/utils.d.ts +8 -0
- package/dist/helper/db/utils.js +85 -26
- package/dist/models/core/RWSModel.js +29 -32
- package/dist/models/interfaces/IIdTypeOpts.d.ts +2 -0
- package/dist/models/interfaces/ITrackerOpts.d.ts +1 -0
- package/dist/models/utils/ModelUtils.js +8 -1
- package/dist/models/utils/PaginationUtils.js +5 -6
- package/dist/services/DBService.js +7 -8
- package/package.json +1 -1
- package/src/decorators/IdType.ts +10 -1
- package/src/decorators/InverseRelation.ts +2 -2
- package/src/decorators/Relation.ts +2 -2
- package/src/helper/DbHelper.ts +2 -2
- package/src/helper/db/schema-generator.ts +73 -29
- package/src/helper/db/type-converter.ts +10 -4
- package/src/helper/db/utils.ts +121 -40
- package/src/models/interfaces/IIdTypeOpts.ts +2 -0
- package/src/models/interfaces/ITrackerOpts.ts +1 -0
- package/src/models/utils/ModelUtils.ts +10 -1
- package/tsconfig.json +1 -1
|
@@ -3,6 +3,12 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
require("reflect-metadata");
|
|
4
4
|
function IdType(type, opts = null, tags = []) {
|
|
5
5
|
const metaOpts = { type, dbOptions: opts && opts.dbOptions ? opts.dbOptions : null };
|
|
6
|
+
if (opts && opts.dbOptions) {
|
|
7
|
+
metaOpts.dbOptions = opts.dbOptions;
|
|
8
|
+
}
|
|
9
|
+
if (opts && opts.noAuto) {
|
|
10
|
+
metaOpts.noAuto = opts.noAuto;
|
|
11
|
+
}
|
|
6
12
|
return function (target, key) {
|
|
7
13
|
Reflect.defineMetadata(`IdType:${key}`, metaOpts, target);
|
|
8
14
|
};
|
|
@@ -3,7 +3,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
require("reflect-metadata");
|
|
4
4
|
const ModelUtils_1 = require("../models/utils/ModelUtils");
|
|
5
5
|
function guessForeignKey(inversionModel, bindingModel, decoratorsData) {
|
|
6
|
-
var _a;
|
|
7
6
|
let key = null;
|
|
8
7
|
let defaultKey = `${bindingModel._collection}_id`;
|
|
9
8
|
const relDecorators = {};
|
|
@@ -21,7 +20,7 @@ function guessForeignKey(inversionModel, bindingModel, decoratorsData) {
|
|
|
21
20
|
}
|
|
22
21
|
}
|
|
23
22
|
for (const relKey of Object.keys(relDecorators)) {
|
|
24
|
-
const prodMeta =
|
|
23
|
+
const prodMeta = relDecorators[relKey]?.metadata;
|
|
25
24
|
if (prodMeta && prodMeta.relatedTo._collection === bindingModel._collection) {
|
|
26
25
|
return prodMeta.relationField;
|
|
27
26
|
}
|
|
@@ -41,8 +40,8 @@ function InverseRelation(inversionModel, sourceModel, relationOptions = null) {
|
|
|
41
40
|
foreignKey: relationOptions && relationOptions.foreignKey ? relationOptions.foreignKey : guessForeignKey(model, source, decoratorsData),
|
|
42
41
|
// Generate a unique relation name if one is not provided
|
|
43
42
|
relationName: relationOptions && relationOptions.relationName ?
|
|
44
|
-
relationOptions.relationName
|
|
45
|
-
|
|
43
|
+
relationOptions.relationName :
|
|
44
|
+
null
|
|
46
45
|
};
|
|
47
46
|
return metaOpts;
|
|
48
47
|
});
|
|
@@ -16,8 +16,8 @@ function Relation(theModel, relationOptions = _DEFAULTS) {
|
|
|
16
16
|
key,
|
|
17
17
|
// Generate a unique relation name if one is not provided
|
|
18
18
|
relationName: relationOptions.relationName ?
|
|
19
|
-
relationOptions.relationName
|
|
20
|
-
|
|
19
|
+
relationOptions.relationName :
|
|
20
|
+
null
|
|
21
21
|
};
|
|
22
22
|
if (relationOptions.required) {
|
|
23
23
|
metaOpts.cascade.onDelete = 'Restrict';
|
|
@@ -8,10 +8,10 @@ function TrackType(type, opts = null, tags = []) {
|
|
|
8
8
|
isArray: false
|
|
9
9
|
};
|
|
10
10
|
}
|
|
11
|
-
if (!
|
|
11
|
+
if (!opts?.required) {
|
|
12
12
|
opts.required = false;
|
|
13
13
|
}
|
|
14
|
-
if (!
|
|
14
|
+
if (!opts?.isArray) {
|
|
15
15
|
opts.isArray = false;
|
|
16
16
|
}
|
|
17
17
|
const required = opts.required;
|
|
@@ -60,7 +60,7 @@ export declare class DbHelper {
|
|
|
60
60
|
/**
|
|
61
61
|
* Convert a JavaScript type to a Prisma schema type
|
|
62
62
|
*/
|
|
63
|
-
static toConfigCase(modelType: any, dbType?:
|
|
63
|
+
static toConfigCase(modelType: any, dbType?: IDbConfigParams['db_type']): string;
|
|
64
64
|
/**
|
|
65
65
|
* Process type functions metadata to extract database-specific options
|
|
66
66
|
*/
|
package/dist/helper/DbHelper.js
CHANGED
|
@@ -10,6 +10,10 @@ const db_1 = require("./db");
|
|
|
10
10
|
* It delegates to the specialized modules for specific functionality.
|
|
11
11
|
*/
|
|
12
12
|
class DbHelper {
|
|
13
|
+
/**
|
|
14
|
+
* The environment variable name for the Prisma database URL
|
|
15
|
+
*/
|
|
16
|
+
static dbUrlVarName = db_1.SchemaGenerator.dbUrlVarName;
|
|
13
17
|
/**
|
|
14
18
|
* Install Prisma with the generated schema
|
|
15
19
|
* @param configService The configuration service
|
|
@@ -30,7 +34,7 @@ class DbHelper {
|
|
|
30
34
|
}
|
|
31
35
|
static async migrateDBModels(configService, dbService, leaveFile = false) {
|
|
32
36
|
process.env = { ...process.env, [this.dbUrlVarName]: configService.get('db_url') };
|
|
33
|
-
const [_, schemaPath] = db_1.DbUtils.
|
|
37
|
+
const [_, schemaPath] = db_1.DbUtils.getProcessedSchemaDir();
|
|
34
38
|
await console_1.rwsShell.runCommand(`${db_1.DbUtils.detectInstaller()} prisma migrate dev --create-only --schema=${schemaPath}`, process.cwd());
|
|
35
39
|
}
|
|
36
40
|
/**
|
|
@@ -107,7 +111,3 @@ class DbHelper {
|
|
|
107
111
|
}
|
|
108
112
|
}
|
|
109
113
|
exports.DbHelper = DbHelper;
|
|
110
|
-
/**
|
|
111
|
-
* The environment variable name for the Prisma database URL
|
|
112
|
-
*/
|
|
113
|
-
DbHelper.dbUrlVarName = db_1.SchemaGenerator.dbUrlVarName;
|
|
@@ -5,6 +5,7 @@ exports.RelationManager = void 0;
|
|
|
5
5
|
* Manages database relations for schema generation
|
|
6
6
|
*/
|
|
7
7
|
class RelationManager {
|
|
8
|
+
static allRelations = new Map();
|
|
8
9
|
/**
|
|
9
10
|
* Mark a relation between two models
|
|
10
11
|
* @param relationKey A unique key for the relation
|
|
@@ -102,4 +103,3 @@ class RelationManager {
|
|
|
102
103
|
}
|
|
103
104
|
}
|
|
104
105
|
exports.RelationManager = RelationManager;
|
|
105
|
-
RelationManager.allRelations = new Map();
|
|
@@ -11,10 +11,13 @@ const _model_1 = require("../../models/_model");
|
|
|
11
11
|
const utils_1 = require("./utils");
|
|
12
12
|
const type_converter_1 = require("./type-converter");
|
|
13
13
|
const relation_manager_1 = require("./relation-manager");
|
|
14
|
+
const _EXECUTE_PRISMA_CMD = true;
|
|
15
|
+
const _REMOVE_SCHEMA_FILE = true;
|
|
14
16
|
/**
|
|
15
17
|
* Handles Prisma schema generation
|
|
16
18
|
*/
|
|
17
19
|
class SchemaGenerator {
|
|
20
|
+
static dbUrlVarName = 'PRISMA_DB_URL';
|
|
18
21
|
/**
|
|
19
22
|
* Generate the base schema for Prisma
|
|
20
23
|
* @param dbType The database type
|
|
@@ -39,21 +42,31 @@ datasource db {
|
|
|
39
42
|
* @returns The model section
|
|
40
43
|
*/
|
|
41
44
|
static async generateModelSections(model, configService) {
|
|
42
|
-
var _a, _b;
|
|
43
45
|
let section = '';
|
|
44
46
|
const modelMetadatas = await _model_1.RWSModel.getModelAnnotations(model);
|
|
45
47
|
const dbType = configService.get('db_type') || 'mongodb';
|
|
46
48
|
const modelName = model._collection;
|
|
47
49
|
section += `model ${modelName} {\n`;
|
|
48
|
-
|
|
50
|
+
let hasIdType = false;
|
|
51
|
+
let idFieldName;
|
|
52
|
+
for (const someModelMetaKey in modelMetadatas) {
|
|
53
|
+
const isIdTyped = modelMetadatas[someModelMetaKey].annotationType === 'IdType';
|
|
54
|
+
if (isIdTyped) {
|
|
55
|
+
hasIdType = true;
|
|
56
|
+
idFieldName = someModelMetaKey;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
let idGenerated = false;
|
|
60
|
+
if (!model._NO_ID && !hasIdType) {
|
|
49
61
|
section += `\t${utils_1.DbUtils.generateId(dbType, modelMetadatas)}\n`;
|
|
62
|
+
idGenerated = true;
|
|
50
63
|
}
|
|
51
64
|
for (const key in modelMetadatas) {
|
|
52
65
|
const modelMetadata = modelMetadatas[key].metadata;
|
|
53
66
|
let requiredString = modelMetadata.required ? '' : '?';
|
|
54
67
|
const annotationType = modelMetadatas[key].annotationType;
|
|
55
68
|
let indexedId = false;
|
|
56
|
-
if (model._NO_ID) {
|
|
69
|
+
if (model._NO_ID || hasIdType) {
|
|
57
70
|
indexedId = true;
|
|
58
71
|
requiredString = '';
|
|
59
72
|
}
|
|
@@ -65,17 +78,17 @@ datasource db {
|
|
|
65
78
|
const relatedModel = relationMeta.relatedTo;
|
|
66
79
|
const isMany = relationMeta.many;
|
|
67
80
|
const cascadeOpts = [];
|
|
68
|
-
if (
|
|
81
|
+
if (relationMeta.cascade?.onDelete) {
|
|
69
82
|
cascadeOpts.push(`onDelete: ${relationMeta.cascade.onDelete}`);
|
|
70
83
|
}
|
|
71
|
-
if (
|
|
84
|
+
if (relationMeta.cascade?.onUpdate) {
|
|
72
85
|
cascadeOpts.push(`onUpdate: ${relationMeta.cascade.onUpdate}`);
|
|
73
86
|
}
|
|
74
87
|
const relatedModelName = relatedModel._collection;
|
|
75
88
|
const relationKey = [modelName, relatedModelName].join('_');
|
|
76
89
|
const relationIndex = relation_manager_1.RelationManager.getRelationCounter(relationKey);
|
|
77
|
-
const relationName =
|
|
78
|
-
const mapName =
|
|
90
|
+
const relationName = relationMeta.relationName ? relationMeta.relationName : null;
|
|
91
|
+
const mapName = relationMeta.mappingName ? relationMeta.mappingName : null;
|
|
79
92
|
const relatedModelMetadatas = await _model_1.RWSModel.getModelAnnotations(relatedModel);
|
|
80
93
|
const relationFieldName = modelMetadata.relationField ? modelMetadata.relationField : key.toLowerCase() + '_' + modelMetadata.relationField.toLowerCase();
|
|
81
94
|
const relatedToField = modelMetadata.relatedToField || 'id';
|
|
@@ -86,10 +99,10 @@ datasource db {
|
|
|
86
99
|
const cascadeStr = cascadeOpts.length ? `, ${cascadeOpts.join(', ')}` : '';
|
|
87
100
|
if (isMany) {
|
|
88
101
|
// Add an inverse field to the related model if it doesn't exist
|
|
89
|
-
section += `\t${key} ${relatedModel._collection}[] @relation("${relationName}", fields: [${relationFieldName}], references: [${relatedToField}]
|
|
102
|
+
section += `\t${key} ${relatedModel._collection}[] @relation(${relationName ? `"${relationName}", ` : ''}fields: [${relationFieldName}], references: [${relatedToField}]${mapName ? `, map: "${mapName}"` : ''}${cascadeStr})\n`;
|
|
90
103
|
}
|
|
91
104
|
else {
|
|
92
|
-
section += `\t${key} ${relatedModel._collection}${requiredString} @relation("${relationName}", fields: [${relationFieldName}], references: [${relatedToField}]
|
|
105
|
+
section += `\t${key} ${relatedModel._collection}${requiredString} @relation(${relationName ? `"${relationName}", ` : ''}fields: [${relationFieldName}], references: [${relatedToField}]${mapName ? `, map: "${mapName}"` : ''}${cascadeStr})\n`;
|
|
93
106
|
if (!bindingFieldExists) {
|
|
94
107
|
const relatedFieldMeta = relatedModelMetadatas[relatedToField];
|
|
95
108
|
if (!relatedFieldMeta.metadata.required) {
|
|
@@ -131,8 +144,11 @@ datasource db {
|
|
|
131
144
|
const relationKey = [relatedModelName, modelName].join('_');
|
|
132
145
|
const relationIndex = relation_manager_1.RelationManager.getRelationCounter(relationKey, true);
|
|
133
146
|
const relationName = relation_manager_1.RelationManager.getShortenedRelationName(relatedModelName, modelName, relationIndex);
|
|
134
|
-
|
|
135
|
-
|
|
147
|
+
let relationTag = '';
|
|
148
|
+
if (relationMeta.relationName) {
|
|
149
|
+
relationTag = ` @relation("${relationMeta.relationName}")`;
|
|
150
|
+
}
|
|
151
|
+
section += `\t${key} ${relationMeta.inversionModel._collection}[]${relationTag}\n`;
|
|
136
152
|
relation_manager_1.RelationManager.completeRelation(relationKey, relationIndex, true);
|
|
137
153
|
}
|
|
138
154
|
else if (annotationType === 'InverseTimeSeries') {
|
|
@@ -151,10 +167,16 @@ datasource db {
|
|
|
151
167
|
section += `\t${key} String[]\n`;
|
|
152
168
|
}
|
|
153
169
|
}
|
|
154
|
-
else
|
|
170
|
+
else {
|
|
155
171
|
const trackMeta = modelMetadata;
|
|
156
|
-
const
|
|
157
|
-
|
|
172
|
+
const trackTags = trackMeta.tags || [];
|
|
173
|
+
const tags = trackTags.map((item) => '@' + item);
|
|
174
|
+
const isNoIdBehavior = model._NO_ID || idFieldName;
|
|
175
|
+
const isOverrideBehavior = (hasIdType && annotationType === 'IdType' && key === 'id' && idFieldName === 'id')
|
|
176
|
+
||
|
|
177
|
+
(model._NO_ID && model._SUPER_TAGS.some(a => a.fields.includes('id')) && key === 'id');
|
|
178
|
+
if (key === 'id' &&
|
|
179
|
+
isNoIdBehavior && !isOverrideBehavior) {
|
|
158
180
|
continue;
|
|
159
181
|
}
|
|
160
182
|
if (trackMeta.unique) {
|
|
@@ -173,7 +195,17 @@ datasource db {
|
|
|
173
195
|
// Process any database-specific options from the metadata
|
|
174
196
|
const dbSpecificTags = type_converter_1.TypeConverter.processTypeOptions(trackMeta, dbType);
|
|
175
197
|
tags.push(...dbSpecificTags);
|
|
176
|
-
|
|
198
|
+
const isIdTypeField = modelMetadatas[key].annotationType === 'IdType';
|
|
199
|
+
const fieldInUniqueSuperTag = model._SUPER_TAGS.some(st => st.tagType === 'unique' && st.fields.includes(key));
|
|
200
|
+
if (isIdTypeField) {
|
|
201
|
+
requiredString = '';
|
|
202
|
+
}
|
|
203
|
+
let trackField = `${key} ${type_converter_1.TypeConverter.toConfigCase(trackMeta, dbType, key === 'id', isOverrideBehavior)}${requiredString} ${tags.join(' ')}`;
|
|
204
|
+
if (isIdTypeField) {
|
|
205
|
+
trackField += utils_1.DbUtils.addIdPart(dbType, utils_1.DbUtils.doesUseUuid(modelMetadatas), trackMeta.noAuto);
|
|
206
|
+
idGenerated = true;
|
|
207
|
+
}
|
|
208
|
+
section += `\t${trackField}\n`;
|
|
177
209
|
}
|
|
178
210
|
}
|
|
179
211
|
if (model._SUPER_TAGS.length) {
|
|
@@ -250,11 +282,11 @@ datasource db {
|
|
|
250
282
|
fs_1.default.unlinkSync(schemaPath);
|
|
251
283
|
}
|
|
252
284
|
fs_1.default.writeFileSync(schemaPath, template);
|
|
253
|
-
|
|
254
|
-
|
|
285
|
+
if (_EXECUTE_PRISMA_CMD)
|
|
286
|
+
await console_1.rwsShell.runCommand(`${utils_1.DbUtils.detectInstaller()} prisma generate --schema=${schemaPath}`, process.cwd());
|
|
255
287
|
console.log(chalk_1.default.green('[RWS Init]') + ' prisma schema generated from ', schemaPath);
|
|
256
|
-
if (
|
|
257
|
-
|
|
288
|
+
if (_REMOVE_SCHEMA_FILE) {
|
|
289
|
+
fs_1.default.unlinkSync(schemaPath);
|
|
258
290
|
}
|
|
259
291
|
}
|
|
260
292
|
}
|
|
@@ -266,9 +298,8 @@ datasource db {
|
|
|
266
298
|
*/
|
|
267
299
|
static async pushDBModels(configService, dbService, leaveFile = false) {
|
|
268
300
|
process.env = { ...process.env, [this.dbUrlVarName]: configService.get('db_url') };
|
|
269
|
-
const [_, schemaPath] = utils_1.DbUtils.
|
|
301
|
+
const [_, schemaPath] = utils_1.DbUtils.getProcessedSchemaDir();
|
|
270
302
|
await console_1.rwsShell.runCommand(`${utils_1.DbUtils.detectInstaller()} prisma db push --schema=${schemaPath}`, process.cwd());
|
|
271
303
|
}
|
|
272
304
|
}
|
|
273
305
|
exports.SchemaGenerator = SchemaGenerator;
|
|
274
|
-
SchemaGenerator.dbUrlVarName = 'PRISMA_DB_URL';
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { IDbOpts } from '../../models/interfaces/IDbOpts';
|
|
2
2
|
import { ITrackerMetaOpts } from '../../models/_model';
|
|
3
3
|
import { IIdMetaOpts } from 'src/decorators/IdType';
|
|
4
|
+
import { IDbConfigParams } from 'src/types/DbConfigHandler';
|
|
4
5
|
/**
|
|
5
6
|
* Handles type conversion for database schema generation
|
|
6
7
|
*/
|
|
@@ -8,7 +9,7 @@ export declare class TypeConverter {
|
|
|
8
9
|
/**
|
|
9
10
|
* Convert a JavaScript type to a Prisma schema type
|
|
10
11
|
*/
|
|
11
|
-
static toConfigCase(modelType: ITrackerMetaOpts | IIdMetaOpts, dbType?:
|
|
12
|
+
static toConfigCase(modelType: ITrackerMetaOpts | IIdMetaOpts, dbType?: IDbConfigParams['db_type'], isId?: boolean, isIdOverride?: boolean): string;
|
|
12
13
|
/**
|
|
13
14
|
* Process type functions metadata to extract database-specific options
|
|
14
15
|
* @param metadata The metadata from a type function
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.TypeConverter = void 0;
|
|
4
|
+
const utils_1 = require("./utils");
|
|
4
5
|
/**
|
|
5
6
|
* Handles type conversion for database schema generation
|
|
6
7
|
*/
|
|
@@ -8,7 +9,7 @@ class TypeConverter {
|
|
|
8
9
|
/**
|
|
9
10
|
* Convert a JavaScript type to a Prisma schema type
|
|
10
11
|
*/
|
|
11
|
-
static toConfigCase(modelType, dbType = 'mongodb', isId = false) {
|
|
12
|
+
static toConfigCase(modelType, dbType = 'mongodb', isId = false, isIdOverride = false) {
|
|
12
13
|
const type = modelType.type;
|
|
13
14
|
let input = type.name;
|
|
14
15
|
// Handle basic types
|
|
@@ -30,6 +31,9 @@ class TypeConverter {
|
|
|
30
31
|
input = 'Int';
|
|
31
32
|
}
|
|
32
33
|
}
|
|
34
|
+
if (input == 'BigInt') {
|
|
35
|
+
input = 'BigInt';
|
|
36
|
+
}
|
|
33
37
|
if (input == 'Object') {
|
|
34
38
|
input = 'Json';
|
|
35
39
|
}
|
|
@@ -53,8 +57,8 @@ class TypeConverter {
|
|
|
53
57
|
const firstChar = input.charAt(0).toUpperCase();
|
|
54
58
|
const restOfString = input.slice(1);
|
|
55
59
|
let resultField = firstChar + restOfString;
|
|
56
|
-
if (isId) {
|
|
57
|
-
return dbType
|
|
60
|
+
if (isId && !isIdOverride) {
|
|
61
|
+
return utils_1.DbUtils.getDefaultPrismaType(dbType, false);
|
|
58
62
|
}
|
|
59
63
|
const trackerModelType = modelType;
|
|
60
64
|
if (trackerModelType.isArray) {
|
|
@@ -81,7 +85,6 @@ class TypeConverter {
|
|
|
81
85
|
* @returns Array of tags to apply to the field
|
|
82
86
|
*/
|
|
83
87
|
static processTypeOptions(metadata, dbType) {
|
|
84
|
-
var _a, _b, _c, _d;
|
|
85
88
|
const tags = [...(metadata.tags || [])];
|
|
86
89
|
// Extract any database-specific options from the metadata
|
|
87
90
|
// and convert them to appropriate Prisma schema tags
|
|
@@ -91,7 +94,7 @@ class TypeConverter {
|
|
|
91
94
|
let tag = null;
|
|
92
95
|
if (metadata.dbOptions.mysql.useType && !metadata.dbOptions.mysql.useText) {
|
|
93
96
|
const tagName = metadata.dbOptions.mysql.useType === 'VarChar' ? 'db.' + metadata.dbOptions.mysql.useType : metadata.dbOptions.mysql.useType;
|
|
94
|
-
let tagParams = tagName === 'db.VarChar' && metadata.dbOptions.mysql.maxLength ? metadata.dbOptions.mysql.maxLength : (
|
|
97
|
+
let tagParams = tagName === 'db.VarChar' && metadata.dbOptions.mysql.maxLength ? metadata.dbOptions.mysql.maxLength : (metadata.dbOptions.mysql?.params?.join(', ') || '');
|
|
95
98
|
tag = `@${tagName}(${tagParams})`;
|
|
96
99
|
}
|
|
97
100
|
if (metadata.dbOptions.mysql.useText) {
|
|
@@ -100,7 +103,7 @@ class TypeConverter {
|
|
|
100
103
|
if (tag) {
|
|
101
104
|
tags.push(tag);
|
|
102
105
|
}
|
|
103
|
-
if (metadata.dbOptions.mysql.useUuid &&
|
|
106
|
+
if (metadata.dbOptions.mysql.useUuid && metadata.tags?.includes('id')) {
|
|
104
107
|
tags.push('default(uuid())');
|
|
105
108
|
}
|
|
106
109
|
}
|
|
@@ -109,7 +112,7 @@ class TypeConverter {
|
|
|
109
112
|
if (metadata.dbOptions.postgres.useText) {
|
|
110
113
|
tags.push('@db.Text');
|
|
111
114
|
}
|
|
112
|
-
if (metadata.dbOptions.postgres.useUuid &&
|
|
115
|
+
if (metadata.dbOptions.postgres.useUuid && metadata.tags?.includes('id')) {
|
|
113
116
|
tags.push('@default(uuid())');
|
|
114
117
|
tags.push('@db.Uuid');
|
|
115
118
|
}
|
|
@@ -8,6 +8,7 @@ export declare class DbUtils {
|
|
|
8
8
|
* Get the directory and path for the Prisma schema file
|
|
9
9
|
*/
|
|
10
10
|
static getSchemaDir(): [string, string];
|
|
11
|
+
static getProcessedSchemaDir(): [string, string];
|
|
11
12
|
/**
|
|
12
13
|
* Detect the package installer (yarn or npx)
|
|
13
14
|
*/
|
|
@@ -19,6 +20,13 @@ export declare class DbUtils {
|
|
|
19
20
|
annotationType: string;
|
|
20
21
|
metadata: IIdMetaOpts;
|
|
21
22
|
}>, optional?: boolean): string;
|
|
23
|
+
static getDefaultPrismaType(dbType: IDbConfigParams['db_type'], useUuid: boolean): string;
|
|
24
|
+
static doesUseUuid(modelMeta: Record<string, {
|
|
25
|
+
annotationType: string;
|
|
26
|
+
metadata: IIdMetaOpts;
|
|
27
|
+
}>): boolean;
|
|
28
|
+
static addIdPart(dbType: IDbConfigParams['db_type'], useUuid: boolean, noAuto?: boolean): string;
|
|
29
|
+
static generateIdDefault(dbType: IDbConfigParams['db_type'], useUuid: boolean): string;
|
|
22
30
|
}
|
|
23
31
|
export declare const workspaceRootPath: string;
|
|
24
32
|
export declare const moduleDirPath: string;
|
package/dist/helper/db/utils.js
CHANGED
|
@@ -22,6 +22,11 @@ class DbUtils {
|
|
|
22
22
|
const schemaPath = path_1.default.join(schemaDir, 'schema.prisma');
|
|
23
23
|
return [schemaDir, schemaPath];
|
|
24
24
|
}
|
|
25
|
+
static getProcessedSchemaDir() {
|
|
26
|
+
const schemaDir = path_1.default.join(workspaceRoot, 'node_modules', '.prisma', 'client');
|
|
27
|
+
const schemaPath = path_1.default.join(schemaDir, 'schema.prisma');
|
|
28
|
+
return [schemaDir, schemaPath];
|
|
29
|
+
}
|
|
25
30
|
/**
|
|
26
31
|
* Detect the package installer (yarn or npx)
|
|
27
32
|
*/
|
|
@@ -35,8 +40,7 @@ class DbUtils {
|
|
|
35
40
|
* Generate an ID field based on the database type
|
|
36
41
|
*/
|
|
37
42
|
static generateId(dbType, modelMeta, optional = false) {
|
|
38
|
-
|
|
39
|
-
let useUuid = false;
|
|
43
|
+
let useUuid = this.doesUseUuid(modelMeta);
|
|
40
44
|
let field = 'id';
|
|
41
45
|
const tags = [];
|
|
42
46
|
for (const key in modelMeta) {
|
|
@@ -47,50 +51,105 @@ class DbUtils {
|
|
|
47
51
|
const dbSpecificTags = type_converter_1.TypeConverter.processTypeOptions({ tags: [], dbOptions: modelMetadata.dbOptions }, dbType);
|
|
48
52
|
tags.push(...dbSpecificTags);
|
|
49
53
|
field = key;
|
|
50
|
-
if ((_b = (_a = modelMetadata.dbOptions) === null || _a === void 0 ? void 0 : _a.mysql) === null || _b === void 0 ? void 0 : _b.useUuid) {
|
|
51
|
-
useUuid = true;
|
|
52
|
-
}
|
|
53
|
-
if ((_d = (_c = modelMetadata.dbOptions) === null || _c === void 0 ? void 0 : _c.postgres) === null || _d === void 0 ? void 0 : _d.useUuid) {
|
|
54
|
-
useUuid = true;
|
|
55
|
-
}
|
|
56
|
-
if (modelMetadata.type.name === 'String') {
|
|
57
|
-
useUuid = true;
|
|
58
|
-
}
|
|
59
54
|
}
|
|
60
55
|
}
|
|
61
56
|
}
|
|
62
|
-
|
|
57
|
+
const idPrismaType = this.getDefaultPrismaType(dbType, useUuid);
|
|
63
58
|
let reqStr = '';
|
|
64
59
|
if (optional) {
|
|
65
60
|
reqStr = '?';
|
|
66
61
|
}
|
|
62
|
+
let idString = `${field} ${idPrismaType}${reqStr}`;
|
|
63
|
+
idString += this.addIdPart(dbType, useUuid, modelMeta[field].metadata.noAuto);
|
|
64
|
+
if (dbType === 'mongodb') {
|
|
65
|
+
tags.push('@map("_id")');
|
|
66
|
+
tags.push('@db.ObjectId');
|
|
67
|
+
}
|
|
68
|
+
if (tags.length) {
|
|
69
|
+
idString += ' ' + tags.join(' ');
|
|
70
|
+
}
|
|
71
|
+
if (!idString) {
|
|
72
|
+
throw new Error(`DB type "${dbType}" is not supported!`);
|
|
73
|
+
}
|
|
74
|
+
return idString;
|
|
75
|
+
}
|
|
76
|
+
static getDefaultPrismaType(dbType, useUuid) {
|
|
77
|
+
let idPrismaType = 'String';
|
|
67
78
|
switch (dbType) {
|
|
68
|
-
case 'mongodb':
|
|
69
|
-
idString = `${field} String${reqStr} @id @default(auto()) @map("_id") @db.ObjectId`;
|
|
70
|
-
break;
|
|
71
79
|
case 'mysql':
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
80
|
+
if (useUuid) {
|
|
81
|
+
idPrismaType = 'String';
|
|
82
|
+
}
|
|
83
|
+
else {
|
|
84
|
+
idPrismaType = 'Int';
|
|
85
|
+
}
|
|
75
86
|
break;
|
|
76
87
|
case 'postgresql':
|
|
77
88
|
case 'postgres':
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
89
|
+
if (useUuid) {
|
|
90
|
+
idPrismaType = 'String';
|
|
91
|
+
}
|
|
92
|
+
else {
|
|
93
|
+
idPrismaType = 'Int';
|
|
94
|
+
}
|
|
81
95
|
break;
|
|
82
96
|
case 'sqlite':
|
|
83
|
-
|
|
97
|
+
if (useUuid) {
|
|
98
|
+
idPrismaType = 'String';
|
|
99
|
+
}
|
|
100
|
+
else {
|
|
101
|
+
idPrismaType = 'Int';
|
|
102
|
+
}
|
|
84
103
|
break;
|
|
85
104
|
}
|
|
86
|
-
|
|
87
|
-
|
|
105
|
+
return idPrismaType;
|
|
106
|
+
}
|
|
107
|
+
static doesUseUuid(modelMeta) {
|
|
108
|
+
let useUuid = false;
|
|
109
|
+
for (const key in modelMeta) {
|
|
110
|
+
const modelMetadata = modelMeta[key].metadata;
|
|
111
|
+
const annotationType = modelMeta[key].annotationType;
|
|
112
|
+
if (key !== 'id') {
|
|
113
|
+
if (annotationType == 'IdType') {
|
|
114
|
+
if (modelMetadata.dbOptions?.mysql?.useUuid) {
|
|
115
|
+
useUuid = true;
|
|
116
|
+
}
|
|
117
|
+
if (modelMetadata.dbOptions?.postgres?.useUuid) {
|
|
118
|
+
useUuid = true;
|
|
119
|
+
}
|
|
120
|
+
if (modelMetadata.type.name === 'String') {
|
|
121
|
+
useUuid = true;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
88
125
|
}
|
|
89
|
-
|
|
90
|
-
|
|
126
|
+
return useUuid;
|
|
127
|
+
}
|
|
128
|
+
static addIdPart(dbType, useUuid, noAuto = false) {
|
|
129
|
+
let idString = ` @id${!noAuto ? ` @default(${this.generateIdDefault(dbType, useUuid)})` : ''}`;
|
|
130
|
+
if (dbType === 'mongodb') {
|
|
131
|
+
idString += ' @map("_id")';
|
|
132
|
+
idString += ' @db.ObjectId';
|
|
91
133
|
}
|
|
92
134
|
return idString;
|
|
93
135
|
}
|
|
136
|
+
static generateIdDefault(dbType, useUuid) {
|
|
137
|
+
switch (dbType) {
|
|
138
|
+
case 'mongodb':
|
|
139
|
+
return `auto()`;
|
|
140
|
+
case 'mysql':
|
|
141
|
+
return useUuid
|
|
142
|
+
? `uuid()`
|
|
143
|
+
: `autoincrement()`;
|
|
144
|
+
case 'postgresql':
|
|
145
|
+
case 'postgres':
|
|
146
|
+
return useUuid
|
|
147
|
+
? `uuid()`
|
|
148
|
+
: `autoincrement()`;
|
|
149
|
+
case 'sqlite':
|
|
150
|
+
return 'autoincrement()';
|
|
151
|
+
}
|
|
152
|
+
}
|
|
94
153
|
}
|
|
95
154
|
exports.DbUtils = DbUtils;
|
|
96
155
|
exports.workspaceRootPath = workspaceRoot;
|
|
@@ -17,6 +17,15 @@ const TimeSeriesUtils_1 = require("../utils/TimeSeriesUtils");
|
|
|
17
17
|
const ModelUtils_1 = require("../utils/ModelUtils");
|
|
18
18
|
const HydrateUtils_1 = require("../utils/HydrateUtils");
|
|
19
19
|
class RWSModel {
|
|
20
|
+
static services = {};
|
|
21
|
+
id;
|
|
22
|
+
static _collection = null;
|
|
23
|
+
static _RELATIONS = {};
|
|
24
|
+
static _NO_ID = false;
|
|
25
|
+
static _SUPER_TAGS = [];
|
|
26
|
+
static _BANNED_KEYS = ['_collection'];
|
|
27
|
+
static allModels = [];
|
|
28
|
+
static _CUT_KEYS = [];
|
|
20
29
|
constructor(data = null) {
|
|
21
30
|
if (!this.getCollection()) {
|
|
22
31
|
throw new Error('Model must have a collection defined');
|
|
@@ -110,12 +119,11 @@ class RWSModel {
|
|
|
110
119
|
return RelationUtils_1.RelationUtils.getRelationManyMeta(model, classFields);
|
|
111
120
|
}
|
|
112
121
|
static async paginate(paginateParams, findParams) {
|
|
113
|
-
|
|
114
|
-
const
|
|
115
|
-
const
|
|
116
|
-
const
|
|
117
|
-
const
|
|
118
|
-
const fullData = (_e = findParams === null || findParams === void 0 ? void 0 : findParams.fullData) !== null && _e !== void 0 ? _e : false;
|
|
122
|
+
const conditions = findParams?.conditions ?? {};
|
|
123
|
+
const ordering = findParams?.ordering ?? null;
|
|
124
|
+
const fields = findParams?.fields ?? null;
|
|
125
|
+
const allowRelations = findParams?.allowRelations ?? true;
|
|
126
|
+
const fullData = findParams?.fullData ?? false;
|
|
119
127
|
const collection = Reflect.get(this, '_collection');
|
|
120
128
|
this.checkForInclusionWithThrow(this.name);
|
|
121
129
|
try {
|
|
@@ -231,12 +239,11 @@ class RWSModel {
|
|
|
231
239
|
return await this.services.dbService.watchCollection(collection, preRun);
|
|
232
240
|
}
|
|
233
241
|
static async findOneBy(findParams) {
|
|
234
|
-
|
|
235
|
-
const
|
|
236
|
-
const
|
|
237
|
-
const
|
|
238
|
-
const
|
|
239
|
-
const fullData = (_e = findParams === null || findParams === void 0 ? void 0 : findParams.fullData) !== null && _e !== void 0 ? _e : false;
|
|
242
|
+
const conditions = findParams?.conditions ?? {};
|
|
243
|
+
const ordering = findParams?.ordering ?? null;
|
|
244
|
+
const fields = findParams?.fields ?? null;
|
|
245
|
+
const allowRelations = findParams?.allowRelations ?? true;
|
|
246
|
+
const fullData = findParams?.fullData ?? false;
|
|
240
247
|
this.checkForInclusionWithThrow('');
|
|
241
248
|
const collection = Reflect.get(this, '_collection');
|
|
242
249
|
const dbData = await this.services.dbService.findOneBy(collection, conditions, fields, ordering, allowRelations);
|
|
@@ -247,11 +254,10 @@ class RWSModel {
|
|
|
247
254
|
return null;
|
|
248
255
|
}
|
|
249
256
|
static async find(id, findParams = null) {
|
|
250
|
-
|
|
251
|
-
const
|
|
252
|
-
const
|
|
253
|
-
const
|
|
254
|
-
const fullData = (_d = findParams === null || findParams === void 0 ? void 0 : findParams.fullData) !== null && _d !== void 0 ? _d : false;
|
|
257
|
+
const ordering = findParams?.ordering ?? null;
|
|
258
|
+
const fields = findParams?.fields ?? null;
|
|
259
|
+
const allowRelations = findParams?.allowRelations ?? true;
|
|
260
|
+
const fullData = findParams?.fullData ?? false;
|
|
255
261
|
const collection = Reflect.get(this, '_collection');
|
|
256
262
|
this.checkForInclusionWithThrow(this.name);
|
|
257
263
|
const dbData = await this.services.dbService.findOneBy(collection, { id }, fields, ordering, allowRelations);
|
|
@@ -262,16 +268,15 @@ class RWSModel {
|
|
|
262
268
|
return null;
|
|
263
269
|
}
|
|
264
270
|
static async findBy(findParams) {
|
|
265
|
-
|
|
266
|
-
const
|
|
267
|
-
const
|
|
268
|
-
const
|
|
269
|
-
const
|
|
270
|
-
const fullData = (_e = findParams === null || findParams === void 0 ? void 0 : findParams.fullData) !== null && _e !== void 0 ? _e : false;
|
|
271
|
+
const conditions = findParams?.conditions ?? {};
|
|
272
|
+
const ordering = findParams?.ordering ?? null;
|
|
273
|
+
const fields = findParams?.fields ?? null;
|
|
274
|
+
const allowRelations = findParams?.allowRelations ?? true;
|
|
275
|
+
const fullData = findParams?.fullData ?? false;
|
|
271
276
|
const collection = Reflect.get(this, '_collection');
|
|
272
277
|
this.checkForInclusionWithThrow(this.name);
|
|
273
278
|
try {
|
|
274
|
-
const paginateParams =
|
|
279
|
+
const paginateParams = findParams?.pagination ? findParams?.pagination : undefined;
|
|
275
280
|
const dbData = await this.services.dbService.findBy(collection, conditions, fields, ordering, paginateParams);
|
|
276
281
|
if (dbData.length) {
|
|
277
282
|
const instanced = [];
|
|
@@ -327,14 +332,6 @@ class RWSModel {
|
|
|
327
332
|
}
|
|
328
333
|
}
|
|
329
334
|
exports.RWSModel = RWSModel;
|
|
330
|
-
RWSModel.services = {};
|
|
331
|
-
RWSModel._collection = null;
|
|
332
|
-
RWSModel._RELATIONS = {};
|
|
333
|
-
RWSModel._NO_ID = false;
|
|
334
|
-
RWSModel._SUPER_TAGS = [];
|
|
335
|
-
RWSModel._BANNED_KEYS = ['_collection'];
|
|
336
|
-
RWSModel.allModels = [];
|
|
337
|
-
RWSModel._CUT_KEYS = [];
|
|
338
335
|
__decorate([
|
|
339
336
|
(0, decorators_1.TrackType)(String),
|
|
340
337
|
__metadata("design:type", Object)
|