rudb_functions/functioncatalog.rs
1//! What `duckdb_functions()` says about each function this engine knows.
2//!
3//! Twenty one columns and one row per name per argument count, over the scalar and aggregate names
4//! in [`crate::signature`] and the table functions in [`crate::table`]. It is the same kind of table
5//! as `duckdb_types()`: a client reads it to find out what the engine supports, so it lists what the
6//! engine has rather than what the pinned binary has.
7//!
8//! # An overload here is a name and a count, not a name and a pair of types
9//!
10//! This is the one place where rudb's table and upstream's are shaped differently rather than just
11//! different lengths, and it follows from a decision [`crate::signature`] made first. That table
12//! resolves by shape: `+` is one entry saying both arguments promote and the result is what they
13//! promote to. Upstream carries an entry per pair of argument types, because it carries an
14//! implementation per pair, so it reports 44 rows for `+` naming concrete types where this reports
15//! two, one per arity.
16//!
17//! So the types in this table are declared types. `T` is the type variable and means the call
18//! decides, and every argument spelled `T` in one row is the same type as the others. `ANY` is the
19//! weaker one and means the argument is not tied to the others, which is what `count(x)` takes. Both
20//! spellings are upstream's own, which uses `T` for `list_extract` and `lag` and `ANY` for `least`,
21//! so a client that already reads this table does not have to learn a third vocabulary. A return of
22//! `ANY` means the arguments decide it in a way no name can say, which is where `sum` is, since it
23//! promotes and then widens an integer to the accumulator.
24//!
25//! # Builtins are in `system.main` and rudb has no catalog called that
26//!
27//! Said plainly because it is the one column here that names something that does not exist yet.
28//! Upstream puts every builtin in `system.main` and `system.pg_catalog` and puts nothing in
29//! `memory`, which is the opposite of `duckdb_types()`, where the types are repeated once per
30//! catalog. Reporting `memory` here would break every client query that filters on the schema and
31//! would say the functions belong to a database, which is not true of a builtin. So this says
32//! `system.main`. The catalog tables have landed since and the catalog still has no `system` entry,
33//! so `duckdb_schemas()` cannot return the name this column reports. That is #607 rather than a
34//! thing this file can fix, because the entry has to come from the catalog and not from here.
35//!
36//! `function_oid` is null for the same reason `database_oid` is null in `duckdb_types()`: upstream's
37//! is a counter its catalog handed out at startup and rudb has no oid space. `description`,
38//! `comment`, `examples` and `categories` are null because rudb has no documentation strings
39//! attached to its functions, and inventing a sentence per name here would put the documentation
40//! somewhere nobody maintains it.
41//!
42//! # What the table does not have yet
43//!
44//! No window functions, because rudb has none. No macros, no pragma functions and no table macros,
45//! for the same reason. `has_side_effects` is false and `stability` is `CONSISTENT` on every scalar
46//! and aggregate row, because every function rudb has is a pure function of its arguments: there is
47//! no `random`, no `nextval` and no `now` in the table yet. A volatile one arrives with a row that
48//! says so rather than with this column quietly staying wrong, which is why it is derived from
49//! nothing and asserted in a test.
50
51use rudb_common::{Field, LogicalType};
52
53use crate::signature::{FunctionKind, FunctionRow, function_rows};
54use crate::table::TableFunction;
55
56/// What one row of `duckdb_functions()` says, before it is turned into values.
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct FunctionEntry {
59 /// The name as it is written in a query.
60 pub name: &'static str,
61 /// `scalar`, `aggregate` or `table`, which are the three kinds rudb has.
62 pub function_type: &'static str,
63 /// The name this one resolves to, and `None` for a name that is its own.
64 pub alias_of: Option<&'static str>,
65 /// What the call produces, and `None` for a table function, whose columns are not one type.
66 pub return_type: Option<&'static str>,
67 /// One name per argument, in order.
68 pub parameters: Vec<String>,
69 /// One type per argument, in order, the same length as `parameters`.
70 pub parameter_types: Vec<String>,
71 /// The type of the trailing variadic argument, for the names that take one.
72 pub varargs: Option<&'static str>,
73 /// Whether calling it twice can give two answers, and `None` for a table function, which is
74 /// where upstream leaves this column null.
75 pub has_side_effects: Option<bool>,
76 /// How much the engine may reuse a result, and `None` for a table function.
77 pub stability: Option<&'static str>,
78}
79
80/// The catalog builtins are reported as belonging to, which is upstream's name for it.
81pub const FUNCTION_CATALOG: &str = "system";
82
83/// The schema builtins are reported as belonging to.
84pub const FUNCTION_SCHEMA: &str = "main";
85
86/// The stability every function in this engine has, since none of them is volatile yet.
87pub const CONSISTENT: &str = "CONSISTENT";
88
89/// The columns `duckdb_functions()` produces, which is DuckDB's twenty one.
90#[must_use]
91pub fn function_fields() -> Vec<Field> {
92 vec![
93 Field::new("database_name", LogicalType::Varchar),
94 // A varchar and not a bigint, which looks like a mistake upstream and is reproduced because
95 // a client that reads the column reads whatever type it was handed. It is null on every row
96 // there, so nothing has ever had to parse it.
97 Field::new("database_oid", LogicalType::Varchar),
98 Field::new("schema_name", LogicalType::Varchar),
99 Field::new("function_name", LogicalType::Varchar),
100 Field::new("alias_of", LogicalType::Varchar),
101 Field::new("function_type", LogicalType::Varchar),
102 Field::new("description", LogicalType::Varchar),
103 Field::new("comment", LogicalType::Varchar),
104 Field::new("tags", LogicalType::map(LogicalType::Varchar, LogicalType::Varchar)),
105 Field::new("return_type", LogicalType::Varchar),
106 Field::new("parameters", LogicalType::list(LogicalType::Varchar)),
107 Field::new("parameter_types", LogicalType::list(LogicalType::Varchar)),
108 Field::new("varargs", LogicalType::Varchar),
109 Field::new("macro_definition", LogicalType::Varchar),
110 Field::new("has_side_effects", LogicalType::Boolean),
111 Field::new("internal", LogicalType::Boolean),
112 Field::new("extension_name", LogicalType::Varchar),
113 Field::new("function_oid", LogicalType::BigInt),
114 Field::new("examples", LogicalType::list(LogicalType::Varchar)),
115 Field::new("stability", LogicalType::Varchar),
116 Field::new("categories", LogicalType::list(LogicalType::Varchar)),
117 ]
118}
119
120/// Every function this engine has, sorted by name and then by how many arguments it takes.
121///
122/// Sorted rather than left in whatever order the two tables behind it are written in, because a
123/// client reading this table is looking a name up and an unsorted catalog makes that a scan of the
124/// whole thing. Upstream's own order is not reproduced: it is the order its catalog registered the
125/// functions in, the two corpus records that read the table both say `order by`, and there is
126/// nothing in it that is a fact about the language.
127#[must_use]
128pub fn function_entries() -> Vec<FunctionEntry> {
129 let mut entries: Vec<FunctionEntry> = function_rows().into_iter().map(scalar).collect();
130 entries.extend(tables());
131 entries.sort_by(|left, right| {
132 left.name.cmp(right.name).then(left.parameters.len().cmp(&right.parameters.len()))
133 });
134 entries
135}
136
137/// One scalar or aggregate overload, as a row.
138fn scalar(row: FunctionRow) -> FunctionEntry {
139 FunctionEntry {
140 name: row.name,
141 function_type: match row.kind {
142 FunctionKind::Scalar => "scalar",
143 FunctionKind::Aggregate => "aggregate",
144 },
145 alias_of: row.alias_of,
146 return_type: Some(row.returns),
147 parameters: named(row.alias_of.unwrap_or(row.name), row.types.len()),
148 parameter_types: row.types.iter().map(|name| (*name).to_string()).collect(),
149 varargs: row.varargs,
150 has_side_effects: Some(false),
151 stability: Some(CONSISTENT),
152 }
153}
154
155/// Every table function, one row per argument count it takes.
156///
157/// A table function's named parameters go on the end of `parameters` after its positional ones,
158/// which is upstream's shape: its `read_csv` row is `col0` followed by forty seven option names. So
159/// rudb's is `col0` followed by the six options it acts on, and that list grows as they land rather
160/// than being padded out to upstream's length with names nothing reads.
161fn tables() -> Vec<FunctionEntry> {
162 let mut entries = Vec::new();
163 for function in TABLE_FUNCTIONS {
164 for count in positional_counts(*function) {
165 let mut parameters = positional(count);
166 let mut parameter_types = vec![positional_type(*function).to_string(); count];
167 for (name, ty) in function.parameters() {
168 parameters.push((*name).to_string());
169 parameter_types.push(ty.to_string());
170 }
171 entries.push(FunctionEntry {
172 name: function.name(),
173 function_type: "table",
174 alias_of: None,
175 // Null, and upstream's is null too. A table function produces columns rather than a
176 // value, so there is no one type to name, and the columns are in `duckdb_columns()`
177 // for a table and in the file for a file reader.
178 return_type: None,
179 parameters,
180 parameter_types,
181 varargs: None,
182 has_side_effects: None,
183 stability: None,
184 });
185 }
186 }
187 for (alias, function) in TABLE_ALIASES {
188 let rows: Vec<FunctionEntry> = entries
189 .iter()
190 .filter(|entry| entry.name == function.name())
191 // `alias_of` stays null, which is upstream's answer for these two rather than an
192 // omission here: `parquet_scan` and `read_csv_auto` are separate registrations there and
193 // report as their own functions, where `len` and `mean` report as aliases.
194 .map(|entry| FunctionEntry { name: alias, ..entry.clone() })
195 .collect();
196 entries.extend(rows);
197 }
198 entries
199}
200
201/// The table functions, in no particular order, since [`function_entries`] sorts.
202const TABLE_FUNCTIONS: &[TableFunction] = &[
203 TableFunction::Range,
204 TableFunction::GenerateSeries,
205 TableFunction::ReadParquet,
206 TableFunction::ReadCsv,
207 TableFunction::RudbStrategies,
208 TableFunction::DuckdbKeywords,
209 TableFunction::DuckdbTypes,
210 TableFunction::DuckdbFunctions,
211 TableFunction::DuckdbSettings,
212 TableFunction::DuckdbDatabases,
213 TableFunction::DuckdbSchemas,
214 TableFunction::DuckdbTables,
215 TableFunction::DuckdbColumns,
216];
217
218/// The second name each of the two file readers answers to.
219const TABLE_ALIASES: &[(&str, TableFunction)] =
220 &[("parquet_scan", TableFunction::ReadParquet), ("read_csv_auto", TableFunction::ReadCsv)];
221
222/// How many positional arguments a table function takes, one count per row it produces.
223fn positional_counts(function: TableFunction) -> Vec<usize> {
224 match function {
225 TableFunction::Range | TableFunction::GenerateSeries => vec![1, 2, 3],
226 TableFunction::ReadParquet | TableFunction::ReadCsv => vec![1],
227 TableFunction::RudbStrategies
228 | TableFunction::DuckdbKeywords
229 | TableFunction::DuckdbTypes
230 | TableFunction::DuckdbFunctions
231 | TableFunction::DuckdbSettings
232 | TableFunction::DuckdbDatabases
233 | TableFunction::DuckdbSchemas
234 | TableFunction::DuckdbTables
235 | TableFunction::DuckdbColumns => vec![0],
236 }
237}
238
239/// The type a table function's positional arguments take.
240const fn positional_type(function: TableFunction) -> &'static str {
241 match function {
242 TableFunction::ReadParquet | TableFunction::ReadCsv => "VARCHAR",
243 _ => "BIGINT",
244 }
245}
246
247/// The names the first `count` arguments go by, which are upstream's for a function whose
248/// parameters have no names of their own.
249fn positional(count: usize) -> Vec<String> {
250 (0..count).map(|at| format!("col{at}")).collect()
251}
252
253/// The names one function's arguments go by, which is [`positional`] unless the function is in
254/// [`PARAMETER_NAMES`].
255fn named(name: &str, count: usize) -> Vec<String> {
256 match PARAMETER_NAMES.iter().find(|(entry, _)| *entry == name) {
257 Some((_, names)) if names.len() == count => {
258 names.iter().map(|name| (*name).to_string()).collect()
259 }
260 _ => positional(count),
261 }
262}
263
264/// The scalar functions whose arguments upstream gives real names rather than `col0`.
265///
266/// Short on purpose. Upstream names the arguments of a few dozen functions and leaves the rest as
267/// `col0`, and the ones it names are the ones where the name carries information a type does not:
268/// `regexp_replace(string, regex, replacement)` is three VARCHARs and the order is not guessable
269/// from that. `current_setting` is here because its error message names the parameter, so a row
270/// saying `col0` next to a message saying `setting_name` would be this table disagreeing with the
271/// binder about the same argument.
272///
273/// A row only applies at the argument count it has names for, so a function with two arities keeps
274/// `col0` at the arity this list does not cover rather than being given the wrong names.
275const PARAMETER_NAMES: &[(&str, &[&str])] = &[("current_setting", &["setting_name"])];
276
277#[cfg(test)]
278mod tests {
279 use super::{CONSISTENT, function_entries, function_fields};
280
281 #[test]
282 fn the_table_is_the_shape_the_pin_returns() {
283 assert_eq!(function_fields().len(), 21);
284 let entries = function_entries();
285 assert!(!entries.is_empty());
286 // Every row has as many parameter names as it has parameter types, which is the one thing a
287 // client reading the two columns together relies on and the one thing a table built out of
288 // two lists can get wrong.
289 for entry in &entries {
290 assert_eq!(
291 entry.parameters.len(),
292 entry.parameter_types.len(),
293 "{} takes {} names and {} types",
294 entry.name,
295 entry.parameters.len(),
296 entry.parameter_types.len()
297 );
298 }
299 }
300
301 #[test]
302 fn a_name_with_two_arities_is_two_rows_and_a_name_with_one_is_one() {
303 let entries = function_entries();
304 let rows = |name: &str| entries.iter().filter(|entry| entry.name == name).count();
305 // `+` is the unary and the binary form, so it is two rows here and 44 on the pin, which is
306 // the difference between resolving by shape and carrying an implementation per type pair.
307 assert_eq!(rows("+"), 2);
308 assert_eq!(rows("*"), 1);
309 // `substring` takes two arguments or three and not one, so the hole in the range is a hole
310 // in the table rather than a row that binds a call the engine refuses.
311 assert_eq!(rows("substring"), 2);
312 let substring: Vec<usize> = entries
313 .iter()
314 .filter(|entry| entry.name == "substring")
315 .map(|entry| entry.parameters.len())
316 .collect();
317 assert_eq!(substring, [2, 3]);
318 }
319
320 #[test]
321 fn an_alias_is_a_row_of_its_own_that_says_what_it_resolves_to() {
322 let entries = function_entries();
323 let len: Vec<&super::FunctionEntry> =
324 entries.iter().filter(|entry| entry.name == "len").collect();
325 assert_eq!(len.len(), 1);
326 assert_eq!(len[0].alias_of, Some("length"));
327 assert_eq!(len[0].return_type, Some("BIGINT"));
328 // The two file reader aliases report as their own functions and not as aliases, which is
329 // what the pin does with them.
330 let scan: Vec<&super::FunctionEntry> =
331 entries.iter().filter(|entry| entry.name == "parquet_scan").collect();
332 assert_eq!(scan.len(), 1);
333 assert_eq!(scan[0].alias_of, None);
334 assert_eq!(scan[0].function_type, "table");
335 }
336
337 #[test]
338 fn a_shape_that_promotes_is_declared_with_the_type_variable() {
339 let entries = function_entries();
340 let row = |name: &str, count: usize| {
341 entries
342 .iter()
343 .find(|entry| entry.name == name && entry.parameters.len() == count)
344 .unwrap_or_else(|| panic!("{name} of {count}"))
345 };
346 // Both arguments meet at one type and the result is that type.
347 assert_eq!(row("%", 2).parameter_types, ["T", "T"]);
348 assert_eq!(row("%", 2).return_type, Some("T"));
349 // Both arguments meet at one type and the result moves off it, because a decimal sum gains
350 // a carry digit, so the result is the weaker spelling.
351 assert_eq!(row("+", 2).parameter_types, ["T", "T"]);
352 assert_eq!(row("+", 2).return_type, Some("ANY"));
353 // The argument is not constrained at all and the result is fixed.
354 assert_eq!(row("count", 1).parameter_types, ["ANY"]);
355 assert_eq!(row("count", 1).return_type, Some("BIGINT"));
356 // A string function names the type it needs, because it refuses anything else rather than
357 // casting to it.
358 assert_eq!(row("lower", 1).parameter_types, ["VARCHAR"]);
359 assert_eq!(row("lower", 1).return_type, Some("VARCHAR"));
360 // A string and then a whole number that is not cast to one.
361 assert_eq!(row("substring", 3).parameter_types, ["VARCHAR", "BIGINT", "BIGINT"]);
362 }
363
364 #[test]
365 fn a_table_function_has_no_return_type_and_no_stability() {
366 let entries = function_entries();
367 let range: Vec<&super::FunctionEntry> =
368 entries.iter().filter(|entry| entry.name == "range").collect();
369 // One, two or three arguments, which is what the function takes and what the pin reports.
370 assert_eq!(range.len(), 3);
371 for entry in &range {
372 assert_eq!(entry.function_type, "table");
373 assert_eq!(entry.return_type, None);
374 assert_eq!(entry.stability, None);
375 assert_eq!(entry.has_side_effects, None);
376 }
377 // A file reader's named options go on the end of its positional argument, which is the
378 // shape the pin has and the reason `parameters` is longer than the call is.
379 let csv = entries
380 .iter()
381 .find(|entry| entry.name == "read_csv")
382 .expect("the csv reader is a table function");
383 assert_eq!(csv.parameters[0], "col0");
384 assert_eq!(csv.parameter_types[0], "VARCHAR");
385 assert_eq!(
386 csv.parameters[1..],
387 ["all_varchar", "delim", "escape", "header", "quote", "sep"]
388 );
389 }
390
391 /// The one scalar whose argument has a name, and the reason it needs one.
392 #[test]
393 fn a_setting_is_read_by_an_argument_the_table_names() {
394 let entry = function_entries()
395 .into_iter()
396 .find(|entry| entry.name == "current_setting")
397 .expect("a row for it");
398 assert_eq!(entry.function_type, "scalar");
399 assert_eq!(entry.parameters, ["setting_name"]);
400 assert_eq!(entry.parameter_types, ["VARCHAR"]);
401 assert_eq!(entry.return_type, Some("ANY"));
402 // Every other scalar keeps `col0`, so the list is an exception and not a new convention.
403 let lower = function_entries()
404 .into_iter()
405 .find(|entry| entry.name == "lower")
406 .expect("a row for it");
407 assert_eq!(lower.parameters, ["col0"]);
408 }
409
410 #[test]
411 fn nothing_in_this_engine_is_volatile_yet_and_the_table_says_so() {
412 // There is no `random`, no `nextval` and no `now` in the function table, so every scalar and
413 // aggregate row is consistent and has no side effects. The day one of those lands this test
414 // fails, which is the point: the column has to be given a real answer rather than inheriting
415 // one nobody looked at.
416 for entry in function_entries().iter().filter(|entry| entry.function_type != "table") {
417 assert_eq!(entry.stability, Some(CONSISTENT), "{}", entry.name);
418 assert_eq!(entry.has_side_effects, Some(false), "{}", entry.name);
419 }
420 }
421}