alasql 4.2.7 → 4.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/alasql.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.2.7 build: develop-993501d9 | © 2014-2024 Andrey Gershun & Mathias Wulff | License: MIT
2
2
  /*
3
3
  @module alasql
4
- @version 4.2.6
4
+ @version 4.2.7
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.2.7';
145
+ alasql.build = 'develop-993501d9';
146
146
 
147
147
  /**
148
148
  Debug flag
@@ -6459,26 +6459,9 @@ function queryfn(query, oldscope, cb, A, B) {
6459
6459
  query.queriesdata = [];
6460
6460
 
6461
6461
  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
6462
  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
6463
  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
6464
  });
6481
-
6482
6465
  }
6483
6466
 
6484
6467
  query.scope = oldscope ? cloneDeep(oldscope) : {};
@@ -6487,11 +6470,8 @@ function queryfn(query, oldscope, cb, A, B) {
6487
6470
 
6488
6471
  let result;
6489
6472
  query.sources.forEach(function (source, idx) {
6490
- // source.data = query.database.tables[source.tableid].data;
6491
-
6492
6473
  source.query = query;
6493
6474
  var rs = source.datafn(query, query.params, queryfn2, idx, alasql);
6494
-
6495
6475
  if (typeof rs !== 'undefined') {
6496
6476
  // TODO - this is a hack: check if result is array - check all cases and make it more logical
6497
6477
  if ((query.intofn || query.intoallfn) && Array.isArray(rs)) {
@@ -6519,29 +6499,20 @@ function queryfn(query, oldscope, cb, A, B) {
6519
6499
 
6520
6500
  return result;
6521
6501
  }
6522
-
6523
6502
  function queryfn2(data, idx, query) {
6524
-
6525
- //console.trace();
6526
-
6527
6503
  if (idx >= 0) {
6528
- var source = query.sources[idx];
6504
+ let source = query.sources[idx];
6529
6505
  source.data = data;
6530
- if (typeof source.data == 'function') {
6506
+ if (typeof source.data === 'function') {
6531
6507
  source.getfn = source.data;
6532
6508
  source.dontcache = source.getfn.dontcache;
6533
-
6534
- // var prevsource = query.sources[h-1];
6535
- if (source.joinmode == 'OUTER' || source.joinmode == 'RIGHT' || source.joinmode == 'ANTI') {
6509
+ if (['OUTER', 'RIGHT', 'ANTI'].includes(source.joinmode)) {
6536
6510
  source.dontcache = false;
6537
6511
  }
6538
6512
  source.data = {};
6539
6513
  }
6540
6514
  } else {
6541
- // subqueries
6542
-
6543
6515
  query.queriesdata[-idx - 1] = flatArray(data);
6544
-
6545
6516
  }
6546
6517
 
6547
6518
  query.sourceslen--;
@@ -7175,11 +7146,11 @@ function swapSources(query, h) {
7175
7146
  var source = query.sources[h];
7176
7147
  var nextsource = query.sources[h + 1];
7177
7148
 
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;
7149
+ let onleftfn = source.onleftfn;
7150
+ let onleftfns = source.onleftfns;
7151
+ let onrightfn = source.onrightfn;
7152
+ let onrightfns = source.onrightfns;
7153
+ let optimization = source.optimization;
7183
7154
 
7184
7155
  source.onleftfn = nextsource.onrightfn;
7185
7156
  source.onleftfns = nextsource.onrightfns;
@@ -7365,7 +7336,6 @@ yy.Select = class Select {
7365
7336
  query.explain = this.explain; // Explain
7366
7337
  query.explaination = [];
7367
7338
  query.explid = 1;
7368
-
7369
7339
  query.modifier = this.modifier;
7370
7340
 
7371
7341
  query.database = db;
@@ -7452,40 +7422,22 @@ yy.Select = class Select {
7452
7422
  query.corresponding = this.corresponding; // If CORRESPONDING flag exists
7453
7423
  if (this.union) {
7454
7424
  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
- }
7425
+ query.orderfn = this.union.order ? this.union.compileOrder(query, params) : null;
7460
7426
  } else if (this.unionall) {
7461
7427
  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
- }
7428
+ query.orderfn = this.unionall.order ? this.unionall.compileOrder(query, params) : null;
7467
7429
  } else if (this.except) {
7468
7430
  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
- }
7431
+ query.orderfn = this.except.order ? this.except.compileOrder(query, params) : null;
7474
7432
  } else if (this.intersect) {
7475
7433
  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
- }
7434
+ query.orderfn = this.intersect.order ? this.intersect.compileOrder(query, params) : null;
7481
7435
  }
7482
7436
 
7483
7437
  // SELECT INTO
7484
7438
  if (this.into) {
7485
7439
  if (this.into instanceof yy.Table) {
7486
- //
7487
7440
  // Save into the table in database
7488
- //
7489
7441
  if (
7490
7442
  alasql.options.autocommit &&
7491
7443
  alasql.databases[this.into.databaseid || databaseid].engineid
@@ -7536,7 +7488,6 @@ yy.Select = class Select {
7536
7488
  qs += 'undefined, undefined,';
7537
7489
  }
7538
7490
  query.intoallfns = qs + 'this.data,columns,cb)';
7539
-
7540
7491
  } else if (this.into instanceof yy.ParamValue) {
7541
7492
  //
7542
7493
  // Save data into parameters array
@@ -7547,11 +7498,9 @@ yy.Select = class Select {
7547
7498
 
7548
7499
  if (query.intofns) {
7549
7500
  // Create intofn function
7550
-
7551
7501
  query.intofn = new Function('r,i,params,alasql', 'var y;' + query.intofns);
7552
7502
  } else if (query.intoallfns) {
7553
7503
  // Create intoallfn function
7554
-
7555
7504
  query.intoallfn = new Function('columns,cb,params,alasql', 'var y;' + query.intoallfns);
7556
7505
  }
7557
7506
  }
@@ -7578,16 +7527,11 @@ yy.Select = class Select {
7578
7527
  if (cb) {
7579
7528
  cb(res2);
7580
7529
  }
7581
-
7582
7530
  return res2;
7583
7531
  });
7584
-
7585
- // if(typeof res1 != 'undefined') res1 = modify(query,res1);
7586
7532
  return res1;
7587
7533
  };
7588
7534
 
7589
- // statement.dbversion = ;
7590
-
7591
7535
  statement.query = query;
7592
7536
  return statement;
7593
7537
  }
@@ -7601,8 +7545,6 @@ yy.Select = class Select {
7601
7545
  if (!this.exists) return;
7602
7546
  query.existsfn = this.exists.map(function (ex) {
7603
7547
  var nq = ex.compile(query.database.databaseid);
7604
-
7605
- // if(!nq.query.modifier) nq.query.modifier = 'RECORDSET';
7606
7548
  nq.query.modifier = 'RECORDSET';
7607
7549
  return nq;
7608
7550
  });
@@ -7612,17 +7554,10 @@ yy.Select = class Select {
7612
7554
  if (!this.queries) return;
7613
7555
  query.queriesfn = this.queries.map(function (q) {
7614
7556
  var nq = q.compile(query.database.databaseid);
7615
-
7616
- // if(!nq.query) nq.query = {};
7617
7557
  nq.query.modifier = 'RECORDSET';
7618
- // if(!nq.query.modifier) nq.query.modifier = 'RECORDSET';
7619
7558
  return nq;
7620
7559
  });
7621
7560
  }
7622
-
7623
- // exec(databaseid) {
7624
- // throw new Error('Select statement should be precompiled');
7625
- // }
7626
7561
  };
7627
7562
 
7628
7563
  /**
@@ -7665,89 +7600,52 @@ function modify(query, res) {
7665
7600
  }
7666
7601
  }
7667
7602
 
7668
- if (modifier === 'VALUE') {
7603
+ switch (modifier) {
7604
+ case 'VALUE':
7605
+ if (res.length === 0) return undefined;
7606
+ const keyValue = columns && columns.length > 0 ? columns[0].columnid : Object.keys(res[0])[0];
7607
+ return res[0][keyValue];
7669
7608
 
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;
7609
+ case 'ROW':
7610
+ if (res.length === 0) return undefined;
7611
+ return Object.values(res[0]);
7612
+
7613
+ case 'COLUMN':
7614
+ if (res.length === 0) return [];
7615
+
7616
+ let key;
7696
7617
  if (columns && columns.length > 0) {
7697
7618
  key = columns[0].columnid;
7698
7619
  } else {
7699
7620
  key = Object.keys(res[0])[0];
7700
7621
  }
7701
7622
 
7623
+ let ar = [];
7702
7624
  for (var i = 0, ilen = res.length; i < ilen; i++) {
7703
7625
  ar.push(res[i][key]);
7704
7626
  }
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
7627
 
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);
7628
+ return ar;
7629
+
7630
+ case 'MATRIX':
7631
+ if (res.length === 0) return undefined;
7632
+ return res.map(row => columns.map(col => row[col.columnid]));
7633
+
7634
+ case 'INDEX':
7635
+ if (res.length === 0) return undefined;
7636
+ const keyIndex = columns && columns.length > 0 ? columns[0].columnid : Object.keys(res[0])[0];
7637
+ const valIndex = columns && columns.length > 1 ? columns[1].columnid : Object.keys(res[0])[1];
7638
+ return res.reduce((acc, row) => ({...acc, [row[keyIndex]]: row[valIndex]}), {});
7639
+
7640
+ case 'RECORDSET':
7641
+ // Assuming alasql.Recordset is available in the scope
7642
+ return new alasql.Recordset({columns: columns, data: res});
7643
+
7644
+ case 'TEXTSTRING':
7645
+ if (res.length === 0) return undefined;
7646
+ const keyTextString =
7647
+ columns && columns.length > 0 ? columns[0].columnid : Object.keys(res[0])[0];
7648
+ return res.map(row => row[keyTextString]).join('\n');
7751
7649
  }
7752
7650
  return res;
7753
7651
  }
@@ -7773,8 +7671,7 @@ yy.ExistsValue = class ExistsValue {
7773
7671
  }
7774
7672
 
7775
7673
  toJS(context, tableid, defcols) {
7776
-
7777
- return 'this.existsfn[' + this.existsidx + '](params,null,' + context + ').data.length';
7674
+ return `this.existsfn[${this.existsidx}](params, null, ${context}).data.length`;
7778
7675
  }
7779
7676
  };
7780
7677
 
@@ -7782,27 +7679,18 @@ yy.ExistsValue = class ExistsValue {
7782
7679
  // Prepare subqueries and exists
7783
7680
  //
7784
7681
  alasql.precompile = function (statement, databaseid, params) {
7785
-
7786
7682
  if (!statement) return;
7787
7683
  statement.params = params;
7788
7684
  if (statement.queries) {
7789
-
7790
7685
  statement.queriesfn = statement.queries.map(function (q) {
7791
7686
  var nq = q.compile(databaseid || statement.database.databaseid);
7792
-
7793
- // nq.query.modifier = undefined;
7794
- // if(!nq.query.modifier) nq.query.modifier = 'RECORDSET';
7795
7687
  nq.query.modifier = 'RECORDSET';
7796
7688
  return nq;
7797
7689
  });
7798
7690
  }
7799
7691
  if (statement.exists) {
7800
-
7801
7692
  statement.existsfn = statement.exists.map(function (ex) {
7802
7693
  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
7694
  nq.query.modifier = 'RECORDSET';
7807
7695
  return nq;
7808
7696
  });
@@ -7819,24 +7707,15 @@ alasql.precompile = function (statement, databaseid, params) {
7819
7707
  /* global yy, alasql, Mongo, returnTrue */
7820
7708
 
