tspace-mysql 1.1.2 → 1.1.3

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.
@@ -1,1176 +1,942 @@
1
1
  "use strict";
2
- var __extends = (this && this.__extends) || (function () {
3
- var extendStatics = function (d, b) {
4
- extendStatics = Object.setPrototypeOf ||
5
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
- return extendStatics(d, b);
8
- };
9
- return function (d, b) {
10
- if (typeof b !== "function" && b !== null)
11
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
- extendStatics(d, b);
13
- function __() { this.constructor = d; }
14
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
- };
16
- })();
17
- var __assign = (this && this.__assign) || function () {
18
- __assign = Object.assign || function(t) {
19
- for (var s, i = 1, n = arguments.length; i < n; i++) {
20
- s = arguments[i];
21
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
22
- t[p] = s[p];
23
- }
24
- return t;
25
- };
26
- return __assign.apply(this, arguments);
27
- };
28
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
29
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
30
- return new (P || (P = Promise))(function (resolve, reject) {
31
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
32
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
33
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
34
- step((generator = generator.apply(thisArg, _arguments || [])).next());
35
- });
36
- };
37
- var __generator = (this && this.__generator) || function (thisArg, body) {
38
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
39
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
40
- function verb(n) { return function (v) { return step([n, v]); }; }
41
- function step(op) {
42
- if (f) throw new TypeError("Generator is already executing.");
43
- while (_) try {
44
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
45
- if (y = 0, t) op = [op[0] & 2, t.value];
46
- switch (op[0]) {
47
- case 0: case 1: t = op; break;
48
- case 4: _.label++; return { value: op[1], done: false };
49
- case 5: _.label++; y = op[1]; op = [0]; continue;
50
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
51
- default:
52
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
53
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
54
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
55
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
56
- if (t[2]) _.ops.pop();
57
- _.trys.pop(); continue;
58
- }
59
- op = body.call(thisArg, _);
60
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
61
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
62
- }
63
- };
64
- var __read = (this && this.__read) || function (o, n) {
65
- var m = typeof Symbol === "function" && o[Symbol.iterator];
66
- if (!m) return o;
67
- var i = m.call(o), r, ar = [], e;
68
- try {
69
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
70
- }
71
- catch (error) { e = { error: error }; }
72
- finally {
73
- try {
74
- if (r && !r.done && (m = i["return"])) m.call(i);
75
- }
76
- finally { if (e) throw e.error; }
77
- }
78
- return ar;
79
- };
80
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
81
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
82
- if (ar || !(i in from)) {
83
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
84
- ar[i] = from[i];
85
- }
86
- }
87
- return to.concat(ar || Array.prototype.slice.call(from));
88
- };
89
- var __values = (this && this.__values) || function(o) {
90
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
91
- if (m) return m.call(o);
92
- if (o && typeof o.length === "number") return {
93
- next: function () {
94
- if (o && i >= o.length) o = void 0;
95
- return { value: o && o[i++], done: !o };
96
- }
97
- };
98
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
99
- };
100
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
101
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
102
4
  };
103
5
  Object.defineProperty(exports, "__esModule", { value: true });
104
6
  exports.Model = void 0;
