zormz 1.3.0 → 1.4.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/README.md CHANGED
@@ -84,16 +84,44 @@ export const prueba1 = defineTable("prueba1", {
84
84
  resultado: int().Default(0).$(),
85
85
  fechaRegistro: timestamp().required().now().$(),
86
86
  fechaUpdate: timestamp().required().now().onUpdate().$()
87
-
88
87
  });
89
88
 
89
+ ```
90
+ o
91
+ ```ts
92
+ export function generateTables() {
93
+ return {
94
+ colaborador: defineTable("colaborador", {
95
+ idcolaborador: int().Pk().$(),
96
+ idusuario: int().Required().$(),
97
+ nombrecompleto: varchar(150).$(),
98
+ dni: varchar(9).$(),
99
+ rol: varchar(50).$(),
100
+ diastrabajo: varchar(200).Default("sabado - domingo").$(),
101
+ activo: bool().default(true).$(),
102
+ }),
103
+ permisos: defineTable("permisos", {
104
+ idpermiso: int().Pk().$(),
105
+ nombre: varchar(100).$(),
106
+ descripcion: varchar(250).$(),
107
+ estado: bool().default(true).$(),
108
+ }),
109
+ detallespermisos: defineTable("detallespermisos", {
110
+ iddetallepermiso: int().Pk().$(),
111
+ idcolaborador: int().$(),
112
+ idppermiso: int().Default(0).$(),
113
+ }),
114
+ };
115
+ }
90
116
  ```
91
117
 
92
118
  ### Notas importantes
93
119
  * **.pk()** define la columna como clave primaria
94
120
  * **.Default()** entrega un valor por defecto
95
121
  * **.$()** finaliza la definicion y entrega un valor compatible con *$columns*
96
-
122
+ * **.required()** Indica que los valores de la fila no podran ser null, si o si un valor obligatorio
123
+ * **.now()** Solo esta disponible para timestamp , indica fecha automatica de registra
124
+ * **.onUpdate()** Tomara la fecha actual cada ves que se haga un update
97
125
  ## Generacion de tablas
98
126
  ```ts
99
127
  generateTable(prueba1(), prueba1.$columns);
@@ -102,6 +130,11 @@ Esto crea la tabla en la base de datos respetando tipos, claves primarias y valo
102
130
 
103
131
  ---
104
132
 
133
+ ## Eliminar tablas
134
+ ```ts
135
+ await dropTable(prueba4());
136
+ ```
137
+
105
138
  ## Insertar Datos
106
139
 
107
140
  ```ts
@@ -124,6 +157,7 @@ const datos = await DB.select()
124
157
  ---
125
158
 
126
159
  ## Update de Datos
160
+ ### .set() Recibe un objeto con clave valor de las tablas o un array con UP
127
161
  ```ts
128
162
  await DB.Update(prueba1())
129
163
  .set({ valor: "nuevo valor", resultado: 2 })
@@ -131,6 +165,16 @@ await DB.Update(prueba1())
131
165
  .execute();
132
166
 
133
167
  ```
168
+ o
169
+ ```ts
170
+ //Usar la funcion UP
171
+ const response = await DB.Update(producto())
172
+ .set([UP(producto.stockactual, `${producto.stockactual} - 4`, true)])
173
+ .where(eq(producto.idproducto, 4))
174
+ .execute();
175
+
176
+ ```
177
+
134
178
  ---
135
179
  ## Delete de Datos
136
180
  ```ts
@@ -139,7 +183,29 @@ await DB.Delete(prueba1())
139
183
  .execute();
140
184
 
141
185
  ```
186
+ ## JOINS
187
+ ```ts
188
+ const { detallespermisos, colaborador, permisos } = generateTables();
189
+
190
+ const response = await DB.Select([
191
+ detallespermisos.iddetallepermiso,
192
+ colaborador.nombrecompleto,
193
+ colaborador.dni,
194
+ permisos.nombre,
195
+ permisos.estado,
196
+ ])
197
+ .from(detallespermisos())
198
+ .innerJOIN(
199
+ colaborador(),
200
+ eq(colaborador.idcolaborador, detallespermisos.idcolaborador, false),
201
+ )
202
+ .innerJOIN(
203
+ permisos(),
204
+ eq(permisos.idpermiso, detallespermisos.idppermiso, false),
205
+ )
206
+ .execute();
142
207
 
