hamelin_translation 0.9.6

Lowering and IR for Hamelin query language
Documentation
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
//! Fuse projection commands (SELECT, SET, DROP) into minimal SELECT commands.
//!
//! This pass runs after normalize_commands.
//! Pipeline-level pass contract: `Arc<TypedPipeline> -> Result<Arc<TypedPipeline>, ...>`

use std::collections::HashSet;
use std::sync::Arc;

use ordermap::OrderMap;

use hamelin_lib::{
    err::TranslationError,
    tree::{
        ast::{
            command::Command,
            expression::{Expression, ExpressionKind},
            identifier::{CompoundIdentifier, Identifier, SimpleIdentifier},
            node::Span,
        },
        builder::{self, field, field_ref, select_command, ExpressionBuilder},
        typed_ast::{
            clause::Projections,
            command::{
                TypedCommand, TypedCommandKind, TypedDropCommand, TypedSelectCommand,
                TypedSetCommand,
            },
            context::StatementTranslationContext,
            environment::TypeEnvironment,
            expression::{TypedExpression, TypedExpressionKind},
            pipeline::TypedPipeline,
        },
    },
    types::{struct_type::Struct, Type},
};

/// Fuse projection commands (SELECT, SET, DROP) into minimal SELECT commands.
///
/// Pipeline-level pass contract: `Arc<TypedPipeline> -> Result<Arc<TypedPipeline>, ...>`
///
/// This creates a minimal number of SELECT commands by:
/// 1. Accumulating SET/DROP operations into a pending SELECT
/// 2. Detecting dependency barriers when SET references a field we assigned
/// 3. Emitting the pending SELECT when we hit a barrier or non-projection command
///
/// Returns the original `Rc` unchanged if no fusion is needed.
pub fn fuse_projections(
    pipeline: Arc<TypedPipeline>,
    ctx: &mut StatementTranslationContext,
) -> Result<Arc<TypedPipeline>, Arc<TranslationError>> {
    // Check if fusion is needed
    let needs_fusion = pipeline
        .valid_ref()?
        .commands
        .iter()
        .any(command_needs_fusion);

    if !needs_fusion {
        return Ok(pipeline);
    }

    let valid = pipeline.valid_ref()?;

    // Fuse commands
    let fused_commands = fuse_commands(&valid.commands)?;

    let mut pipe_builder = builder::pipeline().at(pipeline.ast.span.clone());
    for cmd in fused_commands {
        pipe_builder = pipe_builder.command(cmd);
    }
    let fused_ast = pipe_builder.build();

    // Re-typecheck
    Ok(Arc::new(TypedPipeline::from_ast_with_context(
        Arc::new(fused_ast),
        ctx,
    )))
}

/// Check if a command needs fusion (SET or DROP).
fn command_needs_fusion(cmd: &Arc<TypedCommand>) -> bool {
    matches!(
        &cmd.kind,
        TypedCommandKind::Set(_) | TypedCommandKind::Drop(_)
    )
}

/// Fuse commands into minimal SELECT commands.
fn fuse_commands(commands: &[Arc<TypedCommand>]) -> Result<Vec<Command>, Arc<TranslationError>> {
    let mut result: Vec<Command> = Vec::new();
    let mut pending: Option<PendingSelect> = None;

    for command in commands {
        match &command.kind {
            TypedCommandKind::Select(select_cmd) => {
                // SELECT is a barrier - emit pending and start new
                if let Some(p) = pending.take() {
                    result.push(p.emit()?);
                }
                pending = Some(PendingSelect::from_select(command, select_cmd)?);
            }

            TypedCommandKind::Set(set_cmd) => {
                let refs = extract_field_references_from_projections(&set_cmd.projections);

                if let Some(ref mut p) = pending {
                    // Check for dependency barrier:
                    // Expression (RHS) references an assigned identifier
                    let expr_depends = refs
                        .iter()
                        .any(|r| p.assigned.iter().any(|a| identifiers_overlap(r, a)));
                    // Target (LHS) is a child of a non-struct-literal assignment
                    // (e.g., SET x.y = 1 when x was assigned as a computed expression).
                    // If the parent assignment is a struct literal, we can modify it in-place.
                    let target_depends = set_cmd.projections.assignments.iter().any(|assignment| {
                        assignment
                            .identifier
                            .valid_ref()
                            .is_ok_and(|target| has_non_literal_ancestor(&p.assignments, target))
                    });
                    if expr_depends || target_depends {
                        if let Some(prev) = pending.take() {
                            result.push(prev.emit()?);
                        }
                        pending = Some(PendingSelect::from_set(command, set_cmd)?);
                    } else {
                        p.merge_set(command, set_cmd)?;
                    }
                } else {
                    pending = Some(PendingSelect::from_set(command, set_cmd)?);
                }
            }

            TypedCommandKind::Drop(drop_cmd) => {
                if let Some(ref mut p) = pending {
                    // DROP is a barrier if it drops a child of a non-struct-literal assignment
                    let drop_depends = drop_cmd
                        .dropped_fields
                        .iter()
                        .any(|dropped| has_non_literal_ancestor(&p.assignments, dropped));
                    if drop_depends {
                        if let Some(prev) = pending.take() {
                            result.push(prev.emit()?);
                        }
                        pending = Some(PendingSelect::from_drop(command, drop_cmd));
                    } else {
                        p.merge_drop(command, drop_cmd);
                    }
                } else {
                    pending = Some(PendingSelect::from_drop(command, drop_cmd));
                }
            }

            _ => {
                // Non-projection command (WHERE, SORT, AGG, etc.) is a barrier
                if let Some(p) = pending.take() {
                    result.push(p.emit()?);
                }
                // Pass through the original AST command
                result.push(command.ast.as_ref().clone());
            }
        }
    }

    // Flush remaining
    if let Some(p) = pending {
        result.push(p.emit()?);
    }

    Ok(result)
}

