tspace-mysql 1.3.5 → 1.3.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -35,7 +35,7 @@ npm install tspace-mysql --save
35
35
  - [Make Migration](#make-migration)
36
36
  - [Migrate](#migrate)
37
37
  - [Query](#query)
38
- - [Menerate Models](#generate-models)
38
+ - [Generate Models](#generate-models)
39
39
  - [Blueprint](#blueprint)
40
40
 
41
41
  ## Configuration
@@ -960,9 +960,9 @@ tspace-mysql make:migration users --dir=app/Models/Migrations
960
960
  * @arg --dir=directory => find migrate in directory. default find in root folder
961
961
  * @arg --type=js // extension js default ts
962
962
  */
963
- tspace-mysql migrate <folder> --type=... --dir=....
963
+ tspace-mysql migrate <folder> --type=<type file js or ts> --dir=<directory for migrate>
964
964
 
965
- tspace-mysql migrate --dir=App/Models/Migrations --type=js
965
+ tspace-mysql migrate --dir=app/Models/Migrations --type=js
966
966
 
967
967
  /**
968
968
  *
@@ -989,7 +989,7 @@ tspace-mysql query "SELECT * FROM users"
989
989
  # Generate Models
990
990
  Command will be generate models from table in database
991
991
  ```js
992
- tspace-mysql generate:models
992
+ tspace-mysql generate:models --dir=<folder for creating>
993
993
 
994
994
  ```
995
995
 
@@ -999,14 +999,14 @@ Schema table created by command make:migration, you may use the:
999
999
  import { Schema , Blueprint , DB } from 'tspace-mysql'
1000
1000
  (async () => {
1001
1001
  await new Schema().table('users',{
1002
- id : new Blueprint().int().notNull().primary().autoIncrement(),
1003
- uuid : new Blueprint().varchar(120).null()
1004
- name : new Blueprint().varchar(120).default('name'),
1005
- email : new Blueprint().varchar(255).unique().notNull(),
1002
+ id : new Blueprint().int().notNull().primary().autoIncrement(),
1003
+ uuid : new Blueprint().varchar(120).null()
1004
+ name : new Blueprint().varchar(120).default('name'),
1005
+ email : new Blueprint().varchar(255).unique().notNull(),
1006
1006
  email_verify : new Blueprint().tinyInt(),
1007
- password : new Blueprint().varchar(255),
1008
- created_at : new Blueprint().null().timestamp(),
1009
- updated_at : new Blueprint().null().timestamp()
1007
+ password : new Blueprint().varchar(255),
1008
+ created_at : new Blueprint().null().timestamp(),
1009
+ updated_at : new Blueprint().null().timestamp()
1010
1010
  })
1011
1011
  /**
1012
1012
  *
@@ -11,7 +11,7 @@ class ${model} extends Model {
11
11
  * @useMethod
12
12
  *
13
13
  * this.useDebug() // => runing a uuid (universally unique identifier) when insert new data
14
- * this.usePrimaryKey('id') // => runing a uuid (universally unique identifier) when insert new data
14
+ * this.usePrimaryKey('id')
15
15
  * this.useTimestamp({ createdAt : 'created_at' , updatedAt : 'updated_at' }) // runing a timestamp when insert or update
16
16
  * this.useSoftDelete()
17
17
  * this.useTable('users')
@@ -431,14 +431,14 @@ declare class Builder extends AbstractBuilder {
431
431
  * @param {array} data create multiple data
432
432
  * @return {this} this this
433
433
  */
434
- createMultiple(data: Array<any>): this;
434
+ createMultiple(data: Array<Record<string, any>>): this;
435
435
  /**
436
436
  *
437
437
  * insert muliple data into the database
438
438
  * @param {array} data create multiple data
439
439
  * @return {this} this this
440
440
  */
441
- insertMultiple(data: Array<any>): this;
441
+ insertMultiple(data: Array<Record<string, any>>): this;
442
442
  /**
443
443
  *
444
444
  * @return {string} return sql query
@@ -1724,7 +1724,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
1724
1724
  this.$state.set('SELECT', [
1725
1725
  `${this.$constants('SELECT')}`,
1726
1726
  `${this.$constants('COUNT')}(${column})`,
1727
- `${this.$constants('AS')} total`
1727
+ `${this.$constants('AS')} \`total\``
1728
1728
  ].join(' '));
1729
1729
  const sql = this._buildQuery();
1730
1730
  const result = yield this.queryStatement(sql);
@@ -1747,7 +1747,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
1747
1747
  `${this.$state.get('FROM')}`,
1748
1748
  `${this.$state.get('TABLE_NAME')}`,
1749
1749
  `${this.$state.get('WHERE')}`,
1750
- `${this.$constants('LIMIT')} 1) ${this.$constants('AS')} 'exists'`
1750
+ `${this.$constants('LIMIT')} 1) ${this.$constants('AS')} \`exists\``
1751
1751
  ].join(' '));
1752
1752
  return Boolean(this.resultHandler(!!((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.exists) || false));
1753
1753
  });
@@ -1764,7 +1764,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
1764
1764
  this.$state.set('SELECT', [
1765
1765
  `${this.$constants('SELECT')}`,
1766
1766
  `${this.$constants('AVG')}(${column})`,
1767
- `${this.$constants('AS')} avg`
1767
+ `${this.$constants('AS')} \`avg\``
1768
1768
  ].join(' '));
1769
1769
  const sql = this._buildQuery();
1770
1770
  const result = yield this.queryStatement(sql);
@@ -1780,7 +1780,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
1780
1780
  sum(column = 'id') {
1781
1781
  var _a;
1782
1782
  return __awaiter(this, void 0, void 0, function* () {
1783
- this.$state.set('SELECT', `${this.$constants('SELECT')} ${this.$constants('SUM')}(${column}) ${this.$constants('AS')} sum`);
1783
+ this.$state.set('SELECT', `${this.$constants('SELECT')} ${this.$constants('SUM')}(${column}) ${this.$constants('AS')} \`sum\``);
1784
1784
  const sql = this._buildQuery();
1785
1785
  const result = yield this.queryStatement(sql);
1786
1786
  return Number(this.resultHandler(((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.sum) || 0));
@@ -1795,7 +1795,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
1795
1795
  max(column = 'id') {
1796
1796
  var _a;
1797
1797
  return __awaiter(this, void 0, void 0, function* () {
1798
- this.$state.set('SELECT', `${this.$constants('SELECT')} ${this.$constants('MAX')}(${column}) ${this.$constants('AS')} max`);
1798
+ this.$state.set('SELECT', `${this.$constants('SELECT')} ${this.$constants('MAX')}(${column}) ${this.$constants('AS')} \`max\``);
1799
1799
  const sql = this._buildQuery();
1800
1800
  const result = yield this.queryStatement(sql);
1801
1801
  return Number(this.resultHandler(((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.max) || 0));
@@ -1810,7 +1810,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
1810
1810
  min(column = 'id') {
1811
1811
  var _a;
1812
1812
  return __awaiter(this, void 0, void 0, function* () {
1813
- this.$state.set('SELECT', `${this.$constants('SELECT')} ${this.$constants('MIN')}(${column}) ${this.$constants('AS')} min`);
1813
+ this.$state.set('SELECT', `${this.$constants('SELECT')} ${this.$constants('MIN')}(${column}) ${this.$constants('AS')} \`min\``);
1814
1814
  const sql = this._buildQuery();
1815
1815
  const result = yield this.queryStatement(sql);
1816
1816
  return Number(this.resultHandler(((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.min) || 0));
@@ -1986,8 +1986,8 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
1986
1986
  `${this.$constants('FROM')}`,
1987
1987
  `\`${table.replace(/\`/g, '')}\``
1988
1988
  ].join(' ');
1989
- const raw = yield this.queryStatement(sql);
1990
- const schemas = raw.map((r) => {
1989
+ const raws = yield this.queryStatement(sql);
1990
+ return raws.map((r) => {
1991
1991
  const schema = [];
1992
1992
  schema.push(`${r.Field}`);
1993
1993
  schema.push(`${r.Type}`);
@@ -2011,7 +2011,6 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
2011
2011
  }
2012
2012
  return schema.join(' ');
2013
2013
  });
2014
- return schemas;
2015
2014
  });
2016
2015
  }
2017
2016
  /**
@@ -268,7 +268,27 @@ declare class Model extends AbstractModel {
268
268
  limit?: boolean;
269
269
  offset?: boolean;
270
270
  }): Model;
271
+ /**
272
+ *
273
+ * execute the query using raw sql syntax
274
+ * @override method
275
+ * @param {string} sql
276
+ * @return {this} this
277
+ */
271
278
  protected queryStatement(sql: string): Promise<Array<any>>;
279
+ /**
280
+ *
281
+ * execute the query using raw sql syntax actions for insert update and delete
282
+ * @override method
283
+ * @param {Object} actions
284
+ * @property {Function} actions.sql
285
+ * @property {Function} actions.returnId
286
+ * @return {this} this
287
+ */
288
+ protected actionStatement({ sql, returnId }: {
289
+ sql: string;
290
+ returnId?: boolean;
291
+ }): Promise<any>;
272
292
  /**
273
293
  * Assign table name
274
294
  * @param {string} table table name
@@ -891,11 +911,7 @@ declare class Model extends AbstractModel {
891
911
  * @param {array<object>} data create multiple data
892
912
  * @return {this} this this
893
913
  */
894
- createMultiple(data: Array<{
895
- [key: string]: any;
896
- }> & {
897
- length?: never;
898
- }): this;
914
+ createMultiple(data: Array<Record<string, any>>): this;
899
915
  /**
900
916
  *
901
917
  * insert muliple data into the database
@@ -903,11 +919,7 @@ declare class Model extends AbstractModel {
903
919
  * @param {array<object>} data create multiple data
904
920
  * @return {this} this this
905
921
  */
906
- insertMultiple(data: Array<{
907
- [key: string]: any;
908
- }> & {
909
- length?: never;
910
- }): this;
922
+ insertMultiple(data: Array<Record<string, any>>): this;
911
923
  /**
912
924
  *
913
925
  * @param {object} data create not exists data
@@ -984,6 +996,7 @@ declare class Model extends AbstractModel {
984
996
  private _handleRelations;
985
997
  private _handleRelationsQuery;
986
998
  private _validateMethod;
999
+ private _tryToCreateTable;
987
1000
  private _initialModel;
988
1001
  }
989
1002
  export { Model };
@@ -399,7 +399,6 @@ class Model extends AbstractModel_1.AbstractModel {
399
399
  const copy = Object.fromEntries(instance.$state.get());
400
400
  const newInstance = new Model();
401
401
  newInstance.$state.clone(copy);
402
- newInstance.$state.set('SAVE', '');
403
402
  if ((options === null || options === void 0 ? void 0 : options.insert) == null)
404
403
  newInstance.$state.set('INSERT', '');
405
404
  if ((options === null || options === void 0 ? void 0 : options.update) == null)
@@ -412,8 +411,16 @@ class Model extends AbstractModel_1.AbstractModel {
412
411
  newInstance.$state.set('LIMIT', '');
413
412
  if ((options === null || options === void 0 ? void 0 : options.offset) == null)
414
413
  newInstance.$state.set('OFFSET', '');
414
+ newInstance.$state.set('SAVE', '');
415
415
  return newInstance;
416
416
  }
417
+ /**
418
+ *
419
+ * execute the query using raw sql syntax
420
+ * @override method
421
+ * @param {string} sql
422
+ * @return {this} this
423
+ */
417
424
  queryStatement(sql) {
418
425
  return __awaiter(this, void 0, void 0, function* () {
419
426
  try {
@@ -424,24 +431,42 @@ class Model extends AbstractModel_1.AbstractModel {
424
431
  return result;
425
432
  }
426
433
  catch (e) {
427
- const createTable = this.$state.get('CREATE_TABLE');
428
- const tableName = this.$state.get('TABLE_NAME');
429
- if (createTable == null)
430
- throw e;
431
- if (this.$state.get('QUERIES') > 3)
432
- throw e;
433
- try {
434
- yield new Schema_1.Schema()
435
- .debug(this.$state.get('DEBUG'))
436
- .createTable(tableName, createTable);
437
- }
438
- catch (e) {
439
- throw e;
440
- }
434
+ yield this._tryToCreateTable(e);
441
435
  return yield this.queryStatement(sql);
442
436
  }
443
437
  });
444
438
  }
439
+ /**
440
+ *
441
+ * execute the query using raw sql syntax actions for insert update and delete
442
+ * @override method
443
+ * @param {Object} actions
444
+ * @property {Function} actions.sql
445
+ * @property {Function} actions.returnId
446
+ * @return {this} this
447
+ */
448
+ actionStatement({ sql, returnId = false }) {
449
+ return __awaiter(this, void 0, void 0, function* () {
450
+ try {
451
+ if (this.$state.get('DEBUG'))
452
+ this.$utils.consoleDebug(sql);
453
+ this.$state.set('QUERIES', this.$state.get('QUERIES') + 1);
454
+ if (returnId) {
455
+ const result = yield this.$pool.query(sql);
456
+ return [result.affectedRows, result.insertId];
457
+ }
458
+ const { affectedRows: result } = yield this.$pool.query(sql);
459
+ return result;
460
+ }
461
+ catch (e) {
462
+ yield this._tryToCreateTable(e);
463
+ return yield this.actionStatement({
464
+ sql,
465
+ returnId
466
+ });
467
+ }
468
+ });
469
+ }
445
470
  /**
446
471
  * Assign table name
447
472
  * @param {string} table table name
@@ -1073,7 +1098,10 @@ class Model extends AbstractModel_1.AbstractModel {
1073
1098
  * @return {string}
1074
1099
  */
1075
1100
  toString() {
1076
- return this._buildQueryModel();
1101
+ const sql = this._buildQueryModel();
1102
+ if (this.$state.get('DEBUG'))
1103
+ this.$utils.consoleDebug(sql);
1104
+ return this.resultHandler(sql);
1077
1105
  }
1078
1106
  /**
1079
1107
  *
@@ -1081,7 +1109,10 @@ class Model extends AbstractModel_1.AbstractModel {
1081
1109
  * @return {string}
1082
1110
  */
1083
1111
  toSQL() {
1084
- return this._buildQueryModel();
1112
+ const sql = this._buildQueryModel();
1113
+ if (this.$state.get('DEBUG'))
1114
+ this.$utils.consoleDebug(sql);
1115
+ return this.resultHandler(sql);
1085
1116
  }
1086
1117
  /**
1087
1118
  *
@@ -1094,7 +1125,7 @@ class Model extends AbstractModel_1.AbstractModel {
1094
1125
  const result = yield this.queryStatement(sql);
1095
1126
  if (this.$state.get('HIDDEN').length)
1096
1127
  this._hiddenColumnModel(result);
1097
- return JSON.stringify(result);
1128
+ return this.resultHandler(JSON.stringify(result));
1098
1129
  });
1099
1130
  }
1100
1131
  /**
@@ -1109,7 +1140,7 @@ class Model extends AbstractModel_1.AbstractModel {
1109
1140
  const sql = this._buildQueryModel();
1110
1141
  const result = yield this.queryStatement(sql);
1111
1142
  const toArray = result.map((data) => data[column]);
1112
- return toArray;
1143
+ return this.resultHandler(toArray);
1113
1144
  });
1114
1145
  }
1115
1146
  /**
@@ -1121,7 +1152,7 @@ class Model extends AbstractModel_1.AbstractModel {
1121
1152
  avg(column = 'id') {
1122
1153
  var _a;
1123
1154
  return __awaiter(this, void 0, void 0, function* () {
1124
- this.selectRaw(`${this.$constants('AVG')}(${column}) ${this.$constants('AS')} avg`);
1155
+ this.selectRaw(`${this.$constants('AVG')}(${column}) ${this.$constants('AS')} \`avg\``);
1125
1156
  const sql = this._buildQueryModel();
1126
1157
  const result = yield this.queryStatement(sql);
1127
1158
  return Number(this.resultHandler(((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.avg) || 0));
@@ -1136,7 +1167,7 @@ class Model extends AbstractModel_1.AbstractModel {
1136
1167
  sum(column = 'id') {
1137
1168
  var _a;
1138
1169
  return __awaiter(this, void 0, void 0, function* () {
1139
- this.selectRaw(`${this.$constants('SUM')}(${column}) ${this.$constants('AS')} sum`);
1170
+ this.selectRaw(`${this.$constants('SUM')}(${column}) ${this.$constants('AS')} \`sum\``);
1140
1171
  const sql = this._buildQueryModel();
1141
1172
  const result = yield this.queryStatement(sql);
1142
1173
  return Number(this.resultHandler(((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.sum) || 0));
@@ -1151,7 +1182,7 @@ class Model extends AbstractModel_1.AbstractModel {
1151
1182
  max(column = 'id') {
1152
1183
  var _a;
1153
1184
  return __awaiter(this, void 0, void 0, function* () {
1154
- this.selectRaw(`${this.$constants('MAX')}(${column}) ${this.$constants('AS')} max`);
1185
+ this.selectRaw(`${this.$constants('MAX')}(${column}) ${this.$constants('AS')} \`max\``);
1155
1186
  const sql = this._buildQueryModel();
1156
1187
  const result = yield this.queryStatement(sql);
1157
1188
  return Number(this.resultHandler(((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.max) || 0));
@@ -1166,7 +1197,7 @@ class Model extends AbstractModel_1.AbstractModel {
1166
1197
  min(column = 'id') {
1167
1198
  var _a;
1168
1199
  return __awaiter(this, void 0, void 0, function* () {
1169
- this.selectRaw(`${this.$constants('MIN')}(${column}) ${this.$constants('AS')} min`);
1200
+ this.selectRaw(`${this.$constants('MIN')}(${column}) ${this.$constants('AS')} \`min\``);
1170
1201
  const sql = this._buildQueryModel();
1171
1202
  const result = yield this.queryStatement(sql);
1172
1203
  return Number(this.resultHandler(((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.min) || 0));
@@ -1181,7 +1212,7 @@ class Model extends AbstractModel_1.AbstractModel {
1181
1212
  count(column = 'id') {
1182
1213
  var _a;
1183
1214
  return __awaiter(this, void 0, void 0, function* () {
1184
- this.selectRaw(`${this.$constants('COUNT')}(${column}) ${this.$constants('AS')} total`);
1215
+ this.selectRaw(`${this.$constants('COUNT')}(${column}) ${this.$constants('AS')} \`total\``);
1185
1216
  const sql = this._buildQueryModel();
1186
1217
  const result = yield this.queryStatement(sql);
1187
1218
  return Number(this.resultHandler(((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.total) || 0));
@@ -1201,7 +1232,7 @@ class Model extends AbstractModel_1.AbstractModel {
1201
1232
  `${this.$constants('SELECT')}`,
1202
1233
  `${this.$constants('EXISTS')}`,
1203
1234
  `(${sql})`,
1204
- `${this.$constants('AS')} 'exists'`
1235
+ `${this.$constants('AS')} \`exists\``
1205
1236
  ].join(' '));
1206
1237
  return Boolean(this.resultHandler(!!((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.exists) || false));
1207
1238
  });
@@ -1702,13 +1733,13 @@ class Model extends AbstractModel_1.AbstractModel {
1702
1733
  }
1703
1734
  }
1704
1735
  switch (String(this.$state.get('SAVE'))) {
1705
- case 'INSERT_MULTIPLE': return yield this._createMultipleModel();
1706
1736
  case 'INSERT': return yield this._insertModel();
1707
1737
  case 'UPDATE': return yield this._updateModel();
1738
+ case 'INSERT_MULTIPLE': return yield this._createMultipleModel();
1708
1739
  case 'INSERT_NOT_EXISTS': return yield this._insertNotExistsModel();
1709
1740
  case 'UPDATE_OR_INSERT': return yield this._updateOrInsertModel();
1710
1741
  case 'INSERT_OR_SELECT': return yield this._insertOrSelectModel();
1711
- default: throw new Error(`unknown this [${this.$state.get('SAVE')}]`);
1742
+ default: throw new Error(`Unknown this [${this.$state.get('SAVE')}]`);
1712
1743
  }
1713
1744
  });
1714
1745
  }
@@ -2581,10 +2612,11 @@ class Model extends AbstractModel_1.AbstractModel {
2581
2612
  return this.resultHandler(null);
2582
2613
  if (!result)
2583
2614
  return this.resultHandler(null);
2584
- return yield new Model().copyModel(this)
2615
+ const resultData = yield new Model().copyModel(this)
2585
2616
  .where('id', id)
2586
2617
  .bind(this.$pool.get())
2587
2618
  .first();
2619
+ return this.resultHandler(resultData);
2588
2620
  });
2589
2621
  }
2590
2622
  _createMultipleModel() {
@@ -2765,6 +2797,29 @@ class Model extends AbstractModel_1.AbstractModel {
2765
2797
  }
2766
2798
  }
2767
2799
  }
2800
+ _tryToCreateTable(e) {
2801
+ var _a;
2802
+ return __awaiter(this, void 0, void 0, function* () {
2803
+ const createTable = this.$state.get('CREATE_TABLE');
2804
+ if (createTable == null)
2805
+ throw e;
2806
+ const errorMessage = (_a = e === null || e === void 0 ? void 0 : e.message) !== null && _a !== void 0 ? _a : '';
2807
+ const errorWhenTableIsNotExists = "doesn't exist";
2808
+ if (!errorMessage.toLocaleLowerCase().includes(errorWhenTableIsNotExists))
2809
+ throw e;
2810
+ if (this.$state.get('QUERIES') > 3)
2811
+ throw e;
2812
+ try {
2813
+ const tableName = this.$state.get('TABLE_NAME');
2814
+ yield new Schema_1.Schema()
2815
+ .debug(this.$state.get('DEBUG'))
2816
+ .createTable(tableName, createTable);
2817
+ }
2818
+ catch (e) {
2819
+ throw e;
2820
+ }
2821
+ });
2822
+ }
2768
2823
  _initialModel() {
2769
2824
  this.$state = new StateHandler_1.StateHandler(this.$constants('MODEL'));
2770
2825
  this._makeTableName();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tspace-mysql",
3
- "version": "1.3.5",
3
+ "version": "1.3.6",
4
4
  "description": "mysql query builder object relational mapping",
5
5
  "main": "dist/lib/index.js",
6
6
  "types": "dist/lib/index.d.ts",