All files / server query-builder.ts

85.8% Statements 520/606
76.54% Branches 385/503
93.33% Functions 42/45
86.65% Lines 500/577

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 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485                                                                                                          92x                                     673x 673x 673x 673x     673x 673x 826x       673x 921x 921x 921x 891x 891x 9x   9x 18x     9x 9x 19x 19x 19x 19x 19x 2x 3x         882x           673x 932x 932x 932x 902x 902x 891x 9x     11x 2x             673x 891x 891x 891x     891x         901x         673x 9x   9x 11x 11x 11x     12x                   673x                         571x     571x     571x 225x 265x 265x 265x 265x 265x   265x           571x 570x             570x 758x 758x 758x 758x           571x 101x 108x 108x 108x 108x 108x           108x           571x       571x                           14x             14x     14x             14x                                               2x             2x     2x   2x 4x 4x   4x 4x     4x   4x               4x       4x 4x                                   4x           2x                                       27x 16x 16x     15x                                                       15x     15x       11x     4x                               12x                       938x               938x                 938x     938x 38x 38x     38x     38x   38x 38x     38x         938x   169x   402x   216x   112x   6x   8x   25x                           239x   239x   4x       235x                         674x     674x     674x 347x 370x 370x 266x           670x 123x 134x 134x 134x     71x 20x 20x 10x       61x     61x 61x 61x 59x           670x                         567x     567x     567x 294x 308x 308x 27x         567x                             1691x 470x   470x 281x 593x 593x 281x     189x 189x 420x 420x 189x         1221x 1221x 1221x 1221x     1183x 1183x 1183x 1691x     1183x     574x 103x 103x 30x           544x 544x       574x             609x     42x 567x     27x 27x                   540x                           571x   34x 2x             32x 1x           31x       537x   21x 2x   19x         516x 33114x   33105x 33104x       516x   6x 4x   2x     509x   509x   153x   5x       5x 148x   148x 148x       3x   3x 3x       38x   2x   4x   2x   43x   18x   57x   4x           26x 21x 21x   21x     16x 16x 15x     15x 15x 15x 15x                 16x           10x   13x 13x 13x         10x 10x 9x   1x     40x 38x         2x   2x 2x             39x 39x       12x 12x       27x   6x   2x   2x   1x                           2x     2x   1x     1x   1x     1x   1x                     105x     105x 45x 45x   45x       45x 45x     45x 45x 45x 45x                 45x             60x   60x 60x         52x 52x 52x 52x                     52x             8x 8x       6x     60x 60x 60x 60x           60x 6x 6x 6x                     6x                           60x 60x     60x 60x 60x 60x     60x 3x 3x 3x 3x 3x       57x 2x 2x 2x 2x 2x 2x 2x       55x 2x 2x 2x 2x   2x 2x 2x 2x       53x 5x 5x 5x       48x 2x 2x 2x 2x       46x 4x 4x 4x       42x 42x 12x 12x 12x 12x 12x 12x 12x       30x 30x 1x 1x 1x 1x 1x 1x 1x 1x       29x 2x 2x 2x 2x   2x 2x 2x 2x       27x 2x 2x 2x       25x 2x 2x 2x 2x 2x 2x       23x 4x 4x 4x       19x 5x 5x 5x 5x       14x 14x 3x 3x 3x 3x 3x       11x 11x 3x 3x 3x 3x 3x     8x                 165x     165x                           165x                                   165x     165x 149x 149x     147x 147x                 16x 16x     10x 10x                                                               567x     567x 567x 1x       566x     567x 224x 263x 263x 263x     263x   263x   12x 12x   12x           12x 12x       251x 251x 251x             566x 101x 108x 108x 108x     108x   108x   23x 23x   23x                       23x 23x       85x 85x         85x                   566x             567x     567x     108x       567x 68x   75x 1x       74x 75x         566x 101x     101x 7x     101x 108x   80x         566x               533x     533x     533x 532x       533x 196x 236x 236x 236x 236x 236x   86x           533x                 566x 566x 1x     566x   566x 51x 1x   50x     565x 17x 1x   16x     564x    
/**
 * Shared Query Builder
 * Contains all SQL building logic that was previously duplicated between executor and multi-cube-builder
 * Single source of truth for all SQL generation
 */
 
import {
  sql,
  and,
  or,
  eq,
  ne,
  gt,
  gte,
  lt,
  lte,
  isNull,
  isNotNull,
  inArray,
  notInArray,
  count,
  sum,
  min,
  max,
  countDistinct,
  asc,
  desc,
  SQL,
  type AnyColumn,
  arrayContains as drizzleArrayContains,
  arrayContained as drizzleArrayContained,
  arrayOverlaps as drizzleArrayOverlaps
} from 'drizzle-orm'
 
import type {
  SemanticQuery,
  FilterOperator,
  Filter,
  FilterCondition,
  LogicalFilter,
  TimeGranularity,
  Cube,
  QueryContext,
  QueryPlan,
  JoinKeyInfo
} from './types'
 
import { resolveSqlExpression } from './cube-utils'
import type { DatabaseAdapter } from './adapters/base-adapter'
import { CalculatedMeasureResolver } from './calculated-measure-resolver'
import { substituteTemplate, getMemberReferences, type ResolvedMeasures } from './template-substitution'
 
export class QueryBuilder {
  constructor(private databaseAdapter: DatabaseAdapter) {}
 
