tspace-mysql 1.3.5 → 1.3.7

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
@@ -412,7 +412,7 @@ class User extends Model {
412
412
  * this.useRegistry() // => build-in functions registry
413
413
  * this.useLoadRelationsInRegistry() // => auto generated results from relationship to results
414
414
  * this.useBuiltInRelationFunctions() // => build-in functions relationships to results
415
- * this.useSchema({
415
+ * this.useValidationSchema({
416
416
  * id : Number,
417
417
  * username : String
418
418
  * created_at : Date,
@@ -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
  *
@@ -9,9 +9,9 @@ class ${model} extends Model {
9
9
  *
10
10
  * Assign setting global in your model
11
11
  * @useMethod
12
- *
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
12
+ * this.useUUID() // => runing a uuid (universally unique identifier) when insert new data
13
+ * this.useDebug() // debug raw query
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')
@@ -0,0 +1,122 @@
1
+ import { Pagination } from '../Interface';
2
+ import { StateHandler } from '../StateHandler';
3
+ declare abstract class AbstractBuilder {
4
+ protected $setters: string[];
5
+ protected $utils: {
6
+ [key: string]: Function;
7
+ };
8
+ protected $constants: Function;
9
+ protected $state: StateHandler;
10
+ protected $pool: {
11
+ query: Function;
12
+ set: Function;
13
+ get: Function;
14
+ };
15
+ protected $logger: {
16
+ get: Function;
17
+ set: (value: string) => void;
18
+ reset: () => void;
19
+ check: (value: string) => boolean;
20
+ };
21
+ protected $attributes: {
22
+ [key: string]: any;
23
+ } | null;
24
+ abstract void(): this;
25
+ abstract debug(): this;
26
+ abstract dd(): this;
27
+ abstract select(...columns: string[]): this;
28
+ abstract distinct(...columns: string[]): this;
29
+ abstract whereNull(column: string): this;
30
+ abstract whereNotNull(column: string): this;
31
+ abstract where(column: string, operator: string, value: string): this;
32
+ abstract whereSensitive(column: string, operator: string, value: string): this;
33
+ abstract whereRaw(sql: string): this;
34
+ abstract whereId(id: number): this;
35
+ abstract whereUser(id: number): this;
36
+ abstract whereEmail(value: string): this;
37
+ abstract whereQuery(callback: Function): this;
38
+ abstract orWhere(column: string, operator: string, value: string): this;
39
+ abstract whereIn(column: string, arrayValues: Array<any>): this;
40
+ abstract orWhereIn(column: string, arrayValues: Array<any>): this;
41
+ abstract whereNotIn(column: string, arrayValues: Array<any>): this;
42
+ abstract whereSubQuery(column: string, subQuery: string): this;
43
+ abstract whereNotSubQuery(column: string, subQuery: string): this;
44
+ abstract orWhereSubQuery(column: string, subQuery: string): this;
45
+ abstract whereBetween(column: string, arrayValue: Array<any>): this;
46
+ abstract whereNotBetween(column: string, arrayValue: Array<any>): this;
47
+ abstract having(condition: string): this;
48
+ abstract havingRaw(condition: string): this;
49
+ abstract join(pk: string, fk: string): this;
50
+ abstract rightJoin(pk: string, fk: string): this;
51
+ abstract leftJoin(pk: string, fk: string): this;
52
+ abstract crossJoin(pk: string, fk: string): this;
53
+ abstract orderBy(column: string, order: string): this;
54
+ abstract orderByRaw(column: string, order: string): this;
55
+ abstract latest(...columns: Array<string>): this;
56
+ abstract latestRaw(...columns: Array<string>): this;
57
+ abstract oldest(...columns: Array<string>): this;
58
+ abstract oldestRaw(...columns: Array<string>): this;
59
+ abstract groupBy(...columns: string[]): this;
60
+ abstract groupByRaw(...columns: string[]): this;
61
+ abstract random(): this;
62
+ abstract inRandom(): this;
63
+ abstract limit(number: number): this;
64
+ abstract hidden(...columns: string[]): this;
65
+ abstract insert(objects: object): this;
66
+ abstract create(objects: object): this;
67
+ abstract update(objects: object): this;
68
+ abstract insertNotExists(objects: object): this;
69
+ abstract createNotExists(objects: object): this;
70
+ abstract insertOrUpdate(objects: object): this;
71
+ abstract createOrUpdate(objects: object): this;
72
+ abstract updateOrInsert(objects: object): this;
73
+ abstract updateOrCreate(objects: object): this;
74
+ abstract createMultiple(objects: object): this;
75
+ abstract insertMultiple(objects: object): this;
76
+ abstract except(...columns: string[]): this;
77
+ abstract only(...columns: string[]): this;
78
+ abstract drop(): Promise<any>;
79
+ abstract truncate(): Promise<any>;
80
+ abstract all(): Promise<Array<any>>;
81
+ abstract find(id: number): Promise<any>;
82
+ abstract pagination({ limit, page }: {
83
+ limit: number;
84
+ page: number;
85
+ }): Promise<Pagination>;
86
+ abstract paginate({ limit, page }: {
87
+ limit: number;
88
+ page: number;
89
+ }): Promise<Pagination>;
90
+ abstract first(): Promise<any>;
91
+ abstract firstOrError(message: string, options?: {
92
+ [key: string]: any;
93
+ }): Promise<any>;
94
+ abstract findOneOrError(message: string, options?: {
95
+ [key: string]: any;
96
+ }): Promise<any>;
97
+ abstract get(): Promise<any>;
98
+ abstract findOne(): Promise<any>;
99
+ abstract findMany(): Promise<any>;
100
+ abstract getGroupBy(column: string): Promise<any>;
101
+ abstract findManyGroupBy(column: string): Promise<any>;
102
+ abstract toArray(column: string): Promise<any>;
103
+ abstract toJSON(): Promise<any>;
104
+ abstract toSQL(): string;
105
+ abstract toString(): string;
106
+ abstract count(column: string): Promise<number>;
107
+ abstract sum(column: string): Promise<number>;
108
+ abstract avg(column: string): Promise<number>;
109
+ abstract max(column: string): Promise<number>;
110
+ abstract min(column: string): Promise<number>;
111
+ abstract rawQuery(sql: string): Promise<Array<any>>;
112
+ abstract delete(): Promise<boolean>;
113
+ abstract exists(): Promise<boolean>;
114
+ abstract save(): Promise<{
115
+ [key: string]: any;
116
+ } | Array<any> | null | undefined>;
117
+ abstract increment(column: string, value: number): Promise<any>;
118
+ abstract decrement(column: string, value: number): Promise<any>;
119
+ abstract faker(round: number): Promise<any>;
120
+ }
121
+ export { AbstractBuilder };
122
+ export default AbstractBuilder;
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AbstractBuilder = void 0;
4
+ const StateHandler_1 = require("../StateHandler");
5
+ class AbstractBuilder {
6
+ constructor() {
7
+ this.$setters = [
8
+ '$attributes',
9
+ '$logger',
10
+ '$utils',
11
+ '$constants',
12
+ '$pool',
13
+ '$state',
14
+ ];
15
+ this.$utils = {};
16
+ this.$constants = (name) => { };
17
+ this.$state = new StateHandler_1.StateHandler({});
18
+ this.$pool = {
19
+ query: (sql) => { },
20
+ set: (pool) => { },
21
+ get: () => { }
22
+ };
23
+ this.$logger = {
24
+ get: () => { },
25
+ set: (value) => { },
26
+ reset: () => { },
27
+ check: (value) => true || false
28
+ };
29
+ this.$attributes = null;
30
+ }
31
+ }
32
+ exports.AbstractBuilder = AbstractBuilder;
33
+ exports.default = AbstractBuilder;
@@ -0,0 +1,20 @@
1
+ import Builder from '../Builder';
2
+ import { Connection, ConnectionOptions } from '../Interface';
3
+ declare abstract class AbstractDB extends Builder {
4
+ abstract table(tableName: string): void;
5
+ abstract beginTransaction(): Promise<any>;
6
+ abstract makeObject(value: any): Record<string, any> | null;
7
+ abstract makeArray(value: any): Array<any>;
8
+ abstract generateUUID(): string;
9
+ abstract raw(sql: string): string;
10
+ abstract constants(constants?: string): string | {
11
+ [key: string]: any;
12
+ };
13
+ abstract caseUpdate(cases: {
14
+ when: string;
15
+ then: string;
16
+ }[], final?: string): string | [];
17
+ abstract getConnection(options: ConnectionOptions): Connection;
18
+ }
19
+ export { AbstractDB };
20
+ export default AbstractDB;
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.AbstractDB = void 0;
7
+ const Builder_1 = __importDefault(require("../Builder"));
8
+ class AbstractDB extends Builder_1.default {
9
+ }
10
+ exports.AbstractDB = AbstractDB;
11
+ exports.default = AbstractDB;
@@ -0,0 +1,45 @@
1
+ import { Relation, RelationQuery } from '../Interface';
2
+ import Builder from '../Builder';
3
+ declare abstract class AbstractModel extends Builder {
4
+ protected abstract useUUID(): this;
5
+ protected abstract usePrimaryKey(primaryKey: string): this;
6
+ protected abstract useRegistry(): this;
7
+ protected abstract useDebug(): this;
8
+ protected abstract useTable(table: string): this;
9
+ protected abstract useTablePlural(): this;
10
+ protected abstract useTableSingular(): this;
11
+ protected abstract useTimestamp(): this;
12
+ protected abstract useSoftDelete(): this;
13
+ protected abstract usePattern(pattern: string): this;
14
+ protected abstract useLoadRelationsInRegistry(): this;
15
+ protected abstract useBuiltInRelationFunctions(): this;
16
+ protected abstract define(): void;
17
+ protected abstract hasOne({ name, model, localKey, foreignKey, freezeTable, as }: Relation): this;
18
+ protected abstract hasMany({ name, model, localKey, foreignKey, freezeTable, as }: Relation): this;
19
+ protected abstract belongsTo({ name, model, localKey, foreignKey, freezeTable, as }: Relation): this;
20
+ protected abstract belongsToMany({ name, model, localKey, foreignKey, freezeTable, as }: Relation): this;
21
+ protected abstract buildMethodRelation(name: string, callback?: Function): this;
22
+ protected abstract hasOneBuilder({ name, model, localKey, foreignKey, freezeTable, as }: RelationQuery, callback: Function): this;
23
+ protected abstract hasManyBuilder({ name, model, localKey, foreignKey, freezeTable, as }: RelationQuery, callback: Function): this;
24
+ protected abstract belongsToBuilder({ name, model, localKey, foreignKey, freezeTable, as }: RelationQuery, callback: Function): this;
25
+ protected abstract belongsToManyBuilder({ name, model, localKey, foreignKey, freezeTable, as }: RelationQuery, callback: Function): this;
26
+ abstract ignoreSoftDelete(): this;
27
+ abstract disableSoftDelete(): this;
28
+ abstract registry(func: {
29
+ [key: string]: Function;
30
+ }): this;
31
+ abstract onlyTrashed(): Promise<any>;
32
+ abstract trashed(): Promise<any>;
33
+ abstract restore(): Promise<any>;
34
+ abstract with(...nameRelations: string[]): this;
35
+ abstract withQuery(nameRelations: string, callback: Function): this;
36
+ abstract withExists(...nameRelations: string[]): this;
37
+ abstract withAndTrashed(...nameRelations: string[]): this;
38
+ abstract has(...nameRelations: string[]): this;
39
+ abstract relations(...nameRelations: string[]): this;
40
+ abstract relationQuery(nameRelations: string, callback: Function): this;
41
+ abstract relationsExists(...nameRelations: string[]): this;
42
+ abstract relationsAndTrashed(...nameRelations: string[]): this;
43
+ }
44
+ export { AbstractModel };
45
+ export default AbstractModel;
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.AbstractModel = void 0;
7
+ const Builder_1 = __importDefault(require("../Builder"));
8
+ class AbstractModel extends Builder_1.default {
9
+ }
10
+ exports.AbstractModel = AbstractModel;
11
+ exports.default = AbstractModel;
@@ -1,3 +1,17 @@
1
+ /**
2
+ * make schema for table with Blueprint
3
+ * @example
4
+ * import { Schema , Blueprint } from 'tspace-mysql'
5
+ * await new Schema().table('persos1',{
6
+ * id : new Blueprint().int().notNull().primary().autoIncrement(),
7
+ * name : new Blueprint().varchar(255).default('my name ...'),
8
+ * email : new Blueprint().varchar(255).unique(),
9
+ * verify : new Blueprint().tinyInt(1).notNull(),
10
+ * created_at : new Blueprint().timestamp().null(),
11
+ * updated_at : new Blueprint().timestamp().null(),
12
+ * deleted_at : new Blueprint().timestamp().null()
13
+ * })
14
+ */
1
15
  declare class Blueprint {
2
16
  protected type: string;
3
17
  protected attrbuites: Array<string>;
@@ -115,10 +129,10 @@ declare class Blueprint {
115
129
  primary(): this;
116
130
  /**
117
131
  * Assign attrbuites 'default' in table
118
- * @param {string | number} n default value
132
+ * @param {string | number} value default value
119
133
  * @return {this} this
120
134
  */
121
- default(n: string | number): this;
135
+ default(value: string | number): this;
122
136
  /**
123
137
  * Assign attrbuites 'default currentTimestamp' in table
124
138
  * @return {this} this
@@ -1,6 +1,20 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Blueprint = void 0;
4
+ /**
5
+ * make schema for table with Blueprint
6
+ * @example
7
+ * import { Schema , Blueprint } from 'tspace-mysql'
8
+ * await new Schema().table('persos1',{
9
+ * id : new Blueprint().int().notNull().primary().autoIncrement(),
10
+ * name : new Blueprint().varchar(255).default('my name ...'),
11
+ * email : new Blueprint().varchar(255).unique(),
12
+ * verify : new Blueprint().tinyInt(1).notNull(),
13
+ * created_at : new Blueprint().timestamp().null(),
14
+ * updated_at : new Blueprint().timestamp().null(),
15
+ * deleted_at : new Blueprint().timestamp().null()
16
+ * })
17
+ */
4
18
  class Blueprint {
5
19
  constructor() {
6
20
  this.type = '';
@@ -190,11 +204,11 @@ class Blueprint {
190
204
  }
191
205
  /**
192
206
  * Assign attrbuites 'default' in table
193
- * @param {string | number} n default value
207
+ * @param {string | number} value default value
194
208
  * @return {this} this
195
209
  */
196
- default(n) {
197
- this._addAssignAttrbuite(`DEFAULT '${n}'`);
210
+ default(value) {
211
+ this._addAssignAttrbuite(`DEFAULT '${value}'`);
198
212
  return this;
199
213
  }
200
214
  /**
@@ -1,4 +1,4 @@
1
- import { AbstractBuilder } from './AbstractBuilder';
1
+ import { AbstractBuilder } from './Abstract/AbstractBuilder';
2
2
  import { Pagination, Backup, ConnectionOptions, BackupToFile, Connection, ConnectionTransaction } from './Interface';
3
3
  declare class Builder extends AbstractBuilder {
4
4
  constructor();
@@ -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
@@ -26,7 +26,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
26
26
  exports.Builder = void 0;
27
27
  const fs_1 = __importDefault(require("fs"));
28
28
  const sql_formatter_1 = require("sql-formatter");
29
- const AbstractBuilder_1 = require("./AbstractBuilder");
29
+ const AbstractBuilder_1 = require("./Abstract/AbstractBuilder");
30
30
  const utils_1 = require("../utils");
31
31
  const constants_1 = require("../constants");
32
32
  const DB_1 = require("./DB");
@@ -52,7 +52,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
52
52
  * @return {this} this
53
53
  */
54
54
  except(...columns) {
55
- this.$state.set('EXCEPT', columns.length ? columns : ['id']);
55
+ this.$state.set('EXCEPT', columns.length ? columns : []);
56
56
  return this;
57
57
  }
58
58
  /**
@@ -1343,7 +1343,10 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
1343
1343
  ].join(' ');
1344
1344
  const rawColumns = yield this.queryStatement(sql);
1345
1345
  const columns = rawColumns.map((column) => column.Field);
1346
- const removeExcept = columns.filter((column) => !String(this.$state.get('EXCEPT')).includes(column));
1346
+ const removeExcept = columns.filter((column) => {
1347
+ const excepts = this.$state.get('EXCEPT');
1348
+ return excepts.every((except) => except !== column);
1349
+ });
1347
1350
  return removeExcept;
1348
1351
  });
1349
1352
  }
@@ -1724,7 +1727,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
1724
1727
  this.$state.set('SELECT', [
1725
1728
  `${this.$constants('SELECT')}`,
1726
1729
  `${this.$constants('COUNT')}(${column})`,
1727
- `${this.$constants('AS')} total`
1730
+ `${this.$constants('AS')} \`total\``
1728
1731
  ].join(' '));
1729
1732
  const sql = this._buildQuery();
1730
1733
  const result = yield this.queryStatement(sql);
@@ -1747,7 +1750,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
1747
1750
  `${this.$state.get('FROM')}`,
1748
1751
  `${this.$state.get('TABLE_NAME')}`,
1749
1752
  `${this.$state.get('WHERE')}`,
1750
- `${this.$constants('LIMIT')} 1) ${this.$constants('AS')} 'exists'`
1753
+ `${this.$constants('LIMIT')} 1) ${this.$constants('AS')} \`exists\``
1751
1754
  ].join(' '));
1752
1755
  return Boolean(this.resultHandler(!!((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.exists) || false));
1753
1756
  });
@@ -1764,7 +1767,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
1764
1767
  this.$state.set('SELECT', [
1765
1768
  `${this.$constants('SELECT')}`,
1766
1769
  `${this.$constants('AVG')}(${column})`,
1767
- `${this.$constants('AS')} avg`
1770
+ `${this.$constants('AS')} \`avg\``
1768
1771
  ].join(' '));
1769
1772
  const sql = this._buildQuery();
1770
1773
  const result = yield this.queryStatement(sql);
@@ -1780,7 +1783,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
1780
1783
  sum(column = 'id') {
1781
1784
  var _a;
1782
1785
  return __awaiter(this, void 0, void 0, function* () {
1783
- this.$state.set('SELECT', `${this.$constants('SELECT')} ${this.$constants('SUM')}(${column}) ${this.$constants('AS')} sum`);
1786
+ this.$state.set('SELECT', `${this.$constants('SELECT')} ${this.$constants('SUM')}(${column}) ${this.$constants('AS')} \`sum\``);
1784
1787
  const sql = this._buildQuery();
1785
1788
  const result = yield this.queryStatement(sql);
1786
1789
  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 +1798,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
1795
1798
  max(column = 'id') {
1796
1799
  var _a;
1797
1800
  return __awaiter(this, void 0, void 0, function* () {
1798
- this.$state.set('SELECT', `${this.$constants('SELECT')} ${this.$constants('MAX')}(${column}) ${this.$constants('AS')} max`);
1801
+ this.$state.set('SELECT', `${this.$constants('SELECT')} ${this.$constants('MAX')}(${column}) ${this.$constants('AS')} \`max\``);
1799
1802
  const sql = this._buildQuery();
1800
1803
  const result = yield this.queryStatement(sql);
1801
1804
  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 +1813,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
1810
1813
  min(column = 'id') {
1811
1814
  var _a;
1812
1815
  return __awaiter(this, void 0, void 0, function* () {
1813
- this.$state.set('SELECT', `${this.$constants('SELECT')} ${this.$constants('MIN')}(${column}) ${this.$constants('AS')} min`);
1816
+ this.$state.set('SELECT', `${this.$constants('SELECT')} ${this.$constants('MIN')}(${column}) ${this.$constants('AS')} \`min\``);
1814
1817
  const sql = this._buildQuery();
1815
1818
  const result = yield this.queryStatement(sql);
1816
1819
  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 +1989,8 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
1986
1989
  `${this.$constants('FROM')}`,
1987
1990
  `\`${table.replace(/\`/g, '')}\``
1988
1991
  ].join(' ');
1989
- const raw = yield this.queryStatement(sql);
1990
- const schemas = raw.map((r) => {
1992
+ const raws = yield this.queryStatement(sql);
1993
+ return raws.map((r) => {
1991
1994
  const schema = [];
1992
1995
  schema.push(`${r.Field}`);
1993
1996
  schema.push(`${r.Type}`);
@@ -2011,7 +2014,6 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
2011
2014
  }
2012
2015
  return schema.join(' ');
2013
2016
  });
2014
- return schemas;
2015
2017
  });
2016
2018
  }
2017
2019
  /**
@@ -2163,6 +2165,8 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
2163
2165
  tabWidth: 2,
2164
2166
  linesBetweenQueries: 1,
2165
2167
  }));
2168
+ // fs.writeFileSync(filePath, [...sql,'COMMIT;'].join('\n'))
2169
+ console.log(sql);
2166
2170
  return;
2167
2171
  });
2168
2172
  }
@@ -1,4 +1,4 @@
1
- import { AbstractDB } from './AbstractDB';
1
+ import { AbstractDB } from './Abstract/AbstractDB';
2
2
  import { Connection, ConnectionOptions, ConnectionTransaction } from './Interface';
3
3
  /**
4
4
  * Assign table name
@@ -24,7 +24,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
26
  exports.DB = void 0;
27
- const AbstractDB_1 = require("./AbstractDB");
27
+ const AbstractDB_1 = require("./Abstract/AbstractDB");
28
28
  const ProxyHandler_1 = require("./ProxyHandler");
29
29
  const connection_1 = require("../connection");
30
30
  const StateHandler_1 = __importDefault(require("./StateHandler"));
@@ -1,4 +1,4 @@
1
- import { AbstractModel } from './AbstractModel';
1
+ import { AbstractModel } from './Abstract/AbstractModel';
2
2
  import { Relation, Pagination, RelationQuery } from './Interface';
3
3
  declare class Model extends AbstractModel {
4
4
  constructor();
@@ -211,7 +211,7 @@ declare class Model extends AbstractModel {
211
211
  * @example
212
212
  * class User extends Model {
213
213
  * constructor() {
214
- * this.useSchema({
214
+ * this.useValidationSchema({
215
215
  * id : Number,
216
216
  * email : String,
217
217
  * name : String,
@@ -221,7 +221,7 @@ declare class Model extends AbstractModel {
221
221
  * }
222
222
  * @return {this} this
223
223
  */
224
- protected useSchema(schema: Record<string, NumberConstructor | StringConstructor | DateConstructor>): this;
224
+ protected useValidationSchema(schema: Record<string, NumberConstructor | StringConstructor | DateConstructor>): this;
225
225
  /**
226
226
  * Assign hook function when execute returned results to callback function
227
227
  * @param {Array<Function>} arrayFunctions functions for callback result
@@ -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 };
@@ -16,7 +16,7 @@ exports.Model = void 0;
16
16
  const pluralize_1 = __importDefault(require("pluralize"));
17
17
  const DB_1 = require("./DB");
18
18
  const Schema_1 = require("./Schema");
19
- const AbstractModel_1 = require("./AbstractModel");
19
+ const AbstractModel_1 = require("./Abstract/AbstractModel");
20
20
  const ProxyHandler_1 = require("./ProxyHandler");
21
21
  const StateHandler_1 = require("./StateHandler");
22
22
  class Model extends AbstractModel_1.AbstractModel {
@@ -301,7 +301,7 @@ class Model extends AbstractModel_1.AbstractModel {
301
301
  * @example
302
302
  * class User extends Model {
303
303
  * constructor() {
304
- * this.useSchema({
304
+ * this.useValidationSchema({
305
305
  * id : Number,
306
306
  * email : String,
307
307
  * name : String,
@@ -311,7 +311,7 @@ class Model extends AbstractModel_1.AbstractModel {
311
311
  * }
312
312
  * @return {this} this
313
313
  */
314
- useSchema(schema) {
314
+ useValidationSchema(schema) {
315
315
  this.$state.set('SCHEMA', schema);
316
316
  return this;
317
317
  }
@@ -342,7 +342,10 @@ class Model extends AbstractModel_1.AbstractModel {
342
342
  return __awaiter(this, void 0, void 0, function* () {
343
343
  if (this.$state.get('SCHEMA')) {
344
344
  const columns = Object.keys(this.$state.get('SCHEMA'));
345
- const removeExcept = columns.filter((column) => !String(this.$state.get('EXCEPT')).includes(column));
345
+ const removeExcept = columns.filter((column) => {
346
+ const excepts = this.$state.get('EXCEPT');
347
+ return excepts.every((except) => except !== column);
348
+ });
346
349
  return removeExcept;
347
350
  }
348
351
  const rawColumns = yield this.queryStatement([
@@ -352,7 +355,10 @@ class Model extends AbstractModel_1.AbstractModel {
352
355
  `${this.$state.get('TABLE_NAME')}`
353
356
  ].join(' '));
354
357
  const columns = rawColumns.map((column) => column.Field);
355
- const removeExcept = columns.filter((column) => !String(this.$state.get('EXCEPT')).includes(column));
358
+ const removeExcept = columns.filter((column) => {
359
+ const excepts = this.$state.get('EXCEPT');
360
+ return excepts.every((except) => except !== column);
361
+ });
356
362
  return removeExcept;
357
363
  });
358
364
  }
@@ -399,7 +405,6 @@ class Model extends AbstractModel_1.AbstractModel {
399
405
  const copy = Object.fromEntries(instance.$state.get());
400
406
  const newInstance = new Model();
401
407
  newInstance.$state.clone(copy);
402
- newInstance.$state.set('SAVE', '');
403
408
  if ((options === null || options === void 0 ? void 0 : options.insert) == null)
404
409
  newInstance.$state.set('INSERT', '');
405
410
  if ((options === null || options === void 0 ? void 0 : options.update) == null)
@@ -412,8 +417,16 @@ class Model extends AbstractModel_1.AbstractModel {
412
417
  newInstance.$state.set('LIMIT', '');
413
418
  if ((options === null || options === void 0 ? void 0 : options.offset) == null)
414
419
  newInstance.$state.set('OFFSET', '');
420
+ newInstance.$state.set('SAVE', '');
415
421
  return newInstance;
416
422
  }
423
+ /**
424
+ *
425
+ * execute the query using raw sql syntax
426
+ * @override method
427
+ * @param {string} sql
428
+ * @return {this} this
429
+ */
417
430
  queryStatement(sql) {
418
431
  return __awaiter(this, void 0, void 0, function* () {
419
432
  try {
@@ -424,24 +437,42 @@ class Model extends AbstractModel_1.AbstractModel {
424
437
  return result;
425
438
  }
426
439
  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
- }
440
+ yield this._tryToCreateTable(e);
441
441
  return yield this.queryStatement(sql);
442
442
  }
443
443
  });
444
444
  }
445
+ /**
446
+ *
447
+ * execute the query using raw sql syntax actions for insert update and delete
448
+ * @override method
449
+ * @param {Object} actions
450
+ * @property {Function} actions.sql
451
+ * @property {Function} actions.returnId
452
+ * @return {this} this
453
+ */
454
+ actionStatement({ sql, returnId = false }) {
455
+ return __awaiter(this, void 0, void 0, function* () {
456
+ try {
457
+ if (this.$state.get('DEBUG'))
458
+ this.$utils.consoleDebug(sql);
459
+ this.$state.set('QUERIES', this.$state.get('QUERIES') + 1);
460
+ if (returnId) {
461
+ const result = yield this.$pool.query(sql);
462
+ return [result.affectedRows, result.insertId];
463
+ }
464
+ const { affectedRows: result } = yield this.$pool.query(sql);
465
+ return result;
466
+ }
467
+ catch (e) {
468
+ yield this._tryToCreateTable(e);
469
+ return yield this.actionStatement({
470
+ sql,
471
+ returnId
472
+ });
473
+ }
474
+ });
475
+ }
445
476
  /**
446
477
  * Assign table name
447
478
  * @param {string} table table name
@@ -1073,7 +1104,10 @@ class Model extends AbstractModel_1.AbstractModel {
1073
1104
  * @return {string}
1074
1105
  */
1075
1106
  toString() {
1076
- return this._buildQueryModel();
1107
+ const sql = this._buildQueryModel();
1108
+ if (this.$state.get('DEBUG'))
1109
+ this.$utils.consoleDebug(sql);
1110
+ return this.resultHandler(sql);
1077
1111
  }
1078
1112
  /**
1079
1113
  *
@@ -1081,7 +1115,10 @@ class Model extends AbstractModel_1.AbstractModel {
1081
1115
  * @return {string}
1082
1116
  */
1083
1117
  toSQL() {
1084
- return this._buildQueryModel();
1118
+ const sql = this._buildQueryModel();
1119
+ if (this.$state.get('DEBUG'))
1120
+ this.$utils.consoleDebug(sql);
1121
+ return this.resultHandler(sql);
1085
1122
  }
1086
1123
  /**
1087
1124
  *
@@ -1094,7 +1131,7 @@ class Model extends AbstractModel_1.AbstractModel {
1094
1131
  const result = yield this.queryStatement(sql);
1095
1132
  if (this.$state.get('HIDDEN').length)
1096
1133
  this._hiddenColumnModel(result);
1097
- return JSON.stringify(result);
1134
+ return this.resultHandler(JSON.stringify(result));
1098
1135
  });
1099
1136
  }
1100
1137
  /**
@@ -1109,7 +1146,7 @@ class Model extends AbstractModel_1.AbstractModel {
1109
1146
  const sql = this._buildQueryModel();
1110
1147
  const result = yield this.queryStatement(sql);
1111
1148
  const toArray = result.map((data) => data[column]);
1112
- return toArray;
1149
+ return this.resultHandler(toArray);
1113
1150
  });
1114
1151
  }
1115
1152
  /**
@@ -1121,7 +1158,7 @@ class Model extends AbstractModel_1.AbstractModel {
1121
1158
  avg(column = 'id') {
1122
1159
  var _a;
1123
1160
  return __awaiter(this, void 0, void 0, function* () {
1124
- this.selectRaw(`${this.$constants('AVG')}(${column}) ${this.$constants('AS')} avg`);
1161
+ this.selectRaw(`${this.$constants('AVG')}(${column}) ${this.$constants('AS')} \`avg\``);
1125
1162
  const sql = this._buildQueryModel();
1126
1163
  const result = yield this.queryStatement(sql);
1127
1164
  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 +1173,7 @@ class Model extends AbstractModel_1.AbstractModel {
1136
1173
  sum(column = 'id') {
1137
1174
  var _a;
1138
1175
  return __awaiter(this, void 0, void 0, function* () {
1139
- this.selectRaw(`${this.$constants('SUM')}(${column}) ${this.$constants('AS')} sum`);
1176
+ this.selectRaw(`${this.$constants('SUM')}(${column}) ${this.$constants('AS')} \`sum\``);
1140
1177
  const sql = this._buildQueryModel();
1141
1178
  const result = yield this.queryStatement(sql);
1142
1179
  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 +1188,7 @@ class Model extends AbstractModel_1.AbstractModel {
1151
1188
  max(column = 'id') {
1152
1189
  var _a;
1153
1190
  return __awaiter(this, void 0, void 0, function* () {
1154
- this.selectRaw(`${this.$constants('MAX')}(${column}) ${this.$constants('AS')} max`);
1191
+ this.selectRaw(`${this.$constants('MAX')}(${column}) ${this.$constants('AS')} \`max\``);
1155
1192
  const sql = this._buildQueryModel();
1156
1193
  const result = yield this.queryStatement(sql);
1157
1194
  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 +1203,7 @@ class Model extends AbstractModel_1.AbstractModel {
1166
1203
  min(column = 'id') {
1167
1204
  var _a;
1168
1205
  return __awaiter(this, void 0, void 0, function* () {
1169
- this.selectRaw(`${this.$constants('MIN')}(${column}) ${this.$constants('AS')} min`);
1206
+ this.selectRaw(`${this.$constants('MIN')}(${column}) ${this.$constants('AS')} \`min\``);
1170
1207
  const sql = this._buildQueryModel();
1171
1208
  const result = yield this.queryStatement(sql);
1172
1209
  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 +1218,7 @@ class Model extends AbstractModel_1.AbstractModel {
1181
1218
  count(column = 'id') {
1182
1219
  var _a;
1183
1220
  return __awaiter(this, void 0, void 0, function* () {
1184
- this.selectRaw(`${this.$constants('COUNT')}(${column}) ${this.$constants('AS')} total`);
1221
+ this.selectRaw(`${this.$constants('COUNT')}(${column}) ${this.$constants('AS')} \`total\``);
1185
1222
  const sql = this._buildQueryModel();
1186
1223
  const result = yield this.queryStatement(sql);
1187
1224
  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 +1238,7 @@ class Model extends AbstractModel_1.AbstractModel {
1201
1238
  `${this.$constants('SELECT')}`,
1202
1239
  `${this.$constants('EXISTS')}`,
1203
1240
  `(${sql})`,
1204
- `${this.$constants('AS')} 'exists'`
1241
+ `${this.$constants('AS')} \`exists\``
1205
1242
  ].join(' '));
1206
1243
  return Boolean(this.resultHandler(!!((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.exists) || false));
1207
1244
  });
@@ -1702,13 +1739,13 @@ class Model extends AbstractModel_1.AbstractModel {
1702
1739
  }
1703
1740
  }
1704
1741
  switch (String(this.$state.get('SAVE'))) {
1705
- case 'INSERT_MULTIPLE': return yield this._createMultipleModel();
1706
1742
  case 'INSERT': return yield this._insertModel();
1707
1743
  case 'UPDATE': return yield this._updateModel();
1744
+ case 'INSERT_MULTIPLE': return yield this._createMultipleModel();
1708
1745
  case 'INSERT_NOT_EXISTS': return yield this._insertNotExistsModel();
1709
1746
  case 'UPDATE_OR_INSERT': return yield this._updateOrInsertModel();
1710
1747
  case 'INSERT_OR_SELECT': return yield this._insertOrSelectModel();
1711
- default: throw new Error(`unknown this [${this.$state.get('SAVE')}]`);
1748
+ default: throw new Error(`Unknown this [${this.$state.get('SAVE')}]`);
1712
1749
  }
1713
1750
  });
1714
1751
  }
@@ -2581,10 +2618,11 @@ class Model extends AbstractModel_1.AbstractModel {
2581
2618
  return this.resultHandler(null);
2582
2619
  if (!result)
2583
2620
  return this.resultHandler(null);
2584
- return yield new Model().copyModel(this)
2621
+ const resultData = yield new Model().copyModel(this)
2585
2622
  .where('id', id)
2586
2623
  .bind(this.$pool.get())
2587
2624
  .first();
2625
+ return this.resultHandler(resultData);
2588
2626
  });
2589
2627
  }
2590
2628
  _createMultipleModel() {
@@ -2765,6 +2803,29 @@ class Model extends AbstractModel_1.AbstractModel {
2765
2803
  }
2766
2804
  }
2767
2805
  }
2806
+ _tryToCreateTable(e) {
2807
+ var _a;
2808
+ return __awaiter(this, void 0, void 0, function* () {
2809
+ const createTable = this.$state.get('CREATE_TABLE');
2810
+ if (createTable == null)
2811
+ throw e;
2812
+ const errorMessage = (_a = e === null || e === void 0 ? void 0 : e.message) !== null && _a !== void 0 ? _a : '';
2813
+ const errorWhenTableIsNotExists = "doesn't exist";
2814
+ if (!errorMessage.toLocaleLowerCase().includes(errorWhenTableIsNotExists))
2815
+ throw e;
2816
+ if (this.$state.get('QUERIES') > 3)
2817
+ throw e;
2818
+ try {
2819
+ const tableName = this.$state.get('TABLE_NAME');
2820
+ yield new Schema_1.Schema()
2821
+ .debug(this.$state.get('DEBUG'))
2822
+ .createTable(tableName, createTable);
2823
+ }
2824
+ catch (e) {
2825
+ throw e;
2826
+ }
2827
+ });
2828
+ }
2768
2829
  _initialModel() {
2769
2830
  this.$state = new StateHandler_1.StateHandler(this.$constants('MODEL'));
2770
2831
  this._makeTableName();
@@ -1,13 +1,7 @@
1
1
  import { Builder } from "./Builder";
2
2
  declare class Schema extends Builder {
3
- table: (table: string, schemas: Record<string, {
4
- type: string;
5
- attrbuites: string[];
6
- }>) => Promise<void>;
7
- createTable: (table: string, schemas: Record<string, {
8
- type: string;
9
- attrbuites: string[];
10
- }>) => Promise<any>;
3
+ table: (table: string, schemas: Record<string, any>) => Promise<void>;
4
+ createTable: (table: string, schemas: Record<string, any>) => Promise<any>;
11
5
  }
12
6
  export { Schema };
13
7
  export default Schema;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tspace-mysql",
3
- "version": "1.3.5",
3
+ "version": "1.3.7",
4
4
  "description": "mysql query builder object relational mapping",
5
5
  "main": "dist/lib/index.js",
6
6
  "types": "dist/lib/index.d.ts",