tspace-mysql 1.3.9 → 1.4.0

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
@@ -3,7 +3,7 @@
3
3
  [![NPM version](https://img.shields.io/npm/v/tspace-mysql.svg)](https://www.npmjs.com)
4
4
  [![NPM downloads](https://img.shields.io/npm/dm/tspace-mysql.svg)](https://www.npmjs.com)
5
5
 
6
- Tspace-mysql is an ORM that can run in NodeJs and can be used with TypeScript.
6
+ tspace-mysql is an ORM that can run in NodeJs and can be used with TypeScript.
7
7
  Its always support the latest TypeScript and JavaScript features and provide additional features that help you to develop.
8
8
 
9
9
  ## Install
@@ -35,6 +35,7 @@ npm install tspace-mysql --save
35
35
  - [Make Migration](#make-migration)
36
36
  - [Migrate](#migrate)
37
37
  - [Query](#query)
38
+ - [Dump](#dump)
38
39
  - [Generate Models](#generate-models)
39
40
  - [Blueprint](#blueprint)
40
41
 
@@ -63,7 +64,7 @@ source db {
63
64
  port = 3306
64
65
  database = npm
65
66
  user = root
66
- password =
67
+ password = database
67
68
  connectionLimit = 10
68
69
  dateStrings = true
69
70
  connectTimeout = 60000
@@ -616,49 +617,54 @@ class Comment extends Model {
616
617
  }
617
618
  +--------------------------------------------------------------------------+
618
619
  // Deeply nested relations
619
- await new User().relations('posts')
620
- .relationQuery('posts', (query : Post) => {
621
- return query.relations('comments','user')
622
- .relationQuery('comments', (query : Comment) => {
623
- return query.relations('user','post')
624
- })
625
- .relationQuery('user', (query : User) => {
626
- return query.relations('posts').relationQuery('posts',(query : Post)=> {
627
- return query.relations('comments','user')
628
- // relation n, n, ...n
629
- })
620
+ await new User()
621
+ .relations('posts')
622
+ .relationQuery('posts', (query : Post) => {
623
+ return query.relations('comments','user')
624
+ .relationQuery('comments', (query : Comment) => {
625
+ return query.relations('user','post')
626
+ })
627
+ .relationQuery('user', (query : User) => {
628
+ return query.relations('posts').relationQuery('posts',(query : Post)=> {
629
+ return query.relations('comments','user')
630
+ // relation n, n, ...n
630
631
  })
631
632
  })
632
- .findMany()
633
+ })
634
+ .findMany()
633
635
 
634
636
  // Select some columns in nested relations
635
- await new User().relations('posts')
636
- .relationQuery('posts', (query : Post) => query.select('id','user_id','title'))
637
- .findMany()
637
+ await new User()
638
+ .relations('posts')
639
+ .relationQuery('posts', (query : Post) => query.select('id','user_id','title'))
640
+ .findMany()
638
641
 
639
642
  // Where some columns in nested relations
640
- await new User().relations('posts')
641
- .relationQuery('posts', (query : Post) => query.whereIn('id',[1,3,5]))
642
- .findMany()
643
+ await new User()
644
+ .relations('posts')
645
+ .relationQuery('posts', (query : Post) => query.whereIn('id',[1,3,5]))
646
+ .findMany()
643
647
 
644
648
  // Sort data in nested relations
645
- await new User().relations('posts')
646
- .relationQuery('posts', (query : Post) => query.latest('id'))
647
- .findMany()
649
+ await new User()
650
+ .relations('posts')
651
+ .relationQuery('posts', (query : Post) => query.latest('id'))
652
+ .findMany()
648
653
 
649
654
  // Limit data in nested relations
650
- await new User().relations('posts')
651
- .relationQuery('posts', (query : Post) => {
652
- return query
653
- .limit(1)
654
- .relations('comments')
655
- .relationQuery('comments', (query : Comment) => query.limit(1))
656
- })
657
- .findMany()
655
+ await new User()
656
+ .relations('posts')
657
+ .relationQuery('posts', (query : Post) => {
658
+ return query
659
+ .limit(1)
660
+ .relations('comments')
661
+ .relationQuery('comments', (query : Comment) => query.limit(1))
662
+ })
663
+ .findMany()
658
664
 
659
665
  ```
660
666
  ## Relation Exists
661
- Relationships can return only result is not isempty related with soft delete.
667
+ Relationships can return only result is not empty in relations.
662
668
  let's example a exists in relations :
663
669
  ```js
664
670
  +-------------+--------------+----------------------------+--------------------+
@@ -991,6 +997,14 @@ Command will be execute a query
991
997
  ```js
992
998
  tspace-mysql query "SELECT * FROM users"
993
999
 
1000
+ ```
1001
+ # Dump
1002
+ Command will be dump database or table into file
1003
+ ```js
1004
+ tspace-mysql dump:db --db=database --values
1005
+
1006
+ tspace-mysql dump:table --table=table --values
1007
+
994
1008
  ```
995
1009
 
996
1010
  # Generate Models
@@ -2,24 +2,37 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const lib_1 = require("../../lib");
4
4
  exports.default = (cmd) => {
5
- const { dir, cwd, fs, db } = cmd;
5
+ const { dir, cwd, fs, values, db } = cmd;
6
6
  if (dir) {
7
7
  try {
8
- fs.accessSync(cwd + `/${dir}`, fs.F_OK, {
8
+ fs.accessSync(`${cwd}/${dir}`, fs.F_OK, {
9
9
  recursive: true
10
10
  });
11
11
  }
12
12
  catch (e) {
13
- fs.mkdirSync(cwd + `/${dir}`, {
13
+ fs.mkdirSync(`${cwd}/${dir}`, {
14
14
  recursive: true
15
15
  });
16
16
  }
17
17
  }
18
- const directory = `${cwd}/${dir}/dump_${+new Date()}.sql`;
19
- new lib_1.DB().backupToFile({
20
- filePath: directory,
21
- database: db
22
- })
23
- .then(r => console.log('dump file successfully'))
24
- .catch(err => console.log(err));
18
+ if (values) {
19
+ const directory = `${cwd}/${dir}/dump-schema_${+new Date()}.sql`;
20
+ new lib_1.DB().backupSchemaToFile({
21
+ filePath: directory,
22
+ database: db
23
+ })
24
+ .then(r => console.log(`dump schema database "${db}" file successfully`))
25
+ .catch(err => console.log(err))
26
+ .finally(() => process.exit(0));
27
+ }
28
+ else {
29
+ const directory = `${cwd}/${dir}/dump_${+new Date()}.sql`;
30
+ new lib_1.DB().backupToFile({
31
+ filePath: directory,
32
+ database: db
33
+ })
34
+ .then(r => console.log(`dump database "${db}" file successfully`))
35
+ .catch(err => console.log(err))
36
+ .finally(() => process.exit(0));
37
+ }
25
38
  };
@@ -0,0 +1,4 @@
1
+ declare const _default: (cmd: {
2
+ [x: string]: any;
3
+ }) => void;
4
+ export default _default;
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const lib_1 = require("../../lib");
4
+ exports.default = (cmd) => {
5
+ const { dir, cwd, fs, values, table } = cmd;
6
+ if (dir) {
7
+ try {
8
+ fs.accessSync(`${cwd}/${dir}`, fs.F_OK, {
9
+ recursive: true
10
+ });
11
+ }
12
+ catch (e) {
13
+ fs.mkdirSync(`${cwd}/${dir}`, {
14
+ recursive: true
15
+ });
16
+ }
17
+ }
18
+ if (values) {
19
+ const directory = `${cwd}/${dir}/dump-schema_${+new Date()}.sql`;
20
+ new lib_1.DB().backupTableSchemaToFile({
21
+ filePath: directory,
22
+ table
23
+ })
24
+ .then(r => console.log(`dump table schema "${table}" file successfully`))
25
+ .catch(err => console.log(err))
26
+ .finally(() => process.exit(0));
27
+ }
28
+ else {
29
+ const directory = `${cwd}/${dir}/dump_${+new Date()}.sql`;
30
+ new lib_1.DB().backupTableToFile({
31
+ filePath: directory,
32
+ table
33
+ })
34
+ .then(r => console.log(`dump table "${table}" file successfully`))
35
+ .catch(err => console.log(err))
36
+ .finally(() => process.exit(0));
37
+ }
38
+ };
@@ -10,12 +10,12 @@ exports.default = (cmd) => {
10
10
  const { dir, cwd, type, fs, npm } = cmd;
11
11
  if (dir) {
12
12
  try {
13
- fs.accessSync(cwd + `/${dir}`, fs.F_OK, {
13
+ fs.accessSync(`${cwd}/${dir}`, fs.F_OK, {
14
14
  recursive: true
15
15
  });
16
16
  }
17
17
  catch (e) {
18
- fs.mkdirSync(cwd + `/${dir}`, {
18
+ fs.mkdirSync(`${cwd}/${dir}`, {
19
19
  recursive: true
20
20
  });
21
21
  }
@@ -27,7 +27,8 @@ exports.default = (cmd) => {
27
27
  }
28
28
  return str.join('');
29
29
  };
30
- new lib_1.DB().rawQuery('SHOW TABLES').then(tables => {
30
+ new lib_1.DB().rawQuery('SHOW TABLES')
31
+ .then(tables => {
31
32
  var _a;
32
33
  for (let i = 0; i < tables.length; i++) {
33
34
  const table = String((_a = Object.values(tables[i])) === null || _a === void 0 ? void 0 : _a.shift());
@@ -51,9 +52,11 @@ exports.default = (cmd) => {
51
52
  throw err;
52
53
  });
53
54
  console.log(`Model : '${model}' created successfully`);
54
- });
55
+ })
56
+ .catch(err => console.log(err));
55
57
  }
56
58
  console.log('\nGenerate Models has completed');
57
59
  })
58
- .catch(err => console.log(err));
60
+ .catch(err => console.log(err))
61
+ .finally(() => process.exit(0));
59
62
  };
@@ -5,7 +5,29 @@ const Model = (model, npm, schema) => {
5
5
  class ${model} extends Model {
6
6
  constructor(){
7
7
  super()
8
- ${schema}
8
+ /**
9
+ *
10
+ * @Configuration registry in your model
11
+ *
12
+ * this.useDebug()
13
+ * this.useTimestamp({
14
+ * createdAt : 'created_at',
15
+ * updatedAt : 'updated_at'
16
+ * }) // runing a timestamp when insert or update
17
+ * this.useSoftDelete('deletedAt') // => default target to colmun deleted_at
18
+ * this.usePattern('snake_case') // => default 'snake_case'
19
+ * this.useUUID('uuid') // => runing a uuid (universally unique identifier) when insert new data
20
+ * this.useRegistry() // => build-in functions registry
21
+ * this.useLoadRelationsInRegistry() // => auto generated results from relationship to results
22
+ * this.useBuiltInRelationFunctions() // => build-in functions relationships to results
23
+ */
24
+
25
+ /**
26
+ *
27
+ * @Schema table
28
+ *
29
+ */
30
+ ${schema}
9
31
  }
10
32
  }
11
33
  export { ${model} }
package/dist/cli/index.js CHANGED
@@ -3,7 +3,7 @@
3
3
  var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  return (mod && mod.__esModule) ? mod : { "default": mod };
5
5
  };
6
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
6
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;
7
7
  Object.defineProperty(exports, "__esModule", { value: true });
8
8
  const fs_1 = __importDefault(require("fs"));
9
9
  const make_1 = __importDefault(require("./models/make"));
@@ -12,6 +12,7 @@ const make_3 = __importDefault(require("./migrate/make"));
12
12
  const make_4 = __importDefault(require("./generate/make"));
13
13
  const query_1 = __importDefault(require("./query"));
14
14
  const db_1 = __importDefault(require("./dump/db"));
15
+ const db_2 = __importDefault(require("./dump/db"));
15
16
  const commands = {
16
17
  'query': query_1.default,
17
18
  'make:model': make_1.default,
@@ -19,7 +20,9 @@ const commands = {
19
20
  'make:migration': make_2.default,
20
21
  'migrate': make_3.default,
21
22
  'generate:models': make_4.default,
23
+ 'gen:models': make_4.default,
22
24
  'dump:db': db_1.default,
25
+ 'dump:table': db_2.default
23
26
  };
24
27
  try {
25
28
  const name = (_c = (_b = (_a = process.argv.slice(2)) === null || _a === void 0 ? void 0 : _a.find(data => {
@@ -33,11 +36,20 @@ try {
33
36
  const db = (_m = (_l = (_k = process.argv.slice(2)) === null || _k === void 0 ? void 0 : _k.find(data => {
34
37
  return data === null || data === void 0 ? void 0 : data.includes('--db=');
35
38
  })) === null || _l === void 0 ? void 0 : _l.replace('--db=', '')) !== null && _m !== void 0 ? _m : null;
36
- let type = (_q = (_p = (_o = process.argv.slice(2)) === null || _o === void 0 ? void 0 : _o.find(data => {
39
+ const table = (_q = (_p = (_o = process.argv.slice(2)) === null || _o === void 0 ? void 0 : _o.find(data => {
40
+ return data === null || data === void 0 ? void 0 : data.includes('--table=');
41
+ })) === null || _p === void 0 ? void 0 : _p.replace('--table=', '')) !== null && _q !== void 0 ? _q : null;
42
+ let type = ((_t = (_s = (_r = process.argv.slice(2)) === null || _r === void 0 ? void 0 : _r.find(data => {
37
43
  return data === null || data === void 0 ? void 0 : data.includes('--type=');
38
- })) === null || _p === void 0 ? void 0 : _p.replace('--type=', '.')) !== null && _q !== void 0 ? _q : '.ts';
44
+ })) === null || _s === void 0 ? void 0 : _s.replace('--type=', '.')) !== null && _t !== void 0 ? _t : '.ts');
39
45
  type = ['.js', '.ts'].includes(type) ? type : '.ts';
40
- const file = (_r = process.argv.slice(3)[0]) !== null && _r !== void 0 ? _r : '';
46
+ const file = (_u = process.argv.slice(3)[0]) !== null && _u !== void 0 ? _u : '';
47
+ const env = (_x = (_w = (_v = process.argv.slice(2)) === null || _v === void 0 ? void 0 : _v.find(data => {
48
+ return data === null || data === void 0 ? void 0 : data.includes('--env=');
49
+ })) === null || _w === void 0 ? void 0 : _w.replace('--env=', '')) !== null && _x !== void 0 ? _x : null;
50
+ const values = (_0 = (((_y = process.argv.slice(2)) === null || _y === void 0 ? void 0 : _y.includes('--values')) || ((_z = process.argv.slice(2)) === null || _z === void 0 ? void 0 : _z.includes('--v')))) !== null && _0 !== void 0 ? _0 : false;
51
+ if (env != null)
52
+ process.env.NODE_ENV = env;
41
53
  const cmd = {
42
54
  name,
43
55
  file,
@@ -48,6 +60,8 @@ try {
48
60
  fs: fs_1.default,
49
61
  sql,
50
62
  db,
63
+ table,
64
+ values,
51
65
  npm: 'tspace-mysql'
52
66
  };
53
67
  commands[process.argv[2]](cmd);
@@ -59,7 +73,9 @@ catch (err) {
59
73
  tspace-mysql migrate --dir=App/Models/Migrations --type=js
60
74
  tspace-mysql query "SELECT * FROM users"
61
75
  tspace-mysql generate:models --dir=app/Models
62
- tspace-mysql dump:db --dir=app/Models
76
+ tspace-mysql dump:db --db=database --dir=app/db
77
+ tspace-mysql dump:table --table=table --dir=app/table
63
78
  `);
64
79
  console.log(`Read more https://www.npmjs.com/package/tspace-mysql`);
80
+ process.exit(0);
65
81
  }
@@ -10,12 +10,12 @@ exports.default = (cmd) => {
10
10
  const { file, migrate, dir, type, cwd, fs, npm } = cmd;
11
11
  if (dir) {
12
12
  try {
13
- fs.accessSync(cwd + `/${dir}`, fs.F_OK, {
13
+ fs.accessSync(`${cwd}/${dir}`, fs.F_OK, {
14
14
  recursive: true
15
15
  });
16
16
  }
17
17
  catch (e) {
18
- fs.mkdirSync(cwd + `/${dir}`, {
18
+ fs.mkdirSync(`${cwd}/${dir}`, {
19
19
  recursive: true
20
20
  });
21
21
  }
@@ -3,5 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const lib_1 = require("../../lib");
4
4
  exports.default = (cmd) => {
5
5
  const { sql } = cmd;
6
- new lib_1.DB().rawQuery(sql === null || sql === void 0 ? void 0 : sql.replace(/`/g, '')).then(result => console.log(result));
6
+ new lib_1.DB().rawQuery(sql === null || sql === void 0 ? void 0 : sql.replace(/`/g, ''))
7
+ .then(result => console.log(result))
8
+ .catch(err => console.log(err))
9
+ .finally(() => process.exit(0));
7
10
  };
@@ -14,7 +14,7 @@ declare abstract class AbstractDB extends Builder {
14
14
  when: string;
15
15
  then: string;
16
16
  }[], final?: string): string | [];
17
- abstract getConnection(options: ConnectionOptions): Connection;
17
+ abstract getConnection(options: ConnectionOptions): Promise<Connection>;
18
18
  }
19
19
  export { AbstractDB };
20
20
  export default AbstractDB;
@@ -97,6 +97,11 @@ declare class Blueprint {
97
97
  * @return {this} this
98
98
  */
99
99
  dateTime(): this;
100
+ /**
101
+ * Assign type 'DATETIME' in table
102
+ * @return {this} this
103
+ */
104
+ datetime(): this;
100
105
  /**
101
106
  * Assign type 'TIMESTAMP' in table
102
107
  * @return {this} this
@@ -161,6 +161,15 @@ class Blueprint {
161
161
  this.valueType = Date;
162
162
  return this;
163
163
  }
164
+ /**
165
+ * Assign type 'DATETIME' in table
166
+ * @return {this} this
167
+ */
168
+ datetime() {
169
+ this._addAssignType(`DATETIME`);
170
+ this.valueType = Date;
171
+ return this;
172
+ }
164
173
  /**
165
174
  * Assign type 'TIMESTAMP' in table
166
175
  * @return {this} this
@@ -1,5 +1,5 @@
1
1
  import { AbstractBuilder } from './Abstract/AbstractBuilder';
2
- import { Pagination, Backup, ConnectionOptions, BackupToFile, Connection, ConnectionTransaction } from './Interface';
2
+ import { Pagination, Backup, ConnectionOptions, BackupToFile, Connection, ConnectionTransaction, BackupTableToFile } from './Interface';
3
3
  declare class Builder extends AbstractBuilder {
4
4
  constructor();
5
5
  /**
@@ -823,10 +823,54 @@ declare class Builder extends AbstractBuilder {
823
823
  * @param {string} backup.connection.database
824
824
  * @param {string} backup.connection.username
825
825
  * @param {string} backup.connection.password
826
-
827
826
  * @return {Promise<boolean>}
828
827
  */
829
828
  backupToFile({ filePath, database, connection }: BackupToFile): Promise<void>;
829
+ /**
830
+ *
831
+ * backup database intro file
832
+ * @param {Object} backupOptions
833
+ * @param {string} backup.database
834
+ * @param {object?} backup.filePath
835
+ * @param {object?} backup.connection
836
+ * @param {string} backup.connection.host
837
+ * @param {number} backup.connection.port
838
+ * @param {string} backup.connection.database
839
+ * @param {string} backup.connection.username
840
+ * @param {string} backup.connection.password
841
+ * @return {Promise<boolean>}
842
+ */
843
+ backupSchemaToFile({ filePath, database, connection }: BackupToFile): Promise<void>;
844
+ /**
845
+ *
846
+ * backup table intro file
847
+ * @param {Object} backupOptions
848
+ * @param {string} backup.table
849
+ * @param {object?} backup.filePath
850
+ * @param {object?} backup.connection
851
+ * @param {string} backup.connection.host
852
+ * @param {number} backup.connection.port
853
+ * @param {string} backup.connection.database
854
+ * @param {string} backup.connection.username
855
+ * @param {string} backup.connection.password
856
+ * @return {Promise<boolean>}
857
+ */
858
+ backupTableToFile({ filePath, table, connection }: BackupTableToFile): Promise<void>;
859
+ /**
860
+ *
861
+ * backup table only schema intro file
862
+ * @param {Object} backupOptions
863
+ * @param {string} backup.table
864
+ * @param {object?} backup.filePath
865
+ * @param {object?} backup.connection
866
+ * @param {string} backup.connection.host
867
+ * @param {number} backup.connection.port
868
+ * @param {string} backup.connection.database
869
+ * @param {string} backup.connection.username
870
+ * @param {string} backup.connection.password
871
+ * @return {Promise<boolean>}
872
+ */
873
+ backupTableSchemaToFile({ filePath, table, connection }: BackupTableToFile): Promise<void>;
830
874
  /**
831
875
  *
832
876
  * fake data
@@ -2186,7 +2186,6 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
2186
2186
  * @param {string} backup.connection.database
2187
2187
  * @param {string} backup.connection.username
2188
2188
  * @param {string} backup.connection.password
2189
-
2190
2189
  * @return {Promise<boolean>}
2191
2190
  */
2192
2191
  backupToFile({ filePath, database, connection }) {
@@ -2242,8 +2241,142 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
2242
2241
  tabWidth: 2,
2243
2242
  linesBetweenQueries: 1,
2244
2243
  }));
2245
- // fs.writeFileSync(filePath, [...sql,'COMMIT;'].join('\n'))
2246
- console.log(sql);
2244
+ return;
2245
+ });
2246
+ }
2247
+ /**
2248
+ *
2249
+ * backup database intro file
2250
+ * @param {Object} backupOptions
2251
+ * @param {string} backup.database
2252
+ * @param {object?} backup.filePath
2253
+ * @param {object?} backup.connection
2254
+ * @param {string} backup.connection.host
2255
+ * @param {number} backup.connection.port
2256
+ * @param {string} backup.connection.database
2257
+ * @param {string} backup.connection.username
2258
+ * @param {string} backup.connection.password
2259
+ * @return {Promise<boolean>}
2260
+ */
2261
+ backupSchemaToFile({ filePath, database, connection }) {
2262
+ var _a, _b;
2263
+ return __awaiter(this, void 0, void 0, function* () {
2264
+ const tables = yield this.queryStatement(this.$constants('SHOW_TABLES'));
2265
+ let backup = [];
2266
+ for (const t of tables) {
2267
+ const table = String((_a = Object.values(t)) === null || _a === void 0 ? void 0 : _a.shift());
2268
+ const schemas = yield this.showSchemas(table);
2269
+ const createTableSQL = [
2270
+ `${this.$constants('CREATE_TABLE_NOT_EXISTS')}`,
2271
+ `\`${table}\``,
2272
+ `(${schemas.join(',')})`,
2273
+ `${this.$constants('ENGINE')};`,
2274
+ ];
2275
+ backup = [
2276
+ ...backup,
2277
+ {
2278
+ table: createTableSQL.join(' ')
2279
+ }
2280
+ ];
2281
+ }
2282
+ if (connection != null && ((_b = Object.keys(connection)) === null || _b === void 0 ? void 0 : _b.length))
2283
+ this.connection(connection);
2284
+ let sql = [
2285
+ `SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";`,
2286
+ `START TRANSACTION;`,
2287
+ `SET time_zone = "+00:00";`,
2288
+ `${this.$constants('CREATE_DATABASE_NOT_EXISTS')} \`${database}\`;`,
2289
+ `USE \`${database}\`;`
2290
+ ];
2291
+ for (const b of backup) {
2292
+ sql = [...sql, b.table];
2293
+ }
2294
+ fs_1.default.writeFileSync(filePath, (0, sql_formatter_1.format)([...sql, 'COMMIT;'].join('\n'), {
2295
+ language: 'spark',
2296
+ tabWidth: 2,
2297
+ linesBetweenQueries: 1,
2298
+ }));
2299
+ return;
2300
+ });
2301
+ }
2302
+ /**
2303
+ *
2304
+ * backup table intro file
2305
+ * @param {Object} backupOptions
2306
+ * @param {string} backup.table
2307
+ * @param {object?} backup.filePath
2308
+ * @param {object?} backup.connection
2309
+ * @param {string} backup.connection.host
2310
+ * @param {number} backup.connection.port
2311
+ * @param {string} backup.connection.database
2312
+ * @param {string} backup.connection.username
2313
+ * @param {string} backup.connection.password
2314
+ * @return {Promise<boolean>}
2315
+ */
2316
+ backupTableToFile({ filePath, table, connection }) {
2317
+ var _a;
2318
+ return __awaiter(this, void 0, void 0, function* () {
2319
+ const schemas = yield this.showSchemas(table);
2320
+ const createTableSQL = [
2321
+ `${this.$constants('CREATE_TABLE_NOT_EXISTS')}`,
2322
+ `\`${table}\``,
2323
+ `(${schemas.join(',')})`,
2324
+ `${this.$constants('ENGINE')};`,
2325
+ ];
2326
+ const values = yield this.showValues(table);
2327
+ let valueSQL = [];
2328
+ if (values.length) {
2329
+ const columns = yield this.showColumns(table);
2330
+ valueSQL = [
2331
+ `${this.$constants('INSERT')}`,
2332
+ `\`${table}\``,
2333
+ `(${columns.map((column) => `\`${column}\``).join(',')})`,
2334
+ `${this.$constants('VALUES')} ${values.join(',')};`
2335
+ ];
2336
+ }
2337
+ const sql = [createTableSQL.join(' '), valueSQL.join(' ')];
2338
+ if (connection != null && ((_a = Object.keys(connection)) === null || _a === void 0 ? void 0 : _a.length))
2339
+ this.connection(connection);
2340
+ fs_1.default.writeFileSync(filePath, (0, sql_formatter_1.format)(sql.join('\n'), {
2341
+ language: 'spark',
2342
+ tabWidth: 2,
2343
+ linesBetweenQueries: 1,
2344
+ }));
2345
+ return;
2346
+ });
2347
+ }
2348
+ /**
2349
+ *
2350
+ * backup table only schema intro file
2351
+ * @param {Object} backupOptions
2352
+ * @param {string} backup.table
2353
+ * @param {object?} backup.filePath
2354
+ * @param {object?} backup.connection
2355
+ * @param {string} backup.connection.host
2356
+ * @param {number} backup.connection.port
2357
+ * @param {string} backup.connection.database
2358
+ * @param {string} backup.connection.username
2359
+ * @param {string} backup.connection.password
2360
+ * @return {Promise<boolean>}
2361
+ */
2362
+ backupTableSchemaToFile({ filePath, table, connection }) {
2363
+ var _a;
2364
+ return __awaiter(this, void 0, void 0, function* () {
2365
+ const schemas = yield this.showSchemas(table);
2366
+ const createTableSQL = [
2367
+ `${this.$constants('CREATE_TABLE_NOT_EXISTS')}`,
2368
+ `\`${table}\``,
2369
+ `(${schemas.join(',')})`,
2370
+ `${this.$constants('ENGINE')};`,
2371
+ ];
2372
+ const sql = [createTableSQL.join(' ')];
2373
+ if (connection != null && ((_a = Object.keys(connection)) === null || _a === void 0 ? void 0 : _a.length))
2374
+ this.connection(connection);
2375
+ fs_1.default.writeFileSync(filePath, (0, sql_formatter_1.format)(sql.join('\n'), {
2376
+ language: 'spark',
2377
+ tabWidth: 2,
2378
+ linesBetweenQueries: 1,
2379
+ }));
2247
2380
  return;
2248
2381
  });
2249
2382
  }
@@ -63,7 +63,17 @@ declare class DB extends AbstractDB {
63
63
  * @param {string} option.password
64
64
  * @return {Connection}
65
65
  */
66
- getConnection(options: ConnectionOptions): Connection;
66
+ getConnection(options?: ConnectionOptions): Promise<Connection>;
67
+ /**
68
+ * Get a connection
69
+ * @return {ConnectionTransaction} object - Connection for the transaction
70
+ * @type {object} connection
71
+ * @property {function} connection.query - execute query sql then release connection to pool
72
+ * @property {function} connection.startTransaction - start transaction of query
73
+ * @property {function} connection.commit - commit transaction of query
74
+ * @property {function} connection.rollback - rollback transaction of query
75
+ */
76
+ beginTransaction(): Promise<ConnectionTransaction>;
67
77
  /**
68
78
  * Covert result to array
69
79
  * @param {any} result table name
@@ -76,16 +86,6 @@ declare class DB extends AbstractDB {
76
86
  * @return {Record | null} object | null
77
87
  */
78
88
  static makeObject(result: any): Record<string, any> | null;
79
- /**
80
- * Get a connection
81
- * @return {ConnectionTransaction} object - Connection for the transaction
82
- * @type {object} connection
83
- * @property {function} connection.query - execute query sql then release connection to pool
84
- * @property {function} connection.startTransaction - start transaction of query
85
- * @property {function} connection.commit - commit transaction of query
86
- * @property {function} connection.rollback - rollback transaction of query
87
- */
88
- beginTransaction(): Promise<ConnectionTransaction>;
89
89
  /**
90
90
  * Assign table name
91
91
  * @static
@@ -147,7 +147,7 @@ declare class DB extends AbstractDB {
147
147
  * @param {string} option.password
148
148
  * @return {Connection}
149
149
  */
150
- static getConnection(options: ConnectionOptions): Connection;
150
+ static getConnection(options: ConnectionOptions): Promise<Connection>;
151
151
  private _typeOf;
152
152
  private _initialDB;
153
153
  }
@@ -161,13 +161,34 @@ class DB extends AbstractDB_1.AbstractDB {
161
161
  * @return {Connection}
162
162
  */
163
163
  getConnection(options) {
164
- const { host, port, database, username: user, password } = options, others = __rest(options, ["host", "port", "database", "username", "password"]);
165
- const pool = new connection_1.PoolConnection(Object.assign({ host,
166
- port,
167
- database,
168
- user,
169
- password }, others));
170
- return pool.connection();
164
+ return __awaiter(this, void 0, void 0, function* () {
165
+ if (options == null) {
166
+ const pool = yield this.$pool.get();
167
+ return yield pool.connection();
168
+ }
169
+ const { host, port, database, username: user, password } = options, others = __rest(options, ["host", "port", "database", "username", "password"]);
170
+ const pool = new connection_1.PoolConnection(Object.assign({ host,
171
+ port,
172
+ database,
173
+ user,
174
+ password }, others));
175
+ return yield pool.connection();
176
+ });
177
+ }
178
+ /**
179
+ * Get a connection
180
+ * @return {ConnectionTransaction} object - Connection for the transaction
181
+ * @type {object} connection
182
+ * @property {function} connection.query - execute query sql then release connection to pool
183
+ * @property {function} connection.startTransaction - start transaction of query
184
+ * @property {function} connection.commit - commit transaction of query
185
+ * @property {function} connection.rollback - rollback transaction of query
186
+ */
187
+ beginTransaction() {
188
+ return __awaiter(this, void 0, void 0, function* () {
189
+ const pool = yield this.$pool.get();
190
+ return yield pool.connection();
191
+ });
171
192
  }
172
193
  /**
173
194
  * Covert result to array
@@ -217,21 +238,6 @@ class DB extends AbstractDB_1.AbstractDB {
217
238
  };
218
239
  }
219
240
  }
220
- /**
221
- * Get a connection
222
- * @return {ConnectionTransaction} object - Connection for the transaction
223
- * @type {object} connection
224
- * @property {function} connection.query - execute query sql then release connection to pool
225
- * @property {function} connection.startTransaction - start transaction of query
226
- * @property {function} connection.commit - commit transaction of query
227
- * @property {function} connection.rollback - rollback transaction of query
228
- */
229
- beginTransaction() {
230
- return __awaiter(this, void 0, void 0, function* () {
231
- const pool = yield this.$pool.get();
232
- return yield pool.connection();
233
- });
234
- }
235
241
  /**
236
242
  * Assign table name
237
243
  * @static
@@ -329,13 +335,20 @@ class DB extends AbstractDB_1.AbstractDB {
329
335
  * @return {Connection}
330
336
  */
331
337
  static getConnection(options) {
332
- const { host, port, database, username: user, password } = options, others = __rest(options, ["host", "port", "database", "username", "password"]);
333
- const pool = new connection_1.PoolConnection(Object.assign({ host,
334
- port,
335
- database,
336
- user,
337
- password }, others));
338
- return pool.connection();
338
+ return __awaiter(this, void 0, void 0, function* () {
339
+ if (options == null) {
340
+ const self = new this();
341
+ const pool = yield self.$pool.get();
342
+ return yield pool.connection();
343
+ }
344
+ const { host, port, database, username: user, password } = options, others = __rest(options, ["host", "port", "database", "username", "password"]);
345
+ const pool = new connection_1.PoolConnection(Object.assign({ host,
346
+ port,
347
+ database,
348
+ user,
349
+ password }, others));
350
+ return pool.connection();
351
+ });
339
352
  }
340
353
  _typeOf(data) {
341
354
  return Object.prototype.toString.apply(data).slice(8, -1).toLocaleLowerCase();
@@ -55,6 +55,18 @@ export interface Backup {
55
55
  export interface BackupToFile {
56
56
  database: string;
57
57
  filePath: string;
58
+ table?: string;
59
+ connection?: {
60
+ host: string;
61
+ port: number;
62
+ database: string;
63
+ username: string;
64
+ password: string;
65
+ };
66
+ }
67
+ export interface BackupTableToFile {
68
+ filePath: string;
69
+ table: string;
58
70
  connection?: {
59
71
  host: string;
60
72
  port: number;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tspace-mysql",
3
- "version": "1.3.9",
3
+ "version": "1.4.0",
4
4
  "description": "mysql query builder object relational mapping",
5
5
  "main": "dist/lib/index.js",
6
6
  "types": "dist/lib/index.d.ts",