zormz 1.1.2 → 1.2.2

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,57 @@ function defineTable(tableName, columns) {
179
199
  });
180
200
  return proxy;
181
201
  }
202
+ async function generateTable(tabla, columns) {
203
+ let queries = "";
204
+ let columnDefs = [];
205
+ let sql = "";
206
+ let id = false;
207
+ for (const columnName in columns) {
208
+ const col = columns[columnName];
209
+ sql = ` ${columnName} `;
210
+ if (!col.typo) {
211
+ throw new Error(`La columna ${columnName} no tiene el tipo definido`);
212
+ }
213
+ if (col.typo === "varchar") sql += `VARCHAR(${col.maxLength ? col.maxLength : "100"})`;
214
+ if (col.typo === "int") {
215
+ sql += col.id && tipoConexionZORMZ3691 === "pg" ? " " : ` INT `;
216
+ }
217
+ if (col.typo === "DateTime") sql += " DATETIME ";
218
+ if (col.typo === "bool") sql += " TINYINT ";
219
+ if (col.typo === "double") sql += " DOUBLE ";
220
+ if (col.typo === "Timestamp") sql += tipoConexionZORMZ3691 === "mysql" ? " TIMESTAMP " : " TIMESTAMPTZ ";
221
+ if (col.id) {
222
+ if (id) throw new Error(`El id no puede repetirse en 2 campos de la tabla '${tabla}'`);
223
+ sql += tipoConexionZORMZ3691 === "mysql" ? " NOT NULL AUTO_INCREMENT " : " SERIAL ";
224
+ sql += " PRIMARY KEY ";
225
+ id = true;
226
+ columnDefs.push(sql);
227
+ continue;
228
+ }
229
+ sql += col.unique === void 0 ? " NOT NULL " : " UNIQUE";
230
+ sql += col.default === void 0 ? col.unique === void 0 ? " " : " NOT NULL " : ` DEFAULT ${typeof col.default === "string" ? tipoConexionZORMZ3691 === "mysql" ? `"${col.default}"` : `'${col.default}'` : col.default}`;
231
+ columnDefs.push(sql);
232
+ }
233
+ queries += `CREATE TABLE IF NOT EXISTS ${tabla} (
234
+ `;
235
+ queries += columnDefs.join(", \n");
236
+ queries += ");";
237
+ if (tipoConexionZORMZ3691 === "mysql") {
238
+ const response = await conexionZORMZ3691.executeConsulta({ query: queries, mensaje: "Error al crear la base de datos" });
239
+ if (response.warningStatus > 0) {
240
+ console.log(` La tabla ${tabla} ya existe \u{1F642}\u{1F610} `);
241
+ } else {
242
+ console.log(`\u{1F44D}\u{1F44D} Se creo con exito la tabla ${tabla} \u{1F61C}`);
243
+ }
244
+ return;
245
+ } else {
246
+ const response = await conexionZORMZ3691.executeConsulta({
247
+ query: queries,
248
+ mensaje: "Error al crear la base de datos"
249
+ });
250
+ console.log(`\u{1F44D}\u{1F44D} Se creo con exito la tabla ${tabla} \u{1F61C}`);
251
+ }
252
+ }
182
253
 
183
254
  // conection/middleware/delete.ts
184
255
  var _condicion, _tabla;
@@ -212,11 +283,19 @@ var DeleteR = class {
212
283
  }
213
284
  async execute() {
214
285
  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;
286
+ if (this.conexion.tipo === "mysql") {
287
+ const respuesta = await this.conexion.executeConsulta({
288
+ query,
289
+ mensaje: "Ocurrio un error al momento de eliminar un dato"
290
+ });
291
+ return respuesta.affectedRows;
292
+ } else {
293
+ const respuesta = await this.conexion.executeConsulta({
294
+ query,
295
+ mensaje: "Ocurrio un error al momento de eliminar un dato"
296
+ });
297
+ return respuesta.rowCount;
298
+ }
220
299
  }
221
300
  };
222
301
  _condicion = new WeakMap();
