datafusion-expr 53.1.0

Logical plan and expression representation for DataFusion query engine
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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

//! Argument resolution logic for named function parameters

use crate::Expr;
use datafusion_common::{Result, plan_err};

/// Represents a named function argument with its original case and quote information.
///
/// This struct preserves whether an identifier was quoted in the SQL, which determines
/// whether case-sensitive or case-insensitive matching should be used per SQL standards.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ArgumentName {
    /// The argument name in its original case as it appeared in the SQL
    pub value: String,
    /// Whether the identifier was quoted (e.g., "STR" vs STR)
    /// - true: quoted identifier, requires case-sensitive matching
    /// - false: unquoted identifier, uses case-insensitive matching
    pub is_quoted: bool,
}

/// Resolves function arguments, handling named and positional notation.
///
/// This function validates and reorders arguments to match the function's parameter names
/// when named arguments are used.
///
/// # Rules
/// - All positional arguments must come before named arguments
/// - Named arguments can be in any order after positional arguments
/// - Parameter names follow SQL identifier rules: unquoted names are case-insensitive
///   (normalized to lowercase), quoted names are case-sensitive
/// - No duplicate parameter names allowed
///
/// # Arguments
/// * `param_names` - The function's parameter names in order
/// * `args` - The argument expressions
/// * `arg_names` - Optional parameter name for each argument
///
/// # Returns
/// A vector of expressions in the correct order matching the parameter names
///
/// # Examples
/// ```text
/// Given parameters ["a", "b", "c"]
/// And call: func(10, c => 30, b => 20)
/// Returns: [Expr(10), Expr(20), Expr(30)]
/// ```
pub fn resolve_function_arguments(
    param_names: &[String],
    args: Vec<Expr>,
    arg_names: Vec<Option<ArgumentName>>,
) -> Result<Vec<Expr>> {
    if args.len() != arg_names.len() {
        return plan_err!(
            "Internal error: args length ({}) != arg_names length ({})",
            args.len(),
            arg_names.len()
        );
    }

    // Check if all arguments are positional (fast path)
    if arg_names.iter().all(|name| name.is_none()) {
        return Ok(args);
    }

    validate_argument_order(&arg_names)?;

    reorder_named_arguments(param_names, args, arg_names)
}

/// Validates that positional arguments come before named arguments
fn validate_argument_order(arg_names: &[Option<ArgumentName>]) -> Result<()> {
    let mut seen_named = false;
    for (i, arg_name) in arg_names.iter().enumerate() {
        match arg_name {
            Some(_) => seen_named = true,
            None if seen_named => {
                return plan_err!(
                    "Positional argument at position {} follows named argument. \
                     All positional arguments must come before named arguments.",
                    i
                );
            }
            None => {}
        }
    }
    Ok(())
}

