@zuzjs/orm 0.3.7 → 0.3.8

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/dist/index.d.ts CHANGED
@@ -1,7 +1,299 @@
1
- import "reflect-metadata";
2
- import { EntitySchema, EntityTarget, MixedList, ObjectLiteral, Repository } from "typeorm";
3
- import ZormQueryBuilder from "./drivers/queryBuilder.js";
4
- import { DeleteQueryResult, InsertQueryResult, SelectQueryResult, UpdateQueryResult } from "./types.js";
1
+ import { ObjectLiteral, Repository, MixedList, EntitySchema, EntityTarget } from 'typeorm';
2
+ export { BaseEntity, Column, Entity, JoinColumn, ManyToMany, ManyToOne, OneToMany, OneToOne, PrimaryColumn, PrimaryGeneratedColumn } from 'typeorm';
3
+ import { QueryResult as QueryResult$1 } from 'mysql2';
4
+ import { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';
5
+
6
+ type dynamicObject = {
7
+ [x: string]: any;
8
+ };
9
+ interface ModelGenerator {
10
+ generate: () => void;
11
+ connection: () => ConnectionDetails;
12
+ mapColumns: (sqlType: string) => void;
13
+ }
14
+ type ConnectionDetails = {
15
+ host: string;
16
+ port: string | number;
17
+ user: string;
18
+ password: string;
19
+ database: string;
20
+ params: dynamicObject;
21
+ };
22
+ type QueryAction = "create" | "upsert" | "select" | "update" | "delete";
23
+ type QueryResult = InsertQueryResult | SelectQueryResult | UpdateQueryResult | DeleteQueryResult;
24
+ /**
25
+ * Defines supported comparison operators for filtering queries.
26
+ * Enables IntelliSense support in `.where()` conditions.
27
+ *
28
+ * @template T The type of the value being compared (e.g., number, string, Date).
29
+ */
30
+ type WhereOperators<T> = {
31
+ /**
32
+ * Greater than (`>`) operator.
33
+ *
34
+ * @example
35
+ * query.where({ age: { gt: 18 } }) // WHERE age > 18
36
+ */
37
+ gt?: T;
38
+ /**
39
+ * Greater than or equal to (`>=`) operator.
40
+ *
41
+ * @example
42
+ * query.where({ price: { gte: 100 } }) // WHERE price >= 100
43
+ */
44
+ gte?: T;
45
+ /**
46
+ * Less than (`<`) operator.
47
+ *
48
+ * @example
49
+ * query.where({ age: { lt: 30 } }) // WHERE age < 30
50
+ */
51
+ lt?: T;
52
+ /**
53
+ * Less than or equal to (`<=`) operator.
54
+ *
55
+ * @example
56
+ * query.where({ date: { lte: '2024-01-01' } }) // WHERE date <= '2024-01-01'
57
+ */
58
+ lte?: T;
59
+ /**
60
+ * Not equal (`!=`) operator.
61
+ *
62
+ * @example
63
+ * query.where({ status: { ne: 'inactive' } }) // WHERE status != 'inactive'
64
+ */
65
+ ne?: T;
66
+ /**
67
+ * Equal (`=`) operator.
68
+ * This is typically unnecessary since `.where({ key: value })` already handles equality.
69
+ *
70
+ * @example
71
+ * query.where({ id: { eq: 1 } }) // WHERE id = 1
72
+ */
73
+ eq?: T;
74
+ };
75
+ type PartialConditions<T> = Partial<Record<keyof T, string | number | boolean | WhereOperators<any>>>;
76
+ type QueryError = {
77
+ code: number | string;
78
+ message: string;
79
+ query: string;
80
+ values: string[];
81
+ };
82
+ type InsertQueryResult = {
83
+ created: boolean;
84
+ id?: number;
85
+ record?: ObjectLiteral;
86
+ records?: ObjectLiteral[];
87
+ error?: QueryError;
88
+ };
89
+ type SelectQueryResult = {
90
+ hasRows: boolean;
91
+ count?: number;
92
+ row?: any;
93
+ rows?: any[];
94
+ error?: QueryError;
95
+ save?: () => void;
96
+ };
97
+ type UpdateQueryResult = {
98
+ updated: boolean;
99
+ record?: ObjectLiteral;
100
+ records?: ObjectLiteral[];
101
+ error?: QueryError;
102
+ };
103
+ type DeleteQueryResult = {
104
+ deleted: boolean;
105
+ count: number;
106
+ error?: QueryError;
107
+ };
108
+
109
+ declare class ZormExprBuilder<T extends ObjectLiteral> {
110
+ private _parts;
111
+ private _params;
112
+ private _paramIdx;
113
+ private _alias;
114
+ private static globalParamIdx;
115
+ constructor(alias?: string, parent?: {
116
+ params: Record<string, any>;
117
+ idx: number;
118
+ });
119
+ field(col: keyof T | string): this;
120
+ equals(value: any): this;
121
+ append(extra: string): this;
122
+ wrap(wrapper: (expr: string) => string): this;
123
+ exists(sub: (q: ZormExprBuilder<T>) => ZormExprBuilder<T>): this;
124
+ select(expr: string): this;
125
+ from(table: string, alias: string): this;
126
+ where(cond: Record<string, any>): this;
127
+ or(): this;
128
+ group(): this;
129
+ fromUnixTime(): this;
130
+ date(): this;
131
+ substring(column: keyof T | string, delimiter: string, index: number): this;
132
+ toExpression(): {
133
+ expression: string;
134
+ param: Record<string, any>;
135
+ };
136
+ buildExpression(): string;
137
+ buildParams(): Record<string, any>;
138
+ }
139
+
140
+ declare class ZormQueryBuilder<T extends ObjectLiteral, R = QueryResult$1> extends Promise<R> {
141
+ private repository;
142
+ private queryBuilder;
143
+ private entityAlias;
144
+ private action;
145
+ private queryValues;
146
+ private usePromise;
147
+ private whereCount;
148
+ private isActiveRecord;
149
+ private activeRecord;
150
+ private joinedAliases;
151
+ constructor(repository: Repository<T>, _action: QueryAction, _usePromise?: boolean);
152
+ _create(): this;
153
+ upsert(): this;
154
+ _update(): this;
155
+ _delete(): this;
156
+ _getRawQuery(): [string, any[]];
157
+ active(): this;
158
+ _saveActiveRecord(activeRecord: T): Promise<T | null>;
159
+ clone(): ZormQueryBuilder<T, R>;
160
+ /**
161
+ * Sets the values for an insert or update query.
162
+ * @param data - The data to be inserted or updated.
163
+ * @returns The current instance of ZormQueryBuilder.
164
+ */
165
+ with(data: QueryDeepPartialEntity<T> | QueryDeepPartialEntity<T[]>): this;
166
+ /**
167
+ * Sets the values for an insert or update query.
168
+ * @param data - The data to be inserted or updated.
169
+ * @returns The current instance of ZormQueryBuilder.
170
+ */
171
+ withData(data: QueryDeepPartialEntity<T> | QueryDeepPartialEntity<T[]>): this;
172
+ /**
173
+ * Specifies the fields to be selected in a select query.
174
+ * @param fields - The fields to be selected.
175
+ * @returns The current instance of ZormQueryBuilder.
176
+ */
177
+ select(fields: (keyof T)[]): this;
178
+ private applyCondition;
179
+ /**
180
+ * Adds a custom expression-based WHERE clause using a fluent builder.
181
+ * @param fn - A callback that receives a ZormExprBuilder and returns an expression + param.
182
+ */
183
+ expression(exprFn: (q: ZormExprBuilder<T>) => ZormExprBuilder<T>,
184
+ /** Add parentheses group to built expression */
185
+ group?: boolean): this;
186
+ /**
187
+ * Adds a WHERE condition to the query.
188
+ * @param condition - The condition to be added.
189
+ * @returns The current instance of ZormQueryBuilder.
190
+ */
191
+ where(condition: PartialConditions<T>): this;
192
+ /**
193
+ * Adds an OR condition to the query.
194
+ * @param condition - The condition to be added.
195
+ * @returns The current instance of ZormQueryBuilder.
196
+ */
197
+ or(condition: PartialConditions<T>): this;
198
+ /**
199
+ * Adds an ORDER BY clause to the query.
200
+ * @param field - The field to order by.
201
+ * @param direction - The direction of the order (ASC or DESC).
202
+ * @returns The current instance of ZormQueryBuilder.
203
+ */
204
+ orderBy(field: keyof T, direction?: "ASC" | "DESC"): this;
205
+ /**
206
+ * Adds a LIMIT clause to the query.
207
+ * @param n - The maximum number of records to return.
208
+ * @returns The current instance of ZormQueryBuilder.
209
+ */
210
+ limit(n: number): this;
211
+ /**
212
+ * Adds an OFFSET clause to the query.
213
+ * @param n - The number of records to skip.
214
+ * @returns The current instance of ZormQueryBuilder.
215
+ */
216
+ offset(n: number): this;
217
+ /**
218
+ * Adds relations to be included in the query.
219
+ * @param relations - The relations to be included.
220
+ * @returns The current instance of ZormQueryBuilder.
221
+ */
222
+ withRelation(rel: string, ...more: string[]): this;
223
+ /**
224
+ * Adds an INNER JOIN clause to the query.
225
+ * @param relation - The relation to join.
226
+ * @param alias - The alias for the joined relation.
227
+ * @param condition - Optional condition for the join.
228
+ * @returns The current instance of ZormQueryBuilder.
229
+ */
230
+ innerJoin(relation: string, alias: string, condition?: string): this;
231
+ /**
232
+ * Adds a LEFT JOIN clause to the query.
233
+ * @param relation - The relation to join.
234
+ * @param alias - The alias for the joined relation.
235
+ * @param condition - Optional condition for the join.
236
+ * @returns The current instance of ZormQueryBuilder.
237
+ */
238
+ leftJoin(relation: string, alias: string, condition?: string): this;
239
+ /**
240
+ * Adds a GROUP BY clause to the query.
241
+ * @param field - The field to group by.
242
+ * @returns The current instance of ZormQueryBuilder.
243
+ */
244
+ groupBy(field: keyof T): this;
245
+ /**
246
+ * Adds a HAVING clause to the query.
247
+ * @param condition - The condition for the HAVING clause.
248
+ * @returns The current instance of ZormQueryBuilder.
249
+ */
250
+ having(condition: string): this;
251
+ /**
252
+ * Adds an IN clause to the query.
253
+ * @param field - The field to check.
254
+ * @param values - The values for the IN clause.
255
+ * @returns The current instance of ZormQueryBuilder.
256
+ */
257
+ in(field: keyof T, values: any[]): this;
258
+ /**
259
+ * Adds a LIKE condition to the query, supporting both single and multiple values.
260
+ * If an array is provided, it uses OR conditions between them.
261
+ * @param field - The field to apply the LIKE condition on.
262
+ * @param value - A string or an array of strings to match.
263
+ * @returns The current instance of ZormQueryBuilder.
264
+ */
265
+ like(conditions: Partial<Record<keyof T, string | string[]>>, mode: "contains" | "startsWith" | "endsWith" | "exact"): this;
266
+ /**
267
+ * Adds a DISTINCT clause to the query.
268
+ * @returns The current instance of ZormQueryBuilder.
269
+ */
270
+ distinct(): this;
271
+ count(field?: keyof T): Promise<number>;
272
+ sum(field: keyof T): Promise<number>;
273
+ avg(field: keyof T): Promise<number>;
274
+ min(field: keyof T): Promise<number>;
275
+ max(field: keyof T): Promise<number>;
276
+ /**
277
+ * Executes a raw SQL query.
278
+ * @param sql - The raw SQL query.
279
+ * @param params - Optional parameters for the query.
280
+ * @returns A promise that resolves with the query result.
281
+ */
282
+ rawQuery(sql: string, params?: any): Promise<any>;
283
+ /**
284
+ * Executes the query and returns the result.
285
+ * @returns A promise that resolves with the query result.
286
+ */
287
+ execute(): Promise<R>;
288
+ /**
289
+ * Handles the fulfillment and rejection of the promise.
290
+ * @param onfulfilled - The callback to execute when the promise is fulfilled.
291
+ * @param onrejected - The callback to execute when the promise is rejected.
292
+ * @returns A promise that resolves with the result of the callback.
293
+ */
294
+ then<TResult1 = R, TResult2 = never>(onfulfilled?: ((value: R) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null): Promise<TResult1 | TResult2>;
295
+ }
296
+
5
297
  /**
6
298
  * Zorm is a lightweight ORM wrapper around TypeORM with support for MySQL.
7
299
  */
@@ -90,5 +382,5 @@ declare class Zorm {
90
382
  */
91
383
  delete<T extends ObjectLiteral>(entity: EntityTarget<T>): ZormQueryBuilder<T, DeleteQueryResult>;
92
384
  }
93
- export default Zorm;
94
- export * from "./types.js";
385
+
386
+ export { type ConnectionDetails, type DeleteQueryResult, type InsertQueryResult, type ModelGenerator, type PartialConditions, type QueryAction, type QueryError, type QueryResult, type SelectQueryResult, type UpdateQueryResult, type WhereOperators, Zorm as default, type dynamicObject };
package/dist/index.js CHANGED
@@ -1,232 +1 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- var __importDefault = (this && this.__importDefault) || function (mod) {
17
- return (mod && mod.__esModule) ? mod : { "default": mod };
18
- };
19
- Object.defineProperty(exports, "__esModule", { value: true });
20
- const path_1 = __importDefault(require("path"));
21
- const picocolors_1 = __importDefault(require("picocolors"));
22
- require("reflect-metadata");
23
- const typeorm_1 = require("typeorm");
24
- const index_js_1 = require("./core/index.js");
25
- const index_js_2 = require("./drivers/mysql/index.js");
26
- const queryBuilder_js_1 = __importDefault(require("./drivers/queryBuilder.js"));
27
- /**
28
- * Zorm is a lightweight ORM wrapper around TypeORM with support for MySQL.
29
- */
30
- class Zorm {
31
- /**
32
- * Singleton instance of Zorm.
33
- * @private
34
- */
35
- static instance;
36
- /**
37
- * TypeORM DataSource instance.
38
- * @private
39
- */
40
- dataSource;
41
- /**
42
- * Flag to track if the connection is initialized.
43
- * @private
44
- */
45
- initialized = false;
46
- /**
47
- * Determines whether to use Promises for queries.
48
- * @private
49
- */
50
- usePromise = false;
51
- _init;
52
- /**
53
- * Private constructor to enforce singleton pattern.
54
- * @param {string} connectionString - The database connection string.
55
- * @param {string | null} [entitiesPath] - Path to the entities directory.
56
- * @param {boolean} [usePromise] - Whether to use Promises for queries.
57
- * @private
58
- */
59
- constructor(connectionString, entities, entitiesPath, usePromise) {
60
- const _dist = entitiesPath || path_1.default.join(`src`, `zorm`);
61
- const dist = path_1.default.join(process.cwd(), _dist);
62
- const _checkDist = (0, index_js_1.checkDirectory)(dist, false);
63
- this.usePromise = usePromise || false;
64
- if (!_checkDist.access) {
65
- console.log(picocolors_1.default.red(`○ ${_checkDist.message}`));
66
- return;
67
- }
68
- if (connectionString.startsWith(`mysql`)) {
69
- const driver = new index_js_2.MySqlDriver(decodeURIComponent(connectionString));
70
- const conn = driver.connection();
71
- this.dataSource = new typeorm_1.DataSource({
72
- type: "mysql",
73
- username: conn.user,
74
- password: conn.password,
75
- host: conn.host,
76
- port: Number(conn.port),
77
- database: conn.database,
78
- entities: entities || []
79
- });
80
- this._init = this.dataSource.initialize.bind(this.dataSource);
81
- }
82
- else {
83
- console.log(`Only MySQL is supported for now`);
84
- process.exit(1);
85
- }
86
- }
87
- /**
88
- * Returns the singleton instance of Zorm.
89
- * @param {string} connectionString - The database connection string.
90
- * @param {string | null} [entitiesPath] - Path to the entities directory.
91
- * @param {boolean} [usePromise] - Whether to use Promises for queries.
92
- * @returns {Zorm} The singleton instance of Zorm.
93
- */
94
- static get(connectionString, entities, entitiesPath, usePromise) {
95
- if (!Zorm.instance) {
96
- Zorm.instance = new Zorm(connectionString, entities, entitiesPath, usePromise);
97
- }
98
- return Zorm.instance;
99
- }
100
- /**
101
- * Connects to the database and initializes entities.
102
- * @param {MixedList<string | Function | EntitySchema<any>>} entities - List of entity schemas.
103
- * @returns {Promise<void>} Resolves when the connection is initialized.
104
- */
105
- async connect(entities) {
106
- if (!this.initialized) {
107
- try {
108
- if (entities && !this.dataSource.options.entities?.length) {
109
- this.dataSource.setOptions({ entities });
110
- }
111
- await this._init();
112
- this.initialized = true;
113
- console.log(picocolors_1.default.green("○ Zorm is connected"));
114
- }
115
- catch (e) {
116
- console.log(picocolors_1.default.red("○ Error while connecting to your MySQL Server with following error:"), e);
117
- }
118
- }
119
- }
120
- whenReady() {
121
- if (this.initialized)
122
- return this;
123
- const handler = {
124
- get: (target, prop) => {
125
- if (prop === 'then')
126
- return undefined;
127
- const value = target[prop];
128
- if (typeof value === 'function') {
129
- return (...args) => {
130
- const result = value.apply(target, args);
131
- if (result && result.constructor.name === 'ZormQueryBuilder') {
132
- return this.wrapQueryBuilder(result);
133
- }
134
- this._init().then(() => result);
135
- };
136
- }
137
- return value;
138
- }
139
- };
140
- return new Proxy(this, handler);
141
- }
142
- wrapQueryBuilder(qb) {
143
- const handler = {
144
- get: (target, prop) => {
145
- if (prop === 'then')
146
- return undefined;
147
- const value = target[prop];
148
- if (typeof value === 'function') {
149
- return (...args) => {
150
- const result = value.apply(target, args);
151
- // Chain: if returns new QB, wrap it
152
- if (result && result.constructor.name === 'ZormQueryBuilder') {
153
- return this.wrapQueryBuilder(result);
154
- }
155
- // Final: return Promise
156
- return this._init().then(() => result);
157
- };
158
- }
159
- return value;
160
- }
161
- };
162
- return new Proxy(qb, handler);
163
- }
164
- /**
165
- * Returns the appropriate QueryBuilder based on the database type.
166
- * @param {EntityTarget<T>} entity - The entity target.
167
- * @param {QueryAction} action - The query action type.
168
- * @returns {ZormQueryBuilder<T, R>} Query builder instance.
169
- * @private
170
- */
171
- getQueryBuilder(entity, action) {
172
- const repository = this.getRepository(entity);
173
- switch (this.dataSource.options.type) {
174
- case "mysql":
175
- case "mariadb":
176
- case "postgres":
177
- case "sqlite":
178
- case "mssql":
179
- case "oracle":
180
- return new queryBuilder_js_1.default(repository, action, this.usePromise);
181
- case "mongodb":
182
- throw new Error("MongoDB does not support QueryBuilder. Use repository methods instead.");
183
- default:
184
- throw new Error(`Unsupported database type: ${this.dataSource.options.type}`);
185
- }
186
- }
187
- /**
188
- * Retrieves the repository for a given entity.
189
- * @param {EntityTarget<T>} entity - The entity target.
190
- * @returns {Repository<T>} The repository instance.
191
- */
192
- getRepository(entity) {
193
- return this.dataSource.getRepository(entity);
194
- }
195
- /**
196
- * Creates a new record in the database.
197
- * @param {EntityTarget<T>} entity - The entity target.
198
- * @returns {ZormQueryBuilder<T, InsertQueryResult>} The query builder instance.
199
- */
200
- create(entity) {
201
- return this.getQueryBuilder(entity, "create");
202
- }
203
- /**
204
- * Finds records in the database.
205
- * @param {EntityTarget<T>} entity - The entity target.
206
- * @returns {ZormQueryBuilder<T, SelectQueryResult>} The query builder instance.
207
- */
208
- find(entity) {
209
- return this.getQueryBuilder(entity, "select");
210
- }
211
- // upsert<T extends ObjectLiteral>(entity: EntityTarget<T>): ZormQueryBuilder<T, InsertQueryResult> {
212
- // return this.getQueryBuilder(entity, "upsert");
213
- // }
214
- /**
215
- * Updates records in the database.
216
- * @param {EntityTarget<T>} entity - The entity target.
217
- * @returns {ZormQueryBuilder<T, UpdateQueryResult>} The query builder instance.
218
- */
219
- update(entity) {
220
- return this.getQueryBuilder(entity, "update");
221
- }
222
- /**
223
- * Deletes records from the database.
224
- * @param {EntityTarget<T>} entity - The entity target.
225
- * @returns {ZormQueryBuilder<T, DeleteQueryResult>} The query builder instance.
226
- */
227
- delete(entity) {
228
- return this.getQueryBuilder(entity, "delete");
229
- }
230
- }
231
- exports.default = Zorm;
232
- __exportStar(require("./types.js"), exports);
1
+ import {b,e,c,d}from'./chunk-3TCXY5YG.js';import S from'path';import Q from'picocolors';import'reflect-metadata';import {DataSource}from'typeorm';export{BaseEntity,Column,Entity,JoinColumn,ManyToMany,ManyToOne,OneToMany,OneToOne,PrimaryColumn,PrimaryGeneratedColumn}from'typeorm';var m=class c{_parts=[];_params={};_paramIdx=0;_alias;static globalParamIdx=0;constructor(e,t){this._alias=e?`${e}.`:"",this._paramIdx=t?t.idx:0,this._params=t?t.params:{};}field(e){return this._parts.push(`${this._alias}${String(e)}`),this}equals(e){let t=`p${this._paramIdx++}`;return this.append(` = :${t}`),this._params[t]=e,this}append(e){if(this._parts.length===0)throw new Error("Cannot append to empty expression");return this._parts[this._parts.length-1]+=e,this}wrap(e){if(this._parts.length===0)throw new Error("Cannot wrap empty expression");return this._parts[this._parts.length-1]=e(this._parts[this._parts.length-1]),this}exists(e){let t=new c(void 0,{params:this._params,idx:this._paramIdx});return e(t),this._parts.push(`EXISTS (${t.buildExpression()})`),this._paramIdx=t._paramIdx,this}select(e){return this._parts.push(`SELECT ${e}`),this}from(e,t){return this._parts.push(`FROM ${e} ${t}`),this._alias=t,this}where(e){let t=[];for(let[r,i]of Object.entries(e)){let s=`p${this._paramIdx++}`;t.push(`${r} = :${s}`),this._params[s]=i;}return this._parts.push(`WHERE ${t.join(" AND ")}`),this}or(){return this._parts.push("OR"),this}group(){return this.wrap(e=>`(${e})`)}fromUnixTime(){return this.wrap(e=>`FROM_UNIXTIME(${e})`),this}date(){return this.wrap(e=>`DATE(${e})`),this}substring(e,t,r){return this._parts=[`SUBSTRING_INDEX(${this._alias}${String(e)}, '${t}', ${r})`],this}toExpression(){return {expression:this._parts.join(" "),param:this._params}}buildExpression(){return this.toExpression().expression}buildParams(){return this.toExpression().param}},$=m;var f=class c$1 extends Promise{repository;queryBuilder;entityAlias;action;queryValues=null;usePromise;whereCount=0;isActiveRecord=false;activeRecord;joinedAliases={};constructor(e,t,r){super(()=>{}),this.repository=e,this.entityAlias=e.metadata.tableName,this.queryBuilder=e.createQueryBuilder(this.entityAlias),this.action=t,this.usePromise=r||false,this.activeRecord=null;}_create(){if(this.queryValues)this.queryBuilder=this.queryBuilder.insert().into(this.entityAlias).values(this.queryValues);else throw c("\u25CB Values are missing. You forgot to call .with({ key: value })");return this}upsert(){if(this.queryValues)this.queryBuilder=this.repository.createQueryBuilder(this.entityAlias).insert().into(this.entityAlias).values(this.queryValues).orUpdate(Object.keys(this.queryValues));else throw c("\u25CB Values are missing. You forgot to call .with({ key: value })");return this}_update(){if(this.queryValues)if(this.whereCount>0)this.queryBuilder=this.queryBuilder.update().set(this.queryValues);else throw c("\u25CB Update must have at least one WHERE condition. You forgot to call .where({ condition: value })");else throw c("\u25CB Values are missing. You forgot to call .with({ key: value })");return this}_delete(){if(this.whereCount>0)this.queryBuilder=this.queryBuilder.delete();else throw c("\u25CB Delete must have at least one WHERE condition. You forgot to call .where({ condition: value })");return this}_getRawQuery(){return this.queryBuilder.getQueryAndParameters()}active(){return this.isActiveRecord=true,this}async _saveActiveRecord(e){return this.repository.save(e)}clone(){let e=new c$1(this.repository,this.action,this.usePromise);return e.queryBuilder=this.queryBuilder.clone(),e.entityAlias=this.entityAlias,e.queryValues=this.queryValues?structuredClone(this.queryValues):null,e.whereCount=this.whereCount,e.isActiveRecord=this.isActiveRecord,e.activeRecord=this.activeRecord,e}with(e){return this.queryValues=e,this}withData(e){return this.queryValues=e,this}select(e){return this.queryBuilder.select(e.map(t=>`${this.entityAlias}.${String(t)}`)),this}applyCondition(e,t,r){Object.entries(t).forEach(([i,s],u)=>{let a=`${i}Param${u}_${this.whereCount}`,l="=";if(typeof s=="string"){let n=s.match(/^(!=|>=|<=|>|<|=)\s*(.+)$/);if(n){let[,o,h]=n;l=o;let y=isNaN(Number(h))?h.trim():Number(h);e[r](`${e.alias}.${i} ${l} :${a}`,{[a]:y});return}}else if(typeof s=="object"&&s!==null){let n={gt:">",gte:">=",lt:"<",lte:"<=",ne:"!=",eq:"="};Object.entries(s).forEach(([o,h])=>{if(n[o]){let y=`${i}Param_${o}_${this.whereCount++}`;e[r](`${e.alias}.${i} ${n[o]} :${y}`,{[y]:h});}});return}e[r](`${this.entityAlias}.${i} = :${a}`,{[a]:s}),this.whereCount++;});}expression(e,t=true){let r=this.queryBuilder,i=e(new $(this.entityAlias)),s=i.buildExpression();return r.andWhere(t?`(${s})`:s,i.buildParams()),this.whereCount++,this}where(e){let t=this.queryBuilder;return this.applyCondition(t,e,"andWhere"),this}or(e){let t=this.queryBuilder;return this.applyCondition(t,e,"orWhere"),this}orderBy(e,t="ASC"){return this.queryBuilder.orderBy(`${this.entityAlias}.${String(e)}`,t),this}limit(e){return this.queryBuilder.limit(e),this}offset(e){return this.queryBuilder.offset(e),this}withRelation(e,...t){return [e,...t].forEach(r=>this.queryBuilder.leftJoinAndSelect(`${this.entityAlias}.${r}`,r)),this}innerJoin(e,t,r){return r?this.queryBuilder.innerJoin(`${this.entityAlias}.${e}`,t,r):this.queryBuilder.innerJoin(`${this.entityAlias}.${e}`,t),this.joinedAliases[t]=e,this}leftJoin(e,t,r){return r?this.queryBuilder.leftJoin(`${this.entityAlias}.${e}`,t,r):this.queryBuilder.leftJoin(`${this.entityAlias}.${e}`,t),this.joinedAliases[t]=e,this}groupBy(e){return this.queryBuilder.groupBy(`${this.entityAlias}.${String(e)}`),this}having(e){return this.queryBuilder.having(e),this}in(e,t){return this.queryBuilder.andWhere(`${this.entityAlias}.${String(e)} IN (:...values)`,{values:t}),this.whereCount++,this}like(e,t){if(!e||Object.keys(e).length===0)return this;let r=this.queryBuilder,i=[],s={};return Object.entries(e).forEach(([u,a])=>{let l=Array.isArray(a)?a:[a],n=[];l.forEach((o,h)=>{let y=`${u}LikeParam${h}_${this.whereCount}`;n.push(`${this.entityAlias}.${String(u)} LIKE :${y}`);let p=o;switch(t||"contains"){case "startsWith":p=`${o}%`;break;case "endsWith":p=`%${o}`;break;case "exact":p=`${o}`;break;default:p=`%${o}%`;}s[y]=p;}),n.length>0&&i.push(`(${n.join(" OR ")})`);}),i.length>0&&(r.andWhere(`(${i.join(" OR ")})`,s),this.whereCount++),this}distinct(){return this.queryBuilder.distinct(true),this}async count(e){return e&&this.queryBuilder.select(`COUNT(${e})`),await this.queryBuilder.getCount()}async sum(e){return (await this.queryBuilder.select(`SUM(${this.entityAlias}.${String(e)})`,"sum").getRawOne()).sum||0}async avg(e){return (await this.queryBuilder.select(`AVG(${this.entityAlias}.${String(e)})`,"avg").getRawOne()).avg||0}async min(e){return (await this.queryBuilder.select(`MIN(${this.entityAlias}.${String(e)})`,"min").getRawOne()).min||0}async max(e){return (await this.queryBuilder.select(`MAX(${this.entityAlias}.${String(e)})`,"max").getRawOne()).max||0}async rawQuery(e,t){return await this.repository.query(e,t)}async execute(){let e={};Object.keys(Object.prototype).forEach(t=>{Object.prototype.hasOwnProperty.call(Object.prototype,t)&&(e[t]=Object.prototype[t],delete Object.prototype[t]);});try{switch(this.action){case "upsert":case "create":this._create();let t=await this.queryBuilder.execute();return {created:!0,id:t.raw.insertId,record:t.generatedMaps[0],records:t.generatedMaps.length>1?t.generatedMaps:null};case "update":this._update();let r=this.queryBuilder,i=await r.execute(),s=r.getQuery().split("WHERE")[1]?.trim(),a=await this.repository.createQueryBuilder(this.entityAlias).where(s,r.getParameters()).getMany();return {updated:i.affected?i.affected>0:!1,record:a[0],records:a.length>1?a:[]};case "delete":this._delete();let l=await this.queryBuilder.execute();return {deleted:l.affected?l.affected>0:!1,count:l.affected||0};default:let n=await this.queryBuilder.getMany(),o={hasRows:n.length>0,count:n.length,row:n.length>0?n[0]:null,rows:n.length==1?[n[0]]:n};return this.isActiveRecord&&(o.save=()=>this._saveActiveRecord(n[0])),o}}catch(t){let r=t,i={code:d[r.code]||r.code,message:r.message,query:r.query,values:r.parameters};switch(this.action){case "upsert":case "create":let s={created:false,id:0,error:i};return this.usePromise?Promise.reject(s):s;case "update":let u={updated:false,error:i};return this.usePromise?Promise.reject(u):u;case "delete":let a={deleted:false,error:i};return this.usePromise?Promise.reject(a):a;default:let l={hasRows:false,count:0,row:null,rows:[],error:i};return this.usePromise?Promise.reject(l):l}}finally{Object.entries(e).forEach(([t,r])=>{Object.prototype[t]=r;});}}then(e,t){return this.execute().then(e,t)}},x=f;var B=class c{static instance;dataSource;initialized=false;usePromise=false;_init;constructor(e$1,t,r,i){let s=r||S.join("src","zorm"),u=S.join(process.cwd(),s),a=b(u,false);if(this.usePromise=i||false,!a.access){console.log(Q.red(`\u25CB ${a.message}`));return}if(e$1.startsWith("mysql")){let n=new e(decodeURIComponent(e$1)).connection();this.dataSource=new DataSource({type:"mysql",username:n.user,password:n.password,host:n.host,port:Number(n.port),database:n.database,entities:t||[]}),this._init=this.dataSource.initialize.bind(this.dataSource);}else console.log("Only MySQL is supported for now"),process.exit(1);}static get(e,t,r,i){return c.instance||(c.instance=new c(e,t,r,i)),c.instance}async connect(e){if(!this.initialized)try{e&&!this.dataSource.options.entities?.length&&this.dataSource.setOptions({entities:e}),await this._init(),this.initialized=!0,console.log(Q.green("\u25CB Zorm is connected"));}catch(t){console.log(Q.red("\u25CB Error while connecting to your MySQL Server with following error:"),t);}}whenReady(){if(this.initialized)return this;let e={get:(t,r)=>{if(r==="then")return;let i=t[r];return typeof i=="function"?(...s)=>{let u=i.apply(t,s);if(u&&u.constructor.name==="ZormQueryBuilder")return this.wrapQueryBuilder(u);this._init().then(()=>u);}:i}};return new Proxy(this,e)}wrapQueryBuilder(e){let t={get:(r,i)=>{if(i==="then")return;let s=r[i];return typeof s=="function"?(...u)=>{let a=s.apply(r,u);return a&&a.constructor.name==="ZormQueryBuilder"?this.wrapQueryBuilder(a):this._init().then(()=>a)}:s}};return new Proxy(e,t)}getQueryBuilder(e,t){let r=this.getRepository(e);switch(this.dataSource.options.type){case "mysql":case "mariadb":case "postgres":case "sqlite":case "mssql":case "oracle":return new x(r,t,this.usePromise);case "mongodb":throw new Error("MongoDB does not support QueryBuilder. Use repository methods instead.");default:throw new Error(`Unsupported database type: ${this.dataSource.options.type}`)}}getRepository(e){return this.dataSource.getRepository(e)}create(e){return this.getQueryBuilder(e,"create")}find(e){return this.getQueryBuilder(e,"select")}update(e){return this.getQueryBuilder(e,"update")}delete(e){return this.getQueryBuilder(e,"delete")}},ae=B;export{ae as default};
package/package.json CHANGED
@@ -1,51 +1,59 @@
1
1
  {
2
- "name": "@zuzjs/orm",
3
- "version": "0.3.7",
4
- "keywords": [
5
- "orm",
6
- "zuz",
7
- "zuz.js",
8
- "zuz orm",
9
- "zuzjs"
10
- ],
11
- "description": "ZuzJS ORM Library",
12
- "author": "Zuz.js Team <support@zuz.com.pk>",
13
- "license": "MIT",
14
- "type": "commonjs",
15
- "main": "dist/index.js",
16
- "bin": {
17
- "zorm": "dist/bin.js"
18
- },
19
- "exports": {
20
- ".": "./dist/index.js"
21
- },
22
- "files": [
23
- "dist"
24
- ],
25
- "scripts": {
26
- "dev": "tsc -d -w -p tsconfig.json"
27
- },
28
- "engines": {
29
- "node": ">=18.17.0"
30
- },
31
- "sideEffects": ["reflect-metadata"],
32
- "dependencies": {
33
- "@types/md5": "^2.3.5",
34
- "commander": "14.0.0",
35
- "md5": "^2.3.0",
36
- "mysql2": "3.14.1",
37
- "nanoid": "5.1.5",
38
- "picocolors": "^1.1.1",
39
- "reflect-metadata": "^0.2.2",
40
- "typeorm": "^0.3.25"
41
- },
42
- "devDependencies": {
43
- "husky": "^9.1.7",
44
- "ts-node": "^10.9.2",
45
- "typescript": "^5.8.3"
46
- },
47
- "peerDependencies": {
48
- "reflect-metadata": "^0.2.2",
49
- "typeorm": "^0.3.25"
2
+ "name": "@zuzjs/orm",
3
+ "version": "0.3.8",
4
+ "description": "ZuzJS ORM Library",
5
+ "keywords": [
6
+ "orm",
7
+ "zuz",
8
+ "zuz.js",
9
+ "zuz orm",
10
+ "zuzjs"
11
+ ],
12
+ "homepage": "https://orm.zuz.com.pk",
13
+ "bugs": {
14
+ "url": "https://github.com/zuzpk/zorm/issues"
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/zuzpk/zorm.git"
19
+ },
20
+ "author": "Zuz.js Team <support@zuz.com.pk>",
21
+ "license": "MIT",
22
+ "type": "module",
23
+ "main": "./dist/index.cjs",
24
+ "module": "./dist/index.js",
25
+ "types": "./dist/index.d.ts",
26
+ "bin": {
27
+ "zorm": "./dist/bin.cjs"
28
+ },
29
+ "exports": {
30
+ ".": {
31
+ "types": "./dist/index.d.ts",
32
+ "import": "./dist/index.js",
33
+ "require": "./dist/index.cjs"
50
34
  }
35
+ },
36
+ "files": [
37
+ "dist"
38
+ ],
39
+ "engines": {
40
+ "node": ">=18.17.0"
41
+ },
42
+ "sideEffects": [
43
+ "reflect-metadata"
44
+ ],
45
+ "dependencies": {
46
+ "@types/md5": "^2.3.6",
47
+ "commander": "14.0.3",
48
+ "md5": "^2.3.0",
49
+ "mysql2": "3.17.1",
50
+ "nanoid": "5.1.6",
51
+ "picocolors": "^1.1.1",
52
+ "reflect-metadata": "^0.2.2",
53
+ "typeorm": "^0.3.28"
54
+ },
55
+ "peerDependencies": {
56
+ "reflect-metadata": "^0.2.2",
57
+ "typeorm": "^0.3.28"
58
+ }
51
59
  }
@@ -1,5 +0,0 @@
1
- export declare const buildEntities: (connection: string, dist?: string) => void;
2
- /**
3
- * Pull using DATABASE_URL from .env in project directory
4
- **/
5
- export declare const Pull: () => void;