tspace-mysql 1.5.0 → 1.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +1856 -701
  2. package/build/cli/dump/db.js +3 -2
  3. package/build/cli/generate/make.js +17 -15
  4. package/build/cli/generate/modelDecorator.d.ts +1 -1
  5. package/build/cli/generate/modelDecorator.js +2 -3
  6. package/build/cli/index.js +45 -27
  7. package/build/cli/migrate/make.d.ts +1 -1
  8. package/build/cli/migrate/make.js +2 -2
  9. package/build/cli/migrations/make-db.d.ts +4 -0
  10. package/build/cli/migrations/make-db.js +58 -0
  11. package/build/cli/migrations/make.d.ts +2 -0
  12. package/build/cli/migrations/make.js +201 -0
  13. package/build/lib/Interface.d.ts +24 -5
  14. package/build/lib/connection/index.d.ts +5 -1
  15. package/build/lib/connection/index.js +65 -8
  16. package/build/lib/connection/options.js +2 -2
  17. package/build/lib/constants/index.js +13 -3
  18. package/build/lib/{tspace → core}/Abstracts/AbstractBuilder.d.ts +1 -1
  19. package/build/lib/{tspace → core}/Abstracts/AbstractModel.d.ts +15 -13
  20. package/build/lib/{tspace → core}/Blueprint.d.ts +14 -3
  21. package/build/lib/{tspace → core}/Blueprint.js +30 -4
  22. package/build/lib/{tspace → core}/Builder.d.ts +140 -44
  23. package/build/lib/{tspace → core}/Builder.js +772 -459
  24. package/build/lib/{tspace → core}/DB.d.ts +20 -4
  25. package/build/lib/{tspace → core}/DB.js +73 -39
  26. package/build/lib/{tspace → core}/Decorator.js +2 -2
  27. package/build/lib/{tspace → core/Handlers}/Logger.d.ts +3 -3
  28. package/build/lib/{tspace → core/Handlers}/Logger.js +4 -4
  29. package/build/lib/{tspace → core}/Handlers/Proxy.js +2 -2
  30. package/build/lib/{tspace → core}/Handlers/Relation.d.ts +2 -4
  31. package/build/lib/{tspace → core}/Handlers/Relation.js +69 -48
  32. package/build/lib/{tspace → core}/Handlers/State.d.ts +1 -1
  33. package/build/lib/{tspace → core}/Handlers/State.js +3 -3
  34. package/build/lib/{tspace → core}/Model.d.ts +358 -133
  35. package/build/lib/{tspace → core}/Model.js +1316 -558
  36. package/build/lib/core/Schema.d.ts +137 -0
  37. package/build/lib/{tspace → core}/Schema.js +147 -52
  38. package/build/lib/core/Type.d.ts +6 -0
  39. package/build/lib/core/Type.js +2 -0
  40. package/build/lib/{tspace → core}/index.d.ts +2 -1
  41. package/build/lib/{tspace → core}/index.js +3 -2
  42. package/build/lib/index.d.ts +2 -2
  43. package/build/lib/index.js +2 -2
  44. package/build/lib/utils/index.d.ts +1 -0
  45. package/build/lib/utils/index.js +17 -7
  46. package/package.json +6 -4
  47. package/build/lib/tspace/Schema.d.ts +0 -70
  48. /package/build/lib/{tspace → core}/Abstracts/AbstractBuilder.js +0 -0
  49. /package/build/lib/{tspace → core}/Abstracts/AbstractDB.d.ts +0 -0
  50. /package/build/lib/{tspace → core}/Abstracts/AbstractDB.js +0 -0
  51. /package/build/lib/{tspace → core}/Abstracts/AbstractModel.js +0 -0
  52. /package/build/lib/{tspace → core}/Decorator.d.ts +0 -0
  53. /package/build/lib/{tspace → core}/Handlers/Proxy.d.ts +0 -0