  /**
   * Build resolvedMeasures map for a set of measures
   * This centralizes the logic for building both regular and calculated measures
   * in dependency order, avoiding duplication across main queries and CTEs
   *
   * @param measureNames - Array of measure names to resolve (e.g., ["Employees.count", "Employees.activePercentage"])
   * @param cubeMap - Map of all cubes involved in the query
   * @param context - Query context with database and security context
   * @param customMeasureBuilder - Optional function to override how individual measures are built
   * @returns Map of measure names to SQL builder functions
   */
  buildResolvedMeasures(
    measureNames: string[],
    cubeMap: Map<string, Cube>,
    context: QueryContext,
    customMeasureBuilder?: (measureName: string, measure: any, cube: Cube) => SQL
  ): ResolvedMeasures {
    const resolvedMeasures: ResolvedMeasures = new Map()
    const regularMeasures: string[] = []
    const calculatedMeasures: string[] = []
    const allMeasuresToResolve = new Set<string>(measureNames)
 
    // Build dependency graph
    const resolver = new CalculatedMeasureResolver(cubeMap)
    for (const cube of cubeMap.values()) {
      resolver.buildGraph(cube)
    }
 
    // First pass: classify user-requested measures and collect dependencies
    for (const measureName of measureNames) {
      const [cubeName, fieldName] = measureName.split('.')
      const cube = cubeMap.get(cubeName)
      if (cube && cube.measures && cube.measures[fieldName]) {
        const measure = cube.measures[fieldName]
        if (CalculatedMeasureResolver.isCalculatedMeasure(measure)) {
          calculatedMeasures.push(measureName)
          // Add all dependencies to measures that need to be resolved
          const deps = getMemberReferences(measure.calculatedSql!, cubeName)
          deps.forEach(dep => allMeasuresToResolve.add(dep))
 
          // Also add transitive calculated measure dependencies
          const calculatedDeps = resolver.getAllDependencies(measureName)
          calculatedDeps.forEach(dep => {
            const [depCubeName, depFieldName] = dep.split('.')
            const depCube = cubeMap.get(depCubeName)
            Eif (depCube && depCube.measures[depFieldName]) {
              const depMeasure = depCube.measures[depFieldName]
              if (CalculatedMeasureResolver.isCalculatedMeasure(depMeasure)) {
                const nestedDeps = getMemberReferences(depMeasure.calculatedSql!, depCubeName)
                nestedDeps.forEach(nestedDep => allMeasuresToResolve.add(nestedDep))
              }
            }
          })
        } else {
          regularMeasures.push(measureName)
        }
      }
    }
 
    // Second pass: classify all measures that need to be resolved (including dependencies)
    for (const measureName of allMeasuresToResolve) {
      const [cubeName, fieldName] = measureName.split('.')
      const cube = cubeMap.get(cubeName)
      if (cube && cube.measures && cube.measures[fieldName]) {
        const measure = cube.measures[fieldName]
        if (!CalculatedMeasureResolver.isCalculatedMeasure(measure)) {
          if (!regularMeasures.includes(measureName)) {
            regularMeasures.push(measureName)
          }
        } else {
          if (!calculatedMeasures.includes(measureName)) {
            calculatedMeasures.push(measureName)
          }
        }
      }
    }
 
    // Build regular measures first
    for (const measureName of regularMeasures) {
      const [cubeName, fieldName] = measureName.split('.')
      const cube = cubeMap.get(cubeName)!
      const measure = cube.measures[fieldName]
 
      // Use custom builder if provided, otherwise use default
      Iif (customMeasureBuilder) {
        const builtExpr = customMeasureBuilder(measureName, measure, cube)
        resolvedMeasures.set(measureName, () => builtExpr)
      } else {
        // Store a FUNCTION that builds the SQL expression to avoid mutation issues
        resolvedMeasures.set(measureName, () => this.buildMeasureExpression(measure, context))
      }
    }
 
    // Build calculated measures in dependency order
    if (calculatedMeasures.length > 0) {
      const sortedCalculated = resolver.topologicalSort(calculatedMeasures)
 
      for (const measureName of sortedCalculated) {
        const [cubeName, fieldName] = measureName.split('.')
        const cube = cubeMap.get(cubeName)!
        const measure = cube.measures[fieldName]
 
        // Store a FUNCTION that builds the calculated measure SQL
        resolvedMeasures.set(measureName, () => this.buildCalculatedMeasure(
          measure,
          cube,
          cubeMap,
          resolvedMeasures,
          context
        ))
      }
    }
 
    return resolvedMeasures
  }
 
  /**
   * Build dynamic selections for measures, dimensions, and time dimensions
   * Works for both single and multi-cube queries
   * Handles calculated measures with dependency resolution
   */
  buildSelections(
    cubes: Map<string, Cube> | Cube,
    query: SemanticQuery,
    context: QueryContext
  ): Record<string, SQL | AnyColumn> {
    const selections: Record<string, SQL | AnyColumn> = {}
 
    // Convert single cube to map for consistent handling
    const cubeMap = cubes instanceof Map ? cubes : new Map([[cubes.name, cubes]])
 
    // Add dimensions
    if (query.dimensions) {
      for (const dimensionName of query.dimensions) {
        const [cubeName, fieldName] = dimensionName.split('.')
        const cube = cubeMap.get(cubeName)
        Eif (cube && cube.dimensions && cube.dimensions[fieldName]) {
          const dimension = cube.dimensions[fieldName]
          const sqlExpr = resolveSqlExpression(dimension.sql, context)
          // Use explicit alias for dimension expressions so they can be referenced in ORDER BY
          selections[dimensionName] = sql`${sqlExpr}`.as(dimensionName) as unknown as SQL
        }
      }
    }
 
    // Add measures with aggregations using the centralized helper
    if (query.measures) {
      const resolvedMeasures = this.buildResolvedMeasures(
        query.measures,
        cubeMap,
        context
      )
 
      // Add user-requested measures to selections
      for (const measureName of query.measures) {
        const measureBuilder = resolvedMeasures.get(measureName)
        Eif (measureBuilder) {
          const measureExpr = measureBuilder()
          selections[measureName] = sql`${measureExpr}`.as(measureName) as unknown as SQL
        }
      }
    }
 
    // Add time dimensions with granularity
    if (query.timeDimensions) {
      for (const timeDim of query.timeDimensions) {
        const [cubeName, fieldName] = timeDim.dimension.split('.')
        const cube = cubeMap.get(cubeName)
        Eif (cube && cube.dimensions && cube.dimensions[fieldName]) {
          const dimension = cube.dimensions[fieldName]
          const timeExpr = this.buildTimeDimensionExpression(
            dimension.sql,
            timeDim.granularity,
            context
          )
          // Use explicit alias for time dimension expressions so they can be referenced in ORDER BY
          selections[timeDim.dimension] = sql`${timeExpr}`.as(timeDim.dimension) as unknown as SQL
        }
      }
    }
 
    // Default to COUNT(*) if no selections
    Iif (Object.keys(selections).length === 0) {
      selections.count = count()
    }
 
    return selections
  }
 
  /**
   * Build calculated measure expression by substituting {member} references
   * with resolved SQL expressions
   */
  public buildCalculatedMeasure(
    measure: any,
    cube: Cube,
    allCubes: Map<string, Cube>,
    resolvedMeasures: ResolvedMeasures,
    context: QueryContext
  ): SQL {
    Iif (!measure.calculatedSql) {
      throw new Error(
        `Calculated measure '${cube.name}.${measure.name}' missing calculatedSql property`
      )
    }
 
    // Preprocess template for database-specific transformations (e.g., SQLite float division)
    const preprocessedSql = this.databaseAdapter.preprocessCalculatedTemplate(measure.calculatedSql)
 
    // Substitute {member} references with resolved SQL
    const substitutedSql = substituteTemplate(preprocessedSql, {
      cube,
      allCubes,
      resolvedMeasures,
      queryContext: context
    })
 
    return substitutedSql
  }
 
