All files / server executor.ts

72.25% Statements 435/602
65.83% Branches 291/442
78.57% Functions 33/42
72.77% Lines 425/584

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 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957                                                                                                                        133x   133x 133x     133x 133x 133x 133x 133x 133x 133x 133x                         915x   915x   15x 15x 2x       900x   18x 18x 3x       882x                   882x 882x 26x             884x 14x     14x 14x 14x 14x 13x 5x             5x                                 8x           1x                           879x 5x       874x 13x       861x 15x       846x         846x     846x               846x     846x     846x     846x     846x 846x     835x 35423x 35423x 32009x 45228x 45228x     45228x 45194x 45194x     45194x       45228x 45228x       35423x       915x 915x     915x   915x           915x 9x 9x 9x         8x           1x         835x       42x 42x 42x 2x       42x     42x 42x 42x 42x   42x 42x                                                           5x     5x                                     5x                         5x 5x         5x       5x         5x     5x   10x       10x   10x       5x     5x             5x         5x                       13x     13x                                     13x                               13x     13x 13x         13x               13x     13x     13x         13x               13x   28x             13x                             15x     15x                                     15x                                 15x     15x 15x         15x             15x     15x     15x     15x               15x                 15x                                                                                                                                                                                                                             10x     10x               10x     10x     10x     10x 10x     10x 52x 52x 52x 52x 52x     52x 52x 52x     52x       52x 52x       52x       10x 10x     10x   10x                               843x 843x 843x 843x                                                                                                           882x   882x 151x 162x 43x 43x     43x 41x     41x 41x         41x       43x 43x 41x                   882x 882x   882x   882x 151x 162x 162x 162x 162x     162x 108x 108x                         882x     882x                 882x 882x 199x 162x     162x 206x 199x 199x 199x 199x 199x           199x   2x 2x                 197x       155x 155x     41x 41x         1x 1x                   199x           162x 504x 504x   234x     234x 234x   234x     234x     234x 35x 35x   35x       234x   5x 229x   30x                       882x 881x   881x 1153x 1153x   1153x 1153x     1153x 11x   11x       11x 11x   11x 11x         11x 3x       11x       3x   3x     8x       11x 1x       11x                 11x 11x                   882x     882x         882x 151x             882x                                         882x     882x 199x   244x     244x 2x     2x 2x 2x 2x     2x                 2x 2x   2x 2x                         2x 2x                     244x   162x   162x   162x       82x       82x 82x     82x   82x                           82x       244x       244x       244x 244x   171x   171x 9x   171x   73x   73x                                           882x 882x       882x 199x   244x 244x 162x         82x 9x       73x 73x 73x             882x                 882x 382x       882x 882x     882x       882x               882x 439x       882x               882x 26x     26x       882x 882x 198x       880x   880x             2112x 2112x   2112x 2112x 1784x       2112x                             24x 24x 24x                     5x                                                                                                                                                                                                                                                                                                                                               29x             29x     29x     29x   29x                         845x 845x 845x     845x 845x 240x       845x 844x 1116x 1368x 1116x 1116x 1116x                   845x 304x 349x 434x 349x 349x 349x                   845x 127x 134x 159x 134x 134x 134x                   845x                                       856x   371x   371x 646x     646x     544x 544x 544x   544x 646x       524x 524x     5x       519x 519x               519x 482x                     853x 127x 134x 77x     77x   77x 77x 77x   77x 77x   77x 77x   77x 73x                                                           11x       11x 8x 3x 3x     3x                   11x 11x   11x       11x 10x 10x 10x     8x 8x 3x             5x 8x 5x                           3x 11x                 3x       11x   3x               11x                                                               11x                           11x                         11x         11x   11x       3x                         8x                                                
/**
 * Unified Drizzle Query Executor
 * Handles both single and multi-cube queries through a unified execution path
 * Uses QueryBuilder for SQL generation and QueryPlanner for query planning
 */
 
import {
  and,
  eq,
  sql,
  SQL,
  sum,
  min,
  max
} from 'drizzle-orm'
 
import type {
  SecurityContext,
  SemanticQuery,
  QueryResult,
  MeasureAnnotation,
  DimensionAnnotation,
  TimeDimensionAnnotation,
  DatabaseExecutor,
  Cube,
  QueryContext,
  QueryPlan,
  JoinKeyInfo,
  CacheConfig,
  ExplainOptions,
  ExplainResult,
  ExecutionOptions
} from './types'
 
import { resolveSqlExpression } from './cube-utils'
import { FilterCacheManager, getFilterKey, getTimeDimensionFilterKey, flattenFilters } from './filter-cache'
import { generateCacheKey } from './cache-utils'
import { QueryBuilder } from './query-builder'
import { QueryPlanner } from './query-planner'
import { CTEBuilder } from './cte-builder'
import { MeasureBuilder } from './builders/measure-builder'
import { validateQueryAgainstCubes } from './compiler'
import { applyGapFilling } from './gap-filler'
import type { DatabaseAdapter } from './adapters/base-adapter'
import { ComparisonQueryBuilder } from './comparison-query-builder'
import { FunnelQueryBuilder } from './funnel-query-builder'
import { FlowQueryBuilder } from './flow-query-builder'
import { RetentionQueryBuilder } from './retention-query-builder'
 
export class QueryExecutor {
  private queryBuilder: QueryBuilder
  private queryPlanner: QueryPlanner
  private cteBuilder: CTEBuilder
  private databaseAdapter: DatabaseAdapter
  private comparisonQueryBuilder: ComparisonQueryBuilder
  private funnelQueryBuilder: FunnelQueryBuilder
  private flowQueryBuilder: FlowQueryBuilder
  private retentionQueryBuilder: RetentionQueryBuilder
  private cacheConfig?: CacheConfig
 
  constructor(private dbExecutor: DatabaseExecutor, cacheConfig?: CacheConfig) {
    // Get the database adapter from the executor
    this.databaseAdapter = dbExecutor.databaseAdapter
    Iif (!this.databaseAdapter) {
      throw new Error('DatabaseExecutor must have a databaseAdapter property')
    }
    this.queryBuilder = new QueryBuilder(this.databaseAdapter)
    this.queryPlanner = new QueryPlanner()
    this.cteBuilder = new CTEBuilder(this.queryBuilder)
    this.comparisonQueryBuilder = new ComparisonQueryBuilder(this.databaseAdapter)
    this.funnelQueryBuilder = new FunnelQueryBuilder(this.databaseAdapter)
    this.flowQueryBuilder = new FlowQueryBuilder(this.databaseAdapter)
    this.retentionQueryBuilder = new RetentionQueryBuilder(this.databaseAdapter)
    this.cacheConfig = cacheConfig
  }
 
