All files / server/types cube.ts

0% Statements 0/0
0% Branches 0/0
0% Functions 0/0
0% Lines 0/0

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
/**
 * Cube, dimension, measure, and join definitions
 * Core semantic layer building blocks
 */
 
import type { SQL, AnyColumn, Table, Subquery, View } from 'drizzle-orm'
import type {
  SecurityContext,
  DrizzleDatabase,
  QueryResult,
  MeasureType,
  DimensionType,
  TimeGranularity
} from './core'
import type { SemanticQuery } from './query'
import type { FilterCacheManager } from '../filter-cache'
 
/**
 * Any queryable relation that can be used in FROM/JOIN clauses
 * Supports tables, views, subqueries, and raw SQL expressions
 */
export type QueryableRelation = Table | View | Subquery | SQL
 
/**
 * Base query definition that can be extended dynamically
 * Returns just the FROM/JOIN/WHERE setup, not a complete SELECT
 */
export interface BaseQueryDefinition {
  /** Main table to query from */
  from: QueryableRelation
  /** Optional joins to other tables */
  joins?: Array<{
    table: QueryableRelation
    on: SQL
    type?: 'left' | 'right' | 'inner' | 'full'
  }>
  /** Base WHERE conditions (typically security context filtering) */
  where?: SQL
}
 
/**
 * Query context passed to cube SQL functions
 * Provides access to database, schema, and security context
 */
export interface QueryContext {
  /** Drizzle database instance */
  db: DrizzleDatabase
  /** Database schema (tables, columns, etc.) */
  schema?: any
  /** Security context for filtering */
  securityContext: SecurityContext
  /** The semantic query being executed */
  query?: SemanticQuery
  /** The compiled cube being queried */
  cube?: Cube
  /**
   * Filter cache for parameter deduplication across CTEs
   * Created at query start and used throughout query building
   */
  filterCache?: FilterCacheManager
}
 
/**
 * Multi-cube query context for cross-cube operations
 */
export interface MultiCubeQueryContext 
  extends QueryContext {
  /** Available cubes for cross-cube operations */
  cubes: Map<string, Cube>
  /** Current cube being processed */
  currentCube: Cube
}
 
/**
 * Hierarchy definition for grouped drill-down paths
 * Groups dimensions into ordered levels for structured navigation
 */
export interface Hierarchy {
  /** Unique identifier for the hierarchy */
  name: string
  /** Display title for the hierarchy */
  title?: string
  /**
   * Dimension names in order from least to most granular
   * @example ['country', 'region', 'city'] for geographic hierarchy
   * @example ['category', 'subcategory', 'product'] for product hierarchy
   */
  levels: string[]
}
 
/**
 * Cube definition focused on Drizzle query building
 */
export interface Cube {
  name: string
  title?: string
  description?: string
 
  /**
   * Example questions that can be answered using this cube
   * Used by AI agents to understand cube capabilities
   * @example ['What was total revenue last month?', 'Show me sales by category']
   */
  exampleQuestions?: string[]
 
  /**
   * Base query setup - returns the foundation that can be extended
   * Should return FROM/JOIN/WHERE setup, NOT a complete SELECT
   */
  sql: (ctx: QueryContext) => BaseQueryDefinition
 
  /** Cube dimensions using direct column references */
  dimensions: Record<string, Dimension>
 
  /** Cube measures using direct column references */
  measures: Record<string, Measure>
 
  /** Optional joins to other cubes for multi-cube queries */
  joins?: Record<string, CubeJoin>
 
  /**
   * Hierarchies for structured drill-down paths
   * Groups dimensions into levels for navigation (e.g., country -> region -> city)
   * A dimension can appear in multiple hierarchies
   */
  hierarchies?: Record<string, Hierarchy>
 
  /** Whether cube is publicly accessible */
  public?: boolean
 
  /** SQL alias for the cube */
  sqlAlias?: string
 
  /** Data source identifier */
  dataSource?: string
 
  /** Additional metadata */
  meta?: Record<string, any>
}
 
/**
 * Dimension definition
 */
export interface Dimension {
  name: string
  title?: string
  description?: string
 