  /**
   * Build resolved measures map for a calculated measure from CTE columns
   * This handles re-aggregating pre-aggregated CTE columns for calculated measures
   *
   * IMPORTANT: For calculated measures in CTEs, we cannot sum/avg pre-computed ratios.
   * We must recalculate from the base measures that were pre-aggregated in the CTE.
   *
   * @param measure - The calculated measure to build
   * @param cube - The cube containing this measure
   * @param cteInfo - CTE metadata (alias, measures, cube reference)
   * @param allCubes - Map of all cubes in the query
   * @param context - Query context
   * @returns SQL expression for the calculated measure using CTE column references
   */
  public buildCTECalculatedMeasure(
    measure: any,
    cube: Cube,
    cteInfo: { cteAlias: string; measures: string[]; cube: Cube },
    allCubes: Map<string, Cube>,
    context: QueryContext
  ): SQL {
    Iif (!measure.calculatedSql) {
      throw new Error(
        `Calculated measure '${cube.name}.${measure.name || 'unknown'}' missing calculatedSql property`
      )
    }
 
    // Build a resolvedMeasures map with CTE column references
    const cteResolvedMeasures = new Map<string, () => SQL>()
 
    // Get all dependencies for this calculated measure
    const deps = getMemberReferences(measure.calculatedSql, cube.name)
 
    for (const depMeasureName of deps) {
      const [depCubeName, depFieldName] = depMeasureName.split('.')
      const depCube = allCubes.get(depCubeName)
 
      Eif (depCube && depCube.measures[depFieldName]) {
        const depMeasure = depCube.measures[depFieldName]
 
        // Check if this dependency is also in the CTE
        Eif (cteInfo.measures.includes(depMeasureName)) {
          // Reference the CTE column and apply appropriate aggregation
          const cteDepColumn = sql`${sql.identifier(cteInfo.cteAlias)}.${sql.identifier(depFieldName)}`
 
          // Apply aggregation based on the dependency's type
          // For pre-aggregated values in CTEs, we need to re-aggregate them properly:
          // - count/sum values should be summed
          // - avg values should be averaged (though ideally weighted average)
          // - min/max values should take min/max
          let aggregatedDep: SQL
          switch (depMeasure.type) {
            case 'count':
            case 'countDistinct':
            case 'sum':
              aggregatedDep = sum(cteDepColumn)
              break
            case 'avg':
              aggregatedDep = this.databaseAdapter.buildAvg(cteDepColumn)
              break
            case 'min':
              aggregatedDep = min(cteDepColumn)
              break
            case 'max':
              aggregatedDep = max(cteDepColumn)
              break
            case 'number':
              aggregatedDep = sum(cteDepColumn)
              break
            default:
              aggregatedDep = sum(cteDepColumn)
          }
 
          // Store the aggregated CTE column as a builder function
          cteResolvedMeasures.set(depMeasureName, () => aggregatedDep)
        }
      }
    }
 
    // Re-apply the calculated measure template with CTE-based dependencies
    return this.buildCalculatedMeasure(
      measure,
      cube,
      allCubes,
      cteResolvedMeasures,
      context
    )
  }
 
  /**
   * Build measure expression for HAVING clause, handling CTE references correctly
   */
  private buildHavingMeasureExpression(
    cubeName: string,
    fieldKey: string,
    measure: any,
    context: QueryContext,
    queryPlan?: QueryPlan
  ): SQL {
    // Check if this measure is from a CTE cube
    if (queryPlan && queryPlan.preAggregationCTEs) {
      const cteInfo = queryPlan.preAggregationCTEs.find(cte => cte.cube.name === cubeName)
      if (cteInfo && cteInfo.measures.includes(`${cubeName}.${fieldKey}`)) {
        // This measure is from a CTE - reference the CTE alias instead of the original table
 
        Iif (measure.type === 'calculated' && measure.calculatedSql) {
          // Get the cube for this measure
          const cube = queryPlan.primaryCube.name === cubeName
            ? queryPlan.primaryCube
            : queryPlan.joinCubes?.find(jc => jc.cube.name === cubeName)?.cube
 
          if (!cube) {
            throw new Error(`Cube ${cubeName} not found in query plan`)
          }
 
          // Build a cubeMap for the calculated measure builder
          const cubeMap = new Map<string, Cube>([[queryPlan.primaryCube.name, queryPlan.primaryCube]])
          if (queryPlan.joinCubes) {
            for (const jc of queryPlan.joinCubes) {
              cubeMap.set(jc.cube.name, jc.cube)
            }
          }
 
          // Use the shared helper to build calculated measure from CTE columns
          return this.buildCTECalculatedMeasure(
            measure,
            cube,
            cteInfo,
            cubeMap,
            context
          )
        } else {
          // For non-calculated measures, aggregate the CTE column directly
          const cteColumn = sql`${sql.identifier(cteInfo.cteAlias)}.${sql.identifier(fieldKey)}`
 
          // Apply aggregation function based on measure type
          switch (measure.type) {
            case 'count':
            case 'countDistinct':
            case 'sum':
              return sum(cteColumn)
            case 'avg':
              // For average of averages, we should use a weighted average, but for now use simple avg
              return this.databaseAdapter.buildAvg(cteColumn)
            case 'min':
              return min(cteColumn)
            case 'max':
              return max(cteColumn)
            case 'number':
              // For number type, use sum to combine values
              return sum(cteColumn)
            default:
              return sum(cteColumn)
          }
        }
      }
    }
 
    // Not from CTE - use regular measure expression
    return this.buildMeasureExpression(measure, context)
  }
 
  /**
   * Build measure expression with aggregation and filters
   * Note: This should NOT be called for calculated measures
   */
  buildMeasureExpression(
    measure: any,
    context: QueryContext
  ): SQL {
    // Calculated measures should be built via buildCalculatedMeasure
    Iif (measure.type === 'calculated') {
      throw new Error(
        `Cannot build calculated measure '${measure.name}' directly. ` +
        `Use buildCalculatedMeasure instead.`
      )
    }
 
    // Non-calculated measures must have sql property
    Iif (!measure.sql) {
      throw new Error(
        `Measure '${measure.name}' of type '${measure.type}' is missing required 'sql' property. ` +
        `Only calculated measures can omit 'sql'.`
      )
    }
 
    // resolveSqlExpression already applies isolation via isolateSqlExpression()
    // This protects against Drizzle SQL object mutation during reuse
    let baseExpr = resolveSqlExpression(measure.sql, context)
 
    // Apply measure filters if they exist
    if (measure.filters && measure.filters.length > 0) {
      const filterConditions = measure.filters.map((filter: (ctx: QueryContext) => SQL) => {
        const filterResult = filter(context)
        // Single wrap is OK here - we're creating fresh SQL for grouping in parentheses
        // The filter function itself should handle isolation if needed
        return filterResult ? sql`(${filterResult})` : undefined
      }).filter(Boolean) // Remove any undefined conditions
 
      Eif (filterConditions.length > 0) {
        // Use CASE WHEN for conditional aggregation via adapter
        const andCondition = filterConditions.length === 1 ? filterConditions[0] : and(...filterConditions)
        const caseExpr = this.databaseAdapter.buildCaseWhen([
          { when: andCondition!, then: baseExpr }
        ])
        baseExpr = caseExpr
      }
    }
 
    // Apply aggregation function based on measure type
    switch (measure.type) {
      case 'count':
        return count(baseExpr)
      case 'countDistinct':
        return countDistinct(baseExpr)
      case 'sum':
        return sum(baseExpr)
      case 'avg':
        return this.databaseAdapter.buildAvg(baseExpr)
      case 'min':
        return min(baseExpr)
      case 'max':
        return max(baseExpr)
      case 'number':
        return baseExpr as SQL
      default:
        return count(baseExpr)
    }
  }
 
  /**
   * Build time dimension expression with granularity using database adapter
   */
  buildTimeDimensionExpression(
    dimensionSql: any,
    granularity: string | undefined,
    context: QueryContext
  ): SQL {
    const baseExpr = resolveSqlExpression(dimensionSql, context)
    
    if (!granularity) {
      // Ensure we return SQL even when no granularity is applied
      return baseExpr instanceof SQL ? baseExpr : sql`${baseExpr}`
    }
    
    // Use database adapter for database-specific time dimension building
    return this.databaseAdapter.buildTimeDimension(granularity as TimeGranularity, baseExpr)
  }
 