  /**
   * Unified query execution method that handles both single and multi-cube queries
   * @param options.skipCache - Skip cache lookup (but still cache the fresh result)
   */
  async execute(
    cubes: Map<string, Cube>,
    query: SemanticQuery,
    securityContext: SecurityContext,
    options?: ExecutionOptions
  ): Promise<QueryResult> {
    try {
      // Check for funnel queries FIRST - funnel queries have different validation
      if (this.funnelQueryBuilder.hasFunnel(query)) {
        // Validate funnel configuration separately
        const funnelValidation = this.funnelQueryBuilder.validateConfig(query.funnel!, cubes)
        if (!funnelValidation.isValid) {
          throw new Error(`Funnel validation failed: ${funnelValidation.errors.join(', ')}`)
        }
        // Skip standard validation for funnel queries and go directly to execution
        // (after cache check below)
      } else if (this.flowQueryBuilder.hasFlow(query)) {
        // Validate flow configuration separately
        const flowValidation = this.flowQueryBuilder.validateConfig(query.flow!, cubes)
        if (!flowValidation.isValid) {
          throw new Error(`Flow validation failed: ${flowValidation.errors.join(', ')}`)
        }
        // Skip standard validation for flow queries and go directly to execution
        // (after cache check below)
      I} else if (this.retentionQueryBuilder.hasRetention(query)) {
        // Validate retention configuration separately
        const retentionValidation = this.retentionQueryBuilder.validateConfig(query.retention!, cubes)
        if (!retentionValidation.isValid) {
          throw new Error(`Retention validation failed: ${retentionValidation.errors.join(', ')}`)
        }
        // Skip standard validation for retention queries and go directly to execution
        // (after cache check below)
      } else {
        // Standard validation for non-funnel/non-flow queries
        const validation = validateQueryAgainstCubes(cubes, query)
        if (!validation.isValid) {
          throw new Error(`Query validation failed: ${validation.errors.join(', ')}`)
        }
      }
 
      // Check cache BEFORE expensive operations (after validation, includes security context)
      // Skip cache lookup if options.skipCache is true (but still cache the result later)
      let cacheKey: string | undefined
      if (this.cacheConfig?.enabled !== false && this.cacheConfig?.provider) {
        cacheKey = generateCacheKey(query, securityContext, this.cacheConfig)
 
        // Only do cache lookup if not explicitly bypassing cache
        if (!options?.skipCache) {
          try {
            const startTime = Date.now()
            const cacheResult = await this.cacheConfig.provider.get<QueryResult>(cacheKey)
            if (cacheResult) {
              this.cacheConfig.onCacheEvent?.({
                type: 'hit',
                key: cacheKey,
                durationMs: Date.now() - startTime
              })
 
              // Return cached result WITH cache metadata
              return {
                ...cacheResult.value,
                cache: cacheResult.metadata
                  ? {
                      hit: true,
                      cachedAt: new Date(cacheResult.metadata.cachedAt).toISOString(),
                      ttlMs: cacheResult.metadata.ttlMs,
                      ttlRemainingMs: cacheResult.metadata.ttlRemainingMs
                    }
                  : {
                      hit: true,
                      cachedAt: new Date().toISOString(),
                      ttlMs: 0,
                      ttlRemainingMs: 0
                    }
              }
            }
            this.cacheConfig.onCacheEvent?.({
              type: 'miss',
              key: cacheKey,
              durationMs: Date.now() - startTime
            })
          } catch (error) {
            this.cacheConfig.onError?.(error as Error, 'get')
            // Continue without cache - failures are non-fatal
          }
        } else E{
          // skipCache requested - emit a bypass event if handler exists
          this.cacheConfig.onCacheEvent?.({
            type: 'miss',
            key: cacheKey,
            durationMs: 0
          })
        }
      }
 
      // Check for compareDateRange queries and route to comparison execution
      if (this.comparisonQueryBuilder.hasComparison(query)) {
        return this.executeComparisonQueryWithCache(cubes, query, securityContext, cacheKey)
      }
 
      // Check for funnel queries and route to funnel execution
      if (this.funnelQueryBuilder.hasFunnel(query)) {
        return this.executeFunnelQueryWithCache(cubes, query, securityContext, cacheKey)
      }
 
      // Check for flow queries and route to flow execution
      if (this.flowQueryBuilder.hasFlow(query)) {
        return this.executeFlowQueryWithCache(cubes, query, securityContext, cacheKey)
      }
 
      // Check for retention queries and route to retention execution
      Iif (this.retentionQueryBuilder.hasRetention(query)) {
        return this.executeRetentionQueryWithCache(cubes, query, securityContext, cacheKey)
      }
 
      // Create filter cache for parameter deduplication across CTEs
      const filterCache = new FilterCacheManager()
 
      // Create query context with filter cache
      const context: QueryContext = {
        db: this.dbExecutor.db,
        schema: this.dbExecutor.schema,
        securityContext,
        filterCache
      }
 
      // Pre-build filter SQL for reuse across CTEs and main query
      this.preloadFilterCache(query, filterCache, cubes, context)
 
      // Create unified query plan (works for both single and multi-cube)
      const queryPlan = this.queryPlanner.createQueryPlan(cubes, query, context)
 
      // Validate security context is applied to all cubes in the query plan
      this.validateSecurityContext(queryPlan, context)
 
      // Build the query using unified approach
      const builtQuery = this.buildUnifiedQuery(queryPlan, query, context)
 
      // Execute query - pass numeric field names for selective conversion
      const numericFields = this.queryBuilder.collectNumericFields(cubes, query)
      const data = await this.dbExecutor.execute(builtQuery, numericFields)
      
      // Process time dimension results
      const mappedData = Array.isArray(data) ? data.map(row => {
        const mappedRow = { ...row }
        if (query.timeDimensions) {
          for (const timeDim of query.timeDimensions) {
            Eif (timeDim.dimension in mappedRow) {
              let dateValue = mappedRow[timeDim.dimension]
 
              // If we have a date that is not 'T' in the center and Z at the end, we need to fix it
              if (typeof dateValue === 'string' && dateValue.match(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/)) {
                const isoString = dateValue.replace(' ', 'T')
                const finalIsoString = !isoString.endsWith('Z') && !isoString.includes('+')
                  ? isoString + 'Z'
                  : isoString
                dateValue = new Date(finalIsoString)
              }
 
              // Convert time dimension result using database adapter if required
              dateValue = this.databaseAdapter.convertTimeDimensionResult(dateValue)
              mappedRow[timeDim.dimension] = dateValue
            }
          }
        }
        return mappedRow
      }) : [data]
 
      // Apply gap filling for time series if requested
      const measureNames = query.measures || []
      const filledData = applyGapFilling(mappedData, query, measureNames)
 
      // Generate annotations for UI
      const annotation = this.generateAnnotations(queryPlan, query)
 
      const result: QueryResult = {
        data: filledData,
        annotation
      }
 
      // Cache result before returning (without cache metadata - that's only on cache hits)
      if (cacheKey && this.cacheConfig?.provider) {
        try {
          const startTime = Date.now()
          await this.cacheConfig.provider.set(
            cacheKey,
            result,
            this.cacheConfig.defaultTtlMs ?? 300000
          )
          this.cacheConfig.onCacheEvent?.({
            type: 'set',
            key: cacheKey,
            durationMs: Date.now() - startTime
          })
        } catch (error) {
          this.cacheConfig.onError?.(error as Error, 'set')
          // Continue without caching - failures are non-fatal
        }
      }
 
      return result
    } catch (error) {
      // Extract the actual database error from the cause chain
      // Drizzle ORM wraps database errors, but the real error is in the cause
      Eif (error instanceof Error) {
        let dbError: Error = error
        while (dbError.cause instanceof Error) {
          dbError = dbError.cause
        }
 
        // Build comprehensive error message with the actual database error
        let message = dbError.message
 
        // Add PostgreSQL-specific details if available
        const pgError = dbError as any
        if (pgError.code) message += ` [${pgError.code}]`
        Iif (pgError.detail) message += ` Detail: ${pgError.detail}`
        Iif (pgError.hint) message += ` Hint: ${pgError.hint}`
 
        error.message = `Query execution failed: ${message}`
        throw error
      }
      throw new Error(`Query execution failed: Unknown error`)
    }
  }
 
  /**
   * Legacy interface for single cube queries
   */
  async executeQuery(
    cube: Cube,
    query: SemanticQuery,
    securityContext: SecurityContext
  ): Promise<QueryResult> {
    // Convert single cube to map for unified execution
    const cubes = new Map<string, Cube>()
    cubes.set(cube.name, cube)
    return this.execute(cubes, query, securityContext)
  }
 
  /**
   * Execute a comparison query with caching support
   * Wraps executeComparisonQuery with cache set logic
   */
  private async executeComparisonQueryWithCache(
    cubes: Map<string, Cube>,
    query: SemanticQuery,
    securityContext: SecurityContext,
    cacheKey: string | undefined
  ): Promise<QueryResult> {
    const result = await this.executeComparisonQuery(cubes, query, securityContext)
 
    // Cache result before returning (without cache metadata - that's only on cache hits)
    Iif (cacheKey && this.cacheConfig?.provider) {
      try {
        const startTime = Date.now()
        await this.cacheConfig.provider.set(
          cacheKey,
          result,
          this.cacheConfig.defaultTtlMs ?? 300000
        )
        this.cacheConfig.onCacheEvent?.({
          type: 'set',
          key: cacheKey,
          durationMs: Date.now() - startTime
        })
      } catch (error) {
        this.cacheConfig.onError?.(error as Error, 'set')
        // Continue without caching - failures are non-fatal
      }
    }
 
    return result
  }
 
  /**
   * Execute a comparison query with multiple date periods
   * Expands compareDateRange into multiple sub-queries and merges results
   */
  private async executeComparisonQuery(
    cubes: Map<string, Cube>,
    query: SemanticQuery,
    securityContext: SecurityContext
  ): Promise<QueryResult> {
    // Get the time dimension with compareDateRange
    const timeDimension = this.comparisonQueryBuilder.getComparisonTimeDimension(query)
    Iif (!timeDimension || !timeDimension.compareDateRange) {
      throw new Error('No compareDateRange found in query')
    }
 
    // Normalize periods (parse relative dates, etc.)
    const periods = this.comparisonQueryBuilder.normalizePeriods(
      timeDimension.compareDateRange
    )
 
    Iif (periods.length < 2) {
      throw new Error('compareDateRange requires at least 2 periods')
    }
 
    // Get granularity (default to 'day' if not specified)
    const granularity = timeDimension.granularity || 'day'
 
    // Execute query for each period in parallel
    const periodResultPromises = periods.map(async (period) => {
      // Create a sub-query for this specific period
      const periodQuery = this.comparisonQueryBuilder.createPeriodQuery(query, period)
 
      // Execute using the standard path (this.execute handles the rest)
      // Note: We call executeStandardQuery to avoid recursion
      const result = await this.executeStandardQuery(cubes, periodQuery, securityContext)
 
      return { result, period }
    })
 
    // Wait for all period queries to complete
    const periodResults = await Promise.all(periodResultPromises)
 
    // Merge results with period metadata
    const mergedResult = this.comparisonQueryBuilder.mergeComparisonResults(
      periodResults,
      timeDimension,
      granularity
    )
 
    // Sort by period index and time dimension
    mergedResult.data = this.comparisonQueryBuilder.sortComparisonResults(
      mergedResult.data as any,
      timeDimension.dimension
    )
 
    return mergedResult
  }
 