  /**
   * Alternative names for this dimension
   * Used by AI agents for natural language matching
   * @example ['date', 'day', 'timestamp'] for a createdAt dimension
   */
  synonyms?: string[]
 
  type: DimensionType
 
  /** Direct column reference or SQL expression */
  sql: AnyColumn | SQL | ((ctx: QueryContext) => AnyColumn | SQL)
 
  /** Whether this is a primary key */
  primaryKey?: boolean
 
  /** Whether to show in UI */
  shown?: boolean
 
  /** Display format */
  format?: string
 
  /** Additional metadata */
  meta?: Record<string, any>
 
  /**
   * Supported granularities for time dimensions
   * If not specified for time dimensions, defaults to ['year', 'quarter', 'month', 'week', 'day']
   * Only applies when type is 'time'
   * @example ['year', 'quarter', 'month', 'day'] for a custom subset
   */
  granularities?: TimeGranularity[]
}
 
/**
 * Measure definition
 */
export interface Measure {
  name: string
  title?: string
  description?: string
 
  /**
   * Alternative names for this measure
   * Used by AI agents for natural language matching
   * @example ['revenue', 'sales', 'income'] for a totalRevenue measure
   */
  synonyms?: string[]
 
  type: MeasureType
 
  /**
   * Column to aggregate or SQL expression
   * Optional for calculated measures (type: 'calculated') which use calculatedSql instead
   */
  sql?: AnyColumn | SQL | ((ctx: QueryContext) => AnyColumn | SQL)
 
  /** Display format */
  format?: string
 
  /** Whether to show in UI */
  shown?: boolean
 
  /** Filters applied to this measure */
  filters?: Array<(ctx: QueryContext) => SQL>
 
  /** Rolling window configuration */
  rollingWindow?: {
    trailing?: string
    leading?: string
    offset?: string
  }
 
  /**
   * Calculated measure template with {member} references
   * Only used when type === 'calculated'
   * Example: "1.0 * {completed} / NULLIF({total}, 0)"
   */
  calculatedSql?: string
 
  /**
   * List of measure dependencies for calculated measures
   * Auto-detected from calculatedSql if not provided
   * Example: ['completed', 'total']
   */
  dependencies?: string[]
 
  /** Additional metadata */
  meta?: Record<string, any>
 
  /**
   * Dimension names shown when drilling into this measure
   * Can include cross-cube dimensions via joins (e.g., 'Products.name', 'Users.email')
   * If not specified, drilling is disabled for this measure
   * @example ['id', 'status', 'createdAt'] for same-cube dimensions
   * @example ['Orders.id', 'Products.name', 'Users.city'] for cross-cube dimensions
   */
  drillMembers?: string[]
 
  /**
   * Statistical function configuration
   * Used for percentile, stddev, variance measure types
   */
  statisticalConfig?: {
    /** Percentile value (0-100) for percentile measures. Default: 50 for median */
    percentile?: number
    /** Use sample vs population calculation for stddev/variance. Default: false (population) */
    useSample?: boolean
  }
 
  /**
   * Window function configuration
   * Used for lag, lead, rank, movingAvg, and other window function measure types
   *
   * Post-aggregation window functions:
   * When `measure` is specified, the window function operates on AGGREGATED data.
   * The base measure is first aggregated (grouped by query dimensions), then the
   * window function is applied to the aggregated results.
   *
   * Example: Month-over-month revenue change
   * ```typescript
   * revenueChange: {
   *   type: 'lag',
   *   windowConfig: {
   *     measure: 'totalRevenue',  // Reference to aggregate measure
   *     operation: 'difference',   // current - previous
   *     orderBy: [{ field: 'date', direction: 'asc' }]
   *   }
   * }
   * ```
   */
  windowConfig?: {
    /**
     * Reference to the measure this window function operates on.
     * The referenced measure will be aggregated first, then the window function applied.
     * Can be a simple name ('totalRevenue') or fully qualified ('Sales.totalRevenue').
     */
    measure?: string
 
    /**
     * Operation to perform after getting the window result:
     * - 'raw': Return the window function result directly (default for rank, rowNumber, ntile)
     * - 'difference': Subtract window result from current value (current - window)
     * - 'ratio': Divide current value by window result (current / window)
     * - 'percentChange': Calculate percentage change ((current - window) / window * 100)
     *
     * Default: 'difference' for lag/lead, 'raw' for rank/rowNumber/ntile/firstValue/lastValue
     */
    operation?: 'raw' | 'difference' | 'ratio' | 'percentChange'
 
    /** Dimension references to partition by (e.g., ['employeeId']) */
    partitionBy?: string[]
    /** Columns to order by with direction */
    orderBy?: Array<{ field: string; direction: 'asc' | 'desc' }>
    /** Number of rows to offset for lag/lead. Default: 1 */
    offset?: number
    /** Default value when offset is out of bounds for lag/lead */
    defaultValue?: any
    /** Number of buckets for ntile. Default: 4 */
    nTile?: number
    /** Window frame specification for moving aggregates */
    frame?: {
      type: 'rows' | 'range'
      start: number | 'unbounded'
      end: number | 'current' | 'unbounded'
    }
  }
}
 