  /**
   * Build WHERE conditions from semantic query filters (dimensions only)
   * Works for both single and multi-cube queries
   */
  buildWhereConditions(
    cubes: Map<string, Cube> | Cube, 
    query: SemanticQuery, 
    context: QueryContext,
    queryPlan?: QueryPlan
  ): SQL[] {
    const conditions: SQL[] = []
    
    // Convert single cube to map for consistent handling
    const cubeMap = cubes instanceof Map ? cubes : new Map([[cubes.name, cubes]])
    
    // Process regular filters (dimensions only for WHERE clause)
    if (query.filters && query.filters.length > 0) {
      for (const filter of query.filters) {
        const condition = this.processFilter(filter, cubeMap, context, 'where', queryPlan)
        if (condition) {
          conditions.push(condition)
        }
      }
    }    
 
    // Process time dimension date range filters
    if (query.timeDimensions) {
      for (const timeDim of query.timeDimensions) {
        const [cubeName, fieldName] = timeDim.dimension.split('.')
        const cube = cubeMap.get(cubeName)
        if (cube && cube.dimensions[fieldName] && timeDim.dateRange) {
          // Check if this cube is in a pre-aggregation CTE - if so, skip this filter in WHERE clause
          // The time dimension filter will be applied within the CTE itself during pre-aggregation
          if (queryPlan?.preAggregationCTEs) {
            const isInCTE = queryPlan.preAggregationCTEs.some((cte: any) => cte.cube.name === cubeName)
            if (isInCTE) {
              continue // Skip this filter - it's handled in the CTE
            }
          }
          
          const dimension = cube.dimensions[fieldName]
          // Use the raw field expression for date filtering (not the truncated version)
          // This ensures we filter on the actual timestamp values before aggregation
          const fieldExpr = resolveSqlExpression(dimension.sql, context)
          const dateCondition = this.buildDateRangeCondition(fieldExpr, timeDim.dateRange)         
          if (dateCondition) {
            conditions.push(dateCondition)
          }
        }
      }
    }    
    
    return conditions
  }
 
  /**
   * Build HAVING conditions from semantic query filters (measures only)
   * Works for both single and multi-cube queries
   */
  buildHavingConditions(
    cubes: Map<string, Cube> | Cube, 
    query: SemanticQuery, 
    context: QueryContext,
    queryPlan?: QueryPlan
  ): SQL[] {
    const conditions: SQL[] = []
    
    // Convert single cube to map for consistent handling
    const cubeMap = cubes instanceof Map ? cubes : new Map([[cubes.name, cubes]])
    
    // Process regular filters (measures only for HAVING clause)
    if (query.filters && query.filters.length > 0) {
      for (const filter of query.filters) {
        const condition = this.processFilter(filter, cubeMap, context, 'having', queryPlan)
        if (condition) {
          conditions.push(condition)
        }
      }
    }    
    
    return conditions
  }
 
  /**
   * Process a single filter (basic or logical)
   * @param filterType - 'where' for dimension filters, 'having' for measure filters
   */
  private processFilter(
    filter: Filter,
    cubes: Map<string, Cube>,
    context: QueryContext,
    filterType: 'where' | 'having',
    queryPlan?: QueryPlan
  ): SQL | null {
    // Handle logical filters (AND/OR)
    if ('and' in filter || 'or' in filter) {
      const logicalFilter = filter as LogicalFilter
      
      if (logicalFilter.and) {
        const conditions = logicalFilter.and
          .map(f => this.processFilter(f, cubes, context, filterType, queryPlan))
          .filter((condition): condition is SQL => condition !== null)
        return conditions.length > 0 ? and(...conditions) as SQL : null
      }
      
      Eif (logicalFilter.or) {
        const conditions = logicalFilter.or
          .map(f => this.processFilter(f, cubes, context, filterType, queryPlan))
          .filter((condition): condition is SQL => condition !== null)
        return conditions.length > 0 ? or(...conditions) as SQL : null
      }
    }
    
    // Handle simple filter condition
    const filterCondition = filter as FilterCondition
    const [cubeName, fieldKey] = filterCondition.member.split('.')
    const cube = cubes.get(cubeName)
    if (!cube) return null
        
    // Find the field in dimensions or measures
    const dimension = cube.dimensions[fieldKey]
    const measure = cube.measures[fieldKey]
    const field = dimension || measure
    Iif (!field) return null
    
    // Apply filter based on type and what we're looking for
    if (filterType === 'where' && dimension) {
      // Check if this cube is in a pre-aggregation CTE - if so, skip this filter in WHERE clause
      // The filter will be applied within the CTE itself
      if (queryPlan?.preAggregationCTEs) {
        const isInCTE = queryPlan.preAggregationCTEs.some((cte: any) => cte.cube.name === cubeName)
        if (isInCTE) {
          return null // Skip this filter - it's handled in the CTE
        }
      }
 
      // For array operators, we need the raw column (not isolated SQL)
      // because Drizzle's array functions need column type metadata for proper encoding
      const isArrayOperator = ['arrayContains', 'arrayOverlaps', 'arrayContained'].includes(filterCondition.operator)
      const fieldExpr = isArrayOperator
        ? (typeof dimension.sql === 'function' ? dimension.sql(context) : dimension.sql)
        : resolveSqlExpression(dimension.sql, context)
 
      return this.buildFilterCondition(
        fieldExpr,
        filterCondition.operator,
        filterCondition.values,
        field,
        filterCondition.dateRange
      )
    } else if (filterType === 'where' && measure) {
      // NEVER apply measure filters in WHERE clause - they should only be in HAVING
      // This prevents incorrect behavior where measure filters are applied before aggregation
      return null
    } else if (filterType === 'having' && measure) {
      // HAVING clause: use aggregated measure expression
      // Check if this measure is from a CTE cube
      const measureExpr = this.buildHavingMeasureExpression(cubeName, fieldKey, measure, context, queryPlan)
      return this.buildFilterCondition(
        measureExpr,
        filterCondition.operator,
        filterCondition.values,
        field,
        filterCondition.dateRange
      )
    }
    
    // Skip if this filter doesn't match the type we're processing
    return null
  }
 