  /**
   * Execute a funnel query with caching support
   */
  private async executeFunnelQueryWithCache(
    cubes: Map<string, Cube>,
    query: SemanticQuery,
    securityContext: SecurityContext,
    cacheKey: string | undefined
  ): Promise<QueryResult> {
    const result = await this.executeFunnelQuery(cubes, query, securityContext)
 
    // Cache result before returning
    Iif (cacheKey && this.cacheConfig?.provider) {
      try {
        const startTime = Date.now()
        await this.cacheConfig.provider.set(
          cacheKey,
          result,
          this.cacheConfig.defaultTtlMs ?? 300000
        )
        this.cacheConfig.onCacheEvent?.({
          type: 'set',
          key: cacheKey,
          durationMs: Date.now() - startTime
        })
      } catch (error) {
        this.cacheConfig.onError?.(error as Error, 'set')
      }
    }
 
    // Return result with cache metadata (miss - freshly computed)
    return {
      ...result,
      cache: {
        hit: false
      }
    }
  }
 
  /**
   * Execute a funnel analysis query
   */
  private async executeFunnelQuery(
    cubes: Map<string, Cube>,
    query: SemanticQuery,
    securityContext: SecurityContext
  ): Promise<QueryResult> {
    const config = query.funnel!
 
    // Validate funnel configuration
    const validation = this.funnelQueryBuilder.validateConfig(config, cubes)
    Iif (!validation.isValid) {
      throw new Error(`Funnel validation failed: ${validation.errors.join(', ')}`)
    }
 
    // Create query context
    const context: QueryContext = {
      db: this.dbExecutor.db,
      schema: this.dbExecutor.schema,
      securityContext
    }
 
    // Build funnel query using Drizzle query builder
    // The refactored buildFunnelQuery returns a query builder with .toSQL() support
    const funnelQuery = this.funnelQueryBuilder.buildFunnelQuery(config, cubes, context)
 
    // Execute the query builder directly
    const rawResult = await funnelQuery as unknown as Record<string, unknown>[]
 
    // Transform to step rows
    const funnelRows = this.funnelQueryBuilder.transformResult(rawResult, config)
 
    // Build annotation with funnel metadata
    // Note: Funnel queries have a different annotation structure
    // The funnel property contains the funnel-specific metadata
    const annotation: QueryResult['annotation'] & { funnel?: unknown } = {
      measures: {} as Record<string, MeasureAnnotation>,
      dimensions: {} as Record<string, DimensionAnnotation>,
      segments: {},
      timeDimensions: {} as Record<string, TimeDimensionAnnotation>
    }
 
    // Add funnel metadata to annotation (as additional property)
    ;(annotation as any).funnel = {
      config,
      steps: config.steps.map((step, index) => ({
        name: step.name,
        index,
        timeToConvert: step.timeToConvert
      }))
    }
 
    return {
      data: funnelRows as unknown as Record<string, unknown>[],
      annotation
    }
  }
 
  /**
   * Execute a flow query with caching support
   */
  private async executeFlowQueryWithCache(
    cubes: Map<string, Cube>,
    query: SemanticQuery,
    securityContext: SecurityContext,
    cacheKey: string | undefined
  ): Promise<QueryResult> {
    const result = await this.executeFlowQuery(cubes, query, securityContext)
 
    // Cache result before returning
    Iif (cacheKey && this.cacheConfig?.provider) {
      try {
        const startTime = Date.now()
        await this.cacheConfig.provider.set(
          cacheKey,
          result,
          this.cacheConfig.defaultTtlMs ?? 300000
        )
        this.cacheConfig.onCacheEvent?.({
          type: 'set',
          key: cacheKey,
          durationMs: Date.now() - startTime
        })
      } catch (error) {
        this.cacheConfig.onError?.(error as Error, 'set')
      }
    }
 
    // Return result with cache metadata (miss - freshly computed)
    return {
      ...result,
      cache: {
        hit: false
      }
    }
  }
 
  /**
   * Execute a flow analysis query
   * Produces Sankey diagram data (nodes and links)
   */
  private async executeFlowQuery(
    cubes: Map<string, Cube>,
    query: SemanticQuery,
    securityContext: SecurityContext
  ): Promise<QueryResult> {
    const config = query.flow!
 
    // Validate flow configuration
    const validation = this.flowQueryBuilder.validateConfig(config, cubes)
    Iif (!validation.isValid) {
      throw new Error(`Flow validation failed: ${validation.errors.join(', ')}`)
    }
 
    // Create query context
    const context: QueryContext = {
      db: this.dbExecutor.db,
      schema: this.dbExecutor.schema,
      securityContext
    }
 
    // Build flow query using Drizzle query builder
    const flowQuery = this.flowQueryBuilder.buildFlowQuery(config, cubes, context)
 
    // Execute the query
    const rawResult = await flowQuery as unknown as Record<string, unknown>[]
 
    // Transform to FlowResultRow (nodes and links)
    const flowData = this.flowQueryBuilder.transformResult(rawResult)
 
    // Build annotation with flow metadata
    const annotation: QueryResult['annotation'] & { flow?: unknown } = {
      measures: {} as Record<string, MeasureAnnotation>,
      dimensions: {} as Record<string, DimensionAnnotation>,
      segments: {},
      timeDimensions: {} as Record<string, TimeDimensionAnnotation>
    }
 
    // Add flow metadata to annotation
    ;(annotation as any).flow = {
      config,
      startingStep: {
        name: config.startingStep.name,
      },
      stepsBefore: config.stepsBefore,
      stepsAfter: config.stepsAfter,
    }
 
    return {
      data: [flowData] as unknown as Record<string, unknown>[],
      annotation
    }
  }
 
  /**
   * Execute a retention query with caching support
   */
  private async executeRetentionQueryWithCache(
    cubes: Map<string, Cube>,
    query: SemanticQuery,
    securityContext: SecurityContext,
    cacheKey: string | undefined
  ): Promise<QueryResult> {
    const result = await this.executeRetentionQuery(cubes, query, securityContext)
 
    // Cache result before returning
    if (cacheKey && this.cacheConfig?.provider) {
      try {
        const startTime = Date.now()
        await this.cacheConfig.provider.set(
          cacheKey,
          result,
          this.cacheConfig.defaultTtlMs ?? 300000
        )
        this.cacheConfig.onCacheEvent?.({
          type: 'set',
          key: cacheKey,
          durationMs: Date.now() - startTime
        })
      } catch (error) {
        this.cacheConfig.onError?.(error as Error, 'set')
      }
    }
 
    // Return result with cache metadata (miss - freshly computed)
    return {
      ...result,
      cache: {
        hit: false
      }
    }
  }
 
  /**
   * Execute a retention analysis query
   * Calculates cohort-based retention rates
   */
  private async executeRetentionQuery(
    cubes: Map<string, Cube>,
    query: SemanticQuery,
    securityContext: SecurityContext
  ): Promise<QueryResult> {
    const config = query.retention!
 
    // Validate retention configuration
    const validation = this.retentionQueryBuilder.validateConfig(config, cubes)
    if (!validation.isValid) {
      throw new Error(`Retention validation failed: ${validation.errors.join(', ')}`)
    }
 
    // Create query context
    const context: QueryContext = {
      db: this.dbExecutor.db,
      schema: this.dbExecutor.schema,
      securityContext
    }
 
    // Build retention query using Drizzle query builder
    const retentionQuery = this.retentionQueryBuilder.buildRetentionQuery(config, cubes, context)
 
    // Execute the query
    const rawResult = await retentionQuery as unknown as Record<string, unknown>[]
 
    // Transform to RetentionResultRow
    const retentionRows = this.retentionQueryBuilder.transformResult(rawResult, config)
 
    // Build annotation with retention metadata
    const annotation: QueryResult['annotation'] & { retention?: unknown } = {
      measures: {} as Record<string, MeasureAnnotation>,
      dimensions: {} as Record<string, DimensionAnnotation>,
      segments: {},
      timeDimensions: {} as Record<string, TimeDimensionAnnotation>
    }
 
    // Add retention metadata to annotation
    ;(annotation as any).retention = {
      config,
      granularity: config.granularity,
      periods: config.periods,
      retentionType: config.retentionType,
      breakdownDimensions: config.breakdownDimensions
    }
 
    return {
      data: retentionRows as unknown as Record<string, unknown>[],
      annotation
    }
  }
 
