Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 1799x 1799x 1796x 2396x 2396x 1799x 741x 861x 861x 1799x 303x 324x 324x 1799x 902x 942x 1799x 2388x 669x 669x 1446x 669x 1719x 1719x 1719x 1719x 327x 327x 177x 150x 174x 150x 321x 72x 72x 147x 72x 249x 249x 249x 249x 135x 1733x 1733x 1733x 1733x 1733x 1733x 1733x 1352x 381x 381x 381x 1733x 807x 687x 687x 807x 687x 687x 687x 747x 726x 687x 696x 618x 1115x 1115x 1115x 1304x 1208x 1208x 1208x 1115x 1115x 1115x 1208x 1121x 1115x 2936x 2054x 819x 819x 192x 1862x 381x 381x 846x 381x 465x 465x 465x 465x 474x 474x 474x 474x 3x 3x 471x 471x 471x 474x 381x 489x 489x 492x 492x 492x 492x 489x 1284x 1284x 1284x 1284x 1359x 1359x 1359x 201x 1158x 1539x 1539x 1539x 132x 1407x 1407x 1092x 315x 315x 192x 381x 381x 381x 474x 474x 147x 327x 714x 474x 474x 474x 3x 324x 324x 324x 381x 324x 324x 324x 504x 504x 504x 504x 504x 90x 414x 414x 6x 6x 12x 6x 324x 6x 6x 6x 6x 12x 12x 12x 6x 501x 6x 495x 888x 888x 342x 153x 66x 66x 66x 3x 63x 63x 63x 63x 54x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 15x 12x 27x 6x 63x 63x 36x 27x 27x 63x 63x 21x 27x 54x 54x 54x 54x 54x 27x 30x 15x 15x 30x 15x 15x 12x 30x 15x 15x 9x 15x 9x 6x 6x 27x 27x 27x 27x 27x 27x 27x 6x 21x 27x 27x 27x 27x 27x 27x 27x 21x 21x 21x 21x 21x 21x 21x 6x 6x 27x 27x 27x 27x 27x 12x 15x 30x 15x 15x 15x 27x | /**
* Query Planner for Unified Query Architecture
* Handles query planning, cube analysis, and join resolution
* All SQL building has been moved to QueryBuilder
*/
import type {
Cube,
QueryContext,
QueryPlan,
CubeJoin,
SemanticQuery,
QueryAnalysis,
PrimaryCubeAnalysis,
PrimaryCubeCandidate,
JoinPathAnalysis,
JoinPathStep,
PreAggregationAnalysis
} from './types'
import {
resolveCubeReference,
getJoinType,
expandBelongsToManyJoin
} from './cube-utils'
import { eq, and, sql, type SQL } from 'drizzle-orm'
/**
* Pre-aggregation plan for handling hasMany relationships
*/
// interface PreAggregationPlan {
// cube: Cube
// alias: string
// joinKeys: Array<{
// sourceColumn: string
// targetColumn: string
// }>
// needsPreAggregation: boolean
// measures: string[]
// }
export class QueryPlanner {
/**
* Analyze a semantic query to determine which cubes are involved
*/
analyzeCubeUsage(query: SemanticQuery): Set<string> {
const cubesUsed = new Set<string>()
// Extract cube names from measures
if (query.measures) {
for (const measure of query.measures) {
const [cubeName] = measure.split('.')
cubesUsed.add(cubeName)
}
}
// Extract cube names from dimensions
if (query.dimensions) {
for (const dimension of query.dimensions) {
const [cubeName] = dimension.split('.')
cubesUsed.add(cubeName)
}
}
// Extract cube names from time dimensions
if (query.timeDimensions) {
for (const timeDim of query.timeDimensions) {
const [cubeName] = timeDim.dimension.split('.')
cubesUsed.add(cubeName)
}
}
// Extract cube names from filters
if (query.filters) {
for (const filter of query.filters) {
this.extractCubeNamesFromFilter(filter, cubesUsed)
}
}
return cubesUsed
}
/**
* Recursively extract cube names from filters (handles logical filters)
*/
private extractCubeNamesFromFilter(filter: any, cubesUsed: Set<string>): void {
// Handle logical filters (AND/OR) - Server format: { and: [...] } or { or: [...] }
if ('and' in filter || 'or' in filter) {
const logicalFilters = filter.and || filter.or || []
for (const subFilter of logicalFilters) {
this.extractCubeNamesFromFilter(subFilter, cubesUsed)
}
return
}
// Handle simple filter condition
Eif ('member' in filter) {
const [cubeName] = filter.member.split('.')
Eif (cubeName) {
cubesUsed.add(cubeName)
}
}
}
/**
* Extract measures referenced in filters (for CTE inclusion)
*/
private extractMeasuresFromFilters(query: SemanticQuery, cubeName: string): string[] {
const measures: string[] = []
if (!query.filters) {
return measures
}
for (const filter of query.filters) {
this.extractMeasuresFromFilter(filter, cubeName, measures)
}
return measures
}
/**
* Recursively extract measures from filters for a specific cube
*/
private extractMeasuresFromFilter(filter: any, targetCubeName: string, measures: string[]): void {
// Handle logical filters (AND/OR)
if ('and' in filter || 'or' in filter) {
const logicalFilters = filter.and || filter.or || []
for (const subFilter of logicalFilters) {
this.extractMeasuresFromFilter(subFilter, targetCubeName, measures)
}
return
}
// Handle simple filter condition
Eif ('member' in filter) {
const memberName = filter.member
const [cubeName] = memberName.split('.')
if (cubeName === targetCubeName) {
// This is a filter on the target cube - check if it's a measure
// We'll include it and let the CTE building logic determine if it's actually a measure
measures.push(memberName)
}
}
}
/**
* Create a unified query plan that works for both single and multi-cube queries
*/
createQueryPlan(
cubes: Map<string, Cube>,
query: SemanticQuery,
ctx: QueryContext
): QueryPlan {
const cubesUsed = this.analyzeCubeUsage(query)
const cubeNames = Array.from(cubesUsed)
Iif (cubeNames.length === 0) {
throw new Error('No cubes found in query')
}
// Choose primary cube
const primaryCubeName = this.choosePrimaryCube(cubeNames, query, cubes)
const primaryCube = cubes.get(primaryCubeName)
Iif (!primaryCube) {
throw new Error(`Primary cube '${primaryCubeName}' not found`)
}
// For single cube queries, return simple plan with empty join array
if (cubeNames.length === 1) {
return {
primaryCube,
joinCubes: [], // Empty for single cube
selections: {}, // Will be built by QueryBuilder
whereConditions: [], // Will be built by QueryBuilder
groupByFields: [] // Will be built by QueryBuilder
}
}
// For multi-cube queries, build join plan
const joinCubes = this.buildJoinPlan(cubes, primaryCube, cubeNames, ctx)
// Detect hasMany relationships and plan pre-aggregation CTEs
const preAggregationCTEs = this.planPreAggregationCTEs(cubes, primaryCube, joinCubes, query)
return {
primaryCube,
joinCubes,
selections: {}, // Will be built by QueryBuilder
whereConditions: [], // Will be built by QueryBuilder
groupByFields: [], // Will be built by QueryBuilder
preAggregationCTEs
}
}
/**
* Choose the primary cube based on query analysis
* Uses a consistent strategy to avoid measure order dependencies
*/
choosePrimaryCube(cubeNames: string[], query: SemanticQuery, cubes?: Map<string, Cube>): string {
// Strategy: Prefer the cube that has dimensions in the query
// This represents the "grain" of the analysis
if (query.dimensions && query.dimensions.length > 0 && cubes) {
const dimensionCubes = query.dimensions.map(d => d.split('.')[0])
// Find the cube with the most dimensions in the query
const cubeDimensionCount = new Map<string, number>()
for (const cube of dimensionCubes) {
cubeDimensionCount.set(cube, (cubeDimensionCount.get(cube) || 0) + 1)
}
Eif (cubeDimensionCount.size > 0) {
// Return the cube with the most dimensions, but verify connectivity first
const maxDimensions = Math.max(...cubeDimensionCount.values())
const primaryCandidates = [...cubeDimensionCount.entries()]
.filter(([, count]) => count === maxDimensions)
.map(([name]) => name)
.sort()
// Check if the primary candidate can reach all other required cubes
for (const candidate of primaryCandidates) {
if (this.canReachAllCubes(candidate, cubeNames, cubes)) {
return candidate
}
}
}
}
// Fallback: Choose cube with most connectivity that can reach all other cubes
Eif (cubes) {
const connectivityScores = new Map<string, number>()
for (const cubeName of cubeNames) {
if (this.canReachAllCubes(cubeName, cubeNames, cubes)) {
const cube = cubes.get(cubeName)
const joinCount = cube?.joins ? Object.keys(cube.joins).length : 0
connectivityScores.set(cubeName, joinCount)
}
}
Eif (connectivityScores.size > 0) {
// Find cube with highest connectivity, break ties alphabetically
const maxConnectivity = Math.max(...connectivityScores.values())
const mostConnectedCubes = [...connectivityScores.entries()]
.filter(([, count]) => count === maxConnectivity)
.map(([name]) => name)
.sort()
return mostConnectedCubes[0]
}
}
// Final fallback: alphabetical order for consistency
return [...cubeNames].sort()[0]
}
/**
* Check if a cube can reach all other cubes in the list via joins
*/
private canReachAllCubes(fromCube: string, allCubes: string[], cubes: Map<string, Cube>): boolean {
const otherCubes = allCubes.filter(name => name !== fromCube)
for (const targetCube of otherCubes) {
const path = this.findJoinPath(cubes, fromCube, targetCube, new Set())
if (!path || path.length === 0) {
return false
}
}
return true
}
/**
* Build join plan for multi-cube query
* Supports both direct joins and transitive joins through intermediate cubes
*/
private buildJoinPlan(
cubes: Map<string, Cube>,
primaryCube: Cube,
cubeNames: string[],
ctx: QueryContext
): QueryPlan['joinCubes'] {
const joinCubes: QueryPlan['joinCubes'] = []
const processedCubes = new Set([primaryCube.name])
// Find cubes to join (all except primary)
const cubesToJoin = cubeNames.filter(name => name !== primaryCube.name)
for (const cubeName of cubesToJoin) {
Iif (processedCubes.has(cubeName)) {
continue // Already processed
}
const joinPath = this.findJoinPath(cubes, primaryCube.name, cubeName, processedCubes)
Iif (!joinPath || joinPath.length === 0) {
throw new Error(`No join path found from '${primaryCube.name}' to '${cubeName}'`)
}
// Add all cubes in the join path
for (const { toCube, joinDef } of joinPath) {
Iif (processedCubes.has(toCube)) {
continue // Skip if already processed
}
const cube = cubes.get(toCube)
Iif (!cube) {
throw new Error(`Cube '${toCube}' not found`)
}
// Check if this is a belongsToMany relationship
if (joinDef.relationship === 'belongsToMany' && joinDef.through) {
// Expand the belongsToMany join into junction table joins
const expanded = expandBelongsToManyJoin(joinDef, ctx.securityContext)
// Add the join with junction table information
joinCubes.push({
cube,
alias: `${toCube.toLowerCase()}_cube`,
joinType: expanded.junctionJoins[1].joinType, // Use the target join type
joinCondition: expanded.junctionJoins[1].condition, // Target join condition
junctionTable: {
table: joinDef.through.table,
alias: `junction_${toCube.toLowerCase()}`,
joinType: expanded.junctionJoins[0].joinType,
joinCondition: expanded.junctionJoins[0].condition,
securitySql: joinDef.through.securitySql
}
})
} else {
// Regular join (belongsTo, hasOne, hasMany)
// Build join condition using new array-based format
// For regular table joins, we don't use artificial aliases - use actual table references
const joinCondition = this.buildJoinCondition(
joinDef as CubeJoin,
null, // No source alias needed - use the actual column
null // No target alias needed - use the actual column
)
// Derive join type from relationship
const joinType = getJoinType(joinDef.relationship, joinDef.sqlJoinType) as 'inner' | 'left' | 'right' | 'full'
joinCubes.push({
cube,
alias: `${toCube.toLowerCase()}_cube`,
joinType,
joinCondition
})
}
processedCubes.add(toCube)
}
}
return joinCubes
}
/**
* Build join condition from new array-based join definition
*/
private buildJoinCondition(
joinDef: CubeJoin,
sourceAlias: string | null,
targetAlias: string | null
): SQL {
const conditions: SQL[] = []
// Process array of join conditions
for (const joinOn of joinDef.on) {
// Use actual column objects instead of aliases for regular table joins
const sourceCol = sourceAlias
? sql`${sql.identifier(sourceAlias)}.${sql.identifier(joinOn.source.name)}`
: joinOn.source
const targetCol = targetAlias
? sql`${sql.identifier(targetAlias)}.${sql.identifier(joinOn.target.name)}`
: joinOn.target
// Use custom comparator or default to eq
const comparator = joinOn.as || eq
conditions.push(comparator(sourceCol as any, targetCol as any))
}
return and(...conditions)!
}
/**
* Find join path from source cube to target cube
* Returns array of join steps to reach target
*/
private findJoinPath(
cubes: Map<string, Cube>,
fromCube: string,
toCube: string,
alreadyProcessed: Set<string>
): Array<{ fromCube: string, toCube: string, joinDef: any }> | null {
Iif (fromCube === toCube) {
return []
}
// BFS to find shortest path
const queue: Array<{ cube: string, path: Array<{ fromCube: string, toCube: string, joinDef: any }> }> = [
{ cube: fromCube, path: [] }
]
const visited = new Set([fromCube, ...alreadyProcessed])
while (queue.length > 0) {
const { cube: currentCube, path } = queue.shift()!
const cubeDefinition = cubes.get(currentCube)
if (!cubeDefinition?.joins) {
continue
}
// Check all joins from current cube - resolve lazy references
for (const [, joinDef] of Object.entries(cubeDefinition.joins)) {
// Resolve cube reference to get actual cube name
const resolvedTargetCube = resolveCubeReference(joinDef.targetCube)
const actualTargetName = resolvedTargetCube.name
if (visited.has(actualTargetName)) {
continue
}
const newPath = [...path, {
fromCube: currentCube,
toCube: actualTargetName,
joinDef
}]
if (actualTargetName === toCube) {
return newPath
}
visited.add(actualTargetName)
queue.push({ cube: actualTargetName, path: newPath })
}
}
// If no direct path found, try looking for reverse joins
// (where other cubes join to the current cube chain)
return null
}
/**
* Plan pre-aggregation CTEs for hasMany relationships to prevent fan-out
* Note: belongsToMany relationships handle fan-out differently through their junction table structure
* and don't require CTEs - the two-hop join with the junction table provides natural grouping
*/
private planPreAggregationCTEs(
_cubes: Map<string, Cube>,
primaryCube: Cube,
joinCubes: QueryPlan['joinCubes'],
query: SemanticQuery
): QueryPlan['preAggregationCTEs'] {
const preAggCTEs: QueryPlan['preAggregationCTEs'] = []
Iif (!query.measures || query.measures.length === 0) {
return preAggCTEs // No measures, no fan-out risk
}
// Check each join cube for hasMany relationships
for (const joinCube of joinCubes) {
const hasManyJoinDef = this.findHasManyJoinDef(primaryCube, joinCube.cube.name)
if (!hasManyJoinDef) {
continue // Not a hasMany relationship
}
// Check if we have measures from this hasMany cube (from SELECT clause)
const measuresFromSelect = query.measures ? query.measures.filter(m =>
m.startsWith(joinCube.cube.name + '.')
) : []
// Also check for measures referenced in filters (for HAVING clause)
const measuresFromFilters = this.extractMeasuresFromFilters(query, joinCube.cube.name)
// Combine and deduplicate measures from both SELECT and filters
const allMeasuresFromThisCube = [...new Set([...measuresFromSelect, ...measuresFromFilters])]
if (allMeasuresFromThisCube.length === 0) {
continue // No measures from this cube, no fan-out risk
}
// Expand calculated measures to include their dependencies
const expandedMeasures = this.expandCalculatedMeasureDependencies(
joinCube.cube,
allMeasuresFromThisCube
)
// Extract join keys from the new array-based format
const joinKeys = hasManyJoinDef.on.map(joinOn => ({
sourceColumn: joinOn.source.name,
targetColumn: joinOn.target.name,
sourceColumnObj: joinOn.source,
targetColumnObj: joinOn.target
}))
preAggCTEs!.push({
cube: joinCube.cube,
alias: joinCube.alias,
cteAlias: `${joinCube.cube.name.toLowerCase()}_agg`,
joinKeys,
measures: expandedMeasures
})
}
return preAggCTEs
}
/**
* Expand calculated measures to include their dependencies
*/
private expandCalculatedMeasureDependencies(
cube: Cube,
measures: string[]
): string[] {
const expandedSet = new Set<string>()
const toProcess = [...measures]
while (toProcess.length > 0) {
const measureName = toProcess.pop()!
Iif (expandedSet.has(measureName)) {
continue
}
expandedSet.add(measureName)
const [, fieldName] = measureName.split('.')
if (!cube.measures || !cube.measures[fieldName]) {
continue
}
const measure = cube.measures[fieldName]
// If it's a calculated measure, extract its dependencies
if (measure.type === 'calculated' && measure.calculatedSql) {
const deps = this.extractDependenciesFromTemplate(measure.calculatedSql, cube.name)
for (const dep of deps) {
if (!expandedSet.has(dep)) {
toProcess.push(dep)
}
}
}
}
return Array.from(expandedSet)
}
/**
* Extract measure references from calculatedSql template
*/
private extractDependenciesFromTemplate(calculatedSql: string, cubeName: string): string[] {
const regex = /\{([^}]+)\}/g
const matches = calculatedSql.matchAll(regex)
const deps: string[] = []
for (const match of matches) {
const ref = match[1].trim()
// Handle both {measure} and {Cube.measure} formats
Iif (ref.includes('.')) {
deps.push(ref)
} else {
deps.push(`${cubeName}.${ref}`)
}
}
return deps
}
/**
* Find hasMany join definition from primary cube to target cube
*/
private findHasManyJoinDef(
primaryCube: Cube,
targetCubeName: string
): CubeJoin | null {
if (!primaryCube.joins) {
return null
}
// Look through all joins from primary cube
for (const [, joinDef] of Object.entries(primaryCube.joins)) {
const resolvedTargetCube = resolveCubeReference(joinDef.targetCube)
if (resolvedTargetCube.name === targetCubeName && joinDef.relationship === 'hasMany') {
return joinDef as CubeJoin
}
}
return null
}
/**
* Analyze query planning decisions without building the full query
* Returns detailed metadata about how the query plan would be constructed
* Used for debugging and transparency in the playground UI
*/
analyzeQueryPlan(
cubes: Map<string, Cube>,
query: SemanticQuery,
_ctx: QueryContext
): QueryAnalysis {
const cubesUsed = this.analyzeCubeUsage(query)
const cubeNames = Array.from(cubesUsed)
// Handle empty query
if (cubeNames.length === 0) {
return {
timestamp: new Date().toISOString(),
cubeCount: 0,
cubesInvolved: [],
primaryCube: {
selectedCube: '',
reason: 'single_cube',
explanation: 'No cubes found in query'
},
joinPaths: [],
preAggregations: [],
querySummary: {
queryType: 'single_cube',
joinCount: 0,
cteCount: 0,
hasPreAggregation: false
},
warnings: ['No cubes found in query - add measures or dimensions']
}
}
// Analyze primary cube selection
const primaryCubeAnalysis = this.analyzePrimaryCubeSelection(cubeNames, query, cubes)
const primaryCubeName = primaryCubeAnalysis.selectedCube
// Build analysis object
const analysis: QueryAnalysis = {
timestamp: new Date().toISOString(),
cubeCount: cubeNames.length,
cubesInvolved: cubeNames.sort(),
primaryCube: primaryCubeAnalysis,
joinPaths: [],
preAggregations: [],
querySummary: {
queryType: 'single_cube',
joinCount: 0,
cteCount: 0,
hasPreAggregation: false
},
warnings: []
}
// If multi-cube, analyze join paths
if (cubeNames.length > 1) {
const cubesToJoin = cubeNames.filter(name => name !== primaryCubeName)
for (const targetCube of cubesToJoin) {
analysis.joinPaths.push(
this.analyzeJoinPath(cubes, primaryCubeName, targetCube)
)
}
// Analyze pre-aggregation requirements
const primaryCube = cubes.get(primaryCubeName)
Eif (primaryCube) {
analysis.preAggregations = this.analyzePreAggregations(
cubes,
primaryCube,
cubesToJoin,
query
)
}
// Update summary
const successfulPaths = analysis.joinPaths.filter(p => p.pathFound)
const failedPaths = analysis.joinPaths.filter(p => !p.pathFound)
analysis.querySummary.joinCount = successfulPaths.length
analysis.querySummary.cteCount = analysis.preAggregations.length
analysis.querySummary.hasPreAggregation = analysis.preAggregations.length > 0
if (analysis.preAggregations.length > 0) {
analysis.querySummary.queryType = 'multi_cube_cte'
} else {
analysis.querySummary.queryType = 'multi_cube_join'
}
// Add warnings for failed paths
for (const failedPath of failedPaths) {
analysis.warnings!.push(
`No join path found to cube '${failedPath.targetCube}'. Check that joins are defined correctly.`
)
}
}
return analysis
}
/**
* Analyze why a particular cube was chosen as primary
*/
private analyzePrimaryCubeSelection(
cubeNames: string[],
query: SemanticQuery,
cubes: Map<string, Cube>
): PrimaryCubeAnalysis {
// Single cube case
if (cubeNames.length === 1) {
return {
selectedCube: cubeNames[0],
reason: 'single_cube',
explanation: 'Only one cube is used in this query'
}
}
// Build candidates list
const candidates: PrimaryCubeCandidate[] = []
const dimensionCubes = (query.dimensions || []).map(d => d.split('.')[0])
const cubeDimensionCount = new Map<string, number>()
for (const cube of dimensionCubes) {
cubeDimensionCount.set(cube, (cubeDimensionCount.get(cube) || 0) + 1)
}
for (const cubeName of cubeNames) {
const cube = cubes.get(cubeName)
const dimensionCount = cubeDimensionCount.get(cubeName) || 0
const joinCount = cube?.joins ? Object.keys(cube.joins).length : 0
const canReachAll = this.canReachAllCubes(cubeName, cubeNames, cubes)
candidates.push({
cubeName,
dimensionCount,
joinCount,
canReachAll
})
}
// Tier 1: Check for dimension-based selection
if (query.dimensions && query.dimensions.length > 0) {
const maxDimensions = Math.max(...candidates.map(c => c.dimensionCount))
Eif (maxDimensions > 0) {
const primaryCandidates = candidates
.filter(c => c.dimensionCount === maxDimensions)
.sort((a, b) => a.cubeName.localeCompare(b.cubeName))
// Check if candidate can reach all other cubes
for (const candidate of primaryCandidates) {
if (candidate.canReachAll) {
return {
selectedCube: candidate.cubeName,
reason: 'most_dimensions',
explanation: `Selected because it has ${candidate.dimensionCount} dimension${candidate.dimensionCount !== 1 ? 's' : ''} in the query (defines the analytical grain)`,
candidates
}
}
}
}
}
// Tier 2: Connectivity-based selection
const reachableCandidates = candidates.filter(c => c.canReachAll)
if (reachableCandidates.length > 0) {
const maxConnectivity = Math.max(...reachableCandidates.map(c => c.joinCount))
const mostConnected = reachableCandidates
.filter(c => c.joinCount === maxConnectivity)
.sort((a, b) => a.cubeName.localeCompare(b.cubeName))[0]
return {
selectedCube: mostConnected.cubeName,
reason: 'most_connected',
explanation: `Selected because it has ${mostConnected.joinCount} join relationship${mostConnected.joinCount !== 1 ? 's' : ''} and can reach all other cubes`,
candidates
}
}
// Tier 3: Alphabetical fallback
const fallback = [...cubeNames].sort()[0]
return {
selectedCube: fallback,
reason: 'alphabetical_fallback',
explanation: 'Selected alphabetically as fallback (no cube could reach all others)',
candidates
}
}
/**
* Analyze the join path between two cubes with detailed step information
*/
private analyzeJoinPath(
cubes: Map<string, Cube>,
fromCube: string,
toCube: string
): JoinPathAnalysis {
const visitedCubes: string[] = [fromCube]
// BFS to find path with tracking
const queue: Array<{
cube: string
path: Array<{ fromCube: string; toCube: string; joinDef: CubeJoin }>
}> = [{ cube: fromCube, path: [] }]
const visited = new Set([fromCube])
while (queue.length > 0) {
const { cube: currentCube, path } = queue.shift()!
const cubeDefinition = cubes.get(currentCube)
if (!cubeDefinition?.joins) {
continue
}
for (const [, joinDef] of Object.entries(cubeDefinition.joins)) {
const resolvedTargetCube = resolveCubeReference(joinDef.targetCube)
const actualTargetName = resolvedTargetCube.name
Iif (visited.has(actualTargetName)) {
continue
}
visitedCubes.push(actualTargetName)
visited.add(actualTargetName)
const newPath = [...path, {
fromCube: currentCube,
toCube: actualTargetName,
joinDef: joinDef as CubeJoin
}]
if (actualTargetName === toCube) {
// Found the path - convert to analysis format
const pathSteps: JoinPathStep[] = newPath.map(step => {
const joinType = getJoinType(step.joinDef.relationship, step.joinDef.sqlJoinType) as 'inner' | 'left' | 'right' | 'full'
const joinColumns = step.joinDef.on.map(joinOn => ({
sourceColumn: joinOn.source.name,
targetColumn: joinOn.target.name
}))
const result: JoinPathStep = {
fromCube: step.fromCube,
toCube: step.toCube,
relationship: step.joinDef.relationship,
joinType,
joinColumns
}
// Add junction table info for belongsToMany
Iif (step.joinDef.relationship === 'belongsToMany' && step.joinDef.through) {
const through = step.joinDef.through
result.junctionTable = {
tableName: (through.table as any)[Symbol.for('drizzle:Name')] || 'junction_table',
sourceColumns: through.sourceKey.map(k => k.target.name),
targetColumns: through.targetKey.map(k => k.source.name)
}
}
return result
})
return {
targetCube: toCube,
pathFound: true,
path: pathSteps,
pathLength: pathSteps.length,
visitedCubes
}
}
queue.push({ cube: actualTargetName, path: newPath })
}
}
// No path found
return {
targetCube: toCube,
pathFound: false,
error: `No join path found from '${fromCube}' to '${toCube}'. Ensure the target cube has a relationship defined (belongsTo, hasOne, hasMany, or belongsToMany).`,
visitedCubes
}
}
/**
* Analyze pre-aggregation requirements for hasMany relationships
*/
private analyzePreAggregations(
_cubes: Map<string, Cube>,
primaryCube: Cube,
cubesToJoin: string[],
query: SemanticQuery
): PreAggregationAnalysis[] {
const preAggregations: PreAggregationAnalysis[] = []
Iif (!query.measures || query.measures.length === 0) {
return preAggregations
}
for (const targetCubeName of cubesToJoin) {
const hasManyJoinDef = this.findHasManyJoinDef(primaryCube, targetCubeName)
if (!hasManyJoinDef) {
continue
}
// Check if we have measures from this cube
const measuresFromThisCube = query.measures.filter(m =>
m.startsWith(targetCubeName + '.')
)
Iif (measuresFromThisCube.length === 0) {
continue
}
// Extract join keys
const joinKeys = hasManyJoinDef.on.map(joinOn => ({
sourceColumn: joinOn.source.name,
targetColumn: joinOn.target.name
}))
preAggregations.push({
cubeName: targetCubeName,
cteAlias: `${targetCubeName.toLowerCase()}_agg`,
reason: `hasMany relationship from ${primaryCube.name} - requires pre-aggregation to prevent row duplication (fan-out)`,
measures: measuresFromThisCube,
joinKeys
})
}
return preAggregations
}
} |