@@ -269,29 +348,69 @@ var QueryBuilder = class {
269
348
  let param = "";
270
349
  let arrayArrays = false;
271
350
  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
- });
351
+ if (this.conexion.tipo === "mysql") {
352
+ if (typeof this.parametros !== "string") {
353
+ if (Array.isArray(this.valores[0])) arrayArrays = true;
354
+ this.parametros.forEach((valor, index) => {
355
+ param += valor;
356
+ paramespaces += `?`;
357
+ if (index < this.parametros.length - 1) {
358
+ param += ", ";
359
+ paramespaces += ", ";
360
+ }
361
+ });
362
+ }
363
+ } else if (this.conexion.tipo === "pg") {
364
+ let i = 1;
365
+ let cantidadCaracter = this.tabla.length + 1;
366
+ if (!Array.isArray(this.valores[0])) {
367
+ throw new Error(
368
+ "PostgreSQL requiere array de arrays en INSERT m\xFAltiple"
369
+ );
370
+ }
371
+ if (typeof this.parametros !== "string") {
372
+ this.parametros.forEach((valor, index) => {
373
+ param += valor.slice(cantidadCaracter);
374
+ if (index < this.parametros.length - 1) {
375
+ param += ", ";
376
+ }
377
+ });
378
+ }
379
+ paramespaces = this.valores.map((row) => {
380
+ const p = row.map(() => `$${i++}`).join(", ");
381
+ return `(${p})`;
382
+ }).join(", ");
383
+ let datos = this.valores;
384
+ if (Array.isArray(this.valores[0])) {
385
+ datos = this.valores.flat();
386
+ }
387
+ this.valores = datos;
282
388
  }
283
389
  let query = `${query1} (${param}) VALUES `;
284
- if (arrayArrays) {
390
+ if (this.conexion.tipo === "mysql" && arrayArrays) {
285
391
  query += ` ? `;
286
- } else {
392
+ } else if (this.conexion.tipo === "mysql") {
287
393
  query += `(${paramespaces})`;
394
+ } else {
395
+ query += paramespaces;
396
+ }
397
+ if (this.conexion.tipo === "mysql") {
398
+ const respuesta = await this.conexion.executeConsulta({
399
+ query,
400
+ valores: this.valores,
401
+ mensaje: `Ocurrio un error al ingresar datos a ${this.tabla} `
402
+ });
403
+ console.log(respuesta);
404
+ return respuesta.insertId;
405
+ } else if (this.conexion.tipo === "pg") {
406
+ query += " RETURNING id ";
407
+ const respuesta = await this.conexion.executeConsulta({
408
+ query,
409
+ valores: this.valores,
410
+ mensaje: `Ocurrio un error al ingresar datos a ${this.tabla} `
411
+ });
412
+ return respuesta.rows;
288
413
  }
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
414
  }
296
415
  };
297
416
 
@@ -411,11 +530,19 @@ var Select = class {
411
530
  }
412
531
  }
413
532
  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;
533
+ if (this.conexion.tipo === "mysql") {
534
+ const respuesta = await this.conexion.executeConsulta({
535
+ query,
536
+ mensaje: "Ocurrio un error realizar un select"
537
+ });
538
+ return respuesta;
539
+ } else if (this.conexion.tipo === "pg") {
540
+ const respuesta = await this.conexion.executeConsulta({
541
+ query,
542
+ mensaje: "Ocurrio un error realizar un select"
543
+ });
544
+ return respuesta.rows;
545
+ }
419
546
  }
420
547
  };
421
548
 
@@ -430,8 +557,8 @@ var OR = (...valor1) => {
430
557
  };