  /**
   * Standard query execution (non-comparison)
   * This is the core execution logic extracted for use by comparison queries
   */
  private async executeStandardQuery(
    cubes: Map<string, Cube>,
    query: SemanticQuery,
    securityContext: SecurityContext
  ): Promise<QueryResult> {
    // Create filter cache for parameter deduplication across CTEs
    const filterCache = new FilterCacheManager()
 
    // Create query context with filter cache
    const context: QueryContext = {
      db: this.dbExecutor.db,
      schema: this.dbExecutor.schema,
      securityContext,
      filterCache
    }
 
    // Pre-build filter SQL for reuse across CTEs and main query
    this.preloadFilterCache(query, filterCache, cubes, context)
 
    // Create unified query plan (works for both single and multi-cube)
    const queryPlan = this.queryPlanner.createQueryPlan(cubes, query, context)
 
    // Build the query using unified approach
    const builtQuery = this.buildUnifiedQuery(queryPlan, query, context)
 
    // Execute query - pass numeric field names for selective conversion
    const numericFields = this.queryBuilder.collectNumericFields(cubes, query)
    const data = await this.dbExecutor.execute(builtQuery, numericFields)
 
    // Process time dimension results
    const mappedData = Array.isArray(data) ? data.map(row => {
      const mappedRow = { ...row }
      Eif (query.timeDimensions) {
        for (const timeDim of query.timeDimensions) {
          Eif (timeDim.dimension in mappedRow) {
            let dateValue = mappedRow[timeDim.dimension]
 
            // If we have a date that is not 'T' in the center and Z at the end, we need to fix it
            Eif (typeof dateValue === 'string' && dateValue.match(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/)) {
              const isoString = dateValue.replace(' ', 'T')
              const finalIsoString = !isoString.endsWith('Z') && !isoString.includes('+')
                ? isoString + 'Z'
                : isoString
              dateValue = new Date(finalIsoString)
            }
 
            // Convert time dimension result using database adapter if required
            dateValue = this.databaseAdapter.convertTimeDimensionResult(dateValue)
            mappedRow[timeDim.dimension] = dateValue
          }
        }
      }
      return mappedRow
    }) : [data]
 
    // Apply gap filling for time series if requested
    const measureNames = query.measures || []
    const filledData = applyGapFilling(mappedData, query, measureNames)
 
    // Generate annotations for UI
    const annotation = this.generateAnnotations(queryPlan, query)
 
    return {
      data: filledData,
      annotation
    }
  }
 
  /**
   * Validate that all cubes in the query plan have proper security filtering.
   * Emits a warning if a cube's sql() function doesn't return a WHERE clause.
   *
   * Security is critical in multi-tenant applications - this validation helps
   * detect cubes that may leak data across tenants.
   */
  private validateSecurityContext(queryPlan: QueryPlan, context: QueryContext): void {
    // Only run validation in development or when explicitly enabled
    // Use safe check for process.env to support edge runtimes (Cloudflare Workers, etc.)
    const nodeEnv = typeof process !== 'undefined' ? process.env?.NODE_ENV : undefined
    const warnSecurity = typeof process !== 'undefined' ? process.env?.DRIZZLE_CUBE_WARN_SECURITY : undefined
    Eif (nodeEnv !== 'development' && !warnSecurity) {
      return
    }
 
    // Collect all cubes in the query (primary + joined cubes + CTE cubes)
    const cubesToCheck: Cube[] = [queryPlan.primaryCube]
 
    for (const joinInfo of queryPlan.joinCubes || []) {
      cubesToCheck.push(joinInfo.cube)
    }
 
    for (const cteInfo of queryPlan.preAggregationCTEs || []) {
      cubesToCheck.push(cteInfo.cube)
    }
 
    // Track unique cubes to avoid duplicate warnings
    const checkedCubes = new Set<string>()
 
    // Check each cube's security context
    for (const cube of cubesToCheck) {
      if (checkedCubes.has(cube.name)) continue
      checkedCubes.add(cube.name)
 
      try {
        // Skip warning for cubes explicitly marked as public
        if (cube.public) continue
 
        const securityResult = cube.sql(context)
 
        // A properly secured cube should have a 'where' clause that filters by security context
        // If no 'where' clause is present, the cube might be returning all data
        if (!securityResult.where) {
          console.warn(
            `[drizzle-cube] WARNING: Cube '${cube.name}' has no security filtering. ` +
            `If this cube contains public data, add 'public: true' to suppress this warning. ` +
            `Otherwise, ensure sql() returns: { from: table, where: eq(table.orgId, ctx.securityContext.orgId) }`
          )
        }
      } catch {
        // If calling sql() throws, skip validation for this cube
        // The actual execution will catch the error with better context
      }
    }
  }
 