  /**
   * Build filter condition using Drizzle operators
   */
  private buildFilterCondition(
    fieldExpr: AnyColumn | SQL,
    operator: FilterOperator,
    values: any[],
    field?: any,
    dateRange?: string | string[]
  ): SQL | null {
    // Handle dateRange for date filters
    if (dateRange !== undefined) {
      // Validate: dateRange only works with inDateRange operator
      if (operator !== 'inDateRange') {
        throw new Error(
          `dateRange can only be used with 'inDateRange' operator, but got '${operator}'. ` +
          `Use explicit date values in the 'values' array for other date operators.`
        )
      }
 
      // Validate: field must be a time dimension
      if (field && field.type !== 'time') {
        throw new Error(
          `dateRange can only be used on time dimensions, but field '${field.name || 'unknown'}' has type '${field.type}'`
        )
      }
 
      // Use existing buildDateRangeCondition logic - dateRange takes precedence over values
      return this.buildDateRangeCondition(fieldExpr, dateRange)
    }
 
    // Handle empty values
    if (!values || values.length === 0) {
      // For empty equals filter, return condition that matches nothing
      if (operator === 'equals') {
        return this.databaseAdapter.buildBooleanLiteral(false)
      }
      return null
    }
 
    // Filter out empty/null values and values containing null bytes for security
    // For date operators, don't convert values yet - we'll normalize to Date first    
    const filteredValues = values.filter(v => {
      if (v === null || v === undefined || v === '') return false
      // Reject values containing null bytes for security
      if (typeof v === 'string' && v.includes('\x00')) return false
      return true
    }).map(this.databaseAdapter.convertFilterValue)
        
    // For certain operators, we need at least one non-empty value
    if (filteredValues.length === 0 && !['set', 'notSet'].includes(operator)) {
      // For empty equals filter, return condition that matches nothing
      if (operator === 'equals') {
        return this.databaseAdapter.buildBooleanLiteral(false)
      }
      return null
    }
 
    const value = filteredValues[0]
    
    switch (operator) {
      case 'equals':
        if (filteredValues.length > 1) {
          // For time-type fields, normalize all values
          Iif (field?.type === 'time') {
            const normalizedValues = filteredValues.map(v => this.normalizeDate(v) || v)
            return inArray(fieldExpr as AnyColumn, normalizedValues)
          }
          return inArray(fieldExpr as AnyColumn, filteredValues)
        E} else if (filteredValues.length === 1) {
          // For time-type fields, normalize the single value
          const finalValue = field?.type === 'time' ? this.normalizeDate(value) || value : value
          return eq(fieldExpr as AnyColumn, finalValue)
        }
        return this.databaseAdapter.buildBooleanLiteral(false)
      case 'notEquals':
        Iif (filteredValues.length > 1) {
          return notInArray(fieldExpr as AnyColumn, filteredValues)
        E} else if (filteredValues.length === 1) {
          return ne(fieldExpr as AnyColumn, value)
        }
        return null
      case 'contains':
        return this.databaseAdapter.buildStringCondition(fieldExpr, 'contains', value)
      case 'notContains':
        return this.databaseAdapter.buildStringCondition(fieldExpr, 'notContains', value)
      case 'startsWith':
        return this.databaseAdapter.buildStringCondition(fieldExpr, 'startsWith', value)
      case 'endsWith':
        return this.databaseAdapter.buildStringCondition(fieldExpr, 'endsWith', value)
      case 'gt':
        return gt(fieldExpr as AnyColumn, value)
      case 'gte':
        return gte(fieldExpr as AnyColumn, value)
      case 'lt':
        return lt(fieldExpr as AnyColumn, value)
      case 'lte':
        return lte(fieldExpr as AnyColumn, value)
      case 'set':
        return isNotNull(fieldExpr as AnyColumn)
      case 'notSet':
        return isNull(fieldExpr as AnyColumn)
      case 'inDateRange':
        if (filteredValues.length >= 2) {
          const startDate = this.normalizeDate(filteredValues[0])
          let endDate = this.normalizeDate(filteredValues[1])
 
          if (startDate && endDate) {
            // For date-only strings in original values, treat end date as end-of-day
            // Check original values array (before filtering/conversion)
            const originalEndValue = values[1]
            if (typeof originalEndValue === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(originalEndValue.trim())) {
              const endDateObj = typeof endDate === 'number'
                ? new Date(endDate * (this.databaseAdapter.getEngineType() === 'sqlite' ? 1000 : 1))
                : new Date(endDate)
              const endOfDay = new Date(endDateObj)
              endOfDay.setUTCHours(23, 59, 59, 999)
              if (this.databaseAdapter.isTimestampInteger()) {
                endDate = this.databaseAdapter.getEngineType() === 'sqlite'
                  ? Math.floor(endOfDay.getTime() / 1000)
                  : endOfDay.getTime()
              } else E{
                // PostgreSQL and MySQL need ISO strings
                endDate = endOfDay.toISOString()
              }
            }
 
            return and(
              gte(fieldExpr as AnyColumn, startDate),
              lte(fieldExpr as AnyColumn, endDate)
            ) as SQL
          }
        }
        return null
      case 'beforeDate': {
        const beforeValue = this.normalizeDate(value)
        Eif (beforeValue) {          
          return lt(fieldExpr as AnyColumn, beforeValue)
        }
        return null
      }
      case 'afterDate': {
        const afterValue = this.normalizeDate(value)
        if (afterValue) {          
          return gt(fieldExpr as AnyColumn, afterValue)
        }
        return null
      }
      case 'between':
        if (filteredValues.length >= 2) {
          return and(
            gte(fieldExpr as AnyColumn, filteredValues[0]),
            lte(fieldExpr as AnyColumn, filteredValues[1])
          ) as SQL
        }
        return null
      case 'notBetween':
        Eif (filteredValues.length >= 2) {
          return or(
            lt(fieldExpr as AnyColumn, filteredValues[0]),
            gt(fieldExpr as AnyColumn, filteredValues[1])
          ) as SQL
        }
        return null
      case 'in':
        Eif (filteredValues.length > 0) {
          return inArray(fieldExpr as AnyColumn, filteredValues)
        }
        return null
      case 'notIn':
        Eif (filteredValues.length > 0) {
          return notInArray(fieldExpr as AnyColumn, filteredValues)
        }
        return null
      case 'like':
        return this.databaseAdapter.buildStringCondition(fieldExpr, 'like', value)
      case 'notLike':
        return this.databaseAdapter.buildStringCondition(fieldExpr, 'notLike', value)
      case 'ilike':
        return this.databaseAdapter.buildStringCondition(fieldExpr, 'ilike', value)
      case 'regex':
        return this.databaseAdapter.buildStringCondition(fieldExpr, 'regex', value)
      case 'notRegex':
        return this.databaseAdapter.buildStringCondition(fieldExpr, 'notRegex', value)
      case 'isEmpty':
        return or(
          isNull(fieldExpr as AnyColumn),
          eq(fieldExpr as AnyColumn, '')
        ) as SQL
      case 'isNotEmpty':
        return and(
          isNotNull(fieldExpr as AnyColumn),
          ne(fieldExpr as AnyColumn, '')
        ) as SQL
      // PostgreSQL array operators - silent no-op for other databases
      // These use Drizzle's built-in array operator functions
      case 'arrayContains':
        Iif (this.databaseAdapter.getEngineType() === 'postgres') {
          return drizzleArrayContains(fieldExpr as AnyColumn, filteredValues)
        }
        return null
      case 'arrayOverlaps':
        Iif (this.databaseAdapter.getEngineType() === 'postgres') {
          return drizzleArrayOverlaps(fieldExpr as AnyColumn, filteredValues)
        }
        return null
      case 'arrayContained':
        Iif (this.databaseAdapter.getEngineType() === 'postgres') {
          return drizzleArrayContained(fieldExpr as AnyColumn, filteredValues)
        }
        return null
      default:
        return null
    }
  }
 
