@sqb/connect 4.0.9 → 4.0.13

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 (89) hide show
  1. package/dist/client/Adapter.d.ts +57 -0
  2. package/dist/client/Adapter.js +2 -0
  3. package/dist/client/Cursor.d.ts +116 -0
  4. package/dist/client/Cursor.js +250 -0
  5. package/dist/client/CursorStream.d.ts +29 -0
  6. package/dist/client/CursorStream.js +98 -0
  7. package/dist/client/FieldInfoMap.d.ts +10 -0
  8. package/dist/client/FieldInfoMap.js +33 -0
  9. package/dist/client/SqbClient.d.ts +70 -0
  10. package/dist/client/SqbClient.js +165 -0
  11. package/dist/client/SqbConnection.d.ts +74 -0
  12. package/dist/client/SqbConnection.js +272 -0
  13. package/dist/client/extensions.d.ts +4 -0
  14. package/dist/client/extensions.js +14 -0
  15. package/dist/client/helpers.d.ts +9 -0
  16. package/dist/client/helpers.js +133 -0
  17. package/dist/client/types.d.ts +189 -0
  18. package/dist/client/types.js +5 -0
  19. package/dist/index.d.ts +28 -0
  20. package/dist/index.js +37 -0
  21. package/dist/orm/base-entity.class.d.ts +16 -0
  22. package/dist/orm/base-entity.class.js +56 -0
  23. package/dist/orm/commands/command.helper.d.ts +14 -0
  24. package/dist/orm/commands/command.helper.js +140 -0
  25. package/dist/orm/commands/count.command.d.ts +11 -0
  26. package/dist/orm/commands/count.command.js +30 -0
  27. package/dist/orm/commands/create.command.d.ts +20 -0
  28. package/dist/orm/commands/create.command.js +83 -0
  29. package/dist/orm/commands/destroy.command.d.ts +11 -0
  30. package/dist/orm/commands/destroy.command.js +30 -0
  31. package/dist/orm/commands/find.command.d.ts +44 -0
  32. package/dist/orm/commands/find.command.js +308 -0
  33. package/dist/orm/commands/row-converter.d.ts +55 -0
  34. package/dist/orm/commands/row-converter.js +187 -0
  35. package/dist/orm/commands/update.command.d.ts +22 -0
  36. package/dist/orm/commands/update.command.js +82 -0
  37. package/dist/orm/decorators/column.decorator.d.ts +4 -0
  38. package/dist/orm/decorators/column.decorator.js +14 -0
  39. package/dist/orm/decorators/embedded.decorator.d.ts +2 -0
  40. package/dist/orm/decorators/embedded.decorator.js +17 -0
  41. package/dist/orm/decorators/entity.decorator.d.ts +6 -0
  42. package/dist/orm/decorators/entity.decorator.js +23 -0
  43. package/dist/orm/decorators/events.decorator.d.ts +6 -0
  44. package/dist/orm/decorators/events.decorator.js +76 -0
  45. package/dist/orm/decorators/foreignkey.decorator.d.ts +2 -0
  46. package/dist/orm/decorators/foreignkey.decorator.js +13 -0
  47. package/dist/orm/decorators/index.decorator.d.ts +3 -0
  48. package/dist/orm/decorators/index.decorator.js +22 -0
  49. package/dist/orm/decorators/link.decorator.d.ts +23 -0
  50. package/dist/orm/decorators/link.decorator.js +88 -0
  51. package/dist/orm/decorators/primarykey.decorator.d.ts +3 -0
  52. package/dist/orm/decorators/primarykey.decorator.js +23 -0
  53. package/dist/orm/decorators/transform.decorator.d.ts +3 -0
  54. package/dist/orm/decorators/transform.decorator.js +24 -0
  55. package/dist/orm/model/abstract-entityelement.d.ts +8 -0
  56. package/dist/orm/model/abstract-entityelement.js +10 -0
  57. package/dist/orm/model/association-node.d.ts +9 -0
  58. package/dist/orm/model/association-node.js +25 -0
  59. package/dist/orm/model/association.d.ts +28 -0
  60. package/dist/orm/model/association.js +129 -0
  61. package/dist/orm/model/entity-association-element.d.ts +9 -0
  62. package/dist/orm/model/entity-association-element.js +13 -0
  63. package/dist/orm/model/entity-column-element.d.ts +68 -0
  64. package/dist/orm/model/entity-column-element.js +27 -0
  65. package/dist/orm/model/entity-model.d.ts +59 -0
  66. package/dist/orm/model/entity-model.js +295 -0
  67. package/dist/orm/model/entity-object-element.d.ts +12 -0
  68. package/dist/orm/model/entity-object-element.js +24 -0
  69. package/dist/orm/model/index-meta.d.ts +9 -0
  70. package/dist/orm/model/index-meta.js +16 -0
  71. package/dist/orm/model/link-chain.d.ts +15 -0
  72. package/dist/orm/model/link-chain.js +50 -0
  73. package/dist/orm/orm.const.d.ts +2 -0
  74. package/dist/orm/orm.const.js +5 -0
  75. package/dist/orm/orm.type.d.ts +112 -0
  76. package/dist/orm/orm.type.js +2 -0
  77. package/dist/orm/repository.class.d.ts +125 -0
  78. package/dist/orm/repository.class.js +217 -0
  79. package/dist/orm/util/entity-mapping.d.ts +12 -0
  80. package/dist/orm/util/entity-mapping.js +154 -0
  81. package/dist/orm/util/extract-keyvalues.d.ts +2 -0
  82. package/dist/orm/util/extract-keyvalues.js +60 -0
  83. package/dist/orm/util/orm.helper.d.ts +14 -0
  84. package/dist/orm/util/orm.helper.js +39 -0
  85. package/dist/orm/util/serialize-element.d.ts +2 -0
  86. package/dist/orm/util/serialize-element.js +43 -0
  87. package/dist/types.d.ts +2 -0
  88. package/dist/types.js +2 -0
  89. package/package.json +3 -3
