forked from brianc/node-sql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery.js
More file actions
557 lines (484 loc) · 14.3 KB
/
query.js
File metadata and controls
557 lines (484 loc) · 14.3 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
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
'use strict';
var _ = require('lodash');
var alias = require('./alias');
var assert = require('assert');
var sliced = require('sliced');
var util = require('util');
var valueExpressionMixin = require('./valueExpression');
var Node = require('./');
var Select = require('./select');
var From = require('./from');
var Where = require('./where');
var OrderBy = require('./orderBy');
var GroupBy = require('./groupBy');
var Having = require('./having');
var Insert = require('./insert');
var Replace = require('./replace');
var Update = require('./update');
var Delete = require('./delete');
var Returning = require('./returning');
var OnDuplicate = require('./onDuplicate');
var OnConflict = require('./onConflict');
var ForUpdate = require('./forUpdate');
var ForShare = require('./forShare');
var Create = require('./create');
var Drop = require('./drop');
var Truncate = require('./truncate');
var Distinct = require('./distinct');
var DistinctOn = require('./distinctOn');
var Alter = require('./alter');
var AddColumn = require('./addColumn');
var DropColumn = require('./dropColumn');
var RenameColumn = require('./renameColumn');
var Rename = require('./rename');
var Column = require('../column');
var ParameterNode = require('./parameter');
var PrefixUnaryNode = require('./prefixUnary');
var IfExists = require('./ifExists');
var IfNotExists = require('./ifNotExists');
var OrIgnore = require('./orIgnore');
var Cascade = require('./cascade');
var Restrict = require('./restrict');
var Indexes = require('./indexes');
var CreateIndex = require('./createIndex');
var DropIndex = require('./dropIndex');
var Table = require('./table');
var CreateView = require('./createView');
var JoinNode = require('./join');
var Modifier = Node.define({
constructor: function(table, type, count) {
this.table = table;
this.type = type;
this.count = count;
}
});
// get the first element of an arguments if it is an array, else return arguments as an array
var getArrayOrArgsAsArray = function(args) {
if (util.isArray(args[0])) {
return args[0];
}
return sliced(args);
};
var Query = Node.define({
type: 'QUERY',
constructor: function(table) {
Node.call(this);
this.table = table;
if (table) {
this.sql = table.sql;
}
},
select: function() {
var select;
if (this._select) {
select = this._select;
} else {
select = this._select = new Select();
this.add(select);
}
//allow things like .select(a.star(), [ a.id, a.name ])
//this will flatten them into a single array
var args = sliced(arguments).reduce(function(cur, next) {
if (util.isArray(next)) {
return cur.concat(next);
}
cur.push(next);
return cur;
}, []);
select.addAll(args);
// if this is a subquery then add reference to this column
if (this.type === 'SUBQUERY') {
for (var j = 0; j < select.nodes.length; j++) {
var name = select.nodes[j].alias || select.nodes[j].name;
var col = new Column(select.nodes[j]);
col.name = name;
col.property = name;
col.table = this;
if (this[name] === undefined) {
this[name] = col;
}
}
}
return this;
},
star: function() {
assert(this.type === 'SUBQUERY', 'star() can only be used on a subQuery');
return new Column({
table: this,
star: true
});
},
from: function() {
var tableNodes = arguments;
if (Array.isArray(arguments[0])) {
tableNodes = arguments[0];
}
for (var i=0; i<tableNodes.length; i++) {
this.add(new From().add(tableNodes[i]));
}
return this;
},
leftJoin: function(other) {
assert(this.type === 'SUBQUERY', 'leftJoin() can only be used on a subQuery');
return new JoinNode('LEFT', this, other.toNode());
},
fullJoin: function(other) {
// assert(this.type === 'SUBQUERY', 'fullJoin() can only be used on a subQuery');
return new JoinNode('FULL', this, other.toNode());
},
where: function(node) {
if (arguments.length > 1) {
// allow multiple where clause arguments
var args = sliced(arguments);
for (var i = 0; i < args.length; i++) {
this.where(args[i]);
}
return this;
}
// calling #where twice functions like calling #where & then #and
if (this.whereClause) {
return this.and(node);
}
this.whereClause = new Where(this.table);
this.whereClause.add(node);
return this.add(this.whereClause);
},
or: function(node) {
if (!this.whereClause) return this.where(node);
this.whereClause.or(node);
return this;
},
and: function(node) {
if (!this.whereClause) return this.where(node);
this.whereClause.and(node);
return this;
},
order: function() {
var args = getArrayOrArgsAsArray(arguments);
var orderBy;
if (args.length === 0) {
return this;
}
if (this._orderBy) {
orderBy = this._orderBy;
} else {
orderBy = this._orderBy = new OrderBy();
this.add(orderBy);
}
orderBy.addAll(args);
return this;
},
group: function() {
var args = getArrayOrArgsAsArray(arguments);
var groupBy = new GroupBy().addAll(args);
return this.add(groupBy);
},
having: function() {
var args = getArrayOrArgsAsArray(arguments);
var having = new Having().addAll(args);
return this.add(having);
},
insert: function(o) {
var self = this;
var args = sliced(arguments);
// object literal
if (arguments.length === 1 && !o.toNode && !o.forEach) {
args = [];
Object.keys(o).forEach(function(key) {
var col = self.table.get(key);
if(col && !col.autoGenerated)
args.push(col.value(o[key]));
});
} else if (o.forEach) {
o.forEach(function(arg) {
return self.insert.call(self, arg);
});
return self;
}
if (self.insertClause) {
self.insertClause.add(args);
return self;
} else {
self.insertClause = new Insert();
self.insertClause.add(args);
return self.add(self.insertClause);
}
},
replace: function(o) {
var self = this;
var args = sliced(arguments);
// object literal
if (arguments.length === 1 && !o.toNode && !o.forEach) {
args = [];
Object.keys(o).forEach(function(key) {
var col = self.table.get(key);
if(col && !col.autoGenerated)
args.push(col.value(o[key]));
});
} else if (o.forEach) {
o.forEach(function(arg) {
return self.replace.call(self, arg);
});
return self;
}
if (self.replaceClause) {
self.replaceClause.add(args);
return self;
} else {
self.replaceClause = new Replace();
self.replaceClause.add(args);
return self.add(self.replaceClause);
}
},
update: function(o) {
var self = this;
var update = new Update();
Object.keys(o).forEach(function(key) {
var col = self.table.get(key);
if(col && !col.autoGenerated) {
var val = o[key];
update.add(col.value(ParameterNode.getNodeOrParameterNode(val)));
}
});
return this.add(update);
},
parameter: function(v) {
var param = ParameterNode.getNodeOrParameterNode(v);
param.isExplicit = true;
return this.add(param);
},
delete: function(params) {
var result;
if (params) {
var TableDefinition = require('../table');
if (params instanceof TableDefinition || Array.isArray(params)) {
//handle explicit delete queries:
// e.g. post.delete(post).from(post) -> DELETE post FROM post
// e.g. post.delete([post, user]).from(post) -> DELETE post, user FROM post
if (Array.isArray(params)) {
params = params.map(function(table) { return new Table(table); });
} else {
params = [ new Table(params) ];
}
result = this.add(new Delete().addAll(params));
} else {
//syntax sugar for post.delete().from(post).where(params)
result = this.add(new Delete()).where(params);
}
} else{
result = this.add(new Delete());
}
return result;
},
returning: function() {
var returning = new Returning();
if (arguments.length === 0)
returning.add('*');
else
returning.addAll(getArrayOrArgsAsArray(arguments));
return this.add(returning);
},
onDuplicate: function(o) {
var self = this;
var onDuplicate = new OnDuplicate();
Object.keys(o).forEach(function(key) {
var col = self.table.get(key);
if(col && !col.autoGenerated)
var val = o[key];
onDuplicate.add(col.value(ParameterNode.getNodeOrParameterNode(val))); // jshint ignore:line
});
return self.add(onDuplicate);
},
onConflict: function(o) {
var self = this;
var onConflict = new OnConflict();
Object.keys(o).forEach(function(key) {
onConflict[key] = o[key];
});
return self.add(onConflict);
},
forUpdate: function() {
assert(typeof this._select !== 'undefined', 'FOR UPDATE can be used only in a select statement');
this.add(new ForUpdate());
return this;
},
forShare: function() {
assert(typeof this._select !== 'undefined', 'FOR SHARE can be used only in a select statement');
this.add(new ForShare());
return this;
},
create: function(indexName) {
if (this.indexesClause) {
var createIndex = new CreateIndex(this.table, indexName);
this.add(createIndex);
return createIndex;
} else {
return this.add(new Create(this.table.isTemporary));
}
},
drop: function() {
if (this.indexesClause) {
var args = sliced(arguments);
var dropIndex = new DropIndex(this.table, args);
this.add(dropIndex);
return dropIndex;
} else {
return this.add(new Drop(this.table));
}
},
truncate: function() {
return this.add(new Truncate(this.table));
},
distinct: function() {
return this.add(new Distinct());
},
distinctOn: function() {
var distinctOn;
if (this._distinctOn) {
distinctOn = this._distinctOn;
} else {
var select = this.nodes.filter(function (node) {return node.type === 'SELECT';}).shift();
distinctOn = this._distinctOn = new DistinctOn();
select.add(distinctOn);
}
//allow things like .distinctOn(a.star(), [ a.id, a.name ])
//this will flatten them into a single array
var args = sliced(arguments).reduce(function(cur, next) {
if (util.isArray(next)) {
return cur.concat(next);
}
cur.push(next);
return cur;
}, []);
distinctOn.addAll(args);
return this;
},
alter: function() {
return this.add(new Alter());
},
rename: function(newName) {
var renameClause = new Rename();
if (!newName.toNode) {
newName = new Column({
name: newName,
table: this.table
});
}
renameClause.add(newName.toNode());
this.nodes[0].add(renameClause);
return this;
},
addColumn: function(column, dataType) {
var addClause = new AddColumn();
if (!column.toNode) {
column = new Column({
name: column,
table: this.table
});
}
if (dataType) {
column.dataType = dataType;
}
addClause.add(column.toNode());
this.nodes[0].add(addClause);
return this;
},
dropColumn: function(column) {
var dropClause = new DropColumn();
if (!column.toNode) {
column = new Column({
name: column,
table: this.table
});
}
dropClause.add(column.toNode());
this.nodes[0].add(dropClause);
return this;
},
renameColumn: function(oldColumn, newColumn) {
var renameClause = new RenameColumn();
if (!oldColumn.toNode) {
oldColumn = new Column({
name: oldColumn,
table: this.table
});
}
if (!newColumn.toNode) {
newColumn = new Column({
name: newColumn,
table: this.table
});
}
renameClause.add(oldColumn.toNode());
renameClause.add(newColumn.toNode());
this.nodes[0].add(renameClause);
return this;
},
limit: function(count) {
return this.add(new Modifier(this, 'LIMIT', count));
},
offset: function(count) {
return this.add(new Modifier(this, 'OFFSET', count));
},
exists: function() {
assert(this.type === 'SUBQUERY', 'exists() can only be used on a subQuery');
return new PrefixUnaryNode({
left: this,
operator: "EXISTS"
});
},
notExists: function() {
assert(this.type === 'SUBQUERY', 'notExists() can only be used on a subQuery');
return new PrefixUnaryNode({
left: this,
operator: "NOT EXISTS"
});
},
ifExists: function() {
this.nodes[0].unshift(new IfExists());
return this;
},
ifNotExists: function() {
this.nodes[0].unshift(new IfNotExists());
return this;
},
orIgnore: function() {
this.nodes[0].unshift(new OrIgnore());
return this;
},
cascade: function() {
this.nodes[0].add(new Cascade());
return this;
},
restrict: function() {
this.nodes[0].add(new Restrict());
return this;
},
indexes: function() {
this.indexesClause = new Indexes({
table: this.table
});
return this.add(this.indexesClause);
},
createView: function(viewName) {
this.add(new CreateView(viewName));
return this;
}
});
// Here we are extending query with valueExpressions so that it's possible to write queries like
// var query=sql.select(a.select(a.x.sum()).plus(b.select(b.y.sum()))
// which generates:
// SELECT (SELECT SUM(a.x) FROM a) + (SELECT SUM(b.y) FROM b)
// We need to remove "or" and "and" from here because it conflicts with the already existing functionality of appending
// to the where clause like so:
// var query=a.select().where(a.name.equals("joe")).or(a.name.equals("sam"))
var valueExpressions=valueExpressionMixin();
delete valueExpressions.or;
delete valueExpressions.and;
_.extend(Query.prototype, valueExpressions);
// Extend the query with the aliasMixin so that it's possible to write queries like
// var query=sql.select(a.select(a.count()).as("column1"))
// which generates:
// SELECT (SELECT COUNT(*) FROM a) AS "column1"
_.extend(Query.prototype, alias.AliasMixin);
module.exports = Query;