@zuzjs/orm 0.3.6 → 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/bin.cjs +4 -0
- package/dist/bin.d.cts +1 -0
- package/dist/bin.d.ts +0 -1
- package/dist/bin.js +2 -25
- package/dist/chunk-3TCXY5YG.js +16 -0
- package/dist/chunk-ZWZYE56D.cjs +17 -0
- package/dist/index.cjs +2 -0
- package/dist/index.d.cts +386 -0
- package/dist/index.d.ts +303 -8
- package/dist/index.js +1 -183
- package/package.json +56 -48
- package/dist/core/cli.d.ts +0 -5
- package/dist/core/cli.js +0 -78
- package/dist/core/index.d.ts +0 -8
- package/dist/core/index.js +0 -72
- package/dist/drivers/expressionBuilder.d.ts +0 -32
- package/dist/drivers/expressionBuilder.js +0 -100
- package/dist/drivers/mysql/index.d.ts +0 -39
- package/dist/drivers/mysql/index.js +0 -336
- package/dist/drivers/queryBuilder.d.ts +0 -162
- package/dist/drivers/queryBuilder.js +0 -518
- package/dist/types.d.ts +0 -104
- package/dist/types.js +0 -14
|
@@ -1,162 +0,0 @@
|
|
|
1
|
-
import { QueryResult } from "mysql2";
|
|
2
|
-
import { ObjectLiteral, Repository } from "typeorm";
|
|
3
|
-
import { QueryDeepPartialEntity } from "typeorm/query-builder/QueryPartialEntity";
|
|
4
|
-
import { PartialConditions, QueryAction } from "../types";
|
|
5
|
-
import ZormExprBuilder from "./expressionBuilder";
|
|
6
|
-
declare class ZormQueryBuilder<T extends ObjectLiteral, R = QueryResult> extends Promise<R> {
|
|
7
|
-
private repository;
|
|
8
|
-
private queryBuilder;
|
|
9
|
-
private entityAlias;
|
|
10
|
-
private action;
|
|
11
|
-
private queryValues;
|
|
12
|
-
private usePromise;
|
|
13
|
-
private whereCount;
|
|
14
|
-
private isActiveRecord;
|
|
15
|
-
private activeRecord;
|
|
16
|
-
private joinedAliases;
|
|
17
|
-
constructor(repository: Repository<T>, _action: QueryAction, _usePromise?: boolean);
|
|
18
|
-
_create(): this;
|
|
19
|
-
upsert(): this;
|
|
20
|
-
_update(): this;
|
|
21
|
-
_delete(): this;
|
|
22
|
-
_getRawQuery(): [string, any[]];
|
|
23
|
-
active(): this;
|
|
24
|
-
_saveActiveRecord(activeRecord: T): Promise<T | null>;
|
|
25
|
-
clone(): ZormQueryBuilder<T, R>;
|
|
26
|
-
/**
|
|
27
|
-
* Sets the values for an insert or update query.
|
|
28
|
-
* @param data - The data to be inserted or updated.
|
|
29
|
-
* @returns The current instance of ZormQueryBuilder.
|
|
30
|
-
*/
|
|
31
|
-
with(data: QueryDeepPartialEntity<T> | QueryDeepPartialEntity<T[]>): this;
|
|
32
|
-
/**
|
|
33
|
-
* Sets the values for an insert or update query.
|
|
34
|
-
* @param data - The data to be inserted or updated.
|
|
35
|
-
* @returns The current instance of ZormQueryBuilder.
|
|
36
|
-
*/
|
|
37
|
-
withData(data: QueryDeepPartialEntity<T> | QueryDeepPartialEntity<T[]>): this;
|
|
38
|
-
/**
|
|
39
|
-
* Specifies the fields to be selected in a select query.
|
|
40
|
-
* @param fields - The fields to be selected.
|
|
41
|
-
* @returns The current instance of ZormQueryBuilder.
|
|
42
|
-
*/
|
|
43
|
-
select(fields: (keyof T)[]): this;
|
|
44
|
-
private applyCondition;
|
|
45
|
-
/**
|
|
46
|
-
* Adds a custom expression-based WHERE clause using a fluent builder.
|
|
47
|
-
* @param fn - A callback that receives a ZormExprBuilder and returns an expression + param.
|
|
48
|
-
*/
|
|
49
|
-
expression(exprFn: (q: ZormExprBuilder<T>) => ZormExprBuilder<T>,
|
|
50
|
-
/** Add parentheses group to built expression */
|
|
51
|
-
group?: boolean): this;
|
|
52
|
-
/**
|
|
53
|
-
* Adds a WHERE condition to the query.
|
|
54
|
-
* @param condition - The condition to be added.
|
|
55
|
-
* @returns The current instance of ZormQueryBuilder.
|
|
56
|
-
*/
|
|
57
|
-
where(condition: PartialConditions<T>): this;
|
|
58
|
-
/**
|
|
59
|
-
* Adds an OR condition to the query.
|
|
60
|
-
* @param condition - The condition to be added.
|
|
61
|
-
* @returns The current instance of ZormQueryBuilder.
|
|
62
|
-
*/
|
|
63
|
-
or(condition: PartialConditions<T>): this;
|
|
64
|
-
/**
|
|
65
|
-
* Adds an ORDER BY clause to the query.
|
|
66
|
-
* @param field - The field to order by.
|
|
67
|
-
* @param direction - The direction of the order (ASC or DESC).
|
|
68
|
-
* @returns The current instance of ZormQueryBuilder.
|
|
69
|
-
*/
|
|
70
|
-
orderBy(field: keyof T, direction?: "ASC" | "DESC"): this;
|
|
71
|
-
/**
|
|
72
|
-
* Adds a LIMIT clause to the query.
|
|
73
|
-
* @param n - The maximum number of records to return.
|
|
74
|
-
* @returns The current instance of ZormQueryBuilder.
|
|
75
|
-
*/
|
|
76
|
-
limit(n: number): this;
|
|
77
|
-
/**
|
|
78
|
-
* Adds an OFFSET clause to the query.
|
|
79
|
-
* @param n - The number of records to skip.
|
|
80
|
-
* @returns The current instance of ZormQueryBuilder.
|
|
81
|
-
*/
|
|
82
|
-
offset(n: number): this;
|
|
83
|
-
/**
|
|
84
|
-
* Adds relations to be included in the query.
|
|
85
|
-
* @param relations - The relations to be included.
|
|
86
|
-
* @returns The current instance of ZormQueryBuilder.
|
|
87
|
-
*/
|
|
88
|
-
withRelation(rel: string, ...more: string[]): this;
|
|
89
|
-
/**
|
|
90
|
-
* Adds an INNER JOIN clause to the query.
|
|
91
|
-
* @param relation - The relation to join.
|
|
92
|
-
* @param alias - The alias for the joined relation.
|
|
93
|
-
* @param condition - Optional condition for the join.
|
|
94
|
-
* @returns The current instance of ZormQueryBuilder.
|
|
95
|
-
*/
|
|
96
|
-
innerJoin(relation: string, alias: string, condition?: string): this;
|
|
97
|
-
/**
|
|
98
|
-
* Adds a LEFT JOIN clause to the query.
|
|
99
|
-
* @param relation - The relation to join.
|
|
100
|
-
* @param alias - The alias for the joined relation.
|
|
101
|
-
* @param condition - Optional condition for the join.
|
|
102
|
-
* @returns The current instance of ZormQueryBuilder.
|
|
103
|
-
*/
|
|
104
|
-
leftJoin(relation: string, alias: string, condition?: string): this;
|
|
105
|
-
/**
|
|
106
|
-
* Adds a GROUP BY clause to the query.
|
|
107
|
-
* @param field - The field to group by.
|
|
108
|
-
* @returns The current instance of ZormQueryBuilder.
|
|
109
|
-
*/
|
|
110
|
-
groupBy(field: keyof T): this;
|
|
111
|
-
/**
|
|
112
|
-
* Adds a HAVING clause to the query.
|
|
113
|
-
* @param condition - The condition for the HAVING clause.
|
|
114
|
-
* @returns The current instance of ZormQueryBuilder.
|
|
115
|
-
*/
|
|
116
|
-
having(condition: string): this;
|
|
117
|
-
/**
|
|
118
|
-
* Adds an IN clause to the query.
|
|
119
|
-
* @param field - The field to check.
|
|
120
|
-
* @param values - The values for the IN clause.
|
|
121
|
-
* @returns The current instance of ZormQueryBuilder.
|
|
122
|
-
*/
|
|
123
|
-
in(field: keyof T, values: any[]): this;
|
|
124
|
-
/**
|
|
125
|
-
* Adds a LIKE condition to the query, supporting both single and multiple values.
|
|
126
|
-
* If an array is provided, it uses OR conditions between them.
|
|
127
|
-
* @param field - The field to apply the LIKE condition on.
|
|
128
|
-
* @param value - A string or an array of strings to match.
|
|
129
|
-
* @returns The current instance of ZormQueryBuilder.
|
|
130
|
-
*/
|
|
131
|
-
like(conditions: Partial<Record<keyof T, string | string[]>>, mode: "contains" | "startsWith" | "endsWith" | "exact"): this;
|
|
132
|
-
/**
|
|
133
|
-
* Adds a DISTINCT clause to the query.
|
|
134
|
-
* @returns The current instance of ZormQueryBuilder.
|
|
135
|
-
*/
|
|
136
|
-
distinct(): this;
|
|
137
|
-
count(field?: keyof T): Promise<number>;
|
|
138
|
-
sum(field: keyof T): Promise<number>;
|
|
139
|
-
avg(field: keyof T): Promise<number>;
|
|
140
|
-
min(field: keyof T): Promise<number>;
|
|
141
|
-
max(field: keyof T): Promise<number>;
|
|
142
|
-
/**
|
|
143
|
-
* Executes a raw SQL query.
|
|
144
|
-
* @param sql - The raw SQL query.
|
|
145
|
-
* @param params - Optional parameters for the query.
|
|
146
|
-
* @returns A promise that resolves with the query result.
|
|
147
|
-
*/
|
|
148
|
-
rawQuery(sql: string, params?: any): Promise<any>;
|
|
149
|
-
/**
|
|
150
|
-
* Executes the query and returns the result.
|
|
151
|
-
* @returns A promise that resolves with the query result.
|
|
152
|
-
*/
|
|
153
|
-
execute(): Promise<R>;
|
|
154
|
-
/**
|
|
155
|
-
* Handles the fulfillment and rejection of the promise.
|
|
156
|
-
* @param onfulfilled - The callback to execute when the promise is fulfilled.
|
|
157
|
-
* @param onrejected - The callback to execute when the promise is rejected.
|
|
158
|
-
* @returns A promise that resolves with the result of the callback.
|
|
159
|
-
*/
|
|
160
|
-
then<TResult1 = R, TResult2 = never>(onfulfilled?: ((value: R) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null): Promise<TResult1 | TResult2>;
|
|
161
|
-
}
|
|
162
|
-
export default ZormQueryBuilder;
|
|
@@ -1,518 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
-
};
|
|
5
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
const core_1 = require("../core");
|
|
7
|
-
const expressionBuilder_1 = __importDefault(require("./expressionBuilder"));
|
|
8
|
-
const index_js_1 = require("./mysql/index.js");
|
|
9
|
-
class ZormQueryBuilder extends Promise {
|
|
10
|
-
repository;
|
|
11
|
-
queryBuilder;
|
|
12
|
-
entityAlias;
|
|
13
|
-
action;
|
|
14
|
-
queryValues = null;
|
|
15
|
-
usePromise;
|
|
16
|
-
whereCount = 0;
|
|
17
|
-
isActiveRecord = false;
|
|
18
|
-
activeRecord;
|
|
19
|
-
joinedAliases = {};
|
|
20
|
-
// private currentWhereLogic: 'AND' | 'OR' = 'AND';
|
|
21
|
-
constructor(repository, _action, _usePromise) {
|
|
22
|
-
super(() => { }); // Required for extending Promise
|
|
23
|
-
this.repository = repository;
|
|
24
|
-
this.entityAlias = repository.metadata.tableName;
|
|
25
|
-
this.queryBuilder = repository.createQueryBuilder(this.entityAlias);
|
|
26
|
-
this.action = _action;
|
|
27
|
-
this.usePromise = _usePromise || false;
|
|
28
|
-
this.activeRecord = null;
|
|
29
|
-
// switch (_action) {
|
|
30
|
-
// case "create":
|
|
31
|
-
// case "upsert":
|
|
32
|
-
// this.queryBuilder = repository.createQueryBuilder(this.entityAlias) as InsertQueryBuilder<ObjectLiteral>;
|
|
33
|
-
// break;
|
|
34
|
-
// case "update":
|
|
35
|
-
// this.queryBuilder = repository.createQueryBuilder(this.entityAlias).update() as UpdateQueryBuilder<T>;
|
|
36
|
-
// break;
|
|
37
|
-
// case "delete":
|
|
38
|
-
// this.queryBuilder = repository.createQueryBuilder(this.entityAlias).delete() as DeleteQueryBuilder<T>;
|
|
39
|
-
// break;
|
|
40
|
-
// case "select":
|
|
41
|
-
// default:
|
|
42
|
-
// this.queryBuilder = repository.createQueryBuilder(this.entityAlias) as SelectQueryBuilder<T>;
|
|
43
|
-
// break;
|
|
44
|
-
// }
|
|
45
|
-
}
|
|
46
|
-
_create() {
|
|
47
|
-
if (this.queryValues) {
|
|
48
|
-
this.queryBuilder = this.queryBuilder
|
|
49
|
-
.insert()
|
|
50
|
-
.into(this.entityAlias)
|
|
51
|
-
.values(this.queryValues);
|
|
52
|
-
}
|
|
53
|
-
else
|
|
54
|
-
throw (0, core_1.stackTrace)(`○ Values are missing. You forgot to call .with({ key: value })`);
|
|
55
|
-
return this;
|
|
56
|
-
}
|
|
57
|
-
upsert() {
|
|
58
|
-
if (this.queryValues) {
|
|
59
|
-
this.queryBuilder = this.repository.createQueryBuilder(this.entityAlias)
|
|
60
|
-
.insert()
|
|
61
|
-
.into(this.entityAlias)
|
|
62
|
-
.values(this.queryValues)
|
|
63
|
-
.orUpdate(Object.keys(this.queryValues));
|
|
64
|
-
}
|
|
65
|
-
else
|
|
66
|
-
throw (0, core_1.stackTrace)(`○ Values are missing. You forgot to call .with({ key: value })`);
|
|
67
|
-
return this;
|
|
68
|
-
}
|
|
69
|
-
_update() {
|
|
70
|
-
if (this.queryValues) {
|
|
71
|
-
if (this.whereCount > 0) {
|
|
72
|
-
this.queryBuilder = this.queryBuilder
|
|
73
|
-
.update()
|
|
74
|
-
.set(this.queryValues);
|
|
75
|
-
}
|
|
76
|
-
else {
|
|
77
|
-
throw (0, core_1.stackTrace)(`○ Update must have at least one WHERE condition. You forgot to call .where({ condition: value })`);
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
else
|
|
81
|
-
throw (0, core_1.stackTrace)(`○ Values are missing. You forgot to call .with({ key: value })`);
|
|
82
|
-
return this;
|
|
83
|
-
}
|
|
84
|
-
_delete() {
|
|
85
|
-
if (this.whereCount > 0) {
|
|
86
|
-
this.queryBuilder = this.queryBuilder.delete();
|
|
87
|
-
}
|
|
88
|
-
else {
|
|
89
|
-
throw (0, core_1.stackTrace)(`○ Delete must have at least one WHERE condition. You forgot to call .where({ condition: value })`);
|
|
90
|
-
}
|
|
91
|
-
return this;
|
|
92
|
-
}
|
|
93
|
-
_getRawQuery() {
|
|
94
|
-
return this.queryBuilder.getQueryAndParameters();
|
|
95
|
-
}
|
|
96
|
-
active() {
|
|
97
|
-
this.isActiveRecord = true;
|
|
98
|
-
return this;
|
|
99
|
-
}
|
|
100
|
-
async _saveActiveRecord(activeRecord) {
|
|
101
|
-
// if (!this.activeRecord) throw new Error("No active record found. Use `findOne` first.");
|
|
102
|
-
return this.repository.save(activeRecord);
|
|
103
|
-
// return this
|
|
104
|
-
}
|
|
105
|
-
clone() {
|
|
106
|
-
const cloned = new ZormQueryBuilder(this.repository, this.action, this.usePromise);
|
|
107
|
-
cloned.queryBuilder = this.queryBuilder.clone(); // Deep clone of query builder
|
|
108
|
-
cloned.entityAlias = this.entityAlias;
|
|
109
|
-
cloned.queryValues = this.queryValues ? structuredClone(this.queryValues) : null;
|
|
110
|
-
cloned.whereCount = this.whereCount;
|
|
111
|
-
cloned.isActiveRecord = this.isActiveRecord;
|
|
112
|
-
cloned.activeRecord = this.activeRecord;
|
|
113
|
-
return cloned;
|
|
114
|
-
}
|
|
115
|
-
/**
|
|
116
|
-
* Sets the values for an insert or update query.
|
|
117
|
-
* @param data - The data to be inserted or updated.
|
|
118
|
-
* @returns The current instance of ZormQueryBuilder.
|
|
119
|
-
*/
|
|
120
|
-
with(data) {
|
|
121
|
-
this.queryValues = data;
|
|
122
|
-
return this;
|
|
123
|
-
}
|
|
124
|
-
/**
|
|
125
|
-
* Sets the values for an insert or update query.
|
|
126
|
-
* @param data - The data to be inserted or updated.
|
|
127
|
-
* @returns The current instance of ZormQueryBuilder.
|
|
128
|
-
*/
|
|
129
|
-
withData(data) {
|
|
130
|
-
this.queryValues = data;
|
|
131
|
-
return this;
|
|
132
|
-
}
|
|
133
|
-
/**
|
|
134
|
-
* Specifies the fields to be selected in a select query.
|
|
135
|
-
* @param fields - The fields to be selected.
|
|
136
|
-
* @returns The current instance of ZormQueryBuilder.
|
|
137
|
-
*/
|
|
138
|
-
select(fields) {
|
|
139
|
-
this.queryBuilder
|
|
140
|
-
.select(fields.map(field => `${this.entityAlias}.${String(field)}`));
|
|
141
|
-
return this;
|
|
142
|
-
}
|
|
143
|
-
applyCondition(qb, condition, type) {
|
|
144
|
-
Object.entries(condition).forEach(([key, value], index) => {
|
|
145
|
-
const paramKey = `${key}Param${index}_${this.whereCount}`; // Unique parameter name
|
|
146
|
-
let sqlOperator = "="; // Default to "="
|
|
147
|
-
if (typeof value === "string") {
|
|
148
|
-
const match = value.match(/^(!=|>=|<=|>|<|=)\s*(.+)$/); // Improved regex
|
|
149
|
-
if (match) {
|
|
150
|
-
const [, operator, rawValue] = match;
|
|
151
|
-
sqlOperator = operator; // Directly use the matched operator
|
|
152
|
-
const parsedValue = !isNaN(Number(rawValue)) ? Number(rawValue) : rawValue.trim(); // Convert to number if possible
|
|
153
|
-
qb[type](`${qb.alias}.${key} ${sqlOperator} :${paramKey}`, { [paramKey]: parsedValue });
|
|
154
|
-
return;
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
else if (typeof value === "object" && value !== null) {
|
|
158
|
-
// Support object-based conditions: { age: { gt: 18, lt: 20 } }
|
|
159
|
-
const operators = {
|
|
160
|
-
gt: ">",
|
|
161
|
-
gte: ">=",
|
|
162
|
-
lt: "<",
|
|
163
|
-
lte: "<=",
|
|
164
|
-
ne: "!=",
|
|
165
|
-
eq: "="
|
|
166
|
-
};
|
|
167
|
-
Object.entries(value).forEach(([opKey, opValue]) => {
|
|
168
|
-
if (operators[opKey]) {
|
|
169
|
-
const paramKey = `${key}Param_${opKey}_${this.whereCount++}`; // Unique param key
|
|
170
|
-
qb[type](`${qb.alias}.${key} ${operators[opKey]} :${paramKey}`, { [paramKey]: opValue });
|
|
171
|
-
}
|
|
172
|
-
});
|
|
173
|
-
return; // Prevent default equality case for objects
|
|
174
|
-
}
|
|
175
|
-
// Default case (normal equality condition)
|
|
176
|
-
qb[type](`${this.entityAlias}.${key} = :${paramKey}`, { [paramKey]: value });
|
|
177
|
-
this.whereCount++;
|
|
178
|
-
});
|
|
179
|
-
}
|
|
180
|
-
/**
|
|
181
|
-
* Adds a custom expression-based WHERE clause using a fluent builder.
|
|
182
|
-
* @param fn - A callback that receives a ZormExprBuilder and returns an expression + param.
|
|
183
|
-
*/
|
|
184
|
-
expression(exprFn,
|
|
185
|
-
/** Add parentheses group to built expression */
|
|
186
|
-
group = true) {
|
|
187
|
-
const qb = this.queryBuilder;
|
|
188
|
-
const result = exprFn(new expressionBuilder_1.default(this.entityAlias));
|
|
189
|
-
const _expression = result.buildExpression();
|
|
190
|
-
qb.andWhere(group ? `(${_expression})` : _expression, result.buildParams());
|
|
191
|
-
this.whereCount++;
|
|
192
|
-
return this;
|
|
193
|
-
}
|
|
194
|
-
// expression(exprFn: (q: ZormExprBuilder<T>) => ZormExprBuilder<T>): this {
|
|
195
|
-
// const qb = this.queryBuilder as SelectQueryBuilder<T> | UpdateQueryBuilder<T>;
|
|
196
|
-
// const result = exprFn(new ZormExprBuilder<T>(this.entityAlias));
|
|
197
|
-
// // const expression =
|
|
198
|
-
// qb.andWhere(result.buildExpression(), result.buildParams());
|
|
199
|
-
// // if ('expression' in result && 'param' in result) {
|
|
200
|
-
// // } else {
|
|
201
|
-
// // // fallback if only expression was built without .equals()
|
|
202
|
-
// // }
|
|
203
|
-
// // qb.andWhere(result.buildExpression(), result.buildParams());
|
|
204
|
-
// this.whereCount++;
|
|
205
|
-
// return this;
|
|
206
|
-
// }
|
|
207
|
-
/**
|
|
208
|
-
* Adds a WHERE condition to the query.
|
|
209
|
-
* @param condition - The condition to be added.
|
|
210
|
-
* @returns The current instance of ZormQueryBuilder.
|
|
211
|
-
*/
|
|
212
|
-
where(condition) {
|
|
213
|
-
const qb = this.queryBuilder;
|
|
214
|
-
this.applyCondition(qb, condition, `andWhere`);
|
|
215
|
-
return this;
|
|
216
|
-
}
|
|
217
|
-
/**
|
|
218
|
-
* Adds an OR condition to the query.
|
|
219
|
-
* @param condition - The condition to be added.
|
|
220
|
-
* @returns The current instance of ZormQueryBuilder.
|
|
221
|
-
*/
|
|
222
|
-
or(condition) {
|
|
223
|
-
const qb = this.queryBuilder;
|
|
224
|
-
this.applyCondition(qb, condition, `orWhere`);
|
|
225
|
-
return this;
|
|
226
|
-
}
|
|
227
|
-
/**
|
|
228
|
-
* Adds an ORDER BY clause to the query.
|
|
229
|
-
* @param field - The field to order by.
|
|
230
|
-
* @param direction - The direction of the order (ASC or DESC).
|
|
231
|
-
* @returns The current instance of ZormQueryBuilder.
|
|
232
|
-
*/
|
|
233
|
-
orderBy(field, direction = "ASC") {
|
|
234
|
-
this.queryBuilder.orderBy(`${this.entityAlias}.${String(field)}`, direction);
|
|
235
|
-
return this;
|
|
236
|
-
}
|
|
237
|
-
/**
|
|
238
|
-
* Adds a LIMIT clause to the query.
|
|
239
|
-
* @param n - The maximum number of records to return.
|
|
240
|
-
* @returns The current instance of ZormQueryBuilder.
|
|
241
|
-
*/
|
|
242
|
-
limit(n) {
|
|
243
|
-
this.queryBuilder.limit(n);
|
|
244
|
-
return this;
|
|
245
|
-
}
|
|
246
|
-
/**
|
|
247
|
-
* Adds an OFFSET clause to the query.
|
|
248
|
-
* @param n - The number of records to skip.
|
|
249
|
-
* @returns The current instance of ZormQueryBuilder.
|
|
250
|
-
*/
|
|
251
|
-
offset(n) {
|
|
252
|
-
this.queryBuilder.offset(n);
|
|
253
|
-
return this;
|
|
254
|
-
}
|
|
255
|
-
/**
|
|
256
|
-
* Adds relations to be included in the query.
|
|
257
|
-
* @param relations - The relations to be included.
|
|
258
|
-
* @returns The current instance of ZormQueryBuilder.
|
|
259
|
-
*/
|
|
260
|
-
withRelation(rel, ...more) {
|
|
261
|
-
[rel, ...more].forEach(relation => this.queryBuilder.leftJoinAndSelect(`${this.entityAlias}.${relation}`, relation));
|
|
262
|
-
return this;
|
|
263
|
-
}
|
|
264
|
-
/**
|
|
265
|
-
* Adds an INNER JOIN clause to the query.
|
|
266
|
-
* @param relation - The relation to join.
|
|
267
|
-
* @param alias - The alias for the joined relation.
|
|
268
|
-
* @param condition - Optional condition for the join.
|
|
269
|
-
* @returns The current instance of ZormQueryBuilder.
|
|
270
|
-
*/
|
|
271
|
-
innerJoin(relation, alias, condition) {
|
|
272
|
-
if (condition) {
|
|
273
|
-
this.queryBuilder.innerJoin(`${this.entityAlias}.${relation}`, alias, condition);
|
|
274
|
-
}
|
|
275
|
-
else {
|
|
276
|
-
this.queryBuilder.innerJoin(`${this.entityAlias}.${relation}`, alias);
|
|
277
|
-
}
|
|
278
|
-
this.joinedAliases[alias] = relation;
|
|
279
|
-
return this;
|
|
280
|
-
}
|
|
281
|
-
/**
|
|
282
|
-
* Adds a LEFT JOIN clause to the query.
|
|
283
|
-
* @param relation - The relation to join.
|
|
284
|
-
* @param alias - The alias for the joined relation.
|
|
285
|
-
* @param condition - Optional condition for the join.
|
|
286
|
-
* @returns The current instance of ZormQueryBuilder.
|
|
287
|
-
*/
|
|
288
|
-
leftJoin(relation, alias, condition) {
|
|
289
|
-
if (condition) {
|
|
290
|
-
this.queryBuilder.leftJoin(`${this.entityAlias}.${relation}`, alias, condition);
|
|
291
|
-
}
|
|
292
|
-
else {
|
|
293
|
-
this.queryBuilder.leftJoin(`${this.entityAlias}.${relation}`, alias);
|
|
294
|
-
}
|
|
295
|
-
this.joinedAliases[alias] = relation;
|
|
296
|
-
return this;
|
|
297
|
-
}
|
|
298
|
-
/**
|
|
299
|
-
* Adds a GROUP BY clause to the query.
|
|
300
|
-
* @param field - The field to group by.
|
|
301
|
-
* @returns The current instance of ZormQueryBuilder.
|
|
302
|
-
*/
|
|
303
|
-
groupBy(field) {
|
|
304
|
-
this.queryBuilder.groupBy(`${this.entityAlias}.${String(field)}`);
|
|
305
|
-
return this;
|
|
306
|
-
}
|
|
307
|
-
/**
|
|
308
|
-
* Adds a HAVING clause to the query.
|
|
309
|
-
* @param condition - The condition for the HAVING clause.
|
|
310
|
-
* @returns The current instance of ZormQueryBuilder.
|
|
311
|
-
*/
|
|
312
|
-
having(condition) {
|
|
313
|
-
this.queryBuilder.having(condition);
|
|
314
|
-
return this;
|
|
315
|
-
}
|
|
316
|
-
/**
|
|
317
|
-
* Adds an IN clause to the query.
|
|
318
|
-
* @param field - The field to check.
|
|
319
|
-
* @param values - The values for the IN clause.
|
|
320
|
-
* @returns The current instance of ZormQueryBuilder.
|
|
321
|
-
*/
|
|
322
|
-
in(field, values) {
|
|
323
|
-
this.queryBuilder.andWhere(`${this.entityAlias}.${String(field)} IN (:...values)`, { values });
|
|
324
|
-
this.whereCount++;
|
|
325
|
-
return this;
|
|
326
|
-
}
|
|
327
|
-
/**
|
|
328
|
-
* Adds a LIKE condition to the query, supporting both single and multiple values.
|
|
329
|
-
* If an array is provided, it uses OR conditions between them.
|
|
330
|
-
* @param field - The field to apply the LIKE condition on.
|
|
331
|
-
* @param value - A string or an array of strings to match.
|
|
332
|
-
* @returns The current instance of ZormQueryBuilder.
|
|
333
|
-
*/
|
|
334
|
-
like(conditions, mode) {
|
|
335
|
-
if (!conditions || Object.keys(conditions).length === 0)
|
|
336
|
-
return this;
|
|
337
|
-
const qb = this.queryBuilder;
|
|
338
|
-
const orConditions = [];
|
|
339
|
-
const params = {};
|
|
340
|
-
Object.entries(conditions).forEach(([field, value]) => {
|
|
341
|
-
const values = Array.isArray(value) ? value : [value];
|
|
342
|
-
const fieldConditions = [];
|
|
343
|
-
values.forEach((val, index) => {
|
|
344
|
-
const paramKey = `${field}LikeParam${index}_${this.whereCount}`;
|
|
345
|
-
fieldConditions.push(`${this.entityAlias}.${String(field)} LIKE :${paramKey}`);
|
|
346
|
-
let formattedVal = val;
|
|
347
|
-
switch (mode || "contains") {
|
|
348
|
-
case "startsWith":
|
|
349
|
-
formattedVal = `${val}%`;
|
|
350
|
-
break;
|
|
351
|
-
case "endsWith":
|
|
352
|
-
formattedVal = `%${val}`;
|
|
353
|
-
break;
|
|
354
|
-
case "exact":
|
|
355
|
-
formattedVal = `${val}`;
|
|
356
|
-
break;
|
|
357
|
-
case "contains":
|
|
358
|
-
default:
|
|
359
|
-
formattedVal = `%${val}%`;
|
|
360
|
-
}
|
|
361
|
-
params[paramKey] = formattedVal; // Directly use the value (supports %xyz% pattern)
|
|
362
|
-
});
|
|
363
|
-
if (fieldConditions.length > 0) {
|
|
364
|
-
orConditions.push(`(${fieldConditions.join(" OR ")})`);
|
|
365
|
-
}
|
|
366
|
-
});
|
|
367
|
-
if (orConditions.length > 0) {
|
|
368
|
-
qb.andWhere(`(${orConditions.join(" OR ")})`, params);
|
|
369
|
-
this.whereCount++;
|
|
370
|
-
}
|
|
371
|
-
return this;
|
|
372
|
-
}
|
|
373
|
-
/**
|
|
374
|
-
* Adds a DISTINCT clause to the query.
|
|
375
|
-
* @returns The current instance of ZormQueryBuilder.
|
|
376
|
-
*/
|
|
377
|
-
distinct() {
|
|
378
|
-
this.queryBuilder.distinct(true);
|
|
379
|
-
return this;
|
|
380
|
-
}
|
|
381
|
-
async count(field) {
|
|
382
|
-
if (field) {
|
|
383
|
-
this.queryBuilder.select(`COUNT(${field})`);
|
|
384
|
-
}
|
|
385
|
-
return await this.queryBuilder.getCount();
|
|
386
|
-
}
|
|
387
|
-
async sum(field) {
|
|
388
|
-
const result = await this.queryBuilder.select(`SUM(${this.entityAlias}.${String(field)})`, "sum").getRawOne();
|
|
389
|
-
return result.sum || 0;
|
|
390
|
-
}
|
|
391
|
-
async avg(field) {
|
|
392
|
-
const result = await this.queryBuilder.select(`AVG(${this.entityAlias}.${String(field)})`, "avg").getRawOne();
|
|
393
|
-
return result.avg || 0;
|
|
394
|
-
}
|
|
395
|
-
async min(field) {
|
|
396
|
-
const result = await this.queryBuilder.select(`MIN(${this.entityAlias}.${String(field)})`, "min").getRawOne();
|
|
397
|
-
return result.min || 0;
|
|
398
|
-
}
|
|
399
|
-
async max(field) {
|
|
400
|
-
const result = await this.queryBuilder.select(`MAX(${this.entityAlias}.${String(field)})`, "max").getRawOne();
|
|
401
|
-
return result.max || 0;
|
|
402
|
-
}
|
|
403
|
-
/**
|
|
404
|
-
* Executes a raw SQL query.
|
|
405
|
-
* @param sql - The raw SQL query.
|
|
406
|
-
* @param params - Optional parameters for the query.
|
|
407
|
-
* @returns A promise that resolves with the query result.
|
|
408
|
-
*/
|
|
409
|
-
async rawQuery(sql, params) {
|
|
410
|
-
return await this.repository.query(sql, params);
|
|
411
|
-
}
|
|
412
|
-
/**
|
|
413
|
-
* Executes the query and returns the result.
|
|
414
|
-
* @returns A promise that resolves with the query result.
|
|
415
|
-
*/
|
|
416
|
-
async execute() {
|
|
417
|
-
const removedMethods = {};
|
|
418
|
-
Object.keys(Object.prototype).forEach((method) => {
|
|
419
|
-
if (Object.prototype.hasOwnProperty.call(Object.prototype, method)) {
|
|
420
|
-
removedMethods[method] = Object.prototype[method];
|
|
421
|
-
delete Object.prototype[method];
|
|
422
|
-
}
|
|
423
|
-
});
|
|
424
|
-
try {
|
|
425
|
-
switch (this.action) {
|
|
426
|
-
case "upsert":
|
|
427
|
-
case "create":
|
|
428
|
-
this._create();
|
|
429
|
-
const _create = await this.queryBuilder.execute();
|
|
430
|
-
return {
|
|
431
|
-
created: true,
|
|
432
|
-
id: _create.raw.insertId,
|
|
433
|
-
record: _create.generatedMaps[0],
|
|
434
|
-
records: _create.generatedMaps.length > 1 ? _create.generatedMaps : null
|
|
435
|
-
};
|
|
436
|
-
case "update":
|
|
437
|
-
this._update();
|
|
438
|
-
const _updateQuery = this.queryBuilder;
|
|
439
|
-
const _update = await _updateQuery.execute();
|
|
440
|
-
const whereQuery = _updateQuery.getQuery().split("WHERE")[1]?.trim(); // Get the WHERE clause
|
|
441
|
-
const _get = this.repository
|
|
442
|
-
.createQueryBuilder(this.entityAlias)
|
|
443
|
-
.where(whereQuery, _updateQuery.getParameters()); // Use the same parameters
|
|
444
|
-
// console.log(_updateQuery.getQueryAndParameters())
|
|
445
|
-
const _updated = await _get.getMany();
|
|
446
|
-
return {
|
|
447
|
-
updated: _update.affected ? _update.affected > 0 : false,
|
|
448
|
-
record: _updated[0],
|
|
449
|
-
records: _updated.length > 1 ? _updated : []
|
|
450
|
-
};
|
|
451
|
-
case "delete":
|
|
452
|
-
this._delete();
|
|
453
|
-
const _delete = await this.queryBuilder.execute();
|
|
454
|
-
return {
|
|
455
|
-
deleted: _delete.affected ? _delete.affected > 0 : false,
|
|
456
|
-
count: _delete.affected || 0
|
|
457
|
-
};
|
|
458
|
-
case "select":
|
|
459
|
-
default:
|
|
460
|
-
const _select = await this.queryBuilder.getMany();
|
|
461
|
-
const _result = {
|
|
462
|
-
hasRows: _select.length > 0,
|
|
463
|
-
count: _select.length,
|
|
464
|
-
row: _select.length > 0 ? _select[0] : null,
|
|
465
|
-
rows: _select.length == 1 ? [_select[0]] : _select,
|
|
466
|
-
};
|
|
467
|
-
if (this.isActiveRecord) {
|
|
468
|
-
_result.save = () => this._saveActiveRecord(_select[0]);
|
|
469
|
-
}
|
|
470
|
-
return _result;
|
|
471
|
-
}
|
|
472
|
-
}
|
|
473
|
-
catch (err) {
|
|
474
|
-
const _e = err;
|
|
475
|
-
const error = {
|
|
476
|
-
code: index_js_1.MySQLErrorMap[_e.code] || _e.code,
|
|
477
|
-
message: _e.message,
|
|
478
|
-
query: _e.query, // The SQL query that caused the error
|
|
479
|
-
values: _e.parameters, // Parameters used in the query
|
|
480
|
-
};
|
|
481
|
-
switch (this.action) {
|
|
482
|
-
case "upsert":
|
|
483
|
-
case "create":
|
|
484
|
-
const _c = {
|
|
485
|
-
created: false,
|
|
486
|
-
id: 0,
|
|
487
|
-
error
|
|
488
|
-
};
|
|
489
|
-
return this.usePromise ? Promise.reject(_c) : _c;
|
|
490
|
-
case "update":
|
|
491
|
-
const _u = { updated: false, error };
|
|
492
|
-
return this.usePromise ? Promise.reject(_u) : _u;
|
|
493
|
-
case "delete":
|
|
494
|
-
const _d = { deleted: false, error };
|
|
495
|
-
return this.usePromise ? Promise.reject(_d) : _d;
|
|
496
|
-
case "select":
|
|
497
|
-
default:
|
|
498
|
-
const _s = { hasRows: false, count: 0, row: null, rows: [], error };
|
|
499
|
-
return this.usePromise ? Promise.reject(_s) : _s;
|
|
500
|
-
}
|
|
501
|
-
}
|
|
502
|
-
finally {
|
|
503
|
-
Object.entries(removedMethods).forEach(([method, fn]) => {
|
|
504
|
-
Object.prototype[method] = fn;
|
|
505
|
-
});
|
|
506
|
-
}
|
|
507
|
-
}
|
|
508
|
-
/**
|
|
509
|
-
* Handles the fulfillment and rejection of the promise.
|
|
510
|
-
* @param onfulfilled - The callback to execute when the promise is fulfilled.
|
|
511
|
-
* @param onrejected - The callback to execute when the promise is rejected.
|
|
512
|
-
* @returns A promise that resolves with the result of the callback.
|
|
513
|
-
*/
|
|
514
|
-
then(onfulfilled, onrejected) {
|
|
515
|
-
return this.execute().then(onfulfilled, onrejected);
|
|
516
|
-
}
|
|
517
|
-
}
|
|
518
|
-
exports.default = ZormQueryBuilder;
|