diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000..86fa4b9c19 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,4 @@ +*.js text eol=lf +*.xlsx binary +*.xls binary +*.csv binary diff --git a/CHANGELOG.md b/CHANGELOG.md index b01a4a7907..a977a84fdd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,9 @@ # Changelog -### 0.0.44 "Roma" (02.04.2015 - ...04.2015) +### 0.0.45 "Rio de Janeiro" (14.04.2015 - ...04.2015) +* Changed CRLF for alacon.js and alaserver.js to LF + +### 0.0.44 "Roma" (02.04.2015 - 13.04.2015) * Added params to SQLite attached database: alasql('ATTACH SQLITE DATABASE a(?)',[event],cb); * Root directory was cleaned * Gulp version is updated diff --git a/alasql.js b/alasql.js index d5c8069126..a9fa873e8c 100755 --- a/alasql.js +++ b/alasql.js @@ -31,88 +31,88 @@ SOFTWARE. */ - -/** - UMD envelope - */ - -(function (root, factory) { - if (typeof define === 'function' && define.amd) { - define([], factory); - } else if (typeof exports === 'object') { - module.exports = factory(); - } else { - root.alasql = factory(); - } -}(this, function () { - -/** - alasql - Main Alasql class - @param {string | Object} sql SQL-statement or data object for fuent interface - @param {Object} params SQL parameters - @param {Function} cb callback function - @param {Object} scope Scope for nested queries - @return {array} Result data object - - Standard sync call: - alasql('CREATE TABLE one'); - Query: - var res = alasql('SELECT * FROM one'); - Call with parameters: - var res = alasql('SELECT * FROM ?',[data]); - Standard async call with callback 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) { - if(typeof importScripts != 'function' && alasql.webworker) { - var id = alasql.lastid++; - alasql.buffer[id] = cb; - alasql.webworker.postMessage({id:id,sql:sql,params:params}); - } else { - 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 && typeof sql == "object" && sql instanceof Array) { - // One argument data object - fluent interface - var select = new yy.Select({ - columns:[new yy.Column({columnid:'*'})], - from: [new yy.ParamValue({param:0})] - }); - select.preparams = [sql]; - return select; - } else { - // 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 HTMElement) { - 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); - } - }; -}; - -/** Current version of alasql */ -alasql.version = "0.0.44"; - + +/** + UMD envelope + */ + +(function (root, factory) { + if (typeof define === 'function' && define.amd) { + define([], factory); + } else if (typeof exports === 'object') { + module.exports = factory(); + } else { + root.alasql = factory(); + } +}(this, function () { + +/** + alasql - Main Alasql class + @param {string | Object} sql SQL-statement or data object for fuent interface + @param {Object} params SQL parameters + @param {Function} cb callback function + @param {Object} scope Scope for nested queries + @return {array} Result data object + + Standard sync call: + alasql('CREATE TABLE one'); + Query: + var res = alasql('SELECT * FROM one'); + Call with parameters: + var res = alasql('SELECT * FROM ?',[data]); + Standard async call with callback 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) { + if(typeof importScripts != 'function' && alasql.webworker) { + var id = alasql.lastid++; + alasql.buffer[id] = cb; + alasql.webworker.postMessage({id:id,sql:sql,params:params}); + } else { + 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 && typeof sql == "object" && sql instanceof Array) { + // One argument data object - fluent interface + var select = new yy.Select({ + columns:[new yy.Column({columnid:'*'})], + from: [new yy.ParamValue({param:0})] + }); + select.preparams = [sql]; + return select; + } else { + // 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 HTMElement) { + 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); + } + }; +}; + +/** Current version of alasql */ +alasql.version = "0.0.44"; + /* parser generated by jison 0.4.15 */ @@ -201,9 +201,9 @@ performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate /* actio var $0 = $$.length - 1; switch (yystate) { case 1: - - if (yy.casesensitive) this.$ = $$[$0]; - else this.$ = $$[$0].toLowerCase(); + + if (yy.casesensitive) this.$ = $$[$0]; + else this.$ = $$[$0].toLowerCase(); break; case 2: @@ -225,12 +225,12 @@ case 9: this.$ = $$[$0]; $$[$0].explain = true; break; case 10: - - this.$ = $$[$0]; - if(yy.exists) this.$.exists = yy.exists; - delete yy.exists; - if(yy.queries) this.$.queries = yy.queries; - delete yy.queries; + + this.$ = $$[$0]; + if(yy.exists) this.$.exists = yy.exists; + delete yy.exists; + if(yy.queries) this.$.queries = yy.queries; + delete yy.queries; break; case 11: case 63: case 74: case 83: case 144: case 145: case 147: case 155: case 157: case 162: case 170: case 172: case 225: case 266: case 361: case 364: case 376: case 381: case 382: case 416: @@ -246,14 +246,14 @@ case 57: this.$ = {name:$$[$0-4], select:$$[$0-1]}; break; case 58: - yy.extend(this.$,$$[$0-7]); yy.extend(this.$,$$[$0-6]); yy.extend(this.$,$$[$0-5]); yy.extend(this.$,$$[$0-4]); - yy.extend(this.$,$$[$0-3]); yy.extend(this.$,$$[$0-2]);yy.extend(this.$,$$[$0-1]); - yy.extend(this.$,$$[$0]); - this.$ = $$[$0-7]; -/* if(yy.exists) this.$.exists = yy.exists; - delete yy.exists; - if(yy.queries) this.$.queries = yy.queries; - delete yy.queries; + yy.extend(this.$,$$[$0-7]); yy.extend(this.$,$$[$0-6]); yy.extend(this.$,$$[$0-5]); yy.extend(this.$,$$[$0-4]); + yy.extend(this.$,$$[$0-3]); yy.extend(this.$,$$[$0-2]);yy.extend(this.$,$$[$0-1]); + yy.extend(this.$,$$[$0]); + this.$ = $$[$0-7]; +/* if(yy.exists) this.$.exists = yy.exists; + delete yy.exists; + if(yy.queries) this.$.queries = yy.queries; + delete yy.queries; */ break; case 59: @@ -305,18 +305,18 @@ case 76: case 77: case 78: case 79: this.$ = {into: $$[$0]} break; case 80: - - 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}})]})}; - } + + 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 81: @@ -368,22 +368,22 @@ case 98: case 99: case 102: case 105: this.$ = $$[$0]; $$[$0].as = 'default'; break; case 108: - - var s = $$[$0]; - s = s.substr(1,s.length-2); - var x3 = s.substr(-3).toUpperCase(); - var x4 = s.substr(-4).toUpperCase(); - var r; - if(s[0] == '#') { - r = 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') { - r = new yy.FuncValue({funcid: x3, args:[new yy.StringValue({value: s}), new yy.Json({value:{headers:true}})]}); - } else if(x4=='XLSX' || x4 == 'JSON') { - r = new yy.FuncValue({funcid: x4, args:[new yy.StringValue({value: s}), new yy.Json({value:{headers:true}})]}); - } else { - throw new Error('Unknown string in FROM clause'); - }; - this.$ = r; + + var s = $$[$0]; + s = s.substr(1,s.length-2); + var x3 = s.substr(-3).toUpperCase(); + var x4 = s.substr(-4).toUpperCase(); + var r; + if(s[0] == '#') { + r = 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') { + r = new yy.FuncValue({funcid: x3, args:[new yy.StringValue({value: s}), new yy.Json({value:{headers:true}})]}); + } else if(x4=='XLSX' || x4 == 'JSON') { + r = new yy.FuncValue({funcid: x4, args:[new yy.StringValue({value: s}), new yy.Json({value:{headers:true}})]}); + } else { + throw new Error('Unknown string in FROM clause'); + }; + this.$ = r; break; case 109: @@ -570,11 +570,11 @@ case 208: this.$ = new yy.Json({value:$$[$0]}); break; case 210: - - if(!yy.queries) yy.queries = []; - yy.queries.push($$[$0-1]); - $$[$0-1].queriesidx = yy.queries.length; - this.$ = $$[$0-1]; + + if(!yy.queries) yy.queries = []; + yy.queries.push($$[$0-1]); + $$[$0-1].queriesidx = yy.queries.length; + this.$ = $$[$0-1]; break; case 211: @@ -608,7 +608,7 @@ case 227: this.$ = new yy.AggrValue({aggregatorid: $$[$0-5].toUpperCase(), expression: $$[$0-2], distinct:true, over:$$[$0]}); break; case 228: - this.$ = new yy.AggrValue({aggregatorid: $$[$0-5].toUpperCase(), expression: $$[$0-2], + this.$ = new yy.AggrValue({aggregatorid: $$[$0-5].toUpperCase(), expression: $$[$0-2], over:$$[$0]}); break; case 230: case 231: @@ -651,13 +651,13 @@ case 243: this.$ = "ARRAY"; break; case 244: - - if(alasql.aggr[$$[$0-3]]) { - this.$ = new yy.AggrValue({aggregatorid: 'REDUCE', - funcid: $$[$0-3], expression: $$[$0-1].pop() }); - } else { - this.$ = new yy.FuncValue({funcid: $$[$0-3], args: $$[$0-1]}); - }; + + if(alasql.aggr[$$[$0-3]]) { + this.$ = new yy.AggrValue({aggregatorid: 'REDUCE', + funcid: $$[$0-3], expression: $$[$0-1].pop() }); + } else { + this.$ = new yy.FuncValue({funcid: $$[$0-3], args: $$[$0-1]}); + }; break; case 245: @@ -688,25 +688,25 @@ case 254: this.$ = new yy.VarValue({variable:$$[$0]}); break; case 255: - - if(!yy.exists) yy.exists = []; - this.$ = new yy.ExistsValue({value:$$[$0-1], existsidx:yy.exists.length}); - yy.exists.push($$[$0-1]); + + if(!yy.exists) yy.exists = []; + this.$ = new yy.ExistsValue({value:$$[$0-1], existsidx:yy.exists.length}); + yy.exists.push($$[$0-1]); break; case 256: case 257: this.$ = new yy.ParamValue({param: $$[$0]}); break; case 258: - - if(typeof yy.question == 'undefined') yy.question = 0; - this.$ = new yy.ParamValue({param: yy.question++}); + + if(typeof yy.question == 'undefined') yy.question = 0; + this.$ = new yy.ParamValue({param: yy.question++}); break; case 259: - - if(typeof yy.question == 'undefined') yy.question = 0; - this.$ = new yy.ParamValue({param: yy.question++, array:true}); + + if(typeof yy.question == 'undefined') yy.question = 0; + this.$ = new yy.ParamValue({param: yy.question++, array:true}); break; case 260: @@ -782,15 +782,15 @@ case 288: this.$ = new yy.Op({left:$$[$0-2], op:'!===' , right:$$[$0]}); break; case 289: - - if(!yy.queries) yy.queries = []; - this.$ = new yy.Op({left:$$[$0-5], op:$$[$0-4] , allsome:$$[$0-3], right:$$[$0-1], queriesidx: yy.queries.length}); - yy.queries.push($$[$0-1]); + + if(!yy.queries) yy.queries = []; + this.$ = new yy.Op({left:$$[$0-5], op:$$[$0-4] , allsome:$$[$0-3], right:$$[$0-1], queriesidx: yy.queries.length}); + yy.queries.push($$[$0-1]); break; case 290: - - this.$ = new yy.Op({left:$$[$0-5], op:$$[$0-4] , allsome:$$[$0-3], right:$$[$0-1]}); + + this.$ = new yy.Op({left:$$[$0-5], op:$$[$0-4] , allsome:$$[$0-3], right:$$[$0-1]}); break; case 291: @@ -812,17 +812,17 @@ case 296: this.$ = new yy.UniOp({right: $$[$0-1]}); break; case 297: - - if(!yy.queries) yy.queries = []; - this.$ = new yy.Op({left: $$[$0-4], op:'IN', right:$$[$0-1], queriesidx: yy.queries.length}); - yy.queries.push($$[$0-1]); + + if(!yy.queries) yy.queries = []; + this.$ = new yy.Op({left: $$[$0-4], op:'IN', right:$$[$0-1], queriesidx: yy.queries.length}); + yy.queries.push($$[$0-1]); break; case 298: - - if(!yy.queries) yy.queries = []; - this.$ = new yy.Op({left: $$[$0-5], op:'NOT IN', right:$$[$0-1], queriesidx: yy.queries.length}); - yy.queries.push($$[$0-1]); + + if(!yy.queries) yy.queries = []; + this.$ = new yy.Op({left: $$[$0-5], op:'NOT IN', right:$$[$0-1], queriesidx: yy.queries.length}); + yy.queries.push($$[$0-1]); break; case 299: @@ -910,16 +910,16 @@ case 339: case 340: case 342: case 350: this.$ = $$[$0-2]; $$[$0-2].push($$[$0]) break; case 351: - - this.$ = new yy.CreateTable({table:$$[$0-4]}); - //yy.extend(this.$,$$[$0-6]); - yy.extend(this.$,$$[$0-5]); - yy.extend(this.$,$$[$0-2]); + + this.$ = new yy.CreateTable({table:$$[$0-4]}); + //yy.extend(this.$,$$[$0-6]); + yy.extend(this.$,$$[$0-5]); + yy.extend(this.$,$$[$0-2]); break; case 352: - - this.$ = new yy.CreateTable({table:$$[$0]}); + + this.$ = new yy.CreateTable({table:$$[$0]}); break; case 362: case 363: @@ -980,8 +980,8 @@ case 401: this.$ = undefined break; case 403: - - yy.extend($$[$0-1],$$[$0]); this.$ = $$[$0-1]; + + yy.extend($$[$0-1],$$[$0]); this.$ = $$[$0-1]; break; case 405: @@ -1060,7 +1060,7 @@ case 431: this.$ = new yy.CreateDatabase({engineid:$$[$0-7].toUpperCase(), databaseid:$$[$0-4], args:$$[$0-2], as:$$[$0] }); yy.extend(this.$,$$[$0-5]); break; case 432: - this.$ = new yy.CreateDatabase({engineid:$$[$0-4].toUpperCase(), + this.$ = new yy.CreateDatabase({engineid:$$[$0-4].toUpperCase(), as:$$[$0], args:[$$[$0-1]] }); yy.extend(this.$,$$[$0-2]); break; case 433: @@ -1130,14 +1130,14 @@ case 456: this.$ = new yy.ShowCreateTable({table: $$[$0-2], databaseid:$$[$0]}); break; case 457: - - this.$ = new yy.CreateTable({table:$$[$0-5],view:true,select:$$[$0],viewcolumns:$$[$0-3]}); - yy.extend(this.$,$$[$0-6]); + + this.$ = new yy.CreateTable({table:$$[$0-5],view:true,select:$$[$0],viewcolumns:$$[$0-3]}); + yy.extend(this.$,$$[$0-6]); break; case 458: - - this.$ = new yy.CreateTable({table:$$[$0-2],view:true,select:$$[$0]}); + + this.$ = new yy.CreateTable({table:$$[$0-2],view:true,select:$$[$0]}); break; case 459: @@ -1222,9 +1222,9 @@ case 510: this.$ = new yy.BeginTransaction(); break; case 511: - 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; + 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 512: @@ -1234,9 +1234,9 @@ case 513: this.$ = $$[$0]; break; case 514: - this.$ = new yy.While({expression:$$[$0-1],loopstat:$$[$0]}); - if($$[$0].exists) this.$.exists = $$[$0].exists; - if($$[$0].queries) this.$.queries = $$[$0].queries; + 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 515: @@ -1273,10 +1273,10 @@ case 530: this.$ = new yy.TruncateTable({table:$$[$0]}); break; case 531: - - 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]); + + 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 532: case 533: @@ -2383,720 +2383,720 @@ function ID(){ -/* -// -// Utilities for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -/** - Alasql utility functions - */ -var utils = alasql.utils = {}; - -/** - Return true. - Stub for non-ecisting WHERE clause, because is faster then if(whenrfn) whenfn() - @return {boolean} true - */ -function returnTrue () {return true}; - -/** - Return undefined - Stub for non-ecisting WHERE clause, because is faster then if(whenrfn) whenfn() - @return undefined - */ -function returnUndefined() {}; - -/** - Escape quotes - @param {string} s Source string - @return {string} Escaped string - */ -var escapeq = utils.escapeq = function(s) { -// console.log(s); - return s.replace(/\'/g,'\\\''); -} - - -/** - Double quotes - @param {string} s Source string - @return {string} Escaped string - */ -var escapeqq = utils.undoubleq = function(s) { - return s.replace(/(\')/g,'\'\''); -} - -/** - Replace double quotes - @param {string} s Source string - @return {string} Replaced string - */ -var doubleq = utils.doubleq = function(s) { - return s.replace(/(\'\')/g,'\\\''); -} - - -/** - Replace sigle quote to escaped single quote - @param {string} s Source string - @return {string} Replaced string - */ - var doubleqq = utils.doubleqq = function(s) { - return s.replace(/\'/g,"\'"); -} - - -var cutbom = function(s) { - if(s[0] == String.fromCharCode(65279)) s = s.substr(1); - return s; -}; - -/** - Load text file from anywhere - @param {string} path File path - @param {boolean} asy True - async call, false - sync call - @param {function} success Success function - @param {function} error Error function -*/ -var loadFile = utils.loadFile = function(path, asy, success, error) { - - if(typeof exports == 'object') { - // For Node.js - var fs = require('fs'); -// console.log(36,path); -// console.log(typeof path); - if(!path) { - 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 { - // var data = fs.readFileSync(path); - // success(data.toString()); - if(asy) { - fs.readFile(path,function(err,data){ - if(err) { - throw err; - } - success(cutbom(data.toString())); - }); - } else { - var data = fs.readFileSync(path); - success(cutbom(data.toString())); - } - } - } else if(typeof cordova == 'object') { - // console.log('CORDOVA'+path); - // console.log(cordova); -// console.log('CORDOVA'+path); - - // Cordova - - window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) { - fileSystem.root.getFile(path, {create:false}, function (fileEntry) { - -// var reader = new FileReader(); -// // console.log('READ FILE 2'); -// reader.onloadend = function(e) { -// // console.log('READ FILE 3',this.result); -// success(this.result); -// }; -// reader.readAsText(file); - - fileEntry.file(function(file){ - var fileReader = new FileReader(); - fileReader.onloadend = function(e){ - success(cutbom(this.result)); - }; - fileReader.readAsText(file); - }); - // }); - }); - }); - -/* - - var paths = path.split('/'); - var filename = paths[paths.length-1]; - var dirpath = path.substr(0,path.length-filename.length); - // console.log('CORDOVA',filename,dirpath); - //return success('[{"a":"'+filename+'"}]'); - - window.resolveLocalFileSystemURL(dirpath, function(dir) { - dir.getFile(filename, null, function(file) { - file.file(function(file) { - var reader = new FileReader(); - // console.log('READ FILE 2'); - reader.onloadend = function(e) { -// console.log('READ FILE 3',this.result); - success(this.result); - }; - reader.readAsText(file); - }); - }); - }); -*/ - } else { - // if(typeof path == "string") { - // } - if(typeof path == "string") { - // For browser read from tag - if((path.substr(0,1) == '#') && (typeof document != 'undefined')) { - var data = document.querySelector(path).textContent; - success(data); - } else { - // For browser - var xhr = new XMLHttpRequest(); - xhr.onreadystatechange = function() { - if (xhr.readyState === XMLHttpRequest.DONE) { - if (xhr.status === 200) { - if (success) - success(cutbom(xhr.responseText)); - } else { - if (error) - error(xhr); - } - } - }; - xhr.open("GET", path, asy); // Async - xhr.send(); - } - } else if(path instanceof Event) { - // console.log("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(cutbom(data)); - }; - reader.readAsText(files[0]); - } - } -}; - -/** - Load binary file from anywhere - @param {string} path File path - @param {boolean} asy True - async call, false - sync call - @param {function} success Success function - @param {function} error Error function - @return 1 for Async, data - for sync version -*/ - -var loadBinaryFile = utils.loadBinaryFile = function(path, asy, success, error) { - if(typeof exports == 'object') { - // For Node.js - var fs = require('fs'); - if(asy) { - fs.readFile(path,function(err,data){ - if(err) { - throw err; - } - var arr = new Array(); - 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 = new Array(); - for(var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]); - success(arr.join("")); - } -// 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 = new Array(); - for(var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]); - success(arr.join("")); - }; - xhr.send(); - } else if(path instanceof Event) { - // console.log("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.readAsBinaryString(files[0]); - } - }; -}; - - -var removeFile = utils.removeFile = function(path,cb) { - if(typeof exports == 'object') { - var fs = require('fs'); - fs.remove(path,cb); - } else if(typeof cordova == 'object') { - window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) { - fileSystem.root.getFile(path, {create:false}, function (fileEntry) { - fileEntry.remove(cb); - if(cb) cb(); - }, function(){ - if(cb) cb(); - }); - }); - } else { - throw new Error('You can remove files only in Node.js and Apache Cordova'); - }; -}; - - -var deleteFile = utils.deleteFile = function(path,cb){ - if(typeof exports == 'object') { - var fs = require('fs'); - fs.unlink(path, cb); - }; -}; - -var fileExists = utils.fileExists = function(path,cb){ - if(typeof exports == 'object') { - var fs = require('fs'); - fs.exists(path,cb); - } else if(typeof cordova == 'object') { - window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) { - fileSystem.root.getFile(path, {create:false}, function (fileEntry) { - cb(true); - }, function(){ - cb(false); - }); - }); -/* - function fail(){ - callback(false); - } - try { - // Cordova - var paths = path.split('/'); - var filename = paths[paths.length-1]; - var dirpath = path.substr(0,path.length-filename.length); - - window.resolveLocalFileSystemURL(dirpath, function(dir) { - dir.getFile(filename, null, function(file) { - file.file(function(file) { - callback(true); - },fail); - },fail); - },fail); - } catch(err) { - fail(); - }; -*/ - } else { - // TODO Cordova, etc. - throw new Error('You can use exists() only in Node.js or Apach Cordova'); - } -}; - -/** - Save text file from anywhere - @param {string} path File path - @param {array of objects} data Data object - @param {function} cb Callback -*/ - -var saveFile = utils.saveFile = function(path, data, cb) { - if(!path) { - alasql.options.stdout = true; - console.log(data); - if(cb) cb(); - } else { - if(typeof exports == 'object') { - // For Node.js - var fs = require('fs'); - var data = fs.writeFileSync(path,data); - if(cb) cb(); - } else if(typeof cordova == 'object') { - // For Apache Cordova - window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) { -// alasql.utils.removeFile(path,function(){ - fileSystem.root.getFile(path, {create:true}, function (fileEntry) { - fileEntry.createWriter(function(fileWriter) { - fileWriter.onwriteend = function(){ - if(cb) cb(); - }; - fileWriter.write(data); - }); - }); - // }); - }); - -/* - } else if((typeof cordova == 'object') && cordova.file) { -// console.log('saveFile 1'); - // Cordova - var paths = path.split('/'); - var filename = paths[paths.length-1]; - var dirpath = path.substr(0,path.length-filename.length); - // console.log('CORDOVA',filename,dirpath); - //return success('[{"a":"'+filename+'"}]'); - - window.resolveLocalFileSystemURL(dirpath, function(dir) { -// console.log('saveFile 2'); - - dir.getFile(filename, {create:true}, function(file) { -// console.log('saveFile 3'); - -// file.file(function(file) { -// console.log('saveFile 4'); - - file.createWriter(function(fileWriter) { - -// fileWriter.seek(fileWriter.length); - - var blob = new Blob([data], {type:'text/plain'}); - fileWriter.write(blob); - fileWriter.onwriteend = function(){ - if(cb) cb(); - }; -// console.log("ok, in theory i worked"); - }); -*/ -/* - // Corodva - function writeFinish() { - // ... your done code here... - return cb() - }; - var written = 0; - var BLOCK_SIZE = 1*1024*1024; // write 1M every time of write - function writeNext(cbFinish) { - var sz = Math.min(BLOCK_SIZE, data.length - written); - var sub = data.slice(written, written+sz); - writer.write(sub); - written += sz; - writer.onwrite = function(evt) { - if (written < data.length) - writeNext(cbFinish); - else - cbFinish(); - }; - } - writeNext(writeFinish); - } -*/ -// }); -// }); -// }); - } else { - var blob = new Blob([data], {type: "text/plain;charset=utf-8"}); - saveAs(blob, path); - if(cb) cb(); - } - }; -}; - - -// For LOAD -// var saveBinaryFile = utils.saveFile = function(path, data, cb) { -// if(typeof exports == 'object') { -// // For Node.js -// var fs = require('fs'); -// var data = fs.writeFileSync(path,data); -// } else { -// var blob = new Blob([data], {type: "text/plain;charset=utf-8"}); -// saveAs(blob, path); -// } -// }; - - -// Fast hash function - -/** - Hash string to integer number - @param {string} str Source string - @return {integer} hash number -*/ - -var hash = utils.hash = function hash(str){ - var h = 0; - if (str.length == 0) return h; - for (var i = 0; i < str.length; i++) { - h = ((h<<5)-h)+str.charCodeAt(i); - h = h & h; - } - return h; -}; - -/** - Union arrays - */ -var arrayUnion = utils.arrayUnion = function (a,b) { - var r = b.slice(0); - a.forEach(function(i) { if (r.indexOf(i) < 0) r.push(i); }); - return r; -}; - -/** - Array Difference - */ -var arrayDiff = utils.arrayDiff = function (a,b) { - return a.filter(function(i) {return b.indexOf(i) < 0;}); -}; - -/** - Arrays deep intersect (with records) - */ -var arrayIntersect = utils.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; -}; - - -/** - Arrays deep union (with records) - */ -var arrayUnionDeep = utils.arrayUnionDeep = function (a,b) { - var r = b.slice(0); - a.forEach(function(ai) { - var found = false; - - r.forEach(function(ri){ -// found = found || equalDeep(ai, ri, true); - found = found || deepEqual(ai, ri); - }); - - if(!found) { - r.push(ai); - } - }); - return r; -}; - -/** - Arrays deep union (with records) - */ -var arrayExceptDeep = utils.arrayExceptDeep = function (a,b) { - var r = []; - a.forEach(function(ai) { - var found = false; - - b.forEach(function(bi){ -// found = found || equalDeep(ai, bi, true); - found = found || deepEqual(ai, bi); - }); - - if(!found) { - r.push(ai); - } - }); - return r; -}; - -/** - Arrays deep intersect (with records) - */ -var arrayIntersectDeep = utils.arrayIntersectDeep = function(a,b) { - var r = []; - a.forEach(function(ai) { - var found = false; - - b.forEach(function(bi){ -// found = found || equalDeep(ai, bi, true); - found = found || deepEqual(ai, bi, true); - }); - - if(found) { - r.push(ai); - } - }); - return r; -}; - -/** - Deep clone obects - */ -var cloneDeep = utils.cloneDeep = function cloneDeep(obj) { - if(obj == null || typeof(obj) != 'object') - return obj; - - var temp = obj.constructor(); // changed - - for(var key in obj) { - if(obj.hasOwnProperty(key)) { - temp[key] = cloneDeep(obj[key]); - } - } - return temp; -} - -/** - Check equality of objects -*/ -var equalDeep = utils.equalDeep = function equalDeep (x, y, deep) { - if (deep) { - if (x == y) return true; - - var p; - for (p in y) { - if (typeof (x[p]) == 'undefined') { return false; } - } - - for (p in y) { - if (y[p]) { - switch (typeof (y[p])) { - case 'object': - if (!equalDeep(y[p],x[p])) { return false; } break; - case 'function': - if (typeof (x[p]) == 'undefined' || - (p != 'equals' && y[p].toString() != x[p].toString())) - return false; - break; - default: - if (y[p] != x[p]) { return false; } - } - } else { - if (x[p]) - return false; - } - } - - for (p in x) { - if (typeof (y[p]) == 'undefined') { return false; } - } - - return true; - } - return x == y; -}; - -/** - COmpare two object in deep - */ -var deepEqual = utils.deepEqual = function (x, y) { - if ((typeof x == "object" && x != null) && (typeof y == "object" && y != null)) { - if (Object.keys(x).length != Object.keys(y).length) - return false; - - for (var prop in x) { - if (y.hasOwnProperty(prop)) - { - if (! deepEqual(x[prop], y[prop])) - return false; - } - else - return false; - } - - return true; - } - else if (x !== y) - return false; - else - return true; -} - - -/** - Extend object - */ -var extend = utils.extend = function extend (a,b){ - if(typeof a == 'undefined') a = {}; - for(key in b) { - if(b.hasOwnProperty(key)) { - a[key] = b[key] - } - } - return a; -};; - -/** - Flat array by first row - */ -var flatArray = utils.flatArray = function(a) { - if(!a || a.length == 0) return []; - var key = Object.keys(a[0])[0]; - if(typeof key == 'undefined') return []; - return a.map(function(ai) {return ai[key]}); -}; - -/** - Convert array of objects to array of arrays - */ -var arrayOfArrays = utils.arrayOfArrays = function (a) { - return a.map(function(aa){ - var ar = []; - for(var key in aa) ar.push(aa[key]); - return ar; - }); -}; - -/** - Excel:convert number to Excel column, like 1 => 'A' - @param {integer} i Column number, starting with 0 - @return {string} Column name, starting with 'A' -*/ - -var xlsnc = utils.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; -}; - -/** - Excel:conver Excel column name to number - @param {integer} i Column number, like 'A' or 'BE' - @return {string} Column name, starting with 0 -*/ -var xlscn = utils.xlscn = function(s) { - var n = s.charCodeAt(0)-65; - if(s.length>1) { - n = (n+1)*26+s.charCodeAt(1)-65; -// console.log(n, s.charCodeAt(0)-65, s.charCodeAt(1)-65); - if(s.length>2) { - n = (n+1)*26+s.charCodeAt(2)-65; - } - } - return n; -}; - -var domEmptyChildren = utils.domEmptyChildren = function (container){ - var len = container.childNodes.length; - while (len--) { - container.removeChild(container.lastChild); - }; -}; - +/* +// +// Utilities for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +/** + Alasql utility functions + */ +var utils = alasql.utils = {}; + +/** + Return true. + Stub for non-ecisting WHERE clause, because is faster then if(whenrfn) whenfn() + @return {boolean} true + */ +function returnTrue () {return true}; + +/** + Return undefined + Stub for non-ecisting WHERE clause, because is faster then if(whenrfn) whenfn() + @return undefined + */ +function returnUndefined() {}; + +/** + Escape quotes + @param {string} s Source string + @return {string} Escaped string + */ +var escapeq = utils.escapeq = function(s) { +// console.log(s); + return s.replace(/\'/g,'\\\''); +} + + +/** + Double quotes + @param {string} s Source string + @return {string} Escaped string + */ +var escapeqq = utils.undoubleq = function(s) { + return s.replace(/(\')/g,'\'\''); +} + +/** + Replace double quotes + @param {string} s Source string + @return {string} Replaced string + */ +var doubleq = utils.doubleq = function(s) { + return s.replace(/(\'\')/g,'\\\''); +} + + +/** + Replace sigle quote to escaped single quote + @param {string} s Source string + @return {string} Replaced string + */ + var doubleqq = utils.doubleqq = function(s) { + return s.replace(/\'/g,"\'"); +} + + +var cutbom = function(s) { + if(s[0] == String.fromCharCode(65279)) s = s.substr(1); + return s; +}; + +/** + Load text file from anywhere + @param {string} path File path + @param {boolean} asy True - async call, false - sync call + @param {function} success Success function + @param {function} error Error function +*/ +var loadFile = utils.loadFile = function(path, asy, success, error) { + + if(typeof exports == 'object') { + // For Node.js + var fs = require('fs'); +// console.log(36,path); +// console.log(typeof path); + if(!path) { + 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 { + // var data = fs.readFileSync(path); + // success(data.toString()); + if(asy) { + fs.readFile(path,function(err,data){ + if(err) { + throw err; + } + success(cutbom(data.toString())); + }); + } else { + var data = fs.readFileSync(path); + success(cutbom(data.toString())); + } + } + } else if(typeof cordova == 'object') { + // console.log('CORDOVA'+path); + // console.log(cordova); +// console.log('CORDOVA'+path); + + // Cordova + + window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) { + fileSystem.root.getFile(path, {create:false}, function (fileEntry) { + +// var reader = new FileReader(); +// // console.log('READ FILE 2'); +// reader.onloadend = function(e) { +// // console.log('READ FILE 3',this.result); +// success(this.result); +// }; +// reader.readAsText(file); + + fileEntry.file(function(file){ + var fileReader = new FileReader(); + fileReader.onloadend = function(e){ + success(cutbom(this.result)); + }; + fileReader.readAsText(file); + }); + // }); + }); + }); + +/* + + var paths = path.split('/'); + var filename = paths[paths.length-1]; + var dirpath = path.substr(0,path.length-filename.length); + // console.log('CORDOVA',filename,dirpath); + //return success('[{"a":"'+filename+'"}]'); + + window.resolveLocalFileSystemURL(dirpath, function(dir) { + dir.getFile(filename, null, function(file) { + file.file(function(file) { + var reader = new FileReader(); + // console.log('READ FILE 2'); + reader.onloadend = function(e) { +// console.log('READ FILE 3',this.result); + success(this.result); + }; + reader.readAsText(file); + }); + }); + }); +*/ + } else { + // if(typeof path == "string") { + // } + if(typeof path == "string") { + // For browser read from tag + if((path.substr(0,1) == '#') && (typeof document != 'undefined')) { + var data = document.querySelector(path).textContent; + success(data); + } else { + // For browser + var xhr = new XMLHttpRequest(); + xhr.onreadystatechange = function() { + if (xhr.readyState === XMLHttpRequest.DONE) { + if (xhr.status === 200) { + if (success) + success(cutbom(xhr.responseText)); + } else { + if (error) + error(xhr); + } + } + }; + xhr.open("GET", path, asy); // Async + xhr.send(); + } + } else if(path instanceof Event) { + // console.log("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(cutbom(data)); + }; + reader.readAsText(files[0]); + } + } +}; + +/** + Load binary file from anywhere + @param {string} path File path + @param {boolean} asy True - async call, false - sync call + @param {function} success Success function + @param {function} error Error function + @return 1 for Async, data - for sync version +*/ + +var loadBinaryFile = utils.loadBinaryFile = function(path, asy, success, error) { + if(typeof exports == 'object') { + // For Node.js + var fs = require('fs'); + if(asy) { + fs.readFile(path,function(err,data){ + if(err) { + throw err; + } + var arr = new Array(); + 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 = new Array(); + for(var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]); + success(arr.join("")); + } +// 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 = new Array(); + for(var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]); + success(arr.join("")); + }; + xhr.send(); + } else if(path instanceof Event) { + // console.log("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.readAsBinaryString(files[0]); + } + }; +}; + + +var removeFile = utils.removeFile = function(path,cb) { + if(typeof exports == 'object') { + var fs = require('fs'); + fs.remove(path,cb); + } else if(typeof cordova == 'object') { + window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) { + fileSystem.root.getFile(path, {create:false}, function (fileEntry) { + fileEntry.remove(cb); + if(cb) cb(); + }, function(){ + if(cb) cb(); + }); + }); + } else { + throw new Error('You can remove files only in Node.js and Apache Cordova'); + }; +}; + + +var deleteFile = utils.deleteFile = function(path,cb){ + if(typeof exports == 'object') { + var fs = require('fs'); + fs.unlink(path, cb); + }; +}; + +var fileExists = utils.fileExists = function(path,cb){ + if(typeof exports == 'object') { + var fs = require('fs'); + fs.exists(path,cb); + } else if(typeof cordova == 'object') { + window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) { + fileSystem.root.getFile(path, {create:false}, function (fileEntry) { + cb(true); + }, function(){ + cb(false); + }); + }); +/* + function fail(){ + callback(false); + } + try { + // Cordova + var paths = path.split('/'); + var filename = paths[paths.length-1]; + var dirpath = path.substr(0,path.length-filename.length); + + window.resolveLocalFileSystemURL(dirpath, function(dir) { + dir.getFile(filename, null, function(file) { + file.file(function(file) { + callback(true); + },fail); + },fail); + },fail); + } catch(err) { + fail(); + }; +*/ + } else { + // TODO Cordova, etc. + throw new Error('You can use exists() only in Node.js or Apach Cordova'); + } +}; + +/** + Save text file from anywhere + @param {string} path File path + @param {array of objects} data Data object + @param {function} cb Callback +*/ + +var saveFile = utils.saveFile = function(path, data, cb) { + if(!path) { + alasql.options.stdout = true; + console.log(data); + if(cb) cb(); + } else { + if(typeof exports == 'object') { + // For Node.js + var fs = require('fs'); + var data = fs.writeFileSync(path,data); + if(cb) cb(); + } else if(typeof cordova == 'object') { + // For Apache Cordova + window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) { +// alasql.utils.removeFile(path,function(){ + fileSystem.root.getFile(path, {create:true}, function (fileEntry) { + fileEntry.createWriter(function(fileWriter) { + fileWriter.onwriteend = function(){ + if(cb) cb(); + }; + fileWriter.write(data); + }); + }); + // }); + }); + +/* + } else if((typeof cordova == 'object') && cordova.file) { +// console.log('saveFile 1'); + // Cordova + var paths = path.split('/'); + var filename = paths[paths.length-1]; + var dirpath = path.substr(0,path.length-filename.length); + // console.log('CORDOVA',filename,dirpath); + //return success('[{"a":"'+filename+'"}]'); + + window.resolveLocalFileSystemURL(dirpath, function(dir) { +// console.log('saveFile 2'); + + dir.getFile(filename, {create:true}, function(file) { +// console.log('saveFile 3'); + +// file.file(function(file) { +// console.log('saveFile 4'); + + file.createWriter(function(fileWriter) { + +// fileWriter.seek(fileWriter.length); + + var blob = new Blob([data], {type:'text/plain'}); + fileWriter.write(blob); + fileWriter.onwriteend = function(){ + if(cb) cb(); + }; +// console.log("ok, in theory i worked"); + }); +*/ +/* + // Corodva + function writeFinish() { + // ... your done code here... + return cb() + }; + var written = 0; + var BLOCK_SIZE = 1*1024*1024; // write 1M every time of write + function writeNext(cbFinish) { + var sz = Math.min(BLOCK_SIZE, data.length - written); + var sub = data.slice(written, written+sz); + writer.write(sub); + written += sz; + writer.onwrite = function(evt) { + if (written < data.length) + writeNext(cbFinish); + else + cbFinish(); + }; + } + writeNext(writeFinish); + } +*/ +// }); +// }); +// }); + } else { + var blob = new Blob([data], {type: "text/plain;charset=utf-8"}); + saveAs(blob, path); + if(cb) cb(); + } + }; +}; + + +// For LOAD +// var saveBinaryFile = utils.saveFile = function(path, data, cb) { +// if(typeof exports == 'object') { +// // For Node.js +// var fs = require('fs'); +// var data = fs.writeFileSync(path,data); +// } else { +// var blob = new Blob([data], {type: "text/plain;charset=utf-8"}); +// saveAs(blob, path); +// } +// }; + + +// Fast hash function + +/** + Hash string to integer number + @param {string} str Source string + @return {integer} hash number +*/ + +var hash = utils.hash = function hash(str){ + var h = 0; + if (str.length == 0) return h; + for (var i = 0; i < str.length; i++) { + h = ((h<<5)-h)+str.charCodeAt(i); + h = h & h; + } + return h; +}; + +/** + Union arrays + */ +var arrayUnion = utils.arrayUnion = function (a,b) { + var r = b.slice(0); + a.forEach(function(i) { if (r.indexOf(i) < 0) r.push(i); }); + return r; +}; + +/** + Array Difference + */ +var arrayDiff = utils.arrayDiff = function (a,b) { + return a.filter(function(i) {return b.indexOf(i) < 0;}); +}; + +/** + Arrays deep intersect (with records) + */ +var arrayIntersect = utils.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; +}; + + +/** + Arrays deep union (with records) + */ +var arrayUnionDeep = utils.arrayUnionDeep = function (a,b) { + var r = b.slice(0); + a.forEach(function(ai) { + var found = false; + + r.forEach(function(ri){ +// found = found || equalDeep(ai, ri, true); + found = found || deepEqual(ai, ri); + }); + + if(!found) { + r.push(ai); + } + }); + return r; +}; + +/** + Arrays deep union (with records) + */ +var arrayExceptDeep = utils.arrayExceptDeep = function (a,b) { + var r = []; + a.forEach(function(ai) { + var found = false; + + b.forEach(function(bi){ +// found = found || equalDeep(ai, bi, true); + found = found || deepEqual(ai, bi); + }); + + if(!found) { + r.push(ai); + } + }); + return r; +}; + +/** + Arrays deep intersect (with records) + */ +var arrayIntersectDeep = utils.arrayIntersectDeep = function(a,b) { + var r = []; + a.forEach(function(ai) { + var found = false; + + b.forEach(function(bi){ +// found = found || equalDeep(ai, bi, true); + found = found || deepEqual(ai, bi, true); + }); + + if(found) { + r.push(ai); + } + }); + return r; +}; + +/** + Deep clone obects + */ +var cloneDeep = utils.cloneDeep = function cloneDeep(obj) { + if(obj == null || typeof(obj) != 'object') + return obj; + + var temp = obj.constructor(); // changed + + for(var key in obj) { + if(obj.hasOwnProperty(key)) { + temp[key] = cloneDeep(obj[key]); + } + } + return temp; +} + +/** + Check equality of objects +*/ +var equalDeep = utils.equalDeep = function equalDeep (x, y, deep) { + if (deep) { + if (x == y) return true; + + var p; + for (p in y) { + if (typeof (x[p]) == 'undefined') { return false; } + } + + for (p in y) { + if (y[p]) { + switch (typeof (y[p])) { + case 'object': + if (!equalDeep(y[p],x[p])) { return false; } break; + case 'function': + if (typeof (x[p]) == 'undefined' || + (p != 'equals' && y[p].toString() != x[p].toString())) + return false; + break; + default: + if (y[p] != x[p]) { return false; } + } + } else { + if (x[p]) + return false; + } + } + + for (p in x) { + if (typeof (y[p]) == 'undefined') { return false; } + } + + return true; + } + return x == y; +}; + +/** + COmpare two object in deep + */ +var deepEqual = utils.deepEqual = function (x, y) { + if ((typeof x == "object" && x != null) && (typeof y == "object" && y != null)) { + if (Object.keys(x).length != Object.keys(y).length) + return false; + + for (var prop in x) { + if (y.hasOwnProperty(prop)) + { + if (! deepEqual(x[prop], y[prop])) + return false; + } + else + return false; + } + + return true; + } + else if (x !== y) + return false; + else + return true; +} + + +/** + Extend object + */ +var extend = utils.extend = function extend (a,b){ + if(typeof a == 'undefined') a = {}; + for(key in b) { + if(b.hasOwnProperty(key)) { + a[key] = b[key] + } + } + return a; +};; + +/** + Flat array by first row + */ +var flatArray = utils.flatArray = function(a) { + if(!a || a.length == 0) return []; + var key = Object.keys(a[0])[0]; + if(typeof key == 'undefined') return []; + return a.map(function(ai) {return ai[key]}); +}; + +/** + Convert array of objects to array of arrays + */ +var arrayOfArrays = utils.arrayOfArrays = function (a) { + return a.map(function(aa){ + var ar = []; + for(var key in aa) ar.push(aa[key]); + return ar; + }); +}; + +/** + Excel:convert number to Excel column, like 1 => 'A' + @param {integer} i Column number, starting with 0 + @return {string} Column name, starting with 'A' +*/ + +var xlsnc = utils.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; +}; + +/** + Excel:conver Excel column name to number + @param {integer} i Column number, like 'A' or 'BE' + @return {string} Column name, starting with 0 +*/ +var xlscn = utils.xlscn = function(s) { + var n = s.charCodeAt(0)-65; + if(s.length>1) { + n = (n+1)*26+s.charCodeAt(1)-65; +// console.log(n, s.charCodeAt(0)-65, s.charCodeAt(1)-65); + if(s.length>2) { + n = (n+1)*26+s.charCodeAt(2)-65; + } + } + return n; +}; + +var domEmptyChildren = utils.domEmptyChildren = function (container){ + var len = container.childNodes.length; + while (len--) { + container.removeChild(container.lastChild); + }; +}; + /** @@ -3208,7152 +3208,7163 @@ alasql.utils.uncomment = function uncomment(str) { }; -/* -// -// Database class for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - - -// Initial parameters -/** - Jison parser - */ -alasql.parser = parser; - -/** - Jison parser - @param {string} sql SQL statement - @return {object} AST (Abstract Syntax Tree) - */ -alasql.parse = function(sql) { - return parser.parse(alasql.utils.uncomment(sql)); -}; // Shortcut - -// Database Engines -/** - List of engines of external databases - */ -alasql.engines = {}; - -// Databases -/** - List of databases - */ -alasql.databases = {}; - -/** Number of databases */ -alasql.databasenum = 0; // Current database - -// Deafult options -/** - Alasql options object - */ -alasql.options = {}; -alasql.options.errorlog = false; // Log or throw error -alasql.options.valueof = false; // Use valueof in orderfn -alasql.options.dropifnotexists = false; // DROP database in any case -alasql.options.datetimeformat = 'sql'; // How to handle DATE and DATETIME types - // Another value is 'javascript' -alasql.options.casesensitive = true; // Table and column names are case sensitive and converted to lower-case -alasql.options.logtarget = 'output'; // target for log. Values: 'console', 'output', 'id' of html tag -alasql.options.logprompt = true; // Print SQL at log - -//alasql.options.worker = false; -// Variables -alasql.vars = {}; -alasql.declares = {}; - -// AUTOCOMMIT ON | OFF -alasql.options.autocommit = true; - -alasql.options.cache = true; - -alasql.prompthistory = []; - -alasql.from = {}; // FROM functions -alasql.into = {}; // INTO functions - -alasql.fn = {}; -alasql.aggr = {}; - -alasql.busy = 0; - -// Cache -alasql.MAXSQLCACHESIZE = 10000; -alasql.DEFAULTDATABASEID = 'alasql'; - -/* WebWorker */ -alasql.lastid = 0; -alasql.buffer = {}; - -/** - Select current database - @param {string} databaseid Selected database identificator - */ -alasql.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(); -}; - -// Run one statement -/** - Run SQL statement on current database - */ -alasql.exec = function (sql, params, cb, scope) { - delete alasql.error; - 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); - } -} - -/** - Run SQL statement on specific database - */ -alasql.dexec = function (databaseid, sql, params, cb, scope) { - var db = alasql.databases[databaseid]; -// if(db.databaseid != databaseid) console.trace('got!'); -// console.log(3,db.databaseid,databaseid); - - // Create hash - if(alasql.options.cache) { - var 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(ast.statements.length == 0) return 0; - else if(ast.statements.length == 1) { - if(ast.statements[0].compile) { - -// Compile and Execute - var statement = ast.statements[0].compile(databaseid); - 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 { -// console.log(ast.statements[0]); - 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 - */ -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 alasql.MAXSQLCACHESIZE) { -// this.resetSqlCache(); -// } -// }; -// return statement; -// } - -// SQL.js compatibility method -//Database.prototype.prepare = Database.prototype.compile; - - -// Added for compatibility with WebSQL - - - - - -/* -// -// 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 - */ - -var Transaction = alasql.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 -// console.log(this); - return this; -}; - -// Main class - - -// Commit - -/** - Commit transaction - */ -Transaction.prototype.commit = function() { - this.commited = true; - alasql.databases[this.databaseid].dbversion = Date.now(); - delete this.bank; -}; - -// Rollback -/** - Rollback transaction - */ -Transaction.prototype.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'); - } -}; - -// Transactions stub - -/** - Execute SQL statement - @param {string} sql SQL statement - @param {object} params Parameters - @param {function} cb Callback function - @return result - */ -Transaction.prototype.exec = function(sql, params, cb) { -// console.log(this.databaseid); - return alasql.dexec(this.databaseid,sql,params,cb); -}; - -Transaction.prototype.executeSQL = Transaction.prototype.exec; - -/* -Transaction.prototype.query = Database.prototype.exec; -Transaction.prototype.run = Database.prototype.exec; -Transaction.prototype.queryArray = function(sql, params, cb) { - return flatArray(this.exec(sql, params, cb)); -} - -Transaction.prototype.queryArrayOfArrays = function(sql, params, cb) { - return arrayOfArrays(this.exec(sql, params, cb)); -} - -Transaction.prototype.querySingle = function(sql, params, cb) { - return this.exec(sql, params, cb)[0]; -} -Transaction.prototype.queryValue = function(sql, params, cb) { - var res = this.querySingle(sql, params, cb); - return res[Object.keys(res)[0]]; -} -*/ - - -/* -// -// Table class for Alasql.js -// Date: 14.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -// Table class -var Table = alasql.Table = function(params){ - // Columns - this.columns = []; - this.xcolumns = {}; - // Data array - this.data = []; - - this.inddefs = {}; - this.indices = {}; - - this.uniqs = {}; - this.uniqdefs = {}; - - extend(this,params); -}; - - -// View = function(){ -// this.data = []; -// this.columns = []; -// this.ixcolumns = {}; -// this.ixdefs = {}; -// this.indices = {}; -// }; - -// alasql.View = View; - -Table.prototype.indexColumns = function() { - var self = this; - self.xcolumns = {}; - self.columns.forEach(function(col){ - self.xcolumns[col.columnid] = col; - }); -} - - - - -/* -// -// View class for Alasql.js -// Date: 14.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -// Table class -var View = alasql.View = function(params){ - // Columns - this.columns = []; - this.xcolumns = {}; - // Data array - this.query = []; - - extend(this,params); -}; - -// View = function(){ -// this.data = []; -// this.columns = []; -// this.ixcolumns = {}; -// this.ixdefs = {}; -// this.indices = {}; -// }; - -// alasql.View = View; - - - - -/* -// -// Query class for Alasql.js -// Date: 14.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -// Table class - -/** - @class Query Main query class - */ -var Query = alasql.Query = function(params){ - this.alasql = alasql; -// console.log(12,alasql); - // Columns - this.columns = []; - this.xcolumns = {}; - this.selectGroup = []; - this.groupColumns = {}; - // Data array - extend(this,params); -}; - -/** - @class Recordset data object - */ -var Recordset = alasql.Recordset = function(params){ - // Data array - extend(this,params); -}; - - -// View = function(){ -// this.data = []; -// this.columns = []; -// this.ixcolumns = {}; -// this.ixdefs = {}; -// this.indices = {}; -// }; - -// alasql.View = View; - - - - -/* -// -// Parser helper for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -var yy = parser.yy = {}; - -// Utility -yy.extend = extend; -// Option for case sensitive -yy.casesensitive = alasql.options.casesensitive; - -// Base class for all yy classes -var Base = yy.Base = function (params) { return yy.extend(this, params); }; - -Base.prototype.toString = function() {} -Base.prototype.toType = function() {} -Base.prototype.toJavaScript = function() {} - -//var BaseClause = yy,BaseClause = function (params) { return yy.extend(this, params); }; -Base.prototype.compile = returnUndefined; -Base.prototype.exec = function() {} - -//var BaseStatement = yy,BaseStatement = function (params) { return yy.extend(this, params); }; -Base.prototype.compile = returnUndefined; -Base.prototype.exec = function() {} - - - - -/* -// -// Statements class for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -// Statements container -yy.Statements = function(params) { return yy.extend(this, params); }; - -yy.Statements.prototype.toString = function () { - return this.statements.map(function(st){return st.toString()}).join(';'+NL()); -}; - -// Compile array of statements into single statement -yy.Statements.prototype.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; - } - } -}; - - - -// Main query procedure -function queryfn(query,oldscope,cb, A,B) { - var ms; - query.sourceslen = query.sources.length; - var slen = query.sourceslen; - query.query = query; // TODO Remove to prevent memory leaks - query.A = A; - query.B = B; -// console.log(arguments); - query.cb = cb; - query.oldscope = oldscope; - - // Run all subqueries before main statement - if(query.queriesfn) { - query.sourceslen += query.queriesfn.length; - slen += query.queriesfn.length; - - query.queriesdata = []; - -// console.log(8); - query.queriesfn.forEach(function(q,idx){ -// if(query.explain) ms = Date.now(); -//console.log(18,idx); -// var res = flatArray(q(query.params,null,queryfn2,(-idx-1),query)); - -// var res = flatArray(queryfn(q.query,null,queryfn2,(-idx-1),query)); -// console.log(A,B); -// console.log(q); - q.query.params = query.params; -// query.queriesdata[idx] = - - if(false) { - queryfn(q.query,query.oldscope,queryfn2,(-idx-1),query); - } else { - queryfn2([],(-idx-1),query); - } - -// console.log(27,q); - - -// query.explaination.push({explid: query.explid++, description:'Query '+idx,ms:Date.now()-ms}); -// query.queriesdata[idx] = res; -// return res; - }); -// console.log(9,query.queriesdata.length); -// console.log(query.queriesdata[0]); - } - - var scope; - if(!oldscope) scope = {}; - else scope = cloneDeep(oldscope); - query.scope = scope; - - // First - refresh data sources - - var result; - query.sources.forEach(function(source, idx){ -// source.data = query.database.tables[source.tableid].data; -// console.log(666,idx); - source.query = query; - var rs = source.datafn(query, query.params, queryfn2, idx, alasql); -// console.log(333,rs); - if(typeof rs != undefined) { - // TODO - this is a hack: check if result is array - check all cases and - // make it more logical - if((query.intofn || query.intoallfn) && rs instanceof Array) rs = rs.length; - result = rs; - } -// console.log(444,result); -// -// Ugly hack to use in query.wherefn and source.srcwherefns functions -// constructions like this.queriesdata['test']. -// I can elimite it with source.srcwherefn.bind(this)() -// but it may be slow. -// - source.queriesdata = query.queriesdata; - }); - if(slen == 0) result = queryfn3(query); - return result; -}; - -function queryfn2(data,idx,query) { - -//console.log(56,arguments); -// console.log(78,data, idx,query); -//console.trace(); - - if(idx>=0) { - var source = query.sources[idx]; - source.data = data; - if(typeof source.data == 'function') { - source.getfn = source.data; - source.dontcache = source.getfn.dontcache; - - // var prevsource = query.sources[h-1]; - if(source.joinmode == 'OUTER' || source.joinmode == 'RIGHT' || source.joinmode == 'ANTI') { - source.dontcache = false; - } - source.data = {}; - } - } else { - // subqueries -// console.log("queriesdata",data, flatArray(data)); - query.queriesdata[-idx-1] = flatArray(data); -// console.log(98,query.queriesdata); -// console.log(79,query.queriesdata); - } - - query.sourceslen--; - if(query.sourceslen>0) return; - - return queryfn3(query); -}; - -function queryfn3(query) { -//console.log(55,query); - - - var scope = query.scope; - // Preindexation of data sources -// if(!oldscope) { - preIndex(query); -// } - - // query.sources.forEach(function(source) { - // console.log(source.data); - // }); - - // Prepare variables - query.data = []; - query.xgroups = {}; - query.groups = []; - - // Level of Joins - var h = 0; - - // Start walking over data - doJoin(query, scope, h); - -//console.log(85,query.data[0]); - - // If groupping, then filter groups with HAVING function -// console.log(query.havingfns); - if(query.groupfn) { - query.data = []; - if(query.groups.length == 0) { - var g = {}; - if(query.selectGroup.length>0) { -// console.log(query.selectGroup); - query.selectGroup.forEach(function(sg){ - if(sg.aggregatorid == "COUNT" || sg.aggregatorid == "SUM") { - g[sg.nick] = 0; - } else { - g[sg.nick] = undefined; - } - }); - }; - query.groups = [g]; -// console.log(); - }; - // console.log('EMPTY',query.groups); - // debugger; - // if(false && (query.groups.length == 1) && (Object.keys(query.groups[0]).length == 0)) { - // console.log('EMPTY',query.groups); - // } else { - for(var i=0,ilen=query.groups.length;i 0) { - for(var i=0,ilen=query.data.length;i 0 && source.optimization == 'ix' && source.onleftfn && source.onrightfn) { - // If there is no table.indices - create it - if(source.databaseid && alasql.databases[source.databaseid].tables[source.tableid]) { - if(!alasql.databases[source.databaseid].tables[source.tableid].indices) query.database.tables[source.tableid].indices = {}; - // Check if index already exists - var ixx = alasql.databases[source.databaseid].tables[source.tableid].indices[hash(source.onrightfns+'`'+source.srcwherefns)]; - if( !alasql.databases[source.databaseid].tables[source.tableid].dirty && ixx) { - source.ix = ixx; - } - }; - if(!source.ix) { - source.ix = {}; - // Walking over source data - var scope = {}; - var i = 0; - var ilen = source.data.length; - var dataw; -// while(source.getfn i=query.sources.length) { -//console.log(query.wherefns); - // Then apply where and select -// console.log(query); - if(query.wherefn(scope,query.params, alasql)) { - -// console.log("scope",scope.schools); - -// var res = query.selectfn(scope, query.params, alasql); -// console.log("last",res); - // If there is a GROUP BY then pipe to groupping function - if(query.groupfn) { - query.groupfn(scope, query.params, query.alasql) - } else { - query.data.push(query.selectfn(scope, query.params, alasql)); - } - } - } else if(query.sources[h].applyselect) { -// console.log('APPLY',scope); -// console.log('scope1',scope); -// console.log(scope); - var source = query.sources[h]; - source.applyselect(query.params, function(data){ - if(data.length > 0) { - // console.log('APPLY CB'); - for(var i=0;i0) { - s += NL()+ID()+K('GROUP BY')+' '+this.group.map(function(grp){ - return grp.toString(); - }).join(', '); - }; - if(this.having) s += NL()+ID()+K('HAVING')+' '+this.having.toString(); - - if(this.order && this.order.length>0) { - s += NL()+ID()+K('ORDER BY')+' '+this.order.map(function(ord){ - return ord.toString(); - }).join(', '); - }; - if(this.limit) s += NL()+ID()+K('LIMIT')+' '+this.limit.value; - if(this.offset) s += NL()+ID()+K('OFFSET')+' '+this.offset.value; - if(this.union) s += NL()+K('UNION')+NL()+this.union.toString(); - if(this.unionall) s += NL()+K('UNION ALL')+NL()+this.unionall.toString(); - if(this.except) s += NL()+K('EXCEPT')+NL()+this.except.toString(); - if(this.intersect) s += NL()+K('INTERSECT')+NL()+this.intersect.toString(); - return s; -}; - -/** - Select statement in expression - */ -yy.Select.prototype.toJavaScript = function(context, tableid, defcols) { -// console.log('Expression',this); -// if(this.expression.reduced) return 'true'; -// return this.expression.toJavaScript(context, tableid, defcols); -// console.log('Select.toJS', 81, this.queriesidx); -// var s = 'this.queriesdata['+(this.queriesidx-1)+'][0]'; -//console.log(this); - var s = 'alasql.utils.flatArray(this.queriesfn['+(this.queriesidx-1)+'](this.params,null,'+context+'))[0]'; -// s = '(console.log(this.queriesfn[0]),'+s+')'; - - return s; -}; - - -// Compile SELECT statement -yy.Select.prototype.compile = function(databaseid) { - var db = alasql.databases[databaseid]; - // Create variable for query - var query = new Query(); - - query.removeKeys = []; - - 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); - // 3. Compile SELECT clause - - this.compileSelectGroup0(query); - - if(this.group || query.selectGroup.length>0) { - query.selectgfns = this.compileSelectGroup1(query); - } else { - query.selectfns = this.compileSelect1(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); - - 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; - - // 8. Compile ORDER BY clause - if(this.order) query.orderfn = this.compileOrder(query); - -// TOP - 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 - 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 -// console.log(this.into); - if(this.into) { - if(this.into instanceof yy.Table) { - if(alasql.options.autocommit && alasql.databases[this.into.databaseid||databaseid].engineid) { - 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 { - query.intofns = - 'alasql.databases[\''+(this.into.databaseid||databaseid)+'\'].tables'+ - '[\''+this.into.tableid+'\'].data.push(r);'; - } - } else if(this.into instanceof yy.VarValue) { - query.intoallfns = 'alasql.vars["'+this.into.variable+'"]=this.data;res=1;if(cb)res=cb(res);return res;'; - } else if (this.into instanceof yy.FuncValue) { - -/* - query.intofns = 'alasql.into[\''+this.into.funcid+'\']('; - var ss = ['r','i']; - if(this.into.args && this.into.args.length>0 ) - this.into.args.forEach(function(arg){ - ss.push(arg.toJavaScript()); - }); - query.intofns += ss.join(',')+')'; -*/ - var qs = 'alasql.into[\''+this.into.funcid.toUpperCase()+'\']('; - if(this.into.args && this.into.args.length>0 ) { - qs += this.into.args[0].toJavaScript()+','; - if(this.into.args.length > 1) { - qs += this.into.args[1].toJavaScript()+','; - } else { - qs += 'null,'; - } - } else { - qs += 'null, null,' - } - query.intoallfns = qs+'this.data,columns,cb)'; -//console.log('999'); - - - - - } else if (this.into instanceof yy.ParamValue) { -// console.log(184); -// query.intofns = 'params[\''+this.into.param+"\'](r)"; - query.intofns = "params['"+this.into.param+"'].push(r)"; - - }; -// console.log(query.intofns); - if(query.intofns) { - query.intofn = new Function("r,i,params,alasql",query.intofns); - }; - - if(query.intoallfns) { -// console.log(query.intoallfns); - query.intoallfn = new Function("columns,cb,alasql",query.intoallfns); - } - - } -//console.log(query); - - // Now, compile all togeather into one function with query object in scope - var statement = function(params, cb, oldscope) { - query.params = params; - var res1 = queryfn(query,oldscope,function(res){ - -//console.log(res[0].schoolid); -//console.log(184,res); - var res2 = modify(query, res); - - - if(cb) cb(res2); -//console.log(8888,res2); - return res2; - - }); -//console.log(9999,res1); - -// if(typeof res1 != 'undefined') res1 = modify(query,res1); - - return res1; - - }; - -// statement.dbversion = ; -// console.log(statement.query); -//console.log(202,statement); - statement.query = query; - return statement; -}; - -function modify(query, res) { - if(query.modifier == 'VALUE') { -// console.log(222,res); - if(res.length > 0) { - var key; - if(query.columns && query.columns.length > 0) key = query.columns[0].columnid; - else key = Object.keys(res[0])[0]; - res = res[0][key]; - } else { - res = undefined; - } - } if(query.modifier == 'ROW') { - if(res.length > 0) { - var key; - if(query.columns && query.columns.length > 0) key = query.columns[0].columnid; - else key = Object.keys(res[0])[0]; - var a = []; - for(var key in res[0]) { - a.push(res[0][key]); - }; - res = a; - } else { - res = undefined; - } - } if(query.modifier == 'COLUMN') { - var ar = []; - if(res.length > 0) { - var key; - if(query.columns && query.columns.length > 0) key = query.columns[0].columnid; - else key = Object.keys(res[0])[0]; - for(var i=0, ilen=res.length; i 0) { - key = query.columns[0].columnid; - val = query.columns[1].columnid; - } else { - var okeys = Object.keys(res[0]); - key = okeys[0]; - val = okeys[1]; - } - for(var i=0, ilen=res.length; i 0) key = query.columns[0].columnid; - else key = Object.keys(res[0])[0]; - var s = ''; - for(var i=0, ilen=res.length; i0) { - // s += tq.args.map(function(arg){ - // return arg.toJavaScript(); - // }).concat('cb,idx,query').join(','); - // } - // if(tq.args && tq.args.length>0) { - // s += tq.args.map(function(arg){ - // return arg.toJavaScript(); - // }).concat().join(','); - // } - if(tq.args && tq.args.length>0) { - if(tq.args[0]) { - s += tq.args[0].toJavaScript('query.oldscope')+','; - } else { - s += 'null,'; - }; - if(tq.args[1]) { - s += tq.args[1].toJavaScript('query.oldscope')+','; - } else { - s += 'null,'; - }; - } else { - s += 'null,null,' - } - s += 'cb,idx,query'; - s += ');/*if(cb)res=cb(res,idx,query);*/return res'; -// console.log(s); - source.datafn = new Function('query, params, cb, idx, alasql',s); - - } else if(tq instanceof yy.FromData) { - source.datafn = function(query,params,cb,idx, alasql) { - var res = tq.data; - if(cb) res = cb(res,idx,query); - return res; - } - } else { - throw new Error('Wrong table at FROM'); - } -// source.data = alasql.databases[source.databaseid].tables[source.tableid].data; - query.sources.push(source); - - }); - // TODO Add joins - query.defaultTableid = query.sources[0].alias; -//console.log(query.defaultTableid); -}; - -alasql.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; i0) { - // s += tq.args.map(function(arg){ - // return arg.toJavaScript(); - // }).concat('cb,idx,query').join(','); - // } - // if(tq.args && tq.args.length>0) { - // s += tq.args.map(function(arg){ - // return arg.toJavaScript(); - // }).concat().join(','); - // } - if(jn.args && jn.args.length>0) { - if(jn.args[0]) { - s += jn.args[0].toJavaScript('query.oldscope')+','; - } else { - s += 'null,'; - }; - if(jn.args[1]) { - s += jn.args[1].toJavaScript('query.oldscope')+','; - } else { - s += 'null,'; - }; - } else { - s += 'null,null,' - } - s += 'cb,idx,query'; - s += ');/*if(cb)res=cb(res,idx,query);*/return res'; -// console.log(s); - source.datafn = new Function('query, params, cb, idx, alasql',s); - - query.aliases[source.alias] = {type:'funcvalue'}; - } -/* - } else if(tq instanceof yy.Select) { - query.aliases[alias] = {type:'subquery'}; - } else if(tq instanceof yy.ParamValue) { - query.aliases[alias] = {type:'paramvalue'}; - } else if(tq instanceof yy.FuncValue) { - query.aliases[alias] = {type:'paramvalue'}; - } else { - throw new Error('Wrong table at FROM'); - } -*/ - var alias = source.alias; - - // Test NATURAL-JOIN - if(jn.natural) { - if(jn.using || jn.on) { - throw new Error('NATURAL JOIN cannot have USING or ON clauses'); - } else { -// source.joinmode == "INNER"; - if(query.sources.length > 0) { - var prevSource = query.sources[query.sources.length-1]; - var prevTable = alasql.databases[prevSource.databaseid].tables[prevSource.tableid]; - var table = alasql.databases[source.databaseid].tables[source.tableid]; - - if(prevTable && table) { - var c1 = prevTable.columns.map(function(col){return col.columnid}); - var c2 = table.columns.map(function(col){return col.columnid}); - jn.using = arrayIntersect(c1,c2).map(function(colid){return {columnid:colid}}); -// console.log(jn.using); - } else { - throw new Error('In this version of Alasql NATURAL JOIN '+ - 'works for tables with predefined columns only'); - }; - } - } - } - - - - - - - - if(jn.using) { - var prevSource = query.sources[query.sources.length-1]; -// console.log(query.sources[0],prevSource,source); - source.onleftfns = jn.using.map(function(col){ -// console.log(141,colid); - return "p['"+(prevSource.alias||prevSource.tableid)+"']['"+col.columnid+"']"; - }).join('+"`"+'); - - - - source.onleftfn = new Function('p,params,alasql','return '+source.onleftfns); - - source.onrightfns = jn.using.map(function(col){ - return "p['"+(source.alias||source.tableid)+"']['"+col.columnid+"']"; - }).join('+"`"+'); - source.onrightfn = new Function('p,params,alasql','return '+source.onrightfns); - source.optimization = 'ix'; -// console.log(151,source.onleftfns, source.onrightfns); -// console.log(source); - } else if(jn.on) { -//console.log(jn.on); - if(jn.on instanceof yy.Op && jn.on.op == '=' && !jn.on.allsome) { -// console.log('ix optimization', jn.on.toJavaScript('p',query.defaultTableid) ); - source.optimization = 'ix'; - // source.onleftfns = jn.on.left.toJavaScript('p',query.defaultTableid); - // source.onleftfn = new Function('p', 'return '+source.onleftfns); - // source.onrightfns = jn.on.right.toJavaScript('p',query.defaultTableid); - // source.onrightfn = new Function('p', 'return '+source.onrightfns); - - var lefts = ''; - var rights = ''; - var middles = ''; - var middlef = false; - // Test right and left sides - var ls = jn.on.left.toJavaScript('p',query.defaultTableid,query.defcols); - var rs = jn.on.right.toJavaScript('p',query.defaultTableid,query.defcols); - - if((ls.indexOf("p['"+alias+"']")>-1) && !(rs.indexOf("p['"+alias+"']")>-1)){ - if((ls.match(/p\[\'.*?\'\]/g)||[]).every(function(s){ - return s == "p['"+alias+"']"})) { rights = ls; } - else { middlef = true }; - - } else if(!(ls.indexOf("p['"+alias+"']")>-1) && (rs.indexOf("p['"+alias+"']")>-1)){ - if((rs.match(/p\[\'.*?\'\]/g)||[]).every(function(s){ - return s == "p['"+alias+"']"})) { lefts = ls; } - else { middlef = true }; - } else { - middlef = true; - } - -// console.log(alias, 1,lefts, rights, middlef); - - if((rs.indexOf("p['"+alias+"']")>-1) && !(ls.indexOf("p['"+alias+"']")>-1)){ - if((rs.match(/p\[\'.*?\'\]/g)||[]).every(function(s){ - return s == "p['"+alias+"']"})) { rights = rs; } - else { middlef = true }; - } else if(!(rs.indexOf("p['"+alias+"']")>-1) && (ls.indexOf("p['"+alias+"']")>-1)){ - if((ls.match(/p\[\'.*?\'\]/g)||[]).every(function(s){ - return s == "p['"+alias+"']"})) { lefts = rs; } - else { middlef = true }; - } else { - middlef = true; - } - -// console.log(alias, 2,lefts, rights, middlef); - - if(middlef) { -// middles = jn.on.toJavaScript('p',query.defaultTableid); -// } else { - rights = ''; - lefts = ''; - middles = jn.on.toJavaScript('p',query.defaultTableid,query.defcols); - source.optimization = 'no'; - // What to here? - } - - source.onleftfns = lefts; - source.onrightfns = rights; - source.onmiddlefns = middles || 'true'; -// console.log(source.onleftfns, '-',source.onrightfns, '-',source.onmiddlefns); - - source.onleftfn = new Function('p,params,alasql', 'return '+source.onleftfns); - source.onrightfn = new Function('p,params,alasql', 'return '+source.onrightfns); - source.onmiddlefn = new Function('p,params,alasql', 'return '+source.onmiddlefns); - -// } else if(jn.on instanceof yy.Op && jn.on.op == 'AND') { -// console.log('join on and ',jn); - - } else { -// console.log('no optimization'); - source.optimization = 'no'; -// source.onleftfn = returnTrue; -// source.onleftfns = "true"; - source.onmiddlefns = jn.on.toJavaScript('p',query.defaultTableid,query.defcols); - source.onmiddlefn = new Function('p,params,alasql','return '+jn.on.toJavaScript('p',query.defaultTableid,query.defcols)); - }; -// console.log(source.onleftfns, source.onrightfns, source.onmiddlefns); - - // Optimization function - }; - -// source.data = alasql.databases[source.databaseid].tables[source.tableid].data; -//console.log(source, jn); - // TODO SubQueries -/* if(source.joinmode == 'RIGHT') { - var prevSource = query.sources.pop(); - if(prevSource.joinmode == 'INNER') { - prevSource.joinmode = 'LEFT'; - var onleftfn = prevSource.onleftfn; - var onleftfns = prevSource.onleftfns; - var onrightfn = prevSource.onrightfn; - var onrightfns = prevSource.onrightfns; - var optimization = prevSource.optimization; - - prevSource.onleftfn = source.onrightfn; - prevSource.onleftfns = source.onrightfns; - prevSource.onrightfn = source.onleftfn; - prevSource.onrightfns = source.onleftfns; - prevSource.optimization = source.optimization; - - source.onleftfn = onleftfn; - source.onleftfns = onleftfns; - source.onrightfn = onrightfn; - source.onrightfns = onrightfns; - source.optimization = optimization; - - source.joinmode = 'INNER'; - query.sources.push(source); - query.sources.push(prevSource); - } else { - throw new Error('Do not know how to process this SQL'); - } - } else { - query.sources.push(source); - } -*/ - query.sources.push(source); - }; - }); -// console.log('sources',query.sources); -} - +/* +// +// Database class for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ -yy.Select.prototype.compileWhere = function(query) { - if(this.where) { - if(typeof this.where == "function") { - return this.where; - } else { - s = this.where.toJavaScript('p',query.defaultTableid,query.defcols); - query.wherefns = s; -// console.log(s); - return new Function('p,params,alasql','return '+s); - } - } else return function(){return true}; -}; +// Initial parameters +/** + Jison parser + */ +alasql.parser = parser; +/** + Jison parser + @param {string} sql SQL statement + @return {object} AST (Abstract Syntax Tree) + */ +alasql.parse = function(sql) { + return parser.parse(alasql.utils.uncomment(sql)); +}; // Shortcut +// Database Engines +/** + List of engines of external databases + */ +alasql.engines = {}; -yy.Select.prototype.compileWhereJoins = function(query) { - return; +// Databases +/** + List of databases + */ +alasql.databases = {}; - // TODO Fix Where optimization - //console.log(query); +/** Number of databases */ +alasql.databasenum = 0; // Current database - optimizeWhereJoin(query, this.where.expression); +// Deafult options +/** + Alasql options object + */ +alasql.options = {}; +alasql.options.errorlog = false; // Log or throw error +alasql.options.valueof = false; // Use valueof in orderfn +alasql.options.dropifnotexists = false; // DROP database in any case +alasql.options.datetimeformat = 'sql'; // How to handle DATE and DATETIME types + // Another value is 'javascript' +alasql.options.casesensitive = true; // Table and column names are case sensitive and converted to lower-case +alasql.options.logtarget = 'output'; // target for log. Values: 'console', 'output', 'id' of html tag +alasql.options.logprompt = true; // Print SQL at log - //for sources compile wherefs - query.sources.forEach(function(source) { - if(source.srcwherefns) { - source.srcwherefn = new Function('p,params,alasql','return '+source.srcwherefns); - }; - if(source.wxleftfns) { - source.wxleftfn = new Function('p,params,alasql','return '+source.wxleftfns); - }; - if(source.wxrightfns) { - source.wxrightfn = new Function('p,params,alasql','return '+source.wxrightfns); - }; -// console.log(source.alias, source.wherefns) -// console.log(source); - }); -}; +//alasql.options.worker = false; +// Variables +alasql.vars = {}; +alasql.declares = {}; -function optimizeWhereJoin (query, ast) { - if(!ast) return false; - if(!(ast instanceof yy.Op)) return; - if(ast.op != '=' && ast.op != 'AND') return; - if(ast.allsome) return; +// AUTOCOMMIT ON | OFF +alasql.options.autocommit = true; - var s = ast.toJavaScript('p',query.defaultTableid,query.defcols); - var fsrc = []; - query.sources.forEach(function(source,idx) { - // Optimization allowed only for tables only - if(source.tableid) { - // This is a good place to remove all unnecessary optimizations - if(s.indexOf('p[\''+source.alias+'\']')>-1) fsrc.push(source); - }; - }); -//console.log(fsrc.length); -// if(fsrc.length < query.sources.length) return; -// console.log(ast); -// console.log(s); -// console.log(fsrc.length); - if(fsrc.length == 0) { -// console.log('no optimization, can remove this part of ast'); - return; - } else if (fsrc.length == 1) { +alasql.options.cache = true; - if(!(s.match(/p\[\'.*?\'\]/g)||[]) - .every(function(s){ - return s == "p['"+fsrc[0].alias+"']"})) { - return; - // This is means, that we have column from parent query - // So we return without optimization - } +alasql.prompthistory = []; - var src = fsrc[0]; // optmiization source - src.srcwherefns = src.srcwherefns ? src.srcwherefns+'&&'+s : s; +alasql.from = {}; // FROM functions +alasql.into = {}; // INTO functions - if((ast instanceof yy.Op) && (ast.op == '=' && !ast.allsome)) { - if(ast.left instanceof yy.Column) { - var ls = ast.left.toJavaScript('p',query.defaultTableid,query.defcols); - var rs = ast.right.toJavaScript('p',query.defaultTableid,query.defcols); - if(rs.indexOf('p[\''+fsrc[0].alias+'\']') == -1) { - fsrc[0].wxleftfns = ls; - fsrc[0].wxrightfns = rs; - } - } if(ast.right instanceof yy.Column) { - var ls = ast.left.toJavaScript('p',query.defaultTableid,query.defcols); - var rs = ast.right.toJavaScript('p',query.defaultTableid,query.defcols); - if(ls.indexOf('p[\''+fsrc[0].alias+'\']') == -1) { - fsrc[0].wxleftfns = rs; - fsrc[0].wxrightfns = ls; - } +alasql.fn = {}; +alasql.aggr = {}; + +alasql.busy = 0; + +// Cache +alasql.MAXSQLCACHESIZE = 10000; +alasql.DEFAULTDATABASEID = 'alasql'; + +/* WebWorker */ +alasql.lastid = 0; +alasql.buffer = {}; + +/** + Select current database + @param {string} databaseid Selected database identificator + */ +alasql.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(); +}; + +// Run one statement +/** + Run SQL statement on current database + */ +alasql.exec = function (sql, params, cb, scope) { + delete alasql.error; + 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); + } +} + +/** + Run SQL statement on specific database + */ +alasql.dexec = function (databaseid, sql, params, cb, scope) { + var db = alasql.databases[databaseid]; +// if(db.databaseid != databaseid) console.trace('got!'); +// console.log(3,db.databaseid,databaseid); + + // Create hash + if(alasql.options.cache) { + var 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(ast.statements.length == 0) return 0; + else if(ast.statements.length == 1) { + if(ast.statements[0].compile) { + +// Compile and Execute + var statement = ast.statements[0].compile(databaseid); + 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 { +// console.log(ast.statements[0]); + alasql.precompile(ast.statements[0],alasql.useid,params); + var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope); + return res; } - ast.reduced = true; // To do not duplicate wherefn and srcwherefn - return; } else { - if(ast.op = 'AND') { - optimizeWhereJoin(query,ast.left); - optimizeWhereJoin(query,ast.right); - } + // 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) { + var useid = alasql.useid; + if(useid != databaseid) alasql.use(databaseid); + var res = []; + for (var i=0, ilen=ast.statements.length; i 0) tmpid = query.sources[0].alias; -// console.log(new yy.Column({columnid:colid}).toJavaScript('p',query.sources[0].alias)); -// query.selectfns += 'r[\''+colid+'\']=p[\''+tmpid+'\'][\''+colid+'\'];'; -//console.log(374, colid); - if(Object.keys(query.selectColumns).length != 0) query.removeKeys.push(colid); - query.selectfns += 'r[\''+escapeq(colid)+'\']='+(new yy.Column({columnid:colid}).toJavaScript('p',tmpid))+';'; - } - }); -}; - - // Create negative array - - var s = ''; -// s+= query.selectfns; - - allgroup.forEach(function(agroup) { -//console.log(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 -// else return "r['"+columnid+"']"; - else return coljs; - }); - if(rg.length == 0) rg = ["''"]; - - // console.log('rg',rg); - - s += rg.join('+"`"+'); - s += '];if(!g) {this.groups.push((g=this.xgroups['; - s += rg.join('+"`"+'); - s += '] = {'; -// s += ']=r'; - s += agroup.map(function(col2){ - var columnid = col2.split('\t')[0]; - var coljs = col2.split('\t')[1]; - - if(columnid == '') return ''; - else return "'"+columnid+"':"+coljs+","; - }).join(''); - - var neggroup = arrayDiff(allgroups,agroup); - -// console.log(neggroup); - - s += neggroup.map(function(col2){ - var columnid = col2.split('\t')[0]; - var coljs = col2.split('\t')[1] - return "'"+columnid+"':null,"; - }).join(''); - - var aft = ''; -// s += self.columns.map(function(col){ -//console.log('query.selectGroup',query.selectGroup); - s += query.selectGroup.map(function(col,idx){ -//console.log(idx, col.toString(), col.as); - var colexp = col.expression.toJavaScript("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' - || col.aggregatorid == 'MIN' - || col.aggregatorid == 'MAX' - || col.aggregatorid == 'FIRST' - || col.aggregatorid == 'LAST' -// || col.aggregatorid == 'AVG' -// ) { return '\''+col.as+'\':r[\''+col.as+'\'],'; }//f.field.arguments[0].toJavaScript(); - ) { return '\''+colas+'\':'+colexp+','; }//f.field.arguments[0].toJavaScript(); - 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 { - return '\''+colas+'\':(typeof '+colexp+' != "undefined")?1:0,'; - } - -// else if(col.aggregatorid == 'MIN') { return '\''+col.as+'\':r[\''+col.as+'\'],'; } -// else if(col.aggregatorid == 'MAX') { return '\''+col.as+'\':r[\''+col.as+'\'],'; } - } else if(col.aggregatorid == 'AVG') { - query.removeKeys.push('_SUM_'+colas); - query.removeKeys.push('_COUNT_'+colas); - return '\''+colas+'\':'+colexp+',\'_SUM_'+colas+'\':'+colexp+',\'_COUNT_'+colas+'\':1,'; - } else if(col.aggregatorid == 'AGGR') { - aft += ',g[\''+colas+'\']='+col.expression.toJavaScript('g',-1); - return ''; - } else if(col.aggregatorid == 'REDUCE') { - return '\''+colas+'\':alasql.aggr[\''+col.funcid+'\']('+colexp+'),'; - } - return ''; - } else return ''; - }).join(''); - - - - - - // columnid:r.columnid - // var srg = [];//rg.map(function(fn){ return (fn+':'+fn); }); - - // var srg = this.group.map(function(col){ - // if(col == '') return ''; - // else return col.columnid+':'+col.toJavaScript('r',''); - // }); - - // Initializw aggregators - - /* - this.columns.forEach(function(col){ - // console.log(f); - // if(f.constructor.name == 'LiteralValue') return ''; - - - if (col instanceof yy.AggrValue) { - if (col.aggregatorid == 'SUM') { srg.push("'"+col.as+'\':0'); }//f.field.arguments[0].toJavaScript(); - else if(col.aggregatorid == 'COUNT') {srg.push( "'"+col.as+'\':0'); } - else if(col.aggregatorid == 'MIN') { srg.push( "'"+col.as+'\':Infinity'); } - else if(col.aggregatorid == 'MAX') { srg.push( "'"+col.as+'\':-Infinity'); } - // else if(col.aggregatorid == 'AVG') { srg.push(col.as+':0'); } - // return 'group.'+f.name.value+'=+(+group.'+f.name.value+'||0)+'+f.field.arguments[0].toJavaScript('rec','')+';'; //f.field.arguments[0].toJavaScript(); - }; - - }); - - */ - - /*****************/ - - // s += srg.join(','); - - // var ss = []; - // gff.forEach(function(fn){ - // ss.push(fn+':rec.'+fn); - // }); - // s += ss.join(','); - // s += '});};'; - - s += '}'+aft+',g));} else {'; - // console.log(s, this.columns); - - - - // var neggroup = arrayDiff(allgroups,agroup); - - // console.log(agroup,neggroup); - - // s += neggroup.map(function(columnid){ - // return "g['"+columnid+"']=null;"; - // }).join(''); - - // console.log(s); - - - //console.log(query.selectfn); -// s += self.columns.map(function(col){ - s += query.selectGroup.map(function(col,idx){ - var colas = col.nick; - // if(typeof colas == 'undefined') { - // if(col instanceof yy.Column) colas = col.columnid; - // else colas = col.toString(); - // } - var colexp = col.expression.toJavaScript("p",tableid,defcols); - - if (col instanceof yy.AggrValue) { - if(col.distinct) { - var pre = 'if(typeof '+colexp+'!="undefined" && (!g[\'$$_VALUES_'+colas+'\']['+colexp+'])) \ - {'; - var post = 'g[\'$$_VALUES_'+colas+'\']['+colexp+']=true;}'; - } else { - var pre = '', post = ''; - } - if (col.aggregatorid == 'SUM') { return pre+'g[\''+colas+'\']+='+colexp+';'+post; }//f.field.arguments[0].toJavaScript(); - else if(col.aggregatorid == 'COUNT') { -// console.log(221,col.expression.columnid == '*'); - if(col.expression.columnid == '*') return pre+'g[\''+colas+'\']++;'+post; - else { - return pre+'if(typeof '+colexp+'!="undefined") g[\''+colas+'\']++;'+post; - } - } - else if(col.aggregatorid == 'ARRAY') { return pre+'g[\''+colas+'\'].push('+colexp+');'+post; } - else if(col.aggregatorid == 'MIN') { return pre+'g[\''+colas+'\']=Math.min(g[\''+colas+'\'],'+colexp+');'+post; } - else if(col.aggregatorid == 'MAX') { return pre+'g[\''+colas+'\']=Math.max(g[\''+colas+'\'],'+colexp+');'+post; } - else if(col.aggregatorid == 'FIRST') { return ''; } - else if(col.aggregatorid == 'LAST') { return pre+'g[\''+colas+'\']='+colexp+';'+post; } - else if(col.aggregatorid == 'AVG') { - return pre+'g[\'_SUM_'+colas+'\']+='+colexp+';' - + 'g[\'_COUNT_'+colas+'\']++;' - + 'g[\''+colas+'\']=g[\'_SUM_'+colas+'\']/g[\'_COUNT_'+colas+'\'];'+post; -// } - // else if(col.aggregatorid == 'AVG') { srg.push(colas+':0'); } - } else if(col.aggregatorid == 'AGGR') { - return pre+'g[\''+colas+'\']='+col.expression.toJavaScript('g',-1)+';'+post; - } else if(col.aggregatorid == 'REDUCE') { - return pre+'g[\''+colas+'\']=alasql.aggr.'+col.funcid+'('+colexp+',g[\''+colas+'\']);'+post; - } - return ''; - } else return ''; - }).join(''); - - - // s += selectFields.map(function(f){ - // console.log(f); - // if(f.constructor.name == 'LiteralValue') return ''; - // if (f.field instanceof SQLParser.nodes.FunctionValue - // && (f.field.name.toUpperCase() == 'SUM' || f.field.name.toUpperCase() == 'COUNT')) { - // return 'group.'+f.name.value+'=+(+group.'+f.name.value+'||0)+'+f.field.arguments[0].toJavaScript('rec','')+';'; //f.field.arguments[0].toJavaScript(); - // return 'group.'+f.name.value+'+='+f.field.arguments[0].toJavaScript('rec','')+';'; //f.field.arguments[0].toJavaScript(); - // return 'group.'+f.name.value+'+=rec.'+f.name.value+';'; //f.field.arguments[0].toJavaScript(); - // }; - // return ''; - // }).join(''); - - //s += ' group.amt += rec.emplid;'; - //s += 'group.count++;'; - s += '}'; - - }); - -// console.log('groupfn',s); - return new Function('p,params,alasql',s); - -} - - -/* -// -// Select compiler part for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -// yy.Select.prototype.compileSources = function(query) { -// return sources; -// }; - -function compileSelectStar (query,alias) { - // console.log(query.aliases[alias]); -// console.log(query,alias); - // console.log(query.aliases[alias].tableid); -// console.log(42,631,alias); -// console.log(query.aliases); - var s = '', sp = '', ss=[]; -// if(!alias) { -// sp += 'for(var k1 in p) var w=p[k1];for(var k2 in w){r[k2]=w[k2]};'; -// } else { - if(query.aliases[alias].tableid) { - var columns = alasql.databases[query.aliases[alias].databaseid].tables[query.aliases[alias].tableid].columns; - }; - // Check if this is a Table or other - - if(columns && columns.length > 0) { - columns.forEach(function(tcol){ - ss.push('\''+tcol.columnid+'\':p[\''+alias+'\'][\''+tcol.columnid+'\']'); - query.selectColumns[escapeq(tcol.columnid)] = true; - - // console.log('ok',s); - - var coldef = { - columnid:tcol.columnid, - dbtypeid:tcol.dbtypeid, - dbsize:tcol.dbsize, - dbprecision:tcol.dbprecision, - dbenum: tcol.dbenum - }; - query.columns.push(coldef); - query.xcolumns[coldef.columnid]=coldef; - - }); -//console.log(999,columns); - } else { - // if column not exists, then copy all - sp += 'var w=p["'+alias+'"];for(var k in w){r[k]=w[k]};'; -//console.log(777, sp); - query.dirtyColumns = true; - } -// } -//console.log({s:ss.join(','),sp:sp}); - return {s:ss.join(','),sp:sp}; -} - - -yy.Select.prototype.compileSelect1 = function(query) { - 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){ -//console.log(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); - if(ret.s) ss = ss.concat(ret.s); - sp += ret.sp; - - } else { -// console.log('aliases', query.aliases); - for(var alias in query.aliases) { - var ret = compileSelectStar(query, alias); //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; -// console.log(query.sources); - 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 != '_') { - 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]) { -// console.log(query.database,tbid,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; -//console.log(xcolumns, col,123); -// console.log(0); - if(xcolumns && columns.length > 0) { -// console.log(1); - var tcol = xcolumns[col.columnid]; - var coldef = { - columnid:col.as || col.columnid, - dbtypeid:tcol.dbtypeid, - dbsize:tcol.dbsize, - dbpecision:tcol.dbprecision, - dbenum: tcol.dbenum, - }; -// console.log(2); - query.columns.push(coldef); - query.xcolumns[coldef.columnid]=coldef; - } else { - query.dirtyColumns = true; - } - } else { - // This is a subquery? - // throw new Error('There is now such table \''+col.tableid+'\''); - }; - - } - } else if(col instanceof yy.AggrValue) { - if(!self.group) { -// self.group=[new yy.Column({columnid:'q',as:'q' })]; - self.group = ['']; - } - if(!col.as) col.as = escapeq(col.toString()); - if (col.aggregatorid == 'SUM' || col.aggregatorid == 'MAX' || col.aggregatorid == 'MIN' || - col.aggregatorid == 'FIRST' || col.aggregatorid == 'LAST' || - col.aggregatorid == 'AVG' || col.aggregatorid == 'ARRAY' || col.aggregatorid == 'REDUCE' - ) { - ss.push("'"+escapeq(col.as)+'\':'+col.expression.toJavaScript("p",query.defaultTableid,query.defcols)) - } else if (col.aggregatorid == 'COUNT') { - ss.push("'"+escapeq(col.as)+"':1"); - // Nothing - } - query.selectColumns[col.aggregatorid+'('+escapeq(col.expression.toString())+')'] = thtd; - -// else if (col.aggregatorid == 'MAX') { -// ss.push((col.as || col.columnid)+':'+col.toJavaScript("p.",query.defaultTableid)) -// } else if (col.aggregatorid == 'MIN') { -// ss.push((col.as || col.columnid)+':'+col.toJavaScript("p.",query.defaultTableid)) -// } - } else { - ss.push('\''+escapeq(col.as || col.columnid || col.toString())+'\':'+col.toJavaScript("p",query.defaultTableid,query.defcols)); -// ss.push('\''+escapeq(col.toString())+'\':'+col.toJavaScript("p",query.defaultTableid)); - //if(col instanceof yy.Expression) { - query.selectColumns[escapeq(col.as || col.columnid || col.toString())] = true; - } - }); - s += ss.join(',')+'};'+sp; - return s; -//console.log(42,753,query.xcolumns, query.selectColumns); -} -yy.Select.prototype.compileSelect2 = function(query) { - - var s = query.selectfns ; -// console.log(s); - return new Function('p,params,alasql',s+'return r'); -}; - - -yy.Select.prototype.compileSelectGroup0 = function(query) { - var self = this; - self.columns.forEach(function(col,idx){ - if(col instanceof yy.Column && col.columnid == '*') { - } else { - var colas; - // = col.as; - if(col instanceof yy.Column) { - colas = escapeq(col.columnid); - } else { - colas = escapeq(col.toString()); - } - for(var i=0;irb) return 1; - if(ra==rb) return 0; - return -1; - } - }; +alasql.querySingle = function (sql, params, cb) { + var res = this.exec(sql, params)[0]; + if(cb) cb(res); + return res; +}; - var s = ''; - var sk = ''; - this.order.forEach(function(ord,idx){ - // console.log(ord instanceof yy.Expression); - // console.log(ord.toJavaScript('a','')); - // console.log(ord.expression instanceof yy.Column); - - // Date conversion - var dg = ''; -//console.log(ord.expression, ord.expression instanceof yy.NumValue); - if(ord.expression instanceof yy.NumValue) { - ord.expression = self.columns[ord.expression.value-1]; - }; +alasql.queryRow = function (sql, params, cb) { + var res = this.querySingle(sql, params); + var a = []; + for(var key in res) { + a.push(res[key]); + }; + if(cb) cb(a); + return a; +}; - 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') dg = '.valueOf()'; - // TODO Add other types mapping - } else { - if(alasql.options.valueof) dg = '.valueOf()'; // TODO Check - } - // COLLATE NOCASE - if(ord.nocase) dg += '.toUpperCase()'; +alasql.queryValue = function (sql, params, cb) { + var res = this.exec(sql, params)[0]; + var val = res[Object.keys(res)[0]]; + if(cb) cb(val); + return val; + // TODO Refactor to query.columns +}; - s += 'if(a[\''+columnid+"']"+dg+(ord.direction == 'ASC'?'>':'<')+'b[\''+columnid+"']"+dg+')return 1;'; - s += 'if(a[\''+columnid+"']"+dg+'==b[\''+columnid+"']"+dg+'){'; +alasql.queryArrayOfArrays = function (sql, params, cb) { + var res = this.exec(sql, params); + var keys = Object.keys(res[0]); + var klen = keys.length; + var aa = []; + for(var i=0, ilen=res.length;i':'<')+ord.toJavaScript('b','')+dg+')return 1;'; - s += 'if('+ord.toJavaScript('a','')+dg+'=='+ord.toJavaScript('b','')+dg+'){'; - } + if(cb) cb(aa); + return aa; +}; +*/ +/*alasql.queryColumn = function (sql, params, cb) { + var res = this.exec(sql, params); + var keys = Object.keys(res[0]); + var klen = keys.length; + var aa = []; + for(var i=0, ilen=res.length;i':'<')+'b'+dg+')return 1;'; -// s += 'if(a'+dg+'==b'+dg+'){'; + if(cb) cb(aa); + return aa; +}; +*/ +/* +alasql.value = alasql.queryValue; +alasql.single = alasql.querySingle; +alasql.row = alasql.queryRow; +alasql.column = alasql.queryArray; +alasql.array = alasql.queryArray; +alasql.matrix = alasql.queryArrayOfArrays; +*/ + + +/* +// +// Database class for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +// Main Database class +/** + @class Database + */ + +var Database = alasql.Database = function (databaseid) { + var self = this; + if(self === alasql) { + if(databaseid) { +// if(alasql.databases[databaseid]) { + self = alasql.databases[databaseid]; // } else { - // TODO Add date comparision - // s += 'if(a[\''+columnid+"']"+dg+(ord.direction == 'ASC'?'>':'<')+'b[\''+columnid+"']"+dg+')return 1;'; - // s += 'if(a[\''+columnid+"']"+dg+'==b[\''+columnid+"']"+dg+'){'; + alasql.databases[databaseid] = self; // } - sk += '}'; - }); - s += 'return 0;'; - s += sk+'return -1'; - query.orderfns = s; -//console.log(s); - return new Function('a,b',s); + if(!self) { + throw new Error('Database "'+databaseid+'" not found'); + } + } else { + // Create new database (or get alasql?) + self = alasql.databases.alasql; +// self = new Database(databaseid); // to call without new + } + } + if(!databaseid) { + databaseid = "db"+(alasql.databasenum++); // Random name }; + self.databaseid = databaseid; + alasql.databases[databaseid] = self; + self.tables = {}; + self.views = {}; + + self.indices = {}; +// self.fn = {}; + self.resetSqlCache(); + self.dbversion = 0; + return self; }; +/** + Reset SQL statements cache + */ + +Database.prototype.resetSqlCache = function () { + this.sqlCache = {}; // Cache for compiled SQL statements + this.sqlCacheSize = 0; +} + + +// // Main SQL function + +/** + Run SQL statement on database + @param {string} sql SQL statement + @param [object] params Parameters + @param {function} cb callback + */ + +Database.prototype.exec = function(sql, params, cb) { + return alasql.dexec(this.databaseid, sql, params, cb); +}; + +// // Compile +// var statement = this.compile(sql); +// // Run +// if(statement) { +// var data = statement(params, cb); +// return data; +// } +// return; +// }; + +// // Async version of exec + + +// Database.prototype.aexec = function(sql, params) { +// var self = this; +// return new Promise(function(resolve, reject){ +// alasql.dexec(this.databaseid,sql,params,resolve); +// }); +// }; + + +// Aliases like MS SQL +/* +Database.prototype.query = Database.prototype.exec; +Database.prototype.run = Database.prototype.exec; +Database.prototype.queryArray = function(sql, params, cb) { + return flatArray(this.exec(sql, params, cb)); +} + +Database.prototype.queryArrayOfArrays = function(sql, params, cb) { + return arrayOfArrays(this.exec(sql, params, cb)); +} + +Database.prototype.querySingle = function(sql, params, cb) { + return this.exec(sql, params, cb)[0]; +} +Database.prototype.queryValue = function(sql, params, cb) { + var res = this.querySingle(sql, params, cb); + return res[Object.keys(res)[0]]; +} + +Database.prototype.value = Database.prototype.queryValue; +Database.prototype.row = Database.prototype.querySingle; +Database.prototype.array = Database.prototype.queryArray; +Database.prototype.matrix = Database.prototype.queryArrayOfArrays; + + +// Compile statements +Database.prototype.compile = function(sql, kind) { + return alasql.compile(sql, kind, databaseid); +}; + +*/ +// var self = this; +// var hh = hash(sql); + +// // Check cache with hash of SQL statement +// var statement = this.sqlcache[hh]; +// if(!statement) { + +// // If not fount, then compile it +// var ast = alasql.parse(sql); +// // Save to cache + +// statement = this.sqlcache[hh]= ast.compile(self); + +// // Memory leak prevention +// this.sqlcachesize++; +// if(this.sqlcachesize > alasql.MAXSQLCACHESIZE) { +// this.resetSqlCache(); +// } +// }; +// return statement; +// } + +// SQL.js compatibility method +//Database.prototype.prepare = Database.prototype.compile; + + +// Added for compatibility with WebSQL + + + + + +/* +// +// 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 + */ + +var Transaction = alasql.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 +// console.log(this); + return this; +}; + +// Main class + + +// Commit + +/** + Commit transaction + */ +Transaction.prototype.commit = function() { + this.commited = true; + alasql.databases[this.databaseid].dbversion = Date.now(); + delete this.bank; +}; + +// Rollback +/** + Rollback transaction + */ +Transaction.prototype.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'); + } +}; + +// Transactions stub + +/** + Execute SQL statement + @param {string} sql SQL statement + @param {object} params Parameters + @param {function} cb Callback function + @return result + */ +Transaction.prototype.exec = function(sql, params, cb) { +// console.log(this.databaseid); + return alasql.dexec(this.databaseid,sql,params,cb); +}; + +Transaction.prototype.executeSQL = Transaction.prototype.exec; + +/* +Transaction.prototype.query = Database.prototype.exec; +Transaction.prototype.run = Database.prototype.exec; +Transaction.prototype.queryArray = function(sql, params, cb) { + return flatArray(this.exec(sql, params, cb)); +} + +Transaction.prototype.queryArrayOfArrays = function(sql, params, cb) { + return arrayOfArrays(this.exec(sql, params, cb)); +} + +Transaction.prototype.querySingle = function(sql, params, cb) { + return this.exec(sql, params, cb)[0]; +} +Transaction.prototype.queryValue = function(sql, params, cb) { + var res = this.querySingle(sql, params, cb); + return res[Object.keys(res)[0]]; +} +*/ + + +/* +// +// Table class for Alasql.js +// Date: 14.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +// Table class +var Table = alasql.Table = function(params){ + // Columns + this.columns = []; + this.xcolumns = {}; + // Data array + this.data = []; + + this.inddefs = {}; + this.indices = {}; + + this.uniqs = {}; + this.uniqdefs = {}; + + extend(this,params); +}; + + +// View = function(){ +// this.data = []; +// this.columns = []; +// this.ixcolumns = {}; +// this.ixdefs = {}; +// this.indices = {}; +// }; + +// alasql.View = View; + +Table.prototype.indexColumns = function() { + var self = this; + self.xcolumns = {}; + self.columns.forEach(function(col){ + self.xcolumns[col.columnid] = col; + }); +} + + + + +/* +// +// View class for Alasql.js +// Date: 14.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +// Table class +var View = alasql.View = function(params){ + // Columns + this.columns = []; + this.xcolumns = {}; + // Data array + this.query = []; + + extend(this,params); +}; + +// View = function(){ +// this.data = []; +// this.columns = []; +// this.ixcolumns = {}; +// this.ixdefs = {}; +// this.indices = {}; +// }; + +// alasql.View = View; + + + + +/* +// +// Query class for Alasql.js +// Date: 14.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +// Table class + +/** + @class Query Main query class + */ +var Query = alasql.Query = function(params){ + this.alasql = alasql; +// console.log(12,alasql); + // Columns + this.columns = []; + this.xcolumns = {}; + this.selectGroup = []; + this.groupColumns = {}; + // Data array + extend(this,params); +}; + +/** + @class Recordset data object + */ +var Recordset = alasql.Recordset = function(params){ + // Data array + extend(this,params); +}; + + +// View = function(){ +// this.data = []; +// this.columns = []; +// this.ixcolumns = {}; +// this.ixdefs = {}; +// this.indices = {}; +// }; + +// alasql.View = View; + + + + +/* +// +// Parser helper for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +var yy = parser.yy = {}; + +// Utility +yy.extend = extend; +// Option for case sensitive +yy.casesensitive = alasql.options.casesensitive; + +// Base class for all yy classes +var Base = yy.Base = function (params) { return yy.extend(this, params); }; + +Base.prototype.toString = function() {} +Base.prototype.toType = function() {} +Base.prototype.toJavaScript = function() {} + +//var BaseClause = yy,BaseClause = function (params) { return yy.extend(this, params); }; +Base.prototype.compile = returnUndefined; +Base.prototype.exec = function() {} + +//var BaseStatement = yy,BaseStatement = function (params) { return yy.extend(this, params); }; +Base.prototype.compile = returnUndefined; +Base.prototype.exec = function() {} + + + + +/* +// +// Statements class for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +// Statements container +yy.Statements = function(params) { return yy.extend(this, params); }; + +yy.Statements.prototype.toString = function () { + return this.statements.map(function(st){return st.toString()}).join(';'+NL()); +}; + +// Compile array of statements into single statement +yy.Statements.prototype.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; + } + } +}; + + + +// Main query procedure +function queryfn(query,oldscope,cb, A,B) { + var ms; + query.sourceslen = query.sources.length; + var slen = query.sourceslen; + query.query = query; // TODO Remove to prevent memory leaks + query.A = A; + query.B = B; +// console.log(arguments); + query.cb = cb; + query.oldscope = oldscope; + + // Run all subqueries before main statement + if(query.queriesfn) { + query.sourceslen += query.queriesfn.length; + slen += query.queriesfn.length; + + query.queriesdata = []; + +// console.log(8); + query.queriesfn.forEach(function(q,idx){ +// if(query.explain) ms = Date.now(); +//console.log(18,idx); +// var res = flatArray(q(query.params,null,queryfn2,(-idx-1),query)); + +// var res = flatArray(queryfn(q.query,null,queryfn2,(-idx-1),query)); +// console.log(A,B); +// console.log(q); + q.query.params = query.params; +// query.queriesdata[idx] = + + if(false) { + queryfn(q.query,query.oldscope,queryfn2,(-idx-1),query); + } else { + queryfn2([],(-idx-1),query); + } + +// console.log(27,q); + + +// query.explaination.push({explid: query.explid++, description:'Query '+idx,ms:Date.now()-ms}); +// query.queriesdata[idx] = res; +// return res; + }); +// console.log(9,query.queriesdata.length); +// console.log(query.queriesdata[0]); + } + + var scope; + if(!oldscope) scope = {}; + else scope = cloneDeep(oldscope); + query.scope = scope; + + // First - refresh data sources + + var result; + query.sources.forEach(function(source, idx){ +// source.data = query.database.tables[source.tableid].data; +// console.log(666,idx); + source.query = query; + var rs = source.datafn(query, query.params, queryfn2, idx, alasql); +// console.log(333,rs); + if(typeof rs != undefined) { + // TODO - this is a hack: check if result is array - check all cases and + // make it more logical + if((query.intofn || query.intoallfn) && rs instanceof Array) rs = rs.length; + result = rs; + } +// console.log(444,result); +// +// Ugly hack to use in query.wherefn and source.srcwherefns functions +// constructions like this.queriesdata['test']. +// I can elimite it with source.srcwherefn.bind(this)() +// but it may be slow. +// + source.queriesdata = query.queriesdata; + }); + if(slen == 0) result = queryfn3(query); + return result; +}; + +function queryfn2(data,idx,query) { + +//console.log(56,arguments); +// console.log(78,data, idx,query); +//console.trace(); + + if(idx>=0) { + var source = query.sources[idx]; + source.data = data; + if(typeof source.data == 'function') { + source.getfn = source.data; + source.dontcache = source.getfn.dontcache; + + // var prevsource = query.sources[h-1]; + if(source.joinmode == 'OUTER' || source.joinmode == 'RIGHT' || source.joinmode == 'ANTI') { + source.dontcache = false; + } + source.data = {}; + } + } else { + // subqueries +// console.log("queriesdata",data, flatArray(data)); + query.queriesdata[-idx-1] = flatArray(data); +// console.log(98,query.queriesdata); +// console.log(79,query.queriesdata); + } + + query.sourceslen--; + if(query.sourceslen>0) return; + + return queryfn3(query); +}; + +function queryfn3(query) { +//console.log(55,query); + + + var scope = query.scope; + // Preindexation of data sources +// if(!oldscope) { + preIndex(query); +// } + + // query.sources.forEach(function(source) { + // console.log(source.data); + // }); + + // Prepare variables + query.data = []; + query.xgroups = {}; + query.groups = []; + + // Level of Joins + var h = 0; + + // Start walking over data + doJoin(query, scope, h); + +//console.log(85,query.data[0]); + + // If groupping, then filter groups with HAVING function +// console.log(query.havingfns); + if(query.groupfn) { + query.data = []; + if(query.groups.length == 0) { + var g = {}; + if(query.selectGroup.length>0) { +// console.log(query.selectGroup); + query.selectGroup.forEach(function(sg){ + if(sg.aggregatorid == "COUNT" || sg.aggregatorid == "SUM") { + g[sg.nick] = 0; + } else { + g[sg.nick] = undefined; + } + }); + }; + query.groups = [g]; +// console.log(); + }; + // console.log('EMPTY',query.groups); + // debugger; + // if(false && (query.groups.length == 1) && (Object.keys(query.groups[0]).length == 0)) { + // console.log('EMPTY',query.groups); + // } else { + for(var i=0,ilen=query.groups.length;i 0) { + for(var i=0,ilen=query.data.length;i 0 && source.optimization == 'ix' && source.onleftfn && source.onrightfn) { + // If there is no table.indices - create it + if(source.databaseid && alasql.databases[source.databaseid].tables[source.tableid]) { + if(!alasql.databases[source.databaseid].tables[source.tableid].indices) query.database.tables[source.tableid].indices = {}; + // Check if index already exists + var ixx = alasql.databases[source.databaseid].tables[source.tableid].indices[hash(source.onrightfns+'`'+source.srcwherefns)]; + if( !alasql.databases[source.databaseid].tables[source.tableid].dirty && ixx) { + source.ix = ixx; + } + }; + if(!source.ix) { + source.ix = {}; + // Walking over source data + var scope = {}; + var i = 0; + var ilen = source.data.length; + var dataw; +// while(source.getfn i=query.sources.length) { +//console.log(query.wherefns); + // Then apply where and select +// console.log(query); + if(query.wherefn(scope,query.params, alasql)) { + +// console.log("scope",scope.schools); + +// var res = query.selectfn(scope, query.params, alasql); +// console.log("last",res); + // If there is a GROUP BY then pipe to groupping function + if(query.groupfn) { + query.groupfn(scope, query.params, query.alasql) + } else { + query.data.push(query.selectfn(scope, query.params, alasql)); + } + } + } else if(query.sources[h].applyselect) { +// console.log('APPLY',scope); +// console.log('scope1',scope); +// console.log(scope); + var source = query.sources[h]; + source.applyselect(query.params, function(data){ + if(data.length > 0) { + // console.log('APPLY CB'); + for(var i=0;i0) { + s += NL()+ID()+K('GROUP BY')+' '+this.group.map(function(grp){ + return grp.toString(); + }).join(', '); + }; + if(this.having) s += NL()+ID()+K('HAVING')+' '+this.having.toString(); + + if(this.order && this.order.length>0) { + s += NL()+ID()+K('ORDER BY')+' '+this.order.map(function(ord){ + return ord.toString(); + }).join(', '); + }; + if(this.limit) s += NL()+ID()+K('LIMIT')+' '+this.limit.value; + if(this.offset) s += NL()+ID()+K('OFFSET')+' '+this.offset.value; + if(this.union) s += NL()+K('UNION')+NL()+this.union.toString(); + if(this.unionall) s += NL()+K('UNION ALL')+NL()+this.unionall.toString(); + if(this.except) s += NL()+K('EXCEPT')+NL()+this.except.toString(); + if(this.intersect) s += NL()+K('INTERSECT')+NL()+this.intersect.toString(); + return s; +}; + +/** + Select statement in expression + */ +yy.Select.prototype.toJavaScript = function(context, tableid, defcols) { +// console.log('Expression',this); +// if(this.expression.reduced) return 'true'; +// return this.expression.toJavaScript(context, tableid, defcols); +// console.log('Select.toJS', 81, this.queriesidx); +// var s = 'this.queriesdata['+(this.queriesidx-1)+'][0]'; +//console.log(this); + var s = 'alasql.utils.flatArray(this.queriesfn['+(this.queriesidx-1)+'](this.params,null,'+context+'))[0]'; +// s = '(console.log(this.queriesfn[0]),'+s+')'; + + return s; +}; + + +// Compile SELECT statement +yy.Select.prototype.compile = function(databaseid) { + var db = alasql.databases[databaseid]; + // Create variable for query + var query = new Query(); + + query.removeKeys = []; + + 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); + // 3. Compile SELECT clause + + this.compileSelectGroup0(query); + + if(this.group || query.selectGroup.length>0) { + query.selectgfns = this.compileSelectGroup1(query); + } else { + query.selectfns = this.compileSelect1(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); + + 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; + + // 8. Compile ORDER BY clause + if(this.order) query.orderfn = this.compileOrder(query); + +// TOP + 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 + 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 +// console.log(this.into); + if(this.into) { + if(this.into instanceof yy.Table) { + if(alasql.options.autocommit && alasql.databases[this.into.databaseid||databaseid].engineid) { + 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 { + query.intofns = + 'alasql.databases[\''+(this.into.databaseid||databaseid)+'\'].tables'+ + '[\''+this.into.tableid+'\'].data.push(r);'; + } + } else if(this.into instanceof yy.VarValue) { + query.intoallfns = 'alasql.vars["'+this.into.variable+'"]=this.data;res=1;if(cb)res=cb(res);return res;'; + } else if (this.into instanceof yy.FuncValue) { + +/* + query.intofns = 'alasql.into[\''+this.into.funcid+'\']('; + var ss = ['r','i']; + if(this.into.args && this.into.args.length>0 ) + this.into.args.forEach(function(arg){ + ss.push(arg.toJavaScript()); + }); + query.intofns += ss.join(',')+')'; +*/ + var qs = 'alasql.into[\''+this.into.funcid.toUpperCase()+'\']('; + if(this.into.args && this.into.args.length>0 ) { + qs += this.into.args[0].toJavaScript()+','; + if(this.into.args.length > 1) { + qs += this.into.args[1].toJavaScript()+','; + } else { + qs += 'null,'; + } + } else { + qs += 'null, null,' + } + query.intoallfns = qs+'this.data,columns,cb)'; +//console.log('999'); + + + + + } else if (this.into instanceof yy.ParamValue) { +// console.log(184); +// query.intofns = 'params[\''+this.into.param+"\'](r)"; + query.intofns = "params['"+this.into.param+"'].push(r)"; + + }; +// console.log(query.intofns); + if(query.intofns) { + query.intofn = new Function("r,i,params,alasql",query.intofns); + }; + + if(query.intoallfns) { +// console.log(query.intoallfns); + query.intoallfn = new Function("columns,cb,alasql",query.intoallfns); + } + + } +//console.log(query); + + // Now, compile all togeather into one function with query object in scope + var statement = function(params, cb, oldscope) { + query.params = params; + var res1 = queryfn(query,oldscope,function(res){ + +//console.log(res[0].schoolid); +//console.log(184,res); + var res2 = modify(query, res); + + + if(cb) cb(res2); +//console.log(8888,res2); + return res2; + + }); +//console.log(9999,res1); + +// if(typeof res1 != 'undefined') res1 = modify(query,res1); + + return res1; + + }; + +// statement.dbversion = ; +// console.log(statement.query); +//console.log(202,statement); + statement.query = query; + return statement; +}; + +function modify(query, res) { + if(query.modifier == 'VALUE') { +// console.log(222,res); + if(res.length > 0) { + var key; + if(query.columns && query.columns.length > 0) key = query.columns[0].columnid; + else key = Object.keys(res[0])[0]; + res = res[0][key]; + } else { + res = undefined; + } + } if(query.modifier == 'ROW') { + if(res.length > 0) { + var key; + if(query.columns && query.columns.length > 0) key = query.columns[0].columnid; + else key = Object.keys(res[0])[0]; + var a = []; + for(var key in res[0]) { + a.push(res[0][key]); + }; + res = a; + } else { + res = undefined; + } + } if(query.modifier == 'COLUMN') { + var ar = []; + if(res.length > 0) { + var key; + if(query.columns && query.columns.length > 0) key = query.columns[0].columnid; + else key = Object.keys(res[0])[0]; + for(var i=0, ilen=res.length; i 0) { + key = query.columns[0].columnid; + val = query.columns[1].columnid; + } else { + var okeys = Object.keys(res[0]); + key = okeys[0]; + val = okeys[1]; + } + for(var i=0, ilen=res.length; i 0) key = query.columns[0].columnid; + else key = Object.keys(res[0])[0]; + var s = ''; + for(var i=0, ilen=res.length; i0) { + // s += tq.args.map(function(arg){ + // return arg.toJavaScript(); + // }).concat('cb,idx,query').join(','); + // } + // if(tq.args && tq.args.length>0) { + // s += tq.args.map(function(arg){ + // return arg.toJavaScript(); + // }).concat().join(','); + // } + if(tq.args && tq.args.length>0) { + if(tq.args[0]) { + s += tq.args[0].toJavaScript('query.oldscope')+','; + } else { + s += 'null,'; + }; + if(tq.args[1]) { + s += tq.args[1].toJavaScript('query.oldscope')+','; + } else { + s += 'null,'; + }; + } else { + s += 'null,null,' + } + s += 'cb,idx,query'; + s += ');/*if(cb)res=cb(res,idx,query);*/return res'; +// console.log(s); + source.datafn = new Function('query, params, cb, idx, alasql',s); + + } else if(tq instanceof yy.FromData) { + source.datafn = function(query,params,cb,idx, alasql) { + var res = tq.data; + if(cb) res = cb(res,idx,query); + return res; + } + } else { + throw new Error('Wrong table at FROM'); + } +// source.data = alasql.databases[source.databaseid].tables[source.tableid].data; + query.sources.push(source); + + }); + // TODO Add joins + query.defaultTableid = query.sources[0].alias; +//console.log(query.defaultTableid); +}; + +alasql.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; i0) { + // s += tq.args.map(function(arg){ + // return arg.toJavaScript(); + // }).concat('cb,idx,query').join(','); + // } + // if(tq.args && tq.args.length>0) { + // s += tq.args.map(function(arg){ + // return arg.toJavaScript(); + // }).concat().join(','); + // } + if(jn.args && jn.args.length>0) { + if(jn.args[0]) { + s += jn.args[0].toJavaScript('query.oldscope')+','; + } else { + s += 'null,'; + }; + if(jn.args[1]) { + s += jn.args[1].toJavaScript('query.oldscope')+','; + } else { + s += 'null,'; + }; + } else { + s += 'null,null,' + } + s += 'cb,idx,query'; + s += ');/*if(cb)res=cb(res,idx,query);*/return res'; +// console.log(s); + source.datafn = new Function('query, params, cb, idx, alasql',s); + + query.aliases[source.alias] = {type:'funcvalue'}; + } +/* + } else if(tq instanceof yy.Select) { + query.aliases[alias] = {type:'subquery'}; + } else if(tq instanceof yy.ParamValue) { + query.aliases[alias] = {type:'paramvalue'}; + } else if(tq instanceof yy.FuncValue) { + query.aliases[alias] = {type:'paramvalue'}; + } else { + throw new Error('Wrong table at FROM'); + } +*/ + var alias = source.alias; + + // Test NATURAL-JOIN + if(jn.natural) { + if(jn.using || jn.on) { + throw new Error('NATURAL JOIN cannot have USING or ON clauses'); + } else { +// source.joinmode == "INNER"; + if(query.sources.length > 0) { + var prevSource = query.sources[query.sources.length-1]; + var prevTable = alasql.databases[prevSource.databaseid].tables[prevSource.tableid]; + var table = alasql.databases[source.databaseid].tables[source.tableid]; + + if(prevTable && table) { + var c1 = prevTable.columns.map(function(col){return col.columnid}); + var c2 = table.columns.map(function(col){return col.columnid}); + jn.using = arrayIntersect(c1,c2).map(function(colid){return {columnid:colid}}); +// console.log(jn.using); + } else { + throw new Error('In this version of Alasql NATURAL JOIN '+ + 'works for tables with predefined columns only'); + }; + } + } + } + + + + + + + + if(jn.using) { + var prevSource = query.sources[query.sources.length-1]; +// console.log(query.sources[0],prevSource,source); + source.onleftfns = jn.using.map(function(col){ +// console.log(141,colid); + return "p['"+(prevSource.alias||prevSource.tableid)+"']['"+col.columnid+"']"; + }).join('+"`"+'); + + + + source.onleftfn = new Function('p,params,alasql','return '+source.onleftfns); + + source.onrightfns = jn.using.map(function(col){ + return "p['"+(source.alias||source.tableid)+"']['"+col.columnid+"']"; + }).join('+"`"+'); + source.onrightfn = new Function('p,params,alasql','return '+source.onrightfns); + source.optimization = 'ix'; +// console.log(151,source.onleftfns, source.onrightfns); +// console.log(source); + } else if(jn.on) { +//console.log(jn.on); + if(jn.on instanceof yy.Op && jn.on.op == '=' && !jn.on.allsome) { +// console.log('ix optimization', jn.on.toJavaScript('p',query.defaultTableid) ); + source.optimization = 'ix'; + // source.onleftfns = jn.on.left.toJavaScript('p',query.defaultTableid); + // source.onleftfn = new Function('p', 'return '+source.onleftfns); + // source.onrightfns = jn.on.right.toJavaScript('p',query.defaultTableid); + // source.onrightfn = new Function('p', 'return '+source.onrightfns); + + var lefts = ''; + var rights = ''; + var middles = ''; + var middlef = false; + // Test right and left sides + var ls = jn.on.left.toJavaScript('p',query.defaultTableid,query.defcols); + var rs = jn.on.right.toJavaScript('p',query.defaultTableid,query.defcols); + + if((ls.indexOf("p['"+alias+"']")>-1) && !(rs.indexOf("p['"+alias+"']")>-1)){ + if((ls.match(/p\[\'.*?\'\]/g)||[]).every(function(s){ + return s == "p['"+alias+"']"})) { rights = ls; } + else { middlef = true }; + + } else if(!(ls.indexOf("p['"+alias+"']")>-1) && (rs.indexOf("p['"+alias+"']")>-1)){ + if((rs.match(/p\[\'.*?\'\]/g)||[]).every(function(s){ + return s == "p['"+alias+"']"})) { lefts = ls; } + else { middlef = true }; + } else { + middlef = true; + } + +// console.log(alias, 1,lefts, rights, middlef); + + if((rs.indexOf("p['"+alias+"']")>-1) && !(ls.indexOf("p['"+alias+"']")>-1)){ + if((rs.match(/p\[\'.*?\'\]/g)||[]).every(function(s){ + return s == "p['"+alias+"']"})) { rights = rs; } + else { middlef = true }; + } else if(!(rs.indexOf("p['"+alias+"']")>-1) && (ls.indexOf("p['"+alias+"']")>-1)){ + if((ls.match(/p\[\'.*?\'\]/g)||[]).every(function(s){ + return s == "p['"+alias+"']"})) { lefts = rs; } + else { middlef = true }; + } else { + middlef = true; + } + +// console.log(alias, 2,lefts, rights, middlef); + + if(middlef) { +// middles = jn.on.toJavaScript('p',query.defaultTableid); +// } else { + rights = ''; + lefts = ''; + middles = jn.on.toJavaScript('p',query.defaultTableid,query.defcols); + source.optimization = 'no'; + // What to here? + } + + source.onleftfns = lefts; + source.onrightfns = rights; + source.onmiddlefns = middles || 'true'; +// console.log(source.onleftfns, '-',source.onrightfns, '-',source.onmiddlefns); + + source.onleftfn = new Function('p,params,alasql', 'return '+source.onleftfns); + source.onrightfn = new Function('p,params,alasql', 'return '+source.onrightfns); + source.onmiddlefn = new Function('p,params,alasql', 'return '+source.onmiddlefns); + +// } else if(jn.on instanceof yy.Op && jn.on.op == 'AND') { +// console.log('join on and ',jn); + + } else { +// console.log('no optimization'); + source.optimization = 'no'; +// source.onleftfn = returnTrue; +// source.onleftfns = "true"; + source.onmiddlefns = jn.on.toJavaScript('p',query.defaultTableid,query.defcols); + source.onmiddlefn = new Function('p,params,alasql','return '+jn.on.toJavaScript('p',query.defaultTableid,query.defcols)); + }; +// console.log(source.onleftfns, source.onrightfns, source.onmiddlefns); + + // Optimization function + }; + +// source.data = alasql.databases[source.databaseid].tables[source.tableid].data; +//console.log(source, jn); + // TODO SubQueries +/* if(source.joinmode == 'RIGHT') { + var prevSource = query.sources.pop(); + if(prevSource.joinmode == 'INNER') { + prevSource.joinmode = 'LEFT'; + var onleftfn = prevSource.onleftfn; + var onleftfns = prevSource.onleftfns; + var onrightfn = prevSource.onrightfn; + var onrightfns = prevSource.onrightfns; + var optimization = prevSource.optimization; + + prevSource.onleftfn = source.onrightfn; + prevSource.onleftfns = source.onrightfns; + prevSource.onrightfn = source.onleftfn; + prevSource.onrightfns = source.onleftfns; + prevSource.optimization = source.optimization; + + source.onleftfn = onleftfn; + source.onleftfns = onleftfns; + source.onrightfn = onrightfn; + source.onrightfns = onrightfns; + source.optimization = optimization; + + source.joinmode = 'INNER'; + query.sources.push(source); + query.sources.push(prevSource); + } else { + throw new Error('Do not know how to process this SQL'); + } + } else { + query.sources.push(source); + } +*/ + query.sources.push(source); + }; + }); +// console.log('sources',query.sources); +} + + + +yy.Select.prototype.compileWhere = function(query) { + if(this.where) { + if(typeof this.where == "function") { + return this.where; + } else { + s = this.where.toJavaScript('p',query.defaultTableid,query.defcols); + query.wherefns = s; +// console.log(s); + return new Function('p,params,alasql','return '+s); + } + } else return function(){return true}; +}; + + + +yy.Select.prototype.compileWhereJoins = function(query) { + return; + + // TODO Fix Where optimization + //console.log(query); + + optimizeWhereJoin(query, this.where.expression); + + //for sources compile wherefs + query.sources.forEach(function(source) { + if(source.srcwherefns) { + source.srcwherefn = new Function('p,params,alasql','return '+source.srcwherefns); + }; + if(source.wxleftfns) { + source.wxleftfn = new Function('p,params,alasql','return '+source.wxleftfns); + }; + if(source.wxrightfns) { + source.wxrightfn = new Function('p,params,alasql','return '+source.wxrightfns); + }; +// console.log(source.alias, source.wherefns) +// console.log(source); + }); +}; + +function optimizeWhereJoin (query, ast) { + if(!ast) return false; + if(!(ast instanceof yy.Op)) return; + if(ast.op != '=' && ast.op != 'AND') return; + if(ast.allsome) return; + + var s = ast.toJavaScript('p',query.defaultTableid,query.defcols); + var fsrc = []; + query.sources.forEach(function(source,idx) { + // Optimization allowed only for tables only + if(source.tableid) { + // This is a good place to remove all unnecessary optimizations + if(s.indexOf('p[\''+source.alias+'\']')>-1) fsrc.push(source); + }; + }); +//console.log(fsrc.length); +// if(fsrc.length < query.sources.length) return; +// console.log(ast); +// console.log(s); +// console.log(fsrc.length); + if(fsrc.length == 0) { +// console.log('no optimization, can remove this part of ast'); + return; + } else if (fsrc.length == 1) { + + if(!(s.match(/p\[\'.*?\'\]/g)||[]) + .every(function(s){ + return s == "p['"+fsrc[0].alias+"']"})) { + return; + // This is means, that we have column from parent query + // So we return without optimization + } + + var src = fsrc[0]; // optmiization source + src.srcwherefns = src.srcwherefns ? src.srcwherefns+'&&'+s : s; + + if((ast instanceof yy.Op) && (ast.op == '=' && !ast.allsome)) { + if(ast.left instanceof yy.Column) { + var ls = ast.left.toJavaScript('p',query.defaultTableid,query.defcols); + var rs = ast.right.toJavaScript('p',query.defaultTableid,query.defcols); + if(rs.indexOf('p[\''+fsrc[0].alias+'\']') == -1) { + fsrc[0].wxleftfns = ls; + fsrc[0].wxrightfns = rs; + } + } if(ast.right instanceof yy.Column) { + var ls = ast.left.toJavaScript('p',query.defaultTableid,query.defcols); + var rs = ast.right.toJavaScript('p',query.defaultTableid,query.defcols); + if(ls.indexOf('p[\''+fsrc[0].alias+'\']') == -1) { + fsrc[0].wxleftfns = rs; + fsrc[0].wxrightfns = ls; + } + } + } + ast.reduced = true; // To do not duplicate wherefn and srcwherefn + return; + } else { + if(ast.op = 'AND') { + optimizeWhereJoin(query,ast.left); + optimizeWhereJoin(query,ast.right); + } + } + +}; + + + + +/* +// +// Select compiler part for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +/** + Compile group of statements + */ +yy.Select.prototype.compileGroup = function(query) { +// console.log(this.group); + var self = this; + var tableid = query.sources[0].alias; + var defcols = query.defcols; +// console.log(16,tableid, defcols); + +// console.log(query.sources[0].alias,query.defcols); + var allgroup = [[]]; + if(this.group) { + allgroup = decartes(this.group,query); + } +// console.log(23,allgroup); + +// console.log(allgroup); + // 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; + +//console.log(42,294, this.group); +//console.log(allgroups); +// console.log(42,364,query.selectColumns) + +if(false) { + allgroups.forEach(function(col2){ +// console.log(42,365,colid, query.selectColumns[colid]) + if(query.selectColumns[colid]) { +// console.log(colid,'ok'); + } else { +// if(colid.indexOf()) +// console.log(colid,'bad'); + var tmpid = 'default'; + if(query.sources.length > 0) tmpid = query.sources[0].alias; +// console.log(new yy.Column({columnid:colid}).toJavaScript('p',query.sources[0].alias)); +// query.selectfns += 'r[\''+colid+'\']=p[\''+tmpid+'\'][\''+colid+'\'];'; +//console.log(374, colid); + if(Object.keys(query.selectColumns).length != 0) query.removeKeys.push(colid); + query.selectfns += 'r[\''+escapeq(colid)+'\']='+(new yy.Column({columnid:colid}).toJavaScript('p',tmpid))+';'; + } + }); +}; + + // Create negative array + + var s = ''; +// s+= query.selectfns; + + allgroup.forEach(function(agroup) { +//console.log(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 +// else return "r['"+columnid+"']"; + else return coljs; + }); + if(rg.length == 0) rg = ["''"]; + + // console.log('rg',rg); + + s += rg.join('+"`"+'); + s += '];if(!g) {this.groups.push((g=this.xgroups['; + s += rg.join('+"`"+'); + s += '] = {'; +// s += ']=r'; + s += agroup.map(function(col2){ + var columnid = col2.split('\t')[0]; + var coljs = col2.split('\t')[1]; + + if(columnid == '') return ''; + else return "'"+columnid+"':"+coljs+","; + }).join(''); + + var neggroup = arrayDiff(allgroups,agroup); + +// console.log(neggroup); + + s += neggroup.map(function(col2){ + var columnid = col2.split('\t')[0]; + var coljs = col2.split('\t')[1] + return "'"+columnid+"':null,"; + }).join(''); + + var aft = ''; +// s += self.columns.map(function(col){ +//console.log('query.selectGroup',query.selectGroup); + s += query.selectGroup.map(function(col,idx){ +//console.log(idx, col.toString(), col.as); + var colexp = col.expression.toJavaScript("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' + || col.aggregatorid == 'MIN' + || col.aggregatorid == 'MAX' + || col.aggregatorid == 'FIRST' + || col.aggregatorid == 'LAST' +// || col.aggregatorid == 'AVG' +// ) { return '\''+col.as+'\':r[\''+col.as+'\'],'; }//f.field.arguments[0].toJavaScript(); + ) { return '\''+colas+'\':'+colexp+','; }//f.field.arguments[0].toJavaScript(); + 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 { + return '\''+colas+'\':(typeof '+colexp+' != "undefined")?1:0,'; + } + +// else if(col.aggregatorid == 'MIN') { return '\''+col.as+'\':r[\''+col.as+'\'],'; } +// else if(col.aggregatorid == 'MAX') { return '\''+col.as+'\':r[\''+col.as+'\'],'; } + } else if(col.aggregatorid == 'AVG') { + query.removeKeys.push('_SUM_'+colas); + query.removeKeys.push('_COUNT_'+colas); + return '\''+colas+'\':'+colexp+',\'_SUM_'+colas+'\':'+colexp+',\'_COUNT_'+colas+'\':1,'; + } else if(col.aggregatorid == 'AGGR') { + aft += ',g[\''+colas+'\']='+col.expression.toJavaScript('g',-1); + return ''; + } else if(col.aggregatorid == 'REDUCE') { + return '\''+colas+'\':alasql.aggr[\''+col.funcid+'\']('+colexp+'),'; + } + return ''; + } else return ''; + }).join(''); + + + + + + // columnid:r.columnid + // var srg = [];//rg.map(function(fn){ return (fn+':'+fn); }); + + // var srg = this.group.map(function(col){ + // if(col == '') return ''; + // else return col.columnid+':'+col.toJavaScript('r',''); + // }); + + // Initializw aggregators + + /* + this.columns.forEach(function(col){ + // console.log(f); + // if(f.constructor.name == 'LiteralValue') return ''; + + + if (col instanceof yy.AggrValue) { + if (col.aggregatorid == 'SUM') { srg.push("'"+col.as+'\':0'); }//f.field.arguments[0].toJavaScript(); + else if(col.aggregatorid == 'COUNT') {srg.push( "'"+col.as+'\':0'); } + else if(col.aggregatorid == 'MIN') { srg.push( "'"+col.as+'\':Infinity'); } + else if(col.aggregatorid == 'MAX') { srg.push( "'"+col.as+'\':-Infinity'); } + // else if(col.aggregatorid == 'AVG') { srg.push(col.as+':0'); } + // return 'group.'+f.name.value+'=+(+group.'+f.name.value+'||0)+'+f.field.arguments[0].toJavaScript('rec','')+';'; //f.field.arguments[0].toJavaScript(); + }; + + }); + + */ + + /*****************/ + + // s += srg.join(','); + + // var ss = []; + // gff.forEach(function(fn){ + // ss.push(fn+':rec.'+fn); + // }); + // s += ss.join(','); + // s += '});};'; + + s += '}'+aft+',g));} else {'; + // console.log(s, this.columns); + + + + // var neggroup = arrayDiff(allgroups,agroup); + + // console.log(agroup,neggroup); + + // s += neggroup.map(function(columnid){ + // return "g['"+columnid+"']=null;"; + // }).join(''); + + // console.log(s); + + + //console.log(query.selectfn); +// s += self.columns.map(function(col){ + s += query.selectGroup.map(function(col,idx){ + var colas = col.nick; + // if(typeof colas == 'undefined') { + // if(col instanceof yy.Column) colas = col.columnid; + // else colas = col.toString(); + // } + var colexp = col.expression.toJavaScript("p",tableid,defcols); + + if (col instanceof yy.AggrValue) { + if(col.distinct) { + var pre = 'if(typeof '+colexp+'!="undefined" && (!g[\'$$_VALUES_'+colas+'\']['+colexp+'])) \ + {'; + var post = 'g[\'$$_VALUES_'+colas+'\']['+colexp+']=true;}'; + } else { + var pre = '', post = ''; + } + if (col.aggregatorid == 'SUM') { return pre+'g[\''+colas+'\']+='+colexp+';'+post; }//f.field.arguments[0].toJavaScript(); + else if(col.aggregatorid == 'COUNT') { +// console.log(221,col.expression.columnid == '*'); + if(col.expression.columnid == '*') return pre+'g[\''+colas+'\']++;'+post; + else { + return pre+'if(typeof '+colexp+'!="undefined") g[\''+colas+'\']++;'+post; + } + } + else if(col.aggregatorid == 'ARRAY') { return pre+'g[\''+colas+'\'].push('+colexp+');'+post; } + else if(col.aggregatorid == 'MIN') { return pre+'g[\''+colas+'\']=Math.min(g[\''+colas+'\'],'+colexp+');'+post; } + else if(col.aggregatorid == 'MAX') { return pre+'g[\''+colas+'\']=Math.max(g[\''+colas+'\'],'+colexp+');'+post; } + else if(col.aggregatorid == 'FIRST') { return ''; } + else if(col.aggregatorid == 'LAST') { return pre+'g[\''+colas+'\']='+colexp+';'+post; } + else if(col.aggregatorid == 'AVG') { + return pre+'g[\'_SUM_'+colas+'\']+='+colexp+';' + + 'g[\'_COUNT_'+colas+'\']++;' + + 'g[\''+colas+'\']=g[\'_SUM_'+colas+'\']/g[\'_COUNT_'+colas+'\'];'+post; +// } + // else if(col.aggregatorid == 'AVG') { srg.push(colas+':0'); } + } else if(col.aggregatorid == 'AGGR') { + return pre+'g[\''+colas+'\']='+col.expression.toJavaScript('g',-1)+';'+post; + } else if(col.aggregatorid == 'REDUCE') { + return pre+'g[\''+colas+'\']=alasql.aggr.'+col.funcid+'('+colexp+',g[\''+colas+'\']);'+post; + } + return ''; + } else return ''; + }).join(''); + + + // s += selectFields.map(function(f){ + // console.log(f); + // if(f.constructor.name == 'LiteralValue') return ''; + // if (f.field instanceof SQLParser.nodes.FunctionValue + // && (f.field.name.toUpperCase() == 'SUM' || f.field.name.toUpperCase() == 'COUNT')) { + // return 'group.'+f.name.value+'=+(+group.'+f.name.value+'||0)+'+f.field.arguments[0].toJavaScript('rec','')+';'; //f.field.arguments[0].toJavaScript(); + // return 'group.'+f.name.value+'+='+f.field.arguments[0].toJavaScript('rec','')+';'; //f.field.arguments[0].toJavaScript(); + // return 'group.'+f.name.value+'+=rec.'+f.name.value+';'; //f.field.arguments[0].toJavaScript(); + // }; + // return ''; + // }).join(''); + + //s += ' group.amt += rec.emplid;'; + //s += 'group.count++;'; + s += '}'; + + }); + +// console.log('groupfn',s); + return new Function('p,params,alasql',s); + +} + + +/* +// +// Select compiler part for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +// yy.Select.prototype.compileSources = function(query) { +// return sources; +// }; + +function compileSelectStar (query,alias) { + // console.log(query.aliases[alias]); +// console.log(query,alias); + // console.log(query.aliases[alias].tableid); +// console.log(42,631,alias); +// console.log(query.aliases); + var s = '', sp = '', ss=[]; +// if(!alias) { +// sp += 'for(var k1 in p) var w=p[k1];for(var k2 in w){r[k2]=w[k2]};'; +// } else { + if(query.aliases[alias].tableid) { + var columns = alasql.databases[query.aliases[alias].databaseid].tables[query.aliases[alias].tableid].columns; + }; + // Check if this is a Table or other + + if(columns && columns.length > 0) { + columns.forEach(function(tcol){ + ss.push('\''+tcol.columnid+'\':p[\''+alias+'\'][\''+tcol.columnid+'\']'); + query.selectColumns[escapeq(tcol.columnid)] = true; + + // console.log('ok',s); + + var coldef = { + columnid:tcol.columnid, + dbtypeid:tcol.dbtypeid, + dbsize:tcol.dbsize, + dbprecision:tcol.dbprecision, + dbenum: tcol.dbenum + }; + query.columns.push(coldef); + query.xcolumns[coldef.columnid]=coldef; + + }); +//console.log(999,columns); + } else { + // if column not exists, then copy all + sp += 'var w=p["'+alias+'"];for(var k in w){r[k]=w[k]};'; +//console.log(777, sp); + query.dirtyColumns = true; + } +// } +//console.log({s:ss.join(','),sp:sp}); + return {s:ss.join(','),sp:sp}; +} + + +yy.Select.prototype.compileSelect1 = function(query) { + 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){ +//console.log(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); + if(ret.s) ss = ss.concat(ret.s); + sp += ret.sp; + + } else { +// console.log('aliases', query.aliases); + for(var alias in query.aliases) { + var ret = compileSelectStar(query, alias); //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; +// console.log(query.sources); + 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 != '_') { + 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]) { +// console.log(query.database,tbid,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; +//console.log(xcolumns, col,123); +// console.log(0); + if(xcolumns && columns.length > 0) { +// console.log(1); + var tcol = xcolumns[col.columnid]; + var coldef = { + columnid:col.as || col.columnid, + dbtypeid:tcol.dbtypeid, + dbsize:tcol.dbsize, + dbpecision:tcol.dbprecision, + dbenum: tcol.dbenum, + }; +// console.log(2); + query.columns.push(coldef); + query.xcolumns[coldef.columnid]=coldef; + } else { + query.dirtyColumns = true; + } + } else { + // This is a subquery? + // throw new Error('There is now such table \''+col.tableid+'\''); + }; + + } + } else if(col instanceof yy.AggrValue) { + if(!self.group) { +// self.group=[new yy.Column({columnid:'q',as:'q' })]; + self.group = ['']; + } + if(!col.as) col.as = escapeq(col.toString()); + if (col.aggregatorid == 'SUM' || col.aggregatorid == 'MAX' || col.aggregatorid == 'MIN' || + col.aggregatorid == 'FIRST' || col.aggregatorid == 'LAST' || + col.aggregatorid == 'AVG' || col.aggregatorid == 'ARRAY' || col.aggregatorid == 'REDUCE' + ) { + ss.push("'"+escapeq(col.as)+'\':'+col.expression.toJavaScript("p",query.defaultTableid,query.defcols)) + } else if (col.aggregatorid == 'COUNT') { + ss.push("'"+escapeq(col.as)+"':1"); + // Nothing + } + query.selectColumns[col.aggregatorid+'('+escapeq(col.expression.toString())+')'] = thtd; + +// else if (col.aggregatorid == 'MAX') { +// ss.push((col.as || col.columnid)+':'+col.toJavaScript("p.",query.defaultTableid)) +// } else if (col.aggregatorid == 'MIN') { +// ss.push((col.as || col.columnid)+':'+col.toJavaScript("p.",query.defaultTableid)) +// } + } else { + ss.push('\''+escapeq(col.as || col.columnid || col.toString())+'\':'+col.toJavaScript("p",query.defaultTableid,query.defcols)); +// ss.push('\''+escapeq(col.toString())+'\':'+col.toJavaScript("p",query.defaultTableid)); + //if(col instanceof yy.Expression) { + query.selectColumns[escapeq(col.as || col.columnid || col.toString())] = true; + } + }); + s += ss.join(',')+'};'+sp; + return s; +//console.log(42,753,query.xcolumns, query.selectColumns); +} +yy.Select.prototype.compileSelect2 = function(query) { + + var s = query.selectfns ; +// console.log(s); + return new Function('p,params,alasql',s+'return r'); +}; + + +yy.Select.prototype.compileSelectGroup0 = function(query) { + var self = this; + self.columns.forEach(function(col,idx){ + if(col instanceof yy.Column && col.columnid == '*') { + } else { + var colas; + // = col.as; + if(col instanceof yy.Column) { + colas = escapeq(col.columnid); + } else { + colas = escapeq(col.toString()); + } + for(var i=0;irb) return 1; + if(ra==rb) return 0; + return -1; + } + }; + + var s = ''; + var sk = ''; + this.order.forEach(function(ord,idx){ + // console.log(ord instanceof yy.Expression); + // console.log(ord.toJavaScript('a','')); + // console.log(ord.expression instanceof yy.Column); + + // Date conversion + var dg = ''; +//console.log(ord.expression, ord.expression instanceof yy.NumValue); + if(ord.expression instanceof yy.NumValue) { + ord.expression = self.columns[ord.expression.value-1]; + }; + + 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') 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.toJavaScript('a','')+dg+(ord.direction == 'ASC'?'>':'<')+ord.toJavaScript('b','')+dg+')return 1;'; + s += 'if('+ord.toJavaScript('a','')+dg+'=='+ord.toJavaScript('b','')+dg+'){'; + } + +// if(columnid == '_') { +// s += 'if(a'+dg+(ord.direction == 'ASC'?'>':'<')+'b'+dg+')return 1;'; +// s += 'if(a'+dg+'==b'+dg+'){'; +// } else { + // TODO Add date comparision + // s += 'if(a[\''+columnid+"']"+dg+(ord.direction == 'ASC'?'>':'<')+'b[\''+columnid+"']"+dg+')return 1;'; + // s += 'if(a[\''+columnid+"']"+dg+'==b[\''+columnid+"']"+dg+'){'; +// } + sk += '}'; + }); + s += 'return 0;'; + s += sk+'return -1'; + query.orderfns = s; +//console.log(s); + return new Function('a,b',s); + }; +}; + + + +/* +// +// ROLLUP(), CUBE(), GROUPING SETS() for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +/** + Calculate ROLLUP() combination + */ + +var rollup = function (a,query) { + var rr = []; + var mask = 0; + var glen = a.length; + for(var g=0;g'+gv[t]+'<',gv[t]=='',typeof gv[t]); +// console.log(gv[t].toString()); +//console.log('+++'); + res = res.map(function(r){ + query.groupColumns[escapeq(gv[t].toString())] = escapeq(gv[t].toString()); + return r.concat(escapeq(gv[t].toString()) + +'\t' + +gv[t].toJavaScript('p',query.sources[0].alias,query.defcols)) + }); +// res = res.concat(gv[t]); + }; + + // switch(gv[t].t) { + // case 'plain': + // res = res.map(function(r){return r.concat(gv[t].p)}); + + // break; + // case 'rollup': res = cartes(res,rollup(gv[t].p)); break; + // case 'cube': res = cartes(res,cube(gv[t].p)); break; + // case 'groupingsets': res = cartes(res,groupingsets(gv[t].p)); break; + // default: res = res.concat(gv[t]); + // } + }; + return res; + } else if(gv instanceof yy.FuncValue) { +// console.log(gv); + query.groupColumns[escapeq(gv.toString())] = escapeq(gv.toString()); + return [gv.toString()+'\t'+gv.toJavaScript('p',query.sources[0].alias,query.defcols)]; + } else if(gv instanceof yy.Column) { + gv.nick = escapeq(gv.columnid); + query.groupColumns[gv.nick] = gv.nick; + return [gv.nick+'\t'+gv.toJavaScript('p',query.sources[0].alias,query.defcols)]; // Is this ever happened? + // } else if(gv instanceof yy.Expression) { + // return [gv.columnid]; // Is this ever happened? + } else { + query.groupColumns[escapeq(gv.toString())] = escapeq(gv.toString()); + return [escapeq(gv.toString())+'\t'+gv.toJavaScript('p',query.sources[0].alias,query.defcols)]; +// throw new Error('Single argument in the group without array'); + }; + + + // switch(gv.t) { + // case 'plain': return gv.p; break; + // case 'rollup': return rollup(gv.p); break; + // case 'cube': return cube(gv.p); break; + // case 'groupingsets': return groupingsets(gv.p); break; + // default: return [gv];//return decartes(gv.p); + // } + // return gv; +}; + + + + +/* +// +// Select run-time part for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +yy.Select.prototype.compileDefCols = function(query, databaseid) { +// console.log('defcols'); + var defcols = {}; + if(this.from) { + this.from.forEach(function(fr){ + if(fr instanceof yy.Table) { + var alias = fr.as || fr.tableid; +// console.log(alasql.databases[fr.databaseid || databaseid]); +// console.log(alasql.databases[fr.databaseid || databaseid].tables, fr.tableid); +//console.log(alasql.databases[fr.databaseid || databaseid].tables, fr.tableid); +//console.log(alasql.databases); + var table = alasql.databases[fr.databaseid || databaseid].tables[fr.tableid]; +//console.log(table); + 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.ParamValue) { + + } else if(fr instanceof yy.VarValue) { + + } else if(fr instanceof yy.FuncValue) { + + } else if(fr instanceof yy.FromData) { + + } else { + throw new Error('Unknown type of FROM clause'); + }; + }); + }; + + if(this.joins) { + this.joins.forEach(function(jn){ +// console.log(jn); + 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]; +// console.log(jn.table.tableid, jn.table.databaseid); + 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; + // } +// console.log(defcols); + return defcols; +} + +/* +// +// UNION for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +// SELECT UNION statement + +yy.Union = function (params) { return yy.extend(this, params); } +yy.Union.prototype.toString = function () { + return K('UNION'); +}; + +yy.Union.prototype.compile = function (tableid) { + return null; +}; + +/* +// +// CROSS AND OUTER APPLY for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +yy.Apply = function (params) { return yy.extend(this, params); } +yy.Apply.prototype.toString = function () { + var s = K(this.applymode)+' '+K('APPLY')+' ('; + s += this.select.toString()+')'; + if(this.as) s += ' '+K('AS')+' '+L(this.as); + return s; +}; + + + +/* +// +// CROSS AND OUTER APPLY for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +yy.Over = function (params) { return yy.extend(this, params); } +yy.Over.prototype.toString = function () { + var s = K('OVER')+' ('; + if(this.partition) { + s += K('PARTITION')+' '+K('BY')+' '+this.partition.toString(); + if(this.order) s+=' '; + } + if(this.order) { + s += K('ORDER')+' '+K('BY')+' '+this.order.toString(); + } + s += ')'; + return s; +}; + + + +/* +// +// Expressions for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +yy.ExpressionStatement = function(params) { return yy.extend(this, params); }; +yy.ExpressionStatement.prototype.toString = function() { + return this.expression.toString(); +}; + +yy.ExpressionStatement.prototype.execute = function (databaseid, params, cb) { + if(this.expression) { +// console.log(this.expression.toJavaScript('','', null)); +// console.log(this.expression.toJavaScript('','', null)); + var expr = new Function("params,alasql,p",'return '+this.expression.toJavaScript('','', null)); + var res = expr(params,alasql); + if(cb) res = cb(res); + return res; + } +} + +yy.Expression = function(params) { return yy.extend(this, params); }; +yy.Expression.prototype.toString = function() { + var s = this.expression.toString(); + if(this.order) s += ' '+this.order.toString(); + if(this.nocase) s += ' '+K('COLLATE')+' '+K('NOCASE'); + return s; +}; +yy.Expression.prototype.findAggregator = function (query){ + if(this.expression.findAggregator) this.expression.findAggregator(query); +}; + +yy.Expression.prototype.toJavaScript = function(context, tableid, defcols) { +// console.log('Expression',this); + if(this.expression.reduced) return 'true'; + return this.expression.toJavaScript(context, tableid, defcols); +}; +yy.Expression.prototype.compile = function(context, tableid, defcols){ +// console.log('Expression',this); + if(this.reduced) return returnTrue(); + return new Function('p','return '+this.toJavaScript(context, tableid, defcols)); +}; + + +yy.JavaScript = function(params) { return yy.extend(this, params); }; +yy.JavaScript.prototype.toString = function() { + var s = '``'+this.value+'``'; + return s; +}; + +yy.JavaScript.prototype.toJavaScript = function(context, tableid, defcols) { +// console.log('Expression',this); + return '('+this.value+')'; +}; +yy.JavaScript.prototype.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; +} + + +yy.Literal = function (params) { return yy.extend(this, params); } +yy.Literal.prototype.toString = function() { + var s = this.value; + if(this.value1) s = this.value1+'.'+s; +// else s = tableid+'.'+s; + return L(s); +} + + +yy.Join = function (params) { return yy.extend(this, params); } +yy.Join.prototype.toString = function() { + var s = NL()+ID(); + if(this.joinmode) s += K(this.joinmode)+' '; + s += K('JOIN')+this.table.toString(); + return s; +} + +//yy.Join.prototype.toJavaScript = function(context, tableid) { +// return 'JOIN'+this.table.toString(); +//} + + +yy.Table = function (params) { return yy.extend(this, params); } +yy.Table.prototype.toString = function() { + var s = this.tableid; +// if(this.joinmode) + if(this.databaseid) s = this.databaseid+'.'+s; + return L(s); +}; + + +yy.View = function (params) { return yy.extend(this, params); } +yy.View.prototype.toString = function() { + var s = this.viewid; +// if(this.joinmode) + if(this.databaseid) s = this.databaseid+'.'+s; + return L(s); +}; + + +yy.Op = function (params) { return yy.extend(this, params); } +yy.Op.prototype.toString = function() { + if(this.op == 'IN' || this.op == 'NOT IN') { + return this.left.toString()+" "+P(this.op)+" ("+this.right.toString()+")"; + } + if(this.allsome) { + return this.left.toString()+" "+P(this.op)+" "+this.allsome+' ('+this.right.toString()+')'; + } + if(this.op == '->') { + var s = this.left.toString()+"->"; +// console.log(this.right); + 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()+" "+P(this.op)+" "+(this.allsome?this.allsome+' ':'')+this.right.toString(); +}; + +yy.Op.prototype.findAggregator = function (query){ +// console.log(this.toString()); + 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); + } +}; + +yy.Op.prototype.toType = function(tableid) { + if(['-','*','/','%','^'].indexOf(this.op) >-1) return 'number'; + 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'].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'; +}; + +yy.Op.prototype.toJavaScript = function(context,tableid,defcols) { +// console.log(this); + var op = this.op; + if(this.op == '=') op = '==='; + else if(this.op == '<>') op = '!='; + else if(this.op == 'OR') op = '||'; + + if(this.op == '->') { +// console.log(this.right, typeof this.right); + if(typeof this.right == "string") { + return this.left.toJavaScript(context,tableid, defcols)+'["'+this.right+'"]'; + } else if(typeof this.right == "number") { + return this.left.toJavaScript(context,tableid, defcols)+'['+this.right+']'; + } else if(this.right instanceof yy.FuncValue) { + ss = []; + if(!this.right.args || this.right.args.length == 0) { + } else { + var ss = this.right.args.map(function(arg){ + return arg.toJavaScript(context,tableid, defcols); + }); + } + return this.left.toJavaScript(context,tableid, defcols)+'[\''+this.right.funcid+'\']('+ + ss.join(',')+')'; + } else { + return this.left.toJavaScript(context,tableid, defcols)+'['+this.right.toJavaScript(context,tableid, defcols)+']'; + } + } + + if(this.op == 'IS') { + return '((typeof '+this.left.toJavaScript(context,tableid, defcols)+"=='undefined') == " + + '(typeof '+this.right.toJavaScript(context,tableid, defcols)+"=='undefined'))"; + } + + + if(this.op == '==') { + return 'alasql.utils.deepEqual('+this.left.toJavaScript(context,tableid, defcols)+","+this.right.toJavaScript(context,tableid, defcols)+')'; + } + if(this.op == '===') { + return "(("+this.left.toJavaScript(context,tableid, defcols)+").valueOf()===("+this.right.toJavaScript(context,tableid, defcols)+'.valueOf()))'; + } + + if(this.op == '!===') { + return "!(("+this.left.toJavaScript(context,tableid, defcols)+").valueOf()===("+this.right.toJavaScript(context,tableid, defcols)+'.valueOf()))'; + } + + + if(this.op == '!==') { + return '(!alasql.utils.deepEqual('+this.left.toJavaScript(context,tableid, defcols)+","+this.right.toJavaScript(context,tableid, defcols)+'))'; + } + + if(this.op == 'LIKE') { + var s = "("+this.left.toJavaScript(context,tableid, defcols)+"+'')"+ + ".toUpperCase().match(new RegExp('^'+("+this.right.toJavaScript(context,tableid, defcols)+").replace(/\\\%/g,'.*').toUpperCase()+'$','g'))" +// console.log(s); + return s; + }; + + if(this.op == 'NOT LIKE') { + var s = "!(("+this.left.toJavaScript(context,tableid, defcols)+"+'')"+ + ".toUpperCase().match(new RegExp('^'+("+this.right.toJavaScript(context,tableid, defcols)+").replace(/\\\%/g,'.*').toUpperCase()+'$','g')))" + return s; + }; + + if(this.op == 'BETWEEN') { + if(this.right instanceof yy.Op && this.right.op == 'AND') { + return '(('+this.right.left.toJavaScript(context,tableid, defcols)+'<='+this.left.toJavaScript(context,tableid, defcols)+')&&'+ + '('+this.left.toJavaScript(context,tableid, defcols)+'<='+this.right.right.toJavaScript(context,tableid, defcols)+'))'; + } else { + throw new Error('Wrong BETWEEN operator without AND part'); + } + }; + + if(this.op == 'NOT BETWEEN') { + if(this.right instanceof yy.Op && this.right.op == 'AND') { + return '!(('+this.right.left.toJavaScript(context,tableid, defcols)+'<='+this.left.toJavaScript(context,tableid, defcols)+')&&'+ + '('+this.left.toJavaScript(context,tableid, defcols)+'<='+this.right.right.toJavaScript(context,tableid, defcols)+'))'; + } else { + throw new Error('Wrong NOT BETWEEN operator without AND part'); + } + }; + + if(this.op == 'IN') { + if(this.right instanceof yy.Select ) { + var s = '('; +// s += 'this.query.queriesdata['+this.queriesidx+']'; + s += 'alasql.utils.flatArray(this.query.queriesfn['+(this.queriesidx)+'](params,null,p))'; + s += '.indexOf('; + s += this.left.toJavaScript(context,tableid, defcols)+')>-1)'; + return s; + } else if(this.right instanceof Array ) { +// if(this.right.length == 0) return 'false'; + var s = '(['+this.right.map(function(a){return a.toJavaScript(context,tableid, defcols)}).join(',')+'].indexOf('; + s += this.left.toJavaScript(context,tableid, defcols)+')>-1)'; +//console.log(s); + return s; + } else { + var s = '('+this.right.toJavaScript(context,tableid, defcols)+'.indexOf('; + s += this.left.toJavaScript(context,tableid, defcols)+')>-1)'; + return s; +// } else { +// throw new Error('Wrong IN operator without SELECT part'); + } + }; + + + if(this.op == 'NOT IN') { + if(this.right instanceof yy.Select ) { + var s = '(' + //this.query.queriesdata['+this.queriesidx+'] + s += 'alasql.utils.flatArray(this.query.queriesfn['+(this.queriesidx)+'](params,null,p))'; + s +='.indexOf('; + s += this.left.toJavaScript(context,tableid, defcols)+')<0)'; + return s; + } else if(this.right instanceof Array ) { +// if(this.right.length == 0) return 'true'; + var s = '(['+this.right.map(function(a){return a.toJavaScript(context,tableid, defcols)}).join(',')+'].indexOf('; + s += this.left.toJavaScript(context,tableid, defcols)+')<0)'; + return s; + } else { + throw new Error('Wrong NOT IN operator without SELECT part'); + } + }; + + if(this.allsome == 'ALL') { + if(this.right instanceof yy.Select ) { +// var s = 'this.query.queriesdata['+this.queriesidx+']'; + var s = 'alasql.utils.flatArray(this.query.queriesfn['+(this.queriesidx)+'](params,null,p))'; + + s +='.every(function(b){return ('; + s += this.left.toJavaScript(context,tableid, defcols)+')'+op+'b})'; + return s; + } else if(this.right instanceof Array ) { + var s = '['+this.right.map(function(a){return a.toJavaScript(context,tableid, defcols)}).join(',')+'].every(function(b){return ('; + s += this.left.toJavaScript(context,tableid, defcols)+')'+op+'b})'; + return s; + } else { + throw new Error('Wrong NOT IN operator without SELECT part'); + } + }; + + if(this.allsome == 'SOME' || this.allsome == 'ANY') { + if(this.right instanceof yy.Select ) { +// var s = 'this.query.queriesdata['+this.queriesidx+']'; + var s = 'alasql.utils.flatArray(this.query.queriesfn['+(this.queriesidx)+'](params,null,p))'; + s+='.some(function(b){return ('; + s += this.left.toJavaScript(context,tableid, defcols)+')'+op+'b})'; + return s; + } else if(this.right instanceof Array ) { + var s = '['+this.right.map(function(a){return a.toJavaScript(context,tableid, defcols)}).join(',')+'].some(function(b){return ('; + s += this.left.toJavaScript(context,tableid, defcols)+')'+op+'b})'; + return s; + } else { + throw new Error('Wrong NOT IN operator without SELECT part'); + } + }; + +// Special case for AND optimization (if reduced) + if(this.op == 'AND') { + if(this.left.reduced) { + if(this.right.reduced) { + return 'true'; + } else { + return this.right.toJavaScript(context,tableid, defcols); + } + } else if(this.right.reduced) { + return this.left.toJavaScript(context,tableid, defcols); + } + + // Otherwise process as regular operation (see below) + op = '&&'; + + } + + if(this.op == '^') { + return 'Math.pow('+this.left.toJavaScript(context,tableid, defcols) + +','+this.right.toJavaScript(context,tableid, defcols)+')'; + }; + + + // Change names +// console.log(this); + return '('+this.left.toJavaScript(context,tableid, defcols)+op+this.right.toJavaScript(context,tableid, defcols)+')'; +}; + + + +yy.VarValue = function (params) { return yy.extend(this, params); } +yy.VarValue.prototype.toString = function() { + return '@'+L(this.variable); +}; + +yy.VarValue.prototype.toType = function() { + return 'unknown'; +}; + +yy.VarValue.prototype.toJavaScript = function() { + return "alasql.vars['"+this.variable+"']"; +} + + +yy.NumValue = function (params) { return yy.extend(this, params); } +yy.NumValue.prototype.toString = function() { + return N(this.value.toString()); +}; + +yy.NumValue.prototype.toType = function() { + return 'number'; +}; + +yy.NumValue.prototype.toJavaScript = function() { + return ""+this.value; +} + + + + +yy.StringValue = function (params) { return yy.extend(this, params); } +yy.StringValue.prototype.toString = function() { + return "'"+S(this.value.toString())+"'"; +} + +yy.StringValue.prototype.toType = function() { + return 'string'; +} + +yy.StringValue.prototype.toJavaScript = function() { +// console.log("'"+doubleqq(this.value)+"'"); +// return "'"+doubleqq(this.value)+"'"; + return "'"+escapeq(this.value)+"'"; + +} + + +yy.LogicValue = function (params) { return yy.extend(this, params); } +yy.LogicValue.prototype.toString = function() { + return this.value?'TRUE':'FALSE'; +} + +yy.LogicValue.prototype.toType = function() { + return 'boolean'; +} + +yy.LogicValue.prototype.toJavaScript = function() { + return this.value?'true':'false'; +} + +yy.NullValue = function (params) { return yy.extend(this, params); } +yy.NullValue.prototype.toString = function() { + return 'NULL'; +} +yy.NullValue.prototype.toJavaScript = function() { + return 'undefined'; +} + +yy.ParamValue = function (params) { return yy.extend(this, params); } +yy.ParamValue.prototype.toString = function() { + return '$'+this.param; +} +yy.ParamValue.prototype.toJavaScript = function() { + if(typeof this.param == "string") return "params[\'"+this.param+"\']"; + else return "params["+this.param+"]"; +} + + + +yy.UniOp = function (params) { return yy.extend(this, params); } +yy.UniOp.prototype.toString = function() { + if(this.op == '-') return this.op+this.right.toString(); + if(this.op == '+') return this.op+this.right.toString(); + if(this.op == 'NOT') return this.op+'('+this.right.toString()+')'; + else if(this.op == null) return '('+this.right.toString()+')'; +}; + +yy.UniOp.prototype.findAggregator = function (query){ + if(this.right.findAggregator) this.right.findAggregator(query); +}; + +yy.UniOp.prototype.toType = function(tableid) { + if(this.op == '-') return 'number'; + if(this.op == '+') return 'number'; + if(this.op == 'NOT') return 'boolean'; +}; + +yy.UniOp.prototype.toJavaScript = function(context, tableid, defcols) { + if(this.op == '-') return "(-("+this.right.toJavaScript(context, tableid, defcols)+"))"; + if(this.op == '+') return "("+this.right.toJavaScript(context, tableid, defcols)+")"; + if(this.op == 'NOT') return '!('+this.right.toJavaScript(context, tableid, defcols)+')'; + else if(this.op == null) return '('+this.right.toJavaScript(context, tableid, defcols)+')'; +}; + + + +// yy.Star = function (params) { return yy.extend(this, params); } +// yy.Star.prototype.toString = function() { +// var s = this.fieldid; +// if(this.tableid) { +// s = this.tableid+'.'+s; +// if(this.databaseid) { +// s = this.databaseid+'.'+s; +// } +// } +// if(this.alias) s += ' AS '+this.alias; +// return s; +// } + +yy.Column = function(params) { return yy.extend(this, params); } +yy.Column.prototype.toString = function() { + var s; + if(this.columnid == +this.columnid) { + 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) s += ' AS '+this.alias; + return s; +}; + +yy.Column.prototype.toJavaScript = function(context, tableid, defcols) { +// var s = this.value; +// var s = this.columnid; +// if(this.tableid) { +// s = this.tableid+'.'+s; +// // if(this.databaseid) { +// // s = this.databaseid+'.'+s; +// // } +// } else { +// s = tableid+'.'+s; +// } +//console.log('yy.Column',this, tableid); +// console.log(392,this.columnid); + 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 != '_') { + 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 != '_') { + s = context+'[\''+(this.tableid || tableid) + '\'][\''+this.columnid+'\']'; + } else { + s = context+'[\''+(this.tableid || tableid) + '\']'; + }; + } + } else if(tableid == -1) { +// if(this.columnid != '') { + s = context+'[\''+this.columnid+'\']'; +// } else { +// s = context; +// } + } else { + if(this.columnid != '_') { + s = context+'[\''+(this.tableid || tableid) + '\'][\''+this.columnid+'\']'; + } else { + s = context+'[\''+(this.tableid || tableid) + '\']'; + } + } + } +// console.log(context,s); +// console.trace(new Error()); + return s; +} + + + + +yy.AggrValue = function(params){ return yy.extend(this, params); } +yy.AggrValue.prototype.toString = function() { + var s = ''; + if(this.aggregatorid == 'REDUCE') s += L(this.funcid)+'('; + else s += this.aggregatorid+'('; + if(this.distinct) s+= K('DISTINCT')+' '; + if(this.expression) s += this.expression.toString(); + s += ')'; + if(this.over) s += ' '+this.over.toString(); +// console.log(this.over); +// if(this.alias) s += ' AS '+this.alias; + return s; +}; +yy.AggrValue.prototype.findAggregator = function (query){ +// console.log('aggregator found',this.toString()); + +// var colas = this.as || this.toString(); + + var colas = escapeq(this.toString())+':'+query.selectGroup.length; +// console.log('findAgg',this); + + +/* var found = false; + for(var i=0;i-1) return 'number'; + if(['ARRAY'].indexOf(this.aggregatorid)>-1) return 'array'; + if(['FIRST','LAST' ].indexOf(this.aggregatorid)>-1) return this.expression.toType(); +} +yy.AggrValue.prototype.toJavaScript = function(context, tableid, defcols) { +// var s = 'alasql.functions.'+this.funcid+'('; +// if(this.expression) s += this.expression.toJavaScript(context, tableid); +// s += ')'; +// if(this.alias) s += ' AS '+this.alias; +// return s; +// var s = ''; +//if(this.as) console.log(499,this.as); +// var colas = this.as; + var colas = this.nick; + if(typeof colas == 'undefined') colas = this.toString(); + return 'g[\''+colas+'\']'; +} + + +yy.OrderExpression = function(params){ return yy.extend(this, params); } +yy.OrderExpression.prototype.toString = function() { + var s = this.expression.toString(); + if(this.order) s += ' '+this.order.toString(); + if(this.nocase) s += ' '+K('COLLATE')+' '+K('NOCASE'); + return s; +} + +yy.GroupExpression = function(params){ return yy.extend(this, params); } +yy.GroupExpression.prototype.toString = function() { + return this.type+'('+this.group.toString()+')'; +} + + +yy.ColumnDef = function (params) { return yy.extend(this, params); } +yy.ColumnDef.prototype.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; +} + + +// Alasql Linq library + +yy.FromData = function(params) { return yy.extend(this, params); }; +yy.FromData.prototype.toString = function() { + if(this.data) return K('DATA')+'('+((Math.random()*10e15)|0)+')'; + else return '?'; +}; +yy.FromData.prototype.toJavaScript = function(){ +// console.log('yy.FromData.prototype.toJavaScript'); +}; + +yy.Select.prototype.exec = function(params,cb) { + + if(this.preparams) params = this.preparams.concat(params); +// console.log(15,this.preparams); + + var databaseid = alasql.useid; + db = alasql.databases[databaseid]; + var sql = this.toString(); + var hh = hash(sql); +// console.log(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; +}; + +yy.Select.prototype.Select = function(){ + var self = this; + var agrs = []; + if(arguments.length > 1) { + args = Array.prototype.slice.call(arguments);; + } else if(arguments.length == 1) { + if(arguments[0] instanceof Array) { + 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 + } + }); + +// console.log(self instanceof yy.Select); + return self; +}; + +yy.Select.prototype.From = function(tableid){ + var self = this; + if(!self.from) self.from = []; + if(tableid instanceof Array) { + 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; +} + +yy.Select.prototype.OrderBy = function(){ + var self = this; + var agrs = []; + + self.order = []; + + if(arguments.length == 0) { +// self.order.push(new yy.OrderExpression({expression: new yy.Column({columnid:"_"}), direction:'ASC'})); + args = ["_"]; + } else if(arguments.length > 1) { + args = Array.prototype.slice.call(arguments);; + } else if(arguments.length == 1) { + if(arguments[0] instanceof Array) { + 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; +} + +yy.Select.prototype.Top = function(topnum){ + var self = this; + self.top = new yy.NumValue({value:topnum}); + return self; +}; + +yy.Select.prototype.GroupBy = function(){ + var self = this; + var agrs = []; + + if(arguments.length > 1) { + args = Array.prototype.slice.call(arguments);; + } else if(arguments.length == 1) { + if(arguments[0] instanceof Array) { + 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; +}; + +yy.Select.prototype.Where = function(expr){ + var self = this; + if(typeof expr == 'function' ) { + self.where = expr; + } + return self; +}; + + + +/* +// +// Functions for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +yy.FuncValue = function(params){ return yy.extend(this, params); } +yy.FuncValue.prototype.toString = function() { + 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) s += ' AS '+this.as.toString(); +// if(this.alias) s += ' AS '+this.alias; + return s; +} + +yy.FuncValue.prototype.findAggregator = function(query) { + if(this.args && this.args.length > 0) { + this.args.forEach(function(arg){ + if(arg.findAggregator) arg.findAggregator(query); + }); + } +}; + +yy.FuncValue.prototype.toJavaScript = function(context, tableid, defcols) { + var s = ''; + var funcid = this.funcid; + // IF this is standard compile functions + if(alasql.fn[funcid]) { + // This is user-defined run-time function + // TODO arguments!!! +// var s = ''; + if(this.newid) s+= 'new '; + s += 'alasql.fn.'+this.funcid+'('; +// if(this.args) s += this.args.toJavaScript(context, tableid); + if(this.args && this.args.length > 0) { + s += this.args.map(function(arg){ + return arg.toJavaScript(context, tableid, defcols); + }).join(','); + }; + s += ')'; + } else if(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.toJavaScript(context, tableid)})); + } else { + s += alasql.stdlib[funcid.toUpperCase()](); + } + } else if(alasql.stdfn[funcid.toUpperCase()]) { + if(this.newid) s+= 'new '; + s += 'alasql.stdfn.'+this.funcid.toUpperCase()+'('; +// if(this.args) s += this.args.toJavaScript(context, tableid); + if(this.args && this.args.length > 0) { + s += this.args.map(function(arg){ + return arg.toJavaScript(context, tableid, defcols); + }).join(','); + }; + s += ')'; + } else { + // Aggregator + } +//console.log('userfn:',s,this); + +// if(this.alias) s += ' AS '+this.alias; + return s; +} + +// // Functions compiler +// nodes.FunctionValue.prototype.toJavaScript = function (context, tableid) { +// var s = ''; +// s += fns[this.name.toUpperCase()].apply(null,this.arguments.map(function(arg){ +// if(arg) return arg.toJavaScript(context, tableid); +// else return ''; +// })); +// return s; +// }; + +// +// SQL FUNCTIONS COMPILERS +// Based on SQLite functions + +// IMPORTANT: These are compiled functions + +//alasql.fn = {}; // Keep for compatibility +//alasql.userlib = alasql.fn; + +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+')'}; +stdlib.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'); + }; +}; +stdlib.IFNULL = function(a,b) {return '('+a+'||'+b+')'}; +stdlib.INSTR = function(s,p) {return '(('+s+').indexOf('+p+')+1)'}; + +stdlib.LEN = stdlib.LENGTH = function(s) {return '('+s+'+"").length';}; +//stdlib.LENGTH = function(s) {return '('+s+').length'}; + +stdlib.LOWER = stdlib.LCASE = function(s) {return '('+s+').toLowerCase()';} +//stdlib.LCASE = function(s) {return '('+s+').toLowerCase()';} + + +// LTRIM + +stdlib.GREATEST = function(){ + return 'Math.max('+Array.prototype.join.call(arguments, ',')+')' +}; + +stdlib.LEAST = function(){ + return 'Math.min('+Array.prototype.join.call(arguments, ',')+')' +}; + +stdlib.MID = function(a,b,c){ + if(arguments.length == 2) return '('+a+').substr('+b+'-1)'; + else if(arguments.length == 3) return '('+a+').substr('+b+'-1,'+c+')'; +}; + +stdlib.NULLIF = function(a,b){return '('+a+'=='+b+'?null:'+a+')'}; + +stdlib.POWER = function(a,b) {return 'Math.pow('+a+','+b+')'}; + +stdlib.RANDOM = function(r) { + if(arguments.length == 0) { + return 'Math.random()'; + } else { + return '(Math.random()*('+r+')|0)'; + } +} +stdlib.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+')'; + } +} +stdlib.SQRT = function(s) {return 'Math.sqrt('+s+')'}; + +stdlib.TRIM = function(s) {return s+'.trim()'}; + +stdlib.UPPER = stdlib.UCASE = function(s) {return '('+s+').toUpperCase()';} +//stdlib.UCASE = function(s) {return '('+s+').toUpperCase()';} +//REPLACE +// RTRIM +// SUBSTR +// TRIM +//REPLACE +// RTRIM +// SUBSTR +// TRIM + + +// Aggregator for joining strings +alasql.aggr.GROUP_CONCAT = function(v,s){ + if(typeof s == "undefined") return v; else return s+','+v; +}; + + + + +// +// +// SQL and JS DateTime functions +// +// + + + +/* +// +// CASE for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +yy.CaseValue = function(params) { return yy.extend(this, params); }; +yy.CaseValue.prototype.toString = function() { + var s = 'CASE '; + if(this.expression) s += this.expression.toString(); + if(this.whens) { + s += this.whens.map(function(w) { return ' WHEN '+ + w.when.toString() + ' THEN '+w.then.toString()}).join(); + } + s += ' END'; + return s; +}; + +yy.CaseValue.prototype.findAggregator = function (query){ +// console.log(this.toString()); + if(this.expression && this.expression.findAggregator) this.expression.findAggregator(query); + if(this.whens && this.whens.length > 0) { + this.whens.forEach(function(w) { + if(w.when.findAggregator) w.when.findAggregator(query); + if(w.then.findAggregator) w.then.findAggregator(query); + }); + } +}; + +yy.CaseValue.prototype.toJavaScript = function(context, tableid, defcols) { + + var s = '(function('+context+',params,alasql){var r;'; + if(this.expression) { +// this.expression.toJavaScript(context, tableid) + s += 'v='+this.expression.toJavaScript(context, tableid, defcols)+';'; + s += (this.whens||[]).map(function(w) { return ' if(v=='+w.when.toJavaScript(context,tableid, defcols) + +') {r='+w.then.toJavaScript(context,tableid, defcols)+'}'; }).join(' else '); + if(this.elses) s += ' else {r='+this.elses.toJavaScript(context,tableid, defcols)+'}'; + } else { + s += (this.whens||[]).map(function(w) { return ' if('+w.when.toJavaScript(context,tableid, defcols) + +') {r='+w.then.toJavaScript(context,tableid, defcols)+'}'; }).join(' else '); + if(this.elses) s += ' else {r='+this.elses.toJavaScript(context,tableid,defcols)+'}'; + } + s += 'return r;})('+context+',params,alasql)'; + + return s; +}; + +/* +// +// JSON for Alasql.js +// Date: 19.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +yy.Json = function (params) { return yy.extend(this, params); } +yy.Json.prototype.toString = function() { + var s = '@'; + s += JSONtoString(this.value); + s += ''; + return s; +}; + +var JSONtoString = alasql.utils.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(obj instanceof Array) { + s += '['+obj.map(function(b){ + return JSONtoString(b); + }).join(',')+']'; + } else if(!obj.toJavaScript || 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; +} + + + +function JSONtoJavaScript(obj, context, tableid, defcols) { + 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(obj instanceof Array) { + s += '['+obj.map(function(b){ + return JSONtoJavaScript(b, context, tableid, defcols); + }).join(',')+']'; + } else if(!obj.toJavaScript || 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 += ':'+JSONtoJavaScript(obj[k], context, tableid, defcols); + ss.push(s1); + }; + s += ss.join(',')+'}'; + } else if(obj.toJavaScript) { + s = obj.toJavaScript(context, tableid, defcols); + } else { + throw new Error('1Can not parse JSON object '+JSON.stringify(obj)); + } + } else { + throw new Error('2Can not parse JSON object '+JSON.stringify(obj)); + } + + return s; +} + +yy.Json.prototype.toJavaScript = function(context, tableid, defcols) { + // TODO reod + return JSONtoJavaScript(this.value,context, tableid, defcols); +} + + + + +/* +// +// CAST and CONVERT functions +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +yy.Convert = function(params) { return yy.extend(this, params); }; +yy.Convert.prototype.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; +}; +yy.Convert.prototype.toJavaScript = function(context, tableid, defcols) { + +// if(this.style) { + return 'alasql.stdfn.CONVERT('+this.expression.toJavaScript(context, tableid, defcols) + +',{dbtypeid:"'+this.dbtypeid+'",dbsize:'+this.dbsize+',style:'+ + this.style+'})'; +// } +/* + if(this.dbtypeid == 'INT') { + return '(('+this.expression.toJavaScript(context, tableid, defcols)+')|0)'; + } if(this.dbtypeid == 'STRING') { + return '(""+'+this.expression.toJavaScript(context, tableid, defcols)+')'; + } if(this.dbtypeid == 'NUMBER') { + return '(+('+this.expression.toJavaScript(context, tableid, defcols)+'))'; + } if(this.dbtypeid == 'DATE') { + if(alasql.options.datetimeformat == 'javascript') { + return '(new Date('+this.expression.toJavaScript(context, tableid, defcols)+'))'; + } else if(alasql.options.datetimeformat == 'sql') { + return this.expression.toJavaScript(context, tableid, defcols); + } + } if(this.dbtypeid == 'DATETIME') { + if(alasql.options.datetimeformat == 'javascript') { + return '(new Date('+this.expression.toJavaScript(context, tableid, defcols)+'))'; + } else if(alasql.options.datetimeformat == 'sql') { + return this.expression.toJavaScript(context, tableid, defcols); + } + } else { + + }; +*/ + throw new Error('There is not such type conversion for '+this.toString()); +}; + +/** + Convert one type to another + */ +alasql.stdfn.CONVERT = function(value, args) { + var val = value; +// console.log(args); + 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); + + if(args.style == 1) { // mm/dd/yy + val = ("0"+(t.getMonth()+1)).substr(-2)+'/'+("0"+t.getDate()).substr(-2)+'/'+("0"+t.getYear()).substr(-2); + } else if(args.style == 2) { // yy.mm.dd + val = ("0"+t.getYear()).substr(-2)+'.'+("0"+(t.getMonth()+1)).substr(-2)+'.'+("0"+t.getDate()).substr(-2); + } else if(args.style == 3) { // dd/mm/yy + val = ("0"+t.getDate()).substr(-2)+'/'+("0"+(t.getMonth()+1)).substr(-2)+'/'+("0"+t.getYear()).substr(-2); + } else if(args.style == 4) { // dd.mm.yy + val = ("0"+t.getDate()).substr(-2)+'.'+("0"+(t.getMonth()+1)).substr(-2)+'.'+("0"+t.getYear()).substr(-2); + } else if(args.style == 5) { // dd-mm-yy + val = ("0"+t.getDate()).substr(-2)+'-'+("0"+(t.getMonth()+1)).substr(-2)+'-'+("0"+t.getYear()).substr(-2); + } else if(args.style == 6) { // dd mon yy + val = ("0"+t.getDate()).substr(-2)+' '+t.toString().substr(4,3).toLowerCase()+' '+("0"+t.getYear()).substr(-2); + } else if(args.style == 7) { // Mon dd,yy + val = t.toString().substr(4,3)+' '+("0"+t.getDate()).substr(-2)+','+("0"+t.getYear()).substr(-2); + } else if(args.style == 8) { // hh:mm:ss + val = ("0"+t.getHours()).substr(-2)+':'+("0"+(t.getMinutes()+1)).substr(-2)+':'+("0"+t.getSeconds()).substr(-2); + + } else if(args.style == 10) { // mm-dd-yy + val = ("0"+(t.getMonth()+1)).substr(-2)+'-'+("0"+t.getDate()).substr(-2)+'-'+("0"+t.getYear()).substr(-2); + } else if(args.style == 11) { // yy/mm/dd + val = ("0"+t.getYear()).substr(-2)+'/'+("0"+(t.getMonth()+1)).substr(-2)+'/'+("0"+t.getDate()).substr(-2); + } else if(args.style == 12) { // yymmdd + val = ("0"+t.getYear()).substr(-2)+("0"+(t.getMonth()+1)).substr(-2)+("0"+t.getDate()).substr(-2); + + + } else if(args.style == 101) { // mm/dd/yy + val = ("0"+(t.getMonth()+1)).substr(-2)+'/'+("0"+t.getDate()).substr(-2)+'/'+t.getFullYear(); + } else if(args.style == 102) { // yy.mm.dd + val = t.getFullYear()+'.'+("0"+(t.getMonth()+1)).substr(-2)+'.'+("0"+t.getDate()).substr(-2); + } else if(args.style == 103) { // dd/mm/yy + val = ("0"+t.getDate()).substr(-2)+'/'+("0"+(t.getMonth()+1)).substr(-2)+'/'+t.getFullYear(); + } else if(args.style == 104) { // dd.mm.yy + val = ("0"+t.getDate()).substr(-2)+'.'+("0"+(t.getMonth()+1)).substr(-2)+'.'+t.getFullYear(); + } else if(args.style == 105) { // dd-mm-yy + val = ("0"+t.getDate()).substr(-2)+'-'+("0"+(t.getMonth()+1)).substr(-2)+'-'+t.getFullYear(); + } else if(args.style == 106) { // dd mon yy + val = ("0"+t.getDate()).substr(-2)+' '+t.toString().substr(4,3).toLowerCase()+' '+t.getFullYear(); + } else if(args.style == 107) { // Mon dd,yy + val = t.toString().substr(4,3)+' '+("0"+t.getDate()).substr(-2)+','+t.getFullYear(); + } else if(args.style == 108) { // hh:mm:ss + val = ("0"+t.getHours()).substr(-2)+':'+("0"+(t.getMinutes()+1)).substr(-2)+':'+("0"+t.getSeconds()).substr(-2); + + } else if(args.style == 110) { // mm-dd-yy + val = ("0"+(t.getMonth()+1)).substr(-2)+'-'+("0"+t.getDate()).substr(-2)+'-'+t.getFullYear(); + } else if(args.style == 111) { // yy/mm/dd + val = t.getFullYear()+'/'+("0"+(t.getMonth()+1)).substr(-2)+'/'+("0"+t.getDate()).substr(-2); + } else if(args.style == 112) { // yymmdd + val = t.getFullYear()+("0"+(t.getMonth()+1)).substr(-2)+("0"+t.getDate()).substr(-2); + } else { + throw new Error('The CONVERT style '+args.style+' is not realized yet.'); + } + }; + + if(args.dbtypeid == 'Date') { + return new Date(val); + } else if(args.dbtypeid.toUpperCase() == '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(args.dbtypeid == 'DATETIME') { + 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()).substr(-3) + return s; + } else if(args.dbtypeid.toUpperCase() == 'STRING') { + return ""+val; + } else if(args.dbtypeid.toUpperCase() == 'NUMBER' || args.dbtypeid == 'FLOAT') { + return +val; + } else if(args.dbtypeid.toUpperCase() == 'MONEY') { + var m = +val; + return (m|0)+((m*100)%100)/100; + } else if(args.dbtypeid.toUpperCase() == 'BOOLEAN') { + return !!val; + } else if(args.dbtypeid.toUpperCase() == 'INT') { + return val|0; + } else if(args.dbtypeid.toUpperCase() == 'VARCHAR' || args.dbtypeid == 'NVARCHAR') { + if(args.dbsize) return (""+val).substr(0,args.dbsize); + else return ""+val; + } else if(args.dbtypeid.toUpperCase() == 'CHAR' || args.dbtypeid == 'NCHAR') { + return (val+(new Array(args.dbsize+1).join(" "))).substr(0,args.dbsize); + //else return ""+val.substr(0,1); + } +}; + + + +/* +// +// CREATE TABLE for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +yy.ColumnDef = function (params) { return yy.extend(this, params); } +yy.ColumnDef.prototype.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; +} + +yy.CreateTable = function (params) { return yy.extend(this, params); } +yy.CreateTable.prototype.toString = function() { + var s = K('CREATE'); + if(this.temporary) s+=' '+K('TEMPORARY'); + if(this.view) s += ' '+K('VIEW'); + else s += ' '+K('TABLE'); + if(this.ifnotexists) s += ' '+K('IF')+' '+K('NOT')+' '+K('EXISTS'); + s += ' '+this.table.toString(); + if(this.viewcolumns) { + s += '('+this.viewcolumns.map(function(vcol){ + return vcol.toString(); + }).join(',')+')'; + } + if(this.as) s += ' '+K('AS')+' '+L(this.as); + else { + var ss = this.columns.map(function(col){ + return col.toString(); + }); + s += ' ('+NL()+ID()+ss.join(','+NL()+ID())+')'; + }; + if(this.view && this.select) { + s += ' AS '+this.select.toString(); + } + return s; +} + +// CREATE TABLE +//yy.CreateTable.prototype.compile = returnUndefined; +yy.CreateTable.prototype.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||[]; +// console.log(this); + + // IF NOT EXISTS + if(this.ifnotexists && db.tables[tableid]) return 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? + + var ss = []; + if(this.columns) { + this.columns.forEach(function(col) { + var dbtypeid = col.dbtypeid; + if(!alasql.fn[dbtypeid]) dbtypeid = dbtypeid.toUpperCase(); + var newcol = { + columnid: col.columnid, + dbtypeid: dbtypeid // TODO: Add types table + }; + + if(col.default) { + ss.push('\''+col.columnid+'\':'+col.default.toJavaScript()); + } + + table.columns.push(newcol); + table.xcolumns[newcol.columnid] = newcol; + + // 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",'return '+pk.onrightfns); + pk.hh = hash(pk.onrightfns); + table.indices[pk.hh] = {}; + }; + + }); + }; + table.defaultfns = ss.join(','); + + +// if(constraints) { + constraints.forEach(function(con) { + //console.log(con, con.columns); + 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",'return '+pk.onrightfns); + pk.hh = hash(pk.onrightfns); + table.indices[pk.hh] = {}; + } + }); + + if(this.view && this.viewcolumns) { + var self = this; + this.viewcolumns.forEach(function(vcol,idx){ + self.select.columns[idx].as = vcol.columnid; + }); + } + +// console.log(100,db.engineid); + if(db.engineid) { +// console.log(101,db.engineid); + return alasql.engines[db.engineid].createTable(this.table.databaseid || databaseid, tableid, this.ifnotexists, cb); +// console.log('createtable',res1); +// return res1; + } + +// } +// if(table.pk) { + table.insert = function(r) { + if(this.pk) { + var pk = this.pk; + var addr = pk.onrightfn(r); + if(typeof this.indices[pk.hh][addr] != 'undefined') { + throw new Error('Cannot insert record, because it already exists in primary key'); + } else { + table.data.push(r); + this.indices[pk.hh][addr]=r; + }; + } else { + table.data.push(r); + } + }; + + table.delete = function(i) { + if(this.pk) { + var r = this.data[i]; + var pk = this.pk; + var addr = pk.onrightfn(r); + if(typeof this.indices[pk.hh][addr] == 'undefined') { + throw new Error('Something wrong with index on table'); + } else { + this.indices[pk.hh][addr]=undefined; + }; + } + }; + + table.deleteall = function() { + this.data.length = 0; + if(this.pk) { +// var r = this.data[i]; + this.indices[this.pk.hh] = {}; + } + }; + + table.update = function(assignfn, i, params) { + if(this.pk) { + var r = this.data[i]; + var pk = this.pk; + var addr = pk.onrightfn(r,params); + if(typeof this.indices[pk.hh][addr] == 'undefined') { + throw new Error('Something wrong with index on table'); + } else { + this.indices[pk.hh][addr]=undefined; + assignfn(r,params,alasql); + var newaddr = pk.onrightfn(r); + if(typeof this.indices[pk.hh][newaddr] != 'undefined') { + throw new Error('Record already exists'); + } else { + this.indices[pk.hh][newaddr] = r; + } + } + + } else { + assignfn(this.data[i],params,alasql); + }; + + }; + + if(this.view && this.select) { + table.view = true; +// console.log(this.select.toString()); +// console.log('this.table.databaseid',this.table.databaseid); +// console.log(this.select.compile(this.table.databaseid||databaseid)); + table.select = this.select.compile(this.table.databaseid||databaseid); + } +// console.log(databaseid); +// console.log(db.databaseid,db.tables); +// console.log(table); + if(cb) cb(1); + + return 1; +}; + + + + +// +// Date functions +// +// (c) 2014, Andrey Gershun +// + +/** Standard JavaScript data types */ + +alasql.fn.Date = Object; +alasql.fn.Date = Date; +alasql.fn.Number = Number; +alasql.fn.String = String; +alasql.fn.Boolean = Boolean; + +/** Extend Object with properties */ +stdfn.EXTEND = alasql.utils.extend; + + +stdfn.CHAR = String.fromCharCode.bind(String); +stdfn.ASCII = function(a) { + return a.charCodeAt(0); +}; + +/** + Return first non-null argument + See https://msdn.microsoft.com/en-us/library/ms190349.aspx +*/ +stdfn.COALESCE = function() { + for(var i=0;i 0) { + for(var i=0, ilen=table.data.length; i 0) { + for(var i=0, ilen=table.data.length; i=0) { + q += "+"+values[idx].toJavaScript(); + } else if (alasql.fn[table.xcolumns[col.columnid].dbtypeid]) { + q += "(new "+table.xcolumns[col.columnid].dbtypeid+"("; + q += values[idx].toJavaScript(); + q += "))"; + } else { + q += values[idx].toJavaScript(); + }; + } else { + q += values[idx].toJavaScript(); + } + ss.push(q); + + }); + } else { +// var table = db.tables[tableid]; +// console.log('table1', db, self); +//console.log(111, table.columns); +//console.log(74,table); + if((values instanceof Array) && table.columns && table.columns.length > 0) { + table.columns.forEach(function(col, idx){ + + var q = '\''+col.columnid +'\':'; +// var val = values[idx].toJavaScript(); + + if(["INT","FLOAT","NUMBER","MONEY"].indexOf(col.dbtypeid) >=0) { + q += "+"+values[idx].toJavaScript(); + } else if (alasql.fn[col.dbtypeid]) { + q += "(new "+col.dbtypeid+"("; + q += values[idx].toJavaScript(); + q += "))"; + } else { + q += values[idx].toJavaScript(); + } + + // if(table.xcolumns && table.xcolumns[col.columnid] && + // (table.xcolumns[col.columnid].dbtypeid == "DATE" || + // table.xcolumns[col.columnid].dbtypeid == "DATETIME" + // )) { + // val = "(new Date("+val+"))"; + // } + // || table.xcolumns[col.columnid].dbtypeid == "FLOAT" + // || table.xcolumns[col.columnid].dbtypeid == "NUMBER" + // || table.xcolumns[col.columnid].dbtypeid == "MONEY" + // )) q += '+'; + // console.log(self.values[idx].toString()); + //console.log(self); +// q += val; + + // if(table.xcolumns && table.xcolumns[col.columnid] && table.xcolumns[col.columnid].dbtypeid == "INT") q += '|0'; + ss.push(q); + + // console.log(fld); + // TODO: type checking and conversions + // rec[fld.fldid] = eval(self.insertExpression[idx].toJavaScript('','')); + // console.log(rec[fld.fldid]); + // if(rec[fld.fldid] == "NULL") rec[fld.fldid] = undefined; + + // if(table.xflds[fld.fldid].dbtypeid == "INT") rec[fld.fldid] = +rec[fld.fldid]|0; + // else if(table.xflds[fld.fldid].dbtypeid == "FLOAT" || table.xflds[fld.fldid].dbtypeid == "MONEY" ) + // rec[fld.fldid] = +rec[fld.fldid]; + }); + } else { +// console.log(222,values); +// sw = 'var w='+JSONtoJavaScript(values)+';for(var k in w){r[k]=w[k]};'; + sw = JSONtoJavaScript(values); + } + } +//console.log(ss); + + if(db.tables[tableid].defaultfns) ss.unshift(db.tables[tableid].defaultfns); + if(sw) { + s += 'a='+sw+';'; + } else { + s += 'a={'+ss.join(',')+'};'; + } +// s += 'db.tables[\''+tableid+'\'].insert(r);'; + if(db.tables[tableid].insert) { + s += 'alasql.databases[\''+databaseid+'\'].tables[\''+tableid+'\'].insert(a);'; + } else { + s += 'aa.push(a);'; + } + }); + + s33 = s3+s; + + if(db.tables[tableid].insert) { +// s += 'alasql.databases[\''+databaseid+'\'].tables[\''+tableid+'\'].insert(r);'; + } else { + s += 'alasql.databases[\''+databaseid+'\'].tables[\''+tableid+'\'].data='+ + 'alasql.databases[\''+databaseid+'\'].tables[\''+tableid+'\'].data.concat(aa);'; + } + + s += 'return '+self.values.length; + +//console.log(s); + var insertfn = new Function('db, params, alasql',s3+s); + +// INSERT INTO table SELECT + + } else if(this.select) { + 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,null, cb); + return res; + }; + return statement; + } else { + var insertfn = function(db, params, alasql) { + var res = selectfn(params); + if(db.tables[tableid].insert) { + // If insert() function exists (issue #92) + for(var i=0,ilen=res.length;i 0) { + s += '('+this.args.map(function(arg){ return arg.toString()}).join(', ')+')'; + } + if(this.as) s += ' '+K('AS')+' '+L(this.as); + return s; +} +//yy.CreateDatabase.prototype.compile = returnUndefined; +yy.CreateDatabase.prototype.execute = function (databaseid, params, cb) { + // console.log(alasql.useid, databaseid, this.databaseid); + // console.trace(); + var args; + if(this.args && this.args.length > 0) { + args = this.args.map(function(arg){ + return new Function('params','return '+arg.toJavaScript())(params); + }); + }; + 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; + } +}; + +// CREATE DATABASE databaseid +yy.AttachDatabase = function (params) { return yy.extend(this, params); }; +yy.AttachDatabase.prototype.toString = function() { + var s = K('ATTACH'); + if(this.engineid) s += ' '+L(this.engineid); + s += ' '+K('DATABASE')+' '+L(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+= ' '+K('AS')+' '+L(this.as); + return s; +} +//yy.CreateDatabase.prototype.compile = returnUndefined; +yy.AttachDatabase.prototype.execute = function (databaseid, params, cb) { + // console.log(alasql.useid, databaseid, this.databaseid); + // console.trace(); + 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 = K('DETACH'); + s += ' '+K('DATABASE')+' '+L(this.databaseid); + return s; +} +//yy.CreateDatabase.prototype.compile = returnUndefined; +yy.DetachDatabase.prototype.execute = function (databaseid, params, cb) { + // console.log(alasql.useid, databaseid, this.databaseid); + // console.trace(); + 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"); + } +// console.log(dbid); + 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; +}; + +// USE DATABSE databaseid +// USE databaseid +yy.UseDatabase = function (params) { return yy.extend(this, params); }; +yy.UseDatabase.prototype.toString = function() { + return K('USE') +' '+K('DATABASE')+' '+L(this.databaseid); +} +//yy.UseDatabase.prototype.compile = returnUndefined; +yy.UseDatabase.prototype.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; +}; + +// DROP DATABASE databaseid +yy.DropDatabase = function (params) { return yy.extend(this, params); } +yy.DropDatabase.prototype.toString = function() { + var s = K('DROP'); + if(this.ifexists) s += ' '+K('IF')+' '+K('EXISTS'); + s += ' '+K('DATABASE')+' '+L(this.databaseid); + return s; +} +//yy.DropDatabase.prototype.compile = returnUndefined; +yy.DropDatabase.prototype.execute = function (databaseid, params, cb) { + if(this.engineid) { + +// console.log(this,this.databaseid, this.ifexists); + 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"); + } +// console.log(dbid); + 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; +}; + + + + + + + +/* +// +// SET for Alasql.js +// Date: 01.12.2014 +// (c) 2014, Andrey Gershun +// +*/ + +yy.Declare = function (params) { return yy.extend(this, params); } +yy.Declare.prototype.toString = function() { + var s = K('DECLARE')+' '; + if(this.declares && this.declares.length > 0) { + s = this.declares.map(function(declare){ + var s = ''; + s += '@'+L(declare.variable)+' '; + s += declare.dbtypeid; + if(this.dbsize) s += '('+N(this.dbsize); + if(this.dbprecision) s+= ','+N(this.dbprecision); + s += ')'; + if(declare.expression) s += ' = '+declare.expression.toString(); + return s; + }).join(','); + } + return s; +} + +yy.Declare.prototype.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) { + // console.log(this.expression.toJavaScript('','', null)); + alasql.vars[declare.variable] = new Function("params,alasql","return " + +declare.expression.toJavaScript('','', 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; +}; + + + +/* +// +// SHOW for Alasql.js +// Date: 19.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +yy.ShowDatabases = function (params) { return yy.extend(this, params); } +yy.ShowDatabases.prototype.toString = function() { + var s = K('SHOW')+' '+K('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) { + res = res.filter(function(d){ + return d.databaseid.match(new RegExp((self.like.value).replace(/\%/g,'.*'),'g')); + }); + } + if(cb) cb(res); + return res; + }; + +}; + + +yy.ShowTables = function (params) { return yy.extend(this, params); } +yy.ShowTables.prototype.toString = function() { + var s = K('SHOW')+' '+K('TABLES'); + if(this.databaseid) s += ' FROM '+this.databaseid; + if(this.like) s += ' '+K('LIKE')+' '+this.like.toString(); + return s; +} +yy.ShowTables.prototype.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,'.*'),'g')); + }); + }; + if(cb) cb(res); + return res; +}; + +yy.ShowColumns = function (params) { return yy.extend(this, params); } +yy.ShowColumns.prototype.toString = function() { + var s = K('SHOW')+' '+K('COLUMNS'); + if(this.table.tableid) s += ' '+K('FROM')+' '+this.table.tableid; + if(this.databaseid) s += ' '+K('FROM')+' '+this.databaseid; + return s; +}; + +yy.ShowColumns.prototype.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 []; + } +}; + +yy.ShowIndex = function (params) { return yy.extend(this, params); } +yy.ShowIndex.prototype.toString = function() { + var s = K('SHOW')+' '+K('INDEX'); + if(this.table.tableid) s += ' '+K('FROM')+' '+this.table.tableid; + if(this.databaseid) s += ' '+K('FROM')+' '+this.databaseid; + return s; +} +yy.ShowIndex.prototype.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; +}; + +yy.ShowCreateTable = function (params) { return yy.extend(this, params); } +yy.ShowCreateTable.prototype.toString = function() { + var s = K('SHOW')+' '+K('CREATE')+' '+K('TABLE')+' '+L(this.table.tableid); + if(this.databaseid) s += ' '+K('FROM')+' '+L(this.databaseid); + return s; +} +yy.ShowCreateTable.prototype.execute = function (databaseid) { + var db = alasql.databases[this.databaseid || databaseid]; + var table = db.tables[this.table.tableid]; + var self = this; + if(table) { + var s = K('CREATE')+' '+K('TABLE')+' '+L(this.table.tableid)+' ('; + var ss = []; + if(table.columns) { + table.columns.forEach(function(col){ + var a = L(col.columnid)+' '+K(col.dbtypeid); + if(col.dbsize) a += '('+N(col.dbsize)+')'; + if(col.primarykey) a += ' '+K('PRIMARY')+' '+K('KEY'); + // TODO extend + ss.push(a); + }); + s += ss.join(', '); + }; + s += ')'; + return s; + } else { + throw new Error('There is no such table "'+this.table.tableid+'"'); + } +}; + + +/* +// +// SET for Alasql.js +// Date: 01.12.2014 +// (c) 2014, Andrey Gershun +// +*/ + +yy.SetVariable = function (params) { return yy.extend(this, params); } +yy.SetVariable.prototype.toString = function() { + var s = K('SET')+' '; + if(typeof this.value != 'undefined') s += K(this.variable.toUpperCase())+' '+(this.value?'ON':'OFF'); + if(this.expression) s += '@' + L(this.variable)+' = '+this.expression.toString(); + return s; +} + +yy.SetVariable.prototype.execute = function (databaseid,params,cb) { +// console.log(this); + 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) { +// console.log(this.expression.toJavaScript('','', null)); + var res = new Function("params,alasql","return " + +this.expression.toJavaScript('','', null))(params,alasql); + if(alasql.declares[this.variable]) { + res = alasql.stdfn.CONVERT(res,alasql.declares[this.variable]); + } + if(this.props && this.props.length > 0) { + var fs = 'alasql.vars[\''+this.variable+'\']'; + fs += this.props.map(function(prop){ + if(typeof prop == 'string') { + return '[\''+prop+'\']'; + } else if(typeof prop == 'number') { + return '['+prop+']'; + } else { + // console.log('prop:',prop, prop.toJavaScript()); + return '['+prop.toJavaScript()+']'; +// } else { +// console.log(prop, typeof ); +// throw new Error('Wrong SET property'); + } + }).join(); +// console.log(fs); + new Function("value,alasql",fs +'=value')(res,alasql); + } else { + alasql.vars[this.variable] = res; + } + } + var res = 1; + if(cb) res=cb(res); + return res; +}; + + + +// Console functions +/* +alasql.con = { + results:{} +}; + +alasql.con.open = function(el) { + // For browser only + if (typeof exports === 'object') return; + + // Find parent element + el = el || document.getElementById('alasql-con') || document.getElementsByTagName('body'); + if(!el) {throw new Error('Cannot fid element for console.')} + + var conel = document.createElement('div'); + conel.style.width = "1000px"; + conel.style.height = "320px"; + + alasql.con.conel = conel; + + var lenta = document.createElement('div'); + lenta.style.width = "1000px"; + lenta.style.height = "200px"; + lenta.style.overflow = "scroll"; + alasql.con.lenta = lenta; + + var inpel = document.createElement('div'); + inpel.style.width = "1000px"; + inpel.style.height = "100px"; + inpel.style.contentEditable = true; + inpel.innerHTML = 'command '; + alasql.con.inpel = inpel; + + conel.appendChild(lenta); + conel.appendChild(inpel); + el.appendChild(conel); +}; + +alasql.con.clear = function() { + // For browser only + if (typeof exports === 'object') return; + + alasql.con.conel.innerHTML = ''; +}; + +alasql.con.close = function() { + // For browser only + if (typeof exports === 'object') return; + + alasql.con.conel.removeChild(alasql.con.lenta); + alasql.con.conel.removeChild(alasql.con.inel); + alasql.con.conel.parentElement.removeChild(conel); +}; + +alasql.con.log = function() { + // For browser only + if (typeof exports === 'object') { + console.log.bind(console).apply(this, arguments); + } else { + var s = '
'; + s += Array.prototype.slice.call(arguments, 0).map(function(arg){ + return arg.toString(); + }).join(' '); + s += '
'; + alasql.con.conel.innerHTML += s; + }; + +}; +*/ +alasql.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',sql); + + if(res instanceof Array) { + if(console.table) { + // For Chrome and other consoles + console.table(res); + } else { + // Add print procedure + console.log(JSONtoString(res)); + } + } else { + console.log(JSONtoString(res)); + } -/* -// -// ROLLUP(), CUBE(), GROUPING SETS() for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -/** - Calculate ROLLUP() combination - */ - -var rollup = function (a,query) { - var rr = []; - var mask = 0; - var glen = a.length; - for(var g=0;g'+gv[t]+'<',gv[t]=='',typeof gv[t]); -// console.log(gv[t].toString()); -//console.log('+++'); - res = res.map(function(r){ - query.groupColumns[escapeq(gv[t].toString())] = escapeq(gv[t].toString()); - return r.concat(escapeq(gv[t].toString()) - +'\t' - +gv[t].toJavaScript('p',query.sources[0].alias,query.defcols)) - }); -// res = res.concat(gv[t]); - }; - - // switch(gv[t].t) { - // case 'plain': - // res = res.map(function(r){return r.concat(gv[t].p)}); - - // break; - // case 'rollup': res = cartes(res,rollup(gv[t].p)); break; - // case 'cube': res = cartes(res,cube(gv[t].p)); break; - // case 'groupingsets': res = cartes(res,groupingsets(gv[t].p)); break; - // default: res = res.concat(gv[t]); - // } - }; - return res; - } else if(gv instanceof yy.FuncValue) { -// console.log(gv); - query.groupColumns[escapeq(gv.toString())] = escapeq(gv.toString()); - return [gv.toString()+'\t'+gv.toJavaScript('p',query.sources[0].alias,query.defcols)]; - } else if(gv instanceof yy.Column) { - gv.nick = escapeq(gv.columnid); - query.groupColumns[gv.nick] = gv.nick; - return [gv.nick+'\t'+gv.toJavaScript('p',query.sources[0].alias,query.defcols)]; // Is this ever happened? - // } else if(gv instanceof yy.Expression) { - // return [gv.columnid]; // Is this ever happened? - } else { - query.groupColumns[escapeq(gv.toString())] = escapeq(gv.toString()); - return [escapeq(gv.toString())+'\t'+gv.toJavaScript('p',query.sources[0].alias,query.defcols)]; -// throw new Error('Single argument in the group without array'); - }; - - - // switch(gv.t) { - // case 'plain': return gv.p; break; - // case 'rollup': return rollup(gv.p); break; - // case 'cube': return cube(gv.p); break; - // case 'groupingsets': return groupingsets(gv.p); break; - // default: return [gv];//return decartes(gv.p); - // } - // return gv; -}; - - - - -/* -// -// Select run-time part for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.Select.prototype.compileDefCols = function(query, databaseid) { -// console.log('defcols'); - var defcols = {}; - if(this.from) { - this.from.forEach(function(fr){ - if(fr instanceof yy.Table) { - var alias = fr.as || fr.tableid; -// console.log(alasql.databases[fr.databaseid || databaseid]); -// console.log(alasql.databases[fr.databaseid || databaseid].tables, fr.tableid); -//console.log(alasql.databases[fr.databaseid || databaseid].tables, fr.tableid); -//console.log(alasql.databases); - var table = alasql.databases[fr.databaseid || databaseid].tables[fr.tableid]; -//console.log(table); - 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.ParamValue) { - - } else if(fr instanceof yy.VarValue) { - - } else if(fr instanceof yy.FuncValue) { - - } else if(fr instanceof yy.FromData) { - - } else { - throw new Error('Unknown type of FROM clause'); - }; - }); - }; - - if(this.joins) { - this.joins.forEach(function(jn){ -// console.log(jn); - 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]; -// console.log(jn.table.tableid, jn.table.databaseid); - 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; - // } -// console.log(defcols); - return defcols; -} - -/* -// -// UNION for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -// SELECT UNION statement - -yy.Union = function (params) { return yy.extend(this, params); } -yy.Union.prototype.toString = function () { - return K('UNION'); -}; - -yy.Union.prototype.compile = function (tableid) { - return null; -}; - -/* -// -// CROSS AND OUTER APPLY for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.Apply = function (params) { return yy.extend(this, params); } -yy.Apply.prototype.toString = function () { - var s = K(this.applymode)+' '+K('APPLY')+' ('; - s += this.select.toString()+')'; - if(this.as) s += ' '+K('AS')+' '+L(this.as); - return s; -}; - - - -/* -// -// CROSS AND OUTER APPLY for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.Over = function (params) { return yy.extend(this, params); } -yy.Over.prototype.toString = function () { - var s = K('OVER')+' ('; - if(this.partition) { - s += K('PARTITION')+' '+K('BY')+' '+this.partition.toString(); - if(this.order) s+=' '; - } - if(this.order) { - s += K('ORDER')+' '+K('BY')+' '+this.order.toString(); - } - s += ')'; - return s; -}; - - - -/* -// -// Expressions for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.ExpressionStatement = function(params) { return yy.extend(this, params); }; -yy.ExpressionStatement.prototype.toString = function() { - return this.expression.toString(); -}; - -yy.ExpressionStatement.prototype.execute = function (databaseid, params, cb) { - if(this.expression) { -// console.log(this.expression.toJavaScript('','', null)); -// console.log(this.expression.toJavaScript('','', null)); - var expr = new Function("params,alasql,p",'return '+this.expression.toJavaScript('','', null)); - var res = expr(params,alasql); - if(cb) res = cb(res); - return res; - } -} - -yy.Expression = function(params) { return yy.extend(this, params); }; -yy.Expression.prototype.toString = function() { - var s = this.expression.toString(); - if(this.order) s += ' '+this.order.toString(); - if(this.nocase) s += ' '+K('COLLATE')+' '+K('NOCASE'); - return s; -}; -yy.Expression.prototype.findAggregator = function (query){ - if(this.expression.findAggregator) this.expression.findAggregator(query); -}; - -yy.Expression.prototype.toJavaScript = function(context, tableid, defcols) { -// console.log('Expression',this); - if(this.expression.reduced) return 'true'; - return this.expression.toJavaScript(context, tableid, defcols); -}; -yy.Expression.prototype.compile = function(context, tableid, defcols){ -// console.log('Expression',this); - if(this.reduced) return returnTrue(); - return new Function('p','return '+this.toJavaScript(context, tableid, defcols)); -}; - - -yy.JavaScript = function(params) { return yy.extend(this, params); }; -yy.JavaScript.prototype.toString = function() { - var s = '``'+this.value+'``'; - return s; -}; - -yy.JavaScript.prototype.toJavaScript = function(context, tableid, defcols) { -// console.log('Expression',this); - return '('+this.value+')'; -}; -yy.JavaScript.prototype.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; -} - - -yy.Literal = function (params) { return yy.extend(this, params); } -yy.Literal.prototype.toString = function() { - var s = this.value; - if(this.value1) s = this.value1+'.'+s; -// else s = tableid+'.'+s; - return L(s); -} - - -yy.Join = function (params) { return yy.extend(this, params); } -yy.Join.prototype.toString = function() { - var s = NL()+ID(); - if(this.joinmode) s += K(this.joinmode)+' '; - s += K('JOIN')+this.table.toString(); - return s; -} - -//yy.Join.prototype.toJavaScript = function(context, tableid) { -// return 'JOIN'+this.table.toString(); -//} - - -yy.Table = function (params) { return yy.extend(this, params); } -yy.Table.prototype.toString = function() { - var s = this.tableid; -// if(this.joinmode) - if(this.databaseid) s = this.databaseid+'.'+s; - return L(s); -}; - - -yy.View = function (params) { return yy.extend(this, params); } -yy.View.prototype.toString = function() { - var s = this.viewid; -// if(this.joinmode) - if(this.databaseid) s = this.databaseid+'.'+s; - return L(s); -}; - - -yy.Op = function (params) { return yy.extend(this, params); } -yy.Op.prototype.toString = function() { - if(this.op == 'IN' || this.op == 'NOT IN') { - return this.left.toString()+" "+P(this.op)+" ("+this.right.toString()+")"; - } - if(this.allsome) { - return this.left.toString()+" "+P(this.op)+" "+this.allsome+' ('+this.right.toString()+')'; - } - if(this.op == '->') { - var s = this.left.toString()+"->"; -// console.log(this.right); - 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()+" "+P(this.op)+" "+(this.allsome?this.allsome+' ':'')+this.right.toString(); -}; - -yy.Op.prototype.findAggregator = function (query){ -// console.log(this.toString()); - 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); - } -}; - -yy.Op.prototype.toType = function(tableid) { - if(['-','*','/','%','^'].indexOf(this.op) >-1) return 'number'; - 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'].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'; -}; - -yy.Op.prototype.toJavaScript = function(context,tableid,defcols) { -// console.log(this); - var op = this.op; - if(this.op == '=') op = '==='; - else if(this.op == '<>') op = '!='; - else if(this.op == 'OR') op = '||'; - - if(this.op == '->') { -// console.log(this.right, typeof this.right); - if(typeof this.right == "string") { - return this.left.toJavaScript(context,tableid, defcols)+'["'+this.right+'"]'; - } else if(typeof this.right == "number") { - return this.left.toJavaScript(context,tableid, defcols)+'['+this.right+']'; - } else if(this.right instanceof yy.FuncValue) { - ss = []; - if(!this.right.args || this.right.args.length == 0) { - } else { - var ss = this.right.args.map(function(arg){ - return arg.toJavaScript(context,tableid, defcols); - }); - } - return this.left.toJavaScript(context,tableid, defcols)+'[\''+this.right.funcid+'\']('+ - ss.join(',')+')'; - } else { - return this.left.toJavaScript(context,tableid, defcols)+'['+this.right.toJavaScript(context,tableid, defcols)+']'; - } - } - - if(this.op == 'IS') { - return '((typeof '+this.left.toJavaScript(context,tableid, defcols)+"=='undefined') == " - + '(typeof '+this.right.toJavaScript(context,tableid, defcols)+"=='undefined'))"; - } - - - if(this.op == '==') { - return 'alasql.utils.deepEqual('+this.left.toJavaScript(context,tableid, defcols)+","+this.right.toJavaScript(context,tableid, defcols)+')'; - } - if(this.op == '===') { - return "(("+this.left.toJavaScript(context,tableid, defcols)+").valueOf()===("+this.right.toJavaScript(context,tableid, defcols)+'.valueOf()))'; - } - - if(this.op == '!===') { - return "!(("+this.left.toJavaScript(context,tableid, defcols)+").valueOf()===("+this.right.toJavaScript(context,tableid, defcols)+'.valueOf()))'; - } - - - if(this.op == '!==') { - return '(!alasql.utils.deepEqual('+this.left.toJavaScript(context,tableid, defcols)+","+this.right.toJavaScript(context,tableid, defcols)+'))'; - } - - if(this.op == 'LIKE') { - var s = "("+this.left.toJavaScript(context,tableid, defcols)+"+'')"+ - ".toUpperCase().match(new RegExp('^'+("+this.right.toJavaScript(context,tableid, defcols)+").replace(/\\\%/g,'.*').toUpperCase()+'$','g'))" -// console.log(s); - return s; - }; - - if(this.op == 'NOT LIKE') { - var s = "!(("+this.left.toJavaScript(context,tableid, defcols)+"+'')"+ - ".toUpperCase().match(new RegExp('^'+("+this.right.toJavaScript(context,tableid, defcols)+").replace(/\\\%/g,'.*').toUpperCase()+'$','g')))" - return s; - }; - - if(this.op == 'BETWEEN') { - if(this.right instanceof yy.Op && this.right.op == 'AND') { - return '(('+this.right.left.toJavaScript(context,tableid, defcols)+'<='+this.left.toJavaScript(context,tableid, defcols)+')&&'+ - '('+this.left.toJavaScript(context,tableid, defcols)+'<='+this.right.right.toJavaScript(context,tableid, defcols)+'))'; - } else { - throw new Error('Wrong BETWEEN operator without AND part'); - } - }; - - if(this.op == 'NOT BETWEEN') { - if(this.right instanceof yy.Op && this.right.op == 'AND') { - return '!(('+this.right.left.toJavaScript(context,tableid, defcols)+'<='+this.left.toJavaScript(context,tableid, defcols)+')&&'+ - '('+this.left.toJavaScript(context,tableid, defcols)+'<='+this.right.right.toJavaScript(context,tableid, defcols)+'))'; - } else { - throw new Error('Wrong NOT BETWEEN operator without AND part'); - } - }; - - if(this.op == 'IN') { - if(this.right instanceof yy.Select ) { - var s = '('; -// s += 'this.query.queriesdata['+this.queriesidx+']'; - s += 'alasql.utils.flatArray(this.query.queriesfn['+(this.queriesidx)+'](params,null,p))'; - s += '.indexOf('; - s += this.left.toJavaScript(context,tableid, defcols)+')>-1)'; - return s; - } else if(this.right instanceof Array ) { -// if(this.right.length == 0) return 'false'; - var s = '(['+this.right.map(function(a){return a.toJavaScript(context,tableid, defcols)}).join(',')+'].indexOf('; - s += this.left.toJavaScript(context,tableid, defcols)+')>-1)'; -//console.log(s); - return s; - } else { - var s = '('+this.right.toJavaScript(context,tableid, defcols)+'.indexOf('; - s += this.left.toJavaScript(context,tableid, defcols)+')>-1)'; - return s; -// } else { -// throw new Error('Wrong IN operator without SELECT part'); - } - }; - - - if(this.op == 'NOT IN') { - if(this.right instanceof yy.Select ) { - var s = '(' - //this.query.queriesdata['+this.queriesidx+'] - s += 'alasql.utils.flatArray(this.query.queriesfn['+(this.queriesidx)+'](params,null,p))'; - s +='.indexOf('; - s += this.left.toJavaScript(context,tableid, defcols)+')<0)'; - return s; - } else if(this.right instanceof Array ) { -// if(this.right.length == 0) return 'true'; - var s = '(['+this.right.map(function(a){return a.toJavaScript(context,tableid, defcols)}).join(',')+'].indexOf('; - s += this.left.toJavaScript(context,tableid, defcols)+')<0)'; - return s; - } else { - throw new Error('Wrong NOT IN operator without SELECT part'); - } - }; - - if(this.allsome == 'ALL') { - if(this.right instanceof yy.Select ) { -// var s = 'this.query.queriesdata['+this.queriesidx+']'; - var s = 'alasql.utils.flatArray(this.query.queriesfn['+(this.queriesidx)+'](params,null,p))'; - - s +='.every(function(b){return ('; - s += this.left.toJavaScript(context,tableid, defcols)+')'+op+'b})'; - return s; - } else if(this.right instanceof Array ) { - var s = '['+this.right.map(function(a){return a.toJavaScript(context,tableid, defcols)}).join(',')+'].every(function(b){return ('; - s += this.left.toJavaScript(context,tableid, defcols)+')'+op+'b})'; - return s; - } else { - throw new Error('Wrong NOT IN operator without SELECT part'); - } - }; - - if(this.allsome == 'SOME' || this.allsome == 'ANY') { - if(this.right instanceof yy.Select ) { -// var s = 'this.query.queriesdata['+this.queriesidx+']'; - var s = 'alasql.utils.flatArray(this.query.queriesfn['+(this.queriesidx)+'](params,null,p))'; - s+='.some(function(b){return ('; - s += this.left.toJavaScript(context,tableid, defcols)+')'+op+'b})'; - return s; - } else if(this.right instanceof Array ) { - var s = '['+this.right.map(function(a){return a.toJavaScript(context,tableid, defcols)}).join(',')+'].some(function(b){return ('; - s += this.left.toJavaScript(context,tableid, defcols)+')'+op+'b})'; - return s; - } else { - throw new Error('Wrong NOT IN operator without SELECT part'); - } - }; - -// Special case for AND optimization (if reduced) - if(this.op == 'AND') { - if(this.left.reduced) { - if(this.right.reduced) { - return 'true'; - } else { - return this.right.toJavaScript(context,tableid, defcols); - } - } else if(this.right.reduced) { - return this.left.toJavaScript(context,tableid, defcols); - } - - // Otherwise process as regular operation (see below) - op = '&&'; - - } - - if(this.op == '^') { - return 'Math.pow('+this.left.toJavaScript(context,tableid, defcols) - +','+this.right.toJavaScript(context,tableid, defcols)+')'; - }; - - - // Change names -// console.log(this); - return '('+this.left.toJavaScript(context,tableid, defcols)+op+this.right.toJavaScript(context,tableid, defcols)+')'; -}; - - - -yy.VarValue = function (params) { return yy.extend(this, params); } -yy.VarValue.prototype.toString = function() { - return '@'+L(this.variable); -}; - -yy.VarValue.prototype.toType = function() { - return 'unknown'; -}; - -yy.VarValue.prototype.toJavaScript = function() { - return "alasql.vars['"+this.variable+"']"; -} - - -yy.NumValue = function (params) { return yy.extend(this, params); } -yy.NumValue.prototype.toString = function() { - return N(this.value.toString()); -}; - -yy.NumValue.prototype.toType = function() { - return 'number'; -}; - -yy.NumValue.prototype.toJavaScript = function() { - return ""+this.value; -} - - - - -yy.StringValue = function (params) { return yy.extend(this, params); } -yy.StringValue.prototype.toString = function() { - return "'"+S(this.value.toString())+"'"; -} - -yy.StringValue.prototype.toType = function() { - return 'string'; -} - -yy.StringValue.prototype.toJavaScript = function() { -// console.log("'"+doubleqq(this.value)+"'"); -// return "'"+doubleqq(this.value)+"'"; - return "'"+escapeq(this.value)+"'"; - -} - - -yy.LogicValue = function (params) { return yy.extend(this, params); } -yy.LogicValue.prototype.toString = function() { - return this.value?'TRUE':'FALSE'; -} - -yy.LogicValue.prototype.toType = function() { - return 'boolean'; -} - -yy.LogicValue.prototype.toJavaScript = function() { - return this.value?'true':'false'; -} - -yy.NullValue = function (params) { return yy.extend(this, params); } -yy.NullValue.prototype.toString = function() { - return 'NULL'; -} -yy.NullValue.prototype.toJavaScript = function() { - return 'undefined'; -} - -yy.ParamValue = function (params) { return yy.extend(this, params); } -yy.ParamValue.prototype.toString = function() { - return '$'+this.param; -} -yy.ParamValue.prototype.toJavaScript = function() { - if(typeof this.param == "string") return "params[\'"+this.param+"\']"; - else return "params["+this.param+"]"; -} - - - -yy.UniOp = function (params) { return yy.extend(this, params); } -yy.UniOp.prototype.toString = function() { - if(this.op == '-') return this.op+this.right.toString(); - if(this.op == '+') return this.op+this.right.toString(); - if(this.op == 'NOT') return this.op+'('+this.right.toString()+')'; - else if(this.op == null) return '('+this.right.toString()+')'; -}; - -yy.UniOp.prototype.findAggregator = function (query){ - if(this.right.findAggregator) this.right.findAggregator(query); -}; - -yy.UniOp.prototype.toType = function(tableid) { - if(this.op == '-') return 'number'; - if(this.op == '+') return 'number'; - if(this.op == 'NOT') return 'boolean'; -}; - -yy.UniOp.prototype.toJavaScript = function(context, tableid, defcols) { - if(this.op == '-') return "(-("+this.right.toJavaScript(context, tableid, defcols)+"))"; - if(this.op == '+') return "("+this.right.toJavaScript(context, tableid, defcols)+")"; - if(this.op == 'NOT') return '!('+this.right.toJavaScript(context, tableid, defcols)+')'; - else if(this.op == null) return '('+this.right.toJavaScript(context, tableid, defcols)+')'; -}; - - - -// yy.Star = function (params) { return yy.extend(this, params); } -// yy.Star.prototype.toString = function() { -// var s = this.fieldid; -// if(this.tableid) { -// s = this.tableid+'.'+s; -// if(this.databaseid) { -// s = this.databaseid+'.'+s; -// } -// } -// if(this.alias) s += ' AS '+this.alias; -// return s; -// } - -yy.Column = function(params) { return yy.extend(this, params); } -yy.Column.prototype.toString = function() { - var s; - if(this.columnid == +this.columnid) { - 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) s += ' AS '+this.alias; - return s; -}; - -yy.Column.prototype.toJavaScript = function(context, tableid, defcols) { -// var s = this.value; -// var s = this.columnid; -// if(this.tableid) { -// s = this.tableid+'.'+s; -// // if(this.databaseid) { -// // s = this.databaseid+'.'+s; -// // } -// } else { -// s = tableid+'.'+s; -// } -//console.log('yy.Column',this, tableid); -// console.log(392,this.columnid); - 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 != '_') { - 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 != '_') { - s = context+'[\''+(this.tableid || tableid) + '\'][\''+this.columnid+'\']'; - } else { - s = context+'[\''+(this.tableid || tableid) + '\']'; - }; - } - } else if(tableid == -1) { -// if(this.columnid != '') { - s = context+'[\''+this.columnid+'\']'; -// } else { -// s = context; -// } - } else { - if(this.columnid != '_') { - s = context+'[\''+(this.tableid || tableid) + '\'][\''+this.columnid+'\']'; - } else { - s = context+'[\''+(this.tableid || tableid) + '\']'; - } - } - } -// console.log(context,s); -// console.trace(new Error()); - return s; -} - - - - -yy.AggrValue = function(params){ return yy.extend(this, params); } -yy.AggrValue.prototype.toString = function() { - var s = ''; - if(this.aggregatorid == 'REDUCE') s += L(this.funcid)+'('; - else s += this.aggregatorid+'('; - if(this.distinct) s+= K('DISTINCT')+' '; - if(this.expression) s += this.expression.toString(); - s += ')'; - if(this.over) s += ' '+this.over.toString(); -// console.log(this.over); -// if(this.alias) s += ' AS '+this.alias; - return s; -}; -yy.AggrValue.prototype.findAggregator = function (query){ -// console.log('aggregator found',this.toString()); - -// var colas = this.as || this.toString(); - - var colas = escapeq(this.toString())+':'+query.selectGroup.length; -// console.log('findAgg',this); - - -/* var found = false; - for(var i=0;i-1) return 'number'; - if(['ARRAY'].indexOf(this.aggregatorid)>-1) return 'array'; - if(['FIRST','LAST' ].indexOf(this.aggregatorid)>-1) return this.expression.toType(); -} -yy.AggrValue.prototype.toJavaScript = function(context, tableid, defcols) { -// var s = 'alasql.functions.'+this.funcid+'('; -// if(this.expression) s += this.expression.toJavaScript(context, tableid); -// s += ')'; -// if(this.alias) s += ' AS '+this.alias; -// return s; -// var s = ''; -//if(this.as) console.log(499,this.as); -// var colas = this.as; - var colas = this.nick; - if(typeof colas == 'undefined') colas = this.toString(); - return 'g[\''+colas+'\']'; -} - - -yy.OrderExpression = function(params){ return yy.extend(this, params); } -yy.OrderExpression.prototype.toString = function() { - var s = this.expression.toString(); - if(this.order) s += ' '+this.order.toString(); - if(this.nocase) s += ' '+K('COLLATE')+' '+K('NOCASE'); - return s; -} - -yy.GroupExpression = function(params){ return yy.extend(this, params); } -yy.GroupExpression.prototype.toString = function() { - return this.type+'('+this.group.toString()+')'; -} - - -yy.ColumnDef = function (params) { return yy.extend(this, params); } -yy.ColumnDef.prototype.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; -} - - -// Alasql Linq library - -yy.FromData = function(params) { return yy.extend(this, params); }; -yy.FromData.prototype.toString = function() { - if(this.data) return K('DATA')+'('+((Math.random()*10e15)|0)+')'; - else return '?'; -}; -yy.FromData.prototype.toJavaScript = function(){ -// console.log('yy.FromData.prototype.toJavaScript'); -}; - -yy.Select.prototype.exec = function(params,cb) { - - if(this.preparams) params = this.preparams.concat(params); -// console.log(15,this.preparams); - - var databaseid = alasql.useid; - db = alasql.databases[databaseid]; - var sql = this.toString(); - var hh = hash(sql); -// console.log(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; -}; - -yy.Select.prototype.Select = function(){ - var self = this; - var agrs = []; - if(arguments.length > 1) { - args = Array.prototype.slice.call(arguments);; - } else if(arguments.length == 1) { - if(arguments[0] instanceof Array) { - 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 - } - }); - -// console.log(self instanceof yy.Select); - return self; -}; - -yy.Select.prototype.From = function(tableid){ - var self = this; - if(!self.from) self.from = []; - if(tableid instanceof Array) { - 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; -} - -yy.Select.prototype.OrderBy = function(){ - var self = this; - var agrs = []; - - self.order = []; - - if(arguments.length == 0) { -// self.order.push(new yy.OrderExpression({expression: new yy.Column({columnid:"_"}), direction:'ASC'})); - args = ["_"]; - } else if(arguments.length > 1) { - args = Array.prototype.slice.call(arguments);; - } else if(arguments.length == 1) { - if(arguments[0] instanceof Array) { - 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; -} - -yy.Select.prototype.Top = function(topnum){ - var self = this; - self.top = new yy.NumValue({value:topnum}); - return self; -}; - -yy.Select.prototype.GroupBy = function(){ - var self = this; - var agrs = []; - - if(arguments.length > 1) { - args = Array.prototype.slice.call(arguments);; - } else if(arguments.length == 1) { - if(arguments[0] instanceof Array) { - 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; -}; - -yy.Select.prototype.Where = function(expr){ - var self = this; - if(typeof expr == 'function' ) { - self.where = expr; - } - return self; -}; - - - -/* -// -// Functions for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.FuncValue = function(params){ return yy.extend(this, params); } -yy.FuncValue.prototype.toString = function() { - 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) s += ' AS '+this.as.toString(); -// if(this.alias) s += ' AS '+this.alias; - return s; -} - -yy.FuncValue.prototype.findAggregator = function(query) { - if(this.args && this.args.length > 0) { - this.args.forEach(function(arg){ - if(arg.findAggregator) arg.findAggregator(query); - }); - } -}; - -yy.FuncValue.prototype.toJavaScript = function(context, tableid, defcols) { - var s = ''; - var funcid = this.funcid; - // IF this is standard compile functions - if(alasql.fn[funcid]) { - // This is user-defined run-time function - // TODO arguments!!! -// var s = ''; - if(this.newid) s+= 'new '; - s += 'alasql.fn.'+this.funcid+'('; -// if(this.args) s += this.args.toJavaScript(context, tableid); - if(this.args && this.args.length > 0) { - s += this.args.map(function(arg){ - return arg.toJavaScript(context, tableid, defcols); - }).join(','); - }; - s += ')'; - } else if(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.toJavaScript(context, tableid)})); - } else { - s += alasql.stdlib[funcid.toUpperCase()](); - } - } else if(alasql.stdfn[funcid.toUpperCase()]) { - if(this.newid) s+= 'new '; - s += 'alasql.stdfn.'+this.funcid.toUpperCase()+'('; -// if(this.args) s += this.args.toJavaScript(context, tableid); - if(this.args && this.args.length > 0) { - s += this.args.map(function(arg){ - return arg.toJavaScript(context, tableid, defcols); - }).join(','); - }; - s += ')'; - } else { - // Aggregator - } -//console.log('userfn:',s,this); - -// if(this.alias) s += ' AS '+this.alias; - return s; -} - -// // Functions compiler -// nodes.FunctionValue.prototype.toJavaScript = function (context, tableid) { -// var s = ''; -// s += fns[this.name.toUpperCase()].apply(null,this.arguments.map(function(arg){ -// if(arg) return arg.toJavaScript(context, tableid); -// else return ''; -// })); -// return s; -// }; - -// -// SQL FUNCTIONS COMPILERS -// Based on SQLite functions - -// IMPORTANT: These are compiled functions - -//alasql.fn = {}; // Keep for compatibility -//alasql.userlib = alasql.fn; - -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+')'}; -stdlib.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'); - }; -}; -stdlib.IFNULL = function(a,b) {return '('+a+'||'+b+')'}; -stdlib.INSTR = function(s,p) {return '(('+s+').indexOf('+p+')+1)'}; - -stdlib.LEN = stdlib.LENGTH = function(s) {return '('+s+'+"").length';}; -//stdlib.LENGTH = function(s) {return '('+s+').length'}; - -stdlib.LOWER = stdlib.LCASE = function(s) {return '('+s+').toLowerCase()';} -//stdlib.LCASE = function(s) {return '('+s+').toLowerCase()';} - - -// LTRIM - -stdlib.GREATEST = function(){ - return 'Math.max('+Array.prototype.join.call(arguments, ',')+')' -}; - -stdlib.LEAST = function(){ - return 'Math.min('+Array.prototype.join.call(arguments, ',')+')' -}; - -stdlib.MID = function(a,b,c){ - if(arguments.length == 2) return '('+a+').substr('+b+'-1)'; - else if(arguments.length == 3) return '('+a+').substr('+b+'-1,'+c+')'; -}; - -stdlib.NULLIF = function(a,b){return '('+a+'=='+b+'?null:'+a+')'}; - -stdlib.POWER = function(a,b) {return 'Math.pow('+a+','+b+')'}; - -stdlib.RANDOM = function(r) { - if(arguments.length == 0) { - return 'Math.random()'; - } else { - return '(Math.random()*('+r+')|0)'; - } -} -stdlib.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+')'; - } -} -stdlib.SQRT = function(s) {return 'Math.sqrt('+s+')'}; - -stdlib.TRIM = function(s) {return s+'.trim()'}; - -stdlib.UPPER = stdlib.UCASE = function(s) {return '('+s+').toUpperCase()';} -//stdlib.UCASE = function(s) {return '('+s+').toUpperCase()';} -//REPLACE -// RTRIM -// SUBSTR -// TRIM -//REPLACE -// RTRIM -// SUBSTR -// TRIM - - -// Aggregator for joining strings -alasql.aggr.GROUP_CONCAT = function(v,s){ - if(typeof s == "undefined") return v; else return s+','+v; -}; - - - - -// -// -// SQL and JS DateTime functions -// -// - - - -/* -// -// CASE for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.CaseValue = function(params) { return yy.extend(this, params); }; -yy.CaseValue.prototype.toString = function() { - var s = 'CASE '; - if(this.expression) s += this.expression.toString(); - if(this.whens) { - s += this.whens.map(function(w) { return ' WHEN '+ - w.when.toString() + ' THEN '+w.then.toString()}).join(); - } - s += ' END'; - return s; -}; - -yy.CaseValue.prototype.findAggregator = function (query){ -// console.log(this.toString()); - if(this.expression && this.expression.findAggregator) this.expression.findAggregator(query); - if(this.whens && this.whens.length > 0) { - this.whens.forEach(function(w) { - if(w.when.findAggregator) w.when.findAggregator(query); - if(w.then.findAggregator) w.then.findAggregator(query); - }); - } -}; - -yy.CaseValue.prototype.toJavaScript = function(context, tableid, defcols) { - - var s = '(function('+context+',params,alasql){var r;'; - if(this.expression) { -// this.expression.toJavaScript(context, tableid) - s += 'v='+this.expression.toJavaScript(context, tableid, defcols)+';'; - s += (this.whens||[]).map(function(w) { return ' if(v=='+w.when.toJavaScript(context,tableid, defcols) - +') {r='+w.then.toJavaScript(context,tableid, defcols)+'}'; }).join(' else '); - if(this.elses) s += ' else {r='+this.elses.toJavaScript(context,tableid, defcols)+'}'; - } else { - s += (this.whens||[]).map(function(w) { return ' if('+w.when.toJavaScript(context,tableid, defcols) - +') {r='+w.then.toJavaScript(context,tableid, defcols)+'}'; }).join(' else '); - if(this.elses) s += ' else {r='+this.elses.toJavaScript(context,tableid,defcols)+'}'; - } - s += 'return r;})('+context+',params,alasql)'; - - return s; -}; - -/* -// -// JSON for Alasql.js -// Date: 19.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.Json = function (params) { return yy.extend(this, params); } -yy.Json.prototype.toString = function() { - var s = '@'; - s += JSONtoString(this.value); - s += ''; - return s; -}; - -var JSONtoString = alasql.utils.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(obj instanceof Array) { - s += '['+obj.map(function(b){ - return JSONtoString(b); - }).join(',')+']'; - } else if(!obj.toJavaScript || 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; -} - - - -function JSONtoJavaScript(obj, context, tableid, defcols) { - 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(obj instanceof Array) { - s += '['+obj.map(function(b){ - return JSONtoJavaScript(b, context, tableid, defcols); - }).join(',')+']'; - } else if(!obj.toJavaScript || 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 += ':'+JSONtoJavaScript(obj[k], context, tableid, defcols); - ss.push(s1); - }; - s += ss.join(',')+'}'; - } else if(obj.toJavaScript) { - s = obj.toJavaScript(context, tableid, defcols); - } else { - throw new Error('1Can not parse JSON object '+JSON.stringify(obj)); - } - } else { - throw new Error('2Can not parse JSON object '+JSON.stringify(obj)); - } - - return s; -} - -yy.Json.prototype.toJavaScript = function(context, tableid, defcols) { - // TODO reod - return JSONtoJavaScript(this.value,context, tableid, defcols); -} - - - - -/* -// -// CAST and CONVERT functions -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.Convert = function(params) { return yy.extend(this, params); }; -yy.Convert.prototype.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; -}; -yy.Convert.prototype.toJavaScript = function(context, tableid, defcols) { - -// if(this.style) { - return 'alasql.stdfn.CONVERT('+this.expression.toJavaScript(context, tableid, defcols) - +',{dbtypeid:"'+this.dbtypeid+'",dbsize:'+this.dbsize+',style:'+ - this.style+'})'; -// } -/* - if(this.dbtypeid == 'INT') { - return '(('+this.expression.toJavaScript(context, tableid, defcols)+')|0)'; - } if(this.dbtypeid == 'STRING') { - return '(""+'+this.expression.toJavaScript(context, tableid, defcols)+')'; - } if(this.dbtypeid == 'NUMBER') { - return '(+('+this.expression.toJavaScript(context, tableid, defcols)+'))'; - } if(this.dbtypeid == 'DATE') { - if(alasql.options.datetimeformat == 'javascript') { - return '(new Date('+this.expression.toJavaScript(context, tableid, defcols)+'))'; - } else if(alasql.options.datetimeformat == 'sql') { - return this.expression.toJavaScript(context, tableid, defcols); - } - } if(this.dbtypeid == 'DATETIME') { - if(alasql.options.datetimeformat == 'javascript') { - return '(new Date('+this.expression.toJavaScript(context, tableid, defcols)+'))'; - } else if(alasql.options.datetimeformat == 'sql') { - return this.expression.toJavaScript(context, tableid, defcols); - } - } else { - - }; -*/ - throw new Error('There is not such type conversion for '+this.toString()); -}; - -/** - Convert one type to another - */ -alasql.stdfn.CONVERT = function(value, args) { - var val = value; -// console.log(args); - 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); - - if(args.style == 1) { // mm/dd/yy - val = ("0"+(t.getMonth()+1)).substr(-2)+'/'+("0"+t.getDate()).substr(-2)+'/'+("0"+t.getYear()).substr(-2); - } else if(args.style == 2) { // yy.mm.dd - val = ("0"+t.getYear()).substr(-2)+'.'+("0"+(t.getMonth()+1)).substr(-2)+'.'+("0"+t.getDate()).substr(-2); - } else if(args.style == 3) { // dd/mm/yy - val = ("0"+t.getDate()).substr(-2)+'/'+("0"+(t.getMonth()+1)).substr(-2)+'/'+("0"+t.getYear()).substr(-2); - } else if(args.style == 4) { // dd.mm.yy - val = ("0"+t.getDate()).substr(-2)+'.'+("0"+(t.getMonth()+1)).substr(-2)+'.'+("0"+t.getYear()).substr(-2); - } else if(args.style == 5) { // dd-mm-yy - val = ("0"+t.getDate()).substr(-2)+'-'+("0"+(t.getMonth()+1)).substr(-2)+'-'+("0"+t.getYear()).substr(-2); - } else if(args.style == 6) { // dd mon yy - val = ("0"+t.getDate()).substr(-2)+' '+t.toString().substr(4,3).toLowerCase()+' '+("0"+t.getYear()).substr(-2); - } else if(args.style == 7) { // Mon dd,yy - val = t.toString().substr(4,3)+' '+("0"+t.getDate()).substr(-2)+','+("0"+t.getYear()).substr(-2); - } else if(args.style == 8) { // hh:mm:ss - val = ("0"+t.getHours()).substr(-2)+':'+("0"+(t.getMinutes()+1)).substr(-2)+':'+("0"+t.getSeconds()).substr(-2); - - } else if(args.style == 10) { // mm-dd-yy - val = ("0"+(t.getMonth()+1)).substr(-2)+'-'+("0"+t.getDate()).substr(-2)+'-'+("0"+t.getYear()).substr(-2); - } else if(args.style == 11) { // yy/mm/dd - val = ("0"+t.getYear()).substr(-2)+'/'+("0"+(t.getMonth()+1)).substr(-2)+'/'+("0"+t.getDate()).substr(-2); - } else if(args.style == 12) { // yymmdd - val = ("0"+t.getYear()).substr(-2)+("0"+(t.getMonth()+1)).substr(-2)+("0"+t.getDate()).substr(-2); - - - } else if(args.style == 101) { // mm/dd/yy - val = ("0"+(t.getMonth()+1)).substr(-2)+'/'+("0"+t.getDate()).substr(-2)+'/'+t.getFullYear(); - } else if(args.style == 102) { // yy.mm.dd - val = t.getFullYear()+'.'+("0"+(t.getMonth()+1)).substr(-2)+'.'+("0"+t.getDate()).substr(-2); - } else if(args.style == 103) { // dd/mm/yy - val = ("0"+t.getDate()).substr(-2)+'/'+("0"+(t.getMonth()+1)).substr(-2)+'/'+t.getFullYear(); - } else if(args.style == 104) { // dd.mm.yy - val = ("0"+t.getDate()).substr(-2)+'.'+("0"+(t.getMonth()+1)).substr(-2)+'.'+t.getFullYear(); - } else if(args.style == 105) { // dd-mm-yy - val = ("0"+t.getDate()).substr(-2)+'-'+("0"+(t.getMonth()+1)).substr(-2)+'-'+t.getFullYear(); - } else if(args.style == 106) { // dd mon yy - val = ("0"+t.getDate()).substr(-2)+' '+t.toString().substr(4,3).toLowerCase()+' '+t.getFullYear(); - } else if(args.style == 107) { // Mon dd,yy - val = t.toString().substr(4,3)+' '+("0"+t.getDate()).substr(-2)+','+t.getFullYear(); - } else if(args.style == 108) { // hh:mm:ss - val = ("0"+t.getHours()).substr(-2)+':'+("0"+(t.getMinutes()+1)).substr(-2)+':'+("0"+t.getSeconds()).substr(-2); - - } else if(args.style == 110) { // mm-dd-yy - val = ("0"+(t.getMonth()+1)).substr(-2)+'-'+("0"+t.getDate()).substr(-2)+'-'+t.getFullYear(); - } else if(args.style == 111) { // yy/mm/dd - val = t.getFullYear()+'/'+("0"+(t.getMonth()+1)).substr(-2)+'/'+("0"+t.getDate()).substr(-2); - } else if(args.style == 112) { // yymmdd - val = t.getFullYear()+("0"+(t.getMonth()+1)).substr(-2)+("0"+t.getDate()).substr(-2); - } else { - throw new Error('The CONVERT style '+args.style+' is not realized yet.'); - } - }; - - if(args.dbtypeid == 'Date') { - return new Date(val); - } else if(args.dbtypeid.toUpperCase() == '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(args.dbtypeid == 'DATETIME') { - 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()).substr(-3) - return s; - } else if(args.dbtypeid.toUpperCase() == 'STRING') { - return ""+val; - } else if(args.dbtypeid.toUpperCase() == 'NUMBER' || args.dbtypeid == 'FLOAT') { - return +val; - } else if(args.dbtypeid.toUpperCase() == 'MONEY') { - var m = +val; - return (m|0)+((m*100)%100)/100; - } else if(args.dbtypeid.toUpperCase() == 'BOOLEAN') { - return !!val; - } else if(args.dbtypeid.toUpperCase() == 'INT') { - return val|0; - } else if(args.dbtypeid.toUpperCase() == 'VARCHAR' || args.dbtypeid == 'NVARCHAR') { - if(args.dbsize) return (""+val).substr(0,args.dbsize); - else return ""+val; - } else if(args.dbtypeid.toUpperCase() == 'CHAR' || args.dbtypeid == 'NCHAR') { - return (val+(new Array(args.dbsize+1).join(" "))).substr(0,args.dbsize); - //else return ""+val.substr(0,1); - } -}; - - - -/* -// -// CREATE TABLE for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.ColumnDef = function (params) { return yy.extend(this, params); } -yy.ColumnDef.prototype.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; -} - -yy.CreateTable = function (params) { return yy.extend(this, params); } -yy.CreateTable.prototype.toString = function() { - var s = K('CREATE'); - if(this.temporary) s+=' '+K('TEMPORARY'); - if(this.view) s += ' '+K('VIEW'); - else s += ' '+K('TABLE'); - if(this.ifnotexists) s += ' '+K('IF')+' '+K('NOT')+' '+K('EXISTS'); - s += ' '+this.table.toString(); - if(this.viewcolumns) { - s += '('+this.viewcolumns.map(function(vcol){ - return vcol.toString(); - }).join(',')+')'; - } - if(this.as) s += ' '+K('AS')+' '+L(this.as); - else { - var ss = this.columns.map(function(col){ - return col.toString(); - }); - s += ' ('+NL()+ID()+ss.join(','+NL()+ID())+')'; - }; - if(this.view && this.select) { - s += ' AS '+this.select.toString(); - } - return s; -} - -// CREATE TABLE -//yy.CreateTable.prototype.compile = returnUndefined; -yy.CreateTable.prototype.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||[]; -// console.log(this); - - // IF NOT EXISTS - if(this.ifnotexists && db.tables[tableid]) return 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? - - var ss = []; - if(this.columns) { - this.columns.forEach(function(col) { - var dbtypeid = col.dbtypeid; - if(!alasql.fn[dbtypeid]) dbtypeid = dbtypeid.toUpperCase(); - var newcol = { - columnid: col.columnid, - dbtypeid: dbtypeid // TODO: Add types table - }; - - if(col.default) { - ss.push('\''+col.columnid+'\':'+col.default.toJavaScript()); - } - - table.columns.push(newcol); - table.xcolumns[newcol.columnid] = newcol; - - // 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",'return '+pk.onrightfns); - pk.hh = hash(pk.onrightfns); - table.indices[pk.hh] = {}; - }; - - }); - }; - table.defaultfns = ss.join(','); - - -// if(constraints) { - constraints.forEach(function(con) { - //console.log(con, con.columns); - 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",'return '+pk.onrightfns); - pk.hh = hash(pk.onrightfns); - table.indices[pk.hh] = {}; - } - }); - - if(this.view && this.viewcolumns) { - var self = this; - this.viewcolumns.forEach(function(vcol,idx){ - self.select.columns[idx].as = vcol.columnid; - }); - } - -// console.log(100,db.engineid); - if(db.engineid) { -// console.log(101,db.engineid); - return alasql.engines[db.engineid].createTable(this.table.databaseid || databaseid, tableid, this.ifnotexists, cb); -// console.log('createtable',res1); -// return res1; - } - -// } -// if(table.pk) { - table.insert = function(r) { - if(this.pk) { - var pk = this.pk; - var addr = pk.onrightfn(r); - if(typeof this.indices[pk.hh][addr] != 'undefined') { - throw new Error('Cannot insert record, because it already exists in primary key'); - } else { - table.data.push(r); - this.indices[pk.hh][addr]=r; - }; - } else { - table.data.push(r); - } - }; - - table.delete = function(i) { - if(this.pk) { - var r = this.data[i]; - var pk = this.pk; - var addr = pk.onrightfn(r); - if(typeof this.indices[pk.hh][addr] == 'undefined') { - throw new Error('Something wrong with index on table'); - } else { - this.indices[pk.hh][addr]=undefined; - }; - } - }; - - table.deleteall = function() { - this.data.length = 0; - if(this.pk) { -// var r = this.data[i]; - this.indices[this.pk.hh] = {}; - } - }; - - table.update = function(assignfn, i, params) { - if(this.pk) { - var r = this.data[i]; - var pk = this.pk; - var addr = pk.onrightfn(r,params); - if(typeof this.indices[pk.hh][addr] == 'undefined') { - throw new Error('Something wrong with index on table'); - } else { - this.indices[pk.hh][addr]=undefined; - assignfn(r,params,alasql); - var newaddr = pk.onrightfn(r); - if(typeof this.indices[pk.hh][newaddr] != 'undefined') { - throw new Error('Record already exists'); - } else { - this.indices[pk.hh][newaddr] = r; - } - } - - } else { - assignfn(this.data[i],params,alasql); - }; - - }; - - if(this.view && this.select) { - table.view = true; -// console.log(this.select.toString()); -// console.log('this.table.databaseid',this.table.databaseid); -// console.log(this.select.compile(this.table.databaseid||databaseid)); - table.select = this.select.compile(this.table.databaseid||databaseid); - } -// console.log(databaseid); -// console.log(db.databaseid,db.tables); -// console.log(table); - if(cb) cb(1); - - return 1; -}; - - + } 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; + } + } -// -// Date functions -// -// (c) 2014, Andrey Gershun -// + var s = ''; -/** Standard JavaScript data types */ + if(typeof sql == 'string' && alasql.options.logprompt) { +// s += '

'+olduseid+'> '+alasql.pretty(sql)+'

'; + s += '
'+alasql.pretty(sql)+'
'; + } -alasql.fn.Date = Object; -alasql.fn.Date = Date; -alasql.fn.Number = Number; -alasql.fn.String = String; -alasql.fn.Boolean = Boolean; + if(res instanceof Array) { + if(res.length == 0) { + s += '

[ ]

' + } else if(typeof res[0] != 'object' || res[0] instanceof Array) { + for(var i=0,ilen=res.length;i'; + } + } else { + s += loghtml(res); + } + } else { + s += loghtml(res); + } + el.innerHTML += s; + } +}; -/** Extend Object with properties */ -stdfn.EXTEND = alasql.utils.extend; +alasql.clear = function() { + var target = alasql.options.logtarget; + // For node other + if(typeof exports == 'object') { + target = 'console'; + }; + if(target == 'console' || typeof exports == 'object') { + if(console.clear) { + console.clear(); + } else { + // Something todo in Node + } + } 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 = ''; + } +} -stdfn.CHAR = String.fromCharCode.bind(String); -stdfn.ASCII = function(a) { - return a.charCodeAt(0); -}; +alasql.write = function(s) { +// console.log('write',s); + var target = alasql.options.logtarget; + // For node other + if(typeof exports == 'object') { + target = 'console'; + }; -/** - Return first non-null argument - See https://msdn.microsoft.com/en-us/library/ms190349.aspx -*/ -stdfn.COALESCE = function() { - for(var i=0;i'; + } + // if () {} -stdfn.OBJECT_ID = function(objid){ - return !!alasql.tables[objid]; + // if(typeof res == 'object') { + // s += '

'+JSON.stringify(res)+'

'; + // } else { + // } + return s; }; -stdfn.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); -}; -stdfn.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; -}; -stdfn.GETDATE = stdfn.NOW; +function scrollTo(element, to, duration) { + if (duration <= 0) return; + var difference = to - element.scrollTop; + var perTick = difference / duration * 10; -// stdfn.GETDATE = function(){ -// var d = new Date(); -// var s = d.getFullYear()+"."+("0"+(d.getMonth()+1)).substr(-2)+"."+("0"+d.getDate()).substr(-2); -// return s; -// } + setTimeout(function() { + if (element.scrollTop==to) return; + element.scrollTop = element.scrollTop + perTick; + scrollTo(element, to, duration - 10); + }, 10); +} + +alasql.prompt = function(el, useidel, firstsql) { + if(typeof exports == 'object') { + throw new Error('The functionality of prompt is 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('

'+(Date.now()-tm)+' ms

'); + } catch (err) { + alasql.write('

'+olduseid+'> '+sql+'

'); + alasql.write('

'+err+'

'); + } + }; + 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('

'+(Date.now()-tm)+' ms

'); + } catch (err) { + alasql.write('

'+olduseid+'> '+alasql.pretty(sql, false)+'

'); + alasql.write('

'+err+'

'); + } + el.focus(); +// console.log(el.getBoundingClientRect().top); + 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(); + } -stdfn.SECOND = function(d){ - d = new Date(d); - return d.getSeconds(); -}; + } 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(); + } + } + } +} -stdfn.MINUTE = function(d){ - d = new Date(d); - return d.getMinutes(); -}; -stdfn.HOUR = function(d){ - d = new Date(d); - return d.getHours(); -}; -stdfn.DAYOFWEEK = stdfn.WEEKDAY = function(d){ - d = new Date(d); - return d.getDay(); -}; -stdfn.DAY = stdfn.DAYOFMONTH = function(d){ - d = new Date(d); - return d.getDate(); -}; -stdfn.MONTH = function(d){ - d = new Date(d); - return d.getMonth()+1; +/* +// +// Commit for Alasql.js +// Date: 01.12.2014 +// (c) 2014, Andrey Gershun +// +*/ +yy.BeginTransaction = function (params) { return yy.extend(this, params); } +yy.BeginTransaction.prototype.toString = function() { + return K('BEGIN')+' '+K('TRANSACTION'); +} + +yy.BeginTransaction.prototype.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; }; -stdfn.YEAR = function(d){ - d = new Date(d); - return d.getFullYear(); +yy.CommitTransaction = function (params) { return yy.extend(this, params); } +yy.CommitTransaction.prototype.toString = function() { + return K('COMMIT')+' '+K('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; }; -/* -// -// DROP TABLE for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.DropTable = function (params) { return yy.extend(this, params); } -yy.DropTable.prototype.toString = function() { - var s = K('DROP')+' '; - if(this.view) s += K('VIEW'); - else s += K('TABLE'); - if(this.ifexists) s += ' '+K('IF')+' '+K('EXISTS'); - s += ' '+this.table.toString(); - return s; -} - - -// DROP TABLE -yy.DropTable.prototype.execute = function (databaseid, params, cb) { -// console.log(arguments); -// console.log(alasql.databases[databaseid]); - var db = alasql.databases[this.table.databaseid || databaseid]; - var tableid = this.table.tableid; -// console.log(db, this.table.databaseid ); - if(db.engineid /*&& alasql.options.autocommit*/) { - return alasql.engines[db.engineid].dropTable(this.table.databaseid || databaseid,tableid, this.ifexists, cb); - } - if(!this.ifexists || this.ifexists && db.tables[tableid]) { - if(!db.tables[tableid]) { - if(!alasql.options.dropifnotexists) { - throw new Error('Can not drop table \''+this.table.tableid+'\', because it does not exist in the database.'); - } - } else { - delete db.tables[tableid]; - return 1; - } - } - return 0; -}; - - -yy.TruncateTable = function (params) { return yy.extend(this, params); } -yy.TruncateTable.prototype.toString = function() { - var s = K('TRUNCATE')+' '+K('TABLE'); - 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; -// console.log(db, this.table.databaseid ); - 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 0; -}; - - -/* -// -// ALTER TABLE for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -// ALTER TABLE table1 RENAME TO table2 -yy.AlterTable = function (params) { return yy.extend(this, params); } -yy.AlterTable.prototype.toString = function() { - var s = 'ALTER TABLE '+this.table.toString(); - if(this.renameto) s += ' RENAME TO '+this.renameto; - return s; -} - -yy.AlterTable.prototype.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 0) { - for(var i=0, ilen=table.data.length; i 0) { - for(var i=0, ilen=table.data.length; i=0) { - q += "+"+values[idx].toJavaScript(); - } else if (alasql.fn[table.xcolumns[col.columnid].dbtypeid]) { - q += "(new "+table.xcolumns[col.columnid].dbtypeid+"("; - q += values[idx].toJavaScript(); - q += "))"; - } else { - q += values[idx].toJavaScript(); - }; - } else { - q += values[idx].toJavaScript(); - } - ss.push(q); - - }); - } else { -// var table = db.tables[tableid]; -// console.log('table1', db, self); -//console.log(111, table.columns); -//console.log(74,table); - if((values instanceof Array) && table.columns && table.columns.length > 0) { - table.columns.forEach(function(col, idx){ - - var q = '\''+col.columnid +'\':'; -// var val = values[idx].toJavaScript(); - - if(["INT","FLOAT","NUMBER","MONEY"].indexOf(col.dbtypeid) >=0) { - q += "+"+values[idx].toJavaScript(); - } else if (alasql.fn[col.dbtypeid]) { - q += "(new "+col.dbtypeid+"("; - q += values[idx].toJavaScript(); - q += "))"; - } else { - q += values[idx].toJavaScript(); - } - - // if(table.xcolumns && table.xcolumns[col.columnid] && - // (table.xcolumns[col.columnid].dbtypeid == "DATE" || - // table.xcolumns[col.columnid].dbtypeid == "DATETIME" - // )) { - // val = "(new Date("+val+"))"; - // } - // || table.xcolumns[col.columnid].dbtypeid == "FLOAT" - // || table.xcolumns[col.columnid].dbtypeid == "NUMBER" - // || table.xcolumns[col.columnid].dbtypeid == "MONEY" - // )) q += '+'; - // console.log(self.values[idx].toString()); - //console.log(self); -// q += val; - - // if(table.xcolumns && table.xcolumns[col.columnid] && table.xcolumns[col.columnid].dbtypeid == "INT") q += '|0'; - ss.push(q); - - // console.log(fld); - // TODO: type checking and conversions - // rec[fld.fldid] = eval(self.insertExpression[idx].toJavaScript('','')); - // console.log(rec[fld.fldid]); - // if(rec[fld.fldid] == "NULL") rec[fld.fldid] = undefined; - - // if(table.xflds[fld.fldid].dbtypeid == "INT") rec[fld.fldid] = +rec[fld.fldid]|0; - // else if(table.xflds[fld.fldid].dbtypeid == "FLOAT" || table.xflds[fld.fldid].dbtypeid == "MONEY" ) - // rec[fld.fldid] = +rec[fld.fldid]; - }); - } else { -// console.log(222,values); -// sw = 'var w='+JSONtoJavaScript(values)+';for(var k in w){r[k]=w[k]};'; - sw = JSONtoJavaScript(values); - } - } -//console.log(ss); - - if(db.tables[tableid].defaultfns) ss.unshift(db.tables[tableid].defaultfns); - if(sw) { - s += 'a='+sw+';'; - } else { - s += 'a={'+ss.join(',')+'};'; - } -// s += 'db.tables[\''+tableid+'\'].insert(r);'; - if(db.tables[tableid].insert) { - s += 'alasql.databases[\''+databaseid+'\'].tables[\''+tableid+'\'].insert(a);'; - } else { - s += 'aa.push(a);'; - } - }); - - s33 = s3+s; - - if(db.tables[tableid].insert) { -// s += 'alasql.databases[\''+databaseid+'\'].tables[\''+tableid+'\'].insert(r);'; - } else { - s += 'alasql.databases[\''+databaseid+'\'].tables[\''+tableid+'\'].data='+ - 'alasql.databases[\''+databaseid+'\'].tables[\''+tableid+'\'].data.concat(aa);'; - } - - s += 'return '+self.values.length; - -//console.log(s); - var insertfn = new Function('db, params, alasql',s3+s); - -// INSERT INTO table SELECT - - } else if(this.select) { - 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,null, cb); - return res; - }; - return statement; - } else { - var insertfn = function(db, params, alasql) { - var res = selectfn(params); - db.tables[tableid].data = db.tables[tableid].data.concat(res); - return res.length; - } - } - - - } else if(this.default) { - var insertfns = 'db.tables[\''+tableid+'\'].data.push({'+table.defaultfns+'});return 1;'; - var insertfn = new Function('db,params,alasql',insertfns); - } else { - throw new Error('Wrong INSERT parameters'); - } - -// console.log(1,s); -// console.log(s33); - - if(db.engineid && alasql.engines[db.engineid].intoTable && alasql.options.autocommit) { - var statement = function(params, cb) { - var aa = new Function("db,params",s33+'return aa;')(db,params); -// console.log(s33); - var res = alasql.engines[db.engineid].intoTable(db.databaseid,tableid,aa, null, cb); -// if(cb) cb(res); - return res; - }; - - } else { - - var statement = function(params, cb) { - //console.log(databaseid); - 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); - } - // var res = insertfn(db, params); - if(cb) cb(res); - return res; - }; - }; - - return statement; -}; - -yy.Insert.prototype.execute = function (databaseid, params, cb) { - return this.compile(databaseid)(params,cb); -// throw new Error('Insert statement is should be compiled') -} - - - - - -/* -// -// DELETE for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.Delete = function (params) { return yy.extend(this, params); } -yy.Delete.prototype.toString = function() { - var s = 'DELETE FROM '+this.table.toString(); - if(this.where) s += ' WHERE '+this.where.toString(); - return s; -} - -yy.Delete.prototype.compile = function (databaseid) { -// console.log(11,this); - databaseid = this.table.databaseid || databaseid; - var tableid = this.table.tableid; - var statement; - var db = alasql.databases[databaseid]; - - - - if(this.where) { -// try { -// console.log(this, 22, this.where.toJavaScript('r','')); -// } catch(err){console.log(444,err)}; -// var query = {}; - wherefn = new Function('r,params','return ('+this.where.toJavaScript('r','')+')'); -// console.log(wherefn); - 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]; -// table.dirty = true; - var orignum = table.data.length; - - var newtable = []; - for(var i=0, ilen=table.data.length;i 0) { - s += '('+this.args.map(function(arg){ return arg.toString()}).join(', ')+')'; - } - if(this.as) s += ' '+K('AS')+' '+L(this.as); - return s; -} -//yy.CreateDatabase.prototype.compile = returnUndefined; -yy.CreateDatabase.prototype.execute = function (databaseid, params, cb) { - // console.log(alasql.useid, databaseid, this.databaseid); - // console.trace(); - var args; - if(this.args && this.args.length > 0) { - args = this.args.map(function(arg){ - return new Function('params','return '+arg.toJavaScript())(params); - }); - }; - 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; - } -}; - -// CREATE DATABASE databaseid -yy.AttachDatabase = function (params) { return yy.extend(this, params); }; -yy.AttachDatabase.prototype.toString = function() { - var s = K('ATTACH'); - if(this.engineid) s += ' '+L(this.engineid); - s += ' '+K('DATABASE')+' '+L(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+= ' '+K('AS')+' '+L(this.as); - return s; -} -//yy.CreateDatabase.prototype.compile = returnUndefined; -yy.AttachDatabase.prototype.execute = function (databaseid, params, cb) { - // console.log(alasql.useid, databaseid, this.databaseid); - // console.trace(); - 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 = K('DETACH'); - s += ' '+K('DATABASE')+' '+L(this.databaseid); - return s; -} -//yy.CreateDatabase.prototype.compile = returnUndefined; -yy.DetachDatabase.prototype.execute = function (databaseid, params, cb) { - // console.log(alasql.useid, databaseid, this.databaseid); - // console.trace(); - 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"); - } -// console.log(dbid); - 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; -}; - -// USE DATABSE databaseid -// USE databaseid -yy.UseDatabase = function (params) { return yy.extend(this, params); }; -yy.UseDatabase.prototype.toString = function() { - return K('USE') +' '+K('DATABASE')+' '+L(this.databaseid); -} -//yy.UseDatabase.prototype.compile = returnUndefined; -yy.UseDatabase.prototype.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; -}; - -// DROP DATABASE databaseid -yy.DropDatabase = function (params) { return yy.extend(this, params); } -yy.DropDatabase.prototype.toString = function() { - var s = K('DROP'); - if(this.ifexists) s += ' '+K('IF')+' '+K('EXISTS'); - s += ' '+K('DATABASE')+' '+L(this.databaseid); - return s; -} -//yy.DropDatabase.prototype.compile = returnUndefined; -yy.DropDatabase.prototype.execute = function (databaseid, params, cb) { - if(this.engineid) { - -// console.log(this,this.databaseid, this.ifexists); - 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"); - } -// console.log(dbid); - 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; -}; - - - - - - - -/* -// -// SET for Alasql.js -// Date: 01.12.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.Declare = function (params) { return yy.extend(this, params); } -yy.Declare.prototype.toString = function() { - var s = K('DECLARE')+' '; - if(this.declares && this.declares.length > 0) { - s = this.declares.map(function(declare){ - var s = ''; - s += '@'+L(declare.variable)+' '; - s += declare.dbtypeid; - if(this.dbsize) s += '('+N(this.dbsize); - if(this.dbprecision) s+= ','+N(this.dbprecision); - s += ')'; - if(declare.expression) s += ' = '+declare.expression.toString(); - return s; - }).join(','); - } - return s; -} - -yy.Declare.prototype.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) { - // console.log(this.expression.toJavaScript('','', null)); - alasql.vars[declare.variable] = new Function("params,alasql","return " - +declare.expression.toJavaScript('','', 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; -}; - - - -/* -// -// SHOW for Alasql.js -// Date: 19.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.ShowDatabases = function (params) { return yy.extend(this, params); } -yy.ShowDatabases.prototype.toString = function() { - var s = K('SHOW')+' '+K('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) { - res = res.filter(function(d){ - return d.databaseid.match(new RegExp((self.like.value).replace(/\%/g,'.*'),'g')); - }); - } - if(cb) cb(res); - return res; - }; - -}; - - -yy.ShowTables = function (params) { return yy.extend(this, params); } -yy.ShowTables.prototype.toString = function() { - var s = K('SHOW')+' '+K('TABLES'); - if(this.databaseid) s += ' FROM '+this.databaseid; - if(this.like) s += ' '+K('LIKE')+' '+this.like.toString(); - return s; -} -yy.ShowTables.prototype.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,'.*'),'g')); - }); - }; - if(cb) cb(res); - return res; -}; - -yy.ShowColumns = function (params) { return yy.extend(this, params); } -yy.ShowColumns.prototype.toString = function() { - var s = K('SHOW')+' '+K('COLUMNS'); - if(this.table.tableid) s += ' '+K('FROM')+' '+this.table.tableid; - if(this.databaseid) s += ' '+K('FROM')+' '+this.databaseid; - return s; -}; - -yy.ShowColumns.prototype.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 []; - } -}; - -yy.ShowIndex = function (params) { return yy.extend(this, params); } -yy.ShowIndex.prototype.toString = function() { - var s = K('SHOW')+' '+K('INDEX'); - if(this.table.tableid) s += ' '+K('FROM')+' '+this.table.tableid; - if(this.databaseid) s += ' '+K('FROM')+' '+this.databaseid; - return s; -} -yy.ShowIndex.prototype.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; -}; - -yy.ShowCreateTable = function (params) { return yy.extend(this, params); } -yy.ShowCreateTable.prototype.toString = function() { - var s = K('SHOW')+' '+K('CREATE')+' '+K('TABLE')+' '+L(this.table.tableid); - if(this.databaseid) s += ' '+K('FROM')+' '+L(this.databaseid); - return s; -} -yy.ShowCreateTable.prototype.execute = function (databaseid) { - var db = alasql.databases[this.databaseid || databaseid]; - var table = db.tables[this.table.tableid]; - var self = this; - if(table) { - var s = K('CREATE')+' '+K('TABLE')+' '+L(this.table.tableid)+' ('; - var ss = []; - if(table.columns) { - table.columns.forEach(function(col){ - var a = L(col.columnid)+' '+K(col.dbtypeid); - if(col.dbsize) a += '('+N(col.dbsize)+')'; - if(col.primarykey) a += ' '+K('PRIMARY')+' '+K('KEY'); - // TODO extend - ss.push(a); - }); - s += ss.join(', '); - }; - s += ')'; - return s; - } else { - throw new Error('There is no such table "'+this.table.tableid+'"'); - } -}; - - -/* -// -// SET for Alasql.js -// Date: 01.12.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.SetVariable = function (params) { return yy.extend(this, params); } -yy.SetVariable.prototype.toString = function() { - var s = K('SET')+' '; - if(typeof this.value != 'undefined') s += K(this.variable.toUpperCase())+' '+(this.value?'ON':'OFF'); - if(this.expression) s += '@' + L(this.variable)+' = '+this.expression.toString(); - return s; -} - -yy.SetVariable.prototype.execute = function (databaseid,params,cb) { -// console.log(this); - 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) { -// console.log(this.expression.toJavaScript('','', null)); - var res = new Function("params,alasql","return " - +this.expression.toJavaScript('','', null))(params,alasql); - if(alasql.declares[this.variable]) { - res = alasql.stdfn.CONVERT(res,alasql.declares[this.variable]); - } - if(this.props && this.props.length > 0) { - var fs = 'alasql.vars[\''+this.variable+'\']'; - fs += this.props.map(function(prop){ - if(typeof prop == 'string') { - return '[\''+prop+'\']'; - } else if(typeof prop == 'number') { - return '['+prop+']'; - } else { - // console.log('prop:',prop, prop.toJavaScript()); - return '['+prop.toJavaScript()+']'; -// } else { -// console.log(prop, typeof ); -// throw new Error('Wrong SET property'); - } - }).join(); -// console.log(fs); - new Function("value,alasql",fs +'=value')(res,alasql); - } else { - alasql.vars[this.variable] = res; - } - } - var res = 1; - if(cb) res=cb(res); - return res; -}; - - - -// Console functions -/* -alasql.con = { - results:{} -}; - -alasql.con.open = function(el) { - // For browser only - if (typeof exports === 'object') return; - - // Find parent element - el = el || document.getElementById('alasql-con') || document.getElementsByTagName('body'); - if(!el) {throw new Error('Cannot fid element for console.')} - - var conel = document.createElement('div'); - conel.style.width = "1000px"; - conel.style.height = "320px"; - - alasql.con.conel = conel; - - var lenta = document.createElement('div'); - lenta.style.width = "1000px"; - lenta.style.height = "200px"; - lenta.style.overflow = "scroll"; - alasql.con.lenta = lenta; - - var inpel = document.createElement('div'); - inpel.style.width = "1000px"; - inpel.style.height = "100px"; - inpel.style.contentEditable = true; - inpel.innerHTML = 'command '; - alasql.con.inpel = inpel; - - conel.appendChild(lenta); - conel.appendChild(inpel); - el.appendChild(conel); -}; - -alasql.con.clear = function() { - // For browser only - if (typeof exports === 'object') return; - - alasql.con.conel.innerHTML = ''; -}; - -alasql.con.close = function() { - // For browser only - if (typeof exports === 'object') return; - - alasql.con.conel.removeChild(alasql.con.lenta); - alasql.con.conel.removeChild(alasql.con.inel); - alasql.con.conel.parentElement.removeChild(conel); -}; - -alasql.con.log = function() { - // For browser only - if (typeof exports === 'object') { - console.log.bind(console).apply(this, arguments); - } else { - var s = '

'; - s += Array.prototype.slice.call(arguments, 0).map(function(arg){ - return arg.toString(); - }).join(' '); - s += '
'; - alasql.con.conel.innerHTML += s; - }; - -}; -*/ -alasql.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',sql); - - if(res instanceof Array) { - 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 += '

'+olduseid+'> '+alasql.pretty(sql)+'

'; - s += '
'+alasql.pretty(sql)+'
'; - } - - if(res instanceof Array) { - if(res.length == 0) { - s += '

[ ]

' - } else if(typeof res[0] != 'object' || res[0] instanceof Array) { - for(var i=0,ilen=res.length;i'; - } - } else { - s += loghtml(res); - } - } else { - s += loghtml(res); - } - el.innerHTML += s; - } -}; - -alasql.clear = function() { - var target = alasql.options.logtarget; - // For node other - if(typeof exports == 'object') { - target = 'console'; - }; - - if(target == 'console' || typeof exports == 'object') { - if(console.clear) { - console.clear(); - } else { - // Something todo in Node - } - } 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.write = function(s) { -// console.log('write',s); - var target = alasql.options.logtarget; - // For node other - if(typeof exports == 'object') { - target = 'console'; - }; - - if(target == 'console' || typeof exports == 'object') { - if(console.log) { - console.log(s); - } else { - // Something todo in Node - } - } 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; - } -} - -function loghtml(res) { -// console.log(res); - var s = ''; - if(typeof res == 'undefined') { - s += 'undefined'; - } else if(res instanceof Array) { - s += ''; - s += ''; - var cols = []; - for(colid in res[0]) { - cols.push(colid); - } - s += '
#'; - cols.forEach(function(colid){ - s += ''+colid; - }); - for(var i=0,ilen=res.length;i'; - } - // if () {} - - // if(typeof res == 'object') { - // s += '

'+JSON.stringify(res)+'

'; - // } else { - // } - return s; -}; - - - -function scrollTo(element, to, duration) { - if (duration <= 0) return; - var difference = to - element.scrollTop; - var perTick = difference / duration * 10; - - setTimeout(function() { - if (element.scrollTop==to) return; - element.scrollTop = element.scrollTop + perTick; - scrollTo(element, to, duration - 10); - }, 10); -} - -alasql.prompt = function(el, useidel, firstsql) { - if(typeof exports == 'object') { - throw new Error('The functionality of prompt is 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('

'+(Date.now()-tm)+' ms

'); - } catch (err) { - alasql.write('

'+olduseid+'> '+sql+'

'); - alasql.write('

'+err+'

'); - } - }; - - 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('

'+(Date.now()-tm)+' ms

'); - } catch (err) { - alasql.write('

'+olduseid+'> '+alasql.pretty(sql, false)+'

'); - alasql.write('

'+err+'

'); - } - el.focus(); -// console.log(el.getBoundingClientRect().top); - 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(); - } - } - - } -} - - - - - -/* -// -// Commit for Alasql.js -// Date: 01.12.2014 -// (c) 2014, Andrey Gershun -// -*/ -yy.BeginTransaction = function (params) { return yy.extend(this, params); } -yy.BeginTransaction.prototype.toString = function() { - return K('BEGIN')+' '+K('TRANSACTION'); -} - -yy.BeginTransaction.prototype.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; -}; - -yy.CommitTransaction = function (params) { return yy.extend(this, params); } -yy.CommitTransaction.prototype.toString = function() { - return K('COMMIT')+' '+K('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); } -yy.RollbackTransaction.prototype.toString = function() { - return K('ROLLBACK')+' '+K('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; -}; +yy.RollbackTransaction = function (params) { return yy.extend(this, params); } +yy.RollbackTransaction.prototype.toString = function() { + return K('ROLLBACK')+' '+K('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; +}; // @@ -11022,209 +11033,209 @@ function XLSXLSX(X,filename, opts, cb, idx, query) { -/* -// -// HELP for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.Help = function (params) { return yy.extend(this, params); } -yy.Help.prototype.toString = function() { - var s = K('HELP'); - if(this.subject) s += ' '+L(this.subject); - return s; -} - -// Help string -helpdocs = [ - {command:'ALTER TABLE table RENAME TO table'}, - {command:'ALTER TABLE table ADD COLUMN column coldef'}, - {command:'ALTER TABLE table MODIFY COLUMN column coldef'}, - {command:'ALTER TABLE table RENAME COLUMN column TO column'}, - {command:'ALTER TABLE table DROP column'}, - {command:'ATTACH engine DATABASE database'}, - {command:'ASSERT value'}, - {command:'BEGIN [TRANSACTION]'}, - {command:'COMMIT [TRANSACTION]'}, - {command:'CREATE [engine] DATABASE [IF NOT EXISTS] database'}, - {command:'CREATE TABLE [IF NOT EXISTS] table (column definitions)'}, - {command:'DELETE FROM table [WHERE expression]'}, - {command:'DETACH DATABASE database'}, - {command:'DROP [engine] DATABASE [IF EXISTS] database'}, - {command:'DROP TABLE [IF EXISTS] table'}, - {command:'INSERT INTO table VALUES value,...'}, - {command:'INSERT INTO table DEFAULT VALUES'}, - {command:'INSERT INTO table SELECT select'}, - {command:'HELP [subject]'}, - {command:'ROLLBACK [TRANSACTION]'}, - {command:'SELECT [modificator] columns [INTO table] [FROM table,...] [[mode] JOIN [ON] [USING]] [WHERE ] [GROUP BY] [HAVING] [ORDER BY] '}, - {command:'SET option value'}, - {command:'SHOW [engine] DATABASES'}, - {command:'SHOW TABLES'}, - {command:'SHOW CREATE TABLE table'}, - {command:'UPDATE table SET column1 = expression1, ... [WHERE expression]'}, - {command:'USE [DATABASE] database'}, - {command:'expression'}, - {command:'See also http://github/agershun/alasq for more information'} -]; - -// execute -yy.Help.prototype.execute = function (databaseid, params, cb) { - var ss = []; - if(!this.subject) { - ss = helpdocs; - } else { - ss.push('See also http://github/agershun/alasq for more information'); - } - if(cb) ss = cb(ss); - return ss; -}; - - -/* -// -// HELP for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.Print = function (params) { return yy.extend(this, params); } -yy.Print.prototype.toString = function() { - var s = K('PRINT'); - if(this.statement) s += ' '+this.statement.toString(); - return s; -} - -/** - Print result of select statement or expression -*/ -yy.Print.prototype.execute = function (databaseid,params,cb) { -// console.log(this.url); - var res, s; - - if(this.statement) { - s = this.statement.execute(databaseid,params); - } else { - s = ''; - } - s = JSONtoString(s); - - console.log(s); - - if(cb) res = cb(res); - return res; -}; - - -/* -// -// HELP for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.Source = function (params) { return yy.extend(this, params); } -yy.Source.prototype.toString = function() { - var s = K('SOURCE'); - if(this.url) s += ' '+S('\''+this.url+'\''); - return s; -} - -// SOURCE FILE -yy.Source.prototype.execute = function (databaseid,params,cb) { -// console.log(this.url); - var res; - loadFile(this.url, !!cb, function(data){ -// console.log(data); -// res = 1; - res = alasql(data); - if(cb) res = cb(res); - return res; - }, function(err){ - throw err; - }); - return res; -}; - - -/* -// -// HELP for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.Require = function (params) { return yy.extend(this, params); } -yy.Require.prototype.toString = function() { - var s = K('REQUIRE'); - if(this.paths && this.paths.length > 0) { - s += this.paths.map(function(path){ - return path.toString() - }).join(','); - } - return s; -} - -/** - Attach plug-in for Alasql - */ -yy.Require.prototype.execute = function (databaseid,params,cb) { - var self = this; - var res = 0; - var ss = ''; -// console.log(this.paths); - if(this.paths.length > 0) { - this.paths.forEach(function(path){ - loadFile(path.value, !!cb, function(data){ - res++; -// console.log(res,self.paths.length); -// console.log(data); - ss += data; - if(reshttp://github/agershun/alasq for more information'} +]; + +// execute +yy.Help.prototype.execute = function (databaseid, params, cb) { + var ss = []; + if(!this.subject) { + ss = helpdocs; + } else { + ss.push('See also http://github/agershun/alasq for more information'); + } + if(cb) ss = cb(ss); + return ss; +}; + + +/* +// +// HELP for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +yy.Print = function (params) { return yy.extend(this, params); } +yy.Print.prototype.toString = function() { + var s = K('PRINT'); + if(this.statement) s += ' '+this.statement.toString(); + return s; +} + +/** + Print result of select statement or expression +*/ +yy.Print.prototype.execute = function (databaseid,params,cb) { +// console.log(this.url); + var res, s; + + if(this.statement) { + s = this.statement.execute(databaseid,params); + } else { + s = ''; + } + s = JSONtoString(s); + + console.log(s); + + if(cb) res = cb(res); + return res; +}; + + +/* +// +// HELP for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +yy.Source = function (params) { return yy.extend(this, params); } +yy.Source.prototype.toString = function() { + var s = K('SOURCE'); + if(this.url) s += ' '+S('\''+this.url+'\''); + return s; +} + +// SOURCE FILE +yy.Source.prototype.execute = function (databaseid,params,cb) { +// console.log(this.url); + var res; + loadFile(this.url, !!cb, function(data){ +// console.log(data); +// res = 1; + res = alasql(data); + if(cb) res = cb(res); + return res; + }, function(err){ + throw err; + }); + return res; +}; + + +/* +// +// HELP for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +yy.Require = function (params) { return yy.extend(this, params); } +yy.Require.prototype.toString = function() { + var s = K('REQUIRE'); + if(this.paths && this.paths.length > 0) { + s += this.paths.map(function(path){ + return path.toString() + }).join(','); + } + return s; +} + +/** + Attach plug-in for Alasql + */ +yy.Require.prototype.execute = function (databaseid,params,cb) { + var self = this; + var res = 0; + var ss = ''; +// console.log(this.paths); + if(this.paths.length > 0) { + this.paths.forEach(function(path){ + loadFile(path.value, !!cb, function(data){ + res++; +// console.log(res,self.paths.length); +// console.log(data); + ss += data; + if(res 2) { - var sql = process.argv[2]; - var parami = 3; - if(sql == '-f') { - console.log(sql); - sql = fs.readFile(sql).toString(); - parami++; - } - - var params = []; - for(var i=parami;i 2) { + var sql = process.argv[2]; + var parami = 3; + if(sql == '-f') { + console.log(sql); + sql = fs.readFile(sql).toString(); + parami++; + } + + var params = []; + for(var i=parami;i",right:$$[$0]});break;case 277:this.$=new yy.Op({left:$$[$0-4],op:"->",right:$$[$0-1]});break;case 279:this.$=new yy.Op({left:$$[$0-2],op:">",right:$$[$0]});break;case 280:this.$=new yy.Op({left:$$[$0-2],op:">=",right:$$[$0]});break;case 281:this.$=new yy.Op({left:$$[$0-2],op:"<",right:$$[$0]});break;case 282:this.$=new yy.Op({left:$$[$0-2],op:"<=",right:$$[$0]});break;case 283:this.$=new yy.Op({left:$$[$0-2],op:"=",right:$$[$0]});break;case 284:this.$=new yy.Op({left:$$[$0-2],op:"==",right:$$[$0]});break;case 285:this.$=new yy.Op({left:$$[$0-2],op:"===",right:$$[$0]});break;case 286:this.$=new yy.Op({left:$$[$0-2],op:"!=",right:$$[$0]});break;case 287:this.$=new yy.Op({left:$$[$0-2],op:"!==",right:$$[$0]});break;case 288:this.$=new yy.Op({left:$$[$0-2],op:"!===",right:$$[$0]});break;case 289:if(!yy.queries)yy.queries=[];this.$=new yy.Op({left:$$[$0-5],op:$$[$0-4],allsome:$$[$0-3],right:$$[$0-1],queriesidx:yy.queries.length});yy.queries.push($$[$0-1]);break;case 290:this.$=new yy.Op({left:$$[$0-5],op:$$[$0-4],allsome:$$[$0-3],right:$$[$0-1]});break;case 291:this.$=new yy.Op({left:$$[$0-2],op:"AND",right:$$[$0]});break;case 292:this.$=new yy.Op({left:$$[$0-2],op:"OR",right:$$[$0]});break;case 293:this.$=new yy.UniOp({op:"NOT",right:$$[$0]});break;case 294:this.$=new yy.UniOp({op:"-",right:$$[$0]});break;case 295:this.$=new yy.UniOp({op:"+",right:$$[$0]});break;case 296:this.$=new yy.UniOp({right:$$[$0-1]});break;case 297:if(!yy.queries)yy.queries=[];this.$=new yy.Op({left:$$[$0-4],op:"IN",right:$$[$0-1],queriesidx:yy.queries.length});yy.queries.push($$[$0-1]);break;case 298:if(!yy.queries)yy.queries=[];this.$=new yy.Op({left:$$[$0-5],op:"NOT IN",right:$$[$0-1],queriesidx:yy.queries.length});yy.queries.push($$[$0-1]);break;case 299:this.$=new yy.Op({left:$$[$0-4],op:"IN",right:$$[$0-1]});break;case 300:this.$=new yy.Op({left:$$[$0-5],op:"NOT IN",right:$$[$0-1]});break;case 301:this.$=new yy.Op({left:$$[$0-3],op:"IN",right:[]});break;case 302:this.$=new yy.Op({left:$$[$0-4],op:"NOT IN",right:[]});break;case 303:this.$=new yy.Op({left:$$[$0-2],op:"IN",right:$$[$0]});break;case 304:this.$=new yy.Op({left:$$[$0-3],op:"NOT IN",right:$$[$0]});break;case 305:this.$=new yy.Op({left:$$[$0-2],op:"BETWEEN",right:$$[$0]});break;case 306:this.$=new yy.Op({left:$$[$0-2],op:"NOT BETWEEN",right:$$[$0]});break;case 307:this.$=new yy.Op({op:"IS",left:$$[$0-2],right:$$[$0]});break;case 308:this.$=new yy.Convert({expression:$$[$0-2]});yy.extend(this.$,$$[$0]);break;case 309:case 310:this.$=$$[$0];break;case 311:this.$=$$[$0-1];break;case 318:this.$="ALL";break;case 319:this.$="SOME";break;case 320:this.$="ANY";break;case 321:this.$=new yy.Update({table:$$[$0-4],columns:$$[$0-2],where:$$[$0]});break;case 322:this.$=new yy.Update({table:$$[$0-2],columns:$$[$0]});break;case 325:this.$=new yy.SetColumn({columnid:$$[$0-2],expression:$$[$0]});break;case 326:this.$=new yy.Delete({table:$$[$0-2],where:$$[$0]});break;case 327:this.$=new yy.Delete({table:$$[$0]});break;case 328:this.$=new yy.Insert({into:$$[$0-2],values:$$[$0]});break;case 329:this.$=new yy.Insert({into:$$[$0-2],"default":true});break;case 330:this.$=new yy.Insert({into:$$[$0-5],columns:$$[$0-3],values:$$[$0]});break;case 331:this.$=new yy.Insert({into:$$[$0-1],select:$$[$0]});break;case 332:this.$=new yy.Insert({into:$$[$0-4],columns:$$[$0-2],select:$$[$0]});break;case 335:this.$=[$$[$0-1]];break;case 338:this.$=$$[$0-4];$$[$0-4].push($$[$0-1]);break;case 339:case 340:case 342:case 350:this.$=$$[$0-2];$$[$0-2].push($$[$0]);break;case 351:this.$=new yy.CreateTable({table:$$[$0-4]});yy.extend(this.$,$$[$0-5]);yy.extend(this.$,$$[$0-2]);break;case 352:this.$=new yy.CreateTable({table:$$[$0]});break;case 362:case 363:this.$={temporary:true};break;case 365:this.$={ifnotexists:true};break;case 366:this.$={columns:$$[$0-2],constraints:$$[$0]};break;case 367:this.$={columns:$$[$0]};break;case 368:this.$={as:$$[$0]};break;case 369:case 392:this.$=[$$[$0]];break;case 370:case 393:case 496:case 501:case 521:case 525:$$[$0-2].push($$[$0]);this.$=$$[$0-2];break;case 371:case 372:case 373:case 374:case 375:$$[$0].constraintid=$$[$0-1];this.$=$$[$0];break;case 378:this.$={type:"CHECK",expression:$$[$0-1]};break;case 379:this.$={type:"PRIMARY KEY",columns:$$[$0-1]};break;case 380:this.$={type:"FOREIGN KEY",columns:$$[$0-7],fktableid:$$[$0-4],fkcolumns:$$[$0-2]};break;case 394:this.$=new yy.ColumnDef({columnid:$$[$0-2]});yy.extend(this.$,$$[$0-1]);yy.extend(this.$,$$[$0]);break;case 395:this.$=new yy.ColumnDef({columnid:$$[$0-1]});yy.extend(this.$,$$[$0]);break;case 396:this.$=new yy.ColumnDef({columnid:$$[$0],dbtypeid:""});break;case 397:this.$={dbtypeid:$$[$0-5],dbsize:+$$[$0-3],dbprecision:+$$[$0-1]};break;case 398:this.$={dbtypeid:$$[$0-3],dbsize:+$$[$0-1]};break;case 399:this.$={dbtypeid:$$[$0]};break;case 400:this.$={dbtypeid:"ENUM",enumvalues:$$[$0-1]};break;case 401:this.$=undefined;break;case 403:yy.extend($$[$0-1],$$[$0]);this.$=$$[$0-1];break;case 405:this.$={primarykey:true};break;case 406:case 407:this.$={foreignkey:{tableid:$$[$0-3],columnid:$$[$0-1]}};break;case 408:this.$={auto_increment:true};break;case 409:this.$={identity:[$$[$0-3],$$[$0-1]]};break;case 410:this.$={identity:[1,1]};break;case 411:this.$={"default":$$[$0]};break;case 412:this.$={"null":true};break;case 413:this.$={notnull:true};break;case 414:this.$=$$[$0];break;case 415:this.$=new yy.DropTable({table:$$[$0]});yy.extend(this.$,$$[$0-1]);break;case 417:this.$={ifexists:true};break;case 418:this.$=new yy.AlterTable({table:$$[$0-3],renameto:$$[$0]});break;case 419:this.$=new yy.AlterTable({table:$$[$0-3],addcolumn:$$[$0]});break;case 420:this.$=new yy.AlterTable({table:$$[$0-3],modifycolumn:$$[$0]});break;case 421:this.$=new yy.AlterTable({table:$$[$0-5],renamecolumn:$$[$0-2],to:$$[$0]});break;case 422:this.$=new yy.AlterTable({table:$$[$0-3],dropcolumn:$$[$0]});break;case 423:this.$=new yy.AlterTable({table:$$[$0-2],renameto:$$[$0]});break;case 424:this.$=new yy.AttachDatabase({databaseid:$$[$0],engineid:$$[$0-2].toUpperCase()});break;case 425:this.$=new yy.AttachDatabase({databaseid:$$[$0-3],engineid:$$[$0-5].toUpperCase(),args:$$[$0-1]});break;case 426:this.$=new yy.AttachDatabase({databaseid:$$[$0-2],engineid:$$[$0-4].toUpperCase(),as:$$[$0]});break;case 427:this.$=new yy.AttachDatabase({databaseid:$$[$0-5],engineid:$$[$0-7].toUpperCase(),as:$$[$0],args:$$[$0-3]});break;case 428:this.$=new yy.DetachDatabase({databaseid:$$[$0]});break;case 429:this.$=new yy.CreateDatabase({databaseid:$$[$0]});yy.extend(this.$,$$[$0]);break;case 430:this.$=new yy.CreateDatabase({engineid:$$[$0-4].toUpperCase(),databaseid:$$[$0-1],as:$$[$0]});yy.extend(this.$,$$[$0-2]);break;case 431:this.$=new yy.CreateDatabase({engineid:$$[$0-7].toUpperCase(),databaseid:$$[$0-4],args:$$[$0-2],as:$$[$0]});yy.extend(this.$,$$[$0-5]);break;case 432:this.$=new yy.CreateDatabase({engineid:$$[$0-4].toUpperCase(),as:$$[$0],args:[$$[$0-1]]});yy.extend(this.$,$$[$0-2]);break;case 433:this.$=undefined;break;case 434:case 467:case 485:case 488:case 505:this.$=$$[$0-1];break;case 435:case 436:this.$=new yy.UseDatabase({databaseid:$$[$0]});break;case 437:this.$=new yy.DropDatabase({databaseid:$$[$0]});yy.extend(this.$,$$[$0-1]);break;case 438:case 439:this.$=new yy.DropDatabase({databaseid:$$[$0],engineid:$$[$0-3].toUpperCase()});yy.extend(this.$,$$[$0-1]);break;case 440:this.$=new yy.CreateIndex({indexid:$$[$0-5],table:$$[$0-3],columns:$$[$0-1]});break;case 441:this.$=new yy.CreateIndex({indexid:$$[$0-5],table:$$[$0-3],columns:$$[$0-1],unique:true});break;case 442:this.$=new yy.DropIndex({indexid:$$[$0]});break;case 443:this.$=new yy.ShowDatabases;break;case 444:this.$=new yy.ShowDatabases({like:$$[$0]});break;case 445:this.$=new yy.ShowDatabases({engineid:$$[$0-1].toUpperCase()});break;case 446:this.$=new yy.ShowDatabases({engineid:$$[$0-3].toUpperCase(),like:$$[$0]});break;case 447:this.$=new yy.ShowTables;break;case 448:this.$=new yy.ShowTables({like:$$[$0]});break;case 449:this.$=new yy.ShowTables({databaseid:$$[$0]});break;case 450:this.$=new yy.ShowTables({like:$$[$0],databaseid:$$[$0-2]});break;case 451:this.$=new yy.ShowColumns({table:$$[$0]});break;case 452:this.$=new yy.ShowColumns({table:$$[$0-2],databaseid:$$[$0]});break;case 453:this.$=new yy.ShowIndex({table:$$[$0]});break;case 454:this.$=new yy.ShowIndex({table:$$[$0-2],databaseid:$$[$0]});break;case 455:this.$=new yy.ShowCreateTable({table:$$[$0]});break;case 456:this.$=new yy.ShowCreateTable({table:$$[$0-2],databaseid:$$[$0]});break;case 457:this.$=new yy.CreateTable({table:$$[$0-5],view:true,select:$$[$0],viewcolumns:$$[$0-3]});yy.extend(this.$,$$[$0-6]);break;case 458:this.$=new yy.CreateTable({table:$$[$0-2],view:true,select:$$[$0]});break;case 459:this.$=new yy.DropTable({table:$$[$0],view:true});yy.extend(this.$,$$[$0-1]);break;case 460:this.$=new yy.Help({subject:$$[$0].value.toUpperCase()});break;case 461:this.$=new yy.Help;break;case 462:this.$=new yy.ExpressionStatement({expression:$$[$0]});break;case 463:this.$=new yy.Source({url:$$[$0].value});break;case 464:this.$=new yy.Assert({value:$$[$0]});break;case 465:this.$=new yy.Assert({value:$$[$0].value});break;case 466:this.$=new yy.Assert({value:$$[$0],message:$$[$0-2]});break;case 468:case 479:case 481:this.$=$$[$0].value;break;case 469:case 477:this.$=+$$[$0].value;break;case 470:this.$=!!$$[$0].value;break;case 478:this.$=""+$$[$0].value;break;case 484:this.$=$$[$0-1];break;case 486:case 489:this.$=$$[$0-2];break;case 487:this.$={};break;case 490:this.$=[];break;case 491:yy.extend($$[$0-2],$$[$0]);this.$=$$[$0-2];break;case 493:this.$={};this.$[$$[$0-2].substr(1,$$[$0-2].length-2)]=$$[$0];break;case 494:case 495:this.$={};this.$[$$[$0-2]]=$$[$0];break;case 498:this.$=new yy.SetVariable({variable:$$[$0-1].toLowerCase(),value:$$[$0]});break;case 499:this.$=new yy.SetVariable({variable:$$[$0-2],expression:$$[$0]});break;case 500:this.$=new yy.SetVariable({variable:$$[$0-3],props:$$[$0-2],expression:$$[$0]});break;case 506:this.$=true;break;case 507:this.$=false;break;case 508:this.$=new yy.CommitTransaction;break;case 509:this.$=new yy.RollbackTransaction;break;case 510:this.$=new yy.BeginTransaction;break;case 511: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 512:this.$=new yy.If({expression:$$[$0-1],thenstat:$$[$0]});break;case 513:this.$=$$[$0];break;case 514: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 515:this.$=new yy.Continue;break;case 516:this.$=new yy.Break;break;case 517:this.$=new yy.BeginEnd({statements:$$[$0-1]});break;case 518:case 519:this.$=new yy.Print({statement:$$[$0]});break;case 520:this.$=new yy.Require({paths:$$[$0]});break;case 523:this.$=new yy.Declare({declares:$$[$0]});break;case 526:this.$={variable:$$[$0-1]};yy.extend(this.$,$$[$0]);break;case 527:this.$={variable:$$[$0-2]};yy.extend(this.$,$$[$0]);break;case 528:this.$={variable:$$[$0-3],expression:$$[$0]};yy.extend(this.$,$$[$0-2]);break;case 529:this.$={variable:$$[$0-4],expression:$$[$0]};yy.extend(this.$,$$[$0-2]);break;case 530:this.$=new yy.TruncateTable({table:$$[$0]});break;case 531: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 532:case 533:this.$={into:$$[$0]};break;case 535:this.$={on:$$[$0]};break;case 540:this.$={matched:true,action:$$[$0]};break;case 541:this.$={matched:true,expr:$$[$0-2],action:$$[$0]};break;case 542:this.$={"delete":true};break;case 543:this.$={update:$$[$0]};break;case 544:case 545:this.$={matched:false,bytarget:true,action:$$[$0]};break;case 546:case 547:this.$={matched:false,bytarget:true,expr:$$[$0-2],action:$$[$0]};break;case 548:this.$={matched:false,bysource:true,action:$$[$0]};break;case 549:this.$={matched:false,bysource:true,expr:$$[$0-2],action:$$[$0]};break;case 550:this.$={insert:true,values:$$[$0]};break;case 551:this.$={insert:true,values:$$[$0],columns:$$[$0-3]};break;case 552:this.$={insert:true,defaultvalues:true};break;case 553:this.$={insert:true,defaultvalues:true,columns:$$[$0-3]};break;case 555:this.$={output:{columns:$$[$0]}};break;case 556:this.$={output:{columns:$$[$0-3],intovar:$$[$0]}};break;case 557:this.$={output:{columns:$$[$0-2],intotable:$$[$0]}};break;case 558:this.$={output:{columns:$$[$0-5],intotable:$$[$0-3],intocolumns:$$[$0-1]}};break}},table:[o([8,9,11],$V0,{6:1,7:2,10:3,12:4,16:5,17:7,18:8,19:9,20:10,21:11,22:12,23:13,24:14,25:15,26:16,27:17,28:18,29:19,30:20,31:21,32:22,33:23,34:24,35:25,36:26,37:27,38:28,39:29,40:30,41:31,42:32,43:33,44:34,46:36,47:37,48:38,49:39,50:40,51:41,52:42,53:43,54:44,55:45,56:46,57:47,58:48,66:59,74:79,13:$V1,45:$V2,59:$V3,80:$V4,165:$V5,237:$V6,238:$V7,241:$V8,242:$V9,250:$Va,263:$Vb,292:$Vc,294:$Vd,295:$Ve,299:$Vf,301:$Vg,303:$Vh,304:$Vi,309:$Vj,311:$Vk,312:$Vl,328:$Vm,330:$Vn,331:$Vo,333:$Vp,334:$Vq,335:$Vr,336:$Vs,337:$Vt,339:$Vu,342:$Vv,343:$Vw}),{1:[3]},{8:[1,81],9:$Vx,11:$Vy},o($Vz,[2,6]),o($Vz,[2,7]),o($VA,[2,10]),o($Vz,$V0,{16:5,17:7,18:8,19:9,20:10,21:11,22:12,23:13,24:14,25:15,26:16,27:17,28:18,29:19,30:20,31:21,32:22,33:23,34:24,35:25,36:26,37:27,38:28,39:29,40:30,41:31,42:32,43:33,44:34,46:36,47:37,48:38,49:39,50:40,51:41,52:42,53:43,54:44,55:45,56:46,57:47,58:48,66:59,74:79,10:84,14:[1,85],45:$V2,59:$V3,80:$V4,165:$V5,237:$V6,238:$V7,241:$V8,242:$V9,250:$Va,263:$Vb,292:$Vc,294:$Vd,295:$Ve,299:$Vf,301:$Vg,303:$Vh,304:$Vi,309:$Vj,311:$Vk,312:$Vl,328:$Vm,330:$Vn,331:$Vo,333:$Vp,334:$Vq,335:$Vr,336:$Vs,337:$Vt,339:$Vu,342:$Vv,343:$Vw}),o($VA,[2,12]),o($VA,[2,13]),o($VA,[2,14]),o($VA,[2,15]),o($VA,[2,16]),o($VA,[2,17]),o($VA,[2,18]),o($VA,[2,19]),o($VA,[2,20]),o($VA,[2,21]),o($VA,[2,22]),o($VA,[2,23]),o($VA,[2,24]),o($VA,[2,25]),o($VA,[2,26]),o($VA,[2,27]),o($VA,[2,28]),o($VA,[2,29]),o($VA,[2,30]),o($VA,[2,31]),o($VA,[2,32]),o($VA,[2,33]),o($VA,[2,34]),o($VA,[2,35]),o($VA,[2,36]),o($VA,[2,37]),o($VA,[2,38]),o($VA,[2,39]),o($VA,[2,40]),o($VA,[2,41]),o($VA,[2,42]),o($VA,[2,43]),o($VA,[2,44]),o($VA,[2,45]),o($VA,[2,46]),o($VA,[2,47]),o($VA,[2,48]),o($VA,[2,49]),o($VA,[2,50]),o($VA,[2,51]),o($VA,[2,52]),o($VA,[2,53]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:86,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{251:[1,141]},{3:142,4:$VB,5:$VC},{3:144,4:$VB,5:$VC,78:[1,146],86:[1,145],251:[1,147],300:[1,143],308:[1,148]},{192:$V71,340:149,341:150},{97:[1,152]},{300:[1,153]},{3:155,4:$VB,5:$VC,86:[1,156],251:[1,157],300:[1,154],308:[1,158]},o($V81,[2,333],{243:159,91:[1,160]}),{251:[1,161]},o($V91,[2,75],{67:162,91:[1,163]}),{3:173,4:$VB,5:$VC,64:$Va1,91:[1,166],92:168,93:170,94:169,95:171,96:$Vb1,99:165,105:172,192:$Vc1,194:$VZ,195:$V_,196:$V$,197:$V01,344:164},{3:178,4:$VB,5:$VC,60:176,62:177},{3:182,4:$VB,5:$VC,86:[1,183],250:[1,179],305:[1,181],306:[1,184],307:[1,180]},{251:[1,185]},o([9,11,201],$V0,{10:3,12:4,16:5,17:7,18:8,19:9,20:10,21:11,22:12,23:13,24:14,25:15,26:16,27:17,28:18,29:19,30:20,31:21,32:22,33:23,34:24,35:25,36:26,37:27,38:28,39:29,40:30,41:31,42:32,43:33,44:34,46:36,47:37,48:38,49:39,50:40,51:41,52:42,53:43,54:44,55:45,56:46,57:47,58:48,66:59,74:79,7:187,13:$V1,45:$V2,59:$V3,80:$V4,165:$V5,237:$V6,238:$V7,241:$V8,242:$V9,250:$Va,263:$Vb,292:$Vc,294:$Vd,295:$Ve,299:$Vf,301:$Vg,303:$Vh,304:$Vi,309:$Vj,311:$Vk,312:$Vl,328:$Vm,329:[1,186],330:$Vn,331:$Vo,333:$Vp,334:$Vq,335:$Vr,336:$Vs,337:$Vt,339:$Vu,342:$Vv,343:$Vw}),{329:[1,188]},{329:[1,189]},{3:191,4:$VB,5:$VC,300:[1,190]},{3:193,4:$VB,5:$VC,92:192},o($VA,[2,461],{152:194,96:$VE,190:$VV}),o($Vd1,[2,212]),{96:$VE,152:195,190:$VV},{3:207,4:$VB,5:$VC,89:200,93:205,94:204,96:[1,198],151:$VF,152:201,158:202,159:203,163:196,170:197,171:$Ve1,188:$VT,189:$VU,190:$VV,191:$VW,192:$Vf1,194:$VZ,195:$V_,196:$V$,197:$V01,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:208,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($VA,[2,515]),o($VA,[2,516]),{3:106,4:$VB,5:$VC,33:209,49:104,64:$VD,66:59,74:79,80:$V4,89:92,93:88,94:96,95:97,96:$VE,121:211,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,310:210,313:126,314:$V51,318:$V61},{96:$VE,152:213,190:$VV,338:212},{3:214,4:$VB,5:$VC,192:[1,215]},o($Vg1,$Vh1,{76:219,75:[1,216],78:[1,217],79:[1,218],88:$Vi1}),o($Vj1,[2,63],{81:[1,221],82:[1,222],83:[1,223],84:[1,224],85:[1,225],86:[1,226],87:[1,227]}),{1:[2,3]},o($Vz,$V0,{16:5,17:7,18:8,19:9,20:10,21:11,22:12,23:13,24:14,25:15,26:16,27:17,28:18,29:19,30:20,31:21,32:22,33:23,34:24,35:25,36:26,37:27,38:28,39:29,40:30,41:31,42:32,43:33,44:34,46:36,47:37,48:38,49:39,50:40,51:41,52:42,53:43,54:44,55:45,56:46,57:47,58:48,66:59,74:79,10:228,45:$V2,59:$V3,80:$V4,165:$V5,237:$V6,238:$V7,241:$V8,242:$V9,250:$Va,263:$Vb,292:$Vc,294:$Vd,295:$Ve,299:$Vf,301:$Vg,303:$Vh,304:$Vi,309:$Vj,311:$Vk,312:$Vl,328:$Vm,330:$Vn,331:$Vo,333:$Vp,334:$Vq,335:$Vr,336:$Vs,337:$Vt,339:$Vu,342:$Vv,343:$Vw}),o($Vz,$V0,{16:5,17:7,18:8,19:9,20:10,21:11,22:12,23:13,24:14,25:15,26:16,27:17,28:18,29:19,30:20,31:21,32:22,33:23,34:24,35:25,36:26,37:27,38:28,39:29,40:30,41:31,42:32,43:33,44:34,46:36,47:37,48:38,49:39,50:40,51:41,52:42,53:43,54:44,55:45,56:46,57:47,58:48,66:59,74:79,10:229,45:$V2,59:$V3,80:$V4,165:$V5,237:$V6,238:$V7,241:$V8,242:$V9,250:$Va,263:$Vb,292:$Vc,294:$Vd,295:$Ve,299:$Vf,301:$Vg,303:$Vh,304:$Vi,309:$Vj,311:$Vk,312:$Vl,328:$Vm,330:$Vn,331:$Vo,333:$Vp,334:$Vq,335:$Vr,336:$Vs,337:$Vt,339:$Vu,342:$Vv,343:$Vw}),o($Vz,[2,8]),{15:[1,230]},o($VA,$V0,{16:5,17:7,18:8,19:9,20:10,21:11,22:12,23:13,24:14,25:15,26:16,27:17,28:18,29:19,30:20,31:21,32:22,33:23,34:24,35:25,36:26,37:27,38:28,39:29,40:30,41:31,42:32,43:33,44:34,46:36,47:37,48:38,49:39,50:40,51:41,52:42,53:43,54:44,55:45,56:46,57:47,58:48,66:59,74:79,10:231,224:251,45:$V2,59:$V3,80:$V4,154:$Vk1,165:$V5,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1,237:$V6,238:$V7,241:$V8,242:$V9,250:$Va,263:$Vb,292:$Vc,294:$Vd,295:$Ve,299:$Vf,301:$Vg,303:$Vh,304:$Vi,309:$Vj,311:$Vk,312:$Vl,328:$Vm,330:$Vn,331:$Vo,333:$Vp,334:$Vq,335:$Vr,336:$Vs,337:$Vt,339:$Vu,342:$Vv,343:$Vw}),o($Vd1,[2,194]),o($Vd1,[2,195]),o($Vd1,[2,196]),o($Vd1,[2,197]),o($Vd1,[2,198]),o($Vd1,[2,199]),o($Vd1,[2,200]),o($Vd1,[2,201]),o($Vd1,[2,202]),o($Vd1,[2,203]),o($Vd1,[2,204]),o($Vd1,[2,205]),o($Vd1,[2,206]),o($Vd1,[2,207]),o($Vd1,[2,208]),o($Vd1,[2,209]),{3:106,4:$VB,5:$VC,33:260,49:104,64:$VD,66:59,74:79,80:$V4,89:92,93:88,94:96,95:97,96:$VE,121:261,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($Vd1,[2,211]),{64:[1,262]},o($Vd1,$VL1,{64:$VM1,106:[1,264]}),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:265,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:266,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:267,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($Vd1,[2,189]),o([4,5,8,9,11,45,59,61,63,64,65,80,90,91,96,97,102,104,112,113,114,115,116,117,118,119,124,125,134,135,136,137,138,141,142,144,146,149,150,151,154,165,166,167,169,178,179,180,181,182,183,184,185,186,188,189,190,191,192,193,194,195,196,197,198,201,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,226,227,228,229,231,232,233,234,237,238,241,242,246,250,257,258,259,263,274,275,278,279,291,292,294,295,299,301,303,304,309,311,312,314,318,320,322,328,330,331,333,334,335,336,337,339,342,343,355],[2,248]),o($VN1,[2,249]),o($VN1,[2,250]),o($VN1,$VO1),o($VN1,[2,252]),o($VN1,[2,253]),{3:268,4:$VB,5:$VC},{3:269,4:$VB,5:$VC},o($VP1,[2,258]),o($VP1,[2,259]),{3:270,4:$VB,5:$VC,64:$VQ1,89:273,94:275,96:$VE,151:$VF,152:272,158:274,188:$VT,189:$VU,190:$VV,194:$VZ,195:$V_,196:$V$,197:$V01,313:276,318:$V61},{64:[1,277]},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:278,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,199:279,202:280,203:$VR1,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{64:[1,282]},{64:[1,283]},o($VS1,[2,472]),{3:298,4:$VB,5:$VC,64:$VT1,89:290,93:296,94:295,96:$VE,151:$VF,152:291,155:293,158:292,159:294,163:288,188:$VT,189:$VU,190:$VV,191:$VW,192:$Vf1,194:$VZ,195:$V_,196:$V$,197:$V01,313:126,314:$V51,315:284,316:287,317:289,318:$V61,321:285,322:[1,286]},{3:299,4:$VB,5:$VC,93:300},{64:[2,235]},{64:[2,236]},{64:[2,237]},{64:[2,238]},{64:[2,239]},{64:[2,240]},{64:[2,241]},{64:[2,242]},{64:[2,243]},o($VU1,[2,1]),o($VU1,[2,2]),{3:306,4:$VB,5:$VC,96:$VV1,151:$VW1,319:301,320:[1,302],323:303},{3:193,4:$VB,5:$VC,92:307},{300:[1,308]},o($V81,$VX1,{252:309,263:$VY1}),{300:[1,311]},{3:312,4:$VB,5:$VC},{86:[1,313]},o($V81,$VX1,{252:314,263:$VY1}),o($V81,$VX1,{252:315,263:$VY1}),o($VA,[2,523],{61:[1,316]}),o($VZ1,[2,524]),{3:317,4:$VB,5:$VC},{3:193,4:$VB,5:$VC,92:318},{3:319,4:$VB,5:$VC},o($V81,$V_1,{293:320,263:$V$1}),{300:[1,322]},{3:323,4:$VB,5:$VC},o($V81,$V_1,{293:324,263:$V$1}),o($V81,$V_1,{293:325,263:$V$1}),{3:193,4:$VB,5:$VC,92:326},o($V81,[2,334]),{3:193,4:$VB,5:$VC,92:327},o($V02,[2,83],{68:328,97:[1,329]}),{3:173,4:$VB,5:$VC,92:330,93:331,94:332,95:333,96:[1,334],192:$Vc1,194:$VZ,195:$V_,196:$V$,197:$V01},{122:[1,336],345:335},{122:[2,532]},{3:173,4:$VB,5:$VC,64:$Va1,92:168,93:170,94:169,95:171,96:$Vb1,99:337,105:172,192:$Vc1,194:$VZ,195:$V_,196:$V$,197:$V01},{33:338,66:59,74:79,80:$V4},o($V12,[2,95],{3:339,4:$VB,5:$VC,63:[1,340]}),o($V12,[2,98],{3:341,4:$VB,5:$VC,63:[1,342]}),o($V12,[2,99],{3:343,4:$VB,5:$VC,63:[1,344]}),o($V12,[2,102],{3:345,4:$VB,5:$VC,63:[1,346]}),o($V12,[2,105],{3:347,4:$VB,5:$VC,63:[1,348]}),o([4,5,8,9,11,61,63,65,97,102,104,112,113,114,115,116,117,118,119,120,122,124,125,135,136,137,138,144,201,205],$V22,{64:$VM1,106:$V32}),{3:270,4:$VB,5:$VC},o([4,5,8,9,11,61,63,65,102,104,112,113,114,115,116,117,118,119,120,122,124,125,135,136,137,138,144,201,205],[2,108]),{33:350,61:[1,351],66:59,74:79,80:$V4},o($V42,[2,56]),{63:[1,352]},{251:[1,353]},{97:[1,354]},o($VA,[2,443],{206:[1,355]}),{305:[1,356]},{97:[1,357]},o($VA,[2,447],{97:[1,359],206:[1,358]}),{3:193,4:$VB,5:$VC,92:360},o($VA,[2,510]),{9:$Vx,11:$Vy,201:[1,361]},o($VA,[2,508]),o($VA,[2,509]),{3:362,4:$VB,5:$VC},o($VA,[2,436]),{238:[1,363]},o([8,9,11,63,64,80,97,124,201,205,238,244,246,292,295,296,297,298],$V22,{106:$V32}),o($VA,[2,460]),o($VA,[2,463]),o($VA,[2,464]),o($VA,[2,465]),o($VA,$VO1,{61:[1,364]}),{64:$VQ1,89:273,94:275,96:$VE,151:$VF,152:272,158:274,188:$VT,189:$VU,190:$VV,194:$VZ,195:$V_,196:$V$,197:$V01,313:276,318:$V61},o($V52,[2,219]),o($V52,[2,220]),o($V52,[2,221]),o($V52,[2,222]),o($V52,[2,223]),o($V52,[2,224]),o($V52,[2,225]),{64:$VM1},o($VA,$V0,{16:5,17:7,18:8,19:9,20:10,21:11,22:12,23:13,24:14,25:15,26:16,27:17,28:18,29:19,30:20,31:21,32:22,33:23,34:24,35:25,36:26,37:27,38:28,39:29,40:30,41:31,42:32,43:33,44:34,46:36,47:37,48:38,49:39,50:40,51:41,52:42,53:43,54:44,55:45,56:46,57:47,58:48,66:59,74:79,224:251,10:365,45:$V2,59:$V3,80:$V4,154:$Vk1,165:$V5,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1,237:$V6,238:$V7,241:$V8,242:$V9,250:$Va,263:$Vb,292:$Vc,294:$Vd,295:$Ve,299:$Vf,301:$Vg,303:$Vh,304:$Vi,309:$Vj,311:$Vk,312:$Vl,328:$Vm,330:$Vn,331:$Vo,333:$Vp,334:$Vq,335:$Vr,336:$Vs,337:$Vt,339:$Vu,342:$Vv,343:$Vw}),o($VA,[2,518]),o($VA,[2,519]),o($VA,[2,462],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),o($VA,[2,520],{61:[1,366]}),o($VZ1,[2,522]),{120:[1,368],324:367,327:[1,369]},{3:370,4:$VB,5:$VC},o($Vg1,$Vh1,{76:371,88:$Vi1}),o($Vg1,$Vh1,{76:372,88:$Vi1}),o($Vg1,$Vh1,{76:373,88:$Vi1}),{3:106,4:$VB,5:$VC,49:104,64:$VD,77:374,89:92,93:88,94:96,95:97,96:$VE,121:376,147:375,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{64:[1,378],89:377,151:$VF},o($Vj1,[2,64]),o($Vj1,[2,65]),o($Vj1,[2,66]),o($Vj1,[2,67]),o($Vj1,[2,68]),o($Vj1,[2,69]),o($Vj1,[2,70]),o($Vz,[2,4]),o($Vz,[2,5]),o($Vz,$V0,{16:5,17:7,18:8,19:9,20:10,21:11,22:12,23:13,24:14,25:15,26:16,27:17,28:18,29:19,30:20,31:21,32:22,33:23,34:24,35:25,36:26,37:27,38:28,39:29,40:30,41:31,42:32,43:33,44:34,46:36,47:37,48:38,49:39,50:40,51:41,52:42,53:43,54:44,55:45,56:46,57:47,58:48,66:59,74:79,10:379,45:$V2,59:$V3,80:$V4,165:$V5,237:$V6,238:$V7,241:$V8,242:$V9,250:$Va,263:$Vb,292:$Vc,294:$Vd,295:$Ve,299:$Vf,301:$Vg,303:$Vh,304:$Vi,309:$Vj,311:$Vk,312:$Vl,328:$Vm,330:$Vn,331:$Vo,333:$Vp,334:$Vq,335:$Vr,336:$Vs,337:$Vt,339:$Vu,342:$Vv,343:$Vw}),o($Vz,[2,512],{332:380,205:[1,381]}),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:382,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:383,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:384,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:385,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:386,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:387,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:388,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:389,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:390,4:$VB,5:$VC,64:[1,392],89:391,93:393,151:$VF},o($V62,[2,312],{156:87,93:88,157:89,155:90,153:91,89:92,158:93,152:94,159:95,94:96,95:97,160:98,161:99,162:100,163:101,164:102,49:104,172:105,3:106,313:126,121:394,4:$VB,5:$VC,64:$VD,96:$VE,151:$VF,154:$VG,165:$V5,166:$VH,167:$VI,169:$VJ,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,314:$V51,318:$V61}),o($V62,[2,313],{156:87,93:88,157:89,155:90,153:91,89:92,158:93,152:94,159:95,94:96,95:97,160:98,161:99,162:100,163:101,164:102,49:104,172:105,3:106,313:126,121:395,4:$VB,5:$VC,64:$VD,96:$VE,151:$VF,154:$VG,165:$V5,166:$VH,167:$VI,169:$VJ,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,314:$V51,318:$V61}),o($V62,[2,314],{156:87,93:88,157:89,155:90,153:91,89:92,158:93,152:94,159:95,94:96,95:97,160:98,161:99,162:100,163:101,164:102,49:104,172:105,3:106,313:126,121:396,4:$VB,5:$VC,64:$VD,96:$VE,151:$VF,154:$VG,165:$V5,166:$VH,167:$VI,169:$VJ,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,314:$V51,318:$V61}),o($V62,[2,315],{156:87,93:88,157:89,155:90,153:91,89:92,158:93,152:94,159:95,94:96,95:97,160:98,161:99,162:100,163:101,164:102,49:104,172:105,3:106,313:126,121:397,4:$VB,5:$VC,64:$VD,96:$VE,151:$VF,154:$VG,165:$V5,166:$VH,167:$VI,169:$VJ,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,314:$V51,318:$V61}),o($V62,[2,316],{156:87,93:88,157:89,155:90,153:91,89:92,158:93,152:94,159:95,94:96,95:97,160:98,161:99,162:100,163:101,164:102,49:104,172:105,3:106,313:126,121:398,4:$VB,5:$VC,64:$VD,96:$VE,151:$VF,154:$VG,165:$V5,166:$VH,167:$VI,169:$VJ,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,314:$V51,318:$V61}),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:399,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:400,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($V62,[2,317],{156:87,93:88,157:89,155:90,153:91,89:92,158:93,152:94,159:95,94:96,95:97,160:98,161:99,162:100,163:101,164:102,49:104,172:105,3:106,313:126,121:401,4:$VB,5:$VC,64:$VD,96:$VE,151:$VF,154:$VG,165:$V5,166:$VH,167:$VI,169:$VJ,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,314:$V51,318:$V61}),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:402,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:403,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{79:[1,405],225:404,235:[1,406],236:[1,407]},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:408,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:409,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:298,4:$VB,5:$VC,64:[1,410],93:413,155:412,192:$V72,230:411},{229:[1,415]},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:416,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:417,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:418,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{4:$V82,168:419,288:$V92},{65:[1,422]},{65:[1,423],154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},{3:106,4:$VB,5:$VC,49:104,64:$VD,75:[1,425],79:[1,426],89:92,93:88,94:96,95:97,96:$VE,121:424,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,65:[1,428],89:92,93:88,94:96,95:97,96:$VE,121:429,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,187:427,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:430,4:$VB,5:$VC,81:$Va2,154:[1,432]},o([4,5,8,9,11,45,59,61,63,65,80,91,96,97,102,104,112,113,114,115,116,117,118,119,124,125,134,135,136,137,138,141,142,144,149,150,151,165,190,201,203,204,205,214,215,216,217,218,219,220,221,222,223,226,227,228,229,231,232,234,237,238,241,242,250,263,292,294,295,299,301,303,304,309,311,312,328,330,331,333,334,335,336,337,339,342,343,355],[2,293],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,233:$VJ1}),o($Vb2,[2,294],{224:251,154:$Vk1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1}),o($Vb2,[2,295],{224:251,154:$Vk1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1}),o($VP1,[2,256]),o($VP1,[2,257]),o([4,5,8,9,11,45,59,61,63,65,80,91,96,97,102,104,112,113,114,115,116,117,118,119,120,122,124,125,134,135,136,137,138,141,142,144,149,150,151,154,165,190,201,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,226,227,228,229,231,232,233,234,237,238,241,242,250,263,292,294,295,299,301,303,304,309,311,312,328,330,331,333,334,335,336,337,339,342,343,355],[2,254]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:433,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($VS1,[2,468]),o($VS1,[2,469]),o($VS1,[2,470]),o($VS1,[2,471]),o($VS1,[2,473]),{33:434,66:59,74:79,80:$V4},{154:$Vk1,199:435,202:280,203:$VR1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},{200:436,201:$Vc2,202:437,203:$VR1,205:$Vd2},o($Ve2,[2,263]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:439,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:440,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{4:$V82,168:441,288:$V92},o($VS1,[2,474]),{61:[1,443],322:[1,442]},o($VS1,[2,490]),o($Vf2,[2,497]),o($Vg2,[2,475]),o($Vg2,[2,476]),o($Vg2,[2,477]),o($Vg2,[2,478]),o($Vg2,[2,479]),o($Vg2,[2,480]),o($Vg2,[2,481]),o($Vg2,[2,482]),o($Vg2,[2,483]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:444,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($VS1,$VL1,{64:$VM1,106:$Vh2}),o($Vd1,[2,213],{64:$VM1}),o($Vd1,[2,214]),{61:[1,447],320:[1,446]},o($VS1,[2,487]),o($Vi2,[2,492]),{195:[1,448]},{195:[1,449]},{195:[1,450]},{292:[1,454],295:[1,451],297:[1,452],298:[1,453]},{3:455,4:$VB,5:$VC},{3:456,4:$VB,5:$VC},{228:[1,457]},o($Vj2,$VX1,{252:458,263:$VY1}),{120:[1,459]},{3:460,4:$VB,5:$VC},{3:193,4:$VB,5:$VC,92:461},{3:193,4:$VB,5:$VC,92:462},{192:$V71,341:463},{4:$V82,63:[1,465],168:464,288:$V92},o($VA,[2,327],{124:[1,466]}),o($VA,[2,428]),{3:467,4:$VB,5:$VC},{193:[1,468]},o($Vj2,$V_1,{293:469,263:$V$1}),o($VA,[2,442]),{3:193,4:$VB,5:$VC,92:470},{3:193,4:$VB,5:$VC,92:471},{33:475,64:[1,474],66:59,74:79,80:$V4,244:[1,472],246:[1,473]},{296:[1,476]},o($Vk2,[2,145],{69:477,124:[1,478]}),{3:173,4:$VB,5:$VC,64:$Va1,92:168,93:170,94:169,95:171,96:$Vb1,98:479,99:480,105:172,192:$Vc1,194:$VZ,195:$V_,196:$V$,197:$V01},o($V91,[2,76]),o($V91,[2,77]),o($V91,[2,78]),o($V91,[2,79]),o($V91,[2,80]),{120:[1,482],346:481},{3:173,4:$VB,5:$VC,64:$Va1,92:168,93:170,94:169,95:171,96:$Vb1,99:483,105:172,192:$Vc1,194:$VZ,195:$V_,196:$V$,197:$V01},{122:[2,533]},{65:[1,484]},o($V12,[2,93]),{3:485,4:$VB,5:$VC},o($V12,[2,96]),{3:486,4:$VB,5:$VC},o($V12,[2,100]),{3:487,4:$VB,5:$VC},o($V12,[2,103]),{3:488,4:$VB,5:$VC},o($V12,[2,106]),{3:489,4:$VB,5:$VC},{3:490,4:$VB,5:$VC},o($VA,[2,54]),{3:178,4:$VB,5:$VC,62:491},{64:[1,492]},{3:193,4:$VB,5:$VC,92:493},{3:193,4:$VB,5:$VC,92:494},{96:$VE,152:495,190:$VV},o($VA,[2,445],{206:[1,496]}),{3:193,4:$VB,5:$VC,92:497},{96:$VE,152:498,190:$VV},{3:499,4:$VB,5:$VC},o($VA,[2,530]),o($VA,[2,517]),o($VA,[2,435]),{3:503,4:$VB,5:$VC,155:502,239:500,240:501},{163:504,192:$Vf1,313:126,314:$V51,318:$V61},o($VA,[2,514]),{96:$VE,152:505,190:$VV},o($VA,[2,498]),o($VA,[2,506]),o($VA,[2,507]),{213:[1,508],218:[1,506],325:507},{3:106,4:$VB,5:$VC,49:104,64:$VD,77:509,89:92,93:88,94:96,95:97,96:$VE,121:376,147:375,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,77:510,89:92,93:88,94:96,95:97,96:$VE,121:376,147:375,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,77:511,89:92,93:88,94:96,95:97,96:$VE,121:376,147:375,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($Vl2,[2,62],{61:$Vm2}),o($Vn2,$Vo2,{148:513,149:$Vp2,150:$Vq2}),o($Vr2,[2,186],{224:251,3:517,152:519,4:$VB,5:$VC,63:[1,516],96:$VE,151:[1,518],154:$Vk1,190:$VV,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),o($Vg1,[2,71],{90:[1,520]}),{89:521,151:$VF},o($Vz,[2,9]),o($VA,[2,511]),o($VA,$V0,{16:5,17:7,18:8,19:9,20:10,21:11,22:12,23:13,24:14,25:15,26:16,27:17,28:18,29:19,30:20,31:21,32:22,33:23,34:24,35:25,36:26,37:27,38:28,39:29,40:30,41:31,42:32,43:33,44:34,46:36,47:37,48:38,49:39,50:40,51:41,52:42,53:43,54:44,55:45,56:46,57:47,58:48,66:59,74:79,10:522,45:$V2,59:$V3,80:$V4,165:$V5,237:$V6,238:$V7,241:$V8,242:$V9,250:$Va,263:$Vb,292:$Vc,294:$Vd,295:$Ve,299:$Vf,301:$Vg,303:$Vh,304:$Vi,309:$Vj,311:$Vk,312:$Vl,328:$Vm,330:$Vn,331:$Vo,333:$Vp,334:$Vq,335:$Vr,336:$Vs,337:$Vt,339:$Vu,342:$Vv,343:$Vw}),o($Vs2,[2,267],{224:251,154:$Vk1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1}),o($Vs2,[2,268],{224:251,154:$Vk1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1}),o($Vb2,[2,269],{224:251,154:$Vk1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1}),o($Vb2,[2,270],{224:251,154:$Vk1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1}),o($Vt2,[2,271],{224:251,212:$Vr1,213:$Vs1}),o($Vt2,[2,272],{224:251,212:$Vr1,213:$Vs1}),o($Vt2,[2,273],{224:251,212:$Vr1,213:$Vs1}),o([4,5,8,9,11,45,59,61,63,65,80,91,96,97,102,104,112,113,114,115,116,117,118,119,124,125,134,135,136,137,138,141,142,144,149,150,151,154,165,190,201,203,204,205,206,207,208,209,210,211,212,214,215,216,217,218,219,220,221,222,223,226,227,228,229,231,232,233,234,237,238,241,242,250,263,292,294,295,299,301,303,304,309,311,312,328,330,331,333,334,335,336,337,339,342,343,355],[2,274],{224:251,213:$Vs1}),o($Vd1,[2,275],{64:$VM1}),o($Vd1,[2,276]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:523,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($Vd1,[2,278]),o($Vu2,[2,279],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,228:$VF1,229:$VG1,233:$VJ1}),o($Vu2,[2,280],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,228:$VF1,229:$VG1,233:$VJ1}),o($Vu2,[2,281],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,228:$VF1,229:$VG1,233:$VJ1}),o($Vu2,[2,282],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,228:$VF1,229:$VG1,233:$VJ1}),o($Vu2,[2,283],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,228:$VF1,229:$VG1,233:$VJ1}),o($Vu2,[2,284],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,228:$VF1,229:$VG1,233:$VJ1}),o($Vu2,[2,285],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,228:$VF1,229:$VG1,233:$VJ1}),o($Vu2,[2,286],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,228:$VF1,229:$VG1,233:$VJ1}),o($Vu2,[2,287],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,228:$VF1,229:$VG1,233:$VJ1}),o($Vu2,[2,288],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,228:$VF1,229:$VG1,233:$VJ1}),{64:[1,524]},{64:[2,318]},{64:[2,319]},{64:[2,320]},o([4,5,8,9,11,45,59,61,63,65,80,91,96,97,102,104,112,113,114,115,116,117,118,119,124,125,134,135,136,137,138,141,142,144,149,150,151,165,190,201,203,204,205,226,227,231,232,234,237,238,241,242,250,263,292,294,295,299,301,303,304,309,311,312,328,330,331,333,334,335,336,337,339,342,343,355],[2,291],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,228:$VF1,229:$VG1,233:$VJ1}),o([4,5,8,9,11,45,59,61,63,65,80,91,96,97,102,104,112,113,114,115,116,117,118,119,124,125,134,135,136,137,138,141,142,144,149,150,151,165,190,201,203,204,205,227,234,237,238,241,242,250,263,292,294,295,299,301,303,304,309,311,312,328,330,331,333,334,335,336,337,339,342,343,355],[2,292],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1}),{3:106,4:$VB,5:$VC,33:525,49:104,64:$VD,65:[1,527],66:59,74:79,80:$V4,89:92,93:88,94:96,95:97,96:$VE,121:429,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,187:526,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($Vd1,[2,303]),o($Vd1,[2,309]),o($Vd1,[2,310]),{64:[1,528]},{3:298,4:$VB,5:$VC,64:[1,529],93:413,155:412,192:$V72,230:530},o($Vv2,[2,305],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,228:$VF1,229:$VG1,233:$VJ1}),o($Vv2,[2,306],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,228:$VF1,229:$VG1,233:$VJ1}),o([4,5,8,9,11,45,59,61,63,65,80,91,96,97,102,104,112,113,114,115,116,117,118,119,124,125,134,135,136,137,138,141,142,144,149,150,151,165,190,201,203,204,205,214,215,216,217,218,219,220,221,222,223,226,227,228,229,231,232,233,234,237,238,241,242,250,263,292,294,295,299,301,303,304,309,311,312,328,330,331,333,334,335,336,337,339,342,343,355],[2,307],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1}),o($Vd1,[2,308]),o($Vw2,[2,399],{64:[1,531]}),{64:[1,532]},o($Vd1,[2,210]),o($Vd1,[2,296]),{65:[1,533],154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:534,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:535,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{61:$Vx2,65:[1,536]},o($VP1,[2,245]),o($Vy2,[2,246],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),o($Vd1,$Vz2,{106:[1,538]}),o($VS1,[2,192]),o($Vd1,[2,188]),{65:[1,539],154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},{65:[1,540]},{200:541,201:$Vc2,202:437,203:$VR1,205:$Vd2},{201:[1,542]},o($Ve2,[2,262]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:543,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{154:$Vk1,204:[1,544],206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},{63:[1,545],154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},{61:[1,546]},o($VS1,[2,488]),{3:298,4:$VB,5:$VC,64:$VT1,89:290,93:296,94:295,96:$VE,151:$VF,152:291,155:293,158:292,159:294,163:288,188:$VT,189:$VU,190:$VV,191:$VW,192:$Vf1,194:$VZ,195:$V_,196:$V$,197:$V01,313:126,314:$V51,316:548,317:289,318:$V61,322:[1,547]},{65:[1,549],154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},{3:550,4:$VB,5:$VC,81:$Va2},o($VS1,[2,485]),{3:306,4:$VB,5:$VC,96:$VV1,151:$VW1,320:[1,551],323:552},{3:298,4:$VB,5:$VC,64:$VT1,89:290,93:296,94:295,96:$VE,151:$VF,152:291,155:293,158:292,159:294,163:288,188:$VT,189:$VU,190:$VV,191:$VW,192:$Vf1,194:$VZ,195:$V_,196:$V$,197:$V01,313:126,314:$V51,316:553,317:289,318:$V61},{3:298,4:$VB,5:$VC,64:$VT1,89:290,93:296,94:295,96:$VE,151:$VF,152:291,155:293,158:292,159:294,163:288,188:$VT,189:$VU,190:$VV,191:$VW,192:$Vf1,194:$VZ,195:$V_,196:$V$,197:$V01,313:126,314:$V51,316:554,317:289,318:$V61},{3:298,4:$VB,5:$VC,64:$VT1,89:290,93:296,94:295,96:$VE,151:$VF,152:291,155:293,158:292,159:294,163:288,188:$VT,189:$VU,190:$VV,191:$VW,192:$Vf1,194:$VZ,195:$V_,196:$V$,197:$V01,313:126,314:$V51,316:555,317:289,318:$V61},{83:[1,557],296:[1,556]},{83:[1,558]},{83:[1,559]},{83:[1,560]},o($VA,[2,424],{63:[1,562],64:[1,561]}),o($VA,[2,429]),{193:[1,563]},{3:564,4:$VB,5:$VC,96:$VE,152:565,190:$VV},{3:193,4:$VB,5:$VC,92:566},{120:[1,567]},o($VA,[2,352],{64:[1,568]}),{63:[1,570],64:[1,569]},o($VZ1,[2,525]),o($VZ1,[2,526],{218:[1,571]}),{4:$V82,168:572,288:$V92},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:573,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($VA,[2,437]),o($Vj2,[2,417]),{3:574,4:$VB,5:$VC,96:$VE,152:575,190:$VV},o($VA,[2,415]),o($VA,[2,459]),{64:$VA2,94:579,163:578,192:$Vf1,194:$VZ,195:$V_,196:$V$,197:$V01,245:576,313:126,314:$V51,318:$V61},{244:[1,580]},{3:503,4:$VB,5:$VC,123:581,155:582},o($VA,[2,331]),{3:583,4:$VB,5:$VC},o($VB2,[2,147],{70:584,125:[1,585]}),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:586,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($V02,[2,81],{61:[1,587]}),o($VC2,[2,88],{100:588,107:589,101:590,108:591,111:594,102:$VD2,104:$VE2,112:$VF2,113:$VG2,114:$VH2,115:$VI2,116:$VJ2,117:$VK2,118:$VL2,119:$VM2}),{203:$VN2,347:603,349:604,350:605},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:607,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{120:[2,534]},o($V12,[2,92],{3:608,4:$VB,5:$VC,63:[1,609]}),o($V12,[2,94]),o($V12,[2,97]),o($V12,[2,101]),o($V12,[2,104]),o($V12,[2,107]),o([4,5,8,9,11,61,63,64,65,80,97,102,104,112,113,114,115,116,117,118,119,120,122,124,125,135,136,137,138,144,201,205,238,244,246,292,295,296,297,298],[2,109]),o($V42,[2,55]),{33:610,66:59,74:79,80:$V4},o($VA,[2,455],{97:[1,611]}),o($VA,[2,451],{97:[1,612]}),o($VA,[2,444]),{96:$VE,152:613,190:$VV},o($VA,[2,453],{97:[1,614]}),o($VA,[2,448]),o($VA,[2,449],{206:[1,615]}),o($VA,[2,322],{61:$VO2,124:[1,616]}),o($VP2,[2,323]),{218:[1,618]},o([8,9,11,61,65,102,104,112,113,114,115,116,117,118,119,124,125,135,136,137,138,144,201,205,218],$VL1,{106:$Vh2}),o($VA,[2,466]),o($VZ1,[2,521]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:619,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{213:[1,621],218:[1,620]},{3:623,4:$VB,5:$VC,64:$VQ2,151:$VR2,326:622},o($Vl2,[2,59],{61:$Vm2}),o($Vl2,[2,60],{61:$Vm2}),o($Vl2,[2,61],{61:$Vm2}),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:376,147:626,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($Vn2,[2,175]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:627,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:628,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:629,4:$VB,5:$VC,96:$VE,151:[1,630],152:631,190:$VV},o($Vr2,[2,181]),o($Vr2,[2,183]),o($Vr2,[2,185]),o($Vg1,[2,73]),{65:[1,632]},o($VA,[2,513]),{65:[1,633],154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},{3:106,4:$VB,5:$VC,33:634,49:104,64:$VD,66:59,74:79,80:$V4,89:92,93:88,94:96,95:97,96:$VE,121:429,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,187:635,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{65:[1,636]},{61:$Vx2,65:[1,637]},o($Vd1,[2,301]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:638,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,33:639,49:104,64:$VD,65:[1,641],66:59,74:79,80:$V4,89:92,93:88,94:96,95:97,96:$VE,121:429,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,187:640,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($Vd1,[2,304]),{151:[1,642]},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:644,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,247:643,313:126,314:$V51,318:$V61},o($Vd1,$VS2,{173:645,174:$VT2}),{65:[1,647],154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},{65:[1,648],154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},o($VP1,[2,244]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:649,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:650,4:$VB,5:$VC,154:[1,651]},o($VS1,[2,467]),o($Vd1,[2,255]),{201:[1,652]},o($Vd1,[2,261]),{154:$Vk1,201:[2,265],206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:653,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{4:$V82,168:654,288:$V92},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:655,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($VS1,[2,489]),o($Vf2,[2,496]),o($Vg2,[2,484]),o($VS1,$Vz2,{106:[1,656]}),o($VS1,[2,486]),o($Vi2,[2,491]),o($Vi2,[2,493]),o($Vi2,[2,494]),o($Vi2,[2,495]),{3:657,4:$VB,5:$VC},{3:658,4:$VB,5:$VC},{3:660,4:$VB,5:$VC,285:659},{3:660,4:$VB,5:$VC,285:661},{3:662,4:$VB,5:$VC},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:429,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,187:663,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:664,4:$VB,5:$VC},o($Vj2,[2,365]),o($VA,$VU2,{302:665,63:$VV2,64:[1,666]}),o($VA,$VU2,{302:668,63:$VV2}),{64:[1,669]},{3:193,4:$VB,5:$VC,92:670},{3:660,4:$VB,5:$VC,63:[1,673],253:671,264:672,285:674},{3:503,4:$VB,5:$VC,123:675,155:582},{33:676,66:59,74:79,80:$V4},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:677,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($VZ1,[2,527],{218:[1,678]}),o($VA,[2,326],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),o($VA,[2,438]),o($VA,[2,439]),o($VA,[2,328],{61:$VW2}),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:644,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,247:680,313:126,314:$V51,318:$V61},o($VX2,[2,336]),o($VX2,[2,337]),o($VA,[2,329]),{61:$VY2,65:[1,681]},o($VZ2,[2,349]),o($VA,[2,423]),o($V_2,[2,162],{71:683,138:[1,684]}),{126:[1,685]},o($Vk2,[2,146],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),{3:173,4:$VB,5:$VC,64:$Va1,92:168,93:170,94:169,95:171,96:$Vb1,99:686,105:172,192:$Vc1,194:$VZ,195:$V_,196:$V$,197:$V01},o($V02,[2,82],{108:591,111:594,107:687,101:688,102:$VD2,104:$VE2,112:$VF2,113:$VG2,114:$VH2,115:$VI2,116:$VJ2,117:$VK2,118:$VL2,119:$VM2}),o($V$2,[2,113]),o($V$2,[2,114]),{3:173,4:$VB,5:$VC,64:[1,692],92:690,93:693,94:691,95:694,109:689,192:$Vc1,194:$VZ,195:$V_,196:$V$,197:$V01},{103:[1,695],113:$V03},{103:[1,697],113:$V13},o($V23,[2,129]),{102:[1,701],104:[1,700],111:699,113:$VG2,114:$VH2,115:$VI2,116:$VJ2,117:$VK2,118:$VL2,119:$VM2},o($V23,[2,131]),{113:[1,702]},{104:[1,704],113:[1,703]},{104:[1,706],113:[1,705]},{104:[1,707]},{113:[1,708]},{113:[1,709]},o($VA,[2,554],{348:710,349:711,350:712,203:$VN2,355:[1,713]}),o($V33,[2,538]),o($V33,[2,539]),{228:[1,715],351:[1,714]},{154:$Vk1,203:[2,535],206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},o($V12,[2,90]),{3:716,4:$VB,5:$VC},{65:[1,717]},{3:718,4:$VB,5:$VC},{3:719,4:$VB,5:$VC},o($VA,[2,446]),{3:720,4:$VB,5:$VC},{96:$VE,152:721,190:$VV},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:722,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:503,4:$VB,5:$VC,155:502,240:723},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:724,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($VA,[2,499],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:725,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:623,4:$VB,5:$VC,64:$VQ2,151:$VR2,326:726},o($V43,[2,502]),o($V43,[2,503]),o($V43,[2,504]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:727,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($Vn2,$Vo2,{148:728,149:$Vp2,150:$Vq2}),o($Vn2,[2,177],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),o($Vn2,[2,178],{224:251,149:[1,729],154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),o($Vr2,[2,180]),o($Vr2,[2,182]),o($Vr2,[2,184]),o($Vg1,[2,72]),o($Vd1,[2,277]),{65:[1,730]},{61:$Vx2,65:[1,731]},o($Vd1,[2,297]),o($Vd1,[2,299]),{65:[1,732],154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},{65:[1,733]},{61:$Vx2,65:[1,734]},o($Vd1,[2,302]),{61:[1,735],65:[1,736]},{61:$V53,65:[1,737]},o($Vy2,[2,341],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),o($Vd1,[2,226]),{64:[1,739]},o($Vd1,$VS2,{173:740,174:$VT2}),o($Vd1,$VS2,{173:741,174:$VT2}),o($Vy2,[2,247],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),o($VS1,[2,190]),o($Vd1,[2,187]),o($Vd1,[2,260]),o($Ve2,[2,264],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),{61:[1,743],65:[1,742]},{61:[1,745],65:[1,744],154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},{3:650,4:$VB,5:$VC},o($VA,[2,418]),{296:[1,746]},o($VA,[2,419]),o($V63,[2,396],{168:747,4:$V82,287:[1,748],288:$V92}),o($VA,[2,420]),o($VA,[2,422]),{61:$Vx2,65:[1,749]},o($VA,[2,426]),o($VA,[2,430]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:429,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,187:750,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:751,4:$VB,5:$VC},o($VA,[2,432]),{3:753,4:$VB,5:$VC,96:$V73,277:752},{64:[1,755]},{65:[1,756]},{61:[1,757],65:[2,367]},{33:758,66:59,74:79,80:$V4},o($Vy2,[2,392]),{61:$VY2,65:[1,759]},o($VA,[2,458]),o($VZ1,[2,528],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:760,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{64:[1,761],94:763,163:762,192:$Vf1,194:$VZ,195:$V_,196:$V$,197:$V01,313:126,314:$V51,318:$V61},{61:$V53,65:[1,764]},{33:766,66:59,74:79,80:$V4,244:[1,765]},{3:503,4:$VB,5:$VC,155:767},o($V83,[2,170],{72:768,144:[1,769]}),{126:[1,770]},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:776,127:771,129:772,130:$V93,132:$Va3,133:$Vb3,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($VC2,[2,89]),o($V$2,[2,111]),o($V$2,[2,112]),o($V$2,[2,144],{110:777,120:[1,778],122:[1,779]}),o($Vc3,[2,116],{3:780,4:$VB,5:$VC,63:[1,781]}),{3:782,4:$VB,5:$VC,63:[1,783]},{33:784,66:59,74:79,80:$V4},o($Vc3,[2,123],{3:785,4:$VB,5:$VC,63:[1,786]}),o($Vc3,[2,126],{3:787,4:$VB,5:$VC,63:[1,788]}),{64:[1,789]},o($V23,[2,141]),{64:[1,790]},o($V23,[2,137]),o($V23,[2,130]),{113:$V13},{113:$V03},o($V23,[2,132]),o($V23,[2,133]),{113:[1,791]},o($V23,[2,135]),{113:[1,792]},{113:[1,793]},o($V23,[2,139]),o($V23,[2,140]),o($VA,[2,531]),o($V33,[2,536]),o($V33,[2,537]),{3:106,4:$VB,5:$VC,49:104,64:$VD,77:794,89:92,93:88,94:96,95:97,96:$VE,121:376,147:375,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{204:[1,795],226:[1,796]},{351:[1,797]},o($V12,[2,91]),o($V42,[2,57]),o($VA,[2,456]),o($VA,[2,452]),o($VA,[2,454]),o($VA,[2,450]),o($VA,[2,321],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),o($VP2,[2,324]),o($VP2,[2,325],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),o($VA,[2,500],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),o($V43,[2,501]),{65:[1,798],154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},o($Vn2,[2,174]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:799,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($Vd1,[2,289]),o($Vd1,[2,290]),o($Vd1,[2,311]),o($Vd1,[2,298]),o($Vd1,[2,300]),{151:[1,800]},o($Vw2,[2,398]),o($Vw2,[2,400]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:801,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{138:$Vd3,175:802,176:803,177:[1,804]},o($Vd1,[2,227]),o($Vd1,[2,228]),o($Vd1,[2,215]),{151:[1,806]},o($Vd1,[2,217]),{151:[1,807]},{3:808,4:$VB,5:$VC},o($V63,[2,401],{286:809,289:810,290:811,272:820,191:$Ve3,228:$Vf3,246:$Vg3,258:$Vh3,274:$Vi3,275:$Vj3,278:$Vk3,279:$Vl3,291:$Vm3}),o($V63,[2,395]),o($VA,[2,425],{63:[1,822]}),{61:$Vx2,65:[1,823]},o($VA,[2,434]),{61:$Vn3,65:[1,824]},o($Vy2,[2,388]),o($Vy2,[2,389]),{3:753,4:$VB,5:$VC,96:$V73,277:826},o($VA,[2,353],{254:827,255:828,256:829,246:$Vo3,257:$Vp3,258:$Vq3,259:$Vr3}),o($Vs3,$Vt3,{3:660,265:834,285:835,266:836,267:837,4:$VB,5:$VC,273:$Vu3}),{65:[2,368]},{63:[1,839]},o($VZ1,[2,529],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:644,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,247:840,313:126,314:$V51,318:$V61},o($VX2,[2,339]),o($VX2,[2,340]),o($VX2,[2,335]),{64:$VA2,94:579,163:578,192:$Vf1,194:$VZ,195:$V_,196:$V$,197:$V01,245:841,313:126,314:$V51,318:$V61},o($VA,[2,332]),o($VZ2,[2,350]),o($Vv3,[2,157],{73:842,135:[1,843],136:[1,844],137:[1,845]}),{89:846,151:$VF},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:849,139:847,140:848,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($VB2,[2,155],{128:850,61:$Vw3,134:[1,852]}),o($Vx3,[2,149]),{131:[1,853]},{64:[1,854]},{64:[1,855]},o($Vx3,[2,154],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),o($V$2,[2,115]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:856,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:503,4:$VB,5:$VC,123:857,155:582},o($Vc3,[2,117]),{3:858,4:$VB,5:$VC},o($Vc3,[2,119]),{3:859,4:$VB,5:$VC},{65:[1,860]},o($Vc3,[2,124]),{3:861,4:$VB,5:$VC},o($Vc3,[2,127]),{3:862,4:$VB,5:$VC},{33:863,66:59,74:79,80:$V4},{33:864,66:59,74:79,80:$V4},o($V23,[2,134]),o($V23,[2,136]),o($V23,[2,138]),o($VA,[2,555],{61:$Vm2,91:[1,865]}),{237:$Vy3,241:$Vz3,352:866},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:869,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{126:[1,871],204:[1,870],226:[1,872]},o($V43,[2,505]),o($Vn2,[2,179],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),{65:[1,873]},o($Vy2,[2,342],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),{65:[1,874],138:$Vd3,176:875},{65:[1,876]},{126:[1,877]},{126:[1,878]},{65:[1,879]},{65:[1,880]},o($VA,[2,421]),o($V63,[2,394]),o($V63,[2,402],{272:820,290:881,191:$Ve3,228:$Vf3,246:$Vg3,258:$Vh3,274:$Vi3,275:$Vj3,278:$Vk3,279:$Vl3,291:$Vm3}),o($V52,[2,404]),{276:[1,882]},{276:[1,883]},{3:884,4:$VB,5:$VC},o($V52,[2,408]),o($V52,[2,410],{64:[1,885]}),{3:207,4:$VB,5:$VC,89:200,93:205,94:204,96:$VE,151:$VF,152:201,158:202,159:203,170:886,171:$Ve1,188:$VT,189:$VU,190:$VV,191:$VW,194:$VZ,195:$V_,196:$V$,197:$V01},o($V52,[2,412]),{191:[1,887]},o($V52,[2,414]),{64:[1,888]},{3:889,4:$VB,5:$VC},o($VA,$VU2,{302:890,63:$VV2}),o($VA,[2,440]),{3:891,4:$VB,5:$VC,96:[1,892]},{61:$Vn3,65:[1,893]},o($VA,[2,351]),o($VA,[2,354],{256:894,246:$Vo3,257:$Vp3,258:$Vq3,259:$Vr3}),o($VA3,[2,356]),o($VA3,[2,357]),{218:[1,895]},{218:[1,896]},{218:[1,897]},{61:[1,898],65:[2,366]},o($Vy2,[2,393]),o($Vy2,[2,369]),{78:[1,906],86:[1,907],268:899,269:900,270:901,271:902,272:903,274:$Vi3,275:[1,904],276:[1,908],278:[1,905]},{3:909,4:$VB,5:$VC},{33:910,66:59,74:79,80:$V4},{61:$V53,65:[1,911]},o($VA,[2,330],{61:$VW2}),o($Vv3,[2,58]),{33:912,66:59,74:79,79:[1,913],80:$V4},{33:914,66:59,74:79,80:$V4},{33:915,66:59,74:79,80:$V4},o($V83,[2,172],{145:916,146:[1,917]}),o($V_2,[2,163],{61:$VB3}),o($VC3,[2,164]),o($VC3,[2,166],{224:251,141:[1,919],142:[1,920],154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),o($VB2,[2,148]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:776,129:921,130:$V93,132:$Va3,133:$Vb3,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:922,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{64:[1,923]},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:776,127:924,129:772,130:$V93,132:$Va3,133:$Vb3,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:776,127:925,129:772,130:$V93,132:$Va3,133:$Vb3,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($V$2,[2,142],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),o($V$2,[2,143],{61:$VY2}),o($Vc3,[2,118]),o($Vc3,[2,120]),{3:926,4:$VB,5:$VC,63:[1,927]},o($Vc3,[2,125]),o($Vc3,[2,128]),{65:[1,928]},{65:[1,929]},{3:193,4:$VB,5:$VC,92:931,192:[1,930]},o($V33,[2,540]),o($V33,[2,542]),{238:[1,932]},{154:$Vk1,204:[1,933],206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},{242:$VD3,353:934},{311:[1,937],354:[1,936]},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:938,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($Vw2,[2,397]),o($Vd1,[2,230]),{65:[1,939]},o($Vd1,[2,231]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:776,127:940,129:772,130:$V93,132:$Va3,133:$Vb3,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:849,139:941,140:848,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($Vd1,[2,216]),o($Vd1,[2,218]),o($V52,[2,403]),o($V52,[2,405]),{279:[1,942]},{64:[1,943]},{89:944,151:$VF},o($V52,[2,411]),o($V52,[2,413]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:945,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($VA,[2,427]),o($VA,[2,431]),o($Vy2,[2,390]),o($Vy2,[2,391]),o($VA,[2,441]),o($VA3,[2,355]),{3:946,4:$VB,5:$VC},{89:947,151:$VF},{3:948,4:$VB,5:$VC},o($Vs3,$Vt3,{267:837,266:949,273:$Vu3}),o($Vy2,[2,371]),o($Vy2,[2,372]),o($Vy2,[2,373]),o($Vy2,[2,374]),o($Vy2,[2,375]),{276:[1,950]},{276:[1,951]},o($Vy2,[2,385]),{3:952,4:$VB,5:$VC},{3:953,4:$VB,5:$VC},o($Vs3,[2,377]),o($VA,[2,457]),o($VX2,[2,338]),o($Vv3,[2,158]),{33:954,66:59,74:79,80:$V4},o($Vv3,[2,160]),o($Vv3,[2,161]),o($V83,[2,171]),{89:955,151:$VF},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:849,140:956,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($VC3,[2,167]),{143:[1,957]},o($Vx3,[2,150]),o($VB2,[2,156],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:776,127:958,129:772,130:$V93,132:$Va3,133:$Vb3,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{61:$Vw3,65:[1,959]},{61:$Vw3,65:[1,960]},o($Vc3,[2,121]),{3:961,4:$VB,5:$VC},{3:962,4:$VB,5:$VC,63:[1,963]},{3:964,4:$VB,5:$VC,63:[1,965]},{3:966,4:$VB,5:$VC},o($VA,[2,557],{64:[1,967]}),{3:503,4:$VB,5:$VC,155:502,239:968,240:501},{237:$Vy3,241:$Vz3,352:969},o($V33,[2,544]),{64:[1,971],244:[1,970],246:[1,972]},{204:[1,973],226:[1,974]},{204:[1,975],226:[1,976]},{154:$Vk1,204:[1,977],206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},o($Vd1,[2,232]),o([65,138],[2,233],{61:$Vw3}),{61:$VB3,65:[2,234]},{3:978,4:$VB,5:$VC},{3:979,4:$VB,5:$VC},{61:[1,980]},{65:[1,981],154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},o($VA3,[2,358]),o($VA3,[2,359]),o($VA3,[2,360]),o($Vy2,[2,370]),{64:[1,982]},{64:[1,983]},{64:[1,984]},{64:[1,985]},o($Vv3,[2,159]),o($V83,[2,173]),o($VC3,[2,165]),o($VC3,[2,168],{141:[1,986]}),{61:$Vw3,65:[1,987]},o($Vx3,[2,152]),o($Vx3,[2,153]),o($Vc3,[2,122]),o($V$2,[2,84]),{3:988,4:$VB,5:$VC},o($V$2,[2,86]),{3:989,4:$VB,5:$VC},o($VA,[2,556]),{3:503,4:$VB,5:$VC,123:990,155:582},o($V33,[2,543],{61:$VO2}),o($V33,[2,541]),{64:$VA2,94:579,163:578,192:$Vf1,194:$VZ,195:$V_,196:$V$,197:$V01,245:991,313:126,314:$V51,318:$V61},{3:503,4:$VB,5:$VC,123:992,155:582},{244:[1,993]},{242:$VD3,353:994},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:995,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{242:$VD3,353:996},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:997,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{242:$VD3,353:998},{64:[1,999]},{65:[1,1e3]},{89:1001,151:$VF},o($V52,[2,378]),{3:753,4:$VB,5:$VC,96:$V73,277:1002},{3:753,4:$VB,5:$VC,96:$V73,277:1003},{3:503,4:$VB,5:$VC,123:1004,155:582},{3:503,4:$VB,5:$VC,123:1005,155:582},o($VC3,[2,169]),o($Vx3,[2,151]),o($V$2,[2,85]),o($V$2,[2,87]),{61:$VY2,65:[1,1006]},o($V33,[2,550],{61:$VW2}),{61:$VY2,65:[1,1007]},o($V33,[2,552]),o($V33,[2,545]),{154:$Vk1,204:[1,1008],206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},o($V33,[2,548]),{154:$Vk1,204:[1,1009],206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},o($V33,[2,546]),{3:1010,4:$VB,5:$VC},o($V52,[2,407]),{65:[1,1011]},{61:$Vn3,65:[1,1012]},{61:$Vn3,65:[1,1013]},{61:$VY2,65:[1,1014]},{61:$VY2,65:[1,1015]},o($VA,[2,558]),{244:[1,1016],246:[1,1017]},{242:$VD3,353:1018},{237:$Vy3,241:$Vz3,352:1019},{65:[1,1020]},o($V52,[2,409]),o($Vy2,[2,379]),{279:[1,1021]},o($Vy2,[2,386]),o($Vy2,[2,387]),{64:$VA2,94:579,163:578,192:$Vf1,194:$VZ,195:$V_,196:$V$,197:$V01,245:1022,313:126,314:$V51,318:$V61},{244:[1,1023]},o($V33,[2,547]),o($V33,[2,549]),o($V52,[2,406]),{3:1024,4:$VB,5:$VC},o($V33,[2,551],{61:$VW2}),o($V33,[2,553]),{64:[1,1025]},{3:753,4:$VB,5:$VC,96:$V73,277:1026},{61:$Vn3,65:[1,1027]},o($Vy2,[2,381],{280:1028,281:1029,120:[1,1030]}),o($Vy2,[2,380]),{120:[1,1032],282:1031},{241:[1,1033]},o($Vy2,[2,382]),{237:[1,1034]},{283:[1,1035]},{283:[1,1036]},{284:[1,1037]},{284:[1,1038]},{120:[2,383]},o($Vy2,[2,384])],defaultActions:{81:[2,3],129:[2,235],130:[2,236],131:[2,237],132:[2,238],133:[2,239],134:[2,240],135:[2,241],136:[2,242],137:[2,243],165:[2,532],337:[2,533],405:[2,318],406:[2,319],407:[2,320],483:[2,534],758:[2,368],1037:[2,383]},parseError:function parseError(str,hash){if(hash.recoverable){this.trace(str) }else{throw new Error(str)}},parse:function parse(input){var self=this,stack=[0],tstack=[],vstack=[null],lstack=[],table=this.table,yytext="",yylineno=0,yyleng=0,recovering=0,TERROR=2,EOF=1;var args=lstack.slice.call(arguments,1);var lexer=Object.create(this.lexer);var sharedState={yy:{}};for(var k in this.yy){if(Object.prototype.hasOwnProperty.call(this.yy,k)){sharedState.yy[k]=this.yy[k]}}lexer.setInput(input,sharedState.yy);sharedState.yy.lexer=lexer;sharedState.yy.parser=this;if(typeof lexer.yylloc=="undefined"){lexer.yylloc={}}var yyloc=lexer.yylloc;lstack.push(yyloc);var ranges=lexer.options&&lexer.options.ranges;if(typeof sharedState.yy.parseError==="function"){this.parseError=sharedState.yy.parseError}else{this.parseError=Object.getPrototypeOf(this).parseError}function popStack(n){stack.length=stack.length-2*n;vstack.length=vstack.length-n;lstack.length=lstack.length-n}_token_stack:function lex(){var token;token=lexer.lex()||EOF;if(typeof token!=="number"){token=self.symbols_[token]||token}return token}var symbol,preErrorSymbol,state,action,a,r,yyval={},p,len,newState,expected;while(true){state=stack[stack.length-1];if(this.defaultActions[state]){action=this.defaultActions[state]}else{if(symbol===null||typeof symbol=="undefined"){symbol=lex()}action=table[state]&&table[state][symbol]}if(typeof action==="undefined"||!action.length||!action[0]){var errStr="";expected=[];for(p in table[state]){if(this.terminals_[p]&&p>TERROR){expected.push("'"+this.terminals_[p]+"'")}}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})}if(action[0]instanceof Array&&action.length>1){throw new Error("Parse Error: multiple actions possible at state: "+state+", token: "+symbol)}switch(action[0]){case 1:stack.push(symbol);vstack.push(lexer.yytext);lstack.push(lexer.yylloc);stack.push(action[1]);symbol=null;if(!preErrorSymbol){yyleng=lexer.yyleng;yytext=lexer.yytext;yylineno=lexer.yylineno;yyloc=lexer.yylloc;if(recovering>0){recovering--}}else{symbol=preErrorSymbol;preErrorSymbol=null}break;case 2:len=this.productions_[action[1]][1];yyval.$=vstack[vstack.length-len];yyval._$={first_line:lstack[lstack.length-(len||1)].first_line,last_line:lstack[lstack.length-1].last_line,first_column:lstack[lstack.length-(len||1)].first_column,last_column:lstack[lstack.length-1].last_column};if(ranges){yyval._$.range=[lstack[lstack.length-(len||1)].range[0],lstack[lstack.length-1].range[1]]}r=this.performAction.apply(yyval,[yytext,yyleng,yylineno,sharedState.yy,action[1],vstack,lstack].concat(args));if(typeof r!=="undefined"){return r}if(len){stack=stack.slice(0,-1*len*2);vstack=vstack.slice(0,-1*len);lstack=lstack.slice(0,-1*len)}stack.push(this.productions_[action[1]][0]);vstack.push(yyval.$);lstack.push(yyval._$);newState=table[stack[stack.length-2]][stack[stack.length-1]];stack.push(newState);break;case 3:return true}}return true}};var lexer=function(){var lexer={EOF:1,parseError:function parseError(str,hash){if(this.yy.parser){this.yy.parser.parseError(str,hash)}else{throw new Error(str)}},setInput:function(input,yy){this.yy=yy||this.yy||{};this._input=input;this._more=this._backtrack=this.done=false;this.yylineno=this.yyleng=0;this.yytext=this.matched=this.match="";this.conditionStack=["INITIAL"];this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0};if(this.options.ranges){this.yylloc.range=[0,0]}this.offset=0;return this},input:function(){var ch=this._input[0];this.yytext+=ch;this.yyleng++;this.offset++;this.match+=ch;this.matched+=ch;var lines=ch.match(/(?:\r\n?|\n).*/g);if(lines){this.yylineno++;this.yylloc.last_line++}else{this.yylloc.last_column++}if(this.options.ranges){this.yylloc.range[1]++}this._input=this._input.slice(1);return ch},unput:function(ch){var len=ch.length;var lines=ch.split(/(?:\r\n?|\n)/g);this._input=ch+this._input;this.yytext=this.yytext.substr(0,this.yytext.length-len);this.offset-=len;var oldLines=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1);this.matched=this.matched.substr(0,this.matched.length-1);if(lines.length-1){this.yylineno-=lines.length-1}var r=this.yylloc.range;this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:lines?(lines.length===oldLines.length?this.yylloc.first_column:0)+oldLines[oldLines.length-lines.length].length-lines[0].length:this.yylloc.first_column-len};if(this.options.ranges){this.yylloc.range=[r[0],r[0]+this.yyleng-len]}this.yyleng=this.yytext.length;return this},more:function(){this._more=true;return this},reject:function(){if(this.options.backtrack_lexer){this._backtrack=true}else{return this.parseError("Lexical error on line "+(this.yylineno+1)+". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})}return this},less:function(n){this.unput(this.match.slice(n))},pastInput:function(){var past=this.matched.substr(0,this.matched.length-this.match.length);return(past.length>20?"...":"")+past.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var next=this.match;if(next.length<20){next+=this._input.substr(0,20-next.length)}return(next.substr(0,20)+(next.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var pre=this.pastInput();var c=new Array(pre.length+1).join("-");return pre+this.upcomingInput()+"\n"+c+"^"},test_match:function(match,indexed_rule){var token,lines,backup;if(this.options.backtrack_lexer){backup={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done};if(this.options.ranges){backup.yylloc.range=this.yylloc.range.slice(0)}}lines=match[0].match(/(?:\r\n?|\n).*/g);if(lines){this.yylineno+=lines.length}this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:lines?lines[lines.length-1].length-lines[lines.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+match[0].length};this.yytext+=match[0];this.match+=match[0];this.matches=match;this.yyleng=this.yytext.length;if(this.options.ranges){this.yylloc.range=[this.offset,this.offset+=this.yyleng]}this._more=false;this._backtrack=false;this._input=this._input.slice(match[0].length);this.matched+=match[0];token=this.performAction.call(this,this.yy,this,indexed_rule,this.conditionStack[this.conditionStack.length-1]);if(this.done&&this._input){this.done=false}if(token){return token}else if(this._backtrack){for(var k in backup){this[k]=backup[k]}return false}return false},next:function(){if(this.done){return this.EOF}if(!this._input){this.done=true}var token,match,tempMatch,index;if(!this._more){this.yytext="";this.match=""}var rules=this._currentRules();for(var i=0;imatch[0].length)){match=tempMatch;index=i;if(this.options.backtrack_lexer){token=this.test_match(tempMatch,rules[i]);if(token!==false){return token}else if(this._backtrack){match=false;continue}else{return false}}else if(!this.options.flex){break}}}if(match){token=this.test_match(match,rules[index]);if(token!==false){return token}return false}if(this._input===""){return this.EOF}else{return this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})}},lex:function lex(){var r=this.next();if(r){return r}else{return this.lex()}},begin:function begin(condition){this.conditionStack.push(condition)},popState:function popState(){var n=this.conditionStack.length-1;if(n>0){return this.conditionStack.pop()}else{return this.conditionStack[0]}},_currentRules:function _currentRules(){if(this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]){return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules}else{return this.conditions["INITIAL"].rules}},topState:function topState(n){n=this.conditionStack.length-1-Math.abs(n||0);if(n>=0){return this.conditionStack[n]}else{return"INITIAL"}},pushState:function pushState(condition){this.begin(condition)},stateStackSize:function stateStackSize(){return this.conditionStack.length},options:{"case-insensitive":true},performAction:function anonymous(yy,yy_,$avoiding_name_collisions,YY_START){var YYSTATE=YY_START;switch($avoiding_name_collisions){case 0:return 165;break;case 1:return 197;break;case 2:return 314;break;case 3:return 5;break;case 4:return 5;break;case 5:return 190;break;case 6:return 190;break;case 7:return 96;break;case 8:return 96;break;case 9:return;break;case 10:return;break;case 11:break;case 12:return 227;break;case 13:return 226;break;case 14:return"ABSOLUTE";break;case 15:return 284;break;case 16:return 297;break;case 17:return 185;break;case 18:return 79;break;case 19:return 294;break;case 20:return 226;break;case 21:return 119;break;case 22:return 236;break;case 23:return 103;break;case 24:return 186;break;case 25:return 63;break;case 26:return 312;break;case 27:return 141;break;case 28:return 299;break;case 29:return 258;break;case 30:return 258;break;case 31:return 182;break;case 32:return 331;break;case 33:return 231;break;case 34:return 335;break;case 35:return 232;break;case 36:return 207;break;case 37:return 126;break;case 38:return 198;break;case 39:return 167;break;case 40:return 259;break;case 41:return 274;break;case 42:return"CLOSE";break;case 43:return 142;break;case 44:return"COLUMN";break;case 45:return"COLUMNS";break;case 46:return"COMMIT";break;case 47:return"CONSTRAINT";break;case 48:return"CONTINUE";break;case 49:return"CONVERT";break;case 50:return"COUNT";break;case 51:return 250;break;case 52:return"CROSS";break;case 53:return 133;break;case 54:return"CURRENT_TIMESTAMP";break;case 55:return"CURSOR";break;case 56:return 300;break;case 57:return 305;break;case 58:return 339;break;case 59:return 246;break;case 60:return 241;break;case 61:return"DELETED";break;case 62:return 141;break;case 63:return 301;break;case 64:return 75;break;case 65:return 292;break;case 66:return 201;break;case 67:return 257;break;case 68:return 288;break;case 69:return 205;break;case 70:return 136;break;case 71:return 193;break;case 72:return 13;break;case 73:return 189;break;case 74:return"FETCH";break;case 75:return 183;break;case 76:return 278;break;case 77:return 97;break;case 78:return 11;break;case 79:return 125;break;case 80:return 130;break;case 81:return 134;break;case 82:return 309;break;case 83:return 263;break;case 84:return 291;break;case 85:return 233;break;case 86:return 229;break;case 87:return 86;break;case 88:return 114;break;case 89:return 242;break;case 90:return"INSERTED";break;case 91:return 137;break;case 92:return 91;break;case 93:return 113;break;case 94:return 276;break;case 95:return 184;break;case 96:return 115;break;case 97:return 206;break;case 98:return 144;break;case 99:return 311;break;case 100:return"MATCHED";break;case 101:return 84;break;case 102:return"MAX";break;case 103:return"MERGE";break;case 104:return"MIN";break;case 105:return"EXCEPT";break;case 106:return"MODIFY";break;case 107:return 112;break;case 108:return"NEXT";break;case 109:return 166;break;case 110:return 143;break;case 111:return 283;break;case 112:return 228;break;case 113:return 191;break;case 114:return 327;break;case 115:return 120;break;case 116:return 146;break;case 117:return"OPEN";break;case 118:return 227;break;case 119:return 138;break;case 120:return 104;break;case 121:return 174;break;case 122:return 177;break;case 123:return 90;break;case 124:return 15;break;case 125:return 275;break;case 126:return 336;break;case 127:return"PRIOR";break;case 128:return 14;break;case 129:return 87;break;case 130:return"REDUCE";break;case 131:return 279;break;case 132:return"RELATIVE";break;case 133:return 295;break;case 134:return 337;break;case 135:return"RESTORE";break;case 136:return 116;break;case 137:return 330;break;case 138:return 132;break;case 139:return 82;break;case 140:return 300;break;case 141:return 305;break;case 142:return 80;break;case 143:return 118;break;case 144:return 238;break;case 145:return 131;break;case 146:return 304;break;case 147:return 235;break;case 148:return"STORE";break;case 149:return"SUM";break;case 150:return 251;break;case 151:return 306;break;case 152:return 354;break;case 153:return 149;break;case 154:return 85;break;case 155:return 150;break;case 156:return 204;break;case 157:return 296;break;case 158:return 88;break;case 159:return"TRAN";break;case 160:return 329;break;case 161:return 188;break;case 162:return 342;break;case 163:return 135;break;case 164:return 78;break;case 165:return 237;break;case 166:return 303;break;case 167:return 122;break;case 168:return 81;break;case 169:return 244;break;case 170:return 308;break;case 171:return 203;break;case 172:return 124;break;case 173:return 333;break;case 174:return 59;break;case 175:return 329;break;case 176:return 151;break;case 177:return 151;break;case 178:return 213;break;case 179:return 208;break;case 180:return 209;break;case 181:return 154;break;case 182:return 210;break;case 183:return 211;break;case 184:return 223;break;case 185:return 220;break;case 186:return 222;break;case 187:return 219;break;case 188:return 215;break;case 189:return 214;break;case 190:return 217;break;case 191:return 221;break;case 192:return 216;break;case 193:return 218;break;case 194:return 221;break;case 195:return 64;break;case 196:return 65;break;case 197:return 192;break;case 198:return 318;break;case 199:return 320;break;case 200:return 322;break;case 201:return 106;break;case 202:return 61;break;case 203:return 234;break;case 204:return 195;break;case 205:return 9;break;case 206:return 194;break;case 207:return 196;break;case 208:return 212;break;case 209:return 4;break;case 210:return 8;break;case 211:return"INVALID";break}},rules:[/^(?:``([^\`])+``)/i,/^(?:\[\?\])/i,/^(?:@\[)/i,/^(?:\[([^\]])*?\])/i,/^(?:`([^\`])*?`)/i,/^(?:N(['](\\.|[^']|\\')*?['])+)/i,/^(?:X(['](\\.|[^']|\\')*?['])+)/i,/^(?:(['](\\.|[^']|\\')*?['])+)/i,/^(?:(["](\\.|[^"]|\\")*?["])+)/i,/^(?:\/\*(.*?)\*\/)/i,/^(?:--(.*?)($|\r\n|\r|\n))/i,/^(?:\s+)/i,/^(?:\|\|)/i,/^(?:&&)/i,/^(?:ABSOLUTE\b)/i,/^(?:ACTION\b)/i,/^(?:ADD\b)/i,/^(?:AGGR\b)/i,/^(?:ALL\b)/i,/^(?:ALTER\b)/i,/^(?:AND\b)/i,/^(?:ANTI\b)/i,/^(?:ANY\b)/i,/^(?:APPLY\b)/i,/^(?:ARRAY\b)/i,/^(?:AS\b)/i,/^(?:ASSERT\b)/i,/^(?:ASC\b)/i,/^(?:ATTACH\b)/i,/^(?:AUTOINCREMENT\b)/i,/^(?:AUTO_INCREMENT\b)/i,/^(?:AVG\b)/i,/^(?:BEGIN\b)/i,/^(?:BETWEEN\b)/i,/^(?:BREAK\b)/i,/^(?:NOT\s+BETWEEN\b)/i,/^(?:NOT\s+LIKE\b)/i,/^(?:BY\b)/i,/^(?:CASE\b)/i,/^(?:CAST\b)/i,/^(?:CHARSET\b)/i,/^(?:CHECK\b)/i,/^(?:CLOSE\b)/i,/^(?:COLLATE\b)/i,/^(?:COLUMN\b)/i,/^(?:COLUMNS\b)/i,/^(?:COMMIT\b)/i,/^(?:CONSTRAINT\b)/i,/^(?:CONTINUE\b)/i,/^(?:CONVERT\b)/i,/^(?:COUNT\b)/i,/^(?:CREATE\b)/i,/^(?:CROSS\b)/i,/^(?:CUBE\b)/i,/^(?:CURRENT_TIMESTAMP\b)/i,/^(?:CURSOR\b)/i,/^(?:DATABASE\b)/i,/^(?:DATABASES\b)/i,/^(?:DECLARE\b)/i,/^(?:DEFAULT\b)/i,/^(?:DELETE\b)/i,/^(?:DELETED\b)/i,/^(?:DESC\b)/i,/^(?:DETACH\b)/i,/^(?:DISTINCT\b)/i,/^(?:DROP\b)/i,/^(?:END\b)/i,/^(?:ENGINE\b)/i,/^(?:ENUM\b)/i,/^(?:ELSE\b)/i,/^(?:EXCEPT\b)/i,/^(?:EXISTS\b)/i,/^(?:EXPLAIN\b)/i,/^(?:FALSE\b)/i,/^(?:FETCH\b)/i,/^(?:FIRST\b)/i,/^(?:FOREIGN\b)/i,/^(?:FROM\b)/i,/^(?:GO\b)/i,/^(?:GROUP\b)/i,/^(?:GROUPING\b)/i,/^(?:HAVING\b)/i,/^(?:HELP\b)/i,/^(?:IF\b)/i,/^(?:IDENTITY\b)/i,/^(?:IS\b)/i,/^(?:IN\b)/i,/^(?:INDEX\b)/i,/^(?:INNER\b)/i,/^(?:INSERT\b)/i,/^(?:INSERTED\b)/i,/^(?:INTERSECT\b)/i,/^(?:INTO\b)/i,/^(?:JOIN\b)/i,/^(?:KEY\b)/i,/^(?:LAST\b)/i,/^(?:LEFT\b)/i,/^(?:LIKE\b)/i,/^(?:LIMIT\b)/i,/^(?:SOURCE\b)/i,/^(?:MATCHED\b)/i,/^(?:MATRIX\b)/i,/^(?:MAX\b)/i,/^(?:MERGE\b)/i,/^(?:MIN\b)/i,/^(?:MINUS\b)/i,/^(?:MODIFY\b)/i,/^(?:NATURAL\b)/i,/^(?:NEXT\b)/i,/^(?:NEW\b)/i,/^(?:NOCASE\b)/i,/^(?:NO\b)/i,/^(?:NOT\b)/i,/^(?:NULL\b)/i,/^(?:OFF\b)/i,/^(?:ON\b)/i,/^(?:OFFSET\b)/i,/^(?:OPEN\b)/i,/^(?:OR\b)/i,/^(?:ORDER\b)/i,/^(?:OUTER\b)/i,/^(?:OVER\b)/i,/^(?:PARTITION\b)/i,/^(?:PERCENT\b)/i,/^(?:PLAN\b)/i,/^(?:PRIMARY\b)/i,/^(?:PRINT\b)/i,/^(?:PRIOR\b)/i,/^(?:QUERY\b)/i,/^(?:RECORDSET\b)/i,/^(?:REDUCE\b)/i,/^(?:REFERENCES\b)/i,/^(?:RELATIVE\b)/i,/^(?:RENAME\b)/i,/^(?:REQUIRE\b)/i,/^(?:RESTORE\b)/i,/^(?:RIGHT\b)/i,/^(?:ROLLBACK\b)/i,/^(?:ROLLUP\b)/i,/^(?:ROW\b)/i,/^(?:SCHEMA\b)/i,/^(?:SCHEMAS\b)/i,/^(?:SELECT\b)/i,/^(?:SEMI\b)/i,/^(?:SET\b)/i,/^(?:SETS\b)/i,/^(?:SHOW\b)/i,/^(?:SOME\b)/i,/^(?:STORE\b)/i,/^(?:SUM\b)/i,/^(?:TABLE\b)/i,/^(?:TABLES\b)/i,/^(?:TARGET\b)/i,/^(?:TD\b)/i,/^(?:TEXTSTRING\b)/i,/^(?:TH\b)/i,/^(?:THEN\b)/i,/^(?:TO\b)/i,/^(?:TOP\b)/i,/^(?:TRAN\b)/i,/^(?:TRANSACTION\b)/i,/^(?:TRUE\b)/i,/^(?:TRUNCATE\b)/i,/^(?:UNION\b)/i,/^(?:UNIQUE\b)/i,/^(?:UPDATE\b)/i,/^(?:USE\b)/i,/^(?:USING\b)/i,/^(?:VALUE\b)/i,/^(?:VALUES\b)/i,/^(?:VIEW\b)/i,/^(?:WHEN\b)/i,/^(?:WHERE\b)/i,/^(?:WHILE\b)/i,/^(?:WITH\b)/i,/^(?:WORK\b)/i,/^(?:(\d*[.])?\d+[eE]\d+)/i,/^(?:(\d*[.])?\d+)/i,/^(?:->)/i,/^(?:\+)/i,/^(?:-)/i,/^(?:\*)/i,/^(?:\/)/i,/^(?:%)/i,/^(?:!===)/i,/^(?:===)/i,/^(?:!==)/i,/^(?:==)/i,/^(?:>=)/i,/^(?:>)/i,/^(?:<=)/i,/^(?:<>)/i,/^(?:<)/i,/^(?:=)/i,/^(?:!=)/i,/^(?:\()/i,/^(?:\))/i,/^(?:@)/i,/^(?:\{)/i,/^(?:\})/i,/^(?:\])/i,/^(?:\.)/i,/^(?:,)/i,/^(?:::)/i,/^(?::)/i,/^(?:;)/i,/^(?:\$)/i,/^(?:\?)/i,/^(?:\^)/i,/^(?:[a-zA-Z_][a-zA-Z_0-9]*)/i,/^(?:$)/i,/^(?:.)/i],conditions:{INITIAL:{rules:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211],inclusive:true}}};return lexer}();parser.lexer=lexer;function Parser(){this.yy={}}Parser.prototype=parser;parser.Parser=Parser;return new Parser}();if(typeof require!=="undefined"&&typeof exports!=="undefined"){exports.parser=parser;exports.Parser=parser.Parser;exports.parse=function(){return parser.parse.apply(parser,arguments)};exports.main=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)};if(typeof module!=="undefined"&&require.main===module){exports.main(process.argv.slice(1))}}alasql.prettyflag=false;alasql.pretty=function(sql,flag){var pf=alasql.prettyflag;alasql.prettyflag=!flag;var s=alasql.parse(sql).toString();alasql.prettyflag=pf;return s};function K(s){if(alasql.prettyflag){return''+s.toUpperCase()+""}else{return s}}function P(s){if(alasql.prettyflag){return''+s+""}else{return s}}function L(s){if(alasql.prettyflag){return''+s+""}else{return s}}function N(s){if(alasql.prettyflag){return''+s+""}else{return s}}function S(s){if(alasql.prettyflag){return''+s+""}else{return s}}function NL(){if(alasql.prettyflag){return"
"}else{return" "}}function ID(){if(alasql.prettyflag){return"     "}else{return""}}var utils=alasql.utils={};function returnTrue(){return true}function returnUndefined(){}var escapeq=utils.escapeq=function(s){return s.replace(/\'/g,"\\'")};var escapeqq=utils.undoubleq=function(s){return s.replace(/(\')/g,"''")};var doubleq=utils.doubleq=function(s){return s.replace(/(\'\')/g,"\\'")};var doubleqq=utils.doubleqq=function(s){return s.replace(/\'/g,"'")};var cutbom=function(s){if(s[0]==String.fromCharCode(65279))s=s.substr(1);return s};var loadFile=utils.loadFile=function(path,asy,success,error){if(typeof exports=="object"){var fs=require("fs");if(!path){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(asy){fs.readFile(path,function(err,data){if(err){throw err}success(cutbom(data.toString()))})}else{var data=fs.readFileSync(path);success(cutbom(data.toString()))}}}else if(typeof cordova=="object"){window.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)})})})}else{if(typeof path=="string"){if(path.substr(0,1)=="#"&&typeof document!="undefined"){var data=document.querySelector(path).textContent;success(data)}else{var xhr=new XMLHttpRequest;xhr.onreadystatechange=function(){if(xhr.readyState===XMLHttpRequest.DONE){if(xhr.status===200){if(success)success(cutbom(xhr.responseText))}else{if(error)error(xhr)}}};xhr.open("GET",path,asy);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(cutbom(data))};reader.readAsText(files[0])}}};var loadBinaryFile=utils.loadBinaryFile=function(path,asy,success,error){if(typeof exports=="object"){var fs=require("fs");if(asy){fs.readFile(path,function(err,data){if(err){throw err}var arr=new Array;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=new Array;for(var i=0;i!=data.length;++i)arr[i]=String.fromCharCode(data[i]);success(arr.join(""))}}else{if(typeof path=="string"){var xhr=new XMLHttpRequest;xhr.open("GET",path,asy);xhr.responseType="arraybuffer";xhr.onload=function(){var data=new Uint8Array(xhr.response);var arr=new Array;for(var i=0;i!=data.length;++i)arr[i]=String.fromCharCode(data[i]);success(arr.join(""))};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.readAsBinaryString(files[0])}}};var removeFile=utils.removeFile=function(path,cb){if(typeof exports=="object"){var fs=require("fs");fs.remove(path,cb)}else if(typeof cordova=="object"){window.requestFileSystem(LocalFileSystem.PERSISTENT,0,function(fileSystem){fileSystem.root.getFile(path,{create:false},function(fileEntry){fileEntry.remove(cb);if(cb)cb()},function(){if(cb)cb()})})}else{throw new Error("You can remove files only in Node.js and Apache Cordova")}};var deleteFile=utils.deleteFile=function(path,cb){if(typeof exports=="object"){var fs=require("fs");fs.unlink(path,cb)}};var fileExists=utils.fileExists=function(path,cb){if(typeof exports=="object"){var fs=require("fs");fs.exists(path,cb)}else if(typeof cordova=="object"){window.requestFileSystem(LocalFileSystem.PERSISTENT,0,function(fileSystem){fileSystem.root.getFile(path,{create:false},function(fileEntry){cb(true)},function(){cb(false)})})}else{throw new Error("You can use exists() only in Node.js or Apach Cordova")}};var saveFile=utils.saveFile=function(path,data,cb){if(!path){alasql.options.stdout=true;console.log(data);if(cb)cb()}else{if(typeof exports=="object"){var fs=require("fs");var data=fs.writeFileSync(path,data);if(cb)cb()}else if(typeof cordova=="object"){window.requestFileSystem(LocalFileSystem.PERSISTENT,0,function(fileSystem){fileSystem.root.getFile(path,{create:true},function(fileEntry){fileEntry.createWriter(function(fileWriter){fileWriter.onwriteend=function(){if(cb)cb()};fileWriter.write(data)})})})}else{var blob=new Blob([data],{type:"text/plain;charset=utf-8"});saveAs(blob,path);if(cb)cb()}}};var hash=utils.hash=function hash(str){var h=0;if(str.length==0)return h;for(var i=0;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 xlscn=utils.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};var domEmptyChildren=utils.domEmptyChildren=function(container){var len=container.childNodes.length;while(len--){container.removeChild(container.lastChild)}};alasql.utils.uncomment=function uncomment(str){str=("__"+str+"__").split("");var quote=false,quoteSign,blockComment=false,lineComment=false;for(var i=0,l=str.length;ialasql.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{if(cb){alasql.adrun(databaseid,ast,params,cb,scope)}else{return alasql.drun(databaseid,ast,params,cb,scope)}}};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=0){var source=query.sources[idx];source.data=data;if(typeof source.data=="function"){source.getfn=source.data;source.dontcache=source.getfn.dontcache;if(source.joinmode=="OUTER"||source.joinmode=="RIGHT"||source.joinmode=="ANTI"){source.dontcache=false}source.data={}}}else{query.queriesdata[-idx-1]=flatArray(data)}query.sourceslen--;if(query.sourceslen>0)return;return queryfn3(query)}function queryfn3(query){var scope=query.scope;preIndex(query);query.data=[];query.xgroups={};query.groups=[];var h=0;doJoin(query,scope,h);if(query.groupfn){query.data=[];if(query.groups.length==0){var g={};if(query.selectGroup.length>0){query.selectGroup.forEach(function(sg){if(sg.aggregatorid=="COUNT"||sg.aggregatorid=="SUM"){g[sg.nick]=0}else{g[sg.nick]=undefined}})}query.groups=[g]}for(var i=0,ilen=query.groups.length;i0){for(var i=0,ilen=query.data.length;i0&&source.optimization=="ix"&&source.onleftfn&&source.onrightfn){if(source.databaseid&&alasql.databases[source.databaseid].tables[source.tableid]){if(!alasql.databases[source.databaseid].tables[source.tableid].indices)query.database.tables[source.tableid].indices={};var ixx=alasql.databases[source.databaseid].tables[source.tableid].indices[hash(source.onrightfns+"`"+source.srcwherefns)];if(!alasql.databases[source.databaseid].tables[source.tableid].dirty&&ixx){source.ix=ixx}}if(!source.ix){source.ix={};var scope={};var i=0;var ilen=source.data.length;var dataw;while((dataw=source.data[i])||source.getfn&&(dataw=source.getfn(i))||i=query.sources.length){if(query.wherefn(scope,query.params,alasql)){if(query.groupfn){query.groupfn(scope,query.params,query.alasql)}else{query.data.push(query.selectfn(scope,query.params,alasql))}}}else if(query.sources[h].applyselect){var source=query.sources[h];source.applyselect(query.params,function(data){if(data.length>0){for(var i=0;i0){s+=NL()+ID()+K("GROUP BY")+" "+this.group.map(function(grp){return grp.toString()}).join(", ")}if(this.having)s+=NL()+ID()+K("HAVING")+" "+this.having.toString();if(this.order&&this.order.length>0){s+=NL()+ID()+K("ORDER BY")+" "+this.order.map(function(ord){return ord.toString()}).join(", ")}if(this.limit)s+=NL()+ID()+K("LIMIT")+" "+this.limit.value;if(this.offset)s+=NL()+ID()+K("OFFSET")+" "+this.offset.value;if(this.union)s+=NL()+K("UNION")+NL()+this.union.toString();if(this.unionall)s+=NL()+K("UNION ALL")+NL()+this.unionall.toString();if(this.except)s+=NL()+K("EXCEPT")+NL()+this.except.toString();if(this.intersect)s+=NL()+K("INTERSECT")+NL()+this.intersect.toString();return s};yy.Select.prototype.toJavaScript=function(context,tableid,defcols){var s="alasql.utils.flatArray(this.queriesfn["+(this.queriesidx-1)+"](this.params,null,"+context+"))[0]";return s};yy.Select.prototype.compile=function(databaseid){var db=alasql.databases[databaseid];var query=new Query;query.removeKeys=[];query.explain=this.explain;query.explaination=[];query.explid=1;query.modifier=this.modifier;query.database=db;this.compileWhereExists(query);this.compileQueries(query);query.defcols=this.compileDefCols(query,databaseid);query.fromfn=this.compileFrom(query);if(this.joins)this.compileJoins(query);this.compileSelectGroup0(query);if(this.group||query.selectGroup.length>0){query.selectgfns=this.compileSelectGroup1(query)}else{query.selectfns=this.compileSelect1(query)}if(this.where)this.compileWhereJoins(query);query.wherefn=this.compileWhere(query);if(this.group||query.selectGroup.length>0)query.groupfn=this.compileGroup(query);if(this.having)query.havingfn=this.compileHaving(query);if(this.group||query.selectGroup.length>0){query.selectgfn=this.compileSelectGroup2(query)}else{query.selectfn=this.compileSelect2(query)}query.distinct=this.distinct;if(this.order)query.orderfn=this.compileOrder(query);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;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}}if(this.into){if(this.into instanceof yy.Table){if(alasql.options.autocommit&&alasql.databases[this.into.databaseid||databaseid].engineid){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{query.intofns="alasql.databases['"+(this.into.databaseid||databaseid)+"'].tables"+"['"+this.into.tableid+"'].data.push(r);"}}else if(this.into instanceof yy.VarValue){query.intoallfns='alasql.vars["'+this.into.variable+'"]=this.data;res=1;if(cb)res=cb(res);return res;'}else if(this.into instanceof yy.FuncValue){var qs="alasql.into['"+this.into.funcid.toUpperCase()+"'](";if(this.into.args&&this.into.args.length>0){qs+=this.into.args[0].toJavaScript()+",";if(this.into.args.length>1){qs+=this.into.args[1].toJavaScript()+","}else{qs+="null,"}}else{qs+="null, null,"}query.intoallfns=qs+"this.data,columns,cb)"}else if(this.into instanceof yy.ParamValue){query.intofns="params['"+this.into.param+"'].push(r)"}if(query.intofns){query.intofn=new Function("r,i,params,alasql",query.intofns)}if(query.intoallfns){query.intoallfn=new Function("columns,cb,alasql",query.intoallfns)}}var statement=function(params,cb,oldscope){query.params=params;var res1=queryfn(query,oldscope,function(res){var res2=modify(query,res);if(cb)cb(res2);return res2});return res1};statement.query=query;return statement};function modify(query,res){if(query.modifier=="VALUE"){if(res.length>0){var key;if(query.columns&&query.columns.length>0)key=query.columns[0].columnid;else key=Object.keys(res[0])[0];res=res[0][key]}else{res=undefined}}if(query.modifier=="ROW"){if(res.length>0){var key;if(query.columns&&query.columns.length>0)key=query.columns[0].columnid;else key=Object.keys(res[0])[0];var a=[];for(var key in res[0]){a.push(res[0][key])}res=a}else{res=undefined}}if(query.modifier=="COLUMN"){var ar=[];if(res.length>0){var key;if(query.columns&&query.columns.length>0)key=query.columns[0].columnid;else key=Object.keys(res[0])[0];for(var i=0,ilen=res.length;i0){key=query.columns[0].columnid;val=query.columns[1].columnid}else{var okeys=Object.keys(res[0]);key=okeys[0];val=okeys[1]}for(var i=0,ilen=res.length;i0)key=query.columns[0].columnid;else key=Object.keys(res[0])[0];var s="";for(var i=0,ilen=res.length;i0){if(tq.args[0]){s+=tq.args[0].toJavaScript("query.oldscope")+","}else{s+="null,"}if(tq.args[1]){s+=tq.args[1].toJavaScript("query.oldscope")+","}else{s+="null,"}}else{s+="null,null,"}s+="cb,idx,query";s+=");/*if(cb)res=cb(res,idx,query);*/return res";source.datafn=new Function("query, params, cb, idx, alasql",s)}else if(tq instanceof yy.FromData){source.datafn=function(query,params,cb,idx,alasql){var res=tq.data;if(cb)res=cb(res,idx,query);return res}}else{throw new Error("Wrong table at FROM")}query.sources.push(source)});query.defaultTableid=query.sources[0].alias};alasql.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;i0){if(jn.args[0]){s+=jn.args[0].toJavaScript("query.oldscope")+","}else{s+="null,"}if(jn.args[1]){s+=jn.args[1].toJavaScript("query.oldscope")+","}else{s+="null,"}}else{s+="null,null,"}s+="cb,idx,query";s+=");/*if(cb)res=cb(res,idx,query);*/return res";source.datafn=new Function("query, params, cb, idx, alasql",s);query.aliases[source.alias]={type:"funcvalue"}}var alias=source.alias;if(jn.natural){if(jn.using||jn.on){throw new Error("NATURAL JOIN cannot have USING or ON clauses")}else{if(query.sources.length>0){var prevSource=query.sources[query.sources.length-1];var prevTable=alasql.databases[prevSource.databaseid].tables[prevSource.tableid];var table=alasql.databases[source.databaseid].tables[source.tableid];if(prevTable&&table){var c1=prevTable.columns.map(function(col){return col.columnid});var c2=table.columns.map(function(col){return col.columnid});jn.using=arrayIntersect(c1,c2).map(function(colid){return{columnid:colid}})}else{throw new Error("In this version of Alasql NATURAL JOIN "+"works for tables with predefined columns only")}}}}if(jn.using){var prevSource=query.sources[query.sources.length-1];source.onleftfns=jn.using.map(function(col){return"p['"+(prevSource.alias||prevSource.tableid)+"']['"+col.columnid+"']"}).join('+"`"+');source.onleftfn=new Function("p,params,alasql","return "+source.onleftfns);source.onrightfns=jn.using.map(function(col){return"p['"+(source.alias||source.tableid)+"']['"+col.columnid+"']"}).join('+"`"+');source.onrightfn=new Function("p,params,alasql","return "+source.onrightfns);source.optimization="ix"}else if(jn.on){if(jn.on instanceof yy.Op&&jn.on.op=="="&&!jn.on.allsome){source.optimization="ix";var lefts="";var rights="";var middles="";var middlef=false;var ls=jn.on.left.toJavaScript("p",query.defaultTableid,query.defcols);var rs=jn.on.right.toJavaScript("p",query.defaultTableid,query.defcols);if(ls.indexOf("p['"+alias+"']")>-1&&!(rs.indexOf("p['"+alias+"']")>-1)){if((ls.match(/p\[\'.*?\'\]/g)||[]).every(function(s){return s=="p['"+alias+"']"})){rights=ls}else{middlef=true}}else if(!(ls.indexOf("p['"+alias+"']")>-1)&&rs.indexOf("p['"+alias+"']")>-1){if((rs.match(/p\[\'.*?\'\]/g)||[]).every(function(s){return s=="p['"+alias+"']"})){lefts=ls}else{middlef=true}}else{middlef=true}if(rs.indexOf("p['"+alias+"']")>-1&&!(ls.indexOf("p['"+alias+"']")>-1)){if((rs.match(/p\[\'.*?\'\]/g)||[]).every(function(s){return s=="p['"+alias+"']"})){rights=rs}else{middlef=true}}else if(!(rs.indexOf("p['"+alias+"']")>-1)&&ls.indexOf("p['"+alias+"']")>-1){if((ls.match(/p\[\'.*?\'\]/g)||[]).every(function(s){return s=="p['"+alias+"']"})){lefts=rs}else{middlef=true}}else{middlef=true}if(middlef){rights="";lefts="";middles=jn.on.toJavaScript("p",query.defaultTableid,query.defcols);source.optimization="no"}source.onleftfns=lefts;source.onrightfns=rights;source.onmiddlefns=middles||"true";source.onleftfn=new Function("p,params,alasql","return "+source.onleftfns);source.onrightfn=new Function("p,params,alasql","return "+source.onrightfns);source.onmiddlefn=new Function("p,params,alasql","return "+source.onmiddlefns)}else{source.optimization="no";source.onmiddlefns=jn.on.toJavaScript("p",query.defaultTableid,query.defcols);source.onmiddlefn=new Function("p,params,alasql","return "+jn.on.toJavaScript("p",query.defaultTableid,query.defcols))}}query.sources.push(source)}})};yy.Select.prototype.compileWhere=function(query){if(this.where){if(typeof this.where=="function"){return this.where}else{s=this.where.toJavaScript("p",query.defaultTableid,query.defcols);query.wherefns=s;return new Function("p,params,alasql","return "+s)}}else return function(){return true}};yy.Select.prototype.compileWhereJoins=function(query){return;optimizeWhereJoin(query,this.where.expression);query.sources.forEach(function(source){if(source.srcwherefns){source.srcwherefn=new Function("p,params,alasql","return "+source.srcwherefns)}if(source.wxleftfns){source.wxleftfn=new Function("p,params,alasql","return "+source.wxleftfns)}if(source.wxrightfns){source.wxrightfn=new Function("p,params,alasql","return "+source.wxrightfns)}})};function optimizeWhereJoin(query,ast){if(!ast)return false;if(!(ast instanceof yy.Op))return;if(ast.op!="="&&ast.op!="AND")return;if(ast.allsome)return;var s=ast.toJavaScript("p",query.defaultTableid,query.defcols);var fsrc=[];query.sources.forEach(function(source,idx){if(source.tableid){if(s.indexOf("p['"+source.alias+"']")>-1)fsrc.push(source)}});if(fsrc.length==0){return}else if(fsrc.length==1){if(!(s.match(/p\[\'.*?\'\]/g)||[]).every(function(s){return s=="p['"+fsrc[0].alias+"']"})){return}var src=fsrc[0];src.srcwherefns=src.srcwherefns?src.srcwherefns+"&&"+s:s;if(ast instanceof yy.Op&&(ast.op=="="&&!ast.allsome)){if(ast.left instanceof yy.Column){var ls=ast.left.toJavaScript("p",query.defaultTableid,query.defcols);var rs=ast.right.toJavaScript("p",query.defaultTableid,query.defcols);if(rs.indexOf("p['"+fsrc[0].alias+"']")==-1){fsrc[0].wxleftfns=ls;fsrc[0].wxrightfns=rs}}if(ast.right instanceof yy.Column){var ls=ast.left.toJavaScript("p",query.defaultTableid,query.defcols);var rs=ast.right.toJavaScript("p",query.defaultTableid,query.defcols);if(ls.indexOf("p['"+fsrc[0].alias+"']")==-1){fsrc[0].wxleftfns=rs;fsrc[0].wxrightfns=ls}}}ast.reduced=true;return}else{if(ast.op="AND"){optimizeWhereJoin(query,ast.left);optimizeWhereJoin(query,ast.right)}}}yy.Select.prototype.compileGroup=function(query){var self=this;var tableid=query.sources[0].alias;var defcols=query.defcols;var allgroup=[[]]; -if(this.group){allgroup=decartes(this.group,query)}var allgroups=[];allgroup.forEach(function(a){allgroups=arrayUnion(allgroups,a)});query.allgroups=allgroups;if(false){allgroups.forEach(function(col2){if(query.selectColumns[colid]){}else{var tmpid="default";if(query.sources.length>0)tmpid=query.sources[0].alias;if(Object.keys(query.selectColumns).length!=0)query.removeKeys.push(colid);query.selectfns+="r['"+escapeq(colid)+"']="+new yy.Column({columnid:colid}).toJavaScript("p",tmpid)+";"}})}var s="";allgroup.forEach(function(agroup){s+="var g=this.xgroups[";var rg=agroup.map(function(col2){var columnid=col2.split(" ")[0];var coljs=col2.split(" ")[1];if(columnid=="")return"1";else 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(" ")[0];var coljs=col2.split(" ")[1];if(columnid=="")return"";else return"'"+columnid+"':"+coljs+","}).join("");var neggroup=arrayDiff(allgroups,agroup);s+=neggroup.map(function(col2){var columnid=col2.split(" ")[0];var coljs=col2.split(" ")[1];return"'"+columnid+"':null,"}).join("");var aft="";s+=query.selectGroup.map(function(col,idx){var colexp=col.expression.toJavaScript("p",tableid,defcols);var colas=col.nick;if(col instanceof yy.AggrValue){if(col.distinct){aft+=",g['$$_VALUES_"+colas+"']={},g['$$_VALUES_"+colas+"']["+colexp+"]=true"}if(col.aggregatorid=="SUM"||col.aggregatorid=="MIN"||col.aggregatorid=="MAX"||col.aggregatorid=="FIRST"||col.aggregatorid=="LAST"){return"'"+colas+"':"+colexp+","}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+",'_COUNT_"+colas+"':1,"}else if(col.aggregatorid=="AGGR"){aft+=",g['"+colas+"']="+col.expression.toJavaScript("g",-1);return""}else if(col.aggregatorid=="REDUCE"){return"'"+colas+"':alasql.aggr['"+col.funcid+"']("+colexp+"),"}return""}else return""}).join("");s+="}"+aft+",g));} else {";s+=query.selectGroup.map(function(col,idx){var colas=col.nick;var colexp=col.expression.toJavaScript("p",tableid,defcols);if(col instanceof yy.AggrValue){if(col.distinct){var pre="if(typeof "+colexp+'!="undefined" && (!g[\'$$_VALUES_'+colas+"']["+colexp+"])) {";var post="g['$$_VALUES_"+colas+"']["+colexp+"]=true;}"}else{var pre="",post=""}if(col.aggregatorid=="SUM"){return pre+"g['"+colas+"']+="+colexp+";"+post}else if(col.aggregatorid=="COUNT"){if(col.expression.columnid=="*")return pre+"g['"+colas+"']++;"+post;else{return pre+"if(typeof "+colexp+'!="undefined") g[\''+colas+"']++;"+post}}else if(col.aggregatorid=="ARRAY"){return pre+"g['"+colas+"'].push("+colexp+");"+post}else if(col.aggregatorid=="MIN"){return pre+"g['"+colas+"']=Math.min(g['"+colas+"'],"+colexp+");"+post}else if(col.aggregatorid=="MAX"){return pre+"g['"+colas+"']=Math.max(g['"+colas+"'],"+colexp+");"+post}else if(col.aggregatorid=="FIRST"){return""}else if(col.aggregatorid=="LAST"){return pre+"g['"+colas+"']="+colexp+";"+post}else if(col.aggregatorid=="AVG"){return pre+"g['_SUM_"+colas+"']+="+colexp+";"+"g['_COUNT_"+colas+"']++;"+"g['"+colas+"']=g['_SUM_"+colas+"']/g['_COUNT_"+colas+"'];"+post}else if(col.aggregatorid=="AGGR"){return pre+"g['"+colas+"']="+col.expression.toJavaScript("g",-1)+";"+post}else if(col.aggregatorid=="REDUCE"){return pre+"g['"+colas+"']=alasql.aggr."+col.funcid+"("+colexp+",g['"+colas+"']);"+post}return""}else return""}).join("");s+="}"});return new Function("p,params,alasql",s)};function compileSelectStar(query,alias){var s="",sp="",ss=[];if(query.aliases[alias].tableid){var columns=alasql.databases[query.aliases[alias].databaseid].tables[query.aliases[alias].tableid].columns}if(columns&&columns.length>0){columns.forEach(function(tcol){ss.push("'"+tcol.columnid+"':p['"+alias+"']['"+tcol.columnid+"']");query.selectColumns[escapeq(tcol.columnid)]=true;var coldef={columnid:tcol.columnid,dbtypeid:tcol.dbtypeid,dbsize:tcol.dbsize,dbprecision:tcol.dbprecision,dbenum:tcol.dbenum};query.columns.push(coldef);query.xcolumns[coldef.columnid]=coldef})}else{sp+='var w=p["'+alias+'"];for(var k in w){r[k]=w[k]};';query.dirtyColumns=true}return{s:ss.join(","),sp:sp}}yy.Select.prototype.compileSelect1=function(query){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){var ret=compileSelectStar(query,col.tableid);if(ret.s)ss=ss.concat(ret.s);sp+=ret.sp}else{for(var alias in query.aliases){var ret=compileSelectStar(query,alias);if(ret.s)ss=ss.concat(ret.s);sp+=ret.sp}}}else{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!="_"){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];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{query.dirtyColumns=true}}else{}}}else if(col instanceof yy.AggrValue){if(!self.group){self.group=[""]}if(!col.as)col.as=escapeq(col.toString());if(col.aggregatorid=="SUM"||col.aggregatorid=="MAX"||col.aggregatorid=="MIN"||col.aggregatorid=="FIRST"||col.aggregatorid=="LAST"||col.aggregatorid=="AVG"||col.aggregatorid=="ARRAY"||col.aggregatorid=="REDUCE"){ss.push("'"+escapeq(col.as)+"':"+col.expression.toJavaScript("p",query.defaultTableid,query.defcols))}else if(col.aggregatorid=="COUNT"){ss.push("'"+escapeq(col.as)+"':1")}query.selectColumns[col.aggregatorid+"("+escapeq(col.expression.toString())+")"]=thtd}else{ss.push("'"+escapeq(col.as||col.columnid||col.toString())+"':"+col.toJavaScript("p",query.defaultTableid,query.defcols));query.selectColumns[escapeq(col.as||col.columnid||col.toString())]=true}});s+=ss.join(",")+"};"+sp;return s};yy.Select.prototype.compileSelect2=function(query){var s=query.selectfns;return new Function("p,params,alasql",s+"return r")};yy.Select.prototype.compileSelectGroup0=function(query){var self=this;self.columns.forEach(function(col,idx){if(col instanceof yy.Column&&col.columnid=="*"){}else{var colas;if(col instanceof yy.Column){colas=escapeq(col.columnid)}else{colas=escapeq(col.toString())}for(var i=0;irb)return 1;if(ra==rb)return 0;return-1}}var s="";var sk="";this.order.forEach(function(ord,idx){var dg="";if(ord.expression instanceof yy.NumValue){ord.expression=self.columns[ord.expression.value-1]}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")dg=".valueOf()"}else{if(alasql.options.valueof)dg=".valueOf()"}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()";if(ord.nocase)dg+=".toUpperCase()";s+="if("+ord.toJavaScript("a","")+dg+(ord.direction=="ASC"?">":"<")+ord.toJavaScript("b","")+dg+")return 1;";s+="if("+ord.toJavaScript("a","")+dg+"=="+ord.toJavaScript("b","")+dg+"){"}sk+="}"});s+="return 0;";s+=sk+"return -1";query.orderfns=s;return new Function("a,b",s)}};var rollup=function(a,query){var rr=[];var mask=0;var glen=a.length;for(var g=0;g"){var s=this.left.toString()+"->";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()+" "+P(this.op)+" "+(this.allsome?this.allsome+" ":"")+this.right.toString()};yy.Op.prototype.findAggregator=function(query){if(this.left&&this.left.findAggregator)this.left.findAggregator(query);if(this.right&&this.right.findAggregator&&!this.allsome){this.right.findAggregator(query)}};yy.Op.prototype.toType=function(tableid){if(["-","*","/","%","^"].indexOf(this.op)>-1)return"number";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"].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"};yy.Op.prototype.toJavaScript=function(context,tableid,defcols){var op=this.op;if(this.op=="=")op="===";else if(this.op=="<>")op="!=";else if(this.op=="OR")op="||";if(this.op=="->"){if(typeof this.right=="string"){return this.left.toJavaScript(context,tableid,defcols)+'["'+this.right+'"]'}else if(typeof this.right=="number"){return this.left.toJavaScript(context,tableid,defcols)+"["+this.right+"]"}else if(this.right instanceof yy.FuncValue){ss=[];if(!this.right.args||this.right.args.length==0){}else{var ss=this.right.args.map(function(arg){return arg.toJavaScript(context,tableid,defcols)})}return this.left.toJavaScript(context,tableid,defcols)+"['"+this.right.funcid+"']("+ss.join(",")+")"}else{return this.left.toJavaScript(context,tableid,defcols)+"["+this.right.toJavaScript(context,tableid,defcols)+"]"}}if(this.op=="IS"){return"((typeof "+this.left.toJavaScript(context,tableid,defcols)+"=='undefined') == "+"(typeof "+this.right.toJavaScript(context,tableid,defcols)+"=='undefined'))"}if(this.op=="=="){return"alasql.utils.deepEqual("+this.left.toJavaScript(context,tableid,defcols)+","+this.right.toJavaScript(context,tableid,defcols)+")"}if(this.op=="==="){return"(("+this.left.toJavaScript(context,tableid,defcols)+").valueOf()===("+this.right.toJavaScript(context,tableid,defcols)+".valueOf()))"}if(this.op=="!==="){return"!(("+this.left.toJavaScript(context,tableid,defcols)+").valueOf()===("+this.right.toJavaScript(context,tableid,defcols)+".valueOf()))"}if(this.op=="!=="){return"(!alasql.utils.deepEqual("+this.left.toJavaScript(context,tableid,defcols)+","+this.right.toJavaScript(context,tableid,defcols)+"))"}if(this.op=="LIKE"){var s="("+this.left.toJavaScript(context,tableid,defcols)+"+'')"+".toUpperCase().match(new RegExp('^'+("+this.right.toJavaScript(context,tableid,defcols)+").replace(/\\%/g,'.*').toUpperCase()+'$','g'))";return s}if(this.op=="NOT LIKE"){var s="!(("+this.left.toJavaScript(context,tableid,defcols)+"+'')"+".toUpperCase().match(new RegExp('^'+("+this.right.toJavaScript(context,tableid,defcols)+").replace(/\\%/g,'.*').toUpperCase()+'$','g')))";return s}if(this.op=="BETWEEN"){if(this.right instanceof yy.Op&&this.right.op=="AND"){return"(("+this.right.left.toJavaScript(context,tableid,defcols)+"<="+this.left.toJavaScript(context,tableid,defcols)+")&&"+"("+this.left.toJavaScript(context,tableid,defcols)+"<="+this.right.right.toJavaScript(context,tableid,defcols)+"))"}else{throw new Error("Wrong BETWEEN operator without AND part")}}if(this.op=="NOT BETWEEN"){if(this.right instanceof yy.Op&&this.right.op=="AND"){return"!(("+this.right.left.toJavaScript(context,tableid,defcols)+"<="+this.left.toJavaScript(context,tableid,defcols)+")&&"+"("+this.left.toJavaScript(context,tableid,defcols)+"<="+this.right.right.toJavaScript(context,tableid,defcols)+"))"}else{throw new Error("Wrong NOT BETWEEN operator without AND part")}}if(this.op=="IN"){if(this.right instanceof yy.Select){var s="(";s+="alasql.utils.flatArray(this.query.queriesfn["+this.queriesidx+"](params,null,p))";s+=".indexOf(";s+=this.left.toJavaScript(context,tableid,defcols)+")>-1)";return s}else if(this.right instanceof Array){var s="(["+this.right.map(function(a){return a.toJavaScript(context,tableid,defcols)}).join(",")+"].indexOf(";s+=this.left.toJavaScript(context,tableid,defcols)+")>-1)";return s}else{var s="("+this.right.toJavaScript(context,tableid,defcols)+".indexOf(";s+=this.left.toJavaScript(context,tableid,defcols)+")>-1)";return s}}if(this.op=="NOT IN"){if(this.right instanceof yy.Select){var s="(";s+="alasql.utils.flatArray(this.query.queriesfn["+this.queriesidx+"](params,null,p))";s+=".indexOf(";s+=this.left.toJavaScript(context,tableid,defcols)+")<0)";return s}else if(this.right instanceof Array){var s="(["+this.right.map(function(a){return a.toJavaScript(context,tableid,defcols)}).join(",")+"].indexOf(";s+=this.left.toJavaScript(context,tableid,defcols)+")<0)";return s}else{throw new Error("Wrong NOT IN operator without SELECT part")}}if(this.allsome=="ALL"){if(this.right instanceof yy.Select){var s="alasql.utils.flatArray(this.query.queriesfn["+this.queriesidx+"](params,null,p))";s+=".every(function(b){return (";s+=this.left.toJavaScript(context,tableid,defcols)+")"+op+"b})";return s}else if(this.right instanceof Array){var s="["+this.right.map(function(a){return a.toJavaScript(context,tableid,defcols)}).join(",")+"].every(function(b){return (";s+=this.left.toJavaScript(context,tableid,defcols)+")"+op+"b})";return s}else{throw new Error("Wrong NOT IN operator without SELECT part")}}if(this.allsome=="SOME"||this.allsome=="ANY"){if(this.right instanceof yy.Select){var s="alasql.utils.flatArray(this.query.queriesfn["+this.queriesidx+"](params,null,p))";s+=".some(function(b){return (";s+=this.left.toJavaScript(context,tableid,defcols)+")"+op+"b})";return s}else if(this.right instanceof Array){var s="["+this.right.map(function(a){return a.toJavaScript(context,tableid,defcols)}).join(",")+"].some(function(b){return (";s+=this.left.toJavaScript(context,tableid,defcols)+")"+op+"b})";return s}else{throw new Error("Wrong NOT IN operator without SELECT part")}}if(this.op=="AND"){if(this.left.reduced){if(this.right.reduced){return"true"}else{return this.right.toJavaScript(context,tableid,defcols)}}else if(this.right.reduced){return this.left.toJavaScript(context,tableid,defcols)}op="&&"}if(this.op=="^"){return"Math.pow("+this.left.toJavaScript(context,tableid,defcols)+","+this.right.toJavaScript(context,tableid,defcols)+")"}return"("+this.left.toJavaScript(context,tableid,defcols)+op+this.right.toJavaScript(context,tableid,defcols)+")"};yy.VarValue=function(params){return yy.extend(this,params)};yy.VarValue.prototype.toString=function(){return"@"+L(this.variable)};yy.VarValue.prototype.toType=function(){return"unknown"};yy.VarValue.prototype.toJavaScript=function(){return"alasql.vars['"+this.variable+"']"};yy.NumValue=function(params){return yy.extend(this,params)};yy.NumValue.prototype.toString=function(){return N(this.value.toString())};yy.NumValue.prototype.toType=function(){return"number"};yy.NumValue.prototype.toJavaScript=function(){return""+this.value};yy.StringValue=function(params){return yy.extend(this,params)};yy.StringValue.prototype.toString=function(){return"'"+S(this.value.toString())+"'"};yy.StringValue.prototype.toType=function(){return"string"};yy.StringValue.prototype.toJavaScript=function(){return"'"+escapeq(this.value)+"'"};yy.LogicValue=function(params){return yy.extend(this,params)};yy.LogicValue.prototype.toString=function(){return this.value?"TRUE":"FALSE"};yy.LogicValue.prototype.toType=function(){return"boolean"};yy.LogicValue.prototype.toJavaScript=function(){return this.value?"true":"false"};yy.NullValue=function(params){return yy.extend(this,params)};yy.NullValue.prototype.toString=function(){return"NULL"};yy.NullValue.prototype.toJavaScript=function(){return"undefined"};yy.ParamValue=function(params){return yy.extend(this,params)};yy.ParamValue.prototype.toString=function(){return"$"+this.param};yy.ParamValue.prototype.toJavaScript=function(){if(typeof this.param=="string")return"params['"+this.param+"']";else return"params["+this.param+"]"};yy.UniOp=function(params){return yy.extend(this,params)};yy.UniOp.prototype.toString=function(){if(this.op=="-")return this.op+this.right.toString();if(this.op=="+")return this.op+this.right.toString();if(this.op=="NOT")return this.op+"("+this.right.toString()+")";else if(this.op==null)return"("+this.right.toString()+")"};yy.UniOp.prototype.findAggregator=function(query){if(this.right.findAggregator)this.right.findAggregator(query)};yy.UniOp.prototype.toType=function(tableid){if(this.op=="-")return"number";if(this.op=="+")return"number";if(this.op=="NOT")return"boolean"};yy.UniOp.prototype.toJavaScript=function(context,tableid,defcols){if(this.op=="-")return"(-("+this.right.toJavaScript(context,tableid,defcols)+"))";if(this.op=="+")return"("+this.right.toJavaScript(context,tableid,defcols)+")";if(this.op=="NOT")return"!("+this.right.toJavaScript(context,tableid,defcols)+")";else if(this.op==null)return"("+this.right.toJavaScript(context,tableid,defcols)+")"};yy.Column=function(params){return yy.extend(this,params)};yy.Column.prototype.toString=function(){var s;if(this.columnid==+this.columnid){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}}return s};yy.Column.prototype.toJavaScript=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"){s="g['"+this.nick+"']"}else if(this.tableid){if(this.columnid!="_"){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!="_"){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)+"']"}}}return s};yy.AggrValue=function(params){return yy.extend(this,params)};yy.AggrValue.prototype.toString=function(){var s="";if(this.aggregatorid=="REDUCE")s+=L(this.funcid)+"(";else s+=this.aggregatorid+"(";if(this.distinct)s+=K("DISTINCT")+" ";if(this.expression)s+=this.expression.toString();s+=")";if(this.over)s+=" "+this.over.toString();return s};yy.AggrValue.prototype.findAggregator=function(query){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-1)return"number";if(["ARRAY"].indexOf(this.aggregatorid)>-1)return"array";if(["FIRST","LAST"].indexOf(this.aggregatorid)>-1)return this.expression.toType()};yy.AggrValue.prototype.toJavaScript=function(context,tableid,defcols){var colas=this.nick;if(typeof colas=="undefined")colas=this.toString();return"g['"+colas+"']"};yy.OrderExpression=function(params){return yy.extend(this,params)};yy.OrderExpression.prototype.toString=function(){var s=this.expression.toString();if(this.order)s+=" "+this.order.toString();if(this.nocase)s+=" "+K("COLLATE")+" "+K("NOCASE");return s};yy.GroupExpression=function(params){return yy.extend(this,params)};yy.GroupExpression.prototype.toString=function(){return this.type+"("+this.group.toString()+")"};yy.ColumnDef=function(params){return yy.extend(this,params)};yy.ColumnDef.prototype.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};yy.FromData=function(params){return yy.extend(this,params)};yy.FromData.prototype.toString=function(){if(this.data)return K("DATA")+"("+(Math.random()*1e16|0)+")";else return"?"};yy.FromData.prototype.toJavaScript=function(){};yy.Select.prototype.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;if(db.sqlCacheSize>alasql.MAXSQLCACHESIZE){db.resetSqlCache()}db.sqlCacheSize++;db.sqlCache[hh]=statement;var res=alasql.res=statement(params,cb);return res};yy.Select.prototype.Select=function(){var self=this;var agrs=[];if(arguments.length>1){args=Array.prototype.slice.call(arguments)}else if(arguments.length==1){if(arguments[0]instanceof Array){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{}});return self};yy.Select.prototype.From=function(tableid){var self=this;if(!self.from)self.from=[];if(tableid instanceof Array){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};yy.Select.prototype.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(arguments[0]instanceof Array){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};yy.Select.prototype.Top=function(topnum){var self=this;self.top=new yy.NumValue({value:topnum});return self};yy.Select.prototype.GroupBy=function(){var self=this;var agrs=[];if(arguments.length>1){args=Array.prototype.slice.call(arguments) -}else if(arguments.length==1){if(arguments[0]instanceof Array){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};yy.Select.prototype.Where=function(expr){var self=this;if(typeof expr=="function"){self.where=expr}return self};yy.FuncValue=function(params){return yy.extend(this,params)};yy.FuncValue.prototype.toString=function(){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)s+=" AS "+this.as.toString();return s};yy.FuncValue.prototype.findAggregator=function(query){if(this.args&&this.args.length>0){this.args.forEach(function(arg){if(arg.findAggregator)arg.findAggregator(query)})}};yy.FuncValue.prototype.toJavaScript=function(context,tableid,defcols){var s="";var funcid=this.funcid;if(alasql.fn[funcid]){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.toJavaScript(context,tableid,defcols)}).join(",")}s+=")"}else if(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.toJavaScript(context,tableid)}))}else{s+=alasql.stdlib[funcid.toUpperCase()]()}}else if(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.toJavaScript(context,tableid,defcols)}).join(",")}s+=")"}else{}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+")"};stdlib.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")}};stdlib.IFNULL=function(a,b){return"("+a+"||"+b+")"};stdlib.INSTR=function(s,p){return"(("+s+").indexOf("+p+")+1)"};stdlib.LEN=stdlib.LENGTH=function(s){return"("+s+'+"").length'};stdlib.LOWER=stdlib.LCASE=function(s){return"("+s+").toLowerCase()"};stdlib.GREATEST=function(){return"Math.max("+Array.prototype.join.call(arguments,",")+")"};stdlib.LEAST=function(){return"Math.min("+Array.prototype.join.call(arguments,",")+")"};stdlib.MID=function(a,b,c){if(arguments.length==2)return"("+a+").substr("+b+"-1)";else if(arguments.length==3)return"("+a+").substr("+b+"-1,"+c+")"};stdlib.NULLIF=function(a,b){return"("+a+"=="+b+"?null:"+a+")"};stdlib.POWER=function(a,b){return"Math.pow("+a+","+b+")"};stdlib.RANDOM=function(r){if(arguments.length==0){return"Math.random()"}else{return"(Math.random()*("+r+")|0)"}};stdlib.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+")"}};stdlib.SQRT=function(s){return"Math.sqrt("+s+")"};stdlib.TRIM=function(s){return s+".trim()"};stdlib.UPPER=stdlib.UCASE=function(s){return"("+s+").toUpperCase()"};alasql.aggr.GROUP_CONCAT=function(v,s){if(typeof s=="undefined")return v;else return s+","+v};yy.CaseValue=function(params){return yy.extend(this,params)};yy.CaseValue.prototype.toString=function(){var s="CASE ";if(this.expression)s+=this.expression.toString();if(this.whens){s+=this.whens.map(function(w){return" WHEN "+w.when.toString()+" THEN "+w.then.toString()}).join()}s+=" END";return s};yy.CaseValue.prototype.findAggregator=function(query){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)})}};yy.CaseValue.prototype.toJavaScript=function(context,tableid,defcols){var s="(function("+context+",params,alasql){var r;";if(this.expression){s+="v="+this.expression.toJavaScript(context,tableid,defcols)+";";s+=(this.whens||[]).map(function(w){return" if(v=="+w.when.toJavaScript(context,tableid,defcols)+") {r="+w.then.toJavaScript(context,tableid,defcols)+"}"}).join(" else ");if(this.elses)s+=" else {r="+this.elses.toJavaScript(context,tableid,defcols)+"}"}else{s+=(this.whens||[]).map(function(w){return" if("+w.when.toJavaScript(context,tableid,defcols)+") {r="+w.then.toJavaScript(context,tableid,defcols)+"}"}).join(" else ");if(this.elses)s+=" else {r="+this.elses.toJavaScript(context,tableid,defcols)+"}"}s+="return r;})("+context+",params,alasql)";return s};yy.Json=function(params){return yy.extend(this,params)};yy.Json.prototype.toString=function(){var s="@";s+=JSONtoString(this.value);s+="";return s};var JSONtoString=alasql.utils.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(obj instanceof Array){s+="["+obj.map(function(b){return JSONtoString(b)}).join(",")+"]"}else if(!obj.toJavaScript||obj instanceof yy.Json){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};function JSONtoJavaScript(obj,context,tableid,defcols){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(obj instanceof Array){s+="["+obj.map(function(b){return JSONtoJavaScript(b,context,tableid,defcols)}).join(",")+"]"}else if(!obj.toJavaScript||obj instanceof yy.Json){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+=":"+JSONtoJavaScript(obj[k],context,tableid,defcols);ss.push(s1)}s+=ss.join(",")+"}"}else if(obj.toJavaScript){s=obj.toJavaScript(context,tableid,defcols)}else{throw new Error("1Can not parse JSON object "+JSON.stringify(obj))}}else{throw new Error("2Can not parse JSON object "+JSON.stringify(obj))}return s}yy.Json.prototype.toJavaScript=function(context,tableid,defcols){return JSONtoJavaScript(this.value,context,tableid,defcols)};yy.Convert=function(params){return yy.extend(this,params)};yy.Convert.prototype.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};yy.Convert.prototype.toJavaScript=function(context,tableid,defcols){return"alasql.stdfn.CONVERT("+this.expression.toJavaScript(context,tableid,defcols)+',{dbtypeid:"'+this.dbtypeid+'",dbsize:'+this.dbsize+",style:"+this.style+"})";throw new Error("There is not such type conversion for "+this.toString())};alasql.stdfn.CONVERT=function(value,args){var val=value;if(args.style){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);if(args.style==1){val=("0"+(t.getMonth()+1)).substr(-2)+"/"+("0"+t.getDate()).substr(-2)+"/"+("0"+t.getYear()).substr(-2)}else if(args.style==2){val=("0"+t.getYear()).substr(-2)+"."+("0"+(t.getMonth()+1)).substr(-2)+"."+("0"+t.getDate()).substr(-2)}else if(args.style==3){val=("0"+t.getDate()).substr(-2)+"/"+("0"+(t.getMonth()+1)).substr(-2)+"/"+("0"+t.getYear()).substr(-2)}else if(args.style==4){val=("0"+t.getDate()).substr(-2)+"."+("0"+(t.getMonth()+1)).substr(-2)+"."+("0"+t.getYear()).substr(-2)}else if(args.style==5){val=("0"+t.getDate()).substr(-2)+"-"+("0"+(t.getMonth()+1)).substr(-2)+"-"+("0"+t.getYear()).substr(-2)}else if(args.style==6){val=("0"+t.getDate()).substr(-2)+" "+t.toString().substr(4,3).toLowerCase()+" "+("0"+t.getYear()).substr(-2)}else if(args.style==7){val=t.toString().substr(4,3)+" "+("0"+t.getDate()).substr(-2)+","+("0"+t.getYear()).substr(-2)}else if(args.style==8){val=("0"+t.getHours()).substr(-2)+":"+("0"+(t.getMinutes()+1)).substr(-2)+":"+("0"+t.getSeconds()).substr(-2)}else if(args.style==10){val=("0"+(t.getMonth()+1)).substr(-2)+"-"+("0"+t.getDate()).substr(-2)+"-"+("0"+t.getYear()).substr(-2)}else if(args.style==11){val=("0"+t.getYear()).substr(-2)+"/"+("0"+(t.getMonth()+1)).substr(-2)+"/"+("0"+t.getDate()).substr(-2)}else if(args.style==12){val=("0"+t.getYear()).substr(-2)+("0"+(t.getMonth()+1)).substr(-2)+("0"+t.getDate()).substr(-2)}else if(args.style==101){val=("0"+(t.getMonth()+1)).substr(-2)+"/"+("0"+t.getDate()).substr(-2)+"/"+t.getFullYear()}else if(args.style==102){val=t.getFullYear()+"."+("0"+(t.getMonth()+1)).substr(-2)+"."+("0"+t.getDate()).substr(-2)}else if(args.style==103){val=("0"+t.getDate()).substr(-2)+"/"+("0"+(t.getMonth()+1)).substr(-2)+"/"+t.getFullYear()}else if(args.style==104){val=("0"+t.getDate()).substr(-2)+"."+("0"+(t.getMonth()+1)).substr(-2)+"."+t.getFullYear()}else if(args.style==105){val=("0"+t.getDate()).substr(-2)+"-"+("0"+(t.getMonth()+1)).substr(-2)+"-"+t.getFullYear()}else if(args.style==106){val=("0"+t.getDate()).substr(-2)+" "+t.toString().substr(4,3).toLowerCase()+" "+t.getFullYear()}else if(args.style==107){val=t.toString().substr(4,3)+" "+("0"+t.getDate()).substr(-2)+","+t.getFullYear()}else if(args.style==108){val=("0"+t.getHours()).substr(-2)+":"+("0"+(t.getMinutes()+1)).substr(-2)+":"+("0"+t.getSeconds()).substr(-2)}else if(args.style==110){val=("0"+(t.getMonth()+1)).substr(-2)+"-"+("0"+t.getDate()).substr(-2)+"-"+t.getFullYear()}else if(args.style==111){val=t.getFullYear()+"/"+("0"+(t.getMonth()+1)).substr(-2)+"/"+("0"+t.getDate()).substr(-2)}else if(args.style==112){val=t.getFullYear()+("0"+(t.getMonth()+1)).substr(-2)+("0"+t.getDate()).substr(-2)}else{throw new Error("The CONVERT style "+args.style+" is not realized yet.")}}if(args.dbtypeid=="Date"){return new Date(val)}else if(args.dbtypeid.toUpperCase()=="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(args.dbtypeid=="DATETIME"){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()).substr(-3);return s}else if(args.dbtypeid.toUpperCase()=="STRING"){return""+val}else if(args.dbtypeid.toUpperCase()=="NUMBER"||args.dbtypeid=="FLOAT"){return+val}else if(args.dbtypeid.toUpperCase()=="MONEY"){var m=+val;return(m|0)+m*100%100/100}else if(args.dbtypeid.toUpperCase()=="BOOLEAN"){return!!val}else if(args.dbtypeid.toUpperCase()=="INT"){return val|0}else if(args.dbtypeid.toUpperCase()=="VARCHAR"||args.dbtypeid=="NVARCHAR"){if(args.dbsize)return(""+val).substr(0,args.dbsize);else return""+val}else if(args.dbtypeid.toUpperCase()=="CHAR"||args.dbtypeid=="NCHAR"){return(val+new Array(args.dbsize+1).join(" ")).substr(0,args.dbsize)}};yy.ColumnDef=function(params){return yy.extend(this,params)};yy.ColumnDef.prototype.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};yy.CreateTable=function(params){return yy.extend(this,params)};yy.CreateTable.prototype.toString=function(){var s=K("CREATE");if(this.temporary)s+=" "+K("TEMPORARY");if(this.view)s+=" "+K("VIEW");else s+=" "+K("TABLE");if(this.ifnotexists)s+=" "+K("IF")+" "+K("NOT")+" "+K("EXISTS");s+=" "+this.table.toString();if(this.viewcolumns){s+="("+this.viewcolumns.map(function(vcol){return vcol.toString()}).join(",")+")"}if(this.as)s+=" "+K("AS")+" "+L(this.as);else{var ss=this.columns.map(function(col){return col.toString()});s+=" ("+NL()+ID()+ss.join(","+NL()+ID())+")"}if(this.view&&this.select){s+=" AS "+this.select.toString()}return s};yy.CreateTable.prototype.execute=function(databaseid,params,cb){var db=alasql.databases[this.table.databaseid||databaseid];var tableid=this.table.tableid;if(!tableid){throw new Error("Table name is not defined")}var columns=this.columns;var constraints=this.constraints||[];if(this.ifnotexists&&db.tables[tableid])return 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;var ss=[];if(this.columns){this.columns.forEach(function(col){var dbtypeid=col.dbtypeid;if(!alasql.fn[dbtypeid])dbtypeid=dbtypeid.toUpperCase();var newcol={columnid:col.columnid,dbtypeid:dbtypeid};if(col.default){ss.push("'"+col.columnid+"':"+col.default.toJavaScript())}table.columns.push(newcol);table.xcolumns[newcol.columnid]=newcol;if(col.primarykey){var pk=table.pk={};pk.columns=[col.columnid];pk.onrightfns="r['"+col.columnid+"']";pk.onrightfn=new Function("r","return "+pk.onrightfns);pk.hh=hash(pk.onrightfns);table.indices[pk.hh]={}}})}table.defaultfns=ss.join(",");constraints.forEach(function(con){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","return "+pk.onrightfns);pk.hh=hash(pk.onrightfns);table.indices[pk.hh]={}}});if(this.view&&this.viewcolumns){var self=this;this.viewcolumns.forEach(function(vcol,idx){self.select.columns[idx].as=vcol.columnid})}if(db.engineid){return alasql.engines[db.engineid].createTable(this.table.databaseid||databaseid,tableid,this.ifnotexists,cb)}table.insert=function(r){if(this.pk){var pk=this.pk;var addr=pk.onrightfn(r);if(typeof this.indices[pk.hh][addr]!="undefined"){throw new Error("Cannot insert record, because it already exists in primary key")}else{table.data.push(r);this.indices[pk.hh][addr]=r}}else{table.data.push(r)}};table.delete=function(i){if(this.pk){var r=this.data[i];var pk=this.pk;var addr=pk.onrightfn(r);if(typeof this.indices[pk.hh][addr]=="undefined"){throw new Error("Something wrong with index on table")}else{this.indices[pk.hh][addr]=undefined}}};table.deleteall=function(){this.data.length=0;if(this.pk){this.indices[this.pk.hh]={}}};table.update=function(assignfn,i,params){if(this.pk){var r=this.data[i];var pk=this.pk;var addr=pk.onrightfn(r,params);if(typeof this.indices[pk.hh][addr]=="undefined"){throw new Error("Something wrong with index on table")}else{this.indices[pk.hh][addr]=undefined;assignfn(r,params,alasql);var newaddr=pk.onrightfn(r);if(typeof this.indices[pk.hh][newaddr]!="undefined"){throw new Error("Record already exists")}else{this.indices[pk.hh][newaddr]=r}}}else{assignfn(this.data[i],params,alasql)}};if(this.view&&this.select){table.view=true;table.select=this.select.compile(this.table.databaseid||databaseid)}if(cb)cb(1);return 1};alasql.fn.Date=Object;alasql.fn.Date=Date;alasql.fn.Number=Number;alasql.fn.String=String;alasql.fn.Boolean=Boolean;stdfn.EXTEND=alasql.utils.extend;stdfn.CHAR=String.fromCharCode.bind(String);stdfn.ASCII=function(a){return a.charCodeAt(0)};stdfn.COALESCE=function(){for(var i=0;i0){for(var i=0,ilen=table.data.length;i0){for(var i=0,ilen=table.data.length;i=0){q+="+"+values[idx].toJavaScript()}else if(alasql.fn[table.xcolumns[col.columnid].dbtypeid]){q+="(new "+table.xcolumns[col.columnid].dbtypeid+"(";q+=values[idx].toJavaScript();q+="))"}else{q+=values[idx].toJavaScript()}}else{q+=values[idx].toJavaScript()}ss.push(q)})}else{if(values instanceof Array&&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].toJavaScript()}else if(alasql.fn[col.dbtypeid]){q+="(new "+col.dbtypeid+"(";q+=values[idx].toJavaScript();q+="))"}else{q+=values[idx].toJavaScript()}ss.push(q)})}else{sw=JSONtoJavaScript(values)}}if(db.tables[tableid].defaultfns)ss.unshift(db.tables[tableid].defaultfns);if(sw){s+="a="+sw+";"}else{s+="a={"+ss.join(",")+"};"}if(db.tables[tableid].insert){s+="alasql.databases['"+databaseid+"'].tables['"+tableid+"'].insert(a);"}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);"}s+="return "+self.values.length;var insertfn=new Function("db, params, alasql",s3+s)}else if(this.select){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,null,cb);return res};return statement}else{var insertfn=function(db,params,alasql){var res=selectfn(params);db.tables[tableid].data=db.tables[tableid].data.concat(res);return res.length}}}else if(this.default){var insertfns="db.tables['"+tableid+"'].data.push({"+table.defaultfns+"});return 1;";var insertfn=new Function("db,params,alasql",insertfns)}else{throw new Error("Wrong INSERT parameters")}if(db.engineid&&alasql.engines[db.engineid].intoTable&&alasql.options.autocommit){var statement=function(params,cb){var aa=new Function("db,params",s33+"return aa;")(db,params);var res=alasql.engines[db.engineid].intoTable(db.databaseid,tableid,aa,null,cb);return res}}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)}if(cb)cb(res);return res}}return statement};yy.Insert.prototype.execute=function(databaseid,params,cb){return this.compile(databaseid)(params,cb)};yy.Delete=function(params){return yy.extend(this,params)};yy.Delete.prototype.toString=function(){var s="DELETE FROM "+this.table.toString();if(this.where)s+=" WHERE "+this.where.toString();return s};yy.Delete.prototype.compile=function(databaseid){databaseid=this.table.databaseid||databaseid;var tableid=this.table.tableid;var statement;var db=alasql.databases[databaseid];if(this.where){wherefn=new Function("r,params","return ("+this.where.toJavaScript("r","")+")");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;i0){s+="("+this.args.map(function(arg){return arg.toString()}).join(", ")+")"}if(this.as)s+=" "+K("AS")+" "+L(this.as);return s};yy.CreateDatabase.prototype.execute=function(databaseid,params,cb){var args;if(this.args&&this.args.length>0){args=this.args.map(function(arg){return new Function("params","return "+arg.toJavaScript())(params)})}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}};yy.AttachDatabase=function(params){return yy.extend(this,params)};yy.AttachDatabase.prototype.toString=function(){var s=K("ATTACH");if(this.engineid)s+=" "+L(this.engineid);s+=" "+K("DATABASE")+" "+L(this.databaseid);if(args){s+="(";if(args.length>0){s+=args.map(function(arg){return arg.toString()}).join(", ")}s+=")"}if(this.as)s+=" "+K("AS")+" "+L(this.as);return s};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};yy.DetachDatabase=function(params){return yy.extend(this,params)};yy.DetachDatabase.prototype.toString=function(){var s=K("DETACH");s+=" "+K("DATABASE")+" "+L(this.databaseid);return s};yy.DetachDatabase.prototype.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};yy.UseDatabase=function(params){return yy.extend(this,params)};yy.UseDatabase.prototype.toString=function(){return K("USE")+" "+K("DATABASE")+" "+L(this.databaseid)};yy.UseDatabase.prototype.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};yy.DropDatabase=function(params){return yy.extend(this,params)};yy.DropDatabase.prototype.toString=function(){var s=K("DROP");if(this.ifexists)s+=" "+K("IF")+" "+K("EXISTS");s+=" "+K("DATABASE")+" "+L(this.databaseid);return s};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]){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};yy.Declare=function(params){return yy.extend(this,params)};yy.Declare.prototype.toString=function(){var s=K("DECLARE")+" ";if(this.declares&&this.declares.length>0){s=this.declares.map(function(declare){var s="";s+="@"+L(declare.variable)+" ";s+=declare.dbtypeid;if(this.dbsize)s+="("+N(this.dbsize);if(this.dbprecision)s+=","+N(this.dbprecision);s+=")";if(declare.expression)s+=" = "+declare.expression.toString();return s}).join(",")}return s};yy.Declare.prototype.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};if(declare.expression){alasql.vars[declare.variable]=new Function("params,alasql","return "+declare.expression.toJavaScript("","",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};yy.ShowDatabases=function(params){return yy.extend(this,params)};yy.ShowDatabases.prototype.toString=function(){var s=K("SHOW")+" "+K("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){res=res.filter(function(d){return d.databaseid.match(new RegExp(self.like.value.replace(/\%/g,".*"),"g"))})}if(cb)cb(res);return res}};yy.ShowTables=function(params){return yy.extend(this,params)};yy.ShowTables.prototype.toString=function(){var s=K("SHOW")+" "+K("TABLES");if(this.databaseid)s+=" FROM "+this.databaseid;if(this.like)s+=" "+K("LIKE")+" "+this.like.toString();return s};yy.ShowTables.prototype.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,".*"),"g"))})}if(cb)cb(res);return res};yy.ShowColumns=function(params){return yy.extend(this,params)};yy.ShowColumns.prototype.toString=function(){var s=K("SHOW")+" "+K("COLUMNS");if(this.table.tableid)s+=" "+K("FROM")+" "+this.table.tableid;if(this.databaseid)s+=" "+K("FROM")+" "+this.databaseid;return s};yy.ShowColumns.prototype.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[]}};yy.ShowIndex=function(params){return yy.extend(this,params)};yy.ShowIndex.prototype.toString=function(){var s=K("SHOW")+" "+K("INDEX");if(this.table.tableid)s+=" "+K("FROM")+" "+this.table.tableid;if(this.databaseid)s+=" "+K("FROM")+" "+this.databaseid;return s};yy.ShowIndex.prototype.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};yy.ShowCreateTable=function(params){return yy.extend(this,params)};yy.ShowCreateTable.prototype.toString=function(){var s=K("SHOW")+" "+K("CREATE")+" "+K("TABLE")+" "+L(this.table.tableid);if(this.databaseid)s+=" "+K("FROM")+" "+L(this.databaseid);return s};yy.ShowCreateTable.prototype.execute=function(databaseid){var db=alasql.databases[this.databaseid||databaseid];var table=db.tables[this.table.tableid];var self=this;if(table){var s=K("CREATE")+" "+K("TABLE")+" "+L(this.table.tableid)+" (";var ss=[];if(table.columns){table.columns.forEach(function(col){var a=L(col.columnid)+" "+K(col.dbtypeid);if(col.dbsize)a+="("+N(col.dbsize)+")";if(col.primarykey)a+=" "+K("PRIMARY")+" "+K("KEY");ss.push(a)});s+=ss.join(", ")}s+=")";return s}else{throw new Error('There is no such table "'+this.table.tableid+'"')}};yy.SetVariable=function(params){return yy.extend(this,params)};yy.SetVariable.prototype.toString=function(){var s=K("SET")+" ";if(typeof this.value!="undefined")s+=K(this.variable.toUpperCase())+" "+(this.value?"ON":"OFF");if(this.expression)s+="@"+L(this.variable)+" = "+this.expression.toString();return s};yy.SetVariable.prototype.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){var res=new Function("params,alasql","return "+this.expression.toJavaScript("","",null))(params,alasql);if(alasql.declares[this.variable]){res=alasql.stdfn.CONVERT(res,alasql.declares[this.variable])}if(this.props&&this.props.length>0){var fs="alasql.vars['"+this.variable+"']";fs+=this.props.map(function(prop){if(typeof prop=="string"){return"['"+prop+"']"}else if(typeof prop=="number"){return"["+prop+"]"}else{return"["+prop.toJavaScript()+"]"}}).join();new Function("value,alasql",fs+"=value")(res,alasql)}else{alasql.vars[this.variable]=res}}var res=1;if(cb)res=cb(res);return res};alasql.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",sql);if(res instanceof Array){if(console.table){console.table(res)}else{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{el=target}}var s="";if(typeof sql=="string"&&alasql.options.logprompt){s+="

"+alasql.pretty(sql)+"
"}if(res instanceof Array){if(res.length==0){s+="

[ ]

"}else if(typeof res[0]!="object"||res[0]instanceof Array){for(var i=0,ilen=res.length;i"+loghtml(res[i])+"

"}}else{s+=loghtml(res)}}else{s+=loghtml(res)}el.innerHTML+=s}};alasql.clear=function(){var target=alasql.options.logtarget;if(typeof exports=="object"){target="console"}if(target=="console"||typeof exports=="object"){if(console.clear){console.clear()}else{}}else{var el;if(target=="output"){el=document.getElementsByTagName("output")[0]}else{if(typeof target=="string"){el=document.getElementById(target)}else{el=target}}el.innerHTML=""}};alasql.write=function(s){var target=alasql.options.logtarget;if(typeof exports=="object"){target="console"}if(target=="console"||typeof exports=="object"){if(console.log){console.log(s)}else{}}else{var el;if(target=="output"){el=document.getElementsByTagName("output")[0]}else{if(typeof target=="string"){el=document.getElementById(target)}else{el=target}}el.innerHTML+=s}};function loghtml(res){var s="";if(typeof res=="undefined"){s+="undefined"}else if(res instanceof Array){s+="";s+="";var cols=[];for(colid in res[0]){cols.push(colid)}s+="
#";cols.forEach(function(colid){s+=""+colid});for(var i=0,ilen=res.length;i"+(i+1);cols.forEach(function(colid){s+=" ";if(+res[i][colid]==+res[i][colid]){s+='
';if(typeof res[i][colid]=="undefined")s+="NULL";else s+=res[i][colid];s+="
"}else{if(typeof res[i][colid]=="undefined"){s+="NULL"}else if(typeof res[i][colid]=="string"){s+=res[i][colid]}else s+=JSONtoString(res[i][colid])}})}s+="
"}else{s+="

"+JSONtoString(res)+"

"}return s}function scrollTo(element,to,duration){if(duration<=0)return;var difference=to-element.scrollTop;var perTick=difference/duration*10;setTimeout(function(){if(element.scrollTop==to)return;element.scrollTop=element.scrollTop+perTick;scrollTo(element,to,duration-10)},10)}alasql.prompt=function(el,useidel,firstsql){if(typeof exports=="object"){throw new Error("The functionality of prompt is 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('

'+(Date.now()-tm)+" ms

")}catch(err){alasql.write("

"+olduseid+"> "+sql+"

");alasql.write('

'+err+"

")}}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('

'+(Date.now()-tm)+" ms

")}catch(err){alasql.write("

"+olduseid+"> "+alasql.pretty(sql,false)+"

");alasql.write('

'+err+"

")}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()}}}};yy.BeginTransaction=function(params){return yy.extend(this,params)};yy.BeginTransaction.prototype.toString=function(){return K("BEGIN")+" "+K("TRANSACTION")};yy.BeginTransaction.prototype.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{}if(cb)cb(res);return res};yy.CommitTransaction=function(params){return yy.extend(this,params)};yy.CommitTransaction.prototype.toString=function(){return K("COMMIT")+" "+K("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{}if(cb)cb(res);return res};yy.RollbackTransaction=function(params){return yy.extend(this,params)};yy.RollbackTransaction.prototype.toString=function(){return K("ROLLBACK")+" "+K("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{}if(cb)cb(res);return res};alasql.into.SQL=function(filename,opts,data,columns,cb){var res;if(typeof filename=="object"){opts=filename;filename=""}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{}}for(var i=0,ilen=data.length;i0){columns=Object.keys(data[0]).map(function(columnid){return{columnid:columnid}})}if(typeof filename=="object"){opts=filename;filename=null}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")}alasql.utils.saveFile(filename,s);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=" ";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"){opts=filename;filename=null}var opt={};opt.separator=",";opt.quote='"';alasql.utils.extend(opt,opts);var res=data.length;var s="";if(opt.headers){s+=columns.map(function(col){return col.columnid}).join(opt.separator)+"\n"}data.forEach(function(d,idx){s+=columns.map(function(col){var s=d[col.columnid];s=(s+"").replace(new RegExp("\\"+opt.quote,"g"),'""');if((s+"").indexOf(opt.separator)>-1||(s+"").indexOf(opt.quote)>-1)s=opt.quote+s+opt.quote;return s}).join(opt.separator)+"\n"});if(filename){alasql.utils.saveFile(filename,s)}else{console.log(s)}if(cb)res=cb(res);return res};alasql.into.XLSX=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 exports=="object"){var XLSX=require("xlsx")}else{var XLSX=window.XLSX}var opt={sheetid:"Sheet1",headers:true};alasql.utils.extend(opt,opts);var res=data.length;var wb={SheetNames:[],Sheets:{}};if(opt.sourcefilename){alasql.utils.loadBinaryFile(opt.sourcefilename,!!cb,function(data){wb=XLSX.read(data,{type:"binary"});doExport()})}else{doExport()}function doExport(){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+data.length+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}});i++}for(var j=0;j=N)return EOF;if(eol)return eol=false,EOL;var j=I;if(text.charCodeAt(j)===quoteCode){var i=j;while(i++http://github/agershun/alasq for more information'}];yy.Help.prototype.execute=function(databaseid,params,cb){var ss=[];if(!this.subject){ss=helpdocs}else{ss.push('See also http://github/agershun/alasq for more information')}if(cb)ss=cb(ss);return ss};yy.Print=function(params){return yy.extend(this,params)};yy.Print.prototype.toString=function(){var s=K("PRINT");if(this.statement)s+=" "+this.statement.toString();return s};yy.Print.prototype.execute=function(databaseid,params,cb){var res,s;if(this.statement){s=this.statement.execute(databaseid,params)}else{s=""}s=JSONtoString(s);console.log(s);if(cb)res=cb(res);return res};yy.Source=function(params){return yy.extend(this,params)};yy.Source.prototype.toString=function(){var s=K("SOURCE");if(this.url)s+=" "+S("'"+this.url+"'");return s};yy.Source.prototype.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};yy.Require=function(params){return yy.extend(this,params)};yy.Require.prototype.toString=function(){var s=K("REQUIRE");if(this.paths&&this.paths.length>0){s+=this.paths.map(function(path){return path.toString()}).join(",")}return s};yy.Require.prototype.execute=function(databaseid,params,cb){var self=this;var res=0;var ss="";if(this.paths.length>0){this.paths.forEach(function(path){loadFile(path.value,!!cb,function(data){res++;ss+=data;if(res0){res=res.filter(function(d){return d.databaseid.match(relike)})}}if(cb)cb(res);return res};LS.createTable=function(databaseid,tableid,ifnotexists,cb){var lsdbid=alasql.databases[databaseid].lsdbid;var tb=LS.get(lsdbid+"."+tableid);var res=1;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];lsdb.tables[tableid]={columns:table.columns};LS.set(lsdbid,lsdb);LS.set(lsdbid+"."+tableid,[]);if(cb)cb(res);return res};LS.dropTable=function(databaseid,tableid,ifexists,cb){var res=1;var lsdbid=alasql.databases[databaseid].lsdbid;var lsdb=LS.get(lsdbid);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);if(cb)cb(res);return res};LS.fromTable=function(databaseid,tableid,cb,idx,query){var lsdbid=alasql.databases[databaseid].lsdbid;var res=LS.get(lsdbid+"."+tableid);if(cb)res=cb(res,idx,query);return res};LS.intoTable=function(databaseid,tableid,value,columns,cb){var lsdbid=alasql.databases[databaseid].lsdbid;var res=value.length;var tb=LS.get(lsdbid+"."+tableid);if(!tb)tb=[];tb=tb.concat(value);LS.set(lsdbid+"."+tableid,tb);if(cb)cb(res);return res};LS.loadTableData=function(databaseid,tableid){var db=alasql.databases[databaseid];var lsdbid=alasql.databases[databaseid].lsdbid;db.tables[tableid].data=LS.get(lsdbid+"."+tableid)};LS.saveTableData=function(databaseid,tableid){var db=alasql.databases[databaseid];var lsdbid=alasql.databases[databaseid].lsdbid;LS.set(lsdbid+"."+tableid,db.tables[tableid].data);db.tables[tableid].data=null};LS.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){lsdb.tables[tbid]={columns:db.tables[tbid].columns};LS.set(lsdbid+"."+tbid,db.tables[tbid].data)}}LS.set(lsdbid,lsdb);return 1};LS.begin=LS.commit;LS.rollback=function(databaseid,cb){var db=alasql.databases[databaseid];db.dbversion++;var lsdbid=alasql.databases[databaseid].lsdbid;var lsdb=LS.get(lsdbid);if(lsdb.tables){for(var tbid in lsdb.tables){var tb=new alasql.Table({columns:db.tables[tbid].columns});extend(tb,lsdb.tables[tbid]);lsdb.tables[tbid]=tb;if(!alasql.options.autocommit){lsdb.tables[tbid].data=LS.get(db.lsdbid+"."+tbid)}lsdb.tables[tbid].indexColumns()}}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"};var SQLITE=alasql.engines.SQLITE=function(){};SQLITE.createDatabase=function(wdbid,args,ifnotexists,dbid,cb){throw new Error("Connot create SQLITE database in memory. Attach it.")};SQLITE.dropDatabase=function(databaseid){throw new Error("This is impossible to drop SQLite database. Detach it.")};SQLITE.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};SQLITE.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)};SQLITE.intoTable=function(databaseid,tableid,value,columns,cb){var sqldb=alasql.databases[databaseid].sqldb;for(var i=0,ilen=value.length;i1){var sql="REQUIRE "+paths.map(function(p){return'"'+p+'"'}).join(",");alasql(sql,[],cb)}}else if(path===false){delete alasql.webworker;return}}} \ No newline at end of file +}};var Database=alasql.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{self=alasql.databases.alasql}}if(!databaseid){databaseid="db"+alasql.databasenum++}self.databaseid=databaseid;alasql.databases[databaseid]=self;self.tables={};self.views={};self.indices={};self.resetSqlCache();self.dbversion=0;return self};Database.prototype.resetSqlCache=function(){this.sqlCache={};this.sqlCacheSize=0};Database.prototype.exec=function(sql,params,cb){return alasql.dexec(this.databaseid,sql,params,cb)};Database.prototype.transaction=function(cb){var tx=new alasql.Transaction(this.databaseid);var res=cb(tx);return res};var Transaction=alasql.Transaction=function(databaseid){this.transactionid=Date.now();this.databaseid=databaseid;this.commited=false;this.dbversion=alasql.databases[databaseid].dbversion;this.bank=JSON.stringify(alasql.databases[databaseid]);return this};Transaction.prototype.commit=function(){this.commited=true;alasql.databases[this.databaseid].dbversion=Date.now();delete this.bank};Transaction.prototype.rollback=function(){if(!this.commited){alasql.databases[this.databaseid]=JSON.parse(this.bank);delete this.bank}else{throw new Error("Transaction already commited")}};Transaction.prototype.exec=function(sql,params,cb){return alasql.dexec(this.databaseid,sql,params,cb)};Transaction.prototype.executeSQL=Transaction.prototype.exec;var Table=alasql.Table=function(params){this.columns=[];this.xcolumns={};this.data=[];this.inddefs={};this.indices={};this.uniqs={};this.uniqdefs={};extend(this,params)};Table.prototype.indexColumns=function(){var self=this;self.xcolumns={};self.columns.forEach(function(col){self.xcolumns[col.columnid]=col})};var View=alasql.View=function(params){this.columns=[];this.xcolumns={};this.query=[];extend(this,params)};var Query=alasql.Query=function(params){this.alasql=alasql;this.columns=[];this.xcolumns={};this.selectGroup=[];this.groupColumns={};extend(this,params)};var Recordset=alasql.Recordset=function(params){extend(this,params)};var yy=parser.yy={};yy.extend=extend;yy.casesensitive=alasql.options.casesensitive;var Base=yy.Base=function(params){return yy.extend(this,params)};Base.prototype.toString=function(){};Base.prototype.toType=function(){};Base.prototype.toJavaScript=function(){};Base.prototype.compile=returnUndefined;Base.prototype.exec=function(){};Base.prototype.compile=returnUndefined;Base.prototype.exec=function(){};yy.Statements=function(params){return yy.extend(this,params)};yy.Statements.prototype.toString=function(){return this.statements.map(function(st){return st.toString()}).join(";"+NL())};yy.Statements.prototype.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}}};function queryfn(query,oldscope,cb,A,B){var ms;query.sourceslen=query.sources.length;var slen=query.sourceslen;query.query=query;query.A=A;query.B=B;query.cb=cb;query.oldscope=oldscope;if(query.queriesfn){query.sourceslen+=query.queriesfn.length;slen+=query.queriesfn.length;query.queriesdata=[];query.queriesfn.forEach(function(q,idx){q.query.params=query.params;if(false){queryfn(q.query,query.oldscope,queryfn2,-idx-1,query)}else{queryfn2([],-idx-1,query)}})}var scope;if(!oldscope)scope={};else scope=cloneDeep(oldscope);query.scope=scope;var result;query.sources.forEach(function(source,idx){source.query=query;var rs=source.datafn(query,query.params,queryfn2,idx,alasql);if(typeof rs!=undefined){if((query.intofn||query.intoallfn)&&rs instanceof Array)rs=rs.length;result=rs}source.queriesdata=query.queriesdata});if(slen==0)result=queryfn3(query);return result}function queryfn2(data,idx,query){if(idx>=0){var source=query.sources[idx];source.data=data;if(typeof source.data=="function"){source.getfn=source.data;source.dontcache=source.getfn.dontcache;if(source.joinmode=="OUTER"||source.joinmode=="RIGHT"||source.joinmode=="ANTI"){source.dontcache=false}source.data={}}}else{query.queriesdata[-idx-1]=flatArray(data)}query.sourceslen--;if(query.sourceslen>0)return;return queryfn3(query)}function queryfn3(query){var scope=query.scope;preIndex(query);query.data=[];query.xgroups={};query.groups=[];var h=0;doJoin(query,scope,h);if(query.groupfn){query.data=[];if(query.groups.length==0){var g={};if(query.selectGroup.length>0){query.selectGroup.forEach(function(sg){if(sg.aggregatorid=="COUNT"||sg.aggregatorid=="SUM"){g[sg.nick]=0}else{g[sg.nick]=undefined}})}query.groups=[g]}for(var i=0,ilen=query.groups.length;i0){for(var i=0,ilen=query.data.length;i0&&source.optimization=="ix"&&source.onleftfn&&source.onrightfn){if(source.databaseid&&alasql.databases[source.databaseid].tables[source.tableid]){if(!alasql.databases[source.databaseid].tables[source.tableid].indices)query.database.tables[source.tableid].indices={};var ixx=alasql.databases[source.databaseid].tables[source.tableid].indices[hash(source.onrightfns+"`"+source.srcwherefns)];if(!alasql.databases[source.databaseid].tables[source.tableid].dirty&&ixx){source.ix=ixx}}if(!source.ix){source.ix={};var scope={};var i=0;var ilen=source.data.length;var dataw;while((dataw=source.data[i])||source.getfn&&(dataw=source.getfn(i))||i=query.sources.length){if(query.wherefn(scope,query.params,alasql)){if(query.groupfn){query.groupfn(scope,query.params,query.alasql)}else{query.data.push(query.selectfn(scope,query.params,alasql))}}}else if(query.sources[h].applyselect){var source=query.sources[h];source.applyselect(query.params,function(data){if(data.length>0){for(var i=0;i0){s+=NL()+ID()+K("GROUP BY")+" "+this.group.map(function(grp){return grp.toString()}).join(", ")}if(this.having)s+=NL()+ID()+K("HAVING")+" "+this.having.toString();if(this.order&&this.order.length>0){s+=NL()+ID()+K("ORDER BY")+" "+this.order.map(function(ord){return ord.toString()}).join(", ")}if(this.limit)s+=NL()+ID()+K("LIMIT")+" "+this.limit.value;if(this.offset)s+=NL()+ID()+K("OFFSET")+" "+this.offset.value;if(this.union)s+=NL()+K("UNION")+NL()+this.union.toString();if(this.unionall)s+=NL()+K("UNION ALL")+NL()+this.unionall.toString();if(this.except)s+=NL()+K("EXCEPT")+NL()+this.except.toString();if(this.intersect)s+=NL()+K("INTERSECT")+NL()+this.intersect.toString();return s};yy.Select.prototype.toJavaScript=function(context,tableid,defcols){var s="alasql.utils.flatArray(this.queriesfn["+(this.queriesidx-1)+"](this.params,null,"+context+"))[0]";return s};yy.Select.prototype.compile=function(databaseid){var db=alasql.databases[databaseid];var query=new Query;query.removeKeys=[];query.explain=this.explain;query.explaination=[];query.explid=1;query.modifier=this.modifier;query.database=db;this.compileWhereExists(query);this.compileQueries(query);query.defcols=this.compileDefCols(query,databaseid);query.fromfn=this.compileFrom(query);if(this.joins)this.compileJoins(query);this.compileSelectGroup0(query);if(this.group||query.selectGroup.length>0){query.selectgfns=this.compileSelectGroup1(query)}else{query.selectfns=this.compileSelect1(query)}if(this.where)this.compileWhereJoins(query);query.wherefn=this.compileWhere(query);if(this.group||query.selectGroup.length>0)query.groupfn=this.compileGroup(query);if(this.having)query.havingfn=this.compileHaving(query);if(this.group||query.selectGroup.length>0){query.selectgfn=this.compileSelectGroup2(query)}else{query.selectfn=this.compileSelect2(query)}query.distinct=this.distinct;if(this.order)query.orderfn=this.compileOrder(query);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;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}}if(this.into){if(this.into instanceof yy.Table){if(alasql.options.autocommit&&alasql.databases[this.into.databaseid||databaseid].engineid){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{query.intofns="alasql.databases['"+(this.into.databaseid||databaseid)+"'].tables"+"['"+this.into.tableid+"'].data.push(r);"}}else if(this.into instanceof yy.VarValue){query.intoallfns='alasql.vars["'+this.into.variable+'"]=this.data;res=1;if(cb)res=cb(res);return res;'}else if(this.into instanceof yy.FuncValue){var qs="alasql.into['"+this.into.funcid.toUpperCase()+"'](";if(this.into.args&&this.into.args.length>0){qs+=this.into.args[0].toJavaScript()+",";if(this.into.args.length>1){qs+=this.into.args[1].toJavaScript()+","}else{qs+="null,"}}else{qs+="null, null,"}query.intoallfns=qs+"this.data,columns,cb)"}else if(this.into instanceof yy.ParamValue){query.intofns="params['"+this.into.param+"'].push(r)"}if(query.intofns){query.intofn=new Function("r,i,params,alasql",query.intofns)}if(query.intoallfns){query.intoallfn=new Function("columns,cb,alasql",query.intoallfns)}}var statement=function(params,cb,oldscope){query.params=params;var res1=queryfn(query,oldscope,function(res){var res2=modify(query,res);if(cb)cb(res2);return res2});return res1};statement.query=query;return statement};function modify(query,res){if(query.modifier=="VALUE"){if(res.length>0){var key;if(query.columns&&query.columns.length>0)key=query.columns[0].columnid;else key=Object.keys(res[0])[0];res=res[0][key]}else{res=undefined}}if(query.modifier=="ROW"){if(res.length>0){var key;if(query.columns&&query.columns.length>0)key=query.columns[0].columnid;else key=Object.keys(res[0])[0];var a=[];for(var key in res[0]){a.push(res[0][key])}res=a}else{res=undefined}}if(query.modifier=="COLUMN"){var ar=[];if(res.length>0){var key;if(query.columns&&query.columns.length>0)key=query.columns[0].columnid;else key=Object.keys(res[0])[0];for(var i=0,ilen=res.length;i0){key=query.columns[0].columnid;val=query.columns[1].columnid}else{var okeys=Object.keys(res[0]);key=okeys[0];val=okeys[1]}for(var i=0,ilen=res.length;i0)key=query.columns[0].columnid;else key=Object.keys(res[0])[0];var s="";for(var i=0,ilen=res.length;i0){if(tq.args[0]){s+=tq.args[0].toJavaScript("query.oldscope")+","}else{s+="null,"}if(tq.args[1]){s+=tq.args[1].toJavaScript("query.oldscope")+","}else{s+="null,"}}else{s+="null,null,"}s+="cb,idx,query";s+=");/*if(cb)res=cb(res,idx,query);*/return res";source.datafn=new Function("query, params, cb, idx, alasql",s)}else if(tq instanceof yy.FromData){source.datafn=function(query,params,cb,idx,alasql){var res=tq.data;if(cb)res=cb(res,idx,query);return res}}else{throw new Error("Wrong table at FROM")}query.sources.push(source)});query.defaultTableid=query.sources[0].alias};alasql.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;i0){if(jn.args[0]){s+=jn.args[0].toJavaScript("query.oldscope")+","}else{s+="null,"}if(jn.args[1]){s+=jn.args[1].toJavaScript("query.oldscope")+","}else{s+="null,"}}else{s+="null,null,"}s+="cb,idx,query";s+=");/*if(cb)res=cb(res,idx,query);*/return res";source.datafn=new Function("query, params, cb, idx, alasql",s);query.aliases[source.alias]={type:"funcvalue"}}var alias=source.alias;if(jn.natural){if(jn.using||jn.on){throw new Error("NATURAL JOIN cannot have USING or ON clauses")}else{if(query.sources.length>0){var prevSource=query.sources[query.sources.length-1];var prevTable=alasql.databases[prevSource.databaseid].tables[prevSource.tableid];var table=alasql.databases[source.databaseid].tables[source.tableid];if(prevTable&&table){var c1=prevTable.columns.map(function(col){return col.columnid});var c2=table.columns.map(function(col){return col.columnid});jn.using=arrayIntersect(c1,c2).map(function(colid){return{columnid:colid}})}else{throw new Error("In this version of Alasql NATURAL JOIN "+"works for tables with predefined columns only")}}}}if(jn.using){var prevSource=query.sources[query.sources.length-1];source.onleftfns=jn.using.map(function(col){return"p['"+(prevSource.alias||prevSource.tableid)+"']['"+col.columnid+"']"}).join('+"`"+');source.onleftfn=new Function("p,params,alasql","return "+source.onleftfns);source.onrightfns=jn.using.map(function(col){return"p['"+(source.alias||source.tableid)+"']['"+col.columnid+"']"}).join('+"`"+');source.onrightfn=new Function("p,params,alasql","return "+source.onrightfns);source.optimization="ix"}else if(jn.on){if(jn.on instanceof yy.Op&&jn.on.op=="="&&!jn.on.allsome){source.optimization="ix";var lefts="";var rights="";var middles="";var middlef=false;var ls=jn.on.left.toJavaScript("p",query.defaultTableid,query.defcols);var rs=jn.on.right.toJavaScript("p",query.defaultTableid,query.defcols);if(ls.indexOf("p['"+alias+"']")>-1&&!(rs.indexOf("p['"+alias+"']")>-1)){if((ls.match(/p\[\'.*?\'\]/g)||[]).every(function(s){return s=="p['"+alias+"']"})){rights=ls}else{middlef=true}}else if(!(ls.indexOf("p['"+alias+"']")>-1)&&rs.indexOf("p['"+alias+"']")>-1){if((rs.match(/p\[\'.*?\'\]/g)||[]).every(function(s){return s=="p['"+alias+"']"})){lefts=ls}else{middlef=true}}else{middlef=true}if(rs.indexOf("p['"+alias+"']")>-1&&!(ls.indexOf("p['"+alias+"']")>-1)){if((rs.match(/p\[\'.*?\'\]/g)||[]).every(function(s){return s=="p['"+alias+"']"})){rights=rs}else{middlef=true}}else if(!(rs.indexOf("p['"+alias+"']")>-1)&&ls.indexOf("p['"+alias+"']")>-1){if((ls.match(/p\[\'.*?\'\]/g)||[]).every(function(s){return s=="p['"+alias+"']"})){lefts=rs}else{middlef=true}}else{middlef=true}if(middlef){rights="";lefts="";middles=jn.on.toJavaScript("p",query.defaultTableid,query.defcols);source.optimization="no"}source.onleftfns=lefts;source.onrightfns=rights;source.onmiddlefns=middles||"true";source.onleftfn=new Function("p,params,alasql","return "+source.onleftfns);source.onrightfn=new Function("p,params,alasql","return "+source.onrightfns);source.onmiddlefn=new Function("p,params,alasql","return "+source.onmiddlefns)}else{source.optimization="no";source.onmiddlefns=jn.on.toJavaScript("p",query.defaultTableid,query.defcols);source.onmiddlefn=new Function("p,params,alasql","return "+jn.on.toJavaScript("p",query.defaultTableid,query.defcols))}}query.sources.push(source)}})};yy.Select.prototype.compileWhere=function(query){if(this.where){if(typeof this.where=="function"){return this.where}else{s=this.where.toJavaScript("p",query.defaultTableid,query.defcols);query.wherefns=s;return new Function("p,params,alasql","return "+s)}}else return function(){return true}};yy.Select.prototype.compileWhereJoins=function(query){return;optimizeWhereJoin(query,this.where.expression);query.sources.forEach(function(source){if(source.srcwherefns){source.srcwherefn=new Function("p,params,alasql","return "+source.srcwherefns)}if(source.wxleftfns){source.wxleftfn=new Function("p,params,alasql","return "+source.wxleftfns)}if(source.wxrightfns){source.wxrightfn=new Function("p,params,alasql","return "+source.wxrightfns)}})};function optimizeWhereJoin(query,ast){if(!ast)return false;if(!(ast instanceof yy.Op))return;if(ast.op!="="&&ast.op!="AND")return;if(ast.allsome)return;var s=ast.toJavaScript("p",query.defaultTableid,query.defcols);var fsrc=[];query.sources.forEach(function(source,idx){if(source.tableid){if(s.indexOf("p['"+source.alias+"']")>-1)fsrc.push(source)}});if(fsrc.length==0){return}else if(fsrc.length==1){if(!(s.match(/p\[\'.*?\'\]/g)||[]).every(function(s){return s=="p['"+fsrc[0].alias+"']"})){return}var src=fsrc[0];src.srcwherefns=src.srcwherefns?src.srcwherefns+"&&"+s:s;if(ast instanceof yy.Op&&(ast.op=="="&&!ast.allsome)){if(ast.left instanceof yy.Column){var ls=ast.left.toJavaScript("p",query.defaultTableid,query.defcols);var rs=ast.right.toJavaScript("p",query.defaultTableid,query.defcols);if(rs.indexOf("p['"+fsrc[0].alias+"']")==-1){fsrc[0].wxleftfns=ls;fsrc[0].wxrightfns=rs}}if(ast.right instanceof yy.Column){var ls=ast.left.toJavaScript("p",query.defaultTableid,query.defcols);var rs=ast.right.toJavaScript("p",query.defaultTableid,query.defcols);if(ls.indexOf("p['"+fsrc[0].alias+"']")==-1){fsrc[0].wxleftfns=rs;fsrc[0].wxrightfns=ls}}}ast.reduced=true;return}else{if(ast.op="AND"){optimizeWhereJoin(query,ast.left);optimizeWhereJoin(query,ast.right)}}}yy.Select.prototype.compileGroup=function(query){var self=this;var tableid=query.sources[0].alias; +var defcols=query.defcols;var allgroup=[[]];if(this.group){allgroup=decartes(this.group,query)}var allgroups=[];allgroup.forEach(function(a){allgroups=arrayUnion(allgroups,a)});query.allgroups=allgroups;if(false){allgroups.forEach(function(col2){if(query.selectColumns[colid]){}else{var tmpid="default";if(query.sources.length>0)tmpid=query.sources[0].alias;if(Object.keys(query.selectColumns).length!=0)query.removeKeys.push(colid);query.selectfns+="r['"+escapeq(colid)+"']="+new yy.Column({columnid:colid}).toJavaScript("p",tmpid)+";"}})}var s="";allgroup.forEach(function(agroup){s+="var g=this.xgroups[";var rg=agroup.map(function(col2){var columnid=col2.split(" ")[0];var coljs=col2.split(" ")[1];if(columnid=="")return"1";else 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(" ")[0];var coljs=col2.split(" ")[1];if(columnid=="")return"";else return"'"+columnid+"':"+coljs+","}).join("");var neggroup=arrayDiff(allgroups,agroup);s+=neggroup.map(function(col2){var columnid=col2.split(" ")[0];var coljs=col2.split(" ")[1];return"'"+columnid+"':null,"}).join("");var aft="";s+=query.selectGroup.map(function(col,idx){var colexp=col.expression.toJavaScript("p",tableid,defcols);var colas=col.nick;if(col instanceof yy.AggrValue){if(col.distinct){aft+=",g['$$_VALUES_"+colas+"']={},g['$$_VALUES_"+colas+"']["+colexp+"]=true"}if(col.aggregatorid=="SUM"||col.aggregatorid=="MIN"||col.aggregatorid=="MAX"||col.aggregatorid=="FIRST"||col.aggregatorid=="LAST"){return"'"+colas+"':"+colexp+","}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+",'_COUNT_"+colas+"':1,"}else if(col.aggregatorid=="AGGR"){aft+=",g['"+colas+"']="+col.expression.toJavaScript("g",-1);return""}else if(col.aggregatorid=="REDUCE"){return"'"+colas+"':alasql.aggr['"+col.funcid+"']("+colexp+"),"}return""}else return""}).join("");s+="}"+aft+",g));} else {";s+=query.selectGroup.map(function(col,idx){var colas=col.nick;var colexp=col.expression.toJavaScript("p",tableid,defcols);if(col instanceof yy.AggrValue){if(col.distinct){var pre="if(typeof "+colexp+'!="undefined" && (!g[\'$$_VALUES_'+colas+"']["+colexp+"])) {";var post="g['$$_VALUES_"+colas+"']["+colexp+"]=true;}"}else{var pre="",post=""}if(col.aggregatorid=="SUM"){return pre+"g['"+colas+"']+="+colexp+";"+post}else if(col.aggregatorid=="COUNT"){if(col.expression.columnid=="*")return pre+"g['"+colas+"']++;"+post;else{return pre+"if(typeof "+colexp+'!="undefined") g[\''+colas+"']++;"+post}}else if(col.aggregatorid=="ARRAY"){return pre+"g['"+colas+"'].push("+colexp+");"+post}else if(col.aggregatorid=="MIN"){return pre+"g['"+colas+"']=Math.min(g['"+colas+"'],"+colexp+");"+post}else if(col.aggregatorid=="MAX"){return pre+"g['"+colas+"']=Math.max(g['"+colas+"'],"+colexp+");"+post}else if(col.aggregatorid=="FIRST"){return""}else if(col.aggregatorid=="LAST"){return pre+"g['"+colas+"']="+colexp+";"+post}else if(col.aggregatorid=="AVG"){return pre+"g['_SUM_"+colas+"']+="+colexp+";"+"g['_COUNT_"+colas+"']++;"+"g['"+colas+"']=g['_SUM_"+colas+"']/g['_COUNT_"+colas+"'];"+post}else if(col.aggregatorid=="AGGR"){return pre+"g['"+colas+"']="+col.expression.toJavaScript("g",-1)+";"+post}else if(col.aggregatorid=="REDUCE"){return pre+"g['"+colas+"']=alasql.aggr."+col.funcid+"("+colexp+",g['"+colas+"']);"+post}return""}else return""}).join("");s+="}"});return new Function("p,params,alasql",s)};function compileSelectStar(query,alias){var s="",sp="",ss=[];if(query.aliases[alias].tableid){var columns=alasql.databases[query.aliases[alias].databaseid].tables[query.aliases[alias].tableid].columns}if(columns&&columns.length>0){columns.forEach(function(tcol){ss.push("'"+tcol.columnid+"':p['"+alias+"']['"+tcol.columnid+"']");query.selectColumns[escapeq(tcol.columnid)]=true;var coldef={columnid:tcol.columnid,dbtypeid:tcol.dbtypeid,dbsize:tcol.dbsize,dbprecision:tcol.dbprecision,dbenum:tcol.dbenum};query.columns.push(coldef);query.xcolumns[coldef.columnid]=coldef})}else{sp+='var w=p["'+alias+'"];for(var k in w){r[k]=w[k]};';query.dirtyColumns=true}return{s:ss.join(","),sp:sp}}yy.Select.prototype.compileSelect1=function(query){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){var ret=compileSelectStar(query,col.tableid);if(ret.s)ss=ss.concat(ret.s);sp+=ret.sp}else{for(var alias in query.aliases){var ret=compileSelectStar(query,alias);if(ret.s)ss=ss.concat(ret.s);sp+=ret.sp}}}else{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!="_"){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];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{query.dirtyColumns=true}}else{}}}else if(col instanceof yy.AggrValue){if(!self.group){self.group=[""]}if(!col.as)col.as=escapeq(col.toString());if(col.aggregatorid=="SUM"||col.aggregatorid=="MAX"||col.aggregatorid=="MIN"||col.aggregatorid=="FIRST"||col.aggregatorid=="LAST"||col.aggregatorid=="AVG"||col.aggregatorid=="ARRAY"||col.aggregatorid=="REDUCE"){ss.push("'"+escapeq(col.as)+"':"+col.expression.toJavaScript("p",query.defaultTableid,query.defcols))}else if(col.aggregatorid=="COUNT"){ss.push("'"+escapeq(col.as)+"':1")}query.selectColumns[col.aggregatorid+"("+escapeq(col.expression.toString())+")"]=thtd}else{ss.push("'"+escapeq(col.as||col.columnid||col.toString())+"':"+col.toJavaScript("p",query.defaultTableid,query.defcols));query.selectColumns[escapeq(col.as||col.columnid||col.toString())]=true}});s+=ss.join(",")+"};"+sp;return s};yy.Select.prototype.compileSelect2=function(query){var s=query.selectfns;return new Function("p,params,alasql",s+"return r")};yy.Select.prototype.compileSelectGroup0=function(query){var self=this;self.columns.forEach(function(col,idx){if(col instanceof yy.Column&&col.columnid=="*"){}else{var colas;if(col instanceof yy.Column){colas=escapeq(col.columnid)}else{colas=escapeq(col.toString())}for(var i=0;irb)return 1;if(ra==rb)return 0;return-1}}var s="";var sk="";this.order.forEach(function(ord,idx){var dg="";if(ord.expression instanceof yy.NumValue){ord.expression=self.columns[ord.expression.value-1]}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")dg=".valueOf()"}else{if(alasql.options.valueof)dg=".valueOf()"}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()";if(ord.nocase)dg+=".toUpperCase()";s+="if("+ord.toJavaScript("a","")+dg+(ord.direction=="ASC"?">":"<")+ord.toJavaScript("b","")+dg+")return 1;";s+="if("+ord.toJavaScript("a","")+dg+"=="+ord.toJavaScript("b","")+dg+"){"}sk+="}"});s+="return 0;";s+=sk+"return -1";query.orderfns=s;return new Function("a,b",s)}};var rollup=function(a,query){var rr=[];var mask=0;var glen=a.length;for(var g=0;g"){var s=this.left.toString()+"->";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()+" "+P(this.op)+" "+(this.allsome?this.allsome+" ":"")+this.right.toString()};yy.Op.prototype.findAggregator=function(query){if(this.left&&this.left.findAggregator)this.left.findAggregator(query);if(this.right&&this.right.findAggregator&&!this.allsome){this.right.findAggregator(query)}};yy.Op.prototype.toType=function(tableid){if(["-","*","/","%","^"].indexOf(this.op)>-1)return"number";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"].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"};yy.Op.prototype.toJavaScript=function(context,tableid,defcols){var op=this.op;if(this.op=="=")op="===";else if(this.op=="<>")op="!=";else if(this.op=="OR")op="||";if(this.op=="->"){if(typeof this.right=="string"){return this.left.toJavaScript(context,tableid,defcols)+'["'+this.right+'"]'}else if(typeof this.right=="number"){return this.left.toJavaScript(context,tableid,defcols)+"["+this.right+"]"}else if(this.right instanceof yy.FuncValue){ss=[];if(!this.right.args||this.right.args.length==0){}else{var ss=this.right.args.map(function(arg){return arg.toJavaScript(context,tableid,defcols)})}return this.left.toJavaScript(context,tableid,defcols)+"['"+this.right.funcid+"']("+ss.join(",")+")"}else{return this.left.toJavaScript(context,tableid,defcols)+"["+this.right.toJavaScript(context,tableid,defcols)+"]"}}if(this.op=="IS"){return"((typeof "+this.left.toJavaScript(context,tableid,defcols)+"=='undefined') == "+"(typeof "+this.right.toJavaScript(context,tableid,defcols)+"=='undefined'))"}if(this.op=="=="){return"alasql.utils.deepEqual("+this.left.toJavaScript(context,tableid,defcols)+","+this.right.toJavaScript(context,tableid,defcols)+")"}if(this.op=="==="){return"(("+this.left.toJavaScript(context,tableid,defcols)+").valueOf()===("+this.right.toJavaScript(context,tableid,defcols)+".valueOf()))"}if(this.op=="!==="){return"!(("+this.left.toJavaScript(context,tableid,defcols)+").valueOf()===("+this.right.toJavaScript(context,tableid,defcols)+".valueOf()))"}if(this.op=="!=="){return"(!alasql.utils.deepEqual("+this.left.toJavaScript(context,tableid,defcols)+","+this.right.toJavaScript(context,tableid,defcols)+"))"}if(this.op=="LIKE"){var s="("+this.left.toJavaScript(context,tableid,defcols)+"+'')"+".toUpperCase().match(new RegExp('^'+("+this.right.toJavaScript(context,tableid,defcols)+").replace(/\\%/g,'.*').toUpperCase()+'$','g'))";return s}if(this.op=="NOT LIKE"){var s="!(("+this.left.toJavaScript(context,tableid,defcols)+"+'')"+".toUpperCase().match(new RegExp('^'+("+this.right.toJavaScript(context,tableid,defcols)+").replace(/\\%/g,'.*').toUpperCase()+'$','g')))";return s}if(this.op=="BETWEEN"){if(this.right instanceof yy.Op&&this.right.op=="AND"){return"(("+this.right.left.toJavaScript(context,tableid,defcols)+"<="+this.left.toJavaScript(context,tableid,defcols)+")&&"+"("+this.left.toJavaScript(context,tableid,defcols)+"<="+this.right.right.toJavaScript(context,tableid,defcols)+"))"}else{throw new Error("Wrong BETWEEN operator without AND part")}}if(this.op=="NOT BETWEEN"){if(this.right instanceof yy.Op&&this.right.op=="AND"){return"!(("+this.right.left.toJavaScript(context,tableid,defcols)+"<="+this.left.toJavaScript(context,tableid,defcols)+")&&"+"("+this.left.toJavaScript(context,tableid,defcols)+"<="+this.right.right.toJavaScript(context,tableid,defcols)+"))"}else{throw new Error("Wrong NOT BETWEEN operator without AND part")}}if(this.op=="IN"){if(this.right instanceof yy.Select){var s="(";s+="alasql.utils.flatArray(this.query.queriesfn["+this.queriesidx+"](params,null,p))";s+=".indexOf(";s+=this.left.toJavaScript(context,tableid,defcols)+")>-1)";return s}else if(this.right instanceof Array){var s="(["+this.right.map(function(a){return a.toJavaScript(context,tableid,defcols)}).join(",")+"].indexOf(";s+=this.left.toJavaScript(context,tableid,defcols)+")>-1)";return s}else{var s="("+this.right.toJavaScript(context,tableid,defcols)+".indexOf(";s+=this.left.toJavaScript(context,tableid,defcols)+")>-1)";return s}}if(this.op=="NOT IN"){if(this.right instanceof yy.Select){var s="(";s+="alasql.utils.flatArray(this.query.queriesfn["+this.queriesidx+"](params,null,p))";s+=".indexOf(";s+=this.left.toJavaScript(context,tableid,defcols)+")<0)";return s}else if(this.right instanceof Array){var s="(["+this.right.map(function(a){return a.toJavaScript(context,tableid,defcols)}).join(",")+"].indexOf(";s+=this.left.toJavaScript(context,tableid,defcols)+")<0)";return s}else{throw new Error("Wrong NOT IN operator without SELECT part")}}if(this.allsome=="ALL"){if(this.right instanceof yy.Select){var s="alasql.utils.flatArray(this.query.queriesfn["+this.queriesidx+"](params,null,p))";s+=".every(function(b){return (";s+=this.left.toJavaScript(context,tableid,defcols)+")"+op+"b})";return s}else if(this.right instanceof Array){var s="["+this.right.map(function(a){return a.toJavaScript(context,tableid,defcols)}).join(",")+"].every(function(b){return (";s+=this.left.toJavaScript(context,tableid,defcols)+")"+op+"b})";return s}else{throw new Error("Wrong NOT IN operator without SELECT part")}}if(this.allsome=="SOME"||this.allsome=="ANY"){if(this.right instanceof yy.Select){var s="alasql.utils.flatArray(this.query.queriesfn["+this.queriesidx+"](params,null,p))";s+=".some(function(b){return (";s+=this.left.toJavaScript(context,tableid,defcols)+")"+op+"b})";return s}else if(this.right instanceof Array){var s="["+this.right.map(function(a){return a.toJavaScript(context,tableid,defcols)}).join(",")+"].some(function(b){return (";s+=this.left.toJavaScript(context,tableid,defcols)+")"+op+"b})";return s}else{throw new Error("Wrong NOT IN operator without SELECT part")}}if(this.op=="AND"){if(this.left.reduced){if(this.right.reduced){return"true"}else{return this.right.toJavaScript(context,tableid,defcols)}}else if(this.right.reduced){return this.left.toJavaScript(context,tableid,defcols)}op="&&"}if(this.op=="^"){return"Math.pow("+this.left.toJavaScript(context,tableid,defcols)+","+this.right.toJavaScript(context,tableid,defcols)+")"}return"("+this.left.toJavaScript(context,tableid,defcols)+op+this.right.toJavaScript(context,tableid,defcols)+")"};yy.VarValue=function(params){return yy.extend(this,params)};yy.VarValue.prototype.toString=function(){return"@"+L(this.variable)};yy.VarValue.prototype.toType=function(){return"unknown"};yy.VarValue.prototype.toJavaScript=function(){return"alasql.vars['"+this.variable+"']"};yy.NumValue=function(params){return yy.extend(this,params)};yy.NumValue.prototype.toString=function(){return N(this.value.toString())};yy.NumValue.prototype.toType=function(){return"number"};yy.NumValue.prototype.toJavaScript=function(){return""+this.value};yy.StringValue=function(params){return yy.extend(this,params)};yy.StringValue.prototype.toString=function(){return"'"+S(this.value.toString())+"'"};yy.StringValue.prototype.toType=function(){return"string"};yy.StringValue.prototype.toJavaScript=function(){return"'"+escapeq(this.value)+"'"};yy.LogicValue=function(params){return yy.extend(this,params)};yy.LogicValue.prototype.toString=function(){return this.value?"TRUE":"FALSE"};yy.LogicValue.prototype.toType=function(){return"boolean"};yy.LogicValue.prototype.toJavaScript=function(){return this.value?"true":"false"};yy.NullValue=function(params){return yy.extend(this,params)};yy.NullValue.prototype.toString=function(){return"NULL"};yy.NullValue.prototype.toJavaScript=function(){return"undefined"};yy.ParamValue=function(params){return yy.extend(this,params)};yy.ParamValue.prototype.toString=function(){return"$"+this.param};yy.ParamValue.prototype.toJavaScript=function(){if(typeof this.param=="string")return"params['"+this.param+"']";else return"params["+this.param+"]"};yy.UniOp=function(params){return yy.extend(this,params)};yy.UniOp.prototype.toString=function(){if(this.op=="-")return this.op+this.right.toString();if(this.op=="+")return this.op+this.right.toString();if(this.op=="NOT")return this.op+"("+this.right.toString()+")";else if(this.op==null)return"("+this.right.toString()+")"};yy.UniOp.prototype.findAggregator=function(query){if(this.right.findAggregator)this.right.findAggregator(query)};yy.UniOp.prototype.toType=function(tableid){if(this.op=="-")return"number";if(this.op=="+")return"number";if(this.op=="NOT")return"boolean"};yy.UniOp.prototype.toJavaScript=function(context,tableid,defcols){if(this.op=="-")return"(-("+this.right.toJavaScript(context,tableid,defcols)+"))";if(this.op=="+")return"("+this.right.toJavaScript(context,tableid,defcols)+")";if(this.op=="NOT")return"!("+this.right.toJavaScript(context,tableid,defcols)+")";else if(this.op==null)return"("+this.right.toJavaScript(context,tableid,defcols)+")"};yy.Column=function(params){return yy.extend(this,params)};yy.Column.prototype.toString=function(){var s;if(this.columnid==+this.columnid){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}}return s};yy.Column.prototype.toJavaScript=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"){s="g['"+this.nick+"']"}else if(this.tableid){if(this.columnid!="_"){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!="_"){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)+"']"}}}return s};yy.AggrValue=function(params){return yy.extend(this,params)};yy.AggrValue.prototype.toString=function(){var s="";if(this.aggregatorid=="REDUCE")s+=L(this.funcid)+"(";else s+=this.aggregatorid+"(";if(this.distinct)s+=K("DISTINCT")+" ";if(this.expression)s+=this.expression.toString();s+=")";if(this.over)s+=" "+this.over.toString();return s};yy.AggrValue.prototype.findAggregator=function(query){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-1)return"number";if(["ARRAY"].indexOf(this.aggregatorid)>-1)return"array";if(["FIRST","LAST"].indexOf(this.aggregatorid)>-1)return this.expression.toType()};yy.AggrValue.prototype.toJavaScript=function(context,tableid,defcols){var colas=this.nick;if(typeof colas=="undefined")colas=this.toString();return"g['"+colas+"']"};yy.OrderExpression=function(params){return yy.extend(this,params)};yy.OrderExpression.prototype.toString=function(){var s=this.expression.toString();if(this.order)s+=" "+this.order.toString();if(this.nocase)s+=" "+K("COLLATE")+" "+K("NOCASE");return s};yy.GroupExpression=function(params){return yy.extend(this,params)};yy.GroupExpression.prototype.toString=function(){return this.type+"("+this.group.toString()+")"};yy.ColumnDef=function(params){return yy.extend(this,params)};yy.ColumnDef.prototype.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};yy.FromData=function(params){return yy.extend(this,params)};yy.FromData.prototype.toString=function(){if(this.data)return K("DATA")+"("+(Math.random()*1e16|0)+")";else return"?"};yy.FromData.prototype.toJavaScript=function(){};yy.Select.prototype.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;if(db.sqlCacheSize>alasql.MAXSQLCACHESIZE){db.resetSqlCache()}db.sqlCacheSize++;db.sqlCache[hh]=statement;var res=alasql.res=statement(params,cb);return res};yy.Select.prototype.Select=function(){var self=this;var agrs=[];if(arguments.length>1){args=Array.prototype.slice.call(arguments)}else if(arguments.length==1){if(arguments[0]instanceof Array){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{}});return self};yy.Select.prototype.From=function(tableid){var self=this;if(!self.from)self.from=[];if(tableid instanceof Array){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};yy.Select.prototype.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(arguments[0]instanceof Array){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};yy.Select.prototype.Top=function(topnum){var self=this;self.top=new yy.NumValue({value:topnum});return self};yy.Select.prototype.GroupBy=function(){var self=this;var agrs=[]; +if(arguments.length>1){args=Array.prototype.slice.call(arguments)}else if(arguments.length==1){if(arguments[0]instanceof Array){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};yy.Select.prototype.Where=function(expr){var self=this;if(typeof expr=="function"){self.where=expr}return self};yy.FuncValue=function(params){return yy.extend(this,params)};yy.FuncValue.prototype.toString=function(){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)s+=" AS "+this.as.toString();return s};yy.FuncValue.prototype.findAggregator=function(query){if(this.args&&this.args.length>0){this.args.forEach(function(arg){if(arg.findAggregator)arg.findAggregator(query)})}};yy.FuncValue.prototype.toJavaScript=function(context,tableid,defcols){var s="";var funcid=this.funcid;if(alasql.fn[funcid]){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.toJavaScript(context,tableid,defcols)}).join(",")}s+=")"}else if(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.toJavaScript(context,tableid)}))}else{s+=alasql.stdlib[funcid.toUpperCase()]()}}else if(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.toJavaScript(context,tableid,defcols)}).join(",")}s+=")"}else{}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+")"};stdlib.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")}};stdlib.IFNULL=function(a,b){return"("+a+"||"+b+")"};stdlib.INSTR=function(s,p){return"(("+s+").indexOf("+p+")+1)"};stdlib.LEN=stdlib.LENGTH=function(s){return"("+s+'+"").length'};stdlib.LOWER=stdlib.LCASE=function(s){return"("+s+").toLowerCase()"};stdlib.GREATEST=function(){return"Math.max("+Array.prototype.join.call(arguments,",")+")"};stdlib.LEAST=function(){return"Math.min("+Array.prototype.join.call(arguments,",")+")"};stdlib.MID=function(a,b,c){if(arguments.length==2)return"("+a+").substr("+b+"-1)";else if(arguments.length==3)return"("+a+").substr("+b+"-1,"+c+")"};stdlib.NULLIF=function(a,b){return"("+a+"=="+b+"?null:"+a+")"};stdlib.POWER=function(a,b){return"Math.pow("+a+","+b+")"};stdlib.RANDOM=function(r){if(arguments.length==0){return"Math.random()"}else{return"(Math.random()*("+r+")|0)"}};stdlib.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+")"}};stdlib.SQRT=function(s){return"Math.sqrt("+s+")"};stdlib.TRIM=function(s){return s+".trim()"};stdlib.UPPER=stdlib.UCASE=function(s){return"("+s+").toUpperCase()"};alasql.aggr.GROUP_CONCAT=function(v,s){if(typeof s=="undefined")return v;else return s+","+v};yy.CaseValue=function(params){return yy.extend(this,params)};yy.CaseValue.prototype.toString=function(){var s="CASE ";if(this.expression)s+=this.expression.toString();if(this.whens){s+=this.whens.map(function(w){return" WHEN "+w.when.toString()+" THEN "+w.then.toString()}).join()}s+=" END";return s};yy.CaseValue.prototype.findAggregator=function(query){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)})}};yy.CaseValue.prototype.toJavaScript=function(context,tableid,defcols){var s="(function("+context+",params,alasql){var r;";if(this.expression){s+="v="+this.expression.toJavaScript(context,tableid,defcols)+";";s+=(this.whens||[]).map(function(w){return" if(v=="+w.when.toJavaScript(context,tableid,defcols)+") {r="+w.then.toJavaScript(context,tableid,defcols)+"}"}).join(" else ");if(this.elses)s+=" else {r="+this.elses.toJavaScript(context,tableid,defcols)+"}"}else{s+=(this.whens||[]).map(function(w){return" if("+w.when.toJavaScript(context,tableid,defcols)+") {r="+w.then.toJavaScript(context,tableid,defcols)+"}"}).join(" else ");if(this.elses)s+=" else {r="+this.elses.toJavaScript(context,tableid,defcols)+"}"}s+="return r;})("+context+",params,alasql)";return s};yy.Json=function(params){return yy.extend(this,params)};yy.Json.prototype.toString=function(){var s="@";s+=JSONtoString(this.value);s+="";return s};var JSONtoString=alasql.utils.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(obj instanceof Array){s+="["+obj.map(function(b){return JSONtoString(b)}).join(",")+"]"}else if(!obj.toJavaScript||obj instanceof yy.Json){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};function JSONtoJavaScript(obj,context,tableid,defcols){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(obj instanceof Array){s+="["+obj.map(function(b){return JSONtoJavaScript(b,context,tableid,defcols)}).join(",")+"]"}else if(!obj.toJavaScript||obj instanceof yy.Json){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+=":"+JSONtoJavaScript(obj[k],context,tableid,defcols);ss.push(s1)}s+=ss.join(",")+"}"}else if(obj.toJavaScript){s=obj.toJavaScript(context,tableid,defcols)}else{throw new Error("1Can not parse JSON object "+JSON.stringify(obj))}}else{throw new Error("2Can not parse JSON object "+JSON.stringify(obj))}return s}yy.Json.prototype.toJavaScript=function(context,tableid,defcols){return JSONtoJavaScript(this.value,context,tableid,defcols)};yy.Convert=function(params){return yy.extend(this,params)};yy.Convert.prototype.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};yy.Convert.prototype.toJavaScript=function(context,tableid,defcols){return"alasql.stdfn.CONVERT("+this.expression.toJavaScript(context,tableid,defcols)+',{dbtypeid:"'+this.dbtypeid+'",dbsize:'+this.dbsize+",style:"+this.style+"})";throw new Error("There is not such type conversion for "+this.toString())};alasql.stdfn.CONVERT=function(value,args){var val=value;if(args.style){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);if(args.style==1){val=("0"+(t.getMonth()+1)).substr(-2)+"/"+("0"+t.getDate()).substr(-2)+"/"+("0"+t.getYear()).substr(-2)}else if(args.style==2){val=("0"+t.getYear()).substr(-2)+"."+("0"+(t.getMonth()+1)).substr(-2)+"."+("0"+t.getDate()).substr(-2)}else if(args.style==3){val=("0"+t.getDate()).substr(-2)+"/"+("0"+(t.getMonth()+1)).substr(-2)+"/"+("0"+t.getYear()).substr(-2)}else if(args.style==4){val=("0"+t.getDate()).substr(-2)+"."+("0"+(t.getMonth()+1)).substr(-2)+"."+("0"+t.getYear()).substr(-2)}else if(args.style==5){val=("0"+t.getDate()).substr(-2)+"-"+("0"+(t.getMonth()+1)).substr(-2)+"-"+("0"+t.getYear()).substr(-2)}else if(args.style==6){val=("0"+t.getDate()).substr(-2)+" "+t.toString().substr(4,3).toLowerCase()+" "+("0"+t.getYear()).substr(-2)}else if(args.style==7){val=t.toString().substr(4,3)+" "+("0"+t.getDate()).substr(-2)+","+("0"+t.getYear()).substr(-2)}else if(args.style==8){val=("0"+t.getHours()).substr(-2)+":"+("0"+(t.getMinutes()+1)).substr(-2)+":"+("0"+t.getSeconds()).substr(-2)}else if(args.style==10){val=("0"+(t.getMonth()+1)).substr(-2)+"-"+("0"+t.getDate()).substr(-2)+"-"+("0"+t.getYear()).substr(-2)}else if(args.style==11){val=("0"+t.getYear()).substr(-2)+"/"+("0"+(t.getMonth()+1)).substr(-2)+"/"+("0"+t.getDate()).substr(-2)}else if(args.style==12){val=("0"+t.getYear()).substr(-2)+("0"+(t.getMonth()+1)).substr(-2)+("0"+t.getDate()).substr(-2)}else if(args.style==101){val=("0"+(t.getMonth()+1)).substr(-2)+"/"+("0"+t.getDate()).substr(-2)+"/"+t.getFullYear()}else if(args.style==102){val=t.getFullYear()+"."+("0"+(t.getMonth()+1)).substr(-2)+"."+("0"+t.getDate()).substr(-2)}else if(args.style==103){val=("0"+t.getDate()).substr(-2)+"/"+("0"+(t.getMonth()+1)).substr(-2)+"/"+t.getFullYear()}else if(args.style==104){val=("0"+t.getDate()).substr(-2)+"."+("0"+(t.getMonth()+1)).substr(-2)+"."+t.getFullYear()}else if(args.style==105){val=("0"+t.getDate()).substr(-2)+"-"+("0"+(t.getMonth()+1)).substr(-2)+"-"+t.getFullYear()}else if(args.style==106){val=("0"+t.getDate()).substr(-2)+" "+t.toString().substr(4,3).toLowerCase()+" "+t.getFullYear()}else if(args.style==107){val=t.toString().substr(4,3)+" "+("0"+t.getDate()).substr(-2)+","+t.getFullYear()}else if(args.style==108){val=("0"+t.getHours()).substr(-2)+":"+("0"+(t.getMinutes()+1)).substr(-2)+":"+("0"+t.getSeconds()).substr(-2)}else if(args.style==110){val=("0"+(t.getMonth()+1)).substr(-2)+"-"+("0"+t.getDate()).substr(-2)+"-"+t.getFullYear()}else if(args.style==111){val=t.getFullYear()+"/"+("0"+(t.getMonth()+1)).substr(-2)+"/"+("0"+t.getDate()).substr(-2)}else if(args.style==112){val=t.getFullYear()+("0"+(t.getMonth()+1)).substr(-2)+("0"+t.getDate()).substr(-2)}else{throw new Error("The CONVERT style "+args.style+" is not realized yet.")}}if(args.dbtypeid=="Date"){return new Date(val)}else if(args.dbtypeid.toUpperCase()=="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(args.dbtypeid=="DATETIME"){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()).substr(-3);return s}else if(args.dbtypeid.toUpperCase()=="STRING"){return""+val}else if(args.dbtypeid.toUpperCase()=="NUMBER"||args.dbtypeid=="FLOAT"){return+val}else if(args.dbtypeid.toUpperCase()=="MONEY"){var m=+val;return(m|0)+m*100%100/100}else if(args.dbtypeid.toUpperCase()=="BOOLEAN"){return!!val}else if(args.dbtypeid.toUpperCase()=="INT"){return val|0}else if(args.dbtypeid.toUpperCase()=="VARCHAR"||args.dbtypeid=="NVARCHAR"){if(args.dbsize)return(""+val).substr(0,args.dbsize);else return""+val}else if(args.dbtypeid.toUpperCase()=="CHAR"||args.dbtypeid=="NCHAR"){return(val+new Array(args.dbsize+1).join(" ")).substr(0,args.dbsize)}};yy.ColumnDef=function(params){return yy.extend(this,params)};yy.ColumnDef.prototype.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};yy.CreateTable=function(params){return yy.extend(this,params)};yy.CreateTable.prototype.toString=function(){var s=K("CREATE");if(this.temporary)s+=" "+K("TEMPORARY");if(this.view)s+=" "+K("VIEW");else s+=" "+K("TABLE");if(this.ifnotexists)s+=" "+K("IF")+" "+K("NOT")+" "+K("EXISTS");s+=" "+this.table.toString();if(this.viewcolumns){s+="("+this.viewcolumns.map(function(vcol){return vcol.toString()}).join(",")+")"}if(this.as)s+=" "+K("AS")+" "+L(this.as);else{var ss=this.columns.map(function(col){return col.toString()});s+=" ("+NL()+ID()+ss.join(","+NL()+ID())+")"}if(this.view&&this.select){s+=" AS "+this.select.toString()}return s};yy.CreateTable.prototype.execute=function(databaseid,params,cb){var db=alasql.databases[this.table.databaseid||databaseid];var tableid=this.table.tableid;if(!tableid){throw new Error("Table name is not defined")}var columns=this.columns;var constraints=this.constraints||[];if(this.ifnotexists&&db.tables[tableid])return 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;var ss=[];if(this.columns){this.columns.forEach(function(col){var dbtypeid=col.dbtypeid;if(!alasql.fn[dbtypeid])dbtypeid=dbtypeid.toUpperCase();var newcol={columnid:col.columnid,dbtypeid:dbtypeid};if(col.default){ss.push("'"+col.columnid+"':"+col.default.toJavaScript())}table.columns.push(newcol);table.xcolumns[newcol.columnid]=newcol;if(col.primarykey){var pk=table.pk={};pk.columns=[col.columnid];pk.onrightfns="r['"+col.columnid+"']";pk.onrightfn=new Function("r","return "+pk.onrightfns);pk.hh=hash(pk.onrightfns);table.indices[pk.hh]={}}})}table.defaultfns=ss.join(",");constraints.forEach(function(con){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","return "+pk.onrightfns);pk.hh=hash(pk.onrightfns);table.indices[pk.hh]={}}});if(this.view&&this.viewcolumns){var self=this;this.viewcolumns.forEach(function(vcol,idx){self.select.columns[idx].as=vcol.columnid})}if(db.engineid){return alasql.engines[db.engineid].createTable(this.table.databaseid||databaseid,tableid,this.ifnotexists,cb)}table.insert=function(r){if(this.pk){var pk=this.pk;var addr=pk.onrightfn(r);if(typeof this.indices[pk.hh][addr]!="undefined"){throw new Error("Cannot insert record, because it already exists in primary key")}else{table.data.push(r);this.indices[pk.hh][addr]=r}}else{table.data.push(r)}};table.delete=function(i){if(this.pk){var r=this.data[i];var pk=this.pk;var addr=pk.onrightfn(r);if(typeof this.indices[pk.hh][addr]=="undefined"){throw new Error("Something wrong with index on table")}else{this.indices[pk.hh][addr]=undefined}}};table.deleteall=function(){this.data.length=0;if(this.pk){this.indices[this.pk.hh]={}}};table.update=function(assignfn,i,params){if(this.pk){var r=this.data[i];var pk=this.pk;var addr=pk.onrightfn(r,params);if(typeof this.indices[pk.hh][addr]=="undefined"){throw new Error("Something wrong with index on table")}else{this.indices[pk.hh][addr]=undefined;assignfn(r,params,alasql);var newaddr=pk.onrightfn(r);if(typeof this.indices[pk.hh][newaddr]!="undefined"){throw new Error("Record already exists")}else{this.indices[pk.hh][newaddr]=r}}}else{assignfn(this.data[i],params,alasql)}};if(this.view&&this.select){table.view=true;table.select=this.select.compile(this.table.databaseid||databaseid)}if(cb)cb(1);return 1};alasql.fn.Date=Object;alasql.fn.Date=Date;alasql.fn.Number=Number;alasql.fn.String=String;alasql.fn.Boolean=Boolean;stdfn.EXTEND=alasql.utils.extend;stdfn.CHAR=String.fromCharCode.bind(String);stdfn.ASCII=function(a){return a.charCodeAt(0)};stdfn.COALESCE=function(){for(var i=0;i0){for(var i=0,ilen=table.data.length;i0){for(var i=0,ilen=table.data.length;i=0){q+="+"+values[idx].toJavaScript()}else if(alasql.fn[table.xcolumns[col.columnid].dbtypeid]){q+="(new "+table.xcolumns[col.columnid].dbtypeid+"(";q+=values[idx].toJavaScript();q+="))"}else{q+=values[idx].toJavaScript()}}else{q+=values[idx].toJavaScript()}ss.push(q)})}else{if(values instanceof Array&&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].toJavaScript()}else if(alasql.fn[col.dbtypeid]){q+="(new "+col.dbtypeid+"(";q+=values[idx].toJavaScript();q+="))"}else{q+=values[idx].toJavaScript()}ss.push(q)})}else{sw=JSONtoJavaScript(values)}}if(db.tables[tableid].defaultfns)ss.unshift(db.tables[tableid].defaultfns);if(sw){s+="a="+sw+";"}else{s+="a={"+ss.join(",")+"};"}if(db.tables[tableid].insert){s+="alasql.databases['"+databaseid+"'].tables['"+tableid+"'].insert(a);"}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);"}s+="return "+self.values.length;var insertfn=new Function("db, params, alasql",s3+s)}else if(this.select){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,null,cb);return res};return statement}else{var insertfn=function(db,params,alasql){var res=selectfn(params);if(db.tables[tableid].insert){for(var i=0,ilen=res.length;i0){s+="("+this.args.map(function(arg){return arg.toString()}).join(", ")+")"}if(this.as)s+=" "+K("AS")+" "+L(this.as);return s};yy.CreateDatabase.prototype.execute=function(databaseid,params,cb){var args;if(this.args&&this.args.length>0){args=this.args.map(function(arg){return new Function("params","return "+arg.toJavaScript())(params)})}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}};yy.AttachDatabase=function(params){return yy.extend(this,params)};yy.AttachDatabase.prototype.toString=function(){var s=K("ATTACH");if(this.engineid)s+=" "+L(this.engineid);s+=" "+K("DATABASE")+" "+L(this.databaseid);if(args){s+="(";if(args.length>0){s+=args.map(function(arg){return arg.toString()}).join(", ")}s+=")"}if(this.as)s+=" "+K("AS")+" "+L(this.as);return s};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};yy.DetachDatabase=function(params){return yy.extend(this,params)};yy.DetachDatabase.prototype.toString=function(){var s=K("DETACH");s+=" "+K("DATABASE")+" "+L(this.databaseid);return s};yy.DetachDatabase.prototype.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};yy.UseDatabase=function(params){return yy.extend(this,params)};yy.UseDatabase.prototype.toString=function(){return K("USE")+" "+K("DATABASE")+" "+L(this.databaseid)};yy.UseDatabase.prototype.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};yy.DropDatabase=function(params){return yy.extend(this,params)};yy.DropDatabase.prototype.toString=function(){var s=K("DROP");if(this.ifexists)s+=" "+K("IF")+" "+K("EXISTS");s+=" "+K("DATABASE")+" "+L(this.databaseid);return s};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]){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};yy.Declare=function(params){return yy.extend(this,params)};yy.Declare.prototype.toString=function(){var s=K("DECLARE")+" ";if(this.declares&&this.declares.length>0){s=this.declares.map(function(declare){var s="";s+="@"+L(declare.variable)+" ";s+=declare.dbtypeid;if(this.dbsize)s+="("+N(this.dbsize);if(this.dbprecision)s+=","+N(this.dbprecision);s+=")";if(declare.expression)s+=" = "+declare.expression.toString();return s}).join(",")}return s};yy.Declare.prototype.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};if(declare.expression){alasql.vars[declare.variable]=new Function("params,alasql","return "+declare.expression.toJavaScript("","",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};yy.ShowDatabases=function(params){return yy.extend(this,params)};yy.ShowDatabases.prototype.toString=function(){var s=K("SHOW")+" "+K("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){res=res.filter(function(d){return d.databaseid.match(new RegExp(self.like.value.replace(/\%/g,".*"),"g"))})}if(cb)cb(res);return res}};yy.ShowTables=function(params){return yy.extend(this,params)};yy.ShowTables.prototype.toString=function(){var s=K("SHOW")+" "+K("TABLES");if(this.databaseid)s+=" FROM "+this.databaseid;if(this.like)s+=" "+K("LIKE")+" "+this.like.toString();return s};yy.ShowTables.prototype.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,".*"),"g"))})}if(cb)cb(res);return res};yy.ShowColumns=function(params){return yy.extend(this,params)};yy.ShowColumns.prototype.toString=function(){var s=K("SHOW")+" "+K("COLUMNS");if(this.table.tableid)s+=" "+K("FROM")+" "+this.table.tableid;if(this.databaseid)s+=" "+K("FROM")+" "+this.databaseid;return s};yy.ShowColumns.prototype.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[]}};yy.ShowIndex=function(params){return yy.extend(this,params)};yy.ShowIndex.prototype.toString=function(){var s=K("SHOW")+" "+K("INDEX");if(this.table.tableid)s+=" "+K("FROM")+" "+this.table.tableid;if(this.databaseid)s+=" "+K("FROM")+" "+this.databaseid;return s};yy.ShowIndex.prototype.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};yy.ShowCreateTable=function(params){return yy.extend(this,params)};yy.ShowCreateTable.prototype.toString=function(){var s=K("SHOW")+" "+K("CREATE")+" "+K("TABLE")+" "+L(this.table.tableid);if(this.databaseid)s+=" "+K("FROM")+" "+L(this.databaseid);return s};yy.ShowCreateTable.prototype.execute=function(databaseid){var db=alasql.databases[this.databaseid||databaseid];var table=db.tables[this.table.tableid];var self=this;if(table){var s=K("CREATE")+" "+K("TABLE")+" "+L(this.table.tableid)+" (";var ss=[];if(table.columns){table.columns.forEach(function(col){var a=L(col.columnid)+" "+K(col.dbtypeid);if(col.dbsize)a+="("+N(col.dbsize)+")";if(col.primarykey)a+=" "+K("PRIMARY")+" "+K("KEY");ss.push(a)});s+=ss.join(", ")}s+=")";return s}else{throw new Error('There is no such table "'+this.table.tableid+'"')}};yy.SetVariable=function(params){return yy.extend(this,params)};yy.SetVariable.prototype.toString=function(){var s=K("SET")+" ";if(typeof this.value!="undefined")s+=K(this.variable.toUpperCase())+" "+(this.value?"ON":"OFF");if(this.expression)s+="@"+L(this.variable)+" = "+this.expression.toString();return s};yy.SetVariable.prototype.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){var res=new Function("params,alasql","return "+this.expression.toJavaScript("","",null))(params,alasql);if(alasql.declares[this.variable]){res=alasql.stdfn.CONVERT(res,alasql.declares[this.variable])}if(this.props&&this.props.length>0){var fs="alasql.vars['"+this.variable+"']";fs+=this.props.map(function(prop){if(typeof prop=="string"){return"['"+prop+"']"}else if(typeof prop=="number"){return"["+prop+"]"}else{return"["+prop.toJavaScript()+"]"}}).join();new Function("value,alasql",fs+"=value")(res,alasql)}else{alasql.vars[this.variable]=res}}var res=1;if(cb)res=cb(res);return res};alasql.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",sql);if(res instanceof Array){if(console.table){console.table(res)}else{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{el=target}}var s="";if(typeof sql=="string"&&alasql.options.logprompt){s+="

"+alasql.pretty(sql)+"
"}if(res instanceof Array){if(res.length==0){s+="

[ ]

"}else if(typeof res[0]!="object"||res[0]instanceof Array){for(var i=0,ilen=res.length;i"+loghtml(res[i])+"

"}}else{s+=loghtml(res)}}else{s+=loghtml(res)}el.innerHTML+=s}};alasql.clear=function(){var target=alasql.options.logtarget;if(typeof exports=="object"){target="console"}if(target=="console"||typeof exports=="object"){if(console.clear){console.clear()}else{}}else{var el;if(target=="output"){el=document.getElementsByTagName("output")[0]}else{if(typeof target=="string"){el=document.getElementById(target)}else{el=target}}el.innerHTML=""}};alasql.write=function(s){var target=alasql.options.logtarget;if(typeof exports=="object"){target="console"}if(target=="console"||typeof exports=="object"){if(console.log){console.log(s)}else{}}else{var el;if(target=="output"){el=document.getElementsByTagName("output")[0]}else{if(typeof target=="string"){el=document.getElementById(target)}else{el=target}}el.innerHTML+=s}};function loghtml(res){var s="";if(typeof res=="undefined"){s+="undefined"}else if(res instanceof Array){s+="";s+="";var cols=[];for(colid in res[0]){cols.push(colid)}s+="
#";cols.forEach(function(colid){s+=""+colid});for(var i=0,ilen=res.length;i"+(i+1);cols.forEach(function(colid){s+=" ";if(+res[i][colid]==+res[i][colid]){s+='
';if(typeof res[i][colid]=="undefined")s+="NULL";else s+=res[i][colid];s+="
"}else{if(typeof res[i][colid]=="undefined"){s+="NULL"}else if(typeof res[i][colid]=="string"){s+=res[i][colid]}else s+=JSONtoString(res[i][colid])}})}s+="
"}else{s+="

"+JSONtoString(res)+"

"}return s}function scrollTo(element,to,duration){if(duration<=0)return;var difference=to-element.scrollTop;var perTick=difference/duration*10;setTimeout(function(){if(element.scrollTop==to)return;element.scrollTop=element.scrollTop+perTick;scrollTo(element,to,duration-10)},10)}alasql.prompt=function(el,useidel,firstsql){if(typeof exports=="object"){throw new Error("The functionality of prompt is 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('

'+(Date.now()-tm)+" ms

")}catch(err){alasql.write("

"+olduseid+"> "+sql+"

");alasql.write('

'+err+"

")}}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('

'+(Date.now()-tm)+" ms

")}catch(err){alasql.write("

"+olduseid+"> "+alasql.pretty(sql,false)+"

");alasql.write('

'+err+"

")}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()}}}};yy.BeginTransaction=function(params){return yy.extend(this,params)};yy.BeginTransaction.prototype.toString=function(){return K("BEGIN")+" "+K("TRANSACTION")};yy.BeginTransaction.prototype.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{}if(cb)cb(res);return res};yy.CommitTransaction=function(params){return yy.extend(this,params)};yy.CommitTransaction.prototype.toString=function(){return K("COMMIT")+" "+K("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{}if(cb)cb(res);return res};yy.RollbackTransaction=function(params){return yy.extend(this,params)};yy.RollbackTransaction.prototype.toString=function(){return K("ROLLBACK")+" "+K("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{}if(cb)cb(res);return res};alasql.into.SQL=function(filename,opts,data,columns,cb){var res;if(typeof filename=="object"){opts=filename;filename=""}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{}}for(var i=0,ilen=data.length;i0){columns=Object.keys(data[0]).map(function(columnid){return{columnid:columnid}})}if(typeof filename=="object"){opts=filename;filename=null}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")}alasql.utils.saveFile(filename,s);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=" ";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"){opts=filename;filename=null}var opt={};opt.separator=",";opt.quote='"';alasql.utils.extend(opt,opts);var res=data.length;var s="";if(opt.headers){s+=columns.map(function(col){return col.columnid}).join(opt.separator)+"\n"}data.forEach(function(d,idx){s+=columns.map(function(col){var s=d[col.columnid];s=(s+"").replace(new RegExp("\\"+opt.quote,"g"),'""');if((s+"").indexOf(opt.separator)>-1||(s+"").indexOf(opt.quote)>-1)s=opt.quote+s+opt.quote;return s}).join(opt.separator)+"\n"});if(filename){alasql.utils.saveFile(filename,s)}else{console.log(s)}if(cb)res=cb(res);return res};alasql.into.XLSX=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 exports=="object"){var XLSX=require("xlsx")}else{var XLSX=window.XLSX}var opt={sheetid:"Sheet1",headers:true};alasql.utils.extend(opt,opts);var res=data.length;var wb={SheetNames:[],Sheets:{}};if(opt.sourcefilename){alasql.utils.loadBinaryFile(opt.sourcefilename,!!cb,function(data){wb=XLSX.read(data,{type:"binary"});doExport()})}else{doExport()}function doExport(){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+data.length+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}});i++}for(var j=0;j=N)return EOF;if(eol)return eol=false,EOL;var j=I;if(text.charCodeAt(j)===quoteCode){var i=j;while(i++http://github/agershun/alasq for more information'}];yy.Help.prototype.execute=function(databaseid,params,cb){var ss=[];if(!this.subject){ss=helpdocs}else{ss.push('See also http://github/agershun/alasq for more information')}if(cb)ss=cb(ss);return ss};yy.Print=function(params){return yy.extend(this,params)};yy.Print.prototype.toString=function(){var s=K("PRINT");if(this.statement)s+=" "+this.statement.toString();return s};yy.Print.prototype.execute=function(databaseid,params,cb){var res,s;if(this.statement){s=this.statement.execute(databaseid,params)}else{s=""}s=JSONtoString(s);console.log(s);if(cb)res=cb(res);return res};yy.Source=function(params){return yy.extend(this,params)};yy.Source.prototype.toString=function(){var s=K("SOURCE");if(this.url)s+=" "+S("'"+this.url+"'");return s};yy.Source.prototype.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};yy.Require=function(params){return yy.extend(this,params)};yy.Require.prototype.toString=function(){var s=K("REQUIRE");if(this.paths&&this.paths.length>0){s+=this.paths.map(function(path){return path.toString()}).join(",")}return s};yy.Require.prototype.execute=function(databaseid,params,cb){var self=this;var res=0;var ss="";if(this.paths.length>0){this.paths.forEach(function(path){loadFile(path.value,!!cb,function(data){res++;ss+=data;if(res0){res=res.filter(function(d){return d.databaseid.match(relike)})}}if(cb)cb(res);return res};LS.createTable=function(databaseid,tableid,ifnotexists,cb){var lsdbid=alasql.databases[databaseid].lsdbid;var tb=LS.get(lsdbid+"."+tableid);var res=1;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];lsdb.tables[tableid]={columns:table.columns};LS.set(lsdbid,lsdb);LS.set(lsdbid+"."+tableid,[]);if(cb)cb(res);return res};LS.dropTable=function(databaseid,tableid,ifexists,cb){var res=1;var lsdbid=alasql.databases[databaseid].lsdbid;var lsdb=LS.get(lsdbid);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);if(cb)cb(res);return res};LS.fromTable=function(databaseid,tableid,cb,idx,query){var lsdbid=alasql.databases[databaseid].lsdbid;var res=LS.get(lsdbid+"."+tableid);if(cb)res=cb(res,idx,query);return res};LS.intoTable=function(databaseid,tableid,value,columns,cb){var lsdbid=alasql.databases[databaseid].lsdbid;var res=value.length;var tb=LS.get(lsdbid+"."+tableid);if(!tb)tb=[];tb=tb.concat(value);LS.set(lsdbid+"."+tableid,tb);if(cb)cb(res);return res};LS.loadTableData=function(databaseid,tableid){var db=alasql.databases[databaseid];var lsdbid=alasql.databases[databaseid].lsdbid;db.tables[tableid].data=LS.get(lsdbid+"."+tableid)};LS.saveTableData=function(databaseid,tableid){var db=alasql.databases[databaseid];var lsdbid=alasql.databases[databaseid].lsdbid;LS.set(lsdbid+"."+tableid,db.tables[tableid].data);db.tables[tableid].data=null};LS.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){lsdb.tables[tbid]={columns:db.tables[tbid].columns};LS.set(lsdbid+"."+tbid,db.tables[tbid].data)}}LS.set(lsdbid,lsdb);return 1};LS.begin=LS.commit;LS.rollback=function(databaseid,cb){var db=alasql.databases[databaseid];db.dbversion++;var lsdbid=alasql.databases[databaseid].lsdbid;var lsdb=LS.get(lsdbid);if(lsdb.tables){for(var tbid in lsdb.tables){var tb=new alasql.Table({columns:db.tables[tbid].columns});extend(tb,lsdb.tables[tbid]);lsdb.tables[tbid]=tb;if(!alasql.options.autocommit){lsdb.tables[tbid].data=LS.get(db.lsdbid+"."+tbid)}lsdb.tables[tbid].indexColumns()}}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"};var SQLITE=alasql.engines.SQLITE=function(){};SQLITE.createDatabase=function(wdbid,args,ifnotexists,dbid,cb){throw new Error("Connot create SQLITE database in memory. Attach it.")};SQLITE.dropDatabase=function(databaseid){throw new Error("This is impossible to drop SQLite database. Detach it.")};SQLITE.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};SQLITE.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)};SQLITE.intoTable=function(databaseid,tableid,value,columns,cb){var sqldb=alasql.databases[databaseid].sqldb;for(var i=0,ilen=value.length;i1){var sql="REQUIRE "+paths.map(function(p){return'"'+p+'"'}).join(",");alasql(sql,[],cb)}}else if(path===false){delete alasql.webworker;return}}} \ No newline at end of file diff --git a/dist/alasql.js b/dist/alasql.js index d5c8069126..a9fa873e8c 100755 --- a/dist/alasql.js +++ b/dist/alasql.js @@ -31,88 +31,88 @@ SOFTWARE. */ - -/** - UMD envelope - */ - -(function (root, factory) { - if (typeof define === 'function' && define.amd) { - define([], factory); - } else if (typeof exports === 'object') { - module.exports = factory(); - } else { - root.alasql = factory(); - } -}(this, function () { - -/** - alasql - Main Alasql class - @param {string | Object} sql SQL-statement or data object for fuent interface - @param {Object} params SQL parameters - @param {Function} cb callback function - @param {Object} scope Scope for nested queries - @return {array} Result data object - - Standard sync call: - alasql('CREATE TABLE one'); - Query: - var res = alasql('SELECT * FROM one'); - Call with parameters: - var res = alasql('SELECT * FROM ?',[data]); - Standard async call with callback 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) { - if(typeof importScripts != 'function' && alasql.webworker) { - var id = alasql.lastid++; - alasql.buffer[id] = cb; - alasql.webworker.postMessage({id:id,sql:sql,params:params}); - } else { - 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 && typeof sql == "object" && sql instanceof Array) { - // One argument data object - fluent interface - var select = new yy.Select({ - columns:[new yy.Column({columnid:'*'})], - from: [new yy.ParamValue({param:0})] - }); - select.preparams = [sql]; - return select; - } else { - // 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 HTMElement) { - 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); - } - }; -}; - -/** Current version of alasql */ -alasql.version = "0.0.44"; - + +/** + UMD envelope + */ + +(function (root, factory) { + if (typeof define === 'function' && define.amd) { + define([], factory); + } else if (typeof exports === 'object') { + module.exports = factory(); + } else { + root.alasql = factory(); + } +}(this, function () { + +/** + alasql - Main Alasql class + @param {string | Object} sql SQL-statement or data object for fuent interface + @param {Object} params SQL parameters + @param {Function} cb callback function + @param {Object} scope Scope for nested queries + @return {array} Result data object + + Standard sync call: + alasql('CREATE TABLE one'); + Query: + var res = alasql('SELECT * FROM one'); + Call with parameters: + var res = alasql('SELECT * FROM ?',[data]); + Standard async call with callback 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) { + if(typeof importScripts != 'function' && alasql.webworker) { + var id = alasql.lastid++; + alasql.buffer[id] = cb; + alasql.webworker.postMessage({id:id,sql:sql,params:params}); + } else { + 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 && typeof sql == "object" && sql instanceof Array) { + // One argument data object - fluent interface + var select = new yy.Select({ + columns:[new yy.Column({columnid:'*'})], + from: [new yy.ParamValue({param:0})] + }); + select.preparams = [sql]; + return select; + } else { + // 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 HTMElement) { + 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); + } + }; +}; + +/** Current version of alasql */ +alasql.version = "0.0.44"; + /* parser generated by jison 0.4.15 */ @@ -201,9 +201,9 @@ performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate /* actio var $0 = $$.length - 1; switch (yystate) { case 1: - - if (yy.casesensitive) this.$ = $$[$0]; - else this.$ = $$[$0].toLowerCase(); + + if (yy.casesensitive) this.$ = $$[$0]; + else this.$ = $$[$0].toLowerCase(); break; case 2: @@ -225,12 +225,12 @@ case 9: this.$ = $$[$0]; $$[$0].explain = true; break; case 10: - - this.$ = $$[$0]; - if(yy.exists) this.$.exists = yy.exists; - delete yy.exists; - if(yy.queries) this.$.queries = yy.queries; - delete yy.queries; + + this.$ = $$[$0]; + if(yy.exists) this.$.exists = yy.exists; + delete yy.exists; + if(yy.queries) this.$.queries = yy.queries; + delete yy.queries; break; case 11: case 63: case 74: case 83: case 144: case 145: case 147: case 155: case 157: case 162: case 170: case 172: case 225: case 266: case 361: case 364: case 376: case 381: case 382: case 416: @@ -246,14 +246,14 @@ case 57: this.$ = {name:$$[$0-4], select:$$[$0-1]}; break; case 58: - yy.extend(this.$,$$[$0-7]); yy.extend(this.$,$$[$0-6]); yy.extend(this.$,$$[$0-5]); yy.extend(this.$,$$[$0-4]); - yy.extend(this.$,$$[$0-3]); yy.extend(this.$,$$[$0-2]);yy.extend(this.$,$$[$0-1]); - yy.extend(this.$,$$[$0]); - this.$ = $$[$0-7]; -/* if(yy.exists) this.$.exists = yy.exists; - delete yy.exists; - if(yy.queries) this.$.queries = yy.queries; - delete yy.queries; + yy.extend(this.$,$$[$0-7]); yy.extend(this.$,$$[$0-6]); yy.extend(this.$,$$[$0-5]); yy.extend(this.$,$$[$0-4]); + yy.extend(this.$,$$[$0-3]); yy.extend(this.$,$$[$0-2]);yy.extend(this.$,$$[$0-1]); + yy.extend(this.$,$$[$0]); + this.$ = $$[$0-7]; +/* if(yy.exists) this.$.exists = yy.exists; + delete yy.exists; + if(yy.queries) this.$.queries = yy.queries; + delete yy.queries; */ break; case 59: @@ -305,18 +305,18 @@ case 76: case 77: case 78: case 79: this.$ = {into: $$[$0]} break; case 80: - - 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}})]})}; - } + + 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 81: @@ -368,22 +368,22 @@ case 98: case 99: case 102: case 105: this.$ = $$[$0]; $$[$0].as = 'default'; break; case 108: - - var s = $$[$0]; - s = s.substr(1,s.length-2); - var x3 = s.substr(-3).toUpperCase(); - var x4 = s.substr(-4).toUpperCase(); - var r; - if(s[0] == '#') { - r = 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') { - r = new yy.FuncValue({funcid: x3, args:[new yy.StringValue({value: s}), new yy.Json({value:{headers:true}})]}); - } else if(x4=='XLSX' || x4 == 'JSON') { - r = new yy.FuncValue({funcid: x4, args:[new yy.StringValue({value: s}), new yy.Json({value:{headers:true}})]}); - } else { - throw new Error('Unknown string in FROM clause'); - }; - this.$ = r; + + var s = $$[$0]; + s = s.substr(1,s.length-2); + var x3 = s.substr(-3).toUpperCase(); + var x4 = s.substr(-4).toUpperCase(); + var r; + if(s[0] == '#') { + r = 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') { + r = new yy.FuncValue({funcid: x3, args:[new yy.StringValue({value: s}), new yy.Json({value:{headers:true}})]}); + } else if(x4=='XLSX' || x4 == 'JSON') { + r = new yy.FuncValue({funcid: x4, args:[new yy.StringValue({value: s}), new yy.Json({value:{headers:true}})]}); + } else { + throw new Error('Unknown string in FROM clause'); + }; + this.$ = r; break; case 109: @@ -570,11 +570,11 @@ case 208: this.$ = new yy.Json({value:$$[$0]}); break; case 210: - - if(!yy.queries) yy.queries = []; - yy.queries.push($$[$0-1]); - $$[$0-1].queriesidx = yy.queries.length; - this.$ = $$[$0-1]; + + if(!yy.queries) yy.queries = []; + yy.queries.push($$[$0-1]); + $$[$0-1].queriesidx = yy.queries.length; + this.$ = $$[$0-1]; break; case 211: @@ -608,7 +608,7 @@ case 227: this.$ = new yy.AggrValue({aggregatorid: $$[$0-5].toUpperCase(), expression: $$[$0-2], distinct:true, over:$$[$0]}); break; case 228: - this.$ = new yy.AggrValue({aggregatorid: $$[$0-5].toUpperCase(), expression: $$[$0-2], + this.$ = new yy.AggrValue({aggregatorid: $$[$0-5].toUpperCase(), expression: $$[$0-2], over:$$[$0]}); break; case 230: case 231: @@ -651,13 +651,13 @@ case 243: this.$ = "ARRAY"; break; case 244: - - if(alasql.aggr[$$[$0-3]]) { - this.$ = new yy.AggrValue({aggregatorid: 'REDUCE', - funcid: $$[$0-3], expression: $$[$0-1].pop() }); - } else { - this.$ = new yy.FuncValue({funcid: $$[$0-3], args: $$[$0-1]}); - }; + + if(alasql.aggr[$$[$0-3]]) { + this.$ = new yy.AggrValue({aggregatorid: 'REDUCE', + funcid: $$[$0-3], expression: $$[$0-1].pop() }); + } else { + this.$ = new yy.FuncValue({funcid: $$[$0-3], args: $$[$0-1]}); + }; break; case 245: @@ -688,25 +688,25 @@ case 254: this.$ = new yy.VarValue({variable:$$[$0]}); break; case 255: - - if(!yy.exists) yy.exists = []; - this.$ = new yy.ExistsValue({value:$$[$0-1], existsidx:yy.exists.length}); - yy.exists.push($$[$0-1]); + + if(!yy.exists) yy.exists = []; + this.$ = new yy.ExistsValue({value:$$[$0-1], existsidx:yy.exists.length}); + yy.exists.push($$[$0-1]); break; case 256: case 257: this.$ = new yy.ParamValue({param: $$[$0]}); break; case 258: - - if(typeof yy.question == 'undefined') yy.question = 0; - this.$ = new yy.ParamValue({param: yy.question++}); + + if(typeof yy.question == 'undefined') yy.question = 0; + this.$ = new yy.ParamValue({param: yy.question++}); break; case 259: - - if(typeof yy.question == 'undefined') yy.question = 0; - this.$ = new yy.ParamValue({param: yy.question++, array:true}); + + if(typeof yy.question == 'undefined') yy.question = 0; + this.$ = new yy.ParamValue({param: yy.question++, array:true}); break; case 260: @@ -782,15 +782,15 @@ case 288: this.$ = new yy.Op({left:$$[$0-2], op:'!===' , right:$$[$0]}); break; case 289: - - if(!yy.queries) yy.queries = []; - this.$ = new yy.Op({left:$$[$0-5], op:$$[$0-4] , allsome:$$[$0-3], right:$$[$0-1], queriesidx: yy.queries.length}); - yy.queries.push($$[$0-1]); + + if(!yy.queries) yy.queries = []; + this.$ = new yy.Op({left:$$[$0-5], op:$$[$0-4] , allsome:$$[$0-3], right:$$[$0-1], queriesidx: yy.queries.length}); + yy.queries.push($$[$0-1]); break; case 290: - - this.$ = new yy.Op({left:$$[$0-5], op:$$[$0-4] , allsome:$$[$0-3], right:$$[$0-1]}); + + this.$ = new yy.Op({left:$$[$0-5], op:$$[$0-4] , allsome:$$[$0-3], right:$$[$0-1]}); break; case 291: @@ -812,17 +812,17 @@ case 296: this.$ = new yy.UniOp({right: $$[$0-1]}); break; case 297: - - if(!yy.queries) yy.queries = []; - this.$ = new yy.Op({left: $$[$0-4], op:'IN', right:$$[$0-1], queriesidx: yy.queries.length}); - yy.queries.push($$[$0-1]); + + if(!yy.queries) yy.queries = []; + this.$ = new yy.Op({left: $$[$0-4], op:'IN', right:$$[$0-1], queriesidx: yy.queries.length}); + yy.queries.push($$[$0-1]); break; case 298: - - if(!yy.queries) yy.queries = []; - this.$ = new yy.Op({left: $$[$0-5], op:'NOT IN', right:$$[$0-1], queriesidx: yy.queries.length}); - yy.queries.push($$[$0-1]); + + if(!yy.queries) yy.queries = []; + this.$ = new yy.Op({left: $$[$0-5], op:'NOT IN', right:$$[$0-1], queriesidx: yy.queries.length}); + yy.queries.push($$[$0-1]); break; case 299: @@ -910,16 +910,16 @@ case 339: case 340: case 342: case 350: this.$ = $$[$0-2]; $$[$0-2].push($$[$0]) break; case 351: - - this.$ = new yy.CreateTable({table:$$[$0-4]}); - //yy.extend(this.$,$$[$0-6]); - yy.extend(this.$,$$[$0-5]); - yy.extend(this.$,$$[$0-2]); + + this.$ = new yy.CreateTable({table:$$[$0-4]}); + //yy.extend(this.$,$$[$0-6]); + yy.extend(this.$,$$[$0-5]); + yy.extend(this.$,$$[$0-2]); break; case 352: - - this.$ = new yy.CreateTable({table:$$[$0]}); + + this.$ = new yy.CreateTable({table:$$[$0]}); break; case 362: case 363: @@ -980,8 +980,8 @@ case 401: this.$ = undefined break; case 403: - - yy.extend($$[$0-1],$$[$0]); this.$ = $$[$0-1]; + + yy.extend($$[$0-1],$$[$0]); this.$ = $$[$0-1]; break; case 405: @@ -1060,7 +1060,7 @@ case 431: this.$ = new yy.CreateDatabase({engineid:$$[$0-7].toUpperCase(), databaseid:$$[$0-4], args:$$[$0-2], as:$$[$0] }); yy.extend(this.$,$$[$0-5]); break; case 432: - this.$ = new yy.CreateDatabase({engineid:$$[$0-4].toUpperCase(), + this.$ = new yy.CreateDatabase({engineid:$$[$0-4].toUpperCase(), as:$$[$0], args:[$$[$0-1]] }); yy.extend(this.$,$$[$0-2]); break; case 433: @@ -1130,14 +1130,14 @@ case 456: this.$ = new yy.ShowCreateTable({table: $$[$0-2], databaseid:$$[$0]}); break; case 457: - - this.$ = new yy.CreateTable({table:$$[$0-5],view:true,select:$$[$0],viewcolumns:$$[$0-3]}); - yy.extend(this.$,$$[$0-6]); + + this.$ = new yy.CreateTable({table:$$[$0-5],view:true,select:$$[$0],viewcolumns:$$[$0-3]}); + yy.extend(this.$,$$[$0-6]); break; case 458: - - this.$ = new yy.CreateTable({table:$$[$0-2],view:true,select:$$[$0]}); + + this.$ = new yy.CreateTable({table:$$[$0-2],view:true,select:$$[$0]}); break; case 459: @@ -1222,9 +1222,9 @@ case 510: this.$ = new yy.BeginTransaction(); break; case 511: - 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; + 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 512: @@ -1234,9 +1234,9 @@ case 513: this.$ = $$[$0]; break; case 514: - this.$ = new yy.While({expression:$$[$0-1],loopstat:$$[$0]}); - if($$[$0].exists) this.$.exists = $$[$0].exists; - if($$[$0].queries) this.$.queries = $$[$0].queries; + 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 515: @@ -1273,10 +1273,10 @@ case 530: this.$ = new yy.TruncateTable({table:$$[$0]}); break; case 531: - - 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]); + + 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 532: case 533: @@ -2383,720 +2383,720 @@ function ID(){ -/* -// -// Utilities for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -/** - Alasql utility functions - */ -var utils = alasql.utils = {}; - -/** - Return true. - Stub for non-ecisting WHERE clause, because is faster then if(whenrfn) whenfn() - @return {boolean} true - */ -function returnTrue () {return true}; - -/** - Return undefined - Stub for non-ecisting WHERE clause, because is faster then if(whenrfn) whenfn() - @return undefined - */ -function returnUndefined() {}; - -/** - Escape quotes - @param {string} s Source string - @return {string} Escaped string - */ -var escapeq = utils.escapeq = function(s) { -// console.log(s); - return s.replace(/\'/g,'\\\''); -} - - -/** - Double quotes - @param {string} s Source string - @return {string} Escaped string - */ -var escapeqq = utils.undoubleq = function(s) { - return s.replace(/(\')/g,'\'\''); -} - -/** - Replace double quotes - @param {string} s Source string - @return {string} Replaced string - */ -var doubleq = utils.doubleq = function(s) { - return s.replace(/(\'\')/g,'\\\''); -} - - -/** - Replace sigle quote to escaped single quote - @param {string} s Source string - @return {string} Replaced string - */ - var doubleqq = utils.doubleqq = function(s) { - return s.replace(/\'/g,"\'"); -} - - -var cutbom = function(s) { - if(s[0] == String.fromCharCode(65279)) s = s.substr(1); - return s; -}; - -/** - Load text file from anywhere - @param {string} path File path - @param {boolean} asy True - async call, false - sync call - @param {function} success Success function - @param {function} error Error function -*/ -var loadFile = utils.loadFile = function(path, asy, success, error) { - - if(typeof exports == 'object') { - // For Node.js - var fs = require('fs'); -// console.log(36,path); -// console.log(typeof path); - if(!path) { - 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 { - // var data = fs.readFileSync(path); - // success(data.toString()); - if(asy) { - fs.readFile(path,function(err,data){ - if(err) { - throw err; - } - success(cutbom(data.toString())); - }); - } else { - var data = fs.readFileSync(path); - success(cutbom(data.toString())); - } - } - } else if(typeof cordova == 'object') { - // console.log('CORDOVA'+path); - // console.log(cordova); -// console.log('CORDOVA'+path); - - // Cordova - - window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) { - fileSystem.root.getFile(path, {create:false}, function (fileEntry) { - -// var reader = new FileReader(); -// // console.log('READ FILE 2'); -// reader.onloadend = function(e) { -// // console.log('READ FILE 3',this.result); -// success(this.result); -// }; -// reader.readAsText(file); - - fileEntry.file(function(file){ - var fileReader = new FileReader(); - fileReader.onloadend = function(e){ - success(cutbom(this.result)); - }; - fileReader.readAsText(file); - }); - // }); - }); - }); - -/* - - var paths = path.split('/'); - var filename = paths[paths.length-1]; - var dirpath = path.substr(0,path.length-filename.length); - // console.log('CORDOVA',filename,dirpath); - //return success('[{"a":"'+filename+'"}]'); - - window.resolveLocalFileSystemURL(dirpath, function(dir) { - dir.getFile(filename, null, function(file) { - file.file(function(file) { - var reader = new FileReader(); - // console.log('READ FILE 2'); - reader.onloadend = function(e) { -// console.log('READ FILE 3',this.result); - success(this.result); - }; - reader.readAsText(file); - }); - }); - }); -*/ - } else { - // if(typeof path == "string") { - // } - if(typeof path == "string") { - // For browser read from tag - if((path.substr(0,1) == '#') && (typeof document != 'undefined')) { - var data = document.querySelector(path).textContent; - success(data); - } else { - // For browser - var xhr = new XMLHttpRequest(); - xhr.onreadystatechange = function() { - if (xhr.readyState === XMLHttpRequest.DONE) { - if (xhr.status === 200) { - if (success) - success(cutbom(xhr.responseText)); - } else { - if (error) - error(xhr); - } - } - }; - xhr.open("GET", path, asy); // Async - xhr.send(); - } - } else if(path instanceof Event) { - // console.log("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(cutbom(data)); - }; - reader.readAsText(files[0]); - } - } -}; - -/** - Load binary file from anywhere - @param {string} path File path - @param {boolean} asy True - async call, false - sync call - @param {function} success Success function - @param {function} error Error function - @return 1 for Async, data - for sync version -*/ - -var loadBinaryFile = utils.loadBinaryFile = function(path, asy, success, error) { - if(typeof exports == 'object') { - // For Node.js - var fs = require('fs'); - if(asy) { - fs.readFile(path,function(err,data){ - if(err) { - throw err; - } - var arr = new Array(); - 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 = new Array(); - for(var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]); - success(arr.join("")); - } -// 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 = new Array(); - for(var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]); - success(arr.join("")); - }; - xhr.send(); - } else if(path instanceof Event) { - // console.log("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.readAsBinaryString(files[0]); - } - }; -}; - - -var removeFile = utils.removeFile = function(path,cb) { - if(typeof exports == 'object') { - var fs = require('fs'); - fs.remove(path,cb); - } else if(typeof cordova == 'object') { - window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) { - fileSystem.root.getFile(path, {create:false}, function (fileEntry) { - fileEntry.remove(cb); - if(cb) cb(); - }, function(){ - if(cb) cb(); - }); - }); - } else { - throw new Error('You can remove files only in Node.js and Apache Cordova'); - }; -}; - - -var deleteFile = utils.deleteFile = function(path,cb){ - if(typeof exports == 'object') { - var fs = require('fs'); - fs.unlink(path, cb); - }; -}; - -var fileExists = utils.fileExists = function(path,cb){ - if(typeof exports == 'object') { - var fs = require('fs'); - fs.exists(path,cb); - } else if(typeof cordova == 'object') { - window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) { - fileSystem.root.getFile(path, {create:false}, function (fileEntry) { - cb(true); - }, function(){ - cb(false); - }); - }); -/* - function fail(){ - callback(false); - } - try { - // Cordova - var paths = path.split('/'); - var filename = paths[paths.length-1]; - var dirpath = path.substr(0,path.length-filename.length); - - window.resolveLocalFileSystemURL(dirpath, function(dir) { - dir.getFile(filename, null, function(file) { - file.file(function(file) { - callback(true); - },fail); - },fail); - },fail); - } catch(err) { - fail(); - }; -*/ - } else { - // TODO Cordova, etc. - throw new Error('You can use exists() only in Node.js or Apach Cordova'); - } -}; - -/** - Save text file from anywhere - @param {string} path File path - @param {array of objects} data Data object - @param {function} cb Callback -*/ - -var saveFile = utils.saveFile = function(path, data, cb) { - if(!path) { - alasql.options.stdout = true; - console.log(data); - if(cb) cb(); - } else { - if(typeof exports == 'object') { - // For Node.js - var fs = require('fs'); - var data = fs.writeFileSync(path,data); - if(cb) cb(); - } else if(typeof cordova == 'object') { - // For Apache Cordova - window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) { -// alasql.utils.removeFile(path,function(){ - fileSystem.root.getFile(path, {create:true}, function (fileEntry) { - fileEntry.createWriter(function(fileWriter) { - fileWriter.onwriteend = function(){ - if(cb) cb(); - }; - fileWriter.write(data); - }); - }); - // }); - }); - -/* - } else if((typeof cordova == 'object') && cordova.file) { -// console.log('saveFile 1'); - // Cordova - var paths = path.split('/'); - var filename = paths[paths.length-1]; - var dirpath = path.substr(0,path.length-filename.length); - // console.log('CORDOVA',filename,dirpath); - //return success('[{"a":"'+filename+'"}]'); - - window.resolveLocalFileSystemURL(dirpath, function(dir) { -// console.log('saveFile 2'); - - dir.getFile(filename, {create:true}, function(file) { -// console.log('saveFile 3'); - -// file.file(function(file) { -// console.log('saveFile 4'); - - file.createWriter(function(fileWriter) { - -// fileWriter.seek(fileWriter.length); - - var blob = new Blob([data], {type:'text/plain'}); - fileWriter.write(blob); - fileWriter.onwriteend = function(){ - if(cb) cb(); - }; -// console.log("ok, in theory i worked"); - }); -*/ -/* - // Corodva - function writeFinish() { - // ... your done code here... - return cb() - }; - var written = 0; - var BLOCK_SIZE = 1*1024*1024; // write 1M every time of write - function writeNext(cbFinish) { - var sz = Math.min(BLOCK_SIZE, data.length - written); - var sub = data.slice(written, written+sz); - writer.write(sub); - written += sz; - writer.onwrite = function(evt) { - if (written < data.length) - writeNext(cbFinish); - else - cbFinish(); - }; - } - writeNext(writeFinish); - } -*/ -// }); -// }); -// }); - } else { - var blob = new Blob([data], {type: "text/plain;charset=utf-8"}); - saveAs(blob, path); - if(cb) cb(); - } - }; -}; - - -// For LOAD -// var saveBinaryFile = utils.saveFile = function(path, data, cb) { -// if(typeof exports == 'object') { -// // For Node.js -// var fs = require('fs'); -// var data = fs.writeFileSync(path,data); -// } else { -// var blob = new Blob([data], {type: "text/plain;charset=utf-8"}); -// saveAs(blob, path); -// } -// }; - - -// Fast hash function - -/** - Hash string to integer number - @param {string} str Source string - @return {integer} hash number -*/ - -var hash = utils.hash = function hash(str){ - var h = 0; - if (str.length == 0) return h; - for (var i = 0; i < str.length; i++) { - h = ((h<<5)-h)+str.charCodeAt(i); - h = h & h; - } - return h; -}; - -/** - Union arrays - */ -var arrayUnion = utils.arrayUnion = function (a,b) { - var r = b.slice(0); - a.forEach(function(i) { if (r.indexOf(i) < 0) r.push(i); }); - return r; -}; - -/** - Array Difference - */ -var arrayDiff = utils.arrayDiff = function (a,b) { - return a.filter(function(i) {return b.indexOf(i) < 0;}); -}; - -/** - Arrays deep intersect (with records) - */ -var arrayIntersect = utils.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; -}; - - -/** - Arrays deep union (with records) - */ -var arrayUnionDeep = utils.arrayUnionDeep = function (a,b) { - var r = b.slice(0); - a.forEach(function(ai) { - var found = false; - - r.forEach(function(ri){ -// found = found || equalDeep(ai, ri, true); - found = found || deepEqual(ai, ri); - }); - - if(!found) { - r.push(ai); - } - }); - return r; -}; - -/** - Arrays deep union (with records) - */ -var arrayExceptDeep = utils.arrayExceptDeep = function (a,b) { - var r = []; - a.forEach(function(ai) { - var found = false; - - b.forEach(function(bi){ -// found = found || equalDeep(ai, bi, true); - found = found || deepEqual(ai, bi); - }); - - if(!found) { - r.push(ai); - } - }); - return r; -}; - -/** - Arrays deep intersect (with records) - */ -var arrayIntersectDeep = utils.arrayIntersectDeep = function(a,b) { - var r = []; - a.forEach(function(ai) { - var found = false; - - b.forEach(function(bi){ -// found = found || equalDeep(ai, bi, true); - found = found || deepEqual(ai, bi, true); - }); - - if(found) { - r.push(ai); - } - }); - return r; -}; - -/** - Deep clone obects - */ -var cloneDeep = utils.cloneDeep = function cloneDeep(obj) { - if(obj == null || typeof(obj) != 'object') - return obj; - - var temp = obj.constructor(); // changed - - for(var key in obj) { - if(obj.hasOwnProperty(key)) { - temp[key] = cloneDeep(obj[key]); - } - } - return temp; -} - -/** - Check equality of objects -*/ -var equalDeep = utils.equalDeep = function equalDeep (x, y, deep) { - if (deep) { - if (x == y) return true; - - var p; - for (p in y) { - if (typeof (x[p]) == 'undefined') { return false; } - } - - for (p in y) { - if (y[p]) { - switch (typeof (y[p])) { - case 'object': - if (!equalDeep(y[p],x[p])) { return false; } break; - case 'function': - if (typeof (x[p]) == 'undefined' || - (p != 'equals' && y[p].toString() != x[p].toString())) - return false; - break; - default: - if (y[p] != x[p]) { return false; } - } - } else { - if (x[p]) - return false; - } - } - - for (p in x) { - if (typeof (y[p]) == 'undefined') { return false; } - } - - return true; - } - return x == y; -}; - -/** - COmpare two object in deep - */ -var deepEqual = utils.deepEqual = function (x, y) { - if ((typeof x == "object" && x != null) && (typeof y == "object" && y != null)) { - if (Object.keys(x).length != Object.keys(y).length) - return false; - - for (var prop in x) { - if (y.hasOwnProperty(prop)) - { - if (! deepEqual(x[prop], y[prop])) - return false; - } - else - return false; - } - - return true; - } - else if (x !== y) - return false; - else - return true; -} - - -/** - Extend object - */ -var extend = utils.extend = function extend (a,b){ - if(typeof a == 'undefined') a = {}; - for(key in b) { - if(b.hasOwnProperty(key)) { - a[key] = b[key] - } - } - return a; -};; - -/** - Flat array by first row - */ -var flatArray = utils.flatArray = function(a) { - if(!a || a.length == 0) return []; - var key = Object.keys(a[0])[0]; - if(typeof key == 'undefined') return []; - return a.map(function(ai) {return ai[key]}); -}; - -/** - Convert array of objects to array of arrays - */ -var arrayOfArrays = utils.arrayOfArrays = function (a) { - return a.map(function(aa){ - var ar = []; - for(var key in aa) ar.push(aa[key]); - return ar; - }); -}; - -/** - Excel:convert number to Excel column, like 1 => 'A' - @param {integer} i Column number, starting with 0 - @return {string} Column name, starting with 'A' -*/ - -var xlsnc = utils.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; -}; - -/** - Excel:conver Excel column name to number - @param {integer} i Column number, like 'A' or 'BE' - @return {string} Column name, starting with 0 -*/ -var xlscn = utils.xlscn = function(s) { - var n = s.charCodeAt(0)-65; - if(s.length>1) { - n = (n+1)*26+s.charCodeAt(1)-65; -// console.log(n, s.charCodeAt(0)-65, s.charCodeAt(1)-65); - if(s.length>2) { - n = (n+1)*26+s.charCodeAt(2)-65; - } - } - return n; -}; - -var domEmptyChildren = utils.domEmptyChildren = function (container){ - var len = container.childNodes.length; - while (len--) { - container.removeChild(container.lastChild); - }; -}; - +/* +// +// Utilities for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +/** + Alasql utility functions + */ +var utils = alasql.utils = {}; + +/** + Return true. + Stub for non-ecisting WHERE clause, because is faster then if(whenrfn) whenfn() + @return {boolean} true + */ +function returnTrue () {return true}; + +/** + Return undefined + Stub for non-ecisting WHERE clause, because is faster then if(whenrfn) whenfn() + @return undefined + */ +function returnUndefined() {}; + +/** + Escape quotes + @param {string} s Source string + @return {string} Escaped string + */ +var escapeq = utils.escapeq = function(s) { +// console.log(s); + return s.replace(/\'/g,'\\\''); +} + + +/** + Double quotes + @param {string} s Source string + @return {string} Escaped string + */ +var escapeqq = utils.undoubleq = function(s) { + return s.replace(/(\')/g,'\'\''); +} + +/** + Replace double quotes + @param {string} s Source string + @return {string} Replaced string + */ +var doubleq = utils.doubleq = function(s) { + return s.replace(/(\'\')/g,'\\\''); +} + + +/** + Replace sigle quote to escaped single quote + @param {string} s Source string + @return {string} Replaced string + */ + var doubleqq = utils.doubleqq = function(s) { + return s.replace(/\'/g,"\'"); +} + + +var cutbom = function(s) { + if(s[0] == String.fromCharCode(65279)) s = s.substr(1); + return s; +}; + +/** + Load text file from anywhere + @param {string} path File path + @param {boolean} asy True - async call, false - sync call + @param {function} success Success function + @param {function} error Error function +*/ +var loadFile = utils.loadFile = function(path, asy, success, error) { + + if(typeof exports == 'object') { + // For Node.js + var fs = require('fs'); +// console.log(36,path); +// console.log(typeof path); + if(!path) { + 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 { + // var data = fs.readFileSync(path); + // success(data.toString()); + if(asy) { + fs.readFile(path,function(err,data){ + if(err) { + throw err; + } + success(cutbom(data.toString())); + }); + } else { + var data = fs.readFileSync(path); + success(cutbom(data.toString())); + } + } + } else if(typeof cordova == 'object') { + // console.log('CORDOVA'+path); + // console.log(cordova); +// console.log('CORDOVA'+path); + + // Cordova + + window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) { + fileSystem.root.getFile(path, {create:false}, function (fileEntry) { + +// var reader = new FileReader(); +// // console.log('READ FILE 2'); +// reader.onloadend = function(e) { +// // console.log('READ FILE 3',this.result); +// success(this.result); +// }; +// reader.readAsText(file); + + fileEntry.file(function(file){ + var fileReader = new FileReader(); + fileReader.onloadend = function(e){ + success(cutbom(this.result)); + }; + fileReader.readAsText(file); + }); + // }); + }); + }); + +/* + + var paths = path.split('/'); + var filename = paths[paths.length-1]; + var dirpath = path.substr(0,path.length-filename.length); + // console.log('CORDOVA',filename,dirpath); + //return success('[{"a":"'+filename+'"}]'); + + window.resolveLocalFileSystemURL(dirpath, function(dir) { + dir.getFile(filename, null, function(file) { + file.file(function(file) { + var reader = new FileReader(); + // console.log('READ FILE 2'); + reader.onloadend = function(e) { +// console.log('READ FILE 3',this.result); + success(this.result); + }; + reader.readAsText(file); + }); + }); + }); +*/ + } else { + // if(typeof path == "string") { + // } + if(typeof path == "string") { + // For browser read from tag + if((path.substr(0,1) == '#') && (typeof document != 'undefined')) { + var data = document.querySelector(path).textContent; + success(data); + } else { + // For browser + var xhr = new XMLHttpRequest(); + xhr.onreadystatechange = function() { + if (xhr.readyState === XMLHttpRequest.DONE) { + if (xhr.status === 200) { + if (success) + success(cutbom(xhr.responseText)); + } else { + if (error) + error(xhr); + } + } + }; + xhr.open("GET", path, asy); // Async + xhr.send(); + } + } else if(path instanceof Event) { + // console.log("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(cutbom(data)); + }; + reader.readAsText(files[0]); + } + } +}; + +/** + Load binary file from anywhere + @param {string} path File path + @param {boolean} asy True - async call, false - sync call + @param {function} success Success function + @param {function} error Error function + @return 1 for Async, data - for sync version +*/ + +var loadBinaryFile = utils.loadBinaryFile = function(path, asy, success, error) { + if(typeof exports == 'object') { + // For Node.js + var fs = require('fs'); + if(asy) { + fs.readFile(path,function(err,data){ + if(err) { + throw err; + } + var arr = new Array(); + 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 = new Array(); + for(var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]); + success(arr.join("")); + } +// 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 = new Array(); + for(var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]); + success(arr.join("")); + }; + xhr.send(); + } else if(path instanceof Event) { + // console.log("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.readAsBinaryString(files[0]); + } + }; +}; + + +var removeFile = utils.removeFile = function(path,cb) { + if(typeof exports == 'object') { + var fs = require('fs'); + fs.remove(path,cb); + } else if(typeof cordova == 'object') { + window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) { + fileSystem.root.getFile(path, {create:false}, function (fileEntry) { + fileEntry.remove(cb); + if(cb) cb(); + }, function(){ + if(cb) cb(); + }); + }); + } else { + throw new Error('You can remove files only in Node.js and Apache Cordova'); + }; +}; + + +var deleteFile = utils.deleteFile = function(path,cb){ + if(typeof exports == 'object') { + var fs = require('fs'); + fs.unlink(path, cb); + }; +}; + +var fileExists = utils.fileExists = function(path,cb){ + if(typeof exports == 'object') { + var fs = require('fs'); + fs.exists(path,cb); + } else if(typeof cordova == 'object') { + window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) { + fileSystem.root.getFile(path, {create:false}, function (fileEntry) { + cb(true); + }, function(){ + cb(false); + }); + }); +/* + function fail(){ + callback(false); + } + try { + // Cordova + var paths = path.split('/'); + var filename = paths[paths.length-1]; + var dirpath = path.substr(0,path.length-filename.length); + + window.resolveLocalFileSystemURL(dirpath, function(dir) { + dir.getFile(filename, null, function(file) { + file.file(function(file) { + callback(true); + },fail); + },fail); + },fail); + } catch(err) { + fail(); + }; +*/ + } else { + // TODO Cordova, etc. + throw new Error('You can use exists() only in Node.js or Apach Cordova'); + } +}; + +/** + Save text file from anywhere + @param {string} path File path + @param {array of objects} data Data object + @param {function} cb Callback +*/ + +var saveFile = utils.saveFile = function(path, data, cb) { + if(!path) { + alasql.options.stdout = true; + console.log(data); + if(cb) cb(); + } else { + if(typeof exports == 'object') { + // For Node.js + var fs = require('fs'); + var data = fs.writeFileSync(path,data); + if(cb) cb(); + } else if(typeof cordova == 'object') { + // For Apache Cordova + window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) { +// alasql.utils.removeFile(path,function(){ + fileSystem.root.getFile(path, {create:true}, function (fileEntry) { + fileEntry.createWriter(function(fileWriter) { + fileWriter.onwriteend = function(){ + if(cb) cb(); + }; + fileWriter.write(data); + }); + }); + // }); + }); + +/* + } else if((typeof cordova == 'object') && cordova.file) { +// console.log('saveFile 1'); + // Cordova + var paths = path.split('/'); + var filename = paths[paths.length-1]; + var dirpath = path.substr(0,path.length-filename.length); + // console.log('CORDOVA',filename,dirpath); + //return success('[{"a":"'+filename+'"}]'); + + window.resolveLocalFileSystemURL(dirpath, function(dir) { +// console.log('saveFile 2'); + + dir.getFile(filename, {create:true}, function(file) { +// console.log('saveFile 3'); + +// file.file(function(file) { +// console.log('saveFile 4'); + + file.createWriter(function(fileWriter) { + +// fileWriter.seek(fileWriter.length); + + var blob = new Blob([data], {type:'text/plain'}); + fileWriter.write(blob); + fileWriter.onwriteend = function(){ + if(cb) cb(); + }; +// console.log("ok, in theory i worked"); + }); +*/ +/* + // Corodva + function writeFinish() { + // ... your done code here... + return cb() + }; + var written = 0; + var BLOCK_SIZE = 1*1024*1024; // write 1M every time of write + function writeNext(cbFinish) { + var sz = Math.min(BLOCK_SIZE, data.length - written); + var sub = data.slice(written, written+sz); + writer.write(sub); + written += sz; + writer.onwrite = function(evt) { + if (written < data.length) + writeNext(cbFinish); + else + cbFinish(); + }; + } + writeNext(writeFinish); + } +*/ +// }); +// }); +// }); + } else { + var blob = new Blob([data], {type: "text/plain;charset=utf-8"}); + saveAs(blob, path); + if(cb) cb(); + } + }; +}; + + +// For LOAD +// var saveBinaryFile = utils.saveFile = function(path, data, cb) { +// if(typeof exports == 'object') { +// // For Node.js +// var fs = require('fs'); +// var data = fs.writeFileSync(path,data); +// } else { +// var blob = new Blob([data], {type: "text/plain;charset=utf-8"}); +// saveAs(blob, path); +// } +// }; + + +// Fast hash function + +/** + Hash string to integer number + @param {string} str Source string + @return {integer} hash number +*/ + +var hash = utils.hash = function hash(str){ + var h = 0; + if (str.length == 0) return h; + for (var i = 0; i < str.length; i++) { + h = ((h<<5)-h)+str.charCodeAt(i); + h = h & h; + } + return h; +}; + +/** + Union arrays + */ +var arrayUnion = utils.arrayUnion = function (a,b) { + var r = b.slice(0); + a.forEach(function(i) { if (r.indexOf(i) < 0) r.push(i); }); + return r; +}; + +/** + Array Difference + */ +var arrayDiff = utils.arrayDiff = function (a,b) { + return a.filter(function(i) {return b.indexOf(i) < 0;}); +}; + +/** + Arrays deep intersect (with records) + */ +var arrayIntersect = utils.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; +}; + + +/** + Arrays deep union (with records) + */ +var arrayUnionDeep = utils.arrayUnionDeep = function (a,b) { + var r = b.slice(0); + a.forEach(function(ai) { + var found = false; + + r.forEach(function(ri){ +// found = found || equalDeep(ai, ri, true); + found = found || deepEqual(ai, ri); + }); + + if(!found) { + r.push(ai); + } + }); + return r; +}; + +/** + Arrays deep union (with records) + */ +var arrayExceptDeep = utils.arrayExceptDeep = function (a,b) { + var r = []; + a.forEach(function(ai) { + var found = false; + + b.forEach(function(bi){ +// found = found || equalDeep(ai, bi, true); + found = found || deepEqual(ai, bi); + }); + + if(!found) { + r.push(ai); + } + }); + return r; +}; + +/** + Arrays deep intersect (with records) + */ +var arrayIntersectDeep = utils.arrayIntersectDeep = function(a,b) { + var r = []; + a.forEach(function(ai) { + var found = false; + + b.forEach(function(bi){ +// found = found || equalDeep(ai, bi, true); + found = found || deepEqual(ai, bi, true); + }); + + if(found) { + r.push(ai); + } + }); + return r; +}; + +/** + Deep clone obects + */ +var cloneDeep = utils.cloneDeep = function cloneDeep(obj) { + if(obj == null || typeof(obj) != 'object') + return obj; + + var temp = obj.constructor(); // changed + + for(var key in obj) { + if(obj.hasOwnProperty(key)) { + temp[key] = cloneDeep(obj[key]); + } + } + return temp; +} + +/** + Check equality of objects +*/ +var equalDeep = utils.equalDeep = function equalDeep (x, y, deep) { + if (deep) { + if (x == y) return true; + + var p; + for (p in y) { + if (typeof (x[p]) == 'undefined') { return false; } + } + + for (p in y) { + if (y[p]) { + switch (typeof (y[p])) { + case 'object': + if (!equalDeep(y[p],x[p])) { return false; } break; + case 'function': + if (typeof (x[p]) == 'undefined' || + (p != 'equals' && y[p].toString() != x[p].toString())) + return false; + break; + default: + if (y[p] != x[p]) { return false; } + } + } else { + if (x[p]) + return false; + } + } + + for (p in x) { + if (typeof (y[p]) == 'undefined') { return false; } + } + + return true; + } + return x == y; +}; + +/** + COmpare two object in deep + */ +var deepEqual = utils.deepEqual = function (x, y) { + if ((typeof x == "object" && x != null) && (typeof y == "object" && y != null)) { + if (Object.keys(x).length != Object.keys(y).length) + return false; + + for (var prop in x) { + if (y.hasOwnProperty(prop)) + { + if (! deepEqual(x[prop], y[prop])) + return false; + } + else + return false; + } + + return true; + } + else if (x !== y) + return false; + else + return true; +} + + +/** + Extend object + */ +var extend = utils.extend = function extend (a,b){ + if(typeof a == 'undefined') a = {}; + for(key in b) { + if(b.hasOwnProperty(key)) { + a[key] = b[key] + } + } + return a; +};; + +/** + Flat array by first row + */ +var flatArray = utils.flatArray = function(a) { + if(!a || a.length == 0) return []; + var key = Object.keys(a[0])[0]; + if(typeof key == 'undefined') return []; + return a.map(function(ai) {return ai[key]}); +}; + +/** + Convert array of objects to array of arrays + */ +var arrayOfArrays = utils.arrayOfArrays = function (a) { + return a.map(function(aa){ + var ar = []; + for(var key in aa) ar.push(aa[key]); + return ar; + }); +}; + +/** + Excel:convert number to Excel column, like 1 => 'A' + @param {integer} i Column number, starting with 0 + @return {string} Column name, starting with 'A' +*/ + +var xlsnc = utils.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; +}; + +/** + Excel:conver Excel column name to number + @param {integer} i Column number, like 'A' or 'BE' + @return {string} Column name, starting with 0 +*/ +var xlscn = utils.xlscn = function(s) { + var n = s.charCodeAt(0)-65; + if(s.length>1) { + n = (n+1)*26+s.charCodeAt(1)-65; +// console.log(n, s.charCodeAt(0)-65, s.charCodeAt(1)-65); + if(s.length>2) { + n = (n+1)*26+s.charCodeAt(2)-65; + } + } + return n; +}; + +var domEmptyChildren = utils.domEmptyChildren = function (container){ + var len = container.childNodes.length; + while (len--) { + container.removeChild(container.lastChild); + }; +}; + /** @@ -3208,7152 +3208,7163 @@ alasql.utils.uncomment = function uncomment(str) { }; -/* -// -// Database class for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - - -// Initial parameters -/** - Jison parser - */ -alasql.parser = parser; - -/** - Jison parser - @param {string} sql SQL statement - @return {object} AST (Abstract Syntax Tree) - */ -alasql.parse = function(sql) { - return parser.parse(alasql.utils.uncomment(sql)); -}; // Shortcut - -// Database Engines -/** - List of engines of external databases - */ -alasql.engines = {}; - -// Databases -/** - List of databases - */ -alasql.databases = {}; - -/** Number of databases */ -alasql.databasenum = 0; // Current database - -// Deafult options -/** - Alasql options object - */ -alasql.options = {}; -alasql.options.errorlog = false; // Log or throw error -alasql.options.valueof = false; // Use valueof in orderfn -alasql.options.dropifnotexists = false; // DROP database in any case -alasql.options.datetimeformat = 'sql'; // How to handle DATE and DATETIME types - // Another value is 'javascript' -alasql.options.casesensitive = true; // Table and column names are case sensitive and converted to lower-case -alasql.options.logtarget = 'output'; // target for log. Values: 'console', 'output', 'id' of html tag -alasql.options.logprompt = true; // Print SQL at log - -//alasql.options.worker = false; -// Variables -alasql.vars = {}; -alasql.declares = {}; - -// AUTOCOMMIT ON | OFF -alasql.options.autocommit = true; - -alasql.options.cache = true; - -alasql.prompthistory = []; - -alasql.from = {}; // FROM functions -alasql.into = {}; // INTO functions - -alasql.fn = {}; -alasql.aggr = {}; - -alasql.busy = 0; - -// Cache -alasql.MAXSQLCACHESIZE = 10000; -alasql.DEFAULTDATABASEID = 'alasql'; - -/* WebWorker */ -alasql.lastid = 0; -alasql.buffer = {}; - -/** - Select current database - @param {string} databaseid Selected database identificator - */ -alasql.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(); -}; - -// Run one statement -/** - Run SQL statement on current database - */ -alasql.exec = function (sql, params, cb, scope) { - delete alasql.error; - 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); - } -} - -/** - Run SQL statement on specific database - */ -alasql.dexec = function (databaseid, sql, params, cb, scope) { - var db = alasql.databases[databaseid]; -// if(db.databaseid != databaseid) console.trace('got!'); -// console.log(3,db.databaseid,databaseid); - - // Create hash - if(alasql.options.cache) { - var 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(ast.statements.length == 0) return 0; - else if(ast.statements.length == 1) { - if(ast.statements[0].compile) { - -// Compile and Execute - var statement = ast.statements[0].compile(databaseid); - 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 { -// console.log(ast.statements[0]); - 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 - */ -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 alasql.MAXSQLCACHESIZE) { -// this.resetSqlCache(); -// } -// }; -// return statement; -// } - -// SQL.js compatibility method -//Database.prototype.prepare = Database.prototype.compile; - - -// Added for compatibility with WebSQL - - - - - -/* -// -// 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 - */ - -var Transaction = alasql.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 -// console.log(this); - return this; -}; - -// Main class - - -// Commit - -/** - Commit transaction - */ -Transaction.prototype.commit = function() { - this.commited = true; - alasql.databases[this.databaseid].dbversion = Date.now(); - delete this.bank; -}; - -// Rollback -/** - Rollback transaction - */ -Transaction.prototype.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'); - } -}; - -// Transactions stub - -/** - Execute SQL statement - @param {string} sql SQL statement - @param {object} params Parameters - @param {function} cb Callback function - @return result - */ -Transaction.prototype.exec = function(sql, params, cb) { -// console.log(this.databaseid); - return alasql.dexec(this.databaseid,sql,params,cb); -}; - -Transaction.prototype.executeSQL = Transaction.prototype.exec; - -/* -Transaction.prototype.query = Database.prototype.exec; -Transaction.prototype.run = Database.prototype.exec; -Transaction.prototype.queryArray = function(sql, params, cb) { - return flatArray(this.exec(sql, params, cb)); -} - -Transaction.prototype.queryArrayOfArrays = function(sql, params, cb) { - return arrayOfArrays(this.exec(sql, params, cb)); -} - -Transaction.prototype.querySingle = function(sql, params, cb) { - return this.exec(sql, params, cb)[0]; -} -Transaction.prototype.queryValue = function(sql, params, cb) { - var res = this.querySingle(sql, params, cb); - return res[Object.keys(res)[0]]; -} -*/ - - -/* -// -// Table class for Alasql.js -// Date: 14.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -// Table class -var Table = alasql.Table = function(params){ - // Columns - this.columns = []; - this.xcolumns = {}; - // Data array - this.data = []; - - this.inddefs = {}; - this.indices = {}; - - this.uniqs = {}; - this.uniqdefs = {}; - - extend(this,params); -}; - - -// View = function(){ -// this.data = []; -// this.columns = []; -// this.ixcolumns = {}; -// this.ixdefs = {}; -// this.indices = {}; -// }; - -// alasql.View = View; - -Table.prototype.indexColumns = function() { - var self = this; - self.xcolumns = {}; - self.columns.forEach(function(col){ - self.xcolumns[col.columnid] = col; - }); -} - - - - -/* -// -// View class for Alasql.js -// Date: 14.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -// Table class -var View = alasql.View = function(params){ - // Columns - this.columns = []; - this.xcolumns = {}; - // Data array - this.query = []; - - extend(this,params); -}; - -// View = function(){ -// this.data = []; -// this.columns = []; -// this.ixcolumns = {}; -// this.ixdefs = {}; -// this.indices = {}; -// }; - -// alasql.View = View; - - - - -/* -// -// Query class for Alasql.js -// Date: 14.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -// Table class - -/** - @class Query Main query class - */ -var Query = alasql.Query = function(params){ - this.alasql = alasql; -// console.log(12,alasql); - // Columns - this.columns = []; - this.xcolumns = {}; - this.selectGroup = []; - this.groupColumns = {}; - // Data array - extend(this,params); -}; - -/** - @class Recordset data object - */ -var Recordset = alasql.Recordset = function(params){ - // Data array - extend(this,params); -}; - - -// View = function(){ -// this.data = []; -// this.columns = []; -// this.ixcolumns = {}; -// this.ixdefs = {}; -// this.indices = {}; -// }; - -// alasql.View = View; - - - - -/* -// -// Parser helper for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -var yy = parser.yy = {}; - -// Utility -yy.extend = extend; -// Option for case sensitive -yy.casesensitive = alasql.options.casesensitive; - -// Base class for all yy classes -var Base = yy.Base = function (params) { return yy.extend(this, params); }; - -Base.prototype.toString = function() {} -Base.prototype.toType = function() {} -Base.prototype.toJavaScript = function() {} - -//var BaseClause = yy,BaseClause = function (params) { return yy.extend(this, params); }; -Base.prototype.compile = returnUndefined; -Base.prototype.exec = function() {} - -//var BaseStatement = yy,BaseStatement = function (params) { return yy.extend(this, params); }; -Base.prototype.compile = returnUndefined; -Base.prototype.exec = function() {} - - - - -/* -// -// Statements class for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -// Statements container -yy.Statements = function(params) { return yy.extend(this, params); }; - -yy.Statements.prototype.toString = function () { - return this.statements.map(function(st){return st.toString()}).join(';'+NL()); -}; - -// Compile array of statements into single statement -yy.Statements.prototype.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; - } - } -}; - - - -// Main query procedure -function queryfn(query,oldscope,cb, A,B) { - var ms; - query.sourceslen = query.sources.length; - var slen = query.sourceslen; - query.query = query; // TODO Remove to prevent memory leaks - query.A = A; - query.B = B; -// console.log(arguments); - query.cb = cb; - query.oldscope = oldscope; - - // Run all subqueries before main statement - if(query.queriesfn) { - query.sourceslen += query.queriesfn.length; - slen += query.queriesfn.length; - - query.queriesdata = []; - -// console.log(8); - query.queriesfn.forEach(function(q,idx){ -// if(query.explain) ms = Date.now(); -//console.log(18,idx); -// var res = flatArray(q(query.params,null,queryfn2,(-idx-1),query)); - -// var res = flatArray(queryfn(q.query,null,queryfn2,(-idx-1),query)); -// console.log(A,B); -// console.log(q); - q.query.params = query.params; -// query.queriesdata[idx] = - - if(false) { - queryfn(q.query,query.oldscope,queryfn2,(-idx-1),query); - } else { - queryfn2([],(-idx-1),query); - } - -// console.log(27,q); - - -// query.explaination.push({explid: query.explid++, description:'Query '+idx,ms:Date.now()-ms}); -// query.queriesdata[idx] = res; -// return res; - }); -// console.log(9,query.queriesdata.length); -// console.log(query.queriesdata[0]); - } - - var scope; - if(!oldscope) scope = {}; - else scope = cloneDeep(oldscope); - query.scope = scope; - - // First - refresh data sources - - var result; - query.sources.forEach(function(source, idx){ -// source.data = query.database.tables[source.tableid].data; -// console.log(666,idx); - source.query = query; - var rs = source.datafn(query, query.params, queryfn2, idx, alasql); -// console.log(333,rs); - if(typeof rs != undefined) { - // TODO - this is a hack: check if result is array - check all cases and - // make it more logical - if((query.intofn || query.intoallfn) && rs instanceof Array) rs = rs.length; - result = rs; - } -// console.log(444,result); -// -// Ugly hack to use in query.wherefn and source.srcwherefns functions -// constructions like this.queriesdata['test']. -// I can elimite it with source.srcwherefn.bind(this)() -// but it may be slow. -// - source.queriesdata = query.queriesdata; - }); - if(slen == 0) result = queryfn3(query); - return result; -}; - -function queryfn2(data,idx,query) { - -//console.log(56,arguments); -// console.log(78,data, idx,query); -//console.trace(); - - if(idx>=0) { - var source = query.sources[idx]; - source.data = data; - if(typeof source.data == 'function') { - source.getfn = source.data; - source.dontcache = source.getfn.dontcache; - - // var prevsource = query.sources[h-1]; - if(source.joinmode == 'OUTER' || source.joinmode == 'RIGHT' || source.joinmode == 'ANTI') { - source.dontcache = false; - } - source.data = {}; - } - } else { - // subqueries -// console.log("queriesdata",data, flatArray(data)); - query.queriesdata[-idx-1] = flatArray(data); -// console.log(98,query.queriesdata); -// console.log(79,query.queriesdata); - } - - query.sourceslen--; - if(query.sourceslen>0) return; - - return queryfn3(query); -}; - -function queryfn3(query) { -//console.log(55,query); - - - var scope = query.scope; - // Preindexation of data sources -// if(!oldscope) { - preIndex(query); -// } - - // query.sources.forEach(function(source) { - // console.log(source.data); - // }); - - // Prepare variables - query.data = []; - query.xgroups = {}; - query.groups = []; - - // Level of Joins - var h = 0; - - // Start walking over data - doJoin(query, scope, h); - -//console.log(85,query.data[0]); - - // If groupping, then filter groups with HAVING function -// console.log(query.havingfns); - if(query.groupfn) { - query.data = []; - if(query.groups.length == 0) { - var g = {}; - if(query.selectGroup.length>0) { -// console.log(query.selectGroup); - query.selectGroup.forEach(function(sg){ - if(sg.aggregatorid == "COUNT" || sg.aggregatorid == "SUM") { - g[sg.nick] = 0; - } else { - g[sg.nick] = undefined; - } - }); - }; - query.groups = [g]; -// console.log(); - }; - // console.log('EMPTY',query.groups); - // debugger; - // if(false && (query.groups.length == 1) && (Object.keys(query.groups[0]).length == 0)) { - // console.log('EMPTY',query.groups); - // } else { - for(var i=0,ilen=query.groups.length;i 0) { - for(var i=0,ilen=query.data.length;i 0 && source.optimization == 'ix' && source.onleftfn && source.onrightfn) { - // If there is no table.indices - create it - if(source.databaseid && alasql.databases[source.databaseid].tables[source.tableid]) { - if(!alasql.databases[source.databaseid].tables[source.tableid].indices) query.database.tables[source.tableid].indices = {}; - // Check if index already exists - var ixx = alasql.databases[source.databaseid].tables[source.tableid].indices[hash(source.onrightfns+'`'+source.srcwherefns)]; - if( !alasql.databases[source.databaseid].tables[source.tableid].dirty && ixx) { - source.ix = ixx; - } - }; - if(!source.ix) { - source.ix = {}; - // Walking over source data - var scope = {}; - var i = 0; - var ilen = source.data.length; - var dataw; -// while(source.getfn i=query.sources.length) { -//console.log(query.wherefns); - // Then apply where and select -// console.log(query); - if(query.wherefn(scope,query.params, alasql)) { - -// console.log("scope",scope.schools); - -// var res = query.selectfn(scope, query.params, alasql); -// console.log("last",res); - // If there is a GROUP BY then pipe to groupping function - if(query.groupfn) { - query.groupfn(scope, query.params, query.alasql) - } else { - query.data.push(query.selectfn(scope, query.params, alasql)); - } - } - } else if(query.sources[h].applyselect) { -// console.log('APPLY',scope); -// console.log('scope1',scope); -// console.log(scope); - var source = query.sources[h]; - source.applyselect(query.params, function(data){ - if(data.length > 0) { - // console.log('APPLY CB'); - for(var i=0;i0) { - s += NL()+ID()+K('GROUP BY')+' '+this.group.map(function(grp){ - return grp.toString(); - }).join(', '); - }; - if(this.having) s += NL()+ID()+K('HAVING')+' '+this.having.toString(); - - if(this.order && this.order.length>0) { - s += NL()+ID()+K('ORDER BY')+' '+this.order.map(function(ord){ - return ord.toString(); - }).join(', '); - }; - if(this.limit) s += NL()+ID()+K('LIMIT')+' '+this.limit.value; - if(this.offset) s += NL()+ID()+K('OFFSET')+' '+this.offset.value; - if(this.union) s += NL()+K('UNION')+NL()+this.union.toString(); - if(this.unionall) s += NL()+K('UNION ALL')+NL()+this.unionall.toString(); - if(this.except) s += NL()+K('EXCEPT')+NL()+this.except.toString(); - if(this.intersect) s += NL()+K('INTERSECT')+NL()+this.intersect.toString(); - return s; -}; - -/** - Select statement in expression - */ -yy.Select.prototype.toJavaScript = function(context, tableid, defcols) { -// console.log('Expression',this); -// if(this.expression.reduced) return 'true'; -// return this.expression.toJavaScript(context, tableid, defcols); -// console.log('Select.toJS', 81, this.queriesidx); -// var s = 'this.queriesdata['+(this.queriesidx-1)+'][0]'; -//console.log(this); - var s = 'alasql.utils.flatArray(this.queriesfn['+(this.queriesidx-1)+'](this.params,null,'+context+'))[0]'; -// s = '(console.log(this.queriesfn[0]),'+s+')'; - - return s; -}; - - -// Compile SELECT statement -yy.Select.prototype.compile = function(databaseid) { - var db = alasql.databases[databaseid]; - // Create variable for query - var query = new Query(); - - query.removeKeys = []; - - 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); - // 3. Compile SELECT clause - - this.compileSelectGroup0(query); - - if(this.group || query.selectGroup.length>0) { - query.selectgfns = this.compileSelectGroup1(query); - } else { - query.selectfns = this.compileSelect1(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); - - 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; - - // 8. Compile ORDER BY clause - if(this.order) query.orderfn = this.compileOrder(query); - -// TOP - 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 - 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 -// console.log(this.into); - if(this.into) { - if(this.into instanceof yy.Table) { - if(alasql.options.autocommit && alasql.databases[this.into.databaseid||databaseid].engineid) { - 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 { - query.intofns = - 'alasql.databases[\''+(this.into.databaseid||databaseid)+'\'].tables'+ - '[\''+this.into.tableid+'\'].data.push(r);'; - } - } else if(this.into instanceof yy.VarValue) { - query.intoallfns = 'alasql.vars["'+this.into.variable+'"]=this.data;res=1;if(cb)res=cb(res);return res;'; - } else if (this.into instanceof yy.FuncValue) { - -/* - query.intofns = 'alasql.into[\''+this.into.funcid+'\']('; - var ss = ['r','i']; - if(this.into.args && this.into.args.length>0 ) - this.into.args.forEach(function(arg){ - ss.push(arg.toJavaScript()); - }); - query.intofns += ss.join(',')+')'; -*/ - var qs = 'alasql.into[\''+this.into.funcid.toUpperCase()+'\']('; - if(this.into.args && this.into.args.length>0 ) { - qs += this.into.args[0].toJavaScript()+','; - if(this.into.args.length > 1) { - qs += this.into.args[1].toJavaScript()+','; - } else { - qs += 'null,'; - } - } else { - qs += 'null, null,' - } - query.intoallfns = qs+'this.data,columns,cb)'; -//console.log('999'); - - - - - } else if (this.into instanceof yy.ParamValue) { -// console.log(184); -// query.intofns = 'params[\''+this.into.param+"\'](r)"; - query.intofns = "params['"+this.into.param+"'].push(r)"; - - }; -// console.log(query.intofns); - if(query.intofns) { - query.intofn = new Function("r,i,params,alasql",query.intofns); - }; - - if(query.intoallfns) { -// console.log(query.intoallfns); - query.intoallfn = new Function("columns,cb,alasql",query.intoallfns); - } - - } -//console.log(query); - - // Now, compile all togeather into one function with query object in scope - var statement = function(params, cb, oldscope) { - query.params = params; - var res1 = queryfn(query,oldscope,function(res){ - -//console.log(res[0].schoolid); -//console.log(184,res); - var res2 = modify(query, res); - - - if(cb) cb(res2); -//console.log(8888,res2); - return res2; - - }); -//console.log(9999,res1); - -// if(typeof res1 != 'undefined') res1 = modify(query,res1); - - return res1; - - }; - -// statement.dbversion = ; -// console.log(statement.query); -//console.log(202,statement); - statement.query = query; - return statement; -}; - -function modify(query, res) { - if(query.modifier == 'VALUE') { -// console.log(222,res); - if(res.length > 0) { - var key; - if(query.columns && query.columns.length > 0) key = query.columns[0].columnid; - else key = Object.keys(res[0])[0]; - res = res[0][key]; - } else { - res = undefined; - } - } if(query.modifier == 'ROW') { - if(res.length > 0) { - var key; - if(query.columns && query.columns.length > 0) key = query.columns[0].columnid; - else key = Object.keys(res[0])[0]; - var a = []; - for(var key in res[0]) { - a.push(res[0][key]); - }; - res = a; - } else { - res = undefined; - } - } if(query.modifier == 'COLUMN') { - var ar = []; - if(res.length > 0) { - var key; - if(query.columns && query.columns.length > 0) key = query.columns[0].columnid; - else key = Object.keys(res[0])[0]; - for(var i=0, ilen=res.length; i 0) { - key = query.columns[0].columnid; - val = query.columns[1].columnid; - } else { - var okeys = Object.keys(res[0]); - key = okeys[0]; - val = okeys[1]; - } - for(var i=0, ilen=res.length; i 0) key = query.columns[0].columnid; - else key = Object.keys(res[0])[0]; - var s = ''; - for(var i=0, ilen=res.length; i0) { - // s += tq.args.map(function(arg){ - // return arg.toJavaScript(); - // }).concat('cb,idx,query').join(','); - // } - // if(tq.args && tq.args.length>0) { - // s += tq.args.map(function(arg){ - // return arg.toJavaScript(); - // }).concat().join(','); - // } - if(tq.args && tq.args.length>0) { - if(tq.args[0]) { - s += tq.args[0].toJavaScript('query.oldscope')+','; - } else { - s += 'null,'; - }; - if(tq.args[1]) { - s += tq.args[1].toJavaScript('query.oldscope')+','; - } else { - s += 'null,'; - }; - } else { - s += 'null,null,' - } - s += 'cb,idx,query'; - s += ');/*if(cb)res=cb(res,idx,query);*/return res'; -// console.log(s); - source.datafn = new Function('query, params, cb, idx, alasql',s); - - } else if(tq instanceof yy.FromData) { - source.datafn = function(query,params,cb,idx, alasql) { - var res = tq.data; - if(cb) res = cb(res,idx,query); - return res; - } - } else { - throw new Error('Wrong table at FROM'); - } -// source.data = alasql.databases[source.databaseid].tables[source.tableid].data; - query.sources.push(source); - - }); - // TODO Add joins - query.defaultTableid = query.sources[0].alias; -//console.log(query.defaultTableid); -}; - -alasql.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; i0) { - // s += tq.args.map(function(arg){ - // return arg.toJavaScript(); - // }).concat('cb,idx,query').join(','); - // } - // if(tq.args && tq.args.length>0) { - // s += tq.args.map(function(arg){ - // return arg.toJavaScript(); - // }).concat().join(','); - // } - if(jn.args && jn.args.length>0) { - if(jn.args[0]) { - s += jn.args[0].toJavaScript('query.oldscope')+','; - } else { - s += 'null,'; - }; - if(jn.args[1]) { - s += jn.args[1].toJavaScript('query.oldscope')+','; - } else { - s += 'null,'; - }; - } else { - s += 'null,null,' - } - s += 'cb,idx,query'; - s += ');/*if(cb)res=cb(res,idx,query);*/return res'; -// console.log(s); - source.datafn = new Function('query, params, cb, idx, alasql',s); - - query.aliases[source.alias] = {type:'funcvalue'}; - } -/* - } else if(tq instanceof yy.Select) { - query.aliases[alias] = {type:'subquery'}; - } else if(tq instanceof yy.ParamValue) { - query.aliases[alias] = {type:'paramvalue'}; - } else if(tq instanceof yy.FuncValue) { - query.aliases[alias] = {type:'paramvalue'}; - } else { - throw new Error('Wrong table at FROM'); - } -*/ - var alias = source.alias; - - // Test NATURAL-JOIN - if(jn.natural) { - if(jn.using || jn.on) { - throw new Error('NATURAL JOIN cannot have USING or ON clauses'); - } else { -// source.joinmode == "INNER"; - if(query.sources.length > 0) { - var prevSource = query.sources[query.sources.length-1]; - var prevTable = alasql.databases[prevSource.databaseid].tables[prevSource.tableid]; - var table = alasql.databases[source.databaseid].tables[source.tableid]; - - if(prevTable && table) { - var c1 = prevTable.columns.map(function(col){return col.columnid}); - var c2 = table.columns.map(function(col){return col.columnid}); - jn.using = arrayIntersect(c1,c2).map(function(colid){return {columnid:colid}}); -// console.log(jn.using); - } else { - throw new Error('In this version of Alasql NATURAL JOIN '+ - 'works for tables with predefined columns only'); - }; - } - } - } - - - - - - - - if(jn.using) { - var prevSource = query.sources[query.sources.length-1]; -// console.log(query.sources[0],prevSource,source); - source.onleftfns = jn.using.map(function(col){ -// console.log(141,colid); - return "p['"+(prevSource.alias||prevSource.tableid)+"']['"+col.columnid+"']"; - }).join('+"`"+'); - - - - source.onleftfn = new Function('p,params,alasql','return '+source.onleftfns); - - source.onrightfns = jn.using.map(function(col){ - return "p['"+(source.alias||source.tableid)+"']['"+col.columnid+"']"; - }).join('+"`"+'); - source.onrightfn = new Function('p,params,alasql','return '+source.onrightfns); - source.optimization = 'ix'; -// console.log(151,source.onleftfns, source.onrightfns); -// console.log(source); - } else if(jn.on) { -//console.log(jn.on); - if(jn.on instanceof yy.Op && jn.on.op == '=' && !jn.on.allsome) { -// console.log('ix optimization', jn.on.toJavaScript('p',query.defaultTableid) ); - source.optimization = 'ix'; - // source.onleftfns = jn.on.left.toJavaScript('p',query.defaultTableid); - // source.onleftfn = new Function('p', 'return '+source.onleftfns); - // source.onrightfns = jn.on.right.toJavaScript('p',query.defaultTableid); - // source.onrightfn = new Function('p', 'return '+source.onrightfns); - - var lefts = ''; - var rights = ''; - var middles = ''; - var middlef = false; - // Test right and left sides - var ls = jn.on.left.toJavaScript('p',query.defaultTableid,query.defcols); - var rs = jn.on.right.toJavaScript('p',query.defaultTableid,query.defcols); - - if((ls.indexOf("p['"+alias+"']")>-1) && !(rs.indexOf("p['"+alias+"']")>-1)){ - if((ls.match(/p\[\'.*?\'\]/g)||[]).every(function(s){ - return s == "p['"+alias+"']"})) { rights = ls; } - else { middlef = true }; - - } else if(!(ls.indexOf("p['"+alias+"']")>-1) && (rs.indexOf("p['"+alias+"']")>-1)){ - if((rs.match(/p\[\'.*?\'\]/g)||[]).every(function(s){ - return s == "p['"+alias+"']"})) { lefts = ls; } - else { middlef = true }; - } else { - middlef = true; - } - -// console.log(alias, 1,lefts, rights, middlef); - - if((rs.indexOf("p['"+alias+"']")>-1) && !(ls.indexOf("p['"+alias+"']")>-1)){ - if((rs.match(/p\[\'.*?\'\]/g)||[]).every(function(s){ - return s == "p['"+alias+"']"})) { rights = rs; } - else { middlef = true }; - } else if(!(rs.indexOf("p['"+alias+"']")>-1) && (ls.indexOf("p['"+alias+"']")>-1)){ - if((ls.match(/p\[\'.*?\'\]/g)||[]).every(function(s){ - return s == "p['"+alias+"']"})) { lefts = rs; } - else { middlef = true }; - } else { - middlef = true; - } - -// console.log(alias, 2,lefts, rights, middlef); - - if(middlef) { -// middles = jn.on.toJavaScript('p',query.defaultTableid); -// } else { - rights = ''; - lefts = ''; - middles = jn.on.toJavaScript('p',query.defaultTableid,query.defcols); - source.optimization = 'no'; - // What to here? - } - - source.onleftfns = lefts; - source.onrightfns = rights; - source.onmiddlefns = middles || 'true'; -// console.log(source.onleftfns, '-',source.onrightfns, '-',source.onmiddlefns); - - source.onleftfn = new Function('p,params,alasql', 'return '+source.onleftfns); - source.onrightfn = new Function('p,params,alasql', 'return '+source.onrightfns); - source.onmiddlefn = new Function('p,params,alasql', 'return '+source.onmiddlefns); - -// } else if(jn.on instanceof yy.Op && jn.on.op == 'AND') { -// console.log('join on and ',jn); - - } else { -// console.log('no optimization'); - source.optimization = 'no'; -// source.onleftfn = returnTrue; -// source.onleftfns = "true"; - source.onmiddlefns = jn.on.toJavaScript('p',query.defaultTableid,query.defcols); - source.onmiddlefn = new Function('p,params,alasql','return '+jn.on.toJavaScript('p',query.defaultTableid,query.defcols)); - }; -// console.log(source.onleftfns, source.onrightfns, source.onmiddlefns); - - // Optimization function - }; - -// source.data = alasql.databases[source.databaseid].tables[source.tableid].data; -//console.log(source, jn); - // TODO SubQueries -/* if(source.joinmode == 'RIGHT') { - var prevSource = query.sources.pop(); - if(prevSource.joinmode == 'INNER') { - prevSource.joinmode = 'LEFT'; - var onleftfn = prevSource.onleftfn; - var onleftfns = prevSource.onleftfns; - var onrightfn = prevSource.onrightfn; - var onrightfns = prevSource.onrightfns; - var optimization = prevSource.optimization; - - prevSource.onleftfn = source.onrightfn; - prevSource.onleftfns = source.onrightfns; - prevSource.onrightfn = source.onleftfn; - prevSource.onrightfns = source.onleftfns; - prevSource.optimization = source.optimization; - - source.onleftfn = onleftfn; - source.onleftfns = onleftfns; - source.onrightfn = onrightfn; - source.onrightfns = onrightfns; - source.optimization = optimization; - - source.joinmode = 'INNER'; - query.sources.push(source); - query.sources.push(prevSource); - } else { - throw new Error('Do not know how to process this SQL'); - } - } else { - query.sources.push(source); - } -*/ - query.sources.push(source); - }; - }); -// console.log('sources',query.sources); -} - +/* +// +// Database class for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ -yy.Select.prototype.compileWhere = function(query) { - if(this.where) { - if(typeof this.where == "function") { - return this.where; - } else { - s = this.where.toJavaScript('p',query.defaultTableid,query.defcols); - query.wherefns = s; -// console.log(s); - return new Function('p,params,alasql','return '+s); - } - } else return function(){return true}; -}; +// Initial parameters +/** + Jison parser + */ +alasql.parser = parser; +/** + Jison parser + @param {string} sql SQL statement + @return {object} AST (Abstract Syntax Tree) + */ +alasql.parse = function(sql) { + return parser.parse(alasql.utils.uncomment(sql)); +}; // Shortcut +// Database Engines +/** + List of engines of external databases + */ +alasql.engines = {}; -yy.Select.prototype.compileWhereJoins = function(query) { - return; +// Databases +/** + List of databases + */ +alasql.databases = {}; - // TODO Fix Where optimization - //console.log(query); +/** Number of databases */ +alasql.databasenum = 0; // Current database - optimizeWhereJoin(query, this.where.expression); +// Deafult options +/** + Alasql options object + */ +alasql.options = {}; +alasql.options.errorlog = false; // Log or throw error +alasql.options.valueof = false; // Use valueof in orderfn +alasql.options.dropifnotexists = false; // DROP database in any case +alasql.options.datetimeformat = 'sql'; // How to handle DATE and DATETIME types + // Another value is 'javascript' +alasql.options.casesensitive = true; // Table and column names are case sensitive and converted to lower-case +alasql.options.logtarget = 'output'; // target for log. Values: 'console', 'output', 'id' of html tag +alasql.options.logprompt = true; // Print SQL at log - //for sources compile wherefs - query.sources.forEach(function(source) { - if(source.srcwherefns) { - source.srcwherefn = new Function('p,params,alasql','return '+source.srcwherefns); - }; - if(source.wxleftfns) { - source.wxleftfn = new Function('p,params,alasql','return '+source.wxleftfns); - }; - if(source.wxrightfns) { - source.wxrightfn = new Function('p,params,alasql','return '+source.wxrightfns); - }; -// console.log(source.alias, source.wherefns) -// console.log(source); - }); -}; +//alasql.options.worker = false; +// Variables +alasql.vars = {}; +alasql.declares = {}; -function optimizeWhereJoin (query, ast) { - if(!ast) return false; - if(!(ast instanceof yy.Op)) return; - if(ast.op != '=' && ast.op != 'AND') return; - if(ast.allsome) return; +// AUTOCOMMIT ON | OFF +alasql.options.autocommit = true; - var s = ast.toJavaScript('p',query.defaultTableid,query.defcols); - var fsrc = []; - query.sources.forEach(function(source,idx) { - // Optimization allowed only for tables only - if(source.tableid) { - // This is a good place to remove all unnecessary optimizations - if(s.indexOf('p[\''+source.alias+'\']')>-1) fsrc.push(source); - }; - }); -//console.log(fsrc.length); -// if(fsrc.length < query.sources.length) return; -// console.log(ast); -// console.log(s); -// console.log(fsrc.length); - if(fsrc.length == 0) { -// console.log('no optimization, can remove this part of ast'); - return; - } else if (fsrc.length == 1) { +alasql.options.cache = true; - if(!(s.match(/p\[\'.*?\'\]/g)||[]) - .every(function(s){ - return s == "p['"+fsrc[0].alias+"']"})) { - return; - // This is means, that we have column from parent query - // So we return without optimization - } +alasql.prompthistory = []; - var src = fsrc[0]; // optmiization source - src.srcwherefns = src.srcwherefns ? src.srcwherefns+'&&'+s : s; +alasql.from = {}; // FROM functions +alasql.into = {}; // INTO functions - if((ast instanceof yy.Op) && (ast.op == '=' && !ast.allsome)) { - if(ast.left instanceof yy.Column) { - var ls = ast.left.toJavaScript('p',query.defaultTableid,query.defcols); - var rs = ast.right.toJavaScript('p',query.defaultTableid,query.defcols); - if(rs.indexOf('p[\''+fsrc[0].alias+'\']') == -1) { - fsrc[0].wxleftfns = ls; - fsrc[0].wxrightfns = rs; - } - } if(ast.right instanceof yy.Column) { - var ls = ast.left.toJavaScript('p',query.defaultTableid,query.defcols); - var rs = ast.right.toJavaScript('p',query.defaultTableid,query.defcols); - if(ls.indexOf('p[\''+fsrc[0].alias+'\']') == -1) { - fsrc[0].wxleftfns = rs; - fsrc[0].wxrightfns = ls; - } +alasql.fn = {}; +alasql.aggr = {}; + +alasql.busy = 0; + +// Cache +alasql.MAXSQLCACHESIZE = 10000; +alasql.DEFAULTDATABASEID = 'alasql'; + +/* WebWorker */ +alasql.lastid = 0; +alasql.buffer = {}; + +/** + Select current database + @param {string} databaseid Selected database identificator + */ +alasql.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(); +}; + +// Run one statement +/** + Run SQL statement on current database + */ +alasql.exec = function (sql, params, cb, scope) { + delete alasql.error; + 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); + } +} + +/** + Run SQL statement on specific database + */ +alasql.dexec = function (databaseid, sql, params, cb, scope) { + var db = alasql.databases[databaseid]; +// if(db.databaseid != databaseid) console.trace('got!'); +// console.log(3,db.databaseid,databaseid); + + // Create hash + if(alasql.options.cache) { + var 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(ast.statements.length == 0) return 0; + else if(ast.statements.length == 1) { + if(ast.statements[0].compile) { + +// Compile and Execute + var statement = ast.statements[0].compile(databaseid); + 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 { +// console.log(ast.statements[0]); + alasql.precompile(ast.statements[0],alasql.useid,params); + var res = alasql.res = ast.statements[0].execute(databaseid, params, cb, scope); + return res; } - ast.reduced = true; // To do not duplicate wherefn and srcwherefn - return; } else { - if(ast.op = 'AND') { - optimizeWhereJoin(query,ast.left); - optimizeWhereJoin(query,ast.right); - } + // 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) { + var useid = alasql.useid; + if(useid != databaseid) alasql.use(databaseid); + var res = []; + for (var i=0, ilen=ast.statements.length; i 0) tmpid = query.sources[0].alias; -// console.log(new yy.Column({columnid:colid}).toJavaScript('p',query.sources[0].alias)); -// query.selectfns += 'r[\''+colid+'\']=p[\''+tmpid+'\'][\''+colid+'\'];'; -//console.log(374, colid); - if(Object.keys(query.selectColumns).length != 0) query.removeKeys.push(colid); - query.selectfns += 'r[\''+escapeq(colid)+'\']='+(new yy.Column({columnid:colid}).toJavaScript('p',tmpid))+';'; - } - }); -}; - - // Create negative array - - var s = ''; -// s+= query.selectfns; - - allgroup.forEach(function(agroup) { -//console.log(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 -// else return "r['"+columnid+"']"; - else return coljs; - }); - if(rg.length == 0) rg = ["''"]; - - // console.log('rg',rg); - - s += rg.join('+"`"+'); - s += '];if(!g) {this.groups.push((g=this.xgroups['; - s += rg.join('+"`"+'); - s += '] = {'; -// s += ']=r'; - s += agroup.map(function(col2){ - var columnid = col2.split('\t')[0]; - var coljs = col2.split('\t')[1]; - - if(columnid == '') return ''; - else return "'"+columnid+"':"+coljs+","; - }).join(''); - - var neggroup = arrayDiff(allgroups,agroup); - -// console.log(neggroup); - - s += neggroup.map(function(col2){ - var columnid = col2.split('\t')[0]; - var coljs = col2.split('\t')[1] - return "'"+columnid+"':null,"; - }).join(''); - - var aft = ''; -// s += self.columns.map(function(col){ -//console.log('query.selectGroup',query.selectGroup); - s += query.selectGroup.map(function(col,idx){ -//console.log(idx, col.toString(), col.as); - var colexp = col.expression.toJavaScript("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' - || col.aggregatorid == 'MIN' - || col.aggregatorid == 'MAX' - || col.aggregatorid == 'FIRST' - || col.aggregatorid == 'LAST' -// || col.aggregatorid == 'AVG' -// ) { return '\''+col.as+'\':r[\''+col.as+'\'],'; }//f.field.arguments[0].toJavaScript(); - ) { return '\''+colas+'\':'+colexp+','; }//f.field.arguments[0].toJavaScript(); - 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 { - return '\''+colas+'\':(typeof '+colexp+' != "undefined")?1:0,'; - } - -// else if(col.aggregatorid == 'MIN') { return '\''+col.as+'\':r[\''+col.as+'\'],'; } -// else if(col.aggregatorid == 'MAX') { return '\''+col.as+'\':r[\''+col.as+'\'],'; } - } else if(col.aggregatorid == 'AVG') { - query.removeKeys.push('_SUM_'+colas); - query.removeKeys.push('_COUNT_'+colas); - return '\''+colas+'\':'+colexp+',\'_SUM_'+colas+'\':'+colexp+',\'_COUNT_'+colas+'\':1,'; - } else if(col.aggregatorid == 'AGGR') { - aft += ',g[\''+colas+'\']='+col.expression.toJavaScript('g',-1); - return ''; - } else if(col.aggregatorid == 'REDUCE') { - return '\''+colas+'\':alasql.aggr[\''+col.funcid+'\']('+colexp+'),'; - } - return ''; - } else return ''; - }).join(''); - - - - - - // columnid:r.columnid - // var srg = [];//rg.map(function(fn){ return (fn+':'+fn); }); - - // var srg = this.group.map(function(col){ - // if(col == '') return ''; - // else return col.columnid+':'+col.toJavaScript('r',''); - // }); - - // Initializw aggregators - - /* - this.columns.forEach(function(col){ - // console.log(f); - // if(f.constructor.name == 'LiteralValue') return ''; - - - if (col instanceof yy.AggrValue) { - if (col.aggregatorid == 'SUM') { srg.push("'"+col.as+'\':0'); }//f.field.arguments[0].toJavaScript(); - else if(col.aggregatorid == 'COUNT') {srg.push( "'"+col.as+'\':0'); } - else if(col.aggregatorid == 'MIN') { srg.push( "'"+col.as+'\':Infinity'); } - else if(col.aggregatorid == 'MAX') { srg.push( "'"+col.as+'\':-Infinity'); } - // else if(col.aggregatorid == 'AVG') { srg.push(col.as+':0'); } - // return 'group.'+f.name.value+'=+(+group.'+f.name.value+'||0)+'+f.field.arguments[0].toJavaScript('rec','')+';'; //f.field.arguments[0].toJavaScript(); - }; - - }); - - */ - - /*****************/ - - // s += srg.join(','); - - // var ss = []; - // gff.forEach(function(fn){ - // ss.push(fn+':rec.'+fn); - // }); - // s += ss.join(','); - // s += '});};'; - - s += '}'+aft+',g));} else {'; - // console.log(s, this.columns); - - - - // var neggroup = arrayDiff(allgroups,agroup); - - // console.log(agroup,neggroup); - - // s += neggroup.map(function(columnid){ - // return "g['"+columnid+"']=null;"; - // }).join(''); - - // console.log(s); - - - //console.log(query.selectfn); -// s += self.columns.map(function(col){ - s += query.selectGroup.map(function(col,idx){ - var colas = col.nick; - // if(typeof colas == 'undefined') { - // if(col instanceof yy.Column) colas = col.columnid; - // else colas = col.toString(); - // } - var colexp = col.expression.toJavaScript("p",tableid,defcols); - - if (col instanceof yy.AggrValue) { - if(col.distinct) { - var pre = 'if(typeof '+colexp+'!="undefined" && (!g[\'$$_VALUES_'+colas+'\']['+colexp+'])) \ - {'; - var post = 'g[\'$$_VALUES_'+colas+'\']['+colexp+']=true;}'; - } else { - var pre = '', post = ''; - } - if (col.aggregatorid == 'SUM') { return pre+'g[\''+colas+'\']+='+colexp+';'+post; }//f.field.arguments[0].toJavaScript(); - else if(col.aggregatorid == 'COUNT') { -// console.log(221,col.expression.columnid == '*'); - if(col.expression.columnid == '*') return pre+'g[\''+colas+'\']++;'+post; - else { - return pre+'if(typeof '+colexp+'!="undefined") g[\''+colas+'\']++;'+post; - } - } - else if(col.aggregatorid == 'ARRAY') { return pre+'g[\''+colas+'\'].push('+colexp+');'+post; } - else if(col.aggregatorid == 'MIN') { return pre+'g[\''+colas+'\']=Math.min(g[\''+colas+'\'],'+colexp+');'+post; } - else if(col.aggregatorid == 'MAX') { return pre+'g[\''+colas+'\']=Math.max(g[\''+colas+'\'],'+colexp+');'+post; } - else if(col.aggregatorid == 'FIRST') { return ''; } - else if(col.aggregatorid == 'LAST') { return pre+'g[\''+colas+'\']='+colexp+';'+post; } - else if(col.aggregatorid == 'AVG') { - return pre+'g[\'_SUM_'+colas+'\']+='+colexp+';' - + 'g[\'_COUNT_'+colas+'\']++;' - + 'g[\''+colas+'\']=g[\'_SUM_'+colas+'\']/g[\'_COUNT_'+colas+'\'];'+post; -// } - // else if(col.aggregatorid == 'AVG') { srg.push(colas+':0'); } - } else if(col.aggregatorid == 'AGGR') { - return pre+'g[\''+colas+'\']='+col.expression.toJavaScript('g',-1)+';'+post; - } else if(col.aggregatorid == 'REDUCE') { - return pre+'g[\''+colas+'\']=alasql.aggr.'+col.funcid+'('+colexp+',g[\''+colas+'\']);'+post; - } - return ''; - } else return ''; - }).join(''); - - - // s += selectFields.map(function(f){ - // console.log(f); - // if(f.constructor.name == 'LiteralValue') return ''; - // if (f.field instanceof SQLParser.nodes.FunctionValue - // && (f.field.name.toUpperCase() == 'SUM' || f.field.name.toUpperCase() == 'COUNT')) { - // return 'group.'+f.name.value+'=+(+group.'+f.name.value+'||0)+'+f.field.arguments[0].toJavaScript('rec','')+';'; //f.field.arguments[0].toJavaScript(); - // return 'group.'+f.name.value+'+='+f.field.arguments[0].toJavaScript('rec','')+';'; //f.field.arguments[0].toJavaScript(); - // return 'group.'+f.name.value+'+=rec.'+f.name.value+';'; //f.field.arguments[0].toJavaScript(); - // }; - // return ''; - // }).join(''); - - //s += ' group.amt += rec.emplid;'; - //s += 'group.count++;'; - s += '}'; - - }); - -// console.log('groupfn',s); - return new Function('p,params,alasql',s); - -} - - -/* -// -// Select compiler part for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -// yy.Select.prototype.compileSources = function(query) { -// return sources; -// }; - -function compileSelectStar (query,alias) { - // console.log(query.aliases[alias]); -// console.log(query,alias); - // console.log(query.aliases[alias].tableid); -// console.log(42,631,alias); -// console.log(query.aliases); - var s = '', sp = '', ss=[]; -// if(!alias) { -// sp += 'for(var k1 in p) var w=p[k1];for(var k2 in w){r[k2]=w[k2]};'; -// } else { - if(query.aliases[alias].tableid) { - var columns = alasql.databases[query.aliases[alias].databaseid].tables[query.aliases[alias].tableid].columns; - }; - // Check if this is a Table or other - - if(columns && columns.length > 0) { - columns.forEach(function(tcol){ - ss.push('\''+tcol.columnid+'\':p[\''+alias+'\'][\''+tcol.columnid+'\']'); - query.selectColumns[escapeq(tcol.columnid)] = true; - - // console.log('ok',s); - - var coldef = { - columnid:tcol.columnid, - dbtypeid:tcol.dbtypeid, - dbsize:tcol.dbsize, - dbprecision:tcol.dbprecision, - dbenum: tcol.dbenum - }; - query.columns.push(coldef); - query.xcolumns[coldef.columnid]=coldef; - - }); -//console.log(999,columns); - } else { - // if column not exists, then copy all - sp += 'var w=p["'+alias+'"];for(var k in w){r[k]=w[k]};'; -//console.log(777, sp); - query.dirtyColumns = true; - } -// } -//console.log({s:ss.join(','),sp:sp}); - return {s:ss.join(','),sp:sp}; -} - - -yy.Select.prototype.compileSelect1 = function(query) { - 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){ -//console.log(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); - if(ret.s) ss = ss.concat(ret.s); - sp += ret.sp; - - } else { -// console.log('aliases', query.aliases); - for(var alias in query.aliases) { - var ret = compileSelectStar(query, alias); //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; -// console.log(query.sources); - 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 != '_') { - 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]) { -// console.log(query.database,tbid,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; -//console.log(xcolumns, col,123); -// console.log(0); - if(xcolumns && columns.length > 0) { -// console.log(1); - var tcol = xcolumns[col.columnid]; - var coldef = { - columnid:col.as || col.columnid, - dbtypeid:tcol.dbtypeid, - dbsize:tcol.dbsize, - dbpecision:tcol.dbprecision, - dbenum: tcol.dbenum, - }; -// console.log(2); - query.columns.push(coldef); - query.xcolumns[coldef.columnid]=coldef; - } else { - query.dirtyColumns = true; - } - } else { - // This is a subquery? - // throw new Error('There is now such table \''+col.tableid+'\''); - }; - - } - } else if(col instanceof yy.AggrValue) { - if(!self.group) { -// self.group=[new yy.Column({columnid:'q',as:'q' })]; - self.group = ['']; - } - if(!col.as) col.as = escapeq(col.toString()); - if (col.aggregatorid == 'SUM' || col.aggregatorid == 'MAX' || col.aggregatorid == 'MIN' || - col.aggregatorid == 'FIRST' || col.aggregatorid == 'LAST' || - col.aggregatorid == 'AVG' || col.aggregatorid == 'ARRAY' || col.aggregatorid == 'REDUCE' - ) { - ss.push("'"+escapeq(col.as)+'\':'+col.expression.toJavaScript("p",query.defaultTableid,query.defcols)) - } else if (col.aggregatorid == 'COUNT') { - ss.push("'"+escapeq(col.as)+"':1"); - // Nothing - } - query.selectColumns[col.aggregatorid+'('+escapeq(col.expression.toString())+')'] = thtd; - -// else if (col.aggregatorid == 'MAX') { -// ss.push((col.as || col.columnid)+':'+col.toJavaScript("p.",query.defaultTableid)) -// } else if (col.aggregatorid == 'MIN') { -// ss.push((col.as || col.columnid)+':'+col.toJavaScript("p.",query.defaultTableid)) -// } - } else { - ss.push('\''+escapeq(col.as || col.columnid || col.toString())+'\':'+col.toJavaScript("p",query.defaultTableid,query.defcols)); -// ss.push('\''+escapeq(col.toString())+'\':'+col.toJavaScript("p",query.defaultTableid)); - //if(col instanceof yy.Expression) { - query.selectColumns[escapeq(col.as || col.columnid || col.toString())] = true; - } - }); - s += ss.join(',')+'};'+sp; - return s; -//console.log(42,753,query.xcolumns, query.selectColumns); -} -yy.Select.prototype.compileSelect2 = function(query) { - - var s = query.selectfns ; -// console.log(s); - return new Function('p,params,alasql',s+'return r'); -}; - - -yy.Select.prototype.compileSelectGroup0 = function(query) { - var self = this; - self.columns.forEach(function(col,idx){ - if(col instanceof yy.Column && col.columnid == '*') { - } else { - var colas; - // = col.as; - if(col instanceof yy.Column) { - colas = escapeq(col.columnid); - } else { - colas = escapeq(col.toString()); - } - for(var i=0;irb) return 1; - if(ra==rb) return 0; - return -1; - } - }; +alasql.querySingle = function (sql, params, cb) { + var res = this.exec(sql, params)[0]; + if(cb) cb(res); + return res; +}; - var s = ''; - var sk = ''; - this.order.forEach(function(ord,idx){ - // console.log(ord instanceof yy.Expression); - // console.log(ord.toJavaScript('a','')); - // console.log(ord.expression instanceof yy.Column); - - // Date conversion - var dg = ''; -//console.log(ord.expression, ord.expression instanceof yy.NumValue); - if(ord.expression instanceof yy.NumValue) { - ord.expression = self.columns[ord.expression.value-1]; - }; +alasql.queryRow = function (sql, params, cb) { + var res = this.querySingle(sql, params); + var a = []; + for(var key in res) { + a.push(res[key]); + }; + if(cb) cb(a); + return a; +}; - 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') dg = '.valueOf()'; - // TODO Add other types mapping - } else { - if(alasql.options.valueof) dg = '.valueOf()'; // TODO Check - } - // COLLATE NOCASE - if(ord.nocase) dg += '.toUpperCase()'; +alasql.queryValue = function (sql, params, cb) { + var res = this.exec(sql, params)[0]; + var val = res[Object.keys(res)[0]]; + if(cb) cb(val); + return val; + // TODO Refactor to query.columns +}; - s += 'if(a[\''+columnid+"']"+dg+(ord.direction == 'ASC'?'>':'<')+'b[\''+columnid+"']"+dg+')return 1;'; - s += 'if(a[\''+columnid+"']"+dg+'==b[\''+columnid+"']"+dg+'){'; +alasql.queryArrayOfArrays = function (sql, params, cb) { + var res = this.exec(sql, params); + var keys = Object.keys(res[0]); + var klen = keys.length; + var aa = []; + for(var i=0, ilen=res.length;i':'<')+ord.toJavaScript('b','')+dg+')return 1;'; - s += 'if('+ord.toJavaScript('a','')+dg+'=='+ord.toJavaScript('b','')+dg+'){'; - } + if(cb) cb(aa); + return aa; +}; +*/ +/*alasql.queryColumn = function (sql, params, cb) { + var res = this.exec(sql, params); + var keys = Object.keys(res[0]); + var klen = keys.length; + var aa = []; + for(var i=0, ilen=res.length;i':'<')+'b'+dg+')return 1;'; -// s += 'if(a'+dg+'==b'+dg+'){'; + if(cb) cb(aa); + return aa; +}; +*/ +/* +alasql.value = alasql.queryValue; +alasql.single = alasql.querySingle; +alasql.row = alasql.queryRow; +alasql.column = alasql.queryArray; +alasql.array = alasql.queryArray; +alasql.matrix = alasql.queryArrayOfArrays; +*/ + + +/* +// +// Database class for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +// Main Database class +/** + @class Database + */ + +var Database = alasql.Database = function (databaseid) { + var self = this; + if(self === alasql) { + if(databaseid) { +// if(alasql.databases[databaseid]) { + self = alasql.databases[databaseid]; // } else { - // TODO Add date comparision - // s += 'if(a[\''+columnid+"']"+dg+(ord.direction == 'ASC'?'>':'<')+'b[\''+columnid+"']"+dg+')return 1;'; - // s += 'if(a[\''+columnid+"']"+dg+'==b[\''+columnid+"']"+dg+'){'; + alasql.databases[databaseid] = self; // } - sk += '}'; - }); - s += 'return 0;'; - s += sk+'return -1'; - query.orderfns = s; -//console.log(s); - return new Function('a,b',s); + if(!self) { + throw new Error('Database "'+databaseid+'" not found'); + } + } else { + // Create new database (or get alasql?) + self = alasql.databases.alasql; +// self = new Database(databaseid); // to call without new + } + } + if(!databaseid) { + databaseid = "db"+(alasql.databasenum++); // Random name }; + self.databaseid = databaseid; + alasql.databases[databaseid] = self; + self.tables = {}; + self.views = {}; + + self.indices = {}; +// self.fn = {}; + self.resetSqlCache(); + self.dbversion = 0; + return self; }; +/** + Reset SQL statements cache + */ + +Database.prototype.resetSqlCache = function () { + this.sqlCache = {}; // Cache for compiled SQL statements + this.sqlCacheSize = 0; +} + + +// // Main SQL function + +/** + Run SQL statement on database + @param {string} sql SQL statement + @param [object] params Parameters + @param {function} cb callback + */ + +Database.prototype.exec = function(sql, params, cb) { + return alasql.dexec(this.databaseid, sql, params, cb); +}; + +// // Compile +// var statement = this.compile(sql); +// // Run +// if(statement) { +// var data = statement(params, cb); +// return data; +// } +// return; +// }; + +// // Async version of exec + + +// Database.prototype.aexec = function(sql, params) { +// var self = this; +// return new Promise(function(resolve, reject){ +// alasql.dexec(this.databaseid,sql,params,resolve); +// }); +// }; + + +// Aliases like MS SQL +/* +Database.prototype.query = Database.prototype.exec; +Database.prototype.run = Database.prototype.exec; +Database.prototype.queryArray = function(sql, params, cb) { + return flatArray(this.exec(sql, params, cb)); +} + +Database.prototype.queryArrayOfArrays = function(sql, params, cb) { + return arrayOfArrays(this.exec(sql, params, cb)); +} + +Database.prototype.querySingle = function(sql, params, cb) { + return this.exec(sql, params, cb)[0]; +} +Database.prototype.queryValue = function(sql, params, cb) { + var res = this.querySingle(sql, params, cb); + return res[Object.keys(res)[0]]; +} + +Database.prototype.value = Database.prototype.queryValue; +Database.prototype.row = Database.prototype.querySingle; +Database.prototype.array = Database.prototype.queryArray; +Database.prototype.matrix = Database.prototype.queryArrayOfArrays; + + +// Compile statements +Database.prototype.compile = function(sql, kind) { + return alasql.compile(sql, kind, databaseid); +}; + +*/ +// var self = this; +// var hh = hash(sql); + +// // Check cache with hash of SQL statement +// var statement = this.sqlcache[hh]; +// if(!statement) { + +// // If not fount, then compile it +// var ast = alasql.parse(sql); +// // Save to cache + +// statement = this.sqlcache[hh]= ast.compile(self); + +// // Memory leak prevention +// this.sqlcachesize++; +// if(this.sqlcachesize > alasql.MAXSQLCACHESIZE) { +// this.resetSqlCache(); +// } +// }; +// return statement; +// } + +// SQL.js compatibility method +//Database.prototype.prepare = Database.prototype.compile; + + +// Added for compatibility with WebSQL + + + + + +/* +// +// 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 + */ + +var Transaction = alasql.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 +// console.log(this); + return this; +}; + +// Main class + + +// Commit + +/** + Commit transaction + */ +Transaction.prototype.commit = function() { + this.commited = true; + alasql.databases[this.databaseid].dbversion = Date.now(); + delete this.bank; +}; + +// Rollback +/** + Rollback transaction + */ +Transaction.prototype.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'); + } +}; + +// Transactions stub + +/** + Execute SQL statement + @param {string} sql SQL statement + @param {object} params Parameters + @param {function} cb Callback function + @return result + */ +Transaction.prototype.exec = function(sql, params, cb) { +// console.log(this.databaseid); + return alasql.dexec(this.databaseid,sql,params,cb); +}; + +Transaction.prototype.executeSQL = Transaction.prototype.exec; + +/* +Transaction.prototype.query = Database.prototype.exec; +Transaction.prototype.run = Database.prototype.exec; +Transaction.prototype.queryArray = function(sql, params, cb) { + return flatArray(this.exec(sql, params, cb)); +} + +Transaction.prototype.queryArrayOfArrays = function(sql, params, cb) { + return arrayOfArrays(this.exec(sql, params, cb)); +} + +Transaction.prototype.querySingle = function(sql, params, cb) { + return this.exec(sql, params, cb)[0]; +} +Transaction.prototype.queryValue = function(sql, params, cb) { + var res = this.querySingle(sql, params, cb); + return res[Object.keys(res)[0]]; +} +*/ + + +/* +// +// Table class for Alasql.js +// Date: 14.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +// Table class +var Table = alasql.Table = function(params){ + // Columns + this.columns = []; + this.xcolumns = {}; + // Data array + this.data = []; + + this.inddefs = {}; + this.indices = {}; + + this.uniqs = {}; + this.uniqdefs = {}; + + extend(this,params); +}; + + +// View = function(){ +// this.data = []; +// this.columns = []; +// this.ixcolumns = {}; +// this.ixdefs = {}; +// this.indices = {}; +// }; + +// alasql.View = View; + +Table.prototype.indexColumns = function() { + var self = this; + self.xcolumns = {}; + self.columns.forEach(function(col){ + self.xcolumns[col.columnid] = col; + }); +} + + + + +/* +// +// View class for Alasql.js +// Date: 14.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +// Table class +var View = alasql.View = function(params){ + // Columns + this.columns = []; + this.xcolumns = {}; + // Data array + this.query = []; + + extend(this,params); +}; + +// View = function(){ +// this.data = []; +// this.columns = []; +// this.ixcolumns = {}; +// this.ixdefs = {}; +// this.indices = {}; +// }; + +// alasql.View = View; + + + + +/* +// +// Query class for Alasql.js +// Date: 14.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +// Table class + +/** + @class Query Main query class + */ +var Query = alasql.Query = function(params){ + this.alasql = alasql; +// console.log(12,alasql); + // Columns + this.columns = []; + this.xcolumns = {}; + this.selectGroup = []; + this.groupColumns = {}; + // Data array + extend(this,params); +}; + +/** + @class Recordset data object + */ +var Recordset = alasql.Recordset = function(params){ + // Data array + extend(this,params); +}; + + +// View = function(){ +// this.data = []; +// this.columns = []; +// this.ixcolumns = {}; +// this.ixdefs = {}; +// this.indices = {}; +// }; + +// alasql.View = View; + + + + +/* +// +// Parser helper for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +var yy = parser.yy = {}; + +// Utility +yy.extend = extend; +// Option for case sensitive +yy.casesensitive = alasql.options.casesensitive; + +// Base class for all yy classes +var Base = yy.Base = function (params) { return yy.extend(this, params); }; + +Base.prototype.toString = function() {} +Base.prototype.toType = function() {} +Base.prototype.toJavaScript = function() {} + +//var BaseClause = yy,BaseClause = function (params) { return yy.extend(this, params); }; +Base.prototype.compile = returnUndefined; +Base.prototype.exec = function() {} + +//var BaseStatement = yy,BaseStatement = function (params) { return yy.extend(this, params); }; +Base.prototype.compile = returnUndefined; +Base.prototype.exec = function() {} + + + + +/* +// +// Statements class for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +// Statements container +yy.Statements = function(params) { return yy.extend(this, params); }; + +yy.Statements.prototype.toString = function () { + return this.statements.map(function(st){return st.toString()}).join(';'+NL()); +}; + +// Compile array of statements into single statement +yy.Statements.prototype.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; + } + } +}; + + + +// Main query procedure +function queryfn(query,oldscope,cb, A,B) { + var ms; + query.sourceslen = query.sources.length; + var slen = query.sourceslen; + query.query = query; // TODO Remove to prevent memory leaks + query.A = A; + query.B = B; +// console.log(arguments); + query.cb = cb; + query.oldscope = oldscope; + + // Run all subqueries before main statement + if(query.queriesfn) { + query.sourceslen += query.queriesfn.length; + slen += query.queriesfn.length; + + query.queriesdata = []; + +// console.log(8); + query.queriesfn.forEach(function(q,idx){ +// if(query.explain) ms = Date.now(); +//console.log(18,idx); +// var res = flatArray(q(query.params,null,queryfn2,(-idx-1),query)); + +// var res = flatArray(queryfn(q.query,null,queryfn2,(-idx-1),query)); +// console.log(A,B); +// console.log(q); + q.query.params = query.params; +// query.queriesdata[idx] = + + if(false) { + queryfn(q.query,query.oldscope,queryfn2,(-idx-1),query); + } else { + queryfn2([],(-idx-1),query); + } + +// console.log(27,q); + + +// query.explaination.push({explid: query.explid++, description:'Query '+idx,ms:Date.now()-ms}); +// query.queriesdata[idx] = res; +// return res; + }); +// console.log(9,query.queriesdata.length); +// console.log(query.queriesdata[0]); + } + + var scope; + if(!oldscope) scope = {}; + else scope = cloneDeep(oldscope); + query.scope = scope; + + // First - refresh data sources + + var result; + query.sources.forEach(function(source, idx){ +// source.data = query.database.tables[source.tableid].data; +// console.log(666,idx); + source.query = query; + var rs = source.datafn(query, query.params, queryfn2, idx, alasql); +// console.log(333,rs); + if(typeof rs != undefined) { + // TODO - this is a hack: check if result is array - check all cases and + // make it more logical + if((query.intofn || query.intoallfn) && rs instanceof Array) rs = rs.length; + result = rs; + } +// console.log(444,result); +// +// Ugly hack to use in query.wherefn and source.srcwherefns functions +// constructions like this.queriesdata['test']. +// I can elimite it with source.srcwherefn.bind(this)() +// but it may be slow. +// + source.queriesdata = query.queriesdata; + }); + if(slen == 0) result = queryfn3(query); + return result; +}; + +function queryfn2(data,idx,query) { + +//console.log(56,arguments); +// console.log(78,data, idx,query); +//console.trace(); + + if(idx>=0) { + var source = query.sources[idx]; + source.data = data; + if(typeof source.data == 'function') { + source.getfn = source.data; + source.dontcache = source.getfn.dontcache; + + // var prevsource = query.sources[h-1]; + if(source.joinmode == 'OUTER' || source.joinmode == 'RIGHT' || source.joinmode == 'ANTI') { + source.dontcache = false; + } + source.data = {}; + } + } else { + // subqueries +// console.log("queriesdata",data, flatArray(data)); + query.queriesdata[-idx-1] = flatArray(data); +// console.log(98,query.queriesdata); +// console.log(79,query.queriesdata); + } + + query.sourceslen--; + if(query.sourceslen>0) return; + + return queryfn3(query); +}; + +function queryfn3(query) { +//console.log(55,query); + + + var scope = query.scope; + // Preindexation of data sources +// if(!oldscope) { + preIndex(query); +// } + + // query.sources.forEach(function(source) { + // console.log(source.data); + // }); + + // Prepare variables + query.data = []; + query.xgroups = {}; + query.groups = []; + + // Level of Joins + var h = 0; + + // Start walking over data + doJoin(query, scope, h); + +//console.log(85,query.data[0]); + + // If groupping, then filter groups with HAVING function +// console.log(query.havingfns); + if(query.groupfn) { + query.data = []; + if(query.groups.length == 0) { + var g = {}; + if(query.selectGroup.length>0) { +// console.log(query.selectGroup); + query.selectGroup.forEach(function(sg){ + if(sg.aggregatorid == "COUNT" || sg.aggregatorid == "SUM") { + g[sg.nick] = 0; + } else { + g[sg.nick] = undefined; + } + }); + }; + query.groups = [g]; +// console.log(); + }; + // console.log('EMPTY',query.groups); + // debugger; + // if(false && (query.groups.length == 1) && (Object.keys(query.groups[0]).length == 0)) { + // console.log('EMPTY',query.groups); + // } else { + for(var i=0,ilen=query.groups.length;i 0) { + for(var i=0,ilen=query.data.length;i 0 && source.optimization == 'ix' && source.onleftfn && source.onrightfn) { + // If there is no table.indices - create it + if(source.databaseid && alasql.databases[source.databaseid].tables[source.tableid]) { + if(!alasql.databases[source.databaseid].tables[source.tableid].indices) query.database.tables[source.tableid].indices = {}; + // Check if index already exists + var ixx = alasql.databases[source.databaseid].tables[source.tableid].indices[hash(source.onrightfns+'`'+source.srcwherefns)]; + if( !alasql.databases[source.databaseid].tables[source.tableid].dirty && ixx) { + source.ix = ixx; + } + }; + if(!source.ix) { + source.ix = {}; + // Walking over source data + var scope = {}; + var i = 0; + var ilen = source.data.length; + var dataw; +// while(source.getfn i=query.sources.length) { +//console.log(query.wherefns); + // Then apply where and select +// console.log(query); + if(query.wherefn(scope,query.params, alasql)) { + +// console.log("scope",scope.schools); + +// var res = query.selectfn(scope, query.params, alasql); +// console.log("last",res); + // If there is a GROUP BY then pipe to groupping function + if(query.groupfn) { + query.groupfn(scope, query.params, query.alasql) + } else { + query.data.push(query.selectfn(scope, query.params, alasql)); + } + } + } else if(query.sources[h].applyselect) { +// console.log('APPLY',scope); +// console.log('scope1',scope); +// console.log(scope); + var source = query.sources[h]; + source.applyselect(query.params, function(data){ + if(data.length > 0) { + // console.log('APPLY CB'); + for(var i=0;i0) { + s += NL()+ID()+K('GROUP BY')+' '+this.group.map(function(grp){ + return grp.toString(); + }).join(', '); + }; + if(this.having) s += NL()+ID()+K('HAVING')+' '+this.having.toString(); + + if(this.order && this.order.length>0) { + s += NL()+ID()+K('ORDER BY')+' '+this.order.map(function(ord){ + return ord.toString(); + }).join(', '); + }; + if(this.limit) s += NL()+ID()+K('LIMIT')+' '+this.limit.value; + if(this.offset) s += NL()+ID()+K('OFFSET')+' '+this.offset.value; + if(this.union) s += NL()+K('UNION')+NL()+this.union.toString(); + if(this.unionall) s += NL()+K('UNION ALL')+NL()+this.unionall.toString(); + if(this.except) s += NL()+K('EXCEPT')+NL()+this.except.toString(); + if(this.intersect) s += NL()+K('INTERSECT')+NL()+this.intersect.toString(); + return s; +}; + +/** + Select statement in expression + */ +yy.Select.prototype.toJavaScript = function(context, tableid, defcols) { +// console.log('Expression',this); +// if(this.expression.reduced) return 'true'; +// return this.expression.toJavaScript(context, tableid, defcols); +// console.log('Select.toJS', 81, this.queriesidx); +// var s = 'this.queriesdata['+(this.queriesidx-1)+'][0]'; +//console.log(this); + var s = 'alasql.utils.flatArray(this.queriesfn['+(this.queriesidx-1)+'](this.params,null,'+context+'))[0]'; +// s = '(console.log(this.queriesfn[0]),'+s+')'; + + return s; +}; + + +// Compile SELECT statement +yy.Select.prototype.compile = function(databaseid) { + var db = alasql.databases[databaseid]; + // Create variable for query + var query = new Query(); + + query.removeKeys = []; + + 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); + // 3. Compile SELECT clause + + this.compileSelectGroup0(query); + + if(this.group || query.selectGroup.length>0) { + query.selectgfns = this.compileSelectGroup1(query); + } else { + query.selectfns = this.compileSelect1(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); + + 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; + + // 8. Compile ORDER BY clause + if(this.order) query.orderfn = this.compileOrder(query); + +// TOP + 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 + 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 +// console.log(this.into); + if(this.into) { + if(this.into instanceof yy.Table) { + if(alasql.options.autocommit && alasql.databases[this.into.databaseid||databaseid].engineid) { + 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 { + query.intofns = + 'alasql.databases[\''+(this.into.databaseid||databaseid)+'\'].tables'+ + '[\''+this.into.tableid+'\'].data.push(r);'; + } + } else if(this.into instanceof yy.VarValue) { + query.intoallfns = 'alasql.vars["'+this.into.variable+'"]=this.data;res=1;if(cb)res=cb(res);return res;'; + } else if (this.into instanceof yy.FuncValue) { + +/* + query.intofns = 'alasql.into[\''+this.into.funcid+'\']('; + var ss = ['r','i']; + if(this.into.args && this.into.args.length>0 ) + this.into.args.forEach(function(arg){ + ss.push(arg.toJavaScript()); + }); + query.intofns += ss.join(',')+')'; +*/ + var qs = 'alasql.into[\''+this.into.funcid.toUpperCase()+'\']('; + if(this.into.args && this.into.args.length>0 ) { + qs += this.into.args[0].toJavaScript()+','; + if(this.into.args.length > 1) { + qs += this.into.args[1].toJavaScript()+','; + } else { + qs += 'null,'; + } + } else { + qs += 'null, null,' + } + query.intoallfns = qs+'this.data,columns,cb)'; +//console.log('999'); + + + + + } else if (this.into instanceof yy.ParamValue) { +// console.log(184); +// query.intofns = 'params[\''+this.into.param+"\'](r)"; + query.intofns = "params['"+this.into.param+"'].push(r)"; + + }; +// console.log(query.intofns); + if(query.intofns) { + query.intofn = new Function("r,i,params,alasql",query.intofns); + }; + + if(query.intoallfns) { +// console.log(query.intoallfns); + query.intoallfn = new Function("columns,cb,alasql",query.intoallfns); + } + + } +//console.log(query); + + // Now, compile all togeather into one function with query object in scope + var statement = function(params, cb, oldscope) { + query.params = params; + var res1 = queryfn(query,oldscope,function(res){ + +//console.log(res[0].schoolid); +//console.log(184,res); + var res2 = modify(query, res); + + + if(cb) cb(res2); +//console.log(8888,res2); + return res2; + + }); +//console.log(9999,res1); + +// if(typeof res1 != 'undefined') res1 = modify(query,res1); + + return res1; + + }; + +// statement.dbversion = ; +// console.log(statement.query); +//console.log(202,statement); + statement.query = query; + return statement; +}; + +function modify(query, res) { + if(query.modifier == 'VALUE') { +// console.log(222,res); + if(res.length > 0) { + var key; + if(query.columns && query.columns.length > 0) key = query.columns[0].columnid; + else key = Object.keys(res[0])[0]; + res = res[0][key]; + } else { + res = undefined; + } + } if(query.modifier == 'ROW') { + if(res.length > 0) { + var key; + if(query.columns && query.columns.length > 0) key = query.columns[0].columnid; + else key = Object.keys(res[0])[0]; + var a = []; + for(var key in res[0]) { + a.push(res[0][key]); + }; + res = a; + } else { + res = undefined; + } + } if(query.modifier == 'COLUMN') { + var ar = []; + if(res.length > 0) { + var key; + if(query.columns && query.columns.length > 0) key = query.columns[0].columnid; + else key = Object.keys(res[0])[0]; + for(var i=0, ilen=res.length; i 0) { + key = query.columns[0].columnid; + val = query.columns[1].columnid; + } else { + var okeys = Object.keys(res[0]); + key = okeys[0]; + val = okeys[1]; + } + for(var i=0, ilen=res.length; i 0) key = query.columns[0].columnid; + else key = Object.keys(res[0])[0]; + var s = ''; + for(var i=0, ilen=res.length; i0) { + // s += tq.args.map(function(arg){ + // return arg.toJavaScript(); + // }).concat('cb,idx,query').join(','); + // } + // if(tq.args && tq.args.length>0) { + // s += tq.args.map(function(arg){ + // return arg.toJavaScript(); + // }).concat().join(','); + // } + if(tq.args && tq.args.length>0) { + if(tq.args[0]) { + s += tq.args[0].toJavaScript('query.oldscope')+','; + } else { + s += 'null,'; + }; + if(tq.args[1]) { + s += tq.args[1].toJavaScript('query.oldscope')+','; + } else { + s += 'null,'; + }; + } else { + s += 'null,null,' + } + s += 'cb,idx,query'; + s += ');/*if(cb)res=cb(res,idx,query);*/return res'; +// console.log(s); + source.datafn = new Function('query, params, cb, idx, alasql',s); + + } else if(tq instanceof yy.FromData) { + source.datafn = function(query,params,cb,idx, alasql) { + var res = tq.data; + if(cb) res = cb(res,idx,query); + return res; + } + } else { + throw new Error('Wrong table at FROM'); + } +// source.data = alasql.databases[source.databaseid].tables[source.tableid].data; + query.sources.push(source); + + }); + // TODO Add joins + query.defaultTableid = query.sources[0].alias; +//console.log(query.defaultTableid); +}; + +alasql.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; i0) { + // s += tq.args.map(function(arg){ + // return arg.toJavaScript(); + // }).concat('cb,idx,query').join(','); + // } + // if(tq.args && tq.args.length>0) { + // s += tq.args.map(function(arg){ + // return arg.toJavaScript(); + // }).concat().join(','); + // } + if(jn.args && jn.args.length>0) { + if(jn.args[0]) { + s += jn.args[0].toJavaScript('query.oldscope')+','; + } else { + s += 'null,'; + }; + if(jn.args[1]) { + s += jn.args[1].toJavaScript('query.oldscope')+','; + } else { + s += 'null,'; + }; + } else { + s += 'null,null,' + } + s += 'cb,idx,query'; + s += ');/*if(cb)res=cb(res,idx,query);*/return res'; +// console.log(s); + source.datafn = new Function('query, params, cb, idx, alasql',s); + + query.aliases[source.alias] = {type:'funcvalue'}; + } +/* + } else if(tq instanceof yy.Select) { + query.aliases[alias] = {type:'subquery'}; + } else if(tq instanceof yy.ParamValue) { + query.aliases[alias] = {type:'paramvalue'}; + } else if(tq instanceof yy.FuncValue) { + query.aliases[alias] = {type:'paramvalue'}; + } else { + throw new Error('Wrong table at FROM'); + } +*/ + var alias = source.alias; + + // Test NATURAL-JOIN + if(jn.natural) { + if(jn.using || jn.on) { + throw new Error('NATURAL JOIN cannot have USING or ON clauses'); + } else { +// source.joinmode == "INNER"; + if(query.sources.length > 0) { + var prevSource = query.sources[query.sources.length-1]; + var prevTable = alasql.databases[prevSource.databaseid].tables[prevSource.tableid]; + var table = alasql.databases[source.databaseid].tables[source.tableid]; + + if(prevTable && table) { + var c1 = prevTable.columns.map(function(col){return col.columnid}); + var c2 = table.columns.map(function(col){return col.columnid}); + jn.using = arrayIntersect(c1,c2).map(function(colid){return {columnid:colid}}); +// console.log(jn.using); + } else { + throw new Error('In this version of Alasql NATURAL JOIN '+ + 'works for tables with predefined columns only'); + }; + } + } + } + + + + + + + + if(jn.using) { + var prevSource = query.sources[query.sources.length-1]; +// console.log(query.sources[0],prevSource,source); + source.onleftfns = jn.using.map(function(col){ +// console.log(141,colid); + return "p['"+(prevSource.alias||prevSource.tableid)+"']['"+col.columnid+"']"; + }).join('+"`"+'); + + + + source.onleftfn = new Function('p,params,alasql','return '+source.onleftfns); + + source.onrightfns = jn.using.map(function(col){ + return "p['"+(source.alias||source.tableid)+"']['"+col.columnid+"']"; + }).join('+"`"+'); + source.onrightfn = new Function('p,params,alasql','return '+source.onrightfns); + source.optimization = 'ix'; +// console.log(151,source.onleftfns, source.onrightfns); +// console.log(source); + } else if(jn.on) { +//console.log(jn.on); + if(jn.on instanceof yy.Op && jn.on.op == '=' && !jn.on.allsome) { +// console.log('ix optimization', jn.on.toJavaScript('p',query.defaultTableid) ); + source.optimization = 'ix'; + // source.onleftfns = jn.on.left.toJavaScript('p',query.defaultTableid); + // source.onleftfn = new Function('p', 'return '+source.onleftfns); + // source.onrightfns = jn.on.right.toJavaScript('p',query.defaultTableid); + // source.onrightfn = new Function('p', 'return '+source.onrightfns); + + var lefts = ''; + var rights = ''; + var middles = ''; + var middlef = false; + // Test right and left sides + var ls = jn.on.left.toJavaScript('p',query.defaultTableid,query.defcols); + var rs = jn.on.right.toJavaScript('p',query.defaultTableid,query.defcols); + + if((ls.indexOf("p['"+alias+"']")>-1) && !(rs.indexOf("p['"+alias+"']")>-1)){ + if((ls.match(/p\[\'.*?\'\]/g)||[]).every(function(s){ + return s == "p['"+alias+"']"})) { rights = ls; } + else { middlef = true }; + + } else if(!(ls.indexOf("p['"+alias+"']")>-1) && (rs.indexOf("p['"+alias+"']")>-1)){ + if((rs.match(/p\[\'.*?\'\]/g)||[]).every(function(s){ + return s == "p['"+alias+"']"})) { lefts = ls; } + else { middlef = true }; + } else { + middlef = true; + } + +// console.log(alias, 1,lefts, rights, middlef); + + if((rs.indexOf("p['"+alias+"']")>-1) && !(ls.indexOf("p['"+alias+"']")>-1)){ + if((rs.match(/p\[\'.*?\'\]/g)||[]).every(function(s){ + return s == "p['"+alias+"']"})) { rights = rs; } + else { middlef = true }; + } else if(!(rs.indexOf("p['"+alias+"']")>-1) && (ls.indexOf("p['"+alias+"']")>-1)){ + if((ls.match(/p\[\'.*?\'\]/g)||[]).every(function(s){ + return s == "p['"+alias+"']"})) { lefts = rs; } + else { middlef = true }; + } else { + middlef = true; + } + +// console.log(alias, 2,lefts, rights, middlef); + + if(middlef) { +// middles = jn.on.toJavaScript('p',query.defaultTableid); +// } else { + rights = ''; + lefts = ''; + middles = jn.on.toJavaScript('p',query.defaultTableid,query.defcols); + source.optimization = 'no'; + // What to here? + } + + source.onleftfns = lefts; + source.onrightfns = rights; + source.onmiddlefns = middles || 'true'; +// console.log(source.onleftfns, '-',source.onrightfns, '-',source.onmiddlefns); + + source.onleftfn = new Function('p,params,alasql', 'return '+source.onleftfns); + source.onrightfn = new Function('p,params,alasql', 'return '+source.onrightfns); + source.onmiddlefn = new Function('p,params,alasql', 'return '+source.onmiddlefns); + +// } else if(jn.on instanceof yy.Op && jn.on.op == 'AND') { +// console.log('join on and ',jn); + + } else { +// console.log('no optimization'); + source.optimization = 'no'; +// source.onleftfn = returnTrue; +// source.onleftfns = "true"; + source.onmiddlefns = jn.on.toJavaScript('p',query.defaultTableid,query.defcols); + source.onmiddlefn = new Function('p,params,alasql','return '+jn.on.toJavaScript('p',query.defaultTableid,query.defcols)); + }; +// console.log(source.onleftfns, source.onrightfns, source.onmiddlefns); + + // Optimization function + }; + +// source.data = alasql.databases[source.databaseid].tables[source.tableid].data; +//console.log(source, jn); + // TODO SubQueries +/* if(source.joinmode == 'RIGHT') { + var prevSource = query.sources.pop(); + if(prevSource.joinmode == 'INNER') { + prevSource.joinmode = 'LEFT'; + var onleftfn = prevSource.onleftfn; + var onleftfns = prevSource.onleftfns; + var onrightfn = prevSource.onrightfn; + var onrightfns = prevSource.onrightfns; + var optimization = prevSource.optimization; + + prevSource.onleftfn = source.onrightfn; + prevSource.onleftfns = source.onrightfns; + prevSource.onrightfn = source.onleftfn; + prevSource.onrightfns = source.onleftfns; + prevSource.optimization = source.optimization; + + source.onleftfn = onleftfn; + source.onleftfns = onleftfns; + source.onrightfn = onrightfn; + source.onrightfns = onrightfns; + source.optimization = optimization; + + source.joinmode = 'INNER'; + query.sources.push(source); + query.sources.push(prevSource); + } else { + throw new Error('Do not know how to process this SQL'); + } + } else { + query.sources.push(source); + } +*/ + query.sources.push(source); + }; + }); +// console.log('sources',query.sources); +} + + + +yy.Select.prototype.compileWhere = function(query) { + if(this.where) { + if(typeof this.where == "function") { + return this.where; + } else { + s = this.where.toJavaScript('p',query.defaultTableid,query.defcols); + query.wherefns = s; +// console.log(s); + return new Function('p,params,alasql','return '+s); + } + } else return function(){return true}; +}; + + + +yy.Select.prototype.compileWhereJoins = function(query) { + return; + + // TODO Fix Where optimization + //console.log(query); + + optimizeWhereJoin(query, this.where.expression); + + //for sources compile wherefs + query.sources.forEach(function(source) { + if(source.srcwherefns) { + source.srcwherefn = new Function('p,params,alasql','return '+source.srcwherefns); + }; + if(source.wxleftfns) { + source.wxleftfn = new Function('p,params,alasql','return '+source.wxleftfns); + }; + if(source.wxrightfns) { + source.wxrightfn = new Function('p,params,alasql','return '+source.wxrightfns); + }; +// console.log(source.alias, source.wherefns) +// console.log(source); + }); +}; + +function optimizeWhereJoin (query, ast) { + if(!ast) return false; + if(!(ast instanceof yy.Op)) return; + if(ast.op != '=' && ast.op != 'AND') return; + if(ast.allsome) return; + + var s = ast.toJavaScript('p',query.defaultTableid,query.defcols); + var fsrc = []; + query.sources.forEach(function(source,idx) { + // Optimization allowed only for tables only + if(source.tableid) { + // This is a good place to remove all unnecessary optimizations + if(s.indexOf('p[\''+source.alias+'\']')>-1) fsrc.push(source); + }; + }); +//console.log(fsrc.length); +// if(fsrc.length < query.sources.length) return; +// console.log(ast); +// console.log(s); +// console.log(fsrc.length); + if(fsrc.length == 0) { +// console.log('no optimization, can remove this part of ast'); + return; + } else if (fsrc.length == 1) { + + if(!(s.match(/p\[\'.*?\'\]/g)||[]) + .every(function(s){ + return s == "p['"+fsrc[0].alias+"']"})) { + return; + // This is means, that we have column from parent query + // So we return without optimization + } + + var src = fsrc[0]; // optmiization source + src.srcwherefns = src.srcwherefns ? src.srcwherefns+'&&'+s : s; + + if((ast instanceof yy.Op) && (ast.op == '=' && !ast.allsome)) { + if(ast.left instanceof yy.Column) { + var ls = ast.left.toJavaScript('p',query.defaultTableid,query.defcols); + var rs = ast.right.toJavaScript('p',query.defaultTableid,query.defcols); + if(rs.indexOf('p[\''+fsrc[0].alias+'\']') == -1) { + fsrc[0].wxleftfns = ls; + fsrc[0].wxrightfns = rs; + } + } if(ast.right instanceof yy.Column) { + var ls = ast.left.toJavaScript('p',query.defaultTableid,query.defcols); + var rs = ast.right.toJavaScript('p',query.defaultTableid,query.defcols); + if(ls.indexOf('p[\''+fsrc[0].alias+'\']') == -1) { + fsrc[0].wxleftfns = rs; + fsrc[0].wxrightfns = ls; + } + } + } + ast.reduced = true; // To do not duplicate wherefn and srcwherefn + return; + } else { + if(ast.op = 'AND') { + optimizeWhereJoin(query,ast.left); + optimizeWhereJoin(query,ast.right); + } + } + +}; + + + + +/* +// +// Select compiler part for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +/** + Compile group of statements + */ +yy.Select.prototype.compileGroup = function(query) { +// console.log(this.group); + var self = this; + var tableid = query.sources[0].alias; + var defcols = query.defcols; +// console.log(16,tableid, defcols); + +// console.log(query.sources[0].alias,query.defcols); + var allgroup = [[]]; + if(this.group) { + allgroup = decartes(this.group,query); + } +// console.log(23,allgroup); + +// console.log(allgroup); + // 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; + +//console.log(42,294, this.group); +//console.log(allgroups); +// console.log(42,364,query.selectColumns) + +if(false) { + allgroups.forEach(function(col2){ +// console.log(42,365,colid, query.selectColumns[colid]) + if(query.selectColumns[colid]) { +// console.log(colid,'ok'); + } else { +// if(colid.indexOf()) +// console.log(colid,'bad'); + var tmpid = 'default'; + if(query.sources.length > 0) tmpid = query.sources[0].alias; +// console.log(new yy.Column({columnid:colid}).toJavaScript('p',query.sources[0].alias)); +// query.selectfns += 'r[\''+colid+'\']=p[\''+tmpid+'\'][\''+colid+'\'];'; +//console.log(374, colid); + if(Object.keys(query.selectColumns).length != 0) query.removeKeys.push(colid); + query.selectfns += 'r[\''+escapeq(colid)+'\']='+(new yy.Column({columnid:colid}).toJavaScript('p',tmpid))+';'; + } + }); +}; + + // Create negative array + + var s = ''; +// s+= query.selectfns; + + allgroup.forEach(function(agroup) { +//console.log(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 +// else return "r['"+columnid+"']"; + else return coljs; + }); + if(rg.length == 0) rg = ["''"]; + + // console.log('rg',rg); + + s += rg.join('+"`"+'); + s += '];if(!g) {this.groups.push((g=this.xgroups['; + s += rg.join('+"`"+'); + s += '] = {'; +// s += ']=r'; + s += agroup.map(function(col2){ + var columnid = col2.split('\t')[0]; + var coljs = col2.split('\t')[1]; + + if(columnid == '') return ''; + else return "'"+columnid+"':"+coljs+","; + }).join(''); + + var neggroup = arrayDiff(allgroups,agroup); + +// console.log(neggroup); + + s += neggroup.map(function(col2){ + var columnid = col2.split('\t')[0]; + var coljs = col2.split('\t')[1] + return "'"+columnid+"':null,"; + }).join(''); + + var aft = ''; +// s += self.columns.map(function(col){ +//console.log('query.selectGroup',query.selectGroup); + s += query.selectGroup.map(function(col,idx){ +//console.log(idx, col.toString(), col.as); + var colexp = col.expression.toJavaScript("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' + || col.aggregatorid == 'MIN' + || col.aggregatorid == 'MAX' + || col.aggregatorid == 'FIRST' + || col.aggregatorid == 'LAST' +// || col.aggregatorid == 'AVG' +// ) { return '\''+col.as+'\':r[\''+col.as+'\'],'; }//f.field.arguments[0].toJavaScript(); + ) { return '\''+colas+'\':'+colexp+','; }//f.field.arguments[0].toJavaScript(); + 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 { + return '\''+colas+'\':(typeof '+colexp+' != "undefined")?1:0,'; + } + +// else if(col.aggregatorid == 'MIN') { return '\''+col.as+'\':r[\''+col.as+'\'],'; } +// else if(col.aggregatorid == 'MAX') { return '\''+col.as+'\':r[\''+col.as+'\'],'; } + } else if(col.aggregatorid == 'AVG') { + query.removeKeys.push('_SUM_'+colas); + query.removeKeys.push('_COUNT_'+colas); + return '\''+colas+'\':'+colexp+',\'_SUM_'+colas+'\':'+colexp+',\'_COUNT_'+colas+'\':1,'; + } else if(col.aggregatorid == 'AGGR') { + aft += ',g[\''+colas+'\']='+col.expression.toJavaScript('g',-1); + return ''; + } else if(col.aggregatorid == 'REDUCE') { + return '\''+colas+'\':alasql.aggr[\''+col.funcid+'\']('+colexp+'),'; + } + return ''; + } else return ''; + }).join(''); + + + + + + // columnid:r.columnid + // var srg = [];//rg.map(function(fn){ return (fn+':'+fn); }); + + // var srg = this.group.map(function(col){ + // if(col == '') return ''; + // else return col.columnid+':'+col.toJavaScript('r',''); + // }); + + // Initializw aggregators + + /* + this.columns.forEach(function(col){ + // console.log(f); + // if(f.constructor.name == 'LiteralValue') return ''; + + + if (col instanceof yy.AggrValue) { + if (col.aggregatorid == 'SUM') { srg.push("'"+col.as+'\':0'); }//f.field.arguments[0].toJavaScript(); + else if(col.aggregatorid == 'COUNT') {srg.push( "'"+col.as+'\':0'); } + else if(col.aggregatorid == 'MIN') { srg.push( "'"+col.as+'\':Infinity'); } + else if(col.aggregatorid == 'MAX') { srg.push( "'"+col.as+'\':-Infinity'); } + // else if(col.aggregatorid == 'AVG') { srg.push(col.as+':0'); } + // return 'group.'+f.name.value+'=+(+group.'+f.name.value+'||0)+'+f.field.arguments[0].toJavaScript('rec','')+';'; //f.field.arguments[0].toJavaScript(); + }; + + }); + + */ + + /*****************/ + + // s += srg.join(','); + + // var ss = []; + // gff.forEach(function(fn){ + // ss.push(fn+':rec.'+fn); + // }); + // s += ss.join(','); + // s += '});};'; + + s += '}'+aft+',g));} else {'; + // console.log(s, this.columns); + + + + // var neggroup = arrayDiff(allgroups,agroup); + + // console.log(agroup,neggroup); + + // s += neggroup.map(function(columnid){ + // return "g['"+columnid+"']=null;"; + // }).join(''); + + // console.log(s); + + + //console.log(query.selectfn); +// s += self.columns.map(function(col){ + s += query.selectGroup.map(function(col,idx){ + var colas = col.nick; + // if(typeof colas == 'undefined') { + // if(col instanceof yy.Column) colas = col.columnid; + // else colas = col.toString(); + // } + var colexp = col.expression.toJavaScript("p",tableid,defcols); + + if (col instanceof yy.AggrValue) { + if(col.distinct) { + var pre = 'if(typeof '+colexp+'!="undefined" && (!g[\'$$_VALUES_'+colas+'\']['+colexp+'])) \ + {'; + var post = 'g[\'$$_VALUES_'+colas+'\']['+colexp+']=true;}'; + } else { + var pre = '', post = ''; + } + if (col.aggregatorid == 'SUM') { return pre+'g[\''+colas+'\']+='+colexp+';'+post; }//f.field.arguments[0].toJavaScript(); + else if(col.aggregatorid == 'COUNT') { +// console.log(221,col.expression.columnid == '*'); + if(col.expression.columnid == '*') return pre+'g[\''+colas+'\']++;'+post; + else { + return pre+'if(typeof '+colexp+'!="undefined") g[\''+colas+'\']++;'+post; + } + } + else if(col.aggregatorid == 'ARRAY') { return pre+'g[\''+colas+'\'].push('+colexp+');'+post; } + else if(col.aggregatorid == 'MIN') { return pre+'g[\''+colas+'\']=Math.min(g[\''+colas+'\'],'+colexp+');'+post; } + else if(col.aggregatorid == 'MAX') { return pre+'g[\''+colas+'\']=Math.max(g[\''+colas+'\'],'+colexp+');'+post; } + else if(col.aggregatorid == 'FIRST') { return ''; } + else if(col.aggregatorid == 'LAST') { return pre+'g[\''+colas+'\']='+colexp+';'+post; } + else if(col.aggregatorid == 'AVG') { + return pre+'g[\'_SUM_'+colas+'\']+='+colexp+';' + + 'g[\'_COUNT_'+colas+'\']++;' + + 'g[\''+colas+'\']=g[\'_SUM_'+colas+'\']/g[\'_COUNT_'+colas+'\'];'+post; +// } + // else if(col.aggregatorid == 'AVG') { srg.push(colas+':0'); } + } else if(col.aggregatorid == 'AGGR') { + return pre+'g[\''+colas+'\']='+col.expression.toJavaScript('g',-1)+';'+post; + } else if(col.aggregatorid == 'REDUCE') { + return pre+'g[\''+colas+'\']=alasql.aggr.'+col.funcid+'('+colexp+',g[\''+colas+'\']);'+post; + } + return ''; + } else return ''; + }).join(''); + + + // s += selectFields.map(function(f){ + // console.log(f); + // if(f.constructor.name == 'LiteralValue') return ''; + // if (f.field instanceof SQLParser.nodes.FunctionValue + // && (f.field.name.toUpperCase() == 'SUM' || f.field.name.toUpperCase() == 'COUNT')) { + // return 'group.'+f.name.value+'=+(+group.'+f.name.value+'||0)+'+f.field.arguments[0].toJavaScript('rec','')+';'; //f.field.arguments[0].toJavaScript(); + // return 'group.'+f.name.value+'+='+f.field.arguments[0].toJavaScript('rec','')+';'; //f.field.arguments[0].toJavaScript(); + // return 'group.'+f.name.value+'+=rec.'+f.name.value+';'; //f.field.arguments[0].toJavaScript(); + // }; + // return ''; + // }).join(''); + + //s += ' group.amt += rec.emplid;'; + //s += 'group.count++;'; + s += '}'; + + }); + +// console.log('groupfn',s); + return new Function('p,params,alasql',s); + +} + + +/* +// +// Select compiler part for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +// yy.Select.prototype.compileSources = function(query) { +// return sources; +// }; + +function compileSelectStar (query,alias) { + // console.log(query.aliases[alias]); +// console.log(query,alias); + // console.log(query.aliases[alias].tableid); +// console.log(42,631,alias); +// console.log(query.aliases); + var s = '', sp = '', ss=[]; +// if(!alias) { +// sp += 'for(var k1 in p) var w=p[k1];for(var k2 in w){r[k2]=w[k2]};'; +// } else { + if(query.aliases[alias].tableid) { + var columns = alasql.databases[query.aliases[alias].databaseid].tables[query.aliases[alias].tableid].columns; + }; + // Check if this is a Table or other + + if(columns && columns.length > 0) { + columns.forEach(function(tcol){ + ss.push('\''+tcol.columnid+'\':p[\''+alias+'\'][\''+tcol.columnid+'\']'); + query.selectColumns[escapeq(tcol.columnid)] = true; + + // console.log('ok',s); + + var coldef = { + columnid:tcol.columnid, + dbtypeid:tcol.dbtypeid, + dbsize:tcol.dbsize, + dbprecision:tcol.dbprecision, + dbenum: tcol.dbenum + }; + query.columns.push(coldef); + query.xcolumns[coldef.columnid]=coldef; + + }); +//console.log(999,columns); + } else { + // if column not exists, then copy all + sp += 'var w=p["'+alias+'"];for(var k in w){r[k]=w[k]};'; +//console.log(777, sp); + query.dirtyColumns = true; + } +// } +//console.log({s:ss.join(','),sp:sp}); + return {s:ss.join(','),sp:sp}; +} + + +yy.Select.prototype.compileSelect1 = function(query) { + 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){ +//console.log(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); + if(ret.s) ss = ss.concat(ret.s); + sp += ret.sp; + + } else { +// console.log('aliases', query.aliases); + for(var alias in query.aliases) { + var ret = compileSelectStar(query, alias); //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; +// console.log(query.sources); + 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 != '_') { + 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]) { +// console.log(query.database,tbid,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; +//console.log(xcolumns, col,123); +// console.log(0); + if(xcolumns && columns.length > 0) { +// console.log(1); + var tcol = xcolumns[col.columnid]; + var coldef = { + columnid:col.as || col.columnid, + dbtypeid:tcol.dbtypeid, + dbsize:tcol.dbsize, + dbpecision:tcol.dbprecision, + dbenum: tcol.dbenum, + }; +// console.log(2); + query.columns.push(coldef); + query.xcolumns[coldef.columnid]=coldef; + } else { + query.dirtyColumns = true; + } + } else { + // This is a subquery? + // throw new Error('There is now such table \''+col.tableid+'\''); + }; + + } + } else if(col instanceof yy.AggrValue) { + if(!self.group) { +// self.group=[new yy.Column({columnid:'q',as:'q' })]; + self.group = ['']; + } + if(!col.as) col.as = escapeq(col.toString()); + if (col.aggregatorid == 'SUM' || col.aggregatorid == 'MAX' || col.aggregatorid == 'MIN' || + col.aggregatorid == 'FIRST' || col.aggregatorid == 'LAST' || + col.aggregatorid == 'AVG' || col.aggregatorid == 'ARRAY' || col.aggregatorid == 'REDUCE' + ) { + ss.push("'"+escapeq(col.as)+'\':'+col.expression.toJavaScript("p",query.defaultTableid,query.defcols)) + } else if (col.aggregatorid == 'COUNT') { + ss.push("'"+escapeq(col.as)+"':1"); + // Nothing + } + query.selectColumns[col.aggregatorid+'('+escapeq(col.expression.toString())+')'] = thtd; + +// else if (col.aggregatorid == 'MAX') { +// ss.push((col.as || col.columnid)+':'+col.toJavaScript("p.",query.defaultTableid)) +// } else if (col.aggregatorid == 'MIN') { +// ss.push((col.as || col.columnid)+':'+col.toJavaScript("p.",query.defaultTableid)) +// } + } else { + ss.push('\''+escapeq(col.as || col.columnid || col.toString())+'\':'+col.toJavaScript("p",query.defaultTableid,query.defcols)); +// ss.push('\''+escapeq(col.toString())+'\':'+col.toJavaScript("p",query.defaultTableid)); + //if(col instanceof yy.Expression) { + query.selectColumns[escapeq(col.as || col.columnid || col.toString())] = true; + } + }); + s += ss.join(',')+'};'+sp; + return s; +//console.log(42,753,query.xcolumns, query.selectColumns); +} +yy.Select.prototype.compileSelect2 = function(query) { + + var s = query.selectfns ; +// console.log(s); + return new Function('p,params,alasql',s+'return r'); +}; + + +yy.Select.prototype.compileSelectGroup0 = function(query) { + var self = this; + self.columns.forEach(function(col,idx){ + if(col instanceof yy.Column && col.columnid == '*') { + } else { + var colas; + // = col.as; + if(col instanceof yy.Column) { + colas = escapeq(col.columnid); + } else { + colas = escapeq(col.toString()); + } + for(var i=0;irb) return 1; + if(ra==rb) return 0; + return -1; + } + }; + + var s = ''; + var sk = ''; + this.order.forEach(function(ord,idx){ + // console.log(ord instanceof yy.Expression); + // console.log(ord.toJavaScript('a','')); + // console.log(ord.expression instanceof yy.Column); + + // Date conversion + var dg = ''; +//console.log(ord.expression, ord.expression instanceof yy.NumValue); + if(ord.expression instanceof yy.NumValue) { + ord.expression = self.columns[ord.expression.value-1]; + }; + + 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') 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.toJavaScript('a','')+dg+(ord.direction == 'ASC'?'>':'<')+ord.toJavaScript('b','')+dg+')return 1;'; + s += 'if('+ord.toJavaScript('a','')+dg+'=='+ord.toJavaScript('b','')+dg+'){'; + } + +// if(columnid == '_') { +// s += 'if(a'+dg+(ord.direction == 'ASC'?'>':'<')+'b'+dg+')return 1;'; +// s += 'if(a'+dg+'==b'+dg+'){'; +// } else { + // TODO Add date comparision + // s += 'if(a[\''+columnid+"']"+dg+(ord.direction == 'ASC'?'>':'<')+'b[\''+columnid+"']"+dg+')return 1;'; + // s += 'if(a[\''+columnid+"']"+dg+'==b[\''+columnid+"']"+dg+'){'; +// } + sk += '}'; + }); + s += 'return 0;'; + s += sk+'return -1'; + query.orderfns = s; +//console.log(s); + return new Function('a,b',s); + }; +}; + + + +/* +// +// ROLLUP(), CUBE(), GROUPING SETS() for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +/** + Calculate ROLLUP() combination + */ + +var rollup = function (a,query) { + var rr = []; + var mask = 0; + var glen = a.length; + for(var g=0;g'+gv[t]+'<',gv[t]=='',typeof gv[t]); +// console.log(gv[t].toString()); +//console.log('+++'); + res = res.map(function(r){ + query.groupColumns[escapeq(gv[t].toString())] = escapeq(gv[t].toString()); + return r.concat(escapeq(gv[t].toString()) + +'\t' + +gv[t].toJavaScript('p',query.sources[0].alias,query.defcols)) + }); +// res = res.concat(gv[t]); + }; + + // switch(gv[t].t) { + // case 'plain': + // res = res.map(function(r){return r.concat(gv[t].p)}); + + // break; + // case 'rollup': res = cartes(res,rollup(gv[t].p)); break; + // case 'cube': res = cartes(res,cube(gv[t].p)); break; + // case 'groupingsets': res = cartes(res,groupingsets(gv[t].p)); break; + // default: res = res.concat(gv[t]); + // } + }; + return res; + } else if(gv instanceof yy.FuncValue) { +// console.log(gv); + query.groupColumns[escapeq(gv.toString())] = escapeq(gv.toString()); + return [gv.toString()+'\t'+gv.toJavaScript('p',query.sources[0].alias,query.defcols)]; + } else if(gv instanceof yy.Column) { + gv.nick = escapeq(gv.columnid); + query.groupColumns[gv.nick] = gv.nick; + return [gv.nick+'\t'+gv.toJavaScript('p',query.sources[0].alias,query.defcols)]; // Is this ever happened? + // } else if(gv instanceof yy.Expression) { + // return [gv.columnid]; // Is this ever happened? + } else { + query.groupColumns[escapeq(gv.toString())] = escapeq(gv.toString()); + return [escapeq(gv.toString())+'\t'+gv.toJavaScript('p',query.sources[0].alias,query.defcols)]; +// throw new Error('Single argument in the group without array'); + }; + + + // switch(gv.t) { + // case 'plain': return gv.p; break; + // case 'rollup': return rollup(gv.p); break; + // case 'cube': return cube(gv.p); break; + // case 'groupingsets': return groupingsets(gv.p); break; + // default: return [gv];//return decartes(gv.p); + // } + // return gv; +}; + + + + +/* +// +// Select run-time part for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +yy.Select.prototype.compileDefCols = function(query, databaseid) { +// console.log('defcols'); + var defcols = {}; + if(this.from) { + this.from.forEach(function(fr){ + if(fr instanceof yy.Table) { + var alias = fr.as || fr.tableid; +// console.log(alasql.databases[fr.databaseid || databaseid]); +// console.log(alasql.databases[fr.databaseid || databaseid].tables, fr.tableid); +//console.log(alasql.databases[fr.databaseid || databaseid].tables, fr.tableid); +//console.log(alasql.databases); + var table = alasql.databases[fr.databaseid || databaseid].tables[fr.tableid]; +//console.log(table); + 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.ParamValue) { + + } else if(fr instanceof yy.VarValue) { + + } else if(fr instanceof yy.FuncValue) { + + } else if(fr instanceof yy.FromData) { + + } else { + throw new Error('Unknown type of FROM clause'); + }; + }); + }; + + if(this.joins) { + this.joins.forEach(function(jn){ +// console.log(jn); + 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]; +// console.log(jn.table.tableid, jn.table.databaseid); + 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; + // } +// console.log(defcols); + return defcols; +} + +/* +// +// UNION for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +// SELECT UNION statement + +yy.Union = function (params) { return yy.extend(this, params); } +yy.Union.prototype.toString = function () { + return K('UNION'); +}; + +yy.Union.prototype.compile = function (tableid) { + return null; +}; + +/* +// +// CROSS AND OUTER APPLY for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +yy.Apply = function (params) { return yy.extend(this, params); } +yy.Apply.prototype.toString = function () { + var s = K(this.applymode)+' '+K('APPLY')+' ('; + s += this.select.toString()+')'; + if(this.as) s += ' '+K('AS')+' '+L(this.as); + return s; +}; + + + +/* +// +// CROSS AND OUTER APPLY for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +yy.Over = function (params) { return yy.extend(this, params); } +yy.Over.prototype.toString = function () { + var s = K('OVER')+' ('; + if(this.partition) { + s += K('PARTITION')+' '+K('BY')+' '+this.partition.toString(); + if(this.order) s+=' '; + } + if(this.order) { + s += K('ORDER')+' '+K('BY')+' '+this.order.toString(); + } + s += ')'; + return s; +}; + + + +/* +// +// Expressions for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +yy.ExpressionStatement = function(params) { return yy.extend(this, params); }; +yy.ExpressionStatement.prototype.toString = function() { + return this.expression.toString(); +}; + +yy.ExpressionStatement.prototype.execute = function (databaseid, params, cb) { + if(this.expression) { +// console.log(this.expression.toJavaScript('','', null)); +// console.log(this.expression.toJavaScript('','', null)); + var expr = new Function("params,alasql,p",'return '+this.expression.toJavaScript('','', null)); + var res = expr(params,alasql); + if(cb) res = cb(res); + return res; + } +} + +yy.Expression = function(params) { return yy.extend(this, params); }; +yy.Expression.prototype.toString = function() { + var s = this.expression.toString(); + if(this.order) s += ' '+this.order.toString(); + if(this.nocase) s += ' '+K('COLLATE')+' '+K('NOCASE'); + return s; +}; +yy.Expression.prototype.findAggregator = function (query){ + if(this.expression.findAggregator) this.expression.findAggregator(query); +}; + +yy.Expression.prototype.toJavaScript = function(context, tableid, defcols) { +// console.log('Expression',this); + if(this.expression.reduced) return 'true'; + return this.expression.toJavaScript(context, tableid, defcols); +}; +yy.Expression.prototype.compile = function(context, tableid, defcols){ +// console.log('Expression',this); + if(this.reduced) return returnTrue(); + return new Function('p','return '+this.toJavaScript(context, tableid, defcols)); +}; + + +yy.JavaScript = function(params) { return yy.extend(this, params); }; +yy.JavaScript.prototype.toString = function() { + var s = '``'+this.value+'``'; + return s; +}; + +yy.JavaScript.prototype.toJavaScript = function(context, tableid, defcols) { +// console.log('Expression',this); + return '('+this.value+')'; +}; +yy.JavaScript.prototype.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; +} + + +yy.Literal = function (params) { return yy.extend(this, params); } +yy.Literal.prototype.toString = function() { + var s = this.value; + if(this.value1) s = this.value1+'.'+s; +// else s = tableid+'.'+s; + return L(s); +} + + +yy.Join = function (params) { return yy.extend(this, params); } +yy.Join.prototype.toString = function() { + var s = NL()+ID(); + if(this.joinmode) s += K(this.joinmode)+' '; + s += K('JOIN')+this.table.toString(); + return s; +} + +//yy.Join.prototype.toJavaScript = function(context, tableid) { +// return 'JOIN'+this.table.toString(); +//} + + +yy.Table = function (params) { return yy.extend(this, params); } +yy.Table.prototype.toString = function() { + var s = this.tableid; +// if(this.joinmode) + if(this.databaseid) s = this.databaseid+'.'+s; + return L(s); +}; + + +yy.View = function (params) { return yy.extend(this, params); } +yy.View.prototype.toString = function() { + var s = this.viewid; +// if(this.joinmode) + if(this.databaseid) s = this.databaseid+'.'+s; + return L(s); +}; + + +yy.Op = function (params) { return yy.extend(this, params); } +yy.Op.prototype.toString = function() { + if(this.op == 'IN' || this.op == 'NOT IN') { + return this.left.toString()+" "+P(this.op)+" ("+this.right.toString()+")"; + } + if(this.allsome) { + return this.left.toString()+" "+P(this.op)+" "+this.allsome+' ('+this.right.toString()+')'; + } + if(this.op == '->') { + var s = this.left.toString()+"->"; +// console.log(this.right); + 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()+" "+P(this.op)+" "+(this.allsome?this.allsome+' ':'')+this.right.toString(); +}; + +yy.Op.prototype.findAggregator = function (query){ +// console.log(this.toString()); + 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); + } +}; + +yy.Op.prototype.toType = function(tableid) { + if(['-','*','/','%','^'].indexOf(this.op) >-1) return 'number'; + 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'].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'; +}; + +yy.Op.prototype.toJavaScript = function(context,tableid,defcols) { +// console.log(this); + var op = this.op; + if(this.op == '=') op = '==='; + else if(this.op == '<>') op = '!='; + else if(this.op == 'OR') op = '||'; + + if(this.op == '->') { +// console.log(this.right, typeof this.right); + if(typeof this.right == "string") { + return this.left.toJavaScript(context,tableid, defcols)+'["'+this.right+'"]'; + } else if(typeof this.right == "number") { + return this.left.toJavaScript(context,tableid, defcols)+'['+this.right+']'; + } else if(this.right instanceof yy.FuncValue) { + ss = []; + if(!this.right.args || this.right.args.length == 0) { + } else { + var ss = this.right.args.map(function(arg){ + return arg.toJavaScript(context,tableid, defcols); + }); + } + return this.left.toJavaScript(context,tableid, defcols)+'[\''+this.right.funcid+'\']('+ + ss.join(',')+')'; + } else { + return this.left.toJavaScript(context,tableid, defcols)+'['+this.right.toJavaScript(context,tableid, defcols)+']'; + } + } + + if(this.op == 'IS') { + return '((typeof '+this.left.toJavaScript(context,tableid, defcols)+"=='undefined') == " + + '(typeof '+this.right.toJavaScript(context,tableid, defcols)+"=='undefined'))"; + } + + + if(this.op == '==') { + return 'alasql.utils.deepEqual('+this.left.toJavaScript(context,tableid, defcols)+","+this.right.toJavaScript(context,tableid, defcols)+')'; + } + if(this.op == '===') { + return "(("+this.left.toJavaScript(context,tableid, defcols)+").valueOf()===("+this.right.toJavaScript(context,tableid, defcols)+'.valueOf()))'; + } + + if(this.op == '!===') { + return "!(("+this.left.toJavaScript(context,tableid, defcols)+").valueOf()===("+this.right.toJavaScript(context,tableid, defcols)+'.valueOf()))'; + } + + + if(this.op == '!==') { + return '(!alasql.utils.deepEqual('+this.left.toJavaScript(context,tableid, defcols)+","+this.right.toJavaScript(context,tableid, defcols)+'))'; + } + + if(this.op == 'LIKE') { + var s = "("+this.left.toJavaScript(context,tableid, defcols)+"+'')"+ + ".toUpperCase().match(new RegExp('^'+("+this.right.toJavaScript(context,tableid, defcols)+").replace(/\\\%/g,'.*').toUpperCase()+'$','g'))" +// console.log(s); + return s; + }; + + if(this.op == 'NOT LIKE') { + var s = "!(("+this.left.toJavaScript(context,tableid, defcols)+"+'')"+ + ".toUpperCase().match(new RegExp('^'+("+this.right.toJavaScript(context,tableid, defcols)+").replace(/\\\%/g,'.*').toUpperCase()+'$','g')))" + return s; + }; + + if(this.op == 'BETWEEN') { + if(this.right instanceof yy.Op && this.right.op == 'AND') { + return '(('+this.right.left.toJavaScript(context,tableid, defcols)+'<='+this.left.toJavaScript(context,tableid, defcols)+')&&'+ + '('+this.left.toJavaScript(context,tableid, defcols)+'<='+this.right.right.toJavaScript(context,tableid, defcols)+'))'; + } else { + throw new Error('Wrong BETWEEN operator without AND part'); + } + }; + + if(this.op == 'NOT BETWEEN') { + if(this.right instanceof yy.Op && this.right.op == 'AND') { + return '!(('+this.right.left.toJavaScript(context,tableid, defcols)+'<='+this.left.toJavaScript(context,tableid, defcols)+')&&'+ + '('+this.left.toJavaScript(context,tableid, defcols)+'<='+this.right.right.toJavaScript(context,tableid, defcols)+'))'; + } else { + throw new Error('Wrong NOT BETWEEN operator without AND part'); + } + }; + + if(this.op == 'IN') { + if(this.right instanceof yy.Select ) { + var s = '('; +// s += 'this.query.queriesdata['+this.queriesidx+']'; + s += 'alasql.utils.flatArray(this.query.queriesfn['+(this.queriesidx)+'](params,null,p))'; + s += '.indexOf('; + s += this.left.toJavaScript(context,tableid, defcols)+')>-1)'; + return s; + } else if(this.right instanceof Array ) { +// if(this.right.length == 0) return 'false'; + var s = '(['+this.right.map(function(a){return a.toJavaScript(context,tableid, defcols)}).join(',')+'].indexOf('; + s += this.left.toJavaScript(context,tableid, defcols)+')>-1)'; +//console.log(s); + return s; + } else { + var s = '('+this.right.toJavaScript(context,tableid, defcols)+'.indexOf('; + s += this.left.toJavaScript(context,tableid, defcols)+')>-1)'; + return s; +// } else { +// throw new Error('Wrong IN operator without SELECT part'); + } + }; + + + if(this.op == 'NOT IN') { + if(this.right instanceof yy.Select ) { + var s = '(' + //this.query.queriesdata['+this.queriesidx+'] + s += 'alasql.utils.flatArray(this.query.queriesfn['+(this.queriesidx)+'](params,null,p))'; + s +='.indexOf('; + s += this.left.toJavaScript(context,tableid, defcols)+')<0)'; + return s; + } else if(this.right instanceof Array ) { +// if(this.right.length == 0) return 'true'; + var s = '(['+this.right.map(function(a){return a.toJavaScript(context,tableid, defcols)}).join(',')+'].indexOf('; + s += this.left.toJavaScript(context,tableid, defcols)+')<0)'; + return s; + } else { + throw new Error('Wrong NOT IN operator without SELECT part'); + } + }; + + if(this.allsome == 'ALL') { + if(this.right instanceof yy.Select ) { +// var s = 'this.query.queriesdata['+this.queriesidx+']'; + var s = 'alasql.utils.flatArray(this.query.queriesfn['+(this.queriesidx)+'](params,null,p))'; + + s +='.every(function(b){return ('; + s += this.left.toJavaScript(context,tableid, defcols)+')'+op+'b})'; + return s; + } else if(this.right instanceof Array ) { + var s = '['+this.right.map(function(a){return a.toJavaScript(context,tableid, defcols)}).join(',')+'].every(function(b){return ('; + s += this.left.toJavaScript(context,tableid, defcols)+')'+op+'b})'; + return s; + } else { + throw new Error('Wrong NOT IN operator without SELECT part'); + } + }; + + if(this.allsome == 'SOME' || this.allsome == 'ANY') { + if(this.right instanceof yy.Select ) { +// var s = 'this.query.queriesdata['+this.queriesidx+']'; + var s = 'alasql.utils.flatArray(this.query.queriesfn['+(this.queriesidx)+'](params,null,p))'; + s+='.some(function(b){return ('; + s += this.left.toJavaScript(context,tableid, defcols)+')'+op+'b})'; + return s; + } else if(this.right instanceof Array ) { + var s = '['+this.right.map(function(a){return a.toJavaScript(context,tableid, defcols)}).join(',')+'].some(function(b){return ('; + s += this.left.toJavaScript(context,tableid, defcols)+')'+op+'b})'; + return s; + } else { + throw new Error('Wrong NOT IN operator without SELECT part'); + } + }; + +// Special case for AND optimization (if reduced) + if(this.op == 'AND') { + if(this.left.reduced) { + if(this.right.reduced) { + return 'true'; + } else { + return this.right.toJavaScript(context,tableid, defcols); + } + } else if(this.right.reduced) { + return this.left.toJavaScript(context,tableid, defcols); + } + + // Otherwise process as regular operation (see below) + op = '&&'; + + } + + if(this.op == '^') { + return 'Math.pow('+this.left.toJavaScript(context,tableid, defcols) + +','+this.right.toJavaScript(context,tableid, defcols)+')'; + }; + + + // Change names +// console.log(this); + return '('+this.left.toJavaScript(context,tableid, defcols)+op+this.right.toJavaScript(context,tableid, defcols)+')'; +}; + + + +yy.VarValue = function (params) { return yy.extend(this, params); } +yy.VarValue.prototype.toString = function() { + return '@'+L(this.variable); +}; + +yy.VarValue.prototype.toType = function() { + return 'unknown'; +}; + +yy.VarValue.prototype.toJavaScript = function() { + return "alasql.vars['"+this.variable+"']"; +} + + +yy.NumValue = function (params) { return yy.extend(this, params); } +yy.NumValue.prototype.toString = function() { + return N(this.value.toString()); +}; + +yy.NumValue.prototype.toType = function() { + return 'number'; +}; + +yy.NumValue.prototype.toJavaScript = function() { + return ""+this.value; +} + + + + +yy.StringValue = function (params) { return yy.extend(this, params); } +yy.StringValue.prototype.toString = function() { + return "'"+S(this.value.toString())+"'"; +} + +yy.StringValue.prototype.toType = function() { + return 'string'; +} + +yy.StringValue.prototype.toJavaScript = function() { +// console.log("'"+doubleqq(this.value)+"'"); +// return "'"+doubleqq(this.value)+"'"; + return "'"+escapeq(this.value)+"'"; + +} + + +yy.LogicValue = function (params) { return yy.extend(this, params); } +yy.LogicValue.prototype.toString = function() { + return this.value?'TRUE':'FALSE'; +} + +yy.LogicValue.prototype.toType = function() { + return 'boolean'; +} + +yy.LogicValue.prototype.toJavaScript = function() { + return this.value?'true':'false'; +} + +yy.NullValue = function (params) { return yy.extend(this, params); } +yy.NullValue.prototype.toString = function() { + return 'NULL'; +} +yy.NullValue.prototype.toJavaScript = function() { + return 'undefined'; +} + +yy.ParamValue = function (params) { return yy.extend(this, params); } +yy.ParamValue.prototype.toString = function() { + return '$'+this.param; +} +yy.ParamValue.prototype.toJavaScript = function() { + if(typeof this.param == "string") return "params[\'"+this.param+"\']"; + else return "params["+this.param+"]"; +} + + + +yy.UniOp = function (params) { return yy.extend(this, params); } +yy.UniOp.prototype.toString = function() { + if(this.op == '-') return this.op+this.right.toString(); + if(this.op == '+') return this.op+this.right.toString(); + if(this.op == 'NOT') return this.op+'('+this.right.toString()+')'; + else if(this.op == null) return '('+this.right.toString()+')'; +}; + +yy.UniOp.prototype.findAggregator = function (query){ + if(this.right.findAggregator) this.right.findAggregator(query); +}; + +yy.UniOp.prototype.toType = function(tableid) { + if(this.op == '-') return 'number'; + if(this.op == '+') return 'number'; + if(this.op == 'NOT') return 'boolean'; +}; + +yy.UniOp.prototype.toJavaScript = function(context, tableid, defcols) { + if(this.op == '-') return "(-("+this.right.toJavaScript(context, tableid, defcols)+"))"; + if(this.op == '+') return "("+this.right.toJavaScript(context, tableid, defcols)+")"; + if(this.op == 'NOT') return '!('+this.right.toJavaScript(context, tableid, defcols)+')'; + else if(this.op == null) return '('+this.right.toJavaScript(context, tableid, defcols)+')'; +}; + + + +// yy.Star = function (params) { return yy.extend(this, params); } +// yy.Star.prototype.toString = function() { +// var s = this.fieldid; +// if(this.tableid) { +// s = this.tableid+'.'+s; +// if(this.databaseid) { +// s = this.databaseid+'.'+s; +// } +// } +// if(this.alias) s += ' AS '+this.alias; +// return s; +// } + +yy.Column = function(params) { return yy.extend(this, params); } +yy.Column.prototype.toString = function() { + var s; + if(this.columnid == +this.columnid) { + 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) s += ' AS '+this.alias; + return s; +}; + +yy.Column.prototype.toJavaScript = function(context, tableid, defcols) { +// var s = this.value; +// var s = this.columnid; +// if(this.tableid) { +// s = this.tableid+'.'+s; +// // if(this.databaseid) { +// // s = this.databaseid+'.'+s; +// // } +// } else { +// s = tableid+'.'+s; +// } +//console.log('yy.Column',this, tableid); +// console.log(392,this.columnid); + 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 != '_') { + 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 != '_') { + s = context+'[\''+(this.tableid || tableid) + '\'][\''+this.columnid+'\']'; + } else { + s = context+'[\''+(this.tableid || tableid) + '\']'; + }; + } + } else if(tableid == -1) { +// if(this.columnid != '') { + s = context+'[\''+this.columnid+'\']'; +// } else { +// s = context; +// } + } else { + if(this.columnid != '_') { + s = context+'[\''+(this.tableid || tableid) + '\'][\''+this.columnid+'\']'; + } else { + s = context+'[\''+(this.tableid || tableid) + '\']'; + } + } + } +// console.log(context,s); +// console.trace(new Error()); + return s; +} + + + + +yy.AggrValue = function(params){ return yy.extend(this, params); } +yy.AggrValue.prototype.toString = function() { + var s = ''; + if(this.aggregatorid == 'REDUCE') s += L(this.funcid)+'('; + else s += this.aggregatorid+'('; + if(this.distinct) s+= K('DISTINCT')+' '; + if(this.expression) s += this.expression.toString(); + s += ')'; + if(this.over) s += ' '+this.over.toString(); +// console.log(this.over); +// if(this.alias) s += ' AS '+this.alias; + return s; +}; +yy.AggrValue.prototype.findAggregator = function (query){ +// console.log('aggregator found',this.toString()); + +// var colas = this.as || this.toString(); + + var colas = escapeq(this.toString())+':'+query.selectGroup.length; +// console.log('findAgg',this); + + +/* var found = false; + for(var i=0;i-1) return 'number'; + if(['ARRAY'].indexOf(this.aggregatorid)>-1) return 'array'; + if(['FIRST','LAST' ].indexOf(this.aggregatorid)>-1) return this.expression.toType(); +} +yy.AggrValue.prototype.toJavaScript = function(context, tableid, defcols) { +// var s = 'alasql.functions.'+this.funcid+'('; +// if(this.expression) s += this.expression.toJavaScript(context, tableid); +// s += ')'; +// if(this.alias) s += ' AS '+this.alias; +// return s; +// var s = ''; +//if(this.as) console.log(499,this.as); +// var colas = this.as; + var colas = this.nick; + if(typeof colas == 'undefined') colas = this.toString(); + return 'g[\''+colas+'\']'; +} + + +yy.OrderExpression = function(params){ return yy.extend(this, params); } +yy.OrderExpression.prototype.toString = function() { + var s = this.expression.toString(); + if(this.order) s += ' '+this.order.toString(); + if(this.nocase) s += ' '+K('COLLATE')+' '+K('NOCASE'); + return s; +} + +yy.GroupExpression = function(params){ return yy.extend(this, params); } +yy.GroupExpression.prototype.toString = function() { + return this.type+'('+this.group.toString()+')'; +} + + +yy.ColumnDef = function (params) { return yy.extend(this, params); } +yy.ColumnDef.prototype.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; +} + + +// Alasql Linq library + +yy.FromData = function(params) { return yy.extend(this, params); }; +yy.FromData.prototype.toString = function() { + if(this.data) return K('DATA')+'('+((Math.random()*10e15)|0)+')'; + else return '?'; +}; +yy.FromData.prototype.toJavaScript = function(){ +// console.log('yy.FromData.prototype.toJavaScript'); +}; + +yy.Select.prototype.exec = function(params,cb) { + + if(this.preparams) params = this.preparams.concat(params); +// console.log(15,this.preparams); + + var databaseid = alasql.useid; + db = alasql.databases[databaseid]; + var sql = this.toString(); + var hh = hash(sql); +// console.log(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; +}; + +yy.Select.prototype.Select = function(){ + var self = this; + var agrs = []; + if(arguments.length > 1) { + args = Array.prototype.slice.call(arguments);; + } else if(arguments.length == 1) { + if(arguments[0] instanceof Array) { + 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 + } + }); + +// console.log(self instanceof yy.Select); + return self; +}; + +yy.Select.prototype.From = function(tableid){ + var self = this; + if(!self.from) self.from = []; + if(tableid instanceof Array) { + 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; +} + +yy.Select.prototype.OrderBy = function(){ + var self = this; + var agrs = []; + + self.order = []; + + if(arguments.length == 0) { +// self.order.push(new yy.OrderExpression({expression: new yy.Column({columnid:"_"}), direction:'ASC'})); + args = ["_"]; + } else if(arguments.length > 1) { + args = Array.prototype.slice.call(arguments);; + } else if(arguments.length == 1) { + if(arguments[0] instanceof Array) { + 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; +} + +yy.Select.prototype.Top = function(topnum){ + var self = this; + self.top = new yy.NumValue({value:topnum}); + return self; +}; + +yy.Select.prototype.GroupBy = function(){ + var self = this; + var agrs = []; + + if(arguments.length > 1) { + args = Array.prototype.slice.call(arguments);; + } else if(arguments.length == 1) { + if(arguments[0] instanceof Array) { + 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; +}; + +yy.Select.prototype.Where = function(expr){ + var self = this; + if(typeof expr == 'function' ) { + self.where = expr; + } + return self; +}; + + + +/* +// +// Functions for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +yy.FuncValue = function(params){ return yy.extend(this, params); } +yy.FuncValue.prototype.toString = function() { + 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) s += ' AS '+this.as.toString(); +// if(this.alias) s += ' AS '+this.alias; + return s; +} + +yy.FuncValue.prototype.findAggregator = function(query) { + if(this.args && this.args.length > 0) { + this.args.forEach(function(arg){ + if(arg.findAggregator) arg.findAggregator(query); + }); + } +}; + +yy.FuncValue.prototype.toJavaScript = function(context, tableid, defcols) { + var s = ''; + var funcid = this.funcid; + // IF this is standard compile functions + if(alasql.fn[funcid]) { + // This is user-defined run-time function + // TODO arguments!!! +// var s = ''; + if(this.newid) s+= 'new '; + s += 'alasql.fn.'+this.funcid+'('; +// if(this.args) s += this.args.toJavaScript(context, tableid); + if(this.args && this.args.length > 0) { + s += this.args.map(function(arg){ + return arg.toJavaScript(context, tableid, defcols); + }).join(','); + }; + s += ')'; + } else if(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.toJavaScript(context, tableid)})); + } else { + s += alasql.stdlib[funcid.toUpperCase()](); + } + } else if(alasql.stdfn[funcid.toUpperCase()]) { + if(this.newid) s+= 'new '; + s += 'alasql.stdfn.'+this.funcid.toUpperCase()+'('; +// if(this.args) s += this.args.toJavaScript(context, tableid); + if(this.args && this.args.length > 0) { + s += this.args.map(function(arg){ + return arg.toJavaScript(context, tableid, defcols); + }).join(','); + }; + s += ')'; + } else { + // Aggregator + } +//console.log('userfn:',s,this); + +// if(this.alias) s += ' AS '+this.alias; + return s; +} + +// // Functions compiler +// nodes.FunctionValue.prototype.toJavaScript = function (context, tableid) { +// var s = ''; +// s += fns[this.name.toUpperCase()].apply(null,this.arguments.map(function(arg){ +// if(arg) return arg.toJavaScript(context, tableid); +// else return ''; +// })); +// return s; +// }; + +// +// SQL FUNCTIONS COMPILERS +// Based on SQLite functions + +// IMPORTANT: These are compiled functions + +//alasql.fn = {}; // Keep for compatibility +//alasql.userlib = alasql.fn; + +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+')'}; +stdlib.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'); + }; +}; +stdlib.IFNULL = function(a,b) {return '('+a+'||'+b+')'}; +stdlib.INSTR = function(s,p) {return '(('+s+').indexOf('+p+')+1)'}; + +stdlib.LEN = stdlib.LENGTH = function(s) {return '('+s+'+"").length';}; +//stdlib.LENGTH = function(s) {return '('+s+').length'}; + +stdlib.LOWER = stdlib.LCASE = function(s) {return '('+s+').toLowerCase()';} +//stdlib.LCASE = function(s) {return '('+s+').toLowerCase()';} + + +// LTRIM + +stdlib.GREATEST = function(){ + return 'Math.max('+Array.prototype.join.call(arguments, ',')+')' +}; + +stdlib.LEAST = function(){ + return 'Math.min('+Array.prototype.join.call(arguments, ',')+')' +}; + +stdlib.MID = function(a,b,c){ + if(arguments.length == 2) return '('+a+').substr('+b+'-1)'; + else if(arguments.length == 3) return '('+a+').substr('+b+'-1,'+c+')'; +}; + +stdlib.NULLIF = function(a,b){return '('+a+'=='+b+'?null:'+a+')'}; + +stdlib.POWER = function(a,b) {return 'Math.pow('+a+','+b+')'}; + +stdlib.RANDOM = function(r) { + if(arguments.length == 0) { + return 'Math.random()'; + } else { + return '(Math.random()*('+r+')|0)'; + } +} +stdlib.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+')'; + } +} +stdlib.SQRT = function(s) {return 'Math.sqrt('+s+')'}; + +stdlib.TRIM = function(s) {return s+'.trim()'}; + +stdlib.UPPER = stdlib.UCASE = function(s) {return '('+s+').toUpperCase()';} +//stdlib.UCASE = function(s) {return '('+s+').toUpperCase()';} +//REPLACE +// RTRIM +// SUBSTR +// TRIM +//REPLACE +// RTRIM +// SUBSTR +// TRIM + + +// Aggregator for joining strings +alasql.aggr.GROUP_CONCAT = function(v,s){ + if(typeof s == "undefined") return v; else return s+','+v; +}; + + + + +// +// +// SQL and JS DateTime functions +// +// + + + +/* +// +// CASE for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +yy.CaseValue = function(params) { return yy.extend(this, params); }; +yy.CaseValue.prototype.toString = function() { + var s = 'CASE '; + if(this.expression) s += this.expression.toString(); + if(this.whens) { + s += this.whens.map(function(w) { return ' WHEN '+ + w.when.toString() + ' THEN '+w.then.toString()}).join(); + } + s += ' END'; + return s; +}; + +yy.CaseValue.prototype.findAggregator = function (query){ +// console.log(this.toString()); + if(this.expression && this.expression.findAggregator) this.expression.findAggregator(query); + if(this.whens && this.whens.length > 0) { + this.whens.forEach(function(w) { + if(w.when.findAggregator) w.when.findAggregator(query); + if(w.then.findAggregator) w.then.findAggregator(query); + }); + } +}; + +yy.CaseValue.prototype.toJavaScript = function(context, tableid, defcols) { + + var s = '(function('+context+',params,alasql){var r;'; + if(this.expression) { +// this.expression.toJavaScript(context, tableid) + s += 'v='+this.expression.toJavaScript(context, tableid, defcols)+';'; + s += (this.whens||[]).map(function(w) { return ' if(v=='+w.when.toJavaScript(context,tableid, defcols) + +') {r='+w.then.toJavaScript(context,tableid, defcols)+'}'; }).join(' else '); + if(this.elses) s += ' else {r='+this.elses.toJavaScript(context,tableid, defcols)+'}'; + } else { + s += (this.whens||[]).map(function(w) { return ' if('+w.when.toJavaScript(context,tableid, defcols) + +') {r='+w.then.toJavaScript(context,tableid, defcols)+'}'; }).join(' else '); + if(this.elses) s += ' else {r='+this.elses.toJavaScript(context,tableid,defcols)+'}'; + } + s += 'return r;})('+context+',params,alasql)'; + + return s; +}; + +/* +// +// JSON for Alasql.js +// Date: 19.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +yy.Json = function (params) { return yy.extend(this, params); } +yy.Json.prototype.toString = function() { + var s = '@'; + s += JSONtoString(this.value); + s += ''; + return s; +}; + +var JSONtoString = alasql.utils.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(obj instanceof Array) { + s += '['+obj.map(function(b){ + return JSONtoString(b); + }).join(',')+']'; + } else if(!obj.toJavaScript || 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; +} + + + +function JSONtoJavaScript(obj, context, tableid, defcols) { + 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(obj instanceof Array) { + s += '['+obj.map(function(b){ + return JSONtoJavaScript(b, context, tableid, defcols); + }).join(',')+']'; + } else if(!obj.toJavaScript || 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 += ':'+JSONtoJavaScript(obj[k], context, tableid, defcols); + ss.push(s1); + }; + s += ss.join(',')+'}'; + } else if(obj.toJavaScript) { + s = obj.toJavaScript(context, tableid, defcols); + } else { + throw new Error('1Can not parse JSON object '+JSON.stringify(obj)); + } + } else { + throw new Error('2Can not parse JSON object '+JSON.stringify(obj)); + } + + return s; +} + +yy.Json.prototype.toJavaScript = function(context, tableid, defcols) { + // TODO reod + return JSONtoJavaScript(this.value,context, tableid, defcols); +} + + + + +/* +// +// CAST and CONVERT functions +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +yy.Convert = function(params) { return yy.extend(this, params); }; +yy.Convert.prototype.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; +}; +yy.Convert.prototype.toJavaScript = function(context, tableid, defcols) { + +// if(this.style) { + return 'alasql.stdfn.CONVERT('+this.expression.toJavaScript(context, tableid, defcols) + +',{dbtypeid:"'+this.dbtypeid+'",dbsize:'+this.dbsize+',style:'+ + this.style+'})'; +// } +/* + if(this.dbtypeid == 'INT') { + return '(('+this.expression.toJavaScript(context, tableid, defcols)+')|0)'; + } if(this.dbtypeid == 'STRING') { + return '(""+'+this.expression.toJavaScript(context, tableid, defcols)+')'; + } if(this.dbtypeid == 'NUMBER') { + return '(+('+this.expression.toJavaScript(context, tableid, defcols)+'))'; + } if(this.dbtypeid == 'DATE') { + if(alasql.options.datetimeformat == 'javascript') { + return '(new Date('+this.expression.toJavaScript(context, tableid, defcols)+'))'; + } else if(alasql.options.datetimeformat == 'sql') { + return this.expression.toJavaScript(context, tableid, defcols); + } + } if(this.dbtypeid == 'DATETIME') { + if(alasql.options.datetimeformat == 'javascript') { + return '(new Date('+this.expression.toJavaScript(context, tableid, defcols)+'))'; + } else if(alasql.options.datetimeformat == 'sql') { + return this.expression.toJavaScript(context, tableid, defcols); + } + } else { + + }; +*/ + throw new Error('There is not such type conversion for '+this.toString()); +}; + +/** + Convert one type to another + */ +alasql.stdfn.CONVERT = function(value, args) { + var val = value; +// console.log(args); + 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); + + if(args.style == 1) { // mm/dd/yy + val = ("0"+(t.getMonth()+1)).substr(-2)+'/'+("0"+t.getDate()).substr(-2)+'/'+("0"+t.getYear()).substr(-2); + } else if(args.style == 2) { // yy.mm.dd + val = ("0"+t.getYear()).substr(-2)+'.'+("0"+(t.getMonth()+1)).substr(-2)+'.'+("0"+t.getDate()).substr(-2); + } else if(args.style == 3) { // dd/mm/yy + val = ("0"+t.getDate()).substr(-2)+'/'+("0"+(t.getMonth()+1)).substr(-2)+'/'+("0"+t.getYear()).substr(-2); + } else if(args.style == 4) { // dd.mm.yy + val = ("0"+t.getDate()).substr(-2)+'.'+("0"+(t.getMonth()+1)).substr(-2)+'.'+("0"+t.getYear()).substr(-2); + } else if(args.style == 5) { // dd-mm-yy + val = ("0"+t.getDate()).substr(-2)+'-'+("0"+(t.getMonth()+1)).substr(-2)+'-'+("0"+t.getYear()).substr(-2); + } else if(args.style == 6) { // dd mon yy + val = ("0"+t.getDate()).substr(-2)+' '+t.toString().substr(4,3).toLowerCase()+' '+("0"+t.getYear()).substr(-2); + } else if(args.style == 7) { // Mon dd,yy + val = t.toString().substr(4,3)+' '+("0"+t.getDate()).substr(-2)+','+("0"+t.getYear()).substr(-2); + } else if(args.style == 8) { // hh:mm:ss + val = ("0"+t.getHours()).substr(-2)+':'+("0"+(t.getMinutes()+1)).substr(-2)+':'+("0"+t.getSeconds()).substr(-2); + + } else if(args.style == 10) { // mm-dd-yy + val = ("0"+(t.getMonth()+1)).substr(-2)+'-'+("0"+t.getDate()).substr(-2)+'-'+("0"+t.getYear()).substr(-2); + } else if(args.style == 11) { // yy/mm/dd + val = ("0"+t.getYear()).substr(-2)+'/'+("0"+(t.getMonth()+1)).substr(-2)+'/'+("0"+t.getDate()).substr(-2); + } else if(args.style == 12) { // yymmdd + val = ("0"+t.getYear()).substr(-2)+("0"+(t.getMonth()+1)).substr(-2)+("0"+t.getDate()).substr(-2); + + + } else if(args.style == 101) { // mm/dd/yy + val = ("0"+(t.getMonth()+1)).substr(-2)+'/'+("0"+t.getDate()).substr(-2)+'/'+t.getFullYear(); + } else if(args.style == 102) { // yy.mm.dd + val = t.getFullYear()+'.'+("0"+(t.getMonth()+1)).substr(-2)+'.'+("0"+t.getDate()).substr(-2); + } else if(args.style == 103) { // dd/mm/yy + val = ("0"+t.getDate()).substr(-2)+'/'+("0"+(t.getMonth()+1)).substr(-2)+'/'+t.getFullYear(); + } else if(args.style == 104) { // dd.mm.yy + val = ("0"+t.getDate()).substr(-2)+'.'+("0"+(t.getMonth()+1)).substr(-2)+'.'+t.getFullYear(); + } else if(args.style == 105) { // dd-mm-yy + val = ("0"+t.getDate()).substr(-2)+'-'+("0"+(t.getMonth()+1)).substr(-2)+'-'+t.getFullYear(); + } else if(args.style == 106) { // dd mon yy + val = ("0"+t.getDate()).substr(-2)+' '+t.toString().substr(4,3).toLowerCase()+' '+t.getFullYear(); + } else if(args.style == 107) { // Mon dd,yy + val = t.toString().substr(4,3)+' '+("0"+t.getDate()).substr(-2)+','+t.getFullYear(); + } else if(args.style == 108) { // hh:mm:ss + val = ("0"+t.getHours()).substr(-2)+':'+("0"+(t.getMinutes()+1)).substr(-2)+':'+("0"+t.getSeconds()).substr(-2); + + } else if(args.style == 110) { // mm-dd-yy + val = ("0"+(t.getMonth()+1)).substr(-2)+'-'+("0"+t.getDate()).substr(-2)+'-'+t.getFullYear(); + } else if(args.style == 111) { // yy/mm/dd + val = t.getFullYear()+'/'+("0"+(t.getMonth()+1)).substr(-2)+'/'+("0"+t.getDate()).substr(-2); + } else if(args.style == 112) { // yymmdd + val = t.getFullYear()+("0"+(t.getMonth()+1)).substr(-2)+("0"+t.getDate()).substr(-2); + } else { + throw new Error('The CONVERT style '+args.style+' is not realized yet.'); + } + }; + + if(args.dbtypeid == 'Date') { + return new Date(val); + } else if(args.dbtypeid.toUpperCase() == '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(args.dbtypeid == 'DATETIME') { + 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()).substr(-3) + return s; + } else if(args.dbtypeid.toUpperCase() == 'STRING') { + return ""+val; + } else if(args.dbtypeid.toUpperCase() == 'NUMBER' || args.dbtypeid == 'FLOAT') { + return +val; + } else if(args.dbtypeid.toUpperCase() == 'MONEY') { + var m = +val; + return (m|0)+((m*100)%100)/100; + } else if(args.dbtypeid.toUpperCase() == 'BOOLEAN') { + return !!val; + } else if(args.dbtypeid.toUpperCase() == 'INT') { + return val|0; + } else if(args.dbtypeid.toUpperCase() == 'VARCHAR' || args.dbtypeid == 'NVARCHAR') { + if(args.dbsize) return (""+val).substr(0,args.dbsize); + else return ""+val; + } else if(args.dbtypeid.toUpperCase() == 'CHAR' || args.dbtypeid == 'NCHAR') { + return (val+(new Array(args.dbsize+1).join(" "))).substr(0,args.dbsize); + //else return ""+val.substr(0,1); + } +}; + + + +/* +// +// CREATE TABLE for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +yy.ColumnDef = function (params) { return yy.extend(this, params); } +yy.ColumnDef.prototype.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; +} + +yy.CreateTable = function (params) { return yy.extend(this, params); } +yy.CreateTable.prototype.toString = function() { + var s = K('CREATE'); + if(this.temporary) s+=' '+K('TEMPORARY'); + if(this.view) s += ' '+K('VIEW'); + else s += ' '+K('TABLE'); + if(this.ifnotexists) s += ' '+K('IF')+' '+K('NOT')+' '+K('EXISTS'); + s += ' '+this.table.toString(); + if(this.viewcolumns) { + s += '('+this.viewcolumns.map(function(vcol){ + return vcol.toString(); + }).join(',')+')'; + } + if(this.as) s += ' '+K('AS')+' '+L(this.as); + else { + var ss = this.columns.map(function(col){ + return col.toString(); + }); + s += ' ('+NL()+ID()+ss.join(','+NL()+ID())+')'; + }; + if(this.view && this.select) { + s += ' AS '+this.select.toString(); + } + return s; +} + +// CREATE TABLE +//yy.CreateTable.prototype.compile = returnUndefined; +yy.CreateTable.prototype.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||[]; +// console.log(this); + + // IF NOT EXISTS + if(this.ifnotexists && db.tables[tableid]) return 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? + + var ss = []; + if(this.columns) { + this.columns.forEach(function(col) { + var dbtypeid = col.dbtypeid; + if(!alasql.fn[dbtypeid]) dbtypeid = dbtypeid.toUpperCase(); + var newcol = { + columnid: col.columnid, + dbtypeid: dbtypeid // TODO: Add types table + }; + + if(col.default) { + ss.push('\''+col.columnid+'\':'+col.default.toJavaScript()); + } + + table.columns.push(newcol); + table.xcolumns[newcol.columnid] = newcol; + + // 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",'return '+pk.onrightfns); + pk.hh = hash(pk.onrightfns); + table.indices[pk.hh] = {}; + }; + + }); + }; + table.defaultfns = ss.join(','); + + +// if(constraints) { + constraints.forEach(function(con) { + //console.log(con, con.columns); + 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",'return '+pk.onrightfns); + pk.hh = hash(pk.onrightfns); + table.indices[pk.hh] = {}; + } + }); + + if(this.view && this.viewcolumns) { + var self = this; + this.viewcolumns.forEach(function(vcol,idx){ + self.select.columns[idx].as = vcol.columnid; + }); + } + +// console.log(100,db.engineid); + if(db.engineid) { +// console.log(101,db.engineid); + return alasql.engines[db.engineid].createTable(this.table.databaseid || databaseid, tableid, this.ifnotexists, cb); +// console.log('createtable',res1); +// return res1; + } + +// } +// if(table.pk) { + table.insert = function(r) { + if(this.pk) { + var pk = this.pk; + var addr = pk.onrightfn(r); + if(typeof this.indices[pk.hh][addr] != 'undefined') { + throw new Error('Cannot insert record, because it already exists in primary key'); + } else { + table.data.push(r); + this.indices[pk.hh][addr]=r; + }; + } else { + table.data.push(r); + } + }; + + table.delete = function(i) { + if(this.pk) { + var r = this.data[i]; + var pk = this.pk; + var addr = pk.onrightfn(r); + if(typeof this.indices[pk.hh][addr] == 'undefined') { + throw new Error('Something wrong with index on table'); + } else { + this.indices[pk.hh][addr]=undefined; + }; + } + }; + + table.deleteall = function() { + this.data.length = 0; + if(this.pk) { +// var r = this.data[i]; + this.indices[this.pk.hh] = {}; + } + }; + + table.update = function(assignfn, i, params) { + if(this.pk) { + var r = this.data[i]; + var pk = this.pk; + var addr = pk.onrightfn(r,params); + if(typeof this.indices[pk.hh][addr] == 'undefined') { + throw new Error('Something wrong with index on table'); + } else { + this.indices[pk.hh][addr]=undefined; + assignfn(r,params,alasql); + var newaddr = pk.onrightfn(r); + if(typeof this.indices[pk.hh][newaddr] != 'undefined') { + throw new Error('Record already exists'); + } else { + this.indices[pk.hh][newaddr] = r; + } + } + + } else { + assignfn(this.data[i],params,alasql); + }; + + }; + + if(this.view && this.select) { + table.view = true; +// console.log(this.select.toString()); +// console.log('this.table.databaseid',this.table.databaseid); +// console.log(this.select.compile(this.table.databaseid||databaseid)); + table.select = this.select.compile(this.table.databaseid||databaseid); + } +// console.log(databaseid); +// console.log(db.databaseid,db.tables); +// console.log(table); + if(cb) cb(1); + + return 1; +}; + + + + +// +// Date functions +// +// (c) 2014, Andrey Gershun +// + +/** Standard JavaScript data types */ + +alasql.fn.Date = Object; +alasql.fn.Date = Date; +alasql.fn.Number = Number; +alasql.fn.String = String; +alasql.fn.Boolean = Boolean; + +/** Extend Object with properties */ +stdfn.EXTEND = alasql.utils.extend; + + +stdfn.CHAR = String.fromCharCode.bind(String); +stdfn.ASCII = function(a) { + return a.charCodeAt(0); +}; + +/** + Return first non-null argument + See https://msdn.microsoft.com/en-us/library/ms190349.aspx +*/ +stdfn.COALESCE = function() { + for(var i=0;i 0) { + for(var i=0, ilen=table.data.length; i 0) { + for(var i=0, ilen=table.data.length; i=0) { + q += "+"+values[idx].toJavaScript(); + } else if (alasql.fn[table.xcolumns[col.columnid].dbtypeid]) { + q += "(new "+table.xcolumns[col.columnid].dbtypeid+"("; + q += values[idx].toJavaScript(); + q += "))"; + } else { + q += values[idx].toJavaScript(); + }; + } else { + q += values[idx].toJavaScript(); + } + ss.push(q); + + }); + } else { +// var table = db.tables[tableid]; +// console.log('table1', db, self); +//console.log(111, table.columns); +//console.log(74,table); + if((values instanceof Array) && table.columns && table.columns.length > 0) { + table.columns.forEach(function(col, idx){ + + var q = '\''+col.columnid +'\':'; +// var val = values[idx].toJavaScript(); + + if(["INT","FLOAT","NUMBER","MONEY"].indexOf(col.dbtypeid) >=0) { + q += "+"+values[idx].toJavaScript(); + } else if (alasql.fn[col.dbtypeid]) { + q += "(new "+col.dbtypeid+"("; + q += values[idx].toJavaScript(); + q += "))"; + } else { + q += values[idx].toJavaScript(); + } + + // if(table.xcolumns && table.xcolumns[col.columnid] && + // (table.xcolumns[col.columnid].dbtypeid == "DATE" || + // table.xcolumns[col.columnid].dbtypeid == "DATETIME" + // )) { + // val = "(new Date("+val+"))"; + // } + // || table.xcolumns[col.columnid].dbtypeid == "FLOAT" + // || table.xcolumns[col.columnid].dbtypeid == "NUMBER" + // || table.xcolumns[col.columnid].dbtypeid == "MONEY" + // )) q += '+'; + // console.log(self.values[idx].toString()); + //console.log(self); +// q += val; + + // if(table.xcolumns && table.xcolumns[col.columnid] && table.xcolumns[col.columnid].dbtypeid == "INT") q += '|0'; + ss.push(q); + + // console.log(fld); + // TODO: type checking and conversions + // rec[fld.fldid] = eval(self.insertExpression[idx].toJavaScript('','')); + // console.log(rec[fld.fldid]); + // if(rec[fld.fldid] == "NULL") rec[fld.fldid] = undefined; + + // if(table.xflds[fld.fldid].dbtypeid == "INT") rec[fld.fldid] = +rec[fld.fldid]|0; + // else if(table.xflds[fld.fldid].dbtypeid == "FLOAT" || table.xflds[fld.fldid].dbtypeid == "MONEY" ) + // rec[fld.fldid] = +rec[fld.fldid]; + }); + } else { +// console.log(222,values); +// sw = 'var w='+JSONtoJavaScript(values)+';for(var k in w){r[k]=w[k]};'; + sw = JSONtoJavaScript(values); + } + } +//console.log(ss); + + if(db.tables[tableid].defaultfns) ss.unshift(db.tables[tableid].defaultfns); + if(sw) { + s += 'a='+sw+';'; + } else { + s += 'a={'+ss.join(',')+'};'; + } +// s += 'db.tables[\''+tableid+'\'].insert(r);'; + if(db.tables[tableid].insert) { + s += 'alasql.databases[\''+databaseid+'\'].tables[\''+tableid+'\'].insert(a);'; + } else { + s += 'aa.push(a);'; + } + }); + + s33 = s3+s; + + if(db.tables[tableid].insert) { +// s += 'alasql.databases[\''+databaseid+'\'].tables[\''+tableid+'\'].insert(r);'; + } else { + s += 'alasql.databases[\''+databaseid+'\'].tables[\''+tableid+'\'].data='+ + 'alasql.databases[\''+databaseid+'\'].tables[\''+tableid+'\'].data.concat(aa);'; + } + + s += 'return '+self.values.length; + +//console.log(s); + var insertfn = new Function('db, params, alasql',s3+s); + +// INSERT INTO table SELECT + + } else if(this.select) { + 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,null, cb); + return res; + }; + return statement; + } else { + var insertfn = function(db, params, alasql) { + var res = selectfn(params); + if(db.tables[tableid].insert) { + // If insert() function exists (issue #92) + for(var i=0,ilen=res.length;i 0) { + s += '('+this.args.map(function(arg){ return arg.toString()}).join(', ')+')'; + } + if(this.as) s += ' '+K('AS')+' '+L(this.as); + return s; +} +//yy.CreateDatabase.prototype.compile = returnUndefined; +yy.CreateDatabase.prototype.execute = function (databaseid, params, cb) { + // console.log(alasql.useid, databaseid, this.databaseid); + // console.trace(); + var args; + if(this.args && this.args.length > 0) { + args = this.args.map(function(arg){ + return new Function('params','return '+arg.toJavaScript())(params); + }); + }; + 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; + } +}; + +// CREATE DATABASE databaseid +yy.AttachDatabase = function (params) { return yy.extend(this, params); }; +yy.AttachDatabase.prototype.toString = function() { + var s = K('ATTACH'); + if(this.engineid) s += ' '+L(this.engineid); + s += ' '+K('DATABASE')+' '+L(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+= ' '+K('AS')+' '+L(this.as); + return s; +} +//yy.CreateDatabase.prototype.compile = returnUndefined; +yy.AttachDatabase.prototype.execute = function (databaseid, params, cb) { + // console.log(alasql.useid, databaseid, this.databaseid); + // console.trace(); + 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 = K('DETACH'); + s += ' '+K('DATABASE')+' '+L(this.databaseid); + return s; +} +//yy.CreateDatabase.prototype.compile = returnUndefined; +yy.DetachDatabase.prototype.execute = function (databaseid, params, cb) { + // console.log(alasql.useid, databaseid, this.databaseid); + // console.trace(); + 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"); + } +// console.log(dbid); + 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; +}; + +// USE DATABSE databaseid +// USE databaseid +yy.UseDatabase = function (params) { return yy.extend(this, params); }; +yy.UseDatabase.prototype.toString = function() { + return K('USE') +' '+K('DATABASE')+' '+L(this.databaseid); +} +//yy.UseDatabase.prototype.compile = returnUndefined; +yy.UseDatabase.prototype.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; +}; + +// DROP DATABASE databaseid +yy.DropDatabase = function (params) { return yy.extend(this, params); } +yy.DropDatabase.prototype.toString = function() { + var s = K('DROP'); + if(this.ifexists) s += ' '+K('IF')+' '+K('EXISTS'); + s += ' '+K('DATABASE')+' '+L(this.databaseid); + return s; +} +//yy.DropDatabase.prototype.compile = returnUndefined; +yy.DropDatabase.prototype.execute = function (databaseid, params, cb) { + if(this.engineid) { + +// console.log(this,this.databaseid, this.ifexists); + 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"); + } +// console.log(dbid); + 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; +}; + + + + + + + +/* +// +// SET for Alasql.js +// Date: 01.12.2014 +// (c) 2014, Andrey Gershun +// +*/ + +yy.Declare = function (params) { return yy.extend(this, params); } +yy.Declare.prototype.toString = function() { + var s = K('DECLARE')+' '; + if(this.declares && this.declares.length > 0) { + s = this.declares.map(function(declare){ + var s = ''; + s += '@'+L(declare.variable)+' '; + s += declare.dbtypeid; + if(this.dbsize) s += '('+N(this.dbsize); + if(this.dbprecision) s+= ','+N(this.dbprecision); + s += ')'; + if(declare.expression) s += ' = '+declare.expression.toString(); + return s; + }).join(','); + } + return s; +} + +yy.Declare.prototype.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) { + // console.log(this.expression.toJavaScript('','', null)); + alasql.vars[declare.variable] = new Function("params,alasql","return " + +declare.expression.toJavaScript('','', 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; +}; + + + +/* +// +// SHOW for Alasql.js +// Date: 19.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +yy.ShowDatabases = function (params) { return yy.extend(this, params); } +yy.ShowDatabases.prototype.toString = function() { + var s = K('SHOW')+' '+K('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) { + res = res.filter(function(d){ + return d.databaseid.match(new RegExp((self.like.value).replace(/\%/g,'.*'),'g')); + }); + } + if(cb) cb(res); + return res; + }; + +}; + + +yy.ShowTables = function (params) { return yy.extend(this, params); } +yy.ShowTables.prototype.toString = function() { + var s = K('SHOW')+' '+K('TABLES'); + if(this.databaseid) s += ' FROM '+this.databaseid; + if(this.like) s += ' '+K('LIKE')+' '+this.like.toString(); + return s; +} +yy.ShowTables.prototype.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,'.*'),'g')); + }); + }; + if(cb) cb(res); + return res; +}; + +yy.ShowColumns = function (params) { return yy.extend(this, params); } +yy.ShowColumns.prototype.toString = function() { + var s = K('SHOW')+' '+K('COLUMNS'); + if(this.table.tableid) s += ' '+K('FROM')+' '+this.table.tableid; + if(this.databaseid) s += ' '+K('FROM')+' '+this.databaseid; + return s; +}; + +yy.ShowColumns.prototype.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 []; + } +}; + +yy.ShowIndex = function (params) { return yy.extend(this, params); } +yy.ShowIndex.prototype.toString = function() { + var s = K('SHOW')+' '+K('INDEX'); + if(this.table.tableid) s += ' '+K('FROM')+' '+this.table.tableid; + if(this.databaseid) s += ' '+K('FROM')+' '+this.databaseid; + return s; +} +yy.ShowIndex.prototype.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; +}; + +yy.ShowCreateTable = function (params) { return yy.extend(this, params); } +yy.ShowCreateTable.prototype.toString = function() { + var s = K('SHOW')+' '+K('CREATE')+' '+K('TABLE')+' '+L(this.table.tableid); + if(this.databaseid) s += ' '+K('FROM')+' '+L(this.databaseid); + return s; +} +yy.ShowCreateTable.prototype.execute = function (databaseid) { + var db = alasql.databases[this.databaseid || databaseid]; + var table = db.tables[this.table.tableid]; + var self = this; + if(table) { + var s = K('CREATE')+' '+K('TABLE')+' '+L(this.table.tableid)+' ('; + var ss = []; + if(table.columns) { + table.columns.forEach(function(col){ + var a = L(col.columnid)+' '+K(col.dbtypeid); + if(col.dbsize) a += '('+N(col.dbsize)+')'; + if(col.primarykey) a += ' '+K('PRIMARY')+' '+K('KEY'); + // TODO extend + ss.push(a); + }); + s += ss.join(', '); + }; + s += ')'; + return s; + } else { + throw new Error('There is no such table "'+this.table.tableid+'"'); + } +}; + + +/* +// +// SET for Alasql.js +// Date: 01.12.2014 +// (c) 2014, Andrey Gershun +// +*/ + +yy.SetVariable = function (params) { return yy.extend(this, params); } +yy.SetVariable.prototype.toString = function() { + var s = K('SET')+' '; + if(typeof this.value != 'undefined') s += K(this.variable.toUpperCase())+' '+(this.value?'ON':'OFF'); + if(this.expression) s += '@' + L(this.variable)+' = '+this.expression.toString(); + return s; +} + +yy.SetVariable.prototype.execute = function (databaseid,params,cb) { +// console.log(this); + 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) { +// console.log(this.expression.toJavaScript('','', null)); + var res = new Function("params,alasql","return " + +this.expression.toJavaScript('','', null))(params,alasql); + if(alasql.declares[this.variable]) { + res = alasql.stdfn.CONVERT(res,alasql.declares[this.variable]); + } + if(this.props && this.props.length > 0) { + var fs = 'alasql.vars[\''+this.variable+'\']'; + fs += this.props.map(function(prop){ + if(typeof prop == 'string') { + return '[\''+prop+'\']'; + } else if(typeof prop == 'number') { + return '['+prop+']'; + } else { + // console.log('prop:',prop, prop.toJavaScript()); + return '['+prop.toJavaScript()+']'; +// } else { +// console.log(prop, typeof ); +// throw new Error('Wrong SET property'); + } + }).join(); +// console.log(fs); + new Function("value,alasql",fs +'=value')(res,alasql); + } else { + alasql.vars[this.variable] = res; + } + } + var res = 1; + if(cb) res=cb(res); + return res; +}; + + + +// Console functions +/* +alasql.con = { + results:{} +}; + +alasql.con.open = function(el) { + // For browser only + if (typeof exports === 'object') return; + + // Find parent element + el = el || document.getElementById('alasql-con') || document.getElementsByTagName('body'); + if(!el) {throw new Error('Cannot fid element for console.')} + + var conel = document.createElement('div'); + conel.style.width = "1000px"; + conel.style.height = "320px"; + + alasql.con.conel = conel; + + var lenta = document.createElement('div'); + lenta.style.width = "1000px"; + lenta.style.height = "200px"; + lenta.style.overflow = "scroll"; + alasql.con.lenta = lenta; + + var inpel = document.createElement('div'); + inpel.style.width = "1000px"; + inpel.style.height = "100px"; + inpel.style.contentEditable = true; + inpel.innerHTML = 'command '; + alasql.con.inpel = inpel; + + conel.appendChild(lenta); + conel.appendChild(inpel); + el.appendChild(conel); +}; + +alasql.con.clear = function() { + // For browser only + if (typeof exports === 'object') return; + + alasql.con.conel.innerHTML = ''; +}; + +alasql.con.close = function() { + // For browser only + if (typeof exports === 'object') return; + + alasql.con.conel.removeChild(alasql.con.lenta); + alasql.con.conel.removeChild(alasql.con.inel); + alasql.con.conel.parentElement.removeChild(conel); +}; + +alasql.con.log = function() { + // For browser only + if (typeof exports === 'object') { + console.log.bind(console).apply(this, arguments); + } else { + var s = '

'; + s += Array.prototype.slice.call(arguments, 0).map(function(arg){ + return arg.toString(); + }).join(' '); + s += '
'; + alasql.con.conel.innerHTML += s; + }; + +}; +*/ +alasql.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',sql); + + if(res instanceof Array) { + if(console.table) { + // For Chrome and other consoles + console.table(res); + } else { + // Add print procedure + console.log(JSONtoString(res)); + } + } else { + console.log(JSONtoString(res)); + } -/* -// -// ROLLUP(), CUBE(), GROUPING SETS() for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -/** - Calculate ROLLUP() combination - */ - -var rollup = function (a,query) { - var rr = []; - var mask = 0; - var glen = a.length; - for(var g=0;g'+gv[t]+'<',gv[t]=='',typeof gv[t]); -// console.log(gv[t].toString()); -//console.log('+++'); - res = res.map(function(r){ - query.groupColumns[escapeq(gv[t].toString())] = escapeq(gv[t].toString()); - return r.concat(escapeq(gv[t].toString()) - +'\t' - +gv[t].toJavaScript('p',query.sources[0].alias,query.defcols)) - }); -// res = res.concat(gv[t]); - }; - - // switch(gv[t].t) { - // case 'plain': - // res = res.map(function(r){return r.concat(gv[t].p)}); - - // break; - // case 'rollup': res = cartes(res,rollup(gv[t].p)); break; - // case 'cube': res = cartes(res,cube(gv[t].p)); break; - // case 'groupingsets': res = cartes(res,groupingsets(gv[t].p)); break; - // default: res = res.concat(gv[t]); - // } - }; - return res; - } else if(gv instanceof yy.FuncValue) { -// console.log(gv); - query.groupColumns[escapeq(gv.toString())] = escapeq(gv.toString()); - return [gv.toString()+'\t'+gv.toJavaScript('p',query.sources[0].alias,query.defcols)]; - } else if(gv instanceof yy.Column) { - gv.nick = escapeq(gv.columnid); - query.groupColumns[gv.nick] = gv.nick; - return [gv.nick+'\t'+gv.toJavaScript('p',query.sources[0].alias,query.defcols)]; // Is this ever happened? - // } else if(gv instanceof yy.Expression) { - // return [gv.columnid]; // Is this ever happened? - } else { - query.groupColumns[escapeq(gv.toString())] = escapeq(gv.toString()); - return [escapeq(gv.toString())+'\t'+gv.toJavaScript('p',query.sources[0].alias,query.defcols)]; -// throw new Error('Single argument in the group without array'); - }; - - - // switch(gv.t) { - // case 'plain': return gv.p; break; - // case 'rollup': return rollup(gv.p); break; - // case 'cube': return cube(gv.p); break; - // case 'groupingsets': return groupingsets(gv.p); break; - // default: return [gv];//return decartes(gv.p); - // } - // return gv; -}; - - - - -/* -// -// Select run-time part for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.Select.prototype.compileDefCols = function(query, databaseid) { -// console.log('defcols'); - var defcols = {}; - if(this.from) { - this.from.forEach(function(fr){ - if(fr instanceof yy.Table) { - var alias = fr.as || fr.tableid; -// console.log(alasql.databases[fr.databaseid || databaseid]); -// console.log(alasql.databases[fr.databaseid || databaseid].tables, fr.tableid); -//console.log(alasql.databases[fr.databaseid || databaseid].tables, fr.tableid); -//console.log(alasql.databases); - var table = alasql.databases[fr.databaseid || databaseid].tables[fr.tableid]; -//console.log(table); - 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.ParamValue) { - - } else if(fr instanceof yy.VarValue) { - - } else if(fr instanceof yy.FuncValue) { - - } else if(fr instanceof yy.FromData) { - - } else { - throw new Error('Unknown type of FROM clause'); - }; - }); - }; - - if(this.joins) { - this.joins.forEach(function(jn){ -// console.log(jn); - 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]; -// console.log(jn.table.tableid, jn.table.databaseid); - 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; - // } -// console.log(defcols); - return defcols; -} - -/* -// -// UNION for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -// SELECT UNION statement - -yy.Union = function (params) { return yy.extend(this, params); } -yy.Union.prototype.toString = function () { - return K('UNION'); -}; - -yy.Union.prototype.compile = function (tableid) { - return null; -}; - -/* -// -// CROSS AND OUTER APPLY for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.Apply = function (params) { return yy.extend(this, params); } -yy.Apply.prototype.toString = function () { - var s = K(this.applymode)+' '+K('APPLY')+' ('; - s += this.select.toString()+')'; - if(this.as) s += ' '+K('AS')+' '+L(this.as); - return s; -}; - - - -/* -// -// CROSS AND OUTER APPLY for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.Over = function (params) { return yy.extend(this, params); } -yy.Over.prototype.toString = function () { - var s = K('OVER')+' ('; - if(this.partition) { - s += K('PARTITION')+' '+K('BY')+' '+this.partition.toString(); - if(this.order) s+=' '; - } - if(this.order) { - s += K('ORDER')+' '+K('BY')+' '+this.order.toString(); - } - s += ')'; - return s; -}; - - - -/* -// -// Expressions for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.ExpressionStatement = function(params) { return yy.extend(this, params); }; -yy.ExpressionStatement.prototype.toString = function() { - return this.expression.toString(); -}; - -yy.ExpressionStatement.prototype.execute = function (databaseid, params, cb) { - if(this.expression) { -// console.log(this.expression.toJavaScript('','', null)); -// console.log(this.expression.toJavaScript('','', null)); - var expr = new Function("params,alasql,p",'return '+this.expression.toJavaScript('','', null)); - var res = expr(params,alasql); - if(cb) res = cb(res); - return res; - } -} - -yy.Expression = function(params) { return yy.extend(this, params); }; -yy.Expression.prototype.toString = function() { - var s = this.expression.toString(); - if(this.order) s += ' '+this.order.toString(); - if(this.nocase) s += ' '+K('COLLATE')+' '+K('NOCASE'); - return s; -}; -yy.Expression.prototype.findAggregator = function (query){ - if(this.expression.findAggregator) this.expression.findAggregator(query); -}; - -yy.Expression.prototype.toJavaScript = function(context, tableid, defcols) { -// console.log('Expression',this); - if(this.expression.reduced) return 'true'; - return this.expression.toJavaScript(context, tableid, defcols); -}; -yy.Expression.prototype.compile = function(context, tableid, defcols){ -// console.log('Expression',this); - if(this.reduced) return returnTrue(); - return new Function('p','return '+this.toJavaScript(context, tableid, defcols)); -}; - - -yy.JavaScript = function(params) { return yy.extend(this, params); }; -yy.JavaScript.prototype.toString = function() { - var s = '``'+this.value+'``'; - return s; -}; - -yy.JavaScript.prototype.toJavaScript = function(context, tableid, defcols) { -// console.log('Expression',this); - return '('+this.value+')'; -}; -yy.JavaScript.prototype.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; -} - - -yy.Literal = function (params) { return yy.extend(this, params); } -yy.Literal.prototype.toString = function() { - var s = this.value; - if(this.value1) s = this.value1+'.'+s; -// else s = tableid+'.'+s; - return L(s); -} - - -yy.Join = function (params) { return yy.extend(this, params); } -yy.Join.prototype.toString = function() { - var s = NL()+ID(); - if(this.joinmode) s += K(this.joinmode)+' '; - s += K('JOIN')+this.table.toString(); - return s; -} - -//yy.Join.prototype.toJavaScript = function(context, tableid) { -// return 'JOIN'+this.table.toString(); -//} - - -yy.Table = function (params) { return yy.extend(this, params); } -yy.Table.prototype.toString = function() { - var s = this.tableid; -// if(this.joinmode) - if(this.databaseid) s = this.databaseid+'.'+s; - return L(s); -}; - - -yy.View = function (params) { return yy.extend(this, params); } -yy.View.prototype.toString = function() { - var s = this.viewid; -// if(this.joinmode) - if(this.databaseid) s = this.databaseid+'.'+s; - return L(s); -}; - - -yy.Op = function (params) { return yy.extend(this, params); } -yy.Op.prototype.toString = function() { - if(this.op == 'IN' || this.op == 'NOT IN') { - return this.left.toString()+" "+P(this.op)+" ("+this.right.toString()+")"; - } - if(this.allsome) { - return this.left.toString()+" "+P(this.op)+" "+this.allsome+' ('+this.right.toString()+')'; - } - if(this.op == '->') { - var s = this.left.toString()+"->"; -// console.log(this.right); - 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()+" "+P(this.op)+" "+(this.allsome?this.allsome+' ':'')+this.right.toString(); -}; - -yy.Op.prototype.findAggregator = function (query){ -// console.log(this.toString()); - 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); - } -}; - -yy.Op.prototype.toType = function(tableid) { - if(['-','*','/','%','^'].indexOf(this.op) >-1) return 'number'; - 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'].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'; -}; - -yy.Op.prototype.toJavaScript = function(context,tableid,defcols) { -// console.log(this); - var op = this.op; - if(this.op == '=') op = '==='; - else if(this.op == '<>') op = '!='; - else if(this.op == 'OR') op = '||'; - - if(this.op == '->') { -// console.log(this.right, typeof this.right); - if(typeof this.right == "string") { - return this.left.toJavaScript(context,tableid, defcols)+'["'+this.right+'"]'; - } else if(typeof this.right == "number") { - return this.left.toJavaScript(context,tableid, defcols)+'['+this.right+']'; - } else if(this.right instanceof yy.FuncValue) { - ss = []; - if(!this.right.args || this.right.args.length == 0) { - } else { - var ss = this.right.args.map(function(arg){ - return arg.toJavaScript(context,tableid, defcols); - }); - } - return this.left.toJavaScript(context,tableid, defcols)+'[\''+this.right.funcid+'\']('+ - ss.join(',')+')'; - } else { - return this.left.toJavaScript(context,tableid, defcols)+'['+this.right.toJavaScript(context,tableid, defcols)+']'; - } - } - - if(this.op == 'IS') { - return '((typeof '+this.left.toJavaScript(context,tableid, defcols)+"=='undefined') == " - + '(typeof '+this.right.toJavaScript(context,tableid, defcols)+"=='undefined'))"; - } - - - if(this.op == '==') { - return 'alasql.utils.deepEqual('+this.left.toJavaScript(context,tableid, defcols)+","+this.right.toJavaScript(context,tableid, defcols)+')'; - } - if(this.op == '===') { - return "(("+this.left.toJavaScript(context,tableid, defcols)+").valueOf()===("+this.right.toJavaScript(context,tableid, defcols)+'.valueOf()))'; - } - - if(this.op == '!===') { - return "!(("+this.left.toJavaScript(context,tableid, defcols)+").valueOf()===("+this.right.toJavaScript(context,tableid, defcols)+'.valueOf()))'; - } - - - if(this.op == '!==') { - return '(!alasql.utils.deepEqual('+this.left.toJavaScript(context,tableid, defcols)+","+this.right.toJavaScript(context,tableid, defcols)+'))'; - } - - if(this.op == 'LIKE') { - var s = "("+this.left.toJavaScript(context,tableid, defcols)+"+'')"+ - ".toUpperCase().match(new RegExp('^'+("+this.right.toJavaScript(context,tableid, defcols)+").replace(/\\\%/g,'.*').toUpperCase()+'$','g'))" -// console.log(s); - return s; - }; - - if(this.op == 'NOT LIKE') { - var s = "!(("+this.left.toJavaScript(context,tableid, defcols)+"+'')"+ - ".toUpperCase().match(new RegExp('^'+("+this.right.toJavaScript(context,tableid, defcols)+").replace(/\\\%/g,'.*').toUpperCase()+'$','g')))" - return s; - }; - - if(this.op == 'BETWEEN') { - if(this.right instanceof yy.Op && this.right.op == 'AND') { - return '(('+this.right.left.toJavaScript(context,tableid, defcols)+'<='+this.left.toJavaScript(context,tableid, defcols)+')&&'+ - '('+this.left.toJavaScript(context,tableid, defcols)+'<='+this.right.right.toJavaScript(context,tableid, defcols)+'))'; - } else { - throw new Error('Wrong BETWEEN operator without AND part'); - } - }; - - if(this.op == 'NOT BETWEEN') { - if(this.right instanceof yy.Op && this.right.op == 'AND') { - return '!(('+this.right.left.toJavaScript(context,tableid, defcols)+'<='+this.left.toJavaScript(context,tableid, defcols)+')&&'+ - '('+this.left.toJavaScript(context,tableid, defcols)+'<='+this.right.right.toJavaScript(context,tableid, defcols)+'))'; - } else { - throw new Error('Wrong NOT BETWEEN operator without AND part'); - } - }; - - if(this.op == 'IN') { - if(this.right instanceof yy.Select ) { - var s = '('; -// s += 'this.query.queriesdata['+this.queriesidx+']'; - s += 'alasql.utils.flatArray(this.query.queriesfn['+(this.queriesidx)+'](params,null,p))'; - s += '.indexOf('; - s += this.left.toJavaScript(context,tableid, defcols)+')>-1)'; - return s; - } else if(this.right instanceof Array ) { -// if(this.right.length == 0) return 'false'; - var s = '(['+this.right.map(function(a){return a.toJavaScript(context,tableid, defcols)}).join(',')+'].indexOf('; - s += this.left.toJavaScript(context,tableid, defcols)+')>-1)'; -//console.log(s); - return s; - } else { - var s = '('+this.right.toJavaScript(context,tableid, defcols)+'.indexOf('; - s += this.left.toJavaScript(context,tableid, defcols)+')>-1)'; - return s; -// } else { -// throw new Error('Wrong IN operator without SELECT part'); - } - }; - - - if(this.op == 'NOT IN') { - if(this.right instanceof yy.Select ) { - var s = '(' - //this.query.queriesdata['+this.queriesidx+'] - s += 'alasql.utils.flatArray(this.query.queriesfn['+(this.queriesidx)+'](params,null,p))'; - s +='.indexOf('; - s += this.left.toJavaScript(context,tableid, defcols)+')<0)'; - return s; - } else if(this.right instanceof Array ) { -// if(this.right.length == 0) return 'true'; - var s = '(['+this.right.map(function(a){return a.toJavaScript(context,tableid, defcols)}).join(',')+'].indexOf('; - s += this.left.toJavaScript(context,tableid, defcols)+')<0)'; - return s; - } else { - throw new Error('Wrong NOT IN operator without SELECT part'); - } - }; - - if(this.allsome == 'ALL') { - if(this.right instanceof yy.Select ) { -// var s = 'this.query.queriesdata['+this.queriesidx+']'; - var s = 'alasql.utils.flatArray(this.query.queriesfn['+(this.queriesidx)+'](params,null,p))'; - - s +='.every(function(b){return ('; - s += this.left.toJavaScript(context,tableid, defcols)+')'+op+'b})'; - return s; - } else if(this.right instanceof Array ) { - var s = '['+this.right.map(function(a){return a.toJavaScript(context,tableid, defcols)}).join(',')+'].every(function(b){return ('; - s += this.left.toJavaScript(context,tableid, defcols)+')'+op+'b})'; - return s; - } else { - throw new Error('Wrong NOT IN operator without SELECT part'); - } - }; - - if(this.allsome == 'SOME' || this.allsome == 'ANY') { - if(this.right instanceof yy.Select ) { -// var s = 'this.query.queriesdata['+this.queriesidx+']'; - var s = 'alasql.utils.flatArray(this.query.queriesfn['+(this.queriesidx)+'](params,null,p))'; - s+='.some(function(b){return ('; - s += this.left.toJavaScript(context,tableid, defcols)+')'+op+'b})'; - return s; - } else if(this.right instanceof Array ) { - var s = '['+this.right.map(function(a){return a.toJavaScript(context,tableid, defcols)}).join(',')+'].some(function(b){return ('; - s += this.left.toJavaScript(context,tableid, defcols)+')'+op+'b})'; - return s; - } else { - throw new Error('Wrong NOT IN operator without SELECT part'); - } - }; - -// Special case for AND optimization (if reduced) - if(this.op == 'AND') { - if(this.left.reduced) { - if(this.right.reduced) { - return 'true'; - } else { - return this.right.toJavaScript(context,tableid, defcols); - } - } else if(this.right.reduced) { - return this.left.toJavaScript(context,tableid, defcols); - } - - // Otherwise process as regular operation (see below) - op = '&&'; - - } - - if(this.op == '^') { - return 'Math.pow('+this.left.toJavaScript(context,tableid, defcols) - +','+this.right.toJavaScript(context,tableid, defcols)+')'; - }; - - - // Change names -// console.log(this); - return '('+this.left.toJavaScript(context,tableid, defcols)+op+this.right.toJavaScript(context,tableid, defcols)+')'; -}; - - - -yy.VarValue = function (params) { return yy.extend(this, params); } -yy.VarValue.prototype.toString = function() { - return '@'+L(this.variable); -}; - -yy.VarValue.prototype.toType = function() { - return 'unknown'; -}; - -yy.VarValue.prototype.toJavaScript = function() { - return "alasql.vars['"+this.variable+"']"; -} - - -yy.NumValue = function (params) { return yy.extend(this, params); } -yy.NumValue.prototype.toString = function() { - return N(this.value.toString()); -}; - -yy.NumValue.prototype.toType = function() { - return 'number'; -}; - -yy.NumValue.prototype.toJavaScript = function() { - return ""+this.value; -} - - - - -yy.StringValue = function (params) { return yy.extend(this, params); } -yy.StringValue.prototype.toString = function() { - return "'"+S(this.value.toString())+"'"; -} - -yy.StringValue.prototype.toType = function() { - return 'string'; -} - -yy.StringValue.prototype.toJavaScript = function() { -// console.log("'"+doubleqq(this.value)+"'"); -// return "'"+doubleqq(this.value)+"'"; - return "'"+escapeq(this.value)+"'"; - -} - - -yy.LogicValue = function (params) { return yy.extend(this, params); } -yy.LogicValue.prototype.toString = function() { - return this.value?'TRUE':'FALSE'; -} - -yy.LogicValue.prototype.toType = function() { - return 'boolean'; -} - -yy.LogicValue.prototype.toJavaScript = function() { - return this.value?'true':'false'; -} - -yy.NullValue = function (params) { return yy.extend(this, params); } -yy.NullValue.prototype.toString = function() { - return 'NULL'; -} -yy.NullValue.prototype.toJavaScript = function() { - return 'undefined'; -} - -yy.ParamValue = function (params) { return yy.extend(this, params); } -yy.ParamValue.prototype.toString = function() { - return '$'+this.param; -} -yy.ParamValue.prototype.toJavaScript = function() { - if(typeof this.param == "string") return "params[\'"+this.param+"\']"; - else return "params["+this.param+"]"; -} - - - -yy.UniOp = function (params) { return yy.extend(this, params); } -yy.UniOp.prototype.toString = function() { - if(this.op == '-') return this.op+this.right.toString(); - if(this.op == '+') return this.op+this.right.toString(); - if(this.op == 'NOT') return this.op+'('+this.right.toString()+')'; - else if(this.op == null) return '('+this.right.toString()+')'; -}; - -yy.UniOp.prototype.findAggregator = function (query){ - if(this.right.findAggregator) this.right.findAggregator(query); -}; - -yy.UniOp.prototype.toType = function(tableid) { - if(this.op == '-') return 'number'; - if(this.op == '+') return 'number'; - if(this.op == 'NOT') return 'boolean'; -}; - -yy.UniOp.prototype.toJavaScript = function(context, tableid, defcols) { - if(this.op == '-') return "(-("+this.right.toJavaScript(context, tableid, defcols)+"))"; - if(this.op == '+') return "("+this.right.toJavaScript(context, tableid, defcols)+")"; - if(this.op == 'NOT') return '!('+this.right.toJavaScript(context, tableid, defcols)+')'; - else if(this.op == null) return '('+this.right.toJavaScript(context, tableid, defcols)+')'; -}; - - - -// yy.Star = function (params) { return yy.extend(this, params); } -// yy.Star.prototype.toString = function() { -// var s = this.fieldid; -// if(this.tableid) { -// s = this.tableid+'.'+s; -// if(this.databaseid) { -// s = this.databaseid+'.'+s; -// } -// } -// if(this.alias) s += ' AS '+this.alias; -// return s; -// } - -yy.Column = function(params) { return yy.extend(this, params); } -yy.Column.prototype.toString = function() { - var s; - if(this.columnid == +this.columnid) { - 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) s += ' AS '+this.alias; - return s; -}; - -yy.Column.prototype.toJavaScript = function(context, tableid, defcols) { -// var s = this.value; -// var s = this.columnid; -// if(this.tableid) { -// s = this.tableid+'.'+s; -// // if(this.databaseid) { -// // s = this.databaseid+'.'+s; -// // } -// } else { -// s = tableid+'.'+s; -// } -//console.log('yy.Column',this, tableid); -// console.log(392,this.columnid); - 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 != '_') { - 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 != '_') { - s = context+'[\''+(this.tableid || tableid) + '\'][\''+this.columnid+'\']'; - } else { - s = context+'[\''+(this.tableid || tableid) + '\']'; - }; - } - } else if(tableid == -1) { -// if(this.columnid != '') { - s = context+'[\''+this.columnid+'\']'; -// } else { -// s = context; -// } - } else { - if(this.columnid != '_') { - s = context+'[\''+(this.tableid || tableid) + '\'][\''+this.columnid+'\']'; - } else { - s = context+'[\''+(this.tableid || tableid) + '\']'; - } - } - } -// console.log(context,s); -// console.trace(new Error()); - return s; -} - - - - -yy.AggrValue = function(params){ return yy.extend(this, params); } -yy.AggrValue.prototype.toString = function() { - var s = ''; - if(this.aggregatorid == 'REDUCE') s += L(this.funcid)+'('; - else s += this.aggregatorid+'('; - if(this.distinct) s+= K('DISTINCT')+' '; - if(this.expression) s += this.expression.toString(); - s += ')'; - if(this.over) s += ' '+this.over.toString(); -// console.log(this.over); -// if(this.alias) s += ' AS '+this.alias; - return s; -}; -yy.AggrValue.prototype.findAggregator = function (query){ -// console.log('aggregator found',this.toString()); - -// var colas = this.as || this.toString(); - - var colas = escapeq(this.toString())+':'+query.selectGroup.length; -// console.log('findAgg',this); - - -/* var found = false; - for(var i=0;i-1) return 'number'; - if(['ARRAY'].indexOf(this.aggregatorid)>-1) return 'array'; - if(['FIRST','LAST' ].indexOf(this.aggregatorid)>-1) return this.expression.toType(); -} -yy.AggrValue.prototype.toJavaScript = function(context, tableid, defcols) { -// var s = 'alasql.functions.'+this.funcid+'('; -// if(this.expression) s += this.expression.toJavaScript(context, tableid); -// s += ')'; -// if(this.alias) s += ' AS '+this.alias; -// return s; -// var s = ''; -//if(this.as) console.log(499,this.as); -// var colas = this.as; - var colas = this.nick; - if(typeof colas == 'undefined') colas = this.toString(); - return 'g[\''+colas+'\']'; -} - - -yy.OrderExpression = function(params){ return yy.extend(this, params); } -yy.OrderExpression.prototype.toString = function() { - var s = this.expression.toString(); - if(this.order) s += ' '+this.order.toString(); - if(this.nocase) s += ' '+K('COLLATE')+' '+K('NOCASE'); - return s; -} - -yy.GroupExpression = function(params){ return yy.extend(this, params); } -yy.GroupExpression.prototype.toString = function() { - return this.type+'('+this.group.toString()+')'; -} - - -yy.ColumnDef = function (params) { return yy.extend(this, params); } -yy.ColumnDef.prototype.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; -} - - -// Alasql Linq library - -yy.FromData = function(params) { return yy.extend(this, params); }; -yy.FromData.prototype.toString = function() { - if(this.data) return K('DATA')+'('+((Math.random()*10e15)|0)+')'; - else return '?'; -}; -yy.FromData.prototype.toJavaScript = function(){ -// console.log('yy.FromData.prototype.toJavaScript'); -}; - -yy.Select.prototype.exec = function(params,cb) { - - if(this.preparams) params = this.preparams.concat(params); -// console.log(15,this.preparams); - - var databaseid = alasql.useid; - db = alasql.databases[databaseid]; - var sql = this.toString(); - var hh = hash(sql); -// console.log(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; -}; - -yy.Select.prototype.Select = function(){ - var self = this; - var agrs = []; - if(arguments.length > 1) { - args = Array.prototype.slice.call(arguments);; - } else if(arguments.length == 1) { - if(arguments[0] instanceof Array) { - 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 - } - }); - -// console.log(self instanceof yy.Select); - return self; -}; - -yy.Select.prototype.From = function(tableid){ - var self = this; - if(!self.from) self.from = []; - if(tableid instanceof Array) { - 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; -} - -yy.Select.prototype.OrderBy = function(){ - var self = this; - var agrs = []; - - self.order = []; - - if(arguments.length == 0) { -// self.order.push(new yy.OrderExpression({expression: new yy.Column({columnid:"_"}), direction:'ASC'})); - args = ["_"]; - } else if(arguments.length > 1) { - args = Array.prototype.slice.call(arguments);; - } else if(arguments.length == 1) { - if(arguments[0] instanceof Array) { - 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; -} - -yy.Select.prototype.Top = function(topnum){ - var self = this; - self.top = new yy.NumValue({value:topnum}); - return self; -}; - -yy.Select.prototype.GroupBy = function(){ - var self = this; - var agrs = []; - - if(arguments.length > 1) { - args = Array.prototype.slice.call(arguments);; - } else if(arguments.length == 1) { - if(arguments[0] instanceof Array) { - 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; -}; - -yy.Select.prototype.Where = function(expr){ - var self = this; - if(typeof expr == 'function' ) { - self.where = expr; - } - return self; -}; - - - -/* -// -// Functions for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.FuncValue = function(params){ return yy.extend(this, params); } -yy.FuncValue.prototype.toString = function() { - 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) s += ' AS '+this.as.toString(); -// if(this.alias) s += ' AS '+this.alias; - return s; -} - -yy.FuncValue.prototype.findAggregator = function(query) { - if(this.args && this.args.length > 0) { - this.args.forEach(function(arg){ - if(arg.findAggregator) arg.findAggregator(query); - }); - } -}; - -yy.FuncValue.prototype.toJavaScript = function(context, tableid, defcols) { - var s = ''; - var funcid = this.funcid; - // IF this is standard compile functions - if(alasql.fn[funcid]) { - // This is user-defined run-time function - // TODO arguments!!! -// var s = ''; - if(this.newid) s+= 'new '; - s += 'alasql.fn.'+this.funcid+'('; -// if(this.args) s += this.args.toJavaScript(context, tableid); - if(this.args && this.args.length > 0) { - s += this.args.map(function(arg){ - return arg.toJavaScript(context, tableid, defcols); - }).join(','); - }; - s += ')'; - } else if(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.toJavaScript(context, tableid)})); - } else { - s += alasql.stdlib[funcid.toUpperCase()](); - } - } else if(alasql.stdfn[funcid.toUpperCase()]) { - if(this.newid) s+= 'new '; - s += 'alasql.stdfn.'+this.funcid.toUpperCase()+'('; -// if(this.args) s += this.args.toJavaScript(context, tableid); - if(this.args && this.args.length > 0) { - s += this.args.map(function(arg){ - return arg.toJavaScript(context, tableid, defcols); - }).join(','); - }; - s += ')'; - } else { - // Aggregator - } -//console.log('userfn:',s,this); - -// if(this.alias) s += ' AS '+this.alias; - return s; -} - -// // Functions compiler -// nodes.FunctionValue.prototype.toJavaScript = function (context, tableid) { -// var s = ''; -// s += fns[this.name.toUpperCase()].apply(null,this.arguments.map(function(arg){ -// if(arg) return arg.toJavaScript(context, tableid); -// else return ''; -// })); -// return s; -// }; - -// -// SQL FUNCTIONS COMPILERS -// Based on SQLite functions - -// IMPORTANT: These are compiled functions - -//alasql.fn = {}; // Keep for compatibility -//alasql.userlib = alasql.fn; - -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+')'}; -stdlib.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'); - }; -}; -stdlib.IFNULL = function(a,b) {return '('+a+'||'+b+')'}; -stdlib.INSTR = function(s,p) {return '(('+s+').indexOf('+p+')+1)'}; - -stdlib.LEN = stdlib.LENGTH = function(s) {return '('+s+'+"").length';}; -//stdlib.LENGTH = function(s) {return '('+s+').length'}; - -stdlib.LOWER = stdlib.LCASE = function(s) {return '('+s+').toLowerCase()';} -//stdlib.LCASE = function(s) {return '('+s+').toLowerCase()';} - - -// LTRIM - -stdlib.GREATEST = function(){ - return 'Math.max('+Array.prototype.join.call(arguments, ',')+')' -}; - -stdlib.LEAST = function(){ - return 'Math.min('+Array.prototype.join.call(arguments, ',')+')' -}; - -stdlib.MID = function(a,b,c){ - if(arguments.length == 2) return '('+a+').substr('+b+'-1)'; - else if(arguments.length == 3) return '('+a+').substr('+b+'-1,'+c+')'; -}; - -stdlib.NULLIF = function(a,b){return '('+a+'=='+b+'?null:'+a+')'}; - -stdlib.POWER = function(a,b) {return 'Math.pow('+a+','+b+')'}; - -stdlib.RANDOM = function(r) { - if(arguments.length == 0) { - return 'Math.random()'; - } else { - return '(Math.random()*('+r+')|0)'; - } -} -stdlib.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+')'; - } -} -stdlib.SQRT = function(s) {return 'Math.sqrt('+s+')'}; - -stdlib.TRIM = function(s) {return s+'.trim()'}; - -stdlib.UPPER = stdlib.UCASE = function(s) {return '('+s+').toUpperCase()';} -//stdlib.UCASE = function(s) {return '('+s+').toUpperCase()';} -//REPLACE -// RTRIM -// SUBSTR -// TRIM -//REPLACE -// RTRIM -// SUBSTR -// TRIM - - -// Aggregator for joining strings -alasql.aggr.GROUP_CONCAT = function(v,s){ - if(typeof s == "undefined") return v; else return s+','+v; -}; - - - - -// -// -// SQL and JS DateTime functions -// -// - - - -/* -// -// CASE for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.CaseValue = function(params) { return yy.extend(this, params); }; -yy.CaseValue.prototype.toString = function() { - var s = 'CASE '; - if(this.expression) s += this.expression.toString(); - if(this.whens) { - s += this.whens.map(function(w) { return ' WHEN '+ - w.when.toString() + ' THEN '+w.then.toString()}).join(); - } - s += ' END'; - return s; -}; - -yy.CaseValue.prototype.findAggregator = function (query){ -// console.log(this.toString()); - if(this.expression && this.expression.findAggregator) this.expression.findAggregator(query); - if(this.whens && this.whens.length > 0) { - this.whens.forEach(function(w) { - if(w.when.findAggregator) w.when.findAggregator(query); - if(w.then.findAggregator) w.then.findAggregator(query); - }); - } -}; - -yy.CaseValue.prototype.toJavaScript = function(context, tableid, defcols) { - - var s = '(function('+context+',params,alasql){var r;'; - if(this.expression) { -// this.expression.toJavaScript(context, tableid) - s += 'v='+this.expression.toJavaScript(context, tableid, defcols)+';'; - s += (this.whens||[]).map(function(w) { return ' if(v=='+w.when.toJavaScript(context,tableid, defcols) - +') {r='+w.then.toJavaScript(context,tableid, defcols)+'}'; }).join(' else '); - if(this.elses) s += ' else {r='+this.elses.toJavaScript(context,tableid, defcols)+'}'; - } else { - s += (this.whens||[]).map(function(w) { return ' if('+w.when.toJavaScript(context,tableid, defcols) - +') {r='+w.then.toJavaScript(context,tableid, defcols)+'}'; }).join(' else '); - if(this.elses) s += ' else {r='+this.elses.toJavaScript(context,tableid,defcols)+'}'; - } - s += 'return r;})('+context+',params,alasql)'; - - return s; -}; - -/* -// -// JSON for Alasql.js -// Date: 19.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.Json = function (params) { return yy.extend(this, params); } -yy.Json.prototype.toString = function() { - var s = '@'; - s += JSONtoString(this.value); - s += ''; - return s; -}; - -var JSONtoString = alasql.utils.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(obj instanceof Array) { - s += '['+obj.map(function(b){ - return JSONtoString(b); - }).join(',')+']'; - } else if(!obj.toJavaScript || 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; -} - - - -function JSONtoJavaScript(obj, context, tableid, defcols) { - 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(obj instanceof Array) { - s += '['+obj.map(function(b){ - return JSONtoJavaScript(b, context, tableid, defcols); - }).join(',')+']'; - } else if(!obj.toJavaScript || 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 += ':'+JSONtoJavaScript(obj[k], context, tableid, defcols); - ss.push(s1); - }; - s += ss.join(',')+'}'; - } else if(obj.toJavaScript) { - s = obj.toJavaScript(context, tableid, defcols); - } else { - throw new Error('1Can not parse JSON object '+JSON.stringify(obj)); - } - } else { - throw new Error('2Can not parse JSON object '+JSON.stringify(obj)); - } - - return s; -} - -yy.Json.prototype.toJavaScript = function(context, tableid, defcols) { - // TODO reod - return JSONtoJavaScript(this.value,context, tableid, defcols); -} - - - - -/* -// -// CAST and CONVERT functions -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.Convert = function(params) { return yy.extend(this, params); }; -yy.Convert.prototype.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; -}; -yy.Convert.prototype.toJavaScript = function(context, tableid, defcols) { - -// if(this.style) { - return 'alasql.stdfn.CONVERT('+this.expression.toJavaScript(context, tableid, defcols) - +',{dbtypeid:"'+this.dbtypeid+'",dbsize:'+this.dbsize+',style:'+ - this.style+'})'; -// } -/* - if(this.dbtypeid == 'INT') { - return '(('+this.expression.toJavaScript(context, tableid, defcols)+')|0)'; - } if(this.dbtypeid == 'STRING') { - return '(""+'+this.expression.toJavaScript(context, tableid, defcols)+')'; - } if(this.dbtypeid == 'NUMBER') { - return '(+('+this.expression.toJavaScript(context, tableid, defcols)+'))'; - } if(this.dbtypeid == 'DATE') { - if(alasql.options.datetimeformat == 'javascript') { - return '(new Date('+this.expression.toJavaScript(context, tableid, defcols)+'))'; - } else if(alasql.options.datetimeformat == 'sql') { - return this.expression.toJavaScript(context, tableid, defcols); - } - } if(this.dbtypeid == 'DATETIME') { - if(alasql.options.datetimeformat == 'javascript') { - return '(new Date('+this.expression.toJavaScript(context, tableid, defcols)+'))'; - } else if(alasql.options.datetimeformat == 'sql') { - return this.expression.toJavaScript(context, tableid, defcols); - } - } else { - - }; -*/ - throw new Error('There is not such type conversion for '+this.toString()); -}; - -/** - Convert one type to another - */ -alasql.stdfn.CONVERT = function(value, args) { - var val = value; -// console.log(args); - 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); - - if(args.style == 1) { // mm/dd/yy - val = ("0"+(t.getMonth()+1)).substr(-2)+'/'+("0"+t.getDate()).substr(-2)+'/'+("0"+t.getYear()).substr(-2); - } else if(args.style == 2) { // yy.mm.dd - val = ("0"+t.getYear()).substr(-2)+'.'+("0"+(t.getMonth()+1)).substr(-2)+'.'+("0"+t.getDate()).substr(-2); - } else if(args.style == 3) { // dd/mm/yy - val = ("0"+t.getDate()).substr(-2)+'/'+("0"+(t.getMonth()+1)).substr(-2)+'/'+("0"+t.getYear()).substr(-2); - } else if(args.style == 4) { // dd.mm.yy - val = ("0"+t.getDate()).substr(-2)+'.'+("0"+(t.getMonth()+1)).substr(-2)+'.'+("0"+t.getYear()).substr(-2); - } else if(args.style == 5) { // dd-mm-yy - val = ("0"+t.getDate()).substr(-2)+'-'+("0"+(t.getMonth()+1)).substr(-2)+'-'+("0"+t.getYear()).substr(-2); - } else if(args.style == 6) { // dd mon yy - val = ("0"+t.getDate()).substr(-2)+' '+t.toString().substr(4,3).toLowerCase()+' '+("0"+t.getYear()).substr(-2); - } else if(args.style == 7) { // Mon dd,yy - val = t.toString().substr(4,3)+' '+("0"+t.getDate()).substr(-2)+','+("0"+t.getYear()).substr(-2); - } else if(args.style == 8) { // hh:mm:ss - val = ("0"+t.getHours()).substr(-2)+':'+("0"+(t.getMinutes()+1)).substr(-2)+':'+("0"+t.getSeconds()).substr(-2); - - } else if(args.style == 10) { // mm-dd-yy - val = ("0"+(t.getMonth()+1)).substr(-2)+'-'+("0"+t.getDate()).substr(-2)+'-'+("0"+t.getYear()).substr(-2); - } else if(args.style == 11) { // yy/mm/dd - val = ("0"+t.getYear()).substr(-2)+'/'+("0"+(t.getMonth()+1)).substr(-2)+'/'+("0"+t.getDate()).substr(-2); - } else if(args.style == 12) { // yymmdd - val = ("0"+t.getYear()).substr(-2)+("0"+(t.getMonth()+1)).substr(-2)+("0"+t.getDate()).substr(-2); - - - } else if(args.style == 101) { // mm/dd/yy - val = ("0"+(t.getMonth()+1)).substr(-2)+'/'+("0"+t.getDate()).substr(-2)+'/'+t.getFullYear(); - } else if(args.style == 102) { // yy.mm.dd - val = t.getFullYear()+'.'+("0"+(t.getMonth()+1)).substr(-2)+'.'+("0"+t.getDate()).substr(-2); - } else if(args.style == 103) { // dd/mm/yy - val = ("0"+t.getDate()).substr(-2)+'/'+("0"+(t.getMonth()+1)).substr(-2)+'/'+t.getFullYear(); - } else if(args.style == 104) { // dd.mm.yy - val = ("0"+t.getDate()).substr(-2)+'.'+("0"+(t.getMonth()+1)).substr(-2)+'.'+t.getFullYear(); - } else if(args.style == 105) { // dd-mm-yy - val = ("0"+t.getDate()).substr(-2)+'-'+("0"+(t.getMonth()+1)).substr(-2)+'-'+t.getFullYear(); - } else if(args.style == 106) { // dd mon yy - val = ("0"+t.getDate()).substr(-2)+' '+t.toString().substr(4,3).toLowerCase()+' '+t.getFullYear(); - } else if(args.style == 107) { // Mon dd,yy - val = t.toString().substr(4,3)+' '+("0"+t.getDate()).substr(-2)+','+t.getFullYear(); - } else if(args.style == 108) { // hh:mm:ss - val = ("0"+t.getHours()).substr(-2)+':'+("0"+(t.getMinutes()+1)).substr(-2)+':'+("0"+t.getSeconds()).substr(-2); - - } else if(args.style == 110) { // mm-dd-yy - val = ("0"+(t.getMonth()+1)).substr(-2)+'-'+("0"+t.getDate()).substr(-2)+'-'+t.getFullYear(); - } else if(args.style == 111) { // yy/mm/dd - val = t.getFullYear()+'/'+("0"+(t.getMonth()+1)).substr(-2)+'/'+("0"+t.getDate()).substr(-2); - } else if(args.style == 112) { // yymmdd - val = t.getFullYear()+("0"+(t.getMonth()+1)).substr(-2)+("0"+t.getDate()).substr(-2); - } else { - throw new Error('The CONVERT style '+args.style+' is not realized yet.'); - } - }; - - if(args.dbtypeid == 'Date') { - return new Date(val); - } else if(args.dbtypeid.toUpperCase() == '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(args.dbtypeid == 'DATETIME') { - 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()).substr(-3) - return s; - } else if(args.dbtypeid.toUpperCase() == 'STRING') { - return ""+val; - } else if(args.dbtypeid.toUpperCase() == 'NUMBER' || args.dbtypeid == 'FLOAT') { - return +val; - } else if(args.dbtypeid.toUpperCase() == 'MONEY') { - var m = +val; - return (m|0)+((m*100)%100)/100; - } else if(args.dbtypeid.toUpperCase() == 'BOOLEAN') { - return !!val; - } else if(args.dbtypeid.toUpperCase() == 'INT') { - return val|0; - } else if(args.dbtypeid.toUpperCase() == 'VARCHAR' || args.dbtypeid == 'NVARCHAR') { - if(args.dbsize) return (""+val).substr(0,args.dbsize); - else return ""+val; - } else if(args.dbtypeid.toUpperCase() == 'CHAR' || args.dbtypeid == 'NCHAR') { - return (val+(new Array(args.dbsize+1).join(" "))).substr(0,args.dbsize); - //else return ""+val.substr(0,1); - } -}; - - - -/* -// -// CREATE TABLE for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.ColumnDef = function (params) { return yy.extend(this, params); } -yy.ColumnDef.prototype.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; -} - -yy.CreateTable = function (params) { return yy.extend(this, params); } -yy.CreateTable.prototype.toString = function() { - var s = K('CREATE'); - if(this.temporary) s+=' '+K('TEMPORARY'); - if(this.view) s += ' '+K('VIEW'); - else s += ' '+K('TABLE'); - if(this.ifnotexists) s += ' '+K('IF')+' '+K('NOT')+' '+K('EXISTS'); - s += ' '+this.table.toString(); - if(this.viewcolumns) { - s += '('+this.viewcolumns.map(function(vcol){ - return vcol.toString(); - }).join(',')+')'; - } - if(this.as) s += ' '+K('AS')+' '+L(this.as); - else { - var ss = this.columns.map(function(col){ - return col.toString(); - }); - s += ' ('+NL()+ID()+ss.join(','+NL()+ID())+')'; - }; - if(this.view && this.select) { - s += ' AS '+this.select.toString(); - } - return s; -} - -// CREATE TABLE -//yy.CreateTable.prototype.compile = returnUndefined; -yy.CreateTable.prototype.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||[]; -// console.log(this); - - // IF NOT EXISTS - if(this.ifnotexists && db.tables[tableid]) return 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? - - var ss = []; - if(this.columns) { - this.columns.forEach(function(col) { - var dbtypeid = col.dbtypeid; - if(!alasql.fn[dbtypeid]) dbtypeid = dbtypeid.toUpperCase(); - var newcol = { - columnid: col.columnid, - dbtypeid: dbtypeid // TODO: Add types table - }; - - if(col.default) { - ss.push('\''+col.columnid+'\':'+col.default.toJavaScript()); - } - - table.columns.push(newcol); - table.xcolumns[newcol.columnid] = newcol; - - // 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",'return '+pk.onrightfns); - pk.hh = hash(pk.onrightfns); - table.indices[pk.hh] = {}; - }; - - }); - }; - table.defaultfns = ss.join(','); - - -// if(constraints) { - constraints.forEach(function(con) { - //console.log(con, con.columns); - 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",'return '+pk.onrightfns); - pk.hh = hash(pk.onrightfns); - table.indices[pk.hh] = {}; - } - }); - - if(this.view && this.viewcolumns) { - var self = this; - this.viewcolumns.forEach(function(vcol,idx){ - self.select.columns[idx].as = vcol.columnid; - }); - } - -// console.log(100,db.engineid); - if(db.engineid) { -// console.log(101,db.engineid); - return alasql.engines[db.engineid].createTable(this.table.databaseid || databaseid, tableid, this.ifnotexists, cb); -// console.log('createtable',res1); -// return res1; - } - -// } -// if(table.pk) { - table.insert = function(r) { - if(this.pk) { - var pk = this.pk; - var addr = pk.onrightfn(r); - if(typeof this.indices[pk.hh][addr] != 'undefined') { - throw new Error('Cannot insert record, because it already exists in primary key'); - } else { - table.data.push(r); - this.indices[pk.hh][addr]=r; - }; - } else { - table.data.push(r); - } - }; - - table.delete = function(i) { - if(this.pk) { - var r = this.data[i]; - var pk = this.pk; - var addr = pk.onrightfn(r); - if(typeof this.indices[pk.hh][addr] == 'undefined') { - throw new Error('Something wrong with index on table'); - } else { - this.indices[pk.hh][addr]=undefined; - }; - } - }; - - table.deleteall = function() { - this.data.length = 0; - if(this.pk) { -// var r = this.data[i]; - this.indices[this.pk.hh] = {}; - } - }; - - table.update = function(assignfn, i, params) { - if(this.pk) { - var r = this.data[i]; - var pk = this.pk; - var addr = pk.onrightfn(r,params); - if(typeof this.indices[pk.hh][addr] == 'undefined') { - throw new Error('Something wrong with index on table'); - } else { - this.indices[pk.hh][addr]=undefined; - assignfn(r,params,alasql); - var newaddr = pk.onrightfn(r); - if(typeof this.indices[pk.hh][newaddr] != 'undefined') { - throw new Error('Record already exists'); - } else { - this.indices[pk.hh][newaddr] = r; - } - } - - } else { - assignfn(this.data[i],params,alasql); - }; - - }; - - if(this.view && this.select) { - table.view = true; -// console.log(this.select.toString()); -// console.log('this.table.databaseid',this.table.databaseid); -// console.log(this.select.compile(this.table.databaseid||databaseid)); - table.select = this.select.compile(this.table.databaseid||databaseid); - } -// console.log(databaseid); -// console.log(db.databaseid,db.tables); -// console.log(table); - if(cb) cb(1); - - return 1; -}; - - + } 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; + } + } -// -// Date functions -// -// (c) 2014, Andrey Gershun -// + var s = ''; -/** Standard JavaScript data types */ + if(typeof sql == 'string' && alasql.options.logprompt) { +// s += '

'+olduseid+'> '+alasql.pretty(sql)+'

'; + s += '
'+alasql.pretty(sql)+'
'; + } -alasql.fn.Date = Object; -alasql.fn.Date = Date; -alasql.fn.Number = Number; -alasql.fn.String = String; -alasql.fn.Boolean = Boolean; + if(res instanceof Array) { + if(res.length == 0) { + s += '

[ ]

' + } else if(typeof res[0] != 'object' || res[0] instanceof Array) { + for(var i=0,ilen=res.length;i'; + } + } else { + s += loghtml(res); + } + } else { + s += loghtml(res); + } + el.innerHTML += s; + } +}; -/** Extend Object with properties */ -stdfn.EXTEND = alasql.utils.extend; +alasql.clear = function() { + var target = alasql.options.logtarget; + // For node other + if(typeof exports == 'object') { + target = 'console'; + }; + if(target == 'console' || typeof exports == 'object') { + if(console.clear) { + console.clear(); + } else { + // Something todo in Node + } + } 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 = ''; + } +} -stdfn.CHAR = String.fromCharCode.bind(String); -stdfn.ASCII = function(a) { - return a.charCodeAt(0); -}; +alasql.write = function(s) { +// console.log('write',s); + var target = alasql.options.logtarget; + // For node other + if(typeof exports == 'object') { + target = 'console'; + }; -/** - Return first non-null argument - See https://msdn.microsoft.com/en-us/library/ms190349.aspx -*/ -stdfn.COALESCE = function() { - for(var i=0;i'; + } + // if () {} -stdfn.OBJECT_ID = function(objid){ - return !!alasql.tables[objid]; + // if(typeof res == 'object') { + // s += '

'+JSON.stringify(res)+'

'; + // } else { + // } + return s; }; -stdfn.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); -}; -stdfn.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; -}; -stdfn.GETDATE = stdfn.NOW; +function scrollTo(element, to, duration) { + if (duration <= 0) return; + var difference = to - element.scrollTop; + var perTick = difference / duration * 10; -// stdfn.GETDATE = function(){ -// var d = new Date(); -// var s = d.getFullYear()+"."+("0"+(d.getMonth()+1)).substr(-2)+"."+("0"+d.getDate()).substr(-2); -// return s; -// } + setTimeout(function() { + if (element.scrollTop==to) return; + element.scrollTop = element.scrollTop + perTick; + scrollTo(element, to, duration - 10); + }, 10); +} + +alasql.prompt = function(el, useidel, firstsql) { + if(typeof exports == 'object') { + throw new Error('The functionality of prompt is 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('

'+(Date.now()-tm)+' ms

'); + } catch (err) { + alasql.write('

'+olduseid+'> '+sql+'

'); + alasql.write('

'+err+'

'); + } + }; + 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('

'+(Date.now()-tm)+' ms

'); + } catch (err) { + alasql.write('

'+olduseid+'> '+alasql.pretty(sql, false)+'

'); + alasql.write('

'+err+'

'); + } + el.focus(); +// console.log(el.getBoundingClientRect().top); + 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(); + } -stdfn.SECOND = function(d){ - d = new Date(d); - return d.getSeconds(); -}; + } 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(); + } + } + } +} -stdfn.MINUTE = function(d){ - d = new Date(d); - return d.getMinutes(); -}; -stdfn.HOUR = function(d){ - d = new Date(d); - return d.getHours(); -}; -stdfn.DAYOFWEEK = stdfn.WEEKDAY = function(d){ - d = new Date(d); - return d.getDay(); -}; -stdfn.DAY = stdfn.DAYOFMONTH = function(d){ - d = new Date(d); - return d.getDate(); -}; -stdfn.MONTH = function(d){ - d = new Date(d); - return d.getMonth()+1; +/* +// +// Commit for Alasql.js +// Date: 01.12.2014 +// (c) 2014, Andrey Gershun +// +*/ +yy.BeginTransaction = function (params) { return yy.extend(this, params); } +yy.BeginTransaction.prototype.toString = function() { + return K('BEGIN')+' '+K('TRANSACTION'); +} + +yy.BeginTransaction.prototype.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; }; -stdfn.YEAR = function(d){ - d = new Date(d); - return d.getFullYear(); +yy.CommitTransaction = function (params) { return yy.extend(this, params); } +yy.CommitTransaction.prototype.toString = function() { + return K('COMMIT')+' '+K('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; }; -/* -// -// DROP TABLE for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.DropTable = function (params) { return yy.extend(this, params); } -yy.DropTable.prototype.toString = function() { - var s = K('DROP')+' '; - if(this.view) s += K('VIEW'); - else s += K('TABLE'); - if(this.ifexists) s += ' '+K('IF')+' '+K('EXISTS'); - s += ' '+this.table.toString(); - return s; -} - - -// DROP TABLE -yy.DropTable.prototype.execute = function (databaseid, params, cb) { -// console.log(arguments); -// console.log(alasql.databases[databaseid]); - var db = alasql.databases[this.table.databaseid || databaseid]; - var tableid = this.table.tableid; -// console.log(db, this.table.databaseid ); - if(db.engineid /*&& alasql.options.autocommit*/) { - return alasql.engines[db.engineid].dropTable(this.table.databaseid || databaseid,tableid, this.ifexists, cb); - } - if(!this.ifexists || this.ifexists && db.tables[tableid]) { - if(!db.tables[tableid]) { - if(!alasql.options.dropifnotexists) { - throw new Error('Can not drop table \''+this.table.tableid+'\', because it does not exist in the database.'); - } - } else { - delete db.tables[tableid]; - return 1; - } - } - return 0; -}; - - -yy.TruncateTable = function (params) { return yy.extend(this, params); } -yy.TruncateTable.prototype.toString = function() { - var s = K('TRUNCATE')+' '+K('TABLE'); - 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; -// console.log(db, this.table.databaseid ); - 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 0; -}; - - -/* -// -// ALTER TABLE for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -// ALTER TABLE table1 RENAME TO table2 -yy.AlterTable = function (params) { return yy.extend(this, params); } -yy.AlterTable.prototype.toString = function() { - var s = 'ALTER TABLE '+this.table.toString(); - if(this.renameto) s += ' RENAME TO '+this.renameto; - return s; -} - -yy.AlterTable.prototype.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 0) { - for(var i=0, ilen=table.data.length; i 0) { - for(var i=0, ilen=table.data.length; i=0) { - q += "+"+values[idx].toJavaScript(); - } else if (alasql.fn[table.xcolumns[col.columnid].dbtypeid]) { - q += "(new "+table.xcolumns[col.columnid].dbtypeid+"("; - q += values[idx].toJavaScript(); - q += "))"; - } else { - q += values[idx].toJavaScript(); - }; - } else { - q += values[idx].toJavaScript(); - } - ss.push(q); - - }); - } else { -// var table = db.tables[tableid]; -// console.log('table1', db, self); -//console.log(111, table.columns); -//console.log(74,table); - if((values instanceof Array) && table.columns && table.columns.length > 0) { - table.columns.forEach(function(col, idx){ - - var q = '\''+col.columnid +'\':'; -// var val = values[idx].toJavaScript(); - - if(["INT","FLOAT","NUMBER","MONEY"].indexOf(col.dbtypeid) >=0) { - q += "+"+values[idx].toJavaScript(); - } else if (alasql.fn[col.dbtypeid]) { - q += "(new "+col.dbtypeid+"("; - q += values[idx].toJavaScript(); - q += "))"; - } else { - q += values[idx].toJavaScript(); - } - - // if(table.xcolumns && table.xcolumns[col.columnid] && - // (table.xcolumns[col.columnid].dbtypeid == "DATE" || - // table.xcolumns[col.columnid].dbtypeid == "DATETIME" - // )) { - // val = "(new Date("+val+"))"; - // } - // || table.xcolumns[col.columnid].dbtypeid == "FLOAT" - // || table.xcolumns[col.columnid].dbtypeid == "NUMBER" - // || table.xcolumns[col.columnid].dbtypeid == "MONEY" - // )) q += '+'; - // console.log(self.values[idx].toString()); - //console.log(self); -// q += val; - - // if(table.xcolumns && table.xcolumns[col.columnid] && table.xcolumns[col.columnid].dbtypeid == "INT") q += '|0'; - ss.push(q); - - // console.log(fld); - // TODO: type checking and conversions - // rec[fld.fldid] = eval(self.insertExpression[idx].toJavaScript('','')); - // console.log(rec[fld.fldid]); - // if(rec[fld.fldid] == "NULL") rec[fld.fldid] = undefined; - - // if(table.xflds[fld.fldid].dbtypeid == "INT") rec[fld.fldid] = +rec[fld.fldid]|0; - // else if(table.xflds[fld.fldid].dbtypeid == "FLOAT" || table.xflds[fld.fldid].dbtypeid == "MONEY" ) - // rec[fld.fldid] = +rec[fld.fldid]; - }); - } else { -// console.log(222,values); -// sw = 'var w='+JSONtoJavaScript(values)+';for(var k in w){r[k]=w[k]};'; - sw = JSONtoJavaScript(values); - } - } -//console.log(ss); - - if(db.tables[tableid].defaultfns) ss.unshift(db.tables[tableid].defaultfns); - if(sw) { - s += 'a='+sw+';'; - } else { - s += 'a={'+ss.join(',')+'};'; - } -// s += 'db.tables[\''+tableid+'\'].insert(r);'; - if(db.tables[tableid].insert) { - s += 'alasql.databases[\''+databaseid+'\'].tables[\''+tableid+'\'].insert(a);'; - } else { - s += 'aa.push(a);'; - } - }); - - s33 = s3+s; - - if(db.tables[tableid].insert) { -// s += 'alasql.databases[\''+databaseid+'\'].tables[\''+tableid+'\'].insert(r);'; - } else { - s += 'alasql.databases[\''+databaseid+'\'].tables[\''+tableid+'\'].data='+ - 'alasql.databases[\''+databaseid+'\'].tables[\''+tableid+'\'].data.concat(aa);'; - } - - s += 'return '+self.values.length; - -//console.log(s); - var insertfn = new Function('db, params, alasql',s3+s); - -// INSERT INTO table SELECT - - } else if(this.select) { - 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,null, cb); - return res; - }; - return statement; - } else { - var insertfn = function(db, params, alasql) { - var res = selectfn(params); - db.tables[tableid].data = db.tables[tableid].data.concat(res); - return res.length; - } - } - - - } else if(this.default) { - var insertfns = 'db.tables[\''+tableid+'\'].data.push({'+table.defaultfns+'});return 1;'; - var insertfn = new Function('db,params,alasql',insertfns); - } else { - throw new Error('Wrong INSERT parameters'); - } - -// console.log(1,s); -// console.log(s33); - - if(db.engineid && alasql.engines[db.engineid].intoTable && alasql.options.autocommit) { - var statement = function(params, cb) { - var aa = new Function("db,params",s33+'return aa;')(db,params); -// console.log(s33); - var res = alasql.engines[db.engineid].intoTable(db.databaseid,tableid,aa, null, cb); -// if(cb) cb(res); - return res; - }; - - } else { - - var statement = function(params, cb) { - //console.log(databaseid); - 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); - } - // var res = insertfn(db, params); - if(cb) cb(res); - return res; - }; - }; - - return statement; -}; - -yy.Insert.prototype.execute = function (databaseid, params, cb) { - return this.compile(databaseid)(params,cb); -// throw new Error('Insert statement is should be compiled') -} - - - - - -/* -// -// DELETE for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.Delete = function (params) { return yy.extend(this, params); } -yy.Delete.prototype.toString = function() { - var s = 'DELETE FROM '+this.table.toString(); - if(this.where) s += ' WHERE '+this.where.toString(); - return s; -} - -yy.Delete.prototype.compile = function (databaseid) { -// console.log(11,this); - databaseid = this.table.databaseid || databaseid; - var tableid = this.table.tableid; - var statement; - var db = alasql.databases[databaseid]; - - - - if(this.where) { -// try { -// console.log(this, 22, this.where.toJavaScript('r','')); -// } catch(err){console.log(444,err)}; -// var query = {}; - wherefn = new Function('r,params','return ('+this.where.toJavaScript('r','')+')'); -// console.log(wherefn); - 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]; -// table.dirty = true; - var orignum = table.data.length; - - var newtable = []; - for(var i=0, ilen=table.data.length;i 0) { - s += '('+this.args.map(function(arg){ return arg.toString()}).join(', ')+')'; - } - if(this.as) s += ' '+K('AS')+' '+L(this.as); - return s; -} -//yy.CreateDatabase.prototype.compile = returnUndefined; -yy.CreateDatabase.prototype.execute = function (databaseid, params, cb) { - // console.log(alasql.useid, databaseid, this.databaseid); - // console.trace(); - var args; - if(this.args && this.args.length > 0) { - args = this.args.map(function(arg){ - return new Function('params','return '+arg.toJavaScript())(params); - }); - }; - 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; - } -}; - -// CREATE DATABASE databaseid -yy.AttachDatabase = function (params) { return yy.extend(this, params); }; -yy.AttachDatabase.prototype.toString = function() { - var s = K('ATTACH'); - if(this.engineid) s += ' '+L(this.engineid); - s += ' '+K('DATABASE')+' '+L(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+= ' '+K('AS')+' '+L(this.as); - return s; -} -//yy.CreateDatabase.prototype.compile = returnUndefined; -yy.AttachDatabase.prototype.execute = function (databaseid, params, cb) { - // console.log(alasql.useid, databaseid, this.databaseid); - // console.trace(); - 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 = K('DETACH'); - s += ' '+K('DATABASE')+' '+L(this.databaseid); - return s; -} -//yy.CreateDatabase.prototype.compile = returnUndefined; -yy.DetachDatabase.prototype.execute = function (databaseid, params, cb) { - // console.log(alasql.useid, databaseid, this.databaseid); - // console.trace(); - 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"); - } -// console.log(dbid); - 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; -}; - -// USE DATABSE databaseid -// USE databaseid -yy.UseDatabase = function (params) { return yy.extend(this, params); }; -yy.UseDatabase.prototype.toString = function() { - return K('USE') +' '+K('DATABASE')+' '+L(this.databaseid); -} -//yy.UseDatabase.prototype.compile = returnUndefined; -yy.UseDatabase.prototype.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; -}; - -// DROP DATABASE databaseid -yy.DropDatabase = function (params) { return yy.extend(this, params); } -yy.DropDatabase.prototype.toString = function() { - var s = K('DROP'); - if(this.ifexists) s += ' '+K('IF')+' '+K('EXISTS'); - s += ' '+K('DATABASE')+' '+L(this.databaseid); - return s; -} -//yy.DropDatabase.prototype.compile = returnUndefined; -yy.DropDatabase.prototype.execute = function (databaseid, params, cb) { - if(this.engineid) { - -// console.log(this,this.databaseid, this.ifexists); - 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"); - } -// console.log(dbid); - 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; -}; - - - - - - - -/* -// -// SET for Alasql.js -// Date: 01.12.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.Declare = function (params) { return yy.extend(this, params); } -yy.Declare.prototype.toString = function() { - var s = K('DECLARE')+' '; - if(this.declares && this.declares.length > 0) { - s = this.declares.map(function(declare){ - var s = ''; - s += '@'+L(declare.variable)+' '; - s += declare.dbtypeid; - if(this.dbsize) s += '('+N(this.dbsize); - if(this.dbprecision) s+= ','+N(this.dbprecision); - s += ')'; - if(declare.expression) s += ' = '+declare.expression.toString(); - return s; - }).join(','); - } - return s; -} - -yy.Declare.prototype.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) { - // console.log(this.expression.toJavaScript('','', null)); - alasql.vars[declare.variable] = new Function("params,alasql","return " - +declare.expression.toJavaScript('','', 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; -}; - - - -/* -// -// SHOW for Alasql.js -// Date: 19.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.ShowDatabases = function (params) { return yy.extend(this, params); } -yy.ShowDatabases.prototype.toString = function() { - var s = K('SHOW')+' '+K('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) { - res = res.filter(function(d){ - return d.databaseid.match(new RegExp((self.like.value).replace(/\%/g,'.*'),'g')); - }); - } - if(cb) cb(res); - return res; - }; - -}; - - -yy.ShowTables = function (params) { return yy.extend(this, params); } -yy.ShowTables.prototype.toString = function() { - var s = K('SHOW')+' '+K('TABLES'); - if(this.databaseid) s += ' FROM '+this.databaseid; - if(this.like) s += ' '+K('LIKE')+' '+this.like.toString(); - return s; -} -yy.ShowTables.prototype.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,'.*'),'g')); - }); - }; - if(cb) cb(res); - return res; -}; - -yy.ShowColumns = function (params) { return yy.extend(this, params); } -yy.ShowColumns.prototype.toString = function() { - var s = K('SHOW')+' '+K('COLUMNS'); - if(this.table.tableid) s += ' '+K('FROM')+' '+this.table.tableid; - if(this.databaseid) s += ' '+K('FROM')+' '+this.databaseid; - return s; -}; - -yy.ShowColumns.prototype.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 []; - } -}; - -yy.ShowIndex = function (params) { return yy.extend(this, params); } -yy.ShowIndex.prototype.toString = function() { - var s = K('SHOW')+' '+K('INDEX'); - if(this.table.tableid) s += ' '+K('FROM')+' '+this.table.tableid; - if(this.databaseid) s += ' '+K('FROM')+' '+this.databaseid; - return s; -} -yy.ShowIndex.prototype.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; -}; - -yy.ShowCreateTable = function (params) { return yy.extend(this, params); } -yy.ShowCreateTable.prototype.toString = function() { - var s = K('SHOW')+' '+K('CREATE')+' '+K('TABLE')+' '+L(this.table.tableid); - if(this.databaseid) s += ' '+K('FROM')+' '+L(this.databaseid); - return s; -} -yy.ShowCreateTable.prototype.execute = function (databaseid) { - var db = alasql.databases[this.databaseid || databaseid]; - var table = db.tables[this.table.tableid]; - var self = this; - if(table) { - var s = K('CREATE')+' '+K('TABLE')+' '+L(this.table.tableid)+' ('; - var ss = []; - if(table.columns) { - table.columns.forEach(function(col){ - var a = L(col.columnid)+' '+K(col.dbtypeid); - if(col.dbsize) a += '('+N(col.dbsize)+')'; - if(col.primarykey) a += ' '+K('PRIMARY')+' '+K('KEY'); - // TODO extend - ss.push(a); - }); - s += ss.join(', '); - }; - s += ')'; - return s; - } else { - throw new Error('There is no such table "'+this.table.tableid+'"'); - } -}; - - -/* -// -// SET for Alasql.js -// Date: 01.12.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.SetVariable = function (params) { return yy.extend(this, params); } -yy.SetVariable.prototype.toString = function() { - var s = K('SET')+' '; - if(typeof this.value != 'undefined') s += K(this.variable.toUpperCase())+' '+(this.value?'ON':'OFF'); - if(this.expression) s += '@' + L(this.variable)+' = '+this.expression.toString(); - return s; -} - -yy.SetVariable.prototype.execute = function (databaseid,params,cb) { -// console.log(this); - 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) { -// console.log(this.expression.toJavaScript('','', null)); - var res = new Function("params,alasql","return " - +this.expression.toJavaScript('','', null))(params,alasql); - if(alasql.declares[this.variable]) { - res = alasql.stdfn.CONVERT(res,alasql.declares[this.variable]); - } - if(this.props && this.props.length > 0) { - var fs = 'alasql.vars[\''+this.variable+'\']'; - fs += this.props.map(function(prop){ - if(typeof prop == 'string') { - return '[\''+prop+'\']'; - } else if(typeof prop == 'number') { - return '['+prop+']'; - } else { - // console.log('prop:',prop, prop.toJavaScript()); - return '['+prop.toJavaScript()+']'; -// } else { -// console.log(prop, typeof ); -// throw new Error('Wrong SET property'); - } - }).join(); -// console.log(fs); - new Function("value,alasql",fs +'=value')(res,alasql); - } else { - alasql.vars[this.variable] = res; - } - } - var res = 1; - if(cb) res=cb(res); - return res; -}; - - - -// Console functions -/* -alasql.con = { - results:{} -}; - -alasql.con.open = function(el) { - // For browser only - if (typeof exports === 'object') return; - - // Find parent element - el = el || document.getElementById('alasql-con') || document.getElementsByTagName('body'); - if(!el) {throw new Error('Cannot fid element for console.')} - - var conel = document.createElement('div'); - conel.style.width = "1000px"; - conel.style.height = "320px"; - - alasql.con.conel = conel; - - var lenta = document.createElement('div'); - lenta.style.width = "1000px"; - lenta.style.height = "200px"; - lenta.style.overflow = "scroll"; - alasql.con.lenta = lenta; - - var inpel = document.createElement('div'); - inpel.style.width = "1000px"; - inpel.style.height = "100px"; - inpel.style.contentEditable = true; - inpel.innerHTML = 'command '; - alasql.con.inpel = inpel; - - conel.appendChild(lenta); - conel.appendChild(inpel); - el.appendChild(conel); -}; - -alasql.con.clear = function() { - // For browser only - if (typeof exports === 'object') return; - - alasql.con.conel.innerHTML = ''; -}; - -alasql.con.close = function() { - // For browser only - if (typeof exports === 'object') return; - - alasql.con.conel.removeChild(alasql.con.lenta); - alasql.con.conel.removeChild(alasql.con.inel); - alasql.con.conel.parentElement.removeChild(conel); -}; - -alasql.con.log = function() { - // For browser only - if (typeof exports === 'object') { - console.log.bind(console).apply(this, arguments); - } else { - var s = '

'; - s += Array.prototype.slice.call(arguments, 0).map(function(arg){ - return arg.toString(); - }).join(' '); - s += '
'; - alasql.con.conel.innerHTML += s; - }; - -}; -*/ -alasql.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',sql); - - if(res instanceof Array) { - 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 += '

'+olduseid+'> '+alasql.pretty(sql)+'

'; - s += '
'+alasql.pretty(sql)+'
'; - } - - if(res instanceof Array) { - if(res.length == 0) { - s += '

[ ]

' - } else if(typeof res[0] != 'object' || res[0] instanceof Array) { - for(var i=0,ilen=res.length;i'; - } - } else { - s += loghtml(res); - } - } else { - s += loghtml(res); - } - el.innerHTML += s; - } -}; - -alasql.clear = function() { - var target = alasql.options.logtarget; - // For node other - if(typeof exports == 'object') { - target = 'console'; - }; - - if(target == 'console' || typeof exports == 'object') { - if(console.clear) { - console.clear(); - } else { - // Something todo in Node - } - } 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.write = function(s) { -// console.log('write',s); - var target = alasql.options.logtarget; - // For node other - if(typeof exports == 'object') { - target = 'console'; - }; - - if(target == 'console' || typeof exports == 'object') { - if(console.log) { - console.log(s); - } else { - // Something todo in Node - } - } 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; - } -} - -function loghtml(res) { -// console.log(res); - var s = ''; - if(typeof res == 'undefined') { - s += 'undefined'; - } else if(res instanceof Array) { - s += ''; - s += ''; - var cols = []; - for(colid in res[0]) { - cols.push(colid); - } - s += '
#'; - cols.forEach(function(colid){ - s += ''+colid; - }); - for(var i=0,ilen=res.length;i'; - } - // if () {} - - // if(typeof res == 'object') { - // s += '

'+JSON.stringify(res)+'

'; - // } else { - // } - return s; -}; - - - -function scrollTo(element, to, duration) { - if (duration <= 0) return; - var difference = to - element.scrollTop; - var perTick = difference / duration * 10; - - setTimeout(function() { - if (element.scrollTop==to) return; - element.scrollTop = element.scrollTop + perTick; - scrollTo(element, to, duration - 10); - }, 10); -} - -alasql.prompt = function(el, useidel, firstsql) { - if(typeof exports == 'object') { - throw new Error('The functionality of prompt is 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('

'+(Date.now()-tm)+' ms

'); - } catch (err) { - alasql.write('

'+olduseid+'> '+sql+'

'); - alasql.write('

'+err+'

'); - } - }; - - 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('

'+(Date.now()-tm)+' ms

'); - } catch (err) { - alasql.write('

'+olduseid+'> '+alasql.pretty(sql, false)+'

'); - alasql.write('

'+err+'

'); - } - el.focus(); -// console.log(el.getBoundingClientRect().top); - 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(); - } - } - - } -} - - - - - -/* -// -// Commit for Alasql.js -// Date: 01.12.2014 -// (c) 2014, Andrey Gershun -// -*/ -yy.BeginTransaction = function (params) { return yy.extend(this, params); } -yy.BeginTransaction.prototype.toString = function() { - return K('BEGIN')+' '+K('TRANSACTION'); -} - -yy.BeginTransaction.prototype.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; -}; - -yy.CommitTransaction = function (params) { return yy.extend(this, params); } -yy.CommitTransaction.prototype.toString = function() { - return K('COMMIT')+' '+K('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); } -yy.RollbackTransaction.prototype.toString = function() { - return K('ROLLBACK')+' '+K('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; -}; +yy.RollbackTransaction = function (params) { return yy.extend(this, params); } +yy.RollbackTransaction.prototype.toString = function() { + return K('ROLLBACK')+' '+K('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; +}; // @@ -11022,209 +11033,209 @@ function XLSXLSX(X,filename, opts, cb, idx, query) { -/* -// -// HELP for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.Help = function (params) { return yy.extend(this, params); } -yy.Help.prototype.toString = function() { - var s = K('HELP'); - if(this.subject) s += ' '+L(this.subject); - return s; -} - -// Help string -helpdocs = [ - {command:'ALTER TABLE table RENAME TO table'}, - {command:'ALTER TABLE table ADD COLUMN column coldef'}, - {command:'ALTER TABLE table MODIFY COLUMN column coldef'}, - {command:'ALTER TABLE table RENAME COLUMN column TO column'}, - {command:'ALTER TABLE table DROP column'}, - {command:'ATTACH engine DATABASE database'}, - {command:'ASSERT value'}, - {command:'BEGIN [TRANSACTION]'}, - {command:'COMMIT [TRANSACTION]'}, - {command:'CREATE [engine] DATABASE [IF NOT EXISTS] database'}, - {command:'CREATE TABLE [IF NOT EXISTS] table (column definitions)'}, - {command:'DELETE FROM table [WHERE expression]'}, - {command:'DETACH DATABASE database'}, - {command:'DROP [engine] DATABASE [IF EXISTS] database'}, - {command:'DROP TABLE [IF EXISTS] table'}, - {command:'INSERT INTO table VALUES value,...'}, - {command:'INSERT INTO table DEFAULT VALUES'}, - {command:'INSERT INTO table SELECT select'}, - {command:'HELP [subject]'}, - {command:'ROLLBACK [TRANSACTION]'}, - {command:'SELECT [modificator] columns [INTO table] [FROM table,...] [[mode] JOIN [ON] [USING]] [WHERE ] [GROUP BY] [HAVING] [ORDER BY] '}, - {command:'SET option value'}, - {command:'SHOW [engine] DATABASES'}, - {command:'SHOW TABLES'}, - {command:'SHOW CREATE TABLE table'}, - {command:'UPDATE table SET column1 = expression1, ... [WHERE expression]'}, - {command:'USE [DATABASE] database'}, - {command:'expression'}, - {command:'See also http://github/agershun/alasq for more information'} -]; - -// execute -yy.Help.prototype.execute = function (databaseid, params, cb) { - var ss = []; - if(!this.subject) { - ss = helpdocs; - } else { - ss.push('See also http://github/agershun/alasq for more information'); - } - if(cb) ss = cb(ss); - return ss; -}; - - -/* -// -// HELP for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.Print = function (params) { return yy.extend(this, params); } -yy.Print.prototype.toString = function() { - var s = K('PRINT'); - if(this.statement) s += ' '+this.statement.toString(); - return s; -} - -/** - Print result of select statement or expression -*/ -yy.Print.prototype.execute = function (databaseid,params,cb) { -// console.log(this.url); - var res, s; - - if(this.statement) { - s = this.statement.execute(databaseid,params); - } else { - s = ''; - } - s = JSONtoString(s); - - console.log(s); - - if(cb) res = cb(res); - return res; -}; - - -/* -// -// HELP for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.Source = function (params) { return yy.extend(this, params); } -yy.Source.prototype.toString = function() { - var s = K('SOURCE'); - if(this.url) s += ' '+S('\''+this.url+'\''); - return s; -} - -// SOURCE FILE -yy.Source.prototype.execute = function (databaseid,params,cb) { -// console.log(this.url); - var res; - loadFile(this.url, !!cb, function(data){ -// console.log(data); -// res = 1; - res = alasql(data); - if(cb) res = cb(res); - return res; - }, function(err){ - throw err; - }); - return res; -}; - - -/* -// -// HELP for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.Require = function (params) { return yy.extend(this, params); } -yy.Require.prototype.toString = function() { - var s = K('REQUIRE'); - if(this.paths && this.paths.length > 0) { - s += this.paths.map(function(path){ - return path.toString() - }).join(','); - } - return s; -} - -/** - Attach plug-in for Alasql - */ -yy.Require.prototype.execute = function (databaseid,params,cb) { - var self = this; - var res = 0; - var ss = ''; -// console.log(this.paths); - if(this.paths.length > 0) { - this.paths.forEach(function(path){ - loadFile(path.value, !!cb, function(data){ - res++; -// console.log(res,self.paths.length); -// console.log(data); - ss += data; - if(reshttp://github/agershun/alasq for more information'} +]; + +// execute +yy.Help.prototype.execute = function (databaseid, params, cb) { + var ss = []; + if(!this.subject) { + ss = helpdocs; + } else { + ss.push('See also http://github/agershun/alasq for more information'); + } + if(cb) ss = cb(ss); + return ss; +}; + + +/* +// +// HELP for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +yy.Print = function (params) { return yy.extend(this, params); } +yy.Print.prototype.toString = function() { + var s = K('PRINT'); + if(this.statement) s += ' '+this.statement.toString(); + return s; +} + +/** + Print result of select statement or expression +*/ +yy.Print.prototype.execute = function (databaseid,params,cb) { +// console.log(this.url); + var res, s; + + if(this.statement) { + s = this.statement.execute(databaseid,params); + } else { + s = ''; + } + s = JSONtoString(s); + + console.log(s); + + if(cb) res = cb(res); + return res; +}; + + +/* +// +// HELP for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +yy.Source = function (params) { return yy.extend(this, params); } +yy.Source.prototype.toString = function() { + var s = K('SOURCE'); + if(this.url) s += ' '+S('\''+this.url+'\''); + return s; +} + +// SOURCE FILE +yy.Source.prototype.execute = function (databaseid,params,cb) { +// console.log(this.url); + var res; + loadFile(this.url, !!cb, function(data){ +// console.log(data); +// res = 1; + res = alasql(data); + if(cb) res = cb(res); + return res; + }, function(err){ + throw err; + }); + return res; +}; + + +/* +// +// HELP for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +yy.Require = function (params) { return yy.extend(this, params); } +yy.Require.prototype.toString = function() { + var s = K('REQUIRE'); + if(this.paths && this.paths.length > 0) { + s += this.paths.map(function(path){ + return path.toString() + }).join(','); + } + return s; +} + +/** + Attach plug-in for Alasql + */ +yy.Require.prototype.execute = function (databaseid,params,cb) { + var self = this; + var res = 0; + var ss = ''; +// console.log(this.paths); + if(this.paths.length > 0) { + this.paths.forEach(function(path){ + loadFile(path.value, !!cb, function(data){ + res++; +// console.log(res,self.paths.length); +// console.log(data); + ss += data; + if(res",right:$$[$0]});break;case 277:this.$=new yy.Op({left:$$[$0-4],op:"->",right:$$[$0-1]});break;case 279:this.$=new yy.Op({left:$$[$0-2],op:">",right:$$[$0]});break;case 280:this.$=new yy.Op({left:$$[$0-2],op:">=",right:$$[$0]});break;case 281:this.$=new yy.Op({left:$$[$0-2],op:"<",right:$$[$0]});break;case 282:this.$=new yy.Op({left:$$[$0-2],op:"<=",right:$$[$0]});break;case 283:this.$=new yy.Op({left:$$[$0-2],op:"=",right:$$[$0]});break;case 284:this.$=new yy.Op({left:$$[$0-2],op:"==",right:$$[$0]});break;case 285:this.$=new yy.Op({left:$$[$0-2],op:"===",right:$$[$0]});break;case 286:this.$=new yy.Op({left:$$[$0-2],op:"!=",right:$$[$0]});break;case 287:this.$=new yy.Op({left:$$[$0-2],op:"!==",right:$$[$0]});break;case 288:this.$=new yy.Op({left:$$[$0-2],op:"!===",right:$$[$0]});break;case 289:if(!yy.queries)yy.queries=[];this.$=new yy.Op({left:$$[$0-5],op:$$[$0-4],allsome:$$[$0-3],right:$$[$0-1],queriesidx:yy.queries.length});yy.queries.push($$[$0-1]);break;case 290:this.$=new yy.Op({left:$$[$0-5],op:$$[$0-4],allsome:$$[$0-3],right:$$[$0-1]});break;case 291:this.$=new yy.Op({left:$$[$0-2],op:"AND",right:$$[$0]});break;case 292:this.$=new yy.Op({left:$$[$0-2],op:"OR",right:$$[$0]});break;case 293:this.$=new yy.UniOp({op:"NOT",right:$$[$0]});break;case 294:this.$=new yy.UniOp({op:"-",right:$$[$0]});break;case 295:this.$=new yy.UniOp({op:"+",right:$$[$0]});break;case 296:this.$=new yy.UniOp({right:$$[$0-1]});break;case 297:if(!yy.queries)yy.queries=[];this.$=new yy.Op({left:$$[$0-4],op:"IN",right:$$[$0-1],queriesidx:yy.queries.length});yy.queries.push($$[$0-1]);break;case 298:if(!yy.queries)yy.queries=[];this.$=new yy.Op({left:$$[$0-5],op:"NOT IN",right:$$[$0-1],queriesidx:yy.queries.length});yy.queries.push($$[$0-1]);break;case 299:this.$=new yy.Op({left:$$[$0-4],op:"IN",right:$$[$0-1]});break;case 300:this.$=new yy.Op({left:$$[$0-5],op:"NOT IN",right:$$[$0-1]});break;case 301:this.$=new yy.Op({left:$$[$0-3],op:"IN",right:[]});break;case 302:this.$=new yy.Op({left:$$[$0-4],op:"NOT IN",right:[]});break;case 303:this.$=new yy.Op({left:$$[$0-2],op:"IN",right:$$[$0]});break;case 304:this.$=new yy.Op({left:$$[$0-3],op:"NOT IN",right:$$[$0]});break;case 305:this.$=new yy.Op({left:$$[$0-2],op:"BETWEEN",right:$$[$0]});break;case 306:this.$=new yy.Op({left:$$[$0-2],op:"NOT BETWEEN",right:$$[$0]});break;case 307:this.$=new yy.Op({op:"IS",left:$$[$0-2],right:$$[$0]});break;case 308:this.$=new yy.Convert({expression:$$[$0-2]});yy.extend(this.$,$$[$0]);break;case 309:case 310:this.$=$$[$0];break;case 311:this.$=$$[$0-1];break;case 318:this.$="ALL";break;case 319:this.$="SOME";break;case 320:this.$="ANY";break;case 321:this.$=new yy.Update({table:$$[$0-4],columns:$$[$0-2],where:$$[$0]});break;case 322:this.$=new yy.Update({table:$$[$0-2],columns:$$[$0]});break;case 325:this.$=new yy.SetColumn({columnid:$$[$0-2],expression:$$[$0]});break;case 326:this.$=new yy.Delete({table:$$[$0-2],where:$$[$0]});break;case 327:this.$=new yy.Delete({table:$$[$0]});break;case 328:this.$=new yy.Insert({into:$$[$0-2],values:$$[$0]});break;case 329:this.$=new yy.Insert({into:$$[$0-2],"default":true});break;case 330:this.$=new yy.Insert({into:$$[$0-5],columns:$$[$0-3],values:$$[$0]});break;case 331:this.$=new yy.Insert({into:$$[$0-1],select:$$[$0]});break;case 332:this.$=new yy.Insert({into:$$[$0-4],columns:$$[$0-2],select:$$[$0]});break;case 335:this.$=[$$[$0-1]];break;case 338:this.$=$$[$0-4];$$[$0-4].push($$[$0-1]);break;case 339:case 340:case 342:case 350:this.$=$$[$0-2];$$[$0-2].push($$[$0]);break;case 351:this.$=new yy.CreateTable({table:$$[$0-4]});yy.extend(this.$,$$[$0-5]);yy.extend(this.$,$$[$0-2]);break;case 352:this.$=new yy.CreateTable({table:$$[$0]});break;case 362:case 363:this.$={temporary:true};break;case 365:this.$={ifnotexists:true};break;case 366:this.$={columns:$$[$0-2],constraints:$$[$0]};break;case 367:this.$={columns:$$[$0]};break;case 368:this.$={as:$$[$0]};break;case 369:case 392:this.$=[$$[$0]];break;case 370:case 393:case 496:case 501:case 521:case 525:$$[$0-2].push($$[$0]);this.$=$$[$0-2];break;case 371:case 372:case 373:case 374:case 375:$$[$0].constraintid=$$[$0-1];this.$=$$[$0];break;case 378:this.$={type:"CHECK",expression:$$[$0-1]};break;case 379:this.$={type:"PRIMARY KEY",columns:$$[$0-1]};break;case 380:this.$={type:"FOREIGN KEY",columns:$$[$0-7],fktableid:$$[$0-4],fkcolumns:$$[$0-2]};break;case 394:this.$=new yy.ColumnDef({columnid:$$[$0-2]});yy.extend(this.$,$$[$0-1]);yy.extend(this.$,$$[$0]);break;case 395:this.$=new yy.ColumnDef({columnid:$$[$0-1]});yy.extend(this.$,$$[$0]);break;case 396:this.$=new yy.ColumnDef({columnid:$$[$0],dbtypeid:""});break;case 397:this.$={dbtypeid:$$[$0-5],dbsize:+$$[$0-3],dbprecision:+$$[$0-1]};break;case 398:this.$={dbtypeid:$$[$0-3],dbsize:+$$[$0-1]};break;case 399:this.$={dbtypeid:$$[$0]};break;case 400:this.$={dbtypeid:"ENUM",enumvalues:$$[$0-1]};break;case 401:this.$=undefined;break;case 403:yy.extend($$[$0-1],$$[$0]);this.$=$$[$0-1];break;case 405:this.$={primarykey:true};break;case 406:case 407:this.$={foreignkey:{tableid:$$[$0-3],columnid:$$[$0-1]}};break;case 408:this.$={auto_increment:true};break;case 409:this.$={identity:[$$[$0-3],$$[$0-1]]};break;case 410:this.$={identity:[1,1]};break;case 411:this.$={"default":$$[$0]};break;case 412:this.$={"null":true};break;case 413:this.$={notnull:true};break;case 414:this.$=$$[$0];break;case 415:this.$=new yy.DropTable({table:$$[$0]});yy.extend(this.$,$$[$0-1]);break;case 417:this.$={ifexists:true};break;case 418:this.$=new yy.AlterTable({table:$$[$0-3],renameto:$$[$0]});break;case 419:this.$=new yy.AlterTable({table:$$[$0-3],addcolumn:$$[$0]});break;case 420:this.$=new yy.AlterTable({table:$$[$0-3],modifycolumn:$$[$0]});break;case 421:this.$=new yy.AlterTable({table:$$[$0-5],renamecolumn:$$[$0-2],to:$$[$0]});break;case 422:this.$=new yy.AlterTable({table:$$[$0-3],dropcolumn:$$[$0]});break;case 423:this.$=new yy.AlterTable({table:$$[$0-2],renameto:$$[$0]});break;case 424:this.$=new yy.AttachDatabase({databaseid:$$[$0],engineid:$$[$0-2].toUpperCase()});break;case 425:this.$=new yy.AttachDatabase({databaseid:$$[$0-3],engineid:$$[$0-5].toUpperCase(),args:$$[$0-1]});break;case 426:this.$=new yy.AttachDatabase({databaseid:$$[$0-2],engineid:$$[$0-4].toUpperCase(),as:$$[$0]});break;case 427:this.$=new yy.AttachDatabase({databaseid:$$[$0-5],engineid:$$[$0-7].toUpperCase(),as:$$[$0],args:$$[$0-3]});break;case 428:this.$=new yy.DetachDatabase({databaseid:$$[$0]});break;case 429:this.$=new yy.CreateDatabase({databaseid:$$[$0]});yy.extend(this.$,$$[$0]);break;case 430:this.$=new yy.CreateDatabase({engineid:$$[$0-4].toUpperCase(),databaseid:$$[$0-1],as:$$[$0]});yy.extend(this.$,$$[$0-2]);break;case 431:this.$=new yy.CreateDatabase({engineid:$$[$0-7].toUpperCase(),databaseid:$$[$0-4],args:$$[$0-2],as:$$[$0]});yy.extend(this.$,$$[$0-5]);break;case 432:this.$=new yy.CreateDatabase({engineid:$$[$0-4].toUpperCase(),as:$$[$0],args:[$$[$0-1]]});yy.extend(this.$,$$[$0-2]);break;case 433:this.$=undefined;break;case 434:case 467:case 485:case 488:case 505:this.$=$$[$0-1];break;case 435:case 436:this.$=new yy.UseDatabase({databaseid:$$[$0]});break;case 437:this.$=new yy.DropDatabase({databaseid:$$[$0]});yy.extend(this.$,$$[$0-1]);break;case 438:case 439:this.$=new yy.DropDatabase({databaseid:$$[$0],engineid:$$[$0-3].toUpperCase()});yy.extend(this.$,$$[$0-1]);break;case 440:this.$=new yy.CreateIndex({indexid:$$[$0-5],table:$$[$0-3],columns:$$[$0-1]});break;case 441:this.$=new yy.CreateIndex({indexid:$$[$0-5],table:$$[$0-3],columns:$$[$0-1],unique:true});break;case 442:this.$=new yy.DropIndex({indexid:$$[$0]});break;case 443:this.$=new yy.ShowDatabases;break;case 444:this.$=new yy.ShowDatabases({like:$$[$0]});break;case 445:this.$=new yy.ShowDatabases({engineid:$$[$0-1].toUpperCase()});break;case 446:this.$=new yy.ShowDatabases({engineid:$$[$0-3].toUpperCase(),like:$$[$0]});break;case 447:this.$=new yy.ShowTables;break;case 448:this.$=new yy.ShowTables({like:$$[$0]});break;case 449:this.$=new yy.ShowTables({databaseid:$$[$0]});break;case 450:this.$=new yy.ShowTables({like:$$[$0],databaseid:$$[$0-2]});break;case 451:this.$=new yy.ShowColumns({table:$$[$0]});break;case 452:this.$=new yy.ShowColumns({table:$$[$0-2],databaseid:$$[$0]});break;case 453:this.$=new yy.ShowIndex({table:$$[$0]});break;case 454:this.$=new yy.ShowIndex({table:$$[$0-2],databaseid:$$[$0]});break;case 455:this.$=new yy.ShowCreateTable({table:$$[$0]});break;case 456:this.$=new yy.ShowCreateTable({table:$$[$0-2],databaseid:$$[$0]});break;case 457:this.$=new yy.CreateTable({table:$$[$0-5],view:true,select:$$[$0],viewcolumns:$$[$0-3]});yy.extend(this.$,$$[$0-6]);break;case 458:this.$=new yy.CreateTable({table:$$[$0-2],view:true,select:$$[$0]});break;case 459:this.$=new yy.DropTable({table:$$[$0],view:true});yy.extend(this.$,$$[$0-1]);break;case 460:this.$=new yy.Help({subject:$$[$0].value.toUpperCase()});break;case 461:this.$=new yy.Help;break;case 462:this.$=new yy.ExpressionStatement({expression:$$[$0]});break;case 463:this.$=new yy.Source({url:$$[$0].value});break;case 464:this.$=new yy.Assert({value:$$[$0]});break;case 465:this.$=new yy.Assert({value:$$[$0].value});break;case 466:this.$=new yy.Assert({value:$$[$0],message:$$[$0-2]});break;case 468:case 479:case 481:this.$=$$[$0].value;break;case 469:case 477:this.$=+$$[$0].value;break;case 470:this.$=!!$$[$0].value;break;case 478:this.$=""+$$[$0].value;break;case 484:this.$=$$[$0-1];break;case 486:case 489:this.$=$$[$0-2];break;case 487:this.$={};break;case 490:this.$=[];break;case 491:yy.extend($$[$0-2],$$[$0]);this.$=$$[$0-2];break;case 493:this.$={};this.$[$$[$0-2].substr(1,$$[$0-2].length-2)]=$$[$0];break;case 494:case 495:this.$={};this.$[$$[$0-2]]=$$[$0];break;case 498:this.$=new yy.SetVariable({variable:$$[$0-1].toLowerCase(),value:$$[$0]});break;case 499:this.$=new yy.SetVariable({variable:$$[$0-2],expression:$$[$0]});break;case 500:this.$=new yy.SetVariable({variable:$$[$0-3],props:$$[$0-2],expression:$$[$0]});break;case 506:this.$=true;break;case 507:this.$=false;break;case 508:this.$=new yy.CommitTransaction;break;case 509:this.$=new yy.RollbackTransaction;break;case 510:this.$=new yy.BeginTransaction;break;case 511: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 512:this.$=new yy.If({expression:$$[$0-1],thenstat:$$[$0]});break;case 513:this.$=$$[$0];break;case 514: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 515:this.$=new yy.Continue;break;case 516:this.$=new yy.Break;break;case 517:this.$=new yy.BeginEnd({statements:$$[$0-1]});break;case 518:case 519:this.$=new yy.Print({statement:$$[$0]});break;case 520:this.$=new yy.Require({paths:$$[$0]});break;case 523:this.$=new yy.Declare({declares:$$[$0]});break;case 526:this.$={variable:$$[$0-1]};yy.extend(this.$,$$[$0]);break;case 527:this.$={variable:$$[$0-2]};yy.extend(this.$,$$[$0]);break;case 528:this.$={variable:$$[$0-3],expression:$$[$0]};yy.extend(this.$,$$[$0-2]);break;case 529:this.$={variable:$$[$0-4],expression:$$[$0]};yy.extend(this.$,$$[$0-2]);break;case 530:this.$=new yy.TruncateTable({table:$$[$0]});break;case 531: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 532:case 533:this.$={into:$$[$0]};break;case 535:this.$={on:$$[$0]};break;case 540:this.$={matched:true,action:$$[$0]};break;case 541:this.$={matched:true,expr:$$[$0-2],action:$$[$0]};break;case 542:this.$={"delete":true};break;case 543:this.$={update:$$[$0]};break;case 544:case 545:this.$={matched:false,bytarget:true,action:$$[$0]};break;case 546:case 547:this.$={matched:false,bytarget:true,expr:$$[$0-2],action:$$[$0]};break;case 548:this.$={matched:false,bysource:true,action:$$[$0]};break;case 549:this.$={matched:false,bysource:true,expr:$$[$0-2],action:$$[$0]};break;case 550:this.$={insert:true,values:$$[$0]};break;case 551:this.$={insert:true,values:$$[$0],columns:$$[$0-3]};break;case 552:this.$={insert:true,defaultvalues:true};break;case 553:this.$={insert:true,defaultvalues:true,columns:$$[$0-3]};break;case 555:this.$={output:{columns:$$[$0]}};break;case 556:this.$={output:{columns:$$[$0-3],intovar:$$[$0]}};break;case 557:this.$={output:{columns:$$[$0-2],intotable:$$[$0]}};break;case 558:this.$={output:{columns:$$[$0-5],intotable:$$[$0-3],intocolumns:$$[$0-1]}};break}},table:[o([8,9,11],$V0,{6:1,7:2,10:3,12:4,16:5,17:7,18:8,19:9,20:10,21:11,22:12,23:13,24:14,25:15,26:16,27:17,28:18,29:19,30:20,31:21,32:22,33:23,34:24,35:25,36:26,37:27,38:28,39:29,40:30,41:31,42:32,43:33,44:34,46:36,47:37,48:38,49:39,50:40,51:41,52:42,53:43,54:44,55:45,56:46,57:47,58:48,66:59,74:79,13:$V1,45:$V2,59:$V3,80:$V4,165:$V5,237:$V6,238:$V7,241:$V8,242:$V9,250:$Va,263:$Vb,292:$Vc,294:$Vd,295:$Ve,299:$Vf,301:$Vg,303:$Vh,304:$Vi,309:$Vj,311:$Vk,312:$Vl,328:$Vm,330:$Vn,331:$Vo,333:$Vp,334:$Vq,335:$Vr,336:$Vs,337:$Vt,339:$Vu,342:$Vv,343:$Vw}),{1:[3]},{8:[1,81],9:$Vx,11:$Vy},o($Vz,[2,6]),o($Vz,[2,7]),o($VA,[2,10]),o($Vz,$V0,{16:5,17:7,18:8,19:9,20:10,21:11,22:12,23:13,24:14,25:15,26:16,27:17,28:18,29:19,30:20,31:21,32:22,33:23,34:24,35:25,36:26,37:27,38:28,39:29,40:30,41:31,42:32,43:33,44:34,46:36,47:37,48:38,49:39,50:40,51:41,52:42,53:43,54:44,55:45,56:46,57:47,58:48,66:59,74:79,10:84,14:[1,85],45:$V2,59:$V3,80:$V4,165:$V5,237:$V6,238:$V7,241:$V8,242:$V9,250:$Va,263:$Vb,292:$Vc,294:$Vd,295:$Ve,299:$Vf,301:$Vg,303:$Vh,304:$Vi,309:$Vj,311:$Vk,312:$Vl,328:$Vm,330:$Vn,331:$Vo,333:$Vp,334:$Vq,335:$Vr,336:$Vs,337:$Vt,339:$Vu,342:$Vv,343:$Vw}),o($VA,[2,12]),o($VA,[2,13]),o($VA,[2,14]),o($VA,[2,15]),o($VA,[2,16]),o($VA,[2,17]),o($VA,[2,18]),o($VA,[2,19]),o($VA,[2,20]),o($VA,[2,21]),o($VA,[2,22]),o($VA,[2,23]),o($VA,[2,24]),o($VA,[2,25]),o($VA,[2,26]),o($VA,[2,27]),o($VA,[2,28]),o($VA,[2,29]),o($VA,[2,30]),o($VA,[2,31]),o($VA,[2,32]),o($VA,[2,33]),o($VA,[2,34]),o($VA,[2,35]),o($VA,[2,36]),o($VA,[2,37]),o($VA,[2,38]),o($VA,[2,39]),o($VA,[2,40]),o($VA,[2,41]),o($VA,[2,42]),o($VA,[2,43]),o($VA,[2,44]),o($VA,[2,45]),o($VA,[2,46]),o($VA,[2,47]),o($VA,[2,48]),o($VA,[2,49]),o($VA,[2,50]),o($VA,[2,51]),o($VA,[2,52]),o($VA,[2,53]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:86,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{251:[1,141]},{3:142,4:$VB,5:$VC},{3:144,4:$VB,5:$VC,78:[1,146],86:[1,145],251:[1,147],300:[1,143],308:[1,148]},{192:$V71,340:149,341:150},{97:[1,152]},{300:[1,153]},{3:155,4:$VB,5:$VC,86:[1,156],251:[1,157],300:[1,154],308:[1,158]},o($V81,[2,333],{243:159,91:[1,160]}),{251:[1,161]},o($V91,[2,75],{67:162,91:[1,163]}),{3:173,4:$VB,5:$VC,64:$Va1,91:[1,166],92:168,93:170,94:169,95:171,96:$Vb1,99:165,105:172,192:$Vc1,194:$VZ,195:$V_,196:$V$,197:$V01,344:164},{3:178,4:$VB,5:$VC,60:176,62:177},{3:182,4:$VB,5:$VC,86:[1,183],250:[1,179],305:[1,181],306:[1,184],307:[1,180]},{251:[1,185]},o([9,11,201],$V0,{10:3,12:4,16:5,17:7,18:8,19:9,20:10,21:11,22:12,23:13,24:14,25:15,26:16,27:17,28:18,29:19,30:20,31:21,32:22,33:23,34:24,35:25,36:26,37:27,38:28,39:29,40:30,41:31,42:32,43:33,44:34,46:36,47:37,48:38,49:39,50:40,51:41,52:42,53:43,54:44,55:45,56:46,57:47,58:48,66:59,74:79,7:187,13:$V1,45:$V2,59:$V3,80:$V4,165:$V5,237:$V6,238:$V7,241:$V8,242:$V9,250:$Va,263:$Vb,292:$Vc,294:$Vd,295:$Ve,299:$Vf,301:$Vg,303:$Vh,304:$Vi,309:$Vj,311:$Vk,312:$Vl,328:$Vm,329:[1,186],330:$Vn,331:$Vo,333:$Vp,334:$Vq,335:$Vr,336:$Vs,337:$Vt,339:$Vu,342:$Vv,343:$Vw}),{329:[1,188]},{329:[1,189]},{3:191,4:$VB,5:$VC,300:[1,190]},{3:193,4:$VB,5:$VC,92:192},o($VA,[2,461],{152:194,96:$VE,190:$VV}),o($Vd1,[2,212]),{96:$VE,152:195,190:$VV},{3:207,4:$VB,5:$VC,89:200,93:205,94:204,96:[1,198],151:$VF,152:201,158:202,159:203,163:196,170:197,171:$Ve1,188:$VT,189:$VU,190:$VV,191:$VW,192:$Vf1,194:$VZ,195:$V_,196:$V$,197:$V01,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:208,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($VA,[2,515]),o($VA,[2,516]),{3:106,4:$VB,5:$VC,33:209,49:104,64:$VD,66:59,74:79,80:$V4,89:92,93:88,94:96,95:97,96:$VE,121:211,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,310:210,313:126,314:$V51,318:$V61},{96:$VE,152:213,190:$VV,338:212},{3:214,4:$VB,5:$VC,192:[1,215]},o($Vg1,$Vh1,{76:219,75:[1,216],78:[1,217],79:[1,218],88:$Vi1}),o($Vj1,[2,63],{81:[1,221],82:[1,222],83:[1,223],84:[1,224],85:[1,225],86:[1,226],87:[1,227]}),{1:[2,3]},o($Vz,$V0,{16:5,17:7,18:8,19:9,20:10,21:11,22:12,23:13,24:14,25:15,26:16,27:17,28:18,29:19,30:20,31:21,32:22,33:23,34:24,35:25,36:26,37:27,38:28,39:29,40:30,41:31,42:32,43:33,44:34,46:36,47:37,48:38,49:39,50:40,51:41,52:42,53:43,54:44,55:45,56:46,57:47,58:48,66:59,74:79,10:228,45:$V2,59:$V3,80:$V4,165:$V5,237:$V6,238:$V7,241:$V8,242:$V9,250:$Va,263:$Vb,292:$Vc,294:$Vd,295:$Ve,299:$Vf,301:$Vg,303:$Vh,304:$Vi,309:$Vj,311:$Vk,312:$Vl,328:$Vm,330:$Vn,331:$Vo,333:$Vp,334:$Vq,335:$Vr,336:$Vs,337:$Vt,339:$Vu,342:$Vv,343:$Vw}),o($Vz,$V0,{16:5,17:7,18:8,19:9,20:10,21:11,22:12,23:13,24:14,25:15,26:16,27:17,28:18,29:19,30:20,31:21,32:22,33:23,34:24,35:25,36:26,37:27,38:28,39:29,40:30,41:31,42:32,43:33,44:34,46:36,47:37,48:38,49:39,50:40,51:41,52:42,53:43,54:44,55:45,56:46,57:47,58:48,66:59,74:79,10:229,45:$V2,59:$V3,80:$V4,165:$V5,237:$V6,238:$V7,241:$V8,242:$V9,250:$Va,263:$Vb,292:$Vc,294:$Vd,295:$Ve,299:$Vf,301:$Vg,303:$Vh,304:$Vi,309:$Vj,311:$Vk,312:$Vl,328:$Vm,330:$Vn,331:$Vo,333:$Vp,334:$Vq,335:$Vr,336:$Vs,337:$Vt,339:$Vu,342:$Vv,343:$Vw}),o($Vz,[2,8]),{15:[1,230]},o($VA,$V0,{16:5,17:7,18:8,19:9,20:10,21:11,22:12,23:13,24:14,25:15,26:16,27:17,28:18,29:19,30:20,31:21,32:22,33:23,34:24,35:25,36:26,37:27,38:28,39:29,40:30,41:31,42:32,43:33,44:34,46:36,47:37,48:38,49:39,50:40,51:41,52:42,53:43,54:44,55:45,56:46,57:47,58:48,66:59,74:79,10:231,224:251,45:$V2,59:$V3,80:$V4,154:$Vk1,165:$V5,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1,237:$V6,238:$V7,241:$V8,242:$V9,250:$Va,263:$Vb,292:$Vc,294:$Vd,295:$Ve,299:$Vf,301:$Vg,303:$Vh,304:$Vi,309:$Vj,311:$Vk,312:$Vl,328:$Vm,330:$Vn,331:$Vo,333:$Vp,334:$Vq,335:$Vr,336:$Vs,337:$Vt,339:$Vu,342:$Vv,343:$Vw}),o($Vd1,[2,194]),o($Vd1,[2,195]),o($Vd1,[2,196]),o($Vd1,[2,197]),o($Vd1,[2,198]),o($Vd1,[2,199]),o($Vd1,[2,200]),o($Vd1,[2,201]),o($Vd1,[2,202]),o($Vd1,[2,203]),o($Vd1,[2,204]),o($Vd1,[2,205]),o($Vd1,[2,206]),o($Vd1,[2,207]),o($Vd1,[2,208]),o($Vd1,[2,209]),{3:106,4:$VB,5:$VC,33:260,49:104,64:$VD,66:59,74:79,80:$V4,89:92,93:88,94:96,95:97,96:$VE,121:261,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($Vd1,[2,211]),{64:[1,262]},o($Vd1,$VL1,{64:$VM1,106:[1,264]}),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:265,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:266,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:267,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($Vd1,[2,189]),o([4,5,8,9,11,45,59,61,63,64,65,80,90,91,96,97,102,104,112,113,114,115,116,117,118,119,124,125,134,135,136,137,138,141,142,144,146,149,150,151,154,165,166,167,169,178,179,180,181,182,183,184,185,186,188,189,190,191,192,193,194,195,196,197,198,201,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,226,227,228,229,231,232,233,234,237,238,241,242,246,250,257,258,259,263,274,275,278,279,291,292,294,295,299,301,303,304,309,311,312,314,318,320,322,328,330,331,333,334,335,336,337,339,342,343,355],[2,248]),o($VN1,[2,249]),o($VN1,[2,250]),o($VN1,$VO1),o($VN1,[2,252]),o($VN1,[2,253]),{3:268,4:$VB,5:$VC},{3:269,4:$VB,5:$VC},o($VP1,[2,258]),o($VP1,[2,259]),{3:270,4:$VB,5:$VC,64:$VQ1,89:273,94:275,96:$VE,151:$VF,152:272,158:274,188:$VT,189:$VU,190:$VV,194:$VZ,195:$V_,196:$V$,197:$V01,313:276,318:$V61},{64:[1,277]},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:278,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,199:279,202:280,203:$VR1,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{64:[1,282]},{64:[1,283]},o($VS1,[2,472]),{3:298,4:$VB,5:$VC,64:$VT1,89:290,93:296,94:295,96:$VE,151:$VF,152:291,155:293,158:292,159:294,163:288,188:$VT,189:$VU,190:$VV,191:$VW,192:$Vf1,194:$VZ,195:$V_,196:$V$,197:$V01,313:126,314:$V51,315:284,316:287,317:289,318:$V61,321:285,322:[1,286]},{3:299,4:$VB,5:$VC,93:300},{64:[2,235]},{64:[2,236]},{64:[2,237]},{64:[2,238]},{64:[2,239]},{64:[2,240]},{64:[2,241]},{64:[2,242]},{64:[2,243]},o($VU1,[2,1]),o($VU1,[2,2]),{3:306,4:$VB,5:$VC,96:$VV1,151:$VW1,319:301,320:[1,302],323:303},{3:193,4:$VB,5:$VC,92:307},{300:[1,308]},o($V81,$VX1,{252:309,263:$VY1}),{300:[1,311]},{3:312,4:$VB,5:$VC},{86:[1,313]},o($V81,$VX1,{252:314,263:$VY1}),o($V81,$VX1,{252:315,263:$VY1}),o($VA,[2,523],{61:[1,316]}),o($VZ1,[2,524]),{3:317,4:$VB,5:$VC},{3:193,4:$VB,5:$VC,92:318},{3:319,4:$VB,5:$VC},o($V81,$V_1,{293:320,263:$V$1}),{300:[1,322]},{3:323,4:$VB,5:$VC},o($V81,$V_1,{293:324,263:$V$1}),o($V81,$V_1,{293:325,263:$V$1}),{3:193,4:$VB,5:$VC,92:326},o($V81,[2,334]),{3:193,4:$VB,5:$VC,92:327},o($V02,[2,83],{68:328,97:[1,329]}),{3:173,4:$VB,5:$VC,92:330,93:331,94:332,95:333,96:[1,334],192:$Vc1,194:$VZ,195:$V_,196:$V$,197:$V01},{122:[1,336],345:335},{122:[2,532]},{3:173,4:$VB,5:$VC,64:$Va1,92:168,93:170,94:169,95:171,96:$Vb1,99:337,105:172,192:$Vc1,194:$VZ,195:$V_,196:$V$,197:$V01},{33:338,66:59,74:79,80:$V4},o($V12,[2,95],{3:339,4:$VB,5:$VC,63:[1,340]}),o($V12,[2,98],{3:341,4:$VB,5:$VC,63:[1,342]}),o($V12,[2,99],{3:343,4:$VB,5:$VC,63:[1,344]}),o($V12,[2,102],{3:345,4:$VB,5:$VC,63:[1,346]}),o($V12,[2,105],{3:347,4:$VB,5:$VC,63:[1,348]}),o([4,5,8,9,11,61,63,65,97,102,104,112,113,114,115,116,117,118,119,120,122,124,125,135,136,137,138,144,201,205],$V22,{64:$VM1,106:$V32}),{3:270,4:$VB,5:$VC},o([4,5,8,9,11,61,63,65,102,104,112,113,114,115,116,117,118,119,120,122,124,125,135,136,137,138,144,201,205],[2,108]),{33:350,61:[1,351],66:59,74:79,80:$V4},o($V42,[2,56]),{63:[1,352]},{251:[1,353]},{97:[1,354]},o($VA,[2,443],{206:[1,355]}),{305:[1,356]},{97:[1,357]},o($VA,[2,447],{97:[1,359],206:[1,358]}),{3:193,4:$VB,5:$VC,92:360},o($VA,[2,510]),{9:$Vx,11:$Vy,201:[1,361]},o($VA,[2,508]),o($VA,[2,509]),{3:362,4:$VB,5:$VC},o($VA,[2,436]),{238:[1,363]},o([8,9,11,63,64,80,97,124,201,205,238,244,246,292,295,296,297,298],$V22,{106:$V32}),o($VA,[2,460]),o($VA,[2,463]),o($VA,[2,464]),o($VA,[2,465]),o($VA,$VO1,{61:[1,364]}),{64:$VQ1,89:273,94:275,96:$VE,151:$VF,152:272,158:274,188:$VT,189:$VU,190:$VV,194:$VZ,195:$V_,196:$V$,197:$V01,313:276,318:$V61},o($V52,[2,219]),o($V52,[2,220]),o($V52,[2,221]),o($V52,[2,222]),o($V52,[2,223]),o($V52,[2,224]),o($V52,[2,225]),{64:$VM1},o($VA,$V0,{16:5,17:7,18:8,19:9,20:10,21:11,22:12,23:13,24:14,25:15,26:16,27:17,28:18,29:19,30:20,31:21,32:22,33:23,34:24,35:25,36:26,37:27,38:28,39:29,40:30,41:31,42:32,43:33,44:34,46:36,47:37,48:38,49:39,50:40,51:41,52:42,53:43,54:44,55:45,56:46,57:47,58:48,66:59,74:79,224:251,10:365,45:$V2,59:$V3,80:$V4,154:$Vk1,165:$V5,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1,237:$V6,238:$V7,241:$V8,242:$V9,250:$Va,263:$Vb,292:$Vc,294:$Vd,295:$Ve,299:$Vf,301:$Vg,303:$Vh,304:$Vi,309:$Vj,311:$Vk,312:$Vl,328:$Vm,330:$Vn,331:$Vo,333:$Vp,334:$Vq,335:$Vr,336:$Vs,337:$Vt,339:$Vu,342:$Vv,343:$Vw}),o($VA,[2,518]),o($VA,[2,519]),o($VA,[2,462],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),o($VA,[2,520],{61:[1,366]}),o($VZ1,[2,522]),{120:[1,368],324:367,327:[1,369]},{3:370,4:$VB,5:$VC},o($Vg1,$Vh1,{76:371,88:$Vi1}),o($Vg1,$Vh1,{76:372,88:$Vi1}),o($Vg1,$Vh1,{76:373,88:$Vi1}),{3:106,4:$VB,5:$VC,49:104,64:$VD,77:374,89:92,93:88,94:96,95:97,96:$VE,121:376,147:375,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{64:[1,378],89:377,151:$VF},o($Vj1,[2,64]),o($Vj1,[2,65]),o($Vj1,[2,66]),o($Vj1,[2,67]),o($Vj1,[2,68]),o($Vj1,[2,69]),o($Vj1,[2,70]),o($Vz,[2,4]),o($Vz,[2,5]),o($Vz,$V0,{16:5,17:7,18:8,19:9,20:10,21:11,22:12,23:13,24:14,25:15,26:16,27:17,28:18,29:19,30:20,31:21,32:22,33:23,34:24,35:25,36:26,37:27,38:28,39:29,40:30,41:31,42:32,43:33,44:34,46:36,47:37,48:38,49:39,50:40,51:41,52:42,53:43,54:44,55:45,56:46,57:47,58:48,66:59,74:79,10:379,45:$V2,59:$V3,80:$V4,165:$V5,237:$V6,238:$V7,241:$V8,242:$V9,250:$Va,263:$Vb,292:$Vc,294:$Vd,295:$Ve,299:$Vf,301:$Vg,303:$Vh,304:$Vi,309:$Vj,311:$Vk,312:$Vl,328:$Vm,330:$Vn,331:$Vo,333:$Vp,334:$Vq,335:$Vr,336:$Vs,337:$Vt,339:$Vu,342:$Vv,343:$Vw}),o($Vz,[2,512],{332:380,205:[1,381]}),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:382,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:383,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:384,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:385,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:386,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:387,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:388,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:389,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:390,4:$VB,5:$VC,64:[1,392],89:391,93:393,151:$VF},o($V62,[2,312],{156:87,93:88,157:89,155:90,153:91,89:92,158:93,152:94,159:95,94:96,95:97,160:98,161:99,162:100,163:101,164:102,49:104,172:105,3:106,313:126,121:394,4:$VB,5:$VC,64:$VD,96:$VE,151:$VF,154:$VG,165:$V5,166:$VH,167:$VI,169:$VJ,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,314:$V51,318:$V61}),o($V62,[2,313],{156:87,93:88,157:89,155:90,153:91,89:92,158:93,152:94,159:95,94:96,95:97,160:98,161:99,162:100,163:101,164:102,49:104,172:105,3:106,313:126,121:395,4:$VB,5:$VC,64:$VD,96:$VE,151:$VF,154:$VG,165:$V5,166:$VH,167:$VI,169:$VJ,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,314:$V51,318:$V61}),o($V62,[2,314],{156:87,93:88,157:89,155:90,153:91,89:92,158:93,152:94,159:95,94:96,95:97,160:98,161:99,162:100,163:101,164:102,49:104,172:105,3:106,313:126,121:396,4:$VB,5:$VC,64:$VD,96:$VE,151:$VF,154:$VG,165:$V5,166:$VH,167:$VI,169:$VJ,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,314:$V51,318:$V61}),o($V62,[2,315],{156:87,93:88,157:89,155:90,153:91,89:92,158:93,152:94,159:95,94:96,95:97,160:98,161:99,162:100,163:101,164:102,49:104,172:105,3:106,313:126,121:397,4:$VB,5:$VC,64:$VD,96:$VE,151:$VF,154:$VG,165:$V5,166:$VH,167:$VI,169:$VJ,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,314:$V51,318:$V61}),o($V62,[2,316],{156:87,93:88,157:89,155:90,153:91,89:92,158:93,152:94,159:95,94:96,95:97,160:98,161:99,162:100,163:101,164:102,49:104,172:105,3:106,313:126,121:398,4:$VB,5:$VC,64:$VD,96:$VE,151:$VF,154:$VG,165:$V5,166:$VH,167:$VI,169:$VJ,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,314:$V51,318:$V61}),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:399,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:400,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($V62,[2,317],{156:87,93:88,157:89,155:90,153:91,89:92,158:93,152:94,159:95,94:96,95:97,160:98,161:99,162:100,163:101,164:102,49:104,172:105,3:106,313:126,121:401,4:$VB,5:$VC,64:$VD,96:$VE,151:$VF,154:$VG,165:$V5,166:$VH,167:$VI,169:$VJ,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,314:$V51,318:$V61}),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:402,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:403,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{79:[1,405],225:404,235:[1,406],236:[1,407]},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:408,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:409,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:298,4:$VB,5:$VC,64:[1,410],93:413,155:412,192:$V72,230:411},{229:[1,415]},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:416,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:417,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:418,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{4:$V82,168:419,288:$V92},{65:[1,422]},{65:[1,423],154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},{3:106,4:$VB,5:$VC,49:104,64:$VD,75:[1,425],79:[1,426],89:92,93:88,94:96,95:97,96:$VE,121:424,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,65:[1,428],89:92,93:88,94:96,95:97,96:$VE,121:429,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,187:427,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:430,4:$VB,5:$VC,81:$Va2,154:[1,432]},o([4,5,8,9,11,45,59,61,63,65,80,91,96,97,102,104,112,113,114,115,116,117,118,119,124,125,134,135,136,137,138,141,142,144,149,150,151,165,190,201,203,204,205,214,215,216,217,218,219,220,221,222,223,226,227,228,229,231,232,234,237,238,241,242,250,263,292,294,295,299,301,303,304,309,311,312,328,330,331,333,334,335,336,337,339,342,343,355],[2,293],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,233:$VJ1}),o($Vb2,[2,294],{224:251,154:$Vk1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1}),o($Vb2,[2,295],{224:251,154:$Vk1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1}),o($VP1,[2,256]),o($VP1,[2,257]),o([4,5,8,9,11,45,59,61,63,65,80,91,96,97,102,104,112,113,114,115,116,117,118,119,120,122,124,125,134,135,136,137,138,141,142,144,149,150,151,154,165,190,201,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,226,227,228,229,231,232,233,234,237,238,241,242,250,263,292,294,295,299,301,303,304,309,311,312,328,330,331,333,334,335,336,337,339,342,343,355],[2,254]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:433,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($VS1,[2,468]),o($VS1,[2,469]),o($VS1,[2,470]),o($VS1,[2,471]),o($VS1,[2,473]),{33:434,66:59,74:79,80:$V4},{154:$Vk1,199:435,202:280,203:$VR1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},{200:436,201:$Vc2,202:437,203:$VR1,205:$Vd2},o($Ve2,[2,263]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:439,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:440,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{4:$V82,168:441,288:$V92},o($VS1,[2,474]),{61:[1,443],322:[1,442]},o($VS1,[2,490]),o($Vf2,[2,497]),o($Vg2,[2,475]),o($Vg2,[2,476]),o($Vg2,[2,477]),o($Vg2,[2,478]),o($Vg2,[2,479]),o($Vg2,[2,480]),o($Vg2,[2,481]),o($Vg2,[2,482]),o($Vg2,[2,483]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:444,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($VS1,$VL1,{64:$VM1,106:$Vh2}),o($Vd1,[2,213],{64:$VM1}),o($Vd1,[2,214]),{61:[1,447],320:[1,446]},o($VS1,[2,487]),o($Vi2,[2,492]),{195:[1,448]},{195:[1,449]},{195:[1,450]},{292:[1,454],295:[1,451],297:[1,452],298:[1,453]},{3:455,4:$VB,5:$VC},{3:456,4:$VB,5:$VC},{228:[1,457]},o($Vj2,$VX1,{252:458,263:$VY1}),{120:[1,459]},{3:460,4:$VB,5:$VC},{3:193,4:$VB,5:$VC,92:461},{3:193,4:$VB,5:$VC,92:462},{192:$V71,341:463},{4:$V82,63:[1,465],168:464,288:$V92},o($VA,[2,327],{124:[1,466]}),o($VA,[2,428]),{3:467,4:$VB,5:$VC},{193:[1,468]},o($Vj2,$V_1,{293:469,263:$V$1}),o($VA,[2,442]),{3:193,4:$VB,5:$VC,92:470},{3:193,4:$VB,5:$VC,92:471},{33:475,64:[1,474],66:59,74:79,80:$V4,244:[1,472],246:[1,473]},{296:[1,476]},o($Vk2,[2,145],{69:477,124:[1,478]}),{3:173,4:$VB,5:$VC,64:$Va1,92:168,93:170,94:169,95:171,96:$Vb1,98:479,99:480,105:172,192:$Vc1,194:$VZ,195:$V_,196:$V$,197:$V01},o($V91,[2,76]),o($V91,[2,77]),o($V91,[2,78]),o($V91,[2,79]),o($V91,[2,80]),{120:[1,482],346:481},{3:173,4:$VB,5:$VC,64:$Va1,92:168,93:170,94:169,95:171,96:$Vb1,99:483,105:172,192:$Vc1,194:$VZ,195:$V_,196:$V$,197:$V01},{122:[2,533]},{65:[1,484]},o($V12,[2,93]),{3:485,4:$VB,5:$VC},o($V12,[2,96]),{3:486,4:$VB,5:$VC},o($V12,[2,100]),{3:487,4:$VB,5:$VC},o($V12,[2,103]),{3:488,4:$VB,5:$VC},o($V12,[2,106]),{3:489,4:$VB,5:$VC},{3:490,4:$VB,5:$VC},o($VA,[2,54]),{3:178,4:$VB,5:$VC,62:491},{64:[1,492]},{3:193,4:$VB,5:$VC,92:493},{3:193,4:$VB,5:$VC,92:494},{96:$VE,152:495,190:$VV},o($VA,[2,445],{206:[1,496]}),{3:193,4:$VB,5:$VC,92:497},{96:$VE,152:498,190:$VV},{3:499,4:$VB,5:$VC},o($VA,[2,530]),o($VA,[2,517]),o($VA,[2,435]),{3:503,4:$VB,5:$VC,155:502,239:500,240:501},{163:504,192:$Vf1,313:126,314:$V51,318:$V61},o($VA,[2,514]),{96:$VE,152:505,190:$VV},o($VA,[2,498]),o($VA,[2,506]),o($VA,[2,507]),{213:[1,508],218:[1,506],325:507},{3:106,4:$VB,5:$VC,49:104,64:$VD,77:509,89:92,93:88,94:96,95:97,96:$VE,121:376,147:375,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,77:510,89:92,93:88,94:96,95:97,96:$VE,121:376,147:375,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,77:511,89:92,93:88,94:96,95:97,96:$VE,121:376,147:375,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($Vl2,[2,62],{61:$Vm2}),o($Vn2,$Vo2,{148:513,149:$Vp2,150:$Vq2}),o($Vr2,[2,186],{224:251,3:517,152:519,4:$VB,5:$VC,63:[1,516],96:$VE,151:[1,518],154:$Vk1,190:$VV,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),o($Vg1,[2,71],{90:[1,520]}),{89:521,151:$VF},o($Vz,[2,9]),o($VA,[2,511]),o($VA,$V0,{16:5,17:7,18:8,19:9,20:10,21:11,22:12,23:13,24:14,25:15,26:16,27:17,28:18,29:19,30:20,31:21,32:22,33:23,34:24,35:25,36:26,37:27,38:28,39:29,40:30,41:31,42:32,43:33,44:34,46:36,47:37,48:38,49:39,50:40,51:41,52:42,53:43,54:44,55:45,56:46,57:47,58:48,66:59,74:79,10:522,45:$V2,59:$V3,80:$V4,165:$V5,237:$V6,238:$V7,241:$V8,242:$V9,250:$Va,263:$Vb,292:$Vc,294:$Vd,295:$Ve,299:$Vf,301:$Vg,303:$Vh,304:$Vi,309:$Vj,311:$Vk,312:$Vl,328:$Vm,330:$Vn,331:$Vo,333:$Vp,334:$Vq,335:$Vr,336:$Vs,337:$Vt,339:$Vu,342:$Vv,343:$Vw}),o($Vs2,[2,267],{224:251,154:$Vk1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1}),o($Vs2,[2,268],{224:251,154:$Vk1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1}),o($Vb2,[2,269],{224:251,154:$Vk1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1}),o($Vb2,[2,270],{224:251,154:$Vk1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1}),o($Vt2,[2,271],{224:251,212:$Vr1,213:$Vs1}),o($Vt2,[2,272],{224:251,212:$Vr1,213:$Vs1}),o($Vt2,[2,273],{224:251,212:$Vr1,213:$Vs1}),o([4,5,8,9,11,45,59,61,63,65,80,91,96,97,102,104,112,113,114,115,116,117,118,119,124,125,134,135,136,137,138,141,142,144,149,150,151,154,165,190,201,203,204,205,206,207,208,209,210,211,212,214,215,216,217,218,219,220,221,222,223,226,227,228,229,231,232,233,234,237,238,241,242,250,263,292,294,295,299,301,303,304,309,311,312,328,330,331,333,334,335,336,337,339,342,343,355],[2,274],{224:251,213:$Vs1}),o($Vd1,[2,275],{64:$VM1}),o($Vd1,[2,276]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:523,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($Vd1,[2,278]),o($Vu2,[2,279],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,228:$VF1,229:$VG1,233:$VJ1}),o($Vu2,[2,280],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,228:$VF1,229:$VG1,233:$VJ1}),o($Vu2,[2,281],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,228:$VF1,229:$VG1,233:$VJ1}),o($Vu2,[2,282],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,228:$VF1,229:$VG1,233:$VJ1}),o($Vu2,[2,283],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,228:$VF1,229:$VG1,233:$VJ1}),o($Vu2,[2,284],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,228:$VF1,229:$VG1,233:$VJ1}),o($Vu2,[2,285],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,228:$VF1,229:$VG1,233:$VJ1}),o($Vu2,[2,286],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,228:$VF1,229:$VG1,233:$VJ1}),o($Vu2,[2,287],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,228:$VF1,229:$VG1,233:$VJ1}),o($Vu2,[2,288],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,228:$VF1,229:$VG1,233:$VJ1}),{64:[1,524]},{64:[2,318]},{64:[2,319]},{64:[2,320]},o([4,5,8,9,11,45,59,61,63,65,80,91,96,97,102,104,112,113,114,115,116,117,118,119,124,125,134,135,136,137,138,141,142,144,149,150,151,165,190,201,203,204,205,226,227,231,232,234,237,238,241,242,250,263,292,294,295,299,301,303,304,309,311,312,328,330,331,333,334,335,336,337,339,342,343,355],[2,291],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,228:$VF1,229:$VG1,233:$VJ1}),o([4,5,8,9,11,45,59,61,63,65,80,91,96,97,102,104,112,113,114,115,116,117,118,119,124,125,134,135,136,137,138,141,142,144,149,150,151,165,190,201,203,204,205,227,234,237,238,241,242,250,263,292,294,295,299,301,303,304,309,311,312,328,330,331,333,334,335,336,337,339,342,343,355],[2,292],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1}),{3:106,4:$VB,5:$VC,33:525,49:104,64:$VD,65:[1,527],66:59,74:79,80:$V4,89:92,93:88,94:96,95:97,96:$VE,121:429,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,187:526,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($Vd1,[2,303]),o($Vd1,[2,309]),o($Vd1,[2,310]),{64:[1,528]},{3:298,4:$VB,5:$VC,64:[1,529],93:413,155:412,192:$V72,230:530},o($Vv2,[2,305],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,228:$VF1,229:$VG1,233:$VJ1}),o($Vv2,[2,306],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,228:$VF1,229:$VG1,233:$VJ1}),o([4,5,8,9,11,45,59,61,63,65,80,91,96,97,102,104,112,113,114,115,116,117,118,119,124,125,134,135,136,137,138,141,142,144,149,150,151,165,190,201,203,204,205,214,215,216,217,218,219,220,221,222,223,226,227,228,229,231,232,233,234,237,238,241,242,250,263,292,294,295,299,301,303,304,309,311,312,328,330,331,333,334,335,336,337,339,342,343,355],[2,307],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1}),o($Vd1,[2,308]),o($Vw2,[2,399],{64:[1,531]}),{64:[1,532]},o($Vd1,[2,210]),o($Vd1,[2,296]),{65:[1,533],154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:534,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:535,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{61:$Vx2,65:[1,536]},o($VP1,[2,245]),o($Vy2,[2,246],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),o($Vd1,$Vz2,{106:[1,538]}),o($VS1,[2,192]),o($Vd1,[2,188]),{65:[1,539],154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},{65:[1,540]},{200:541,201:$Vc2,202:437,203:$VR1,205:$Vd2},{201:[1,542]},o($Ve2,[2,262]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:543,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{154:$Vk1,204:[1,544],206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},{63:[1,545],154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},{61:[1,546]},o($VS1,[2,488]),{3:298,4:$VB,5:$VC,64:$VT1,89:290,93:296,94:295,96:$VE,151:$VF,152:291,155:293,158:292,159:294,163:288,188:$VT,189:$VU,190:$VV,191:$VW,192:$Vf1,194:$VZ,195:$V_,196:$V$,197:$V01,313:126,314:$V51,316:548,317:289,318:$V61,322:[1,547]},{65:[1,549],154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},{3:550,4:$VB,5:$VC,81:$Va2},o($VS1,[2,485]),{3:306,4:$VB,5:$VC,96:$VV1,151:$VW1,320:[1,551],323:552},{3:298,4:$VB,5:$VC,64:$VT1,89:290,93:296,94:295,96:$VE,151:$VF,152:291,155:293,158:292,159:294,163:288,188:$VT,189:$VU,190:$VV,191:$VW,192:$Vf1,194:$VZ,195:$V_,196:$V$,197:$V01,313:126,314:$V51,316:553,317:289,318:$V61},{3:298,4:$VB,5:$VC,64:$VT1,89:290,93:296,94:295,96:$VE,151:$VF,152:291,155:293,158:292,159:294,163:288,188:$VT,189:$VU,190:$VV,191:$VW,192:$Vf1,194:$VZ,195:$V_,196:$V$,197:$V01,313:126,314:$V51,316:554,317:289,318:$V61},{3:298,4:$VB,5:$VC,64:$VT1,89:290,93:296,94:295,96:$VE,151:$VF,152:291,155:293,158:292,159:294,163:288,188:$VT,189:$VU,190:$VV,191:$VW,192:$Vf1,194:$VZ,195:$V_,196:$V$,197:$V01,313:126,314:$V51,316:555,317:289,318:$V61},{83:[1,557],296:[1,556]},{83:[1,558]},{83:[1,559]},{83:[1,560]},o($VA,[2,424],{63:[1,562],64:[1,561]}),o($VA,[2,429]),{193:[1,563]},{3:564,4:$VB,5:$VC,96:$VE,152:565,190:$VV},{3:193,4:$VB,5:$VC,92:566},{120:[1,567]},o($VA,[2,352],{64:[1,568]}),{63:[1,570],64:[1,569]},o($VZ1,[2,525]),o($VZ1,[2,526],{218:[1,571]}),{4:$V82,168:572,288:$V92},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:573,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($VA,[2,437]),o($Vj2,[2,417]),{3:574,4:$VB,5:$VC,96:$VE,152:575,190:$VV},o($VA,[2,415]),o($VA,[2,459]),{64:$VA2,94:579,163:578,192:$Vf1,194:$VZ,195:$V_,196:$V$,197:$V01,245:576,313:126,314:$V51,318:$V61},{244:[1,580]},{3:503,4:$VB,5:$VC,123:581,155:582},o($VA,[2,331]),{3:583,4:$VB,5:$VC},o($VB2,[2,147],{70:584,125:[1,585]}),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:586,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($V02,[2,81],{61:[1,587]}),o($VC2,[2,88],{100:588,107:589,101:590,108:591,111:594,102:$VD2,104:$VE2,112:$VF2,113:$VG2,114:$VH2,115:$VI2,116:$VJ2,117:$VK2,118:$VL2,119:$VM2}),{203:$VN2,347:603,349:604,350:605},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:607,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{120:[2,534]},o($V12,[2,92],{3:608,4:$VB,5:$VC,63:[1,609]}),o($V12,[2,94]),o($V12,[2,97]),o($V12,[2,101]),o($V12,[2,104]),o($V12,[2,107]),o([4,5,8,9,11,61,63,64,65,80,97,102,104,112,113,114,115,116,117,118,119,120,122,124,125,135,136,137,138,144,201,205,238,244,246,292,295,296,297,298],[2,109]),o($V42,[2,55]),{33:610,66:59,74:79,80:$V4},o($VA,[2,455],{97:[1,611]}),o($VA,[2,451],{97:[1,612]}),o($VA,[2,444]),{96:$VE,152:613,190:$VV},o($VA,[2,453],{97:[1,614]}),o($VA,[2,448]),o($VA,[2,449],{206:[1,615]}),o($VA,[2,322],{61:$VO2,124:[1,616]}),o($VP2,[2,323]),{218:[1,618]},o([8,9,11,61,65,102,104,112,113,114,115,116,117,118,119,124,125,135,136,137,138,144,201,205,218],$VL1,{106:$Vh2}),o($VA,[2,466]),o($VZ1,[2,521]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:619,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{213:[1,621],218:[1,620]},{3:623,4:$VB,5:$VC,64:$VQ2,151:$VR2,326:622},o($Vl2,[2,59],{61:$Vm2}),o($Vl2,[2,60],{61:$Vm2}),o($Vl2,[2,61],{61:$Vm2}),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:376,147:626,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($Vn2,[2,175]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:627,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:628,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:629,4:$VB,5:$VC,96:$VE,151:[1,630],152:631,190:$VV},o($Vr2,[2,181]),o($Vr2,[2,183]),o($Vr2,[2,185]),o($Vg1,[2,73]),{65:[1,632]},o($VA,[2,513]),{65:[1,633],154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},{3:106,4:$VB,5:$VC,33:634,49:104,64:$VD,66:59,74:79,80:$V4,89:92,93:88,94:96,95:97,96:$VE,121:429,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,187:635,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{65:[1,636]},{61:$Vx2,65:[1,637]},o($Vd1,[2,301]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:638,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,33:639,49:104,64:$VD,65:[1,641],66:59,74:79,80:$V4,89:92,93:88,94:96,95:97,96:$VE,121:429,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,187:640,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($Vd1,[2,304]),{151:[1,642]},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:644,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,247:643,313:126,314:$V51,318:$V61},o($Vd1,$VS2,{173:645,174:$VT2}),{65:[1,647],154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},{65:[1,648],154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},o($VP1,[2,244]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:649,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:650,4:$VB,5:$VC,154:[1,651]},o($VS1,[2,467]),o($Vd1,[2,255]),{201:[1,652]},o($Vd1,[2,261]),{154:$Vk1,201:[2,265],206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:653,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{4:$V82,168:654,288:$V92},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:655,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($VS1,[2,489]),o($Vf2,[2,496]),o($Vg2,[2,484]),o($VS1,$Vz2,{106:[1,656]}),o($VS1,[2,486]),o($Vi2,[2,491]),o($Vi2,[2,493]),o($Vi2,[2,494]),o($Vi2,[2,495]),{3:657,4:$VB,5:$VC},{3:658,4:$VB,5:$VC},{3:660,4:$VB,5:$VC,285:659},{3:660,4:$VB,5:$VC,285:661},{3:662,4:$VB,5:$VC},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:429,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,187:663,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:664,4:$VB,5:$VC},o($Vj2,[2,365]),o($VA,$VU2,{302:665,63:$VV2,64:[1,666]}),o($VA,$VU2,{302:668,63:$VV2}),{64:[1,669]},{3:193,4:$VB,5:$VC,92:670},{3:660,4:$VB,5:$VC,63:[1,673],253:671,264:672,285:674},{3:503,4:$VB,5:$VC,123:675,155:582},{33:676,66:59,74:79,80:$V4},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:677,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($VZ1,[2,527],{218:[1,678]}),o($VA,[2,326],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),o($VA,[2,438]),o($VA,[2,439]),o($VA,[2,328],{61:$VW2}),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:644,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,247:680,313:126,314:$V51,318:$V61},o($VX2,[2,336]),o($VX2,[2,337]),o($VA,[2,329]),{61:$VY2,65:[1,681]},o($VZ2,[2,349]),o($VA,[2,423]),o($V_2,[2,162],{71:683,138:[1,684]}),{126:[1,685]},o($Vk2,[2,146],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),{3:173,4:$VB,5:$VC,64:$Va1,92:168,93:170,94:169,95:171,96:$Vb1,99:686,105:172,192:$Vc1,194:$VZ,195:$V_,196:$V$,197:$V01},o($V02,[2,82],{108:591,111:594,107:687,101:688,102:$VD2,104:$VE2,112:$VF2,113:$VG2,114:$VH2,115:$VI2,116:$VJ2,117:$VK2,118:$VL2,119:$VM2}),o($V$2,[2,113]),o($V$2,[2,114]),{3:173,4:$VB,5:$VC,64:[1,692],92:690,93:693,94:691,95:694,109:689,192:$Vc1,194:$VZ,195:$V_,196:$V$,197:$V01},{103:[1,695],113:$V03},{103:[1,697],113:$V13},o($V23,[2,129]),{102:[1,701],104:[1,700],111:699,113:$VG2,114:$VH2,115:$VI2,116:$VJ2,117:$VK2,118:$VL2,119:$VM2},o($V23,[2,131]),{113:[1,702]},{104:[1,704],113:[1,703]},{104:[1,706],113:[1,705]},{104:[1,707]},{113:[1,708]},{113:[1,709]},o($VA,[2,554],{348:710,349:711,350:712,203:$VN2,355:[1,713]}),o($V33,[2,538]),o($V33,[2,539]),{228:[1,715],351:[1,714]},{154:$Vk1,203:[2,535],206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},o($V12,[2,90]),{3:716,4:$VB,5:$VC},{65:[1,717]},{3:718,4:$VB,5:$VC},{3:719,4:$VB,5:$VC},o($VA,[2,446]),{3:720,4:$VB,5:$VC},{96:$VE,152:721,190:$VV},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:722,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:503,4:$VB,5:$VC,155:502,240:723},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:724,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($VA,[2,499],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:725,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:623,4:$VB,5:$VC,64:$VQ2,151:$VR2,326:726},o($V43,[2,502]),o($V43,[2,503]),o($V43,[2,504]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:727,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($Vn2,$Vo2,{148:728,149:$Vp2,150:$Vq2}),o($Vn2,[2,177],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),o($Vn2,[2,178],{224:251,149:[1,729],154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),o($Vr2,[2,180]),o($Vr2,[2,182]),o($Vr2,[2,184]),o($Vg1,[2,72]),o($Vd1,[2,277]),{65:[1,730]},{61:$Vx2,65:[1,731]},o($Vd1,[2,297]),o($Vd1,[2,299]),{65:[1,732],154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},{65:[1,733]},{61:$Vx2,65:[1,734]},o($Vd1,[2,302]),{61:[1,735],65:[1,736]},{61:$V53,65:[1,737]},o($Vy2,[2,341],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),o($Vd1,[2,226]),{64:[1,739]},o($Vd1,$VS2,{173:740,174:$VT2}),o($Vd1,$VS2,{173:741,174:$VT2}),o($Vy2,[2,247],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),o($VS1,[2,190]),o($Vd1,[2,187]),o($Vd1,[2,260]),o($Ve2,[2,264],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),{61:[1,743],65:[1,742]},{61:[1,745],65:[1,744],154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},{3:650,4:$VB,5:$VC},o($VA,[2,418]),{296:[1,746]},o($VA,[2,419]),o($V63,[2,396],{168:747,4:$V82,287:[1,748],288:$V92}),o($VA,[2,420]),o($VA,[2,422]),{61:$Vx2,65:[1,749]},o($VA,[2,426]),o($VA,[2,430]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:429,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,187:750,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:751,4:$VB,5:$VC},o($VA,[2,432]),{3:753,4:$VB,5:$VC,96:$V73,277:752},{64:[1,755]},{65:[1,756]},{61:[1,757],65:[2,367]},{33:758,66:59,74:79,80:$V4},o($Vy2,[2,392]),{61:$VY2,65:[1,759]},o($VA,[2,458]),o($VZ1,[2,528],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:760,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{64:[1,761],94:763,163:762,192:$Vf1,194:$VZ,195:$V_,196:$V$,197:$V01,313:126,314:$V51,318:$V61},{61:$V53,65:[1,764]},{33:766,66:59,74:79,80:$V4,244:[1,765]},{3:503,4:$VB,5:$VC,155:767},o($V83,[2,170],{72:768,144:[1,769]}),{126:[1,770]},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:776,127:771,129:772,130:$V93,132:$Va3,133:$Vb3,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($VC2,[2,89]),o($V$2,[2,111]),o($V$2,[2,112]),o($V$2,[2,144],{110:777,120:[1,778],122:[1,779]}),o($Vc3,[2,116],{3:780,4:$VB,5:$VC,63:[1,781]}),{3:782,4:$VB,5:$VC,63:[1,783]},{33:784,66:59,74:79,80:$V4},o($Vc3,[2,123],{3:785,4:$VB,5:$VC,63:[1,786]}),o($Vc3,[2,126],{3:787,4:$VB,5:$VC,63:[1,788]}),{64:[1,789]},o($V23,[2,141]),{64:[1,790]},o($V23,[2,137]),o($V23,[2,130]),{113:$V13},{113:$V03},o($V23,[2,132]),o($V23,[2,133]),{113:[1,791]},o($V23,[2,135]),{113:[1,792]},{113:[1,793]},o($V23,[2,139]),o($V23,[2,140]),o($VA,[2,531]),o($V33,[2,536]),o($V33,[2,537]),{3:106,4:$VB,5:$VC,49:104,64:$VD,77:794,89:92,93:88,94:96,95:97,96:$VE,121:376,147:375,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{204:[1,795],226:[1,796]},{351:[1,797]},o($V12,[2,91]),o($V42,[2,57]),o($VA,[2,456]),o($VA,[2,452]),o($VA,[2,454]),o($VA,[2,450]),o($VA,[2,321],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),o($VP2,[2,324]),o($VP2,[2,325],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),o($VA,[2,500],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),o($V43,[2,501]),{65:[1,798],154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},o($Vn2,[2,174]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:799,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($Vd1,[2,289]),o($Vd1,[2,290]),o($Vd1,[2,311]),o($Vd1,[2,298]),o($Vd1,[2,300]),{151:[1,800]},o($Vw2,[2,398]),o($Vw2,[2,400]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:801,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{138:$Vd3,175:802,176:803,177:[1,804]},o($Vd1,[2,227]),o($Vd1,[2,228]),o($Vd1,[2,215]),{151:[1,806]},o($Vd1,[2,217]),{151:[1,807]},{3:808,4:$VB,5:$VC},o($V63,[2,401],{286:809,289:810,290:811,272:820,191:$Ve3,228:$Vf3,246:$Vg3,258:$Vh3,274:$Vi3,275:$Vj3,278:$Vk3,279:$Vl3,291:$Vm3}),o($V63,[2,395]),o($VA,[2,425],{63:[1,822]}),{61:$Vx2,65:[1,823]},o($VA,[2,434]),{61:$Vn3,65:[1,824]},o($Vy2,[2,388]),o($Vy2,[2,389]),{3:753,4:$VB,5:$VC,96:$V73,277:826},o($VA,[2,353],{254:827,255:828,256:829,246:$Vo3,257:$Vp3,258:$Vq3,259:$Vr3}),o($Vs3,$Vt3,{3:660,265:834,285:835,266:836,267:837,4:$VB,5:$VC,273:$Vu3}),{65:[2,368]},{63:[1,839]},o($VZ1,[2,529],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:644,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,247:840,313:126,314:$V51,318:$V61},o($VX2,[2,339]),o($VX2,[2,340]),o($VX2,[2,335]),{64:$VA2,94:579,163:578,192:$Vf1,194:$VZ,195:$V_,196:$V$,197:$V01,245:841,313:126,314:$V51,318:$V61},o($VA,[2,332]),o($VZ2,[2,350]),o($Vv3,[2,157],{73:842,135:[1,843],136:[1,844],137:[1,845]}),{89:846,151:$VF},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:849,139:847,140:848,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($VB2,[2,155],{128:850,61:$Vw3,134:[1,852]}),o($Vx3,[2,149]),{131:[1,853]},{64:[1,854]},{64:[1,855]},o($Vx3,[2,154],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),o($V$2,[2,115]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:856,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:503,4:$VB,5:$VC,123:857,155:582},o($Vc3,[2,117]),{3:858,4:$VB,5:$VC},o($Vc3,[2,119]),{3:859,4:$VB,5:$VC},{65:[1,860]},o($Vc3,[2,124]),{3:861,4:$VB,5:$VC},o($Vc3,[2,127]),{3:862,4:$VB,5:$VC},{33:863,66:59,74:79,80:$V4},{33:864,66:59,74:79,80:$V4},o($V23,[2,134]),o($V23,[2,136]),o($V23,[2,138]),o($VA,[2,555],{61:$Vm2,91:[1,865]}),{237:$Vy3,241:$Vz3,352:866},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:869,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{126:[1,871],204:[1,870],226:[1,872]},o($V43,[2,505]),o($Vn2,[2,179],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),{65:[1,873]},o($Vy2,[2,342],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),{65:[1,874],138:$Vd3,176:875},{65:[1,876]},{126:[1,877]},{126:[1,878]},{65:[1,879]},{65:[1,880]},o($VA,[2,421]),o($V63,[2,394]),o($V63,[2,402],{272:820,290:881,191:$Ve3,228:$Vf3,246:$Vg3,258:$Vh3,274:$Vi3,275:$Vj3,278:$Vk3,279:$Vl3,291:$Vm3}),o($V52,[2,404]),{276:[1,882]},{276:[1,883]},{3:884,4:$VB,5:$VC},o($V52,[2,408]),o($V52,[2,410],{64:[1,885]}),{3:207,4:$VB,5:$VC,89:200,93:205,94:204,96:$VE,151:$VF,152:201,158:202,159:203,170:886,171:$Ve1,188:$VT,189:$VU,190:$VV,191:$VW,194:$VZ,195:$V_,196:$V$,197:$V01},o($V52,[2,412]),{191:[1,887]},o($V52,[2,414]),{64:[1,888]},{3:889,4:$VB,5:$VC},o($VA,$VU2,{302:890,63:$VV2}),o($VA,[2,440]),{3:891,4:$VB,5:$VC,96:[1,892]},{61:$Vn3,65:[1,893]},o($VA,[2,351]),o($VA,[2,354],{256:894,246:$Vo3,257:$Vp3,258:$Vq3,259:$Vr3}),o($VA3,[2,356]),o($VA3,[2,357]),{218:[1,895]},{218:[1,896]},{218:[1,897]},{61:[1,898],65:[2,366]},o($Vy2,[2,393]),o($Vy2,[2,369]),{78:[1,906],86:[1,907],268:899,269:900,270:901,271:902,272:903,274:$Vi3,275:[1,904],276:[1,908],278:[1,905]},{3:909,4:$VB,5:$VC},{33:910,66:59,74:79,80:$V4},{61:$V53,65:[1,911]},o($VA,[2,330],{61:$VW2}),o($Vv3,[2,58]),{33:912,66:59,74:79,79:[1,913],80:$V4},{33:914,66:59,74:79,80:$V4},{33:915,66:59,74:79,80:$V4},o($V83,[2,172],{145:916,146:[1,917]}),o($V_2,[2,163],{61:$VB3}),o($VC3,[2,164]),o($VC3,[2,166],{224:251,141:[1,919],142:[1,920],154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),o($VB2,[2,148]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:776,129:921,130:$V93,132:$Va3,133:$Vb3,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:922,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{64:[1,923]},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:776,127:924,129:772,130:$V93,132:$Va3,133:$Vb3,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:776,127:925,129:772,130:$V93,132:$Va3,133:$Vb3,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($V$2,[2,142],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),o($V$2,[2,143],{61:$VY2}),o($Vc3,[2,118]),o($Vc3,[2,120]),{3:926,4:$VB,5:$VC,63:[1,927]},o($Vc3,[2,125]),o($Vc3,[2,128]),{65:[1,928]},{65:[1,929]},{3:193,4:$VB,5:$VC,92:931,192:[1,930]},o($V33,[2,540]),o($V33,[2,542]),{238:[1,932]},{154:$Vk1,204:[1,933],206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},{242:$VD3,353:934},{311:[1,937],354:[1,936]},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:938,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($Vw2,[2,397]),o($Vd1,[2,230]),{65:[1,939]},o($Vd1,[2,231]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:776,127:940,129:772,130:$V93,132:$Va3,133:$Vb3,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:849,139:941,140:848,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($Vd1,[2,216]),o($Vd1,[2,218]),o($V52,[2,403]),o($V52,[2,405]),{279:[1,942]},{64:[1,943]},{89:944,151:$VF},o($V52,[2,411]),o($V52,[2,413]),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:945,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($VA,[2,427]),o($VA,[2,431]),o($Vy2,[2,390]),o($Vy2,[2,391]),o($VA,[2,441]),o($VA3,[2,355]),{3:946,4:$VB,5:$VC},{89:947,151:$VF},{3:948,4:$VB,5:$VC},o($Vs3,$Vt3,{267:837,266:949,273:$Vu3}),o($Vy2,[2,371]),o($Vy2,[2,372]),o($Vy2,[2,373]),o($Vy2,[2,374]),o($Vy2,[2,375]),{276:[1,950]},{276:[1,951]},o($Vy2,[2,385]),{3:952,4:$VB,5:$VC},{3:953,4:$VB,5:$VC},o($Vs3,[2,377]),o($VA,[2,457]),o($VX2,[2,338]),o($Vv3,[2,158]),{33:954,66:59,74:79,80:$V4},o($Vv3,[2,160]),o($Vv3,[2,161]),o($V83,[2,171]),{89:955,151:$VF},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:849,140:956,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},o($VC3,[2,167]),{143:[1,957]},o($Vx3,[2,150]),o($VB2,[2,156],{224:251,154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1}),{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:776,127:958,129:772,130:$V93,132:$Va3,133:$Vb3,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{61:$Vw3,65:[1,959]},{61:$Vw3,65:[1,960]},o($Vc3,[2,121]),{3:961,4:$VB,5:$VC},{3:962,4:$VB,5:$VC,63:[1,963]},{3:964,4:$VB,5:$VC,63:[1,965]},{3:966,4:$VB,5:$VC},o($VA,[2,557],{64:[1,967]}),{3:503,4:$VB,5:$VC,155:502,239:968,240:501},{237:$Vy3,241:$Vz3,352:969},o($V33,[2,544]),{64:[1,971],244:[1,970],246:[1,972]},{204:[1,973],226:[1,974]},{204:[1,975],226:[1,976]},{154:$Vk1,204:[1,977],206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},o($Vd1,[2,232]),o([65,138],[2,233],{61:$Vw3}),{61:$VB3,65:[2,234]},{3:978,4:$VB,5:$VC},{3:979,4:$VB,5:$VC},{61:[1,980]},{65:[1,981],154:$Vk1,206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},o($VA3,[2,358]),o($VA3,[2,359]),o($VA3,[2,360]),o($Vy2,[2,370]),{64:[1,982]},{64:[1,983]},{64:[1,984]},{64:[1,985]},o($Vv3,[2,159]),o($V83,[2,173]),o($VC3,[2,165]),o($VC3,[2,168],{141:[1,986]}),{61:$Vw3,65:[1,987]},o($Vx3,[2,152]),o($Vx3,[2,153]),o($Vc3,[2,122]),o($V$2,[2,84]),{3:988,4:$VB,5:$VC},o($V$2,[2,86]),{3:989,4:$VB,5:$VC},o($VA,[2,556]),{3:503,4:$VB,5:$VC,123:990,155:582},o($V33,[2,543],{61:$VO2}),o($V33,[2,541]),{64:$VA2,94:579,163:578,192:$Vf1,194:$VZ,195:$V_,196:$V$,197:$V01,245:991,313:126,314:$V51,318:$V61},{3:503,4:$VB,5:$VC,123:992,155:582},{244:[1,993]},{242:$VD3,353:994},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:995,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{242:$VD3,353:996},{3:106,4:$VB,5:$VC,49:104,64:$VD,89:92,93:88,94:96,95:97,96:$VE,121:997,151:$VF,152:94,153:91,154:$VG,155:90,156:87,157:89,158:93,159:95,160:98,161:99,162:100,163:101,164:102,165:$V5,166:$VH,167:$VI,169:$VJ,172:105,178:$VK,179:$VL,180:$VM,181:$VN,182:$VO,183:$VP,184:$VQ,185:$VR,186:$VS,188:$VT,189:$VU,190:$VV,191:$VW,192:$VX,193:$VY,194:$VZ,195:$V_,196:$V$,197:$V01,198:$V11,208:$V21,209:$V31,228:$V41,313:126,314:$V51,318:$V61},{242:$VD3,353:998},{64:[1,999]},{65:[1,1e3]},{89:1001,151:$VF},o($V52,[2,378]),{3:753,4:$VB,5:$VC,96:$V73,277:1002},{3:753,4:$VB,5:$VC,96:$V73,277:1003},{3:503,4:$VB,5:$VC,123:1004,155:582},{3:503,4:$VB,5:$VC,123:1005,155:582},o($VC3,[2,169]),o($Vx3,[2,151]),o($V$2,[2,85]),o($V$2,[2,87]),{61:$VY2,65:[1,1006]},o($V33,[2,550],{61:$VW2}),{61:$VY2,65:[1,1007]},o($V33,[2,552]),o($V33,[2,545]),{154:$Vk1,204:[1,1008],206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},o($V33,[2,548]),{154:$Vk1,204:[1,1009],206:$Vl1,207:$Vm1,208:$Vn1,209:$Vo1,210:$Vp1,211:$Vq1,212:$Vr1,213:$Vs1,214:$Vt1,215:$Vu1,216:$Vv1,217:$Vw1,218:$Vx1,219:$Vy1,220:$Vz1,221:$VA1,222:$VB1,223:$VC1,224:251,226:$VD1,227:$VE1,228:$VF1,229:$VG1,231:$VH1,232:$VI1,233:$VJ1,234:$VK1},o($V33,[2,546]),{3:1010,4:$VB,5:$VC},o($V52,[2,407]),{65:[1,1011]},{61:$Vn3,65:[1,1012]},{61:$Vn3,65:[1,1013]},{61:$VY2,65:[1,1014]},{61:$VY2,65:[1,1015]},o($VA,[2,558]),{244:[1,1016],246:[1,1017]},{242:$VD3,353:1018},{237:$Vy3,241:$Vz3,352:1019},{65:[1,1020]},o($V52,[2,409]),o($Vy2,[2,379]),{279:[1,1021]},o($Vy2,[2,386]),o($Vy2,[2,387]),{64:$VA2,94:579,163:578,192:$Vf1,194:$VZ,195:$V_,196:$V$,197:$V01,245:1022,313:126,314:$V51,318:$V61},{244:[1,1023]},o($V33,[2,547]),o($V33,[2,549]),o($V52,[2,406]),{3:1024,4:$VB,5:$VC},o($V33,[2,551],{61:$VW2}),o($V33,[2,553]),{64:[1,1025]},{3:753,4:$VB,5:$VC,96:$V73,277:1026},{61:$Vn3,65:[1,1027]},o($Vy2,[2,381],{280:1028,281:1029,120:[1,1030]}),o($Vy2,[2,380]),{120:[1,1032],282:1031},{241:[1,1033]},o($Vy2,[2,382]),{237:[1,1034]},{283:[1,1035]},{283:[1,1036]},{284:[1,1037]},{284:[1,1038]},{120:[2,383]},o($Vy2,[2,384])],defaultActions:{81:[2,3],129:[2,235],130:[2,236],131:[2,237],132:[2,238],133:[2,239],134:[2,240],135:[2,241],136:[2,242],137:[2,243],165:[2,532],337:[2,533],405:[2,318],406:[2,319],407:[2,320],483:[2,534],758:[2,368],1037:[2,383]},parseError:function parseError(str,hash){if(hash.recoverable){this.trace(str) }else{throw new Error(str)}},parse:function parse(input){var self=this,stack=[0],tstack=[],vstack=[null],lstack=[],table=this.table,yytext="",yylineno=0,yyleng=0,recovering=0,TERROR=2,EOF=1;var args=lstack.slice.call(arguments,1);var lexer=Object.create(this.lexer);var sharedState={yy:{}};for(var k in this.yy){if(Object.prototype.hasOwnProperty.call(this.yy,k)){sharedState.yy[k]=this.yy[k]}}lexer.setInput(input,sharedState.yy);sharedState.yy.lexer=lexer;sharedState.yy.parser=this;if(typeof lexer.yylloc=="undefined"){lexer.yylloc={}}var yyloc=lexer.yylloc;lstack.push(yyloc);var ranges=lexer.options&&lexer.options.ranges;if(typeof sharedState.yy.parseError==="function"){this.parseError=sharedState.yy.parseError}else{this.parseError=Object.getPrototypeOf(this).parseError}function popStack(n){stack.length=stack.length-2*n;vstack.length=vstack.length-n;lstack.length=lstack.length-n}_token_stack:function lex(){var token;token=lexer.lex()||EOF;if(typeof token!=="number"){token=self.symbols_[token]||token}return token}var symbol,preErrorSymbol,state,action,a,r,yyval={},p,len,newState,expected;while(true){state=stack[stack.length-1];if(this.defaultActions[state]){action=this.defaultActions[state]}else{if(symbol===null||typeof symbol=="undefined"){symbol=lex()}action=table[state]&&table[state][symbol]}if(typeof action==="undefined"||!action.length||!action[0]){var errStr="";expected=[];for(p in table[state]){if(this.terminals_[p]&&p>TERROR){expected.push("'"+this.terminals_[p]+"'")}}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})}if(action[0]instanceof Array&&action.length>1){throw new Error("Parse Error: multiple actions possible at state: "+state+", token: "+symbol)}switch(action[0]){case 1:stack.push(symbol);vstack.push(lexer.yytext);lstack.push(lexer.yylloc);stack.push(action[1]);symbol=null;if(!preErrorSymbol){yyleng=lexer.yyleng;yytext=lexer.yytext;yylineno=lexer.yylineno;yyloc=lexer.yylloc;if(recovering>0){recovering--}}else{symbol=preErrorSymbol;preErrorSymbol=null}break;case 2:len=this.productions_[action[1]][1];yyval.$=vstack[vstack.length-len];yyval._$={first_line:lstack[lstack.length-(len||1)].first_line,last_line:lstack[lstack.length-1].last_line,first_column:lstack[lstack.length-(len||1)].first_column,last_column:lstack[lstack.length-1].last_column};if(ranges){yyval._$.range=[lstack[lstack.length-(len||1)].range[0],lstack[lstack.length-1].range[1]]}r=this.performAction.apply(yyval,[yytext,yyleng,yylineno,sharedState.yy,action[1],vstack,lstack].concat(args));if(typeof r!=="undefined"){return r}if(len){stack=stack.slice(0,-1*len*2);vstack=vstack.slice(0,-1*len);lstack=lstack.slice(0,-1*len)}stack.push(this.productions_[action[1]][0]);vstack.push(yyval.$);lstack.push(yyval._$);newState=table[stack[stack.length-2]][stack[stack.length-1]];stack.push(newState);break;case 3:return true}}return true}};var lexer=function(){var lexer={EOF:1,parseError:function parseError(str,hash){if(this.yy.parser){this.yy.parser.parseError(str,hash)}else{throw new Error(str)}},setInput:function(input,yy){this.yy=yy||this.yy||{};this._input=input;this._more=this._backtrack=this.done=false;this.yylineno=this.yyleng=0;this.yytext=this.matched=this.match="";this.conditionStack=["INITIAL"];this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0};if(this.options.ranges){this.yylloc.range=[0,0]}this.offset=0;return this},input:function(){var ch=this._input[0];this.yytext+=ch;this.yyleng++;this.offset++;this.match+=ch;this.matched+=ch;var lines=ch.match(/(?:\r\n?|\n).*/g);if(lines){this.yylineno++;this.yylloc.last_line++}else{this.yylloc.last_column++}if(this.options.ranges){this.yylloc.range[1]++}this._input=this._input.slice(1);return ch},unput:function(ch){var len=ch.length;var lines=ch.split(/(?:\r\n?|\n)/g);this._input=ch+this._input;this.yytext=this.yytext.substr(0,this.yytext.length-len);this.offset-=len;var oldLines=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1);this.matched=this.matched.substr(0,this.matched.length-1);if(lines.length-1){this.yylineno-=lines.length-1}var r=this.yylloc.range;this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:lines?(lines.length===oldLines.length?this.yylloc.first_column:0)+oldLines[oldLines.length-lines.length].length-lines[0].length:this.yylloc.first_column-len};if(this.options.ranges){this.yylloc.range=[r[0],r[0]+this.yyleng-len]}this.yyleng=this.yytext.length;return this},more:function(){this._more=true;return this},reject:function(){if(this.options.backtrack_lexer){this._backtrack=true}else{return this.parseError("Lexical error on line "+(this.yylineno+1)+". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})}return this},less:function(n){this.unput(this.match.slice(n))},pastInput:function(){var past=this.matched.substr(0,this.matched.length-this.match.length);return(past.length>20?"...":"")+past.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var next=this.match;if(next.length<20){next+=this._input.substr(0,20-next.length)}return(next.substr(0,20)+(next.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var pre=this.pastInput();var c=new Array(pre.length+1).join("-");return pre+this.upcomingInput()+"\n"+c+"^"},test_match:function(match,indexed_rule){var token,lines,backup;if(this.options.backtrack_lexer){backup={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done};if(this.options.ranges){backup.yylloc.range=this.yylloc.range.slice(0)}}lines=match[0].match(/(?:\r\n?|\n).*/g);if(lines){this.yylineno+=lines.length}this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:lines?lines[lines.length-1].length-lines[lines.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+match[0].length};this.yytext+=match[0];this.match+=match[0];this.matches=match;this.yyleng=this.yytext.length;if(this.options.ranges){this.yylloc.range=[this.offset,this.offset+=this.yyleng]}this._more=false;this._backtrack=false;this._input=this._input.slice(match[0].length);this.matched+=match[0];token=this.performAction.call(this,this.yy,this,indexed_rule,this.conditionStack[this.conditionStack.length-1]);if(this.done&&this._input){this.done=false}if(token){return token}else if(this._backtrack){for(var k in backup){this[k]=backup[k]}return false}return false},next:function(){if(this.done){return this.EOF}if(!this._input){this.done=true}var token,match,tempMatch,index;if(!this._more){this.yytext="";this.match=""}var rules=this._currentRules();for(var i=0;imatch[0].length)){match=tempMatch;index=i;if(this.options.backtrack_lexer){token=this.test_match(tempMatch,rules[i]);if(token!==false){return token}else if(this._backtrack){match=false;continue}else{return false}}else if(!this.options.flex){break}}}if(match){token=this.test_match(match,rules[index]);if(token!==false){return token}return false}if(this._input===""){return this.EOF}else{return this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})}},lex:function lex(){var r=this.next();if(r){return r}else{return this.lex()}},begin:function begin(condition){this.conditionStack.push(condition)},popState:function popState(){var n=this.conditionStack.length-1;if(n>0){return this.conditionStack.pop()}else{return this.conditionStack[0]}},_currentRules:function _currentRules(){if(this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]){return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules}else{return this.conditions["INITIAL"].rules}},topState:function topState(n){n=this.conditionStack.length-1-Math.abs(n||0);if(n>=0){return this.conditionStack[n]}else{return"INITIAL"}},pushState:function pushState(condition){this.begin(condition)},stateStackSize:function stateStackSize(){return this.conditionStack.length},options:{"case-insensitive":true},performAction:function anonymous(yy,yy_,$avoiding_name_collisions,YY_START){var YYSTATE=YY_START;switch($avoiding_name_collisions){case 0:return 165;break;case 1:return 197;break;case 2:return 314;break;case 3:return 5;break;case 4:return 5;break;case 5:return 190;break;case 6:return 190;break;case 7:return 96;break;case 8:return 96;break;case 9:return;break;case 10:return;break;case 11:break;case 12:return 227;break;case 13:return 226;break;case 14:return"ABSOLUTE";break;case 15:return 284;break;case 16:return 297;break;case 17:return 185;break;case 18:return 79;break;case 19:return 294;break;case 20:return 226;break;case 21:return 119;break;case 22:return 236;break;case 23:return 103;break;case 24:return 186;break;case 25:return 63;break;case 26:return 312;break;case 27:return 141;break;case 28:return 299;break;case 29:return 258;break;case 30:return 258;break;case 31:return 182;break;case 32:return 331;break;case 33:return 231;break;case 34:return 335;break;case 35:return 232;break;case 36:return 207;break;case 37:return 126;break;case 38:return 198;break;case 39:return 167;break;case 40:return 259;break;case 41:return 274;break;case 42:return"CLOSE";break;case 43:return 142;break;case 44:return"COLUMN";break;case 45:return"COLUMNS";break;case 46:return"COMMIT";break;case 47:return"CONSTRAINT";break;case 48:return"CONTINUE";break;case 49:return"CONVERT";break;case 50:return"COUNT";break;case 51:return 250;break;case 52:return"CROSS";break;case 53:return 133;break;case 54:return"CURRENT_TIMESTAMP";break;case 55:return"CURSOR";break;case 56:return 300;break;case 57:return 305;break;case 58:return 339;break;case 59:return 246;break;case 60:return 241;break;case 61:return"DELETED";break;case 62:return 141;break;case 63:return 301;break;case 64:return 75;break;case 65:return 292;break;case 66:return 201;break;case 67:return 257;break;case 68:return 288;break;case 69:return 205;break;case 70:return 136;break;case 71:return 193;break;case 72:return 13;break;case 73:return 189;break;case 74:return"FETCH";break;case 75:return 183;break;case 76:return 278;break;case 77:return 97;break;case 78:return 11;break;case 79:return 125;break;case 80:return 130;break;case 81:return 134;break;case 82:return 309;break;case 83:return 263;break;case 84:return 291;break;case 85:return 233;break;case 86:return 229;break;case 87:return 86;break;case 88:return 114;break;case 89:return 242;break;case 90:return"INSERTED";break;case 91:return 137;break;case 92:return 91;break;case 93:return 113;break;case 94:return 276;break;case 95:return 184;break;case 96:return 115;break;case 97:return 206;break;case 98:return 144;break;case 99:return 311;break;case 100:return"MATCHED";break;case 101:return 84;break;case 102:return"MAX";break;case 103:return"MERGE";break;case 104:return"MIN";break;case 105:return"EXCEPT";break;case 106:return"MODIFY";break;case 107:return 112;break;case 108:return"NEXT";break;case 109:return 166;break;case 110:return 143;break;case 111:return 283;break;case 112:return 228;break;case 113:return 191;break;case 114:return 327;break;case 115:return 120;break;case 116:return 146;break;case 117:return"OPEN";break;case 118:return 227;break;case 119:return 138;break;case 120:return 104;break;case 121:return 174;break;case 122:return 177;break;case 123:return 90;break;case 124:return 15;break;case 125:return 275;break;case 126:return 336;break;case 127:return"PRIOR";break;case 128:return 14;break;case 129:return 87;break;case 130:return"REDUCE";break;case 131:return 279;break;case 132:return"RELATIVE";break;case 133:return 295;break;case 134:return 337;break;case 135:return"RESTORE";break;case 136:return 116;break;case 137:return 330;break;case 138:return 132;break;case 139:return 82;break;case 140:return 300;break;case 141:return 305;break;case 142:return 80;break;case 143:return 118;break;case 144:return 238;break;case 145:return 131;break;case 146:return 304;break;case 147:return 235;break;case 148:return"STORE";break;case 149:return"SUM";break;case 150:return 251;break;case 151:return 306;break;case 152:return 354;break;case 153:return 149;break;case 154:return 85;break;case 155:return 150;break;case 156:return 204;break;case 157:return 296;break;case 158:return 88;break;case 159:return"TRAN";break;case 160:return 329;break;case 161:return 188;break;case 162:return 342;break;case 163:return 135;break;case 164:return 78;break;case 165:return 237;break;case 166:return 303;break;case 167:return 122;break;case 168:return 81;break;case 169:return 244;break;case 170:return 308;break;case 171:return 203;break;case 172:return 124;break;case 173:return 333;break;case 174:return 59;break;case 175:return 329;break;case 176:return 151;break;case 177:return 151;break;case 178:return 213;break;case 179:return 208;break;case 180:return 209;break;case 181:return 154;break;case 182:return 210;break;case 183:return 211;break;case 184:return 223;break;case 185:return 220;break;case 186:return 222;break;case 187:return 219;break;case 188:return 215;break;case 189:return 214;break;case 190:return 217;break;case 191:return 221;break;case 192:return 216;break;case 193:return 218;break;case 194:return 221;break;case 195:return 64;break;case 196:return 65;break;case 197:return 192;break;case 198:return 318;break;case 199:return 320;break;case 200:return 322;break;case 201:return 106;break;case 202:return 61;break;case 203:return 234;break;case 204:return 195;break;case 205:return 9;break;case 206:return 194;break;case 207:return 196;break;case 208:return 212;break;case 209:return 4;break;case 210:return 8;break;case 211:return"INVALID";break}},rules:[/^(?:``([^\`])+``)/i,/^(?:\[\?\])/i,/^(?:@\[)/i,/^(?:\[([^\]])*?\])/i,/^(?:`([^\`])*?`)/i,/^(?:N(['](\\.|[^']|\\')*?['])+)/i,/^(?:X(['](\\.|[^']|\\')*?['])+)/i,/^(?:(['](\\.|[^']|\\')*?['])+)/i,/^(?:(["](\\.|[^"]|\\")*?["])+)/i,/^(?:\/\*(.*?)\*\/)/i,/^(?:--(.*?)($|\r\n|\r|\n))/i,/^(?:\s+)/i,/^(?:\|\|)/i,/^(?:&&)/i,/^(?:ABSOLUTE\b)/i,/^(?:ACTION\b)/i,/^(?:ADD\b)/i,/^(?:AGGR\b)/i,/^(?:ALL\b)/i,/^(?:ALTER\b)/i,/^(?:AND\b)/i,/^(?:ANTI\b)/i,/^(?:ANY\b)/i,/^(?:APPLY\b)/i,/^(?:ARRAY\b)/i,/^(?:AS\b)/i,/^(?:ASSERT\b)/i,/^(?:ASC\b)/i,/^(?:ATTACH\b)/i,/^(?:AUTOINCREMENT\b)/i,/^(?:AUTO_INCREMENT\b)/i,/^(?:AVG\b)/i,/^(?:BEGIN\b)/i,/^(?:BETWEEN\b)/i,/^(?:BREAK\b)/i,/^(?:NOT\s+BETWEEN\b)/i,/^(?:NOT\s+LIKE\b)/i,/^(?:BY\b)/i,/^(?:CASE\b)/i,/^(?:CAST\b)/i,/^(?:CHARSET\b)/i,/^(?:CHECK\b)/i,/^(?:CLOSE\b)/i,/^(?:COLLATE\b)/i,/^(?:COLUMN\b)/i,/^(?:COLUMNS\b)/i,/^(?:COMMIT\b)/i,/^(?:CONSTRAINT\b)/i,/^(?:CONTINUE\b)/i,/^(?:CONVERT\b)/i,/^(?:COUNT\b)/i,/^(?:CREATE\b)/i,/^(?:CROSS\b)/i,/^(?:CUBE\b)/i,/^(?:CURRENT_TIMESTAMP\b)/i,/^(?:CURSOR\b)/i,/^(?:DATABASE\b)/i,/^(?:DATABASES\b)/i,/^(?:DECLARE\b)/i,/^(?:DEFAULT\b)/i,/^(?:DELETE\b)/i,/^(?:DELETED\b)/i,/^(?:DESC\b)/i,/^(?:DETACH\b)/i,/^(?:DISTINCT\b)/i,/^(?:DROP\b)/i,/^(?:END\b)/i,/^(?:ENGINE\b)/i,/^(?:ENUM\b)/i,/^(?:ELSE\b)/i,/^(?:EXCEPT\b)/i,/^(?:EXISTS\b)/i,/^(?:EXPLAIN\b)/i,/^(?:FALSE\b)/i,/^(?:FETCH\b)/i,/^(?:FIRST\b)/i,/^(?:FOREIGN\b)/i,/^(?:FROM\b)/i,/^(?:GO\b)/i,/^(?:GROUP\b)/i,/^(?:GROUPING\b)/i,/^(?:HAVING\b)/i,/^(?:HELP\b)/i,/^(?:IF\b)/i,/^(?:IDENTITY\b)/i,/^(?:IS\b)/i,/^(?:IN\b)/i,/^(?:INDEX\b)/i,/^(?:INNER\b)/i,/^(?:INSERT\b)/i,/^(?:INSERTED\b)/i,/^(?:INTERSECT\b)/i,/^(?:INTO\b)/i,/^(?:JOIN\b)/i,/^(?:KEY\b)/i,/^(?:LAST\b)/i,/^(?:LEFT\b)/i,/^(?:LIKE\b)/i,/^(?:LIMIT\b)/i,/^(?:SOURCE\b)/i,/^(?:MATCHED\b)/i,/^(?:MATRIX\b)/i,/^(?:MAX\b)/i,/^(?:MERGE\b)/i,/^(?:MIN\b)/i,/^(?:MINUS\b)/i,/^(?:MODIFY\b)/i,/^(?:NATURAL\b)/i,/^(?:NEXT\b)/i,/^(?:NEW\b)/i,/^(?:NOCASE\b)/i,/^(?:NO\b)/i,/^(?:NOT\b)/i,/^(?:NULL\b)/i,/^(?:OFF\b)/i,/^(?:ON\b)/i,/^(?:OFFSET\b)/i,/^(?:OPEN\b)/i,/^(?:OR\b)/i,/^(?:ORDER\b)/i,/^(?:OUTER\b)/i,/^(?:OVER\b)/i,/^(?:PARTITION\b)/i,/^(?:PERCENT\b)/i,/^(?:PLAN\b)/i,/^(?:PRIMARY\b)/i,/^(?:PRINT\b)/i,/^(?:PRIOR\b)/i,/^(?:QUERY\b)/i,/^(?:RECORDSET\b)/i,/^(?:REDUCE\b)/i,/^(?:REFERENCES\b)/i,/^(?:RELATIVE\b)/i,/^(?:RENAME\b)/i,/^(?:REQUIRE\b)/i,/^(?:RESTORE\b)/i,/^(?:RIGHT\b)/i,/^(?:ROLLBACK\b)/i,/^(?:ROLLUP\b)/i,/^(?:ROW\b)/i,/^(?:SCHEMA\b)/i,/^(?:SCHEMAS\b)/i,/^(?:SELECT\b)/i,/^(?:SEMI\b)/i,/^(?:SET\b)/i,/^(?:SETS\b)/i,/^(?:SHOW\b)/i,/^(?:SOME\b)/i,/^(?:STORE\b)/i,/^(?:SUM\b)/i,/^(?:TABLE\b)/i,/^(?:TABLES\b)/i,/^(?:TARGET\b)/i,/^(?:TD\b)/i,/^(?:TEXTSTRING\b)/i,/^(?:TH\b)/i,/^(?:THEN\b)/i,/^(?:TO\b)/i,/^(?:TOP\b)/i,/^(?:TRAN\b)/i,/^(?:TRANSACTION\b)/i,/^(?:TRUE\b)/i,/^(?:TRUNCATE\b)/i,/^(?:UNION\b)/i,/^(?:UNIQUE\b)/i,/^(?:UPDATE\b)/i,/^(?:USE\b)/i,/^(?:USING\b)/i,/^(?:VALUE\b)/i,/^(?:VALUES\b)/i,/^(?:VIEW\b)/i,/^(?:WHEN\b)/i,/^(?:WHERE\b)/i,/^(?:WHILE\b)/i,/^(?:WITH\b)/i,/^(?:WORK\b)/i,/^(?:(\d*[.])?\d+[eE]\d+)/i,/^(?:(\d*[.])?\d+)/i,/^(?:->)/i,/^(?:\+)/i,/^(?:-)/i,/^(?:\*)/i,/^(?:\/)/i,/^(?:%)/i,/^(?:!===)/i,/^(?:===)/i,/^(?:!==)/i,/^(?:==)/i,/^(?:>=)/i,/^(?:>)/i,/^(?:<=)/i,/^(?:<>)/i,/^(?:<)/i,/^(?:=)/i,/^(?:!=)/i,/^(?:\()/i,/^(?:\))/i,/^(?:@)/i,/^(?:\{)/i,/^(?:\})/i,/^(?:\])/i,/^(?:\.)/i,/^(?:,)/i,/^(?:::)/i,/^(?::)/i,/^(?:;)/i,/^(?:\$)/i,/^(?:\?)/i,/^(?:\^)/i,/^(?:[a-zA-Z_][a-zA-Z_0-9]*)/i,/^(?:$)/i,/^(?:.)/i],conditions:{INITIAL:{rules:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211],inclusive:true}}};return lexer}();parser.lexer=lexer;function Parser(){this.yy={}}Parser.prototype=parser;parser.Parser=Parser;return new Parser}();if(typeof require!=="undefined"&&typeof exports!=="undefined"){exports.parser=parser;exports.Parser=parser.Parser;exports.parse=function(){return parser.parse.apply(parser,arguments)};exports.main=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)};if(typeof module!=="undefined"&&require.main===module){exports.main(process.argv.slice(1))}}alasql.prettyflag=false;alasql.pretty=function(sql,flag){var pf=alasql.prettyflag;alasql.prettyflag=!flag;var s=alasql.parse(sql).toString();alasql.prettyflag=pf;return s};function K(s){if(alasql.prettyflag){return''+s.toUpperCase()+""}else{return s}}function P(s){if(alasql.prettyflag){return''+s+""}else{return s}}function L(s){if(alasql.prettyflag){return''+s+""}else{return s}}function N(s){if(alasql.prettyflag){return''+s+""}else{return s}}function S(s){if(alasql.prettyflag){return''+s+""}else{return s}}function NL(){if(alasql.prettyflag){return"
"}else{return" "}}function ID(){if(alasql.prettyflag){return"     "}else{return""}}var utils=alasql.utils={};function returnTrue(){return true}function returnUndefined(){}var escapeq=utils.escapeq=function(s){return s.replace(/\'/g,"\\'")};var escapeqq=utils.undoubleq=function(s){return s.replace(/(\')/g,"''")};var doubleq=utils.doubleq=function(s){return s.replace(/(\'\')/g,"\\'")};var doubleqq=utils.doubleqq=function(s){return s.replace(/\'/g,"'")};var cutbom=function(s){if(s[0]==String.fromCharCode(65279))s=s.substr(1);return s};var loadFile=utils.loadFile=function(path,asy,success,error){if(typeof exports=="object"){var fs=require("fs");if(!path){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(asy){fs.readFile(path,function(err,data){if(err){throw err}success(cutbom(data.toString()))})}else{var data=fs.readFileSync(path);success(cutbom(data.toString()))}}}else if(typeof cordova=="object"){window.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)})})})}else{if(typeof path=="string"){if(path.substr(0,1)=="#"&&typeof document!="undefined"){var data=document.querySelector(path).textContent;success(data)}else{var xhr=new XMLHttpRequest;xhr.onreadystatechange=function(){if(xhr.readyState===XMLHttpRequest.DONE){if(xhr.status===200){if(success)success(cutbom(xhr.responseText))}else{if(error)error(xhr)}}};xhr.open("GET",path,asy);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(cutbom(data))};reader.readAsText(files[0])}}};var loadBinaryFile=utils.loadBinaryFile=function(path,asy,success,error){if(typeof exports=="object"){var fs=require("fs");if(asy){fs.readFile(path,function(err,data){if(err){throw err}var arr=new Array;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=new Array;for(var i=0;i!=data.length;++i)arr[i]=String.fromCharCode(data[i]);success(arr.join(""))}}else{if(typeof path=="string"){var xhr=new XMLHttpRequest;xhr.open("GET",path,asy);xhr.responseType="arraybuffer";xhr.onload=function(){var data=new Uint8Array(xhr.response);var arr=new Array;for(var i=0;i!=data.length;++i)arr[i]=String.fromCharCode(data[i]);success(arr.join(""))};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.readAsBinaryString(files[0])}}};var removeFile=utils.removeFile=function(path,cb){if(typeof exports=="object"){var fs=require("fs");fs.remove(path,cb)}else if(typeof cordova=="object"){window.requestFileSystem(LocalFileSystem.PERSISTENT,0,function(fileSystem){fileSystem.root.getFile(path,{create:false},function(fileEntry){fileEntry.remove(cb);if(cb)cb()},function(){if(cb)cb()})})}else{throw new Error("You can remove files only in Node.js and Apache Cordova")}};var deleteFile=utils.deleteFile=function(path,cb){if(typeof exports=="object"){var fs=require("fs");fs.unlink(path,cb)}};var fileExists=utils.fileExists=function(path,cb){if(typeof exports=="object"){var fs=require("fs");fs.exists(path,cb)}else if(typeof cordova=="object"){window.requestFileSystem(LocalFileSystem.PERSISTENT,0,function(fileSystem){fileSystem.root.getFile(path,{create:false},function(fileEntry){cb(true)},function(){cb(false)})})}else{throw new Error("You can use exists() only in Node.js or Apach Cordova")}};var saveFile=utils.saveFile=function(path,data,cb){if(!path){alasql.options.stdout=true;console.log(data);if(cb)cb()}else{if(typeof exports=="object"){var fs=require("fs");var data=fs.writeFileSync(path,data);if(cb)cb()}else if(typeof cordova=="object"){window.requestFileSystem(LocalFileSystem.PERSISTENT,0,function(fileSystem){fileSystem.root.getFile(path,{create:true},function(fileEntry){fileEntry.createWriter(function(fileWriter){fileWriter.onwriteend=function(){if(cb)cb()};fileWriter.write(data)})})})}else{var blob=new Blob([data],{type:"text/plain;charset=utf-8"});saveAs(blob,path);if(cb)cb()}}};var hash=utils.hash=function hash(str){var h=0;if(str.length==0)return h;for(var i=0;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 xlscn=utils.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};var domEmptyChildren=utils.domEmptyChildren=function(container){var len=container.childNodes.length;while(len--){container.removeChild(container.lastChild)}};alasql.utils.uncomment=function uncomment(str){str=("__"+str+"__").split("");var quote=false,quoteSign,blockComment=false,lineComment=false;for(var i=0,l=str.length;ialasql.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{if(cb){alasql.adrun(databaseid,ast,params,cb,scope)}else{return alasql.drun(databaseid,ast,params,cb,scope)}}};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=0){var source=query.sources[idx];source.data=data;if(typeof source.data=="function"){source.getfn=source.data;source.dontcache=source.getfn.dontcache;if(source.joinmode=="OUTER"||source.joinmode=="RIGHT"||source.joinmode=="ANTI"){source.dontcache=false}source.data={}}}else{query.queriesdata[-idx-1]=flatArray(data)}query.sourceslen--;if(query.sourceslen>0)return;return queryfn3(query)}function queryfn3(query){var scope=query.scope;preIndex(query);query.data=[];query.xgroups={};query.groups=[];var h=0;doJoin(query,scope,h);if(query.groupfn){query.data=[];if(query.groups.length==0){var g={};if(query.selectGroup.length>0){query.selectGroup.forEach(function(sg){if(sg.aggregatorid=="COUNT"||sg.aggregatorid=="SUM"){g[sg.nick]=0}else{g[sg.nick]=undefined}})}query.groups=[g]}for(var i=0,ilen=query.groups.length;i0){for(var i=0,ilen=query.data.length;i0&&source.optimization=="ix"&&source.onleftfn&&source.onrightfn){if(source.databaseid&&alasql.databases[source.databaseid].tables[source.tableid]){if(!alasql.databases[source.databaseid].tables[source.tableid].indices)query.database.tables[source.tableid].indices={};var ixx=alasql.databases[source.databaseid].tables[source.tableid].indices[hash(source.onrightfns+"`"+source.srcwherefns)];if(!alasql.databases[source.databaseid].tables[source.tableid].dirty&&ixx){source.ix=ixx}}if(!source.ix){source.ix={};var scope={};var i=0;var ilen=source.data.length;var dataw;while((dataw=source.data[i])||source.getfn&&(dataw=source.getfn(i))||i=query.sources.length){if(query.wherefn(scope,query.params,alasql)){if(query.groupfn){query.groupfn(scope,query.params,query.alasql)}else{query.data.push(query.selectfn(scope,query.params,alasql))}}}else if(query.sources[h].applyselect){var source=query.sources[h];source.applyselect(query.params,function(data){if(data.length>0){for(var i=0;i0){s+=NL()+ID()+K("GROUP BY")+" "+this.group.map(function(grp){return grp.toString()}).join(", ")}if(this.having)s+=NL()+ID()+K("HAVING")+" "+this.having.toString();if(this.order&&this.order.length>0){s+=NL()+ID()+K("ORDER BY")+" "+this.order.map(function(ord){return ord.toString()}).join(", ")}if(this.limit)s+=NL()+ID()+K("LIMIT")+" "+this.limit.value;if(this.offset)s+=NL()+ID()+K("OFFSET")+" "+this.offset.value;if(this.union)s+=NL()+K("UNION")+NL()+this.union.toString();if(this.unionall)s+=NL()+K("UNION ALL")+NL()+this.unionall.toString();if(this.except)s+=NL()+K("EXCEPT")+NL()+this.except.toString();if(this.intersect)s+=NL()+K("INTERSECT")+NL()+this.intersect.toString();return s};yy.Select.prototype.toJavaScript=function(context,tableid,defcols){var s="alasql.utils.flatArray(this.queriesfn["+(this.queriesidx-1)+"](this.params,null,"+context+"))[0]";return s};yy.Select.prototype.compile=function(databaseid){var db=alasql.databases[databaseid];var query=new Query;query.removeKeys=[];query.explain=this.explain;query.explaination=[];query.explid=1;query.modifier=this.modifier;query.database=db;this.compileWhereExists(query);this.compileQueries(query);query.defcols=this.compileDefCols(query,databaseid);query.fromfn=this.compileFrom(query);if(this.joins)this.compileJoins(query);this.compileSelectGroup0(query);if(this.group||query.selectGroup.length>0){query.selectgfns=this.compileSelectGroup1(query)}else{query.selectfns=this.compileSelect1(query)}if(this.where)this.compileWhereJoins(query);query.wherefn=this.compileWhere(query);if(this.group||query.selectGroup.length>0)query.groupfn=this.compileGroup(query);if(this.having)query.havingfn=this.compileHaving(query);if(this.group||query.selectGroup.length>0){query.selectgfn=this.compileSelectGroup2(query)}else{query.selectfn=this.compileSelect2(query)}query.distinct=this.distinct;if(this.order)query.orderfn=this.compileOrder(query);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;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}}if(this.into){if(this.into instanceof yy.Table){if(alasql.options.autocommit&&alasql.databases[this.into.databaseid||databaseid].engineid){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{query.intofns="alasql.databases['"+(this.into.databaseid||databaseid)+"'].tables"+"['"+this.into.tableid+"'].data.push(r);"}}else if(this.into instanceof yy.VarValue){query.intoallfns='alasql.vars["'+this.into.variable+'"]=this.data;res=1;if(cb)res=cb(res);return res;'}else if(this.into instanceof yy.FuncValue){var qs="alasql.into['"+this.into.funcid.toUpperCase()+"'](";if(this.into.args&&this.into.args.length>0){qs+=this.into.args[0].toJavaScript()+",";if(this.into.args.length>1){qs+=this.into.args[1].toJavaScript()+","}else{qs+="null,"}}else{qs+="null, null,"}query.intoallfns=qs+"this.data,columns,cb)"}else if(this.into instanceof yy.ParamValue){query.intofns="params['"+this.into.param+"'].push(r)"}if(query.intofns){query.intofn=new Function("r,i,params,alasql",query.intofns)}if(query.intoallfns){query.intoallfn=new Function("columns,cb,alasql",query.intoallfns)}}var statement=function(params,cb,oldscope){query.params=params;var res1=queryfn(query,oldscope,function(res){var res2=modify(query,res);if(cb)cb(res2);return res2});return res1};statement.query=query;return statement};function modify(query,res){if(query.modifier=="VALUE"){if(res.length>0){var key;if(query.columns&&query.columns.length>0)key=query.columns[0].columnid;else key=Object.keys(res[0])[0];res=res[0][key]}else{res=undefined}}if(query.modifier=="ROW"){if(res.length>0){var key;if(query.columns&&query.columns.length>0)key=query.columns[0].columnid;else key=Object.keys(res[0])[0];var a=[];for(var key in res[0]){a.push(res[0][key])}res=a}else{res=undefined}}if(query.modifier=="COLUMN"){var ar=[];if(res.length>0){var key;if(query.columns&&query.columns.length>0)key=query.columns[0].columnid;else key=Object.keys(res[0])[0];for(var i=0,ilen=res.length;i0){key=query.columns[0].columnid;val=query.columns[1].columnid}else{var okeys=Object.keys(res[0]);key=okeys[0];val=okeys[1]}for(var i=0,ilen=res.length;i0)key=query.columns[0].columnid;else key=Object.keys(res[0])[0];var s="";for(var i=0,ilen=res.length;i0){if(tq.args[0]){s+=tq.args[0].toJavaScript("query.oldscope")+","}else{s+="null,"}if(tq.args[1]){s+=tq.args[1].toJavaScript("query.oldscope")+","}else{s+="null,"}}else{s+="null,null,"}s+="cb,idx,query";s+=");/*if(cb)res=cb(res,idx,query);*/return res";source.datafn=new Function("query, params, cb, idx, alasql",s)}else if(tq instanceof yy.FromData){source.datafn=function(query,params,cb,idx,alasql){var res=tq.data;if(cb)res=cb(res,idx,query);return res}}else{throw new Error("Wrong table at FROM")}query.sources.push(source)});query.defaultTableid=query.sources[0].alias};alasql.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;i0){if(jn.args[0]){s+=jn.args[0].toJavaScript("query.oldscope")+","}else{s+="null,"}if(jn.args[1]){s+=jn.args[1].toJavaScript("query.oldscope")+","}else{s+="null,"}}else{s+="null,null,"}s+="cb,idx,query";s+=");/*if(cb)res=cb(res,idx,query);*/return res";source.datafn=new Function("query, params, cb, idx, alasql",s);query.aliases[source.alias]={type:"funcvalue"}}var alias=source.alias;if(jn.natural){if(jn.using||jn.on){throw new Error("NATURAL JOIN cannot have USING or ON clauses")}else{if(query.sources.length>0){var prevSource=query.sources[query.sources.length-1];var prevTable=alasql.databases[prevSource.databaseid].tables[prevSource.tableid];var table=alasql.databases[source.databaseid].tables[source.tableid];if(prevTable&&table){var c1=prevTable.columns.map(function(col){return col.columnid});var c2=table.columns.map(function(col){return col.columnid});jn.using=arrayIntersect(c1,c2).map(function(colid){return{columnid:colid}})}else{throw new Error("In this version of Alasql NATURAL JOIN "+"works for tables with predefined columns only")}}}}if(jn.using){var prevSource=query.sources[query.sources.length-1];source.onleftfns=jn.using.map(function(col){return"p['"+(prevSource.alias||prevSource.tableid)+"']['"+col.columnid+"']"}).join('+"`"+');source.onleftfn=new Function("p,params,alasql","return "+source.onleftfns);source.onrightfns=jn.using.map(function(col){return"p['"+(source.alias||source.tableid)+"']['"+col.columnid+"']"}).join('+"`"+');source.onrightfn=new Function("p,params,alasql","return "+source.onrightfns);source.optimization="ix"}else if(jn.on){if(jn.on instanceof yy.Op&&jn.on.op=="="&&!jn.on.allsome){source.optimization="ix";var lefts="";var rights="";var middles="";var middlef=false;var ls=jn.on.left.toJavaScript("p",query.defaultTableid,query.defcols);var rs=jn.on.right.toJavaScript("p",query.defaultTableid,query.defcols);if(ls.indexOf("p['"+alias+"']")>-1&&!(rs.indexOf("p['"+alias+"']")>-1)){if((ls.match(/p\[\'.*?\'\]/g)||[]).every(function(s){return s=="p['"+alias+"']"})){rights=ls}else{middlef=true}}else if(!(ls.indexOf("p['"+alias+"']")>-1)&&rs.indexOf("p['"+alias+"']")>-1){if((rs.match(/p\[\'.*?\'\]/g)||[]).every(function(s){return s=="p['"+alias+"']"})){lefts=ls}else{middlef=true}}else{middlef=true}if(rs.indexOf("p['"+alias+"']")>-1&&!(ls.indexOf("p['"+alias+"']")>-1)){if((rs.match(/p\[\'.*?\'\]/g)||[]).every(function(s){return s=="p['"+alias+"']"})){rights=rs}else{middlef=true}}else if(!(rs.indexOf("p['"+alias+"']")>-1)&&ls.indexOf("p['"+alias+"']")>-1){if((ls.match(/p\[\'.*?\'\]/g)||[]).every(function(s){return s=="p['"+alias+"']"})){lefts=rs}else{middlef=true}}else{middlef=true}if(middlef){rights="";lefts="";middles=jn.on.toJavaScript("p",query.defaultTableid,query.defcols);source.optimization="no"}source.onleftfns=lefts;source.onrightfns=rights;source.onmiddlefns=middles||"true";source.onleftfn=new Function("p,params,alasql","return "+source.onleftfns);source.onrightfn=new Function("p,params,alasql","return "+source.onrightfns);source.onmiddlefn=new Function("p,params,alasql","return "+source.onmiddlefns)}else{source.optimization="no";source.onmiddlefns=jn.on.toJavaScript("p",query.defaultTableid,query.defcols);source.onmiddlefn=new Function("p,params,alasql","return "+jn.on.toJavaScript("p",query.defaultTableid,query.defcols))}}query.sources.push(source)}})};yy.Select.prototype.compileWhere=function(query){if(this.where){if(typeof this.where=="function"){return this.where}else{s=this.where.toJavaScript("p",query.defaultTableid,query.defcols);query.wherefns=s;return new Function("p,params,alasql","return "+s)}}else return function(){return true}};yy.Select.prototype.compileWhereJoins=function(query){return;optimizeWhereJoin(query,this.where.expression);query.sources.forEach(function(source){if(source.srcwherefns){source.srcwherefn=new Function("p,params,alasql","return "+source.srcwherefns)}if(source.wxleftfns){source.wxleftfn=new Function("p,params,alasql","return "+source.wxleftfns)}if(source.wxrightfns){source.wxrightfn=new Function("p,params,alasql","return "+source.wxrightfns)}})};function optimizeWhereJoin(query,ast){if(!ast)return false;if(!(ast instanceof yy.Op))return;if(ast.op!="="&&ast.op!="AND")return;if(ast.allsome)return;var s=ast.toJavaScript("p",query.defaultTableid,query.defcols);var fsrc=[];query.sources.forEach(function(source,idx){if(source.tableid){if(s.indexOf("p['"+source.alias+"']")>-1)fsrc.push(source)}});if(fsrc.length==0){return}else if(fsrc.length==1){if(!(s.match(/p\[\'.*?\'\]/g)||[]).every(function(s){return s=="p['"+fsrc[0].alias+"']"})){return}var src=fsrc[0];src.srcwherefns=src.srcwherefns?src.srcwherefns+"&&"+s:s;if(ast instanceof yy.Op&&(ast.op=="="&&!ast.allsome)){if(ast.left instanceof yy.Column){var ls=ast.left.toJavaScript("p",query.defaultTableid,query.defcols);var rs=ast.right.toJavaScript("p",query.defaultTableid,query.defcols);if(rs.indexOf("p['"+fsrc[0].alias+"']")==-1){fsrc[0].wxleftfns=ls;fsrc[0].wxrightfns=rs}}if(ast.right instanceof yy.Column){var ls=ast.left.toJavaScript("p",query.defaultTableid,query.defcols);var rs=ast.right.toJavaScript("p",query.defaultTableid,query.defcols);if(ls.indexOf("p['"+fsrc[0].alias+"']")==-1){fsrc[0].wxleftfns=rs;fsrc[0].wxrightfns=ls}}}ast.reduced=true;return}else{if(ast.op="AND"){optimizeWhereJoin(query,ast.left);optimizeWhereJoin(query,ast.right)}}}yy.Select.prototype.compileGroup=function(query){var self=this;var tableid=query.sources[0].alias;var defcols=query.defcols;var allgroup=[[]]; -if(this.group){allgroup=decartes(this.group,query)}var allgroups=[];allgroup.forEach(function(a){allgroups=arrayUnion(allgroups,a)});query.allgroups=allgroups;if(false){allgroups.forEach(function(col2){if(query.selectColumns[colid]){}else{var tmpid="default";if(query.sources.length>0)tmpid=query.sources[0].alias;if(Object.keys(query.selectColumns).length!=0)query.removeKeys.push(colid);query.selectfns+="r['"+escapeq(colid)+"']="+new yy.Column({columnid:colid}).toJavaScript("p",tmpid)+";"}})}var s="";allgroup.forEach(function(agroup){s+="var g=this.xgroups[";var rg=agroup.map(function(col2){var columnid=col2.split(" ")[0];var coljs=col2.split(" ")[1];if(columnid=="")return"1";else 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(" ")[0];var coljs=col2.split(" ")[1];if(columnid=="")return"";else return"'"+columnid+"':"+coljs+","}).join("");var neggroup=arrayDiff(allgroups,agroup);s+=neggroup.map(function(col2){var columnid=col2.split(" ")[0];var coljs=col2.split(" ")[1];return"'"+columnid+"':null,"}).join("");var aft="";s+=query.selectGroup.map(function(col,idx){var colexp=col.expression.toJavaScript("p",tableid,defcols);var colas=col.nick;if(col instanceof yy.AggrValue){if(col.distinct){aft+=",g['$$_VALUES_"+colas+"']={},g['$$_VALUES_"+colas+"']["+colexp+"]=true"}if(col.aggregatorid=="SUM"||col.aggregatorid=="MIN"||col.aggregatorid=="MAX"||col.aggregatorid=="FIRST"||col.aggregatorid=="LAST"){return"'"+colas+"':"+colexp+","}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+",'_COUNT_"+colas+"':1,"}else if(col.aggregatorid=="AGGR"){aft+=",g['"+colas+"']="+col.expression.toJavaScript("g",-1);return""}else if(col.aggregatorid=="REDUCE"){return"'"+colas+"':alasql.aggr['"+col.funcid+"']("+colexp+"),"}return""}else return""}).join("");s+="}"+aft+",g));} else {";s+=query.selectGroup.map(function(col,idx){var colas=col.nick;var colexp=col.expression.toJavaScript("p",tableid,defcols);if(col instanceof yy.AggrValue){if(col.distinct){var pre="if(typeof "+colexp+'!="undefined" && (!g[\'$$_VALUES_'+colas+"']["+colexp+"])) {";var post="g['$$_VALUES_"+colas+"']["+colexp+"]=true;}"}else{var pre="",post=""}if(col.aggregatorid=="SUM"){return pre+"g['"+colas+"']+="+colexp+";"+post}else if(col.aggregatorid=="COUNT"){if(col.expression.columnid=="*")return pre+"g['"+colas+"']++;"+post;else{return pre+"if(typeof "+colexp+'!="undefined") g[\''+colas+"']++;"+post}}else if(col.aggregatorid=="ARRAY"){return pre+"g['"+colas+"'].push("+colexp+");"+post}else if(col.aggregatorid=="MIN"){return pre+"g['"+colas+"']=Math.min(g['"+colas+"'],"+colexp+");"+post}else if(col.aggregatorid=="MAX"){return pre+"g['"+colas+"']=Math.max(g['"+colas+"'],"+colexp+");"+post}else if(col.aggregatorid=="FIRST"){return""}else if(col.aggregatorid=="LAST"){return pre+"g['"+colas+"']="+colexp+";"+post}else if(col.aggregatorid=="AVG"){return pre+"g['_SUM_"+colas+"']+="+colexp+";"+"g['_COUNT_"+colas+"']++;"+"g['"+colas+"']=g['_SUM_"+colas+"']/g['_COUNT_"+colas+"'];"+post}else if(col.aggregatorid=="AGGR"){return pre+"g['"+colas+"']="+col.expression.toJavaScript("g",-1)+";"+post}else if(col.aggregatorid=="REDUCE"){return pre+"g['"+colas+"']=alasql.aggr."+col.funcid+"("+colexp+",g['"+colas+"']);"+post}return""}else return""}).join("");s+="}"});return new Function("p,params,alasql",s)};function compileSelectStar(query,alias){var s="",sp="",ss=[];if(query.aliases[alias].tableid){var columns=alasql.databases[query.aliases[alias].databaseid].tables[query.aliases[alias].tableid].columns}if(columns&&columns.length>0){columns.forEach(function(tcol){ss.push("'"+tcol.columnid+"':p['"+alias+"']['"+tcol.columnid+"']");query.selectColumns[escapeq(tcol.columnid)]=true;var coldef={columnid:tcol.columnid,dbtypeid:tcol.dbtypeid,dbsize:tcol.dbsize,dbprecision:tcol.dbprecision,dbenum:tcol.dbenum};query.columns.push(coldef);query.xcolumns[coldef.columnid]=coldef})}else{sp+='var w=p["'+alias+'"];for(var k in w){r[k]=w[k]};';query.dirtyColumns=true}return{s:ss.join(","),sp:sp}}yy.Select.prototype.compileSelect1=function(query){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){var ret=compileSelectStar(query,col.tableid);if(ret.s)ss=ss.concat(ret.s);sp+=ret.sp}else{for(var alias in query.aliases){var ret=compileSelectStar(query,alias);if(ret.s)ss=ss.concat(ret.s);sp+=ret.sp}}}else{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!="_"){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];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{query.dirtyColumns=true}}else{}}}else if(col instanceof yy.AggrValue){if(!self.group){self.group=[""]}if(!col.as)col.as=escapeq(col.toString());if(col.aggregatorid=="SUM"||col.aggregatorid=="MAX"||col.aggregatorid=="MIN"||col.aggregatorid=="FIRST"||col.aggregatorid=="LAST"||col.aggregatorid=="AVG"||col.aggregatorid=="ARRAY"||col.aggregatorid=="REDUCE"){ss.push("'"+escapeq(col.as)+"':"+col.expression.toJavaScript("p",query.defaultTableid,query.defcols))}else if(col.aggregatorid=="COUNT"){ss.push("'"+escapeq(col.as)+"':1")}query.selectColumns[col.aggregatorid+"("+escapeq(col.expression.toString())+")"]=thtd}else{ss.push("'"+escapeq(col.as||col.columnid||col.toString())+"':"+col.toJavaScript("p",query.defaultTableid,query.defcols));query.selectColumns[escapeq(col.as||col.columnid||col.toString())]=true}});s+=ss.join(",")+"};"+sp;return s};yy.Select.prototype.compileSelect2=function(query){var s=query.selectfns;return new Function("p,params,alasql",s+"return r")};yy.Select.prototype.compileSelectGroup0=function(query){var self=this;self.columns.forEach(function(col,idx){if(col instanceof yy.Column&&col.columnid=="*"){}else{var colas;if(col instanceof yy.Column){colas=escapeq(col.columnid)}else{colas=escapeq(col.toString())}for(var i=0;irb)return 1;if(ra==rb)return 0;return-1}}var s="";var sk="";this.order.forEach(function(ord,idx){var dg="";if(ord.expression instanceof yy.NumValue){ord.expression=self.columns[ord.expression.value-1]}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")dg=".valueOf()"}else{if(alasql.options.valueof)dg=".valueOf()"}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()";if(ord.nocase)dg+=".toUpperCase()";s+="if("+ord.toJavaScript("a","")+dg+(ord.direction=="ASC"?">":"<")+ord.toJavaScript("b","")+dg+")return 1;";s+="if("+ord.toJavaScript("a","")+dg+"=="+ord.toJavaScript("b","")+dg+"){"}sk+="}"});s+="return 0;";s+=sk+"return -1";query.orderfns=s;return new Function("a,b",s)}};var rollup=function(a,query){var rr=[];var mask=0;var glen=a.length;for(var g=0;g"){var s=this.left.toString()+"->";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()+" "+P(this.op)+" "+(this.allsome?this.allsome+" ":"")+this.right.toString()};yy.Op.prototype.findAggregator=function(query){if(this.left&&this.left.findAggregator)this.left.findAggregator(query);if(this.right&&this.right.findAggregator&&!this.allsome){this.right.findAggregator(query)}};yy.Op.prototype.toType=function(tableid){if(["-","*","/","%","^"].indexOf(this.op)>-1)return"number";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"].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"};yy.Op.prototype.toJavaScript=function(context,tableid,defcols){var op=this.op;if(this.op=="=")op="===";else if(this.op=="<>")op="!=";else if(this.op=="OR")op="||";if(this.op=="->"){if(typeof this.right=="string"){return this.left.toJavaScript(context,tableid,defcols)+'["'+this.right+'"]'}else if(typeof this.right=="number"){return this.left.toJavaScript(context,tableid,defcols)+"["+this.right+"]"}else if(this.right instanceof yy.FuncValue){ss=[];if(!this.right.args||this.right.args.length==0){}else{var ss=this.right.args.map(function(arg){return arg.toJavaScript(context,tableid,defcols)})}return this.left.toJavaScript(context,tableid,defcols)+"['"+this.right.funcid+"']("+ss.join(",")+")"}else{return this.left.toJavaScript(context,tableid,defcols)+"["+this.right.toJavaScript(context,tableid,defcols)+"]"}}if(this.op=="IS"){return"((typeof "+this.left.toJavaScript(context,tableid,defcols)+"=='undefined') == "+"(typeof "+this.right.toJavaScript(context,tableid,defcols)+"=='undefined'))"}if(this.op=="=="){return"alasql.utils.deepEqual("+this.left.toJavaScript(context,tableid,defcols)+","+this.right.toJavaScript(context,tableid,defcols)+")"}if(this.op=="==="){return"(("+this.left.toJavaScript(context,tableid,defcols)+").valueOf()===("+this.right.toJavaScript(context,tableid,defcols)+".valueOf()))"}if(this.op=="!==="){return"!(("+this.left.toJavaScript(context,tableid,defcols)+").valueOf()===("+this.right.toJavaScript(context,tableid,defcols)+".valueOf()))"}if(this.op=="!=="){return"(!alasql.utils.deepEqual("+this.left.toJavaScript(context,tableid,defcols)+","+this.right.toJavaScript(context,tableid,defcols)+"))"}if(this.op=="LIKE"){var s="("+this.left.toJavaScript(context,tableid,defcols)+"+'')"+".toUpperCase().match(new RegExp('^'+("+this.right.toJavaScript(context,tableid,defcols)+").replace(/\\%/g,'.*').toUpperCase()+'$','g'))";return s}if(this.op=="NOT LIKE"){var s="!(("+this.left.toJavaScript(context,tableid,defcols)+"+'')"+".toUpperCase().match(new RegExp('^'+("+this.right.toJavaScript(context,tableid,defcols)+").replace(/\\%/g,'.*').toUpperCase()+'$','g')))";return s}if(this.op=="BETWEEN"){if(this.right instanceof yy.Op&&this.right.op=="AND"){return"(("+this.right.left.toJavaScript(context,tableid,defcols)+"<="+this.left.toJavaScript(context,tableid,defcols)+")&&"+"("+this.left.toJavaScript(context,tableid,defcols)+"<="+this.right.right.toJavaScript(context,tableid,defcols)+"))"}else{throw new Error("Wrong BETWEEN operator without AND part")}}if(this.op=="NOT BETWEEN"){if(this.right instanceof yy.Op&&this.right.op=="AND"){return"!(("+this.right.left.toJavaScript(context,tableid,defcols)+"<="+this.left.toJavaScript(context,tableid,defcols)+")&&"+"("+this.left.toJavaScript(context,tableid,defcols)+"<="+this.right.right.toJavaScript(context,tableid,defcols)+"))"}else{throw new Error("Wrong NOT BETWEEN operator without AND part")}}if(this.op=="IN"){if(this.right instanceof yy.Select){var s="(";s+="alasql.utils.flatArray(this.query.queriesfn["+this.queriesidx+"](params,null,p))";s+=".indexOf(";s+=this.left.toJavaScript(context,tableid,defcols)+")>-1)";return s}else if(this.right instanceof Array){var s="(["+this.right.map(function(a){return a.toJavaScript(context,tableid,defcols)}).join(",")+"].indexOf(";s+=this.left.toJavaScript(context,tableid,defcols)+")>-1)";return s}else{var s="("+this.right.toJavaScript(context,tableid,defcols)+".indexOf(";s+=this.left.toJavaScript(context,tableid,defcols)+")>-1)";return s}}if(this.op=="NOT IN"){if(this.right instanceof yy.Select){var s="(";s+="alasql.utils.flatArray(this.query.queriesfn["+this.queriesidx+"](params,null,p))";s+=".indexOf(";s+=this.left.toJavaScript(context,tableid,defcols)+")<0)";return s}else if(this.right instanceof Array){var s="(["+this.right.map(function(a){return a.toJavaScript(context,tableid,defcols)}).join(",")+"].indexOf(";s+=this.left.toJavaScript(context,tableid,defcols)+")<0)";return s}else{throw new Error("Wrong NOT IN operator without SELECT part")}}if(this.allsome=="ALL"){if(this.right instanceof yy.Select){var s="alasql.utils.flatArray(this.query.queriesfn["+this.queriesidx+"](params,null,p))";s+=".every(function(b){return (";s+=this.left.toJavaScript(context,tableid,defcols)+")"+op+"b})";return s}else if(this.right instanceof Array){var s="["+this.right.map(function(a){return a.toJavaScript(context,tableid,defcols)}).join(",")+"].every(function(b){return (";s+=this.left.toJavaScript(context,tableid,defcols)+")"+op+"b})";return s}else{throw new Error("Wrong NOT IN operator without SELECT part")}}if(this.allsome=="SOME"||this.allsome=="ANY"){if(this.right instanceof yy.Select){var s="alasql.utils.flatArray(this.query.queriesfn["+this.queriesidx+"](params,null,p))";s+=".some(function(b){return (";s+=this.left.toJavaScript(context,tableid,defcols)+")"+op+"b})";return s}else if(this.right instanceof Array){var s="["+this.right.map(function(a){return a.toJavaScript(context,tableid,defcols)}).join(",")+"].some(function(b){return (";s+=this.left.toJavaScript(context,tableid,defcols)+")"+op+"b})";return s}else{throw new Error("Wrong NOT IN operator without SELECT part")}}if(this.op=="AND"){if(this.left.reduced){if(this.right.reduced){return"true"}else{return this.right.toJavaScript(context,tableid,defcols)}}else if(this.right.reduced){return this.left.toJavaScript(context,tableid,defcols)}op="&&"}if(this.op=="^"){return"Math.pow("+this.left.toJavaScript(context,tableid,defcols)+","+this.right.toJavaScript(context,tableid,defcols)+")"}return"("+this.left.toJavaScript(context,tableid,defcols)+op+this.right.toJavaScript(context,tableid,defcols)+")"};yy.VarValue=function(params){return yy.extend(this,params)};yy.VarValue.prototype.toString=function(){return"@"+L(this.variable)};yy.VarValue.prototype.toType=function(){return"unknown"};yy.VarValue.prototype.toJavaScript=function(){return"alasql.vars['"+this.variable+"']"};yy.NumValue=function(params){return yy.extend(this,params)};yy.NumValue.prototype.toString=function(){return N(this.value.toString())};yy.NumValue.prototype.toType=function(){return"number"};yy.NumValue.prototype.toJavaScript=function(){return""+this.value};yy.StringValue=function(params){return yy.extend(this,params)};yy.StringValue.prototype.toString=function(){return"'"+S(this.value.toString())+"'"};yy.StringValue.prototype.toType=function(){return"string"};yy.StringValue.prototype.toJavaScript=function(){return"'"+escapeq(this.value)+"'"};yy.LogicValue=function(params){return yy.extend(this,params)};yy.LogicValue.prototype.toString=function(){return this.value?"TRUE":"FALSE"};yy.LogicValue.prototype.toType=function(){return"boolean"};yy.LogicValue.prototype.toJavaScript=function(){return this.value?"true":"false"};yy.NullValue=function(params){return yy.extend(this,params)};yy.NullValue.prototype.toString=function(){return"NULL"};yy.NullValue.prototype.toJavaScript=function(){return"undefined"};yy.ParamValue=function(params){return yy.extend(this,params)};yy.ParamValue.prototype.toString=function(){return"$"+this.param};yy.ParamValue.prototype.toJavaScript=function(){if(typeof this.param=="string")return"params['"+this.param+"']";else return"params["+this.param+"]"};yy.UniOp=function(params){return yy.extend(this,params)};yy.UniOp.prototype.toString=function(){if(this.op=="-")return this.op+this.right.toString();if(this.op=="+")return this.op+this.right.toString();if(this.op=="NOT")return this.op+"("+this.right.toString()+")";else if(this.op==null)return"("+this.right.toString()+")"};yy.UniOp.prototype.findAggregator=function(query){if(this.right.findAggregator)this.right.findAggregator(query)};yy.UniOp.prototype.toType=function(tableid){if(this.op=="-")return"number";if(this.op=="+")return"number";if(this.op=="NOT")return"boolean"};yy.UniOp.prototype.toJavaScript=function(context,tableid,defcols){if(this.op=="-")return"(-("+this.right.toJavaScript(context,tableid,defcols)+"))";if(this.op=="+")return"("+this.right.toJavaScript(context,tableid,defcols)+")";if(this.op=="NOT")return"!("+this.right.toJavaScript(context,tableid,defcols)+")";else if(this.op==null)return"("+this.right.toJavaScript(context,tableid,defcols)+")"};yy.Column=function(params){return yy.extend(this,params)};yy.Column.prototype.toString=function(){var s;if(this.columnid==+this.columnid){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}}return s};yy.Column.prototype.toJavaScript=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"){s="g['"+this.nick+"']"}else if(this.tableid){if(this.columnid!="_"){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!="_"){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)+"']"}}}return s};yy.AggrValue=function(params){return yy.extend(this,params)};yy.AggrValue.prototype.toString=function(){var s="";if(this.aggregatorid=="REDUCE")s+=L(this.funcid)+"(";else s+=this.aggregatorid+"(";if(this.distinct)s+=K("DISTINCT")+" ";if(this.expression)s+=this.expression.toString();s+=")";if(this.over)s+=" "+this.over.toString();return s};yy.AggrValue.prototype.findAggregator=function(query){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-1)return"number";if(["ARRAY"].indexOf(this.aggregatorid)>-1)return"array";if(["FIRST","LAST"].indexOf(this.aggregatorid)>-1)return this.expression.toType()};yy.AggrValue.prototype.toJavaScript=function(context,tableid,defcols){var colas=this.nick;if(typeof colas=="undefined")colas=this.toString();return"g['"+colas+"']"};yy.OrderExpression=function(params){return yy.extend(this,params)};yy.OrderExpression.prototype.toString=function(){var s=this.expression.toString();if(this.order)s+=" "+this.order.toString();if(this.nocase)s+=" "+K("COLLATE")+" "+K("NOCASE");return s};yy.GroupExpression=function(params){return yy.extend(this,params)};yy.GroupExpression.prototype.toString=function(){return this.type+"("+this.group.toString()+")"};yy.ColumnDef=function(params){return yy.extend(this,params)};yy.ColumnDef.prototype.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};yy.FromData=function(params){return yy.extend(this,params)};yy.FromData.prototype.toString=function(){if(this.data)return K("DATA")+"("+(Math.random()*1e16|0)+")";else return"?"};yy.FromData.prototype.toJavaScript=function(){};yy.Select.prototype.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;if(db.sqlCacheSize>alasql.MAXSQLCACHESIZE){db.resetSqlCache()}db.sqlCacheSize++;db.sqlCache[hh]=statement;var res=alasql.res=statement(params,cb);return res};yy.Select.prototype.Select=function(){var self=this;var agrs=[];if(arguments.length>1){args=Array.prototype.slice.call(arguments)}else if(arguments.length==1){if(arguments[0]instanceof Array){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{}});return self};yy.Select.prototype.From=function(tableid){var self=this;if(!self.from)self.from=[];if(tableid instanceof Array){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};yy.Select.prototype.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(arguments[0]instanceof Array){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};yy.Select.prototype.Top=function(topnum){var self=this;self.top=new yy.NumValue({value:topnum});return self};yy.Select.prototype.GroupBy=function(){var self=this;var agrs=[];if(arguments.length>1){args=Array.prototype.slice.call(arguments) -}else if(arguments.length==1){if(arguments[0]instanceof Array){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};yy.Select.prototype.Where=function(expr){var self=this;if(typeof expr=="function"){self.where=expr}return self};yy.FuncValue=function(params){return yy.extend(this,params)};yy.FuncValue.prototype.toString=function(){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)s+=" AS "+this.as.toString();return s};yy.FuncValue.prototype.findAggregator=function(query){if(this.args&&this.args.length>0){this.args.forEach(function(arg){if(arg.findAggregator)arg.findAggregator(query)})}};yy.FuncValue.prototype.toJavaScript=function(context,tableid,defcols){var s="";var funcid=this.funcid;if(alasql.fn[funcid]){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.toJavaScript(context,tableid,defcols)}).join(",")}s+=")"}else if(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.toJavaScript(context,tableid)}))}else{s+=alasql.stdlib[funcid.toUpperCase()]()}}else if(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.toJavaScript(context,tableid,defcols)}).join(",")}s+=")"}else{}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+")"};stdlib.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")}};stdlib.IFNULL=function(a,b){return"("+a+"||"+b+")"};stdlib.INSTR=function(s,p){return"(("+s+").indexOf("+p+")+1)"};stdlib.LEN=stdlib.LENGTH=function(s){return"("+s+'+"").length'};stdlib.LOWER=stdlib.LCASE=function(s){return"("+s+").toLowerCase()"};stdlib.GREATEST=function(){return"Math.max("+Array.prototype.join.call(arguments,",")+")"};stdlib.LEAST=function(){return"Math.min("+Array.prototype.join.call(arguments,",")+")"};stdlib.MID=function(a,b,c){if(arguments.length==2)return"("+a+").substr("+b+"-1)";else if(arguments.length==3)return"("+a+").substr("+b+"-1,"+c+")"};stdlib.NULLIF=function(a,b){return"("+a+"=="+b+"?null:"+a+")"};stdlib.POWER=function(a,b){return"Math.pow("+a+","+b+")"};stdlib.RANDOM=function(r){if(arguments.length==0){return"Math.random()"}else{return"(Math.random()*("+r+")|0)"}};stdlib.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+")"}};stdlib.SQRT=function(s){return"Math.sqrt("+s+")"};stdlib.TRIM=function(s){return s+".trim()"};stdlib.UPPER=stdlib.UCASE=function(s){return"("+s+").toUpperCase()"};alasql.aggr.GROUP_CONCAT=function(v,s){if(typeof s=="undefined")return v;else return s+","+v};yy.CaseValue=function(params){return yy.extend(this,params)};yy.CaseValue.prototype.toString=function(){var s="CASE ";if(this.expression)s+=this.expression.toString();if(this.whens){s+=this.whens.map(function(w){return" WHEN "+w.when.toString()+" THEN "+w.then.toString()}).join()}s+=" END";return s};yy.CaseValue.prototype.findAggregator=function(query){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)})}};yy.CaseValue.prototype.toJavaScript=function(context,tableid,defcols){var s="(function("+context+",params,alasql){var r;";if(this.expression){s+="v="+this.expression.toJavaScript(context,tableid,defcols)+";";s+=(this.whens||[]).map(function(w){return" if(v=="+w.when.toJavaScript(context,tableid,defcols)+") {r="+w.then.toJavaScript(context,tableid,defcols)+"}"}).join(" else ");if(this.elses)s+=" else {r="+this.elses.toJavaScript(context,tableid,defcols)+"}"}else{s+=(this.whens||[]).map(function(w){return" if("+w.when.toJavaScript(context,tableid,defcols)+") {r="+w.then.toJavaScript(context,tableid,defcols)+"}"}).join(" else ");if(this.elses)s+=" else {r="+this.elses.toJavaScript(context,tableid,defcols)+"}"}s+="return r;})("+context+",params,alasql)";return s};yy.Json=function(params){return yy.extend(this,params)};yy.Json.prototype.toString=function(){var s="@";s+=JSONtoString(this.value);s+="";return s};var JSONtoString=alasql.utils.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(obj instanceof Array){s+="["+obj.map(function(b){return JSONtoString(b)}).join(",")+"]"}else if(!obj.toJavaScript||obj instanceof yy.Json){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};function JSONtoJavaScript(obj,context,tableid,defcols){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(obj instanceof Array){s+="["+obj.map(function(b){return JSONtoJavaScript(b,context,tableid,defcols)}).join(",")+"]"}else if(!obj.toJavaScript||obj instanceof yy.Json){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+=":"+JSONtoJavaScript(obj[k],context,tableid,defcols);ss.push(s1)}s+=ss.join(",")+"}"}else if(obj.toJavaScript){s=obj.toJavaScript(context,tableid,defcols)}else{throw new Error("1Can not parse JSON object "+JSON.stringify(obj))}}else{throw new Error("2Can not parse JSON object "+JSON.stringify(obj))}return s}yy.Json.prototype.toJavaScript=function(context,tableid,defcols){return JSONtoJavaScript(this.value,context,tableid,defcols)};yy.Convert=function(params){return yy.extend(this,params)};yy.Convert.prototype.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};yy.Convert.prototype.toJavaScript=function(context,tableid,defcols){return"alasql.stdfn.CONVERT("+this.expression.toJavaScript(context,tableid,defcols)+',{dbtypeid:"'+this.dbtypeid+'",dbsize:'+this.dbsize+",style:"+this.style+"})";throw new Error("There is not such type conversion for "+this.toString())};alasql.stdfn.CONVERT=function(value,args){var val=value;if(args.style){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);if(args.style==1){val=("0"+(t.getMonth()+1)).substr(-2)+"/"+("0"+t.getDate()).substr(-2)+"/"+("0"+t.getYear()).substr(-2)}else if(args.style==2){val=("0"+t.getYear()).substr(-2)+"."+("0"+(t.getMonth()+1)).substr(-2)+"."+("0"+t.getDate()).substr(-2)}else if(args.style==3){val=("0"+t.getDate()).substr(-2)+"/"+("0"+(t.getMonth()+1)).substr(-2)+"/"+("0"+t.getYear()).substr(-2)}else if(args.style==4){val=("0"+t.getDate()).substr(-2)+"."+("0"+(t.getMonth()+1)).substr(-2)+"."+("0"+t.getYear()).substr(-2)}else if(args.style==5){val=("0"+t.getDate()).substr(-2)+"-"+("0"+(t.getMonth()+1)).substr(-2)+"-"+("0"+t.getYear()).substr(-2)}else if(args.style==6){val=("0"+t.getDate()).substr(-2)+" "+t.toString().substr(4,3).toLowerCase()+" "+("0"+t.getYear()).substr(-2)}else if(args.style==7){val=t.toString().substr(4,3)+" "+("0"+t.getDate()).substr(-2)+","+("0"+t.getYear()).substr(-2)}else if(args.style==8){val=("0"+t.getHours()).substr(-2)+":"+("0"+(t.getMinutes()+1)).substr(-2)+":"+("0"+t.getSeconds()).substr(-2)}else if(args.style==10){val=("0"+(t.getMonth()+1)).substr(-2)+"-"+("0"+t.getDate()).substr(-2)+"-"+("0"+t.getYear()).substr(-2)}else if(args.style==11){val=("0"+t.getYear()).substr(-2)+"/"+("0"+(t.getMonth()+1)).substr(-2)+"/"+("0"+t.getDate()).substr(-2)}else if(args.style==12){val=("0"+t.getYear()).substr(-2)+("0"+(t.getMonth()+1)).substr(-2)+("0"+t.getDate()).substr(-2)}else if(args.style==101){val=("0"+(t.getMonth()+1)).substr(-2)+"/"+("0"+t.getDate()).substr(-2)+"/"+t.getFullYear()}else if(args.style==102){val=t.getFullYear()+"."+("0"+(t.getMonth()+1)).substr(-2)+"."+("0"+t.getDate()).substr(-2)}else if(args.style==103){val=("0"+t.getDate()).substr(-2)+"/"+("0"+(t.getMonth()+1)).substr(-2)+"/"+t.getFullYear()}else if(args.style==104){val=("0"+t.getDate()).substr(-2)+"."+("0"+(t.getMonth()+1)).substr(-2)+"."+t.getFullYear()}else if(args.style==105){val=("0"+t.getDate()).substr(-2)+"-"+("0"+(t.getMonth()+1)).substr(-2)+"-"+t.getFullYear()}else if(args.style==106){val=("0"+t.getDate()).substr(-2)+" "+t.toString().substr(4,3).toLowerCase()+" "+t.getFullYear()}else if(args.style==107){val=t.toString().substr(4,3)+" "+("0"+t.getDate()).substr(-2)+","+t.getFullYear()}else if(args.style==108){val=("0"+t.getHours()).substr(-2)+":"+("0"+(t.getMinutes()+1)).substr(-2)+":"+("0"+t.getSeconds()).substr(-2)}else if(args.style==110){val=("0"+(t.getMonth()+1)).substr(-2)+"-"+("0"+t.getDate()).substr(-2)+"-"+t.getFullYear()}else if(args.style==111){val=t.getFullYear()+"/"+("0"+(t.getMonth()+1)).substr(-2)+"/"+("0"+t.getDate()).substr(-2)}else if(args.style==112){val=t.getFullYear()+("0"+(t.getMonth()+1)).substr(-2)+("0"+t.getDate()).substr(-2)}else{throw new Error("The CONVERT style "+args.style+" is not realized yet.")}}if(args.dbtypeid=="Date"){return new Date(val)}else if(args.dbtypeid.toUpperCase()=="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(args.dbtypeid=="DATETIME"){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()).substr(-3);return s}else if(args.dbtypeid.toUpperCase()=="STRING"){return""+val}else if(args.dbtypeid.toUpperCase()=="NUMBER"||args.dbtypeid=="FLOAT"){return+val}else if(args.dbtypeid.toUpperCase()=="MONEY"){var m=+val;return(m|0)+m*100%100/100}else if(args.dbtypeid.toUpperCase()=="BOOLEAN"){return!!val}else if(args.dbtypeid.toUpperCase()=="INT"){return val|0}else if(args.dbtypeid.toUpperCase()=="VARCHAR"||args.dbtypeid=="NVARCHAR"){if(args.dbsize)return(""+val).substr(0,args.dbsize);else return""+val}else if(args.dbtypeid.toUpperCase()=="CHAR"||args.dbtypeid=="NCHAR"){return(val+new Array(args.dbsize+1).join(" ")).substr(0,args.dbsize)}};yy.ColumnDef=function(params){return yy.extend(this,params)};yy.ColumnDef.prototype.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};yy.CreateTable=function(params){return yy.extend(this,params)};yy.CreateTable.prototype.toString=function(){var s=K("CREATE");if(this.temporary)s+=" "+K("TEMPORARY");if(this.view)s+=" "+K("VIEW");else s+=" "+K("TABLE");if(this.ifnotexists)s+=" "+K("IF")+" "+K("NOT")+" "+K("EXISTS");s+=" "+this.table.toString();if(this.viewcolumns){s+="("+this.viewcolumns.map(function(vcol){return vcol.toString()}).join(",")+")"}if(this.as)s+=" "+K("AS")+" "+L(this.as);else{var ss=this.columns.map(function(col){return col.toString()});s+=" ("+NL()+ID()+ss.join(","+NL()+ID())+")"}if(this.view&&this.select){s+=" AS "+this.select.toString()}return s};yy.CreateTable.prototype.execute=function(databaseid,params,cb){var db=alasql.databases[this.table.databaseid||databaseid];var tableid=this.table.tableid;if(!tableid){throw new Error("Table name is not defined")}var columns=this.columns;var constraints=this.constraints||[];if(this.ifnotexists&&db.tables[tableid])return 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;var ss=[];if(this.columns){this.columns.forEach(function(col){var dbtypeid=col.dbtypeid;if(!alasql.fn[dbtypeid])dbtypeid=dbtypeid.toUpperCase();var newcol={columnid:col.columnid,dbtypeid:dbtypeid};if(col.default){ss.push("'"+col.columnid+"':"+col.default.toJavaScript())}table.columns.push(newcol);table.xcolumns[newcol.columnid]=newcol;if(col.primarykey){var pk=table.pk={};pk.columns=[col.columnid];pk.onrightfns="r['"+col.columnid+"']";pk.onrightfn=new Function("r","return "+pk.onrightfns);pk.hh=hash(pk.onrightfns);table.indices[pk.hh]={}}})}table.defaultfns=ss.join(",");constraints.forEach(function(con){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","return "+pk.onrightfns);pk.hh=hash(pk.onrightfns);table.indices[pk.hh]={}}});if(this.view&&this.viewcolumns){var self=this;this.viewcolumns.forEach(function(vcol,idx){self.select.columns[idx].as=vcol.columnid})}if(db.engineid){return alasql.engines[db.engineid].createTable(this.table.databaseid||databaseid,tableid,this.ifnotexists,cb)}table.insert=function(r){if(this.pk){var pk=this.pk;var addr=pk.onrightfn(r);if(typeof this.indices[pk.hh][addr]!="undefined"){throw new Error("Cannot insert record, because it already exists in primary key")}else{table.data.push(r);this.indices[pk.hh][addr]=r}}else{table.data.push(r)}};table.delete=function(i){if(this.pk){var r=this.data[i];var pk=this.pk;var addr=pk.onrightfn(r);if(typeof this.indices[pk.hh][addr]=="undefined"){throw new Error("Something wrong with index on table")}else{this.indices[pk.hh][addr]=undefined}}};table.deleteall=function(){this.data.length=0;if(this.pk){this.indices[this.pk.hh]={}}};table.update=function(assignfn,i,params){if(this.pk){var r=this.data[i];var pk=this.pk;var addr=pk.onrightfn(r,params);if(typeof this.indices[pk.hh][addr]=="undefined"){throw new Error("Something wrong with index on table")}else{this.indices[pk.hh][addr]=undefined;assignfn(r,params,alasql);var newaddr=pk.onrightfn(r);if(typeof this.indices[pk.hh][newaddr]!="undefined"){throw new Error("Record already exists")}else{this.indices[pk.hh][newaddr]=r}}}else{assignfn(this.data[i],params,alasql)}};if(this.view&&this.select){table.view=true;table.select=this.select.compile(this.table.databaseid||databaseid)}if(cb)cb(1);return 1};alasql.fn.Date=Object;alasql.fn.Date=Date;alasql.fn.Number=Number;alasql.fn.String=String;alasql.fn.Boolean=Boolean;stdfn.EXTEND=alasql.utils.extend;stdfn.CHAR=String.fromCharCode.bind(String);stdfn.ASCII=function(a){return a.charCodeAt(0)};stdfn.COALESCE=function(){for(var i=0;i0){for(var i=0,ilen=table.data.length;i0){for(var i=0,ilen=table.data.length;i=0){q+="+"+values[idx].toJavaScript()}else if(alasql.fn[table.xcolumns[col.columnid].dbtypeid]){q+="(new "+table.xcolumns[col.columnid].dbtypeid+"(";q+=values[idx].toJavaScript();q+="))"}else{q+=values[idx].toJavaScript()}}else{q+=values[idx].toJavaScript()}ss.push(q)})}else{if(values instanceof Array&&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].toJavaScript()}else if(alasql.fn[col.dbtypeid]){q+="(new "+col.dbtypeid+"(";q+=values[idx].toJavaScript();q+="))"}else{q+=values[idx].toJavaScript()}ss.push(q)})}else{sw=JSONtoJavaScript(values)}}if(db.tables[tableid].defaultfns)ss.unshift(db.tables[tableid].defaultfns);if(sw){s+="a="+sw+";"}else{s+="a={"+ss.join(",")+"};"}if(db.tables[tableid].insert){s+="alasql.databases['"+databaseid+"'].tables['"+tableid+"'].insert(a);"}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);"}s+="return "+self.values.length;var insertfn=new Function("db, params, alasql",s3+s)}else if(this.select){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,null,cb);return res};return statement}else{var insertfn=function(db,params,alasql){var res=selectfn(params);db.tables[tableid].data=db.tables[tableid].data.concat(res);return res.length}}}else if(this.default){var insertfns="db.tables['"+tableid+"'].data.push({"+table.defaultfns+"});return 1;";var insertfn=new Function("db,params,alasql",insertfns)}else{throw new Error("Wrong INSERT parameters")}if(db.engineid&&alasql.engines[db.engineid].intoTable&&alasql.options.autocommit){var statement=function(params,cb){var aa=new Function("db,params",s33+"return aa;")(db,params);var res=alasql.engines[db.engineid].intoTable(db.databaseid,tableid,aa,null,cb);return res}}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)}if(cb)cb(res);return res}}return statement};yy.Insert.prototype.execute=function(databaseid,params,cb){return this.compile(databaseid)(params,cb)};yy.Delete=function(params){return yy.extend(this,params)};yy.Delete.prototype.toString=function(){var s="DELETE FROM "+this.table.toString();if(this.where)s+=" WHERE "+this.where.toString();return s};yy.Delete.prototype.compile=function(databaseid){databaseid=this.table.databaseid||databaseid;var tableid=this.table.tableid;var statement;var db=alasql.databases[databaseid];if(this.where){wherefn=new Function("r,params","return ("+this.where.toJavaScript("r","")+")");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;i0){s+="("+this.args.map(function(arg){return arg.toString()}).join(", ")+")"}if(this.as)s+=" "+K("AS")+" "+L(this.as);return s};yy.CreateDatabase.prototype.execute=function(databaseid,params,cb){var args;if(this.args&&this.args.length>0){args=this.args.map(function(arg){return new Function("params","return "+arg.toJavaScript())(params)})}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}};yy.AttachDatabase=function(params){return yy.extend(this,params)};yy.AttachDatabase.prototype.toString=function(){var s=K("ATTACH");if(this.engineid)s+=" "+L(this.engineid);s+=" "+K("DATABASE")+" "+L(this.databaseid);if(args){s+="(";if(args.length>0){s+=args.map(function(arg){return arg.toString()}).join(", ")}s+=")"}if(this.as)s+=" "+K("AS")+" "+L(this.as);return s};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};yy.DetachDatabase=function(params){return yy.extend(this,params)};yy.DetachDatabase.prototype.toString=function(){var s=K("DETACH");s+=" "+K("DATABASE")+" "+L(this.databaseid);return s};yy.DetachDatabase.prototype.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};yy.UseDatabase=function(params){return yy.extend(this,params)};yy.UseDatabase.prototype.toString=function(){return K("USE")+" "+K("DATABASE")+" "+L(this.databaseid)};yy.UseDatabase.prototype.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};yy.DropDatabase=function(params){return yy.extend(this,params)};yy.DropDatabase.prototype.toString=function(){var s=K("DROP");if(this.ifexists)s+=" "+K("IF")+" "+K("EXISTS");s+=" "+K("DATABASE")+" "+L(this.databaseid);return s};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]){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};yy.Declare=function(params){return yy.extend(this,params)};yy.Declare.prototype.toString=function(){var s=K("DECLARE")+" ";if(this.declares&&this.declares.length>0){s=this.declares.map(function(declare){var s="";s+="@"+L(declare.variable)+" ";s+=declare.dbtypeid;if(this.dbsize)s+="("+N(this.dbsize);if(this.dbprecision)s+=","+N(this.dbprecision);s+=")";if(declare.expression)s+=" = "+declare.expression.toString();return s}).join(",")}return s};yy.Declare.prototype.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};if(declare.expression){alasql.vars[declare.variable]=new Function("params,alasql","return "+declare.expression.toJavaScript("","",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};yy.ShowDatabases=function(params){return yy.extend(this,params)};yy.ShowDatabases.prototype.toString=function(){var s=K("SHOW")+" "+K("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){res=res.filter(function(d){return d.databaseid.match(new RegExp(self.like.value.replace(/\%/g,".*"),"g"))})}if(cb)cb(res);return res}};yy.ShowTables=function(params){return yy.extend(this,params)};yy.ShowTables.prototype.toString=function(){var s=K("SHOW")+" "+K("TABLES");if(this.databaseid)s+=" FROM "+this.databaseid;if(this.like)s+=" "+K("LIKE")+" "+this.like.toString();return s};yy.ShowTables.prototype.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,".*"),"g"))})}if(cb)cb(res);return res};yy.ShowColumns=function(params){return yy.extend(this,params)};yy.ShowColumns.prototype.toString=function(){var s=K("SHOW")+" "+K("COLUMNS");if(this.table.tableid)s+=" "+K("FROM")+" "+this.table.tableid;if(this.databaseid)s+=" "+K("FROM")+" "+this.databaseid;return s};yy.ShowColumns.prototype.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[]}};yy.ShowIndex=function(params){return yy.extend(this,params)};yy.ShowIndex.prototype.toString=function(){var s=K("SHOW")+" "+K("INDEX");if(this.table.tableid)s+=" "+K("FROM")+" "+this.table.tableid;if(this.databaseid)s+=" "+K("FROM")+" "+this.databaseid;return s};yy.ShowIndex.prototype.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};yy.ShowCreateTable=function(params){return yy.extend(this,params)};yy.ShowCreateTable.prototype.toString=function(){var s=K("SHOW")+" "+K("CREATE")+" "+K("TABLE")+" "+L(this.table.tableid);if(this.databaseid)s+=" "+K("FROM")+" "+L(this.databaseid);return s};yy.ShowCreateTable.prototype.execute=function(databaseid){var db=alasql.databases[this.databaseid||databaseid];var table=db.tables[this.table.tableid];var self=this;if(table){var s=K("CREATE")+" "+K("TABLE")+" "+L(this.table.tableid)+" (";var ss=[];if(table.columns){table.columns.forEach(function(col){var a=L(col.columnid)+" "+K(col.dbtypeid);if(col.dbsize)a+="("+N(col.dbsize)+")";if(col.primarykey)a+=" "+K("PRIMARY")+" "+K("KEY");ss.push(a)});s+=ss.join(", ")}s+=")";return s}else{throw new Error('There is no such table "'+this.table.tableid+'"')}};yy.SetVariable=function(params){return yy.extend(this,params)};yy.SetVariable.prototype.toString=function(){var s=K("SET")+" ";if(typeof this.value!="undefined")s+=K(this.variable.toUpperCase())+" "+(this.value?"ON":"OFF");if(this.expression)s+="@"+L(this.variable)+" = "+this.expression.toString();return s};yy.SetVariable.prototype.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){var res=new Function("params,alasql","return "+this.expression.toJavaScript("","",null))(params,alasql);if(alasql.declares[this.variable]){res=alasql.stdfn.CONVERT(res,alasql.declares[this.variable])}if(this.props&&this.props.length>0){var fs="alasql.vars['"+this.variable+"']";fs+=this.props.map(function(prop){if(typeof prop=="string"){return"['"+prop+"']"}else if(typeof prop=="number"){return"["+prop+"]"}else{return"["+prop.toJavaScript()+"]"}}).join();new Function("value,alasql",fs+"=value")(res,alasql)}else{alasql.vars[this.variable]=res}}var res=1;if(cb)res=cb(res);return res};alasql.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",sql);if(res instanceof Array){if(console.table){console.table(res)}else{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{el=target}}var s="";if(typeof sql=="string"&&alasql.options.logprompt){s+="

"+alasql.pretty(sql)+"
"}if(res instanceof Array){if(res.length==0){s+="

[ ]

"}else if(typeof res[0]!="object"||res[0]instanceof Array){for(var i=0,ilen=res.length;i"+loghtml(res[i])+"

"}}else{s+=loghtml(res)}}else{s+=loghtml(res)}el.innerHTML+=s}};alasql.clear=function(){var target=alasql.options.logtarget;if(typeof exports=="object"){target="console"}if(target=="console"||typeof exports=="object"){if(console.clear){console.clear()}else{}}else{var el;if(target=="output"){el=document.getElementsByTagName("output")[0]}else{if(typeof target=="string"){el=document.getElementById(target)}else{el=target}}el.innerHTML=""}};alasql.write=function(s){var target=alasql.options.logtarget;if(typeof exports=="object"){target="console"}if(target=="console"||typeof exports=="object"){if(console.log){console.log(s)}else{}}else{var el;if(target=="output"){el=document.getElementsByTagName("output")[0]}else{if(typeof target=="string"){el=document.getElementById(target)}else{el=target}}el.innerHTML+=s}};function loghtml(res){var s="";if(typeof res=="undefined"){s+="undefined"}else if(res instanceof Array){s+="";s+="";var cols=[];for(colid in res[0]){cols.push(colid)}s+="
#";cols.forEach(function(colid){s+=""+colid});for(var i=0,ilen=res.length;i"+(i+1);cols.forEach(function(colid){s+=" ";if(+res[i][colid]==+res[i][colid]){s+='
';if(typeof res[i][colid]=="undefined")s+="NULL";else s+=res[i][colid];s+="
"}else{if(typeof res[i][colid]=="undefined"){s+="NULL"}else if(typeof res[i][colid]=="string"){s+=res[i][colid]}else s+=JSONtoString(res[i][colid])}})}s+="
"}else{s+="

"+JSONtoString(res)+"

"}return s}function scrollTo(element,to,duration){if(duration<=0)return;var difference=to-element.scrollTop;var perTick=difference/duration*10;setTimeout(function(){if(element.scrollTop==to)return;element.scrollTop=element.scrollTop+perTick;scrollTo(element,to,duration-10)},10)}alasql.prompt=function(el,useidel,firstsql){if(typeof exports=="object"){throw new Error("The functionality of prompt is 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('

'+(Date.now()-tm)+" ms

")}catch(err){alasql.write("

"+olduseid+"> "+sql+"

");alasql.write('

'+err+"

")}}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('

'+(Date.now()-tm)+" ms

")}catch(err){alasql.write("

"+olduseid+"> "+alasql.pretty(sql,false)+"

");alasql.write('

'+err+"

")}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()}}}};yy.BeginTransaction=function(params){return yy.extend(this,params)};yy.BeginTransaction.prototype.toString=function(){return K("BEGIN")+" "+K("TRANSACTION")};yy.BeginTransaction.prototype.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{}if(cb)cb(res);return res};yy.CommitTransaction=function(params){return yy.extend(this,params)};yy.CommitTransaction.prototype.toString=function(){return K("COMMIT")+" "+K("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{}if(cb)cb(res);return res};yy.RollbackTransaction=function(params){return yy.extend(this,params)};yy.RollbackTransaction.prototype.toString=function(){return K("ROLLBACK")+" "+K("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{}if(cb)cb(res);return res};alasql.into.SQL=function(filename,opts,data,columns,cb){var res;if(typeof filename=="object"){opts=filename;filename=""}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{}}for(var i=0,ilen=data.length;i0){columns=Object.keys(data[0]).map(function(columnid){return{columnid:columnid}})}if(typeof filename=="object"){opts=filename;filename=null}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")}alasql.utils.saveFile(filename,s);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=" ";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"){opts=filename;filename=null}var opt={};opt.separator=",";opt.quote='"';alasql.utils.extend(opt,opts);var res=data.length;var s="";if(opt.headers){s+=columns.map(function(col){return col.columnid}).join(opt.separator)+"\n"}data.forEach(function(d,idx){s+=columns.map(function(col){var s=d[col.columnid];s=(s+"").replace(new RegExp("\\"+opt.quote,"g"),'""');if((s+"").indexOf(opt.separator)>-1||(s+"").indexOf(opt.quote)>-1)s=opt.quote+s+opt.quote;return s}).join(opt.separator)+"\n"});if(filename){alasql.utils.saveFile(filename,s)}else{console.log(s)}if(cb)res=cb(res);return res};alasql.into.XLSX=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 exports=="object"){var XLSX=require("xlsx")}else{var XLSX=window.XLSX}var opt={sheetid:"Sheet1",headers:true};alasql.utils.extend(opt,opts);var res=data.length;var wb={SheetNames:[],Sheets:{}};if(opt.sourcefilename){alasql.utils.loadBinaryFile(opt.sourcefilename,!!cb,function(data){wb=XLSX.read(data,{type:"binary"});doExport()})}else{doExport()}function doExport(){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+data.length+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}});i++}for(var j=0;j=N)return EOF;if(eol)return eol=false,EOL;var j=I;if(text.charCodeAt(j)===quoteCode){var i=j;while(i++http://github/agershun/alasq for more information'}];yy.Help.prototype.execute=function(databaseid,params,cb){var ss=[];if(!this.subject){ss=helpdocs}else{ss.push('See also http://github/agershun/alasq for more information')}if(cb)ss=cb(ss);return ss};yy.Print=function(params){return yy.extend(this,params)};yy.Print.prototype.toString=function(){var s=K("PRINT");if(this.statement)s+=" "+this.statement.toString();return s};yy.Print.prototype.execute=function(databaseid,params,cb){var res,s;if(this.statement){s=this.statement.execute(databaseid,params)}else{s=""}s=JSONtoString(s);console.log(s);if(cb)res=cb(res);return res};yy.Source=function(params){return yy.extend(this,params)};yy.Source.prototype.toString=function(){var s=K("SOURCE");if(this.url)s+=" "+S("'"+this.url+"'");return s};yy.Source.prototype.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};yy.Require=function(params){return yy.extend(this,params)};yy.Require.prototype.toString=function(){var s=K("REQUIRE");if(this.paths&&this.paths.length>0){s+=this.paths.map(function(path){return path.toString()}).join(",")}return s};yy.Require.prototype.execute=function(databaseid,params,cb){var self=this;var res=0;var ss="";if(this.paths.length>0){this.paths.forEach(function(path){loadFile(path.value,!!cb,function(data){res++;ss+=data;if(res0){res=res.filter(function(d){return d.databaseid.match(relike)})}}if(cb)cb(res);return res};LS.createTable=function(databaseid,tableid,ifnotexists,cb){var lsdbid=alasql.databases[databaseid].lsdbid;var tb=LS.get(lsdbid+"."+tableid);var res=1;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];lsdb.tables[tableid]={columns:table.columns};LS.set(lsdbid,lsdb);LS.set(lsdbid+"."+tableid,[]);if(cb)cb(res);return res};LS.dropTable=function(databaseid,tableid,ifexists,cb){var res=1;var lsdbid=alasql.databases[databaseid].lsdbid;var lsdb=LS.get(lsdbid);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);if(cb)cb(res);return res};LS.fromTable=function(databaseid,tableid,cb,idx,query){var lsdbid=alasql.databases[databaseid].lsdbid;var res=LS.get(lsdbid+"."+tableid);if(cb)res=cb(res,idx,query);return res};LS.intoTable=function(databaseid,tableid,value,columns,cb){var lsdbid=alasql.databases[databaseid].lsdbid;var res=value.length;var tb=LS.get(lsdbid+"."+tableid);if(!tb)tb=[];tb=tb.concat(value);LS.set(lsdbid+"."+tableid,tb);if(cb)cb(res);return res};LS.loadTableData=function(databaseid,tableid){var db=alasql.databases[databaseid];var lsdbid=alasql.databases[databaseid].lsdbid;db.tables[tableid].data=LS.get(lsdbid+"."+tableid)};LS.saveTableData=function(databaseid,tableid){var db=alasql.databases[databaseid];var lsdbid=alasql.databases[databaseid].lsdbid;LS.set(lsdbid+"."+tableid,db.tables[tableid].data);db.tables[tableid].data=null};LS.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){lsdb.tables[tbid]={columns:db.tables[tbid].columns};LS.set(lsdbid+"."+tbid,db.tables[tbid].data)}}LS.set(lsdbid,lsdb);return 1};LS.begin=LS.commit;LS.rollback=function(databaseid,cb){var db=alasql.databases[databaseid];db.dbversion++;var lsdbid=alasql.databases[databaseid].lsdbid;var lsdb=LS.get(lsdbid);if(lsdb.tables){for(var tbid in lsdb.tables){var tb=new alasql.Table({columns:db.tables[tbid].columns});extend(tb,lsdb.tables[tbid]);lsdb.tables[tbid]=tb;if(!alasql.options.autocommit){lsdb.tables[tbid].data=LS.get(db.lsdbid+"."+tbid)}lsdb.tables[tbid].indexColumns()}}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"};var SQLITE=alasql.engines.SQLITE=function(){};SQLITE.createDatabase=function(wdbid,args,ifnotexists,dbid,cb){throw new Error("Connot create SQLITE database in memory. Attach it.")};SQLITE.dropDatabase=function(databaseid){throw new Error("This is impossible to drop SQLite database. Detach it.")};SQLITE.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};SQLITE.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)};SQLITE.intoTable=function(databaseid,tableid,value,columns,cb){var sqldb=alasql.databases[databaseid].sqldb;for(var i=0,ilen=value.length;i1){var sql="REQUIRE "+paths.map(function(p){return'"'+p+'"'}).join(",");alasql(sql,[],cb)}}else if(path===false){delete alasql.webworker;return}}} \ No newline at end of file +}};var Database=alasql.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{self=alasql.databases.alasql}}if(!databaseid){databaseid="db"+alasql.databasenum++}self.databaseid=databaseid;alasql.databases[databaseid]=self;self.tables={};self.views={};self.indices={};self.resetSqlCache();self.dbversion=0;return self};Database.prototype.resetSqlCache=function(){this.sqlCache={};this.sqlCacheSize=0};Database.prototype.exec=function(sql,params,cb){return alasql.dexec(this.databaseid,sql,params,cb)};Database.prototype.transaction=function(cb){var tx=new alasql.Transaction(this.databaseid);var res=cb(tx);return res};var Transaction=alasql.Transaction=function(databaseid){this.transactionid=Date.now();this.databaseid=databaseid;this.commited=false;this.dbversion=alasql.databases[databaseid].dbversion;this.bank=JSON.stringify(alasql.databases[databaseid]);return this};Transaction.prototype.commit=function(){this.commited=true;alasql.databases[this.databaseid].dbversion=Date.now();delete this.bank};Transaction.prototype.rollback=function(){if(!this.commited){alasql.databases[this.databaseid]=JSON.parse(this.bank);delete this.bank}else{throw new Error("Transaction already commited")}};Transaction.prototype.exec=function(sql,params,cb){return alasql.dexec(this.databaseid,sql,params,cb)};Transaction.prototype.executeSQL=Transaction.prototype.exec;var Table=alasql.Table=function(params){this.columns=[];this.xcolumns={};this.data=[];this.inddefs={};this.indices={};this.uniqs={};this.uniqdefs={};extend(this,params)};Table.prototype.indexColumns=function(){var self=this;self.xcolumns={};self.columns.forEach(function(col){self.xcolumns[col.columnid]=col})};var View=alasql.View=function(params){this.columns=[];this.xcolumns={};this.query=[];extend(this,params)};var Query=alasql.Query=function(params){this.alasql=alasql;this.columns=[];this.xcolumns={};this.selectGroup=[];this.groupColumns={};extend(this,params)};var Recordset=alasql.Recordset=function(params){extend(this,params)};var yy=parser.yy={};yy.extend=extend;yy.casesensitive=alasql.options.casesensitive;var Base=yy.Base=function(params){return yy.extend(this,params)};Base.prototype.toString=function(){};Base.prototype.toType=function(){};Base.prototype.toJavaScript=function(){};Base.prototype.compile=returnUndefined;Base.prototype.exec=function(){};Base.prototype.compile=returnUndefined;Base.prototype.exec=function(){};yy.Statements=function(params){return yy.extend(this,params)};yy.Statements.prototype.toString=function(){return this.statements.map(function(st){return st.toString()}).join(";"+NL())};yy.Statements.prototype.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}}};function queryfn(query,oldscope,cb,A,B){var ms;query.sourceslen=query.sources.length;var slen=query.sourceslen;query.query=query;query.A=A;query.B=B;query.cb=cb;query.oldscope=oldscope;if(query.queriesfn){query.sourceslen+=query.queriesfn.length;slen+=query.queriesfn.length;query.queriesdata=[];query.queriesfn.forEach(function(q,idx){q.query.params=query.params;if(false){queryfn(q.query,query.oldscope,queryfn2,-idx-1,query)}else{queryfn2([],-idx-1,query)}})}var scope;if(!oldscope)scope={};else scope=cloneDeep(oldscope);query.scope=scope;var result;query.sources.forEach(function(source,idx){source.query=query;var rs=source.datafn(query,query.params,queryfn2,idx,alasql);if(typeof rs!=undefined){if((query.intofn||query.intoallfn)&&rs instanceof Array)rs=rs.length;result=rs}source.queriesdata=query.queriesdata});if(slen==0)result=queryfn3(query);return result}function queryfn2(data,idx,query){if(idx>=0){var source=query.sources[idx];source.data=data;if(typeof source.data=="function"){source.getfn=source.data;source.dontcache=source.getfn.dontcache;if(source.joinmode=="OUTER"||source.joinmode=="RIGHT"||source.joinmode=="ANTI"){source.dontcache=false}source.data={}}}else{query.queriesdata[-idx-1]=flatArray(data)}query.sourceslen--;if(query.sourceslen>0)return;return queryfn3(query)}function queryfn3(query){var scope=query.scope;preIndex(query);query.data=[];query.xgroups={};query.groups=[];var h=0;doJoin(query,scope,h);if(query.groupfn){query.data=[];if(query.groups.length==0){var g={};if(query.selectGroup.length>0){query.selectGroup.forEach(function(sg){if(sg.aggregatorid=="COUNT"||sg.aggregatorid=="SUM"){g[sg.nick]=0}else{g[sg.nick]=undefined}})}query.groups=[g]}for(var i=0,ilen=query.groups.length;i0){for(var i=0,ilen=query.data.length;i0&&source.optimization=="ix"&&source.onleftfn&&source.onrightfn){if(source.databaseid&&alasql.databases[source.databaseid].tables[source.tableid]){if(!alasql.databases[source.databaseid].tables[source.tableid].indices)query.database.tables[source.tableid].indices={};var ixx=alasql.databases[source.databaseid].tables[source.tableid].indices[hash(source.onrightfns+"`"+source.srcwherefns)];if(!alasql.databases[source.databaseid].tables[source.tableid].dirty&&ixx){source.ix=ixx}}if(!source.ix){source.ix={};var scope={};var i=0;var ilen=source.data.length;var dataw;while((dataw=source.data[i])||source.getfn&&(dataw=source.getfn(i))||i=query.sources.length){if(query.wherefn(scope,query.params,alasql)){if(query.groupfn){query.groupfn(scope,query.params,query.alasql)}else{query.data.push(query.selectfn(scope,query.params,alasql))}}}else if(query.sources[h].applyselect){var source=query.sources[h];source.applyselect(query.params,function(data){if(data.length>0){for(var i=0;i0){s+=NL()+ID()+K("GROUP BY")+" "+this.group.map(function(grp){return grp.toString()}).join(", ")}if(this.having)s+=NL()+ID()+K("HAVING")+" "+this.having.toString();if(this.order&&this.order.length>0){s+=NL()+ID()+K("ORDER BY")+" "+this.order.map(function(ord){return ord.toString()}).join(", ")}if(this.limit)s+=NL()+ID()+K("LIMIT")+" "+this.limit.value;if(this.offset)s+=NL()+ID()+K("OFFSET")+" "+this.offset.value;if(this.union)s+=NL()+K("UNION")+NL()+this.union.toString();if(this.unionall)s+=NL()+K("UNION ALL")+NL()+this.unionall.toString();if(this.except)s+=NL()+K("EXCEPT")+NL()+this.except.toString();if(this.intersect)s+=NL()+K("INTERSECT")+NL()+this.intersect.toString();return s};yy.Select.prototype.toJavaScript=function(context,tableid,defcols){var s="alasql.utils.flatArray(this.queriesfn["+(this.queriesidx-1)+"](this.params,null,"+context+"))[0]";return s};yy.Select.prototype.compile=function(databaseid){var db=alasql.databases[databaseid];var query=new Query;query.removeKeys=[];query.explain=this.explain;query.explaination=[];query.explid=1;query.modifier=this.modifier;query.database=db;this.compileWhereExists(query);this.compileQueries(query);query.defcols=this.compileDefCols(query,databaseid);query.fromfn=this.compileFrom(query);if(this.joins)this.compileJoins(query);this.compileSelectGroup0(query);if(this.group||query.selectGroup.length>0){query.selectgfns=this.compileSelectGroup1(query)}else{query.selectfns=this.compileSelect1(query)}if(this.where)this.compileWhereJoins(query);query.wherefn=this.compileWhere(query);if(this.group||query.selectGroup.length>0)query.groupfn=this.compileGroup(query);if(this.having)query.havingfn=this.compileHaving(query);if(this.group||query.selectGroup.length>0){query.selectgfn=this.compileSelectGroup2(query)}else{query.selectfn=this.compileSelect2(query)}query.distinct=this.distinct;if(this.order)query.orderfn=this.compileOrder(query);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;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}}if(this.into){if(this.into instanceof yy.Table){if(alasql.options.autocommit&&alasql.databases[this.into.databaseid||databaseid].engineid){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{query.intofns="alasql.databases['"+(this.into.databaseid||databaseid)+"'].tables"+"['"+this.into.tableid+"'].data.push(r);"}}else if(this.into instanceof yy.VarValue){query.intoallfns='alasql.vars["'+this.into.variable+'"]=this.data;res=1;if(cb)res=cb(res);return res;'}else if(this.into instanceof yy.FuncValue){var qs="alasql.into['"+this.into.funcid.toUpperCase()+"'](";if(this.into.args&&this.into.args.length>0){qs+=this.into.args[0].toJavaScript()+",";if(this.into.args.length>1){qs+=this.into.args[1].toJavaScript()+","}else{qs+="null,"}}else{qs+="null, null,"}query.intoallfns=qs+"this.data,columns,cb)"}else if(this.into instanceof yy.ParamValue){query.intofns="params['"+this.into.param+"'].push(r)"}if(query.intofns){query.intofn=new Function("r,i,params,alasql",query.intofns)}if(query.intoallfns){query.intoallfn=new Function("columns,cb,alasql",query.intoallfns)}}var statement=function(params,cb,oldscope){query.params=params;var res1=queryfn(query,oldscope,function(res){var res2=modify(query,res);if(cb)cb(res2);return res2});return res1};statement.query=query;return statement};function modify(query,res){if(query.modifier=="VALUE"){if(res.length>0){var key;if(query.columns&&query.columns.length>0)key=query.columns[0].columnid;else key=Object.keys(res[0])[0];res=res[0][key]}else{res=undefined}}if(query.modifier=="ROW"){if(res.length>0){var key;if(query.columns&&query.columns.length>0)key=query.columns[0].columnid;else key=Object.keys(res[0])[0];var a=[];for(var key in res[0]){a.push(res[0][key])}res=a}else{res=undefined}}if(query.modifier=="COLUMN"){var ar=[];if(res.length>0){var key;if(query.columns&&query.columns.length>0)key=query.columns[0].columnid;else key=Object.keys(res[0])[0];for(var i=0,ilen=res.length;i0){key=query.columns[0].columnid;val=query.columns[1].columnid}else{var okeys=Object.keys(res[0]);key=okeys[0];val=okeys[1]}for(var i=0,ilen=res.length;i0)key=query.columns[0].columnid;else key=Object.keys(res[0])[0];var s="";for(var i=0,ilen=res.length;i0){if(tq.args[0]){s+=tq.args[0].toJavaScript("query.oldscope")+","}else{s+="null,"}if(tq.args[1]){s+=tq.args[1].toJavaScript("query.oldscope")+","}else{s+="null,"}}else{s+="null,null,"}s+="cb,idx,query";s+=");/*if(cb)res=cb(res,idx,query);*/return res";source.datafn=new Function("query, params, cb, idx, alasql",s)}else if(tq instanceof yy.FromData){source.datafn=function(query,params,cb,idx,alasql){var res=tq.data;if(cb)res=cb(res,idx,query);return res}}else{throw new Error("Wrong table at FROM")}query.sources.push(source)});query.defaultTableid=query.sources[0].alias};alasql.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;i0){if(jn.args[0]){s+=jn.args[0].toJavaScript("query.oldscope")+","}else{s+="null,"}if(jn.args[1]){s+=jn.args[1].toJavaScript("query.oldscope")+","}else{s+="null,"}}else{s+="null,null,"}s+="cb,idx,query";s+=");/*if(cb)res=cb(res,idx,query);*/return res";source.datafn=new Function("query, params, cb, idx, alasql",s);query.aliases[source.alias]={type:"funcvalue"}}var alias=source.alias;if(jn.natural){if(jn.using||jn.on){throw new Error("NATURAL JOIN cannot have USING or ON clauses")}else{if(query.sources.length>0){var prevSource=query.sources[query.sources.length-1];var prevTable=alasql.databases[prevSource.databaseid].tables[prevSource.tableid];var table=alasql.databases[source.databaseid].tables[source.tableid];if(prevTable&&table){var c1=prevTable.columns.map(function(col){return col.columnid});var c2=table.columns.map(function(col){return col.columnid});jn.using=arrayIntersect(c1,c2).map(function(colid){return{columnid:colid}})}else{throw new Error("In this version of Alasql NATURAL JOIN "+"works for tables with predefined columns only")}}}}if(jn.using){var prevSource=query.sources[query.sources.length-1];source.onleftfns=jn.using.map(function(col){return"p['"+(prevSource.alias||prevSource.tableid)+"']['"+col.columnid+"']"}).join('+"`"+');source.onleftfn=new Function("p,params,alasql","return "+source.onleftfns);source.onrightfns=jn.using.map(function(col){return"p['"+(source.alias||source.tableid)+"']['"+col.columnid+"']"}).join('+"`"+');source.onrightfn=new Function("p,params,alasql","return "+source.onrightfns);source.optimization="ix"}else if(jn.on){if(jn.on instanceof yy.Op&&jn.on.op=="="&&!jn.on.allsome){source.optimization="ix";var lefts="";var rights="";var middles="";var middlef=false;var ls=jn.on.left.toJavaScript("p",query.defaultTableid,query.defcols);var rs=jn.on.right.toJavaScript("p",query.defaultTableid,query.defcols);if(ls.indexOf("p['"+alias+"']")>-1&&!(rs.indexOf("p['"+alias+"']")>-1)){if((ls.match(/p\[\'.*?\'\]/g)||[]).every(function(s){return s=="p['"+alias+"']"})){rights=ls}else{middlef=true}}else if(!(ls.indexOf("p['"+alias+"']")>-1)&&rs.indexOf("p['"+alias+"']")>-1){if((rs.match(/p\[\'.*?\'\]/g)||[]).every(function(s){return s=="p['"+alias+"']"})){lefts=ls}else{middlef=true}}else{middlef=true}if(rs.indexOf("p['"+alias+"']")>-1&&!(ls.indexOf("p['"+alias+"']")>-1)){if((rs.match(/p\[\'.*?\'\]/g)||[]).every(function(s){return s=="p['"+alias+"']"})){rights=rs}else{middlef=true}}else if(!(rs.indexOf("p['"+alias+"']")>-1)&&ls.indexOf("p['"+alias+"']")>-1){if((ls.match(/p\[\'.*?\'\]/g)||[]).every(function(s){return s=="p['"+alias+"']"})){lefts=rs}else{middlef=true}}else{middlef=true}if(middlef){rights="";lefts="";middles=jn.on.toJavaScript("p",query.defaultTableid,query.defcols);source.optimization="no"}source.onleftfns=lefts;source.onrightfns=rights;source.onmiddlefns=middles||"true";source.onleftfn=new Function("p,params,alasql","return "+source.onleftfns);source.onrightfn=new Function("p,params,alasql","return "+source.onrightfns);source.onmiddlefn=new Function("p,params,alasql","return "+source.onmiddlefns)}else{source.optimization="no";source.onmiddlefns=jn.on.toJavaScript("p",query.defaultTableid,query.defcols);source.onmiddlefn=new Function("p,params,alasql","return "+jn.on.toJavaScript("p",query.defaultTableid,query.defcols))}}query.sources.push(source)}})};yy.Select.prototype.compileWhere=function(query){if(this.where){if(typeof this.where=="function"){return this.where}else{s=this.where.toJavaScript("p",query.defaultTableid,query.defcols);query.wherefns=s;return new Function("p,params,alasql","return "+s)}}else return function(){return true}};yy.Select.prototype.compileWhereJoins=function(query){return;optimizeWhereJoin(query,this.where.expression);query.sources.forEach(function(source){if(source.srcwherefns){source.srcwherefn=new Function("p,params,alasql","return "+source.srcwherefns)}if(source.wxleftfns){source.wxleftfn=new Function("p,params,alasql","return "+source.wxleftfns)}if(source.wxrightfns){source.wxrightfn=new Function("p,params,alasql","return "+source.wxrightfns)}})};function optimizeWhereJoin(query,ast){if(!ast)return false;if(!(ast instanceof yy.Op))return;if(ast.op!="="&&ast.op!="AND")return;if(ast.allsome)return;var s=ast.toJavaScript("p",query.defaultTableid,query.defcols);var fsrc=[];query.sources.forEach(function(source,idx){if(source.tableid){if(s.indexOf("p['"+source.alias+"']")>-1)fsrc.push(source)}});if(fsrc.length==0){return}else if(fsrc.length==1){if(!(s.match(/p\[\'.*?\'\]/g)||[]).every(function(s){return s=="p['"+fsrc[0].alias+"']"})){return}var src=fsrc[0];src.srcwherefns=src.srcwherefns?src.srcwherefns+"&&"+s:s;if(ast instanceof yy.Op&&(ast.op=="="&&!ast.allsome)){if(ast.left instanceof yy.Column){var ls=ast.left.toJavaScript("p",query.defaultTableid,query.defcols);var rs=ast.right.toJavaScript("p",query.defaultTableid,query.defcols);if(rs.indexOf("p['"+fsrc[0].alias+"']")==-1){fsrc[0].wxleftfns=ls;fsrc[0].wxrightfns=rs}}if(ast.right instanceof yy.Column){var ls=ast.left.toJavaScript("p",query.defaultTableid,query.defcols);var rs=ast.right.toJavaScript("p",query.defaultTableid,query.defcols);if(ls.indexOf("p['"+fsrc[0].alias+"']")==-1){fsrc[0].wxleftfns=rs;fsrc[0].wxrightfns=ls}}}ast.reduced=true;return}else{if(ast.op="AND"){optimizeWhereJoin(query,ast.left);optimizeWhereJoin(query,ast.right)}}}yy.Select.prototype.compileGroup=function(query){var self=this;var tableid=query.sources[0].alias; +var defcols=query.defcols;var allgroup=[[]];if(this.group){allgroup=decartes(this.group,query)}var allgroups=[];allgroup.forEach(function(a){allgroups=arrayUnion(allgroups,a)});query.allgroups=allgroups;if(false){allgroups.forEach(function(col2){if(query.selectColumns[colid]){}else{var tmpid="default";if(query.sources.length>0)tmpid=query.sources[0].alias;if(Object.keys(query.selectColumns).length!=0)query.removeKeys.push(colid);query.selectfns+="r['"+escapeq(colid)+"']="+new yy.Column({columnid:colid}).toJavaScript("p",tmpid)+";"}})}var s="";allgroup.forEach(function(agroup){s+="var g=this.xgroups[";var rg=agroup.map(function(col2){var columnid=col2.split(" ")[0];var coljs=col2.split(" ")[1];if(columnid=="")return"1";else 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(" ")[0];var coljs=col2.split(" ")[1];if(columnid=="")return"";else return"'"+columnid+"':"+coljs+","}).join("");var neggroup=arrayDiff(allgroups,agroup);s+=neggroup.map(function(col2){var columnid=col2.split(" ")[0];var coljs=col2.split(" ")[1];return"'"+columnid+"':null,"}).join("");var aft="";s+=query.selectGroup.map(function(col,idx){var colexp=col.expression.toJavaScript("p",tableid,defcols);var colas=col.nick;if(col instanceof yy.AggrValue){if(col.distinct){aft+=",g['$$_VALUES_"+colas+"']={},g['$$_VALUES_"+colas+"']["+colexp+"]=true"}if(col.aggregatorid=="SUM"||col.aggregatorid=="MIN"||col.aggregatorid=="MAX"||col.aggregatorid=="FIRST"||col.aggregatorid=="LAST"){return"'"+colas+"':"+colexp+","}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+",'_COUNT_"+colas+"':1,"}else if(col.aggregatorid=="AGGR"){aft+=",g['"+colas+"']="+col.expression.toJavaScript("g",-1);return""}else if(col.aggregatorid=="REDUCE"){return"'"+colas+"':alasql.aggr['"+col.funcid+"']("+colexp+"),"}return""}else return""}).join("");s+="}"+aft+",g));} else {";s+=query.selectGroup.map(function(col,idx){var colas=col.nick;var colexp=col.expression.toJavaScript("p",tableid,defcols);if(col instanceof yy.AggrValue){if(col.distinct){var pre="if(typeof "+colexp+'!="undefined" && (!g[\'$$_VALUES_'+colas+"']["+colexp+"])) {";var post="g['$$_VALUES_"+colas+"']["+colexp+"]=true;}"}else{var pre="",post=""}if(col.aggregatorid=="SUM"){return pre+"g['"+colas+"']+="+colexp+";"+post}else if(col.aggregatorid=="COUNT"){if(col.expression.columnid=="*")return pre+"g['"+colas+"']++;"+post;else{return pre+"if(typeof "+colexp+'!="undefined") g[\''+colas+"']++;"+post}}else if(col.aggregatorid=="ARRAY"){return pre+"g['"+colas+"'].push("+colexp+");"+post}else if(col.aggregatorid=="MIN"){return pre+"g['"+colas+"']=Math.min(g['"+colas+"'],"+colexp+");"+post}else if(col.aggregatorid=="MAX"){return pre+"g['"+colas+"']=Math.max(g['"+colas+"'],"+colexp+");"+post}else if(col.aggregatorid=="FIRST"){return""}else if(col.aggregatorid=="LAST"){return pre+"g['"+colas+"']="+colexp+";"+post}else if(col.aggregatorid=="AVG"){return pre+"g['_SUM_"+colas+"']+="+colexp+";"+"g['_COUNT_"+colas+"']++;"+"g['"+colas+"']=g['_SUM_"+colas+"']/g['_COUNT_"+colas+"'];"+post}else if(col.aggregatorid=="AGGR"){return pre+"g['"+colas+"']="+col.expression.toJavaScript("g",-1)+";"+post}else if(col.aggregatorid=="REDUCE"){return pre+"g['"+colas+"']=alasql.aggr."+col.funcid+"("+colexp+",g['"+colas+"']);"+post}return""}else return""}).join("");s+="}"});return new Function("p,params,alasql",s)};function compileSelectStar(query,alias){var s="",sp="",ss=[];if(query.aliases[alias].tableid){var columns=alasql.databases[query.aliases[alias].databaseid].tables[query.aliases[alias].tableid].columns}if(columns&&columns.length>0){columns.forEach(function(tcol){ss.push("'"+tcol.columnid+"':p['"+alias+"']['"+tcol.columnid+"']");query.selectColumns[escapeq(tcol.columnid)]=true;var coldef={columnid:tcol.columnid,dbtypeid:tcol.dbtypeid,dbsize:tcol.dbsize,dbprecision:tcol.dbprecision,dbenum:tcol.dbenum};query.columns.push(coldef);query.xcolumns[coldef.columnid]=coldef})}else{sp+='var w=p["'+alias+'"];for(var k in w){r[k]=w[k]};';query.dirtyColumns=true}return{s:ss.join(","),sp:sp}}yy.Select.prototype.compileSelect1=function(query){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){var ret=compileSelectStar(query,col.tableid);if(ret.s)ss=ss.concat(ret.s);sp+=ret.sp}else{for(var alias in query.aliases){var ret=compileSelectStar(query,alias);if(ret.s)ss=ss.concat(ret.s);sp+=ret.sp}}}else{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!="_"){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];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{query.dirtyColumns=true}}else{}}}else if(col instanceof yy.AggrValue){if(!self.group){self.group=[""]}if(!col.as)col.as=escapeq(col.toString());if(col.aggregatorid=="SUM"||col.aggregatorid=="MAX"||col.aggregatorid=="MIN"||col.aggregatorid=="FIRST"||col.aggregatorid=="LAST"||col.aggregatorid=="AVG"||col.aggregatorid=="ARRAY"||col.aggregatorid=="REDUCE"){ss.push("'"+escapeq(col.as)+"':"+col.expression.toJavaScript("p",query.defaultTableid,query.defcols))}else if(col.aggregatorid=="COUNT"){ss.push("'"+escapeq(col.as)+"':1")}query.selectColumns[col.aggregatorid+"("+escapeq(col.expression.toString())+")"]=thtd}else{ss.push("'"+escapeq(col.as||col.columnid||col.toString())+"':"+col.toJavaScript("p",query.defaultTableid,query.defcols));query.selectColumns[escapeq(col.as||col.columnid||col.toString())]=true}});s+=ss.join(",")+"};"+sp;return s};yy.Select.prototype.compileSelect2=function(query){var s=query.selectfns;return new Function("p,params,alasql",s+"return r")};yy.Select.prototype.compileSelectGroup0=function(query){var self=this;self.columns.forEach(function(col,idx){if(col instanceof yy.Column&&col.columnid=="*"){}else{var colas;if(col instanceof yy.Column){colas=escapeq(col.columnid)}else{colas=escapeq(col.toString())}for(var i=0;irb)return 1;if(ra==rb)return 0;return-1}}var s="";var sk="";this.order.forEach(function(ord,idx){var dg="";if(ord.expression instanceof yy.NumValue){ord.expression=self.columns[ord.expression.value-1]}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")dg=".valueOf()"}else{if(alasql.options.valueof)dg=".valueOf()"}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()";if(ord.nocase)dg+=".toUpperCase()";s+="if("+ord.toJavaScript("a","")+dg+(ord.direction=="ASC"?">":"<")+ord.toJavaScript("b","")+dg+")return 1;";s+="if("+ord.toJavaScript("a","")+dg+"=="+ord.toJavaScript("b","")+dg+"){"}sk+="}"});s+="return 0;";s+=sk+"return -1";query.orderfns=s;return new Function("a,b",s)}};var rollup=function(a,query){var rr=[];var mask=0;var glen=a.length;for(var g=0;g"){var s=this.left.toString()+"->";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()+" "+P(this.op)+" "+(this.allsome?this.allsome+" ":"")+this.right.toString()};yy.Op.prototype.findAggregator=function(query){if(this.left&&this.left.findAggregator)this.left.findAggregator(query);if(this.right&&this.right.findAggregator&&!this.allsome){this.right.findAggregator(query)}};yy.Op.prototype.toType=function(tableid){if(["-","*","/","%","^"].indexOf(this.op)>-1)return"number";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"].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"};yy.Op.prototype.toJavaScript=function(context,tableid,defcols){var op=this.op;if(this.op=="=")op="===";else if(this.op=="<>")op="!=";else if(this.op=="OR")op="||";if(this.op=="->"){if(typeof this.right=="string"){return this.left.toJavaScript(context,tableid,defcols)+'["'+this.right+'"]'}else if(typeof this.right=="number"){return this.left.toJavaScript(context,tableid,defcols)+"["+this.right+"]"}else if(this.right instanceof yy.FuncValue){ss=[];if(!this.right.args||this.right.args.length==0){}else{var ss=this.right.args.map(function(arg){return arg.toJavaScript(context,tableid,defcols)})}return this.left.toJavaScript(context,tableid,defcols)+"['"+this.right.funcid+"']("+ss.join(",")+")"}else{return this.left.toJavaScript(context,tableid,defcols)+"["+this.right.toJavaScript(context,tableid,defcols)+"]"}}if(this.op=="IS"){return"((typeof "+this.left.toJavaScript(context,tableid,defcols)+"=='undefined') == "+"(typeof "+this.right.toJavaScript(context,tableid,defcols)+"=='undefined'))"}if(this.op=="=="){return"alasql.utils.deepEqual("+this.left.toJavaScript(context,tableid,defcols)+","+this.right.toJavaScript(context,tableid,defcols)+")"}if(this.op=="==="){return"(("+this.left.toJavaScript(context,tableid,defcols)+").valueOf()===("+this.right.toJavaScript(context,tableid,defcols)+".valueOf()))"}if(this.op=="!==="){return"!(("+this.left.toJavaScript(context,tableid,defcols)+").valueOf()===("+this.right.toJavaScript(context,tableid,defcols)+".valueOf()))"}if(this.op=="!=="){return"(!alasql.utils.deepEqual("+this.left.toJavaScript(context,tableid,defcols)+","+this.right.toJavaScript(context,tableid,defcols)+"))"}if(this.op=="LIKE"){var s="("+this.left.toJavaScript(context,tableid,defcols)+"+'')"+".toUpperCase().match(new RegExp('^'+("+this.right.toJavaScript(context,tableid,defcols)+").replace(/\\%/g,'.*').toUpperCase()+'$','g'))";return s}if(this.op=="NOT LIKE"){var s="!(("+this.left.toJavaScript(context,tableid,defcols)+"+'')"+".toUpperCase().match(new RegExp('^'+("+this.right.toJavaScript(context,tableid,defcols)+").replace(/\\%/g,'.*').toUpperCase()+'$','g')))";return s}if(this.op=="BETWEEN"){if(this.right instanceof yy.Op&&this.right.op=="AND"){return"(("+this.right.left.toJavaScript(context,tableid,defcols)+"<="+this.left.toJavaScript(context,tableid,defcols)+")&&"+"("+this.left.toJavaScript(context,tableid,defcols)+"<="+this.right.right.toJavaScript(context,tableid,defcols)+"))"}else{throw new Error("Wrong BETWEEN operator without AND part")}}if(this.op=="NOT BETWEEN"){if(this.right instanceof yy.Op&&this.right.op=="AND"){return"!(("+this.right.left.toJavaScript(context,tableid,defcols)+"<="+this.left.toJavaScript(context,tableid,defcols)+")&&"+"("+this.left.toJavaScript(context,tableid,defcols)+"<="+this.right.right.toJavaScript(context,tableid,defcols)+"))"}else{throw new Error("Wrong NOT BETWEEN operator without AND part")}}if(this.op=="IN"){if(this.right instanceof yy.Select){var s="(";s+="alasql.utils.flatArray(this.query.queriesfn["+this.queriesidx+"](params,null,p))";s+=".indexOf(";s+=this.left.toJavaScript(context,tableid,defcols)+")>-1)";return s}else if(this.right instanceof Array){var s="(["+this.right.map(function(a){return a.toJavaScript(context,tableid,defcols)}).join(",")+"].indexOf(";s+=this.left.toJavaScript(context,tableid,defcols)+")>-1)";return s}else{var s="("+this.right.toJavaScript(context,tableid,defcols)+".indexOf(";s+=this.left.toJavaScript(context,tableid,defcols)+")>-1)";return s}}if(this.op=="NOT IN"){if(this.right instanceof yy.Select){var s="(";s+="alasql.utils.flatArray(this.query.queriesfn["+this.queriesidx+"](params,null,p))";s+=".indexOf(";s+=this.left.toJavaScript(context,tableid,defcols)+")<0)";return s}else if(this.right instanceof Array){var s="(["+this.right.map(function(a){return a.toJavaScript(context,tableid,defcols)}).join(",")+"].indexOf(";s+=this.left.toJavaScript(context,tableid,defcols)+")<0)";return s}else{throw new Error("Wrong NOT IN operator without SELECT part")}}if(this.allsome=="ALL"){if(this.right instanceof yy.Select){var s="alasql.utils.flatArray(this.query.queriesfn["+this.queriesidx+"](params,null,p))";s+=".every(function(b){return (";s+=this.left.toJavaScript(context,tableid,defcols)+")"+op+"b})";return s}else if(this.right instanceof Array){var s="["+this.right.map(function(a){return a.toJavaScript(context,tableid,defcols)}).join(",")+"].every(function(b){return (";s+=this.left.toJavaScript(context,tableid,defcols)+")"+op+"b})";return s}else{throw new Error("Wrong NOT IN operator without SELECT part")}}if(this.allsome=="SOME"||this.allsome=="ANY"){if(this.right instanceof yy.Select){var s="alasql.utils.flatArray(this.query.queriesfn["+this.queriesidx+"](params,null,p))";s+=".some(function(b){return (";s+=this.left.toJavaScript(context,tableid,defcols)+")"+op+"b})";return s}else if(this.right instanceof Array){var s="["+this.right.map(function(a){return a.toJavaScript(context,tableid,defcols)}).join(",")+"].some(function(b){return (";s+=this.left.toJavaScript(context,tableid,defcols)+")"+op+"b})";return s}else{throw new Error("Wrong NOT IN operator without SELECT part")}}if(this.op=="AND"){if(this.left.reduced){if(this.right.reduced){return"true"}else{return this.right.toJavaScript(context,tableid,defcols)}}else if(this.right.reduced){return this.left.toJavaScript(context,tableid,defcols)}op="&&"}if(this.op=="^"){return"Math.pow("+this.left.toJavaScript(context,tableid,defcols)+","+this.right.toJavaScript(context,tableid,defcols)+")"}return"("+this.left.toJavaScript(context,tableid,defcols)+op+this.right.toJavaScript(context,tableid,defcols)+")"};yy.VarValue=function(params){return yy.extend(this,params)};yy.VarValue.prototype.toString=function(){return"@"+L(this.variable)};yy.VarValue.prototype.toType=function(){return"unknown"};yy.VarValue.prototype.toJavaScript=function(){return"alasql.vars['"+this.variable+"']"};yy.NumValue=function(params){return yy.extend(this,params)};yy.NumValue.prototype.toString=function(){return N(this.value.toString())};yy.NumValue.prototype.toType=function(){return"number"};yy.NumValue.prototype.toJavaScript=function(){return""+this.value};yy.StringValue=function(params){return yy.extend(this,params)};yy.StringValue.prototype.toString=function(){return"'"+S(this.value.toString())+"'"};yy.StringValue.prototype.toType=function(){return"string"};yy.StringValue.prototype.toJavaScript=function(){return"'"+escapeq(this.value)+"'"};yy.LogicValue=function(params){return yy.extend(this,params)};yy.LogicValue.prototype.toString=function(){return this.value?"TRUE":"FALSE"};yy.LogicValue.prototype.toType=function(){return"boolean"};yy.LogicValue.prototype.toJavaScript=function(){return this.value?"true":"false"};yy.NullValue=function(params){return yy.extend(this,params)};yy.NullValue.prototype.toString=function(){return"NULL"};yy.NullValue.prototype.toJavaScript=function(){return"undefined"};yy.ParamValue=function(params){return yy.extend(this,params)};yy.ParamValue.prototype.toString=function(){return"$"+this.param};yy.ParamValue.prototype.toJavaScript=function(){if(typeof this.param=="string")return"params['"+this.param+"']";else return"params["+this.param+"]"};yy.UniOp=function(params){return yy.extend(this,params)};yy.UniOp.prototype.toString=function(){if(this.op=="-")return this.op+this.right.toString();if(this.op=="+")return this.op+this.right.toString();if(this.op=="NOT")return this.op+"("+this.right.toString()+")";else if(this.op==null)return"("+this.right.toString()+")"};yy.UniOp.prototype.findAggregator=function(query){if(this.right.findAggregator)this.right.findAggregator(query)};yy.UniOp.prototype.toType=function(tableid){if(this.op=="-")return"number";if(this.op=="+")return"number";if(this.op=="NOT")return"boolean"};yy.UniOp.prototype.toJavaScript=function(context,tableid,defcols){if(this.op=="-")return"(-("+this.right.toJavaScript(context,tableid,defcols)+"))";if(this.op=="+")return"("+this.right.toJavaScript(context,tableid,defcols)+")";if(this.op=="NOT")return"!("+this.right.toJavaScript(context,tableid,defcols)+")";else if(this.op==null)return"("+this.right.toJavaScript(context,tableid,defcols)+")"};yy.Column=function(params){return yy.extend(this,params)};yy.Column.prototype.toString=function(){var s;if(this.columnid==+this.columnid){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}}return s};yy.Column.prototype.toJavaScript=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"){s="g['"+this.nick+"']"}else if(this.tableid){if(this.columnid!="_"){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!="_"){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)+"']"}}}return s};yy.AggrValue=function(params){return yy.extend(this,params)};yy.AggrValue.prototype.toString=function(){var s="";if(this.aggregatorid=="REDUCE")s+=L(this.funcid)+"(";else s+=this.aggregatorid+"(";if(this.distinct)s+=K("DISTINCT")+" ";if(this.expression)s+=this.expression.toString();s+=")";if(this.over)s+=" "+this.over.toString();return s};yy.AggrValue.prototype.findAggregator=function(query){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-1)return"number";if(["ARRAY"].indexOf(this.aggregatorid)>-1)return"array";if(["FIRST","LAST"].indexOf(this.aggregatorid)>-1)return this.expression.toType()};yy.AggrValue.prototype.toJavaScript=function(context,tableid,defcols){var colas=this.nick;if(typeof colas=="undefined")colas=this.toString();return"g['"+colas+"']"};yy.OrderExpression=function(params){return yy.extend(this,params)};yy.OrderExpression.prototype.toString=function(){var s=this.expression.toString();if(this.order)s+=" "+this.order.toString();if(this.nocase)s+=" "+K("COLLATE")+" "+K("NOCASE");return s};yy.GroupExpression=function(params){return yy.extend(this,params)};yy.GroupExpression.prototype.toString=function(){return this.type+"("+this.group.toString()+")"};yy.ColumnDef=function(params){return yy.extend(this,params)};yy.ColumnDef.prototype.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};yy.FromData=function(params){return yy.extend(this,params)};yy.FromData.prototype.toString=function(){if(this.data)return K("DATA")+"("+(Math.random()*1e16|0)+")";else return"?"};yy.FromData.prototype.toJavaScript=function(){};yy.Select.prototype.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;if(db.sqlCacheSize>alasql.MAXSQLCACHESIZE){db.resetSqlCache()}db.sqlCacheSize++;db.sqlCache[hh]=statement;var res=alasql.res=statement(params,cb);return res};yy.Select.prototype.Select=function(){var self=this;var agrs=[];if(arguments.length>1){args=Array.prototype.slice.call(arguments)}else if(arguments.length==1){if(arguments[0]instanceof Array){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{}});return self};yy.Select.prototype.From=function(tableid){var self=this;if(!self.from)self.from=[];if(tableid instanceof Array){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};yy.Select.prototype.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(arguments[0]instanceof Array){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};yy.Select.prototype.Top=function(topnum){var self=this;self.top=new yy.NumValue({value:topnum});return self};yy.Select.prototype.GroupBy=function(){var self=this;var agrs=[]; +if(arguments.length>1){args=Array.prototype.slice.call(arguments)}else if(arguments.length==1){if(arguments[0]instanceof Array){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};yy.Select.prototype.Where=function(expr){var self=this;if(typeof expr=="function"){self.where=expr}return self};yy.FuncValue=function(params){return yy.extend(this,params)};yy.FuncValue.prototype.toString=function(){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)s+=" AS "+this.as.toString();return s};yy.FuncValue.prototype.findAggregator=function(query){if(this.args&&this.args.length>0){this.args.forEach(function(arg){if(arg.findAggregator)arg.findAggregator(query)})}};yy.FuncValue.prototype.toJavaScript=function(context,tableid,defcols){var s="";var funcid=this.funcid;if(alasql.fn[funcid]){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.toJavaScript(context,tableid,defcols)}).join(",")}s+=")"}else if(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.toJavaScript(context,tableid)}))}else{s+=alasql.stdlib[funcid.toUpperCase()]()}}else if(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.toJavaScript(context,tableid,defcols)}).join(",")}s+=")"}else{}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+")"};stdlib.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")}};stdlib.IFNULL=function(a,b){return"("+a+"||"+b+")"};stdlib.INSTR=function(s,p){return"(("+s+").indexOf("+p+")+1)"};stdlib.LEN=stdlib.LENGTH=function(s){return"("+s+'+"").length'};stdlib.LOWER=stdlib.LCASE=function(s){return"("+s+").toLowerCase()"};stdlib.GREATEST=function(){return"Math.max("+Array.prototype.join.call(arguments,",")+")"};stdlib.LEAST=function(){return"Math.min("+Array.prototype.join.call(arguments,",")+")"};stdlib.MID=function(a,b,c){if(arguments.length==2)return"("+a+").substr("+b+"-1)";else if(arguments.length==3)return"("+a+").substr("+b+"-1,"+c+")"};stdlib.NULLIF=function(a,b){return"("+a+"=="+b+"?null:"+a+")"};stdlib.POWER=function(a,b){return"Math.pow("+a+","+b+")"};stdlib.RANDOM=function(r){if(arguments.length==0){return"Math.random()"}else{return"(Math.random()*("+r+")|0)"}};stdlib.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+")"}};stdlib.SQRT=function(s){return"Math.sqrt("+s+")"};stdlib.TRIM=function(s){return s+".trim()"};stdlib.UPPER=stdlib.UCASE=function(s){return"("+s+").toUpperCase()"};alasql.aggr.GROUP_CONCAT=function(v,s){if(typeof s=="undefined")return v;else return s+","+v};yy.CaseValue=function(params){return yy.extend(this,params)};yy.CaseValue.prototype.toString=function(){var s="CASE ";if(this.expression)s+=this.expression.toString();if(this.whens){s+=this.whens.map(function(w){return" WHEN "+w.when.toString()+" THEN "+w.then.toString()}).join()}s+=" END";return s};yy.CaseValue.prototype.findAggregator=function(query){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)})}};yy.CaseValue.prototype.toJavaScript=function(context,tableid,defcols){var s="(function("+context+",params,alasql){var r;";if(this.expression){s+="v="+this.expression.toJavaScript(context,tableid,defcols)+";";s+=(this.whens||[]).map(function(w){return" if(v=="+w.when.toJavaScript(context,tableid,defcols)+") {r="+w.then.toJavaScript(context,tableid,defcols)+"}"}).join(" else ");if(this.elses)s+=" else {r="+this.elses.toJavaScript(context,tableid,defcols)+"}"}else{s+=(this.whens||[]).map(function(w){return" if("+w.when.toJavaScript(context,tableid,defcols)+") {r="+w.then.toJavaScript(context,tableid,defcols)+"}"}).join(" else ");if(this.elses)s+=" else {r="+this.elses.toJavaScript(context,tableid,defcols)+"}"}s+="return r;})("+context+",params,alasql)";return s};yy.Json=function(params){return yy.extend(this,params)};yy.Json.prototype.toString=function(){var s="@";s+=JSONtoString(this.value);s+="";return s};var JSONtoString=alasql.utils.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(obj instanceof Array){s+="["+obj.map(function(b){return JSONtoString(b)}).join(",")+"]"}else if(!obj.toJavaScript||obj instanceof yy.Json){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};function JSONtoJavaScript(obj,context,tableid,defcols){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(obj instanceof Array){s+="["+obj.map(function(b){return JSONtoJavaScript(b,context,tableid,defcols)}).join(",")+"]"}else if(!obj.toJavaScript||obj instanceof yy.Json){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+=":"+JSONtoJavaScript(obj[k],context,tableid,defcols);ss.push(s1)}s+=ss.join(",")+"}"}else if(obj.toJavaScript){s=obj.toJavaScript(context,tableid,defcols)}else{throw new Error("1Can not parse JSON object "+JSON.stringify(obj))}}else{throw new Error("2Can not parse JSON object "+JSON.stringify(obj))}return s}yy.Json.prototype.toJavaScript=function(context,tableid,defcols){return JSONtoJavaScript(this.value,context,tableid,defcols)};yy.Convert=function(params){return yy.extend(this,params)};yy.Convert.prototype.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};yy.Convert.prototype.toJavaScript=function(context,tableid,defcols){return"alasql.stdfn.CONVERT("+this.expression.toJavaScript(context,tableid,defcols)+',{dbtypeid:"'+this.dbtypeid+'",dbsize:'+this.dbsize+",style:"+this.style+"})";throw new Error("There is not such type conversion for "+this.toString())};alasql.stdfn.CONVERT=function(value,args){var val=value;if(args.style){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);if(args.style==1){val=("0"+(t.getMonth()+1)).substr(-2)+"/"+("0"+t.getDate()).substr(-2)+"/"+("0"+t.getYear()).substr(-2)}else if(args.style==2){val=("0"+t.getYear()).substr(-2)+"."+("0"+(t.getMonth()+1)).substr(-2)+"."+("0"+t.getDate()).substr(-2)}else if(args.style==3){val=("0"+t.getDate()).substr(-2)+"/"+("0"+(t.getMonth()+1)).substr(-2)+"/"+("0"+t.getYear()).substr(-2)}else if(args.style==4){val=("0"+t.getDate()).substr(-2)+"."+("0"+(t.getMonth()+1)).substr(-2)+"."+("0"+t.getYear()).substr(-2)}else if(args.style==5){val=("0"+t.getDate()).substr(-2)+"-"+("0"+(t.getMonth()+1)).substr(-2)+"-"+("0"+t.getYear()).substr(-2)}else if(args.style==6){val=("0"+t.getDate()).substr(-2)+" "+t.toString().substr(4,3).toLowerCase()+" "+("0"+t.getYear()).substr(-2)}else if(args.style==7){val=t.toString().substr(4,3)+" "+("0"+t.getDate()).substr(-2)+","+("0"+t.getYear()).substr(-2)}else if(args.style==8){val=("0"+t.getHours()).substr(-2)+":"+("0"+(t.getMinutes()+1)).substr(-2)+":"+("0"+t.getSeconds()).substr(-2)}else if(args.style==10){val=("0"+(t.getMonth()+1)).substr(-2)+"-"+("0"+t.getDate()).substr(-2)+"-"+("0"+t.getYear()).substr(-2)}else if(args.style==11){val=("0"+t.getYear()).substr(-2)+"/"+("0"+(t.getMonth()+1)).substr(-2)+"/"+("0"+t.getDate()).substr(-2)}else if(args.style==12){val=("0"+t.getYear()).substr(-2)+("0"+(t.getMonth()+1)).substr(-2)+("0"+t.getDate()).substr(-2)}else if(args.style==101){val=("0"+(t.getMonth()+1)).substr(-2)+"/"+("0"+t.getDate()).substr(-2)+"/"+t.getFullYear()}else if(args.style==102){val=t.getFullYear()+"."+("0"+(t.getMonth()+1)).substr(-2)+"."+("0"+t.getDate()).substr(-2)}else if(args.style==103){val=("0"+t.getDate()).substr(-2)+"/"+("0"+(t.getMonth()+1)).substr(-2)+"/"+t.getFullYear()}else if(args.style==104){val=("0"+t.getDate()).substr(-2)+"."+("0"+(t.getMonth()+1)).substr(-2)+"."+t.getFullYear()}else if(args.style==105){val=("0"+t.getDate()).substr(-2)+"-"+("0"+(t.getMonth()+1)).substr(-2)+"-"+t.getFullYear()}else if(args.style==106){val=("0"+t.getDate()).substr(-2)+" "+t.toString().substr(4,3).toLowerCase()+" "+t.getFullYear()}else if(args.style==107){val=t.toString().substr(4,3)+" "+("0"+t.getDate()).substr(-2)+","+t.getFullYear()}else if(args.style==108){val=("0"+t.getHours()).substr(-2)+":"+("0"+(t.getMinutes()+1)).substr(-2)+":"+("0"+t.getSeconds()).substr(-2)}else if(args.style==110){val=("0"+(t.getMonth()+1)).substr(-2)+"-"+("0"+t.getDate()).substr(-2)+"-"+t.getFullYear()}else if(args.style==111){val=t.getFullYear()+"/"+("0"+(t.getMonth()+1)).substr(-2)+"/"+("0"+t.getDate()).substr(-2)}else if(args.style==112){val=t.getFullYear()+("0"+(t.getMonth()+1)).substr(-2)+("0"+t.getDate()).substr(-2)}else{throw new Error("The CONVERT style "+args.style+" is not realized yet.")}}if(args.dbtypeid=="Date"){return new Date(val)}else if(args.dbtypeid.toUpperCase()=="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(args.dbtypeid=="DATETIME"){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()).substr(-3);return s}else if(args.dbtypeid.toUpperCase()=="STRING"){return""+val}else if(args.dbtypeid.toUpperCase()=="NUMBER"||args.dbtypeid=="FLOAT"){return+val}else if(args.dbtypeid.toUpperCase()=="MONEY"){var m=+val;return(m|0)+m*100%100/100}else if(args.dbtypeid.toUpperCase()=="BOOLEAN"){return!!val}else if(args.dbtypeid.toUpperCase()=="INT"){return val|0}else if(args.dbtypeid.toUpperCase()=="VARCHAR"||args.dbtypeid=="NVARCHAR"){if(args.dbsize)return(""+val).substr(0,args.dbsize);else return""+val}else if(args.dbtypeid.toUpperCase()=="CHAR"||args.dbtypeid=="NCHAR"){return(val+new Array(args.dbsize+1).join(" ")).substr(0,args.dbsize)}};yy.ColumnDef=function(params){return yy.extend(this,params)};yy.ColumnDef.prototype.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};yy.CreateTable=function(params){return yy.extend(this,params)};yy.CreateTable.prototype.toString=function(){var s=K("CREATE");if(this.temporary)s+=" "+K("TEMPORARY");if(this.view)s+=" "+K("VIEW");else s+=" "+K("TABLE");if(this.ifnotexists)s+=" "+K("IF")+" "+K("NOT")+" "+K("EXISTS");s+=" "+this.table.toString();if(this.viewcolumns){s+="("+this.viewcolumns.map(function(vcol){return vcol.toString()}).join(",")+")"}if(this.as)s+=" "+K("AS")+" "+L(this.as);else{var ss=this.columns.map(function(col){return col.toString()});s+=" ("+NL()+ID()+ss.join(","+NL()+ID())+")"}if(this.view&&this.select){s+=" AS "+this.select.toString()}return s};yy.CreateTable.prototype.execute=function(databaseid,params,cb){var db=alasql.databases[this.table.databaseid||databaseid];var tableid=this.table.tableid;if(!tableid){throw new Error("Table name is not defined")}var columns=this.columns;var constraints=this.constraints||[];if(this.ifnotexists&&db.tables[tableid])return 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;var ss=[];if(this.columns){this.columns.forEach(function(col){var dbtypeid=col.dbtypeid;if(!alasql.fn[dbtypeid])dbtypeid=dbtypeid.toUpperCase();var newcol={columnid:col.columnid,dbtypeid:dbtypeid};if(col.default){ss.push("'"+col.columnid+"':"+col.default.toJavaScript())}table.columns.push(newcol);table.xcolumns[newcol.columnid]=newcol;if(col.primarykey){var pk=table.pk={};pk.columns=[col.columnid];pk.onrightfns="r['"+col.columnid+"']";pk.onrightfn=new Function("r","return "+pk.onrightfns);pk.hh=hash(pk.onrightfns);table.indices[pk.hh]={}}})}table.defaultfns=ss.join(",");constraints.forEach(function(con){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","return "+pk.onrightfns);pk.hh=hash(pk.onrightfns);table.indices[pk.hh]={}}});if(this.view&&this.viewcolumns){var self=this;this.viewcolumns.forEach(function(vcol,idx){self.select.columns[idx].as=vcol.columnid})}if(db.engineid){return alasql.engines[db.engineid].createTable(this.table.databaseid||databaseid,tableid,this.ifnotexists,cb)}table.insert=function(r){if(this.pk){var pk=this.pk;var addr=pk.onrightfn(r);if(typeof this.indices[pk.hh][addr]!="undefined"){throw new Error("Cannot insert record, because it already exists in primary key")}else{table.data.push(r);this.indices[pk.hh][addr]=r}}else{table.data.push(r)}};table.delete=function(i){if(this.pk){var r=this.data[i];var pk=this.pk;var addr=pk.onrightfn(r);if(typeof this.indices[pk.hh][addr]=="undefined"){throw new Error("Something wrong with index on table")}else{this.indices[pk.hh][addr]=undefined}}};table.deleteall=function(){this.data.length=0;if(this.pk){this.indices[this.pk.hh]={}}};table.update=function(assignfn,i,params){if(this.pk){var r=this.data[i];var pk=this.pk;var addr=pk.onrightfn(r,params);if(typeof this.indices[pk.hh][addr]=="undefined"){throw new Error("Something wrong with index on table")}else{this.indices[pk.hh][addr]=undefined;assignfn(r,params,alasql);var newaddr=pk.onrightfn(r);if(typeof this.indices[pk.hh][newaddr]!="undefined"){throw new Error("Record already exists")}else{this.indices[pk.hh][newaddr]=r}}}else{assignfn(this.data[i],params,alasql)}};if(this.view&&this.select){table.view=true;table.select=this.select.compile(this.table.databaseid||databaseid)}if(cb)cb(1);return 1};alasql.fn.Date=Object;alasql.fn.Date=Date;alasql.fn.Number=Number;alasql.fn.String=String;alasql.fn.Boolean=Boolean;stdfn.EXTEND=alasql.utils.extend;stdfn.CHAR=String.fromCharCode.bind(String);stdfn.ASCII=function(a){return a.charCodeAt(0)};stdfn.COALESCE=function(){for(var i=0;i0){for(var i=0,ilen=table.data.length;i0){for(var i=0,ilen=table.data.length;i=0){q+="+"+values[idx].toJavaScript()}else if(alasql.fn[table.xcolumns[col.columnid].dbtypeid]){q+="(new "+table.xcolumns[col.columnid].dbtypeid+"(";q+=values[idx].toJavaScript();q+="))"}else{q+=values[idx].toJavaScript()}}else{q+=values[idx].toJavaScript()}ss.push(q)})}else{if(values instanceof Array&&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].toJavaScript()}else if(alasql.fn[col.dbtypeid]){q+="(new "+col.dbtypeid+"(";q+=values[idx].toJavaScript();q+="))"}else{q+=values[idx].toJavaScript()}ss.push(q)})}else{sw=JSONtoJavaScript(values)}}if(db.tables[tableid].defaultfns)ss.unshift(db.tables[tableid].defaultfns);if(sw){s+="a="+sw+";"}else{s+="a={"+ss.join(",")+"};"}if(db.tables[tableid].insert){s+="alasql.databases['"+databaseid+"'].tables['"+tableid+"'].insert(a);"}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);"}s+="return "+self.values.length;var insertfn=new Function("db, params, alasql",s3+s)}else if(this.select){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,null,cb);return res};return statement}else{var insertfn=function(db,params,alasql){var res=selectfn(params);if(db.tables[tableid].insert){for(var i=0,ilen=res.length;i0){s+="("+this.args.map(function(arg){return arg.toString()}).join(", ")+")"}if(this.as)s+=" "+K("AS")+" "+L(this.as);return s};yy.CreateDatabase.prototype.execute=function(databaseid,params,cb){var args;if(this.args&&this.args.length>0){args=this.args.map(function(arg){return new Function("params","return "+arg.toJavaScript())(params)})}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}};yy.AttachDatabase=function(params){return yy.extend(this,params)};yy.AttachDatabase.prototype.toString=function(){var s=K("ATTACH");if(this.engineid)s+=" "+L(this.engineid);s+=" "+K("DATABASE")+" "+L(this.databaseid);if(args){s+="(";if(args.length>0){s+=args.map(function(arg){return arg.toString()}).join(", ")}s+=")"}if(this.as)s+=" "+K("AS")+" "+L(this.as);return s};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};yy.DetachDatabase=function(params){return yy.extend(this,params)};yy.DetachDatabase.prototype.toString=function(){var s=K("DETACH");s+=" "+K("DATABASE")+" "+L(this.databaseid);return s};yy.DetachDatabase.prototype.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};yy.UseDatabase=function(params){return yy.extend(this,params)};yy.UseDatabase.prototype.toString=function(){return K("USE")+" "+K("DATABASE")+" "+L(this.databaseid)};yy.UseDatabase.prototype.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};yy.DropDatabase=function(params){return yy.extend(this,params)};yy.DropDatabase.prototype.toString=function(){var s=K("DROP");if(this.ifexists)s+=" "+K("IF")+" "+K("EXISTS");s+=" "+K("DATABASE")+" "+L(this.databaseid);return s};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]){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};yy.Declare=function(params){return yy.extend(this,params)};yy.Declare.prototype.toString=function(){var s=K("DECLARE")+" ";if(this.declares&&this.declares.length>0){s=this.declares.map(function(declare){var s="";s+="@"+L(declare.variable)+" ";s+=declare.dbtypeid;if(this.dbsize)s+="("+N(this.dbsize);if(this.dbprecision)s+=","+N(this.dbprecision);s+=")";if(declare.expression)s+=" = "+declare.expression.toString();return s}).join(",")}return s};yy.Declare.prototype.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};if(declare.expression){alasql.vars[declare.variable]=new Function("params,alasql","return "+declare.expression.toJavaScript("","",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};yy.ShowDatabases=function(params){return yy.extend(this,params)};yy.ShowDatabases.prototype.toString=function(){var s=K("SHOW")+" "+K("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){res=res.filter(function(d){return d.databaseid.match(new RegExp(self.like.value.replace(/\%/g,".*"),"g"))})}if(cb)cb(res);return res}};yy.ShowTables=function(params){return yy.extend(this,params)};yy.ShowTables.prototype.toString=function(){var s=K("SHOW")+" "+K("TABLES");if(this.databaseid)s+=" FROM "+this.databaseid;if(this.like)s+=" "+K("LIKE")+" "+this.like.toString();return s};yy.ShowTables.prototype.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,".*"),"g"))})}if(cb)cb(res);return res};yy.ShowColumns=function(params){return yy.extend(this,params)};yy.ShowColumns.prototype.toString=function(){var s=K("SHOW")+" "+K("COLUMNS");if(this.table.tableid)s+=" "+K("FROM")+" "+this.table.tableid;if(this.databaseid)s+=" "+K("FROM")+" "+this.databaseid;return s};yy.ShowColumns.prototype.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[]}};yy.ShowIndex=function(params){return yy.extend(this,params)};yy.ShowIndex.prototype.toString=function(){var s=K("SHOW")+" "+K("INDEX");if(this.table.tableid)s+=" "+K("FROM")+" "+this.table.tableid;if(this.databaseid)s+=" "+K("FROM")+" "+this.databaseid;return s};yy.ShowIndex.prototype.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};yy.ShowCreateTable=function(params){return yy.extend(this,params)};yy.ShowCreateTable.prototype.toString=function(){var s=K("SHOW")+" "+K("CREATE")+" "+K("TABLE")+" "+L(this.table.tableid);if(this.databaseid)s+=" "+K("FROM")+" "+L(this.databaseid);return s};yy.ShowCreateTable.prototype.execute=function(databaseid){var db=alasql.databases[this.databaseid||databaseid];var table=db.tables[this.table.tableid];var self=this;if(table){var s=K("CREATE")+" "+K("TABLE")+" "+L(this.table.tableid)+" (";var ss=[];if(table.columns){table.columns.forEach(function(col){var a=L(col.columnid)+" "+K(col.dbtypeid);if(col.dbsize)a+="("+N(col.dbsize)+")";if(col.primarykey)a+=" "+K("PRIMARY")+" "+K("KEY");ss.push(a)});s+=ss.join(", ")}s+=")";return s}else{throw new Error('There is no such table "'+this.table.tableid+'"')}};yy.SetVariable=function(params){return yy.extend(this,params)};yy.SetVariable.prototype.toString=function(){var s=K("SET")+" ";if(typeof this.value!="undefined")s+=K(this.variable.toUpperCase())+" "+(this.value?"ON":"OFF");if(this.expression)s+="@"+L(this.variable)+" = "+this.expression.toString();return s};yy.SetVariable.prototype.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){var res=new Function("params,alasql","return "+this.expression.toJavaScript("","",null))(params,alasql);if(alasql.declares[this.variable]){res=alasql.stdfn.CONVERT(res,alasql.declares[this.variable])}if(this.props&&this.props.length>0){var fs="alasql.vars['"+this.variable+"']";fs+=this.props.map(function(prop){if(typeof prop=="string"){return"['"+prop+"']"}else if(typeof prop=="number"){return"["+prop+"]"}else{return"["+prop.toJavaScript()+"]"}}).join();new Function("value,alasql",fs+"=value")(res,alasql)}else{alasql.vars[this.variable]=res}}var res=1;if(cb)res=cb(res);return res};alasql.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",sql);if(res instanceof Array){if(console.table){console.table(res)}else{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{el=target}}var s="";if(typeof sql=="string"&&alasql.options.logprompt){s+="

"+alasql.pretty(sql)+"
"}if(res instanceof Array){if(res.length==0){s+="

[ ]

"}else if(typeof res[0]!="object"||res[0]instanceof Array){for(var i=0,ilen=res.length;i"+loghtml(res[i])+"

"}}else{s+=loghtml(res)}}else{s+=loghtml(res)}el.innerHTML+=s}};alasql.clear=function(){var target=alasql.options.logtarget;if(typeof exports=="object"){target="console"}if(target=="console"||typeof exports=="object"){if(console.clear){console.clear()}else{}}else{var el;if(target=="output"){el=document.getElementsByTagName("output")[0]}else{if(typeof target=="string"){el=document.getElementById(target)}else{el=target}}el.innerHTML=""}};alasql.write=function(s){var target=alasql.options.logtarget;if(typeof exports=="object"){target="console"}if(target=="console"||typeof exports=="object"){if(console.log){console.log(s)}else{}}else{var el;if(target=="output"){el=document.getElementsByTagName("output")[0]}else{if(typeof target=="string"){el=document.getElementById(target)}else{el=target}}el.innerHTML+=s}};function loghtml(res){var s="";if(typeof res=="undefined"){s+="undefined"}else if(res instanceof Array){s+="";s+="";var cols=[];for(colid in res[0]){cols.push(colid)}s+="
#";cols.forEach(function(colid){s+=""+colid});for(var i=0,ilen=res.length;i"+(i+1);cols.forEach(function(colid){s+=" ";if(+res[i][colid]==+res[i][colid]){s+='
';if(typeof res[i][colid]=="undefined")s+="NULL";else s+=res[i][colid];s+="
"}else{if(typeof res[i][colid]=="undefined"){s+="NULL"}else if(typeof res[i][colid]=="string"){s+=res[i][colid]}else s+=JSONtoString(res[i][colid])}})}s+="
"}else{s+="

"+JSONtoString(res)+"

"}return s}function scrollTo(element,to,duration){if(duration<=0)return;var difference=to-element.scrollTop;var perTick=difference/duration*10;setTimeout(function(){if(element.scrollTop==to)return;element.scrollTop=element.scrollTop+perTick;scrollTo(element,to,duration-10)},10)}alasql.prompt=function(el,useidel,firstsql){if(typeof exports=="object"){throw new Error("The functionality of prompt is 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('

'+(Date.now()-tm)+" ms

")}catch(err){alasql.write("

"+olduseid+"> "+sql+"

");alasql.write('

'+err+"

")}}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('

'+(Date.now()-tm)+" ms

")}catch(err){alasql.write("

"+olduseid+"> "+alasql.pretty(sql,false)+"

");alasql.write('

'+err+"

")}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()}}}};yy.BeginTransaction=function(params){return yy.extend(this,params)};yy.BeginTransaction.prototype.toString=function(){return K("BEGIN")+" "+K("TRANSACTION")};yy.BeginTransaction.prototype.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{}if(cb)cb(res);return res};yy.CommitTransaction=function(params){return yy.extend(this,params)};yy.CommitTransaction.prototype.toString=function(){return K("COMMIT")+" "+K("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{}if(cb)cb(res);return res};yy.RollbackTransaction=function(params){return yy.extend(this,params)};yy.RollbackTransaction.prototype.toString=function(){return K("ROLLBACK")+" "+K("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{}if(cb)cb(res);return res};alasql.into.SQL=function(filename,opts,data,columns,cb){var res;if(typeof filename=="object"){opts=filename;filename=""}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{}}for(var i=0,ilen=data.length;i0){columns=Object.keys(data[0]).map(function(columnid){return{columnid:columnid}})}if(typeof filename=="object"){opts=filename;filename=null}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")}alasql.utils.saveFile(filename,s);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=" ";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"){opts=filename;filename=null}var opt={};opt.separator=",";opt.quote='"';alasql.utils.extend(opt,opts);var res=data.length;var s="";if(opt.headers){s+=columns.map(function(col){return col.columnid}).join(opt.separator)+"\n"}data.forEach(function(d,idx){s+=columns.map(function(col){var s=d[col.columnid];s=(s+"").replace(new RegExp("\\"+opt.quote,"g"),'""');if((s+"").indexOf(opt.separator)>-1||(s+"").indexOf(opt.quote)>-1)s=opt.quote+s+opt.quote;return s}).join(opt.separator)+"\n"});if(filename){alasql.utils.saveFile(filename,s)}else{console.log(s)}if(cb)res=cb(res);return res};alasql.into.XLSX=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 exports=="object"){var XLSX=require("xlsx")}else{var XLSX=window.XLSX}var opt={sheetid:"Sheet1",headers:true};alasql.utils.extend(opt,opts);var res=data.length;var wb={SheetNames:[],Sheets:{}};if(opt.sourcefilename){alasql.utils.loadBinaryFile(opt.sourcefilename,!!cb,function(data){wb=XLSX.read(data,{type:"binary"});doExport()})}else{doExport()}function doExport(){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+data.length+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}});i++}for(var j=0;j=N)return EOF;if(eol)return eol=false,EOL;var j=I;if(text.charCodeAt(j)===quoteCode){var i=j;while(i++http://github/agershun/alasq for more information'}];yy.Help.prototype.execute=function(databaseid,params,cb){var ss=[];if(!this.subject){ss=helpdocs}else{ss.push('See also http://github/agershun/alasq for more information')}if(cb)ss=cb(ss);return ss};yy.Print=function(params){return yy.extend(this,params)};yy.Print.prototype.toString=function(){var s=K("PRINT");if(this.statement)s+=" "+this.statement.toString();return s};yy.Print.prototype.execute=function(databaseid,params,cb){var res,s;if(this.statement){s=this.statement.execute(databaseid,params)}else{s=""}s=JSONtoString(s);console.log(s);if(cb)res=cb(res);return res};yy.Source=function(params){return yy.extend(this,params)};yy.Source.prototype.toString=function(){var s=K("SOURCE");if(this.url)s+=" "+S("'"+this.url+"'");return s};yy.Source.prototype.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};yy.Require=function(params){return yy.extend(this,params)};yy.Require.prototype.toString=function(){var s=K("REQUIRE");if(this.paths&&this.paths.length>0){s+=this.paths.map(function(path){return path.toString()}).join(",")}return s};yy.Require.prototype.execute=function(databaseid,params,cb){var self=this;var res=0;var ss="";if(this.paths.length>0){this.paths.forEach(function(path){loadFile(path.value,!!cb,function(data){res++;ss+=data;if(res0){res=res.filter(function(d){return d.databaseid.match(relike)})}}if(cb)cb(res);return res};LS.createTable=function(databaseid,tableid,ifnotexists,cb){var lsdbid=alasql.databases[databaseid].lsdbid;var tb=LS.get(lsdbid+"."+tableid);var res=1;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];lsdb.tables[tableid]={columns:table.columns};LS.set(lsdbid,lsdb);LS.set(lsdbid+"."+tableid,[]);if(cb)cb(res);return res};LS.dropTable=function(databaseid,tableid,ifexists,cb){var res=1;var lsdbid=alasql.databases[databaseid].lsdbid;var lsdb=LS.get(lsdbid);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);if(cb)cb(res);return res};LS.fromTable=function(databaseid,tableid,cb,idx,query){var lsdbid=alasql.databases[databaseid].lsdbid;var res=LS.get(lsdbid+"."+tableid);if(cb)res=cb(res,idx,query);return res};LS.intoTable=function(databaseid,tableid,value,columns,cb){var lsdbid=alasql.databases[databaseid].lsdbid;var res=value.length;var tb=LS.get(lsdbid+"."+tableid);if(!tb)tb=[];tb=tb.concat(value);LS.set(lsdbid+"."+tableid,tb);if(cb)cb(res);return res};LS.loadTableData=function(databaseid,tableid){var db=alasql.databases[databaseid];var lsdbid=alasql.databases[databaseid].lsdbid;db.tables[tableid].data=LS.get(lsdbid+"."+tableid)};LS.saveTableData=function(databaseid,tableid){var db=alasql.databases[databaseid];var lsdbid=alasql.databases[databaseid].lsdbid;LS.set(lsdbid+"."+tableid,db.tables[tableid].data);db.tables[tableid].data=null};LS.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){lsdb.tables[tbid]={columns:db.tables[tbid].columns};LS.set(lsdbid+"."+tbid,db.tables[tbid].data)}}LS.set(lsdbid,lsdb);return 1};LS.begin=LS.commit;LS.rollback=function(databaseid,cb){var db=alasql.databases[databaseid];db.dbversion++;var lsdbid=alasql.databases[databaseid].lsdbid;var lsdb=LS.get(lsdbid);if(lsdb.tables){for(var tbid in lsdb.tables){var tb=new alasql.Table({columns:db.tables[tbid].columns});extend(tb,lsdb.tables[tbid]);lsdb.tables[tbid]=tb;if(!alasql.options.autocommit){lsdb.tables[tbid].data=LS.get(db.lsdbid+"."+tbid)}lsdb.tables[tbid].indexColumns()}}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"};var SQLITE=alasql.engines.SQLITE=function(){};SQLITE.createDatabase=function(wdbid,args,ifnotexists,dbid,cb){throw new Error("Connot create SQLITE database in memory. Attach it.")};SQLITE.dropDatabase=function(databaseid){throw new Error("This is impossible to drop SQLite database. Detach it.")};SQLITE.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};SQLITE.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)};SQLITE.intoTable=function(databaseid,tableid,value,columns,cb){var sqldb=alasql.databases[databaseid].sqldb;for(var i=0,ilen=value.length;i1){var sql="REQUIRE "+paths.map(function(p){return'"'+p+'"'}).join(",");alasql(sql,[],cb)}}else if(path===false){delete alasql.webworker;return}}} \ No newline at end of file diff --git a/package.json b/package.json index 8b1a6aaf5f..a2af45dff5 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "alasql", "description": "Alasql - JavaScript SQL database and data manipulation library", - "version": "0.0.44", + "version": "0.0.45", "author": "Andrey Gershun ", "directories": { "example": "examples", diff --git a/src/05copyright.js b/src/05copyright.js index 7ff5ea996a..75dda8177d 100644 --- a/src/05copyright.js +++ b/src/05copyright.js @@ -2,7 +2,7 @@ // alasql.js // AlaSQL - JavaScript SQL database // Date: 13.04.2015 -// Version: 0.0.44 +// Version: 0.0.45 // (ñ) 2014-2015, Andrey Gershun // diff --git a/src/10start.js b/src/10start.js index 2ca493f5e6..6be3ab0595 100644 --- a/src/10start.js +++ b/src/10start.js @@ -1,82 +1,82 @@ - -/** - UMD envelope - */ - -(function (root, factory) { - if (typeof define === 'function' && define.amd) { - define([], factory); - } else if (typeof exports === 'object') { - module.exports = factory(); - } else { - root.alasql = factory(); - } -}(this, function () { - -/** - alasql - Main Alasql class - @param {string | Object} sql SQL-statement or data object for fuent interface - @param {Object} params SQL parameters - @param {Function} cb callback function - @param {Object} scope Scope for nested queries - @return {array} Result data object - - Standard sync call: - alasql('CREATE TABLE one'); - Query: - var res = alasql('SELECT * FROM one'); - Call with parameters: - var res = alasql('SELECT * FROM ?',[data]); - Standard async call with callback 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) { - if(typeof importScripts != 'function' && alasql.webworker) { - var id = alasql.lastid++; - alasql.buffer[id] = cb; - alasql.webworker.postMessage({id:id,sql:sql,params:params}); - } else { - 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 && typeof sql == "object" && sql instanceof Array) { - // One argument data object - fluent interface - var select = new yy.Select({ - columns:[new yy.Column({columnid:'*'})], - from: [new yy.ParamValue({param:0})] - }); - select.preparams = [sql]; - return select; - } else { - // 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 HTMElement) { - 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); - } - }; -}; - -/** Current version of alasql */ -alasql.version = "0.0.44"; - + +/** + UMD envelope + */ + +(function (root, factory) { + if (typeof define === 'function' && define.amd) { + define([], factory); + } else if (typeof exports === 'object') { + module.exports = factory(); + } else { + root.alasql = factory(); + } +}(this, function () { + +/** + alasql - Main Alasql class + @param {string | Object} sql SQL-statement or data object for fuent interface + @param {Object} params SQL parameters + @param {Function} cb callback function + @param {Object} scope Scope for nested queries + @return {array} Result data object + + Standard sync call: + alasql('CREATE TABLE one'); + Query: + var res = alasql('SELECT * FROM one'); + Call with parameters: + var res = alasql('SELECT * FROM ?',[data]); + Standard async call with callback 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) { + if(typeof importScripts != 'function' && alasql.webworker) { + var id = alasql.lastid++; + alasql.buffer[id] = cb; + alasql.webworker.postMessage({id:id,sql:sql,params:params}); + } else { + 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 && typeof sql == "object" && sql instanceof Array) { + // One argument data object - fluent interface + var select = new yy.Select({ + columns:[new yy.Column({columnid:'*'})], + from: [new yy.ParamValue({param:0})] + }); + select.preparams = [sql]; + return select; + } else { + // 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 HTMElement) { + 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); + } + }; +}; + +/** Current version of alasql */ +alasql.version = "0.0.45"; + diff --git a/src/20database.js b/src/20database.js index 474313cafa..50d5c6a318 100644 --- a/src/20database.js +++ b/src/20database.js @@ -1,149 +1,153 @@ -/* -// -// Database class for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -// Main Database class -/** - @class Database - */ - -var Database = alasql.Database = function (databaseid) { - var self = this; - if(self === alasql) { - if(databaseid) { - self = alasql.databases[databaseid]; - if(!self) { - throw new Error('Database "'+databaseid+'" not found'); - } - } else { - // Create new database (or get alasql?) - self = alasql.databases.alasql; -// self = new Database(databaseid); // to call without new - } - } - if(!databaseid) { - databaseid = "db"+(alasql.databasenum++); // Random name - }; - self.databaseid = databaseid; - alasql.databases[databaseid] = self; - self.tables = {}; - self.views = {}; - - self.indices = {}; -// self.fn = {}; - self.resetSqlCache(); - self.dbversion = 0; - return self; -}; - - -/** - Reset SQL statements cache - */ - -Database.prototype.resetSqlCache = function () { - this.sqlCache = {}; // Cache for compiled SQL statements - this.sqlCacheSize = 0; -} - - -// // Main SQL function - -/** - Run SQL statement on database - @param {string} sql SQL statement - @param [object] params Parameters - @param {function} cb callback - */ - -Database.prototype.exec = function(sql, params, cb) { - return alasql.dexec(this.databaseid, sql, params, cb); -}; - -// // Compile -// var statement = this.compile(sql); -// // Run -// if(statement) { -// var data = statement(params, cb); -// return data; -// } -// return; -// }; - -// // Async version of exec - - -// Database.prototype.aexec = function(sql, params) { -// var self = this; -// return new Promise(function(resolve, reject){ -// alasql.dexec(this.databaseid,sql,params,resolve); -// }); -// }; - - -// Aliases like MS SQL -/* -Database.prototype.query = Database.prototype.exec; -Database.prototype.run = Database.prototype.exec; -Database.prototype.queryArray = function(sql, params, cb) { - return flatArray(this.exec(sql, params, cb)); -} - -Database.prototype.queryArrayOfArrays = function(sql, params, cb) { - return arrayOfArrays(this.exec(sql, params, cb)); -} - -Database.prototype.querySingle = function(sql, params, cb) { - return this.exec(sql, params, cb)[0]; -} -Database.prototype.queryValue = function(sql, params, cb) { - var res = this.querySingle(sql, params, cb); - return res[Object.keys(res)[0]]; -} - -Database.prototype.value = Database.prototype.queryValue; -Database.prototype.row = Database.prototype.querySingle; -Database.prototype.array = Database.prototype.queryArray; -Database.prototype.matrix = Database.prototype.queryArrayOfArrays; - - -// Compile statements -Database.prototype.compile = function(sql, kind) { - return alasql.compile(sql, kind, databaseid); -}; - -*/ -// var self = this; -// var hh = hash(sql); - -// // Check cache with hash of SQL statement -// var statement = this.sqlcache[hh]; -// if(!statement) { - -// // If not fount, then compile it -// var ast = alasql.parse(sql); -// // Save to cache - -// statement = this.sqlcache[hh]= ast.compile(self); - -// // Memory leak prevention -// this.sqlcachesize++; -// if(this.sqlcachesize > alasql.MAXSQLCACHESIZE) { -// this.resetSqlCache(); -// } -// }; -// return statement; -// } - -// SQL.js compatibility method -//Database.prototype.prepare = Database.prototype.compile; - - -// Added for compatibility with WebSQL - - - +/* +// +// Database class for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +// Main Database class +/** + @class Database + */ + +var Database = alasql.Database = function (databaseid) { + var self = this; + if(self === alasql) { + if(databaseid) { +// if(alasql.databases[databaseid]) { + self = alasql.databases[databaseid]; +// } else { + alasql.databases[databaseid] = self; +// } + if(!self) { + throw new Error('Database "'+databaseid+'" not found'); + } + } else { + // Create new database (or get alasql?) + self = alasql.databases.alasql; +// self = new Database(databaseid); // to call without new + } + } + if(!databaseid) { + databaseid = "db"+(alasql.databasenum++); // Random name + }; + self.databaseid = databaseid; + alasql.databases[databaseid] = self; + self.tables = {}; + self.views = {}; + + self.indices = {}; +// self.fn = {}; + self.resetSqlCache(); + self.dbversion = 0; + return self; +}; + + +/** + Reset SQL statements cache + */ + +Database.prototype.resetSqlCache = function () { + this.sqlCache = {}; // Cache for compiled SQL statements + this.sqlCacheSize = 0; +} + + +// // Main SQL function + +/** + Run SQL statement on database + @param {string} sql SQL statement + @param [object] params Parameters + @param {function} cb callback + */ + +Database.prototype.exec = function(sql, params, cb) { + return alasql.dexec(this.databaseid, sql, params, cb); +}; + +// // Compile +// var statement = this.compile(sql); +// // Run +// if(statement) { +// var data = statement(params, cb); +// return data; +// } +// return; +// }; + +// // Async version of exec + + +// Database.prototype.aexec = function(sql, params) { +// var self = this; +// return new Promise(function(resolve, reject){ +// alasql.dexec(this.databaseid,sql,params,resolve); +// }); +// }; + + +// Aliases like MS SQL +/* +Database.prototype.query = Database.prototype.exec; +Database.prototype.run = Database.prototype.exec; +Database.prototype.queryArray = function(sql, params, cb) { + return flatArray(this.exec(sql, params, cb)); +} + +Database.prototype.queryArrayOfArrays = function(sql, params, cb) { + return arrayOfArrays(this.exec(sql, params, cb)); +} + +Database.prototype.querySingle = function(sql, params, cb) { + return this.exec(sql, params, cb)[0]; +} +Database.prototype.queryValue = function(sql, params, cb) { + var res = this.querySingle(sql, params, cb); + return res[Object.keys(res)[0]]; +} + +Database.prototype.value = Database.prototype.queryValue; +Database.prototype.row = Database.prototype.querySingle; +Database.prototype.array = Database.prototype.queryArray; +Database.prototype.matrix = Database.prototype.queryArrayOfArrays; + + +// Compile statements +Database.prototype.compile = function(sql, kind) { + return alasql.compile(sql, kind, databaseid); +}; + +*/ +// var self = this; +// var hh = hash(sql); + +// // Check cache with hash of SQL statement +// var statement = this.sqlcache[hh]; +// if(!statement) { + +// // If not fount, then compile it +// var ast = alasql.parse(sql); +// // Save to cache + +// statement = this.sqlcache[hh]= ast.compile(self); + +// // Memory leak prevention +// this.sqlcachesize++; +// if(this.sqlcachesize > alasql.MAXSQLCACHESIZE) { +// this.resetSqlCache(); +// } +// }; +// return statement; +// } + +// SQL.js compatibility method +//Database.prototype.prepare = Database.prototype.compile; + + +// Added for compatibility with WebSQL + + + diff --git a/src/70insert.js b/src/70insert.js index 9a3d35a7fa..6bd0025e77 100644 --- a/src/70insert.js +++ b/src/70insert.js @@ -1,223 +1,230 @@ -/* -// -// INSERT for Alasql.js -// Date: 03.11.2014 -// (c) 2014, Andrey Gershun -// -*/ - -yy.Insert = function (params) { return yy.extend(this, params); } -yy.Insert.prototype.toString = function() { - var s = 'INSERT 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; -} - -yy.Insert.prototype.compile = function (databaseid) { - var self = this; - databaseid = self.into.databaseid || databaseid - var db = alasql.databases[databaseid]; -// console.log(self); - var tableid = self.into.tableid; - var table = db.tables[tableid]; - - // Check, if this dirty flag is required - var s = ''; - var sw = ''; -// var s = 'db.tables[\''+tableid+'\'].dirty=true;'; - var s3 = 'var a,aa=[];'; - var s33; - - -// INSERT INTO table VALUES - if(this.values) { - -// console.log(1); - self.values.forEach(function(values) { - var ss = []; - -// s += 'db.tables[\''+tableid+'\'].data.push({'; - -// s += ''; - if(self.columns) { - self.columns.forEach(function(col, idx){ -//console.log(db.tables, tableid, table); - // ss.push(col.columnid +':'+ self.values[idx].value.toString()); - // console.log(rec[f.name.value]); - // if(rec[f.name.value] == "NULL") rec[f.name.value] = undefined; - - // if(table.xflds[f.name.value].dbtypeid == "INT") rec[f.name.value] = +rec[f.name.value]|0; - // else if(table.xflds[f.name.value].dbtypeid == "FLOAT") rec[f.name.value] = +rec[f.name.value]; - var q = "'"+col.columnid +'\':'; - if(table.xcolumns && table.xcolumns[col.columnid]) { - if(["INT","FLOAT","NUMBER","MONEY"].indexOf(table.xcolumns[col.columnid].dbtypeid) >=0) { - q += "+"+values[idx].toJavaScript(); - } else if (alasql.fn[table.xcolumns[col.columnid].dbtypeid]) { - q += "(new "+table.xcolumns[col.columnid].dbtypeid+"("; - q += values[idx].toJavaScript(); - q += "))"; - } else { - q += values[idx].toJavaScript(); - }; - } else { - q += values[idx].toJavaScript(); - } - ss.push(q); - - }); - } else { -// var table = db.tables[tableid]; -// console.log('table1', db, self); -//console.log(111, table.columns); -//console.log(74,table); - if((values instanceof Array) && table.columns && table.columns.length > 0) { - table.columns.forEach(function(col, idx){ - - var q = '\''+col.columnid +'\':'; -// var val = values[idx].toJavaScript(); - - if(["INT","FLOAT","NUMBER","MONEY"].indexOf(col.dbtypeid) >=0) { - q += "+"+values[idx].toJavaScript(); - } else if (alasql.fn[col.dbtypeid]) { - q += "(new "+col.dbtypeid+"("; - q += values[idx].toJavaScript(); - q += "))"; - } else { - q += values[idx].toJavaScript(); - } - - // if(table.xcolumns && table.xcolumns[col.columnid] && - // (table.xcolumns[col.columnid].dbtypeid == "DATE" || - // table.xcolumns[col.columnid].dbtypeid == "DATETIME" - // )) { - // val = "(new Date("+val+"))"; - // } - // || table.xcolumns[col.columnid].dbtypeid == "FLOAT" - // || table.xcolumns[col.columnid].dbtypeid == "NUMBER" - // || table.xcolumns[col.columnid].dbtypeid == "MONEY" - // )) q += '+'; - // console.log(self.values[idx].toString()); - //console.log(self); -// q += val; - - // if(table.xcolumns && table.xcolumns[col.columnid] && table.xcolumns[col.columnid].dbtypeid == "INT") q += '|0'; - ss.push(q); - - // console.log(fld); - // TODO: type checking and conversions - // rec[fld.fldid] = eval(self.insertExpression[idx].toJavaScript('','')); - // console.log(rec[fld.fldid]); - // if(rec[fld.fldid] == "NULL") rec[fld.fldid] = undefined; - - // if(table.xflds[fld.fldid].dbtypeid == "INT") rec[fld.fldid] = +rec[fld.fldid]|0; - // else if(table.xflds[fld.fldid].dbtypeid == "FLOAT" || table.xflds[fld.fldid].dbtypeid == "MONEY" ) - // rec[fld.fldid] = +rec[fld.fldid]; - }); - } else { -// console.log(222,values); -// sw = 'var w='+JSONtoJavaScript(values)+';for(var k in w){r[k]=w[k]};'; - sw = JSONtoJavaScript(values); - } - } -//console.log(ss); - - if(db.tables[tableid].defaultfns) ss.unshift(db.tables[tableid].defaultfns); - if(sw) { - s += 'a='+sw+';'; - } else { - s += 'a={'+ss.join(',')+'};'; - } -// s += 'db.tables[\''+tableid+'\'].insert(r);'; - if(db.tables[tableid].insert) { - s += 'alasql.databases[\''+databaseid+'\'].tables[\''+tableid+'\'].insert(a);'; - } else { - s += 'aa.push(a);'; - } - }); - - s33 = s3+s; - - if(db.tables[tableid].insert) { -// s += 'alasql.databases[\''+databaseid+'\'].tables[\''+tableid+'\'].insert(r);'; - } else { - s += 'alasql.databases[\''+databaseid+'\'].tables[\''+tableid+'\'].data='+ - 'alasql.databases[\''+databaseid+'\'].tables[\''+tableid+'\'].data.concat(aa);'; - } - - s += 'return '+self.values.length; - -//console.log(s); - var insertfn = new Function('db, params, alasql',s3+s); - -// INSERT INTO table SELECT - - } else if(this.select) { - 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,null, cb); - return res; - }; - return statement; - } else { - var insertfn = function(db, params, alasql) { - var res = selectfn(params); - db.tables[tableid].data = db.tables[tableid].data.concat(res); - return res.length; - } - } - - - } else if(this.default) { - var insertfns = 'db.tables[\''+tableid+'\'].data.push({'+table.defaultfns+'});return 1;'; - var insertfn = new Function('db,params,alasql',insertfns); - } else { - throw new Error('Wrong INSERT parameters'); - } - -// console.log(1,s); -// console.log(s33); - - if(db.engineid && alasql.engines[db.engineid].intoTable && alasql.options.autocommit) { - var statement = function(params, cb) { - var aa = new Function("db,params",s33+'return aa;')(db,params); -// console.log(s33); - var res = alasql.engines[db.engineid].intoTable(db.databaseid,tableid,aa, null, cb); -// if(cb) cb(res); - return res; - }; - - } else { - - var statement = function(params, cb) { - //console.log(databaseid); - 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); - } - // var res = insertfn(db, params); - if(cb) cb(res); - return res; - }; - }; - - return statement; -}; - -yy.Insert.prototype.execute = function (databaseid, params, cb) { - return this.compile(databaseid)(params,cb); -// throw new Error('Insert statement is should be compiled') -} - - - +/* +// +// INSERT for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +yy.Insert = function (params) { return yy.extend(this, params); } +yy.Insert.prototype.toString = function() { + var s = 'INSERT 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; +} + +yy.Insert.prototype.compile = function (databaseid) { + var self = this; + databaseid = self.into.databaseid || databaseid + var db = alasql.databases[databaseid]; +// console.log(self); + var tableid = self.into.tableid; + var table = db.tables[tableid]; + + // Check, if this dirty flag is required + var s = ''; + var sw = ''; +// var s = 'db.tables[\''+tableid+'\'].dirty=true;'; + var s3 = 'var a,aa=[];'; + var s33; + + +// INSERT INTO table VALUES + if(this.values) { + +// console.log(1); + self.values.forEach(function(values) { + var ss = []; + +// s += 'db.tables[\''+tableid+'\'].data.push({'; + +// s += ''; + if(self.columns) { + self.columns.forEach(function(col, idx){ +//console.log(db.tables, tableid, table); + // ss.push(col.columnid +':'+ self.values[idx].value.toString()); + // console.log(rec[f.name.value]); + // if(rec[f.name.value] == "NULL") rec[f.name.value] = undefined; + + // if(table.xflds[f.name.value].dbtypeid == "INT") rec[f.name.value] = +rec[f.name.value]|0; + // else if(table.xflds[f.name.value].dbtypeid == "FLOAT") rec[f.name.value] = +rec[f.name.value]; + var q = "'"+col.columnid +'\':'; + if(table.xcolumns && table.xcolumns[col.columnid]) { + if(["INT","FLOAT","NUMBER","MONEY"].indexOf(table.xcolumns[col.columnid].dbtypeid) >=0) { + q += "+"+values[idx].toJavaScript(); + } else if (alasql.fn[table.xcolumns[col.columnid].dbtypeid]) { + q += "(new "+table.xcolumns[col.columnid].dbtypeid+"("; + q += values[idx].toJavaScript(); + q += "))"; + } else { + q += values[idx].toJavaScript(); + }; + } else { + q += values[idx].toJavaScript(); + } + ss.push(q); + + }); + } else { +// var table = db.tables[tableid]; +// console.log('table1', db, self); +//console.log(111, table.columns); +//console.log(74,table); + if((values instanceof Array) && table.columns && table.columns.length > 0) { + table.columns.forEach(function(col, idx){ + + var q = '\''+col.columnid +'\':'; +// var val = values[idx].toJavaScript(); + + if(["INT","FLOAT","NUMBER","MONEY"].indexOf(col.dbtypeid) >=0) { + q += "+"+values[idx].toJavaScript(); + } else if (alasql.fn[col.dbtypeid]) { + q += "(new "+col.dbtypeid+"("; + q += values[idx].toJavaScript(); + q += "))"; + } else { + q += values[idx].toJavaScript(); + } + + // if(table.xcolumns && table.xcolumns[col.columnid] && + // (table.xcolumns[col.columnid].dbtypeid == "DATE" || + // table.xcolumns[col.columnid].dbtypeid == "DATETIME" + // )) { + // val = "(new Date("+val+"))"; + // } + // || table.xcolumns[col.columnid].dbtypeid == "FLOAT" + // || table.xcolumns[col.columnid].dbtypeid == "NUMBER" + // || table.xcolumns[col.columnid].dbtypeid == "MONEY" + // )) q += '+'; + // console.log(self.values[idx].toString()); + //console.log(self); +// q += val; + + // if(table.xcolumns && table.xcolumns[col.columnid] && table.xcolumns[col.columnid].dbtypeid == "INT") q += '|0'; + ss.push(q); + + // console.log(fld); + // TODO: type checking and conversions + // rec[fld.fldid] = eval(self.insertExpression[idx].toJavaScript('','')); + // console.log(rec[fld.fldid]); + // if(rec[fld.fldid] == "NULL") rec[fld.fldid] = undefined; + + // if(table.xflds[fld.fldid].dbtypeid == "INT") rec[fld.fldid] = +rec[fld.fldid]|0; + // else if(table.xflds[fld.fldid].dbtypeid == "FLOAT" || table.xflds[fld.fldid].dbtypeid == "MONEY" ) + // rec[fld.fldid] = +rec[fld.fldid]; + }); + } else { +// console.log(222,values); +// sw = 'var w='+JSONtoJavaScript(values)+';for(var k in w){r[k]=w[k]};'; + sw = JSONtoJavaScript(values); + } + } +//console.log(ss); + + if(db.tables[tableid].defaultfns) ss.unshift(db.tables[tableid].defaultfns); + if(sw) { + s += 'a='+sw+';'; + } else { + s += 'a={'+ss.join(',')+'};'; + } +// s += 'db.tables[\''+tableid+'\'].insert(r);'; + if(db.tables[tableid].insert) { + s += 'alasql.databases[\''+databaseid+'\'].tables[\''+tableid+'\'].insert(a);'; + } else { + s += 'aa.push(a);'; + } + }); + + s33 = s3+s; + + if(db.tables[tableid].insert) { +// s += 'alasql.databases[\''+databaseid+'\'].tables[\''+tableid+'\'].insert(r);'; + } else { + s += 'alasql.databases[\''+databaseid+'\'].tables[\''+tableid+'\'].data='+ + 'alasql.databases[\''+databaseid+'\'].tables[\''+tableid+'\'].data.concat(aa);'; + } + + s += 'return '+self.values.length; + +//console.log(s); + var insertfn = new Function('db, params, alasql',s3+s); + +// INSERT INTO table SELECT + + } else if(this.select) { + 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,null, cb); + return res; + }; + return statement; + } else { + var insertfn = function(db, params, alasql) { + var res = selectfn(params); + if(db.tables[tableid].insert) { + // If insert() function exists (issue #92) + for(var i=0,ilen=res.length;i + + + + + + + + + + + + + + + + + + + + +