tspace-mysql 1.1.8 → 1.2.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.
Files changed (36) hide show
  1. package/README.md +115 -38
  2. package/dist/cli/generate/make.d.ts +4 -0
  3. package/dist/cli/generate/make.js +45 -0
  4. package/dist/cli/index.js +27 -13
  5. package/dist/cli/migrate/make.js +5 -4
  6. package/dist/cli/models/make.d.ts +1 -1
  7. package/dist/cli/models/make.js +2 -2
  8. package/dist/cli/models/model.js +3 -4
  9. package/dist/cli/query/index.d.ts +4 -0
  10. package/dist/cli/query/index.js +7 -0
  11. package/dist/lib/connection/index.d.ts +8 -32
  12. package/dist/lib/connection/index.js +50 -37
  13. package/dist/lib/connection/options.d.ts +4 -0
  14. package/dist/lib/{config/env.js → connection/options.js} +10 -7
  15. package/dist/lib/constants/index.d.ts +2 -2
  16. package/dist/lib/constants/index.js +14 -11
  17. package/dist/lib/tspace/AbstractDB.d.ts +2 -0
  18. package/dist/lib/tspace/AbstractDatabase.d.ts +23 -19
  19. package/dist/lib/tspace/AbstractDatabase.js +29 -26
  20. package/dist/lib/tspace/AbstractModel.d.ts +5 -4
  21. package/dist/lib/tspace/Blueprint.js +4 -2
  22. package/dist/lib/tspace/DB.d.ts +23 -2
  23. package/dist/lib/tspace/DB.js +93 -30
  24. package/dist/lib/tspace/Database.d.ts +26 -13
  25. package/dist/lib/tspace/Database.js +920 -777
  26. package/dist/lib/tspace/Interface.d.ts +26 -0
  27. package/dist/lib/tspace/Logger.js +5 -4
  28. package/dist/lib/tspace/Model.d.ts +73 -23
  29. package/dist/lib/tspace/Model.js +1208 -867
  30. package/dist/lib/tspace/ProxyHandler.d.ts +9 -1
  31. package/dist/lib/tspace/ProxyHandler.js +8 -9
  32. package/dist/lib/tspace/Schema.js +35 -22
  33. package/dist/lib/utils/index.d.ts +0 -1
  34. package/dist/lib/utils/index.js +15 -44
  35. package/package.json +4 -2
  36. package/dist/lib/config/env.d.ts +0 -4
@@ -6,31 +6,19 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.Pool = exports.PoolConnection = void 0;
7
7
  const fs_1 = __importDefault(require("fs"));
8
8
  const path_1 = __importDefault(require("path"));
9
- const env_1 = __importDefault(require("../config/env"));
9
+ const options_1 = __importDefault(require("./options"));
10
10
  const mysql2_1 = require("mysql2");
