myorm_pg 2.5.2 → 2.6.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 (60) hide show
  1. package/lib/Index.d.ts +32 -32
  2. package/lib/Index.js +53 -53
  3. package/lib/core/decorators/SchemasDecorators.d.ts +44 -44
  4. package/lib/core/decorators/SchemasDecorators.js +144 -144
  5. package/lib/core/decorators/SchemasDecorators.js.map +1 -1
  6. package/lib/core/design/Type.d.ts +38 -37
  7. package/lib/core/design/Type.d.ts.map +1 -1
  8. package/lib/core/design/Type.js +142 -137
  9. package/lib/core/design/Type.js.map +1 -1
  10. package/lib/core/enums/DBTypes.d.ts +18 -18
  11. package/lib/core/enums/DBTypes.js +22 -22
  12. package/lib/core/enums/DBTypes.js.map +1 -1
  13. package/lib/core/enums/RelationType.d.ts +6 -6
  14. package/lib/core/enums/RelationType.js +10 -10
  15. package/lib/core/enums/RelationType.js.map +1 -1
  16. package/lib/core/exceptions/ConnectionFailException.d.ts +4 -4
  17. package/lib/core/exceptions/ConnectionFailException.js +12 -12
  18. package/lib/core/exceptions/ConstraintFailException.d.ts +4 -4
  19. package/lib/core/exceptions/ConstraintFailException.js +12 -12
  20. package/lib/core/exceptions/Exception.d.ts +4 -4
  21. package/lib/core/exceptions/Exception.js +9 -9
  22. package/lib/core/exceptions/InvalidOperationException.d.ts +5 -5
  23. package/lib/core/exceptions/InvalidOperationException.js +13 -13
  24. package/lib/core/exceptions/NotImplementedException.d.ts +4 -4
  25. package/lib/core/exceptions/NotImplementedException.js +12 -12
  26. package/lib/core/exceptions/QueryFailException.d.ts +5 -5
  27. package/lib/core/exceptions/QueryFailException.js +13 -13
  28. package/lib/core/exceptions/TypeNotSuportedException.d.ts +4 -4
  29. package/lib/core/exceptions/TypeNotSuportedException.js +12 -12
  30. package/lib/core/objects/DBOperationLogHandler.d.ts +15 -15
  31. package/lib/core/objects/DBOperationLogHandler.js +16 -16
  32. package/lib/core/objects/DBOperationLogHandler.js.map +1 -1
  33. package/lib/core/objects/interfaces/IDBConnection.d.ts +13 -13
  34. package/lib/core/objects/interfaces/IDBConnection.js +2 -2
  35. package/lib/core/objects/interfaces/IDBContext.d.ts +41 -41
  36. package/lib/core/objects/interfaces/IDBContext.js +2 -2
  37. package/lib/core/objects/interfaces/IDBManager.d.ts +12 -12
  38. package/lib/core/objects/interfaces/IDBManager.js +2 -2
  39. package/lib/core/objects/interfaces/IDBSet.d.ts +38 -35
  40. package/lib/core/objects/interfaces/IDBSet.d.ts.map +1 -1
  41. package/lib/core/objects/interfaces/IDBSet.js +2 -2
  42. package/lib/core/objects/interfaces/IStatement.d.ts +16 -16
  43. package/lib/core/objects/interfaces/IStatement.js +15 -15
  44. package/lib/core/objects/interfaces/IStatement.js.map +1 -1
  45. package/lib/implementations/PGDBConnection.d.ts +18 -18
  46. package/lib/implementations/PGDBConnection.js +102 -102
  47. package/lib/implementations/PGDBContext.d.ts +55 -55
  48. package/lib/implementations/PGDBContext.js +298 -298
  49. package/lib/implementations/PGDBManager.d.ts +31 -31
  50. package/lib/implementations/PGDBManager.js +242 -242
  51. package/lib/implementations/PGDBSet.d.ts +52 -48
  52. package/lib/implementations/PGDBSet.d.ts.map +1 -1
  53. package/lib/implementations/PGDBSet.js +984 -928
  54. package/lib/implementations/PGDBSet.js.map +1 -1
  55. package/lib/implementations/PGFluentField.d.ts +17 -17
  56. package/lib/implementations/PGFluentField.js +153 -153
  57. package/lib/implementations/PGSetHelper.d.ts +18 -18
  58. package/lib/implementations/PGSetHelper.js +47 -47
  59. package/lib/implementations/PGSetHelper.js.map +1 -1
  60. package/package.json +1 -1
