zormz 1.1.2 → 1.2.3

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
@@ -41,29 +41,6 @@ const { connecionLocal, getConexion } = require("zormz");
41
41
 
42
42
  ---
43
43
 
44
- ## Ejemplo: Insertar datos
45
-
46
- ```ts
47
- const response = await DB.Insert('datosPrueba',
48
- ['nombre', 'data']).Values(['yunno','magic wind']).execute();
49
- ```
50
-
51
- Resultado esperado:
52
-
53
- ```sql
54
- INSERT INTO datosPrueba (nombre, data) VALUES (?, ?);
55
- ```
56
-
57
- ---
58
-
59
- ## Ejemplo: Select
60
-
61
- ```ts
62
- let datos = await DB.select().from("datosPrueba").execute();
63
- console.log(datos);
64
- ```
65
-
66
- ---
67
44
 
68
45
  ## Conexión a la base de datos
69
46
  ### mysql local
@@ -93,46 +70,99 @@ getConexion("pg",conexionPg);
93
70
  ```
94
71
  ---
95
72
 
96
- ## Definir tablas para uso dev
97
- * Puede exportarse como una constante para programarlo y guiarnos facilmente
98
- ### defineTable
99
- * `export const productosPrueba = defineTable("productosPrueba",{`
100
- * `id:"id",`
101
- * `nombre:"nombre",`
102
- * `descripcion:"descripcion"`
103
- * `});`
73
+
74
+ ## Métodos disponibles
75
+
76
+ ### **Select**
77
+ ### **Insert**
78
+ ### **Update**
79
+ ### **Delete**
80
+
81
+
104
82
  ---
105
83
 
106
- ## Ejemplo: definicion de tabla
84
+ ## Creación de tablas para autocompletado y SQL
85
+
86
+ Por ahora, la creación de tablas en **ZORMZ** no es avanzada. Sin embargo, ya permite **definir la estructura de la base de datos desde TypeScript o js**, lo que habilita:
87
+
88
+ * Autocompletado en el editor
89
+ * Tipado básico de columnas
90
+
91
+ Esto es útil si ya tienes la base de datos creada o si quieres preparar el schema antes de automatizarlo.
92
+
93
+
94
+ ### Ejemplo de definición de tabla
107
95
 
108
96
  ```ts
109
- const response = await DB.Insert(productosPrueba(),
110
- [productosPrueba.nombre,productosPrueba.descripcion]).Values(['yunno','magic wind']).execute();
97
+ export const datosPrueba = defineTable("datosPrueba", {
98
+ id: { typo: "int", id: true },
99
+
100
+ nombre: {
101
+ typo: "varchar",
102
+ maxLength: 200,
103
+ default: "hola"
104
+ },
105
+
106
+ data: {
107
+ typo: "varchar",
108
+ default: "none magic"
109
+ },
110
+
111
+ edad: {
112
+ typo: "int",
113
+ default:19
114
+ }
115
+ });
111
116
  ```
117
+
118
+ ### Notas
119
+
120
+ * `defineTable` registra el nombre de la tabla y sus columnas
121
+ * Cada propiedad representa una columna
122
+ * El objetivo actual es **autocompletado y estructura**, no migraciones complejas
123
+ * El sistema está en evolución 😢
124
+
112
125
  ---
126
+ ## Creacion de tabla desde ZORMZ
127
+ Para la creacion de la tabla se necesita que la tabla este definido
128
+ * $columns : es un parametro que por defecto se obtiene al definir la tabla, este reserva gran parte de los datos.
113
129
 
114
- ## Métodos disponibles
130
+ ```ts
131
+ import { master } from "./archivos/prueba";
132
+ generateTable(master(), master.$columns);
115
133
 
