zormz 1.2.2 → 1.2.4

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
@@ -1,7 +1,7 @@
1
1
  # ZORMZ
2
2
 
3
- Un ORM ligero escrito en TypeScript para MySQL y PostgreSQL, diseñado para ser simple, rápido y extensible.
4
- por ahora solo es posible conectarse a una base de datos.
3
+ Un ORM ligero escrito en TypeScript para **MySQL** y **PostgreSQL**, diseñado para ser simple, rápido y extensible.
4
+ Permite conectarse a una base de datos, definir tablas desde TypeScript con autocompletado y tipado, y generar tablas automáticamente.
5
5
 
6
6
  ---
7
7
 
@@ -11,7 +11,11 @@ por ahora solo es posible conectarse a una base de datos.
11
11
  * Tipado completo en **TypeScript**
12
12
  * Builder con sintaxis encadenada: `select().from().where().execute()`
13
13
  * Insert múltiple con arrays
14
- * Soporte para MySQL y PostgreSQL
14
+ * Update y Delete con condiciones
15
+ * Definición de columnas con encadenamiento:
16
+ * `int().Pk().$()`
17
+ * `varchar(200).Default("hola").$()`
18
+ * Generación automática de tablas en MySQL y PostgreSQL
15
19
  * Sin dependencias pesadas
16
20
  * Fácil de extender
17
21
 
@@ -21,207 +25,177 @@ por ahora solo es posible conectarse a una base de datos.
21
25
 
22
26
  ```bash
23
27
  npm install zormz
24
- ```
25
-
26
- ---
27
-
28
- ## Uso básico
29
28
 
30
- ### Importación (ESM)
29
+ ```
31
30
 
31
+ ## Uso basico
32
+ ### importacion ESM
32
33
  ```ts
33
- import { connecionLocal, getConexion } from "zormz";
34
- ```
35
34
 
36
- ### Importación (CommonJS)
35
+ import { connecionLocal, getConexion, defineTable, generateTable, int, varchar, DB, eq, ORQ } from "zormz";
37
36
 
38
- ```js
39
- const { connecionLocal, getConexion } = require("zormz");
40
37
  ```
38
+ ### importacion COMMONJS
41
39
 
42
- ---
43
-
40
+ ```ts
41
+ const { connecionLocal, getConexion, defineTable, generateTable, int, varchar, DB, eq, ORQ } = require("zormz");
44
42
 
45
- ## Conexión a la base de datos
46
- ### mysql local
43
+ ```
44
+ ## Conexion a la base de datos
45
+ ### MYSQL
47
46
  ```ts