105
- var AbstractModel_1 = require("./AbstractModel");
106
- var pluralize_1 = __importDefault(require("pluralize"));
107
- var DB_1 = require("./DB");
108
- var ProxyHandler_1 = require("./ProxyHandler");
109
- var Model = /** @class */ (function (_super) {
110
- __extends(Model, _super);
111
- function Model() {
112
- var _this = _super.call(this) || this;
113
- _this._initialModel();
114
- return new Proxy(_this, ProxyHandler_1.proxyHandler);
7
+ const pluralize_1 = __importDefault(require("pluralize"));
8
+ const AbstractModel_1 = require("./AbstractModel");
9
+ const DB_1 = require("./DB");
10
+ const ProxyHandler_1 = require("./ProxyHandler");
11
+ class Model extends AbstractModel_1.AbstractModel {
12
+ constructor() {
13
+ super();
14
+ /**
15
+ *
16
+ * Get initialize for model
17
+ */
18
+ this._initialModel();
19
+ /**
20
+ *
21
+ * Boot Setup for model
22
+ */
23
+ this.boot();
24
+ return new Proxy(this, ProxyHandler_1.proxyHandler);
115
25
  }
116
26
  /**
117
27
  *
118
28
  * Assign function callback in model
119
29
  * @return {this} this
120
30
  */
121
- Model.prototype.useRegistry = function () {
122
- this.$db.set('REGISTRY', __assign(__assign({}, this.$db.get('REGISTRY')), { attach: this._attach, detach: this._detach }));
31
+ useRegistry() {
32
+ this.$db.set('REGISTRY', {
33
+ ...this.$db.get('REGISTRY'),
34
+ attach: this._attach,
35
+ detach: this._detach
36
+ });
123
37
  return this;
124
- };
38
+ }
125
39
  /**
126
40
  *
127
41
  * Assign function callback in model
128
42
  * @return {this} this
129
43
  */
130
- Model.prototype.usePrimaryKey = function (primary) {
44
+ usePrimaryKey(primary) {
131
45
  this.$db.set('PRIMARY_KEY', primary);
132
46
  return this;
133
- };
47
+ }
134
48
  /**
135
49
  * Assign in model uuid when creating
136
- * @param {string} uuid custom column uuid
50
+ * @param {string?} column [column=uuid] custom column replace this
137
51
  * @return {this} this
138
52
  */
139
- Model.prototype.useUUID = function (uuid) {
53
+ useUUID(column) {
140
54
  this.$db.set('UUID', true);
141
- if (uuid)
142
- this.$db.set('UUID_FORMAT', uuid);
55
+ if (column)
56
+ this.$db.set('UUID_FORMAT', column);
143
57
  return this;
144
- };
58
+ }
145
59
  /**
146
60
  * Assign in model console.log sql statement
147
61
  * @return {this} this
148
62
  */
149
- Model.prototype.useDebug = function () {
63
+ useDebug() {
150
64
  this.$db.set('DEBUG', true);
151
65
  return this;
152
- };
66
+ }
153
67
  /**
154
68
  *
155
69
  * Assign in model use pattern [snake_case , camelCase]
156
70
  * @param {string} pattern
157
71
  * @return {this} this
158
72
  */
159
- Model.prototype.usePattern = function (pattern) {
160
- var allowPattern = [
73
+ usePattern(pattern) {
74
+ const allowPattern = [
161
75
  this.$constants('PATTERN').snake_case,
162
76
  this.$constants('PATTERN').camelCase
163
77
  ];
164
- this._assertError(!allowPattern.includes(pattern), "allow pattern ".concat(allowPattern, " only"));
78
+ this._assertError(!allowPattern.includes(pattern), `tspace-mysql support only pattern [${allowPattern}]`);
165
79
  this.$db.set('PATTERN', pattern);
166
80
  return this;
167
- };
81
+ }
168
82
  /**
169
83
  *
170
84
  * Assign in model show data not be deleted
171
85
  * Relations has reference this method
86
+ * @param {string?} column
172
87
  * @return {this} this
173
88
  */
174
- Model.prototype.useSoftDelete = function () {
89
+ useSoftDelete(column) {
175
90
  this.$db.set('SOFT_DELETE', true);
176
- this.$db.set('SOFT_DELETE_RELATIONS', true);
177
- return this;
178
- };
179
- /**
180
- * Assign in model show data not be deleted in relations
181
- * repicate
182
- * @return {this} this
183
- */
184
- Model.prototype.useDisableSoftDeleteInRelations = function () {
185
- this.$db.set('SOFT_DELETE_RELATIONS', false);
91
+ if (column)
92
+ this.$db.set('SOFT_DELETE_FORMAT', column);
186
93
  return this;
187
- };
94
+ }
188
95
  /**
189
96
  *
190
97
  * Assign timestamp when insert || updated created_at and update_at in table
98
+ * @param {object} timestampFormat
99
+ * @property {string} timestampFormat.createdAt - change column of created at
100
+ * @property {string} timestampFormat.updatedAt - change column of updated at
191
101
  * @return {this} this
192
102
  */
193
- Model.prototype.useTimestamp = function (timestampFormat) {
103
+ useTimestamp(timestampFormat) {
194
104
  this.$db.set('TIMESTAMP', true);
195
- if (timestampFormat)
105
+ if (timestampFormat) {
196
106
  this.$db.set('TIMESTAMP_FORMAT', {
197
107
  CREATED_AT: timestampFormat.createdAt,
198
108
  UPDATED_AT: timestampFormat.updatedAt
199
109
  });
110
+ }
200
111
  return this;
201
- };
112
+ }
202
113
  /**
203
114
  *
204
115
  * Assign table name in model
116
+ * @param {string} table table name in database
205
117
  * @return {this} this
206
118
  */
207
- Model.prototype.useTable = function (table) {
208
- this.$db.set('TABLE_NAME', "`".concat(table, "`"));
209
- this.$db.get('SELECT', "".concat(this.$constants('SELECT'), " *"));
210
- this.$db.get('FROM', "".concat(this.$constants('FROM'), "'"));
119
+ useTable(table) {
120
+ this.$db.set('TABLE_NAME', `\`${table}\``);
121
+ this.$db.get('SELECT', `${this.$constants('SELECT')} *`);
122
+ this.$db.get('FROM', `${this.$constants('FROM')}'`);
211
123
  return this;
212
- };
124
+ }
213
125
  /**
214
126
  *
215
127
  * Assign table name in model with signgular pattern
216
128
  * @return {this} this
217
129
  */
218
- Model.prototype.useTableSingular = function () {
219
- var table = this._classToTableName(this.constructor.name, { singular: true });
220
- this.$db.set('TABLE_NAME', "`".concat(pluralize_1.default.singular(table), "`"));
221
- this.$db.get('SELECT', "".concat(this.$constants('SELECT'), " *"));
222
- this.$db.get('FROM', "".concat(this.$constants('FROM'), "'"));
130
+ useTableSingular() {
131
+ const table = this._classToTableName(this.constructor?.name, { singular: true });
132
+ this.$db.set('TABLE_NAME', `\`${pluralize_1.default.singular(table)}\``);
133
+ this.$db.get('SELECT', `${this.$constants('SELECT')} *`);
134
+ this.$db.get('FROM', `${this.$constants('FROM')}'`);
223
135
  return this;
224
- };
136
+ }
225
137
  /**
226
138
  *
227
139
  * Assign table name in model with pluarl pattern
228
140
  * @return {this} this
229
141
  */
230
- Model.prototype.useTablePlural = function () {
231
- var table = this._classToTableName(this.constructor.name);
232
- this.$db.set('TABLE_NAME', "`".concat(pluralize_1.default.plural(table), "`"));
233
- this.$db.get('SELECT', "".concat(this.$constants('SELECT'), " *"));
234
- this.$db.get('FROM', "".concat(this.$constants('FROM'), "'"));
142
+ useTablePlural() {
143
+ const table = this._classToTableName(this.constructor?.name);
144
+ this.$db.set('TABLE_NAME', `\`${pluralize_1.default.plural(table)}\``);
145
+ this.$db.get('SELECT', `${this.$constants('SELECT')} *`);
146
+ this.$db.get('FROM', `${this.$constants('FROM')}'`);
147
+ return this;
148
+ }
149
+ /**
150
+ *
151
+ * boot for initialize of models
152
+ * @return {this} this
153
+ */
154
+ boot() {
235
155
  return this;
236
- };
156
+ }
157
+ /**
158
+ *
159
+ * Clone instance of model
160
+ * @override Method
161
+ * @return {this} this
162
+ */
163
+ clone(instance) {
164
+ if (!(instance instanceof Model)) {
165
+ throw new Error('value is not a instanceof Model');
166
+ }
167
+ const copy = Object.fromEntries(instance.$db.get());
168
+ this.$db.clone(copy);
169
+ return this;
170
+ }
237
171
  /**
238
172
  * Assign ignore delete_at in model
173
+ * @param {boolean} condition
239
174
  * @return {this} this
240
175
  */
241
- Model.prototype.ignoreSoftDelete = function (condition) {
242
- if (condition === void 0) { condition = false; }
176
+ ignoreSoftDelete(condition = false) {
243
177
  this.$db.set('SOFT_DELETE', condition);
244
178
  return this;
245
- };
179
+ }
246
180
  /**
247
- * return ignore delete at all data
181
+ * Assign ignore delete_at in model
182
+ * @param {boolean} condition
248
183
  * @return {this} this
249
184
  */
250
- Model.prototype.disableSoftDelete = function (condition) {
251
- if (condition === void 0) { condition = false; }
185
+ disableSoftDelete(condition = false) {
252
186
  this.$db.set('SOFT_DELETE', condition);
253
187
  return this;
254
- };
188
+ }
189
+ /**
190
+ * Assign build in function to result of data
191
+ * @param {object} func
192
+ * @return {this} this
193
+ */
194
+ registry(func) {
195
+ this.$db.set('REGISTRY', {
196
+ ...func,
197
+ attach: this._attach,
198
+ detach: this._detach
199
+ });
200
+ return this;
201
+ }
255
202
  /**
256
203
  *
257
- * @param {function} func
204
+ * Use relations in registry of model return result of relation query
205
+ * @param {...string} nameRelations ...name registry in models using (hasOne , hasMany , belongsTo , belongsToMany)
258
206
  * @return {this} this
259
207
  */
260
- Model.prototype.registry = function (func) {
261
- this.$db.set('REGISTRY', __assign(__assign({}, func), { attach: this._attach, detach: this._detach }));
208
+ with(...nameRelations) {
209
+ const relations = nameRelations.map((name) => {
210
+ const relation = this.$db.get('RELATION')?.find((data) => data.name === name);
211
+ this._assertError(relation == null, `relation ${name} not be register !`);
212
+ const relationHasExists = Object.values(this.$constants('RELATIONSHIP'))?.includes(relation.relation);
213
+ this._assertError(!relationHasExists, `unknown relationship in [${this.$constants('RELATIONSHIP')}] !`);
214
+ if (relation.query == null)
215
+ relation.query = new relation.model();
216
+ return relation;
217
+ });
218
+ relations.sort((cur, prev) => cur.relation.length - prev.relation.length);
219
+ const setRelations = this.$db.get('WITH').length
220
+ ? [...relations.map((w) => {
221
+ const exists = this.$db.get('WITH').find((r) => r.name === w.name);
222
+ if (exists)
223
+ return null;
224
+ return w;
225
+ }).filter((d) => d != null),
226
+ ...this.$db.get('WITH')]
227
+ : relations;
228
+ this.$db.set('WITH', setRelations);
262
229
  return this;
263
- };
230
+ }
264
231
  /**
265
232
  *
266
- * relation model retrun result of relation query
233
+ * Use relations in registry of model return only exists result of relation query
234
+ * @param {...string} nameRelations if data exists return blank
235
+ * @return {this} this
236
+ */
237
+ withExists(...nameRelations) {
238
+ this.with(...nameRelations);
239
+ this.$db.set('WITH_EXISTS', true);
240
+ return this;
241
+ }
242
+ /**
243
+ *
244
+ * Use relation '${name}' registry of model return callback this query model
245
+ * @param {string} nameRelation name relation in registry in your model
246
+ * @param {function} callback query callback
247
+ * @return {this} this
248
+ */
249
+ withQuery(nameRelation, callback) {
250
+ const relation = this.$db.get('WITH').find((data) => data.name === nameRelation);
251
+ this._assertError(relation == null, `relation ${nameRelation} not be register !`);
252
+ const relationHasExists = Object.values(this.$constants('RELATIONSHIP'))?.includes(relation.relation);
253
+ this._assertError(!relationHasExists, `unknown relationship in [${this.$constants('RELATIONSHIP')}] !`);
254
+ relation.query = callback(new relation.model());
255
+ return this;
256
+ }
257
+ /**
258
+ *
259
+ * Use relations in registry of model retrun result of relation query
267
260
  * @param {...string} nameRelations ...name registry in models using (hasOne , hasMany , belongsTo , belongsToMany)
268
261
  * @return {this} this
269
262
  */
270
- Model.prototype.with = function () {
271
- var _this = this;
272
- var nameRelations = [];
273
- for (var _i = 0; _i < arguments.length; _i++) {
274
- nameRelations[_i] = arguments[_i];
275
- }
276
- var relations = nameRelations.map(function (name) {
277
- var _a;
278
- var relation = (_a = _this.$db.get('RELATION')) === null || _a === void 0 ? void 0 : _a.find(function (data) { return data.name === name; });
279
- if (relation == null)
280
- throw new Error("relation ".concat(name, " not be register !"));
281
- var relationHasExists = Object.values(_this.$constants('RELATIONSHIP')).includes(relation.relation);
282
- if (!relationHasExists) {
283
- throw new Error("unknown relationship in [".concat(_this.$constants('RELATIONSHIP'), "] !"));
284
- }
263
+ relations(...nameRelations) {
264
+ const relations = nameRelations.map((name) => {
265
+ const relation = this.$db.get('RELATION')?.find((data) => data.name === name);
266
+ this._assertError(relation == null, `relation ${name} not be register !`);
267
+ const relationHasExists = Object.values(this.$constants('RELATIONSHIP'))?.includes(relation.relation);
268
+ this._assertError(!relationHasExists, `unknown relationship in [${this.$constants('RELATIONSHIP')}] !`);
285
269
  if (relation.query == null)
286
270
  relation.query = new relation.model();
287
271
  return relation;
288
272
  });
289
- relations.sort(function (cur, prev) { return cur.relation.length - prev.relation.length; });
290
- var setRelations = this.$db.get('WITH').length
291
- ? __spreadArray(__spreadArray([], __read(relations.map(function (w) {
292
- var exists = _this.$db.get('WITH').find(function (r) { return r.name === w.name; });
293
- if (exists)
294
- return null;
295
- return w;
296
- }).filter(function (d) { return d != null; })), false), __read(this.$db.get('WITH')), false) : relations;
273
+ relations.sort((cur, prev) => cur.relation.length - prev.relation.length);
274
+ const setRelations = this.$db.get('WITH').length
275
+ ? [...relations.map((w) => {
276
+ const exists = this.$db.get('WITH').find((r) => r.name === w.name);
277
+ if (exists)
278
+ return null;
279
+ return w;
280
+ }).filter((d) => d != null), ...this.$db.get('WITH')]
281
+ : relations;
297
282
  this.$db.set('WITH', setRelations);
298
283
  return this;
299
- };
284
+ }
300
285
  /**
301
286
  *
302
- * relation model return only exists result of relation query
287
+ * Use relations in registry of model return only exists result of relation query
303
288
  * @param {...string} nameRelations if data exists return blank
304
289
  * @return {this}
305
290
  */
306
- Model.prototype.withExists = function () {
307
- var nameRelations = [];
308
- for (var _i = 0; _i < arguments.length; _i++) {
309
- nameRelations[_i] = arguments[_i];
310
- }
311
- this.with.apply(this, __spreadArray([], __read(nameRelations), false));
291
+ relationsExists(...nameRelations) {
292
+ this.with(...nameRelations);
312
293
  this.$db.set('WITH_EXISTS', true);
313
294
  return this;
314
- };
295
+ }
315
296
  /**
316
297
  *
317
- * deep relation in model return callback query
298
+ * Use relation '${name}' registry of model return callback this query model
318
299
  * @param {string} nameRelation name relation in registry in your model
319
300
  * @param {function} callback query callback
320
301
  * @return {this} this
321
302
  */
322
- Model.prototype.withQuery = function (nameRelation, callback) {
323
- var relation = this.$db.get('WITH').find(function (data) { return data.name === nameRelation; });
324
- if (relation == null)
325
- throw new Error("relation ".concat(nameRelation, " not be register !"));
326
- if (!Object.values(this.$constants('RELATIONSHIP')).includes(relation.relation)) {
327
- throw new Error("unknown relationship in [".concat(this.$constants('RELATIONSHIP'), "] !"));
328
- }
303
+ relationQuery(nameRelation, callback) {
304
+ const relation = this.$db.get('WITH').find((data) => data.name === nameRelation);
305
+ this._assertError(relation == null, `relation ${nameRelation} not be register !`);
306
+ const relationHasExists = Object.values(this.$constants('RELATIONSHIP'))?.includes(relation.relation);
307
+ this._assertError(!relationHasExists, `unknown relationship in [${this.$constants('RELATIONSHIP')}] !`);
329
308
  relation.query = callback(new relation.model());
330
309
  return this;
331
- };
310
+ }
332
311
  /**
333
312
  * Assign the relation in model Objects
334
- * @param {object} relations registry relation in your model
335
- * @param {string} relation.name
336
- * @param {string} relation.as
337
- * @param {class} relation.model
338
- * @param {string} relation.localKey
339
- * @param {string} relation.foreignKey
340
- * @param {string} relation.freezeTable
341
- * @return {this} this
313
+ * @param {object} relations registry relation in your model
314
+ * @property {string} relation.name
315
+ * @property {string} relation.as
316
+ * @property {class} relation.model
317
+ * @property {string} relation.localKey
318
+ * @property {string} relation.foreignKey
319
+ * @property {string} relation.freezeTable
320
+ * @return {this} this
342
321
  */
343
- Model.prototype.hasOne = function (_a) {
344
- var name = _a.name, as = _a.as, model = _a.model, localKey = _a.localKey, foreignKey = _a.foreignKey, freezeTable = _a.freezeTable;
345
- var relation = {
346
- name: name,
347
- model: model,
348
- as: as,
322
+ hasOne({ name, as, model, localKey, foreignKey, freezeTable }) {
323
+ const relation = {
324
+ name,
325
+ model,
326
+ as,
349
327
  relation: this.$constants('RELATIONSHIP').hasOne,
350
- localKey: localKey,
351
- foreignKey: foreignKey,
352
- freezeTable: freezeTable,
328
+ localKey,
329
+ foreignKey,
330
+ freezeTable,
353
331
  query: null
354
332
  };
355
- this.$db.set('RELATION', __spreadArray(__spreadArray([], __read(this.$db.get('RELATION')), false), [relation], false));
333
+ this.$db.set('RELATION', [...this.$db.get('RELATION'), relation]);
356
334
  return this;
357
- };
335
+ }
358
336
  /**
359
337
  * Assign the relation in model Objects
360
- * @param {object} relations registry relation in your model
361
- * @param {string} relation.name
362
- * @param {string} relation.as
363
- * @param {class} relation.model
364
- * @param {string} relation.localKey
365
- * @param {string} relation.foreignKey
366
- * @param {string} relation.freezeTable
367
- * @return {this} this
338
+ * @param {object} relations registry relation in your model
339
+ * @property {string} relation.name
340
+ * @property {string} relation.as
341
+ * @property {class} relation.model
342
+ * @property {string} relation.localKey
343
+ * @property {string} relation.foreignKey
344
+ * @property {string} relation.freezeTable
345
+ * @return {this} this
368
346
  */
369
- Model.prototype.hasMany = function (_a) {
370
- var name = _a.name, as = _a.as, model = _a.model, localKey = _a.localKey, foreignKey = _a.foreignKey, freezeTable = _a.freezeTable;
371
- var relation = {
372
- name: name,
373
- model: model,
374
- as: as,
347
+ hasMany({ name, as, model, localKey, foreignKey, freezeTable }) {
348
+ const relation = {
349
+ name,
350
+ model,
351
+ as,
375
352
  relation: this.$constants('RELATIONSHIP').hasMany,
376
- localKey: localKey,
377
- foreignKey: foreignKey,
378
- freezeTable: freezeTable,
353
+ localKey,
354
+ foreignKey,
355
+ freezeTable,
379
356
  query: null
380
357
  };
381
- this.$db.set('RELATION', __spreadArray(__spreadArray([], __read(this.$db.get('RELATION')), false), [relation], false));
358
+ this.$db.set('RELATION', [...this.$db.get('RELATION'), relation]);
382
359
  return this;
383
- };
360
+ }
384
361
  /**
385
362
  * Assign the relation in model Objects
386
- * @param {object} relations registry relation in your model
387
- * @param {string} relation.name
388
- * @param {string} relation.as
389
- * @param {class} relation.model
390
- * @param {string} relation.localKey
391
- * @param {string} relation.foreignKey
392
- * @param {string} relation.freezeTable
393
- * @return {this} this
363
+ * @param {object} relations registry relation in your model
364
+ * @property {string} relation.name
365
+ * @property {string} relation.as
366
+ * @property {class} relation.model
367
+ * @property {string} relation.localKey
368
+ * @property {string} relation.foreignKey
369
+ * @property {string} relation.freezeTable
370
+ * @return {this} this
394
371
  */
395
- Model.prototype.belongsTo = function (_a) {
396
- var name = _a.name, as = _a.as, model = _a.model, localKey = _a.localKey, foreignKey = _a.foreignKey, freezeTable = _a.freezeTable;
397
- var relation = {
398
- name: name,
399
- as: as,
400
- model: model,
372
+ belongsTo({ name, as, model, localKey, foreignKey, freezeTable }) {
373
+ const relation = {
374
+ name,
375
+ as,
376
+ model,
401
377
  relation: this.$constants('RELATIONSHIP').belongsTo,
402
- localKey: localKey,
403
- foreignKey: foreignKey,
404
- freezeTable: freezeTable,
378
+ localKey,
379
+ foreignKey,
380
+ freezeTable,
405
381
  query: null
406
382
  };
407
- this.$db.set('RELATION', __spreadArray(__spreadArray([], __read(this.$db.get('RELATION')), false), [relation], false));
383
+ this.$db.set('RELATION', [...this.$db.get('RELATION'), relation]);
408
384
  return this;
409
- };
385
+ }
410
386
  /**
411
387
  * Assign the relation in model Objects
412
- * @param {object} relations registry relation in your model
413
- * @param {string} relation.name
414
- * @param {string} relation.as
415
- * @param {class} relation.model
416
- * @param {string} relation.localKey
417
- * @param {string} relation.foreignKey
418
- * @param {string} relation.freezeTable
419
- * @return {this} this
388
+ * @param {object} relations registry relation in your model
389
+ * @property {string} relation.name
390
+ * @property {string} relation.as
391
+ * @property {class} relation.model
392
+ * @property {string} relation.localKey
393
+ * @property {string} relation.foreignKey
394
+ * @property {string} relation.freezeTable
395
+ * @return {this} this
420
396
  */
421
- Model.prototype.belongsToMany = function (_a) {
422
- var name = _a.name, as = _a.as, model = _a.model, localKey = _a.localKey, foreignKey = _a.foreignKey, freezeTable = _a.freezeTable;
423
- var relation = {
424
- name: name,
425
- model: model,
426
- as: as,
397
+ belongsToMany({ name, as, model, localKey, foreignKey, freezeTable }) {
398
+ const relation = {
399
+ name,
400
+ model,
401
+ as,
427
402
  relation: this.$constants('RELATIONSHIP').belongsToMany,
428
- localKey: localKey,
429
- foreignKey: foreignKey,
430
- freezeTable: freezeTable,
403
+ localKey,
404
+ foreignKey,
405
+ freezeTable,
431
406
  query: null
432
407
  };
433
- this.$db.set('RELATION', __spreadArray(__spreadArray([], __read(this.$db.get('RELATION')), false), [relation], false));
408
+ this.$db.set('RELATION', [...this.$db.get('RELATION'), relation]);
434
409
  return this;
435
- };
436
- /**
437
- * Assign the relation in model Objects
438
- * @param {object} relations registry relation in your model
439
- * @param {string?} relation.name
440
- * @param {string} relation.as
441
- * @param {class} relation.model
442
- * @param {string} relation.localKey
443
- * @param {string} relation.foreignKey
444
- * @param {string} relation.freezeTable
445
- * @return {this} this
446
- */
447
- Model.prototype.hasOneQuery = function (_a, callback) {
448
- var name = _a.name, as = _a.as, model = _a.model, localKey = _a.localKey, foreignKey = _a.foreignKey, freezeTable = _a.freezeTable;
449
- var nameRelation = name == null
410
+ }
411
+ /**
412
+ * Assign the relation in model Objects
413
+ * @param {object} relations registry relation in your model
414
+ * @property {string} relation.name
415
+ * @property {string} relation.as
416
+ * @property {class} relation.model
417
+ * @property {string} relation.localKey
418
+ * @property {string} relation.foreignKey
419
+ * @property {string} relation.freezeTable
420
+ * @param {function} callback callback query relation of model
421
+ * @return {this} this
422
+ */
423
+ hasOneQuery({ name, as, model, localKey, foreignKey, freezeTable }, callback) {
424
+ const nameRelation = name == null
450
425
  ? this._functionRelationName()
451
426
  : String(name);
452
- var relation = {
427
+ const relation = {
453
428
  name: nameRelation,
454
- model: model,
455
- as: as,
429
+ model,
430
+ as,
456
431
  relation: this.$constants('RELATIONSHIP').hasOne,
457
- localKey: localKey,
458
- foreignKey: foreignKey,
459
- freezeTable: freezeTable,
432
+ localKey,
433
+ foreignKey,
434
+ freezeTable,
460
435
  query: null
461
436
  };
462
- this.$db.set('RELATION', __spreadArray(__spreadArray([], __read(this.$db.get('RELATION')), false), [relation], false));
463
- this.with(nameRelation);
464
- var r = this.$db.get('WITH').find(function (data) { return data.name === nameRelation; });
465
- this._assertError(r == null, "relation ".concat(nameRelation, " not be register !"));
466
- this._assertError(!Object.values(this.$constants('RELATIONSHIP')).includes(r.relation), "unknown relationship in [".concat(this.$constants('RELATIONSHIP'), "] !"));
437
+ const r = this._handleRelationsQuery(nameRelation, relation);
467
438
  r.query = callback(new r.model());
468
439
  return this;
469
- };
440
+ }
470
441
  /**
471
442
  * Assign the relation in model Objects
472
- * @param {object} relations registry relation in your model
473
- * @param {string?} relation.name
474
- * @param {string} relation.as
475
- * @param {class} relation.model
476
- * @param {string} relation.localKey
477
- * @param {string} relation.foreignKey
478
- * @param {string} relation.freezeTable
479
- * @return {this} this
443
+ * @param {object} relations registry relation in your model
444
+ * @property {string} relation.name
445
+ * @property {string} relation.as
446
+ * @property {class} relation.model
447
+ * @property {string} relation.localKey
448
+ * @property {string} relation.foreignKey
449
+ * @property {string} relation.freezeTable
450
+ * @param {function} callback callback query relation of model
451
+ * @return {this} this
480
452
  */
481
- Model.prototype.hasManyQuery = function (_a, callback) {
482
- var name = _a.name, as = _a.as, model = _a.model, localKey = _a.localKey, foreignKey = _a.foreignKey, freezeTable = _a.freezeTable;
483
- var nameRelation = name == null
453
+ hasManyQuery({ name, as, model, localKey, foreignKey, freezeTable }, callback) {
454
+ const nameRelation = name == null
484
455
  ? this._functionRelationName()
485
456
  : String(name);
486
- var relation = {
457
+ const relation = {
487
458
  name: nameRelation,
488
- model: model,
489
- as: as,
459
+ model,
460
+ as,
490
461
  relation: this.$constants('RELATIONSHIP').hasMany,
491
- localKey: localKey,
492
- foreignKey: foreignKey,
493
- freezeTable: freezeTable,
462
+ localKey,
463
+ foreignKey,
464
+ freezeTable,
494
465
  query: null
495
466
  };
496
- this.$db.set('RELATION', __spreadArray(__spreadArray([], __read(this.$db.get('RELATION')), false), [relation], false));
497
- this.with(nameRelation);
498
- var r = this.$db.get('WITH').find(function (data) { return data.name === nameRelation; });
499
- this._assertError(r == null, "relation ".concat(nameRelation, " not be register !"));
500
- this._assertError(!Object.values(this.$constants('RELATIONSHIP')).includes(r.relation), "unknown relationship in [".concat(this.$constants('RELATIONSHIP'), "] !"));
467
+ const r = this._handleRelationsQuery(nameRelation, relation);
501
468
  r.query = callback(new r.model());
502
469
  return this;
503
- };
470
+ }
504
471
  /**
505
472
  * Assign the relation in model Objects
506
- * @param {object} relations registry relation in your model
507
- * @param {string} relation.name
508
- * @param {string} relation.as
509
- * @param {class} relation.model
510
- * @param {string} relation.localKey
511
- * @param {string} relation.foreignKey
512
- * @param {string} relation.freezeTable
513
- * @return {this} this
473
+ * @param {object} relations registry relation in your model
474
+ * @property {string} relation.name
475
+ * @property {string} relation.as
476
+ * @property {class} relation.model
477
+ * @property {string} relation.localKey
478
+ * @property {string} relation.foreignKey
479
+ * @property {string} relation.freezeTable
480
+ * @param {function} callback callback query relation of model
481
+ * @return {this} this
514
482
  */
515
- Model.prototype.belongsToQuery = function (_a, callback) {
516
- var name = _a.name, as = _a.as, model = _a.model, localKey = _a.localKey, foreignKey = _a.foreignKey, freezeTable = _a.freezeTable;
517
- var nameRelation = name == null
483
+ belongsToQuery({ name, as, model, localKey, foreignKey, freezeTable }, callback) {
484
+ const nameRelation = name == null
518
485
  ? this._functionRelationName()
519
486
  : String(name);
520
- var relation = {
487
+ const relation = {
521
488
  name: nameRelation,
522
- model: model,
523
- as: as,
489
+ model,
490
+ as,
524
491
  relation: this.$constants('RELATIONSHIP').belongsTo,
525
- localKey: localKey,
526
- foreignKey: foreignKey,
527
- freezeTable: freezeTable,
492
+ localKey,
493
+ foreignKey,
494
+ freezeTable,
528
495
  query: null
529
496
  };
530
- this.$db.set('RELATION', __spreadArray(__spreadArray([], __read(this.$db.get('RELATION')), false), [relation], false));
531
- this.with(nameRelation);
532
- var r = this.$db.get('WITH').find(function (data) { return data.name === nameRelation; });
533
- this._assertError(r == null, "relation ".concat(nameRelation, " not be register !"));
534
- this._assertError(!Object.values(this.$constants('RELATIONSHIP')).includes(r.relation), "unknown relationship in [".concat(this.$constants('RELATIONSHIP'), "] !"));
497
+ const r = this._handleRelationsQuery(nameRelation, relation);
535
498
  r.query = callback(new r.model());
536
499
  return this;
537
- };
500
+ }
538
501
  /**
539
502
  * Assign the relation in model Objects
540
- * @param {object} relations registry relation in your model
541
- * @param {string} relation.name
542
- * @param {string} relation.as
543
- * @param {class} relation.model
544
- * @param {string} relation.localKey
545
- * @param {string} relation.foreignKey
546
- * @param {string} relation.freezeTable
547
- * @return {this} this
503
+ * @param {object} relations registry relation in your model
504
+ * @property {string} relation.name
505
+ * @property {string} relation.as
506
+ * @property {class} relation.model
507
+ * @property {string} relation.localKey
508
+ * @property {string} relation.foreignKey
509
+ * @property {string} relation.freezeTable
510
+ * @param {function} callback callback query relation of model
511
+ * @return {this} this
548
512
  */
549
- Model.prototype.belongsToManyQuery = function (_a, callback) {
550
- var name = _a.name, as = _a.as, model = _a.model, localKey = _a.localKey, foreignKey = _a.foreignKey, freezeTable = _a.freezeTable;
551
- var nameRelation = name == null
513
+ belongsToManyQuery({ name, as, model, localKey, foreignKey, freezeTable }, callback) {
514
+ const nameRelation = name == null
552
515
  ? this._functionRelationName()
553
516
  : String(name);
554
- var relation = {
517
+ const relation = {
555
518
  name: nameRelation,
556
- model: model,
557
- as: as,
519
+ model,
520
+ as,
558
521
  relation: this.$constants('RELATIONSHIP').belongsToMany,
559
- localKey: localKey,
560
- foreignKey: foreignKey,
561
- freezeTable: freezeTable,
522
+ localKey,
523
+ foreignKey,
524
+ freezeTable,
562
525
  query: null
563
526
  };
564
- this.$db.set('RELATION', __spreadArray(__spreadArray([], __read(this.$db.get('RELATION')), false), [relation], false));
565
- this.with(nameRelation);
566
- var r = this.$db.get('WITH').find(function (data) { return data.name === nameRelation; });
567
- this._assertError(r == null, "relation ".concat(nameRelation, " not be register !"));
568
- this._assertError(!Object.values(this.$constants('RELATIONSHIP')).includes(r.relation), "unknown relationship in [".concat(this.$constants('RELATIONSHIP'), "] !"));
527
+ const r = this._handleRelationsQuery(nameRelation, relation);
569
528
  r.query = callback(new r.model());
570
529
  return this;
571
- };
530
+ }
572
531
  /**
573
532
  * return only in trashed (data has been remove)
574
533
  * @return {promise}
575
534
  */
576
- Model.prototype.trashed = function () {
577
- return __awaiter(this, void 0, void 0, function () {
578
- var sql;
579
- return __generator(this, function (_a) {
580
- switch (_a.label) {
581
- case 0:
582
- this.whereNotNull(this._valuePattern('deletedAt'));
583
- sql = this._queryGenrateModel();
584
- return [4 /*yield*/, this._execute(sql, 'GET')];
585
- case 1: return [2 /*return*/, _a.sent()];
586
- }
587
- });
588
- });
589
- };
535
+ async trashed() {
536
+ this.whereNotNull(this._valuePattern(this.$db.get('SOFT_DELETE_FORMAT')));
537
+ const sql = this._buildQueryModel();
538
+ return await this._execute({ sql, type: 'GET' });
539
+ }
590
540
  /**
591
541
  * return all only in trashed (data has been remove)
592
542
  * @return {promise}
593
543
  */
594
- Model.prototype.onlyTrashed = function () {
595
- return __awaiter(this, void 0, void 0, function () {
596
- var sql;
597
- return __generator(this, function (_a) {
598
- switch (_a.label) {
599
- case 0:
600
- this.$db.set('SOFT_DELETE', false);
601
- this.whereNotNull(this._valuePattern('deletedAt'));
602
- sql = this._queryGenrateModel();
603
- return [4 /*yield*/, this._execute(sql, 'GET')];
604
- case 1: return [2 /*return*/, _a.sent()];
605
- }
606
- });
607
- });
608
- };
544
+ async onlyTrashed() {
545
+ this.$db.set('SOFT_DELETE', false);
546
+ this.whereNotNull(this._valuePattern(this.$db.get('SOFT_DELETE_FORMAT')));
547
+ const sql = this._buildQueryModel();
548
+ return await this._execute({ sql, type: 'GET' });
549
+ }
609
550
  /**
610
551
  * restore data in trashed
611
552
  * @return {promise}
612
553
  */
613
- Model.prototype.restore = function () {
614
- return __awaiter(this, void 0, void 0, function () {
615
- var updatedAt, deletedAt, query;
616
- return __generator(this, function (_a) {
617
- switch (_a.label) {
618
- case 0:
619
- updatedAt = this._valuePattern('updatedAt');
620
- deletedAt = this._valuePattern('deletedAt');
621
- query = this.$db.get('TIMESTAMP')
622
- ? "".concat(deletedAt, " = NULL , ").concat(updatedAt, " = '").concat(this.$utils.timestamp(), "'")
623
- : "".concat(deletedAt, " = NULL");
624
- this.$db.set('UPDATE', [
625
- "".concat(this.$constants('UPDATE')),
626
- "".concat(this.$db.get('TABLE_NAME')),
627
- "SET ".concat(query)
628
- ].join(' '));
629
- this.$db.set('SAVE', 'UPDATE');
630
- return [4 /*yield*/, this.save()];
631
- case 1: return [2 /*return*/, _a.sent()];
632
- }
633
- });
634
- });
635
- };
554
+ async restore() {
555
+ const updatedAt = this._valuePattern(this.$db.get('TIMESTAMP_FORMAT').UPDATED_AT);
556
+ const deletedAt = this._valuePattern(this.$db.get('SOFT_DELETE_FORMAT'));
557
+ const query = this.$db.get('TIMESTAMP')
558
+ ? `${deletedAt} = NULL , ${updatedAt} = '${this.$utils.timestamp()}'`
559
+ : `${deletedAt} = NULL`;
560
+ this.$db.set('UPDATE', [
561
+ `${this.$constants('UPDATE')}`,
562
+ `${this.$db.get('TABLE_NAME')}`,
563
+ `SET ${query}`
564
+ ].join(' '));
565
+ this.$db.set('SAVE', 'UPDATE');
566
+ return await this.save();
567
+ }
636
568
  /**
637
569
  *
638
570
  * @override Method
639
571
  * @return {string}
640
572
  */
641
- Model.prototype.toString = function () {
642
- return this._queryGenrateModel();
643
- };
573
+ toString() {
574
+ return this._buildQueryModel();
575
+ }
644
576
  /**
645
577
  *
646
578
  * @override Method
647
579
  * @return {string}
648
580
  */
649
- Model.prototype.toSQL = function () {
650
- return this._queryGenrateModel();
651
- };
581
+ toSQL() {
582
+ return this._buildQueryModel();
583
+ }
652
584
  /**
653
585
  *
654
586
  * @override Method
655
587
  * @return {promise<string>}
656
588
  */
657
- Model.prototype.toJSON = function () {
658
- return __awaiter(this, void 0, void 0, function () {
659
- var sql, result;
660
- return __generator(this, function (_a) {
661
- switch (_a.label) {
662
- case 0:
663
- sql = this._queryGenrateModel();
664
- return [4 /*yield*/, this._queryStatementModel(sql)];
665
- case 1:
666
- result = _a.sent();
667
- if (this.$db.get('HIDDEN').length)
668
- this._hiddenColumnModel(result);
669
- return [2 /*return*/, JSON.stringify(result)];
670
- }
671
- });
672
- });
673
- };
589
+ async toJSON() {
590
+ const sql = this._buildQueryModel();
591
+ const result = await this._queryStatementModel(sql);
592
+ if (this.$db.get('HIDDEN').length)
593
+ this._hiddenColumnModel(result);
594
+ return JSON.stringify(result);
595
+ }
674
596
  /**
675
597
  *
676
598
  * @override Method
677
599
  * @param {string=} column [column=id]
678
600
  * @return {promise<Array>}
679
601
  */
680
- Model.prototype.toArray = function (column) {
681
- if (column === void 0) { column = 'id'; }
682
- return __awaiter(this, void 0, void 0, function () {
683
- var sql, result, toArray;
684
- return __generator(this, function (_a) {
685
- switch (_a.label) {
686
- case 0:
687
- this.$db.set('SELECT', "".concat(this.$constants('SELECT'), " ").concat(column));
688
- sql = this._queryGenrateModel();
689
- return [4 /*yield*/, this._queryStatementModel(sql)];
690
- case 1:
691
- result = _a.sent();
692
- toArray = result.map(function (data) { return data[column]; });
693
- return [2 /*return*/, toArray];
694
- }
695
- });
696
- });
697
- };
602
+ async toArray(column = 'id') {
603
+ this.$db.set('SELECT', `${this.$constants('SELECT')} ${column}`);
604
+ const sql = this._buildQueryModel();
605
+ const result = await this._queryStatementModel(sql);
606
+ const toArray = result.map((data) => data[column]);
607
+ return toArray;
608
+ }
698
609
  /**
699
610
  *
700
611
  * @override Method
701
612
  * @param {string=} column [column=id]
702
613
  * @return {promise<number>}
703
614
  */
704
- Model.prototype.avg = function (column) {
705
- var _a;
706
- if (column === void 0) { column = 'id'; }
707
- return __awaiter(this, void 0, void 0, function () {
708
- var sql, result;
709
- return __generator(this, function (_b) {
710
- switch (_b.label) {
711
- case 0:
712
- this.$db.set('SELECT', [
713
- "".concat(this.$constants('SELECT')),
714
- "".concat(this.$constants('AVG'), "(").concat(column, ")"),
715
- "".concat(this.$constants('AS'), " avg")
716
- ].join(' '));
717
- sql = this._queryGenrateModel();
718
- return [4 /*yield*/, this._queryStatementModel(sql)];
719
- case 1:
720
- result = _b.sent();
721
- return [2 /*return*/, ((_a = result.shift()) === null || _a === void 0 ? void 0 : _a.avg) || 0];
722
- }
723
- });
724
- });
725
- };
615
+ async avg(column = 'id') {
616
+ this.$db.set('SELECT', [
617
+ `${this.$constants('SELECT')}`,
618
+ `${this.$constants('AVG')}(${column})`,
619
+ `${this.$constants('AS')} avg`
620
+ ].join(' '));
621
+ const sql = this._buildQueryModel();
622
+ const result = await this._queryStatementModel(sql);
623
+ return result?.shift()?.avg || 0;
624
+ }
726
625
  /**
727
626
  *
728
627
  * @override Method
729
- * @param {string=} column [column=id]
628
+ * @param {string} column [column=id]
730
629
  * @return {promise<number>}
731
630
  */
732
- Model.prototype.sum = function (column) {
733
- var _a;
734
- if (column === void 0) { column = 'id'; }
735
- return __awaiter(this, void 0, void 0, function () {
736
- var sql, result;
737
- return __generator(this, function (_b) {
738
- switch (_b.label) {
739
- case 0:
740
- this.$db.set('SELECT', [
741
- "".concat(this.$constants('SELECT')),
742
- "".concat(this.$constants('SUM'), "(").concat(column, ")"),
743
- "".concat(this.$constants('AS'), " sum")
744
- ].join(' '));
745
- sql = this._queryGenrateModel();
746
- return [4 /*yield*/, this._queryStatementModel(sql)];
747
- case 1:
748
- result = _b.sent();
749
- return [2 /*return*/, ((_a = result.shift()) === null || _a === void 0 ? void 0 : _a.sum) || 0];
750
- }
751
- });
752
- });
753
- };
631
+ async sum(column = 'id') {
632
+ this.$db.set('SELECT', [
633
+ `${this.$constants('SELECT')}`,
634
+ `${this.$constants('SUM')}(${column})`,
635
+ `${this.$constants('AS')} sum`
636
+ ].join(' '));
637
+ const sql = this._buildQueryModel();
638
+ const result = await this._queryStatementModel(sql);
639
+ return result?.shift()?.sum || 0;
640
+ }
754
641
  /**
755
642
  *
756
643
  * @override Method
757
644
  * @param {string=} column [column=id]
758
645
  * @return {promise<number>}
759
646
  */
760
- Model.prototype.max = function (column) {
761
- var _a;
762
- if (column === void 0) { column = 'id'; }
763
- return __awaiter(this, void 0, void 0, function () {
764
- var sql, result;
765
- return __generator(this, function (_b) {
766
- switch (_b.label) {
767
- case 0:
768
- this.$db.set('SELECT', [
769
- "".concat(this.$constants('SELECT')),
770
- "".concat(this.$constants('MAX'), "(").concat(column, ")"),
771
- "".concat(this.$constants('AS'), " max")
772
- ].join(' '));
773
- sql = this._queryGenrateModel();
774
- return [4 /*yield*/, this._queryStatementModel(sql)];
775
- case 1:
776
- result = _b.sent();
777
- return [2 /*return*/, ((_a = result.shift()) === null || _a === void 0 ? void 0 : _a.max) || 0];
778
- }
779
- });
780
- });
781
- };
647
+ async max(column = 'id') {
648
+ this.$db.set('SELECT', [
649
+ `${this.$constants('SELECT')}`,
650
+ `${this.$constants('MAX')}(${column})`,
651
+ `${this.$constants('AS')} max`
652
+ ].join(' '));
653
+ const sql = this._buildQueryModel();
654
+ const result = await this._queryStatementModel(sql);
655
+ return result?.shift()?.max || 0;
656
+ }
782
657
  /**
783
658
  *
784
659
  * @override Method
785
660
  * @param {string=} column [column=id]
786
661
  * @return {promise<number>}
787
662
  */
788
- Model.prototype.min = function (column) {
789
- var _a;
790
- if (column === void 0) { column = 'id'; }
791
- return __awaiter(this, void 0, void 0, function () {
792
- var sql, result;
793
- return __generator(this, function (_b) {
794
- switch (_b.label) {
795
- case 0:
796
- this.$db.set('SELECT', [
797
- "".concat(this.$constants('SELECT')),
798
- "".concat(this.$constants('MIN'), "(").concat(column, ")"),
799
- "".concat(this.$constants('AS'), " min")
800
- ].join(' '));
801
- sql = this._queryGenrateModel();
802
- return [4 /*yield*/, this._queryStatementModel(sql)];
803
- case 1:
804
- result = _b.sent();
805
- return [2 /*return*/, ((_a = result.shift()) === null || _a === void 0 ? void 0 : _a.min) || 0];
806
- }
807
- });
808
- });
809
- };
663
+ async min(column = 'id') {
664
+ this.$db.set('SELECT', [
665
+ `${this.$constants('SELECT')}`,
666
+ `${this.$constants('MIN')}(${column})`,
667
+ `${this.$constants('AS')} min`
668
+ ].join(' '));
669
+ const sql = this._buildQueryModel();
670
+ const result = await this._queryStatementModel(sql);
671
+ return result?.shift()?.min || 0;
672
+ }
810
673
  /**
811
674
  *
812
675
  * @override Method
813
676
  * @param {string=} column [column=id]
814
677
  * @return {promise<number>}
815
678
  */
816
- Model.prototype.count = function (column) {
817
- var _a;
818
- if (column === void 0) { column = 'id'; }
819
- return __awaiter(this, void 0, void 0, function () {
820
- var sql, result;
821
- return __generator(this, function (_b) {
822
- switch (_b.label) {
823
- case 0:
824
- this.$db.set('SELECT', "".concat(this.$constants('SELECT'), " ").concat(this.$constants('COUNT'), "(").concat(column, ") ").concat(this.$constants('AS'), " total"));
825
- sql = this._queryGenrateModel();
826
- return [4 /*yield*/, this._queryStatementModel(sql)];
827
- case 1:
828
- result = _b.sent();
829
- return [2 /*return*/, ((_a = result.shift()) === null || _a === void 0 ? void 0 : _a.total) || 0];
830
- }
831
- });
832
- });
833
- };
679
+ async count(column = 'id') {
680
+ this.$db.set('SELECT', [
681
+ `${this.$constants('SELECT')}`,
682
+ `${this.$constants('COUNT')}(${column})`,
683
+ `${this.$constants('AS')} total`
684
+ ].join(' '));
685
+ const sql = this._buildQueryModel();
686
+ const result = await this._queryStatementModel(sql);
687
+ return result?.shift()?.total || 0;
688
+ }
834
689
  /**
835
690
  * delete data from the database
836
691
  * @override Method
837
692
  * @return {promise<boolean>}
838
693
  */
839
- Model.prototype.delete = function () {
840
- var _a, _b;
841
- return __awaiter(this, void 0, void 0, function () {
842
- var deletedAt, query, sql, updatedAt, result_1, result;
843
- return __generator(this, function (_c) {
844
- switch (_c.label) {
845
- case 0:
846
- if (!this.$db.get('WHERE'))
847
- throw new Error("Can't delete without where condition");
848
- if (!this.$db.get('SOFT_DELETE')) return [3 /*break*/, 2];
849
- deletedAt = this._valuePattern('deletedAt');
850
- query = "".concat(deletedAt, " = '").concat(this.$utils.timestamp(), "'");
851
- sql = [
852
- "".concat(this.$constants('UPDATE')),
853
- "".concat(this.$db.get('TABLE_NAME')),
854
- "".concat(this.$constants('SET')),
855
- "".concat(query)
856
- ].join(' ');
857
- if (this.$db.get('TIMESTAMP')) {
858
- updatedAt = this._valuePattern('updatedAt');
859
- sql = "".concat(sql, " , ").concat(updatedAt, " = '").concat(this.$utils.timestamp(), "'");
860
- }
861
- this.$db.set('UPDATE', "".concat(sql, " ").concat(this.$db.get('WHERE')));
862
- return [4 /*yield*/, this._actionStatementModel({ sql: this.$db.get('UPDATE') })];
863
- case 1:
864
- result_1 = _c.sent();
865
- return [2 /*return*/, (_a = !!result_1) !== null && _a !== void 0 ? _a : false];
866
- case 2:
867
- this.$db.set('DELETE', [
868
- "".concat(this.$constants('DELETE')),
869
- "".concat(this.$db.get('FROM')),
870
- "".concat(this.$db.get('TABLE_NAME')),
871
- "".concat(this.$db.get('WHERE'))
872
- ].join(' '));
873
- return [4 /*yield*/, this._actionStatementModel({ sql: this.$db.get('DELETE') })];
874
- case 3:
875
- result = _c.sent();
876
- return [2 /*return*/, (_b = !!result) !== null && _b !== void 0 ? _b : false];
877
- }
878
- });
879
- });
880
- };
694
+ async delete() {
695
+ if (!this.$db.get('WHERE'))
696
+ throw new Error("can't delete without where condition");
697
+ if (this.$db.get('SOFT_DELETE')) {
698
+ const deletedAt = this._valuePattern(this.$db.get('SOFT_DELETE_FORMAT'));
699
+ const query = `${deletedAt} = '${this.$utils.timestamp()}'`;
700
+ let sql = [
701
+ `${this.$constants('UPDATE')}`,
702
+ `${this.$db.get('TABLE_NAME')}`,
703
+ `${this.$constants('SET')}`,
704
+ `${query}`
705
+ ].join(' ');
706
+ if (this.$db.get('TIMESTAMP')) {
707
+ const updatedAt = this._valuePattern(this.$db.get('TIMESTAMP_FORMAT').UPDATED_AT);
708
+ sql = `${sql} , ${updatedAt} = '${this.$utils.timestamp()}'`;
709
+ }
710
+ this.$db.set('UPDATE', `${sql} ${this.$db.get('WHERE')}`);
711
+ const result = await this._actionStatementModel({ sql: this.$db.get('UPDATE') });
712
+ return !!result ?? false;
713
+ }
714
+ this.$db.set('DELETE', [
715
+ `${this.$constants('DELETE')}`,
716
+ `${this.$db.get('FROM')}`,
717
+ `${this.$db.get('TABLE_NAME')}`,
718
+ `${this.$db.get('WHERE')}`
719
+ ].join(' '));
720
+ const result = await this._actionStatementModel({ sql: this.$db.get('DELETE') });
721
+ return !!result ?? false;
722
+ }
881
723
  /**
882
724
  *
883
725
  * @override Method
884
- * @return {promise<object | null>}
726
+ * @return {promise<any>}
885
727
  */
886
- Model.prototype.first = function () {
887
- var _a;
888
- return __awaiter(this, void 0, void 0, function () {
889
- var sql;
890
- return __generator(this, function (_b) {
891
- switch (_b.label) {
892
- case 0:
893
- if (!((_a = this.$db.get('EXCEPT')) === null || _a === void 0 ? void 0 : _a.length)) return [3 /*break*/, 2];
894
- return [4 /*yield*/, this._exceptColumns()];
895
- case 1:
896
- _b.sent();
897
- _b.label = 2;
898
- case 2:
899
- sql = this._queryGenrateModel();
900
- if (!!sql.includes(this.$constants('LIMIT'))) return [3 /*break*/, 4];
901
- sql = "".concat(sql, " ").concat(this.$constants('LIMIT'), " 1");
902
- return [4 /*yield*/, this._execute(sql, 'FIRST')];
903
- case 3: return [2 /*return*/, _b.sent()];
904
- case 4:
905
- sql = sql.replace(this.$db.get('LIMIT'), "".concat(this.$constants('LIMIT'), " 1"));
906
- return [4 /*yield*/, this._execute(sql, 'FIRST')];
907
- case 5: return [2 /*return*/, _b.sent()];
908
- }
909
- });
910
- });
911
- };
728
+ async first() {
729
+ if (this.$db.get('EXCEPT')?.length)
730
+ await this._exceptColumns();
731
+ let sql = this._buildQueryModel();
732
+ if (!sql.includes(this.$constants('LIMIT'))) {
733
+ sql = `${sql} ${this.$constants('LIMIT')} 1`;
734
+ if (this.$db.get('WITH_EXISTS')) {
735
+ sql = this._queryRelationsExists();
736
+ }
737
+ return await this._execute({ sql, type: 'FIRST' });
738
+ }
739
+ sql = sql.replace(this.$db.get('LIMIT'), `${this.$constants('LIMIT')} 1`);
740
+ if (this.$db.get('WITH_EXISTS')) {
741
+ sql = this._queryRelationsExists();
742
+ }
743
+ return await this._execute({ sql, type: 'FIRST' });
744
+ }
912
745
  /**
913
746
  *
914
747
  * @override Method
915
- * @return {promise<object | null>}
748
+ * @return {promise<any>}
916
749
  */
917
- Model.prototype.findOne = function () {
918
- return __awaiter(this, void 0, void 0, function () {
919
- return __generator(this, function (_a) {
920
- switch (_a.label) {
921
- case 0: return [4 /*yield*/, this.first()];
922
- case 1: return [2 /*return*/, _a.sent()];
923
- }
924
- });
925
- });
926
- };
750
+ async findOne() {
751
+ return await this.first();
752
+ }
927
753
  /**
928
754
  *
929
755
  * @override Method
930
- * @return {promise<array>}
756
+ * @return {promise<object | Error>}
931
757
  */
932
- Model.prototype.all = function () {
933
- return __awaiter(this, void 0, void 0, function () {
934
- var sql, result;
935
- return __generator(this, function (_a) {
936
- switch (_a.label) {
937
- case 0:
938
- sql = [
939
- "".concat(this.$constants('SELECT')),
940
- "*",
941
- "".concat(this.$constants('FROM')),
942
- "".concat(this.$db.get('TABLE_NAME'))
943
- ].join(' ');
944
- return [4 /*yield*/, this._queryStatementModel(sql)];
945
- case 1:
946
- result = _a.sent();
947
- return [2 /*return*/, result];
948
- }
949
- });
950
- });
951
- };
758
+ async firstOrError(message, options) {
759
+ if (this.$db.get('EXCEPT')?.length)
760
+ await this._exceptColumns();
761
+ let sql = this._buildQueryModel();
762
+ if (!sql.includes(this.$constants('LIMIT'))) {
763
+ sql = `${sql} ${this.$constants('LIMIT')} 1`;
764
+ return await this._execute({ sql, type: 'FIRST_OR_ERROR', message, options });
765
+ }
766
+ sql = sql.replace(this.$db.get('LIMIT'), `${this.$constants('LIMIT')} 1`);
767
+ if (this.$db.get('WITH_EXISTS')) {
768
+ sql = this._queryRelationsExists();
769
+ }
770
+ return await this._execute({ sql, type: 'FIRST_OR_ERROR', message, options });
771
+ }
952
772
  /**
953
773
  *
954
774
  * @override Method
955
- * @return {promise<object | null>}
775
+ * @return {promise<any>}
956
776
  */
957
- Model.prototype.find = function (id) {
958
- return __awaiter(this, void 0, void 0, function () {
959
- var sql, result;
960
- return __generator(this, function (_a) {
961
- switch (_a.label) {
962
- case 0:
963
- sql = [
964
- "".concat(this.$constants('SELECT')),
965
- "*",
966
- "".concat(this.$constants('FROM')),
967
- "".concat(this.$db.get('TABLE_NAME')),
968
- "".concat(this.$constants('WHERE')),
969
- "".concat(this.$constants('PRIMARY_KEY'), " = ").concat(id)
970
- ].join(' ');
971
- return [4 /*yield*/, this._queryStatementModel(sql)];
972
- case 1:
973
- result = _a.sent();
974
- return [2 /*return*/, result.shift() || null];
975
- }
976
- });
977
- });
978
- };
777
+ async findOneOrError(message, options) {
778
+ return this.firstOrError(message, options);
779
+ }
979
780
  /**
980
781
  *
981
782
  * @override Method
982
783
  * @return {promise<array>}
983
784
  */
984
- Model.prototype.get = function () {
985
- var _a;
986
- return __awaiter(this, void 0, void 0, function () {
987
- var sql;
988
- return __generator(this, function (_b) {
989
- switch (_b.label) {
990
- case 0:
991
- if (!((_a = this.$db.get('EXCEPT')) === null || _a === void 0 ? void 0 : _a.length)) return [3 /*break*/, 2];
992
- return [4 /*yield*/, this._exceptColumns()];
993
- case 1:
994
- _b.sent();
995
- _b.label = 2;
996
- case 2:
997
- sql = this._queryGenrateModel();
998
- return [4 /*yield*/, this._execute(sql, 'GET')];
999
- case 3: return [2 /*return*/, _b.sent()];
1000
- }
1001
- });
1002
- });
1003
- };
785
+ async all() {
786
+ const sql = [
787
+ `${this.$constants('SELECT')}`,
788
+ `*`,
789
+ `${this.$constants('FROM')}`,
790
+ `${this.$db.get('TABLE_NAME')}`
791
+ ].join(' ');
792
+ const result = await this._queryStatementModel(sql);
793
+ return result;
794
+ }
795
+ /**
796
+ *
797
+ * @override Method
798
+ * @return {promise<object | null>}
799
+ */
800
+ async find(id) {
801
+ const sql = [
802
+ `${this.$constants('SELECT')}`,
803
+ `*`,
804
+ `${this.$constants('FROM')}`,
805
+ `${this.$db.get('TABLE_NAME')}`,
806
+ `${this.$constants('WHERE')}`,
807
+ `${this.$constants('PRIMARY_KEY')} = ${id}`
808
+ ].join(' ');
809
+ const result = await this._queryStatementModel(sql);
810
+ return result?.shift() || null;
811
+ }
1004
812
  /**
1005
813
  *
1006
814
  * @override Method
1007
815
  * @return {promise<array>}
1008
816
  */
1009
- Model.prototype.findMany = function () {
1010
- var _a;
1011
- return __awaiter(this, void 0, void 0, function () {
1012
- var sql;
1013
- return __generator(this, function (_b) {
1014
- switch (_b.label) {
1015
- case 0:
1016
- if (!((_a = this.$db.get('EXCEPT')) === null || _a === void 0 ? void 0 : _a.length)) return [3 /*break*/, 2];
1017
- return [4 /*yield*/, this._exceptColumns()];
1018
- case 1:
1019
- _b.sent();
1020
- _b.label = 2;
1021
- case 2:
1022
- sql = this._queryGenrateModel();
1023
- return [4 /*yield*/, this._execute(sql, 'GET')];
1024
- case 3: return [2 /*return*/, _b.sent()];
1025
- }
1026
- });
1027
- });
1028
- };
817
+ async get() {
818
+ if (this.$db.get('EXCEPT')?.length)
819
+ await this._exceptColumns();
820
+ let sql = this._buildQueryModel();
821
+ if (this.$db.get('WITH_EXISTS')) {
822
+ sql = this._queryRelationsExists();
823
+ }
824
+ return await this._execute({ sql, type: 'GET' });
825
+ }
1029
826
  /**
1030
827
  *
1031
828
  * @override Method
1032
- * @param {?object} paginationOptions
1033
- * @param {number} paginationOptions.limit
1034
- * @param {number} paginationOptions.page
1035
- * @return {promise<Pagination>}
1036
- */
1037
- Model.prototype.pagination = function (paginationOptions) {
1038
- var _a, _b;
1039
- return __awaiter(this, void 0, void 0, function () {
1040
- var limit, page, offset, sql;
1041
- return __generator(this, function (_c) {
1042
- switch (_c.label) {
1043
- case 0:
1044
- limit = 15;
1045
- page = 1;
1046
- if (paginationOptions != null) {
1047
- limit = (paginationOptions === null || paginationOptions === void 0 ? void 0 : paginationOptions.limit) || limit;
1048
- page = (paginationOptions === null || paginationOptions === void 0 ? void 0 : paginationOptions.page) || page;
1049
- }
1050
- this._assertError((_a = this.$logger) === null || _a === void 0 ? void 0 : _a.check('limit'), "this '[pagination]' can't support '[limit]' method");
1051
- if (!((_b = this.$db.get('EXCEPT')) === null || _b === void 0 ? void 0 : _b.length)) return [3 /*break*/, 2];
1052
- return [4 /*yield*/, this._exceptColumns()];
1053
- case 1:
1054
- _c.sent();
1055
- _c.label = 2;
1056
- case 2:
1057
- offset = (page - 1) * limit;
1058
- this.$db.set('PER_PAGE', limit);
1059
- this.$db.set('PAGE', page);
1060
- sql = this._queryGenrateModel();
1061
- if (!!sql.includes(this.$constants('LIMIT'))) return [3 /*break*/, 4];
1062
- sql = [
1063
- "".concat(sql),
1064
- "".concat(this.$constants('LIMIT')),
1065
- "".concat(limit),
1066
- "".concat(this.$constants('OFFSET')),
1067
- "".concat(offset)
1068
- ].join(' ');
1069
- return [4 /*yield*/, this._execute(sql, 'PAGINATION')];
1070
- case 3: return [2 /*return*/, _c.sent()];
1071
- case 4:
1072
- sql = sql.replace(this.$db.get('LIMIT'), [
1073
- "".concat(this.$constants('LIMIT')),
1074
- "".concat(limit),
1075
- "".concat(this.$constants('OFFSET')),
1076
- "".concat(offset)
1077
- ].join(' '));
1078
- return [4 /*yield*/, this._execute(sql, 'PAGINATION')];
1079
- case 5: return [2 /*return*/, _c.sent()];
1080
- }
1081
- });
1082
- });
1083
- };
829
+ * @return {promise<array>}
830
+ */
831
+ async findMany() {
832
+ if (this.$db.get('EXCEPT')?.length)
833
+ await this._exceptColumns();
834
+ const sql = this._buildQueryModel();
835
+ return await this._execute({ sql, type: 'GET' });
836
+ }
1084
837
  /**
1085
838
  *
1086
839
  * @override Method
1087
- * @param {Object} pagination page , limit
1088
- * @param {number} pagination.limit
1089
- * @param {number} pagination.page
840
+ * @param {?object} paginationOptions by default page = 1 , limit = 15
841
+ * @property {number} paginationOptions.limit
842
+ * @property {number} paginationOptions.page
1090
843
  * @return {promise<Pagination>}
1091
844
  */
1092
- Model.prototype.paginate = function (paginationOptions) {
1093
- return __awaiter(this, void 0, void 0, function () {
1094
- var limit, page;
1095
- return __generator(this, function (_a) {
1096
- switch (_a.label) {
1097
- case 0:
1098
- limit = 15;
1099
- page = 1;
1100
- if (paginationOptions != null) {
1101
- limit = (paginationOptions === null || paginationOptions === void 0 ? void 0 : paginationOptions.limit) || limit;
1102
- page = (paginationOptions === null || paginationOptions === void 0 ? void 0 : paginationOptions.page) || page;
1103
- }
1104
- return [4 /*yield*/, this.pagination({ limit: limit, page: page })];
1105
- case 1: return [2 /*return*/, _a.sent()];
1106
- }
1107
- });
1108
- });
1109
- };
845
+ async pagination(paginationOptions) {
846
+ let limit = 15;
847
+ let page = 1;
848
+ if (paginationOptions != null) {
849
+ limit = paginationOptions?.limit || limit;
850
+ page = paginationOptions?.page || page;
851
+ }
852
+ this._assertError(this.$logger?.check('limit'), `this '[pagination]' can't support '[limit]' method`);
853
+ if (this.$db.get('EXCEPT')?.length)
854
+ await this._exceptColumns();
855
+ const offset = (page - 1) * limit;
856
+ this.$db.set('PER_PAGE', limit);
857
+ this.$db.set('PAGE', page);
858
+ let sql = this._buildQueryModel();
859
+ if (this.$db.get('WITH_EXISTS')) {
860
+ sql = this._queryRelationsExists();
861
+ }
862
+ if (!sql.includes(this.$constants('LIMIT'))) {
863
+ sql = [
864
+ `${sql}`,
865
+ `${this.$constants('LIMIT')}`,
866
+ `${limit}`,
867
+ `${this.$constants('OFFSET')}`,
868
+ `${offset}`
869
+ ].join(' ');
870
+ return await this._execute({ sql, type: 'PAGINATION' });
871
+ }
872
+ sql = sql.replace(this.$db.get('LIMIT'), [
873
+ `${this.$constants('LIMIT')}`,
874
+ `${limit}`,
875
+ `${this.$constants('OFFSET')}`,
876
+ `${offset}`
877
+ ].join(' '));
878
+ return await this._execute({ sql, type: 'PAGINATION' });
879
+ }
880
+ /**
881
+ *
882
+ * @override Method
883
+ * @param {?object} paginationOptions by default page = 1 , limit = 15
884
+ * @property {number} paginationOptions.limit
885
+ * @property {number} paginationOptions.page
886
+ * @return {promise<Pagination>}
887
+ */
888
+ async paginate(paginationOptions) {
889
+ let limit = 15;
890
+ let page = 1;
891
+ if (paginationOptions != null) {
892
+ limit = paginationOptions?.limit || limit;
893
+ page = paginationOptions?.page || page;
894
+ }
895
+ return await this.pagination({ limit, page });
896
+ }
1110
897
  /**
1111
898
  *
1112
899
  * @override Method
1113
900
  * @param {string} column
1114
901
  * @return {Promise<array>}
1115
902
  */
1116
- Model.prototype.getGroupBy = function (column) {
1117
- var _a;
1118
- return __awaiter(this, void 0, void 0, function () {
1119
- var sql, results, data, sqlChild, childData, child, resultData;
1120
- return __generator(this, function (_b) {
1121
- switch (_b.label) {
1122
- case 0:
1123
- if (!((_a = this.$db.get('EXCEPT')) === null || _a === void 0 ? void 0 : _a.length)) return [3 /*break*/, 2];
1124
- return [4 /*yield*/, this._exceptColumns()];
1125
- case 1:
1126
- _b.sent();
1127
- _b.label = 2;
1128
- case 2:
1129
- this.$db.set('GROUP_BY', "".concat(this.$constants('GROUP_BY'), " ").concat(column));
1130
- this.$db.set('SELECT', [
1131
- "".concat(this.$db.get('SELECT'), ","),
1132
- "".concat(this.$constants('GROUP_CONCAT'), "(id)"),
1133
- "".concat(this.$constants('AS'), " data")
1134
- ].join(' '));
1135
- sql = this._queryGenrateModel();
1136
- return [4 /*yield*/, this._queryStatementModel(sql)];
1137
- case 3:
1138
- results = _b.sent();
1139
- data = [];
1140
- results.forEach(function (result) {
1141
- var _a, _b;
1142
- var splits = (_b = (_a = result === null || result === void 0 ? void 0 : result.data) === null || _a === void 0 ? void 0 : _a.split(',')) !== null && _b !== void 0 ? _b : '0';
1143
- splits.forEach(function (split) { return data = __spreadArray(__spreadArray([], __read(data), false), [split], false); });
1144
- });
1145
- sqlChild = [
1146
- "".concat(this.$constants('SELECT')),
1147
- "*",
1148
- "".concat(this.$constants('FROM')),
1149
- "".concat(this.$db.get('TABLE_NAME')),
1150
- "".concat(this.$constants('WHERE'), " id"),
1151
- "".concat(this.$constants('IN')),
1152
- "(".concat(data.map(function (a) { return "'".concat(a, "'"); }).join(',') || ['0'], ")")
1153
- ].join(' ');
1154
- return [4 /*yield*/, this._queryStatementModel(sqlChild)];
1155
- case 4:
1156
- childData = _b.sent();
1157
- return [4 /*yield*/, this._executeGroup(childData)];
1158
- case 5:
1159
- child = _b.sent();
1160
- resultData = results.map(function (result) {
1161
- var _a;
1162
- var id = result[column];
1163
- var newData = child.filter(function (data) { return data[column] === id; });
1164
- return (_a = {},
1165
- _a[column] = id,
1166
- _a.data = newData,
1167
- _a);
1168
- });
1169
- return [2 /*return*/, resultData];
1170
- }
903
+ async getGroupBy(column) {
904
+ if (this.$db.get('EXCEPT')?.length)
905
+ await this._exceptColumns();
906
+ this.$db.set('GROUP_BY', `${this.$constants('GROUP_BY')} ${column}`);
907
+ this.$db.set('SELECT', [
908
+ `${this.$db.get('SELECT')},`,
909
+ `${this.$constants('GROUP_CONCAT')}(id)`,
910
+ `${this.$constants('AS')} data`
911
+ ].join(' '));
912
+ const sql = this._buildQueryModel();
913
+ const results = await this._queryStatementModel(sql);
914
+ let data = [];
915
+ results.forEach((result) => {
916
+ const splits = result?.data?.split(',') ?? '0';
917
+ splits.forEach((split) => data = [...data, split]);
918
+ });
919
+ const sqlChild = [
920
+ `${this.$constants('SELECT')}`,
921
+ `*`,
922
+ `${this.$constants('FROM')}`,
923
+ `${this.$db.get('TABLE_NAME')}`,
924
+ `${this.$constants('WHERE')} id`,
925
+ `${this.$constants('IN')}`,
926
+ `(${data.map((a) => `\'${a}\'`).join(',') || ['0']})`
927
+ ].join(' ');
928
+ const childData = await this._queryStatementModel(sqlChild);
929
+ const child = await this._executeGroup(childData);
930
+ const resultData = results.map((result) => {
931
+ const id = result[column];
932
+ const newData = child.filter((data) => data[column] === id);
933
+ return ({
934
+ [column]: id,
935
+ data: newData
1171
936
  });
1172
937
  });
1173
- };
938
+ return resultData;
939
+ }
1174
940
  /**
1175
941
  *
1176
942
  * update data in the database
@@ -1178,117 +944,117 @@ var Model = /** @class */ (function (_super) {
1178
944
  * @param {object} data
1179
945
  * @return {this} this
1180
946
  */
1181
- Model.prototype.update = function (data) {
1182
- var query = this._queryUpdateModel(data);
947
+ update(data) {
948
+ const query = this._queryUpdateModel(data);
1183
949
  this.$db.set('UPDATE', [
1184
- "".concat(this.$constants('UPDATE')),
1185
- "".concat(this.$db.get('TABLE_NAME')),
1186
- "".concat(query)
950
+ `${this.$constants('UPDATE')}`,
951
+ `${this.$db.get('TABLE_NAME')}`,
952
+ `${query}`
1187
953
  ].join(' '));
1188
954
  this.$db.set('SAVE', 'UPDATE');
1189
955
  return this;
1190
- };
956
+ }
1191
957
  /**
1192
958
  *
1193
959
  * @override Method
1194
960
  * @param {object} data for insert
1195
961
  * @return {this} this
1196
962
  */
1197
- Model.prototype.insert = function (data) {
1198
- var query = this._queryInsertModel(data);
963
+ insert(data) {
964
+ const query = this._queryInsertModel(data);
1199
965
  this.$db.set('INSERT', [
1200
- "".concat(this.$constants('INSERT')),
1201
- "".concat(this.$db.get('TABLE_NAME')),
1202
- "".concat(query)
966
+ `${this.$constants('INSERT')}`,
967
+ `${this.$db.get('TABLE_NAME')}`,
968
+ `${query}`
1203
969
  ].join(' '));
1204
970
  this.$db.set('SAVE', 'INSERT');
1205
971
  return this;
1206
- };
972
+ }
1207
973
  /**
1208
974
  *
1209
975
  * @override Method
1210
976
  * @param {object} data for insert
1211
977
  * @return {this} this
1212
978
  */
1213
- Model.prototype.create = function (data) {
1214
- var query = this._queryInsertModel(data);
979
+ create(data) {
980
+ const query = this._queryInsertModel(data);
1215
981
  this.$db.set('INSERT', [
1216
- "".concat(this.$constants('INSERT')),
1217
- "".concat(this.$db.get('TABLE_NAME')),
1218
- "".concat(query)
982
+ `${this.$constants('INSERT')}`,
983
+ `${this.$db.get('TABLE_NAME')}`,
984
+ `${query}`
1219
985
  ].join(' '));
1220
986
  this.$db.set('SAVE', 'INSERT');
1221
987
  return this;
1222
- };
988
+ }
1223
989
  /**
1224
990
  *
1225
991
  * @override Method
1226
992
  * @param {object} data for update or create
1227
993
  * @return {this} this
1228
994
  */
1229
- Model.prototype.updateOrCreate = function (data) {
1230
- var queryUpdate = this._queryUpdateModel(data);
1231
- var queryInsert = this._queryInsertModel(data);
995
+ updateOrCreate(data) {
996
+ const queryUpdate = this._queryUpdateModel(data);
997
+ const queryInsert = this._queryInsertModel(data);
1232
998
  this.$db.set('INSERT', [
1233
- "".concat(this.$constants('INSERT')),
1234
- "".concat(this.$db.get('TABLE_NAME')),
1235
- "".concat(queryInsert)
999
+ `${this.$constants('INSERT')}`,
1000
+ `${this.$db.get('TABLE_NAME')}`,
1001
+ `${queryInsert}`
1236
1002
  ].join(' '));
1237
1003
  this.$db.set('UPDATE', [
1238
- "".concat(this.$constants('UPDATE')),
1239
- "".concat(this.$db.get('TABLE_NAME')),
1240
- "".concat(queryUpdate)
1004
+ `${this.$constants('UPDATE')}`,
1005
+ `${this.$db.get('TABLE_NAME')}`,
1006
+ `${queryUpdate}`
1241
1007
  ].join(' '));
1242
1008
  this.$db.set('SAVE', 'UPDATE_OR_INSERT');
1243
1009
  return this;
1244
- };
1010
+ }
1245
1011
  /**
1246
1012
  *
1247
1013
  * @override Method
1248
1014
  * @param {object} data for update or create
1249
1015
  * @return {this} this
1250
1016
  */
1251
- Model.prototype.updateOrInsert = function (data) {
1017
+ updateOrInsert(data) {
1252
1018
  this.updateOrCreate(data);
1253
1019
  return this;
1254
- };
1020
+ }
1255
1021
  /**
1256
1022
  *
1257
1023
  * @override Method
1258
1024
  * @param {object} data for update or create
1259
1025
  * @return {this} this
1260
1026
  */
1261
- Model.prototype.insertOrUpdate = function (data) {
1027
+ insertOrUpdate(data) {
1262
1028
  this.updateOrCreate(data);
1263
1029
  return this;
1264
- };
1030
+ }
1265
1031
  /**
1266
1032
  *
1267
1033
  * @override Method
1268
1034
  * @param {object} data for update or create
1269
1035
  * @return {this} this
1270
1036
  */
1271
- Model.prototype.createOrUpdate = function (data) {
1037
+ createOrUpdate(data) {
1272
1038
  this.updateOrCreate(data);
1273
1039
  return this;
1274
- };
1040
+ }
1275
1041
  /**
1276
1042
  *
1277
- * insert muliple data into the database
1043
+ * insert multiple data into the database
1278
1044
  * @override Method
1279
1045
  * @param {array<object>} data create multiple data
1280
1046
  * @return {this} this this
1281
1047
  */
1282
- Model.prototype.createMultiple = function (data) {
1283
- var query = this._queryInsertMultipleModel(data);
1048
+ createMultiple(data) {
1049
+ const query = this._queryInsertMultipleModel(data);
1284
1050
  this.$db.set('INSERT', [
1285
- "".concat(this.$constants('INSERT')),
1286
- "".concat(this.$db.get('TABLE_NAME')),
1287
- "".concat(query)
1051
+ `${this.$constants('INSERT')}`,
1052
+ `${this.$db.get('TABLE_NAME')}`,
1053
+ `${query}`
1288
1054
  ].join(' '));
1289
1055
  this.$db.set('SAVE', 'INSERT_MULTIPLE');
1290
1056
  return this;
1291
- };
1057
+ }
1292
1058
  /**
1293
1059
  *
1294
1060
  * insert muliple data into the database
@@ -1296,290 +1062,178 @@ var Model = /** @class */ (function (_super) {
1296
1062
  * @param {array<object>} data create multiple data
1297
1063
  * @return {this} this this
1298
1064
  */
1299
- Model.prototype.insertMultiple = function (data) {
1300
- var query = this._queryInsertMultipleModel(data);
1065
+ insertMultiple(data) {
1066
+ const query = this._queryInsertMultipleModel(data);
1301
1067
  this.$db.set('INSERT', [
1302
- "".concat(this.$constants('INSERT')),
1303
- "".concat(this.$db.get('TABLE_NAME')),
1304
- "".concat(query)
1068
+ `${this.$constants('INSERT')}`,
1069
+ `${this.$db.get('TABLE_NAME')}`,
1070
+ `${query}`
1305
1071
  ].join(' '));
1306
1072
  this.$db.set('SAVE', 'INSERT_MULTIPLE');
1307
1073
  return this;
1308
- };
1074
+ }
1309
1075
  /**
1310
1076
  *
1311
1077
  * @override Method
1312
- * @param {object?} transaction using DB.beginTransaction()
1313
- * Ex. +---------------------------------------------------+
1314
- * const transaction = await new DB().beginTransaction()
1315
- *
1316
- * try {
1317
- * const useSave = await create ...something then .save(transaction)
1318
- * const useSave2 = await create ...something then .save(transaction)
1319
- * throw new Error('try to errors')
1320
- * } catch (e) {
1321
- * const rollback = await transaction.rollback()
1322
- * // rollback => ture
1323
- * // !done transaction has been rolled back [useSave , useSave2]
1324
- * }
1325
- *
1326
- * @return {Promise<array | object | null>}
1078
+ * @return {Promise<any>}
1327
1079
  */
1328
- Model.prototype.save = function (transaction) {
1329
- var _a;
1330
- return __awaiter(this, void 0, void 0, function () {
1331
- var attributes, query_1, query, _b;
1332
- return __generator(this, function (_c) {
1333
- switch (_c.label) {
1334
- case 0:
1335
- if (transaction != null)
1336
- this.$db.set('TRANSACTION', transaction);
1337
- attributes = this.$attributes;
1338
- if ((_a = Object.keys(attributes)) === null || _a === void 0 ? void 0 : _a.length) {
1339
- while (true) {
1340
- if (this.$db.get('WHERE')) {
1341
- query_1 = this._queryUpdateModel(attributes);
1342
- this.$db.set('UPDATE', [
1343
- "".concat(this.$constants('UPDATE')),
1344
- "".concat(this.$db.get('TABLE_NAME')),
1345
- "".concat(query_1)
1346
- ].join(' '));
1347
- this.$db.set('SAVE', 'UPDATE');
1348
- break;
1349
- }
1350
- query = this._queryInsertModel(attributes);
1351
- this.$db.set('INSERT', [
1352
- "".concat(this.$constants('INSERT')),
1353
- "".concat(this.$db.get('TABLE_NAME')),
1354
- "".concat(query)
1355
- ].join(' '));
1356
- this.$db.set('SAVE', 'INSERT');
1357
- break;
1358
- }
1359
- }
1360
- _b = this.$db.get('SAVE');
1361
- switch (_b) {
1362
- case 'INSERT_MULTIPLE': return [3 /*break*/, 1];
1363
- case 'INSERT': return [3 /*break*/, 3];
1364
- case 'UPDATE': return [3 /*break*/, 5];
1365
- case 'INSERT_NOT_EXISTS': return [3 /*break*/, 7];
1366
- case 'UPDATE_OR_INSERT': return [3 /*break*/, 9];
1367
- }
1368
- return [3 /*break*/, 11];
1369
- case 1: return [4 /*yield*/, this._createMultipleModel()];
1370
- case 2: return [2 /*return*/, _c.sent()];
1371
- case 3: return [4 /*yield*/, this._createModel()];
1372
- case 4: return [2 /*return*/, _c.sent()];
1373
- case 5: return [4 /*yield*/, this._updateModel()];
1374
- case 6: return [2 /*return*/, _c.sent()];
1375
- case 7: return [4 /*yield*/, this._insertNotExistsModel()];
1376
- case 8: return [2 /*return*/, _c.sent()];
1377
- case 9: return [4 /*yield*/, this._updateOrInsertModel()];
1378
- case 10: return [2 /*return*/, _c.sent()];
1379
- case 11: throw new Error("unknown this [".concat(this.$db.get('SAVE'), "]"));
1080
+ async save() {
1081
+ const attributes = this.$attributes;
1082
+ if (Object.keys(attributes)?.length) {
1083
+ while (true) {
1084
+ if (this.$db.get('WHERE')) {
1085
+ const query = this._queryUpdateModel(attributes);
1086
+ this.$db.set('UPDATE', [
1087
+ `${this.$constants('UPDATE')}`,
1088
+ `${this.$db.get('TABLE_NAME')}`,
1089
+ `${query}`
1090
+ ].join(' '));
1091
+ this.$db.set('SAVE', 'UPDATE');
1092
+ break;
1380
1093
  }
1381
- });
1382
- });
1383
- };
1094
+ const query = this._queryInsertModel(attributes);
1095
+ this.$db.set('INSERT', [
1096
+ `${this.$constants('INSERT')}`,
1097
+ `${this.$db.get('TABLE_NAME')}`,
1098
+ `${query}`
1099
+ ].join(' '));
1100
+ this.$db.set('SAVE', 'INSERT');
1101
+ break;
1102
+ }
1103
+ }
1104
+ switch (this.$db.get('SAVE')) {
1105
+ case 'INSERT_MULTIPLE': return await this._createMultipleModel();
1106
+ case 'INSERT': return await this._createModel();
1107
+ case 'UPDATE': return await this._updateModel();
1108
+ case 'INSERT_NOT_EXISTS': return await this._insertNotExistsModel();
1109
+ case 'UPDATE_OR_INSERT': return await this._updateOrInsertModel();
1110
+ default: throw new Error(`unknown this [${this.$db.get('SAVE')}]`);
1111
+ }
1112
+ }
1384
1113
  /**
1385
1114
  *
1386
1115
  * fake data
1387
1116
  * @param {number} rows number of rows
1388
- * @return {promise<any}
1117
+ * @return {promise<any>}
1389
1118
  */
1390
- Model.prototype.faker = function (rows) {
1391
- if (rows === void 0) { rows = 1; }
1392
- return __awaiter(this, void 0, void 0, function () {
1393
- var data, row, sql, fields, columnAndValue, fields_1, fields_1_1, _a, field, type, check, query;
1394
- var e_1, _b, _c;
1395
- return __generator(this, function (_d) {
1396
- switch (_d.label) {
1397
- case 0:
1398
- data = [];
1399
- row = 0;
1400
- _d.label = 1;
1401
- case 1:
1402
- if (!(row < rows)) return [3 /*break*/, 4];
1403
- sql = [
1404
- "".concat(this.$constants('SHOW')),
1405
- "".concat(this.$constants('FIELDS')),
1406
- "".concat(this.$constants('FROM')),
1407
- "".concat(this.$db.get('TABLE_NAME'))
1408
- ].join(' ');
1409
- return [4 /*yield*/, this._queryStatementModel(sql)];
1410
- case 2:
1411
- fields = _d.sent();
1412
- columnAndValue = {};
1413
- try {
1414
- for (fields_1 = (e_1 = void 0, __values(fields)), fields_1_1 = fields_1.next(); !fields_1_1.done; fields_1_1 = fields_1.next()) {
1415
- _a = fields_1_1.value, field = _a.Field, type = _a.Type;
1416
- check = [
1417
- field.toLowerCase() === 'id',
1418
- field.toLowerCase() === '_id',
1419
- field.toLowerCase() === 'uuid'
1420
- ].some(function (f) { return f; });
1421
- if (check)
1422
- continue;
1423
- columnAndValue = __assign(__assign({}, columnAndValue), (_c = {}, _c[field] = this.$utils.faker(type), _c));
1424
- }
1425
- }
1426
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1427
- finally {
1428
- try {
1429
- if (fields_1_1 && !fields_1_1.done && (_b = fields_1.return)) _b.call(fields_1);
1430
- }
1431
- finally { if (e_1) throw e_1.error; }
1432
- }
1433
- data = __spreadArray(__spreadArray([], __read(data), false), [columnAndValue], false);
1434
- _d.label = 3;
1435
- case 3:
1436
- row++;
1437
- return [3 /*break*/, 1];
1438
- case 4:
1439
- query = this._queryInsertMultipleModel(data);
1440
- this.$db.set('INSERT', [
1441
- "".concat(this.$constants('INSERT')),
1442
- "".concat(this.$db.get('TABLE_NAME')),
1443
- "".concat(query)
1444
- ].join(' '));
1445
- this.$db.set('SAVE', 'INSERT_MULTIPLE');
1446
- return [4 /*yield*/, this.save()];
1447
- case 5: return [2 /*return*/, _d.sent()];
1448
- }
1449
- });
1450
- });
1451
- };
1452
- /**
1453
- *
1454
- * @override Method
1455
- * @param {number} id
1456
- * @return {this}
1457
- */
1458
- Model.prototype.whereUser = function (id) {
1459
- var column = this._valuePattern('userId');
1460
- id = this.$utils.escape(id);
1461
- if (!this.$db.get('WHERE').includes(this.$constants('WHERE'))) {
1462
- this.$db.set('WHERE', [
1463
- "".concat(this.$constants('WHERE')),
1464
- "".concat(column, " = '").concat(id, "'")
1465
- ].join(' '));
1466
- return this;
1119
+ async faker(rows = 1) {
1120
+ let data = [];
1121
+ for (let row = 0; row < rows; row++) {
1122
+ const sql = [
1123
+ `${this.$constants('SHOW')}`,
1124
+ `${this.$constants('FIELDS')}`,
1125
+ `${this.$constants('FROM')}`,
1126
+ `${this.$db.get('TABLE_NAME')}`
1127
+ ].join(' ');
1128
+ const fields = await this._queryStatementModel(sql);
1129
+ let columnAndValue = {};
1130
+ for (const { Field: field, Type: type } of fields) {
1131
+ const check = [
1132
+ field.toLowerCase() === 'id',
1133
+ field.toLowerCase() === '_id',
1134
+ field.toLowerCase() === 'uuid'
1135
+ ].some(f => f);
1136
+ if (check)
1137
+ continue;
1138
+ columnAndValue = {
1139
+ ...columnAndValue,
1140
+ [field]: this.$utils.faker(type)
1141
+ };
1142
+ }
1143
+ data = [...data, columnAndValue];
1467
1144
  }
1468
- this.$db.set('WHERE', [
1469
- "".concat(this.$db.get('WHERE')),
1470
- "".concat(this.$constants('AND')),
1471
- "".concat(column, " = '").concat(id, "'")
1145
+ const query = this._queryInsertMultipleModel(data);
1146
+ this.$db.set('INSERT', [
1147
+ `${this.$constants('INSERT')}`,
1148
+ `${this.$db.get('TABLE_NAME')}`,
1149
+ `${query}`
1472
1150
  ].join(' '));
1473
- return this;
1474
- };
1475
- Model.prototype._queryStatementModel = function (sql) {
1476
- return __awaiter(this, void 0, void 0, function () {
1477
- var result;
1478
- return __generator(this, function (_a) {
1479
- switch (_a.label) {
1480
- case 0:
1481
- if (this.$db.get('DEBUG'))
1482
- this.$utils.consoleDebug(sql);
1483
- return [4 /*yield*/, this.$pool.get(sql)];
1484
- case 1:
1485
- result = _a.sent();
1486
- this._registry(result);
1487
- return [2 /*return*/, result];
1488
- }
1489
- });
1490
- });
1491
- };
1492
- Model.prototype._actionStatementModel = function (_a) {
1493
- var _b = _a === void 0 ? {} : _a, sql = _b.sql, _c = _b.returnId, returnId = _c === void 0 ? false : _c;
1494
- return __awaiter(this, void 0, void 0, function () {
1495
- var result_2, result;
1496
- return __generator(this, function (_d) {
1497
- switch (_d.label) {
1498
- case 0:
1499
- if (this.$db.get('DEBUG'))
1500
- this.$utils.consoleDebug(sql);
1501
- if (!returnId) return [3 /*break*/, 2];
1502
- return [4 /*yield*/, this.$pool.get(sql)];
1503
- case 1:
1504
- result_2 = _d.sent();
1505
- return [2 /*return*/, [result_2.affectedRows, result_2.insertId]];
1506
- case 2: return [4 /*yield*/, this.$pool.get(sql)];
1507
- case 3:
1508
- result = (_d.sent()).affectedRows;
1509
- return [2 /*return*/, result];
1510
- }
1511
- });
1512
- });
1513
- };
1514
- Model.prototype._valuePattern = function (value) {
1151
+ this.$db.set('SAVE', 'INSERT_MULTIPLE');
1152
+ return await this.save();
1153
+ }
1154
+ async _queryStatementModel(sql) {
1155
+ if (this.$db.get('DEBUG'))
1156
+ this.$utils.consoleDebug(sql);
1157
+ const result = await this.$pool.get(sql);
1158
+ this._registry(result);
1159
+ return result;
1160
+ }
1161
+ async _actionStatementModel({ sql, returnId = false }) {
1162
+ if (this.$db.get('DEBUG'))
1163
+ this.$utils.consoleDebug(sql);
1164
+ if (returnId) {
1165
+ const result = await this.$pool.get(sql);
1166
+ return [result.affectedRows, result.insertId];
1167
+ }
1168
+ const { affectedRows: result } = await this.$pool.get(sql);
1169
+ return result;
1170
+ }
1171
+ _valuePattern(value) {
1515
1172
  switch (this.$db.get('PATTERN')) {
1516
1173
  case this.$constants('PATTERN').snake_case: {
1517
- return value.replace(/([A-Z])/g, function (str) { return "_".concat(str.toLowerCase()); });
1174
+ return value.replace(/([A-Z])/g, (str) => `_${str.toLowerCase()}`);
1518
1175
  }
1519
1176
  case this.$constants('PATTERN').camelCase: {
1520
- return value.replace(/(.(\_|-|\s)+.)/g, function (str) { return "".concat(str[0]).concat(str[str.length - 1].toUpperCase()); });
1177
+ return value.replace(/(.(\_|-|\s)+.)/g, (str) => `${str[0]}${str[str.length - 1].toUpperCase()}`);
1521
1178
  }
1522
1179
  default: return value;
1523
1180
  }
1524
- };
1525
- Model.prototype._isPatternSnakeCase = function () {
1181
+ }
1182
+ _isPatternSnakeCase() {
1526
1183
  return this.$db.get('PATTERN') === this.$constants('PATTERN').snake_case;
1527
- };
1528
- Model.prototype._classToTableName = function (className, _a) {
1529
- var _b = _a === void 0 ? {} : _a, _c = _b.singular, singular = _c === void 0 ? false : _c;
1184
+ }
1185
+ _classToTableName(className, { singular = false } = {}) {
1530
1186
  if (className == null)
1531
1187
  className = this.constructor.name;
1532
- var tb = className.replace(/([A-Z])/g, function (str) { return '_' + str.toLowerCase(); }).slice(1);
1188
+ const tb = className.replace(/([A-Z])/g, (str) => '_' + str.toLowerCase()).slice(1);
1533
1189
  if (singular)
1534
1190
  return tb;
1535
1191
  return pluralize_1.default.plural(tb);
1536
- };
1537
- Model.prototype._tableName = function () {
1538
- var tb = this._classToTableName();
1539
- this.$db.set('SELECT', "".concat(this.$constants('SELECT'), " *"));
1540
- this.$db.set('FROM', "".concat(this.$constants('FROM')));
1541
- this.$db.set('TABLE_NAME', "`".concat(tb, "`"));
1192
+ }
1193
+ _tableName() {
1194
+ const tb = this._classToTableName();
1195
+ this.$db.set('SELECT', `${this.$constants('SELECT')} *`);
1196
+ this.$db.set('FROM', `${this.$constants('FROM')}`);
1197
+ this.$db.set('TABLE_NAME', `\`${tb}\``);
1542
1198
  return this;
1543
- };
1544
- Model.prototype._valueInRelation = function (relationModel) {
1545
- var _a, _b;
1546
- var relation = relationModel.relation;
1547
- var model = (_a = relationModel.model) === null || _a === void 0 ? void 0 : _a.name;
1548
- var table = relationModel.freezeTable
1199
+ }
1200
+ _valueInRelation(relationModel) {
1201
+ const relation = relationModel.relation;
1202
+ const model = relationModel.model?.name;
1203
+ const table = relationModel.freezeTable
1549
1204
  ? relationModel.freezeTable
1550
- : (_b = relationModel.query) === null || _b === void 0 ? void 0 : _b.tableName;
1551
- var name = relationModel.name;
1552
- var as = relationModel.as;
1553
- if (!model || model == null)
1554
- throw new Error('Not found model');
1555
- var localKey = relationModel.localKey
1205
+ : relationModel.query?.tableName;
1206
+ const name = relationModel.name;
1207
+ const as = relationModel.as;
1208
+ this._assertError(!model || model == null, 'not found model');
1209
+ let localKey = relationModel.localKey
1556
1210
  ? relationModel.localKey
1557
1211
  : this.$db.get('PRIMARY_KEY');
1558
- var foreignKey = relationModel.foreignKey
1212
+ let foreignKey = relationModel.foreignKey
1559
1213
  ? relationModel.foreignKey
1560
1214
  : this._valuePattern([
1561
- "".concat(pluralize_1.default.singular(this.$db.get('TABLE_NAME').replace(/\`/g, ''))),
1562
- "".concat(this.$db.get('PRIMARY_KEY'))
1215
+ `${pluralize_1.default.singular(this.$db.get('TABLE_NAME').replace(/\`/g, ''))}`,
1216
+ `${this.$db.get('PRIMARY_KEY')}`
1563
1217
  ].join('_'));
1564
- var checkRelationIsBelongsTo = [
1218
+ const checkRelationIsBelongsTo = [
1565
1219
  relationModel.localKey == null,
1566
1220
  relationModel.foreignKey == null,
1567
1221
  relation === this.$constants('RELATIONSHIP').belongsTo
1568
- ].every(function (c) { return c; });
1222
+ ].every(c => c);
1569
1223
  if (checkRelationIsBelongsTo) {
1570
1224
  foreignKey = localKey;
1571
1225
  localKey = this._valuePattern([
1572
- "".concat(pluralize_1.default.singular(table)),
1573
- "".concat(this.$db.get('PRIMARY_KEY'))
1226
+ `${pluralize_1.default.singular(table)}`,
1227
+ `${this.$db.get('PRIMARY_KEY')}`
1574
1228
  ].join('_'));
1575
1229
  }
1576
- return { name: name, as: as, relation: relation, table: table, localKey: localKey, foreignKey: foreignKey, model: model };
1577
- };
1578
- Model.prototype._queryGenrateModel = function () {
1579
- var sql = [];
1230
+ return { name, as, relation, table, localKey, foreignKey, model };
1231
+ }
1232
+ _buildQueryModel() {
1233
+ let sql = [];
1580
1234
  while (true) {
1581
1235
  if (this.$db.get('SOFT_DELETE')) {
1582
- var deletedAt = this._valuePattern('deletedAt');
1236
+ const deletedAt = this._valuePattern(this.$db.get('SOFT_DELETE_FORMAT'));
1583
1237
  this.whereNull(deletedAt);
1584
1238
  }
1585
1239
  if (this.$db.get('INSERT')) {
@@ -1591,7 +1245,7 @@ var Model = /** @class */ (function (_super) {
1591
1245
  if (this.$db.get('UPDATE')) {
1592
1246
  sql = [
1593
1247
  this.$db.get('UPDATE'),
1594
- this.$db.get('WHERE'),
1248
+ this.$db.get('WHERE')
1595
1249
  ];
1596
1250
  break;
1597
1251
  }
@@ -1615,423 +1269,315 @@ var Model = /** @class */ (function (_super) {
1615
1269
  ];
1616
1270
  break;
1617
1271
  }
1618
- var filterSql = sql.filter(function (data) { return data !== '' || data == null; });
1272
+ const filterSql = sql.filter(data => data !== '' || data == null);
1619
1273
  return filterSql.join(' ');
1620
- };
1621
- Model.prototype._exceptColumns = function () {
1622
- return __awaiter(this, void 0, void 0, function () {
1623
- var sql, rawColumns, columns, removeExcept;
1624
- var _this = this;
1625
- return __generator(this, function (_a) {
1626
- switch (_a.label) {
1627
- case 0:
1628
- sql = [
1629
- "".concat(this.$constants('SHOW')),
1630
- "".concat(this.$constants('COLUMNS')),
1631
- "".concat(this.$constants('FROM')),
1632
- "".concat(this.$db.get('TABLE_NAME'))
1633
- ].join(' ');
1634
- return [4 /*yield*/, this._queryStatementModel(sql)];
1635
- case 1:
1636
- rawColumns = _a.sent();
1637
- columns = rawColumns.map(function (column) { return column.Field; });
1638
- removeExcept = columns.filter(function (column) { return !_this.$db.get('EXCEPT').includes(column); });
1639
- this.select(removeExcept.join(','));
1640
- return [2 /*return*/, this];
1641
- }
1642
- });
1643
- });
1644
- };
1645
- Model.prototype._showOnly = function (data) {
1646
- var _this = this;
1647
- var result = [];
1648
- var hasNameRelation = this.$db.get('WITH').map(function (w) { var _a; return (_a = w.as) !== null && _a !== void 0 ? _a : w.name; });
1649
- data.forEach(function (d) {
1650
- var newData = {};
1651
- _this.$db.get('ONLY').forEach(function (only) {
1652
- var _a;
1274
+ }
1275
+ async _exceptColumns() {
1276
+ const sql = [
1277
+ `${this.$constants('SHOW')}`,
1278
+ `${this.$constants('COLUMNS')}`,
1279
+ `${this.$constants('FROM')}`,
1280
+ `${this.$db.get('TABLE_NAME')}`
1281
+ ].join(' ');
1282
+ const rawColumns = await this._queryStatementModel(sql);
1283
+ const columns = rawColumns.map((column) => column.Field);
1284
+ const removeExcept = columns.filter((column) => !this.$db.get('EXCEPT').includes(column));
1285
+ this.select(removeExcept.join(','));
1286
+ return this;
1287
+ }
1288
+ _showOnly(data) {
1289
+ let result = [];
1290
+ const hasNameRelation = this.$db.get('WITH').map((w) => w.as ?? w.name);
1291
+ data.forEach((d) => {
1292
+ let newData = {};
1293
+ this.$db.get('ONLY').forEach((only) => {
1653
1294
  if (d.hasOwnProperty(only))
1654
- newData = __assign(__assign({}, newData), (_a = {}, _a[only] = d[only], _a));
1295
+ newData = { ...newData, [only]: d[only] };
1655
1296
  });
1656
- hasNameRelation.forEach(function (name) {
1657
- var _a;
1297
+ hasNameRelation.forEach((name) => {
1658
1298
  if (name)
1659
- newData = __assign(__assign({}, newData), (_a = {}, _a[name] = d[name], _a));
1299
+ newData = { ...newData, [name]: d[name] };
1660
1300
  });
1661
- result = __spreadArray(__spreadArray([], __read(result), false), [newData], false);
1301
+ result = [...result, newData];
1662
1302
  });
1663
1303
  return result;
1664
- };
1665
- Model.prototype._execute = function (sql, type) {
1666
- return __awaiter(this, void 0, void 0, function () {
1667
- var result, emptyData, relations, relations_1, relations_1_1, relation, relationIsBelongsToMany, dataFromRelation, e_2_1;
1668
- var e_2, _a;
1669
- return __generator(this, function (_b) {
1670
- switch (_b.label) {
1671
- case 0: return [4 /*yield*/, this._queryStatementModel(sql)];
1672
- case 1:
1673
- result = _b.sent();
1674
- emptyData = this._returnEmpty(type);
1675
- if (!result.length)
1676
- return [2 /*return*/, emptyData];
1677
- relations = this.$db.get('WITH');
1678
- if (!relations.length)
1679
- return [2 /*return*/, this._returnResult(type, result) || emptyData];
1680
- _b.label = 2;
1681
- case 2:
1682
- _b.trys.push([2, 9, 10, 11]);
1683
- relations_1 = __values(relations), relations_1_1 = relations_1.next();
1684
- _b.label = 3;
1685
- case 3:
1686
- if (!!relations_1_1.done) return [3 /*break*/, 8];
1687
- relation = relations_1_1.value;
1688
- relationIsBelongsToMany = relation.relation === this.$constants('RELATIONSHIP').belongsToMany;
1689
- if (!relationIsBelongsToMany) return [3 /*break*/, 5];
1690
- return [4 /*yield*/, this._belongsToMany(result, relation)];
1691
- case 4:
1692
- result = _b.sent();
1693
- return [3 /*break*/, 7];
1694
- case 5: return [4 /*yield*/, this._relation(result, relation)];
1695
- case 6:
1696
- dataFromRelation = _b.sent();
1697
- result = this._relationFilter(result, dataFromRelation, relation);
1698
- _b.label = 7;
1699
- case 7:
1700
- relations_1_1 = relations_1.next();
1701
- return [3 /*break*/, 3];
1702
- case 8: return [3 /*break*/, 11];
1703
- case 9:
1704
- e_2_1 = _b.sent();
1705
- e_2 = { error: e_2_1 };
1706
- return [3 /*break*/, 11];
1707
- case 10:
1708
- try {
1709
- if (relations_1_1 && !relations_1_1.done && (_a = relations_1.return)) _a.call(relations_1);
1710
- }
1711
- finally { if (e_2) throw e_2.error; }
1712
- return [7 /*endfinally*/];
1713
- case 11:
1714
- if (this.$db.get('HIDDEN').length)
1715
- this._hiddenColumnModel(result);
1716
- return [2 /*return*/, this._returnResult(type, result) || emptyData];
1717
- }
1718
- });
1719
- });
1720
- };
1721
- Model.prototype._executeGroup = function (dataParents, type) {
1722
- var _a;
1723
- if (type === void 0) { type = 'GET'; }
1724
- return __awaiter(this, void 0, void 0, function () {
1725
- var emptyData, relations, relations_2, relations_2_1, relation, dataChilds, e_3_1, resultData;
1726
- var e_3, _b;
1727
- return __generator(this, function (_c) {
1728
- switch (_c.label) {
1729
- case 0:
1730
- emptyData = this._returnEmpty(type);
1731
- if (!dataParents.length)
1732
- return [2 /*return*/, emptyData];
1733
- relations = this.$db.get('WITH');
1734
- if (!relations.length) return [3 /*break*/, 8];
1735
- _c.label = 1;
1736
- case 1:
1737
- _c.trys.push([1, 6, 7, 8]);
1738
- relations_2 = __values(relations), relations_2_1 = relations_2.next();
1739
- _c.label = 2;
1740
- case 2:
1741
- if (!!relations_2_1.done) return [3 /*break*/, 5];
1742
- relation = relations_2_1.value;
1743
- if (relation.relation === this.$constants('RELATIONSHIP').belongsToMany) {
1744
- return [2 /*return*/, this._belongsToMany(dataParents, relation)];
1745
- }
1746
- return [4 /*yield*/, this._relation(dataParents, relation)];
1747
- case 3:
1748
- dataChilds = _c.sent();
1749
- dataParents = this._relationFilter(dataParents, dataChilds, relation);
1750
- _c.label = 4;
1751
- case 4:
1752
- relations_2_1 = relations_2.next();
1753
- return [3 /*break*/, 2];
1754
- case 5: return [3 /*break*/, 8];
1755
- case 6:
1756
- e_3_1 = _c.sent();
1757
- e_3 = { error: e_3_1 };
1758
- return [3 /*break*/, 8];
1759
- case 7:
1760
- try {
1761
- if (relations_2_1 && !relations_2_1.done && (_b = relations_2.return)) _b.call(relations_2);
1762
- }
1763
- finally { if (e_3) throw e_3.error; }
1764
- return [7 /*endfinally*/];
1765
- case 8:
1766
- if ((_a = this.$db.get('HIDDEN')) === null || _a === void 0 ? void 0 : _a.length)
1767
- this._hiddenColumnModel(dataParents);
1768
- resultData = this._returnResult(type, dataParents);
1769
- return [2 /*return*/, resultData || emptyData];
1770
- }
1771
- });
1772
- });
1773
- };
1774
- Model.prototype._relationFilter = function (dataParents, dataChilds, relations) {
1775
- var e_4, _a, e_5, _b;
1776
- var _this = this;
1777
- var _c = this._valueInRelation(relations), name = _c.name, as = _c.as, relation = _c.relation, localKey = _c.localKey, foreignKey = _c.foreignKey;
1778
- var keyRelation = as !== null && as !== void 0 ? as : name;
1779
- try {
1780
- for (var dataParents_1 = __values(dataParents), dataParents_1_1 = dataParents_1.next(); !dataParents_1_1.done; dataParents_1_1 = dataParents_1.next()) {
1781
- var dataParent = dataParents_1_1.value;
1782
- var relationIsHasOneOrBelongsTo = [
1783
- this.$constants('RELATIONSHIP').hasOne,
1784
- this.$constants('RELATIONSHIP').belongsTo
1785
- ].some(function (r) { return r === relation; });
1786
- if (relationIsHasOneOrBelongsTo)
1787
- dataParent[keyRelation] = null;
1788
- else
1789
- dataParent[keyRelation] = [];
1790
- if (!dataChilds.length)
1791
- continue;
1792
- try {
1793
- for (var dataChilds_1 = (e_5 = void 0, __values(dataChilds)), dataChilds_1_1 = dataChilds_1.next(); !dataChilds_1_1.done; dataChilds_1_1 = dataChilds_1.next()) {
1794
- var dataChild = dataChilds_1_1.value;
1795
- if (dataChild[foreignKey] === dataParent[localKey]) {
1796
- var relationIsHasOneOrBelongsTo_1 = [
1797
- this.$constants('RELATIONSHIP').hasOne,
1798
- this.$constants('RELATIONSHIP').belongsTo
1799
- ].some(function (r) { return r === relation; });
1800
- if (relationIsHasOneOrBelongsTo_1) {
1801
- dataParent[keyRelation] = dataParent[keyRelation] || dataChild;
1802
- continue;
1803
- }
1804
- if (dataParent[keyRelation] == null)
1805
- dataParent[keyRelation] = [];
1806
- dataParent[keyRelation].push(dataChild);
1807
- }
1808
- }
1809
- }
1810
- catch (e_5_1) { e_5 = { error: e_5_1 }; }
1811
- finally {
1812
- try {
1813
- if (dataChilds_1_1 && !dataChilds_1_1.done && (_b = dataChilds_1.return)) _b.call(dataChilds_1);
1814
- }
1815
- finally { if (e_5) throw e_5.error; }
1816
- }
1304
+ }
1305
+ async _execute({ sql, type, message, options }) {
1306
+ let result = await this._queryStatementModel(sql);
1307
+ const emptyData = this._returnEmpty(type, result, message, options);
1308
+ if (!result.length)
1309
+ return emptyData;
1310
+ const relations = this.$db.get('WITH');
1311
+ if (!relations.length)
1312
+ return this._returnResult(type, result) || emptyData;
1313
+ for (const relation of relations) {
1314
+ const relationIsBelongsToMany = relation.relation === this.$constants('RELATIONSHIP').belongsToMany;
1315
+ if (relationIsBelongsToMany) {
1316
+ result = await this._belongsToMany(result, relation);
1317
+ continue;
1817
1318
  }
1319
+ const dataFromRelation = await this._relation(result, relation);
1320
+ result = this._relationMapData(result, dataFromRelation, relation);
1818
1321
  }
1819
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
1820
- finally {
1821
- try {
1822
- if (dataParents_1_1 && !dataParents_1_1.done && (_a = dataParents_1.return)) _a.call(dataParents_1);
1322
+ if (this.$db.get('HIDDEN').length)
1323
+ this._hiddenColumnModel(result);
1324
+ return this._returnResult(type, result) || emptyData;
1325
+ }
1326
+ async _executeGroup(dataParents, type = 'GET') {
1327
+ const emptyData = this._returnEmpty(type, dataParents);
1328
+ if (!dataParents.length)
1329
+ return emptyData;
1330
+ const relations = this.$db.get('WITH');
1331
+ if (relations.length) {
1332
+ for (const relation of relations) {
1333
+ if (relation.relation === this.$constants('RELATIONSHIP').belongsToMany) {
1334
+ return this._belongsToMany(dataParents, relation);
1335
+ }
1336
+ let dataChilds = await this._relation(dataParents, relation);
1337
+ dataParents = this._relationMapData(dataParents, dataChilds, relation);
1823
1338
  }
1824
- finally { if (e_4) throw e_4.error; }
1825
1339
  }
1826
- if (this.$db.get('WITH_EXISTS')) {
1827
- var dataPerentOnlyRelationIsNotNull = dataParents.filter(function (dataPerent) {
1828
- if (Array.isArray(dataPerent[keyRelation])) {
1829
- var isNotEmpty_1 = Boolean(dataPerent[keyRelation].length);
1830
- if (!isNotEmpty_1 && dataPerent.id) {
1831
- _this.$db.set('WITH_EXISTS_NOT_ID', __spreadArray(__spreadArray([], __read(_this.$db.get('WITH_EXISTS_NOT_ID')), false), [
1832
- dataPerent.id
1833
- ], false));
1340
+ if (this.$db.get('HIDDEN')?.length)
1341
+ this._hiddenColumnModel(dataParents);
1342
+ const resultData = this._returnResult(type, dataParents);
1343
+ return resultData || emptyData;
1344
+ }
1345
+ _relationMapData(dataParents, dataChilds, relations) {
1346
+ const { name, as, relation, localKey, foreignKey } = this._valueInRelation(relations);
1347
+ const keyRelation = as ?? name;
1348
+ for (const dataParent of dataParents) {
1349
+ const relationIsHasOneOrBelongsTo = [
1350
+ this.$constants('RELATIONSHIP').hasOne,
1351
+ this.$constants('RELATIONSHIP').belongsTo
1352
+ ].some(r => r === relation);
1353
+ dataParent[keyRelation] = [];
1354
+ if (relationIsHasOneOrBelongsTo)
1355
+ dataParent[keyRelation] = null;
1356
+ if (!dataChilds.length)
1357
+ continue;
1358
+ for (const dataChild of dataChilds) {
1359
+ if (dataChild[foreignKey] === dataParent[localKey]) {
1360
+ const relationIsHasOneOrBelongsTo = [
1361
+ this.$constants('RELATIONSHIP').hasOne,
1362
+ this.$constants('RELATIONSHIP').belongsTo
1363
+ ].some(r => r === relation);
1364
+ if (relationIsHasOneOrBelongsTo) {
1365
+ dataParent[keyRelation] = dataParent[keyRelation] || dataChild;
1366
+ continue;
1834
1367
  }
1835
- return isNotEmpty_1;
1836
- }
1837
- var isNotEmpty = dataPerent[keyRelation] != null;
1838
- if (!isNotEmpty && dataPerent.id) {
1839
- _this.$db.set('WITH_EXISTS_NOT_ID', __spreadArray(__spreadArray([], __read(_this.$db.get('WITH_EXISTS_NOT_ID')), false), [
1840
- dataPerent.id
1841
- ], false));
1368
+ if (dataParent[keyRelation] == null)
1369
+ dataParent[keyRelation] = [];
1370
+ dataParent[keyRelation].push(dataChild);
1842
1371
  }
1843
- return isNotEmpty;
1844
- });
1845
- return dataPerentOnlyRelationIsNotNull;
1372
+ }
1846
1373
  }
1847
1374
  return dataParents;
1848
- };
1849
- Model.prototype._relation = function (parents, relation) {
1850
- var _a;
1851
- return __awaiter(this, void 0, void 0, function () {
1852
- var _b, localKey, foreignKey, localKeyId, dataPerentId, query, dataFromRelation;
1853
- return __generator(this, function (_c) {
1854
- switch (_c.label) {
1855
- case 0:
1856
- if (!((_a = Object.keys(relation)) === null || _a === void 0 ? void 0 : _a.length))
1857
- return [2 /*return*/, []];
1858
- _b = this._valueInRelation(relation), localKey = _b.localKey, foreignKey = _b.foreignKey;
1859
- localKeyId = parents.map(function (parent) {
1860
- return parent[localKey];
1861
- }).filter(function (data) { return data != null; });
1862
- dataPerentId = Array.from(new Set(localKeyId)) || [];
1863
- if (!dataPerentId.length && this.$db.get('WITH_EXISTS'))
1864
- return [2 /*return*/, []];
1865
- this._assertError(!dataPerentId.length, "unknown relationship without primary or foreign key");
1866
- return [4 /*yield*/, relation.query];
1867
- case 1:
1868
- query = _c.sent();
1869
- this._assertError(query == null, "unknown callback query in [relation : '".concat(relation.name, "']"));
1870
- return [4 /*yield*/, query
1871
- .whereIn(foreignKey, dataPerentId)
1872
- .debug(this.$db.get('DEBUG'))
1873
- .ignoreSoftDelete(this.$db.get('SOFT_DELETE_RELATIONS'))
1874
- .get()];
1875
- case 2:
1876
- dataFromRelation = _c.sent();
1877
- return [2 /*return*/, dataFromRelation];
1375
+ }
1376
+ _handleRelationsExists(relation) {
1377
+ this._assertError(!Object.keys(relation)?.length, `unknown [relation]`);
1378
+ const { localKey, foreignKey } = this._valueInRelation(relation);
1379
+ const query = relation.query;
1380
+ this._assertError(query == null, `unknown callback query in [relation : '${relation.name}']`);
1381
+ const clone = new Model().clone(query);
1382
+ if (clone.$db.get('WITH').length) {
1383
+ for (const r of clone.$db.get('WITH')) {
1384
+ if (r.query == null)
1385
+ continue;
1386
+ const sql = clone._handleRelationsExists(r);
1387
+ clone.whereExists(sql);
1388
+ }
1389
+ }
1390
+ const sql = clone
1391
+ .bind(this.$pool.load())
1392
+ .whereReference(`\`${this.tableName}\`.\`${localKey}\``, `\`${query.tableName}\`.\`${foreignKey}\``)
1393
+ .toString();
1394
+ return sql;
1395
+ }
1396
+ _queryRelationsExists() {
1397
+ const relations = this.$db.get('WITH');
1398
+ for (const index in relations) {
1399
+ const relation = relations[index];
1400
+ if (!Object.keys(relation)?.length)
1401
+ continue;
1402
+ const { localKey, foreignKey } = this._valueInRelation(relation);
1403
+ const query = relation.query;
1404
+ this._assertError(query == null, `unknown callback query in [relation : '${relation.name}']`);
1405
+ let clone = new Model().clone(query);
1406
+ if (clone.$db.get('WITH').length) {
1407
+ for (const r of clone.$db.get('WITH')) {
1408
+ if (r.query == null)
1409
+ continue;
1410
+ const sql = clone._handleRelationsExists(r);
1411
+ clone.whereExists(sql);
1878
1412
  }
1879
- });
1880
- });
1881
- };
1882
- Model.prototype._handleBelongsToMany = function (dataFromParent, relation, pivotTable) {
1883
- return __awaiter(this, void 0, void 0, function () {
1884
- var _a, name, localKey, foreignKey, localKeyId, dataPerentId, modelOther, other, otherlocalKey, otherforeignKey, sqldataChilds, dataChilds, otherId, otherArrId, otherdataChilds;
1885
- return __generator(this, function (_b) {
1886
- switch (_b.label) {
1887
- case 0:
1888
- _a = this._valueInRelation(relation), name = _a.name, localKey = _a.localKey, foreignKey = _a.foreignKey;
1889
- localKeyId = dataFromParent.map(function (dataPerent) {
1890
- return dataPerent[localKey];
1891
- }).filter(function (data) { return data != null; });
1892
- dataPerentId = Array.from(new Set(localKeyId)).join(',') || [];
1893
- this._assertError(!dataPerentId.length, "unknown relationship without primary or foreign key");
1894
- modelOther = new relation.model();
1895
- other = this._classToTableName(modelOther.constructor.name, { singular: true });
1896
- otherlocalKey = 'id';
1897
- otherforeignKey = this._valuePattern("".concat(other, "Id"));
1898
- sqldataChilds = [
1899
- "".concat(this.$constants('SELECT')),
1900
- "*",
1901
- "".concat(this.$constants('FROM')),
1902
- "".concat(pivotTable),
1903
- "".concat(this.$constants('WHERE')),
1904
- "".concat(foreignKey, " ").concat(this.$constants('IN'), " (").concat(dataPerentId, ")")
1905
- ].join(' ');
1906
- return [4 /*yield*/, this._queryStatementModel(sqldataChilds)];
1907
- case 1:
1908
- dataChilds = _b.sent();
1909
- otherId = dataChilds.map(function (sub) { return sub[otherforeignKey]; }).filter(function (data) { return data != null; });
1910
- otherArrId = Array.from(new Set(otherId)) || [];
1911
- return [4 /*yield*/, this._queryStatementModel(modelOther
1912
- .whereIn(otherlocalKey, otherArrId)
1913
- .toString())];
1914
- case 2:
1915
- otherdataChilds = _b.sent();
1916
- dataChilds.forEach(function (sub) {
1917
- sub[other] = [];
1918
- otherdataChilds.forEach(function (otherSub) {
1919
- if (otherSub[otherlocalKey] === sub[otherforeignKey]) {
1920
- sub[other] = otherSub;
1921
- }
1922
- });
1923
- });
1924
- dataFromParent.forEach(function (dataPerent) {
1925
- if (dataPerent[name] == null)
1926
- dataPerent[name] = [];
1927
- dataChilds.forEach(function (sub) {
1928
- if (sub[foreignKey] === dataPerent[localKey]) {
1929
- dataPerent[name].push(sub);
1930
- }
1931
- });
1932
- });
1933
- if (this.$db.get('HIDDEN').length)
1934
- this._hiddenColumnModel(dataFromParent);
1935
- return [2 /*return*/, dataFromParent];
1413
+ }
1414
+ const sql = clone
1415
+ .bind(this.$pool.load())
1416
+ .whereReference(`\`${this.tableName}\`.\`${localKey}\``, `\`${query.tableName}\`.\`${foreignKey}\``)
1417
+ .toString();
1418
+ this.whereExists(sql);
1419
+ }
1420
+ const sql = this._buildQueryModel();
1421
+ return sql;
1422
+ }
1423
+ async _relation(parents, relation) {
1424
+ if (!Object.keys(relation)?.length)
1425
+ return [];
1426
+ const { localKey, foreignKey } = this._valueInRelation(relation);
1427
+ const localKeyId = parents.map((parent) => {
1428
+ const data = parent[localKey];
1429
+ if (!parent.hasOwnProperty(localKey)) {
1430
+ this._assertError(data == null, "unknown relationship without primary or foreign key");
1431
+ }
1432
+ return data;
1433
+ }).filter((data) => data != null);
1434
+ const dataPerentId = Array.from(new Set(localKeyId)) || [];
1435
+ if (!dataPerentId.length && this.$db.get('WITH_EXISTS'))
1436
+ return [];
1437
+ const query = await relation.query;
1438
+ this._assertError(query == null, `unknown callback query in [relation : '${relation.name}']`);
1439
+ const dataFromRelation = await query
1440
+ .bind(this.$pool.load())
1441
+ .whereIn(foreignKey, dataPerentId)
1442
+ .debug(this.$db.get('DEBUG'))
1443
+ .get();
1444
+ return dataFromRelation;
1445
+ }
1446
+ async _handleBelongsToMany(dataFromParent, relation, pivotTable) {
1447
+ let { name, localKey, foreignKey } = this._valueInRelation(relation);
1448
+ const localKeyId = dataFromParent.map((parent) => {
1449
+ const data = parent[localKey];
1450
+ if (!parent.hasOwnProperty(localKey)) {
1451
+ this._assertError(data == null, "unknown relationship without primary or foreign key");
1452
+ }
1453
+ return data;
1454
+ }).filter((data) => data != null);
1455
+ const dataPerentId = Array.from(new Set(localKeyId)).join(',') || [];
1456
+ if (!dataPerentId.length && this.$db.get('WITH_EXISTS'))
1457
+ return [];
1458
+ const modelOther = new relation.model();
1459
+ const other = this._classToTableName(modelOther.constructor.name, { singular: true });
1460
+ const otherlocalKey = 'id';
1461
+ const otherforeignKey = this._valuePattern(`${other}Id`);
1462
+ const sqldataChilds = [
1463
+ `${this.$constants('SELECT')}`,
1464
+ `*`,
1465
+ `${this.$constants('FROM')}`,
1466
+ `${pivotTable}`,
1467
+ `${this.$constants('WHERE')}`,
1468
+ `${foreignKey} ${this.$constants('IN')} (${dataPerentId})`
1469
+ ].join(' ');
1470
+ let dataChilds = await this._queryStatementModel(sqldataChilds);
1471
+ const otherId = dataChilds.map((sub) => sub[otherforeignKey]).filter((data) => data != null);
1472
+ const otherArrId = Array.from(new Set(otherId)) || [];
1473
+ const otherdataChilds = await this._queryStatementModel(modelOther
1474
+ .bind(this.$pool.load())
1475
+ .whereIn(otherlocalKey, otherArrId)
1476
+ .debug(this.$db.get('DEBUG'))
1477
+ .toString());
1478
+ dataChilds.forEach((sub) => {
1479
+ sub[other] = [];
1480
+ otherdataChilds.forEach((otherSub) => {
1481
+ if (otherSub[otherlocalKey] === sub[otherforeignKey]) {
1482
+ sub[other] = otherSub;
1936
1483
  }
1937
1484
  });
1938
1485
  });
1939
- };
1940
- Model.prototype._belongsToMany = function (dataFromParent, relation) {
1941
- var _a, _b;
1942
- return __awaiter(this, void 0, void 0, function () {
1943
- var local, modelOther, other, pivotTable, err_1, pivotTable, e_6;
1944
- return __generator(this, function (_c) {
1945
- switch (_c.label) {
1946
- case 0:
1947
- local = this.$utils.columnRelation(this.constructor.name);
1948
- modelOther = new relation.model();
1949
- other = this._classToTableName(modelOther.constructor.name, { singular: true });
1950
- _c.label = 1;
1951
- case 1:
1952
- _c.trys.push([1, 3, , 8]);
1953
- pivotTable = (_a = relation.freezeTable) !== null && _a !== void 0 ? _a : "".concat(local, "_").concat(other);
1954
- return [4 /*yield*/, this._handleBelongsToMany(dataFromParent, relation, pivotTable)];
1955
- case 2: return [2 /*return*/, _c.sent()];
1956
- case 3:
1957
- err_1 = _c.sent();
1958
- _c.label = 4;
1959
- case 4:
1960
- _c.trys.push([4, 6, , 7]);
1961
- pivotTable = (_b = relation.freezeTable) !== null && _b !== void 0 ? _b : "".concat(other, "_").concat(local);
1962
- return [4 /*yield*/, this._handleBelongsToMany(dataFromParent, relation, pivotTable)];
1963
- case 5: return [2 /*return*/, _c.sent()];
1964
- case 6:
1965
- e_6 = _c.sent();
1966
- throw new Error(err_1.message);
1967
- case 7: return [3 /*break*/, 8];
1968
- case 8: return [2 /*return*/];
1486
+ dataFromParent.forEach((dataPerent) => {
1487
+ if (dataPerent[name] == null)
1488
+ dataPerent[name] = [];
1489
+ dataChilds.forEach((sub) => {
1490
+ if (sub[foreignKey] === dataPerent[localKey]) {
1491
+ dataPerent[name].push(sub);
1969
1492
  }
1970
1493
  });
1971
1494
  });
1972
- };
1973
- Model.prototype._pagination = function (data) {
1974
- var _a, _b, _c;
1975
- return __awaiter(this, void 0, void 0, function () {
1976
- var currentPage, limit, sql, res, total, lastPage, nextPage, prevPage, totalPage, meta;
1977
- return __generator(this, function (_d) {
1978
- switch (_d.label) {
1979
- case 0:
1980
- currentPage = +(this.$db.get('PAGE'));
1981
- this.select([
1982
- "".concat(this.$constants('COUNT'), "(").concat(this.$db.get('PRIMARY_KEY'), ")"),
1983
- "".concat(this.$constants('AS')),
1984
- "total"
1985
- ].join(' '));
1986
- limit = Number(this.$db.get('PER_PAGE'));
1987
- this._assertError(limit < 1, "minimun less 1 of limit");
1988
- if (Boolean((_a = this.$db.get('WITH_EXISTS_NOT_ID')) === null || _a === void 0 ? void 0 : _a.length)) {
1989
- this.whereNotIn('id', __spreadArray([], __read(new Set(this.$db.get('WITH_EXISTS_NOT_ID'))), false));
1990
- }
1991
- sql = this._queryGenrateModel();
1992
- return [4 /*yield*/, this._queryStatementModel(sql)];
1993
- case 1:
1994
- res = _d.sent();
1995
- total = (_b = res.shift().total) !== null && _b !== void 0 ? _b : 0;
1996
- lastPage = Math.ceil(total / limit) || 0;
1997
- lastPage = lastPage > 1 ? lastPage : 1;
1998
- nextPage = currentPage + 1;
1999
- prevPage = currentPage - 1 === 0 ? 1 : currentPage - 1;
2000
- totalPage = (_c = data === null || data === void 0 ? void 0 : data.length) !== null && _c !== void 0 ? _c : 0;
2001
- meta = {
2002
- total: total,
2003
- limit: limit,
2004
- totalPage: totalPage,
2005
- currentPage: currentPage,
2006
- lastPage: lastPage,
2007
- nextPage: nextPage,
2008
- prevPage: prevPage,
2009
- };
2010
- if (this._isPatternSnakeCase()) {
2011
- return [2 /*return*/, this.$utils.snakeCase(this._result({
2012
- meta: meta,
2013
- data: data
2014
- }))];
2015
- }
2016
- return [2 /*return*/, this._result({
2017
- meta: meta,
2018
- data: data
2019
- })];
2020
- }
2021
- });
1495
+ if (this.$db.get('HIDDEN').length)
1496
+ this._hiddenColumnModel(dataFromParent);
1497
+ return dataFromParent;
1498
+ }
1499
+ async _belongsToMany(dataFromParent, relation) {
1500
+ const local = this.$utils.columnRelation(this.constructor.name);
1501
+ const modelOther = new relation.model();
1502
+ const other = this._classToTableName(modelOther.constructor.name, { singular: true });
1503
+ try {
1504
+ const pivotTable = relation.freezeTable ?? `${local}_${other}`;
1505
+ return await this._handleBelongsToMany(dataFromParent, relation, pivotTable);
1506
+ }
1507
+ catch (err) {
1508
+ try {
1509
+ const pivotTable = relation.freezeTable ?? `${other}_${local}`;
1510
+ return await this._handleBelongsToMany(dataFromParent, relation, pivotTable);
1511
+ }
1512
+ catch (e) {
1513
+ throw new Error(err.message);
1514
+ }
1515
+ }
1516
+ }
1517
+ async _pagination(data) {
1518
+ const currentPage = +(this.$db.get('PAGE'));
1519
+ this.select([
1520
+ `${this.$constants('COUNT')}(${this.$db.get('PRIMARY_KEY')})`,
1521
+ `${this.$constants('AS')}`,
1522
+ `total`
1523
+ ].join(' '));
1524
+ const limit = Number(this.$db.get('PER_PAGE'));
1525
+ this._assertError(limit < 1, "minimun less 1 of limit");
1526
+ const sql = this._buildQueryModel();
1527
+ const res = await this._queryStatementModel(sql);
1528
+ const total = res.shift().total ?? 0;
1529
+ let lastPage = Math.ceil(total / limit) || 0;
1530
+ lastPage = lastPage > 1 ? lastPage : 1;
1531
+ const nextPage = currentPage + 1;
1532
+ const prevPage = currentPage - 1 === 0 ? 1 : currentPage - 1;
1533
+ const totalPage = data?.length ?? 0;
1534
+ const meta = {
1535
+ total,
1536
+ limit,
1537
+ totalPage,
1538
+ currentPage,
1539
+ lastPage,
1540
+ nextPage,
1541
+ prevPage,
1542
+ };
1543
+ if (this._isPatternSnakeCase()) {
1544
+ return this.$utils.snakeCase(this._result({
1545
+ meta,
1546
+ data
1547
+ }));
1548
+ }
1549
+ return this._result({
1550
+ meta,
1551
+ data
2022
1552
  });
2023
- };
2024
- Model.prototype._result = function (data) {
1553
+ }
1554
+ _result(data) {
2025
1555
  this.$db.get('RESULT', data);
2026
1556
  return data;
2027
- };
2028
- Model.prototype._returnEmpty = function (type) {
2029
- var emptyData = null;
1557
+ }
1558
+ _returnEmpty(type, result, message, options) {
1559
+ let emptyData = null;
2030
1560
  switch (type) {
2031
1561
  case 'FIRST': {
2032
1562
  emptyData = null;
2033
1563
  break;
2034
1564
  }
1565
+ case 'FIRST_OR_ERROR': {
1566
+ if (!result?.length) {
1567
+ if (options == null) {
1568
+ throw {
1569
+ message,
1570
+ code: 400
1571
+ };
1572
+ }
1573
+ throw {
1574
+ message,
1575
+ ...options
1576
+ };
1577
+ }
1578
+ emptyData = null;
1579
+ break;
1580
+ }
2035
1581
  case 'GET': {
2036
1582
  emptyData = [];
2037
1583
  break;
@@ -2055,39 +1601,52 @@ var Model = /** @class */ (function (_super) {
2055
1601
  throw new Error('Missing method first get or pagination');
2056
1602
  }
2057
1603
  }
2058
- if (this._isPatternSnakeCase())
1604
+ if (this._isPatternSnakeCase()) {
2059
1605
  return this.$utils.snakeCase(this._result(emptyData));
1606
+ }
2060
1607
  return this._result(emptyData);
2061
- };
2062
- Model.prototype._returnResult = function (type, data) {
2063
- var _this = this;
2064
- var _a, _b, _c;
2065
- if ((_a = Object.keys(this.$db.get('REGISTRY'))) === null || _a === void 0 ? void 0 : _a.length) {
2066
- data === null || data === void 0 ? void 0 : data.forEach(function (d) {
2067
- for (var name in _this.$db.get('REGISTRY')) {
2068
- var registry = _this.$db.get('REGISTRY');
1608
+ }
1609
+ _returnResult(type, data) {
1610
+ if (Object.keys(this.$db.get('REGISTRY'))?.length) {
1611
+ data?.forEach((d) => {
1612
+ for (const name in this.$db.get('REGISTRY')) {
1613
+ const registry = this.$db.get('REGISTRY');
2069
1614
  d[name] = registry[name];
2070
1615
  }
2071
1616
  });
2072
1617
  }
2073
- if ((_b = this.$db.get('ONLY')) === null || _b === void 0 ? void 0 : _b.length) {
1618
+ if (this.$db.get('ONLY')?.length) {
2074
1619
  data = this._showOnly(data);
2075
1620
  }
2076
1621
  switch (type) {
2077
1622
  case 'FIRST': {
2078
1623
  if (this.$db.get('PLUCK')) {
2079
- var pluck = this.$db.get('PLUCK');
2080
- var newData = data.shift();
2081
- var checkProperty = newData.hasOwnProperty(pluck);
2082
- this._assertError(!checkProperty, "can't find property '".concat(pluck, "' of result"));
1624
+ const pluck = this.$db.get('PLUCK');
1625
+ const newData = data.shift();
1626
+ const checkProperty = newData.hasOwnProperty(pluck);
1627
+ this._assertError(!checkProperty, `can't find property '${pluck}' of result`);
2083
1628
  return this._result(newData[pluck]);
2084
1629
  }
2085
- return this._result((_c = data.shift()) !== null && _c !== void 0 ? _c : null);
1630
+ return this._result(data.shift() ?? null);
1631
+ }
1632
+ case 'FIRST_OR_ERROR': {
1633
+ if (this.$db.get('PLUCK')) {
1634
+ const pluck = this.$db.get('PLUCK');
1635
+ const newData = data.shift();
1636
+ const checkProperty = newData.hasOwnProperty(pluck);
1637
+ this._assertError(!checkProperty, `can't find property '${pluck}' of result`);
1638
+ const result = this._result(newData[pluck]) ?? null;
1639
+ return result;
1640
+ }
1641
+ const result = this._result(data.shift() ?? null);
1642
+ if (result == null)
1643
+ throw new Error();
1644
+ return result;
2086
1645
  }
2087
1646
  case 'GET': {
2088
1647
  if (this.$db.get('CHUNK')) {
2089
- var result = data.reduce(function (resultArray, item, index) {
2090
- var chunkIndex = Math.floor(index / _this.$db.get('CHUNK'));
1648
+ const result = data.reduce((resultArray, item, index) => {
1649
+ const chunkIndex = Math.floor(index / this.$db.get('CHUNK'));
2091
1650
  if (!resultArray[chunkIndex])
2092
1651
  resultArray[chunkIndex] = [];
2093
1652
  resultArray[chunkIndex].push(item);
@@ -2096,9 +1655,9 @@ var Model = /** @class */ (function (_super) {
2096
1655
  return this._result(result);
2097
1656
  }
2098
1657
  if (this.$db.get('PLUCK')) {
2099
- var pluck_1 = this.$db.get('PLUCK');
2100
- var newData = data.map(function (d) { return d[pluck_1]; });
2101
- this._assertError(newData.every(function (d) { return d == null; }), "can't find property '".concat(pluck_1, "' of result"));
1658
+ const pluck = this.$db.get('PLUCK');
1659
+ const newData = data.map((d) => d[pluck]);
1660
+ this._assertError(newData.every((d) => d == null), `can't find property '${pluck}' of result`);
2102
1661
  return this._result(newData);
2103
1662
  }
2104
1663
  return this._result(data);
@@ -2110,574 +1669,401 @@ var Model = /** @class */ (function (_super) {
2110
1669
  throw new Error('Missing method first get or pagination');
2111
1670
  }
2112
1671
  }
2113
- };
2114
- Model.prototype._hiddenColumnModel = function (object) {
2115
- var hidden = this.$db.get('HIDDEN');
2116
- if (object === null || object === void 0 ? void 0 : object.length) {
2117
- hidden.forEach(function (column) {
2118
- object.forEach(function (objColumn) {
1672
+ }
1673
+ _hiddenColumnModel(object) {
1674
+ const hidden = this.$db.get('HIDDEN');
1675
+ if (object?.length) {
1676
+ hidden.forEach((column) => {
1677
+ object.forEach((objColumn) => {
2119
1678
  delete objColumn[column];
2120
1679
  });
2121
1680
  });
2122
1681
  }
2123
1682
  return object;
2124
- };
2125
- Model.prototype._attach = function (name, dataId, fields) {
2126
- var _a;
2127
- return __awaiter(this, void 0, void 0, function () {
2128
- var relation, thisTable, relationTable, result, pivotTable, success, e_7, errorTable, search, pivotTable, success, e_8;
2129
- var _this = this;
2130
- return __generator(this, function (_b) {
2131
- switch (_b.label) {
2132
- case 0:
2133
- this._assertError(!Array.isArray(dataId), "this ".concat(dataId, " is not an array"));
2134
- relation = (_a = this.$db.get('RELATION')) === null || _a === void 0 ? void 0 : _a.find(function (data) { return data.name === name; });
2135
- this._assertError(!relation, "unknown name relation ['".concat(name, "'] in model"));
2136
- thisTable = this.$utils.columnRelation(this.constructor.name);
2137
- relationTable = this._classToTableName(relation.model.name, { singular: true });
2138
- result = this.$db.get('RESULT');
2139
- _b.label = 1;
2140
- case 1:
2141
- _b.trys.push([1, 3, , 8]);
2142
- pivotTable = "".concat(thisTable, "_").concat(relationTable);
2143
- return [4 /*yield*/, new DB_1.DB().table(pivotTable).createMultiple(dataId.map(function (id) {
2144
- var _a;
2145
- return __assign((_a = {}, _a[_this._valuePattern("".concat(relationTable, "Id"))] = id, _a[_this._valuePattern("".concat(thisTable, "Id"))] = result.id, _a), fields);
2146
- })).save()];
2147
- case 2:
2148
- success = _b.sent();
2149
- return [2 /*return*/, success];
2150
- case 3:
2151
- e_7 = _b.sent();
2152
- errorTable = e_7.message;
2153
- search = errorTable.search("ER_NO_SUCH_TABLE");
2154
- if (!!search)
2155
- throw new Error(e_7.message);
2156
- _b.label = 4;
2157
- case 4:
2158
- _b.trys.push([4, 6, , 7]);
2159
- pivotTable = "".concat(relationTable, "_").concat(thisTable);
2160
- return [4 /*yield*/, new DB_1.DB().table(pivotTable).createMultiple(dataId.map(function (id) {
2161
- var _a;
2162
- return __assign((_a = {}, _a[_this._valuePattern("".concat(relationTable, "Id"))] = id, _a[_this._valuePattern("".concat(thisTable, "Id"))] = result.id, _a), fields);
2163
- })).save()];
2164
- case 5:
2165
- success = _b.sent();
2166
- return [2 /*return*/, success];
2167
- case 6:
2168
- e_8 = _b.sent();
2169
- throw new Error(e_8.message);
2170
- case 7: return [3 /*break*/, 8];
2171
- case 8: return [2 /*return*/];
2172
- }
2173
- });
2174
- });
2175
- };
2176
- Model.prototype._detach = function (name, dataId) {
2177
- return __awaiter(this, void 0, void 0, function () {
2178
- var relation, thisTable, relationTable, result, pivotTable, dataId_1, dataId_1_1, id, e_9_1, e_10, errorTable, search, pivotTable, dataId_2, dataId_2_1, id, e_11_1, e_12;
2179
- var e_9, _a, e_11, _b;
2180
- return __generator(this, function (_c) {
2181
- switch (_c.label) {
2182
- case 0:
2183
- this._assertError(!Array.isArray(dataId), "this ".concat(dataId, " is not an array"));
2184
- relation = this.$db.get('RELATION').find(function (data) { return data.name === name; });
2185
- this._assertError(!relation, "unknown name relation [".concat(name, "] in model"));
2186
- thisTable = this.$utils.columnRelation(this.constructor.name);
2187
- relationTable = this._classToTableName(relation.model.name, { singular: true });
2188
- result = this.$db.get('RESULT');
2189
- _c.label = 1;
2190
- case 1:
2191
- _c.trys.push([1, 10, , 22]);
2192
- pivotTable = "".concat(thisTable, "_").concat(relationTable);
2193
- _c.label = 2;
2194
- case 2:
2195
- _c.trys.push([2, 7, 8, 9]);
2196
- dataId_1 = __values(dataId), dataId_1_1 = dataId_1.next();
2197
- _c.label = 3;
2198
- case 3:
2199
- if (!!dataId_1_1.done) return [3 /*break*/, 6];
2200
- id = dataId_1_1.value;
2201
- return [4 /*yield*/, new DB_1.DB().table(pivotTable)
2202
- .where(this._valuePattern("".concat(relationTable, "Id")), id)
2203
- .where(this._valuePattern("".concat(thisTable, "Id")), result.id)
2204
- .delete()];
2205
- case 4:
2206
- _c.sent();
2207
- _c.label = 5;
2208
- case 5:
2209
- dataId_1_1 = dataId_1.next();
2210
- return [3 /*break*/, 3];
2211
- case 6: return [3 /*break*/, 9];
2212
- case 7:
2213
- e_9_1 = _c.sent();
2214
- e_9 = { error: e_9_1 };
2215
- return [3 /*break*/, 9];
2216
- case 8:
2217
- try {
2218
- if (dataId_1_1 && !dataId_1_1.done && (_a = dataId_1.return)) _a.call(dataId_1);
2219
- }
2220
- finally { if (e_9) throw e_9.error; }
2221
- return [7 /*endfinally*/];
2222
- case 9: return [2 /*return*/, true];
2223
- case 10:
2224
- e_10 = _c.sent();
2225
- errorTable = e_10.message;
2226
- search = errorTable.search("ER_NO_SUCH_TABLE");
2227
- if (!!search)
2228
- throw new Error(e_10.message);
2229
- _c.label = 11;
2230
- case 11:
2231
- _c.trys.push([11, 20, , 21]);
2232
- pivotTable = "".concat(relationTable, "_").concat(thisTable);
2233
- _c.label = 12;
2234
- case 12:
2235
- _c.trys.push([12, 17, 18, 19]);
2236
- dataId_2 = __values(dataId), dataId_2_1 = dataId_2.next();
2237
- _c.label = 13;
2238
- case 13:
2239
- if (!!dataId_2_1.done) return [3 /*break*/, 16];
2240
- id = dataId_2_1.value;
2241
- return [4 /*yield*/, new DB_1.DB().table(pivotTable)
2242
- .where(this._valuePattern("".concat(relationTable, "Id")), id)
2243
- .where(this._valuePattern("".concat(thisTable, "Id")), result.id)
2244
- .delete()];
2245
- case 14:
2246
- _c.sent();
2247
- _c.label = 15;
2248
- case 15:
2249
- dataId_2_1 = dataId_2.next();
2250
- return [3 /*break*/, 13];
2251
- case 16: return [3 /*break*/, 19];
2252
- case 17:
2253
- e_11_1 = _c.sent();
2254
- e_11 = { error: e_11_1 };
2255
- return [3 /*break*/, 19];
2256
- case 18:
2257
- try {
2258
- if (dataId_2_1 && !dataId_2_1.done && (_b = dataId_2.return)) _b.call(dataId_2);
2259
- }
2260
- finally { if (e_11) throw e_11.error; }
2261
- return [7 /*endfinally*/];
2262
- case 19: return [2 /*return*/, true];
2263
- case 20:
2264
- e_12 = _c.sent();
2265
- throw new Error(e_12.message);
2266
- case 21: return [3 /*break*/, 22];
2267
- case 22: return [2 /*return*/];
1683
+ }
1684
+ async _attach(name, dataId, fields) {
1685
+ this._assertError(!Array.isArray(dataId), `this ${dataId} is not an array`);
1686
+ const relation = this.$db.get('RELATION')?.find((data) => data.name === name);
1687
+ this._assertError(!relation, `unknown name relation ['${name}'] in model`);
1688
+ const thisTable = this.$utils.columnRelation(this.constructor.name);
1689
+ const relationTable = this._classToTableName(relation.model.name, { singular: true });
1690
+ const result = this.$db.get('RESULT');
1691
+ try {
1692
+ const pivotTable = `${thisTable}_${relationTable}`;
1693
+ const success = await new DB_1.DB().table(pivotTable).createMultiple(dataId.map((id) => {
1694
+ return {
1695
+ [this._valuePattern(`${relationTable}Id`)]: id,
1696
+ [this._valuePattern(`${thisTable}Id`)]: result.id,
1697
+ ...fields
1698
+ };
1699
+ })).save();
1700
+ return success;
1701
+ }
1702
+ catch (e) {
1703
+ const errorTable = e.message;
1704
+ const search = errorTable.search("ER_NO_SUCH_TABLE");
1705
+ if (!!search)
1706
+ throw new Error(e.message);
1707
+ try {
1708
+ const pivotTable = `${relationTable}_${thisTable}`;
1709
+ const success = await new DB_1.DB().table(pivotTable).createMultiple(dataId.map((id) => {
1710
+ return {
1711
+ [this._valuePattern(`${relationTable}Id`)]: id,
1712
+ [this._valuePattern(`${thisTable}Id`)]: result.id,
1713
+ ...fields
1714
+ };
1715
+ })).save();
1716
+ return success;
1717
+ }
1718
+ catch (e) {
1719
+ throw new Error(e.message);
1720
+ }
1721
+ }
1722
+ }
1723
+ async _detach(name, dataId) {
1724
+ this._assertError(!Array.isArray(dataId), `this ${dataId} is not an array`);
1725
+ const relation = this.$db.get('RELATION').find((data) => data.name === name);
1726
+ this._assertError(!relation, `unknown name relation [${name}] in model`);
1727
+ const thisTable = this.$utils.columnRelation(this.constructor.name);
1728
+ const relationTable = this._classToTableName(relation.model.name, { singular: true });
1729
+ const result = this.$db.get('RESULT');
1730
+ try {
1731
+ const pivotTable = `${thisTable}_${relationTable}`;
1732
+ for (const id of dataId) {
1733
+ await new DB_1.DB().table(pivotTable)
1734
+ .where(this._valuePattern(`${relationTable}Id`), id)
1735
+ .where(this._valuePattern(`${thisTable}Id`), result.id)
1736
+ .delete();
1737
+ }
1738
+ return true;
1739
+ }
1740
+ catch (e) {
1741
+ const errorTable = e.message;
1742
+ const search = errorTable.search("ER_NO_SUCH_TABLE");
1743
+ if (!!search)
1744
+ throw new Error(e.message);
1745
+ try {
1746
+ const pivotTable = `${relationTable}_${thisTable}`;
1747
+ for (const id of dataId) {
1748
+ await new DB_1.DB().table(pivotTable)
1749
+ .where(this._valuePattern(`${relationTable}Id`), id)
1750
+ .where(this._valuePattern(`${thisTable}Id`), result.id)
1751
+ .delete();
2268
1752
  }
2269
- });
2270
- });
2271
- };
2272
- Model.prototype._queryUpdateModel = function (objects) {
2273
- var _a;
2274
- var _this = this;
1753
+ return true;
1754
+ }
1755
+ catch (e) {
1756
+ throw new Error(e.message);
1757
+ }
1758
+ }
1759
+ }
1760
+ _queryUpdateModel(objects) {
2275
1761
  if (this.$db.get('TIMESTAMP')) {
2276
- var updatedAt = this._valuePattern('updatedAt');
2277
- objects = __assign(__assign({}, objects), (_a = {}, _a[updatedAt] = this.$utils.timestamp(), _a));
1762
+ const updatedAt = this._valuePattern(this.$db.get('TIMESTAMP_FORMAT').UPDATED_AT);
1763
+ objects = { ...objects,
1764
+ [updatedAt]: this.$utils.timestamp(),
1765
+ };
2278
1766
  }
2279
- var keyValue = Object.entries(objects).map(function (_a) {
2280
- var _b = __read(_a, 2), column = _b[0], value = _b[1];
2281
- return "".concat(column, " = ").concat(value == null || value === 'NULL'
1767
+ const keyValue = Object.entries(objects).map(([column, value]) => {
1768
+ return `${column} = ${value == null || value === 'NULL'
2282
1769
  ? 'NULL'
2283
- : "'".concat(_this.$utils.covertBooleanToNumber(value), "'"));
1770
+ : `'${this.$utils.covertBooleanToNumber(value)}'`}`;
2284
1771
  });
2285
- return "".concat(this.$constants('SET'), " ").concat(keyValue);
2286
- };
2287
- Model.prototype._queryInsertModel = function (objects) {
2288
- var _a, _b;
2289
- var _this = this;
1772
+ return `${this.$constants('SET')} ${keyValue}`;
1773
+ }
1774
+ _queryInsertModel(objects) {
2290
1775
  if (this.$db.get('TIMESTAMP')) {
2291
- var createdAt = this._valuePattern(this.$db.get('TIMESTAMP_FORMAT').CREATED_AT);
2292
- var updatedAt = this._valuePattern(this.$db.get('TIMESTAMP_FORMAT').UPDATED_AT);
2293
- objects = __assign(__assign({}, objects), (_a = {}, _a[createdAt] = this.$utils.timestamp(), _a[updatedAt] = this.$utils.timestamp(), _a));
1776
+ const createdAt = this._valuePattern(this.$db.get('TIMESTAMP_FORMAT').CREATED_AT);
1777
+ const updatedAt = this._valuePattern(this.$db.get('TIMESTAMP_FORMAT').UPDATED_AT);
1778
+ objects = { ...objects,
1779
+ [createdAt]: this.$utils.timestamp(),
1780
+ [updatedAt]: this.$utils.timestamp(),
1781
+ };
2294
1782
  }
2295
1783
  if (this.$db.get('UUID')) {
2296
- console.log(this.$db.get('UUID_FORMAT'));
2297
- objects = __assign(__assign({}, objects), (_b = {}, _b[this.$db.get('UUID_FORMAT')] = this.$utils.generateUUID(), _b));
1784
+ objects = {
1785
+ ...objects,
1786
+ [this.$db.get('UUID_FORMAT')]: this.$utils.generateUUID()
1787
+ };
2298
1788
  }
2299
- var columns = Object.keys(objects).map(function (data) { return "".concat(data); });
2300
- var values = Object.values(objects).map(function (data) {
2301
- return "".concat(data == null || data === 'NULL' ?
1789
+ const columns = Object.keys(objects).map((column) => `\`${column}\``);
1790
+ const values = Object.values(objects).map((data) => {
1791
+ return `${data == null || data === 'NULL' ?
2302
1792
  'NULL' :
2303
- "'".concat(_this.$utils.covertBooleanToNumber(data), "'"));
1793
+ `'${this.$utils.covertBooleanToNumber(data)}'`}`;
2304
1794
  });
2305
- return "(".concat(columns, ") ").concat(this.$constants('VALUES'), " (").concat(values, ")");
2306
- };
2307
- Model.prototype._queryInsertMultipleModel = function (data) {
2308
- var e_13, _a, _b, _c;
2309
- var _this = this;
2310
- var _d;
2311
- var values = [];
2312
- try {
2313
- for (var data_1 = __values(data), data_1_1 = data_1.next(); !data_1_1.done; data_1_1 = data_1.next()) {
2314
- var objects = data_1_1.value;
2315
- if (this.$db.get('TIMESTAMP')) {
2316
- var createdAt = this._valuePattern(this.$db.get('TIMESTAMP_FORMAT').CREATED_AT);
2317
- var updatedAt = this._valuePattern(this.$db.get('TIMESTAMP_FORMAT').UPDATED_AT);
2318
- objects = __assign(__assign({}, objects), (_b = {}, _b[createdAt] = this.$utils.timestamp(), _b[updatedAt] = this.$utils.timestamp(), _b));
2319
- }
2320
- if (this.$db.get('UUID')) {
2321
- objects = __assign(__assign({}, objects), (_c = {}, _c[this.$db.get('UUID_FORMAT')] = this.$utils.generateUUID(), _c));
2322
- }
2323
- var val = Object.values(objects).map(function (data) {
2324
- return "".concat(data == null || data === 'NULL' ?
2325
- 'NULL' :
2326
- "'".concat(_this.$utils.covertBooleanToNumber(data), "'"));
2327
- });
2328
- values.push("(".concat(val.join(','), ")"));
1795
+ return [
1796
+ `(${columns})`,
1797
+ `${this.$constants('VALUES')}`,
1798
+ `(${values})`
1799
+ ].join(' ');
1800
+ }
1801
+ _queryInsertMultipleModel(data) {
1802
+ let values = [];
1803
+ let columns = Object.keys([...data]?.shift()).map((column) => `\`${column}\``);
1804
+ for (let objects of data) {
1805
+ if (this.$db.get('TIMESTAMP')) {
1806
+ const createdAt = this._valuePattern(this.$db.get('TIMESTAMP_FORMAT').CREATED_AT);
1807
+ const updatedAt = this._valuePattern(this.$db.get('TIMESTAMP_FORMAT').UPDATED_AT);
1808
+ objects = { ...objects,
1809
+ [createdAt]: this.$utils.timestamp(),
1810
+ [updatedAt]: this.$utils.timestamp(),
1811
+ };
1812
+ columns = [
1813
+ ...columns,
1814
+ `\`${createdAt}\``,
1815
+ `\`${updatedAt}\``
1816
+ ];
2329
1817
  }
2330
- }
2331
- catch (e_13_1) { e_13 = { error: e_13_1 }; }
2332
- finally {
2333
- try {
2334
- if (data_1_1 && !data_1_1.done && (_a = data_1.return)) _a.call(data_1);
1818
+ if (this.$db.get('UUID')) {
1819
+ const uuid = this.$db.get('UUID_FORMAT');
1820
+ objects = {
1821
+ ...objects,
1822
+ [uuid]: this.$utils.generateUUID()
1823
+ };
1824
+ columns = [
1825
+ ...columns,
1826
+ `\`${uuid}\``
1827
+ ];
2335
1828
  }
2336
- finally { if (e_13) throw e_13.error; }
1829
+ const v = Object.values(objects).map((data) => {
1830
+ return `${data == null || data === 'NULL' ?
1831
+ 'NULL' :
1832
+ `'${this.$utils.covertBooleanToNumber(data)}'`}`;
1833
+ });
1834
+ values = [
1835
+ ...values,
1836
+ `(${v.join(',')})`
1837
+ ];
2337
1838
  }
2338
- var columns = Object.keys((_d = data[0]) !== null && _d !== void 0 ? _d : []).map(function (data) { return "".concat(data); });
2339
- return "(".concat(columns, ") ").concat(this.$constants('VALUES'), " ").concat(values.join(','));
2340
- };
2341
- Model.prototype._registry = function (data) {
2342
- var _this = this;
2343
- var _a;
2344
- if ((_a = Object.keys(this.$db.get('REGISTRY'))) === null || _a === void 0 ? void 0 : _a.length) {
2345
- data === null || data === void 0 ? void 0 : data.forEach(function (d) {
2346
- for (var name in _this.$db.get('REGISTRY')) {
2347
- var registry = _this.$db.get('REGISTRY');
1839
+ return [
1840
+ `(${[...new Set(columns)].join(',')})`,
1841
+ `${this.$constants('VALUES')}`,
1842
+ `${values.join(',')}`
1843
+ ].join(' ');
1844
+ }
1845
+ _registry(data) {
1846
+ if (Object.keys(this.$db.get('REGISTRY'))?.length) {
1847
+ data?.forEach((d) => {
1848
+ for (const name in this.$db.get('REGISTRY')) {
1849
+ const registry = this.$db.get('REGISTRY');
2348
1850
  d[name] = registry[name];
2349
1851
  }
2350
1852
  });
2351
1853
  }
2352
1854
  return this;
2353
- };
2354
- Model.prototype._insertNotExistsModel = function () {
2355
- var _a;
2356
- return __awaiter(this, void 0, void 0, function () {
2357
- var sql, check, _b, result, _c, _d, result_3, id, sql_1, data;
2358
- return __generator(this, function (_e) {
2359
- switch (_e.label) {
2360
- case 0:
2361
- this._assertError(!this.$db.get('WHERE'), "can't insert [insertNotExists] without where condition");
2362
- sql = [
2363
- "".concat(this.$constants('SELECT')),
2364
- "".concat(this.$constants('EXISTS'), "(").concat(this.$constants('SELECT')),
2365
- "*",
2366
- "".concat(this.$db.get('FROM')),
2367
- "".concat(this.$db.get('TABLE_NAME')),
2368
- "".concat(this.$db.get('WHERE')),
2369
- "".concat(this.$constants('LIMIT'), " 1)"),
2370
- "".concat(this.$constants('AS'), " 'exists'")
2371
- ].join(' ');
2372
- check = false;
2373
- return [4 /*yield*/, this._queryStatementModel(sql)];
2374
- case 1:
2375
- _b = __read.apply(void 0, [_e.sent(), 1]), result = _b[0].exists;
2376
- check = !!parseInt(result);
2377
- _c = check;
2378
- switch (_c) {
2379
- case false: return [3 /*break*/, 2];
2380
- case true: return [3 /*break*/, 6];
2381
- }
2382
- return [3 /*break*/, 7];
2383
- case 2: return [4 /*yield*/, this._actionStatementModel({
2384
- sql: this.$db.get('INSERT'),
2385
- returnId: true
2386
- })];
2387
- case 3:
2388
- _d = __read.apply(void 0, [_e.sent(), 2]), result_3 = _d[0], id = _d[1];
2389
- if (this.$db.get('TRANSACTION')) {
2390
- (_a = this.$db.get('TRANSACTION')) === null || _a === void 0 ? void 0 : _a.query.push({
2391
- table: this.$db.get('TABLE_NAME'),
2392
- id: id
2393
- });
2394
- }
2395
- if (!result_3) return [3 /*break*/, 5];
2396
- sql_1 = [
2397
- "".concat(this.$db.get('SELECT')),
2398
- "".concat(this.$db.get('FROM')),
2399
- "".concat(this.$db.get('TABLE_NAME')),
2400
- "".concat(this.$constants('WHERE'), " id = ").concat(id)
2401
- ].join(' ');
2402
- return [4 /*yield*/, this._queryStatementModel(sql_1)];
2403
- case 4:
2404
- data = _e.sent();
2405
- return [2 /*return*/, (data === null || data === void 0 ? void 0 : data.shift()) || null];
2406
- case 5: return [2 /*return*/, null];
2407
- case 6:
2408
- {
2409
- return [2 /*return*/, null];
2410
- }
2411
- _e.label = 7;
2412
- case 7:
2413
- {
2414
- return [2 /*return*/, null];
2415
- }
2416
- _e.label = 8;
2417
- case 8: return [2 /*return*/];
1855
+ }
1856
+ async _insertNotExistsModel() {
1857
+ this._assertError(!this.$db.get('WHERE'), "can't insert [insertNotExists] without where condition");
1858
+ let sql = [
1859
+ `${this.$constants('SELECT')}`,
1860
+ `${this.$constants('EXISTS')}(${this.$constants('SELECT')}`,
1861
+ `*`,
1862
+ `${this.$db.get('FROM')}`,
1863
+ `${this.$db.get('TABLE_NAME')}`,
1864
+ `${this.$db.get('WHERE')}`,
1865
+ `${this.$constants('LIMIT')} 1)`,
1866
+ `${this.$constants('AS')} 'exists'`
1867
+ ].join(' ');
1868
+ let check = false;
1869
+ const [{ exists: result }] = await this._queryStatementModel(sql);
1870
+ check = !!parseInt(result);
1871
+ switch (check) {
1872
+ case false: {
1873
+ const [result, id] = await this._actionStatementModel({
1874
+ sql: this.$db.get('INSERT'),
1875
+ returnId: true
1876
+ });
1877
+ if (result) {
1878
+ const sql = [
1879
+ `${this.$db.get('SELECT')}`,
1880
+ `${this.$db.get('FROM')}`,
1881
+ `${this.$db.get('TABLE_NAME')}`,
1882
+ `${this.$constants('WHERE')} id = ${id}`
1883
+ ].join(' ');
1884
+ const data = await this._queryStatementModel(sql);
1885
+ return data?.shift() || null;
2418
1886
  }
2419
- });
1887
+ return null;
1888
+ }
1889
+ case true: {
1890
+ return null;
1891
+ }
1892
+ default: {
1893
+ return null;
1894
+ }
1895
+ }
1896
+ }
1897
+ async _createModel() {
1898
+ const [result, id] = await this._actionStatementModel({
1899
+ sql: this.$db.get('INSERT'),
1900
+ returnId: true
2420
1901
  });
2421
- };
2422
- Model.prototype._createModel = function () {
2423
- var _a;
2424
- return __awaiter(this, void 0, void 0, function () {
2425
- var _b, result, id, sql, data, result_4;
2426
- return __generator(this, function (_c) {
2427
- switch (_c.label) {
2428
- case 0: return [4 /*yield*/, this._actionStatementModel({
2429
- sql: this.$db.get('INSERT'),
2430
- returnId: true
2431
- })];
2432
- case 1:
2433
- _b = __read.apply(void 0, [_c.sent(), 2]), result = _b[0], id = _b[1];
2434
- if (this.$db.get('TRANSACTION')) {
2435
- (_a = this.$db.get('TRANSACTION')) === null || _a === void 0 ? void 0 : _a.query.push({
2436
- table: this.$db.get('TABLE_NAME'),
2437
- id: id
2438
- });
2439
- }
2440
- if (!result) return [3 /*break*/, 3];
2441
- sql = [
2442
- "".concat(this.$db.get('SELECT')),
2443
- "".concat(this.$db.get('FROM')),
2444
- "".concat(this.$db.get('TABLE_NAME')),
2445
- "".concat(this.$constants('WHERE'), " id = ").concat(id)
2446
- ].join(' ');
2447
- return [4 /*yield*/, this._queryStatementModel(sql)];
2448
- case 2:
2449
- data = _c.sent();
2450
- result_4 = (data === null || data === void 0 ? void 0 : data.shift()) || null;
2451
- this.$db.set('RESULT', result_4);
2452
- return [2 /*return*/, result_4];
2453
- case 3: return [2 /*return*/, null];
2454
- }
2455
- });
1902
+ if (result) {
1903
+ const sql = [
1904
+ `${this.$db.get('SELECT')}`,
1905
+ `${this.$db.get('FROM')}`,
1906
+ `${this.$db.get('TABLE_NAME')}`,
1907
+ `${this.$constants('WHERE')} id = ${id}`
1908
+ ].join(' ');
1909
+ const data = await this._queryStatementModel(sql);
1910
+ const result = data?.shift() || null;
1911
+ this.$db.set('RESULT', result);
1912
+ return result;
1913
+ }
1914
+ return null;
1915
+ }
1916
+ async _createMultipleModel() {
1917
+ const [result, id] = await this._actionStatementModel({
1918
+ sql: this.$db.get('INSERT'),
1919
+ returnId: true
2456
1920
  });
2457
- };
2458
- Model.prototype._createMultipleModel = function () {
2459
- var _a;
2460
- return __awaiter(this, void 0, void 0, function () {
2461
- var _b, result, id, arrayId, arrayId_1, arrayId_1_1, id_1, sql, data, resultData;
2462
- var e_14, _c;
2463
- return __generator(this, function (_d) {
2464
- switch (_d.label) {
2465
- case 0: return [4 /*yield*/, this._actionStatementModel({
2466
- sql: this.$db.get('INSERT'),
2467
- returnId: true
2468
- })];
2469
- case 1:
2470
- _b = __read.apply(void 0, [_d.sent(), 2]), result = _b[0], id = _b[1];
2471
- if (!result) return [3 /*break*/, 3];
2472
- arrayId = __spreadArray([], __read(Array(result)), false).map(function (_, i) { return i + id; });
2473
- try {
2474
- for (arrayId_1 = __values(arrayId), arrayId_1_1 = arrayId_1.next(); !arrayId_1_1.done; arrayId_1_1 = arrayId_1.next()) {
2475
- id_1 = arrayId_1_1.value;
2476
- if (this.$db.get('TRANSACTION')) {
2477
- (_a = this.$db.get('TRANSACTION')) === null || _a === void 0 ? void 0 : _a.query.push({
2478
- table: this.$db.get('TABLE_NAME'),
2479
- id: id_1
2480
- });
2481
- }
2482
- }
2483
- }
2484
- catch (e_14_1) { e_14 = { error: e_14_1 }; }
2485
- finally {
2486
- try {
2487
- if (arrayId_1_1 && !arrayId_1_1.done && (_c = arrayId_1.return)) _c.call(arrayId_1);
2488
- }
2489
- finally { if (e_14) throw e_14.error; }
2490
- }
2491
- sql = [
2492
- "".concat(this.$db.get('SELECT')),
2493
- "".concat(this.$db.get('FROM')),
2494
- "".concat(this.$db.get('TABLE_NAME')),
2495
- "".concat(this.$constants('WHERE'), " id"),
2496
- "".concat(this.$constants('IN'), " (").concat(arrayId, ")")
2497
- ].join(' ');
2498
- return [4 /*yield*/, this._queryStatementModel(sql)];
2499
- case 2:
2500
- data = _d.sent();
2501
- resultData = data || null;
2502
- this.$db.set('RESULT', resultData);
2503
- return [2 /*return*/, resultData];
2504
- case 3: return [2 /*return*/, null];
1921
+ if (result) {
1922
+ const arrayId = [...Array(result)].map((_, i) => i + id);
1923
+ const sql = [
1924
+ `${this.$db.get('SELECT')}`,
1925
+ `${this.$db.get('FROM')}`,
1926
+ `${this.$db.get('TABLE_NAME')}`,
1927
+ `${this.$constants('WHERE')} id`,
1928
+ `${this.$constants('IN')} (${arrayId})`
1929
+ ].join(' ');
1930
+ const data = await this._queryStatementModel(sql);
1931
+ const resultData = data || null;
1932
+ this.$db.set('RESULT', resultData);
1933
+ return resultData;
1934
+ }
1935
+ return null;
1936
+ }
1937
+ async _updateOrInsertModel() {
1938
+ this._assertError(!this.$db.get('WHERE'), "can't update or insert [updateOrInsert] without where condition");
1939
+ let sql = '';
1940
+ let check = false;
1941
+ sql = [
1942
+ `${this.$constants('SELECT')}`,
1943
+ `${this.$constants('EXISTS')}(${this.$constants('SELECT')}`,
1944
+ `*`,
1945
+ `${this.$db.get('FROM')}`,
1946
+ `${this.$db.get('TABLE_NAME')}`,
1947
+ `${this.$db.get('WHERE')}`,
1948
+ `${this.$constants('LIMIT')} 1)`,
1949
+ `${this.$constants('AS')} 'exists'`
1950
+ ].join(' ');
1951
+ const [{ exists: result }] = await this._queryStatementModel(sql);
1952
+ check = !!Number.parseInt(result);
1953
+ switch (check) {
1954
+ case false: {
1955
+ const [result, id] = await this._actionStatementModel({
1956
+ sql: this.$db.get('INSERT'),
1957
+ returnId: true
1958
+ });
1959
+ if (result) {
1960
+ const sql = [
1961
+ `${this.$db.get('SELECT')}`,
1962
+ `${this.$db.get('FROM')}`,
1963
+ `${this.$db.get('TABLE_NAME')}`,
1964
+ `${this.$constants('WHERE')} id = ${id}`
1965
+ ].join(' ');
1966
+ const data = await this._queryStatementModel(sql);
1967
+ const resultData = { ...data?.shift(), action_status: 'insert' } || null;
1968
+ this.$db.set('RESULT', resultData);
1969
+ return resultData;
2505
1970
  }
2506
- });
2507
- });
2508
- };
2509
- Model.prototype._updateOrInsertModel = function () {
2510
- var _a;
2511
- return __awaiter(this, void 0, void 0, function () {
2512
- var sql, check, _b, result, _c, _d, result_5, id, sql_2, data, resultData, result_6, data, data_2, data_2_1, val;
2513
- var e_15, _e;
2514
- return __generator(this, function (_f) {
2515
- switch (_f.label) {
2516
- case 0:
2517
- this._assertError(!this.$db.get('WHERE'), "can't update or insert [updateOrInsert] without where condition");
2518
- sql = '';
2519
- check = false;
2520
- sql = [
2521
- "".concat(this.$constants('SELECT')),
2522
- "".concat(this.$constants('EXISTS'), "(").concat(this.$constants('SELECT')),
2523
- "*",
2524
- "".concat(this.$db.get('FROM')),
2525
- "".concat(this.$db.get('TABLE_NAME')),
2526
- "".concat(this.$db.get('WHERE')),
2527
- "".concat(this.$constants('LIMIT'), " 1)"),
2528
- "".concat(this.$constants('AS'), " 'exists'")
2529
- ].join(' ');
2530
- return [4 /*yield*/, this._queryStatementModel(sql)];
2531
- case 1:
2532
- _b = __read.apply(void 0, [_f.sent(), 1]), result = _b[0].exists;
2533
- check = !!Number.parseInt(result);
2534
- _c = check;
2535
- switch (_c) {
2536
- case false: return [3 /*break*/, 2];
2537
- case true: return [3 /*break*/, 6];
2538
- }
2539
- return [3 /*break*/, 10];
2540
- case 2: return [4 /*yield*/, this._actionStatementModel({
2541
- sql: this.$db.get('INSERT'),
2542
- returnId: true
2543
- })];
2544
- case 3:
2545
- _d = __read.apply(void 0, [_f.sent(), 2]), result_5 = _d[0], id = _d[1];
2546
- if (this.$db.get('TRANSACTION')) {
2547
- (_a = this.$db.get('TRANSACTION')) === null || _a === void 0 ? void 0 : _a.query.push({
2548
- table: this.$db.get('TABLE_NAME'),
2549
- id: id
2550
- });
2551
- }
2552
- if (!result_5) return [3 /*break*/, 5];
2553
- sql_2 = [
2554
- "".concat(this.$db.get('SELECT')),
2555
- "".concat(this.$db.get('FROM')),
2556
- "".concat(this.$db.get('TABLE_NAME')),
2557
- "".concat(this.$constants('WHERE'), " id = ").concat(id)
2558
- ].join(' ');
2559
- return [4 /*yield*/, this._queryStatementModel(sql_2)];
2560
- case 4:
2561
- data = _f.sent();
2562
- resultData = __assign(__assign({}, data === null || data === void 0 ? void 0 : data.shift()), { action_status: 'insert' }) || null;
2563
- this.$db.set('RESULT', resultData);
2564
- return [2 /*return*/, resultData];
2565
- case 5: return [2 /*return*/, null];
2566
- case 6: return [4 /*yield*/, this._actionStatementModel({
2567
- sql: [
2568
- "".concat(this.$db.get('UPDATE')),
2569
- "".concat(this.$db.get('WHERE'))
2570
- ].join(' ')
2571
- })];
2572
- case 7:
2573
- result_6 = _f.sent();
2574
- if (!result_6) return [3 /*break*/, 9];
2575
- return [4 /*yield*/, this._queryStatementModel([
2576
- "".concat(this.$db.get('SELECT')),
2577
- "".concat(this.$db.get('FROM')),
2578
- "".concat(this.$db.get('TABLE_NAME')),
2579
- "".concat(this.$db.get('WHERE'))
2580
- ].join(' '))];
2581
- case 8:
2582
- data = _f.sent();
2583
- if ((data === null || data === void 0 ? void 0 : data.length) > 1) {
2584
- try {
2585
- for (data_2 = __values(data), data_2_1 = data_2.next(); !data_2_1.done; data_2_1 = data_2.next()) {
2586
- val = data_2_1.value;
2587
- val.action_status = 'update';
2588
- }
2589
- }
2590
- catch (e_15_1) { e_15 = { error: e_15_1 }; }
2591
- finally {
2592
- try {
2593
- if (data_2_1 && !data_2_1.done && (_e = data_2.return)) _e.call(data_2);
2594
- }
2595
- finally { if (e_15) throw e_15.error; }
2596
- }
2597
- return [2 /*return*/, data || []];
2598
- }
2599
- return [2 /*return*/, __assign(__assign({}, data === null || data === void 0 ? void 0 : data.shift()), { action_status: 'update' }) || null];
2600
- case 9: return [2 /*return*/, null];
2601
- case 10:
2602
- {
2603
- return [2 /*return*/, null];
1971
+ return null;
1972
+ }
1973
+ case true: {
1974
+ const result = await this._actionStatementModel({
1975
+ sql: [
1976
+ `${this.$db.get('UPDATE')}`,
1977
+ `${this.$db.get('WHERE')}`
1978
+ ].join(' ')
1979
+ });
1980
+ if (result) {
1981
+ const data = await this._queryStatementModel([
1982
+ `${this.$db.get('SELECT')}`,
1983
+ `${this.$db.get('FROM')}`,
1984
+ `${this.$db.get('TABLE_NAME')}`,
1985
+ `${this.$db.get('WHERE')}`
1986
+ ].join(' '));
1987
+ if (data?.length > 1) {
1988
+ for (const val of data) {
1989
+ val.action_status = 'update';
2604
1990
  }
2605
- _f.label = 11;
2606
- case 11: return [2 /*return*/];
2607
- }
2608
- });
2609
- });
2610
- };
2611
- Model.prototype._updateModel = function (ignoreWhere) {
2612
- if (ignoreWhere === void 0) { ignoreWhere = false; }
2613
- return __awaiter(this, void 0, void 0, function () {
2614
- var _a, result, data, res;
2615
- return __generator(this, function (_b) {
2616
- switch (_b.label) {
2617
- case 0:
2618
- this._assertError(!this.$db.get('WHERE') && !ignoreWhere, "can't update [update] without where condition");
2619
- return [4 /*yield*/, this._actionStatementModel({ sql: [
2620
- "".concat(this.$db.get('UPDATE')),
2621
- "".concat(this.$db.get('WHERE'))
2622
- ].join(' '), returnId: true })];
2623
- case 1:
2624
- _a = __read.apply(void 0, [_b.sent(), 1]), result = _a[0];
2625
- if (!result)
2626
- return [2 /*return*/, null];
2627
- return [4 /*yield*/, this._queryStatementModel([
2628
- "".concat(this.$db.get('SELECT')),
2629
- "".concat(this.$db.get('FROM')),
2630
- "".concat(this.$db.get('TABLE_NAME')),
2631
- "".concat(this.$db.get('WHERE'))
2632
- ].join(' '))];
2633
- case 2:
2634
- data = _b.sent();
2635
- if ((data === null || data === void 0 ? void 0 : data.length) > 1)
2636
- return [2 /*return*/, data || []];
2637
- res = (data === null || data === void 0 ? void 0 : data.shift()) || null;
2638
- this.$db.set('RESULT', res);
2639
- return [2 /*return*/, res];
1991
+ return data || [];
1992
+ }
1993
+ return { ...data?.shift(), action_status: 'update' } || null;
2640
1994
  }
2641
- });
2642
- });
2643
- };
2644
- Model.prototype._assertError = function (condition, message) {
2645
- if (condition === void 0) { condition = true; }
2646
- if (message === void 0) { message = 'error'; }
1995
+ return null;
1996
+ }
1997
+ default: {
1998
+ return null;
1999
+ }
2000
+ }
2001
+ }
2002
+ async _updateModel(ignoreWhere = false) {
2003
+ this._assertError(!this.$db.get('WHERE') && !ignoreWhere, "can't update [update] without where condition");
2004
+ const [result] = await this._actionStatementModel({ sql: [
2005
+ `${this.$db.get('UPDATE')}`,
2006
+ `${this.$db.get('WHERE')}`
2007
+ ].join(' '), returnId: true });
2008
+ if (!result)
2009
+ return null;
2010
+ const data = await this._queryStatementModel([
2011
+ `${this.$db.get('SELECT')}`,
2012
+ `${this.$db.get('FROM')}`,
2013
+ `${this.$db.get('TABLE_NAME')}`,
2014
+ `${this.$db.get('WHERE')}`
2015
+ ].join(' '));
2016
+ if (data?.length > 1)
2017
+ return data || [];
2018
+ const res = data?.shift() || null;
2019
+ this.$db.set('RESULT', res);
2020
+ return res;
2021
+ }
2022
+ _assertError(condition = true, message = 'error') {
2647
2023
  if (typeof condition === 'string') {
2648
2024
  throw new Error(condition);
2649
2025
  }
2650
2026
  if (condition)
2651
2027
  throw new Error(message);
2652
2028
  return;
2653
- };
2654
- Model.prototype._functionRelationName = function () {
2655
- var functionName = __spreadArray([], __read(this.$logger.get()), false)[this.$logger.get().length - 2];
2656
- return functionName.replace(/([A-Z])/g, function (str) { return "_".concat(str.toLowerCase()); });
2657
- };
2658
- Model.prototype._initialModel = function () {
2029
+ }
2030
+ _functionRelationName() {
2031
+ const functionName = [...this.$logger.get()][this.$logger.get().length - 2];
2032
+ return functionName.replace(/([A-Z])/g, (str) => `_${str.toLowerCase()}`);
2033
+ }
2034
+ _handleRelationsQuery(nameRelation, relation) {
2035
+ this.$db.set('RELATION', [...this.$db.get('RELATION'), relation]);
2036
+ this.with(nameRelation);
2037
+ const r = this.$db.get('WITH').find((data) => data.name === nameRelation);
2038
+ this._assertError(r == null, `relation ${nameRelation} not be register !`);
2039
+ this._assertError(!Object.values(this.$constants('RELATIONSHIP')).includes(r.relation), `unknown relationship in [${this.$constants('RELATIONSHIP')}] !`);
2040
+ return r;
2041
+ }
2042
+ _initialModel() {
2659
2043
  this.$db = this._setupModel();
2660
2044
  this._tableName();
2661
2045
  return this;
2662
- };
2663
- Model.prototype._setupModel = function () {
2664
- var _this = this;
2665
- var db = new Map(Object.entries(__assign({}, this.$constants('MODEL'))));
2046
+ }
2047
+ _setupModel() {
2048
+ let db = new Map(Object.entries({ ...this.$constants('MODEL') }));
2666
2049
  return {
2667
- get: function (key) {
2050
+ get: (key) => {
2668
2051
  if (key == null)
2669
2052
  return db;
2670
- _this._assertError(!db.has(key), "can't get this [".concat(key, "]"));
2053
+ this._assertError(!db.has(key), `can't get this [${key}]`);
2671
2054
  return db.get(key);
2672
2055
  },
2673
- set: function (key, value) {
2674
- _this._assertError(!db.has(key), "can't set this [".concat(key, "]"));
2056
+ set: (key, value) => {
2057
+ this._assertError(!db.has(key), `can't set this [${key}]`);
2675
2058
  db.set(key, value);
2676
2059
  return;
2060
+ },
2061
+ clone: (data) => {
2062
+ db = new Map(Object.entries({ ...data }));
2063
+ return;
2677
2064
  }
2678
2065
  };
2679
- };
2680
- return Model;
2681
- }(AbstractModel_1.AbstractModel));
2066
+ }
2067
+ }
2682
2068
  exports.Model = Model;
2683
2069
  exports.default = Model;