alasql 4.2.7 → 4.3.1

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.js CHANGED
@@ -1,7 +1,7 @@
1
- //! AlaSQL v4.2.6 build: develop-6db74fcc | © 2014-2024 Andrey Gershun & Mathias Wulff | License: MIT
1
+ //! AlaSQL v4.3.0 build: develop-35aa279d | © 2014-2024 Andrey Gershun & Mathias Wulff | License: MIT
2
2
  /*
3
3
  @module alasql
4
- @version 4.2.6
4
+ @version 4.3.0
5
5
 
6
6
  AlaSQL - JavaScript SQL database
7
7
  © 2014-2024 Andrey Gershun & Mathias Wulff
@@ -141,8 +141,8 @@ SOFTWARE.
141
141
  Current version of alasql
142
142
  @constant {string}
143
143
  */
144
- alasql.version = '4.2.6';
145
- alasql.build = 'develop-6db74fcc';
144
+ alasql.version = '4.3.0';
145
+ alasql.build = 'develop-35aa279d';
146
146
 
147
147
  /**
148
148
  Debug flag
@@ -1904,10 +1904,10 @@ case 759:
1904
1904
  this.$ = new yy.AddRule({right:$$[$0]});
1905
1905
  break;
1906
1906
  case 762:
1907
- this.$ = new yy.Term({termid:$$[$0]});
1907
+ this.$ = {termid: $$[$0]};
1908
1908
  break;
1909
1909
  case 763:
1910
- this.$ = new yy.Term({termid:$$[$0-3],args:$$[$0-1]});
1910
+ this.$ = {termid:$$[$0-3], args:$$[$0-1]};
1911
1911
  break;
1912
1912
  case 766:
1913
1913
 
@@ -3361,7 +3361,10 @@ utils.isWebWorker = (function () {
3361
3361
  */