48
- import { connecionLocal, DB, getConexion } from "zormz";
49
- //de preferencia esto en el archivo raiz index.ts
50
- const conexion: connecionLocal = {
51
- database: "pruebamaster",
52
- user: "root",
47
+ const conexionMysql: connecionLocal = {
48
+ database: "pruebas",
49
+ host: "localhost",
53
50
  password: "",
54
51
  port: 3306,
55
- host: "localhost",
52
+ user: "root",
56
53
  };
57
54
 
58
- getConexion("mysql", conexion);
59
- ```
60
-
61
- ---
55
+ getConexion("mysql", conexionMysql);
62
56
 
63
- ### pg en linea
57
+ ```
64
58
 
59
+ ### PG
65
60
  ```ts
66
- const conexionPg:connecionRed = {
67
- connectionString:"ruta de la conexion"
61
+ //Conexion por red , aqui solo se pone la ruta que por defecto te arroja la base de datos de la nube
62
+ const conexion2:connecionRed = {
63
+ connectionString:"direccion"
68
64
  }
69
- getConexion("pg",conexionPg);
70
- ```
71
- ---
72
-
73
-
74
- ## Métodos disponibles
75
-
76
- ### **Select**
77
- ### **Insert**
78
- ### **Update**
79
- ### **Delete**
80
65
 
66
+ const conexion: connecionLocal = {
67
+ database: "pruebamaster",
68
+ host: "localhost",
69
+ password: "zainmaster123",
70
+ port: 5432,
71
+ user: "postgres",
72
+ };
81
73
 
82
- ---
74
+ getConexion("pg", conexion);
83
75
 
84
- ## Creación de tablas para autocompletado y SQL
76
+ ```
85
77
 
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:
78
+ ## Definicion de Tablas
87
79
 
88
- * Autocompletado en el editor
89
- * Tipado básico de columnas
80
+ ```ts
81
+ export const prueba1 = defineTable("prueba1", {
82
+ id: int().Pk().$(),
83
+ valor: varchar(200).Default("hola").$(),
84
+ resultado: int().Default(0).$(),
85
+ fechaRegistro: timestamp().required().now().$(),
86
+ fechaUpdate: timestamp().required().now().onUpdate().$()
90
87
 
91
- Esto es útil si ya tienes la base de datos creada o si quieres preparar el schema antes de automatizarlo.
88
+ });
92
89
 
90
+ ```
93
91
 
94
- ### Ejemplo de definición de tabla
92
+ ### Notas importantes
93
+ * **.pk()** define la columna como clave primaria
94
+ * **.Default()** entrega un valor por defecto
95
+ * **.$()** finaliza la definicion y entrega un valor compatible con *$columns*
95
96
 
97
+ ## Generacion de tablas
96
98
  ```ts
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
- });
99
+ generateTable(prueba1(), prueba1.$columns);
116
100
  ```
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 😢
101
+ Esto crea la tabla en la base de datos respetando tipos, claves primarias y valores por defecto.
124
102
 
125
103
  ---
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.
104
+
105
+ ## Insertar Datos
129
106
 
130
107
  ```ts
131
- import { master } from "./archivos/prueba";
132
- generateTable(master(), master.$columns);
108
+ await DB.Insert(prueba1(), [prueba1.valor, prueba1.resultado])
109
+ .Values([["hola mundo", 1], ["prueba", 0]])
110
+ .execute();
133
111
 
134
112
  ```
113
+ ---
135
114
 
136
- ## Ejemplo: Insertar datos
115
+ ## Select de Datos
137
116
 
138
117
  ```ts
139
- const response = await DB.Insert(datosPrueba(),
140
- [datosPrueba.nombre, datosPrueba.data]).Values(['yunno','magic wind']).execute();
141
- ```
118
+ const datos = await DB.select()
119
+ .from(prueba1())
120
+ .where(eq(prueba1.id, 1))
121
+ .execute();
142
122
 
143
- Resultado esperado:
144
-
145
- ```sql
146
- INSERT INTO datosPrueba (nombre, data) VALUES (?, ?);
147
123
  ```
148
-
149
124
  ---
150
125
 
151
- ## Ejemplo: Select
152
-
126
+ ## Update de Datos
153
127
  ```ts
154
- let datos = await DB.select().from(datosPrueba()).where(eq(datosPrueba.id,2)).execute();
155
- console.log(datos);
128
+ await DB.Update(prueba1())
129
+ .set({ valor: "nuevo valor", resultado: 2 })
130
+ .where(eq(prueba1.id, 1))
131
+ .execute();
132
+
156
133
  ```
157
134
  ---
158
-
159
- ## Ejemplo: Insert
160
-
135
+ ## Delete de Datos
161
136
  ```ts
162
- const response = await DB.Insert(productosPrueba(),
163
- [productosPrueba.nombre,productosPrueba.descripcion]).Values(['yunno','magic wind']).execute();
137
+ await DB.Delete(prueba1())
138
+ .where(ORQ(prueba1.id, 2, 3))
139
+ .execute();
140
+
164
141
  ```
142
+
165
143
  ---
166
144
 
167
- ## Ejemplo completo
145
+ ## Ejemplo de Uso
168
146
 
169
147
  ```ts
170
- import { connecionLocal, DB, eq, getConexion, ORQ } from "zormz";
148
+ import { connecionLocal, getConexion, defineTable, generateTable, int, varchar, DB, eq, ORQ } from "zormz";
171
149
 
