@e-mc/db 0.0.1

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.
@@ -0,0 +1,272 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DB_SOURCE_TYPE = exports.DB_SOURCE_CLIENT = exports.checkTimeout = exports.executeBatchQuery = exports.executeQuery = exports.setCredential = void 0;
4
+ const util_1 = require("../util");
5
+ const mysql_1 = require("../mysql");
6
+ const types_1 = require("../../types");
7
+ const index_1 = require("../index");
8
+ const pool_1 = require("../pool");
9
+ class PostgresPool extends pool_1.default {
10
+ getConnection() {
11
+ return this.client.connect();
12
+ }
13
+ close() {
14
+ return this.client.end();
15
+ }
16
+ isEmpty() {
17
+ return this.closed || this.client.totalCount === 0 && this.client.waitingCount === 0;
18
+ }
19
+ get closed() {
20
+ return this.client.ended;
21
+ }
22
+ }
23
+ const POOL_STATE = {};
24
+ function removePoolProperties(options) {
25
+ if (!options.uuidKey && ('ssl' in options || 'max' in options || 'min' in options || 'idleTimeoutMillis' in options || 'log' in options || 'allowExitOnIdle' in options || 'maxUses' in options)) {
26
+ return { ...options, ssl: (0, types_1.isObject)(options.ssl) ? true : undefined, max: undefined, min: undefined, idleTimeoutMillis: undefined, log: undefined, allowExitOnIdle: undefined, maxUses: undefined };
27
+ }
28
+ return options;
29
+ }
30
+ const getPoolKey = (credential) => (credential.host || '') + '_' + (credential.port || '5432') + (credential.user || '') + '_' + (credential.password || '') + '_' + (credential.database || '') + '_' + (credential.connectionString || '');
31
+ function setCredential(item) {
32
+ let credential = this.getCredential(item);
33
+ if (credential) {
34
+ mysql_1.setAuthentication.call(this, credential);
35
+ }
36
+ else {
37
+ credential = { connectionString: item.uri };
38
+ item.credential = credential;
39
+ }
40
+ if (!credential.connectionString) {
41
+ const errors = [];
42
+ if (!credential.host) {
43
+ errors.push('host');
44
+ }
45
+ if (!credential.user) {
46
+ errors.push('user');
47
+ }
48
+ if (errors.length) {
49
+ throw (0, types_1.errorMessage)("postgres" /* STRINGS.MODULE_NAME */, 'Not defined - ' + errors.join(' | '));
50
+ }
51
+ }
52
+ const usePool = item.usePool;
53
+ if (item.usePool && typeof credential.password !== 'function') {
54
+ let username, password, pool;
55
+ if (typeof usePool === 'string' && (username = credential.user || credential.connectionString && (0, util_1.parseConnectionString)(credential.connectionString)?.username)) {
56
+ [password, pool] = pool_1.default.validateKey(POOL_STATE, username, usePool);
57
+ if (pool) {
58
+ pool.add(item, password);
59
+ return;
60
+ }
61
+ }
62
+ const poolKey = getPoolKey(credential);
63
+ if (!(pool = POOL_STATE[poolKey]) || pool.closed) {
64
+ const { Pool } = require("pg" /* STRINGS.PACKAGE_NAME */);
65
+ const config = this.getPoolConfig("postgres" /* STRINGS.MODULE_NAME */, password);
66
+ if (config) {
67
+ const { min, max, idle } = config;
68
+ if (min >= 0) {
69
+ credential.min ?? (credential.min = min);
70
+ }
71
+ if (max > 0) {
72
+ credential.max ?? (credential.max = max);
73
+ }
74
+ if (idle > 0) {
75
+ credential.idleTimeoutMillis ?? (credential.idleTimeoutMillis = idle);
76
+ }
77
+ }
78
+ new PostgresPool(new Pool(credential), poolKey, username && password ? { username, password } : undefined).add(item).parent = POOL_STATE;
79
+ }
80
+ else {
81
+ pool.add(item);
82
+ }
83
+ }
84
+ else if ('usePool' in item) {
85
+ item.usePool = false;
86
+ }
87
+ }
88
+ exports.setCredential = setCredential;
89
+ async function executeQuery(item, options) {
90
+ return (await executeBatchQuery.call(this, [item], options))[0] || [];
91
+ }
92
+ exports.executeQuery = executeQuery;
93
+ async function executeBatchQuery(batch, options = '', outResult) {
94
+ const length = batch.length;
95
+ if (length === 0) {
96
+ return [];
97
+ }
98
+ const db = require("pg" /* STRINGS.PACKAGE_NAME */);
99
+ let parallel, connectOnce, errorQuery, sessionKey, outCacheMiss;
100
+ if ((0, types_1.isPlainObject)(options)) {
101
+ ({ parallel, connectOnce, errorQuery, sessionKey, outCacheMiss } = options);
102
+ }
103
+ else {
104
+ if (typeof options === 'string') {
105
+ sessionKey = options;
106
+ }
107
+ options = undefined;
108
+ }
109
+ if (length === 1) {
110
+ connectOnce = false;
111
+ parallel = false;
112
+ }
113
+ else if (parallel === undefined) {
114
+ parallel = !batch.some(item => item.parallel === false);
115
+ }
116
+ if (!parallel) {
117
+ outResult || (outResult = new Array(length));
118
+ }
119
+ const caching = this.hasCache("postgres" /* STRINGS.MODULE_NAME */, sessionKey);
120
+ const tasks = new Array(length);
121
+ const clients = [];
122
+ const pools = [];
123
+ let postgresPool, postgresClient, postgresCredential, onceCredential = connectOnce ? batch[0].credential : undefined;
124
+ const getConnection = async (item, credential) => {
125
+ item.transactionState = 64 /* TRANSACTION.AUTH */;
126
+ let client;
127
+ if (postgresPool) {
128
+ pools.push(client = await postgresPool.getConnection());
129
+ item.transactionState &= ~64 /* TRANSACTION.AUTH */;
130
+ return client;
131
+ }
132
+ const pool = item.usePool && pool_1.default.findKey(POOL_STATE, item.usePool, getPoolKey(credential), ...connectOnce ? [item, batch[0]] : [item]);
133
+ if (pool) {
134
+ try {
135
+ pools.push(client = await pool.getConnection());
136
+ if (connectOnce) {
137
+ postgresPool = pool;
138
+ }
139
+ pool.connected = true;
140
+ }
141
+ catch (err) {
142
+ let close;
143
+ switch (err instanceof Error && err.code) {
144
+ case '28000':
145
+ case '28P01':
146
+ close = 1;
147
+ break;
148
+ default:
149
+ close = pool.closeable;
150
+ break;
151
+ }
152
+ if (close) {
153
+ await pool.detach(true);
154
+ if (close === 1) {
155
+ throw err;
156
+ }
157
+ }
158
+ pool.connected = false;
159
+ }
160
+ }
161
+ if (!client) {
162
+ clients.push(client = new db.Client((postgresCredential || credential)));
163
+ await client.connect();
164
+ }
165
+ if (connectOnce) {
166
+ if (!parallel) {
167
+ postgresClient = client;
168
+ }
169
+ postgresCredential = credential;
170
+ }
171
+ item.transactionState &= ~64 /* TRANSACTION.AUTH */;
172
+ return client;
173
+ };
174
+ for (let i = 0; i < length; ++i) {
175
+ const item = batch[i];
176
+ const { source, query, params, ignoreCache } = item;
177
+ let credential = postgresCredential || onceCredential, error;
178
+ if (!credential && !(0, types_1.isPlainObject)(credential = item.credential) && (error = (0, types_1.errorMessage)(source, "Invalid credentials" /* ERR_DB.CREDENTIALS */)) || !query && (error = (0, types_1.errorMessage)(source, "Missing database query" /* ERR_DB.QUERY */))) {
179
+ if (this.handleFail(error, item, { errorQuery })) {
180
+ if (!parallel) {
181
+ tasks.length = 0;
182
+ break;
183
+ }
184
+ tasks[i] = Promise.reject(error);
185
+ }
186
+ else if (parallel) {
187
+ tasks[i] = Promise.resolve([]);
188
+ }
189
+ else {
190
+ outResult[i] = [];
191
+ }
192
+ continue;
193
+ }
194
+ item.transactionState = 1 /* TRANSACTION.ACTIVE */;
195
+ const renewCache = ignoreCache === 0;
196
+ const cacheValue = renewCache ? { sessionKey, renewCache } : sessionKey;
197
+ let queryString = '';
198
+ if (caching && ignoreCache !== true || ignoreCache === false || ignoreCache === 1 || renewCache) {
199
+ queryString = index_1.default.asString(query, true) + '_' + index_1.default.asString(params, true);
200
+ if (ignoreCache !== 1) {
201
+ const result = this.getQueryResult(source, removePoolProperties(credential), queryString, cacheValue);
202
+ if (result) {
203
+ if (parallel) {
204
+ tasks[i] = Promise.resolve(result);
205
+ }
206
+ else {
207
+ outResult[i] = result;
208
+ }
209
+ this.add(item, 4 /* TRANSACTION.COMMIT */ | 128 /* TRANSACTION.CACHE */);
210
+ continue;
211
+ }
212
+ if (!ignoreCache && outCacheMiss) {
213
+ outCacheMiss.push(source);
214
+ }
215
+ }
216
+ }
217
+ if (onceCredential && parallel) {
218
+ try {
219
+ postgresClient = await getConnection(item, onceCredential);
220
+ }
221
+ catch {
222
+ connectOnce = false;
223
+ parallel = false;
224
+ }
225
+ onceCredential = undefined;
226
+ }
227
+ tasks[i] = new Promise(async (resolve, reject) => {
228
+ let commandType;
229
+ try {
230
+ const client = postgresClient || await getConnection(item, credential);
231
+ if (postgresClient && parallel) {
232
+ postgresClient = undefined;
233
+ }
234
+ commandType = this.commandType.SELECT;
235
+ const { rows, command } = await client.query(query, params);
236
+ this.add(item, 4 /* TRANSACTION.COMMIT */);
237
+ resolve(rows.length || command === 'SELECT' ? this.setQueryResult(source, removePoolProperties(credential), queryString, rows, cacheValue) : null);
238
+ }
239
+ catch (err) {
240
+ if (this.handleFail(err, item, { errorQuery, commandType })) {
241
+ reject(err);
242
+ }
243
+ else {
244
+ resolve([]);
245
+ }
246
+ }
247
+ });
248
+ if (!parallel) {
249
+ try {
250
+ outResult[i] = await tasks[i];
251
+ }
252
+ catch {
253
+ tasks.length = 0;
254
+ break;
255
+ }
256
+ }
257
+ }
258
+ return this.processRows(batch, tasks, {
259
+ disconnect: () => {
260
+ clients.forEach(item => item.end(err => err && this.writeFail(["Unable to close connnection" /* ERR_DB.CONNECTION_CLOSE */, "postgres" /* STRINGS.MODULE_NAME */], err, { type: 65536 /* LOG_TYPE.DB */, fatal: false })));
261
+ pools.forEach(item => item.release());
262
+ },
263
+ parallel
264
+ }, outResult);
265
+ }
266
+ exports.executeBatchQuery = executeBatchQuery;
267
+ function checkTimeout(value, limit = 0) {
268
+ return pool_1.default.checkTimeout(POOL_STATE, value, limit);
269
+ }
270
+ exports.checkTimeout = checkTimeout;
271
+ exports.DB_SOURCE_CLIENT = true;
272
+ exports.DB_SOURCE_TYPE = types_1.DB_TYPE.SQL;
@@ -0,0 +1,7 @@
1
+ import type { RedisDataSource } from '../../types/lib/db';
2
+
3
+ import type { IDbSourceClient } from '../types';
4
+
5
+ declare const Redis: IDbSourceClient<RedisDataSource>;
6
+
7
+ export = Redis;