-
Notifications
You must be signed in to change notification settings - Fork 0
/
query.js
660 lines (589 loc) · 16.1 KB
/
query.js
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
var co = require('co');
var extend = require('extend-merge').extend;
var merge = require('extend-merge').merge;
var Model = require('chaos-orm').Model;
function isEmpty(value) {
if (!value) {
return true;
}
for (var i in value) {
return false;
}
if (Array.isArray(value) && value.length) {
return false;
}
return true;
}
/**
* The Query wrapper.
*/
class Query {
/**
* Gets/sets classes dependencies.
*
* @param Object classes The classes dependencies to set or none to get it.
* @return mixed The classes dependencies.
*/
static classes(classes) {
if (arguments.length) {
this._classes = extend({}, this._classes, classes);
}
return this._classes;
}
/**
* Creates a new record object with default values.
*
* @param array config Possible options are:
* - `'model'` _Function_ : A model class.
* - `'schema'` _Object_ : Alternatively a schema instance can be provided instead of the model.
* - `'query'` _Object_ : The query.
*/
constructor(config) {
var defaults = {
model: undefined,
schema: undefined,
query: {}
};
config = extend({}, defaults, config);
if (config.model) {
this._model = config.model;
this._schema = this._model.definition();
} else {
this._schema = config.schema;
}
/**
* Count the number of identical aliases in a query for building unique aliases.
*
* @var Object
*/
this._aliasCounter = {};
/**
* Map beetween relation paths and corresponding aliases.
*
* @var Object
*/
this._aliases = {};
/**
* Map beetween generated aliases and corresponding schema.
*
* @var Object
*/
this._schemas = {};
/**
* The relations to include.
*
* @var Array
*/
this._embed = [];
/**
* Some conditions over some relations.
*
* @var Array
*/
this._has = [];
/**
* Pagination.
*
* @var Array
*/
this._page = [];
/**
* Default fetch options.
*
* @var Object
*/
this._fetchOptions = {};
var schema = this.schema();
/**
* The select statement instance.
*
* @var Function
*/
this._statement = schema.connection().dialect().statement('select');
var source = schema.source();
var from = {};
from[source] = this.alias('', schema);
this.statement().from(from);
for (var key in config.query) {
if (typeof this[key] !== 'function') {
throw new Error("Invalid option `'" + key + "'` as query options.");
}
this[key](config.query[key]);
}
}
/**
* Gets the schema.
*
* @return Function Returns the schema.
*/
schema() {
if (!this._schema) {
throw new Error("Error, missing schema for this query.");
}
return this._schema;
}
/**
* Gets the model.
*
* @return Function Returns the model.
*/
model() {
return this._model;
}
/**
* Gets the query statement.
*
* @return Function Returns a connection instance.
*/
statement() {
return this._statement;
}
/**
* Get/set default fetch options.
*
* @param Object|null $fetchOptions The fetching options.
* @return Object.
*/
fetchOptions(fetchOptions) {
if (arguments.length) {
this._fetchOptions = fetchOptions;
return this;
}
return Object.assign({ return: 'entity' }, this._fetchOptions);
}
/**
* Executes the query and returns the result.
*
* @param Object Options The fetching options.
* @return Promise A Promise.
*/
get(options) {
return co(function*(){
options = extend({}, this.fetchOptions(), options);
this._applyHas();
this._applyLimit();
var schema = this.schema();
var statement = this.statement();
var allFields = !statement.data('fields').length;
if (allFields) {
var star = {};
star[this.alias()] = ['*'];
statement.fields([star]);
}
if (statement.data('joins').length) {
this.group(schema.key());
}
var collection;
var ret = options['return'];
var cursor = yield schema.connection().query(statement.toString(this._schemas, this._aliases));
var key = schema.key();
switch (ret) {
case 'entity':
var model = this.model();
if (!model) {
throw new Error("Missing model for this query, set `'return'` to `'object'` to get row data.");
}
collection = model.create([], {
type: 'set',
exists: true
});
if (this.statement().data('limit')) {
var count = this.count();
collection.meta({ count: yield count });
}
for (var record of cursor) {
collection.push(model.create(record, {
exists: record[key] !== undefined ? true : null
}));
}
break;
case 'array':
case 'object':
collection = [];
for (var record of cursor) {
collection.push(extend({}, record));
}
break;
default:
throw new Error("Invalid `'" + options['return'] + "'` mode as `'return'` value");
break;
}
return schema.embed(collection, this._embed, { fetchOptions: options });
}.bind(this));
}
/**
* Alias for `get()`
*
* @return object An iterator instance.
*/
all(options) {
return this.get(options);
}
/**
* Executes the query and returns the first result only.
*
* @return object An entity instance.
*/
first(options) {
return co(function*() {
var result = yield this.get(options);
return result.length ? (Array.isArray(result) ? result[0] : result.get(0)) : null;
}.bind(this));
}
/**
* Executes the query and returns the count number.
*
* @return integer The number of rows in result.
*/
count() {
return co(function*() {
this._applyHas();
var statement = this.statement();
var counter = this.schema().connection().dialect().statement('select');
var primaryKey = statement.dialect().name(this.alias() + '.' + this.schema().key());
counter.fields({ ':plain': 'COUNT(DISTINCT ' + primaryKey + ') as count' });
counter.data('from', statement.data('from'));
counter.data('joins', statement.data('joins'));
counter.data('where', statement.data('where'));
counter.data('group', statement.data('group'));
counter.data('having', statement.data('having'));
var cursor = yield this.schema().connection().query('SELECT SUM(count) FROM(' + counter.toString(this._schemas, this._aliases) + ') x');
var result = cursor.next();
var key = Object.keys(result)[0]
return Number.parseInt(result[key]);
}.bind(this));
}
/**
* Adds some fields to the query
*
* @param mixed fields The fields.
* @return Function Returns `this`.
*/
fields(fields) {
fields = Array.isArray(fields) && arguments.length === 1 ? fields : Array.prototype.slice.call(arguments);
var schema = this.schema();
for (var value of fields) {
if (typeof value === 'string' && schema.has(value)) {
var aliased = {};
aliased[this.alias()] = [value]
this.statement().fields(aliased);
} else {
this.statement().fields(value);
}
}
return this;
}
/**
* Adds some where conditions to the query
*
* @param mixed conditions The conditions for this query.
* @return Function Returns `this`.
*/
where(conditions, alias) {
if (!isEmpty(conditions)) {
var conditions = this.statement().dialect().prefix(conditions, alias ? alias : this.alias(), false);
this.statement().where(conditions);
}
return this;
}
/**
* Alias for `where()`.
*
* @param mixed conditions The conditions for this query.
* @return Function Returns `this`.
*/
conditions(conditions) {
return this.where(conditions);
}
/**
* Adds some group by fields to the query
*
* @param mixed fields The fields.
* @return Function Returns `this`.
*/
group(fields) {
fields = Array.isArray(fields) && arguments.length === 1 ? fields : Array.prototype.slice.call(arguments);
fields = this.statement().dialect().prefix(fields, this.alias());
this.statement().group(fields);
return this;
}
/**
* Adds some having conditions to the query
*
* @param mixed conditions The conditions for this query.
* @return Function Returns `this`.
*/
having(conditions) {
conditions = this.statement().dialect().prefix(conditions, this.alias());
this.statement().having(conditions);
return this;
}
/**
* Adds some order by fields to the query
*
* @param mixed fields The fields.
* @return Function Returns `this`.
*/
order(fields) {
fields = Array.isArray(fields) && arguments.length === 1 ? fields : Array.prototype.slice.call(arguments);
fields = this.statement().dialect().prefix(fields, this.alias());
this.statement().order(fields);
return this;
}
/**
* Sets page number.
*
* @param integer page The page number
* @return self
*/
page(page)
{
this._page.page = page;
return this;
}
/**
* Sets offset value.
*
* @param integer offset The offset value.
* @return self
*/
offset(offset)
{
this._page.offset = offset;
return this;
}
/**
* Sets limit value.
*
* @param integer limit The number of results to limit or `0` for limit at all.
* @return self
*/
limit(limit)
{
this._page.limit = Number.parseInt(limit);
return this;
}
/**
* Set the lock mode.
*
* @param mixed mode The lock mode or `false` to disable it.
* @return self
*/
lock(mode) {
mode = mode || 'update';
this.statement().lock(mode);
return this;
}
/**
* Applies a query handler
*
* @param Closure closure A closure.
* @return Function Returns `this`.
*/
handler(closure) {
if (typeof closure === 'function') {
closure(this);
}
return this;
}
/**
* Sets the relations to retrieve.
*
* @param array embed The relations to load with the query.
* @return object Returns `this`.
*/
embed(embed, conditions) {
if (!arguments.length) {
return this._embed;
}
if (!isEmpty(embed)) {
if (typeof embed === "string" && arguments.length === 2) {
var mix = {};
mix[embed] = conditions || [];
embed = [mix];
} else {
embed = Array.isArray(embed) ? embed : [embed];
}
this._embed = this._embed.concat(embed);
}
return this;
}
/**
* Sets the conditionnal dependency over some relations.
*
* @param array The conditionnal dependency.
*/
has(has, conditions) {
if (!arguments.length) {
return this._has;
}
if (!isEmpty(has)) {
if (typeof has === 'string') {
var mix = {};
mix[has] = conditions || [];
has = [mix];
}
this._has = this._has.concat(has);
}
return this;
}
/**
* Gets a unique alias for the query or a query's relation if `relpath` is set.
*
* @param string path A dotted relation name or for identifying the query's relation.
* @param object schema The corresponding schema to alias.
* @return string A string alias.
*/
alias(path, schema) {
if (arguments.length < 2) {
path = path || '';
if (this._aliases[path] !== undefined) {
return this._aliases[path];
} else {
throw new Error("No alias has been defined for `'" + path + "'`.");
}
}
var alias = schema.source();
if (this._aliasCounter[alias] === undefined) {
this._aliasCounter[alias] = 0;
this._aliases[path] = alias;
} else {
alias = this._aliases[path] = alias + '__' + this._aliasCounter[alias]++;
}
this._schemas[alias] = schema;
return alias;
}
/**
* Applies the has conditions.
*/
_applyHas() {
var schema = this.schema();
var tree = schema.treeify(this.has());
this._applyJoins(this.schema(), tree, '', this.alias());
var has = this.has();
for (var value of has) {
var key = Object.keys(value)[0];
var conditions = value[key];
this.where(conditions, this.alias(key));
}
this._has = [];
}
/**
* Applies the limit range when applicable.
*/
_applyLimit() {
if (!this._page.limit) {
return;
}
var offset;
if (this._page.offset) {
offset = this._page.offset;
} else {
var page = this._page.page ? this._page.page : 1;
offset = (page - 1) * this._page.limit;
}
this.statement().limit(this._page.limit, offset);
}
/**
* Applies joins.
*
* @param Object schema The schema to perform joins on.
* @param Array tree The tree of relations to join.
* @param Array basePath The base relation path.
* @param String aliasFrom The alias name of the from model.
*/
_applyJoins(schema, tree, basePath, aliasFrom) {
for (var key in tree) {
var children = tree[key] && tree[key].embed ? tree[key].embed : {};
var rel = schema.relation(key);
var path = basePath ? basePath + '.' + key : key;
var to;
if (rel.type() !== 'hasManyThrough') {
to = this._join(path, rel, aliasFrom);
} else {
var name = rel.using();
var nameThrough = rel.through();
var pathThrough = path ? path + '.' + nameThrough : nameThrough;
var from = rel.from();
var relThrough = from.definition().relation(nameThrough);
var aliasThrough = this._join(pathThrough, relThrough, aliasFrom);
var modelThrough = relThrough.to();
var relTo = modelThrough.definition().relation(name);
to = this._join(path, relTo, aliasThrough);
}
if (children && Object.keys(children).length) {
this._applyJoins(rel.to().definition(), children, path, to);
}
}
}
/**
* Set a query's join according a Relationship.
*
* @param string path The relation path.
* @param object rel A Relationship instance.
* @param string fromAlias The "from" model alias.
* @return string The "to" model alias.
*/
_join(path, rel, fromAlias) {
if (this._aliases[path] !== undefined) {
return this._aliases[path];
}
var schema = rel.to().definition();
var source = schema.source();
var toAlias = this.alias(path, schema);
var table = {};
table[source] = toAlias;
this.statement().join(
table,
this._on(rel, fromAlias, toAlias),
'LEFT'
);
return toAlias;
}
/**
* Build the `ON` constraints from a `Relationship` instance.
*
* @param object rel A Relationship instance.
* @param string fromAlias The "from" model alias.
* @param string toAlias The "to" model alias.
* @return array A constraints array.
*/
_on(rel, fromAlias, toAlias) {
if (rel.type() === 'hasManyThrough') {
return [];
}
var keys = rel.keys();
var fromField = Object.keys(keys)[0];
var toField = keys[fromField];
return { '=': [{ ':name': fromAlias + '.' + fromField }, { ':name': toAlias + '.' + toField }] };
}
/**
* Return the SQL string.
*
* @return String
*/
toString() {
var statement = this._statement;
this._applyHas();
this._applyLimit();
var parts = {
fields: statement.data('fields').slice(),
joins: statement.data('joins').slice(),
where: statement.data('where').slice(),
limit: statement.data('limit')
};
var noFields = !statement.data('fields');
if (noFields) {
statement.fields({ [this.alias()]: ['*'] });
}
var sql = statement.toString(this._schemas, this._aliases);
for (var name in parts) {
statement.data(name, parts[name]);
}
this._aliasCounter = {};
this._aliases = {};
this.alias('', this.schema());
return sql;
}
}
module.exports = Query;