/// Pending SELECT being accumulated during fusion.
///
/// Tracks assignments by identifier, preserving insertion order via OrderMap.
struct PendingSelect {
    /// The SELECT assignments being built (identifier -> AST expression)
    /// Only contains explicit assignments from SET/SELECT, NOT passthroughs.
    /// Passthroughs are computed at emit() time from output_schema.
    assignments: OrderMap<Identifier, Arc<Expression>>,
    /// Set of identifiers that have been explicitly assigned (not passthrough)
    /// Used for barrier detection (SET referencing assigned field).
    assigned: HashSet<Identifier>,
    /// Set of identifiers that have been dropped.
    /// Used to determine if struct passthroughs need to recurse.
    dropped: HashSet<Identifier>,
    /// Output schema after all fused commands have been applied.
    /// Used to generate passthroughs at emit() time.
    output_schema: Arc<TypeEnvironment>,
    /// AST span for the synthesized command
    span: Span,
}

impl PendingSelect {
    /// Initialize from a SELECT command
    ///
    /// SELECT replaces the schema entirely, so we store all its assignments
    /// and use its output_schema directly.
    fn from_select(
        command: &TypedCommand,
        select_cmd: &TypedSelectCommand,
    ) -> Result<Self, Arc<TranslationError>> {
        let mut assignments = ordermap::OrderMap::new();
        let mut assigned = HashSet::new();

        for assignment in &select_cmd.projections.assignments {
            let id = assignment.identifier.clone().valid()?;
            // Use the original AST expression
            assignments.insert(id.clone(), assignment.expression.ast.clone());
            // Track as assigned - SET referencing these fields should trigger barrier
            assigned.insert(id);
        }

        Ok(Self {
            assignments,
            assigned,
            dropped: HashSet::new(),
            output_schema: command.output_schema.clone(),
            span: command.ast.span,
        })
    }

    /// Initialize from a SET command (SET assignments first, then passthrough)
    ///
    /// SET assignment keys appear before existing fields in the output schema,
    /// so we store them first in the OrderMap.
    /// Passthroughs are NOT computed here - they're generated at emit() time
    /// based on output_schema minus assignments.
    fn from_set(
        command: &TypedCommand,
        set_cmd: &TypedSetCommand,
    ) -> Result<Self, Arc<TranslationError>> {
        let mut assignments = ordermap::OrderMap::new();
        let mut assigned = HashSet::new();

        // Store only the SET's explicit assignments
        for assignment in &set_cmd.projections.assignments {
            let id = assignment.identifier.clone().valid()?;
            assignments.insert(id.clone(), assignment.expression.ast.clone());
            assigned.insert(id);
        }

        Ok(Self {
            assignments,
            assigned,
            dropped: HashSet::new(),
            output_schema: command.output_schema.clone(),
            span: command.ast.span,
        })
    }

    /// Initialize from a DROP command (passthrough minus dropped fields)
    ///
    /// DROP doesn't have any explicit assignments - all fields are passthroughs
    /// except for the dropped ones. Passthroughs are generated at emit() time.
    fn from_drop(command: &TypedCommand, drop_cmd: &TypedDropCommand) -> Self {
        // DROP has no explicit assignments - everything comes from output_schema
        // Track dropped fields so struct passthroughs know to recurse
        let dropped = drop_cmd.dropped_fields.iter().cloned().collect();
        Self {
            assignments: ordermap::OrderMap::new(),
            assigned: HashSet::new(),
            dropped,
            output_schema: command.output_schema.clone(),
            span: command.ast.span,
        }
    }

    /// Merge a SET command into this pending SELECT.
    ///
    /// SET assignment keys appear before existing fields in the output schema,
    /// so new assignments are inserted before existing ones in the OrderMap.
    /// Passthroughs are computed at emit() time from the output schema.
    ///
    /// When a compound target's parent is a struct literal in assignments,
    /// we fold the assignment into the literal in-place rather than adding
    /// a separate entry.
    fn merge_set(
        &mut self,
        command: &TypedCommand,
        set_cmd: &TypedSetCommand,
    ) -> Result<(), Arc<TranslationError>> {
        // Resolve all identifiers upfront
        let resolved: Vec<_> = set_cmd
            .projections
            .assignments
            .iter()
            .map(|a| a.identifier.clone().valid().map(|id| (id, a)))
            .collect::<Result<_, _>>()?;

        // First, handle compound targets that modify existing struct literal assignments.
        // These get folded into the literal rather than added as separate entries.
        let mut folded_into_literal = HashSet::new();
        for (id, assignment) in &resolved {
            if let Some((ancestor_id, child_path)) =
                find_struct_literal_ancestor(&self.assignments, id)
            {
                if let Some(ancestor_expr) = self.assignments.get_mut(&ancestor_id) {
                    let folded = modify_struct_literal_field(
                        ancestor_expr,
                        &child_path,
                        Some(assignment.expression.ast.clone()),
                    );
                    if folded {
                        folded_into_literal.insert(id.clone());
                    }
                }
            }
        }

        // Build new assignments with SET fields first, then existing fields
        let mut new_assignments = OrderMap::new();

        // Add SET's non-folded assignments (they go to the front)
        for (id, assignment) in &resolved {
            if folded_into_literal.contains(id) {
                continue;
            }
            new_assignments.insert(id.clone(), assignment.expression.ast.clone());
            self.assigned.insert(id.clone());
        }

        // Then add existing explicit assignments (skipping any that the new SET shadows)
        // If SET assigns x.y and we had x = expr, the new SET shadows our x.
        // If SET assigns x and we had x.y = expr, the new SET also shadows our x.y.
        for (id, expr) in self.assignments.drain(..) {
            if new_assignments
                .keys()
                .any(|new_id| identifiers_overlap(&id, new_id))
            {
                continue;
            }
            new_assignments.insert(id, expr);
        }

        self.assignments = new_assignments;
        self.output_schema = command.output_schema.clone();
        self.expand_span(&command.ast.span);
        Ok(())
    }

    /// Merge a DROP command into this pending SELECT
    ///
    /// DROP removes fields. We remove any explicit assignments for dropped fields,
    /// and update output_schema. Passthroughs will be computed at emit() time.
    ///
    /// When dropping a child of a struct literal assignment, we prune the field
    /// from the literal rather than tracking it as a separate drop.
    fn merge_drop(&mut self, command: &TypedCommand, drop_cmd: &TypedDropCommand) {
        for dropped in &drop_cmd.dropped_fields {
            // Try to prune from a struct literal ancestor first
            let pruned = find_struct_literal_ancestor(&self.assignments, dropped)
                .and_then(|(ancestor_id, child_path)| {
                    let expr = self.assignments.get_mut(&ancestor_id)?;
                    modify_struct_literal_field(expr, &child_path, None).then_some(())
                })
                .is_some();

            if !pruned {
                self.assignments.remove(dropped);
                self.assigned.remove(dropped);
                self.dropped.insert(dropped.clone());
            }
        }
        self.output_schema = command.output_schema.clone();
        self.expand_span(&command.ast.span);
    }