@@ -1,929 +1,985 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- const Type_1 = __importDefault(require("../core/design/Type"));
16
- const DBTypes_1 = require("../core/enums/DBTypes");
17
- const IStatement_1 = require("../core/objects/interfaces/IStatement");
18
- const SchemasDecorators_1 = __importDefault(require("../core/decorators/SchemasDecorators"));
19
- const NotImplementedException_1 = __importDefault(require("../core/exceptions/NotImplementedException"));
20
- const TypeNotSuportedException_1 = __importDefault(require("../core/exceptions/TypeNotSuportedException"));
21
- const InvalidOperationException_1 = __importDefault(require("../core/exceptions/InvalidOperationException"));
22
- const RelationType_1 = require("../core/enums/RelationType");
23
- const ConstraintFailException_1 = __importDefault(require("../core/exceptions/ConstraintFailException"));
24
- const PGFluentField_1 = __importDefault(require("./PGFluentField"));
25
- const PGSetHelper_1 = __importDefault(require("./PGSetHelper"));
26
- class PGDBSet {
27
- constructor(cTor, context) {
28
- this._statements = [];
29
- this._ordering = [];
30
- this._includes = [];
31
- this._type = cTor;
32
- this._table = Type_1.default.GetTableName(cTor);
33
- this._maps = Type_1.default.GetColumnNameAndType(cTor);
34
- this._manager = context["_manager"];
35
- this._context = context;
36
- }
37
- AddAsync(obj) {
38
- return this.CreatePromisse(() => __awaiter(this, void 0, void 0, function* () {
39
- var _a, _b;
40
- if (!obj)
41
- throw new InvalidOperationException_1.default(`Cannot insert a null reference object of ${this._type.name}`);
42
- if (!this.IsCorrectType(obj))
43
- throw new InvalidOperationException_1.default(`The object passed as argument is not a ${this._type.name} instance`);
44
- let sql = `insert into "${this._table}"(`;
45
- let values = `values (`;
46
- let returnKey = '';
47
- let key;
48
- let subTypes = [];
49
- for (let map of this._maps) {
50
- if (SchemasDecorators_1.default.IsPrimaryKey(this._type, map.Field)) {
51
- returnKey = `returning ${map.Column}`;
52
- key =
53
- {
54
- Column: map.Column,
55
- Property: map.Field
56
- };
57
- continue;
58
- }
59
- let currPropValue = Reflect.get(obj, map.Field);
60
- if (currPropValue == undefined || currPropValue == null) {
61
- sql += `"${map.Column}",`;
62
- values += `null,`;
63
- continue;
64
- }
65
- let relation = SchemasDecorators_1.default.GetRelationAttribute(this._type, map.Field);
66
- let designType = Type_1.default.GetDesingType(this._type, map.Field);
67
- if ((designType && this._context.IsMapped(designType)) || (relation && this._context.IsMapped(relation.TypeBuilder()))) {
68
- subTypes.push({
69
- Column: map.Column,
70
- Field: map.Field,
71
- Type: map.Type
72
- });
73
- continue;
74
- }
75
- let colType = Type_1.default.CastType(map.Type);
76
- sql += `"${map.Column}",`;
77
- values += `${this.CreateValueStatement(colType, Reflect.get(obj, map.Field))},`;
78
- }
79
- if (key == undefined) {
80
- throw new InvalidOperationException_1.default(`The type ${this._type.name} must have a primary key field`);
81
- }
82
- sql = sql.substring(0, sql.length - 1) + ") ";
83
- values = values.substring(0, values.length - 1) + ")";
84
- let insert = `${sql} ${values} ${returnKey};`;
85
- let retun = yield this._manager.Execute(insert);
86
- if (key != undefined && retun.rows.length > 0) {
87
- obj[key.Property] = retun.rows[0][key.Column];
88
- }
89
- let subTypesUpdates = [];
90
- let updatableFields = [];
91
- for (let sub of subTypes) {
92
- let relation = SchemasDecorators_1.default.GetRelationAttribute(this._type, sub.Field);
93
- let subType = Type_1.default.GetDesingType(this._type, sub.Field);
94
- if (!subType && !relation)
95
- throw new InvalidOperationException_1.default(`Can not determine the relation of the property ${this._type}.${sub.Field}`);
96
- if (!subType && relation) {
97
- subType = relation.TypeBuilder();
98
- }
99
- let isArray = subType == Array;
100
- if (isArray) {
101
- if (!relation)
102
- continue;
103
- subType = relation === null || relation === void 0 ? void 0 : relation.TypeBuilder();
104
- }
105
- let subObj = Reflect.get(obj, sub.Field);
106
- if (subObj == undefined)
107
- continue;
108
- let subPK = SchemasDecorators_1.default.ExtractPrimaryKey(subType);
109
- if (subPK == undefined) {
110
- throw new InvalidOperationException_1.default(`The type ${subType.name} must have a primary key column`);
111
- }
112
- let colletion = this._context.Collection(subType);
113
- if (key != undefined) {
114
- for (let subKey of Type_1.default.GetProperties(subType)) {
115
- let subRelation = SchemasDecorators_1.default.GetRelationAttribute(subType, subKey);
116
- if (subRelation && subRelation.TypeBuilder() == this._type) {
117
- if (subRelation.Field != undefined && subRelation.Field != sub.Field)
118
- continue;
119
- if (subRelation.Relation == RelationType_1.RelationType.ONE_TO_MANY || subRelation.Relation == RelationType_1.RelationType.MANY_TO_MANY) {
120
- updatableFields.push(subKey);
121
- if (isArray) {
122
- for (let i of subObj) {
123
- if (i == undefined)
124
- continue;
125
- let metadata = Type_1.default.ExtractMetadata(i).filter(s => s.Field == subKey && s.Loaded);
126
- let value = [];
127
- if (metadata.length > 0) {
128
- value = ((_a = Reflect.get(i, subKey)) !== null && _a !== void 0 ? _a : []).filter(s => s[subPK] != obj[subPK]);
129
- }
130
- else {
131
- let item = yield colletion["Where"]({ Field: subPK, Value: Reflect.get(i, subPK) })["LoadRelationOn"](subKey)["FirstOrDefaultAsync"]();
132
- value = item == undefined ? [] : item[subKey];
133
- }
134
- value.push(obj);
135
- Reflect.set(i, subKey, value);
136
- }
137
- }
138
- else {
139
- let metadata = Type_1.default.ExtractMetadata(subObj).filter(s => s.Field == subKey && s.Loaded);
140
- let value = [];
141
- if (metadata.length > 0) {
142
- value = ((_b = Reflect.get(subObj, subKey)) !== null && _b !== void 0 ? _b : []).filter(s => s[subPK] != obj[subPK]);
143
- }
144
- else {
145
- let item = yield colletion["Where"]({ Field: subPK, Value: Reflect.get(subObj, subPK) })["LoadRelationOn"](subKey)["FirstOrDefaultAsync"]();
146
- value = item == undefined ? [] : item[subKey];
147
- }
148
- value.push(obj);
149
- Reflect.set(subObj, subKey, value);
150
- }
151
- }
152
- else {
153
- if (subRelation.Relation == RelationType_1.RelationType.MANY_TO_ONE && isArray) {
154
- for (let i of subObj) {
155
- if (i == undefined)
156
- continue;
157
- Reflect.set(i, subKey, obj);
158
- }
159
- }
160
- else {
161
- Reflect.set(subObj, subKey, obj);
162
- }
163
- }
164
- }
165
- }
166
- }
167
- if (isArray) {
168
- for (let i of subObj) {
169
- if (i == undefined)
170
- continue;
171
- if (!Type_1.default.HasValue(Reflect.get(i, subPK)))
172
- yield colletion["AddAsync"](i);
173
- else
174
- yield colletion["UpdateObjectAsync"](i, false, updatableFields);
175
- }
176
- }
177
- else {
178
- if (subObj == undefined)
179
- continue;
180
- if (!Type_1.default.HasValue(Reflect.get(subObj, subPK)))
181
- yield colletion["AddAsync"](subObj);
182
- else
183
- yield colletion["UpdateObjectAsync"](subObj, false, updatableFields);
184
- }
185
- let columnType = Type_1.default.CastType(Type_1.default.GetDesingTimeTypeName(subType, subPK));
186
- if ((relation === null || relation === void 0 ? void 0 : relation.Relation) == RelationType_1.RelationType.MANY_TO_MANY || (relation === null || relation === void 0 ? void 0 : relation.Relation) == RelationType_1.RelationType.ONE_TO_MANY || isArray)
187
- columnType = Type_1.default.AsArray(columnType);
188
- if (subObj == undefined)
189
- continue;
190
- let updateValues = [Reflect.get(subObj, subPK)];
191
- if (isArray) {
192
- updateValues = [];
193
- for (let i of subObj) {
194
- if (i == undefined)
195
- continue;
196
- updateValues.push(Reflect.get(i, subPK));
197
- }
198
- }
199
- subTypesUpdates.push(`"${sub.Column}" = ${this.CreateValueStatement(columnType, isArray ? updateValues : updateValues[0])}`);
200
- }
201
- if (subTypesUpdates.length > 0) {
202
- let subUpdate = `update "${Type_1.default.GetTableName(this._type)}" set `;
203
- for (let p of subTypesUpdates) {
204
- subUpdate += `${p},`;
205
- }
206
- subUpdate = `${subUpdate.substring(0, subUpdate.length - 1)} where `;
207
- subUpdate += this.EvaluateStatement({
208
- StatementType: StatementType.WHERE,
209
- Statement: {
210
- Field: key.Property,
211
- Kind: IStatement_1.Operation.EQUALS,
212
- Value: Reflect.get(obj, key.Property)
213
- }
214
- });
215
- yield this._manager.ExecuteNonQuery(subUpdate);
216
- }
217
- return obj;
218
- }));
219
- }
220
- UpdateAsync(obj) {
221
- return __awaiter(this, void 0, void 0, function* () {
222
- return yield this.UpdateObjectAsync(obj, false);
223
- });
224
- }
225
- UpdateObjectAsync(obj, cascade, fieldsAllowed) {
226
- return this.CreatePromisse(() => __awaiter(this, void 0, void 0, function* () {
227
- var _a;
228
- fieldsAllowed = fieldsAllowed !== null && fieldsAllowed !== void 0 ? fieldsAllowed : [];
229
- if (!this.IsCorrectType(obj))
230
- throw new InvalidOperationException_1.default(`The object passed as argument is not a ${this._type.name} instance`);
231
- if (!obj)
232
- throw new InvalidOperationException_1.default(`Cannot update a null reference object of ${this._type.name}`);
233
- let keys = Type_1.default.GetProperties(this._type).filter(p => SchemasDecorators_1.default.IsPrimaryKey(this._type, p));
234
- let wheres = [];
235
- if (keys && keys.length > 0) {
236
- keys.forEach((w, i) => {
237
- let keyValue = Reflect.get(obj, w);
238
- if (!keyValue)
239
- throw new ConstraintFailException_1.default(`The field ${this._type.name}.${w} is a primary key but has no value`);
240
- wheres.push({
241
- Statement: {
242
- Field: w,
243
- Kind: IStatement_1.Operation.EQUALS,
244
- Value: Reflect.get(obj, w)
245
- },
246
- StatementType: i == 0 ? StatementType.WHERE : StatementType.AND
247
- });
248
- });
249
- }
250
- let update = `update "${this._table}" set`;
251
- let values = "";
252
- let key;
253
- let subTypes = [];
254
- for (let map of this._maps) {
255
- let designType = Type_1.default.GetDesingType(this._type, map.Field);
256
- let relation = SchemasDecorators_1.default.GetRelationAttribute(this._type, map.Field);
257
- if ((designType && this._context.IsMapped(designType)) || (relation && this._context.IsMapped(relation.TypeBuilder()))) {
258
- subTypes.push({
259
- Column: map.Column,
260
- Field: map.Field,
261
- Type: map.Type
262
- });
263
- continue;
264
- }
265
- let colType = Type_1.default.CastType(map.Type);
266
- if (SchemasDecorators_1.default.IsPrimaryKey(this._type, map.Field)) {
267
- key =
268
- {
269
- Column: map.Column,
270
- Property: map.Field
271
- };
272
- continue;
273
- }
274
- values += `"${map.Column}" = ${this.CreateValueStatement(colType, Reflect.get(obj, map.Field))},`;
275
- }
276
- update = `${update} ${values.substring(0, values.length - 1)}`;
277
- for (let where of wheres) {
278
- update += ` ${where.StatementType} ${this.EvaluateStatement(where)} `;
279
- }
280
- yield this._manager.ExecuteNonQuery(update);
281
- let subTypesUpdates = [];
282
- for (let sub of subTypes) {
283
- let relation = SchemasDecorators_1.default.GetRelationAttribute(this._type, sub.Field);
284
- let subType = Type_1.default.GetDesingType(this._type, sub.Field);
285
- if (!subType && !relation)
286
- throw new InvalidOperationException_1.default(`Can not determine the relation of the property ${this._type}.${sub.Field}`);
287
- if (!subType && relation) {
288
- subType = relation.TypeBuilder();
289
- }
290
- let isArray = subType == Array;
291
- if (isArray) {
292
- if (!relation)
293
- continue;
294
- subType = relation === null || relation === void 0 ? void 0 : relation.TypeBuilder();
295
- }
296
- let subObj = Reflect.get(obj, sub.Field);
297
- let subPK = SchemasDecorators_1.default.ExtractPrimaryKey(subType);
298
- let metadata = Type_1.default.ExtractMetadata(obj);
299
- let meta = metadata.filter(s => s.Field == sub.Field && s.Loaded);
300
- if (meta.length > 0 && subObj == undefined) {
301
- if (meta[0].Loaded)
302
- subTypesUpdates.push(`"${sub.Column}" = null`);
303
- continue;
304
- }
305
- if (meta.length == 0 && fieldsAllowed.filter(s => s == sub.Field).length == 0)
306
- continue;
307
- if (subObj == undefined)
308
- continue;
309
- if (subPK == undefined) {
310
- throw new InvalidOperationException_1.default(`The type ${subType.name} must have a primary key column`);
311
- }
312
- if (key != undefined) {
313
- for (let subKey of Type_1.default.GetProperties(subType)) {
314
- let subRelation = SchemasDecorators_1.default.GetRelationAttribute(subType, subKey);
315
- if (subRelation && subRelation.TypeBuilder() == this._type) {
316
- if (subRelation.Field != undefined && subRelation.Field != sub.Field)
317
- continue;
318
- if (subRelation.Relation == RelationType_1.RelationType.ONE_TO_MANY || subRelation.Relation == RelationType_1.RelationType.MANY_TO_MANY) {
319
- if (isArray) {
320
- for (let i of subObj) {
321
- if (i == undefined)
322
- continue;
323
- let value = ((_a = Reflect.get(i, subKey)) !== null && _a !== void 0 ? _a : []).filter(s => s[subPK] != obj[subPK]);
324
- value.push(obj);
325
- Reflect.set(i, subKey, value);
326
- }
327
- }
328
- }
329
- else {
330
- if (subRelation.Relation == RelationType_1.RelationType.MANY_TO_ONE) {
331
- for (let i of subObj) {
332
- if (i == undefined)
333
- continue;
334
- Reflect.set(i, subKey, obj);
335
- }
336
- }
337
- else {
338
- Reflect.set(subObj, subKey, obj);
339
- }
340
- }
341
- }
342
- }
343
- }
344
- let colletion = this._context.Collection(subType);
345
- if (isArray) {
346
- for (let i of subObj) {
347
- if (i == undefined)
348
- continue;
349
- if (!Type_1.default.HasValue(Reflect.get(i, subPK)))
350
- yield colletion["AddAsync"](i);
351
- else if (cascade || fieldsAllowed.filter(s => s == sub.Field).length > 0)
352
- yield colletion["UpdateObjectAsync"](i, false);
353
- }
354
- }
355
- else {
356
- if (subObj == undefined)
357
- continue;
358
- if (!Type_1.default.HasValue(Reflect.get(subObj, subPK)))
359
- yield colletion["AddAsync"](subObj);
360
- else if (cascade || fieldsAllowed.filter(s => s == sub.Field).length > 0)
361
- yield colletion["UpdateObjectAsync"](subObj, false);
362
- }
363
- let columnType = Type_1.default.CastType(Type_1.default.GetDesingTimeTypeName(subType, subPK));
364
- if ((relation === null || relation === void 0 ? void 0 : relation.Relation) == RelationType_1.RelationType.MANY_TO_MANY || (relation === null || relation === void 0 ? void 0 : relation.Relation) == RelationType_1.RelationType.ONE_TO_MANY)
365
- columnType = Type_1.default.AsArray(columnType);
366
- if (subObj == undefined)
367
- continue;
368
- let updateValues = [Reflect.get(subObj, subPK)];
369
- if (isArray) {
370
- updateValues = [];
371
- for (let i of subObj) {
372
- if (i == undefined)
373
- continue;
374
- updateValues.push(Reflect.get(i, subPK));
375
- }
376
- }
377
- subTypesUpdates.push(`"${sub.Column}" = ${this.CreateValueStatement(columnType, isArray ? updateValues : updateValues[0])}`);
378
- }
379
- if (subTypesUpdates.length > 0) {
380
- let subUpdate = `update "${Type_1.default.GetTableName(this._type)}" set `;
381
- for (let p of subTypesUpdates) {
382
- subUpdate += `${p},`;
383
- }
384
- subUpdate = `${subUpdate.substring(0, subUpdate.length - 1)} where `;
385
- subUpdate += this.EvaluateStatement({
386
- StatementType: StatementType.WHERE,
387
- Statement: {
388
- Field: key.Property,
389
- Kind: IStatement_1.Operation.EQUALS,
390
- Value: Reflect.get(obj, key.Property)
391
- }
392
- });
393
- yield this._manager.ExecuteNonQuery(subUpdate);
394
- }
395
- return obj;
396
- }));
397
- }
398
- DeleteAsync(obj) {
399
- return this.CreatePromisse(() => __awaiter(this, void 0, void 0, function* () {
400
- if (!obj)
401
- throw new InvalidOperationException_1.default(`Cannot delete a null reference object of ${this._type.name}`);
402
- if (!this.IsCorrectType(obj))
403
- throw new InvalidOperationException_1.default(`The object passed as argument is not a ${this._type.name} instance`);
404
- let keys = Type_1.default.GetProperties(this._type).filter(p => SchemasDecorators_1.default.IsPrimaryKey(this._type, p));
405
- let wheres = [];
406
- if (keys && keys.length > 0) {
407
- keys.forEach((w, i) => {
408
- wheres.push({
409
- Statement: {
410
- Field: w,
411
- Kind: IStatement_1.Operation.EQUALS,
412
- Value: Reflect.get(obj, w)
413
- },
414
- StatementType: i == 0 ? StatementType.WHERE : StatementType.AND
415
- });
416
- });
417
- }
418
- let del = `delete from "${this._table}" `;
419
- for (let where of wheres) {
420
- del += ` ${where.StatementType} ${this.EvaluateStatement(where)} `;
421
- }
422
- yield this._manager.ExecuteNonQuery(del);
423
- return obj;
424
- }));
425
- }
426
- Where(statement) {
427
- var _a;
428
- this.ResetFilters();
429
- this._statements.push({
430
- Statement: {
431
- Field: statement.Field.toString(),
432
- Kind: (_a = statement.Kind) !== null && _a !== void 0 ? _a : IStatement_1.Operation.EQUALS,
433
- Value: statement.Value
434
- },
435
- StatementType: StatementType.WHERE
436
- });
437
- return this;
438
- }
439
- And(statement) {
440
- var _a;
441
- this._statements.push({
442
- Statement: {
443
- Field: statement.Field.toString(),
444
- Kind: (_a = statement.Kind) !== null && _a !== void 0 ? _a : IStatement_1.Operation.EQUALS,
445
- Value: statement.Value
446
- },
447
- StatementType: StatementType.AND
448
- });
449
- return this;
450
- }
451
- Or(statement) {
452
- var _a;
453
- this._statements.push({
454
- Statement: {
455
- Field: statement.Field.toString(),
456
- Kind: (_a = statement.Kind) !== null && _a !== void 0 ? _a : IStatement_1.Operation.EQUALS,
457
- Value: statement.Value
458
- },
459
- StatementType: StatementType.OR
460
- });
461
- return this;
462
- }
463
- OrderBy(key) {
464
- this._ordering.push({
465
- Field: key,
466
- Order: OrderDirection.ASC
467
- });
468
- return this;
469
- }
470
- Join(key) {
471
- this._includes.push({
472
- Field: key
473
- });
474
- return this;
475
- }
476
- OrderDescendingBy(key) {
477
- this._ordering.push({
478
- Field: key,
479
- Order: OrderDirection.DESC
480
- });
481
- return this;
482
- }
483
- Limit(limit) {
484
- this._limit = limit >= 1 ? { Limit: limit } : undefined;
485
- return this;
486
- }
487
- CountAsync() {
488
- return __awaiter(this, void 0, void 0, function* () {
489
- return this.CreatePromisse(() => __awaiter(this, void 0, void 0, function* () {
490
- let query = `select count(*) from "${this._table}"`;
491
- if (this._whereAsString != undefined && this._statements.length > 0) {
492
- throw new InvalidOperationException_1.default("Is not possible combine free and structured queries");
493
- }
494
- if (this._whereAsString != undefined) {
495
- query += ` ${this._whereAsString} `;
496
- }
497
- query += this.EvaluateWhere();
498
- let ordenation = "";
499
- for (let orderby of this._ordering) {
500
- ordenation += `${this.EvaluateOrderBy(orderby)},`;
501
- }
502
- if (this._ordering.length > 0) {
503
- query += ` order by ${ordenation.substring(0, ordenation.length - 1)}`;
504
- }
505
- if (this._limit != undefined) {
506
- query += ` limit ${this._limit.Limit}`;
507
- }
508
- var r = yield this._manager.Execute(query);
509
- this.Reset();
510
- return r.rows[0].count;
511
- }));
512
- });
513
- }
514
- ToListAsync() {
515
- return __awaiter(this, void 0, void 0, function* () {
516
- return this.CreatePromisse(() => __awaiter(this, void 0, void 0, function* () {
517
- let whereSrt = PGSetHelper_1.default.ExtractWhereData(this);
518
- let sqlSrt = PGSetHelper_1.default.ExtractSQLData(this);
519
- let query = `select "${this._table}".* from "${this._table}"`;
520
- if (sqlSrt && sqlSrt.toLowerCase().trim().startsWith(`select distinct "${this._table}".*`))
521
- query = sqlSrt;
522
- if (!whereSrt) {
523
- if (this._whereAsString != undefined && this._statements.length > 0) {
524
- throw new InvalidOperationException_1.default("Is not possible combine free and structured queries");
525
- }
526
- if (this._whereAsString != undefined) {
527
- query += ` ${this._whereAsString} `;
528
- }
529
- query += this.EvaluateWhere();
530
- }
531
- else {
532
- query += whereSrt;
533
- }
534
- let ordenation = "";
535
- for (let orderby of this._ordering) {
536
- ordenation += `${this.EvaluateOrderBy(orderby)},`;
537
- }
538
- if (this._ordering.length > 0) {
539
- query += ` order by ${ordenation.substring(0, ordenation.length - 1)}`;
540
- }
541
- if (this._limit != undefined) {
542
- query += ` limit ${this._limit.Limit}`;
543
- }
544
- var r = yield this._manager.Execute(query);
545
- if (r.rows.length == 0) {
546
- this.Reset();
547
- return [];
548
- }
549
- let list = [];
550
- list = yield this.BuildObjects(r);
551
- this.Reset();
552
- return list;
553
- }));
554
- });
555
- }
556
- FirstOrDefaultAsync() {
557
- return __awaiter(this, void 0, void 0, function* () {
558
- return this.CreatePromisse(() => __awaiter(this, void 0, void 0, function* () {
559
- let rows = yield this.Limit(1).ToListAsync();
560
- if (rows && rows.length > 0)
561
- return rows[0];
562
- return undefined;
563
- }));
564
- });
565
- }
566
- WhereField(field) {
567
- this.ResetFilters();
568
- return new PGFluentField_1.default(this, field, false);
569
- }
570
- AndField(field) {
571
- return new PGFluentField_1.default(this, field, false);
572
- }
573
- OrField(field) {
574
- return new PGFluentField_1.default(this, field, true);
575
- }
576
- WhereAsString(where) {
577
- this.ResetFilters();
578
- if (where && !where.trim().toLocaleLowerCase().startsWith("where")) {
579
- where = `where ${where}`;
580
- }
581
- this._whereAsString = where;
582
- return this;
583
- }
584
- LoadRelationOn(field) {
585
- return this.Join(field);
586
- }
587
- CreatePromisse(func) {
588
- return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
589
- try {
590
- resolve(yield func());
591
- }
592
- catch (err) {
593
- reject(err);
594
- }
595
- }));
596
- }
597
- CleanQueryTree() {
598
- this.Reset();
599
- }
600
- CreateValueStatement(colType, value) {
601
- if (value == undefined || value == null)
602
- return 'null';
603
- if (colType == DBTypes_1.DBTypes.TEXT) {
604
- return `$$${value}$$`;
605
- }
606
- else if (colType == DBTypes_1.DBTypes.BOOLEAN) {
607
- return `${value.toString().toLowerCase()}`;
608
- }
609
- else if (Type_1.default.IsNumber(colType)) {
610
- if (isNaN(value))
611
- throw new InvalidOperationException_1.default(`Can not cast the value "${value}" in a number`);
612
- return `${value}`.replace(',', '.');
613
- }
614
- else if (Type_1.default.IsDate(colType)) {
615
- let dt;
616
- if (value.constructor == Date)
617
- dt = value;
618
- else
619
- dt = new Date(value.toString());
620
- if (!dt)
621
- throw new InvalidOperationException_1.default(`Can not cast the value: "${value}" in a valid date`);
622
- let dtStr = `${dt.getFullYear()}-${dt.getMonth() + 1}-${dt.getDate()}`;
623
- if (colType == DBTypes_1.DBTypes.DATE) {
624
- return `'${dtStr}'::date`;
625
- }
626
- else {
627
- return `'${dtStr} ${dt.getHours()}:${dt.getMinutes()}'::timestamp`;
628
- }
629
- }
630
- else if (Type_1.default.IsArray(colType)) {
631
- let valuesStr = 'array[';
632
- let elementType = Type_1.default.ExtractElementType(colType);
633
- let hasItens = false;
634
- for (let i in value) {
635
- hasItens = true;
636
- valuesStr += `${this.CreateValueStatement(elementType, value[i])},`;
637
- }
638
- if (hasItens)
639
- valuesStr = valuesStr.substring(0, valuesStr.length - 1);
640
- valuesStr += `]::${this._manager["CastToPostgreSQLType"](colType)}`;
641
- return valuesStr;
642
- }
643
- throw new TypeNotSuportedException_1.default(`The type ${colType} is not suported`);
644
- }
645
- EvaluateWhere() {
646
- let query = "";
647
- for (let i = 0; i < this._statements.length; i++) {
648
- let where = this._statements[i];
649
- if (i == 0 && where.StatementType != StatementType.WHERE)
650
- throw new InvalidOperationException_1.default(`The query three must start with a WHERE statement`);
651
- if (i > 0 && where.StatementType == StatementType.WHERE)
652
- where.StatementType = StatementType.AND;
653
- query += ` ${where.StatementType} ${this.EvaluateStatement(where)} `;
654
- }
655
- return query;
656
- }
657
- EvaluateStatement(pgStatement) {
658
- let column = Type_1.default.GetColumnName(this._type, pgStatement.Statement.Field.toString());
659
- let typeName = Type_1.default.GetDesingTimeTypeName(this._type, pgStatement.Statement.Field.toString());
660
- let operation = this.GetOperators(pgStatement.Statement.Kind);
661
- let type = Type_1.default.GetDesingType(this._type, pgStatement.Statement.Field.toString());
662
- let isArray = type == Array;
663
- let relation = SchemasDecorators_1.default.GetRelationAttribute(this._type, pgStatement.Statement.Field.toString());
664
- if (!type) {
665
- if (!relation) {
666
- throw new InvalidOperationException_1.default(`Can not determine the correct type conversion for propety ${pgStatement.Statement.Field.toString()}`);
667
- }
668
- type = relation.TypeBuilder();
669
- }
670
- if (pgStatement.Statement.Value == undefined)
671
- return `"${this._table}".${column} is null`;
672
- if (this._context.IsMapped(type) || (relation && this._context.IsMapped(relation.TypeBuilder()))) {
673
- if (!relation)
674
- throw new InvalidOperationException_1.default(`Can not determine the correct type conversion for propety ${pgStatement.Statement.Field.toString()}`);
675
- if (isArray) {
676
- if (pgStatement.Statement.Value.lenght == 0)
677
- return `coalesce(array_length("${this._table}".${column}, 1), 0) = 0`;
678
- if (pgStatement.Statement.Value.filter(s => s == undefined || s == null).length > 0)
679
- throw new InvalidOperationException_1.default(`Can not compare relations with null or undefined objets`);
680
- let c = pgStatement.Statement.Value[0];
681
- let k = SchemasDecorators_1.default.ExtractPrimaryKey(c.constructor);
682
- if (!k)
683
- throw new ConstraintFailException_1.default(`The type ${c.constructor.name} must have a key field`);
684
- let elementType = Type_1.default.GetDesingTimeTypeName(c.constructor, k);
685
- let internalType = Type_1.default.CastType(elementType);
686
- let keyType = DBTypes_1.DBTypes.LONGARRAY;
687
- if (Type_1.default.IsNumber(internalType))
688
- keyType = DBTypes_1.DBTypes.LONGARRAY;
689
- else if (Type_1.default.IsText(internalType))
690
- keyType = DBTypes_1.DBTypes.TEXTARRAY;
691
- else if (Type_1.default.IsDate(internalType))
692
- keyType = DBTypes_1.DBTypes.DATEARRAY;
693
- else
694
- throw new InvalidOperationException_1.default(`Can not determine the correct type conversion for propety ${pgStatement.Statement.Field.toString()}`);
695
- let newValues = [];
696
- for (let e of pgStatement.Statement.Value) {
697
- newValues = [e[k]];
698
- }
699
- typeName = keyType;
700
- pgStatement.Statement.Value = newValues;
701
- }
702
- else {
703
- let k = SchemasDecorators_1.default.ExtractPrimaryKey(pgStatement.Statement.Value.constructor);
704
- if (!k)
705
- throw new ConstraintFailException_1.default(`The type ${pgStatement.Statement.Value.constructor.name} must have a key field`);
706
- let elementType = Type_1.default.GetDesingTimeTypeName(pgStatement.Statement.Value.constructor, k);
707
- let internalType = Type_1.default.CastType(elementType);
708
- typeName = internalType;
709
- pgStatement.Statement.Value = pgStatement.Statement.Value[k];
710
- }
711
- }
712
- if (isArray) {
713
- if (!typeName)
714
- throw new InvalidOperationException_1.default(`Can not determine the correct type conversion for propety ${pgStatement.Statement.Field.toString()}`);
715
- if (pgStatement.Statement.Kind == IStatement_1.Operation.EQUALS) {
716
- return `"${this._table}".${column} = ${this.CreateValueStatement(typeName, pgStatement.Statement.Value)}`;
717
- }
718
- if (pgStatement.Statement.Kind == IStatement_1.Operation.NOTEQUALS) {
719
- return `"${this._table}".${column} != ${this.CreateValueStatement(typeName, pgStatement.Statement.Value)}`;
720
- }
721
- if (pgStatement.Statement.Kind == IStatement_1.Operation.SMALLER || pgStatement.Statement.Kind == IStatement_1.Operation.SMALLEROREQUALS) {
722
- return `"${this._table}".${column} <@ ${this.CreateValueStatement(typeName, pgStatement.Statement.Value)}`;
723
- }
724
- if ([IStatement_1.Operation.STARTWITH, IStatement_1.Operation.CONSTAINS, IStatement_1.Operation.ENDWITH, IStatement_1.Operation.GREATHER, IStatement_1.Operation.GREATHEROREQUALS].includes(pgStatement.Statement.Kind)) {
725
- return `"${this._table}".${column} @> ${this.CreateValueStatement(typeName, pgStatement.Statement.Value)}`;
726
- }
727
- }
728
- if (Type_1.default.IsNumber(Type_1.default.CastType(typeName.toString())) || Type_1.default.IsDate(Type_1.default.CastType(typeName.toString()))) {
729
- operation[1] = "";
730
- operation[2] = "";
731
- if (Type_1.default.IsDate(Type_1.default.CastType(typeName.toString()))) {
732
- let dt = pgStatement.Statement.Value;
733
- if (!dt)
734
- throw new InvalidOperationException_1.default(`Can not cast the value: "${pgStatement.Statement.Value}" in a valid date`);
735
- let dtStr = `${dt.getFullYear()}-${dt.getMonth() + 1}-${dt.getDate()}`;
736
- if (Type_1.default.CastType(typeName.toString()) == DBTypes_1.DBTypes.DATE) {
737
- pgStatement.Statement.Value = `'${dtStr}'::date`;
738
- }
739
- else {
740
- pgStatement.Statement.Value = `'${dtStr} ${dt.getHours()}:${dt.getMinutes()}'::timestamp`;
741
- }
742
- }
743
- if ([IStatement_1.Operation.CONSTAINS, IStatement_1.Operation.ENDWITH, IStatement_1.Operation.STARTWITH].filter(s => s == pgStatement.Statement.Kind).length > 0) {
744
- throw new InvalidOperationException_1.default(`Can execute ${pgStatement.Statement.Kind.toString().toLocaleLowerCase()} only with text and array fields`);
745
- }
746
- }
747
- else {
748
- operation[1] = `$$${operation[1]}`;
749
- operation[2] = `${operation[2]}$$`;
750
- }
751
- return `"${this._table}".${column} ${operation[0]} ${operation[1]}${pgStatement.Statement.Value}${operation[2]}`;
752
- }
753
- EvaluateOrderBy(ordering) {
754
- let column = Type_1.default.GetColumnName(this._type, ordering.Field.toString());
755
- return ` "${this._table}".${column} ${ordering.Order}`;
756
- }
757
- GetOperators(operation) {
758
- switch (operation) {
759
- case IStatement_1.Operation.EQUALS: return ["=", "", ""];
760
- case IStatement_1.Operation.CONSTAINS: return ["ilike", "%", "%"];
761
- case IStatement_1.Operation.STARTWITH:
762
- return ["ilike", "", "%"];
763
- ;
764
- case IStatement_1.Operation.ENDWITH:
765
- return ["ilike", "%", ""];
766
- ;
767
- case IStatement_1.Operation.GREATHER:
768
- return [">", "", ""];
769
- ;
770
- case IStatement_1.Operation.GREATHEROREQUALS:
771
- return [">=", "", ""];
772
- ;
773
- case IStatement_1.Operation.SMALLER:
774
- return ["<", "", ""];
775
- ;
776
- case IStatement_1.Operation.SMALLEROREQUALS:
777
- return ["<=", "", ""];
778
- ;
779
- case IStatement_1.Operation.NOTEQUALS:
780
- return ["!=", "", ""];
781
- ;
782
- default: throw new NotImplementedException_1.default(`The operation ${operation} is not supported`);
783
- }
784
- }
785
- Reset() {
786
- this._ordering = [];
787
- this._includes = [];
788
- this._limit = undefined;
789
- this.ResetFilters();
790
- }
791
- ResetFilters() {
792
- this._statements = [];
793
- this._whereAsString = undefined;
794
- PGSetHelper_1.default.CleanORMData(this);
795
- }
796
- IsCorrectType(obj) {
797
- let sameCTor = obj && obj.constructor && obj.constructor == this._type;
798
- if (sameCTor)
799
- return true;
800
- if (obj.prototype == this._type)
801
- return true;
802
- if (obj.prototype && obj.prototype.constructor == this._type)
803
- return true;
804
- let objectKeys = Object.keys(obj);
805
- for (let map of this._maps) {
806
- let v = obj[map.Field];
807
- if (v == undefined) {
808
- let exists = objectKeys.filter(s => s == map.Field).length > 0;
809
- if (!exists) {
810
- let allowNull = SchemasDecorators_1.default.AllowNullValue(this._type, map.Field);
811
- if (!allowNull)
812
- return false;
813
- }
814
- }
815
- }
816
- obj.__proto__ = this._type;
817
- return true;
818
- }
819
- BuildObjects(r) {
820
- return __awaiter(this, void 0, void 0, function* () {
821
- let list = [];
822
- for (let row of r.rows) {
823
- let instance = Reflect.construct(this._type, []);
824
- for (let map of this._maps) {
825
- let type = Type_1.default.GetDesingType(this._type, map.Field);
826
- let relation = SchemasDecorators_1.default.GetRelationAttribute(this._type, map.Field);
827
- if ((!type || type === Array) && relation)
828
- type = relation.TypeBuilder();
829
- if (!this._context.IsMapped(type)) {
830
- let v = Reflect.get(row, map.Column);
831
- let vType = Type_1.default.CastType(map.Type);
832
- if (v != undefined) {
833
- if ([DBTypes_1.DBTypes.INTEGER, DBTypes_1.DBTypes.LONG, DBTypes_1.DBTypes.SERIAL].includes(vType))
834
- Reflect.set(instance, map.Field, Number.parseInt(v));
835
- else if (DBTypes_1.DBTypes.DOUBLE == vType)
836
- Reflect.set(instance, map.Field, Number.parseFloat(v));
837
- else if ([DBTypes_1.DBTypes.DATE, DBTypes_1.DBTypes.DATETIME].includes(vType)) {
838
- try {
839
- v = new Date(v);
840
- }
841
- catch (_a) { }
842
- Reflect.set(instance, map.Field, v);
843
- }
844
- else if (DBTypes_1.DBTypes.TEXT == vType)
845
- Reflect.set(instance, map.Field, v.toString());
846
- else
847
- Reflect.set(instance, map.Field, v);
848
- }
849
- else
850
- Reflect.set(instance, map.Field, v);
851
- }
852
- else {
853
- if (Reflect.get(row, map.Column) == undefined) {
854
- if (this._includes.filter(s => s.Field == map.Field).length > 0) {
855
- Type_1.default.InjectMetadata(instance, {
856
- Field: map.Field,
857
- Type: map.Type,
858
- Value: Reflect.get(row, map.Column),
859
- Loaded: true
860
- });
861
- }
862
- continue;
863
- }
864
- let includeType = this._includes.filter(s => s.Field == map.Field);
865
- let loaded = false;
866
- if (includeType.length > 0) {
867
- loaded = true;
868
- let colletion = this._context.Collection(type);
869
- if (colletion == undefined)
870
- continue;
871
- let subKey = SchemasDecorators_1.default.ExtractPrimaryKey(type);
872
- if ((relation === null || relation === void 0 ? void 0 : relation.Relation) == RelationType_1.RelationType.MANY_TO_MANY || (relation === null || relation === void 0 ? void 0 : relation.Relation) == RelationType_1.RelationType.ONE_TO_MANY) {
873
- let values = Reflect.get(row, map.Column);
874
- if (!values || values.length == 0)
875
- continue;
876
- colletion.Where({
877
- Field: subKey,
878
- Kind: IStatement_1.Operation.EQUALS,
879
- Value: values[0]
880
- });
881
- for (let i = 0; i < values.length; i++) {
882
- if (i == 0)
883
- continue;
884
- colletion.Or({
885
- Field: subKey,
886
- Kind: IStatement_1.Operation.EQUALS,
887
- Value: values[i]
888
- });
889
- }
890
- let subObjets = yield colletion.ToListAsync();
891
- Reflect.set(instance, map.Field, subObjets);
892
- }
893
- else {
894
- colletion.Where({
895
- Field: subKey,
896
- Kind: IStatement_1.Operation.EQUALS,
897
- Value: Reflect.get(row, map.Column)
898
- });
899
- let subObjet = yield colletion.FirstOrDefaultAsync();
900
- Reflect.set(instance, map.Field, subObjet);
901
- }
902
- }
903
- Type_1.default.InjectMetadata(instance, {
904
- Field: map.Field,
905
- Type: map.Type,
906
- Value: Reflect.get(row, map.Column),
907
- Loaded: loaded
908
- });
909
- }
910
- }
911
- list.push(instance);
912
- }
913
- return list;
914
- });
915
- }
916
- }
917
- exports.default = PGDBSet;
918
- var OrderDirection;
919
- (function (OrderDirection) {
920
- OrderDirection["ASC"] = "asc";
921
- OrderDirection["DESC"] = "desc";
922
- })(OrderDirection || (OrderDirection = {}));
923
- var StatementType;
924
- (function (StatementType) {
925
- StatementType["WHERE"] = "where";
926
- StatementType["OR"] = "or";
927
- StatementType["AND"] = "and";
928
- })(StatementType || (StatementType = {}));
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const Type_1 = __importDefault(require("../core/design/Type"));
16
+ const DBTypes_1 = require("../core/enums/DBTypes");
17
+ const IStatement_1 = require("../core/objects/interfaces/IStatement");
18
+ const SchemasDecorators_1 = __importDefault(require("../core/decorators/SchemasDecorators"));
19
+ const NotImplementedException_1 = __importDefault(require("../core/exceptions/NotImplementedException"));
20
+ const TypeNotSuportedException_1 = __importDefault(require("../core/exceptions/TypeNotSuportedException"));
21
+ const InvalidOperationException_1 = __importDefault(require("../core/exceptions/InvalidOperationException"));
22
+ const RelationType_1 = require("../core/enums/RelationType");
23
+ const ConstraintFailException_1 = __importDefault(require("../core/exceptions/ConstraintFailException"));
24
+ const PGFluentField_1 = __importDefault(require("./PGFluentField"));
25
+ const PGSetHelper_1 = __importDefault(require("./PGSetHelper"));
26
+ class PGDBSet {
27
+ constructor(cTor, context) {
28
+ this._statements = [];
29
+ this._ordering = [];
30
+ this._includes = [];
31
+ this._type = cTor;
32
+ this._table = Type_1.default.GetTableName(cTor);
33
+ this._maps = Type_1.default.GetColumnNameAndType(cTor);
34
+ this._manager = context["_manager"];
35
+ this._context = context;
36
+ }
37
+ AddAsync(obj) {
38
+ return this.CreatePromisse(() => __awaiter(this, void 0, void 0, function* () {
39
+ var _a, _b;
40
+ if (!obj)
41
+ throw new InvalidOperationException_1.default(`Cannot insert a null reference object of ${this._type.name}`);
42
+ if (!this.IsCorrectType(obj))
43
+ throw new InvalidOperationException_1.default(`The object passed as argument is not a ${this._type.name} instance`);
44
+ let sql = `insert into "${this._table}"(`;
45
+ let values = `values (`;
46
+ let returnKey = '';
47
+ let key;
48
+ let subTypes = [];
49
+ for (let map of this._maps) {
50
+ if (SchemasDecorators_1.default.IsPrimaryKey(this._type, map.Field)) {
51
+ returnKey = `returning ${map.Column}`;
52
+ key =
53
+ {
54
+ Column: map.Column,
55
+ Property: map.Field
56
+ };
57
+ continue;
58
+ }
59
+ let currPropValue = Reflect.get(obj, map.Field);
60
+ if (currPropValue == undefined || currPropValue == null) {
61
+ sql += `"${map.Column}",`;
62
+ values += `null,`;
63
+ continue;
64
+ }
65
+ let relation = SchemasDecorators_1.default.GetRelationAttribute(this._type, map.Field);
66
+ let designType = Type_1.default.GetDesingType(this._type, map.Field);
67
+ if ((designType && this._context.IsMapped(designType)) || (relation && this._context.IsMapped(relation.TypeBuilder()))) {
68
+ subTypes.push({
69
+ Column: map.Column,
70
+ Field: map.Field,
71
+ Type: map.Type
72
+ });
73
+ continue;
74
+ }
75
+ let colType = Type_1.default.CastType(map.Type);
76
+ sql += `"${map.Column}",`;
77
+ values += `${this.CreateValueStatement(colType, Reflect.get(obj, map.Field))},`;
78
+ }
79
+ if (key == undefined) {
80
+ throw new InvalidOperationException_1.default(`The type ${this._type.name} must have a primary key field`);
81
+ }
82
+ sql = sql.substring(0, sql.length - 1) + ") ";
83
+ values = values.substring(0, values.length - 1) + ")";
84
+ let insert = `${sql} ${values} ${returnKey};`;
85
+ let retun = yield this._manager.Execute(insert);
86
+ if (key != undefined && retun.rows.length > 0) {
87
+ obj[key.Property] = retun.rows[0][key.Column];
88
+ }
89
+ let subTypesUpdates = [];
90
+ let updatableFields = [];
91
+ for (let sub of subTypes) {
92
+ let relation = SchemasDecorators_1.default.GetRelationAttribute(this._type, sub.Field);
93
+ let subType = Type_1.default.GetDesingType(this._type, sub.Field);
94
+ if (!subType && !relation)
95
+ throw new InvalidOperationException_1.default(`Can not determine the relation of the property ${this._type}.${sub.Field}`);
96
+ if (!subType && relation) {
97
+ subType = relation.TypeBuilder();
98
+ }
99
+ let isArray = subType == Array;
100
+ if (isArray) {
101
+ if (!relation)
102
+ continue;
103
+ subType = relation === null || relation === void 0 ? void 0 : relation.TypeBuilder();
104
+ }
105
+ let subObj = Reflect.get(obj, sub.Field);
106
+ if (subObj == undefined)
107
+ continue;
108
+ let subPK = SchemasDecorators_1.default.ExtractPrimaryKey(subType);
109
+ if (subPK == undefined) {
110
+ throw new InvalidOperationException_1.default(`The type ${subType.name} must have a primary key column`);
111
+ }
112
+ let colletion = this._context.Collection(subType);
113
+ if (key != undefined) {
114
+ for (let subKey of Type_1.default.GetProperties(subType)) {
115
+ let subRelation = SchemasDecorators_1.default.GetRelationAttribute(subType, subKey);
116
+ if (subRelation && subRelation.TypeBuilder() == this._type) {
117
+ if (subRelation.Field != undefined && subRelation.Field != sub.Field)
118
+ continue;
119
+ if (subRelation.Relation == RelationType_1.RelationType.ONE_TO_MANY || subRelation.Relation == RelationType_1.RelationType.MANY_TO_MANY) {
120
+ updatableFields.push(subKey);
121
+ if (isArray) {
122
+ for (let i of subObj) {
123
+ if (i == undefined)
124
+ continue;
125
+ let metadata = Type_1.default.ExtractMetadata(i).filter(s => s.Field == subKey && s.Loaded);
126
+ let value = [];
127
+ if (metadata.length > 0) {
128
+ value = ((_a = Reflect.get(i, subKey)) !== null && _a !== void 0 ? _a : []).filter(s => s[subPK] != obj[subPK]);
129
+ }
130
+ else {
131
+ let item = yield colletion["Where"]({ Field: subPK, Value: Reflect.get(i, subPK) })["LoadRelationOn"](subKey)["FirstOrDefaultAsync"]();
132
+ value = item == undefined ? [] : item[subKey];
133
+ value = value !== null && value !== void 0 ? value : [];
134
+ }
135
+ value.push(obj);
136
+ Reflect.set(i, subKey, value);
137
+ }
138
+ }
139
+ else {
140
+ let metadata = Type_1.default.ExtractMetadata(subObj).filter(s => s.Field == subKey && s.Loaded);
141
+ let value = [];
142
+ if (metadata.length > 0) {
143
+ value = ((_b = Reflect.get(subObj, subKey)) !== null && _b !== void 0 ? _b : []).filter(s => s[subPK] != obj[subPK]);
144
+ }
145
+ else {
146
+ let item = yield colletion["Where"]({ Field: subPK, Value: Reflect.get(subObj, subPK) })["LoadRelationOn"](subKey)["FirstOrDefaultAsync"]();
147
+ value = item == undefined ? [] : item[subKey];
148
+ value = value !== null && value !== void 0 ? value : [];
149
+ }
150
+ value.push(obj);
151
+ Reflect.set(subObj, subKey, value);
152
+ }
153
+ }
154
+ else {
155
+ if (subRelation.Relation == RelationType_1.RelationType.MANY_TO_ONE && isArray) {
156
+ for (let i of subObj) {
157
+ if (i == undefined)
158
+ continue;
159
+ Reflect.set(i, subKey, obj);
160
+ }
161
+ }
162
+ else {
163
+ Reflect.set(subObj, subKey, obj);
164
+ }
165
+ }
166
+ }
167
+ }
168
+ }
169
+ if (isArray) {
170
+ for (let i of subObj) {
171
+ if (i == undefined)
172
+ continue;
173
+ if (!Type_1.default.HasValue(Reflect.get(i, subPK)))
174
+ yield colletion["AddAsync"](i);
175
+ else
176
+ yield colletion["UpdateObjectAsync"](i, false, updatableFields);
177
+ }
178
+ }
179
+ else {
180
+ if (subObj == undefined)
181
+ continue;
182
+ if (!Type_1.default.HasValue(Reflect.get(subObj, subPK)))
183
+ yield colletion["AddAsync"](subObj);
184
+ else
185
+ yield colletion["UpdateObjectAsync"](subObj, false, updatableFields);
186
+ }
187
+ let columnType = Type_1.default.CastType(Type_1.default.GetDesingTimeTypeName(subType, subPK));
188
+ if ((relation === null || relation === void 0 ? void 0 : relation.Relation) == RelationType_1.RelationType.MANY_TO_MANY || (relation === null || relation === void 0 ? void 0 : relation.Relation) == RelationType_1.RelationType.ONE_TO_MANY || isArray)
189
+ columnType = Type_1.default.AsArray(columnType);
190
+ if (subObj == undefined)
191
+ continue;
192
+ let updateValues = [Reflect.get(subObj, subPK)];
193
+ if (isArray) {
194
+ updateValues = [];
195
+ for (let i of subObj) {
196
+ if (i == undefined)
197
+ continue;
198
+ updateValues.push(Reflect.get(i, subPK));
199
+ }
200
+ }
201
+ subTypesUpdates.push(`"${sub.Column}" = ${this.CreateValueStatement(columnType, isArray ? updateValues : updateValues[0])}`);
202
+ }
203
+ if (subTypesUpdates.length > 0) {
204
+ let subUpdate = `update "${Type_1.default.GetTableName(this._type)}" set `;
205
+ for (let p of subTypesUpdates) {
206
+ subUpdate += `${p},`;
207
+ }
208
+ subUpdate = `${subUpdate.substring(0, subUpdate.length - 1)} where `;
209
+ subUpdate += this.EvaluateStatement({
210
+ StatementType: StatementType.WHERE,
211
+ Statement: {
212
+ Field: key.Property,
213
+ Kind: IStatement_1.Operation.EQUALS,
214
+ Value: Reflect.get(obj, key.Property)
215
+ }
216
+ });
217
+ yield this._manager.ExecuteNonQuery(subUpdate);
218
+ }
219
+ return obj;
220
+ }));
221
+ }
222
+ UpdateAsync(obj) {
223
+ return __awaiter(this, void 0, void 0, function* () {
224
+ return yield this.UpdateObjectAsync(obj, false);
225
+ });
226
+ }
227
+ UpdateObjectAndRelationsAsync(obj, relations) {
228
+ return __awaiter(this, void 0, void 0, function* () {
229
+ Type_1.default.DeleteMetadata(obj);
230
+ return this.UpdateObjectAsync(obj, false, relations ? relations.map(s => s.toString()) : []);
231
+ });
232
+ }
233
+ UpdateObjectAsync(obj, cascade, fieldsAllowed) {
234
+ return this.CreatePromisse(() => __awaiter(this, void 0, void 0, function* () {
235
+ var _a, _b;
236
+ fieldsAllowed = fieldsAllowed !== null && fieldsAllowed !== void 0 ? fieldsAllowed : [];
237
+ if (!this.IsCorrectType(obj))
238
+ throw new InvalidOperationException_1.default(`The object passed as argument is not a ${this._type.name} instance`);
239
+ if (!obj)
240
+ throw new InvalidOperationException_1.default(`Cannot update a null reference object of ${this._type.name}`);
241
+ let keys = Type_1.default.GetProperties(this._type).filter(p => SchemasDecorators_1.default.IsPrimaryKey(this._type, p));
242
+ let wheres = [];
243
+ if (keys && keys.length > 0) {
244
+ keys.forEach((w, i) => {
245
+ let keyValue = Reflect.get(obj, w);
246
+ if (!keyValue)
247
+ throw new ConstraintFailException_1.default(`The field ${this._type.name}.${w} is a primary key but has no value`);
248
+ wheres.push({
249
+ Statement: {
250
+ Field: w,
251
+ Kind: IStatement_1.Operation.EQUALS,
252
+ Value: Reflect.get(obj, w)
253
+ },
254
+ StatementType: i == 0 ? StatementType.WHERE : StatementType.AND
255
+ });
256
+ });
257
+ }
258
+ let update = `update "${this._table}" set`;
259
+ let values = "";
260
+ let key;
261
+ let subTypes = [];
262
+ for (let map of this._maps) {
263
+ let designType = Type_1.default.GetDesingType(this._type, map.Field);
264
+ let relation = SchemasDecorators_1.default.GetRelationAttribute(this._type, map.Field);
265
+ if ((designType && this._context.IsMapped(designType)) || (relation && this._context.IsMapped(relation.TypeBuilder()))) {
266
+ subTypes.push({
267
+ Column: map.Column,
268
+ Field: map.Field,
269
+ Type: map.Type
270
+ });
271
+ continue;
272
+ }
273
+ let colType = Type_1.default.CastType(map.Type);
274
+ if (SchemasDecorators_1.default.IsPrimaryKey(this._type, map.Field)) {
275
+ key =
276
+ {
277
+ Column: map.Column,
278
+ Property: map.Field
279
+ };
280
+ continue;
281
+ }
282
+ values += `"${map.Column}" = ${this.CreateValueStatement(colType, Reflect.get(obj, map.Field))},`;
283
+ }
284
+ update = `${update} ${values.substring(0, values.length - 1)}`;
285
+ for (let where of wheres) {
286
+ update += ` ${where.StatementType} ${this.EvaluateStatement(where)} `;
287
+ }
288
+ yield this._manager.ExecuteNonQuery(update);
289
+ let subTypesUpdates = [];
290
+ for (let sub of subTypes) {
291
+ let relation = SchemasDecorators_1.default.GetRelationAttribute(this._type, sub.Field);
292
+ let subType = Type_1.default.GetDesingType(this._type, sub.Field);
293
+ if (!subType && !relation)
294
+ throw new InvalidOperationException_1.default(`Can not determine the relation of the property ${this._type}.${sub.Field}`);
295
+ if (!subType && relation) {
296
+ subType = relation.TypeBuilder();
297
+ }
298
+ let isArray = subType == Array;
299
+ if (isArray) {
300
+ if (!relation)
301
+ continue;
302
+ subType = relation === null || relation === void 0 ? void 0 : relation.TypeBuilder();
303
+ }
304
+ let subObj = Reflect.get(obj, sub.Field);
305
+ let subPK = SchemasDecorators_1.default.ExtractPrimaryKey(subType);
306
+ let metadata = Type_1.default.ExtractMetadata(obj);
307
+ let meta = metadata.filter(s => s.Field == sub.Field && s.Loaded);
308
+ if (((meta.length > 0 && meta[0].Loaded) || fieldsAllowed.filter(s => s == sub.Field).length > 0) && subObj == undefined) {
309
+ subTypesUpdates.push(`"${sub.Column}" = null`);
310
+ continue;
311
+ }
312
+ if (meta.length == 0 && fieldsAllowed.filter(s => s == sub.Field).length == 0)
313
+ continue;
314
+ if (subObj == undefined)
315
+ continue;
316
+ if (subPK == undefined) {
317
+ throw new InvalidOperationException_1.default(`The type ${subType.name} must have a primary key column`);
318
+ }
319
+ if (key != undefined) {
320
+ let colletion = this._context.Collection(subType);
321
+ for (let subKey of Type_1.default.GetProperties(subType)) {
322
+ let subRelation = SchemasDecorators_1.default.GetRelationAttribute(subType, subKey);
323
+ if (subRelation && subRelation.TypeBuilder() == this._type) {
324
+ if (subRelation.Field != undefined && subRelation.Field != sub.Field)
325
+ continue;
326
+ if (subRelation.Relation == RelationType_1.RelationType.ONE_TO_MANY || subRelation.Relation == RelationType_1.RelationType.MANY_TO_MANY) {
327
+ if (isArray) {
328
+ for (let i of subObj) {
329
+ if (i == undefined)
330
+ continue;
331
+ let subFKTypeIsArray = Type_1.default.GetDesingType(subType, subKey) == Array;
332
+ if (subFKTypeIsArray) {
333
+ let value = [];
334
+ let subMeta = Type_1.default.ExtractMetadata(i);
335
+ if (subMeta.length > 0 && subMeta.filter(s => s.Field == subKey && s.Loaded).length > 0) {
336
+ value = ((_a = Reflect.get(i, subKey)) !== null && _a !== void 0 ? _a : []).filter(s => s[subPK] != obj[subPK]);
337
+ }
338
+ else {
339
+ let item = yield colletion["Where"]({ Field: subPK, Value: Reflect.get(i, subPK) })["LoadRelationOn"](subKey)["FirstOrDefaultAsync"]();
340
+ value = item == undefined ? [] : item[subKey];
341
+ value = value !== null && value !== void 0 ? value : [];
342
+ }
343
+ value.push(obj);
344
+ Reflect.set(i, subKey, value);
345
+ }
346
+ else {
347
+ Reflect.set(i, subKey, obj);
348
+ }
349
+ }
350
+ }
351
+ else {
352
+ let subFKTypeIsArray = Type_1.default.GetDesingType(subType, subKey) == Array;
353
+ if (subFKTypeIsArray) {
354
+ let value = [];
355
+ let subMeta = Type_1.default.ExtractMetadata(subObj);
356
+ if (subMeta.length > 0 && subMeta.filter(s => s.Field == subKey && s.Loaded).length > 0) {
357
+ value = ((_b = Reflect.get(subObj, subKey)) !== null && _b !== void 0 ? _b : []).filter(s => s[subPK] != obj[subPK]);
358
+ }
359
+ else {
360
+ let item = yield colletion["Where"]({ Field: subPK, Value: Reflect.get(subObj, subPK) })["LoadRelationOn"](subKey)["FirstOrDefaultAsync"]();
361
+ value = item == undefined ? [] : item[subKey];
362
+ value = value !== null && value !== void 0 ? value : [];
363
+ }
364
+ value.push(obj);
365
+ Reflect.set(subObj, subKey, value);
366
+ }
367
+ else {
368
+ Reflect.set(subObj, subKey, obj);
369
+ }
370
+ }
371
+ }
372
+ else {
373
+ if (subRelation.Relation == RelationType_1.RelationType.MANY_TO_ONE) {
374
+ for (let i of subObj) {
375
+ if (i == undefined)
376
+ continue;
377
+ Reflect.set(i, subKey, obj);
378
+ }
379
+ }
380
+ else {
381
+ Reflect.set(subObj, subKey, obj);
382
+ }
383
+ }
384
+ }
385
+ }
386
+ }
387
+ let colletion = this._context.Collection(subType);
388
+ if (isArray) {
389
+ for (let i of subObj) {
390
+ if (i == undefined)
391
+ continue;
392
+ if (!Type_1.default.HasValue(Reflect.get(i, subPK)))
393
+ yield colletion["AddAsync"](i);
394
+ else if (cascade || fieldsAllowed.filter(s => s == sub.Field).length > 0)
395
+ yield colletion["UpdateObjectAsync"](i, false);
396
+ }
397
+ }
398
+ else {
399
+ if (subObj == undefined)
400
+ continue;
401
+ if (!Type_1.default.HasValue(Reflect.get(subObj, subPK)))
402
+ yield colletion["AddAsync"](subObj);
403
+ else if (cascade || fieldsAllowed.filter(s => s == sub.Field).length > 0)
404
+ yield colletion["UpdateObjectAsync"](subObj, false);
405
+ }
406
+ let columnType = Type_1.default.CastType(Type_1.default.GetDesingTimeTypeName(subType, subPK));
407
+ if ((relation === null || relation === void 0 ? void 0 : relation.Relation) == RelationType_1.RelationType.MANY_TO_MANY || (relation === null || relation === void 0 ? void 0 : relation.Relation) == RelationType_1.RelationType.ONE_TO_MANY)
408
+ columnType = Type_1.default.AsArray(columnType);
409
+ if (subObj == undefined)
410
+ continue;
411
+ let updateValues = [Reflect.get(subObj, subPK)];
412
+ if (isArray) {
413
+ updateValues = [];
414
+ for (let i of subObj) {
415
+ if (i == undefined)
416
+ continue;
417
+ updateValues.push(Reflect.get(i, subPK));
418
+ }
419
+ }
420
+ subTypesUpdates.push(`"${sub.Column}" = ${this.CreateValueStatement(columnType, isArray ? updateValues : updateValues[0])}`);
421
+ }
422
+ if (subTypesUpdates.length > 0) {
423
+ let subUpdate = `update "${Type_1.default.GetTableName(this._type)}" set `;
424
+ for (let p of subTypesUpdates) {
425
+ subUpdate += `${p},`;
426
+ }
427
+ subUpdate = `${subUpdate.substring(0, subUpdate.length - 1)} where `;
428
+ subUpdate += this.EvaluateStatement({
429
+ StatementType: StatementType.WHERE,
430
+ Statement: {
431
+ Field: key.Property,
432
+ Kind: IStatement_1.Operation.EQUALS,
433
+ Value: Reflect.get(obj, key.Property)
434
+ }
435
+ });
436
+ yield this._manager.ExecuteNonQuery(subUpdate);
437
+ }
438
+ return obj;
439
+ }));
440
+ }
441
+ DeleteAsync(obj) {
442
+ return this.CreatePromisse(() => __awaiter(this, void 0, void 0, function* () {
443
+ if (!obj)
444
+ throw new InvalidOperationException_1.default(`Cannot delete a null reference object of ${this._type.name}`);
445
+ if (!this.IsCorrectType(obj))
446
+ throw new InvalidOperationException_1.default(`The object passed as argument is not a ${this._type.name} instance`);
447
+ let keys = Type_1.default.GetProperties(this._type).filter(p => SchemasDecorators_1.default.IsPrimaryKey(this._type, p));
448
+ let wheres = [];
449
+ if (keys && keys.length > 0) {
450
+ keys.forEach((w, i) => {
451
+ wheres.push({
452
+ Statement: {
453
+ Field: w,
454
+ Kind: IStatement_1.Operation.EQUALS,
455
+ Value: Reflect.get(obj, w)
456
+ },
457
+ StatementType: i == 0 ? StatementType.WHERE : StatementType.AND
458
+ });
459
+ });
460
+ }
461
+ let del = `delete from "${this._table}" `;
462
+ for (let where of wheres) {
463
+ del += ` ${where.StatementType} ${this.EvaluateStatement(where)} `;
464
+ }
465
+ yield this._manager.ExecuteNonQuery(del);
466
+ return obj;
467
+ }));
468
+ }
469
+ Where(statement) {
470
+ var _a;
471
+ this.ResetFilters();
472
+ this._statements.push({
473
+ Statement: {
474
+ Field: statement.Field.toString(),
475
+ Kind: (_a = statement.Kind) !== null && _a !== void 0 ? _a : IStatement_1.Operation.EQUALS,
476
+ Value: statement.Value
477
+ },
478
+ StatementType: StatementType.WHERE
479
+ });
480
+ return this;
481
+ }
482
+ And(statement) {
483
+ var _a;
484
+ this._statements.push({
485
+ Statement: {
486
+ Field: statement.Field.toString(),
487
+ Kind: (_a = statement.Kind) !== null && _a !== void 0 ? _a : IStatement_1.Operation.EQUALS,
488
+ Value: statement.Value
489
+ },
490
+ StatementType: StatementType.AND
491
+ });
492
+ return this;
493
+ }
494
+ Or(statement) {
495
+ var _a;
496
+ this._statements.push({
497
+ Statement: {
498
+ Field: statement.Field.toString(),
499
+ Kind: (_a = statement.Kind) !== null && _a !== void 0 ? _a : IStatement_1.Operation.EQUALS,
500
+ Value: statement.Value
501
+ },
502
+ StatementType: StatementType.OR
503
+ });
504
+ return this;
505
+ }
506
+ OrderBy(key) {
507
+ this._ordering.push({
508
+ Field: key,
509
+ Order: OrderDirection.ASC
510
+ });
511
+ return this;
512
+ }
513
+ Join(key) {
514
+ this._includes.push({
515
+ Field: key
516
+ });
517
+ return this;
518
+ }
519
+ OrderDescendingBy(key) {
520
+ this._ordering.push({
521
+ Field: key,
522
+ Order: OrderDirection.DESC
523
+ });
524
+ return this;
525
+ }
526
+ Limit(limit) {
527
+ this._limit = limit >= 1 ? { Limit: limit } : undefined;
528
+ return this;
529
+ }
530
+ Offset(offset) {
531
+ this._offset = offset >= 1 ? { OffSet: offset } : undefined;
532
+ return this;
533
+ }
534
+ Take(quantity) {
535
+ return this.Limit(quantity);
536
+ }
537
+ CountAsync() {
538
+ return __awaiter(this, void 0, void 0, function* () {
539
+ return this.CreatePromisse(() => __awaiter(this, void 0, void 0, function* () {
540
+ let query = `select count(*) from "${this._table}"`;
541
+ if (this._whereAsString != undefined && this._statements.length > 0) {
542
+ throw new InvalidOperationException_1.default("Is not possible combine free and structured queries");
543
+ }
544
+ if (this._whereAsString != undefined) {
545
+ query += ` ${this._whereAsString} `;
546
+ }
547
+ query += this.EvaluateWhere();
548
+ let ordenation = "";
549
+ for (let orderby of this._ordering) {
550
+ ordenation += `${this.EvaluateOrderBy(orderby)},`;
551
+ }
552
+ if (this._ordering.length > 0) {
553
+ query += ` order by ${ordenation.substring(0, ordenation.length - 1)}`;
554
+ }
555
+ if (this._offset != undefined) {
556
+ query += ` offset ${this._offset.OffSet}`;
557
+ }
558
+ if (this._limit != undefined) {
559
+ query += ` limit ${this._limit.Limit}`;
560
+ }
561
+ var r = yield this._manager.Execute(query);
562
+ this.Reset();
563
+ return r.rows[0].count;
564
+ }));
565
+ });
566
+ }
567
+ ToListAsync() {
568
+ return __awaiter(this, void 0, void 0, function* () {
569
+ return this.CreatePromisse(() => __awaiter(this, void 0, void 0, function* () {
570
+ let whereSrt = PGSetHelper_1.default.ExtractWhereData(this);
571
+ let sqlSrt = PGSetHelper_1.default.ExtractSQLData(this);
572
+ let query = `select "${this._table}".* from "${this._table}"`;
573
+ if (sqlSrt && sqlSrt.toLowerCase().trim().startsWith(`select distinct "${this._table}".*`))
574
+ query = sqlSrt;
575
+ if (!whereSrt) {
576
+ if (this._whereAsString != undefined && this._statements.length > 0) {
577
+ throw new InvalidOperationException_1.default("Is not possible combine free and structured queries");
578
+ }
579
+ if (this._whereAsString != undefined) {
580
+ query += ` ${this._whereAsString} `;
581
+ }
582
+ query += this.EvaluateWhere();
583
+ }
584
+ else {
585
+ query += whereSrt;
586
+ }
587
+ let ordenation = "";
588
+ for (let orderby of this._ordering) {
589
+ ordenation += `${this.EvaluateOrderBy(orderby)},`;
590
+ }
591
+ if (this._ordering.length > 0) {
592
+ query += ` order by ${ordenation.substring(0, ordenation.length - 1)}`;
593
+ }
594
+ if (this._offset != undefined) {
595
+ query += ` offset ${this._offset.OffSet}`;
596
+ }
597
+ if (this._limit != undefined) {
598
+ query += ` limit ${this._limit.Limit}`;
599
+ }
600
+ var r = yield this._manager.Execute(query);
601
+ if (r.rows.length == 0) {
602
+ this.Reset();
603
+ return [];
604
+ }
605
+ let list = [];
606
+ list = yield this.BuildObjects(r);
607
+ this.Reset();
608
+ return list;
609
+ }));
610
+ });
611
+ }
612
+ FirstOrDefaultAsync() {
613
+ return __awaiter(this, void 0, void 0, function* () {
614
+ return this.CreatePromisse(() => __awaiter(this, void 0, void 0, function* () {
615
+ let rows = yield this.Limit(1).ToListAsync();
616
+ if (rows && rows.length > 0)
617
+ return rows[0];
618
+ return undefined;
619
+ }));
620
+ });
621
+ }
622
+ WhereField(field) {
623
+ this.ResetFilters();
624
+ return new PGFluentField_1.default(this, field, false);
625
+ }
626
+ AndField(field) {
627
+ return new PGFluentField_1.default(this, field, false);
628
+ }
629
+ OrField(field) {
630
+ return new PGFluentField_1.default(this, field, true);
631
+ }
632
+ WhereAsString(where) {
633
+ this.ResetFilters();
634
+ if (where && !where.trim().toLocaleLowerCase().startsWith("where")) {
635
+ where = `where ${where}`;
636
+ }
637
+ this._whereAsString = where;
638
+ return this;
639
+ }
640
+ LoadRelationOn(field) {
641
+ return this.Join(field);
642
+ }
643
+ CreatePromisse(func) {
644
+ return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
645
+ try {
646
+ resolve(yield func());
647
+ }
648
+ catch (err) {
649
+ reject(err);
650
+ }
651
+ }));
652
+ }
653
+ CleanQueryTree() {
654
+ this.Reset();
655
+ }
656
+ CreateValueStatement(colType, value) {
657
+ if (value == undefined || value == null)
658
+ return 'null';
659
+ if (colType == DBTypes_1.DBTypes.TEXT) {
660
+ return `$$${value}$$`;
661
+ }
662
+ else if (colType == DBTypes_1.DBTypes.BOOLEAN) {
663
+ return `${value.toString().toLowerCase()}`;
664
+ }
665
+ else if (Type_1.default.IsNumber(colType)) {
666
+ if (isNaN(value))
667
+ throw new InvalidOperationException_1.default(`Can not cast the value "${value}" in a number`);
668
+ return `${value}`.replace(',', '.');
669
+ }
670
+ else if (Type_1.default.IsDate(colType)) {
671
+ let dt;
672
+ if (value.constructor == Date)
673
+ dt = value;
674
+ else
675
+ dt = new Date(value.toString());
676
+ if (!dt)
677
+ throw new InvalidOperationException_1.default(`Can not cast the value: "${value}" in a valid date`);
678
+ let dtStr = `${dt.getFullYear()}-${dt.getMonth() + 1}-${dt.getDate()}`;
679
+ if (colType == DBTypes_1.DBTypes.DATE) {
680
+ return `'${dtStr}'::date`;
681
+ }
682
+ else {
683
+ return `'${dtStr} ${dt.getHours()}:${dt.getMinutes()}'::timestamp`;
684
+ }
685
+ }
686
+ else if (Type_1.default.IsArray(colType)) {
687
+ let valuesStr = 'array[';
688
+ let elementType = Type_1.default.ExtractElementType(colType);
689
+ let hasItens = false;
690
+ for (let i in value) {
691
+ hasItens = true;
692
+ valuesStr += `${this.CreateValueStatement(elementType, value[i])},`;
693
+ }
694
+ if (hasItens)
695
+ valuesStr = valuesStr.substring(0, valuesStr.length - 1);
696
+ valuesStr += `]::${this._manager["CastToPostgreSQLType"](colType)}`;
697
+ return valuesStr;
698
+ }
699
+ throw new TypeNotSuportedException_1.default(`The type ${colType} is not suported`);
700
+ }
701
+ EvaluateWhere() {
702
+ let query = "";
703
+ for (let i = 0; i < this._statements.length; i++) {
704
+ let where = this._statements[i];
705
+ if (i == 0 && where.StatementType != StatementType.WHERE)
706
+ throw new InvalidOperationException_1.default(`The query three must start with a WHERE statement`);
707
+ if (i > 0 && where.StatementType == StatementType.WHERE)
708
+ where.StatementType = StatementType.AND;
709
+ query += ` ${where.StatementType} ${this.EvaluateStatement(where)} `;
710
+ }
711
+ return query;
712
+ }
713
+ EvaluateStatement(pgStatement) {
714
+ let column = Type_1.default.GetColumnName(this._type, pgStatement.Statement.Field.toString());
715
+ let typeName = Type_1.default.GetDesingTimeTypeName(this._type, pgStatement.Statement.Field.toString());
716
+ let operation = this.GetOperators(pgStatement.Statement.Kind);
717
+ let type = Type_1.default.GetDesingType(this._type, pgStatement.Statement.Field.toString());
718
+ let isArray = type == Array;
719
+ let relation = SchemasDecorators_1.default.GetRelationAttribute(this._type, pgStatement.Statement.Field.toString());
720
+ if (!type) {
721
+ if (!relation) {
722
+ throw new InvalidOperationException_1.default(`Can not determine the correct type conversion for propety ${pgStatement.Statement.Field.toString()}`);
723
+ }
724
+ type = relation.TypeBuilder();
725
+ }
726
+ if (pgStatement.Statement.Value == undefined)
727
+ return `"${this._table}".${column} is null`;
728
+ if (this._context.IsMapped(type) || (relation && this._context.IsMapped(relation.TypeBuilder()))) {
729
+ if (!relation)
730
+ throw new InvalidOperationException_1.default(`Can not determine the correct type conversion for propety ${pgStatement.Statement.Field.toString()}`);
731
+ if (isArray) {
732
+ if (pgStatement.Statement.Value.lenght == 0)
733
+ return `coalesce(array_length("${this._table}".${column}, 1), 0) = 0`;
734
+ if (pgStatement.Statement.Value.filter(s => s == undefined || s == null).length > 0)
735
+ throw new InvalidOperationException_1.default(`Can not compare relations with null or undefined objets`);
736
+ let c = pgStatement.Statement.Value[0];
737
+ let k = SchemasDecorators_1.default.ExtractPrimaryKey(c.constructor);
738
+ if (!k)
739
+ throw new ConstraintFailException_1.default(`The type ${c.constructor.name} must have a key field`);
740
+ let elementType = Type_1.default.GetDesingTimeTypeName(c.constructor, k);
741
+ let internalType = Type_1.default.CastType(elementType);
742
+ let keyType = DBTypes_1.DBTypes.LONGARRAY;
743
+ if (Type_1.default.IsNumber(internalType))
744
+ keyType = DBTypes_1.DBTypes.LONGARRAY;
745
+ else if (Type_1.default.IsText(internalType))
746
+ keyType = DBTypes_1.DBTypes.TEXTARRAY;
747
+ else if (Type_1.default.IsDate(internalType))
748
+ keyType = DBTypes_1.DBTypes.DATEARRAY;
749
+ else
750
+ throw new InvalidOperationException_1.default(`Can not determine the correct type conversion for propety ${pgStatement.Statement.Field.toString()}`);
751
+ let newValues = [];
752
+ for (let e of pgStatement.Statement.Value) {
753
+ newValues = [e[k]];
754
+ }
755
+ typeName = keyType;
756
+ pgStatement.Statement.Value = newValues;
757
+ }
758
+ else {
759
+ let k = SchemasDecorators_1.default.ExtractPrimaryKey(pgStatement.Statement.Value.constructor);
760
+ if (!k)
761
+ throw new ConstraintFailException_1.default(`The type ${pgStatement.Statement.Value.constructor.name} must have a key field`);
762
+ let elementType = Type_1.default.GetDesingTimeTypeName(pgStatement.Statement.Value.constructor, k);
763
+ let internalType = Type_1.default.CastType(elementType);
764
+ typeName = internalType;
765
+ pgStatement.Statement.Value = pgStatement.Statement.Value[k];
766
+ }
767
+ }
768
+ if (isArray) {
769
+ if (!typeName)
770
+ throw new InvalidOperationException_1.default(`Can not determine the correct type conversion for propety ${pgStatement.Statement.Field.toString()}`);
771
+ if (pgStatement.Statement.Kind == IStatement_1.Operation.EQUALS) {
772
+ return `"${this._table}".${column} = ${this.CreateValueStatement(typeName, pgStatement.Statement.Value)}`;
773
+ }
774
+ if (pgStatement.Statement.Kind == IStatement_1.Operation.NOTEQUALS) {
775
+ return `"${this._table}".${column} != ${this.CreateValueStatement(typeName, pgStatement.Statement.Value)}`;
776
+ }
777
+ if (pgStatement.Statement.Kind == IStatement_1.Operation.SMALLER || pgStatement.Statement.Kind == IStatement_1.Operation.SMALLEROREQUALS) {
778
+ return `"${this._table}".${column} <@ ${this.CreateValueStatement(typeName, pgStatement.Statement.Value)}`;
779
+ }
780
+ if ([IStatement_1.Operation.STARTWITH, IStatement_1.Operation.CONSTAINS, IStatement_1.Operation.ENDWITH, IStatement_1.Operation.GREATHER, IStatement_1.Operation.GREATHEROREQUALS].includes(pgStatement.Statement.Kind)) {
781
+ return `"${this._table}".${column} @> ${this.CreateValueStatement(typeName, pgStatement.Statement.Value)}`;
782
+ }
783
+ }
784
+ if (Type_1.default.IsNumber(Type_1.default.CastType(typeName.toString())) || Type_1.default.IsDate(Type_1.default.CastType(typeName.toString()))) {
785
+ operation[1] = "";
786
+ operation[2] = "";
787
+ if (Type_1.default.IsDate(Type_1.default.CastType(typeName.toString()))) {
788
+ let dt = pgStatement.Statement.Value;
789
+ if (!dt)
790
+ throw new InvalidOperationException_1.default(`Can not cast the value: "${pgStatement.Statement.Value}" in a valid date`);
791
+ let dtStr = `${dt.getFullYear()}-${dt.getMonth() + 1}-${dt.getDate()}`;
792
+ if (Type_1.default.CastType(typeName.toString()) == DBTypes_1.DBTypes.DATE) {
793
+ pgStatement.Statement.Value = `'${dtStr}'::date`;
794
+ }
795
+ else {
796
+ pgStatement.Statement.Value = `'${dtStr} ${dt.getHours()}:${dt.getMinutes()}'::timestamp`;
797
+ }
798
+ }
799
+ if ([IStatement_1.Operation.CONSTAINS, IStatement_1.Operation.ENDWITH, IStatement_1.Operation.STARTWITH].filter(s => s == pgStatement.Statement.Kind).length > 0) {
800
+ throw new InvalidOperationException_1.default(`Can execute ${pgStatement.Statement.Kind.toString().toLocaleLowerCase()} only with text and array fields`);
801
+ }
802
+ }
803
+ else {
804
+ operation[1] = `$$${operation[1]}`;
805
+ operation[2] = `${operation[2]}$$`;
806
+ }
807
+ return `"${this._table}".${column} ${operation[0]} ${operation[1]}${pgStatement.Statement.Value}${operation[2]}`;
808
+ }
809
+ EvaluateOrderBy(ordering) {
810
+ let column = Type_1.default.GetColumnName(this._type, ordering.Field.toString());
811
+ return ` "${this._table}".${column} ${ordering.Order}`;
812
+ }
813
+ GetOperators(operation) {
814
+ switch (operation) {
815
+ case IStatement_1.Operation.EQUALS: return ["=", "", ""];
816
+ case IStatement_1.Operation.CONSTAINS: return ["ilike", "%", "%"];
817
+ case IStatement_1.Operation.STARTWITH:
818
+ return ["ilike", "", "%"];
819
+ ;
820
+ case IStatement_1.Operation.ENDWITH:
821
+ return ["ilike", "%", ""];
822
+ ;
823
+ case IStatement_1.Operation.GREATHER:
824
+ return [">", "", ""];
825
+ ;
826
+ case IStatement_1.Operation.GREATHEROREQUALS:
827
+ return [">=", "", ""];
828
+ ;
829
+ case IStatement_1.Operation.SMALLER:
830
+ return ["<", "", ""];
831
+ ;
832
+ case IStatement_1.Operation.SMALLEROREQUALS:
833
+ return ["<=", "", ""];
834
+ ;
835
+ case IStatement_1.Operation.NOTEQUALS:
836
+ return ["!=", "", ""];
837
+ ;
838
+ default: throw new NotImplementedException_1.default(`The operation ${operation} is not supported`);
839
+ }
840
+ }
841
+ Reset() {
842
+ this._ordering = [];
843
+ this._includes = [];
844
+ this._limit = undefined;
845
+ this.ResetFilters();
846
+ }
847
+ ResetFilters() {
848
+ this._statements = [];
849
+ this._whereAsString = undefined;
850
+ PGSetHelper_1.default.CleanORMData(this);
851
+ }
852
+ IsCorrectType(obj) {
853
+ let sameCTor = obj && obj.constructor && obj.constructor == this._type;
854
+ if (sameCTor)
855
+ return true;
856
+ if (obj.prototype == this._type)
857
+ return true;
858
+ if (obj.prototype && obj.prototype.constructor == this._type)
859
+ return true;
860
+ let objectKeys = Object.keys(obj);
861
+ for (let map of this._maps) {
862
+ let v = obj[map.Field];
863
+ if (v == undefined) {
864
+ let exists = objectKeys.filter(s => s == map.Field).length > 0;
865
+ if (!exists) {
866
+ let allowNull = SchemasDecorators_1.default.AllowNullValue(this._type, map.Field);
867
+ if (!allowNull)
868
+ return false;
869
+ }
870
+ }
871
+ }
872
+ obj.__proto__ = this._type;
873
+ return true;
874
+ }
875
+ BuildObjects(r) {
876
+ return __awaiter(this, void 0, void 0, function* () {
877
+ let list = [];
878
+ for (let row of r.rows) {
879
+ let instance = Reflect.construct(this._type, []);
880
+ for (let map of this._maps) {
881
+ let type = Type_1.default.GetDesingType(this._type, map.Field);
882
+ let relation = SchemasDecorators_1.default.GetRelationAttribute(this._type, map.Field);
883
+ if ((!type || type === Array) && relation)
884
+ type = relation.TypeBuilder();
885
+ if (!this._context.IsMapped(type)) {
886
+ let v = Reflect.get(row, map.Column);
887
+ let vType = Type_1.default.CastType(map.Type);
888
+ if (v != undefined) {
889
+ if ([DBTypes_1.DBTypes.INTEGER, DBTypes_1.DBTypes.LONG, DBTypes_1.DBTypes.SERIAL].includes(vType))
890
+ Reflect.set(instance, map.Field, Number.parseInt(v));
891
+ else if (DBTypes_1.DBTypes.DOUBLE == vType)
892
+ Reflect.set(instance, map.Field, Number.parseFloat(v));
893
+ else if ([DBTypes_1.DBTypes.DATE, DBTypes_1.DBTypes.DATETIME].includes(vType)) {
894
+ try {
895
+ v = new Date(v);
896
+ }
897
+ catch (_a) { }
898
+ Reflect.set(instance, map.Field, v);
899
+ }
900
+ else if (DBTypes_1.DBTypes.TEXT == vType)
901
+ Reflect.set(instance, map.Field, v.toString());
902
+ else
903
+ Reflect.set(instance, map.Field, v);
904
+ }
905
+ else
906
+ Reflect.set(instance, map.Field, v);
907
+ }
908
+ else {
909
+ if (Reflect.get(row, map.Column) == undefined) {
910
+ if (this._includes.filter(s => s.Field == map.Field).length > 0) {
911
+ Type_1.default.InjectMetadata(instance, {
912
+ Field: map.Field,
913
+ Type: map.Type,
914
+ Value: Reflect.get(row, map.Column),
915
+ Loaded: true
916
+ });
917
+ }
918
+ continue;
919
+ }
920
+ let includeType = this._includes.filter(s => s.Field == map.Field);
921
+ let loaded = false;
922
+ if (includeType.length > 0) {
923
+ loaded = true;
924
+ let colletion = this._context.Collection(type);
925
+ if (colletion == undefined)
926
+ continue;
927
+ let subKey = SchemasDecorators_1.default.ExtractPrimaryKey(type);
928
+ if ((relation === null || relation === void 0 ? void 0 : relation.Relation) == RelationType_1.RelationType.MANY_TO_MANY || (relation === null || relation === void 0 ? void 0 : relation.Relation) == RelationType_1.RelationType.ONE_TO_MANY) {
929
+ let values = Reflect.get(row, map.Column);
930
+ if (!values || values.length == 0)
931
+ continue;
932
+ colletion.Where({
933
+ Field: subKey,
934
+ Kind: IStatement_1.Operation.EQUALS,
935
+ Value: values[0]
936
+ });
937
+ for (let i = 0; i < values.length; i++) {
938
+ if (i == 0)
939
+ continue;
940
+ colletion.Or({
941
+ Field: subKey,
942
+ Kind: IStatement_1.Operation.EQUALS,
943
+ Value: values[i]
944
+ });
945
+ }
946
+ let subObjets = yield colletion.ToListAsync();
947
+ Reflect.set(instance, map.Field, subObjets);
948
+ }
949
+ else {
950
+ colletion.Where({
951
+ Field: subKey,
952
+ Kind: IStatement_1.Operation.EQUALS,
953
+ Value: Reflect.get(row, map.Column)
954
+ });
955
+ let subObjet = yield colletion.FirstOrDefaultAsync();
956
+ Reflect.set(instance, map.Field, subObjet);
957
+ }
958
+ }
959
+ Type_1.default.InjectMetadata(instance, {
960
+ Field: map.Field,
961
+ Type: map.Type,
962
+ Value: Reflect.get(row, map.Column),
963
+ Loaded: loaded
964
+ });
965
+ }
966
+ }
967
+ list.push(instance);
968
+ }
969
+ return list;
970
+ });
971
+ }
972
+ }
973
+ exports.default = PGDBSet;
974
+ var OrderDirection;
975
+ (function (OrderDirection) {
976
+ OrderDirection["ASC"] = "asc";
977
+ OrderDirection["DESC"] = "desc";
978
+ })(OrderDirection || (OrderDirection = {}));
979
+ var StatementType;
980
+ (function (StatementType) {
981
+ StatementType["WHERE"] = "where";
982
+ StatementType["OR"] = "or";
983
+ StatementType["AND"] = "and";
984
+ })(StatementType || (StatementType = {}));
929
985
  //# sourceMappingURL=PGDBSet.js.map