172
150
  const conexion: connecionLocal = {
173
151
  database: "pruebamaster",
174
- user: "root",
175
- password: "",
176
- port: 3306,
177
152
  host: "localhost",
153
+ password: "pgZORMZ",
154
+ port: 5432,
155
+ user: "postgres",
178
156
  };
179
157
 
180
- getConexion("mysql", conexion);
158
+ getConexion("pg", conexion);
181
159
 
182
- async function pruebaData() {
183
- let datos = await DB.select().from("datosPrueba").execute();
184
- console.log(datos);
160
+ const prueba1 = defineTable("prueba1", {
161
+ id: int().Pk().$(),
162
+ valor: varchar(200).Default("hola").$(),
163
+ resultado: int().Default(0).$()
164
+ });
185
165
 
186
- let response = await DB.Insert("datosPrueba", ["nombre", "data"])
187
- .Values([
188
- ["yunno", "magic wind"],
189
- ["astta", "no magic"],
190
- ])
166
+ generateTable(prueba1(), prueba1.$columns);
167
+
168
+ async function pruebaData() {
169
+ await DB.Insert(prueba1(), [prueba1.valor, prueba1.resultado])
170
+ .Values([["hola mundo", 1], ["prueba", 0]])
191
171
  .execute();
192
- console.log(response);
193
172
 
194
- let update = await DB.Update("datosPrueba")
195
- .set({ nombre: "yukio", data: "es un juego ?" })
196
- .where(eq("id", 1))
173
+ const datos = await DB.select().from(prueba1()).execute();
174
+ console.log(datos);
175
+
176
+ await DB.Update(prueba1())
177
+ .set({ valor: "actualizado", resultado: 2 })
178
+ .where(eq(prueba1.id, 1))
197
179
  .execute();
198
- console.log(update);
199
180
 
200
- let eliminados = await DB.Delete("datosPrueba")
201
- .where(ORQ("id", 3, 4, 5, 6))
181
+ await DB.Delete(prueba1())
182
+ .where(ORQ(prueba1.id, 2, 3))
202
183
  .execute();
203
- console.log(eliminados);
204
184
  }
205
185
 
206
- pruebaData().catch((e) => {
207
- console.log("error al cargar los datos");
208
- });
186
+ pruebaData().catch(console.error);
209
187
 
210
188
  ```
211
189
 
212
190
  ---
213
191
 
214
- ## 📝 Notas
215
-
216
- * Este ORM está en versión inicial.
217
- * Puedes extenderlo o contribuir con nuevas funciones.
218
-
219
- ---
220
-
221
-
192
+ ## Notas
193
+ * ORM en version inicial con enfoque de tipado y autompletado
194
+ * Compatible con **MYSQL** y **PG**
195
+ * Preparado para extenderse
222
196
 
223
- ## 📄 Licencia
197
+ ## Licencia
224
198
 
225
199
  ISC © Yukio-kayaba
226
200
 
227
- [![GitHub](https://img.shields.io/badge/GitHub-Follow%20me-black?logo=github)](https://github.com/yukio-kayaba/)
201
+ [![GitHub](https://img.shields.io/badge/GitHub-Sigue%20me-black?logo=github)](https://github.com/yukio-kayaba/)
package/dist/index.cjs CHANGED
@@ -199,6 +199,29 @@ function defineTable(tableName, columns) {
199
199
  });
200
200
  return proxy;
201
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
+ }
202
225
  async function generateTable(tabla, columns) {
203
226
  let queries = "";
204
227
  let columnDefs = [];
@@ -210,14 +233,7 @@ async function generateTable(tabla, columns) {
210
233
  if (!col.typo) {
211
234
  throw new Error(`La columna ${columnName} no tiene el tipo definido`);
212
235
  }
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 ";
236
+ sql += ValidacionTypos(col.typo, col.id, col.maxLength);
221
237
  if (col.id) {
222
238
  if (id) throw new Error(`El id no puede repetirse en 2 campos de la tabla '${tabla}'`);
223
239
  sql += tipoConexionZORMZ3691 === "mysql" ? " NOT NULL AUTO_INCREMENT " : " SERIAL ";
package/dist/index.d.cts CHANGED
@@ -31,14 +31,15 @@ declare class BDconnection {
31
31
  */
32
32
  declare function getConexion(bd: connectionDB, datos: connecionLocal | connecionRed): Promise<void>;
33
33
  declare function getRed(): BDconnection;
34
- type ColumnTypes = "varchar" | "int" | "double" | "bool" | "DateTime" | "Timestamp";
34
+ type ColumnTypes = "varchar" | "int" | "double" | "bool" | "timestamp" | "float" | "money";
35
35
  type ColumnTypeMap = {
36
36
  varchar: string;
37
37
  double: number;
38
- DateTime: Date;
39
38
  int: number;
40
39
  bool: boolean;
41
- Timestamp: Date;
40
+ timestamp: Date;
41
+ float: number;
42
+ money: number;
42
43
  };
43
44
  interface ColumnDefinition<T extends ColumnTypes = ColumnTypes> {
44
45
  typo: T;
@@ -348,7 +349,7 @@ declare const MENOR: (valor: string, valor2: string) => string;
348
349
  * @example
349
350
  *
350
351
  * FechaRegistro: {
351
- typo: "Timestamp ",
352
+ typo: "timestamp ",
352
353
  default: CURRENT_TIMESTAMP()
353
354
  },
354
355
  *
package/dist/index.d.ts CHANGED
@@ -31,14 +31,15 @@ declare class BDconnection {
31
31
  */
32
32
  declare function getConexion(bd: connectionDB, datos: connecionLocal | connecionRed): Promise<void>;
33
33
  declare function getRed(): BDconnection;
34
- type ColumnTypes = "varchar" | "int" | "double" | "bool" | "DateTime" | "Timestamp";
34
+ type ColumnTypes = "varchar" | "int" | "double" | "bool" | "timestamp" | "float" | "money";
35
35
  type ColumnTypeMap = {
36
36
  varchar: string;
37
37
  double: number;
38
- DateTime: Date;
39
38
  int: number;
40
39
  bool: boolean;
41
- Timestamp: Date;
40
+ timestamp: Date;
41
+ float: number;
42
+ money: number;
42
43
  };
43
44
  interface ColumnDefinition<T extends ColumnTypes = ColumnTypes> {
44
45
  typo: T;
@@ -348,7 +349,7 @@ declare const MENOR: (valor: string, valor2: string) => string;
348
349
  * @example
349
350
  *
350
351
  * FechaRegistro: {
351
- typo: "Timestamp ",
352
+ typo: "timestamp ",
352
353
  default: CURRENT_TIMESTAMP()
353
354
  },
354
355
  *
package/dist/index.js CHANGED
@@ -144,6 +144,29 @@ function defineTable(tableName, columns) {
144
144
  });
145
145
  return proxy;
146
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
+ }
147
170
  async function generateTable(tabla, columns) {
148
171
  let queries = "";
149
172
  let columnDefs = [];
@@ -155,14 +178,7 @@ async function generateTable(tabla, columns) {
155
178
  if (!col.typo) {
156
179
  throw new Error(`La columna ${columnName} no tiene el tipo definido`);
157
180
  }
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 ";
181
+ sql += ValidacionTypos(col.typo, col.id, col.maxLength);
166
182
  if (col.id) {
167
183
  if (id) throw new Error(`El id no puede repetirse en 2 campos de la tabla '${tabla}'`);
168
184
  sql += tipoConexionZORMZ3691 === "mysql" ? " NOT NULL AUTO_INCREMENT " : " SERIAL ";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zormz",
3
- "version": "1.2.2",
3
+ "version": "1.2.4",
4
4
  "description": "",
5
5
  "author": "",
6
6
  "license": "ISC",
@@ -13,7 +13,6 @@
13
13
  "require": "./dist/index.cjs"
14
14
  }
15
15
  },
16
- "type": "module",
17
16
  "files": [
18
17
  "dist",
19
18
  "README.md"