@sqb/connect 4.0.5 → 4.0.8

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 -13
  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,74 +0,0 @@
1
- import { classes } from '@sqb/builder';
2
- import { AsyncEventEmitter } from 'strict-typed-events';
3
- import { Type } from 'ts-gems';
4
- import { SqbClient } from './SqbClient';
5
- import { ConnectionOptions, QueryExecuteOptions, QueryRequest } from './types';
6
- import { Adapter } from './Adapter';
7
- import { Repository } from '../orm/repository.class';
8
- interface SqbConnectionEvents {
9
- close: () => void;
10
- execute: (request: QueryRequest) => void;
11
- error: (error: Error) => void;
12
- retain: (refCount: number) => void;
13
- release: (refCount: number) => void;
14
- 'start-transaction': () => void;
15
- 'set-savepoint': () => void;
16
- 'release-savepoint': () => void;
17
- 'rollback-savepoint': () => void;
18
- commit: () => void;
19
- rollback: () => void;
20
- }
21
- export declare class SqbConnection extends AsyncEventEmitter<SqbConnectionEvents> {
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 {};
@@ -1,274 +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.SqbConnection = void 0;
7
- const builder_1 = require("@sqb/builder");
8
- const strict_typed_events_1 = require("strict-typed-events");
9
- const assert_1 = __importDefault(require("assert"));
10
- const debug_1 = __importDefault(require("debug"));
11
- const putil_varhelpers_1 = require("putil-varhelpers");
12
- const putil_taskqueue_1 = __importDefault(require("putil-taskqueue"));
13
- const helpers_1 = require("./helpers");
14
- const Cursor_1 = require("./Cursor");
15
- const repository_class_1 = require("../orm/repository.class");
16
- const entity_model_1 = require("../orm/model/entity-model");
17
- const debug = (0, debug_1.default)('sqb:connection');
18
- class SqbConnection extends strict_typed_events_1.AsyncEventEmitter {
19
- constructor(client, adapterConnection, options) {
20
- super();
21
- this.client = client;
22
- this._tasks = new putil_taskqueue_1.default();
23
- this._inTransaction = false;
24
- this._refCount = 1;
25
- this._intlcon = adapterConnection;
26
- this._options = options || {};
27
- }
28
- /**
29
- * Returns session id
30
- */
31
- get sessionId() {
32
- return this._intlcon && this._intlcon.sessionId;
33
- }
34
- /**
35
- * Returns reference counter value
36
- */
37
- get refCount() {
38
- return this._refCount;
39
- }
40
- /**
41
- * Returns true if transaction started
42
- */
43
- get inTransaction() {
44
- if (this._intlcon && typeof this._intlcon.getInTransaction === 'function') {
45
- this._inTransaction = this._intlcon.getInTransaction();
46
- }
47
- return this._inTransaction;
48
- }
49
- /**
50
- * Increases internal reference counter to keep session alive
51
- */
52
- retain() {
53
- this._refCount++;
54
- debug('[%s] retain | refCount: %s', this.sessionId, this._refCount);
55
- this.emit('retain', this._refCount);
56
- }
57
- /**
58
- * Decreases the internal reference counter.
59
- * When reference count is 0, connection returns to the pool.
60
- * Returns true if connection released.
61
- */
62
- release() {
63
- if (!this._intlcon)
64
- return true;
65
- const ref = --this._refCount;
66
- this.emit('release', this._refCount);
67
- debug('[%s] release | refCount: %s', this.sessionId, ref);
68
- if (!ref) {
69
- this.close().catch(() => 0);
70
- return true;
71
- }
72
- return false;
73
- }
74
- /**
75
- * Immediately releases the connection.
76
- */
77
- async close() {
78
- if (!this._intlcon)
79
- return;
80
- await this.emitAsync({ event: 'close', serial: true });
81
- const intlcon = this._intlcon;
82
- this._intlcon = undefined;
83
- this.client.pool.release(intlcon)
84
- .catch(e => this.client.emit('error', e));
85
- debug('[%s] closed', intlcon.sessionId);
86
- }
87
- async execute(query, options) {
88
- if (!this._intlcon)
89
- throw new Error(`Can't execute query, because connection is released`);
90
- return this._tasks.enqueue(() => this._execute(query, options));
91
- }
92
- getRepository(entity, opts) {
93
- let ctor;
94
- if (typeof entity === 'string') {
95
- ctor = this.client.getEntity(entity);
96
- if (!ctor)
97
- throw new Error(`Repository "${entity}" is not registered`);
98
- }
99
- else
100
- ctor = entity;
101
- const entityDef = entity_model_1.EntityModel.get(ctor);
102
- if (!entityDef)
103
- throw new Error(`You must provide an @Entity annotated constructor`);
104
- return new repository_class_1.Repository(entityDef, this, opts?.schema);
105
- }
106
- async getSchema() {
107
- assert_1.default.ok(this._intlcon, `Can't set schema, because connection is released`);
108
- assert_1.default.ok(this._intlcon.getSchema, `${this.client.dialect} adapter does have Schema support`);
109
- return await this._intlcon.getSchema();
110
- }
111
- async setSchema(schema) {
112
- assert_1.default.ok(this._intlcon, `Can't set schema, because connection is released`);
113
- assert_1.default.ok(this._intlcon.setSchema, `${this.client.dialect} adapter does have Schema support`);
114
- await this._intlcon.setSchema(schema);
115
- }
116
- /**
117
- * Executes a query
118
- */
119
- async _execute(query, options) {
120
- assert_1.default.ok(this._intlcon, `Can't execute query, because connection is released`);
121
- const intlcon = this._intlcon;
122
- this.retain();
123
- try {
124
- const startTime = Date.now();
125
- const request = this._prepareQueryRequest(query, options);
126
- debug('[%s] execute | %o', this.sessionId, request);
127
- this.emit('execute', request);
128
- // Call execute hooks
129
- if (request.executeHooks) {
130
- for (const fn of request.executeHooks) {
131
- await fn(this, request);
132
- }
133
- }
134
- const response = await intlcon.execute(request);
135
- if (!response)
136
- throw new Error('Database adapter returned an empty response');
137
- const result = {
138
- executeTime: Date.now() - startTime
139
- };
140
- if (request.showSql)
141
- result.query = request;
142
- if (response.rows || response.cursor) {
143
- if (!response.fields)
144
- throw new Error('Adapter did not returned fields info');
145
- if (!response.rowType)
146
- throw new Error('Adapter did not returned rowType');
147
- result.fields = (0, helpers_1.wrapAdapterFields)(response.fields, request.fieldNaming);
148
- result.rowType = response.rowType;
149
- if (response.rows) {
150
- result.rows = request.objectRows ?
151
- (0, helpers_1.normalizeRowsToObjectRows)(result.fields, response.rowType, response.rows, request) :
152
- (0, helpers_1.normalizeRowsToArrayRows)(result.fields, response.rowType, response.rows, request);
153
- (0, helpers_1.callFetchHooks)(result.rows, request);
154
- }
155
- else if (response.cursor) {
156
- const cursor = result.cursor = new Cursor_1.Cursor(this, result.fields, response.cursor, request);
157
- const hook = () => cursor.close();
158
- cursor.once('close', () => this.off('close', hook));
159
- this.on('close', hook);
160
- }
161
- }
162
- if (response.rowsAffected)
163
- result.rowsAffected = response.rowsAffected;
164
- return result;
165
- }
166
- finally {
167
- this.release();
168
- }
169
- }
170
- async startTransaction() {
171
- if (!this._intlcon)
172
- throw new Error('Can not call startTransaction() on a released connection');
173
- await this._intlcon.startTransaction();
174
- this._inTransaction = true;
175
- this.emit('start-transaction');
176
- }
177
- async commit() {
178
- if (!this._intlcon)
179
- throw new Error('Can not call commit() on a released connection');
180
- await this._intlcon.commit();
181
- this._inTransaction = false;
182
- this.emit('commit');
183
- }
184
- async rollback() {
185
- if (!this._intlcon)
186
- throw new Error('Can not call rollback() on a released connection');
187
- await this._intlcon.rollback();
188
- this._inTransaction = false;
189
- this.emit('rollback');
190
- }
191
- async setSavepoint(savepoint) {
192
- if (!this._intlcon)
193
- throw new Error('Can not call setSavepoint() on a released connection');
194
- if (typeof this._intlcon.setSavepoint !== 'function')
195
- throw new Error(this.client.driver + ' does not support setSavepoint method');
196
- if (!this.inTransaction)
197
- await this.startTransaction();
198
- await this._intlcon.setSavepoint(savepoint);
199
- this.emit('set-savepoint');
200
- }
201
- async releaseSavepoint(savepoint) {
202
- if (!this._intlcon)
203
- throw new Error('Can not call releaseSavepoint() on a released connection');
204
- if (typeof this._intlcon.releaseSavepoint !== 'function')
205
- throw new Error(this.client.driver + ' does not support releaseSavepoint method');
206
- await this._intlcon.releaseSavepoint(savepoint);
207
- this.emit('release-savepoint');
208
- }
209
- async rollbackSavepoint(savepoint) {
210
- if (!this._intlcon)
211
- throw new Error('Can not call rollbackSavepoint() on a released connection');
212
- if (typeof this._intlcon.rollbackSavepoint !== 'function')
213
- throw new Error(this.client.driver + ' does not support rollbackSavepoint method');
214
- await this._intlcon.rollbackSavepoint(savepoint);
215
- this.emit('rollback-savepoint');
216
- }
217
- async test() {
218
- if (!this._intlcon)
219
- throw new Error('Can not call test() on a released connection');
220
- await this._intlcon.test();
221
- }
222
- _prepareQueryRequest(query, options = {}) {
223
- if (!this._intlcon)
224
- throw new Error('Session released');
225
- const defaults = this.client.defaults;
226
- const request = {
227
- dialect: this.client.dialect,
228
- sql: '',
229
- autoCommit: this.inTransaction ? false :
230
- (0, putil_varhelpers_1.coerceToBoolean)((0, putil_varhelpers_1.coalesce)(options.autoCommit, this._options?.autoCommit, defaults.autoCommit), true),
231
- cursor: (0, putil_varhelpers_1.coerceToBoolean)((0, putil_varhelpers_1.coalesce)(options.cursor, defaults.cursor), false),
232
- objectRows: (0, putil_varhelpers_1.coerceToBoolean)((0, putil_varhelpers_1.coalesce)(options.objectRows, defaults.objectRows), true),
233
- ignoreNulls: (0, putil_varhelpers_1.coerceToBoolean)((0, putil_varhelpers_1.coalesce)(options.ignoreNulls, defaults.ignoreNulls), false),
234
- fetchRows: (0, putil_varhelpers_1.coerceToInt)((0, putil_varhelpers_1.coalesce)(options.fetchRows, defaults.fetchRows), 100),
235
- fieldNaming: (0, putil_varhelpers_1.coalesce)(options.namingStrategy, defaults.fieldNaming),
236
- transform: (0, putil_varhelpers_1.coalesce)(options.transform, defaults.transform),
237
- showSql: (0, putil_varhelpers_1.coerceToBoolean)((0, putil_varhelpers_1.coalesce)(options.showSql, defaults.showSql), false),
238
- prettyPrint: (0, putil_varhelpers_1.coerceToBoolean)((0, putil_varhelpers_1.coalesce)(options.prettyPrint, defaults.prettyPrint), false),
239
- action: (0, putil_varhelpers_1.coerceToString)(options.action),
240
- fetchAsString: options.fetchAsString
241
- };
242
- request.ignoreNulls = request.ignoreNulls && request.objectRows;
243
- if (query instanceof builder_1.classes.Query) {
244
- if (this._intlcon.onGenerateQuery)
245
- this._intlcon.onGenerateQuery(request, query);
246
- const q = query
247
- .generate({
248
- dialect: request.dialect,
249
- dialectVersion: request.dialectVersion,
250
- params: options.params,
251
- strictParams: true,
252
- prettyPrint: request.prettyPrint
253
- });
254
- request.sql = q.sql;
255
- request.params = q.params;
256
- request.paramOptions = q.paramOptions;
257
- if (q.returningFields)
258
- request.returningFields = q.returningFields;
259
- if (query.listenerCount('execute'))
260
- request.executeHooks = query.listeners('execute');
261
- if (query.listenerCount('fetch'))
262
- request.fetchHooks = query.listeners('fetch');
263
- }
264
- else if (typeof query === 'string') {
265
- request.sql = query;
266
- request.params = options.params;
267
- }
268
- // @ts-ignore
269
- if (!request.sql)
270
- throw new Error('No sql given');
271
- return request;
272
- }
273
- }
274
- exports.SqbConnection = SqbConnection;
@@ -1,4 +0,0 @@
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;
@@ -1,14 +0,0 @@
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;
@@ -1,9 +0,0 @@
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;
@@ -1,133 +0,0 @@
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;