431
558
  var ORQ = (condicion1, ...condicionals) => {
432
559
  const data2 = condicionals.map((dato) => {
433
- if (typeof dato == "number" || typeof dato == "boolean") return ` '${condicion1}' = ${dato}`;
434
- return ` '${condicion1}' = '${dato}' `;
560
+ if (typeof dato == "number" || typeof dato == "boolean") return ` ${condicion1} = ${dato}`;
561
+ return ` ${condicion1} = '${dato}' `;
435
562
  });
436
563
  const separador = data2.join(" or ");
437
564
  return separador;
@@ -471,6 +598,9 @@ var MAYOR = (valor, valor2) => {
471
598
  var MENOR = (valor, valor2) => {
472
599
  return ` ${valor} < ${valor2} `;
473
600
  };
601
+ var CURRENT_TIMESTAMP = () => {
602
+ return " CURRENT_TIMESTAMP ";
603
+ };
474
604
 
475
605
  // conection/middleware/update.ts
476
606
  var Update = class {
@@ -539,11 +669,10 @@ var Update = class {
539
669
  mensaje: "Error Update"
540
670
  });
541
671
  if (this.conexion.tipo === "mysql") {
542
- return respuesta;
672
+ return respuesta.affectedRows;
543
673
  } else {
544
674
  return {
545
- resultado: respuesta.rows.info,
546
- filasAfectadas: respuesta.rows.affectedRows
675
+ resultado: respuesta.rowCount
547
676
  };
548
677
  }
549
678
  }
@@ -564,14 +693,14 @@ var DB = class {
564
693
  /**
565
694
  * @param {string[]} parametros - campo opcional
566
695
  */
567
- static select(parametros) {
696
+ static Select(parametros) {
568
697
  const conex = getRed();
569
698
  return new Select(conex, parametros);
570
699
  }
571
700
  /**
572
701
  * @param {string} nombreTabla - nombre de la tabla a actualizar
573
702
  */
574
- static update(nombreTabla) {
703
+ static Update(nombreTabla) {
575
704
  const conex = getRed();
576
705
  return new Update(conex, nombreTabla);
577
706
  }
@@ -590,6 +719,7 @@ var DB = class {
590
719
  0 && (module.exports = {
591
720
  AND,
592
721
  BDconnection,
722
+ CURRENT_TIMESTAMP,
593
723
  DB,
594
724
  DeleteR,
595
725
  ILIKE,
@@ -605,6 +735,7 @@ var DB = class {
605
735
  Update,
606
736
  defineTable,
607
737
  eq,
738
+ generateTable,
608
739
  getConexion,
609
740
  getRed
610
741
  });
package/dist/index.d.cts CHANGED
@@ -29,24 +29,54 @@ 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" | "DateTime" | "Timestamp";
35
+ type ColumnTypeMap = {
36
+ varchar: string;
37
+ double: number;
38
+ DateTime: Date;
39
+ int: number;
40
+ bool: boolean;
41
+ Timestamp: Date;
42
+ };
43
+ interface ColumnDefinition<T extends ColumnTypes = ColumnTypes> {
44
+ typo: T;
45
+ id?: boolean;
46
+ maxLength?: number;
47
+ default?: ColumnTypeMap[T];
48
+ unique?: boolean;
49
+ }
50
+ type TableProxy<TCols> = {
51
+ (): string;
52
+ $columns: TCols;
53
+ } & {
54
+ [K in keyof TCols]: string;
55
+ };
35
56
  /**
36
57
  *
37
58
  * @param {string} tableName
38
59
  * @param {string} columns
39
60
  * @example
40
61
  * export const productosPrueba = defineTable("productosPrueba",{
41
- * id:"id",
42
- * nombre:"nombre",
43
- * descripcion:"descripcion"
62
+ * id:{typo:"int",id:true},
63
+ dato: {
64
+ typo:"varchar",
65
+ maxLength:200,
66
+ default:"hola mundo"
67
+ },
68
+ edad: {
69
+ typo:"int",
70
+ default: 0,
71
+ },
72
+ apellido : {
73
+ typo:"varchar",
74
+ }
44
75
  * });
45
76
  * @returns
46
77
  */
47
- declare function defineTable<T extends ColumnsMap>(tableName: string, columns: T): T & (() => string) & {
48
- name: string;
49
- };
78
+ declare function defineTable<T extends Record<string, ColumnDefinition>>(tableName: string, columns: T): TableProxy<T>;
79
+ declare function generateTable<T extends Record<string, ColumnDefinition>>(tabla: string, columns: T): Promise<void>;
50
80
 
51
81
  declare class DeleteR {
52
82
  #private;
@@ -66,7 +96,7 @@ declare class DeleteR {
66
96
  * DB.Delete(tabla).WHERE(AND(eq(valor,valor), eq(valor2,valor2)))
67
97
  */
68
98
  where(condicion: string): this;
69
- execute(): Promise<any>;
99
+ execute(): Promise<number | null>;
70
100
  }
71
101
 
72
102
  type arrayData = (string | number)[];
@@ -98,7 +128,17 @@ declare class QueryBuilder {
98
128
  * @returns
99
129
  */
100
130
  Values(values: arrayData | arrayDatas): this;
101
- execute(): Promise<any>;
131
+ execute(): Promise<number | any[] | undefined>;
132
+ }
133
+
134
+ interface ResultSetHeaderMysql {
135
+ fieldCount: number;
136
+ affectedRows: number;
137
+ insertId: number;
138
+ info: string;
139
+ serverStatus: number;
140
+ warningStatus: number;
141
+ changedRows: number;
102
142
  }
103
143
 
104
144
  type valor = "ASC" | "DESC";
@@ -158,7 +198,7 @@ declare class Select {
158
198
  /**
159
199
  * @returns {Promise<Array<Object>>}
160
200
  */
161
- execute(): Promise<any>;
201
+ execute(): Promise<any[] | ResultSetHeaderMysql | undefined>;
162
202
  }
163
203
 
164
204
  type Valores = Record<string, string | number | undefined>;
@@ -201,11 +241,11 @@ declare class DB {
201
241
  /**
202
242
  * @param {string[]} parametros - campo opcional
203
243
  */
204
- static select(parametros?: string[]): Select;
244
+ static Select(parametros?: string[]): Select;
205
245
  /**
206
246
  * @param {string} nombreTabla - nombre de la tabla a actualizar
207
247
  */
208
- static update(nombreTabla: string): Update;
248
+ static Update(nombreTabla: string): Update;
209
249
  /**
210
250
  *
211
251
  * @param {string} nombreTabla -- tabla a eliminar
@@ -304,5 +344,16 @@ declare const MAYOR: (valor: string, valor2: string) => string;
304
344
  * @returns
305
345
  */
306
346
  declare const MENOR: (valor: string, valor2: string) => string;
347
+ /**
348
+ * @example
349
+ *
350
+ * FechaRegistro: {
351
+ typo: "Timestamp ",
352
+ default: CURRENT_TIMESTAMP()
353
+ },
354
+ *
355
+ * @returns
356
+ */
357
+ declare const CURRENT_TIMESTAMP: () => string;
307
358
 
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 };
359
+ 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,54 @@ 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" | "DateTime" | "Timestamp";
35
+ type ColumnTypeMap = {
36
+ varchar: string;
37
+ double: number;
38
+ DateTime: Date;
39
+ int: number;
40
+ bool: boolean;
41
+ Timestamp: Date;
42
+ };
43
+ interface ColumnDefinition<T extends ColumnTypes = ColumnTypes> {
44
+ typo: T;
45
+ id?: boolean;
46
+ maxLength?: number;
47
+ default?: ColumnTypeMap[T];
48
+ unique?: boolean;
49
+ }
50
+ type TableProxy<TCols> = {
51
+ (): string;
52
+ $columns: TCols;
53
+ } & {
54
+ [K in keyof TCols]: string;
55
+ };
35
56
  /**
36
57
  *
37
58
  * @param {string} tableName
38
59
  * @param {string} columns
39
60
  * @example
40
61
  * export const productosPrueba = defineTable("productosPrueba",{
41
- * id:"id",
42
- * nombre:"nombre",
43
- * descripcion:"descripcion"
62
+ * id:{typo:"int",id:true},
63
+ dato: {
64
+ typo:"varchar",
65
+ maxLength:200,
66
+ default:"hola mundo"
67
+ },
68
+ edad: {
69
+ typo:"int",
70
+ default: 0,
71
+ },
72
+ apellido : {
73
+ typo:"varchar",
74
+ }
44
75
  * });
45
76
  * @returns
46
77
  */
47
- declare function defineTable<T extends ColumnsMap>(tableName: string, columns: T): T & (() => string) & {
48
- name: string;
49
- };
78
+ declare function defineTable<T extends Record<string, ColumnDefinition>>(tableName: string, columns: T): TableProxy<T>;
79
+ declare function generateTable<T extends Record<string, ColumnDefinition>>(tabla: string, columns: T): Promise<void>;
50
80
 
51
81
  declare class DeleteR {
52
82
  #private;
@@ -66,7 +96,7 @@ declare class DeleteR {
66
96
  * DB.Delete(tabla).WHERE(AND(eq(valor,valor), eq(valor2,valor2)))
67
97
  */
68
98
  where(condicion: string): this;
69
- execute(): Promise<any>;
99
+ execute(): Promise<number | null>;
70
100
  }
71
101
 
72
102
  type arrayData = (string | number)[];
@@ -98,7 +128,17 @@ declare class QueryBuilder {
98
128
  * @returns
99
129
  */
100
130
  Values(values: arrayData | arrayDatas): this;
101
- execute(): Promise<any>;
131
+ execute(): Promise<number | any[] | undefined>;
132
+ }
133
+
134
+ interface ResultSetHeaderMysql {
135
+ fieldCount: number;
136
+ affectedRows: number;
137
+ insertId: number;
138
+ info: string;
139
+ serverStatus: number;
140
+ warningStatus: number;
141
+ changedRows: number;
102
142
  }
103
143
 
104
144
  type valor = "ASC" | "DESC";
@@ -158,7 +198,7 @@ declare class Select {
158
198
  /**
159
199
  * @returns {Promise<Array<Object>>}
160
200
  */
161
- execute(): Promise<any>;
201
+ execute(): Promise<any[] | ResultSetHeaderMysql | undefined>;
162
202
  }
163
203
 
164
204
  type Valores = Record<string, string | number | undefined>;
@@ -201,11 +241,11 @@ declare class DB {
201
241
  /**
202
242
  * @param {string[]} parametros - campo opcional
203
243
  */
204
- static select(parametros?: string[]): Select;
244
+ static Select(parametros?: string[]): Select;
205
245
  /**
206
246
  * @param {string} nombreTabla - nombre de la tabla a actualizar
207
247
  */
208
- static update(nombreTabla: string): Update;
248
+ static Update(nombreTabla: string): Update;
209
249
  /**
210
250
  *
211
251
  * @param {string} nombreTabla -- tabla a eliminar
@@ -304,5 +344,16 @@ declare const MAYOR: (valor: string, valor2: string) => string;
304
344
  * @returns
305
345
  */
306
346
  declare const MENOR: (valor: string, valor2: string) => string;
347
+ /**
348
+ * @example
349
+ *
350
+ * FechaRegistro: {
351
+ typo: "Timestamp ",
352
+ default: CURRENT_TIMESTAMP()
353
+ },
354
+ *
355
+ * @returns
356
+ */
357
+ declare const CURRENT_TIMESTAMP: () => string;
307
358
 
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 };
359
+ 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,57 @@ function defineTable(tableName, columns) {
126
144
  });
127
145
  return proxy;
128
146
  }
147
+ async function generateTable(tabla, columns) {
148
+ let queries = "";
149
+ let columnDefs = [];
150
+ let sql = "";
151
+ let id = false;
152
+ for (const columnName in columns) {
153
+ const col = columns[columnName];
154
+ sql = ` ${columnName} `;
155
+ if (!col.typo) {
156
+ throw new Error(`La columna ${columnName} no tiene el tipo definido`);
157
+ }
158
+ if (col.typo === "varchar") sql += `VARCHAR(${col.maxLength ? col.maxLength : "100"})`;
159
+ if (col.typo === "int") {
160
+ sql += col.id && tipoConexionZORMZ3691 === "pg" ? " " : ` INT `;
161
+ }
162
+ if (col.typo === "DateTime") sql += " DATETIME ";
163
+ if (col.typo === "bool") sql += " TINYINT ";
164
+ if (col.typo === "double") sql += " DOUBLE ";
165
+ if (col.typo === "Timestamp") sql += tipoConexionZORMZ3691 === "mysql" ? " TIMESTAMP " : " TIMESTAMPTZ ";
166
+ if (col.id) {
167
+ if (id) throw new Error(`El id no puede repetirse en 2 campos de la tabla '${tabla}'`);
168
+ sql += tipoConexionZORMZ3691 === "mysql" ? " NOT NULL AUTO_INCREMENT " : " SERIAL ";
169
+ sql += " PRIMARY KEY ";
170
+ id = true;
171
+ columnDefs.push(sql);
172
+ continue;
173
+ }
174
+ sql += col.unique === void 0 ? " NOT NULL " : " UNIQUE";
175
+ sql += col.default === void 0 ? col.unique === void 0 ? " " : " NOT NULL " : ` DEFAULT ${typeof col.default === "string" ? tipoConexionZORMZ3691 === "mysql" ? `"${col.default}"` : `'${col.default}'` : col.default}`;
176
+ columnDefs.push(sql);
177
+ }
178
+ queries += `CREATE TABLE IF NOT EXISTS ${tabla} (
179
+ `;
180
+ queries += columnDefs.join(", \n");
181
+ queries += ");";
182
+ if (tipoConexionZORMZ3691 === "mysql") {
183
+ const response = await conexionZORMZ3691.executeConsulta({ query: queries, mensaje: "Error al crear la base de datos" });
184
+ if (response.warningStatus > 0) {
185
+ console.log(` La tabla ${tabla} ya existe \u{1F642}\u{1F610} `);
186
+ } else {
187
+ console.log(`\u{1F44D}\u{1F44D} Se creo con exito la tabla ${tabla} \u{1F61C}`);
188
+ }
189
+ return;
190
+ } else {
191
+ const response = await conexionZORMZ3691.executeConsulta({
192
+ query: queries,
193
+ mensaje: "Error al crear la base de datos"
194
+ });
195
+ console.log(`\u{1F44D}\u{1F44D} Se creo con exito la tabla ${tabla} \u{1F61C}`);
196
+ }
197
+ }
129
198
 
130
199
  // conection/middleware/delete.ts
131
200
  var _condicion, _tabla;
@@ -159,11 +228,19 @@ var DeleteR = class {
159
228
  }
160
229
  async execute() {
161
230
  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;
231
+ if (this.conexion.tipo === "mysql") {
232
+ const respuesta = await this.conexion.executeConsulta({
233
+ query,
234
+ mensaje: "Ocurrio un error al momento de eliminar un dato"
235
+ });
236
+ return respuesta.affectedRows;
237
+ } else {
238
+ const respuesta = await this.conexion.executeConsulta({
239
+ query,
240
+ mensaje: "Ocurrio un error al momento de eliminar un dato"
241
+ });
242
+ return respuesta.rowCount;
243
+ }
167
244
  }
168
245
  };
169
246
  _condicion = new WeakMap();
@@ -216,29 +293,69 @@ var QueryBuilder = class {
216
293
  let param = "";
217
294
  let arrayArrays = false;
218
295
  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
- });
296
+ if (this.conexion.tipo === "mysql") {
297
+ if (typeof this.parametros !== "string") {
298
+ if (Array.isArray(this.valores[0])) arrayArrays = true;
299
+ this.parametros.forEach((valor, index) => {
300
+ param += valor;
301
+ paramespaces += `?`;
302
+ if (index < this.parametros.length - 1) {
303
+ param += ", ";
304
+ paramespaces += ", ";
305
+ }
306
+ });
307
+ }
308
+ } else if (this.conexion.tipo === "pg") {
309
+ let i = 1;
310
+ let cantidadCaracter = this.tabla.length + 1;
311
+ if (!Array.isArray(this.valores[0])) {
312
+ throw new Error(
313
+ "PostgreSQL requiere array de arrays en INSERT m\xFAltiple"
314
+ );
315
+ }
316
+ if (typeof this.parametros !== "string") {
317
+ this.parametros.forEach((valor, index) => {
318
+ param += valor.slice(cantidadCaracter);
319
+ if (index < this.parametros.length - 1) {
320
+ param += ", ";
321
+ }
322
+ });
323
+ }
324
+ paramespaces = this.valores.map((row) => {
325
+ const p = row.map(() => `$${i++}`).join(", ");
326
+ return `(${p})`;
327
+ }).join(", ");
328
+ let datos = this.valores;
329
+ if (Array.isArray(this.valores[0])) {
330
+ datos = this.valores.flat();
331
+ }
332
+ this.valores = datos;
229
333
  }
230
334
  let query = `${query1} (${param}) VALUES `;
231
- if (arrayArrays) {
335
+ if (this.conexion.tipo === "mysql" && arrayArrays) {
232
336
  query += ` ? `;
233
- } else {
337
+ } else if (this.conexion.tipo === "mysql") {
234
338
  query += `(${paramespaces})`;
339
+ } else {
340
+ query += paramespaces;
341
+ }
342
+ if (this.conexion.tipo === "mysql") {
343
+ const respuesta = await this.conexion.executeConsulta({
344
+ query,
345
+ valores: this.valores,
346
+ mensaje: `Ocurrio un error al ingresar datos a ${this.tabla} `
347
+ });
348
+ console.log(respuesta);
349
+ return respuesta.insertId;
350
+ } else if (this.conexion.tipo === "pg") {
351
+ query += " RETURNING id ";
352
+ const respuesta = await this.conexion.executeConsulta({
353
+ query,
354
+ valores: this.valores,
355
+ mensaje: `Ocurrio un error al ingresar datos a ${this.tabla} `
356
+ });
357
+ return respuesta.rows;
235
358
  }
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
359
  }
243
360
  };
244
361
 
@@ -358,11 +475,19 @@ var Select = class {
358
475
  }
359
476
  }
360
477
  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;
478
+ if (this.conexion.tipo === "mysql") {
479
+ const respuesta = await this.conexion.executeConsulta({
480
+ query,
481
+ mensaje: "Ocurrio un error realizar un select"
482
+ });
483
+ return respuesta;
484
+ } else if (this.conexion.tipo === "pg") {
485
+ const respuesta = await this.conexion.executeConsulta({
486
+ query,
487
+ mensaje: "Ocurrio un error realizar un select"
488
+ });
489
+ return respuesta.rows;
490
+ }
366
491
  }
367
492
  };
