@@ -64,6 +64,8 @@ enum EvalMethod {
6464 /// [ELSE result]
6565 /// END
6666 WithExpression ( ProjectedCaseBody ) ,
67+ /// Route remaining literal WHEN matches after evaluating the leading branches.
68+ WithLiteralWhen ( ProjectedCaseBody , LiteralLookupTable ) ,
6769 /// This is a specialization for a specific use case where we can take a fast path
6870 /// for expressions that are infallible and can be cheaply computed for the entire
6971 /// record batch rather than just for the rows where the predicate is true.
@@ -128,6 +130,108 @@ struct CaseBody {
128130}
129131
130132impl CaseBody {
133+ fn literal_branch_lookup ( & self ) -> Option < LiteralLookupTable > {
134+ // For short CASE expressions, sequential comparisons avoid lookup/gather setup.
135+ if self . when_then_expr . len ( ) <= 8 {
136+ return None ;
137+ }
138+ // Map keys to original branch indices using the existing first-match/NULL rules.
139+ let count = u32:: try_from ( self . when_then_expr . len ( ) ) . ok ( ) ?;
140+ let body = Self {
141+ expr : self . expr . clone ( ) ,
142+ when_then_expr : self
143+ . when_then_expr
144+ . iter ( )
145+ . zip ( 0 ..count)
146+ . map ( |( ( when, _) , index) | ( Arc :: clone ( when) , lit ( index) ) )
147+ . collect ( ) ,
148+ else_expr : Some ( lit ( count) ) ,
149+ } ;
150+ LiteralLookupTable :: maybe_new ( & body)
151+ }
152+
153+ fn case_when_literal_branches (
154+ & self ,
155+ batch : & RecordBatch ,
156+ keys : & ArrayRef ,
157+ return_type : & DataType ,
158+ lookup : & LiteralLookupTable ,
159+ ) -> Result < ColumnarValue > {
160+ let row_count = batch. num_rows ( ) ;
161+ let count = u32:: try_from ( row_count) . map_err ( |_| {
162+ internal_datafusion_err ! ( "CASE batch exceeds row index limit" )
163+ } ) ?;
164+ let branch_expr = |branch : usize | -> Result < Option < Arc < dyn PhysicalExpr > > > {
165+ if let Some ( ( _, then) ) = self . when_then_expr . get ( branch) {
166+ Ok ( Some ( Arc :: clone ( then) ) )
167+ } else {
168+ self . else_expr
169+ . as_ref ( )
170+ . map ( |otherwise| {
171+ try_cast (
172+ Arc :: clone ( otherwise) ,
173+ & batch. schema ( ) ,
174+ return_type. clone ( ) ,
175+ )
176+ } )
177+ . transpose ( )
178+ }
179+ } ;
180+ let mut result = ResultBuilder :: new ( return_type, row_count) ;
181+ if row_count == 0 {
182+ return result. finish ( ) ;
183+ }
184+ // A constant batch needs one lookup and no gathers, including a batch of NULLs.
185+ let first = keys. slice ( 0 , 1 ) ;
186+ let same_key = if keys. logical_null_count ( ) == row_count {
187+ true
188+ } else {
189+ let value = ScalarValue :: try_from_array ( keys, 0 ) ?. to_scalar ( ) ?;
190+ let equal = compare_with_eq ( & value, keys, keys. data_type ( ) . is_nested ( ) ) ?;
191+ equal. null_count ( ) == 0 && !equal. has_false ( )
192+ } ;
193+ if same_key {
194+ let index = lookup. map_keys_to_values ( & first) ?;
195+ let branch = index. as_primitive :: < UInt32Type > ( ) . value ( 0 ) as usize ;
196+ return match branch_expr ( branch) ? {
197+ Some ( expr) => expr. evaluate ( batch) ,
198+ None => result. finish ( ) ,
199+ } ;
200+ }
201+ let branches = lookup. map_keys_to_values ( keys) ?;
202+ let mut selections = vec ! [ Vec :: new( ) ; self . when_then_expr. len( ) + 1 ] ;
203+ for ( row, branch) in
204+ ( 0 ..count) . zip ( branches. as_primitive :: < UInt32Type > ( ) . values ( ) )
205+ {
206+ selections[ * branch as usize ] . push ( row) ;
207+ }
208+ for ( branch, rows) in selections. into_iter ( ) . enumerate ( ) {
209+ if rows. is_empty ( ) {
210+ continue ;
211+ }
212+ let Some ( expr) = branch_expr ( branch) ? else {
213+ continue ;
214+ } ;
215+ if rows. len ( ) == row_count {
216+ return expr. evaluate ( batch) ;
217+ }
218+ let indices: ArrayRef = Arc :: new ( UInt32Array :: from ( rows) ) ;
219+ let columns = batch
220+ . columns ( )
221+ . iter ( )
222+ . map ( |column| arrow:: compute:: take ( column, & indices, None ) )
223+ . collect :: < std:: result:: Result < Vec < _ > , ArrowError > > ( ) ?;
224+ // Expressions without column references still need the selected row count.
225+ let selected = RecordBatch :: try_new_with_options (
226+ batch. schema ( ) ,
227+ columns,
228+ & RecordBatchOptions :: new ( ) . with_row_count ( Some ( indices. len ( ) ) ) ,
229+ ) ?;
230+ result. add_branch_result ( & indices, expr. evaluate ( & selected) ?) ?;
231+ }
232+ result. finish ( )
233+ }
234+
131235 /// Derives a [ProjectedCaseBody] from this [CaseBody].
132236 fn project ( & self ) -> Result < ProjectedCaseBody > {
133237 // Determine the set of columns that are used in all the expressions of the case body.
@@ -685,6 +789,9 @@ impl CaseExpr {
685789 return Ok ( EvalMethod :: WithExprScalarLookupTable ( mapping) ) ;
686790 }
687791
792+ if let Some ( mapping) = body. literal_branch_lookup ( ) {
793+ return Ok ( EvalMethod :: WithLiteralWhen ( body. project ( ) ?, mapping) ) ;
794+ }
688795 return Ok ( EvalMethod :: WithExpression ( body. project ( ) ?) ) ;
689796 }
690797
@@ -750,6 +857,7 @@ impl CaseBody {
750857 & self ,
751858 batch : & RecordBatch ,
752859 return_type : & DataType ,
860+ lookup : Option < & LiteralLookupTable > ,
753861 ) -> Result < ColumnarValue > {
754862 let mut result_builder = ResultBuilder :: new ( return_type, batch. num_rows ( ) ) ;
755863
@@ -817,6 +925,19 @@ impl CaseBody {
817925 let base_value_is_nested = base_values. data_type ( ) . is_nested ( ) ;
818926
819927 for i in 0 ..self . when_then_expr . len ( ) {
928+ // Preserve early exits for common leading branches before paying for routing.
929+ if i == 2
930+ && let Some ( lookup) = lookup
931+ {
932+ let value = self . case_when_literal_branches (
933+ & remainder_batch,
934+ & base_values,
935+ return_type,
936+ lookup,
937+ ) ?;
938+ result_builder. add_branch_result ( & remainder_rows, value) ?;
939+ return result_builder. finish ( ) ;
940+ }
820941 // Evaluate the 'when' predicate for the remainder batch
821942 // This results in a boolean array with the same length as the remaining number of rows
822943 let when_expr = & self . when_then_expr [ i] . 0 ;
@@ -1047,6 +1168,7 @@ impl CaseExpr {
10471168 & self ,
10481169 batch : & RecordBatch ,
10491170 projected : & ProjectedCaseBody ,
1171+ lookup : Option < & LiteralLookupTable > ,
10501172 ) -> Result < ColumnarValue > {
10511173 let return_type = self . data_type ( & batch. schema ( ) ) ?;
10521174 // projected.projection may include indexes of lambda variables not available on this batch
@@ -1060,9 +1182,9 @@ impl CaseExpr {
10601182 let projected_batch = batch. project ( & projection) ?;
10611183 projected
10621184 . body
1063- . case_when_with_expr ( & projected_batch, & return_type)
1185+ . case_when_with_expr ( & projected_batch, & return_type, lookup )
10641186 } else {
1065- self . body . case_when_with_expr ( batch, & return_type)
1187+ self . body . case_when_with_expr ( batch, & return_type, lookup )
10661188 }
10671189 }
10681190
@@ -1326,7 +1448,10 @@ impl PhysicalExpr for CaseExpr {
13261448 EvalMethod :: WithExpression ( p) => {
13271449 // this use case evaluates "expr" and then compares the values with the "when"
13281450 // values
1329- self . case_when_with_expr ( batch, p)
1451+ self . case_when_with_expr ( batch, p, None )
1452+ }
1453+ EvalMethod :: WithLiteralWhen ( p, lookup) => {
1454+ self . case_when_with_expr ( batch, p, Some ( lookup) )
13301455 }
13311456 EvalMethod :: NoExpression ( p) => {
13321457 // The "when" conditions all evaluate to boolean in this use case and can be
@@ -3524,3 +3649,6 @@ mod proto_tests {
35243649 assert ! ( matches!( err, DataFusionError :: Internal ( msg) if msg. contains( "call 2" ) ) ) ;
35253650 }
35263651}
3652+
3653+ #[ cfg( test) ]
3654+ mod literal_branches_tests;
0 commit comments