  /**
   * Build date range condition for time dimensions
   */
  buildDateRangeCondition(
    fieldExpr: AnyColumn | SQL,
    dateRange: string | string[]
  ): SQL | null {
    Iif (!dateRange) return null
 
    // Handle array date range first
    if (Array.isArray(dateRange) && dateRange.length >= 2) {
      const startDate = this.normalizeDate(dateRange[0])
      let endDate = this.normalizeDate(dateRange[1])
 
      Iif (!startDate || !endDate) return null
 
      // For date-only strings, treat end date as end-of-day (23:59:59.999)
      // to include all records on that day
      Eif (typeof dateRange[1] === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(dateRange[1].trim())) {
        const endDateObj = typeof endDate === 'number'
          ? new Date(endDate * (this.databaseAdapter.getEngineType() === 'sqlite' ? 1000 : 1))
          : new Date(endDate)
        const endOfDay = new Date(endDateObj)
        endOfDay.setUTCHours(23, 59, 59, 999)
        if (this.databaseAdapter.isTimestampInteger()) {
          endDate = this.databaseAdapter.getEngineType() === 'sqlite'
            ? Math.floor(endOfDay.getTime() / 1000)
            : endOfDay.getTime()
        } else E{
          // PostgreSQL and MySQL need ISO strings
          endDate = endOfDay.toISOString()
        }
      }
 
      return and(
        gte(fieldExpr as AnyColumn, startDate),
        lte(fieldExpr as AnyColumn, endDate)
      ) as SQL
    }
 
    // Handle string date range
    Eif (typeof dateRange === 'string') {
      // Handle relative date expressions
      const relativeDates = this.parseRelativeDateRange(dateRange)
      if (relativeDates) {
        // Convert Date objects to appropriate format for the database
        let start: string | number
        let end: string | number
 
        if (this.databaseAdapter.isTimestampInteger()) {
          if (this.databaseAdapter.getEngineType() === 'sqlite') {
            start = Math.floor(relativeDates.start.getTime() / 1000)
            end = Math.floor(relativeDates.end.getTime() / 1000)
          } else E{
            start = relativeDates.start.getTime()
            end = relativeDates.end.getTime()
          }
        } else E{
          // PostgreSQL and MySQL need ISO strings
          start = relativeDates.start.toISOString()
          end = relativeDates.end.toISOString()
        }
 
        return and(
          gte(fieldExpr as AnyColumn, start),
          lte(fieldExpr as AnyColumn, end)
        ) as SQL
      }
 
      // Handle absolute date (single date)
      const normalizedDate = this.normalizeDate(dateRange)
      if (!normalizedDate) return null
 
      // For single date, create range for the whole day
      // normalizedDate might be a timestamp (number) or ISO string depending on database
      const dateObj = typeof normalizedDate === 'number'
        ? new Date(normalizedDate * (this.databaseAdapter.getEngineType() === 'sqlite' ? 1000 : 1))
        : new Date(normalizedDate)
      const startOfDay = new Date(dateObj)
      startOfDay.setUTCHours(0, 0, 0, 0)  // Ensure we start at midnight UTC
      const endOfDay = new Date(dateObj)
      endOfDay.setUTCHours(23, 59, 59, 999)  // Ensure we end at 11:59:59.999 UTC
 
      // Convert to appropriate format for the database
      let startValue: string | number
      let endValue: string | number
 
      if (this.databaseAdapter.isTimestampInteger()) {
        if (this.databaseAdapter.getEngineType() === 'sqlite') {
          startValue = Math.floor(startOfDay.getTime() / 1000)
          endValue = Math.floor(endOfDay.getTime() / 1000)
        } else E{
          startValue = startOfDay.getTime()
          endValue = endOfDay.getTime()
        }
      } else E{
        // PostgreSQL and MySQL need ISO strings
        startValue = startOfDay.toISOString()
        endValue = endOfDay.toISOString()
      }
 
      return and(
        gte(fieldExpr as AnyColumn, startValue),
        lte(fieldExpr as AnyColumn, endValue)
      ) as SQL
    }
 
    return null
  }
 
  /**
   * Parse relative date range expressions like "today", "yesterday", "last 7 days", "this month", etc.
   * Handles all 14 DATE_RANGE_OPTIONS from the client
   */
  private parseRelativeDateRange(dateRange: string): { start: Date; end: Date } | null {
    const now = new Date()
    const lowerRange = dateRange.toLowerCase().trim()
    
    // Extract UTC date components for consistent calculations
    const utcYear = now.getUTCFullYear()
    const utcMonth = now.getUTCMonth()
    const utcDate = now.getUTCDate()
    const utcDay = now.getUTCDay()
 
    // Handle "today"
    if (lowerRange === 'today') {
      const start = new Date(now)
      start.setUTCHours(0, 0, 0, 0)
      const end = new Date(now)
      end.setUTCHours(23, 59, 59, 999)
      return { start, end }
    }
 
    // Handle "yesterday"
    if (lowerRange === 'yesterday') {
      const start = new Date(now)
      start.setUTCDate(utcDate - 1)
      start.setUTCHours(0, 0, 0, 0)
      const end = new Date(now)
      end.setUTCDate(utcDate - 1)
      end.setUTCHours(23, 59, 59, 999)
      return { start, end }
    }
 
    // Handle "this week" (Monday to Sunday)
    if (lowerRange === 'this week') {
      const mondayOffset = utcDay === 0 ? -6 : 1 - utcDay // If Sunday, go back 6 days, otherwise go to Monday
      const start = new Date(now)
      start.setUTCDate(utcDate + mondayOffset)
      start.setUTCHours(0, 0, 0, 0)
      
      const end = new Date(start)
      end.setUTCDate(start.getUTCDate() + 6) // Sunday
      end.setUTCHours(23, 59, 59, 999)
      return { start, end }
    }
 
    // Handle "this month"
    if (lowerRange === 'this month') {
      const start = new Date(Date.UTC(utcYear, utcMonth, 1, 0, 0, 0, 0))
      const end = new Date(Date.UTC(utcYear, utcMonth + 1, 0, 23, 59, 59, 999))
      return { start, end }
    }
 
    // Handle "this quarter"
    if (lowerRange === 'this quarter') {
      const quarter = Math.floor(utcMonth / 3)
      const start = new Date(Date.UTC(utcYear, quarter * 3, 1, 0, 0, 0, 0))
      const end = new Date(Date.UTC(utcYear, quarter * 3 + 3, 0, 23, 59, 59, 999))
      return { start, end }
    }
 
    // Handle "this year"
    if (lowerRange === 'this year') {
      const start = new Date(Date.UTC(utcYear, 0, 1, 0, 0, 0, 0))
      const end = new Date(Date.UTC(utcYear, 11, 31, 23, 59, 59, 999))
      return { start, end }
    }
 
    // Handle "last N days" pattern
    const lastDaysMatch = lowerRange.match(/^last\s+(\d+)\s+days?$/)
    if (lastDaysMatch) {
      const days = parseInt(lastDaysMatch[1], 10)
      const start = new Date(now)
      start.setUTCDate(utcDate - days + 1) // Include today in the count
      start.setUTCHours(0, 0, 0, 0)
      const end = new Date(now)
      end.setUTCHours(23, 59, 59, 999)
      return { start, end }
    }
 
    // Handle "last N weeks" pattern
    const lastWeeksMatch = lowerRange.match(/^last\s+(\d+)\s+weeks?$/)
    if (lastWeeksMatch) {
      const weeks = parseInt(lastWeeksMatch[1], 10)
      const days = weeks * 7
      const start = new Date(now)
      start.setUTCDate(utcDate - days + 1) // Include today in the count
      start.setUTCHours(0, 0, 0, 0)
      const end = new Date(now)
      end.setUTCHours(23, 59, 59, 999)
      return { start, end }
    }
 
    // Handle "last week" (previous Monday to Sunday)
    if (lowerRange === 'last week') {
      const lastMondayOffset = utcDay === 0 ? -13 : -6 - utcDay // Go to previous Monday
      const start = new Date(now)
      start.setUTCDate(utcDate + lastMondayOffset)
      start.setUTCHours(0, 0, 0, 0)
      
      const end = new Date(start)
      end.setUTCDate(start.getUTCDate() + 6) // Previous Sunday
      end.setUTCHours(23, 59, 59, 999)
      return { start, end }
    }
 
    // Handle "last month"
    if (lowerRange === 'last month') {
      const start = new Date(Date.UTC(utcYear, utcMonth - 1, 1, 0, 0, 0, 0))
      const end = new Date(Date.UTC(utcYear, utcMonth, 0, 23, 59, 59, 999))
      return { start, end }
    }
 
    // Handle "last quarter"
    if (lowerRange === 'last quarter') {
      const currentQuarter = Math.floor(utcMonth / 3)
      const lastQuarter = currentQuarter === 0 ? 3 : currentQuarter - 1
      const year = currentQuarter === 0 ? utcYear - 1 : utcYear
      const start = new Date(Date.UTC(year, lastQuarter * 3, 1, 0, 0, 0, 0))
      const end = new Date(Date.UTC(year, lastQuarter * 3 + 3, 0, 23, 59, 59, 999))
      return { start, end }
    }
 
    // Handle "last year"
    if (lowerRange === 'last year') {
      const start = new Date(Date.UTC(utcYear - 1, 0, 1, 0, 0, 0, 0))
      const end = new Date(Date.UTC(utcYear - 1, 11, 31, 23, 59, 59, 999))
      return { start, end }
    }
 
    // Handle "last 12 months" (rolling 12 months)
    if (lowerRange === 'last 12 months') {
      const start = new Date(Date.UTC(utcYear, utcMonth - 11, 1, 0, 0, 0, 0))
      const end = new Date(now)
      end.setUTCHours(23, 59, 59, 999)
      return { start, end }
    }
 
    // Handle "last N months" pattern (legacy support)
    const lastMonthsMatch = lowerRange.match(/^last\s+(\d+)\s+months?$/)
    if (lastMonthsMatch) {
      const months = parseInt(lastMonthsMatch[1], 10)
      const start = new Date(Date.UTC(utcYear, utcMonth - months + 1, 1, 0, 0, 0, 0))
      const end = new Date(now)
      end.setUTCHours(23, 59, 59, 999)
      return { start, end }
    }
 
    // Handle "last N years" pattern (legacy support)
    const lastYearsMatch = lowerRange.match(/^last\s+(\d+)\s+years?$/)
    if (lastYearsMatch) {
      const years = parseInt(lastYearsMatch[1], 10)
      const start = new Date(Date.UTC(utcYear - years, 0, 1, 0, 0, 0, 0))
      const end = new Date(now)
      end.setUTCHours(23, 59, 59, 999)
      return { start, end }
    }
 
    return null
  }
 
