alasql = function (sql, params, cb, scope) { params = params||[]; if(typeof importScripts !== 'function' && alasql.webworker) { var id = alasql.lastid++; alasql.buffer[id] = cb; alasql.webworker.postMessage({id:id,sql:sql,params:params}); return; } if(arguments.length === 0) { // Without arguments - Fluent interface return new yy.Select({ columns:[new yy.Column({columnid:'*'})], from: [new yy.ParamValue({param:0})] }); } else if(arguments.length === 1){ // Access promise notation without using `.promise(...)` if(sql.constructor === Array){ return alasql.promise(sql); } } // Avoid setting params if not needed even with callback if(typeof params === 'function'){ scope = cb; cb = params; params = []; } if(typeof params !== 'object'){ params = [params]; } // Standard interface // alasql('#sql'); if(typeof sql === 'string' && sql[0]==='#' && typeof document === "object") { sql = document.querySelector(sql).textContent; } else if(typeof sql === 'object' && sql instanceof HTMLElement) { sql = sql.textContent; } else if(typeof sql === 'function') { // to run multiline functions sql = sql.toString().slice(14,-3); } // Run SQL return alasql.exec(sql, params, cb, scope); }
n/a
Database = function (databaseid) { var self = this; if(self === alasql) { if(databaseid) { self = alasql.databases[databaseid]; alasql.databases[databaseid] = self; if(!self) { throw new Error('Database "'+databaseid+'" not found'); } } else { // Create new database (or get alasql?) self = alasql.databases.alasql; // For SQL Server examples, USE tempdb if(alasql.options.tsql){ alasql.databases.tempdb = alasql.databases.alasql; } } } if(!databaseid) { databaseid = "db"+(alasql.databasenum++); // Random name } // Step 1 self.databaseid = databaseid; alasql.databases[databaseid] = self; self.dbversion = 0; //Steps 2-5 self.tables = {}; self.views = {}; self.triggers = {}; self.indices = {}; // Step 6: Objects storage self.objects = {}; self.counter = 0; self.resetSqlCache(); return self; }
...
var res = alasql.engines[this.engineid].createDatabase(this.databaseid, this.args, this.ifnotexists, this.as, cb);
return res;
} else {
var dbid = this.databaseid;
if(alasql.databases[dbid]) {
throw new Error("Database '"+dbid+"' already exists")
};
var a = new alasql.Database(dbid);
var res = 1;
if(cb) return cb(res);
return res;
}
};
// CREATE DATABASE databaseid
yy.AttachDatabase = function (params) { return yy.extend(this, params); };
...
Query = function (params){ this.alasql = alasql; // Columns this.columns = []; this.xcolumns = {}; this.selectGroup = []; this.groupColumns = {}; // Data array extend(this,params); }
n/a
Recordset = function (params){ // Data array extend(this,params); }
...
val = okeys[1];
}
for(var i=0, ilen=res.length; i<ilen; i++){
ar[res[i][key]] = res[i][val];
}
res = ar;
}else if(modifier === 'RECORDSET') {
res = new alasql.Recordset({columns:columns, data:res});
}else if(modifier === 'TEXTSTRING') {
var key;
if(columns && columns.length > 0){
key = columns[0].columnid;
} else{
key = Object.keys(res[0])[0];
}
...
Table = function (params){ // Step 1: Data array this.data = []; // Step 2: Columns this.columns = []; this.xcolumns = {}; // Step 3: indices this.inddefs = {}; this.indices = {}; this.uniqs = {}; this.uniqdefs = {}; // Step 4: identities this.identities = {}; // Step 5: checkfn... this.checks = []; this.checkfns = []; // For restore... to be done... // Step 6: INSERT/DELETE/UPDATE // Step 7: Triggers... // Create trigger hubs this.beforeinsert = {}; this.afterinsert = {}; this.insteadofinsert = {}; this.beforedelete = {}; this.afterdelete = {}; this.insteadofdelete = {}; this.beforeupdate = {}; this.afterupdate = {}; this.insteadofupdate = {}; // Done extend(this,params); }
...
this.$ = r;
break;
case 201:
if($$[$0-2] == 'INFORMATION_SCHEMA') {
this.$ = new yy.FuncValue({funcid: $$[$0-2], args:[new yy.StringValue({value:$$[$0]})]});
} else {
this.$ = new yy.Table({databaseid: $$[$0-2], tableid:$$[$0]});
}
break;
case 202:
this.$ = new yy.Table({tableid: $$[$0]});
break;
case 203: case 204:
this.$ = $$[$0-1]; $$[$0-1].push($$[$0]);
...
Transaction = function (databaseid) { this.transactionid = Date.now(); this.databaseid = databaseid; this.commited = false; this.dbversion = alasql.databases[databaseid].dbversion; // this.bank = cloneDeep(alasql.databases[databaseid]); this.bank = JSON.stringify(alasql.databases[databaseid]); // TODO CLone Tables with insertfns return this; }
...
//
// Transactio class for Alasql.js
// Date: 03.11.2014
// (c) 2014, Andrey Gershun
//
*/
Database.prototype.transaction = function(cb) {
var tx = new alasql.Transaction(this.databaseid);
var res = cb(tx);
return res;
};
// Transaction class (for WebSQL compatibility)
/**
Transaction class
@class Transaction
...
View = function (params){ // Columns this.columns = []; this.xcolumns = {}; // Data array this.query = []; extend(this,params); }
n/a
adrun = function (databaseid, ast, params, cb, scope) { var idx = 0; var noqueries = ast.statements.length; if (alasql.options.progress !== false) { alasql.options.progress(noqueries, idx++); } // alasql.busy++; var useid = alasql.useid; if(useid !== databaseid) { alasql.use(databaseid); } var res = []; function adrunone(data) { if(data !== undefined){ res.push(data); } var astatement = ast.statements.shift(); if(!astatement) { if(useid !== databaseid){ alasql.use(useid); } cb(res); } else { if(astatement.compile) { var statement = astatement.compile(alasql.useid); statement(params, adrunone, scope); if (alasql.options.progress !== false) { alasql.options.progress(noqueries, idx++); } } else { alasql.precompile(ast.statements[0],alasql.useid,params); astatement.execute(alasql.useid, params, adrunone); if (alasql.options.progress !== false) { alasql.options.progress(noqueries, idx++); } } } } adrunone(); /** @todo Check, why data is empty here */ }
...
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
return alasql.drun(databaseid, ast, params, cb, scope);
}
}
};
/**
Run multiple statements and return array of results sync
...
autoval = function (tablename, colname, getNext, databaseid){ var db = databaseid?alasql.databases[databaseid]:alasql.databases[alasql.useid]; if(!db.tables[tablename]){ throw new Error('Tablename not found: '+tablename); } if(!db.tables[tablename].identities[colname]){ throw new Error('Colname not found: '+colname); } if(getNext){ return db.tables[tablename].identities[colname].value || null; } return (db.tables[tablename].identities[colname].value - db.tables[tablename].identities[colname].step) || null }
...
*/
Database.prototype.exec = function(sql, params, cb) {
return alasql.dexec(this.databaseid, sql, params, cb);
};
Database.prototype.autoval = function(tablename, colname, getNext) {
return alasql.autoval(tablename, colname, getNext, this.databaseid);
};
// Aliases like MS SQL
/*
//
// Transactio class for Alasql.js
...
clear = function () { var target = alasql.options.logtarget; // For node other if(utils.isNode || utils.isMeteorServer) { if(console.clear) { console.clear(); } } else { var el; if(target === 'output') { el = document.getElementsByTagName('output')[0]; } else { if(typeof target === 'string') { el = document.getElementById(target); } else { // in case of DOM el = target; } } el.innerHTML = ''; } }
...
}
};
alasql.clear = function() {
var target = alasql.options.logtarget;
// For node other
if(utils.isNode || utils.isMeteorServer) {
if(console.clear) {
console.clear();
}
} else {
var el;
if(target === 'output') {
el = document.getElementsByTagName('output')[0];
} else {
if(typeof target === 'string') {
...
compile = function (sql, databaseid) { databaseid = databaseid || alasql.useid; var ast = alasql.parse(sql); // Create AST if(1 === ast.statements.length) { var statement = ast.statements[0].compile(databaseid) statement.promise = function(params){ return new Promise(function(resolve, reject){ statement(params, function(data,err) { if(err) { reject(err); } else { resolve(data); } }); }); }; return statement; } else { throw new Error('Cannot compile, because number of statements in SQL is not equal to 1'); } }
...
You can also define your own aggregator functions (like your own `SUM(...)`). See more [in the wiki](https://github.com/agershun
/alasql/wiki/User-Defined-Functions)
### Compiled statements and functions
```js
var ins = alasql.compile('INSERT INTO one VALUES (?,?)');
ins(1,10);
ins(2,20);
```
See more [in the wiki](https://github.com/agershun/alasql/wiki/Compile)
...
dexec = function (databaseid, sql, params, cb, scope) { var db = alasql.databases[databaseid]; // if(db.databaseid != databaseid) console.trace('got!'); var hh; // Create hash if(alasql.options.cache) { hh = hash(sql); var statement = db.sqlCache[hh]; // If database structure was not changed sinse lat time return cache if(statement && db.dbversion === statement.dbversion) { return statement(params, cb); } } // Create AST var ast = alasql.parse(sql); if(!ast.statements){ return; } if(0 === ast.statements.length){ return 0; } else if(1 === ast.statements.length) { if(ast.statements[0].compile) { // Compile and Execute var statement = ast.statements[0].compile(databaseid, params); if(!statement){ return; } statement.sql = sql; statement.dbversion = db.dbversion; if(alasql.options.cache) { // Secure sqlCache size if (db.sqlCacheSize > alasql.MAXSQLCACHESIZE) { db.resetSqlCache(); } db.sqlCacheSize++; db.sqlCache[hh] = statement; } var res = alasql.res = statement(params, cb, scope); return res; } else { alasql.precompile(ast.statements[0],alasql.useid,params); var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope); return res; } } else { // Multiple statements if(cb) { alasql.adrun(databaseid, ast, params, cb, scope); } else { return alasql.drun(databaseid, ast, params, cb, scope); } } }
...
cb = params;
params = {};
}
delete alasql.error;
params = params || {};
if(alasql.options.errorlog){
try {
return alasql.dexec(alasql.useid, sql, params, cb, scope);
} catch(err){
alasql.error = err;
if(cb){
cb(null,alasql.error);
}
}
} else {
...
drun = function (databaseid, ast, params, cb, scope) { var useid = alasql.useid; if(useid !== databaseid){ alasql.use(databaseid); } var res = []; for (var i=0, ilen=ast.statements.length; i<ilen; i++) { if(ast.statements[i]) { if(ast.statements[i].compile) { var statement = ast.statements[i].compile(alasql.useid); res.push(alasql.res = statement(params,null,scope)); } else { alasql.precompile(ast.statements[i],alasql.useid,params); res.push(alasql.res = ast.statements[i].execute(alasql.useid, params)); } } } if(useid !== databaseid){ alasql.use(useid); } if(cb){ cb(res); } alasql.res = res; return res; }
...
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
return alasql.drun(databaseid, ast, params, cb, scope);
}
}
};
/**
Run multiple statements and return array of results sync
*/
alasql.drun = function (databaseid, ast, params, cb, scope) {
...
engines.FILE = function (){}
n/a
engines.INDEXEDDB = function (){}
n/a
engines.LOCALSTORAGE = function (){}
n/a
engines.SQLITE = function (){}
n/a
engines.WEBSQL = function (){}
n/a
exec = function (sql, params, cb, scope) { // Avoid setting params if not needed even with callback if(typeof params === 'function'){ scope = cb; cb = params; params = {}; } delete alasql.error; params = params || {}; if(alasql.options.errorlog){ try { return alasql.dexec(alasql.useid, sql, params, cb, scope); } catch(err){ alasql.error = err; if(cb){ cb(null,alasql.error); } } } else { return alasql.dexec(alasql.useid, sql, params, cb, scope); } }
...
alasql('SELECT * FROM ?',[data],function(res){
console.log(data);
});
Call with scope for subquery (to pass common values):
var scope = {one:{a:2,b;20}}
alasql('SELECT * FROM ? two WHERE two.a = one.a',[data],null,scope);
Call for fluent interface with data object:
alasql(data).Where(function(x){return x.a == 10}).exec();
Call for fluent interface without data object:
alasql().From(data).Where(function(x){return x.a == 10}).exec();
*/
var alasql = function(sql, params, cb, scope) {
params = params||[];
...
function String() { [native code] }
n/a
log = function (sql, params) { var olduseid = alasql.useid; var target = alasql.options.logtarget; // For node other if(utils.isNode) { target = 'console'; } var res; if(typeof sql === "string") { res = alasql(sql, params); } else { res = sql; } // For Node and console.output if(target === 'console' || utils.isNode) { if(typeof sql === 'string' && alasql.options.logprompt){ console.log(olduseid+'>',sql); } if(Array.isArray(res)) { if(console.table) { // For Chrome and other consoles console.table(res); } else { // Add print procedure console.log(JSONtoString(res)); } } else { console.log(JSONtoString(res)); } } else { var el; if(target === 'output') { el = document.getElementsByTagName('output')[0]; } else { if(typeof target === 'string') { el = document.getElementById(target); } else { // in case of DOM el = target; } } var s = ''; if(typeof sql === 'string' && alasql.options.logprompt) { s += '<pre><code>'+alasql.pretty(sql)+'</code></pre>'; } if(Array.isArray(res)) { if(res.length === 0) { s += '<p>[ ]</p>' } else if(typeof res[0] !== 'object' || Array.isArray(res[0])) { for(var i=0,ilen=res.length;i<ilen;i++) { s += '<p>'+loghtml(res[i])+'</p>'; } } else { s += loghtml(res); } } else { s += loghtml(res); } el.innerHTML += s; } }
...
* SELECT UNIQUE
* SELECT MINUS SELECT
* RENAME TABLE table TO literal
* ALTER TABLE table RENAME COLUMN column TO column
* ALTER TABLE table DROP COLUMN column
* Double quoter sign '' and \\' translates into '
* Test with World and Neptuno databases for compatibility
* alasql.test(), alasql.log(), alasql.write(), alasql.writep()
* Console
### 0.0.21 (19.11.2014 - 20.11.2014)
* SELECT a AS q, b w FROM one - AS is not required
* Comments '--' and '/* */' - single line
* Double quote sign in the string 'Bon''appetite'
...
parse = function (sql) { return alasqlparser.parse(alasql.utils.uncomment(sql)); }
...
var url = require('url');
var port = (process.argv[2] || 1337)|0;
if(!port) {
throw new Error('Wrong port number '+process.argv[3]);
}
http.createServer(function (req, res) {
var sql = decodeURI(url.parse(req.url).search).substr(1);
var a = '';
try {
a = alasql(sql);
} catch(err) {
a = err.toString();
};
res.writeHead(200, {'Content-Type': 'application/json'});
...
precompile = function (statement, databaseid, params){ if(!statement) return; statement.params = params; if(statement.queries) { statement.queriesfn = statement.queries.map(function(q) { var nq = q.compile(databaseid || statement.database.databaseid); nq.query.modifier = 'RECORDSET'; return nq; }); } if(statement.exists) { statement.existsfn = statement.exists.map(function(ex) { var nq = ex.compile(databaseid || statement.database.databaseid); nq.query.modifier = 'RECORDSET'; return nq; }); }; }
...
}
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
...
prepareFromData = function (data, array) { var res = data; if(typeof data == "string") { res = data.split(/\r?\n/); if(array) { for(var i=0, ilen=res.length; i<ilen;i++) { res[i] = [res[i]]; } } } else if(array) { res = []; for(var i=0, ilen=data.length; i<ilen;i++) { res.push([data[i]]); } } else if(typeof data == 'object' && !(Array.isArray(data) )) { // } else if(typeof data == 'object' && !(typeof data.length == 'undefined')) { if(typeof Mongo != 'undefined' && typeof Mongo.Collection != 'undefined' && data instanceof Mongo.Collection) { res = data.find().fetch(); } else { res = []; for(var key in data) { if(data.hasOwnProperty(key)) res.push([key,data[key]]); }; } }; return res; }
...
res = data;
if(cb) res = cb(res,idx,query);
return res;
});
return res;
}
} else if(tq instanceof yy.ParamValue) {
var ps = "var res = alasql.prepareFromData(params['"+tq.param+"
;']";
if(tq.array) ps+=",true";
ps += ");if(cb)res=cb(res,idx,query);return res"
source.datafn = new Function('query,params,cb,idx,alasql',ps);
} else if(tq.inserted) {
var ps = "var res = alasql.prepareFromData(alasql.inserted";
if(tq.array) ps+=",true";
ps += ");if(cb)res=cb(res,idx,query);return res"
...
pretty = function (sql, flag) { var pf = alasql.prettyflag; alasql.prettyflag = !flag; var s = alasql.parse(sql).toString(); alasql.prettyflag = pf; return s; }
...
} else {
// in case of DOM
el = target;
}
}
var s = '';
if(typeof sql === 'string' && alasql.options.logprompt) {
s += '<pre><code>'+alasql.pretty(sql)+'</code
></pre>';
}
if(Array.isArray(res)) {
if(res.length === 0) {
s += '<p>[ ]</p>'
} else if(typeof res[0] !== 'object' || Array.isArray(res[0])) {
for(var i=0,ilen=res.length;i<ilen;i++) {
s += '<p>'+loghtml(res[i])+'</p>';
...
promise = function (sql, params) { if(typeof Promise === "undefined"){ throw new Error('Please include a Promise/A+ library'); } if(typeof sql === 'string'){ return promiseExec(sql, params); } if(!utils.isArray(sql) || sql.length<1 || typeof params !== "undefined"){ throw new Error('Error in .promise parameters'); } return promiseAll(sql); }
...
### Read and write Excel, and raw data files
You can import from and export to CSV, TAB, TXT, and JSON files. File extensions can be omitted. Calls to files will always be [[
async]] so the approach is to chain the queries if you have more than one:
```js
var tabFile = 'mydata.tab'
alasql.promise([
"select * from txt('MyFile.log') where [0] like 'M%'",
["select * from tab(?) order by [1]", [tabFile]], // note how to pass parameter when promises are chained
"select [3] as city,[4] as population from csv('./data/cities')",
"select * from json('../config/myJsonfile')"
]).then(function(results){
console.log(results)
}).catch(console.error)
...
prompt = function (el, useidel, firstsql) { if(utils.isNode) { throw new Error('The prompt not realized for Node.js'); } var prompti = 0; if(typeof el === 'string'){ el = document.getElementById(el); } if(typeof useidel === 'string'){ useidel = document.getElementById(useidel); } useidel.textContent = alasql.useid; if(firstsql) { alasql.prompthistory.push(firstsql); prompti = alasql.prompthistory.length; try { var tm = Date.now(); alasql.log(firstsql); alasql.write('<p style="color:blue">'+(Date.now()-tm)+' ms</p>'); } catch (err) { alasql.write('<p>'+olduseid+'> <b>'+sql+'</b></p>'); alasql.write('<p style="color:red">'+err+'<p>'); } } var y = el.getBoundingClientRect().top + document.getElementsByTagName('body')[0].scrollTop; scrollTo(document.getElementsByTagName('body')[0],y,500); el.onkeydown = function(event) { if(event.which === 13) { var sql = el.value; var olduseid = alasql.useid; el.value = ''; alasql.prompthistory.push(sql); prompti = alasql.prompthistory.length; try { var tm = Date.now(); alasql.log(sql); alasql.write('<p style="color:blue">'+(Date.now()-tm)+' ms</p>'); } catch (err) { alasql.write('<p>'+olduseid+'> '+alasql.pretty(sql, false)+'</p>'); alasql.write('<p style="color:red">'+err+'<p>'); } el.focus(); useidel.textContent = alasql.useid; var y = el.getBoundingClientRect().top + document.getElementsByTagName('body')[0].scrollTop; scrollTo(document.getElementsByTagName('body')[0],y,500); } else if(event.which === 38) { prompti--; if(prompti<0){ prompti = 0; } if(alasql.prompthistory[prompti]) { el.value = alasql.prompthistory[prompti]; event.preventDefault(); } } else if(event.which === 40) { prompti++; if(prompti>=alasql.prompthistory.length) { prompti = alasql.prompthistory.length; el.value = ''; } else if(alasql.prompthistory[prompti]) { el.value = alasql.prompthistory[prompti]; event.preventDefault(); } } } }
n/a
test = function (name, times, fn) { if(arguments.length === 0) { alasql.log(alasql.con.results); return; } else if(arguments.length === 1) { var tm = Date.now(); fn(); alasql.con.log(Date.now()-tm); return; } if(arguments.length === 2) { fn = times; times = 1; } var tm = Date.now(); for(var i=0;i<times;i++){ fn(); } alasql.con.results[name] = Date.now()-tm; }
...
* SELECT UNIQUE
* SELECT MINUS SELECT
* RENAME TABLE table TO literal
* ALTER TABLE table RENAME COLUMN column TO column
* ALTER TABLE table DROP COLUMN column
* Double quoter sign '' and \\' translates into '
* Test with World and Neptuno databases for compatibility
* alasql.test(), alasql.log(), alasql.write(), alasql.writep()
* Console
### 0.0.21 (19.11.2014 - 20.11.2014)
* SELECT a AS q, b w FROM one - AS is not required
* Comments '--' and '/* */' - single line
* Double quote sign in the string 'Bon''appetite'
...
use = function (databaseid) { if(!databaseid){ databaseid = alasql.DEFAULTDATABASEID; } if(alasql.useid === databaseid){ return; } alasql.useid = databaseid; var db = alasql.databases[alasql.useid]; alasql.tables = db.tables; // alasql.fn = db.fn; db.resetSqlCache(); if(alasql.options.usedbo) { alasql.databases.dbo = db; // Operator??? } }
...
};
/**
Run multiple statements and return array of results sync
*/
alasql.drun = function (databaseid, ast, params, cb, scope) {
var useid = alasql.useid;
if(useid !== databaseid){
alasql.use(databaseid);
}
var res = [];
for (var i=0, ilen=ast.statements.length; i<ilen; i++) {
if(ast.statements[i]) {
if(ast.statements[i].compile) {
var statement = ast.statements[i].compile(alasql.useid);
res.push(alasql.res = statement(params,null,scope));
...
write = function (s) { var target = alasql.options.logtarget; // For node other if(utils.isNode || utils.isMeteorServer) { if(console.log) { console.log(s); } } else { var el; if(target === 'output') { el = document.getElementsByTagName('output')[0]; } else { if(typeof target === 'string') { el = document.getElementById(target); } else { // in case of DOM el = target; } } el.innerHTML += s; } }
...
* SELECT UNIQUE
* SELECT MINUS SELECT
* RENAME TABLE table TO literal
* ALTER TABLE table RENAME COLUMN column TO column
* ALTER TABLE table DROP COLUMN column
* Double quoter sign '' and \\' translates into '
* Test with World and Neptuno databases for compatibility
* alasql.test(), alasql.log(), alasql.write(), alasql.writep()
* Console
### 0.0.21 (19.11.2014 - 20.11.2014)
* SELECT a AS q, b w FROM one - AS is not required
* Comments '--' and '/* */' - single line
* Double quote sign in the string 'Bon''appetite'
...
yy.AggrValue = function (params){ return yy.extend(this, params); }
n/a
yy.AlterTable = function (params) { return yy.extend(this, params); }
n/a
yy.Apply = function (params) { return yy.extend(this, params); }
n/a
yy.ArrayValue = function (params) { return yy.extend(this, params); }
n/a
yy.Assert = function (params) { return yy.extend(this, params); }
n/a
yy.AttachDatabase = function (params) { return yy.extend(this, params); }
n/a
yy.Base = function (params) { return yy.extend(this, params); }
n/a
yy.BeginEnd = function (params) { return yy.extend(this, params); }
n/a
yy.BeginTransaction = function (params) { return yy.extend(this, params); }
n/a
yy.Break = function (params) { return yy.extend(this, params); }
n/a
yy.CaseValue = function (params) { return yy.extend(this, params); }
n/a
yy.Column = function (params) { return yy.extend(this, params); }
n/a
yy.ColumnDef = function (params) { return yy.extend(this, params); }
n/a
yy.CommitTransaction = function (params) { return yy.extend(this, params); }
n/a
yy.Continue = function (params) { return yy.extend(this, params); }
n/a
yy.Convert = function (params) { return yy.extend(this, params); }
n/a
yy.CreateDatabase = function (params) { return yy.extend(this, params); }
n/a
yy.CreateEdge = function (params) { return yy.extend(this, params); }
n/a
yy.CreateGraph = function (params) { return yy.extend(this, params); }
n/a
yy.CreateIndex = function (params) { return yy.extend(this, params); }
n/a
yy.CreateTable = function (params) { return yy.extend(this, params); }
n/a
yy.CreateTrigger = function (params) { return yy.extend(this, params); }
n/a
yy.CreateVertex = function (params) { return yy.extend(this, params); }
n/a
yy.Declare = function (params) { return yy.extend(this, params); }
n/a
yy.Delete = function (params) { return yy.extend(this, params); }
n/a
yy.DetachDatabase = function (params) { return yy.extend(this, params); }
n/a
yy.DomainValueValue = function (params) { return yy.extend(this, params); }
n/a
yy.DropDatabase = function (params) { return yy.extend(this, params); }
n/a
yy.DropIndex = function (params) { return yy.extend(this, params); }
n/a
yy.DropTable = function (params) { return yy.extend(this, params); }
n/a
yy.DropTrigger = function (params) { return yy.extend(this, params); }
n/a
yy.ExistsValue = function (params) { return yy.extend(this, params); }
n/a
yy.Expression = function (params) { return yy.extend(this, params); }
n/a
yy.ExpressionStatement = function (params) { return yy.extend(this, params); }
n/a
yy.FromData = function (params) { return yy.extend(this, params); }
n/a
yy.FuncValue = function (params){ return yy.extend(this, params); }
n/a
yy.GroupExpression = function (params){ return yy.extend(this, params); }
n/a
yy.If = function (params) { return yy.extend(this, params); }
n/a
yy.Insert = function (params) { return yy.extend(this, params); }
n/a
yy.JavaScript = function (params) { return yy.extend(this, params); }
n/a
yy.Join = function (params) { return yy.extend(this, params); }
n/a
yy.Json = function (params) { return yy.extend(this, params); }
n/a
yy.Literal = function (params) { return yy.extend(this, params); }
n/a
yy.LogicValue = function (params) { return yy.extend(this, params); }
n/a
yy.Merge = function (params) { return yy.extend(this, params); }
n/a
yy.NullValue = function (params) { return yy.extend(this, params); }
n/a
yy.NumValue = function (params) { return yy.extend(this, params); }
n/a
yy.Op = function (params) { return yy.extend(this, params); }
n/a
yy.OrderExpression = function (params){ return yy.extend(this, params); }
n/a
yy.Over = function (params) { return yy.extend(this, params); }
n/a
yy.ParamValue = function (params) { return yy.extend(this, params); }
n/a
yy.Print = function (params) { return yy.extend(this, params); }
n/a
yy.Reindex = function (params) { return yy.extend(this, params); }
n/a
yy.Require = function (params) { return yy.extend(this, params); }
n/a
yy.RollbackTransaction = function (params) { return yy.extend(this, params); }
n/a
yy.Search = function (params) { return yy.extend(this, params); }
n/a
yy.Select = function (params) { return yy.extend(this, params); }
n/a
yy.SetColumn = function (params) { return yy.extend(this, params); }
n/a
yy.SetVariable = function (params) { return yy.extend(this, params); }
n/a
yy.ShowColumns = function (params) { return yy.extend(this, params); }
n/a
yy.ShowCreateTable = function (params) { return yy.extend(this, params); }
n/a
yy.ShowDatabases = function (params) { return yy.extend(this, params); }
n/a
yy.ShowIndex = function (params) { return yy.extend(this, params); }
n/a
yy.ShowTables = function (params) { return yy.extend(this, params); }
n/a
yy.Source = function (params) { return yy.extend(this, params); }
n/a
yy.Statements = function (params) { return yy.extend(this, params); }
n/a
yy.StringValue = function (params) { return yy.extend(this, params); }
n/a
yy.Table = function (params) { return yy.extend(this, params); }
n/a
yy.TruncateTable = function (params) { return yy.extend(this, params); }
n/a
yy.UniOp = function (params) { return yy.extend(this, params); }
n/a
yy.Union = function (params) { return yy.extend(this, params); }
n/a
yy.Update = function (params) { return yy.extend(this, params); }
n/a
yy.UseDatabase = function (params) { return yy.extend(this, params); }
n/a
yy.VarValue = function (params) { return yy.extend(this, params); }
n/a
yy.View = function (params) { return yy.extend(this, params); }
n/a
yy.While = function (params) { return yy.extend(this, params); }
n/a
yy.WithSelect = function (params) { return yy.extend(this, params); }
n/a
Database = function (databaseid) { var self = this; if(self === alasql) { if(databaseid) { self = alasql.databases[databaseid]; alasql.databases[databaseid] = self; if(!self) { throw new Error('Database "'+databaseid+'" not found'); } } else { // Create new database (or get alasql?) self = alasql.databases.alasql; // For SQL Server examples, USE tempdb if(alasql.options.tsql){ alasql.databases.tempdb = alasql.databases.alasql; } } } if(!databaseid) { databaseid = "db"+(alasql.databasenum++); // Random name } // Step 1 self.databaseid = databaseid; alasql.databases[databaseid] = self; self.dbversion = 0; //Steps 2-5 self.tables = {}; self.views = {}; self.triggers = {}; self.indices = {}; // Step 6: Objects storage self.objects = {}; self.counter = 0; self.resetSqlCache(); return self; }
...
var res = alasql.engines[this.engineid].createDatabase(this.databaseid, this.args, this.ifnotexists, this.as, cb);
return res;
} else {
var dbid = this.databaseid;
if(alasql.databases[dbid]) {
throw new Error("Database '"+dbid+"' already exists")
};
var a = new alasql.Database(dbid);
var res = 1;
if(cb) return cb(res);
return res;
}
};
// CREATE DATABASE databaseid
yy.AttachDatabase = function (params) { return yy.extend(this, params); };
...
autoval = function (tablename, colname, getNext) { return alasql.autoval(tablename, colname, getNext, this.databaseid); }
...
*/
Database.prototype.exec = function(sql, params, cb) {
return alasql.dexec(this.databaseid, sql, params, cb);
};
Database.prototype.autoval = function(tablename, colname, getNext) {
return alasql.autoval(tablename, colname, getNext, this.databaseid);
};
// Aliases like MS SQL
/*
//
// Transactio class for Alasql.js
...
exec = function (sql, params, cb) { return alasql.dexec(this.databaseid, sql, params, cb); }
...
alasql('SELECT * FROM ?',[data],function(res){
console.log(data);
});
Call with scope for subquery (to pass common values):
var scope = {one:{a:2,b;20}}
alasql('SELECT * FROM ? two WHERE two.a = one.a',[data],null,scope);
Call for fluent interface with data object:
alasql(data).Where(function(x){return x.a == 10}).exec();
Call for fluent interface without data object:
alasql().From(data).Where(function(x){return x.a == 10}).exec();
*/
var alasql = function(sql, params, cb, scope) {
params = params||[];
...
resetSqlCache = function () { this.sqlCache = {}; // Cache for compiled SQL statements this.sqlCacheSize = 0; }
...
if(alasql.useid === databaseid){
return;
}
alasql.useid = databaseid;
var db = alasql.databases[alasql.useid];
alasql.tables = db.tables;
// alasql.fn = db.fn;
db.resetSqlCache();
if(alasql.options.usedbo) {
alasql.databases.dbo = db; // Operator???
}
};
alasql.autoval = function(tablename, colname, getNext, databaseid){
var db = databaseid?alasql.databases[databaseid]:alasql.databases[alasql.useid];
if(!db.tables[tablename]){
...
transaction = function (cb) { var tx = new alasql.Transaction(this.databaseid); var res = cb(tx); return res; }
...
// console.trace();
var indexedDB = utils.global.indexedDB;
var ixdbid = alasql.databases[databaseid].ixdbid;
var request1 = indexedDB.open(ixdbid);
request1.onsuccess = function(event) {
var ixdb = event.target.result;
var tx = ixdb.transaction([tableid],"readwrite");
var tb = tx.objectStore(tableid);
for(var i=0, ilen = value.length;i<ilen;i++) {
tb.add(value[i]);
};
tx.oncomplete = function() {
ixdb.close();
...
Table = function (params){ // Step 1: Data array this.data = []; // Step 2: Columns this.columns = []; this.xcolumns = {}; // Step 3: indices this.inddefs = {}; this.indices = {}; this.uniqs = {}; this.uniqdefs = {}; // Step 4: identities this.identities = {}; // Step 5: checkfn... this.checks = []; this.checkfns = []; // For restore... to be done... // Step 6: INSERT/DELETE/UPDATE // Step 7: Triggers... // Create trigger hubs this.beforeinsert = {}; this.afterinsert = {}; this.insteadofinsert = {}; this.beforedelete = {}; this.afterdelete = {}; this.insteadofdelete = {}; this.beforeupdate = {}; this.afterupdate = {}; this.insteadofupdate = {}; // Done extend(this,params); }
...
this.$ = r;
break;
case 201:
if($$[$0-2] == 'INFORMATION_SCHEMA') {
this.$ = new yy.FuncValue({funcid: $$[$0-2], args:[new yy.StringValue({value:$$[$0]})]});
} else {
this.$ = new yy.Table({databaseid: $$[$0-2], tableid:$$[$0]});
}
break;
case 202:
this.$ = new yy.Table({tableid: $$[$0]});
break;
case 203: case 204:
this.$ = $$[$0-1]; $$[$0-1].push($$[$0]);
...
indexColumns = function () { var self = this; self.xcolumns = {}; self.columns.forEach(function(col){ self.xcolumns[col.columnid] = col; }); }
...
// CREATE TABLE
yy.Reindex.prototype.execute = function (databaseid,params,cb) {
// var self = this;
var db = alasql.databases[databaseid];
var indexid = this.indexid;
var tableid = db.indices[indexid];
var table = db.tables[tableid];
table.indexColumns();
var res = 1;
if(cb) res = cb(res);
return res;
};
/*
//
// DROP TABLE for Alasql.js
...
Transaction = function (databaseid) { this.transactionid = Date.now(); this.databaseid = databaseid; this.commited = false; this.dbversion = alasql.databases[databaseid].dbversion; // this.bank = cloneDeep(alasql.databases[databaseid]); this.bank = JSON.stringify(alasql.databases[databaseid]); // TODO CLone Tables with insertfns return this; }
...
//
// Transactio class for Alasql.js
// Date: 03.11.2014
// (c) 2014, Andrey Gershun
//
*/
Database.prototype.transaction = function(cb) {
var tx = new alasql.Transaction(this.databaseid);
var res = cb(tx);
return res;
};
// Transaction class (for WebSQL compatibility)
/**
Transaction class
@class Transaction
...
commit = function () { this.commited = true; alasql.databases[this.databaseid].dbversion = Date.now(); delete this.bank; }
...
yy.CommitTransaction = function (params) { return yy.extend(this, params); }
yy.CommitTransaction.prototype.toString = function() {
return 'COMMIT TRANSACTION';
}
yy.CommitTransaction.prototype.execute = function (databaseid,params, cb) {
var res = 1;
if(alasql.databases[databaseid].engineid) {
return alasql.engines[alasql.databases[alasql.useid].engineid].commit(databaseid, cb
);
} else {
// alasql commit!!!
}
if(cb) cb(res);
return res;
};
yy.RollbackTransaction = function (params) { return yy.extend(this, params); }
...
exec = function (sql, params, cb) { return alasql.dexec(this.databaseid,sql,params,cb); }
...
alasql('SELECT * FROM ?',[data],function(res){
console.log(data);
});
Call with scope for subquery (to pass common values):
var scope = {one:{a:2,b;20}}
alasql('SELECT * FROM ? two WHERE two.a = one.a',[data],null,scope);
Call for fluent interface with data object:
alasql(data).Where(function(x){return x.a == 10}).exec();
Call for fluent interface without data object:
alasql().From(data).Where(function(x){return x.a == 10}).exec();
*/
var alasql = function(sql, params, cb, scope) {
params = params||[];
...
executeSQL = function (sql, params, cb) { return alasql.dexec(this.databaseid,sql,params,cb); }
n/a
rollback = function () { if(!this.commited) { alasql.databases[this.databaseid] = JSON.parse(this.bank); // alasql.databases[this.databaseid].tables = this.bank; // alasql.databases[this.databaseid].dbversion = this.dbversion; delete this.bank; } else { throw new Error('Transaction already commited'); } }
...
yy.RollbackTransaction = function (params) { return yy.extend(this, params); }
yy.RollbackTransaction.prototype.toString = function() {
return 'ROLLBACK TRANSACTION';
}
yy.RollbackTransaction.prototype.execute = function (databaseid,params,cb) {
var res = 1;
if(alasql.databases[databaseid].engineid) {
return alasql.engines[alasql.databases[databaseid].engineid].rollback(databaseid, cb
);
} else {
// alasql commit!!!
}
if(cb) cb(res);
return res;
};
if(alasql.options.tsql) {
...
function Parser() { this.yy = {}; }
n/a
function commonjsMain(args) { if (!args[1]) { console.log('Usage: '+args[0]+' FILE'); process.exit(1); } var source = require('fs').readFileSync(require('path').normalize(args[1]), "utf8"); return exports.parser.parse(source); }
...
console.log('Usage: '+args[0]+' FILE');
process.exit(1);
}
var source = require('fs').readFileSync(require('path').normalize(args[1]), "utf8");
return exports.parser.parse(source);
};
if (typeof module !== 'undefined' && require.main === module) {
exports.main(process.argv.slice(1));
}
}
/**
12prettyflag.js - prettify
@todo move this functionality to plugin
*/
...
parse = function () { return parser.parse.apply(parser, arguments); }
...
var url = require('url');
var port = (process.argv[2] || 1337)|0;
if(!port) {
throw new Error('Wrong port number '+process.argv[3]);
}
http.createServer(function (req, res) {
var sql = decodeURI(url.parse(req.url).search).substr(1);
var a = '';
try {
a = alasql(sql);
} catch(err) {
a = err.toString();
};
res.writeHead(200, {'Content-Type': 'application/json'});
...
GROUP_CONCAT = function (v, s, stage){ if(stage == 1) { return v; } else if(stage == 2) { return s+','+v; } }
n/a
MEDIAN = function (v, s, stage){ if(stage === 2) { if(v === null){ return s; } s.push(v); return s; } else if(stage === 1) { if(v === null){ return []; } return [v]; } else { var p = s.sort(); return p[(p.length/2)|0]; }; }
n/a
STD = function (v, s, stage){ if(stage == 1 || stage == 2 ) { return alasql.aggr.VARP(v,s,stage); } else { return Math.sqrt(alasql.aggr.VARP(v,s,stage)); } }
n/a
STDDEV = function (v, s, stage){ if(stage == 1 || stage == 2 ) { return alasql.aggr.VARP(v,s,stage); } else { return Math.sqrt(alasql.aggr.VARP(v,s,stage)); } }
n/a
STDEV = function (v, s, stage){ if(stage === 1 || stage === 2 ) { return alasql.aggr.VAR(v,s,stage); } else { return Math.sqrt(alasql.aggr.VAR(v,s,stage)); } }
n/a
STDEVP = function (v, s, stage){ if(stage == 1 || stage == 2 ) { return alasql.aggr.VARP(v,s,stage); } else { return Math.sqrt(alasql.aggr.VARP(v,s,stage)); } }
n/a
VAR = function (v, s, stage){ if(stage === 1) { if(v === null){ return {arr:[],sum:0}; } return {arr:[v],sum:v}; } else if(stage === 2) { if(v === null){ return s; } s.arr.push(v); s.sum += v; return s; } else { var N = s.arr.length; var avg = s.sum / N; var std = 0; for(var i=0;i<N;i++) { std += (s.arr[i]-avg)*(s.arr[i]-avg); } std = std/(N-1); return std; } }
...
}
std = std/(N-1);
return std;
}
};
alasql.aggr.STDEV = function(v,s,stage){
if(stage === 1 || stage === 2 ) {
return alasql.aggr.VAR(v,s,stage);
} else {
return Math.sqrt(alasql.aggr.VAR(v,s,stage));
}
};
// Standard deviation
// alasql.aggr.VARP = function(v,s,acc){
// };
...
VARP = function (v, s, stage){ if(stage == 1) { return {arr:[v],sum:v}; } else if(stage == 2) { s.arr.push(v); s.sum += v; return s; } else { var N = s.arr.length; var avg = s.sum / N; var std = 0; for(var i=0;i<N;i++) { std += (s.arr[i]-avg)*(s.arr[i]-avg); } std = std/N; return std; } }
...
}
std = std/N;
return std;
}
};
alasql.aggr.STD = alasql.aggr.STDDEV = alasql.aggr.STDEVP = function(v,s,stage){
if(stage == 1 || stage == 2 ) {
return alasql.aggr.VARP(v,s,stage);
} else {
return Math.sqrt(alasql.aggr.VARP(v,s,stage));
}
};
// String functions
stdfn.REPLACE = function (target,pattern,replacement) {
return (target||'').split(pattern).join(replacement);
...
FILE = function (){}
n/a
FILESTORAGE = function (){}
n/a
INDEXEDDB = function (){}
n/a
LOCALSTORAGE = function (){}
n/a
SQLITE = function (){}
n/a
WEBSQL = function (){}
n/a
FILE = function (){}
n/a
attachDatabase = function (fsdbid, dbid, args, params, cb){ var res = 1; if(alasql.databases[dbid]) { throw new Error('Unable to attach database as "'+dbid+'" because it already exists'); }; var db = new alasql.Database(dbid || fsdbid); db.engineid = "FILESTORAGE"; // db.fsdbid = fsdbid; db.filename = args[0].value; loadFile(db.filename, !!cb, function(s){ try { db.data = JSON.parse(s); } catch(err) { throw new Error('Data in FileStorage database are corrupted'); } db.tables = db.data.tables; // IF AUTOCOMMIT IS OFF then copy data to memory if(!alasql.options.autocommit) { if(db.tables){ for(var tbid in db.tables) { db.tables[tbid].data = db.data[tbid]; } } } if(cb) res = cb(res); }); return res; }
...
return s;
}
//yy.CreateDatabase.prototype.compile = returnUndefined;
yy.AttachDatabase.prototype.execute = function (databaseid, params, cb) {
if(!alasql.engines[this.engineid]) {
throw new Error('Engine "'+this.engineid+'" is not defined.');
};
var res = alasql.engines[this.engineid].attachDatabase(this.databaseid, this.as, this
.args, params, cb);
return res;
};
// CREATE DATABASE databaseid
yy.DetachDatabase = function (params) { return yy.extend(this, params); };
yy.DetachDatabase.prototype.toString = function() {
var s = 'DETACH';
s += ' DATABASE'+' '+this.databaseid;
...
begin = function (databaseid, cb) { var db = alasql.databases[databaseid]; var fsdb = {tables:{}}; if(db.tables) { for(var tbid in db.tables) { db.data.tables[tbid] = {columns: db.tables[tbid].columns}; db.data[tbid] = db.tables[tbid].data; }; }; FS.updateFile(databaseid); return cb?cb(1):1; }
...
} else {
return "INITIAL";
}
},
// alias for begin(condition)
pushState:function pushState(condition) {
this.begin(condition);
},
// return the number of states currently on the stack
stateStackSize:function stateStackSize() {
return this.conditionStack.length;
},
options: {"case-insensitive":true},
...
commit = function (databaseid, cb) { var db = alasql.databases[databaseid]; var fsdb = {tables:{}}; if(db.tables) { for(var tbid in db.tables) { db.data.tables[tbid] = {columns: db.tables[tbid].columns}; db.data[tbid] = db.tables[tbid].data; }; }; FS.updateFile(databaseid); return cb?cb(1):1; }
...
yy.CommitTransaction = function (params) { return yy.extend(this, params); }
yy.CommitTransaction.prototype.toString = function() {
return 'COMMIT TRANSACTION';
}
yy.CommitTransaction.prototype.execute = function (databaseid,params, cb) {
var res = 1;
if(alasql.databases[databaseid].engineid) {
return alasql.engines[alasql.databases[alasql.useid].engineid].commit(databaseid, cb
);
} else {
// alasql commit!!!
}
if(cb) cb(res);
return res;
};
yy.RollbackTransaction = function (params) { return yy.extend(this, params); }
...
createDatabase = function (fsdbid, args, ifnotexists, dbid, cb){ var res = 1; var filename = args[0].value; alasql.utils.fileExists(filename, function(fex){ if(fex) { if(ifnotexists) { res = 0; if(cb) res = cb(res); return res; } else { throw new Error('Cannot create new database file, because it alreagy exists'); } } else { var data = {tables:{}}; alasql.utils.saveFile(filename,JSON.stringify(data),function(data){ if(cb) res = cb(res); }); } }); return res; }
...
var args;
if(this.args && this.args.length > 0) {
args = this.args.map(function(arg){
return new Function('params,alasql','var y;return '+arg.toJS())(params,alasql);
});
};
if(this.engineid) {
var res = alasql.engines[this.engineid].createDatabase(this.databaseid, this.args,
this.ifnotexists, this.as, cb);
return res;
} else {
var dbid = this.databaseid;
if(alasql.databases[dbid]) {
throw new Error("Database '"+dbid+"' already exists")
};
var a = new alasql.Database(dbid);
...
createTable = function (databaseid, tableid, ifnotexists, cb) { var db = alasql.databases[databaseid]; var tb = db.data[tableid]; var res = 1; if(tb && !ifnotexists) { throw new Error('Table "'+tableid+'" alsready exists in the database "'+fsdbid+'"'); }; var table = alasql.databases[databaseid].tables[tableid]; db.data.tables[tableid] = {columns:table.columns}; db.data[tableid] = []; FS.updateFile(databaseid); if(cb) cb(res); return res; }
...
}
//Used in 420from queryfn when table.view = true!
if(this.view && this.select) {
table.view = true;
table.select = this.select.compile(this.table.databaseid||databaseid);
}
if(db.engineid) {
return alasql.engines[db.engineid].createTable(this.table.databaseid || databaseid,
tableid, this.ifnotexists, cb);
}
// }
table.insert = function(r,orreplace) {
var oldinserted = alasql.inserted;
alasql.inserted = [r];
var table = this;
var toreplace = false; // For INSERT OR REPLACE
...
dropDatabase = function (fsdbid, ifexists, cb){ var res; var filename = fsdbid.value; alasql.utils.fileExists(filename, function(fex){ if(fex) { res = 1; alasql.utils.deleteFile(filename, function(){ res = 1; if(cb) res = cb(res); }); } else { if(!ifexists) { throw new Error('Cannot drop database file, because it does not exist'); } res = 0; if(cb) res = cb(res); } }); return res; }
...
if(this.ifexists) s += ' IF EXISTS';
s += ' DATABASE '+this.databaseid;
return s;
}
//yy.DropDatabase.prototype.compile = returnUndefined;
yy.DropDatabase.prototype.execute = function (databaseid, params, cb) {
if(this.engineid) {
return alasql.engines[this.engineid].dropDatabase(this.databaseid, this.ifexists, cb
);
}
var res;
var dbid = this.databaseid;
if(dbid == alasql.DEFAULTDATABASEID) {
throw new Error("Drop of default database is prohibited");
}
if(!alasql.databases[dbid]) {
...
dropTable = function (databaseid, tableid, ifexists, cb) { var res = 1; var db = alasql.databases[databaseid]; if(!ifexists && !db.tables[tableid]) { throw new Error('Cannot drop table "'+tableid+'" in fileStorage, because it does not exist'); }; delete db.tables[tableid]; delete db.data.tables[tableid]; delete db.data[tableid]; FS.updateFile(databaseid); if(cb) cb(res); return res; }
...
if(!ifexists || ifexists && db.tables[tableid]) {
if(!db.tables[tableid]) {
if(!alasql.options.dropifnotexists) {
throw new Error('Can not drop table \''+table.tableid+'\', because it does not exist in the database
.');
}
} else {
if(db.engineid /*&& alasql.options.autocommit*/) {
alasql.engines[db.engineid].dropTable(table.databaseid || databaseid, tableid, ifexists
, function(res1){
delete db.tables[tableid];
res+=res1;
count++;
if(count == tlen && cb) cb(res);
});
} else {
delete db.tables[tableid];
...
fromTable = function (databaseid, tableid, cb, idx, query) { var db = alasql.databases[databaseid]; var res = db.data[tableid]; if(cb) res = cb(res, idx, query); return res; }
...
// Get columns from table
source.columns = alasql.databases[source.databaseid].tables[source.tableid].columns;
if(alasql.options.autocommit && alasql.databases[source.databaseid].engineid &&
!alasql.databases[source.databaseid].tables[source.tableid].view
) {
// TODO -- make view for external engine
source.datafn = function(query,params,cb,idx, alasql) {
return alasql.engines[alasql.databases[source.databaseid].engineid].fromTable(
source.databaseid, source.tableid,cb,idx,query);
}
} else if(alasql.databases[source.databaseid].tables[source.tableid].view){
source.datafn = function(query,params,cb,idx, alasql) {
var res = alasql.databases[source.databaseid].tables[source.tableid].select(params);
if(cb) res = cb(res,idx,query);
return res;
...
intoTable = function (databaseid, tableid, value, columns, cb) { var db = alasql.databases[databaseid]; var res = value.length; var tb = db.data[tableid]; if(!tb) tb = []; db.data[tableid] = tb.concat(value); FS.updateFile(databaseid); if(cb) cb(res); return res; }
...
if(this.into instanceof yy.Table) {
//
// Save into the table in database
//
if(alasql.options.autocommit && alasql.databases[this.into.databaseid||databaseid].engineid) {
// For external database when AUTOCOMMIT is ONs
query.intoallfns = 'return alasql.engines["'+alasql.databases[this.into.databaseid||databaseid].engineid+'
;"]'+
'.intoTable("'+(this.into.databaseid||databaseid)+'",
x22;'+this.into.tableid+'",this.data, columns, cb);';
} else {
// Into AlaSQL tables
query.intofns =
'alasql.databases[\''+(this.into.databaseid||databaseid)+'\'].tables'+
'[\''+this.into.tableid+'\'].data.push(r);';
}
} else if(this.into instanceof yy.VarValue) {
...
loadTableData = function (databaseid, tableid){ var db = alasql.databases[databaseid]; db.tables[tableid].data = db.data[tableid]; }
...
} else {
var statement = function(params, cb) {
var db = alasql.databases[databaseid];
if(alasql.options.autocommit && db.engineid) {
alasql.engines[db.engineid].loadTableData(databaseid,tableid);
}
var res = insertfn(db,params,alasql);
if(alasql.options.autocommit && db.engineid) {
alasql.engines[db.engineid].saveTableData(databaseid,tableid);
}
...
rollback = function (databaseid, cb) { var res = 1; var db = alasql.databases[databaseid]; db.dbversion++; // var lsdbid = alasql.databases[databaseid].lsdbid; // lsdb = LS.get(lsdbid); wait(); function wait() { setTimeout(function(){ if(db.issaving) { return wait(); } else { alasql.loadFile(db.filename,!!cb,function(data){ db.data = data; db.tables = {}; for(var tbid in db.data.tables) { var tb = new alasql.Table({columns: db.data.tables[tbid].columns}); extend(tb,db.data.tables[tbid]); db.tables[tbid] = tb; if(!alasql.options.autocommit) { db.tables[tbid].data = db.data[tbid]; } db.tables[tbid].indexColumns(); // index columns // convert types } delete alasql.databases[databaseid]; alasql.databases[databaseid] = new alasql.Database(databaseid); extend(alasql.databases[databaseid], db); alasql.databases[databaseid].engineid = 'FILESTORAGE'; alasql.databases[databaseid].filename = db.filename; if(cb) res = cb(res); // Todo: check why no return }); }; },100); }; }
...
yy.RollbackTransaction = function (params) { return yy.extend(this, params); }
yy.RollbackTransaction.prototype.toString = function() {
return 'ROLLBACK TRANSACTION';
}
yy.RollbackTransaction.prototype.execute = function (databaseid,params,cb) {
var res = 1;
if(alasql.databases[databaseid].engineid) {
return alasql.engines[alasql.databases[databaseid].engineid].rollback(databaseid, cb
);
} else {
// alasql commit!!!
}
if(cb) cb(res);
return res;
};
if(alasql.options.tsql) {
...
saveTableData = function (databaseid, tableid){ var db = alasql.databases[databaseid]; db.data[tableid] = db.tables[tableid].data; db.tables[tableid].data = null; FS.updateFile(databaseid); }
...
if(alasql.options.autocommit && db.engineid) {
alasql.engines[db.engineid].loadTableData(databaseid,tableid);
}
var res = insertfn(db,params,alasql);
if(alasql.options.autocommit && db.engineid) {
alasql.engines[db.engineid].saveTableData(databaseid,tableid);
}
// var res = insertfn(db, params);
if(alasql.options.nocount) res = undefined;
if(cb) cb(res);
return res;
};
};
...
updateFile = function (databaseid) { var db = alasql.databases[databaseid]; if(db.issaving) { db.postsave = true; return; }; db.issaving = true; db.postsave = false; alasql.utils.saveFile(db.filename, JSON.stringify(db.data), function(){ db.issaving = false; if(db.postsave) { setTimeout(function(){ FS.updateFile(databaseid); },50); // TODO Test with different timeout parameters }; }); }
...
if(tb && !ifnotexists) {
throw new Error('Table "'+tableid+'" alsready exists in the database "'+fsdbid+'"
x27;);
};
var table = alasql.databases[databaseid].tables[tableid];
db.data.tables[tableid] = {columns:table.columns};
db.data[tableid] = [];
FS.updateFile(databaseid);
if(cb) cb(res);
return res;
};
FS.updateFile = function(databaseid) {
...
INDEXEDDB = function (){}
n/a
attachDatabase = function (ixdbid, dbid, args, params, cb) { if(!utils.hasIndexedDB){ throw new Error('The current browser does not support IndexedDB'); } var indexedDB = utils.global.indexedDB; var request1 = IDB.getDatabaseNames(); request1.onsuccess = function(event) { var dblist = event.target.result; if(!dblist.contains(ixdbid)){ throw new Error('IndexedDB: Cannot attach database "'+ixdbid+'" because it does not exist'); }; var request2 = indexedDB.open(ixdbid); request2.onsuccess = function(event) { var ixdb = event.target.result; var db = new alasql.Database(dbid || ixdbid); db.engineid = "INDEXEDDB"; db.ixdbid = ixdbid; db.tables = []; var tblist = ixdb.objectStoreNames; for(var i=0;i<tblist.length;i++){ db.tables[tblist[i]] = {}; }; event.target.result.close(); if(cb) cb(1); }; }; }
...
return s;
}
//yy.CreateDatabase.prototype.compile = returnUndefined;
yy.AttachDatabase.prototype.execute = function (databaseid, params, cb) {
if(!alasql.engines[this.engineid]) {
throw new Error('Engine "'+this.engineid+'" is not defined.');
};
var res = alasql.engines[this.engineid].attachDatabase(this.databaseid, this.as, this
.args, params, cb);
return res;
};
// CREATE DATABASE databaseid
yy.DetachDatabase = function (params) { return yy.extend(this, params); };
yy.DetachDatabase.prototype.toString = function() {
var s = 'DETACH';
s += ' DATABASE'+' '+this.databaseid;
...
createDatabase = function (ixdbid, args, ifnotexists, dbid, cb){ var indexedDB = utils.global.indexedDB; if(IDB.getDatabaseNamesNotSupported) { // Hack for Firefox if(ifnotexists) { var dbExists = true; var request2 = indexedDB.open(ixdbid); request2.onupgradeneeded = function (e){ dbExists = false; // e.target.transaction.abort(); // cb(0); }; request2.onsuccess = function(event) { event.target.result.close(); if(dbExists) { if(cb) cb(0); } else { if(cb) cb(1); } }; } else { var request1 = indexedDB.open(ixdbid); request1.onupgradeneeded = function (e){ e.target.transaction.abort(); }; request1.onabort = function(event) { if(cb) cb(1); }; request1.onsuccess = function(event) { event.target.result.close(); throw new Error('IndexedDB: Cannot create new database "'+ixdbid+'" because it already exists'); // cb(0); }; } } else { var request1 = IDB.getDatabaseNames(); request1.onsuccess = function(event) { var dblist = event.target.result; if(dblist.contains(ixdbid)){ if(ifnotexists) { if(cb) cb(0); return; } else { throw new Error('IndexedDB: Cannot create new database "'+ixdbid+'" because it already exists'); } }; var request2 = indexedDB.open(ixdbid,1); request2.onsuccess = function(event) { event.target.result.close(); if(cb) cb(1); }; }; } }
...
var args;
if(this.args && this.args.length > 0) {
args = this.args.map(function(arg){
return new Function('params,alasql','var y;return '+arg.toJS())(params,alasql);
});
};
if(this.engineid) {
var res = alasql.engines[this.engineid].createDatabase(this.databaseid, this.args,
this.ifnotexists, this.as, cb);
return res;
} else {
var dbid = this.databaseid;
if(alasql.databases[dbid]) {
throw new Error("Database '"+dbid+"' already exists")
};
var a = new alasql.Database(dbid);
...
createTable = function (databaseid, tableid, ifnotexists, cb) { var indexedDB = utils.global.indexedDB; var ixdbid = alasql.databases[databaseid].ixdbid; var request1 = IDB.getDatabaseNames(); request1.onsuccess = function(event) { var dblist = event.target.result; if(!dblist.contains(ixdbid)){ throw new Error('IndexedDB: Cannot create table in database "'+ixdbid+'" because it does not exist'); }; var request2 = indexedDB.open(ixdbid); request2.onversionchange = function(event) { event.target.result.close(); }; request2.onsuccess = function(event) { var version = event.target.result.version; event.target.result.close(); var request3 = indexedDB.open(ixdbid, version+1); request3.onupgradeneeded = function(event) { var ixdb = event.target.result; var store = ixdb.createObjectStore(tableid, {autoIncrement:true}); }; request3.onsuccess = function(event) { event.target.result.close(); if(cb) cb(1); }; request3.onerror = function(event){ throw event; } request3.onblocked = function(event){ throw new Error('Cannot create table "'+tableid+'" because database "'+databaseid+'" is blocked'); } }; }; }
...
}
//Used in 420from queryfn when table.view = true!
if(this.view && this.select) {
table.view = true;
table.select = this.select.compile(this.table.databaseid||databaseid);
}
if(db.engineid) {
return alasql.engines[db.engineid].createTable(this.table.databaseid || databaseid,
tableid, this.ifnotexists, cb);
}
// }
table.insert = function(r,orreplace) {
var oldinserted = alasql.inserted;
alasql.inserted = [r];
var table = this;
var toreplace = false; // For INSERT OR REPLACE
...
deleteFromTable = function (databaseid, tableid, wherefn, params, cb){ // console.trace(); var indexedDB = utils.global.indexedDB; var ixdbid = alasql.databases[databaseid].ixdbid; var request = indexedDB.open(ixdbid); request.onsuccess = function(event) { var res = []; var ixdb = event.target.result; var tx = ixdb.transaction([tableid], 'readwrite'); var store = tx.objectStore(tableid); var cur = store.openCursor(); var num = 0; cur.onblocked = function(event) { } cur.onerror = function(event) { } cur.onsuccess = function(event) { var cursor = event.target.result; if(cursor) { if((!wherefn) || wherefn(cursor.value,params)) { cursor.delete(); num++; } cursor.continue(); } else { ixdb.close(); if(cb) cb(num); } } } }
...
});
}
var wherefn = new Function('r,params,alasql','var y;return ('+this.where.toJS('r','')+
x27;)').bind(this);
statement = (function (params, cb) {
if(db.engineid && alasql.engines[db.engineid].deleteFromTable) {
return alasql.engines[db.engineid].deleteFromTable(databaseid, tableid, wherefn,
params, cb);
}
if(alasql.options.autocommit && db.engineid && db.engineid == 'LOCALSTORAGE') {
alasql.engines[db.engineid].loadTableData(databaseid,tableid);
}
var table = db.tables[tableid];
...
dropDatabase = function (ixdbid, ifexists, cb){ var indexedDB = utils.global.indexedDB; var request1 = IDB.getDatabaseNames(); request1.onsuccess = function(event) { var dblist = event.target.result; if(!dblist.contains(ixdbid)){ if(ifexists) { if(cb) cb(0); return; } else { throw new Error('IndexedDB: Cannot drop new database "'+ixdbid+'" because it does not exist'); } }; var request2 = indexedDB.deleteDatabase(ixdbid); request2.onsuccess = function(event) { if(cb) cb(1); } }; }
...
if(this.ifexists) s += ' IF EXISTS';
s += ' DATABASE '+this.databaseid;
return s;
}
//yy.DropDatabase.prototype.compile = returnUndefined;
yy.DropDatabase.prototype.execute = function (databaseid, params, cb) {
if(this.engineid) {
return alasql.engines[this.engineid].dropDatabase(this.databaseid, this.ifexists, cb
);
}
var res;
var dbid = this.databaseid;
if(dbid == alasql.DEFAULTDATABASEID) {
throw new Error("Drop of default database is prohibited");
}
if(!alasql.databases[dbid]) {
...
dropTable = function (databaseid, tableid, ifexists, cb) { var indexedDB = utils.global.indexedDB; var ixdbid = alasql.databases[databaseid].ixdbid; var request1 = IDB.getDatabaseNames(); request1.onsuccess = function(event) { var dblist = event.target.result; if(!dblist.contains(ixdbid)){ throw new Error('IndexedDB: Cannot drop table in database "'+ixdbid+'" because it does not exist'); } var request2 = indexedDB.open(ixdbid); request2.onversionchange = function(event) { event.target.result.close(); }; request2.onsuccess = function(event) { var version = event.target.result.version; event.target.result.close(); var request3 = indexedDB.open(ixdbid, version+1); request3.onupgradeneeded = function(event) { var ixdb = event.target.result; if(ixdb.objectStoreNames.contains(tableid)) { ixdb.deleteObjectStore(tableid); delete alasql.databases[databaseid].tables[tableid]; } else { if(!ifexists) { throw new Error('IndexedDB: Cannot drop table "'+tableid+'" because it does not exist'); } } }; request3.onsuccess = function(event) { event.target.result.close(); if(cb) cb(1); }; request3.onerror = function(event){ throw event; } request3.onblocked = function(event){ throw new Error('Cannot drop table "'+tableid+'" because database "'+databaseid+'" is blocked'); } }; }; }
...
if(!ifexists || ifexists && db.tables[tableid]) {
if(!db.tables[tableid]) {
if(!alasql.options.dropifnotexists) {
throw new Error('Can not drop table \''+table.tableid+'\', because it does not exist in the database
.');
}
} else {
if(db.engineid /*&& alasql.options.autocommit*/) {
alasql.engines[db.engineid].dropTable(table.databaseid || databaseid, tableid, ifexists
, function(res1){
delete db.tables[tableid];
res+=res1;
count++;
if(count == tlen && cb) cb(res);
});
} else {
delete db.tables[tableid];
...
fromTable = function (databaseid, tableid, cb, idx, query){ // console.trace(); var indexedDB = utils.global.indexedDB; var ixdbid = alasql.databases[databaseid].ixdbid; var request = indexedDB.open(ixdbid); request.onsuccess = function(event) { var res = []; var ixdb = event.target.result; var tx = ixdb.transaction([tableid]); var store = tx.objectStore(tableid); var cur = store.openCursor(); cur.onblocked = function(event) { } cur.onerror = function(event) { } cur.onsuccess = function(event) { var cursor = event.target.result; if(cursor) { res.push(cursor.value); cursor.continue(); } else { ixdb.close(); if(cb) cb(res, idx, query); } } } }
...
// Get columns from table
source.columns = alasql.databases[source.databaseid].tables[source.tableid].columns;
if(alasql.options.autocommit && alasql.databases[source.databaseid].engineid &&
!alasql.databases[source.databaseid].tables[source.tableid].view
) {
// TODO -- make view for external engine
source.datafn = function(query,params,cb,idx, alasql) {
return alasql.engines[alasql.databases[source.databaseid].engineid].fromTable(
source.databaseid, source.tableid,cb,idx,query);
}
} else if(alasql.databases[source.databaseid].tables[source.tableid].view){
source.datafn = function(query,params,cb,idx, alasql) {
var res = alasql.databases[source.databaseid].tables[source.tableid].select(params);
if(cb) res = cb(res,idx,query);
return res;
...
intoTable = function (databaseid, tableid, value, columns, cb) { // console.trace(); var indexedDB = utils.global.indexedDB; var ixdbid = alasql.databases[databaseid].ixdbid; var request1 = indexedDB.open(ixdbid); request1.onsuccess = function(event) { var ixdb = event.target.result; var tx = ixdb.transaction([tableid],"readwrite"); var tb = tx.objectStore(tableid); for(var i=0, ilen = value.length;i<ilen;i++) { tb.add(value[i]); }; tx.oncomplete = function() { ixdb.close(); if(cb) cb(ilen); } }; }
...
if(this.into instanceof yy.Table) {
//
// Save into the table in database
//
if(alasql.options.autocommit && alasql.databases[this.into.databaseid||databaseid].engineid) {
// For external database when AUTOCOMMIT is ONs
query.intoallfns = 'return alasql.engines["'+alasql.databases[this.into.databaseid||databaseid].engineid+'
;"]'+
'.intoTable("'+(this.into.databaseid||databaseid)+'",
x22;'+this.into.tableid+'",this.data, columns, cb);';
} else {
// Into AlaSQL tables
query.intofns =
'alasql.databases[\''+(this.into.databaseid||databaseid)+'\'].tables'+
'[\''+this.into.tableid+'\'].data.push(r);';
}
} else if(this.into instanceof yy.VarValue) {
...
showDatabases = function (like, cb) { var request = IDB.getDatabaseNames(); request.onsuccess = function(event) { var dblist = event.target.result; if(IDB.getDatabaseNamesNotSupported) { throw new Error('SHOW DATABASE is not supported in this browser'); } var res = []; if(like) { var relike = new RegExp((like.value).replace(/\%/g,'.*'),'g'); } for(var i=0;i<dblist.length;i++) { if(!like || dblist[i].match(relike)) { res.push({databaseid: dblist[i]}); } }; cb(res); }; }
...
yy.ShowDatabases.prototype.toString = function() {
var s = 'SHOW DATABASES';
if(this.like) s += 'LIKE '+this.like.toString();
return s;
}
yy.ShowDatabases.prototype.execute = function (databaseid, params, cb) {
if(this.engineid) {
return alasql.engines[this.engineid].showDatabases(this.like, cb);
} else {
var self = this;
var res = [];
for(dbid in alasql.databases) {
res.push({databaseid: dbid});
};
if(self.like && res && res.length > 0) {
...
updateTable = function (databaseid, tableid, assignfn, wherefn, params, cb){ // console.trace(); var indexedDB = utils.global.indexedDB; var ixdbid = alasql.databases[databaseid].ixdbid; var request = indexedDB.open(ixdbid); request.onsuccess = function(event) { var res = []; var ixdb = event.target.result; var tx = ixdb.transaction([tableid], 'readwrite'); var store = tx.objectStore(tableid); var cur = store.openCursor(); var num = 0; cur.onblocked = function(event) { } cur.onerror = function(event) { } cur.onsuccess = function(event) { var cursor = event.target.result; if(cursor) { if((!wherefn) || wherefn(cursor.value,params)) { var r = cursor.value; assignfn(r,params); cursor.update(r); num++; } cursor.continue(); } else { ixdb.close(); if(cb) cb(num); } } } }
...
this.columns.forEach(function(col){
s += 'r[\''+col.column.columnid+'\']='+col.expression.toJS('r','')+';
x27;;
});
var assignfn = new Function('r,params,alasql','var y;'+s);
var statement = function(params, cb) {
var db = alasql.databases[databaseid];
if(db.engineid && alasql.engines[db.engineid].updateTable) {
return alasql.engines[db.engineid].updateTable(databaseid, tableid, assignfn, wherefn
, params, cb);
}
if(alasql.options.autocommit && db.engineid) {
alasql.engines[db.engineid].loadTableData(databaseid,tableid);
}
var table = db.tables[tableid];
if(!table) {
throw new Error("Table '"+tableid+"' not exists")
...
LOCALSTORAGE = function (){}
n/a
attachDatabase = function (lsdbid, databaseid, args, params, cb){ var res = 1; if(alasql.databases[databaseid]) { throw new Error('Unable to attach database as "'+databaseid+'" because it already exists'); }; if(!databaseid) databaseid = lsdbid; var db = new alasql.Database(databaseid); db.engineid = "LOCALSTORAGE"; db.lsdbid = lsdbid; db.tables = LS.get(lsdbid).tables; // IF AUTOABORT IS OFF then copy data to memory if(!alasql.options.autocommit) { if(db.tables){ for(var tbid in db.tables) { LS.restoreTable(databaseid,tbid); } } } if(cb) res = cb(res); return res; }
...
return s;
}
//yy.CreateDatabase.prototype.compile = returnUndefined;
yy.AttachDatabase.prototype.execute = function (databaseid, params, cb) {
if(!alasql.engines[this.engineid]) {
throw new Error('Engine "'+this.engineid+'" is not defined.');
};
var res = alasql.engines[this.engineid].attachDatabase(this.databaseid, this.as, this
.args, params, cb);
return res;
};
// CREATE DATABASE databaseid
yy.DetachDatabase = function (params) { return yy.extend(this, params); };
yy.DetachDatabase.prototype.toString = function() {
var s = 'DETACH';
s += ' DATABASE'+' '+this.databaseid;
...
begin = function (databaseid, cb) { var db = alasql.databases[databaseid]; var lsdbid = alasql.databases[databaseid].lsdbid; var lsdb = {databaseid:lsdbid, tables:{}}; if(db.tables) { for(var tbid in db.tables) { // TODO: Question - do we need this line lsdb.tables[tbid] = true; LS.storeTable(databaseid,tbid); }; } LS.set(lsdbid,lsdb); return cb?cb(1):1; }
...
} else {
return "INITIAL";
}
},
// alias for begin(condition)
pushState:function pushState(condition) {
this.begin(condition);
},
// return the number of states currently on the stack
stateStackSize:function stateStackSize() {
return this.conditionStack.length;
},
options: {"case-insensitive":true},
...
commit = function (databaseid, cb) { var db = alasql.databases[databaseid]; var lsdbid = alasql.databases[databaseid].lsdbid; var lsdb = {databaseid:lsdbid, tables:{}}; if(db.tables) { for(var tbid in db.tables) { // TODO: Question - do we need this line lsdb.tables[tbid] = true; LS.storeTable(databaseid,tbid); }; } LS.set(lsdbid,lsdb); return cb?cb(1):1; }
...
yy.CommitTransaction = function (params) { return yy.extend(this, params); }
yy.CommitTransaction.prototype.toString = function() {
return 'COMMIT TRANSACTION';
}
yy.CommitTransaction.prototype.execute = function (databaseid,params, cb) {
var res = 1;
if(alasql.databases[databaseid].engineid) {
return alasql.engines[alasql.databases[alasql.useid].engineid].commit(databaseid, cb
);
} else {
// alasql commit!!!
}
if(cb) cb(res);
return res;
};
yy.RollbackTransaction = function (params) { return yy.extend(this, params); }
...
createDatabase = function (lsdbid, args, ifnotexists, databaseid, cb){ var res = 1; var ls = LS.get('alasql'); // Read list of all databases if(!(ifnotexists && ls && ls.databases && ls.databases[lsdbid])) { if(!ls) ls = {databases:{}}; // Empty record if(ls.databases && ls.databases[lsdbid]) { throw new Error('localStorage: Cannot create new database "'+lsdbid+'" because it already exists'); } ls.databases[lsdbid] = true; LS.set('alasql',ls); LS.set(lsdbid,{databaseid:lsdbid, tables:{}}); // Create database record } else { res = 0; } if(cb) res = cb(res); return res; }
...
var args;
if(this.args && this.args.length > 0) {
args = this.args.map(function(arg){
return new Function('params,alasql','var y;return '+arg.toJS())(params,alasql);
});
};
if(this.engineid) {
var res = alasql.engines[this.engineid].createDatabase(this.databaseid, this.args,
this.ifnotexists, this.as, cb);
return res;
} else {
var dbid = this.databaseid;
if(alasql.databases[dbid]) {
throw new Error("Database '"+dbid+"' already exists")
};
var a = new alasql.Database(dbid);
...
createTable = function (databaseid, tableid, ifnotexists, cb) { var res = 1; var lsdbid = alasql.databases[databaseid].lsdbid; var tb = LS.get(lsdbid+'.'+tableid); // Check if such record exists if(tb && !ifnotexists) { throw new Error('Table "'+tableid+'" alsready exists in localStorage database "'+lsdbid+'"'); }; var lsdb = LS.get(lsdbid); var table = alasql.databases[databaseid].tables[tableid]; // TODO: Check if required lsdb.tables[tableid] = true; LS.set(lsdbid, lsdb); LS.storeTable(databaseid,tableid); if(cb) res = cb(res); return res; }
...
}
//Used in 420from queryfn when table.view = true!
if(this.view && this.select) {
table.view = true;
table.select = this.select.compile(this.table.databaseid||databaseid);
}
if(db.engineid) {
return alasql.engines[db.engineid].createTable(this.table.databaseid || databaseid,
tableid, this.ifnotexists, cb);
}
// }
table.insert = function(r,orreplace) {
var oldinserted = alasql.inserted;
alasql.inserted = [r];
var table = this;
var toreplace = false; // For INSERT OR REPLACE
...
dropDatabase = function (lsdbid, ifexists, cb){ var res = 1; var ls = LS.get('alasql'); if(!(ifexists && ls && ls.databases && !ls.databases[lsdbid])) { // 1. Remove record from 'alasql' record if(!ls) { if(!ifexists) { throw new Error('There is no any AlaSQL databases in localStorage'); } else { return cb?cb(0):0; } }; if(ls.databases && !ls.databases[lsdbid]) { throw new Error('localStorage: Cannot drop database "'+lsdbid+'" because there is no such database'); } delete ls.databases[lsdbid]; LS.set('alasql',ls); // 2. Remove tables definitions var db = LS.get(lsdbid); for(var tableid in db.tables) { localStorage.removeItem(lsdbid+'.'+tableid); } // 3. Remove database definition localStorage.removeItem(lsdbid); } else { res = 0; } if(cb) res = cb(res); return res; }
...
if(this.ifexists) s += ' IF EXISTS';
s += ' DATABASE '+this.databaseid;
return s;
}
//yy.DropDatabase.prototype.compile = returnUndefined;
yy.DropDatabase.prototype.execute = function (databaseid, params, cb) {
if(this.engineid) {
return alasql.engines[this.engineid].dropDatabase(this.databaseid, this.ifexists, cb
);
}
var res;
var dbid = this.databaseid;
if(dbid == alasql.DEFAULTDATABASEID) {
throw new Error("Drop of default database is prohibited");
}
if(!alasql.databases[dbid]) {
...
dropTable = function (databaseid, tableid, ifexists, cb) { var res = 1; var lsdbid = alasql.databases[databaseid].lsdbid; if(alasql.options.autocommit) { var lsdb = LS.get(lsdbid); } else { var lsdb = alasql.databases[databaseid]; } if(!ifexists && !lsdb.tables[tableid]) { throw new Error('Cannot drop table "'+tableid+'" in localStorage, because it does not exist'); }; delete lsdb.tables[tableid]; LS.set(lsdbid, lsdb); // localStorage.removeItem(lsdbid+'.'+tableid); LS.removeTable(databaseid,tableid); if(cb) res = cb(res); return res; }
...
if(!ifexists || ifexists && db.tables[tableid]) {
if(!db.tables[tableid]) {
if(!alasql.options.dropifnotexists) {
throw new Error('Can not drop table \''+table.tableid+'\', because it does not exist in the database
.');
}
} else {
if(db.engineid /*&& alasql.options.autocommit*/) {
alasql.engines[db.engineid].dropTable(table.databaseid || databaseid, tableid, ifexists
, function(res1){
delete db.tables[tableid];
res+=res1;
count++;
if(count == tlen && cb) cb(res);
});
} else {
delete db.tables[tableid];
...
fromTable = function (databaseid, tableid, cb, idx, query) { var lsdbid = alasql.databases[databaseid].lsdbid; // var res = LS.get(lsdbid+'.'+tableid); var res = LS.restoreTable(databaseid,tableid).data; if(cb) res = cb(res, idx, query); return res; }
...
// Get columns from table
source.columns = alasql.databases[source.databaseid].tables[source.tableid].columns;
if(alasql.options.autocommit && alasql.databases[source.databaseid].engineid &&
!alasql.databases[source.databaseid].tables[source.tableid].view
) {
// TODO -- make view for external engine
source.datafn = function(query,params,cb,idx, alasql) {
return alasql.engines[alasql.databases[source.databaseid].engineid].fromTable(
source.databaseid, source.tableid,cb,idx,query);
}
} else if(alasql.databases[source.databaseid].tables[source.tableid].view){
source.datafn = function(query,params,cb,idx, alasql) {
var res = alasql.databases[source.databaseid].tables[source.tableid].select(params);
if(cb) res = cb(res,idx,query);
return res;
...
get = function (key) { var s = localStorage.getItem(key); if(typeof s === "undefined") return; var v = undefined; try { v = JSON.parse(s); } catch(err) { throw new Error('Cannot parse JSON object from localStorage'+s); } return v; }
...
Restore table structure and data
@param databaseid {string} AlaSQL database id (not external localStorage)
@param tableid {string} Table name
@return Nothing
*/
LS.restoreTable = function(databaseid,tableid) {
var db = alasql.databases[databaseid];
var tbl = LS.get(db.lsdbid+'.'+tableid);
var table = new alasql.Table();
for(var f in tbl) {
table[f] = tbl[f];
}
db.tables[tableid] = table;
table.indexColumns();
// We need to add other things here
...
intoTable = function (databaseid, tableid, value, columns, cb) { var lsdbid = alasql.databases[databaseid].lsdbid; var res = value.length; // var tb = LS.get(lsdbid+'.'+tableid); var tb = LS.restoreTable(databaseid,tableid); if(!tb.data) tb.data = []; tb.data = tb.data.concat(value); // LS.set(lsdbid+'.'+tableid, tb); LS.storeTable(databaseid,tableid); if(cb) res = cb(res); return res; }
...
if(this.into instanceof yy.Table) {
//
// Save into the table in database
//
if(alasql.options.autocommit && alasql.databases[this.into.databaseid||databaseid].engineid) {
// For external database when AUTOCOMMIT is ONs
query.intoallfns = 'return alasql.engines["'+alasql.databases[this.into.databaseid||databaseid].engineid+'
;"]'+
'.intoTable("'+(this.into.databaseid||databaseid)+'",
x22;'+this.into.tableid+'",this.data, columns, cb);';
} else {
// Into AlaSQL tables
query.intofns =
'alasql.databases[\''+(this.into.databaseid||databaseid)+'\'].tables'+
'[\''+this.into.tableid+'\'].data.push(r);';
}
} else if(this.into instanceof yy.VarValue) {
...
loadTableData = function (databaseid, tableid){ var db = alasql.databases[databaseid]; var lsdbid = alasql.databases[databaseid].lsdbid; LS.restoreTable(databaseid,tableid); // db.tables[tableid].data = LS.get(lsdbid+'.'+tableid); }
...
} else {
var statement = function(params, cb) {
var db = alasql.databases[databaseid];
if(alasql.options.autocommit && db.engineid) {
alasql.engines[db.engineid].loadTableData(databaseid,tableid);
}
var res = insertfn(db,params,alasql);
if(alasql.options.autocommit && db.engineid) {
alasql.engines[db.engineid].saveTableData(databaseid,tableid);
}
...
removeTable = function (databaseid, tableid) { var db = alasql.databases[databaseid]; localStorage.removeItem(db.lsdbid+'.'+tableid); }
...
}
if(!ifexists && !lsdb.tables[tableid]) {
throw new Error('Cannot drop table "'+tableid+'" in localStorage, because it does not exist');
};
delete lsdb.tables[tableid];
LS.set(lsdbid, lsdb);
// localStorage.removeItem(lsdbid+'.'+tableid);
LS.removeTable(databaseid,tableid);
if(cb) res = cb(res);
return res;
}
/**
Read all data from table
*/
...
restoreTable = function (databaseid, tableid) { var db = alasql.databases[databaseid]; var tbl = LS.get(db.lsdbid+'.'+tableid); var table = new alasql.Table(); for(var f in tbl) { table[f] = tbl[f]; } db.tables[tableid] = table; table.indexColumns(); // We need to add other things here return table; }
...
db.engineid = "LOCALSTORAGE";
db.lsdbid = lsdbid;
db.tables = LS.get(lsdbid).tables;
// IF AUTOABORT IS OFF then copy data to memory
if(!alasql.options.autocommit) {
if(db.tables){
for(var tbid in db.tables) {
LS.restoreTable(databaseid,tbid);
}
}
}
if(cb) res = cb(res);
return res;
};
...
rollback = function (databaseid, cb) { // This does not work and should be fixed // Plus test 151 and 231 return; var db = alasql.databases[databaseid]; db.dbversion++; var lsdbid = alasql.databases[databaseid].lsdbid; var lsdb = LS.get(lsdbid); // if(!alasql.options.autocommit) { delete alasql.databases[databaseid]; alasql.databases[databaseid] = new alasql.Database(databaseid); extend(alasql.databases[databaseid], lsdb); alasql.databases[databaseid].databaseid = databaseid; alasql.databases[databaseid].engineid = 'LOCALSTORAGE'; if(lsdb.tables){ for(var tbid in lsdb.tables) { LS.restoreTable(databaseid,tbid); // index columns // convert types } } // } }
...
yy.RollbackTransaction = function (params) { return yy.extend(this, params); }
yy.RollbackTransaction.prototype.toString = function() {
return 'ROLLBACK TRANSACTION';
}
yy.RollbackTransaction.prototype.execute = function (databaseid,params,cb) {
var res = 1;
if(alasql.databases[databaseid].engineid) {
return alasql.engines[alasql.databases[databaseid].engineid].rollback(databaseid, cb
);
} else {
// alasql commit!!!
}
if(cb) cb(res);
return res;
};
if(alasql.options.tsql) {
...
saveTableData = function (databaseid, tableid){ var db = alasql.databases[databaseid]; var lsdbid = alasql.databases[databaseid].lsdbid; LS.storeTable(lsdbid,tableid); // LS.set(lsdbid+'.'+tableid,db.tables[tableid].data); db.tables[tableid].data = undefined; }
...
if(alasql.options.autocommit && db.engineid) {
alasql.engines[db.engineid].loadTableData(databaseid,tableid);
}
var res = insertfn(db,params,alasql);
if(alasql.options.autocommit && db.engineid) {
alasql.engines[db.engineid].saveTableData(databaseid,tableid);
}
// var res = insertfn(db, params);
if(alasql.options.nocount) res = undefined;
if(cb) cb(res);
return res;
};
};
...
set = function (key, value){ if(typeof value === 'undefined') localStorage.removeItem(key); else localStorage.setItem(key,JSON.stringify(value)); }
...
var table = db.tables[tableid];
// Create empty structure for table
var tbl = {};
tbl.columns = table.columns;
tbl.data = table.data;
tbl.identities = table.identities;
// TODO: May be add indexes, objects and other fields?
LS.set(db.lsdbid+'.'+tableid,tbl);
};
/**
Restore table structure and data
@param databaseid {string} AlaSQL database id (not external localStorage)
@param tableid {string} Table name
@return Nothing
...
showDatabases = function (like, cb) { var res = []; var ls = LS.get('alasql'); if(like) { // TODO: If we have a special function for LIKE patterns? var relike = new RegExp(like.value.replace(/\%/g,'.*'),'g'); } if(ls && ls.databases) { for(dbid in ls.databases) { res.push({databaseid: dbid}); }; if(like && res && res.length > 0) { res = res.filter(function(d){ return d.databaseid.match(relike); }); } }; if(cb) res=cb(res); return res; }
...
yy.ShowDatabases.prototype.toString = function() {
var s = 'SHOW DATABASES';
if(this.like) s += 'LIKE '+this.like.toString();
return s;
}
yy.ShowDatabases.prototype.execute = function (databaseid, params, cb) {
if(this.engineid) {
return alasql.engines[this.engineid].showDatabases(this.like, cb);
} else {
var self = this;
var res = [];
for(dbid in alasql.databases) {
res.push({databaseid: dbid});
};
if(self.like && res && res.length > 0) {
...
storeTable = function (databaseid, tableid) { var db = alasql.databases[databaseid]; var table = db.tables[tableid]; // Create empty structure for table var tbl = {}; tbl.columns = table.columns; tbl.data = table.data; tbl.identities = table.identities; // TODO: May be add indexes, objects and other fields? LS.set(db.lsdbid+'.'+tableid,tbl); }
...
var lsdb = LS.get(lsdbid);
var table = alasql.databases[databaseid].tables[tableid];
// TODO: Check if required
lsdb.tables[tableid] = true;
LS.set(lsdbid, lsdb);
LS.storeTable(databaseid,tableid);
if(cb) res = cb(res);
return res;
}
/**
Empty table and reset identities
...
truncateTable = function (databaseid, tableid, ifexists, cb){ var res = 1 var lsdbid = alasql.databases[databaseid].lsdbid; if(alasql.options.autocommit) { var lsdb = LS.get(lsdbid); } else { var lsdb = alasql.databases[databaseid]; } if(!ifexists && !lsdb.tables[tableid]) { throw (new Error('Cannot truncate table "'+tableid+'" in localStorage, because it does not exist')); }; //load table var tbl = LS.restoreTable(databaseid,tableid); //clear data from table tbl.data = []; //TODO reset all identities //but identities are not working on LOCALSTORAGE //See test 607 for details //store table LS.storeTable(databaseid,tableid); if(cb) res = cb(res); return res; }
...
s += ' '+this.table.toString();
return s;
};
yy.TruncateTable.prototype.execute = function (databaseid, params, cb) {
var db = alasql.databases[this.table.databaseid || databaseid];
var tableid = this.table.tableid;
if(db.engineid) {
return alasql.engines[db.engineid].truncateTable(this.table.databaseid || databaseid
,tableid, this.ifexists, cb);
}
if(db.tables[tableid]) {
db.tables[tableid].data = [];
} else {
throw new Error('Cannot truncate table becaues it does not exist');
}
return cb?cb(0):0;
...
SQLITE = function (){}
n/a
attachDatabase = function (sqldbid, dbid, args, params, cb){ var res = 1; if(alasql.databases[dbid]) { throw new Error('Unable to attach database as "'+dbid+'" because it already exists'); }; if(args[0] && (args[0] instanceof yy.StringValue) || (args[0] instanceof yy.ParamValue)) { if(args[0] instanceof yy.StringValue) { var value = args[0].value; } else if(args[0] instanceof yy.ParamValue) { var value = params[args[0].param]; } alasql.utils.loadBinaryFile(value,true,function(data){ var db = new alasql.Database(dbid || sqldbid); db.engineid = "SQLITE"; db.sqldbid = sqldbid; var sqldb = db.sqldb = new SQL.Database(data); db.tables = []; var tables = sqldb.exec("SELECT * FROM sqlite_master WHERE type='table'")[0].values; tables.forEach(function(tbl){ db.tables[tbl[1]] = {}; var columns = db.tables[tbl[1]].columns = []; var ast = alasql.parse(tbl[4]); var coldefs = ast.statements[0].columns; if(coldefs && coldefs.length>0) { coldefs.forEach(function(cd){ columns.push(cd); }); } }); cb(1); }, function(err){ throw new Error('Cannot open SQLite database file "'+args[0].value+'"'); }) return res; } else { throw new Error('Cannot attach SQLite database without a file'); }; return res; }
...
return s;
}
//yy.CreateDatabase.prototype.compile = returnUndefined;
yy.AttachDatabase.prototype.execute = function (databaseid, params, cb) {
if(!alasql.engines[this.engineid]) {
throw new Error('Engine "'+this.engineid+'" is not defined.');
};
var res = alasql.engines[this.engineid].attachDatabase(this.databaseid, this.as, this
.args, params, cb);
return res;
};
// CREATE DATABASE databaseid
yy.DetachDatabase = function (params) { return yy.extend(this, params); };
yy.DetachDatabase.prototype.toString = function() {
var s = 'DETACH';
s += ' DATABASE'+' '+this.databaseid;
...
createDatabase = function (wdbid, args, ifnotexists, dbid, cb){ throw new Error('Connot create SQLITE database in memory. Attach it.'); }
...
var args;
if(this.args && this.args.length > 0) {
args = this.args.map(function(arg){
return new Function('params,alasql','var y;return '+arg.toJS())(params,alasql);
});
};
if(this.engineid) {
var res = alasql.engines[this.engineid].createDatabase(this.databaseid, this.args,
this.ifnotexists, this.as, cb);
return res;
} else {
var dbid = this.databaseid;
if(alasql.databases[dbid]) {
throw new Error("Database '"+dbid+"' already exists")
};
var a = new alasql.Database(dbid);
...
dropDatabase = function (databaseid){ throw new Error('This is impossible to drop SQLite database. Detach it.'); }
...
if(this.ifexists) s += ' IF EXISTS';
s += ' DATABASE '+this.databaseid;
return s;
}
//yy.DropDatabase.prototype.compile = returnUndefined;
yy.DropDatabase.prototype.execute = function (databaseid, params, cb) {
if(this.engineid) {
return alasql.engines[this.engineid].dropDatabase(this.databaseid, this.ifexists, cb
);
}
var res;
var dbid = this.databaseid;
if(dbid == alasql.DEFAULTDATABASEID) {
throw new Error("Drop of default database is prohibited");
}
if(!alasql.databases[dbid]) {
...
fromTable = function (databaseid, tableid, cb, idx, query){ var data = alasql.databases[databaseid].sqldb.exec("SELECT * FROM "+tableid); var columns = query.sources[idx].columns = []; if(data[0].columns.length > 0) { data[0].columns.forEach(function(columnid) { columns.push({columnid:columnid}); }); }; var res = []; if(data[0].values.length > 0) { data[0].values.forEach(function(d){ var r = {}; columns.forEach(function(col,idx){ r[col.columnid] = d[idx]; }); res.push(r); }); } if(cb) cb(res, idx, query); }
...
// Get columns from table
source.columns = alasql.databases[source.databaseid].tables[source.tableid].columns;
if(alasql.options.autocommit && alasql.databases[source.databaseid].engineid &&
!alasql.databases[source.databaseid].tables[source.tableid].view
) {
// TODO -- make view for external engine
source.datafn = function(query,params,cb,idx, alasql) {
return alasql.engines[alasql.databases[source.databaseid].engineid].fromTable(
source.databaseid, source.tableid,cb,idx,query);
}
} else if(alasql.databases[source.databaseid].tables[source.tableid].view){
source.datafn = function(query,params,cb,idx, alasql) {
var res = alasql.databases[source.databaseid].tables[source.tableid].select(params);
if(cb) res = cb(res,idx,query);
return res;
...
intoTable = function (databaseid, tableid, value, columns, cb) { var sqldb = alasql.databases[databaseid].sqldb; for(var i=0, ilen = value.length;i<ilen;i++) { var s = "INSERT INTO "+tableid+" ("; var d = value[i]; var keys = Object.keys(d); s += keys.join(","); s += ") VALUES ("; s += keys.map(function(k){ v = d[k]; if(typeof v == 'string') v = "'"+v+"'"; return v; }).join(","); s += ")"; sqldb.exec(s); }; var res = ilen; if(cb) cb(res); return res; }
...
if(this.into instanceof yy.Table) {
//
// Save into the table in database
//
if(alasql.options.autocommit && alasql.databases[this.into.databaseid||databaseid].engineid) {
// For external database when AUTOCOMMIT is ONs
query.intoallfns = 'return alasql.engines["'+alasql.databases[this.into.databaseid||databaseid].engineid+'
;"]'+
'.intoTable("'+(this.into.databaseid||databaseid)+'",
x22;'+this.into.tableid+'",this.data, columns, cb);';
} else {
// Into AlaSQL tables
query.intofns =
'alasql.databases[\''+(this.into.databaseid||databaseid)+'\'].tables'+
'[\''+this.into.tableid+'\'].data.push(r);';
}
} else if(this.into instanceof yy.VarValue) {
...
WEBSQL = function (){}
n/a
attachDatabase = function (databaseid, dbid, args, params, cb){ var res = 1; if(alasql.databases[dbid]) { throw new Error('Unable to attach database as "'+dbid+'" because it already exists'); }; alasqlopenDatabase(databaseid, args[0], args[1], args[2]); return res; }
...
return s;
}
//yy.CreateDatabase.prototype.compile = returnUndefined;
yy.AttachDatabase.prototype.execute = function (databaseid, params, cb) {
if(!alasql.engines[this.engineid]) {
throw new Error('Engine "'+this.engineid+'" is not defined.');
};
var res = alasql.engines[this.engineid].attachDatabase(this.databaseid, this.as, this
.args, params, cb);
return res;
};
// CREATE DATABASE databaseid
yy.DetachDatabase = function (params) { return yy.extend(this, params); };
yy.DetachDatabase.prototype.toString = function() {
var s = 'DETACH';
s += ' DATABASE'+' '+this.databaseid;
...
createDatabase = function (wdbid, args, dbid, cb){ var res = 1; var wdb = openDatabase(wdbid, args[0], args[1], args[2]); if(this.dbid) { var db = alasql.createDatabase(this.dbid); db.engineid = 'WEBSQL'; db.wdbid = wdbid; sb.wdb = db; } if(!wdb) { throw new Error('Cannot create WebSQL database "'+databaseid+'"') } if(cb) cb(res); return res; }
...
var args;
if(this.args && this.args.length > 0) {
args = this.args.map(function(arg){
return new Function('params,alasql','var y;return '+arg.toJS())(params,alasql);
});
};
if(this.engineid) {
var res = alasql.engines[this.engineid].createDatabase(this.databaseid, this.args,
this.ifnotexists, this.as, cb);
return res;
} else {
var dbid = this.databaseid;
if(alasql.databases[dbid]) {
throw new Error("Database '"+dbid+"' already exists")
};
var a = new alasql.Database(dbid);
...
dropDatabase = function (databaseid){ throw new Error('This is impossible to drop WebSQL database.'); }
...
if(this.ifexists) s += ' IF EXISTS';
s += ' DATABASE '+this.databaseid;
return s;
}
//yy.DropDatabase.prototype.compile = returnUndefined;
yy.DropDatabase.prototype.execute = function (databaseid, params, cb) {
if(this.engineid) {
return alasql.engines[this.engineid].dropDatabase(this.databaseid, this.ifexists, cb
);
}
var res;
var dbid = this.databaseid;
if(dbid == alasql.DEFAULTDATABASEID) {
throw new Error("Drop of default database is prohibited");
}
if(!alasql.databases[dbid]) {
...
function FileStorage(path, opts) { var self = this; opts = opts || {}; var db ; Object.defineProperty(this, '___priv_bk___', { value: { path: path } , writable: false , enumerable: false }); Object.defineProperty(this, '___priv_strict___', { value: !!opts.strict , writable: false , enumerable: false }); Object.defineProperty(this, '___priv_ws___', { value: opts.ws || ' ' , writable: false , enumerable: false }); loadFile(path,true,function(data){ try { db = JSON.parse(data); } catch(e) { db = {}; } Object.keys(db).forEach(function (key) { self[key] = db[key]; }, self); }); }
...
var fst = require('./filestorage.js');
var f = new fst.FileStorage('./test.json',{ strict: false, ws: '' });
f.setItem('aaa',{a:1,b:1});
...
function Boolean() { [native code] }
n/a
function Date() { [native code] }
n/a
function Number() { [native code] }
n/a
function String() { [native code] }
n/a
function String() { [native code] }
n/a
entityify = function (){return this.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">" )}
n/a
isAlpha = function ( ){return this>="a"&&this<="z\uffff"||this>="A"&&this<="Z\uffff"}
n/a
isDigit = function (){return this>="0"&& this<="9"}
n/a
supplant = function (e){return this.replace(/\{([^{}]*)\}/g,function(t,n){var r=e[n];return typeof r=="string"||typeof r=="number"?r:t})}
n/a
CSV = function (contents, opts, cb, idx, query) { var opt = { separator: ',', quote: '"', headers:true }; alasql.utils.extend(opt, opts); var res; var hs = []; function parseText(text) { var delimiterCode = opt.separator.charCodeAt(0); var quoteCode = opt.quote.charCodeAt(0); var EOL = {}, EOF = {}, rows = [], N = text.length, I = 0, n = 0, t, eol; function token() { if (I >= N){ return EOF; } if (eol){ return eol = false, EOL; } var j = I; if (text.charCodeAt(j) === quoteCode) { var i = j; while (i++ < N) { if (text.charCodeAt(i) === quoteCode) { if (text.charCodeAt(i + 1) !== quoteCode){ break; } ++i; } } I = i + 2; var c = text.charCodeAt(i + 1); if (c === 13) { eol = true; if (text.charCodeAt(i + 2) === 10){ ++I; } } else if (c === 10) { eol = true; } return text.substring(j + 1, i).replace(/""/g, '"'); } while (I < N) { var c = text.charCodeAt(I++), k = 1; if(c === 10){ eol = true; } else if (c === 13) { eol = true; if (text.charCodeAt(I) === 10){ ++I; ++k; } } else if(c !== delimiterCode){ continue; } return text.substring(j, I - k); } return text.substring(j); } while ((t = token()) !== EOF) { var a = []; while (t !== EOL && t !== EOF) { a.push(t.trim()); t = token(); } if(opt.headers) { if(n === 0) { if(typeof opt.headers === 'boolean') { hs = a; } else if(Array.isArray(opt.headers)) { hs = opt.headers; var r = {}; hs.forEach(function(h,idx){ r[h] = a[idx]; // Please avoid === here if((typeof r[h] !== 'undefined') && r[h].length !== 0 && (r[h]).trim() == +r[h]){ // jshint ignore:line r[h] = +r[h]; } }); rows.push(r); } } else { var r = {}; hs.forEach(function(h,idx){ r[h] = a[idx]; if((typeof r[h] !== 'undefined') && r[h].length !== 0 && r[h].trim() == +r[h]){ // jshint ignore:line r[h] = +r[h]; } }); rows.push(r); } n++; } else { rows.push(a); } } res = rows; if(opt.headers) { if(query && query.sources && query.sources[idx]) { var columns = query.sources[idx].columns = []; hs.forEach(function(h){ columns.push({columnid:h}); }); } } if(cb){ res = cb(res, idx, query); } } if( (new RegExp("\n")).test(contents) ) { parseText(contents) } else { contents = alasql.utils.autoExtFilename(contents,'csv',opts); alasql.utils.loadFile(contents,!!cb,parseText); } return res; }
...
alasql.into.TAB = alasql.into.TSV = function(filename, opts, data, columns, cb) {
var opt = {};
alasql.utils.extend(opt, opts);
opt.separator = '\t';
filename = alasql.utils.autoExtFilename(filename,'tab',opts);
opt.autoExt = false;
return alasql.into.CSV(filename, opt, data, columns, cb);
}
alasql.into.CSV = function(filename, opts, data, columns, cb) {
if(columns.length === 0 && data.length > 0) {
columns = Object.keys(data[0]).map(function(columnid){return {columnid:columnid}});
}
if(typeof filename === 'object') {
...
FILE = function (filename, opts, cb, idx, query) { var fname; if(typeof filename === 'string') { fname = filename; } else if(filename instanceof Event) { fname = filename.target.files[0].name; } else { throw new Error("Wrong usage of FILE() function"); } var parts = fname.split('.'); var ext = parts[parts.length-1].toUpperCase(); if(alasql.from[ext]) { return alasql.from[ext](filename, opts, cb, idx, query); } else { throw new Error('Cannot recognize file type for loading'); } }
n/a
GEXF = function (filename, opts, cb, idx, query) { var res; alasql('SEARCH FROM XML('+filename+')',[],function(data){ res = data; console.log(res); if(cb) res=cb(res); }); return res; }
n/a
HTML = function (selector, opts, cb, idx, query) { var opt = {}; alasql.utils.extend(opt, opts); var sel = document.querySelector(selector); if(!sel && sel.tagName !== "TABLE") { throw new Error('Selected HTML element is not a TABLE'); } var res = []; var headers = opt.headers; if(headers && !(Array.isArray(headers))) { headers = []; var ths = sel.querySelector("thead tr").children; for(var i=0;i<ths.length;i++){ if(!(ths.item(i).style && ths.item(i).style.display === "none" && opt.skipdisplaynone)) { headers.push(ths.item(i).textContent); } else { headers.push(undefined); } } } var trs = sel.querySelectorAll("tbody tr"); for(var j=0;j<trs.length;j++) { var tds = trs.item(j).children; var r = {}; for(var i=0;i<tds.length;i++){ if(!(tds.item(i).style && tds.item(i).style.display === "none" && opt.skipdisplaynone)) { if(headers) { r[headers[i]] = tds.item(i).textContent; } else { r[i] = tds.item(i).textContent; } } } res.push(r); } if(cb){ res = cb(res, idx, query); } return res; }
n/a
INFORMATION_SCHEMA = function (filename, opts, cb, idx, query) { if(filename == 'VIEWS' || filename == 'TABLES' ) { var res = []; for(var databaseid in alasql.databases) { var tables = alasql.databases[databaseid].tables; for(var tableid in tables) { if((tables[tableid].view && filename == 'VIEWS') || (!tables[tableid].view && filename == 'TABLES')) { res.push({TABLE_CATALOG:databaseid,TABLE_NAME:tableid}); } } } if(cb) res = cb(res, idx, query); return res; } throw new Error('Unknown INFORMATION_SCHEMA table'); }
n/a
JSON = function (filename, opts, cb, idx, query) { var res; filename = alasql.utils.autoExtFilename(filename,'json',opts); alasql.utils.loadFile(filename,!!cb,function(data){ res = JSON.parse(data); if(cb){ res = cb(res, idx, query); } }); return res; }
n/a
METEOR = function (filename, opts, cb, idx, query) { var res = filename.find(opts).fetch(); if(cb){ res = cb(res, idx, query); } return res; }
n/a
RANGE = function (start, finish, cb, idx, query) { var res = []; for(var i=start;i<=finish;i++){ res.push(i); } // res = new alasql.Recordset({data:res,columns:{columnid:'_'}}); if(cb){ res = cb(res, idx, query); } return res; }
n/a
TAB = function (filename, opts, cb, idx, query) { opts = opts || {}; opts.separator = '\t'; filename = alasql.utils.autoExtFilename(filename,'tab',opts); opts.autoext = false; return alasql.from.CSV(filename, opts, cb, idx, query); }
n/a
TABLETOP = function (key, opts, cb, idx, query) { var res = []; var opt = {headers:true, simpleSheet:true, key:key}; alasql.utils.extend(opt, opts); opt.callback = function(data){ for(var i=0; i<data.length; i++) { for (var prop in data[i]) { if(data[i][prop] == +data[i][prop] && data[i].hasOwnProperty(prop)){ // jshint ignore:line data[i][prop] = +data[i][prop]; } } } res = data; if(cb){ res = cb(res, idx, query); } }; Tabletop.init(opt); return null; }
n/a
TSV = function (filename, opts, cb, idx, query) { opts = opts || {}; opts.separator = '\t'; filename = alasql.utils.autoExtFilename(filename,'tab',opts); opts.autoext = false; return alasql.from.CSV(filename, opts, cb, idx, query); }
n/a
TXT = function (filename, opts, cb, idx, query) { var res; filename = alasql.utils.autoExtFilename(filename,'txt',opts); alasql.utils.loadFile(filename,!!cb,function(data){ res = data.split(/\r?\n/); // Remove last line if empty if(res[res.length-1] === ''){ res.pop(); } for(var i=0, ilen=res.length; i<ilen;i++) { // Please avoid '===' here if(res[i] == +res[i]){ // jshint ignore:line res[i] = +res[i]; } res[i] = [res[i]]; } if(cb){ res = cb(res, idx, query); } }); return res; }
n/a
XLS = function (filename, opts, cb, idx, query) { opts=opts||{}; filename = alasql.utils.autoExtFilename(filename,'xls',opts); opts.autoExt = false; return XLSXLSX(getXLS(),filename, opts, cb, idx, query); }
n/a
XLSX = function (filename, opts, cb, idx, query) { opts=opts||{}; filename = alasql.utils.autoExtFilename(filename,'xlsx',opts); opts.autoExt = false; return XLSXLSX(getXLSX(),filename, opts, cb, idx, query); }
n/a
XML = function (filename, opts, cb, idx, query) { var res; alasql.utils.loadFile(filename,!!cb,function(data){ res = xmlparse(data).root; if(cb) res = cb(res, idx, query); }); return res; }
n/a
CSV = function (filename, opts, data, columns, cb) { if(columns.length === 0 && data.length > 0) { columns = Object.keys(data[0]).map(function(columnid){return {columnid:columnid}}); } if(typeof filename === 'object') { opts = filename; filename = undefined; } var opt = {headers:true}; //opt.separator = ','; opt.separator = ';'; opt.quote = '"'; opt.utf8Bom = true; if(opts && !opts.headers && typeof opts.headers !== 'undefined'){ opt.utf8Bom = false; } alasql.utils.extend(opt, opts); var res = data.length; var s = opt.utf8Bom ? "\ufeff" : ''; if(opt.headers) { s += opt.quote+columns.map(function(col){ return col.columnid.trim(); }).join(opt.quote+opt.separator+opt.quote)+opt.quote+'\r\n'; } data.forEach(function(d){ s += columns.map(function(col){ var s = d[col.columnid]; // escape the character wherever it appears in the field if (opt.quote !== '') { s = (s+"").replace(new RegExp('\\'+opt.quote,"g"), opt.quote + opt.quote); } //Excel 2013 needs quotes around strings - thanks for _not_ complying with RFC for CSV if(+s!=s){ // jshint ignore:line s = opt.quote + s + opt.quote; } return s; }).join(opt.separator)+'\r\n'; }); filename = alasql.utils.autoExtFilename(filename,'csv',opts); res = alasql.utils.saveFile(filename,s, null, {disableAutoBom: true}); if(cb){ res = cb(res); } return res; }
...
alasql.into.TAB = alasql.into.TSV = function(filename, opts, data, columns, cb) {
var opt = {};
alasql.utils.extend(opt, opts);
opt.separator = '\t';
filename = alasql.utils.autoExtFilename(filename,'tab',opts);
opt.autoExt = false;
return alasql.into.CSV(filename, opt, data, columns, cb);
}
alasql.into.CSV = function(filename, opts, data, columns, cb) {
if(columns.length === 0 && data.length > 0) {
columns = Object.keys(data[0]).map(function(columnid){return {columnid:columnid}});
}
if(typeof filename === 'object') {
...
HTML = function (selector, opts, data, columns, cb) { var res = 1; if(typeof exports !== 'object') { var opt = {headers:true}; alasql.utils.extend(opt, opts); var sel = document.querySelector(selector); if(!sel) { throw new Error('Selected HTML element is not found'); }; if(columns.length === 0) { if(typeof data[0] === "object") { columns = Object.keys(data[0]).map(function(columnid){return {columnid:columnid}}); } else { // What should I do? // columns = [{columnid:"_"}]; } } var tbe = document.createElement('table'); var thead = document.createElement('thead'); tbe.appendChild(thead); if(opt.headers) { var tre = document.createElement('tr'); for(var i=0;i<columns.length;i++){ var the = document.createElement('th'); the.textContent = columns[i].columnid; tre.appendChild(the); } thead.appendChild(tre); } var tbody = document.createElement('tbody'); tbe.appendChild(tbody); for(var j=0;j<data.length;j++){ var tre = document.createElement('tr'); for(var i=0;i<columns.length;i++){ var the = document.createElement('td'); the.textContent = data[j][columns[i].columnid]; tre.appendChild(the); } tbody.appendChild(tre); } alasql.utils.domEmptyChildren(sel); sel.appendChild(tbe); } if(cb){ res = cb(res); } return res; }
n/a
JSON = function (filename, opts, data, columns, cb) { var res = 1; if(typeof filename === 'object') { opts = filename; filename = undefined; } var s = JSON.stringify(data); filename = alasql.utils.autoExtFilename(filename,'json',opts); res = alasql.utils.saveFile(filename,s); if(cb){ res = cb(res); } return res; }
n/a
SQL = function (filename, opts, data, columns, cb) { var res; if(typeof filename === 'object') { opts = filename; filename = undefined; } var opt = {}; alasql.utils.extend(opt, opts); if(typeof opt.tableid === 'undefined') { throw new Error('Table for INSERT TO is not defined.'); } var s = ''; if(columns.length === 0) { if(typeof data[0] === "object") { columns = Object.keys(data[0]).map(function(columnid){return {columnid:columnid}}); } else { // What should I do? // columns = [{columnid:"_"}]; } } for(var i=0,ilen=data.length;i<ilen;i++) { s += 'INSERT INTO '+opts.tableid +'('; s += columns.map(function(col){return col.columnid}).join(","); s += ') VALUES ('; s += columns.map(function(col){ var val = data[i][col.columnid]; if(col.typeid) { if(col.typeid === 'STRING' || col.typeid === 'VARCHAR' || col.typeid === 'NVARCHAR' || col.typeid === 'CHAR' || col.typeid === 'NCHAR') { val = "'"+escapeqq(val)+"'"; } } else { if(typeof val == 'string') { val = "'"+escapeqq(val)+"'"; } } return val; }); s += ');\n'; } // if(filename === '') { // } else { filename = alasql.utils.autoExtFilename(filename,'sql',opts); res = alasql.utils.saveFile(filename,s); if(cb){ res = cb(res); } return res; }
n/a
TAB = function (filename, opts, data, columns, cb) { var opt = {}; alasql.utils.extend(opt, opts); opt.separator = '\t'; filename = alasql.utils.autoExtFilename(filename,'tab',opts); opt.autoExt = false; return alasql.into.CSV(filename, opt, data, columns, cb); }
n/a
TSV = function (filename, opts, data, columns, cb) { var opt = {}; alasql.utils.extend(opt, opts); opt.separator = '\t'; filename = alasql.utils.autoExtFilename(filename,'tab',opts); opt.autoExt = false; return alasql.into.CSV(filename, opt, data, columns, cb); }
n/a
TXT = function (filename, opts, data, columns, cb) { // If columns is empty if(columns.length === 0 && data.length > 0) { columns = Object.keys(data[0]).map(function(columnid){return {columnid:columnid}}); } // If one parameter if(typeof filename === 'object') { opts = filename; filename = undefined; } var res = data.length; var s = ''; if(data.length > 0) { var key = columns[0].columnid; s += data.map(function(d){ return d[key]; }).join('\n'); } filename = alasql.utils.autoExtFilename(filename,'txt',opts); res = alasql.utils.saveFile(filename,s); if(cb){ res = cb(res); } return res; }
n/a
XLS = function (filename, opts, data, columns, cb) { // If filename is not defined then output to the result if(typeof filename == 'object') { opts = filename; filename = undefined; } // Set sheets var sheets = {}; if(opts && opts.sheets) { sheets = opts.sheets; }; // Default sheet var sheet = {headers:true}; if(typeof sheets['Sheet1'] != 'undefined') { sheet = sheets[0]; } else { if(typeof opts != 'undefined') { sheet = opts; } }; // Set sheet name and default is 'Sheet1' if(typeof sheet.sheetid == 'undefined') { sheet.sheetid = 'Sheet1'; }; var s = toHTML(); // File is ready to save filename = alasql.utils.autoExtFilename(filename,'xls',opts); var res = alasql.utils.saveFile(filename,s); if(cb) res = cb(res); return res; function toHTML() { // Generate prologue var s = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" \ xmlns="http://www.w3.org/TR/REC-html40"><head> \ <meta charset="utf-8" /> \ <!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets> '; // Worksheets s+=' <x:ExcelWorksheet><x:Name>' + sheet.sheetid + '</x:Name><x:WorksheetOptions><x:DisplayGridlines/> </x:WorksheetOptions >\ </x:ExcelWorksheet>'; s += '</x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head>'; // Generate body s += '<body'; if(typeof sheet.style != 'undefined') { s += ' style="'; if(typeof sheet.style == 'function') { s += sheet.style(sheet); } else { s += sheet.style; } s += '"'; } s +='>'; s += '<table>'; if(typeof sheet.caption != 'undefined') { var caption = sheet.caption; if(typeof caption == 'string') { caption = {title:caption}; } s += '<caption'; if(typeof caption.style != 'undefined') { s += ' style="'; if(typeof caption.style == 'function') { s += caption.style(sheet,caption); } else { s += caption.style; } s += '" ' } s += '>'; s += caption.title; s += '</caption>'; } // Columns // If columns defined in sheet, then take them if(typeof sheet.columns != 'undefined') { columns = sheet.columns; } else { // Autogenerate columns if they are passed as parameters if(columns.length == 0 && data.length > 0) { if(typeof data[0] == 'object') { if(Array.isArray(data[0])) { columns = data[0].map(function(d,columnidx){ return {columnid:columnidx}; }); } else { columns = Object.keys(data[0]).map(function(columnid){ return {columnid:columnid}; }); } } } }; // Prepare columns columns.forEach(function(column,columnidx){ if(typeof sheet.column != 'undefined') { extend(column,sheet.column); } if(typeof column.width == 'undefined') { if(sheet.column && sheet.column.width !='undefined') { column.width = sheet.column.width; } else { column.width = "120px"; } } if(typeof column.width == 'number') column.width = column.width + "px"; if(typeof column.columnid == 'undefined') column.columnid = columnidx; if(typeof column.title == 'undefined') column.title = ""+column.columnid.trim(); if(sheet.headers && Array.isArray(sheet.headers)) column.title = sheet.headers[columnidx]; }); // Set columns widths s += '<colgroups>'; columns.forEach(function (column) { s += '<col style="width: '+column.width+'"></col>'; }); s += '</colgroups>'; // Headers if(sheet.headers) { s += '<thead>'; s += '<tr>'; // TODO: Skip columns to body // Headers columns.forEach(function (column,columnidx) { s += '<th '; // Column style if(typeof column.style != 'undefined') { s += ' style="'; if(typeof column.style == 'function') { s += column.style(sheet,column,columnidx); } else { s += column.style; } s += '" ' } s += '>'; // Column title if(typeof column.title != 'undefined') { if(typeof column.title == 'function') { s += column.title(sheet,column,columnidx); } else { s += column.title; ...
n/a
XLSX = function (filename, opts, data, columns, cb) {
/** @type {number} result */
var res = 1;
if(deepEqual(columns,[{columnid:'_'}])) {
data = data.map(function(dat){return dat._;});
columns = undefined;
} else {
}
filename = alasql.utils.autoExtFilename(filename,'xlsx',opts);
var XLSX = getXLSX();
/* If called without filename, use opts */
if(typeof filename == 'object') {
opts = filename;
filename = undefined;
};
/** @type {object} Workbook */
var wb = {SheetNames:[], Sheets:{}};
// ToDo: check if cb must be treated differently here
if(opts.sourcefilename) {
alasql.utils.loadBinaryFile(opts.sourcefilename,!!cb,function(data){
wb = XLSX.read(data,{type:'binary'});
doExport();
});
} else {
doExport();
};
/* Return result */
if(cb) res = cb(res);
return res;
/**
Export workbook
@function
*/
function doExport() {
/*
If opts is array of arrays then this is a
multisheet workboook, else it is a singlesheet
*/
if(typeof opts == 'object' && Array.isArray(opts)) {
if(data && data.length > 0) {
data.forEach(function(dat,idx){
prepareSheet(opts[idx],dat,undefined,idx+1)
});
}
} else {
prepareSheet(opts,data,columns,1);
}
saveWorkbook(cb);
}
/**
Prepare sheet
@params {object} opts
@params {array|object} data
@params {array} columns Columns
*/
function prepareSheet(opts, data, columns, idx) {
/** Default options for sheet */
var opt = {sheetid:'Sheet '+idx,headers:true};
alasql.utils.extend(opt, opts);
var dataLength = Object.keys(data).length;
// Generate columns if they are not defined
if((!columns || columns.length == 0) && dataLength > 0) {
columns = Object.keys(data[0]).map(function(columnid){return {columnid:columnid}});
}
var cells = {};
if(wb.SheetNames.indexOf(opt.sheetid) > -1) {
cells = wb.Sheets[opt.sheetid];
} else {
wb.SheetNames.push(opt.sheetid);
wb.Sheets[opt.sheetid] = {};
cells = wb.Sheets[opt.sheetid];
}
var range = "A1";
if(opt.range) range = opt.range;
var col0 = alasql.utils.xlscn(range.match(/[A-Z]+/)[0]);
var row0 = +range.match(/[0-9]+/)[0]-1;
if(wb.Sheets[opt.sheetid]['!ref']) {
var rangem = wb.Sheets[opt.sheetid]['!ref'];
var colm = alasql.utils.xlscn(rangem.match(/[A-Z]+/)[0]);
var rowm = +rangem.match(/[0-9]+/)[0]-1;
} else {
var colm = 1, rowm = 1;
}
var colmax = Math.max(col0+columns.length,colm);
var rowmax = Math.max(row0+dataLength+2,rowm);
var i = row0+1;
wb.Sheets[opt.sheetid]['!ref'] = 'A1:'+alasql.utils.xlsnc(colmax)+(rowmax);
if(opt.headers) {
columns.forEach(function(col, idx){
cells[alasql.utils.xlsnc(col0+idx)+""+i] = {v:col.columnid.trim()};
});
i++;
}
for(var j=0;j<dataLength;j++) {
columns.forEach(function(col, idx){
var cell = {v:data[j][col.columnid]};
if(typeof data[j][col.columnid] == 'number') {
cell.t = 'n';
} else if(typeof data[j][col.columnid] == 'string') {
cell.t = 's';
} else if(typeof data[j][col.columnid] == 'boolean') {
cell.t = 'b';
} else if(typeof data[j][col.columnid] == 'object') {
if(data[j][col.columnid] instanceof Date) {
cell.t = 'd';
}
}
cells[alasql.utils.xlsnc(col0+idx)+""+i] = cell;
});
i++;
}
}
/**
Save Workbook
@params {array} wb Workbook
@params {callback} cb Callback
*/
function saveWorkbook(cb) {
var XLSX;
if(typeof filename == 'undefined') {
res = wb;
} else {
XLSX = getXLSX();
if(utils.isNode || utils.isMeteorServer) {
XLSX.writeFile(wb, filename);
} else {
var wopts = { bookType:'xlsx', bookSST:false, type:'binary' };
var wbout = XLSX.write(wb,wopts);
function s2ab(s) {
var buf = new ArrayBuffer(s.length);
var view = new Uint8Array(buf);
for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
return buf;
}
/* the saveAs call downloads a file on the local machine */
if(isIE() == 9) {
throw new Error('Cannot save XLSX files in IE9. Please use XLS() export function'); ...
n/a
XLSXML = function (filename, opts, data, columns, cb) { opts = opts || {}; // If filename is not defined then output to the result if(typeof filename == 'object') { opts = filename; filename = undefined; } // Set sheets var sheets = {}; if(opts && opts.sheets) { sheets = opts.sheets; } else { sheets.Sheet1 = opts; }; // File is ready to save filename = alasql.utils.autoExtFilename(filename,'xls',opts); var res = alasql.utils.saveFile(filename,toXML()); if(cb) res = cb(res); return res; function toXML() { var s1 = '<?xml version="1.0"?> \ <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" \ xmlns:o="urn:schemas-microsoft-com:office:office" \ xmlns:x="urn:schemas-microsoft-com:office:excel" \ xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" \ xmlns:html="http://www.w3.org/TR/REC-html40"> \ <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"> \ </DocumentProperties> \ <OfficeDocumentSettings xmlns="urn:schemas-microsoft-com:office:office"> \ <AllowPNG/> \ </OfficeDocumentSettings> \ <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel"> \ <ActiveSheet>0</ActiveSheet> \ </ExcelWorkbook> \ <Styles> \ <Style ss:ID="Default" ss:Name="Normal"> \ <Alignment ss:Vertical="Bottom"/> \ <Borders/> \ <Font ss:FontName="Calibri" x:Family="Swiss" ss:Size="12" ss:Color="#000000"/> \ <Interior/> \ <NumberFormat/> \ <Protection/> \ </Style>'; var s2 = ''; // for styles var s3 = ' </Styles>'; var styles = {}; // hash based storage for styles var stylesn = 62; // First style // Generate style function hstyle(st) { // Prepare string var s = ''; for(var key in st) { s += '<'+key; for(var attr in st[key]) { s += ' '; if(attr.substr(0,2) == 'x:') { s += attr; } else { s += 'ss:'; } s += attr+'="'+st[key][attr]+'"'; } s += '/>'; } var hh = hash(s); // Store in hash if(styles[hh]) { } else { styles[hh] = {styleid:stylesn}; s2 += '<Style ss:ID="s'+stylesn+'">'; s2 += s; s2 += '</Style>'; stylesn++; } return 's'+styles[hh].styleid; } for (var sheetid in sheets) { var sheet = sheets[sheetid]; // If columns defined in sheet, then take them if(typeof sheet.columns != 'undefined') { columns = sheet.columns; } else { // Autogenerate columns if they are passed as parameters if(columns.length == 0 && data.length > 0) { if(typeof data[0] == 'object') { if(Array.isArray(data[0])) { columns = data[0].map(function(d,columnidx){ return {columnid:columnidx}; }); } else { columns = Object.keys(data[0]).map(function(columnid){ return {columnid:columnid}; }); } } } }; // Prepare columns columns.forEach(function(column,columnidx){ if(typeof sheet.column != 'undefined') { extend(column,sheet.column); } if(typeof column.width == 'undefined') { if(sheet.column && (typeof sheet.column.width !='undefined')) { column.width = sheet.column.width; } else { column.width = 120; } } if(typeof column.width == 'number') column.width = column.width; if(typeof column.columnid == 'undefined') column.columnid = columnidx; if(typeof column.title == 'undefined') column.title = ""+column.columnid.trim(); if(sheet.headers && Array.isArray(sheet.headers)) column.title = sheet.headers[idx]; }); // Header s3 +='<Worksheet ss:Name="'+sheetid+'"> \ <Table ss:ExpandedColumnCount="'+columns.length +'" ss:ExpandedRowCount="'+((sheet.headers?1:0)+Math.min(data.length,sheet.limit||data.length)) +'" x:FullColumns="1" \ x:FullRows="1" ss:DefaultColumnWidth="65" ss:DefaultRowHeight="15">'; columns.forEach(function (column,columnidx) { s3 += '<Column ss:Index="'+(columnidx+1) +'" ss:AutoFitWidth="0" ss:Width="'+column.width+'"/>' }); // Headers if(sheet.headers) { s3 += '<Row ss:A ...
n/a
parseError = function (str, hash) { if (hash.expected && hash.expected.indexOf("'LITERAL'") > -1 && /[a-zA-Z_][a-zA-Z_0-9]*/.test(hash.token) && nonReserved.indexOf (hash.token) > -1) { return } throw new SyntaxError(str) }
...
if (lexer.showPosition) {
errStr = 'Parse error on line '+(yylineno+1)+":\n"+lexer.showPosition()+"\nExpecting "+expected
.join(', ') + ", got '" + (this.terminals_[symbol] || symbol)+ "'";
} else {
errStr = 'Parse error on line '+(yylineno+1)+": Unexpected " +
(symbol == EOF ? "end of input" :
("'"+(this.terminals_[symbol] || symbol)+"'"));
}
this.parseError(errStr, {
text: lexer.match,
token: this.terminals_[symbol] || symbol,
line: lexer.yylineno,
loc: yyloc,
expected: expected,
recoverable: (error_rule_depth !== false)
});
...
APROP = function (val, args) { if( (typeof val !== 'object') || (val === null) || (typeof args !== 'object') || (typeof val[args[0]] === 'undefined')) { return {status: 1, values: [undefined]}; } else { return {status: 1, values: [val[args[0]]]}; } }
n/a
AS = function (val, args) { alasql.vars[args[0]] = val; return {status: 1, values: [val]}; }
n/a
AT = function (val, args) { var v = alasql.vars[args[0]]; return {status: 1, values: [v]}; }
n/a
ATTR = function (val, args, stope) { if(stope.mode === 'XML') { if(typeof args === 'undefined') { return {status: 1, values: [val.attributes]}; } else { if( typeof val === 'object' && typeof val.attributes === 'object' && typeof val.attributes[args[0]] !== 'undefined' ){ return {status: 1, values: [val.attributes[args[0]]]}; } else { return {status: -1, values: []}; } } } else { throw new Error('ATTR is not using in usual mode'); } }
n/a
CHILD = function (val, args, stope) { if(typeof val === 'object') { if(Array.isArray(val)){ return {status: 1, values: val}; } else { if(stope.mode === 'XML') { return {status: 1, values: Object.keys(val.children).map(function(key){return val.children[key];})}; } else { return {status: 1, values: Object.keys(val).map(function(key){return val[key];})}; } } } else { // If primitive value return {status: 1, values:[]}; } }
n/a
CLASS = function (val, args) { // Please avoid `===` here if(val.$class == args) { // jshint ignore:line return {status: 1, values: [val]}; } else { return {status: -1, values: []}; } }
n/a
CLONEDEEP = function (val) { // TODO something wrong var z = cloneDeep(val); return {status: 1, values: [z]}; }
n/a
CONTENT = function (val, args, stope) { if(stope.mode === 'XML') { return {status: 1, values: [val.content]}; } else { throw new Error('ATTR is not using in usual mode'); } }
n/a
D3 = function (val) { if(val.$node !== 'VERTEX' && val.$node === 'EDGE') { val.source = val.$in[0]; val.target = val.$out[0]; } return {status: 1, values: [val]}; }
n/a
EDGE = function (val ) { if(val.$node === 'EDGE') { return {status: 1, values: [val]}; } else { return {status: -1, values: []}; } }
n/a
EQ = function (val, args, stope, params) { var exprs = args[0].toJS('x',''); var exprfn = new Function('x,alasql,params','return '+exprs); if(val === exprfn(val,alasql,params)) { return {status: 1, values: [val]}; } else { return {status: -1, values: []}; } }
n/a
EX = function (val, args, stope, params) { var exprs = args[0].toJS('x',''); var exprfn = new Function('x,alasql,params','return '+exprs); return {status: 1, values: [exprfn(val,alasql,params)]}; }
n/a
IN = function (val) { if(val.$in && val.$in.length > 0) { var res = val.$in.map(function(v){ return alasql.databases[alasql.useid].objects[v] }); return {status: 1, values: res}; } else { return {status: -1, values: []}; } }
n/a
ININ = function (val ) { if(val.$in && val.$in.length > 0) { var res = []; val.$in.forEach(function(v){ var av = alasql.databases[alasql.useid].objects[v]; if(av && av.$in && av.$in.length > 0) { av.$in.forEach(function(vv){ res = res.concat(alasql.databases[alasql.useid].objects[vv]); }); } }); return {status: 1, values: res}; } else { return {status: -1, values: []}; } }
n/a
INSTANCEOF = function (val, args) { if(val instanceof alasql.fn[args[0]]) { return {status: 1, values: [val]}; } else { return {status: -1, values: []}; } }
n/a
KEYS = function (val) { if(typeof val === 'object' && val !== null) { return {status: 1, values: Object.keys(val)}; } else { // If primitive value return {status: 1, values:[]}; } }
n/a
LIKE = function (val, args, stope, params) { var exprs = args[0].toJS('x',''); var exprfn = new Function('x,alasql,params','return '+exprs); if(val.toUpperCase().match(new RegExp('^'+exprfn(val,alasql,params).toUpperCase() .replace(/%/g,'.*').replace(/\?|_/g,'.')+'$'),'g')) { return {status: 1, values: [val]}; } else { return {status: -1, values: []}; } }
n/a
NAME = function (val, args) { if(val.name === args[0]) { return {status: 1, values: [val]}; } else { return {status: -1, values: []}; } }
n/a
ORDERBY = function (val, args) { var res = val.sort(compileSearchOrder(args)); return {status: 1, values: res}; }
n/a
OUT = function (val ) { if(val.$out && val.$out.length > 0) { var res = val.$out.map(function(v){ return alasql.databases[alasql.useid].objects[v] }); return {status: 1, values: res}; } else { return {status: -1, values: []}; } }
n/a
OUTOUT = function (val ) { if(val.$out && val.$out.length > 0) { var res = []; val.$out.forEach(function(v){ var av = alasql.databases[alasql.useid].objects[v]; if(av && av.$out && av.$out.length > 0) { av.$out.forEach(function(vv){ res = res.concat(alasql.databases[alasql.useid].objects[vv]); }); } }); return {status: 1, values: res}; } else { return {status: -1, values: []}; } }
n/a
PARENT = function () { // TODO: implement console.log('PARENT not implemented', arguments); return {status: -1, values: []}; }
n/a
PROP = function (val, args, stope) { if(stope.mode === 'XML') { var arr = []; val.children.forEach(function(v){ if(v.name.toUpperCase() === args[0].toUpperCase()) { arr.push(v) } }); if(arr.length>0) { return {status: 1, values: arr}; } else { return {status: -1, values: []}; } } else { if( (typeof val !== 'object') || (val === null) || (typeof args !== 'object') || (typeof val[args[0]] === 'undefined') ) { return {status: -1, values: []}; } else { return {status: 1, values: [val[args[0]]]}; } } }
n/a
REF = function (val ) { return {status: 1, values: [alasql.databases[alasql.useid].objects[val]]}; }
n/a
RETURN = function (val, args, stope, params) { var res = {}; if(args && args.length > 0) { args.forEach(function(arg){ var exprs = arg.toJS('x',''); var exprfn = new Function('x,alasql,params','return '+exprs); if(typeof arg.as === 'undefined'){ arg.as = arg.toString(); } res[arg.as] = exprfn(val,alasql,params); }); } return {status: 1, values: [res]}; }
n/a
ROW = function (val, args, stope, params) { var s = 'var y;return ['; s += args.map(function(arg){ return arg.toJS('x',''); }).join(','); s += ']' var setfn = new Function('x,params,alasql',s); var rv = setfn(val,params,alasql); return {status: 1, values: [rv]}; }
n/a
SET = function (val, args, stope, params) { var s = args.map(function(st){ if(st.method === '@') { return 'alasql.vars[\''+st.variable+'\']='+st.expression.toJS('x',''); } else if(st.method === '$') { return 'params[\''+st.variable+'\']='+st.expression.toJS('x',''); } else { return 'x[\''+st.column.columnid+'\']='+st.expression.toJS('x',''); } }).join(';'); var setfn = new Function('x,params,alasql',s); setfn(val,params,alasql); return {status: 1, values: [val]}; }
n/a
SHARP = function (val, args) { var obj = alasql.databases[alasql.useid].objects[args[0]]; if(typeof val !== 'undefined' && val === obj) { return {status: 1, values: [val]}; } else { return {status: -1, values: []}; } }
n/a
VERTEX = function (val) { if(val.$node === 'VERTEX') { return {status: 1, values: [val]}; } else { return {status: -1, values: []}; } }
n/a
WHERE = function (val, args, stope, params) { var exprs = args[0].toJS('x',''); var exprfn = new Function('x,alasql,params','return '+exprs); if(exprfn(val,alasql,params)) { return {status: 1, values: [val]}; } else { return {status: -1, values: []}; } }
n/a
ADDDATE = function (d, interval) { var nd = (new Date(d)).getTime() + interval; return new Date(nd); }
n/a
ASCII = function (a) { return a.charCodeAt(0); }
n/a
CHAR = function () { [native code] }
n/a
COALESCE = function () { for(var i=0;i<arguments.length;i++) { if(typeof arguments[i] == 'undefined') continue; if(typeof arguments[i] == "number" && isNaN(arguments[i]) ) continue; return arguments[i]; } return undefined; }
n/a
CONCAT = function (){ return Array.prototype.slice.call(arguments).join(''); }
n/a
CONCAT_WS = function () { args = Array.prototype.slice.call(arguments); return args.slice(1, args.length).join(args[0]); }
n/a
CONVERT = function (value, args) { var val = value; if(args.style) { // TODO 9,109, 20,120,21,121,126,130,131 conversions var t; if(/\d{8}/.test(val)){ t = new Date(+val.substr(0,4),+val.substr(4,2)-1,+val.substr(6,2)); } else{ t = new Date(val); } switch(args.style){ case 1: // mm/dd/yy val = ("0"+(t.getMonth()+1)).substr(-2)+'/'+("0"+t.getDate()).substr(-2)+'/'+("0"+t.getYear()).substr(-2); break; case 2: // yy.mm.dd val = ("0"+t.getYear()).substr(-2)+'.'+("0"+(t.getMonth()+1)).substr(-2)+'.'+("0"+t.getDate()).substr(-2); break; case 3: // dd/mm/yy val = ("0"+t.getDate()).substr(-2)+'/'+("0"+(t.getMonth()+1)).substr(-2)+'/'+("0"+t.getYear()).substr(-2); break; case 4: // dd.mm.yy val = ("0"+t.getDate()).substr(-2)+'.'+("0"+(t.getMonth()+1)).substr(-2)+'.'+("0"+t.getYear()).substr(-2); break; case 5: // dd-mm-yy val = ("0"+t.getDate()).substr(-2)+'-'+("0"+(t.getMonth()+1)).substr(-2)+'-'+("0"+t.getYear()).substr(-2); break; case 6: // dd mon yy val = ("0"+t.getDate()).substr(-2)+' '+t.toString().substr(4,3).toLowerCase()+' '+("0"+t.getYear()).substr(-2); break; case 7: // Mon dd,yy val = t.toString().substr(4,3)+' '+("0"+t.getDate()).substr(-2)+','+("0"+t.getYear()).substr(-2); break; case 8 : // hh:mm:ss case 108 : // hh:mm:ss val = ("0"+t.getHours()).substr(-2)+':'+("0"+(t.getMinutes())).substr(-2)+':'+("0"+t.getSeconds()).substr(-2); break; case 10: // mm-dd-yy val = ("0"+(t.getMonth()+1)).substr(-2)+'-'+("0"+t.getDate()).substr(-2)+'-'+("0"+t.getYear()).substr(-2); break; case 11: // yy/mm/dd val = ("0"+t.getYear()).substr(-2)+'/'+("0"+(t.getMonth()+1)).substr(-2)+'/'+("0"+t.getDate()).substr(-2); break; case 12: // yymmdd val = ("0"+t.getYear()).substr(-2)+("0"+(t.getMonth()+1)).substr(-2)+("0"+t.getDate()).substr(-2); break; case 101: // mm/dd/yyyy val = ("0"+(t.getMonth()+1)).substr(-2)+'/'+("0"+t.getDate()).substr(-2)+'/'+t.getFullYear(); break; case 102: // yyyy.mm.dd val = t.getFullYear()+'.'+("0"+(t.getMonth()+1)).substr(-2)+'.'+("0"+t.getDate()).substr(-2); break; case 103: // dd/mm/yyyy val = ("0"+t.getDate()).substr(-2)+'/'+("0"+(t.getMonth()+1)).substr(-2)+'/'+t.getFullYear(); break; case 104: // dd.mm.yyyy val = ("0"+t.getDate()).substr(-2)+'.'+("0"+(t.getMonth()+1)).substr(-2)+'.'+t.getFullYear(); break; case 105: // dd-mm-yyyy val = ("0"+t.getDate()).substr(-2)+'-'+("0"+(t.getMonth()+1)).substr(-2)+'-'+t.getFullYear(); break; case 106: // dd mon yyyy val = ("0"+t.getDate()).substr(-2)+' '+t.toString().substr(4,3).toLowerCase()+' '+t.getFullYear(); break; case 107: // Mon dd,yyyy val = t.toString().substr(4,3)+' '+("0"+t.getDate()).substr(-2)+','+t.getFullYear(); break; case 110: // mm-dd-yyyy val = ("0"+(t.getMonth()+1)).substr(-2)+'-'+("0"+t.getDate()).substr(-2)+'-'+t.getFullYear(); break; case 111: // yyyy/mm/dd val = t.getFullYear()+'/'+("0"+(t.getMonth()+1)).substr(-2)+'/'+("0"+t.getDate()).substr(-2); break; case 112: // yyyymmdd val = t.getFullYear()+("0"+(t.getMonth()+1)).substr(-2)+("0"+t.getDate()).substr(-2); break; default: throw new Error('The CONVERT style '+args.style+' is not realized yet.'); } }; var udbtypeid = args.dbtypeid.toUpperCase(); if(args.dbtypeid == 'Date') { return new Date(val); } else if(udbtypeid == 'DATE') { var d = new Date(val); var s = d.getFullYear()+"."+("0"+(d.getMonth()+1)).substr(-2)+"."+("0"+d.getDate()).substr(-2); return s; } else if(udbtypeid == 'DATETIME' || udbtypeid == 'DATETIME2') { var d = new Date(val); var s = d.getFullYear()+"."+("0"+(d.getMonth()+1)).substr(-2)+"."+("0"+d.getDate()).substr(-2); s += " "+("0"+d.getHours()).substr(-2)+":"+("0"+d.getMinutes()).substr(-2)+":"+("0"+d.getSeconds()).substr(-2); s += '.'+("00"+d.getMilliseconds()).subs ...
...
s += ','+this.expression.toString();
if(this.style) s += ','+this.style;
s += ')';
return s;
};
yy.Convert.prototype.toJS = function(context, tableid, defcols) {
// if(this.style) {
return 'alasql.stdfn.CONVERT('+this.expression.toJS(context, tableid, defcols
)
+',{dbtypeid:"'+this.dbtypeid+'",dbsize:'+this.dbsize+',style:'+
this.style+'})';
// }
throw new Error('There is not such type conversion for '+this.toString());
};
/**
Convert one type to another
...
CURRENT_TIMESTAMP = function (){ var d = new Date(); var s = d.getFullYear()+"."+("0"+(d.getMonth()+1)).substr(-2)+"."+("0"+d.getDate()).substr(-2); s += " "+("0"+d.getHours()).substr(-2)+":"+("0"+d.getMinutes()).substr(-2)+":"+("0"+d.getSeconds()).substr(-2); s += '.'+("00"+d.getMilliseconds()).substr(-3) return s; }
n/a
DATE = function (d) { if(/\d{8}/.test(d)) return new Date(+d.substr(0,4),+d.substr(4,2)-1,+d.substr(6,2)); return new Date(d); }
n/a
DATEADD = function (period, interval, d) { var nd = (new Date(d)).getTime() + interval*PERIODS[period.toLowerCase()]; return new Date(nd); }
n/a
DATEDIFF = function (period, d1, d2) { var interval = (new Date(d2)).getTime() - (new Date(d1)).getTime(); return interval / PERIODS[period.toLowerCase()]; }
n/a
DATE_ADD = function (d, interval) { var nd = (new Date(d)).getTime() + interval; return new Date(nd); }
n/a
DATE_SUB = function (d, interval) { var nd = (new Date(d)).getTime() - interval; return new Date(nd); }
n/a
DAY = function (d){ var d = new Date(d); return d.getDate(); }
n/a
DAYOFMONTH = function (d){ var d = new Date(d); return d.getDate(); }
n/a
DAYOFWEEK = function (d){ var d = new Date(d); return d.getDay(); }
n/a
function extend(a, b){ a = a || {}; for(var key in b) { if(b.hasOwnProperty(key)) { a[key] = b[key]; } } return a; }
n/a
GEN_RANDOM_UUID = function () { var d0 = Math.random()*0xffffffff|0; var d1 = Math.random()*0xffffffff|0; var d2 = Math.random()*0xffffffff|0; var d3 = Math.random()*0xffffffff|0; return lut[d0&0xff]+lut[d0>>8&0xff]+lut[d0>>16&0xff]+lut[d0>>24&0xff]+'-'+ lut[d1&0xff]+lut[d1>>8&0xff]+'-'+lut[d1>>16&0x0f|0x40]+lut[d1>>24&0xff]+'-'+ lut[d2&0x3f|0x80]+lut[d2>>8&0xff]+'-'+lut[d2>>16&0xff]+lut[d2>>24&0xff]+ lut[d3&0xff]+lut[d3>>8&0xff]+lut[d3>>16&0xff]+lut[d3>>24&0xff]; }
n/a
GETDATE = function (){ var d = new Date(); var s = d.getFullYear()+"."+("0"+(d.getMonth()+1)).substr(-2)+"."+("0"+d.getDate()).substr(-2); s += " "+("0"+d.getHours()).substr(-2)+":"+("0"+d.getMinutes()).substr(-2)+":"+("0"+d.getSeconds()).substr(-2); s += '.'+("00"+d.getMilliseconds()).substr(-3) return s; }
n/a
HOUR = function (d){ var d = new Date(d); return d.getHours(); }
n/a
INTERVAL = function (interval, period) { return interval*PERIODS[period.toLowerCase()]; }
n/a
MINUTE = function (d){ var d = new Date(d); return d.getMinutes(); }
n/a
MONTH = function (d){ var d = new Date(d); return d.getMonth()+1; }
n/a
NEWID = function () { var d0 = Math.random()*0xffffffff|0; var d1 = Math.random()*0xffffffff|0; var d2 = Math.random()*0xffffffff|0; var d3 = Math.random()*0xffffffff|0; return lut[d0&0xff]+lut[d0>>8&0xff]+lut[d0>>16&0xff]+lut[d0>>24&0xff]+'-'+ lut[d1&0xff]+lut[d1>>8&0xff]+'-'+lut[d1>>16&0x0f|0x40]+lut[d1>>24&0xff]+'-'+ lut[d2&0x3f|0x80]+lut[d2>>8&0xff]+'-'+lut[d2>>16&0xff]+lut[d2>>24&0xff]+ lut[d3&0xff]+lut[d3>>8&0xff]+lut[d3>>16&0xff]+lut[d3>>24&0xff]; }
n/a
NOW = function (){ var d = new Date(); var s = d.getFullYear()+"."+("0"+(d.getMonth()+1)).substr(-2)+"."+("0"+d.getDate()).substr(-2); s += " "+("0"+d.getHours()).substr(-2)+":"+("0"+d.getMinutes()).substr(-2)+":"+("0"+d.getSeconds()).substr(-2); s += '.'+("00"+d.getMilliseconds()).substr(-3) return s; }
n/a
OBJECT_ID = function (name, type) { if(typeof type == 'undefined') type = 'T'; type = type.toUpperCase(); var sname = name.split('.'); var dbid = alasql.useid; var objname = sname[0]; if(sname.length == 2) { dbid = sname[0]; objname = sname[1]; } var tables = alasql.databases[dbid].tables; dbid = alasql.databases[dbid].databaseid; for(var tableid in tables) { if(tableid == objname) { // TODO: What OBJECT_ID actually returns if(tables[tableid].view && type == 'V') return dbid+'.'+tableid; if(!tables[tableid].view && type == 'T') return dbid+'.'+tableid; return undefined; } } return undefined; }
n/a
REGEXP_LIKE = function (a, b, c) { return (a||'').search(RegExp(b,c))>-1; }
...
+ 'alasql.utils.like(' + rightJS()+ "," + leftJS();
if(this.escape) {
s += ','+ref(this.escape);
}
s += '))';
}
if(this.op === 'REGEXP') {
s = 'alasql.stdfn.REGEXP_LIKE('
+ leftJS()
+ ','
+ rightJS()
+ ')';
}
if(this.op === 'GLOB') {
s = 'alasql.utils.glob('
...
REPLACE = function (target, pattern, replacement) { return (target||'').split(pattern).join(replacement); }
n/a
SECOND = function (d){ var d = new Date(d); return d.getSeconds(); }
n/a
SUBDATE = function (d, interval) { var nd = (new Date(d)).getTime() - interval; return new Date(nd); }
n/a
USER = function (){ return 'alasql'; }
n/a
UUID = function () { var d0 = Math.random()*0xffffffff|0; var d1 = Math.random()*0xffffffff|0; var d2 = Math.random()*0xffffffff|0; var d3 = Math.random()*0xffffffff|0; return lut[d0&0xff]+lut[d0>>8&0xff]+lut[d0>>16&0xff]+lut[d0>>24&0xff]+'-'+ lut[d1&0xff]+lut[d1>>8&0xff]+'-'+lut[d1>>16&0x0f|0x40]+lut[d1>>24&0xff]+'-'+ lut[d2&0x3f|0x80]+lut[d2>>8&0xff]+'-'+lut[d2>>16&0xff]+lut[d2>>24&0xff]+ lut[d3&0xff]+lut[d3>>8&0xff]+lut[d3>>16&0xff]+lut[d3>>24&0xff]; }
n/a
WEEKDAY = function (d){ var d = new Date(d); return d.getDay(); }
n/a
YEAR = function (d){ var d = new Date(d); return d.getFullYear(); }
n/a
ABS = function (a) {return 'Math.abs('+a+')'}
n/a
CEIL = function (s) {return 'Math.ceil('+s+')'}
n/a
CEILING = function (s) {return 'Math.ceil('+s+')'}
n/a
CLONEDEEP = function (a) {return 'alasql.utils.cloneDeep('+a+')'}
n/a
EXP = function (a) {return 'Math.pow(Math.E,'+a+')'}
n/a
FLOOR = function (s) {return 'Math.floor('+s+')'}
n/a
GREATEST = function (){ return 'Math.max('+Array.prototype.join.call(arguments, ',')+')' }
n/a
IFNULL = function (a, b) {return '('+a+'||'+b+')'}
n/a
IIF = function (a, b, c) { if(arguments.length == 3) { return '(('+a+')?('+b+'):('+c+'))'; } else { throw new Error('Number of arguments of IFF is not equals to 3'); }; }
n/a
INSTR = function (s, p) {return '(('+s+').indexOf('+p+')+1)'}
n/a
ISNULL = function (a, b){return '('+a+'=='+b+'?undefined:'+a+')'}
n/a
LCASE = function (s) {return und(s,'String(y).toLowerCase()');}
n/a
LEAST = function (){ return 'Math.min('+Array.prototype.join.call(arguments, ',')+')' }
n/a
LEN = function (s) {return und(s,'y.length');}
n/a
LENGTH = function (s) {return und(s,'y.length');}
n/a
LOWER = function (s) {return und(s,'String(y).toLowerCase()');}
n/a
MAX = function (){ return 'Math.max('+Array.prototype.join.call(arguments, ',')+')' }
n/a
MID = function (a, b, c){ if(arguments.length == 2) return und(a,'y.substr('+b+'-1)'); else if(arguments.length == 3) return und(a,'y.substr('+b+'-1,'+c+')'); }
n/a
MIN = function (){ return 'Math.min('+Array.prototype.join.call(arguments, ',')+')' }
n/a
NULLIF = function (a, b){return '('+a+'=='+b+'?undefined:'+a+')'}
n/a
POWER = function (a, b) {return 'Math.pow('+a+','+b+')'}
n/a
RANDOM = function (r) { if(arguments.length == 0) { return 'Math.random()'; } else { return '(Math.random()*('+r+')|0)'; } }
n/a
ROUND = function (s, d) { if(arguments.length == 2) { return 'Math.round(('+s+')*Math.pow(10,('+d+')))/Math.pow(10,('+d+'))'; } else { return 'Math.round('+s+')'; } }
n/a
ROWNUM = function () {return '1'}
n/a
ROW_NUMBER = function () {return '1'}
n/a
SQRT = function (s) {return 'Math.sqrt('+s+')'}
n/a
SUBSTR = function (a, b, c){ if(arguments.length == 2) return und(a,'y.substr('+b+'-1)'); else if(arguments.length == 3) return und(a,'y.substr('+b+'-1,'+c+')'); }
n/a
SUBSTRING = function (a, b, c){ if(arguments.length == 2) return und(a,'y.substr('+b+'-1)'); else if(arguments.length == 3) return und(a,'y.substr('+b+'-1,'+c+')'); }
n/a
TRIM = function (s) {return und(s,'y.trim()');}
n/a
UCASE = function (s) {return und(s,'String(y).toUpperCase()');}
n/a
UPPER = function (s) {return und(s,'String(y).toUpperCase()');}
n/a
JSONtoString = function (obj) { var s = ''; if(typeof obj == "string") s = '"'+obj+'"'; else if(typeof obj == "number") s = obj; else if(typeof obj == "boolean") s = obj; else if(typeof obj == "object") { if(Array.isArray(obj)) { s += '['+obj.map(function(b){ return JSONtoString(b); }).join(',')+']'; } else if(!obj.toJS || obj instanceof yy.Json) { // to prevent recursion s = '{'; var ss = []; for(var k in obj) { var s1 = ''; if(typeof k == "string") s1 += '"'+k+'"'; else if(typeof k == "number") s1 += k; else if(typeof k == "boolean") s1 += k; else { throw new Error('THis is not ES6... no expressions on left side yet'); } s1 += ':'+JSONtoString(obj[k]); ss.push(s1); }; s += ss.join(',')+'}'; } else if(obj.toString) { s = obj.toString(); } else { throw new Error('1Can not show JSON object '+JSON.stringify(obj)); } } else { throw new Error('2Can not show JSON object '+JSON.stringify(obj)); } return s; }
n/a
arrayDiff = function (a, b) { return a.filter(function(i) {return b.indexOf(i) < 0;}); }
n/a
arrayExceptDeep = function (a, b) { var r = []; a.forEach(function(ai) { var found = false; b.forEach(function(bi){ found = found || deepEqual(ai, bi); }); if(!found) { r.push(ai); } }); return r; }
n/a
arrayIntersect = function (a, b) { var r = []; a.forEach(function(ai) { var found = false; b.forEach(function(bi){ found = found || (ai===bi); }); if(found) { r.push(ai); } }); return r; }
n/a
arrayIntersectDeep = function (a, b) { var r = []; a.forEach(function(ai) { var found = false; b.forEach(function(bi){ found = found || deepEqual(ai, bi, true); }); if(found) { r.push(ai); } }); return r; }
n/a
arrayOfArrays = function (a) { return a.map(function(aa){ var ar = []; for(var key in aa){ ar.push(aa[key]); } return ar; }); }
...
* Changed approach to execute and compilations
* Broke transactions (to be reviewed)
### 0.0.16 (11.11.2014 - 12.11.2014)
* PRIMARY KEY and FOREIGN KEY parser
* Use array of arrays as parameter value for FROM clause, column names like \[2\] or table\[0\]
* alasql.queryArrayOfArrays(), utils.arrayOfArrays()
* PRIMARY KEY ON inseert, delete, update with one or multiple keys
* Fixed Uppercase and LowerCase problem
* CREATE DATABASE, USE DATABASE, DROP DATABASE
* CROSS and NATURAL JOINs
* RANDOM
* INSERT INTO table DEFAULT VALUES
* CREATE TABLE table (column type DEFAULT value)
...
arrayUnion = function (a, b) { var r = b.slice(0); a.forEach(function(i){ if (r.indexOf(i) < 0){ r.push(i); } }); return r; }
n/a
arrayUnionDeep = function (a, b) { var r = b.slice(0); a.forEach(function(ai) { var found = false; r.forEach(function(ri){ found = found || deepEqual(ai, ri); }); if(!found) { r.push(ai); } }); return r; }
n/a
autoExtFilename = function (filename, ext, config) { config = config || {}; if(typeof filename !== 'string' || filename.match(/^[A-z]+:\/\/|\n|\..{2,4}$/) || config.autoExt === 0 || config.autoExt === false ){ return filename; } return filename+'.'+ext }
...
});
s += ');\n';
}
// if(filename === '') {
// } else {
filename = alasql.utils.autoExtFilename(filename,'sql',opts);
res = alasql.utils.saveFile(filename,s);
if(cb){
res = cb(res);
}
return res;
};
...
function cloneDeep(obj) { if(null === obj || typeof(obj) !== 'object'){ return obj; } if(obj instanceof Date) { return new Date(obj); } var temp = obj.constructor(); // changed for(var key in obj) { if(obj.hasOwnProperty(key)) { temp[key] = cloneDeep(obj[key]); } } return temp; }
...
}
// if(this.alias) s += ' AS '+this.alias;
return s;
}
var stdlib = alasql.stdlib = {}
var stdfn = alasql.stdfn = {}
stdlib.ABS = function(a) {return 'Math.abs('+a+')'};
stdlib.CLONEDEEP = function(a) {return 'alasql.utils.cloneDeep('+a+')
x27;};
stdfn.CONCAT = function(){
return Array.prototype.slice.call(arguments).join('');
};
stdlib.EXP = function(a) {return 'Math.pow(Math.E,'+a+')'};
stdlib.IIF = function(a,b,c) {
if(arguments.length == 3) {
return '(('+a+')?('+b+'):('+c+'))';
...
deepEqual = function (x, y) { if(x===y){ return true; } if (typeof x === "object" && null !== x && (typeof y === "object" && null !== y)) { if (Object.keys(x).length !== Object.keys(y).length) { return false; } for (var prop in x) { if (!deepEqual(x[prop], y[prop])) { return false; } } return true; } return false; }
...
+ '(' + leftJS() + "==null)" // Cant be ===
+ " === "
+ '(' + rightJS() + "==null)" // Cant be ===
+ ')';
}
if(this.op === '==') {
s = ''
+ 'alasql.utils.deepEqual('
+ leftJS()
+ ','
+ rightJS()
+ ')';
}
if(this.op === '===' || this.op === '!===') {
s = ''
...
deleteFile = function (path, cb){ //*not-for-browser/* if(utils.isNode) { var fs = require('fs'); fs.unlink(path, cb); } else if(utils.isReactNative) { // If ReactNative var RNFS = require('react-native-fs'); RNFS.unlink(path).then(function(){ cb && cb(); }).catch(function(err){ throw err; }); } //*/ }
...
FS.dropDatabase = function(fsdbid, ifexists, cb){
var res;
var filename = fsdbid.value;
alasql.utils.fileExists(filename, function(fex){
if(fex) {
res = 1;
alasql.utils.deleteFile(filename, function(){
res = 1;
if(cb) res = cb(res);
});
} else {
if(!ifexists) {
throw new Error('Cannot drop database file, because it does not exist');
}
...
distinctArray = function (data) { var uniq = {}; // TODO: Speedup, because Object.keys is slow for(var i=0,ilen=data.length;i<ilen;i++) { var uix; if(typeof data[i] === 'object') { uix = Object.keys(data[i]).sort().map(function(k){return k+'`'+data[i][k];}).join('`'); } else { uix = data[i]; } uniq[uix] = data[i]; } var res = []; for(var key in uniq){ res.push(uniq[key]); } return res; }
n/a
domEmptyChildren = function (container){ var len = container.childNodes.length; while (len--) { container.removeChild(container.lastChild); } }
...
for(var i=0;i<columns.length;i++){
var the = document.createElement('td');
the.textContent = data[j][columns[i].columnid];
tre.appendChild(the);
}
tbody.appendChild(tre);
}
alasql.utils.domEmptyChildren(sel);
sel.appendChild(tbe);
}
if(cb){
res = cb(res);
}
return res;
...
doubleq = function (s) { return s.replace(/(\'\')/g,'\\\''); }
n/a
doubleqq = function (s) { return s.replace(/\'/g,"\'"); }
n/a
escapeq = function (s) { return ('' + s).replace(/["'\\\n\r\u2028\u2029]/g, function (character) { // Escape all characters not included in SingleStringCharacters and // DoubleStringCharacters on // http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4 switch (character) { case '"': case "'": case '\\': return '\\' + character // Four possible LineTerminator characters need to be escaped: case '\n': return '\\n' case '\r': return '\\r' case '\u2028': return '\\u2028' case '\u2029': return '\\u2029' } }) }
n/a
function extend(a, b){ a = a || {}; for(var key in b) { if(b.hasOwnProperty(key)) { a[key] = b[key]; } } return a; }
...
// Plugin sample
var yy = alasql.yy;
yy.Echo = function (params) { return yy.extend(this, params); }
yy.Echo.prototype.toString = function() {
var s = 'TEST '+this.expr.toString();
return s;
}
yy.Echo.prototype.execute = function (databaseid, params, cb) {
// var self = this;
...
fileExists = function (path, cb){ if(utils.isNode) { //*not-for-browser/* var fs = require('fs'); fs.exists(path,cb); } else if(utils.isCordova) { utils.global.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) { fileSystem.root.getFile(path, {create:false}, function (fileEntry) { cb(true); }, function(){ cb(false); }); }); } else if(utils.isReactNative) { // If ReactNative var RNFS = require('react-native-fs'); RNFS.exists(path).then(function(yes){ cb && cb(yes); }).catch(function(err){ throw err; }); //*/ } else { // TODO Cordova, etc. throw new Error('You can use exists() only in Node.js or Apach Cordova'); } }
...
var FS = alasql.engines.FILESTORAGE = alasql.engines.FILE = function (){};
FS.createDatabase = function(fsdbid, args, ifnotexists, dbid, cb){
var res = 1;
var filename = args[0].value;
alasql.utils.fileExists(filename, function(fex){
if(fex) {
if(ifnotexists) {
res = 0;
if(cb) res = cb(res);
return res;
} else {
...
findAlaSQLPath = function () { /** type {string} Path to alasql library and plugins */ if (utils.isWebWorker) { return ''; /** @todo Check how to get path in worker */ } else if(utils.isMeteorClient) { return '/packages/dist/'; } else if(utils.isMeteorServer) { return 'assets/packages/dist/'; } else if(utils.isNode) { return __dirname; } else if(utils.isBrowser) { var sc = document.getElementsByTagName('script'); for(var i=0;i<sc.length;i++) { if (sc[i].src.substr(-16).toLowerCase() === 'alasql-worker.js') { return sc[i].src.substr(0,sc[i].src.length-16); } else if (sc[i].src.substr(-20).toLowerCase() === 'alasql-worker.min.js') { return sc[i].src.substr(0,sc[i].src.length-20); } else if (sc[i].src.substr(-9).toLowerCase() === 'alasql.js') { return sc[i].src.substr(0,sc[i].src.length-9); } else if (sc[i].src.substr(-13).toLowerCase() === 'alasql.min.js') { return sc[i].src.substr(0,sc[i].src.length-13); } } } return ''; }
...
}
return XLSX;
}
var getXLS = function(){
return getXLSX();
}
// set AlaSQl path
alasql.path = alasql.utils.findAlaSQLPath();
/**
Strip all comments.
@function
@param {string} str
@return {string}
Based om the https://github.com/lehni/uncomment.js/blob/master/uncomment.js
I just replaced JavaScript's '//' to SQL's '--' and remove other stuff
...
flatArray = function (a) { if(!a || 0 === a.length){ return []; } // For recordsets if(typeof a === 'object' && a instanceof alasql.Recordset) { return a.data.map(function(ai){return ai[a.columns[0].columnid];}); } // Else for other arrays var key = Object.keys(a[0])[0]; if(key === undefined){ return []; } return a.map(function(ai) {return ai[key];}); }
...
/**
Select statement in expression
*/
yy.Select.prototype.toJS = function(context) {
// if(this.expression.reduced) return 'true';
// return this.expression.toJS(context, tableid, defcols);
// var s = 'this.queriesdata['+(this.queriesidx-1)+'][0]';
var s = 'alasql.utils.flatArray(this.queriesfn['+(this.queriesidx-1)+'
;](this.params,null,'+context+'))[0]';
return s;
};
// Compile SELECT statement
yy.Select.prototype.compile = function(databaseid, params) {
var db = alasql.databases[databaseid];
// Create variable for query
var query = new Query();
...
glob = function (value, pattern) { var i=0; var s = '^'; while(i<pattern.length) { var c = pattern[i], c1 = ''; if(i<pattern.length-1) c1 = pattern[i+1]; if(c==='[' && c1 === '^') { s += '[^'; i++; } else if(c==='[' || c===']' ) { s += c; } else if(c==='*') { s += '.*'; } else if(c === '?') { s += '.'; } else if('/.*+?|(){}'.indexOf(c)>-1) { s += '\\'+c; } else { s += c; } i++; } s += '$'; return (''+(value||'')).toUpperCase().search(RegExp(s.toUpperCase()))>-1; }
...
s = 'alasql.stdfn.REGEXP_LIKE('
+ leftJS()
+ ','
+ rightJS()
+ ')';
}
if(this.op === 'GLOB') {
s = 'alasql.utils.glob('
+ leftJS()
+ ','
+ rightJS()
+ ')';
}
if(this.op === 'BETWEEN' || this.op === 'NOT BETWEEN') {
var left = leftJS()
...
hash = function (str){ var hash = 5381, i = str.length while(i) hash = (hash * 33) ^ str.charCodeAt(--i) return hash; }
n/a
isArray = function (obj){ return "[object Array]"===Object.prototype.toString.call(obj); }
...
/*!
* @overview es6-promise - a tiny implementation of Promises/A+.
* @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald
)
* @license Licensed under MIT license
* See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
* @version 3.2.1
*/
(function(){"use strict";function t(t){return"function"==typeof t||"object"==typeof t&&
;null!==t}function e(t){return"function"==typeof t}function n(t){G=t}function r(t){Q=t}function o(){return function(){
process.nextTick(a)}}function i(){return function(){B(a)}}function s(){var t=0,e=new X(a),n=document.createTextNode("");
return e.observe(n,{characterData:!0}),function(){n.data=t=++t%2}}function u(){var t=new MessageChannel;return t.port1.onmessage
=a,function(){t.port2.postMessage(0)}}function c(){return function(){setTimeout(a,1)}}function a(){for(var t=0;J>t;t+=2){var
e=tt[t],n=tt[t+1];e(n),tt[t]=void 0,tt[t+1]=void 0}J=0}function f(){try{var t=require,e=t("vertx");return B=e.runOnLoop
||e.runOnContext,i()}catch(n){return c()}}function l(t,e){var n=this,r=new this.constructor(p);void 0===r[rt]&&k(r);var
o=n._state;if(o){var i=arguments[o-1];Q(function(){x(o,r,i,n._result)})}else E(n,r,t,e);return r}function h(t){var e=this;if(t
x26;&"object"==typeof t&&t.constructor===e)return t;var n=new e(p);return g(n,t),n}function p(){}function
_(){return new TypeError("You cannot resolve a promise with itself")}function d(){return new TypeError("A promises
callback cannot return that same promise.")}function v(t){try{return t.then}catch(e){return ut.error=e,ut}}function y(t,e,
n,r){try{t.call(e,n,r)}catch(o){return o}}function m(t,e,n){Q(function(t){var r=!1,o=y(n,e,function(n){r||(r=!0,e!==n?g(t,n):S(t
,n))},function(e){r||(r=!0,j(t,e))},"Settle: "+(t._label||" unknown promise"));!r&&o&&(r
=!0,j(t,o))},t)}function b(t,e){e._state===it?S(t,e._result):e._state===st?j(t,e._result):E(e,void 0,function(e){g(t,e)},function
(e){j(t,e)})}function w(t,n,r){n.constructor===t.constructor&&r===et&&constructor.resolve===nt?b(t,n):r===ut
?j(t,ut.error):void 0===r?S(t,n):e(r)?m(t,n,r):S(t,n)}function g(e,n){e===n?j(e,_()):t(n)?w(e,n,v(n)):S(e,n)}function A(t){t._onerror
&&t._onerror(t._result),T(t)}function S(t,e){t._state===ot&&(t._result=e,t._state=it,0!==t._subscribers.length
&&Q(T,t))}function j(t,e){t._state===ot&&(t._state=st,t._result=e,Q(A,t))}function E(t,e,n,r){var o=t._subscribers
,i=o.length;t._onerror=null,o[i]=e,o[i+it]=n,o[i+st]=r,0===i&&t._state&&Q(T,t)}function T(t){var e=t._subscribers
,n=t._state;if(0!==e.length){for(var r,o,i=t._result,s=0;s<e.length;s+=3)r=e[s],o=e[s+n],r?x(n,r,o,i):o(i);t._subscribers.length
=0}}function M(){this.error=null}function P(t,e){try{return t(e)}catch(n){return ct.error=n,ct}}function x(t,n,r,o){var i,s,u,c,
a=e(r);if(a){if(i=P(r,o),i===ct?(c=!0,s=i.error,i=null):u=!0,n===i)return void j(n,d())}else i=o,u=!0;n._state!==ot||(a&&
;u?g(n,i):c?j(n,s):t===it?S(n,i):t===st&&j(n,i))}function C(t,e){try{e(function(e){g(t,e)},function(e){j(t,e)})}catch(
n){j(t,n)}}function O(){return at++}function k(t){t[rt]=at++,t._state=void 0,t._result=void 0,t._subscribers=[]}function Y(t){return
new _t(this,t).promise}function q(t){var e=this;return new e(I(t)?function(n,r){for(var o=t.length,i=0;o>i;i++)e.resolve(t
[i]).then(n,r)}:function(t,e){e(new TypeError("You must pass an array to race."))})}function F(t){var e=this,n=new e(p
);return j(n,t),n}function D(){throw new TypeError("You must pass a resolver function as the first argument to the promise
constructor")}function K(){throw new TypeError("Failed to construct 'Promise': Please use the 'new'
; operator, this object constructor cannot be called as a function.")}function L(t){this[rt]=O(),this._result=this._state=void
0,this._subscribers=[],p!==t&&("function"!=typeof t&&D(),this instanceof L?C(this,t):K())}function
N(t,e){this._instanceConstructor=t,this.promise=new t(p),this.promise[rt]||k(this.promise),Array.isArray(e)?(this._input=e,this.length=e.length,this._remaining=e.length,this._result=new Array(this.length),0===this.length
?S(this.promise,this._result):(this.length=this.length||0,this._enumerate(),0===this._remaining&&S(this.promise,this._result
))):j(this.promise,U())}function U(){return new Error("Array Methods must be provided an Array")}function W(){var t;if
("undefined"!=typeof global)t=global;else if("undefined"!=typeof self)t=self;else try{t=Function("return
this")()}catch(e){throw new Error("polyfill failed because global object is unavailable in this environment")}var
n=t.Promise;(!n||"[object Promise]"!==Object.prototype.toString.call(n.resolve())||n.cast)&&(t.Promise=pt)}
var z;z=Array.isArray?Array.isArray:function(t){return"[object Array]"===Object.prototype.toString.call(t)};var B,G,H,
I=z,J=0,Q=function(t,e){tt[J]=t,tt[J+1]=e,J+=2,2===J&&(G?G(a):H())},R="undefined"!=typeof window?window:void
0,V=R||{},X=V.MutationObserver||V.WebKitMutationObserver,Z="undefined"==typeof self&&"undefined"!=
typeof process&&"[object process]"==={}.toString.call(process),$="undefined"!=typeof Uint8ClampedArray
&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel,tt=new Array(1e3
);H=Z?o():X?s():$?u():void 0===R&&"function"==typeof require?f():c();var et=l,nt=h,rt=Math.random().toString
(36).substring(16),ot=void 0,it=1,st=2,ut=new M,ct=new M,at=0,ft=Y,lt=q,ht=F,pt=L;L.all=ft,L.race=lt,L.resolve=nt,L.reject=ht,L.
_setScheduler=n,L._setAsap=r,L._asap=Q,L.prototype={constructor:L,then:et,"catch":function(t){return this.then(null,t)}};
var _t=N;N.prototype._enumerate=function(){for(var t=this.length,e=this._input,n=0;this._state===ot&&t>n;n++)this
._eachEntry(e[n],n)},N.prototype._eachEntry=function(t,e){var n=this._instanceConstructor,r=n.resolve;if(r===nt){var o=v(t);if(o
===et&&t._state!==ot)this._settledAt(t._state,e,t._result);else if("function"!=typeof o)this._remaining--,this
._result[e]=t;else if(n===pt){var i=new n(p);w(i,t,o),this._willSettleAt(i,e)}else this._willSettleAt(new n(function(e){e(t)}),e
)}else this._willSettleAt(r(t),e)},N.prototype._settledAt=function(t,e,n){var r=this.promise;r._state===ot&&(this._remaining
--,t===st?j(r,n):this._result[e]=n),0===this._remaining&&S(r,this._result)},N.prototype._willSettleAt=function(t,e){var
n=this;E(t,void 0,function(t){n._settledAt(it,e,t)},function(t){n._settledAt(st,e,t)})};var dt=W,vt={Promise:pt,polyfill:dt};
x22;function"==typeof define&&define.amd?define(function(){return vt}):"undefined"!=typeof module&
x26;module.exports?module.exports=vt:"undefined"!=typeof this&&(this.ES6Promise=vt),dt()}).call(this);
}
}
var promiseExec = function(sql, params, counterStep, counterTotal){
return new utils.global.Promise(function(resolve, reject){
alasql(sql, params, function(data,err) {
...
isNativeFunction = function (fn){ return typeof fn === "function" && !!~(fn.toString().indexOf("[native code]")); }
...
/**
Find out if code is running in a web worker enviroment
@return {boolean} True if code is running in a web worker enviroment
*/
utils.isWebWorker = (function(){
try{
var importScripts = utils.global.importScripts;
return (utils.isNativeFunction(importScripts));
}catch(e){
return false;
}
})();
/**
Find out if code is running in a node enviroment
@return {boolean} True if code is running in a node enviroment
...
like = function (pattern, value, escape) { // Verify escape character if(!escape) escape = ''; var i=0; var s = '^'; while(i<pattern.length) { var c = pattern[i], c1 = ''; if(i<pattern.length-1) c1 = pattern[i+1]; if(c === escape) { s += '\\'+c1; i++; } else if(c==='[' && c1 === '^') { s += '[^'; i++; } else if(c==='[' || c===']' ) { s += c; } else if(c==='%') { s += '.*'; } else if(c === '_') { s += '.'; } else if('/.*+?|(){}'.indexOf(c)>-1) { s += '\\'+c; } else { s += c; } i++; } s += '$'; return (''+(value||'')).toUpperCase().search(RegExp(s.toUpperCase()))>-1; }
...
var removeLikeKeys = query.removeLikeKeys;
// Remove unused columns
// SELECT * REMOVE COLUMNS LIKE "%b"
for(var i=0,ilen=query.data.length;i<ilen;i++) {
r = query.data[i];
for(var k in r) {
for(j=0;j<query.removeLikeKeys.length;j++) {
if(alasql.utils.like(query.removeLikeKeys[j],k)) {
delete r[k];
}
}
}
}
if(query.columns.length > 0) {
query.columns = query.columns.filter(function(column){
...
loadBinaryFile = function (path, asy, success, error) { var fs; if(utils.isNode || utils.isMeteorServer) { //*not-for-browser/* if(utils.isMeteorServer) { fs = Npm.require('fs'); // For Meteor } else { fs = require('fs'); } if(/^[a-z]+:\/\//i.test(path)) { var request = require('request'); request({url:path,encoding:null},function(err, response, data) { if(err) { throw err; } var arr = []; for(var i = 0; i < data.length; ++i){ arr[i] = String.fromCharCode(data[i]); } success(arr.join("")); }); } else { if(asy) { fs.readFile(path,function(err,data){ if(err) { throw err; } var arr = []; for(var i = 0; i < data.length; ++i){ arr[i] = String.fromCharCode(data[i]); } success(arr.join("")); }); } else { var data = fs.readFileSync(path); var arr = []; for(var i = 0; i < data.length; ++i){ arr[i] = String.fromCharCode(data[i]); } success(arr.join("")); } } } else if(utils.isReactNative) { // If ReactNative //var RNFS = require('react-native-fs'); var RNFetchBlob = require('react-native-fetch-blob').default var dirs = RNFetchBlob.fs.dirs //should use readStream instead if the file is large RNFetchBlob.fs.readFile(path, 'base64').then(function(data){ //RNFetchBlob.base64.decode(data) //need more test on excel success(data); }) //*/ } else { if(typeof path === "string") { // For browser var xhr = new XMLHttpRequest(); xhr.open("GET", path, asy); // Async xhr.responseType = "arraybuffer"; xhr.onload = function() { var data = new Uint8Array(xhr.response); var arr = []; for(var i = 0; i < data.length; ++i){ arr[i] = String.fromCharCode(data[i]); } success(arr.join("")); } // xhr.responseType = "blob"; xhr.send(); } else if(path instanceof Event) { var files = path.target.files; var reader = new FileReader(); var name = files[0].name; reader.onload = function(e) { var data = e.target.result; success(data); }; reader.readAsArrayBuffer(files[0]); } else if(path instanceof Blob) { success(path); } } }
...
};
/** @type {object} Workbook */
var wb = {SheetNames:[], Sheets:{}};
// ToDo: check if cb must be treated differently here
if(opts.sourcefilename) {
alasql.utils.loadBinaryFile(opts.sourcefilename,!!cb,function(data){
wb = XLSX.read(data,{type:'binary'});
doExport();
});
} else {
doExport();
};
...
loadFile = function (path, asy, success, error) { var data, fs; if(utils.isNode || utils.isMeteorServer) { //*not-for-browser/* if(utils.isMeteor) { fs = Npm.require('fs'); } else { fs = require('fs'); } // If path is empty, than read data from stdin (for Node) if(typeof path === 'undefined') { var buff = ''; process.stdin.setEncoding('utf8'); process.stdin.on('readable', function() { var chunk = process.stdin.read(); if (chunk !== null) { buff += chunk.toString(); } }); process.stdin.on('end', function() { success(cutbom(buff)); }); } else { if(/^[a-z]+:\/\//i.test(path)) { var request = require('request'); request(path,function(err, response, body) { if(err) { throw err; } success(cutbom(body.toString())); }); } else { //If async callthen call async if(asy) { fs.readFile(path,function(err,data){ if(err) { throw err; } success(cutbom(data.toString())); }); } else { // Call sync version data = fs.readFileSync(path); success(cutbom(data.toString())); } } } } else if(utils.isReactNative) { // If ReactNative var RNFS = require('react-native-fs'); RNFS.readFile(path,'utf8').then(function(contents){ success(cutbom(contents)); }).catch(function(err){ throw err; }); //*/ } else if(utils.isCordova) { /* If Cordova */ utils.global.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) { fileSystem.root.getFile(path, {create:false}, function (fileEntry) { fileEntry.file(function(file){ var fileReader = new FileReader(); fileReader.onloadend = function(e){ success(cutbom(this.result)); }; fileReader.readAsText(file); }); }); }); /** @todo Check eliminated code below */ } else { /* For string */ if(typeof path === "string") { // For browser read from tag /* SELECT * FROM TXT('#one') -- read data from HTML element with id="one" */ if((path.substr(0,1) === '#') && (typeof document !== 'undefined')) { data = document.querySelector(path).textContent; success(data); } else { /* Simply read file from HTTP request, like: SELECT * FROM TXT('http://alasql.org/README.md'); */ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status === 200) { if (success){ success(cutbom(xhr.responseText)); } } else if (error){ error(xhr); } // Todo: else...? } }; xhr.open("GET", path, asy); // Async xhr.responseType = "text"; xhr.send(); } } else if(path instanceof Event) { /* For browser read from files input element <input type="files" onchange="readFile(event)"> <script> ...
...
// Read JSON file
alasql.from.JSON = function(filename, opts, cb, idx, query) {
var res;
filename = alasql.utils.autoExtFilename(filename,'json',opts);
alasql.utils.loadFile(filename,!!cb,function(data){
res = JSON.parse(data);
if(cb){
res = cb(res, idx, query);
}
});
return res;
...
removeFile = function (path, cb) { if(utils.isNode) { //*not-for-browser/* var fs = require('fs'); fs.remove(path,cb); } else if(utils.isCordova) { utils.global.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) { fileSystem.root.getFile(path, {create:false}, function (fileEntry) { fileEntry.remove(cb); cb && cb(); // jshint ignore:line }, function(){ cb && cb(); // jshint ignore:line }); }); } else if(utils.isReactNative) { // If ReactNative var RNFS = require('react-native-fs'); RNFS.unlink(path).then(function(){ cb && cb(); }).catch(function(err){ throw err; }); //*/ } else { throw new Error('You can remove files only in Node.js and Apache Cordova'); } }
n/a
saveFile = function (path, data, cb, opts) { var res = 1; if(path === undefined) { // // Return data into result variable // like: alasql('SELECT * INTO TXT() FROM ?',[data]); // res = data; if(cb){ res = cb(res); } } else { if(utils.isNode) { //*not-for-browser/* var fs = require('fs'); data = fs.writeFileSync(path,data); if(cb){ res = cb(res); } }else if(utils.isReactNative) { var RNFS = require('react-native-fs'); RNFS.writeFile(path, data).then(function(success){ //, 'utf8' if(cb) res = cb(res); }).catch(function(err){ console.log(err.message); }); } else if(utils.isCordova) { utils.global.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) { fileSystem.root.getFile(path, {create:true}, function (fileEntry) { fileEntry.createWriter(function(fileWriter) { fileWriter.onwriteend = function(){ if(cb){ res = cb(res); } } fileWriter.write(data); }); }); }); //*/ } else { if(isIE() === 9) { // Solution was taken from // http://megatuto.com/formation-JAVASCRIPT.php?JAVASCRIPT_Example=Javascript+Save+CSV+file+in+IE+8/IE+9+without+using +window.open()+Categorie+javascript+internet-explorer-8&category=&article=7993 // Prepare data var ndata = data.replace(/\r\n/g,'&#A;&#D;'); ndata = ndata.replace(/\n/g,'&#D;'); ndata = ndata.replace(/\t/g,'	'); var testlink = utils.global.open("about:blank", "_blank"); testlink.document.write(ndata); //fileData has contents for the file testlink.document.close(); testlink.document.execCommand('SaveAs', false, path); testlink.close(); } else { var opt = { disableAutoBom: false }; alasql.utils.extend(opt, opts); var blob = new Blob([data], {type: "text/plain;charset=utf-8"}); saveAs(blob, path, opt.disableAutoBom); if(cb){ res = cb(res); } } } } return res; }
...
s += ');\n';
}
// if(filename === '') {
// } else {
filename = alasql.utils.autoExtFilename(filename,'sql',opts);
res = alasql.utils.saveFile(filename,s);
if(cb){
res = cb(res);
}
return res;
};
alasql.into.HTML = function(selector, opts, data, columns, cb) {
...
function uncomment(str) {
// Add some padding so we can always look ahead and behind by two chars
str = ('__' + str + '__').split('');
var quote = false,
quoteSign,
// regularExpression = false,
// characterClass = false,
blockComment = false,
lineComment = false;
// preserveComment = false;
for (var i = 0, l = str.length; i < l; i++) {
// When checking for quote escaping, we also need to check that the
// escape sign itself is not escaped, as otherwise '\\' would cause
// the wrong impression of an unclosed string:
var unescaped = str[i - 1] !== '\\' || str[i - 2] === '\\';
if (quote) {
if (str[i] === quoteSign && unescaped){
quote = false;
}
} else if (blockComment) {
// Is the block comment closing?
if (str[i] === '*' && str[i + 1] === '/') {
// if (!preserveComment)
str[i] = str[i + 1] = '';
blockComment /* = preserveComment*/ = false;
// Increase by 1 to skip closing '/', as it would be mistaken
// for a regexp otherwise
i++;
} else { //if (!preserveComment) {
str[i] = '';
}
} else if (lineComment) {
// One-line comments end with the line-break
if (str[i + 1] === '\n' || str[i + 1] === '\r'){
lineComment = false;
}
str[i] = '';
} else {
if (str[i] === '"' || str[i] === "'") {
quote = true;
quoteSign = str[i];
} else if (str[i] === '[' && str[i-1] !== "@") {
quote = true;
quoteSign = ']';
// } else if (str[i] === '-' && str[i + 1] === '-') {
// str[i] = '';
// lineComment = true;
} else if (str[i] === '/' && str[i + 1] === '*') {
// Do not filter out conditional comments /*@ ... */
// and comments marked as protected /*! ... */
str[i] = '';
blockComment = true;
}
}
}
// Remove padding again.
str = str.join('').slice(2, -2);
return str;
}
...
@todo Add other parsers
@example
alasql.parse = function(sql) {
// My own parser here
}
*/
alasql.parse = function(sql) {
return alasqlparser.parse(alasql.utils.uncomment(sql));
};
/**
List of engines of external databases
@type {object}
@todo Create collection type
*/
alasql.engines = {};
...
undoubleq = function (s) { return s.replace(/(\')/g,'\'\''); }
n/a
xlscn = function (s) { var n = s.charCodeAt(0)-65; if(s.length>1) { n = (n+1)*26+s.charCodeAt(1)-65; if(s.length>2) { n = (n+1)*26+s.charCodeAt(2)-65; } } return n; }
...
wb.Sheets[opt.sheetid] = {};
cells = wb.Sheets[opt.sheetid];
}
var range = "A1";
if(opt.range) range = opt.range;
var col0 = alasql.utils.xlscn(range.match(/[A-Z]+/)[0]);
var row0 = +range.match(/[0-9]+/)[0]-1;
if(wb.Sheets[opt.sheetid]['!ref']) {
var rangem = wb.Sheets[opt.sheetid]['!ref'];
var colm = alasql.utils.xlscn(rangem.match(/[A-Z]+/)[0]);
var rowm = +rangem.match(/[0-9]+/)[0]-1;
} else {
...
xlsnc = function (i) { var addr = String.fromCharCode(65+i%26); if(i>=26) { i=((i/26)|0)-1; addr = String.fromCharCode(65+i%26)+addr; if(i>26) { i=((i/26)|0)-1; addr = String.fromCharCode(65+i%26)+addr; } } return addr; }
...
var colm = 1, rowm = 1;
}
var colmax = Math.max(col0+columns.length,colm);
var rowmax = Math.max(row0+dataLength+2,rowm);
var i = row0+1;
wb.Sheets[opt.sheetid]['!ref'] = 'A1:'+alasql.utils.xlsnc(colmax
)+(rowmax);
if(opt.headers) {
columns.forEach(function(col, idx){
cells[alasql.utils.xlsnc(col0+idx)+""+i] = {v:col.columnid.trim()};
});
i++;
}
...
AggrValue = function (params){ return yy.extend(this, params); }
...
this.$ = new yy.FuncValue({funcid:'CURRENT_TIMESTAMP'});
break;
case 327:
if($$[$0-2].length > 1 && ($$[$0-4].toUpperCase() == 'MAX' || $$[$0-4].toUpperCase() == 'MIN
x27;)) {
this.$ = new yy.FuncValue({funcid:$$[$0-4],args:$$[$0-2]});
} else {
this.$ = new yy.AggrValue({aggregatorid: $$[$0-4].toUpperCase(), expression: $$[$0
-2].pop(), over:$$[$0]});
}
break;
case 328:
this.$ = new yy.AggrValue({aggregatorid: $$[$0-5].toUpperCase(), expression: $$[$0-2], distinct:true, over:$$[$0]});
break;
case 329:
this.$ = new yy.AggrValue({aggregatorid: $$[$0-5].toUpperCase(), expression: $$[$0-2],
...
AlterTable = function (params) { return yy.extend(this, params); }
...
case 564:
this.$ = new yy.DropTable({tables:$$[$0],type:$$[$0-2]}); yy.extend(this.$, $$[$0-1]);
break;
case 568:
this.$ = {ifexists: true};
break;
case 569:
this.$ = new yy.AlterTable({table:$$[$0-3], renameto: $$[$0]});
break;
case 570:
this.$ = new yy.AlterTable({table:$$[$0-3], addcolumn: $$[$0]});
break;
case 571:
this.$ = new yy.AlterTable({table:$$[$0-3], modifycolumn: $$[$0]});
break;
...
Apply = function (params) { return yy.extend(this, params); }
...
case 170:
this.$ = { from: $$[$0-1], joins: $$[$0] };
break;
case 171:
this.$ = { from: $$[$0-2], joins: $$[$0-1] };
break;
case 173:
this.$ = new yy.Apply({select: $$[$0-2], applymode:'CROSS', as:$$[$0]});
break;
case 174:
this.$ = new yy.Apply({select: $$[$0-3], applymode:'CROSS', as:$$[$0]});
break;
case 175:
this.$ = new yy.Apply({select: $$[$0-2], applymode:'OUTER', as:$$[$0]});
break;
...
ArrayValue = function (params) { return yy.extend(this, params); }
...
case 363:
if(!yy.exists) yy.exists = [];
this.$ = new yy.ExistsValue({value:$$[$0-1], existsidx:yy.exists.length});
yy.exists.push($$[$0-1]);
break;
case 364:
this.$ = new yy.ArrayValue({value:$$[$0-1]});
break;
case 365: case 366:
this.$ = new yy.ParamValue({param: $$[$0]});
break;
case 367:
if(typeof yy.question == 'undefined') yy.question = 0;
...
Assert = function (params) { return yy.extend(this, params); }
...
case 614: case 760:
this.$ = new yy.ExpressionStatement({expression:$$[$0]});
break;
case 615:
this.$ = new yy.Source({url:$$[$0].value});
break;
case 616:
this.$ = new yy.Assert({value:$$[$0]});
break;
case 617:
this.$ = new yy.Assert({value:$$[$0].value});
break;
case 618:
this.$ = new yy.Assert({value:$$[$0], message:$$[$0-2]});
break;
...
AttachDatabase = function (params) { return yy.extend(this, params); }
...
case 573:
this.$ = new yy.AlterTable({table:$$[$0-3], dropcolumn: $$[$0]});
break;
case 574:
this.$ = new yy.AlterTable({table:$$[$0-2], renameto: $$[$0]});
break;
case 575:
this.$ = new yy.AttachDatabase({databaseid:$$[$0], engineid:$$[$0-2].toUpperCase() });
break;
case 576:
this.$ = new yy.AttachDatabase({databaseid:$$[$0-3], engineid:$$[$0-5].toUpperCase(), args:$$[$0-1] });
break;
case 577:
this.$ = new yy.AttachDatabase({databaseid:$$[$0-2], engineid:$$[$0-4].toUpperCase(), as:$$[$0] });
break;
...
Base = function (params) { return yy.extend(this, params); }
n/a
BeginEnd = function (params) { return yy.extend(this, params); }
...
case 672:
this.$ = new yy.Continue();
break;
case 673:
this.$ = new yy.Break();
break;
case 674:
this.$ = new yy.BeginEnd({statements:$$[$0-1]});
break;
case 675:
this.$ = new yy.Print({exprs:$$[$0]});
break;
case 676:
this.$ = new yy.Print({select:$$[$0]});
break;
...
BeginTransaction = function (params) { return yy.extend(this, params); }
...
case 665:
this.$ = new yy.CommitTransaction();
break;
case 666:
this.$ = new yy.RollbackTransaction();
break;
case 667:
this.$ = new yy.BeginTransaction();
break;
case 668:
this.$ = new yy.If({expression:$$[$0-2],thenstat:$$[$0-1], elsestat:$$[$0]});
if($$[$0-1].exists) this.$.exists = $$[$0-1].exists;
if($$[$0-1].queries) this.$.queries = $$[$0-1].queries;
break;
case 669:
...
Break = function (params) { return yy.extend(this, params); }
...
if($$[$0].exists) this.$.exists = $$[$0].exists;
if($$[$0].queries) this.$.queries = $$[$0].queries;
break;
case 672:
this.$ = new yy.Continue();
break;
case 673:
this.$ = new yy.Break();
break;
case 674:
this.$ = new yy.BeginEnd({statements:$$[$0-1]});
break;
case 675:
this.$ = new yy.Print({exprs:$$[$0]});
break;
...
CaseValue = function (params) { return yy.extend(this, params); }
...
break;
case 368:
if(typeof yy.question == 'undefined') yy.question = 0;
this.$ = new yy.ParamValue({param: yy.question++, array:true});
break;
case 369:
this.$ = new yy.CaseValue({expression:$$[$0-3], whens: $$[$0-2], elses: $$[$0-1]});
break;
case 370:
this.$ = new yy.CaseValue({whens: $$[$0-2], elses: $$[$0-1]});
break;
case 371: case 699: case 700:
this.$ = $$[$0-1]; this.$.push($$[$0]);
break;
...
Column = function (params) { return yy.extend(this, params); }
...
alasql.webworker.postMessage({id:id,sql:sql,params:params});
return;
}
if(arguments.length === 0) {
// Without arguments - Fluent interface
return new yy.Select({
columns:[new yy.Column({columnid:'*'})],
from: [new yy.ParamValue({param:0})]
});
} else if(arguments.length === 1){
// Access promise notation without using `.promise(...)`
if(sql.constructor === Array){
return alasql.promise(sql);
}
...
ColumnDef = function (params) { return yy.extend(this, params); }
...
this.$ = {type: 'FOREIGN KEY', columns: $$[$0-5], fktable: $$[$0-2], fkcolumns: $$[$0-1]};
break;
case 525:
this.$ = {type: 'UNIQUE', columns: $$[$0-1], clustered:($$[$0-3]+'').toUpperCase()};
break;
case 534:
this.$ = new yy.ColumnDef({columnid:$$[$0-2]}); yy.extend(this.$,$$[$0-1]); yy.extend
(this.$,$$[$0]);
break;
case 535:
this.$ = new yy.ColumnDef({columnid:$$[$0-1]}); yy.extend(this.$,$$[$0]);
break;
case 536:
this.$ = new yy.ColumnDef({columnid:$$[$0], dbtypeid: ''});
break;
...
CommitTransaction = function (params) { return yy.extend(this, params); }
...
case 663:
this.$ = true;
break;
case 664:
this.$ = false;
break;
case 665:
this.$ = new yy.CommitTransaction();
break;
case 666:
this.$ = new yy.RollbackTransaction();
break;
case 667:
this.$ = new yy.BeginTransaction();
break;
...
Continue = function (params) { return yy.extend(this, params); }
...
break;
case 671:
this.$ = new yy.While({expression:$$[$0-1],loopstat:$$[$0]});
if($$[$0].exists) this.$.exists = $$[$0].exists;
if($$[$0].queries) this.$.queries = $$[$0].queries;
break;
case 672:
this.$ = new yy.Continue();
break;
case 673:
this.$ = new yy.Break();
break;
case 674:
this.$ = new yy.BeginEnd({statements:$$[$0-1]});
break;
...
Convert = function (params) { return yy.extend(this, params); }
...
case 314:
this.$ = new yy.FuncValue({funcid:$$[$0], newid:true});
break;
case 315:
this.$ = $$[$0]; yy.extend(this.$,{newid:true});
break;
case 316:
this.$ = new yy.Convert({expression:$$[$0-3]}) ; yy.extend(this.$,$$[$0-1]) ;
break;
case 317:
this.$ = new yy.Convert({expression:$$[$0-5], style:$$[$0-1]}) ; yy.extend(this.$,$$[$0-3]) ;
break;
case 318:
this.$ = new yy.Convert({expression:$$[$0-1]}) ; yy.extend(this.$,$$[$0-3]) ;
break;
...
CreateDatabase = function (params) { return yy.extend(this, params); }
...
case 578:
this.$ = new yy.AttachDatabase({databaseid:$$[$0-5], engineid:$$[$0-7].toUpperCase(), as:$$[$0], args:$$[$0-3]});
break;
case 579:
this.$ = new yy.DetachDatabase({databaseid:$$[$0]});
break;
case 580:
this.$ = new yy.CreateDatabase({databaseid:$$[$0] }); yy.extend(this.$,$$[$0]);
break;
case 581:
this.$ = new yy.CreateDatabase({engineid:$$[$0-4].toUpperCase(), databaseid:$$[$0-1], as:$$[$0] }); yy.extend(this.$,$$[$0-2]);
break;
case 582:
this.$ = new yy.CreateDatabase({engineid:$$[$0-7].toUpperCase(), databaseid:$$[$0-4], args:$$[$0-2], as:$$[$0] }); yy.extend(this
.$,$$[$0-5]);
break;
...
CreateEdge = function (params) { return yy.extend(this, params); }
...
this.$ = {content:$$[$0]};
break;
case 727:
this.$ = {select:$$[$0]};
break;
case 728:
this.$ = new yy.CreateEdge({from:$$[$0-3],to:$$[$0-1],name:$$[$0-5]});
yy.extend(this.$,$$[$0]);
break;
case 729:
this.$ = new yy.CreateGraph({graph:$$[$0]});
break;
case 730:
this.$ = new yy.CreateGraph({from:$$[$0]});
...
CreateGraph = function (params) { return yy.extend(this, params); }
...
break;
case 728:
this.$ = new yy.CreateEdge({from:$$[$0-3],to:$$[$0-1],name:$$[$0-5]});
yy.extend(this.$,$$[$0]);
break;
case 729:
this.$ = new yy.CreateGraph({graph:$$[$0]});
break;
case 730:
this.$ = new yy.CreateGraph({from:$$[$0]});
break;
case 733:
this.$ = $$[$0-2];
...
CreateIndex = function (params) { return yy.extend(this, params); }
...
case 588:
this.$ = new yy.DropDatabase({databaseid: $$[$0] }); yy.extend(this.$,$$[$0-1]);
break;
case 589: case 590:
this.$ = new yy.DropDatabase({databaseid: $$[$0], engineid:$$[$0-3].toUpperCase() }); yy.extend(this.$,$$[$0-1]);
break;
case 591:
this.$ = new yy.CreateIndex({indexid:$$[$0-5], table:$$[$0-3], columns:$$[$0-1]})
break;
case 592:
this.$ = new yy.CreateIndex({indexid:$$[$0-5], table:$$[$0-3], columns:$$[$0-1], unique:true})
break;
case 593:
this.$ = new yy.DropIndex({indexid:$$[$0]});
break;
...
CreateTable = function (params) { return yy.extend(this, params); }
...
this.$ = $$[$0-4]; $$[$0-4].push($$[$0-1])
break;
case 477: case 478: case 480: case 488:
this.$ = $$[$0-2]; $$[$0-2].push($$[$0])
break;
case 489:
this.$ = new yy.CreateTable({table:$$[$0-4]});
yy.extend(this.$,$$[$0-7]);
yy.extend(this.$,$$[$0-6]);
yy.extend(this.$,$$[$0-5]);
yy.extend(this.$,$$[$0-2]);
yy.extend(this.$,$$[$0]);
break;
case 490:
...
CreateTrigger = function (params) { return yy.extend(this, params); }
...
this.$ = new yy.Term({termid:$$[$0]});
break;
case 758:
this.$ = new yy.Term({termid:$$[$0-3],args:$$[$0-1]});
break;
case 761:
this.$ = new yy.CreateTrigger({trigger:$$[$0-6], when:$$[$0-5], action:$$[$0-4], table
:$$[$0-2], statement:$$[$0]});
if($$[$0].exists) this.$.exists = $$[$0].exists;
if($$[$0].queries) this.$.queries = $$[$0].queries;
break;
case 762:
this.$ = new yy.CreateTrigger({trigger:$$[$0-5], when:$$[$0-4], action:$$[$0-3], table:$$[$0-1], funcid:$$[$0]});
break;
...
CreateVertex = function (params) { return yy.extend(this, params); }
...
this.$ = {output:{columns:$$[$0-2], intotable: $$[$0]}}
break;
case 721:
this.$ = {output:{columns:$$[$0-5], intotable: $$[$0-3], intocolumns:$$[$0-1]}}
break;
case 722:
this.$ = new yy.CreateVertex({class:$$[$0-3],sharp:$$[$0-2], name:$$[$0-1]});
yy.extend(this.$,$$[$0]);
break;
case 725:
this.$ = {sets:$$[$0]};
break;
case 726:
this.$ = {content:$$[$0]};
...
Declare = function (params) { return yy.extend(this, params); }
...
case 679: case 680:
this.$ = $$[$0].toUpperCase();
break;
case 681:
this.$ = new yy.Echo({expr:$$[$0]});
break;
case 686:
this.$ = new yy.Declare({declares:$$[$0]});
break;
case 689:
this.$ = {variable: $$[$0-1]}; yy.extend(this.$,$$[$0]);
break;
case 690:
this.$ = {variable: $$[$0-2]}; yy.extend(this.$,$$[$0]);
break;
...
Delete = function (params) { return yy.extend(this, params); }
...
case 453:
this.$ = new yy.SetColumn({column:$$[$0-2], expression:$$[$0]})
break;
case 454:
this.$ = new yy.SetColumn({variable:$$[$0-2], expression:$$[$0], method:$$[$0-3]})
break;
case 455:
this.$ = new yy.Delete({table:$$[$0-2], where:$$[$0]});
break;
case 456:
this.$ = new yy.Delete({table:$$[$0]});
break;
case 457:
this.$ = new yy.Insert({into:$$[$0-2], values: $$[$0]});
break;
...
DetachDatabase = function (params) { return yy.extend(this, params); }
...
case 577:
this.$ = new yy.AttachDatabase({databaseid:$$[$0-2], engineid:$$[$0-4].toUpperCase(), as:$$[$0] });
break;
case 578:
this.$ = new yy.AttachDatabase({databaseid:$$[$0-5], engineid:$$[$0-7].toUpperCase(), as:$$[$0], args:$$[$0-3]});
break;
case 579:
this.$ = new yy.DetachDatabase({databaseid:$$[$0]});
break;
case 580:
this.$ = new yy.CreateDatabase({databaseid:$$[$0] }); yy.extend(this.$,$$[$0]);
break;
case 581:
this.$ = new yy.CreateDatabase({engineid:$$[$0-4].toUpperCase(), databaseid:$$[$0-1], as:$$[$0] }); yy.extend(this.$,$$[$0-2]);
break;
...
DomainValueValue = function (params) { return yy.extend(this, params); }
...
case 285: case 286:
this.$ = new yy.Column({columnid: $$[$0], tableid: $$[$0-2]});
break;
case 287:
this.$ = new yy.Column({columnid: $$[$0]});
break;
case 302:
this.$ = new yy.DomainValueValue();
break;
case 303:
this.$ = new yy.Json({value:$$[$0]});
break;
case 306: case 307: case 308:
if(!yy.queries) yy.queries = [];
...
DropDatabase = function (params) { return yy.extend(this, params); }
...
case 584:
this.$ = undefined;
break;
case 586: case 587:
this.$ = new yy.UseDatabase({databaseid: $$[$0] });
break;
case 588:
this.$ = new yy.DropDatabase({databaseid: $$[$0] }); yy.extend(this.$,$$[$0-1]);
break;
case 589: case 590:
this.$ = new yy.DropDatabase({databaseid: $$[$0], engineid:$$[$0-3].toUpperCase() }); yy.extend(this.$,$$[$0-1]);
break;
case 591:
this.$ = new yy.CreateIndex({indexid:$$[$0-5], table:$$[$0-3], columns:$$[$0-1]})
break;
...
DropIndex = function (params) { return yy.extend(this, params); }
...
case 591:
this.$ = new yy.CreateIndex({indexid:$$[$0-5], table:$$[$0-3], columns:$$[$0-1]})
break;
case 592:
this.$ = new yy.CreateIndex({indexid:$$[$0-5], table:$$[$0-3], columns:$$[$0-1], unique:true})
break;
case 593:
this.$ = new yy.DropIndex({indexid:$$[$0]});
break;
case 594:
this.$ = new yy.ShowDatabases();
break;
case 595:
this.$ = new yy.ShowDatabases({like:$$[$0]});
break;
...
DropTable = function (params) { return yy.extend(this, params); }
...
case 562:
this.$ = {"onupdate":$$[$0]};
break;
case 563:
this.$ = {"onupdate":$$[$0-1]};
break;
case 564:
this.$ = new yy.DropTable({tables:$$[$0],type:$$[$0-2]}); yy.extend(this.$, $$[$0-1]);
break;
case 568:
this.$ = {ifexists: true};
break;
case 569:
this.$ = new yy.AlterTable({table:$$[$0-3], renameto: $$[$0]});
break;
...
DropTrigger = function (params) { return yy.extend(this, params); }
...
case 770:
this.$ = 'DELETE';
break;
case 771:
this.$ = 'UPDATE';
break;
case 772:
this.$ = new yy.DropTrigger({trigger:$$[$0]});
break;
case 773:
this.$ = new yy.Reindex({indexid:$$[$0]});
break;
case 1047: case 1067: case 1069: case 1071: case 1075: case 1077: case 1079: case 1081: case 1083: case 1085:
this.$ = [];
break;
...
ExistsValue = function (params) { return yy.extend(this, params); }
...
break;
case 362:
this.$ = new yy.VarValue({variable:$$[$0]});
break;
case 363:
if(!yy.exists) yy.exists = [];
this.$ = new yy.ExistsValue({value:$$[$0-1], existsidx:yy.exists.length});
yy.exists.push($$[$0-1]);
break;
case 364:
this.$ = new yy.ArrayValue({value:$$[$0-1]});
break;
case 365: case 366:
this.$ = new yy.ParamValue({param: $$[$0]});
...
Expression = function (params) { return yy.extend(this, params); }
...
case 235:
this.$ = {on: $$[$0]};
break;
case 236: case 697:
this.$ = {using: $$[$0]};
break;
case 239:
this.$ = {where: new yy.Expression({expression:$$[$0]})};
break;
case 241:
this.$ = {group:$$[$0-1]}; yy.extend(this.$,$$[$0]);
break;
case 244:
this.$ = new yy.GroupExpression({type:'GROUPING SETS', group: $$[$0-1]});
break;
...
ExpressionStatement = function (params) { return yy.extend(this, params); }
...
yy.extend(this.$,$$[$0-6]);
yy.extend(this.$,$$[$0-4]);
break;
case 613:
this.$ = new yy.DropTable({tables:$$[$0], view:true}); yy.extend(this.$, $$[$0-1]);
break;
case 614: case 760:
this.$ = new yy.ExpressionStatement({expression:$$[$0]});
break;
case 615:
this.$ = new yy.Source({url:$$[$0].value});
break;
case 616:
this.$ = new yy.Assert({value:$$[$0]});
break;
...
FromData = function (params) { return yy.extend(this, params); }
n/a
FuncValue = function (params){ return yy.extend(this, params); }
...
case 168:
var s = $$[$0];
s = s.substr(1,s.length-2);
var x3 = s.substr(-3).toUpperCase();
var x4 = s.substr(-4).toUpperCase();
if(s[0] == '#') {
this.$ = {into: new yy.FuncValue({funcid: 'HTML', args:[new yy.StringValue
({value: s}), new yy.Json({value:{headers:true}})]})};
} else if(x3=='XLS' || x3 == 'CSV' || x3=='TAB') {
this.$ = {into: new yy.FuncValue({funcid: x3, args:[new yy.StringValue({value: s}), new yy.Json({value:{headers:true}})]})};
} else if(x4=='XLSX' || x4 == 'JSON') {
this.$ = {into: new yy.FuncValue({funcid: x4, args:[new yy.StringValue({value: s}), new yy.Json({value:{headers:true}})]})};
}
break;
case 169:
...
GroupExpression = function (params){ return yy.extend(this, params); }
...
case 239:
this.$ = {where: new yy.Expression({expression:$$[$0]})};
break;
case 241:
this.$ = {group:$$[$0-1]}; yy.extend(this.$,$$[$0]);
break;
case 244:
this.$ = new yy.GroupExpression({type:'GROUPING SETS', group: $$[$0-1]});
break;
case 245:
this.$ = new yy.GroupExpression({type:'ROLLUP', group: $$[$0-1]});
break;
case 246:
this.$ = new yy.GroupExpression({type:'CUBE', group: $$[$0-1]});
break;
...
If = function (params) { return yy.extend(this, params); }
...
case 666:
this.$ = new yy.RollbackTransaction();
break;
case 667:
this.$ = new yy.BeginTransaction();
break;
case 668:
this.$ = new yy.If({expression:$$[$0-2],thenstat:$$[$0-1], elsestat:$$[$0]});
if($$[$0-1].exists) this.$.exists = $$[$0-1].exists;
if($$[$0-1].queries) this.$.queries = $$[$0-1].queries;
break;
case 669:
this.$ = new yy.If({expression:$$[$0-1],thenstat:$$[$0]});
if($$[$0].exists) this.$.exists = $$[$0].exists;
...
Insert = function (params) { return yy.extend(this, params); }
...
case 455:
this.$ = new yy.Delete({table:$$[$0-2], where:$$[$0]});
break;
case 456:
this.$ = new yy.Delete({table:$$[$0]});
break;
case 457:
this.$ = new yy.Insert({into:$$[$0-2], values: $$[$0]});
break;
case 458:
this.$ = new yy.Insert({into:$$[$0-1], values: $$[$0]});
break;
case 459: case 461:
this.$ = new yy.Insert({into:$$[$0-2], values: $$[$0], orreplace:true});
break;
...
JavaScript = function (params) { return yy.extend(this, params); }
...
case 309:
this.$ = $$[$0]
break;
case 310:
this.$ = new yy.FuncValue({funcid:'CURRENT_TIMESTAMP'});
break;
case 311:
this.$ = new yy.JavaScript({value:$$[$0].substr(2,$$[$0].length-4)});
break;
case 312:
this.$ = new yy.JavaScript({value:'alasql.fn["'+$$[$0-2]+'"] = '+$$[$0].substr(2,$$[$0].length-4)});
break;
case 313:
this.$ = new yy.JavaScript({value:'alasql.aggr["'+$$[$0-2]+'"] = '+$$[$0].substr(2,$$[$0].length-
4)});
break;
...
Join = function (params) { return yy.extend(this, params); }
...
case 202:
this.$ = new yy.Table({tableid: $$[$0]});
break;
case 203: case 204:
this.$ = $$[$0-1]; $$[$0-1].push($$[$0]);
break;
case 207:
this.$ = new yy.Join($$[$0-2]); yy.extend(this.$, $$[$0-1]); yy.extend(this.$, $$[$0
]);
break;
case 208:
this.$ = {table: $$[$0]};
break;
case 209:
this.$ = {table: $$[$0-1], as: $$[$0] } ;
break;
...
Json = function (params) { return yy.extend(this, params); }
...
case 116:
this.$ = {srchid:"ININ"};
break;
case 117:
this.$ = {srchid:"CONTENT"};
break;
case 118:
this.$ = {srchid:"EX",args:[new yy.Json({value:$$[$0]})]};
break;
case 119:
this.$ = {srchid:"AT", args:[$$[$0]]};
break;
case 120:
this.$ = {srchid:"AS", args:[$$[$0]]};
break;
...
Literal = function (params) { return yy.extend(this, params); }
n/a
LogicValue = function (params) { return yy.extend(this, params); }
...
case 355:
$$[$0-2].push($$[$0]); this.$ = $$[$0-2]
break;
case 356:
this.$ = new yy.NumValue({value:+$$[$0]});
break;
case 357:
this.$ = new yy.LogicValue({value:true});
break;
case 358:
this.$ = new yy.LogicValue({value:false});
break;
case 359:
this.$ = new yy.StringValue({value: $$[$0].substr(1,$$[$0].length-2).replace(/(\\\')/g,"'").replace(/(\'
;\')/g,"'")});
break;
...
Merge = function (params) { return yy.extend(this, params); }
...
this.$ = {variable: $$[$0-4], expression:$$[$0]}; yy.extend(this.$,$$[$0-2]);
break;
case 693:
this.$ = new yy.TruncateTable({table:$$[$0]});
break;
case 694:
this.$ = new yy.Merge(); yy.extend(this.$,$$[$0-4]); yy.extend(this.$,$$[$0-3]);
yy.extend(this.$,$$[$0-2]);
yy.extend(this.$,{matches:$$[$0-1]});yy.extend(this.$,$$[$0]);
break;
case 695: case 696:
this.$ = {into: $$[$0]};
break;
case 698:
...
NullValue = function (params) { return yy.extend(this, params); }
...
case 359:
this.$ = new yy.StringValue({value: $$[$0].substr(1,$$[$0].length-2).replace(/(\\\')/g,"'").replace(/(\'
;\')/g,"'")});
break;
case 360:
this.$ = new yy.StringValue({value: $$[$0].substr(2,$$[$0].length-3).replace(/(\\\')/g,"'").replace(/(\'
;\')/g,"'")});
break;
case 361:
this.$ = new yy.NullValue({value:undefined});
break;
case 362:
this.$ = new yy.VarValue({variable:$$[$0]});
break;
case 363:
if(!yy.exists) yy.exists = [];
...
NumValue = function (params) { return yy.extend(this, params); }
...
case 353:
this.$ = new yy.FuncValue({ funcid: 'INTERVAL', args:[$$[$0-1],new yy.StringValue({value:($$[$0]).toLowerCase()})]});
break;
case 355:
$$[$0-2].push($$[$0]); this.$ = $$[$0-2]
break;
case 356:
this.$ = new yy.NumValue({value:+$$[$0]});
break;
case 357:
this.$ = new yy.LogicValue({value:true});
break;
case 358:
this.$ = new yy.LogicValue({value:false});
break;
...
Op = function (params) { return yy.extend(this, params); }
...
case 371: case 699: case 700:
this.$ = $$[$0-1]; this.$.push($$[$0]);
break;
case 373:
this.$ = {when: $$[$0-2], then: $$[$0] };
break;
case 376: case 377:
this.$ = new yy.Op({left:$$[$0-2], op:'REGEXP', right:$$[$0]});
break;
case 378:
this.$ = new yy.Op({left:$$[$0-2], op:'GLOB', right:$$[$0]});
break;
case 379:
this.$ = new yy.Op({left:$$[$0-2], op:'LIKE', right:$$[$0]});
break;
...
OrderExpression = function (params){ return yy.extend(this, params); }
...
}
if(args.length > 0) {
args.forEach(function(arg){
var expr = new yy.Column({columnid:arg});
if(typeof arg == 'function'){
expr = arg;
}
self.order.push(new yy.OrderExpression({expression: expr, direction:'ASC'
;}));
});
}
return self;
}
yy.Select.prototype.Top = function(topnum){
var self = this;
self.top = new yy.NumValue({value:topnum});
...
Over = function (params) { return yy.extend(this, params); }
...
this.$ = new yy.AggrValue({aggregatorid: $$[$0-5].toUpperCase(), expression: $$[$0-2], distinct:true, over:$$[$0]});
break;
case 329:
this.$ = new yy.AggrValue({aggregatorid: $$[$0-5].toUpperCase(), expression: $$[$0-2],
over:$$[$0]});
break;
case 331: case 332:
this.$ = new yy.Over(); yy.extend(this.$,$$[$0-1]);
break;
case 333:
this.$ = new yy.Over(); yy.extend(this.$,$$[$0-2]); yy.extend(this.$,$$[$0-1]);
break;
case 334:
this.$ = {partition:$$[$0]};
break;
...
ParamValue = function (params) { return yy.extend(this, params); }
...
return;
}
if(arguments.length === 0) {
// Without arguments - Fluent interface
return new yy.Select({
columns:[new yy.Column({columnid:'*'})],
from: [new yy.ParamValue({param:0})]
});
} else if(arguments.length === 1){
// Access promise notation without using `.promise(...)`
if(sql.constructor === Array){
return alasql.promise(sql);
}
}
...
Print = function (params) { return yy.extend(this, params); }
...
case 673:
this.$ = new yy.Break();
break;
case 674:
this.$ = new yy.BeginEnd({statements:$$[$0-1]});
break;
case 675:
this.$ = new yy.Print({exprs:$$[$0]});
break;
case 676:
this.$ = new yy.Print({select:$$[$0]});
break;
case 677:
this.$ = new yy.Require({paths:$$[$0]});
break;
...
Reindex = function (params) { return yy.extend(this, params); }
...
case 771:
this.$ = 'UPDATE';
break;
case 772:
this.$ = new yy.DropTrigger({trigger:$$[$0]});
break;
case 773:
this.$ = new yy.Reindex({indexid:$$[$0]});
break;
case 1047: case 1067: case 1069: case 1071: case 1075: case 1077: case 1079: case 1081: case 1083: case 1085:
this.$ = [];
break;
case 1048: case 1062: case 1064: case 1068: case 1070: case 1072: case 1076: case 1078: case 1080: case 1082: case 1084: case 1086
:
$$[$0-1].push($$[$0]);
break;
...
Require = function (params) { return yy.extend(this, params); }
...
case 675:
this.$ = new yy.Print({exprs:$$[$0]});
break;
case 676:
this.$ = new yy.Print({select:$$[$0]});
break;
case 677:
this.$ = new yy.Require({paths:$$[$0]});
break;
case 678:
this.$ = new yy.Require({plugins:$$[$0]});
break;
case 679: case 680:
this.$ = $$[$0].toUpperCase();
break;
...
RollbackTransaction = function (params) { return yy.extend(this, params); }
...
case 664:
this.$ = false;
break;
case 665:
this.$ = new yy.CommitTransaction();
break;
case 666:
this.$ = new yy.RollbackTransaction();
break;
case 667:
this.$ = new yy.BeginTransaction();
break;
case 668:
this.$ = new yy.If({expression:$$[$0-2],thenstat:$$[$0-1], elsestat:$$[$0]});
if($$[$0-1].exists) this.$.exists = $$[$0-1].exists;
...
Search = function (params) { return yy.extend(this, params); }
...
delete yy.exists;
if(yy.queries) this.$.queries = yy.queries;
delete yy.queries;
*/
break;
case 73:
this.$ = new yy.Search({selectors:$$[$0-2], from:$$[$0]});
yy.extend(this.$,$$[$0-1]);
break;
case 74:
this.$ = {pivot:{expr:$$[$0-5], columnid:$$[$0-3], inlist:$$[$0-2], as:$$[$0]}};
break;
case 75:
this.$ = {unpivot:{tocolumnid:$$[$0-8], forcolumnid:$$[$0-6], inlist:$$[$0-3], as:$$[$0]}};
...
Select = function (params) { return yy.extend(this, params); }
...
alasql.buffer[id] = cb;
alasql.webworker.postMessage({id:id,sql:sql,params:params});
return;
}
if(arguments.length === 0) {
// Without arguments - Fluent interface
return new yy.Select({
columns:[new yy.Column({columnid:'*'})],
from: [new yy.ParamValue({param:0})]
});
} else if(arguments.length === 1){
// Access promise notation without using `.promise(...)`
if(sql.constructor === Array){
return alasql.promise(sql);
...
SetColumn = function (params) { return yy.extend(this, params); }
...
case 449:
this.$ = new yy.Update({table:$$[$0-4], columns:$$[$0-2], where:$$[$0]});
break;
case 450:
this.$ = new yy.Update({table:$$[$0-2], columns:$$[$0]});
break;
case 453:
this.$ = new yy.SetColumn({column:$$[$0-2], expression:$$[$0]})
break;
case 454:
this.$ = new yy.SetColumn({variable:$$[$0-2], expression:$$[$0], method:$$[$0-3]})
break;
case 455:
this.$ = new yy.Delete({table:$$[$0-2], where:$$[$0]});
break;
...
SetVariable = function (params) { return yy.extend(this, params); }
...
case 645:
this.$ = {}; this.$[$$[$0-2].substr(1,$$[$0-2].length-2)] = $$[$0];
break;
case 646: case 647:
this.$ = {}; this.$[$$[$0-2]] = $$[$0];
break;
case 650:
this.$ = new yy.SetVariable({variable:$$[$0-2].toLowerCase(), value:$$[$0]});
break;
case 651:
this.$ = new yy.SetVariable({variable:$$[$0-1].toLowerCase(), value:$$[$0]});
break;
case 652:
this.$ = new yy.SetVariable({variable:$$[$0-2], expression:$$[$0]});
break;
...
ShowColumns = function (params) { return yy.extend(this, params); }
...
case 600:
this.$ = new yy.ShowTables({databaseid: $$[$0]});
break;
case 601:
this.$ = new yy.ShowTables({like:$$[$0], databaseid: $$[$0-2]});
break;
case 602:
this.$ = new yy.ShowColumns({table: $$[$0]});
break;
case 603:
this.$ = new yy.ShowColumns({table: $$[$0-2], databaseid:$$[$0]});
break;
case 604:
this.$ = new yy.ShowIndex({table: $$[$0]});
break;
...
ShowCreateTable = function (params) { return yy.extend(this, params); }
...
case 604:
this.$ = new yy.ShowIndex({table: $$[$0]});
break;
case 605:
this.$ = new yy.ShowIndex({table: $$[$0-2], databaseid: $$[$0]});
break;
case 606:
this.$ = new yy.ShowCreateTable({table: $$[$0]});
break;
case 607:
this.$ = new yy.ShowCreateTable({table: $$[$0-2], databaseid:$$[$0]});
break;
case 608:
this.$ = new yy.CreateTable({table:$$[$0-6],view:true,select:$$[$0-1],viewcolumns:$$[$0-4]});
...
ShowDatabases = function (params) { return yy.extend(this, params); }
...
case 592:
this.$ = new yy.CreateIndex({indexid:$$[$0-5], table:$$[$0-3], columns:$$[$0-1], unique:true})
break;
case 593:
this.$ = new yy.DropIndex({indexid:$$[$0]});
break;
case 594:
this.$ = new yy.ShowDatabases();
break;
case 595:
this.$ = new yy.ShowDatabases({like:$$[$0]});
break;
case 596:
this.$ = new yy.ShowDatabases({engineid:$$[$0-1].toUpperCase() });
break;
...
ShowIndex = function (params) { return yy.extend(this, params); }
...
case 602:
this.$ = new yy.ShowColumns({table: $$[$0]});
break;
case 603:
this.$ = new yy.ShowColumns({table: $$[$0-2], databaseid:$$[$0]});
break;
case 604:
this.$ = new yy.ShowIndex({table: $$[$0]});
break;
case 605:
this.$ = new yy.ShowIndex({table: $$[$0-2], databaseid: $$[$0]});
break;
case 606:
this.$ = new yy.ShowCreateTable({table: $$[$0]});
break;
...
ShowTables = function (params) { return yy.extend(this, params); }
...
case 596:
this.$ = new yy.ShowDatabases({engineid:$$[$0-1].toUpperCase() });
break;
case 597:
this.$ = new yy.ShowDatabases({engineid:$$[$0-3].toUpperCase() , like:$$[$0]});
break;
case 598:
this.$ = new yy.ShowTables();
break;
case 599:
this.$ = new yy.ShowTables({like:$$[$0]});
break;
case 600:
this.$ = new yy.ShowTables({databaseid: $$[$0]});
break;
...
Source = function (params) { return yy.extend(this, params); }
...
case 613:
this.$ = new yy.DropTable({tables:$$[$0], view:true}); yy.extend(this.$, $$[$0-1]);
break;
case 614: case 760:
this.$ = new yy.ExpressionStatement({expression:$$[$0]});
break;
case 615:
this.$ = new yy.Source({url:$$[$0].value});
break;
case 616:
this.$ = new yy.Assert({value:$$[$0]});
break;
case 617:
this.$ = new yy.Assert({value:$$[$0].value});
break;
...
Statements = function (params) { return yy.extend(this, params); }
...
case 4:
this.$ = $$[$0]
break;
case 5:
this.$ = $$[$0] ? $$[$0-1] + ' ' + $$[$0] : $$[$0-1]
break;
case 6:
return new yy.Statements({statements:$$[$0-1]});
break;
case 7:
this.$ = $$[$0-2]; if($$[$0]) $$[$0-2].push($$[$0]);
break;
case 8: case 9: case 70: case 80: case 85: case 143: case 177: case 205: case 206: case 242: case 261: case 273: case 354: case
372: case 451: case 474: case 475: case 479: case 487: case 528: case 529: case 566: case 649: case 659: case 683: case 685: case
687: case 701: case 702: case 732: case 756:
this.$ = [$$[$0]];
break;
...
StringValue = function (params) { return yy.extend(this, params); }
...
case 168:
var s = $$[$0];
s = s.substr(1,s.length-2);
var x3 = s.substr(-3).toUpperCase();
var x4 = s.substr(-4).toUpperCase();
if(s[0] == '#') {
this.$ = {into: new yy.FuncValue({funcid: 'HTML', args:[new yy.StringValue({value: s}), new yy.Json({value:{headers:true}})]})};
} else if(x3=='XLS' || x3 == 'CSV' || x3=='TAB') {
this.$ = {into: new yy.FuncValue({funcid: x3, args:[new yy.StringValue({value: s}), new yy.Json({value:{headers:true}})]})};
} else if(x4=='XLSX' || x4 == 'JSON') {
this.$ = {into: new yy.FuncValue({funcid: x4, args:[new yy.StringValue({value: s}), new yy.Json({value:{headers:true}})]})};
}
break;
case 169:
...
Table = function (params) { return yy.extend(this, params); }
...
this.$ = r;
break;
case 201:
if($$[$0-2] == 'INFORMATION_SCHEMA') {
this.$ = new yy.FuncValue({funcid: $$[$0-2], args:[new yy.StringValue({value:$$[$0]})]});
} else {
this.$ = new yy.Table({databaseid: $$[$0-2], tableid:$$[$0]});
}
break;
case 202:
this.$ = new yy.Table({tableid: $$[$0]});
break;
case 203: case 204:
this.$ = $$[$0-1]; $$[$0-1].push($$[$0]);
...
TruncateTable = function (params) { return yy.extend(this, params); }
...
case 691:
this.$ = {variable: $$[$0-3], expression:$$[$0]}; yy.extend(this.$,$$[$0-2]);
break;
case 692:
this.$ = {variable: $$[$0-4], expression:$$[$0]}; yy.extend(this.$,$$[$0-2]);
break;
case 693:
this.$ = new yy.TruncateTable({table:$$[$0]});
break;
case 694:
this.$ = new yy.Merge(); yy.extend(this.$,$$[$0-4]); yy.extend(this.$,$$[$0-3]);
yy.extend(this.$,$$[$0-2]);
yy.extend(this.$,{matches:$$[$0-1]});yy.extend(this.$,$$[$0]);
break;
...
UniOp = function (params) { return yy.extend(this, params); }
...
this.$ = new yy.Op({left:$$[$0-2], op:'AND', right:$$[$0]});
}
break;
case 415:
this.$ = new yy.Op({left:$$[$0-2], op:'OR' , right:$$[$0]});
break;
case 416:
this.$ = new yy.UniOp({op:'NOT' , right:$$[$0]});
break;
case 417:
this.$ = new yy.UniOp({op:'-' , right:$$[$0]});
break;
case 418:
this.$ = new yy.UniOp({op:'+' , right:$$[$0]});
break;
...
Union = function (params) { return yy.extend(this, params); }
n/a
Update = function (params) { return yy.extend(this, params); }
...
case 447:
this.$ = 'SOME';
break;
case 448:
this.$ = 'ANY';
break;
case 449:
this.$ = new yy.Update({table:$$[$0-4], columns:$$[$0-2], where:$$[$0]});
break;
case 450:
this.$ = new yy.Update({table:$$[$0-2], columns:$$[$0]});
break;
case 453:
this.$ = new yy.SetColumn({column:$$[$0-2], expression:$$[$0]})
break;
...
UseDatabase = function (params) { return yy.extend(this, params); }
...
this.$ = new yy.CreateDatabase({engineid:$$[$0-4].toUpperCase(),
as:$$[$0], args:[$$[$0-1]] }); yy.extend(this.$,$$[$0-2]);
break;
case 584:
this.$ = undefined;
break;
case 586: case 587:
this.$ = new yy.UseDatabase({databaseid: $$[$0] });
break;
case 588:
this.$ = new yy.DropDatabase({databaseid: $$[$0] }); yy.extend(this.$,$$[$0-1]);
break;
case 589: case 590:
this.$ = new yy.DropDatabase({databaseid: $$[$0], engineid:$$[$0-3].toUpperCase() }); yy.extend(this.$,$$[$0-1]);
break;
...
VarValue = function (params) { return yy.extend(this, params); }
...
case 360:
this.$ = new yy.StringValue({value: $$[$0].substr(2,$$[$0].length-3).replace(/(\\\')/g,"'").replace(/(\'
;\')/g,"'")});
break;
case 361:
this.$ = new yy.NullValue({value:undefined});
break;
case 362:
this.$ = new yy.VarValue({variable:$$[$0]});
break;
case 363:
if(!yy.exists) yy.exists = [];
this.$ = new yy.ExistsValue({value:$$[$0-1], existsidx:yy.exists.length});
yy.exists.push($$[$0-1]);
break;
...
View = function (params) { return yy.extend(this, params); }
n/a
While = function (params) { return yy.extend(this, params); }
...
if($$[$0].exists) this.$.exists = $$[$0].exists;
if($$[$0].queries) this.$.queries = $$[$0].queries;
break;
case 670:
this.$ = $$[$0];
break;
case 671:
this.$ = new yy.While({expression:$$[$0-1],loopstat:$$[$0]});
if($$[$0].exists) this.$.exists = $$[$0].exists;
if($$[$0].queries) this.$.queries = $$[$0].queries;
break;
case 672:
this.$ = new yy.Continue();
break;
case 673:
...
WithSelect = function (params) { return yy.extend(this, params); }
...
if(yy.queries) this.$.queries = yy.queries;
delete yy.queries;
break;
case 13: case 162: case 172: case 237: case 238: case 240: case 248: case 250: case 259: case 267: case 270: case 375: case 491:
case 501: case 503: case 515: case 521: case 522: case 567:
this.$ = undefined;
break;
case 68:
this.$ = new yy.WithSelect({withs: $$[$0-1], select:$$[$0]});
break;
case 69: case 565:
$$[$0-2].push($$[$0]); this.$=$$[$0-2];
break;
case 71:
this.$ = {name:$$[$0-4], select:$$[$0-1]};
break;
...
function extend(a, b){ a = a || {}; for(var key in b) { if(b.hasOwnProperty(key)) { a[key] = b[key]; } } return a; }
...
// Plugin sample
var yy = alasql.yy;
yy.Echo = function (params) { return yy.extend(this, params); }
yy.Echo.prototype.toString = function() {
var s = 'TEST '+this.expr.toString();
return s;
}
yy.Echo.prototype.execute = function (databaseid, params, cb) {
// var self = this;
...
AggrValue = function (params){ return yy.extend(this, params); }
...
this.$ = new yy.FuncValue({funcid:'CURRENT_TIMESTAMP'});
break;
case 327:
if($$[$0-2].length > 1 && ($$[$0-4].toUpperCase() == 'MAX' || $$[$0-4].toUpperCase() == 'MIN
x27;)) {
this.$ = new yy.FuncValue({funcid:$$[$0-4],args:$$[$0-2]});
} else {
this.$ = new yy.AggrValue({aggregatorid: $$[$0-4].toUpperCase(), expression: $$[$0
-2].pop(), over:$$[$0]});
}
break;
case 328:
this.$ = new yy.AggrValue({aggregatorid: $$[$0-5].toUpperCase(), expression: $$[$0-2], distinct:true, over:$$[$0]});
break;
case 329:
this.$ = new yy.AggrValue({aggregatorid: $$[$0-5].toUpperCase(), expression: $$[$0-2],
...
findAggregator = function (query){ // var colas = this.as || this.toString(); var colas = escapeq(this.toString())+':'+query.selectGroup.length; var found = false; if(!found) { if(!this.nick) { this.nick = colas; var found = false; for(var i=0;i<query.removeKeys.length;i++){ if(query.removeKeys[i]===colas) { found = true; break; } } if(!found){ query.removeKeys.push(colas); } } query.selectGroup.push(this); } return; }
...
// }
} else {
query.groupStar = col.tableid || 'default';
}
});
this.columns.forEach(function(col){
if(col.findAggregator){
col.findAggregator(query);
}
});
if(this.having) {
if(this.having.findAggregator){
this.having.findAggregator(query);
}
}
...
toJS = function () { var colas = this.nick; if(colas === undefined){ colas = this.toString(); } return 'g[\''+colas+'\']'; }
...
* Changed order of LIMIT and ORDER BY processing
#### Version 0.0.4 (28.10.2014-29.10.2014)
* Added /test/main.html mocha browser tests
* Added PERFORMANCE.md and perf.html tests
* StringValue.toJS()
* Added callback to Database.exec
* Sieve of Eratosthenes example
* Remove generation of recs after select in case of group by (for memory optimization)
* Added conversion for type MONEY for INSERT statement
#### Versions 0.0.1 - 0.0.3 (25.10.2014-27.10.2014)
...
toString = function (dontas) { var s = ''; if(this.aggregatorid === 'REDUCE'){ s += this.funcid+'('; } else{ s += this.aggregatorid+'('; } if(this.distinct){ s+= 'DISTINCT '; } if(this.expression){ s += this.expression.toString(); } s += ')'; if(this.over){ s += ' '+this.over.toString(); } if(this.alias && !dontas) s += ' AS '+this.alias; // if(this.alias) s += ' AS '+this.alias; return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
toType = function () { if(['SUM','COUNT','AVG','MIN', 'MAX','AGGR','VAR','STDDEV'].indexOf(this.aggregatorid)>-1){ return 'number'; } if(['ARRAY'].indexOf(this.aggregatorid)>-1){ return 'array'; } if(['FIRST','LAST' ].indexOf(this.aggregatorid)>-1){ return this.expression.toType(); } // todo: implement default; }
...
if(['-','*','/','%','^'].indexOf(this.op) >-1){
return 'number';
}
if(['||'].indexOf(this.op) >-1){
return 'string';
}
if(this.op === '+') {
if(this.left.toType(tableid) === 'string' || this.right.toType(tableid) ===
x27;string'){
return 'string';
}
if(this.left.toType(tableid) === 'number' || this.right.toType(tableid) === 'number'){
return 'number';
}
}
if(['AND','OR','NOT','=','==','===', '!=','!==',
x27;!===','>','>=','<','<=', 'IN', 'NOT IN',
x27;LIKE', 'NOT LIKE', 'REGEXP', 'GLOB'].indexOf(this.op) >-1 ){
...
AlterTable = function (params) { return yy.extend(this, params); }
...
case 564:
this.$ = new yy.DropTable({tables:$$[$0],type:$$[$0-2]}); yy.extend(this.$, $$[$0-1]);
break;
case 568:
this.$ = {ifexists: true};
break;
case 569:
this.$ = new yy.AlterTable({table:$$[$0-3], renameto: $$[$0]});
break;
case 570:
this.$ = new yy.AlterTable({table:$$[$0-3], addcolumn: $$[$0]});
break;
case 571:
this.$ = new yy.AlterTable({table:$$[$0-3], modifycolumn: $$[$0]});
break;
...
execute = function (databaseid, params, cb) { var db = alasql.databases[databaseid]; db.dbversion = Date.now(); if(this.renameto) { var oldtableid = this.table.tableid; var newtableid = this.renameto; var res = 1; if(db.tables[newtableid]) { throw new Error("Can not rename a table '"+oldtableid+"' to '" +newtableid+"', because the table with this name already exists"); } else if(newtableid == oldtableid) { throw new Error("Can not rename a table '"+oldtableid+"' to itself"); } else { db.tables[newtableid] = db.tables[oldtableid]; delete db.tables[oldtableid]; res = 1; }; if(cb) cb(res) return res; } else if(this.addcolumn) { var db = alasql.databases[this.table.databaseid || databaseid]; db.dbversion++; var tableid = this.table.tableid; var table = db.tables[tableid]; var columnid = this.addcolumn.columnid; if(table.xcolumns[columnid]) { throw new Error('Cannot add column "'+columnid+'", because it already exists in the table "'+tableid+'"'); } var col = { columnid:columnid, dbtypeid:this.dbtypeid, dbsize:this.dbsize, dbprecision:this.dbprecision, dbenum:this.dbenum, defaultfns: null // TODO defaultfns!!! }; var defaultfn = function(){}; table.columns.push(col); table.xcolumns[columnid] = col; for(var i=0, ilen=table.data.length; i<ilen; i++) { table.data[i][columnid] = defaultfn(); } // TODO return cb?cb(1):1; } else if(this.modifycolumn) { var db = alasql.databases[this.table.databaseid || databaseid]; db.dbversion++; var tableid = this.table.tableid; var table = db.tables[tableid]; var columnid = this.modifycolumn.columnid; if(!table.xcolumns[columnid]) { throw new Error('Cannot modify column "'+columnid+'", because it was not found in the table "'+tableid+'"'); } var col = table.xcolumns[columnid]; col.dbtypeid = this.dbtypeid; col.dbsize = this.dbsize; col.dbprecision = this.dbprecision; col.dbenum = this.dbenum; // TODO return cb?cb(1):1; } else if(this.renamecolumn) { var db = alasql.databases[this.table.databaseid || databaseid]; db.dbversion++; var tableid = this.table.tableid; var table = db.tables[tableid]; var columnid = this.renamecolumn; var tocolumnid = this.to; var col; if(!table.xcolumns[columnid]) { throw new Error('Column "'+columnid+'" is not found in the table "'+tableid+'"'); } if(table.xcolumns[tocolumnid]) { throw new Error('Column "'+tocolumnid+'" already exists in the table "'+tableid+'"'); } if(columnid != tocolumnid) { for(var j=0; j<table.columns.length; j++) { if(table.columns[j].columnid == columnid) { table.columns[j].columnid = tocolumnid; } }; table.xcolumns[tocolumnid]=table.xcolumns[columnid]; delete table.xcolumns[columnid]; for(var i=0, ilen=table.data.length; i<ilen; i++) { table.data[i][tocolumnid] = table.data[i][columnid]; delete table.data[i][columnid]; } return table.data.length; } else { return cb?cb(0):0; } } else if(this.dropcolumn) { var db = alasql.databases[this.table.databaseid || databaseid]; db.dbversion++; var tableid = this.table.tableid; var table = db.tables[tableid]; var columnid = this.dropcolumn; var found = false; for(var j=0; j<table.columns.length; j++) { if(table.columns[j].columnid == columnid) { found = true; table.columns.splice(j,1); break; } }; if(!found) { throw new Error('Cannot drop column "'+columnid+'", because it was not found in the table "'+tableid+'"'); } delete table.xcolumns[columnid]; for(var i=0, ilen=table.data.length; i<ilen; i++) { delete table.data[i][columnid]; } return cb?cb(table.data.length):table.data.length; } else { throw Error('Unknown ALTER TABLE method'); } }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { var s = 'ALTER TABLE '+this.table.toString(); if(this.renameto) s += ' RENAME TO '+this.renameto; return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
Apply = function (params) { return yy.extend(this, params); }
...
case 170:
this.$ = { from: $$[$0-1], joins: $$[$0] };
break;
case 171:
this.$ = { from: $$[$0-2], joins: $$[$0-1] };
break;
case 173:
this.$ = new yy.Apply({select: $$[$0-2], applymode:'CROSS', as:$$[$0]});
break;
case 174:
this.$ = new yy.Apply({select: $$[$0-3], applymode:'CROSS', as:$$[$0]});
break;
case 175:
this.$ = new yy.Apply({select: $$[$0-2], applymode:'OUTER', as:$$[$0]});
break;
...
toString = function () { var s = this.applymode+' APPLY ('+this.select.toString()+')'; if(this.as) s += ' AS '+this.as; return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
ArrayValue = function (params) { return yy.extend(this, params); }
...
case 363:
if(!yy.exists) yy.exists = [];
this.$ = new yy.ExistsValue({value:$$[$0-1], existsidx:yy.exists.length});
yy.exists.push($$[$0-1]);
break;
case 364:
this.$ = new yy.ArrayValue({value:$$[$0-1]});
break;
case 365: case 366:
this.$ = new yy.ParamValue({param: $$[$0]});
break;
case 367:
if(typeof yy.question == 'undefined') yy.question = 0;
...
toJS = function (context, tableid, defcols) { // return "'"+doubleqq(this.value)+"'"; return '[(' + this.value.map(function(el) { return el.toJS(context, tableid, defcols) }).join('), (') + ')]' }
...
* Changed order of LIMIT and ORDER BY processing
#### Version 0.0.4 (28.10.2014-29.10.2014)
* Added /test/main.html mocha browser tests
* Added PERFORMANCE.md and perf.html tests
* StringValue.toJS()
* Added callback to Database.exec
* Sieve of Eratosthenes example
* Remove generation of recs after select in case of group by (for memory optimization)
* Added conversion for type MONEY for INSERT statement
#### Versions 0.0.1 - 0.0.3 (25.10.2014-27.10.2014)
...
toString = function () { return 'ARRAY[]' }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
toType = function () { return 'object'; }
...
if(['-','*','/','%','^'].indexOf(this.op) >-1){
return 'number';
}
if(['||'].indexOf(this.op) >-1){
return 'string';
}
if(this.op === '+') {
if(this.left.toType(tableid) === 'string' || this.right.toType(tableid) ===
x27;string'){
return 'string';
}
if(this.left.toType(tableid) === 'number' || this.right.toType(tableid) === 'number'){
return 'number';
}
}
if(['AND','OR','NOT','=','==','===', '!=','!==',
x27;!===','>','>=','<','<=', 'IN', 'NOT IN',
x27;LIKE', 'NOT LIKE', 'REGEXP', 'GLOB'].indexOf(this.op) >-1 ){
...
Assert = function (params) { return yy.extend(this, params); }
...
case 614: case 760:
this.$ = new yy.ExpressionStatement({expression:$$[$0]});
break;
case 615:
this.$ = new yy.Source({url:$$[$0].value});
break;
case 616:
this.$ = new yy.Assert({value:$$[$0]});
break;
case 617:
this.$ = new yy.Assert({value:$$[$0].value});
break;
case 618:
this.$ = new yy.Assert({value:$$[$0], message:$$[$0-2]});
break;
...
execute = function (databaseid) { if(!deepEqual(alasql.res,this.value)) { throw new Error((this.message||'Assert wrong')+': '+JSON.stringify(alasql.res)+' == '+JSON.stringify(this.value)); } return 1; }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
AttachDatabase = function (params) { return yy.extend(this, params); }
...
case 573:
this.$ = new yy.AlterTable({table:$$[$0-3], dropcolumn: $$[$0]});
break;
case 574:
this.$ = new yy.AlterTable({table:$$[$0-2], renameto: $$[$0]});
break;
case 575:
this.$ = new yy.AttachDatabase({databaseid:$$[$0], engineid:$$[$0-2].toUpperCase() });
break;
case 576:
this.$ = new yy.AttachDatabase({databaseid:$$[$0-3], engineid:$$[$0-5].toUpperCase(), args:$$[$0-1] });
break;
case 577:
this.$ = new yy.AttachDatabase({databaseid:$$[$0-2], engineid:$$[$0-4].toUpperCase(), as:$$[$0] });
break;
...
execute = function (databaseid, params, cb) { if(!alasql.engines[this.engineid]) { throw new Error('Engine "'+this.engineid+'" is not defined.'); }; var res = alasql.engines[this.engineid].attachDatabase(this.databaseid, this.as, this.args, params, cb); return res; }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { var s = 'ATTACH'; if(this.engineid) s += ' '+this.engineid; s += ' DATABASE'+' '+this.databaseid; // TODO add params if(args) { s += '('; if(args.length>0) { s += args.map(function(arg){ return arg.toString(); }).join(', '); } s += ')'; } if(this.as) s+= ' AS'+' '+this.as; return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
Base = function (params) { return yy.extend(this, params); }
n/a
function returnUndefined() {}
...
You can also define your own aggregator functions (like your own `SUM(...)`). See more [in the wiki](https://github.com/agershun
/alasql/wiki/User-Defined-Functions)
### Compiled statements and functions
```js
var ins = alasql.compile('INSERT INTO one VALUES (?,?)');
ins(1,10);
ins(2,20);
```
See more [in the wiki](https://github.com/agershun/alasql/wiki/Compile)
...
exec = function () {}
...
alasql('SELECT * FROM ?',[data],function(res){
console.log(data);
});
Call with scope for subquery (to pass common values):
var scope = {one:{a:2,b;20}}
alasql('SELECT * FROM ? two WHERE two.a = one.a',[data],null,scope);
Call for fluent interface with data object:
alasql(data).Where(function(x){return x.a == 10}).exec();
Call for fluent interface without data object:
alasql().From(data).Where(function(x){return x.a == 10}).exec();
*/
var alasql = function(sql, params, cb, scope) {
params = params||[];
...
toJS = function () {}
...
* Changed order of LIMIT and ORDER BY processing
#### Version 0.0.4 (28.10.2014-29.10.2014)
* Added /test/main.html mocha browser tests
* Added PERFORMANCE.md and perf.html tests
* StringValue.toJS()
* Added callback to Database.exec
* Sieve of Eratosthenes example
* Remove generation of recs after select in case of group by (for memory optimization)
* Added conversion for type MONEY for INSERT statement
#### Versions 0.0.1 - 0.0.3 (25.10.2014-27.10.2014)
...
toString = function () {}
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
toType = function () {}
...
if(['-','*','/','%','^'].indexOf(this.op) >-1){
return 'number';
}
if(['||'].indexOf(this.op) >-1){
return 'string';
}
if(this.op === '+') {
if(this.left.toType(tableid) === 'string' || this.right.toType(tableid) ===
x27;string'){
return 'string';
}
if(this.left.toType(tableid) === 'number' || this.right.toType(tableid) === 'number'){
return 'number';
}
}
if(['AND','OR','NOT','=','==','===', '!=','!==',
x27;!===','>','>=','<','<=', 'IN', 'NOT IN',
x27;LIKE', 'NOT LIKE', 'REGEXP', 'GLOB'].indexOf(this.op) >-1 ){
...
BeginEnd = function (params) { return yy.extend(this, params); }
...
case 672:
this.$ = new yy.Continue();
break;
case 673:
this.$ = new yy.Break();
break;
case 674:
this.$ = new yy.BeginEnd({statements:$$[$0-1]});
break;
case 675:
this.$ = new yy.Print({exprs:$$[$0]});
break;
case 676:
this.$ = new yy.Print({select:$$[$0]});
break;
...
execute = function (databaseid, params, cb, scope) { var self = this; var res = []; var idx = 0; runone(); function runone() { self.statements[idx].execute(databaseid,params,function(data){ res.push(data); idx++; if(idx<self.statements.length) return runone(); if(cb) res = cb(res); }); } return res; }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { var s = 'BEGIN '+this.statements.toString()+' END'; return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
BeginTransaction = function (params) { return yy.extend(this, params); }
...
case 665:
this.$ = new yy.CommitTransaction();
break;
case 666:
this.$ = new yy.RollbackTransaction();
break;
case 667:
this.$ = new yy.BeginTransaction();
break;
case 668:
this.$ = new yy.If({expression:$$[$0-2],thenstat:$$[$0-1], elsestat:$$[$0]});
if($$[$0-1].exists) this.$.exists = $$[$0-1].exists;
if($$[$0-1].queries) this.$.queries = $$[$0-1].queries;
break;
case 669:
...
execute = function (databaseid, params, cb) { var res = 1; if(alasql.databases[databaseid].engineid) { return alasql.engines[alasql.databases[alasql.useid].engineid].begin(databaseid, cb); } else { // alasql commit!!! } if(cb) cb(res); return res; }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { return 'BEGIN TRANSACTION'; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
Break = function (params) { return yy.extend(this, params); }
...
if($$[$0].exists) this.$.exists = $$[$0].exists;
if($$[$0].queries) this.$.queries = $$[$0].queries;
break;
case 672:
this.$ = new yy.Continue();
break;
case 673:
this.$ = new yy.Break();
break;
case 674:
this.$ = new yy.BeginEnd({statements:$$[$0-1]});
break;
case 675:
this.$ = new yy.Print({exprs:$$[$0]});
break;
...
execute = function (databaseid, params, cb, scope) { var res = 1; if(cb) res = cb(res); return res; }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { var s = 'BREAK'; return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
CaseValue = function (params) { return yy.extend(this, params); }
...
break;
case 368:
if(typeof yy.question == 'undefined') yy.question = 0;
this.$ = new yy.ParamValue({param: yy.question++, array:true});
break;
case 369:
this.$ = new yy.CaseValue({expression:$$[$0-3], whens: $$[$0-2], elses: $$[$0-1]});
break;
case 370:
this.$ = new yy.CaseValue({whens: $$[$0-2], elses: $$[$0-1]});
break;
case 371: case 699: case 700:
this.$ = $$[$0-1]; this.$.push($$[$0]);
break;
...
findAggregator = function (query){ 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); }
...
// }
} else {
query.groupStar = col.tableid || 'default';
}
});
this.columns.forEach(function(col){
if(col.findAggregator){
col.findAggregator(query);
}
});
if(this.having) {
if(this.having.findAggregator){
this.having.findAggregator(query);
}
}
...
toJS = function (context, tableid, defcols) { var s = '((function('+context+',params,alasql){var y,r;'; if(this.expression) { s += 'v='+this.expression.toJS(context, tableid, defcols)+';'; s += (this.whens||[]).map(function(w) { return ' if(v=='+w.when.toJS(context,tableid, defcols) +') {r='+w.then.toJS(context,tableid, defcols)+'}'; }).join(' else '); if(this.elses) s += ' else {r='+this.elses.toJS(context,tableid, defcols)+'}'; } else { s += (this.whens||[]).map(function(w) { return ' if('+w.when.toJS(context,tableid, defcols) +') {r='+w.then.toJS(context,tableid, defcols)+'}'; }).join(' else '); if(this.elses) s += ' else {r='+this.elses.toJS(context,tableid,defcols)+'}'; } // TODO remove bind from CASE s += ';return r;}).bind(this))('+context+',params,alasql)'; return s; }
...
* Changed order of LIMIT and ORDER BY processing
#### Version 0.0.4 (28.10.2014-29.10.2014)
* Added /test/main.html mocha browser tests
* Added PERFORMANCE.md and perf.html tests
* StringValue.toJS()
* Added callback to Database.exec
* Sieve of Eratosthenes example
* Remove generation of recs after select in case of group by (for memory optimization)
* Added conversion for type MONEY for INSERT statement
#### Versions 0.0.1 - 0.0.3 (25.10.2014-27.10.2014)
...
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; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
Column = function (params) { return yy.extend(this, params); }
...
alasql.webworker.postMessage({id:id,sql:sql,params:params});
return;
}
if(arguments.length === 0) {
// Without arguments - Fluent interface
return new yy.Select({
columns:[new yy.Column({columnid:'*'})],
from: [new yy.ParamValue({param:0})]
});
} else if(arguments.length === 1){
// Access promise notation without using `.promise(...)`
if(sql.constructor === Array){
return alasql.promise(sql);
}
...
toJS = function (context, tableid, defcols) { var s = ''; if(!this.tableid && tableid === '' && !defcols) { if(this.columnid !== '_') { s = context+'[\''+this.columnid+'\']'; } else { if(context === 'g') { s = 'g[\'_\']'; } else { s = context; } } } else { if(context === 'g') { // if(this.columnid == '_') { // } else { s = 'g[\''+this.nick+'\']'; // } } else if(this.tableid) { if(this.columnid !== '_') { // if() { // s = context+'[\''+tableid + '\'][\''+this.tableid+'\'][\''+this.columnid+'\']'; // } else { s = context+'[\''+(this.tableid) + '\'][\''+this.columnid+'\']'; // } } else { if(context === 'g') { s = 'g[\'_\']'; } else { s = context+'[\''+(this.tableid) + '\']'; } } } else if(defcols) { var tbid = defcols[this.columnid]; if(tbid === '-') { throw new Error('Cannot resolve column "'+this.columnid+'" because it exists in two source tables'); } else if(tbid) { if(this.columnid !== '_') { s = context+'[\''+(tbid) + '\'][\''+this.columnid+'\']'; } else { s = context+'[\''+(tbid) + '\']'; } } else { if(this.columnid !== '_') { // if(defcols['.'][this.tableid]) { // s = context+'[\''+tableid + '\'][\''+this.tableid + '\'][\''+this.columnid+'\']'; // } else { s = context+'[\''+(this.tableid || tableid) + '\'][\''+this.columnid+'\']'; // } } else { s = context+'[\''+(this.tableid || tableid) + '\']'; } } } else if(tableid === -1) { s = context+'[\''+this.columnid+'\']'; } else { if(this.columnid !== '_') { s = context+'[\''+(this.tableid || tableid) + '\'][\''+this.columnid+'\']'; } else { s = context+'[\''+(this.tableid || tableid) + '\']'; } } } // console.trace(new Error()); return s; }
...
* Changed order of LIMIT and ORDER BY processing
#### Version 0.0.4 (28.10.2014-29.10.2014)
* Added /test/main.html mocha browser tests
* Added PERFORMANCE.md and perf.html tests
* StringValue.toJS()
* Added callback to Database.exec
* Sieve of Eratosthenes example
* Remove generation of recs after select in case of group by (for memory optimization)
* Added conversion for type MONEY for INSERT statement
#### Versions 0.0.1 - 0.0.3 (25.10.2014-27.10.2014)
...
toString = function (dontas) { var s; if(this.columnid == +this.columnid) { // jshint ignore:line s = '['+this.columnid+']'; } else { s = this.columnid; } if(this.tableid) { if(+this.columnid === this.columnid) { s = this.tableid+s; } else { s = this.tableid+'.'+s; } if(this.databaseid) { s = this.databaseid+'.'+s; } } if(this.alias && !dontas) s += ' AS '+this.alias; return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
ColumnDef = function (params) { return yy.extend(this, params); }
...
this.$ = {type: 'FOREIGN KEY', columns: $$[$0-5], fktable: $$[$0-2], fkcolumns: $$[$0-1]};
break;
case 525:
this.$ = {type: 'UNIQUE', columns: $$[$0-1], clustered:($$[$0-3]+'').toUpperCase()};
break;
case 534:
this.$ = new yy.ColumnDef({columnid:$$[$0-2]}); yy.extend(this.$,$$[$0-1]); yy.extend
(this.$,$$[$0]);
break;
case 535:
this.$ = new yy.ColumnDef({columnid:$$[$0-1]}); yy.extend(this.$,$$[$0]);
break;
case 536:
this.$ = new yy.ColumnDef({columnid:$$[$0], dbtypeid: ''});
break;
...
toString = function () { var s = this.columnid; if(this.dbtypeid){ s += ' '+this.dbtypeid; } if(this.dbsize) { s += '('+this.dbsize; if(this.dbprecision){ s += ','+this.dbprecision; } s += ')'; } if(this.primarykey){ s += ' PRIMARY KEY'; } if(this.notnull){ s += ' NOT NULL'; } return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
CommitTransaction = function (params) { return yy.extend(this, params); }
...
case 663:
this.$ = true;
break;
case 664:
this.$ = false;
break;
case 665:
this.$ = new yy.CommitTransaction();
break;
case 666:
this.$ = new yy.RollbackTransaction();
break;
case 667:
this.$ = new yy.BeginTransaction();
break;
...
execute = function (databaseid, params, cb) { var res = 1; if(alasql.databases[databaseid].engineid) { return alasql.engines[alasql.databases[alasql.useid].engineid].commit(databaseid, cb); } else { // alasql commit!!! } if(cb) cb(res); return res; }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { return 'COMMIT TRANSACTION'; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
Continue = function (params) { return yy.extend(this, params); }
...
break;
case 671:
this.$ = new yy.While({expression:$$[$0-1],loopstat:$$[$0]});
if($$[$0].exists) this.$.exists = $$[$0].exists;
if($$[$0].queries) this.$.queries = $$[$0].queries;
break;
case 672:
this.$ = new yy.Continue();
break;
case 673:
this.$ = new yy.Break();
break;
case 674:
this.$ = new yy.BeginEnd({statements:$$[$0-1]});
break;
...
execute = function (databaseid, params, cb, scope) { var res = 1; if(cb) res = cb(res); return res; }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { var s = 'CONTINUE'; return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
Convert = function (params) { return yy.extend(this, params); }
...
case 314:
this.$ = new yy.FuncValue({funcid:$$[$0], newid:true});
break;
case 315:
this.$ = $$[$0]; yy.extend(this.$,{newid:true});
break;
case 316:
this.$ = new yy.Convert({expression:$$[$0-3]}) ; yy.extend(this.$,$$[$0-1]) ;
break;
case 317:
this.$ = new yy.Convert({expression:$$[$0-5], style:$$[$0-1]}) ; yy.extend(this.$,$$[$0-3]) ;
break;
case 318:
this.$ = new yy.Convert({expression:$$[$0-1]}) ; yy.extend(this.$,$$[$0-3]) ;
break;
...
toJS = function (context, tableid, defcols) { // if(this.style) { return 'alasql.stdfn.CONVERT('+this.expression.toJS(context, tableid, defcols) +',{dbtypeid:"'+this.dbtypeid+'",dbsize:'+this.dbsize+',style:'+ this.style+'})'; // } throw new Error('There is not such type conversion for '+this.toString()); }
...
* Changed order of LIMIT and ORDER BY processing
#### Version 0.0.4 (28.10.2014-29.10.2014)
* Added /test/main.html mocha browser tests
* Added PERFORMANCE.md and perf.html tests
* StringValue.toJS()
* Added callback to Database.exec
* Sieve of Eratosthenes example
* Remove generation of recs after select in case of group by (for memory optimization)
* Added conversion for type MONEY for INSERT statement
#### Versions 0.0.1 - 0.0.3 (25.10.2014-27.10.2014)
...
toString = function () { var s = 'CONVERT('; s += this.dbtypeid; if(typeof this.dbsize != 'undefined') { s += '('+this.dbsize; if(this.dbprecision) s += ','+dbprecision; s += ')'; } s += ','+this.expression.toString(); if(this.style) s += ','+this.style; s += ')'; return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
CreateDatabase = function (params) { return yy.extend(this, params); }
...
case 578:
this.$ = new yy.AttachDatabase({databaseid:$$[$0-5], engineid:$$[$0-7].toUpperCase(), as:$$[$0], args:$$[$0-3]});
break;
case 579:
this.$ = new yy.DetachDatabase({databaseid:$$[$0]});
break;
case 580:
this.$ = new yy.CreateDatabase({databaseid:$$[$0] }); yy.extend(this.$,$$[$0]);
break;
case 581:
this.$ = new yy.CreateDatabase({engineid:$$[$0-4].toUpperCase(), databaseid:$$[$0-1], as:$$[$0] }); yy.extend(this.$,$$[$0-2]);
break;
case 582:
this.$ = new yy.CreateDatabase({engineid:$$[$0-7].toUpperCase(), databaseid:$$[$0-4], args:$$[$0-2], as:$$[$0] }); yy.extend(this
.$,$$[$0-5]);
break;
...
execute = function (databaseid, params, cb) { var args; if(this.args && this.args.length > 0) { args = this.args.map(function(arg){ return new Function('params,alasql','var y;return '+arg.toJS())(params,alasql); }); }; if(this.engineid) { var res = alasql.engines[this.engineid].createDatabase(this.databaseid, this.args, this.ifnotexists, this.as, cb); return res; } else { var dbid = this.databaseid; if(alasql.databases[dbid]) { throw new Error("Database '"+dbid+"' already exists") }; var a = new alasql.Database(dbid); var res = 1; if(cb) return cb(res); return res; } }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { var s = 'CREATE'; if(this.engineid) s+=' '+this.engineid; s += ' DATABASE'; if(this.ifnotexists) s += ' IF NOT EXISTS'; s += ' '+this.databaseid; if(this.args && this.args.length > 0) { s += '('+this.args.map(function(arg){ return arg.toString()}).join(', ')+')'; } if(this.as) s += ' AS '+this.as; return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
CreateEdge = function (params) { return yy.extend(this, params); }
...
this.$ = {content:$$[$0]};
break;
case 727:
this.$ = {select:$$[$0]};
break;
case 728:
this.$ = new yy.CreateEdge({from:$$[$0-3],to:$$[$0-1],name:$$[$0-5]});
yy.extend(this.$,$$[$0]);
break;
case 729:
this.$ = new yy.CreateGraph({graph:$$[$0]});
break;
case 730:
this.$ = new yy.CreateGraph({from:$$[$0]});
...
compile = function (databaseid) { var dbid = databaseid; var fromfn = new Function('params,alasql','var y;return '+this.from.toJS()); var tofn = new Function('params,alasql','var y;return '+this.to.toJS()); // CREATE VERTEX "Name" if(typeof this.name !== 'undefined') { var s = 'x.name='+this.name.toJS(); var namefn = new Function('x',s); } if(this.sets && this.sets.length > 0) { var s = this.sets.map(function(st){ return 'x[\''+st.column.columnid+'\']='+st.expression.toJS('x',''); }).join(';'); var setfn = new Function('x,params,alasql','var y;'+s); } /* todo: handle content, select and default else if(this.content) { } else if(this.select) { } else { } */ var statement = function(params,cb){ var res = 0; // CREATE VERTEX without parameters var db = alasql.databases[dbid]; var edge = {$id: db.counter++, $node:'EDGE'}; var v1 = fromfn(params,alasql); var v2 = tofn(params,alasql); // Set link edge.$in = [v1.$id]; edge.$out = [v2.$id]; // Set sides if(v1.$out === undefined){ v1.$out = []; } v1.$out.push(edge.$id); if(typeof v2.$in === undefined){ v2.$in = []; } v2.$in.push(edge.$id); // Save in objects db.objects[edge.$id] = edge; res = edge; if(namefn){ namefn(edge); } if(setfn){ setfn(edge,params,alasql); } if(cb){ res = cb(res); } return res; }; return statement; }
...
You can also define your own aggregator functions (like your own `SUM(...)`). See more [in the wiki](https://github.com/agershun
/alasql/wiki/User-Defined-Functions)
### Compiled statements and functions
```js
var ins = alasql.compile('INSERT INTO one VALUES (?,?)');
ins(1,10);
ins(2,20);
```
See more [in the wiki](https://github.com/agershun/alasql/wiki/Compile)
...
toJS = function (context) { var s = 'this.queriesfn['+(this.queriesidx-1)+'](this.params,null,'+context+')'; return s; }
...
* Changed order of LIMIT and ORDER BY processing
#### Version 0.0.4 (28.10.2014-29.10.2014)
* Added /test/main.html mocha browser tests
* Added PERFORMANCE.md and perf.html tests
* StringValue.toJS()
* Added callback to Database.exec
* Sieve of Eratosthenes example
* Remove generation of recs after select in case of group by (for memory optimization)
* Added conversion for type MONEY for INSERT statement
#### Versions 0.0.1 - 0.0.3 (25.10.2014-27.10.2014)
...
toString = function () { var s = 'CREATE EDGE'+' '; if(this.class){ s += this.class+' '; } // todo: SET // todo: CONTENT // todo: SELECT return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
CreateGraph = function (params) { return yy.extend(this, params); }
...
break;
case 728:
this.$ = new yy.CreateEdge({from:$$[$0-3],to:$$[$0-1],name:$$[$0-5]});
yy.extend(this.$,$$[$0]);
break;
case 729:
this.$ = new yy.CreateGraph({graph:$$[$0]});
break;
case 730:
this.$ = new yy.CreateGraph({from:$$[$0]});
break;
case 733:
this.$ = $$[$0-2];
...
compile1 = function (databaseid) { var dbid = databaseid; var fromfn = new Function('params,alasql','var y;return '+this.from.toJS()); var tofn = new Function('params,alasql','var y;return '+this.to.toJS()); // CREATE VERTEX "Name" if(typeof this.name !== 'undefined') { var s = 'x.name='+this.name.toJS(); var namefn = new Function('x',s); } if(this.sets && this.sets.length > 0) { var s = this.sets.map(function(st){ return 'x[\''+st.column.columnid+'\']='+st.expression.toJS('x',''); }).join(';'); var setfn = new Function('x,params,alasql','var y;'+s); } // Todo: handle content, select and default var statement = function(params,cb){ var res = 0; // CREATE VERTEX without parameters var db = alasql.databases[dbid]; var edge = {$id: db.counter++, $node:'EDGE'}; var v1 = fromfn(params,alasql); var v2 = tofn(params,alasql); // Set link edge.$in = [v1.$id]; edge.$out = [v2.$id]; // Set sides if(typeof v1.$out === 'undefined'){ v1.$out = []; } v1.$out.push(edge.$id); if(typeof v2.$in === 'undefined'){ v2.$in = []; } v2.$in.push(edge.$id); // Save in objects db.objects[edge.$id] = edge; res = edge; if(namefn){ namefn(edge); } if(setfn){ setfn(edge,params,alasql); } if(cb){ res = cb(res); } return res; } return statement; }
n/a
execute = function (databaseid, params, cb) { var res = []; if(this.from) { if(alasql.from[this.from.funcid]) { this.graph = alasql.from[this.from.funcid.toUpperCase()] } } // stop; this.graph.forEach(function(g){ if(g.source) { // GREATE EDGE var e = {}; if(typeof g.as !== 'undefined'){ alasql.vars[g.as] = e; } if(typeof g.prop !== 'undefined') { // e[g.prop] = e; // v.$id = g.prop; // We do not create $id for edge automatically e.name = g.prop; } if(typeof g.sharp !== 'undefined'){ e.$id = g.sharp; } if(typeof g.name !== 'undefined'){ e.name = g.name; } if(typeof g.class !== 'undefined'){ e.$class = g.class; } var db = alasql.databases[databaseid]; if(typeof e.$id === 'undefined') { e.$id = db.counter++; } e.$node='EDGE'; if(typeof g.json !== 'undefined') { extend(e,(new Function('params,alasql','var y;return '+ g.json.toJS()))(params,alasql)); } var v1; if(g.source.vars) { var vo = alasql.vars[g.source.vars]; if(typeof vo === 'object'){ v1 = vo; } else{ v1 = db.objects[vo]; } } else { var av1 = g.source.sharp; if(typeof av1 === 'undefined'){ av1 = g.source.prop; } v1 = alasql.databases[databaseid].objects[av1]; if( typeof v1 === 'undefined' && alasql.options.autovertex && ((typeof g.source.prop !== 'undefined') || (typeof g.source.name !== 'undefined')) ){ v1 = findVertex(g.source.prop || g.source.name); if(typeof v1 === 'undefined') { v1 = createVertex(g.source); } } } var v2; if(g.source.vars) { var vo = alasql.vars[g.target.vars]; if(typeof vo === 'object'){ v2 = vo; } else{ v2 = db.objects[vo]; } } else { var av2 = g.target.sharp; if(typeof av2 === 'undefined'){ av2 = g.target.prop; } v2 = alasql.databases[databaseid].objects[av2]; if( typeof v2 === 'undefined' && alasql.options.autovertex && ((typeof g.target.prop !== 'undefined') || (typeof g.target.name !== 'undefined')) ) { v2 = findVertex(g.target.prop || g.target.name); if(typeof v2 === 'undefined') { v2 = createVertex(g.target); } } } // Set link e.$in = [v1.$id]; e.$out = [v2.$id]; // Set sides if(typeof v1.$out === 'undefined'){ v1.$out = []; } v1.$out.push(e.$id); if(typeof v2.$in === 'undefined'){ v2.$in = []; } v2.$in.push(e.$id); db.objects[e.$id] = e; if(typeof e.$class !== 'undefined') { if(typeof alasql.databases[databaseid].tables[e.$class] === 'undefined') { throw new Error('No such class. Pleace use CREATE CLASS'); } else { // TODO - add insert() alasql.databases[databaseid].tables[e.$class].data.push(e); } } res.push(e.$id); } else { createVertex(g); } }); if(cb){ res = cb(res); } return res; // Find vertex by name function findVertex(name) { var objects = alasql.databases[alasql.useid].objects; for(var k in objects) { if(objects[k].name === name) { return objects[k]; } } return undefined; } function createVertex(g) { // GREATE VERTEX var v = {}; if(typeof g.as !== 'undefined'){ alasql.vars[g.as] = v; } if(typeof g.prop !== 'undefined') { // v[g.prop] = true; v.$id = g.prop; v.name = g.prop; } if(typeof g.sharp !== 'undefined'){ v.$id = g.sharp; } if(typeof g.name !== 'undefined'){ v.name = g.name; } if(typeof g.class !== 'undefined'){ v.$class = g.class; } var db = alasql.databases[databaseid]; if(typeof v.$id === 'undefined') { v.$id = db.counter++; } v.$node='VERTEX'; if(typeof g.json !== 'undefined') { extend(v,(new Function('params,alasql','var y;return '+ g.json.toJS()))(para ...
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { var s = 'CREATE GRAPH'+' '; if(this.class){ s += this.class+' '; } return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
CreateIndex = function (params) { return yy.extend(this, params); }
...
case 588:
this.$ = new yy.DropDatabase({databaseid: $$[$0] }); yy.extend(this.$,$$[$0-1]);
break;
case 589: case 590:
this.$ = new yy.DropDatabase({databaseid: $$[$0], engineid:$$[$0-3].toUpperCase() }); yy.extend(this.$,$$[$0-1]);
break;
case 591:
this.$ = new yy.CreateIndex({indexid:$$[$0-5], table:$$[$0-3], columns:$$[$0-1]})
break;
case 592:
this.$ = new yy.CreateIndex({indexid:$$[$0-5], table:$$[$0-3], columns:$$[$0-1], unique:true})
break;
case 593:
this.$ = new yy.DropIndex({indexid:$$[$0]});
break;
...
execute = function (databaseid, params, cb) { // var self = this; var db = alasql.databases[databaseid]; var tableid = this.table.tableid; var table = db.tables[tableid]; var indexid = this.indexid; db.indices[indexid] = tableid; var rightfns = this.columns.map(function(expr){ return expr.expression.toJS('r','') }).join("+'`'+"); var rightfn = new Function('r,params,alasql','return '+rightfns); if(this.unique) { table.uniqdefs[indexid] = { rightfns: rightfns }; var ux = table.uniqs[indexid] = {}; if(table.data.length > 0) { for(var i=0, ilen=table.data.length; i<ilen;i++) { var addr = rightfns(table.data[i]); if(!ux[addr]) { ux[addr] = {num:0}; }; ux[addr].num++; } } } else { var hh = hash(rightfns); table.inddefs[indexid] = {rightfns:rightfns, hh:hh}; table.indices[hh] = {}; var ix = table.indices[hh] = {}; if(table.data.length > 0) { for(var i=0, ilen=table.data.length; i<ilen;i++) { var addr = rightfn(table.data[i],params,alasql); if(!ix[addr]) { ix[addr] = []; }; ix[addr].push(table.data[i]); } } }; var res = 1; if(cb) res = cb(res); return res; }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { var s = 'CREATE'; if(this.unique) s+=' UNIQUE'; s += ' INDEX ' + this.indexid + " ON "+this.table.toString(); s += "("+this.columns.toString()+")"; return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
CreateTable = function (params) { return yy.extend(this, params); }
...
this.$ = $$[$0-4]; $$[$0-4].push($$[$0-1])
break;
case 477: case 478: case 480: case 488:
this.$ = $$[$0-2]; $$[$0-2].push($$[$0])
break;
case 489:
this.$ = new yy.CreateTable({table:$$[$0-4]});
yy.extend(this.$,$$[$0-7]);
yy.extend(this.$,$$[$0-6]);
yy.extend(this.$,$$[$0-5]);
yy.extend(this.$,$$[$0-2]);
yy.extend(this.$,$$[$0]);
break;
case 490:
...
execute = function (databaseid, params, cb) { // var self = this; var db = alasql.databases[this.table.databaseid || databaseid]; var tableid = this.table.tableid; if(!tableid) { throw new Error('Table name is not defined'); } // var ifnotexists = this.ifnotexists; var columns = this.columns; // if(false) { // if(!columns) { // throw new Error('Columns are not defined'); // } // } var constraints = this.constraints||[]; // IF NOT EXISTS if(this.ifnotexists && db.tables[tableid]){ return cb?cb(0):0; } if(db.tables[tableid]) { throw new Error('Can not create table \''+tableid +'\', because it already exists in the database \''+db.databaseid+'\''); } var table = db.tables[tableid] = new alasql.Table(); // TODO Can use special object? // If this is a class if(this.class) { table.isclass = true; } var ss = []; // DEFAULT function components var uss = []; // ON UPDATE function components if(columns) { columns.forEach(function(col) { var dbtypeid = col.dbtypeid; if(!alasql.fn[dbtypeid]){ dbtypeid = dbtypeid.toUpperCase(); } // Process SERIAL data type like Postgress if(['SERIAL','SMALLSERIAL','BIGSERIAL'].indexOf(dbtypeid)>-1){ col.identity = {value:1,step:1}; } var newcol = { columnid: col.columnid, dbtypeid: dbtypeid, dbsize: col.dbsize, // Fixed issue #150 dbprecision: col.dbprecision, // Fixed issue #150 notnull: col.notnull, identity: col.identity }; if(col.identity) { table.identities[col.columnid]={value:+col.identity.value,step:+col.identity.step}; } if(col.check) { table.checks.push({id: col.check.constrantid, fn: new Function("r",'var y;return '+col.check.expression.toJS('r',''))}); } if(col.default) { ss.push('\''+col.columnid+'\':'+col.default.toJS('r','')); } // Check for primary key if(col.primarykey) { var pk = table.pk = {}; pk.columns = [col.columnid]; pk.onrightfns = 'r[\''+col.columnid+'\']'; pk.onrightfn = new Function("r",'var y;return '+pk.onrightfns); pk.hh = hash(pk.onrightfns); table.uniqs[pk.hh] = {}; } // UNIQUE clause if(col.unique) { var uk = {}; table.uk = table.uk||[]; table.uk.push(uk); uk.columns = [col.columnid]; uk.onrightfns = 'r[\''+col.columnid+'\']'; uk.onrightfn = new Function("r",'var y;return '+uk.onrightfns); uk.hh = hash(uk.onrightfns); table.uniqs[uk.hh] = {}; } // UNIQUE clause if(col.foreignkey) { var fk = col.foreignkey.table; var fktable = alasql.databases[fk.databaseid||alasql.useid].tables[fk.tableid]; if(typeof fk.columnid === 'undefined') { if(fktable.pk.columns && fktable.pk.columns.length >0 ){ fk.columnid = fktable.pk.columns[0]; } else { throw new Error('FOREIGN KEY allowed only to tables with PRIMARY KEYs'); } } var fkfn = function(r) { var rr = {}; if(typeof r[col.columnid] === 'undefined'){ return true; } rr[fk.columnid] = r[col.columnid]; var addr = fktable.pk.onrightfn(rr); if(!fktable.uniqs[fktable.pk.hh][addr]) { throw new Error('Foreign key "'+r[col.columnid]+'" is not found in table '+fktable.tableid); } return true; }; table.checks.push({fn: fkfn}); } if(col.onupdate) { uss.push('r[\''+col.columnid+'\']='+col.onupdate.toJS('r','')); } table.columns.push(newcol); table.xcolumns[newcol.columnid] = newcol; }); } table.defaultfns = ss.join(','); table.onupdatefns = uss.join(';'); // if(constraints) { constraints.forEach(function(con) { var checkfn; if(con.type === 'PRIMARY KEY') { if(table.pk) { throw new Error('Primary key already exists'); } var pk = table.pk = {}; pk.columns = con.columns; pk.onrightfns = pk.columns.map(function(columnid){ return 'r[\''+columnid+'\']' }).join("+'`'+"); pk.onrightfn = new Function("r",'var y;return '+pk.onrightfns); pk.h ...
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { var s = 'CREATE'; if(this.temporary){ s+=' TEMPORARY'; } if(this.view){ s += ' VIEW'; } else{ s += ' '+(this.class?'CLASS':'TABLE'); } if(this.ifnotexists){ s += ' IF NOT EXISTS'; } s += ' '+this.table.toString(); if(this.viewcolumns) { s += '('+this.viewcolumns.map(function(vcol){ return vcol.toString(); }).join(',')+')'; } if(this.as){ s += ' AS '+this.as; } else { var ss = this.columns.map(function(col){ return col.toString(); }); s += ' ('+ss.join(',')+')'; } if(this.view && this.select) { s += ' AS '+this.select.toString(); } return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
CreateTrigger = function (params) { return yy.extend(this, params); }
...
this.$ = new yy.Term({termid:$$[$0]});
break;
case 758:
this.$ = new yy.Term({termid:$$[$0-3],args:$$[$0-1]});
break;
case 761:
this.$ = new yy.CreateTrigger({trigger:$$[$0-6], when:$$[$0-5], action:$$[$0-4], table
:$$[$0-2], statement:$$[$0]});
if($$[$0].exists) this.$.exists = $$[$0].exists;
if($$[$0].queries) this.$.queries = $$[$0].queries;
break;
case 762:
this.$ = new yy.CreateTrigger({trigger:$$[$0-5], when:$$[$0-4], action:$$[$0-3], table:$$[$0-1], funcid:$$[$0]});
break;
...
execute = function (databaseid, params, cb) { var res = 1; // No tables removed var triggerid = this.trigger; databaseid = this.table.databaseid || databaseid; var db = alasql.databases[databaseid]; var tableid = this.table.tableid; var trigger = { action: this.action, when: this.when, statement: this.statement, funcid: this.funcid }; db.triggers[triggerid] = trigger; if(trigger.action == 'INSERT' && trigger.when == 'BEFORE') { db.tables[tableid].beforeinsert[triggerid] = trigger; } else if(trigger.action == 'INSERT' && trigger.when == 'AFTER') { db.tables[tableid].afterinsert[triggerid] = trigger; } else if(trigger.action == 'INSERT' && trigger.when == 'INSTEADOF') { db.tables[tableid].insteadofinsert[triggerid] = trigger; } else if(trigger.action == 'DELETE' && trigger.when == 'BEFORE') { db.tables[tableid].beforedelete[triggerid] = trigger; } else if(trigger.action == 'DELETE' && trigger.when == 'AFTER') { db.tables[tableid].afterdelete[triggerid] = trigger; } else if(trigger.action == 'DELETE' && trigger.when == 'INSTEADOF') { db.tables[tableid].insteadofdelete[triggerid] = trigger; } else if(trigger.action == 'UPDATE' && trigger.when == 'BEFORE') { db.tables[tableid].beforeupdate[triggerid] = trigger; } else if(trigger.action == 'UPDATE' && trigger.when == 'AFTER') { db.tables[tableid].afterupdate[triggerid] = trigger; } else if(trigger.action == 'UPDATE' && trigger.when == 'INSTEADOF') { db.tables[tableid].insteadofupdate[triggerid] = trigger; } if(cb) res = cb(res); return res; }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { var s = 'CREATE TRIGGER '+this.trigger +' '; if(this.when) s += this.when+' '; s += this.action+' ON '; if(this.table.databaseid) s += this.table.databaseid+'.'; s += this.table.tableid+' '; s += this.statement.toString(); return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
CreateVertex = function (params) { return yy.extend(this, params); }
...
this.$ = {output:{columns:$$[$0-2], intotable: $$[$0]}}
break;
case 721:
this.$ = {output:{columns:$$[$0-5], intotable: $$[$0-3], intocolumns:$$[$0-1]}}
break;
case 722:
this.$ = new yy.CreateVertex({class:$$[$0-3],sharp:$$[$0-2], name:$$[$0-1]});
yy.extend(this.$,$$[$0]);
break;
case 725:
this.$ = {sets:$$[$0]};
break;
case 726:
this.$ = {content:$$[$0]};
...
compile = function (databaseid) { var dbid = databaseid; // CREATE VERTEX #id var sharp = this.sharp; // CREATE VERTEX "Name" if(typeof this.name !== 'undefined') { var s = 'x.name='+this.name.toJS(); var namefn = new Function('x',s); } if(this.sets && this.sets.length > 0) { var s = this.sets.map(function(st){ return 'x[\''+st.column.columnid+'\']='+st.expression.toJS('x',''); }).join(';'); var setfn = new Function('x,params,alasql',s); } // Todo: check for content, select and default var statement = function(params,cb){ var res; // CREATE VERTEX without parameters var db = alasql.databases[dbid]; var id; if(typeof sharp !== 'undefined') { id = sharp; } else { id = db.counter++; } var vertex = {$id: id, $node:'VERTEX'}; db.objects[vertex.$id] = vertex; res = vertex; if(namefn){ namefn(vertex); } if(setfn){ setfn(vertex,params,alasql); } if(cb){ res = cb(res); } return res; } return statement; }
...
You can also define your own aggregator functions (like your own `SUM(...)`). See more [in the wiki](https://github.com/agershun
/alasql/wiki/User-Defined-Functions)
### Compiled statements and functions
```js
var ins = alasql.compile('INSERT INTO one VALUES (?,?)');
ins(1,10);
ins(2,20);
```
See more [in the wiki](https://github.com/agershun/alasql/wiki/Compile)
...
toJS = function (context) { var s = 'this.queriesfn['+(this.queriesidx-1)+'](this.params,null,'+context+')'; // var s = ''; return s; }
...
* Changed order of LIMIT and ORDER BY processing
#### Version 0.0.4 (28.10.2014-29.10.2014)
* Added /test/main.html mocha browser tests
* Added PERFORMANCE.md and perf.html tests
* StringValue.toJS()
* Added callback to Database.exec
* Sieve of Eratosthenes example
* Remove generation of recs after select in case of group by (for memory optimization)
* Added conversion for type MONEY for INSERT statement
#### Versions 0.0.1 - 0.0.3 (25.10.2014-27.10.2014)
...
toString = function () { var s = 'CREATE VERTEX '; if(this.class){ s += this.class+' '; } if(this.sharp){ s += '#'+this.sharp+' '; } if(this.sets) { s += this.sets.toString(); } else if(this.content) { s += this.content.toString(); } else if(this.select) { s += this.select.toString(); } return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
Declare = function (params) { return yy.extend(this, params); }
...
case 679: case 680:
this.$ = $$[$0].toUpperCase();
break;
case 681:
this.$ = new yy.Echo({expr:$$[$0]});
break;
case 686:
this.$ = new yy.Declare({declares:$$[$0]});
break;
case 689:
this.$ = {variable: $$[$0-1]}; yy.extend(this.$,$$[$0]);
break;
case 690:
this.$ = {variable: $$[$0-2]}; yy.extend(this.$,$$[$0]);
break;
...
execute = function (databaseid, params, cb) { var res = 1; if(this.declares && this.declares.length > 0) { this.declares.map(function(declare){ var dbtypeid = declare.dbtypeid; if(!alasql.fn[dbtypeid]){ dbtypeid = dbtypeid.toUpperCase(); } alasql.declares[declare.variable] = {dbtypeid:dbtypeid, dbsize:declare.dbsize, dbprecision:declare.dbprecision}; // Set value if(declare.expression) { alasql.vars[declare.variable] = new Function("params,alasql","return " +declare.expression.toJS('({})','', null))(params,alasql); if(alasql.declares[declare.variable]) { alasql.vars[declare.variable] = alasql.stdfn.CONVERT(alasql.vars[declare.variable],alasql.declares[declare.variable]); } } }); } if(cb){ res=cb(res); } return res; }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { var s = 'DECLARE '; if(this.declares && this.declares.length > 0) { s = this.declares.map(function(declare){ var s = ''; s += '@'+declare.variable+' '; s += declare.dbtypeid; if(this.dbsize){ s += '('+this.dbsize; if(this.dbprecision){ s+= ','+this.dbprecision; } s += ')'; } if(declare.expression){ s += ' = '+declare.expression.toString(); } return s; }).join(','); } return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
Delete = function (params) { return yy.extend(this, params); }
...
case 453:
this.$ = new yy.SetColumn({column:$$[$0-2], expression:$$[$0]})
break;
case 454:
this.$ = new yy.SetColumn({variable:$$[$0-2], expression:$$[$0], method:$$[$0-3]})
break;
case 455:
this.$ = new yy.Delete({table:$$[$0-2], where:$$[$0]});
break;
case 456:
this.$ = new yy.Delete({table:$$[$0]});
break;
case 457:
this.$ = new yy.Insert({into:$$[$0-2], values: $$[$0]});
break;
...
compile = function (databaseid) { databaseid = this.table.databaseid || databaseid; var tableid = this.table.tableid; var statement; var db = alasql.databases[databaseid]; if(this.where) { if(this.exists) { this.existsfn = this.exists.map(function(ex) { var nq = ex.compile(databaseid); nq.query.modifier='RECORDSET'; return nq; }); } if(this.queries) { this.queriesfn = this.queries.map(function(q) { var nq = q.compile(databaseid); nq.query.modifier='RECORDSET'; return nq; }); } var wherefn = new Function('r,params,alasql','var y;return ('+this.where.toJS('r','')+')').bind(this); statement = (function (params, cb) { if(db.engineid && alasql.engines[db.engineid].deleteFromTable) { return alasql.engines[db.engineid].deleteFromTable(databaseid, tableid, wherefn, params, cb); } if(alasql.options.autocommit && db.engineid && db.engineid == 'LOCALSTORAGE') { alasql.engines[db.engineid].loadTableData(databaseid,tableid); } var table = db.tables[tableid]; var orignum = table.data.length; var newtable = []; for(var i=0, ilen=table.data.length;i<ilen;i++) { if(wherefn(table.data[i],params,alasql)) { // Check for transaction - if it is not possible then return all back if(table.delete) { table.delete(i,params,alasql); } else { // Simply do not push } } else newtable.push(table.data[i]); } table.data = newtable; // Trigger prevent functionality for(var tr in table.afterdelete) { var trigger = table.afterdelete[tr]; if(trigger) { if(trigger.funcid) { alasql.fn[trigger.funcid](); } else if(trigger.statement) { trigger.statement.execute(databaseid); } } }; var res = orignum - table.data.length; if(alasql.options.autocommit && db.engineid && db.engineid == 'LOCALSTORAGE') { alasql.engines[db.engineid].saveTableData(databaseid,tableid); } if(cb) cb(res); return res; }); } else { statement = function (params, cb) { if(alasql.options.autocommit && db.engineid) { alasql.engines[db.engineid].loadTableData(databaseid,tableid); } var table = db.tables[tableid]; table.dirty = true; var orignum = db.tables[tableid].data.length; //table.deleteall(); // Delete all records from the array db.tables[tableid].data.length = 0; // Reset PRIMARY KEY and indexes for(var ix in db.tables[tableid].uniqs) { db.tables[tableid].uniqs[ix] = {}; } for(var ix in db.tables[tableid].indices) { db.tables[tableid].indices[ix] = {}; } if(alasql.options.autocommit && db.engineid) { alasql.engines[db.engineid].saveTableData(databaseid,tableid); } if(cb) cb(orignum); return orignum; }; } return statement; }
...
You can also define your own aggregator functions (like your own `SUM(...)`). See more [in the wiki](https://github.com/agershun
/alasql/wiki/User-Defined-Functions)
### Compiled statements and functions
```js
var ins = alasql.compile('INSERT INTO one VALUES (?,?)');
ins(1,10);
ins(2,20);
```
See more [in the wiki](https://github.com/agershun/alasql/wiki/Compile)
...
execute = function (databaseid, params, cb) { return this.compile(databaseid)(params,cb); }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { var s = 'DELETE FROM '+this.table.toString(); if(this.where) s += ' WHERE '+this.where.toString(); return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
DetachDatabase = function (params) { return yy.extend(this, params); }
...
case 577:
this.$ = new yy.AttachDatabase({databaseid:$$[$0-2], engineid:$$[$0-4].toUpperCase(), as:$$[$0] });
break;
case 578:
this.$ = new yy.AttachDatabase({databaseid:$$[$0-5], engineid:$$[$0-7].toUpperCase(), as:$$[$0], args:$$[$0-3]});
break;
case 579:
this.$ = new yy.DetachDatabase({databaseid:$$[$0]});
break;
case 580:
this.$ = new yy.CreateDatabase({databaseid:$$[$0] }); yy.extend(this.$,$$[$0]);
break;
case 581:
this.$ = new yy.CreateDatabase({engineid:$$[$0-4].toUpperCase(), databaseid:$$[$0-1], as:$$[$0] }); yy.extend(this.$,$$[$0-2]);
break;
...
execute = function (databaseid, params, cb) { if(!alasql.databases[this.databaseid].engineid) { throw new Error('Cannot detach database "'+this.engineid+'", because it was not attached.'); }; var res; var dbid = this.databaseid; if(dbid == alasql.DEFAULTDATABASEID) { throw new Error("Drop of default database is prohibited"); } if(!alasql.databases[dbid]) { if(!this.ifexists) { throw new Error("Database '"+dbid+"' does not exist"); } else { res = 0; } } else { delete alasql.databases[dbid]; if(dbid == alasql.useid) { alasql.use(); } res = 1; } if(cb) cb(res); return res; // var res = alasql.engines[this.engineid].attachDatabase(this.databaseid, this.as, cb); // return res; }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { var s = 'DETACH'; s += ' DATABASE'+' '+this.databaseid; return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
DomainValueValue = function (params) { return yy.extend(this, params); }
...
case 285: case 286:
this.$ = new yy.Column({columnid: $$[$0], tableid: $$[$0-2]});
break;
case 287:
this.$ = new yy.Column({columnid: $$[$0]});
break;
case 302:
this.$ = new yy.DomainValueValue();
break;
case 303:
this.$ = new yy.Json({value:$$[$0]});
break;
case 306: case 307: case 308:
if(!yy.queries) yy.queries = [];
...
toJS = function (context, tableid, defcols) { // return "'"+doubleqq(this.value)+"'"; return context; }
...
* Changed order of LIMIT and ORDER BY processing
#### Version 0.0.4 (28.10.2014-29.10.2014)
* Added /test/main.html mocha browser tests
* Added PERFORMANCE.md and perf.html tests
* StringValue.toJS()
* Added callback to Database.exec
* Sieve of Eratosthenes example
* Remove generation of recs after select in case of group by (for memory optimization)
* Added conversion for type MONEY for INSERT statement
#### Versions 0.0.1 - 0.0.3 (25.10.2014-27.10.2014)
...
toString = function () { return 'VALUE' }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
toType = function () { return 'object'; }
...
if(['-','*','/','%','^'].indexOf(this.op) >-1){
return 'number';
}
if(['||'].indexOf(this.op) >-1){
return 'string';
}
if(this.op === '+') {
if(this.left.toType(tableid) === 'string' || this.right.toType(tableid) ===
x27;string'){
return 'string';
}
if(this.left.toType(tableid) === 'number' || this.right.toType(tableid) === 'number'){
return 'number';
}
}
if(['AND','OR','NOT','=','==','===', '!=','!==',
x27;!===','>','>=','<','<=', 'IN', 'NOT IN',
x27;LIKE', 'NOT LIKE', 'REGEXP', 'GLOB'].indexOf(this.op) >-1 ){
...
DropDatabase = function (params) { return yy.extend(this, params); }
...
case 584:
this.$ = undefined;
break;
case 586: case 587:
this.$ = new yy.UseDatabase({databaseid: $$[$0] });
break;
case 588:
this.$ = new yy.DropDatabase({databaseid: $$[$0] }); yy.extend(this.$,$$[$0-1]);
break;
case 589: case 590:
this.$ = new yy.DropDatabase({databaseid: $$[$0], engineid:$$[$0-3].toUpperCase() }); yy.extend(this.$,$$[$0-1]);
break;
case 591:
this.$ = new yy.CreateIndex({indexid:$$[$0-5], table:$$[$0-3], columns:$$[$0-1]})
break;
...
execute = function (databaseid, params, cb) { if(this.engineid) { return alasql.engines[this.engineid].dropDatabase(this.databaseid, this.ifexists, cb); } var res; var dbid = this.databaseid; if(dbid == alasql.DEFAULTDATABASEID) { throw new Error("Drop of default database is prohibited"); } if(!alasql.databases[dbid]) { if(!this.ifexists) { throw new Error("Database '"+dbid+"' does not exist"); } else { res = 0; } } else { if(alasql.databases[dbid].engineid) { throw new Error("Cannot drop database '"+dbid+"', because it is attached. Detach it."); } delete alasql.databases[dbid]; if(dbid == alasql.useid) { alasql.use(); } res = 1; } if(cb) cb(res); return res; }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { var s = 'DROP'; if(this.ifexists) s += ' IF EXISTS'; s += ' DATABASE '+this.databaseid; return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
DropIndex = function (params) { return yy.extend(this, params); }
...
case 591:
this.$ = new yy.CreateIndex({indexid:$$[$0-5], table:$$[$0-3], columns:$$[$0-1]})
break;
case 592:
this.$ = new yy.CreateIndex({indexid:$$[$0-5], table:$$[$0-3], columns:$$[$0-1], unique:true})
break;
case 593:
this.$ = new yy.DropIndex({indexid:$$[$0]});
break;
case 594:
this.$ = new yy.ShowDatabases();
break;
case 595:
this.$ = new yy.ShowDatabases({like:$$[$0]});
break;
...
compile = function (db) { var indexid = this.indexid; return function() { return 1; } }
...
You can also define your own aggregator functions (like your own `SUM(...)`). See more [in the wiki](https://github.com/agershun
/alasql/wiki/User-Defined-Functions)
### Compiled statements and functions
```js
var ins = alasql.compile('INSERT INTO one VALUES (?,?)');
ins(1,10);
ins(2,20);
```
See more [in the wiki](https://github.com/agershun/alasql/wiki/Compile)
...
toString = function () { return 'DROP INDEX' + this.indexid; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
DropTable = function (params) { return yy.extend(this, params); }
...
case 562:
this.$ = {"onupdate":$$[$0]};
break;
case 563:
this.$ = {"onupdate":$$[$0-1]};
break;
case 564:
this.$ = new yy.DropTable({tables:$$[$0],type:$$[$0-2]}); yy.extend(this.$, $$[$0-1]);
break;
case 568:
this.$ = {ifexists: true};
break;
case 569:
this.$ = new yy.AlterTable({table:$$[$0-3], renameto: $$[$0]});
break;
...
execute = function (databaseid, params, cb) { var ifexists = this.ifexists; var res = 0; // No tables removed var count = 0; var tlen = this.tables.length; // For each table in the list this.tables.forEach(function(table){ var db = alasql.databases[table.databaseid || databaseid]; var tableid = table.tableid; /** @todo Test with AUTOCOMMIT flag is ON */ /** @todo Test with IndexedDB and multiple tables */ if(!ifexists || ifexists && db.tables[tableid]) { if(!db.tables[tableid]) { if(!alasql.options.dropifnotexists) { throw new Error('Can not drop table \''+table.tableid+'\', because it does not exist in the database.'); } } else { if(db.engineid /*&& alasql.options.autocommit*/) { alasql.engines[db.engineid].dropTable(table.databaseid || databaseid, tableid, ifexists, function(res1){ delete db.tables[tableid]; res+=res1; count++; if(count == tlen && cb) cb(res); }); } else { delete db.tables[tableid]; res++; count++; if(count == tlen && cb) cb(res); } } } else { count++; if(count == tlen && cb) cb(res); } }); // if(cb) res = cb(res); return res; }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { var s = 'DROP'+' '; if(this.view) s += 'VIEW'; else s += 'TABLE'; if(this.ifexists) s += ' IF EXISTS'; s += ' '+this.tables.toString(); return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
DropTrigger = function (params) { return yy.extend(this, params); }
...
case 770:
this.$ = 'DELETE';
break;
case 771:
this.$ = 'UPDATE';
break;
case 772:
this.$ = new yy.DropTrigger({trigger:$$[$0]});
break;
case 773:
this.$ = new yy.Reindex({indexid:$$[$0]});
break;
case 1047: case 1067: case 1069: case 1071: case 1075: case 1077: case 1079: case 1081: case 1083: case 1085:
this.$ = [];
break;
...
execute = function (databaseid, params, cb) { var res = 0; // No tables removed var db = alasql.databases[databaseid]; var triggerid = this.trigger; // For each table in the list var tableid = db.triggers[triggerid]; if(tableid) { res = 1; delete db.tables[tableid].beforeinsert[triggerid]; delete db.tables[tableid].afterinsert[triggerid]; delete db.tables[tableid].insteadofinsert[triggerid]; delete db.tables[tableid].beforedelte[triggerid]; delete db.tables[tableid].afterdelete[triggerid]; delete db.tables[tableid].insteadofdelete[triggerid]; delete db.tables[tableid].beforeupdate[triggerid]; delete db.tables[tableid].afterupdate[triggerid]; delete db.tables[tableid].insteadofupdate[triggerid]; delete db.triggers[triggerid]; } else { throw new Error('Trigger not found'); } if(cb) res = cb(res); return res; }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { var s = 'DROP TRIGGER '+this.trigger; return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
ExistsValue = function (params) { return yy.extend(this, params); }
...
break;
case 362:
this.$ = new yy.VarValue({variable:$$[$0]});
break;
case 363:
if(!yy.exists) yy.exists = [];
this.$ = new yy.ExistsValue({value:$$[$0-1], existsidx:yy.exists.length});
yy.exists.push($$[$0-1]);
break;
case 364:
this.$ = new yy.ArrayValue({value:$$[$0-1]});
break;
case 365: case 366:
this.$ = new yy.ParamValue({param: $$[$0]});
...
toJS = function (context, tableid, defcols) { return 'this.existsfn['+this.existsidx+'](params,null,'+context+').data.length'; }
...
* Changed order of LIMIT and ORDER BY processing
#### Version 0.0.4 (28.10.2014-29.10.2014)
* Added /test/main.html mocha browser tests
* Added PERFORMANCE.md and perf.html tests
* StringValue.toJS()
* Added callback to Database.exec
* Sieve of Eratosthenes example
* Remove generation of recs after select in case of group by (for memory optimization)
* Added conversion for type MONEY for INSERT statement
#### Versions 0.0.1 - 0.0.3 (25.10.2014-27.10.2014)
...
toString = function () { return 'EXISTS('+this.value.toString()+')'; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
toType = function () { return 'boolean'; }
...
if(['-','*','/','%','^'].indexOf(this.op) >-1){
return 'number';
}
if(['||'].indexOf(this.op) >-1){
return 'string';
}
if(this.op === '+') {
if(this.left.toType(tableid) === 'string' || this.right.toType(tableid) ===
x27;string'){
return 'string';
}
if(this.left.toType(tableid) === 'number' || this.right.toType(tableid) === 'number'){
return 'number';
}
}
if(['AND','OR','NOT','=','==','===', '!=','!==',
x27;!===','>','>=','<','<=', 'IN', 'NOT IN',
x27;LIKE', 'NOT LIKE', 'REGEXP', 'GLOB'].indexOf(this.op) >-1 ){
...
Expression = function (params) { return yy.extend(this, params); }
...
case 235:
this.$ = {on: $$[$0]};
break;
case 236: case 697:
this.$ = {using: $$[$0]};
break;
case 239:
this.$ = {where: new yy.Expression({expression:$$[$0]})};
break;
case 241:
this.$ = {group:$$[$0-1]}; yy.extend(this.$,$$[$0]);
break;
case 244:
this.$ = new yy.GroupExpression({type:'GROUPING SETS', group: $$[$0-1]});
break;
...
compile = function (context, tableid, defcols){ if(this.reduced) { return returnTrue(); } return new Function('p','var y;return '+this.toJS(context, tableid, defcols)); }
...
You can also define your own aggregator functions (like your own `SUM(...)`). See more [in the wiki](https://github.com/agershun
/alasql/wiki/User-Defined-Functions)
### Compiled statements and functions
```js
var ins = alasql.compile('INSERT INTO one VALUES (?,?)');
ins(1,10);
ins(2,20);
```
See more [in the wiki](https://github.com/agershun/alasql/wiki/Compile)
...
findAggregator = function (query){ if(this.expression.findAggregator) { this.expression.findAggregator(query); } }
...
// }
} else {
query.groupStar = col.tableid || 'default';
}
});
this.columns.forEach(function(col){
if(col.findAggregator){
col.findAggregator(query);
}
});
if(this.having) {
if(this.having.findAggregator){
this.having.findAggregator(query);
}
}
...
toJS = function (context, tableid, defcols) { if(this.expression.reduced) { return 'true'; } return this.expression.toJS(context, tableid, defcols); }
...
* Changed order of LIMIT and ORDER BY processing
#### Version 0.0.4 (28.10.2014-29.10.2014)
* Added /test/main.html mocha browser tests
* Added PERFORMANCE.md and perf.html tests
* StringValue.toJS()
* Added callback to Database.exec
* Sieve of Eratosthenes example
* Remove generation of recs after select in case of group by (for memory optimization)
* Added conversion for type MONEY for INSERT statement
#### Versions 0.0.1 - 0.0.3 (25.10.2014-27.10.2014)
...
toString = function (dontas) { var s = this.expression.toString(dontas); if(this.order) { s += ' '+this.order.toString(); } if(this.nocase) { s += ' COLLATE NOCASE'; } return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
ExpressionStatement = function (params) { return yy.extend(this, params); }
...
yy.extend(this.$,$$[$0-6]);
yy.extend(this.$,$$[$0-4]);
break;
case 613:
this.$ = new yy.DropTable({tables:$$[$0], view:true}); yy.extend(this.$, $$[$0-1]);
break;
case 614: case 760:
this.$ = new yy.ExpressionStatement({expression:$$[$0]});
break;
case 615:
this.$ = new yy.Source({url:$$[$0].value});
break;
case 616:
this.$ = new yy.Assert({value:$$[$0]});
break;
...
execute = function (databaseid, params, cb) { if(this.expression) { alasql.precompile(this,databaseid,params); // Precompile queries var exprfn = new Function("params,alasql,p",'var y;return '+this.expression.toJS('({})','', null)).bind(this); var res = exprfn(params,alasql); if(cb) { res = cb(res); } return res; } }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { return this.expression.toString(); }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
FromData = function (params) { return yy.extend(this, params); }
n/a
toJS = function (){ }
...
* Changed order of LIMIT and ORDER BY processing
#### Version 0.0.4 (28.10.2014-29.10.2014)
* Added /test/main.html mocha browser tests
* Added PERFORMANCE.md and perf.html tests
* StringValue.toJS()
* Added callback to Database.exec
* Sieve of Eratosthenes example
* Remove generation of recs after select in case of group by (for memory optimization)
* Added conversion for type MONEY for INSERT statement
#### Versions 0.0.1 - 0.0.3 (25.10.2014-27.10.2014)
...
toString = function () { if(this.data) return 'DATA('+((Math.random()*10e15)|0)+')'; else return '?'; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
FuncValue = function (params){ return yy.extend(this, params); }
...
case 168:
var s = $$[$0];
s = s.substr(1,s.length-2);
var x3 = s.substr(-3).toUpperCase();
var x4 = s.substr(-4).toUpperCase();
if(s[0] == '#') {
this.$ = {into: new yy.FuncValue({funcid: 'HTML', args:[new yy.StringValue
({value: s}), new yy.Json({value:{headers:true}})]})};
} else if(x3=='XLS' || x3 == 'CSV' || x3=='TAB') {
this.$ = {into: new yy.FuncValue({funcid: x3, args:[new yy.StringValue({value: s}), new yy.Json({value:{headers:true}})]})};
} else if(x4=='XLSX' || x4 == 'JSON') {
this.$ = {into: new yy.FuncValue({funcid: x4, args:[new yy.StringValue({value: s}), new yy.Json({value:{headers:true}})]})};
}
break;
case 169:
...
execute = function (databaseid, params, cb) { var res = 1; alasql.precompile(this,databaseid,params); // Precompile queries var expr = new Function('params,alasql','var y;return '+this.toJS('','',null)); expr(params,alasql); if(cb) res = cb(res); return res; }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
findAggregator = function (query) { if(this.args && this.args.length > 0) { this.args.forEach(function(arg){ if(arg.findAggregator) arg.findAggregator(query); }); } }
...
// }
} else {
query.groupStar = col.tableid || 'default';
}
});
this.columns.forEach(function(col){
if(col.findAggregator){
col.findAggregator(query);
}
});
if(this.having) {
if(this.having.findAggregator){
this.having.findAggregator(query);
}
}
...
toJS = function (context, tableid, defcols) { var s = ''; var funcid = this.funcid; // IF this is standard compile functions if(!alasql.fn[funcid] && alasql.stdlib[funcid.toUpperCase()]) { if(this.args && this.args.length > 0) { s += alasql.stdlib[funcid.toUpperCase()].apply(this, this.args.map(function(arg) {return arg.toJS(context, tableid)})); } else { s += alasql.stdlib[funcid.toUpperCase()](); } } else if(!alasql.fn[funcid] && alasql.stdfn[funcid.toUpperCase()]) { if(this.newid) s+= 'new '; s += 'alasql.stdfn.'+this.funcid.toUpperCase()+'('; if(this.args && this.args.length > 0) { s += this.args.map(function(arg){ return arg.toJS(context, tableid, defcols); }).join(','); }; s += ')'; } else { // This is user-defined run-time function // TODO arguments!!! if(this.newid) s+= 'new '; s += 'alasql.fn.'+this.funcid+'('; if(this.args && this.args.length > 0) { s += this.args.map(function(arg){ return arg.toJS(context, tableid, defcols); }).join(','); }; s += ')'; } // if(this.alias) s += ' AS '+this.alias; return s; }
...
* Changed order of LIMIT and ORDER BY processing
#### Version 0.0.4 (28.10.2014-29.10.2014)
* Added /test/main.html mocha browser tests
* Added PERFORMANCE.md and perf.html tests
* StringValue.toJS()
* Added callback to Database.exec
* Sieve of Eratosthenes example
* Remove generation of recs after select in case of group by (for memory optimization)
* Added conversion for type MONEY for INSERT statement
#### Versions 0.0.1 - 0.0.3 (25.10.2014-27.10.2014)
...
toString = function (dontas) { var s = ''; if(alasql.fn[this.funcid]) s += this.funcid; else if(alasql.aggr[this.funcid]) s += this.funcid; else if(alasql.stdlib[this.funcid.toUpperCase()] || alasql.stdfn[this.funcid.toUpperCase()]) s += this.funcid.toUpperCase(); s += '('; if(this.args && this.args.length > 0) { s += this.args.map(function(arg){ return arg.toString(); }).join(','); }; s += ')'; if(this.as && !dontas) s += ' AS '+this.as.toString(); // if(this.alias) s += ' AS '+this.alias; return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
GroupExpression = function (params){ return yy.extend(this, params); }
...
case 239:
this.$ = {where: new yy.Expression({expression:$$[$0]})};
break;
case 241:
this.$ = {group:$$[$0-1]}; yy.extend(this.$,$$[$0]);
break;
case 244:
this.$ = new yy.GroupExpression({type:'GROUPING SETS', group: $$[$0-1]});
break;
case 245:
this.$ = new yy.GroupExpression({type:'ROLLUP', group: $$[$0-1]});
break;
case 246:
this.$ = new yy.GroupExpression({type:'CUBE', group: $$[$0-1]});
break;
...
toString = function () { return this.type+'('+this.group.toString()+')'; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
If = function (params) { return yy.extend(this, params); }
...
case 666:
this.$ = new yy.RollbackTransaction();
break;
case 667:
this.$ = new yy.BeginTransaction();
break;
case 668:
this.$ = new yy.If({expression:$$[$0-2],thenstat:$$[$0-1], elsestat:$$[$0]});
if($$[$0-1].exists) this.$.exists = $$[$0-1].exists;
if($$[$0-1].queries) this.$.queries = $$[$0-1].queries;
break;
case 669:
this.$ = new yy.If({expression:$$[$0-1],thenstat:$$[$0]});
if($$[$0].exists) this.$.exists = $$[$0].exists;
...
execute = function (databaseid, params, cb){ var res; var fn = new Function('params,alasql,p','var y;return '+this.expression.toJS('({})','',null)).bind(this); if(fn(params,alasql)) res = this.thenstat.execute(databaseid,params,cb); else { if(this.elsestat) res = this.elsestat.execute(databaseid,params,cb); else { if(cb) res = cb(res); } } return res; }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { var s = 'IF'+' '; s += this.expression.toString(); s += ' '+this.thenstat.toString(); if(this.elsestat) s += ' ELSE '+this.thenstat.toString(); return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
Insert = function (params) { return yy.extend(this, params); }
...
case 455:
this.$ = new yy.Delete({table:$$[$0-2], where:$$[$0]});
break;
case 456:
this.$ = new yy.Delete({table:$$[$0]});
break;
case 457:
this.$ = new yy.Insert({into:$$[$0-2], values: $$[$0]});
break;
case 458:
this.$ = new yy.Insert({into:$$[$0-1], values: $$[$0]});
break;
case 459: case 461:
this.$ = new yy.Insert({into:$$[$0-2], values: $$[$0], orreplace:true});
break;
...
compile = function (databaseid) { var self = this; databaseid = self.into.databaseid || databaseid var db = alasql.databases[databaseid]; var tableid = self.into.tableid; var table = db.tables[tableid]; if(!table){ throw "Table '"+tableid+"' could not be found"; } // Check, if this dirty flag is required var s = ''; var sw = ''; var s = 'db.tables[\''+tableid+'\'].dirty=true;'; var s3 = 'var a,aa=[],x;'; var s33; // INSERT INTO table VALUES if(this.values) { if(this.exists) { this.existsfn = this.exists.map(function(ex) { var nq = ex.compile(databaseid); nq.query.modifier='RECORDSET'; return nq; }); } if(this.queries) { this.queriesfn = this.queries.map(function(q) { var nq = q.compile(databaseid); nq.query.modifier='RECORDSET'; return nq; }); } self.values.forEach(function(values) { var ss = []; if(self.columns) { self.columns.forEach(function(col, idx){ var q = "'"+col.columnid +'\':'; if(table.xcolumns && table.xcolumns[col.columnid]) { if(["INT","FLOAT","NUMBER","MONEY"].indexOf(table.xcolumns[col.columnid].dbtypeid) >=0) { //q += '' q += "(x="+values[idx].toJS()+",x==undefined?undefined:+x)"; } else if (alasql.fn[table.xcolumns[col.columnid].dbtypeid]) { q += "(new "+table.xcolumns[col.columnid].dbtypeid+"("; q += values[idx].toJS(); q += "))"; } else { q += values[idx].toJS(); }; } else { q += values[idx].toJS(); } ss.push(q); }); } else { if((Array.isArray(values)) && table.columns && table.columns.length > 0) { table.columns.forEach(function(col, idx){ var q = '\''+col.columnid +'\':'; if(["INT","FLOAT","NUMBER","MONEY"].indexOf(col.dbtypeid) >=0) { q += "+"+values[idx].toJS(); } else if (alasql.fn[col.dbtypeid]) { q += "(new "+col.dbtypeid+"("; q += values[idx].toJS(); q += "))"; } else { q += values[idx].toJS(); } ss.push(q); }); } else { sw = JSONtoJS(values); } } if(db.tables[tableid].defaultfns) { ss.unshift(db.tables[tableid].defaultfns); }; if(sw) { s += 'a='+sw+';'; } else { s += 'a={'+ss.join(',')+'};'; } // If this is a class if(db.tables[tableid].isclass) { s += 'var db=alasql.databases[\''+databaseid+'\'];'; s+= 'a.$class="'+tableid+'";'; s+= 'a.$id=db.counter++;'; s+= 'db.objects[a.$id]=a;'; }; if(db.tables[tableid].insert) { s += 'var db=alasql.databases[\''+databaseid+'\'];'; s += 'db.tables[\''+tableid+'\'].insert(a,'+(self.orreplace?"true":"false")+');'; } else { s += 'aa.push(a);'; } }); s33 = s3+s; if(db.tables[tableid].insert) { } else { s += 'alasql.databases[\''+databaseid+'\'].tables[\''+tableid+'\'].data='+ 'alasql.databases[\''+databaseid+'\'].tables[\''+tableid+'\'].data.concat(aa);'; } if(db.tables[tableid].insert) { if(db.tables[tableid].isclass) { s += 'return a.$id;'; } else { s += 'return '+self.values.length; } } else { s += 'return '+self.values.length; } var insertfn = new Function('db, params, alasql','var y;'+s3+s).bind(this); // INSERT INTO table SELECT } else if(this.select) { this.select.modifier = 'RECORDSET'; var selectfn = this.select.compile(databaseid); if(db.engineid && alasql.engines[db.engineid].intoTable) { var statement = function(params, cb) { var aa = selectfn(params); var res = alasql.engines[db.engineid].intoTable(db.databaseid,tableid,aa.data,null, cb); return res; }; return statement; } else { var defaultfns = 'return alasql.utils.extend(r,{'+table.defaultfns+'})'; var defaultfn = new Function('r,db,params,alasql',defaultfns); var insertfn = function(db, params, alasql) { var res = selectfn(params).data; if(db.tables[tableid].insert) { // If insert() function exists (issue #92) ...
...
You can also define your own aggregator functions (like your own `SUM(...)`). See more [in the wiki](https://github.com/agershun
/alasql/wiki/User-Defined-Functions)
### Compiled statements and functions
```js
var ins = alasql.compile('INSERT INTO one VALUES (?,?)');
ins(1,10);
ins(2,20);
```
See more [in the wiki](https://github.com/agershun/alasql/wiki/Compile)
...
execute = function (databaseid, params, cb) { return this.compile(databaseid)(params,cb); // throw new Error('Insert statement is should be compiled') }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toJS = function (context, tableid, defcols) { // if(this.expression.reduced) return 'true'; // return this.expression.toJS(context, tableid, defcols); // var s = 'this.queriesdata['+(this.queriesidx-1)+'][0]'; var s = 'this.queriesfn['+(this.queriesidx-1)+'](this.params,null,'+context+')'; return s; }
...
* Changed order of LIMIT and ORDER BY processing
#### Version 0.0.4 (28.10.2014-29.10.2014)
* Added /test/main.html mocha browser tests
* Added PERFORMANCE.md and perf.html tests
* StringValue.toJS()
* Added callback to Database.exec
* Sieve of Eratosthenes example
* Remove generation of recs after select in case of group by (for memory optimization)
* Added conversion for type MONEY for INSERT statement
#### Versions 0.0.1 - 0.0.3 (25.10.2014-27.10.2014)
...
toString = function () { var s = 'INSERT '; if(this.orreplace) s += 'OR REPLACE '; if(this.replaceonly) s = 'REPLACE '; s += 'INTO '+this.into.toString(); if(this.columns) s += '('+this.columns.toString()+')'; if(this.values) s += ' VALUES '+this.values.toString(); if(this.select) s += ' '+this.select.toString(); return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
JavaScript = function (params) { return yy.extend(this, params); }
...
case 309:
this.$ = $$[$0]
break;
case 310:
this.$ = new yy.FuncValue({funcid:'CURRENT_TIMESTAMP'});
break;
case 311:
this.$ = new yy.JavaScript({value:$$[$0].substr(2,$$[$0].length-4)});
break;
case 312:
this.$ = new yy.JavaScript({value:'alasql.fn["'+$$[$0-2]+'"] = '+$$[$0].substr(2,$$[$0].length-4)});
break;
case 313:
this.$ = new yy.JavaScript({value:'alasql.aggr["'+$$[$0-2]+'"] = '+$$[$0].substr(2,$$[$0].length-
4)});
break;
...
execute = function (databaseid, params, cb) { var res = 1; var expr = new Function("params,alasql,p",this.value); expr(params,alasql); if(cb){ res = cb(res); } return res; }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toJS = function () { return '('+this.value+')'; }
...
* Changed order of LIMIT and ORDER BY processing
#### Version 0.0.4 (28.10.2014-29.10.2014)
* Added /test/main.html mocha browser tests
* Added PERFORMANCE.md and perf.html tests
* StringValue.toJS()
* Added callback to Database.exec
* Sieve of Eratosthenes example
* Remove generation of recs after select in case of group by (for memory optimization)
* Added conversion for type MONEY for INSERT statement
#### Versions 0.0.1 - 0.0.3 (25.10.2014-27.10.2014)
...
toString = function () { var s = '``'+this.value+'``'; return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
Join = function (params) { return yy.extend(this, params); }
...
case 202:
this.$ = new yy.Table({tableid: $$[$0]});
break;
case 203: case 204:
this.$ = $$[$0-1]; $$[$0-1].push($$[$0]);
break;
case 207:
this.$ = new yy.Join($$[$0-2]); yy.extend(this.$, $$[$0-1]); yy.extend(this.$, $$[$0
]);
break;
case 208:
this.$ = {table: $$[$0]};
break;
case 209:
this.$ = {table: $$[$0-1], as: $$[$0] } ;
break;
...
toString = function () { var s = ' '; if(this.joinmode){ s += this.joinmode+' '; } s += 'JOIN ' + this.table.toString(); return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
Json = function (params) { return yy.extend(this, params); }
...
case 116:
this.$ = {srchid:"ININ"};
break;
case 117:
this.$ = {srchid:"CONTENT"};
break;
case 118:
this.$ = {srchid:"EX",args:[new yy.Json({value:$$[$0]})]};
break;
case 119:
this.$ = {srchid:"AT", args:[$$[$0]]};
break;
case 120:
this.$ = {srchid:"AS", args:[$$[$0]]};
break;
...
toJS = function (context, tableid, defcols) { // TODO redo return JSONtoJS(this.value,context, tableid, defcols); }
...
* Changed order of LIMIT and ORDER BY processing
#### Version 0.0.4 (28.10.2014-29.10.2014)
* Added /test/main.html mocha browser tests
* Added PERFORMANCE.md and perf.html tests
* StringValue.toJS()
* Added callback to Database.exec
* Sieve of Eratosthenes example
* Remove generation of recs after select in case of group by (for memory optimization)
* Added conversion for type MONEY for INSERT statement
#### Versions 0.0.1 - 0.0.3 (25.10.2014-27.10.2014)
...
toString = function () { var s = ''; // '@' s += JSONtoString(this.value); s += ''; return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
Literal = function (params) { return yy.extend(this, params); }
n/a
toString = function (dontas) { var s = this.value; if(this.value1){ s = this.value1+'.'+s; } if(this.alias && !dontas) s += ' AS '+this.alias; // else s = tableid+'.'+s; return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
LogicValue = function (params) { return yy.extend(this, params); }
...
case 355:
$$[$0-2].push($$[$0]); this.$ = $$[$0-2]
break;
case 356:
this.$ = new yy.NumValue({value:+$$[$0]});
break;
case 357:
this.$ = new yy.LogicValue({value:true});
break;
case 358:
this.$ = new yy.LogicValue({value:false});
break;
case 359:
this.$ = new yy.StringValue({value: $$[$0].substr(1,$$[$0].length-2).replace(/(\\\')/g,"'").replace(/(\'
;\')/g,"'")});
break;
...
toJS = function () { return this.value?'true':'false'; }
...
* Changed order of LIMIT and ORDER BY processing
#### Version 0.0.4 (28.10.2014-29.10.2014)
* Added /test/main.html mocha browser tests
* Added PERFORMANCE.md and perf.html tests
* StringValue.toJS()
* Added callback to Database.exec
* Sieve of Eratosthenes example
* Remove generation of recs after select in case of group by (for memory optimization)
* Added conversion for type MONEY for INSERT statement
#### Versions 0.0.1 - 0.0.3 (25.10.2014-27.10.2014)
...
toString = function () { return this.value?'TRUE':'FALSE'; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
toType = function () { return 'boolean'; }
...
if(['-','*','/','%','^'].indexOf(this.op) >-1){
return 'number';
}
if(['||'].indexOf(this.op) >-1){
return 'string';
}
if(this.op === '+') {
if(this.left.toType(tableid) === 'string' || this.right.toType(tableid) ===
x27;string'){
return 'string';
}
if(this.left.toType(tableid) === 'number' || this.right.toType(tableid) === 'number'){
return 'number';
}
}
if(['AND','OR','NOT','=','==','===', '!=','!==',
x27;!===','>','>=','<','<=', 'IN', 'NOT IN',
x27;LIKE', 'NOT LIKE', 'REGEXP', 'GLOB'].indexOf(this.op) >-1 ){
...
Merge = function (params) { return yy.extend(this, params); }
...
this.$ = {variable: $$[$0-4], expression:$$[$0]}; yy.extend(this.$,$$[$0-2]);
break;
case 693:
this.$ = new yy.TruncateTable({table:$$[$0]});
break;
case 694:
this.$ = new yy.Merge(); yy.extend(this.$,$$[$0-4]); yy.extend(this.$,$$[$0-3]);
yy.extend(this.$,$$[$0-2]);
yy.extend(this.$,{matches:$$[$0-1]});yy.extend(this.$,$$[$0]);
break;
case 695: case 696:
this.$ = {into: $$[$0]};
break;
case 698:
...
execute = function (databaseid, params, cb) { var res = 1; if(cb) res=cb(res); return res; }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { var s = 'MERGE '; s += this.into.tableid+' '; if(this.into.as) s += 'AS '+this.into.as+' '; s += 'USING '+this.using.tableid+' '; if(this.using.as) s += 'AS '+this.using.as+' '; s += 'ON '+this.on.toString()+' '; this.matches.forEach(function(m){ s += 'WHEN '; if(!m.matched) s += 'NOT '; s += 'MATCHED '; if(m.bytarget) s += 'BY TARGET '; if(m.bysource) s += 'BY SOURCE '; if(m.expr) s+= 'AND'+' '+m.expr.toString()+' '; s += 'THEN '; if(m.action.delete) s += 'DELETE '; if(m.action.insert) { s += 'INSERT '; if(m.action.columns) s += '('+m.action.columns.toString()+') '; if(m.action.values) s += 'VALUES ('+m.action.values.toString()+') '; if(m.action.defaultvalues) s += 'DEFAULT VALUES '; } if(m.action.update) { s += 'UPDATE '; s += m.action.update.map(function(u){ return u.toString(); }).join(',')+' '; } }); return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
NullValue = function (params) { return yy.extend(this, params); }
...
case 359:
this.$ = new yy.StringValue({value: $$[$0].substr(1,$$[$0].length-2).replace(/(\\\')/g,"'").replace(/(\'
;\')/g,"'")});
break;
case 360:
this.$ = new yy.StringValue({value: $$[$0].substr(2,$$[$0].length-3).replace(/(\\\')/g,"'").replace(/(\'
;\')/g,"'")});
break;
case 361:
this.$ = new yy.NullValue({value:undefined});
break;
case 362:
this.$ = new yy.VarValue({variable:$$[$0]});
break;
case 363:
if(!yy.exists) yy.exists = [];
...
toJS = function () { return 'undefined'; // return 'undefined'; }
...
* Changed order of LIMIT and ORDER BY processing
#### Version 0.0.4 (28.10.2014-29.10.2014)
* Added /test/main.html mocha browser tests
* Added PERFORMANCE.md and perf.html tests
* StringValue.toJS()
* Added callback to Database.exec
* Sieve of Eratosthenes example
* Remove generation of recs after select in case of group by (for memory optimization)
* Added conversion for type MONEY for INSERT statement
#### Versions 0.0.1 - 0.0.3 (25.10.2014-27.10.2014)
...
toString = function () { return 'NULL'; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
NumValue = function (params) { return yy.extend(this, params); }
...
case 353:
this.$ = new yy.FuncValue({ funcid: 'INTERVAL', args:[$$[$0-1],new yy.StringValue({value:($$[$0]).toLowerCase()})]});
break;
case 355:
$$[$0-2].push($$[$0]); this.$ = $$[$0-2]
break;
case 356:
this.$ = new yy.NumValue({value:+$$[$0]});
break;
case 357:
this.$ = new yy.LogicValue({value:true});
break;
case 358:
this.$ = new yy.LogicValue({value:false});
break;
...
toJS = function () { return ""+this.value; }
...
* Changed order of LIMIT and ORDER BY processing
#### Version 0.0.4 (28.10.2014-29.10.2014)
* Added /test/main.html mocha browser tests
* Added PERFORMANCE.md and perf.html tests
* StringValue.toJS()
* Added callback to Database.exec
* Sieve of Eratosthenes example
* Remove generation of recs after select in case of group by (for memory optimization)
* Added conversion for type MONEY for INSERT statement
#### Versions 0.0.1 - 0.0.3 (25.10.2014-27.10.2014)
...
toString = function () { return this.value.toString(); }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
toType = function () { return 'number'; }
...
if(['-','*','/','%','^'].indexOf(this.op) >-1){
return 'number';
}
if(['||'].indexOf(this.op) >-1){
return 'string';
}
if(this.op === '+') {
if(this.left.toType(tableid) === 'string' || this.right.toType(tableid) ===
x27;string'){
return 'string';
}
if(this.left.toType(tableid) === 'number' || this.right.toType(tableid) === 'number'){
return 'number';
}
}
if(['AND','OR','NOT','=','==','===', '!=','!==',
x27;!===','>','>=','<','<=', 'IN', 'NOT IN',
x27;LIKE', 'NOT LIKE', 'REGEXP', 'GLOB'].indexOf(this.op) >-1 ){
...
Op = function (params) { return yy.extend(this, params); }
...
case 371: case 699: case 700:
this.$ = $$[$0-1]; this.$.push($$[$0]);
break;
case 373:
this.$ = {when: $$[$0-2], then: $$[$0] };
break;
case 376: case 377:
this.$ = new yy.Op({left:$$[$0-2], op:'REGEXP', right:$$[$0]});
break;
case 378:
this.$ = new yy.Op({left:$$[$0-2], op:'GLOB', right:$$[$0]});
break;
case 379:
this.$ = new yy.Op({left:$$[$0-2], op:'LIKE', right:$$[$0]});
break;
...
findAggregator = function (query){ if(this.left && this.left.findAggregator){ this.left.findAggregator(query); } // Do not go in > ALL if(this.right && this.right.findAggregator && (!this.allsome)) { this.right.findAggregator(query); } }
...
// }
} else {
query.groupStar = col.tableid || 'default';
}
});
this.columns.forEach(function(col){
if(col.findAggregator){
col.findAggregator(query);
}
});
if(this.having) {
if(this.having.findAggregator){
this.having.findAggregator(query);
}
}
...
toJS = function (context, tableid, defcols) { var s; var refs = []; var op = this.op; var _this = this; //var leftJS = function(){return _this.left.toJS(context,tableid, defcols)}; //var rightJS = function(){return _this.right.toJS(context,tableid, defcols)}; var accessedLeft = false, accessedRight = false var ref = function(expr) { if (expr.toJS) { expr = expr.toJS(context, tableid, defcols) } var i = refs.push(expr) - 1 return 'y[' + i + ']' } var leftJS = function() { return ref(_this.left) } var rightJS = function() { return ref(_this.right) } if(this.op === '='){ op = '==='; } else if(this.op === '<>'){ op = '!='; } else if(this.op === 'OR'){ op = '||'; } // Arrow operator if(this.op === '->') { // Expression to prevent error if object is empty (#344) var ljs = '('+leftJS()+'||{})'; if(typeof this.right === "string") { s = ljs +'["'+this.right+'"]'; } else if(typeof this.right === "number") { s = ljs+'['+this.right+']'; } else if(this.right instanceof yy.FuncValue) { var ss = []; if(!(!this.right.args || 0 === this.right.args.length)) { var ss = this.right.args.map(ref); } s = '' + ljs + "['" + this.right.funcid + "'](" + ss.join(',') + ')'; } else { s = '' + ljs + '[' + rightJS() + ']'; } } if(this.op === '!') { if(typeof this.right === "string") { s = '' + 'alasql.databases[alasql.useid].objects[' + leftJS() + ']["' + this.right + '"]'; } // TODO - add other cases } if(this.op === 'IS') { s = '' + '(' + '(' + leftJS() + "==null)" // Cant be === + " === " + '(' + rightJS() + "==null)" // Cant be === + ')'; } if(this.op === '==') { s = '' + 'alasql.utils.deepEqual(' + leftJS() + ',' + rightJS() + ')'; } if(this.op === '===' || this.op === '!===') { s = '' + '(' + ( (this.op === '!===') ? '!' : '') + '(' + '(' + leftJS() + ").valueOf()" + '===' + '(' + rightJS() + ").valueOf()" + ')' + ')'; } if(this.op === '!==') { s = '' + '(!alasql.utils.deepEqual(' + leftJS() + "," + rightJS() + '))'; } if(this.op === '||') { s = '' + "(''+(" + leftJS() + "||'')+(" + rightJS() + '||""))'; } if(this.op === 'LIKE' || this.op === 'NOT LIKE') { var s = '(' + ( (this.op === 'NOT LIKE') ? '!' : '') + 'alasql.utils.like(' + rightJS()+ "," + leftJS(); if(this.escape) { s += ','+ref(this.escape); } s += '))'; } if(this.op === 'REGEXP') { s = 'alasql.stdfn.REGEXP_LIKE(' + leftJS() + ',' + rightJS() + ')'; } if(this.op === 'GLOB') { s = 'alasql.utils.glob(' + leftJS() + ',' + rightJS() + ')'; } if(this.op === 'BETWEEN' || this.op === 'NOT BETWEEN') { var left = leftJS() s = '' + '(' + ( (this.op === 'NOT BETWEEN') ? '!' : '') + '(' + '(' + ref(this.right1) + '<=' + left + ') && (' + left + '<=' + ref(this.right2) + ')' + ')' + ')'; } if(this.op === 'IN') { if(this.right instanceof yy.Select ) { s = '('; s += 'alasql.utils.flatArray(this.queriesfn['+(this.queriesidx)+'](params,null,'+context+'))'; s += '.indexOf('; s += leftJS()+')>-1)'; } else if(Array.isArray(this.right)) { s = '([' + this.right.map(ref).join(',') + '].indexOf(' + leftJS() + ')>-1)'; } else { s = '('+rightJS()+'.indexOf(' + leftJS()+')>-1)'; } } if(this.op === 'NOT IN') { if(this.right instanceof yy.Select ) { s = '('; //this.query.queriesdata['+this.queriesidx+'] s += 'alasql.utils.flatArray(this.queriesfn['+(this.queriesidx)+'](params,null,p))'; s +='.indexOf('; s += leftJS()+')<0)'; } else if(Array.isArray(this.right)) { s = '(['+this.right.map(re ...
...
* Changed order of LIMIT and ORDER BY processing
#### Version 0.0.4 (28.10.2014-29.10.2014)
* Added /test/main.html mocha browser tests
* Added PERFORMANCE.md and perf.html tests
* StringValue.toJS()
* Added callback to Database.exec
* Sieve of Eratosthenes example
* Remove generation of recs after select in case of group by (for memory optimization)
* Added conversion for type MONEY for INSERT statement
#### Versions 0.0.1 - 0.0.3 (25.10.2014-27.10.2014)
...
toString = function () { if(this.op === 'IN' || this.op === 'NOT IN') { return this.left.toString()+" "+this.op+" ("+this.right.toString()+")"; } if(this.allsome) { return this.left.toString()+" "+this.op+" "+this.allsome+' ('+this.right.toString()+')'; } if(this.op === '->' || this.op === '!') { var s = this.left.toString()+this.op; if(typeof this.right !== 'string' && typeof this.right !== 'number' ){ s += '('; } s += this.right.toString(); if(typeof this.right !== 'string' && typeof this.right !== 'number' ){ s += ')'; } return s; } return this.left.toString() + " " + this.op + " " + (this.allsome ? this.allsome+' ' : '') + this.right.toString(); }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
toType = function (tableid) { if(['-','*','/','%','^'].indexOf(this.op) >-1){ return 'number'; } if(['||'].indexOf(this.op) >-1){ return 'string'; } if(this.op === '+') { if(this.left.toType(tableid) === 'string' || this.right.toType(tableid) === 'string'){ return 'string'; } if(this.left.toType(tableid) === 'number' || this.right.toType(tableid) === 'number'){ return 'number'; } } if(['AND','OR','NOT','=','==','===', '!=','!==','!===','>','>=','<','<=', 'IN', 'NOT IN', 'LIKE', 'NOT LIKE', 'REGEXP', 'GLOB']. indexOf(this.op) >-1 ){ return 'boolean'; } if(this.op === 'BETWEEN' || this.op === 'NOT BETWEEN' || this.op === 'IS NULL' || this.op === 'IS NOT NULL'){ return 'boolean'; } if(this.allsome){ return 'boolean'; } if(!this.op){ return this.left.toType(); } return 'unknown'; }
...
if(['-','*','/','%','^'].indexOf(this.op) >-1){
return 'number';
}
if(['||'].indexOf(this.op) >-1){
return 'string';
}
if(this.op === '+') {
if(this.left.toType(tableid) === 'string' || this.right.toType(tableid) ===
x27;string'){
return 'string';
}
if(this.left.toType(tableid) === 'number' || this.right.toType(tableid) === 'number'){
return 'number';
}
}
if(['AND','OR','NOT','=','==','===', '!=','!==',
x27;!===','>','>=','<','<=', 'IN', 'NOT IN',
x27;LIKE', 'NOT LIKE', 'REGEXP', 'GLOB'].indexOf(this.op) >-1 ){
...
OrderExpression = function (params){ return yy.extend(this, params); }
...
}
if(args.length > 0) {
args.forEach(function(arg){
var expr = new yy.Column({columnid:arg});
if(typeof arg == 'function'){
expr = arg;
}
self.order.push(new yy.OrderExpression({expression: expr, direction:'ASC'
;}));
});
}
return self;
}
yy.Select.prototype.Top = function(topnum){
var self = this;
self.top = new yy.NumValue({value:topnum});
...
toString = function (dontas) { var s = this.expression.toString(dontas); if(this.order) { s += ' '+this.order.toString(); } if(this.nocase) { s += ' COLLATE NOCASE'; } return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
Over = function (params) { return yy.extend(this, params); }
...
this.$ = new yy.AggrValue({aggregatorid: $$[$0-5].toUpperCase(), expression: $$[$0-2], distinct:true, over:$$[$0]});
break;
case 329:
this.$ = new yy.AggrValue({aggregatorid: $$[$0-5].toUpperCase(), expression: $$[$0-2],
over:$$[$0]});
break;
case 331: case 332:
this.$ = new yy.Over(); yy.extend(this.$,$$[$0-1]);
break;
case 333:
this.$ = new yy.Over(); yy.extend(this.$,$$[$0-2]); yy.extend(this.$,$$[$0-1]);
break;
case 334:
this.$ = {partition:$$[$0]};
break;
...
toString = function () { var s = 'OVER ('; if(this.partition) { s += 'PARTITION BY '+this.partition.toString(); if(this.order) s+=' '; } if(this.order) { s += 'ORDER BY '+this.order.toString(); } s += ')'; return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
ParamValue = function (params) { return yy.extend(this, params); }
...
return;
}
if(arguments.length === 0) {
// Without arguments - Fluent interface
return new yy.Select({
columns:[new yy.Column({columnid:'*'})],
from: [new yy.ParamValue({param:0})]
});
} else if(arguments.length === 1){
// Access promise notation without using `.promise(...)`
if(sql.constructor === Array){
return alasql.promise(sql);
}
}
...
toJS = function () { if(typeof this.param === "string"){ return "params['"+this.param+"']"; } return "params["+this.param+"]"; }
...
* Changed order of LIMIT and ORDER BY processing
#### Version 0.0.4 (28.10.2014-29.10.2014)
* Added /test/main.html mocha browser tests
* Added PERFORMANCE.md and perf.html tests
* StringValue.toJS()
* Added callback to Database.exec
* Sieve of Eratosthenes example
* Remove generation of recs after select in case of group by (for memory optimization)
* Added conversion for type MONEY for INSERT statement
#### Versions 0.0.1 - 0.0.3 (25.10.2014-27.10.2014)
...
toString = function () { return '$'+this.param; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
Print = function (params) { return yy.extend(this, params); }
...
case 673:
this.$ = new yy.Break();
break;
case 674:
this.$ = new yy.BeginEnd({statements:$$[$0-1]});
break;
case 675:
this.$ = new yy.Print({exprs:$$[$0]});
break;
case 676:
this.$ = new yy.Print({select:$$[$0]});
break;
case 677:
this.$ = new yy.Require({paths:$$[$0]});
break;
...
execute = function (databaseid, params, cb) { var self = this; var res = 1; alasql.precompile(this,databaseid,params); /** @todo Change from alasql to this */ if(this.exprs && this.exprs.length >0) { var rs = this.exprs.map(function(expr){ var exprfn = new Function("params,alasql,p",'var y;return '+expr.toJS('({})','', null)).bind(self); var r = exprfn(params,alasql); return JSONtoString(r); }); console.log.apply(console,rs); } else if(this.select) { var r = this.select.execute(databaseid,params); console.log(JSONtoString(r)); } else { console.log(); } if(cb) res = cb(res); return res; }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { var s = 'PRINT'; if(this.statement) s += ' '+this.statement.toString(); return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
Reindex = function (params) { return yy.extend(this, params); }
...
case 771:
this.$ = 'UPDATE';
break;
case 772:
this.$ = new yy.DropTrigger({trigger:$$[$0]});
break;
case 773:
this.$ = new yy.Reindex({indexid:$$[$0]});
break;
case 1047: case 1067: case 1069: case 1071: case 1075: case 1077: case 1079: case 1081: case 1083: case 1085:
this.$ = [];
break;
case 1048: case 1062: case 1064: case 1068: case 1070: case 1072: case 1076: case 1078: case 1080: case 1082: case 1084: case 1086
:
$$[$0-1].push($$[$0]);
break;
...
execute = function (databaseid, params, cb) { // var self = this; var db = alasql.databases[databaseid]; var indexid = this.indexid; var tableid = db.indices[indexid]; var table = db.tables[tableid]; table.indexColumns(); var res = 1; if(cb) res = cb(res); return res; }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { var s = 'REINDEX '+this.indexid; return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
Require = function (params) { return yy.extend(this, params); }
...
case 675:
this.$ = new yy.Print({exprs:$$[$0]});
break;
case 676:
this.$ = new yy.Print({select:$$[$0]});
break;
case 677:
this.$ = new yy.Require({paths:$$[$0]});
break;
case 678:
this.$ = new yy.Require({plugins:$$[$0]});
break;
case 679: case 680:
this.$ = $$[$0].toUpperCase();
break;
...
execute = function (databaseid, params, cb) { var self = this; var res = 0; var ss = ''; if(this.paths && this.paths.length > 0) { this.paths.forEach(function(path){ loadFile(path.value, !!cb, function(data){ res++; ss += data; if(res<self.paths.length) return; new Function("params,alasql",ss)(params,alasql); if(cb) res = cb(res); }); }); } else if(this.plugins && this.plugins.length > 0) { this.plugins.forEach(function(plugin){ // If plugin is not loaded already if(!alasql.plugins[plugin]) { loadFile(alasql.path+'/alasql-'+plugin.toLowerCase()+'.js', !!cb, function(data){ // Execute all plugins at the same time res++; ss += data; if(res<self.plugins.length) return; new Function("params,alasql",ss)(params,alasql); alasql.plugins[plugin] = true; // Plugin is loaded if(cb) res = cb(res); }); } }); } else { if(cb) res = cb(res); } return res; }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { var s = 'REQUIRE'; if(this.paths && this.paths.length > 0) { s += this.paths.map(function(path){ return path.toString() }).join(','); } if(this.plugins && this.plugins.length > 0) { s += this.plugins.map(function(plugin){ return plugin.toUpperCase(); }).join(','); } return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
RollbackTransaction = function (params) { return yy.extend(this, params); }
...
case 664:
this.$ = false;
break;
case 665:
this.$ = new yy.CommitTransaction();
break;
case 666:
this.$ = new yy.RollbackTransaction();
break;
case 667:
this.$ = new yy.BeginTransaction();
break;
case 668:
this.$ = new yy.If({expression:$$[$0-2],thenstat:$$[$0-1], elsestat:$$[$0]});
if($$[$0-1].exists) this.$.exists = $$[$0-1].exists;
...
execute = function (databaseid, params, cb) { var res = 1; if(alasql.databases[databaseid].engineid) { return alasql.engines[alasql.databases[databaseid].engineid].rollback(databaseid, cb); } else { // alasql commit!!! } if(cb) cb(res); return res; }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { return 'ROLLBACK TRANSACTION'; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
Search = function (params) { return yy.extend(this, params); }
...
delete yy.exists;
if(yy.queries) this.$.queries = yy.queries;
delete yy.queries;
*/
break;
case 73:
this.$ = new yy.Search({selectors:$$[$0-2], from:$$[$0]});
yy.extend(this.$,$$[$0-1]);
break;
case 74:
this.$ = {pivot:{expr:$$[$0-5], columnid:$$[$0-3], inlist:$$[$0-2], as:$$[$0]}};
break;
case 75:
this.$ = {unpivot:{tocolumnid:$$[$0-8], forcolumnid:$$[$0-6], inlist:$$[$0-3], as:$$[$0]}};
...
compile = function (databaseid) { var dbid = databaseid; var self = this; var statement = function(params,cb){ var res; doSearch.bind(self)(dbid,params,function(data){ res = modify(statement.query,data); if(cb){ res = cb(res); } }); return res; }; statement.query = {}; return statement; }
...
You can also define your own aggregator functions (like your own `SUM(...)`). See more [in the wiki](https://github.com/agershun
/alasql/wiki/User-Defined-Functions)
### Compiled statements and functions
```js
var ins = alasql.compile('INSERT INTO one VALUES (?,?)');
ins(1,10);
ins(2,20);
```
See more [in the wiki](https://github.com/agershun/alasql/wiki/Compile)
...
toJS = function (context) { var s = 'this.queriesfn['+(this.queriesidx-1)+'](this.params,null,'+context+')'; // var s = ''; return s; }
...
* Changed order of LIMIT and ORDER BY processing
#### Version 0.0.4 (28.10.2014-29.10.2014)
* Added /test/main.html mocha browser tests
* Added PERFORMANCE.md and perf.html tests
* StringValue.toJS()
* Added callback to Database.exec
* Sieve of Eratosthenes example
* Remove generation of recs after select in case of group by (for memory optimization)
* Added conversion for type MONEY for INSERT statement
#### Versions 0.0.1 - 0.0.3 (25.10.2014-27.10.2014)
...
toString = function () { var s = 'SEARCH' + ' '; if (this.selectors){ s += this.selectors.toString(); } if (this.from){ s += 'FROM' + ' ' + this.from.toString(); } return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
Select = function (params) { return yy.extend(this, params); }
...
alasql.buffer[id] = cb;
alasql.webworker.postMessage({id:id,sql:sql,params:params});
return;
}
if(arguments.length === 0) {
// Without arguments - Fluent interface
return new yy.Select({
columns:[new yy.Column({columnid:'*'})],
from: [new yy.ParamValue({param:0})]
});
} else if(arguments.length === 1){
// Access promise notation without using `.promise(...)`
if(sql.constructor === Array){
return alasql.promise(sql);
...
From = function (tableid){ var self = this; if(!self.from) self.from = []; if(Array.isArray(tableid)) { var pari = 0; if(self.preparams) { pari = self.preparams.length; } else { self.preparams = []; } self.preparams.push(tableid); self.from.push(new yy.ParamValue({param:pari})); } else if(typeof tableid =="string") { self.from.push(new yy.Table({tableid:tableid})); } else { throw new Error('Unknown arguments in From() function') } return self; }
...
});
Call with scope for subquery (to pass common values):
var scope = {one:{a:2,b;20}}
alasql('SELECT * FROM ? two WHERE two.a = one.a',[data],null,scope);
Call for fluent interface with data object:
alasql(data).Where(function(x){return x.a == 10}).exec();
Call for fluent interface without data object:
alasql().From(data).Where(function(x){return x.a == 10}).exec();
*/
var alasql = function(sql, params, cb, scope) {
params = params||[];
if(typeof importScripts !== 'function' && alasql.webworker) {
...
GroupBy = function (){ var self = this; var agrs = []; if(arguments.length > 1) { args = Array.prototype.slice.call(arguments);; } else if(arguments.length == 1) { if(Array.isArray(arguments[0])) { args = arguments[0]; } else { args = [arguments[0]]; } } else { throw new Error('Wrong number of arguments of Select() function'); } self.group = []; args.forEach(function(arg){ var expr = new yy.Column({columnid:arg}); self.group.push(expr); }); return self; }
n/a
OrderBy = function (){ var self = this; var agrs = []; self.order = []; if(arguments.length == 0) { args = ["_"]; } else if(arguments.length > 1) { args = Array.prototype.slice.call(arguments);; } else if(arguments.length == 1) { if(Array.isArray(arguments[0])) { args = arguments[0]; } else { args = [arguments[0]]; } } else { throw new Error('Wrong number of arguments of Select() function'); } if(args.length > 0) { args.forEach(function(arg){ var expr = new yy.Column({columnid:arg}); if(typeof arg == 'function'){ expr = arg; } self.order.push(new yy.OrderExpression({expression: expr, direction:'ASC'})); }); } return self; }
n/a
Select = function (){ var self = this; var agrs = []; if(arguments.length > 1) { args = Array.prototype.slice.call(arguments);; } else if(arguments.length == 1) { if(Array.isArray(arguments[0])) { args = arguments[0]; } else { args = [arguments[0]]; } } else { throw new Error('Wrong number of arguments of Select() function'); } self.columns = []; args.forEach(function(arg){ if(typeof arg == "string") { self.columns.push(new yy.Column({columnid: arg})); } else if(typeof arg == "function") { var pari = 0; if(self.preparams) { pari = self.preparams.length; } else { self.preparams = []; } self.preparams.push(arg); self.columns.push(new yy.Column({columnid: "*", func:arg, param:pari})); } else { // Unknown type } }); return self; }
...
alasql.buffer[id] = cb;
alasql.webworker.postMessage({id:id,sql:sql,params:params});
return;
}
if(arguments.length === 0) {
// Without arguments - Fluent interface
return new yy.Select({
columns:[new yy.Column({columnid:'*'})],
from: [new yy.ParamValue({param:0})]
});
} else if(arguments.length === 1){
// Access promise notation without using `.promise(...)`
if(sql.constructor === Array){
return alasql.promise(sql);
...
Top = function (topnum){ var self = this; self.top = new yy.NumValue({value:topnum}); return self; }
n/a
Where = function (expr){ var self = this; if(typeof expr == 'function' ) { self.where = expr; } return self; }
...
alasql('SELECT * FROM ?',[data],function(res){
console.log(data);
});
Call with scope for subquery (to pass common values):
var scope = {one:{a:2,b;20}}
alasql('SELECT * FROM ? two WHERE two.a = one.a',[data],null,scope);
Call for fluent interface with data object:
alasql(data).Where(function(x){return x.a == 10}).exec();
Call for fluent interface without data object:
alasql().From(data).Where(function(x){return x.a == 10}).exec();
*/
var alasql = function(sql, params, cb, scope) {
params = params||[];
...
compile = function (databaseid, params) { var db = alasql.databases[databaseid]; // Create variable for query var query = new Query(); // Array with columns to be removed query.removeKeys = []; query.aggrKeys = []; query.explain = this.explain; // Explain query.explaination = []; query.explid = 1; query.modifier = this.modifier; query.database = db; // 0. Precompile whereexists this.compileWhereExists(query); // 0. Precompile queries for IN, NOT IN, ANY and ALL operators this.compileQueries(query); query.defcols = this.compileDefCols(query, databaseid); // 1. Compile FROM clause query.fromfn = this.compileFrom(query); // 2. Compile JOIN clauses if(this.joins){ this.compileJoins(query); } // todo?: 3. Compile SELECT clause // For ROWNUM() query.rownums = []; this.compileSelectGroup0(query); if(this.group || query.selectGroup.length>0) { query.selectgfns = this.compileSelectGroup1(query); } else { query.selectfns = this.compileSelect1(query, params); } // Remove columns clause this.compileRemoveColumns(query); // 5. Optimize WHERE and JOINS if(this.where){ this.compileWhereJoins(query); } // 4. Compile WHERE clause query.wherefn = this.compileWhere(query); // 6. Compile GROUP BY if(this.group || query.selectGroup.length>0){ query.groupfn = this.compileGroup(query); } // 6. Compile HAVING if(this.having){ query.havingfn = this.compileHaving(query); } // 8. Compile ORDER BY clause if(this.order){ query.orderfn = this.compileOrder(query); } if(this.group || query.selectGroup.length>0) { query.selectgfn = this.compileSelectGroup2(query); } else { query.selectfn = this.compileSelect2(query); } // 7. Compile DISTINCT, LIMIT and OFFSET query.distinct = this.distinct; // 9. Compile PIVOT clause if(this.pivot) query.pivotfn = this.compilePivot(query); if(this.unpivot) query.pivotfn = this.compileUnpivot(query); // 10. Compile TOP/LIMIT/OFFSET/FETCH cleuse if(this.top) { query.limit = this.top.value; } else if(this.limit) { query.limit = this.limit.value; if(this.offset) { query.offset = this.offset.value; } } query.percent = this.percent; // 9. Compile ordering function for UNION and UNIONALL query.corresponding = this.corresponding; // If CORRESPONDING flag exists if(this.union) { query.unionfn = this.union.compile(databaseid); if(this.union.order) { query.orderfn = this.union.compileOrder(query); } else { query.orderfn = null; } } else if(this.unionall) { query.unionallfn = this.unionall.compile(databaseid); if(this.unionall.order) { query.orderfn = this.unionall.compileOrder(query); } else { query.orderfn = null; } } else if(this.except) { query.exceptfn = this.except.compile(databaseid); if(this.except.order) { query.orderfn = this.except.compileOrder(query); } else { query.orderfn = null; } } else if(this.intersect) { query.intersectfn = this.intersect.compile(databaseid); if(this.intersect.order) { query.intersectfn = this.intersect.compileOrder(query); } else { query.orderfn = null; } } // SELECT INTO if(this.into) { if(this.into instanceof yy.Table) { // // Save into the table in database // if(alasql.options.autocommit && alasql.databases[this.into.databaseid||databaseid].engineid) { // For external database when AUTOCOMMIT is ONs query.intoallfns = 'return alasql.engines["'+alasql.databases[this.into.databaseid||databaseid].engineid+'"]'+ '.intoTable("'+(this.into.databaseid||databaseid)+'","'+this.into.tableid+'",this.data, columns, cb);'; } else { // Into AlaSQL tables query.intofns = 'alasql.databases[\''+(this.into.databaseid||databaseid)+'\'].tables'+ '[\''+this.into.tableid+'\'].data.push(r);'; } } else if(this.into instanceof yy.VarValue) { // // Save into local variable // SELECT * INTO @VAR1 FROM ? // query.intoallfns = 'alasql.vars["'+this.into.variable+'" ...
...
You can also define your own aggregator functions (like your own `SUM(...)`). See more [in the wiki](https://github.com/agershun
/alasql/wiki/User-Defined-Functions)
### Compiled statements and functions
```js
var ins = alasql.compile('INSERT INTO one VALUES (?,?)');
ins(1,10);
ins(2,20);
```
See more [in the wiki](https://github.com/agershun/alasql/wiki/Compile)
...
compileDefCols = function (query, databaseid) { var defcols = {'.':{}}; if(this.from) { this.from.forEach(function(fr){ defcols['.'][fr.as || fr.tableid] = true; if(fr instanceof yy.Table) { var alias = fr.as || fr.tableid; var table = alasql.databases[fr.databaseid || databaseid].tables[fr.tableid]; if(undefined === table){ throw new Error("Table does not exists: "+fr.tableid);; } if(table.columns) { table.columns.forEach(function(col){ if(defcols[col.columnid]) { defcols[col.columnid] = '-'; // Ambigous } else { defcols[col.columnid] = alias; } }); } } else if(fr instanceof yy.Select) { } else if(fr instanceof yy.Search) { } else if(fr instanceof yy.ParamValue) { } else if(fr instanceof yy.VarValue) { } else if(fr instanceof yy.FuncValue) { } else if(fr instanceof yy.FromData) { } else if(fr instanceof yy.Json) { } else if(fr.inserted) { } else { throw new Error('Unknown type of FROM clause'); }; }); }; if(this.joins) { this.joins.forEach(function(jn){ defcols['.'][jn.as || jn.table.tableid] = true; if(jn.table) { var alias = jn.table.tableid; if(jn.as) alias = jn.as; var alias = jn.as || jn.table.tableid; var table = alasql.databases[jn.table.databaseid || databaseid].tables[jn.table.tableid]; if(table.columns) { table.columns.forEach(function(col){ if(defcols[col.columnid]) { defcols[col.columnid] = '-'; // Ambigous } else { defcols[col.columnid] = alias; } }); } } else if(jn.select) { } else if(jn.param) { } else if(jn.func) { } else { throw new Error('Unknown type of FROM clause'); }; }); }; // for(var k in defcols) { // if(defcols[k] == '-') defcols[k] = undefined; // } return defcols; }
...
query.explid = 1;
query.modifier = this.modifier;
query.database = db;
// 0. Precompile whereexists
this.compileWhereExists(query);
// 0. Precompile queries for IN, NOT IN, ANY and ALL operators
this.compileQueries(query);
query.defcols = this.compileDefCols(query, databaseid);
// 1. Compile FROM clause
query.fromfn = this.compileFrom(query);
// 2. Compile JOIN clauses
if(this.joins){
this.compileJoins(query);
}
// todo?: 3. Compile SELECT clause
...
compileFrom = function (query) { var self = this; query.sources = []; // var tableid = this.from[0].tableid; // var as = ''; // if(self.from[0].as) as = this.from[0].as; query.aliases = {}; if(!self.from) return; self.from.forEach(function(tq){ var alias = tq.as || tq.tableid; if(tq instanceof yy.Table) { query.aliases[alias] = {tableid: tq.tableid, databaseid: tq.databaseid || query.database.databaseid, type:'table'}; } else if(tq instanceof yy.Select) { query.aliases[alias] = {type:'subquery'}; } else if(tq instanceof yy.Search) { query.aliases[alias] = {type:'subsearch'}; } else if(tq instanceof yy.ParamValue) { query.aliases[alias] = {type:'paramvalue'}; } else if(tq instanceof yy.FuncValue) { query.aliases[alias] = {type:'funcvalue'}; } else if(tq instanceof yy.VarValue) { query.aliases[alias] = {type:'varvalue'}; } else if(tq instanceof yy.FromData) { query.aliases[alias] = {type:'fromdata'}; } else if(tq instanceof yy.Json) { query.aliases[alias] = {type:'json'}; } else if(tq.inserted) { query.aliases[alias] = {type:'inserted'}; } else { throw new Error('Wrong table at FROM'); } var source = { alias: alias, databaseid: tq.databaseid || query.database.databaseid, tableid: tq.tableid, joinmode: 'INNER', onmiddlefn: returnTrue, srcwherefns: '', // for optimization srcwherefn: returnTrue, }; if(tq instanceof yy.Table) { // Get columns from table source.columns = alasql.databases[source.databaseid].tables[source.tableid].columns; if(alasql.options.autocommit && alasql.databases[source.databaseid].engineid && !alasql.databases[source.databaseid].tables[source.tableid].view ) { // TODO -- make view for external engine source.datafn = function(query,params,cb,idx, alasql) { return alasql.engines[alasql.databases[source.databaseid].engineid].fromTable( source.databaseid, source.tableid,cb,idx,query); } } else if(alasql.databases[source.databaseid].tables[source.tableid].view){ source.datafn = function(query,params,cb,idx, alasql) { var res = alasql.databases[source.databaseid].tables[source.tableid].select(params); if(cb) res = cb(res,idx,query); return res; } } else { source.datafn = function(query,params,cb,idx, alasql) { /* */ var res = alasql.databases[source.databaseid].tables[source.tableid].data; if(cb) res = cb(res,idx,query); return res; }; } } else if(tq instanceof yy.Select) { source.subquery = tq.compile(query.database.databaseid); if(typeof source.subquery.query.modifier == 'undefined') { source.subquery.query.modifier = 'RECORDSET'; // Subqueries always return recordsets } source.columns = source.subquery.query.columns; source.datafn = function(query, params, cb, idx, alasql) { var res; source.subquery(query.params, function(data){ res = data.data; if(cb) res = cb(res,idx,query); return res; }); return res; } } else if(tq instanceof yy.Search) { source.subsearch = tq; source.columns = []; source.datafn = function(query, params, cb, idx, alasql) { var res; source.subsearch.execute(query.database.databaseid,query.params,function(data){ res = data; if(cb) res = cb(res,idx,query); return res; }); return res; } } else if(tq instanceof yy.ParamValue) { var ps = "var res = alasql.prepareFromData(params['"+tq.param+"']"; if(tq.array) ps+=",true"; ps += ");if(cb)res=cb(res,idx,query);return res" source.datafn = new Function('query,params,cb,idx,alasql',ps); } else if(tq.inserted) { var ps = "var res = alasql.prepareFromData(alasql.inserted"; if(tq.array) ps+=",true"; ps += ");if(cb)res=cb(res,idx,query);return res" source.datafn = new Function('query,params,cb,idx,alasql',ps); } else if(tq instanceof yy.Json) { var ps = "var res = alasql.prepareFromData("+tq.toJS(); i ...
...
query.database = db;
// 0. Precompile whereexists
this.compileWhereExists(query);
// 0. Precompile queries for IN, NOT IN, ANY and ALL operators
this.compileQueries(query);
query.defcols = this.compileDefCols(query, databaseid);
// 1. Compile FROM clause
query.fromfn = this.compileFrom(query);
// 2. Compile JOIN clauses
if(this.joins){
this.compileJoins(query);
}
// todo?: 3. Compile SELECT clause
// For ROWNUM()
query.rownums = [];
...
compileGroup = function (query) { if(query.sources.length > 0) { var tableid = query.sources[0].alias; } else { // If SELECT contains group aggregators without source tables var tableid = ''; } var defcols = query.defcols; var allgroup = [[]]; if(this.group) { allgroup = decartes(this.group,query); } // Prepare groups //var allgroup = [['a'], ['a','b'], ['a', 'b', 'c']]; // Union all arrays to get a maximum var allgroups = []; allgroup.forEach(function(a){ allgroups = arrayUnion(allgroups, a); }); query.allgroups = allgroups; query.ingroup = []; // Create negative array var s = ''; // s+= query.selectfns; allgroup.forEach(function(agroup) { // Start of group function s += 'var g=this.xgroups['; // var gcols = this.group.map(function(col){return col.columnid}); // Group fields with r // Array with group columns from record var rg = agroup.map(function(col2){ var columnid = col2.split('\t')[0]; var coljs = col2.split('\t')[1]; // Check, if aggregator exists but GROUP BY is not exists if(columnid === ''){ return '1'; // Create fictive groupping column for fictive GROUP BY } query.ingroup.push(columnid); return coljs; }); if(rg.length === 0){ rg = ["''"]; } s += rg.join('+"`"+'); s += '];if(!g) {this.groups.push((g=this.xgroups['; s += rg.join('+"`"+'); s += '] = {'; s += agroup.map(function(col2){ var columnid = col2.split('\t')[0]; var coljs = col2.split('\t')[1]; if(columnid === ''){ return ''; } return "'"+columnid+"':"+coljs+","; }).join(''); var neggroup = arrayDiff(allgroups,agroup); s += neggroup.map(function(col2){ var columnid = col2.split('\t')[0]; // var coljs = col2.split('\t')[1] return "'"+columnid+"':null,"; }).join(''); var aft = '', aft2=''; if(typeof query.groupStar !== 'undefined') { aft2 += 'for(var f in p[\''+query.groupStar+'\']) {g[f]=p[\''+query.groupStar+'\'][f];};'; }; /* */ s += query.selectGroup.map(function(col){ var colexp = col.expression.toJS("p",tableid,defcols); var colas = col.nick; // if(typeof colas == 'undefined') { // if(col instanceof yy.Column) colas = col.columnid; // else colas = col.toString(); // }; if (col instanceof yy.AggrValue) { if(col.distinct) { aft += ',g[\'$$_VALUES_'+colas+'\']={},g[\'$$_VALUES_'+colas+'\']['+colexp+']=true'; } if (col.aggregatorid === 'SUM') { return "'"+colas+'\':('+colexp+')||0,'; } else if ( col.aggregatorid === 'MIN' || col.aggregatorid === 'MAX' || col.aggregatorid === 'FIRST' || col.aggregatorid === 'LAST' // || col.aggregatorid == 'AVG' ){ return "'"+colas+'\':'+colexp+','; //f.field.arguments[0].toJS(); } else if(col.aggregatorid === 'ARRAY') { return "'"+colas+'\':['+colexp+'],'; } else if(col.aggregatorid === 'COUNT') { if(col.expression.columnid === '*') { return "'"+colas+'\':1,'; } else { return "'"+colas+'\':(typeof '+colexp+' != "undefined")?1:0,'; } } else if(col.aggregatorid === 'AVG') { query.removeKeys.push('_SUM_'+colas); query.removeKeys.push('_COUNT_'+colas); return '' + "'" + colas + '\':' + colexp + ',\'_SUM_' + colas+'\':(' + colexp + ')||0,\'_COUNT_' + colas + '\':(typeof ' + colexp+' != "undefined")?1:0,'; } else if(col.aggregatorid === 'AGGR') { aft += ',g[\''+colas+'\']='+col.expression.toJS('g',-1); return ''; } else if(col.aggregatorid === 'REDUCE') { query.aggrKeys.push(col); return '\''+colas+'\':alasql.aggr[\''+col.funcid+'\']('+colexp+',undefined,1),'; } return ''; } return ''; }).join(''); s += '}'+aft+',g));'+aft2+'} else {'; /* // var neggroup = arrayDiff(allgroups,agroup); // s += neggroup.map(function(columnid){ // return "g['"+columnid+"']=null;"; // }).join(''); */ s += query.selectGroup.map(functi ...
...
if(this.where){
this.compileWhereJoins(query);
}
// 4. Compile WHERE clause
query.wherefn = this.compileWhere(query);
// 6. Compile GROUP BY
if(this.group || query.selectGroup.length>0){
query.groupfn = this.compileGroup(query);
}
// 6. Compile HAVING
if(this.having){
query.havingfn = this.compileHaving(query);
}
// 8. Compile ORDER BY clause
if(this.order){
...
compileHaving = function (query) { if(this.having) { s = this.having.toJS('g',-1); query.havingfns = s; return new Function('g,params,alasql','var y;return '+s); } else return function(){return true}; }
...
query.wherefn = this.compileWhere(query);
// 6. Compile GROUP BY
if(this.group || query.selectGroup.length>0){
query.groupfn = this.compileGroup(query);
}
// 6. Compile HAVING
if(this.having){
query.havingfn = this.compileHaving(query);
}
// 8. Compile ORDER BY clause
if(this.order){
query.orderfn = this.compileOrder(query);
}
if(this.group || query.selectGroup.length>0) {
query.selectgfn = this.compileSelectGroup2(query);
...
compileJoins = function (query) { // debugger; var self = this; this.joins.forEach(function(jn){ // Test CROSS-JOIN if(jn.joinmode == "CROSS") { if(jn.using || jn.on) { throw new Error('CROSS JOIN cannot have USING or ON clauses'); } else { jn.joinmode == "INNER"; } } var source; var tq; if(jn instanceof yy.Apply) { source = { alias: jn.as, applymode: jn.applymode, onmiddlefn: returnTrue, srcwherefns: '', // for optimization srcwherefn: returnTrue, columns: [] // TODO check this }; source.applyselect = jn.select.compile(query.database.databaseid); source.columns = source.applyselect.query.columns; source.datafn = function(query,params,cb,idx, alasql) { var res; if(cb) res = cb(res,idx,query); return res; } query.sources.push(source); } else { if(jn.table) { tq = jn.table; source = { alias: jn.as||tq.tableid, databaseid: tq.databaseid || query.database.databaseid, tableid: tq.tableid, joinmode: jn.joinmode, onmiddlefn: returnTrue, srcwherefns: '', // for optimization srcwherefn: returnTrue, columns: [] }; // if(!alasql.databases[source.databaseid].tables[source.tableid]) { throw new Error('Table \''+source.tableid+ '\' is not exists in database \''+source.databaseid)+'\''; }; source.columns = alasql.databases[source.databaseid].tables[source.tableid].columns; // source.data = query.database.tables[source.tableid].data; if(alasql.options.autocommit && alasql.databases[source.databaseid].engineid) { source.datafn = function(query,params, cb, idx, alasql) { return alasql.engines[alasql.databases[source.databaseid].engineid].fromTable( source.databaseid, source.tableid, cb, idx,query); } } else if(alasql.databases[source.databaseid].tables[source.tableid].view){ source.datafn = function(query,params,cb,idx, alasql) { var res = alasql.databases[source.databaseid].tables[source.tableid].select(params); if(cb) res = cb(res,idx,query); return res; } } else { source.datafn = function(query,params,cb, idx, alasql) { var res = alasql.databases[source.databaseid].tables[source.tableid].data; if(cb) res = cb(res,idx,query); return res; } }; query.aliases[source.alias] = {tableid: tq.tableid, databaseid: tq.databaseid || query.database.databaseid}; } else if(jn.select) { var tq = jn.select; source = { alias: jn.as, joinmode: jn.joinmode, onmiddlefn: returnTrue, srcwherefns: '', // for optimization srcwherefn: returnTrue, columns: [] }; source.subquery = tq.compile(query.database.databaseid); if(typeof source.subquery.query.modifier == 'undefined') { source.subquery.query.modifier = 'RECORDSET'; // Subqueries always return recordsets } source.columns = source.subquery.query.columns; source.datafn = function(query, params, cb, idx, alasql) { return source.subquery(query.params, null, cb, idx).data; } // } else { // source.datafn = function(query, params, cb, idx, alasql) { // return source.subquery(query.params, null, cb, idx); // } // } query.aliases[source.alias] = {type:'subquery'}; } else if(jn.param) { source = { alias: jn.as, joinmode: jn.joinmode, onmiddlefn: returnTrue, srcwherefns: '', // for optimization srcwherefn: returnTrue }; // source.data = ; var jnparam = jn.param.param; var ps = "var res=alasql.prepareFromData(params['"+jnparam+"']"; if(jn.array) ps += ",true"; ps += ");if(cb)res=cb(res, idx, query);return res"; source.datafn = new Function('query,params,cb,idx, alasql',ps); query.aliases[source.alias] = {type:'paramvalue'}; } else if(jn.variable) { source = { alias: jn.as, joinmode: jn.joinmode, onmiddlefn: returnTrue, srcwherefns: '', // for optimization srcwherefn: returnTrue }; // s ...
...
// 0. Precompile queries for IN, NOT IN, ANY and ALL operators
this.compileQueries(query);
query.defcols = this.compileDefCols(query, databaseid);
// 1. Compile FROM clause
query.fromfn = this.compileFrom(query);
// 2. Compile JOIN clauses
if(this.joins){
this.compileJoins(query);
}
// todo?: 3. Compile SELECT clause
// For ROWNUM()
query.rownums = [];
this.compileSelectGroup0(query);
if(this.group || query.selectGroup.length>0) {
query.selectgfns = this.compileSelectGroup1(query);
...
compileOrder = function (query) {
var self = this;
self.orderColumns = [];
if(this.order) {
if(this.order && this.order.length == 1 && this.order[0].expression
&& typeof this.order[0].expression == "function") {
var func = this.order[0].expression;
return function(a,b){
var ra = func(a),rb = func(b);
if(ra>rb) return 1;
if(ra==rb) return 0;
return -1;
}
};
var s = '';
var sk = '';
this.order.forEach(function(ord,idx){
if(ord.expression instanceof yy.NumValue) {
var v = self.columns[ord.expression.value-1];
} else {
var v = ord.expression;
}
self.orderColumns.push(v);
var key = '$$$'+idx;
// Date conversion
var dg = '';
//if(alasql.options.valueof)
if(ord.expression instanceof yy.Column) {
var columnid = ord.expression.columnid;
if(query.xcolumns[columnid]) {
var dbtypeid = query.xcolumns[columnid].dbtypeid;
if( dbtypeid == 'DATE' || dbtypeid == 'DATETIME' || dbtypeid == 'DATETIME2') dg = '.valueOf()';
// TODO Add other types mapping
} else {
if(alasql.options.valueof) dg = '.valueOf()'; // TODO Check
}
}
// COLLATE NOCASE
if(ord.nocase) dg += '.toUpperCase()';
s += "if((a['"+key+"']||'')"+dg+(ord.direction == 'ASC'?'>':"<")+"(b['"+key+"']||'')"+dg+')return 1;';
s += "if((a['"+key+"']||'')"+dg+"==(b['"+key+"']||'')"+dg+'){';
/*
if(false) {
if(ord.expression instanceof yy.NumValue) {
ord.expression = self.columns[ord.expression.value-1];
ord.expression = new yy.Column({columnid:ord.expression.nick});
};
if(ord.expression instanceof yy.Column) {
var columnid = ord.expression.columnid;
if(query.xcolumns[columnid]) {
var dbtypeid = query.xcolumns[columnid].dbtypeid;
if( dbtypeid == 'DATE' || dbtypeid == 'DATETIME' || dbtypeid == 'DATETIME2') dg = '.valueOf()';
// TODO Add other types mapping
} else {
if(alasql.options.valueof) dg = '.valueOf()'; // TODO Check
}
// COLLATE NOCASE
if(ord.nocase) dg += '.toUpperCase()';
s += 'if((a[\''+columnid+"']||'')"+dg+(ord.direction == 'ASC'?'>':'<')+'(b[\''+columnid+"']||'')"+dg+')return 1;';
s += 'if((a[\''+columnid+"']||'')"+dg+'==(b[\''+columnid+"']||'')"+dg+'){';
} else {
dg = '.valueOf()';
// COLLATE NOCASE
if(ord.nocase) dg += '.toUpperCase()';
s += 'if(('+ord.toJS('a','')+"||'')"+dg+(ord.direction == 'ASC'?'>(':'<(')+ord.toJS('b','')+"||'')"+dg+')return 1;';
s += 'if(('+ord.toJS('a','')+"||'')"+dg+'==('+ord.toJS('b','')+"||'')"+dg+'){';
}
// TODO Add date comparision
}
*/
sk += '}';
});
s += 'return 0;';
s += sk+'return -1';
query.orderfns = s;
return new Function('a,b','var y;'+s);
};
}
...
}
// 6. Compile HAVING
if(this.having){
query.havingfn = this.compileHaving(query);
}
// 8. Compile ORDER BY clause
if(this.order){
query.orderfn = this.compileOrder(query);
}
if(this.group || query.selectGroup.length>0) {
query.selectgfn = this.compileSelectGroup2(query);
} else {
query.selectfn = this.compileSelect2(query);
}
// 7. Compile DISTINCT, LIMIT and OFFSET
...
compilePivot = function (query) {
var self = this;
/** @type {string} Main pivoting column */
var columnid = self.pivot.columnid;
var exprcolid = self.pivot.expr.expression.columnid;
var aggr = self.pivot.expr.aggregatorid;
var inlist = self.pivot.inlist;
if(inlist) {
inlist = inlist.map(function(l){return l.expr.columnid});
}
// Function for PIVOT post production
return function() {
var query = this;
var cols = query.columns.filter(function(col){
return (col.columnid != columnid) && (col.columnid != exprcolid);
}).map(function(col){
return col.columnid;
});
var newcols = [];
var gnewcols = {};
var gr = {};
var ga = {};
var data = [];
query.data.forEach(function(d){
if(!inlist || inlist.indexOf(d[columnid])>-1 ) {
var gx = cols.map(function(colid){return d[colid]}).join('`');
var g = gr[gx];
if(!g) {
g = {};
gr[gx] = g;
data.push(g);
cols.forEach(function(colid){
g[colid] = d[colid];
});
};
if(!ga[gx]) {
ga[gx] = {};
}
if(ga[gx][d[columnid]]) {
ga[gx][d[columnid]]++;
} else {
ga[gx][d[columnid]] = 1;
}
if(!gnewcols[d[columnid]]) {
gnewcols[d[columnid]] = true;
newcols.push(d[columnid]);
};
if(aggr=='SUM' || aggr=='AVG' ) {
if(typeof g[d[columnid]] == 'undefined') g[d[columnid]] = 0;
g[d[columnid]] += d[exprcolid];
} else if(aggr=='COUNT') {
if(typeof g[d[columnid]] == 'undefined') g[d[columnid]] = 0;
g[d[columnid]]++;
} else if(aggr=='MIN') {
if(typeof g[d[columnid]] == 'undefined') g[d[columnid]] = Infinity;
if(d[exprcolid] < g[d[columnid]]) g[d[columnid]] = d[exprcolid];
} else if(aggr=='MAX') {
if(typeof g[d[columnid]] == 'undefined') g[d[columnid]] = -Infinity;
if(d[exprcolid] > g[d[columnid]]) g[d[columnid]] = d[exprcolid];
} else if(aggr=='FIRST') {
if(typeof g[d[columnid]] == 'undefined') g[d[columnid]] = d[exprcolid];
} else if(aggr=='LAST') {
g[d[columnid]] = d[exprcolid];
} else if(alasql.aggr[aggr]) { // Custom aggregator
alasql.aggr[aggr](g[d[columnid]],d[exprcolid]);
} else {
throw new Error('Wrong aggregator in PIVOT clause');
}
}
});
if(aggr=='AVG') {
for(var gx in gr){
var d = gr[gx];
for(var colid in d) {
if((cols.indexOf(colid) == -1) && (colid != exprcolid)) {
d[colid] = d[colid]/ga[gx][colid];
}
}
};
};
// columns
query.data = data;
if(inlist) newcols = inlist;
var ncol = query.columns.filter(function(col){return col.columnid == exprcolid})[0];
query.columns = query.columns.filter(function(col){
return !(col.columnid == columnid || col.columnid == exprcolid);
});
newcols.forEach(function(colid){
var nc = cloneDeep(ncol);
nc.columnid = colid;
query.columns.push(nc);
});
};
}
...
query.selectgfn = this.compileSelectGroup2(query);
} else {
query.selectfn = this.compileSelect2(query);
}
// 7. Compile DISTINCT, LIMIT and OFFSET
query.distinct = this.distinct;
// 9. Compile PIVOT clause
if(this.pivot) query.pivotfn = this.compilePivot(query);
if(this.unpivot) query.pivotfn = this.compileUnpivot(query);
// 10. Compile TOP/LIMIT/OFFSET/FETCH cleuse
if(this.top) {
query.limit = this.top.value;
} else if(this.limit) {
query.limit = this.limit.value;
if(this.offset) {
...
compileQueries = function (query) { if(!this.queries) return; query.queriesfn = this.queries.map(function(q) { var nq = q.compile(query.database.databaseid); // if(!nq.query) nq.query = {}; nq.query.modifier = 'RECORDSET'; return nq; }); }
...
query.explaination = [];
query.explid = 1;
query.modifier = this.modifier;
query.database = db;
// 0. Precompile whereexists
this.compileWhereExists(query);
// 0. Precompile queries for IN, NOT IN, ANY and ALL operators
this.compileQueries(query);
query.defcols = this.compileDefCols(query, databaseid);
// 1. Compile FROM clause
query.fromfn = this.compileFrom(query);
// 2. Compile JOIN clauses
if(this.joins){
this.compileJoins(query);
}
...
compileRemoveColumns = function (query) { var self = this; if(typeof this.removecolumns !== 'undefined') { query.removeKeys = query.removeKeys.concat( this.removecolumns.filter(function (column) { return (typeof column.like === 'undefined'); }).map(function(column){return column.columnid})); query.removeLikeKeys = this.removecolumns.filter(function (column) { return (typeof column.like !== 'undefined'); }).map(function(column){ return column.like.value; }); } }
...
this.compileSelectGroup0(query);
if(this.group || query.selectGroup.length>0) {
query.selectgfns = this.compileSelectGroup1(query);
} else {
query.selectfns = this.compileSelect1(query, params);
}
// Remove columns clause
this.compileRemoveColumns(query);
// 5. Optimize WHERE and JOINS
if(this.where){
this.compileWhereJoins(query);
}
// 4. Compile WHERE clause
query.wherefn = this.compileWhere(query);
// 6. Compile GROUP BY
...
compileSelect1 = function (query, params) { var self = this; query.columns = []; query.xcolumns = {}; query.selectColumns = {}; query.dirtyColumns = false; var s = 'var r={'; var sp = ''; var ss = []; this.columns.forEach(function(col){ if(col instanceof yy.Column) { if(col.columnid === '*') { if(col.func) { sp += 'r=params[\''+col.param+'\'](p[\''+query.sources[0].alias+'\'],p,params,alasql);'; } else if(col.tableid) { //Copy all var ret = compileSelectStar(query, col.tableid, false); if(ret.s){ ss = ss.concat(ret.s); } sp += ret.sp; } else { for(var alias in query.aliases) { var ret = compileSelectStar(query, alias, true); //query.aliases[alias].tableid); if(ret.s) { ss = ss.concat(ret.s); } sp += ret.sp; } // TODO Remove these lines // In case of no information // sp += 'for(var k1 in p){var w=p[k1];'+ // 'for(k2 in w) {r[k2]=w[k2]}}' } } else { // If field, otherwise - expression var tbid = col.tableid; var dbid = col.databaseid || query.sources[0].databaseid || query.database.databaseid; if(!tbid) tbid = query.defcols[col.columnid]; if(!tbid) tbid = query.defaultTableid; if(col.columnid !== '_') { if(false && tbid && !query.defcols['.'][col.tableid] && !query.defcols[col.columnid]) { ss.push('\''+escapeq(col.as || col.columnid)+'\':p[\''+(query.defaultTableid)+'\'][\''+(col.tableid)+'\'][\''+col.columnid +'\']'); } else { // workaround for multisheet xlsx export with custom COLUMNS var isMultisheetParam = params && params.length > 1 && Array.isArray(params[0]) && params[0].length >= 1 && params[0][0].hasOwnProperty('sheetid'); if (isMultisheetParam) { sp = 'var r={};var w=p[\"' + tbid + '\"];' + 'var cols=[' + self.columns.map(function(col) { return "'" + col.columnid + "'"; }) .join(',') + '];var colas=['+ self.columns.map(function(col) { return "'" + (col.as || col.columnid) + "'"; }) .join(',') + '];' + "for (var i=0;i<Object.keys(p['" + tbid + "']).length;i++)" + " for(var k=0;k<cols.length;k++){if (!r.hasOwnProperty(i)) r[i]={}; r[i][colas[k]]=w[i][cols[k]];}"; } else { ss.push('\''+escapeq(col.as || col.columnid)+'\':p[\''+(tbid)+'\'][\''+col.columnid+'\']'); } } } else { ss.push('\''+escapeq(col.as || col.columnid)+'\':p[\''+(tbid)+'\']'); } query.selectColumns[escapeq(col.as || col.columnid)] = true; if(query.aliases[tbid] && query.aliases[tbid].type === 'table') { if(!alasql.databases[dbid].tables[query.aliases[tbid].tableid]) { throw new Error('Table \''+(tbid)+'\' does not exists in database'); } var columns = alasql.databases[dbid].tables[query.aliases[tbid].tableid].columns; var xcolumns = alasql.databases[dbid].tables[query.aliases[tbid].tableid].xcolumns; if(xcolumns && columns.length > 0) { var tcol = xcolumns[col.columnid]; if(undefined === tcol){ throw new Error("Column does not exists: "+col.columnid);; } var coldef = { columnid:col.as || col.columnid, dbtypeid:tcol.dbtypeid, dbsize:tcol.dbsize, dbpecision:tcol.dbprecision, dbenum: tcol.dbenum, }; query.columns.push(coldef); query.xcolumns[coldef.columnid]=coldef; } else { var coldef = { columnid:col.as || col.columnid, }; query.columns.push(coldef); query.xcolumns[coldef.columnid]=coldef; query.dirtyColumns = true; } } else { var coldef = { columnid:col.as || col.columnid, }; query.columns.push(coldef); query.xcolumns[coldef.columnid]=coldef; // This is a subquery? // throw new Error('There is now such table \''+col.tableid+'\''); ...
...
// todo?: 3. Compile SELECT clause
// For ROWNUM()
query.rownums = [];
this.compileSelectGroup0(query);
if(this.group || query.selectGroup.length>0) {
query.selectgfns = this.compileSelectGroup1(query);
} else {
query.selectfns = this.compileSelect1(query, params);
}
// Remove columns clause
this.compileRemoveColumns(query);
// 5. Optimize WHERE and JOINS
if(this.where){
this.compileWhereJoins(query);
}
...
compileSelect2 = function (query) { var s = query.selectfns; if(this.orderColumns && this.orderColumns.length>0) { this.orderColumns.forEach(function(v,idx) { var key = '$$$'+idx; if(v instanceof yy.Column && query.xcolumns[v.columnid]) { s += 'r[\''+key+'\']=r[\''+v.columnid+'\'];'; } else { s += 'r[\''+key+'\']='+v.toJS('p',query.defaultTableid,query.defcols)+';'; } query.removeKeys.push(key); }); } return new Function('p,params,alasql','var y;'+s+'return r'); }
...
// 8. Compile ORDER BY clause
if(this.order){
query.orderfn = this.compileOrder(query);
}
if(this.group || query.selectGroup.length>0) {
query.selectgfn = this.compileSelectGroup2(query);
} else {
query.selectfn = this.compileSelect2(query);
}
// 7. Compile DISTINCT, LIMIT and OFFSET
query.distinct = this.distinct;
// 9. Compile PIVOT clause
if(this.pivot) query.pivotfn = this.compilePivot(query);
if(this.unpivot) query.pivotfn = this.compileUnpivot(query);
// 10. Compile TOP/LIMIT/OFFSET/FETCH cleuse
...
compileSelectGroup0 = function (query) { var self = this; self.columns.forEach(function(col,idx){ if(!(col instanceof yy.Column && col.columnid === '*')){ var colas; // = col.as; if(col instanceof yy.Column) { colas = escapeq(col.columnid); } else { colas = escapeq(col.toString(true)); } for(var i=0;i<idx;i++) { if(colas === self.columns[i].nick) { colas = self.columns[i].nick+':'+idx; break; } } // } col.nick = colas; if( col.funcid && (col.funcid.toUpperCase() === 'ROWNUM'|| col.funcid.toUpperCase() === 'ROW_NUMBER')) { query.rownums.push(col.as); } // } } else { query.groupStar = col.tableid || 'default'; } }); this.columns.forEach(function(col){ if(col.findAggregator){ col.findAggregator(query); } }); if(this.having) { if(this.having.findAggregator){ this.having.findAggregator(query); } } }
...
// 2. Compile JOIN clauses
if(this.joins){
this.compileJoins(query);
}
// todo?: 3. Compile SELECT clause
// For ROWNUM()
query.rownums = [];
this.compileSelectGroup0(query);
if(this.group || query.selectGroup.length>0) {
query.selectgfns = this.compileSelectGroup1(query);
} else {
query.selectfns = this.compileSelect1(query, params);
}
// Remove columns clause
this.compileRemoveColumns(query);
...
compileSelectGroup1 = function (query) { var self = this; var s = 'var r = {};'; self.columns.forEach(function(col){ if(col instanceof yy.Column && col.columnid === '*') { s += 'for(var k in g) {r[k]=g[k]};'; return ''; } else { // var colas = col.as; var colas = col.as; if(colas === undefined) { if(col instanceof yy.Column){ colas = escapeq(col.columnid); } else { colas = col.nick; } } query.groupColumns[colas]=col.nick; s += 'r[\''+colas+'\']='; s += n2u(col.toJS('g',''))+';'; for(var i=0;i<query.removeKeys.length;i++) { // THis part should be intellectual if(query.removeKeys[i] === colas) { query.removeKeys.splice(i,1); break; } } } }); // return new Function('g,params,alasql',s+'return r'); return s; }
...
this.compileJoins(query);
}
// todo?: 3. Compile SELECT clause
// For ROWNUM()
query.rownums = [];
this.compileSelectGroup0(query);
if(this.group || query.selectGroup.length>0) {
query.selectgfns = this.compileSelectGroup1(query);
} else {
query.selectfns = this.compileSelect1(query, params);
}
// Remove columns clause
this.compileRemoveColumns(query);
// 5. Optimize WHERE and JOINS
if(this.where){
...
compileSelectGroup2 = function (query) { var self = this; var s = query.selectgfns; self.columns.forEach(function(col){ if(query.ingroup.indexOf(col.nick)>-1) { s += 'r[\''+(col.as||col.nick)+'\']=g[\''+col.nick+'\'];' }; }); if(this.orderColumns && this.orderColumns.length>0) { this.orderColumns.forEach(function(v,idx) { var key = '$$$'+idx; if(v instanceof yy.Column && query.groupColumns[v.columnid]) { s += 'r[\''+key+'\']=r[\''+v.columnid+'\'];'; } else { s += 'r[\''+key+'\']='+v.toJS('g','')+';'; } query.removeKeys.push(key); }); } return new Function('g,params,alasql','var y;'+s+'return r'); }
...
query.havingfn = this.compileHaving(query);
}
// 8. Compile ORDER BY clause
if(this.order){
query.orderfn = this.compileOrder(query);
}
if(this.group || query.selectGroup.length>0) {
query.selectgfn = this.compileSelectGroup2(query);
} else {
query.selectfn = this.compileSelect2(query);
}
// 7. Compile DISTINCT, LIMIT and OFFSET
query.distinct = this.distinct;
// 9. Compile PIVOT clause
if(this.pivot) query.pivotfn = this.compilePivot(query);
...
compileUnpivot = function (query) { var self = this; var tocolumnid = self.unpivot.tocolumnid; var forcolumnid = self.unpivot.forcolumnid; var inlist = self.unpivot.inlist.map(function(l){return l.columnid}); return function() { var data = []; var xcols = query.columns .map(function(col){return col.columnid}) .filter(function(colid){ return inlist.indexOf(colid)==-1 && colid != forcolumnid && colid != tocolumnid; }); query.data.forEach(function(d){ inlist.forEach(function(colid){ var nd = {}; xcols.forEach(function(xcolid){ nd[xcolid] = d[xcolid]}); nd[forcolumnid] = colid; nd[tocolumnid] = d[colid]; data.push(nd); }); }); query.data = data; }; }
...
} else {
query.selectfn = this.compileSelect2(query);
}
// 7. Compile DISTINCT, LIMIT and OFFSET
query.distinct = this.distinct;
// 9. Compile PIVOT clause
if(this.pivot) query.pivotfn = this.compilePivot(query);
if(this.unpivot) query.pivotfn = this.compileUnpivot(query);
// 10. Compile TOP/LIMIT/OFFSET/FETCH cleuse
if(this.top) {
query.limit = this.top.value;
} else if(this.limit) {
query.limit = this.limit.value;
if(this.offset) {
query.offset = this.offset.value;
...
compileWhere = function (query) { if(this.where) { if(typeof this.where == "function") { return this.where; } else { var s = this.where.toJS('p',query.defaultTableid,query.defcols); query.wherefns = s; return new Function('p,params,alasql','var y;return '+s); } } else return function(){return true}; }
...
// Remove columns clause
this.compileRemoveColumns(query);
// 5. Optimize WHERE and JOINS
if(this.where){
this.compileWhereJoins(query);
}
// 4. Compile WHERE clause
query.wherefn = this.compileWhere(query);
// 6. Compile GROUP BY
if(this.group || query.selectGroup.length>0){
query.groupfn = this.compileGroup(query);
}
// 6. Compile HAVING
if(this.having){
query.havingfn = this.compileHaving(query);
...
compileWhereExists = function (query) { if(!this.exists) return; query.existsfn = this.exists.map(function(ex) { var nq = ex.compile(query.database.databaseid); nq.query.modifier = 'RECORDSET'; return nq; }); }
...
query.aggrKeys = [];
query.explain = this.explain; // Explain
query.explaination = [];
query.explid = 1;
query.modifier = this.modifier;
query.database = db;
// 0. Precompile whereexists
this.compileWhereExists(query);
// 0. Precompile queries for IN, NOT IN, ANY and ALL operators
this.compileQueries(query);
query.defcols = this.compileDefCols(query, databaseid);
// 1. Compile FROM clause
query.fromfn = this.compileFrom(query);
// 2. Compile JOIN clauses
if(this.joins){
...
compileWhereJoins = function (query) { return; // TODO Fix Where optimization optimizeWhereJoin(query, this.where.expression); //for sources compile wherefs query.sources.forEach(function(source) { if(source.srcwherefns) { source.srcwherefn = new Function('p,params,alasql','var y;return '+source.srcwherefns); }; if(source.wxleftfns) { source.wxleftfn = new Function('p,params,alasql','var y;return '+source.wxleftfns); }; if(source.wxrightfns) { source.wxrightfn = new Function('p,params,alasql','var y;return '+source.wxrightfns); }; }); }
...
} else {
query.selectfns = this.compileSelect1(query, params);
}
// Remove columns clause
this.compileRemoveColumns(query);
// 5. Optimize WHERE and JOINS
if(this.where){
this.compileWhereJoins(query);
}
// 4. Compile WHERE clause
query.wherefn = this.compileWhere(query);
// 6. Compile GROUP BY
if(this.group || query.selectGroup.length>0){
query.groupfn = this.compileGroup(query);
}
...
exec = function (params, cb) { if(this.preparams) params = this.preparams.concat(params); var databaseid = alasql.useid; db = alasql.databases[databaseid]; var sql = this.toString(); var hh = hash(sql); var statement = this.compile(databaseid); if(!statement) return; statement.sql = sql; statement.dbversion = db.dbversion; // Secure sqlCache size if (db.sqlCacheSize > alasql.MAXSQLCACHESIZE) { db.resetSqlCache(); } db.sqlCacheSize++; db.sqlCache[hh] = statement; var res = alasql.res = statement(params, cb); return res; }
...
alasql('SELECT * FROM ?',[data],function(res){
console.log(data);
});
Call with scope for subquery (to pass common values):
var scope = {one:{a:2,b;20}}
alasql('SELECT * FROM ? two WHERE two.a = one.a',[data],null,scope);
Call for fluent interface with data object:
alasql(data).Where(function(x){return x.a == 10}).exec();
Call for fluent interface without data object:
alasql().From(data).Where(function(x){return x.a == 10}).exec();
*/
var alasql = function(sql, params, cb, scope) {
params = params||[];
...
execute = function (databaseid, params, cb) { return this.compile(databaseid)(params,cb); // throw new Error('Insert statement is should be compiled') }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toJS = function (context) { // if(this.expression.reduced) return 'true'; // return this.expression.toJS(context, tableid, defcols); // var s = 'this.queriesdata['+(this.queriesidx-1)+'][0]'; var s = 'alasql.utils.flatArray(this.queriesfn['+(this.queriesidx-1)+'](this.params,null,'+context+'))[0]'; return s; }
...
* Changed order of LIMIT and ORDER BY processing
#### Version 0.0.4 (28.10.2014-29.10.2014)
* Added /test/main.html mocha browser tests
* Added PERFORMANCE.md and perf.html tests
* StringValue.toJS()
* Added callback to Database.exec
* Sieve of Eratosthenes example
* Remove generation of recs after select in case of group by (for memory optimization)
* Added conversion for type MONEY for INSERT statement
#### Versions 0.0.1 - 0.0.3 (25.10.2014-27.10.2014)
...
toString = function () { var s; s = ''; if (this.explain) { s += 'EXPLAIN '; } s += 'SELECT '; if (this.modifier) { s += this.modifier + ' '; } if (this.distinct) { s += 'DISTINCT '; } if (this.top) { s += 'TOP ' + this.top.value + ' '; if (this.percent) { s += 'PERCENT '; } } s += this.columns.map(function(col) { var s; s = col.toString(); if (typeof col.as !== 'undefined') { s += ' AS ' + col.as; } return s; }).join(', '); if (this.from) { s += ' FROM ' + this.from.map(function(f) { var ss; ss = f.toString(); if (f.as) { ss += ' AS ' + f.as; } return ss; }).join(','); } if (this.joins) { s += this.joins.map(function(jn) { var ss; ss = ' '; if (jn.joinmode) { ss += jn.joinmode + ' '; } if (jn.table) { ss += 'JOIN ' + jn.table.toString(); } else if (jn.select) { ss += 'JOIN (' + jn.select.toString() + ')'; } else if (jn instanceof alasql.yy.Apply) { ss += jn.toString(); } else { throw new Error('Wrong type in JOIN mode'); } if (jn.as) { ss += ' AS ' + jn.as; } if (jn.using) { ss += ' USING ' + jn.using.toString(); } if (jn.on) { ss += ' ON ' + jn.on.toString(); } return ss; }); } if (this.where) { s += ' WHERE ' + this.where.toString(); } if (this.group && this.group.length > 0) { s += ' GROUP BY ' + this.group.map(function(grp) { return grp.toString(); }).join(', '); } if (this.having) { s += ' HAVING ' + this.having.toString(); } if (this.order && this.order.length > 0) { s += ' ORDER BY ' + this.order.map(function(ord) { return ord.toString(); }).join(', '); } if (this.limit) { s += ' LIMIT ' + this.limit.value; } if (this.offset) { s += ' OFFSET ' + this.offset.value; } if (this.union) { s += ' UNION ' + (this.corresponding ? 'CORRESPONDING ' : '') + this.union.toString(); } if (this.unionall) { s += ' UNION ALL ' + (this.corresponding ? 'CORRESPONDING ' : '') + this.unionall.toString(); } if (this.except) { s += ' EXCEPT ' + (this.corresponding ? 'CORRESPONDING ' : '') + this.except.toString(); } if (this.intersect) { s += ' INTERSECT ' + (this.corresponding ? 'CORRESPONDING ' : '') + this.intersect.toString(); } return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
SetColumn = function (params) { return yy.extend(this, params); }
...
case 449:
this.$ = new yy.Update({table:$$[$0-4], columns:$$[$0-2], where:$$[$0]});
break;
case 450:
this.$ = new yy.Update({table:$$[$0-2], columns:$$[$0]});
break;
case 453:
this.$ = new yy.SetColumn({column:$$[$0-2], expression:$$[$0]})
break;
case 454:
this.$ = new yy.SetColumn({variable:$$[$0-2], expression:$$[$0], method:$$[$0-3]})
break;
case 455:
this.$ = new yy.Delete({table:$$[$0-2], where:$$[$0]});
break;
...
toString = function () { return this.column.toString() + '='+this.expression.toString(); }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
SetVariable = function (params) { return yy.extend(this, params); }
...
case 645:
this.$ = {}; this.$[$$[$0-2].substr(1,$$[$0-2].length-2)] = $$[$0];
break;
case 646: case 647:
this.$ = {}; this.$[$$[$0-2]] = $$[$0];
break;
case 650:
this.$ = new yy.SetVariable({variable:$$[$0-2].toLowerCase(), value:$$[$0]});
break;
case 651:
this.$ = new yy.SetVariable({variable:$$[$0-1].toLowerCase(), value:$$[$0]});
break;
case 652:
this.$ = new yy.SetVariable({variable:$$[$0-2], expression:$$[$0]});
break;
...
execute = function (databaseid, params, cb) { if(typeof this.value != 'undefined') { var val = this.value; if(val == 'ON') val = true; else if(val == 'OFF') val = false; alasql.options[this.variable] = val; } else if(this.expression) { if(this.exists) { this.existsfn = this.exists.map(function(ex) { var nq = ex.compile(databaseid); if(nq.query && !nq.query.modifier) nq.query.modifier='RECORDSET'; return nq; // TODO Include modifier }); } if(this.queries) { this.queriesfn = this.queries.map(function(q) { var nq = q.compile(databaseid); if(nq.query && !nq.query.modifier) nq.query.modifier='RECORDSET'; return nq; // TODO Include modifier }); } var res = new Function("params,alasql","return " +this.expression.toJS('({})','', null)).bind(this)(params,alasql); if(alasql.declares[this.variable]) { res = alasql.stdfn.CONVERT(res,alasql.declares[this.variable]); } if(this.props && this.props.length > 0) { if(this.method == '@') { var fs = 'alasql.vars[\''+this.variable+'\']'; } else { var fs = 'params[\''+this.variable+'\']'; } fs += this.props.map(function(prop){ if(typeof prop == 'string') { return '[\''+prop+'\']'; } else if(typeof prop == 'number') { return '['+prop+']'; } else { return '['+prop.toJS()+']'; } }).join(); new Function("value,params,alasql",'var y;'+fs +'=value')(res,params,alasql); } else { if(this.method == '@') { alasql.vars[this.variable] = res; } else { params[this.variable] = res; } } } var res = 1; if(cb) res=cb(res); return res; }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { var s = 'SET '; if(typeof this.value != 'undefined') s += this.variable.toUpperCase()+' '+(this.value?'ON':'OFF'); if(this.expression) s += this.method + this.variable+' = '+this.expression.toString(); return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
ShowColumns = function (params) { return yy.extend(this, params); }
...
case 600:
this.$ = new yy.ShowTables({databaseid: $$[$0]});
break;
case 601:
this.$ = new yy.ShowTables({like:$$[$0], databaseid: $$[$0-2]});
break;
case 602:
this.$ = new yy.ShowColumns({table: $$[$0]});
break;
case 603:
this.$ = new yy.ShowColumns({table: $$[$0-2], databaseid:$$[$0]});
break;
case 604:
this.$ = new yy.ShowIndex({table: $$[$0]});
break;
...
execute = function (databaseid) { var db = alasql.databases[this.databaseid || databaseid]; var table = db.tables[this.table.tableid]; var self = this; if(table && table.columns) { var res = table.columns.map(function(col){ return {columnid: col.columnid, dbtypeid: col.dbtypeid, dbsize: col.dbsize}; }); return res; } else { return []; } }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { var s = 'SHOW COLUMNS'; if(this.table.tableid) s += ' FROM '+this.table.tableid; if(this.databaseid) s += ' FROM '+this.databaseid; return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
ShowCreateTable = function (params) { return yy.extend(this, params); }
...
case 604:
this.$ = new yy.ShowIndex({table: $$[$0]});
break;
case 605:
this.$ = new yy.ShowIndex({table: $$[$0-2], databaseid: $$[$0]});
break;
case 606:
this.$ = new yy.ShowCreateTable({table: $$[$0]});
break;
case 607:
this.$ = new yy.ShowCreateTable({table: $$[$0-2], databaseid:$$[$0]});
break;
case 608:
this.$ = new yy.CreateTable({table:$$[$0-6],view:true,select:$$[$0-1],viewcolumns:$$[$0-4]});
...
execute = function (databaseid) { var db = alasql.databases[this.databaseid || databaseid]; var table = db.tables[this.table.tableid]; var self = this; if(table) { var s = 'CREATE TABLE '+this.table.tableid+' ('; var ss = []; if(table.columns) { table.columns.forEach(function(col){ var a = col.columnid+' '+col.dbtypeid; if(col.dbsize) a += '('+col.dbsize+')'; if(col.primarykey) a += ' PRIMARY KEY'; // TODO extend ss.push(a); }); s += ss.join(', '); }; s += ')'; return s; } else { throw new Error('There is no such table "'+this.table.tableid+'"'); } }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { var s = 'SHOW CREATE TABLE '+this.table.tableid; if(this.databaseid) s += ' FROM '+this.databaseid; return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
ShowDatabases = function (params) { return yy.extend(this, params); }
...
case 592:
this.$ = new yy.CreateIndex({indexid:$$[$0-5], table:$$[$0-3], columns:$$[$0-1], unique:true})
break;
case 593:
this.$ = new yy.DropIndex({indexid:$$[$0]});
break;
case 594:
this.$ = new yy.ShowDatabases();
break;
case 595:
this.$ = new yy.ShowDatabases({like:$$[$0]});
break;
case 596:
this.$ = new yy.ShowDatabases({engineid:$$[$0-1].toUpperCase() });
break;
...
execute = function (databaseid, params, cb) { if(this.engineid) { return alasql.engines[this.engineid].showDatabases(this.like, cb); } else { var self = this; var res = []; for(dbid in alasql.databases) { res.push({databaseid: dbid}); }; if(self.like && res && res.length > 0) { res = res.filter(function(d){ return alasql.utils.like(self.like.value,d.databaseid); }); } if(cb) cb(res); return res; }; }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { var s = 'SHOW DATABASES'; if(this.like) s += 'LIKE '+this.like.toString(); return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
ShowIndex = function (params) { return yy.extend(this, params); }
...
case 602:
this.$ = new yy.ShowColumns({table: $$[$0]});
break;
case 603:
this.$ = new yy.ShowColumns({table: $$[$0-2], databaseid:$$[$0]});
break;
case 604:
this.$ = new yy.ShowIndex({table: $$[$0]});
break;
case 605:
this.$ = new yy.ShowIndex({table: $$[$0-2], databaseid: $$[$0]});
break;
case 606:
this.$ = new yy.ShowCreateTable({table: $$[$0]});
break;
...
execute = function (databaseid) { var db = alasql.databases[this.databaseid || databaseid]; var table = db.tables[this.table.tableid]; var self = this; var res = []; if(table && table.indices) { for(var ind in table.indices) { res.push({hh:ind, len:Object.keys(table.indices[ind]).length}); } } return res; }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { var s = 'SHOW INDEX'; if(this.table.tableid) s += ' FROM '+this.table.tableid; if(this.databaseid) s += ' FROM '+this.databaseid; return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
ShowTables = function (params) { return yy.extend(this, params); }
...
case 596:
this.$ = new yy.ShowDatabases({engineid:$$[$0-1].toUpperCase() });
break;
case 597:
this.$ = new yy.ShowDatabases({engineid:$$[$0-3].toUpperCase() , like:$$[$0]});
break;
case 598:
this.$ = new yy.ShowTables();
break;
case 599:
this.$ = new yy.ShowTables({like:$$[$0]});
break;
case 600:
this.$ = new yy.ShowTables({databaseid: $$[$0]});
break;
...
execute = function (databaseid, params, cb) { var db = alasql.databases[this.databaseid || databaseid]; var self = this; var res = []; for(tableid in db.tables) { res.push({tableid: tableid}); }; if(self.like && res && res.length > 0) { res = res.filter(function(d){ //return d.tableid.match(new RegExp((self.like.value||'').replace(/\%/g,'.*').replace(/\?|_/g,'.'),'g')); return alasql.utils.like(self.like.value,d.tableid); }); }; if(cb) cb(res); return res; }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { var s = 'SHOW TABLES'; if(this.databaseid) s += ' FROM '+this.databaseid; if(this.like) s += ' LIKE '+this.like.toString(); return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
Source = function (params) { return yy.extend(this, params); }
...
case 613:
this.$ = new yy.DropTable({tables:$$[$0], view:true}); yy.extend(this.$, $$[$0-1]);
break;
case 614: case 760:
this.$ = new yy.ExpressionStatement({expression:$$[$0]});
break;
case 615:
this.$ = new yy.Source({url:$$[$0].value});
break;
case 616:
this.$ = new yy.Assert({value:$$[$0]});
break;
case 617:
this.$ = new yy.Assert({value:$$[$0].value});
break;
...
execute = function (databaseid, params, cb) { var res; loadFile(this.url, !!cb, function(data){ res = alasql(data); if(cb) res = cb(res); return res; }, function(err){ throw err; }); return res; }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { var s = 'ASSERT'; if(this.value) s += ' '+JSON.stringify(this.value); return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
Statements = function (params) { return yy.extend(this, params); }
...
case 4:
this.$ = $$[$0]
break;
case 5:
this.$ = $$[$0] ? $$[$0-1] + ' ' + $$[$0] : $$[$0-1]
break;
case 6:
return new yy.Statements({statements:$$[$0-1]});
break;
case 7:
this.$ = $$[$0-2]; if($$[$0]) $$[$0-2].push($$[$0]);
break;
case 8: case 9: case 70: case 80: case 85: case 143: case 177: case 205: case 206: case 242: case 261: case 273: case 354: case
372: case 451: case 474: case 475: case 479: case 487: case 528: case 529: case 566: case 649: case 659: case 683: case 685: case
687: case 701: case 702: case 732: case 756:
this.$ = [$$[$0]];
break;
...
compile = function (db) { var statements = this.statements.map(function(st){ return st.compile(db) }); if(statements.length === 1) { return statements[0]; } else { return function(params, cb){ var res = statements.map(function(st){ return st(params); }); if(cb){ cb(res); } return res; } } }
...
You can also define your own aggregator functions (like your own `SUM(...)`). See more [in the wiki](https://github.com/agershun
/alasql/wiki/User-Defined-Functions)
### Compiled statements and functions
```js
var ins = alasql.compile('INSERT INTO one VALUES (?,?)');
ins(1,10);
ins(2,20);
```
See more [in the wiki](https://github.com/agershun/alasql/wiki/Compile)
...
toString = function () { return this.statements.map(function(st){return st.toString()}).join('; '); }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
StringValue = function (params) { return yy.extend(this, params); }
...
case 168:
var s = $$[$0];
s = s.substr(1,s.length-2);
var x3 = s.substr(-3).toUpperCase();
var x4 = s.substr(-4).toUpperCase();
if(s[0] == '#') {
this.$ = {into: new yy.FuncValue({funcid: 'HTML', args:[new yy.StringValue({value: s}), new yy.Json({value:{headers:true}})]})};
} else if(x3=='XLS' || x3 == 'CSV' || x3=='TAB') {
this.$ = {into: new yy.FuncValue({funcid: x3, args:[new yy.StringValue({value: s}), new yy.Json({value:{headers:true}})]})};
} else if(x4=='XLSX' || x4 == 'JSON') {
this.$ = {into: new yy.FuncValue({funcid: x4, args:[new yy.StringValue({value: s}), new yy.Json({value:{headers:true}})]})};
}
break;
case 169:
...
toJS = function () { // return "'"+doubleqq(this.value)+"'"; return "'"+escapeq(this.value)+"'"; }
...
* Changed order of LIMIT and ORDER BY processing
#### Version 0.0.4 (28.10.2014-29.10.2014)
* Added /test/main.html mocha browser tests
* Added PERFORMANCE.md and perf.html tests
* StringValue.toJS()
* Added callback to Database.exec
* Sieve of Eratosthenes example
* Remove generation of recs after select in case of group by (for memory optimization)
* Added conversion for type MONEY for INSERT statement
#### Versions 0.0.1 - 0.0.3 (25.10.2014-27.10.2014)
...
toString = function () { return "'"+this.value.toString()+"'"; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
toType = function () { return 'string'; }
...
if(['-','*','/','%','^'].indexOf(this.op) >-1){
return 'number';
}
if(['||'].indexOf(this.op) >-1){
return 'string';
}
if(this.op === '+') {
if(this.left.toType(tableid) === 'string' || this.right.toType(tableid) ===
x27;string'){
return 'string';
}
if(this.left.toType(tableid) === 'number' || this.right.toType(tableid) === 'number'){
return 'number';
}
}
if(['AND','OR','NOT','=','==','===', '!=','!==',
x27;!===','>','>=','<','<=', 'IN', 'NOT IN',
x27;LIKE', 'NOT LIKE', 'REGEXP', 'GLOB'].indexOf(this.op) >-1 ){
...
Table = function (params) { return yy.extend(this, params); }
...
this.$ = r;
break;
case 201:
if($$[$0-2] == 'INFORMATION_SCHEMA') {
this.$ = new yy.FuncValue({funcid: $$[$0-2], args:[new yy.StringValue({value:$$[$0]})]});
} else {
this.$ = new yy.Table({databaseid: $$[$0-2], tableid:$$[$0]});
}
break;
case 202:
this.$ = new yy.Table({tableid: $$[$0]});
break;
case 203: case 204:
this.$ = $$[$0-1]; $$[$0-1].push($$[$0]);
...
toString = function () { var s = this.tableid; // if(this.joinmode) if(this.databaseid){ s = this.databaseid+'.'+s; } return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
TruncateTable = function (params) { return yy.extend(this, params); }
...
case 691:
this.$ = {variable: $$[$0-3], expression:$$[$0]}; yy.extend(this.$,$$[$0-2]);
break;
case 692:
this.$ = {variable: $$[$0-4], expression:$$[$0]}; yy.extend(this.$,$$[$0-2]);
break;
case 693:
this.$ = new yy.TruncateTable({table:$$[$0]});
break;
case 694:
this.$ = new yy.Merge(); yy.extend(this.$,$$[$0-4]); yy.extend(this.$,$$[$0-3]);
yy.extend(this.$,$$[$0-2]);
yy.extend(this.$,{matches:$$[$0-1]});yy.extend(this.$,$$[$0]);
break;
...
execute = function (databaseid, params, cb) { var db = alasql.databases[this.table.databaseid || databaseid]; var tableid = this.table.tableid; if(db.engineid) { return alasql.engines[db.engineid].truncateTable(this.table.databaseid || databaseid,tableid, this.ifexists, cb); } if(db.tables[tableid]) { db.tables[tableid].data = []; } else { throw new Error('Cannot truncate table becaues it does not exist'); } return cb?cb(0):0; }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { var s = 'TRUNCATE TABLE'; s += ' '+this.table.toString(); return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
UniOp = function (params) { return yy.extend(this, params); }
...
this.$ = new yy.Op({left:$$[$0-2], op:'AND', right:$$[$0]});
}
break;
case 415:
this.$ = new yy.Op({left:$$[$0-2], op:'OR' , right:$$[$0]});
break;
case 416:
this.$ = new yy.UniOp({op:'NOT' , right:$$[$0]});
break;
case 417:
this.$ = new yy.UniOp({op:'-' , right:$$[$0]});
break;
case 418:
this.$ = new yy.UniOp({op:'+' , right:$$[$0]});
break;
...
findAggregator = function (query){ if(this.right.findAggregator){ this.right.findAggregator(query); } }
...
// }
} else {
query.groupStar = col.tableid || 'default';
}
});
this.columns.forEach(function(col){
if(col.findAggregator){
col.findAggregator(query);
}
});
if(this.having) {
if(this.having.findAggregator){
this.having.findAggregator(query);
}
}
...
toJS = function (context, tableid, defcols) { if(this.op === '~'){ return "(~("+this.right.toJS(context, tableid, defcols)+"))"; } if(this.op === '-'){ return "(-("+this.right.toJS(context, tableid, defcols)+"))"; } if(this.op === '+'){ return "("+this.right.toJS(context, tableid, defcols)+")"; } if(this.op === 'NOT'){ return '!('+this.right.toJS(context, tableid, defcols)+')'; } if(this.op === '#') { if(this.right instanceof yy.Column) { return "(alasql.databases[alasql.useid].objects[\'"+this.right.columnid+"\'])"; } else { return "(alasql.databases[alasql.useid].objects[" +this.right.toJS(context, tableid, defcols)+"])"; } } // Please avoid === here if(this.op == null){ // jshint ignore:line return '('+this.right.toJS(context, tableid, defcols)+')'; } // Todo: implement default case. }
...
* Changed order of LIMIT and ORDER BY processing
#### Version 0.0.4 (28.10.2014-29.10.2014)
* Added /test/main.html mocha browser tests
* Added PERFORMANCE.md and perf.html tests
* StringValue.toJS()
* Added callback to Database.exec
* Sieve of Eratosthenes example
* Remove generation of recs after select in case of group by (for memory optimization)
* Added conversion for type MONEY for INSERT statement
#### Versions 0.0.1 - 0.0.3 (25.10.2014-27.10.2014)
...
toString = function () { var s; s = void 0; if (this.op === '~') { s = this.op + this.right.toString(); } if (this.op === '-') { s = this.op + this.right.toString(); } if (this.op === '+') { s = this.op + this.right.toString(); } if (this.op === '#') { s = this.op + this.right.toString(); } if (this.op === 'NOT') { s = this.op + '(' + this.right.toString() + ')'; } if (this.op === null) { s = '(' + this.right.toString() + ')'; } if (!s) { s = '(' + this.right.toString() + ')'; } return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
toType = function () { if(this.op === '-'){ return 'number'; } if(this.op === '+'){ return 'number'; } if(this.op === 'NOT'){ return 'boolean'; } // Todo: implement default case }
...
if(['-','*','/','%','^'].indexOf(this.op) >-1){
return 'number';
}
if(['||'].indexOf(this.op) >-1){
return 'string';
}
if(this.op === '+') {
if(this.left.toType(tableid) === 'string' || this.right.toType(tableid) ===
x27;string'){
return 'string';
}
if(this.left.toType(tableid) === 'number' || this.right.toType(tableid) === 'number'){
return 'number';
}
}
if(['AND','OR','NOT','=','==','===', '!=','!==',
x27;!===','>','>=','<','<=', 'IN', 'NOT IN',
x27;LIKE', 'NOT LIKE', 'REGEXP', 'GLOB'].indexOf(this.op) >-1 ){
...
Union = function (params) { return yy.extend(this, params); }
n/a
compile = function (tableid) { return null; }
...
You can also define your own aggregator functions (like your own `SUM(...)`). See more [in the wiki](https://github.com/agershun
/alasql/wiki/User-Defined-Functions)
### Compiled statements and functions
```js
var ins = alasql.compile('INSERT INTO one VALUES (?,?)');
ins(1,10);
ins(2,20);
```
See more [in the wiki](https://github.com/agershun/alasql/wiki/Compile)
...
toString = function () { return 'UNION'; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
Update = function (params) { return yy.extend(this, params); }
...
case 447:
this.$ = 'SOME';
break;
case 448:
this.$ = 'ANY';
break;
case 449:
this.$ = new yy.Update({table:$$[$0-4], columns:$$[$0-2], where:$$[$0]});
break;
case 450:
this.$ = new yy.Update({table:$$[$0-2], columns:$$[$0]});
break;
case 453:
this.$ = new yy.SetColumn({column:$$[$0-2], expression:$$[$0]})
break;
...
compile = function (databaseid) { databaseid = this.table.databaseid || databaseid; var tableid = this.table.tableid; if(this.where) { if(this.exists) { this.existsfn = this.exists.map(function(ex) { var nq = ex.compile(databaseid); nq.query.modifier='RECORDSET'; return nq; }); } if(this.queries) { this.queriesfn = this.queries.map(function(q) { var nq = q.compile(databaseid); nq.query.modifier='RECORDSET'; return nq; }); } var wherefn = new Function('r,params,alasql','var y;return '+this.where.toJS('r','')).bind(this); }; // Construct update function var s = alasql.databases[databaseid].tables[tableid].onupdatefns || ''; s += ';'; this.columns.forEach(function(col){ s += 'r[\''+col.column.columnid+'\']='+col.expression.toJS('r','')+';'; }); var assignfn = new Function('r,params,alasql','var y;'+s); var statement = function(params, cb) { var db = alasql.databases[databaseid]; if(db.engineid && alasql.engines[db.engineid].updateTable) { return alasql.engines[db.engineid].updateTable(databaseid, tableid, assignfn, wherefn, params, cb); } if(alasql.options.autocommit && db.engineid) { alasql.engines[db.engineid].loadTableData(databaseid,tableid); } var table = db.tables[tableid]; if(!table) { throw new Error("Table '"+tableid+"' not exists") } var numrows = 0; for(var i=0, ilen=table.data.length; i<ilen; i++) { if(!wherefn || wherefn(table.data[i], params,alasql) ) { if(table.update) { table.update(assignfn, i, params); } else { assignfn(table.data[i], params,alasql); } numrows++; } }; if(alasql.options.autocommit && db.engineid) { alasql.engines[db.engineid].saveTableData(databaseid,tableid); } if(cb) cb(numrows); return numrows; }; return statement; }
...
You can also define your own aggregator functions (like your own `SUM(...)`). See more [in the wiki](https://github.com/agershun
/alasql/wiki/User-Defined-Functions)
### Compiled statements and functions
```js
var ins = alasql.compile('INSERT INTO one VALUES (?,?)');
ins(1,10);
ins(2,20);
```
See more [in the wiki](https://github.com/agershun/alasql/wiki/Compile)
...
execute = function (databaseid, params, cb) { return this.compile(databaseid)(params,cb); }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { var s = 'UPDATE '+this.table.toString(); if(this.columns) s += ' SET '+this.columns.toString(); if(this.where) s += ' WHERE '+this.where.toString(); return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
UseDatabase = function (params) { return yy.extend(this, params); }
...
this.$ = new yy.CreateDatabase({engineid:$$[$0-4].toUpperCase(),
as:$$[$0], args:[$$[$0-1]] }); yy.extend(this.$,$$[$0-2]);
break;
case 584:
this.$ = undefined;
break;
case 586: case 587:
this.$ = new yy.UseDatabase({databaseid: $$[$0] });
break;
case 588:
this.$ = new yy.DropDatabase({databaseid: $$[$0] }); yy.extend(this.$,$$[$0-1]);
break;
case 589: case 590:
this.$ = new yy.DropDatabase({databaseid: $$[$0], engineid:$$[$0-3].toUpperCase() }); yy.extend(this.$,$$[$0-1]);
break;
...
execute = function (databaseid, params, cb) { var dbid = this.databaseid; if(!alasql.databases[dbid]) { throw new Error("Database '"+dbid+"' does not exist") }; alasql.use(dbid); var res = 1; if(cb) cb(res); return res; }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { return 'USE' +' '+'DATABASE'+' '+this.databaseid; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
VarValue = function (params) { return yy.extend(this, params); }
...
case 360:
this.$ = new yy.StringValue({value: $$[$0].substr(2,$$[$0].length-3).replace(/(\\\')/g,"'").replace(/(\'
;\')/g,"'")});
break;
case 361:
this.$ = new yy.NullValue({value:undefined});
break;
case 362:
this.$ = new yy.VarValue({variable:$$[$0]});
break;
case 363:
if(!yy.exists) yy.exists = [];
this.$ = new yy.ExistsValue({value:$$[$0-1], existsidx:yy.exists.length});
yy.exists.push($$[$0-1]);
break;
...
toJS = function () { return "alasql.vars['"+this.variable+"']"; }
...
* Changed order of LIMIT and ORDER BY processing
#### Version 0.0.4 (28.10.2014-29.10.2014)
* Added /test/main.html mocha browser tests
* Added PERFORMANCE.md and perf.html tests
* StringValue.toJS()
* Added callback to Database.exec
* Sieve of Eratosthenes example
* Remove generation of recs after select in case of group by (for memory optimization)
* Added conversion for type MONEY for INSERT statement
#### Versions 0.0.1 - 0.0.3 (25.10.2014-27.10.2014)
...
toString = function () { return '@'+this.variable; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
toType = function () { return 'unknown'; }
...
if(['-','*','/','%','^'].indexOf(this.op) >-1){
return 'number';
}
if(['||'].indexOf(this.op) >-1){
return 'string';
}
if(this.op === '+') {
if(this.left.toType(tableid) === 'string' || this.right.toType(tableid) ===
x27;string'){
return 'string';
}
if(this.left.toType(tableid) === 'number' || this.right.toType(tableid) === 'number'){
return 'number';
}
}
if(['AND','OR','NOT','=','==','===', '!=','!==',
x27;!===','>','>=','<','<=', 'IN', 'NOT IN',
x27;LIKE', 'NOT LIKE', 'REGEXP', 'GLOB'].indexOf(this.op) >-1 ){
...
View = function (params) { return yy.extend(this, params); }
n/a
toString = function () { var s = this.viewid; // if(this.joinmode) if(this.databaseid){ s = this.databaseid+'.'+s; } return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
While = function (params) { return yy.extend(this, params); }
...
if($$[$0].exists) this.$.exists = $$[$0].exists;
if($$[$0].queries) this.$.queries = $$[$0].queries;
break;
case 670:
this.$ = $$[$0];
break;
case 671:
this.$ = new yy.While({expression:$$[$0-1],loopstat:$$[$0]});
if($$[$0].exists) this.$.exists = $$[$0].exists;
if($$[$0].queries) this.$.queries = $$[$0].queries;
break;
case 672:
this.$ = new yy.Continue();
break;
case 673:
...
execute = function (databaseid, params, cb) { var self = this; var res = []; var fn = new Function('params,alasql,p','var y;return '+this.expression.toJS()); if(cb) { var first = false; loop(); function loop(data) { if(first) { res.push(data); } else { first = true; }; setTimeout(function(){ if(fn(params,alasql)) { self.loopstat.execute(databaseid,params,loop); } else { res = cb(res); } },0); } } else { while(fn(params,alasql)) { var res1 = self.loopstat.execute(databaseid,params); res.push(res1); } } return res; }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { var s = 'WHILE '; s += this.expression.toString(); s += ' '+this.loopstat.toString(); return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...
WithSelect = function (params) { return yy.extend(this, params); }
...
if(yy.queries) this.$.queries = yy.queries;
delete yy.queries;
break;
case 13: case 162: case 172: case 237: case 238: case 240: case 248: case 250: case 259: case 267: case 270: case 375: case 491:
case 501: case 503: case 515: case 521: case 522: case 567:
this.$ = undefined;
break;
case 68:
this.$ = new yy.WithSelect({withs: $$[$0-1], select:$$[$0]});
break;
case 69: case 565:
$$[$0-2].push($$[$0]); this.$=$$[$0-2];
break;
case 71:
this.$ = {name:$$[$0-4], select:$$[$0-1]};
break;
...
execute = function (databaseid, params, cb) { var self = this; // Create temporary tables var savedTables = []; self.withs.forEach(function(w){ savedTables.push(alasql.databases[databaseid].tables[w.name]); var tb = alasql.databases[databaseid].tables[w.name] = new Table({tableid:w.name}); tb.data = w.select.execute(databaseid,params); }); var res = 1; res = this.select.execute(databaseid,params,function(data){ // Clear temporary tables self.withs.forEach(function(w,idx){ if(savedTables[idx]) alasql.databases[databaseid].tables[w.name] = savedTables[idx] ; else delete alasql.databases[databaseid].tables[w.name]; }); if(cb) data = cb(data); return data; }); return res; }
...
db.sqlCacheSize++;
db.sqlCache[hh] = statement;
}
var res = alasql.res = statement(params, cb, scope);
return res;
} else {
alasql.precompile(ast.statements[0],alasql.useid,params);
var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope);
return res;
}
} else {
// Multiple statements
if(cb) {
alasql.adrun(databaseid, ast, params, cb, scope);
} else {
...
toString = function () { var s = 'WITH '; s += this.withs.map(function(w){ return w.name+' AS ('+w.select.toString()+')'; }).join(',')+' '; s += this.select.toString(); return s; }
...
* Added: The `VALUES` keyword is optional when insterting (For the very lazy ones)
* Fix: Multiple worksheet Excel with custom headers
### 0.3.6 "Hipu" (24.01.2017)
* Addded: Support for "use strict"
* Fix: Select.toString() had bugs
* Update: Better and faster deep compare of objects
### 0.3.5 "Maiao" (22.12.2016)
* Added: Import data through AngularJS controllers
* Added: Support for running in VM for nodeJS
* Fix: Typescript definition
...