-
Notifications
You must be signed in to change notification settings - Fork 1
/
dbio.mjs
508 lines (462 loc) · 17.1 KB
/
dbio.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
import {
assertSet, checkChance, ensureArray, ensureString, ignoreErrFunc,
log as _log, need, throwError,
} from './utilitas.mjs';
import { isPrimary } from './callosum.mjs';
const _NEED = ['mysql2', 'pg'];
const [mysqlDefaultPort, postgresqlDefaultPort] = [3306, 5432];
const [mysqlQuote, postgresqlQuote] = ['`', ''];
const IFSC = 'information_schema';
const orders = { '+': 'ASC', ASC: 'ASC', '-': 'DESC', DESC: 'DESC', VECTOR: ' ' };
const [INSERT, UPDATE, RETURNING] = ['INSERT', 'UPDATE', 'RETURNING'];
const RETURNING_ALL = ` RETURNING *`;
const [fieldId, fieldAny] = ['id', '*'];
const fieldCount = `COUNT(${fieldAny})`;
const direct = { direct: true };
const comparison = ['=', '>', '<', '<>', '!='];
const fieldNoQuote = [fieldAny, fieldCount];
const log = content => _log(content, import.meta.url);
const defaultKey = options => options && options.key ? options.key : fieldId;
const queryOne = async (...args) => (await query(...args))[0];
const assertForce = op => assert(op?.force, "Option 'force' is required.", 500);
const [MYSQL, POSTGRESQL] = ['MYSQL', 'POSTGRESQL'];
const quote = name => `${bracket}${name}${bracket}`;
const join = elements => elements.join(', ');
const assembleDelete = table => `DELETE FROM ${quote(assertTable(table))}`;
const execByQuery = async (...a) => await rawQuery(...distillArguments(...a));
const getProvider = async () => (await init()) && provider;
const encodeVector = async embedding => (await getPgvector()).toSql(embedding);
const cleanSql = sql => sql.replace(/\s+/g, ' ');
let provider, pool, actExecute, bracket, sqlShowTables, placeholder, sqlDesc,
sqlShowIndexes, fieldCountResult, doublePlaceholder, pgvector;
const init = async (options) => {
if (options) {
const _provider = ensureString(options?.provider, { case: 'UP' });
let port, vector = '';
switch (_provider) {
case MYSQL:
case 'MARIA':
case 'MARIADB':
const mysql = await need('mysql2/promise');
delete options.provider;
[
provider, pool, port, actExecute, bracket, sqlShowTables,
placeholder, fieldCountResult,
] = [
MYSQL, mysql.createPool(options), mysqlDefaultPort,
'execute', mysqlQuote, 'SHOW TABLES', '?', fieldCount,
];
doublePlaceholder = `${placeholder}${placeholder}`;
[sqlShowIndexes, sqlDesc] = [
`SHOW INDEXES FROM ${doublePlaceholder}`,
`DESC ${doublePlaceholder}`,
];
break;
case 'PG':
case 'POSTGRE':
case 'PSQL':
case POSTGRESQL:
// https://node-postgres.com/apis/pool
const { Pool } = await need('pg');
[
provider, pool, port, actExecute, bracket, placeholder,
fieldCountResult,
] = [
POSTGRESQL, new Pool(options), postgresqlDefaultPort,
'query', postgresqlQuote, '$1', 'count',
];
[sqlShowTables, sqlShowIndexes, sqlDesc] = [
[`${IFSC}.tables`, 'table_schema', "'public'", direct],
['pg_indexes', 'tablename', ''],
[`${IFSC}.COLUMNS`, 'TABLE_NAME', ''],
].map(args => assembleQueryByKeyValue(...args));
if (options?.vector) {
await enableVector();
vector = '(vector)';
}
break;
default:
assert(
!options?.provider,
`Invalid database provider: '${options.provider}'.`, 400
);
}
isPrimary && !options.silent && log(
`Initialized: ${_provider.toLowerCase()}://${options.user}@`
+ `${options.host}:${options.port || port}/${options.database}`
+ `${vector}`
);
}
assert(pool, 'Database has not been initialized.');
return pool;
};
const end = async (options) => {
pool && pool.end();
log('Terminated.');
};
const getPgvector = async () => {
assert(
provider === POSTGRESQL && pool,
'PostgreSQL has not been initialized.', 501
);
return pgvector || (pgvector = await need('pgvector/pg'));
};
const logCommand = (args) => {
const _args = ensureArray(args);
if (~~globalThis.debug > 0 && _args && _args[0]) { log(`SQL: ${_args[0]}`); }
if (~~globalThis.debug > 1 && _args && _args[1]) { console.log(_args[1]); };
};
const getComparison = (val) => Object.isObject(val)
&& comparison.includes(Object.keys(val)[0]) ? Object.keys(val)[0] : null;
const getOrder = (ord) => {
assert(orders[ord], `Invalid order expression: '${ord}'.`, 400);
return orders[ord];
};
const distillArguments = (...args) => {
Array.isArray(args[1]) && args[1].map((v, k) => {
const cps = getComparison(v); cps && (args[1][k] = v[cps]);
});
return args;
};
const rawQuery = async (...args) => {
const conn = await init();
logCommand(...args);
return await conn.query(...args);
};
const rawExecute = async (...args) => {
const conn = await init();
logCommand(...args);
return await conn[actExecute](...args);
};
const handleResult = result => {
switch (provider) {
case MYSQL: return result[0];
case POSTGRESQL: return result.rows;
}
};
const query = async (...args) => handleResult(
await rawQuery(...distillArguments(...args))
);
const execute = async (...args) => {
const resp = await rawExecute(...distillArguments(...args));
switch (provider) {
case MYSQL: return resp[0];
case POSTGRESQL: return resp;
}
};
const assertTable = (table, message, status) => {
assert(table, message || 'Table is required.', status || 500);
return table;
};
const assertKeyValue = (key, value) => {
assert(key, 'Key is required.', 500);
assertSet(Array.isArray(key) || value, 'Value is required.', 500);
};
const assembleQueryByKeyValue = (table, key, value, options) =>
assembleQuery(table) + assembleKeyValue(key, value, options);
// const assertTableKeyValue = (table, key, value) => {
// assertTable(table);
// assertKeyValue(key, value);
// };
const assembleQuery = (table, options) => {
assertTable(table);
const fields = [];
ensureArray(options?.fields).map((field) => {
fields.push(fieldNoQuote.includes(field) || options?.noQuote
? field : quote(field));
});
if (!fields.length) { fields.push(fieldAny); }
return `SELECT ${join(fields)} FROM ${quote(table)}`;
};
const rawAssembleKeyValue = (key, value, options) => {
// TODO: handle JSONB for PostgreSQL only
// for MySQL, JSON should be stringified before assembling
assertKeyValue(key, value);
const [keys, values, conditions] = [[], [], []];
if (Array.isArray(key)) {
key.map(([k, v]) => { keys.push(k); values.push(v); });
} else { keys.push(key); values.push(value); }
values.map((x, i) => {
let _placeholder;
switch (provider) {
case MYSQL:
_placeholder = placeholder;
break;
case POSTGRESQL:
_placeholder = `$${options?.placeholderIndex || (~~i + 1)}`;
}
const val = options?.direct ? value : _placeholder;
let express = `${getComparison(value) || '='} ${val}`;
if (Array.isArray(value)) {
assert(value.length, 'Invalid array value.', 500);
express = `IN (${val})`;
} else if (value === null) { express = `IS ${val}`; }
conditions.push(`${quote(keys[i])} ${express}`);
});
return `${options?.prefix || ''}${conditions.join(` ${options?.operator || 'AND'} `)}`;
};
const assembleKeyValue = (key, value, options) => rawAssembleKeyValue(
key, value, { ...options || {}, prefix: ' WHERE ' }
);
const pushValue = (values, item) => values.push(
Object.isObject(item) || Array.isArray(item) ? JSON.stringify(item) : item
);
const assembleSet = (data, options) => {
assertSet(data, 'Data is required.');
const [isArray, result] = [options?.asArray || Array.isArray(data), []];
ensureArray(data).map((item) => {
assert(Object.keys(item).length, 'Fields are required.', 500);
let [pairs, keys, vals, values, dupSql, i, sql]
= [[], [], [], [], [], 0, ''];
for (let k in item) {
keys.push(k);
switch (provider) {
case MYSQL:
vals.push('?');
pairs.push(`${quote(k)} = ?`);
break;
case POSTGRESQL:
vals.push(`$${++i}`);
pairs.push(`${quote(k)} = $${i}`);
}
pushValue(values, item[k]);
}
if (options?.upsert) {
for (let k in item) {
switch (provider) {
case MYSQL: dupSql.push(`${quote(k)} = ?`); break;
case POSTGRESQL: dupSql.push(`${quote(k)} = $${++i}`); break;
}
pushValue(values, item[k]);
}
switch (provider) {
case MYSQL:
dupSql = ` ON DUPLICATE KEY UPDATE ${join(dupSql)}`;
break;
case POSTGRESQL:
dupSql = ` ON CONFLICT (${defaultKey(options)}) DO UPDATE SET ${join(dupSql)}`;
break;
}
} else { dupSql = ''; }
switch (options?.action) {
case INSERT:
sql = `(${join(keys.map(quote))}) VALUES (${join(vals)})`;
break;
case UPDATE:
sql = `SET ${pairs.join(', ')}`;
break;
default:
throwError(`Invalid action: '${options?.action}'.`, 400);
}
sql = `${options?.prefix || ''}${sql}${dupSql}${options?.subfix || ''}`;
result.push({ sql, values, object: item });
});
return isArray ? result : result[0];
};
const assembleInsert = (table, data, options) => assembleSet(data, {
...options || {}, action: INSERT,
prefix: `INSERT INTO ${quote(assertTable(table))} `,
});
const assembleUpdate = (table, data, options) => assembleSet(data, {
...options || {}, action: UPDATE,
prefix: `UPDATE ${quote(assertTable(table))} `,
});
const assembleTail = (options) => {
let sort = [];
ensureArray(options?.order || []).map?.(x => {
const ord = Object.isObject(x) ? x : { [x]: '+' };
const key = Object.keys(ord)[0];
sort.push(`${quote(key)} ${getOrder(ord[key])}`);
});
return (sort.length ? ` ORDER BY ${join(sort)}` : '')
+ (~~options?.limit ? ` LIMIT ${~~options.limit}` : '')
+ (~~options?.offset ? ` OFFSET ${~~options.offset}` : '');
};
const tables = async (options) => {
const resp = await query(sqlShowTables);
return options?.raw ? resp : resp.map(x => {
switch (provider) {
case MYSQL: return Object.values(x)[0];
case POSTGRESQL: return x.table_name;
}
});
};
const desc = async (table, options) => {
assertTable(table);
const [resp, result] = [await query(sqlDesc, [table]), {}];
if (options?.raw) { return resp; }
switch (provider) {
case MYSQL: resp.map(x => result[x.Field] = x); break;
case POSTGRESQL: resp.map(x => result[x.column_name] = x); break;
}
return result;
};
const indexes = async (table, options) => {
assertTable(table);
const [resp, result] = [await query(sqlShowIndexes, [table]), {}];
if (options?.raw) { return resp; }
switch (provider) {
case MYSQL: resp.map(x => result[x.Key_name] = x); break;
case POSTGRESQL: resp.map(x => result[x.indexname] = x); break;
}
return result;
};
const drop = async (table, options) => {
assertTable(table);
assertForce(options);
const act = {
[MYSQL]: [query, [`DROP TABLE IF EXISTS ${doublePlaceholder}`, [table]]],
[POSTGRESQL]: [execute, [`DROP TABLE IF EXISTS ${table}`]],
}[provider]
return await act[0](...act[1]);
};
const queryAll = (table, options) =>
query(`${assembleQuery(table, options)}${assembleTail(options)}`);
const queryByKeyValue = async (table, key, value, options) => {
Object.isObject(key) && (key = Object.entries(key));
const sql = assembleQuery(table, options)
+ assembleKeyValue(key, value)
+ assembleTail(options);
const resp = await query(sql, Array.isArray(key) ? key.map(x => x[1]) : [value]);
return options?.unique ? (resp && resp.length ? resp[0] : null) : resp;
};
const queryById = async (table, id, options) => await queryByKeyValue(
table, defaultKey(options), id,
{ ...options || {}, unique: !Array.isArray(id) }
);
const insert = async (table, fields, options) => {
let [isArray, key, ids, error, result]
= [Array.isArray(fields), defaultKey(options), [], [], []];
const subfix = provider === POSTGRESQL ? (options?.skipEcho ? (
options?.key ? ` ${RETURNING} ${key}` : ''
) : RETURNING_ALL) : '';
for (let item of assembleInsert(
table, fields, { ...options || {}, asArray: true, subfix })
) {
try {
const resp = await execute(item.sql, item.values);
if (provider === POSTGRESQL) {
resp.affectedRows = resp.rowCount;
await vacuum(table, { auto: true, ...options || {} });
}
resp.key = key;
!resp.insertId && item.object[key]
&& (resp.insertId = item.object[key]);
result.push(resp);
ids.push(resp.insertId);
} catch (err) { error.push(err); }
}
if (!options?.skipEcho && ids.length) {
switch (provider) {
case MYSQL:
result = await queryById(table, ids, options);
break;
case POSTGRESQL:
result = result.map(x => x.rows).flat();
}
}
if (!isArray) {
if (error.length) { throw error[0]; }
return result.length ? result[0] : null;
}
return { error, result };
};
const upsert = (table, fields, options) =>
insert(table, fields, { ...options || {}, upsert: true });
const countAll = async (table) => {
const sql = assembleQuery(table, { fields: fieldCount });
return (await query(sql))[0][fieldCountResult];
};
const countByKeyValue = async (table, key, value) => {
const sql = assembleQuery(table, { fields: fieldCount })
+ assembleKeyValue(key, value);
return (await query(sql, [value]))[0][fieldCountResult];
};
const updateByKeyValue = async (table, key, value, fields, options) => {
assertTable(table);
const dfKey = defaultKey(options);
const subfix = assembleKeyValue(key, value, {
placeholderIndex: Object.keys(fields).length + 1,
}) + (provider === POSTGRESQL ? (options?.skipEcho ? (
options?.key ? ` ${RETURNING} ${dfKey}` : ''
) : RETURNING_ALL) : '');
let { sql, values } = assembleUpdate(table, fields, { subfix });
sql += assembleTail(options);
const resp = await query(sql, [...values, value]);
return !options?.skipEcho && provider === MYSQL
? await queryByKeyValue(table, key, value, options) : resp;
};
const updateById = async (table, id, fields, options) => {
const resp = await updateByKeyValue(
table, defaultKey(options), id, fields, options
);
return Array.isArray(id) ? resp : (resp && resp.length ? resp[0] : null);
};
const deleteByKeyValue = async (table, key, value, options) => {
const sql = assembleDelete(table)
+ assembleKeyValue(key, value)
+ assembleTail(options);
return await {
[MYSQL]: query, [POSTGRESQL]: execByQuery,
}[provider](sql, [value]);
};
const deleteById = async (table, id, options) =>
await deleteByKeyValue(table, defaultKey(options), id);
const deleteAll = async (table, options) => {
assertForce(options);
return await execute(assembleDelete(table));
};
const enableVector = async () => {
const pgvector = await getPgvector();
await execute('CREATE EXTENSION IF NOT EXISTS vector');
// https://github.com/pgvector/pgvector-node?tab=readme-ov-file#node-postgres
pool.on('connect', pgvector.registerType);
};
const vacuum = async (table, options) => {
assertTable(table);
if (!checkChance(options?.auto ? options?.chance : 1)) { return; }
const resp = await execute(`VACUUM ${quote(table)}`);
log(JSON.stringify(resp));
return resp;
};
export default init;
export {
_NEED,
MYSQL,
POSTGRESQL,
assembleInsert,
assembleQuery,
assembleSet,
assembleTail,
assembleUpdate,
cleanSql,
countAll,
countByKeyValue,
deleteAll,
deleteById,
deleteByKeyValue,
desc,
drop,
enableVector,
encodeVector,
end,
execute,
getPgvector,
getProvider,
indexes,
init,
insert,
query,
queryAll,
queryById,
queryByKeyValue,
queryOne,
rawAssembleKeyValue,
rawExecute,
rawQuery,
tables,
updateById,
updateByKeyValue,
upsert,
vacuum,
};