@rws-framework/db 2.4.6 → 3.0.0

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.
Files changed (123) hide show
  1. package/.bin/add-v.sh +9 -9
  2. package/.bin/emerge.sh +10 -10
  3. package/.eslintrc.json +53 -53
  4. package/README.md +404 -404
  5. package/dist/decorators/IdType.d.ts +8 -0
  6. package/dist/decorators/IdType.js +10 -0
  7. package/dist/decorators/InverseRelation.d.ts +2 -2
  8. package/dist/decorators/InverseRelation.js +5 -1
  9. package/dist/decorators/InverseTimeSeries.d.ts +0 -0
  10. package/dist/decorators/InverseTimeSeries.js +0 -0
  11. package/dist/decorators/RWSCollection.d.ts +7 -0
  12. package/dist/decorators/RWSCollection.js +6 -0
  13. package/dist/decorators/Relation.d.ts +8 -6
  14. package/dist/decorators/Relation.js +8 -1
  15. package/dist/decorators/TrackType.d.ts +2 -14
  16. package/dist/decorators/TrackType.js +7 -0
  17. package/dist/decorators/TypeFunctions.d.ts +44 -0
  18. package/dist/decorators/TypeFunctions.js +174 -0
  19. package/dist/decorators/index.d.ts +4 -2
  20. package/dist/decorators/index.js +3 -1
  21. package/dist/helper/DbHelper.d.ts +76 -5
  22. package/dist/helper/DbHelper.js +93 -154
  23. package/dist/helper/FieldsHelper.d.ts +0 -0
  24. package/dist/helper/FieldsHelper.js +0 -0
  25. package/dist/helper/db/index.d.ts +9 -0
  26. package/dist/helper/db/index.js +18 -0
  27. package/dist/helper/db/relation-manager.d.ts +45 -0
  28. package/dist/helper/db/relation-manager.js +105 -0
  29. package/dist/helper/db/schema-generator.d.ts +37 -0
  30. package/dist/helper/db/schema-generator.js +243 -0
  31. package/dist/helper/db/type-converter.d.ts +22 -0
  32. package/dist/helper/db/type-converter.js +106 -0
  33. package/dist/helper/db/utils.d.ts +24 -0
  34. package/dist/helper/db/utils.js +99 -0
  35. package/dist/index.d.ts +3 -3
  36. package/dist/index.js +2 -1
  37. package/dist/models/TimeSeriesModel.d.ts +7 -7
  38. package/dist/models/TimeSeriesModel.js +33 -33
  39. package/dist/models/_model.d.ts +2 -2
  40. package/dist/models/_model.js +0 -0
  41. package/dist/models/core/RWSModel.d.ts +4 -1
  42. package/dist/models/core/RWSModel.js +6 -4
  43. package/dist/models/core/TimeSeriesModel.d.ts +0 -0
  44. package/dist/models/core/TimeSeriesModel.js +0 -0
  45. package/dist/models/index.d.ts +2 -2
  46. package/dist/models/index.js +0 -0
  47. package/dist/models/interfaces/IDbOpts.d.ts +17 -0
  48. package/dist/models/interfaces/IDbOpts.js +2 -0
  49. package/dist/models/interfaces/IIdOpts.d.ts +0 -0
  50. package/dist/models/interfaces/IIdOpts.js +1 -0
  51. package/dist/models/interfaces/IIdTypeOpts.d.ts +3 -0
  52. package/dist/models/interfaces/IIdTypeOpts.js +2 -0
  53. package/dist/models/interfaces/IModel.d.ts +0 -0
  54. package/dist/models/interfaces/IModel.js +0 -0
  55. package/dist/models/interfaces/IRWSModelServices.d.ts +0 -0
  56. package/dist/models/interfaces/IRWSModelServices.js +0 -0
  57. package/dist/models/interfaces/ITrackerOpts.d.ts +12 -0
  58. package/dist/models/interfaces/ITrackerOpts.js +2 -0
  59. package/dist/models/interfaces/OpModelType.d.ts +3 -0
  60. package/dist/models/interfaces/OpModelType.js +0 -0
  61. package/dist/models/types/RelationTypes.d.ts +0 -0
  62. package/dist/models/types/RelationTypes.js +0 -0
  63. package/dist/models/utils/ModelUtils.d.ts +0 -0
  64. package/dist/models/utils/ModelUtils.js +0 -0
  65. package/dist/models/utils/PaginationUtils.d.ts +0 -0
  66. package/dist/models/utils/PaginationUtils.js +0 -0
  67. package/dist/models/utils/RelationUtils.d.ts +1 -1
  68. package/dist/models/utils/RelationUtils.js +2 -2
  69. package/dist/models/utils/TimeSeriesUtils.d.ts +0 -0
  70. package/dist/models/utils/TimeSeriesUtils.js +0 -0
  71. package/dist/services/DBService.d.ts +0 -0
  72. package/dist/services/DBService.js +0 -0
  73. package/dist/types/DbConfigHandler.d.ts +1 -1
  74. package/dist/types/DbConfigHandler.js +0 -0
  75. package/dist/types/FindParams.d.ts +0 -0
  76. package/dist/types/FindParams.js +0 -0
  77. package/dist/types/IRWSModel.d.ts +1 -1
  78. package/dist/types/IRWSModel.js +0 -0
  79. package/dist/types/ITimeSeries.d.ts +0 -0
  80. package/dist/types/ITimeSeries.js +0 -0
  81. package/exec/console.js +110 -110
  82. package/exec/db.rws.webpack.config.js +168 -168
  83. package/exec/src/cli.ts +73 -75
  84. package/exec/tsconfig.json +32 -32
  85. package/exec/webpackFilters.js +17 -17
  86. package/package.json +36 -36
  87. package/src/decorators/IdType.ts +17 -0
  88. package/src/decorators/InverseRelation.ts +41 -37
  89. package/src/decorators/InverseTimeSeries.ts +21 -21
  90. package/src/decorators/RWSCollection.ts +45 -27
  91. package/src/decorators/Relation.ts +61 -48
  92. package/src/decorators/TrackType.ts +65 -69
  93. package/src/decorators/index.ts +16 -8
  94. package/src/empty.js +0 -0
  95. package/src/helper/DbHelper.ts +133 -223
  96. package/src/helper/FieldsHelper.ts +34 -34
  97. package/src/helper/db/index.ts +10 -0
  98. package/src/helper/db/relation-manager.ts +119 -0
  99. package/src/helper/db/schema-generator.ts +302 -0
  100. package/src/helper/db/type-converter.ts +119 -0
  101. package/src/helper/db/utils.ts +120 -0
  102. package/src/index.ts +47 -38
  103. package/src/models/_model.ts +29 -29
  104. package/src/models/core/RWSModel.ts +523 -520
  105. package/src/models/core/TimeSeriesModel.ts +19 -19
  106. package/src/models/index.ts +20 -20
  107. package/src/models/interfaces/IDbOpts.ts +17 -0
  108. package/src/models/interfaces/IIdTypeOpts.ts +4 -0
  109. package/src/models/interfaces/IModel.ts +12 -12
  110. package/src/models/interfaces/IRWSModelServices.ts +7 -7
  111. package/src/models/interfaces/ITrackerOpts.ts +13 -0
  112. package/src/models/interfaces/OpModelType.ts +52 -49
  113. package/src/models/types/RelationTypes.ts +25 -25
  114. package/src/models/utils/ModelUtils.ts +65 -65
  115. package/src/models/utils/PaginationUtils.ts +42 -42
  116. package/src/models/utils/RelationUtils.ts +76 -76
  117. package/src/models/utils/TimeSeriesUtils.ts +38 -38
  118. package/src/services/DBService.ts +277 -277
  119. package/src/types/DbConfigHandler.ts +17 -17
  120. package/src/types/FindParams.ts +13 -13
  121. package/src/types/IRWSModel.ts +2 -2
  122. package/src/types/ITimeSeries.ts +5 -5
  123. package/tsconfig.json +22 -22