@@ -0,0 +1,137 @@
1
+ import { Builder } from "./Builder";
2
+ declare class Schema extends Builder {
3
+ table: (table: string, schemas: Record<string, any>) => Promise<void>;
4
+ createTable: (table: string, schemas: Record<string, any>) => string;
5
+ /**
6
+ *
7
+ * The 'Sync' method is used to check for create or update table or columns with your schema in your model.
8
+ *
9
+ * The schema can define with method 'useSchema'
10
+ * @param {string} pathFolders directory to models
11
+ * @property {boolean} options.force - forec always check all columns if not exists will be created
12
+ * @property {boolean} options.log - show log execution with sql statements
13
+ * @property {boolean} options.foreign - check when has a foreign keys will be created
14
+ * @property {boolean} options.changed - check when column is changed attribute will be change attribute
15
+ * @return {Promise<void>}
16
+ * @example
17
+ *
18
+ * - node_modules
19
+ * - app
20
+ * - Models
21
+ * - User.ts
22
+ * - Post.ts
23
+ *
24
+ * // file User.ts
25
+ * class User extends Model {
26
+ * constructor(){
27
+ * super()
28
+ * this.hasMany({ name : 'posts' , model : Post })
29
+ * this.useSchema ({
30
+ * id : new Blueprint().int().notNull().primary().autoIncrement(),
31
+ * uuid : new Blueprint().varchar(50).null(),
32
+ * email : new Blueprint().int().notNull().unique(),
33
+ * name : new Blueprint().varchar(255).null(),
34
+ * created_at : new Blueprint().timestamp().null(),
35
+ * updated_at : new Blueprint().timestamp().null(),
36
+ * deleted_at : new Blueprint().timestamp().null()
37
+ * })
38
+ * }
39
+ * }
40
+ *
41
+ * // file Post.ts
42
+ * class Post extends Model {
43
+ * constructor(){
44
+ * super()
45
+ * this.hasMany({ name : 'comments' , model : Comment })
46
+ * this.belongsTo({ name : 'user' , model : User })
47
+ * this.useSchema ({
48
+ * id : new Blueprint().int().notNull().primary().autoIncrement(),
49
+ * uuid : new Blueprint().varchar(50).null(),
50
+ * user_id : new Blueprint().int().notNull().foreign({ references : 'id' , on : User , onDelete : 'CASCADE' , onUpdate : 'CASCADE' }),
51
+ * title : new Blueprint().varchar(255).null(),
52
+ * created_at : new Blueprint().timestamp().null(),
53
+ * updated_at : new Blueprint().timestamp().null(),
54
+ * deleted_at : new Blueprint().timestamp().null()
55
+ * })
56
+ * }
57
+ * }
58
+ *
59
+ *
60
+ * await new Schema().sync(`app/Models` , { force : true , log = true, foreign = true , changed = true })
61
+ */
62
+ sync(pathFolders: string, { force, log, foreign, changed }?: {
63
+ force?: boolean | undefined;
64
+ log?: boolean | undefined;
65
+ foreign?: boolean | undefined;
66
+ changed?: boolean | undefined;
67
+ }): Promise<void>;
68
+ /**
69
+ *
70
+ * The 'Sync' method is used to check for create or update table or columns with your schema in your model.
71
+ *
72
+ * The schema can define with method 'useSchema'
73
+ * @param {string} pathFolders directory to models
74
+ * @type {object} options
75
+ * @property {boolean} options.force - forec always check all columns if not exists will be created
76
+ * @property {boolean} options.log - show log execution with sql statements
77
+ * @property {boolean} options.foreign - check when has a foreign keys will be created
78
+ * @property {boolean} options.changed - check when column is changed attribute will be change attribute
79
+ * @return {Promise<void>}
80
+ * @example
81
+ *
82
+ * - node_modules
83
+ * - app
84
+ * - Models
85
+ * - User.ts
86
+ * - Post.ts
87
+ *
88
+ * // file User.ts
89
+ * class User extends Model {
90
+ * constructor(){
91
+ * super()
92
+ * this.hasMany({ name : 'posts' , model : Post })
93
+ * this.useSchema ({
94
+ * id : new Blueprint().int().notNull().primary().autoIncrement(),
95
+ * uuid : new Blueprint().varchar(50).null(),
96
+ * email : new Blueprint().int().notNull().unique(),
97
+ * name : new Blueprint().varchar(255).null(),
98
+ * created_at : new Blueprint().timestamp().null(),
99
+ * updated_at : new Blueprint().timestamp().null(),
100
+ * deleted_at : new Blueprint().timestamp().null()
101
+ * })
102
+ * }
103
+ * }
104
+ *
105
+ * // file Post.ts
106
+ * class Post extends Model {
107
+ * constructor(){
108
+ * super()
109
+ * this.hasMany({ name : 'comments' , model : Comment })
110
+ * this.belongsTo({ name : 'user' , model : User })
111
+ * this.useSchema ({
112
+ * id : new Blueprint().int().notNull().primary().autoIncrement(),
113
+ * uuid : new Blueprint().varchar(50).null(),
114
+ * user_id : new Blueprint().int().notNull().foreign({ references : 'id' , on : User , onDelete : 'CASCADE' , onUpdate : 'CASCADE' }),
115
+ * title : new Blueprint().varchar(255).null(),
116
+ * created_at : new Blueprint().timestamp().null(),
117
+ * updated_at : new Blueprint().timestamp().null(),
118
+ * deleted_at : new Blueprint().timestamp().null()
119
+ * })
120
+ * }
121
+ * }
122
+ *
123
+ *
124
+ * await Schema.sync(`app/Models` , { force : true })
125
+ */
126
+ static sync(pathFolders: string, { force, log, foreign, changed }?: {
127
+ force?: boolean | undefined;
128
+ log?: boolean | undefined;
129
+ foreign?: boolean | undefined;
130
+ changed?: boolean | undefined;
131
+ }): Promise<void>;
132
+ private _import;
133
+ private _syncExecute;
134
+ private _syncForeignKey;
135
+ }
136
+ export { Schema };
137
+ export default Schema;
@@ -77,23 +77,100 @@ class Schema extends Builder_1.Builder {
77
77
  `${key} ${type} ${attributes === null || attributes === void 0 ? void 0 : attributes.join(' ')}`
78
78
  ];
