tspace-mysql 1.3.8 → 1.3.9

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
@@ -414,13 +414,7 @@ class User extends Model {
414
414
  * this.useRegistry() // => build-in functions registry
415
415
  * this.useLoadRelationsInRegistry() // => auto generated results from relationship to results
416
416
  * this.useBuiltInRelationFunctions() // => build-in functions relationships to results
417
- * this.useValidationSchema({
418
- * id : Number,
419
- * username : String
420
- * created_at : Date,
421
- * updated_at : Date,
422
- * }) // => validate type of schema when return results
423
- * this.useCreateTableIfNotExists ({
417
+ * this.useSchema ({
424
418
  * id : new Blueprint().int().notNull().primary().autoIncrement(),
425
419
  * uuid : new Blueprint().varchar(50).null(),
426
420
  * user_id : new Blueprint().int().notNull(),
@@ -428,7 +422,9 @@ class User extends Model {
428
422
  * created_at : new Blueprint().timestamp().null(),
429
423
  * updated_at : new Blueprint().timestamp().null(),
430
424
  * deleted_at : new Blueprint().timestamp().null()
431
- * })
425
+ * }) // auto-generated table when table is not exists and auto-create column when column not exists
426
+ *
427
+ * this.useValidateSchema() // => validate type of value when return results reference to the schema in 'this.useSchema'
432
428
  */
433
429
 
434
430
 
@@ -32,12 +32,26 @@ exports.default = (cmd) => {
32
32
  for (let i = 0; i < tables.length; i++) {
33
33
  const table = String((_a = Object.values(tables[i])) === null || _a === void 0 ? void 0 : _a.shift());
34
34
  const model = snakeCaseToPascal(pluralize_1.default.singular(table));
35
- const data = (0, model_1.default)(model, npm);
36
- fs.writeFile(`${cwd}/${dir}/${model}${type !== null && type !== void 0 ? type : '.ts'}`, data, (err) => {
37
- if (err)
38
- throw err;
35
+ new lib_1.DB().rawQuery(`SHOW COLUMNS FROM ${table}`).then(raw => {
36
+ let schema = '';
37
+ for (const r of raw) {
38
+ schema += `${r.Field} : `;
39
+ schema += `new Blueprint().${/^[^()]*$/.test(r.Type) ? `${r.Type.toLocaleLowerCase()}()` : r.Type.toLocaleLowerCase()}`;
40
+ schema += `${r.Null === 'YES' ? '.null()' : '.notNull()'}`;
41
+ schema += r.Key === 'PRI' ? '.primary()' : r.Key === 'UNI' ? '.unique()' : '';
42
+ schema += r.Default != null ? `.default('${r.Default}')` : '';
43
+ schema += `${r.Extra === 'auto_increment' ? '.autoIncrement()' : ''},
44
+ `;
45
+ }
46
+ const data = (0, model_1.default)(model, npm, `this.useSchema({
47
+ ${schema.replace(/,\s*$/, "")}
48
+ })`);
49
+ fs.writeFile(`${cwd}/${dir}/${model}${type !== null && type !== void 0 ? type : '.ts'}`, data, (err) => {
50
+ if (err)
51
+ throw err;
52
+ });
53
+ console.log(`Model : '${model}' created successfully`);
39
54
  });
40
- console.log(`Model : '${model}' created successfully`);
41
55
  }
42
56
  console.log('\nGenerate Models has completed');
43
57
  })
@@ -1,2 +1,2 @@
1
- declare const Model: (model: string, npm: string) => string;
1
+ declare const Model: (model: string, npm: string, schema: string) => string;
2
2
  export default Model;
@@ -1,26 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const Model = (model, npm) => {
4
- return `import { Model } from '${npm}'
3
+ const Model = (model, npm, schema) => {
4
+ return `import { Model , Blueprint } from '${npm}'
5
5
  class ${model} extends Model {
6
6
  constructor(){
7
7
  super()
8
- /**
9
- *
10
- * Assign setting global in your model
11
- * @useMethod
12
- * this.useUUID() // => runing a uuid (universally unique identifier) when insert new data
13
- * this.useDebug() // debug raw query
14
- * this.usePrimaryKey('id')
15
- * this.useTimestamp({ createdAt : 'created_at' , updatedAt : 'updated_at' }) // runing a timestamp when insert or update
16
- * this.useSoftDelete()
17
- * this.useTable('users')
18
- * this.useTableSingular() // 'user'
19
- * this.useTablePlural() // 'users'
20
- * this.usePattern('snake_case')
21
- * this.useUUID('uuid')
22
- * this.useRegistry()
23
- */
8
+ ${schema}
24
9
  }
25
10
  }
26
11
  export { ${model} }
@@ -1,4 +1,4 @@
1
- declare const _default: (formCommand: {
1
+ declare const _default: (commandInput: {
2
2
  [x: string]: any;
3
3
  }) => void;
4
4
  export default _default;
@@ -1,9 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const child_process_1 = require("child_process");
4
- exports.default = (formCommand) => {
4
+ exports.default = (commandInput) => {
5
5
  var _a, _b, _c;
6
- const { type, dir, cwd, fs } = formCommand;
6
+ const { type, dir, cwd, fs } = commandInput;
7
7
  try {
8
8
  if (dir == null)
9
9
  throw new Error('Not found directory');
@@ -7,7 +7,7 @@ class ${model} extends Model {
7
7
  super()
8
8
  /**
9
9
  *
10
- * Assign setting global in your model
10
+ * //Assign setting global in your model
11
11
  * @useMethod
12
12
  *
13
13
  * this.useDebug()
@@ -16,19 +16,6 @@ class ${model} extends Model {
16
16
  * createdAt : 'created_at',
17
17
  * updatedAt : 'updated_at'
18
18
  * }) // runing a timestamp when insert or update
19
- * this.useSoftDelete()
20
- * this.useTable('users')
21
- * this.useTableSingular() // 'user'
22
- * this.useTablePlural() // 'users'
23
- * this.usePattern('snake_case') // by defalut snake_case
24
- * this.useUUID('uuid') // => runing a uuid (universally unique identifier) when insert new data
25
- * this.useRegistry()
26
- * this.useSchema({
27
- * id : Number,
28
- * username : String
29
- * created_at : Date,
30
- * updated_at : Date,
31
- * }) // validate type of schema when return result
32
19
  */
33
20
  }
34
21
  }
@@ -18,22 +18,23 @@ const environment = () => {
18
18
  return env;
19
19
  };
20
20
  dotenv_1.default.config({ path: environment() });
21
+ const ENV = process.env;
21
22
  const env = {
22
- HOST: process.env.DB_HOST || process.env.TSPACE_HOST,
23
- PORT: process.env.DB_PORT || process.env.TSPACE_PORT || 3306,
24
- USERNAME: process.env.DB_USERNAME || process.env.TSPACE_USERNAME,
25
- PASSWORD: process.env.DB_PASSWORD || process.env.TSPACE_PASSWORD || '',
26
- DATABASE: process.env.DB_DATABASE || process.env.TSPACE_DATABASE,
27
- CONNECTION_LIMIT: process.env.DB_CONNECTION_LIMIT || process.env.TSPACE_CONNECTION_LIMIT || 30,
28
- QUEUE_LIMIT: process.env.DB_QUEUE_LIMIT || process.env.TSPACE_QUEUE_LIMIT || 0,
29
- TIMEOUT: process.env.DB_TIMEOUT || process.env.TSPACE_TIMEOUT || 1000 * 60,
30
- CHARSET: process.env.DB_CHARSET || process.env.TSPACE_CHARSET || 'utf8mb4',
31
- CONNECTION_ERROR: process.env.DB_CONNECTION_ERROR || process.env.TSPACE_CONNECTION_ERROR || true,
32
- WAIT_FOR_CONNECTIONS: process.env.DB_WAIT_FOR_CONNECTIONS || process.env.TSPACE_WAIT_FOR_CONNECTIONS || true,
33
- DATE_STRINGS: process.env.DB_DATE_STRINGS || process.env.TSPACE_DATE_STRINGS || true,
34
- KEEP_ALIVE_DELAY: process.env.DB_KEEP_ALIVE_DELAY || process.env.TSPACE_KEEP_ALIVE_DELAY || 0,
35
- ENABLE_KEEP_ALIVE: process.env.DB_ENABLE_KEEP_ALIVE || process.env.TSPACE_ENABLE_KEEP_ALIVE || false,
36
- MULTIPLE_STATEMENTS: process.env.MULTIPLE_STATEMENTS || process.env.TSPACE_MULTIPLE_STATEMENTS || false
23
+ HOST: ENV.DB_HOST || ENV.TSPACE_HOST,
24
+ PORT: ENV.DB_PORT || ENV.TSPACE_PORT || 3306,
25
+ USERNAME: ENV.DB_USERNAME || ENV.TSPACE_USERNAME,
26
+ PASSWORD: ENV.DB_PASSWORD || ENV.TSPACE_PASSWORD || '',
27
+ DATABASE: ENV.DB_DATABASE || ENV.TSPACE_DATABASE,
28
+ CONNECTION_LIMIT: ENV.DB_CONNECTION_LIMIT || ENV.TSPACE_CONNECTION_LIMIT || 30,
29
+ QUEUE_LIMIT: ENV.DB_QUEUE_LIMIT || ENV.TSPACE_QUEUE_LIMIT || 0,
30
+ TIMEOUT: ENV.DB_TIMEOUT || ENV.TSPACE_TIMEOUT || 1000 * 60,
31
+ CHARSET: ENV.DB_CHARSET || ENV.TSPACE_CHARSET || 'utf8mb4',
32
+ CONNECTION_ERROR: ENV.DB_CONNECTION_ERROR || ENV.TSPACE_CONNECTION_ERROR || true,
33
+ WAIT_FOR_CONNECTIONS: ENV.DB_WAIT_FOR_CONNECTIONS || ENV.TSPACE_WAIT_FOR_CONNECTIONS || true,
34
+ DATE_STRINGS: ENV.DB_DATE_STRINGS || ENV.TSPACE_DATE_STRINGS || true,
35
+ KEEP_ALIVE_DELAY: ENV.DB_KEEP_ALIVE_DELAY || ENV.TSPACE_KEEP_ALIVE_DELAY || 0,
36
+ ENABLE_KEEP_ALIVE: ENV.DB_ENABLE_KEEP_ALIVE || ENV.TSPACE_ENABLE_KEEP_ALIVE || false,
37
+ MULTIPLE_STATEMENTS: ENV.MULTIPLE_STATEMENTS || ENV.TSPACE_MULTIPLE_STATEMENTS || false
37
38
  };
38
39
  for (const [key, value] of Object.entries(env)) {
39
40
  if (value == null)
@@ -67,6 +67,9 @@ const CONSTANTS = Object.freeze({
67
67
  CREATE_TABLE_NOT_EXISTS: 'CREATE TABLE IF NOT EXISTS',
68
68
  ENGINE: 'ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8',
69
69
  RAND: 'RAND()',
70
+ ALTER_TABLE: 'ALTER TABLE',
71
+ ADD: 'ADD',
72
+ AFTER: 'AFTER',
70
73
  RELATIONSHIP: {
71
74
  hasOne: 'hasOne',
72
75
  hasMany: 'hasMany',
@@ -159,9 +162,10 @@ const CONSTANTS = Object.freeze({
159
162
  CREATED_AT: 'created_at',
160
163
  UPDATED_AT: 'updated_at'
161
164
  },
162
- SCHEMA: null,
165
+ VALIDATE_SCHEMA: false,
166
+ VALIDATE_SCHEMA_DEFINED: null,
163
167
  FUNCTION_RELATION: false,
164
- CREATE_TABLE: null,
168
+ SCHEMA_TABLE: null,
165
169
  QUERIES: 0
166
170
  }
167
171
  });
@@ -3,10 +3,10 @@
3
3
  * @example
4
4
  * import { Schema , Blueprint } from 'tspace-mysql'
5
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(),
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
10
  * created_at : new Blueprint().timestamp().null(),
11
11
  * updated_at : new Blueprint().timestamp().null(),
12
12
  * deleted_at : new Blueprint().timestamp().null()
@@ -14,7 +14,8 @@
14
14
  */
15
15
  declare class Blueprint {
16
16
  protected type: string;
17
- protected attrbuites: Array<string>;
17
+ protected attributes: Array<string>;
18
+ protected valueType: NumberConstructor | StringConstructor | DateConstructor;
18
19
  /**
19
20
  * Assign type 'int' in table
20
21
  * @return {this} this
@@ -48,7 +49,7 @@ declare class Blueprint {
48
49
  float(length?: number, decimal?: number): this;
49
50
  /**
50
51
  * Assign type 'VARCHAR' in table
51
- * @param {number} length [length = 100] length of string
52
+ * @param {number} length [length = 191] length of string
52
53
  * @return {this} this
53
54
  */
54
55
  varchar(length?: number): this;
@@ -65,7 +66,6 @@ declare class Blueprint {
65
66
  longText(): this;
66
67
  /**
67
68
  * Assign type 'MEDIUMTEXT' in table
68
- * @param {number} length [length = 1] length of string
69
69
  * @return {this} this
70
70
  */
71
71
  mediumText(): this;
@@ -103,48 +103,48 @@ declare class Blueprint {
103
103
  */
104
104
  timestamp(): this;
105
105
  /**
106
- * Assign type 'UNSIGNED' in table
106
+ * Assign attributes 'UNSIGNED' in table
107
107
  * @return {this} this
108
108
  */
109
109
  unsigned(): this;
110
110
  /**
111
- * Assign type 'UNIQUE' in table
111
+ * Assign attributes 'UNIQUE' in table
112
112
  * @return {this} this
113
113
  */
114
114
  unique(): this;
115
115
  /**
116
- * Assign type 'NULL' in table
116
+ * Assign attributes 'NULL' in table
117
117
  * @return {this} this
118
118
  */
119
119
  null(): this;
120
120
  /**
121
- * Assign type 'NOT NULL' in table
121
+ * Assign attributes 'NOT NULL' in table
122
122
  * @return {this} this
123
123
  */
124
124
  notNull(): this;
125
125
  /**
126
- * Assign type 'PRIMARY KEY' in table
126
+ * Assign attributes 'PRIMARY KEY' in table
127
127
  * @return {this} this
128
128
  */
129
129
  primary(): this;
130
130
  /**
131
- * Assign attrbuites 'default' in table
131
+ * Assign attributes 'default' in table
132
132
  * @param {string | number} value default value
133
133
  * @return {this} this
134
134
  */
135
135
  default(value: string | number): this;
136
136
  /**
137
- * Assign attrbuites 'default currentTimestamp' in table
137
+ * Assign attributes 'default currentTimestamp' in table
138
138
  * @return {this} this
139
139
  */
140
140
  currentTimestamp(): this;
141
141
  /**
142
- * Assign attrbuites 'autoIncrement' in table
142
+ * Assign attributes 'autoIncrement' in table
143
143
  * @return {this} this
144
144
  */
145
145
  autoIncrement(): this;
146
146
  private _addAssignType;
147
- private _addAssignAttrbuite;
147
+ private _addAssignAttribute;
148
148
  }
149
149
  export { Blueprint };
150
150
  export default Blueprint;
@@ -6,10 +6,10 @@ exports.Blueprint = void 0;
6
6
  * @example
7
7
  * import { Schema , Blueprint } from 'tspace-mysql'
8
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(),
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
13
  * created_at : new Blueprint().timestamp().null(),
14
14
  * updated_at : new Blueprint().timestamp().null(),
15
15
  * deleted_at : new Blueprint().timestamp().null()
@@ -18,7 +18,8 @@ exports.Blueprint = void 0;
18
18
  class Blueprint {
19
19
  constructor() {
20
20
  this.type = '';
21
- this.attrbuites = [];
21
+ this.attributes = [];
22
+ this.valueType = String;
22
23
  }
23
24
  /**
24
25
  * Assign type 'int' in table
@@ -26,6 +27,7 @@ class Blueprint {
26
27
  */
27
28
  int() {
28
29
  this._addAssignType('INT');
30
+ this.valueType = Number;
29
31
  return this;
30
32
  }
31
33
  /**
@@ -35,6 +37,7 @@ class Blueprint {
35
37
  */
36
38
  tinyInt(number = 1) {
37
39
  this._addAssignType(`TINYINT(${number})`);
40
+ this.valueType = Number;
38
41
  return this;
39
42
  }
40
43
  /**
@@ -44,6 +47,7 @@ class Blueprint {
44
47
  */
45
48
  bigInt(number = 10) {
46
49
  this._addAssignType(`BIGINT(${number})`);
50
+ this.valueType = Number;
47
51
  return this;
48
52
  }
49
53
  /**
@@ -53,6 +57,7 @@ class Blueprint {
53
57
  * @return {this} this
54
58
  */
55
59
  double(length = 0, decimal = 0) {
60
+ this.valueType = Number;
56
61
  if (!length || !decimal) {
57
62
  this._addAssignType(`DOUBLE`);
58
63
  return this;
@@ -67,6 +72,7 @@ class Blueprint {
67
72
  * @return {this} this
68
73
  */
69
74
  float(length = 0, decimal = 0) {
75
+ this.valueType = Number;
70
76
  if (!length || !decimal) {
71
77
  this._addAssignType(`FLOAT`);
72
78
  return this;
@@ -76,10 +82,10 @@ class Blueprint {
76
82
  }
77
83
  /**
78
84
  * Assign type 'VARCHAR' in table
79
- * @param {number} length [length = 100] length of string
85
+ * @param {number} length [length = 191] length of string
80
86
  * @return {this} this
81
87
  */
82
- varchar(length = 100) {
88
+ varchar(length = 191) {
83
89
  if (length > 255)
84
90
  length = 255;
85
91
  this._addAssignType(`VARCHAR(${length})`);
@@ -104,7 +110,6 @@ class Blueprint {
104
110
  }
105
111
  /**
106
112
  * Assign type 'MEDIUMTEXT' in table
107
- * @param {number} length [length = 1] length of string
108
113
  * @return {this} this
109
114
  */
110
115
  mediumText() {
@@ -135,7 +140,7 @@ class Blueprint {
135
140
  * @return {this} this
136
141
  */
137
142
  enum(...enums) {
138
- this._addAssignType(`ENUM('${enums}')`);
143
+ this._addAssignType(`ENUM(${enums.map(e => `'${e.replace(/'/g, '')}'`)})`);
139
144
  return this;
140
145
  }
141
146
  /**
@@ -144,6 +149,7 @@ class Blueprint {
144
149
  */
145
150
  date() {
146
151
  this._addAssignType(`DATE`);
152
+ this.valueType = Date;
147
153
  return this;
148
154
  }
149
155
  /**
@@ -152,6 +158,7 @@ class Blueprint {
152
158
  */
153
159
  dateTime() {
154
160
  this._addAssignType(`DATETIME`);
161
+ this.valueType = Date;
155
162
  return this;
156
163
  }
157
164
  /**
@@ -160,71 +167,72 @@ class Blueprint {
160
167
  */
161
168
  timestamp() {
162
169
  this._addAssignType(`TIMESTAMP`);
170
+ this.valueType = Date;
163
171
  return this;
164
172
  }
165
173
  /**
166
- * Assign type 'UNSIGNED' in table
174
+ * Assign attributes 'UNSIGNED' in table
167
175
  * @return {this} this
168
176
  */
169
177
  unsigned() {
170
- this._addAssignAttrbuite(`UNSIGNED`);
178
+ this._addAssignAttribute(`UNSIGNED`);
171
179
  return this;
172
180
  }
173
181
  /**
174
- * Assign type 'UNIQUE' in table
182
+ * Assign attributes 'UNIQUE' in table
175
183
  * @return {this} this
176
184
  */
177
185
  unique() {
178
- this._addAssignAttrbuite(`UNIQUE`);
186
+ this._addAssignAttribute(`UNIQUE`);
179
187
  return this;
180
188
  }
181
189
  /**
182
- * Assign type 'NULL' in table
190
+ * Assign attributes 'NULL' in table
183
191
  * @return {this} this
184
192
  */
185
193
  null() {
186
- this._addAssignAttrbuite(`NULL`);
194
+ this._addAssignAttribute(`NULL`);
187
195
  return this;
188
196
  }
189
197
  /**
190
- * Assign type 'NOT NULL' in table
198
+ * Assign attributes 'NOT NULL' in table
191
199
  * @return {this} this
192
200
  */
193
201
  notNull() {
194
- this._addAssignAttrbuite(`NOT NULL`);
202
+ this._addAssignAttribute(`NOT NULL`);
195
203
  return this;
196
204
  }
197
205
  /**
198
- * Assign type 'PRIMARY KEY' in table
206
+ * Assign attributes 'PRIMARY KEY' in table
199
207
  * @return {this} this
200
208
  */
201
209
  primary() {
202
- this._addAssignAttrbuite(`PRIMARY KEY`);
210
+ this._addAssignAttribute(`PRIMARY KEY`);
203
211
  return this;
204
212
  }
205
213
  /**
206
- * Assign attrbuites 'default' in table
214
+ * Assign attributes 'default' in table
207
215
  * @param {string | number} value default value
208
216
  * @return {this} this
209
217
  */
210
218
  default(value) {
211
- this._addAssignAttrbuite(`DEFAULT '${value}'`);
219
+ this._addAssignAttribute(`DEFAULT '${value}'`);
212
220
  return this;
213
221
  }
214
222
  /**
215
- * Assign attrbuites 'default currentTimestamp' in table
223
+ * Assign attributes 'default currentTimestamp' in table
216
224
  * @return {this} this
217
225
  */
218
226
  currentTimestamp() {
219
- this._addAssignAttrbuite(`DEFAULT CURRENT_TIMESTAMP`);
227
+ this._addAssignAttribute(`DEFAULT CURRENT_TIMESTAMP`);
220
228
  return this;
221
229
  }
222
230
  /**
223
- * Assign attrbuites 'autoIncrement' in table
231
+ * Assign attributes 'autoIncrement' in table
224
232
  * @return {this} this
225
233
  */
226
234
  autoIncrement() {
227
- this._addAssignAttrbuite(`AUTO_INCREMENT`);
235
+ this._addAssignAttribute(`AUTO_INCREMENT`);
228
236
  return this;
229
237
  }
230
238
  _addAssignType(type) {
@@ -233,8 +241,8 @@ class Blueprint {
233
241
  this.type = type;
234
242
  return this;
235
243
  }
236
- _addAssignAttrbuite(attrbuite) {
237
- this.attrbuites = [...this.attrbuites, attrbuite];
244
+ _addAssignAttribute(Attribute) {
245
+ this.attributes = [...this.attributes, Attribute];
238
246
  return this;
239
247
  }
240
248
  }
@@ -783,6 +783,12 @@ declare class Builder extends AbstractBuilder {
783
783
  * @return {Promise<Array>}
784
784
  */
785
785
  showSchemas(table?: string): Promise<Array<string>>;
786
+ /**
787
+ *
788
+ * get schema from table
789
+ * @return {this} this this
790
+ */
791
+ getSchema(): Promise<any>;
786
792
  /**
787
793
  *
788
794
  * show values in table
@@ -2077,6 +2077,22 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
2077
2077
  });
2078
2078
  });
2079
2079
  }
2080
+ /**
2081
+ *
2082
+ * get schema from table
2083
+ * @return {this} this this
2084
+ */
2085
+ getSchema() {
2086
+ return __awaiter(this, void 0, void 0, function* () {
2087
+ const sql = [
2088
+ `${this.$constants('SHOW')}`,
2089
+ `${this.$constants('COLUMNS')}`,
2090
+ `${this.$constants('FROM')}`,
2091
+ `\`${this.$state.get('TABLE_NAME').replace(/\`/g, '')}\``
2092
+ ].join(' ');
2093
+ return yield this.queryStatement(sql);
2094
+ });
2095
+ }
2080
2096
  /**
2081
2097
  *
2082
2098
  * show values in table
@@ -40,7 +40,7 @@ declare class Model extends AbstractModel {
40
40
  * import { Blueprint } from 'tspace-mysql'
41
41
  * class User extends Model {
42
42
  * constructor() {
43
- * this.useCreateTableIfNotExists ({
43
+ * this.useSchema ({
44
44
  * id : new Blueprint().int().notNull().primary().autoIncrement(),
45
45
  * uuid : new Blueprint().varchar(50).null(),
46
46
  * email : new Blueprint().varchar(50).null(),
@@ -52,7 +52,7 @@ declare class Model extends AbstractModel {
52
52
  * }
53
53
  * @return {this} this
54
54
  */
55
- protected useCreateTableIfNotExists(schema: Record<string, any>): this;
55
+ protected useSchema(schema: Record<string, any>): this;
56
56
  /**
57
57
  *
58
58
  * Assign function callback in model like constructor()
@@ -211,17 +211,25 @@ declare class Model extends AbstractModel {
211
211
  * @example
212
212
  * class User extends Model {
213
213
  * constructor() {
214
- * this.useValidationSchema({
215
- * id : Number,
216
- * email : String,
217
- * name : String,
218
- * date : Date
219
- * })
214
+ * this.useValidationSchema()
220
215
  * }
221
216
  * }
222
217
  * @return {this} this
223
218
  */
224
- protected useValidationSchema(schema: Record<string, NumberConstructor | StringConstructor | DateConstructor>): this;
219
+ protected useValidationSchema(schema?: null | Record<string, NumberConstructor | StringConstructor | DateConstructor>): this;
220
+ /**
221
+ *
222
+ * Assign schema column in model for validation data types
223
+ * @param {Object<NumberConstructor | StringConstructor | DateConstructor>} schema types (String Number and Date)
224
+ * @example
225
+ * class User extends Model {
226
+ * constructor() {
227
+ * this.useValidationSchema()
228
+ * }
229
+ * }
230
+ * @return {this} this
231
+ */
232
+ protected useValidateSchema(schema?: null | Record<string, NumberConstructor | StringConstructor | DateConstructor>): this;
225
233
  /**
226
234
  * Assign hook function when execute returned results to callback function
227
235
  * @param {Array<Function>} arrayFunctions functions for callback result
@@ -1016,7 +1024,7 @@ declare class Model extends AbstractModel {
1016
1024
  private _handleRelations;
1017
1025
  private _handleRelationsQuery;
1018
1026
  private _validateMethod;
1019
- private _tryToCreateTable;
1027
+ private _checkSchemaOrNextError;
1020
1028
  private _initialModel;
1021
1029
  }
1022
1030
  export { Model };
@@ -73,7 +73,7 @@ class Model extends AbstractModel_1.AbstractModel {
73
73
  * import { Blueprint } from 'tspace-mysql'
74
74
  * class User extends Model {
75
75
  * constructor() {
76
- * this.useCreateTableIfNotExists ({
76
+ * this.useSchema ({
77
77
  * id : new Blueprint().int().notNull().primary().autoIncrement(),
78
78
  * uuid : new Blueprint().varchar(50).null(),
79
79
  * email : new Blueprint().varchar(50).null(),
@@ -85,8 +85,8 @@ class Model extends AbstractModel_1.AbstractModel {
85
85
  * }
86
86
  * @return {this} this
87
87
  */
88
- useCreateTableIfNotExists(schema) {
89
- this.$state.set('CREATE_TABLE', schema);
88
+ useSchema(schema) {
89
+ this.$state.set('SCHEMA_TABLE', schema);
90
90
  return this;
91
91
  }
92
92
  /**
@@ -301,18 +301,31 @@ class Model extends AbstractModel_1.AbstractModel {
301
301
  * @example
302
302
  * class User extends Model {
303
303
  * constructor() {
304
- * this.useValidationSchema({
305
- * id : Number,
306
- * email : String,
307
- * name : String,
308
- * date : Date
309
- * })
304
+ * this.useValidationSchema()
310
305
  * }
311
306
  * }
312
307
  * @return {this} this
313
308
  */
314
309
  useValidationSchema(schema) {
315
- this.$state.set('SCHEMA', schema);
310
+ this.$state.set('VALIDATE_SCHEMA', true);
311
+ this.$state.set('VALIDATE_SCHEMA_DEFINED', schema);
312
+ return this;
313
+ }
314
+ /**
315
+ *
316
+ * Assign schema column in model for validation data types
317
+ * @param {Object<NumberConstructor | StringConstructor | DateConstructor>} schema types (String Number and Date)
318
+ * @example
319
+ * class User extends Model {
320
+ * constructor() {
321
+ * this.useValidationSchema()
322
+ * }
323
+ * }
324
+ * @return {this} this
325
+ */
326
+ useValidateSchema(schema) {
327
+ this.$state.set('VALIDATE_SCHEMA', true);
328
+ this.$state.set('VALIDATE_SCHEMA_DEFINED', schema);
316
329
  return this;
317
330
  }
318
331
  /**
@@ -340,8 +353,8 @@ class Model extends AbstractModel_1.AbstractModel {
340
353
  */
341
354
  exceptColumns() {
342
355
  return __awaiter(this, void 0, void 0, function* () {
343
- if (this.$state.get('SCHEMA')) {
344
- const columns = Object.keys(this.$state.get('SCHEMA'));
356
+ if (this.$state.get('SCHEMA_TABLE')) {
357
+ const columns = Object.keys(this.$state.get('SCHEMA_TABLE'));
345
358
  const removeExcept = columns.filter((column) => {
346
359
  const excepts = this.$state.get('EXCEPT');
347
360
  return excepts.every((except) => except !== column);
@@ -437,7 +450,7 @@ class Model extends AbstractModel_1.AbstractModel {
437
450
  return result;
438
451
  }
439
452
  catch (e) {
440
- yield this._tryToCreateTable(e);
453
+ yield this._checkSchemaOrNextError(e);
441
454
  return yield this.queryStatement(sql);
442
455
  }
443
456
  });
@@ -465,7 +478,7 @@ class Model extends AbstractModel_1.AbstractModel {
465
478
  return result;
466
479
  }
467
480
  catch (e) {
468
- yield this._tryToCreateTable(e);
481
+ yield this._checkSchemaOrNextError(e);
469
482
  return yield this.actionStatement({
470
483
  sql,
471
484
  returnId
@@ -1707,44 +1720,7 @@ class Model extends AbstractModel_1.AbstractModel {
1707
1720
  `${this.$constants('FROM')}`,
1708
1721
  `\`${this.$state.get('TABLE_NAME').replace(/\`/g, '')}\``
1709
1722
  ].join(' ');
1710
- const raw = yield this.queryStatement(sql);
1711
- const schemas = raw.map((r) => {
1712
- let schema = { [r.Field]: String };
1713
- const numberLists = [
1714
- 'tinyint',
1715
- 'smallint',
1716
- 'mediumint',
1717
- 'int',
1718
- 'bigint',
1719
- 'float',
1720
- 'double',
1721
- 'decimal',
1722
- 'real',
1723
- 'bit',
1724
- 'boolean',
1725
- 'serial'
1726
- ];
1727
- const dateAndTimeLists = [
1728
- 'date',
1729
- 'datetime',
1730
- 'time',
1731
- 'timestamp',
1732
- 'year'
1733
- ];
1734
- if (numberLists.includes(r.Type)) {
1735
- schema = {
1736
- [r.Field]: Number
1737
- };
1738
- }
1739
- if (dateAndTimeLists.includes(r.Type)) {
1740
- schema = {
1741
- [r.Field]: Date
1742
- };
1743
- }
1744
- return schema;
1745
- });
1746
- const result = Object.assign({}, ...schemas);
1747
- return result;
1723
+ return yield this.queryStatement(sql);
1748
1724
  });
1749
1725
  }
1750
1726
  /**
@@ -1989,27 +1965,37 @@ class Model extends AbstractModel_1.AbstractModel {
1989
1965
  return result;
1990
1966
  }
1991
1967
  _validateSchema(results) {
1992
- const schema = this.$state.get('SCHEMA');
1993
- if (schema == null)
1994
- return;
1995
1968
  if (!results.length)
1996
1969
  return;
1970
+ const validateSchema = Boolean(this.$state.get('VALIDATE_SCHEMA'));
1971
+ if (!validateSchema)
1972
+ return;
1973
+ const schemaTable = this.$state.get('SCHEMA_TABLE');
1974
+ const schemaTableDefined = this.$state.get('VALIDATE_SCHEMA_DEFINED');
1975
+ this._assertError(schemaTableDefined == null && schemaTable == null, "Can't validate schema withouted schema");
1976
+ const schema = schemaTableDefined !== null && schemaTableDefined !== void 0 ? schemaTableDefined : Object.keys(schemaTable).reduce((acc, key) => {
1977
+ acc[key] = schemaTable[key].valueType;
1978
+ return acc;
1979
+ }, {});
1980
+ if (schema == null)
1981
+ return;
1997
1982
  const typeOf = (data) => Object.prototype.toString.apply(data).slice(8, -1).toLocaleLowerCase();
1998
1983
  const regexDate = /[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/;
1999
1984
  const regexDateTime = /[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1]) (2[0-3]|[01][0-9]):[0-5][0-9]/;
2000
- const selectedAll = this.$state.get('SELECT').replace('SELECT', '').trim() === '*';
1985
+ const select = this.$state.get('SELECT');
1986
+ const selectedAll = select.replace('SELECT', '').trim() === '*';
2001
1987
  for (const result of results) {
2002
1988
  const schemaKeys = Object.keys(schema);
2003
1989
  const resultKeys = Object.keys(result);
2004
1990
  if (schemaKeys.some(s => !resultKeys.includes(s)) && selectedAll) {
2005
1991
  const columns = schemaKeys.filter(x => !resultKeys.includes(x));
2006
- this._assertError(`Not found this column [ ${columns.join(', ')} ] in result`);
1992
+ this._assertError(`Not found this column "${columns.join(', ')}" in result`);
2007
1993
  }
2008
1994
  for (const column in result) {
2009
1995
  const s = schema[column];
2010
1996
  if (s == null && selectedAll) {
2011
1997
  if (!schemaKeys.every(s => resultKeys.includes(s))) {
2012
- this._assertError(`Not found this column [ ${column} ] in result`);
1998
+ this._assertError(`Not found this column "${column}" in result`);
2013
1999
  }
2014
2000
  continue;
2015
2001
  }
@@ -2018,13 +2004,13 @@ class Model extends AbstractModel_1.AbstractModel {
2018
2004
  if (regexDate.test(result[column]) || regexDateTime.test(result[column])) {
2019
2005
  if (typeOf(new Date(result[column])) === typeOf(new s()))
2020
2006
  continue;
2021
- this._assertError(`This column [ ${column} ] is invalid schema field type`);
2007
+ this._assertError(`This column "${column}" is invalid schema field type`);
2022
2008
  }
2023
2009
  if (result[column] == null)
2024
2010
  continue;
2025
2011
  if (typeOf(result[column]) === typeOf(new s()))
2026
2012
  continue;
2027
- this._assertError(`This column [ ${column} ] is invalid schema field type`);
2013
+ this._assertError(`This column "${column}" is invalid schema field type`);
2028
2014
  }
2029
2015
  }
2030
2016
  return;
@@ -2845,23 +2831,48 @@ class Model extends AbstractModel_1.AbstractModel {
2845
2831
  }
2846
2832
  }
2847
2833
  }
2848
- _tryToCreateTable(e) {
2849
- var _a;
2834
+ _checkSchemaOrNextError(e) {
2835
+ var _a, _b, _c, _d, _e;
2850
2836
  return __awaiter(this, void 0, void 0, function* () {
2851
- const createTable = this.$state.get('CREATE_TABLE');
2852
- if (createTable == null)
2853
- throw e;
2854
- const errorMessage = (_a = e === null || e === void 0 ? void 0 : e.message) !== null && _a !== void 0 ? _a : '';
2855
- const errorWhenTableIsNotExists = "doesn't exist";
2856
- if (!errorMessage.toLocaleLowerCase().includes(errorWhenTableIsNotExists))
2857
- throw e;
2858
- if (this.$state.get('QUERIES') > 3)
2859
- throw e;
2860
2837
  try {
2838
+ if (this.$state.get('QUERIES') > 3)
2839
+ throw e;
2840
+ const schemaTable = this.$state.get('SCHEMA_TABLE');
2841
+ if (schemaTable == null)
2842
+ throw e;
2843
+ const errorMessage = (_a = e === null || e === void 0 ? void 0 : e.message) !== null && _a !== void 0 ? _a : '';
2844
+ if (errorMessage.toLocaleLowerCase().includes('unknown column')) {
2845
+ const pattern = /'([^']+)'/;
2846
+ const column = errorMessage.match(pattern)
2847
+ ? String(errorMessage.match(pattern)[0]).replace(/'/g, '').split('.').pop()
2848
+ : null;
2849
+ if (column == null)
2850
+ throw e;
2851
+ const type = (_c = (_b = schemaTable[column]) === null || _b === void 0 ? void 0 : _b.type) !== null && _c !== void 0 ? _c : null;
2852
+ const attributes = (_e = (_d = schemaTable[column]) === null || _d === void 0 ? void 0 : _d.attributes) !== null && _e !== void 0 ? _e : null;
2853
+ if (type == null || attributes == null)
2854
+ throw e;
2855
+ const entries = Object.entries(schemaTable);
2856
+ const indexWithColumn = entries.findIndex(([key]) => key === column);
2857
+ const findAfterIndex = indexWithColumn ? entries[indexWithColumn - 1][0] : null;
2858
+ if (findAfterIndex == null)
2859
+ throw e;
2860
+ const sql = [
2861
+ `${this.$constants('ALTER_TABLE')}`,
2862
+ `${this.$state.get('TABLE_NAME')}`,
2863
+ `${this.$constants('ADD')}`,
2864
+ `\`${column}\` ${type} ${attributes.join(' ')}`,
2865
+ `${this.$constants('AFTER')} \`${findAfterIndex !== null && findAfterIndex !== void 0 ? findAfterIndex : ''}\``
2866
+ ].join(' ');
2867
+ yield this.queryStatement(sql);
2868
+ return;
2869
+ }
2870
+ if (!errorMessage.toLocaleLowerCase().includes("doesn't exist"))
2871
+ throw e;
2861
2872
  const tableName = this.$state.get('TABLE_NAME');
2862
- yield new Schema_1.Schema()
2863
- .debug(this.$state.get('DEBUG'))
2864
- .createTable(tableName, createTable);
2873
+ const sql = new Schema_1.Schema().createTable(tableName, schemaTable);
2874
+ yield this.queryStatement(sql);
2875
+ return;
2865
2876
  }
2866
2877
  catch (e) {
2867
2878
  throw e;
@@ -1,7 +1,7 @@
1
1
  import { Builder } from "./Builder";
2
2
  declare class Schema extends Builder {
3
3
  table: (table: string, schemas: Record<string, any>) => Promise<void>;
4
- createTable: (table: string, schemas: Record<string, any>) => Promise<any>;
4
+ createTable: (table: string, schemas: Record<string, any>) => string;
5
5
  }
6
6
  export { Schema };
7
7
  export default Schema;
@@ -20,10 +20,10 @@ class Schema extends Builder_1.Builder {
20
20
  let columns = [];
21
21
  for (const key in schemas) {
22
22
  const data = schemas[key];
23
- const { type, attrbuites } = data;
23
+ const { type, attributes } = data;
24
24
  columns = [
25
25
  ...columns,
26
- `${key} ${type} ${attrbuites === null || attrbuites === void 0 ? void 0 : attrbuites.join(' ')}`
26
+ `${key} ${type} ${attributes === null || attributes === void 0 ? void 0 : attributes.join(' ')}`
27
27
  ];
28
28
  }
29
29
  const sql = [
@@ -39,14 +39,14 @@ class Schema extends Builder_1.Builder {
39
39
  console.log((_a = err.message) === null || _a === void 0 ? void 0 : _a.replace(/ER_TABLE_EXISTS_ERROR:/g, ""));
40
40
  }
41
41
  });
42
- this.createTable = (table, schemas) => __awaiter(this, void 0, void 0, function* () {
42
+ this.createTable = (table, schemas) => {
43
43
  let columns = [];
44
44
  for (const key in schemas) {
45
45
  const data = schemas[key];
46
- const { type, attrbuites } = data;
46
+ const { type, attributes } = data;
47
47
  columns = [
48
48
  ...columns,
49
- `${key} ${type} ${attrbuites === null || attrbuites === void 0 ? void 0 : attrbuites.join(' ')}`
49
+ `${key} ${type} ${attributes === null || attributes === void 0 ? void 0 : attributes.join(' ')}`
50
50
  ];
51
51
  }
52
52
  const sql = [
@@ -54,8 +54,8 @@ class Schema extends Builder_1.Builder {
54
54
  `${table} (${columns === null || columns === void 0 ? void 0 : columns.join(', ')})`,
55
55
  `ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8`
56
56
  ].join(' ');
57
- return yield this.rawQuery(sql);
58
- });
57
+ return sql;
58
+ };
59
59
  }
60
60
  }
61
61
  exports.Schema = Schema;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tspace-mysql",
3
- "version": "1.3.8",
3
+ "version": "1.3.9",
4
4
  "description": "mysql query builder object relational mapping",
5
5
  "main": "dist/lib/index.js",
6
6
  "types": "dist/lib/index.d.ts",