-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjoin_enumerator.jsx
More file actions
2380 lines (2063 loc) · 87.2 KB
/
join_enumerator.jsx
File metadata and controls
2380 lines (2063 loc) · 87.2 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
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import React, { useState } from 'react';
/**
* PostgreSQL Join Enumerator with Equivalence Class Support
*
* This tool implements PostgreSQL-style join enumeration for cardinality estimation research.
*
* Key Features:
* - Equivalence Classes (ECs): Groups columns that must be equal (PostgreSQL's approach)
* - Column-Aware Transitive Closure: Only infers transitivity when columns match
* - Dynamic Programming: Enumerates subsets level-by-level using previously enumerated subsets
* - Complete Join Conditions: Generated SQL includes ALL join predicates, not just spanning tree
*
* Algorithm Overview:
* 1. Parse query to extract tables and join predicates
* 2. Build Equivalence Classes from join predicates (Union-Find)
* 3. Compute transitive closure (column-aware)
* 4. Enumerate subsets level-by-level:
* - Check connectivity via ECs
* - Find decomposition using DP table
* - Generate SQL with complete join conditions
*
* See RESEARCH_DOCUMENTATION.md for detailed explanation of algorithms and design decisions.
*/
// Join Graph Class with Equivalence Class Support
class JoinGraph {
constructor() {
this.edges = new Set(); // Still keep for quick connectivity checks
this.joinDetails = new Map(); // table1|||table2 -> [{t1col, t2col}, ...]
this.tableAliases = new Map(); // alias -> base table name
this.equivalenceClasses = []; // Array of Sets, each Set contains "table.column" strings
}
setTableAlias(alias, baseTableName) {
this.tableAliases.set(alias, baseTableName);
}
// Build equivalence classes from join predicates
buildEquivalenceClasses() {
console.log('\n🔍 Building Equivalence Classes...');
// Process each join predicate using Union-Find approach
for (let [edge, details] of this.joinDetails.entries()) {
for (let detail of details) {
const left = `${detail.t1}.${detail.t1col}`;
const right = `${detail.t2}.${detail.t2col}`;
// Find ECs containing these columns
let leftEC = this.equivalenceClasses.find(ec => ec.has(left));
let rightEC = this.equivalenceClasses.find(ec => ec.has(right));
if (leftEC && rightEC && leftEC !== rightEC) {
// Merge two different ECs
for (let member of rightEC) leftEC.add(member);
this.equivalenceClasses = this.equivalenceClasses.filter(ec => ec !== rightEC);
} else if (leftEC) {
leftEC.add(right);
} else if (rightEC) {
rightEC.add(left);
} else {
// Create new EC
this.equivalenceClasses.push(new Set([left, right]));
}
}
}
// Display final ECs
console.log(` Built ${this.equivalenceClasses.length} Equivalence Class(es):`);
for (let i = 0; i < this.equivalenceClasses.length; i++) {
const members = Array.from(this.equivalenceClasses[i]);
const tables = [...new Set(members.map(m => m.split('.')[0]))];
console.log(` EC${i + 1}: {${members.join(', ')}} [${tables.length} tables]`);
}
}
// Check if two tables are in the same equivalence class
areInSameEC(t1, t2) {
for (let ec of this.equivalenceClasses) {
let hasT1 = false;
let hasT2 = false;
for (let member of ec) {
const [table, col] = member.split('.');
if (table === t1) hasT1 = true;
if (table === t2) hasT2 = true;
}
if (hasT1 && hasT2) {
return true;
}
}
return false;
}
addJoin(t1, t2, t1col = null, t2col = null, isOriginal = true) {
const edge = [t1, t2].sort().join('|||');
this.edges.add(edge);
// Track column details with original vs transitive flag
if (t1col && t2col) {
if (!this.joinDetails.has(edge)) {
this.joinDetails.set(edge, []);
}
// Normalize: store in sorted order
const [table1, table2] = [t1, t2].sort();
const detail = table1 === t1
? { t1: table1, t1col, t2: table2, t2col, isOriginal }
: { t1: table1, t1col: t2col, t2: table2, t2col: t1col, isOriginal };
this.joinDetails.get(edge).push(detail);
}
}
// Check if two subsets can be joined
// Returns true if any table from left shares an EC with any table from right
canJoin(left, right) {
for (let l of left) {
for (let r of right) {
if (this.areInSameEC(l, r)) {
return true;
}
}
}
return false;
}
isConnected(subset) {
if (subset.size <= 1) return true;
const subsetArray = Array.from(subset);
// Check EC connectivity with BFS
const visited = new Set([subsetArray[0]]);
const queue = [subsetArray[0]];
while (queue.length > 0) {
const current = queue.shift();
for (let other of subsetArray) {
if (!visited.has(other)) {
// Check if connected via equivalence class
if (this.areInSameEC(current, other)) {
visited.add(other);
queue.push(other);
continue;
}
// Check explicit edge (fallback for non-EC connections)
const edge = [current, other].sort().join('|||');
if (this.edges.has(edge)) {
visited.add(other);
queue.push(other);
}
}
}
}
return visited.size === subset.size;
}
// Helper: Check if two join details can form a transitive join
// Returns the transitive join if columns match on shared table, null otherwise
tryFormTransitiveJoin(d1, d2) {
// Check 4 cases for how two joins might share a table with matching columns
if (d1.t2 === d2.t1 && d1.t2col === d2.t1col) {
return { t1: d1.t1, t1col: d1.t1col, t2: d2.t2, t2col: d2.t2col };
} else if (d1.t2 === d2.t2 && d1.t2col === d2.t2col) {
return { t1: d1.t1, t1col: d1.t1col, t2: d2.t1, t2col: d2.t1col };
} else if (d1.t1 === d2.t1 && d1.t1col === d2.t1col) {
return { t1: d1.t2, t1col: d1.t2col, t2: d2.t2, t2col: d2.t2col };
} else if (d1.t1 === d2.t2 && d1.t1col === d2.t2col) {
return { t1: d1.t2, t1col: d1.t2col, t2: d2.t1, t2col: d2.t1col };
}
return null;
}
// Helper: Check if a join already exists in joinDetails
joinExists(transitiveJoin) {
const edge = [transitiveJoin.t1, transitiveJoin.t2].sort().join('|||');
const existing = this.joinDetails.get(edge);
if (!existing) return false;
return existing.some(e =>
(e.t1 === transitiveJoin.t1 && e.t1col === transitiveJoin.t1col &&
e.t2 === transitiveJoin.t2 && e.t2col === transitiveJoin.t2col) ||
(e.t1 === transitiveJoin.t2 && e.t1col === transitiveJoin.t2col &&
e.t2 === transitiveJoin.t1 && e.t2col === transitiveJoin.t1col)
);
}
// Compute transitive closure with column-aware checking
// Only adds transitive joins when columns match on the shared table
computeTransitiveClosure() {
let addedCount = 0;
const maxIterations = 10;
for (let iteration = 0; iteration < maxIterations; iteration++) {
let foundNew = false;
const currentEdges = Array.from(this.joinDetails.entries());
// Try to find new transitive joins
for (let [edge1Key, details1] of currentEdges) {
for (let [edge2Key, details2] of currentEdges) {
if (edge1Key === edge2Key) continue;
for (let d1 of details1) {
for (let d2 of details2) {
const transitiveJoin = this.tryFormTransitiveJoin(d1, d2);
if (transitiveJoin &&
transitiveJoin.t1 !== transitiveJoin.t2 &&
!this.joinExists(transitiveJoin)) {
this.addJoin(transitiveJoin.t1, transitiveJoin.t2,
transitiveJoin.t1col, transitiveJoin.t2col, false);
addedCount++;
foundNew = true;
}
}
}
}
}
if (!foundNew) break;
}
if (addedCount > 0) {
console.log(` Added ${addedCount} transitive join(s)`);
}
return addedCount;
}
}
// PostgreSQL Join Enumerator Class
class PostgreSQLJoinEnumerator {
constructor(tables, joinGraph) {
this.tables = tables.sort();
this.joinGraph = joinGraph;
this.n = tables.length;
}
enumerateAllValid() {
const allSubplans = [];
const dpTable = new Set(); // DP table: tracks which subsets are enumerable
// Level 1: Base tables
for (let table of this.tables) {
const subset = new Set([table]);
const subsetKey = this.getSubsetKey(subset);
if (!dpTable.has(subsetKey)) {
allSubplans.push({
level: 1,
subset: subset,
left: null,
right: null
});
dpTable.add(subsetKey);
}
}
// Levels 2 through n
for (let level = 2; level <= this.n; level++) {
const levelPlans = this.enumerateLevel(level, dpTable);
allSubplans.push(...levelPlans);
}
return allSubplans;
}
enumerateLevel(level, dpTable) {
const plans = [];
const subsets = this.combinations(this.tables, level);
console.log(`\nLevel ${level}: Checking ${subsets.length} possible subsets`);
let skippedSeen = 0;
let skippedDisconnected = 0;
let skippedNoDecomp = 0;
for (let subsetArray of subsets) {
const subset = new Set(subsetArray);
const subsetKey = this.getSubsetKey(subset);
// Skip if already enumerated
if (dpTable.has(subsetKey)) {
skippedSeen++;
continue;
}
// Skip if not connected via equivalence classes
if (!this.joinGraph.isConnected(subset)) {
skippedDisconnected++;
continue;
}
// Find valid decomposition using previously enumerated subsets
const decomposition = this.findValidDecomposition(subset, dpTable);
if (decomposition) {
plans.push({
level: level,
subset: subset,
left: decomposition.left,
right: decomposition.right
});
dpTable.add(subsetKey);
} else {
skippedNoDecomp++;
}
}
console.log(` Added: ${plans.length}, Skipped: seen=${skippedSeen}, disconnected=${skippedDisconnected}, no_decomp=${skippedNoDecomp}`);
return plans;
}
findValidDecomposition(subset, dpTable) {
// Find a valid way to split subset into left and right
// Both left and right must already be in the DP table
const subsetArray = Array.from(subset);
const level = subsetArray.length;
for (let leftSize = 1; leftSize < level; leftSize++) {
const rightSize = level - leftSize;
// Optimization: skip symmetric decompositions
if (leftSize > rightSize) continue;
for (let leftArray of this.combinations(subsetArray, leftSize)) {
const left = new Set(leftArray);
const right = new Set(subsetArray.filter(t => !left.has(t)));
const leftKey = this.getSubsetKey(left);
const rightKey = this.getSubsetKey(right);
// Both sides must be previously enumerated
if (!dpTable.has(leftKey) || !dpTable.has(rightKey)) {
continue;
}
// Check if left and right can be joined via shared EC
if (this.joinGraph.canJoin(left, right)) {
return { left, right };
}
}
}
return null;
}
getSubsetKey(subset) {
// Create a canonical string representation of the subset
return Array.from(subset).sort().join(',');
}
combinations(array, size) {
const result = [];
const combine = (start, combo) => {
if (combo.length === size) {
result.push([...combo]);
return;
}
for (let i = start; i < array.length; i++) {
combo.push(array[i]);
combine(i + 1, combo);
combo.pop();
}
};
combine(0, []);
return result;
}
countByLevel() {
const allPlans = this.enumerateAllValid();
const counts = {};
for (let plan of allPlans) {
counts[plan.level] = (counts[plan.level] || 0) + 1;
}
return counts;
}
}
// Predicate Classifier
class PredicateClassifier {
constructor(sql) {
this.sql = sql;
this.selectionPredicates = {}; // table -> [predicates]
this.joinPredicates = []; // [{tables: Set, predicate: string, leftTable, leftCol, rightTable, rightCol}]
this.complexPredicates = []; // [{tables: Set, predicate: string}]
this.tableAliases = new Map(); // alias -> full table name
this.multiTableOrPredicates = []; // Track multi-table OR predicates for expansion
}
extractTableFromColumn(column) {
// Extract table alias from "table.column" or "table.column::type"
const match = column.match(/^(\w+)\./);
return match ? match[1] : null;
}
extractTablesFromPredicate(predicate) {
// Find all table references in predicate
const tables = new Set();
const regex = /(\w+)\.\w+/g;
let match;
while ((match = regex.exec(predicate)) !== null) {
tables.add(match[1]);
}
return tables;
}
isEquality(operator) {
return operator === '=' || operator === '==';
}
// Extract individual OR terms from a parenthesized OR predicate
extractOrTerms(orPredicate) {
// Remove outer parens if present
let pred = orPredicate.trim();
if (pred.startsWith('(') && pred.endsWith(')')) {
pred = pred.slice(1, -1).trim();
}
// Split by OR at top level (respecting nested parens)
const terms = [];
let current = '';
let parenDepth = 0;
let inString = false;
let stringChar = null;
for (let i = 0; i < pred.length; i++) {
const char = pred[i];
const remaining = pred.substring(i).toUpperCase();
if (!inString) {
if (char === "'" || char === '"') {
inString = true;
stringChar = char;
current += char;
} else if (char === '(') {
parenDepth++;
current += char;
} else if (char === ')') {
parenDepth--;
current += char;
} else if (parenDepth === 0 && remaining.startsWith('OR ')) {
const prevChar = i > 0 ? pred[i - 1] : ' ';
if (/\s/.test(prevChar) || prevChar === ')') {
terms.push(current.trim());
current = '';
i += 2; // Skip 'OR'
continue;
} else {
current += char;
}
} else {
current += char;
}
} else {
if (char === stringChar && (i === 0 || pred[i - 1] !== '\\')) {
inString = false;
stringChar = null;
}
current += char;
}
}
if (current.trim()) {
terms.push(current.trim());
}
return terms;
}
// Expand a multi-table OR to DNF terms
expandMultiTableOr(orPredicate) {
const terms = this.extractOrTerms(orPredicate);
// Each OR term becomes a separate conjunction
const expansions = [];
for (let term of terms) {
// Check if term itself has nested structure
if (term.includes(' AND ') && !term.includes('(')) {
// Simple case: "A AND B"
expansions.push(term);
} else if (term.includes('(') && term.includes(' AND ')) {
// Nested case: "(A AND B)" - recursively handle
// For now, keep as-is (full DNF expansion is complex)
expansions.push(term);
} else {
// Simple term: just a predicate
expansions.push(term);
}
}
return expansions;
}
classifyPredicates() {
// Extract JOIN ON predicates first
// Pattern: [INNER|LEFT|RIGHT|FULL] [OUTER] JOIN table_name [AS] [alias] ON condition
// Alias is optional - if not provided, table name is used as alias
const joinOnPattern = /(?:INNER|LEFT|RIGHT|FULL|CROSS)?\s*(?:OUTER\s+)?JOIN\s+([\w.]+)(?:\s+(?:AS\s+)?(\w+))?\s+ON\s+(.+?)(?=\s*(?:(?:INNER|LEFT|RIGHT|FULL|CROSS)?\s*(?:OUTER\s+)?JOIN|WHERE|GROUP BY|ORDER BY|LIMIT|$))/gis;
let match;
while ((match = joinOnPattern.exec(this.sql)) !== null) {
const tableName = match[1];
const alias = match[2] || match[1]; // Use table name as alias if not provided
const onClause = match[3].trim();
// Split ON clause by AND (in case multiple conditions)
const onPredicates = this.splitByAnd(onClause);
for (let pred of onPredicates) {
pred = pred.trim();
if (!pred) continue;
const tables = this.extractTablesFromPredicate(pred);
// Check if it's a join predicate (equality between two tables)
const joinMatch = pred.match(/(\w+)\.(\w+)\s*(=|==)\s*(\w+)\.(\w+)/);
if (joinMatch && tables.size === 2) {
// Join predicate from ON clause
const leftTable = joinMatch[1];
const leftCol = joinMatch[2];
const rightTable = joinMatch[4];
const rightCol = joinMatch[5];
this.joinPredicates.push({
tables: new Set([leftTable, rightTable]),
predicate: pred,
leftTable,
leftCol,
rightTable,
rightCol
});
} else if (tables.size === 1) {
// Selection predicate in ON clause (unusual but valid)
const table = Array.from(tables)[0];
if (!this.selectionPredicates[table]) {
this.selectionPredicates[table] = [];
}
this.selectionPredicates[table].push(pred);
} else if (tables.size > 1) {
// Complex predicate in ON clause
this.complexPredicates.push({
tables: tables,
predicate: pred
});
}
}
}
// Extract WHERE clause
const whereMatch = this.sql.match(/WHERE\s+(.*?)(?:GROUP BY|ORDER BY|LIMIT|$)/is);
if (!whereMatch) return;
const whereClause = whereMatch[1].trim();
// Split by AND (respects parentheses and quotes)
const predicates = this.splitByAnd(whereClause);
for (let pred of predicates) {
pred = pred.trim();
if (!pred) continue;
// Check for top-level OR (no surrounding parens) - warn and skip
if (this.hasTopLevelOr(pred)) {
console.warn('Top-level OR predicate detected (not fully supported):', pred);
// Treat as complex predicate for now
const tables = this.extractTablesFromPredicate(pred);
if (tables.size > 0) {
this.complexPredicates.push({
tables: tables,
predicate: pred
});
}
continue;
}
const tables = this.extractTablesFromPredicate(pred);
// Check if it's a join predicate (equality between two tables)
const joinMatch = pred.match(/(\w+)\.(\w+)\s*(=|==)\s*(\w+)\.(\w+)/);
if (joinMatch && tables.size === 2) {
// Join predicate
const leftTable = joinMatch[1];
const leftCol = joinMatch[2];
const rightTable = joinMatch[4];
const rightCol = joinMatch[5];
this.joinPredicates.push({
tables: new Set([leftTable, rightTable]),
predicate: pred,
leftTable,
leftCol,
rightTable,
rightCol
});
} else if (tables.size === 1) {
// Selection predicate - check various patterns
const table = Array.from(tables)[0];
// Patterns we recognize as selection predicates:
// 1. Column = value, Column > value, etc.
// 2. Column LIKE 'pattern'
// 3. Column NOT LIKE 'pattern'
// 4. Column IS NULL
// 5. Column IS NOT NULL
// 6. Column IN (values)
// 7. Column NOT IN (values)
// 8. Parenthesized OR of same table
if (!this.selectionPredicates[table]) {
this.selectionPredicates[table] = [];
}
this.selectionPredicates[table].push(pred);
} else if (tables.size > 1) {
// Multi-table predicate
// Check if it's a parenthesized OR
if (pred.trim().startsWith('(') && pred.includes(' OR ')) {
// Multi-table OR - mark for potential expansion
this.multiTableOrPredicates.push({
tables: tables,
predicate: pred
});
console.log('Multi-table OR detected:', pred, '(tables:', Array.from(tables).join(', ') + ')');
}
this.complexPredicates.push({
tables: tables,
predicate: pred
});
}
}
}
hasTopLevelOr(pred) {
// Check if predicate has OR at top level (not in parens)
// Remove parens groups first
let depth = 0;
let inString = false;
let stringChar = null;
let cleaned = '';
for (let i = 0; i < pred.length; i++) {
const char = pred[i];
if (!inString) {
if (char === "'" || char === '"') {
inString = true;
stringChar = char;
} else if (char === '(') {
depth++;
} else if (char === ')') {
depth--;
} else if (depth === 0) {
cleaned += char;
}
} else if (char === stringChar && (i === 0 || pred[i - 1] !== '\\')) {
inString = false;
stringChar = null;
}
}
// Check if cleaned string contains ' OR '
return /\s+OR\s+/i.test(cleaned);
}
splitByAnd(clause) {
// Split by AND while respecting:
// 1. Parentheses (don't split inside parens)
// 2. String literals (don't split inside quotes)
// 3. Keywords in strings ('AND Corporation', 'OR gate')
// 4. BETWEEN...AND (don't split the AND that's part of BETWEEN)
const predicates = [];
let current = '';
let parenDepth = 0;
let inString = false;
let stringChar = null;
let inBetween = false; // Track if we're inside a BETWEEN clause
for (let i = 0; i < clause.length; i++) {
const char = clause[i];
const remaining = clause.substring(i).toUpperCase();
if (!inString) {
if (char === "'" || char === '"') {
inString = true;
stringChar = char;
current += char;
} else if (char === '(') {
parenDepth++;
current += char;
} else if (char === ')') {
parenDepth--;
current += char;
} else if (parenDepth === 0 && remaining.startsWith('BETWEEN ')) {
// Entering a BETWEEN clause
inBetween = true;
current += char;
} else if (parenDepth === 0 && remaining.startsWith('AND ')) {
// Check if this is actually " AND " (not part of a longer word)
const prevChar = i > 0 ? clause[i - 1] : ' ';
if (/\s/.test(prevChar) || prevChar === ')') {
if (inBetween) {
// This is the AND in "BETWEEN x AND y" - don't split
inBetween = false; // Reset flag after consuming the AND
current += char;
} else {
// This is a top-level AND separator - split here
predicates.push(current.trim());
current = '';
i += 3; // Skip 'AND'
continue;
}
} else {
// Part of a word like "ISLAND" or "LAND"
current += char;
}
} else {
current += char;
}
} else {
// Inside string
if (char === stringChar && (i === 0 || clause[i - 1] !== '\\')) {
inString = false;
stringChar = null;
}
current += char;
}
}
if (current.trim()) {
predicates.push(current.trim());
}
return predicates;
}
getPredicatesForSubset(subset) {
const subsetSet = new Set(subset);
const applicable = {
selections: [],
joins: [],
complex: []
};
// Add selection predicates
for (let table of subset) {
if (this.selectionPredicates[table]) {
applicable.selections.push(...this.selectionPredicates[table]);
}
}
// Add join predicates (both tables in subset)
for (let jp of this.joinPredicates) {
if (Array.from(jp.tables).every(t => subsetSet.has(t))) {
applicable.joins.push(jp.predicate);
}
}
// Add complex predicates (all tables in subset)
for (let cp of this.complexPredicates) {
if (Array.from(cp.tables).every(t => subsetSet.has(t))) {
applicable.complex.push(cp.predicate);
}
}
return applicable;
}
getJoinPredicatesBetween(left, right) {
const leftSet = new Set(left);
const rightSet = new Set(right);
const connecting = [];
for (let jp of this.joinPredicates) {
const tables = Array.from(jp.tables);
if (tables.length === 2) {
const hasLeft = tables.some(t => leftSet.has(t));
const hasRight = tables.some(t => rightSet.has(t));
if (hasLeft && hasRight) {
connecting.push(jp);
}
}
}
return connecting;
}
}
// SQL Parser - supports both modern JOIN and old-style comma syntax
// Add transitive joins for tables with same column = same constant
// ONLY when both predicates constrain to the SAME SINGLE VALUE
// Valid: t1.col = 'x' AND t2.col = 'x' => t1.col = t2.col
// Valid: t1.col IN ('x') AND t2.col IN ('x') => t1.col = t2.col
// Valid: t1.col = 'x' AND t2.col IN ('x') => t1.col = t2.col
// Invalid: t1.col IN ('a', 'b') AND t2.col IN ('a', 'b') => NO (could be different)
function addConstantEqualityJoins(joinGraph, classifier, tables) {
console.log('\n🔍 Detecting constant-equality joins...');
// Map: "column:value" -> [{table, column}, ...]
// Only includes predicates that constrain to a SINGLE value
const constantGroups = new Map();
// Scan all tables for selection predicates
for (let table of tables) {
const preds = classifier.getPredicatesForSubset([table]);
for (let pred of preds.selections) {
const result = extractSingleConstantValue(pred);
if (result) {
const { table: tbl, column: col, value: val } = result;
const key = `${col}:${val}`;
if (!constantGroups.has(key)) {
constantGroups.set(key, []);
}
constantGroups.get(key).push({ table: tbl, column: col });
}
}
}
// Add joins for groups with 2+ tables
let addedCount = 0;
for (let [key, group] of constantGroups) {
if (group.length >= 2) {
console.log(` Found ${group.length} tables with ${key}:`);
console.log(` Tables: ${group.map(g => g.table).join(', ')}`);
// Add join between each pair
for (let i = 0; i < group.length; i++) {
for (let j = i + 1; j < group.length; j++) {
joinGraph.addJoin(
group[i].table,
group[j].table,
group[i].column,
group[j].column,
false // isOriginal=false (transitive via constant)
);
addedCount++;
}
}
}
}
if (addedCount > 0) {
console.log(` Added ${addedCount} constant-equality join(s)`);
} else {
console.log(` No constant-equality joins found`);
}
}
// Extract single constant value from a predicate
// Returns {table, column, value} if predicate constrains to ONE value, null otherwise
function extractSingleConstantValue(pred) {
// Pattern 1: table.column = constant
// IMPORTANT: (?:\s|$) accepts EITHER space OR end-of-string
// This is correct - do not change to (?:\s+$) which would require space before end!
const eqMatch = pred.match(/(\w+)\.(\w+)\s*=\s*(.+?)(?:\s|$)/);
if (eqMatch) {
const [_, table, column, rawValue] = eqMatch;
const value = normalizeValue(rawValue);
return { table, column, value };
}
// Pattern 2: table.column IN (...)
const inMatch = pred.match(/(\w+)\.(\w+)\s+IN\s*\(([^)]+)\)/i);
if (inMatch) {
const [_, table, column, valueList] = inMatch;
// Extract individual values
const values = valueList
.split(',')
.map(v => normalizeValue(v.trim()));
// Only valid if exactly ONE value in the IN list
if (values.length === 1) {
return { table, column, value: values[0] };
}
}
return null;
}
// Normalize a constant value: remove quotes, type casts, whitespace
function normalizeValue(rawValue) {
return rawValue
.replace(/['"]/g, '') // Remove quotes
.replace(/::.+$/, '') // Remove type casts like ::timestamp
.trim();
}
// Workload Analyzer - tracks table and column usage across queries
class WorkloadAnalyzer {
constructor() {
this.tables = new Map(); // base_table -> { query_count, columns: Map }
this.query_count = 0;
}
analyzeQuery(tables, aliases, classifier, joinGraph) {
this.query_count++;
// Get base tables (resolve aliases)
const baseTables = new Set();
tables.forEach(alias => {
const baseTable = aliases.get(alias) || alias;
baseTables.add(baseTable);
});
// Track each base table (ignore self-joins - count once per query)
baseTables.forEach(baseTable => {
if (!this.tables.has(baseTable)) {
this.tables.set(baseTable, {
query_count: 0,
columns: new Map()
});
}
const tableData = this.tables.get(baseTable);
tableData.query_count++;
});
// Analyze columns from predicates
this.analyzeColumns(tables, aliases, classifier, joinGraph);
}
analyzeColumns(tables, aliases, classifier, joinGraph) {
// Get all table.column references from all predicates
const tableColumnRefs = this.extractAllTableColumnRefs(tables, classifier);
// Classify each table.column usage
tableColumnRefs.forEach(({ alias, column, predicate, predicateType }) => {
const baseTable = aliases.get(alias) || alias;
if (!this.tables.has(baseTable)) return;
const tableData = this.tables.get(baseTable);
if (!tableData.columns.has(column)) {
tableData.columns.set(column, {
query_count: 0,
join_count: 0,
equality_count: 0,
range_count: 0,
like_count: 0,
range_min: 'NA',
range_max: 'NA',
queries_seen: new Set()
});
}
const columnData = tableData.columns.get(column);
// Track which queries use this column (for query_count)
if (!columnData.queries_seen.has(this.query_count)) {
columnData.queries_seen.add(this.query_count);
columnData.query_count++;
}
// Classify usage
if (predicateType === 'join') {
columnData.join_count++;
} else if (predicateType === 'selection') {
// Further classify selection predicates
if (this.isRangePredicate(predicate)) {
columnData.range_count++;
// Extract and update range bounds
const bounds = this.extractRangeBounds(predicate, column);
this.updateRangeBounds(columnData, bounds.min, bounds.max);
} else if (this.isLikePredicate(predicate)) {
columnData.like_count++;
} else {
// Equality predicates (=, !=, IN, etc.)
columnData.equality_count++;
}
}
});
}
extractAllTableColumnRefs(tables, classifier) {
const refs = [];
// Get predicates for full query
const allPreds = classifier.getPredicatesForSubset(tables);
// Extract from join predicates
allPreds.joins.forEach(pred => {
const columns = this.extractColumnsFromExpression(pred);
columns.forEach(({ alias, column }) => {