  /**
   * Normalize date values to handle strings, numbers, and Date objects
   * Returns ISO string for PostgreSQL/MySQL, Unix timestamp for SQLite, or null
   * Ensures dates are in the correct format for each database engine
   */
  private normalizeDate(value: any): string | number | null {
    Iif (!value) return null
 
    // If it's already a Date object, validate and convert to appropriate format
    Iif (value instanceof Date) {
      if (isNaN(value.getTime())) return null
      // Return timestamp for integer-based databases, ISO string for others
      // SQLite stores timestamps as Unix seconds (not milliseconds)
      if (this.databaseAdapter.isTimestampInteger()) {
        return this.databaseAdapter.getEngineType() === 'sqlite'
          ? Math.floor(value.getTime() / 1000)
          : value.getTime()
      }
      // PostgreSQL and MySQL need ISO strings, not Date objects
      return value.toISOString()
    }
 
    // If it's a number, assume it's a timestamp
    Iif (typeof value === 'number') {
      // If it's a reasonable Unix timestamp in seconds (10 digits), convert to milliseconds
      // Otherwise assume it's already in milliseconds
      const timestamp = value < 10000000000 ? value * 1000 : value
      const date = new Date(timestamp)
      if (isNaN(date.getTime())) return null
      // Return timestamp for integer-based databases, ISO string for others
      // SQLite stores timestamps as Unix seconds (not milliseconds)
      if (this.databaseAdapter.isTimestampInteger()) {
        return this.databaseAdapter.getEngineType() === 'sqlite'
          ? Math.floor(timestamp / 1000)
          : timestamp
      }
      // PostgreSQL and MySQL need ISO strings, not Date objects
      return date.toISOString()
    }
 
    // If it's a string, try to parse it as a Date
    Eif (typeof value === 'string') {
      // Check if it's a date-only string (YYYY-MM-DD format)
      // Parse as UTC midnight to avoid timezone/DST issues
      if (/^\d{4}-\d{2}-\d{2}$/.test(value.trim())) {
        const parsed = new Date(value + 'T00:00:00Z')
        if (isNaN(parsed.getTime())) return null
        // Return timestamp for integer-based databases, ISO string for others
        // SQLite stores timestamps as Unix seconds (not milliseconds)
        Eif (this.databaseAdapter.isTimestampInteger()) {
          return this.databaseAdapter.getEngineType() === 'sqlite'
            ? Math.floor(parsed.getTime() / 1000)
            : parsed.getTime()
        }
        // PostgreSQL and MySQL need ISO strings, not Date objects
        return parsed.toISOString()
      }
 
      // For other formats (with time components), use default parsing
      const parsed = new Date(value)
      if (isNaN(parsed.getTime())) return null
      // Return timestamp for integer-based databases, ISO string for others
      // SQLite stores timestamps as Unix seconds (not milliseconds)
      Eif (this.databaseAdapter.isTimestampInteger()) {
        return this.databaseAdapter.getEngineType() === 'sqlite'
          ? Math.floor(parsed.getTime() / 1000)
          : parsed.getTime()
      }
      // PostgreSQL and MySQL need ISO strings, not Date objects
      return parsed.toISOString()
    }
 
    // Try to parse any other type as date
    const parsed = new Date(value)
    if (isNaN(parsed.getTime())) return null
    // Return timestamp for integer-based databases, ISO string for others
    // SQLite stores timestamps as Unix seconds (not milliseconds)
    if (this.databaseAdapter.isTimestampInteger()) {
      return this.databaseAdapter.getEngineType() === 'sqlite'
        ? Math.floor(parsed.getTime() / 1000)
        : parsed.getTime()
    }
    // PostgreSQL and MySQL need ISO strings, not Date objects
    return parsed.toISOString()
  }
 