368
493
 
@@ -377,8 +502,8 @@ var OR = (...valor1) => {
377
502
  };
378
503
  var ORQ = (condicion1, ...condicionals) => {
379
504
  const data2 = condicionals.map((dato) => {
380
- if (typeof dato == "number" || typeof dato == "boolean") return ` '${condicion1}' = ${dato}`;
381
- return ` '${condicion1}' = '${dato}' `;
505
+ if (typeof dato == "number" || typeof dato == "boolean") return ` ${condicion1} = ${dato}`;
506
+ return ` ${condicion1} = '${dato}' `;
382
507
  });
383
508
  const separador = data2.join(" or ");
384
509
  return separador;
@@ -418,6 +543,9 @@ var MAYOR = (valor, valor2) => {
418
543
  var MENOR = (valor, valor2) => {
419
544
  return ` ${valor} < ${valor2} `;
420
545
  };
546
+ var CURRENT_TIMESTAMP = () => {
547
+ return " CURRENT_TIMESTAMP ";
548
+ };
421
549
 
422
550
  // conection/middleware/update.ts
423
551
  var Update = class {
@@ -486,11 +614,10 @@ var Update = class {
486
614
  mensaje: "Error Update"
487
615
  });
488
616
  if (this.conexion.tipo === "mysql") {
489
- return respuesta;
617
+ return respuesta.affectedRows;
490
618
  } else {
491
619
  return {
492
- resultado: respuesta.rows.info,
493
- filasAfectadas: respuesta.rows.affectedRows
620
+ resultado: respuesta.rowCount
494
621
  };
495
622
  }
496
623
  }
@@ -511,14 +638,14 @@ var DB = class {
511
638
  /**
512
639
  * @param {string[]} parametros - campo opcional
513
640
  */
514
- static select(parametros) {
641
+ static Select(parametros) {
515
642
  const conex = getRed();
516
643
  return new Select(conex, parametros);
517
644
  }
518
645
  /**
519
646
  * @param {string} nombreTabla - nombre de la tabla a actualizar
520
647
  */
521
- static update(nombreTabla) {
648
+ static Update(nombreTabla) {
522
649
  const conex = getRed();
523
650
  return new Update(conex, nombreTabla);
524
651
  }
@@ -536,6 +663,7 @@ var DB = class {
536
663
  export {
537
664
  AND,
538
665
  BDconnection,
666
+ CURRENT_TIMESTAMP,
539
667
  DB,
540
668
  DeleteR,
541
669
  ILIKE,
@@ -551,6 +679,7 @@ export {
551
679
  Update,
552
680
  defineTable,
553
681
  eq,
682
+ generateTable,
554
683
  getConexion,
555
684
  getRed
556
685
  };
package/package.json CHANGED
@@ -1,50 +1,46 @@
1
1
  {
2
2
  "name": "zormz",
3
- "version": "1.1.2",
3
+ "version": "1.2.2",
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
  }