alasql
Version:
AlaSQL.js - JavaScript SQL database library for relational and graph data manipulation with support of localStorage, IndexedDB, and Excel
51 lines (46 loc) • 1.91 kB
JavaScript
/*
//
// CASE for Alasql.js
// Date: 03.11.2014
// (c) 2014, Andrey Gershun
//
*/
yy.CaseValue = function(params) { return yy.extend(this, params); };
yy.CaseValue.prototype.toString = function() {
var s = 'CASE ';
if(this.expression) s += this.expression.toString();
if(this.whens) {
s += this.whens.map(function(w) { return ' WHEN '+
w.when.toString() + ' THEN '+w.then.toString()}).join();
}
s += ' END';
return s;
};
yy.CaseValue.prototype.findAggregator = function (query){
// console.log(this.toString());
if(this.expression && this.expression.findAggregator) this.expression.findAggregator(query);
if(this.whens && this.whens.length > 0) {
this.whens.forEach(function(w) {
if(w.when.findAggregator) w.when.findAggregator(query);
if(w.then.findAggregator) w.then.findAggregator(query);
});
};
if(this.elses && this.elses.findAggregator) this.elses.findAggregator(query);
};
yy.CaseValue.prototype.toJavaScript = function(context, tableid, defcols) {
var s = '((function('+context+',params,alasql){var r;';
if(this.expression) {
// this.expression.toJavaScript(context, tableid)
s += 'v='+this.expression.toJavaScript(context, tableid, defcols)+';';
s += (this.whens||[]).map(function(w) { return ' if(v=='+w.when.toJavaScript(context,tableid, defcols)
+') {r='+w.then.toJavaScript(context,tableid, defcols)+'}'; }).join(' else ');
if(this.elses) s += ' else {r='+this.elses.toJavaScript(context,tableid, defcols)+'}';
} else {
s += (this.whens||[]).map(function(w) { return ' if('+w.when.toJavaScript(context,tableid, defcols)
+') {r='+w.then.toJavaScript(context,tableid, defcols)+'}'; }).join(' else ');
if(this.elses) s += ' else {r='+this.elses.toJavaScript(context,tableid,defcols)+'}';
}
// TODO remove bind from CASE
s += ';return r;}).bind(this))('+context+',params,alasql)';
return s;
};