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 | 357x 357x 357x 9x 348x 303x 126x 372x 372x 372x 372x 372x 372x 372x 2745x 48x 3x 3x 45x 45x 3x 3x 42x 42x 42x 42x 42x 6x 372x 360x 360x 360x 360x 360x 360x 3x 372x 15x 51x 141x 141x 141x 141x 42x 42x 42x 42x 42x 42x 168x 168x 42x 42x 42x 42x 42x 336x 336x 336x 42x 378x 378x 378x 42x 42x 42x 168x 168x 84x 42x 51x 51x 51x 51x 51x 51x 51x 357x 357x 309x 27x 27x 27x 27x 1967x 1967x 1967x 1922x 2576x 2576x 54x 54x 2522x 2522x 2522x 60x 60x 2462x 33x 1964x 738x 879x 879x 12x 12x 867x 867x 867x 6x 6x 861x 24x 1961x 318x 339x 339x 3x 3x 336x 336x 336x 3x 3x 333x 6x 1961x 941x 972x 1955x 33x 1955x 2490x 705x 705x 1518x 705x 1782x 6x 6x 1776x 1776x 6x 6x 1767x 1767x 1767x 9x 9x 1758x 45x | /**
* Semantic Layer Compiler
* Drizzle ORM-first cube compilation and registration with type safety
*/
import type {
SemanticQuery,
QueryResult,
SecurityContext,
DatabaseExecutor,
CubeMetadata,
MeasureMetadata,
DimensionMetadata,
CubeRelationshipMetadata,
Cube,
QueryAnalysis
} 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 metadataCacheTimestamp?: number
private readonly METADATA_CACHE_TTL = 5 * 60 * 1000 // 5 minutes in milliseconds
constructor(options?: {
drizzle?: DatabaseExecutor['db']
schema?: any
databaseExecutor?: DatabaseExecutor
engineType?: 'postgres' | 'mysql' | 'sqlite' | 'singlestore'
}) {
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
)
}
}
/**
* 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' | undefined {
return this.dbExecutor?.getEngineType()
}
/**
* Set Drizzle instance and schema directly
*/
setDrizzle(db: DatabaseExecutor['db'], schema?: any, engineType?: 'postgres' | 'mysql' | 'sqlite' | 'singlestore'): 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 {
// 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
*/
async execute(
query: SemanticQuery,
securityContext: SecurityContext
): Promise<QueryResult> {
Iif (!this.dbExecutor) {
throw new Error('Database executor not configured')
}
const executor = new QueryExecutor(this.dbExecutor)
return executor.execute(this.cubes, query, securityContext)
}
/**
* Execute a multi-cube query
*/
async executeMultiCubeQuery(
query: SemanticQuery,
securityContext: SecurityContext
): Promise<QueryResult> {
return this.execute(query, securityContext)
}
/**
* 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
*/
getMetadata(): CubeMetadata[] {
const now = Date.now()
// Check if cache is valid
Iif (this.metadataCache && this.metadataCacheTimestamp &&
(now - this.metadataCacheTimestamp) < this.METADATA_CACHE_TTL) {
return this.metadataCache
}
// Generate fresh metadata
const metadata = Array.from(this.cubes.values()).map(cube => this.generateCubeMetadata(cube))
// Update cache
this.metadataCache = metadata
this.metadataCacheTimestamp = now
return metadata
}
/**
* 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'
}
/**
* Generate cube metadata for API responses from cubes
* Optimized version that minimizes object iterations
*/
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
for (let i = 0; i < measureKeys.length; i++) {
const key = measureKeys[i]
const measure = cube.measures[key]
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
}
}
// Process dimensions efficiently
for (let i = 0; i < dimensionKeys.length; i++) {
const key = dimensionKeys[i]
const dimension = cube.dimensions[key]
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
}
}
// 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)
}))
})
}
}
return {
name: cube.name,
title: cube.title || cube.name,
description: cube.description,
measures,
dimensions,
segments: [], // Add segments support later if needed
relationships: relationships.length > 0 ? relationships : undefined
}
}
/**
* 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
}
}
/**
* 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
this.metadataCacheTimestamp = 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[] = []
// 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)`)
}
}
|