@sqb/connect 4.0.6 → 4.0.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.
Files changed (90) hide show
  1. package/LICENSE +191 -21
  2. package/package.json +14 -14
  3. package/dist/client/Adapter.d.ts +0 -57
  4. package/dist/client/Adapter.js +0 -2
  5. package/dist/client/Cursor.d.ts +0 -116
  6. package/dist/client/Cursor.js +0 -252
  7. package/dist/client/CursorStream.d.ts +0 -29
  8. package/dist/client/CursorStream.js +0 -100
  9. package/dist/client/FieldInfoMap.d.ts +0 -10
  10. package/dist/client/FieldInfoMap.js +0 -33
  11. package/dist/client/SqbClient.d.ts +0 -70
  12. package/dist/client/SqbClient.js +0 -167
  13. package/dist/client/SqbConnection.d.ts +0 -74
  14. package/dist/client/SqbConnection.js +0 -274
  15. package/dist/client/extensions.d.ts +0 -4
  16. package/dist/client/extensions.js +0 -14
  17. package/dist/client/helpers.d.ts +0 -9
  18. package/dist/client/helpers.js +0 -133
  19. package/dist/client/types.d.ts +0 -189
  20. package/dist/client/types.js +0 -5
  21. package/dist/index.d.ts +0 -28
  22. package/dist/index.js +0 -46
  23. package/dist/orm/base-entity.class.d.ts +0 -16
  24. package/dist/orm/base-entity.class.js +0 -56
  25. package/dist/orm/commands/command.helper.d.ts +0 -14
  26. package/dist/orm/commands/command.helper.js +0 -140
  27. package/dist/orm/commands/count.command.d.ts +0 -11
  28. package/dist/orm/commands/count.command.js +0 -30
  29. package/dist/orm/commands/create.command.d.ts +0 -20
  30. package/dist/orm/commands/create.command.js +0 -83
  31. package/dist/orm/commands/destroy.command.d.ts +0 -11
  32. package/dist/orm/commands/destroy.command.js +0 -30
  33. package/dist/orm/commands/find.command.d.ts +0 -44
  34. package/dist/orm/commands/find.command.js +0 -308
  35. package/dist/orm/commands/row-converter.d.ts +0 -55
  36. package/dist/orm/commands/row-converter.js +0 -187
  37. package/dist/orm/commands/update.command.d.ts +0 -22
  38. package/dist/orm/commands/update.command.js +0 -82
  39. package/dist/orm/decorators/column.decorator.d.ts +0 -4
  40. package/dist/orm/decorators/column.decorator.js +0 -14
  41. package/dist/orm/decorators/embedded.decorator.d.ts +0 -2
  42. package/dist/orm/decorators/embedded.decorator.js +0 -17
  43. package/dist/orm/decorators/entity.decorator.d.ts +0 -6
  44. package/dist/orm/decorators/entity.decorator.js +0 -23
  45. package/dist/orm/decorators/events.decorator.d.ts +0 -6
  46. package/dist/orm/decorators/events.decorator.js +0 -76
  47. package/dist/orm/decorators/foreignkey.decorator.d.ts +0 -2
  48. package/dist/orm/decorators/foreignkey.decorator.js +0 -13
  49. package/dist/orm/decorators/index.decorator.d.ts +0 -3
  50. package/dist/orm/decorators/index.decorator.js +0 -22
  51. package/dist/orm/decorators/link.decorator.d.ts +0 -23
  52. package/dist/orm/decorators/link.decorator.js +0 -88
  53. package/dist/orm/decorators/primarykey.decorator.d.ts +0 -3
  54. package/dist/orm/decorators/primarykey.decorator.js +0 -23
  55. package/dist/orm/decorators/transform.decorator.d.ts +0 -3
  56. package/dist/orm/decorators/transform.decorator.js +0 -24
  57. package/dist/orm/model/abstract-entityelement.d.ts +0 -8
  58. package/dist/orm/model/abstract-entityelement.js +0 -10
  59. package/dist/orm/model/association-node.d.ts +0 -9
  60. package/dist/orm/model/association-node.js +0 -25
  61. package/dist/orm/model/association.d.ts +0 -28
  62. package/dist/orm/model/association.js +0 -129
  63. package/dist/orm/model/entity-association-element.d.ts +0 -9
  64. package/dist/orm/model/entity-association-element.js +0 -13
  65. package/dist/orm/model/entity-column-element.d.ts +0 -68
  66. package/dist/orm/model/entity-column-element.js +0 -29
  67. package/dist/orm/model/entity-model.d.ts +0 -59
  68. package/dist/orm/model/entity-model.js +0 -295
  69. package/dist/orm/model/entity-object-element.d.ts +0 -12
  70. package/dist/orm/model/entity-object-element.js +0 -26
  71. package/dist/orm/model/index-meta.d.ts +0 -9
  72. package/dist/orm/model/index-meta.js +0 -16
  73. package/dist/orm/model/link-chain.d.ts +0 -15
  74. package/dist/orm/model/link-chain.js +0 -50
  75. package/dist/orm/orm.const.d.ts +0 -2
  76. package/dist/orm/orm.const.js +0 -5
  77. package/dist/orm/orm.type.d.ts +0 -112
  78. package/dist/orm/orm.type.js +0 -2
  79. package/dist/orm/repository.class.d.ts +0 -125
  80. package/dist/orm/repository.class.js +0 -217
  81. package/dist/orm/util/entity-mapping.d.ts +0 -12
  82. package/dist/orm/util/entity-mapping.js +0 -154
  83. package/dist/orm/util/extract-keyvalues.d.ts +0 -2
  84. package/dist/orm/util/extract-keyvalues.js +0 -60
  85. package/dist/orm/util/orm.helper.d.ts +0 -14
  86. package/dist/orm/util/orm.helper.js +0 -39
  87. package/dist/orm/util/serialize-element.d.ts +0 -2
  88. package/dist/orm/util/serialize-element.js +0 -43
  89. package/dist/types.d.ts +0 -2
  90. package/dist/types.js +0 -2