3362
3362
  utils.isNode = (function () {
3363
3363
  try {
3364
- return utils.isNativeFunction(utils.global.process.reallyExit);
3364
+ if (typeof process === 'undefined' || !process.versions || !process.versions.node) {
3365
+ return false;
3366
+ }
3367
+ return true;
3365
3368
  } catch (e) {
3366
3369
  return false;
3367
3370
  }
@@ -6459,26 +6462,9 @@ function queryfn(query, oldscope, cb, A, B) {
6459
6462
  query.queriesdata = [];
6460
6463
 
6461
6464
  query.queriesfn.forEach(function (q, idx) {
6462
- // if(query.explain) ms = Date.now();
6463
-
6464
- // var res = flatArray(q(query.params,null,queryfn2,(-idx-1),query));
6465
-
6466
- // var res = flatArray(queryfn(q.query,null,queryfn2,(-idx-1),query));
6467
-
6468
6465
  q.query.params = query.params;
6469
- // query.queriesdata[idx] =
6470
-
6471
- // if(false) {
6472
- // queryfn(q.query,query.oldscope,queryfn2,(-idx-1),query);
6473
- // } else {
6474
6466
  queryfn2([], -idx - 1, query);
6475
- // }
6476
-
6477
- // query.explaination.push({explid: query.explid++, description:'Query '+idx,ms:Date.now()-ms});
6478
- // query.queriesdata[idx] = res;
6479
- // return res;
6480
6467
  });
6481
-
6482
6468
  }
6483
6469
 
6484
6470
  query.scope = oldscope ? cloneDeep(oldscope) : {};
@@ -6487,11 +6473,8 @@ function queryfn(query, oldscope, cb, A, B) {
6487
6473
 
6488
6474
  let result;
6489
6475
  query.sources.forEach(function (source, idx) {
6490
- // source.data = query.database.tables[source.tableid].data;
6491
-
6492
6476
  source.query = query;
6493
6477
  var rs = source.datafn(query, query.params, queryfn2, idx, alasql);
6494
-
6495
6478
  if (typeof rs !== 'undefined') {
6496
6479
  // TODO - this is a hack: check if result is array - check all cases and make it more logical
6497
6480
  if ((query.intofn || query.intoallfn) && Array.isArray(rs)) {
@@ -6519,29 +6502,20 @@ function queryfn(query, oldscope, cb, A, B) {
6519
6502
 
6520
6503
  return result;
6521
6504
  }
6522
-
6523
6505
  function queryfn2(data, idx, query) {
6524
-
6525
- //console.trace();
6526
-
6527
6506
  if (idx >= 0) {
6528
- var source = query.sources[idx];
6507
+ let source = query.sources[idx];
6529
6508
  source.data = data;
6530
- if (typeof source.data == 'function') {
6509
+ if (typeof source.data === 'function') {
6531
6510
  source.getfn = source.data;
6532
6511
  source.dontcache = source.getfn.dontcache;
6533
-
6534
- // var prevsource = query.sources[h-1];
6535
- if (source.joinmode == 'OUTER' || source.joinmode == 'RIGHT' || source.joinmode == 'ANTI') {
6512
+ if (['OUTER', 'RIGHT', 'ANTI'].includes(source.joinmode)) {
6536
6513
  source.dontcache = false;
6537
6514
  }
6538
6515
  source.data = {};
6539
6516
  }
6540
6517
  } else {
6541
- // subqueries
6542
-
6543
6518
  query.queriesdata[-idx - 1] = flatArray(data);
6544
-
6545
6519
  }
6546
6520
 
6547
6521
  query.sourceslen--;
@@ -7175,11 +7149,11 @@ function swapSources(query, h) {
7175
7149
  var source = query.sources[h];
7176
7150
  var nextsource = query.sources[h + 1];
7177
7151
 
7178
- var onleftfn = source.onleftfn;
7179
- var onleftfns = source.onleftfns;
7180
- var onrightfn = source.onrightfn;
7181
- var onrightfns = source.onrightfns;
7182
- var optimization = source.optimization;
7152
+ let onleftfn = source.onleftfn;
7153
+ let onleftfns = source.onleftfns;
7154
+ let onrightfn = source.onrightfn;
7155
+ let onrightfns = source.onrightfns;
7156
+ let optimization = source.optimization;
7183
7157
 
7184
7158
  source.onleftfn = nextsource.onrightfn;
7185
7159
  source.onleftfns = nextsource.onrightfns;
@@ -7365,7 +7339,6 @@ yy.Select = class Select {
7365
7339
  query.explain = this.explain; // Explain
7366
7340
  query.explaination = [];
7367
7341
  query.explid = 1;
7368
-
7369
7342
  query.modifier = this.modifier;
7370
7343
 
7371
7344
  query.database = db;
@@ -7452,40 +7425,22 @@ yy.Select = class Select {
7452
7425
  query.corresponding = this.corresponding; // If CORRESPONDING flag exists
7453
7426
  if (this.union) {
7454
7427
  query.unionfn = this.union.compile(databaseid);
7455
- if (this.union.order) {
7456
- query.orderfn = this.union.compileOrder(query, params);
7457
- } else {
7458
- query.orderfn = null;
7459
- }
7428
+ query.orderfn = this.union.order ? this.union.compileOrder(query, params) : null;
7460
7429
  } else if (this.unionall) {
7461
7430
  query.unionallfn = this.unionall.compile(databaseid);
7462
- if (this.unionall.order) {
7463
- query.orderfn = this.unionall.compileOrder(query, params);
7464
- } else {
7465
- query.orderfn = null;
7466
- }
7431
+ query.orderfn = this.unionall.order ? this.unionall.compileOrder(query, params) : null;
7467
7432
  } else if (this.except) {
7468
7433
  query.exceptfn = this.except.compile(databaseid);
7469
- if (this.except.order) {
7470
- query.orderfn = this.except.compileOrder(query, params);
7471
- } else {
7472
- query.orderfn = null;
7473
- }
7434
+ query.orderfn = this.except.order ? this.except.compileOrder(query, params) : null;
7474
7435
  } else if (this.intersect) {
7475
7436
  query.intersectfn = this.intersect.compile(databaseid);
7476
- if (this.intersect.order) {
7477
- query.intersectfn = this.intersect.compileOrder(query, params);
7478
- } else {
7479
- query.orderfn = null;
7480
- }
7437
+ query.orderfn = this.intersect.order ? this.intersect.compileOrder(query, params) : null;
7481
7438
  }
7482
7439
 
7483
7440
  // SELECT INTO
7484
7441
  if (this.into) {
7485
7442
  if (this.into instanceof yy.Table) {
7486
- //
7487
7443
  // Save into the table in database
7488
- //
7489
7444
  if (
7490
7445
  alasql.options.autocommit &&
7491
7446
  alasql.databases[this.into.databaseid || databaseid].engineid
@@ -7536,7 +7491,6 @@ yy.Select = class Select {
7536
7491
  qs += 'undefined, undefined,';
7537
7492
  }
7538
7493
  query.intoallfns = qs + 'this.data,columns,cb)';
7539
-
7540
7494
  } else if (this.into instanceof yy.ParamValue) {
7541
7495
  //
7542
7496
  // Save data into parameters array
@@ -7547,11 +7501,9 @@ yy.Select = class Select {
7547
7501
 
7548
7502
  if (query.intofns) {
7549
7503
  // Create intofn function
7550
-
7551
7504
  query.intofn = new Function('r,i,params,alasql', 'var y;' + query.intofns);
7552
7505
  } else if (query.intoallfns) {
7553
7506
  // Create intoallfn function
7554
-
7555
7507
  query.intoallfn = new Function('columns,cb,params,alasql', 'var y;' + query.intoallfns);
7556
7508
  }
7557
7509
  }
@@ -7578,16 +7530,11 @@ yy.Select = class Select {
7578
7530
  if (cb) {
7579
7531
  cb(res2);
7580
7532
  }
7581
-
7582
7533
  return res2;
7583
7534
  });
7584
-
7585
- // if(typeof res1 != 'undefined') res1 = modify(query,res1);
7586
7535
  return res1;
7587
7536
  };
7588
7537
 
7589
- // statement.dbversion = ;
7590
-
7591
7538
  statement.query = query;
7592
7539
  return statement;
7593
7540
  }
@@ -7601,8 +7548,6 @@ yy.Select = class Select {
7601
7548
  if (!this.exists) return;
7602
7549
  query.existsfn = this.exists.map(function (ex) {
7603
7550
  var nq = ex.compile(query.database.databaseid);
7604
-
7605
- // if(!nq.query.modifier) nq.query.modifier = 'RECORDSET';
7606
7551
  nq.query.modifier = 'RECORDSET';
7607
7552
  return nq;
7608
7553
  });
@@ -7612,17 +7557,10 @@ yy.Select = class Select {
7612
7557
  if (!this.queries) return;
7613
7558
  query.queriesfn = this.queries.map(function (q) {
7614
7559
  var nq = q.compile(query.database.databaseid);
7615
-
7616
- // if(!nq.query) nq.query = {};
7617
7560
  nq.query.modifier = 'RECORDSET';
7618
- // if(!nq.query.modifier) nq.query.modifier = 'RECORDSET';
7619
7561
  return nq;
7620
7562
  });
7621
7563
  }
7622
-
7623
- // exec(databaseid) {
7624
- // throw new Error('Select statement should be precompiled');
7625
- // }
7626
7564
  };
7627
7565
 
7628
7566
  /**
@@ -7665,89 +7603,52 @@ function modify(query, res) {
7665
7603
  }
7666
7604
  }
7667
7605
 
7668
- if (modifier === 'VALUE') {
7606
+ switch (modifier) {
7607
+ case 'VALUE':
7608
+ if (res.length === 0) return undefined;
7609
+ const keyValue = columns && columns.length > 0 ? columns[0].columnid : Object.keys(res[0])[0];
7610
+ return res[0][keyValue];
7669
7611
 
7670
- if (res.length > 0) {
7671
- var key;
7672
- if (columns && columns.length > 0) {
7673
- key = columns[0].columnid;
7674
- } else {
7675
- key = Object.keys(res[0])[0];
7676
- }
7677
- res = res[0][key];
7678
- } else {
7679
- res = undefined;
7680
- }
7681
- } else if (modifier === 'ROW') {
7682
- if (res.length > 0) {
7683
- var key;
7684
- var a = [];
7685
- for (var key in res[0]) {
7686
- a.push(res[0][key]);
7687
- }
7688
- res = a;
7689
- } else {
7690
- res = undefined;
7691
- }
7692
- } else if (modifier === 'COLUMN') {
7693
- var ar = [];
7694
- if (res.length > 0) {
7695
- var key;
7612
+ case 'ROW':
7613
+ if (res.length === 0) return undefined;
7614
+ return Object.values(res[0]);
7615
+
7616
+ case 'COLUMN':
7617
+ if (res.length === 0) return [];
7618
+
7619
+ let key;
7696
7620
  if (columns && columns.length > 0) {
7697
7621
  key = columns[0].columnid;
7698
7622
  } else {
7699
7623
  key = Object.keys(res[0])[0];
7700
7624
  }
7701
7625
 
7626
+ let ar = [];
7702
7627
  for (var i = 0, ilen = res.length; i < ilen; i++) {
7703
7628
  ar.push(res[i][key]);
7704
7629
  }
7705
- }
7706
- res = ar;
7707
- } else if (modifier === 'MATRIX') {
7708
- // Returns square matrix of rows
7709
- var ar = [];
7710
- for (var i = 0; i < res.length; i++) {
7711
- var a = [];
7712
- var r = res[i];
7713
- for (var j = 0; j < columns.length; j++) {
7714
- a.push(r[columns[j].columnid]);
7715
- }
7716
- ar.push(a);
7717
- }
7718
- res = ar;
7719
- } else if (modifier === 'INDEX') {
7720
- var ar = {};
7721
- var key, val;
7722
- if (columns && columns.length > 0) {
7723
- key = columns[0].columnid;
7724
- val = columns[1].columnid;
7725
- } else {
7726
- var okeys = Object.keys(res[0]);
7727
- key = okeys[0];
7728
- val = okeys[1];
7729
- }
7730
- for (var i = 0, ilen = res.length; i < ilen; i++) {
7731
- ar[res[i][key]] = res[i][val];
7732
- }
7733
- res = ar;
7734
- // res = arrayOfArrays(res);
7735
- } else if (modifier === 'RECORDSET') {
7736
- res = new alasql.Recordset({columns: columns, data: res});
7737
- // res = arrayOfArrays(res);
7738
- } else if (modifier === 'TEXTSTRING') {
7739
- var key;
7740
- if (columns && columns.length > 0) {
7741
- key = columns[0].columnid;
7742
- } else {
7743
- key = Object.keys(res[0])[0];
7744
- }
7745
7630
 
7746
- for (var i = 0, ilen = res.length; i < ilen; i++) {
7747
- res[i] = res[i][key];
7748
- }
7749
- res = res.join('\n');
7750
- // res = arrayOfArrays(res);
7631
+ return ar;
7632
+
7633
+ case 'MATRIX':
7634
+ if (res.length === 0) return undefined;
7635
+ return res.map(row => columns.map(col => row[col.columnid]));
7636
+
7637
+ case 'INDEX':
7638
+ if (res.length === 0) return undefined;
7639
+ const keyIndex = columns && columns.length > 0 ? columns[0].columnid : Object.keys(res[0])[0];
7640
+ const valIndex = columns && columns.length > 1 ? columns[1].columnid : Object.keys(res[0])[1];
7641
+ return res.reduce((acc, row) => ({...acc, [row[keyIndex]]: row[valIndex]}), {});
7642
+
7643
+ case 'RECORDSET':
7644
+ // Assuming alasql.Recordset is available in the scope
7645
+ return new alasql.Recordset({columns: columns, data: res});
7646
+
7647
+ case 'TEXTSTRING':
7648
+ if (res.length === 0) return undefined;
7649
+ const keyTextString =
7650
+ columns && columns.length > 0 ? columns[0].columnid : Object.keys(res[0])[0];
7651
+ return res.map(row => row[keyTextString]).join('\n');
7751
7652
  }
7752
7653
  return res;
7753
7654
  }
@@ -7773,8 +7674,7 @@ yy.ExistsValue = class ExistsValue {
7773
7674
  }
7774
7675
 
7775
7676
  toJS(context, tableid, defcols) {
7776
-
7777
- return 'this.existsfn[' + this.existsidx + '](params,null,' + context + ').data.length';
7677
+ return `this.existsfn[${this.existsidx}](params, null, ${context}).data.length`;
7778
7678
  }
7779
7679
  };
7780
7680
 
@@ -7782,27 +7682,18 @@ yy.ExistsValue = class ExistsValue {
7782
7682
  // Prepare subqueries and exists
7783
7683
  //
7784
7684
  alasql.precompile = function (statement, databaseid, params) {
7785
-
7786
7685
  if (!statement) return;
7787
7686
  statement.params = params;
7788
7687
  if (statement.queries) {
7789
-
7790
7688
  statement.queriesfn = statement.queries.map(function (q) {
7791
7689
  var nq = q.compile(databaseid || statement.database.databaseid);
7792
-
7793
- // nq.query.modifier = undefined;
7794
- // if(!nq.query.modifier) nq.query.modifier = 'RECORDSET';
7795
7690
  nq.query.modifier = 'RECORDSET';
7796
7691
  return nq;
7797
7692
  });
7798
7693
  }
7799
7694
  if (statement.exists) {
7800
-
7801
7695
  statement.existsfn = statement.exists.map(function (ex) {
7802
7696
  var nq = ex.compile(databaseid || statement.database.databaseid);
7803
-
7804
- // if(!nq.query.modifier) nq.query.modifier = 'RECORDSET';
7805
- // if(!nq.query.modifier) nq.query.modifier = 'ARRAY';
7806
7697
  nq.query.modifier = 'RECORDSET';
7807
7698
  return nq;
7808
7699
  });
@@ -7819,24 +7710,15 @@ alasql.precompile = function (statement, databaseid, params) {
7819
7710
  /* global yy, alasql, Mongo, returnTrue */
7820
7711
 
7821
7712
  yy.Select.prototype.compileFrom = function (query) {
7822
-
7823
- var self = this;
7713
+ const self = this;
7824
7714
  query.sources = [];
7825
- // var tableid = this.from[0].tableid;
7826
- // var as = '';
7827
- // if(self.from[0].as) as = this.from[0].as;
7828
-
7829
7715
  query.aliases = {};
7830
- if (!self.from) return;
7831
-
7832
- self.from.forEach(function (tq) {
7833
-
7834
- var ps = '';
7835
7716
 
7836
- var alias = tq.as || tq.tableid;
7717
+ if (!self.from) return;
7837
7718
 
7719
+ self.from.forEach(tq => {
7720
+ const alias = tq.as || tq.tableid;
7838
7721
  if (tq instanceof yy.Table) {
7839
-
7840
7722
  query.aliases[alias] = {
7841
7723
  tableid: tq.tableid,
7842
7724
  databaseid: tq.databaseid || query.database.databaseid,
@@ -7862,7 +7744,7 @@ yy.Select.prototype.compileFrom = function (query) {
7862
7744
  throw new Error('Wrong table at FROM');
7863
7745
  }
7864
7746
 
7865
- var source = {
7747
+ const source = {
7866
7748
  alias: alias,
7867
7749
  databaseid: tq.databaseid || query.database.databaseid,
7868
7750
  tableid: tq.tableid,
@@ -7870,21 +7752,16 @@ yy.Select.prototype.compileFrom = function (query) {
7870
7752
  onmiddlefn: returnTrue,
7871
7753
  srcwherefns: '', // for optimization
7872
7754
  srcwherefn: returnTrue,
7873
- // columns: []
7874
7755
  };
7875
7756
 
7876
7757
  if (tq instanceof yy.Table) {
7877
- // Get columns from table
7878
7758
  source.columns = alasql.databases[source.databaseid].tables[source.tableid].columns;
7879
-
7880
7759
  if (
7881
7760
  alasql.options.autocommit &&
7882
7761
  alasql.databases[source.databaseid].engineid &&
7883
7762
  !alasql.databases[source.databaseid].tables[source.tableid].view
7884
7763
  ) {
7885
-
7886
- // TODO -- make view for external engine
7887
- source.datafn = function (query, params, cb, idx, alasql) {
7764
+ source.datafn = (query, params, cb, idx, alasql) => {
7888
7765
  return alasql.engines[alasql.databases[source.databaseid].engineid].fromTable(
7889
7766
  source.databaseid,
7890
7767
  source.tableid,
@@ -7894,87 +7771,66 @@ yy.Select.prototype.compileFrom = function (query) {
7894
7771
  );
7895
7772
  };
7896
7773
  } else if (alasql.databases[source.databaseid].tables[source.tableid].view) {
7897
- source.datafn = function (query, params, cb, idx, alasql) {
7898
- var res = alasql.databases[source.databaseid].tables[source.tableid].select(params);
7774
+ source.datafn = (query, params, cb, idx, alasql) => {
7775
+ let res = alasql.databases[source.databaseid].tables[source.tableid].select(params);
7899
7776
  if (cb) res = cb(res, idx, query);
7900
7777
  return res;
7901
7778
  };
7902
7779
  } else {
7903
-
7904
- source.datafn = function (query, params, cb, idx, alasql) {
7905
- /*
7906
-
7907
- */
7908
- var res = alasql.databases[source.databaseid].tables[source.tableid].data;
7909
-
7780
+ source.datafn = (query, params, cb, idx, alasql) => {
7781
+ let res = alasql.databases[source.databaseid].tables[source.tableid].data;
7910
7782
  if (cb) res = cb(res, idx, query);
7911
-
7912
7783
  return res;
7913
- // return alasql.databases[source.databaseid].tables[source.tableid].data;
7914
7784
  };
7915
7785
  }
7916
7786
  } else if (tq instanceof yy.Select) {
7917
7787
  source.subquery = tq.compile(query.database.databaseid);
7918
7788
  if (typeof source.subquery.query.modifier === 'undefined') {
7919
- source.subquery.query.modifier = 'RECORDSET'; // Subqueries always return recordsets
7789
+ source.subquery.query.modifier = 'RECORDSET';
7920
7790
  }
7921
7791
  source.columns = source.subquery.query.columns;
7922
7792
 
7923
- // tq.columns;
7924
-
7925
- source.datafn = function (query, params, cb, idx, alasql) {
7926
- // return source.subquery(query.params, cb, idx, query);
7927
- var res;
7928
- source.subquery(query.params, function (data) {
7793
+ source.datafn = (query, params, cb, idx, alasql) => {
7794
+ let res;
7795
+ source.subquery(query.params, data => {
7929
7796
  res = data.data;
7930
7797
  if (cb) res = cb(res, idx, query);
7931
- return res;
7932
- // return data.data;
7933
7798
  });
7934
-
7935
7799
  return res;
7936
7800
  };
7937
7801
  } else if (tq instanceof yy.Search) {
7938
7802
  source.subsearch = tq;
7939
7803
  source.columns = [];
7940
-
7941
- source.datafn = function (query, params, cb, idx, alasql) {
7942
- // return source.subquery(query.params, cb, idx, query);
7943
- var res;
7944
- source.subsearch.execute(query.database.databaseid, query.params, function (data) {
7804
+ source.datafn = (query, params, cb, idx, alasql) => {
7805
+ let res;
7806
+ source.subsearch.execute(query.database.databaseid, query.params, data => {
7945
7807
  res = data;
7946
7808
  if (cb) res = cb(res, idx, query);
7947
- return res;
7948
- // return data.data;
7949
7809
  });
7950
-
7951
7810
  return res;
7952
7811
  };
7953
7812
  } else if (tq instanceof yy.ParamValue) {
7954
- ps = "var res = alasql.prepareFromData(params['" + tq.param + "']";
7955
-
7813
+ let ps = `var res = alasql.prepareFromData(params['${tq.param}']`;
7956
7814
  if (tq.array) ps += ',true';
7957
7815
  ps += ');if(cb)res=cb(res,idx,query);return res';
7958
7816
  source.datafn = new Function('query,params,cb,idx,alasql', ps);
7959
7817
  } else if (tq.inserted) {
7960
- ps = 'var res = alasql.prepareFromData(alasql.inserted';
7818
+ let ps = 'var res = alasql.prepareFromData(alasql.inserted';
7961
7819
  if (tq.array) ps += ',true';
7962
7820
  ps += ');if(cb)res=cb(res,idx,query);return res';
7963
7821
  source.datafn = new Function('query,params,cb,idx,alasql', ps);
7964
7822
  } else if (tq instanceof yy.Json) {
7965
- ps = 'var res = alasql.prepareFromData(' + tq.toJS();
7966
-
7823
+ let ps = 'var res = alasql.prepareFromData(' + tq.toJS();
7967
7824
  if (tq.array) ps += ',true';
7968
7825
  ps += ');if(cb)res=cb(res,idx,query);return res';
7969
7826
  source.datafn = new Function('query,params,cb,idx,alasql', ps);
7970
7827
  } else if (tq instanceof yy.VarValue) {
7971
- ps = "var res = alasql.prepareFromData(alasql.vars['" + tq.variable + "']";
7972
-
7828
+ let ps = `var res = alasql.prepareFromData(alasql.vars['${tq.variable}']`;
7973
7829
  if (tq.array) ps += ',true';
7974
7830
  ps += ');if(cb)res=cb(res,idx,query);return res';
7975
7831
  source.datafn = new Function('query,params,cb,idx,alasql', ps);
7976
7832
  } else if (tq instanceof yy.FuncValue) {
7977
- ps = 'var res=alasql.from[' + JSON.stringify(tq.funcid.toUpperCase()) + '](';
7833
+ let ps = 'var res=alasql.from[' + JSON.stringify(tq.funcid.toUpperCase()) + '](';
7978
7834
 
7979
7835
  if (tq.args && tq.args.length > 0) {
7980
7836
  if (tq.args[0]) {
@@ -7982,6 +7838,7 @@ yy.Select.prototype.compileFrom = function (query) {
7982
7838
  } else {
7983
7839
  ps += 'null,';
7984
7840
  }
7841
+
7985
7842
  if (tq.args[1]) {
7986
7843
  ps += tq.args[1].toJS('query.oldscope') + ',';
7987
7844
  } else {
@@ -7990,46 +7847,32 @@ yy.Select.prototype.compileFrom = function (query) {
7990
7847
  } else {
7991
7848
  ps += 'null,null,';
7992
7849
  }
7993
- ps += 'cb,idx,query';
7994
- ps += ');/*if(cb)res=cb(res,idx,query);*/return res';
7995
-
7996
- source.datafn = new Function('query, params, cb, idx, alasql', ps);
7850
+ ps += 'cb,idx,query); return res';
7851
+ source.datafn = new Function('query,params,cb,idx,alasql', ps);
7997
7852
  } else if (tq instanceof yy.FromData) {
7998
- source.datafn = function (query, params, cb, idx, alasql) {
7999
- var res = tq.data;
7853
+ source.datafn = (query, params, cb, idx, alasql) => {
7854
+ let res = tq.data;
8000
7855
  if (cb) res = cb(res, idx, query);
8001
7856
  return res;
8002
7857
  };
8003
7858
  } else {
8004
7859
  throw new Error('Wrong table at FROM');
8005
7860
  }
8006
- // source.data = alasql.databases[source.databaseid].tables[source.tableid].data;
8007
7861
  query.sources.push(source);
8008
7862
  });
8009
- // TODO Add joins
8010
7863
  query.defaultTableid = query.sources[0].alias;
8011
-
8012
7864
  };
8013
7865
 
8014
7866
  alasql.prepareFromData = function (data, array) {
8015
-
8016
- var i, ilen;
8017
- var res = data;
7867
+ let res = data;
8018
7868
  if (typeof data === 'string') {
8019
7869
  res = data.split(/\r?\n/);
8020
7870
  if (array) {
8021
- for (i = 0, ilen = res.length; i < ilen; i++) {
8022
- res[i] = [res[i]];
8023
- }
7871
+ res = res.map(item => [item]);
8024
7872
  }
8025
7873
  } else if (array) {
8026
- res = [];
8027
- for (i = 0, ilen = data.length; i < ilen; i++) {
8028
- res.push([data[i]]);
8029
- }
8030
-
7874
+ res = data.map(item => [item]);
8031
7875
  } else if (typeof data === 'object' && !Array.isArray(data)) {
8032
- // } else if(typeof data == 'object' && !(typeof data.length == 'undefined')) {
8033
7876
  if (
8034
7877
  typeof Mongo !== 'undefined' &&
8035
7878
  typeof Mongo.Collection !== 'undefined' &&
@@ -8038,13 +7881,11 @@ alasql.prepareFromData = function (data, array) {
8038
7881
  res = data.find().fetch();
8039
7882
  } else {
8040
7883
  res = [];
8041
- for (var key in data) {
7884
+ for (const key in data) {
8042
7885
  if (data.hasOwnProperty(key)) res.push([key, data[key]]);
8043
7886
  }
8044
7887
  }
8045
-
8046
7888
  }
8047
-
8048
7889
  return res;
8049
7890
  };
8050
7891
  /*
@@ -8059,15 +7900,12 @@ alasql.prepareFromData = function (data, array) {
8059
7900
 
8060
7901
  /* global yy, alasql, returnTrue, arrayIntersect */
8061
7902
 
8062
- // Compile JOIN caluese
8063
7903
  yy.Select.prototype.compileJoins = function (query) {
7904
+ const self = this;
8064
7905
 
8065
- // debugger;
8066
- var self = this;
8067
-
8068
- this.joins.forEach(function (jn) {
7906
+ this.joins.forEach(jn => {
7907
+ let tq, ps, source;
8069
7908
  // Test CROSS-JOIN
8070
- var tq, ps, source;
8071
7909
  if (jn.joinmode === 'CROSS') {
8072
7910
  if (jn.using || jn.on) {
8073
7911
  throw new Error('CROSS JOIN cannot have USING or ON clauses');
@@ -8077,7 +7915,6 @@ yy.Select.prototype.compileJoins = function (query) {
8077
7915
  }
8078
7916
 
8079
7917
  if (jn instanceof yy.Apply) {
8080
-
8081
7918
  source = {
8082
7919
  alias: jn.as,
8083
7920
  applymode: jn.applymode,
@@ -8090,7 +7927,7 @@ yy.Select.prototype.compileJoins = function (query) {
8090
7927
  source.columns = source.applyselect.query.columns;
8091
7928
 
8092
7929
  source.datafn = function (query, params, cb, idx, alasql) {
8093
- var res;
7930
+ let res;
8094
7931
  if (cb) res = cb(res, idx, query);
8095
7932
  return res;
8096
7933
  };
@@ -8112,7 +7949,6 @@ yy.Select.prototype.compileJoins = function (query) {
8112
7949
  srcwherefn: returnTrue,
8113
7950
  columns: [],
8114
7951
  };
8115
- //
8116
7952
 
8117
7953
  if (!alasql.databases[source.databaseid].tables[source.tableid]) {
8118
7954
  throw new Error(
@@ -8122,11 +7958,8 @@ yy.Select.prototype.compileJoins = function (query) {
8122
7958
 
8123
7959
  source.columns = alasql.databases[source.databaseid].tables[source.tableid].columns;
8124
7960
 
8125
- // source.data = query.database.tables[source.tableid].data;
8126
7961
  if (alasql.options.autocommit && alasql.databases[source.databaseid].engineid) {
8127
-
8128
7962
  source.datafn = function (query, params, cb, idx, alasql) {
8129
-
8130
7963
  return alasql.engines[alasql.databases[source.databaseid].engineid].fromTable(
8131
7964
  source.databaseid,
8132
7965
  source.tableid,
@@ -8137,31 +7970,26 @@ yy.Select.prototype.compileJoins = function (query) {
8137
7970
  };
8138
7971
  } else if (alasql.databases[source.databaseid].tables[source.tableid].view) {
8139
7972
  source.datafn = function (query, params, cb, idx, alasql) {
8140
- var res = alasql.databases[source.databaseid].tables[source.tableid].select(params);
7973
+ let res = alasql.databases[source.databaseid].tables[source.tableid].select(params);
8141
7974
  if (cb) res = cb(res, idx, query);
8142
7975
  return res;
8143
7976
  };
8144
7977
  } else {
8145
7978
  source.datafn = function (query, params, cb, idx, alasql) {
8146
- var res = alasql.databases[source.databaseid].tables[source.tableid].data;
7979
+ let res = alasql.databases[source.databaseid].tables[source.tableid].data;
8147
7980
  if (cb) res = cb(res, idx, query);
8148
7981
  return res;
8149
7982
  };
8150
7983
  }
8151
7984
 
8152
- // var alias = jn.as || tq.tableid;
8153
- // if(tq) {
8154
7985
  query.aliases[source.alias] = {
8155
7986
  tableid: tq.tableid,
8156
7987
  databaseid: tq.databaseid || query.database.databaseid,
8157
7988
  };
8158
- // }
8159
7989
  } else if (jn.select) {
8160
7990
  tq = jn.select;
8161
7991
  source = {
8162
7992
  alias: jn.as,
8163
- // databaseid: jn.databaseid || query.database.databaseid,
8164
- // tableid: tq.tableid,
8165
7993
  joinmode: jn.joinmode,
8166
7994
  onmiddlefn: returnTrue,
8167
7995
  srcwherefns: '', // for optimization
@@ -8175,121 +8003,92 @@ yy.Select.prototype.compileJoins = function (query) {
8175
8003
  }
8176
8004
  source.columns = source.subquery.query.columns;
8177
8005
 
8178
- // if(jn instanceof yy.Apply) {
8179
8006
  source.datafn = function (query, params, cb, idx, alasql) {
8180
- // return cb(null,idx,alasql);
8181
8007
  source.data = source.subquery(query.params, null, cb, idx).data;
8182
- // var res = alasql.prepareFromData(params[idx]);
8183
- var res = source.data;
8008
+ let res = source.data;
8184
8009
  // Propogate subquery result
8185
8010
  if (cb) res = cb(res, idx, query);
8186
8011
  return res;
8187
8012
  };
8188
- // } else {
8189
- // source.datafn = function(query, params, cb, idx, alasql) {
8190
- // return source.subquery(query.params, null, cb, idx);
8191
- // }
8192
- // }
8193
8013
  query.aliases[source.alias] = {type: 'subquery'};
8194
8014
  } else if (jn.param) {
8195
8015
  source = {
8196
8016
  alias: jn.as,
8197
- // databaseid: jn.databaseid || query.database.databaseid,
8198
- // tableid: tq.tableid,
8199
8017
  joinmode: jn.joinmode,
8200
8018
  onmiddlefn: returnTrue,
8201
8019
  srcwherefns: '', // for optimization
8202
8020
  srcwherefn: returnTrue,
8203
8021
  };
8204
- // source.data = ;
8205
- var jnparam = jn.param.param;
8206
-
8207
- ps = "var res=alasql.prepareFromData(params['" + jnparam + "']";
8022
+ const jnparam = jn.param.param;
8023
+ ps = "let res=alasql.prepareFromData(params['" + jnparam + "']";
8208
8024
  if (jn.array) ps += ',true';
8209
- ps += ');if(cb)res=cb(res, idx, query);return res';
8025
+ ps += '); if(cb) res=cb(res, idx, query); return res';
8210
8026
 
8211
8027
  source.datafn = new Function('query,params,cb,idx, alasql', ps);
8212
8028
  query.aliases[source.alias] = {type: 'paramvalue'};
8213
8029
  } else if (jn.variable) {
8214
8030
  source = {
8215
8031
  alias: jn.as,
8216
- // databaseid: jn.databaseid || query.database.databaseid,
8217
- // tableid: tq.tableid,
8218
8032
  joinmode: jn.joinmode,
8219
8033
  onmiddlefn: returnTrue,
8220
8034
  srcwherefns: '', // for optimization
8221
8035
  srcwherefn: returnTrue,
8222
8036
  };
8223
- // source.data = ;
8224
- // var jnparam = jn.param.param;
8225
-
8226
- ps = "var res=alasql.prepareFromData(alasql.vars['" + jn.variable + "']";
8227
- if (jn.array) ps += ',true';
8228
- ps += ');if(cb)res=cb(res, idx, query);return res';
8037
+ ps = "let res=alasql.prepareFromData(alasql.vars['" + jn.variable + "']";
8038
+ if (jn.array) ps += ', true';
8039
+ ps += '); if(cb)res=cb(res, idx, query);return res';
8229
8040
 
8230
8041
  source.datafn = new Function('query,params,cb,idx, alasql', ps);
8231
8042
  query.aliases[source.alias] = {type: 'varvalue'};
8232
8043
  } else if (jn.func) {
8233
8044
  source = {
8234
8045
  alias: jn.as,
8235
- // databaseid: jn.databaseid || query.database.databaseid,
8236
- // tableid: tq.tableid,
8237
8046
  joinmode: jn.joinmode,
8238
8047
  onmiddlefn: returnTrue,
8239
8048
  srcwherefns: '', // for optimization
8240
8049
  srcwherefn: returnTrue,
8241
8050
  };
8242
- // source.data = ;
8243
8051
 
8244
- var s = 'var res=alasql.from[' + JSON.stringify(jn.func.funcid.toUpperCase()) + '](';
8052
+ let s = 'let res=alasql.from[' + JSON.stringify(jn.func.funcid.toUpperCase()) + '](';
8245
8053
 
8246
- var args = jn.func.args;
8054
+ const args = jn.func.args;
8247
8055
  if (args && args.length > 0) {
8248
8056
  if (args[0]) {
8249
- s += args[0].toJS('query.oldscope') + ',';
8057
+ s += args[0].toJS('query.oldscope') + ', ';
8250
8058
  } else {
8251
- s += 'null,';
8059
+ s += 'null, ';
8252
8060
  }
8253
8061
  if (args[1]) {
8254
- s += args[1].toJS('query.oldscope') + ',';
8062
+ s += args[1].toJS('query.oldscope') + ', ';
8255
8063
  } else {
8256
- s += 'null,';
8064
+ s += 'null, ';
8257
8065
  }
8258
8066
  } else {
8259
- s += 'null,null,';
8067
+ s += 'null, null, ';
8260
8068
  }
8261
- s += 'cb,idx,query';
8262
- s += ');/*if(cb)res=cb(res,idx,query);*/return res';
8263
-
8069
+ s += 'cb, idx, query); return res';
8264
8070
  source.datafn = new Function('query, params, cb, idx, alasql', s);
8265
8071
 
8266
8072
  query.aliases[source.alias] = {type: 'funcvalue'};
8267
8073
  }
8268
8074
 
8269
- var alias = source.alias;
8075
+ const alias = source.alias;
8270
8076
 
8271
8077
  // Test NATURAL-JOIN
8272
8078
  if (jn.natural) {
8273
8079
  if (jn.using || jn.on) {
8274
8080
  throw new Error('NATURAL JOIN cannot have USING or ON clauses');
8275
8081
  } else {
8276
- // source.joinmode == "INNER";
8082
+ // source.joinmode == "INNER";
8277
8083
  if (query.sources.length > 0) {
8278
- var prevSource = query.sources[query.sources.length - 1];
8279
- var prevTable = alasql.databases[prevSource.databaseid].tables[prevSource.tableid];
8280
- var table = alasql.databases[source.databaseid].tables[source.tableid];
8084
+ const prevSource = query.sources[query.sources.length - 1];
8085
+ const prevTable = alasql.databases[prevSource.databaseid].tables[prevSource.tableid];
8086
+ const table = alasql.databases[source.databaseid].tables[source.tableid];
8281
8087
 
8282
8088
  if (prevTable && table) {
8283
- var c1 = prevTable.columns.map(function (col) {
8284
- return col.columnid;
8285
- });
8286
- var c2 = table.columns.map(function (col) {
8287
- return col.columnid;
8288
- });
8289
- jn.using = arrayIntersect(c1, c2).map(function (colid) {
8290
- return {columnid: colid};
8291
- });
8292
-
8089
+ const c1 = prevTable.columns.map(col => col.columnid);
8090
+ const c2 = table.columns.map(col => col.columnid);
8091
+ jn.using = arrayIntersect(c1, c2).map(colid => ({columnid: colid}));
8293
8092
  } else {
8294
8093
  throw new Error(
8295
8094
  'In this version of Alasql NATURAL JOIN ' +
@@ -8301,45 +8100,31 @@ yy.Select.prototype.compileJoins = function (query) {
8301
8100
  }
8302
8101
 
8303
8102
  if (jn.using) {
8304
- prevSource = query.sources[query.sources.length - 1];
8305
-
8103
+ const prevSource = query.sources[query.sources.length - 1];
8306
8104
  source.onleftfns = jn.using
8307
- .map(function (col) {
8308
-
8309
- return "p['" + (prevSource.alias || prevSource.tableid) + "']['" + col.columnid + "']";
8310
- })
8105
+ .map(col => "p['" + (prevSource.alias || prevSource.tableid) + "']['" + col.columnid + "']")
8311
8106
  .join('+"`"+');
8312
8107
 
8313
- source.onleftfn = new Function('p,params,alasql', 'var y;return ' + source.onleftfns);
8108
+ source.onleftfn = new Function('p,params,alasql', 'let y;return ' + source.onleftfns);
8314
8109
 
8315
8110
  source.onrightfns = jn.using
8316
- .map(function (col) {
8317
- return "p['" + (source.alias || source.tableid) + "']['" + col.columnid + "']";
8318
- })
8111
+ .map(col => "p['" + (source.alias || source.tableid) + "']['" + col.columnid + "']")
8319
8112
  .join('+"`"+');
8320
- source.onrightfn = new Function('p,params,alasql', 'var y;return ' + source.onrightfns);
8113
+ source.onrightfn = new Function('p,params,alasql', 'let y;return ' + source.onrightfns);
8321
8114
  source.optimization = 'ix';
8322
-
8323
8115
  } else if (jn.on) {
8324
-
8325
8116
  if (jn.on instanceof yy.Op && jn.on.op === '=' && !jn.on.allsome) {
8326
-
8327
8117
  source.optimization = 'ix';
8328
-
8329
- var lefts = '';
8330
- var rights = '';
8331
- var middles = '';
8332
- var middlef = false;
8118
+ let lefts = '';
8119
+ let rights = '';
8120
+ let middles = '';
8121
+ let middlef = false;
8333
8122
  // Test right and left sides
8334
- var ls = jn.on.left.toJS('p', query.defaultTableid, query.defcols);
8335
- var rs = jn.on.right.toJS('p', query.defaultTableid, query.defcols);
8123
+ const ls = jn.on.left.toJS('p', query.defaultTableid, query.defcols);
8124
+ const rs = jn.on.right.toJS('p', query.defaultTableid, query.defcols);
8336
8125
 
8337
8126
  if (ls.indexOf("p['" + alias + "']") > -1 && !(rs.indexOf("p['" + alias + "']") > -1)) {
8338
- if (
8339
- (ls.match(/p\['.*?'\]/g) || []).every(function (s) {
8340
- return s === "p['" + alias + "']";
8341
- })
8342
- ) {
8127
+ if ((ls.match(/p\['.*?'\]/g) || []).every(s => s === "p['" + alias + "']")) {
8343
8128
  rights = ls;
8344
8129
  } else {
8345
8130
  middlef = true;
@@ -8348,11 +8133,7 @@ yy.Select.prototype.compileJoins = function (query) {
8348
8133
  !(ls.indexOf("p['" + alias + "']") > -1) &&
8349
8134
  rs.indexOf("p['" + alias + "']") > -1
8350
8135
  ) {
8351
- if (
8352
- (rs.match(/p\['.*?'\]/g) || []).every(function (s) {
8353
- return s === "p['" + alias + "']";
8354
- })
8355
- ) {
8136
+ if ((rs.match(/p\['.*?'\]/g) || []).every(s => s === "p['" + alias + "']")) {
8356
8137
  lefts = ls;
8357
8138
  } else {
8358
8139
  middlef = true;
@@ -8362,11 +8143,7 @@ yy.Select.prototype.compileJoins = function (query) {
8362
8143
  }
8363
8144
 
8364
8145
  if (rs.indexOf("p['" + alias + "']") > -1 && !(ls.indexOf("p['" + alias + "']") > -1)) {
8365
- if (
8366
- (rs.match(/p\['.*?'\]/g) || []).every(function (s) {
8367
- return s === "p['" + alias + "']";
8368
- })
8369
- ) {
8146
+ if ((rs.match(/p\['.*?'\]/g) || []).every(s => s === "p['" + alias + "']")) {
8370
8147
  rights = rs;
8371
8148
  } else {
8372
8149
  middlef = true;
@@ -8375,11 +8152,7 @@ yy.Select.prototype.compileJoins = function (query) {
8375
8152
  !(rs.indexOf("p['" + alias + "']") > -1) &&
8376
8153
  ls.indexOf("p['" + alias + "']") > -1
8377
8154
  ) {
8378
- if (
8379
- (ls.match(/p\['.*?'\]/g) || []).every(function (s) {
8380
- return s === "p['" + alias + "']";
8381
- })
8382
- ) {
8155
+ if ((ls.match(/p\['.*?'\]/g) || []).every(s => s === "p['" + alias + "']")) {
8383
8156
  lefts = rs;
8384
8157
  } else {
8385
8158
  middlef = true;
@@ -8389,47 +8162,31 @@ yy.Select.prototype.compileJoins = function (query) {
8389
8162
  }
8390
8163
 
8391
8164
  if (middlef) {
8392
- // middles = jn.on.toJS('p',query.defaultTableid);
8393
- // } else {
8394
8165
  rights = '';
8395
8166
  lefts = '';
8396
8167
  middles = jn.on.toJS('p', query.defaultTableid, query.defcols);
8397
8168
  source.optimization = 'no';
8398
- // What to here?
8399
8169
  }
8400
8170
 
8401
8171
  source.onleftfns = lefts;
8402
8172
  source.onrightfns = rights;
8403
8173
  source.onmiddlefns = middles || 'true';
8404
8174
 
8405
- source.onleftfn = new Function('p,params,alasql', 'var y;return ' + source.onleftfns);
8406
- source.onrightfn = new Function('p,params,alasql', 'var y;return ' + source.onrightfns);
8407
- source.onmiddlefn = new Function('p,params,alasql', 'var y;return ' + source.onmiddlefns);
8408
-
8409
- // } else if(jn.on instanceof yy.Op && jn.on.op == 'AND') {
8410
-
8175
+ source.onleftfn = new Function('p,params,alasql', 'let y;return ' + source.onleftfns);
8176
+ source.onrightfn = new Function('p,params,alasql', 'let y;return ' + source.onrightfns);
8177
+ source.onmiddlefn = new Function('p,params,alasql', 'let y;return ' + source.onmiddlefns);
8411
8178
  } else {
8412
-
8413
8179
  source.optimization = 'no';
8414
- // source.onleftfn = returnTrue;
8415
- // source.onleftfns = "true";
8416
8180
  source.onmiddlefns = jn.on.toJS('p', query.defaultTableid, query.defcols);
8417
8181
  source.onmiddlefn = new Function(
8418
8182
  'p,params,alasql',
8419
- 'var y;return ' + jn.on.toJS('p', query.defaultTableid, query.defcols)
8183
+ 'let y;return ' + jn.on.toJS('p', query.defaultTableid, query.defcols)
8420
8184
  );
8421
8185
  }
8422
-
8423
- // Optimization function
8424
8186
  }
8425
8187
 
8426
- // source.data = alasql.databases[source.databaseid].tables[source.tableid].data;
8427
-
8428
- // TODO SubQueries
8429
-
8430
8188
  query.sources.push(source);
8431
8189
  });
8432
-
8433
8190
  };
8434
8191
  yy.Select.prototype.compileWhere = function (query) {
8435
8192
  if (this.where) {
@@ -8551,15 +8308,10 @@ yy.Select.prototype.compileGroup = function (query) {
8551
8308
  var tableid = '';
8552
8309
  }
8553
8310
  var defcols = query.defcols;
8554
-
8555
8311
  var allgroup = [[]];
8556
8312
  if (this.group) {
8557
8313
  allgroup = decartes(this.group, query);
8558
8314
  }
8559
-
8560
- // Prepare groups
8561
- //var allgroup = [['a'], ['a','b'], ['a', 'b', 'c']];
8562
-
8563
8315
  // Union all arrays to get a maximum
8564
8316
  var allgroups = [];
8565
8317
  allgroup.forEach(function (a) {
@@ -8570,12 +8322,10 @@ yy.Select.prototype.compileGroup = function (query) {
8570
8322
 
8571
8323
  query.ingroup = [];
8572
8324
  var s = '';
8573
- // s+= query.selectfns;
8574
8325
  allgroup.forEach(function (agroup) {
8575
8326
  // Start of group function
8576
8327
  s += 'var g=this.xgroups[';
8577
8328
 
8578
- // var gcols = this.group.map(function(col){return col.columnid}); // Group fields with r
8579
8329
  // Array with group columns from record
8580
8330
  var rg = agroup.map(function (col2) {
8581
8331
  var columnid = col2.split('\t')[0];
@@ -8584,9 +8334,7 @@ yy.Select.prototype.compileGroup = function (query) {
8584
8334
  if (columnid === '') {
8585
8335
  return '1'; // Create fictive grouping column for fictive GROUP BY
8586
8336
  }
8587
- // else return "r['"+columnid+"']";
8588
8337
  query.ingroup.push(columnid);
8589
-
8590
8338
  return coljs;
8591
8339
  });
8592
8340
 
@@ -8598,7 +8346,6 @@ yy.Select.prototype.compileGroup = function (query) {
8598
8346
  s += '];if(!g) {this.groups.push((g=this.xgroups[';
8599
8347
  s += rg.join('+"`"+');
8600
8348
  s += '] = {';
8601
- // s += ']=r';
8602
8349
  s += agroup
8603
8350
  .map(function (col2) {
8604
8351
  var columnid = col2.split('\t')[0];
@@ -8610,17 +8357,14 @@ yy.Select.prototype.compileGroup = function (query) {
8610
8357
  return "'" + columnid + "':" + coljs + ',';
8611
8358
  })
8612
8359
  .join('');
8613
-
8614
8360
  var neggroup = arrayDiff(allgroups, agroup);
8615
8361
 
8616
8362
  s += neggroup
8617
8363
  .map(function (col2) {
8618
8364
  var columnid = col2.split('\t')[0];
8619
- // var coljs = col2.split('\t')[1]
8620
8365
  return "'" + columnid + "':null,";
8621
8366
  })
8622
8367
  .join('');
8623
-
8624
8368
  var aft = '',
8625
8369
  aft2 = '';
8626
8370
 
@@ -8628,19 +8372,10 @@ yy.Select.prototype.compileGroup = function (query) {
8628
8372
  aft2 += "for(var f in p['" + query.groupStar + "']) {g[f]=p['" + query.groupStar + "'][f];};";
8629
8373
  }
8630
8374
 
8631
- /*
8632
- */
8633
- // s += self.columns.map(function(col){
8634
-
8635
8375
  s += query.selectGroup
8636
8376
  .map(function (col) {
8637
-
8638
8377
  var colexp = col.expression.toJS('p', tableid, defcols);
8639
8378
  var colas = col.nick;
8640
- // if(typeof colas == 'undefined') {
8641
- // if(col instanceof yy.Column) colas = col.columnid;
8642
- // else colas = col.toString();
8643
- // };
8644
8379
  let colExpIfFunIdExists = expression => {
8645
8380
  let colexpression = expression.args[0];
8646
8381
  return colexpression.toJS('p', tableid, defcols);
@@ -8666,12 +8401,7 @@ yy.Select.prototype.compileGroup = function (query) {
8666
8401
  return `'${colas}':(${colexp})|| typeof ${colexp} == 'number' ?
8667
8402
  ${colexp} : ${colexp} == 'string' && typeof Number(${colexp}) == 'number' ? Number(${colexp}) :
8668
8403
  typeof ${colexp} === 'boolean' ? Number(${colexp}) : 0,`;
8669
- } else if (
8670
- col.aggregatorid === 'FIRST' ||
8671
- col.aggregatorid === 'LAST'
8672
- // || col.aggregatorid == 'AVG'
8673
- // ) { return "'"+col.as+'\':r[\''+col.as+'\'],'; }//f.field.arguments[0].toJS();
8674
- ) {
8404
+ } else if (col.aggregatorid === 'FIRST' || col.aggregatorid === 'LAST') {
8675
8405
  return "'" + colas + "':" + colexp + ','; //f.field.arguments[0].toJS();
8676
8406
  } else if (col.aggregatorid === 'MIN') {
8677
8407
  if ('funcid' in col.expression) {
@@ -8691,58 +8421,24 @@ yy.Select.prototype.compileGroup = function (query) {
8691
8421
  return `'${colas}' : (typeof ${colexp} == 'number' ? ${colexp} : typeof ${colexp} == 'object' ?
8692
8422
  typeof Number(${colexp}) == 'number' ? ${colexp} : null : null),`;
8693
8423
  } else if (col.aggregatorid === 'ARRAY') {
8694
- return "'" + colas + "':[" + colexp + '],';
8424
+ return `'${colas}':[${colexp}],`;
8695
8425
  } else if (col.aggregatorid === 'COUNT') {
8696
8426
  if (col.expression.columnid === '*') {
8697
- return "'" + colas + "':1,";
8427
+ return `'${colas}':1,`;
8698
8428
  } else {
8699
- // return "'"+colas+'\':(typeof '+colexp+' != "undefined")?1:0,';
8700
- // } else {
8701
- return (
8702
- "'" +
8703
- colas +
8704
- "':(typeof " +
8705
- colexp +
8706
- ' == "undefined" || ' +
8707
- colexp +
8708
- ' === null) ? 0 : 1,'
8709
- );
8429
+ return `'${colas}':(typeof ${colexp} == "undefined" || ${colexp} === null) ? 0 : 1,`;
8710
8430
  }
8711
-
8712
- // else if(col.aggregatorid == 'MIN') { return "'"+col.as+'\':r[\''+col.as+'\'],'; }
8713
- // else if(col.aggregatorid == 'MAX') { return "'"+col.as+'\':r[\''+col.as+'\'],'; }
8714
8431
  } else if (col.aggregatorid === 'AVG') {
8715
- query.removeKeys.push('_SUM_' + colas);
8716
- query.removeKeys.push('_COUNT_' + colas);
8432
+ query.removeKeys.push(`_SUM_${colas}`);
8433
+ query.removeKeys.push(`_COUNT_${colas}`);
8717
8434
 
8718
- return (
8719
- '' +
8720
- "'" +
8721
- colas +
8722
- "':" +
8723
- colexp +
8724
- ",'_SUM_" +
8725
- colas +
8726
- "':(" +
8727
- colexp +
8728
- ")||0,'_COUNT_" +
8729
- colas +
8730
- "':(typeof " +
8731
- colexp +
8732
- ' == "undefined" || ' +
8733
- colexp +
8734
- ' === null) ? 0 : 1,'
8735
- );
8435
+ return `'${colas}':${colexp},'_SUM_${colas}':(${colexp})||0,'_COUNT_${colas}':(typeof ${colexp} == "undefined" || ${colexp} === null) ? 0 : 1,`;
8736
8436
  } else if (col.aggregatorid === 'AGGR') {
8737
- aft += ",g['" + colas + "']=" + col.expression.toJS('g', -1);
8437
+ aft += `,g['${colas}']=${col.expression.toJS('g', -1)}`;
8738
8438
  return '';
8739
8439
  } else if (col.aggregatorid === 'REDUCE') {
8740
- // query.removeKeys.push('_REDUCE_'+colas);
8741
8440
  query.aggrKeys.push(col);
8742
-
8743
- // return "'"+colas+'\':alasql.aggr[\''+col.funcid+'\']('+colexp+',undefined,(acc={}),1),'
8744
- // +'\'__REDUCE__'+colas+'\':acc,';
8745
- return "'" + colas + "':alasql.aggr['" + col.funcid + "'](" + colexp + ',undefined,1),';
8441
+ return `'${colas}':alasql.aggr['${col.funcid}'](${colexp},undefined,1),`;
8746
8442
  }
8747
8443
  return '';
8748
8444
  }
@@ -8752,12 +8448,9 @@ yy.Select.prototype.compileGroup = function (query) {
8752
8448
  .join('');
8753
8449
 
8754
8450
  s += '}' + aft + ',g));' + aft2 + '} else {';
8755
-
8756
- // s += self.columns.map(function(col){
8757
8451
  s += query.selectGroup
8758
8452
  .map(function (col) {
8759
8453
  var colas = col.nick;
8760
-
8761
8454
  var colexp = col.expression.toJS('p', tableid, defcols);
8762
8455
  let colExpIfFunIdExists = expression => {
8763
8456
  let colexpression = expression.args[0];
@@ -8767,28 +8460,22 @@ yy.Select.prototype.compileGroup = function (query) {
8767
8460
  var pre = '',
8768
8461
  post = '';
8769
8462
  if (col.distinct) {
8770
- var pre =
8771
- 'if(typeof ' +
8772
- colexp +
8773
- '!="undefined" && (!g[\'$$_VALUES_' +
8774
- colas +
8775
- "'][" +
8776
- colexp +
8777
- '])) {';
8778
- var post = "g['$$_VALUES_" + colas + "'][" + colexp + ']=true;}';
8463
+ pre = `if(typeof ${colexp}!="undefined" && (!g['$$_VALUES_${colas}'][${colexp}])) {`;
8464
+ post = `g['$$_VALUES_${colas}'][${colexp}]=true;}`;
8779
8465
  }
8466
+
8780
8467
  if (col.aggregatorid === 'SUM') {
8781
8468
  if ('funcid' in col.expression) {
8782
8469
  let colexp1 = colExpIfFunIdExists(col.expression);
8783
8470
  return (
8784
8471
  pre +
8785
8472
  `if(g['${colas}'] == null && ${colexp1} == null){g['${colas}'] = null}
8786
- else if(typeof g['${colas}']!== 'object' && typeof g['${colas}']!== 'number' && typeof ${colexp1}!== 'object' && typeof ${colexp1}!== 'number'){g['${colas}'] = null}
8787
- else if(typeof g['${colas}']!== 'object' && typeof g['${colas}']!== 'number' && typeof ${colexp1} == 'number'){g['${colas}'] = ${colexp}}
8788
- else if(typeof g['${colas}']!== 'number' && typeof ${colexp1}!== 'number' && typeof ${colexp1}!== 'object'){g['${colas}'] = g['${colas}']}
8789
- else if((g['${colas}'] == null || (typeof g['${colas}']!== 'number' && typeof g['${colas}']!== 'object')) && (${colexp1} == null || (typeof ${colexp1}!== 'number' && typeof ${colexp1}!== 'object'))){g['${colas}'] = null}
8790
- else if(typeof g['${colas}'] == 'number' && typeof ${colexp1} ==null){g['${colas}'] = g['${colas}']}
8791
- else if(typeof g['${colas}'] == null && typeof ${colexp1} =='number'){g['${colas}'] = ${colexp}}
8473
+ else if(typeof g['${colas}']!== 'object' && typeof g['${colas}']!== 'number' && typeof ${colexp1}!== 'object' && typeof ${colexp1}!== 'number'){ g['${colas}'] = null }
8474
+ else if(typeof g['${colas}']!== 'object' && typeof g['${colas}']!== 'number' && typeof ${colexp1} == 'number'){ g['${colas}'] = ${colexp} }
8475
+ else if(typeof g['${colas}']!== 'number' && typeof ${colexp1}!== 'number' && typeof ${colexp1}!== 'object'){ g['${colas}'] = g['${colas}'] }
8476
+ else if((g['${colas}'] == null || (typeof g['${colas}']!== 'number' && typeof g['${colas}']!== 'object')) && (${colexp1} == null || (typeof ${colexp1}!== 'number' && typeof ${colexp1}!== 'object'))){ g['${colas}'] = null }
8477
+ else if(typeof g['${colas}'] == 'number' && typeof ${colexp1} ==null){ g['${colas}'] = g['${colas}'] }
8478
+ else if(typeof g['${colas}'] == null && typeof ${colexp1} =='number'){ g['${colas}'] = ${colexp} }
8792
8479
  else{g['${colas}'] += ${colexp}||0}` +
8793
8480
  post
8794
8481
  );
@@ -8830,28 +8517,20 @@ yy.Select.prototype.compileGroup = function (query) {
8830
8517
  post
8831
8518
  );
8832
8519
  } else if (col.aggregatorid === 'COUNT') {
8833
-
8834
8520
  if (col.expression.columnid === '*') {
8835
- return pre + "g['" + colas + "']++;" + post;
8521
+ return `${pre}
8522
+ g['${colas}']++;
8523
+ ${post}`;
8836
8524
  } else {
8837
- return (
8838
- pre +
8839
- 'if(typeof ' +
8840
- colexp +
8841
- '!="undefined" && ' +
8842
- colexp +
8843
- " !== null) g['" +
8844
- colas +
8845
- "']++;" +
8846
- post
8847
- );
8525
+ return `${pre}
8526
+ if(typeof ${colexp}!="undefined" && ${colexp} !== null) g['${colas}']++;
8527
+ ${post}`;
8848
8528
  }
8849
8529
  } else if (col.aggregatorid === 'ARRAY') {
8850
8530
  return pre + "g['" + colas + "'].push(" + colexp + ');' + post;
8851
8531
  } else if (col.aggregatorid === 'MIN') {
8852
8532
  if ('funcid' in col.expression) {
8853
8533
  let colexp1 = colExpIfFunIdExists(col.expression);
8854
-
8855
8534
  return (
8856
8535
  pre +
8857
8536
  `if((g['${colas}'] == null && ${colexp1}!== null) ? y = ${colexp} : (g['${colas}']!== null &&
@@ -8901,47 +8580,21 @@ yy.Select.prototype.compileGroup = function (query) {
8901
8580
  } else if (col.aggregatorid === 'FIRST') {
8902
8581
  return '';
8903
8582
  } else if (col.aggregatorid === 'LAST') {
8904
- return pre + "g['" + colas + "']=" + colexp + ';' + post;
8583
+ return `${pre}g['${colas}']=${colexp};${post}`;
8905
8584
  } else if (col.aggregatorid === 'AVG') {
8906
- return (
8907
- '' +
8908
- pre +
8909
- "g['_SUM_" +
8910
- colas +
8911
- "']+=(y=" +
8912
- colexp +
8913
- ')||0;' +
8914
- "g['_COUNT_" +
8915
- colas +
8916
- '\']+=(typeof y == "undefined" || y === null) ? 0 : 1;' +
8917
- "g['" +
8918
- colas +
8919
- "']=g['_SUM_" +
8920
- colas +
8921
- "']/g['_COUNT_" +
8922
- colas +
8923
- "'];" +
8924
- post
8925
- );
8926
- // }
8927
- // else if(col.aggregatorid == 'AVG') { srg.push(colas+':0'); }
8585
+ return `${pre}
8586
+ g['_SUM_${colas}'] += (y=${colexp})||0;
8587
+ g['_COUNT_${colas}'] += (typeof y == "undefined" || y === null) ? 0 : 1;
8588
+ g['${colas}']=g['_SUM_${colas}'] / g['_COUNT_${colas}'];
8589
+ ${post}`;
8928
8590
  } else if (col.aggregatorid === 'AGGR') {
8929
- return '' + pre + "g['" + colas + "']=" + col.expression.toJS('g', -1) + ';' + post;
8591
+ return `${pre}
8592
+ g['${colas}']=${col.expression.toJS('g', -1)};
8593
+ ${post}`;
8930
8594
  } else if (col.aggregatorid === 'REDUCE') {
8931
- return (
8932
- '' +
8933
- pre +
8934
- "g['" +
8935
- colas +
8936
- "']=alasql.aggr." +
8937
- col.funcid +
8938
- '(' +
8939
- colexp +
8940
- ",g['" +
8941
- colas +
8942
- "'],2);" +
8943
- post
8944
- );
8595
+ return `${pre}
8596
+ g['${colas}'] = alasql.aggr.${col.funcid}(${colexp},g['${colas}'],2);
8597
+ ${post}`;
8945
8598
  }
8946
8599
 
8947
8600
  return '';
@@ -8951,24 +8604,8 @@ yy.Select.prototype.compileGroup = function (query) {
8951
8604
  })
8952
8605
  .join('');
8953
8606
 
8954
- // s += selectFields.map(function(f){
8955
-
8956
- // if(f.constructor.name == 'LiteralValue') return '';
8957
- // if (f.field instanceof SQLParser.nodes.FunctionValue
8958
- // && (f.field.name.toUpperCase() == 'SUM' || f.field.name.toUpperCase() == 'COUNT')) {
8959
- // return 'group.'+f.name.value+'=+(+group.'+f.name.value+'||0)+'+f.field.arguments[0].toJS('rec','')+';'; //f.field.arguments[0].toJS();
8960
- // return 'group.'+f.name.value+'+='+f.field.arguments[0].toJS('rec','')+';'; //f.field.arguments[0].toJS();
8961
- // return 'group.'+f.name.value+'+=rec.'+f.name.value+';'; //f.field.arguments[0].toJS();
8962
- // };
8963
- // return '';
8964
- // }).join('');
8965
-
8966
- // s += ' group.amt += rec.emplid;';
8967
- // s += 'group.count++;';
8968
-
8969
8607
  s += '}';
8970
8608
  });
8971
-
8972
8609
  return new Function('p,params,alasql', 'var y;' + s);
8973
8610
  };
8974
8611
  /*
@@ -9857,22 +9494,22 @@ yy.Select.prototype.compileUnpivot = function (query) {
9857
9494
  Calculate ROLLUP() combination
9858
9495
  */
9859
9496
 
9860
- var rollup = function (a, query) {
9861
- var rr = [];
9862
- var mask = 0;
9863
- var glen = a.length;
9864
- for (var g = 0; g < glen + 1; g++) {
9865
- var ss = [];
9866
- for (var i = 0; i < glen; i++) {
9497
+ const rollup = (a, query) => {
9498
+ const rr = [];
9499
+ let mask = 0;
9500
+ const glen = a.length;
9501
+
9502
+ for (let g = 0; g < glen + 1; g++) {
9503
+ const ss = [];
9504
+ for (let i = 0; i < glen; i++) {
9505
+ let aaa;
9867
9506
  if (a[i] instanceof yy.Column) {
9868
9507
  a[i].nick = escapeq(a[i].columnid);
9869
-
9870
9508
  query.groupColumns[escapeq(a[i].columnid)] = a[i].nick;
9871
- var aaa = a[i].nick + '\t' + a[i].toJS('p', query.sources[0].alias, query.defcols);
9509
+ aaa = `${a[i].nick}\t${a[i].toJS('p', query.sources[0].alias, query.defcols)}`;
9872
9510
  } else {
9873
9511
  query.groupColumns[escapeq(a[i].toString())] = escapeq(a[i].toString());
9874
- var aaa =
9875
- escapeq(a[i].toString()) + '\t' + a[i].toJS('p', query.sources[0].alias, query.defcols);
9512
+ aaa = `${escapeq(a[i].toString())}\t${a[i].toJS('p', query.sources[0].alias, query.defcols)}`;
9876
9513
  }
9877
9514
 
9878
9515
  if (mask & (1 << i)) ss.push(aaa);
@@ -9886,22 +9523,17 @@ var rollup = function (a, query) {
9886
9523
  /**
9887
9524
  Calculate CUBE()
9888
9525
  */
9889
- var cube = function (a, query) {
9890
- var rr = [];
9891
- var glen = a.length;
9892
- var glenCube = 1 << glen;
9893
- for (var g = 0; g < glenCube; g++) {
9894
- var ss = [];
9895
- for (var i = 0; i < glen; i++) {
9896
- if (g & (1 << i))
9897
- //ss.push(a[i]);
9898
- //ss = cartes(ss,decartes(a[i]));
9899
-
9900
- // var aaa = a[i].toString()+'\t'
9901
- // +a[i].toJS('p',query.sources[0].alias,query.defcols);
9902
-
9526
+ const cube = (a, query) => {
9527
+ const rr = [];
9528
+ const glen = a.length;
9529
+ const glenCube = 1 << glen;
9530
+
9531
+ for (let g = 0; g < glenCube; g++) {
9532
+ let ss = [];
9533
+ for (let i = 0; i < glen; i++) {
9534
+ if (g & (1 << i)) {
9903
9535
  ss = ss.concat(decartes(a[i], query));
9904
- //
9536
+ }
9905
9537
  }
9906
9538
  rr.push(ss);
9907
9539
  }
@@ -9909,22 +9541,21 @@ var cube = function (a, query) {
9909
9541
  };
9910
9542
 
9911
9543
  /**
9912
- GROUPING SETS()
9544
+ * GROUPING SETS()
9913
9545
  */
9914
- var groupingsets = function (a, query) {
9915
- return a.reduce(function (acc, d) {
9546
+ const groupingsets = (a, query) =>
9547
+ a.reduce((acc, d) => {
9916
9548
  acc = acc.concat(decartes(d, query));
9917
9549
  return acc;
9918
9550
  }, []);
9919
- };
9920
9551
 
9921
9552
  /**
9922
- Cartesian production
9553
+ * Cartesian production
9923
9554
  */
9924
- var cartes = function (a1, a2) {
9925
- var rrr = [];
9926
- for (var i1 = 0; i1 < a1.length; i1++) {
9927
- for (var i2 = 0; i2 < a2.length; i2++) {
9555
+ const cartes = (a1, a2) => {
9556
+ const rrr = [];
9557
+ for (let i1 = 0; i1 < a1.length; i1++) {
9558
+ for (let i2 = 0; i2 < a2.length; i2++) {
9928
9559
  rrr.push(a1[i1].concat(a2[i2]));
9929
9560
  }
9930
9561
  }
@@ -9933,72 +9564,54 @@ var cartes = function (a1, a2) {
9933
9564
 
9934
9565
  /**
9935
9566
  Prepare groups function
9936
- */
9937
- function decartes(gv, query) {
9938
-
9567
+ */ function decartes(gv, query) {
9939
9568
  if (Array.isArray(gv)) {
9940
- var res = [[]];
9941
- for (var t = 0; t < gv.length; t++) {
9569
+ let res = [[]];
9570
+ for (let t = 0; t < gv.length; t++) {
9942
9571
  if (gv[t] instanceof yy.Column) {
9943
-
9944
9572
  gv[t].nick = gv[t].nick ? escapeq(gv[t].nick) : escapeq(gv[t].columnid);
9945
9573
  query.groupColumns[gv[t].nick] = gv[t].nick;
9946
- res = res.map(function (r) {
9947
- return r.concat(
9948
- gv[t].nick + '\t' + gv[t].toJS('p', query.sources[0].alias, query.defcols)
9949
- );
9950
- });
9951
- // res = res.map(function(r){return r.concat(gv[t].columnid)});
9574
+ res = res.map(r =>
9575
+ r.concat(`${gv[t].nick}\t${gv[t].toJS('p', query.sources[0].alias, query.defcols)}`)
9576
+ );
9952
9577
  } else if (gv[t] instanceof yy.FuncValue) {
9953
9578
  query.groupColumns[escapeq(gv[t].toString())] = escapeq(gv[t].toString());
9954
- res = res.map(function (r) {
9955
- return r.concat(
9956
- escapeq(gv[t].toString()) +
9957
- '\t' +
9958
- gv[t].toJS('p', query.sources[0].alias, query.defcols)
9959
- );
9960
- });
9961
- // to be defined
9579
+ res = res.map(r =>
9580
+ r.concat(
9581
+ `${escapeq(gv[t].toString())}\t${gv[t].toJS('p', query.sources[0].alias, query.defcols)}`
9582
+ )
9583
+ );
9962
9584
  } else if (gv[t] instanceof yy.GroupExpression) {
9963
9585
  if (gv[t].type == 'ROLLUP') res = cartes(res, rollup(gv[t].group, query));
9964
9586
  else if (gv[t].type == 'CUBE') res = cartes(res, cube(gv[t].group, query));
9965
9587
  else if (gv[t].type == 'GROUPING SETS') res = cartes(res, groupingsets(gv[t].group, query));
9966
9588
  else throw new Error('Unknown grouping function');
9967
9589
  } else if (gv[t] === '') {
9968
-
9969
9590
  res = [['1\t1']];
9970
9591
  } else {
9971
- // if(gv[t])
9972
-
9973
- res = res.map(function (r) {
9974
- query.groupColumns[escapeq(gv[t].toString())] = escapeq(gv[t].toString());
9975
- return r.concat(
9976
- escapeq(gv[t].toString()) +
9977
- '\t' +
9978
- gv[t].toJS('p', query.sources[0].alias, query.defcols)
9979
- );
9980
- });
9981
- // res = res.concat(gv[t]);
9592
+ res = res.map(r =>
9593
+ r.concat(
9594
+ `${escapeq(gv[t].toString())}\t${gv[t].toJS('p', query.sources[0].alias, query.defcols)}`
9595
+ )
9596
+ );
9982
9597
  }
9983
-
9984
9598
  }
9985
9599
  return res;
9986
- } else if (gv instanceof yy.FuncValue) {
9600
+ }
9987
9601
 
9602
+ if (gv instanceof yy.FuncValue) {
9988
9603
  query.groupColumns[escapeq(gv.toString())] = escapeq(gv.toString());
9989
- return [gv.toString() + '\t' + gv.toJS('p', query.sources[0].alias, query.defcols)];
9990
- } else if (gv instanceof yy.Column) {
9604
+ return [`${gv.toString()}\t${gv.toJS('p', query.sources[0].alias, query.defcols)}`];
9605
+ }
9606
+
9607
+ if (gv instanceof yy.Column) {
9991
9608
  gv.nick = escapeq(gv.columnid);
9992
9609
  query.groupColumns[gv.nick] = gv.nick;
9993
- return [gv.nick + '\t' + gv.toJS('p', query.sources[0].alias, query.defcols)]; // Is this ever happened?
9994
- // } else if(gv instanceof yy.Expression) {
9995
- // return [gv.columnid]; // Is this ever happened?
9996
- } else {
9997
- query.groupColumns[escapeq(gv.toString())] = escapeq(gv.toString());
9998
- return [escapeq(gv.toString()) + '\t' + gv.toJS('p', query.sources[0].alias, query.defcols)];
9999
- // throw new Error('Single argument in the group without array');
9610
+ return [`${gv.nick}\t${gv.toJS('p', query.sources[0].alias, query.defcols)}`];
10000
9611
  }
10001
9612
 
9613
+ query.groupColumns[escapeq(gv.toString())] = escapeq(gv.toString());
9614
+ return [`${escapeq(gv.toString())}\t${gv.toJS('p', query.sources[0].alias, query.defcols)}`];
10002
9615
  }
10003
9616
  /*
10004
9617
  //
@@ -10052,10 +9665,19 @@ yy.Select.prototype.compileDefCols = function (query, databaseid) {
10052
9665
  defcols['.'][jn.as || jn.table.tableid] = true;
10053
9666
 
10054
9667
  if (jn.table) {
10055
- var alias = jn.table.tableid;
10056
- if (jn.as) alias = jn.as;
10057
9668
  var alias = jn.as || jn.table.tableid;
10058
- var table = alasql.databases[jn.table.databaseid || databaseid].tables[jn.table.tableid];
9669
+ var databaseId = jn.table.databaseid || databaseid;
9670
+ var database = alasql.databases[databaseId];
9671
+
9672
+ if (database === undefined) {
9673
+ throw new Error('Database does not exist: ' + databaseId);
9674
+ }
9675
+
9676
+ var table = database.tables[jn.table.tableid];
9677
+
9678
+ if (table === undefined) {
9679
+ throw new Error('Table does not exist: ' + jn.table.tableid);
9680
+ }
10059
9681
 
10060
9682
  if (table.columns) {
10061
9683
  table.columns.forEach(function (col) {
@@ -10117,9 +9739,11 @@ yy.Apply = class Apply {
10117
9739
  }
10118
9740
 
10119
9741
  toString() {
10120
- var s = this.applymode + ' APPLY (' + this.select.toString() + ')';
9742
+ let s = `${this.applymode} APPLY (${this.select.toString()})`;
10121
9743
 
10122
- if (this.as) s += ' AS ' + this.as;
9744
+ if (this.as) {
9745
+ s += ` AS ${this.as}`;
9746
+ }
10123
9747
 
10124
9748
  return s;
10125
9749
  }
@@ -10138,13 +9762,13 @@ yy.Over = class Over {
10138
9762
  }
10139
9763
 
10140
9764
  toString() {
10141
- var s = 'OVER (';
9765
+ let s = 'OVER (';
10142
9766
  if (this.partition) {
10143
- s += 'PARTITION BY ' + this.partition.toString();
9767
+ s += `PARTITION BY ${this.partition.toString()}`;
10144
9768
  if (this.order) s += ' ';
10145
9769
  }
10146
9770
  if (this.order) {
10147
- s += 'ORDER BY ' + this.order.toString();
9771
+ s += `ORDER BY ${this.order.toString()}`;
10148
9772
  }
10149
9773
  s += ')';
10150
9774
  return s;
@@ -10176,7 +9800,6 @@ yy.Over = class Over {
10176
9800
  */
10177
9801
  execute(databaseid, params, cb) {
10178
9802
  if (this.expression) {
10179
-
10180
9803
  alasql.precompile(this, databaseid, params); // Precompile queries
10181
9804
  var exprfn = new Function(
10182
9805
  'params,alasql,p',
@@ -10433,20 +10056,15 @@ yy.Over = class Over {
10433
10056
  }
10434
10057
 
10435
10058
  toJS(context, tableid, defcols) {
10436
-
10437
10059
  var s;
10438
- var refs = [];
10439
- var op = this.op;
10440
- var _this = this;
10441
- //var leftJS = function(){return _this.left.toJS(context,tableid, defcols)};
10442
- //var rightJS = function(){return _this.right.toJS(context,tableid, defcols)};
10443
- var accessedLeft = false,
10444
- accessedRight = false;
10445
- var ref = function (expr) {
10060
+ let refs = [];
10061
+ let op = this.op;
10062
+ let _this = this;
10063
+ let ref = function (expr) {
10446
10064
  if (expr.toJS) {
10447
10065
  expr = expr.toJS(context, tableid, defcols);
10448
10066
  }
10449
- var i = refs.push(expr) - 1;
10067
+ let i = refs.push(expr) - 1;
10450
10068
  return 'y[' + i + ']';
10451
10069
  };
10452
10070
  var leftJS = function () {
@@ -10462,201 +10080,91 @@ yy.Over = class Over {
10462
10080
  op = '!=';
10463
10081
  } else if (this.op === 'OR') {
10464
10082
  op = '||';
10465
- }
10466
-
10467
- // Arrow operator
10468
- if (this.op === '->') {
10083
+ } else if (this.op === '->') {
10469
10084
  // Expression to prevent error if object is empty (#344)
10470
- var ljs = '(' + leftJS() + '||{})';
10085
+ const ljs = `(${leftJS()} || {})`;
10471
10086
 
10472
10087
  if (typeof this.right === 'string') {
10473
- s = ljs + '["' + escapeq(this.right) + '"]';
10088
+ s = `${ljs}["${escapeq(this.right)}"]`;
10474
10089
  } else if (typeof this.right === 'number') {
10475
- s = ljs + '[' + this.right + ']';
10090
+ s = `${ljs}[${this.right}]`;
10476
10091
  } else if (this.right instanceof yy.FuncValue) {
10477
- var ss = [];
10478
- if (!(!this.right.args || 0 === this.right.args.length)) {
10479
- var ss = this.right.args.map(ref);
10092
+ let ss = [];
10093
+ if (this.right.args && this.right.args.length > 0) {
10094
+ ss = this.right.args.map(ref);
10480
10095
  }
10481
- s = '' + ljs + '[' + JSON.stringify(this.right.funcid) + '](' + ss.join(',') + ')';
10096
+ s = `${ljs}[${JSON.stringify(this.right.funcid)}](${ss.join(',')})`;
10482
10097
  } else {
10483
- s = '' + ljs + '[' + rightJS() + ']';
10098
+ s = `${ljs}[${rightJS()}]`;
10484
10099
  }
10485
- }
10486
-
10487
- if (this.op === '!') {
10100
+ } else if (this.op === '!') {
10488
10101
  if (typeof this.right === 'string') {
10489
- s = '' + 'alasql.databases[alasql.useid].objects[' + leftJS() + ']["' + this.right + '"]';
10102
+ s = `alasql.databases[alasql.useid].objects[${leftJS()}]["${this.right}"]`;
10490
10103
  }
10491
10104
  // TODO - add other cases
10492
- }
10493
-
10494
- if (this.op === 'IS') {
10105
+ } else if (this.op === 'IS') {
10495
10106
  const leftOperand = leftJS();
10496
10107
  const rightOperand = rightJS();
10497
10108
  if (
10498
10109
  this.right instanceof yy.NullValue ||
10499
10110
  (this.right.op === 'NOT' && this.right.right instanceof yy.NullValue)
10500
10111
  ) {
10501
- s = `((${leftOperand} == null) === (${rightOperand} == null))`; // == null cant be ===
10112
+ s = `((${leftOperand} == null) === (${rightOperand} == null))`; // == null can't be ===
10502
10113
  } else {
10503
- s = `((${leftOperand} == ${rightOperand}) || (${leftOperand} < 0 && true == ${rightOperand}))`;
10114
+ s = `((${leftOperand} == ${rightOperand}) || (${leftOperand} < 0 && true == ${rightOperand}))`;
10504
10115
  }
10505
- }
10506
-
10507
- if (this.op === '==') {
10508
- s = '' + 'alasql.utils.deepEqual(' + leftJS() + ',' + rightJS() + ')';
10509
- }
10510
-
10511
- if (this.op === '===' || this.op === '!===') {
10512
- s =
10513
- '' +
10514
- '(' +
10515
- (this.op === '!===' ? '!' : '') +
10516
- '(' +
10517
- '(' +
10518
- leftJS() +
10519
- ').valueOf()' +
10520
- '===' +
10521
- '(' +
10522
- rightJS() +
10523
- ').valueOf()' +
10524
- ')' +
10525
- ')';
10526
- }
10527
-
10528
- if (this.op === '!==') {
10529
- s = '' + '(!alasql.utils.deepEqual(' + leftJS() + ',' + rightJS() + '))';
10530
- }
10531
- if (this.op === '||') {
10532
- s = '' + "(''+(" + leftJS() + "||'')+(" + rightJS() + '||""))';
10533
- }
10534
- if (this.op === 'LIKE' || this.op === 'NOT LIKE') {
10535
- var s =
10536
- '(' +
10537
- (this.op === 'NOT LIKE' ? '!' : '') +
10538
- 'alasql.utils.like(' +
10539
- rightJS() +
10540
- ',' +
10541
- leftJS();
10542
- if (this.escape) {
10543
- s += ',' + ref(this.escape);
10544
- }
10545
- s += '))';
10546
- }
10547
- if (this.op === 'REGEXP') {
10548
- s = 'alasql.stdfn.REGEXP_LIKE(' + leftJS() + ',' + rightJS() + ')';
10549
- }
10550
- if (this.op === 'GLOB') {
10551
- s = 'alasql.utils.glob(' + leftJS() + ',' + rightJS() + ')';
10552
- }
10553
-
10554
- if (this.op === 'BETWEEN' || this.op === 'NOT BETWEEN') {
10555
- var left = leftJS();
10556
- s =
10557
- '' +
10558
- '(' +
10559
- (this.op === 'NOT BETWEEN' ? '!' : '') +
10560
- '(' +
10561
- '(' +
10562
- ref(this.right1) +
10563
- '<=' +
10564
- left +
10565
- ') && (' +
10566
- left +
10567
- '<=' +
10568
- ref(this.right2) +
10569
- ')' +
10570
- ')' +
10571
- ')';
10572
- }
10573
-
10574
- if (this.op === 'IN') {
10116
+ } else if (this.op === '==') {
10117
+ s = `alasql.utils.deepEqual(${leftJS()}, ${rightJS()})`;
10118
+ } else if (this.op === '===' || this.op === '!===') {
10119
+ s = `(${this.op === '!===' ? '!' : ''}((${leftJS()}).valueOf() === (${rightJS()}).valueOf()))`;
10120
+ } else if (this.op === '!==') {
10121
+ s = `(!alasql.utils.deepEqual(${leftJS()}, ${rightJS()}))`;
10122
+ } else if (this.op === '||') {
10123
+ s = `(''+(${leftJS()} || '') + (${rightJS()} || ''))`;
10124
+ } else if (this.op === 'LIKE' || this.op === 'NOT LIKE') {
10125
+ s = `(${this.op === 'NOT LIKE' ? '!' : ''}alasql.utils.like(${rightJS()}, ${leftJS()}${this.escape ? `, ${ref(this.escape)}` : ''}))`;
10126
+ } else if (this.op === 'REGEXP') {
10127
+ s = `alasql.stdfn.REGEXP_LIKE(${leftJS()}, ${rightJS()})`;
10128
+ } else if (this.op === 'GLOB') {
10129
+ s = `alasql.utils.glob(${leftJS()}, ${rightJS()})`;
10130
+ } else if (this.op === 'BETWEEN' || this.op === 'NOT BETWEEN') {
10131
+ const left = leftJS();
10132
+ s = `(${this.op === 'NOT BETWEEN' ? '!' : ''}((${ref(this.right1)} <= ${left}) && (${left} <= ${ref(this.right2)})))`;
10133
+ } else if (this.op === 'IN') {
10575
10134
  if (this.right instanceof yy.Select) {
10576
- s = '(';
10577
- // s += 'this.query.queriesdata['+this.queriesidx+']';
10578
- // s += 'alasql.utils.flatArray(this.query.queriesfn['+(this.queriesidx)+'](params,null,context))';
10579
- s +=
10580
- 'alasql.utils.flatArray(this.queriesfn[' +
10581
- this.queriesidx +
10582
- '](params,null,' +
10583
- context +
10584
- '))';
10585
- s += '.indexOf(';
10586
- s += 'alasql.utils.getValueOf(' + leftJS() + '))>-1)';
10135
+ s = `alasql.utils.flatArray(this.queriesfn[${this.queriesidx}](params, null, ${context})).indexOf(alasql.utils.getValueOf(${leftJS()})) > -1`;
10587
10136
  } else if (Array.isArray(this.right)) {
10588
- if (
10589
- !alasql.options.cache ||
10590
- this.right.filter(value => value instanceof yy.ParamValue).length > 0
10591
- ) {
10592
- // When not using cache, or when the array contains parameters, we need to re-create the Set
10593
- // leverage JS Set, which is faster for lookups than arrays
10594
- s =
10595
- '(new Set([' +
10596
- this.right.map(ref).join(',') +
10597
- ']).has(alasql.utils.getValueOf(' +
10598
- leftJS() +
10599
- ')))';
10137
+ if (!alasql.options.cache || this.right.some(value => value instanceof yy.ParamValue)) {
10138
+ // Leverage JS Set for faster lookups than arrays
10139
+ s = `(new Set([${this.right.map(ref).join(',')}]).has(alasql.utils.getValueOf(${leftJS()})))`;
10600
10140
  } else {
10601
- // Use a cache to not re-create the Set on every identitical query
10602
- if (!alasql.sets) {
10603
- alasql.sets = {};
10604
- }
10141
+ // Use a cache to avoid re-creating the Set on every identical query
10142
+ alasql.sets = alasql.sets || {};
10605
10143
  const allValues = this.right.map(value => value.value);
10606
10144
  const allValuesStr = allValues.join(',');
10607
- if (!alasql.sets[allValuesStr]) {
10608
- // leverage JS Set, which is faster for lookups than arrays
10609
- alasql.sets[allValuesStr] = new Set(allValues);
10610
- }
10611
- s =
10612
- 'alasql.sets["' + allValuesStr + '"].has(alasql.utils.getValueOf(' + leftJS() + '))';
10145
+ alasql.sets[allValuesStr] = alasql.sets[allValuesStr] || new Set(allValues);
10146
+ s = `alasql.sets["${allValuesStr}"].has(alasql.utils.getValueOf(${leftJS()}))`;
10613
10147
  }
10614
10148
  } else {
10615
- s = '(' + rightJS() + '.indexOf(' + leftJS() + ')>-1)';
10616
-
10617
- // } else {
10618
- // throw new Error('Wrong IN operator without SELECT part');
10149
+ s = `(${rightJS()}.indexOf(${leftJS()}) > -1)`;
10619
10150
  }
10620
- }
10621
-
10622
- if (this.op === 'NOT IN') {
10151
+ } else if (this.op === 'NOT IN') {
10623
10152
  if (this.right instanceof yy.Select) {
10624
- s = '(';
10625
- s += 'alasql.utils.flatArray(this.queriesfn[' + this.queriesidx + '](params,null,p))';
10626
- s += '.indexOf(';
10627
- s += 'alasql.utils.getValueOf(' + leftJS() + '))<0)';
10153
+ s = `alasql.utils.flatArray(this.queriesfn[${this.queriesidx}](params, null, p)).indexOf(alasql.utils.getValueOf(${leftJS()})) < 0`;
10628
10154
  } else if (Array.isArray(this.right)) {
10629
- if (
10630
- !alasql.options.cache ||
10631
- this.right.filter(value => value instanceof yy.ParamValue).length > 0
10632
- ) {
10633
- // When not using cache, or when the array contains parameters, we need to re-create the Set
10634
- // leverage JS Set, which is faster for lookups than arrays
10635
- s =
10636
- '(!(new Set([' +
10637
- this.right.map(ref).join(',') +
10638
- ']).has(alasql.utils.getValueOf(' +
10639
- leftJS() +
10640
- '))))';
10155
+ if (!alasql.options.cache || this.right.some(value => value instanceof yy.ParamValue)) {
10156
+ // Leverage JS Set for faster lookups than arrays
10157
+ s = `(!(new Set([${this.right.map(ref).join(',')}]).has(alasql.utils.getValueOf(${leftJS()}))))`;
10641
10158
  } else {
10642
- // Use a cache to not re-create the Set on every identitical query
10643
- if (!alasql.sets) {
10644
- alasql.sets = {};
10645
- }
10159
+ // Use a cache to avoid re-creating the Set on every identical query
10160
+ alasql.sets = alasql.sets || {};
10646
10161
  const allValues = this.right.map(value => value.value);
10647
10162
  const allValuesStr = allValues.join(',');
10648
- if (!alasql.sets[allValuesStr]) {
10649
- // leverage JS Set, which is faster for lookups than arrays
10650
- alasql.sets[allValuesStr] = new Set(allValues);
10651
- }
10652
- s =
10653
- '!alasql.sets["' + allValuesStr + '"].has(alasql.utils.getValueOf(' + leftJS() + '))';
10163
+ alasql.sets[allValuesStr] = alasql.sets[allValuesStr] || new Set(allValues);
10164
+ s = `!alasql.sets["${allValuesStr}"].has(alasql.utils.getValueOf(${leftJS()}))`;
10654
10165
  }
10655
10166
  } else {
10656
- s = '(' + rightJS() + '.indexOf(';
10657
- s += leftJS() + ')==-1)';
10658
-
10659
- // throw new Error('Wrong NOT IN operator without SELECT part');
10167
+ s = `(${rightJS()}.indexOf(${leftJS()}) === -1)`;
10660
10168
  }
10661
10169
  }
10662
10170
 
@@ -10724,9 +10232,7 @@ yy.Over = class Over {
10724
10232
  return '(' + declareRefs + ', ' + expr + ')';
10725
10233
  }
10726
10234
 
10727
- return (
10728
- '(' + declareRefs + ', ' + 'y.some(function(e){return e == null}) ? void 0 : ' + expr + ')'
10729
- );
10235
+ return `(${declareRefs}, y.some(e => e == null) ? void 0 : ${expr})`;
10730
10236
  }
10731
10237
  }
10732
10238
 
@@ -10798,8 +10304,6 @@ yy.Over = class Over {
10798
10304
  }
10799
10305
 
10800
10306
  toJS(context, tableid, defcols) {
10801
-
10802
- // return "'"+doubleqq(this.value)+"'";
10803
10307
  return context;
10804
10308
  }
10805
10309
  }
@@ -11351,7 +10855,6 @@ yy.FuncValue.prototype.toJS = function (context, tableid, defcols) {
11351
10855
  } else if (!alasql.fn[funcid] && alasql.stdfn[funcid.toUpperCase()]) {
11352
10856
  if (this.newid) s += 'new ';
11353
10857
  s += 'alasql.stdfn[' + JSON.stringify(this.funcid.toUpperCase()) + '](';
11354
- // if(this.args) s += this.args.toJS(context, tableid);
11355
10858
  if (this.args && this.args.length > 0) {
11356
10859
  s += this.args
11357
10860
  .map(function (arg) {
@@ -11366,7 +10869,6 @@ yy.FuncValue.prototype.toJS = function (context, tableid, defcols) {
11366
10869
  // var s = '';
11367
10870
  if (this.newid) s += 'new ';
11368
10871
  s += 'alasql.fn[' + JSON.stringify(this.funcid) + '](';
11369
- // if(this.args) s += this.args.toJS(context, tableid);
11370
10872
  if (this.args && this.args.length > 0) {
11371
10873
  s += this.args
11372
10874
  .map(function (arg) {
@@ -11376,9 +10878,18 @@ yy.FuncValue.prototype.toJS = function (context, tableid, defcols) {
11376
10878
  }
11377
10879
  s += ')';
11378
10880
  }
11379
-
11380
10881
  return s;
11381
10882
  };
10883
+ /*
10884
+ //
10885
+ // SQL FUNCTIONS COMPILERS
10886
+ // Based on SQLite functions
10887
+
10888
+ // IMPORTANT: These are compiled functions
10889
+
10890
+ //alasql.fn = {}; // Keep for compatibility
10891
+ //alasql.userlib = alasql.fn;
10892
+ */
11382
10893
 
11383
10894
  var stdlib = (alasql.stdlib = {});
11384
10895
  var stdfn = (alasql.stdfn = {});
@@ -11399,16 +10910,16 @@ stdlib.EXP = function (a) {
11399
10910
 
11400
10911
  stdlib.IIF = function (a, b, c) {
11401
10912
  if (arguments.length === 3) {
11402
- return '((' + a + ')?(' + b + '):(' + c + '))';
10913
+ return `((${a}) ? (${b}) : (${c}))`;
11403
10914
  } else {
11404
10915
  throw new Error('Number of arguments of IFF is not equals to 3');
11405
10916
  }
11406
10917
  };
11407
10918
  stdlib.IFNULL = function (a, b) {
11408
- return '((typeof ' + a + ' ==="undefined" || null === ' + a + ')?' + b + ':' + a + ')';
10919
+ return `((typeof ${a} === "undefined" || ${a} === null) ? ${b} : ${a})`;
11409
10920
  };
11410
10921
  stdlib.INSTR = function (s, p) {
11411
- return '((' + s + ').indexOf(' + p + ')+1)';
10922
+ return `((${s}).indexOf(${p}) + 1)`;
11412
10923
  };
11413
10924
 
11414
10925
  //stdlib.LEN = stdlib.LENGTH = function(s) {return '('+s+'+"").length';};
@@ -11531,7 +11042,7 @@ stdfn.CONCAT_WS = function () {
11531
11042
  // TRIM
11532
11043
 
11533
11044
  // Aggregator for joining strings
11534
- alasql.aggr.GROUP_CONCAT = function (v, s, stage) {
11045
+ alasql.aggr.group_concat = alasql.aggr.GROUP_CONCAT = function (v, s, stage) {
11535
11046
  if (stage === 1) {
11536
11047
  return '' + v;
11537
11048
  } else if (stage === 2) {
@@ -11560,15 +11071,15 @@ alasql.aggr.median = alasql.aggr.MEDIAN = function (v, s, stage) {
11560
11071
  return null;
11561
11072
  }
11562
11073
 
11563
- var r = s.sort((a, b) => {
11074
+ let r = s.sort((a, b) => {
11564
11075
  if (a > b) return 1;
11565
11076
  if (a < b) return -1;
11566
11077
  return 0;
11567
11078
  });
11568
11079
 
11569
- var middle = (r.length + 1) / 2;
11570
- var middleFloor = middle | 0;
11571
- var el = r[middleFloor - 1];
11080
+ let middle = (r.length + 1) / 2;
11081
+ let middleFloor = middle | 0;
11082
+ let el = r[middleFloor - 1];
11572
11083
 
11573
11084
  if (middle === middleFloor || (typeof el !== 'number' && !(el instanceof Number))) {
11574
11085
  return el;
@@ -11584,32 +11095,34 @@ alasql.aggr.QUART = function (v, s, stage, nth) {
11584
11095
  s.push(v);
11585
11096
  }
11586
11097
  return s;
11587
- } else if (stage === 1) {
11098
+ }
11099
+
11100
+ if (stage === 1) {
11588
11101
  if (v === null) {
11589
11102
  return [];
11590
11103
  }
11591
11104
  return [v];
11592
- } else {
11593
- if (!s.length) {
11594
- return s;
11595
- }
11105
+ }
11106
+ if (!s.length) {
11107
+ return s;
11108
+ }
11596
11109
 
11597
- nth = !nth ? 1 : nth;
11598
- var r = s.sort(function (a, b) {
11599
- if (a === b) {
11600
- return 0;
11601
- }
11602
- if (a > b) {
11603
- return 1;
11604
- }
11605
- return -1;
11606
- });
11607
- var p = (nth * (r.length + 1)) / 4;
11608
- if (Number.isInteger(p)) {
11609
- return r[p - 1]; //Integer value
11610
- }
11611
- return r[Math.floor(p)]; //Math.ceil -1 or Math.floor
11110
+ nth = !nth ? 1 : nth;
11111
+ var r = s.sort(function (a, b) {
11112
+ if (a === b) return 0;
11113
+
11114
+ if (a > b) return 1;
11115
+
11116
+ return -1;
11117
+ });
11118
+
11119
+ let p = (nth * (r.length + 1)) / 4;
11120
+
11121
+ if (Number.isInteger(p)) {
11122
+ return r[p - 1]; //Integer value
11612
11123
  }
11124
+
11125
+ return r[Math.floor(p)]; //Math.ceil -1 or Math.floor
11613
11126
  };
11614
11127
 
11615
11128
  alasql.aggr.QUART2 = function (v, s, stage) {
@@ -11624,26 +11137,25 @@ alasql.aggr.QUART3 = function (v, s, stage) {
11624
11137
  // Standard deviation
11625
11138
  alasql.aggr.VAR = function (v, s, stage) {
11626
11139
  if (stage === 1) {
11627
- if (v === null) {
11628
- return {arr: [], sum: 0};
11629
- }
11630
- return {arr: [v], sum: v};
11140
+ // Initialise sum, sum of squares, and count
11141
+ return v === null ? {sum: 0, sumSq: 0, count: 0} : {sum: v, sumSq: v * v, count: 1};
11631
11142
  } else if (stage === 2) {
11632
- if (v === null) {
11633
- return s;
11143
+ // Update sum, sum of squares, and count
11144
+ if (v !== null) {
11145
+ s.sum += v;
11146
+ s.sumSq += v * v;
11147
+ s.count++;
11634
11148
  }
11635
- s.arr.push(v);
11636
- s.sum += v;
11637
11149
  return s;
11638
11150
  } else {
11639
- var N = s.arr.length;
11640
- var avg = s.sum / N;
11641
- var std = 0;
11642
- for (var i = 0; i < N; i++) {
11643
- std += (s.arr[i] - avg) * (s.arr[i] - avg);
11151
+ // Calculate variance using the formula: variance = (sumSq - (sum^2 / count)) / (count - 1)
11152
+ // This avoids the need to store and iterate over all values
11153
+ if (s.count > 1) {
11154
+ return (s.sumSq - (s.sum * s.sum) / s.count) / (s.count - 1);
11155
+ } else {
11156
+ // Handling for cases with less than 2 values (variance is undefined or zero)
11157
+ return 0;
11644
11158
  }
11645
- std = std / (N - 1);
11646
- return std;
11647
11159
  }
11648
11160
  };
11649
11161
 
@@ -11655,27 +11167,33 @@ alasql.aggr.STDEV = function (v, s, stage) {
11655
11167
  }
11656
11168
  };
11657
11169
 
11658
- // Standard deviation
11659
- // alasql.aggr.VARP = function(v,s,acc){
11660
-
11661
- // };
11170
+ alasql.aggr.STDEV = function (v, s, stage) {
11171
+ if (stage === 1 || stage === 2) {
11172
+ return alasql.aggr.VAR(v, s, stage);
11173
+ } else {
11174
+ return Math.sqrt(alasql.aggr.VAR(v, s, stage));
11175
+ }
11176
+ };
11662
11177
 
11663
- alasql.aggr.VARP = function (v, s, stage) {
11664
- if (stage == 1) {
11665
- return {arr: [v], sum: v};
11666
- } else if (stage == 2) {
11667
- s.arr.push(v);
11668
- s.sum += v;
11669
- return s;
11178
+ alasql.aggr.VARP = function (value, accumulator, stage) {
11179
+ if (stage === 1) {
11180
+ // Initialise accumulator with count, sum, and sum of squares
11181
+ return {count: 1, sum: value, sumSq: value * value};
11182
+ } else if (stage === 2) {
11183
+ // Update accumulator
11184
+ accumulator.count++;
11185
+ accumulator.sum += value;
11186
+ accumulator.sumSq += value * value;
11187
+ return accumulator;
11670
11188
  } else {
11671
- var N = s.arr.length;
11672
- var avg = s.sum / N;
11673
- var std = 0;
11674
- for (var i = 0; i < N; i++) {
11675
- std += (s.arr[i] - avg) * (s.arr[i] - avg);
11189
+ // Final stage: Calculate variance
11190
+ if (accumulator.count > 0) {
11191
+ const mean = accumulator.sum / accumulator.count;
11192
+ const variance = accumulator.sumSq / accumulator.count - mean * mean;
11193
+ return variance;
11194
+ } else {
11195
+ return 0; // Return 0 variance if no values were aggregated
11676
11196
  }
11677
- std = std / N;
11678
- return std;
11679
11197
  }
11680
11198
  };
11681
11199
 
@@ -11779,38 +11297,32 @@ yy.CaseValue.prototype.findAggregator = function (query) {
11779
11297
  };
11780
11298
 
11781
11299
  yy.CaseValue.prototype.toJS = function (context, tableid, defcols) {
11782
- var s = '((function(' + context + ',params,alasql){var y,r;';
11783
- if (this.expression) {
11784
- // this.expression.toJS(context, tableid)
11785
- s += 'v=' + this.expression.toJS(context, tableid, defcols) + ';';
11786
- s += (this.whens || [])
11787
- .map(function (w) {
11788
- return (
11789
- ' if(v==' +
11790
- w.when.toJS(context, tableid, defcols) +
11791
- ') {r=' +
11792
- w.then.toJS(context, tableid, defcols) +
11793
- '}'
11794
- );
11795
- })
11796
- .join(' else ');
11797
- if (this.elses) s += ' else {r=' + this.elses.toJS(context, tableid, defcols) + '}';
11300
+ let s = `(((${context}, params, alasql) => {
11301
+ let y, r;`;
11302
+
11303
+ if (this.expression) {
11304
+ // If there's an expression, evaluate it and store in `v`, then compare in `when` clauses
11305
+ s += `let v = ${this.expression.toJS(context, tableid, defcols)};`;
11306
+ this.whens.forEach((w, index) => {
11307
+ const condition = `v === ${w.when.toJS(context, tableid, defcols)}`;
11308
+ const assignment = `r = ${w.then.toJS(context, tableid, defcols)}`;
11309
+ s += `${index === 0 ? 'if' : ' else if'} (${condition}) { ${assignment}; }`;
11310
+ });
11798
11311
  } else {
11799
- s += (this.whens || [])
11800
- .map(function (w) {
11801
- return (
11802
- ' if(' +
11803
- w.when.toJS(context, tableid, defcols) +
11804
- ') {r=' +
11805
- w.then.toJS(context, tableid, defcols) +
11806
- '}'
11807
- );
11808
- })
11809
- .join(' else ');
11810
- if (this.elses) s += ' else {r=' + this.elses.toJS(context, tableid, defcols) + '}';
11312
+ // Directly evaluate `when` conditions without an initial expression
11313
+ this.whens.forEach((w, index) => {
11314
+ const condition = w.when.toJS(context, tableid, defcols);
11315
+ const assignment = `r = ${w.then.toJS(context, tableid, defcols)}`;
11316
+ s += `${index === 0 ? 'if' : ' else if'} (${condition}) { ${assignment}; }`;
11317
+ });
11318
+ }
11319
+
11320
+ // Handle the `else` case
11321
+ if (this.elses) {
11322
+ s += ` else { r = ${this.elses.toJS(context, tableid, defcols)}; }`;
11811
11323
  }
11812
- // TODO remove bind from CASE
11813
- s += ';return r;}).bind(this))(' + context + ',params,alasql)';
11324
+
11325
+ s += '; return r; }))(' + context + ', params, alasql)';
11814
11326
 
11815
11327
  return s;
11816
11328
  };
@@ -11832,47 +11344,31 @@ yy.Json.prototype.toString = function () {
11832
11344
  return s;
11833
11345
  };
11834
11346
 
11835
- var JSONtoString = (alasql.utils.JSONtoString = function (obj) {
11836
- var s = '';
11837
- if (typeof obj == 'string') s = '"' + obj + '"';
11838
- else if (typeof obj == 'number') s = obj;
11839
- else if (typeof obj == 'boolean') s = obj;
11840
- else if (typeof obj == 'object') {
11841
- if (Array.isArray(obj)) {
11842
- s +=
11843
- '[' +
11844
- obj
11845
- .map(function (b) {
11846
- return JSONtoString(b);
11847
- })
11848
- .join(',') +
11849
- ']';
11850
- } else if (!obj.toJS || obj instanceof yy.Json) {
11851
- // to prevent recursion
11852
- s = '{';
11853
- var ss = [];
11854
- for (var k in obj) {
11855
- var s1 = '';
11856
- if (typeof k == 'string') s1 += '"' + k + '"';
11857
- else if (typeof k == 'number') s1 += k;
11858
- else if (typeof k == 'boolean') s1 += k;
11859
- else {
11860
- throw new Error('THis is not ES6... no expressions on left side yet');
11861
- }
11862
- s1 += ':' + JSONtoString(obj[k]);
11863
- ss.push(s1);
11347
+ const JSONtoString = (alasql.utils.JSONtoString = function (obj) {
11348
+ if (typeof obj === 'string') return `"${obj}"`;
11349
+ if (typeof obj === 'number' || typeof obj === 'boolean') return String(obj);
11350
+
11351
+ if (Array.isArray(obj)) {
11352
+ return `[${obj.map(b => JSONtoString(b)).join(',')}]`;
11353
+ }
11354
+
11355
+ if (typeof obj === 'object') {
11356
+ if (!obj.toJS || obj instanceof yy.Json) {
11357
+ const ss = [];
11358
+ for (const k in obj) {
11359
+ const keyStr = typeof k === 'string' ? `"${k}"` : String(k);
11360
+ const valueStr = JSONtoString(obj[k]);
11361
+ ss.push(`${keyStr}:${valueStr}`);
11864
11362
  }
11865
- s += ss.join(',') + '}';
11363
+ return `{${ss.join(',')}}`;
11866
11364
  } else if (obj.toString) {
11867
- s = obj.toString();
11365
+ return obj.toString();
11868
11366
  } else {
11869
- throw new Error('1Can not show JSON object ' + JSON.stringify(obj));
11367
+ throw new Error(`1: Cannot show JSON object ${JSON.stringify(obj)}`);
11870
11368
  }
11871
11369
  } else {
11872
- throw new Error('2Can not show JSON object ' + JSON.stringify(obj));
11370
+ throw new Error(`2: Cannot show JSON object ${JSON.stringify(obj)}`);
11873
11371
  }
11874
-
11875
- return s;
11876
11372
  });
11877
11373
 
11878
11374
  function JSONtoJS(obj, context, tableid, defcols) {
@@ -11880,36 +11376,21 @@ function JSONtoJS(obj, context, tableid, defcols) {
11880
11376
  if (typeof obj == 'string') s = '"' + obj + '"';
11881
11377
  else if (typeof obj == 'number') s = '(' + obj + ')';
11882
11378
  else if (typeof obj == 'boolean') s = obj;
11883
- else if (typeof obj == 'object') {
11379
+ else if (typeof obj === 'object') {
11884
11380
  if (Array.isArray(obj)) {
11885
- s +=
11886
- '[' +
11887
- obj
11888
- .map(function (b) {
11889
- return JSONtoJS(b, context, tableid, defcols);
11890
- })
11891
- .join(',') +
11892
- ']';
11381
+ s += `[${obj.map(b => JSONtoJS(b, context, tableid, defcols)).join(',')}]`;
11893
11382
  } else if (!obj.toJS || obj instanceof yy.Json) {
11894
- // to prevent recursion
11895
- s = '{';
11896
- var ss = [];
11897
- for (var k in obj) {
11898
- var s1 = '';
11899
- if (typeof k == 'string') s1 += '"' + k + '"';
11900
- else if (typeof k == 'number') s1 += k;
11901
- else if (typeof k == 'boolean') s1 += k;
11902
- else {
11903
- throw new Error('THis is not ES6... no expressions on left side yet');
11904
- }
11905
- s1 += ':' + JSONtoJS(obj[k], context, tableid, defcols);
11906
- ss.push(s1);
11383
+ let ss = [];
11384
+ for (const k in obj) {
11385
+ let keyStr = typeof k === 'string' ? `"${k}"` : k.toString();
11386
+ let valueStr = JSONtoJS(obj[k], context, tableid, defcols);
11387
+ ss.push(`${keyStr}:${valueStr}`);
11907
11388
  }
11908
- s += ss.join(',') + '}';
11389
+ s = `{${ss.join(',')}}`;
11909
11390
  } else if (obj.toJS) {
11910
11391
  s = obj.toJS(context, tableid, defcols);
11911
11392
  } else {
11912
- throw new Error('1Can not parse JSON object ' + JSON.stringify(obj));
11393
+ throw new Error(`Cannot parse JSON object ${JSON.stringify(obj)}`);
11913
11394
  }
11914
11395
  } else {
11915
11396
  throw new Error('2Can not parse JSON object ' + JSON.stringify(obj));
@@ -11947,23 +11428,12 @@ yy.Convert.prototype.toString = function () {
11947
11428
  return s;
11948
11429
  };
11949
11430
  yy.Convert.prototype.toJS = function (context, tableid, defcols) {
11950
- // if(this.style) {
11951
- return (
11952
- 'alasql.stdfn.CONVERT(' +
11953
- this.expression.toJS(context, tableid, defcols) +
11954
- ',{dbtypeid:"' +
11955
- this.dbtypeid +
11956
- '",dbsize:' +
11957
- this.dbsize +
11958
- ',dbprecision:' +
11959
- this.dbprecision +
11960
- ',style:' +
11961
- this.style +
11962
- '})'
11963
- );
11964
- // }
11965
-
11966
- throw new Error('There is not such type conversion for ' + this.toString());
11431
+ return `alasql.stdfn.CONVERT(${this.expression.toJS(context, tableid, defcols)}, {
11432
+ dbtypeid: "${this.dbtypeid}",
11433
+ dbsize: ${this.dbsize},
11434
+ dbprecision: ${this.dbprecision},
11435
+ style: ${this.style}
11436
+ })`;
11967
11437
  };
11968
11438
 
11969
11439
  function structuredDate(unFormattedDate) {
@@ -12159,7 +11629,7 @@ yy.ColumnDef = function (params) {
12159
11629
  return Object.assign(this, params);
12160
11630
  };
12161
11631
  yy.ColumnDef.prototype.toString = function () {
12162
- var s = this.columnid;
11632
+ let s = this.columnid;
12163
11633
  if (this.dbtypeid) {
12164
11634
  s += ' ' + this.dbtypeid;
12165
11635
  }
@@ -12187,41 +11657,20 @@ yy.CreateTable = function (params) {
12187
11657
  return Object.assign(this, params);
12188
11658
  };
12189
11659
  yy.CreateTable.prototype.toString = function () {
12190
- var s = 'CREATE';
12191
- if (this.temporary) {
12192
- s += ' TEMPORARY';
12193
- }
11660
+ let s = `CREATE${this.temporary ? ' TEMPORARY' : ''}${this.view ? ' VIEW' : ` ${this.class ? 'CLASS' : 'TABLE'}`}${this.ifnotexists ? ' IF NOT EXISTS' : ''} ${this.table.toString()}`;
12194
11661
 
12195
- if (this.view) {
12196
- s += ' VIEW';
12197
- } else {
12198
- s += ' ' + (this.class ? 'CLASS' : 'TABLE');
12199
- }
12200
- if (this.ifnotexists) {
12201
- s += ' IF NOT EXISTS';
12202
- }
12203
- s += ' ' + this.table.toString();
12204
11662
  if (this.viewcolumns) {
12205
- s +=
12206
- '(' +
12207
- this.viewcolumns
12208
- .map(function (vcol) {
12209
- return vcol.toString();
12210
- })
12211
- .join(',') +
12212
- ')';
11663
+ s += `(${this.viewcolumns.map(vcol => vcol.toString()).join(',')})`;
12213
11664
  }
11665
+
12214
11666
  if (this.as) {
12215
- s += ' AS ' + this.as;
11667
+ s += ` AS ${this.as}`;
12216
11668
  } else {
12217
- var ss = this.columns.map(function (col) {
12218
- return col.toString();
12219
- });
12220
- s += ' (' + ss.join(',') + ')';
11669
+ s += ` (${this.columns.map(col => col.toString()).join(',')})`;
12221
11670
  }
12222
11671
 
12223
11672
  if (this.view && this.select) {
12224
- s += ' AS ' + this.select.toString();
11673
+ s += ` AS ${this.select.toString()}`;
12225
11674
  }
12226
11675
 
12227
11676
  return s;
@@ -12238,13 +11687,7 @@ yy.CreateTable.prototype.execute = function (databaseid, params, cb) {
12238
11687
  throw new Error('Table name is not defined');
12239
11688
  }
12240
11689
 
12241
- // var ifnotexists = this.ifnotexists;
12242
11690
  var columns = this.columns;
12243
- // if(false) {
12244
- // if(!columns) {
12245
- // throw new Error('Columns are not defined');
12246
- // }
12247
- // }
12248
11691
  var constraints = this.constraints || [];
12249
11692
 
12250
11693
  // IF NOT EXISTS
@@ -12295,8 +11738,6 @@ yy.CreateTable.prototype.execute = function (databaseid, params, cb) {
12295
11738
  value: +col.identity.value,
12296
11739
  step: +col.identity.step,
12297
11740
  };
12298
- // ss.push('\''+col.columnid+'\':(alasql.databases[\''+db.databaseid+'\'].tables[\''
12299
- // +tableid+'\'].identities[\''+col.columnid+'\'].value)');
12300
11741
  }
12301
11742
  if (col.check) {
12302
11743
  table.checks.push({
@@ -12333,7 +11774,6 @@ yy.CreateTable.prototype.execute = function (databaseid, params, cb) {
12333
11774
 
12334
11775
  // UNIQUE clause
12335
11776
  if (col.foreignkey) {
12336
-
12337
11777
  var fk = col.foreignkey.table;
12338
11778
  var fktable = alasql.databases[fk.databaseid || databaseid].tables[fk.tableid];
12339
11779
  if (typeof fk.columnid === 'undefined') {
@@ -12343,7 +11783,6 @@ yy.CreateTable.prototype.execute = function (databaseid, params, cb) {
12343
11783
  throw new Error('FOREIGN KEY allowed only to tables with PRIMARY KEYs');
12344
11784
  }
12345
11785
  }
12346
-
12347
11786
  var fkfn = function (r) {
12348
11787
  var rr = {};
12349
11788
  if (typeof r[col.columnid] === 'undefined') {
@@ -12351,7 +11790,6 @@ yy.CreateTable.prototype.execute = function (databaseid, params, cb) {
12351
11790
  }
12352
11791
  rr[fk.columnid] = r[col.columnid];
12353
11792
  var addr = fktable.pk.onrightfn(rr);
12354
-
12355
11793
  if (!fktable.uniqs[fktable.pk.hh][addr]) {
12356
11794
  throw new Error(
12357
11795
  'Foreign key violation' //changed error message
@@ -12360,7 +11798,6 @@ yy.CreateTable.prototype.execute = function (databaseid, params, cb) {
12360
11798
  return true;
12361
11799
  };
12362
11800
  table.checks.push({fn: fkfn});
12363
-
12364
11801
  }
12365
11802
 
12366
11803
  if (col.onupdate) {
@@ -12374,9 +11811,7 @@ yy.CreateTable.prototype.execute = function (databaseid, params, cb) {
12374
11811
  table.defaultfns = ss.join(',');
12375
11812
  table.onupdatefns = uss.join(';');
12376
11813
 
12377
- // if(constraints) {
12378
11814
  constraints.forEach(function (con) {
12379
-
12380
11815
  var checkfn;
12381
11816
 
12382
11817
  if (con.type === 'PRIMARY KEY') {
@@ -12394,10 +11829,8 @@ yy.CreateTable.prototype.execute = function (databaseid, params, cb) {
12394
11829
  pk.hh = hash(pk.onrightfns);
12395
11830
  table.uniqs[pk.hh] = {};
12396
11831
  } else if (con.type === 'CHECK') {
12397
-
12398
11832
  checkfn = new Function('r', 'var y;return ' + con.expression.toJS('r', ''));
12399
11833
  } else if (con.type === 'UNIQUE') {
12400
-
12401
11834
  var uk = {};
12402
11835
  table.uk = table.uk || [];
12403
11836
  table.uk.push(uk);
@@ -12475,25 +11908,18 @@ yy.CreateTable.prototype.execute = function (databaseid, params, cb) {
12475
11908
  //Used in 420from queryfn when table.view = true!
12476
11909
  if (this.view && this.select) {
12477
11910
  table.view = true;
12478
-
12479
11911
  table.select = this.select.compile(this.table.databaseid || databaseid);
12480
11912
  }
12481
11913
 
12482
11914
  if (db.engineid) {
12483
-
12484
11915
  return alasql.engines[db.engineid].createTable(
12485
11916
  this.table.databaseid || databaseid,
12486
11917
  tableid,
12487
11918
  this.ifnotexists,
12488
11919
  cb
12489
11920
  );
12490
-
12491
- // return res1;
12492
11921
  }
12493
11922
 
12494
- // }
12495
- // if(table.pk) {
12496
-
12497
11923
  table.insert = function (r, orreplace) {
12498
11924
  var oldinserted = alasql.inserted;
12499
11925
  alasql.inserted = [r];
@@ -13238,53 +12664,34 @@ yy.CreateEdge.prototype.compile = function (databaseid) {
13238
12664
  var setfn = new Function('x,params,alasql', 'var y;' + s);
13239
12665
  }
13240
12666
 
13241
- /*
13242
- todo: handle content, select and default
13243
- else if(this.content) {
13244
-
13245
- } else if(this.select) {
13246
-
13247
- } else {
13248
- }
13249
- */
12667
+ const statement = (params, cb) => {
12668
+ let res = 0;
12669
+ let db = alasql.databases[dbid];
12670
+ let edge = {$id: db.counter++, $node: 'EDGE'};
12671
+ let v1 = fromfn(params, alasql);
12672
+ let v2 = tofn(params, alasql);
13250
12673
 
13251
- var statement = function (params, cb) {
13252
- var res = 0;
13253
- // CREATE VERTEX without parameters
13254
- var db = alasql.databases[dbid];
13255
- var edge = {$id: db.counter++, $node: 'EDGE'};
13256
- var v1 = fromfn(params, alasql);
13257
- var v2 = tofn(params, alasql);
13258
12674
  // Set link
13259
12675
  edge.$in = [v1.$id];
13260
12676
  edge.$out = [v2.$id];
13261
- // Set sides
13262
- if (v1.$out === undefined) {
13263
- v1.$out = [];
13264
- }
12677
+
12678
+ // Initialize and set sides
12679
+ v1.$out = v1.$out || [];
13265
12680
  v1.$out.push(edge.$id);
13266
12681
 
13267
- if (typeof v2.$in === undefined) {
13268
- v2.$in = [];
13269
- }
12682
+ v2.$in = v2.$in || [];
13270
12683
  v2.$in.push(edge.$id);
13271
12684
 
13272
12685
  // Save in objects
13273
12686
  db.objects[edge.$id] = edge;
13274
12687
  res = edge;
13275
- if (namefn) {
13276
- namefn(edge);
13277
- }
13278
-
13279
- if (setfn) {
13280
- setfn(edge, params, alasql);
13281
- }
13282
12688
 
13283
- if (cb) {
13284
- res = cb(res);
13285
- }
12689
+ // Optional functions
12690
+ namefn?.(edge);
12691
+ setfn?.(edge, params, alasql);
13286
12692
 
13287
- return res;
12693
+ // Callback
12694
+ return cb ? cb(res) : res;
13288
12695
  };
13289
12696
  return statement;
13290
12697
  };
@@ -13309,122 +12716,77 @@ yy.CreateGraph.prototype.execute = function (databaseid, params, cb) {
13309
12716
  }
13310
12717
 
13311
12718
  // stop;
13312
- this.graph.forEach(function (g) {
13313
- if (g.source) {
13314
- // GREATE EDGE
13315
- var e = {};
13316
- if (typeof g.as !== 'undefined') {
13317
- alasql.vars[g.as] = e;
13318
- }
13319
-
13320
- if (typeof g.prop !== 'undefined') {
13321
- // e[g.prop] = e;
13322
- // v.$id = g.prop; // We do not create $id for edge automatically
13323
- e.name = g.prop;
13324
- }
13325
- if (typeof g.sharp !== 'undefined') {
13326
- e.$id = g.sharp;
13327
- }
13328
- if (typeof g.name !== 'undefined') {
13329
- e.name = g.name;
13330
- }
13331
- if (typeof g.class !== 'undefined') {
13332
- e.$class = g.class;
13333
- }
13334
-
13335
- var db = alasql.databases[databaseid];
13336
- if (typeof e.$id === 'undefined') {
13337
- e.$id = db.counter++;
13338
- }
12719
+ this.graph.forEach(g => {
12720
+ if (!g.source) {
12721
+ createVertex(g);
12722
+ } else {
12723
+ // CREATE EDGE
12724
+ let e = {};
12725
+ if (g.as !== undefined) alasql.vars[g.as] = e;
12726
+ if (g.prop !== undefined) e.name = g.prop;
12727
+ if (g.sharp !== undefined) e.$id = g.sharp;
12728
+ if (g.name !== undefined) e.name = g.name;
12729
+ if (g.class !== undefined) e.$class = g.class;
12730
+
12731
+ let db = alasql.databases[databaseid];
12732
+ e.$id = e.$id !== undefined ? e.$id : db.counter++;
13339
12733
  e.$node = 'EDGE';
13340
- if (typeof g.json !== 'undefined') {
13341
- extend(e, new Function('params,alasql', 'var y;return ' + g.json.toJS())(params, alasql));
13342
- }
13343
12734
 
13344
- var v1;
13345
- if (g.source.vars) {
13346
- var vo = alasql.vars[g.source.vars];
13347
- if (typeof vo === 'object') {
13348
- v1 = vo;
13349
- } else {
13350
- v1 = db.objects[vo];
13351
- }
13352
- } else {
13353
- var av1 = g.source.sharp;
13354
- if (typeof av1 === 'undefined') {
13355
- av1 = g.source.prop;
13356
- }
13357
- v1 = alasql.databases[databaseid].objects[av1];
13358
- if (
13359
- typeof v1 === 'undefined' &&
13360
- alasql.options.autovertex &&
13361
- (typeof g.source.prop !== 'undefined' || typeof g.source.name !== 'undefined')
13362
- ) {
13363
- v1 = findVertex(g.source.prop || g.source.name);
13364
- if (typeof v1 === 'undefined') {
13365
- v1 = createVertex(g.source);
13366
- }
13367
- }
12735
+ if (g.json !== undefined) {
12736
+ Object.assign(e, new Function('params, alasql', `return ${g.json.toJS()}`)(params, alasql));
13368
12737
  }
13369
12738
 
13370
- var v2;
13371
- if (g.source.vars) {
13372
- var vo = alasql.vars[g.target.vars];
13373
- if (typeof vo === 'object') {
13374
- v2 = vo;
12739
+ const resolveVertex = (sourceOrTarget, isSource) => {
12740
+ let vertex, vo;
12741
+ if (sourceOrTarget.vars) {
12742
+ vo = alasql.vars[sourceOrTarget.vars];
12743
+ vertex = typeof vo === 'object' ? vo : db.objects[vo];
13375
12744
  } else {
13376
- v2 = db.objects[vo];
13377
- }
13378
- } else {
13379
- var av2 = g.target.sharp;
13380
- if (typeof av2 === 'undefined') {
13381
- av2 = g.target.prop;
13382
- }
13383
- v2 = alasql.databases[databaseid].objects[av2];
13384
- if (
13385
- typeof v2 === 'undefined' &&
13386
- alasql.options.autovertex &&
13387
- (typeof g.target.prop !== 'undefined' || typeof g.target.name !== 'undefined')
13388
- ) {
13389
- v2 = findVertex(g.target.prop || g.target.name);
13390
- if (typeof v2 === 'undefined') {
13391
- v2 = createVertex(g.target);
12745
+ let av = sourceOrTarget.sharp || sourceOrTarget.prop;
12746
+ vertex = db.objects[av];
12747
+ if (
12748
+ vertex === undefined &&
12749
+ alasql.options.autovertex &&
12750
+ (sourceOrTarget.prop || sourceOrTarget.name)
12751
+ ) {
12752
+ vertex =
12753
+ findVertex(sourceOrTarget.prop || sourceOrTarget.name) ||
12754
+ createVertex(sourceOrTarget);
13392
12755
  }
13393
12756
  }
13394
- }
12757
+ if (isSource && vertex && typeof vertex.$out === 'undefined') vertex.$out = [];
12758
+ if (!isSource && vertex && typeof vertex.$in === 'undefined') vertex.$in = [];
12759
+ return vertex;
12760
+ };
13395
12761
 
13396
- // Set link
12762
+ let v1 = resolveVertex(g.source, true);
12763
+ let v2 = resolveVertex(g.target, false);
12764
+
12765
+ // Set link and sides
13397
12766
  e.$in = [v1.$id];
13398
12767
  e.$out = [v2.$id];
13399
- // Set sides
13400
- if (typeof v1.$out === 'undefined') {
13401
- v1.$out = [];
13402
- }
13403
12768
  v1.$out.push(e.$id);
13404
- if (typeof v2.$in === 'undefined') {
13405
- v2.$in = [];
13406
- }
13407
12769
  v2.$in.push(e.$id);
13408
12770
 
13409
12771
  db.objects[e.$id] = e;
13410
- if (typeof e.$class !== 'undefined') {
13411
- if (typeof alasql.databases[databaseid].tables[e.$class] === 'undefined') {
13412
- throw new Error('No such class. Pleace use CREATE CLASS');
12772
+
12773
+ if (e.$class !== undefined) {
12774
+ let classTable = alasql.databases[databaseid].tables[e.$class];
12775
+ if (classTable === undefined) {
12776
+ throw new Error('No such class. Please use CREATE CLASS');
13413
12777
  } else {
13414
- // TODO - add insert()
13415
- alasql.databases[databaseid].tables[e.$class].data.push(e);
12778
+ classTable.data.push(e);
13416
12779
  }
13417
12780
  }
13418
12781
 
13419
12782
  res.push(e.$id);
13420
- } else {
13421
- createVertex(g);
13422
12783
  }
13423
12784
  });
13424
12785
 
13425
12786
  if (cb) {
13426
12787
  res = cb(res);
13427
12788
  }
12789
+
13428
12790
  return res;
13429
12791
 
13430
12792
  // Find vertex by name
@@ -13483,52 +12845,50 @@ yy.CreateGraph.prototype.execute = function (databaseid, params, cb) {
13483
12845
  return v;
13484
12846
  }
13485
12847
  };
13486
-
13487
12848
  yy.CreateGraph.prototype.compile1 = function (databaseid) {
13488
- var dbid = databaseid;
13489
- var fromfn = new Function('params,alasql', 'var y;return ' + this.from.toJS());
13490
- var tofn = new Function('params,alasql', 'var y;return ' + this.to.toJS());
12849
+ const dbid = databaseid;
12850
+ const fromfn = new Function('params, alasql', `return ${this.from.toJS()}`);
12851
+ const tofn = new Function('params, alasql', `return ${this.to.toJS()}`);
12852
+
12853
+ let namefn, setfn;
13491
12854
 
13492
12855
  // CREATE VERTEX "Name"
13493
- if (typeof this.name !== 'undefined') {
13494
- var s = 'x.name=' + this.name.toJS();
13495
- var namefn = new Function('x', s);
12856
+ if (this.name !== undefined) {
12857
+ const s = `x.name = ${this.name.toJS()}`;
12858
+ namefn = new Function('x', s);
13496
12859
  }
13497
12860
 
13498
12861
  if (this.sets && this.sets.length > 0) {
13499
- var s = this.sets
13500
- .map(function (st) {
13501
- return `x[${JSON.stringify(st.column.columnid)}]=` + st.expression.toJS('x', '');
13502
- })
12862
+ const s = this.sets
12863
+ .map(st => `x[${JSON.stringify(st.column.columnid)}] = ${st.expression.toJS('x', '')}`)
13503
12864
  .join(';');
13504
- var setfn = new Function('x,params,alasql', 'var y;' + s);
12865
+ setfn = new Function('x, params, alasql', `var y; ${s}`);
13505
12866
  }
13506
12867
 
13507
12868
  // Todo: handle content, select and default
13508
12869
 
13509
- var statement = function (params, cb) {
13510
- var res = 0;
13511
- // CREATE VERTEX without parameters
13512
- var db = alasql.databases[dbid];
13513
- var edge = {$id: db.counter++, $node: 'EDGE'};
13514
- var v1 = fromfn(params, alasql);
13515
- var v2 = tofn(params, alasql);
12870
+ const statement = (params, cb) => {
12871
+ let res = 0;
12872
+ const db = alasql.databases[dbid];
12873
+ const edge = {$id: db.counter++, $node: 'EDGE'};
12874
+ const v1 = fromfn(params, alasql);
12875
+ const v2 = tofn(params, alasql);
12876
+
13516
12877
  // Set link
13517
12878
  edge.$in = [v1.$id];
13518
12879
  edge.$out = [v2.$id];
12880
+
13519
12881
  // Set sides
13520
- if (typeof v1.$out === 'undefined') {
13521
- v1.$out = [];
13522
- }
12882
+ v1.$out = v1.$out || [];
13523
12883
  v1.$out.push(edge.$id);
13524
12884
 
13525
- if (typeof v2.$in === 'undefined') {
13526
- v2.$in = [];
13527
- }
12885
+ v2.$in = v2.$in || [];
13528
12886
  v2.$in.push(edge.$id);
12887
+
13529
12888
  // Save in objects
13530
12889
  db.objects[edge.$id] = edge;
13531
12890
  res = edge;
12891
+
13532
12892
  if (namefn) {
13533
12893
  namefn(edge);
13534
12894
  }
@@ -13557,13 +12917,13 @@ yy.AlterTable = function (params) {
13557
12917
  return Object.assign(this, params);
13558
12918
  };
13559
12919
  yy.AlterTable.prototype.toString = function () {
13560
- var s = 'ALTER TABLE ' + this.table.toString();
12920
+ let s = 'ALTER TABLE ' + this.table.toString();
13561
12921
  if (this.renameto) s += ' RENAME TO ' + this.renameto;
13562
12922
  return s;
13563
12923
  };
13564
12924
 
13565
12925
  yy.AlterTable.prototype.execute = function (databaseid, params, cb) {
13566
- var db = alasql.databases[databaseid];
12926
+ let db = alasql.databases[databaseid];
13567
12927
  db.dbversion = Date.now();
13568
12928
 
13569
12929
  if (this.renameto) {
@@ -13583,7 +12943,9 @@ yy.AlterTable.prototype.execute = function (databaseid, params, cb) {
13583
12943
  }
13584
12944
  if (cb) cb(res);
13585
12945
  return res;
13586
- } else if (this.addcolumn) {
12946
+ }
12947
+
12948
+ if (this.addcolumn) {
13587
12949
  db = alasql.databases[this.table.databaseid || databaseid];
13588
12950
  db.dbversion++;
13589
12951
  var tableid = this.table.tableid;
@@ -13609,15 +12971,15 @@ yy.AlterTable.prototype.execute = function (databaseid, params, cb) {
13609
12971
  table.columns.push(col);
13610
12972
  table.xcolumns[columnid] = col;
13611
12973
 
13612
- for (var i = 0, ilen = table.data.length; i < ilen; i++) {
13613
-
12974
+ for (let i = 0, ilen = table.data.length; i < ilen; i++) {
13614
12975
  table.data[i][columnid] = defaultfn();
13615
12976
  }
13616
12977
 
13617
- // TODO
13618
12978
  return cb ? cb(1) : 1;
13619
- } else if (this.modifycolumn) {
13620
- var db = alasql.databases[this.table.databaseid || databaseid];
12979
+ }
12980
+
12981
+ if (this.modifycolumn) {
12982
+ let db = alasql.databases[this.table.databaseid || databaseid];
13621
12983
  db.dbversion++;
13622
12984
  var tableid = this.table.tableid;
13623
12985
  var table = db.tables[tableid];
@@ -13635,10 +12997,11 @@ yy.AlterTable.prototype.execute = function (databaseid, params, cb) {
13635
12997
  col.dbprecision = this.dbprecision;
13636
12998
  col.dbenum = this.dbenum;
13637
12999
 
13638
- // TODO
13639
13000
  return cb ? cb(1) : 1;
13640
- } else if (this.renamecolumn) {
13641
- var db = alasql.databases[this.table.databaseid || databaseid];
13001
+ }
13002
+
13003
+ if (this.renamecolumn) {
13004
+ let db = alasql.databases[this.table.databaseid || databaseid];
13642
13005
  db.dbversion++;
13643
13006
 
13644
13007
  var tableid = this.table.tableid;
@@ -13665,16 +13028,16 @@ yy.AlterTable.prototype.execute = function (databaseid, params, cb) {
13665
13028
  delete table.xcolumns[columnid];
13666
13029
 
13667
13030
  for (var i = 0, ilen = table.data.length; i < ilen; i++) {
13668
-
13669
13031
  table.data[i][tocolumnid] = table.data[i][columnid];
13670
13032
  delete table.data[i][columnid];
13671
13033
  }
13672
13034
  return table.data.length;
13673
- } else {
13674
- return cb ? cb(0) : 0;
13675
13035
  }
13676
- } else if (this.dropcolumn) {
13677
- var db = alasql.databases[this.table.databaseid || databaseid];
13036
+ return cb ? cb(0) : 0;
13037
+ }
13038
+
13039
+ if (this.dropcolumn) {
13040
+ let db = alasql.databases[this.table.databaseid || databaseid];
13678
13041
  db.dbversion++;
13679
13042
  var tableid = this.table.tableid;
13680
13043
  var table = db.tables[tableid];
@@ -13700,10 +13063,11 @@ yy.AlterTable.prototype.execute = function (databaseid, params, cb) {
13700
13063
  for (i = 0, ilen = table.data.length; i < ilen; i++) {
13701
13064
  delete table.data[i][columnid];
13702
13065
  }
13066
+
13703
13067
  return cb ? cb(table.data.length) : table.data.length;
13704
- } else {
13705
- throw Error('Unknown ALTER TABLE method');
13706
13068
  }
13069
+
13070
+ throw Error('Unknown ALTER TABLE method');
13707
13071
  };
13708
13072
  /*
13709
13073
  //
@@ -14303,40 +13667,41 @@ yy.CreateTrigger.prototype.toString = function () {
14303
13667
  return s;
14304
13668
  };
14305
13669
 
13670
+ const validTriggers = [
13671
+ 'beforeinsert',
13672
+ 'afterinsert',
13673
+ 'insteadofinsert',
13674
+ 'beforedelete',
13675
+ 'afterdelete',
13676
+ 'insteadofdelete',
13677
+ 'beforeupdate',
13678
+ 'afterupdate',
13679
+ 'insteadofupdate',
13680
+ ];
13681
+
14306
13682
  yy.CreateTrigger.prototype.execute = function (databaseid, params, cb) {
14307
- var res = 1; // No tables removed
14308
- var triggerid = this.trigger;
13683
+ let res = 1; // No tables removed
13684
+ const triggerid = this.trigger;
14309
13685
  databaseid = this.table.databaseid || databaseid;
14310
- var db = alasql.databases[databaseid];
14311
- var tableid = this.table.tableid;
13686
+ const db = alasql.databases[databaseid];
13687
+ const {tableid} = this.table;
14312
13688
 
14313
- var trigger = {
13689
+ const trigger = {
14314
13690
  action: this.action,
14315
13691
  when: this.when,
14316
13692
  statement: this.statement,
14317
13693
  funcid: this.funcid,
14318
- tableid: this.table.tableid,
13694
+ tableid,
14319
13695
  };
14320
13696
 
14321
13697
  db.triggers[triggerid] = trigger;
14322
- if (trigger.action == 'INSERT' && trigger.when == 'BEFORE') {
14323
- db.tables[tableid].beforeinsert[triggerid] = trigger;
14324
- } else if (trigger.action == 'INSERT' && trigger.when == 'AFTER') {
14325
- db.tables[tableid].afterinsert[triggerid] = trigger;
14326
- } else if (trigger.action == 'INSERT' && trigger.when == 'INSTEADOF') {
14327
- db.tables[tableid].insteadofinsert[triggerid] = trigger;
14328
- } else if (trigger.action == 'DELETE' && trigger.when == 'BEFORE') {
14329
- db.tables[tableid].beforedelete[triggerid] = trigger;
14330
- } else if (trigger.action == 'DELETE' && trigger.when == 'AFTER') {
14331
- db.tables[tableid].afterdelete[triggerid] = trigger;
14332
- } else if (trigger.action == 'DELETE' && trigger.when == 'INSTEADOF') {
14333
- db.tables[tableid].insteadofdelete[triggerid] = trigger;
14334
- } else if (trigger.action == 'UPDATE' && trigger.when == 'BEFORE') {
14335
- db.tables[tableid].beforeupdate[triggerid] = trigger;
14336
- } else if (trigger.action == 'UPDATE' && trigger.when == 'AFTER') {
14337
- db.tables[tableid].afterupdate[triggerid] = trigger;
14338
- } else if (trigger.action == 'UPDATE' && trigger.when == 'INSTEADOF') {
14339
- db.tables[tableid].insteadofupdate[triggerid] = trigger;
13698
+ const actionKey = `${this.when}${this.action}`.toLowerCase();
13699
+
13700
+ if (validTriggers.includes(actionKey)) {
13701
+ // Ensure the existence of db.tables[tableid] and db.tables[tableid][actionKey]
13702
+ db.tables[tableid] = db.tables[tableid] || {};
13703
+ db.tables[tableid][actionKey] = db.tables[tableid][actionKey] || {};
13704
+ db.tables[tableid][actionKey][triggerid] = trigger;
14340
13705
  }
14341
13706
 
14342
13707
  if (cb) res = cb(res);
@@ -14361,28 +13726,26 @@ yy.DropTrigger.prototype.toString = function () {
14361
13726
  DROP TRIGGER one;
14362
13727
  */
14363
13728
  yy.DropTrigger.prototype.execute = function (databaseid, params, cb) {
14364
- var res = 0; // No tables removed
14365
- var db = alasql.databases[databaseid];
14366
- var triggerid = this.trigger;
13729
+ let res = 0; // No tables removed
13730
+ const db = alasql.databases[databaseid];
13731
+ const triggerid = this.trigger;
14367
13732
 
14368
- // get the trigger
14369
- var trigger = db.triggers[triggerid];
13733
+ // Get the trigger
13734
+ const trigger = db.triggers[triggerid];
14370
13735
 
14371
- // if the trigger exists
13736
+ // If the trigger exists
14372
13737
  if (trigger) {
14373
- var tableid = db.triggers[triggerid].tableid;
13738
+ const {tableid} = trigger;
14374
13739
 
14375
13740
  if (tableid) {
14376
13741
  res = 1;
14377
- delete db.tables[tableid].beforeinsert[triggerid];
14378
- delete db.tables[tableid].afterinsert[triggerid];
14379
- delete db.tables[tableid].insteadofinsert[triggerid];
14380
- delete db.tables[tableid].beforedelete[triggerid];
14381
- delete db.tables[tableid].afterdelete[triggerid];
14382
- delete db.tables[tableid].insteadofdelete[triggerid];
14383
- delete db.tables[tableid].beforeupdate[triggerid];
14384
- delete db.tables[tableid].afterupdate[triggerid];
14385
- delete db.tables[tableid].insteadofupdate[triggerid];
13742
+
13743
+ // Delete the trigger from all trigger points
13744
+ validTriggers.forEach(point => {
13745
+ delete db.tables[tableid][point][triggerid];
13746
+ });
13747
+
13748
+ // Finally, delete the trigger itself
14386
13749
  delete db.triggers[triggerid];
14387
13750
  } else {
14388
13751
  throw new Error('Trigger Table not found');
@@ -14390,6 +13753,7 @@ yy.DropTrigger.prototype.execute = function (databaseid, params, cb) {
14390
13753
  } else {
14391
13754
  throw new Error('Trigger not found');
14392
13755
  }
13756
+
14393
13757
  if (cb) res = cb(res);
14394
13758
  return res;
14395
13759
  };
@@ -14411,16 +13775,12 @@ yy.Delete.prototype.toString = function () {
14411
13775
  };
14412
13776
 
14413
13777
  yy.Delete.prototype.compile = function (databaseid) {
14414
-
14415
13778
  databaseid = this.table.databaseid || databaseid;
14416
13779
  var tableid = this.table.tableid;
14417
13780
  var statement;
14418
13781
  var db = alasql.databases[databaseid];
14419
13782
 
14420
13783
  if (this.where) {
14421
-
14422
- // this.query = {};
14423
-
14424
13784
  if (this.exists) {
14425
13785
  this.existsfn = this.exists.map(function (ex) {
14426
13786
  var nq = ex.compile(databaseid);
@@ -14428,6 +13788,7 @@ yy.Delete.prototype.compile = function (databaseid) {
14428
13788
  return nq;
14429
13789
  });
14430
13790
  }
13791
+
14431
13792
  if (this.queries) {
14432
13793
  this.queriesfn = this.queries.map(function (q) {
14433
13794
  var nq = q.compile(databaseid);
@@ -14436,10 +13797,6 @@ yy.Delete.prototype.compile = function (databaseid) {
14436
13797
  });
14437
13798
  }
14438
13799
 
14439
- // try {
14440
-
14441
- // var query = {};
14442
-
14443
13800
  var wherefn = new Function(
14444
13801
  'r,params,alasql',
14445
13802
  'var y;return (' + this.where.toJS('r', '') + ')'
@@ -14465,7 +13822,6 @@ yy.Delete.prototype.compile = function (databaseid) {
14465
13822
  }
14466
13823
 
14467
13824
  var table = db.tables[tableid];
14468
- // table.dirty = true;
14469
13825
  var orignum = table.data.length;
14470
13826
 
14471
13827
  var newtable = [];
@@ -14477,9 +13833,10 @@ yy.Delete.prototype.compile = function (databaseid) {
14477
13833
  } else {
14478
13834
  // Simply do not push
14479
13835
  }
14480
- } else newtable.push(table.data[i]);
13836
+ } else {
13837
+ newtable.push(table.data[i]);
13838
+ }
14481
13839
  }
14482
- // table.data = table.data.filter(function(r){return !;});
14483
13840
  table.data = newtable;
14484
13841
 
14485
13842
  // Trigger prevent functionality
@@ -14503,15 +13860,10 @@ yy.Delete.prototype.compile = function (databaseid) {
14503
13860
  alasql.engines[db.engineid].saveTableData(databaseid, tableid);
14504
13861
  }
14505
13862
 
14506
- if (cb) cb(res);
13863
+ if (cb) res = cb(res);
13864
+
14507
13865
  return res;
14508
13866
  };
14509
- // .bind(query);
14510
-
14511
- // if(!this.queries) return;
14512
- // query.queriesfn = this.queries.map(function(q) {
14513
- // return q.compile(alasql.useid);
14514
- // });
14515
13867
  } else {
14516
13868
  statement = function (params, cb) {
14517
13869
  if (alasql.options.autocommit && db.engineid) {
@@ -14521,7 +13873,6 @@ yy.Delete.prototype.compile = function (databaseid) {
14521
13873
  var table = db.tables[tableid];
14522
13874
  table.dirty = true;
14523
13875
  var orignum = db.tables[tableid].data.length;
14524
- //table.deleteall();
14525
13876
  // Delete all records from the array
14526
13877
  db.tables[tableid].data.length = 0;
14527
13878
 
@@ -14674,35 +14025,30 @@ yy.Merge = function (params) {
14674
14025
  return Object.assign(this, params);
14675
14026
  };
14676
14027
  yy.Merge.prototype.toString = function () {
14677
- var s = 'MERGE ';
14678
- s += this.into.tableid + ' ';
14679
- if (this.into.as) s += 'AS ' + this.into.as + ' ';
14680
- s += 'USING ' + this.using.tableid + ' ';
14681
- if (this.using.as) s += 'AS ' + this.using.as + ' ';
14682
- s += 'ON ' + this.on.toString() + ' ';
14683
- this.matches.forEach(function (m) {
14028
+ let s = `MERGE ${this.into.tableid} `;
14029
+ if (this.into.as) s += `AS ${this.into.as} `;
14030
+ s += `USING ${this.using.tableid} `;
14031
+ if (this.using.as) s += `AS ${this.using.as} `;
14032
+ s += `ON ${this.on.toString()} `;
14033
+
14034
+ this.matches.forEach(m => {
14684
14035
  s += 'WHEN ';
14685
14036
  if (!m.matched) s += 'NOT ';
14686
14037
  s += 'MATCHED ';
14687
14038
  if (m.bytarget) s += 'BY TARGET ';
14688
14039
  if (m.bysource) s += 'BY SOURCE ';
14689
- if (m.expr) s += 'AND' + ' ' + m.expr.toString() + ' ';
14040
+ if (m.expr) s += `AND ${m.expr.toString()} `;
14690
14041
  s += 'THEN ';
14691
14042
  if (m.action.delete) s += 'DELETE ';
14692
14043
  if (m.action.insert) {
14693
14044
  s += 'INSERT ';
14694
- if (m.action.columns) s += '(' + m.action.columns.toString() + ') ';
14695
- if (m.action.values) s += 'VALUES (' + m.action.values.toString() + ') ';
14045
+ if (m.action.columns) s += `(${m.action.columns.toString()}) `;
14046
+ if (m.action.values) s += `VALUES (${m.action.values.toString()}) `;
14696
14047
  if (m.action.defaultvalues) s += 'DEFAULT VALUES ';
14697
14048
  }
14698
14049
  if (m.action.update) {
14699
14050
  s += 'UPDATE ';
14700
- s +=
14701
- m.action.update
14702
- .map(function (u) {
14703
- return u.toString();
14704
- })
14705
- .join(',') + ' ';
14051
+ s += m.action.update.map(u => u.toString()).join(', ') + ' ';
14706
14052
  }
14707
14053
  });
14708
14054
 
@@ -14731,25 +14077,19 @@ yy.CreateDatabase = function (params) {
14731
14077
  return Object.assign(this, params);
14732
14078
  };
14733
14079
  yy.CreateDatabase.prototype.toString = function () {
14734
- var s = 'CREATE';
14735
- if (this.engineid) s += ' ' + this.engineid;
14736
- s += ' DATABASE';
14737
- if (this.ifnotexists) s += ' IF NOT EXISTS';
14738
- s += ' ' + this.databaseid;
14080
+ let s = 'CREATE '; // Ensure there's a space after CREATE
14081
+ if (this.engineid) s += `${this.engineid} `;
14082
+ s += 'DATABASE ';
14083
+ if (this.ifnotexists) s += 'IF NOT EXISTS ';
14084
+ s += `${this.databaseid} `;
14085
+
14739
14086
  if (this.args && this.args.length > 0) {
14740
- s +=
14741
- '(' +
14742
- this.args
14743
- .map(function (arg) {
14744
- return arg.toString();
14745
- })
14746
- .join(', ') +
14747
- ')';
14087
+ s += `(${this.args.map(arg => arg.toString()).join(', ')}) `;
14748
14088
  }
14749
- if (this.as) s += ' AS ' + this.as;
14089
+ if (this.as) s += `AS ${this.as}`;
14750
14090
  return s;
14751
14091
  };
14752
- //yy.CreateDatabase.prototype.compile = returnUndefined;
14092
+
14753
14093
  yy.CreateDatabase.prototype.execute = function (databaseid, params, cb) {
14754
14094
  var args;
14755
14095
  if (this.args && this.args.length > 0) {
@@ -14784,25 +14124,21 @@ yy.AttachDatabase = function (params) {
14784
14124
  return Object.assign(this, params);
14785
14125
  };
14786
14126
  yy.AttachDatabase.prototype.toString = function (args) {
14787
- var s = 'ATTACH';
14788
- if (this.engineid) s += ' ' + this.engineid;
14789
- s += ' DATABASE' + ' ' + this.databaseid;
14127
+ let s = 'ATTACH';
14128
+ if (this.engineid) s += ` ${this.engineid}`;
14129
+ s += ` DATABASE ${this.databaseid}`;
14790
14130
  // TODO add params
14791
14131
  if (args) {
14792
14132
  s += '(';
14793
14133
  if (args.length > 0) {
14794
- s += args
14795
- .map(function (arg) {
14796
- return arg.toString();
14797
- })
14798
- .join(', ');
14134
+ s += args.map(arg => arg.toString()).join(', ');
14799
14135
  }
14800
14136
  s += ')';
14801
14137
  }
14802
- if (this.as) s += ' AS' + ' ' + this.as;
14138
+ if (this.as) s += ` AS ${this.as}`;
14803
14139
  return s;
14804
14140
  };
14805
- //yy.CreateDatabase.prototype.compile = returnUndefined;
14141
+
14806
14142
  yy.AttachDatabase.prototype.execute = function (databaseid, params, cb) {
14807
14143
  if (!alasql.engines[this.engineid]) {
14808
14144
  throw new Error('Engine "' + this.engineid + '" is not defined.');
@@ -14873,8 +14209,6 @@ yy.DetachDatabase.prototype.execute = function (databaseid, params, cb) {
14873
14209
  }
14874
14210
  if (cb) cb(res);
14875
14211
  return res;
14876
- // var res = alasql.engines[this.engineid].attachDatabase(this.databaseid, this.as, cb);
14877
- // return res;
14878
14212
  };
14879
14213
 
14880
14214
  // USE DATABSE databaseid
@@ -14912,22 +14246,22 @@ yy.DropDatabase.prototype.execute = function (databaseid, params, cb) {
14912
14246
  if (this.engineid) {
14913
14247
  return alasql.engines[this.engineid].dropDatabase(this.databaseid, this.ifexists, cb);
14914
14248
  }
14915
- var res;
14249
+ let res;
14916
14250
 
14917
- var dbid = this.databaseid;
14251
+ const dbid = this.databaseid;
14918
14252
 
14919
14253
  if (dbid === alasql.DEFAULTDATABASEID) {
14920
14254
  throw new Error('Drop of default database is prohibited');
14921
14255
  }
14922
14256
  if (!alasql.databases[dbid]) {
14923
14257
  if (!this.ifexists) {
14924
- throw new Error("Database '" + dbid + "' does not exist");
14258
+ throw new Error(`Database '${dbid}' does not exist`);
14925
14259
  } else {
14926
14260
  res = 0;
14927
14261
  }
14928
14262
  } else {
14929
14263
  if (alasql.databases[dbid].engineid) {
14930
- throw new Error("Cannot drop database '" + dbid + "', because it is attached. Detach it.");
14264
+ throw new Error(`Cannot drop database '${dbid}', because it is attached. Detach it.`);
14931
14265
  }
14932
14266
 
14933
14267
  delete alasql.databases[dbid];
@@ -14951,24 +14285,22 @@ yy.Declare = function (params) {
14951
14285
  return Object.assign(this, params);
14952
14286
  };
14953
14287
  yy.Declare.prototype.toString = function () {
14954
- var s = 'DECLARE ';
14288
+ let s = 'DECLARE ';
14955
14289
  if (this.declares && this.declares.length > 0) {
14956
- s = this.declares
14957
- .map(function (declare) {
14958
- var s = '';
14959
- s += '@' + declare.variable + ' ';
14960
- s += declare.dbtypeid;
14961
- if (this.dbsize) {
14962
- s += '(' + this.dbsize;
14963
- if (this.dbprecision) {
14964
- s += ',' + this.dbprecision;
14290
+ s += this.declares
14291
+ .map(declare => {
14292
+ let declareStr = `@${declare.variable} ${declare.dbtypeid}`;
14293
+ if (declare.dbsize) {
14294
+ declareStr += `(${declare.dbsize}`;
14295
+ if (declare.dbprecision) {
14296
+ declareStr += `,${declare.dbprecision}`;
14965
14297
  }
14966
- s += ')';
14298
+ declareStr += ')';
14967
14299
  }
14968
14300
  if (declare.expression) {
14969
- s += ' = ' + declare.expression.toString();
14301
+ declareStr += ` = ${declare.expression.toString()}`;
14970
14302
  }
14971
- return s;
14303
+ return declareStr;
14972
14304
  })
14973
14305
  .join(',');
14974
14306
  }
@@ -15177,76 +14509,67 @@ yy.SetVariable.prototype.toString = function () {
15177
14509
  };
15178
14510
 
15179
14511
  yy.SetVariable.prototype.execute = function (databaseid, params, cb) {
15180
-
15181
- if (typeof this.value != 'undefined') {
15182
- var val = this.value;
15183
- if (val == 'ON') val = true;
15184
- else if (val == 'OFF') val = false;
15185
- // if(this.method == '@') {
14512
+ if (typeof this.value !== 'undefined') {
14513
+ let val = this.value;
14514
+ if (val === 'ON') val = true;
14515
+ else if (val === 'OFF') val = false;
15186
14516
  alasql.options[this.variable] = val;
15187
- // } else {
15188
- // params[this.variable] = val;
15189
- // }
15190
14517
  } else if (this.expression) {
15191
14518
  if (this.exists) {
15192
- this.existsfn = this.exists.map(function (ex) {
15193
- var nq = ex.compile(databaseid);
14519
+ this.existsfn = this.exists.map(ex => {
14520
+ let nq = ex.compile(databaseid);
15194
14521
  if (nq.query && !nq.query.modifier) nq.query.modifier = 'RECORDSET';
15195
14522
  return nq;
15196
- // return ex.compile(databaseid);
15197
- // TODO Include modifier
15198
14523
  });
15199
14524
  }
15200
14525
  if (this.queries) {
15201
- this.queriesfn = this.queries.map(function (q) {
15202
- var nq = q.compile(databaseid);
14526
+ this.queriesfn = this.queries.map(q => {
14527
+ let nq = q.compile(databaseid);
15203
14528
  if (nq.query && !nq.query.modifier) nq.query.modifier = 'RECORDSET';
15204
14529
  return nq;
15205
- // TODO Include modifier
15206
14530
  });
15207
14531
  }
15208
14532
 
15209
- var res = new Function(
15210
- 'params,alasql',
14533
+ let res = new Function(
14534
+ 'params, alasql',
15211
14535
  'return ' + this.expression.toJS('({})', '', null)
15212
14536
  ).bind(this)(params, alasql);
14537
+
15213
14538
  if (alasql.declares[this.variable]) {
15214
14539
  res = alasql.stdfn.CONVERT(res, alasql.declares[this.variable]);
15215
14540
  }
14541
+
15216
14542
  if (this.props && this.props.length > 0) {
15217
- if (this.method == '@') {
15218
- var fs = "alasql.vars['" + this.variable + "']";
14543
+ let fs;
14544
+ if (this.method === '@') {
14545
+ fs = `alasql.vars['${this.variable}']`;
15219
14546
  } else {
15220
- var fs = "params['" + this.variable + "']";
15221
- }
15222
- fs += this.props
15223
- .map(function (prop) {
15224
- if (typeof prop == 'string') {
15225
- return "['" + prop + "']";
15226
- } else if (typeof prop == 'number') {
15227
- return '[' + prop + ']';
15228
- } else {
15229
-
15230
- return '[' + prop.toJS() + ']';
15231
- // } else {
15232
-
15233
- // throw new Error('Wrong SET property');
15234
- }
15235
- })
15236
- .join();
14547
+ fs = `params['${this.variable}']`;
14548
+ }
14549
+ this.props.forEach(prop => {
14550
+ if (typeof prop === 'string') {
14551
+ fs += `['${prop}']`;
14552
+ } else if (typeof prop === 'number') {
14553
+ fs += `[${prop}]`;
14554
+ } else {
14555
+ // Assuming prop.toJS() is a method that converts prop to a JavaScript expression.
14556
+ fs += `[${prop.toJS()}]`;
14557
+ }
14558
+ });
15237
14559
 
15238
- new Function('value,params,alasql', 'var y;' + fs + '=value')(res, params, alasql);
14560
+ new Function('value, params, alasql', `${fs} = value`)(res, params, alasql);
15239
14561
  } else {
15240
- if (this.method == '@') {
14562
+ if (this.method === '@') {
15241
14563
  alasql.vars[this.variable] = res;
15242
14564
  } else {
15243
14565
  params[this.variable] = res;
15244
14566
  }
15245
14567
  }
15246
14568
  }
15247
- var res = 1;
15248
- if (cb) res = cb(res);
15249
- return res;
14569
+
14570
+ let result = 1;
14571
+ if (cb) result = cb(result);
14572
+ return result;
15250
14573
  };
15251
14574
  alasql.test = function (name, times, fn) {
15252
14575
  if (arguments.length === 0) {
@@ -15568,7 +14891,7 @@ yy.BeginTransaction.prototype.execute = function (databaseid, params, cb) {
15568
14891
  } else {
15569
14892
  // alasql commit!!!
15570
14893
  }
15571
- if (cb) cb(res);
14894
+ if (cb) res = cb(res);
15572
14895
  return res;
15573
14896
  };
15574
14897
 
@@ -15586,7 +14909,7 @@ yy.CommitTransaction.prototype.execute = function (databaseid, params, cb) {
15586
14909
  } else {
15587
14910
  // alasql commit!!!
15588
14911
  }
15589
- if (cb) cb(res);
14912
+ if (cb) res = cb(res);
15590
14913
  return res;
15591
14914
  };
15592
14915
 
@@ -15604,7 +14927,7 @@ yy.RollbackTransaction.prototype.execute = function (databaseid, params, cb) {
15604
14927
  } else {
15605
14928
  // alasql commit!!!
15606
14929
  }
15607
- if (cb) cb(res);
14930
+ if (cb) res = cb(res);
15608
14931
  return res;
15609
14932
  };
15610
14933
  if (alasql.options.tsql) {
@@ -16820,9 +16143,8 @@ alasql.into.XLSX = function (filename, opts, data, columns, cb) {
16820
16143
 
16821
16144
  alasql.from.METEOR = function (filename, opts, cb, idx, query) {
16822
16145
  var res = filename.find(opts).fetch();
16823
- if (cb) {
16824
- res = cb(res, idx, query);
16825
- }
16146
+ if (cb) res = cb(res, idx, query);
16147
+
16826
16148
  return res;
16827
16149
  };
16828
16150
 
@@ -16836,9 +16158,7 @@ alasql.from.TABLETOP = function (key, opts, cb, idx, query) {
16836
16158
  alasql.utils.extend(opt, opts);
16837
16159
  opt.callback = function (data) {
16838
16160
  res = data;
16839
- if (cb) {
16840
- res = cb(res, idx, query);
16841
- }
16161
+ if (cb) res = cb(res, idx, query);
16842
16162
  };
16843
16163
 
16844
16164
  Tabletop.init(opt);
@@ -16917,11 +16237,8 @@ alasql.from.FILE = function (filename, opts, cb, idx, query) {
16917
16237
  }
16918
16238
 
16919
16239
  var parts = fname.split('.');
16920
-
16921
16240
  var ext = parts[parts.length - 1].toUpperCase();
16922
-
16923
16241
  if (alasql.from[ext]) {
16924
-
16925
16242
  return alasql.from[ext](filename, opts, cb, idx, query);
16926
16243
  } else {
16927
16244
  throw new Error('Cannot recognize file type for loading');
@@ -17547,14 +16864,11 @@ yy.Source.prototype.toString = function () {
17547
16864
 
17548
16865
  // SOURCE FILE
17549
16866
  yy.Source.prototype.execute = function (databaseid, params, cb) {
17550
-
17551
16867
  var res;
17552
16868
  loadFile(
17553
16869
  this.url,
17554
16870
  !!cb,
17555
16871
  function (data) {
17556
-
17557
- // res = 1;
17558
16872
  res = alasql(data);
17559
16873
  if (cb) res = cb(res);
17560
16874
  return res;
@@ -17604,15 +16918,12 @@ yy.Require.prototype.execute = function (databaseid, params, cb) {
17604
16918
  var self = this;
17605
16919
  var res = 0;
17606
16920
  var ss = '';
17607
-
17608
16921
  if (this.paths && this.paths.length > 0) {
17609
16922
  this.paths.forEach(function (path) {
17610
16923
  loadFile(path.value, !!cb, function (data) {
17611
16924
  res++;
17612
-
17613
16925
  ss += data;
17614
16926
  if (res < self.paths.length) return;
17615
-
17616
16927
  new Function('params,alasql', ss)(params, alasql);
17617
16928
  if (cb) res = cb(res);
17618
16929
  });
@@ -17626,7 +16937,6 @@ yy.Require.prototype.execute = function (databaseid, params, cb) {
17626
16937
  res++;
17627
16938
  ss += data;
17628
16939
  if (res < self.plugins.length) return;
17629
-
17630
16940
  new Function('params,alasql', ss)(params, alasql);
17631
16941
  alasql.plugins[plugin] = true; // Plugin is loaded
17632
16942
  if (cb) res = cb(res);
@@ -17657,11 +16967,7 @@ yy.Source.prototype.toString = function () {
17657
16967
 
17658
16968
  // SOURCE FILE
17659
16969
  yy.Assert.prototype.execute = function (databaseid) {
17660
-
17661
16970
  if (!deepEqual(alasql.res, this.value)) {
17662
- // if(this.message) {
17663
- // throw this.
17664
- // } else {
17665
16971
  throw new Error(
17666
16972
  (this.message || 'Assert wrong') +
17667
16973
  ': ' +
@@ -17669,7 +16975,6 @@ yy.Assert.prototype.execute = function (databaseid) {
17669
16975
  ' == ' +
17670
16976
  JSON.stringify(this.value)
17671
16977
  );
17672
- // }
17673
16978
  }
17674
16979
  return 1;
17675
16980
  };
@@ -18211,7 +17516,6 @@ LS.attachDatabase = function (lsdbid, databaseid, args, params, cb) {
18211
17516
  if (db.tables) {
18212
17517
  for (var tbid in db.tables) {
18213
17518
  LS.restoreTable(databaseid, tbid);
18214
- // db.tables[tbid].data = LS.get(db.lsdbid+'.'+tbid);
18215
17519
  }
18216
17520
  }
18217
17521
  }
@@ -18387,9 +17691,7 @@ LS.intoTable = function (databaseid, tableid, value, columns, cb) {
18387
17691
  }
18388
17692
  if (!tb.data) tb.data = [];
18389
17693
  tb.data = tb.data.concat(value);
18390
- // LS.set(lsdbid+'.'+tableid, tb);
18391
17694
  LS.storeTable(databaseid, tableid);
18392
-
18393
17695
  if (cb) res = cb(res);
18394
17696
 
18395
17697
  return res;
@@ -18529,7 +17831,6 @@ SQLITE.attachDatabase = function (sqldbid, dbid, args, params, cb) {
18529
17831
  db.tables[tbl[1]] = {};
18530
17832
  var columns = (db.tables[tbl[1]].columns = []);
18531
17833
  var ast = alasql.parse(tbl[4]);
18532
-
18533
17834
  var coldefs = ast.statements[0].columns;
18534
17835
  if (coldefs && coldefs.length > 0) {
18535
17836
  coldefs.forEach(function (cd) {
@@ -18606,12 +17907,9 @@ SQLITE.intoTable = function (databaseid, tableid, value, columns, cb) {
18606
17907
  var FS = (alasql.engines.FILESTORAGE = alasql.engines.FILE = function () {});
18607
17908
 
18608
17909
  FS.createDatabase = function (fsdbid, args, ifnotexists, dbid, cb) {
18609
-
18610
17910
  var res = 1;
18611
17911
  var filename = args[0].value;
18612
-
18613
17912
  alasql.utils.fileExists(filename, function (fex) {
18614
-
18615
17913
  if (fex) {
18616
17914
  if (ifnotexists) {
18617
17915
  res = 0;
@@ -18672,14 +17970,12 @@ FS.dropDatabase = function (fsdbid, ifexists, cb) {
18672
17970
  };
18673
17971
 
18674
17972
  FS.attachDatabase = function (fsdbid, dbid, args, params, cb) {
18675
-
18676
17973
  var res = 1;
18677
17974
  if (alasql.databases[dbid]) {
18678
17975
  throw new Error('Unable to attach database as "' + dbid + '" because it already exists');
18679
17976
  }
18680
17977
  var db = new alasql.Database(dbid || fsdbid);
18681
17978
  db.engineid = 'FILESTORAGE';
18682
- // db.fsdbid = fsdbid;
18683
17979
  db.filename = args[0].value;
18684
17980
  loadFile(db.filename, !!cb, function (s) {
18685
17981
  try {
@@ -18720,7 +18016,6 @@ FS.createTable = function (databaseid, tableid, ifnotexists, cb) {
18720
18016
  };
18721
18017
 
18722
18018
  FS.updateFile = function (databaseid) {
18723
-
18724
18019
  var db = alasql.databases[databaseid];
18725
18020
  if (db.issaving) {
18726
18021
  db.postsave = true;
@@ -18756,7 +18051,6 @@ FS.dropTable = function (databaseid, tableid, ifexists, cb) {
18756
18051
  };
18757
18052
 
18758
18053
  FS.fromTable = function (databaseid, tableid, cb, idx, query) {
18759
-
18760
18054
  var db = alasql.databases[databaseid];
18761
18055
  var res = db.data[tableid];
18762
18056
  if (cb) res = cb(res, idx, query);
@@ -18787,7 +18081,6 @@ FS.saveTableData = function (databaseid, tableid) {
18787
18081
  };
18788
18082
 
18789
18083
  FS.commit = function (databaseid, cb) {
18790
-
18791
18084
  var db = alasql.databases[databaseid];
18792
18085
  var fsdb = {tables: {}};
18793
18086
  if (db.tables) {
@@ -18806,9 +18099,6 @@ FS.rollback = function (databaseid, cb) {
18806
18099
  var res = 1;
18807
18100
  var db = alasql.databases[databaseid];
18808
18101
  db.dbversion++;
18809
-
18810
- // var lsdbid = alasql.databases[databaseid].lsdbid;
18811
- // lsdb = LS.get(lsdbid);
18812
18102
  wait();
18813
18103
  function wait() {
18814
18104
  setTimeout(function () {
@@ -18826,9 +18116,6 @@ FS.rollback = function (databaseid, cb) {
18826
18116
  db.tables[tbid].data = db.data[tbid];
18827
18117
  }
18828
18118
  db.tables[tbid].indexColumns();
18829
-
18830
- // index columns
18831
- // convert types
18832
18119
  }
18833
18120
 
18834
18121
  delete alasql.databases[databaseid];
@@ -18843,9 +18130,6 @@ FS.rollback = function (databaseid, cb) {
18843
18130
  }
18844
18131
  }, 100);
18845
18132
  }
18846
-
18847
- // if(!alasql.options.autocommit) {
18848
-
18849
18133
  };
18850
18134
  if(utils.isBrowser && !utils.isWebWorker) {
18851
18135
  alasql = alasql || false;