7821
7709
  yy.Select.prototype.compileFrom = function (query) {
7822
-
7823
- var self = this;
7710
+ const self = this;
7824
7711
  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
7712
  query.aliases = {};
7830
- if (!self.from) return;
7831
7713
 
7832
- self.from.forEach(function (tq) {
7833
-
7834
- var ps = '';
7835
-
7836
- var alias = tq.as || tq.tableid;
7714
+ if (!self.from) return;
7837
7715
 
7716
+ self.from.forEach(tq => {
7717
+ const alias = tq.as || tq.tableid;
7838
7718
  if (tq instanceof yy.Table) {
7839
-
7840
7719
  query.aliases[alias] = {
7841
7720
  tableid: tq.tableid,
7842
7721
  databaseid: tq.databaseid || query.database.databaseid,
@@ -7862,7 +7741,7 @@ yy.Select.prototype.compileFrom = function (query) {
7862
7741
  throw new Error('Wrong table at FROM');
7863
7742
  }
7864
7743
 
7865
- var source = {
7744
+ const source = {
7866
7745
  alias: alias,
7867
7746
  databaseid: tq.databaseid || query.database.databaseid,
7868
7747
  tableid: tq.tableid,
@@ -7870,21 +7749,16 @@ yy.Select.prototype.compileFrom = function (query) {
7870
7749
  onmiddlefn: returnTrue,
7871
7750
  srcwherefns: '', // for optimization
7872
7751
  srcwherefn: returnTrue,
7873
- // columns: []
7874
7752
  };
7875
7753
 
7876
7754
  if (tq instanceof yy.Table) {
7877
- // Get columns from table
7878
7755
  source.columns = alasql.databases[source.databaseid].tables[source.tableid].columns;
7879
-
7880
7756
  if (
7881
7757
  alasql.options.autocommit &&
7882
7758
  alasql.databases[source.databaseid].engineid &&
7883
7759
  !alasql.databases[source.databaseid].tables[source.tableid].view
7884
7760
  ) {
7885
-
7886
- // TODO -- make view for external engine
7887
- source.datafn = function (query, params, cb, idx, alasql) {
7761
+ source.datafn = (query, params, cb, idx, alasql) => {
7888
7762
  return alasql.engines[alasql.databases[source.databaseid].engineid].fromTable(
7889
7763
  source.databaseid,
7890
7764
  source.tableid,
@@ -7894,87 +7768,66 @@ yy.Select.prototype.compileFrom = function (query) {
7894
7768
  );
7895
7769
  };
7896
7770
  } 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);
7771
+ source.datafn = (query, params, cb, idx, alasql) => {
7772
+ let res = alasql.databases[source.databaseid].tables[source.tableid].select(params);
7899
7773
  if (cb) res = cb(res, idx, query);
7900
7774
  return res;
7901
7775
  };
7902
7776
  } 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
-
7777
+ source.datafn = (query, params, cb, idx, alasql) => {
7778
+ let res = alasql.databases[source.databaseid].tables[source.tableid].data;
7910
7779
  if (cb) res = cb(res, idx, query);
7911
-
7912
7780
  return res;
7913
- // return alasql.databases[source.databaseid].tables[source.tableid].data;
7914
7781
  };
7915
7782
  }
7916
7783
  } else if (tq instanceof yy.Select) {
7917
7784
  source.subquery = tq.compile(query.database.databaseid);
7918
7785
  if (typeof source.subquery.query.modifier === 'undefined') {
7919
- source.subquery.query.modifier = 'RECORDSET'; // Subqueries always return recordsets
7786
+ source.subquery.query.modifier = 'RECORDSET';
7920
7787
  }
7921
7788
  source.columns = source.subquery.query.columns;
7922
7789
 
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) {
7790
+ source.datafn = (query, params, cb, idx, alasql) => {
7791
+ let res;
7792
+ source.subquery(query.params, data => {
7929
7793
  res = data.data;
7930
7794
  if (cb) res = cb(res, idx, query);
7931
- return res;
7932
- // return data.data;
7933
7795
  });
7934
-
7935
7796
  return res;
7936
7797
  };
7937
7798
  } else if (tq instanceof yy.Search) {
7938
7799
  source.subsearch = tq;
7939
7800
  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) {
7801
+ source.datafn = (query, params, cb, idx, alasql) => {
7802
+ let res;
7803
+ source.subsearch.execute(query.database.databaseid, query.params, data => {
7945
7804
  res = data;
7946
7805
  if (cb) res = cb(res, idx, query);
7947
- return res;
7948
- // return data.data;
7949
7806
  });
7950
-
7951
7807
  return res;
7952
7808
  };
7953
7809
  } else if (tq instanceof yy.ParamValue) {
7954
- ps = "var res = alasql.prepareFromData(params['" + tq.param + "']";
7955
-
7810
+ let ps = `var res = alasql.prepareFromData(params['${tq.param}']`;
7956
7811
  if (tq.array) ps += ',true';
7957
7812
  ps += ');if(cb)res=cb(res,idx,query);return res';
7958
7813
  source.datafn = new Function('query,params,cb,idx,alasql', ps);
7959
7814
  } else if (tq.inserted) {
7960
- ps = 'var res = alasql.prepareFromData(alasql.inserted';
7815
+ let ps = 'var res = alasql.prepareFromData(alasql.inserted';
7961
7816
  if (tq.array) ps += ',true';
7962
7817
  ps += ');if(cb)res=cb(res,idx,query);return res';
7963
7818
  source.datafn = new Function('query,params,cb,idx,alasql', ps);
7964
7819
  } else if (tq instanceof yy.Json) {
7965
- ps = 'var res = alasql.prepareFromData(' + tq.toJS();
7966
-
7820
+ let ps = 'var res = alasql.prepareFromData(' + tq.toJS();
7967
7821
  if (tq.array) ps += ',true';
7968
7822
  ps += ');if(cb)res=cb(res,idx,query);return res';
7969
7823
  source.datafn = new Function('query,params,cb,idx,alasql', ps);
7970
7824
  } else if (tq instanceof yy.VarValue) {
7971
- ps = "var res = alasql.prepareFromData(alasql.vars['" + tq.variable + "']";
7972
-
7825
+ let ps = `var res = alasql.prepareFromData(alasql.vars['${tq.variable}']`;
7973
7826
  if (tq.array) ps += ',true';
7974
7827
  ps += ');if(cb)res=cb(res,idx,query);return res';
7975
7828
  source.datafn = new Function('query,params,cb,idx,alasql', ps);
7976
7829
  } else if (tq instanceof yy.FuncValue) {
7977
- ps = 'var res=alasql.from[' + JSON.stringify(tq.funcid.toUpperCase()) + '](';
7830
+ let ps = 'var res=alasql.from[' + JSON.stringify(tq.funcid.toUpperCase()) + '](';
7978
7831
 
7979
7832
  if (tq.args && tq.args.length > 0) {
7980
7833
  if (tq.args[0]) {
@@ -7982,6 +7835,7 @@ yy.Select.prototype.compileFrom = function (query) {
7982
7835
  } else {
7983
7836
  ps += 'null,';
7984
7837
  }
7838
+
7985
7839
  if (tq.args[1]) {
7986
7840
  ps += tq.args[1].toJS('query.oldscope') + ',';
7987
7841
  } else {
@@ -7990,46 +7844,32 @@ yy.Select.prototype.compileFrom = function (query) {
7990
7844
  } else {
7991
7845
  ps += 'null,null,';
7992
7846
  }
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);
7847
+ ps += 'cb,idx,query); return res';
7848
+ source.datafn = new Function('query,params,cb,idx,alasql', ps);
7997
7849
  } else if (tq instanceof yy.FromData) {
7998
- source.datafn = function (query, params, cb, idx, alasql) {
7999
- var res = tq.data;
7850
+ source.datafn = (query, params, cb, idx, alasql) => {
7851
+ let res = tq.data;
8000
7852
  if (cb) res = cb(res, idx, query);
8001
7853
  return res;
8002
7854
  };
8003
7855
  } else {
8004
7856
  throw new Error('Wrong table at FROM');
8005
7857
  }
8006
- // source.data = alasql.databases[source.databaseid].tables[source.tableid].data;
8007
7858
  query.sources.push(source);
8008
7859
  });
8009
- // TODO Add joins
8010
7860
  query.defaultTableid = query.sources[0].alias;
8011
-
8012
7861
  };
8013
7862
 
8014
7863
  alasql.prepareFromData = function (data, array) {
8015
-
8016
- var i, ilen;
8017
- var res = data;
7864
+ let res = data;
8018
7865
  if (typeof data === 'string') {
8019
7866
  res = data.split(/\r?\n/);
8020
7867
  if (array) {
8021
- for (i = 0, ilen = res.length; i < ilen; i++) {
8022
- res[i] = [res[i]];
8023
- }
7868
+ res = res.map(item => [item]);
8024
7869
  }
8025
7870
  } else if (array) {
8026
- res = [];
8027
- for (i = 0, ilen = data.length; i < ilen; i++) {
8028
- res.push([data[i]]);
8029
- }
8030
-
7871
+ res = data.map(item => [item]);
8031
7872
  } else if (typeof data === 'object' && !Array.isArray(data)) {
8032
- // } else if(typeof data == 'object' && !(typeof data.length == 'undefined')) {
8033
7873
  if (
8034
7874
  typeof Mongo !== 'undefined' &&
8035
7875
  typeof Mongo.Collection !== 'undefined' &&
@@ -8038,13 +7878,11 @@ alasql.prepareFromData = function (data, array) {
8038
7878
  res = data.find().fetch();
8039
7879
  } else {
8040
7880
  res = [];
8041
- for (var key in data) {
7881
+ for (const key in data) {
8042
7882
  if (data.hasOwnProperty(key)) res.push([key, data[key]]);
8043
7883
  }
8044
7884
  }
8045
-
8046
7885
  }
8047
-
8048
7886
  return res;
8049
7887
  };
8050
7888
  /*
@@ -8059,15 +7897,12 @@ alasql.prepareFromData = function (data, array) {
8059
7897
 
8060
7898
  /* global yy, alasql, returnTrue, arrayIntersect */
8061
7899
 
8062
- // Compile JOIN caluese
8063
7900
  yy.Select.prototype.compileJoins = function (query) {
7901
+ const self = this;
8064
7902
 
8065
- // debugger;
8066
- var self = this;
8067
-
8068
- this.joins.forEach(function (jn) {
7903
+ this.joins.forEach(jn => {
7904
+ let tq, ps, source;
8069
7905
  // Test CROSS-JOIN
8070
- var tq, ps, source;
8071
7906
  if (jn.joinmode === 'CROSS') {
8072
7907
  if (jn.using || jn.on) {
8073
7908
  throw new Error('CROSS JOIN cannot have USING or ON clauses');
@@ -8077,7 +7912,6 @@ yy.Select.prototype.compileJoins = function (query) {
8077
7912
  }
8078
7913
 
8079
7914
  if (jn instanceof yy.Apply) {
8080
-
8081
7915
  source = {
8082
7916
  alias: jn.as,
8083
7917
  applymode: jn.applymode,
@@ -8090,7 +7924,7 @@ yy.Select.prototype.compileJoins = function (query) {
8090
7924
  source.columns = source.applyselect.query.columns;
8091
7925
 
8092
7926
  source.datafn = function (query, params, cb, idx, alasql) {
8093
- var res;
7927
+ let res;
8094
7928
  if (cb) res = cb(res, idx, query);
8095
7929
  return res;
8096
7930
  };
@@ -8112,7 +7946,6 @@ yy.Select.prototype.compileJoins = function (query) {
8112
7946
  srcwherefn: returnTrue,
8113
7947
  columns: [],
8114
7948
  };
8115
- //
8116
7949
 
8117
7950
  if (!alasql.databases[source.databaseid].tables[source.tableid]) {
8118
7951
  throw new Error(
@@ -8122,11 +7955,8 @@ yy.Select.prototype.compileJoins = function (query) {
8122
7955
 
8123
7956
  source.columns = alasql.databases[source.databaseid].tables[source.tableid].columns;
8124
7957
 
8125
- // source.data = query.database.tables[source.tableid].data;
8126
7958
  if (alasql.options.autocommit && alasql.databases[source.databaseid].engineid) {
8127
-
8128
7959
  source.datafn = function (query, params, cb, idx, alasql) {
8129
-
8130
7960
  return alasql.engines[alasql.databases[source.databaseid].engineid].fromTable(
8131
7961
  source.databaseid,
8132
7962
  source.tableid,
@@ -8137,31 +7967,26 @@ yy.Select.prototype.compileJoins = function (query) {
8137
7967
  };
8138
7968
  } else if (alasql.databases[source.databaseid].tables[source.tableid].view) {
8139
7969
  source.datafn = function (query, params, cb, idx, alasql) {
8140
- var res = alasql.databases[source.databaseid].tables[source.tableid].select(params);
7970
+ let res = alasql.databases[source.databaseid].tables[source.tableid].select(params);
8141
7971
  if (cb) res = cb(res, idx, query);
8142
7972
  return res;
8143
7973
  };
8144
7974
  } else {
8145
7975
  source.datafn = function (query, params, cb, idx, alasql) {
8146
- var res = alasql.databases[source.databaseid].tables[source.tableid].data;
7976
+ let res = alasql.databases[source.databaseid].tables[source.tableid].data;
8147
7977
  if (cb) res = cb(res, idx, query);
8148
7978
  return res;
8149
7979
  };
8150
7980
  }
8151
7981
 
8152
- // var alias = jn.as || tq.tableid;
8153
- // if(tq) {
8154
7982
  query.aliases[source.alias] = {
8155
7983
  tableid: tq.tableid,
8156
7984
  databaseid: tq.databaseid || query.database.databaseid,
8157
7985
  };
8158
- // }
8159
7986
  } else if (jn.select) {
8160
7987
  tq = jn.select;
8161
7988
  source = {
8162
7989
  alias: jn.as,
8163
- // databaseid: jn.databaseid || query.database.databaseid,
8164
- // tableid: tq.tableid,
8165
7990
  joinmode: jn.joinmode,
8166
7991
  onmiddlefn: returnTrue,
8167
7992
  srcwherefns: '', // for optimization
@@ -8175,121 +8000,92 @@ yy.Select.prototype.compileJoins = function (query) {
8175
8000
  }
8176
8001
  source.columns = source.subquery.query.columns;
8177
8002
 
8178
- // if(jn instanceof yy.Apply) {
8179
8003
  source.datafn = function (query, params, cb, idx, alasql) {
8180
- // return cb(null,idx,alasql);
8181
8004
  source.data = source.subquery(query.params, null, cb, idx).data;
8182
- // var res = alasql.prepareFromData(params[idx]);
8183
- var res = source.data;
8005
+ let res = source.data;
8184
8006
  // Propogate subquery result
8185
8007
  if (cb) res = cb(res, idx, query);
8186
8008
  return res;
8187
8009
  };
8188
- // } else {
8189
- // source.datafn = function(query, params, cb, idx, alasql) {
8190
- // return source.subquery(query.params, null, cb, idx);
8191
- // }
8192
- // }
8193
8010
  query.aliases[source.alias] = {type: 'subquery'};
8194
8011
  } else if (jn.param) {
8195
8012
  source = {
8196
8013
  alias: jn.as,
8197
- // databaseid: jn.databaseid || query.database.databaseid,
8198
- // tableid: tq.tableid,
8199
8014
  joinmode: jn.joinmode,
8200
8015
  onmiddlefn: returnTrue,
8201
8016
  srcwherefns: '', // for optimization
8202
8017
  srcwherefn: returnTrue,
8203
8018
  };
8204
- // source.data = ;
8205
- var jnparam = jn.param.param;
8206
-
8207
- ps = "var res=alasql.prepareFromData(params['" + jnparam + "']";
8019
+ const jnparam = jn.param.param;
8020
+ ps = "let res=alasql.prepareFromData(params['" + jnparam + "']";
8208
8021
  if (jn.array) ps += ',true';
8209
- ps += ');if(cb)res=cb(res, idx, query);return res';
8022
+ ps += '); if(cb) res=cb(res, idx, query); return res';
8210
8023
 
8211
8024
  source.datafn = new Function('query,params,cb,idx, alasql', ps);
8212
8025
  query.aliases[source.alias] = {type: 'paramvalue'};
8213
8026
  } else if (jn.variable) {
8214
8027
  source = {
8215
8028
  alias: jn.as,
8216
- // databaseid: jn.databaseid || query.database.databaseid,
8217
- // tableid: tq.tableid,
8218
8029
  joinmode: jn.joinmode,
8219
8030
  onmiddlefn: returnTrue,
8220
8031
  srcwherefns: '', // for optimization
8221
8032
  srcwherefn: returnTrue,
8222
8033
  };
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';
8034
+ ps = "let res=alasql.prepareFromData(alasql.vars['" + jn.variable + "']";
8035
+ if (jn.array) ps += ', true';
8036
+ ps += '); if(cb)res=cb(res, idx, query);return res';
8229
8037
 
8230
8038
  source.datafn = new Function('query,params,cb,idx, alasql', ps);
8231
8039
  query.aliases[source.alias] = {type: 'varvalue'};
8232
8040
  } else if (jn.func) {
8233
8041
  source = {
8234
8042
  alias: jn.as,
8235
- // databaseid: jn.databaseid || query.database.databaseid,
8236
- // tableid: tq.tableid,
8237
8043
  joinmode: jn.joinmode,
8238
8044
  onmiddlefn: returnTrue,
8239
8045
  srcwherefns: '', // for optimization
8240
8046
  srcwherefn: returnTrue,
8241
8047
  };
8242
- // source.data = ;
8243
8048
 
8244
- var s = 'var res=alasql.from[' + JSON.stringify(jn.func.funcid.toUpperCase()) + '](';
8049
+ let s = 'let res=alasql.from[' + JSON.stringify(jn.func.funcid.toUpperCase()) + '](';
8245
8050
 
8246
- var args = jn.func.args;
8051
+ const args = jn.func.args;
8247
8052
  if (args && args.length > 0) {
8248
8053
  if (args[0]) {
8249
- s += args[0].toJS('query.oldscope') + ',';
8054
+ s += args[0].toJS('query.oldscope') + ', ';
8250
8055
  } else {
8251
- s += 'null,';
8056
+ s += 'null, ';
8252
8057
  }
8253
8058
  if (args[1]) {
8254
- s += args[1].toJS('query.oldscope') + ',';
8059
+ s += args[1].toJS('query.oldscope') + ', ';
8255
8060
  } else {
8256
- s += 'null,';
8061
+ s += 'null, ';
8257
8062
  }
8258
8063
  } else {
8259
- s += 'null,null,';
8064
+ s += 'null, null, ';
8260
8065
  }
8261
- s += 'cb,idx,query';
8262
- s += ');/*if(cb)res=cb(res,idx,query);*/return res';
8263
-
8066
+ s += 'cb, idx, query); return res';
8264
8067
  source.datafn = new Function('query, params, cb, idx, alasql', s);
8265
8068
 
8266
8069
  query.aliases[source.alias] = {type: 'funcvalue'};
8267
8070
  }
8268
8071
 
8269
- var alias = source.alias;
8072
+ const alias = source.alias;
8270
8073
 
8271
8074
  // Test NATURAL-JOIN
8272
8075
  if (jn.natural) {
8273
8076
  if (jn.using || jn.on) {
8274
8077
  throw new Error('NATURAL JOIN cannot have USING or ON clauses');
8275
8078
  } else {
8276
- // source.joinmode == "INNER";
8079
+ // source.joinmode == "INNER";
8277
8080
  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];
8081
+ const prevSource = query.sources[query.sources.length - 1];
8082
+ const prevTable = alasql.databases[prevSource.databaseid].tables[prevSource.tableid];
8083
+ const table = alasql.databases[source.databaseid].tables[source.tableid];
8281
8084
 
8282
8085
  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
-
8086
+ const c1 = prevTable.columns.map(col => col.columnid);
8087
+ const c2 = table.columns.map(col => col.columnid);
8088
+ jn.using = arrayIntersect(c1, c2).map(colid => ({columnid: colid}));
8293
8089
  } else {
8294
8090
  throw new Error(
8295
8091
  'In this version of Alasql NATURAL JOIN ' +
@@ -8301,45 +8097,31 @@ yy.Select.prototype.compileJoins = function (query) {
8301
8097
  }
8302
8098
 
8303
8099
  if (jn.using) {
8304
- prevSource = query.sources[query.sources.length - 1];
8305
-
8100
+ const prevSource = query.sources[query.sources.length - 1];
8306
8101
  source.onleftfns = jn.using
8307
- .map(function (col) {
8308
-
8309
- return "p['" + (prevSource.alias || prevSource.tableid) + "']['" + col.columnid + "']";
8310
- })
8102
+ .map(col => "p['" + (prevSource.alias || prevSource.tableid) + "']['" + col.columnid + "']")
8311
8103
  .join('+"`"+');
8312
8104
 
8313
- source.onleftfn = new Function('p,params,alasql', 'var y;return ' + source.onleftfns);
8105
+ source.onleftfn = new Function('p,params,alasql', 'let y;return ' + source.onleftfns);
8314
8106
 
8315
8107
  source.onrightfns = jn.using
8316
- .map(function (col) {
8317
- return "p['" + (source.alias || source.tableid) + "']['" + col.columnid + "']";
8318
- })
8108
+ .map(col => "p['" + (source.alias || source.tableid) + "']['" + col.columnid + "']")
8319
8109
  .join('+"`"+');
8320
- source.onrightfn = new Function('p,params,alasql', 'var y;return ' + source.onrightfns);
8110
+ source.onrightfn = new Function('p,params,alasql', 'let y;return ' + source.onrightfns);
8321
8111
  source.optimization = 'ix';
8322
-
8323
8112
  } else if (jn.on) {
8324
-
8325
8113
  if (jn.on instanceof yy.Op && jn.on.op === '=' && !jn.on.allsome) {
8326
-
8327
8114
  source.optimization = 'ix';
8328
-
8329
- var lefts = '';
8330
- var rights = '';
8331
- var middles = '';
8332
- var middlef = false;
8115
+ let lefts = '';
8116
+ let rights = '';
8117
+ let middles = '';
8118
+ let middlef = false;
8333
8119
  // 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);
8120
+ const ls = jn.on.left.toJS('p', query.defaultTableid, query.defcols);
8121
+ const rs = jn.on.right.toJS('p', query.defaultTableid, query.defcols);
8336
8122
 
8337
8123
  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
- ) {
8124
+ if ((ls.match(/p\['.*?'\]/g) || []).every(s => s === "p['" + alias + "']")) {
8343
8125
  rights = ls;
8344
8126
  } else {
8345
8127
  middlef = true;
@@ -8348,11 +8130,7 @@ yy.Select.prototype.compileJoins = function (query) {
8348
8130
  !(ls.indexOf("p['" + alias + "']") > -1) &&
8349
8131
  rs.indexOf("p['" + alias + "']") > -1
8350
8132
  ) {
8351
- if (
8352
- (rs.match(/p\['.*?'\]/g) || []).every(function (s) {
8353
- return s === "p['" + alias + "']";
8354
- })
8355
- ) {
8133
+ if ((rs.match(/p\['.*?'\]/g) || []).every(s => s === "p['" + alias + "']")) {
8356
8134
  lefts = ls;
8357
8135
  } else {
8358
8136
  middlef = true;
@@ -8362,11 +8140,7 @@ yy.Select.prototype.compileJoins = function (query) {
8362
8140
  }
8363
8141
 
8364
8142
  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
- ) {
8143
+ if ((rs.match(/p\['.*?'\]/g) || []).every(s => s === "p['" + alias + "']")) {
8370
8144
  rights = rs;
8371
8145
  } else {
8372
8146
  middlef = true;
@@ -8375,11 +8149,7 @@ yy.Select.prototype.compileJoins = function (query) {
8375
8149
  !(rs.indexOf("p['" + alias + "']") > -1) &&
8376
8150
  ls.indexOf("p['" + alias + "']") > -1
8377
8151
  ) {
8378
- if (
8379
- (ls.match(/p\['.*?'\]/g) || []).every(function (s) {
8380
- return s === "p['" + alias + "']";
8381
- })
8382
- ) {
8152
+ if ((ls.match(/p\['.*?'\]/g) || []).every(s => s === "p['" + alias + "']")) {
8383
8153
  lefts = rs;
8384
8154
  } else {
8385
8155
  middlef = true;
@@ -8389,47 +8159,31 @@ yy.Select.prototype.compileJoins = function (query) {
8389
8159
  }
8390
8160
 
8391
8161
  if (middlef) {
8392
- // middles = jn.on.toJS('p',query.defaultTableid);
8393
- // } else {
8394
8162
  rights = '';
8395
8163
  lefts = '';
8396
8164
  middles = jn.on.toJS('p', query.defaultTableid, query.defcols);
8397
8165
  source.optimization = 'no';
8398
- // What to here?
8399
8166
  }
8400
8167
 
8401
8168
  source.onleftfns = lefts;
8402
8169
  source.onrightfns = rights;
8403
8170
  source.onmiddlefns = middles || 'true';
8404
8171
 
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
-
8172
+ source.onleftfn = new Function('p,params,alasql', 'let y;return ' + source.onleftfns);
8173
+ source.onrightfn = new Function('p,params,alasql', 'let y;return ' + source.onrightfns);
8174
+ source.onmiddlefn = new Function('p,params,alasql', 'let y;return ' + source.onmiddlefns);
8411
8175
  } else {
8412
-
8413
8176
  source.optimization = 'no';
8414
- // source.onleftfn = returnTrue;
8415
- // source.onleftfns = "true";
8416
8177
  source.onmiddlefns = jn.on.toJS('p', query.defaultTableid, query.defcols);
8417
8178
  source.onmiddlefn = new Function(
8418
8179
  'p,params,alasql',
8419
- 'var y;return ' + jn.on.toJS('p', query.defaultTableid, query.defcols)
8180
+ 'let y;return ' + jn.on.toJS('p', query.defaultTableid, query.defcols)
8420
8181
  );
8421
8182
  }
8422
-
8423
- // Optimization function
8424
8183
  }
8425
8184
 
8426
- // source.data = alasql.databases[source.databaseid].tables[source.tableid].data;
8427
-
8428
- // TODO SubQueries
8429
-
8430
8185
  query.sources.push(source);
8431
8186
  });
8432
-
8433
8187
  };
8434
8188
  yy.Select.prototype.compileWhere = function (query) {
8435
8189
  if (this.where) {
@@ -8551,15 +8305,10 @@ yy.Select.prototype.compileGroup = function (query) {
8551
8305
  var tableid = '';
8552
8306
  }
8553
8307
  var defcols = query.defcols;
8554
-
8555
8308
  var allgroup = [[]];
8556
8309
  if (this.group) {
8557
8310
  allgroup = decartes(this.group, query);
8558
8311
  }
8559
-
8560
- // Prepare groups
8561
- //var allgroup = [['a'], ['a','b'], ['a', 'b', 'c']];
8562
-
8563
8312
  // Union all arrays to get a maximum
8564
8313
  var allgroups = [];
8565
8314
  allgroup.forEach(function (a) {
@@ -8570,12 +8319,10 @@ yy.Select.prototype.compileGroup = function (query) {
8570
8319
 
8571
8320
  query.ingroup = [];
8572
8321
  var s = '';
8573
- // s+= query.selectfns;
8574
8322
  allgroup.forEach(function (agroup) {
8575
8323
  // Start of group function
8576
8324
  s += 'var g=this.xgroups[';
8577
8325
 
8578
- // var gcols = this.group.map(function(col){return col.columnid}); // Group fields with r
8579
8326
  // Array with group columns from record
8580
8327
  var rg = agroup.map(function (col2) {
8581
8328
  var columnid = col2.split('\t')[0];
@@ -8584,9 +8331,7 @@ yy.Select.prototype.compileGroup = function (query) {
8584
8331
  if (columnid === '') {
8585
8332
  return '1'; // Create fictive grouping column for fictive GROUP BY
8586
8333
  }
8587
- // else return "r['"+columnid+"']";
8588
8334
  query.ingroup.push(columnid);
8589
-
8590
8335
  return coljs;
8591
8336
  });
8592
8337
 
@@ -8598,7 +8343,6 @@ yy.Select.prototype.compileGroup = function (query) {
8598
8343
  s += '];if(!g) {this.groups.push((g=this.xgroups[';
8599
8344
  s += rg.join('+"`"+');
8600
8345
  s += '] = {';
8601
- // s += ']=r';
8602
8346
  s += agroup
8603
8347
  .map(function (col2) {
8604
8348
  var columnid = col2.split('\t')[0];
@@ -8610,17 +8354,14 @@ yy.Select.prototype.compileGroup = function (query) {
8610
8354
  return "'" + columnid + "':" + coljs + ',';
8611
8355
  })
8612
8356
  .join('');
8613
-
8614
8357
  var neggroup = arrayDiff(allgroups, agroup);
8615
8358
 
8616
8359
  s += neggroup
8617
8360
  .map(function (col2) {
8618
8361
  var columnid = col2.split('\t')[0];
8619
- // var coljs = col2.split('\t')[1]
8620
8362
  return "'" + columnid + "':null,";
8621
8363
  })
8622
8364
  .join('');
8623
-
8624
8365
  var aft = '',
8625
8366
  aft2 = '';
8626
8367
 
@@ -8628,19 +8369,10 @@ yy.Select.prototype.compileGroup = function (query) {
8628
8369
  aft2 += "for(var f in p['" + query.groupStar + "']) {g[f]=p['" + query.groupStar + "'][f];};";
8629
8370
  }
8630
8371
 
8631
- /*
8632
- */
8633
- // s += self.columns.map(function(col){
8634
-
8635
8372
  s += query.selectGroup
8636
8373
  .map(function (col) {
8637
-
8638
8374
  var colexp = col.expression.toJS('p', tableid, defcols);
8639
8375
  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
8376
  let colExpIfFunIdExists = expression => {
8645
8377
  let colexpression = expression.args[0];
8646
8378
  return colexpression.toJS('p', tableid, defcols);
@@ -8666,12 +8398,7 @@ yy.Select.prototype.compileGroup = function (query) {
8666
8398
  return `'${colas}':(${colexp})|| typeof ${colexp} == 'number' ?
8667
8399
  ${colexp} : ${colexp} == 'string' && typeof Number(${colexp}) == 'number' ? Number(${colexp}) :
8668
8400
  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
- ) {
8401
+ } else if (col.aggregatorid === 'FIRST' || col.aggregatorid === 'LAST') {
8675
8402
  return "'" + colas + "':" + colexp + ','; //f.field.arguments[0].toJS();
8676
8403
  } else if (col.aggregatorid === 'MIN') {
8677
8404
  if ('funcid' in col.expression) {
@@ -8691,58 +8418,24 @@ yy.Select.prototype.compileGroup = function (query) {
8691
8418
  return `'${colas}' : (typeof ${colexp} == 'number' ? ${colexp} : typeof ${colexp} == 'object' ?
8692
8419
  typeof Number(${colexp}) == 'number' ? ${colexp} : null : null),`;
8693
8420
  } else if (col.aggregatorid === 'ARRAY') {
8694
- return "'" + colas + "':[" + colexp + '],';
8421
+ return `'${colas}':[${colexp}],`;
8695
8422
  } else if (col.aggregatorid === 'COUNT') {
8696
8423
  if (col.expression.columnid === '*') {
8697
- return "'" + colas + "':1,";
8424
+ return `'${colas}':1,`;
8698
8425
  } 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
- );
8426
+ return `'${colas}':(typeof ${colexp} == "undefined" || ${colexp} === null) ? 0 : 1,`;
8710
8427
  }
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
8428
  } else if (col.aggregatorid === 'AVG') {
8715
- query.removeKeys.push('_SUM_' + colas);
8716
- query.removeKeys.push('_COUNT_' + colas);
8429
+ query.removeKeys.push(`_SUM_${colas}`);
8430
+ query.removeKeys.push(`_COUNT_${colas}`);
8717
8431
 
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
- );
8432
+ return `'${colas}':${colexp},'_SUM_${colas}':(${colexp})||0,'_COUNT_${colas}':(typeof ${colexp} == "undefined" || ${colexp} === null) ? 0 : 1,`;
8736
8433
  } else if (col.aggregatorid === 'AGGR') {
8737
- aft += ",g['" + colas + "']=" + col.expression.toJS('g', -1);
8434
+ aft += `,g['${colas}']=${col.expression.toJS('g', -1)}`;
8738
8435
  return '';
8739
8436
  } else if (col.aggregatorid === 'REDUCE') {
8740
- // query.removeKeys.push('_REDUCE_'+colas);
8741
8437
  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),';
8438
+ return `'${colas}':alasql.aggr['${col.funcid}'](${colexp},undefined,1),`;
8746
8439
  }
8747
8440
  return '';
8748
8441
  }
@@ -8752,12 +8445,9 @@ yy.Select.prototype.compileGroup = function (query) {
8752
8445
  .join('');
8753
8446
 
8754
8447
  s += '}' + aft + ',g));' + aft2 + '} else {';
8755
-
8756
- // s += self.columns.map(function(col){
8757
8448
  s += query.selectGroup
8758
8449
  .map(function (col) {
8759
8450
  var colas = col.nick;
8760
-
8761
8451
  var colexp = col.expression.toJS('p', tableid, defcols);
8762
8452
  let colExpIfFunIdExists = expression => {
8763
8453
  let colexpression = expression.args[0];
@@ -8767,28 +8457,22 @@ yy.Select.prototype.compileGroup = function (query) {
8767
8457
  var pre = '',
8768
8458
  post = '';
8769
8459
  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;}';
8460
+ pre = `if(typeof ${colexp}!="undefined" && (!g['$$_VALUES_${colas}'][${colexp}])) {`;
8461
+ post = `g['$$_VALUES_${colas}'][${colexp}]=true;}`;
8779
8462
  }
8463
+
8780
8464
  if (col.aggregatorid === 'SUM') {
8781
8465
  if ('funcid' in col.expression) {
8782
8466
  let colexp1 = colExpIfFunIdExists(col.expression);
8783
8467
  return (
8784
8468
  pre +
8785
8469
  `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}}
8470
+ else if(typeof g['${colas}']!== 'object' && typeof g['${colas}']!== 'number' && typeof ${colexp1}!== 'object' && typeof ${colexp1}!== 'number'){ g['${colas}'] = null }
8471
+ else if(typeof g['${colas}']!== 'object' && typeof g['${colas}']!== 'number' && typeof ${colexp1} == 'number'){ g['${colas}'] = ${colexp} }
8472
+ else if(typeof g['${colas}']!== 'number' && typeof ${colexp1}!== 'number' && typeof ${colexp1}!== 'object'){ g['${colas}'] = g['${colas}'] }
8473
+ else if((g['${colas}'] == null || (typeof g['${colas}']!== 'number' && typeof g['${colas}']!== 'object')) && (${colexp1} == null || (typeof ${colexp1}!== 'number' && typeof ${colexp1}!== 'object'))){ g['${colas}'] = null }
8474
+ else if(typeof g['${colas}'] == 'number' && typeof ${colexp1} ==null){ g['${colas}'] = g['${colas}'] }
8475
+ else if(typeof g['${colas}'] == null && typeof ${colexp1} =='number'){ g['${colas}'] = ${colexp} }
8792
8476
  else{g['${colas}'] += ${colexp}||0}` +
8793
8477
  post
8794
8478
  );
@@ -8830,28 +8514,20 @@ yy.Select.prototype.compileGroup = function (query) {
8830
8514
  post
8831
8515
  );
8832
8516
  } else if (col.aggregatorid === 'COUNT') {
8833
-
8834
8517
  if (col.expression.columnid === '*') {
8835
- return pre + "g['" + colas + "']++;" + post;
8518
+ return `${pre}
8519
+ g['${colas}']++;
8520
+ ${post}`;
8836
8521
  } else {
8837
- return (
8838
- pre +
8839
- 'if(typeof ' +
8840
- colexp +
8841
- '!="undefined" && ' +
8842
- colexp +
8843
- " !== null) g['" +
8844
- colas +
8845
- "']++;" +
8846
- post
8847
- );
8522
+ return `${pre}
8523
+ if(typeof ${colexp}!="undefined" && ${colexp} !== null) g['${colas}']++;
8524
+ ${post}`;
8848
8525
  }
8849
8526
  } else if (col.aggregatorid === 'ARRAY') {
8850
8527
  return pre + "g['" + colas + "'].push(" + colexp + ');' + post;
8851
8528
  } else if (col.aggregatorid === 'MIN') {
8852
8529
  if ('funcid' in col.expression) {
8853
8530
  let colexp1 = colExpIfFunIdExists(col.expression);
8854
-
8855
8531
  return (
8856
8532
  pre +
8857
8533
  `if((g['${colas}'] == null && ${colexp1}!== null) ? y = ${colexp} : (g['${colas}']!== null &&
@@ -8901,47 +8577,21 @@ yy.Select.prototype.compileGroup = function (query) {
8901
8577
  } else if (col.aggregatorid === 'FIRST') {
8902
8578
  return '';
8903
8579
  } else if (col.aggregatorid === 'LAST') {
8904
- return pre + "g['" + colas + "']=" + colexp + ';' + post;
8580
+ return `${pre}g['${colas}']=${colexp};${post}`;
8905
8581
  } 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'); }
8582
+ return `${pre}
8583
+ g['_SUM_${colas}'] += (y=${colexp})||0;
8584
+ g['_COUNT_${colas}'] += (typeof y == "undefined" || y === null) ? 0 : 1;
8585
+ g['${colas}']=g['_SUM_${colas}'] / g['_COUNT_${colas}'];
8586
+ ${post}`;
8928
8587
  } else if (col.aggregatorid === 'AGGR') {
8929
- return '' + pre + "g['" + colas + "']=" + col.expression.toJS('g', -1) + ';' + post;
8588
+ return `${pre}
8589
+ g['${colas}']=${col.expression.toJS('g', -1)};
8590
+ ${post}`;
8930
8591
  } 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
- );
8592
+ return `${pre}
8593
+ g['${colas}'] = alasql.aggr.${col.funcid}(${colexp},g['${colas}'],2);
8594
+ ${post}`;
8945
8595
  }
8946
8596
 
8947
8597
  return '';
@@ -8951,24 +8601,8 @@ yy.Select.prototype.compileGroup = function (query) {
8951
8601
  })
8952
8602
  .join('');
8953
8603
 
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
8604
  s += '}';
8970
8605
  });
8971
-
8972
8606
  return new Function('p,params,alasql', 'var y;' + s);
8973
8607
  };
8974
8608
  /*
@@ -9857,22 +9491,22 @@ yy.Select.prototype.compileUnpivot = function (query) {
9857
9491
  Calculate ROLLUP() combination
9858
9492
  */
9859
9493
 
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++) {
9494
+ const rollup = (a, query) => {
9495
+ const rr = [];
9496
+ let mask = 0;
9497
+ const glen = a.length;
9498
+
9499
+ for (let g = 0; g < glen + 1; g++) {
9500
+ const ss = [];
9501
+ for (let i = 0; i < glen; i++) {
9502
+ let aaa;
9867
9503
  if (a[i] instanceof yy.Column) {
9868
9504
  a[i].nick = escapeq(a[i].columnid);
9869
-
9870
9505
  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);
9506
+ aaa = `${a[i].nick}\t${a[i].toJS('p', query.sources[0].alias, query.defcols)}`;
9872
9507
  } else {
9873
9508
  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);
9509
+ aaa = `${escapeq(a[i].toString())}\t${a[i].toJS('p', query.sources[0].alias, query.defcols)}`;
9876
9510
  }
9877
9511
 
9878
9512
  if (mask & (1 << i)) ss.push(aaa);
@@ -9886,22 +9520,17 @@ var rollup = function (a, query) {
9886
9520
  /**
9887
9521
  Calculate CUBE()
9888
9522
  */
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
-
9523
+ const cube = (a, query) => {
9524
+ const rr = [];
9525
+ const glen = a.length;
9526
+ const glenCube = 1 << glen;
9527
+
9528
+ for (let g = 0; g < glenCube; g++) {
9529
+ let ss = [];
9530
+ for (let i = 0; i < glen; i++) {
9531
+ if (g & (1 << i)) {
9903
9532
  ss = ss.concat(decartes(a[i], query));
9904
- //
9533
+ }
9905
9534
  }
9906
9535
  rr.push(ss);
9907
9536
  }
@@ -9909,22 +9538,21 @@ var cube = function (a, query) {
9909
9538
  };
9910
9539
 
9911
9540
  /**
9912
- GROUPING SETS()
9541
+ * GROUPING SETS()
9913
9542
  */
9914
- var groupingsets = function (a, query) {
9915
- return a.reduce(function (acc, d) {
9543
+ const groupingsets = (a, query) =>
9544
+ a.reduce((acc, d) => {
9916
9545
  acc = acc.concat(decartes(d, query));
9917
9546
  return acc;
9918
9547
  }, []);
9919
- };
9920
9548
 
9921
9549
  /**
9922
- Cartesian production
9550
+ * Cartesian production
9923
9551
  */
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++) {
9552
+ const cartes = (a1, a2) => {
9553
+ const rrr = [];
9554
+ for (let i1 = 0; i1 < a1.length; i1++) {
9555
+ for (let i2 = 0; i2 < a2.length; i2++) {
9928
9556
  rrr.push(a1[i1].concat(a2[i2]));
9929
9557
  }
9930
9558
  }
@@ -9933,72 +9561,54 @@ var cartes = function (a1, a2) {
9933
9561
 
9934
9562
  /**
9935
9563
  Prepare groups function
9936
- */
9937
- function decartes(gv, query) {
9938
-
9564
+ */ function decartes(gv, query) {
9939
9565
  if (Array.isArray(gv)) {
9940
- var res = [[]];
9941
- for (var t = 0; t < gv.length; t++) {
9566
+ let res = [[]];
9567
+ for (let t = 0; t < gv.length; t++) {
9942
9568
  if (gv[t] instanceof yy.Column) {
9943
-
9944
9569
  gv[t].nick = gv[t].nick ? escapeq(gv[t].nick) : escapeq(gv[t].columnid);
9945
9570
  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)});
9571
+ res = res.map(r =>
9572
+ r.concat(`${gv[t].nick}\t${gv[t].toJS('p', query.sources[0].alias, query.defcols)}`)
9573
+ );
9952
9574
  } else if (gv[t] instanceof yy.FuncValue) {
9953
9575
  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
9576
+ res = res.map(r =>
9577
+ r.concat(
9578
+ `${escapeq(gv[t].toString())}\t${gv[t].toJS('p', query.sources[0].alias, query.defcols)}`
9579
+ )
9580
+ );
9962
9581
  } else if (gv[t] instanceof yy.GroupExpression) {
9963
9582
  if (gv[t].type == 'ROLLUP') res = cartes(res, rollup(gv[t].group, query));
9964
9583
  else if (gv[t].type == 'CUBE') res = cartes(res, cube(gv[t].group, query));
9965
9584
  else if (gv[t].type == 'GROUPING SETS') res = cartes(res, groupingsets(gv[t].group, query));
9966
9585
  else throw new Error('Unknown grouping function');
9967
9586
  } else if (gv[t] === '') {
9968
-
9969
9587
  res = [['1\t1']];
9970
9588
  } 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]);
9589
+ res = res.map(r =>
9590
+ r.concat(
9591
+ `${escapeq(gv[t].toString())}\t${gv[t].toJS('p', query.sources[0].alias, query.defcols)}`
9592
+ )
9593
+ );
9982
9594
  }
9983
-
9984
9595
  }
9985
9596
  return res;
9986
- } else if (gv instanceof yy.FuncValue) {
9597
+ }
9987
9598
 
9599
+ if (gv instanceof yy.FuncValue) {
9988
9600
  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) {
9601
+ return [`${gv.toString()}\t${gv.toJS('p', query.sources[0].alias, query.defcols)}`];
9602
+ }
9603
+
9604
+ if (gv instanceof yy.Column) {
9991
9605
  gv.nick = escapeq(gv.columnid);
9992
9606
  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');
9607
+ return [`${gv.nick}\t${gv.toJS('p', query.sources[0].alias, query.defcols)}`];
10000
9608
  }
10001
9609
 
9610
+ query.groupColumns[escapeq(gv.toString())] = escapeq(gv.toString());
9611
+ return [`${escapeq(gv.toString())}\t${gv.toJS('p', query.sources[0].alias, query.defcols)}`];
10002
9612
  }
10003
9613
  /*
10004
9614
  //
@@ -10052,10 +9662,19 @@ yy.Select.prototype.compileDefCols = function (query, databaseid) {
10052
9662
  defcols['.'][jn.as || jn.table.tableid] = true;
10053
9663
 
10054
9664
  if (jn.table) {
10055
- var alias = jn.table.tableid;
10056
- if (jn.as) alias = jn.as;
10057
9665
  var alias = jn.as || jn.table.tableid;
10058
- var table = alasql.databases[jn.table.databaseid || databaseid].tables[jn.table.tableid];
9666
+ var databaseId = jn.table.databaseid || databaseid;
9667
+ var database = alasql.databases[databaseId];
9668
+
9669
+ if (database === undefined) {
9670
+ throw new Error('Database does not exist: ' + databaseId);
9671
+ }
9672
+
9673
+ var table = database.tables[jn.table.tableid];
9674
+
9675
+ if (table === undefined) {
9676
+ throw new Error('Table does not exist: ' + jn.table.tableid);
9677
+ }
10059
9678
 
10060
9679
  if (table.columns) {
10061
9680
  table.columns.forEach(function (col) {
@@ -10117,9 +9736,11 @@ yy.Apply = class Apply {
10117
9736
  }
10118
9737
 
10119
9738
  toString() {
10120
- var s = this.applymode + ' APPLY (' + this.select.toString() + ')';
9739
+ let s = `${this.applymode} APPLY (${this.select.toString()})`;
10121
9740
 
10122
- if (this.as) s += ' AS ' + this.as;
9741
+ if (this.as) {
9742
+ s += ` AS ${this.as}`;
9743
+ }
10123
9744
 
10124
9745
  return s;
10125
9746
  }
@@ -10138,13 +9759,13 @@ yy.Over = class Over {
10138
9759
  }
10139
9760
 
10140
9761
  toString() {
10141
- var s = 'OVER (';
9762
+ let s = 'OVER (';
10142
9763
  if (this.partition) {
10143
- s += 'PARTITION BY ' + this.partition.toString();
9764
+ s += `PARTITION BY ${this.partition.toString()}`;
10144
9765
  if (this.order) s += ' ';
10145
9766
  }
10146
9767
  if (this.order) {
10147
- s += 'ORDER BY ' + this.order.toString();
9768
+ s += `ORDER BY ${this.order.toString()}`;
10148
9769
  }
10149
9770
  s += ')';
10150
9771
  return s;
@@ -10176,7 +9797,6 @@ yy.Over = class Over {
10176
9797
  */
10177
9798
  execute(databaseid, params, cb) {
10178
9799
  if (this.expression) {
10179
-
10180
9800
  alasql.precompile(this, databaseid, params); // Precompile queries
10181
9801
  var exprfn = new Function(
10182
9802
  'params,alasql,p',
@@ -10433,20 +10053,15 @@ yy.Over = class Over {
10433
10053
  }
10434
10054
 
10435
10055
  toJS(context, tableid, defcols) {
10436
-
10437
10056
  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) {
10057
+ let refs = [];
10058
+ let op = this.op;
10059
+ let _this = this;
10060
+ let ref = function (expr) {
10446
10061
  if (expr.toJS) {
10447
10062
  expr = expr.toJS(context, tableid, defcols);
10448
10063
  }
10449
- var i = refs.push(expr) - 1;
10064
+ let i = refs.push(expr) - 1;
10450
10065
  return 'y[' + i + ']';
10451
10066
  };
10452
10067
  var leftJS = function () {
@@ -10462,201 +10077,91 @@ yy.Over = class Over {
10462
10077
  op = '!=';
10463
10078
  } else if (this.op === 'OR') {
10464
10079
  op = '||';
10465
- }
10466
-
10467
- // Arrow operator
10468
- if (this.op === '->') {
10080
+ } else if (this.op === '->') {
10469
10081
  // Expression to prevent error if object is empty (#344)
10470
- var ljs = '(' + leftJS() + '||{})';
10082
+ const ljs = `(${leftJS()} || {})`;
10471
10083
 
10472
10084
  if (typeof this.right === 'string') {
10473
- s = ljs + '["' + escapeq(this.right) + '"]';
10085
+ s = `${ljs}["${escapeq(this.right)}"]`;
10474
10086
  } else if (typeof this.right === 'number') {
10475
- s = ljs + '[' + this.right + ']';
10087
+ s = `${ljs}[${this.right}]`;
10476
10088
  } 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);
10089
+ let ss = [];
10090
+ if (this.right.args && this.right.args.length > 0) {
10091
+ ss = this.right.args.map(ref);
10480
10092
  }
10481
- s = '' + ljs + '[' + JSON.stringify(this.right.funcid) + '](' + ss.join(',') + ')';
10093
+ s = `${ljs}[${JSON.stringify(this.right.funcid)}](${ss.join(',')})`;
10482
10094
  } else {
10483
- s = '' + ljs + '[' + rightJS() + ']';
10095
+ s = `${ljs}[${rightJS()}]`;
10484
10096
  }
10485
- }
10486
-
10487
- if (this.op === '!') {
10097
+ } else if (this.op === '!') {
10488
10098
  if (typeof this.right === 'string') {
10489
- s = '' + 'alasql.databases[alasql.useid].objects[' + leftJS() + ']["' + this.right + '"]';
10099
+ s = `alasql.databases[alasql.useid].objects[${leftJS()}]["${this.right}"]`;
10490
10100
  }
10491
10101
  // TODO - add other cases
10492
- }
10493
-
10494
- if (this.op === 'IS') {
10102
+ } else if (this.op === 'IS') {
10495
10103
  const leftOperand = leftJS();
10496
10104
  const rightOperand = rightJS();
10497
10105
  if (
10498
10106
  this.right instanceof yy.NullValue ||
10499
10107
  (this.right.op === 'NOT' && this.right.right instanceof yy.NullValue)
10500
10108
  ) {
10501
- s = `((${leftOperand} == null) === (${rightOperand} == null))`; // == null cant be ===
10109
+ s = `((${leftOperand} == null) === (${rightOperand} == null))`; // == null can't be ===
10502
10110
  } else {
10503
- s = `((${leftOperand} == ${rightOperand}) || (${leftOperand} < 0 && true == ${rightOperand}))`;
10111
+ s = `((${leftOperand} == ${rightOperand}) || (${leftOperand} < 0 && true == ${rightOperand}))`;
10504
10112
  }
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') {
10113
+ } else if (this.op === '==') {
10114
+ s = `alasql.utils.deepEqual(${leftJS()}, ${rightJS()})`;
10115
+ } else if (this.op === '===' || this.op === '!===') {
10116
+ s = `(${this.op === '!===' ? '!' : ''}((${leftJS()}).valueOf() === (${rightJS()}).valueOf()))`;
10117
+ } else if (this.op === '!==') {
10118
+ s = `(!alasql.utils.deepEqual(${leftJS()}, ${rightJS()}))`;
10119
+ } else if (this.op === '||') {
10120
+ s = `(''+(${leftJS()} || '') + (${rightJS()} || ''))`;
10121
+ } else if (this.op === 'LIKE' || this.op === 'NOT LIKE') {
10122
+ s = `(${this.op === 'NOT LIKE' ? '!' : ''}alasql.utils.like(${rightJS()}, ${leftJS()}${this.escape ? `, ${ref(this.escape)}` : ''}))`;
10123
+ } else if (this.op === 'REGEXP') {
10124
+ s = `alasql.stdfn.REGEXP_LIKE(${leftJS()}, ${rightJS()})`;
10125
+ } else if (this.op === 'GLOB') {
10126
+ s = `alasql.utils.glob(${leftJS()}, ${rightJS()})`;
10127
+ } else if (this.op === 'BETWEEN' || this.op === 'NOT BETWEEN') {
10128
+ const left = leftJS();
10129
+ s = `(${this.op === 'NOT BETWEEN' ? '!' : ''}((${ref(this.right1)} <= ${left}) && (${left} <= ${ref(this.right2)})))`;
10130
+ } else if (this.op === 'IN') {
10575
10131
  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)';
10132
+ s = `alasql.utils.flatArray(this.queriesfn[${this.queriesidx}](params, null, ${context})).indexOf(alasql.utils.getValueOf(${leftJS()})) > -1`;
10587
10133
  } 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
- ')))';
10134
+ if (!alasql.options.cache || this.right.some(value => value instanceof yy.ParamValue)) {
10135
+ // Leverage JS Set for faster lookups than arrays
10136
+ s = `(new Set([${this.right.map(ref).join(',')}]).has(alasql.utils.getValueOf(${leftJS()})))`;
10600
10137
  } else {
10601
- // Use a cache to not re-create the Set on every identitical query
10602
- if (!alasql.sets) {
10603
- alasql.sets = {};
10604
- }
10138
+ // Use a cache to avoid re-creating the Set on every identical query
10139
+ alasql.sets = alasql.sets || {};
10605
10140
  const allValues = this.right.map(value => value.value);
10606
10141
  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() + '))';
10142
+ alasql.sets[allValuesStr] = alasql.sets[allValuesStr] || new Set(allValues);
10143
+ s = `alasql.sets["${allValuesStr}"].has(alasql.utils.getValueOf(${leftJS()}))`;
10613
10144
  }
10614
10145
  } else {
10615
- s = '(' + rightJS() + '.indexOf(' + leftJS() + ')>-1)';
10616
-
10617
- // } else {
10618
- // throw new Error('Wrong IN operator without SELECT part');
10146
+ s = `(${rightJS()}.indexOf(${leftJS()}) > -1)`;
10619
10147
  }
10620
- }
10621
-
10622
- if (this.op === 'NOT IN') {
10148
+ } else if (this.op === 'NOT IN') {
10623
10149
  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)';
10150
+ s = `alasql.utils.flatArray(this.queriesfn[${this.queriesidx}](params, null, p)).indexOf(alasql.utils.getValueOf(${leftJS()})) < 0`;
10628
10151
  } 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
- '))))';
10152
+ if (!alasql.options.cache || this.right.some(value => value instanceof yy.ParamValue)) {
10153
+ // Leverage JS Set for faster lookups than arrays
10154
+ s = `(!(new Set([${this.right.map(ref).join(',')}]).has(alasql.utils.getValueOf(${leftJS()}))))`;
10641
10155
  } else {
10642
- // Use a cache to not re-create the Set on every identitical query
10643
- if (!alasql.sets) {
10644
- alasql.sets = {};
10645
- }
10156
+ // Use a cache to avoid re-creating the Set on every identical query
10157
+ alasql.sets = alasql.sets || {};
10646
10158
  const allValues = this.right.map(value => value.value);
10647
10159
  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() + '))';
10160
+ alasql.sets[allValuesStr] = alasql.sets[allValuesStr] || new Set(allValues);
10161
+ s = `!alasql.sets["${allValuesStr}"].has(alasql.utils.getValueOf(${leftJS()}))`;
10654
10162
  }
10655
10163
  } else {
10656
- s = '(' + rightJS() + '.indexOf(';
10657
- s += leftJS() + ')==-1)';
10658
-
10659
- // throw new Error('Wrong NOT IN operator without SELECT part');
10164
+ s = `(${rightJS()}.indexOf(${leftJS()}) === -1)`;
10660
10165
  }
10661
10166
  }
10662
10167
 
@@ -10724,9 +10229,7 @@ yy.Over = class Over {
10724
10229
  return '(' + declareRefs + ', ' + expr + ')';
10725
10230
  }
10726
10231
 
10727
- return (
10728
- '(' + declareRefs + ', ' + 'y.some(function(e){return e == null}) ? void 0 : ' + expr + ')'
10729
- );
10232
+ return `(${declareRefs}, y.some(e => e == null) ? void 0 : ${expr})`;
10730
10233
  }
10731
10234
  }
10732
10235
 
@@ -10798,8 +10301,6 @@ yy.Over = class Over {
10798
10301
  }
10799
10302
 
10800
10303
  toJS(context, tableid, defcols) {
10801
-
10802
- // return "'"+doubleqq(this.value)+"'";
10803
10304
  return context;
10804
10305
  }
10805
10306
  }
@@ -11351,7 +10852,6 @@ yy.FuncValue.prototype.toJS = function (context, tableid, defcols) {
11351
10852
  } else if (!alasql.fn[funcid] && alasql.stdfn[funcid.toUpperCase()]) {
11352
10853
  if (this.newid) s += 'new ';
11353
10854
  s += 'alasql.stdfn[' + JSON.stringify(this.funcid.toUpperCase()) + '](';
11354
- // if(this.args) s += this.args.toJS(context, tableid);
11355
10855
  if (this.args && this.args.length > 0) {
11356
10856
  s += this.args
11357
10857
  .map(function (arg) {
@@ -11366,7 +10866,6 @@ yy.FuncValue.prototype.toJS = function (context, tableid, defcols) {
11366
10866
  // var s = '';
11367
10867
  if (this.newid) s += 'new ';
11368
10868
  s += 'alasql.fn[' + JSON.stringify(this.funcid) + '](';
11369
- // if(this.args) s += this.args.toJS(context, tableid);
11370
10869
  if (this.args && this.args.length > 0) {
11371
10870
  s += this.args
11372
10871
  .map(function (arg) {
@@ -11376,9 +10875,18 @@ yy.FuncValue.prototype.toJS = function (context, tableid, defcols) {
11376
10875
  }
11377
10876
  s += ')';
11378
10877
  }
11379
-
11380
10878
  return s;
11381
10879
  };
10880
+ /*
10881
+ //
10882
+ // SQL FUNCTIONS COMPILERS
10883
+ // Based on SQLite functions
10884
+
10885
+ // IMPORTANT: These are compiled functions
10886
+
10887
+ //alasql.fn = {}; // Keep for compatibility
10888
+ //alasql.userlib = alasql.fn;
10889
+ */
11382
10890
 
11383
10891
  var stdlib = (alasql.stdlib = {});
11384
10892
  var stdfn = (alasql.stdfn = {});
@@ -11399,16 +10907,16 @@ stdlib.EXP = function (a) {
11399
10907
 
11400
10908
  stdlib.IIF = function (a, b, c) {
11401
10909
  if (arguments.length === 3) {
11402
- return '((' + a + ')?(' + b + '):(' + c + '))';
10910
+ return `((${a}) ? (${b}) : (${c}))`;
11403
10911
  } else {
11404
10912
  throw new Error('Number of arguments of IFF is not equals to 3');
11405
10913
  }
11406
10914
  };
11407
10915
  stdlib.IFNULL = function (a, b) {
11408
- return '((typeof ' + a + ' ==="undefined" || null === ' + a + ')?' + b + ':' + a + ')';
10916
+ return `((typeof ${a} === "undefined" || ${a} === null) ? ${b} : ${a})`;
11409
10917
  };
11410
10918
  stdlib.INSTR = function (s, p) {
11411
- return '((' + s + ').indexOf(' + p + ')+1)';
10919
+ return `((${s}).indexOf(${p}) + 1)`;
11412
10920
  };
11413
10921
 
11414
10922
  //stdlib.LEN = stdlib.LENGTH = function(s) {return '('+s+'+"").length';};
@@ -11560,15 +11068,15 @@ alasql.aggr.median = alasql.aggr.MEDIAN = function (v, s, stage) {
11560
11068
  return null;
11561
11069
  }
11562
11070
 
11563
- var r = s.sort((a, b) => {
11071
+ let r = s.sort((a, b) => {
11564
11072
  if (a > b) return 1;
11565
11073
  if (a < b) return -1;
11566
11074
  return 0;
11567
11075
  });
11568
11076
 
11569
- var middle = (r.length + 1) / 2;
11570
- var middleFloor = middle | 0;
11571
- var el = r[middleFloor - 1];
11077
+ let middle = (r.length + 1) / 2;
11078
+ let middleFloor = middle | 0;
11079
+ let el = r[middleFloor - 1];
11572
11080
 
11573
11081
  if (middle === middleFloor || (typeof el !== 'number' && !(el instanceof Number))) {
11574
11082
  return el;
@@ -11584,32 +11092,34 @@ alasql.aggr.QUART = function (v, s, stage, nth) {
11584
11092
  s.push(v);
11585
11093
  }
11586
11094
  return s;
11587
- } else if (stage === 1) {
11095
+ }
11096
+
11097
+ if (stage === 1) {
11588
11098
  if (v === null) {
11589
11099
  return [];
11590
11100
  }
11591
11101
  return [v];
11592
- } else {
11593
- if (!s.length) {
11594
- return s;
11595
- }
11102
+ }
11103
+ if (!s.length) {
11104
+ return s;
11105
+ }
11596
11106
 
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
11107
+ nth = !nth ? 1 : nth;
11108
+ var r = s.sort(function (a, b) {
11109
+ if (a === b) return 0;
11110
+
11111
+ if (a > b) return 1;
11112
+
11113
+ return -1;
11114
+ });
11115
+
11116
+ let p = (nth * (r.length + 1)) / 4;
11117
+
11118
+ if (Number.isInteger(p)) {
11119
+ return r[p - 1]; //Integer value
11612
11120
  }
11121
+
11122
+ return r[Math.floor(p)]; //Math.ceil -1 or Math.floor
11613
11123
  };
11614
11124
 
11615
11125
  alasql.aggr.QUART2 = function (v, s, stage) {
@@ -11624,26 +11134,25 @@ alasql.aggr.QUART3 = function (v, s, stage) {
11624
11134
  // Standard deviation
11625
11135
  alasql.aggr.VAR = function (v, s, stage) {
11626
11136
  if (stage === 1) {
11627
- if (v === null) {
11628
- return {arr: [], sum: 0};
11629
- }
11630
- return {arr: [v], sum: v};
11137
+ // Initialise sum, sum of squares, and count
11138
+ return v === null ? {sum: 0, sumSq: 0, count: 0} : {sum: v, sumSq: v * v, count: 1};
11631
11139
  } else if (stage === 2) {
11632
- if (v === null) {
11633
- return s;
11140
+ // Update sum, sum of squares, and count
11141
+ if (v !== null) {
11142
+ s.sum += v;
11143
+ s.sumSq += v * v;
11144
+ s.count++;
11634
11145
  }
11635
- s.arr.push(v);
11636
- s.sum += v;
11637
11146
  return s;
11638
11147
  } 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);
11148
+ // Calculate variance using the formula: variance = (sumSq - (sum^2 / count)) / (count - 1)
11149
+ // This avoids the need to store and iterate over all values
11150
+ if (s.count > 1) {
11151
+ return (s.sumSq - (s.sum * s.sum) / s.count) / (s.count - 1);
11152
+ } else {
11153
+ // Handling for cases with less than 2 values (variance is undefined or zero)
11154
+ return 0;
11644
11155
  }
11645
- std = std / (N - 1);
11646
- return std;
11647
11156
  }
11648
11157
  };
11649
11158
 
@@ -11655,27 +11164,33 @@ alasql.aggr.STDEV = function (v, s, stage) {
11655
11164
  }
11656
11165
  };
11657
11166
 
11658
- // Standard deviation
11659
- // alasql.aggr.VARP = function(v,s,acc){
11660
-
11661
- // };
11167
+ alasql.aggr.STDEV = function (v, s, stage) {
11168
+ if (stage === 1 || stage === 2) {
11169
+ return alasql.aggr.VAR(v, s, stage);
11170
+ } else {
11171
+ return Math.sqrt(alasql.aggr.VAR(v, s, stage));
11172
+ }
11173
+ };
11662
11174
 
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;
11175
+ alasql.aggr.VARP = function (value, accumulator, stage) {
11176
+ if (stage === 1) {
11177
+ // Initialise accumulator with count, sum, and sum of squares
11178
+ return {count: 1, sum: value, sumSq: value * value};
11179
+ } else if (stage === 2) {
11180
+ // Update accumulator
11181
+ accumulator.count++;
11182
+ accumulator.sum += value;
11183
+ accumulator.sumSq += value * value;
11184
+ return accumulator;
11670
11185
  } 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);
11186
+ // Final stage: Calculate variance
11187
+ if (accumulator.count > 0) {
11188
+ const mean = accumulator.sum / accumulator.count;
11189
+ const variance = accumulator.sumSq / accumulator.count - mean * mean;
11190
+ return variance;
11191
+ } else {
11192
+ return 0; // Return 0 variance if no values were aggregated
11676
11193
  }
11677
- std = std / N;
11678
- return std;
11679
11194
  }
11680
11195
  };
11681
11196
 
@@ -11779,38 +11294,32 @@ yy.CaseValue.prototype.findAggregator = function (query) {
11779
11294
  };
11780
11295
 
11781
11296
  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) + '}';
11297
+ let s = `(((${context}, params, alasql) => {
11298
+ let y, r;`;
11299
+
11300
+ if (this.expression) {
11301
+ // If there's an expression, evaluate it and store in `v`, then compare in `when` clauses
11302
+ s += `let v = ${this.expression.toJS(context, tableid, defcols)};`;
11303
+ this.whens.forEach((w, index) => {
11304
+ const condition = `v === ${w.when.toJS(context, tableid, defcols)}`;
11305
+ const assignment = `r = ${w.then.toJS(context, tableid, defcols)}`;
11306
+ s += `${index === 0 ? 'if' : ' else if'} (${condition}) { ${assignment}; }`;
11307
+ });
11798
11308
  } 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) + '}';
11309
+ // Directly evaluate `when` conditions without an initial expression
11310
+ this.whens.forEach((w, index) => {
11311
+ const condition = w.when.toJS(context, tableid, defcols);
11312
+ const assignment = `r = ${w.then.toJS(context, tableid, defcols)}`;
11313
+ s += `${index === 0 ? 'if' : ' else if'} (${condition}) { ${assignment}; }`;
11314
+ });
11315
+ }
11316
+
11317
+ // Handle the `else` case
11318
+ if (this.elses) {
11319
+ s += ` else { r = ${this.elses.toJS(context, tableid, defcols)}; }`;
11811
11320
  }
11812
- // TODO remove bind from CASE
11813
- s += ';return r;}).bind(this))(' + context + ',params,alasql)';
11321
+
11322
+ s += '; return r; }))(' + context + ', params, alasql)';
11814
11323
 
11815
11324
  return s;
11816
11325
  };
@@ -11832,47 +11341,31 @@ yy.Json.prototype.toString = function () {
11832
11341
  return s;
11833
11342
  };
11834
11343
 
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);
11344
+ const JSONtoString = (alasql.utils.JSONtoString = function (obj) {
11345
+ if (typeof obj === 'string') return `"${obj}"`;
11346
+ if (typeof obj === 'number' || typeof obj === 'boolean') return String(obj);
11347
+
11348
+ if (Array.isArray(obj)) {
11349
+ return `[${obj.map(b => JSONtoString(b)).join(',')}]`;
11350
+ }
11351
+
11352
+ if (typeof obj === 'object') {
11353
+ if (!obj.toJS || obj instanceof yy.Json) {
11354
+ const ss = [];
11355
+ for (const k in obj) {
11356
+ const keyStr = typeof k === 'string' ? `"${k}"` : String(k);
11357
+ const valueStr = JSONtoString(obj[k]);
11358
+ ss.push(`${keyStr}:${valueStr}`);
11864
11359
  }
11865
- s += ss.join(',') + '}';
11360
+ return `{${ss.join(',')}}`;
11866
11361
  } else if (obj.toString) {
11867
- s = obj.toString();
11362
+ return obj.toString();
11868
11363
  } else {
11869
- throw new Error('1Can not show JSON object ' + JSON.stringify(obj));
11364
+ throw new Error(`1: Cannot show JSON object ${JSON.stringify(obj)}`);
11870
11365
  }
11871
11366
  } else {
11872
- throw new Error('2Can not show JSON object ' + JSON.stringify(obj));
11367
+ throw new Error(`2: Cannot show JSON object ${JSON.stringify(obj)}`);
11873
11368
  }
11874
-
11875
- return s;
11876
11369
  });
11877
11370
 
11878
11371
  function JSONtoJS(obj, context, tableid, defcols) {
@@ -11880,36 +11373,21 @@ function JSONtoJS(obj, context, tableid, defcols) {
11880
11373
  if (typeof obj == 'string') s = '"' + obj + '"';
11881
11374
  else if (typeof obj == 'number') s = '(' + obj + ')';
11882
11375
  else if (typeof obj == 'boolean') s = obj;
11883
- else if (typeof obj == 'object') {
11376
+ else if (typeof obj === 'object') {
11884
11377
  if (Array.isArray(obj)) {
11885
- s +=
11886
- '[' +
11887
- obj
11888
- .map(function (b) {
11889
- return JSONtoJS(b, context, tableid, defcols);
11890
- })
11891
- .join(',') +
11892
- ']';
11378
+ s += `[${obj.map(b => JSONtoJS(b, context, tableid, defcols)).join(',')}]`;
11893
11379
  } 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);
11380
+ let ss = [];
11381
+ for (const k in obj) {
11382
+ let keyStr = typeof k === 'string' ? `"${k}"` : k.toString();
11383
+ let valueStr = JSONtoJS(obj[k], context, tableid, defcols);
11384
+ ss.push(`${keyStr}:${valueStr}`);
11907
11385
  }
11908
- s += ss.join(',') + '}';
11386
+ s = `{${ss.join(',')}}`;
11909
11387
  } else if (obj.toJS) {
11910
11388
  s = obj.toJS(context, tableid, defcols);
11911
11389
  } else {
11912
- throw new Error('1Can not parse JSON object ' + JSON.stringify(obj));
11390
+ throw new Error(`Cannot parse JSON object ${JSON.stringify(obj)}`);
11913
11391
  }
11914
11392
  } else {
11915
11393
  throw new Error('2Can not parse JSON object ' + JSON.stringify(obj));
@@ -11947,23 +11425,12 @@ yy.Convert.prototype.toString = function () {
11947
11425
  return s;
11948
11426
  };
11949
11427
  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());
11428
+ return `alasql.stdfn.CONVERT(${this.expression.toJS(context, tableid, defcols)}, {
11429
+ dbtypeid: "${this.dbtypeid}",
11430
+ dbsize: ${this.dbsize},
11431
+ dbprecision: ${this.dbprecision},
11432
+ style: ${this.style}
11433
+ })`;
11967
11434
  };
11968
11435
 
11969
11436
  function structuredDate(unFormattedDate) {
@@ -12159,7 +11626,7 @@ yy.ColumnDef = function (params) {
12159
11626
  return Object.assign(this, params);
12160
11627
  };
12161
11628
  yy.ColumnDef.prototype.toString = function () {
12162
- var s = this.columnid;
11629
+ let s = this.columnid;
12163
11630
  if (this.dbtypeid) {
12164
11631
  s += ' ' + this.dbtypeid;
12165
11632
  }
@@ -12187,41 +11654,20 @@ yy.CreateTable = function (params) {
12187
11654
  return Object.assign(this, params);
12188
11655
  };
12189
11656
  yy.CreateTable.prototype.toString = function () {
12190
- var s = 'CREATE';
12191
- if (this.temporary) {
12192
- s += ' TEMPORARY';
12193
- }
11657
+ let s = `CREATE${this.temporary ? ' TEMPORARY' : ''}${this.view ? ' VIEW' : ` ${this.class ? 'CLASS' : 'TABLE'}`}${this.ifnotexists ? ' IF NOT EXISTS' : ''} ${this.table.toString()}`;
12194
11658
 
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
11659
  if (this.viewcolumns) {
12205
- s +=
12206
- '(' +
12207
- this.viewcolumns
12208
- .map(function (vcol) {
12209
- return vcol.toString();
12210
- })
12211
- .join(',') +
12212
- ')';
11660
+ s += `(${this.viewcolumns.map(vcol => vcol.toString()).join(',')})`;
12213
11661
  }
11662
+
12214
11663
  if (this.as) {
12215
- s += ' AS ' + this.as;
11664
+ s += ` AS ${this.as}`;
12216
11665
  } else {
12217
- var ss = this.columns.map(function (col) {
12218
- return col.toString();
12219
- });
12220
- s += ' (' + ss.join(',') + ')';
11666
+ s += ` (${this.columns.map(col => col.toString()).join(',')})`;
12221
11667
  }
12222
11668
 
12223
11669
  if (this.view && this.select) {
12224
- s += ' AS ' + this.select.toString();
11670
+ s += ` AS ${this.select.toString()}`;
12225
11671
  }
12226
11672
 
12227
11673
  return s;
@@ -12238,13 +11684,7 @@ yy.CreateTable.prototype.execute = function (databaseid, params, cb) {
12238
11684
  throw new Error('Table name is not defined');
12239
11685
  }
12240
11686
 
12241
- // var ifnotexists = this.ifnotexists;
12242
11687
  var columns = this.columns;
12243
- // if(false) {
12244
- // if(!columns) {
12245
- // throw new Error('Columns are not defined');
12246
- // }
12247
- // }
12248
11688
  var constraints = this.constraints || [];
12249
11689
 
12250
11690
  // IF NOT EXISTS
@@ -12295,8 +11735,6 @@ yy.CreateTable.prototype.execute = function (databaseid, params, cb) {
12295
11735
  value: +col.identity.value,
12296
11736
  step: +col.identity.step,
12297
11737
  };
12298
- // ss.push('\''+col.columnid+'\':(alasql.databases[\''+db.databaseid+'\'].tables[\''
12299
- // +tableid+'\'].identities[\''+col.columnid+'\'].value)');
12300
11738
  }
12301
11739
  if (col.check) {
12302
11740
  table.checks.push({
@@ -12333,7 +11771,6 @@ yy.CreateTable.prototype.execute = function (databaseid, params, cb) {
12333
11771
 
12334
11772
  // UNIQUE clause
12335
11773
  if (col.foreignkey) {
12336
-
12337
11774
  var fk = col.foreignkey.table;
12338
11775
  var fktable = alasql.databases[fk.databaseid || databaseid].tables[fk.tableid];
12339
11776
  if (typeof fk.columnid === 'undefined') {
@@ -12343,7 +11780,6 @@ yy.CreateTable.prototype.execute = function (databaseid, params, cb) {
12343
11780
  throw new Error('FOREIGN KEY allowed only to tables with PRIMARY KEYs');
12344
11781
  }
12345
11782
  }
12346
-
12347
11783
  var fkfn = function (r) {
12348
11784
  var rr = {};
12349
11785
  if (typeof r[col.columnid] === 'undefined') {
@@ -12351,7 +11787,6 @@ yy.CreateTable.prototype.execute = function (databaseid, params, cb) {
12351
11787
  }
12352
11788
  rr[fk.columnid] = r[col.columnid];
12353
11789
  var addr = fktable.pk.onrightfn(rr);
12354
-
12355
11790
  if (!fktable.uniqs[fktable.pk.hh][addr]) {
12356
11791
  throw new Error(
12357
11792
  'Foreign key violation' //changed error message
@@ -12360,7 +11795,6 @@ yy.CreateTable.prototype.execute = function (databaseid, params, cb) {
12360
11795
  return true;
12361
11796
  };
12362
11797
  table.checks.push({fn: fkfn});
12363
-
12364
11798
  }
12365
11799
 
12366
11800
  if (col.onupdate) {
@@ -12374,9 +11808,7 @@ yy.CreateTable.prototype.execute = function (databaseid, params, cb) {
12374
11808
  table.defaultfns = ss.join(',');
12375
11809
  table.onupdatefns = uss.join(';');
12376
11810
 
12377
- // if(constraints) {
12378
11811
  constraints.forEach(function (con) {
12379
-
12380
11812
  var checkfn;
12381
11813
 
12382
11814
  if (con.type === 'PRIMARY KEY') {
@@ -12394,10 +11826,8 @@ yy.CreateTable.prototype.execute = function (databaseid, params, cb) {
12394
11826
  pk.hh = hash(pk.onrightfns);
12395
11827
  table.uniqs[pk.hh] = {};
12396
11828
  } else if (con.type === 'CHECK') {
12397
-
12398
11829
  checkfn = new Function('r', 'var y;return ' + con.expression.toJS('r', ''));
12399
11830
  } else if (con.type === 'UNIQUE') {
12400
-
12401
11831
  var uk = {};
12402
11832
  table.uk = table.uk || [];
12403
11833
  table.uk.push(uk);
@@ -12475,25 +11905,18 @@ yy.CreateTable.prototype.execute = function (databaseid, params, cb) {
12475
11905
  //Used in 420from queryfn when table.view = true!
12476
11906
  if (this.view && this.select) {
12477
11907
  table.view = true;
12478
-
12479
11908
  table.select = this.select.compile(this.table.databaseid || databaseid);
12480
11909
  }
12481
11910
 
12482
11911
  if (db.engineid) {
12483
-
12484
11912
  return alasql.engines[db.engineid].createTable(
12485
11913
  this.table.databaseid || databaseid,
12486
11914
  tableid,
12487
11915
  this.ifnotexists,
12488
11916
  cb
12489
11917
  );
12490
-
12491
- // return res1;
12492
11918
  }
12493
11919
 
12494
- // }
12495
- // if(table.pk) {
12496
-
12497
11920
  table.insert = function (r, orreplace) {
12498
11921
  var oldinserted = alasql.inserted;
12499
11922
  alasql.inserted = [r];
@@ -13238,53 +12661,34 @@ yy.CreateEdge.prototype.compile = function (databaseid) {
13238
12661
  var setfn = new Function('x,params,alasql', 'var y;' + s);
13239
12662
  }
13240
12663
 
13241
- /*
13242
- todo: handle content, select and default
13243
- else if(this.content) {
13244
-
13245
- } else if(this.select) {
13246
-
13247
- } else {
13248
- }
13249
- */
12664
+ const statement = (params, cb) => {
12665
+ let res = 0;
12666
+ let db = alasql.databases[dbid];
12667
+ let edge = {$id: db.counter++, $node: 'EDGE'};
12668
+ let v1 = fromfn(params, alasql);
12669
+ let v2 = tofn(params, alasql);
13250
12670
 
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
12671
  // Set link
13259
12672
  edge.$in = [v1.$id];
13260
12673
  edge.$out = [v2.$id];
13261
- // Set sides
13262
- if (v1.$out === undefined) {
13263
- v1.$out = [];
13264
- }
12674
+
12675
+ // Initialize and set sides
12676
+ v1.$out = v1.$out || [];
13265
12677
  v1.$out.push(edge.$id);
13266
12678
 
13267
- if (typeof v2.$in === undefined) {
13268
- v2.$in = [];
13269
- }
12679
+ v2.$in = v2.$in || [];
13270
12680
  v2.$in.push(edge.$id);
13271
12681
 
13272
12682
  // Save in objects
13273
12683
  db.objects[edge.$id] = edge;
13274
12684
  res = edge;
13275
- if (namefn) {
13276
- namefn(edge);
13277
- }
13278
-
13279
- if (setfn) {
13280
- setfn(edge, params, alasql);
13281
- }
13282
12685
 
13283
- if (cb) {
13284
- res = cb(res);
13285
- }
12686
+ // Optional functions
12687
+ namefn?.(edge);
12688
+ setfn?.(edge, params, alasql);
13286
12689
 
13287
- return res;
12690
+ // Callback
12691
+ return cb ? cb(res) : res;
13288
12692
  };
13289
12693
  return statement;
13290
12694
  };
@@ -13309,122 +12713,77 @@ yy.CreateGraph.prototype.execute = function (databaseid, params, cb) {
13309
12713
  }
13310
12714
 
13311
12715
  // 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
- }
12716
+ this.graph.forEach(g => {
12717
+ if (!g.source) {
12718
+ createVertex(g);
12719
+ } else {
12720
+ // CREATE EDGE
12721
+ let e = {};
12722
+ if (g.as !== undefined) alasql.vars[g.as] = e;
12723
+ if (g.prop !== undefined) e.name = g.prop;
12724
+ if (g.sharp !== undefined) e.$id = g.sharp;
12725
+ if (g.name !== undefined) e.name = g.name;
12726
+ if (g.class !== undefined) e.$class = g.class;
12727
+
12728
+ let db = alasql.databases[databaseid];
12729
+ e.$id = e.$id !== undefined ? e.$id : db.counter++;
13339
12730
  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
12731
 
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
- }
12732
+ if (g.json !== undefined) {
12733
+ Object.assign(e, new Function('params, alasql', `return ${g.json.toJS()}`)(params, alasql));
13368
12734
  }
13369
12735
 
13370
- var v2;
13371
- if (g.source.vars) {
13372
- var vo = alasql.vars[g.target.vars];
13373
- if (typeof vo === 'object') {
13374
- v2 = vo;
12736
+ const resolveVertex = (sourceOrTarget, isSource) => {
12737
+ let vertex, vo;
12738
+ if (sourceOrTarget.vars) {
12739
+ vo = alasql.vars[sourceOrTarget.vars];
12740
+ vertex = typeof vo === 'object' ? vo : db.objects[vo];
13375
12741
  } 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);
12742
+ let av = sourceOrTarget.sharp || sourceOrTarget.prop;
12743
+ vertex = db.objects[av];
12744
+ if (
12745
+ vertex === undefined &&
12746
+ alasql.options.autovertex &&
12747
+ (sourceOrTarget.prop || sourceOrTarget.name)
12748
+ ) {
12749
+ vertex =
12750
+ findVertex(sourceOrTarget.prop || sourceOrTarget.name) ||
12751
+ createVertex(sourceOrTarget);
13392
12752
  }
13393
12753
  }
13394
- }
12754
+ if (isSource && vertex && typeof vertex.$out === 'undefined') vertex.$out = [];
12755
+ if (!isSource && vertex && typeof vertex.$in === 'undefined') vertex.$in = [];
12756
+ return vertex;
12757
+ };
13395
12758
 
13396
- // Set link
12759
+ let v1 = resolveVertex(g.source, true);
12760
+ let v2 = resolveVertex(g.target, false);
12761
+
12762
+ // Set link and sides
13397
12763
  e.$in = [v1.$id];
13398
12764
  e.$out = [v2.$id];
13399
- // Set sides
13400
- if (typeof v1.$out === 'undefined') {
13401
- v1.$out = [];
13402
- }
13403
12765
  v1.$out.push(e.$id);
13404
- if (typeof v2.$in === 'undefined') {
13405
- v2.$in = [];
13406
- }
13407
12766
  v2.$in.push(e.$id);
13408
12767
 
13409
12768
  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');
12769
+
12770
+ if (e.$class !== undefined) {
12771
+ let classTable = alasql.databases[databaseid].tables[e.$class];
12772
+ if (classTable === undefined) {
12773
+ throw new Error('No such class. Please use CREATE CLASS');
13413
12774
  } else {
13414
- // TODO - add insert()
13415
- alasql.databases[databaseid].tables[e.$class].data.push(e);
12775
+ classTable.data.push(e);
13416
12776
  }
13417
12777
  }
13418
12778
 
13419
12779
  res.push(e.$id);
13420
- } else {
13421
- createVertex(g);
13422
12780
  }
13423
12781
  });
13424
12782
 
13425
12783
  if (cb) {
13426
12784
  res = cb(res);
13427
12785
  }
12786
+
13428
12787
  return res;
13429
12788
 
13430
12789
  // Find vertex by name
@@ -13483,52 +12842,50 @@ yy.CreateGraph.prototype.execute = function (databaseid, params, cb) {
13483
12842
  return v;
13484
12843
  }
13485
12844
  };
13486
-
13487
12845
  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());
12846
+ const dbid = databaseid;
12847
+ const fromfn = new Function('params, alasql', `return ${this.from.toJS()}`);
12848
+ const tofn = new Function('params, alasql', `return ${this.to.toJS()}`);
12849
+
12850
+ let namefn, setfn;
13491
12851
 
13492
12852
  // CREATE VERTEX "Name"
13493
- if (typeof this.name !== 'undefined') {
13494
- var s = 'x.name=' + this.name.toJS();
13495
- var namefn = new Function('x', s);
12853
+ if (this.name !== undefined) {
12854
+ const s = `x.name = ${this.name.toJS()}`;
12855
+ namefn = new Function('x', s);
13496
12856
  }
13497
12857
 
13498
12858
  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
- })
12859
+ const s = this.sets
12860
+ .map(st => `x[${JSON.stringify(st.column.columnid)}] = ${st.expression.toJS('x', '')}`)
13503
12861
  .join(';');
13504
- var setfn = new Function('x,params,alasql', 'var y;' + s);
12862
+ setfn = new Function('x, params, alasql', `var y; ${s}`);
13505
12863
  }
13506
12864
 
13507
12865
  // Todo: handle content, select and default
13508
12866
 
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);
12867
+ const statement = (params, cb) => {
12868
+ let res = 0;
12869
+ const db = alasql.databases[dbid];
12870
+ const edge = {$id: db.counter++, $node: 'EDGE'};
12871
+ const v1 = fromfn(params, alasql);
12872
+ const v2 = tofn(params, alasql);
12873
+
13516
12874
  // Set link
13517
12875
  edge.$in = [v1.$id];
13518
12876
  edge.$out = [v2.$id];
12877
+
13519
12878
  // Set sides
13520
- if (typeof v1.$out === 'undefined') {
13521
- v1.$out = [];
13522
- }
12879
+ v1.$out = v1.$out || [];
13523
12880
  v1.$out.push(edge.$id);
13524
12881
 
13525
- if (typeof v2.$in === 'undefined') {
13526
- v2.$in = [];
13527
- }
12882
+ v2.$in = v2.$in || [];
13528
12883
  v2.$in.push(edge.$id);
12884
+
13529
12885
  // Save in objects
13530
12886
  db.objects[edge.$id] = edge;
13531
12887
  res = edge;
12888
+
13532
12889
  if (namefn) {
13533
12890
  namefn(edge);
13534
12891
  }
@@ -13557,13 +12914,13 @@ yy.AlterTable = function (params) {
13557
12914
  return Object.assign(this, params);
13558
12915
  };
13559
12916
  yy.AlterTable.prototype.toString = function () {
13560
- var s = 'ALTER TABLE ' + this.table.toString();
12917
+ let s = 'ALTER TABLE ' + this.table.toString();
13561
12918
  if (this.renameto) s += ' RENAME TO ' + this.renameto;
13562
12919
  return s;
13563
12920
  };
13564
12921
 
13565
12922
  yy.AlterTable.prototype.execute = function (databaseid, params, cb) {
13566
- var db = alasql.databases[databaseid];
12923
+ let db = alasql.databases[databaseid];
13567
12924
  db.dbversion = Date.now();
13568
12925
 
13569
12926
  if (this.renameto) {
@@ -13583,7 +12940,9 @@ yy.AlterTable.prototype.execute = function (databaseid, params, cb) {
13583
12940
  }
13584
12941
  if (cb) cb(res);
13585
12942
  return res;
13586
- } else if (this.addcolumn) {
12943
+ }
12944
+
12945
+ if (this.addcolumn) {
13587
12946
  db = alasql.databases[this.table.databaseid || databaseid];
13588
12947
  db.dbversion++;
13589
12948
  var tableid = this.table.tableid;
@@ -13609,15 +12968,15 @@ yy.AlterTable.prototype.execute = function (databaseid, params, cb) {
13609
12968
  table.columns.push(col);
13610
12969
  table.xcolumns[columnid] = col;
13611
12970
 
13612
- for (var i = 0, ilen = table.data.length; i < ilen; i++) {
13613
-
12971
+ for (let i = 0, ilen = table.data.length; i < ilen; i++) {
13614
12972
  table.data[i][columnid] = defaultfn();
13615
12973
  }
13616
12974
 
13617
- // TODO
13618
12975
  return cb ? cb(1) : 1;
13619
- } else if (this.modifycolumn) {
13620
- var db = alasql.databases[this.table.databaseid || databaseid];
12976
+ }
12977
+
12978
+ if (this.modifycolumn) {
12979
+ let db = alasql.databases[this.table.databaseid || databaseid];
13621
12980
  db.dbversion++;
13622
12981
  var tableid = this.table.tableid;
13623
12982
  var table = db.tables[tableid];
@@ -13635,10 +12994,11 @@ yy.AlterTable.prototype.execute = function (databaseid, params, cb) {
13635
12994
  col.dbprecision = this.dbprecision;
13636
12995
  col.dbenum = this.dbenum;
13637
12996
 
13638
- // TODO
13639
12997
  return cb ? cb(1) : 1;
13640
- } else if (this.renamecolumn) {
13641
- var db = alasql.databases[this.table.databaseid || databaseid];
12998
+ }
12999
+
13000
+ if (this.renamecolumn) {
13001
+ let db = alasql.databases[this.table.databaseid || databaseid];
13642
13002
  db.dbversion++;
13643
13003
 
13644
13004
  var tableid = this.table.tableid;
@@ -13665,16 +13025,16 @@ yy.AlterTable.prototype.execute = function (databaseid, params, cb) {
13665
13025
  delete table.xcolumns[columnid];
13666
13026
 
13667
13027
  for (var i = 0, ilen = table.data.length; i < ilen; i++) {
13668
-
13669
13028
  table.data[i][tocolumnid] = table.data[i][columnid];
13670
13029
  delete table.data[i][columnid];
13671
13030
  }
13672
13031
  return table.data.length;
13673
- } else {
13674
- return cb ? cb(0) : 0;
13675
13032
  }
13676
- } else if (this.dropcolumn) {
13677
- var db = alasql.databases[this.table.databaseid || databaseid];
13033
+ return cb ? cb(0) : 0;
13034
+ }
13035
+
13036
+ if (this.dropcolumn) {
13037
+ let db = alasql.databases[this.table.databaseid || databaseid];
13678
13038
  db.dbversion++;
13679
13039
  var tableid = this.table.tableid;
13680
13040
  var table = db.tables[tableid];
@@ -13700,10 +13060,11 @@ yy.AlterTable.prototype.execute = function (databaseid, params, cb) {
13700
13060
  for (i = 0, ilen = table.data.length; i < ilen; i++) {
13701
13061
  delete table.data[i][columnid];
13702
13062
  }
13063
+
13703
13064
  return cb ? cb(table.data.length) : table.data.length;
13704
- } else {
13705
- throw Error('Unknown ALTER TABLE method');
13706
13065
  }
13066
+
13067
+ throw Error('Unknown ALTER TABLE method');
13707
13068
  };
13708
13069
  /*
13709
13070
  //
@@ -14303,40 +13664,41 @@ yy.CreateTrigger.prototype.toString = function () {
14303
13664
  return s;
14304
13665
  };
14305
13666
 
13667
+ const validTriggers = [
13668
+ 'beforeinsert',
13669
+ 'afterinsert',
13670
+ 'insteadofinsert',
13671
+ 'beforedelete',
13672
+ 'afterdelete',
13673
+ 'insteadofdelete',
13674
+ 'beforeupdate',
13675
+ 'afterupdate',
13676
+ 'insteadofupdate',
13677
+ ];
13678
+
14306
13679
  yy.CreateTrigger.prototype.execute = function (databaseid, params, cb) {
14307
- var res = 1; // No tables removed
14308
- var triggerid = this.trigger;
13680
+ let res = 1; // No tables removed
13681
+ const triggerid = this.trigger;
14309
13682
  databaseid = this.table.databaseid || databaseid;
14310
- var db = alasql.databases[databaseid];
14311
- var tableid = this.table.tableid;
13683
+ const db = alasql.databases[databaseid];
13684
+ const {tableid} = this.table;
14312
13685
 
14313
- var trigger = {
13686
+ const trigger = {
14314
13687
  action: this.action,
14315
13688
  when: this.when,
14316
13689
  statement: this.statement,
14317
13690
  funcid: this.funcid,
14318
- tableid: this.table.tableid,
13691
+ tableid,
14319
13692
  };
14320
13693
 
14321
13694
  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;
13695
+ const actionKey = `${this.when}${this.action}`.toLowerCase();
13696
+
13697
+ if (validTriggers.includes(actionKey)) {
13698
+ // Ensure the existence of db.tables[tableid] and db.tables[tableid][actionKey]
13699
+ db.tables[tableid] = db.tables[tableid] || {};
13700
+ db.tables[tableid][actionKey] = db.tables[tableid][actionKey] || {};
13701
+ db.tables[tableid][actionKey][triggerid] = trigger;
14340
13702
  }
14341
13703
 
14342
13704
  if (cb) res = cb(res);
@@ -14361,28 +13723,26 @@ yy.DropTrigger.prototype.toString = function () {
14361
13723
  DROP TRIGGER one;
14362
13724
  */
14363
13725
  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;
13726
+ let res = 0; // No tables removed
13727
+ const db = alasql.databases[databaseid];
13728
+ const triggerid = this.trigger;
14367
13729
 
14368
- // get the trigger
14369
- var trigger = db.triggers[triggerid];
13730
+ // Get the trigger
13731
+ const trigger = db.triggers[triggerid];
14370
13732
 
14371
- // if the trigger exists
13733
+ // If the trigger exists
14372
13734
  if (trigger) {
14373
- var tableid = db.triggers[triggerid].tableid;
13735
+ const {tableid} = trigger;
14374
13736
 
14375
13737
  if (tableid) {
14376
13738
  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];
13739
+
13740
+ // Delete the trigger from all trigger points
13741
+ validTriggers.forEach(point => {
13742
+ delete db.tables[tableid][point][triggerid];
13743
+ });
13744
+
13745
+ // Finally, delete the trigger itself
14386
13746
  delete db.triggers[triggerid];
14387
13747
  } else {
14388
13748
  throw new Error('Trigger Table not found');
@@ -14390,6 +13750,7 @@ yy.DropTrigger.prototype.execute = function (databaseid, params, cb) {
14390
13750
  } else {
14391
13751
  throw new Error('Trigger not found');
14392
13752
  }
13753
+
14393
13754
  if (cb) res = cb(res);
14394
13755
  return res;
14395
13756
  };
@@ -14411,16 +13772,12 @@ yy.Delete.prototype.toString = function () {
14411
13772
  };
14412
13773
 
14413
13774
  yy.Delete.prototype.compile = function (databaseid) {
14414
-
14415
13775
  databaseid = this.table.databaseid || databaseid;
14416
13776
  var tableid = this.table.tableid;
14417
13777
  var statement;
14418
13778
  var db = alasql.databases[databaseid];
14419
13779
 
14420
13780
  if (this.where) {
14421
-
14422
- // this.query = {};
14423
-
14424
13781
  if (this.exists) {
14425
13782
  this.existsfn = this.exists.map(function (ex) {
14426
13783
  var nq = ex.compile(databaseid);
@@ -14428,6 +13785,7 @@ yy.Delete.prototype.compile = function (databaseid) {
14428
13785
  return nq;
14429
13786
  });
14430
13787
  }
13788
+
14431
13789
  if (this.queries) {
14432
13790
  this.queriesfn = this.queries.map(function (q) {
14433
13791
  var nq = q.compile(databaseid);
@@ -14436,10 +13794,6 @@ yy.Delete.prototype.compile = function (databaseid) {
14436
13794
  });
14437
13795
  }
14438
13796
 
14439
- // try {
14440
-
14441
- // var query = {};
14442
-
14443
13797
  var wherefn = new Function(
14444
13798
  'r,params,alasql',
14445
13799
  'var y;return (' + this.where.toJS('r', '') + ')'
@@ -14465,7 +13819,6 @@ yy.Delete.prototype.compile = function (databaseid) {
14465
13819
  }
14466
13820
 
14467
13821
  var table = db.tables[tableid];
14468
- // table.dirty = true;
14469
13822
  var orignum = table.data.length;
14470
13823
 
14471
13824
  var newtable = [];
@@ -14477,9 +13830,10 @@ yy.Delete.prototype.compile = function (databaseid) {
14477
13830
  } else {
14478
13831
  // Simply do not push
14479
13832
  }
14480
- } else newtable.push(table.data[i]);
13833
+ } else {
13834
+ newtable.push(table.data[i]);
13835
+ }
14481
13836
  }
14482
- // table.data = table.data.filter(function(r){return !;});
14483
13837
  table.data = newtable;
14484
13838
 
14485
13839
  // Trigger prevent functionality
@@ -14503,15 +13857,10 @@ yy.Delete.prototype.compile = function (databaseid) {
14503
13857
  alasql.engines[db.engineid].saveTableData(databaseid, tableid);
14504
13858
  }
14505
13859
 
14506
- if (cb) cb(res);
13860
+ if (cb) res = cb(res);
13861
+
14507
13862
  return res;
14508
13863
  };
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
13864
  } else {
14516
13865
  statement = function (params, cb) {
14517
13866
  if (alasql.options.autocommit && db.engineid) {
@@ -14521,7 +13870,6 @@ yy.Delete.prototype.compile = function (databaseid) {
14521
13870
  var table = db.tables[tableid];
14522
13871
  table.dirty = true;
14523
13872
  var orignum = db.tables[tableid].data.length;
14524
- //table.deleteall();
14525
13873
  // Delete all records from the array
14526
13874
  db.tables[tableid].data.length = 0;
14527
13875
 
@@ -14674,35 +14022,30 @@ yy.Merge = function (params) {
14674
14022
  return Object.assign(this, params);
14675
14023
  };
14676
14024
  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) {
14025
+ let s = `MERGE ${this.into.tableid} `;
14026
+ if (this.into.as) s += `AS ${this.into.as} `;
14027
+ s += `USING ${this.using.tableid} `;
14028
+ if (this.using.as) s += `AS ${this.using.as} `;
14029
+ s += `ON ${this.on.toString()} `;
14030
+
14031
+ this.matches.forEach(m => {
14684
14032
  s += 'WHEN ';
14685
14033
  if (!m.matched) s += 'NOT ';
14686
14034
  s += 'MATCHED ';
14687
14035
  if (m.bytarget) s += 'BY TARGET ';
14688
14036
  if (m.bysource) s += 'BY SOURCE ';
14689
- if (m.expr) s += 'AND' + ' ' + m.expr.toString() + ' ';
14037
+ if (m.expr) s += `AND ${m.expr.toString()} `;
14690
14038
  s += 'THEN ';
14691
14039
  if (m.action.delete) s += 'DELETE ';
14692
14040
  if (m.action.insert) {
14693
14041
  s += 'INSERT ';
14694
- if (m.action.columns) s += '(' + m.action.columns.toString() + ') ';
14695
- if (m.action.values) s += 'VALUES (' + m.action.values.toString() + ') ';
14042
+ if (m.action.columns) s += `(${m.action.columns.toString()}) `;
14043
+ if (m.action.values) s += `VALUES (${m.action.values.toString()}) `;
14696
14044
  if (m.action.defaultvalues) s += 'DEFAULT VALUES ';
14697
14045
  }
14698
14046
  if (m.action.update) {
14699
14047
  s += 'UPDATE ';
14700
- s +=
14701
- m.action.update
14702
- .map(function (u) {
14703
- return u.toString();
14704
- })
14705
- .join(',') + ' ';
14048
+ s += m.action.update.map(u => u.toString()).join(', ') + ' ';
14706
14049
  }
14707
14050
  });
14708
14051
 
@@ -14731,25 +14074,19 @@ yy.CreateDatabase = function (params) {
14731
14074
  return Object.assign(this, params);
14732
14075
  };
14733
14076
  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;
14077
+ let s = 'CREATE '; // Ensure there's a space after CREATE
14078
+ if (this.engineid) s += `${this.engineid} `;
14079
+ s += 'DATABASE ';
14080
+ if (this.ifnotexists) s += 'IF NOT EXISTS ';
14081
+ s += `${this.databaseid} `;
14082
+
14739
14083
  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
- ')';
14084
+ s += `(${this.args.map(arg => arg.toString()).join(', ')}) `;
14748
14085
  }
14749
- if (this.as) s += ' AS ' + this.as;
14086
+ if (this.as) s += `AS ${this.as}`;
14750
14087
  return s;
14751
14088
  };
14752
- //yy.CreateDatabase.prototype.compile = returnUndefined;
14089
+
14753
14090
  yy.CreateDatabase.prototype.execute = function (databaseid, params, cb) {
14754
14091
  var args;
14755
14092
  if (this.args && this.args.length > 0) {
@@ -14784,25 +14121,21 @@ yy.AttachDatabase = function (params) {
14784
14121
  return Object.assign(this, params);
14785
14122
  };
14786
14123
  yy.AttachDatabase.prototype.toString = function (args) {
14787
- var s = 'ATTACH';
14788
- if (this.engineid) s += ' ' + this.engineid;
14789
- s += ' DATABASE' + ' ' + this.databaseid;
14124
+ let s = 'ATTACH';
14125
+ if (this.engineid) s += ` ${this.engineid}`;
14126
+ s += ` DATABASE ${this.databaseid}`;
14790
14127
  // TODO add params
14791
14128
  if (args) {
14792
14129
  s += '(';
14793
14130
  if (args.length > 0) {
14794
- s += args
14795
- .map(function (arg) {
14796
- return arg.toString();
14797
- })
14798
- .join(', ');
14131
+ s += args.map(arg => arg.toString()).join(', ');
14799
14132
  }
14800
14133
  s += ')';
14801
14134
  }
14802
- if (this.as) s += ' AS' + ' ' + this.as;
14135
+ if (this.as) s += ` AS ${this.as}`;
14803
14136
  return s;
14804
14137
  };
14805
- //yy.CreateDatabase.prototype.compile = returnUndefined;
14138
+
14806
14139
  yy.AttachDatabase.prototype.execute = function (databaseid, params, cb) {
14807
14140
  if (!alasql.engines[this.engineid]) {
14808
14141
  throw new Error('Engine "' + this.engineid + '" is not defined.');
@@ -14873,8 +14206,6 @@ yy.DetachDatabase.prototype.execute = function (databaseid, params, cb) {
14873
14206
  }
14874
14207
  if (cb) cb(res);
14875
14208
  return res;
14876
- // var res = alasql.engines[this.engineid].attachDatabase(this.databaseid, this.as, cb);
14877
- // return res;
14878
14209
  };
14879
14210
 
14880
14211
  // USE DATABSE databaseid
@@ -14912,22 +14243,22 @@ yy.DropDatabase.prototype.execute = function (databaseid, params, cb) {
14912
14243
  if (this.engineid) {
14913
14244
  return alasql.engines[this.engineid].dropDatabase(this.databaseid, this.ifexists, cb);
14914
14245
  }
14915
- var res;
14246
+ let res;
14916
14247
 
14917
- var dbid = this.databaseid;
14248
+ const dbid = this.databaseid;
14918
14249
 
14919
14250
  if (dbid === alasql.DEFAULTDATABASEID) {
14920
14251
  throw new Error('Drop of default database is prohibited');
14921
14252
  }
14922
14253
  if (!alasql.databases[dbid]) {
14923
14254
  if (!this.ifexists) {
14924
- throw new Error("Database '" + dbid + "' does not exist");
14255
+ throw new Error(`Database '${dbid}' does not exist`);
14925
14256
  } else {
14926
14257
  res = 0;
14927
14258
  }
14928
14259
  } else {
14929
14260
  if (alasql.databases[dbid].engineid) {
14930
- throw new Error("Cannot drop database '" + dbid + "', because it is attached. Detach it.");
14261
+ throw new Error(`Cannot drop database '${dbid}', because it is attached. Detach it.`);
14931
14262
  }
14932
14263
 
14933
14264
  delete alasql.databases[dbid];
@@ -14951,24 +14282,22 @@ yy.Declare = function (params) {
14951
14282
  return Object.assign(this, params);
14952
14283
  };
14953
14284
  yy.Declare.prototype.toString = function () {
14954
- var s = 'DECLARE ';
14285
+ let s = 'DECLARE ';
14955
14286
  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;
14287
+ s += this.declares
14288
+ .map(declare => {
14289
+ let declareStr = `@${declare.variable} ${declare.dbtypeid}`;
14290
+ if (declare.dbsize) {
14291
+ declareStr += `(${declare.dbsize}`;
14292
+ if (declare.dbprecision) {
14293
+ declareStr += `,${declare.dbprecision}`;
14965
14294
  }
14966
- s += ')';
14295
+ declareStr += ')';
14967
14296
  }
14968
14297
  if (declare.expression) {
14969
- s += ' = ' + declare.expression.toString();
14298
+ declareStr += ` = ${declare.expression.toString()}`;
14970
14299
  }
14971
- return s;
14300
+ return declareStr;
14972
14301
  })
14973
14302
  .join(',');
14974
14303
  }
@@ -15177,76 +14506,67 @@ yy.SetVariable.prototype.toString = function () {
15177
14506
  };
15178
14507
 
15179
14508
  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 == '@') {
14509
+ if (typeof this.value !== 'undefined') {
14510
+ let val = this.value;
14511
+ if (val === 'ON') val = true;
14512
+ else if (val === 'OFF') val = false;
15186
14513
  alasql.options[this.variable] = val;
15187
- // } else {
15188
- // params[this.variable] = val;
15189
- // }
15190
14514
  } else if (this.expression) {
15191
14515
  if (this.exists) {
15192
- this.existsfn = this.exists.map(function (ex) {
15193
- var nq = ex.compile(databaseid);
14516
+ this.existsfn = this.exists.map(ex => {
14517
+ let nq = ex.compile(databaseid);
15194
14518
  if (nq.query && !nq.query.modifier) nq.query.modifier = 'RECORDSET';
15195
14519
  return nq;
15196
- // return ex.compile(databaseid);
15197
- // TODO Include modifier
15198
14520
  });
15199
14521
  }
15200
14522
  if (this.queries) {
15201
- this.queriesfn = this.queries.map(function (q) {
15202
- var nq = q.compile(databaseid);
14523
+ this.queriesfn = this.queries.map(q => {
14524
+ let nq = q.compile(databaseid);
15203
14525
  if (nq.query && !nq.query.modifier) nq.query.modifier = 'RECORDSET';
15204
14526
  return nq;
15205
- // TODO Include modifier
15206
14527
  });
15207
14528
  }
15208
14529
 
15209
- var res = new Function(
15210
- 'params,alasql',
14530
+ let res = new Function(
14531
+ 'params, alasql',
15211
14532
  'return ' + this.expression.toJS('({})', '', null)
15212
14533
  ).bind(this)(params, alasql);
14534
+
15213
14535
  if (alasql.declares[this.variable]) {
15214
14536
  res = alasql.stdfn.CONVERT(res, alasql.declares[this.variable]);
15215
14537
  }
14538
+
15216
14539
  if (this.props && this.props.length > 0) {
15217
- if (this.method == '@') {
15218
- var fs = "alasql.vars['" + this.variable + "']";
14540
+ let fs;
14541
+ if (this.method === '@') {
14542
+ fs = `alasql.vars['${this.variable}']`;
15219
14543
  } 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();
14544
+ fs = `params['${this.variable}']`;
14545
+ }
14546
+ this.props.forEach(prop => {
14547
+ if (typeof prop === 'string') {
14548
+ fs += `['${prop}']`;
14549
+ } else if (typeof prop === 'number') {
14550
+ fs += `[${prop}]`;
14551
+ } else {
14552
+ // Assuming prop.toJS() is a method that converts prop to a JavaScript expression.
14553
+ fs += `[${prop.toJS()}]`;
14554
+ }
14555
+ });
15237
14556
 
15238
- new Function('value,params,alasql', 'var y;' + fs + '=value')(res, params, alasql);
14557
+ new Function('value, params, alasql', `${fs} = value`)(res, params, alasql);
15239
14558
  } else {
15240
- if (this.method == '@') {
14559
+ if (this.method === '@') {
15241
14560
  alasql.vars[this.variable] = res;
15242
14561
  } else {
15243
14562
  params[this.variable] = res;
15244
14563
  }
15245
14564
  }
15246
14565
  }
15247
- var res = 1;
15248
- if (cb) res = cb(res);
15249
- return res;
14566
+
14567
+ let result = 1;
14568
+ if (cb) result = cb(result);
14569
+ return result;
15250
14570
  };
15251
14571
  alasql.test = function (name, times, fn) {
15252
14572
  if (arguments.length === 0) {
@@ -15568,7 +14888,7 @@ yy.BeginTransaction.prototype.execute = function (databaseid, params, cb) {
15568
14888
  } else {
15569
14889
  // alasql commit!!!
15570
14890
  }
15571
- if (cb) cb(res);
14891
+ if (cb) res = cb(res);
15572
14892
  return res;
15573
14893
  };
15574
14894
 
@@ -15586,7 +14906,7 @@ yy.CommitTransaction.prototype.execute = function (databaseid, params, cb) {
15586
14906
  } else {
15587
14907
  // alasql commit!!!
15588
14908
  }
15589
- if (cb) cb(res);
14909
+ if (cb) res = cb(res);
15590
14910
  return res;
15591
14911
  };
15592
14912
 
@@ -15604,7 +14924,7 @@ yy.RollbackTransaction.prototype.execute = function (databaseid, params, cb) {
15604
14924
  } else {
15605
14925
  // alasql commit!!!
15606
14926
  }
15607
- if (cb) cb(res);
14927
+ if (cb) res = cb(res);
15608
14928
  return res;
15609
14929
  };
15610
14930
  if (alasql.options.tsql) {
@@ -16820,9 +16140,8 @@ alasql.into.XLSX = function (filename, opts, data, columns, cb) {
16820
16140
 
16821
16141
  alasql.from.METEOR = function (filename, opts, cb, idx, query) {
16822
16142
  var res = filename.find(opts).fetch();
16823
- if (cb) {
16824
- res = cb(res, idx, query);
16825
- }
16143
+ if (cb) res = cb(res, idx, query);
16144
+
16826
16145
  return res;
16827
16146
  };
16828
16147
 
@@ -16836,9 +16155,7 @@ alasql.from.TABLETOP = function (key, opts, cb, idx, query) {
16836
16155
  alasql.utils.extend(opt, opts);
16837
16156
  opt.callback = function (data) {
16838
16157
  res = data;
16839
- if (cb) {
16840
- res = cb(res, idx, query);
16841
- }
16158
+ if (cb) res = cb(res, idx, query);
16842
16159
  };
16843
16160
 
16844
16161
  Tabletop.init(opt);
@@ -16917,11 +16234,8 @@ alasql.from.FILE = function (filename, opts, cb, idx, query) {
16917
16234
  }
16918
16235
 
16919
16236
  var parts = fname.split('.');
16920
-
16921
16237
  var ext = parts[parts.length - 1].toUpperCase();
16922
-
16923
16238
  if (alasql.from[ext]) {
16924
-
16925
16239
  return alasql.from[ext](filename, opts, cb, idx, query);
16926
16240
  } else {
16927
16241
  throw new Error('Cannot recognize file type for loading');
@@ -17547,14 +16861,11 @@ yy.Source.prototype.toString = function () {
17547
16861
 
17548
16862
  // SOURCE FILE
17549
16863
  yy.Source.prototype.execute = function (databaseid, params, cb) {
17550
-
17551
16864
  var res;
17552
16865
  loadFile(
17553
16866
  this.url,
17554
16867
  !!cb,
17555
16868
  function (data) {
17556
-
17557
- // res = 1;
17558
16869
  res = alasql(data);
17559
16870
  if (cb) res = cb(res);
17560
16871
  return res;
@@ -17604,15 +16915,12 @@ yy.Require.prototype.execute = function (databaseid, params, cb) {
17604
16915
  var self = this;
17605
16916
  var res = 0;
17606
16917
  var ss = '';
17607
-
17608
16918
  if (this.paths && this.paths.length > 0) {
17609
16919
  this.paths.forEach(function (path) {
17610
16920
  loadFile(path.value, !!cb, function (data) {
17611
16921
  res++;
17612
-
17613
16922
  ss += data;
17614
16923
  if (res < self.paths.length) return;
17615
-
17616
16924
  new Function('params,alasql', ss)(params, alasql);
17617
16925
  if (cb) res = cb(res);
17618
16926
  });
@@ -17626,7 +16934,6 @@ yy.Require.prototype.execute = function (databaseid, params, cb) {
17626
16934
  res++;
17627
16935
  ss += data;
17628
16936
  if (res < self.plugins.length) return;
17629
-
17630
16937
  new Function('params,alasql', ss)(params, alasql);
17631
16938
  alasql.plugins[plugin] = true; // Plugin is loaded
17632
16939
  if (cb) res = cb(res);
@@ -17657,11 +16964,7 @@ yy.Source.prototype.toString = function () {
17657
16964
 
17658
16965
  // SOURCE FILE
17659
16966
  yy.Assert.prototype.execute = function (databaseid) {
17660
-
17661
16967
  if (!deepEqual(alasql.res, this.value)) {
17662
- // if(this.message) {
17663
- // throw this.
17664
- // } else {
17665
16968
  throw new Error(
17666
16969
  (this.message || 'Assert wrong') +
17667
16970
  ': ' +
@@ -17669,7 +16972,6 @@ yy.Assert.prototype.execute = function (databaseid) {
17669
16972
  ' == ' +
17670
16973
  JSON.stringify(this.value)
17671
16974
  );
17672
- // }
17673
16975
  }
17674
16976
  return 1;
17675
16977
  };
@@ -18211,7 +17513,6 @@ LS.attachDatabase = function (lsdbid, databaseid, args, params, cb) {
18211
17513
  if (db.tables) {
18212
17514
  for (var tbid in db.tables) {
18213
17515
  LS.restoreTable(databaseid, tbid);
18214
- // db.tables[tbid].data = LS.get(db.lsdbid+'.'+tbid);
18215
17516
  }
18216
17517
  }
18217
17518
  }
@@ -18387,9 +17688,7 @@ LS.intoTable = function (databaseid, tableid, value, columns, cb) {
18387
17688
  }
18388
17689
  if (!tb.data) tb.data = [];
18389
17690
  tb.data = tb.data.concat(value);
18390
- // LS.set(lsdbid+'.'+tableid, tb);
18391
17691
  LS.storeTable(databaseid, tableid);
18392
-
18393
17692
  if (cb) res = cb(res);
18394
17693
 
18395
17694
  return res;
@@ -18529,7 +17828,6 @@ SQLITE.attachDatabase = function (sqldbid, dbid, args, params, cb) {
18529
17828
  db.tables[tbl[1]] = {};
18530
17829
  var columns = (db.tables[tbl[1]].columns = []);
18531
17830
  var ast = alasql.parse(tbl[4]);
18532
-
18533
17831
  var coldefs = ast.statements[0].columns;
18534
17832
  if (coldefs && coldefs.length > 0) {
18535
17833
  coldefs.forEach(function (cd) {
@@ -18606,12 +17904,9 @@ SQLITE.intoTable = function (databaseid, tableid, value, columns, cb) {
18606
17904
  var FS = (alasql.engines.FILESTORAGE = alasql.engines.FILE = function () {});
18607
17905
 
18608
17906
  FS.createDatabase = function (fsdbid, args, ifnotexists, dbid, cb) {
18609
-
18610
17907
  var res = 1;
18611
17908
  var filename = args[0].value;
18612
-
18613
17909
  alasql.utils.fileExists(filename, function (fex) {
18614
-
18615
17910
  if (fex) {
18616
17911
  if (ifnotexists) {
18617
17912
  res = 0;
@@ -18672,14 +17967,12 @@ FS.dropDatabase = function (fsdbid, ifexists, cb) {
18672
17967
  };
18673
17968
 
18674
17969
  FS.attachDatabase = function (fsdbid, dbid, args, params, cb) {
18675
-
18676
17970
  var res = 1;
18677
17971
  if (alasql.databases[dbid]) {
18678
17972
  throw new Error('Unable to attach database as "' + dbid + '" because it already exists');
18679
17973
  }
18680
17974
  var db = new alasql.Database(dbid || fsdbid);
18681
17975
  db.engineid = 'FILESTORAGE';
18682
- // db.fsdbid = fsdbid;
18683
17976
  db.filename = args[0].value;
18684
17977
  loadFile(db.filename, !!cb, function (s) {
18685
17978
  try {
@@ -18720,7 +18013,6 @@ FS.createTable = function (databaseid, tableid, ifnotexists, cb) {
18720
18013
  };
18721
18014
 
18722
18015
  FS.updateFile = function (databaseid) {
18723
-
18724
18016
  var db = alasql.databases[databaseid];
18725
18017
  if (db.issaving) {
18726
18018
  db.postsave = true;
@@ -18756,7 +18048,6 @@ FS.dropTable = function (databaseid, tableid, ifexists, cb) {
18756
18048
  };
18757
18049
 
18758
18050
  FS.fromTable = function (databaseid, tableid, cb, idx, query) {
18759
-
18760
18051
  var db = alasql.databases[databaseid];
18761
18052
  var res = db.data[tableid];
18762
18053
  if (cb) res = cb(res, idx, query);
@@ -18787,7 +18078,6 @@ FS.saveTableData = function (databaseid, tableid) {
18787
18078
  };
18788
18079
 
18789
18080
  FS.commit = function (databaseid, cb) {
18790
-
18791
18081
  var db = alasql.databases[databaseid];
18792
18082
  var fsdb = {tables: {}};
18793
18083
  if (db.tables) {
@@ -18806,9 +18096,6 @@ FS.rollback = function (databaseid, cb) {
18806
18096
  var res = 1;
18807
18097
  var db = alasql.databases[databaseid];
18808
18098
  db.dbversion++;
18809
-
18810
- // var lsdbid = alasql.databases[databaseid].lsdbid;
18811
- // lsdb = LS.get(lsdbid);
18812
18099
  wait();
18813
18100
  function wait() {
18814
18101
  setTimeout(function () {
@@ -18826,9 +18113,6 @@ FS.rollback = function (databaseid, cb) {
18826
18113
  db.tables[tbid].data = db.data[tbid];
18827
18114
  }
18828
18115
  db.tables[tbid].indexColumns();
18829
-
18830
- // index columns
18831
- // convert types
18832
18116
  }
18833
18117
 
18834
18118
  delete alasql.databases[databaseid];
@@ -18843,9 +18127,6 @@ FS.rollback = function (databaseid, cb) {
18843
18127
  }
18844
18128
  }, 100);
18845
18129
  }
18846
-
18847
- // if(!alasql.options.autocommit) {
18848
-
18849
18130
  };
18850
18131
  if(utils.isBrowser && !utils.isWebWorker) {
18851
18132
  alasql = alasql || false;