alasql 4.2.6 → 4.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/alasql.fs.js CHANGED
@@ -1,15 +1,15 @@
1
- //! AlaSQL v4.2.5 build: develop-40f8e9c3 | © 2014-2023 Andrey Gershun & Mathias Wulff | License: MIT
1
+ //! AlaSQL v4.2.7 build: develop-993501d9 | © 2014-2024 Andrey Gershun & Mathias Wulff | License: MIT
2
2
  /*
3
3
  @module alasql
4
- @version 4.2.5
4
+ @version 4.2.7
5
5
 
6
6
  AlaSQL - JavaScript SQL database
7
- © 2014-2023 Andrey Gershun & Mathias Wulff
7
+ © 2014-2024 Andrey Gershun & Mathias Wulff
8
8
 
9
9
  @license
10
10
  The MIT License (MIT)
11
11
 
12
- Copyright 2014-2023 Andrey Gershun (agershun@gmail.com) & Mathias Wulff (m@rawu.dk)
12
+ Copyright 2014-2024 Andrey Gershun (agershun@gmail.com) & Mathias Wulff (m@rawu.dk)
13
13
 
14
14
  Permission is hereby granted, free of charge, to any person obtaining a copy
15
15
  of this software and associated documentation files (the "Software"), to deal
@@ -49,109 +49,109 @@ SOFTWARE.
49
49
  */
50
50
 