  /**
   * Build unified query that works for both single and multi-cube queries
   */
  private buildUnifiedQuery(
    queryPlan: any,
    query: SemanticQuery,
    context: QueryContext
  ) {
    // Pre-build filter SQL for propagating filters to enable parameter deduplication
    // This ensures the same filter values are shared between CTE subqueries and main query
    const preBuiltFilterMap = new Map<string, SQL[]>()
 
    if (queryPlan.preAggregationCTEs && queryPlan.preAggregationCTEs.length > 0) {
      for (const cteInfo of queryPlan.preAggregationCTEs) {
        if (cteInfo.propagatingFilters && cteInfo.propagatingFilters.length > 0) {
          for (const propFilter of cteInfo.propagatingFilters) {
            const sourceCubeName = propFilter.sourceCube.name
 
            // Build filter SQL once if not already built for this cube
            if (!preBuiltFilterMap.has(sourceCubeName)) {
              const syntheticQuery: SemanticQuery = {
                filters: propFilter.filters
              }
              const cubeMap = new Map([[sourceCubeName, propFilter.sourceCube]])
              const filterSQL = this.queryBuilder.buildWhereConditions(
                cubeMap,
                syntheticQuery,
                context
              )
              preBuiltFilterMap.set(sourceCubeName, filterSQL)
            }
 
            // Store the pre-built SQL in the propagating filter for reuse
            const preBuiltSQL = preBuiltFilterMap.get(sourceCubeName)
            if (preBuiltSQL && preBuiltSQL.length > 0) {
              propFilter.preBuiltFilterSQL = preBuiltSQL.length === 1
                ? preBuiltSQL[0]
                : and(...preBuiltSQL) as SQL
            }
          }
        }
      }
    }
 
    // Build pre-aggregation CTEs if needed
    const ctes: any[] = []
    const cteAliasMap = new Map<string, string>()
    // Map downstream cubes to their CTE info (for cubes that join THROUGH a CTE)
    const downstreamCubeMap = new Map<string, { cteAlias: string; joinKeys: Array<{ sourceColumn: string; targetColumn: string; sourceColumnObj?: any; targetColumnObj?: any }> }>()
 
    if (queryPlan.preAggregationCTEs && queryPlan.preAggregationCTEs.length > 0) {
      for (const cteInfo of queryPlan.preAggregationCTEs) {
        const cte = this.cteBuilder.buildPreAggregationCTE(cteInfo, query, context, queryPlan, preBuiltFilterMap)
        if (cte) {
          ctes.push(cte)
          cteAliasMap.set(cteInfo.cube.name, cteInfo.cteAlias)
 
          // Build downstream cube map for cubes that should join through this CTE
          if (cteInfo.downstreamJoinKeys) {
            for (const downstream of cteInfo.downstreamJoinKeys) {
              downstreamCubeMap.set(downstream.targetCubeName, {
                cteAlias: cteInfo.cteAlias,
                joinKeys: downstream.joinKeys
              })
            }
          }
        } else E{
          // Failed to build CTE
        }
      }
    }
    
    // Get primary cube's base SQL definition
    const primaryCubeBase = queryPlan.primaryCube.sql(context)
    
    // Build selections using QueryBuilder - but modify for CTEs
    const selections = this.queryBuilder.buildSelections(
      queryPlan.joinCubes.length > 0 
        ? this.getCubesFromPlan(queryPlan) // Multi-cube
        : queryPlan.primaryCube, // Single cube
      query,
      context
    )
    
    // Replace selections from pre-aggregated cubes with CTE references
    const modifiedSelections = { ...selections }
    if (queryPlan.preAggregationCTEs) {
      for (const cteInfo of queryPlan.preAggregationCTEs) {
        const cubeName = cteInfo.cube.name
 
        // Handle measures from CTE cubes
        for (const measureName of cteInfo.measures) {
          if (modifiedSelections[measureName]) {
            const [, fieldName] = measureName.split('.')
            const cube = this.getCubesFromPlan(queryPlan).get(cubeName)
            Eif (cube && cube.measures && cube.measures[fieldName]) {
              const measure = cube.measures[fieldName]
              const cteColumn = sql`${sql.identifier(cteInfo.cteAlias)}.${sql.identifier(fieldName)}`
 
              // For aggregate CTEs, use appropriate Drizzle aggregate function based on measure type
              // Since CTE is already pre-aggregated, we need to aggregate the pre-aggregated values
              let aggregatedExpr: SQL
 
              if (measure.type === 'calculated' && measure.calculatedSql) {
                // Use QueryBuilder's helper to build calculated measure from CTE columns
                const allCubes = this.getCubesFromPlan(queryPlan)
                aggregatedExpr = this.queryBuilder.buildCTECalculatedMeasure(
                  measure,
                  cube,
                  cteInfo,
                  allCubes,
                  context
                )
              } else {
                // For non-calculated measures, aggregate the CTE column directly
                switch (measure.type) {
                  case 'count':
                  case 'countDistinct':
                  case 'sum':
                    aggregatedExpr = sum(cteColumn)
                    break
                  case 'avg':
                    // For average of averages, we should use a weighted average, but for now use simple avg
                    aggregatedExpr = this.databaseAdapter.buildAvg(cteColumn)
                    break
                  case 'min':
                    aggregatedExpr = min(cteColumn)
                    break
                  case 'max':
                    aggregatedExpr = max(cteColumn)
                    break
                  case 'number':
                    // For number type, use sum to combine values
                    aggregatedExpr = sum(cteColumn)
                    break
                  default:
                    aggregatedExpr = sum(cteColumn)
                }
              }
 
              modifiedSelections[measureName] = sql`${aggregatedExpr}`.as(measureName) as unknown as SQL
            }
          }
        }
        
        // Handle dimensions from CTE cubes (these need to reference join keys in CTE)
        for (const selectionName in modifiedSelections) {
          const [selectionCubeName, fieldName] = selectionName.split('.')
          if (selectionCubeName === cubeName) {
            // This is a dimension/time dimension from a CTE cube
            const cube = this.getCubesFromPlan(queryPlan).get(cubeName)
            
            // Check if this is a dimension or time dimension from this cube
            const isDimension = cube && cube.dimensions?.[fieldName]
            const isTimeDimension = selectionName.startsWith(cubeName + '.')
            
            Eif (isDimension || isTimeDimension) {
              // Check if this is one of the join keys that's already in the CTE
              // First try exact name match
              let matchingJoinKey = cteInfo.joinKeys.find((jk: JoinKeyInfo) => jk.targetColumn === fieldName)
              
              // If no exact match, check if the dimension SQL matches any join key target column
              if (!matchingJoinKey && cube?.dimensions?.[fieldName]) {
                const dimensionSql = cube.dimensions[fieldName].sql
                matchingJoinKey = cteInfo.joinKeys.find((jk: any) => {
                  // Check if the dimension's SQL column matches the join key's target column object
                  return jk.targetColumnObj === dimensionSql
                })
              }
              
              if (matchingJoinKey) {
                // Reference the join key from the CTE using the dimension name
                modifiedSelections[selectionName] = sql`${sql.identifier(cteInfo.cteAlias)}.${sql.identifier(fieldName)}`.as(selectionName) as unknown as SQL
              } else if (isTimeDimension && cube?.dimensions?.[fieldName]) {
                // This is a time dimension that should be available in the CTE
                modifiedSelections[selectionName] = sql`${sql.identifier(cteInfo.cteAlias)}.${sql.identifier(fieldName)}`.as(selectionName) as unknown as SQL
              }
              // For non-join-key dimensions from CTE cubes that aren't handled above,
              // the original selection will be kept (which may cause SQL errors if not properly handled)
            }
          }
        }
      }
    }
 
    // Handle post-aggregation window functions
    // These window functions reference a base measure and operate on aggregated data
    if (query.measures) {
      const allCubes = this.getCubesFromPlan(queryPlan)
 
      for (const measureName of query.measures) {
        const [cubeName, fieldName] = measureName.split('.')
        const cube = allCubes.get(cubeName)
 
        Eif (cube?.measures?.[fieldName]) {
          const measure = cube.measures[fieldName]
 
          // Check if this is a post-aggregation window function
          if (MeasureBuilder.isPostAggregationWindow(measure)) {
            const baseMeasureName = MeasureBuilder.getWindowBaseMeasure(measure, cubeName)
 
            Eif (baseMeasureName) {
              // Build the base measure expression fresh (without alias)
              // We can't use modifiedSelections because those are aliased and SQL doesn't
              // allow referencing SELECT aliases in the same SELECT clause
              const [baseCubeName, baseFieldName] = baseMeasureName.split('.')
              const baseCube = allCubes.get(baseCubeName)
 
              Eif (baseCube?.measures?.[baseFieldName]) {
                const baseMeasure = baseCube.measures[baseFieldName]
 
                // Check if the base measure is from a CTE cube (hasMany relationship)
                // If so, we should reference the CTE column with re-aggregation
                // because the main query has its own GROUP BY
                const cteInfo = queryPlan.preAggregationCTEs?.find(
                  (cte: any) => cte.cube?.name === baseCubeName && cte.measures?.includes(baseMeasureName)
                )
 
                let baseMeasureExpr: SQL
                if (cteInfo) {
                  // Base measure is from a CTE - reference the CTE column
                  // The CTE already contains the aggregated value (e.g., totalLinesOfCode)
                  // But the main query may have additional GROUP BY, so we need to re-aggregate
                  const cteColumn = sql`${sql.identifier(cteInfo.cteAlias)}.${sql.identifier(baseFieldName)}`
                  // Apply sum() to the CTE column to re-aggregate for the main query's GROUP BY
                  baseMeasureExpr = sql`sum(${cteColumn})`
                } else {
                  // Not from a CTE - build the raw aggregation expression (e.g., SUM(column))
                  baseMeasureExpr = this.queryBuilder.buildMeasureExpression(baseMeasure, context, baseCube)
                }
 
                // Ensure the base measure is also in the selections (for display)
                if (!modifiedSelections[baseMeasureName]) {
                  modifiedSelections[baseMeasureName] = sql`${baseMeasureExpr}`.as(baseMeasureName) as unknown as SQL
                }
 
                // Build the window function expression
                const windowExpr = this.buildPostAggregationWindowExpression(
                  measure,
                  baseMeasureExpr,
                  query,
                  context,
                  cube,
                  queryPlan
                )
 
                Eif (windowExpr) {
                  modifiedSelections[measureName] = sql`${windowExpr}`.as(measureName) as unknown as SQL
                }
              }
            }
          }
        }
      }
    }
 
    // Collect all WHERE conditions (declared early for junction table security)
    const allWhereConditions: SQL[] = []
 
    // Start building the query from the primary cube
    let drizzleQuery = context.db
      .select(modifiedSelections)
      .from(primaryCubeBase.from)
 
    // Add CTEs to the query - Drizzle CTEs are added at the start
    if (ctes.length > 0) {
      drizzleQuery = context.db
        .with(...ctes)
        .select(modifiedSelections)
        .from(primaryCubeBase.from)
    }
 
    // Add joins from primary cube base (intra-cube joins)
    Iif (primaryCubeBase.joins) {
      for (const join of primaryCubeBase.joins) {
        switch (join.type || 'left') {
          case 'left':
            drizzleQuery = drizzleQuery.leftJoin(join.table, join.on)
            break
          case 'inner':
            drizzleQuery = drizzleQuery.innerJoin(join.table, join.on)
            break
          case 'right':
            drizzleQuery = drizzleQuery.rightJoin(join.table, join.on)
            break
          case 'full':
            drizzleQuery = drizzleQuery.fullJoin(join.table, join.on)
            break
        }
      }
    }
 
    // Track which cubes have their security handled in JOIN ON clause
    // This prevents duplicate security conditions in WHERE clause
    const cubesWithSecurityInJoin = new Set<string>()
 
    // Add multi-cube joins (inter-cube joins)
    if (queryPlan.joinCubes && queryPlan.joinCubes.length > 0) {
      for (const joinCube of queryPlan.joinCubes) {
        // Check if this cube has been pre-aggregated into a CTE
        const cteAlias = cteAliasMap.get(joinCube.cube.name)
 
        // Handle belongsToMany junction table first if present
        if (joinCube.junctionTable) {
          const junctionTable = joinCube.junctionTable
 
          // Collect all WHERE conditions for junction table including security context
          const junctionWhereConditions: SQL[] = []
          Eif (junctionTable.securitySql) {
            const junctionSecurity = junctionTable.securitySql(context.securityContext)
            Iif (Array.isArray(junctionSecurity)) {
              junctionWhereConditions.push(...junctionSecurity)
            } else {
              junctionWhereConditions.push(junctionSecurity)
            }
          }
 
          // Add junction table join (source -> junction)
          // NOTE: For junction tables (belongsToMany), security filters STAY in WHERE clause
          // because the semantics of many-to-many relationships require filtering out
          // non-matching records rather than returning them as NULLs.
          // The security-in-JOIN-ON logic only applies to regular LEFT JOINs (hasMany/hasOne).
          try {
            switch (junctionTable.joinType || 'left') {
              case 'left':
                drizzleQuery = drizzleQuery.leftJoin(junctionTable.table, junctionTable.joinCondition)
                break
              case 'inner':
                drizzleQuery = drizzleQuery.innerJoin(junctionTable.table, junctionTable.joinCondition)
                break
              case 'right':
                drizzleQuery = drizzleQuery.rightJoin(junctionTable.table, junctionTable.joinCondition)
                break
              case 'full':
                drizzleQuery = drizzleQuery.fullJoin(junctionTable.table, junctionTable.joinCondition)
                break
            }
 
            // Junction table security goes in WHERE clause to properly filter records
            Eif (junctionWhereConditions.length > 0) {
              allWhereConditions.push(...junctionWhereConditions)
            }
          } catch {
            // Junction table join failed, continuing
          }
        }
 
        let joinTarget: any
        let joinCondition: any
        let securityCondition: SQL | undefined
 
        if (cteAlias) {
          // Join to CTE instead of base table - use sql table reference
          joinTarget = sql`${sql.identifier(cteAlias)}`
          // Build CTE join condition using the CTE alias
          joinCondition = this.cteBuilder.buildCTEJoinCondition(joinCube, cteAlias, queryPlan)
          // CTE already has security applied inside it, don't apply again
          securityCondition = undefined
        } else {
          // Check if this cube should join through a CTE (downstream cube)
          // Example: Teams joins through EmployeeTeams CTE when EmployeeTeams has measures
          const downstreamInfo = downstreamCubeMap.get(joinCube.cube.name)
 
          // Regular join to base table
          // Get the cube's SQL definition ONCE to avoid SQL object mutation issues
          const joinCubeBase = joinCube.cube.sql(context)
          joinTarget = joinCubeBase.from
 
          // Get security condition for this cube (for LEFT JOINs, will be added to ON clause)
          securityCondition = joinCubeBase.where
 
          Iif (downstreamInfo) {
            // This cube joins THROUGH a CTE - build join condition referencing CTE alias
            // e.g., Teams.id = employeeteams_agg.team_id
            const conditions: SQL[] = []
            for (const joinKey of downstreamInfo.joinKeys) {
              // Source column is in the CTE (e.g., team_id in employeeteams_agg)
              const cteCol = sql`${sql.identifier(downstreamInfo.cteAlias)}.${sql.identifier(joinKey.sourceColumn)}`
              // Target column is in the downstream cube's table (e.g., id in teams)
              const targetCol = joinKey.targetColumnObj || sql.identifier(joinKey.targetColumn)
              conditions.push(eq(cteCol as any, targetCol as any))
            }
            joinCondition = conditions.length === 1 ? conditions[0] : and(...conditions)
          } else {
            // Standard join using original join condition
            joinCondition = joinCube.joinCondition
          }
        }
 
        const cubeJoinType = joinCube.joinType || 'left'
        // For LEFT/RIGHT/FULL JOINs, include security in ON clause
        // For INNER JOINs, security can go in WHERE (no difference in behavior)
        const effectiveJoinCondition =
          cubeJoinType !== 'inner' && securityCondition
            ? and(joinCondition, securityCondition)
            : joinCondition
 
        try {
          switch (cubeJoinType) {
            case 'left':
              drizzleQuery = drizzleQuery.leftJoin(joinTarget, effectiveJoinCondition)
              // Track that this cube's security is handled in JOIN ON
              if (securityCondition) {
                cubesWithSecurityInJoin.add(joinCube.cube.name)
              }
              break
            case 'inner':
              drizzleQuery = drizzleQuery.innerJoin(joinTarget, joinCondition)
              // Security can go in WHERE for INNER JOINs (no difference)
              break
            case 'right':
              drizzleQuery = drizzleQuery.rightJoin(joinTarget, effectiveJoinCondition)
              if (securityCondition) {
                cubesWithSecurityInJoin.add(joinCube.cube.name)
              }
              break
            case 'full':
              drizzleQuery = drizzleQuery.fullJoin(joinTarget, effectiveJoinCondition)
              if (securityCondition) {
                cubesWithSecurityInJoin.add(joinCube.cube.name)
              }
              break
          }
        } catch {
          // If join fails (e.g., duplicate alias), log and continue
          // Multi-cube join failed, continuing
        }
      }
    }
 
    // Add base WHERE conditions from primary cube
    Eif (primaryCubeBase.where) {
      allWhereConditions.push(primaryCubeBase.where)
    }
 
    // Add WHERE conditions from all joined cubes (including their security context filters)
    if (queryPlan.joinCubes && queryPlan.joinCubes.length > 0) {
      for (const joinCube of queryPlan.joinCubes) {
        // Skip if this cube is handled by a CTE (WHERE conditions are applied within the CTE)
        const cteAlias = cteAliasMap.get(joinCube.cube.name)
        if (cteAlias) {
          continue
        }
 
        // Skip cubes whose security is already in JOIN ON clause (for LEFT/RIGHT/FULL JOINs)
        // This prevents duplicate security conditions and preserves NULL rows in LEFT JOINs
        if (cubesWithSecurityInJoin.has(joinCube.cube.name)) {
          continue
        }
 
        // Get the base query definition for this joined cube to access its WHERE conditions
        const joinCubeBase = joinCube.cube.sql(context)
        Eif (joinCubeBase.where) {
          allWhereConditions.push(joinCubeBase.where)
        }
      }
    }
 
    // Add query-specific WHERE conditions using QueryBuilder
    // Pass preBuiltFilterMap to reuse filter SQL and deduplicate parameters
    const queryWhereConditions = this.queryBuilder.buildWhereConditions(
      queryPlan.joinCubes.length > 0
        ? this.getCubesFromPlan(queryPlan) // Multi-cube
        : queryPlan.primaryCube, // Single cube
      query,
      context,
      queryPlan, // Pass the queryPlan to handle CTE scenarios
      preBuiltFilterMap // Reuse pre-built filters for parameter deduplication
    )
    if (queryWhereConditions.length > 0) {
      allWhereConditions.push(...queryWhereConditions)
    }
 
    // Apply combined WHERE conditions
    Eif (allWhereConditions.length > 0) {
      const combinedWhere = allWhereConditions.length === 1 
        ? allWhereConditions[0] 
        : and(...allWhereConditions) as SQL
      drizzleQuery = drizzleQuery.where(combinedWhere)
    }
 
    // Add GROUP BY using QueryBuilder
    const groupByFields = this.queryBuilder.buildGroupByFields(
      queryPlan.joinCubes.length > 0 
        ? this.getCubesFromPlan(queryPlan) // Multi-cube
        : queryPlan.primaryCube, // Single cube
      query,
      context,
      queryPlan // Pass the queryPlan to handle CTE scenarios
    )
    if (groupByFields.length > 0) {
      drizzleQuery = drizzleQuery.groupBy(...groupByFields)
    }
 
    // Add HAVING conditions using QueryBuilder (after GROUP BY)
    const havingConditions = this.queryBuilder.buildHavingConditions(
      queryPlan.joinCubes.length > 0 
        ? this.getCubesFromPlan(queryPlan) // Multi-cube
        : queryPlan.primaryCube, // Single cube
      query,
      context,
      queryPlan // Pass the queryPlan to handle CTE scenarios
    )
    if (havingConditions.length > 0) {
      const combinedHaving = havingConditions.length === 1 
        ? havingConditions[0] 
        : and(...havingConditions) as SQL
      drizzleQuery = drizzleQuery.having(combinedHaving)
    }
 
    // Add ORDER BY using QueryBuilder
    const orderByFields = this.queryBuilder.buildOrderBy(query)
    if (orderByFields.length > 0) {
      drizzleQuery = drizzleQuery.orderBy(...orderByFields)
    }
 
    // Add LIMIT and OFFSET using QueryBuilder
    drizzleQuery = this.queryBuilder.applyLimitAndOffset(drizzleQuery, query)
 
    return drizzleQuery
  }
 