@@ -1,252 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.Cursor = void 0;
7
- const strict_typed_events_1 = require("strict-typed-events");
8
- const doublylinked_1 = __importDefault(require("doublylinked"));
9
- const putil_taskqueue_1 = __importDefault(require("putil-taskqueue"));
10
- const debug_1 = __importDefault(require("debug"));
11
- const putil_varhelpers_1 = require("putil-varhelpers");
12
- const helpers_1 = require("./helpers");
13
- const CursorStream_1 = require("./CursorStream");
14
- const debug = (0, debug_1.default)('sqb:cursor');
15
- class Cursor extends strict_typed_events_1.AsyncEventEmitter {
16
- constructor(connection, fields, adapterCursor, request) {
17
- super();
18
- this._taskQueue = new putil_taskqueue_1.default();
19
- this._fetchCache = new doublylinked_1.default();
20
- this._rowNum = 0;
21
- this._fetchedAll = false;
22
- this._fetchedRows = 0;
23
- this._connection = connection;
24
- this._intlcur = adapterCursor;
25
- this._fields = fields;
26
- this._request = request;
27
- this._prefetchRows = request?.fetchRows || 100;
28
- }
29
- /**
30
- * Returns the Connection instance
31
- */
32
- get connection() {
33
- return this._connection;
34
- }
35
- /**
36
- * Returns if cursor is before first record.
37
- */
38
- get isBof() {
39
- return !this._rowNum;
40
- }
41
- /**
42
- * Returns if cursor is closed.
43
- */
44
- get isClosed() {
45
- return !this._intlcur;
46
- }
47
- /**
48
- * Returns if cursor is after last record.
49
- */
50
- get isEof() {
51
- return this._fetchedAll && this.rowNum > this._fetchedRows;
52
- }
53
- /**
54
- * Returns number of fetched record count from database.
55
- */
56
- get fetchedRows() {
57
- return this._fetchedRows;
58
- }
59
- /**
60
- * Returns object instance which contains information about fields.
61
- */
62
- get fields() {
63
- return this._fields;
64
- }
65
- /**
66
- * Returns current row
67
- */
68
- get row() {
69
- return this._row;
70
- }
71
- /**
72
- * Returns current row number.
73
- */
74
- get rowNum() {
75
- return this._rowNum;
76
- }
77
- /**
78
- * Enables cache
79
- */
80
- cached() {
81
- if (this.fetchedRows)
82
- throw new Error('Cache can be enabled before fetching rows');
83
- if (!this._cache)
84
- this._cache = new doublylinked_1.default();
85
- }
86
- /**
87
- * Closes cursor
88
- */
89
- async close() {
90
- if (!this._intlcur)
91
- return;
92
- try {
93
- await this._intlcur.close();
94
- this._intlcur = undefined;
95
- debug('close');
96
- this.emit('close');
97
- }
98
- catch (err) {
99
- debug('close-error:', err);
100
- this.emit('error', err);
101
- throw err;
102
- }
103
- }
104
- /**
105
- * If cache is enabled, this call fetches and keeps all records in the internal cache.
106
- * Otherwise it throws error. Once all all records fetched,
107
- * you can close Cursor safely and can continue to use it in memory.
108
- * Returns number of fetched rows
109
- */
110
- async fetchAll() {
111
- if (!this._cache)
112
- throw new Error('fetchAll() method needs cache to be enabled');
113
- const n = this.rowNum;
114
- const v = await this._seek(Number.MAX_SAFE_INTEGER, true);
115
- await this._seek(n - this.rowNum, true);
116
- return v;
117
- }
118
- /**
119
- * Moves cursor to given row number.
120
- * cursor can move both forward and backward if cache enabled.
121
- * Otherwise it throws error.
122
- */
123
- async moveTo(rowNum) {
124
- await this._seek(rowNum - this.rowNum);
125
- return this.row;
126
- }
127
- /**
128
- * Moves cursor forward by one row and returns that row.
129
- * And also it allows iterating over rows easily.
130
- */
131
- async next() {
132
- debug('next');
133
- await this._seek(1);
134
- return this.row;
135
- }
136
- /**
137
- * Moves cursor back by one row and returns that row.
138
- * And also it allows iterating over rows easily.
139
- */
140
- async prev() {
141
- await this._seek(-1);
142
- return this.row;
143
- }
144
- /**
145
- * Moves cursor before first row. (Required cache enabled)
146
- */
147
- reset() {
148
- if (!this._cache)
149
- throw new Error('reset() method needs cache to be enabled');
150
- this._cache.reset();
151
- this._rowNum = 0;
152
- this.emit('reset');
153
- }
154
- /**
155
- * Moves cursor by given step. If caching is enabled,
156
- * cursor can move both forward and backward. Otherwise it throws error.
157
- */
158
- async seek(step) {
159
- await this._seek(step);
160
- return this.row;
161
- }
162
- /**
163
- * Creates and returns a readable stream.
164
- */
165
- toStream(options) {
166
- return new CursorStream_1.CursorStream(this, options);
167
- }
168
- toString() {
169
- return '[object ' + Object.getPrototypeOf(this).constructor.name + ']';
170
- }
171
- inspect() {
172
- return this.toString();
173
- }
174
- /**
175
- *
176
- */
177
- async _seek(step, silent) {
178
- step = (0, putil_varhelpers_1.coerceToInt)(step, 0);
179
- if (!step || (step > 0 && this.isClosed))
180
- return this.rowNum;
181
- if (step < 0 && !this._cache)
182
- throw new Error('To move cursor back, it needs cache to be enabled');
183
- const _this = this;
184
- await this._taskQueue.enqueue(async function () {
185
- /* If moving backward */
186
- if (step < 0) {
187
- /* Seek cache */
188
- while (step < 0 && _this._cache?.cursor) {
189
- _this._row = _this._cache.prev();
190
- _this._rowNum--;
191
- step++;
192
- }
193
- return;
194
- }
195
- while (step > 0) {
196
- if (_this.isEof)
197
- return;
198
- /* Seek cache */
199
- while (step > 0 && _this._cache && (_this._row = _this._cache.next())) {
200
- _this._rowNum++;
201
- step--;
202
- }
203
- /* Fetch from prefetch cache */
204
- while (step > 0 && (_this._row = _this._fetchCache.shift())) {
205
- _this._rowNum++;
206
- step--;
207
- }
208
- if (_this._fetchedAll) {
209
- _this._rowNum++;
210
- _this.emit('eof');
211
- return;
212
- }
213
- if (!step || _this._fetchedAll)
214
- return;
215
- await _this._fetchRows();
216
- }
217
- });
218
- if (!silent)
219
- this.emit('move', this.row, this._rowNum);
220
- return this._rowNum;
221
- }
222
- /**
223
- *
224
- */
225
- async _fetchRows() {
226
- if (!this._intlcur)
227
- throw new Error('Cursor is closed');
228
- let rows = await this._intlcur.fetch(this._prefetchRows);
229
- if (rows && rows.length) {
230
- debug('Fetched %d rows from database', rows.length);
231
- // Normalize rows
232
- rows = this._request.objectRows ?
233
- (0, helpers_1.normalizeRowsToObjectRows)(this._fields, this._intlcur.rowType, rows, this._request) :
234
- (0, helpers_1.normalizeRowsToArrayRows)(this._fields, this._intlcur.rowType, rows, this._request);
235
- (0, helpers_1.callFetchHooks)(rows, this._request);
236
- for (const [idx, row] of rows.entries()) {
237
- this.emit('fetch', row, (this._rowNum + idx + 1));
238
- }
239
- /* Add rows to cache */
240
- if (this._cache) {
241
- this._cache.push(...rows);
242
- }
243
- else
244
- this._fetchCache.push(...rows);
245
- this._fetchedRows += rows.length;
246
- return;
247
- }
248
- this._fetchedAll = true;
249
- return this.close();
250
- }
251
- }
252
- exports.Cursor = Cursor;
@@ -1,29 +0,0 @@
1
- /// <reference types="node" />
2
- import { Readable } from 'stream';
3
- import { Cursor } from './Cursor';
4
- export interface CursorStreamOptions {
5
- objectMode?: boolean;
6
- limit?: number;
7
- }
8
- declare const inspect: unique symbol;
9
- export declare class CursorStream extends Readable {
10
- private readonly _cursor;
11
- private readonly _objectMode?;
12
- private readonly _limit;
13
- private _rowNum;
14
- private _eof;
15
- constructor(cursor: Cursor, options?: CursorStreamOptions);
16
- /**
17
- * Returns if stream is closed.
18
- */
19
- get isClosed(): boolean;
20
- /**
21
- * Closes stream and releases the cursor
22
- */
23
- close(): Promise<void>;
24
- toString(): string;
25
- [inspect](): string;
26
- _read(): void;
27
- emit(event: string | symbol, ...args: any[]): boolean;
28
- }
29
- export {};
@@ -1,100 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.CursorStream = void 0;
7
- const stream_1 = require("stream");
8
- const debug_1 = __importDefault(require("debug"));
9
- const inspect = Symbol.for('nodejs.util.inspect.custom');
10
- const debug = (0, debug_1.default)('sqb:cursorstream');
11
- class CursorStream extends stream_1.Readable {
12
- constructor(cursor, options) {
13
- super(options);
14
- this._rowNum = -1;
15
- this._eof = false;
16
- this._cursor = cursor;
17
- this._objectMode = options?.objectMode;
18
- this._limit = options?.limit || Number.MAX_SAFE_INTEGER;
19
- this.on('end', () => {
20
- this.close().catch(() => false);
21
- });
22
- cursor.once('close', () => this.emit('close'));
23
- cursor.on('error', (err) => this.emit('error', err));
24
- }
25
- /**
26
- * Returns if stream is closed.
27
- */
28
- get isClosed() {
29
- return this._cursor.isClosed;
30
- }
31
- /**
32
- * Closes stream and releases the cursor
33
- */
34
- close() {
35
- this.pause();
36
- this.unpipe();
37
- return this._cursor.close();
38
- }
39
- toString() {
40
- return '[object ' + Object.getPrototypeOf(this).constructor.name + ']';
41
- }
42
- [inspect]() {
43
- return this.toString();
44
- }
45
- _read() {
46
- if (this._rowNum >= this._limit) {
47
- this.pause();
48
- this.unpipe();
49
- this.emit('end');
50
- return;
51
- }
52
- this._cursor.next().then(row => {
53
- if (this._eof)
54
- return this.push(null);
55
- let buf = '';
56
- if (this._rowNum < 0) {
57
- this._rowNum = 0;
58
- if (!this._objectMode)
59
- buf += '[';
60
- }
61
- if (!row) {
62
- this._eof = true;
63
- if (!this._objectMode) {
64
- buf += ']';
65
- this.push(buf);
66
- }
67
- else
68
- this.push(null);
69
- return;
70
- }
71
- this._rowNum++;
72
- if (this._objectMode)
73
- this.push(row);
74
- else {
75
- if (this._rowNum > 1)
76
- buf += ',';
77
- this.push(buf + JSON.stringify(row));
78
- }
79
- }).catch(err => {
80
- /* istanbul ignore next */
81
- if (typeof this.destroy == 'function')
82
- this.destroy(err);
83
- else
84
- this.emit('error', err);
85
- this.close().catch(() => 0);
86
- });
87
- }
88
- emit(event, ...args) {
89
- try {
90
- if (event === 'error' && !this.listenerCount('error'))
91
- return false;
92
- return super.emit(event, ...args);
93
- }
94
- catch (ignored) {
95
- debug('emit-error', ignored);
96
- return false;
97
- }
98
- }
99
- }
100
- exports.CursorStream = CursorStream;
@@ -1,10 +0,0 @@
1
- import { FieldInfo } from './types';
2
- export declare class FieldInfoMap {
3
- private _obj;
4
- private _arr;
5
- add(field: FieldInfo): void;
6
- get(k: string | number): FieldInfo;
7
- entries(): [string, FieldInfo][];
8
- keys(): string[];
9
- values(): FieldInfo[];
10
- }
@@ -1,33 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.FieldInfoMap = void 0;
4
- class FieldInfoMap {
5
- constructor() {
6
- this._obj = {};
7
- this._arr = [];
8
- }
9
- add(field) {
10
- const idx = field.index != null ? field.index : this._arr.length;
11
- this._arr[idx] = field;
12
- field.index = idx;
13
- this._obj = this._arr.reduce((a, f) => {
14
- a[f.name.toUpperCase()] = f;
15
- return a;
16
- }, {});
17
- }
18
- get(k) {
19
- if (typeof k === 'number')
20
- return this._arr[k];
21
- return this._obj[k.toUpperCase()];
22
- }
23
- entries() {
24
- return Object.entries(this._obj);
25
- }
26
- keys() {
27
- return Object.keys(this._obj);
28
- }
29
- values() {
30
- return [...this._arr];
31
- }
32
- }
33
- exports.FieldInfoMap = FieldInfoMap;
@@ -1,70 +0,0 @@
1
- import { Pool as LightningPool } from 'lightning-pool';
2
- import { AsyncEventEmitter } from 'strict-typed-events';
3
- import { Maybe, Type } from 'ts-gems';
4
- import { classes } from '@sqb/builder';
5
- import { ClientConfiguration, QueryExecuteOptions, TransactionFunction, ClientDefaults, ConnectionOptions, QueryRequest, ObjectQueryResult, ArrayQueryResult } from './types';
6
- import { SqbConnection } from './SqbConnection';
7
- import { Repository } from '../orm/repository.class';
8
- declare const inspect: unique symbol;
9
- interface SqbClientEvents {
10
- execute: (request: QueryRequest) => void;
11
- error: (error: Error) => void;
12
- closing: () => void;
13
- close: () => void;
14
- acquire: (connection: SqbConnection) => Promise<void>;
15
- terminate: () => void;
16
- }
17
- export declare class SqbClient extends AsyncEventEmitter<SqbClientEvents> {
18
- private readonly _adapter;
19
- private readonly _pool;
20
- private readonly _defaults;
21
- private readonly _entities;
22
- constructor(config: ClientConfiguration);
23
- get defaults(): ClientDefaults;
24
- /**
25
- * Returns dialect
26
- */
27
- get dialect(): string;
28
- /**
29
- * Returns database driver name
30
- */
31
- get driver(): string;
32
- /**
33
- * Returns true if pool is closed
34
- */
35
- get isClosed(): boolean;
36
- get pool(): LightningPool;
37
- /**
38
- * Obtains a connection from the connection pool and executes the callback
39
- */
40
- acquire(fn: TransactionFunction, options?: ConnectionOptions): Promise<any>;
41
- /**
42
- * Obtains a connection from the connection pool.
43
- */
44
- acquire(options?: ConnectionOptions): Promise<SqbConnection>;
45
- /**
46
- * Shuts down the pool and destroys all resources.
47
- */
48
- close(terminateWait?: number): Promise<void>;
49
- /**
50
- * Executes a query or callback with a new acquired connection.
51
- */
52
- execute(query: string | classes.Query, options?: QueryExecuteOptions & {
53
- objectRows: true;
54
- }): Promise<ObjectQueryResult>;
55
- execute(query: string | classes.Query, options?: QueryExecuteOptions & {
56
- objectRows: false;
57
- }): Promise<ArrayQueryResult>;
58
- execute(query: string | classes.Query, options?: QueryExecuteOptions): Promise<ObjectQueryResult | ArrayQueryResult>;
59
- /**
60
- * Tests the pool
61
- */
62
- test(): Promise<void>;
63
- getRepository<T>(entity: Type<T> | string, opts?: {
64
- schema?: string;
65
- }): Repository<T>;
66
- getEntity<T>(name: string): Maybe<Type<T>>;
67
- toString(): string;
68
- [inspect](): string;
69
- }
70
- export {};
@@ -1,167 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.SqbClient = void 0;
7
- const lightning_pool_1 = require("lightning-pool");
8
- const putil_varhelpers_1 = require("putil-varhelpers");
9
- const strict_typed_events_1 = require("strict-typed-events");
10
- const debug_1 = __importDefault(require("debug"));
11
- const SqbConnection_1 = require("./SqbConnection");
12
- const extensions_1 = require("./extensions");
13
- const repository_class_1 = require("../orm/repository.class");
14
- const entity_model_1 = require("../orm/model/entity-model");
15
- const debug = (0, debug_1.default)('sqb:client');
16
- const inspect = Symbol.for('nodejs.util.inspect.custom');
17
- class SqbClient extends strict_typed_events_1.AsyncEventEmitter {
18
- constructor(config) {
19
- super();
20
- this._entities = {};
21
- if (!(config && typeof config === 'object'))
22
- throw new TypeError('Configuration object required');
23
- let adapter;
24
- if (config.driver) {
25
- adapter = extensions_1.adapters.find(x => x.driver === config.driver);
26
- if (!adapter)
27
- throw new Error(`No database adapter registered for "${config.driver}" driver`);
28
- }
29
- else if (config.dialect) {
30
- adapter = extensions_1.adapters.find(x => x.dialect === config.dialect);
31
- if (!adapter)
32
- throw new Error(`No database adapter registered for "${config.dialect}" dialect`);
33
- }
34
- if (!adapter)
35
- throw new Error(`You must provide one of "driver" or "dialect" properties`);
36
- this._adapter = adapter;
37
- this._defaults = config.defaults || {};
38
- const poolOptions = {};
39
- const popts = config.pool || {};
40
- poolOptions.acquireMaxRetries = (0, putil_varhelpers_1.coerceToInt)(popts.acquireMaxRetries, 0);
41
- poolOptions.acquireRetryWait = (0, putil_varhelpers_1.coerceToInt)(popts.acquireRetryWait, 2000);
42
- poolOptions.acquireTimeoutMillis = (0, putil_varhelpers_1.coerceToInt)(popts.acquireTimeoutMillis, 0);
43
- poolOptions.idleTimeoutMillis = (0, putil_varhelpers_1.coerceToInt)(popts.idleTimeoutMillis, 30000);
44
- poolOptions.max = (0, putil_varhelpers_1.coerceToInt)(popts.max, 10);
45
- poolOptions.maxQueue = (0, putil_varhelpers_1.coerceToInt)(popts.maxQueue, 1000);
46
- poolOptions.max = (0, putil_varhelpers_1.coerceToInt)(popts.max, 10);
47
- poolOptions.min = (0, putil_varhelpers_1.coerceToInt)(popts.min, 0);
48
- poolOptions.minIdle = (0, putil_varhelpers_1.coerceToInt)(popts.minIdle, 0);
49
- poolOptions.validation = (0, putil_varhelpers_1.coerceToBoolean)(popts.validation, false);
50
- const cfg = { ...config };
51
- const poolFactory = {
52
- create: () => adapter.connect(cfg),
53
- destroy: instance => instance.close(),
54
- reset: instance => instance.reset(),
55
- validate: instance => instance.test()
56
- };
57
- this._pool = (0, lightning_pool_1.createPool)(poolFactory, poolOptions);
58
- this._pool.on('closing', () => this.emit('closing'));
59
- this._pool.on('close', () => this.emit('close'));
60
- this._pool.on('terminate', () => this.emit('terminate'));
61
- // @ts-ignore
62
- this._pool.on('error', (...args) => this.emit('error', ...args));
63
- }
64
- get defaults() {
65
- return this._defaults;
66
- }
67
- /**
68
- * Returns dialect
69
- */
70
- get dialect() {
71
- return this._adapter.dialect;
72
- }
73
- /**
74
- * Returns database driver name
75
- */
76
- get driver() {
77
- return this._adapter.driver;
78
- }
79
- /**
80
- * Returns true if pool is closed
81
- */
82
- get isClosed() {
83
- return this._pool.state === lightning_pool_1.PoolState.CLOSED;
84
- }
85
- get pool() {
86
- return this._pool;
87
- }
88
- async acquire(arg0, arg1) {
89
- debug('acquire');
90
- if (typeof arg0 === 'function') {
91
- const connection = await this.acquire(arg1);
92
- try {
93
- return await arg0(connection);
94
- }
95
- finally {
96
- connection.release();
97
- }
98
- }
99
- const options = arg1;
100
- const adapterConnection = await this._pool.acquire();
101
- const opts = { autoCommit: this.defaults.autoCommit, ...options };
102
- const connection = new SqbConnection_1.SqbConnection(this, adapterConnection, opts);
103
- await this.emitAsync({ event: 'acquire', serial: true }, connection);
104
- connection.on('execute', (request) => this.emit('execute', request));
105
- connection.on('error', (error) => this.emit('error', error));
106
- return connection;
107
- }
108
- /**
109
- * Shuts down the pool and destroys all resources.
110
- */
111
- async close(terminateWait) {
112
- const ms = terminateWait == null ? Infinity : 0;
113
- return this._pool.close(ms);
114
- }
115
- async execute(query, options) {
116
- debug('execute');
117
- const connection = await this.acquire();
118
- try {
119
- const qr = await connection.execute(query, options);
120
- if (qr && qr.cursor) {
121
- connection.retain();
122
- qr.cursor.once('close', () => connection.release());
123
- }
124
- return qr;
125
- }
126
- finally {
127
- connection.release();
128
- }
129
- }
130
- /**
131
- * Tests the pool
132
- */
133
- async test() {
134
- const connection = await this.acquire();
135
- try {
136
- await connection.test();
137
- }
138
- finally {
139
- connection.release();
140
- }
141
- }
142
- getRepository(entity, opts) {
143
- let ctor;
144
- if (typeof entity === 'string') {
145
- ctor = this.getEntity(entity);
146
- if (!ctor)
147
- throw new Error(`Repository "${entity}" is not registered`);
148
- }
149
- else
150
- ctor = entity;
151
- const entityDef = entity_model_1.EntityModel.get(ctor);
152
- if (!entityDef)
153
- throw new Error(`You must provide an @Entity annotated constructor`);
154
- return new repository_class_1.Repository(entityDef, this, opts?.schema);
155
- }
156
- getEntity(name) {
157
- return this._entities[name];
158
- }
159
- toString() {
160
- return '[object ' + Object.getPrototypeOf(this).constructor.name + '(' +
161
- this.dialect + ')]';
162
- }
163
- [inspect]() {
164
- return this.toString();
165
- }
166
- }
167
- exports.SqbClient = SqbClient;