myorm_pg 2.5.3 → 2.6.1

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