    /// Expand the span to include another span (union of the two ranges)
    fn expand_span(&mut self, other: &Span) {
        if other.is_none() {
            return;
        }
        if self.span.is_none() {
            self.span = other.clone();
            return;
        }

        if let (Some(self_start), Some(self_end), Some(other_start), Some(other_end)) = (
            self.span.start(),
            self.span.end(),
            other.start(),
            other.end(),
        ) {
            let new_start = self_start.min(other_start);
            let new_end = self_end.max(other_end);
            self.span = Span::new(new_start, new_end);
        }
    }

    /// Emit as an AST SELECT command.
    ///
    /// Emits fields in the order they appear in `output_schema.to_struct()`:
    /// - Top-level: newest fields first (left-most position)
    /// - Nested structs: oldest fields first (preserves original struct order)
    ///
    /// For each field, either emit the explicit assignment or generate a passthrough.
    fn emit(self) -> Result<Command, Arc<TranslationError>> {
        let mut builder = select_command();

        let output_struct = self.output_schema.as_struct();
        let assignment_set: HashSet<_> = self.assignments.keys().cloned().collect();

        let mut fields_to_emit = Vec::new();
        emit_fields_in_schema_order(
            &output_struct,
            &self.assignments,
            &assignment_set,
            &self.dropped,
            &[],
            &mut fields_to_emit,
        )?;

        for (identifier, expr) in fields_to_emit {
            builder = builder.named_field(identifier, expr);
        }

        Ok(builder.at(self.span).build())
    }
}

/// Check if any assignment or drop overlaps with a struct field.
///
/// Returns true if we need to recurse into the struct to handle partial coverage.
/// Returns false if we can emit the struct directly as a passthrough.
fn any_modification_overlaps_struct(
    assignments: &HashSet<Identifier>,
    dropped: &HashSet<Identifier>,
    struct_id: &Identifier,
) -> bool {
    let overlaps_assignments = assignments
        .iter()
        .any(|a| a == struct_id || a.has_prefix(struct_id) || struct_id.has_prefix(a));
    let overlaps_dropped = dropped
        .iter()
        .any(|d| d == struct_id || d.has_prefix(struct_id) || struct_id.has_prefix(d));
    overlaps_assignments || overlaps_dropped
}

/// Recursively emit fields in schema order, using assignments or passthroughs.
///
/// This preserves the correct field ordering from output_schema.to_struct():
/// - Top-level: newest fields first (left-most position)
/// - Nested structs: oldest fields first (preserves original struct order)
///
/// For each field position:
/// - If there's an explicit assignment → emit that
/// - If it's a struct with partial modifications → recurse for ordered leaf fields
/// - If it's a struct with no modifications → emit struct passthrough
/// - Otherwise → emit leaf passthrough
fn emit_fields_in_schema_order(
    schema: &Struct,
    assignments: &OrderMap<Identifier, Arc<Expression>>,
    assignment_set: &HashSet<Identifier>,
    dropped: &HashSet<Identifier>,
    prefix: &[SimpleIdentifier],
    output: &mut Vec<(Identifier, Arc<Expression>)>,
) -> Result<(), Arc<TranslationError>> {
    for (field_name, field_type) in schema.iter() {
        // Build the full identifier path
        let mut path = prefix.to_vec();
        path.push(field_name.clone().into());
        let full_id: Identifier = match path.as_slice() {
            [] => {
                return Err(TranslationError::fatal(
                    "fuse_projections",
                    "emit_fields_in_schema_order called with empty path".into(),
                )
                .into())
            }
            [single] => single.clone().into(),
            [first, second, rest @ ..] => {
                CompoundIdentifier::new(first.clone(), second.clone(), rest.to_vec()).into()
            }
        };

        // Check if this field is exactly covered by an assignment
        if let Some(expr) = assignments.get(&full_id) {
            output.push((full_id, expr.clone()));
            continue;
        }

        // For struct types, check if any modification overlaps with this struct
        if let Type::Struct(inner_struct) = field_type {
            if any_modification_overlaps_struct(assignment_set, dropped, &full_id) {
                // Partial coverage - recurse to emit leaf-level fields in order
                emit_fields_in_schema_order(
                    inner_struct,
                    assignments,
                    assignment_set,
                    dropped,
                    &path,
                    output,
                )?;
            } else {
                // No overlap - emit the struct directly as a passthrough
                let passthrough_expr = synthesize_passthrough_ast(&full_id);
                output.push((full_id, passthrough_expr.into()));
            }
            continue;
        }

        // Leaf field not covered - emit passthrough
        let passthrough_expr = synthesize_passthrough_ast(&full_id);
        output.push((full_id, passthrough_expr.into()));
    }
    Ok(())
}

/// Synthesize a passthrough AST expression for an identifier.
///
/// For simple identifiers (x), creates a column reference.
/// For compound identifiers (x.y.z), creates a field lookup chain.
fn synthesize_passthrough_ast(identifier: &Identifier) -> Expression {
    match identifier {
        Identifier::Simple(simple) => field_ref(simple.as_str()).build(),
        Identifier::Compound(compound) => {
            // Build chain: field_ref(first).field(second).field(third)...
            let mut current: Box<dyn ExpressionBuilder> =
                Box::new(field_ref(compound.first().as_str()));

            for part in compound.rest_parts() {
                current = Box::new(field(current, part.as_str()));
            }

            current.build()
        }
    }
}

/// Check if two identifiers overlap (one is prefix of the other, or they're equal).
fn identifiers_overlap(a: &Identifier, b: &Identifier) -> bool {
    a == b || a.has_prefix(b) || b.has_prefix(a)
}