  /**
   * Convert query plan to cube map for QueryBuilder methods
   */
  private getCubesFromPlan(queryPlan: any): Map<string, Cube> {
    const cubes = new Map<string, Cube>()
    cubes.set(queryPlan.primaryCube.name, queryPlan.primaryCube)
    
    Eif (queryPlan.joinCubes) {
      for (const joinCube of queryPlan.joinCubes) {
        cubes.set(joinCube.cube.name, joinCube.cube)
      }
    }
    
    return cubes
  }
 
 
 
 
 
  /**
   * Generate raw SQL for debugging (without execution) - unified approach
   */
  async generateSQL(
    cube: Cube, 
    query: SemanticQuery, 
    securityContext: SecurityContext
  ): Promise<{ sql: string; params?: any[] }> {
    const cubes = new Map<string, Cube>()
    cubes.set(cube.name, cube)
    return this.generateUnifiedSQL(cubes, query, securityContext)
  }
 
  /**
   * Generate raw SQL for multi-cube queries without execution - unified approach
   */
  async generateMultiCubeSQL(
    cubes: Map<string, Cube>,
    query: SemanticQuery, 
    securityContext: SecurityContext
  ): Promise<{ sql: string; params?: any[] }> {
    return this.generateUnifiedSQL(cubes, query, securityContext)
  }
 