@@ -1,168 +1,107 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
3
  exports.DbHelper = void 0;
7
- const console_1 = require("@rws-framework/console");
8
- const chalk_1 = __importDefault(require("chalk"));
9
- const path_1 = __importDefault(require("path"));
10
- const fs_1 = __importDefault(require("fs"));
11
- const _model_1 = require("../models/_model");
12
- const log = console.log;
13
- const workspaceRoot = console_1.rwsPath.findRootWorkspacePath();
14
- const moduleDir = path_1.default.resolve(workspaceRoot, 'node_modules', '@rws-framework', 'db');
4
+ const db_1 = require("./db");
5
+ /**
6
+ * Database helper class
7
+ *
8
+ * This class provides a facade for the database helper modules.
9
+ * It delegates to the specialized modules for specific functionality.
10
+ */
15
11
  class DbHelper {
12
+ /**
13
+ * Install Prisma with the generated schema
14
+ * @param configService The configuration service
15
+ * @param dbService The database service
16
+ * @param leaveFile Whether to leave the schema file after generation
17
+ */
16
18
  static async installPrisma(configService, dbService, leaveFile = false) {
17
- const dbUrl = configService.get('db_url');
18
- const dbType = configService.get('db_type') || 'mongodb';
19
- let template = `generator client {\n
20
- provider = "prisma-client-js"\n
21
- }\n\n`;
22
- template += `\ndatasource db {\n
23
- provider = "${dbType}"\n
24
- url = env("${this.dbUrlVarName}")\n
25
- }\n\n`;
26
- const dbModels = configService.get('db_models');
27
- if (dbModels) {
28
- for (const model of dbModels) {
29
- const modelSection = await DbHelper.generateModelSections(model, configService);
30
- template += '\n\n' + modelSection;
31
- log(chalk_1.default.green('[RWS]'), chalk_1.default.blue('Building DB Model'), model.name);
32
- // if(RWSModel.isSubclass(model as any, TimeSeriesModel)){
33
- // dbService.collectionExists(model._collection).then((exists: boolean) => {
34
- // if (exists){
35
- // return;
36
- // }
37
- // log(chalk.green('[RWS Init]') + ` creating TimeSeries type collection from ${model} model`);
38
- // dbService.createTimeSeriesCollection(model._collection);
39
- // });
40
- // }
41
- }
42
- const schemaDir = path_1.default.join(moduleDir, 'prisma');
43
- const schemaPath = path_1.default.join(schemaDir, 'schema.prisma');
44
- if (!fs_1.default.existsSync(schemaDir)) {
45
- fs_1.default.mkdirSync(schemaDir);
46
- }
47
- if (fs_1.default.existsSync(schemaPath)) {
48
- fs_1.default.unlinkSync(schemaPath);
49
- }
50
- fs_1.default.writeFileSync(schemaPath, template);
51
- process.env = { ...process.env, [this.dbUrlVarName]: dbUrl };
52
- await console_1.rwsShell.runCommand(`${this.detectInstaller()} prisma generate --schema="${schemaPath}"`, process.cwd());
53
- leaveFile = false;
54
- log(chalk_1.default.green('[RWS Init]') + ' prisma schema generated from ', schemaPath);
55
- if (!leaveFile) {
56
- fs_1.default.unlinkSync(schemaPath);
57
- }
58
- }
19
+ return db_1.SchemaGenerator.installPrisma(configService, dbService, leaveFile);
59
20
  }
60
- static generateId(dbType, options = {}) {
61
- const { useUuid = false, customType } = options;
62
- if (customType) {
63
- return `id ${customType} @id`;
64
- }
65
- switch (dbType) {
66
- case 'mongodb':
67
- return 'id String @id @default(auto()) @map("_id") @db.ObjectId';
68
- case 'mysql':
69
- return useUuid
70
- ? 'id String @id @default(uuid())'
71
- : 'id Int @id @default(autoincrement())';
72
- case 'sqlite':
73
- return 'id Int @id @default(autoincrement())';
74
- default:
75
- throw new Error('Kurwa, nieobsługiwany typ bazy danych!');
76
- }
21
+ /**
22
+ * Push database models to the database
23
+ * @param configService The configuration service
24
+ * @param dbService The database service
25
+ * @param leaveFile Whether to leave the schema file after generation
26
+ */
27
+ static async pushDBModels(configService, dbService, leaveFile = false) {
28
+ return db_1.SchemaGenerator.pushDBModels(configService, dbService, leaveFile);
29
+ }
30
+ /**
31
+ * Generate model sections for the schema
32
+ * @param model The model to generate a section for
33
+ * @param configService The configuration service
34
+ * @returns The model section
35
+ */
36
+ static async generateModelSections(model, configService) {
37
+ return db_1.SchemaGenerator.generateModelSections(model, configService);
77
38
  }
39
+ /**
40
+ * Generate the base schema for Prisma
41
+ * @param dbType The database type
42
+ * @param dbUrl The database URL
43
+ * @returns The base schema
44
+ */
45
+ static generateBaseSchema(dbType, dbUrl) {
46
+ return db_1.SchemaGenerator.generateBaseSchema(dbType, dbUrl);
47
+ }
48
+ /**
49
+ * Get the directory and path for the Prisma schema file
50
+ */
51
+ static getSchemaDir() {
52
+ return db_1.DbUtils.getSchemaDir();
53
+ }
54
+ /**
55
+ * Detect the package installer (yarn or npx)
56
+ */
78
57
  static detectInstaller() {
79
- if (fs_1.default.existsSync(path_1.default.join(workspaceRoot, 'yarn.lock'))) {
80
- return 'yarn';
81
- }
82
- return 'npx';
58
+ return db_1.DbUtils.detectInstaller();
83
59
  }
84
- static async pushDBModels(configService, dbService, leaveFile = false) {
85
- process.env = { ...process.env, [this.dbUrlVarName]: configService.get('db_url') };
86
- const schemaPath = path_1.default.join(workspaceRoot, 'node_modules', '.prisma', 'client', 'schema.prisma');
87
- await console_1.rwsShell.runCommand(`${this.detectInstaller()} prisma db push --schema="${schemaPath}"`, process.cwd());
60
+ /**
61
+ * Generate an ID field based on the database type
62
+ */
63
+ static generateId(dbType, modelMeta) {
64
+ return db_1.DbUtils.generateId(dbType, modelMeta);
88
65
  }
89
- static async generateModelSections(model, configService) {
90
- var _a, _b;
91
- let section = '';
92
- const modelMetadatas = await _model_1.RWSModel.getModelAnnotations(model);
93
- const modelName = model._collection;
94
- section += `model ${modelName} {\n`;
95
- section += `\t${this.generateId(configService.get('db_type'))}\n`;
96
- for (const key in modelMetadatas) {
97
- const modelMetadata = modelMetadatas[key].metadata;
98
- let requiredString = modelMetadata.required ? '' : '?';
99
- const annotationType = modelMetadatas[key].annotationType;
100
- if (key === 'id') {
101
- continue;
102
- }
103
- if (annotationType === 'Relation') {
104
- const relationMeta = modelMetadata;
105
- const relatedModel = relationMeta.relatedTo;
106
- const isMany = relationMeta.many;
107
- const cascadeOpts = [];
108
- if ((_a = relationMeta.cascade) === null || _a === void 0 ? void 0 : _a.onDelete) {
109
- cascadeOpts.push(`onDelete: ${relationMeta.cascade.onDelete}`);
110
- }
111
- if ((_b = relationMeta.cascade) === null || _b === void 0 ? void 0 : _b.onUpdate) {
112
- cascadeOpts.push(`onUpdate: ${relationMeta.cascade.onUpdate}`);
113
- }
114
- if (isMany) {
115
- // Handle many-to-many or one-to-many relation
116
- section += `\t${key} ${relatedModel._collection}[] @relation("${modelName}_${relatedModel._collection}")\n`;
117
- }
118
- else {
119
- // Handle one-to-one or many-to-one relation
120
- section += `\t${key} ${relatedModel._collection}${requiredString} @relation("${modelName}_${relatedModel._collection}", fields: [${modelMetadata.relationField}], references: [${modelMetadata.relatedToField || 'id'}], ${cascadeOpts.join(', ')})\n`;
121
- section += `\t${modelMetadata.relationField} String${requiredString} @db.ObjectId\n`;
122
- }
123
- }
124
- else if (annotationType === 'InverseRelation') {
125
- const relationMeta = modelMetadata;
126
- // Handle inverse relation (one-to-many or one-to-one)
127
- section += `\t${key} ${relationMeta.inversionModel._collection}[] @relation("${relationMeta.relationName ? relationMeta.relationName : `${relationMeta.inversionModel._collection}_${modelName}`}")\n`;
128
- }
129
- else if (annotationType === 'InverseTimeSeries') {
130
- section += `\t${key} String[] @db.ObjectId\n`;
131
- }
132
- else if (annotationType === 'TrackType') {
133
- const tags = modelMetadata.tags.map((item) => '@' + item);
134
- if (modelMetadata.isArray || modelMetadata.type.name === 'Array') {
135
- requiredString = '';
136
- }
137
- section += `\t${key} ${DbHelper.toConfigCase(modelMetadata)}${requiredString} ${tags.join(' ')}\n`;
138
- }
139
- }
140
- section += '}\n';
141
- return section;
66
+ /**
67
+ * Convert a JavaScript type to a Prisma schema type
68
+ */
69
+ static toConfigCase(modelType, dbType = 'mongodb') {
70
+ return db_1.TypeConverter.toConfigCase(modelType, dbType);
71
+ }
72
+ /**
73
+ * Process type functions metadata to extract database-specific options
74
+ */
75
+ static processTypeOptions(metadata, dbType) {
76
+ return db_1.TypeConverter.processTypeOptions(metadata, dbType);
77
+ }
78
+ /**
79
+ * Mark a relation between two models
80
+ */
81
+ static markRelation(relationKey, inverse = false) {
82
+ db_1.RelationManager.markRelation(relationKey, inverse);
83
+ }
84
+ /**
85
+ * Complete a relation between two models
86
+ */
87
+ static completeRelation(relationKey, index, inverse = false) {
88
+ db_1.RelationManager.completeRelation(relationKey, index, inverse);
89
+ }
90
+ /**
91
+ * Get a unique counter for a relation between two models
92
+ */
93
+ static getRelationCounter(relationKey, inverse = false) {
94
+ return db_1.RelationManager.getRelationCounter(relationKey, inverse);
142
95
  }
143
- static toConfigCase(modelType) {
144
- const type = modelType.type;
145
- let input = type.name;
146
- if (input == 'Number') {
147
- input = 'Int';
148
- }
149
- if (input == 'Object') {
150
- input = 'Json';
151
- }
152
- if (input == 'Date') {
153
- input = 'DateTime';
154
- }
155
- if (input == 'Array') {
156
- input = 'Json[]';
157
- }
158
- const firstChar = input.charAt(0).toUpperCase();
159
- const restOfString = input.slice(1);
160
- let resultField = firstChar + restOfString;
161
- if (modelType.isArray) {
162
- resultField += '[]';
163
- }
164
- return resultField;
96
+ /**
97
+ * Generate a shortened relation name to stay within database limits
98
+ */
99
+ static getShortenedRelationName(modelName, relatedModelName, index) {
100
+ return db_1.RelationManager.getShortenedRelationName(modelName, relatedModelName, index);
165
101
  }
166
102
  }
167
103
  exports.DbHelper = DbHelper;
168
- DbHelper.dbUrlVarName = 'PRISMA_DB_URL';
104
+ /**
105
+ * The environment variable name for the Prisma database URL
106
+ */
107
+ DbHelper.dbUrlVarName = db_1.SchemaGenerator.dbUrlVarName;
File without changes
File without changes
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Database helper modules
3
+ *
4
+ * This module exports all the database helper classes for use in the application.
5
+ */
6
+ export { DbUtils, workspaceRootPath, moduleDirPath } from './utils';
7
+ export { TypeConverter } from './type-converter';
8
+ export { RelationManager } from './relation-manager';
9
+ export { SchemaGenerator } from './schema-generator';
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ /**
3
+ * Database helper modules
4
+ *
5
+ * This module exports all the database helper classes for use in the application.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.SchemaGenerator = exports.RelationManager = exports.TypeConverter = exports.moduleDirPath = exports.workspaceRootPath = exports.DbUtils = void 0;
9
+ var utils_1 = require("./utils");
10
+ Object.defineProperty(exports, "DbUtils", { enumerable: true, get: function () { return utils_1.DbUtils; } });
11
+ Object.defineProperty(exports, "workspaceRootPath", { enumerable: true, get: function () { return utils_1.workspaceRootPath; } });
12
+ Object.defineProperty(exports, "moduleDirPath", { enumerable: true, get: function () { return utils_1.moduleDirPath; } });
13
+ var type_converter_1 = require("./type-converter");
14
+ Object.defineProperty(exports, "TypeConverter", { enumerable: true, get: function () { return type_converter_1.TypeConverter; } });
15
+ var relation_manager_1 = require("./relation-manager");
16
+ Object.defineProperty(exports, "RelationManager", { enumerable: true, get: function () { return relation_manager_1.RelationManager; } });
17
+ var schema_generator_1 = require("./schema-generator");
18
+ Object.defineProperty(exports, "SchemaGenerator", { enumerable: true, get: function () { return schema_generator_1.SchemaGenerator; } });
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Manages database relations for schema generation
3
+ */
4
+ export declare class RelationManager {
5
+ private static allRelations;
6
+ /**
7
+ * Mark a relation between two models
8
+ * @param relationKey A unique key for the relation
9
+ * @param inverse Whether this is an inverse relation
10
+ */
11
+ static markRelation(relationKey: string, inverse?: boolean): void;
12
+ /**
13
+ * Complete a relation between two models
14
+ * @param relationKey A unique key for the relation
15
+ * @param index The index of the relation
16
+ * @param inverse Whether this is an inverse relation
17
+ */
18
+ static completeRelation(relationKey: string, index: number, inverse?: boolean): void;
19
+ /**
20
+ * Get a unique counter for a relation between two models
21
+ * @param relationKey A unique key for the relation
22
+ * @param inverse Whether this is an inverse relation
23
+ * @returns A unique counter for this relation
24
+ */
25
+ static getRelationCounter(relationKey: string, inverse?: boolean): number;
26
+ /**
27
+ * Generate a shortened relation name to stay within database limits
28
+ * @param modelName The name of the model
29
+ * @param relatedModelName The name of the related model
30
+ * @param index The index of the relation
31
+ * @returns A shortened relation name
32
+ */
33
+ static getShortenedRelationName(modelName: string, relatedModelName: string, index: number): string;
34
+ /**
35
+ * Reset all relations (useful for testing)
36
+ */
37
+ static resetRelations(): void;
38
+ /**
39
+ * Get all relations (useful for debugging)
40
+ */
41
+ static getAllRelations(): Map<string, {
42
+ base: boolean | null;
43
+ inversion: boolean | null;
44
+ }[]>;
45
+ }
@@ -0,0 +1,105 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RelationManager = void 0;
4
+ /**
5
+ * Manages database relations for schema generation
6
+ */
7
+ class RelationManager {
8
+ /**
9
+ * Mark a relation between two models
10
+ * @param relationKey A unique key for the relation
11
+ * @param inverse Whether this is an inverse relation
12
+ */
13
+ static markRelation(relationKey, inverse = false) {
14
+ if (!this.allRelations.has(relationKey)) {
15
+ this.allRelations.set(relationKey, []);
16
+ }
17
+ const modelRelations = this.allRelations.get(relationKey);
18
+ let marked = false;
19
+ for (const relationInfo of modelRelations) {
20
+ if ((relationInfo.base !== null && !inverse) || (relationInfo.inversion !== null && inverse)) {
21
+ continue;
22
+ }
23
+ if (inverse) {
24
+ relationInfo.inversion = false;
25
+ marked = true;
26
+ }
27
+ else {
28
+ relationInfo.base = false;
29
+ marked = true;
30
+ }
31
+ return;
32
+ }
33
+ if (!marked) {
34
+ modelRelations.push({ base: inverse ? null : false, inversion: inverse ? false : null });
35
+ }
36
+ }
37
+ /**
38
+ * Complete a relation between two models
39
+ * @param relationKey A unique key for the relation
40
+ * @param index The index of the relation
41
+ * @param inverse Whether this is an inverse relation
42
+ */
43
+ static completeRelation(relationKey, index, inverse = false) {
44
+ const modelRelations = this.allRelations.get(relationKey);
45
+ if (inverse) {
46
+ modelRelations[index].inversion = true;
47
+ }
48
+ else {
49
+ modelRelations[index].base = true;
50
+ }
51
+ }
52
+ /**
53
+ * Get a unique counter for a relation between two models
54
+ * @param relationKey A unique key for the relation
55
+ * @param inverse Whether this is an inverse relation
56
+ * @returns A unique counter for this relation
57
+ */
58
+ static getRelationCounter(relationKey, inverse = false) {
59
+ let counter = 0;
60
+ for (const relationInfo of this.allRelations.get(relationKey)) {
61
+ if ((relationInfo.base === true && !inverse) || (relationInfo.inversion === true && inverse)) {
62
+ counter++;
63
+ }
64
+ }
65
+ return counter;
66
+ }
67
+ /**
68
+ * Generate a shortened relation name to stay within database limits
69
+ * @param modelName The name of the model
70
+ * @param relatedModelName The name of the related model
71
+ * @param index The index of the relation
72
+ * @returns A shortened relation name
73
+ */
74
+ static getShortenedRelationName(modelName, relatedModelName, index) {
75
+ const fullRelationName = `${modelName}_${relatedModelName}_${index}`.toLowerCase();
76
+ if (fullRelationName.length <= 64) {
77
+ return fullRelationName;
78
+ }
79
+ const extraChars = 2 + String(index).length;
80
+ const availableChars = 64 - extraChars;
81
+ const modelNameLength = modelName.length;
82
+ const relatedModelNameLength = relatedModelName.length;
83
+ const totalLength = modelNameLength + relatedModelNameLength;
84
+ const modelNameMaxLength = Math.floor(availableChars * (modelNameLength / totalLength));
85
+ const relatedModelNameMaxLength = availableChars - modelNameMaxLength;
86
+ const shortenedModelName = modelName.substring(0, Math.max(3, modelNameMaxLength));
87
+ const shortenedRelatedModelName = relatedModelName.substring(0, Math.max(3, relatedModelNameMaxLength));
88
+ // Create the new relation name
89
+ return `${shortenedModelName}_${shortenedRelatedModelName}_${index}`.toLowerCase();
90
+ }
91
+ /**
92
+ * Reset all relations (useful for testing)
93
+ */
94
+ static resetRelations() {
95
+ this.allRelations.clear();
96
+ }
97
+ /**
98
+ * Get all relations (useful for debugging)
99
+ */
100
+ static getAllRelations() {
101
+ return this.allRelations;
102
+ }
103
+ }
104
+ exports.RelationManager = RelationManager;
105
+ RelationManager.allRelations = new Map();
@@ -0,0 +1,37 @@
1
+ import { IDbConfigHandler } from '../../types/DbConfigHandler';
2
+ import { OpModelType } from '../../models/_model';
3
+ import { DBService } from '../../services/DBService';
4
+ /**
5
+ * Handles Prisma schema generation
6
+ */
7
+ export declare class SchemaGenerator {
8
+ static dbUrlVarName: string;
9
+ /**
10
+ * Generate the base schema for Prisma
11
+ * @param dbType The database type
12
+ * @param dbUrl The database URL
13
+ * @returns The base schema
14
+ */
15
+ static generateBaseSchema(dbType: string, dbUrl: string): string;
16
+ /**
17
+ * Generate model sections for the schema
18
+ * @param model The model to generate a section for
19
+ * @param configService The configuration service
20
+ * @returns The model section
21
+ */
22
+ static generateModelSections(model: OpModelType<any>, configService: IDbConfigHandler): Promise<string>;
23
+ /**
24
+ * Install Prisma with the generated schema
25
+ * @param configService The configuration service
26
+ * @param dbService The database service
27
+ * @param leaveFile Whether to leave the schema file after generation
28
+ */
29
+ static installPrisma(configService: IDbConfigHandler, dbService: DBService, leaveFile?: boolean): Promise<void>;
30
+ /**
31
+ * Push database models to the database
32
+ * @param configService The configuration service
33
+ * @param dbService The database service
34
+ * @param leaveFile Whether to leave the schema file after generation
35
+ */
36
+ static pushDBModels(configService: IDbConfigHandler, dbService: DBService, leaveFile?: boolean): Promise<void>;
37
+ }