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