@areumtecnologia/mysql-db-handler 2.1.0 → 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/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>;
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
- // We do not export the singleton by default in a library usually,
6
- // but we export the classes so the user can instantiate them.
7
-
8
- module.exports = {
9
- DataBase,
10
- Database: DataBase,
11
- DataBaseHandler,
12
- DatabaseHandler: DataBaseHandler,
13
- DataBaseCache,
14
- DatabaseCache: DataBaseCache,
15
- raw: DataBaseHandler.raw
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
+ };
@@ -1,16 +1,13 @@
1
1
  const stream = require('node:stream');
2
-
3
- const ALLOWED_OPERATORS = new Set([
4
- '=', '!=', '<>', '>', '>=', '<', '<=',
5
- 'LIKE', 'NOT LIKE', 'IN', 'NOT IN',
6
- 'REGEXP', 'NOT REGEXP', 'IS', 'IS NOT', 'BETWEEN', 'NOT BETWEEN'
7
- ]);
8
-
9
- function sanitizeOperator(op, defaultOp = '=') {
10
- if (!op) return defaultOp;
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('AND');
468
+ qb.where.push(LogicalOperator.AND);
466
469
  }
467
470
  if (typeof condition === 'string') {
468
471
  if (arguments.length === 2) {
469
- qb.where.push({ [condition]: operatorOrValue, operator: '=' });
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] !== 'AND' && qb.where[qb.where.length - 1] !== 'OR') {
478
- qb.where.push('AND');
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('OR');
496
+ qb.where.push(LogicalOperator.OR);
490
497
  }
491
498
  if (typeof condition === 'string') {
492
499
  if (arguments.length === 2) {
493
- qb.where.push({ [condition]: operatorOrValue, operator: '=' });
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
  }
@@ -815,12 +826,18 @@ class DatabaseHandler {
815
826
  const opKey = keys.find(k => k.toLowerCase() === 'operator');
816
827
  let op = sanitizeOperator(opKey ? param[opKey] : undefined, defaultOp);
817
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
+
818
839
  if (value === null) {
819
- if (op === '=' || op === 'IS') {
820
- conditions.push(`${colSql} IS NULL`);
821
- } else {
822
- conditions.push(`${colSql} IS NOT NULL`);
823
- }
840
+ conditions.push(`${colSql} IS NULL`);
824
841
  continue;
825
842
  }
826
843
 
@@ -1455,4 +1472,10 @@ class DatabaseHandler {
1455
1472
  }
1456
1473
  }
1457
1474
 
1475
+ DatabaseHandler.ArithmeticOperator = ArithmeticOperator;
1476
+ DatabaseHandler.ComparisonOperator = ComparisonOperator;
1477
+ DatabaseHandler.LogicalOperator = LogicalOperator;
1478
+ DatabaseHandler.BitwiseOperator = BitwiseOperator;
1479
+ DatabaseHandler.Operators = Operators;
1480
+
1458
1481
  module.exports = DatabaseHandler;
@@ -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.1.0",
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",