All files server/calculated-measure-resolver.ts

94.21% Statements 114/121
87.3% Branches 55/63
92.85% Functions 13/14
94.06% Lines 111/118

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                                                                                          2783x 2783x                       165x 165x 165x   165x 279x     279x                   279x               165x                 2843x 28879x 69x     69x 69x   69x   123x 123x 123x       69x                 2843x                                     2843x 69x       2843x 69x 123x 123x 24x                               27x 27x 27x     27x 33x 33x 33x                   27x 33x 33x 63x 9x     33x         27x 33x 27x         27x 33x 33x       33x 51x 9x 9x 6x             27x             27x                   360x 360x 360x   360x 33x 33x 33x 3x         357x                       78x 78x 78x   78x 78x 42x 42x 42x     36x 60x 45x 45x 3x   15x   3x 3x       30x 30x 30x                   27x 27x   27x 90x 84x   84x 84x   33x 63x 63x       27x 27x                   42x 117x 66x   66x 102x 102x   102x           102x 102x 3x           99x 3x                               357x 2724x 30x 54x                       5446x      
/**
 * Calculated Measure Resolver
 *
 * Handles dependency resolution for calculated measures:
 * - Extracts {member} references from calculatedSql templates
 * - Builds dependency graph
 * - Performs topological sorting to determine calculation order
 * - Detects circular dependencies
 */
 
import type { Cube, Measure } from './types/cube'
 
/**
 * Dependency information for a calculated measure
 */
export interface MeasureDependency {
  /** Full measure name (e.g., "Cube.measure" or "measure") */
  measureName: string
  /** Referenced cube name (null if same cube) */
  cubeName: string | null
  /** Referenced field name */
  fieldName: string
}
 
/**
 * Dependency graph node
 */
interface GraphNode {
  /** Full measure identifier */
  id: string
  /** List of dependencies (what this measure depends on) */
  dependencies: Set<string>
  /** Incoming edge count for topological sort */
  inDegree: number
}
 
/**
 * Calculated Measure Resolver
 * Manages dependency resolution for calculated measures
 */
export class CalculatedMeasureResolver {
  private dependencyGraph: Map<string, GraphNode>
  private cubes: Map<string, Cube>
 
  constructor(cubes: Map<string, Cube> | Cube) {
    this.cubes = cubes instanceof Map ? cubes : new Map([[cubes.name, cubes]])
    this.dependencyGraph = new Map()
  }
 
  /**
   * Extract {member} references from calculatedSql template
   * Supports both {measure} and {Cube.measure} syntax
   *
   * @param calculatedSql - Template string with {member} references
   * @returns Array of dependency information
   */
  extractDependencies(calculatedSql: string): MeasureDependency[] {
    // Match {member} or {Cube.member} patterns
    const regex = /\{([^}]+)\}/g
    const matches = calculatedSql.matchAll(regex)
    const dependencies: MeasureDependency[] = []
 
    for (const match of matches) {
      const memberRef = match[1].trim()
 
      // Parse member reference
      Iif (memberRef.includes('.')) {
        // Cross-cube reference: {Cube.measure}
        const [cubeName, fieldName] = memberRef.split('.')
        dependencies.push({
          measureName: memberRef,
          cubeName: cubeName.trim(),
          fieldName: fieldName.trim()
        })
      } else {
        // Same-cube reference: {measure}
        dependencies.push({
          measureName: memberRef,
          cubeName: null,
          fieldName: memberRef
        })
      }
    }
 
