@pi-r/mariadb 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,7 @@
1
+ Copyright 2023 An Pham
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,5 @@
1
+ ### @pi-r/mariadb
2
+
3
+ ### LICENSE
4
+
5
+ MIT
@@ -0,0 +1,328 @@
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 = exports.setAuthentication = void 0;
4
+ const util_1 = require("@e-mc/db/util");
5
+ const types_1 = require("@e-mc/types");
6
+ const Db = require("@e-mc/db");
7
+ const DbPool = require('@e-mc/db/pool');
8
+ class MariaDBPool extends DbPool {
9
+ getConnection() {
10
+ return this.client.getConnection();
11
+ }
12
+ close() {
13
+ return this.client.end();
14
+ }
15
+ isEmpty() {
16
+ const client = this.client;
17
+ return this.closed || client.activeConnections() === 0 && client.taskQueueSize() === 0;
18
+ }
19
+ get closed() {
20
+ return this.client.closed;
21
+ }
22
+ }
23
+ const POOL_STATE = {};
24
+ function removePoolProperties(credential) {
25
+ if (!credential.uuidKey && ('ssl' in credential || 'connectionLimit' in credential || 'connectTimeout' in credential || 'idleTimeout' in credential || 'minimumIdle' in credential || 'resetAfterUse' in credential || 'noControlAfterUse' in credential)) {
26
+ return { ...credential, ssl: (0, types_1.isObject)(credential.ssl) ? true : undefined, connectionLimit: undefined, idleTimeout: undefined, connectTimeout: undefined, minimumIdle: undefined, resetAfterUse: undefined, noControlAfterUse: undefined };
27
+ }
28
+ return credential;
29
+ }
30
+ function removeUUIDKey(credential) {
31
+ if ('uuidKey' in credential) {
32
+ credential = { ...credential };
33
+ delete credential.uuidKey;
34
+ return credential;
35
+ }
36
+ return credential;
37
+ }
38
+ const getPoolKey = (credential) => (credential.host || '') + '_' + (credential.port || '3306') + (credential.user || '') + '_' + (credential.password || '') + '_' + (credential.database || '') + '_' + (credential.rowsAsArray ? '1' : '0');
39
+ function setAuthentication(credential) {
40
+ const auth = (0, util_1.parseServerAuth)(credential);
41
+ credential.host || (credential.host = auth.hostname);
42
+ credential.user || (credential.user = auth.username);
43
+ if ((0, types_1.isPlainObject)(credential.ssl)) {
44
+ this.readTLSConfig(credential.ssl);
45
+ }
46
+ }
47
+ exports.setAuthentication = setAuthentication;
48
+ function setCredential(item) {
49
+ let credential = this.getCredential(item);
50
+ if (credential) {
51
+ setAuthentication.call(this, credential);
52
+ }
53
+ else {
54
+ const uri = item.uri;
55
+ credential = {};
56
+ if (uri) {
57
+ const connection = (0, util_1.parseConnectionString)(uri);
58
+ if (connection) {
59
+ const { username, password, hostname, port, database } = connection;
60
+ credential.host = hostname;
61
+ if (port) {
62
+ credential.port = +port;
63
+ }
64
+ credential.user = username;
65
+ credential.password = password;
66
+ credential.database = database;
67
+ }
68
+ }
69
+ item.credential = credential;
70
+ }
71
+ const errors = [];
72
+ if (!credential.host) {
73
+ errors.push('host');
74
+ }
75
+ if (!credential.user) {
76
+ errors.push('user');
77
+ }
78
+ if (errors.length) {
79
+ throw (0, types_1.errorMessage)("mariadb" /* STRINGS.MODULE_NAME */, 'Not defined - ' + errors.join(' | '));
80
+ }
81
+ const usePool = item.usePool;
82
+ if (usePool) {
83
+ let username, password, pool;
84
+ if (typeof usePool === 'string' && (username = credential.user)) {
85
+ [password, pool] = DbPool.validateKey(POOL_STATE, username, usePool);
86
+ if (pool) {
87
+ pool.add(item, password);
88
+ return;
89
+ }
90
+ }
91
+ const poolKey = getPoolKey(credential);
92
+ if (!(pool = POOL_STATE[poolKey]) || pool.closed) {
93
+ const { createPool } = require("mariadb" /* STRINGS.PACKAGE_NAME */);
94
+ const config = this.getPoolConfig("mariadb" /* STRINGS.MODULE_NAME */, password);
95
+ if (config) {
96
+ const { max, idle } = config;
97
+ if (max > 0) {
98
+ credential.connectionLimit ?? (credential.connectionLimit = max);
99
+ }
100
+ if (idle >= 0) {
101
+ credential.idleTimeout ?? (credential.idleTimeout = idle);
102
+ }
103
+ }
104
+ new MariaDBPool(createPool(removeUUIDKey(credential)), poolKey, username && password ? { username, password } : undefined).add(item).parent = POOL_STATE;
105
+ }
106
+ else {
107
+ pool.add(item);
108
+ }
109
+ }
110
+ }
111
+ exports.setCredential = setCredential;
112
+ async function executeQuery(item, options) {
113
+ return (await executeBatchQuery.call(this, [item], options))[0] || [];
114
+ }
115
+ exports.executeQuery = executeQuery;
116
+ async function executeBatchQuery(batch, options = '', outResult) {
117
+ const length = batch.length;
118
+ if (length === 0) {
119
+ return [];
120
+ }
121
+ const db = require("mariadb" /* STRINGS.PACKAGE_NAME */);
122
+ let parallel, connectOnce, errorQuery, sessionKey, outCacheMiss;
123
+ if ((0, types_1.isPlainObject)(options)) {
124
+ ({ parallel, connectOnce, errorQuery, sessionKey, outCacheMiss } = options);
125
+ }
126
+ else {
127
+ if (typeof options === 'string') {
128
+ sessionKey = options;
129
+ }
130
+ options = undefined;
131
+ }
132
+ if (length === 1) {
133
+ connectOnce = false;
134
+ parallel = false;
135
+ }
136
+ else if (parallel === undefined) {
137
+ parallel = !batch.some(item => item.parallel === false);
138
+ }
139
+ if (!parallel) {
140
+ outResult || (outResult = new Array(length));
141
+ }
142
+ const caching = this.hasCache("mariadb" /* STRINGS.MODULE_NAME */, sessionKey);
143
+ const tasks = new Array(length);
144
+ const clients = [];
145
+ const pools = [];
146
+ let mariaDBPool, mariaDBClient, mariaDBCredential, onceCredential = connectOnce ? batch[0].credential : undefined;
147
+ const getConnection = async (item, credential) => {
148
+ item.transactionState = 64 /* DB_TRANSACTION.AUTH */;
149
+ let client;
150
+ if (mariaDBPool) {
151
+ pools.push(client = await mariaDBPool.getConnection());
152
+ item.transactionState &= ~64 /* DB_TRANSACTION.AUTH */;
153
+ return client;
154
+ }
155
+ const pool = item.usePool && DbPool.findKey(POOL_STATE, item.usePool, getPoolKey(credential), ...connectOnce ? [item, batch[0]] : [item]);
156
+ if (pool) {
157
+ try {
158
+ pools.push(client = await pool.getConnection());
159
+ if (connectOnce) {
160
+ mariaDBPool = pool;
161
+ }
162
+ pool.connected = true;
163
+ }
164
+ catch (err) {
165
+ let close;
166
+ switch (err instanceof Error && err.code) {
167
+ case 'ER_ACCESS_DENIED_ERROR':
168
+ case 'ER_DBACCESS_DENIED_ERROR':
169
+ case 'ER_SPECIFIC_ACCESS_DENIED_ERROR':
170
+ case 'ER_ACCESS_DENIED_NO_PASSWORD_ERROR':
171
+ close = 1;
172
+ break;
173
+ default:
174
+ close = pool.closeable;
175
+ break;
176
+ }
177
+ if (close) {
178
+ await pool.detach(true);
179
+ if (close === 1) {
180
+ throw err;
181
+ }
182
+ }
183
+ pool.connected = false;
184
+ }
185
+ }
186
+ if (!client) {
187
+ clients.push(client = await db.createConnection(removeUUIDKey(mariaDBCredential || credential)));
188
+ }
189
+ if (connectOnce) {
190
+ if (!parallel) {
191
+ mariaDBClient = client;
192
+ }
193
+ mariaDBCredential = credential;
194
+ }
195
+ item.transactionState &= ~64 /* DB_TRANSACTION.AUTH */;
196
+ return client;
197
+ };
198
+ for (let i = 0; i < length; ++i) {
199
+ const item = batch[i];
200
+ const { source, query, params, ignoreCache } = item;
201
+ let credential = mariaDBCredential || onceCredential, error;
202
+ const streamRow = typeof item.streamRow === 'string' ? this.hasCoerce("mariadb" /* STRINGS.MODULE_NAME */, 'options', null, item.credential) && (0, types_1.asFunction)(item.streamRow) : item.streamRow;
203
+ if (!(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 */))) {
204
+ if (this.handleFail(error, item, { errorQuery })) {
205
+ if (!parallel) {
206
+ tasks.length = 0;
207
+ break;
208
+ }
209
+ tasks[i] = Promise.reject(error);
210
+ }
211
+ else if (parallel) {
212
+ tasks[i] = Promise.resolve([]);
213
+ }
214
+ else {
215
+ outResult[i] = [];
216
+ }
217
+ continue;
218
+ }
219
+ item.transactionState = 1 /* DB_TRANSACTION.ACTIVE */;
220
+ const renewCache = ignoreCache === 0;
221
+ const cacheValue = renewCache ? { sessionKey, renewCache } : sessionKey;
222
+ let queryString = '';
223
+ if ((caching && ignoreCache !== true || ignoreCache === false || ignoreCache === 1 || renewCache) && !streamRow) {
224
+ queryString = Db.asString(query, true) + '_' + Db.asString(params, true);
225
+ const result = this.getQueryResult(source, removePoolProperties(credential), queryString, cacheValue);
226
+ if (ignoreCache !== 1) {
227
+ if (result) {
228
+ if (parallel) {
229
+ tasks[i] = Promise.resolve(result);
230
+ }
231
+ else {
232
+ outResult[i] = result;
233
+ }
234
+ this.add(item, 4 /* DB_TRANSACTION.COMMIT */ | 128 /* DB_TRANSACTION.CACHE */);
235
+ continue;
236
+ }
237
+ if (!ignoreCache && outCacheMiss) {
238
+ outCacheMiss.push(source);
239
+ }
240
+ }
241
+ }
242
+ if (onceCredential && parallel && !streamRow) {
243
+ try {
244
+ mariaDBClient = await getConnection(item, onceCredential);
245
+ }
246
+ catch {
247
+ connectOnce = false;
248
+ parallel = false;
249
+ }
250
+ onceCredential = undefined;
251
+ }
252
+ tasks[i] = new Promise(async (resolve, reject) => {
253
+ let commandType;
254
+ try {
255
+ const client = mariaDBClient || await getConnection(item, credential);
256
+ if (mariaDBClient && parallel) {
257
+ mariaDBClient = undefined;
258
+ }
259
+ commandType = this.commandType.SELECT;
260
+ if (streamRow) {
261
+ const rows = [];
262
+ const processRow = typeof streamRow === 'function' && streamRow;
263
+ try {
264
+ for await (const row of client.queryStream(query, params)) {
265
+ if (processRow) {
266
+ const err = processRow(row);
267
+ if (err === false) {
268
+ continue;
269
+ }
270
+ if (err instanceof Error) {
271
+ error = err;
272
+ continue;
273
+ }
274
+ }
275
+ rows.push(row);
276
+ }
277
+ }
278
+ catch (err) {
279
+ error = err;
280
+ }
281
+ if (error && this.handleFail(error, item, { errorQuery, commandType })) {
282
+ reject(error);
283
+ }
284
+ else {
285
+ this.add(item, 4 /* DB_TRANSACTION.COMMIT */);
286
+ resolve(!error ? this.setQueryResult(source, removePoolProperties(credential), queryString, rows, cacheValue) : rows);
287
+ }
288
+ }
289
+ else {
290
+ const rows = await client.query(query, params);
291
+ this.add(item, 4 /* DB_TRANSACTION.COMMIT */);
292
+ resolve(Array.isArray(rows) ? this.setQueryResult(source, removePoolProperties(credential), queryString, rows, cacheValue) : null);
293
+ }
294
+ }
295
+ catch (err) {
296
+ if (this.handleFail(err, item, { errorQuery, commandType })) {
297
+ reject(err);
298
+ }
299
+ else {
300
+ resolve([]);
301
+ }
302
+ }
303
+ });
304
+ if (!parallel) {
305
+ try {
306
+ outResult[i] = await tasks[i];
307
+ }
308
+ catch {
309
+ tasks.length = 0;
310
+ break;
311
+ }
312
+ }
313
+ }
314
+ return this.processRows(batch, tasks, {
315
+ disconnect: () => {
316
+ clients.forEach(item => item.end());
317
+ pools.forEach(item => item.release());
318
+ },
319
+ parallel
320
+ }, outResult);
321
+ }
322
+ exports.executeBatchQuery = executeBatchQuery;
323
+ function checkTimeout(value, limit = 0) {
324
+ return DbPool.checkTimeout(POOL_STATE, value, limit);
325
+ }
326
+ exports.checkTimeout = checkTimeout;
327
+ exports.DB_SOURCE_CLIENT = true;
328
+ exports.DB_SOURCE_TYPE = types_1.DB_TYPE.SQL;
package/package.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "@pi-r/mariadb",
3
+ "version": "0.2.0",
4
+ "description": "MariaDB client driver for E-mc.",
5
+ "main": "client/index.js",
6
+ "types": "client/index.d.ts",
7
+ "publishConfig": {
8
+ "access": "public"
9
+ },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "https://github.com/anpham6/pi-r.git",
13
+ "directory": "src/db/mariadb"
14
+ },
15
+ "keywords": [
16
+ "squared",
17
+ "e-mc",
18
+ "squared-functions"
19
+ ],
20
+ "author": "An Pham <anpham6@gmail.com>",
21
+ "license": "MIT",
22
+ "homepage": "https://github.com/anpham6/pi-r#readme",
23
+ "dependencies": {
24
+ "@e-mc/db": "^0.5.3",
25
+ "@e-mc/types": "^0.5.3",
26
+ "mariadb": "^3.1.2"
27
+ }
28
+ }
@@ -0,0 +1,15 @@
1
+ import type { DbDataSource } from '@e-mc/types/lib/squared';
2
+
3
+ import type { ExecuteAction, ServerAuth } from '@e-mc/types/lib/db';
4
+
5
+ import type { SecureContextOptions } from 'tls';
6
+
7
+ import type { PoolConfig, QueryConfig } from 'mariadb';
8
+
9
+ export interface MariaDBDataSource<T = unknown> extends DbDataSource<string | QueryConfig, unknown, unknown, string | MariaDBCredential, string>, ExecuteAction<T> {
10
+ source: "mariadb";
11
+ }
12
+
13
+ export interface MariaDBCredential extends ServerAuth, Omit<PoolConfig, "ssl"> {
14
+ ssl?: boolean | string | SecureContextOptions & { rejectUnauthorized?: boolean };
15
+ }