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 | 140x 140x 140x 1770x 42x 42x 42x 42x 42x 1x 1x 41x 41x 41x 41x 41x 41x 2x 41x 41x 41x 41x 41x 41x 2x 41x 41x 41x 41x 41x 41x 2x 41x 41x 1x 41x 41x 1x 41x 1x 41x 4x 41x 41x 41x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 17x 2x 15x 15x 15x 315x 315x 129x 186x 186x 114x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 18x 18x 16x 15x 22x 2x 2x 2x 2x 4x 4x 4x 2x 2x 2x 1x 1x 20x 20x 20x 20x 22x 20x 20x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 1x 15x 15x 15x 15x 15x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 15x 15x 15x 15x 15x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 15x 15x 15x 15x 20x 20x 20x 20x 15x 15x 23x 23x 23x 1x 22x 15x 15x 15x 15x 15x 15x 6x 6x 6x 6x 15x 14x 14x 15x 15x 1x 14x 15x 8x 8x 8x 8x 15x 15x 15x 15x 15x 15x 15x | /**
* Flow Query Builder
* Handles server-side bidirectional flow analysis with Sankey diagram output
* Generates SQL with CTEs for exploring paths BEFORE and AFTER a starting step
*
* Uses a multi-CTE strategy:
* 1. starting_entities - Find entities matching the starting step
* 2. before_step_N - For each depth, find the Nth event before starting point
* 3. after_step_N - For each depth, find the Nth event after starting point
* 4. nodes_aggregation - Count unique nodes per layer
* 5. links_aggregation - Count transitions between adjacent nodes
*
* Built using Drizzle's query builder pattern for type safety and consistency.
*/
import { sql, SQL, and } from 'drizzle-orm'
import type { DatabaseAdapter } from './adapters/base-adapter'
import type {
FlowQueryConfig,
FlowResultRow,
SankeyNode,
SankeyLink,
FlowValidationResult,
} from './types/flow'
import type {
Cube,
QueryContext,
SemanticQuery,
Filter,
FilterCondition,
LogicalFilter,
} from './types'
import { resolveSqlExpression } from './cube-utils'
import { FilterBuilder } from './builders/filter-builder'
import { DateTimeBuilder } from './builders/date-time-builder'
/**
* Type for CTE objects created by db.$with()
*/
type WithSubquery = ReturnType<ReturnType<any['$with']>['as']>
/**
* Resolved flow configuration with SQL expressions
*/
interface ResolvedFlowConfig {
cube: Cube
cubeBase: { from: any; where?: SQL }
bindingKeyExpr: SQL
timeExpr: SQL
eventExpr: SQL
startingStepFilters: SQL[]
}
export class FlowQueryBuilder {
private filterBuilder: FilterBuilder
private dateTimeBuilder: DateTimeBuilder
private databaseAdapter: DatabaseAdapter
constructor(databaseAdapter: DatabaseAdapter) {
this.databaseAdapter = databaseAdapter
this.dateTimeBuilder = new DateTimeBuilder(databaseAdapter)
this.filterBuilder = new FilterBuilder(databaseAdapter, this.dateTimeBuilder)
}
/**
* Check if query contains flow configuration
*/
hasFlow(query: SemanticQuery): boolean {
return (
query.flow !== undefined &&
query.flow.startingStep !== undefined &&
query.flow.eventDimension !== undefined
)
}
/**
* Validate flow configuration
*/
validateConfig(
config: FlowQueryConfig,
cubes: Map<string, Cube>
): FlowValidationResult {
const errors: string[] = []
const warnings: string[] = []
const engine = this.databaseAdapter.getEngineType()
const supportsLateral = this.databaseAdapter.supportsLateralJoins()
if (engine === 'sqlite') {
errors.push(
'Flow queries are not supported on SQLite. Use PostgreSQL or MySQL for flow analysis.'
)
return { isValid: false, errors, warnings }
}
// Validate binding key
if (typeof config.bindingKey === 'string') {
const [cubeName, dimName] = config.bindingKey.split('.')
Iif (!cubeName || !dimName) {
errors.push(
`Invalid binding key format: ${config.bindingKey}. Expected 'CubeName.dimensionName'`
)
} else {
const cube = cubes.get(cubeName)
Iif (!cube) {
errors.push(`Binding key cube not found: ${cubeName}`)
} else if (!cube.dimensions?.[dimName]) {
errors.push(
`Binding key dimension not found: ${dimName} in cube ${cubeName}`
)
}
}
E} else if (Array.isArray(config.bindingKey)) {
for (const mapping of config.bindingKey) {
const cube = cubes.get(mapping.cube)
if (!cube) {
errors.push(`Binding key mapping cube not found: ${mapping.cube}`)
} else {
const [, dimName] = mapping.dimension.split('.')
if (!cube.dimensions?.[dimName]) {
errors.push(
`Binding key dimension not found: ${dimName} in cube ${mapping.cube}`
)
}
}
}
}
// Validate time dimension
Eif (typeof config.timeDimension === 'string') {
const [cubeName, dimName] = config.timeDimension.split('.')
Iif (!cubeName || !dimName) {
errors.push(
`Invalid time dimension format: ${config.timeDimension}. Expected 'CubeName.dimensionName'`
)
} else {
const cube = cubes.get(cubeName)
Iif (!cube) {
errors.push(`Time dimension cube not found: ${cubeName}`)
} else if (!cube.dimensions?.[dimName]) {
errors.push(`Time dimension not found: ${dimName} in cube ${cubeName}`)
}
}
}
// Validate event dimension
if (config.eventDimension) {
const [cubeName, dimName] = config.eventDimension.split('.')
Iif (!cubeName || !dimName) {
errors.push(
`Invalid event dimension format: ${config.eventDimension}. Expected 'CubeName.dimensionName'`
)
} else {
const cube = cubes.get(cubeName)
Iif (!cube) {
errors.push(`Event dimension cube not found: ${cubeName}`)
} else if (!cube.dimensions?.[dimName]) {
errors.push(
`Event dimension not found: ${dimName} in cube ${cubeName}`
)
}
}
} else E{
errors.push('Event dimension is required for flow analysis')
}
// Validate starting step
Iif (!config.startingStep) {
errors.push('Starting step is required for flow analysis')
} else {
if (!config.startingStep.filter) {
errors.push('Starting step must have at least one filter')
}
Iif (!config.startingStep.name) {
warnings.push('Starting step has no name - using default')
}
}
// Validate depth bounds
if (config.stepsBefore < 0 || config.stepsBefore > 5) {
errors.push(`stepsBefore must be between 0 and 5, got: ${config.stepsBefore}`)
}
if (config.stepsAfter < 0 || config.stepsAfter > 5) {
errors.push(`stepsAfter must be between 0 and 5, got: ${config.stepsAfter}`)
}
// Performance warnings for high depth
if (config.stepsBefore >= 4 || config.stepsAfter >= 4) {
warnings.push(
'High step depth (4-5) may impact query performance on large datasets'
)
}
// Validate join strategy
Iif (
config.joinStrategy &&
!['auto', 'lateral', 'window'].includes(config.joinStrategy)
) {
errors.push(`Invalid joinStrategy: ${config.joinStrategy}`)
I} else if (config.joinStrategy === 'lateral' && !supportsLateral) {
errors.push('Lateral joins are not supported on this database')
}
return {
isValid: errors.length === 0,
errors,
warnings,
}
}
/**
* Build complete flow query using Drizzle's query builder pattern
*
* Creates a series of CTEs to:
* 1. Find entities at the starting step
* 2. Walk backwards N steps to find preceding events
* 3. Walk forwards N steps to find following events
* 4. Aggregate into nodes and links for Sankey visualization
*/
buildFlowQuery(
config: FlowQueryConfig,
cubes: Map<string, Cube>,
context: QueryContext
): ReturnType<typeof context.db.select> {
const engine = this.databaseAdapter.getEngineType()
Iif (engine === 'sqlite') {
throw new Error(
'Flow queries are not supported on SQLite. Use PostgreSQL or MySQL for flow analysis.'
)
}
const supportsLateral = this.databaseAdapter.supportsLateralJoins()
const joinStrategy = config.joinStrategy ?? 'auto'
const useLateral =
joinStrategy === 'lateral' || (joinStrategy === 'auto' && supportsLateral)
Iif (joinStrategy === 'lateral' && !supportsLateral) {
throw new Error('Lateral joins are not supported on this database')
}
// Normalize config for execution
const effectiveConfig: FlowQueryConfig = {
...config,
stepsBefore: config.outputMode === 'sunburst' ? 0 : config.stepsBefore,
}
// Resolve all expressions once
const resolved = this.resolveFlowConfig(effectiveConfig, cubes, context)
// Build all CTEs
const ctes: WithSubquery[] = []
// 1. Starting entities CTE - finds entities matching the starting step
const startingEntitiesCTE = this.buildStartingEntitiesCTE(effectiveConfig, resolved, context)
ctes.push(startingEntitiesCTE)
// 2. Before step CTEs - walk backwards from starting step
const beforeCTEs = useLateral
? this.buildBeforeCTEsLateral(effectiveConfig, resolved, context)
: this.buildBeforeCTEsWindow(effectiveConfig, resolved, context)
ctes.push(...beforeCTEs)
// 3. After step CTEs - walk forwards from starting step
const afterCTEs = useLateral
? this.buildAfterCTEsLateral(effectiveConfig, resolved, context)
: this.buildAfterCTEsWindow(effectiveConfig, resolved, context)
ctes.push(...afterCTEs)
// 4. Nodes aggregation CTE - count entities per (layer, event_type)
const nodesAggCTE = this.buildNodesAggregationCTE(effectiveConfig, context)
ctes.push(nodesAggCTE)
// 5. Links aggregation CTE - count transitions between layers
const linksAggCTE = this.buildLinksAggregationCTE(effectiveConfig, context)
ctes.push(linksAggCTE)
// 6. Final result CTE - combine nodes and links
const finalCTE = this.buildFinalResultCTE(context)
ctes.push(finalCTE)
// Chain all CTEs and select from final result
return context.db.with(...ctes).select().from(finalCTE)
}
/**
* Transform raw SQL result to FlowResultRow
* The raw result contains rows with record_type = 'node' or 'link'
*/
transformResult(rawResult: Record<string, unknown>[]): FlowResultRow {
if (!rawResult || rawResult.length === 0) {
return { nodes: [], links: [] }
}
const nodes: SankeyNode[] = []
const links: SankeyLink[] = []
for (const row of rawResult) {
const recordType = row.record_type as string
if (recordType === 'node') {
nodes.push({
id: String(row.id),
name: String(row.name),
layer: Number(row.layer),
value: Number(row.value),
})
E} else if (recordType === 'link') {
links.push({
source: String(row.source_id),
target: String(row.target_id),
value: Number(row.value),
})
}
}
// Sort nodes by layer for consistent Sankey rendering
nodes.sort((a, b) => a.layer - b.layer)
return { nodes, links }
}
// ============================================================================
// Private: Resolution Methods
// ============================================================================
/**
* Resolve flow configuration to SQL expressions
*/
private resolveFlowConfig(
config: FlowQueryConfig,
cubes: Map<string, Cube>,
context: QueryContext
): ResolvedFlowConfig {
const cube = this.resolveCube(config, cubes)
const cubeBase = cube.sql(context)
return {
cube,
cubeBase,
bindingKeyExpr: this.resolveBindingKey(config, cube, context),
timeExpr: this.resolveTimeDimension(config, cube, context),
eventExpr: this.resolveEventDimension(config, cube, context),
startingStepFilters: this.buildStartingStepFilters(config, cube, context),
}
}
/**
* Resolve the cube for flow analysis
*/
private resolveCube(config: FlowQueryConfig, cubes: Map<string, Cube>): Cube {
let cubeName: string
if (typeof config.bindingKey === 'string') {
;[cubeName] = config.bindingKey.split('.')
E} else if (Array.isArray(config.bindingKey) && config.bindingKey.length > 0) {
cubeName = config.bindingKey[0].cube
} else {
throw new Error('Cannot resolve cube for flow query')
}
const cube = cubes.get(cubeName)
Iif (!cube) {
throw new Error(`Cube not found: ${cubeName}`)
}
return cube
}
/**
* Resolve binding key expression
*/
private resolveBindingKey(
config: FlowQueryConfig,
cube: Cube,
context: QueryContext
): SQL {
Eif (typeof config.bindingKey === 'string') {
const [, dimName] = config.bindingKey.split('.')
const dimension = cube.dimensions?.[dimName]
Iif (!dimension) {
throw new Error(`Binding key dimension not found: ${config.bindingKey}`)
}
return resolveSqlExpression(dimension.sql, context) as SQL
}
const mapping = config.bindingKey.find((m) => m.cube === cube.name)
if (!mapping) {
throw new Error(`No binding key mapping found for cube: ${cube.name}`)
}
const [, dimName] = mapping.dimension.split('.')
const dimension = cube.dimensions?.[dimName]
Iif (!dimension) {
throw new Error(`Binding key dimension not found: ${mapping.dimension}`)
}
return resolveSqlExpression(dimension.sql, context) as SQL
}
/**
* Resolve time dimension expression
*/
private resolveTimeDimension(
config: FlowQueryConfig,
cube: Cube,
context: QueryContext
): SQL {
Eif (typeof config.timeDimension === 'string') {
const [, dimName] = config.timeDimension.split('.')
const dimension = cube.dimensions?.[dimName]
Iif (!dimension) {
throw new Error(`Time dimension not found: ${config.timeDimension}`)
}
return resolveSqlExpression(dimension.sql, context) as SQL
}
const mapping = config.timeDimension.find((m) => m.cube === cube.name)
if (!mapping) {
throw new Error(`No time dimension mapping found for cube: ${cube.name}`)
}
const [, dimName] = mapping.dimension.split('.')
const dimension = cube.dimensions?.[dimName]
Iif (!dimension) {
throw new Error(`Time dimension not found: ${mapping.dimension}`)
}
return resolveSqlExpression(dimension.sql, context) as SQL
}
/**
* Resolve event dimension expression
*/
private resolveEventDimension(
config: FlowQueryConfig,
cube: Cube,
context: QueryContext
): SQL {
const [, dimName] = config.eventDimension.split('.')
const dimension = cube.dimensions?.[dimName]
Iif (!dimension) {
throw new Error(`Event dimension not found: ${config.eventDimension}`)
}
return resolveSqlExpression(dimension.sql, context) as SQL
}
/**
* Build filter conditions for the starting step
*/
private buildStartingStepFilters(
config: FlowQueryConfig,
cube: Cube,
context: QueryContext
): SQL[] {
Iif (!config.startingStep.filter) {
return []
}
const filters = Array.isArray(config.startingStep.filter)
? config.startingStep.filter
: [config.startingStep.filter]
const conditions: SQL[] = []
for (const filter of filters) {
const condition = this.buildFilterCondition(filter, cube, context)
if (condition) {
conditions.push(condition)
}
}
return conditions
}
/**
* Build a single filter condition
*/
private buildFilterCondition(
filter: Filter,
cube: Cube,
context: QueryContext
): SQL | null {
// Handle logical filters (AND/OR)
if ('and' in filter || 'or' in filter) {
const logicalFilter = filter as LogicalFilter
const subConditions: SQL[] = []
const filterList = logicalFilter.and || logicalFilter.or || []
for (const subFilter of filterList) {
const condition = this.buildFilterCondition(subFilter, cube, context)
Eif (condition) {
subConditions.push(condition)
}
}
Iif (subConditions.length === 0) return null
Iif (subConditions.length === 1) return subConditions[0]
if ('and' in filter) {
return and(...subConditions) as SQL
} else {
return sql`(${sql.join(subConditions, sql` OR `)})`
}
}
// Handle client-style group filters
Iif ('type' in filter && 'filters' in filter) {
const groupFilter = filter as { type: 'and' | 'or'; filters: Filter[] }
const subConditions: SQL[] = []
for (const subFilter of groupFilter.filters || []) {
const condition = this.buildFilterCondition(subFilter, cube, context)
if (condition) {
subConditions.push(condition)
}
}
if (subConditions.length === 0) return null
if (subConditions.length === 1) return subConditions[0]
if (groupFilter.type === 'and') {
return and(...subConditions) as SQL
} else {
return sql`(${sql.join(subConditions, sql` OR `)})`
}
}
// Handle simple filter condition
const simpleFilter = filter as FilterCondition
const [, dimName] = simpleFilter.member.split('.')
const dimension = cube.dimensions?.[dimName]
Iif (!dimension) return null
const fieldExpr = resolveSqlExpression(dimension.sql, context)
return this.filterBuilder.buildFilterCondition(
fieldExpr,
simpleFilter.operator,
simpleFilter.values || [],
dimension,
simpleFilter.dateRange
)
}
// ============================================================================
// Private: CTE Builder Methods
// ============================================================================
/**
* Build the starting entities CTE
* Finds all entities matching the starting step filter with their start time and event type
* For sunburst mode, also initializes event_path with the starting event type
*/
private buildStartingEntitiesCTE(
config: FlowQueryConfig,
resolved: ResolvedFlowConfig,
context: QueryContext
): WithSubquery {
const { cubeBase, bindingKeyExpr, timeExpr, eventExpr, startingStepFilters } = resolved
// Build WHERE conditions: security context + starting step filters
const whereConditions: SQL[] = []
Eif (cubeBase.where) {
whereConditions.push(cubeBase.where)
}
whereConditions.push(...startingStepFilters)
// Build query using Drizzle's select pattern
// Include event_path for sunburst mode - initialized to just the event_type
let query = context.db
.select({
binding_key: sql`${bindingKeyExpr}`.as('binding_key'),
start_time: sql`MIN(${timeExpr})`.as('start_time'),
event_type: sql`${eventExpr}`.as('event_type'),
// event_path starts as just the event_type at layer 0
event_path: sql`${eventExpr}`.as('event_path'),
})
.from(cubeBase.from)
// Apply WHERE conditions
Eif (whereConditions.length > 0) {
const combinedWhere =
whereConditions.length === 1
? whereConditions[0]
: (and(...whereConditions) as SQL)
query = query.where(combinedWhere)
}
// Group by binding key and event type
query = query.groupBy(bindingKeyExpr, eventExpr)
// Apply entity limit if specified
if (config.entityLimit) {
query = query.limit(config.entityLimit)
}
return context.db.$with('starting_entities').as(query)
}
/**
* Build CTEs for steps BEFORE the starting point using LATERAL joins
* Uses ORDER BY ... DESC LIMIT 1 to fetch immediate predecessor via index
*/
private buildBeforeCTEsLateral(
config: FlowQueryConfig,
resolved: ResolvedFlowConfig,
context: QueryContext
): WithSubquery[] {
const { cubeBase, bindingKeyExpr, timeExpr, eventExpr } = resolved
const ctes: WithSubquery[] = []
const isSunburst = config.outputMode === 'sunburst'
for (let depth = 1; depth <= config.stepsBefore; depth++) {
const prevAlias = depth === 1 ? 'starting_entities' : `before_step_${depth - 1}`
const prevTimeColumn = depth === 1 ? 'start_time' : 'step_time'
const alias = `before_step_${depth}`
const whereConditions: SQL[] = []
Eif (cubeBase.where) {
whereConditions.push(cubeBase.where)
}
whereConditions.push(
sql`${bindingKeyExpr} = ${sql.identifier(prevAlias)}.binding_key`,
sql`${timeExpr} < ${sql.identifier(prevAlias)}.${sql.identifier(prevTimeColumn)}`
)
const combinedWhere =
whereConditions.length === 1
? whereConditions[0]
: (and(...whereConditions) as SQL)
const eventPathExpr = isSunburst
? sql`${eventExpr} || ${'→'} || ${sql.identifier(prevAlias)}.event_path`
: sql`${eventExpr}`
const lateralSubquery = context.db
.select({
binding_key: sql`${bindingKeyExpr}`.as('binding_key'),
step_time: sql`${timeExpr}`.as('step_time'),
event_type: sql`${eventExpr}`.as('event_type'),
event_path: eventPathExpr.as('event_path'),
})
.from(cubeBase.from)
.where(combinedWhere)
.orderBy(sql`${timeExpr} DESC`)
.limit(1)
const cte = context.db.$with(alias).as(
context.db
.select({
binding_key: sql`e.binding_key`.as('binding_key'),
step_time: sql`e.step_time`.as('step_time'),
event_type: sql`e.event_type`.as('event_type'),
event_path: sql`e.event_path`.as('event_path'),
})
.from(sql`${sql.identifier(prevAlias)}`)
.crossJoinLateral(lateralSubquery.as('e'))
)
ctes.push(cte)
}
return ctes
}
/**
* Build CTEs for steps AFTER the starting point using LATERAL joins
* Uses ORDER BY ... ASC LIMIT 1 to fetch immediate successor via index
*/
private buildAfterCTEsLateral(
config: FlowQueryConfig,
resolved: ResolvedFlowConfig,
context: QueryContext
): WithSubquery[] {
const { cubeBase, bindingKeyExpr, timeExpr, eventExpr } = resolved
const ctes: WithSubquery[] = []
const isSunburst = config.outputMode === 'sunburst'
for (let depth = 1; depth <= config.stepsAfter; depth++) {
const prevAlias = depth === 1 ? 'starting_entities' : `after_step_${depth - 1}`
const prevTimeColumn = depth === 1 ? 'start_time' : 'step_time'
const alias = `after_step_${depth}`
const whereConditions: SQL[] = []
Eif (cubeBase.where) {
whereConditions.push(cubeBase.where)
}
whereConditions.push(
sql`${bindingKeyExpr} = ${sql.identifier(prevAlias)}.binding_key`,
sql`${timeExpr} > ${sql.identifier(prevAlias)}.${sql.identifier(prevTimeColumn)}`
)
const combinedWhere =
whereConditions.length === 1
? whereConditions[0]
: (and(...whereConditions) as SQL)
const eventPathExpr = isSunburst
? sql`${sql.identifier(prevAlias)}.event_path || ${'→'} || ${eventExpr}`
: sql`${eventExpr}`
const lateralSubquery = context.db
.select({
binding_key: sql`${bindingKeyExpr}`.as('binding_key'),
step_time: sql`${timeExpr}`.as('step_time'),
event_type: sql`${eventExpr}`.as('event_type'),
event_path: eventPathExpr.as('event_path'),
})
.from(cubeBase.from)
.where(combinedWhere)
.orderBy(sql`${timeExpr} ASC`)
.limit(1)
const cte = context.db.$with(alias).as(
context.db
.select({
binding_key: sql`e.binding_key`.as('binding_key'),
step_time: sql`e.step_time`.as('step_time'),
event_type: sql`e.event_type`.as('event_type'),
event_path: sql`e.event_path`.as('event_path'),
})
.from(sql`${sql.identifier(prevAlias)}`)
.crossJoinLateral(lateralSubquery.as('e'))
)
ctes.push(cte)
}
return ctes
}
/**
* Build CTEs for steps BEFORE the starting point
* Each CTE finds the immediate predecessor event for entities from the previous CTE
*
* Uses ROW_NUMBER() window function to get exactly the Nth previous event
* For sunburst mode, accumulates event_path by prepending to previous path
*/
private buildBeforeCTEsWindow(
config: FlowQueryConfig,
resolved: ResolvedFlowConfig,
context: QueryContext
): WithSubquery[] {
const { cubeBase, bindingKeyExpr, timeExpr, eventExpr } = resolved
const ctes: WithSubquery[] = []
const isSunburst = config.outputMode === 'sunburst'
for (let depth = 1; depth <= config.stepsBefore; depth++) {
const prevAlias = depth === 1 ? 'starting_entities' : `before_step_${depth - 1}`
const prevTimeColumn = depth === 1 ? 'start_time' : 'step_time'
const alias = `before_step_${depth}`
// Build WHERE conditions
const whereConditions: SQL[] = []
if (cubeBase.where) {
whereConditions.push(cubeBase.where)
}
// Time constraint: event must be BEFORE the reference time
whereConditions.push(
sql`${timeExpr} < ${sql.identifier(prevAlias)}.${sql.identifier(prevTimeColumn)}`
)
const combinedWhere =
whereConditions.length === 1
? whereConditions[0]
: (and(...whereConditions) as SQL)
// Build event_path expression for sunburst mode
// For before steps, prepend current event to previous path (reverse order)
const eventPathExpr = isSunburst
? sql`${eventExpr} || ${'→'} || ${sql.identifier(prevAlias)}.event_path`
: sql`${eventExpr}` // For sankey mode, just use event_type as path
// Build the CTE using a subquery with ROW_NUMBER window function
// ROW_NUMBER() OVER (PARTITION BY binding_key ORDER BY time DESC) gives us the Nth previous event
const rankedQuery = context.db
.select({
binding_key: sql`${bindingKeyExpr}`.as('binding_key'),
step_time: sql`${timeExpr}`.as('step_time'),
event_type: sql`${eventExpr}`.as('event_type'),
event_path: eventPathExpr.as('event_path'),
rn: sql`ROW_NUMBER() OVER (PARTITION BY ${bindingKeyExpr} ORDER BY ${timeExpr} DESC)`.as('rn'),
})
.from(cubeBase.from)
.innerJoin(
sql`${sql.identifier(prevAlias)}`,
sql`${bindingKeyExpr} = ${sql.identifier(prevAlias)}.binding_key`
)
.where(combinedWhere)
// Wrap to filter for rn = 1 (immediate predecessor)
const filteredQuery = context.db
.select({
binding_key: sql`binding_key`.as('binding_key'),
step_time: sql`step_time`.as('step_time'),
event_type: sql`event_type`.as('event_type'),
event_path: sql`event_path`.as('event_path'),
})
.from(rankedQuery.as('ranked'))
.where(sql`rn = 1`)
ctes.push(context.db.$with(alias).as(filteredQuery))
}
return ctes
}
/**
* Build CTEs for steps AFTER the starting point
* Each CTE finds the immediate successor event for entities from the previous CTE
*
* Uses ROW_NUMBER() window function to get exactly the Nth following event
* For sunburst mode, accumulates event_path by concatenating with previous path
*/
private buildAfterCTEsWindow(
config: FlowQueryConfig,
resolved: ResolvedFlowConfig,
context: QueryContext
): WithSubquery[] {
const { cubeBase, bindingKeyExpr, timeExpr, eventExpr } = resolved
const ctes: WithSubquery[] = []
const isSunburst = config.outputMode === 'sunburst'
for (let depth = 1; depth <= config.stepsAfter; depth++) {
const prevAlias = depth === 1 ? 'starting_entities' : `after_step_${depth - 1}`
const prevTimeColumn = depth === 1 ? 'start_time' : 'step_time'
const alias = `after_step_${depth}`
// Build WHERE conditions
const whereConditions: SQL[] = []
if (cubeBase.where) {
whereConditions.push(cubeBase.where)
}
// Time constraint: event must be AFTER the reference time
whereConditions.push(
sql`${timeExpr} > ${sql.identifier(prevAlias)}.${sql.identifier(prevTimeColumn)}`
)
const combinedWhere =
whereConditions.length === 1
? whereConditions[0]
: (and(...whereConditions) as SQL)
// Build event_path expression for sunburst mode
// Concatenates previous path with current event type using arrow separator
const eventPathExpr = isSunburst
? sql`${sql.identifier(prevAlias)}.event_path || ${'→'} || ${eventExpr}`
: sql`${eventExpr}` // For sankey mode, just use event_type as path
// Build the CTE using a subquery with ROW_NUMBER window function
// ROW_NUMBER() OVER (PARTITION BY binding_key ORDER BY time ASC) gives us the Nth following event
const rankedQuery = context.db
.select({
binding_key: sql`${bindingKeyExpr}`.as('binding_key'),
step_time: sql`${timeExpr}`.as('step_time'),
event_type: sql`${eventExpr}`.as('event_type'),
event_path: eventPathExpr.as('event_path'),
rn: sql`ROW_NUMBER() OVER (PARTITION BY ${bindingKeyExpr} ORDER BY ${timeExpr} ASC)`.as('rn'),
})
.from(cubeBase.from)
.innerJoin(
sql`${sql.identifier(prevAlias)}`,
sql`${bindingKeyExpr} = ${sql.identifier(prevAlias)}.binding_key`
)
.where(combinedWhere)
// Wrap to filter for rn = 1 (immediate successor)
const filteredQuery = context.db
.select({
binding_key: sql`binding_key`.as('binding_key'),
step_time: sql`step_time`.as('step_time'),
event_type: sql`event_type`.as('event_type'),
event_path: sql`event_path`.as('event_path'),
})
.from(rankedQuery.as('ranked'))
.where(sql`rn = 1`)
ctes.push(context.db.$with(alias).as(filteredQuery))
}
return ctes
}
/**
* Build the nodes aggregation CTE
* Aggregates counts per (layer, event_type) combination using UNION ALL
* For sunburst mode, aggregates by event_path for unique tree branches
*/
private buildNodesAggregationCTE(
config: FlowQueryConfig,
context: QueryContext
): WithSubquery {
// Build UNION ALL of counts from all layers
const unionParts: SQL[] = []
const isSunburst = config.outputMode === 'sunburst'
// Before steps (negative layers, furthest first)
// Note: Using sql.raw() for prefix strings to avoid multi-digit parameter issues in DuckDB
// These are hardcoded constants (not user input), so sql.raw() is safe here
for (let depth = config.stepsBefore; depth >= 1; depth--) {
const layer = -depth
const alias = `before_step_${depth}`
Iif (isSunburst) {
// Sunburst: Group by event_path for unique branches
unionParts.push(sql`
SELECT
${sql.raw(`'before_${depth}_'`)} || event_path AS node_id,
event_type AS name,
${sql.raw(String(layer))} AS layer,
COUNT(*) AS value
FROM ${sql.identifier(alias)}
GROUP BY event_path, event_type
`)
} else {
// Sankey: Group by event_type (paths can converge)
unionParts.push(sql`
SELECT
${sql.raw(`'before_${depth}_'`)} || event_type AS node_id,
event_type AS name,
${sql.raw(String(layer))} AS layer,
COUNT(*) AS value
FROM ${sql.identifier(alias)}
GROUP BY event_type
`)
}
}
// Starting step (layer 0) - same for both modes since it's the root
unionParts.push(sql`
SELECT
${sql.raw("'start_'")} || event_type AS node_id,
event_type AS name,
0 AS layer,
COUNT(*) AS value
FROM starting_entities
GROUP BY event_type
`)
// After steps (positive layers)
for (let depth = 1; depth <= config.stepsAfter; depth++) {
const layer = depth
const alias = `after_step_${depth}`
if (isSunburst) {
// Sunburst: Group by event_path for unique branches
unionParts.push(sql`
SELECT
${sql.raw(`'after_${depth}_'`)} || event_path AS node_id,
event_type AS name,
${sql.raw(String(layer))} AS layer,
COUNT(*) AS value
FROM ${sql.identifier(alias)}
GROUP BY event_path, event_type
`)
} else {
// Sankey: Group by event_type (paths can converge)
unionParts.push(sql`
SELECT
${sql.raw(`'after_${depth}_'`)} || event_type AS node_id,
event_type AS name,
${sql.raw(String(layer))} AS layer,
COUNT(*) AS value
FROM ${sql.identifier(alias)}
GROUP BY event_type
`)
}
}
const unionQuery = sql.join(unionParts, sql` UNION ALL `)
const query = context.db
.select({
node_id: sql`node_id`.as('node_id'),
name: sql`name`.as('name'),
layer: sql`layer`.as('layer'),
value: sql`value`.as('value'),
})
.from(sql`(${unionQuery}) AS nodes_union`)
return context.db.$with('nodes_agg').as(query)
}
/**
* Build the links aggregation CTE
* Counts transitions between adjacent layers
* For sunburst mode, uses event_path for unique branch identification
*/
private buildLinksAggregationCTE(
config: FlowQueryConfig,
context: QueryContext
): WithSubquery {
const linkParts: SQL[] = []
const isSunburst = config.outputMode === 'sunburst'
// Links between before steps (towards start)
// Note: Using sql.raw() for prefix strings to avoid multi-digit parameter issues in DuckDB
// These are hardcoded constants (not user input), so sql.raw() is safe here
for (let depth = config.stepsBefore; depth >= 2; depth--) {
const fromAlias = `before_step_${depth}`
const toAlias = `before_step_${depth - 1}`
Iif (isSunburst) {
// Sunburst: Use event_path for unique branches
linkParts.push(sql`
SELECT
${sql.raw(`'before_${depth}_'`)} || f.event_path AS source_id,
${sql.raw(`'before_${depth - 1}_'`)} || t.event_path AS target_id,
COUNT(*) AS value
FROM ${sql.identifier(fromAlias)} f
INNER JOIN ${sql.identifier(toAlias)} t ON f.binding_key = t.binding_key
GROUP BY f.event_path, t.event_path
`)
} else {
// Sankey: Use event_type (paths can converge)
linkParts.push(sql`
SELECT
${sql.raw(`'before_${depth}_'`)} || f.event_type AS source_id,
${sql.raw(`'before_${depth - 1}_'`)} || t.event_type AS target_id,
COUNT(*) AS value
FROM ${sql.identifier(fromAlias)} f
INNER JOIN ${sql.identifier(toAlias)} t ON f.binding_key = t.binding_key
GROUP BY f.event_type, t.event_type
`)
}
}
// Link from before_step_1 to start
if (config.stepsBefore >= 1) {
Iif (isSunburst) {
linkParts.push(sql`
SELECT
${sql.raw("'before_1_'")} || b.event_path AS source_id,
${sql.raw("'start_'")} || s.event_type AS target_id,
COUNT(*) AS value
FROM before_step_1 b
INNER JOIN starting_entities s ON b.binding_key = s.binding_key
GROUP BY b.event_path, s.event_type
`)
} else {
linkParts.push(sql`
SELECT
${sql.raw("'before_1_'")} || b.event_type AS source_id,
${sql.raw("'start_'")} || s.event_type AS target_id,
COUNT(*) AS value
FROM before_step_1 b
INNER JOIN starting_entities s ON b.binding_key = s.binding_key
GROUP BY b.event_type, s.event_type
`)
}
}
// Link from start to after_step_1
Eif (config.stepsAfter >= 1) {
if (isSunburst) {
// For sunburst, link from start to path-qualified after_step_1
linkParts.push(sql`
SELECT
${sql.raw("'start_'")} || s.event_type AS source_id,
${sql.raw("'after_1_'")} || a.event_path AS target_id,
COUNT(*) AS value
FROM starting_entities s
INNER JOIN after_step_1 a ON s.binding_key = a.binding_key
GROUP BY s.event_type, a.event_path
`)
} else {
linkParts.push(sql`
SELECT
${sql.raw("'start_'")} || s.event_type AS source_id,
${sql.raw("'after_1_'")} || a.event_type AS target_id,
COUNT(*) AS value
FROM starting_entities s
INNER JOIN after_step_1 a ON s.binding_key = a.binding_key
GROUP BY s.event_type, a.event_type
`)
}
}
// Links between after steps (away from start)
for (let depth = 1; depth < config.stepsAfter; depth++) {
const fromAlias = `after_step_${depth}`
const toAlias = `after_step_${depth + 1}`
Iif (isSunburst) {
// Sunburst: Use event_path for unique branches
linkParts.push(sql`
SELECT
${sql.raw(`'after_${depth}_'`)} || f.event_path AS source_id,
${sql.raw(`'after_${depth + 1}_'`)} || t.event_path AS target_id,
COUNT(*) AS value
FROM ${sql.identifier(fromAlias)} f
INNER JOIN ${sql.identifier(toAlias)} t ON f.binding_key = t.binding_key
GROUP BY f.event_path, t.event_path
`)
} else {
// Sankey: Use event_type (paths can converge)
linkParts.push(sql`
SELECT
${sql.raw(`'after_${depth}_'`)} || f.event_type AS source_id,
${sql.raw(`'after_${depth + 1}_'`)} || t.event_type AS target_id,
COUNT(*) AS value
FROM ${sql.identifier(fromAlias)} f
INNER JOIN ${sql.identifier(toAlias)} t ON f.binding_key = t.binding_key
GROUP BY f.event_type, t.event_type
`)
}
}
// If no links possible, return empty result
Iif (linkParts.length === 0) {
const emptyQuery = context.db
.select({
source_id: sql`NULL`.as('source_id'),
target_id: sql`NULL`.as('target_id'),
value: sql`0`.as('value'),
})
.from(sql`(SELECT 1) AS empty`)
.where(sql`1 = 0`)
return context.db.$with('links_agg').as(emptyQuery)
}
const unionQuery = sql.join(linkParts, sql` UNION ALL `)
const query = context.db
.select({
source_id: sql`source_id`.as('source_id'),
target_id: sql`target_id`.as('target_id'),
value: sql`value`.as('value'),
})
.from(sql`(${unionQuery}) AS links_union`)
return context.db.$with('links_agg').as(query)
}
/**
* Build the final result CTE
* Combines nodes and links into a single result set with record_type discriminator
*/
private buildFinalResultCTE(context: QueryContext): WithSubquery {
// UNION ALL of nodes and links with type discriminator
const unionQuery = sql`
SELECT
'node' AS record_type,
node_id AS id,
name AS name,
layer AS layer,
value AS value,
NULL AS source_id,
NULL AS target_id
FROM nodes_agg
UNION ALL
SELECT
'link' AS record_type,
NULL AS id,
NULL AS name,
NULL AS layer,
value AS value,
source_id AS source_id,
target_id AS target_id
FROM links_agg
WHERE source_id IS NOT NULL
`
const query = context.db
.select({
record_type: sql`record_type`.as('record_type'),
id: sql`id`.as('id'),
name: sql`name`.as('name'),
layer: sql`layer`.as('layer'),
value: sql`value`.as('value'),
source_id: sql`source_id`.as('source_id'),
target_id: sql`target_id`.as('target_id'),
})
.from(sql`(${unionQuery}) AS final_union`)
return context.db.$with('final_result').as(query)
}
}
|