    return dependencies
  }
 
  /**
   * Build dependency graph for all calculated measures in a cube
   *
   * @param cube - The cube containing measures
   */
  buildGraph(cube: Cube): void {
    for (const [fieldName, measure] of Object.entries(cube.measures)) {
      if (measure.type === 'calculated' && measure.calculatedSql) {
        const measureId = `${cube.name}.${fieldName}`
 
        // Extract dependencies
        const deps = this.extractDependencies(measure.calculatedSql)
        const depSet = new Set<string>()
 
        for (const dep of deps) {
          // Resolve to full measure ID
          const depCubeName = dep.cubeName || cube.name
          const depId = `${depCubeName}.${dep.fieldName}`
          depSet.add(depId)
        }
 
        // Add to graph
        this.dependencyGraph.set(measureId, {
          id: measureId,
          dependencies: depSet,
          inDegree: 0
        })
      }
    }
 
    // Calculate in-degrees
    this.calculateInDegrees()
  }
 
  /**
   * Build dependency graph for multiple cubes
   *
   * @param cubes - Map of cubes to analyze
   */
  buildGraphForMultipleCubes(cubes: Map<string, Cube>): void {
    for (const cube of cubes.values()) {
      this.buildGraph(cube)
    }
  }
 
  /**
   * Calculate in-degree for each node (number of measures depending on it)
   */
  private calculateInDegrees(): void {
    // Reset all in-degrees to 0
    for (const node of this.dependencyGraph.values()) {
      node.inDegree = 0
    }
 
    // Count incoming edges
    for (const node of this.dependencyGraph.values()) {
      for (const depId of node.dependencies) {
        const depNode = this.dependencyGraph.get(depId)
        if (depNode) {
          depNode.inDegree++
        }
      }
    }
  }
 
  /**
   * Perform topological sort using Kahn's algorithm
   * Returns measures in dependency order (dependencies first)
   *
   * @param measureNames - List of measure names to sort
   * @returns Sorted array of measure names
   * @throws Error if circular dependency detected
   */
  topologicalSort(measureNames: string[]): string[] {
    // Build subgraph for requested measures only
    const subgraph = new Map<string, GraphNode>()
    const queue: string[] = []
    const sorted: string[] = []
 
    // Initialize subgraph with dependencies copied from main graph
    for (const measureName of measureNames) {
      const node = this.dependencyGraph.get(measureName)
      Eif (node) {
        subgraph.set(measureName, {
          id: node.id,
          dependencies: new Set(node.dependencies),
          inDegree: 0  // Will recalculate below
        })
      }
    }
 
    // Calculate in-degrees within the subgraph
    // In-degree = number of dependencies that are IN the subgraph
    for (const node of subgraph.values()) {
      let inDegree = 0
      for (const depId of node.dependencies) {
        if (subgraph.has(depId)) {
          inDegree++
        }
      }
      node.inDegree = inDegree
    }
 
    // Find nodes with no dependencies within the subgraph (in-degree = 0)
    // These are ready to be processed immediately
    for (const [id, node] of subgraph) {
      if (node.inDegree === 0) {
        queue.push(id)
      }
    }
 
    // Process queue using Kahn's algorithm
    while (queue.length > 0) {
      const currentId = queue.shift()!
      sorted.push(currentId)
 
      // Find all nodes in the subgraph that depend on the current node
      // and decrease their in-degree since we've now processed their dependency
      for (const [nodeId, node] of subgraph) {
        if (node.dependencies.has(currentId)) {
          node.inDegree--
          if (node.inDegree === 0) {
            queue.push(nodeId)
          }
        }
      }
    }
 
    // Check if all nodes were processed
    Iif (sorted.length < subgraph.size) {
      const cycle = this.detectCycle()
      throw new Error(
        `Circular dependency detected in calculated measures: ${cycle ? cycle.join(' -> ') : 'unknown cycle'}`
      )
    }
 
    return sorted
  }
 
  /**
   * Detect circular dependencies using DFS
   * Returns the cycle path if found, null otherwise
   *
   * @returns Array representing the cycle, or null
   */
  detectCycle(): string[] | null {
    const visited = new Set<string>()
    const recursionStack = new Set<string>()
    const path: string[] = []
 
    for (const nodeId of this.dependencyGraph.keys()) {
      Eif (!visited.has(nodeId)) {
        const cycle = this.dfs(nodeId, visited, recursionStack, path)
        if (cycle) {
          return cycle
        }
      }
    }
 
    return null
  }
 
  /**
   * DFS helper for cycle detection
   */
  private dfs(
    nodeId: string,
    visited: Set<string>,
    recursionStack: Set<string>,
    path: string[]
  ): string[] | null {
    visited.add(nodeId)
    recursionStack.add(nodeId)
    path.push(nodeId)
 
    const node = this.dependencyGraph.get(nodeId)
    if (!node) {
      path.pop()
      recursionStack.delete(nodeId)
      return null
    }
 
    for (const depId of node.dependencies) {
      if (!visited.has(depId)) {
        const cycle = this.dfs(depId, visited, recursionStack, path)
        if (cycle) {
          return cycle
        }
      } else if (recursionStack.has(depId)) {
        // Found a cycle
        const cycleStart = path.indexOf(depId)
        return [...path.slice(cycleStart), depId]
      }
    }
 
    path.pop()
    recursionStack.delete(nodeId)
    return null
  }
 
  /**
   * Get all dependencies for a specific measure (direct and transitive)
   *
   * @param measureName - Full measure name (e.g., "Cube.measure")
   * @returns Set of all dependency measure names
   */
  getAllDependencies(measureName: string): Set<string> {
    const allDeps = new Set<string>()
    const visited = new Set<string>()
 
    const collectDeps = (id: string) => {
      if (visited.has(id)) return
      visited.add(id)
 
      const node = this.dependencyGraph.get(id)
      if (!node) return
 
      for (const depId of node.dependencies) {
        allDeps.add(depId)
        collectDeps(depId)
      }
    }
 
    collectDeps(measureName)
    return allDeps
  }
 
  /**
   * Validate that all dependencies exist
   *
   * @param cube - The cube to validate
   * @throws Error if dependencies are missing
   */
  validateDependencies(cube: Cube): void {
    for (const [fieldName, measure] of Object.entries(cube.measures)) {
      if (measure.type === 'calculated' && measure.calculatedSql) {
        const deps = this.extractDependencies(measure.calculatedSql)
 
        for (const dep of deps) {
          const targetCubeName = dep.cubeName || cube.name
          const targetCube = this.cubes.get(targetCubeName)
 
          Iif (!targetCube) {
            throw new Error(
              `Calculated measure '${cube.name}.${fieldName}' references unknown cube '${targetCubeName}'`
            )
          }
 
          const targetMeasure = targetCube.measures[dep.fieldName]
          if (!targetMeasure) {
            throw new Error(
              `Calculated measure '${cube.name}.${fieldName}' references unknown measure '${dep.measureName}'`
            )
          }
 
          // Prevent self-reference
          if (targetCubeName === cube.name && dep.fieldName === fieldName) {
            throw new Error(
              `Calculated measure '${cube.name}.${fieldName}' cannot reference itself`
            )
          }
        }
      }
    }
  }
 
  /**
   * Auto-populate dependencies array for calculated measures
   * Updates the measure objects with detected dependencies
   *
   * @param cube - The cube to update
   */
  populateDependencies(cube: Cube): void {
    for (const [, measure] of Object.entries(cube.measures)) {
      if (measure.type === 'calculated' && measure.calculatedSql && !measure.dependencies) {
        const deps = this.extractDependencies(measure.calculatedSql)
        measure.dependencies = deps.map(d => d.measureName)
      }
    }
  }
 
  /**
   * Check if a measure is a calculated measure
   *
   * @param measure - The measure to check
   * @returns True if the measure is calculated
   */
  static isCalculatedMeasure(measure: Measure): boolean {
    return measure.type === 'calculated' && !!measure.calculatedSql
  }
}