/**
 * Relationship types supported by cube joins
 */
export type CubeRelationship = 'belongsTo' | 'hasOne' | 'hasMany' | 'belongsToMany'
 
/**
 * Type-safe cube join definition with lazy loading support
 */
export interface CubeJoin {
  /** Target cube reference - lazy loaded to avoid circular dependencies */
  targetCube: Cube | (() => Cube)
 
  /** Semantic relationship - determines join behavior */
  relationship: CubeRelationship
 
  /** Array of join conditions - supports multi-column joins */
  on: Array<{
    /** Column from source cube */
    source: AnyColumn
    /** Column from target cube */
    target: AnyColumn
    /** Comparison operator - defaults to eq */
    as?: (source: AnyColumn, target: AnyColumn) => SQL
  }>
 
  /** Override default SQL join type (derived from relationship) */
  sqlJoinType?: 'inner' | 'left' | 'right' | 'full'
 
  /**
   * Preferred path targets - marks this join as the canonical route to reach specific cubes.
   * When multiple paths exist to a target cube, paths using preferred joins are prioritized.
   *
   * Example: EmployeeTeams join with `preferredFor: ['Teams']` ensures employee-team
   * queries use the junction table path rather than going through Departments.
   */
  preferredFor?: string[]
 
  /**
   * Many-to-many relationship configuration through a junction table
   * Only used when relationship is 'belongsToMany'
   */
  through?: {
    /** Junction/join table (Drizzle table reference) */
    table: Table
    /** Join conditions from source cube to junction table */
    sourceKey: Array<{
      source: AnyColumn
      target: AnyColumn
      as?: (source: AnyColumn, target: AnyColumn) => SQL
    }>
    /** Join conditions from junction table to target cube */
    targetKey: Array<{
      source: AnyColumn
      target: AnyColumn
      as?: (source: AnyColumn, target: AnyColumn) => SQL
    }>
    /** Optional security context SQL for junction table */
    securitySql?: (securityContext: SecurityContext) => SQL | SQL[]
  }
}
 
/**
 * Compiled cube with execution function
 */
export interface CompiledCube 
  extends Cube {
  /** Execute a query against this cube */
  queryFn: (query: SemanticQuery, securityContext: SecurityContext) => Promise<QueryResult>
}
 
/**
 * Join key information for CTE joins
 * Describes how a CTE should be joined to the main query
 */
export interface JoinKeyInfo {
  /** Column name in the source table */
  sourceColumn: string
  /** Column name in the target table (CTE) */
  targetColumn: string
  /** Optional Drizzle column object for source */
  sourceColumnObj?: AnyColumn
  /** Optional Drizzle column object for target */
  targetColumnObj?: AnyColumn
}
 
/**
 * Single join key pair for composite key support
 */
export interface JoinKeyPair {
  /** Primary key column on source cube */
  source: AnyColumn
  /** Foreign key column on target cube (CTE cube) */
  target: AnyColumn
}
 
/**
 * Propagating filter information for cross-cube filter propagation
 * When cube A has filters and cube B (with hasMany from A) needs a CTE,
 * A's filters should propagate into B's CTE via a subquery
 */