  /**
   * Build GROUP BY fields from dimensions and time dimensions
   * Works for both single and multi-cube queries
   */
  buildGroupByFields(
    cubes: Map<string, Cube> | Cube, 
    query: SemanticQuery, 
    context: QueryContext,
    queryPlan?: any // Optional QueryPlan for CTE handling
  ): (SQL | AnyColumn)[] {
    const groupFields: (SQL | AnyColumn)[] = []
    
    // Only add GROUP BY if we have measures (aggregations)
    const hasMeasures = query.measures && query.measures.length > 0
    if (!hasMeasures) {
      return []
    }
    
    // Convert single cube to map for consistent handling
    const cubeMap = cubes instanceof Map ? cubes : new Map([[cubes.name, cubes]])
    
    // Add dimensions to GROUP BY
    if (query.dimensions) {
      for (const dimensionName of query.dimensions) {
        const [cubeName, fieldName] = dimensionName.split('.')
        const cube = cubeMap.get(cubeName)
        Eif (cube && cube.dimensions && cube.dimensions[fieldName]) {
          
          // Check if this dimension is from a CTE cube
          const isFromCTE = queryPlan?.preAggregationCTEs?.some((cte: any) => cte.cube.name === cubeName)
          
          if (isFromCTE) {
            // For dimensions from CTE cubes, check if this is a join key that maps to the main table
            const cteInfo = queryPlan.preAggregationCTEs.find((cte: any) => cte.cube.name === cubeName)
            const matchingJoinKey = cteInfo.joinKeys.find((jk: JoinKeyInfo) => jk.targetColumn === fieldName)
            
            Iif (matchingJoinKey && matchingJoinKey.sourceColumnObj) {
              // Use the source column from the main table for GROUP BY instead of the CTE dimension
              groupFields.push(matchingJoinKey.sourceColumnObj)
            } else {
              // This dimension from CTE cube is not a join key - we need to reference it from the CTE
              // But only if it was included in the CTE selections
              const cteDimensionExpr = sql`${sql.identifier(cteInfo.cteAlias)}.${sql.identifier(fieldName)}`
              groupFields.push(cteDimensionExpr)
            }
          } else {
            // Regular dimension from non-CTE cube
            const dimension = cube.dimensions[fieldName]
            const dimensionExpr = resolveSqlExpression(dimension.sql, context)
            groupFields.push(dimensionExpr)
          }
        }
      }
    }
    
    // Add time dimensions to GROUP BY
    if (query.timeDimensions) {
      for (const timeDim of query.timeDimensions) {
        const [cubeName, fieldName] = timeDim.dimension.split('.')
        const cube = cubeMap.get(cubeName)
        Eif (cube && cube.dimensions && cube.dimensions[fieldName]) {
          
          // Check if this time dimension is from a CTE cube
          const isFromCTE = queryPlan?.preAggregationCTEs?.some((cte: any) => cte.cube.name === cubeName)
          
          if (isFromCTE) {
            // For time dimensions from CTE cubes, check if this is a join key that maps to the main table
            const cteInfo = queryPlan.preAggregationCTEs.find((cte: any) => cte.cube.name === cubeName)
            const matchingJoinKey = cteInfo.joinKeys.find((jk: JoinKeyInfo) => jk.targetColumn === fieldName)
            
            Iif (matchingJoinKey && matchingJoinKey.sourceColumnObj) {
              // Use the source column from the main table for GROUP BY with time granularity
              // const dimension = cube.dimensions[fieldName] // Unused
              const timeExpr = this.buildTimeDimensionExpression(
                matchingJoinKey.sourceColumnObj, 
                timeDim.granularity, 
                context
              )
              groupFields.push(timeExpr)
            } else {
              // This time dimension from CTE cube is not a join key - reference it from the CTE
              // The CTE already has the time dimension expression applied, so just reference the column
              const cteDimensionExpr = sql`${sql.identifier(cteInfo.cteAlias)}.${sql.identifier(fieldName)}`
              groupFields.push(cteDimensionExpr)
            }
          } else {
            // Regular time dimension from non-CTE cube
            const dimension = cube.dimensions[fieldName]
            const timeExpr = this.buildTimeDimensionExpression(
              dimension.sql, 
              timeDim.granularity, 
              context
            )
            groupFields.push(timeExpr)
          }
        }
      }
    }
    
    // Note: We used to add join keys from CTEs to GROUP BY, but this is unnecessary
    // Join keys are only needed for the JOIN condition, not for grouping
    // The GROUP BY should only contain columns that are actually selected or used for aggregation
    
    return groupFields
  }
 
  /**
   * Build ORDER BY clause with automatic time dimension sorting
   */
  buildOrderBy(query: SemanticQuery, selectedFields?: string[]): SQL[] {
    const orderClauses: SQL[] = []
    
    // Get all selected fields (measures + dimensions + timeDimensions)
    const allSelectedFields = selectedFields || [
      ...(query.measures || []),
      ...(query.dimensions || []),
      ...(query.timeDimensions?.map(td => td.dimension) || [])
    ]
    
    // First, add explicit ordering from query.order
    if (query.order && Object.keys(query.order).length > 0) {
      for (const [field, direction] of Object.entries(query.order)) {
        // Validate that the field exists in the selected fields
        if (!allSelectedFields.includes(field)) {
          throw new Error(`Cannot order by '${field}': field is not selected in the query`)
        }
        
        // Use Drizzle's built-in asc/desc functions for proper ordering
        const orderClause = direction === 'desc' ? desc(sql.identifier(field)) : asc(sql.identifier(field))
        orderClauses.push(orderClause)
      }
    }
    
    // Then, automatically add time dimension sorting for any time dimensions not explicitly ordered
    if (query.timeDimensions && query.timeDimensions.length > 0) {
      const explicitlyOrderedFields = new Set(Object.keys(query.order || {}))
      
      // Sort time dimensions by their dimension name to ensure consistent ordering
      const sortedTimeDimensions = [...query.timeDimensions].sort((a, b) => 
        a.dimension.localeCompare(b.dimension)
      )
      
      for (const timeDim of sortedTimeDimensions) {
        if (!explicitlyOrderedFields.has(timeDim.dimension)) {
          // Automatically sort time dimensions in ascending order (earliest to latest)
          orderClauses.push(asc(sql.identifier(timeDim.dimension)))
        }
      }
    }
    
    return orderClauses
  }
 
  /**
   * Collect numeric field names (measures + numeric dimensions) for type conversion
   * Works for both single and multi-cube queries
   */
  collectNumericFields(cubes: Map<string, Cube> | Cube, query: SemanticQuery): string[] {
    const numericFields: string[] = []
    
    // Convert single cube to map for consistent handling
    const cubeMap = cubes instanceof Map ? cubes : new Map([[cubes.name, cubes]])
    
    // Add all measure fields (they are always numeric)
    if (query.measures) {
      numericFields.push(...query.measures)
    }
    
    // Add numeric dimension fields
    if (query.dimensions) {
      for (const dimensionName of query.dimensions) {
        const [cubeName, fieldName] = dimensionName.split('.')
        const cube = cubeMap.get(cubeName)
        Eif (cube) {
          const dimension = cube.dimensions[fieldName]
          if (dimension && dimension.type === 'number') {
            // Use the full name (with prefix) as it appears in the result
            numericFields.push(dimensionName)
          }
        }
      }
    }
    
    return numericFields
  }
 
  /**
   * Apply LIMIT and OFFSET to a query with validation
   * If offset is provided without limit, add a reasonable default limit
   */
  applyLimitAndOffset<T>(query: T, semanticQuery: SemanticQuery): T {
    // If offset is provided without limit, add a reasonable default limit
    let effectiveLimit = semanticQuery.limit
    if (semanticQuery.offset !== undefined && semanticQuery.offset > 0 && effectiveLimit === undefined) {
      effectiveLimit = 50 // Default limit when offset is used
    }
    
    let result = query
    
    if (effectiveLimit !== undefined) {
      if (effectiveLimit < 0) {
        throw new Error('Limit must be non-negative')
      }
      result = (result as any).limit(effectiveLimit)
    }
    
    if (semanticQuery.offset !== undefined) {
      if (semanticQuery.offset < 0) {
        throw new Error('Offset must be non-negative')
      }
      result = (result as any).offset(semanticQuery.offset)
    }
    
    return result
  }
}