Skip to main content

rudb_functions/
table.rs

1//! What a table function call resolves to.
2//!
3//! A table function is a function written where a table goes, so `FROM range(10)` produces ten rows
4//! of one column the same way `FROM t` produces whatever is in `t`. That makes it a different
5//! resolution problem from [`crate::signature`]: the answer is not a return type, it is a list of
6//! columns, because the caller can alias them and select from them and join against them.
7//!
8//! Five of them are here. `range` and `generate_series` between them account for two thousand
9//! records in DuckDB's `sqllogictest` corpus, because a test that needs a thousand rows should not
10//! have to write a thousand rows, and the corpus uses them the way a person uses a for loop. The
11//! difference between those two is one row: `range` stops before the end and `generate_series`
12//! stops on it, which is the difference between a half open interval and a closed one, and it is
13//! the only difference. Nothing else about them differs, including the name of the column, which is
14//! the function's own name in both cases.
15//!
16//! `read_parquet` and `read_csv` are the other two and they are a different kind of thing, because
17//! their columns are in the file rather than in this table. That is what [`Columns`] exists to say.
18//! A caller that resolves one of those has to open the file to finish resolving it, and
19//! [`crate::file`] is where that happens. For CSV there is nothing in the file that states the
20//! columns either, so opening it means sniffing it.
21//!
22//! `rudb_strategies()` is the fifth and it is not a DuckDB function. It lists every seam in the
23//! engine and every implementation registered against it, which is how a reader finds out what this
24//! engine will let them swap and what it lets them swap today. It takes no arguments and its
25//! columns are fixed, so resolving it is the simplest case in this file.
26
27use rudb_common::{Error, Field, LogicalType, Result};
28
29/// Which table function a call resolved to.
30///
31/// An enum rather than a name, because the executor dispatches on this and a string comparison per
32/// operator build is a string comparison that can be spelled wrong.
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum TableFunction {
35    /// `range(stop)`, `range(start, stop)`, `range(start, stop, step)`, stopping before the end.
36    Range,
37    /// The same three, stopping on the end.
38    GenerateSeries,
39    /// `read_parquet(path)`, the rows of a Parquet file.
40    ReadParquet,
41    /// `read_csv(path)`, the rows of a CSV file, with everything about how it is written sniffed.
42    ReadCsv,
43    /// `rudb_strategies()`, every seam and every implementation registered against it.
44    RudbStrategies,
45}
46
47impl TableFunction {
48    /// The name the plan records and an error message says.
49    #[must_use]
50    pub const fn name(self) -> &'static str {
51        match self {
52            Self::Range => "range",
53            Self::GenerateSeries => "generate_series",
54            Self::ReadParquet => "read_parquet",
55            Self::ReadCsv => "read_csv",
56            Self::RudbStrategies => "rudb_strategies",
57        }
58    }
59
60    /// Whether the last value is produced.
61    ///
62    /// Only the two series functions differ here. The file readers answer false and nothing asks
63    /// them.
64    #[must_use]
65    pub const fn inclusive(self) -> bool {
66        matches!(self, Self::GenerateSeries)
67    }
68
69    /// The named parameters the call takes, and the type each one wants.
70    ///
71    /// This is the list rudb acts on and not the list DuckDB prints, and the difference is worth
72    /// being plain about. `read_parquet` there takes seventeen named parameters and `read_csv`
73    /// takes around thirty. One of the Parquet ones is on the critical path, since the ClickBench
74    /// entry reads its file with `binary_as_string=True` and without it every string column in
75    /// `hits.parquet` comes back as `BLOB`, and the other sixteen have no caller here yet. A
76    /// parameter that is listed is one that does something, so this list grows as they land rather
77    /// than accepting names and ignoring them, which is the failure mode that makes an option look
78    /// supported when it is not.
79    ///
80    /// The CSV ones here are the ones that say how the file is written, which are the ones where
81    /// guessing wrong changes the answer rather than the speed. `sep` is DuckDB's other name for
82    /// `delim` and is a separate row rather than an alias, because the list is also what the
83    /// candidates on a misspelling are read out of and the binary prints both of them.
84    #[must_use]
85    pub fn parameters(self) -> &'static [(&'static str, LogicalType)] {
86        static READ_PARQUET: &[(&str, LogicalType)] = &[("binary_as_string", LogicalType::Boolean)];
87        static READ_CSV: &[(&str, LogicalType)] = &[
88            ("all_varchar", LogicalType::Boolean),
89            ("delim", LogicalType::Varchar),
90            ("escape", LogicalType::Varchar),
91            ("header", LogicalType::Boolean),
92            ("quote", LogicalType::Varchar),
93            ("sep", LogicalType::Varchar),
94        ];
95        match self {
96            Self::ReadParquet => READ_PARQUET,
97            Self::ReadCsv => READ_CSV,
98            _ => &[],
99        }
100    }
101
102    /// The function of that name, if there is one.
103    #[must_use]
104    pub fn lookup(name: &str) -> Option<Self> {
105        if name.eq_ignore_ascii_case("range") {
106            return Some(Self::Range);
107        }
108        if name.eq_ignore_ascii_case("generate_series") {
109            return Some(Self::GenerateSeries);
110        }
111        if name.eq_ignore_ascii_case("read_parquet") || name.eq_ignore_ascii_case("parquet_scan") {
112            return Some(Self::ReadParquet);
113        }
114        // `read_csv_auto` is the older spelling and DuckDB still answers to it. It meant sniffing
115        // back when `read_csv` did not sniff unless it was told to, and today they are the same
116        // function, which is why they are the same variant here.
117        if name.eq_ignore_ascii_case("read_csv") || name.eq_ignore_ascii_case("read_csv_auto") {
118            return Some(Self::ReadCsv);
119        }
120        if name.eq_ignore_ascii_case("rudb_strategies") {
121            return Some(Self::RudbStrategies);
122        }
123        None
124    }
125}
126
127/// Where a call's columns come from.
128///
129/// A table function that produces a fixed set of columns is resolved by this crate and nothing
130/// else has to be consulted. One that reads a file is not, because the columns are in the file, so
131/// the answer here is which file to open rather than what is in it. An enum rather than an empty
132/// column list, because an empty list is what `read_parquet` of a file with no columns would also
133/// give and a caller that forgot to handle the case would get an empty table instead of an error.
134#[derive(Debug, Clone, PartialEq, Eq)]
135pub enum Columns {
136    /// The columns this call produces, with the names an unaliased call gives them.
137    Fixed(Vec<Field>),
138    /// The columns of the Parquet file the first argument names.
139    Parquet,
140    /// The columns of the CSV file the first argument names, which are sniffed out of its front.
141    Csv,
142}
143
144/// A resolved table function call.
145#[derive(Debug, Clone, PartialEq, Eq)]
146pub struct ResolvedTable {
147    /// Which function.
148    pub function: TableFunction,
149    /// What each argument has to be cast to, the same length as what was passed in.
150    pub arguments: Vec<LogicalType>,
151    /// Where the columns the call produces come from.
152    pub columns: Columns,
153}
154
155/// Resolve a table function call by name and the types of its arguments.
156///
157/// The series pair does not consult the types, only the count, because it takes integers in every
158/// position and the binder casts to that, so there is nothing there for a type to choose between.
159/// DuckDB also has a timestamp and interval form of both, which is a second set of columns rather
160/// than a second overload of the same ones, and adding it means adding it rather than widening this.
161///
162/// The file readers do consult them, because DuckDB does. `read_parquet(3)` and `read_csv(3)` are
163/// binder errors there rather than reads of a file called `3`, which was measured against the binary
164/// rather than assumed, and it is the right answer: a path that arrived as a number is a query that
165/// meant something else.
166///
167/// # Errors
168///
169/// When no table function has that name, or when it has that name and not those arguments.
170pub fn resolve_table(name: &str, arguments: &[LogicalType]) -> Result<ResolvedTable> {
171    let Some(function) = TableFunction::lookup(name) else {
172        return Err(Error::catalog(format!("Table Function with name {name} does not exist!")));
173    };
174    if let Some(columns) = file_columns(function) {
175        // Two overloads, one path and a list of them, which is DuckDB's pair. The list is where
176        // `read_parquet(['a.parquet', 'b.parquet'])` binds, and an empty list arrives typed
177        // `INTEGER[]` there and here, so it lands on the no overload message rather than on a read
178        // of nothing.
179        let list = LogicalType::list(LogicalType::Varchar);
180        let single = arguments.len() == 1 && arguments[0] == LogicalType::Varchar;
181        let many = arguments.len() == 1 && arguments[0] == list;
182        // A bare null matches, and is a sentence about nulls rather than about overloads, which is
183        // what DuckDB answers `read_parquet(NULL)` with. It is left as a null rather than cast to a
184        // path so that the binder still has a null to recognise when it goes looking for the name.
185        let nothing = arguments.len() == 1 && arguments[0] == LogicalType::Null;
186        if !single && !many && !nothing {
187            return Err(no_overload(function, arguments));
188        }
189        let wanted = if many {
190            list
191        } else if nothing {
192            LogicalType::Null
193        } else {
194            LogicalType::Varchar
195        };
196        return Ok(ResolvedTable { function, arguments: vec![wanted], columns });
197    }
198    let arity = arguments.len();
199    if function == TableFunction::RudbStrategies {
200        if arity != 0 {
201            return Err(Error::binder(format!(
202                "Table function rudb_strategies() takes no arguments, {arity} were given"
203            )));
204        }
205        return Ok(ResolvedTable {
206            function,
207            arguments: Vec::new(),
208            columns: Columns::Fixed(strategy_fields()),
209        });
210    }
211    if !(1..=3).contains(&arity) {
212        return Err(Error::binder(format!(
213            "Table function {}() takes between 1 and 3 arguments, {arity} were given",
214            function.name()
215        )));
216    }
217    Ok(ResolvedTable {
218        function,
219        arguments: vec![LogicalType::BigInt; arity],
220        columns: Columns::Fixed(vec![Field::new(function.name(), LogicalType::BigInt)]),
221    })
222}
223
224/// Where a file reading table function's columns come from, and `None` for one that does not read
225/// a file.
226fn file_columns(function: TableFunction) -> Option<Columns> {
227    match function {
228        TableFunction::ReadParquet => Some(Columns::Parquet),
229        TableFunction::ReadCsv => Some(Columns::Csv),
230        TableFunction::Range | TableFunction::GenerateSeries | TableFunction::RudbStrategies => {
231            None
232        }
233    }
234}
235
236/// The columns `rudb_strategies()` produces.
237///
238/// Named here rather than in the executor because the binder resolves the call and the executor
239/// fills it, and a table whose two halves disagree about its own columns is a bug that shows up as
240/// a wrong answer rather than as a compile error.
241///
242/// Nine columns and every one of them earns its place at a seam that has no implementations yet,
243/// which is twenty six of the twenty seven today. `seam`, `milestone` and `seam_description` say
244/// what the seam is and which milestone owes it its first two implementations, and they are filled
245/// whether or not anything is registered. The other six describe an implementation and are null
246/// when there is none, which is how the table says that a seam is planned rather than built without
247/// anybody having to read a design document to find out.
248#[must_use]
249pub fn strategy_fields() -> Vec<Field> {
250    vec![
251        Field::new("seam", LogicalType::Varchar),
252        Field::new("milestone", LogicalType::Varchar),
253        Field::new("seam_description", LogicalType::Varchar),
254        Field::new("implementation", LogicalType::Varchar),
255        Field::new("implementation_description", LogicalType::Varchar),
256        Field::new("provenance", LogicalType::Varchar),
257        Field::new("determinism", LogicalType::Varchar),
258        Field::new("is_reference", LogicalType::Boolean),
259        Field::new("is_default", LogicalType::Boolean),
260    ]
261}
262
263/// DuckDB's message for a call that matched a name and no overload of it.
264///
265/// The candidate list it prints carries fifteen named parameters that none of them accept here, so
266/// what is listed is the two overloads that exist. The first line is the one a test in the wild
267/// asserts on and it is reproduced exactly.
268fn no_overload(function: TableFunction, arguments: &[LogicalType]) -> Error {
269    let written: Vec<String> = arguments.iter().map(ToString::to_string).collect();
270    let name = function.name();
271    Error::binder(format!(
272        "No function matches the given name and argument types '{name}({})'. You might need to \
273         add explicit type casts.\n\tCandidate functions:\n\t{name}(VARCHAR)\n\t{name}(VARCHAR[])\n",
274        written.join(", ")
275    ))
276}
277
278/// The values `start`, `stop` and `step` produce, in order.
279///
280/// Whole rather than an iterator because the caller wants them in a vector to build a vector out
281/// of, and because the count is known up front, which is what keeps a three million row `range`
282/// from growing a `Vec` twenty times on the way there.
283///
284/// A step of zero is an error and is the one case that is not simply an empty result. Everything
285/// else that produces nothing produces nothing: a start past a stop with a positive step, a start
286/// before a stop with a negative one, and the two of them equal under `range`.
287///
288/// # Errors
289///
290/// When the step is zero, with DuckDB's own wording.
291pub fn series(function: TableFunction, start: i64, stop: i64, step: i64) -> Result<Vec<i64>> {
292    let count = series_length(function, start, stop, step)?;
293    let mut out = Vec::with_capacity(count);
294    let mut at = start;
295    for _ in 0..count {
296        out.push(at);
297        // The count was worked out from the same three numbers, so this cannot pass the stop, and
298        // a saturating add is what keeps a step near the end of the range from wrapping into a
299        // value on the wrong side of it rather than stopping.
300        at = at.saturating_add(step);
301    }
302    Ok(out)
303}
304
305/// How many values the series has, without producing any of them.
306///
307/// The executor wants this and not the values. `range(100000000)` is a hundred row chunks a
308/// hundred thousand times over, and building the whole run first to find out how long it is would
309/// be eight hundred megabytes for a query whose answer is one number.
310///
311/// This is also where the step is checked, so the check happens once rather than in each of the
312/// two callers.
313///
314/// # Errors
315///
316/// When the step is zero, with DuckDB's own wording.
317pub fn series_length(function: TableFunction, start: i64, stop: i64, step: i64) -> Result<usize> {
318    if step == 0 {
319        return Err(Error::binder("interval cannot be 0!"));
320    }
321    Ok(length(function, start, stop, step))
322}
323
324/// How many values the series has.
325///
326/// In `i128` because `range(-9223372036854775808, 9223372036854775807)` is a legal call whose
327/// length does not fit in an `i64`, and a length that overflows into a negative is a `Vec` capacity
328/// that panics rather than a query that fails.
329fn length(function: TableFunction, start: i64, stop: i64, step: i64) -> usize {
330    let start = i128::from(start);
331    let stop = i128::from(stop);
332    let step = i128::from(step);
333    let span = if function.inclusive() {
334        if step > 0 { stop - start + 1 } else { stop - start - 1 }
335    } else {
336        stop - start
337    };
338    if (span > 0) != (step > 0) {
339        return 0;
340    }
341    // Rounding away from zero, since a span of five over a step of two is three values and not two.
342    let count = (span + step - step.signum()) / step;
343    usize::try_from(count).unwrap_or(usize::MAX)
344}
345
346#[cfg(test)]
347mod tests {
348    use super::*;
349
350    /// The fixed columns of a resolved call, which every function that does not read a file has.
351    fn fixed(resolved: &ResolvedTable) -> &[Field] {
352        match &resolved.columns {
353            Columns::Fixed(fields) => fields,
354            Columns::Parquet | Columns::Csv => {
355                panic!("{} resolves to a file", resolved.function.name())
356            }
357        }
358    }
359
360    /// A call of `count` integer arguments, which is what every series call looks like.
361    fn integers(count: usize) -> Vec<LogicalType> {
362        vec![LogicalType::BigInt; count]
363    }
364
365    #[test]
366    fn a_name_that_is_not_a_table_function_says_so_rather_than_binding() {
367        let error = resolve_table("read_csv", &integers(1)).unwrap_err();
368        assert!(error.to_string().contains("read_csv"), "{error}");
369    }
370
371    #[test]
372    fn both_names_resolve_and_each_one_names_its_own_column() {
373        let range = resolve_table("range", &integers(1)).unwrap();
374        assert_eq!(fixed(&range)[0].name, "range");
375        let series = resolve_table("GENERATE_SERIES", &integers(3)).unwrap();
376        assert_eq!(fixed(&series)[0].name, "generate_series");
377        assert_eq!(series.arguments.len(), 3);
378    }
379
380    #[test]
381    fn no_arguments_and_four_arguments_are_both_the_arity_error() {
382        assert!(resolve_table("range", &integers(0)).is_err());
383        assert!(resolve_table("range", &integers(4)).is_err());
384    }
385
386    #[test]
387    fn a_series_call_ignores_the_types_it_was_given_and_casts_them_all_to_bigint() {
388        let resolved =
389            resolve_table("range", &[LogicalType::Varchar, LogicalType::Double]).unwrap();
390        assert_eq!(resolved.arguments, integers(2));
391    }
392
393    #[test]
394    fn read_parquet_takes_one_string_and_says_its_columns_are_in_the_file() {
395        let resolved = resolve_table("read_parquet", &[LogicalType::Varchar]).unwrap();
396        assert_eq!(resolved.function, TableFunction::ReadParquet);
397        assert_eq!(resolved.arguments, vec![LogicalType::Varchar]);
398        assert_eq!(resolved.columns, Columns::Parquet);
399    }
400
401    #[test]
402    fn parquet_scan_is_the_same_function_under_duckdbs_other_name_for_it() {
403        assert_eq!(TableFunction::lookup("parquet_scan"), Some(TableFunction::ReadParquet));
404        // And it records itself under the one name, so a plan does not have two spellings in it.
405        let resolved = resolve_table("parquet_scan", &[LogicalType::Varchar]).unwrap();
406        assert_eq!(resolved.function.name(), "read_parquet");
407    }
408
409    #[test]
410    fn a_path_that_is_not_a_string_is_the_message_duckdb_gives_for_it() {
411        // Measured against v1.4.1 on server3: `read_parquet(3)` does not cast, it fails to match.
412        let error = resolve_table("read_parquet", &[LogicalType::Integer]).unwrap_err();
413        assert!(
414            error.message().starts_with(
415                "No function matches the given name and argument types 'read_parquet(INTEGER)'."
416            ),
417            "{error}"
418        );
419        assert!(error.message().contains("read_parquet(VARCHAR)"), "{error}");
420    }
421
422    #[test]
423    fn read_parquet_of_no_arguments_or_two_is_the_same_no_overload_message() {
424        let two = resolve_table("read_parquet", &[LogicalType::Varchar, LogicalType::Varchar]);
425        assert!(two.unwrap_err().message().contains("read_parquet(VARCHAR, VARCHAR)"));
426        let none = resolve_table("read_parquet", &[]);
427        assert!(none.unwrap_err().message().contains("read_parquet()"));
428    }
429
430    #[test]
431    fn range_stops_before_the_end_and_generate_series_stops_on_it() {
432        assert_eq!(series(TableFunction::Range, 0, 3, 1).unwrap(), vec![0, 1, 2]);
433        assert_eq!(series(TableFunction::GenerateSeries, 0, 3, 1).unwrap(), vec![0, 1, 2, 3]);
434    }
435
436    #[test]
437    fn a_step_that_does_not_divide_the_span_stops_before_the_end_of_it() {
438        // DuckDB gives 2, 4, 6 for both of these. The seven is not reached by either, which is
439        // where the two functions stop being different.
440        assert_eq!(series(TableFunction::Range, 2, 7, 2).unwrap(), vec![2, 4, 6]);
441        assert_eq!(series(TableFunction::GenerateSeries, 2, 7, 2).unwrap(), vec![2, 4, 6]);
442    }
443
444    #[test]
445    fn a_negative_step_counts_down_and_stops_on_the_same_rule() {
446        assert_eq!(series(TableFunction::Range, 5, 1, -2).unwrap(), vec![5, 3]);
447        assert_eq!(series(TableFunction::GenerateSeries, 5, 1, -2).unwrap(), vec![5, 3, 1]);
448    }
449
450    #[test]
451    fn a_step_going_the_wrong_way_produces_nothing_rather_than_running_forever() {
452        assert!(series(TableFunction::Range, 0, 10, -1).unwrap().is_empty());
453        assert!(series(TableFunction::Range, 10, 0, 1).unwrap().is_empty());
454    }
455
456    #[test]
457    fn an_empty_range_and_a_single_value_series_are_the_boundary_between_the_two() {
458        assert!(series(TableFunction::Range, 4, 4, 1).unwrap().is_empty());
459        assert_eq!(series(TableFunction::GenerateSeries, 4, 4, 1).unwrap(), vec![4]);
460    }
461
462    #[test]
463    fn a_step_of_zero_is_the_one_case_that_is_an_error_rather_than_nothing() {
464        let error = series(TableFunction::Range, 1, 5, 0).unwrap_err();
465        assert!(error.to_string().contains("interval cannot be 0"), "{error}");
466    }
467
468    #[test]
469    fn a_span_that_does_not_fit_in_an_i64_does_not_overflow_the_length() {
470        // Not run, only counted. The point is that the count is worked out in i128, so this comes
471        // out as a huge number rather than as a negative one that becomes a capacity panic.
472        assert_eq!(length(TableFunction::Range, i64::MIN, i64::MAX, 1), usize::MAX);
473    }
474
475    #[test]
476    fn rudb_strategies_takes_no_arguments_and_produces_a_fixed_table() {
477        let resolved = resolve_table("rudb_strategies", &[]).unwrap();
478        assert_eq!(resolved.function, TableFunction::RudbStrategies);
479        assert!(resolved.arguments.is_empty());
480        assert_eq!(fixed(&resolved), strategy_fields());
481    }
482
483    #[test]
484    fn rudb_strategies_with_an_argument_says_it_takes_none() {
485        let error = resolve_table("rudb_strategies", &[LogicalType::BigInt]).unwrap_err();
486        assert!(error.to_string().contains("takes no arguments"), "{error}");
487    }
488}