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 | 135x 135x 23x 112x 97x 135x 42x 172x 172x 172x 172x 172x 172x 172x 172x 1411x 16x 1x 1x 15x 15x 1x 1x 14x 14x 14x 14x 14x 2x 172x 168x 168x 168x 168x 168x 168x 1x 172x 5x 17x 70x 70x 70x 49x 22x 4x 18x 18x 72x 72x 50x 18x 18x 18x 18x 18x 144x 144x 144x 144x 144x 162x 162x 162x 18x 162x 18x 18x 18x 72x 72x 36x 18x 18x 18x 18x 18x 17x 17x 17x 17x 17x 17x 17x 167x 105x 9x 9x 9x 9x 987x 987x 987x 987x 987x 987x 972x 1274x 1274x 19x 19x 1255x 1255x 1255x 27x 27x 1228x 12x 986x 358x 410x 410x 4x 4x 406x 406x 406x 3x 3x 403x 9x 985x 130x 137x 137x 1x 1x 136x 136x 136x 2x 2x 134x 2x 985x 397x 409x 983x 13x 983x 932x 247x 247x 523x 247x 684x 2x 2x 682x 682x 2x 2x 679x 679x 679x 4x 4x 675x 16x | /**
* Semantic Layer Compiler
* Drizzle ORM-first cube compilation and registration with type safety
*/
import type {
SemanticQuery,
QueryResult,
SecurityContext,
DatabaseExecutor,
CubeMetadata,
MeasureMetadata,
DimensionMetadata,
CubeRelationshipMetadata,
HierarchyMetadata,
Cube,
QueryAnalysis,
CacheConfig,
ExplainOptions,
ExplainResult,
ExecutionOptions,
TimeGranularity
} from './types'
import { createDatabaseExecutor } from './executors'
import { QueryExecutor } from './executor'
import { QueryPlanner } from './query-planner'
import { formatSqlString } from '../adapters/utils'
import { CalculatedMeasureResolver } from './calculated-measure-resolver'
import { validateTemplateSyntax } from './template-substitution'
export class SemanticLayerCompiler {
private cubes: Map<string, Cube> = new Map()
private dbExecutor?: DatabaseExecutor
private metadataCache?: CubeMetadata[]
private cacheConfig?: CacheConfig
constructor(options?: {
drizzle?: DatabaseExecutor['db']
schema?: any
databaseExecutor?: DatabaseExecutor
engineType?: 'postgres' | 'mysql' | 'sqlite' | 'singlestore' | 'duckdb'
/** Cache configuration for query result caching */
cache?: CacheConfig
}) {
if (options?.databaseExecutor) {
this.dbExecutor = options.databaseExecutor
} else if (options?.drizzle) {
// Create database executor from Drizzle instance using the factory
this.dbExecutor = createDatabaseExecutor(
options.drizzle,
options.schema,
options.engineType
)
}
this.cacheConfig = options?.cache
}
/**
* Set or update the database executor
*/
setDatabaseExecutor(executor: DatabaseExecutor): void {
this.dbExecutor = executor
}
/**
* Get the database engine type for SQL formatting
*/
getEngineType(): 'postgres' | 'mysql' | 'sqlite' | 'singlestore' | 'duckdb' | undefined {
return this.dbExecutor?.getEngineType()
}
/**
* Set Drizzle instance and schema directly
*/
setDrizzle(db: DatabaseExecutor['db'], schema?: any, engineType?: 'postgres' | 'mysql' | 'sqlite' | 'singlestore' | 'duckdb'): void {
this.dbExecutor = createDatabaseExecutor(db, schema, engineType)
}
/**
* Check if database executor is configured
*/
hasExecutor(): boolean {
return !!this.dbExecutor
}
/**
* Register a simplified cube with dynamic query building
* Validates calculated measures during registration
*/
registerCube(cube: Cube): void {
// Debug: Log cube registration with meta
Iif (cube.meta) {
console.log(`[DEBUG] registerCube: ${cube.name} has meta:`, JSON.stringify(cube.meta))
}
// Validate calculated measures
this.validateCalculatedMeasures(cube)
// Auto-populate dependencies for calculated measures
const resolver = new CalculatedMeasureResolver(this.cubes)
resolver.populateDependencies(cube)
// Register the cube
this.cubes.set(cube.name, cube)
// Invalidate metadata cache when cubes change
this.invalidateMetadataCache()
}
/**
* Validate calculated measures in a cube
* Checks template syntax, dependency existence, and circular dependencies
*/
private validateCalculatedMeasures(cube: Cube): void {
const errors: string[] = []
// Check each measure
for (const [fieldName, measure] of Object.entries(cube.measures)) {
if (measure.type === 'calculated') {
// Validate calculatedSql exists
if (!measure.calculatedSql) {
errors.push(
`Calculated measure '${cube.name}.${fieldName}' must have calculatedSql property`
)
continue
}
// Validate template syntax
const syntaxValidation = validateTemplateSyntax(measure.calculatedSql)
if (!syntaxValidation.isValid) {
errors.push(
`Invalid calculatedSql syntax in '${cube.name}.${fieldName}': ${syntaxValidation.errors.join(', ')}`
)
continue
}
// Validate dependencies exist (using current cubes + this cube)
const tempCubes = new Map(this.cubes)
tempCubes.set(cube.name, cube)
const resolver = new CalculatedMeasureResolver(tempCubes)
try {
resolver.validateDependencies(cube)
} catch (err) {
errors.push(err instanceof Error ? err.message : String(err))
}
}
}
// Check for circular dependencies across all calculated measures in the cube
if (errors.length === 0) {
const tempCubes = new Map(this.cubes)
tempCubes.set(cube.name, cube)
const resolver = new CalculatedMeasureResolver(tempCubes)
resolver.buildGraph(cube)
const cycle = resolver.detectCycle()
if (cycle) {
errors.push(
`Circular dependency detected in calculated measures: ${cycle.join(' -> ')}`
)
}
}
// Throw if any validation errors
if (errors.length > 0) {
throw new Error(
`Calculated measure validation failed for cube '${cube.name}':\n${errors.join('\n')}`
)
}
}
/**
* Get a cube by name
*/
getCube(name: string): Cube | undefined {
return this.cubes.get(name)
}
/**
* Get all registered cubes
*/
getAllCubes(): Cube[] {
return Array.from(this.cubes.values())
}
/**
* Get all cubes as a Map for multi-cube queries
*/
getAllCubesMap(): Map<string, Cube> {
return this.cubes
}
/**
* Unified query execution method that handles both single and multi-cube queries
* @param options.skipCache - Skip cache lookup (but still cache the fresh result)
*/
async execute(
query: SemanticQuery,
securityContext: SecurityContext,
options?: ExecutionOptions
): Promise<QueryResult> {
Iif (!this.dbExecutor) {
throw new Error('Database executor not configured')
}
const executor = new QueryExecutor(this.dbExecutor, this.cacheConfig)
return executor.execute(this.cubes, query, securityContext, options)
}
/**
* Execute a multi-cube query
* @param options.skipCache - Skip cache lookup (but still cache the fresh result)
*/
async executeMultiCubeQuery(
query: SemanticQuery,
securityContext: SecurityContext,
options?: ExecutionOptions
): Promise<QueryResult> {
return this.execute(query, securityContext, options)
}
/**
* Execute a single cube query
*/
async executeQuery(
cubeName: string,
query: SemanticQuery,
securityContext: SecurityContext
): Promise<QueryResult> {
// Validate cube exists
const cube = this.cubes.get(cubeName)
if (!cube) {
throw new Error(`Cube '${cubeName}' not found`)
}
// Use unified execution which will auto-detect single cube and includes validation
return this.execute(query, securityContext)
}
/**
* Get metadata for all cubes (for API responses)
* Uses caching to improve performance for repeated requests
* Cache is invalidated when cubes are modified (registerCube, removeCube, clearCubes)
*/
getMetadata(): CubeMetadata[] {
// Return cached metadata if available
if (this.metadataCache) {
return this.metadataCache
}
// Generate and cache metadata
this.metadataCache = Array.from(this.cubes.values()).map(cube => this.generateCubeMetadata(cube))
return this.metadataCache
}
/**
* Extract column name from Drizzle column reference
* Handles different column types and extracts the actual column name
*/
private getColumnName(column: any): string {
// If it's a simple column object with name property
Eif (column && column.name) {
return column.name
}
// If it's a column with columnType and name
if (column && column.columnType && column.name) {
return column.name
}
// If it's a string, return as-is
if (typeof column === 'string') {
return column
}
// Fallback: try to extract from object properties
if (column && typeof column === 'object') {
// Try common property names
if (column._.name) return column._.name
if (column.name) return column.name
if (column.columnName) return column.columnName
}
// If we can't determine the column name, return a fallback
return 'unknown_column'
}
/**
* Default time granularities for time dimensions (ordered from least to most granular)
* Used when dimension.granularities is not specified
*/
private static readonly DEFAULT_TIME_GRANULARITIES: TimeGranularity[] = [
'year', 'quarter', 'month', 'week', 'day', 'hour'
]
/**
* Generate cube metadata for API responses from cubes
* Optimized version that minimizes object iterations
* Includes drill-down support: drillMembers on measures, granularities on time dimensions, hierarchies
*/
private generateCubeMetadata(cube: Cube): CubeMetadata {
// Pre-allocate arrays for better performance
const measureKeys = Object.keys(cube.measures)
const dimensionKeys = Object.keys(cube.dimensions)
const measures: MeasureMetadata[] = new Array(measureKeys.length)
const dimensions: DimensionMetadata[] = new Array(dimensionKeys.length)
// Process measures efficiently - include drillMembers for drill-down support
for (let i = 0; i < measureKeys.length; i++) {
const key = measureKeys[i]
const measure = cube.measures[key]
// Normalize drillMembers to full qualified names (CubeName.fieldName)
let drillMembers: string[] | undefined
Iif (measure.drillMembers && measure.drillMembers.length > 0) {
drillMembers = measure.drillMembers.map(member => {
// If already qualified (contains dot), use as-is
if (member.includes('.')) {
return member
}
// Otherwise, prefix with cube name
return `${cube.name}.${member}`
})
}
measures[i] = {
name: `${cube.name}.${key}`,
title: measure.title || key,
shortTitle: measure.title || key,
type: measure.type,
format: undefined, // Measure doesn't have format field
description: measure.description,
synonyms: measure.synonyms,
drillMembers
}
}
// Process dimensions efficiently - include granularities for time dimensions
for (let i = 0; i < dimensionKeys.length; i++) {
const key = dimensionKeys[i]
const dimension = cube.dimensions[key]
// For time dimensions, include granularities (use defaults if not specified)
let granularities: TimeGranularity[] | undefined
if (dimension.type === 'time') {
granularities = dimension.granularities || SemanticLayerCompiler.DEFAULT_TIME_GRANULARITIES
}
dimensions[i] = {
name: `${cube.name}.${key}`,
title: dimension.title || key,
shortTitle: dimension.title || key,
type: dimension.type,
format: undefined, // Dimension doesn't have format field
description: dimension.description,
synonyms: dimension.synonyms,
granularities
}
}
// Process relationships if they exist
const relationships: CubeRelationshipMetadata[] = []
Eif (cube.joins) {
for (const [, join] of Object.entries(cube.joins)) {
const targetCube = typeof join.targetCube === 'function' ? join.targetCube() : join.targetCube
relationships.push({
targetCube: targetCube.name,
relationship: join.relationship,
joinFields: join.on.map(condition => ({
sourceField: this.getColumnName(condition.source),
targetField: this.getColumnName(condition.target)
}))
})
}
}
// Process hierarchies if they exist - convert to full qualified names
const hierarchies: HierarchyMetadata[] = []
Iif (cube.hierarchies) {
for (const [, hierarchy] of Object.entries(cube.hierarchies)) {
hierarchies.push({
name: hierarchy.name,
title: hierarchy.title || hierarchy.name,
cubeName: cube.name,
// Convert level names to full qualified names
levels: hierarchy.levels.map(level => {
if (level.includes('.')) {
return level
}
return `${cube.name}.${level}`
})
})
}
}
const result: CubeMetadata = {
name: cube.name,
title: cube.title || cube.name,
description: cube.description,
exampleQuestions: cube.exampleQuestions,
measures,
dimensions,
segments: [], // Add segments support later if needed
relationships: relationships.length > 0 ? relationships : undefined,
hierarchies: hierarchies.length > 0 ? hierarchies : undefined,
meta: cube.meta
}
// Debug: Log if cube has meta
Iif (cube.meta) {
console.log(`[DEBUG] Cube ${cube.name} has meta:`, JSON.stringify(cube.meta))
}
return result
}
/**
* Get SQL for a query without executing it (debugging)
*/
async generateSQL(
cubeName: string,
query: SemanticQuery,
securityContext: SecurityContext
): Promise<{ sql: string; params?: any[] }> {
const cube = this.getCube(cubeName)
Iif (!cube) {
throw new Error(`Cube '${cubeName}' not found`)
}
Iif (!this.dbExecutor) {
throw new Error('Database executor not configured')
}
const executor = new QueryExecutor(this.dbExecutor)
const result = await executor.generateSQL(cube, query, securityContext)
// Format the SQL using the appropriate dialect
const engineType = this.dbExecutor.getEngineType()
return {
sql: formatSqlString(result.sql, engineType),
params: result.params
}
}
/**
* Get SQL for a multi-cube query without executing it (debugging)
*/
async generateMultiCubeSQL(
query: SemanticQuery,
securityContext: SecurityContext
): Promise<{ sql: string; params?: any[] }> {
if (!this.dbExecutor) {
throw new Error('Database executor not configured')
}
const executor = new QueryExecutor(this.dbExecutor)
const result = await executor.generateMultiCubeSQL(this.cubes, query, securityContext)
// Format the SQL using the appropriate dialect
const engineType = this.dbExecutor.getEngineType()
return {
sql: formatSqlString(result.sql, engineType),
params: result.params
}
}
/**
* Get SQL for a funnel query without executing it (debugging)
* Returns the actual CTE-based SQL that would be executed for funnel queries
*/
async dryRunFunnel(
query: SemanticQuery,
securityContext: SecurityContext
): Promise<{ sql: string; params?: any[] }> {
if (!this.dbExecutor) {
throw new Error('Database executor not configured')
}
const executor = new QueryExecutor(this.dbExecutor)
const result = await executor.dryRunFunnel(this.cubes, query, securityContext)
// Format the SQL using the appropriate dialect
const engineType = this.dbExecutor.getEngineType()
return {
sql: formatSqlString(result.sql, engineType),
params: result.params
}
}
/**
* Get SQL for a flow query without executing it (debugging)
* Returns the actual CTE-based SQL that would be executed for flow queries
*/
async dryRunFlow(
query: SemanticQuery,
securityContext: SecurityContext
): Promise<{ sql: string; params?: any[] }> {
if (!this.dbExecutor) {
throw new Error('Database executor not configured')
}
const executor = new QueryExecutor(this.dbExecutor)
const result = await executor.dryRunFlow(this.cubes, query, securityContext)
// Format the SQL using the appropriate dialect
const engineType = this.dbExecutor.getEngineType()
return {
sql: formatSqlString(result.sql, engineType),
params: result.params
}
}
/**
* Generate SQL for a retention query without execution (dry-run)
* Returns the CTE-based SQL that would be executed for retention analysis
*/
async dryRunRetention(
query: SemanticQuery,
securityContext: SecurityContext
): Promise<{ sql: string; params?: any[] }> {
if (!this.dbExecutor) {
throw new Error('Database executor not configured')
}
const executor = new QueryExecutor(this.dbExecutor)
const result = await executor.dryRunRetention(this.cubes, query, securityContext)
// Format the SQL using the appropriate dialect
const engineType = this.dbExecutor.getEngineType()
return {
sql: formatSqlString(result.sql, engineType),
params: result.params
}
}
/**
* Execute EXPLAIN on a query to get the execution plan
* Uses the same secure path as execute/dryRun to generate SQL,
* then runs database EXPLAIN on it.
*/
async explainQuery(
query: SemanticQuery,
securityContext: SecurityContext,
options?: ExplainOptions
): Promise<ExplainResult> {
if (!this.dbExecutor) {
throw new Error('Database executor not configured')
}
const executor = new QueryExecutor(this.dbExecutor)
return executor.explainQuery(this.cubes, query, securityContext, options)
}
/**
* Check if a cube exists
*/
hasCube(name: string): boolean {
return this.cubes.has(name)
}
/**
* Remove a cube
*/
removeCube(name: string): boolean {
const result = this.cubes.delete(name)
if (result) {
this.invalidateMetadataCache()
}
return result
}
/**
* Clear all cubes
*/
clearCubes(): void {
this.cubes.clear()
this.invalidateMetadataCache()
}
/**
* Invalidate the metadata cache
* Called whenever cubes are modified
*/
private invalidateMetadataCache(): void {
this.metadataCache = undefined
}
/**
* Get cube names
*/
getCubeNames(): string[] {
return Array.from(this.cubes.keys())
}
/**
* Validate a query against registered cubes
* Ensures all referenced cubes and fields exist
*/
validateQuery(query: SemanticQuery): { isValid: boolean; errors: string[] } {
return validateQueryAgainstCubes(this.cubes, query)
}
/**
* Analyze query planning decisions for debugging and transparency
* Returns detailed metadata about how the query would be planned
* Used by the playground UI to help users understand query structure
*/
analyzeQuery(
query: SemanticQuery,
securityContext: SecurityContext
): QueryAnalysis {
Iif (!this.dbExecutor) {
throw new Error('Database executor not configured')
}
const planner = new QueryPlanner()
const ctx = {
db: this.dbExecutor.db,
schema: this.dbExecutor.schema,
securityContext
}
return planner.analyzeQueryPlan(this.cubes, query, ctx)
}
}
/**
* Validate a query against a cubes map
* Standalone function that can be used by both compiler and executor
*/
export function validateQueryAgainstCubes(
cubes: Map<string, Cube>,
query: SemanticQuery
): { isValid: boolean; errors: string[] } {
const errors: string[] = []
// Check for funnel queries - these have their own validation path
// Skip standard validation for funnel queries (validated separately in executor)
Iif (query.funnel !== undefined && query.funnel.steps?.length >= 2) {
// Basic funnel validation here - full validation happens in executor
// Just ensure the cube referenced by bindingKey exists
const bindingKey = query.funnel.bindingKey
if (typeof bindingKey === 'string') {
const [cubeName] = bindingKey.split('.')
if (cubeName && !cubes.has(cubeName)) {
errors.push(`Funnel binding key cube not found: ${cubeName}`)
}
} else if (Array.isArray(bindingKey)) {
for (const mapping of bindingKey) {
if (!cubes.has(mapping.cube)) {
errors.push(`Funnel binding key cube not found: ${mapping.cube}`)
}
}
}
return { isValid: errors.length === 0, errors }
}
// Check for flow queries - these have their own validation path
// Skip standard validation for flow queries (validated separately in executor)
Iif (query.flow !== undefined && query.flow.startingStep !== undefined && query.flow.eventDimension !== undefined) {
// Basic flow validation here - full validation happens in executor
// Just ensure the cube referenced by bindingKey exists
const bindingKey = query.flow.bindingKey
if (typeof bindingKey === 'string') {
const [cubeName] = bindingKey.split('.')
if (cubeName && !cubes.has(cubeName)) {
errors.push(`Flow binding key cube not found: ${cubeName}`)
}
}
return { isValid: errors.length === 0, errors }
}
// Check for retention queries - these have their own validation path
// Skip standard validation for retention queries (validated separately in executor)
Iif (query.retention !== undefined &&
query.retention.timeDimension != null &&
query.retention.bindingKey != null) {
// Validate cube from time dimension exists
const cubeName = extractCubeFromRetentionTimeDimension(query.retention.timeDimension)
if (cubeName && !cubes.has(cubeName)) {
errors.push(`Retention cube not found: ${cubeName}`)
}
// Validate binding key cube(s) exist
const bindingKey = query.retention.bindingKey
if (typeof bindingKey === 'string') {
const [bkCubeName] = bindingKey.split('.')
if (bkCubeName && !cubes.has(bkCubeName)) {
errors.push(`Retention binding key cube not found: ${bkCubeName}`)
}
} else if (Array.isArray(bindingKey)) {
for (const mapping of bindingKey) {
if (!cubes.has(mapping.cube)) {
errors.push(`Retention binding key cube not found: ${mapping.cube}`)
}
}
}
// Validate breakdown dimension cubes exist
if (query.retention.breakdownDimensions && Array.isArray(query.retention.breakdownDimensions)) {
for (const dim of query.retention.breakdownDimensions) {
const [bdCubeName] = dim.split('.')
if (bdCubeName && !cubes.has(bdCubeName)) {
errors.push(`Retention breakdown cube not found: ${bdCubeName}`)
}
}
}
return { isValid: errors.length === 0, errors }
}
// Track all referenced cubes
const referencedCubes = new Set<string>()
// Validate measures
if (query.measures) {
for (const measure of query.measures) {
const [cubeName, fieldName] = measure.split('.')
if (!cubeName || !fieldName) {
errors.push(`Invalid measure format: ${measure}. Expected format: 'CubeName.fieldName'`)
continue
}
referencedCubes.add(cubeName)
// Check if cube exists
const cube = cubes.get(cubeName)
if (!cube) {
errors.push(`Cube '${cubeName}' not found (referenced in measure '${measure}')`)
continue
}
// Check if measure exists on cube
if (!cube.measures[fieldName]) {
errors.push(`Measure '${fieldName}' not found on cube '${cubeName}'`)
}
}
}
// Validate dimensions
if (query.dimensions) {
for (const dimension of query.dimensions) {
const [cubeName, fieldName] = dimension.split('.')
if (!cubeName || !fieldName) {
errors.push(`Invalid dimension format: ${dimension}. Expected format: 'CubeName.fieldName'`)
continue
}
referencedCubes.add(cubeName)
// Check if cube exists
const cube = cubes.get(cubeName)
if (!cube) {
errors.push(`Cube '${cubeName}' not found (referenced in dimension '${dimension}')`)
continue
}
// Check if dimension exists on cube
if (!cube.dimensions[fieldName]) {
errors.push(`Dimension '${fieldName}' not found on cube '${cubeName}'`)
}
}
}
// Validate timeDimensions
if (query.timeDimensions) {
for (const timeDimension of query.timeDimensions) {
const [cubeName, fieldName] = timeDimension.dimension.split('.')
if (!cubeName || !fieldName) {
errors.push(`Invalid timeDimension format: ${timeDimension.dimension}. Expected format: 'CubeName.fieldName'`)
continue
}
referencedCubes.add(cubeName)
// Check if cube exists
const cube = cubes.get(cubeName)
if (!cube) {
errors.push(`Cube '${cubeName}' not found (referenced in timeDimension '${timeDimension.dimension}')`)
continue
}
// Check if dimension exists on cube (timeDimensions reference dimensions)
if (!cube.dimensions[fieldName]) {
errors.push(`TimeDimension '${fieldName}' not found on cube '${cubeName}' (must be a dimension with time type)`)
}
}
}
// Validate filters
if (query.filters) {
for (const filter of query.filters) {
validateFilter(filter, cubes, errors, referencedCubes)
}
}
// Ensure at least one cube is referenced
if (referencedCubes.size === 0) {
errors.push('Query must reference at least one cube through measures, dimensions, or filters')
}
return {
isValid: errors.length === 0,
errors
}
}
/**
* Validate a single filter (recursive for logical filters)
*/
function validateFilter(
filter: any,
cubes: Map<string, Cube>,
errors: string[],
referencedCubes: Set<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) {
validateFilter(subFilter, cubes, errors, referencedCubes)
}
return
}
// Handle simple filter condition
if (!('member' in filter)) {
errors.push('Filter must have a member field')
return
}
const [cubeName, fieldName] = filter.member.split('.')
if (!cubeName || !fieldName) {
errors.push(`Invalid filter member format: ${filter.member}. Expected format: 'CubeName.fieldName'`)
return
}
referencedCubes.add(cubeName)
// Check if cube exists
const cube = cubes.get(cubeName)
if (!cube) {
errors.push(`Cube '${cubeName}' not found (referenced in filter '${filter.member}')`)
return
}
// Check if field exists on cube (can be dimension or measure)
if (!cube.dimensions[fieldName] && !cube.measures[fieldName]) {
errors.push(`Filter field '${fieldName}' not found on cube '${cubeName}' (must be a dimension or measure)`)
}
}
/**
* Extract cube name from retention time dimension (string or object format)
*/
function extractCubeFromRetentionTimeDimension(
timeDim: string | { cube: string; dimension: string }
): string | null {
if (typeof timeDim === 'string') {
const [cubeName] = timeDim.split('.')
return cubeName || null
}
return timeDim.cube
}
|