51
51
  (function (root, factory) {
52
- if (typeof define === 'function' && define.amd) {
53
- define([], factory);
54
- } else if (typeof exports === 'object') {
55
- /** alasql main function */
56
- module.exports = factory();
57
- } else {
58
- root.alasql = factory();
59
- }
52
+ if (typeof define === 'function' && define.amd) {
53
+ define([], factory);
54
+ } else if (typeof exports === 'object') {
55
+ /** alasql main function */
56
+ module.exports = factory();
57
+ } else {
58
+ root.alasql = factory();
59
+ }
60
60
  }(this, function () {
61
61
 
62
- /**
63
- AlaSQL - Main Alasql class
64
- @function
65
- @param {string|function|object} sql - SQL-statement or data object for fluent interface
66
- @param {object} params - SQL parameters
67
- @param {function} cb - callback function
68
- @param {object} scope - Scope for nested queries
69
- @return {any} - Result data object
70
-
71
- @example
72
- Standard sync call:
73
- alasql('CREATE TABLE one');
74
- Query:
75
- var res = alasql('SELECT * FROM one');
76
- Call with parameters:
77
- var res = alasql('SELECT * FROM ?',[data]);
78
- Standard async call with callback function:
79
- alasql('SELECT * FROM ?',[data],function(res){
80
- console.log(data);
81
- });
82
- Call with scope for subquery (to pass common values):
83
- var scope = {one:{a:2,b;20}}
84
- alasql('SELECT * FROM ? two WHERE two.a = one.a',[data],null,scope);
85
- Call for fluent interface with data object:
86
- alasql(data).Where(function(x){return x.a == 10}).exec();
87
- Call for fluent interface without data object:
88
- alasql().From(data).Where(function(x){return x.a == 10}).exec();
89
- */
62
+ /**
63
+ AlaSQL - Main Alasql class
64
+ @function
65
+ @param {string|function|object} sql - SQL-statement or data object for fluent interface
66
+ @param {object} params - SQL parameters
67
+ @param {function} cb - callback function
68
+ @param {object} scope - Scope for nested queries
69
+ @return {any} - Result data object
70
+
71
+ @example
72
+ Standard sync call:
73
+ alasql('CREATE TABLE one');
74
+ Query:
75
+ var res = alasql('SELECT * FROM one');
76
+ Call with parameters:
77
+ var res = alasql('SELECT * FROM ?',[data]);
78
+ Standard async call with callback function:
79
+ alasql('SELECT * FROM ?',[data],function(res){
80
+ console.log(data);
81
+ });
82
+ Call with scope for subquery (to pass common values):
83
+ var scope = {one:{a:2,b;20}}
84
+ alasql('SELECT * FROM ? two WHERE two.a = one.a',[data],null,scope);
85
+ Call for fluent interface with data object:
86
+ alasql(data).Where(function(x){return x.a == 10}).exec();
87
+ Call for fluent interface without data object:
88
+ alasql().From(data).Where(function(x){return x.a == 10}).exec();
89
+ */
90
90
 
91
- var alasql = function(sql, params, cb, scope) {
91
+ let alasql = function (sql, params, cb, scope) {
92
92
 
93
- params = params||[];
93
+ params = params || [];
94
94
 
95
- if(typeof importScripts !== 'function' && alasql.webworker) {
96
- var id = alasql.lastid++;
97
- alasql.buffer[id] = cb;
98
- alasql.webworker.postMessage({id:id,sql:sql,params:params});
99
- return;
100
- }
95
+ if (typeof importScripts !== 'function' && alasql.webworker) {
96
+ var id = alasql.lastid++;
97
+ alasql.buffer[id] = cb;
98
+ alasql.webworker.postMessage({ id: id, sql: sql, params: params });
99
+ return;
100
+ }
101
101
 
102
- if(arguments.length === 0) {
103
- // Without arguments - Fluent interface
104
- return new yy.Select({
105
- columns:[new yy.Column({columnid:'*'})],
106
- from: [new yy.ParamValue({param:0})]
107
- });
108
- } else if(arguments.length === 1){
109
- // Access promise notation without using `.promise(...)`
110
- if(sql.constructor === Array){
111
- return alasql.promise(sql);
102
+ if (arguments.length === 0) {
103
+ // Without arguments - Fluent interface
104
+ return new yy.Select({
105
+ columns: [new yy.Column({ columnid: '*' })],
106
+ from: [new yy.ParamValue({ param: 0 })]
107
+ });
108
+ } else if (arguments.length === 1) {
109
+ // Access promise notation without using `.promise(...)`
110
+ if (sql.constructor === Array) {
111
+ return alasql.promise(sql);
112
+ }
113
+ }
114
+ // Avoid setting params if not needed even with callback
115
+ if (typeof params === 'function') {
116
+ scope = cb;
117
+ cb = params;
118
+ params = [];
112
119
  }
113
- }
114
- // Avoid setting params if not needed even with callback
115
- if(typeof params === 'function'){
116
- scope = cb;
117
- cb = params;
118
- params = [];
119
- }
120
120
 
121
- if(typeof params !== 'object'){
121
+ if (typeof params !== 'object') {
122
122
  params = [params];
123
- }
123
+ }
124
124
 
125
- // Standard interface
126
- // alasql('#sql');
127
- if(typeof sql === 'string' && sql[0]==='#' && typeof document === "object") {
128
- sql = document.querySelector(sql).textContent;
129
- } else if(typeof sql === 'object' && sql instanceof HTMLElement) {
130
- sql = sql.textContent;
131
- } else if(typeof sql === 'function') {
132
- // to run multiline functions
133
- sql = sql.toString();
134
- sql = (/\/\*([\S\s]+)\*\//m.exec(sql) || ['','Function given as SQL. Plese Provide SQL string or have a /* ... */ syle comment with SQL in the function.'])[1];
135
- }
136
- // Run SQL
137
- return alasql.exec(sql, params, cb, scope);
138
- };
125
+ // Standard interface
126
+ // alasql('#sql');
127
+ if (typeof sql === 'string' && sql[0] === '#' && typeof document === "object") {
128
+ sql = document.querySelector(sql).textContent;
129
+ } else if (typeof sql === 'object' && sql instanceof HTMLElement) {
130
+ sql = sql.textContent;
131
+ } else if (typeof sql === 'function') {
132
+ // to run multiline functions
133
+ sql = sql.toString();
134
+ sql = (/\/\*([\S\s]+)\*\//m.exec(sql) || ['', 'Function given as SQL. Plese Provide SQL string or have a /* ... */ syle comment with SQL in the function.'])[1];
135
+ }
136
+ // Run SQL
137
+ return alasql.exec(sql, params, cb, scope);
138
+ };
139
139
 
140
- /**
141
- Current version of alasql
142
- @constant {string}
143
- */
144
- alasql.version = '4.2.5';
145
- alasql.build = 'develop-40f8e9c3';
140
+ /**
141
+ Current version of alasql
142
+ @constant {string}
143
+ */
144
+ alasql.version = '4.2.7';
145
+ alasql.build = 'develop-993501d9';
146
146
 
147
- /**
148
- Debug flag
149
- @type {boolean}
150
- */
151
- alasql.debug = undefined; // Initial debug variable
147
+ /**
148
+ Debug flag
149
+ @type {boolean}
150
+ */
151
+ alasql.debug = undefined; // Initial debug variable
152
152
 
153
153
  /*only-for-browser/*
154
- var require = function(){return null}; // as alasqlparser.js is generated, we can not "remove" references to
154
+ var require = function(){return null}; // as alasqlparser.js is generated, we can not "remove" references to
155
155
  var __dirname = '';
156
156
  //*/
157
157
  /* parser generated by jison 0.4.18 */
@@ -3144,7 +3144,7 @@ if (typeof module !== 'undefined' && require.main === module) {
3144
3144
  */
3145
3145
 
3146
3146
  /**
3147
- Pretty flag - nice HTML output or standard text without any tags
3147
+ Pretty flag - nice HTML output or standard text without any tags
3148
3148
  @type {boolean}
3149
3149
  */
3150
3150
 
@@ -3155,7 +3155,7 @@ alasql.prettyflag = false;
3155
3155
  @function
3156
3156
  @param {string} sql SQL statement
3157
3157
  @param {boolean} flag value
3158
- @return {string} HTML or text string with pretty output
3158
+ @return {string} HTML or text string with pretty output
3159
3159
  */
3160
3160
 
3161
3161
  alasql.pretty = function (sql, flag) {
@@ -3165,7 +3165,6 @@ alasql.pretty = function (sql, flag) {
3165
3165
  alasql.prettyflag = pf;
3166
3166
  return s;
3167
3167
  };
3168
-
3169
3168
  /*jshint unused:false*/
3170
3169
  /*
3171
3170
  Utilities for Alasql.js
@@ -3455,6 +3454,7 @@ utils.hasIndexedDB = (function () {
3455
3454
  utils.isArray = function (obj) {
3456
3455
  return '[object Array]' === Object.prototype.toString.call(obj);
3457
3456
  };
3457
+
3458
3458
  /**
3459
3459
  Load text file from anywhere
3460
3460
  @param {string|object} path File path or HTML event
@@ -3466,7 +3466,9 @@ utils.isArray = function (obj) {
3466
3466
  @todo Define Event type
3467
3467
  @todo Smaller if-else structures.
3468
3468
  */
3469
- var loadFile = (utils.loadFile = function (path, asy, success, error) {
3469
+
3470
+ const protocolRegex = /^[a-z]+:\/\//i;
3471
+ let loadFile = (utils.loadFile = function (path, asy, success, error) {
3470
3472
  var data, fs;
3471
3473
  if (utils.isNode || utils.isMeteorServer) {
3472
3474
  //*not-for-browser/*
@@ -3485,30 +3487,38 @@ var loadFile = (utils.loadFile = function (path, asy, success, error) {
3485
3487
  process.stdin.on('end', function () {
3486
3488
  success(cutbom(buff));
3487
3489
  });
3488
- } else {
3489
- if (/^[a-z]+:\/\//i.test(path)) {
3490
- fetchData(path, x => success(cutbom(x)), error, asy);
3491
- } else {
3492
- //If async callthen call async
3493
- if (asy) {
3494
- fs.readFile(path, function (err, data) {
3495
- if (err) {
3496
- return error(err, null);
3497
- }
3498
- success(cutbom(data.toString()));
3499
- });
3500
- } else {
3501
- // Call sync version
3502
- try {
3503
- data = fs.readFileSync(path);
3504
- } catch (e) {
3505
- return error(err, null);
3506
- }
3507
- success(cutbom(data.toString()));
3490
+ return;
3491
+ }
3492
+
3493
+ if (protocolRegex.test(path)) {
3494
+ fetchData(path, x => success(cutbom(x)), error, asy);
3495
+ return;
3496
+ }
3497
+
3498
+ //If async callthen call async
3499
+ if (asy) {
3500
+ fs.readFile(path, function (err, data) {
3501
+ if (err) {
3502
+ return error(err, null);
3508
3503
  }
3509
- }
3504
+ success(cutbom(data.toString()));
3505
+ });
3506
+ return;
3510
3507
  }
3511
- } else if (utils.isReactNative) {
3508
+
3509
+ // Call sync version
3510
+ try {
3511
+ data = fs.readFileSync(path);
3512
+ } catch (e) {
3513
+ error(err, null);
3514
+ return;
3515
+ }
3516
+
3517
+ success(cutbom(data.toString()));
3518
+ return;
3519
+ }
3520
+
3521
+ if (utils.isReactNative) {
3512
3522
  // If ReactNative
3513
3523
  var RNFS = require('react-native-fs');
3514
3524
  RNFS.readFile(path, 'utf8')
@@ -3519,7 +3529,10 @@ var loadFile = (utils.loadFile = function (path, asy, success, error) {
3519
3529
  return error(err, null);
3520
3530
  });
3521
3531
  //*/
3522
- } else if (utils.isCordova) {
3532
+ return;
3533
+ }
3534
+
3535
+ if (utils.isCordova) {
3523
3536
  /* If Cordova */
3524
3537
  utils.global.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) {
3525
3538
  fileSystem.root.getFile(path, {create: false}, function (fileEntry) {
@@ -3533,48 +3546,52 @@ var loadFile = (utils.loadFile = function (path, asy, success, error) {
3533
3546
  });
3534
3547
  });
3535
3548
 
3536
- /** @todo Check eliminated code below */
3549
+ return;
3550
+ }
3537
3551
 
3538
- } else {
3539
- /* For string */
3540
- if (typeof path === 'string') {
3541
- // For browser read from tag
3542
- /*
3543
- SELECT * FROM TXT('#one') -- read data from HTML element with id="one"
3544
- */
3545
- if (path.substr(0, 1) === '#' && typeof document !== 'undefined') {
3546
- data = document.querySelector(path).textContent;
3547
- success(data);
3548
- } else {
3549
- /*
3550
- Simply read file from HTTP request, like:
3551
- SELECT * FROM TXT('http://alasql.org/README.md');
3552
- */
3553
- fetchData(path, x => success(cutbom(x)), error, asy);
3554
- }
3555
- } else if (path instanceof Event) {
3556
- /*
3557
- For browser read from files input element
3558
- <input type="files" onchange="readFile(event)">
3559
- <script>
3560
- function readFile(event) {
3561
- alasql('SELECT * FROM TXT(?)',[event])
3562
- }
3563
- </script>
3564
- */
3565
- /** @type {array} List of files from <input> element */
3566
- var files = path.target.files;
3567
- /** type {object} */
3568
- var reader = new FileReader();
3569
- /** type {string} */
3570
- var name = files[0].name;
3571
- reader.onload = function (e) {
3572
- var data = e.target.result;
3573
- success(cutbom(data));
3574
- };
3575
- reader.readAsText(files[0]);
3552
+ /* For string */
3553
+ if (typeof path === 'string') {
3554
+ // For browser read from tag
3555
+ /*
3556
+ SELECT * FROM TXT('#one') -- read data from HTML element with id="one"
3557
+ */
3558
+ if (path.substr(0, 1) === '#' && typeof document !== 'undefined') {
3559
+ data = document.querySelector(path).textContent;
3560
+ success(data);
3561
+ return;
3576
3562
  }
3563
+
3564
+ /*
3565
+ Simply read file from HTTP request, like:
3566
+ SELECT * FROM TXT('http://alasql.org/README.md');
3567
+ */
3568
+ fetchData(path, x => success(cutbom(x)), error, asy);
3569
+ return;
3570
+ }
3571
+
3572
+ if (path instanceof Event) {
3573
+ /*
3574
+ For browser read from files input element
3575
+ <input type="files" onchange="readFile(event)">
3576
+ <script>
3577
+ function readFile(event) {
3578
+ alasql('SELECT * FROM TXT(?)',[event])
3579
+ }
3580
+ </script>
3581
+ */
3582
+ /** @type {array} List of files from <input> element */
3583
+ var files = path.target.files;
3584
+ /** type {object} */
3585
+ var reader = new FileReader();
3586
+ /** type {string} */
3587
+ var name = files[0].name;
3588
+ reader.onload = function (e) {
3589
+ var data = e.target.result;
3590
+ success(cutbom(data));
3591
+ };
3592
+ reader.readAsText(files[0]);
3577
3593
  }
3594
+ fetchData(path, x => success(cutbom(x)), error, asy);
3578
3595
  });
3579
3596
 
3580
3597
  let _fetch = typeof fetch !== 'undefined' ? fetch : null;
@@ -4340,15 +4357,15 @@ var getXLSX = function () {
4340
4357
  // set AlaSQl path
4341
4358
  alasql.path = alasql.utils.findAlaSQLPath();
4342
4359
  /**
4343
- Strip all comments.
4344
- @function
4345
- @param {string} str
4346
- @return {string}
4347
- Based om the https://github.com/lehni/uncomment.js/blob/master/uncomment.js
4348
- I just replaced JavaScript's '//' to SQL's '--' and remove other stuff
4349
-
4350
- @todo Fixed [aaa/*bbb] for column names
4351
- @todo Bug if -- comments in the last line
4360
+ Strip all comments.
4361
+ @function
4362
+ @param {string} str
4363
+ @return {string}
4364
+ Based om the https://github.com/lehni/uncomment.js/blob/master/uncomment.js
4365
+ I just replaced JavaScript's '//' to SQL's '--' and remove other stuff
4366
+
4367
+ @todo Fixed [aaa/*bbb] for column names
4368
+ @todo Bug if -- comments in the last line
4352
4369
  @todo Check if it possible to model it with Jison parser
4353
4370
  @todo Remove unused code
4354
4371
  */
@@ -4367,7 +4384,6 @@ alasql.utils.uncomment = function (str) {
4367
4384
  // preserveComment = false;
4368
4385
 
4369
4386
  for (var i = 0, l = str.length; i < l; i++) {
4370
-
4371
4387
  // When checking for quote escaping, we also need to check that the
4372
4388
  // escape sign itself is not escaped, as otherwise '\\' would cause
4373
4389
  // the wrong impression of an unclosed string:
@@ -4377,7 +4393,6 @@ alasql.utils.uncomment = function (str) {
4377
4393
  if (str[i] === quoteSign && unescaped) {
4378
4394
  quote = false;
4379
4395
  }
4380
-
4381
4396
  } else if (blockComment) {
4382
4397
  // Is the block comment closing?
4383
4398
  if (str[i] === '*' && str[i + 1] === '/') {
@@ -4414,7 +4429,6 @@ alasql.utils.uncomment = function (str) {
4414
4429
  // if (!preserveComment)
4415
4430
  str[i] = '';
4416
4431
  blockComment = true;
4417
-
4418
4432
  }
4419
4433
  }
4420
4434
  }
@@ -4600,17 +4614,18 @@ alasql.use = function (databaseid) {
4600
4614
  if (!databaseid) {
4601
4615
  databaseid = alasql.DEFAULTDATABASEID;
4602
4616
  }
4617
+
4603
4618
  if (alasql.useid === databaseid) {
4604
4619
  return;
4605
4620
  }
4621
+
4606
4622
  if (alasql.databases[databaseid] !== undefined) {
4607
4623
  alasql.useid = databaseid;
4608
- var db = alasql.databases[alasql.useid];
4624
+ let db = alasql.databases[alasql.useid];
4609
4625
  alasql.tables = db.tables;
4610
- // alasql.fn = db.fn;
4611
4626
  db.resetSqlCache();
4612
4627
  if (alasql.options.usedbo) {
4613
- alasql.databases.dbo = db; // Operator???
4628
+ alasql.databases.dbo = db;
4614
4629
  }
4615
4630
  } else {
4616
4631
  throw Error('Database does not exist: ' + databaseid);
@@ -4650,7 +4665,9 @@ alasql.exec = function (sql, params, cb, scope) {
4650
4665
  }
4651
4666
 
4652
4667
  delete alasql.error;
4668
+
4653
4669
  params = params || {};
4670
+
4654
4671
  if (alasql.options.errorlog) {
4655
4672
  try {
4656
4673
  return alasql.dexec(alasql.useid, sql, params, cb, scope);
@@ -4676,14 +4693,14 @@ alasql.dexec = function (databaseid, sql, params, cb, scope) {
4676
4693
 
4677
4694
  // Create hash
4678
4695
  if (alasql.options.cache) {
4679
- var statement = db.sqlCache[hh];
4696
+ let statement = db.sqlCache[hh];
4680
4697
  // If database structure was not changed since last time return cache
4681
4698
  if (statement && db.dbversion === statement.dbversion) {
4682
4699
  return statement(params, cb);
4683
4700
  }
4684
4701
  }
4685
4702
 
4686
- var ast = db.astCache[hh];
4703
+ let ast = db.astCache[hh];
4687
4704
  if (alasql.options.cache && !ast) {
4688
4705
  // Create AST cache
4689
4706
  ast = alasql.parse(sql);
@@ -4694,12 +4711,16 @@ alasql.dexec = function (databaseid, sql, params, cb, scope) {
4694
4711
  } else {
4695
4712
  ast = alasql.parse(sql);
4696
4713
  }
4714
+
4697
4715
  if (!ast.statements) {
4698
4716
  return;
4699
4717
  }
4718
+
4700
4719
  if (0 === ast.statements.length) {
4701
4720
  return 0;
4702
- } else if (1 === ast.statements.length) {
4721
+ }
4722
+
4723
+ if (1 === ast.statements.length) {
4703
4724
  if (ast.statements[0].compile) {
4704
4725
  // Compile and Execute
4705
4726
  var statement = ast.statements[0].compile(databaseid, params);
@@ -4719,20 +4740,18 @@ alasql.dexec = function (databaseid, sql, params, cb, scope) {
4719
4740
  }
4720
4741
  var res = (alasql.res = statement(params, cb, scope));
4721
4742
  return res;
4722
- } else {
4723
-
4724
- alasql.precompile(ast.statements[0], alasql.useid, params);
4725
- var res = (alasql.res = ast.statements[0].execute(databaseid, params, cb, scope));
4726
- return res;
4727
- }
4728
- } else {
4729
- // Multiple statements
4730
- if (cb) {
4731
- alasql.adrun(databaseid, ast, params, cb, scope);
4732
- } else {
4733
- return alasql.drun(databaseid, ast, params, cb, scope);
4734
4743
  }
4744
+ alasql.precompile(ast.statements[0], alasql.useid, params);
4745
+ var res = (alasql.res = ast.statements[0].execute(databaseid, params, cb, scope));
4746
+ return res;
4747
+ }
4748
+
4749
+ if (cb) {
4750
+ alasql.adrun(databaseid, ast, params, cb, scope);
4751
+ return;
4735
4752
  }
4753
+
4754
+ return alasql.drun(databaseid, ast, params, cb, scope);
4736
4755
  };
4737
4756
 
4738
4757
  /**
@@ -4791,28 +4810,30 @@ alasql.adrun = function (databaseid, ast, params, cb, scope) {
4791
4810
  if (data !== undefined) {
4792
4811
  res.push(data);
4793
4812
  }
4813
+
4794
4814
  var astatement = ast.statements.shift();
4795
4815
  if (!astatement) {
4796
4816
  if (useid !== databaseid) {
4797
4817
  alasql.use(useid);
4798
4818
  }
4799
4819
  cb(res);
4800
- // alasql.busy--;
4801
- // if(alasql.busy<0) alasql.busy = 0;
4802
- } else {
4803
- if (astatement.compile) {
4804
- var statement = astatement.compile(alasql.useid);
4805
- statement(params, adrunone, scope);
4806
- if (alasql.options.progress !== false) {
4807
- alasql.options.progress(noqueries, idx++);
4808
- }
4809
- } else {
4810
- alasql.precompile(ast.statements[0], alasql.useid, params);
4811
- astatement.execute(alasql.useid, params, adrunone);
4812
- if (alasql.options.progress !== false) {
4813
- alasql.options.progress(noqueries, idx++);
4814
- }
4820
+ return;
4821
+ }
4822
+
4823
+ if (astatement.compile) {
4824
+ var statement = astatement.compile(alasql.useid);
4825
+ statement(params, adrunone, scope);
4826
+ if (alasql.options.progress !== false) {
4827
+ alasql.options.progress(noqueries, idx++);
4815
4828
  }
4829
+ return;
4830
+ }
4831
+
4832
+ alasql.precompile(ast.statements[0], alasql.useid, params);
4833
+ astatement.execute(alasql.useid, params, adrunone);
4834
+
4835
+ if (alasql.options.progress !== false) {
4836
+ alasql.options.progress(noqueries, idx++);
4816
4837
  }
4817
4838
  }
4818
4839
 
@@ -4828,29 +4849,27 @@ alasql.adrun = function (databaseid, ast, params, cb, scope) {
4828
4849
  alasql.compile = function (sql, databaseid) {
4829
4850
  databaseid = databaseid || alasql.useid;
4830
4851
 
4831
- var ast = alasql.parse(sql); // Create AST
4852
+ let ast = alasql.parse(sql); // Create AST
4832
4853
 
4833
- if (1 === ast.statements.length) {
4834
- var statement = ast.statements[0].compile(databaseid);
4835
- statement.promise = function (params) {
4836
- return new Promise(function (resolve, reject) {
4837
- statement(params, function (data, err) {
4838
- if (err) {
4839
- reject(err);
4840
- } else {
4841
- resolve(data);
4842
- }
4843
- });
4844
- });
4845
- };
4854
+ if (1 !== ast.statements.length)
4855
+ throw new Error('Cannot compile, because number of statements in SQL is not equal to 1');
4846
4856
 
4847
- return statement;
4857
+ var statement = ast.statements[0].compile(databaseid);
4848
4858
 
4849
- } else {
4850
- throw new Error('Cannot compile, because number of statements in SQL is not equal to 1');
4851
- }
4852
- };
4859
+ statement.promise = function (params) {
4860
+ return new Promise(function (resolve, reject) {
4861
+ statement(params, function (data, err) {
4862
+ if (err) {
4863
+ reject(err);
4864
+ } else {
4865
+ resolve(data);
4866
+ }
4867
+ });
4868
+ });
4869
+ };
4853
4870
 
4871
+ return statement;
4872
+ };
4854
4873
  //
4855
4874
  // Promises for AlaSQL
4856
4875
  //
@@ -4876,6 +4895,7 @@ var promiseExec = function (sql, params, counterStep, counterTotal) {
4876
4895
 
4877
4896
  const sequentialPromiseResolver = (promiseData, Promise) => {
4878
4897
  var startingPoint = Promise.resolve([]);
4898
+
4879
4899
  promiseData.forEach(p => {
4880
4900
  startingPoint = startingPoint.then(previousResult =>
4881
4901
  promiseExec(p.sql, p.params, p.i, p.length).then(result => [...previousResult, result])
@@ -5233,7 +5253,6 @@ class Recordset {
5233
5253
 
5234
5254
  alasql.Recordset = Recordset;
5235
5255
  alasql.Query = Query;
5236
-
5237
5256
  /*
5238
5257
  //
5239
5258
  // Parser helper for Alasql.js
@@ -5626,7 +5645,6 @@ yy.Search = class Search {
5626
5645
  alasql.vars[sel.args[0]] = oldv;
5627
5646
  return r1;
5628
5647
  }
5629
-
5630
5648
  } else if (sel.selid === 'ARRAY') {
5631
5649
  var nest = processSelector(sel.args, 0, value);
5632
5650
  if (nest.length > 0) {
@@ -5919,10 +5937,6 @@ yy.Search = class Search {
5919
5937
  ) {
5920
5938
  fromdata = fromdata.find().fetch();
5921
5939
  }
5922
-
5923
- // if(typeof fromdata == 'object' && Array.isArray(fromdata)) {
5924
- // selectors.unshift({srchid:'CHILD'});
5925
- // }
5926
5940
  }
5927
5941
 
5928
5942
  // If source data is array than first step is to run over array
@@ -6386,7 +6400,7 @@ var compileSearchOrder = function (order) {
6386
6400
  s += `if (
6387
6401
  (a[${JSON.stringify(columnid)}]||'')${dg}
6388
6402
  ${ord.direction === 'ASC' ? '>' : '<'}
6389
- (b[${JSON.stringify(columnid)}]||'')${dg}
6403
+ (b[${JSON.stringify(columnid)}]||'')${dg}
6390
6404
  ) return 1;
6391
6405
 
6392
6406
  if(
@@ -6402,26 +6416,17 @@ var compileSearchOrder = function (order) {
6402
6416
  if (ord.nocase) {
6403
6417
  dg += '.toUpperCase()';
6404
6418
  }
6405
- s +=
6406
- 'if((' +
6407
- ord.toJS('a', '') +
6408
- "||'')" +
6409
- dg +
6410
- (ord.direction === 'ASC' ? '>(' : '<(') +
6411
- ord.toJS('b', '') +
6412
- "||'')" +
6413
- dg +
6414
- ')return 1;';
6415
- s +=
6416
- 'if((' +
6417
- ord.toJS('a', '') +
6418
- "||'')" +
6419
- dg +
6420
- '==(' +
6421
- ord.toJS('b', '') +
6422
- "||'')" +
6423
- dg +
6424
- '){';
6419
+ s += `
6420
+ if (
6421
+ (${ord.toJS('a', '')} || '')${dg}
6422
+ ${ord.direction === 'ASC' ? '>' : '<'}
6423
+ (${ord.toJS('b', '')} || '')${dg}
6424
+ ) return 1;
6425
+
6426
+ if (
6427
+ (${ord.toJS('a', '')} || '')${dg} ==
6428
+ (${ord.toJS('b', '')} || '')${dg}
6429
+ ) {`;
6425
6430
  }
6426
6431
 
6427
6432
  // TODO Add date comparision
@@ -6438,11 +6443,8 @@ var compileSearchOrder = function (order) {
6438
6443
  };
6439
6444
  // Main query procedure
6440
6445
  function queryfn(query, oldscope, cb, A, B) {
6441
- var aaa = query.sources.length;
6442
-
6443
- var ms;
6444
6446
  query.sourceslen = query.sources.length;
6445
- var slen = query.sourceslen;
6447
+ let slen = query.sourceslen;
6446
6448
  query.query = query; // TODO Remove to prevent memory leaks
6447
6449
  query.A = A;
6448
6450
  query.B = B;
@@ -6457,56 +6459,35 @@ function queryfn(query, oldscope, cb, A, B) {
6457
6459
  query.queriesdata = [];
6458
6460
 
6459
6461
  query.queriesfn.forEach(function (q, idx) {
6460
- // if(query.explain) ms = Date.now();
6461
-
6462
- // var res = flatArray(q(query.params,null,queryfn2,(-idx-1),query));
6463
-
6464
- // var res = flatArray(queryfn(q.query,null,queryfn2,(-idx-1),query));
6465
-
6466
6462
  q.query.params = query.params;
6467
- // query.queriesdata[idx] =
6468
-
6469
- // if(false) {
6470
- // queryfn(q.query,query.oldscope,queryfn2,(-idx-1),query);
6471
- // } else {
6472
6463
  queryfn2([], -idx - 1, query);
6473
- // }
6474
-
6475
- // query.explaination.push({explid: query.explid++, description:'Query '+idx,ms:Date.now()-ms});
6476
- // query.queriesdata[idx] = res;
6477
- // return res;
6478
6464
  });
6479
-
6480
6465
  }
6481
6466
 
6482
- var scope;
6483
- if (!oldscope) scope = {};
6484
- else scope = cloneDeep(oldscope);
6485
- query.scope = scope;
6467
+ query.scope = oldscope ? cloneDeep(oldscope) : {};
6486
6468
 
6487
6469
  // First - refresh data sources
6488
6470
 
6489
6471
  let result;
6490
6472
  query.sources.forEach(function (source, idx) {
6491
- // source.data = query.database.tables[source.tableid].data;
6492
-
6493
6473
  source.query = query;
6494
6474
  var rs = source.datafn(query, query.params, queryfn2, idx, alasql);
6495
-
6496
6475
  if (typeof rs !== 'undefined') {
6497
- // TODO - this is a hack: check if result is array - check all cases and
6498
- // make it more logical
6499
- if ((query.intofn || query.intoallfn) && Array.isArray(rs)) rs = rs.length;
6476
+ // TODO - this is a hack: check if result is array - check all cases and make it more logical
6477
+ if ((query.intofn || query.intoallfn) && Array.isArray(rs)) {
6478
+ rs = rs.length;
6479
+ }
6500
6480
  result = rs;
6501
6481
  }
6502
6482
  //
6503
6483
  // Ugly hack to use in query.wherefn and source.srcwherefns functions
6504
6484
  // constructions like this.queriesdata['test'].
6505
- // I can elimite it with source.srcwherefn.bind(this)()
6485
+ // We can elimite it with source.srcwherefn.bind(this)()
6506
6486
  // but it may be slow.
6507
6487
  //
6508
6488
  source.queriesdata = query.queriesdata;
6509
6489
  });
6490
+
6510
6491
  if (query.sources.length == 0 || 0 === slen) {
6511
6492
  try {
6512
6493
  result = queryfn3(query);
@@ -6518,29 +6499,20 @@ function queryfn(query, oldscope, cb, A, B) {
6518
6499
 
6519
6500
  return result;
6520
6501
  }
6521
-
6522
6502
  function queryfn2(data, idx, query) {
6523
-
6524
- //console.trace();
6525
-
6526
6503
  if (idx >= 0) {
6527
- var source = query.sources[idx];
6504
+ let source = query.sources[idx];
6528
6505
  source.data = data;
6529
- if (typeof source.data == 'function') {
6506
+ if (typeof source.data === 'function') {
6530
6507
  source.getfn = source.data;
6531
6508
  source.dontcache = source.getfn.dontcache;
6532
-
6533
- // var prevsource = query.sources[h-1];
6534
- if (source.joinmode == 'OUTER' || source.joinmode == 'RIGHT' || source.joinmode == 'ANTI') {
6509
+ if (['OUTER', 'RIGHT', 'ANTI'].includes(source.joinmode)) {
6535
6510
  source.dontcache = false;
6536
6511
  }
6537
6512
  source.data = {};
6538
6513
  }
6539
6514
  } else {
6540
- // subqueries
6541
-
6542
6515
  query.queriesdata[-idx - 1] = flatArray(data);
6543
-
6544
6516
  }
6545
6517
 
6546
6518
  query.sourceslen--;
@@ -6554,13 +6526,7 @@ function queryfn3(query) {
6554
6526
  jlen;
6555
6527
 
6556
6528
  // Preindexation of data sources
6557
- // if(!oldscope) {
6558
6529
  preIndex(query);
6559
- // }
6560
-
6561
- // query.sources.forEach(function(source) {
6562
-
6563
- // });
6564
6530
 
6565
6531
  // Prepare variables
6566
6532
  query.data = [];
@@ -6571,17 +6537,14 @@ function queryfn3(query) {
6571
6537
  var h = 0;
6572
6538
 
6573
6539
  // Start walking over data
6574
-
6575
6540
  doJoin(query, scope, h);
6576
6541
 
6577
6542
  // If grouping, then filter groups with HAVING function
6578
-
6579
6543
  if (query.groupfn) {
6580
6544
  query.data = [];
6581
6545
  if (query.groups.length === 0 && query.allgroups.length === 0) {
6582
6546
  var g = {};
6583
6547
  if (query.selectGroup.length > 0) {
6584
-
6585
6548
  query.selectGroup.forEach(function (sg) {
6586
6549
  if (
6587
6550
  sg.aggregatorid == 'COUNT' ||
@@ -6595,37 +6558,25 @@ function queryfn3(query) {
6595
6558
  });
6596
6559
  }
6597
6560
  query.groups = [g];
6598
-
6599
6561
  }
6600
6562
 
6601
- // ******
6602
-
6603
6563
  if (query.aggrKeys.length > 0) {
6604
6564
  var gfns = '';
6605
6565
  query.aggrKeys.forEach(function (col) {
6606
- gfns += `g[${JSON.stringify(col.nick)}] = alasql.aggr[${JSON.stringify(
6566
+ gfns += `
6567
+ g[${JSON.stringify(col.nick)}] = alasql.aggr[${JSON.stringify(
6607
6568
  col.funcid
6608
- )}](undefined,g[${JSON.stringify(col.nick)}],3);`;
6609
-
6610
- // gfns += 'return g[\''+col.nick+'\];';
6569
+ )}](undefined,g[${JSON.stringify(col.nick)}],3); `;
6611
6570
  });
6612
-
6613
6571
  var gfn = new Function('g,params,alasql', 'var y;' + gfns);
6614
6572
  }
6615
6573
 
6616
- // *******
6617
-
6618
- // debugger;
6619
- // if(false && (query.groups.length == 1) && (Object.keys(query.groups[0]).length == 0)) {
6620
-
6621
- // } else {
6622
6574
  for (var i = 0, ilen = query.groups.length; i < ilen; i++) {
6623
6575
  var g = query.groups[i];
6624
6576
 
6625
6577
  if (gfn) gfn(g, query.params, alasql);
6626
6578
 
6627
6579
  if (!query.havingfn || query.havingfn(g, query.params, alasql)) {
6628
-
6629
6580
  var d = query.selectgfn(g, query.params, alasql);
6630
6581
 
6631
6582
  for (const key in query.groupColumns) {
@@ -6641,9 +6592,6 @@ function queryfn3(query) {
6641
6592
  query.data.push(d);
6642
6593
  }
6643
6594
  }
6644
- // }
6645
-
6646
- // query.groups = query.groups.filter();
6647
6595
  }
6648
6596
  // Remove distinct values
6649
6597
  doDistinct(query);
@@ -6752,9 +6700,6 @@ function queryfn3(query) {
6752
6700
  // Reduce to limit and offset
6753
6701
  doLimit(query);
6754
6702
 
6755
- // Remove Angular.js artifacts and other unnecessary columns
6756
- // Issue #25
6757
-
6758
6703
  // TODO: Check what artefacts rest from Angular.js
6759
6704
  if (typeof angular != 'undefined') {
6760
6705
  query.removeKeys.push('$$hashKey');
@@ -6796,7 +6741,6 @@ function queryfn3(query) {
6796
6741
  for (var k in r) {
6797
6742
  for (j = 0; j < query.removeLikeKeys.length; j++) {
6798
6743
  if (alasql.utils.like(query.removeLikeKeys[j], k)) {
6799
- // if(k.match(query.removeLikeKeys[j])) {
6800
6744
  delete r[k];
6801
6745
  }
6802
6746
  }
@@ -6807,7 +6751,6 @@ function queryfn3(query) {
6807
6751
  query.columns = query.columns.filter(function (column) {
6808
6752
  var found = false;
6809
6753
  removeLikeKeys.forEach(function (key) {
6810
- // if(column.columnid.match(key)) found = true;
6811
6754
  if (alasql.utils.like(key, column.columnid)) {
6812
6755
  found = true;
6813
6756
  }
@@ -6818,31 +6761,25 @@ function queryfn3(query) {
6818
6761
  }
6819
6762
 
6820
6763
  if (query.pivotfn) query.pivotfn();
6764
+
6821
6765
  if (query.unpivotfn) query.unpivotfn();
6822
6766
 
6823
6767
  if (query.intoallfn) {
6824
-
6825
- // var res = query.intoallfn(query.columns,query.cb,query.A, query.B, alasql);
6826
6768
  var res = query.intoallfn(query.columns, query.cb, query.params, query.alasql);
6827
-
6828
- // if(query.cb) res = query.cb(res,query.A, query.B);
6829
-
6830
- // debugger;
6831
6769
  return res;
6832
- } else if (query.intofn) {
6770
+ }
6771
+
6772
+ if (query.intofn) {
6833
6773
  ilen = query.data.length;
6834
6774
  for (i = 0; i < ilen; i++) {
6835
6775
  query.intofn(query.data[i], i, query.params, query.alasql);
6836
6776
  }
6837
-
6838
6777
  if (query.cb) query.cb(query.data.length, query.A, query.B);
6839
6778
  return query.data.length;
6840
- } else {
6841
-
6842
- res = query.data;
6843
- if (query.cb) res = query.cb(query.data, query.A, query.B);
6844
- return res;
6845
6779
  }
6780
+ res = query.data;
6781
+ if (query.cb) res = query.cb(query.data, query.A, query.B);
6782
+ return res;
6846
6783
  }
6847
6784
 
6848
6785
  // Limiting
@@ -6895,14 +6832,13 @@ var preIndex = function (query) {
6895
6832
  var source = query.sources[k];
6896
6833
  delete source.ix;
6897
6834
  // If there is indexation rule
6898
-
6899
6835
  if (k > 0 && source.optimization == 'ix' && source.onleftfn && source.onrightfn) {
6900
6836
  // If there is no table.indices - create it
6901
6837
  if (source.databaseid && alasql.databases[source.databaseid].tables[source.tableid]) {
6902
6838
  if (!alasql.databases[source.databaseid].tables[source.tableid].indices)
6903
6839
  query.database.tables[source.tableid].indices = {};
6904
6840
  // Check if index already exists
6905
- var ixx =
6841
+ let ixx =
6906
6842
  alasql.databases[source.databaseid].tables[source.tableid].indices[
6907
6843
  hash(source.onrightfns + '`' + source.srcwherefns)
6908
6844
  ];
@@ -6914,10 +6850,10 @@ var preIndex = function (query) {
6914
6850
  if (!source.ix) {
6915
6851
  source.ix = {};
6916
6852
  // Walking over source data
6917
- var scope = {};
6918
- var i = 0;
6919
- var ilen = source.data.length;
6920
- var dataw;
6853
+ let scope = {};
6854
+ let i = 0;
6855
+ let ilen = source.data.length;
6856
+ let dataw;
6921
6857
  // while(source.getfn i<ilen) {
6922
6858
 
6923
6859
  while (
@@ -6926,9 +6862,7 @@ var preIndex = function (query) {
6926
6862
  i < ilen
6927
6863
  ) {
6928
6864
  if (source.getfn && !source.dontcache) source.data[i] = dataw;
6929
- // scope[tableid] = dataw;
6930
6865
 
6931
- // for(var i=0, ilen=source.data.length; i<ilen; i++) {
6932
6866
  // Prepare scope for indexation
6933
6867
  scope[source.alias || source.tableid] = dataw;
6934
6868
 
@@ -6995,7 +6929,6 @@ var preIndex = function (query) {
6995
6929
  group.push(source.data[i]);
6996
6930
  i++;
6997
6931
  }
6998
- // query.database.tables[source.tableid].indices[hash(source.wxleftfns+'`'+source.onwherefns)] = source.ix;
6999
6932
  if (!alasql.databases[source.databaseid].engineid) {
7000
6933
  alasql.databases[source.databaseid].tables[source.tableid].indices[
7001
6934
  hash(source.wxleftfns + '`')
@@ -7014,7 +6947,6 @@ var preIndex = function (query) {
7014
6947
  source.data = [];
7015
6948
  }
7016
6949
  }
7017
- // }
7018
6950
  // If there is no any optimization than apply srcwhere filter
7019
6951
  } else if (source.srcwherefns && !source.dontcache) {
7020
6952
  if (source.data) {
@@ -7023,16 +6955,13 @@ var preIndex = function (query) {
7023
6955
 
7024
6956
  source.data = source.data.filter(function (r) {
7025
6957
  scope[source.alias] = r;
7026
-
7027
6958
  return source.srcwherefn(scope, query.params, alasql);
7028
6959
  });
7029
6960
 
7030
6961
  scope = {};
7031
6962
  i = 0;
7032
6963
  ilen = source.data.length;
7033
- //var dataw;
7034
- var res = [];
7035
- // while(source.getfn i<ilen) {
6964
+ let res = [];
7036
6965
 
7037
6966
  while (
7038
6967
  (dataw = source.data[i]) ||
@@ -7051,7 +6980,6 @@ var preIndex = function (query) {
7051
6980
  }
7052
6981
  // Change this to another place (this is a wrong)
7053
6982
  if (source.databaseid && alasql.databases[source.databaseid].tables[source.tableid]) {
7054
- //query.database.tables[source.tableid].dirty = false;
7055
6983
  } else {
7056
6984
  // this is a subquery?
7057
6985
  }
@@ -7062,34 +6990,24 @@ var preIndex = function (query) {
7062
6990
  //
7063
6991
 
7064
6992
  function doJoin(query, scope, h) {
7065
-
7066
6993
  // Check, if this is a last join?
7067
6994
  if (h >= query.sources.length) {
7068
6995
  // Todo: check if this runs once too many
7069
-
7070
6996
  // Then apply where and select
7071
-
7072
6997
  if (query.wherefn(scope, query.params, alasql)) {
7073
-
7074
- // var res = query.selectfn(scope, query.params, alasql);
7075
-
7076
6998
  // If there is a GROUP BY then pipe to grouping function
7077
6999
  if (query.groupfn) {
7078
7000
  query.groupfn(scope, query.params, alasql);
7079
7001
  } else {
7080
- // query.qwerty = 999;
7081
-
7082
7002
  query.data.push(query.selectfn(scope, query.params, alasql));
7083
7003
  }
7084
7004
  }
7085
7005
  } else if (query.sources[h].applyselect) {
7086
-
7087
7006
  var source = query.sources[h];
7088
7007
  source.applyselect(
7089
7008
  query.params,
7090
7009
  function (data) {
7091
7010
  if (data.length > 0) {
7092
-
7093
7011
  for (var i = 0; i < data.length; i++) {
7094
7012
  scope[source.alias] = data[i];
7095
7013
  doJoin(query, scope, h + 1);
@@ -7103,101 +7021,79 @@ function doJoin(query, scope, h) {
7103
7021
  },
7104
7022
  scope
7105
7023
  );
7106
-
7107
7024
  } else {
7108
7025
  // STEP 1
7109
7026
 
7110
- var source = query.sources[h];
7111
- var nextsource = query.sources[h + 1];
7112
-
7113
- // if(source.joinmode == "LEFT" || source.joinmode == "INNER" || source.joinmode == "RIGHT"
7114
- // || source.joinmode == "OUTER" || source.joinmode == "SEMI") {
7115
- // Todo: check if this is smart
7116
- if (true) {
7117
- //source.joinmode != "ANTI") {
7118
-
7119
- var tableid = source.alias || source.tableid;
7120
- var pass = false; // For LEFT JOIN
7121
- var data = source.data;
7122
- var opt = false;
7123
-
7124
- // Reduce data for looping if there is optimization hint
7125
- if (!source.getfn || (source.getfn && !source.dontcache)) {
7126
- if (
7127
- source.joinmode != 'RIGHT' &&
7128
- source.joinmode != 'OUTER' &&
7129
- source.joinmode != 'ANTI' &&
7130
- source.optimization == 'ix'
7131
- ) {
7132
- data = source.ix[source.onleftfn(scope, query.params, alasql)] || [];
7133
- opt = true;
7027
+ let source = query.sources[h];
7028
+ let nextsource = query.sources[h + 1];
7134
7029
 
7135
- }
7136
- }
7030
+ let tableid = source.alias || source.tableid;
7031
+ let pass = false; // For LEFT JOIN
7032
+ let data = source.data;
7033
+ let opt = false;
7137
7034
 
7138
- // Main cycle
7139
- var i = 0;
7140
- if (typeof data == 'undefined') {
7141
- throw new Error('Data source number ' + h + ' in undefined');
7035
+ // Reduce data for looping if there is optimization hint
7036
+ if (!source.getfn || (source.getfn && !source.dontcache)) {
7037
+ if (
7038
+ source.joinmode != 'RIGHT' &&
7039
+ source.joinmode != 'OUTER' &&
7040
+ source.joinmode != 'ANTI' &&
7041
+ source.optimization == 'ix'
7042
+ ) {
7043
+ data = source.ix[source.onleftfn(scope, query.params, alasql)] || [];
7044
+ opt = true;
7142
7045
  }
7143
- var ilen = data.length;
7144
- var dataw;
7145
-
7146
- while ((dataw = data[i]) || (!opt && source.getfn && (dataw = source.getfn(i))) || i < ilen) {
7147
- if (!opt && source.getfn && !source.dontcache) data[i] = dataw;
7148
-
7149
- scope[tableid] = dataw;
7150
-
7151
- // Reduce with ON and USING clause
7152
- var usingPassed = !source.onleftfn;
7153
- if (!usingPassed) {
7154
- var left = source.onleftfn(scope, query.params, alasql);
7155
- var right = source.onrightfn(scope, query.params, alasql);
7156
- if (left instanceof String || left instanceof Number) left = left.valueOf();
7157
- if (right instanceof String || right instanceof Number) right = left.valueOf();
7158
- usingPassed = left == right;
7159
- }
7160
-
7161
- if (usingPassed) {
7162
- // For all non-standard JOINs like a-b=0
7163
- if (source.onmiddlefn(scope, query.params, alasql)) {
7164
- // Recursively call new join
7165
- // if(source.joinmode == "LEFT" || source.joinmode == "INNER" || source.joinmode == "OUTER" || source.joinmode == "RIGHT" ) {
7166
- if (source.joinmode != 'SEMI' && source.joinmode != 'ANTI') {
7046
+ }
7167
7047
 
7168
- doJoin(query, scope, h + 1);
7169
- }
7048
+ // Main cycle
7049
+ let i = 0;
7050
+ if (typeof data == 'undefined') {
7051
+ throw new Error('Data source number ' + h + ' in undefined');
7052
+ }
7053
+ let ilen = data.length;
7054
+ let dataw;
7170
7055
 
7171
- // if(source.data[i].f = 200) debugger;
7056
+ while ((dataw = data[i]) || (!opt && source.getfn && (dataw = source.getfn(i))) || i < ilen) {
7057
+ if (!opt && source.getfn && !source.dontcache) data[i] = dataw;
7058
+ scope[tableid] = dataw;
7172
7059
 
7173
- // if(source.joinmode == "RIGHT" || source.joinmode == "ANTI" || source.joinmode == "OUTER") {
7174
- if (source.joinmode != 'LEFT' && source.joinmode != 'INNER') {
7175
- dataw._rightjoin = true;
7176
- }
7060
+ // Reduce with ON and USING clause
7061
+ var usingPassed = !source.onleftfn;
7062
+ if (!usingPassed) {
7063
+ var left = source.onleftfn(scope, query.params, alasql);
7064
+ var right = source.onrightfn(scope, query.params, alasql);
7065
+ if (left instanceof String || left instanceof Number) left = left.valueOf();
7066
+ if (right instanceof String || right instanceof Number) right = left.valueOf();
7067
+ usingPassed = left == right;
7068
+ }
7177
7069
 
7178
- // for LEFT JOIN
7179
- pass = true;
7070
+ if (usingPassed) {
7071
+ // For all non-standard JOINs like a-b=0
7072
+ if (source.onmiddlefn(scope, query.params, alasql)) {
7073
+ // Recursively call new join
7074
+ if (source.joinmode != 'SEMI' && source.joinmode != 'ANTI') {
7075
+ doJoin(query, scope, h + 1);
7076
+ }
7077
+ if (source.joinmode != 'LEFT' && source.joinmode != 'INNER') {
7078
+ dataw._rightjoin = true;
7180
7079
  }
7181
- }
7182
- i++;
7183
- }
7184
7080
 
7185
- // Additional join for LEFT JOINS
7186
- if (
7187
- (source.joinmode == 'LEFT' || source.joinmode == 'OUTER' || source.joinmode == 'SEMI') &&
7188
- !pass
7189
- ) {
7190
- // Clear the scope after the loop
7191
- scope[tableid] = {};
7192
- doJoin(query, scope, h + 1);
7081
+ // for LEFT JOIN
7082
+ pass = true;
7083
+ }
7193
7084
  }
7085
+ i++;
7194
7086
  }
7195
7087
 
7196
- // When there is no records
7197
- // if(data.length == 0 && query.groupfn) {
7198
- // scope[tableid] = undefined;
7199
- // doJoin(query,scope,h+1);
7200
- // }
7088
+ // Additional join for LEFT JOINS
7089
+ if (
7090
+ (source.joinmode == 'LEFT' || source.joinmode == 'OUTER' || source.joinmode == 'SEMI') &&
7091
+ !pass
7092
+ ) {
7093
+ // Clear the scope after the loop
7094
+ scope[tableid] = {};
7095
+ doJoin(query, scope, h + 1);
7096
+ }
7201
7097
 
7202
7098
  // STEP 2
7203
7099
 
@@ -7210,9 +7106,9 @@ function doJoin(query, scope, h) {
7210
7106
  ) {
7211
7107
  scope[source.alias] = {};
7212
7108
 
7213
- var j = 0;
7214
- var jlen = nextsource.data.length;
7215
- var dataw;
7109
+ let j = 0;
7110
+ let jlen = nextsource.data.length;
7111
+ let dataw;
7216
7112
 
7217
7113
  while (
7218
7114
  (dataw = nextsource.data[j]) ||
@@ -7243,7 +7139,6 @@ function doJoin(query, scope, h) {
7243
7139
  }
7244
7140
 
7245
7141
  scope[tableid] = undefined;
7246
-
7247
7142
  }
7248
7143
  }
7249
7144
 
@@ -7251,11 +7146,11 @@ function swapSources(query, h) {
7251
7146
  var source = query.sources[h];
7252
7147
  var nextsource = query.sources[h + 1];
7253
7148
 
7254
- var onleftfn = source.onleftfn;
7255
- var onleftfns = source.onleftfns;
7256
- var onrightfn = source.onrightfn;
7257
- var onrightfns = source.onrightfns;
7258
- var optimization = source.optimization;
7149
+ let onleftfn = source.onleftfn;
7150
+ let onleftfns = source.onleftfns;
7151
+ let onrightfn = source.onrightfn;
7152
+ let onrightfns = source.onrightfns;
7153
+ let optimization = source.optimization;
7259
7154
 
7260
7155
  source.onleftfn = nextsource.onrightfn;
7261
7156
  source.onleftfns = nextsource.onrightfns;
@@ -7441,7 +7336,6 @@ yy.Select = class Select {
7441
7336
  query.explain = this.explain; // Explain
7442
7337
  query.explaination = [];
7443
7338
  query.explid = 1;
7444
-
7445
7339
  query.modifier = this.modifier;
7446
7340
 
7447
7341
  query.database = db;
@@ -7528,40 +7422,22 @@ yy.Select = class Select {
7528
7422
  query.corresponding = this.corresponding; // If CORRESPONDING flag exists
7529
7423
  if (this.union) {
7530
7424
  query.unionfn = this.union.compile(databaseid);
7531
- if (this.union.order) {
7532
- query.orderfn = this.union.compileOrder(query, params);
7533
- } else {
7534
- query.orderfn = null;
7535
- }
7425
+ query.orderfn = this.union.order ? this.union.compileOrder(query, params) : null;
7536
7426
  } else if (this.unionall) {
7537
7427
  query.unionallfn = this.unionall.compile(databaseid);
7538
- if (this.unionall.order) {
7539
- query.orderfn = this.unionall.compileOrder(query, params);
7540
- } else {
7541
- query.orderfn = null;
7542
- }
7428
+ query.orderfn = this.unionall.order ? this.unionall.compileOrder(query, params) : null;
7543
7429
  } else if (this.except) {
7544
7430
  query.exceptfn = this.except.compile(databaseid);
7545
- if (this.except.order) {
7546
- query.orderfn = this.except.compileOrder(query, params);
7547
- } else {
7548
- query.orderfn = null;
7549
- }
7431
+ query.orderfn = this.except.order ? this.except.compileOrder(query, params) : null;
7550
7432
  } else if (this.intersect) {
7551
7433
  query.intersectfn = this.intersect.compile(databaseid);
7552
- if (this.intersect.order) {
7553
- query.intersectfn = this.intersect.compileOrder(query, params);
7554
- } else {
7555
- query.orderfn = null;
7556
- }
7434
+ query.orderfn = this.intersect.order ? this.intersect.compileOrder(query, params) : null;
7557
7435
  }
7558
7436
 
7559
7437
  // SELECT INTO
7560
7438
  if (this.into) {
7561
7439
  if (this.into instanceof yy.Table) {
7562
- //
7563
7440
  // Save into the table in database
7564
- //
7565
7441
  if (
7566
7442
  alasql.options.autocommit &&
7567
7443
  alasql.databases[this.into.databaseid || databaseid].engineid
@@ -7612,7 +7488,6 @@ yy.Select = class Select {
7612
7488
  qs += 'undefined, undefined,';
7613
7489
  }
7614
7490
  query.intoallfns = qs + 'this.data,columns,cb)';
7615
-
7616
7491
  } else if (this.into instanceof yy.ParamValue) {
7617
7492
  //
7618
7493
  // Save data into parameters array
@@ -7623,15 +7498,12 @@ yy.Select = class Select {
7623
7498
 
7624
7499
  if (query.intofns) {
7625
7500
  // Create intofn function
7626
-
7627
7501
  query.intofn = new Function('r,i,params,alasql', 'var y;' + query.intofns);
7628
7502
  } else if (query.intoallfns) {
7629
7503
  // Create intoallfn function
7630
-
7631
7504
  query.intoallfn = new Function('columns,cb,params,alasql', 'var y;' + query.intoallfns);
7632
7505
  }
7633
7506
  }
7634
-
7635
7507
  // Now, compile all togeather into one function with query object in scope
7636
7508
  var statement = function (params, cb, oldscope) {
7637
7509
  query.params = params;
@@ -7655,16 +7527,11 @@ yy.Select = class Select {
7655
7527
  if (cb) {
7656
7528
  cb(res2);
7657
7529
  }
7658
-
7659
7530
  return res2;
7660
7531
  });
7661
-
7662
- // if(typeof res1 != 'undefined') res1 = modify(query,res1);
7663
7532
  return res1;
7664
7533
  };
7665
7534
 
7666
- // statement.dbversion = ;
7667
-
7668
7535
  statement.query = query;
7669
7536
  return statement;
7670
7537
  }
@@ -7678,8 +7545,6 @@ yy.Select = class Select {
7678
7545
  if (!this.exists) return;
7679
7546
  query.existsfn = this.exists.map(function (ex) {
7680
7547
  var nq = ex.compile(query.database.databaseid);
7681
-
7682
- // if(!nq.query.modifier) nq.query.modifier = 'RECORDSET';
7683
7548
  nq.query.modifier = 'RECORDSET';
7684
7549
  return nq;
7685
7550
  });
@@ -7689,17 +7554,10 @@ yy.Select = class Select {
7689
7554
  if (!this.queries) return;
7690
7555
  query.queriesfn = this.queries.map(function (q) {
7691
7556
  var nq = q.compile(query.database.databaseid);
7692
-
7693
- // if(!nq.query) nq.query = {};
7694
7557
  nq.query.modifier = 'RECORDSET';
7695
- // if(!nq.query.modifier) nq.query.modifier = 'RECORDSET';
7696
7558
  return nq;
7697
7559
  });
7698
7560
  }
7699
-
7700
- // exec(databaseid) {
7701
- // throw new Error('Select statement should be precompiled');
7702
- // }
7703
7561
  };
7704
7562
 
7705
7563
  /**
@@ -7742,89 +7600,52 @@ function modify(query, res) {
7742
7600
  }
7743
7601
  }
7744
7602
 
7745
- if (modifier === 'VALUE') {
7603
+ switch (modifier) {
7604
+ case 'VALUE':
7605
+ if (res.length === 0) return undefined;
7606
+ const keyValue = columns && columns.length > 0 ? columns[0].columnid : Object.keys(res[0])[0];
7607
+ return res[0][keyValue];
7746
7608
 
7747
- if (res.length > 0) {
7748
- var key;
7749
- if (columns && columns.length > 0) {
7750
- key = columns[0].columnid;
7751
- } else {
7752
- key = Object.keys(res[0])[0];
7753
- }
7754
- res = res[0][key];
7755
- } else {
7756
- res = undefined;
7757
- }
7758
- } else if (modifier === 'ROW') {
7759
- if (res.length > 0) {
7760
- var key;
7761
- var a = [];
7762
- for (var key in res[0]) {
7763
- a.push(res[0][key]);
7764
- }
7765
- res = a;
7766
- } else {
7767
- res = undefined;
7768
- }
7769
- } else if (modifier === 'COLUMN') {
7770
- var ar = [];
7771
- if (res.length > 0) {
7772
- var key;
7609
+ case 'ROW':
7610
+ if (res.length === 0) return undefined;
7611
+ return Object.values(res[0]);
7612
+
7613
+ case 'COLUMN':
7614
+ if (res.length === 0) return [];
7615
+
7616
+ let key;
7773
7617
  if (columns && columns.length > 0) {
7774
7618
  key = columns[0].columnid;
7775
7619
  } else {
7776
7620
  key = Object.keys(res[0])[0];
7777
7621
  }
7778
7622
 
7623
+ let ar = [];
7779
7624
  for (var i = 0, ilen = res.length; i < ilen; i++) {
7780
7625
  ar.push(res[i][key]);
7781
7626
  }
7782
- }
7783
- res = ar;
7784
- } else if (modifier === 'MATRIX') {
7785
- // Returns square matrix of rows
7786
- var ar = [];
7787
- for (var i = 0; i < res.length; i++) {
7788
- var a = [];
7789
- var r = res[i];
7790
- for (var j = 0; j < columns.length; j++) {
7791
- a.push(r[columns[j].columnid]);
7792
- }
7793
- ar.push(a);
7794
- }
7795
- res = ar;
7796
- } else if (modifier === 'INDEX') {
7797
- var ar = {};
7798
- var key, val;
7799
- if (columns && columns.length > 0) {
7800
- key = columns[0].columnid;
7801
- val = columns[1].columnid;
7802
- } else {
7803
- var okeys = Object.keys(res[0]);
7804
- key = okeys[0];
7805
- val = okeys[1];
7806
- }
7807
- for (var i = 0, ilen = res.length; i < ilen; i++) {
7808
- ar[res[i][key]] = res[i][val];
7809
- }
7810
- res = ar;
7811
- // res = arrayOfArrays(res);
7812
- } else if (modifier === 'RECORDSET') {
7813
- res = new alasql.Recordset({columns: columns, data: res});
7814
- // res = arrayOfArrays(res);
7815
- } else if (modifier === 'TEXTSTRING') {
7816
- var key;
7817
- if (columns && columns.length > 0) {
7818
- key = columns[0].columnid;
7819
- } else {
7820
- key = Object.keys(res[0])[0];
7821
- }
7822
7627
 
7823
- for (var i = 0, ilen = res.length; i < ilen; i++) {
7824
- res[i] = res[i][key];
7825
- }
7826
- res = res.join('\n');
7827
- // res = arrayOfArrays(res);
7628
+ return ar;
7629
+
7630
+ case 'MATRIX':
7631
+ if (res.length === 0) return undefined;
7632
+ return res.map(row => columns.map(col => row[col.columnid]));
7633
+
7634
+ case 'INDEX':
7635
+ if (res.length === 0) return undefined;
7636
+ const keyIndex = columns && columns.length > 0 ? columns[0].columnid : Object.keys(res[0])[0];
7637
+ const valIndex = columns && columns.length > 1 ? columns[1].columnid : Object.keys(res[0])[1];
7638
+ return res.reduce((acc, row) => ({...acc, [row[keyIndex]]: row[valIndex]}), {});
7639
+
7640
+ case 'RECORDSET':
7641
+ // Assuming alasql.Recordset is available in the scope
7642
+ return new alasql.Recordset({columns: columns, data: res});
7643
+
7644
+ case 'TEXTSTRING':
7645
+ if (res.length === 0) return undefined;
7646
+ const keyTextString =
7647
+ columns && columns.length > 0 ? columns[0].columnid : Object.keys(res[0])[0];
7648
+ return res.map(row => row[keyTextString]).join('\n');
7828
7649
  }
7829
7650
  return res;
7830
7651
  }
@@ -7850,8 +7671,7 @@ yy.ExistsValue = class ExistsValue {
7850
7671
  }
7851
7672
 
7852
7673
  toJS(context, tableid, defcols) {
7853
-
7854
- return 'this.existsfn[' + this.existsidx + '](params,null,' + context + ').data.length';
7674
+ return `this.existsfn[${this.existsidx}](params, null, ${context}).data.length`;
7855
7675
  }
7856
7676
  };
7857
7677
 
@@ -7859,27 +7679,18 @@ yy.ExistsValue = class ExistsValue {
7859
7679
  // Prepare subqueries and exists
7860
7680
  //
7861
7681
  alasql.precompile = function (statement, databaseid, params) {
7862
-
7863
7682
  if (!statement) return;
7864
7683
  statement.params = params;
7865
7684
  if (statement.queries) {
7866
-
7867
7685
  statement.queriesfn = statement.queries.map(function (q) {
7868
7686
  var nq = q.compile(databaseid || statement.database.databaseid);
7869
-
7870
- // nq.query.modifier = undefined;
7871
- // if(!nq.query.modifier) nq.query.modifier = 'RECORDSET';
7872
7687
  nq.query.modifier = 'RECORDSET';
7873
7688
  return nq;
7874
7689
  });
7875
7690
  }
7876
7691
  if (statement.exists) {
7877
-
7878
7692
  statement.existsfn = statement.exists.map(function (ex) {
7879
7693
  var nq = ex.compile(databaseid || statement.database.databaseid);
7880
-
7881
- // if(!nq.query.modifier) nq.query.modifier = 'RECORDSET';
7882
- // if(!nq.query.modifier) nq.query.modifier = 'ARRAY';
7883
7694
  nq.query.modifier = 'RECORDSET';
7884
7695
  return nq;
7885
7696
  });
@@ -7896,24 +7707,15 @@ alasql.precompile = function (statement, databaseid, params) {
7896
7707
  /* global yy, alasql, Mongo, returnTrue */
7897
7708
 
7898
7709
  yy.Select.prototype.compileFrom = function (query) {
7899
-
7900
- var self = this;
7710
+ const self = this;
7901
7711
  query.sources = [];
7902
- // var tableid = this.from[0].tableid;
7903
- // var as = '';
7904
- // if(self.from[0].as) as = this.from[0].as;
7905
-
7906
7712
  query.aliases = {};
7907
- if (!self.from) return;
7908
-
7909
- self.from.forEach(function (tq) {
7910
-
7911
- var ps = '';
7912
7713
 
7913
- var alias = tq.as || tq.tableid;
7714
+ if (!self.from) return;
7914
7715
 
7716
+ self.from.forEach(tq => {
7717
+ const alias = tq.as || tq.tableid;
7915
7718
  if (tq instanceof yy.Table) {
7916
-
7917
7719
  query.aliases[alias] = {
7918
7720
  tableid: tq.tableid,
7919
7721
  databaseid: tq.databaseid || query.database.databaseid,
@@ -7939,7 +7741,7 @@ yy.Select.prototype.compileFrom = function (query) {
7939
7741
  throw new Error('Wrong table at FROM');
7940
7742
  }
7941
7743
 
7942
- var source = {
7744
+ const source = {
7943
7745
  alias: alias,
7944
7746
  databaseid: tq.databaseid || query.database.databaseid,
7945
7747
  tableid: tq.tableid,
@@ -7947,21 +7749,16 @@ yy.Select.prototype.compileFrom = function (query) {
7947
7749
  onmiddlefn: returnTrue,
7948
7750
  srcwherefns: '', // for optimization
7949
7751
  srcwherefn: returnTrue,
7950
- // columns: []
7951
7752
  };
7952
7753
 
7953
7754
  if (tq instanceof yy.Table) {
7954
- // Get columns from table
7955
7755
  source.columns = alasql.databases[source.databaseid].tables[source.tableid].columns;
7956
-
7957
7756
  if (
7958
7757
  alasql.options.autocommit &&
7959
7758
  alasql.databases[source.databaseid].engineid &&
7960
7759
  !alasql.databases[source.databaseid].tables[source.tableid].view
7961
7760
  ) {
7962
-
7963
- // TODO -- make view for external engine
7964
- source.datafn = function (query, params, cb, idx, alasql) {
7761
+ source.datafn = (query, params, cb, idx, alasql) => {
7965
7762
  return alasql.engines[alasql.databases[source.databaseid].engineid].fromTable(
7966
7763
  source.databaseid,
7967
7764
  source.tableid,
@@ -7971,87 +7768,66 @@ yy.Select.prototype.compileFrom = function (query) {
7971
7768
  );
7972
7769
  };
7973
7770
  } else if (alasql.databases[source.databaseid].tables[source.tableid].view) {
7974
- source.datafn = function (query, params, cb, idx, alasql) {
7975
- var res = alasql.databases[source.databaseid].tables[source.tableid].select(params);
7771
+ source.datafn = (query, params, cb, idx, alasql) => {
7772
+ let res = alasql.databases[source.databaseid].tables[source.tableid].select(params);
7976
7773
  if (cb) res = cb(res, idx, query);
7977
7774
  return res;
7978
7775
  };
7979
7776
  } else {
7980
-
7981
- source.datafn = function (query, params, cb, idx, alasql) {
7982
- /*
7983
-
7984
- */
7985
- var res = alasql.databases[source.databaseid].tables[source.tableid].data;
7986
-
7777
+ source.datafn = (query, params, cb, idx, alasql) => {
7778
+ let res = alasql.databases[source.databaseid].tables[source.tableid].data;
7987
7779
  if (cb) res = cb(res, idx, query);
7988
-
7989
7780
  return res;
7990
- // return alasql.databases[source.databaseid].tables[source.tableid].data;
7991
7781
  };
7992
7782
  }
7993
7783
  } else if (tq instanceof yy.Select) {
7994
7784
  source.subquery = tq.compile(query.database.databaseid);
7995
7785
  if (typeof source.subquery.query.modifier === 'undefined') {
7996
- source.subquery.query.modifier = 'RECORDSET'; // Subqueries always return recordsets
7786
+ source.subquery.query.modifier = 'RECORDSET';
7997
7787
  }
7998
7788
  source.columns = source.subquery.query.columns;
7999
7789
 
8000
- // tq.columns;
8001
-
8002
- source.datafn = function (query, params, cb, idx, alasql) {
8003
- // return source.subquery(query.params, cb, idx, query);
8004
- var res;
8005
- source.subquery(query.params, function (data) {
7790
+ source.datafn = (query, params, cb, idx, alasql) => {
7791
+ let res;
7792
+ source.subquery(query.params, data => {
8006
7793
  res = data.data;
8007
7794
  if (cb) res = cb(res, idx, query);
8008
- return res;
8009
- // return data.data;
8010
7795
  });
8011
-
8012
7796
  return res;
8013
7797
  };
8014
7798
  } else if (tq instanceof yy.Search) {
8015
7799
  source.subsearch = tq;
8016
7800
  source.columns = [];
8017
-
8018
- source.datafn = function (query, params, cb, idx, alasql) {
8019
- // return source.subquery(query.params, cb, idx, query);
8020
- var res;
8021
- source.subsearch.execute(query.database.databaseid, query.params, function (data) {
7801
+ source.datafn = (query, params, cb, idx, alasql) => {
7802
+ let res;
7803
+ source.subsearch.execute(query.database.databaseid, query.params, data => {
8022
7804
  res = data;
8023
7805
  if (cb) res = cb(res, idx, query);
8024
- return res;
8025
- // return data.data;
8026
7806
  });
8027
-
8028
7807
  return res;
8029
7808
  };
8030
7809
  } else if (tq instanceof yy.ParamValue) {
8031
- ps = "var res = alasql.prepareFromData(params['" + tq.param + "']";
8032
-
7810
+ let ps = `var res = alasql.prepareFromData(params['${tq.param}']`;
8033
7811
  if (tq.array) ps += ',true';
8034
7812
  ps += ');if(cb)res=cb(res,idx,query);return res';
8035
7813
  source.datafn = new Function('query,params,cb,idx,alasql', ps);
8036
7814
  } else if (tq.inserted) {
8037
- ps = 'var res = alasql.prepareFromData(alasql.inserted';
7815
+ let ps = 'var res = alasql.prepareFromData(alasql.inserted';
8038
7816
  if (tq.array) ps += ',true';
8039
7817
  ps += ');if(cb)res=cb(res,idx,query);return res';
8040
7818
  source.datafn = new Function('query,params,cb,idx,alasql', ps);
8041
7819
  } else if (tq instanceof yy.Json) {
8042
- ps = 'var res = alasql.prepareFromData(' + tq.toJS();
8043
-
7820
+ let ps = 'var res = alasql.prepareFromData(' + tq.toJS();
8044
7821
  if (tq.array) ps += ',true';
8045
7822
  ps += ');if(cb)res=cb(res,idx,query);return res';
8046
7823
  source.datafn = new Function('query,params,cb,idx,alasql', ps);
8047
7824
  } else if (tq instanceof yy.VarValue) {
8048
- ps = "var res = alasql.prepareFromData(alasql.vars['" + tq.variable + "']";
8049
-
7825
+ let ps = `var res = alasql.prepareFromData(alasql.vars['${tq.variable}']`;
8050
7826
  if (tq.array) ps += ',true';
8051
7827
  ps += ');if(cb)res=cb(res,idx,query);return res';
8052
7828
  source.datafn = new Function('query,params,cb,idx,alasql', ps);
8053
7829
  } else if (tq instanceof yy.FuncValue) {
8054
- ps = 'var res=alasql.from[' + JSON.stringify(tq.funcid.toUpperCase()) + '](';
7830
+ let ps = 'var res=alasql.from[' + JSON.stringify(tq.funcid.toUpperCase()) + '](';
8055
7831
 
8056
7832
  if (tq.args && tq.args.length > 0) {
8057
7833
  if (tq.args[0]) {
@@ -8059,6 +7835,7 @@ yy.Select.prototype.compileFrom = function (query) {
8059
7835
  } else {
8060
7836
  ps += 'null,';
8061
7837
  }
7838
+
8062
7839
  if (tq.args[1]) {
8063
7840
  ps += tq.args[1].toJS('query.oldscope') + ',';
8064
7841
  } else {
@@ -8067,46 +7844,32 @@ yy.Select.prototype.compileFrom = function (query) {
8067
7844
  } else {
8068
7845
  ps += 'null,null,';
8069
7846
  }
8070
- ps += 'cb,idx,query';
8071
- ps += ');/*if(cb)res=cb(res,idx,query);*/return res';
8072
-
8073
- source.datafn = new Function('query, params, cb, idx, alasql', ps);
7847
+ ps += 'cb,idx,query); return res';
7848
+ source.datafn = new Function('query,params,cb,idx,alasql', ps);
8074
7849
  } else if (tq instanceof yy.FromData) {
8075
- source.datafn = function (query, params, cb, idx, alasql) {
8076
- var res = tq.data;
7850
+ source.datafn = (query, params, cb, idx, alasql) => {
7851
+ let res = tq.data;
8077
7852
  if (cb) res = cb(res, idx, query);
8078
7853
  return res;
8079
7854
  };
8080
7855
  } else {
8081
7856
  throw new Error('Wrong table at FROM');
8082
7857
  }
8083
- // source.data = alasql.databases[source.databaseid].tables[source.tableid].data;
8084
7858
  query.sources.push(source);
8085
7859
  });
8086
- // TODO Add joins
8087
7860
  query.defaultTableid = query.sources[0].alias;
8088
-
8089
7861
  };
8090
7862
 
8091
7863
  alasql.prepareFromData = function (data, array) {
8092
-
8093
- var i, ilen;
8094
- var res = data;
7864
+ let res = data;
8095
7865
  if (typeof data === 'string') {
8096
7866
  res = data.split(/\r?\n/);
8097
7867
  if (array) {
8098
- for (i = 0, ilen = res.length; i < ilen; i++) {
8099
- res[i] = [res[i]];
8100
- }
7868
+ res = res.map(item => [item]);
8101
7869
  }
8102
7870
  } else if (array) {
8103
- res = [];
8104
- for (i = 0, ilen = data.length; i < ilen; i++) {
8105
- res.push([data[i]]);
8106
- }
8107
-
7871
+ res = data.map(item => [item]);
8108
7872
  } else if (typeof data === 'object' && !Array.isArray(data)) {
8109
- // } else if(typeof data == 'object' && !(typeof data.length == 'undefined')) {
8110
7873
  if (
8111
7874
  typeof Mongo !== 'undefined' &&
8112
7875
  typeof Mongo.Collection !== 'undefined' &&
@@ -8115,13 +7878,11 @@ alasql.prepareFromData = function (data, array) {
8115
7878
  res = data.find().fetch();
8116
7879
  } else {
8117
7880
  res = [];
8118
- for (var key in data) {
7881
+ for (const key in data) {
8119
7882
  if (data.hasOwnProperty(key)) res.push([key, data[key]]);
8120
7883
  }
8121
7884
  }
8122
-
8123
7885
  }
8124
-
8125
7886
  return res;
8126
7887
  };
8127
7888
  /*
@@ -8136,15 +7897,12 @@ alasql.prepareFromData = function (data, array) {
8136
7897
 
8137
7898
  /* global yy, alasql, returnTrue, arrayIntersect */
8138
7899
 
8139
- // Compile JOIN caluese
8140
7900
  yy.Select.prototype.compileJoins = function (query) {
7901
+ const self = this;
8141
7902
 
8142
- // debugger;
8143
- var self = this;
8144
-
8145
- this.joins.forEach(function (jn) {
7903
+ this.joins.forEach(jn => {
7904
+ let tq, ps, source;
8146
7905
  // Test CROSS-JOIN
8147
- var tq, ps, source;
8148
7906
  if (jn.joinmode === 'CROSS') {
8149
7907
  if (jn.using || jn.on) {
8150
7908
  throw new Error('CROSS JOIN cannot have USING or ON clauses');
@@ -8154,7 +7912,6 @@ yy.Select.prototype.compileJoins = function (query) {
8154
7912
  }
8155
7913
 
8156
7914
  if (jn instanceof yy.Apply) {
8157
-
8158
7915
  source = {
8159
7916
  alias: jn.as,
8160
7917
  applymode: jn.applymode,
@@ -8167,7 +7924,7 @@ yy.Select.prototype.compileJoins = function (query) {
8167
7924
  source.columns = source.applyselect.query.columns;
8168
7925
 
8169
7926
  source.datafn = function (query, params, cb, idx, alasql) {
8170
- var res;
7927
+ let res;
8171
7928
  if (cb) res = cb(res, idx, query);
8172
7929
  return res;
8173
7930
  };
@@ -8189,7 +7946,6 @@ yy.Select.prototype.compileJoins = function (query) {
8189
7946
  srcwherefn: returnTrue,
8190
7947
  columns: [],
8191
7948
  };
8192
- //
8193
7949
 
8194
7950
  if (!alasql.databases[source.databaseid].tables[source.tableid]) {
8195
7951
  throw new Error(
@@ -8199,11 +7955,8 @@ yy.Select.prototype.compileJoins = function (query) {
8199
7955
 
8200
7956
  source.columns = alasql.databases[source.databaseid].tables[source.tableid].columns;
8201
7957
 
8202
- // source.data = query.database.tables[source.tableid].data;
8203
7958
  if (alasql.options.autocommit && alasql.databases[source.databaseid].engineid) {
8204
-
8205
7959
  source.datafn = function (query, params, cb, idx, alasql) {
8206
-
8207
7960
  return alasql.engines[alasql.databases[source.databaseid].engineid].fromTable(
8208
7961
  source.databaseid,
8209
7962
  source.tableid,
@@ -8214,31 +7967,26 @@ yy.Select.prototype.compileJoins = function (query) {
8214
7967
  };
8215
7968
  } else if (alasql.databases[source.databaseid].tables[source.tableid].view) {
8216
7969
  source.datafn = function (query, params, cb, idx, alasql) {
8217
- var res = alasql.databases[source.databaseid].tables[source.tableid].select(params);
7970
+ let res = alasql.databases[source.databaseid].tables[source.tableid].select(params);
8218
7971
  if (cb) res = cb(res, idx, query);
8219
7972
  return res;
8220
7973
  };
8221
7974
  } else {
8222
7975
  source.datafn = function (query, params, cb, idx, alasql) {
8223
- var res = alasql.databases[source.databaseid].tables[source.tableid].data;
7976
+ let res = alasql.databases[source.databaseid].tables[source.tableid].data;
8224
7977
  if (cb) res = cb(res, idx, query);
8225
7978
  return res;
8226
7979
  };
8227
7980
  }
8228
7981
 
8229
- // var alias = jn.as || tq.tableid;
8230
- // if(tq) {
8231
7982
  query.aliases[source.alias] = {
8232
7983
  tableid: tq.tableid,
8233
7984
  databaseid: tq.databaseid || query.database.databaseid,
8234
7985
  };
8235
- // }
8236
7986
  } else if (jn.select) {
8237
7987
  tq = jn.select;
8238
7988
  source = {
8239
7989
  alias: jn.as,
8240
- // databaseid: jn.databaseid || query.database.databaseid,
8241
- // tableid: tq.tableid,
8242
7990
  joinmode: jn.joinmode,
8243
7991
  onmiddlefn: returnTrue,
8244
7992
  srcwherefns: '', // for optimization
@@ -8252,121 +8000,92 @@ yy.Select.prototype.compileJoins = function (query) {
8252
8000
  }
8253
8001
  source.columns = source.subquery.query.columns;
8254
8002
 
8255
- // if(jn instanceof yy.Apply) {
8256
8003
  source.datafn = function (query, params, cb, idx, alasql) {
8257
- // return cb(null,idx,alasql);
8258
8004
  source.data = source.subquery(query.params, null, cb, idx).data;
8259
- // var res = alasql.prepareFromData(params[idx]);
8260
- var res = source.data;
8005
+ let res = source.data;
8261
8006
  // Propogate subquery result
8262
8007
  if (cb) res = cb(res, idx, query);
8263
8008
  return res;
8264
8009
  };
8265
- // } else {
8266
- // source.datafn = function(query, params, cb, idx, alasql) {
8267
- // return source.subquery(query.params, null, cb, idx);
8268
- // }
8269
- // }
8270
8010
  query.aliases[source.alias] = {type: 'subquery'};
8271
8011
  } else if (jn.param) {
8272
8012
  source = {
8273
8013
  alias: jn.as,
8274
- // databaseid: jn.databaseid || query.database.databaseid,
8275
- // tableid: tq.tableid,
8276
8014
  joinmode: jn.joinmode,
8277
8015
  onmiddlefn: returnTrue,
8278
8016
  srcwherefns: '', // for optimization
8279
8017
  srcwherefn: returnTrue,
8280
8018
  };
8281
- // source.data = ;
8282
- var jnparam = jn.param.param;
8283
-
8284
- ps = "var res=alasql.prepareFromData(params['" + jnparam + "']";
8019
+ const jnparam = jn.param.param;
8020
+ ps = "let res=alasql.prepareFromData(params['" + jnparam + "']";
8285
8021
  if (jn.array) ps += ',true';
8286
- ps += ');if(cb)res=cb(res, idx, query);return res';
8022
+ ps += '); if(cb) res=cb(res, idx, query); return res';
8287
8023
 
8288
8024
  source.datafn = new Function('query,params,cb,idx, alasql', ps);
8289
8025
  query.aliases[source.alias] = {type: 'paramvalue'};
8290
8026
  } else if (jn.variable) {
8291
8027
  source = {
8292
8028
  alias: jn.as,
8293
- // databaseid: jn.databaseid || query.database.databaseid,
8294
- // tableid: tq.tableid,
8295
8029
  joinmode: jn.joinmode,
8296
8030
  onmiddlefn: returnTrue,
8297
8031
  srcwherefns: '', // for optimization
8298
8032
  srcwherefn: returnTrue,
8299
8033
  };
8300
- // source.data = ;
8301
- // var jnparam = jn.param.param;
8302
-
8303
- ps = "var res=alasql.prepareFromData(alasql.vars['" + jn.variable + "']";
8304
- if (jn.array) ps += ',true';
8305
- ps += ');if(cb)res=cb(res, idx, query);return res';
8034
+ ps = "let res=alasql.prepareFromData(alasql.vars['" + jn.variable + "']";
8035
+ if (jn.array) ps += ', true';
8036
+ ps += '); if(cb)res=cb(res, idx, query);return res';
8306
8037
 
8307
8038
  source.datafn = new Function('query,params,cb,idx, alasql', ps);
8308
8039
  query.aliases[source.alias] = {type: 'varvalue'};
8309
8040
  } else if (jn.func) {
8310
8041
  source = {
8311
8042
  alias: jn.as,
8312
- // databaseid: jn.databaseid || query.database.databaseid,
8313
- // tableid: tq.tableid,
8314
8043
  joinmode: jn.joinmode,
8315
8044
  onmiddlefn: returnTrue,
8316
8045
  srcwherefns: '', // for optimization
8317
8046
  srcwherefn: returnTrue,
8318
8047
  };
8319
- // source.data = ;
8320
8048
 
8321
- var s = 'var res=alasql.from[' + JSON.stringify(jn.func.funcid.toUpperCase()) + '](';
8049
+ let s = 'let res=alasql.from[' + JSON.stringify(jn.func.funcid.toUpperCase()) + '](';
8322
8050
 
8323
- var args = jn.func.args;
8051
+ const args = jn.func.args;
8324
8052
  if (args && args.length > 0) {
8325
8053
  if (args[0]) {
8326
- s += args[0].toJS('query.oldscope') + ',';
8054
+ s += args[0].toJS('query.oldscope') + ', ';
8327
8055
  } else {
8328
- s += 'null,';
8056
+ s += 'null, ';
8329
8057
  }
8330
8058
  if (args[1]) {
8331
- s += args[1].toJS('query.oldscope') + ',';
8059
+ s += args[1].toJS('query.oldscope') + ', ';
8332
8060
  } else {
8333
- s += 'null,';
8061
+ s += 'null, ';
8334
8062
  }
8335
8063
  } else {
8336
- s += 'null,null,';
8064
+ s += 'null, null, ';
8337
8065
  }
8338
- s += 'cb,idx,query';
8339
- s += ');/*if(cb)res=cb(res,idx,query);*/return res';
8340
-
8066
+ s += 'cb, idx, query); return res';
8341
8067
  source.datafn = new Function('query, params, cb, idx, alasql', s);
8342
8068
 
8343
8069
  query.aliases[source.alias] = {type: 'funcvalue'};
8344
8070
  }
8345
8071
 
8346
- var alias = source.alias;
8072
+ const alias = source.alias;
8347
8073
 
8348
8074
  // Test NATURAL-JOIN
8349
8075
  if (jn.natural) {
8350
8076
  if (jn.using || jn.on) {
8351
8077
  throw new Error('NATURAL JOIN cannot have USING or ON clauses');
8352
8078
  } else {
8353
- // source.joinmode == "INNER";
8079
+ // source.joinmode == "INNER";
8354
8080
  if (query.sources.length > 0) {
8355
- var prevSource = query.sources[query.sources.length - 1];
8356
- var prevTable = alasql.databases[prevSource.databaseid].tables[prevSource.tableid];
8357
- var table = alasql.databases[source.databaseid].tables[source.tableid];
8081
+ const prevSource = query.sources[query.sources.length - 1];
8082
+ const prevTable = alasql.databases[prevSource.databaseid].tables[prevSource.tableid];
8083
+ const table = alasql.databases[source.databaseid].tables[source.tableid];
8358
8084
 
8359
8085
  if (prevTable && table) {
8360
- var c1 = prevTable.columns.map(function (col) {
8361
- return col.columnid;
8362
- });
8363
- var c2 = table.columns.map(function (col) {
8364
- return col.columnid;
8365
- });
8366
- jn.using = arrayIntersect(c1, c2).map(function (colid) {
8367
- return {columnid: colid};
8368
- });
8369
-
8086
+ const c1 = prevTable.columns.map(col => col.columnid);
8087
+ const c2 = table.columns.map(col => col.columnid);
8088
+ jn.using = arrayIntersect(c1, c2).map(colid => ({columnid: colid}));
8370
8089
  } else {
8371
8090
  throw new Error(
8372
8091
  'In this version of Alasql NATURAL JOIN ' +
@@ -8378,45 +8097,31 @@ yy.Select.prototype.compileJoins = function (query) {
8378
8097
  }
8379
8098
 
8380
8099
  if (jn.using) {
8381
- prevSource = query.sources[query.sources.length - 1];
8382
-
8100
+ const prevSource = query.sources[query.sources.length - 1];
8383
8101
  source.onleftfns = jn.using
8384
- .map(function (col) {
8385
-
8386
- return "p['" + (prevSource.alias || prevSource.tableid) + "']['" + col.columnid + "']";
8387
- })
8102
+ .map(col => "p['" + (prevSource.alias || prevSource.tableid) + "']['" + col.columnid + "']")
8388
8103
  .join('+"`"+');
8389
8104
 
8390
- source.onleftfn = new Function('p,params,alasql', 'var y;return ' + source.onleftfns);
8105
+ source.onleftfn = new Function('p,params,alasql', 'let y;return ' + source.onleftfns);
8391
8106
 
8392
8107
  source.onrightfns = jn.using
8393
- .map(function (col) {
8394
- return "p['" + (source.alias || source.tableid) + "']['" + col.columnid + "']";
8395
- })
8108
+ .map(col => "p['" + (source.alias || source.tableid) + "']['" + col.columnid + "']")
8396
8109
  .join('+"`"+');
8397
- source.onrightfn = new Function('p,params,alasql', 'var y;return ' + source.onrightfns);
8110
+ source.onrightfn = new Function('p,params,alasql', 'let y;return ' + source.onrightfns);
8398
8111
  source.optimization = 'ix';
8399
-
8400
8112
  } else if (jn.on) {
8401
-
8402
8113
  if (jn.on instanceof yy.Op && jn.on.op === '=' && !jn.on.allsome) {
8403
-
8404
8114
  source.optimization = 'ix';
8405
-
8406
- var lefts = '';
8407
- var rights = '';
8408
- var middles = '';
8409
- var middlef = false;
8115
+ let lefts = '';
8116
+ let rights = '';
8117
+ let middles = '';
8118
+ let middlef = false;
8410
8119
  // Test right and left sides
8411
- var ls = jn.on.left.toJS('p', query.defaultTableid, query.defcols);
8412
- var rs = jn.on.right.toJS('p', query.defaultTableid, query.defcols);
8120
+ const ls = jn.on.left.toJS('p', query.defaultTableid, query.defcols);
8121
+ const rs = jn.on.right.toJS('p', query.defaultTableid, query.defcols);
8413
8122
 
8414
8123
  if (ls.indexOf("p['" + alias + "']") > -1 && !(rs.indexOf("p['" + alias + "']") > -1)) {
8415
- if (
8416
- (ls.match(/p\['.*?'\]/g) || []).every(function (s) {
8417
- return s === "p['" + alias + "']";
8418
- })
8419
- ) {
8124
+ if ((ls.match(/p\['.*?'\]/g) || []).every(s => s === "p['" + alias + "']")) {
8420
8125
  rights = ls;
8421
8126
  } else {
8422
8127
  middlef = true;
@@ -8425,11 +8130,7 @@ yy.Select.prototype.compileJoins = function (query) {
8425
8130
  !(ls.indexOf("p['" + alias + "']") > -1) &&
8426
8131
  rs.indexOf("p['" + alias + "']") > -1
8427
8132
  ) {
8428
- if (
8429
- (rs.match(/p\['.*?'\]/g) || []).every(function (s) {
8430
- return s === "p['" + alias + "']";
8431
- })
8432
- ) {
8133
+ if ((rs.match(/p\['.*?'\]/g) || []).every(s => s === "p['" + alias + "']")) {
8433
8134
  lefts = ls;
8434
8135
  } else {
8435
8136
  middlef = true;
@@ -8439,11 +8140,7 @@ yy.Select.prototype.compileJoins = function (query) {
8439
8140
  }
8440
8141
 
8441
8142
  if (rs.indexOf("p['" + alias + "']") > -1 && !(ls.indexOf("p['" + alias + "']") > -1)) {
8442
- if (
8443
- (rs.match(/p\['.*?'\]/g) || []).every(function (s) {
8444
- return s === "p['" + alias + "']";
8445
- })
8446
- ) {
8143
+ if ((rs.match(/p\['.*?'\]/g) || []).every(s => s === "p['" + alias + "']")) {
8447
8144
  rights = rs;
8448
8145
  } else {
8449
8146
  middlef = true;
@@ -8452,11 +8149,7 @@ yy.Select.prototype.compileJoins = function (query) {
8452
8149
  !(rs.indexOf("p['" + alias + "']") > -1) &&
8453
8150
  ls.indexOf("p['" + alias + "']") > -1
8454
8151
  ) {
8455
- if (
8456
- (ls.match(/p\['.*?'\]/g) || []).every(function (s) {
8457
- return s === "p['" + alias + "']";
8458
- })
8459
- ) {
8152
+ if ((ls.match(/p\['.*?'\]/g) || []).every(s => s === "p['" + alias + "']")) {
8460
8153
  lefts = rs;
8461
8154
  } else {
8462
8155
  middlef = true;
@@ -8466,47 +8159,31 @@ yy.Select.prototype.compileJoins = function (query) {
8466
8159
  }
8467
8160
 
8468
8161
  if (middlef) {
8469
- // middles = jn.on.toJS('p',query.defaultTableid);
8470
- // } else {
8471
8162
  rights = '';
8472
8163
  lefts = '';
8473
8164
  middles = jn.on.toJS('p', query.defaultTableid, query.defcols);
8474
8165
  source.optimization = 'no';
8475
- // What to here?
8476
8166
  }
8477
8167
 
8478
8168
  source.onleftfns = lefts;
8479
8169
  source.onrightfns = rights;
8480
8170
  source.onmiddlefns = middles || 'true';
8481
8171
 
8482
- source.onleftfn = new Function('p,params,alasql', 'var y;return ' + source.onleftfns);
8483
- source.onrightfn = new Function('p,params,alasql', 'var y;return ' + source.onrightfns);
8484
- source.onmiddlefn = new Function('p,params,alasql', 'var y;return ' + source.onmiddlefns);
8485
-
8486
- // } else if(jn.on instanceof yy.Op && jn.on.op == 'AND') {
8487
-
8172
+ source.onleftfn = new Function('p,params,alasql', 'let y;return ' + source.onleftfns);
8173
+ source.onrightfn = new Function('p,params,alasql', 'let y;return ' + source.onrightfns);
8174
+ source.onmiddlefn = new Function('p,params,alasql', 'let y;return ' + source.onmiddlefns);
8488
8175
  } else {
8489
-
8490
8176
  source.optimization = 'no';
8491
- // source.onleftfn = returnTrue;
8492
- // source.onleftfns = "true";
8493
8177
  source.onmiddlefns = jn.on.toJS('p', query.defaultTableid, query.defcols);
8494
8178
  source.onmiddlefn = new Function(
8495
8179
  'p,params,alasql',
8496
- 'var y;return ' + jn.on.toJS('p', query.defaultTableid, query.defcols)
8180
+ 'let y;return ' + jn.on.toJS('p', query.defaultTableid, query.defcols)
8497
8181
  );
8498
8182
  }
8499
-
8500
- // Optimization function
8501
8183
  }
8502
8184
 
8503
- // source.data = alasql.databases[source.databaseid].tables[source.tableid].data;
8504
-
8505
- // TODO SubQueries
8506
-
8507
8185
  query.sources.push(source);
8508
8186
  });
8509
-
8510
8187
  };
8511
8188
  yy.Select.prototype.compileWhere = function (query) {
8512
8189
  if (this.where) {
@@ -8628,15 +8305,10 @@ yy.Select.prototype.compileGroup = function (query) {
8628
8305
  var tableid = '';
8629
8306
  }
8630
8307
  var defcols = query.defcols;
8631
-
8632
8308
  var allgroup = [[]];
8633
8309
  if (this.group) {
8634
8310
  allgroup = decartes(this.group, query);
8635
8311
  }
8636
-
8637
- // Prepare groups
8638
- //var allgroup = [['a'], ['a','b'], ['a', 'b', 'c']];
8639
-
8640
8312
  // Union all arrays to get a maximum
8641
8313
  var allgroups = [];
8642
8314
  allgroup.forEach(function (a) {
@@ -8647,12 +8319,10 @@ yy.Select.prototype.compileGroup = function (query) {
8647
8319
 
8648
8320
  query.ingroup = [];
8649
8321
  var s = '';
8650
- // s+= query.selectfns;
8651
8322
  allgroup.forEach(function (agroup) {
8652
8323
  // Start of group function
8653
8324
  s += 'var g=this.xgroups[';
8654
8325
 
8655
- // var gcols = this.group.map(function(col){return col.columnid}); // Group fields with r
8656
8326
  // Array with group columns from record
8657
8327
  var rg = agroup.map(function (col2) {
8658
8328
  var columnid = col2.split('\t')[0];
@@ -8661,9 +8331,7 @@ yy.Select.prototype.compileGroup = function (query) {
8661
8331
  if (columnid === '') {
8662
8332
  return '1'; // Create fictive grouping column for fictive GROUP BY
8663
8333
  }
8664
- // else return "r['"+columnid+"']";
8665
8334
  query.ingroup.push(columnid);
8666
-
8667
8335
  return coljs;
8668
8336
  });
8669
8337
 
@@ -8675,7 +8343,6 @@ yy.Select.prototype.compileGroup = function (query) {
8675
8343
  s += '];if(!g) {this.groups.push((g=this.xgroups[';
8676
8344
  s += rg.join('+"`"+');
8677
8345
  s += '] = {';
8678
- // s += ']=r';
8679
8346
  s += agroup
8680
8347
  .map(function (col2) {
8681
8348
  var columnid = col2.split('\t')[0];
@@ -8687,17 +8354,14 @@ yy.Select.prototype.compileGroup = function (query) {
8687
8354
  return "'" + columnid + "':" + coljs + ',';
8688
8355
  })
8689
8356
  .join('');
8690
-
8691
8357
  var neggroup = arrayDiff(allgroups, agroup);
8692
8358
 
8693
8359
  s += neggroup
8694
8360
  .map(function (col2) {
8695
8361
  var columnid = col2.split('\t')[0];
8696
- // var coljs = col2.split('\t')[1]
8697
8362
  return "'" + columnid + "':null,";
8698
8363
  })
8699
8364
  .join('');
8700
-
8701
8365
  var aft = '',
8702
8366
  aft2 = '';
8703
8367
 
@@ -8705,19 +8369,10 @@ yy.Select.prototype.compileGroup = function (query) {
8705
8369
  aft2 += "for(var f in p['" + query.groupStar + "']) {g[f]=p['" + query.groupStar + "'][f];};";
8706
8370
  }
8707
8371
 
8708
- /*
8709
- */
8710
- // s += self.columns.map(function(col){
8711
-
8712
8372
  s += query.selectGroup
8713
8373
  .map(function (col) {
8714
-
8715
8374
  var colexp = col.expression.toJS('p', tableid, defcols);
8716
8375
  var colas = col.nick;
8717
- // if(typeof colas == 'undefined') {
8718
- // if(col instanceof yy.Column) colas = col.columnid;
8719
- // else colas = col.toString();
8720
- // };
8721
8376
  let colExpIfFunIdExists = expression => {
8722
8377
  let colexpression = expression.args[0];
8723
8378
  return colexpression.toJS('p', tableid, defcols);
@@ -8743,12 +8398,7 @@ yy.Select.prototype.compileGroup = function (query) {
8743
8398
  return `'${colas}':(${colexp})|| typeof ${colexp} == 'number' ?
8744
8399
  ${colexp} : ${colexp} == 'string' && typeof Number(${colexp}) == 'number' ? Number(${colexp}) :
8745
8400
  typeof ${colexp} === 'boolean' ? Number(${colexp}) : 0,`;
8746
- } else if (
8747
- col.aggregatorid === 'FIRST' ||
8748
- col.aggregatorid === 'LAST'
8749
- // || col.aggregatorid == 'AVG'
8750
- // ) { return "'"+col.as+'\':r[\''+col.as+'\'],'; }//f.field.arguments[0].toJS();
8751
- ) {
8401
+ } else if (col.aggregatorid === 'FIRST' || col.aggregatorid === 'LAST') {
8752
8402
  return "'" + colas + "':" + colexp + ','; //f.field.arguments[0].toJS();
8753
8403
  } else if (col.aggregatorid === 'MIN') {
8754
8404
  if ('funcid' in col.expression) {
@@ -8768,58 +8418,24 @@ yy.Select.prototype.compileGroup = function (query) {
8768
8418
  return `'${colas}' : (typeof ${colexp} == 'number' ? ${colexp} : typeof ${colexp} == 'object' ?
8769
8419
  typeof Number(${colexp}) == 'number' ? ${colexp} : null : null),`;
8770
8420
  } else if (col.aggregatorid === 'ARRAY') {
8771
- return "'" + colas + "':[" + colexp + '],';
8421
+ return `'${colas}':[${colexp}],`;
8772
8422
  } else if (col.aggregatorid === 'COUNT') {
8773
8423
  if (col.expression.columnid === '*') {
8774
- return "'" + colas + "':1,";
8424
+ return `'${colas}':1,`;
8775
8425
  } else {
8776
- // return "'"+colas+'\':(typeof '+colexp+' != "undefined")?1:0,';
8777
- // } else {
8778
- return (
8779
- "'" +
8780
- colas +
8781
- "':(typeof " +
8782
- colexp +
8783
- ' == "undefined" || ' +
8784
- colexp +
8785
- ' === null) ? 0 : 1,'
8786
- );
8426
+ return `'${colas}':(typeof ${colexp} == "undefined" || ${colexp} === null) ? 0 : 1,`;
8787
8427
  }
8788
-
8789
- // else if(col.aggregatorid == 'MIN') { return "'"+col.as+'\':r[\''+col.as+'\'],'; }
8790
- // else if(col.aggregatorid == 'MAX') { return "'"+col.as+'\':r[\''+col.as+'\'],'; }
8791
8428
  } else if (col.aggregatorid === 'AVG') {
8792
- query.removeKeys.push('_SUM_' + colas);
8793
- query.removeKeys.push('_COUNT_' + colas);
8429
+ query.removeKeys.push(`_SUM_${colas}`);
8430
+ query.removeKeys.push(`_COUNT_${colas}`);
8794
8431
 
8795
- return (
8796
- '' +
8797
- "'" +
8798
- colas +
8799
- "':" +
8800
- colexp +
8801
- ",'_SUM_" +
8802
- colas +
8803
- "':(" +
8804
- colexp +
8805
- ")||0,'_COUNT_" +
8806
- colas +
8807
- "':(typeof " +
8808
- colexp +
8809
- ' == "undefined" || ' +
8810
- colexp +
8811
- ' === null) ? 0 : 1,'
8812
- );
8432
+ return `'${colas}':${colexp},'_SUM_${colas}':(${colexp})||0,'_COUNT_${colas}':(typeof ${colexp} == "undefined" || ${colexp} === null) ? 0 : 1,`;
8813
8433
  } else if (col.aggregatorid === 'AGGR') {
8814
- aft += ",g['" + colas + "']=" + col.expression.toJS('g', -1);
8434
+ aft += `,g['${colas}']=${col.expression.toJS('g', -1)}`;
8815
8435
  return '';
8816
8436
  } else if (col.aggregatorid === 'REDUCE') {
8817
- // query.removeKeys.push('_REDUCE_'+colas);
8818
8437
  query.aggrKeys.push(col);
8819
-
8820
- // return "'"+colas+'\':alasql.aggr[\''+col.funcid+'\']('+colexp+',undefined,(acc={}),1),'
8821
- // +'\'__REDUCE__'+colas+'\':acc,';
8822
- return "'" + colas + "':alasql.aggr['" + col.funcid + "'](" + colexp + ',undefined,1),';
8438
+ return `'${colas}':alasql.aggr['${col.funcid}'](${colexp},undefined,1),`;
8823
8439
  }
8824
8440
  return '';
8825
8441
  }
@@ -8829,12 +8445,9 @@ yy.Select.prototype.compileGroup = function (query) {
8829
8445
  .join('');
8830
8446
 
8831
8447
  s += '}' + aft + ',g));' + aft2 + '} else {';
8832
-
8833
- // s += self.columns.map(function(col){
8834
8448
  s += query.selectGroup
8835
8449
  .map(function (col) {
8836
8450
  var colas = col.nick;
8837
-
8838
8451
  var colexp = col.expression.toJS('p', tableid, defcols);
8839
8452
  let colExpIfFunIdExists = expression => {
8840
8453
  let colexpression = expression.args[0];
@@ -8844,28 +8457,22 @@ yy.Select.prototype.compileGroup = function (query) {
8844
8457
  var pre = '',
8845
8458
  post = '';
8846
8459
  if (col.distinct) {
8847
- var pre =
8848
- 'if(typeof ' +
8849
- colexp +
8850
- '!="undefined" && (!g[\'$$_VALUES_' +
8851
- colas +
8852
- "'][" +
8853
- colexp +
8854
- '])) {';
8855
- var post = "g['$$_VALUES_" + colas + "'][" + colexp + ']=true;}';
8460
+ pre = `if(typeof ${colexp}!="undefined" && (!g['$$_VALUES_${colas}'][${colexp}])) {`;
8461
+ post = `g['$$_VALUES_${colas}'][${colexp}]=true;}`;
8856
8462
  }
8463
+
8857
8464
  if (col.aggregatorid === 'SUM') {
8858
8465
  if ('funcid' in col.expression) {
8859
8466
  let colexp1 = colExpIfFunIdExists(col.expression);
8860
8467
  return (
8861
8468
  pre +
8862
8469
  `if(g['${colas}'] == null && ${colexp1} == null){g['${colas}'] = null}
8863
- else if(typeof g['${colas}']!== 'object' && typeof g['${colas}']!== 'number' && typeof ${colexp1}!== 'object' && typeof ${colexp1}!== 'number'){g['${colas}'] = null}
8864
- else if(typeof g['${colas}']!== 'object' && typeof g['${colas}']!== 'number' && typeof ${colexp1} == 'number'){g['${colas}'] = ${colexp}}
8865
- else if(typeof g['${colas}']!== 'number' && typeof ${colexp1}!== 'number' && typeof ${colexp1}!== 'object'){g['${colas}'] = g['${colas}']}
8866
- else if((g['${colas}'] == null || (typeof g['${colas}']!== 'number' && typeof g['${colas}']!== 'object')) && (${colexp1} == null || (typeof ${colexp1}!== 'number' && typeof ${colexp1}!== 'object'))){g['${colas}'] = null}
8867
- else if(typeof g['${colas}'] == 'number' && typeof ${colexp1} ==null){g['${colas}'] = g['${colas}']}
8868
- else if(typeof g['${colas}'] == null && typeof ${colexp1} =='number'){g['${colas}'] = ${colexp}}
8470
+ else if(typeof g['${colas}']!== 'object' && typeof g['${colas}']!== 'number' && typeof ${colexp1}!== 'object' && typeof ${colexp1}!== 'number'){ g['${colas}'] = null }
8471
+ else if(typeof g['${colas}']!== 'object' && typeof g['${colas}']!== 'number' && typeof ${colexp1} == 'number'){ g['${colas}'] = ${colexp} }
8472
+ else if(typeof g['${colas}']!== 'number' && typeof ${colexp1}!== 'number' && typeof ${colexp1}!== 'object'){ g['${colas}'] = g['${colas}'] }
8473
+ else if((g['${colas}'] == null || (typeof g['${colas}']!== 'number' && typeof g['${colas}']!== 'object')) && (${colexp1} == null || (typeof ${colexp1}!== 'number' && typeof ${colexp1}!== 'object'))){ g['${colas}'] = null }
8474
+ else if(typeof g['${colas}'] == 'number' && typeof ${colexp1} ==null){ g['${colas}'] = g['${colas}'] }
8475
+ else if(typeof g['${colas}'] == null && typeof ${colexp1} =='number'){ g['${colas}'] = ${colexp} }
8869
8476
  else{g['${colas}'] += ${colexp}||0}` +
8870
8477
  post
8871
8478
  );
@@ -8907,28 +8514,20 @@ yy.Select.prototype.compileGroup = function (query) {
8907
8514
  post
8908
8515
  );
8909
8516
  } else if (col.aggregatorid === 'COUNT') {
8910
-
8911
8517
  if (col.expression.columnid === '*') {
8912
- return pre + "g['" + colas + "']++;" + post;
8518
+ return `${pre}
8519
+ g['${colas}']++;
8520
+ ${post}`;
8913
8521
  } else {
8914
- return (
8915
- pre +
8916
- 'if(typeof ' +
8917
- colexp +
8918
- '!="undefined" && ' +
8919
- colexp +
8920
- " !== null) g['" +
8921
- colas +
8922
- "']++;" +
8923
- post
8924
- );
8522
+ return `${pre}
8523
+ if(typeof ${colexp}!="undefined" && ${colexp} !== null) g['${colas}']++;
8524
+ ${post}`;
8925
8525
  }
8926
8526
  } else if (col.aggregatorid === 'ARRAY') {
8927
8527
  return pre + "g['" + colas + "'].push(" + colexp + ');' + post;
8928
8528
  } else if (col.aggregatorid === 'MIN') {
8929
8529
  if ('funcid' in col.expression) {
8930
8530
  let colexp1 = colExpIfFunIdExists(col.expression);
8931
-
8932
8531
  return (
8933
8532
  pre +
8934
8533
  `if((g['${colas}'] == null && ${colexp1}!== null) ? y = ${colexp} : (g['${colas}']!== null &&
@@ -8978,47 +8577,21 @@ yy.Select.prototype.compileGroup = function (query) {
8978
8577
  } else if (col.aggregatorid === 'FIRST') {
8979
8578
  return '';
8980
8579
  } else if (col.aggregatorid === 'LAST') {
8981
- return pre + "g['" + colas + "']=" + colexp + ';' + post;
8580
+ return `${pre}g['${colas}']=${colexp};${post}`;
8982
8581
  } else if (col.aggregatorid === 'AVG') {
8983
- return (
8984
- '' +
8985
- pre +
8986
- "g['_SUM_" +
8987
- colas +
8988
- "']+=(y=" +
8989
- colexp +
8990
- ')||0;' +
8991
- "g['_COUNT_" +
8992
- colas +
8993
- '\']+=(typeof y == "undefined" || y === null) ? 0 : 1;' +
8994
- "g['" +
8995
- colas +
8996
- "']=g['_SUM_" +
8997
- colas +
8998
- "']/g['_COUNT_" +
8999
- colas +
9000
- "'];" +
9001
- post
9002
- );
9003
- // }
9004
- // else if(col.aggregatorid == 'AVG') { srg.push(colas+':0'); }
8582
+ return `${pre}
8583
+ g['_SUM_${colas}'] += (y=${colexp})||0;
8584
+ g['_COUNT_${colas}'] += (typeof y == "undefined" || y === null) ? 0 : 1;
8585
+ g['${colas}']=g['_SUM_${colas}'] / g['_COUNT_${colas}'];
8586
+ ${post}`;
9005
8587
  } else if (col.aggregatorid === 'AGGR') {
9006
- return '' + pre + "g['" + colas + "']=" + col.expression.toJS('g', -1) + ';' + post;
8588
+ return `${pre}
8589
+ g['${colas}']=${col.expression.toJS('g', -1)};
8590
+ ${post}`;
9007
8591
  } else if (col.aggregatorid === 'REDUCE') {
9008
- return (
9009
- '' +
9010
- pre +
9011
- "g['" +
9012
- colas +
9013
- "']=alasql.aggr." +
9014
- col.funcid +
9015
- '(' +
9016
- colexp +
9017
- ",g['" +
9018
- colas +
9019
- "'],2);" +
9020
- post
9021
- );
8592
+ return `${pre}
8593
+ g['${colas}'] = alasql.aggr.${col.funcid}(${colexp},g['${colas}'],2);
8594
+ ${post}`;
9022
8595
  }
9023
8596
 
9024
8597
  return '';
@@ -9028,24 +8601,8 @@ yy.Select.prototype.compileGroup = function (query) {
9028
8601
  })
9029
8602
  .join('');
9030
8603
 
9031
- // s += selectFields.map(function(f){
9032
-
9033
- // if(f.constructor.name == 'LiteralValue') return '';
9034
- // if (f.field instanceof SQLParser.nodes.FunctionValue
9035
- // && (f.field.name.toUpperCase() == 'SUM' || f.field.name.toUpperCase() == 'COUNT')) {
9036
- // return 'group.'+f.name.value+'=+(+group.'+f.name.value+'||0)+'+f.field.arguments[0].toJS('rec','')+';'; //f.field.arguments[0].toJS();
9037
- // return 'group.'+f.name.value+'+='+f.field.arguments[0].toJS('rec','')+';'; //f.field.arguments[0].toJS();
9038
- // return 'group.'+f.name.value+'+=rec.'+f.name.value+';'; //f.field.arguments[0].toJS();
9039
- // };
9040
- // return '';
9041
- // }).join('');
9042
-
9043
- // s += ' group.amt += rec.emplid;';
9044
- // s += 'group.count++;';
9045
-
9046
8604
  s += '}';
9047
8605
  });
9048
-
9049
8606
  return new Function('p,params,alasql', 'var y;' + s);
9050
8607
  };
9051
8608
  /*
@@ -9934,22 +9491,22 @@ yy.Select.prototype.compileUnpivot = function (query) {
9934
9491
  Calculate ROLLUP() combination
9935
9492
  */
9936
9493
 
9937
- var rollup = function (a, query) {
9938
- var rr = [];
9939
- var mask = 0;
9940
- var glen = a.length;
9941
- for (var g = 0; g < glen + 1; g++) {
9942
- var ss = [];
9943
- for (var i = 0; i < glen; i++) {
9494
+ const rollup = (a, query) => {
9495
+ const rr = [];
9496
+ let mask = 0;
9497
+ const glen = a.length;
9498
+
9499
+ for (let g = 0; g < glen + 1; g++) {
9500
+ const ss = [];
9501
+ for (let i = 0; i < glen; i++) {
9502
+ let aaa;
9944
9503
  if (a[i] instanceof yy.Column) {
9945
9504
  a[i].nick = escapeq(a[i].columnid);
9946
-
9947
9505
  query.groupColumns[escapeq(a[i].columnid)] = a[i].nick;
9948
- var aaa = a[i].nick + '\t' + a[i].toJS('p', query.sources[0].alias, query.defcols);
9506
+ aaa = `${a[i].nick}\t${a[i].toJS('p', query.sources[0].alias, query.defcols)}`;
9949
9507
  } else {
9950
9508
  query.groupColumns[escapeq(a[i].toString())] = escapeq(a[i].toString());
9951
- var aaa =
9952
- escapeq(a[i].toString()) + '\t' + a[i].toJS('p', query.sources[0].alias, query.defcols);
9509
+ aaa = `${escapeq(a[i].toString())}\t${a[i].toJS('p', query.sources[0].alias, query.defcols)}`;
9953
9510
  }
9954
9511
 
9955
9512
  if (mask & (1 << i)) ss.push(aaa);
@@ -9963,22 +9520,17 @@ var rollup = function (a, query) {
9963
9520
  /**
9964
9521
  Calculate CUBE()
9965
9522
  */
9966
- var cube = function (a, query) {
9967
- var rr = [];
9968
- var glen = a.length;
9969
- var glenCube = 1 << glen;
9970
- for (var g = 0; g < glenCube; g++) {
9971
- var ss = [];
9972
- for (var i = 0; i < glen; i++) {
9973
- if (g & (1 << i))
9974
- //ss.push(a[i]);
9975
- //ss = cartes(ss,decartes(a[i]));
9976
-
9977
- // var aaa = a[i].toString()+'\t'
9978
- // +a[i].toJS('p',query.sources[0].alias,query.defcols);
9979
-
9523
+ const cube = (a, query) => {
9524
+ const rr = [];
9525
+ const glen = a.length;
9526
+ const glenCube = 1 << glen;
9527
+
9528
+ for (let g = 0; g < glenCube; g++) {
9529
+ let ss = [];
9530
+ for (let i = 0; i < glen; i++) {
9531
+ if (g & (1 << i)) {
9980
9532
  ss = ss.concat(decartes(a[i], query));
9981
- //
9533
+ }
9982
9534
  }
9983
9535
  rr.push(ss);
9984
9536
  }
@@ -9986,22 +9538,21 @@ var cube = function (a, query) {
9986
9538
  };
9987
9539
 
9988
9540
  /**
9989
- GROUPING SETS()
9541
+ * GROUPING SETS()
9990
9542
  */
9991
- var groupingsets = function (a, query) {
9992
- return a.reduce(function (acc, d) {
9543
+ const groupingsets = (a, query) =>
9544
+ a.reduce((acc, d) => {
9993
9545
  acc = acc.concat(decartes(d, query));
9994
9546
  return acc;
9995
9547
  }, []);
9996
- };
9997
9548
 
9998
9549
  /**
9999
- Cartesian production
9550
+ * Cartesian production
10000
9551
  */
10001
- var cartes = function (a1, a2) {
10002
- var rrr = [];
10003
- for (var i1 = 0; i1 < a1.length; i1++) {
10004
- for (var i2 = 0; i2 < a2.length; i2++) {
9552
+ const cartes = (a1, a2) => {
9553
+ const rrr = [];
9554
+ for (let i1 = 0; i1 < a1.length; i1++) {
9555
+ for (let i2 = 0; i2 < a2.length; i2++) {
10005
9556
  rrr.push(a1[i1].concat(a2[i2]));
10006
9557
  }
10007
9558
  }
@@ -10010,72 +9561,54 @@ var cartes = function (a1, a2) {
10010
9561
 
10011
9562
  /**
10012
9563
  Prepare groups function
10013
- */
10014
- function decartes(gv, query) {
10015
-
9564
+ */ function decartes(gv, query) {
10016
9565
  if (Array.isArray(gv)) {
10017
- var res = [[]];
10018
- for (var t = 0; t < gv.length; t++) {
9566
+ let res = [[]];
9567
+ for (let t = 0; t < gv.length; t++) {
10019
9568
  if (gv[t] instanceof yy.Column) {
10020
-
10021
9569
  gv[t].nick = gv[t].nick ? escapeq(gv[t].nick) : escapeq(gv[t].columnid);
10022
9570
  query.groupColumns[gv[t].nick] = gv[t].nick;
10023
- res = res.map(function (r) {
10024
- return r.concat(
10025
- gv[t].nick + '\t' + gv[t].toJS('p', query.sources[0].alias, query.defcols)
10026
- );
10027
- });
10028
- // res = res.map(function(r){return r.concat(gv[t].columnid)});
9571
+ res = res.map(r =>
9572
+ r.concat(`${gv[t].nick}\t${gv[t].toJS('p', query.sources[0].alias, query.defcols)}`)
9573
+ );
10029
9574
  } else if (gv[t] instanceof yy.FuncValue) {
10030
9575
  query.groupColumns[escapeq(gv[t].toString())] = escapeq(gv[t].toString());
10031
- res = res.map(function (r) {
10032
- return r.concat(
10033
- escapeq(gv[t].toString()) +
10034
- '\t' +
10035
- gv[t].toJS('p', query.sources[0].alias, query.defcols)
10036
- );
10037
- });
10038
- // to be defined
9576
+ res = res.map(r =>
9577
+ r.concat(
9578
+ `${escapeq(gv[t].toString())}\t${gv[t].toJS('p', query.sources[0].alias, query.defcols)}`
9579
+ )
9580
+ );
10039
9581
  } else if (gv[t] instanceof yy.GroupExpression) {
10040
9582
  if (gv[t].type == 'ROLLUP') res = cartes(res, rollup(gv[t].group, query));
10041
9583
  else if (gv[t].type == 'CUBE') res = cartes(res, cube(gv[t].group, query));
10042
9584
  else if (gv[t].type == 'GROUPING SETS') res = cartes(res, groupingsets(gv[t].group, query));
10043
9585
  else throw new Error('Unknown grouping function');
10044
9586
  } else if (gv[t] === '') {
10045
-
10046
9587
  res = [['1\t1']];
10047
9588
  } else {
10048
- // if(gv[t])
10049
-
10050
- res = res.map(function (r) {
10051
- query.groupColumns[escapeq(gv[t].toString())] = escapeq(gv[t].toString());
10052
- return r.concat(
10053
- escapeq(gv[t].toString()) +
10054
- '\t' +
10055
- gv[t].toJS('p', query.sources[0].alias, query.defcols)
10056
- );
10057
- });
10058
- // res = res.concat(gv[t]);
9589
+ res = res.map(r =>
9590
+ r.concat(
9591
+ `${escapeq(gv[t].toString())}\t${gv[t].toJS('p', query.sources[0].alias, query.defcols)}`
9592
+ )
9593
+ );
10059
9594
  }
10060
-
10061
9595
  }
10062
9596
  return res;
10063
- } else if (gv instanceof yy.FuncValue) {
9597
+ }
10064
9598
 
9599
+ if (gv instanceof yy.FuncValue) {
10065
9600
  query.groupColumns[escapeq(gv.toString())] = escapeq(gv.toString());
10066
- return [gv.toString() + '\t' + gv.toJS('p', query.sources[0].alias, query.defcols)];
10067
- } else if (gv instanceof yy.Column) {
9601
+ return [`${gv.toString()}\t${gv.toJS('p', query.sources[0].alias, query.defcols)}`];
9602
+ }
9603
+
9604
+ if (gv instanceof yy.Column) {
10068
9605
  gv.nick = escapeq(gv.columnid);
10069
9606
  query.groupColumns[gv.nick] = gv.nick;
10070
- return [gv.nick + '\t' + gv.toJS('p', query.sources[0].alias, query.defcols)]; // Is this ever happened?
10071
- // } else if(gv instanceof yy.Expression) {
10072
- // return [gv.columnid]; // Is this ever happened?
10073
- } else {
10074
- query.groupColumns[escapeq(gv.toString())] = escapeq(gv.toString());
10075
- return [escapeq(gv.toString()) + '\t' + gv.toJS('p', query.sources[0].alias, query.defcols)];
10076
- // throw new Error('Single argument in the group without array');
9607
+ return [`${gv.nick}\t${gv.toJS('p', query.sources[0].alias, query.defcols)}`];
10077
9608
  }
10078
9609
 
9610
+ query.groupColumns[escapeq(gv.toString())] = escapeq(gv.toString());
9611
+ return [`${escapeq(gv.toString())}\t${gv.toJS('p', query.sources[0].alias, query.defcols)}`];
10079
9612
  }
10080
9613
  /*
10081
9614
  //
@@ -10129,10 +9662,19 @@ yy.Select.prototype.compileDefCols = function (query, databaseid) {
10129
9662
  defcols['.'][jn.as || jn.table.tableid] = true;
10130
9663
 
10131
9664
  if (jn.table) {
10132
- var alias = jn.table.tableid;
10133
- if (jn.as) alias = jn.as;
10134
9665
  var alias = jn.as || jn.table.tableid;
10135
- var table = alasql.databases[jn.table.databaseid || databaseid].tables[jn.table.tableid];
9666
+ var databaseId = jn.table.databaseid || databaseid;
9667
+ var database = alasql.databases[databaseId];
9668
+
9669
+ if (database === undefined) {
9670
+ throw new Error('Database does not exist: ' + databaseId);
9671
+ }
9672
+
9673
+ var table = database.tables[jn.table.tableid];
9674
+
9675
+ if (table === undefined) {
9676
+ throw new Error('Table does not exist: ' + jn.table.tableid);
9677
+ }
10136
9678
 
10137
9679
  if (table.columns) {
10138
9680
  table.columns.forEach(function (col) {
@@ -10194,9 +9736,11 @@ yy.Apply = class Apply {
10194
9736
  }
10195
9737
 
10196
9738
  toString() {
10197
- var s = this.applymode + ' APPLY (' + this.select.toString() + ')';
9739
+ let s = `${this.applymode} APPLY (${this.select.toString()})`;
10198
9740
 
10199
- if (this.as) s += ' AS ' + this.as;
9741
+ if (this.as) {
9742
+ s += ` AS ${this.as}`;
9743
+ }
10200
9744
 
10201
9745
  return s;
10202
9746
  }
@@ -10215,13 +9759,13 @@ yy.Over = class Over {
10215
9759
  }
10216
9760
 
10217
9761
  toString() {
10218
- var s = 'OVER (';
9762
+ let s = 'OVER (';
10219
9763
  if (this.partition) {
10220
- s += 'PARTITION BY ' + this.partition.toString();
9764
+ s += `PARTITION BY ${this.partition.toString()}`;
10221
9765
  if (this.order) s += ' ';
10222
9766
  }
10223
9767
  if (this.order) {
10224
- s += 'ORDER BY ' + this.order.toString();
9768
+ s += `ORDER BY ${this.order.toString()}`;
10225
9769
  }
10226
9770
  s += ')';
10227
9771
  return s;
@@ -10253,7 +9797,6 @@ yy.Over = class Over {
10253
9797
  */
10254
9798
  execute(databaseid, params, cb) {
10255
9799
  if (this.expression) {
10256
-
10257
9800
  alasql.precompile(this, databaseid, params); // Precompile queries
10258
9801
  var exprfn = new Function(
10259
9802
  'params,alasql,p',
@@ -10510,20 +10053,15 @@ yy.Over = class Over {
10510
10053
  }
10511
10054
 
10512
10055
  toJS(context, tableid, defcols) {
10513
-
10514
10056
  var s;
10515
- var refs = [];
10516
- var op = this.op;
10517
- var _this = this;
10518
- //var leftJS = function(){return _this.left.toJS(context,tableid, defcols)};
10519
- //var rightJS = function(){return _this.right.toJS(context,tableid, defcols)};
10520
- var accessedLeft = false,
10521
- accessedRight = false;
10522
- var ref = function (expr) {
10057
+ let refs = [];
10058
+ let op = this.op;
10059
+ let _this = this;
10060
+ let ref = function (expr) {
10523
10061
  if (expr.toJS) {
10524
10062
  expr = expr.toJS(context, tableid, defcols);
10525
10063
  }
10526
- var i = refs.push(expr) - 1;
10064
+ let i = refs.push(expr) - 1;
10527
10065
  return 'y[' + i + ']';
10528
10066
  };
10529
10067
  var leftJS = function () {
@@ -10539,201 +10077,91 @@ yy.Over = class Over {
10539
10077
  op = '!=';
10540
10078
  } else if (this.op === 'OR') {
10541
10079
  op = '||';
10542
- }
10543
-
10544
- // Arrow operator
10545
- if (this.op === '->') {
10080
+ } else if (this.op === '->') {
10546
10081
  // Expression to prevent error if object is empty (#344)
10547
- var ljs = '(' + leftJS() + '||{})';
10082
+ const ljs = `(${leftJS()} || {})`;
10548
10083
 
10549
10084
  if (typeof this.right === 'string') {
10550
- s = ljs + '["' + escapeq(this.right) + '"]';
10085
+ s = `${ljs}["${escapeq(this.right)}"]`;
10551
10086
  } else if (typeof this.right === 'number') {
10552
- s = ljs + '[' + this.right + ']';
10087
+ s = `${ljs}[${this.right}]`;
10553
10088
  } else if (this.right instanceof yy.FuncValue) {
10554
- var ss = [];
10555
- if (!(!this.right.args || 0 === this.right.args.length)) {
10556
- var ss = this.right.args.map(ref);
10089
+ let ss = [];
10090
+ if (this.right.args && this.right.args.length > 0) {
10091
+ ss = this.right.args.map(ref);
10557
10092
  }
10558
- s = '' + ljs + '[' + JSON.stringify(this.right.funcid) + '](' + ss.join(',') + ')';
10093
+ s = `${ljs}[${JSON.stringify(this.right.funcid)}](${ss.join(',')})`;
10559
10094
  } else {
10560
- s = '' + ljs + '[' + rightJS() + ']';
10095
+ s = `${ljs}[${rightJS()}]`;
10561
10096
  }
10562
- }
10563
-
10564
- if (this.op === '!') {
10097
+ } else if (this.op === '!') {
10565
10098
  if (typeof this.right === 'string') {
10566
- s = '' + 'alasql.databases[alasql.useid].objects[' + leftJS() + ']["' + this.right + '"]';
10099
+ s = `alasql.databases[alasql.useid].objects[${leftJS()}]["${this.right}"]`;
10567
10100
  }
10568
10101
  // TODO - add other cases
10569
- }
10570
-
10571
- if (this.op === 'IS') {
10102
+ } else if (this.op === 'IS') {
10572
10103
  const leftOperand = leftJS();
10573
10104
  const rightOperand = rightJS();
10574
10105
  if (
10575
10106
  this.right instanceof yy.NullValue ||
10576
10107
  (this.right.op === 'NOT' && this.right.right instanceof yy.NullValue)
10577
10108
  ) {
10578
- s = `((${leftOperand} == null) === (${rightOperand} == null))`; // == null cant be ===
10109
+ s = `((${leftOperand} == null) === (${rightOperand} == null))`; // == null can't be ===
10579
10110
  } else {
10580
- s = `((${leftOperand} == ${rightOperand}) || (${leftOperand} < 0 && true == ${rightOperand}))`;
10111
+ s = `((${leftOperand} == ${rightOperand}) || (${leftOperand} < 0 && true == ${rightOperand}))`;
10581
10112
  }
10582
- }
10583
-
10584
- if (this.op === '==') {
10585
- s = '' + 'alasql.utils.deepEqual(' + leftJS() + ',' + rightJS() + ')';
10586
- }
10587
-
10588
- if (this.op === '===' || this.op === '!===') {
10589
- s =
10590
- '' +
10591
- '(' +
10592
- (this.op === '!===' ? '!' : '') +
10593
- '(' +
10594
- '(' +
10595
- leftJS() +
10596
- ').valueOf()' +
10597
- '===' +
10598
- '(' +
10599
- rightJS() +
10600
- ').valueOf()' +
10601
- ')' +
10602
- ')';
10603
- }
10604
-
10605
- if (this.op === '!==') {
10606
- s = '' + '(!alasql.utils.deepEqual(' + leftJS() + ',' + rightJS() + '))';
10607
- }
10608
- if (this.op === '||') {
10609
- s = '' + "(''+(" + leftJS() + "||'')+(" + rightJS() + '||""))';
10610
- }
10611
- if (this.op === 'LIKE' || this.op === 'NOT LIKE') {
10612
- var s =
10613
- '(' +
10614
- (this.op === 'NOT LIKE' ? '!' : '') +
10615
- 'alasql.utils.like(' +
10616
- rightJS() +
10617
- ',' +
10618
- leftJS();
10619
- if (this.escape) {
10620
- s += ',' + ref(this.escape);
10621
- }
10622
- s += '))';
10623
- }
10624
- if (this.op === 'REGEXP') {
10625
- s = 'alasql.stdfn.REGEXP_LIKE(' + leftJS() + ',' + rightJS() + ')';
10626
- }
10627
- if (this.op === 'GLOB') {
10628
- s = 'alasql.utils.glob(' + leftJS() + ',' + rightJS() + ')';
10629
- }
10630
-
10631
- if (this.op === 'BETWEEN' || this.op === 'NOT BETWEEN') {
10632
- var left = leftJS();
10633
- s =
10634
- '' +
10635
- '(' +
10636
- (this.op === 'NOT BETWEEN' ? '!' : '') +
10637
- '(' +
10638
- '(' +
10639
- ref(this.right1) +
10640
- '<=' +
10641
- left +
10642
- ') && (' +
10643
- left +
10644
- '<=' +
10645
- ref(this.right2) +
10646
- ')' +
10647
- ')' +
10648
- ')';
10649
- }
10650
-
10651
- if (this.op === 'IN') {
10113
+ } else if (this.op === '==') {
10114
+ s = `alasql.utils.deepEqual(${leftJS()}, ${rightJS()})`;
10115
+ } else if (this.op === '===' || this.op === '!===') {
10116
+ s = `(${this.op === '!===' ? '!' : ''}((${leftJS()}).valueOf() === (${rightJS()}).valueOf()))`;
10117
+ } else if (this.op === '!==') {
10118
+ s = `(!alasql.utils.deepEqual(${leftJS()}, ${rightJS()}))`;
10119
+ } else if (this.op === '||') {
10120
+ s = `(''+(${leftJS()} || '') + (${rightJS()} || ''))`;
10121
+ } else if (this.op === 'LIKE' || this.op === 'NOT LIKE') {
10122
+ s = `(${this.op === 'NOT LIKE' ? '!' : ''}alasql.utils.like(${rightJS()}, ${leftJS()}${this.escape ? `, ${ref(this.escape)}` : ''}))`;
10123
+ } else if (this.op === 'REGEXP') {
10124
+ s = `alasql.stdfn.REGEXP_LIKE(${leftJS()}, ${rightJS()})`;
10125
+ } else if (this.op === 'GLOB') {
10126
+ s = `alasql.utils.glob(${leftJS()}, ${rightJS()})`;
10127
+ } else if (this.op === 'BETWEEN' || this.op === 'NOT BETWEEN') {
10128
+ const left = leftJS();
10129
+ s = `(${this.op === 'NOT BETWEEN' ? '!' : ''}((${ref(this.right1)} <= ${left}) && (${left} <= ${ref(this.right2)})))`;
10130
+ } else if (this.op === 'IN') {
10652
10131
  if (this.right instanceof yy.Select) {
10653
- s = '(';
10654
- // s += 'this.query.queriesdata['+this.queriesidx+']';
10655
- // s += 'alasql.utils.flatArray(this.query.queriesfn['+(this.queriesidx)+'](params,null,context))';
10656
- s +=
10657
- 'alasql.utils.flatArray(this.queriesfn[' +
10658
- this.queriesidx +
10659
- '](params,null,' +
10660
- context +
10661
- '))';
10662
- s += '.indexOf(';
10663
- s += 'alasql.utils.getValueOf(' + leftJS() + '))>-1)';
10132
+ s = `alasql.utils.flatArray(this.queriesfn[${this.queriesidx}](params, null, ${context})).indexOf(alasql.utils.getValueOf(${leftJS()})) > -1`;
10664
10133
  } else if (Array.isArray(this.right)) {
10665
- if (
10666
- !alasql.options.cache ||
10667
- this.right.filter(value => value instanceof yy.ParamValue).length > 0
10668
- ) {
10669
- // When not using cache, or when the array contains parameters, we need to re-create the Set
10670
- // leverage JS Set, which is faster for lookups than arrays
10671
- s =
10672
- '(new Set([' +
10673
- this.right.map(ref).join(',') +
10674
- ']).has(alasql.utils.getValueOf(' +
10675
- leftJS() +
10676
- ')))';
10134
+ if (!alasql.options.cache || this.right.some(value => value instanceof yy.ParamValue)) {
10135
+ // Leverage JS Set for faster lookups than arrays
10136
+ s = `(new Set([${this.right.map(ref).join(',')}]).has(alasql.utils.getValueOf(${leftJS()})))`;
10677
10137
  } else {
10678
- // Use a cache to not re-create the Set on every identitical query
10679
- if (!alasql.sets) {
10680
- alasql.sets = {};
10681
- }
10138
+ // Use a cache to avoid re-creating the Set on every identical query
10139
+ alasql.sets = alasql.sets || {};
10682
10140
  const allValues = this.right.map(value => value.value);
10683
10141
  const allValuesStr = allValues.join(',');
10684
- if (!alasql.sets[allValuesStr]) {
10685
- // leverage JS Set, which is faster for lookups than arrays
10686
- alasql.sets[allValuesStr] = new Set(allValues);
10687
- }
10688
- s =
10689
- 'alasql.sets["' + allValuesStr + '"].has(alasql.utils.getValueOf(' + leftJS() + '))';
10142
+ alasql.sets[allValuesStr] = alasql.sets[allValuesStr] || new Set(allValues);
10143
+ s = `alasql.sets["${allValuesStr}"].has(alasql.utils.getValueOf(${leftJS()}))`;
10690
10144
  }
10691
10145
  } else {
10692
- s = '(' + rightJS() + '.indexOf(' + leftJS() + ')>-1)';
10693
-
10694
- // } else {
10695
- // throw new Error('Wrong IN operator without SELECT part');
10146
+ s = `(${rightJS()}.indexOf(${leftJS()}) > -1)`;
10696
10147
  }
10697
- }
10698
-
10699
- if (this.op === 'NOT IN') {
10148
+ } else if (this.op === 'NOT IN') {
10700
10149
  if (this.right instanceof yy.Select) {
10701
- s = '(';
10702
- s += 'alasql.utils.flatArray(this.queriesfn[' + this.queriesidx + '](params,null,p))';
10703
- s += '.indexOf(';
10704
- s += 'alasql.utils.getValueOf(' + leftJS() + '))<0)';
10150
+ s = `alasql.utils.flatArray(this.queriesfn[${this.queriesidx}](params, null, p)).indexOf(alasql.utils.getValueOf(${leftJS()})) < 0`;
10705
10151
  } else if (Array.isArray(this.right)) {
10706
- if (
10707
- !alasql.options.cache ||
10708
- this.right.filter(value => value instanceof yy.ParamValue).length > 0
10709
- ) {
10710
- // When not using cache, or when the array contains parameters, we need to re-create the Set
10711
- // leverage JS Set, which is faster for lookups than arrays
10712
- s =
10713
- '(!(new Set([' +
10714
- this.right.map(ref).join(',') +
10715
- ']).has(alasql.utils.getValueOf(' +
10716
- leftJS() +
10717
- '))))';
10152
+ if (!alasql.options.cache || this.right.some(value => value instanceof yy.ParamValue)) {
10153
+ // Leverage JS Set for faster lookups than arrays
10154
+ s = `(!(new Set([${this.right.map(ref).join(',')}]).has(alasql.utils.getValueOf(${leftJS()}))))`;
10718
10155
  } else {
10719
- // Use a cache to not re-create the Set on every identitical query
10720
- if (!alasql.sets) {
10721
- alasql.sets = {};
10722
- }
10156
+ // Use a cache to avoid re-creating the Set on every identical query
10157
+ alasql.sets = alasql.sets || {};
10723
10158
  const allValues = this.right.map(value => value.value);
10724
10159
  const allValuesStr = allValues.join(',');
10725
- if (!alasql.sets[allValuesStr]) {
10726
- // leverage JS Set, which is faster for lookups than arrays
10727
- alasql.sets[allValuesStr] = new Set(allValues);
10728
- }
10729
- s =
10730
- '!alasql.sets["' + allValuesStr + '"].has(alasql.utils.getValueOf(' + leftJS() + '))';
10160
+ alasql.sets[allValuesStr] = alasql.sets[allValuesStr] || new Set(allValues);
10161
+ s = `!alasql.sets["${allValuesStr}"].has(alasql.utils.getValueOf(${leftJS()}))`;
10731
10162
  }
10732
10163
  } else {
10733
- s = '(' + rightJS() + '.indexOf(';
10734
- s += leftJS() + ')==-1)';
10735
-
10736
- // throw new Error('Wrong NOT IN operator without SELECT part');
10164
+ s = `(${rightJS()}.indexOf(${leftJS()}) === -1)`;
10737
10165
  }
10738
10166
  }
10739
10167
 
@@ -10801,9 +10229,7 @@ yy.Over = class Over {
10801
10229
  return '(' + declareRefs + ', ' + expr + ')';
10802
10230
  }
10803
10231
 
10804
- return (
10805
- '(' + declareRefs + ', ' + 'y.some(function(e){return e == null}) ? void 0 : ' + expr + ')'
10806
- );
10232
+ return `(${declareRefs}, y.some(e => e == null) ? void 0 : ${expr})`;
10807
10233
  }
10808
10234
  }
10809
10235
 
@@ -10875,8 +10301,6 @@ yy.Over = class Over {
10875
10301
  }
10876
10302
 
10877
10303
  toJS(context, tableid, defcols) {
10878
-
10879
- // return "'"+doubleqq(this.value)+"'";
10880
10304
  return context;
10881
10305
  }
10882
10306
  }
@@ -11428,7 +10852,6 @@ yy.FuncValue.prototype.toJS = function (context, tableid, defcols) {
11428
10852
  } else if (!alasql.fn[funcid] && alasql.stdfn[funcid.toUpperCase()]) {
11429
10853
  if (this.newid) s += 'new ';
11430
10854
  s += 'alasql.stdfn[' + JSON.stringify(this.funcid.toUpperCase()) + '](';
11431
- // if(this.args) s += this.args.toJS(context, tableid);
11432
10855
  if (this.args && this.args.length > 0) {
11433
10856
  s += this.args
11434
10857
  .map(function (arg) {
@@ -11443,7 +10866,6 @@ yy.FuncValue.prototype.toJS = function (context, tableid, defcols) {
11443
10866
  // var s = '';
11444
10867
  if (this.newid) s += 'new ';
11445
10868
  s += 'alasql.fn[' + JSON.stringify(this.funcid) + '](';
11446
- // if(this.args) s += this.args.toJS(context, tableid);
11447
10869
  if (this.args && this.args.length > 0) {
11448
10870
  s += this.args
11449
10871
  .map(function (arg) {
@@ -11453,9 +10875,18 @@ yy.FuncValue.prototype.toJS = function (context, tableid, defcols) {
11453
10875
  }
11454
10876
  s += ')';
11455
10877
  }
11456
-
11457
10878
  return s;
11458
10879
  };
10880
+ /*
10881
+ //
10882
+ // SQL FUNCTIONS COMPILERS
10883
+ // Based on SQLite functions
10884
+
10885
+ // IMPORTANT: These are compiled functions
10886
+
10887
+ //alasql.fn = {}; // Keep for compatibility
10888
+ //alasql.userlib = alasql.fn;
10889
+ */
11459
10890
 
11460
10891
  var stdlib = (alasql.stdlib = {});
11461
10892
  var stdfn = (alasql.stdfn = {});
@@ -11476,16 +10907,16 @@ stdlib.EXP = function (a) {
11476
10907
 
11477
10908
  stdlib.IIF = function (a, b, c) {
11478
10909
  if (arguments.length === 3) {
11479
- return '((' + a + ')?(' + b + '):(' + c + '))';
10910
+ return `((${a}) ? (${b}) : (${c}))`;
11480
10911
  } else {
11481
10912
  throw new Error('Number of arguments of IFF is not equals to 3');
11482
10913
  }
11483
10914
  };
11484
10915
  stdlib.IFNULL = function (a, b) {
11485
- return '((typeof ' + a + ' ==="undefined" || null === ' + a + ')?' + b + ':' + a + ')';
10916
+ return `((typeof ${a} === "undefined" || ${a} === null) ? ${b} : ${a})`;
11486
10917
  };
11487
10918
  stdlib.INSTR = function (s, p) {
11488
- return '((' + s + ').indexOf(' + p + ')+1)';
10919
+ return `((${s}).indexOf(${p}) + 1)`;
11489
10920
  };
11490
10921
 
11491
10922
  //stdlib.LEN = stdlib.LENGTH = function(s) {return '('+s+'+"").length';};
@@ -11637,15 +11068,15 @@ alasql.aggr.median = alasql.aggr.MEDIAN = function (v, s, stage) {
11637
11068
  return null;
11638
11069
  }
11639
11070
 
11640
- var r = s.sort((a, b) => {
11071
+ let r = s.sort((a, b) => {
11641
11072
  if (a > b) return 1;
11642
11073
  if (a < b) return -1;
11643
11074
  return 0;
11644
11075
  });
11645
11076
 
11646
- var middle = (r.length + 1) / 2;
11647
- var middleFloor = middle | 0;
11648
- var el = r[middleFloor - 1];
11077
+ let middle = (r.length + 1) / 2;
11078
+ let middleFloor = middle | 0;
11079
+ let el = r[middleFloor - 1];
11649
11080
 
11650
11081
  if (middle === middleFloor || (typeof el !== 'number' && !(el instanceof Number))) {
11651
11082
  return el;
@@ -11661,32 +11092,34 @@ alasql.aggr.QUART = function (v, s, stage, nth) {
11661
11092
  s.push(v);
11662
11093
  }
11663
11094
  return s;
11664
- } else if (stage === 1) {
11095
+ }
11096
+
11097
+ if (stage === 1) {
11665
11098
  if (v === null) {
11666
11099
  return [];
11667
11100
  }
11668
11101
  return [v];
11669
- } else {
11670
- if (!s.length) {
11671
- return s;
11672
- }
11102
+ }
11103
+ if (!s.length) {
11104
+ return s;
11105
+ }
11673
11106
 
11674
- nth = !nth ? 1 : nth;
11675
- var r = s.sort(function (a, b) {
11676
- if (a === b) {
11677
- return 0;
11678
- }
11679
- if (a > b) {
11680
- return 1;
11681
- }
11682
- return -1;
11683
- });
11684
- var p = (nth * (r.length + 1)) / 4;
11685
- if (Number.isInteger(p)) {
11686
- return r[p - 1]; //Integer value
11687
- }
11688
- return r[Math.floor(p)]; //Math.ceil -1 or Math.floor
11107
+ nth = !nth ? 1 : nth;
11108
+ var r = s.sort(function (a, b) {
11109
+ if (a === b) return 0;
11110
+
11111
+ if (a > b) return 1;
11112
+
11113
+ return -1;
11114
+ });
11115
+
11116
+ let p = (nth * (r.length + 1)) / 4;
11117
+
11118
+ if (Number.isInteger(p)) {
11119
+ return r[p - 1]; //Integer value
11689
11120
  }
11121
+
11122
+ return r[Math.floor(p)]; //Math.ceil -1 or Math.floor
11690
11123
  };
11691
11124
 
11692
11125
  alasql.aggr.QUART2 = function (v, s, stage) {
@@ -11701,26 +11134,25 @@ alasql.aggr.QUART3 = function (v, s, stage) {
11701
11134
  // Standard deviation
11702
11135
  alasql.aggr.VAR = function (v, s, stage) {
11703
11136
  if (stage === 1) {
11704
- if (v === null) {
11705
- return {arr: [], sum: 0};
11706
- }
11707
- return {arr: [v], sum: v};
11137
+ // Initialise sum, sum of squares, and count
11138
+ return v === null ? {sum: 0, sumSq: 0, count: 0} : {sum: v, sumSq: v * v, count: 1};
11708
11139
  } else if (stage === 2) {
11709
- if (v === null) {
11710
- return s;
11140
+ // Update sum, sum of squares, and count
11141
+ if (v !== null) {
11142
+ s.sum += v;
11143
+ s.sumSq += v * v;
11144
+ s.count++;
11711
11145
  }
11712
- s.arr.push(v);
11713
- s.sum += v;
11714
11146
  return s;
11715
11147
  } else {
11716
- var N = s.arr.length;
11717
- var avg = s.sum / N;
11718
- var std = 0;
11719
- for (var i = 0; i < N; i++) {
11720
- std += (s.arr[i] - avg) * (s.arr[i] - avg);
11148
+ // Calculate variance using the formula: variance = (sumSq - (sum^2 / count)) / (count - 1)
11149
+ // This avoids the need to store and iterate over all values
11150
+ if (s.count > 1) {
11151
+ return (s.sumSq - (s.sum * s.sum) / s.count) / (s.count - 1);
11152
+ } else {
11153
+ // Handling for cases with less than 2 values (variance is undefined or zero)
11154
+ return 0;
11721
11155
  }
11722
- std = std / (N - 1);
11723
- return std;
11724
11156
  }
11725
11157
  };
11726
11158
 
@@ -11732,27 +11164,33 @@ alasql.aggr.STDEV = function (v, s, stage) {
11732
11164
  }
11733
11165
  };
11734
11166
 
11735
- // Standard deviation
11736
- // alasql.aggr.VARP = function(v,s,acc){
11737
-
11738
- // };
11167
+ alasql.aggr.STDEV = function (v, s, stage) {
11168
+ if (stage === 1 || stage === 2) {
11169
+ return alasql.aggr.VAR(v, s, stage);
11170
+ } else {
11171
+ return Math.sqrt(alasql.aggr.VAR(v, s, stage));
11172
+ }
11173
+ };
11739
11174
 
11740
- alasql.aggr.VARP = function (v, s, stage) {
11741
- if (stage == 1) {
11742
- return {arr: [v], sum: v};
11743
- } else if (stage == 2) {
11744
- s.arr.push(v);
11745
- s.sum += v;
11746
- return s;
11175
+ alasql.aggr.VARP = function (value, accumulator, stage) {
11176
+ if (stage === 1) {
11177
+ // Initialise accumulator with count, sum, and sum of squares
11178
+ return {count: 1, sum: value, sumSq: value * value};
11179
+ } else if (stage === 2) {
11180
+ // Update accumulator
11181
+ accumulator.count++;
11182
+ accumulator.sum += value;
11183
+ accumulator.sumSq += value * value;
11184
+ return accumulator;
11747
11185
  } else {
11748
- var N = s.arr.length;
11749
- var avg = s.sum / N;
11750
- var std = 0;
11751
- for (var i = 0; i < N; i++) {
11752
- std += (s.arr[i] - avg) * (s.arr[i] - avg);
11186
+ // Final stage: Calculate variance
11187
+ if (accumulator.count > 0) {
11188
+ const mean = accumulator.sum / accumulator.count;
11189
+ const variance = accumulator.sumSq / accumulator.count - mean * mean;
11190
+ return variance;
11191
+ } else {
11192
+ return 0; // Return 0 variance if no values were aggregated
11753
11193
  }
11754
- std = std / N;
11755
- return std;
11756
11194
  }
11757
11195
  };
11758
11196
 
@@ -11856,38 +11294,32 @@ yy.CaseValue.prototype.findAggregator = function (query) {
11856
11294
  };
11857
11295
 
11858
11296
  yy.CaseValue.prototype.toJS = function (context, tableid, defcols) {
11859
- var s = '((function(' + context + ',params,alasql){var y,r;';
11297
+ let s = `(((${context}, params, alasql) => {
11298
+ let y, r;`;
11299
+
11860
11300
  if (this.expression) {
11861
- // this.expression.toJS(context, tableid)
11862
- s += 'v=' + this.expression.toJS(context, tableid, defcols) + ';';
11863
- s += (this.whens || [])
11864
- .map(function (w) {
11865
- return (
11866
- ' if(v==' +
11867
- w.when.toJS(context, tableid, defcols) +
11868
- ') {r=' +
11869
- w.then.toJS(context, tableid, defcols) +
11870
- '}'
11871
- );
11872
- })
11873
- .join(' else ');
11874
- if (this.elses) s += ' else {r=' + this.elses.toJS(context, tableid, defcols) + '}';
11301
+ // If there's an expression, evaluate it and store in `v`, then compare in `when` clauses
11302
+ s += `let v = ${this.expression.toJS(context, tableid, defcols)};`;
11303
+ this.whens.forEach((w, index) => {
11304
+ const condition = `v === ${w.when.toJS(context, tableid, defcols)}`;
11305
+ const assignment = `r = ${w.then.toJS(context, tableid, defcols)}`;
11306
+ s += `${index === 0 ? 'if' : ' else if'} (${condition}) { ${assignment}; }`;
11307
+ });
11875
11308
  } else {
11876
- s += (this.whens || [])
11877
- .map(function (w) {
11878
- return (
11879
- ' if(' +
11880
- w.when.toJS(context, tableid, defcols) +
11881
- ') {r=' +
11882
- w.then.toJS(context, tableid, defcols) +
11883
- '}'
11884
- );
11885
- })
11886
- .join(' else ');
11887
- if (this.elses) s += ' else {r=' + this.elses.toJS(context, tableid, defcols) + '}';
11309
+ // Directly evaluate `when` conditions without an initial expression
11310
+ this.whens.forEach((w, index) => {
11311
+ const condition = w.when.toJS(context, tableid, defcols);
11312
+ const assignment = `r = ${w.then.toJS(context, tableid, defcols)}`;
11313
+ s += `${index === 0 ? 'if' : ' else if'} (${condition}) { ${assignment}; }`;
11314
+ });
11315
+ }
11316
+
11317
+ // Handle the `else` case
11318
+ if (this.elses) {
11319
+ s += ` else { r = ${this.elses.toJS(context, tableid, defcols)}; }`;
11888
11320
  }
11889
- // TODO remove bind from CASE
11890
- s += ';return r;}).bind(this))(' + context + ',params,alasql)';
11321
+
11322
+ s += '; return r; }))(' + context + ', params, alasql)';
11891
11323
 
11892
11324
  return s;
11893
11325
  };
@@ -11909,47 +11341,31 @@ yy.Json.prototype.toString = function () {
11909
11341
  return s;
11910
11342
  };
11911
11343
 
11912
- var JSONtoString = (alasql.utils.JSONtoString = function (obj) {
11913
- var s = '';
11914
- if (typeof obj == 'string') s = '"' + obj + '"';
11915
- else if (typeof obj == 'number') s = obj;
11916
- else if (typeof obj == 'boolean') s = obj;
11917
- else if (typeof obj == 'object') {
11918
- if (Array.isArray(obj)) {
11919
- s +=
11920
- '[' +
11921
- obj
11922
- .map(function (b) {
11923
- return JSONtoString(b);
11924
- })
11925
- .join(',') +
11926
- ']';
11927
- } else if (!obj.toJS || obj instanceof yy.Json) {
11928
- // to prevent recursion
11929
- s = '{';
11930
- var ss = [];
11931
- for (var k in obj) {
11932
- var s1 = '';
11933
- if (typeof k == 'string') s1 += '"' + k + '"';
11934
- else if (typeof k == 'number') s1 += k;
11935
- else if (typeof k == 'boolean') s1 += k;
11936
- else {
11937
- throw new Error('THis is not ES6... no expressions on left side yet');
11938
- }
11939
- s1 += ':' + JSONtoString(obj[k]);
11940
- ss.push(s1);
11344
+ const JSONtoString = (alasql.utils.JSONtoString = function (obj) {
11345
+ if (typeof obj === 'string') return `"${obj}"`;
11346
+ if (typeof obj === 'number' || typeof obj === 'boolean') return String(obj);
11347
+
11348
+ if (Array.isArray(obj)) {
11349
+ return `[${obj.map(b => JSONtoString(b)).join(',')}]`;
11350
+ }
11351
+
11352
+ if (typeof obj === 'object') {
11353
+ if (!obj.toJS || obj instanceof yy.Json) {
11354
+ const ss = [];
11355
+ for (const k in obj) {
11356
+ const keyStr = typeof k === 'string' ? `"${k}"` : String(k);
11357
+ const valueStr = JSONtoString(obj[k]);
11358
+ ss.push(`${keyStr}:${valueStr}`);
11941
11359
  }
11942
- s += ss.join(',') + '}';
11360
+ return `{${ss.join(',')}}`;
11943
11361
  } else if (obj.toString) {
11944
- s = obj.toString();
11362
+ return obj.toString();
11945
11363
  } else {
11946
- throw new Error('1Can not show JSON object ' + JSON.stringify(obj));
11364
+ throw new Error(`1: Cannot show JSON object ${JSON.stringify(obj)}`);
11947
11365
  }
11948
11366
  } else {
11949
- throw new Error('2Can not show JSON object ' + JSON.stringify(obj));
11367
+ throw new Error(`2: Cannot show JSON object ${JSON.stringify(obj)}`);
11950
11368
  }
11951
-
11952
- return s;
11953
11369
  });
11954
11370
 
11955
11371
  function JSONtoJS(obj, context, tableid, defcols) {
@@ -11957,36 +11373,21 @@ function JSONtoJS(obj, context, tableid, defcols) {
11957
11373
  if (typeof obj == 'string') s = '"' + obj + '"';
11958
11374
  else if (typeof obj == 'number') s = '(' + obj + ')';
11959
11375
  else if (typeof obj == 'boolean') s = obj;
11960
- else if (typeof obj == 'object') {
11376
+ else if (typeof obj === 'object') {
11961
11377
  if (Array.isArray(obj)) {
11962
- s +=
11963
- '[' +
11964
- obj
11965
- .map(function (b) {
11966
- return JSONtoJS(b, context, tableid, defcols);
11967
- })
11968
- .join(',') +
11969
- ']';
11378
+ s += `[${obj.map(b => JSONtoJS(b, context, tableid, defcols)).join(',')}]`;
11970
11379
  } else if (!obj.toJS || obj instanceof yy.Json) {
11971
- // to prevent recursion
11972
- s = '{';
11973
- var ss = [];
11974
- for (var k in obj) {
11975
- var s1 = '';
11976
- if (typeof k == 'string') s1 += '"' + k + '"';
11977
- else if (typeof k == 'number') s1 += k;
11978
- else if (typeof k == 'boolean') s1 += k;
11979
- else {
11980
- throw new Error('THis is not ES6... no expressions on left side yet');
11981
- }
11982
- s1 += ':' + JSONtoJS(obj[k], context, tableid, defcols);
11983
- ss.push(s1);
11380
+ let ss = [];
11381
+ for (const k in obj) {
11382
+ let keyStr = typeof k === 'string' ? `"${k}"` : k.toString();
11383
+ let valueStr = JSONtoJS(obj[k], context, tableid, defcols);
11384
+ ss.push(`${keyStr}:${valueStr}`);
11984
11385
  }
11985
- s += ss.join(',') + '}';
11386
+ s = `{${ss.join(',')}}`;
11986
11387
  } else if (obj.toJS) {
11987
11388
  s = obj.toJS(context, tableid, defcols);
11988
11389
  } else {
11989
- throw new Error('1Can not parse JSON object ' + JSON.stringify(obj));
11390
+ throw new Error(`Cannot parse JSON object ${JSON.stringify(obj)}`);
11990
11391
  }
11991
11392
  } else {
11992
11393
  throw new Error('2Can not parse JSON object ' + JSON.stringify(obj));
@@ -12024,23 +11425,12 @@ yy.Convert.prototype.toString = function () {
12024
11425
  return s;
12025
11426
  };
12026
11427
  yy.Convert.prototype.toJS = function (context, tableid, defcols) {
12027
- // if(this.style) {
12028
- return (
12029
- 'alasql.stdfn.CONVERT(' +
12030
- this.expression.toJS(context, tableid, defcols) +
12031
- ',{dbtypeid:"' +
12032
- this.dbtypeid +
12033
- '",dbsize:' +
12034
- this.dbsize +
12035
- ',dbprecision:' +
12036
- this.dbprecision +
12037
- ',style:' +
12038
- this.style +
12039
- '})'
12040
- );
12041
- // }
12042
-
12043
- throw new Error('There is not such type conversion for ' + this.toString());
11428
+ return `alasql.stdfn.CONVERT(${this.expression.toJS(context, tableid, defcols)}, {
11429
+ dbtypeid: "${this.dbtypeid}",
11430
+ dbsize: ${this.dbsize},
11431
+ dbprecision: ${this.dbprecision},
11432
+ style: ${this.style}
11433
+ })`;
12044
11434
  };
12045
11435
 
12046
11436
  function structuredDate(unFormattedDate) {
@@ -12236,7 +11626,7 @@ yy.ColumnDef = function (params) {
12236
11626
  return Object.assign(this, params);
12237
11627
  };
12238
11628
  yy.ColumnDef.prototype.toString = function () {
12239
- var s = this.columnid;
11629
+ let s = this.columnid;
12240
11630
  if (this.dbtypeid) {
12241
11631
  s += ' ' + this.dbtypeid;
12242
11632
  }
@@ -12264,41 +11654,20 @@ yy.CreateTable = function (params) {
12264
11654
  return Object.assign(this, params);
12265
11655
  };
12266
11656
  yy.CreateTable.prototype.toString = function () {
12267
- var s = 'CREATE';
12268
- if (this.temporary) {
12269
- s += ' TEMPORARY';
12270
- }
11657
+ let s = `CREATE${this.temporary ? ' TEMPORARY' : ''}${this.view ? ' VIEW' : ` ${this.class ? 'CLASS' : 'TABLE'}`}${this.ifnotexists ? ' IF NOT EXISTS' : ''} ${this.table.toString()}`;
12271
11658
 
12272
- if (this.view) {
12273
- s += ' VIEW';
12274
- } else {
12275
- s += ' ' + (this.class ? 'CLASS' : 'TABLE');
12276
- }
12277
- if (this.ifnotexists) {
12278
- s += ' IF NOT EXISTS';
12279
- }
12280
- s += ' ' + this.table.toString();
12281
11659
  if (this.viewcolumns) {
12282
- s +=
12283
- '(' +
12284
- this.viewcolumns
12285
- .map(function (vcol) {
12286
- return vcol.toString();
12287
- })
12288
- .join(',') +
12289
- ')';
11660
+ s += `(${this.viewcolumns.map(vcol => vcol.toString()).join(',')})`;
12290
11661
  }
11662
+
12291
11663
  if (this.as) {
12292
- s += ' AS ' + this.as;
11664
+ s += ` AS ${this.as}`;
12293
11665
  } else {
12294
- var ss = this.columns.map(function (col) {
12295
- return col.toString();
12296
- });
12297
- s += ' (' + ss.join(',') + ')';
11666
+ s += ` (${this.columns.map(col => col.toString()).join(',')})`;
12298
11667
  }
12299
11668
 
12300
11669
  if (this.view && this.select) {
12301
- s += ' AS ' + this.select.toString();
11670
+ s += ` AS ${this.select.toString()}`;
12302
11671
  }
12303
11672
 
12304
11673
  return s;
@@ -12315,13 +11684,7 @@ yy.CreateTable.prototype.execute = function (databaseid, params, cb) {
12315
11684
  throw new Error('Table name is not defined');
12316
11685
  }
12317
11686
 
12318
- // var ifnotexists = this.ifnotexists;
12319
11687
  var columns = this.columns;
12320
- // if(false) {
12321
- // if(!columns) {
12322
- // throw new Error('Columns are not defined');
12323
- // }
12324
- // }
12325
11688
  var constraints = this.constraints || [];
12326
11689
 
12327
11690
  // IF NOT EXISTS
@@ -12372,8 +11735,6 @@ yy.CreateTable.prototype.execute = function (databaseid, params, cb) {
12372
11735
  value: +col.identity.value,
12373
11736
  step: +col.identity.step,
12374
11737
  };
12375
- // ss.push('\''+col.columnid+'\':(alasql.databases[\''+db.databaseid+'\'].tables[\''
12376
- // +tableid+'\'].identities[\''+col.columnid+'\'].value)');
12377
11738
  }
12378
11739
  if (col.check) {
12379
11740
  table.checks.push({
@@ -12410,7 +11771,6 @@ yy.CreateTable.prototype.execute = function (databaseid, params, cb) {
12410
11771
 
12411
11772
  // UNIQUE clause
12412
11773
  if (col.foreignkey) {
12413
-
12414
11774
  var fk = col.foreignkey.table;
12415
11775
  var fktable = alasql.databases[fk.databaseid || databaseid].tables[fk.tableid];
12416
11776
  if (typeof fk.columnid === 'undefined') {
@@ -12420,7 +11780,6 @@ yy.CreateTable.prototype.execute = function (databaseid, params, cb) {
12420
11780
  throw new Error('FOREIGN KEY allowed only to tables with PRIMARY KEYs');
12421
11781
  }
12422
11782
  }
12423
-
12424
11783
  var fkfn = function (r) {
12425
11784
  var rr = {};
12426
11785
  if (typeof r[col.columnid] === 'undefined') {
@@ -12428,7 +11787,6 @@ yy.CreateTable.prototype.execute = function (databaseid, params, cb) {
12428
11787
  }
12429
11788
  rr[fk.columnid] = r[col.columnid];
12430
11789
  var addr = fktable.pk.onrightfn(rr);
12431
-
12432
11790
  if (!fktable.uniqs[fktable.pk.hh][addr]) {
12433
11791
  throw new Error(
12434
11792
  'Foreign key violation' //changed error message
@@ -12437,7 +11795,6 @@ yy.CreateTable.prototype.execute = function (databaseid, params, cb) {
12437
11795
  return true;
12438
11796
  };
12439
11797
  table.checks.push({fn: fkfn});
12440
-
12441
11798
  }
12442
11799
 
12443
11800
  if (col.onupdate) {
@@ -12451,9 +11808,7 @@ yy.CreateTable.prototype.execute = function (databaseid, params, cb) {
12451
11808
  table.defaultfns = ss.join(',');
12452
11809
  table.onupdatefns = uss.join(';');
12453
11810
 
12454
- // if(constraints) {
12455
11811
  constraints.forEach(function (con) {
12456
-
12457
11812
  var checkfn;
12458
11813
 
12459
11814
  if (con.type === 'PRIMARY KEY') {
@@ -12471,10 +11826,8 @@ yy.CreateTable.prototype.execute = function (databaseid, params, cb) {
12471
11826
  pk.hh = hash(pk.onrightfns);
12472
11827
  table.uniqs[pk.hh] = {};
12473
11828
  } else if (con.type === 'CHECK') {
12474
-
12475
11829
  checkfn = new Function('r', 'var y;return ' + con.expression.toJS('r', ''));
12476
11830
  } else if (con.type === 'UNIQUE') {
12477
-
12478
11831
  var uk = {};
12479
11832
  table.uk = table.uk || [];
12480
11833
  table.uk.push(uk);
@@ -12552,25 +11905,18 @@ yy.CreateTable.prototype.execute = function (databaseid, params, cb) {
12552
11905
  //Used in 420from queryfn when table.view = true!
12553
11906
  if (this.view && this.select) {
12554
11907
  table.view = true;
12555
-
12556
11908
  table.select = this.select.compile(this.table.databaseid || databaseid);
12557
11909
  }
12558
11910
 
12559
11911
  if (db.engineid) {
12560
-
12561
11912
  return alasql.engines[db.engineid].createTable(
12562
11913
  this.table.databaseid || databaseid,
12563
11914
  tableid,
12564
11915
  this.ifnotexists,
12565
11916
  cb
12566
11917
  );
12567
-
12568
- // return res1;
12569
11918
  }
12570
11919
 
12571
- // }
12572
- // if(table.pk) {
12573
-
12574
11920
  table.insert = function (r, orreplace) {
12575
11921
  var oldinserted = alasql.inserted;
12576
11922
  alasql.inserted = [r];
@@ -13315,53 +12661,34 @@ yy.CreateEdge.prototype.compile = function (databaseid) {
13315
12661
  var setfn = new Function('x,params,alasql', 'var y;' + s);
13316
12662
  }
13317
12663
 
13318
- /*
13319
- todo: handle content, select and default
13320
- else if(this.content) {
13321
-
13322
- } else if(this.select) {
13323
-
13324
- } else {
13325
- }
13326
- */
12664
+ const statement = (params, cb) => {
12665
+ let res = 0;
12666
+ let db = alasql.databases[dbid];
12667
+ let edge = {$id: db.counter++, $node: 'EDGE'};
12668
+ let v1 = fromfn(params, alasql);
12669
+ let v2 = tofn(params, alasql);
13327
12670
 
13328
- var statement = function (params, cb) {
13329
- var res = 0;
13330
- // CREATE VERTEX without parameters
13331
- var db = alasql.databases[dbid];
13332
- var edge = {$id: db.counter++, $node: 'EDGE'};
13333
- var v1 = fromfn(params, alasql);
13334
- var v2 = tofn(params, alasql);
13335
12671
  // Set link
13336
12672
  edge.$in = [v1.$id];
13337
12673
  edge.$out = [v2.$id];
13338
- // Set sides
13339
- if (v1.$out === undefined) {
13340
- v1.$out = [];
13341
- }
12674
+
12675
+ // Initialize and set sides
12676
+ v1.$out = v1.$out || [];
13342
12677
  v1.$out.push(edge.$id);
13343
12678
 
13344
- if (typeof v2.$in === undefined) {
13345
- v2.$in = [];
13346
- }
12679
+ v2.$in = v2.$in || [];
13347
12680
  v2.$in.push(edge.$id);
13348
12681
 
13349
12682
  // Save in objects
13350
12683
  db.objects[edge.$id] = edge;
13351
12684
  res = edge;
13352
- if (namefn) {
13353
- namefn(edge);
13354
- }
13355
-
13356
- if (setfn) {
13357
- setfn(edge, params, alasql);
13358
- }
13359
12685
 
13360
- if (cb) {
13361
- res = cb(res);
13362
- }
12686
+ // Optional functions
12687
+ namefn?.(edge);
12688
+ setfn?.(edge, params, alasql);
13363
12689
 
13364
- return res;
12690
+ // Callback
12691
+ return cb ? cb(res) : res;
13365
12692
  };
13366
12693
  return statement;
13367
12694
  };
@@ -13386,122 +12713,77 @@ yy.CreateGraph.prototype.execute = function (databaseid, params, cb) {
13386
12713
  }
13387
12714
 
13388
12715
  // stop;
13389
- this.graph.forEach(function (g) {
13390
- if (g.source) {
13391
- // GREATE EDGE
13392
- var e = {};
13393
- if (typeof g.as !== 'undefined') {
13394
- alasql.vars[g.as] = e;
13395
- }
13396
-
13397
- if (typeof g.prop !== 'undefined') {
13398
- // e[g.prop] = e;
13399
- // v.$id = g.prop; // We do not create $id for edge automatically
13400
- e.name = g.prop;
13401
- }
13402
- if (typeof g.sharp !== 'undefined') {
13403
- e.$id = g.sharp;
13404
- }
13405
- if (typeof g.name !== 'undefined') {
13406
- e.name = g.name;
13407
- }
13408
- if (typeof g.class !== 'undefined') {
13409
- e.$class = g.class;
13410
- }
13411
-
13412
- var db = alasql.databases[databaseid];
13413
- if (typeof e.$id === 'undefined') {
13414
- e.$id = db.counter++;
13415
- }
12716
+ this.graph.forEach(g => {
12717
+ if (!g.source) {
12718
+ createVertex(g);
12719
+ } else {
12720
+ // CREATE EDGE
12721
+ let e = {};
12722
+ if (g.as !== undefined) alasql.vars[g.as] = e;
12723
+ if (g.prop !== undefined) e.name = g.prop;
12724
+ if (g.sharp !== undefined) e.$id = g.sharp;
12725
+ if (g.name !== undefined) e.name = g.name;
12726
+ if (g.class !== undefined) e.$class = g.class;
12727
+
12728
+ let db = alasql.databases[databaseid];
12729
+ e.$id = e.$id !== undefined ? e.$id : db.counter++;
13416
12730
  e.$node = 'EDGE';
13417
- if (typeof g.json !== 'undefined') {
13418
- extend(e, new Function('params,alasql', 'var y;return ' + g.json.toJS())(params, alasql));
13419
- }
13420
12731
 
13421
- var v1;
13422
- if (g.source.vars) {
13423
- var vo = alasql.vars[g.source.vars];
13424
- if (typeof vo === 'object') {
13425
- v1 = vo;
13426
- } else {
13427
- v1 = db.objects[vo];
13428
- }
13429
- } else {
13430
- var av1 = g.source.sharp;
13431
- if (typeof av1 === 'undefined') {
13432
- av1 = g.source.prop;
13433
- }
13434
- v1 = alasql.databases[databaseid].objects[av1];
13435
- if (
13436
- typeof v1 === 'undefined' &&
13437
- alasql.options.autovertex &&
13438
- (typeof g.source.prop !== 'undefined' || typeof g.source.name !== 'undefined')
13439
- ) {
13440
- v1 = findVertex(g.source.prop || g.source.name);
13441
- if (typeof v1 === 'undefined') {
13442
- v1 = createVertex(g.source);
13443
- }
13444
- }
12732
+ if (g.json !== undefined) {
12733
+ Object.assign(e, new Function('params, alasql', `return ${g.json.toJS()}`)(params, alasql));
13445
12734
  }
13446
12735
 
13447
- var v2;
13448
- if (g.source.vars) {
13449
- var vo = alasql.vars[g.target.vars];
13450
- if (typeof vo === 'object') {
13451
- v2 = vo;
12736
+ const resolveVertex = (sourceOrTarget, isSource) => {
12737
+ let vertex, vo;
12738
+ if (sourceOrTarget.vars) {
12739
+ vo = alasql.vars[sourceOrTarget.vars];
12740
+ vertex = typeof vo === 'object' ? vo : db.objects[vo];
13452
12741
  } else {
13453
- v2 = db.objects[vo];
13454
- }
13455
- } else {
13456
- var av2 = g.target.sharp;
13457
- if (typeof av2 === 'undefined') {
13458
- av2 = g.target.prop;
13459
- }
13460
- v2 = alasql.databases[databaseid].objects[av2];
13461
- if (
13462
- typeof v2 === 'undefined' &&
13463
- alasql.options.autovertex &&
13464
- (typeof g.target.prop !== 'undefined' || typeof g.target.name !== 'undefined')
13465
- ) {
13466
- v2 = findVertex(g.target.prop || g.target.name);
13467
- if (typeof v2 === 'undefined') {
13468
- v2 = createVertex(g.target);
12742
+ let av = sourceOrTarget.sharp || sourceOrTarget.prop;
12743
+ vertex = db.objects[av];
12744
+ if (
12745
+ vertex === undefined &&
12746
+ alasql.options.autovertex &&
12747
+ (sourceOrTarget.prop || sourceOrTarget.name)
12748
+ ) {
12749
+ vertex =
12750
+ findVertex(sourceOrTarget.prop || sourceOrTarget.name) ||
12751
+ createVertex(sourceOrTarget);
13469
12752
  }
13470
12753
  }
13471
- }
12754
+ if (isSource && vertex && typeof vertex.$out === 'undefined') vertex.$out = [];
12755
+ if (!isSource && vertex && typeof vertex.$in === 'undefined') vertex.$in = [];
12756
+ return vertex;
12757
+ };
13472
12758
 
13473
- // Set link
12759
+ let v1 = resolveVertex(g.source, true);
12760
+ let v2 = resolveVertex(g.target, false);
12761
+
12762
+ // Set link and sides
13474
12763
  e.$in = [v1.$id];
13475
12764
  e.$out = [v2.$id];
13476
- // Set sides
13477
- if (typeof v1.$out === 'undefined') {
13478
- v1.$out = [];
13479
- }
13480
12765
  v1.$out.push(e.$id);
13481
- if (typeof v2.$in === 'undefined') {
13482
- v2.$in = [];
13483
- }
13484
12766
  v2.$in.push(e.$id);
13485
12767
 
13486
12768
  db.objects[e.$id] = e;
13487
- if (typeof e.$class !== 'undefined') {
13488
- if (typeof alasql.databases[databaseid].tables[e.$class] === 'undefined') {
13489
- throw new Error('No such class. Pleace use CREATE CLASS');
12769
+
12770
+ if (e.$class !== undefined) {
12771
+ let classTable = alasql.databases[databaseid].tables[e.$class];
12772
+ if (classTable === undefined) {
12773
+ throw new Error('No such class. Please use CREATE CLASS');
13490
12774
  } else {
13491
- // TODO - add insert()
13492
- alasql.databases[databaseid].tables[e.$class].data.push(e);
12775
+ classTable.data.push(e);
13493
12776
  }
13494
12777
  }
13495
12778
 
13496
12779
  res.push(e.$id);
13497
- } else {
13498
- createVertex(g);
13499
12780
  }
13500
12781
  });
13501
12782
 
13502
12783
  if (cb) {
13503
12784
  res = cb(res);
13504
12785
  }
12786
+
13505
12787
  return res;
13506
12788
 
13507
12789
  // Find vertex by name
@@ -13560,52 +12842,50 @@ yy.CreateGraph.prototype.execute = function (databaseid, params, cb) {
13560
12842
  return v;
13561
12843
  }
13562
12844
  };
13563
-
13564
12845
  yy.CreateGraph.prototype.compile1 = function (databaseid) {
13565
- var dbid = databaseid;
13566
- var fromfn = new Function('params,alasql', 'var y;return ' + this.from.toJS());
13567
- var tofn = new Function('params,alasql', 'var y;return ' + this.to.toJS());
12846
+ const dbid = databaseid;
12847
+ const fromfn = new Function('params, alasql', `return ${this.from.toJS()}`);
12848
+ const tofn = new Function('params, alasql', `return ${this.to.toJS()}`);
12849
+
12850
+ let namefn, setfn;
13568
12851
 
13569
12852
  // CREATE VERTEX "Name"
13570
- if (typeof this.name !== 'undefined') {
13571
- var s = 'x.name=' + this.name.toJS();
13572
- var namefn = new Function('x', s);
12853
+ if (this.name !== undefined) {
12854
+ const s = `x.name = ${this.name.toJS()}`;
12855
+ namefn = new Function('x', s);
13573
12856
  }
13574
12857
 
13575
12858
  if (this.sets && this.sets.length > 0) {
13576
- var s = this.sets
13577
- .map(function (st) {
13578
- return `x[${JSON.stringify(st.column.columnid)}]=` + st.expression.toJS('x', '');
13579
- })
12859
+ const s = this.sets
12860
+ .map(st => `x[${JSON.stringify(st.column.columnid)}] = ${st.expression.toJS('x', '')}`)
13580
12861
  .join(';');
13581
- var setfn = new Function('x,params,alasql', 'var y;' + s);
12862
+ setfn = new Function('x, params, alasql', `var y; ${s}`);
13582
12863
  }
13583
12864
 
13584
12865
  // Todo: handle content, select and default
13585
12866
 
13586
- var statement = function (params, cb) {
13587
- var res = 0;
13588
- // CREATE VERTEX without parameters
13589
- var db = alasql.databases[dbid];
13590
- var edge = {$id: db.counter++, $node: 'EDGE'};
13591
- var v1 = fromfn(params, alasql);
13592
- var v2 = tofn(params, alasql);
12867
+ const statement = (params, cb) => {
12868
+ let res = 0;
12869
+ const db = alasql.databases[dbid];
12870
+ const edge = {$id: db.counter++, $node: 'EDGE'};
12871
+ const v1 = fromfn(params, alasql);
12872
+ const v2 = tofn(params, alasql);
12873
+
13593
12874
  // Set link
13594
12875
  edge.$in = [v1.$id];
13595
12876
  edge.$out = [v2.$id];
12877
+
13596
12878
  // Set sides
13597
- if (typeof v1.$out === 'undefined') {
13598
- v1.$out = [];
13599
- }
12879
+ v1.$out = v1.$out || [];
13600
12880
  v1.$out.push(edge.$id);
13601
12881
 
13602
- if (typeof v2.$in === 'undefined') {
13603
- v2.$in = [];
13604
- }
12882
+ v2.$in = v2.$in || [];
13605
12883
  v2.$in.push(edge.$id);
12884
+
13606
12885
  // Save in objects
13607
12886
  db.objects[edge.$id] = edge;
13608
12887
  res = edge;
12888
+
13609
12889
  if (namefn) {
13610
12890
  namefn(edge);
13611
12891
  }
@@ -13634,13 +12914,13 @@ yy.AlterTable = function (params) {
13634
12914
  return Object.assign(this, params);
13635
12915
  };
13636
12916
  yy.AlterTable.prototype.toString = function () {
13637
- var s = 'ALTER TABLE ' + this.table.toString();
12917
+ let s = 'ALTER TABLE ' + this.table.toString();
13638
12918
  if (this.renameto) s += ' RENAME TO ' + this.renameto;
13639
12919
  return s;
13640
12920
  };
13641
12921
 
13642
12922
  yy.AlterTable.prototype.execute = function (databaseid, params, cb) {
13643
- var db = alasql.databases[databaseid];
12923
+ let db = alasql.databases[databaseid];
13644
12924
  db.dbversion = Date.now();
13645
12925
 
13646
12926
  if (this.renameto) {
@@ -13660,7 +12940,9 @@ yy.AlterTable.prototype.execute = function (databaseid, params, cb) {
13660
12940
  }
13661
12941
  if (cb) cb(res);
13662
12942
  return res;
13663
- } else if (this.addcolumn) {
12943
+ }
12944
+
12945
+ if (this.addcolumn) {
13664
12946
  db = alasql.databases[this.table.databaseid || databaseid];
13665
12947
  db.dbversion++;
13666
12948
  var tableid = this.table.tableid;
@@ -13686,15 +12968,15 @@ yy.AlterTable.prototype.execute = function (databaseid, params, cb) {
13686
12968
  table.columns.push(col);
13687
12969
  table.xcolumns[columnid] = col;
13688
12970
 
13689
- for (var i = 0, ilen = table.data.length; i < ilen; i++) {
13690
-
12971
+ for (let i = 0, ilen = table.data.length; i < ilen; i++) {
13691
12972
  table.data[i][columnid] = defaultfn();
13692
12973
  }
13693
12974
 
13694
- // TODO
13695
12975
  return cb ? cb(1) : 1;
13696
- } else if (this.modifycolumn) {
13697
- var db = alasql.databases[this.table.databaseid || databaseid];
12976
+ }
12977
+
12978
+ if (this.modifycolumn) {
12979
+ let db = alasql.databases[this.table.databaseid || databaseid];
13698
12980
  db.dbversion++;
13699
12981
  var tableid = this.table.tableid;
13700
12982
  var table = db.tables[tableid];
@@ -13712,10 +12994,11 @@ yy.AlterTable.prototype.execute = function (databaseid, params, cb) {
13712
12994
  col.dbprecision = this.dbprecision;
13713
12995
  col.dbenum = this.dbenum;
13714
12996
 
13715
- // TODO
13716
12997
  return cb ? cb(1) : 1;
13717
- } else if (this.renamecolumn) {
13718
- var db = alasql.databases[this.table.databaseid || databaseid];
12998
+ }
12999
+
13000
+ if (this.renamecolumn) {
13001
+ let db = alasql.databases[this.table.databaseid || databaseid];
13719
13002
  db.dbversion++;
13720
13003
 
13721
13004
  var tableid = this.table.tableid;
@@ -13742,16 +13025,16 @@ yy.AlterTable.prototype.execute = function (databaseid, params, cb) {
13742
13025
  delete table.xcolumns[columnid];
13743
13026
 
13744
13027
  for (var i = 0, ilen = table.data.length; i < ilen; i++) {
13745
-
13746
13028
  table.data[i][tocolumnid] = table.data[i][columnid];
13747
13029
  delete table.data[i][columnid];
13748
13030
  }
13749
13031
  return table.data.length;
13750
- } else {
13751
- return cb ? cb(0) : 0;
13752
13032
  }
13753
- } else if (this.dropcolumn) {
13754
- var db = alasql.databases[this.table.databaseid || databaseid];
13033
+ return cb ? cb(0) : 0;
13034
+ }
13035
+
13036
+ if (this.dropcolumn) {
13037
+ let db = alasql.databases[this.table.databaseid || databaseid];
13755
13038
  db.dbversion++;
13756
13039
  var tableid = this.table.tableid;
13757
13040
  var table = db.tables[tableid];
@@ -13777,10 +13060,11 @@ yy.AlterTable.prototype.execute = function (databaseid, params, cb) {
13777
13060
  for (i = 0, ilen = table.data.length; i < ilen; i++) {
13778
13061
  delete table.data[i][columnid];
13779
13062
  }
13063
+
13780
13064
  return cb ? cb(table.data.length) : table.data.length;
13781
- } else {
13782
- throw Error('Unknown ALTER TABLE method');
13783
13065
  }
13066
+
13067
+ throw Error('Unknown ALTER TABLE method');
13784
13068
  };
13785
13069
  /*
13786
13070
  //
@@ -14380,40 +13664,41 @@ yy.CreateTrigger.prototype.toString = function () {
14380
13664
  return s;
14381
13665
  };
14382
13666
 
13667
+ const validTriggers = [
13668
+ 'beforeinsert',
13669
+ 'afterinsert',
13670
+ 'insteadofinsert',
13671
+ 'beforedelete',
13672
+ 'afterdelete',
13673
+ 'insteadofdelete',
13674
+ 'beforeupdate',
13675
+ 'afterupdate',
13676
+ 'insteadofupdate',
13677
+ ];
13678
+
14383
13679
  yy.CreateTrigger.prototype.execute = function (databaseid, params, cb) {
14384
- var res = 1; // No tables removed
14385
- var triggerid = this.trigger;
13680
+ let res = 1; // No tables removed
13681
+ const triggerid = this.trigger;
14386
13682
  databaseid = this.table.databaseid || databaseid;
14387
- var db = alasql.databases[databaseid];
14388
- var tableid = this.table.tableid;
13683
+ const db = alasql.databases[databaseid];
13684
+ const {tableid} = this.table;
14389
13685
 
14390
- var trigger = {
13686
+ const trigger = {
14391
13687
  action: this.action,
14392
13688
  when: this.when,
14393
13689
  statement: this.statement,
14394
13690
  funcid: this.funcid,
14395
- tableid: this.table.tableid,
13691
+ tableid,
14396
13692
  };
14397
13693
 
14398
13694
  db.triggers[triggerid] = trigger;
14399
- if (trigger.action == 'INSERT' && trigger.when == 'BEFORE') {
14400
- db.tables[tableid].beforeinsert[triggerid] = trigger;
14401
- } else if (trigger.action == 'INSERT' && trigger.when == 'AFTER') {
14402
- db.tables[tableid].afterinsert[triggerid] = trigger;
14403
- } else if (trigger.action == 'INSERT' && trigger.when == 'INSTEADOF') {
14404
- db.tables[tableid].insteadofinsert[triggerid] = trigger;
14405
- } else if (trigger.action == 'DELETE' && trigger.when == 'BEFORE') {
14406
- db.tables[tableid].beforedelete[triggerid] = trigger;
14407
- } else if (trigger.action == 'DELETE' && trigger.when == 'AFTER') {
14408
- db.tables[tableid].afterdelete[triggerid] = trigger;
14409
- } else if (trigger.action == 'DELETE' && trigger.when == 'INSTEADOF') {
14410
- db.tables[tableid].insteadofdelete[triggerid] = trigger;
14411
- } else if (trigger.action == 'UPDATE' && trigger.when == 'BEFORE') {
14412
- db.tables[tableid].beforeupdate[triggerid] = trigger;
14413
- } else if (trigger.action == 'UPDATE' && trigger.when == 'AFTER') {
14414
- db.tables[tableid].afterupdate[triggerid] = trigger;
14415
- } else if (trigger.action == 'UPDATE' && trigger.when == 'INSTEADOF') {
14416
- db.tables[tableid].insteadofupdate[triggerid] = trigger;
13695
+ const actionKey = `${this.when}${this.action}`.toLowerCase();
13696
+
13697
+ if (validTriggers.includes(actionKey)) {
13698
+ // Ensure the existence of db.tables[tableid] and db.tables[tableid][actionKey]
13699
+ db.tables[tableid] = db.tables[tableid] || {};
13700
+ db.tables[tableid][actionKey] = db.tables[tableid][actionKey] || {};
13701
+ db.tables[tableid][actionKey][triggerid] = trigger;
14417
13702
  }
14418
13703
 
14419
13704
  if (cb) res = cb(res);
@@ -14438,28 +13723,26 @@ yy.DropTrigger.prototype.toString = function () {
14438
13723
  DROP TRIGGER one;
14439
13724
  */
14440
13725
  yy.DropTrigger.prototype.execute = function (databaseid, params, cb) {
14441
- var res = 0; // No tables removed
14442
- var db = alasql.databases[databaseid];
14443
- var triggerid = this.trigger;
13726
+ let res = 0; // No tables removed
13727
+ const db = alasql.databases[databaseid];
13728
+ const triggerid = this.trigger;
14444
13729
 
14445
- // get the trigger
14446
- var trigger = db.triggers[triggerid];
13730
+ // Get the trigger
13731
+ const trigger = db.triggers[triggerid];
14447
13732
 
14448
- // if the trigger exists
13733
+ // If the trigger exists
14449
13734
  if (trigger) {
14450
- var tableid = db.triggers[triggerid].tableid;
13735
+ const {tableid} = trigger;
14451
13736
 
14452
13737
  if (tableid) {
14453
13738
  res = 1;
14454
- delete db.tables[tableid].beforeinsert[triggerid];
14455
- delete db.tables[tableid].afterinsert[triggerid];
14456
- delete db.tables[tableid].insteadofinsert[triggerid];
14457
- delete db.tables[tableid].beforedelete[triggerid];
14458
- delete db.tables[tableid].afterdelete[triggerid];
14459
- delete db.tables[tableid].insteadofdelete[triggerid];
14460
- delete db.tables[tableid].beforeupdate[triggerid];
14461
- delete db.tables[tableid].afterupdate[triggerid];
14462
- delete db.tables[tableid].insteadofupdate[triggerid];
13739
+
13740
+ // Delete the trigger from all trigger points
13741
+ validTriggers.forEach(point => {
13742
+ delete db.tables[tableid][point][triggerid];
13743
+ });
13744
+
13745
+ // Finally, delete the trigger itself
14463
13746
  delete db.triggers[triggerid];
14464
13747
  } else {
14465
13748
  throw new Error('Trigger Table not found');
@@ -14467,6 +13750,7 @@ yy.DropTrigger.prototype.execute = function (databaseid, params, cb) {
14467
13750
  } else {
14468
13751
  throw new Error('Trigger not found');
14469
13752
  }
13753
+
14470
13754
  if (cb) res = cb(res);
14471
13755
  return res;
14472
13756
  };
@@ -14488,16 +13772,12 @@ yy.Delete.prototype.toString = function () {
14488
13772
  };
14489
13773
 
14490
13774
  yy.Delete.prototype.compile = function (databaseid) {
14491
-
14492
13775
  databaseid = this.table.databaseid || databaseid;
14493
13776
  var tableid = this.table.tableid;
14494
13777
  var statement;
14495
13778
  var db = alasql.databases[databaseid];
14496
13779
 
14497
13780
  if (this.where) {
14498
-
14499
- // this.query = {};
14500
-
14501
13781
  if (this.exists) {
14502
13782
  this.existsfn = this.exists.map(function (ex) {
14503
13783
  var nq = ex.compile(databaseid);
@@ -14505,6 +13785,7 @@ yy.Delete.prototype.compile = function (databaseid) {
14505
13785
  return nq;
14506
13786
  });
14507
13787
  }
13788
+
14508
13789
  if (this.queries) {
14509
13790
  this.queriesfn = this.queries.map(function (q) {
14510
13791
  var nq = q.compile(databaseid);
@@ -14513,10 +13794,6 @@ yy.Delete.prototype.compile = function (databaseid) {
14513
13794
  });
14514
13795
  }
14515
13796
 
14516
- // try {
14517
-
14518
- // var query = {};
14519
-
14520
13797
  var wherefn = new Function(
14521
13798
  'r,params,alasql',
14522
13799
  'var y;return (' + this.where.toJS('r', '') + ')'
@@ -14542,7 +13819,6 @@ yy.Delete.prototype.compile = function (databaseid) {
14542
13819
  }
14543
13820
 
14544
13821
  var table = db.tables[tableid];
14545
- // table.dirty = true;
14546
13822
  var orignum = table.data.length;
14547
13823
 
14548
13824
  var newtable = [];
@@ -14554,9 +13830,10 @@ yy.Delete.prototype.compile = function (databaseid) {
14554
13830
  } else {
14555
13831
  // Simply do not push
14556
13832
  }
14557
- } else newtable.push(table.data[i]);
13833
+ } else {
13834
+ newtable.push(table.data[i]);
13835
+ }
14558
13836
  }
14559
- // table.data = table.data.filter(function(r){return !;});
14560
13837
  table.data = newtable;
14561
13838
 
14562
13839
  // Trigger prevent functionality
@@ -14580,15 +13857,10 @@ yy.Delete.prototype.compile = function (databaseid) {
14580
13857
  alasql.engines[db.engineid].saveTableData(databaseid, tableid);
14581
13858
  }
14582
13859
 
14583
- if (cb) cb(res);
13860
+ if (cb) res = cb(res);
13861
+
14584
13862
  return res;
14585
13863
  };
14586
- // .bind(query);
14587
-
14588
- // if(!this.queries) return;
14589
- // query.queriesfn = this.queries.map(function(q) {
14590
- // return q.compile(alasql.useid);
14591
- // });
14592
13864
  } else {
14593
13865
  statement = function (params, cb) {
14594
13866
  if (alasql.options.autocommit && db.engineid) {
@@ -14598,7 +13870,6 @@ yy.Delete.prototype.compile = function (databaseid) {
14598
13870
  var table = db.tables[tableid];
14599
13871
  table.dirty = true;
14600
13872
  var orignum = db.tables[tableid].data.length;
14601
- //table.deleteall();
14602
13873
  // Delete all records from the array
14603
13874
  db.tables[tableid].data.length = 0;
14604
13875
 
@@ -14751,35 +14022,30 @@ yy.Merge = function (params) {
14751
14022
  return Object.assign(this, params);
14752
14023
  };
14753
14024
  yy.Merge.prototype.toString = function () {
14754
- var s = 'MERGE ';
14755
- s += this.into.tableid + ' ';
14756
- if (this.into.as) s += 'AS ' + this.into.as + ' ';
14757
- s += 'USING ' + this.using.tableid + ' ';
14758
- if (this.using.as) s += 'AS ' + this.using.as + ' ';
14759
- s += 'ON ' + this.on.toString() + ' ';
14760
- this.matches.forEach(function (m) {
14025
+ let s = `MERGE ${this.into.tableid} `;
14026
+ if (this.into.as) s += `AS ${this.into.as} `;
14027
+ s += `USING ${this.using.tableid} `;
14028
+ if (this.using.as) s += `AS ${this.using.as} `;
14029
+ s += `ON ${this.on.toString()} `;
14030
+
14031
+ this.matches.forEach(m => {
14761
14032
  s += 'WHEN ';
14762
14033
  if (!m.matched) s += 'NOT ';
14763
14034
  s += 'MATCHED ';
14764
14035
  if (m.bytarget) s += 'BY TARGET ';
14765
14036
  if (m.bysource) s += 'BY SOURCE ';
14766
- if (m.expr) s += 'AND' + ' ' + m.expr.toString() + ' ';
14037
+ if (m.expr) s += `AND ${m.expr.toString()} `;
14767
14038
  s += 'THEN ';
14768
14039
  if (m.action.delete) s += 'DELETE ';
14769
14040
  if (m.action.insert) {
14770
14041
  s += 'INSERT ';
14771
- if (m.action.columns) s += '(' + m.action.columns.toString() + ') ';
14772
- if (m.action.values) s += 'VALUES (' + m.action.values.toString() + ') ';
14042
+ if (m.action.columns) s += `(${m.action.columns.toString()}) `;
14043
+ if (m.action.values) s += `VALUES (${m.action.values.toString()}) `;
14773
14044
  if (m.action.defaultvalues) s += 'DEFAULT VALUES ';
14774
14045
  }
14775
14046
  if (m.action.update) {
14776
14047
  s += 'UPDATE ';
14777
- s +=
14778
- m.action.update
14779
- .map(function (u) {
14780
- return u.toString();
14781
- })
14782
- .join(',') + ' ';
14048
+ s += m.action.update.map(u => u.toString()).join(', ') + ' ';
14783
14049
  }
14784
14050
  });
14785
14051
 
@@ -14808,25 +14074,19 @@ yy.CreateDatabase = function (params) {
14808
14074
  return Object.assign(this, params);
14809
14075
  };
14810
14076
  yy.CreateDatabase.prototype.toString = function () {
14811
- var s = 'CREATE';
14812
- if (this.engineid) s += ' ' + this.engineid;
14813
- s += ' DATABASE';
14814
- if (this.ifnotexists) s += ' IF NOT EXISTS';
14815
- s += ' ' + this.databaseid;
14077
+ let s = 'CREATE '; // Ensure there's a space after CREATE
14078
+ if (this.engineid) s += `${this.engineid} `;
14079
+ s += 'DATABASE ';
14080
+ if (this.ifnotexists) s += 'IF NOT EXISTS ';
14081
+ s += `${this.databaseid} `;
14082
+
14816
14083
  if (this.args && this.args.length > 0) {
14817
- s +=
14818
- '(' +
14819
- this.args
14820
- .map(function (arg) {
14821
- return arg.toString();
14822
- })
14823
- .join(', ') +
14824
- ')';
14084
+ s += `(${this.args.map(arg => arg.toString()).join(', ')}) `;
14825
14085
  }
14826
- if (this.as) s += ' AS ' + this.as;
14086
+ if (this.as) s += `AS ${this.as}`;
14827
14087
  return s;
14828
14088
  };
14829
- //yy.CreateDatabase.prototype.compile = returnUndefined;
14089
+
14830
14090
  yy.CreateDatabase.prototype.execute = function (databaseid, params, cb) {
14831
14091
  var args;
14832
14092
  if (this.args && this.args.length > 0) {
@@ -14861,25 +14121,21 @@ yy.AttachDatabase = function (params) {
14861
14121
  return Object.assign(this, params);
14862
14122
  };
14863
14123
  yy.AttachDatabase.prototype.toString = function (args) {
14864
- var s = 'ATTACH';
14865
- if (this.engineid) s += ' ' + this.engineid;
14866
- s += ' DATABASE' + ' ' + this.databaseid;
14124
+ let s = 'ATTACH';
14125
+ if (this.engineid) s += ` ${this.engineid}`;
14126
+ s += ` DATABASE ${this.databaseid}`;
14867
14127
  // TODO add params
14868
14128
  if (args) {
14869
14129
  s += '(';
14870
14130
  if (args.length > 0) {
14871
- s += args
14872
- .map(function (arg) {
14873
- return arg.toString();
14874
- })
14875
- .join(', ');
14131
+ s += args.map(arg => arg.toString()).join(', ');
14876
14132
  }
14877
14133
  s += ')';
14878
14134
  }
14879
- if (this.as) s += ' AS' + ' ' + this.as;
14135
+ if (this.as) s += ` AS ${this.as}`;
14880
14136
  return s;
14881
14137
  };
14882
- //yy.CreateDatabase.prototype.compile = returnUndefined;
14138
+
14883
14139
  yy.AttachDatabase.prototype.execute = function (databaseid, params, cb) {
14884
14140
  if (!alasql.engines[this.engineid]) {
14885
14141
  throw new Error('Engine "' + this.engineid + '" is not defined.');
@@ -14950,8 +14206,6 @@ yy.DetachDatabase.prototype.execute = function (databaseid, params, cb) {
14950
14206
  }
14951
14207
  if (cb) cb(res);
14952
14208
  return res;
14953
- // var res = alasql.engines[this.engineid].attachDatabase(this.databaseid, this.as, cb);
14954
- // return res;
14955
14209
  };
14956
14210
 
14957
14211
  // USE DATABSE databaseid
@@ -14989,22 +14243,22 @@ yy.DropDatabase.prototype.execute = function (databaseid, params, cb) {
14989
14243
  if (this.engineid) {
14990
14244
  return alasql.engines[this.engineid].dropDatabase(this.databaseid, this.ifexists, cb);
14991
14245
  }
14992
- var res;
14246
+ let res;
14993
14247
 
14994
- var dbid = this.databaseid;
14248
+ const dbid = this.databaseid;
14995
14249
 
14996
14250
  if (dbid === alasql.DEFAULTDATABASEID) {
14997
14251
  throw new Error('Drop of default database is prohibited');
14998
14252
  }
14999
14253
  if (!alasql.databases[dbid]) {
15000
14254
  if (!this.ifexists) {
15001
- throw new Error("Database '" + dbid + "' does not exist");
14255
+ throw new Error(`Database '${dbid}' does not exist`);
15002
14256
  } else {
15003
14257
  res = 0;
15004
14258
  }
15005
14259
  } else {
15006
14260
  if (alasql.databases[dbid].engineid) {
15007
- throw new Error("Cannot drop database '" + dbid + "', because it is attached. Detach it.");
14261
+ throw new Error(`Cannot drop database '${dbid}', because it is attached. Detach it.`);
15008
14262
  }
15009
14263
 
15010
14264
  delete alasql.databases[dbid];
@@ -15028,24 +14282,22 @@ yy.Declare = function (params) {
15028
14282
  return Object.assign(this, params);
15029
14283
  };
15030
14284
  yy.Declare.prototype.toString = function () {
15031
- var s = 'DECLARE ';
14285
+ let s = 'DECLARE ';
15032
14286
  if (this.declares && this.declares.length > 0) {
15033
- s = this.declares
15034
- .map(function (declare) {
15035
- var s = '';
15036
- s += '@' + declare.variable + ' ';
15037
- s += declare.dbtypeid;
15038
- if (this.dbsize) {
15039
- s += '(' + this.dbsize;
15040
- if (this.dbprecision) {
15041
- s += ',' + this.dbprecision;
14287
+ s += this.declares
14288
+ .map(declare => {
14289
+ let declareStr = `@${declare.variable} ${declare.dbtypeid}`;
14290
+ if (declare.dbsize) {
14291
+ declareStr += `(${declare.dbsize}`;
14292
+ if (declare.dbprecision) {
14293
+ declareStr += `,${declare.dbprecision}`;
15042
14294
  }
15043
- s += ')';
14295
+ declareStr += ')';
15044
14296
  }
15045
14297
  if (declare.expression) {
15046
- s += ' = ' + declare.expression.toString();
14298
+ declareStr += ` = ${declare.expression.toString()}`;
15047
14299
  }
15048
- return s;
14300
+ return declareStr;
15049
14301
  })
15050
14302
  .join(',');
15051
14303
  }
@@ -15254,76 +14506,67 @@ yy.SetVariable.prototype.toString = function () {
15254
14506
  };
15255
14507
 
15256
14508
  yy.SetVariable.prototype.execute = function (databaseid, params, cb) {
15257
-
15258
- if (typeof this.value != 'undefined') {
15259
- var val = this.value;
15260
- if (val == 'ON') val = true;
15261
- else if (val == 'OFF') val = false;
15262
- // if(this.method == '@') {
14509
+ if (typeof this.value !== 'undefined') {
14510
+ let val = this.value;
14511
+ if (val === 'ON') val = true;
14512
+ else if (val === 'OFF') val = false;
15263
14513
  alasql.options[this.variable] = val;
15264
- // } else {
15265
- // params[this.variable] = val;
15266
- // }
15267
14514
  } else if (this.expression) {
15268
14515
  if (this.exists) {
15269
- this.existsfn = this.exists.map(function (ex) {
15270
- var nq = ex.compile(databaseid);
14516
+ this.existsfn = this.exists.map(ex => {
14517
+ let nq = ex.compile(databaseid);
15271
14518
  if (nq.query && !nq.query.modifier) nq.query.modifier = 'RECORDSET';
15272
14519
  return nq;
15273
- // return ex.compile(databaseid);
15274
- // TODO Include modifier
15275
14520
  });
15276
14521
  }
15277
14522
  if (this.queries) {
15278
- this.queriesfn = this.queries.map(function (q) {
15279
- var nq = q.compile(databaseid);
14523
+ this.queriesfn = this.queries.map(q => {
14524
+ let nq = q.compile(databaseid);
15280
14525
  if (nq.query && !nq.query.modifier) nq.query.modifier = 'RECORDSET';
15281
14526
  return nq;
15282
- // TODO Include modifier
15283
14527
  });
15284
14528
  }
15285
14529
 
15286
- var res = new Function(
15287
- 'params,alasql',
14530
+ let res = new Function(
14531
+ 'params, alasql',
15288
14532
  'return ' + this.expression.toJS('({})', '', null)
15289
14533
  ).bind(this)(params, alasql);
14534
+
15290
14535
  if (alasql.declares[this.variable]) {
15291
14536
  res = alasql.stdfn.CONVERT(res, alasql.declares[this.variable]);
15292
14537
  }
14538
+
15293
14539
  if (this.props && this.props.length > 0) {
15294
- if (this.method == '@') {
15295
- var fs = "alasql.vars['" + this.variable + "']";
14540
+ let fs;
14541
+ if (this.method === '@') {
14542
+ fs = `alasql.vars['${this.variable}']`;
15296
14543
  } else {
15297
- var fs = "params['" + this.variable + "']";
15298
- }
15299
- fs += this.props
15300
- .map(function (prop) {
15301
- if (typeof prop == 'string') {
15302
- return "['" + prop + "']";
15303
- } else if (typeof prop == 'number') {
15304
- return '[' + prop + ']';
15305
- } else {
15306
-
15307
- return '[' + prop.toJS() + ']';
15308
- // } else {
15309
-
15310
- // throw new Error('Wrong SET property');
15311
- }
15312
- })
15313
- .join();
14544
+ fs = `params['${this.variable}']`;
14545
+ }
14546
+ this.props.forEach(prop => {
14547
+ if (typeof prop === 'string') {
14548
+ fs += `['${prop}']`;
14549
+ } else if (typeof prop === 'number') {
14550
+ fs += `[${prop}]`;
14551
+ } else {
14552
+ // Assuming prop.toJS() is a method that converts prop to a JavaScript expression.
14553
+ fs += `[${prop.toJS()}]`;
14554
+ }
14555
+ });
15314
14556
 
15315
- new Function('value,params,alasql', 'var y;' + fs + '=value')(res, params, alasql);
14557
+ new Function('value, params, alasql', `${fs} = value`)(res, params, alasql);
15316
14558
  } else {
15317
- if (this.method == '@') {
14559
+ if (this.method === '@') {
15318
14560
  alasql.vars[this.variable] = res;
15319
14561
  } else {
15320
14562
  params[this.variable] = res;
15321
14563
  }
15322
14564
  }
15323
14565
  }
15324
- var res = 1;
15325
- if (cb) res = cb(res);
15326
- return res;
14566
+
14567
+ let result = 1;
14568
+ if (cb) result = cb(result);
14569
+ return result;
15327
14570
  };
15328
14571
  alasql.test = function (name, times, fn) {
15329
14572
  if (arguments.length === 0) {
@@ -15645,7 +14888,7 @@ yy.BeginTransaction.prototype.execute = function (databaseid, params, cb) {
15645
14888
  } else {
15646
14889
  // alasql commit!!!
15647
14890
  }
15648
- if (cb) cb(res);
14891
+ if (cb) res = cb(res);
15649
14892
  return res;
15650
14893
  };
15651
14894
 
@@ -15663,7 +14906,7 @@ yy.CommitTransaction.prototype.execute = function (databaseid, params, cb) {
15663
14906
  } else {
15664
14907
  // alasql commit!!!
15665
14908
  }
15666
- if (cb) cb(res);
14909
+ if (cb) res = cb(res);
15667
14910
  return res;
15668
14911
  };
15669
14912
 
@@ -15681,7 +14924,7 @@ yy.RollbackTransaction.prototype.execute = function (databaseid, params, cb) {
15681
14924
  } else {
15682
14925
  // alasql commit!!!
15683
14926
  }
15684
- if (cb) cb(res);
14927
+ if (cb) res = cb(res);
15685
14928
  return res;
15686
14929
  };
15687
14930
  if (alasql.options.tsql) {
@@ -16776,10 +16019,14 @@ alasql.into.XLSX = function (filename, opts, data, columns, cb) {
16776
16019
  var dataLength = Object.keys(data).length;
16777
16020
 
16778
16021
  // Generate columns if they are not defined
16779
- if ((!columns || columns.length == 0) && dataLength > 0) {
16780
- columns = Object.keys(data[0]).map(function (columnid) {
16781
- return {columnid: columnid};
16782
- });
16022
+ if (!columns || columns.length == 0) {
16023
+ if (dataLength > 0) {
16024
+ columns = Object.keys(data[0]).map(function (columnid) {
16025
+ return {columnid: columnid};
16026
+ });
16027
+ } else {
16028
+ columns = [];
16029
+ }
16783
16030
  }
16784
16031
 
16785
16032
  var cells = {};
@@ -16893,9 +16140,8 @@ alasql.into.XLSX = function (filename, opts, data, columns, cb) {
16893
16140
 
16894
16141
  alasql.from.METEOR = function (filename, opts, cb, idx, query) {
16895
16142
  var res = filename.find(opts).fetch();
16896
- if (cb) {
16897
- res = cb(res, idx, query);
16898
- }
16143
+ if (cb) res = cb(res, idx, query);
16144
+
16899
16145
  return res;
16900
16146
  };
16901
16147
 
@@ -16909,9 +16155,7 @@ alasql.from.TABLETOP = function (key, opts, cb, idx, query) {
16909
16155
  alasql.utils.extend(opt, opts);
16910
16156
  opt.callback = function (data) {
16911
16157
  res = data;
16912
- if (cb) {
16913
- res = cb(res, idx, query);
16914
- }
16158
+ if (cb) res = cb(res, idx, query);
16915
16159
  };
16916
16160
 
16917
16161
  Tabletop.init(opt);
@@ -16990,11 +16234,8 @@ alasql.from.FILE = function (filename, opts, cb, idx, query) {
16990
16234
  }
16991
16235
 
16992
16236
  var parts = fname.split('.');
16993
-
16994
16237
  var ext = parts[parts.length - 1].toUpperCase();
16995
-
16996
16238
  if (alasql.from[ext]) {
16997
-
16998
16239
  return alasql.from[ext](filename, opts, cb, idx, query);
16999
16240
  } else {
17000
16241
  throw new Error('Cannot recognize file type for loading');
@@ -17620,14 +16861,11 @@ yy.Source.prototype.toString = function () {
17620
16861
 
17621
16862
  // SOURCE FILE
17622
16863
  yy.Source.prototype.execute = function (databaseid, params, cb) {
17623
-
17624
16864
  var res;
17625
16865
  loadFile(
17626
16866
  this.url,
17627
16867
  !!cb,
17628
16868
  function (data) {
17629
-
17630
- // res = 1;
17631
16869
  res = alasql(data);
17632
16870
  if (cb) res = cb(res);
17633
16871
  return res;
@@ -17677,15 +16915,12 @@ yy.Require.prototype.execute = function (databaseid, params, cb) {
17677
16915
  var self = this;
17678
16916
  var res = 0;
17679
16917
  var ss = '';
17680
-
17681
16918
  if (this.paths && this.paths.length > 0) {
17682
16919
  this.paths.forEach(function (path) {
17683
16920
  loadFile(path.value, !!cb, function (data) {
17684
16921
  res++;
17685
-
17686
16922
  ss += data;
17687
16923
  if (res < self.paths.length) return;
17688
-
17689
16924
  new Function('params,alasql', ss)(params, alasql);
17690
16925
  if (cb) res = cb(res);
17691
16926
  });
@@ -17699,7 +16934,6 @@ yy.Require.prototype.execute = function (databaseid, params, cb) {
17699
16934
  res++;
17700
16935
  ss += data;
17701
16936
  if (res < self.plugins.length) return;
17702
-
17703
16937
  new Function('params,alasql', ss)(params, alasql);
17704
16938
  alasql.plugins[plugin] = true; // Plugin is loaded
17705
16939
  if (cb) res = cb(res);
@@ -17730,11 +16964,7 @@ yy.Source.prototype.toString = function () {
17730
16964
 
17731
16965
  // SOURCE FILE
17732
16966
  yy.Assert.prototype.execute = function (databaseid) {
17733
-
17734
16967
  if (!deepEqual(alasql.res, this.value)) {
17735
- // if(this.message) {
17736
- // throw this.
17737
- // } else {
17738
16968
  throw new Error(
17739
16969
  (this.message || 'Assert wrong') +
17740
16970
  ': ' +
@@ -17742,7 +16972,6 @@ yy.Assert.prototype.execute = function (databaseid) {
17742
16972
  ' == ' +
17743
16973
  JSON.stringify(this.value)
17744
16974
  );
17745
- // }
17746
16975
  }
17747
16976
  return 1;
17748
16977
  };
@@ -18284,7 +17513,6 @@ LS.attachDatabase = function (lsdbid, databaseid, args, params, cb) {
18284
17513
  if (db.tables) {
18285
17514
  for (var tbid in db.tables) {
18286
17515
  LS.restoreTable(databaseid, tbid);
18287
- // db.tables[tbid].data = LS.get(db.lsdbid+'.'+tbid);
18288
17516
  }
18289
17517
  }
18290
17518
  }
@@ -18460,9 +17688,7 @@ LS.intoTable = function (databaseid, tableid, value, columns, cb) {
18460
17688
  }
18461
17689
  if (!tb.data) tb.data = [];
18462
17690
  tb.data = tb.data.concat(value);
18463
- // LS.set(lsdbid+'.'+tableid, tb);
18464
17691
  LS.storeTable(databaseid, tableid);
18465
-
18466
17692
  if (cb) res = cb(res);
18467
17693
 
18468
17694
  return res;
@@ -18602,7 +17828,6 @@ SQLITE.attachDatabase = function (sqldbid, dbid, args, params, cb) {
18602
17828
  db.tables[tbl[1]] = {};
18603
17829
  var columns = (db.tables[tbl[1]].columns = []);
18604
17830
  var ast = alasql.parse(tbl[4]);
18605
-
18606
17831
  var coldefs = ast.statements[0].columns;
18607
17832
  if (coldefs && coldefs.length > 0) {
18608
17833
  coldefs.forEach(function (cd) {
@@ -18679,12 +17904,9 @@ SQLITE.intoTable = function (databaseid, tableid, value, columns, cb) {
18679
17904
  var FS = (alasql.engines.FILESTORAGE = alasql.engines.FILE = function () {});
18680
17905
 
18681
17906
  FS.createDatabase = function (fsdbid, args, ifnotexists, dbid, cb) {
18682
-
18683
17907
  var res = 1;
18684
17908
  var filename = args[0].value;
18685
-
18686
17909
  alasql.utils.fileExists(filename, function (fex) {
18687
-
18688
17910
  if (fex) {
18689
17911
  if (ifnotexists) {
18690
17912
  res = 0;
@@ -18745,14 +17967,12 @@ FS.dropDatabase = function (fsdbid, ifexists, cb) {
18745
17967
  };
18746
17968
 
18747
17969
  FS.attachDatabase = function (fsdbid, dbid, args, params, cb) {
18748
-
18749
17970
  var res = 1;
18750
17971
  if (alasql.databases[dbid]) {
18751
17972
  throw new Error('Unable to attach database as "' + dbid + '" because it already exists');
18752
17973
  }
18753
17974
  var db = new alasql.Database(dbid || fsdbid);
18754
17975
  db.engineid = 'FILESTORAGE';
18755
- // db.fsdbid = fsdbid;
18756
17976
  db.filename = args[0].value;
18757
17977
  loadFile(db.filename, !!cb, function (s) {
18758
17978
  try {
@@ -18793,7 +18013,6 @@ FS.createTable = function (databaseid, tableid, ifnotexists, cb) {
18793
18013
  };
18794
18014
 
18795
18015
  FS.updateFile = function (databaseid) {
18796
-
18797
18016
  var db = alasql.databases[databaseid];
18798
18017
  if (db.issaving) {
18799
18018
  db.postsave = true;
@@ -18829,7 +18048,6 @@ FS.dropTable = function (databaseid, tableid, ifexists, cb) {
18829
18048
  };
18830
18049
 
18831
18050
  FS.fromTable = function (databaseid, tableid, cb, idx, query) {
18832
-
18833
18051
  var db = alasql.databases[databaseid];
18834
18052
  var res = db.data[tableid];
18835
18053
  if (cb) res = cb(res, idx, query);
@@ -18860,7 +18078,6 @@ FS.saveTableData = function (databaseid, tableid) {
18860
18078
  };
18861
18079
 
18862
18080
  FS.commit = function (databaseid, cb) {
18863
-
18864
18081
  var db = alasql.databases[databaseid];
18865
18082
  var fsdb = {tables: {}};
18866
18083
  if (db.tables) {
@@ -18879,9 +18096,6 @@ FS.rollback = function (databaseid, cb) {
18879
18096
  var res = 1;
18880
18097
  var db = alasql.databases[databaseid];
18881
18098
  db.dbversion++;
18882
-
18883
- // var lsdbid = alasql.databases[databaseid].lsdbid;
18884
- // lsdb = LS.get(lsdbid);
18885
18099
  wait();
18886
18100
  function wait() {
18887
18101
  setTimeout(function () {
@@ -18899,9 +18113,6 @@ FS.rollback = function (databaseid, cb) {
18899
18113
  db.tables[tbid].data = db.data[tbid];
18900
18114
  }
18901
18115
  db.tables[tbid].indexColumns();
18902
-
18903
- // index columns
18904
- // convert types
18905
18116
  }
18906
18117
 
18907
18118
  delete alasql.databases[databaseid];
@@ -18916,9 +18127,6 @@ FS.rollback = function (databaseid, cb) {
18916
18127
  }
18917
18128
  }, 100);
18918
18129
  }
18919
-
18920
- // if(!alasql.options.autocommit) {
18921
-
18922
18130
  };
18923
18131
  if(utils.isBrowser && !utils.isWebWorker) {
18924
18132
  alasql = alasql || false;