@areumtecnologia/mysql-db-handler 2.0.3 → 2.1.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.
- package/README.md +1381 -1200
- package/index.d.ts +94 -7
- package/index.js +29 -16
- package/lib/databaseHandler.js +111 -43
- package/lib/operators.js +146 -0
- package/package.json +2 -2
package/index.d.ts
CHANGED
|
@@ -1,5 +1,86 @@
|
|
|
1
1
|
import { Pool, PoolConnection, PoolOptions, ResultSetHeader, RowDataPacket } from 'mysql2/promise';
|
|
2
2
|
|
|
3
|
+
export const ArithmeticOperator: {
|
|
4
|
+
readonly ADD: '+';
|
|
5
|
+
readonly PLUS: '+';
|
|
6
|
+
readonly SUBTRACT: '-';
|
|
7
|
+
readonly MINUS: '-';
|
|
8
|
+
readonly MULTIPLY: '*';
|
|
9
|
+
readonly DIVIDE: '/';
|
|
10
|
+
readonly MODULO: '%';
|
|
11
|
+
readonly MOD: 'MOD';
|
|
12
|
+
readonly DIV: 'DIV';
|
|
13
|
+
readonly INTEGER_DIVIDE: 'DIV';
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export const ComparisonOperator: {
|
|
17
|
+
readonly EQUALS: '=';
|
|
18
|
+
readonly EQUAL: '=';
|
|
19
|
+
readonly EQ: '=';
|
|
20
|
+
readonly NOT_EQUALS: '!=';
|
|
21
|
+
readonly NOT_EQUAL: '!=';
|
|
22
|
+
readonly NEQ: '!=';
|
|
23
|
+
readonly NOT_EQUALS_ALT: '<>';
|
|
24
|
+
readonly DIFFERENT: '<>';
|
|
25
|
+
readonly GREATER_THAN: '>';
|
|
26
|
+
readonly GT: '>';
|
|
27
|
+
readonly LESS_THAN: '<';
|
|
28
|
+
readonly LT: '<';
|
|
29
|
+
readonly GREATER_THAN_OR_EQUAL: '>=';
|
|
30
|
+
readonly GTE: '>=';
|
|
31
|
+
readonly LESS_THAN_OR_EQUAL: '<=';
|
|
32
|
+
readonly LTE: '<=';
|
|
33
|
+
readonly BETWEEN: 'BETWEEN';
|
|
34
|
+
readonly NOT_BETWEEN: 'NOT BETWEEN';
|
|
35
|
+
readonly IN: 'IN';
|
|
36
|
+
readonly NOT_IN: 'NOT IN';
|
|
37
|
+
readonly LIKE: 'LIKE';
|
|
38
|
+
readonly NOT_LIKE: 'NOT LIKE';
|
|
39
|
+
readonly IS_NULL: 'IS NULL';
|
|
40
|
+
readonly IS_NOT_NULL: 'IS NOT NULL';
|
|
41
|
+
readonly IS: 'IS';
|
|
42
|
+
readonly IS_NOT: 'IS NOT';
|
|
43
|
+
readonly REGEXP: 'REGEXP';
|
|
44
|
+
readonly NOT_REGEXP: 'NOT REGEXP';
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
export const LogicalOperator: {
|
|
48
|
+
readonly AND: 'AND';
|
|
49
|
+
readonly OR: 'OR';
|
|
50
|
+
readonly NOT: 'NOT';
|
|
51
|
+
readonly NOT_ALT: '!';
|
|
52
|
+
readonly BANG: '!';
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
export const BitwiseOperator: {
|
|
56
|
+
readonly AND: '&';
|
|
57
|
+
readonly BITWISE_AND: '&';
|
|
58
|
+
readonly OR: '|';
|
|
59
|
+
readonly BITWISE_OR: '|';
|
|
60
|
+
readonly XOR: '^';
|
|
61
|
+
readonly BITWISE_XOR: '^';
|
|
62
|
+
readonly RIGHT_SHIFT: '>>';
|
|
63
|
+
readonly LEFT_SHIFT: '<<';
|
|
64
|
+
readonly SHR: '>>';
|
|
65
|
+
readonly SHL: '<<';
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
export const Operators: {
|
|
69
|
+
readonly Arithmetic: typeof ArithmeticOperator;
|
|
70
|
+
readonly Comparison: typeof ComparisonOperator;
|
|
71
|
+
readonly Logical: typeof LogicalOperator;
|
|
72
|
+
readonly Bitwise: typeof BitwiseOperator;
|
|
73
|
+
readonly Aritmeticos: typeof ArithmeticOperator;
|
|
74
|
+
readonly Comparacao: typeof ComparisonOperator;
|
|
75
|
+
readonly Logicos: typeof LogicalOperator;
|
|
76
|
+
readonly BitwisePT: typeof BitwiseOperator;
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
export type ArithmeticOperatorType = typeof ArithmeticOperator[keyof typeof ArithmeticOperator];
|
|
80
|
+
export type ComparisonOperatorType = typeof ComparisonOperator[keyof typeof ComparisonOperator];
|
|
81
|
+
export type LogicalOperatorType = typeof LogicalOperator[keyof typeof LogicalOperator];
|
|
82
|
+
export type BitwiseOperatorType = typeof BitwiseOperator[keyof typeof BitwiseOperator];
|
|
83
|
+
|
|
3
84
|
export type IsolationLevel = 'READ UNCOMMITTED' | 'READ COMMITTED' | 'REPEATABLE READ' | 'SERIALIZABLE';
|
|
4
85
|
|
|
5
86
|
export interface ExtendedDatabaseConfig extends PoolOptions {
|
|
@@ -131,6 +212,12 @@ export class DataBaseHandler<T = RowDataPacket> {
|
|
|
131
212
|
onError: ((err: Error) => void) | null;
|
|
132
213
|
options: DatabaseHandlerOptions;
|
|
133
214
|
|
|
215
|
+
static readonly ArithmeticOperator: typeof ArithmeticOperator;
|
|
216
|
+
static readonly ComparisonOperator: typeof ComparisonOperator;
|
|
217
|
+
static readonly LogicalOperator: typeof LogicalOperator;
|
|
218
|
+
static readonly BitwiseOperator: typeof BitwiseOperator;
|
|
219
|
+
static readonly Operators: typeof Operators;
|
|
220
|
+
|
|
134
221
|
static raw(sql: string): { __isRawSql: true; sql: string };
|
|
135
222
|
static hasMany(handler: DataBaseHandler<any>, foreignKey: string, localKey?: string): RelationDefinition;
|
|
136
223
|
static belongsTo(handler: DataBaseHandler<any>, foreignKey: string, localKey?: string): RelationDefinition;
|
|
@@ -142,10 +229,10 @@ export class DataBaseHandler<T = RowDataPacket> {
|
|
|
142
229
|
executeQuery(sql: string, params?: any, isWrite?: boolean, options?: Record<string, any>): Promise<any>;
|
|
143
230
|
|
|
144
231
|
// Fluent Joins
|
|
145
|
-
join(table: string, first: string, operator: string, second: string): DataBaseHandler<T>;
|
|
146
|
-
leftJoin(table: string, first: string, operator: string, second: string): DataBaseHandler<T>;
|
|
147
|
-
rightJoin(table: string, first: string, operator: string, second: string): DataBaseHandler<T>;
|
|
148
|
-
innerJoin(table: string, first: string, operator: string, second: string): DataBaseHandler<T>;
|
|
232
|
+
join(table: string, first: string, operator: ComparisonOperatorType | string, second: string): DataBaseHandler<T>;
|
|
233
|
+
leftJoin(table: string, first: string, operator: ComparisonOperatorType | string, second: string): DataBaseHandler<T>;
|
|
234
|
+
rightJoin(table: string, first: string, operator: ComparisonOperatorType | string, second: string): DataBaseHandler<T>;
|
|
235
|
+
innerJoin(table: string, first: string, operator: ComparisonOperatorType | string, second: string): DataBaseHandler<T>;
|
|
149
236
|
|
|
150
237
|
// Eager Loading (N+1 Elimination)
|
|
151
238
|
with(relationName: string, relationOrHandler: RelationDefinition | DataBaseHandler<any>): DataBaseHandler<T>;
|
|
@@ -166,8 +253,8 @@ export class DataBaseHandler<T = RowDataPacket> {
|
|
|
166
253
|
|
|
167
254
|
// Fluent Query Builder
|
|
168
255
|
selectFields(fields: string | string[] | Array<string | { column: string; as: string } | { raw: string }>): DataBaseHandler<T>;
|
|
169
|
-
where(columnOrObject: string | Record<string, any> | any[], operatorOrValue?: any, value?: any): DataBaseHandler<T>;
|
|
170
|
-
orWhere(columnOrObject: string | Record<string, any>, operatorOrValue?: any, value?: any): DataBaseHandler<T>;
|
|
256
|
+
where(columnOrObject: string | Record<string, any> | any[], operatorOrValue?: ComparisonOperatorType | any, value?: any): DataBaseHandler<T>;
|
|
257
|
+
orWhere(columnOrObject: string | Record<string, any>, operatorOrValue?: ComparisonOperatorType | any, value?: any): DataBaseHandler<T>;
|
|
171
258
|
groupBy(cols: string | string[]): DataBaseHandler<T>;
|
|
172
259
|
having(sql: string, bindings?: any[]): DataBaseHandler<T>;
|
|
173
260
|
orderBy(column: string, dir?: 'ASC' | 'DESC'): DataBaseHandler<T>;
|
|
@@ -184,7 +271,7 @@ export class DataBaseHandler<T = RowDataPacket> {
|
|
|
184
271
|
|
|
185
272
|
// Core Operations
|
|
186
273
|
paginate(options?: PaginateOptions): Promise<PaginatedResult<T>>;
|
|
187
|
-
selectToDatatable(rawDtQuery: Record<string, any>, strictCondition?: any[]): Promise<{
|
|
274
|
+
selectToDatatable(rawDtQuery: Record<string, any>, strictCondition?: any[] | Record<string, any>): Promise<{
|
|
188
275
|
draw: number;
|
|
189
276
|
recordsTotal: number;
|
|
190
277
|
recordsFiltered: number;
|
package/index.js
CHANGED
|
@@ -1,16 +1,29 @@
|
|
|
1
|
-
// Áreum Tecnologia - Renan Moreira - renan.moreira@areum.com.br
|
|
2
|
-
const DataBaseCache = require('./lib/database-cache');
|
|
3
|
-
const DataBase = require('./lib/database');
|
|
4
|
-
const DataBaseHandler = require('./lib/databaseHandler');
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
1
|
+
// Áreum Tecnologia - Renan Moreira - renan.moreira@areum.com.br
|
|
2
|
+
const DataBaseCache = require('./lib/database-cache');
|
|
3
|
+
const DataBase = require('./lib/database');
|
|
4
|
+
const DataBaseHandler = require('./lib/databaseHandler');
|
|
5
|
+
const {
|
|
6
|
+
ArithmeticOperator,
|
|
7
|
+
ComparisonOperator,
|
|
8
|
+
LogicalOperator,
|
|
9
|
+
BitwiseOperator,
|
|
10
|
+
Operators
|
|
11
|
+
} = require('./lib/operators');
|
|
12
|
+
// We do not export the singleton by default in a library usually,
|
|
13
|
+
// but we export the classes so the user can instantiate them.
|
|
14
|
+
|
|
15
|
+
module.exports = {
|
|
16
|
+
DataBase,
|
|
17
|
+
Database: DataBase,
|
|
18
|
+
DataBaseHandler,
|
|
19
|
+
DatabaseHandler: DataBaseHandler,
|
|
20
|
+
DataBaseCache,
|
|
21
|
+
DatabaseCache: DataBaseCache,
|
|
22
|
+
raw: DataBaseHandler.raw,
|
|
23
|
+
// Categorized Static Enumerators
|
|
24
|
+
Operators,
|
|
25
|
+
ArithmeticOperator,
|
|
26
|
+
ComparisonOperator,
|
|
27
|
+
LogicalOperator,
|
|
28
|
+
BitwiseOperator
|
|
29
|
+
};
|
package/lib/databaseHandler.js
CHANGED
|
@@ -1,16 +1,13 @@
|
|
|
1
1
|
const stream = require('node:stream');
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
const upper = String(op).toUpperCase().trim();
|
|
12
|
-
return ALLOWED_OPERATORS.has(upper) ? upper : defaultOp;
|
|
13
|
-
}
|
|
2
|
+
const {
|
|
3
|
+
ArithmeticOperator,
|
|
4
|
+
ComparisonOperator,
|
|
5
|
+
LogicalOperator,
|
|
6
|
+
BitwiseOperator,
|
|
7
|
+
Operators,
|
|
8
|
+
ALLOWED_OPERATORS,
|
|
9
|
+
sanitizeOperator
|
|
10
|
+
} = require('./operators');
|
|
14
11
|
|
|
15
12
|
function sanitizeIdentifier(name) {
|
|
16
13
|
if (!name || typeof name !== 'string') return '';
|
|
@@ -106,6 +103,12 @@ class DatabaseHandler {
|
|
|
106
103
|
this._resetBuilder();
|
|
107
104
|
}
|
|
108
105
|
|
|
106
|
+
static ArithmeticOperator = ArithmeticOperator;
|
|
107
|
+
static ComparisonOperator = ComparisonOperator;
|
|
108
|
+
static LogicalOperator = LogicalOperator;
|
|
109
|
+
static BitwiseOperator = BitwiseOperator;
|
|
110
|
+
static Operators = Operators;
|
|
111
|
+
|
|
109
112
|
static raw(sql) {
|
|
110
113
|
return raw(sql);
|
|
111
114
|
}
|
|
@@ -462,11 +465,15 @@ class DatabaseHandler {
|
|
|
462
465
|
where(condition, operatorOrValue, maybeValue) {
|
|
463
466
|
return this._cloneWithBuilder(qb => {
|
|
464
467
|
if (qb.where.length > 0) {
|
|
465
|
-
qb.where.push(
|
|
468
|
+
qb.where.push(LogicalOperator.AND);
|
|
466
469
|
}
|
|
467
470
|
if (typeof condition === 'string') {
|
|
468
471
|
if (arguments.length === 2) {
|
|
469
|
-
|
|
472
|
+
if (operatorOrValue === ComparisonOperator.IS_NULL || operatorOrValue === ComparisonOperator.IS_NOT_NULL) {
|
|
473
|
+
qb.where.push({ [condition]: null, operator: operatorOrValue });
|
|
474
|
+
} else {
|
|
475
|
+
qb.where.push({ [condition]: operatorOrValue, operator: ComparisonOperator.EQUALS });
|
|
476
|
+
}
|
|
470
477
|
} else {
|
|
471
478
|
qb.where.push({ [condition]: maybeValue, operator: operatorOrValue });
|
|
472
479
|
}
|
|
@@ -474,10 +481,10 @@ class DatabaseHandler {
|
|
|
474
481
|
qb.where.push(...condition);
|
|
475
482
|
} else if (typeof condition === 'object' && condition !== null) {
|
|
476
483
|
for (const [k, v] of Object.entries(condition)) {
|
|
477
|
-
if (qb.where.length > 0 && qb.where[qb.where.length - 1] !==
|
|
478
|
-
qb.where.push(
|
|
484
|
+
if (qb.where.length > 0 && qb.where[qb.where.length - 1] !== LogicalOperator.AND && qb.where[qb.where.length - 1] !== LogicalOperator.OR) {
|
|
485
|
+
qb.where.push(LogicalOperator.AND);
|
|
479
486
|
}
|
|
480
|
-
qb.where.push({ [k]: v, operator:
|
|
487
|
+
qb.where.push({ [k]: v, operator: ComparisonOperator.EQUALS });
|
|
481
488
|
}
|
|
482
489
|
}
|
|
483
490
|
});
|
|
@@ -486,11 +493,15 @@ class DatabaseHandler {
|
|
|
486
493
|
orWhere(condition, operatorOrValue, maybeValue) {
|
|
487
494
|
return this._cloneWithBuilder(qb => {
|
|
488
495
|
if (qb.where.length > 0) {
|
|
489
|
-
qb.where.push(
|
|
496
|
+
qb.where.push(LogicalOperator.OR);
|
|
490
497
|
}
|
|
491
498
|
if (typeof condition === 'string') {
|
|
492
499
|
if (arguments.length === 2) {
|
|
493
|
-
|
|
500
|
+
if (operatorOrValue === ComparisonOperator.IS_NULL || operatorOrValue === ComparisonOperator.IS_NOT_NULL) {
|
|
501
|
+
qb.where.push({ [condition]: null, operator: operatorOrValue });
|
|
502
|
+
} else {
|
|
503
|
+
qb.where.push({ [condition]: operatorOrValue, operator: ComparisonOperator.EQUALS });
|
|
504
|
+
}
|
|
494
505
|
} else {
|
|
495
506
|
qb.where.push({ [condition]: maybeValue, operator: operatorOrValue });
|
|
496
507
|
}
|
|
@@ -670,7 +681,15 @@ class DatabaseHandler {
|
|
|
670
681
|
for (const key of Object.keys(flatObject)) {
|
|
671
682
|
if (!key.includes('[')) {
|
|
672
683
|
if (key !== '__proto__' && key !== 'constructor' && key !== 'prototype') {
|
|
673
|
-
|
|
684
|
+
const existing = result[key];
|
|
685
|
+
const incoming = flatObject[key];
|
|
686
|
+
if (existing && typeof existing === 'object' && (!incoming || typeof incoming !== 'object')) {
|
|
687
|
+
// Não sobrescreve um objeto já estruturado (ex: search vindo de search[value]) com valor primitivo
|
|
688
|
+
} else if (existing && typeof existing === 'object' && incoming && typeof incoming === 'object') {
|
|
689
|
+
result[key] = { ...existing, ...incoming };
|
|
690
|
+
} else {
|
|
691
|
+
result[key] = incoming;
|
|
692
|
+
}
|
|
674
693
|
}
|
|
675
694
|
continue;
|
|
676
695
|
}
|
|
@@ -684,7 +703,7 @@ class DatabaseHandler {
|
|
|
684
703
|
for (let i = 0; i < keys.length - 1; i++) {
|
|
685
704
|
const k = keys[i];
|
|
686
705
|
const nextKey = keys[i + 1];
|
|
687
|
-
if (current[k] === undefined) {
|
|
706
|
+
if (current[k] === undefined || current[k] === null || typeof current[k] !== 'object') {
|
|
688
707
|
current[k] = !isNaN(nextKey) ? [] : {};
|
|
689
708
|
}
|
|
690
709
|
current = current[k];
|
|
@@ -807,12 +826,18 @@ class DatabaseHandler {
|
|
|
807
826
|
const opKey = keys.find(k => k.toLowerCase() === 'operator');
|
|
808
827
|
let op = sanitizeOperator(opKey ? param[opKey] : undefined, defaultOp);
|
|
809
828
|
|
|
829
|
+
if (op === ComparisonOperator.IS_NULL || (value === null && (op === ComparisonOperator.EQUALS || op === ComparisonOperator.IS))) {
|
|
830
|
+
conditions.push(`${colSql} IS NULL`);
|
|
831
|
+
continue;
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
if (op === ComparisonOperator.IS_NOT_NULL || (value === null && (op === ComparisonOperator.NOT_EQUALS || op === ComparisonOperator.NOT_EQUALS_ALT || op === ComparisonOperator.IS_NOT))) {
|
|
835
|
+
conditions.push(`${colSql} IS NOT NULL`);
|
|
836
|
+
continue;
|
|
837
|
+
}
|
|
838
|
+
|
|
810
839
|
if (value === null) {
|
|
811
|
-
|
|
812
|
-
conditions.push(`${colSql} IS NULL`);
|
|
813
|
-
} else {
|
|
814
|
-
conditions.push(`${colSql} IS NOT NULL`);
|
|
815
|
-
}
|
|
840
|
+
conditions.push(`${colSql} IS NULL`);
|
|
816
841
|
continue;
|
|
817
842
|
}
|
|
818
843
|
|
|
@@ -954,7 +979,18 @@ class DatabaseHandler {
|
|
|
954
979
|
const parsedDraw = parseInt(draw, 10) || 0;
|
|
955
980
|
|
|
956
981
|
try {
|
|
957
|
-
|
|
982
|
+
let finalStrict = [];
|
|
983
|
+
if (Array.isArray(strictCondition)) {
|
|
984
|
+
finalStrict = [...strictCondition];
|
|
985
|
+
} else if (strictCondition && typeof strictCondition === 'object') {
|
|
986
|
+
const entries = Object.entries(strictCondition);
|
|
987
|
+
for (let i = 0; i < entries.length; i++) {
|
|
988
|
+
const [k, v] = entries[i];
|
|
989
|
+
if (i > 0) finalStrict.push('AND');
|
|
990
|
+
finalStrict.push({ [k]: v });
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
|
|
958
994
|
const softCol = this._getSoftDeleteColumn();
|
|
959
995
|
if (softCol && !this._qb.withTrashed) {
|
|
960
996
|
if (finalStrict.length > 0) finalStrict.push('AND');
|
|
@@ -969,14 +1005,25 @@ class DatabaseHandler {
|
|
|
969
1005
|
const finalBindings = [...baseWhere.bindings];
|
|
970
1006
|
const finalWhereClauses = baseWhere.sql ? [baseWhere.sql] : [];
|
|
971
1007
|
|
|
1008
|
+
// Normaliza columns para suportar tanto Array quanto Objeto indexado ({ '0': {...}, '1': {...} })
|
|
1009
|
+
const colsArray = Array.isArray(columns)
|
|
1010
|
+
? columns
|
|
1011
|
+
: (columns && typeof columns === 'object' ? Object.values(columns) : []);
|
|
1012
|
+
|
|
972
1013
|
const dtSearchClauses = [];
|
|
973
|
-
if (
|
|
974
|
-
|
|
975
|
-
|
|
1014
|
+
if (colsArray.length > 0) {
|
|
1015
|
+
// Normaliza o termo de busca global (suporta search.value, string direta ou fallback q)
|
|
1016
|
+
const rawSearchVal = typeof search === 'string'
|
|
1017
|
+
? search
|
|
1018
|
+
: (search && search.value != null ? search.value : (dtQuery.q != null ? dtQuery.q : ''));
|
|
1019
|
+
const globalSearchTerm = String(rawSearchVal ?? '').trim();
|
|
1020
|
+
|
|
1021
|
+
if (globalSearchTerm !== '') {
|
|
1022
|
+
const searchableCols = colsArray.filter(c => c && c.data && isTrue(c.searchable));
|
|
976
1023
|
if (searchableCols.length > 0) {
|
|
977
|
-
const isRegex = isTrue(search.regex);
|
|
1024
|
+
const isRegex = (typeof search === 'object' && search !== null) ? isTrue(search.regex) : false;
|
|
978
1025
|
const operator = isRegex ? 'REGEXP' : 'LIKE';
|
|
979
|
-
const term = isRegex ?
|
|
1026
|
+
const term = isRegex ? globalSearchTerm : `%${globalSearchTerm}%`;
|
|
980
1027
|
|
|
981
1028
|
const orClauses = searchableCols.map(c => `${safeColumn(c.data)} ${operator} ?`);
|
|
982
1029
|
dtSearchClauses.push(`(${orClauses.join(' OR ')})`);
|
|
@@ -986,14 +1033,23 @@ class DatabaseHandler {
|
|
|
986
1033
|
}
|
|
987
1034
|
}
|
|
988
1035
|
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
const
|
|
993
|
-
const
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
1036
|
+
// Busca individual por coluna
|
|
1037
|
+
for (const col of colsArray) {
|
|
1038
|
+
if (col && col.data && isTrue(col.searchable)) {
|
|
1039
|
+
const colSearch = col.search;
|
|
1040
|
+
const colVal = typeof colSearch === 'string'
|
|
1041
|
+
? colSearch
|
|
1042
|
+
: (colSearch && colSearch.value != null ? colSearch.value : '');
|
|
1043
|
+
const colSearchTerm = String(colVal ?? '').trim();
|
|
1044
|
+
|
|
1045
|
+
if (colSearchTerm !== '') {
|
|
1046
|
+
const isRegex = (typeof colSearch === 'object' && colSearch !== null) ? isTrue(colSearch.regex) : false;
|
|
1047
|
+
const operator = isRegex ? 'REGEXP' : 'LIKE';
|
|
1048
|
+
const term = isRegex ? colSearchTerm : `%${colSearchTerm}%`;
|
|
1049
|
+
|
|
1050
|
+
dtSearchClauses.push(`${safeColumn(col.data)} ${operator} ?`);
|
|
1051
|
+
finalBindings.push(term);
|
|
1052
|
+
}
|
|
997
1053
|
}
|
|
998
1054
|
}
|
|
999
1055
|
}
|
|
@@ -1008,12 +1064,18 @@ class DatabaseHandler {
|
|
|
1008
1064
|
const joinClause = this._buildJoinClauses(this._qb.joins);
|
|
1009
1065
|
|
|
1010
1066
|
let orderSql = '';
|
|
1011
|
-
if (order &&
|
|
1067
|
+
if (order && colsArray.length > 0) {
|
|
1012
1068
|
const orderArray = Array.isArray(order) ? order : Object.values(order);
|
|
1013
1069
|
const orderParts = [];
|
|
1014
1070
|
for (const ord of orderArray) {
|
|
1015
|
-
if (!ord
|
|
1016
|
-
|
|
1071
|
+
if (!ord) continue;
|
|
1072
|
+
let colDef = null;
|
|
1073
|
+
if (ord.column !== undefined && ord.column !== null && ord.column !== '') {
|
|
1074
|
+
colDef = colsArray[parseInt(ord.column, 10)];
|
|
1075
|
+
} else if (ord.name || ord.data) {
|
|
1076
|
+
const targetName = ord.name || ord.data;
|
|
1077
|
+
colDef = colsArray.find(c => c && (c.name === targetName || c.data === targetName));
|
|
1078
|
+
}
|
|
1017
1079
|
if (colDef && isTrue(colDef.orderable) && colDef.data) {
|
|
1018
1080
|
const orderDir = ord.dir && String(ord.dir).toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
|
|
1019
1081
|
orderParts.push(`${safeColumn(colDef.data)} ${orderDir}`);
|
|
@@ -1410,4 +1472,10 @@ class DatabaseHandler {
|
|
|
1410
1472
|
}
|
|
1411
1473
|
}
|
|
1412
1474
|
|
|
1475
|
+
DatabaseHandler.ArithmeticOperator = ArithmeticOperator;
|
|
1476
|
+
DatabaseHandler.ComparisonOperator = ComparisonOperator;
|
|
1477
|
+
DatabaseHandler.LogicalOperator = LogicalOperator;
|
|
1478
|
+
DatabaseHandler.BitwiseOperator = BitwiseOperator;
|
|
1479
|
+
DatabaseHandler.Operators = Operators;
|
|
1480
|
+
|
|
1413
1481
|
module.exports = DatabaseHandler;
|
package/lib/operators.js
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Operadores Aritméticos
|
|
5
|
+
* Usados para realizar cálculos matemáticos com dados numéricos:
|
|
6
|
+
* + : Adição (Soma)
|
|
7
|
+
* - : Subtração
|
|
8
|
+
* * : Multiplicação
|
|
9
|
+
* / : Divisão
|
|
10
|
+
* % ou MOD : Módulo (resto da divisão inteira)
|
|
11
|
+
* DIV : Divisão inteira (descarta a parte decimal)
|
|
12
|
+
*/
|
|
13
|
+
const ArithmeticOperator = Object.freeze({
|
|
14
|
+
ADD: '+',
|
|
15
|
+
PLUS: '+',
|
|
16
|
+
SUBTRACT: '-',
|
|
17
|
+
MINUS: '-',
|
|
18
|
+
MULTIPLY: '*',
|
|
19
|
+
DIVIDE: '/',
|
|
20
|
+
MODULO: '%',
|
|
21
|
+
MOD: 'MOD',
|
|
22
|
+
DIV: 'DIV',
|
|
23
|
+
INTEGER_DIVIDE: 'DIV'
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Operadores de Comparação (Relacionais)
|
|
28
|
+
* Usados para comparar dois valores e retornar verdadeiro (1), falso (0) ou NULL:
|
|
29
|
+
* = : Igual a
|
|
30
|
+
* != ou <> : Diferente de
|
|
31
|
+
* > : Maior que
|
|
32
|
+
* < : Menor que
|
|
33
|
+
* >= : Maior ou igual a
|
|
34
|
+
* <= : Menor ou igual a
|
|
35
|
+
* BETWEEN : Verifica se o valor está dentro de um intervalo
|
|
36
|
+
* IN : Verifica se o valor corresponde a qualquer elemento de uma lista
|
|
37
|
+
* LIKE : Compara padrões de texto (usado com coringas como % e _)
|
|
38
|
+
* IS NULL / IS NOT NULL : Testa se um valor é nulo ou não nulo
|
|
39
|
+
*/
|
|
40
|
+
const ComparisonOperator = Object.freeze({
|
|
41
|
+
EQUALS: '=',
|
|
42
|
+
EQUAL: '=',
|
|
43
|
+
EQ: '=',
|
|
44
|
+
NOT_EQUALS: '!=',
|
|
45
|
+
NOT_EQUAL: '!=',
|
|
46
|
+
NEQ: '!=',
|
|
47
|
+
NOT_EQUALS_ALT: '<>',
|
|
48
|
+
DIFFERENT: '<>',
|
|
49
|
+
GREATER_THAN: '>',
|
|
50
|
+
GT: '>',
|
|
51
|
+
LESS_THAN: '<',
|
|
52
|
+
LT: '<',
|
|
53
|
+
GREATER_THAN_OR_EQUAL: '>=',
|
|
54
|
+
GTE: '>=',
|
|
55
|
+
LESS_THAN_OR_EQUAL: '<=',
|
|
56
|
+
LTE: '<=',
|
|
57
|
+
BETWEEN: 'BETWEEN',
|
|
58
|
+
NOT_BETWEEN: 'NOT BETWEEN',
|
|
59
|
+
IN: 'IN',
|
|
60
|
+
NOT_IN: 'NOT IN',
|
|
61
|
+
LIKE: 'LIKE',
|
|
62
|
+
NOT_LIKE: 'NOT LIKE',
|
|
63
|
+
IS_NULL: 'IS NULL',
|
|
64
|
+
IS_NOT_NULL: 'IS NOT NULL',
|
|
65
|
+
IS: 'IS',
|
|
66
|
+
IS_NOT: 'IS NOT',
|
|
67
|
+
REGEXP: 'REGEXP',
|
|
68
|
+
NOT_REGEXP: 'NOT REGEXP'
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Operadores Lógicos
|
|
73
|
+
* Usados para combinar múltiplas condições em uma consulta:
|
|
74
|
+
* AND : Retorna verdadeiro se todas as condições forem verdadeiras
|
|
75
|
+
* OR : Retorna verdadeiro se pelo menos uma das condições for verdadeira
|
|
76
|
+
* NOT ou ! : Inverte o valor lógico (transforma verdadeiro em falso e vice-versa)
|
|
77
|
+
*/
|
|
78
|
+
const LogicalOperator = Object.freeze({
|
|
79
|
+
AND: 'AND',
|
|
80
|
+
OR: 'OR',
|
|
81
|
+
NOT: 'NOT',
|
|
82
|
+
NOT_ALT: '!',
|
|
83
|
+
BANG: '!'
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Operadores Bit a Bit (Bitwise)
|
|
88
|
+
* Realizam operações em nível de bits:
|
|
89
|
+
* & : E bit a bit (AND)
|
|
90
|
+
* | : OU bit a bit (OR)
|
|
91
|
+
* ^ : OU exclusivo bit a bit (XOR)
|
|
92
|
+
* >> : Deslocamento à direita (Right shift)
|
|
93
|
+
* << : Deslocamento à esquerda (Left shift)
|
|
94
|
+
*/
|
|
95
|
+
const BitwiseOperator = Object.freeze({
|
|
96
|
+
AND: '&',
|
|
97
|
+
BITWISE_AND: '&',
|
|
98
|
+
OR: '|',
|
|
99
|
+
BITWISE_OR: '|',
|
|
100
|
+
XOR: '^',
|
|
101
|
+
BITWISE_XOR: '^',
|
|
102
|
+
RIGHT_SHIFT: '>>',
|
|
103
|
+
LEFT_SHIFT: '<<',
|
|
104
|
+
SHR: '>>',
|
|
105
|
+
SHL: '<<'
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Agrupador central de todos os enumeradores de operadores
|
|
110
|
+
*/
|
|
111
|
+
const Operators = Object.freeze({
|
|
112
|
+
Arithmetic: ArithmeticOperator,
|
|
113
|
+
Comparison: ComparisonOperator,
|
|
114
|
+
Logical: LogicalOperator,
|
|
115
|
+
Bitwise: BitwiseOperator,
|
|
116
|
+
// Aliases em Português
|
|
117
|
+
Aritmeticos: ArithmeticOperator,
|
|
118
|
+
Comparacao: ComparisonOperator,
|
|
119
|
+
Logicos: LogicalOperator,
|
|
120
|
+
BitwisePT: BitwiseOperator
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
// Set com todos os operadores permitidos para sanitização segura
|
|
124
|
+
const ALLOWED_OPERATORS = new Set([
|
|
125
|
+
...Object.values(ComparisonOperator),
|
|
126
|
+
...Object.values(ArithmeticOperator),
|
|
127
|
+
...Object.values(LogicalOperator),
|
|
128
|
+
...Object.values(BitwiseOperator)
|
|
129
|
+
]);
|
|
130
|
+
|
|
131
|
+
function sanitizeOperator(op, defaultOp = '=') {
|
|
132
|
+
if (!op) return defaultOp;
|
|
133
|
+
const upper = String(op).toUpperCase().trim();
|
|
134
|
+
return ALLOWED_OPERATORS.has(upper) ? upper : defaultOp;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
module.exports = {
|
|
138
|
+
ArithmeticOperator,
|
|
139
|
+
ComparisonOperator,
|
|
140
|
+
LogicalOperator,
|
|
141
|
+
BitwiseOperator,
|
|
142
|
+
Operators,
|
|
143
|
+
ALLOWED_OPERATORS,
|
|
144
|
+
sanitizeOperator
|
|
145
|
+
};
|
|
146
|
+
|
package/package.json
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@areumtecnologia/mysql-db-handler",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.1.1",
|
|
4
4
|
"description": "High-scale enterprise Micro-ORM and MySQL Data Mapper with connection pooling, read/write splitting, eager loading, keyset pagination, soft deletes, and fluent query builder for Node.js.",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"types": "index.d.ts",
|
|
7
7
|
"scripts": {
|
|
8
|
-
"test": "node tests/security_and_robustness.test.js && node tests/update_operators.test.js && node tests/selectToDatatable.test.js && node tests/transactions.test.js && node tests/customersSales.test.js && node tests/joins_and_eager_loading.test.js && node tests/read_write_splitting.test.js && node tests/streaming_and_cursor.test.js && node tests/soft_deletes_and_hooks.test.js && node tests/schema_validation_and_hidden.test.js"
|
|
8
|
+
"test": "node tests/security_and_robustness.test.js && node tests/update_operators.test.js && node tests/selectToDatatable.test.js && node tests/transactions.test.js && node tests/customersSales.test.js && node tests/joins_and_eager_loading.test.js && node tests/read_write_splitting.test.js && node tests/streaming_and_cursor.test.js && node tests/soft_deletes_and_hooks.test.js && node tests/schema_validation_and_hidden.test.js && node tests/operators.test.js"
|
|
9
9
|
},
|
|
10
10
|
"author": "Renan Moreira / Áreum Tecnologia",
|
|
11
11
|
"license": "MIT",
|