-
Notifications
You must be signed in to change notification settings - Fork 692
Expand file tree
/
Copy path424select.js
More file actions
executable file
·815 lines (760 loc) · 24.6 KB
/
424select.js
File metadata and controls
executable file
·815 lines (760 loc) · 24.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
/*
//
// Select compiler part for Alasql.js
// Date: 03.11.2014
// (c) 2014, Andrey Gershun
//
*/
// yy.Select.prototype.compileSources = function(query) {
// return sources;
// };
// Regular expression to match aggregate functions that require expression compilation
var re_aggrWithExpression = /^(SUM|MAX|MIN|FIRST|LAST|AVG|ARRAY|REDUCE|TOTAL)$/;
function compileSelectStar(query, aliases, joinstar) {
var sp = '',
ss = [],
columnIds = {};
aliases.forEach(function (alias) {
// console.log(query.aliases[alias]);
// console.log(query,alias);
// console.log(query.aliases[alias].tableid);
// console.log(42,631,alias);
// console.log(query.aliases);
// if(!alias) {
// sp += 'for(var k1 in p) var w=p[k1];for(var k2 in w){r[k2]=w[k2]};';
// } else {
// TODO move this out of this function
query.ixsources = {};
query.sources.forEach(function (source) {
query.ixsources[source.alias] = source;
});
// Fixed
var columns;
if (query.ixsources[alias]) {
var columns = query.ixsources[alias].columns;
}
// if(columns.length == 0 && query.aliases[alias].tableid) {
// var columns = alasql.databases[query.aliases[alias].databaseid].tables[query.aliases[alias].tableid].columns;
// };
// Check if this is a Table or other
if (joinstar && alasql.options.joinstar == 'json') {
sp += "r['" + alias + "']={};";
}
if (columns && columns.length > 0) {
columns.forEach(function (tcol) {
const escapedColumnId = escapeq(tcol.columnid);
if (joinstar && alasql.options.joinstar == 'underscore') {
ss.push(
"'" + alias + '_' + escapedColumnId + "':p['" + alias + "']['" + escapedColumnId + "']"
);
} else if (joinstar && alasql.options.joinstar == 'json') {
// ss.push('\''+alias+'_'+tcol.columnid+'\':p[\''+alias+'\'][\''+tcol.columnid+'\']');
sp +=
"r['" +
alias +
"']['" +
escapedColumnId +
"']=p['" +
alias +
"']['" +
escapedColumnId +
"'];";
} else {
var value = "p['" + alias + "']['" + escapedColumnId + "']";
if (!columnIds[tcol.columnid]) {
var key = "'" + escapedColumnId + "':";
ss.push(key + value);
columnIds[tcol.columnid] = {
id: ss.length - 1,
value: value,
key: key,
};
} else {
var newValue =
value + ' !== undefined ? ' + value + ' : ' + columnIds[tcol.columnid].value;
ss[columnIds[tcol.columnid].id] = columnIds[tcol.columnid].key + newValue;
columnIds[tcol.columnid].value = newValue;
}
}
query.selectColumns[escapedColumnId] = true;
// console.log('ok',tcol);
var coldef = {
columnid: tcol.columnid,
dbtypeid: tcol.dbtypeid,
dbsize: tcol.dbsize,
dbprecision: tcol.dbprecision,
dbenum: tcol.dbenum,
};
query.columns.push(coldef);
query.xcolumns[coldef.columnid] = coldef;
});
//console.log(999,columns);
} else {
// console.log(60,alias,columns);
// If columns are not known (e.g., with inline data using ? placeholders),
// copy all properties dynamically respecting the joinstar option:
// - 'json': Nested objects by alias (e.g., {a: {col: val}, b: {col: val}})
// - 'underscore': Prefix columns with alias (e.g., {a_col: val, b_col: val})
// - 'overwrite': Later columns overwrite earlier ones (default)
if (joinstar && alasql.options.joinstar == 'json') {
// For json mode, create nested object with alias as key
sp += "r['" + escapeq(alias) + "']=p['" + escapeq(alias) + "'];";
} else if (joinstar && alasql.options.joinstar == 'underscore') {
// For underscore mode, prefix each key with alias_
sp +=
'var w=p["' + escapeq(alias) + '"];for(var k in w){r["' + escapeq(alias) + '_"+k]=w[k]};';
} else {
// Default overwrite mode
sp += 'var w=p["' + escapeq(alias) + '"];for(var k in w){r[k]=w[k]};';
}
//console.log(777, sp);
query.dirtyColumns = true;
}
// }
//console.log(87,{s:ss.join(','),sp:sp});
});
return {s: ss.join(','), sp: sp};
}
// Helper function to check if an expression is an arrow operation and extract its path
// Returns null if not an arrow op, or an array of path parts if it is
function getArrowPath(expr) {
if (!expr || expr.op !== '->') {
return null;
}
var path = [];
var current = expr;
while (current && current.op === '->') {
// The right side is the property name
if (typeof current.right === 'string') {
path.unshift(current.right);
} else if (typeof current.right === 'number') {
path.unshift(current.right);
} else {
// Complex expression on right side, can't extract path
return null;
}
current = current.left;
}
// The leftmost should be a column
if (current && current.columnid) {
path.unshift(current.columnid);
return path;
}
return null;
}
yy.Select.prototype.compileSelect1 = function (query, params) {
var self = this;
query.columns = [];
query.xcolumns = {};
query.selectColumns = {};
query.dirtyColumns = false;
var s = 'var r={';
var sp = '';
var ss = [];
//console.log(42,87,this.columns);
this.columns.forEach(function (col) {
if (col instanceof yy.Column) {
if (col.columnid === '*') {
if (col.func) {
sp +=
"r=params['" + col.param + "'](p['" + query.sources[0].alias + "'],p,params,alasql);";
} else if (col.tableid) {
//Copy all
var ret = compileSelectStar(query, [col.tableid], false);
if (ret.s) {
ss = ss.concat(ret.s);
}
sp += ret.sp;
} else {
// console.log('aliases', query.aliases);
var ret = compileSelectStar(query, Object.keys(query.aliases), true); //query.aliases[alias].tableid);
if (ret.s) {
ss = ss.concat(ret.s);
}
sp += ret.sp;
// TODO Remove these lines
// In case of no information
// sp += 'for(var k1 in p){var w=p[k1];'+
// 'for(k2 in w) {r[k2]=w[k2]}}'
}
} else {
// If field, otherwise - expression
var tbid = col.tableid;
// console.log(query.sources);
var dbid = col.databaseid || query.sources[0].databaseid || query.database.databaseid;
if (!tbid) tbid = query.defcols[col.columnid];
if (!tbid) tbid = query.defaultTableid;
if (col.columnid !== '_') {
if (false && tbid && !query.defcols['.'][col.tableid] && !query.defcols[col.columnid]) {
ss.push(
"'" +
escapeq(col.as || col.columnid) +
"':p['" +
query.defaultTableid +
"']['" +
col.tableid +
"']['" +
col.columnid +
"']"
);
} else {
// workaround for multisheet xlsx export with custom COLUMNS
var isMultisheetParam =
params &&
params.length > 1 &&
Array.isArray(params[0]) &&
params[0].length >= 1 &&
params[0][0].hasOwnProperty('sheetid');
if (isMultisheetParam) {
sp =
'var r={};var w=p["' +
tbid +
'"];' +
'var cols=[' +
self.columns
.map(function (col) {
return "'" + col.columnid + "'";
})
.join(',') +
'];var colas=[' +
self.columns
.map(function (col) {
return "'" + (col.as || col.columnid) + "'";
})
.join(',') +
'];' +
"for (var i=0;i<Object.keys(p['" +
tbid +
"']).length;i++)" +
' for(var k=0;k<cols.length;k++){if (!r.hasOwnProperty(i)) r[i]={}; r[i][colas[k]]=w[i][cols[k]];}';
} else {
// For JOINs with inline data where column table is unknown, search all tables
var needsRuntimeResolution =
!col.tableid &&
query.sources.length > 1 &&
(!query.defcols[col.columnid] || query.defcols[col.columnid] === '-');
if (needsRuntimeResolution) {
// Try each table until column is found
var aliases = Object.keys(query.aliases);
var searchExpr = aliases
.map(function (alias) {
return "p['" + alias + "']['" + col.columnid + "']";
})
.join(' ?? ');
ss.push("'" + escapeq(col.as || col.columnid) + "':(" + searchExpr + ')');
} else {
ss.push(
"'" +
escapeq(col.as || col.columnid) +
"':p['" +
tbid +
"']['" +
col.columnid +
"']"
);
}
}
}
} else {
ss.push("'" + escapeq(col.as || col.columnid) + "':p['" + tbid + "']");
}
query.selectColumns[escapeq(col.as || col.columnid)] = true;
if (query.aliases[tbid] && query.aliases[tbid].type === 'table') {
if (!alasql.databases[dbid].tables[query.aliases[tbid].tableid]) {
// console.log(query.database,tbid,query.aliases[tbid].tableid);
throw new Error("Table '" + tbid + "' does not exist in database");
}
var columns = alasql.databases[dbid].tables[query.aliases[tbid].tableid].columns;
var xcolumns = alasql.databases[dbid].tables[query.aliases[tbid].tableid].xcolumns;
//console.log(xcolumns, col,123);
// console.log(0);
if (xcolumns && columns.length > 0) {
// console.log(1);
var tcol = xcolumns[col.columnid];
if (undefined === tcol) {
throw new Error('Column does not exist: ' + col.columnid);
}
var coldef = {
columnid: col.as || col.columnid,
dbtypeid: tcol.dbtypeid,
dbsize: tcol.dbsize,
dbpecision: tcol.dbprecision,
dbenum: tcol.dbenum,
};
// console.log(2);
query.columns.push(coldef);
query.xcolumns[coldef.columnid] = coldef;
} else {
var coldef = {
columnid: col.as || col.columnid,
// dbtypeid:tcol.dbtypeid,
// dbsize:tcol.dbsize,
// dbpecision:tcol.dbprecision,
// dbenum: tcol.dbenum,
};
// console.log(2);
query.columns.push(coldef);
query.xcolumns[coldef.columnid] = coldef;
query.dirtyColumns = true;
}
} else {
var coldef = {
columnid: col.as || col.columnid,
// dbtypeid:tcol.dbtypeid,
// dbsize:tcol.dbsize,
// dbpecision:tcol.dbprecision,
// dbenum: tcol.dbenum,
};
// console.log(2);
query.columns.push(coldef);
query.xcolumns[coldef.columnid] = coldef;
// This is a subquery?
// throw new Error('There is now such table \''+col.tableid+'\'');
}
}
} else if (col instanceof yy.AggrValue) {
// Set alias if not provided
if (!col.as) col.as = escapeq(col.toString());
// Check if this aggregate has an OVER clause (window function)
if (col.over) {
// Track window aggregate for post-processing
query.windowaggrs.push({
as: col.as,
aggregatorid: col.aggregatorid,
expression: col.expression,
partitionColumns: col.over.partition
? col.over.partition.map(function (p) {
return p.columnid || p.toString();
})
: [],
});
} else {
// Regular aggregate - trigger GROUP BY
if (!self.group) self.group = [''];
if (re_aggrWithExpression.test(col.aggregatorid)) {
ss.push(
"'" +
escapeq(col.as) +
"':" +
n2u(col.expression.toJS('p', query.defaultTableid, query.defcols))
);
} else if (col.aggregatorid === 'COUNT') {
ss.push("'" + escapeq(col.as) + "':1");
}
}
// Add column definition for both window and regular aggregates
var coldef = {
columnid: col.as || col.columnid || col.toString(),
};
query.columns.push(coldef);
query.xcolumns[coldef.columnid] = coldef;
} else {
// console.log(203,col.as,col.columnid,col.toString());
// Check if this is an arrow expression and we're outputting to OBJECT
var arrowPath = query.intoObject && !col.as ? getArrowPath(col) : null;
if (arrowPath && arrowPath.length > 1) {
// For arrow expressions in INTO OBJECT(), generate nested object assignment
// This will be added to sp (post-processing) instead of ss (inline object)
var valueJs = n2u(col.toJS('p', query.defaultTableid, query.defcols));
// Generate code to create nested structure
// e.g., for path ['details', 'stock']: r['details'] = r['details'] || {}; r['details']['stock'] = value;
for (var i = 0; i < arrowPath.length - 1; i++) {
var pathSoFar = arrowPath.slice(0, i + 1);
var accessor = pathSoFar
.map(function (p) {
return "['" + escapeq(p) + "']";
})
.join('');
sp += 'r' + accessor + ' = r' + accessor + ' || {};';
}
var fullAccessor = arrowPath
.map(function (p) {
return "['" + escapeq(p) + "']";
})
.join('');
sp += 'r' + fullAccessor + ' = ' + valueJs + ';';
// Use the first part of the path as the column name for metadata
var colName = arrowPath[0];
query.selectColumns[escapeq(colName)] = true;
var coldef = {
columnid: colName,
};
// Only add if not already added
if (!query.xcolumns[coldef.columnid]) {
query.columns.push(coldef);
query.xcolumns[coldef.columnid] = coldef;
}
} else {
ss.push(
"'" +
escapeq(col.as || col.columnid || col.toString()) +
"':" +
n2u(col.toJS('p', query.defaultTableid, query.defcols))
);
// ss.push('\''+escapeq(col.toString())+'\':'+col.toJS("p",query.defaultTableid));
//if(col instanceof yy.Expression) {
query.selectColumns[escapeq(col.as || col.columnid || col.toString())] = true;
var coldef = {
columnid: col.as || col.columnid || col.toString(),
// dbtypeid:tcol.dbtypeid,
// dbsize:tcol.dbsize,
// dbpecision:tcol.dbprecision,
// dbenum: tcol.dbenum,
};
// console.log(2);
query.columns.push(coldef);
query.xcolumns[coldef.columnid] = coldef;
}
}
});
s += ss.join(',') + '};' + sp;
return s;
//console.log(42,753,query.xcolumns, query.selectColumns);
};
yy.Select.prototype.compileSelect2 = function (query, params) {
var s = query.selectfns;
// Only add order keys if there's no union operation (otherwise they'll be added later)
if (
this.orderColumns &&
this.orderColumns.length > 0 &&
!this.union &&
!this.unionall &&
!this.except &&
!this.intersect
) {
this.orderColumns.forEach(function (v, idx) {
var key = '$$$' + idx;
// Handle positional column reference (for SELECT * with ORDER BY numeric)
if (v._useColumnIndex !== undefined) {
// Use Object.keys to get column names and access by index
s += "var keys=Object.keys(r);r['" + key + "']=r[keys[" + v.columnIndex + ']];';
} else if (v instanceof yy.Column && query.xcolumns[v.columnid]) {
s += "r['" + key + "']=r['" + v.columnid + "'];";
} else if (v instanceof yy.ParamValue && query.xcolumns[params[v.param]]) {
s += "r['" + key + "']=r['" + params[v.param] + "'];";
} else {
s += "r['" + key + "']=" + v.toJS('p', query.defaultTableid, query.defcols) + ';';
}
query.removeKeys.push(key);
});
}
return new Function('p,params,alasql', 'var y;' + s + 'return r');
};
yy.Select.prototype.compileSelectGroup0 = function (query) {
var self = this;
// Optimization: Build lookup structures upfront to avoid O(n*m) complexity in the main loop
// Only build these if GROUP BY exists, as they're only used for alias resolution
var groupByAliasMap = null;
var selectColumnNames = null;
if (self.group) {
// Build map of GROUP BY columns that reference aliases (for O(1) lookup)
groupByAliasMap = {};
self.group.forEach(function (gp, idx) {
if (gp instanceof yy.Column && gp.columnid && !gp.tableid) {
groupByAliasMap[gp.columnid] = idx;
}
});
// Build set of actual column names in SELECT to distinguish pure aliases from column renames
// This prevents incorrect replacement of "GROUP BY b" when "SELECT a AS b, b AS c" exists
selectColumnNames = {};
self.columns.forEach(function (col) {
if (col instanceof yy.Column && col.columnid) {
selectColumnNames[col.columnid] = true;
}
});
}
self.columns.forEach(function (col, idx) {
if (!(col instanceof yy.Column && col.columnid === '*')) {
var colas;
// = col.as;
if (col instanceof yy.Column) {
colas = escapeq(col.columnid);
} else {
colas = escapeq(col.toString(true));
// console.log(273,colas);
}
for (var i = 0; i < idx; i++) {
if (colas === self.columns[i].nick) {
colas = self.columns[i].nick + ':' + idx;
break;
}
}
// }
col.nick = colas;
if (self.group) {
// Match GROUP BY columns to SELECT columns by columnid and tableid (for real columns)
var groupIdx = self.group.findIndex(function (gp) {
return gp.columnid === col.columnid && gp.tableid === col.tableid;
});
if (groupIdx > -1) {
self.group[groupIdx].nick = colas;
}
// Also match GROUP BY columns that reference SELECT column aliases
// This handles cases like: SELECT CASE ... END AS age_group ... GROUP BY age_group
// Only apply if:
// 1. The SELECT column has an alias
// 2. That alias matches a GROUP BY column name
// 3. The alias is NOT an actual column name (pure alias, not renaming)
if (
col.as &&
groupByAliasMap &&
groupByAliasMap.hasOwnProperty(col.as) &&
!selectColumnNames[col.as]
) {
var aliasGroupIdx = groupByAliasMap[col.as];
// Replace the GROUP BY column reference with a deep copy of the SELECT expression
// We use deep cloning to ensure nested objects (like CASE whens/elses) are copied
var groupExpr = cloneDeep(col);
// Clear SELECT-specific properties that shouldn't be in GROUP BY
delete groupExpr.as;
groupExpr.nick = colas;
self.group[aliasGroupIdx] = groupExpr;
}
}
if (
col.funcid &&
(col.funcid.toUpperCase() === 'ROWNUM' || col.funcid.toUpperCase() === 'ROW_NUMBER')
) {
// Check if this has OVER clause with PARTITION BY
if (col.over && col.over.partition) {
// Window function with partition - track for post-processing
query.grouprownums.push({
as: col.as,
partitionColumns: col.over.partition.map(function (p) {
return p.columnid || p.toString();
}),
});
} else {
// Regular ROW_NUMBER without partition
query.rownums.push(col.as);
}
}
if (col.funcid && col.funcid.toUpperCase() === 'GROUP_ROW_NUMBER') {
query.grouprownums.push({as: col.as, columnIndex: 0}); // Track which column to use for grouping
}
// Detect positional window functions: LEAD, LAG, FIRST_VALUE, LAST_VALUE
if (col.funcid) {
var fid = col.funcid.toUpperCase();
if (
fid === 'LEAD' ||
fid === 'LAG' ||
fid === 'FIRST_VALUE' ||
fid === 'LAST_VALUE'
) {
var wfConfig = {
funcid: fid,
as: col.as,
expressionColumnId:
col.args && col.args[0] ? col.args[0].columnid : null,
offset:
col.args && col.args[1] ? col.args[1].value : 1,
defaultValue:
col.args && col.args[2]
? col.args[2].value != null
? col.args[2].value
: col.args[2].op === '-' && col.args[2].right
? -col.args[2].right.value
: null
: null,
partitionColumns:
col.over && col.over.partition
? col.over.partition.map(function (p) {
return p.columnid || p.toString();
})
: [],
orderColumns:
col.over && col.over.order
? col.over.order.map(function (o) {
return {
columnid:
o.expression && o.expression.columnid
? o.expression.columnid
: o.columnid || o.toString(),
direction: o.direction || 'ASC',
};
})
: [],
};
query.windowfns.push(wfConfig);
}
}
// console.log("colas:",colas);
// }
} else {
query.groupStar = col.tableid || 'default';
}
});
this.columns.forEach(function (col) {
if (col.findAggregator) {
col.findAggregator(query);
}
});
if (this.having) {
if (this.having.findAggregator) {
this.having.findAggregator(query);
}
}
};
yy.Select.prototype.compileSelectGroup1 = function (query) {
var self = this;
var s = 'var r = {};';
self.columns.forEach(function (col) {
// console.log(col);
if (col instanceof yy.Column && col.columnid === '*') {
// s += 'for(var k in g){r[k]=g[k]};';
// s += 'for(var k in this.query.groupColumns){r[k]=g[this.query.groupColumns[k]]};';
s += 'for(var k in g) {r[k]=g[k]};';
return '';
// console.log(query);
} else {
// var colas = col.as;
var colas = col.as;
if (colas === undefined) {
if (col instanceof yy.Column) {
colas = escapeq(col.columnid);
} else {
colas = col.nick;
}
}
query.groupColumns[colas] = col.nick;
/*/* if(typeof colas == 'undefined') {
if(col instanceof yy.Column) {
colas = col.columnid;
} else {
colas = col.toString();
for(var i=0;i<idx;i++) {
if(colas == self.columns[i].as) {
colas = self.columns[i].as+':'+idx;
break;
}
}
col.as = colas;
}
}
*/
// if(col.as) {
s += "r['" + colas + "']=";
// // } else {
// // s += 'r[\''+escapeq()+'\']=';
// // };
// // s += ';';
// console.log(col);//,col.toJS('g',''));
s += n2u(col.toJS('g', '')) + ';';
/*/*
s += 'g[\''+col.nick+'\'];';
* /
// if(col instanceof yy.Column) {
// s += 'g[\''+col.columnid+'\'];';
// } else {
// s += 'g[\''+col.toString()+'\'];';
// console.log(col);
// var kg = col.toJS('g','')+';';
// for(var i=0;i<query.removeKeys.length;i++) {
// // THis part should be intellectual
// if(query.removeKeys[i] == colas) {
// s += 'g[\''+colas+'\'];';
// break;
// }
// };
// s += kg;
// console.log(s);
// }
// s += col.toJS('g','')+';';
*/
//console.log(colas,query.removeKeys);
for (var i = 0; i < query.removeKeys.length; i++) {
// THis part should be intellectual
if (query.removeKeys[i] === colas) {
query.removeKeys.splice(i, 1);
break;
}
}
}
});
// return new Function('g,params,alasql',s+'return r');
return s;
};
yy.Select.prototype.compileSelectGroup2 = function (query) {
var self = this;
var s = query.selectgfns;
// Create a lookup map for GROUP BY columns to optimize performance
var groupColMap = {};
if (self.group) {
self.group.forEach(function (gp) {
var key = (gp.tableid || '') + '\t' + gp.columnid;
groupColMap[key] = gp;
});
}
self.columns.forEach(function (col) {
// console.log(col);
// Skip SELECT * columns as they are handled differently
if (col instanceof yy.Column && col.columnid === '*') {
return;
}
// Check if this column is part of GROUP BY
// For columns with renamed nicks (e.g., 'x:1'), we need to check the original columnid
var groupCol = null;
if (col instanceof yy.Column && self.group) {
var key = (col.tableid || '') + '\t' + col.columnid;
groupCol = groupColMap[key];
}
var isInGroup = groupCol !== null || query.ingroup.indexOf(col.nick) > -1;
if (isInGroup) {
// For columns in GROUP BY, use the GROUP BY column's nick if available
var groupNick = (groupCol && groupCol.nick) || col.nick;
s += "r['" + (col.as || col.nick) + "']=g['" + groupNick + "'];";
}
});
// Only add order keys if there's no union operation (otherwise they'll be added later)
if (
this.orderColumns &&
this.orderColumns.length > 0 &&
!this.union &&
!this.unionall &&
!this.except &&
!this.intersect
) {
this.orderColumns.forEach(function (v, idx) {
// console.log(411,v);
var key = '$$$' + idx;
// console.log(427,v,query.groupColumns,query.xgroupColumns);
// Handle positional column reference (for SELECT * with ORDER BY numeric)
if (v._useColumnIndex !== undefined) {
// Use Object.keys to get column names and access by index
s += "var keys=Object.keys(r);r['" + key + "']=r[keys[" + v.columnIndex + ']];';
} else if (v instanceof yy.Column && query.groupColumns[v.columnid]) {
s += "r['" + key + "']=r['" + v.columnid + "'];";
} else {
s += "r['" + key + "']=" + v.toJS('g', '') + ';';
}
query.removeKeys.push(key);
});
}
//console.log(425,s);
// console.log('selectg:',s);
return new Function('g,params,alasql', 'var y;' + s + 'return r');
};
// SELECY * REMOVE [COLUMNS] col-list, LIKE ''
yy.Select.prototype.compileRemoveColumns = function (query) {
var self = this;
if (typeof this.removecolumns !== 'undefined') {
query.removeKeys = query.removeKeys.concat(
this.removecolumns
.filter(function (column) {
return typeof column.like === 'undefined';
})
.map(function (column) {
return column.columnid;
})
);
//console.log(query.removeKeys,this.removecolumns);
query.removeLikeKeys = this.removecolumns
.filter(function (column) {
return typeof column.like !== 'undefined';
})
.map(function (column) {
// return new RegExp((column.like.value||'').replace(/\%/g,'.*').replace(/\?|_/g,'.'),'g');
return column.like.value;
});
}
};