/// Check if an identifier has an ancestor in assignments that can't be modified in-place.
///
/// Returns true if there's a strict prefix of `target` in `assignments` whose expression
/// is not a struct literal, OR is a struct literal but the path through it hits a
/// non-literal intermediate field. This means we can't fold the assignment and need a barrier.
fn has_non_literal_ancestor(
    assignments: &OrderMap<Identifier, Arc<Expression>>,
    target: &Identifier,
) -> bool {
    let segments = target.segments();
    for prefix in target.prefixes() {
        if let Some(expr) = assignments.get(&prefix) {
            let ExpressionKind::StructLiteral(ref lit) = expr.kind else {
                return true;
            };
            // Walk the remaining intermediate segments (excluding the leaf)
            // through nested struct literals. If any intermediate is not a
            // struct literal, we can't fold — barrier needed.
            let prefix_len = prefix.segments().len();
            let remaining = &segments[prefix_len..];
            let mut current = lit;
            for segment in &remaining[..remaining.len().saturating_sub(1)] {
                match current
                    .fields
                    .iter()
                    .find(|(id, _)| id.valid_ref().is_ok_and(|n| n == segment))
                {
                    Some((_, child_expr)) => match &child_expr.kind {
                        ExpressionKind::StructLiteral(nested) => current = nested,
                        _ => return true,
                    },
                    None => return false, // field doesn't exist yet, will be created
                }
            }
            return false;
        }
    }
    false
}

/// Find the nearest ancestor in assignments that is a struct literal.
///
/// Returns `Some((ancestor_id, child_path))` where `child_path` is the segments
/// below the ancestor. E.g., for target `x.a.b` with ancestor `x`, returns
/// `(x, [a, b])`.
fn find_struct_literal_ancestor(
    assignments: &OrderMap<Identifier, Arc<Expression>>,
    target: &Identifier,
) -> Option<(Identifier, Vec<SimpleIdentifier>)> {
    let segments = target.segments();
    for prefix in target.prefixes() {
        if let Some(expr) = assignments.get(&prefix) {
            if matches!(expr.kind, ExpressionKind::StructLiteral(_)) {
                let prefix_len = prefix.segments().len();
                let child_path = segments[prefix_len..].to_vec();
                return Some((prefix, child_path));
            }
        }
    }
    None
}

/// Modify a field within a struct literal expression.
///
/// `child_path` is the path of segments below the struct literal to the target field.
/// `new_value` is `Some(expr)` to set/replace the field, or `None` to remove it.
///
/// For nested paths (e.g., `[a, b]`), navigates into nested struct literals.
/// Returns `true` if the modification succeeded, `false` if the path couldn't be followed.
fn modify_struct_literal_field(
    expr: &mut Arc<Expression>,
    child_path: &[SimpleIdentifier],
    new_value: Option<Arc<Expression>>,
) -> bool {
    if child_path.is_empty() {
        return false;
    }

    // Check feasibility before cloning
    if !matches!(expr.kind, ExpressionKind::StructLiteral(_)) {
        return false;
    }

    // Navigate to the parent struct literal containing the target field.
    // For path [a, b, c]: navigate through a, then b, to reach c's parent.
    let owned = Arc::make_mut(expr);
    let ExpressionKind::StructLiteral(ref mut lit) = owned.kind else {
        return false;
    };
    let mut current = lit;

    for segment in &child_path[..child_path.len() - 1] {
        let Some((_, child_expr)) = current.find_field_mut(segment.as_str()) else {
            return false;
        };
        let child = Arc::make_mut(child_expr);
        let ExpressionKind::StructLiteral(ref mut nested) = child.kind else {
            return false;
        };
        current = nested;
    }

    // Apply the modification to the leaf field
    let leaf = child_path.last().expect("child_path is non-empty").as_str();
    match new_value {
        Some(value) => current.set_field(leaf, value),
        None => current.remove_field(leaf),
    }
    true
}

/// Extract all column references from a Projections structure.
fn extract_field_references_from_projections(projections: &Projections) -> HashSet<Identifier> {
    let mut refs = HashSet::new();
    for assignment in &projections.assignments {
        extract_field_references_from_expression(&assignment.expression, &mut refs);
    }
    refs
}

/// Extract all column references from a TypedExpression using find() traversal.
fn extract_field_references_from_expression(
    expr: &TypedExpression,
    refs: &mut HashSet<Identifier>,
) {
    // Use find() to traverse all nodes, collecting field references
    // We return false to keep searching (visit all nodes)
    expr.find(&mut |e| {
        if let TypedExpressionKind::FieldReference(col_ref) = &e.kind {
            if let Ok(simple) = col_ref.field_name.clone().valid() {
                refs.insert(simple.into());
            }
        }
        false // Continue searching to visit all nodes
    });
}

#[cfg(test)]
mod tests {
    use super::*;
    use hamelin_lib::type_check;
    use hamelin_lib::{
        tree::{
            ast::{identifier::CompoundIdentifier, pipeline::Pipeline},
            builder::{
                add, array, drop_command, field_ref, pipeline, select_command, set_command,
                struct_literal,
            },
        },
        types::{struct_type::Struct, INT},
    };
    use pretty_assertions::assert_eq;
    use rstest::rstest;
    use std::sync::Arc;