208
+ ```
143
209
  ---
144
210
 
145
211
  ## Ejemplo de Uso
@@ -156,6 +222,8 @@ const conexion: connecionLocal = {
156
222
  };
157
223
 
158
224
  getConexion("pg", conexion);
225
+ //MYSQL
226
+ //getConexion("mysql", conexion);
159
227
 
160
228
  const prueba1 = defineTable("prueba1", {
161
229
  id: int().Pk().$(),
@@ -193,7 +261,8 @@ pruebaData().catch(console.error);
193
261
  * ORM en version inicial con enfoque de tipado y autompletado
194
262
  * Compatible con **MYSQL** y **PG**
195
263
  * Preparado para extenderse
196
-
264
+ * Las versiones +1.3.0 son mas estables , las anteriores estaban en desarrollo y presentan multiples errores
265
+ * version estable 1.4.0
197
266
  ## Licencia
198
267
 
199
268
  ISC © Yukio-kayaba
package/dist/index.d.mts CHANGED
@@ -28,7 +28,14 @@ type IntType = {
28
28
  unique?: boolean;
29
29
  unsingned:number;
30
30
  autoIncrement?: boolean;
31
- };
31
+ };
32
+
33
+
34
+ interface UpdateParams {
35
+ campoUp: string;
36
+ newCampoUp: string;
37
+ dataTable?: boolean;
38
+ }
32
39
 
33
40
  interface connecionLocal {
34
41
  host: string;
@@ -41,6 +48,7 @@ interface Consultas {
41
48
  query: string;
42
49
  valores?: any[] | [[]];
43
50
  mensaje?: string;
51
+ alertar?: boolean;
44
52
  }
45
53
  interface connecionRed {
46
54
  connectionString: string;
@@ -53,7 +61,7 @@ declare class BDconnection {
53
61
  constructor(bd: connectionDB, datos: connecionLocal | connecionRed);
54
62
  private conexionMysql;
55
63
  private connectionPG;
56
- executeConsulta({ query, valores, mensaje, }: Consultas): Promise<any>;
64
+ executeConsulta({ query, valores, mensaje, alertar, }: Consultas): Promise<any>;
57
65
  }
58
66
  declare function getTipoConexion(): connectionDB;
59
67
  /**
@@ -94,6 +102,7 @@ type TableProxy<TCols> = {
94
102
  */
95
103
  declare function defineTable<T extends Record<string, ColumnDefinition>>(tableName: string, columns: T): TableProxy<T>;
96
104
  declare function generateTable<T extends Record<string, ColumnDefinition>>(tabla: string, columns: T): Promise<void>;
105
+ declare function dropTable(nombreTabla: string): Promise<void>;
97
106
 
98
107
  declare class DeleteR {
99
108
  #private;
@@ -222,8 +231,10 @@ declare class Update {
222
231
  * @param {Valores} valores - valores a actualizar
223
232
  * @example
224
233
  * .set({'campo1':'valor1', 'campo2':'valor2'})
234
+ * .set([UP(producto.stockactual,producto.stockactual)])
235
+ * set([UP(producto.stockactual, `${producto.stockactual} - 4`, true)])
225
236
  */
226
- set(valores: Valores): this;
237
+ set(valores: Valores | UpdateParams[]): this;
227
238
  /**
228
239
  * @param {string} condicion - valor condicional
229
240
  * @example
@@ -362,6 +373,17 @@ declare const MENOR: (valor: string, valor2: string) => string;
362
373
  * @returns
363
374
  */
364
375
  declare const CURRENT_TIMESTAMP: () => string;
376
+ /**
377
+ * @param {string} dataUpdate - campo a actualizar
378
+ * @param {string} newdataUpdate - valor del campo a actualizar
379
+ * @param {boolean} activo - en caso de realizar operaciones matematicas con el mismo campo [true]
380
+ * @example
381
+ *
382
+ *UP(producto.stockactual, `${producto.stockactual} - 4`, true)
383
+ * UP(producto.stockactual,producto.stockactual, true)
384
+ * @returns
385
+ */
386
+ declare const UP: (dataUpdate: string, newdataUpdate: string, activo?: boolean) => UpdateParams;
365
387
 
366
388
  declare class IntColumn {
367
389
  private requerido;
@@ -428,4 +450,4 @@ declare class Money {
428
450
  }
429
451
  declare function money(presicion?: number, decimales?: number): Money;
430
452
 
431
- export { AND, BDconnection, CURRENT_TIMESTAMP, type Consultas, DB, DeleteR, ILIKE, MAYOR, MENOR, NOTNULL, NOW, NULL, OR, ORQ, QueryBuilder, Select, type TableProxy, type Tipos, Update, type Valores, type arrayData, type arrayDatas, bool, type connecionLocal, type connecionRed, type connectionDB, defineTable, eq, generateTable, getConexion, getRed, getTipoConexion, int, money, timestamp, type valor, varchar };
453
+ export { AND, BDconnection, CURRENT_TIMESTAMP, type Consultas, DB, DeleteR, ILIKE, MAYOR, MENOR, NOTNULL, NOW, NULL, OR, ORQ, QueryBuilder, Select, type TableProxy, type Tipos, UP, Update, type Valores, type arrayData, type arrayDatas, bool, type connecionLocal, type connecionRed, type connectionDB, defineTable, dropTable, eq, generateTable, getConexion, getRed, getTipoConexion, int, money, timestamp, type valor, varchar };
package/dist/index.d.ts CHANGED
@@ -28,7 +28,14 @@ type IntType = {
28
28
  unique?: boolean;
29
29
  unsingned:number;
30
30
  autoIncrement?: boolean;
31
- };
31
+ };
32
+
33
+
34
+ interface UpdateParams {
35
+ campoUp: string;
36
+ newCampoUp: string;
37
+ dataTable?: boolean;
38
+ }
32
39
 
33
40
  interface connecionLocal {
34
41
  host: string;
@@ -41,6 +48,7 @@ interface Consultas {
41
48
  query: string;
42
49
  valores?: any[] | [[]];
43
50
  mensaje?: string;
51
+ alertar?: boolean;
44
52
  }
45
53
  interface connecionRed {
46
54
  connectionString: string;
@@ -53,7 +61,7 @@ declare class BDconnection {
53
61
  constructor(bd: connectionDB, datos: connecionLocal | connecionRed);
54
62
  private conexionMysql;
55
63
  private connectionPG;
56
- executeConsulta({ query, valores, mensaje, }: Consultas): Promise<any>;
64
+ executeConsulta({ query, valores, mensaje, alertar, }: Consultas): Promise<any>;
57
65
  }
58
66
  declare function getTipoConexion(): connectionDB;
59
67
  /**
@@ -94,6 +102,7 @@ type TableProxy<TCols> = {
94
102
  */
95
103
  declare function defineTable<T extends Record<string, ColumnDefinition>>(tableName: string, columns: T): TableProxy<T>;
96
104
  declare function generateTable<T extends Record<string, ColumnDefinition>>(tabla: string, columns: T): Promise<void>;
105
+ declare function dropTable(nombreTabla: string): Promise<void>;
97
106
 
98
107
  declare class DeleteR {
99
108
  #private;
@@ -222,8 +231,10 @@ declare class Update {
222
231
  * @param {Valores} valores - valores a actualizar
223
232
  * @example
224
233
  * .set({'campo1':'valor1', 'campo2':'valor2'})
234
+ * .set([UP(producto.stockactual,producto.stockactual)])
235
+ * set([UP(producto.stockactual, `${producto.stockactual} - 4`, true)])
225
236
  */
226
- set(valores: Valores): this;
237
+ set(valores: Valores | UpdateParams[]): this;
227
238
  /**
228
239
  * @param {string} condicion - valor condicional
229
240
  * @example
@@ -362,6 +373,17 @@ declare const MENOR: (valor: string, valor2: string) => string;
362
373
  * @returns
363
374
  */
364
375
  declare const CURRENT_TIMESTAMP: () => string;
376
+ /**
377
+ * @param {string} dataUpdate - campo a actualizar
378
+ * @param {string} newdataUpdate - valor del campo a actualizar
379
+ * @param {boolean} activo - en caso de realizar operaciones matematicas con el mismo campo [true]
380
+ * @example
381
+ *
382
+ *UP(producto.stockactual, `${producto.stockactual} - 4`, true)
383
+ * UP(producto.stockactual,producto.stockactual, true)
384
+ * @returns
385
+ */
386
+ declare const UP: (dataUpdate: string, newdataUpdate: string, activo?: boolean) => UpdateParams;
365
387
 
366
388
  declare class IntColumn {
367
389
  private requerido;
@@ -428,4 +450,4 @@ declare class Money {
428
450
  }
429
451
  declare function money(presicion?: number, decimales?: number): Money;
430
452
 
431
- export { AND, BDconnection, CURRENT_TIMESTAMP, type Consultas, DB, DeleteR, ILIKE, MAYOR, MENOR, NOTNULL, NOW, NULL, OR, ORQ, QueryBuilder, Select, type TableProxy, type Tipos, Update, type Valores, type arrayData, type arrayDatas, bool, type connecionLocal, type connecionRed, type connectionDB, defineTable, eq, generateTable, getConexion, getRed, getTipoConexion, int, money, timestamp, type valor, varchar };
453
+ export { AND, BDconnection, CURRENT_TIMESTAMP, type Consultas, DB, DeleteR, ILIKE, MAYOR, MENOR, NOTNULL, NOW, NULL, OR, ORQ, QueryBuilder, Select, type TableProxy, type Tipos, UP, Update, type Valores, type arrayData, type arrayDatas, bool, type connecionLocal, type connecionRed, type connectionDB, defineTable, dropTable, eq, generateTable, getConexion, getRed, getTipoConexion, int, money, timestamp, type valor, varchar };
package/dist/index.js CHANGED
@@ -52,9 +52,11 @@ __export(index_exports, {
52
52
  ORQ: () => ORQ,
53
53
  QueryBuilder: () => QueryBuilder,
54
54
  Select: () => Select,
55
+ UP: () => UP,
55
56
  Update: () => Update,
56
57
  bool: () => bool,
57
58
  defineTable: () => defineTable,
59
+ dropTable: () => dropTable,
58
60
  eq: () => eq,
59
61
  generateTable: () => generateTable,
60
62
  getConexion: () => getConexion,
@@ -67,6 +69,22 @@ __export(index_exports, {
67
69
  });
68
70
  module.exports = __toCommonJS(index_exports);
69
71
 
72
+ // conection/validator.ts
73
+ var Validator = class {
74
+ };
75
+ Validator.isValidTable = (val) => /^(?![0-9_])[a-z][a-z0-9_]{0,62}$/.test(val);
76
+ Validator.isValidColumn = (val) => /^[a-z][a-z0-9_]{0,62}$/.test(val);
77
+ Validator.isValidUsername = (val) => /^[a-zA-Z0-9\-_]+$/.test(val);
78
+ var RESERVED_WORDS = /* @__PURE__ */ new Set([
79
+ "select",
80
+ "table",
81
+ "user",
82
+ "order",
83
+ "group",
84
+ "where",
85
+ "join"
86
+ ]);
87
+
70
88
  // conection/db.ts
71
89
  var BDconnection = class {
72
90
  constructor(bd, datos) {
@@ -88,7 +106,9 @@ var BDconnection = class {
88
106
  });
89
107
  return pool;
90
108
  } catch (error) {
91
- throw new Error("Mysql no esta instalado . para instalarlo corre : npm install mysql2 ");
109
+ throw new Error(
110
+ "Mysql no esta instalado . para instalarlo corre : npm install mysql2 "
111
+ );
92
112
  }
93
113
  }
94
114
  async connectionPG() {
@@ -114,14 +134,18 @@ var BDconnection = class {
114
134
  console.error(
115
135
  "PostgreSQL no esta instalado. para instalarlo corre : npm install pg"
116
136
  );
117
- throw new Error("PostgreSQL no esta instalado. para instalarlo corre : npm install pg");
137
+ throw new Error(
138
+ "PostgreSQL no esta instalado. para instalarlo corre : npm install pg"
139
+ );
118
140
  }
119
141
  }
120
142
  async executeConsulta({
121
143
  query,
122
144
  valores = void 0,
123
- mensaje
145
+ mensaje,
146
+ alertar = true
124
147
  }) {
148
+ console.log(query);
125
149
  try {
126
150
  if (this.tipo === "mysql") {
127
151
  const pool = await this.conexionMysql();
@@ -153,6 +177,7 @@ var BDconnection = class {
153
177
  }
154
178
  } catch (error) {
155
179
  console.log(error);
180
+ if (!alertar) return;
156
181
  if (typeof error === "object" && error !== null && "code" in error) {
157
182
  if (error.code === "ETIMEDOUT") {
158
183
  throw new Error(`Su red esta limitando el acceso`);
@@ -166,14 +191,16 @@ var conexionZORMZ3691;
166
191
  var tipoConexionZORMZ3691;
167
192
  function getTipoConexion() {
168
193
  if (!tipoConexionZORMZ3691) {
169
- throw new Error("La conexi\xF3n no ha sido inicializada. Por favor, llama a getConexion() primero.");
194
+ throw new Error(
195
+ "La conexi\xF3n no ha sido inicializada. Por favor, llama a getConexion() primero."
196
+ );
170
197
  }
171
198
  return tipoConexionZORMZ3691;
172
199
  }
173
200
  async function getConexion(bd, datos) {
174
201
  conexionZORMZ3691 = new BDconnection(bd, datos);
175
202
  tipoConexionZORMZ3691 = conexionZORMZ3691.tipo;
176
- await conexionZORMZ3691.executeConsulta({ "query": "select 1+1;" }).then((data) => {
203
+ await conexionZORMZ3691.executeConsulta({ query: "select 1+1;" }).then((data) => {
177
204
  console.log(`\u{1F44D}\u{1F44D} Conexi\xF3n ${tipoConexionZORMZ3691} exitosa \u{1F61C}`);
178
205
  }).catch((err) => {
179
206
  console.error(" \u{1F622}\u{1F622} Error al conectar a " + tipoConexionZORMZ3691);
@@ -182,12 +209,34 @@ async function getConexion(bd, datos) {
182
209
  }
183
210
  function getRed() {
184
211
  if (!conexionZORMZ3691) {
185
- throw new Error("La conexi\xF3n no ha sido inicializada. Por favor, llama a getConexion() primero.");
212
+ throw new Error(
213
+ "La conexi\xF3n no ha sido inicializada. Por favor, llama a getConexion() primero."
214
+ );
186
215
  }
187
216
  return conexionZORMZ3691;
188
217
  }
189
218
  function defineTable(tableName, columns) {
190
219
  const fn = () => tableName;
220
+ if (!Validator.isValidTable(tableName)) {
221
+ throw new Error(
222
+ "El nombre de la tabla no puede contener mayusculas o caracteres especiales"
223
+ );
224
+ }
225
+ if (RESERVED_WORDS.has(tableName)) {
226
+ throw new Error(`el nombre ${tableName} es una palabra reservada SQL`);
227
+ }
228
+ for (const campo in columns) {
229
+ if (!Validator.isValidColumn(campo)) {
230
+ throw new Error(
231
+ `El campo ${campo} no puede contener caracteres especiales`
232
+ );
233
+ }
234
+ if (RESERVED_WORDS.has(campo)) {
235
+ throw new Error(
236
+ `El campo ${campo} contiene palabras reservadas de sql \u274C\u274C\u274C `
237
+ );
238
+ }
239
+ }
191
240
  const proxy = new Proxy(fn, {
192
241
  get(_target, prop) {
193
242
  if (prop === "$columns") {
@@ -246,10 +295,15 @@ async function generateTable(tabla, columns) {
246
295
  queries += columnDefs.join(", \n");
247
296
  queries += ");";
248
297
  if (!conexionZORMZ3691 || !tipoConexionZORMZ3691) {
249
- throw new Error("La conexi\xF3n no ha sido inicializada. Por favor, llama a getConexion() primero.");
298
+ throw new Error(
299
+ "La conexi\xF3n no ha sido inicializada. Por favor, llama a getConexion() primero."
300
+ );
250
301
  }
251
302
  if (tipoConexionZORMZ3691 === "mysql") {
252
- const response = await conexionZORMZ3691.executeConsulta({ query: queries, mensaje: "Error al crear la base de datos" });
303
+ const response = await conexionZORMZ3691.executeConsulta({
304
+ query: queries,
305
+ mensaje: "Error al crear la tabla"
306
+ });
253
307
  if (response.warningStatus > 0) {
254
308
  console.log(` La tabla ${tabla} ya existe \u{1F642}\u{1F610} `);
255
309
  } else {
@@ -264,6 +318,33 @@ async function generateTable(tabla, columns) {
264
318
  console.log(`\u{1F44D}\u{1F44D} Se creo con exito la tabla ${tabla} \u{1F61C}`);
265
319
  }
266
320
  }
321
+ async function dropTable(nombreTabla) {
322
+ let sql = `DROP TABLE IF EXISTS ${nombreTabla};`;
323
+ if (!conexionZORMZ3691 || !tipoConexionZORMZ3691) {
324
+ throw new Error(
325
+ "La conexi\xF3n no ha sido inicializada. Por favor, llama a getConexion() primero."
326
+ );
327
+ }
328
+ if (tipoConexionZORMZ3691 === "mysql") {
329
+ const response = await conexionZORMZ3691.executeConsulta({
330
+ query: sql,
331
+ mensaje: "Error al eliminar la tabla",
332
+ alertar: false
333
+ });
334
+ if (response.warningStatus === 0) {
335
+ console.log(`\u{1F44D}\u{1F44D} Se elimino con exito la tabla ${nombreTabla} \u{1F44D}`);
336
+ return;
337
+ }
338
+ console.log(` No existe la tabla ${nombreTabla} \u{1F622}`);
339
+ } else if (tipoConexionZORMZ3691 === "pg") {
340
+ const response = await conexionZORMZ3691.executeConsulta({
341
+ query: sql,
342
+ mensaje: "Error al eliminar la tabla",
343
+ alertar: false
344
+ });
345
+ console.log(` No existe la tabla ${nombreTabla} \u{1F622}`);
346
+ }
347
+ }
267
348
 
268
349
  // conection/middleware/delete.ts
269
350
  var _condicion, _tabla;
@@ -300,13 +381,15 @@ var DeleteR = class {
300
381
  if (this.conexion.tipo === "mysql") {
301
382
  const respuesta = await this.conexion.executeConsulta({
302
383
  query,
303
- mensaje: "Ocurrio un error al momento de eliminar un dato"
384
+ mensaje: "Ocurrio un error al momento de eliminar",
385
+ alertar: false
304
386
  });
305
387
  return respuesta.affectedRows;
306
388
  } else {
307
389
  const respuesta = await this.conexion.executeConsulta({
308
390
  query,
309
- mensaje: "Ocurrio un error al momento de eliminar un dato"
391
+ mensaje: "Ocurrio un error al momento de eliminar",
392
+ alertar: false
310
393
  });
311
394
  return respuesta.rowCount;
312
395
  }
@@ -463,21 +546,21 @@ var Select = class {
463
546
  if (!tabla || typeof tabla !== "string") {
464
547
  throw new Error("La tabla es un campo obligatorio");
465
548
  }
466
- this.innerJoin += ` INNER JOIN ${tabla} ON ${condition}`;
549
+ this.innerJoin += ` INNER JOIN ${tabla} ON ${condition} `;
467
550
  return this;
468
551
  }
469
552
  leftJoin(tabla, condition) {
470
553
  if (!tabla || typeof tabla !== "string") {
471
554
  throw new Error("La tabla es un campo obligatorio");
472
555
  }
473
- this.leftjoins += ` LEFT JOIN ${tabla} ON ${condition}`;
556
+ this.leftjoins += ` LEFT JOIN ${tabla} ON ${condition} `;
474
557
  return this;
475
558
  }
476
559
  rigthJoin(tabla, condition) {
477
560
  if (!tabla || typeof tabla !== "string") {
478
561
  throw new Error("La tabla es un campo obligatorio");
479
562
  }
480
- this.rigthjoins += ` RIGHT JOIN ${tabla} ON ${condition}`;
563
+ this.rigthjoins += ` RIGHT JOIN ${tabla} ON ${condition} `;
481
564
  return this;
482
565
  }
483
566
  /**
@@ -616,6 +699,14 @@ var MENOR = (valor, valor2) => {
616
699
  var CURRENT_TIMESTAMP = () => {
617
700
  return " CURRENT_TIMESTAMP ";
618
701
  };
702
+ var UP = (dataUpdate, newdataUpdate, activo = false) => {
703
+ const tables = {
704
+ campoUp: dataUpdate,
705
+ newCampoUp: newdataUpdate,
706
+ dataTable: activo
707
+ };
708
+ return tables;
709
+ };
619
710
 
620
711
  // conection/middleware/update.ts
621
712
  var Update = class {
@@ -639,19 +730,29 @@ var Update = class {
639
730
  * @param {Valores} valores - valores a actualizar
640
731
  * @example
641
732
  * .set({'campo1':'valor1', 'campo2':'valor2'})
733
+ * .set([UP(producto.stockactual,producto.stockactual)])
734
+ * set([UP(producto.stockactual, `${producto.stockactual} - 4`, true)])
642
735
  */
643
736
  set(valores) {
644
- if (typeof valores !== "object") {
645
- throw new Error("es requerido un objeto");
737
+ const validate = Array.isArray(valores);
738
+ if (valores === null || typeof valores !== "object") {
739
+ throw new Error("es requerido un objeto o un UP array");
646
740
  }
647
741
  let valor = "";
648
- for (const key in valores) {
649
- if (valores.hasOwnProperty(key)) {
650
- const value = valores[key];
651
- if (value === void 0) continue;
652
- valor += eq(key, value);
653
- valor += ",";
742
+ if (typeof valores === "object" && !validate) {
743
+ for (const key in valores) {
744
+ if (valores.hasOwnProperty(key)) {
745
+ const value = valores[key];
746
+ if (value === void 0) continue;
747
+ valor += eq(key, value);
748
+ valor += ",";
749
+ }
654
750
  }
751
+ } else if (validate) {
752
+ valores.forEach((valors) => {
753
+ valor += eq(valors.campoUp, valors.newCampoUp, !valors.dataTable);
754
+ valor += ",";
755
+ });
655
756
  }
656
757
  valor = valor.slice(0, -1);
657
758
  this.valores = valor;
@@ -1001,9 +1102,11 @@ function money(presicion = 10, decimales = 2) {
1001
1102
  ORQ,
1002
1103
  QueryBuilder,
1003
1104
  Select,
1105
+ UP,
1004
1106
  Update,
1005
1107
  bool,
1006
1108
  defineTable,
1109
+ dropTable,
1007
1110
  eq,
1008
1111
  generateTable,
1009
1112
  getConexion,
package/dist/index.mjs CHANGED
@@ -6,6 +6,22 @@ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read fr
6
6
  var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
7
7
  var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
8
8
 
9
+ // conection/validator.ts
10
+ var Validator = class {
11
+ };
12
+ Validator.isValidTable = (val) => /^(?![0-9_])[a-z][a-z0-9_]{0,62}$/.test(val);
13
+ Validator.isValidColumn = (val) => /^[a-z][a-z0-9_]{0,62}$/.test(val);
14
+ Validator.isValidUsername = (val) => /^[a-zA-Z0-9\-_]+$/.test(val);
15
+ var RESERVED_WORDS = /* @__PURE__ */ new Set([
16
+ "select",
17
+ "table",
18
+ "user",
19
+ "order",
20
+ "group",
21
+ "where",
22
+ "join"
23
+ ]);
24
+
9
25
  // conection/db.ts
10
26
  var BDconnection = class {
11
27
  constructor(bd, datos) {
@@ -27,7 +43,9 @@ var BDconnection = class {
27
43
  });
28
44
  return pool;
29
45
  } catch (error) {
30
- throw new Error("Mysql no esta instalado . para instalarlo corre : npm install mysql2 ");
46
+ throw new Error(
47
+ "Mysql no esta instalado . para instalarlo corre : npm install mysql2 "
48
+ );
31
49
  }
32
50
  }
33
51
  async connectionPG() {
@@ -53,14 +71,18 @@ var BDconnection = class {
53
71
  console.error(
54
72
  "PostgreSQL no esta instalado. para instalarlo corre : npm install pg"
55
73
  );
56
- throw new Error("PostgreSQL no esta instalado. para instalarlo corre : npm install pg");
74
+ throw new Error(
75
+ "PostgreSQL no esta instalado. para instalarlo corre : npm install pg"
76
+ );
57
77
  }
58
78
  }
59
79
  async executeConsulta({
60
80
  query,
61
81
  valores = void 0,
62
- mensaje
82
+ mensaje,
83
+ alertar = true
63
84
  }) {
85
+ console.log(query);
64
86
  try {
65
87
  if (this.tipo === "mysql") {
66
88
  const pool = await this.conexionMysql();
@@ -92,6 +114,7 @@ var BDconnection = class {
92
114
  }
93
115
  } catch (error) {
94
116
  console.log(error);
117
+ if (!alertar) return;
95
118
  if (typeof error === "object" && error !== null && "code" in error) {
96
119
  if (error.code === "ETIMEDOUT") {
97
120
  throw new Error(`Su red esta limitando el acceso`);
@@ -105,14 +128,16 @@ var conexionZORMZ3691;
105
128
  var tipoConexionZORMZ3691;
106
129
  function getTipoConexion() {
107
130
  if (!tipoConexionZORMZ3691) {
108
- throw new Error("La conexi\xF3n no ha sido inicializada. Por favor, llama a getConexion() primero.");
131
+ throw new Error(
132
+ "La conexi\xF3n no ha sido inicializada. Por favor, llama a getConexion() primero."
133
+ );
109
134
  }
110
135
  return tipoConexionZORMZ3691;
111
136
  }
112
137
  async function getConexion(bd, datos) {
113
138
  conexionZORMZ3691 = new BDconnection(bd, datos);
114
139
  tipoConexionZORMZ3691 = conexionZORMZ3691.tipo;
115
- await conexionZORMZ3691.executeConsulta({ "query": "select 1+1;" }).then((data) => {
140
+ await conexionZORMZ3691.executeConsulta({ query: "select 1+1;" }).then((data) => {
116
141
  console.log(`\u{1F44D}\u{1F44D} Conexi\xF3n ${tipoConexionZORMZ3691} exitosa \u{1F61C}`);
117
142
  }).catch((err) => {
118
143
  console.error(" \u{1F622}\u{1F622} Error al conectar a " + tipoConexionZORMZ3691);
@@ -121,12 +146,34 @@ async function getConexion(bd, datos) {
121
146
  }
122
147
  function getRed() {
123
148
  if (!conexionZORMZ3691) {
124
- throw new Error("La conexi\xF3n no ha sido inicializada. Por favor, llama a getConexion() primero.");
149
+ throw new Error(
150
+ "La conexi\xF3n no ha sido inicializada. Por favor, llama a getConexion() primero."
151
+ );
125
152
  }
126
153
  return conexionZORMZ3691;
127
154
  }
128
155
  function defineTable(tableName, columns) {
129
156
  const fn = () => tableName;
157
+ if (!Validator.isValidTable(tableName)) {
158
+ throw new Error(
159
+ "El nombre de la tabla no puede contener mayusculas o caracteres especiales"
160
+ );
161
+ }
162
+ if (RESERVED_WORDS.has(tableName)) {
163
+ throw new Error(`el nombre ${tableName} es una palabra reservada SQL`);
164
+ }
165
+ for (const campo in columns) {
166
+ if (!Validator.isValidColumn(campo)) {
167
+ throw new Error(
168
+ `El campo ${campo} no puede contener caracteres especiales`
169
+ );
170
+ }
171
+ if (RESERVED_WORDS.has(campo)) {
172
+ throw new Error(
173
+ `El campo ${campo} contiene palabras reservadas de sql \u274C\u274C\u274C `
174
+ );
175
+ }
176
+ }
130
177
  const proxy = new Proxy(fn, {
131
178
  get(_target, prop) {
132
179
  if (prop === "$columns") {
@@ -185,10 +232,15 @@ async function generateTable(tabla, columns) {
185
232
  queries += columnDefs.join(", \n");
186
233
  queries += ");";
187
234
  if (!conexionZORMZ3691 || !tipoConexionZORMZ3691) {
188
- throw new Error("La conexi\xF3n no ha sido inicializada. Por favor, llama a getConexion() primero.");
235
+ throw new Error(
236
+ "La conexi\xF3n no ha sido inicializada. Por favor, llama a getConexion() primero."
237
+ );
189
238
  }
190
239
  if (tipoConexionZORMZ3691 === "mysql") {
191
- const response = await conexionZORMZ3691.executeConsulta({ query: queries, mensaje: "Error al crear la base de datos" });
240
+ const response = await conexionZORMZ3691.executeConsulta({
241
+ query: queries,
242
+ mensaje: "Error al crear la tabla"
243
+ });
192
244
  if (response.warningStatus > 0) {
193
245
  console.log(` La tabla ${tabla} ya existe \u{1F642}\u{1F610} `);
194
246
  } else {
@@ -203,6 +255,33 @@ async function generateTable(tabla, columns) {
203
255
  console.log(`\u{1F44D}\u{1F44D} Se creo con exito la tabla ${tabla} \u{1F61C}`);
204
256
  }
205
257
  }
258
+ async function dropTable(nombreTabla) {
259
+ let sql = `DROP TABLE IF EXISTS ${nombreTabla};`;
260
+ if (!conexionZORMZ3691 || !tipoConexionZORMZ3691) {
261
+ throw new Error(
262
+ "La conexi\xF3n no ha sido inicializada. Por favor, llama a getConexion() primero."
263
+ );
264
+ }
265
+ if (tipoConexionZORMZ3691 === "mysql") {
266
+ const response = await conexionZORMZ3691.executeConsulta({
267
+ query: sql,
268
+ mensaje: "Error al eliminar la tabla",
269
+ alertar: false
270
+ });
271
+ if (response.warningStatus === 0) {
272
+ console.log(`\u{1F44D}\u{1F44D} Se elimino con exito la tabla ${nombreTabla} \u{1F44D}`);
273
+ return;
274
+ }
275
+ console.log(` No existe la tabla ${nombreTabla} \u{1F622}`);
276
+ } else if (tipoConexionZORMZ3691 === "pg") {
277
+ const response = await conexionZORMZ3691.executeConsulta({
278
+ query: sql,
279
+ mensaje: "Error al eliminar la tabla",
280
+ alertar: false
281
+ });
282
+ console.log(` No existe la tabla ${nombreTabla} \u{1F622}`);
283
+ }
284
+ }
206
285
 
207
286
  // conection/middleware/delete.ts
208
287
  var _condicion, _tabla;
@@ -239,13 +318,15 @@ var DeleteR = class {
239
318
  if (this.conexion.tipo === "mysql") {
240
319
  const respuesta = await this.conexion.executeConsulta({
241
320
  query,
242
- mensaje: "Ocurrio un error al momento de eliminar un dato"
321
+ mensaje: "Ocurrio un error al momento de eliminar",
322
+ alertar: false
243
323
  });
244
324
  return respuesta.affectedRows;
245
325
  } else {
246
326
  const respuesta = await this.conexion.executeConsulta({
247
327
  query,
248
- mensaje: "Ocurrio un error al momento de eliminar un dato"
328
+ mensaje: "Ocurrio un error al momento de eliminar",
329
+ alertar: false
249
330
  });
250
331
  return respuesta.rowCount;
251
332
  }
@@ -402,21 +483,21 @@ var Select = class {
402
483
  if (!tabla || typeof tabla !== "string") {
403
484
  throw new Error("La tabla es un campo obligatorio");
404
485
  }
405
- this.innerJoin += ` INNER JOIN ${tabla} ON ${condition}`;
486
+ this.innerJoin += ` INNER JOIN ${tabla} ON ${condition} `;
406
487
  return this;
407
488
  }
408
489
  leftJoin(tabla, condition) {
409
490
  if (!tabla || typeof tabla !== "string") {
410
491
  throw new Error("La tabla es un campo obligatorio");
411
492
  }
412
- this.leftjoins += ` LEFT JOIN ${tabla} ON ${condition}`;
493
+ this.leftjoins += ` LEFT JOIN ${tabla} ON ${condition} `;
413
494
  return this;
414
495
  }
415
496
  rigthJoin(tabla, condition) {
416
497
  if (!tabla || typeof tabla !== "string") {
417
498
  throw new Error("La tabla es un campo obligatorio");
418
499
  }
419
- this.rigthjoins += ` RIGHT JOIN ${tabla} ON ${condition}`;
500
+ this.rigthjoins += ` RIGHT JOIN ${tabla} ON ${condition} `;
420
501
  return this;
421
502
  }
422
503
  /**
@@ -555,6 +636,14 @@ var MENOR = (valor, valor2) => {
555
636
  var CURRENT_TIMESTAMP = () => {
556
637
  return " CURRENT_TIMESTAMP ";
557
638
  };
639
+ var UP = (dataUpdate, newdataUpdate, activo = false) => {
640
+ const tables = {
641
+ campoUp: dataUpdate,
642
+ newCampoUp: newdataUpdate,
643
+ dataTable: activo
644
+ };
645
+ return tables;
646
+ };
558
647
 
559
648
  // conection/middleware/update.ts
560
649
  var Update = class {
@@ -578,19 +667,29 @@ var Update = class {
578
667
  * @param {Valores} valores - valores a actualizar
579
668
  * @example
580
669
  * .set({'campo1':'valor1', 'campo2':'valor2'})
670
+ * .set([UP(producto.stockactual,producto.stockactual)])
671
+ * set([UP(producto.stockactual, `${producto.stockactual} - 4`, true)])
581
672
  */
582
673
  set(valores) {
583
- if (typeof valores !== "object") {
584
- throw new Error("es requerido un objeto");
674
+ const validate = Array.isArray(valores);
675
+ if (valores === null || typeof valores !== "object") {
676
+ throw new Error("es requerido un objeto o un UP array");
585
677
  }
586
678
  let valor = "";
587
- for (const key in valores) {
588
- if (valores.hasOwnProperty(key)) {
589
- const value = valores[key];
590
- if (value === void 0) continue;
591
- valor += eq(key, value);
592
- valor += ",";
679
+ if (typeof valores === "object" && !validate) {
680
+ for (const key in valores) {
681
+ if (valores.hasOwnProperty(key)) {
682
+ const value = valores[key];
683
+ if (value === void 0) continue;
684
+ valor += eq(key, value);
685
+ valor += ",";
686
+ }
593
687
  }
688
+ } else if (validate) {
689
+ valores.forEach((valors) => {
690
+ valor += eq(valors.campoUp, valors.newCampoUp, !valors.dataTable);
691
+ valor += ",";
692
+ });
594
693
  }
595
694
  valor = valor.slice(0, -1);
596
695
  this.valores = valor;
@@ -939,9 +1038,11 @@ export {
939
1038
  ORQ,
940
1039
  QueryBuilder,
941
1040
  Select,
1041
+ UP,
942
1042
  Update,
943
1043
  bool,
944
1044
  defineTable,
1045
+ dropTable,
945
1046
  eq,
946
1047
  generateTable,
947
1048
  getConexion,
package/package.json CHANGED
@@ -1,9 +1,19 @@
1
1
  {
2
2
  "name": "zormz",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "description": "Un ORM que busca ser ligero y facil de usar",
5
5
  "author": "yukio-kayaba",
6
6
  "license": "ISC",
7
+ "keywords": [
8
+ "orm",
9
+ "database",
10
+ "postgresql",
11
+ "mysql",
12
+ "sql",
13
+ "typescript",
14
+ "zomrz",
15
+ "pg"
16
+ ],
7
17
  "main": "./dist/index.cjs",
8
18
  "module": "./dist/index.js",
9
19
  "types": "./dist/index.d.ts",