  /**
   * Generate SQL for a funnel query without execution (dry-run)
   * Returns the actual CTE-based SQL that would be executed
   */
  async dryRunFunnel(
    cubes: Map<string, Cube>,
    query: SemanticQuery,
    securityContext: SecurityContext
  ): Promise<{ sql: string; params?: any[] }> {
    // Validate funnel query
    if (!this.funnelQueryBuilder.hasFunnel(query)) {
      throw new Error('Query does not contain a valid funnel configuration')
    }
 
    const config = query.funnel!
 
    // Validate funnel configuration
    const validation = this.funnelQueryBuilder.validateConfig(config, cubes)
    if (!validation.isValid) {
      throw new Error(`Funnel validation failed: ${validation.errors.join(', ')}`)
    }
 
    // Create query context
    const context: QueryContext = {
      db: this.dbExecutor.db,
      schema: this.dbExecutor.schema,
      securityContext
    }
 
    // Build funnel query using Drizzle query builder
    // The refactored buildFunnelQuery returns a query builder with .toSQL() support
    const funnelQuery = this.funnelQueryBuilder.buildFunnelQuery(config, cubes, context)
 
    // Use .toSQL() to get the SQL string and parameters
    // This now works because buildFunnelQuery returns a Drizzle query builder
    const sqlObj = funnelQuery.toSQL()
 
    return {
      sql: sqlObj.sql,
      params: sqlObj.params
    }
  }
 
  /**
   * Generate SQL for a flow query without execution (dry-run)
   * Returns the actual CTE-based SQL that would be executed
   */
  async dryRunFlow(
    cubes: Map<string, Cube>,
    query: SemanticQuery,
    securityContext: SecurityContext
  ): Promise<{ sql: string; params?: any[] }> {
    // Validate flow query
    if (!this.flowQueryBuilder.hasFlow(query)) {
      throw new Error('Query does not contain a valid flow configuration')
    }
 
    const config = query.flow!
 
    // Validate flow configuration
    const validation = this.flowQueryBuilder.validateConfig(config, cubes)
    if (!validation.isValid) {
      throw new Error(`Flow validation failed: ${validation.errors.join(', ')}`)
    }
 
    // Create query context
    const context: QueryContext = {
      db: this.dbExecutor.db,
      schema: this.dbExecutor.schema,
      securityContext
    }
 
    // Build flow query using Drizzle query builder
    const flowQuery = this.flowQueryBuilder.buildFlowQuery(config, cubes, context)
 
    // Use .toSQL() to get the SQL string and parameters
    const sqlObj = flowQuery.toSQL()
 
    return {
      sql: sqlObj.sql,
      params: sqlObj.params
    }
  }
 
  /**
   * Generate SQL for a retention query without execution (dry-run)
   * Returns the actual CTE-based SQL that would be executed
   */
  async dryRunRetention(
    cubes: Map<string, Cube>,
    query: SemanticQuery,
    securityContext: SecurityContext
  ): Promise<{ sql: string; params?: any[] }> {
    // Validate retention query
    if (!this.retentionQueryBuilder.hasRetention(query)) {
      throw new Error('Query does not contain a valid retention configuration')
    }
 
    const config = query.retention!
 
    // Validate retention configuration
    const validation = this.retentionQueryBuilder.validateConfig(config, cubes)
    if (!validation.isValid) {
      throw new Error(`Retention validation failed: ${validation.errors.join(', ')}`)
    }
 
    // Create query context
    const context: QueryContext = {
      db: this.dbExecutor.db,
      schema: this.dbExecutor.schema,
      securityContext
    }
 
    // Build retention query using Drizzle query builder
    const retentionQuery = this.retentionQueryBuilder.buildRetentionQuery(config, cubes, context)
 
    // Use .toSQL() to get the SQL string and parameters
    const sqlObj = retentionQuery.toSQL()
 
    return {
      sql: sqlObj.sql,
      params: sqlObj.params
    }
  }
 
  /**
   * Execute EXPLAIN on a query to get the execution plan
   * Generates the SQL using the same secure path as execute/generateSQL,
   * then runs EXPLAIN on the database.
   */
  async explainQuery(
    cubes: Map<string, Cube>,
    query: SemanticQuery,
    securityContext: SecurityContext,
    options?: ExplainOptions
  ): Promise<ExplainResult> {
    // Generate the SQL using the appropriate method
    let sqlResult: { sql: string; params?: any[] }
 
    if (this.funnelQueryBuilder.hasFunnel(query)) {
      sqlResult = await this.dryRunFunnel(cubes, query, securityContext)
    } else if (this.flowQueryBuilder.hasFlow(query)) {
      sqlResult = await this.dryRunFlow(cubes, query, securityContext)
    } else if (this.retentionQueryBuilder.hasRetention(query)) {
      sqlResult = await this.dryRunRetention(cubes, query, securityContext)
    } else {
      sqlResult = await this.generateUnifiedSQL(cubes, query, securityContext)
    }
 
    // Execute EXPLAIN using the database executor
    return this.dbExecutor.explainQuery(
      sqlResult.sql,
      sqlResult.params || [],
      options
    )
  }
 
  /**
   * Generate SQL using unified approach (works for both single and multi-cube)
   */
  private async generateUnifiedSQL(
    cubes: Map<string, Cube>,
    query: SemanticQuery, 
    securityContext: SecurityContext
  ): Promise<{ sql: string; params?: any[] }> {
    const context: QueryContext = {
      db: this.dbExecutor.db,
      schema: this.dbExecutor.schema!,
      securityContext
    }
 
    // Create unified query plan
    const queryPlan = this.queryPlanner.createQueryPlan(cubes, query, context)
    
    // Build the query using unified approach
    const builtQuery = this.buildUnifiedQuery(queryPlan, query, context)
    
    // Extract SQL from the built query
    const sqlObj = builtQuery.toSQL()
    
    return {
      sql: sqlObj.sql,
      params: sqlObj.params
    }
  }
 
  /**
   * Generate annotations for UI metadata - unified approach
   */
  private generateAnnotations(
    queryPlan: any,
    query: SemanticQuery
  ) {
    const measures: Record<string, MeasureAnnotation> = {}
    const dimensions: Record<string, DimensionAnnotation> = {}
    const timeDimensions: Record<string, TimeDimensionAnnotation> = {}
    
    // Get all cubes involved (primary + join cubes)
    const allCubes = [queryPlan.primaryCube].filter(Boolean)
    if (queryPlan.joinCubes && queryPlan.joinCubes.length > 0) {
      allCubes.push(...queryPlan.joinCubes.map((jc: any) => jc.cube).filter(Boolean))
    }
 
    // Generate measure annotations from all cubes
    if (query.measures) {
      for (const measureName of query.measures) {
        const [cubeName, fieldName] = measureName.split('.')
        const cube = allCubes.find(c => c?.name === cubeName)
        Eif (cube && cube.measures[fieldName]) {
          const measure = cube.measures[fieldName]
          measures[measureName] = {
            title: measure.title || fieldName,
            shortTitle: measure.title || fieldName,
            type: measure.type
          }
        }
      }
    }
    
    // Generate dimension annotations from all cubes
    if (query.dimensions) {
      for (const dimensionName of query.dimensions) {
        const [cubeName, fieldName] = dimensionName.split('.')
        const cube = allCubes.find(c => c?.name === cubeName)
        Eif (cube && cube.dimensions?.[fieldName]) {
          const dimension = cube.dimensions[fieldName]
          dimensions[dimensionName] = {
            title: dimension.title || fieldName,
            shortTitle: dimension.title || fieldName,
            type: dimension.type
          }
        }
      }
    }
 
    // Generate time dimension annotations from all cubes
    if (query.timeDimensions) {
      for (const timeDim of query.timeDimensions) {
        const [cubeName, fieldName] = timeDim.dimension.split('.')
        const cube = allCubes.find(c => c?.name === cubeName)
        Eif (cube && cube.dimensions?.[fieldName]) {
          const dimension = cube.dimensions[fieldName]
          timeDimensions[timeDim.dimension] = {
            title: dimension.title || fieldName,
            shortTitle: dimension.title || fieldName,
            type: dimension.type,
            granularity: timeDim.granularity
          }
        }
      }
    }
    
    return {
      measures,
      dimensions,
      segments: {},
      timeDimensions
    }
  }
 
