forked from brianc/node-sql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcolumn.js
More file actions
101 lines (83 loc) · 2.47 KB
/
column.js
File metadata and controls
101 lines (83 loc) · 2.47 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
'use strict';
var _ = require('lodash');
var ColumnNode = require('./node/column');
var OrderByValueNode = require('./node/orderByValue');
var TextNode = require('./node/text');
var valueExpressionMixin = require('./node/valueExpression');
var Column = function(config) {
this.table = config.table;
for (var name in config) {
if (config.hasOwnProperty(name)) {
this[name] = config[name];
}
}
this.asc = this.ascending = this;
this.alias = null;
this.desc = this.descending = new OrderByValueNode({
value : this.toNode(),
direction : new TextNode('DESC')
});
this.dataType = config.dataType;
};
// mix in value expression
_.extend(Column.prototype, valueExpressionMixin());
var contextify = function(base) {
var context = Object.create(Column.prototype);
Object.keys(base).forEach(function (key) {
context[key] = base[key];
});
return context;
};
Column.prototype.value = function(value) {
var context = contextify(this);
context._value = value;
return context;
};
Column.prototype.getValue = function() {
return this._value;
};
Column.prototype.toNode = function() {
// creates a query node from this column
return new ColumnNode(contextify(this));
};
Column.prototype.as = function(alias) {
var context = contextify(this);
context.alias = alias;
return new ColumnNode(context);
};
Column.prototype.arrayAgg = function(alias) {
var context = contextify(this);
context.asArray = true;
context.alias = alias || context.name + 's';
return new ColumnNode(context);
};
Column.prototype.aggregate = function(alias, aggregator) {
var context = contextify(this);
context.aggregator = aggregator.toUpperCase();
context.alias = alias || context.name + '_' + context.aggregator.toLowerCase();
return new ColumnNode(context);
};
Column.prototype.count = function(alias) {
return this.aggregate(alias, 'count');
};
Column.prototype.min = function(alias) {
return this.aggregate(alias, 'min');
};
Column.prototype.max = function(alias) {
return this.aggregate(alias, 'max');
};
Column.prototype.sum = function(alias) {
return this.aggregate(alias, 'sum');
};
Column.prototype.avg = function(alias) {
return this.aggregate(alias, 'avg');
};
Column.prototype.distinct = function() {
var context = contextify(this);
context.distinct = true;
return new ColumnNode(context);
};
Column.prototype.toQuery = function() {
return this.toNode().toQuery();
};
module.exports = Column;