forked from typeorm/typeorm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueryExpressionMap.ts
More file actions
353 lines (295 loc) · 11.2 KB
/
QueryExpressionMap.ts
File metadata and controls
353 lines (295 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
import {Alias} from "./Alias";
import {ObjectLiteral} from "../common/ObjectLiteral";
import {OrderByCondition} from "../find-options/OrderByCondition";
import {JoinAttribute} from "./JoinAttribute";
import {RelationIdAttribute} from "./relation-id/RelationIdAttribute";
import {RelationCountAttribute} from "./relation-count/RelationCountAttribute";
import {Connection} from "../connection/Connection";
import {EntityMetadata} from "../metadata/EntityMetadata";
import {SelectQuery} from "./SelectQuery";
import {ColumnMetadata} from "../metadata/ColumnMetadata";
import {RelationMetadata} from "../metadata/RelationMetadata";
import {QueryBuilder} from "./QueryBuilder";
/**
* Contains all properties of the QueryBuilder that needs to be build a final query.
*/
export class QueryExpressionMap {
// -------------------------------------------------------------------------
// Public Properties
// -------------------------------------------------------------------------
/**
* Indicates if QueryBuilder used to select entities and not a raw results.
*/
queryEntity: boolean = false;
/**
* Main alias is a main selection object selected by QueryBuilder.
*/
mainAlias?: Alias;
/**
* All aliases (including main alias) used in the query.
*/
aliases: Alias[] = [];
/**
* Represents query type. QueryBuilder is able to build SELECT, UPDATE and DELETE queries.
*/
queryType: "select"|"update"|"delete"|"insert"|"relation" = "select";
/**
* Data needs to be SELECT-ed.
*/
selects: SelectQuery[] = [];
/**
* FROM-s to be selected.
*/
// froms: { target: string, alias: string }[] = [];
/**
* If update query was used, it needs "update set" - properties which will be updated by this query.
* If insert query was used, it needs "insert set" - values that needs to be inserted.
*/
valuesSet?: ObjectLiteral|ObjectLiteral[];
/**
* Optional returning (or output) clause for insert, update or delete queries.
*/
returning: string = "";
/**
* JOIN queries.
*/
joinAttributes: JoinAttribute[] = [];
/**
* RelationId queries.
*/
relationIdAttributes: RelationIdAttribute[] = [];
/**
* Relation count queries.
*/
relationCountAttributes: RelationCountAttribute[] = [];
/**
* WHERE queries.
*/
wheres: { type: "simple"|"and"|"or", condition: string }[] = [];
/**
* HAVING queries.
*/
havings: { type: "simple"|"and"|"or", condition: string }[] = [];
/**
* ORDER BY queries.
*/
orderBys: OrderByCondition = {};
/**
* GROUP BY queries.
*/
groupBys: string[] = [];
/**
* LIMIT query.
*/
limit?: number;
/**
* OFFSET query.
*/
offset?: number;
/**
* Number of rows to skip of result using pagination.
*/
skip?: number;
/**
* Number of rows to take using pagination.
*/
take?: number;
/**
* Locking mode.
*/
lockMode?: "optimistic"|"pessimistic_read"|"pessimistic_write";
/**
* Current version of the entity, used for locking.
*/
lockVersion?: number|Date;
/**
* Parameters used to be escaped in final query.
*/
parameters: ObjectLiteral = {};
/**
* Indicates if alias, table names and column names will be ecaped by driver, or not.
*
* todo: rename to isQuotingDisabled, also think if it should be named "escaping"
*/
disableEscaping: boolean = true;
/**
* todo: needs more information.
*/
ignoreParentTablesJoins: boolean = false;
/**
* Indicates if virtual columns should be included in entity result.
*
* todo: what to do with it? is it properly used? what about persistence?
*/
enableRelationIdValues: boolean = false;
/**
* Extra where condition appended to the end of original where conditions with AND keyword.
* Original condition will be wrapped into brackets.
*/
extraAppendedAndWhereCondition: string = "";
/**
* Indicates if query builder creates a subquery.
*/
subQuery: boolean = false;
/**
* If QueryBuilder was created in a subquery mode then its parent QueryBuilder (who created subquery) will be stored here.
*/
parentQueryBuilder: QueryBuilder<any>;
/**
* Indicates if property names are prefixed with alias names during property replacement.
* By default this is enabled, however we need this because aliases are not supported in UPDATE and DELETE queries,
* but user can use them in WHERE expressions.
*/
aliasNamePrefixingEnabled: boolean = true;
/**
* Indicates if query result cache is enabled or not.
*/
cache: boolean = false;
/**
* Time in milliseconds in which cache will expire.
* If not set then global caching time will be used.
*/
cacheDuration: number;
/**
* Cache id.
* Used to identifier your cache queries.
*/
cacheId: string;
/**
* Property path of relation to work with.
* Used in relational query builder.
*/
relationPropertyPath: string;
/**
* Entity (target) which relations will be updated.
*/
of: any|any[];
// -------------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------------
constructor(protected connection: Connection) {
}
// -------------------------------------------------------------------------
// Accessors
// -------------------------------------------------------------------------
/**
* Get all ORDER BY queries - if order by is specified by user then it uses them,
* otherwise it uses default entity order by if it was set.
*/
get allOrderBys() {
if (!Object.keys(this.orderBys).length && this.mainAlias!.hasMetadata) {
const entityOrderBy = this.mainAlias!.metadata.orderBy || {};
return Object.keys(entityOrderBy).reduce((orderBy, key) => {
orderBy[this.mainAlias!.name + "." + key] = entityOrderBy[key];
return orderBy;
}, {} as OrderByCondition);
}
return this.orderBys;
}
// -------------------------------------------------------------------------
// Public Methods
// -------------------------------------------------------------------------
/**
* Creates a main alias and adds it to the current expression map.
*/
setMainAlias(alias: Alias): Alias {
// if main alias is already set then remove it from the array
if (this.mainAlias)
this.aliases.splice(this.aliases.indexOf(this.mainAlias));
// set new main alias
this.mainAlias = alias;
return alias;
}
/**
* Creates a new alias and adds it to the current expression map.
*/
createAlias(options: { type: "from"|"select"|"join"|"other", name?: string, target?: Function|string, tableName?: string, subQuery?: string, metadata?: EntityMetadata }): Alias {
let aliasName = options.name;
if (!aliasName && options.tableName)
aliasName = options.tableName;
if (!aliasName && options.target instanceof Function)
aliasName = options.target.name;
if (!aliasName && typeof options.target === "string")
aliasName = options.target;
const alias = new Alias();
alias.type = options.type;
if (aliasName)
alias.name = aliasName;
if (options.metadata)
alias.metadata = options.metadata;
if (options.target && !alias.hasMetadata)
alias.metadata = this.connection.getMetadata(options.target);
if (options.tableName)
alias.tableName = options.tableName;
if (options.subQuery)
alias.subQuery = options.subQuery;
this.aliases.push(alias);
return alias;
}
/**
* Finds alias with the given name.
* If alias was not found it throw an exception.
*/
findAliasByName(aliasName: string): Alias {
const alias = this.aliases.find(alias => alias.name === aliasName);
if (!alias)
throw new Error(`"${aliasName}" alias was not found. Maybe you forgot to join it?`);
return alias;
}
findColumnByAliasExpression(aliasExpression: string): ColumnMetadata|undefined {
const [aliasName, propertyPath] = aliasExpression.split(".");
const alias = this.findAliasByName(aliasName);
return alias.metadata.findColumnWithPropertyName(propertyPath);
}
/**
* Gets relation metadata of the relation this query builder works with.
*
* todo: add proper exceptions
*/
get relationMetadata(): RelationMetadata {
if (!this.mainAlias)
throw new Error(`Entity to work with is not specified!`); // todo: better message
const relationMetadata = this.mainAlias.metadata.findRelationWithPropertyPath(this.relationPropertyPath);
if (!relationMetadata)
throw new Error(`Relation ${this.relationPropertyPath} was not found in entity ${this.mainAlias.name}`); // todo: better message
return relationMetadata;
}
/**
* Copies all properties of the current QueryExpressionMap into a new one.
* Useful when QueryBuilder needs to create a copy of itself.
*/
clone(): QueryExpressionMap {
const map = new QueryExpressionMap(this.connection);
map.queryType = this.queryType;
map.selects = this.selects.map(select => select);
this.aliases.forEach(alias => map.aliases.push(new Alias(alias)));
map.mainAlias = this.mainAlias;
map.valuesSet = this.valuesSet;
map.joinAttributes = this.joinAttributes.map(join => new JoinAttribute(this.connection, this, join));
map.relationIdAttributes = this.relationIdAttributes.map(relationId => new RelationIdAttribute(this, relationId));
map.relationCountAttributes = this.relationCountAttributes.map(relationCount => new RelationCountAttribute(this, relationCount));
map.wheres = this.wheres.map(where => ({ ...where }));
map.havings = this.havings.map(having => ({ ...having }));
map.orderBys = Object.assign({}, this.orderBys);
map.groupBys = this.groupBys.map(groupBy => groupBy);
map.limit = this.limit;
map.offset = this.offset;
map.skip = this.skip;
map.take = this.take;
map.lockMode = this.lockMode;
map.lockVersion = this.lockVersion;
map.parameters = Object.assign({}, this.parameters);
map.disableEscaping = this.disableEscaping;
map.ignoreParentTablesJoins = this.ignoreParentTablesJoins;
map.enableRelationIdValues = this.enableRelationIdValues;
map.extraAppendedAndWhereCondition = this.extraAppendedAndWhereCondition;
map.subQuery = this.subQuery;
map.aliasNamePrefixingEnabled = this.aliasNamePrefixingEnabled;
map.cache = this.cache;
map.cacheId = this.cacheId;
map.cacheDuration = this.cacheDuration;
map.relationPropertyPath = this.relationPropertyPath;
map.of = this.of;
return map;
}
}