/// Reorders arguments based on named parameters to match signature order
fn reorder_named_arguments(
    param_names: &[String],
    args: Vec<Expr>,
    arg_names: Vec<Option<ArgumentName>>,
) -> Result<Vec<Expr>> {
    let positional_count = arg_names.iter().filter(|n| n.is_none()).count();

    // Capture args length before consuming the vector
    let args_len = args.len();

    let expected_arg_count = param_names.len();

    if positional_count > expected_arg_count {
        return plan_err!(
            "Too many positional arguments: expected at most {}, got {}",
            expected_arg_count,
            positional_count
        );
    }

    let mut result: Vec<Option<Expr>> = vec![None; expected_arg_count];

    for (i, (arg, arg_name)) in args.into_iter().zip(arg_names).enumerate() {
        if let Some(arg_name) = arg_name {
            // Named argument - find parameter index using linear search
            // Match based on SQL identifier rules:
            // - Quoted identifiers: case-sensitive (exact match)
            // - Unquoted identifiers: case-insensitive match
            let param_index = param_names
                .iter()
                .position(|p| {
                    if arg_name.is_quoted {
                        // Quoted: exact case match
                        p == &arg_name.value
                    } else {
                        // Unquoted: case-insensitive match
                        p.eq_ignore_ascii_case(&arg_name.value)
                    }
                })
                .ok_or_else(|| {
                    datafusion_common::plan_datafusion_err!(
                        "Unknown parameter name '{}'. Valid parameters are: [{}]",
                        arg_name.value,
                        param_names.join(", ")
                    )
                })?;

            if result[param_index].is_some() {
                return plan_err!(
                    "Parameter '{}' specified multiple times",
                    arg_name.value
                );
            }

            result[param_index] = Some(arg);
        } else {
            result[i] = Some(arg);
        }
    }

    // Only require parameters up to the number of arguments provided (supports optional parameters)
    let required_count = args_len;
    for i in 0..required_count {
        if result[i].is_none() {
            return plan_err!("Missing required parameter '{}'", param_names[i]);
        }
    }

    // Return only the assigned parameters (handles optional trailing parameters)
    Ok(result.into_iter().take(required_count).flatten().collect())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lit;

    #[test]
    fn test_all_positional() {
        let param_names = vec!["a".to_string(), "b".to_string()];

        let args = vec![lit(1), lit("hello")];
        let arg_names = vec![None, None];

        let result =
            resolve_function_arguments(&param_names, args.clone(), arg_names).unwrap();
        assert_eq!(result.len(), 2);
    }

    #[test]
    fn test_all_named() {
        let param_names = vec!["a".to_string(), "b".to_string()];

        let args = vec![lit(1), lit("hello")];
        let arg_names = vec![
            Some(ArgumentName {
                value: "a".to_string(),
                is_quoted: false,
            }),
            Some(ArgumentName {
                value: "b".to_string(),
                is_quoted: false,
            }),
        ];

        let result = resolve_function_arguments(&param_names, args, arg_names).unwrap();
        assert_eq!(result.len(), 2);
    }

    #[test]
    fn test_case_insensitive_parameter_matching() {
        // Parameter names in function signature (lowercase)
        let param_names = vec!["startpos".to_string(), "length".to_string()];

        // Unquoted arguments with different casing should match case-insensitively
        let args = vec![lit(1), lit(10)];
        let arg_names = vec![
            Some(ArgumentName {
                value: "STARTPOS".to_string(),
                is_quoted: false,
            }),
            Some(ArgumentName {
                value: "LENGTH".to_string(),
                is_quoted: false,
            }),
        ];

        let result = resolve_function_arguments(&param_names, args, arg_names).unwrap();
        assert_eq!(result.len(), 2);
        assert_eq!(result[0], lit(1));
        assert_eq!(result[1], lit(10));

        // Test with reordering and different cases
        let args2 = vec![lit(20), lit(5)];
        let arg_names2 = vec![
            Some(ArgumentName {
                value: "Length".to_string(),
                is_quoted: false,
            }),
            Some(ArgumentName {
                value: "StartPos".to_string(),
                is_quoted: false,
            }),
        ];

        let result2 =
            resolve_function_arguments(&param_names, args2, arg_names2).unwrap();
        assert_eq!(result2.len(), 2);
        assert_eq!(result2[0], lit(5)); // startpos
        assert_eq!(result2[1], lit(20)); // length
    }

    #[test]
    fn test_quoted_parameter_case_sensitive() {
        // Parameter names in function signature (lowercase)
        let param_names = vec!["str".to_string(), "start_pos".to_string()];

        // Quoted identifiers with wrong case should fail
        let args = vec![lit("hello"), lit(1)];
        let arg_names = vec![
            Some(ArgumentName {
                value: "STR".to_string(),
                is_quoted: true,
            }),
            Some(ArgumentName {
                value: "start_pos".to_string(),
                is_quoted: true,
            }),
        ];

        let result = resolve_function_arguments(&param_names, args, arg_names);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Unknown parameter")
        );

        // Quoted identifiers with correct case should succeed
        let args2 = vec![lit("hello"), lit(1)];
        let arg_names2 = vec![
            Some(ArgumentName {
                value: "str".to_string(),
                is_quoted: true,
            }),
            Some(ArgumentName {
                value: "start_pos".to_string(),
                is_quoted: true,
            }),
        ];

        let result2 =
            resolve_function_arguments(&param_names, args2, arg_names2).unwrap();
        assert_eq!(result2.len(), 2);
        assert_eq!(result2[0], lit("hello"));
        assert_eq!(result2[1], lit(1));
    }

    #[test]
    fn test_named_reordering() {
        let param_names = vec!["a".to_string(), "b".to_string(), "c".to_string()];

        // Call with: func(c => 3.0, a => 1, b => "hello")
        let args = vec![lit(3.0), lit(1), lit("hello")];
        let arg_names = vec![
            Some(ArgumentName {
                value: "c".to_string(),
                is_quoted: false,
            }),
            Some(ArgumentName {
                value: "a".to_string(),
                is_quoted: false,
            }),
            Some(ArgumentName {
                value: "b".to_string(),
                is_quoted: false,
            }),
        ];

        let result = resolve_function_arguments(&param_names, args, arg_names).unwrap();

        // Should be reordered to [a, b, c] = [1, "hello", 3.0]
        assert_eq!(result.len(), 3);
        assert_eq!(result[0], lit(1));
        assert_eq!(result[1], lit("hello"));
        assert_eq!(result[2], lit(3.0));
    }

    #[test]
    fn test_mixed_positional_and_named() {
        let param_names = vec!["a".to_string(), "b".to_string(), "c".to_string()];

        // Call with: func(1, c => 3.0, b => "hello")
        let args = vec![lit(1), lit(3.0), lit("hello")];
        let arg_names = vec![
            None,
            Some(ArgumentName {
                value: "c".to_string(),
                is_quoted: false,
            }),
            Some(ArgumentName {
                value: "b".to_string(),
                is_quoted: false,
            }),
        ];

        let result = resolve_function_arguments(&param_names, args, arg_names).unwrap();

        // Should be reordered to [a, b, c] = [1, "hello", 3.0]
        assert_eq!(result.len(), 3);
        assert_eq!(result[0], lit(1));
        assert_eq!(result[1], lit("hello"));
        assert_eq!(result[2], lit(3.0));
    }

    #[test]
    fn test_positional_after_named_error() {
        let param_names = vec!["a".to_string(), "b".to_string()];

        // Call with: func(a => 1, "hello") - ERROR
        let args = vec![lit(1), lit("hello")];
        let arg_names = vec![
            Some(ArgumentName {
                value: "a".to_string(),
                is_quoted: false,
            }),
            None,
        ];

        let result = resolve_function_arguments(&param_names, args, arg_names);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Positional argument")
        );
    }

    #[test]
    fn test_unknown_parameter_name() {
        let param_names = vec!["a".to_string(), "b".to_string()];

        // Call with: func(x => 1, b => "hello") - ERROR
        let args = vec![lit(1), lit("hello")];
        let arg_names = vec![
            Some(ArgumentName {
                value: "x".to_string(),
                is_quoted: false,
            }),
            Some(ArgumentName {
                value: "b".to_string(),
                is_quoted: false,
            }),
        ];

        let result = resolve_function_arguments(&param_names, args, arg_names);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Unknown parameter")
        );
    }

    #[test]
    fn test_duplicate_parameter_name() {
        let param_names = vec!["a".to_string(), "b".to_string()];

        // Call with: func(a => 1, a => 2) - ERROR
        let args = vec![lit(1), lit(2)];
        let arg_names = vec![
            Some(ArgumentName {
                value: "a".to_string(),
                is_quoted: false,
            }),
            Some(ArgumentName {
                value: "a".to_string(),
                is_quoted: false,
            }),
        ];

        let result = resolve_function_arguments(&param_names, args, arg_names);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("specified multiple times")
        );
    }

    #[test]
    fn test_missing_required_parameter() {
        let param_names = vec!["a".to_string(), "b".to_string(), "c".to_string()];

        // Call with: func(a => 1, c => 3.0) - missing 'b'
        let args = vec![lit(1), lit(3.0)];
        let arg_names = vec![
            Some(ArgumentName {
                value: "a".to_string(),
                is_quoted: false,
            }),
            Some(ArgumentName {
                value: "c".to_string(),
                is_quoted: false,
            }),
        ];

        let result = resolve_function_arguments(&param_names, args, arg_names);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Missing required parameter")
        );
    }

    #[test]
    fn test_mixed_case_signature_unquoted_matching() {
        // Test with mixed-case signature parameters (lowercase, camelCase, UPPERCASE)
        // This proves case-insensitive matching works for unquoted identifiers
        let param_names = vec![
            "prefix".to_string(),   // lowercase
            "startPos".to_string(), // camelCase
            "LENGTH".to_string(),   // UPPERCASE
        ];

        // Test 1: All lowercase unquoted arguments should match
        let args1 = vec![lit("a"), lit(1), lit(5)];
        let arg_names1 = vec![
            Some(ArgumentName {
                value: "prefix".to_string(),
                is_quoted: false,
            }),
            Some(ArgumentName {
                value: "startpos".to_string(), // lowercase version of startPos
                is_quoted: false,
            }),
            Some(ArgumentName {
                value: "length".to_string(), // lowercase version of LENGTH
                is_quoted: false,
            }),
        ];

        let result1 =
            resolve_function_arguments(&param_names, args1, arg_names1).unwrap();
        assert_eq!(result1.len(), 3);
        assert_eq!(result1[0], lit("a"));
        assert_eq!(result1[1], lit(1));
        assert_eq!(result1[2], lit(5));

        // Test 2: All uppercase unquoted arguments should match
        let args2 = vec![lit("b"), lit(2), lit(10)];
        let arg_names2 = vec![
            Some(ArgumentName {
                value: "PREFIX".to_string(), // uppercase version of prefix
                is_quoted: false,
            }),
            Some(ArgumentName {
                value: "STARTPOS".to_string(), // uppercase version of startPos
                is_quoted: false,
            }),
            Some(ArgumentName {
                value: "LENGTH".to_string(), // matches UPPERCASE
                is_quoted: false,
            }),
        ];

        let result2 =
            resolve_function_arguments(&param_names, args2, arg_names2).unwrap();
        assert_eq!(result2.len(), 3);
        assert_eq!(result2[0], lit("b"));
        assert_eq!(result2[1], lit(2));
        assert_eq!(result2[2], lit(10));

        // Test 3: Mixed case unquoted arguments should match
        let args3 = vec![lit("c"), lit(3), lit(15)];
        let arg_names3 = vec![
            Some(ArgumentName {
                value: "Prefix".to_string(), // Title case
                is_quoted: false,
            }),
            Some(ArgumentName {
                value: "StartPos".to_string(), // matches camelCase
                is_quoted: false,
            }),
            Some(ArgumentName {
                value: "Length".to_string(), // Title case
                is_quoted: false,
            }),
        ];

        let result3 =
            resolve_function_arguments(&param_names, args3, arg_names3).unwrap();
        assert_eq!(result3.len(), 3);
        assert_eq!(result3[0], lit("c"));
        assert_eq!(result3[1], lit(3));
        assert_eq!(result3[2], lit(15));
    }

    #[test]
    fn test_mixed_case_signature_quoted_matching() {
        // Test that quoted identifiers require exact case match with signature
        let param_names = vec![
            "prefix".to_string(),   // lowercase
            "startPos".to_string(), // camelCase
            "LENGTH".to_string(),   // UPPERCASE
        ];

        // Test 1: Quoted with wrong case should fail for "prefix"
        let args_wrong_prefix = vec![lit("a"), lit(1), lit(5)];
        let arg_names_wrong_prefix = vec![
            Some(ArgumentName {
                value: "PREFIX".to_string(), // Wrong case
                is_quoted: true,
            }),
            Some(ArgumentName {
                value: "startPos".to_string(),
                is_quoted: true,
            }),
            Some(ArgumentName {
                value: "LENGTH".to_string(),
                is_quoted: true,
            }),
        ];

        let result = resolve_function_arguments(
            &param_names,
            args_wrong_prefix,
            arg_names_wrong_prefix,
        );
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Unknown parameter")
        );

        // Test 2: Quoted with wrong case should fail for "startPos"
        let args_wrong_startpos = vec![lit("a"), lit(1), lit(5)];
        let arg_names_wrong_startpos = vec![
            Some(ArgumentName {
                value: "prefix".to_string(),
                is_quoted: true,
            }),
            Some(ArgumentName {
                value: "STARTPOS".to_string(), // Wrong case
                is_quoted: true,
            }),
            Some(ArgumentName {
                value: "LENGTH".to_string(),
                is_quoted: true,
            }),
        ];

        let result2 = resolve_function_arguments(
            &param_names,
            args_wrong_startpos,
            arg_names_wrong_startpos,
        );
        assert!(result2.is_err());
        assert!(
            result2
                .unwrap_err()
                .to_string()
                .contains("Unknown parameter")
        );

        // Test 3: Quoted with wrong case should fail for "LENGTH"
        let args_wrong_length = vec![lit("a"), lit(1), lit(5)];
        let arg_names_wrong_length = vec![
            Some(ArgumentName {
                value: "prefix".to_string(),
                is_quoted: true,
            }),
            Some(ArgumentName {
                value: "startPos".to_string(),
                is_quoted: true,
            }),
            Some(ArgumentName {
                value: "length".to_string(), // Wrong case
                is_quoted: true,
            }),
        ];

        let result3 = resolve_function_arguments(
            &param_names,
            args_wrong_length,
            arg_names_wrong_length,
        );
        assert!(result3.is_err());
        assert!(
            result3
                .unwrap_err()
                .to_string()
                .contains("Unknown parameter")
        );

        // Test 4: Quoted with exact case should succeed
        let args_correct = vec![lit("a"), lit(1), lit(5)];
        let arg_names_correct = vec![
            Some(ArgumentName {
                value: "prefix".to_string(), // Exact match
                is_quoted: true,
            }),
            Some(ArgumentName {
                value: "startPos".to_string(), // Exact match
                is_quoted: true,
            }),
            Some(ArgumentName {
                value: "LENGTH".to_string(), // Exact match
                is_quoted: true,
            }),
        ];

        let result4 =
            resolve_function_arguments(&param_names, args_correct, arg_names_correct)
                .unwrap();
        assert_eq!(result4.len(), 3);
        assert_eq!(result4[0], lit("a"));
        assert_eq!(result4[1], lit(1));
        assert_eq!(result4[2], lit(5));
    }
}