116
- ### **Select**
134
+ ```
117
135
 
118
- * `DB.select(campos)`
119
- * `.from(tabla)`
120
- * `.where(condición, valores).execute()`
136
+ ## Ejemplo: Insertar datos
121
137
 
122
- ### **Insert**
138
+ ```ts
139
+ const response = await DB.Insert(datosPrueba(),
140
+ [datosPrueba.nombre, datosPrueba.data]).Values(['yunno','magic wind']).execute();
141
+ ```
123
142
 
124
- * `DB.Insert(campos)`
125
- * `.valores(arrayDeValores).execute()`
143
+ Resultado esperado:
126
144
 
127
- ### **Update**
145
+ ```sql
146
+ INSERT INTO datosPrueba (nombre, data) VALUES (?, ?);
147
+ ```
148
+
149
+ ---
128
150
 
129
- * `DB.update(tabla)`
130
- * `.set(campos).execute()`
151
+ ## Ejemplo: Select
131
152
 
132
- ### **Delete**
153
+ ```ts
154
+ let datos = await DB.select().from(datosPrueba()).where(eq(datosPrueba.id,2)).execute();
155
+ console.log(datos);
156
+ ```
157
+ ---
133
158
 
134
- * `DB.deleteFrom(tabla).where(condicionales).execute()`
159
+ ## Ejemplo: Insert
135
160
 
161
+ ```ts
162
+ const response = await DB.Insert(productosPrueba(),
163
+ [productosPrueba.nombre,productosPrueba.descripcion]).Values(['yunno','magic wind']).execute();
164
+ ```
165
+ ---
136
166
 
137
167
  ## Ejemplo completo
138
168
 
@@ -161,7 +191,7 @@ async function pruebaData() {
161
191
  .execute();
162
192
  console.log(response);
163
193
 
164
- let update = await DB.update("datosPrueba")
194
+ let update = await DB.Update("datosPrueba")
165
195
  .set({ nombre: "yukio", data: "es un juego ?" })
166
196
  .where(eq("id", 1))
167
197
  .execute();
package/dist/index.cjs CHANGED
@@ -39,6 +39,7 @@ var index_exports = {};
39
39
  __export(index_exports, {
40
40
  AND: () => AND,
41
41
  BDconnection: () => BDconnection,
42
+ CURRENT_TIMESTAMP: () => CURRENT_TIMESTAMP,
42
43
  DB: () => DB,
43
44
  DeleteR: () => DeleteR,
44
45
  ILIKE: () => ILIKE,
@@ -54,13 +55,15 @@ __export(index_exports, {
54
55
  Update: () => Update,
55
56
  defineTable: () => defineTable,
56
57
  eq: () => eq,
58
+ generateTable: () => generateTable,
57
59
  getConexion: () => getConexion,
58
60
  getRed: () => getRed
59
61
  });
60
62
  module.exports = __toCommonJS(index_exports);
61
63
 
62
64
  // conection/db.ts
63
- var conexion1;
65
+ var conexionZORMZ3691;
66
+ var tipoConexionZORMZ3691;
64
67
  var BDconnection = class {
65
68
  constructor(bd, datos) {
66
69
  this.tipo = "pg";
@@ -138,12 +141,7 @@ var BDconnection = class {
138
141
  if (!respuesta) {
139
142
  throw new Error(` Este usuario no esta registrado `);
140
143
  }
141
- if ("rows" in respuesta) {
142
- if (respuesta.rows[0].id) {
143
- return { insertId: respuesta.rows[0].id };
144
- }
145
- return respuesta.rows;
146
- }
144
+ return respuesta;
147
145
  }
148
146
  } catch (error) {
149
147
  console.log(error);
@@ -156,22 +154,44 @@ var BDconnection = class {
156
154
  }
157
155
  }
158
156
  };
159
- function getConexion(bd, datos) {
160
- conexion1 = new BDconnection(bd, datos);
157
+ async function getConexion(bd, datos) {
158
+ conexionZORMZ3691 = new BDconnection(bd, datos);
159
+ tipoConexionZORMZ3691 = conexionZORMZ3691.tipo;
160
+ await conexionZORMZ3691.executeConsulta({ "query": "select 1+1;" }).then((data) => {
161
+ console.log(`\u{1F44D}\u{1F44D} Conexi\xF3n ${tipoConexionZORMZ3691} exitosa \u{1F61C}`);
162
+ }).catch((err) => {
163
+ console.error(" \u{1F622}\u{1F622} Error al conectar a " + tipoConexionZORMZ3691);
164
+ });
161
165
  }
162
166
  function getRed() {
163
- return conexion1;
167
+ return conexionZORMZ3691;
164
168
  }
165
169
  function defineTable(tableName, columns) {
166
170
  const fn = () => tableName;
167
171
  const proxy = new Proxy(fn, {
168
172
  get(_target, prop) {
173
+ if (prop === "$columns") {
174
+ return columns;
175
+ }
169
176
  if (prop === "name") return tableName;
170
177
  if (prop === "toString") return () => tableName;
171
178
  if (prop === "valueOf") return () => tableName;
172
- const col = columns[prop];
173
- if (col !== void 0) return `${tableName}.${col}`;
174
- return fn[prop];
179
+ if (prop in columns) {
180
+ return `${tableName}.${prop.toString()}`;
181
+ }
182
+ return void 0;
183
+ },
184
+ ownKeys() {
185
+ return Reflect.ownKeys(columns);
186
+ },
187
+ getOwnPropertyDescriptor(_target, prop) {
188
+ if (prop in columns) {
189
+ return {
190
+ enumerable: true,
191
+ configurable: true
192
+ };
193
+ }
194
+ return void 0;
175
195
  },
176
196
  apply() {
177
197
  return tableName;
@@ -179,6 +199,73 @@ function defineTable(tableName, columns) {
179
199
  });
180
200
  return proxy;
181
201
  }
202
+ function ValidacionTypos(columna, id, maxLength) {
203
+ let sql = "";
204
+ if (columna === "varchar")
205
+ sql += `VARCHAR(${maxLength ? maxLength : "100"})`;
206
+ if (columna === "int") {
207
+ if (tipoConexionZORMZ3691 === "pg") {
208
+ sql += id ? " " : " INTEGER ";
209
+ } else {
210
+ sql += " INT ";
211
+ }
212
+ }
213
+ if (columna === "bool")
214
+ sql += tipoConexionZORMZ3691 === "mysql" ? " TINYINT(1) " : " BOOLEAN ";
215
+ if (columna === "double")
216
+ sql += tipoConexionZORMZ3691 === "mysql" ? " DOUBLE " : " DOUBLE PRECISION ";
217
+ if (columna === "timestamp")
218
+ sql += tipoConexionZORMZ3691 === "mysql" ? " TIMESTAMP " : " TIMESTAMPTZ ";
219
+ if (columna === "float")
220
+ sql += tipoConexionZORMZ3691 === "mysql" ? " FLOAT " : " REAL";
221
+ if (columna === "money")
222
+ sql += tipoConexionZORMZ3691 === "mysql" ? " DECIMAL(10,2) " : " NUMERIC(10,2)";
223
+ return sql;
224
+ }
225
+ async function generateTable(tabla, columns) {
226
+ let queries = "";
227
+ let columnDefs = [];
228
+ let sql = "";
229
+ let id = false;
230
+ for (const columnName in columns) {
231
+ const col = columns[columnName];
232
+ sql = ` ${columnName} `;
233
+ if (!col.typo) {
234
+ throw new Error(`La columna ${columnName} no tiene el tipo definido`);
235
+ }
236
+ sql += ValidacionTypos(col.typo, col.id, col.maxLength);
237
+ if (col.id) {
238
+ if (id) throw new Error(`El id no puede repetirse en 2 campos de la tabla '${tabla}'`);
239
+ sql += tipoConexionZORMZ3691 === "mysql" ? " NOT NULL AUTO_INCREMENT " : " SERIAL ";
240
+ sql += " PRIMARY KEY ";
241
+ id = true;
242
+ columnDefs.push(sql);
243
+ continue;
244
+ }
245
+ sql += col.unique === void 0 ? " NOT NULL " : " UNIQUE";
246
+ sql += col.default === void 0 ? col.unique === void 0 ? " " : " NOT NULL " : ` DEFAULT ${typeof col.default === "string" ? tipoConexionZORMZ3691 === "mysql" ? `"${col.default}"` : `'${col.default}'` : col.default}`;
247
+ columnDefs.push(sql);
248
+ }
249
+ queries += `CREATE TABLE IF NOT EXISTS ${tabla} (
250
+ `;
251
+ queries += columnDefs.join(", \n");
252
+ queries += ");";
253
+ if (tipoConexionZORMZ3691 === "mysql") {
254
+ const response = await conexionZORMZ3691.executeConsulta({ query: queries, mensaje: "Error al crear la base de datos" });
255
+ if (response.warningStatus > 0) {
256
+ console.log(` La tabla ${tabla} ya existe \u{1F642}\u{1F610} `);
257
+ } else {
258
+ console.log(`\u{1F44D}\u{1F44D} Se creo con exito la tabla ${tabla} \u{1F61C}`);
259
+ }
260
+ return;
261
+ } else {
262
+ const response = await conexionZORMZ3691.executeConsulta({
263
+ query: queries,
264
+ mensaje: "Error al crear la base de datos"
265
+ });
266
+ console.log(`\u{1F44D}\u{1F44D} Se creo con exito la tabla ${tabla} \u{1F61C}`);
267
+ }
268
+ }
182
269
 
183
270
  // conection/middleware/delete.ts
184
271
  var _condicion, _tabla;
@@ -212,11 +299,19 @@ var DeleteR = class {
212
299
  }
213
300
  async execute() {
214
301
  const query = `DELETE FROM ${__privateGet(this, _tabla)} ${__privateGet(this, _condicion)}`;
215
- const respuesta = await this.conexion.executeConsulta({
216
- query,
217
- mensaje: "Ocurrio un error al momento de eliminar un dato"
218
- });
219
- return respuesta.affectedRows;
302
+ if (this.conexion.tipo === "mysql") {
303
+ const respuesta = await this.conexion.executeConsulta({
304
+ query,
305
+ mensaje: "Ocurrio un error al momento de eliminar un dato"
306
+ });
307
+ return respuesta.affectedRows;
308
+ } else {
309
+ const respuesta = await this.conexion.executeConsulta({
310
+ query,
311
+ mensaje: "Ocurrio un error al momento de eliminar un dato"
312
+ });
313
+ return respuesta.rowCount;
314
+ }
220
315
  }
221
316
  };
222
317
  _condicion = new WeakMap();
@@ -269,29 +364,69 @@ var QueryBuilder = class {
269
364
  let param = "";
270
365
  let arrayArrays = false;
271
366
  let paramespaces = "";
272
- if (typeof this.parametros !== "string") {
273
- if (Array.isArray(this.valores)) arrayArrays = true;
274
- this.parametros.forEach((valor, index) => {
275
- param += valor;
276
- paramespaces += ` ? `;
277
- if (index < this.parametros.length - 1) {
278
- param += ", ";
279
- paramespaces += ", ";
280
- }
281
- });
367
+ if (this.conexion.tipo === "mysql") {
368
+ if (typeof this.parametros !== "string") {
369
+ if (Array.isArray(this.valores[0])) arrayArrays = true;
370
+ this.parametros.forEach((valor, index) => {
371
+ param += valor;
372
+ paramespaces += `?`;
373
+ if (index < this.parametros.length - 1) {
374
+ param += ", ";
375
+ paramespaces += ", ";
376
+ }
377
+ });
378
+ }
379
+ } else if (this.conexion.tipo === "pg") {
380
+ let i = 1;
381
+ let cantidadCaracter = this.tabla.length + 1;
382
+ if (!Array.isArray(this.valores[0])) {
383
+ throw new Error(
384
+ "PostgreSQL requiere array de arrays en INSERT m\xFAltiple"
385
+ );
386
+ }
387
+ if (typeof this.parametros !== "string") {
388
+ this.parametros.forEach((valor, index) => {
389
+ param += valor.slice(cantidadCaracter);
390
+ if (index < this.parametros.length - 1) {
391
+ param += ", ";
392
+ }
393
+ });
394
+ }
395
+ paramespaces = this.valores.map((row) => {
396
+ const p = row.map(() => `$${i++}`).join(", ");
397
+ return `(${p})`;
398
+ }).join(", ");
399
+ let datos = this.valores;
400
+ if (Array.isArray(this.valores[0])) {
401
+ datos = this.valores.flat();
402
+ }
403
+ this.valores = datos;
282
404
  }
283
405
  let query = `${query1} (${param}) VALUES `;
284
- if (arrayArrays) {
406
+ if (this.conexion.tipo === "mysql" && arrayArrays) {
285
407
  query += ` ? `;
286
- } else {
408
+ } else if (this.conexion.tipo === "mysql") {
287
409
  query += `(${paramespaces})`;
410
+ } else {
411
+ query += paramespaces;
412
+ }
413
+ if (this.conexion.tipo === "mysql") {
414
+ const respuesta = await this.conexion.executeConsulta({
415
+ query,
416
+ valores: this.valores,
417
+ mensaje: `Ocurrio un error al ingresar datos a ${this.tabla} `
418
+ });
419
+ console.log(respuesta);
420
+ return respuesta.insertId;
421
+ } else if (this.conexion.tipo === "pg") {
422
+ query += " RETURNING id ";
423
+ const respuesta = await this.conexion.executeConsulta({
424
+ query,
425
+ valores: this.valores,
426
+ mensaje: `Ocurrio un error al ingresar datos a ${this.tabla} `
427
+ });
428
+ return respuesta.rows;
288
429
  }
289
- const respuesta = await this.conexion.executeConsulta({
290
- query,
291
- valores: this.valores,
292
- mensaje: `Ocurrio un error al ingresar datos a ${this.tabla} `
293
- });
294
- return respuesta.insertId;
295
430
  }
296
431
  };
297
432
 
@@ -411,11 +546,19 @@ var Select = class {
411
546
  }
412
547
  }
413
548
  const query = `SELECT ${selectFields} from ${this.tabla} ${this.innerJoin} ${this.leftjoins} ${this.rigthjoins} ${this.condicion} ${this.orderBy} ${this.limit};`;
414
- const respuesta = await this.conexion.executeConsulta({
415
- query,
416
- mensaje: "Ocurrio un error realizar un select"
417
- });
418
- return respuesta;
549
+ if (this.conexion.tipo === "mysql") {
550
+ const respuesta = await this.conexion.executeConsulta({
551
+ query,
552
+ mensaje: "Ocurrio un error realizar un select"
553
+ });
554
+ return respuesta;
555
+ } else if (this.conexion.tipo === "pg") {
556
+ const respuesta = await this.conexion.executeConsulta({
557
+ query,
558
+ mensaje: "Ocurrio un error realizar un select"
559
+ });
560
+ return respuesta.rows;
561
+ }
419
562
  }
420
563
  };
421
564
 
@@ -430,8 +573,8 @@ var OR = (...valor1) => {
430
573
  };
431
574
  var ORQ = (condicion1, ...condicionals) => {
432
575
  const data2 = condicionals.map((dato) => {
433
- if (typeof dato == "number" || typeof dato == "boolean") return ` '${condicion1}' = ${dato}`;
434
- return ` '${condicion1}' = '${dato}' `;
576
+ if (typeof dato == "number" || typeof dato == "boolean") return ` ${condicion1} = ${dato}`;
577
+ return ` ${condicion1} = '${dato}' `;
435
578
  });
436
579
  const separador = data2.join(" or ");
437
580
  return separador;
@@ -471,6 +614,9 @@ var MAYOR = (valor, valor2) => {
471
614
  var MENOR = (valor, valor2) => {
472
615
  return ` ${valor} < ${valor2} `;
473
616
  };
617
+ var CURRENT_TIMESTAMP = () => {
618
+ return " CURRENT_TIMESTAMP ";
619
+ };
474
620
 
475
621
  // conection/middleware/update.ts
476
622
  var Update = class {
@@ -539,11 +685,10 @@ var Update = class {
539
685
  mensaje: "Error Update"
540
686
  });
541
687
  if (this.conexion.tipo === "mysql") {
542
- return respuesta;
688
+ return respuesta.affectedRows;
543
689
  } else {
544
690
  return {
545
- resultado: respuesta.rows.info,
546
- filasAfectadas: respuesta.rows.affectedRows
691
+ resultado: respuesta.rowCount
547
692
  };
548
693
  }
549
694
  }
@@ -564,14 +709,14 @@ var DB = class {
564
709
  /**
565
710
  * @param {string[]} parametros - campo opcional
566
711
  */
567
- static select(parametros) {
712
+ static Select(parametros) {
568
713
  const conex = getRed();
569
714
  return new Select(conex, parametros);
570
715
  }
571
716
  /**
572
717
  * @param {string} nombreTabla - nombre de la tabla a actualizar
573
718
  */
574
- static update(nombreTabla) {
719
+ static Update(nombreTabla) {
575
720
  const conex = getRed();
576
721
  return new Update(conex, nombreTabla);
577
722
  }
@@ -590,6 +735,7 @@ var DB = class {
590
735
  0 && (module.exports = {
591
736
  AND,
592
737
  BDconnection,
738
+ CURRENT_TIMESTAMP,
593
739
  DB,
594
740
  DeleteR,
595
741
  ILIKE,
@@ -605,6 +751,7 @@ var DB = class {
605
751
  Update,
606
752
  defineTable,
607
753
  eq,
754
+ generateTable,
608
755
  getConexion,
609
756
  getRed
610
757
  });
package/dist/index.d.cts CHANGED
@@ -29,24 +29,55 @@ declare class BDconnection {
29
29
  * @param datos
30
30
  * //esta funcion realmente puedes ponerlo en tu archivo raiz para que funcion en todo tu programa
31
31
  */
32
- declare function getConexion(bd: connectionDB, datos: connecionLocal | connecionRed): void;
32
+ declare function getConexion(bd: connectionDB, datos: connecionLocal | connecionRed): Promise<void>;
33
33
  declare function getRed(): BDconnection;
34
- type ColumnsMap = Record<string, string>;
34
+ type ColumnTypes = "varchar" | "int" | "double" | "bool" | "timestamp" | "float" | "money";
35
+ type ColumnTypeMap = {
36
+ varchar: string;
37
+ double: number;
38
+ int: number;
39
+ bool: boolean;
40
+ timestamp: Date;
41
+ float: number;
42
+ money: number;
43
+ };
44
+ interface ColumnDefinition<T extends ColumnTypes = ColumnTypes> {
45
+ typo: T;
46
+ id?: boolean;
47
+ maxLength?: number;
48
+ default?: ColumnTypeMap[T];
49
+ unique?: boolean;
50
+ }
51
+ type TableProxy<TCols> = {
52
+ (): string;
53
+ $columns: TCols;
54
+ } & {
55
+ [K in keyof TCols]: string;
56
+ };
35
57
  /**
36
58
  *
37
59
  * @param {string} tableName
38
60
  * @param {string} columns
39
61
  * @example
40
62
  * export const productosPrueba = defineTable("productosPrueba",{
41
- * id:"id",
42
- * nombre:"nombre",
43
- * descripcion:"descripcion"
63
+ * id:{typo:"int",id:true},
64
+ dato: {
65
+ typo:"varchar",
66
+ maxLength:200,
67
+ default:"hola mundo"
68
+ },
69
+ edad: {
70
+ typo:"int",
71
+ default: 0,
72
+ },
73
+ apellido : {
74
+ typo:"varchar",
75
+ }
44
76
  * });
45
77
  * @returns
46
78
  */
47
- declare function defineTable<T extends ColumnsMap>(tableName: string, columns: T): T & (() => string) & {
48
- name: string;
49
- };
79
+ declare function defineTable<T extends Record<string, ColumnDefinition>>(tableName: string, columns: T): TableProxy<T>;
80
+ declare function generateTable<T extends Record<string, ColumnDefinition>>(tabla: string, columns: T): Promise<void>;
50
81
 
51
82
  declare class DeleteR {
52
83
  #private;
@@ -66,7 +97,7 @@ declare class DeleteR {
66
97
  * DB.Delete(tabla).WHERE(AND(eq(valor,valor), eq(valor2,valor2)))
67
98
  */
68
99
  where(condicion: string): this;
69
- execute(): Promise<any>;
100
+ execute(): Promise<number | null>;
70
101
  }
71
102
 
72
103
  type arrayData = (string | number)[];
@@ -98,7 +129,17 @@ declare class QueryBuilder {
98
129
  * @returns
99
130
  */
100
131
  Values(values: arrayData | arrayDatas): this;
101
- execute(): Promise<any>;
132
+ execute(): Promise<number | any[] | undefined>;
133
+ }
134
+
135
+ interface ResultSetHeaderMysql {
136
+ fieldCount: number;
137
+ affectedRows: number;
138
+ insertId: number;
139
+ info: string;
140
+ serverStatus: number;
141
+ warningStatus: number;
142
+ changedRows: number;
102
143
  }
103
144
 
104
145
  type valor = "ASC" | "DESC";
@@ -158,7 +199,7 @@ declare class Select {
158
199
  /**
159
200
  * @returns {Promise<Array<Object>>}
160
201
  */
161
- execute(): Promise<any>;
202
+ execute(): Promise<any[] | ResultSetHeaderMysql | undefined>;
162
203
  }
163
204
 
164
205
  type Valores = Record<string, string | number | undefined>;
@@ -201,11 +242,11 @@ declare class DB {
201
242
  /**
202
243
  * @param {string[]} parametros - campo opcional
203
244
  */
204
- static select(parametros?: string[]): Select;
245
+ static Select(parametros?: string[]): Select;
205
246
  /**
206
247
  * @param {string} nombreTabla - nombre de la tabla a actualizar
207
248
  */
208
- static update(nombreTabla: string): Update;
249
+ static Update(nombreTabla: string): Update;
209
250
  /**
210
251
  *
211
252
  * @param {string} nombreTabla -- tabla a eliminar
@@ -304,5 +345,16 @@ declare const MAYOR: (valor: string, valor2: string) => string;
304
345
  * @returns
305
346
  */
306
347
  declare const MENOR: (valor: string, valor2: string) => string;
348
+ /**
349
+ * @example
350
+ *
351
+ * FechaRegistro: {
352
+ typo: "timestamp ",
353
+ default: CURRENT_TIMESTAMP()
354
+ },
355
+ *
356
+ * @returns
357
+ */
358
+ declare const CURRENT_TIMESTAMP: () => string;
307
359
 
308
- export { AND, BDconnection, type Consultas, DB, DeleteR, ILIKE, MAYOR, MENOR, NOTNULL, NOW, NULL, OR, ORQ, QueryBuilder, Select, type Tipos, Update, type Valores, type arrayData, type arrayDatas, type connecionLocal, type connecionRed, type connectionDB, defineTable, eq, getConexion, getRed, type valor };
360
+ export { AND, BDconnection, CURRENT_TIMESTAMP, type ColumnDefinition, 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, type connecionLocal, type connecionRed, type connectionDB, defineTable, eq, generateTable, getConexion, getRed, type valor };
package/dist/index.d.ts CHANGED
@@ -29,24 +29,55 @@ declare class BDconnection {
29
29
  * @param datos
30
30
  * //esta funcion realmente puedes ponerlo en tu archivo raiz para que funcion en todo tu programa
31
31
  */
32
- declare function getConexion(bd: connectionDB, datos: connecionLocal | connecionRed): void;
32
+ declare function getConexion(bd: connectionDB, datos: connecionLocal | connecionRed): Promise<void>;
33
33
  declare function getRed(): BDconnection;
34
- type ColumnsMap = Record<string, string>;
34
+ type ColumnTypes = "varchar" | "int" | "double" | "bool" | "timestamp" | "float" | "money";
35
+ type ColumnTypeMap = {
36
+ varchar: string;
37
+ double: number;
38
+ int: number;
39
+ bool: boolean;
40
+ timestamp: Date;
41
+ float: number;
42
+ money: number;
43
+ };
44
+ interface ColumnDefinition<T extends ColumnTypes = ColumnTypes> {
45
+ typo: T;
46
+ id?: boolean;
47
+ maxLength?: number;
48
+ default?: ColumnTypeMap[T];
49
+ unique?: boolean;
50
+ }
51
+ type TableProxy<TCols> = {
52
+ (): string;
53
+ $columns: TCols;
54
+ } & {
55
+ [K in keyof TCols]: string;
56
+ };
35
57
  /**
36
58
  *
37
59
  * @param {string} tableName
38
60
  * @param {string} columns
39
61
  * @example
40
62
  * export const productosPrueba = defineTable("productosPrueba",{
41
- * id:"id",
42
- * nombre:"nombre",
43
- * descripcion:"descripcion"
63
+ * id:{typo:"int",id:true},
64
+ dato: {
65
+ typo:"varchar",
66
+ maxLength:200,
67
+ default:"hola mundo"
68
+ },
69
+ edad: {
70
+ typo:"int",
71
+ default: 0,
72
+ },
73
+ apellido : {
74
+ typo:"varchar",
75
+ }
44
76
  * });
45
77
  * @returns
46
78
  */
47
- declare function defineTable<T extends ColumnsMap>(tableName: string, columns: T): T & (() => string) & {
48
- name: string;
49
- };
79
+ declare function defineTable<T extends Record<string, ColumnDefinition>>(tableName: string, columns: T): TableProxy<T>;
80
+ declare function generateTable<T extends Record<string, ColumnDefinition>>(tabla: string, columns: T): Promise<void>;
50
81
 
51
82
  declare class DeleteR {
52
83
  #private;
@@ -66,7 +97,7 @@ declare class DeleteR {
66
97
  * DB.Delete(tabla).WHERE(AND(eq(valor,valor), eq(valor2,valor2)))
67
98
  */
68
99
  where(condicion: string): this;
69
- execute(): Promise<any>;
100
+ execute(): Promise<number | null>;
70
101
  }
71
102
 
72
103
  type arrayData = (string | number)[];
@@ -98,7 +129,17 @@ declare class QueryBuilder {
98
129
  * @returns
99
130
  */
100
131
  Values(values: arrayData | arrayDatas): this;
101
- execute(): Promise<any>;
132
+ execute(): Promise<number | any[] | undefined>;
133
+ }
134
+
135
+ interface ResultSetHeaderMysql {
136
+ fieldCount: number;
137
+ affectedRows: number;
138
+ insertId: number;
139
+ info: string;
140
+ serverStatus: number;
141
+ warningStatus: number;
142
+ changedRows: number;
102
143
  }
103
144
 
104
145
  type valor = "ASC" | "DESC";
@@ -158,7 +199,7 @@ declare class Select {
158
199
  /**
159
200
  * @returns {Promise<Array<Object>>}
160
201
  */
161
- execute(): Promise<any>;
202
+ execute(): Promise<any[] | ResultSetHeaderMysql | undefined>;
162
203
  }
163
204
 
164
205
  type Valores = Record<string, string | number | undefined>;
@@ -201,11 +242,11 @@ declare class DB {
201
242
  /**
202
243
  * @param {string[]} parametros - campo opcional
203
244
  */
204
- static select(parametros?: string[]): Select;
245
+ static Select(parametros?: string[]): Select;
205
246
  /**
206
247
  * @param {string} nombreTabla - nombre de la tabla a actualizar
207
248
  */
208
- static update(nombreTabla: string): Update;
249
+ static Update(nombreTabla: string): Update;
209
250
  /**
210
251
  *
211
252
  * @param {string} nombreTabla -- tabla a eliminar
@@ -304,5 +345,16 @@ declare const MAYOR: (valor: string, valor2: string) => string;
304
345
  * @returns
305
346
  */
306
347
  declare const MENOR: (valor: string, valor2: string) => string;
348
+ /**
349
+ * @example
350
+ *
351
+ * FechaRegistro: {
352
+ typo: "timestamp ",
353
+ default: CURRENT_TIMESTAMP()
354
+ },
355
+ *
356
+ * @returns
357
+ */
358
+ declare const CURRENT_TIMESTAMP: () => string;
307
359
 
308
- export { AND, BDconnection, type Consultas, DB, DeleteR, ILIKE, MAYOR, MENOR, NOTNULL, NOW, NULL, OR, ORQ, QueryBuilder, Select, type Tipos, Update, type Valores, type arrayData, type arrayDatas, type connecionLocal, type connecionRed, type connectionDB, defineTable, eq, getConexion, getRed, type valor };
360
+ export { AND, BDconnection, CURRENT_TIMESTAMP, type ColumnDefinition, 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, type connecionLocal, type connecionRed, type connectionDB, defineTable, eq, generateTable, getConexion, getRed, type valor };
package/dist/index.js CHANGED
@@ -7,7 +7,8 @@ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot
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
9
  // conection/db.ts
10
- var conexion1;
10
+ var conexionZORMZ3691;
11
+ var tipoConexionZORMZ3691;
11
12
  var BDconnection = class {
12
13
  constructor(bd, datos) {
13
14
  this.tipo = "pg";
@@ -85,12 +86,7 @@ var BDconnection = class {
85
86
  if (!respuesta) {
86
87
  throw new Error(` Este usuario no esta registrado `);
87
88
  }
88
- if ("rows" in respuesta) {
89
- if (respuesta.rows[0].id) {
90
- return { insertId: respuesta.rows[0].id };
91
- }
92
- return respuesta.rows;
93
- }
89
+ return respuesta;
94
90
  }
95
91
  } catch (error) {
96
92
  console.log(error);
@@ -103,22 +99,44 @@ var BDconnection = class {
103
99
  }
104
100
  }
105
101
  };
106
- function getConexion(bd, datos) {
107
- conexion1 = new BDconnection(bd, datos);
102
+ async function getConexion(bd, datos) {
103
+ conexionZORMZ3691 = new BDconnection(bd, datos);
104
+ tipoConexionZORMZ3691 = conexionZORMZ3691.tipo;
105
+ await conexionZORMZ3691.executeConsulta({ "query": "select 1+1;" }).then((data) => {
106
+ console.log(`\u{1F44D}\u{1F44D} Conexi\xF3n ${tipoConexionZORMZ3691} exitosa \u{1F61C}`);
107
+ }).catch((err) => {
108
+ console.error(" \u{1F622}\u{1F622} Error al conectar a " + tipoConexionZORMZ3691);
109
+ });
108
110
  }
109
111
  function getRed() {
110
- return conexion1;
112
+ return conexionZORMZ3691;
111
113
  }
112
114
  function defineTable(tableName, columns) {
113
115
  const fn = () => tableName;
114
116
  const proxy = new Proxy(fn, {
115
117
  get(_target, prop) {
118
+ if (prop === "$columns") {
119
+ return columns;
120
+ }
116
121
  if (prop === "name") return tableName;
117
122
  if (prop === "toString") return () => tableName;
118
123
  if (prop === "valueOf") return () => tableName;
119
- const col = columns[prop];
120
- if (col !== void 0) return `${tableName}.${col}`;
121
- return fn[prop];
124
+ if (prop in columns) {
125
+ return `${tableName}.${prop.toString()}`;
126
+ }
127
+ return void 0;
128
+ },
129
+ ownKeys() {
130
+ return Reflect.ownKeys(columns);
131
+ },
132
+ getOwnPropertyDescriptor(_target, prop) {
133
+ if (prop in columns) {
134
+ return {
135
+ enumerable: true,
136
+ configurable: true
137
+ };
138
+ }
139
+ return void 0;
122
140
  },
123
141
  apply() {
124
142
  return tableName;
@@ -126,6 +144,73 @@ function defineTable(tableName, columns) {
126
144
  });
127
145
  return proxy;
128
146
  }
147
+ function ValidacionTypos(columna, id, maxLength) {
148
+ let sql = "";
149
+ if (columna === "varchar")
150
+ sql += `VARCHAR(${maxLength ? maxLength : "100"})`;
151
+ if (columna === "int") {
152
+ if (tipoConexionZORMZ3691 === "pg") {
153
+ sql += id ? " " : " INTEGER ";
154
+ } else {
155
+ sql += " INT ";
156
+ }
157
+ }
158
+ if (columna === "bool")
159
+ sql += tipoConexionZORMZ3691 === "mysql" ? " TINYINT(1) " : " BOOLEAN ";
160
+ if (columna === "double")
161
+ sql += tipoConexionZORMZ3691 === "mysql" ? " DOUBLE " : " DOUBLE PRECISION ";
162
+ if (columna === "timestamp")
163
+ sql += tipoConexionZORMZ3691 === "mysql" ? " TIMESTAMP " : " TIMESTAMPTZ ";
164
+ if (columna === "float")
165
+ sql += tipoConexionZORMZ3691 === "mysql" ? " FLOAT " : " REAL";
166
+ if (columna === "money")
167
+ sql += tipoConexionZORMZ3691 === "mysql" ? " DECIMAL(10,2) " : " NUMERIC(10,2)";
168
+ return sql;
169
+ }
170
+ async function generateTable(tabla, columns) {
171
+ let queries = "";
172
+ let columnDefs = [];
173
+ let sql = "";
174
+ let id = false;
175
+ for (const columnName in columns) {
176
+ const col = columns[columnName];
177
+ sql = ` ${columnName} `;
178
+ if (!col.typo) {
179
+ throw new Error(`La columna ${columnName} no tiene el tipo definido`);
180
+ }
181
+ sql += ValidacionTypos(col.typo, col.id, col.maxLength);
182
+ if (col.id) {
183
+ if (id) throw new Error(`El id no puede repetirse en 2 campos de la tabla '${tabla}'`);
184
+ sql += tipoConexionZORMZ3691 === "mysql" ? " NOT NULL AUTO_INCREMENT " : " SERIAL ";
185
+ sql += " PRIMARY KEY ";
186
+ id = true;
187
+ columnDefs.push(sql);
188
+ continue;
189
+ }
190
+ sql += col.unique === void 0 ? " NOT NULL " : " UNIQUE";
191
+ sql += col.default === void 0 ? col.unique === void 0 ? " " : " NOT NULL " : ` DEFAULT ${typeof col.default === "string" ? tipoConexionZORMZ3691 === "mysql" ? `"${col.default}"` : `'${col.default}'` : col.default}`;
192
+ columnDefs.push(sql);
193
+ }
194
+ queries += `CREATE TABLE IF NOT EXISTS ${tabla} (
195
+ `;
196
+ queries += columnDefs.join(", \n");
197
+ queries += ");";
198
+ if (tipoConexionZORMZ3691 === "mysql") {
199
+ const response = await conexionZORMZ3691.executeConsulta({ query: queries, mensaje: "Error al crear la base de datos" });
200
+ if (response.warningStatus > 0) {
201
+ console.log(` La tabla ${tabla} ya existe \u{1F642}\u{1F610} `);
202
+ } else {
203
+ console.log(`\u{1F44D}\u{1F44D} Se creo con exito la tabla ${tabla} \u{1F61C}`);
204
+ }
205
+ return;
206
+ } else {
207
+ const response = await conexionZORMZ3691.executeConsulta({
208
+ query: queries,
209
+ mensaje: "Error al crear la base de datos"
210
+ });
211
+ console.log(`\u{1F44D}\u{1F44D} Se creo con exito la tabla ${tabla} \u{1F61C}`);
212
+ }
213
+ }
129
214
 
130
215
  // conection/middleware/delete.ts
131
216
  var _condicion, _tabla;
@@ -159,11 +244,19 @@ var DeleteR = class {
159
244
  }
160
245
  async execute() {
161
246
  const query = `DELETE FROM ${__privateGet(this, _tabla)} ${__privateGet(this, _condicion)}`;
162
- const respuesta = await this.conexion.executeConsulta({
163
- query,
164
- mensaje: "Ocurrio un error al momento de eliminar un dato"
165
- });
166
- return respuesta.affectedRows;
247
+ if (this.conexion.tipo === "mysql") {
248
+ const respuesta = await this.conexion.executeConsulta({
249
+ query,
250
+ mensaje: "Ocurrio un error al momento de eliminar un dato"
251
+ });
252
+ return respuesta.affectedRows;
253
+ } else {
254
+ const respuesta = await this.conexion.executeConsulta({
255
+ query,
256
+ mensaje: "Ocurrio un error al momento de eliminar un dato"
257
+ });
258
+ return respuesta.rowCount;
259
+ }
167
260
  }
168
261
  };
169
262
  _condicion = new WeakMap();
@@ -216,29 +309,69 @@ var QueryBuilder = class {
216
309
  let param = "";
217
310
  let arrayArrays = false;
218
311
  let paramespaces = "";
219
- if (typeof this.parametros !== "string") {
220
- if (Array.isArray(this.valores)) arrayArrays = true;
221
- this.parametros.forEach((valor, index) => {
222
- param += valor;
223
- paramespaces += ` ? `;
224
- if (index < this.parametros.length - 1) {
225
- param += ", ";
226
- paramespaces += ", ";
227
- }
228
- });
312
+ if (this.conexion.tipo === "mysql") {
313
+ if (typeof this.parametros !== "string") {
314
+ if (Array.isArray(this.valores[0])) arrayArrays = true;
315
+ this.parametros.forEach((valor, index) => {
316
+ param += valor;
317
+ paramespaces += `?`;
318
+ if (index < this.parametros.length - 1) {
319
+ param += ", ";
320
+ paramespaces += ", ";
321
+ }
322
+ });
323
+ }
324
+ } else if (this.conexion.tipo === "pg") {
325
+ let i = 1;
326
+ let cantidadCaracter = this.tabla.length + 1;
327
+ if (!Array.isArray(this.valores[0])) {
328
+ throw new Error(
329
+ "PostgreSQL requiere array de arrays en INSERT m\xFAltiple"
330
+ );
331
+ }
332
+ if (typeof this.parametros !== "string") {
333
+ this.parametros.forEach((valor, index) => {
334
+ param += valor.slice(cantidadCaracter);
335
+ if (index < this.parametros.length - 1) {
336
+ param += ", ";
337
+ }
338
+ });
339
+ }
340
+ paramespaces = this.valores.map((row) => {
341
+ const p = row.map(() => `$${i++}`).join(", ");
342
+ return `(${p})`;
343
+ }).join(", ");
344
+ let datos = this.valores;
345
+ if (Array.isArray(this.valores[0])) {
346
+ datos = this.valores.flat();
347
+ }
348
+ this.valores = datos;
229
349
  }
230
350
  let query = `${query1} (${param}) VALUES `;
231
- if (arrayArrays) {
351
+ if (this.conexion.tipo === "mysql" && arrayArrays) {
232
352
  query += ` ? `;
233
- } else {
353
+ } else if (this.conexion.tipo === "mysql") {
234
354
  query += `(${paramespaces})`;
355
+ } else {
356
+ query += paramespaces;
357
+ }
358
+ if (this.conexion.tipo === "mysql") {
359
+ const respuesta = await this.conexion.executeConsulta({
360
+ query,
361
+ valores: this.valores,
362
+ mensaje: `Ocurrio un error al ingresar datos a ${this.tabla} `
363
+ });
364
+ console.log(respuesta);
365
+ return respuesta.insertId;
366
+ } else if (this.conexion.tipo === "pg") {
367
+ query += " RETURNING id ";
368
+ const respuesta = await this.conexion.executeConsulta({
369
+ query,
370
+ valores: this.valores,
371
+ mensaje: `Ocurrio un error al ingresar datos a ${this.tabla} `
372
+ });
373
+ return respuesta.rows;
235
374
  }
236
- const respuesta = await this.conexion.executeConsulta({
237
- query,
238
- valores: this.valores,
239
- mensaje: `Ocurrio un error al ingresar datos a ${this.tabla} `
240
- });
241
- return respuesta.insertId;
242
375
  }
243
376
  };
244
377
 
@@ -358,11 +491,19 @@ var Select = class {
358
491
  }
359
492
  }
360
493
  const query = `SELECT ${selectFields} from ${this.tabla} ${this.innerJoin} ${this.leftjoins} ${this.rigthjoins} ${this.condicion} ${this.orderBy} ${this.limit};`;
361
- const respuesta = await this.conexion.executeConsulta({
362
- query,
363
- mensaje: "Ocurrio un error realizar un select"
364
- });
365
- return respuesta;
494
+ if (this.conexion.tipo === "mysql") {
495
+ const respuesta = await this.conexion.executeConsulta({
496
+ query,
497
+ mensaje: "Ocurrio un error realizar un select"
498
+ });
499
+ return respuesta;
500
+ } else if (this.conexion.tipo === "pg") {
501
+ const respuesta = await this.conexion.executeConsulta({
502
+ query,
503
+ mensaje: "Ocurrio un error realizar un select"
504
+ });
505
+ return respuesta.rows;
506
+ }
366
507
  }
367
508
  };
368
509
 
@@ -377,8 +518,8 @@ var OR = (...valor1) => {
377
518
  };
378
519
  var ORQ = (condicion1, ...condicionals) => {
379
520
  const data2 = condicionals.map((dato) => {
380
- if (typeof dato == "number" || typeof dato == "boolean") return ` '${condicion1}' = ${dato}`;
381
- return ` '${condicion1}' = '${dato}' `;
521
+ if (typeof dato == "number" || typeof dato == "boolean") return ` ${condicion1} = ${dato}`;
522
+ return ` ${condicion1} = '${dato}' `;
382
523
  });
383
524
  const separador = data2.join(" or ");
384
525
  return separador;
@@ -418,6 +559,9 @@ var MAYOR = (valor, valor2) => {
418
559
  var MENOR = (valor, valor2) => {
419
560
  return ` ${valor} < ${valor2} `;
420
561
  };
562
+ var CURRENT_TIMESTAMP = () => {
563
+ return " CURRENT_TIMESTAMP ";
564
+ };
421
565
 
422
566
  // conection/middleware/update.ts
423
567
  var Update = class {
@@ -486,11 +630,10 @@ var Update = class {
486
630
  mensaje: "Error Update"
487
631
  });
488
632
  if (this.conexion.tipo === "mysql") {
489
- return respuesta;
633
+ return respuesta.affectedRows;
490
634
  } else {
491
635
  return {
492
- resultado: respuesta.rows.info,
493
- filasAfectadas: respuesta.rows.affectedRows
636
+ resultado: respuesta.rowCount
494
637
  };
495
638
  }
496
639
  }
@@ -511,14 +654,14 @@ var DB = class {
511
654
  /**
512
655
  * @param {string[]} parametros - campo opcional
513
656
  */
514
- static select(parametros) {
657
+ static Select(parametros) {
515
658
  const conex = getRed();
516
659
  return new Select(conex, parametros);
517
660
  }
518
661
  /**
519
662
  * @param {string} nombreTabla - nombre de la tabla a actualizar
520
663
  */
521
- static update(nombreTabla) {
664
+ static Update(nombreTabla) {
522
665
  const conex = getRed();
523
666
  return new Update(conex, nombreTabla);
524
667
  }
@@ -536,6 +679,7 @@ var DB = class {
536
679
  export {
537
680
  AND,
538
681
  BDconnection,
682
+ CURRENT_TIMESTAMP,
539
683
  DB,
540
684
  DeleteR,
541
685
  ILIKE,
@@ -551,6 +695,7 @@ export {
551
695
  Update,
552
696
  defineTable,
553
697
  eq,
698
+ generateTable,
554
699
  getConexion,
555
700
  getRed
556
701
  };
package/package.json CHANGED
@@ -1,50 +1,46 @@
1
1
  {
2
2
  "name": "zormz",
3
- "version": "1.1.2",
3
+ "version": "1.2.3",
4
4
  "description": "",
5
5
  "author": "",
6
6
  "license": "ISC",
7
-
8
7
  "main": "./dist/index.cjs",
9
8
  "module": "./dist/index.js",
10
9
  "types": "./dist/index.d.ts",
11
-
12
10
  "exports": {
13
11
  ".": {
14
12
  "import": "./dist/index.js",
15
13
  "require": "./dist/index.cjs"
16
14
  }
17
15
  },
18
-
19
16
  "type": "module",
20
-
21
17
  "files": [
22
18
  "dist",
23
19
  "README.md"
24
20
  ],
25
-
26
21
  "scripts": {
27
22
  "build": "tsup",
28
23
  "dev": "ts-node index.ts"
29
24
  },
30
-
31
25
  "peerDependencies": {
32
26
  "mysql": "*",
33
- "pg": "*"
27
+ "pg": "^8.16.3"
34
28
  },
35
29
  "peerDependenciesMeta": {
36
- "pg": { "optional": true },
37
- "mysql": { "optional": true }
30
+ "pg": {
31
+ "optional": true
32
+ },
33
+ "mysql": {
34
+ "optional": true
35
+ }
38
36
  },
39
-
40
37
  "dependencies": {
41
38
  "mysql2": "^3.15.3"
42
39
  },
43
-
44
40
  "devDependencies": {
45
- "ts-node": "^10.9.2",
46
- "typescript": "^5.9.3",
47
41
  "@types/node": "^24.10.1",
48
- "tsup": "^8.5.1"
42
+ "ts-node": "^10.9.2",
43
+ "tsup": "^8.5.1",
44
+ "typescript": "^5.9.3"
49
45
  }
50
46
  }