11
11
  class PoolConnection {
12
- OPTIONS = this._loadOptions();
13
12
  /**
14
13
  *
15
14
  * @Init a options connection pool
16
15
  */
17
16
  constructor(options) {
17
+ this.OPTIONS = this._loadOptions();
18
18
  if (options) {
19
- this.OPTIONS = new Map(Object.entries({
20
- ...Object.fromEntries(this.OPTIONS),
21
- ...JSON.parse(JSON.stringify(options))
22
- }));
19
+ this.OPTIONS = new Map(Object.entries(Object.assign(Object.assign({}, Object.fromEntries(this.OPTIONS)), JSON.parse(JSON.stringify(options)))));
23
20
  }
24
21
  }
25
- /**
26
- *
27
- * Set a options connection pool
28
- * @return {this} this
29
- */
30
- options(options) {
31
- this.OPTIONS = new Map(Object.entries(options));
32
- return this;
33
- }
34
22
  /**
35
23
  *
36
24
  * Get a connection to database
@@ -40,17 +28,17 @@ class PoolConnection {
40
28
  */
41
29
  connection() {
42
30
  const pool = (0, mysql2_1.createPool)(Object.fromEntries(this.OPTIONS));
43
- const conn = pool.getConnection((err, _) => {
44
- if (!err)
45
- return;
46
- const message = this._messageError.bind(this);
47
- if (!env_1.default.CONNECTION_ERROR)
48
- return;
49
- process.nextTick(() => {
50
- console.log(message());
51
- return process.exit();
31
+ if (options_1.default.CONNECTION_ERROR) {
32
+ pool.getConnection((err, _) => {
33
+ if (err == null || !err)
34
+ return;
35
+ const message = this._messageError.bind(this);
36
+ process.nextTick(() => {
37
+ console.log(message());
38
+ return process.exit();
39
+ });
52
40
  });
53
- });
41
+ }
54
42
  return {
55
43
  query: (sql) => {
56
44
  return new Promise((resolve, reject) => {
@@ -91,23 +79,41 @@ class PoolConnection {
91
79
  }
92
80
  _defaultOptions() {
93
81
  return new Map(Object.entries({
94
- connectionLimit: Number(env_1.default.CONNECTION_LIMIT),
95
- dateStrings: Boolean(env_1.default.DATE_STRINGS),
96
- connectTimeout: Number(env_1.default.TIMEOUT),
97
- waitForConnections: true,
98
- queueLimit: Number(env_1.default.QUEUE_LIMIT),
99
- charset: 'utf8mb4',
100
- host: String(env_1.default.HOST),
101
- port: Number.isNaN(Number(env_1.default.PORT))
82
+ connectionLimit: Number(options_1.default.CONNECTION_LIMIT),
83
+ dateStrings: Boolean(options_1.default.DATE_STRINGS),
84
+ connectTimeout: Number(options_1.default.TIMEOUT),
85
+ waitForConnections: Boolean(options_1.default.WAIT_FOR_CONNECTIONS),
86
+ queueLimit: Number(options_1.default.QUEUE_LIMIT),
87
+ charset: String(options_1.default.CHARSET),
88
+ host: String(options_1.default.HOST),
89
+ port: Number.isNaN(Number(options_1.default.PORT))
102
90
  ? 3306
103
- : Number(env_1.default.PORT),
104
- database: String(env_1.default.DATABASE),
105
- user: String(env_1.default.USERNAME),
106
- password: String(env_1.default.PASSWORD) === '' ? '' : String(env_1.default.PASSWORD)
91
+ : Number(options_1.default.PORT),
92
+ database: String(options_1.default.DATABASE),
93
+ user: String(options_1.default.USERNAME),
94
+ password: String(options_1.default.PASSWORD) !== ''
95
+ ? String(options_1.default.PASSWORD)
96
+ : ''
107
97
  }));
108
98
  }
109
99
  _loadOptions() {
110
100
  try {
101
+ /**
102
+ *
103
+ * @Json connection
104
+ *
105
+ "host" : "",
106
+ "port" : "",
107
+ "database" : "",
108
+ "user" : "",
109
+ "password" : "",
110
+ "connectionLimit" : "",
111
+ "dateStrings" : "",
112
+ "connectTimeout" : "",
113
+ "waitForConnections" : "",
114
+ "queueLimit" : "",
115
+ "charset" : ""
116
+ */
111
117
  const jsonPath = path_1.default.join(path_1.default.resolve(), 'tspace-mysql.json');
112
118
  const jsonOptionsExists = fs_1.default.existsSync(jsonPath);
113
119
  if (!jsonOptionsExists)
@@ -135,6 +141,13 @@ class PoolConnection {
135
141
  }
136
142
  }
137
143
  exports.PoolConnection = PoolConnection;
144
+ /**
145
+ *
146
+ * Connection to database when service is started
147
+ * @return {Connection} Connection
148
+ * @property {Function} Connection.query
149
+ * @property {Function} Connection.connection
150
+ */
138
151
  const pool = new PoolConnection().connection();
139
152
  exports.Pool = pool;
140
153
  exports.default = pool;
@@ -0,0 +1,4 @@
1
+ declare const _default: Readonly<{
2
+ [x: string]: any;
3
+ }>;
4
+ export default _default;
@@ -7,14 +7,15 @@ const dotenv_1 = __importDefault(require("dotenv"));
7
7
  const path_1 = __importDefault(require("path"));
8
8
  const fs_1 = __importDefault(require("fs"));
9
9
  const environment = () => {
10
- const NODE_ENV = process.env?.NODE_ENV;
11
- const envWithoutEnviroment = path_1.default.join(path_1.default.resolve(), '.env');
10
+ var _a;
11
+ const NODE_ENV = (_a = process.env) === null || _a === void 0 ? void 0 : _a.NODE_ENV;
12
+ const env = path_1.default.join(path_1.default.resolve(), '.env');
12
13
  const envWithEnviroment = path_1.default.join(path_1.default.resolve(), `.env.${NODE_ENV}`);
13
14
  if (NODE_ENV == null)
14
- return envWithoutEnviroment;
15
+ return env;
15
16
  if (fs_1.default.existsSync(envWithEnviroment))
16
17
  return envWithEnviroment;
17
- return envWithoutEnviroment;
18
+ return env;
18
19
  };
19
20
  dotenv_1.default.config({ path: environment() });
20
21
  const env = {
@@ -23,10 +24,12 @@ const env = {
23
24
  USERNAME: process.env.DB_USERNAME || process.env.TSPACE_USERNAME,
24
25
  PASSWORD: process.env.DB_PASSWORD || process.env.TSPACE_PASSWORD || '',
25
26
  DATABASE: process.env.DB_DATABASE || process.env.TSPACE_DATABASE,
26
- CONNECTION_LIMIT: process.env.DB_CONNECTION_LIMIT || process.env.TSPACE_CONNECTION_LIMIT || 10,
27
- CONNECTION_ERROR: process.env.DB_CONNECTION_ERROR || process.env.TSPACE_CONNECTION_ERROR || true,
27
+ CONNECTION_LIMIT: process.env.DB_CONNECTION_LIMIT || process.env.TSPACE_CONNECTION_LIMIT || 151,
28
28
  QUEUE_LIMIT: process.env.DB_QUEUE_LIMIT || process.env.TSPACE_QUEUE_LIMIT || 25,
29
29
  TIMEOUT: process.env.DB_TIMEOUT || process.env.TSPACE_TIMEOUT || 1000 * 30,
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,
30
33
  DATE_STRINGS: process.env.DB_DATE_STRINGS || process.env.TSPACE_DATE_STRINGS || true
31
34
  };
32
35
  for (const [key, value] of Object.entries(env)) {
@@ -36,4 +39,4 @@ for (const [key, value] of Object.entries(env)) {
36
39
  env[key] = JSON.parse(value.toLowerCase());
37
40
  }
38
41
  }
39
- exports.default = Object.freeze({ ...env });
42
+ exports.default = Object.freeze(Object.assign({}, env));
@@ -1,8 +1,8 @@
1
1
  declare const CONSTANTS: {
2
- [x: string]: string | Object;
2
+ [key: string]: string | Object;
3
3
  };
4
4
  export { CONSTANTS };
5
5
  declare const _default: Readonly<{
6
- [x: string]: string | Object;
6
+ [key: string]: string | Object;
7
7
  }>;
8
8
  export default _default;
@@ -4,6 +4,7 @@ exports.CONSTANTS = void 0;
4
4
  const CONSTANTS = {
5
5
  ID: 'ID',
6
6
  SHOW: 'SHOW',
7
+ SHOW_TABLES: 'SHOW TABLES',
7
8
  FIELDS: 'FIELDS',
8
9
  COLUMNS: 'COLUMNS',
9
10
  WHERE: 'WHERE',
@@ -14,9 +15,9 @@ const CONSTANTS = {
14
15
  OR: 'OR',
15
16
  LIKE: 'LIKE',
16
17
  SELECT: 'SELECT',
18
+ SELECTED: '*',
17
19
  DISTINCT: 'DISTINCT',
18
20
  FROM: 'FROM',
19
- STAR: 'STAR',
20
21
  OFFSET: 'OFFSET',
21
22
  GROUP_BY: 'GROUP BY',
22
23
  GROUP_CONCAT: 'GROUP_CONCAT',
@@ -102,7 +103,8 @@ const CONSTANTS = {
102
103
  DEBUG: false,
103
104
  UUID: false,
104
105
  PAGE: 1,
105
- PER_PAGE: 1
106
+ PER_PAGE: 1,
107
+ HOOK: []
106
108
  },
107
109
  MODEL: {
108
110
  PRIMARY_KEY: 'id',
@@ -125,11 +127,6 @@ const CONSTANTS = {
125
127
  HAVING: '',
126
128
  TABLE_NAME: '',
127
129
  UUID_FORMAT: 'uuid',
128
- TIMESTAMP: false,
129
- TIMESTAMP_FORMAT: {
130
- CREATED_AT: 'created_at',
131
- UPDATED_AT: 'updated_at'
132
- },
133
130
  HIDDEN: [],
134
131
  DEBUG: false,
135
132
  UUID: false,
@@ -137,9 +134,6 @@ const CONSTANTS = {
137
134
  SOFT_DELETE_FORMAT: 'deleted_at',
138
135
  SOFT_DELETE_RELATIONS: false,
139
136
  RELATION: [],
140
- WITH: [],
141
- WITH_EXISTS: false,
142
- WITH_EXISTS_NOT_ID: [],
143
137
  PAGE: 1,
144
138
  PER_PAGE: 1,
145
139
  REGISTRY: {},
@@ -147,7 +141,16 @@ const CONSTANTS = {
147
141
  PATTERN: 'snake_case',
148
142
  DISTINCT: '',
149
143
  PLUCK: '',
150
- SAVE: ''
144
+ SAVE: '',
145
+ HOOK: [],
146
+ WITH: [],
147
+ WITH_EXISTS: false,
148
+ WITH_EXISTS_NOT_ID: [],
149
+ TIMESTAMP: false,
150
+ TIMESTAMP_FORMAT: {
151
+ CREATED_AT: 'created_at',
152
+ UPDATED_AT: 'updated_at'
153
+ },
151
154
  }
152
155
  };
153
156
  exports.CONSTANTS = CONSTANTS;
@@ -1,4 +1,5 @@
1
1
  import Database from './Database';
2
+ import { Connection, ConnectionOptions } from './Interface';
2
3
  declare abstract class AbstractDB extends Database {
3
4
  abstract table(tableName: string): void;
4
5
  abstract beginTransaction(): Promise<any>;
@@ -11,6 +12,7 @@ declare abstract class AbstractDB extends Database {
11
12
  when: string;
12
13
  then: string;
13
14
  }[], final?: string): string | [];
15
+ abstract getConnection(options: ConnectionOptions): Connection;
14
16
  }
15
17
  export { AbstractDB };
16
18
  export default AbstractDB;
@@ -6,14 +6,15 @@ declare abstract class AbstractDatabase {
6
6
  };
7
7
  protected $constants: Function;
8
8
  protected $state: {
9
+ original: Function;
9
10
  get: Function;
10
11
  set: Function;
11
12
  clone: Function;
12
13
  };
13
14
  protected $pool: {
14
- get: Function;
15
+ query: Function;
15
16
  set: Function;
16
- load: Function;
17
+ get: Function;
17
18
  };
18
19
  protected $logger: {
19
20
  get: Function;
@@ -22,12 +23,12 @@ declare abstract class AbstractDatabase {
22
23
  };
23
24
  protected $attributes: {
24
25
  [key: string]: any;
25
- };
26
+ } | null;
26
27
  abstract void(): this;
27
28
  abstract debug(): this;
28
29
  abstract dd(): this;
29
- abstract select(...params: string[]): this;
30
- abstract distinct(...params: string[]): this;
30
+ abstract select(...columns: string[]): this;
31
+ abstract distinct(...columns: string[]): this;
31
32
  abstract whereNull(column: string): this;
32
33
  abstract whereNotNull(column: string): this;
33
34
  abstract where(column: string, operator: string, value: string): this;
@@ -51,9 +52,9 @@ declare abstract class AbstractDatabase {
51
52
  abstract leftJoin(pk: string, fk: string): this;
52
53
  abstract crossJoin(pk: string, fk: string): this;
53
54
  abstract orderBy(column: string, order: string): this;
54
- abstract latest(column: string): this;
55
- abstract oldest(column: string): this;
56
- abstract groupBy(column: string): this;
55
+ abstract latest(...columns: Array<string>): this;
56
+ abstract oldest(...columns: Array<string>): this;
57
+ abstract groupBy(...columns: string[]): this;
57
58
  abstract limit(number: number): this;
58
59
  abstract hidden(...columns: string[]): this;
59
60
  abstract insert(objects: object): this;
@@ -67,11 +68,11 @@ declare abstract class AbstractDatabase {
67
68
  abstract updateOrCreate(objects: object): this;
68
69
  abstract createMultiple(objects: object): this;
69
70
  abstract insertMultiple(objects: object): this;
70
- abstract except(...params: string[]): this;
71
- abstract only(...params: string[]): this;
71
+ abstract except(...columns: string[]): this;
72
+ abstract only(...columns: string[]): this;
72
73
  abstract drop(): Promise<any>;
73
74
  abstract truncate(): Promise<any>;
74
- abstract all(): Promise<any>;
75
+ abstract all(): Promise<Array<any>>;
75
76
  abstract find(id: number): Promise<any>;
76
77
  abstract pagination({ limit, page }: {
77
78
  limit: number;
@@ -97,14 +98,17 @@ declare abstract class AbstractDatabase {
97
98
  abstract toJSON(): Promise<any>;
98
99
  abstract toSQL(): string;
99
100
  abstract toString(): string;
100
- abstract count(column: string): Promise<any>;
101
- abstract sum(column: string): Promise<any>;
102
- abstract avg(column: string): Promise<any>;
103
- abstract max(column: string): Promise<any>;
104
- abstract min(column: string): Promise<any>;
105
- abstract delete(): Promise<any>;
106
- abstract exists(): Promise<any>;
107
- abstract save(): Promise<any[] | object | null>;
101
+ abstract count(column: string): Promise<number>;
102
+ abstract sum(column: string): Promise<number>;
103
+ abstract avg(column: string): Promise<number>;
104
+ abstract max(column: string): Promise<number>;
105
+ abstract min(column: string): Promise<number>;
106
+ abstract rawQuery(sql: string): Promise<Array<any>>;
107
+ abstract delete(): Promise<boolean>;
108
+ abstract exists(): Promise<boolean>;
109
+ abstract save(): Promise<{
110
+ [key: string]: any;
111
+ } | Array<any> | null | undefined>;
108
112
  abstract increment(column: string, value: number): Promise<any>;
109
113
  abstract decrement(column: string, value: number): Promise<any>;
110
114
  abstract faker(round: number): Promise<any>;
@@ -1,31 +1,34 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  class AbstractDatabase {
4
- $setters = [
5
- '$attributes',
6
- '$logger',
7
- '$utils',
8
- '$constants',
9
- '$pool',
10
- '$state',
11
- ];
12
- $utils = {};
13
- $constants = (name) => { };
14
- $state = {
15
- get: (key) => { },
16
- set: (key, value) => { },
17
- clone: (data) => { }
18
- };
19
- $pool = {
20
- get: (sql) => { },
21
- set: (pool) => { },
22
- load: () => { }
23
- };
24
- $logger = {
25
- get: () => { },
26
- set: (value) => { },
27
- check: (value) => true || false
28
- };
29
- $attributes = {};
4
+ constructor() {
5
+ this.$setters = [
6
+ '$attributes',
7
+ '$logger',
8
+ '$utils',
9
+ '$constants',
10
+ '$pool',
11
+ '$state',
12
+ ];
13
+ this.$utils = {};
14
+ this.$constants = (name) => { };
15
+ this.$state = {
16
+ original: () => { },
17
+ get: (key) => { },
18
+ set: (key, value) => { },
19
+ clone: (data) => { }
20
+ };
21
+ this.$pool = {
22
+ query: (sql) => { },
23
+ set: (pool) => { },
24
+ get: () => { }
25
+ };
26
+ this.$logger = {
27
+ get: () => { },
28
+ set: (value) => { },
29
+ check: (value) => true || false
30
+ };
31
+ this.$attributes = null;
32
+ }
30
33
  }
31
34
  exports.default = AbstractDatabase;
@@ -17,10 +17,10 @@ declare abstract class AbstractModel extends Database {
17
17
  protected abstract belongsTo({ name, model, localKey, foreignKey, freezeTable, as }: Relation): this;
18
18
  protected abstract belongsToMany({ name, model, localKey, foreignKey, freezeTable, as }: Relation): this;
19
19
  protected abstract buildMethodRelation(name: string, callback?: Function): this;
20
- protected abstract hasOneQuery({ name, model, localKey, foreignKey, freezeTable, as }: RelationQuery, callback: Function): this;
21
- protected abstract hasManyQuery({ name, model, localKey, foreignKey, freezeTable, as }: RelationQuery, callback: Function): this;
22
- protected abstract belongsToQuery({ name, model, localKey, foreignKey, freezeTable, as }: RelationQuery, callback: Function): this;
23
- protected abstract belongsToManyQuery({ name, model, localKey, foreignKey, freezeTable, as }: RelationQuery, callback: Function): this;
20
+ protected abstract hasOneBuilder({ name, model, localKey, foreignKey, freezeTable, as }: RelationQuery, callback: Function): this;
21
+ protected abstract hasManyBuilder({ name, model, localKey, foreignKey, freezeTable, as }: RelationQuery, callback: Function): this;
22
+ protected abstract belongsToBuilder({ name, model, localKey, foreignKey, freezeTable, as }: RelationQuery, callback: Function): this;
23
+ protected abstract belongsToManyBuilder({ name, model, localKey, foreignKey, freezeTable, as }: RelationQuery, callback: Function): this;
24
24
  abstract ignoreSoftDelete(): this;
25
25
  abstract disableSoftDelete(): this;
26
26
  abstract registry(func: {
@@ -32,6 +32,7 @@ declare abstract class AbstractModel extends Database {
32
32
  abstract with(...nameRelations: string[]): this;
33
33
  abstract withQuery(nameRelations: string, callback: Function): this;
34
34
  abstract withExists(...nameRelations: string[]): this;
35
+ abstract has(...nameRelations: string[]): this;
35
36
  abstract relations(...nameRelations: string[]): this;
36
37
  abstract relationQuery(nameRelations: string, callback: Function): this;
37
38
  abstract relationsExists(...nameRelations: string[]): this;
@@ -2,8 +2,10 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Blueprint = void 0;
4
4
  class Blueprint {
5
- type = '';
6
- attrbuites = [];
5
+ constructor() {
6
+ this.type = '';
7
+ this.attrbuites = [];
8
+ }
7
9
  /**
8
10
  * Assign type 'int' in table
9
11
  * @return {this} this
@@ -1,5 +1,5 @@
1
1
  import { AbstractDB } from './AbstractDB';
2
- import { ConnectionTransaction } from '../connection';
2
+ import { Connection, ConnectionOptions, ConnectionTransaction } from './Interface';
3
3
  declare class DB extends AbstractDB {
4
4
  constructor(table?: string);
5
5
  /**
@@ -37,6 +37,17 @@ declare class DB extends AbstractDB {
37
37
  * @return {string} string
38
38
  */
39
39
  raw(sql: string): string;
40
+ /**
41
+ * Get a pool connection
42
+ * @param {Object} options options for connection database with credentials
43
+ * @param {string} option.host
44
+ * @param {number} option.port
45
+ * @param {string} option.database
46
+ * @param {string} option.username
47
+ * @param {string} option.password
48
+ * @return {Connection}
49
+ */
50
+ getConnection(options: ConnectionOptions): Connection;
40
51
  /**
41
52
  * Get a connection
42
53
  * @return {ConnectionTransaction} object
@@ -98,8 +109,18 @@ declare class DB extends AbstractDB {
98
109
  * @property {function} connection.rollback - rollback transaction of query
99
110
  */
100
111
  static beginTransaction(): Promise<ConnectionTransaction>;
112
+ /**
113
+ * Get a pool connection
114
+ * @param {Object} options options for connection database with credentials
115
+ * @param {string} option.host
116
+ * @param {number} option.port
117
+ * @param {string} option.database
118
+ * @param {string} option.username
119
+ * @param {string} option.password
120
+ * @return {Connection}
121
+ */
122
+ static getConnection(options: ConnectionOptions): Connection;
101
123
  private _initialDB;
102
- private _setupDB;
103
124
  }
104
125
  export { DB };
105
126
  export default DB;
@@ -1,8 +1,29 @@
1
1
  "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __rest = (this && this.__rest) || function (s, e) {
12
+ var t = {};
13
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
14
+ t[p] = s[p];
15
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
16
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
17
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
18
+ t[p[i]] = s[p[i]];
19
+ }
20
+ return t;
21
+ };
2
22
  Object.defineProperty(exports, "__esModule", { value: true });
3
23
  exports.DB = void 0;
4
24
  const AbstractDB_1 = require("./AbstractDB");
5
25
  const ProxyHandler_1 = require("./ProxyHandler");
26
+ const connection_1 = require("../connection");
6
27
  class DB extends AbstractDB_1.AbstractDB {
7
28
  constructor(table) {
8
29
  super();
@@ -73,6 +94,25 @@ class DB extends AbstractDB_1.AbstractDB {
73
94
  raw(sql) {
74
95
  return `${this.$constants('RAW')} ${sql}`;
75
96
  }
97
+ /**
98
+ * Get a pool connection
99
+ * @param {Object} options options for connection database with credentials
100
+ * @param {string} option.host
101
+ * @param {number} option.port
102
+ * @param {string} option.database
103
+ * @param {string} option.username
104
+ * @param {string} option.password
105
+ * @return {Connection}
106
+ */
107
+ getConnection(options) {
108
+ const { host, port, database, username: user, password } = options, others = __rest(options, ["host", "port", "database", "username", "password"]);
109
+ const pool = new connection_1.PoolConnection(Object.assign({ host,
110
+ port,
111
+ database,
112
+ user,
113
+ password }, others));
114
+ return pool.connection();
115
+ }
76
116
  /**
77
117
  * Get a connection
78
118
  * @return {ConnectionTransaction} object
@@ -82,9 +122,11 @@ class DB extends AbstractDB_1.AbstractDB {
82
122
  * @property {function} connection.commit - commit transaction of query
83
123
  * @property {function} connection.rollback - rollback transaction of query
84
124
  */
85
- async beginTransaction() {
86
- const pool = await this.$pool.load();
87
- return await pool.connection();
125
+ beginTransaction() {
126
+ return __awaiter(this, void 0, void 0, function* () {
127
+ const pool = yield this.$pool.get();
128
+ return yield pool.connection();
129
+ });
88
130
  }
89
131
  /**
90
132
  * Assign table name
@@ -165,37 +207,58 @@ class DB extends AbstractDB_1.AbstractDB {
165
207
  * @property {function} connection.commit - commit transaction of query
166
208
  * @property {function} connection.rollback - rollback transaction of query
167
209
  */
168
- static async beginTransaction() {
169
- const self = new this();
170
- const pool = await self.$pool.load();
171
- return await pool.connection();
210
+ static beginTransaction() {
211
+ return __awaiter(this, void 0, void 0, function* () {
212
+ const self = new this();
213
+ const pool = yield self.$pool.get();
214
+ return yield pool.connection();
215
+ });
216
+ }
217
+ /**
218
+ * Get a pool connection
219
+ * @param {Object} options options for connection database with credentials
220
+ * @param {string} option.host
221
+ * @param {number} option.port
222
+ * @param {string} option.database
223
+ * @param {string} option.username
224
+ * @param {string} option.password
225
+ * @return {Connection}
226
+ */
227
+ static getConnection(options) {
228
+ const { host, port, database, username: user, password } = options, others = __rest(options, ["host", "port", "database", "username", "password"]);
229
+ const pool = new connection_1.PoolConnection(Object.assign({ host,
230
+ port,
231
+ database,
232
+ user,
233
+ password }, others));
234
+ return pool.connection();
172
235
  }
173
236
  _initialDB() {
174
- this.$state = this._setupDB();
237
+ this.$state = (() => {
238
+ let db = new Map(Object.entries(Object.assign({}, this.$constants('DB'))));
239
+ return {
240
+ original: () => db,
241
+ get: (key) => {
242
+ if (key == null)
243
+ return db;
244
+ if (!db.has(key))
245
+ throw new Error(`can't get this [${key}]`);
246
+ return db.get(key);
247
+ },
248
+ set: (key, value) => {
249
+ if (!db.has(key))
250
+ throw new Error(`can't set this [${key}]`);
251
+ db.set(key, value);
252
+ return;
253
+ },
254
+ clone: (data) => {
255
+ db = new Map(Object.entries(Object.assign({}, data)));
256
+ return;
257
+ }
258
+ };
259
+ })();
175
260
  return this;
176
261
  }
177
- _setupDB() {
178
- let db = new Map(Object.entries({ ...this.$constants('DB') }));
179
- return {
180
- get: (key) => {
181
- if (key == null)
182
- return db;
183
- if (!db.has(key))
184
- throw new Error(`can't get this [${key}]`);
185
- return db.get(key);
186
- },
187
- set: (key, value) => {
188
- if (!db.has(key))
189
- throw new Error(`can't set this [${key}]`);
190
- db.set(key, value);
191
- return;
192
- },
193
- clone: (data) => {
194
- db = new Map(Object.entries({ ...data }));
195
- return;
196
- }
197
- };
198
- }
199
262
  }
200
263
  exports.DB = DB;
201
264
  exports.default = DB;