    #[rstest]
    // Case 1: No SET or DROP commands - passes through unchanged
    #[case::no_fusion_needed(
        pipeline()
            .command(select_command().named_field("a", 1).named_field("b", 2).build())
            .build(),
        pipeline()
            .command(select_command().named_field("a", 1).named_field("b", 2).build())
            .build(),
        Struct::default().with_str("a", INT).with_str("b", INT)
    )]
    // Case 2: SELECT + SET → fused to single SELECT (both projections merged)
    #[case::select_set_fused(
        pipeline()
            .command(select_command().named_field("a", 1).build())
            .command(set_command().named_field("b", 2).build())
            .build(),
        pipeline()
            .command(select_command().named_field("b", 2).named_field("a", 1).build())
            .build(),
        Struct::default().with_str("b", INT).with_str("a", INT)
    )]
    // Case 3: SELECT + DROP → fused to single SELECT (field removed)
    #[case::select_drop_fused(
        pipeline()
            .command(select_command().named_field("a", 1).named_field("b", 2).build())
            .command(drop_command().field("b").build())
            .build(),
        pipeline()
            .command(select_command().named_field("a", 1).build())
            .build(),
        Struct::default().with_str("a", INT)
    )]
    // Case 4: SELECT + multiple SETs → single SELECT
    #[case::select_multiple_sets_fused(
        pipeline()
            .command(select_command().named_field("a", 1).build())
            .command(set_command().named_field("b", 2).build())
            .command(set_command().named_field("c", 3).build())
            .build(),
        pipeline()
            .command(select_command()
                .named_field("c", 3)
                .named_field("b", 2)
                .named_field("a", 1)
                .build())
            .build(),
        Struct::default().with_str("c", INT).with_str("b", INT).with_str("a", INT)
    )]
    // Case 5: SET references field assigned by SELECT → barrier
    // SELECT a = 1 | SET b = a + 1
    // The SET references 'a' which SELECT assigned, so they cannot fuse.
    #[case::barrier_set_refs_select_field(
        pipeline()
            .command(select_command().named_field("a", 1).build())
            .command(set_command().named_field("b", add(field_ref("a"), 1)).build())
            .build(),
        pipeline()
            .command(select_command().named_field("a", 1).build())
            .command(select_command()
                .named_field("b", add(field_ref("a"), 1))
                .named_field("a", field_ref("a"))
                .build())
            .build(),
        Struct::default().with_str("b", INT).with_str("a", INT)
    )]
    // Case 6: SET references field assigned by preceding SET → barrier
    // SELECT a = 1 | SET b = 2 | SET c = b + 1
    // First SET doesn't reference 'a', so it fuses with SELECT.
    // Second SET references 'b' which first SET assigned, so barrier.
    #[case::barrier_set_refs_set_field(
        pipeline()
            .command(select_command().named_field("a", 1).build())
            .command(set_command().named_field("b", 2).build())
            .command(set_command().named_field("c", add(field_ref("b"), 1)).build())
            .build(),
        pipeline()
            .command(select_command()
                .named_field("b", 2)
                .named_field("a", 1)
                .build())
            .command(select_command()
                .named_field("c", add(field_ref("b"), 1))
                .named_field("b", field_ref("b"))
                .named_field("a", field_ref("a"))
                .build())
            .build(),
        Struct::default().with_str("c", INT).with_str("b", INT).with_str("a", INT)
    )]
    // Case 7: Chained SET dependencies → multiple barriers
    // SELECT a = 1 | SET b = a + 1 | SET c = b + 1
    // Each SET references the field assigned by the previous command.
    #[case::barrier_chained_dependencies(
        pipeline()
            .command(select_command().named_field("a", 1).build())
            .command(set_command().named_field("b", add(field_ref("a"), 1)).build())
            .command(set_command().named_field("c", add(field_ref("b"), 1)).build())
            .build(),
        pipeline()
            .command(select_command().named_field("a", 1).build())
            .command(select_command()
                .named_field("b", add(field_ref("a"), 1))
                .named_field("a", field_ref("a"))
                .build())
            .command(select_command()
                .named_field("c", add(field_ref("b"), 1))
                .named_field("b", field_ref("b"))
                .named_field("a", field_ref("a"))
                .build())
            .build(),
        Struct::default().with_str("c", INT).with_str("b", INT).with_str("a", INT)
    )]
    // Case 8: SET overwrites same field without reference → fuses (last write wins)
    // SET a = 1 | SET a = 2
    // Second SET doesn't reference 'a', it just overwrites it. No barrier needed.
    #[case::no_barrier_overwrite_without_ref(
        pipeline()
            .command(set_command().named_field("a", 1).build())
            .command(set_command().named_field("a", 2).build())
            .build(),
        pipeline()
            // Second SET's assignment wins (last write)
            .command(select_command().named_field("a", 2).build())
            .build(),
        Struct::default().with_str("a", INT)
    )]
    // Case 9: SET self-reference → barrier
    // SELECT a = 1 | SET a = a + 1
    // The second SET references 'a' which SELECT assigned.
    #[case::barrier_self_reference(
        pipeline()
            .command(select_command().named_field("a", 1).build())
            .command(set_command().named_field("a", add(field_ref("a"), 1)).build())
            .build(),
        pipeline()
            .command(select_command().named_field("a", 1).build())
            .command(select_command().named_field("a", add(field_ref("a"), 1)).build())
            .build(),
        Struct::default().with_str("a", INT)
    )]
    // Case 10: Independent SETs fuse (no dependency)
    // SELECT a = 1 | SET b = 2 | SET c = 3
    // None of the SETs reference assigned fields, so all fuse.
    #[case::no_barrier_independent_sets(
        pipeline()
            .command(select_command().named_field("a", 1).build())
            .command(set_command().named_field("b", 2).build())
            .command(set_command().named_field("c", 3).build())
            .build(),
        pipeline()
            .command(select_command()
                .named_field("c", 3)
                .named_field("b", 2)
                .named_field("a", 1)
                .build())
            .build(),
        Struct::default().with_str("c", INT).with_str("b", INT).with_str("a", INT)
    )]
    // Case 11: Three SETs without SELECT - verifies from_set prepend order
    // SET a = 1 | SET b = 2 | SET c = 3
    // First SET uses from_set, subsequent SETs use merge_set.
    // Each successive SET prepends, so final order is c, b, a.
    #[case::three_sets_prepend_order(
        pipeline()
            .command(set_command().named_field("a", 1).build())
            .command(set_command().named_field("b", 2).build())
            .command(set_command().named_field("c", 3).build())
            .build(),
        pipeline()
            .command(select_command()
                .named_field("c", 3)
                .named_field("b", 2)
                .named_field("a", 1)
                .build())
            .build(),
        Struct::default().with_str("c", INT).with_str("b", INT).with_str("a", INT)
    )]
    // Case 12: Compound SET assignments are preserved (struct packing happens in IR)
    // SET x.a = 1 | SET x.b = 2 fuses to SELECT x.a = 1, x.b = 2
    // Schema order: a first (created by first SET), b appended by second SET.
    #[case::compound_set_preserved(
        pipeline()
            .command(set_command()
                .named_field(
                    CompoundIdentifier::new("x".into(), "a".into(), vec![]),
                    1,
                )
                .build())
            .command(set_command()
                .named_field(
                    CompoundIdentifier::new("x".into(), "b".into(), vec![]),
                    2,
                )
                .build())
            .build(),
        pipeline()
            .command(select_command()
                .named_field(
                    CompoundIdentifier::new("x".into(), "a".into(), vec![]),
                    1,
                )
                .named_field(
                    CompoundIdentifier::new("x".into(), "b".into(), vec![]),
                    2,
                )
                .build())
            .build(),
        Struct::default()
            .with_str("x", Struct::default().with_str("a", INT).with_str("b", INT).into())
    )]
    // Case 13: Compound SET after EXPLODE barrier with nested struct in input schema
    // This is the exact scenario from the EXPLODE normalization bug:
    // After EXPLODE, input schema has {temp: Int, data: Struct{arr: Array<Int>}}
    // Then SET data.arr = temp assigns a compound identifier.
    // Bug: from_set was adding passthrough for `data` (simple) from flatten() output,
    // which conflicts with the compound assignment `data.arr`.
    // Fix: from_set must skip passthroughs that overlap with compound assignments.
    #[case::compound_set_after_explode_barrier(
        pipeline()
            // Setup: create nested struct and temp field
            .command(set_command()
                .named_field(
                    CompoundIdentifier::new("data".into(), "arr".into(), vec![]),
                    array().element(1).element(2).element(3),
                )
                .named_field("temp", 42)
                .build())
            // EXPLODE is a barrier
            .command(hamelin_lib::tree::builder::explode_command()
                .named_field("temp", field_ref("temp"))
                .build())
            // After barrier: SET with compound identifier into existing struct
            .command(set_command()
                .named_field(
                    CompoundIdentifier::new("data".into(), "arr".into(), vec![]),
                    field_ref("temp"),
                )
                .build())
            .build(),
        pipeline()
            // First SELECT (before barrier)
            .command(select_command()
                .named_field(
                    CompoundIdentifier::new("data".into(), "arr".into(), vec![]),
                    array().element(1).element(2).element(3),
                )
                .named_field("temp", 42)
                .build())
            // EXPLODE barrier preserved
            .command(hamelin_lib::tree::builder::explode_command()
                .named_field("temp", field_ref("temp"))
                .build())
            // Second SELECT: compound assignment + temp passthrough, but NO `data` passthrough
            .command(select_command()
                .named_field(
                    CompoundIdentifier::new("data".into(), "arr".into(), vec![]),
                    field_ref("temp"),
                )
                .named_field("temp", field_ref("temp"))
                .build())
            .build(),
        Struct::default()
            .with_str("data", Struct::default().with_str("arr", INT).into())
            .with_str("temp", INT)
    )]
    // Case 14: Compound SET adding sibling field - must preserve existing siblings
    // SET x.a = 1, x.b = 2 | WHERE true | SET x.y = 3
    // After barrier, input schema has {x: Struct{a: Int, b: Int}}.
    // The SET assigns x.y, which appends to end of x's struct.
    // Expected output schema: {x: Struct{a: Int, b: Int, y: Int}}
    #[case::compound_set_sibling_preserves_existing(
        pipeline()
            // Setup: create struct with two fields
            .command(set_command()
                .named_field(
                    CompoundIdentifier::new("x".into(), "a".into(), vec![]),
                    1,
                )
                .named_field(
                    CompoundIdentifier::new("x".into(), "b".into(), vec![]),
                    2,
                )
                .build())
            // WHERE is a barrier
            .command(hamelin_lib::tree::builder::where_command(true).build())
            // After barrier: SET adds a new sibling field to existing struct
            .command(set_command()
                .named_field(
                    CompoundIdentifier::new("x".into(), "y".into(), vec![]),
                    3,
                )
                .build())
            .build(),
        pipeline()
            // First SELECT (before barrier)
            .command(select_command()
                .named_field(
                    CompoundIdentifier::new("x".into(), "a".into(), vec![]),
                    1,
                )
                .named_field(
                    CompoundIdentifier::new("x".into(), "b".into(), vec![]),
                    2,
                )
                .build())
            // WHERE barrier preserved
            .command(hamelin_lib::tree::builder::where_command(true).build())
            // Second SELECT: passthroughs in schema order, then new field at end
            .command(select_command()
                .named_field(
                    CompoundIdentifier::new("x".into(), "a".into(), vec![]),
                    hamelin_lib::tree::builder::field(field_ref("x"), "a"),
                )
                .named_field(
                    CompoundIdentifier::new("x".into(), "b".into(), vec![]),
                    hamelin_lib::tree::builder::field(field_ref("x"), "b"),
                )
                .named_field(
                    CompoundIdentifier::new("x".into(), "y".into(), vec![]),
                    3,
                )
                .build())
            .build(),
        Struct::default()
            .with_str("x", Struct::default().with_str("a", INT).with_str("b", INT).with_str("y", INT).into())
    )]
    // Case 15: Deep sibling preservation
    // SET x.c.d = 4, x.c.e = 5 | WHERE true | SET x.c.d = 6
    // Expect x.c.e preserved, x.c.d overwritten.
    #[case::deep_sibling_preservation(
        pipeline()
            // Setup: create deeply nested struct with two fields
            .command(set_command()
                .named_field(
                    CompoundIdentifier::new("x".into(), "c".into(), vec!["d".into()]),
                    4,
                )
                .named_field(
                    CompoundIdentifier::new("x".into(), "c".into(), vec!["e".into()]),
                    5,
                )
                .build())
            // WHERE is a barrier
            .command(hamelin_lib::tree::builder::where_command(true).build())
            // After barrier: SET overwrites one deep field
            .command(set_command()
                .named_field(
                    CompoundIdentifier::new("x".into(), "c".into(), vec!["d".into()]),
                    6,
                )
                .build())
            .build(),
        pipeline()
            // First SELECT (before barrier)
            .command(select_command()
                .named_field(
                    CompoundIdentifier::new("x".into(), "c".into(), vec!["d".into()]),
                    4,
                )
                .named_field(
                    CompoundIdentifier::new("x".into(), "c".into(), vec!["e".into()]),
                    5,
                )
                .build())
            // WHERE barrier preserved
            .command(hamelin_lib::tree::builder::where_command(true).build())
            // Second SELECT: overwritten field + passthrough for sibling
            .command(select_command()
                .named_field(
                    CompoundIdentifier::new("x".into(), "c".into(), vec!["d".into()]),
                    6,
                )
                .named_field(
                    CompoundIdentifier::new("x".into(), "c".into(), vec!["e".into()]),
                    hamelin_lib::tree::builder::field(
                        hamelin_lib::tree::builder::field(field_ref("x"), "c"),
                        "e"
                    ),
                )
                .build())
            .build(),
        Struct::default()
            .with_str("x", Struct::default()
                .with_str("c", Struct::default()
                    .with_str("d", INT)
                    .with_str("e", INT)
                    .into())
                .into())
    )]
    // Case 16: Parent vs child conflict - parent first, then child assignment
    // SET x = {a: 1, b: 2} | WHERE true | SET x.a = 3
    // Expect x.a overwritten, x.b preserved via leaf passthrough.
    // First SELECT emits struct literal directly (no desugaring).
    #[case::parent_then_child_assignment(
        pipeline()
            // Setup: create struct via struct literal
            .command(set_command()
                .named_field(
                    "x",
                    hamelin_lib::tree::builder::struct_literal()
                        .field("a", 1)
                        .field("b", 2),
                )
                .build())
            // WHERE is a barrier
            .command(hamelin_lib::tree::builder::where_command(true).build())
            // After barrier: SET assigns a child field
            .command(set_command()
                .named_field(
                    CompoundIdentifier::new("x".into(), "a".into(), vec![]),
                    3,
                )
                .build())
            .build(),
        pipeline()
            // First SELECT: struct literal emitted directly
            .command(select_command()
                .named_field(
                    "x",
                    hamelin_lib::tree::builder::struct_literal()
                        .field("a", 1)
                        .field("b", 2),
                )
                .build())
            // WHERE barrier preserved
            .command(hamelin_lib::tree::builder::where_command(true).build())
            // Second SELECT: child assignment + leaf passthrough for sibling
            .command(select_command()
                .named_field(
                    CompoundIdentifier::new("x".into(), "a".into(), vec![]),
                    3,
                )
                .named_field(
                    CompoundIdentifier::new("x".into(), "b".into(), vec![]),
                    hamelin_lib::tree::builder::field(field_ref("x"), "b"),
                )
                .build())
            .build(),
        Struct::default()
            .with_str("x", Struct::default().with_str("a", INT).with_str("b", INT).into())
    )]
    // Case 17: Child vs parent conflict - child first, then parent assignment
    // SET x.a = 1 | WHERE true | SET x = {y: 2}
    // Parent struct literal REPLACES x entirely. Struct literal emitted directly.
    #[case::child_then_parent_assignment(
        pipeline()
            // Setup: create child field
            .command(set_command()
                .named_field(
                    CompoundIdentifier::new("x".into(), "a".into(), vec![]),
                    1,
                )
                .build())
            // WHERE is a barrier
            .command(hamelin_lib::tree::builder::where_command(true).build())
            // After barrier: SET assigns struct literal - replaces x entirely
            .command(set_command()
                .named_field(
                    "x",
                    hamelin_lib::tree::builder::struct_literal().field("y", 2),
                )
                .build())
            .build(),
        pipeline()
            // First SELECT (before barrier)
            .command(select_command()
                .named_field(
                    CompoundIdentifier::new("x".into(), "a".into(), vec![]),
                    1,
                )
                .build())
            // WHERE barrier preserved
            .command(hamelin_lib::tree::builder::where_command(true).build())
            // Second SELECT: struct literal emitted directly
            .command(select_command()
                .named_field(
                    "x",
                    hamelin_lib::tree::builder::struct_literal().field("y", 2),
                )
                .build())
            .build(),
        Struct::default()
            .with_str("x", Struct::default().with_str("y", INT).into())
    )]
    // Case 18: Mixed deep + new field (recursive example)
    // Input schema x: {a, b, c: {d, e}}, SET assigns x.y = 3, x.c.d = 4
    // Schema order: x: {a, b, c: {d, e}, y} — y appended at end, d replaced in-place.
    #[case::mixed_deep_and_new_field(
        pipeline()
            // Setup: create struct with nested structure
            .command(set_command()
                .named_field(
                    CompoundIdentifier::new("x".into(), "a".into(), vec![]),
                    1,
                )
                .named_field(
                    CompoundIdentifier::new("x".into(), "b".into(), vec![]),
                    2,
                )
                .named_field(
                    CompoundIdentifier::new("x".into(), "c".into(), vec!["d".into()]),
                    10,
                )
                .named_field(
                    CompoundIdentifier::new("x".into(), "c".into(), vec!["e".into()]),
                    20,
                )
                .build())
            // WHERE is a barrier
            .command(hamelin_lib::tree::builder::where_command(true).build())
            // After barrier: SET assigns new sibling + overwrites deep field
            .command(set_command()
                .named_field(
                    CompoundIdentifier::new("x".into(), "y".into(), vec![]),
                    3,
                )
                .named_field(
                    CompoundIdentifier::new("x".into(), "c".into(), vec!["d".into()]),
                    4,
                )
                .build())
            .build(),
        pipeline()
            // First SELECT (before barrier)
            .command(select_command()
                .named_field(
                    CompoundIdentifier::new("x".into(), "a".into(), vec![]),
                    1,
                )
                .named_field(
                    CompoundIdentifier::new("x".into(), "b".into(), vec![]),
                    2,
                )
                .named_field(
                    CompoundIdentifier::new("x".into(), "c".into(), vec!["d".into()]),
                    10,
                )
                .named_field(
                    CompoundIdentifier::new("x".into(), "c".into(), vec!["e".into()]),
                    20,
                )
                .build())
            // WHERE barrier preserved
            .command(hamelin_lib::tree::builder::where_command(true).build())
            // Second SELECT: schema order x.a, x.b, x.c.d, x.c.e, x.y
            .command(select_command()
                .named_field(
                    CompoundIdentifier::new("x".into(), "a".into(), vec![]),
                    hamelin_lib::tree::builder::field(field_ref("x"), "a"),
                )
                .named_field(
                    CompoundIdentifier::new("x".into(), "b".into(), vec![]),
                    hamelin_lib::tree::builder::field(field_ref("x"), "b"),
                )
                .named_field(
                    CompoundIdentifier::new("x".into(), "c".into(), vec!["d".into()]),
                    4,
                )
                .named_field(
                    CompoundIdentifier::new("x".into(), "c".into(), vec!["e".into()]),
                    hamelin_lib::tree::builder::field(
                        hamelin_lib::tree::builder::field(field_ref("x"), "c"),
                        "e"
                    ),
                )
                .named_field(
                    CompoundIdentifier::new("x".into(), "y".into(), vec![]),
                    3,
                )
                .build())
            .build(),
        Struct::default()
            .with_str("x", Struct::default()
                .with_str("a", INT)
                .with_str("b", INT)
                .with_str("c", Struct::default().with_str("d", INT).with_str("e", INT).into())
                .with_str("y", INT)
                .into())
    )]
    // Case 19: DROP + SET within same fused block
    // SET x.a = 1, x.b = 2, x.c = 3 | WHERE true | DROP x.b | SET x.d = 4
    // Schema order: x: {a, c, d} — b dropped, d appended at end.
    #[case::drop_and_set_fused(
        pipeline()
            // Setup: create struct with three fields
            .command(set_command()
                .named_field(
                    CompoundIdentifier::new("x".into(), "a".into(), vec![]),
                    1,
                )
                .named_field(
                    CompoundIdentifier::new("x".into(), "b".into(), vec![]),
                    2,
                )
                .named_field(
                    CompoundIdentifier::new("x".into(), "c".into(), vec![]),
                    3,
                )
                .build())
            // WHERE is a barrier
            .command(hamelin_lib::tree::builder::where_command(true).build())
            // After barrier: DROP one field, then SET adds another
            .command(drop_command()
                .field(CompoundIdentifier::new("x".into(), "b".into(), vec![]))
                .build())
            .command(set_command()
                .named_field(
                    CompoundIdentifier::new("x".into(), "d".into(), vec![]),
                    4,
                )
                .build())
            .build(),
        pipeline()
            // First SELECT (before barrier)
            .command(select_command()
                .named_field(
                    CompoundIdentifier::new("x".into(), "a".into(), vec![]),
                    1,
                )
                .named_field(
                    CompoundIdentifier::new("x".into(), "b".into(), vec![]),
                    2,
                )
                .named_field(
                    CompoundIdentifier::new("x".into(), "c".into(), vec![]),
                    3,
                )
                .build())
            // WHERE barrier preserved
            .command(hamelin_lib::tree::builder::where_command(true).build())
            // Second SELECT: schema order x.a, x.c, x.d
            .command(select_command()
                .named_field(
                    CompoundIdentifier::new("x".into(), "a".into(), vec![]),
                    hamelin_lib::tree::builder::field(field_ref("x"), "a"),
                )
                .named_field(
                    CompoundIdentifier::new("x".into(), "c".into(), vec![]),
                    hamelin_lib::tree::builder::field(field_ref("x"), "c"),
                )
                .named_field(
                    CompoundIdentifier::new("x".into(), "d".into(), vec![]),
                    4,
                )
                .build())
            .build(),
        Struct::default()
            .with_str("x", Struct::default()
                .with_str("a", INT)
                .with_str("c", INT)
                .with_str("d", INT)
                .into())
    )]
    // Case 20: DROP child from direct struct binding
    // SET x = {a: 1, b: 2, c: 3} | WHERE true | DROP x.a
    // First SELECT emits struct literal directly. After barrier, DROP is a passthrough case.
    #[case::drop_child_from_struct_binding(
        pipeline()
            // Setup: create struct via struct literal
            .command(set_command()
                .named_field(
                    "x",
                    struct_literal()
                        .field("a", 1)
                        .field("b", 2)
                        .field("c", 3),
                )
                .build())
            // WHERE is a barrier
            .command(hamelin_lib::tree::builder::where_command(true).build())
            // After barrier: DROP a child field
            .command(drop_command()
                .field(CompoundIdentifier::new("x".into(), "a".into(), vec![]))
                .build())
            .build(),
        pipeline()
            // First SELECT: struct literal emitted directly
            .command(select_command()
                .named_field(
                    "x",
                    struct_literal()
                        .field("a", 1)
                        .field("b", 2)
                        .field("c", 3),
                )
                .build())
            // WHERE barrier preserved
            .command(hamelin_lib::tree::builder::where_command(true).build())
            // Second SELECT: passthroughs for remaining children (x.a dropped)
            .command(select_command()
                .named_field(
                    CompoundIdentifier::new("x".into(), "b".into(), vec![]),
                    hamelin_lib::tree::builder::field(field_ref("x"), "b"),
                )
                .named_field(
                    CompoundIdentifier::new("x".into(), "c".into(), vec![]),
                    hamelin_lib::tree::builder::field(field_ref("x"), "c"),
                )
                .build())
            .build(),
        Struct::default()
            .with_str("x", Struct::default().with_str("b", INT).with_str("c", INT).into())
    )]
    // Case 21: No overlap sanity - unrelated fields passthrough unchanged
    // SET a = 1 | WHERE true | SET b = 2
    // Expect both fields present, no interference.
    #[case::no_overlap_unrelated_fields(
        pipeline()
            // Setup: create one field
            .command(set_command()
                .named_field("a", 1)
                .build())
            // WHERE is a barrier
            .command(hamelin_lib::tree::builder::where_command(true).build())
            // After barrier: SET adds unrelated field
            .command(set_command()
                .named_field("b", 2)
                .build())
            .build(),
        pipeline()
            // First SELECT (before barrier)
            .command(select_command()
                .named_field("a", 1)
                .build())
            // WHERE barrier preserved
            .command(hamelin_lib::tree::builder::where_command(true).build())
            // Second SELECT: new field + passthrough for existing
            .command(select_command()
                .named_field("b", 2)
                .named_field("a", field_ref("a"))
                .build())
            .build(),
        Struct::default().with_str("b", INT).with_str("a", INT)
    )]
    fn test_fuse_projections(
        #[case] input: Pipeline,
        #[case] expected: Pipeline,
        #[case] expected_output_schema: Struct,
    ) {
        let input_typed = type_check(input).output;
        let expected_typed = type_check(expected).output;

        let mut ctx = StatementTranslationContext::default();
        let result = fuse_projections(Arc::new(input_typed), &mut ctx).unwrap();

        // Compare ASTs
        assert_eq!(result.ast, expected_typed.ast);

        // Verify output schema
        let result_schema = result.environment().as_struct().clone();
        assert_eq!(result_schema, expected_output_schema);
    }
}