  /**
   * Pre-build filter SQL and store in cache for reuse across CTEs and main query
   * This enables parameter deduplication - the same filter values are shared
   * rather than appearing as separate parameters in different parts of the query
   */
  private preloadFilterCache(
    query: SemanticQuery,
    filterCache: FilterCacheManager,
    cubes: Map<string, Cube>,
    context: QueryContext
  ): void {
    // Pre-build regular filters
    if (query.filters && query.filters.length > 0) {
      // Flatten nested AND/OR filters to get individual conditions
      const flatFilters = flattenFilters(query.filters)
 
      for (const filter of flatFilters) {
        const key = getFilterKey(filter)
 
        // Skip if already cached (from a previous filter in the same query)
        if (filterCache.has(key)) continue
 
        // Find the cube for this filter's member
        const [cubeName, fieldName] = filter.member.split('.')
        const cube = cubes.get(cubeName)
        Iif (!cube) continue
 
        const dimension = cube.dimensions?.[fieldName]
        if (!dimension) continue
 
        // 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(filter.operator)
        if (isArrayOperator) {
          // Skip caching array operator filters - they require special column handling
          // and will be built fresh each time to ensure proper array encoding
          continue
        }
 
        // Build the filter SQL using the query builder
        const fieldExpr = resolveSqlExpression(dimension.sql, context)
        const filterSQL = this.queryBuilder.buildFilterConditionPublic(
          fieldExpr,
          filter.operator,
          filter.values,
          dimension,
          filter.dateRange
        )
 
        if (filterSQL) {
          filterCache.set(key, filterSQL)
        }
      }
 
      // NOTE: We do NOT cache logical filters (AND/OR) because they can contain
      // mixed cube references. When some cubes are in CTEs, the cached version
      // would reference wrong table contexts. Individual simple filters within
      // logical filters are still cached for deduplication.
    }
 
    // Pre-build time dimension date range filters
    if (query.timeDimensions) {
      for (const timeDim of query.timeDimensions) {
        if (timeDim.dateRange) {
          const key = getTimeDimensionFilterKey(timeDim.dimension, timeDim.dateRange)
 
          // Skip if already cached
          Iif (filterCache.has(key)) continue
 
          const [cubeName, fieldName] = timeDim.dimension.split('.')
          const cube = cubes.get(cubeName)
          Iif (!cube) continue
 
          const dimension = cube.dimensions?.[fieldName]
          Iif (!dimension) continue
 
          const fieldExpr = resolveSqlExpression(dimension.sql, context)
          const dateCondition = this.queryBuilder.buildDateRangeCondition(fieldExpr, timeDim.dateRange)
 
          if (dateCondition) {
            filterCache.set(key, dateCondition)
          }
        }
      }
    }
  }
 
  /**
   * Build post-aggregation window function expression
   *
   * Post-aggregation windows operate on already-aggregated data:
   * 1. The base measure is aggregated (e.g., SUM(revenue))
   * 2. The window function is applied (e.g., LAG(...) OVER ORDER BY date)
   * 3. An optional operation is applied (e.g., current - previous)
   *
   * @param measure - The window function measure definition
   * @param baseMeasureExpr - The aggregated base measure expression
   * @param query - The semantic query (for dimension context)
   * @param context - Query context
   * @param cube - The cube containing this measure
   * @returns SQL expression for the window function
   */
  private buildPostAggregationWindowExpression(
    measure: any,
    baseMeasureExpr: any,
    query: SemanticQuery,
    context: QueryContext,
    cube: Cube,
    queryPlan?: any
  ): SQL | null {
    const windowConfig = measure.windowConfig || {}
 
    // Helper to check if a dimension's cube is in a CTE
    // If so, return the CTE's pre-computed column reference instead of re-computing
    const getCTEDimensionExpr = (dimCubeName: string, fieldName: string): SQL | null => {
      if (!queryPlan?.preAggregationCTEs) return null
      const cteInfo = queryPlan.preAggregationCTEs.find((cte: any) => cte.cube?.name === dimCubeName)
      Eif (cteInfo && cteInfo.cteAlias) {
        // Check if this dimension is in the CTE's selections (time dimensions are included)
        // We reference the CTE's pre-computed column directly
        return sql`${sql.identifier(cteInfo.cteAlias)}.${sql.identifier(fieldName)}`
      }
      return null
    }
 
    // Build ORDER BY expression for the window function
    // Use time dimensions or specified orderBy fields
    type OrderByExpr = { field: any; direction: 'asc' | 'desc' }
    let orderByExprs: OrderByExpr[] | undefined
 
    if (windowConfig.orderBy && windowConfig.orderBy.length > 0) {
      orderByExprs = windowConfig.orderBy
        .map((orderSpec: { field: string; direction: 'asc' | 'desc' }): OrderByExpr | null => {
          const fieldName = orderSpec.field.includes('.') ? orderSpec.field.split('.')[1] : orderSpec.field
 
          // First check if it's a time dimension in the query (with granularity)
          // This takes priority because time dimensions need the granularity-applied expression
          if (query.timeDimensions) {
            for (const timeDim of query.timeDimensions) {
              const [timeDimCubeName, timeDimField] = timeDim.dimension.split('.')
              if (timeDimField === fieldName) {
                // Check if this dimension's cube is in a CTE
                // If so, use the CTE's pre-computed date column
                const cteExpr = getCTEDimensionExpr(timeDimCubeName, fieldName)
                if (cteExpr) {
                  return {
                    field: cteExpr,
                    direction: orderSpec.direction
                  }
                }
 
                // Not from CTE - build the time dimension expression with granularity
                const timeDimension = cube.dimensions?.[timeDimField]
                if (timeDimension) {
                  return {
                    field: this.queryBuilder.buildTimeDimensionExpression(
                      timeDimension.sql,
                      timeDim.granularity,
                      context
                    ),
                    direction: orderSpec.direction
                  }
                }
              }
            }
          }
 
          // Fall back to regular dimensions if not a time dimension
          const dimension = cube.dimensions?.[fieldName]
          Iif (dimension) {
            return {
              field: resolveSqlExpression(dimension.sql, context),
              direction: orderSpec.direction
            }
          }
 
          // Check if the ORDER BY field references the base measure itself
          // This is common for RANK/DENSE_RANK where we order by the aggregated value
          const baseMeasureFieldName = windowConfig.measure?.includes('.')
            ? windowConfig.measure.split('.')[1]
            : windowConfig.measure
 
          if (fieldName === baseMeasureFieldName || orderSpec.field === windowConfig.measure) {
            // Use the base measure expression for ordering
            return {
              field: baseMeasureExpr,
              direction: orderSpec.direction
            }
          }
 
          return null
        })
        .filter((expr: OrderByExpr | null): expr is OrderByExpr => expr !== null)
    E} else if (query.timeDimensions && query.timeDimensions.length > 0) {
      // Default to first time dimension for ordering
      const timeDim = query.timeDimensions[0]
      const [timeCubeName, timeDimField] = timeDim.dimension.split('.')
 
      // Check if the time dimension's cube is in a CTE
      const cteExpr = getCTEDimensionExpr(timeCubeName, timeDimField)
      if (cteExpr) {
        orderByExprs = [{
          field: cteExpr,
          direction: 'asc' as const
        }]
      } else {
        const timeCube = cube.name === timeCubeName ? cube : undefined
 
        if (timeCube?.dimensions?.[timeDimField]) {
          const timeDimension = timeCube.dimensions[timeDimField]
          orderByExprs = [{
            field: this.queryBuilder.buildTimeDimensionExpression(
              timeDimension.sql,
              timeDim.granularity,
              context
            ),
            direction: 'asc' as const
          }]
        }
      }
    }
 
    // Build PARTITION BY expression if specified
    let partitionByExprs: any[] | undefined
    Iif (windowConfig.partitionBy && windowConfig.partitionBy.length > 0) {
      partitionByExprs = windowConfig.partitionBy
        .map((dimRef: string) => {
          const dimName = dimRef.includes('.') ? dimRef.split('.')[1] : dimRef
          const dimension = cube.dimensions?.[dimName]
          if (dimension) {
            return resolveSqlExpression(dimension.sql, context)
          }
          return null
        })
        .filter((expr: any): expr is any => expr !== null)
    }
 
    // Build the base window function using the database adapter
    const windowResult = this.databaseAdapter.buildWindowFunction(
      measure.type,
      baseMeasureExpr,
      partitionByExprs,
      orderByExprs,
      {
        offset: windowConfig.offset,
        defaultValue: windowConfig.defaultValue,
        nTile: windowConfig.nTile,
        frame: windowConfig.frame
      }
    )
 
    Iif (!windowResult) {
      return null
    }
 
    // Apply the operation (difference, ratio, percentChange)
    const operation = windowConfig.operation || MeasureBuilder.getDefaultWindowOperation(measure.type)
 
    switch (operation) {
      case 'difference':
        // For LAG: current - previous (baseMeasure - LAG(baseMeasure))
        // For LEAD: current - next (baseMeasure - LEAD(baseMeasure))
        return sql`${baseMeasureExpr} - ${windowResult}`
 
      case 'ratio':
        // current / window (with NULL protection)
        return sql`${baseMeasureExpr} / NULLIF(${windowResult}, 0)`
 
      case 'percentChange':
        // ((current - window) / window) * 100
        return sql`((${baseMeasureExpr} - ${windowResult}) / NULLIF(${windowResult}, 0)) * 100`
 
      case 'raw':
      default:
        // Return the window function result directly
        return windowResult
    }
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
}