79
79
  }
80
- const sql = [
80
+ return [
81
81
  `${this.$constants('CREATE_TABLE_NOT_EXISTS')}`,
82
- `${table} (${columns === null || columns === void 0 ? void 0 : columns.join(', ')})`,
82
+ `${table} (${columns.join(', ')})`,
83
83
  `${this.$constants('ENGINE')}`
84
84
  ].join(' ');
85
- return sql;
86
85
  };
87
86
  }
87
+ /**
88
+ *
89
+ * The 'Sync' method is used to check for create or update table or columns with your schema in your model.
90
+ *
91
+ * The schema can define with method 'useSchema'
92
+ * @param {string} pathFolders directory to models
93
+ * @property {boolean} options.force - forec always check all columns if not exists will be created
94
+ * @property {boolean} options.log - show log execution with sql statements
95
+ * @property {boolean} options.foreign - check when has a foreign keys will be created
96
+ * @property {boolean} options.changed - check when column is changed attribute will be change attribute
97
+ * @return {Promise<void>}
98
+ * @example
99
+ *
100
+ * - node_modules
101
+ * - app
102
+ * - Models
103
+ * - User.ts
104
+ * - Post.ts
105
+ *
106
+ * // file User.ts
107
+ * class User extends Model {
108
+ * constructor(){
109
+ * super()
110
+ * this.hasMany({ name : 'posts' , model : Post })
111
+ * this.useSchema ({
112
+ * id : new Blueprint().int().notNull().primary().autoIncrement(),
113
+ * uuid : new Blueprint().varchar(50).null(),
114
+ * email : new Blueprint().int().notNull().unique(),
115
+ * name : new Blueprint().varchar(255).null(),
116
+ * created_at : new Blueprint().timestamp().null(),
117
+ * updated_at : new Blueprint().timestamp().null(),
118
+ * deleted_at : new Blueprint().timestamp().null()
119
+ * })
120
+ * }
121
+ * }
122
+ *
123
+ * // file Post.ts
124
+ * class Post extends Model {
125
+ * constructor(){
126
+ * super()
127
+ * this.hasMany({ name : 'comments' , model : Comment })
128
+ * this.belongsTo({ name : 'user' , model : User })
129
+ * this.useSchema ({
130
+ * id : new Blueprint().int().notNull().primary().autoIncrement(),
131
+ * uuid : new Blueprint().varchar(50).null(),
132
+ * user_id : new Blueprint().int().notNull().foreign({ references : 'id' , on : User , onDelete : 'CASCADE' , onUpdate : 'CASCADE' }),
133
+ * title : new Blueprint().varchar(255).null(),
134
+ * created_at : new Blueprint().timestamp().null(),
135
+ * updated_at : new Blueprint().timestamp().null(),
136
+ * deleted_at : new Blueprint().timestamp().null()
137
+ * })
138
+ * }
139
+ * }
140
+ *
141
+ *
142
+ * await new Schema().sync(`app/Models` , { force : true , log = true, foreign = true , changed = true })
143
+ */
144
+ sync(pathFolders_1) {
145
+ return __awaiter(this, arguments, void 0, function* (pathFolders, { force = false, log = false, foreign = false, changed = false } = {}) {
146
+ const directories = fs_1.default.readdirSync(pathFolders, { withFileTypes: true });
147
+ const files = (yield Promise.all(directories.map((directory) => {
148
+ const newDir = path_1.default.resolve(String(pathFolders), directory.name);
149
+ if (directory.isDirectory() && directory.name.toLocaleLowerCase().includes('migrations'))
150
+ return null;
151
+ return directory.isDirectory() ? Schema.sync(newDir, { force, log, changed }) : newDir;
152
+ })));
153
+ const pathModels = [].concat(...files).filter(d => d != null || d === '');
154
+ yield new Promise(r => setTimeout(r, 1200));
155
+ const models = yield Promise.all(pathModels.map((pathModel) => this._import(pathModel)).filter(d => d != null));
156
+ if (!models.length)
157
+ return;
158
+ yield this._syncExecute({ models, force, log, foreign, changed });
159
+ return;
160
+ });
161
+ }
88
162
  /**
89
163
  *
90
164
  * The 'Sync' method is used to check for create or update table or columns with your schema in your model.
91
165
  *
92
166
  * The schema can define with method 'useSchema'
93
- * @param {string} pathFolders directory to models
167
+ * @param {string} pathFolders directory to models
168
+ * @type {object} options
94
169
  * @property {boolean} options.force - forec always check all columns if not exists will be created
95
170
  * @property {boolean} options.log - show log execution with sql statements
96
- * @property {boolean} options.delay - wait for execution
171
+ * @property {boolean} options.foreign - check when has a foreign keys will be created
172
+ * @property {boolean} options.changed - check when column is changed attribute will be change attribute
173
+ * @return {Promise<void>}
97
174
  * @example
98
175
  *
99
176
  * - node_modules
@@ -128,7 +205,7 @@ class Schema extends Builder_1.Builder {
128
205
  * this.useSchema ({
129
206
  * id : new Blueprint().int().notNull().primary().autoIncrement(),
130
207
  * uuid : new Blueprint().varchar(50).null(),
131
- * user_id : new Blueprint().int().notNull().foreign({ references : 'id' , on : User , onDelete : 'CASCADE' , onUpdate : 'CASCADE' }),,
208
+ * user_id : new Blueprint().int().notNull().foreign({ references : 'id' , on : User , onDelete : 'CASCADE' , onUpdate : 'CASCADE' }),
132
209
  * title : new Blueprint().varchar(255).null(),
133
210
  * created_at : new Blueprint().timestamp().null(),
134
211
  * updated_at : new Blueprint().timestamp().null(),
@@ -137,27 +214,15 @@ class Schema extends Builder_1.Builder {
137
214
  * }
138
215
  * }
139
216
  *
217
+ *
140
218
  * await Schema.sync(`app/Models` , { force : true })
141
219
  */