export interface PropagatingFilter {
  /** The source cube whose filters need to propagate */
  sourceCube: Cube
  /** Filters from the source cube to apply */
  filters: import('./query').Filter[]
  /** Join conditions linking source cube PK(s) to target cube FK(s) - supports composite keys */
  joinConditions: JoinKeyPair[]
  /** Pre-built filter SQL for parameter deduplication (optional, built during query planning) */
  preBuiltFilterSQL?: SQL
}
 
/**
 * Pre-aggregation CTE information
 * Describes a Common Table Expression used for pre-aggregating hasMany relationships
 */
export interface PreAggregationCTEInfo {
  /** The cube being pre-aggregated */
  cube: Cube
  /** Table alias for this cube in the main query */
  alias: string
  /** CTE alias (WITH clause name) */
  cteAlias: string
  /** Join keys to connect CTE back to main query (e.g., employee_id for Employees → EmployeeTeams) */
  joinKeys: JoinKeyInfo[]
  /** List of measure names included in this CTE (aggregate measures + window base measures) */
  measures: string[]
  /** Propagating filters from related cubes (for cross-cube filter propagation) */
  propagatingFilters?: PropagatingFilter[]
  /**
   * Downstream join keys for cubes that need to be joined through this CTE.
   * When a query has dimensions from a cube (e.g., Teams) that should be joined
   * through this CTE cube (e.g., EmployeeTeams), we include those join keys here
   * so the CTE includes them in SELECT and GROUP BY, allowing downstream joins.
   */
  downstreamJoinKeys?: DownstreamJoinKeyInfo[]
  /**
   * Type of CTE:
   * - 'aggregate': Standard CTE with GROUP BY for count/sum/avg measures
   *
   * Note: Window function CTEs are no longer used. Post-aggregation window
   * functions (lag, lead, rank, etc.) operate on aggregated data and are
   * applied in the outer query SELECT clause, not in separate CTEs.
   */
  cteType?: 'aggregate'
}
 
/**
 * Information about downstream join keys for CTE building.
 * Used when a cube (e.g., Teams) needs to be joined through a CTE cube (e.g., EmployeeTeams)
 */
export interface DownstreamJoinKeyInfo {
  /** The downstream cube name (e.g., 'Teams') */
  targetCubeName: string
  /** Join keys from CTE cube to downstream cube */
  joinKeys: JoinKeyInfo[]
}
 
/**
 * Unified Query Plan for both single and multi-cube queries
 * - For single-cube queries: joinCubes array is empty
 * - For multi-cube queries: joinCubes contains the additional cubes to join
 * - selections, whereConditions, and groupByFields are populated by QueryBuilder
 */
export interface QueryPlan {
  /** Primary cube that drives the query */
  primaryCube: Cube
  /** Additional cubes to join (empty for single-cube queries) */
  joinCubes: Array<{
    cube: Cube
    alias: string
    joinType: 'inner' | 'left' | 'right' | 'full'
    joinCondition: SQL
    /** Junction table information for belongsToMany relationships */
    junctionTable?: {
      table: Table
      alias: string
      joinType: 'inner' | 'left' | 'right' | 'full'
      joinCondition: SQL
      /** Optional security SQL function to apply to junction table */
      securitySql?: (securityContext: SecurityContext) => SQL | SQL[]
    }
  }>
  /** Combined field selections across all cubes (built by QueryBuilder) */
  selections: Record<string, SQL | AnyColumn>
  /** WHERE conditions for the entire query (built by QueryBuilder) */
  whereConditions: SQL[]
  /** GROUP BY fields if aggregations are present (built by QueryBuilder) */
  groupByFields: (SQL | AnyColumn)[]
  /** Pre-aggregation CTEs for hasMany relationships to prevent fan-out */
  preAggregationCTEs?: PreAggregationCTEInfo[]
}
 
 
 
/**
 * Utility type for cube definition with schema inference
 */
export type CubeDefinition = Omit<Cube, 'name'> & {
  name?: string
}
 
/**
 * Helper type for creating type-safe cubes
 */
export interface CubeDefiner {
  <TName extends string>(
    name: TName,
    definition: CubeDefinition
  ): Cube & { name: TName }
}