@@ -0,0 +1,165 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SqbClient = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const lightning_pool_1 = require("lightning-pool");
6
+ const putil_varhelpers_1 = require("putil-varhelpers");
7
+ const strict_typed_events_1 = require("strict-typed-events");
8
+ const debug_1 = tslib_1.__importDefault(require("debug"));
9
+ const SqbConnection_1 = require("./SqbConnection");
10
+ const extensions_1 = require("./extensions");
11
+ const repository_class_1 = require("../orm/repository.class");
12
+ const entity_model_1 = require("../orm/model/entity-model");
13
+ const debug = (0, debug_1.default)('sqb:client');
14
+ const inspect = Symbol.for('nodejs.util.inspect.custom');
15
+ class SqbClient extends (0, strict_typed_events_1.TypedEventEmitterClass)(strict_typed_events_1.AsyncEventEmitter) {
16
+ constructor(config) {
17
+ super();
18
+ this._entities = {};
19
+ if (!(config && typeof config === 'object'))
20
+ throw new TypeError('Configuration object required');
21
+ let adapter;
22
+ if (config.driver) {
23
+ adapter = extensions_1.adapters.find(x => x.driver === config.driver);
24
+ if (!adapter)
25
+ throw new Error(`No database adapter registered for "${config.driver}" driver`);
26
+ }
27
+ else if (config.dialect) {
28
+ adapter = extensions_1.adapters.find(x => x.dialect === config.dialect);
29
+ if (!adapter)
30
+ throw new Error(`No database adapter registered for "${config.dialect}" dialect`);
31
+ }
32
+ if (!adapter)
33
+ throw new Error(`You must provide one of "driver" or "dialect" properties`);
34
+ this._adapter = adapter;
35
+ this._defaults = config.defaults || {};
36
+ const poolOptions = {};
37
+ const popts = config.pool || {};
38
+ poolOptions.acquireMaxRetries = (0, putil_varhelpers_1.coerceToInt)(popts.acquireMaxRetries, 0);
39
+ poolOptions.acquireRetryWait = (0, putil_varhelpers_1.coerceToInt)(popts.acquireRetryWait, 2000);
40
+ poolOptions.acquireTimeoutMillis = (0, putil_varhelpers_1.coerceToInt)(popts.acquireTimeoutMillis, 0);
41
+ poolOptions.idleTimeoutMillis = (0, putil_varhelpers_1.coerceToInt)(popts.idleTimeoutMillis, 30000);
42
+ poolOptions.max = (0, putil_varhelpers_1.coerceToInt)(popts.max, 10);
43
+ poolOptions.maxQueue = (0, putil_varhelpers_1.coerceToInt)(popts.maxQueue, 1000);
44
+ poolOptions.max = (0, putil_varhelpers_1.coerceToInt)(popts.max, 10);
45
+ poolOptions.min = (0, putil_varhelpers_1.coerceToInt)(popts.min, 0);
46
+ poolOptions.minIdle = (0, putil_varhelpers_1.coerceToInt)(popts.minIdle, 0);
47
+ poolOptions.validation = (0, putil_varhelpers_1.coerceToBoolean)(popts.validation, false);
48
+ const cfg = { ...config };
49
+ const poolFactory = {
50
+ create: () => adapter.connect(cfg),
51
+ destroy: instance => instance.close(),
52
+ reset: instance => instance.reset(),
53
+ validate: instance => instance.test()
54
+ };
55
+ this._pool = (0, lightning_pool_1.createPool)(poolFactory, poolOptions);
56
+ this._pool.on('closing', () => this.emit('closing'));
57
+ this._pool.on('close', () => this.emit('close'));
58
+ this._pool.on('terminate', () => this.emit('terminate'));
59
+ // @ts-ignore
60
+ this._pool.on('error', (...args) => this.emit('error', ...args));
61
+ }
62
+ get defaults() {
63
+ return this._defaults;
64
+ }
65
+ /**
66
+ * Returns dialect
67
+ */
68
+ get dialect() {
69
+ return this._adapter.dialect;
70
+ }
71
+ /**
72
+ * Returns database driver name
73
+ */
74
+ get driver() {
75
+ return this._adapter.driver;
76
+ }
77
+ /**
78
+ * Returns true if pool is closed
79
+ */
80
+ get isClosed() {
81
+ return this._pool.state === lightning_pool_1.PoolState.CLOSED;
82
+ }
83
+ get pool() {
84
+ return this._pool;
85
+ }
86
+ async acquire(arg0, arg1) {
87
+ debug('acquire');
88
+ if (typeof arg0 === 'function') {
89
+ const connection = await this.acquire(arg1);
90
+ try {
91
+ return await arg0(connection);
92
+ }
93
+ finally {
94
+ connection.release();
95
+ }
96
+ }
97
+ const options = arg1;
98
+ const adapterConnection = await this._pool.acquire();
99
+ const opts = { autoCommit: this.defaults.autoCommit, ...options };
100
+ const connection = new SqbConnection_1.SqbConnection(this, adapterConnection, opts);
101
+ await this.emitAsyncSerial('acquire', connection);
102
+ connection.on('execute', (request) => this.emit('execute', request));
103
+ connection.on('error', (error) => this.emit('error', error));
104
+ return connection;
105
+ }
106
+ /**
107
+ * Shuts down the pool and destroys all resources.
108
+ */
109
+ async close(terminateWait) {
110
+ const ms = terminateWait == null ? Infinity : 0;
111
+ return this._pool.close(ms);
112
+ }
113
+ async execute(query, options) {
114
+ debug('execute');
115
+ const connection = await this.acquire();
116
+ try {
117
+ const qr = await connection.execute(query, options);
118
+ if (qr && qr.cursor) {
119
+ connection.retain();
120
+ qr.cursor.once('close', () => connection.release());
121
+ }
122
+ return qr;
123
+ }
124
+ finally {
125
+ connection.release();
126
+ }
127
+ }
128
+ /**
129
+ * Tests the pool
130
+ */
131
+ async test() {
132
+ const connection = await this.acquire();
133
+ try {
134
+ await connection.test();
135
+ }
136
+ finally {
137
+ connection.release();
138
+ }
139
+ }
140
+ getRepository(entity, opts) {
141
+ let ctor;
142
+ if (typeof entity === 'string') {
143
+ ctor = this.getEntity(entity);
144
+ if (!ctor)
145
+ throw new Error(`Repository "${entity}" is not registered`);
146
+ }
147
+ else
148
+ ctor = entity;
149
+ const entityDef = entity_model_1.EntityModel.get(ctor);
150
+ if (!entityDef)
151
+ throw new Error(`You must provide an @Entity annotated constructor`);
152
+ return new repository_class_1.Repository(entityDef, this, opts?.schema);
153
+ }
154
+ getEntity(name) {
155
+ return this._entities[name];
156
+ }
157
+ toString() {
158
+ return '[object ' + Object.getPrototypeOf(this).constructor.name + '(' +
159
+ this.dialect + ')]';
160
+ }
161
+ [inspect]() {
162
+ return this.toString();
163
+ }
164
+ }
165
+ exports.SqbClient = SqbClient;
@@ -0,0 +1,74 @@
1
+ import { classes } from '@sqb/builder';
2
+ import { Type } from 'ts-gems';
3
+ import { SqbClient } from './SqbClient';
4
+ import { ConnectionOptions, QueryExecuteOptions, QueryRequest } from './types';
5
+ import { Adapter } from './Adapter';
6
+ import { Repository } from '../orm/repository.class';
7
+ interface SqbConnectionEvents {
8
+ close: () => void;
9
+ execute: (request: QueryRequest) => void;
10
+ error: (error: Error) => void;
11
+ retain: (refCount: number) => void;
12
+ release: (refCount: number) => void;
13
+ 'start-transaction': () => void;
14
+ 'set-savepoint': () => void;
15
+ 'release-savepoint': () => void;
16
+ 'rollback-savepoint': () => void;
17
+ commit: () => void;
18
+ rollback: () => void;
19
+ }
20
+ declare const SqbConnection_base: Type<import("strict-typed-events").TypedEventEmitter<any, SqbConnectionEvents, SqbConnectionEvents>>;
21
+ export declare class SqbConnection extends SqbConnection_base {
22
+ readonly client: SqbClient;
23
+ private _intlcon?;
24
+ private readonly _tasks;
25
+ private readonly _options?;
26
+ private _inTransaction;
27
+ private _refCount;
28
+ constructor(client: SqbClient, adapterConnection: Adapter.Connection, options?: ConnectionOptions);
29
+ /**
30
+ * Returns session id
31
+ */
32
+ get sessionId(): string;
33
+ /**
34
+ * Returns reference counter value
35
+ */
36
+ get refCount(): number;
37
+ /**
38
+ * Returns true if transaction started
39
+ */
40
+ get inTransaction(): boolean;
41
+ /**
42
+ * Increases internal reference counter to keep session alive
43
+ */
44
+ retain(): void;
45
+ /**
46
+ * Decreases the internal reference counter.
47
+ * When reference count is 0, connection returns to the pool.
48
+ * Returns true if connection released.
49
+ */
50
+ release(): boolean;
51
+ /**
52
+ * Immediately releases the connection.
53
+ */
54
+ close(): Promise<void>;
55
+ execute(query: string | classes.Query, options?: QueryExecuteOptions): Promise<any>;
56
+ getRepository<T>(entity: Type<T> | string, opts?: {
57
+ schema?: string;
58
+ }): Repository<T>;
59
+ getSchema(): Promise<string>;
60
+ setSchema(schema: string): Promise<void>;
61
+ /**
62
+ * Executes a query
63
+ */
64
+ protected _execute(query: string | classes.Query, options?: QueryExecuteOptions): Promise<any>;
65
+ startTransaction(): Promise<void>;
66
+ commit(): Promise<void>;
67
+ rollback(): Promise<void>;
68
+ setSavepoint(savepoint: string): Promise<void>;
69
+ releaseSavepoint(savepoint: string): Promise<void>;
70
+ rollbackSavepoint(savepoint: string): Promise<void>;
71
+ test(): Promise<void>;
72
+ private _prepareQueryRequest;
73
+ }
74
+ export {};
@@ -0,0 +1,272 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SqbConnection = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const builder_1 = require("@sqb/builder");
6
+ const strict_typed_events_1 = require("strict-typed-events");
7
+ const assert_1 = tslib_1.__importDefault(require("assert"));
8
+ const debug_1 = tslib_1.__importDefault(require("debug"));
9
+ const putil_varhelpers_1 = require("putil-varhelpers");
10
+ const putil_taskqueue_1 = tslib_1.__importDefault(require("putil-taskqueue"));
11
+ const helpers_1 = require("./helpers");
12
+ const Cursor_1 = require("./Cursor");
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:connection');
16
+ class SqbConnection extends (0, strict_typed_events_1.TypedEventEmitterClass)(strict_typed_events_1.AsyncEventEmitter) {
17
+ constructor(client, adapterConnection, options) {
18
+ super();
19
+ this.client = client;
20
+ this._tasks = new putil_taskqueue_1.default();
21
+ this._inTransaction = false;
22
+ this._refCount = 1;
23
+ this._intlcon = adapterConnection;
24
+ this._options = options || {};
25
+ }
26
+ /**
27
+ * Returns session id
28
+ */
29
+ get sessionId() {
30
+ return this._intlcon && this._intlcon.sessionId;
31
+ }
32
+ /**
33
+ * Returns reference counter value
34
+ */
35
+ get refCount() {
36
+ return this._refCount;
37
+ }
38
+ /**
39
+ * Returns true if transaction started
40
+ */
41
+ get inTransaction() {
42
+ if (this._intlcon && typeof this._intlcon.getInTransaction === 'function') {
43
+ this._inTransaction = this._intlcon.getInTransaction();
44
+ }
45
+ return this._inTransaction;
46
+ }
47
+ /**
48
+ * Increases internal reference counter to keep session alive
49
+ */
50
+ retain() {
51
+ this._refCount++;
52
+ debug('[%s] retain | refCount: %s', this.sessionId, this._refCount);
53
+ this.emit('retain', this._refCount);
54
+ }
55
+ /**
56
+ * Decreases the internal reference counter.
57
+ * When reference count is 0, connection returns to the pool.
58
+ * Returns true if connection released.
59
+ */
60
+ release() {
61
+ if (!this._intlcon)
62
+ return true;
63
+ const ref = --this._refCount;
64
+ this.emit('release', this._refCount);
65
+ debug('[%s] release | refCount: %s', this.sessionId, ref);
66
+ if (!ref) {
67
+ this.close().catch(() => 0);
68
+ return true;
69
+ }
70
+ return false;
71
+ }
72
+ /**
73
+ * Immediately releases the connection.
74
+ */
75
+ async close() {
76
+ if (!this._intlcon)
77
+ return;
78
+ await this.emitAsyncSerial('close');
79
+ const intlcon = this._intlcon;
80
+ this._intlcon = undefined;
81
+ this.client.pool.release(intlcon)
82
+ .catch(e => this.client.emit('error', e));
83
+ debug('[%s] closed', intlcon.sessionId);
84
+ }
85
+ async execute(query, options) {
86
+ if (!this._intlcon)
87
+ throw new Error(`Can't execute query, because connection is released`);
88
+ return this._tasks.enqueue(() => this._execute(query, options));
89
+ }
90
+ getRepository(entity, opts) {
91
+ let ctor;
92
+ if (typeof entity === 'string') {
93
+ ctor = this.client.getEntity(entity);
94
+ if (!ctor)
95
+ throw new Error(`Repository "${entity}" is not registered`);
96
+ }
97
+ else
98
+ ctor = entity;
99
+ const entityDef = entity_model_1.EntityModel.get(ctor);
100
+ if (!entityDef)
101
+ throw new Error(`You must provide an @Entity annotated constructor`);
102
+ return new repository_class_1.Repository(entityDef, this, opts?.schema);
103
+ }
104
+ async getSchema() {
105
+ assert_1.default.ok(this._intlcon, `Can't set schema, because connection is released`);
106
+ assert_1.default.ok(this._intlcon.getSchema, `${this.client.dialect} adapter does have Schema support`);
107
+ return await this._intlcon.getSchema();
108
+ }
109
+ async setSchema(schema) {
110
+ assert_1.default.ok(this._intlcon, `Can't set schema, because connection is released`);
111
+ assert_1.default.ok(this._intlcon.setSchema, `${this.client.dialect} adapter does have Schema support`);
112
+ await this._intlcon.setSchema(schema);
113
+ }
114
+ /**
115
+ * Executes a query
116
+ */
117
+ async _execute(query, options) {
118
+ assert_1.default.ok(this._intlcon, `Can't execute query, because connection is released`);
119
+ const intlcon = this._intlcon;
120
+ this.retain();
121
+ try {
122
+ const startTime = Date.now();
123
+ const request = this._prepareQueryRequest(query, options);
124
+ debug('[%s] execute | %o', this.sessionId, request);
125
+ this.emit('execute', request);
126
+ // Call execute hooks
127
+ if (request.executeHooks) {
128
+ for (const fn of request.executeHooks) {
129
+ await fn(this, request);
130
+ }
131
+ }
132
+ const response = await intlcon.execute(request);
133
+ if (!response)
134
+ throw new Error('Database adapter returned an empty response');
135
+ const result = {
136
+ executeTime: Date.now() - startTime
137
+ };
138
+ if (request.showSql)
139
+ result.query = request;
140
+ if (response.rows || response.cursor) {
141
+ if (!response.fields)
142
+ throw new Error('Adapter did not returned fields info');
143
+ if (!response.rowType)
144
+ throw new Error('Adapter did not returned rowType');
145
+ result.fields = (0, helpers_1.wrapAdapterFields)(response.fields, request.fieldNaming);
146
+ result.rowType = response.rowType;
147
+ if (response.rows) {
148
+ result.rows = request.objectRows ?
149
+ (0, helpers_1.normalizeRowsToObjectRows)(result.fields, response.rowType, response.rows, request) :
150
+ (0, helpers_1.normalizeRowsToArrayRows)(result.fields, response.rowType, response.rows, request);
151
+ (0, helpers_1.callFetchHooks)(result.rows, request);
152
+ }
153
+ else if (response.cursor) {
154
+ const cursor = result.cursor = new Cursor_1.Cursor(this, result.fields, response.cursor, request);
155
+ const hook = () => cursor.close();
156
+ cursor.once('close', () => this.off('close', hook));
157
+ this.on('close', hook);
158
+ }
159
+ }
160
+ if (response.rowsAffected)
161
+ result.rowsAffected = response.rowsAffected;
162
+ return result;
163
+ }
164
+ finally {
165
+ this.release();
166
+ }
167
+ }
168
+ async startTransaction() {
169
+ if (!this._intlcon)
170
+ throw new Error('Can not call startTransaction() on a released connection');
171
+ await this._intlcon.startTransaction();
172
+ this._inTransaction = true;
173
+ this.emit('start-transaction');
174
+ }
175
+ async commit() {
176
+ if (!this._intlcon)
177
+ throw new Error('Can not call commit() on a released connection');
178
+ await this._intlcon.commit();
179
+ this._inTransaction = false;
180
+ this.emit('commit');
181
+ }
182
+ async rollback() {
183
+ if (!this._intlcon)
184
+ throw new Error('Can not call rollback() on a released connection');
185
+ await this._intlcon.rollback();
186
+ this._inTransaction = false;
187
+ this.emit('rollback');
188
+ }
189
+ async setSavepoint(savepoint) {
190
+ if (!this._intlcon)
191
+ throw new Error('Can not call setSavepoint() on a released connection');
192
+ if (typeof this._intlcon.setSavepoint !== 'function')
193
+ throw new Error(this.client.driver + ' does not support setSavepoint method');
194
+ if (!this.inTransaction)
195
+ await this.startTransaction();
196
+ await this._intlcon.setSavepoint(savepoint);
197
+ this.emit('set-savepoint');
198
+ }
199
+ async releaseSavepoint(savepoint) {
200
+ if (!this._intlcon)
201
+ throw new Error('Can not call releaseSavepoint() on a released connection');
202
+ if (typeof this._intlcon.releaseSavepoint !== 'function')
203
+ throw new Error(this.client.driver + ' does not support releaseSavepoint method');
204
+ await this._intlcon.releaseSavepoint(savepoint);
205
+ this.emit('release-savepoint');
206
+ }
207
+ async rollbackSavepoint(savepoint) {
208
+ if (!this._intlcon)
209
+ throw new Error('Can not call rollbackSavepoint() on a released connection');
210
+ if (typeof this._intlcon.rollbackSavepoint !== 'function')
211
+ throw new Error(this.client.driver + ' does not support rollbackSavepoint method');
212
+ await this._intlcon.rollbackSavepoint(savepoint);
213
+ this.emit('rollback-savepoint');
214
+ }
215
+ async test() {
216
+ if (!this._intlcon)
217
+ throw new Error('Can not call test() on a released connection');
218
+ await this._intlcon.test();
219
+ }
220
+ _prepareQueryRequest(query, options = {}) {
221
+ if (!this._intlcon)
222
+ throw new Error('Session released');
223
+ const defaults = this.client.defaults;
224
+ const request = {
225
+ dialect: this.client.dialect,
226
+ sql: '',
227
+ autoCommit: this.inTransaction ? false :
228
+ (0, putil_varhelpers_1.coerceToBoolean)((0, putil_varhelpers_1.coalesce)(options.autoCommit, this._options?.autoCommit, defaults.autoCommit), true),
229
+ cursor: (0, putil_varhelpers_1.coerceToBoolean)((0, putil_varhelpers_1.coalesce)(options.cursor, defaults.cursor), false),
230
+ objectRows: (0, putil_varhelpers_1.coerceToBoolean)((0, putil_varhelpers_1.coalesce)(options.objectRows, defaults.objectRows), true),
231
+ ignoreNulls: (0, putil_varhelpers_1.coerceToBoolean)((0, putil_varhelpers_1.coalesce)(options.ignoreNulls, defaults.ignoreNulls), false),
232
+ fetchRows: (0, putil_varhelpers_1.coerceToInt)((0, putil_varhelpers_1.coalesce)(options.fetchRows, defaults.fetchRows), 100),
233
+ fieldNaming: (0, putil_varhelpers_1.coalesce)(options.namingStrategy, defaults.fieldNaming),
234
+ transform: (0, putil_varhelpers_1.coalesce)(options.transform, defaults.transform),
235
+ showSql: (0, putil_varhelpers_1.coerceToBoolean)((0, putil_varhelpers_1.coalesce)(options.showSql, defaults.showSql), false),
236
+ prettyPrint: (0, putil_varhelpers_1.coerceToBoolean)((0, putil_varhelpers_1.coalesce)(options.prettyPrint, defaults.prettyPrint), false),
237
+ action: (0, putil_varhelpers_1.coerceToString)(options.action),
238
+ fetchAsString: options.fetchAsString
239
+ };
240
+ request.ignoreNulls = request.ignoreNulls && request.objectRows;
241
+ if (query instanceof builder_1.classes.Query) {
242
+ if (this._intlcon.onGenerateQuery)
243
+ this._intlcon.onGenerateQuery(request, query);
244
+ const q = query
245
+ .generate({
246
+ dialect: request.dialect,
247
+ dialectVersion: request.dialectVersion,
248
+ params: options.params,
249
+ strictParams: true,
250
+ prettyPrint: request.prettyPrint
251
+ });
252
+ request.sql = q.sql;
253
+ request.params = q.params;
254
+ request.paramOptions = q.paramOptions;
255
+ if (q.returningFields)
256
+ request.returningFields = q.returningFields;
257
+ if (query.listenerCount('execute'))
258
+ request.executeHooks = query.listeners('execute');
259
+ if (query.listenerCount('fetch'))
260
+ request.fetchHooks = query.listeners('fetch');
261
+ }
262
+ else if (typeof query === 'string') {
263
+ request.sql = query;
264
+ request.params = options.params;
265
+ }
266
+ // @ts-ignore
267
+ if (!request.sql)
268
+ throw new Error('No sql given');
269
+ return request;
270
+ }
271
+ }
272
+ exports.SqbConnection = SqbConnection;
@@ -0,0 +1,4 @@
1
+ import { Adapter } from './Adapter';
2
+ export declare let adapters: Adapter[];
3
+ export declare function registerAdapter(adapter: Adapter): void;
4
+ export declare function unRegisterAdapter(...adapter: Adapter[]): void;
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.unRegisterAdapter = exports.registerAdapter = exports.adapters = void 0;
4
+ exports.adapters = [];
5
+ function registerAdapter(adapter) {
6
+ if (!adapter.driver)
7
+ throw new TypeError('A DatabaseAdapter must contain "driver" property');
8
+ exports.adapters.push(adapter);
9
+ }
10
+ exports.registerAdapter = registerAdapter;
11
+ function unRegisterAdapter(...adapter) {
12
+ exports.adapters = exports.adapters.filter(x => !adapter.includes(x));
13
+ }
14
+ exports.unRegisterAdapter = unRegisterAdapter;
@@ -0,0 +1,9 @@
1
+ import { Maybe } from 'ts-gems';
2
+ import { ArrayRowset, FieldNaming, ObjectRowset, QueryRequest } from './types';
3
+ import { FieldInfoMap } from './FieldInfoMap';
4
+ import { Adapter } from './Adapter';
5
+ export declare function applyNamingStrategy(value: string, namingStrategy?: FieldNaming): Maybe<string>;
6
+ export declare function wrapAdapterFields(oldFields: Adapter.Field[], fieldNaming?: FieldNaming): FieldInfoMap;
7
+ export declare function normalizeRowsToObjectRows(fields: FieldInfoMap, rowType: 'array' | 'object', oldRows: ObjectRowset | ArrayRowset, options?: Pick<QueryRequest, 'ignoreNulls' | 'transform'>): Record<string, any>[];
8
+ export declare function normalizeRowsToArrayRows(fields: FieldInfoMap, rowType: 'array' | 'object', oldRows: ObjectRowset | ArrayRowset, options?: Pick<QueryRequest, 'ignoreNulls' | 'transform'>): any[][];
9
+ export declare function callFetchHooks(rows: ObjectRowset | ArrayRowset, request: QueryRequest): void;
@@ -0,0 +1,133 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.callFetchHooks = exports.normalizeRowsToArrayRows = exports.normalizeRowsToObjectRows = exports.wrapAdapterFields = exports.applyNamingStrategy = void 0;
4
+ const putil_varhelpers_1 = require("putil-varhelpers");
5
+ const FieldInfoMap_1 = require("./FieldInfoMap");
6
+ function applyNamingStrategy(value, namingStrategy) {
7
+ if (typeof namingStrategy === 'string' && namingStrategy !== 'original') {
8
+ switch (namingStrategy.toLowerCase()) {
9
+ case 'lowercase':
10
+ return value.toLowerCase();
11
+ case 'uppercase':
12
+ return value.toUpperCase();
13
+ case 'camelcase':
14
+ if (!value.match(/[a-z]/))
15
+ return (0, putil_varhelpers_1.camelCase)(value.toLowerCase());
16
+ value = (0, putil_varhelpers_1.camelCase)(value);
17
+ return value[0].toLowerCase() + value.substring(1);
18
+ case 'pascalcase':
19
+ if (!value.match(/[a-z]/))
20
+ return (0, putil_varhelpers_1.pascalCase)(value.toLowerCase());
21
+ return (0, putil_varhelpers_1.pascalCase)(value);
22
+ }
23
+ }
24
+ else if (typeof namingStrategy === 'function')
25
+ return namingStrategy(value);
26
+ return value;
27
+ }
28
+ exports.applyNamingStrategy = applyNamingStrategy;
29
+ function wrapAdapterFields(oldFields, fieldNaming) {
30
+ const mapFieldInfo = (f, index) => {
31
+ const name = applyNamingStrategy(f.fieldName, fieldNaming);
32
+ if (name)
33
+ return { ...f, name, index };
34
+ };
35
+ const result = new FieldInfoMap_1.FieldInfoMap();
36
+ let i = 0;
37
+ oldFields.forEach(f => {
38
+ const x = mapFieldInfo(f, i);
39
+ if (x) {
40
+ i++;
41
+ result.add(x);
42
+ }
43
+ });
44
+ return result;
45
+ }
46
+ exports.wrapAdapterFields = wrapAdapterFields;
47
+ function normalizeRowsToObjectRows(fields, rowType, oldRows, options) {
48
+ return normalizeRows(fields, rowType, oldRows, { ...options, objectRows: true });
49
+ }
50
+ exports.normalizeRowsToObjectRows = normalizeRowsToObjectRows;
51
+ function normalizeRowsToArrayRows(fields, rowType, oldRows, options) {
52
+ return normalizeRows(fields, rowType, oldRows, { ...options, objectRows: false });
53
+ }
54
+ exports.normalizeRowsToArrayRows = normalizeRowsToArrayRows;
55
+ function normalizeRows(fields, rowType, oldRows, options) {
56
+ const ignoreNulls = options.ignoreNulls && options.objectRows;
57
+ const transform = options.transform;
58
+ const coerceValue = (v, f) => {
59
+ if (v === undefined)
60
+ return;
61
+ if (transform)
62
+ v = transform(v, f);
63
+ if (v === null && ignoreNulls)
64
+ return;
65
+ return v;
66
+ };
67
+ if (options.objectRows) {
68
+ if (rowType === 'array') {
69
+ return oldRows.map((row) => {
70
+ const r = {};
71
+ for (const f of fields.values()) {
72
+ const v = coerceValue(row[f.index], f);
73
+ if (v !== undefined)
74
+ r[f.name] = v;
75
+ }
76
+ return r;
77
+ });
78
+ }
79
+ let hasFieldNaming = false;
80
+ for (const f of fields.values()) {
81
+ if (f.name !== f.fieldName) {
82
+ hasFieldNaming = true;
83
+ break;
84
+ }
85
+ }
86
+ if (hasFieldNaming || transform) {
87
+ return oldRows.map((row) => {
88
+ const r = {};
89
+ for (const f of fields.values()) {
90
+ const v = coerceValue(row[f.fieldName], f);
91
+ if (v !== undefined)
92
+ r[f.name] = v;
93
+ }
94
+ return r;
95
+ });
96
+ }
97
+ if (ignoreNulls) {
98
+ oldRows.forEach(row => {
99
+ for (const [k, v] of Object.entries(row)) {
100
+ if (v === null)
101
+ delete row[k];
102
+ }
103
+ });
104
+ }
105
+ return oldRows;
106
+ }
107
+ if (rowType === 'array') {
108
+ oldRows.forEach((row) => {
109
+ for (const [i, v] of row.entries()) {
110
+ row[i] = coerceValue(v, fields.get(i));
111
+ }
112
+ });
113
+ return oldRows;
114
+ }
115
+ return oldRows.map((row) => {
116
+ const r = [];
117
+ for (const f of fields.values()) {
118
+ r[f.index] = coerceValue(row[f.fieldName], f);
119
+ }
120
+ return r;
121
+ });
122
+ }
123
+ function callFetchHooks(rows, request) {
124
+ const fetchHooks = request.fetchHooks;
125
+ if (!fetchHooks)
126
+ return;
127
+ for (const row of rows) {
128
+ for (const fn of fetchHooks) {
129
+ fn(row, request);
130
+ }
131
+ }
132
+ }
133
+ exports.callFetchHooks = callFetchHooks;