142
- static sync(pathFolders, { force = false, log = false, foreign = false, delay = 1500 } = {}) {
143
- return __awaiter(this, void 0, void 0, function* () {
144
- const directories = fs_1.default.readdirSync(pathFolders, { withFileTypes: true });
145
- const files = (yield Promise.all(directories.map((directory) => {
146
- const newDir = path_1.default.resolve(String(pathFolders), directory.name);
147
- if (directory.isDirectory() && directory.name.toLocaleLowerCase().includes('migrations'))
148
- return null;
149
- return directory.isDirectory() ? Schema.sync(newDir, { force, log, delay }) : newDir;
150
- })));
151
- const pathModels = [].concat(...files).filter(d => d != null || d === '');
152
- yield new Promise(r => setTimeout(r, delay));
153
- const models = yield Promise.all(pathModels.map((pathModel) => Schema._import(pathModel)).filter(d => d != null));
154
- if (!models.length)
155
- return;
156
- yield Schema._syncExecute({ models, force, log, foreign });
157
- return;
220
+ static sync(pathFolders_1) {
221
+ return __awaiter(this, arguments, void 0, function* (pathFolders, { force = false, log = false, foreign = false, changed = false } = {}) {
222
+ return new this().sync(pathFolders, { force, log, foreign, changed });
158
223
  });
159
224
  }
160
- static _import(pathModel) {
225
+ _import(pathModel) {
161
226
  return __awaiter(this, void 0, void 0, function* () {
162
227
  try {
163
228
  const loadModel = yield Promise.resolve(`${pathModel}`).then(s => __importStar(require(s))).catch(_ => { });
@@ -170,10 +235,10 @@ class Schema extends Builder_1.Builder {
170
235
  }
171
236
  });
172
237
  }
173
- static _syncExecute({ models, force, log, foreign }) {
174
- var _a, _b, _c, _d;
175
- return __awaiter(this, void 0, void 0, function* () {
176
- const checkTables = yield new Builder_1.Builder().query('SHOW TABLES');
238
+ _syncExecute(_a) {
239
+ return __awaiter(this, arguments, void 0, function* ({ models, force, log, foreign, changed }) {
240
+ var _b, _c, _d, _e, _f, _g, _h, _j;
241
+ const checkTables = yield this.query(this.$constants('SHOW_TABLES'));
177
242
  const existsTables = checkTables.map((c) => Object.values(c)[0]);
178
243
  for (const model of models) {
179
244
  if (model == null)
@@ -183,8 +248,11 @@ class Schema extends Builder_1.Builder {
183
248
  continue;
184
249
  const checkTableIsExists = existsTables.some((table) => table === model.getTableName());
185
250
  if (!checkTableIsExists) {
186
- const sql = new Schema().createTable(`\`${model.getTableName()}\``, schemaModel);
187
- yield new Builder_1.Builder().debug(log).query(sql);
251
+ const sql = this.createTable(`\`${model.getTableName()}\``, schemaModel);
252
+ yield model.debug(log).query(sql);
253
+ const beforeCreatingTheTable = model['$state'].get('BEFORE_CREATING_TABLE');
254
+ if (beforeCreatingTheTable != null)
255
+ yield beforeCreatingTheTable();
188
256
  yield this._syncForeignKey({
189
257
  schemaModel,
190
258
  model,
@@ -204,6 +272,29 @@ class Schema extends Builder_1.Builder {
204
272
  const schemaTable = yield model.getSchema();
205
273
  const schemaTableKeys = schemaTable.map((k) => k.Field);
206
274
  const schemaModelKeys = Object.keys(schemaModel);
275
+ const wasChangedColumns = changed ? Object.entries(schemaModel).map(([key, value]) => {
276
+ const find = schemaTable.find(t => t.Field === key);
277
+ if (find == null)
278
+ return null;
279
+ const compare = String(find.Type).toLocaleLowerCase() !== String(value.type).toLocaleLowerCase();
280
+ return compare ? key : null;
281
+ }).filter(d => d != null) : [];
282
+ if (wasChangedColumns.length) {
283
+ for (const column of wasChangedColumns) {
284
+ if (column == null)
285
+ continue;
286
+ const type = (_c = (_b = schemaModel[column]) === null || _b === void 0 ? void 0 : _b.type) !== null && _c !== void 0 ? _c : null;
287
+ const attributes = (_e = (_d = schemaModel[column]) === null || _d === void 0 ? void 0 : _d.attributes) !== null && _e !== void 0 ? _e : null;
288
+ const sql = [
289
+ this.$constants('ALTER_TABLE'),
290
+ `\`${model.getTableName()}\``,
291
+ this.$constants('CHANGE'),
292
+ `\`${column}\``,
293
+ `\`${column}\` ${type} ${attributes.join(' ')}`,
294
+ ].join(' ');
295
+ yield this.debug(log).query(sql);
296
+ }
297
+ }
207
298
  const missingColumns = schemaModelKeys.filter(schemaModelKey => !schemaTableKeys.includes(schemaModelKey));
208
299
  if (!missingColumns.length)
209
300
  continue;
@@ -211,19 +302,19 @@ class Schema extends Builder_1.Builder {
211
302
  for (const column of missingColumns) {
212
303
  const indexWithColumn = entries.findIndex(([key]) => key === column);
213
304
  const findAfterIndex = indexWithColumn ? entries[indexWithColumn - 1][0] : null;
214
- const type = (_b = (_a = schemaModel[column]) === null || _a === void 0 ? void 0 : _a.type) !== null && _b !== void 0 ? _b : null;
215
- const attributes = (_d = (_c = schemaModel[column]) === null || _c === void 0 ? void 0 : _c.attributes) !== null && _d !== void 0 ? _d : null;
305
+ const type = (_g = (_f = schemaModel[column]) === null || _f === void 0 ? void 0 : _f.type) !== null && _g !== void 0 ? _g : null;
306
+ const attributes = (_j = (_h = schemaModel[column]) === null || _h === void 0 ? void 0 : _h.attributes) !== null && _j !== void 0 ? _j : null;
216
307
  if (findAfterIndex == null || type == null || attributes == null)
217
308
  continue;
218
309
  const sql = [
219
- 'ALTER TABLE',
310
+ this.$constants('ALTER_TABLE'),
220
311
  `\`${model.getTableName()}\``,
221
- 'ADD',
312
+ this.$constants('ADD'),
222
313
  `\`${column}\` ${type} ${attributes.join(' ')}`,
223
- 'AFTER',
314
+ this.$constants('AFTER'),
224
315
  `\`${findAfterIndex}\``
225
316
  ].join(' ');
226
- yield new Builder_1.Builder().debug(log).query(sql);
317
+ yield this.debug(log).query(sql);
227
318
  }
228
319
  yield this._syncForeignKey({
229
320
  schemaModel,
@@ -234,37 +325,41 @@ class Schema extends Builder_1.Builder {
234
325
  return;
235
326
  });
236
327
  }
237
- static _syncForeignKey({ schemaModel, model, log }) {
238
- var _a;
239
- return __awaiter(this, void 0, void 0, function* () {
328
+ _syncForeignKey(_a) {
329
+ return __awaiter(this, arguments, void 0, function* ({ schemaModel, model, log }) {
330
+ var _b;
240
331
  for (const key in schemaModel) {
241
- if (((_a = schemaModel[key]) === null || _a === void 0 ? void 0 : _a.foreignKey) == null)
332
+ if (((_b = schemaModel[key]) === null || _b === void 0 ? void 0 : _b.foreignKey) == null)
242
333
  continue;
243
334
  const foreign = schemaModel[key].foreignKey;
244
- const table = typeof foreign.on === "string" ? foreign.on : foreign.on.getTableName();
335
+ if (foreign.on == null)
336
+ continue;
337
+ const onReference = typeof foreign.on === "string" ? foreign.on : new foreign.on;
338
+ const table = typeof onReference === "string" ? onReference : onReference.getTableName();
339
+ const constraintName = `\`${model.getTableName()}(${key})_${table}(${foreign.references})\``;
245
340
  const sql = [
246
- "ALTER TABLE",
341
+ this.$constants("ALTER_TABLE"),
247
342
  `\`${model.getTableName()}\``,
248
- "ADD CONSTRAINT",
249
- `\`${model.getTableName()}(${key})_${table}(${foreign.references})\``,
250
- `FOREIGN KEY(\`${key}\`)`,
251
- `REFERENCES \`${table}\`(\`${foreign.references}\`)`,
252
- `ON DELETE ${foreign.onDelete} ON UPDATE ${foreign.onUpdate}`
343
+ this.$constants('ADD_CONSTRAINT'),
344
+ `${constraintName}`,
345
+ `${this.$constants('FOREIGN_KEY')}(\`${key}\`)`,
346
+ `${this.$constants('REFERENCES')} \`${table}\`(\`${foreign.references}\`)`,
347
+ `${this.$constants('ON_DELETE')} ${foreign.onDelete} ${this.$constants('ON_UPDATE')} ${foreign.onUpdate}`
253
348
  ].join(' ');
254
349
  try {
255
- yield new Builder_1.Builder().debug(log).query(sql);
350
+ yield this.debug(log).query(sql);
256
351
  }
257
352
  catch (e) {
258
- if (typeof foreign.on === "string")
353
+ if (typeof onReference === "string")
259
354
  continue;
260
355
  if (String(e.message).includes("Duplicate foreign key constraint"))
261
356
  continue;
262
- const schemaModelOn = yield foreign.on.getSchemaModel();
357
+ const schemaModelOn = yield onReference.getSchemaModel();
263
358
  if (!schemaModelOn)
264
359
  continue;
265
- const tableSql = new Schema().createTable(`\`${table}\``, schemaModelOn);
266
- yield new Builder_1.Builder().debug(log).query(tableSql).catch(e => console.log(e));
267
- yield new Builder_1.Builder().debug(log).query(sql).catch(e => console.log(e));
360
+ const tableSql = this.createTable(`\`${table}\``, schemaModelOn);
361
+ yield this.debug(log).query(tableSql).catch(e => console.log(e));
362
+ yield this.debug(log).query(sql).catch(e => console.log(e));
268
363
  continue;
269
364
  }
270
365
  }
@@ -0,0 +1,6 @@
1
+ export type SchemaType<TSchema, TSpecific = any> = {
2
+ [K in keyof TSchema]: K extends keyof TSpecific ? TSpecific[K] : any;
3
+ };
4
+ export type RelationType<T> = {
5
+ [K in keyof T]: T[K];
6
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -5,10 +5,11 @@ import Blueprint from './Blueprint';
5
5
  import Pool from '../connection';
6
6
  export { DB };
7
7
  export { Model };
8
- export { Schema };
9
8
  export { Blueprint };
10
9
  export { Pool };
11
10
  export * from './Decorator';
11
+ export * from './Schema';
12
+ export * from './Type';
12
13
  declare const _default: {
13
14
  DB: typeof DB;
14
15
  Model: typeof Model;
@@ -17,18 +17,19 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
17
17
  return (mod && mod.__esModule) ? mod : { "default": mod };
18
18
  };
19
19
  Object.defineProperty(exports, "__esModule", { value: true });
20
- exports.Pool = exports.Blueprint = exports.Schema = exports.Model = exports.DB = void 0;
20
+ exports.Pool = exports.Blueprint = exports.Model = exports.DB = void 0;
21
21
  const DB_1 = __importDefault(require("./DB"));
22
22
  exports.DB = DB_1.default;
23
23
  const Model_1 = __importDefault(require("./Model"));
24
24
  exports.Model = Model_1.default;
25
25
  const Schema_1 = __importDefault(require("./Schema"));
26
- exports.Schema = Schema_1.default;
27
26
  const Blueprint_1 = __importDefault(require("./Blueprint"));
28
27
  exports.Blueprint = Blueprint_1.default;
29
28
  const connection_1 = __importDefault(require("../connection"));
30
29
  exports.Pool = connection_1.default;
31
30
  __exportStar(require("./Decorator"), exports);
31
+ __exportStar(require("./Schema"), exports);
32
+ __exportStar(require("./Type"), exports);
32
33
  exports.default = {
33
34
  DB: DB_1.default,
34
35
  Model: Model_1.default,
@@ -3,6 +3,6 @@
3
3
  *
4
4
  * @module tspace-mysql
5
5
  */
6
- import * as tspace from './tspace';
7
- export * from './tspace';
6
+ import * as tspace from './core';
7
+ export * from './core';
8
8
  export default tspace;
@@ -31,6 +31,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
31
31
  *
32
32
  * @module tspace-mysql
33
33
  */
34
- const tspace = __importStar(require("./tspace"));
35
- __exportStar(require("./tspace"), exports);
34
+ const tspace = __importStar(require("./core"));
35
+ __exportStar(require("./core"), exports);
36
36
  exports.default = tspace;
@@ -7,6 +7,7 @@ declare const utils: {
7
7
  timestamp: (dateString?: string) => string;
8
8
  date: () => string;
9
9
  escape: (str: any) => any;
10
+ escapeActions: (str: any) => any;
10
11
  escapeXSS: (str: any) => any;
11
12
  isSubQuery: (subQuery: string) => boolean;
12
13
  generateUUID: () => string;
@@ -47,14 +47,25 @@ const date = () => {
47
47
  const escape = (str) => {
48
48
  if (typeof str !== 'string')
49
49
  return str;
50
- return str.replace(/[\0\b\t\n\r\x1a\'\\]/g, '');
50
+ if (str.includes('$RAW:'))
51
+ return str;
52
+ return str.replace(/[\0\b\t\n\r\x1a\'\\]/g, "\\'");
53
+ };
54
+ const escapeActions = (str) => {
55
+ if (typeof str !== 'string')
56
+ return str;
57
+ return str.replace(/[\0\b\r\x1a\'\\]/g, "\\'");
51
58
  };
52
59
  const escapeXSS = (str) => {
53
60
  if (typeof str !== 'string')
54
61
  return str;
55
62
  return str
56
- .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
57
- .replace(/on\w+="[^"]+"/g, '');
63
+ .replace(/[;\\]/gi, '')
64
+ .replace(/on\w+="[^"]+"/gi, '')
65
+ .replace(/\s+(onerror|onload)\s*=/gi, '')
66
+ .replace(/\s+alert*/gi, '')
67
+ .replace(/\([^)]*\) *=>/g, '')
68
+ .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '');
58
69
  };
59
70
  const isSubQuery = (subQuery) => {
60
71
  const checkIsSubQuery = (/\bSELECT\s+(?!\*)/i.test(subQuery));
@@ -140,11 +151,9 @@ const camelCase = (data) => {
140
151
  }
141
152
  };
142
153
  const consoleDebug = (debug) => {
143
- if (debug == null)
144
- return;
145
- if (typeof debug !== "string")
154
+ if (typeof debug !== "string" || debug == null)
146
155
  return;
147
- console.log(`\n\x1b[33m${debug === null || debug === void 0 ? void 0 : debug.replace(/(\r\n|\n|\r|\t)/gm, "").trim()};\x1b[0m`);
156
+ console.log(`\n\x1b[34mQUERY:\x1b[0m \x1b[33m${debug === null || debug === void 0 ? void 0 : debug.replace(/(\r\n|\n|\r|\t)/gm, "").trim()};\x1b[0m`);
148
157
  };
149
158
  const randomString = (length = 100) => {
150
159
  let str = '';
@@ -204,6 +213,7 @@ const utils = {
204
213
  timestamp,
205
214
  date,
206
215
  escape,
216
+ escapeActions,
207
217
  escapeXSS,
208
218
  isSubQuery,
209
219
  generateUUID,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tspace-mysql",
3
- "version": "1.5.0",
4
- "description": "mysql query builder object relational mapping",
3
+ "version": "1.5.2",
4
+ "description": "mysql query builder object relational mapping (ORM)",
5
5
  "main": "build/lib/index.js",
6
6
  "types": "build/lib/index.d.ts",
7
7
  "files": [
@@ -15,8 +15,8 @@
15
15
  "url": "https://github.com/thanathip41/tspace-mysql.git"
16
16
  },
17
17
  "keywords": [
18
- "tspace-mysql",
19
18
  "tspace",
19
+ "tspace-mysql",
20
20
  "mysql",
21
21
  "orm",
22
22
  "relations",
@@ -31,7 +31,8 @@
31
31
  "cli",
32
32
  "migrate",
33
33
  "backup",
34
- "blueprint"
34
+ "blueprint",
35
+ "type safety"
35
36
  ],
36
37
  "author": "Thanathip (https://github.com/thanathip41)",
37
38
  "license": "MIT",
@@ -54,6 +55,7 @@
54
55
  "devDependencies": {
55
56
  "@types/chai": "^4.3.11",
56
57
  "@types/chai-json-schema": "^1.4.9",
58
+ "@types/debug": "^4.1.12",
57
59
  "@types/mocha": "^10.0.6",
58
60
  "@types/mysql": "^2.15.19",
59
61
  "@types/pluralize": "^0.0.29",