Skip to main content

datafusion_expr/logical_plan/
information_schema.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Schema and [`RecordBatch`] builders for the `information_schema` virtual
6//! tables and `SHOW` statements.
7
8use crate::TableType;
9use crate::registry::{ExtensionTypeRegistry, ExtensionTypeRegistryRef};
10use arrow::array::ArrayRef;
11use arrow::array::builder::{BooleanBuilder, StringBuilder, UInt8Builder, UInt64Builder};
12use arrow::datatypes::{DataType, Field, Schema, SchemaRef};
13use arrow::record_batch::RecordBatch;
14use datafusion_common::Result;
15use datafusion_common::config::ConfigEntry;
16use std::fmt::Write;
17use std::sync::Arc;
18
19/// Returns the Arrow schema of `information_schema.tables` rows.
20///
21/// Columns are based on <https://www.postgresql.org/docs/current/infoschema-tables.html>.
22pub fn tables_schema() -> Schema {
23    Schema::new(vec![
24        Field::new("table_catalog", DataType::Utf8, false),
25        Field::new("table_schema", DataType::Utf8, false),
26        Field::new("table_name", DataType::Utf8, false),
27        Field::new("table_type", DataType::Utf8, false),
28    ])
29}
30
31/// Builds `information_schema.tables` rows.
32#[derive(Debug)]
33pub struct InformationSchemaTablesBuilder {
34    schema: SchemaRef,
35    catalog_names: StringBuilder,
36    schema_names: StringBuilder,
37    table_names: StringBuilder,
38    table_types: StringBuilder,
39}
40
41impl Default for InformationSchemaTablesBuilder {
42    fn default() -> Self {
43        Self::new()
44    }
45}
46
47impl InformationSchemaTablesBuilder {
48    /// Construct an empty builder.
49    pub fn new() -> Self {
50        Self {
51            schema: Arc::new(tables_schema()),
52            catalog_names: StringBuilder::new(),
53            schema_names: StringBuilder::new(),
54            table_names: StringBuilder::new(),
55            table_types: StringBuilder::new(),
56        }
57    }
58
59    /// Append one row.
60    pub fn add_table(
61        &mut self,
62        catalog_name: impl AsRef<str>,
63        schema_name: impl AsRef<str>,
64        table_name: impl AsRef<str>,
65        table_type: TableType,
66    ) {
67        // Note: append_value is actually infallible.
68        self.catalog_names.append_value(catalog_name.as_ref());
69        self.schema_names.append_value(schema_name.as_ref());
70        self.table_names.append_value(table_name.as_ref());
71        self.table_types.append_value(match table_type {
72            TableType::Base => "BASE TABLE",
73            TableType::View => "VIEW",
74            TableType::Temporary => "LOCAL TEMPORARY",
75        });
76    }
77
78    /// Finalize the builder into a [`RecordBatch`].
79    pub fn finish(&mut self) -> RecordBatch {
80        RecordBatch::try_new(
81            Arc::clone(&self.schema),
82            vec![
83                Arc::new(self.catalog_names.finish()),
84                Arc::new(self.schema_names.finish()),
85                Arc::new(self.table_names.finish()),
86                Arc::new(self.table_types.finish()),
87            ],
88        )
89        .unwrap()
90    }
91}
92
93/// Returns the Arrow schema of `information_schema.views` rows.
94///
95/// Columns are based on <https://www.postgresql.org/docs/current/infoschema-views.html>.
96pub fn views_schema() -> Schema {
97    Schema::new(vec![
98        Field::new("table_catalog", DataType::Utf8, false),
99        Field::new("table_schema", DataType::Utf8, false),
100        Field::new("table_name", DataType::Utf8, false),
101        Field::new("definition", DataType::Utf8, true),
102    ])
103}
104
105/// Builds `information_schema.views` rows.
106#[derive(Debug)]
107pub struct InformationSchemaViewBuilder {
108    schema: SchemaRef,
109    catalog_names: StringBuilder,
110    schema_names: StringBuilder,
111    table_names: StringBuilder,
112    definitions: StringBuilder,
113}
114
115impl Default for InformationSchemaViewBuilder {
116    fn default() -> Self {
117        Self::new()
118    }
119}
120
121impl InformationSchemaViewBuilder {
122    /// Construct an empty builder.
123    pub fn new() -> Self {
124        Self {
125            schema: Arc::new(views_schema()),
126            catalog_names: StringBuilder::new(),
127            schema_names: StringBuilder::new(),
128            table_names: StringBuilder::new(),
129            definitions: StringBuilder::new(),
130        }
131    }
132
133    /// Append one row. `definition` is the statement that created the table, if known.
134    pub fn add_view(
135        &mut self,
136        catalog_name: impl AsRef<str>,
137        schema_name: impl AsRef<str>,
138        table_name: impl AsRef<str>,
139        definition: Option<&(impl AsRef<str> + ?Sized)>,
140    ) {
141        // Note: append_value is actually infallible.
142        self.catalog_names.append_value(catalog_name.as_ref());
143        self.schema_names.append_value(schema_name.as_ref());
144        self.table_names.append_value(table_name.as_ref());
145        self.definitions.append_option(definition.as_ref());
146    }
147
148    /// Finalize the builder into a [`RecordBatch`].
149    pub fn finish(&mut self) -> RecordBatch {
150        RecordBatch::try_new(
151            Arc::clone(&self.schema),
152            vec![
153                Arc::new(self.catalog_names.finish()),
154                Arc::new(self.schema_names.finish()),
155                Arc::new(self.table_names.finish()),
156                Arc::new(self.definitions.finish()),
157            ],
158        )
159        .unwrap()
160    }
161}
162
163/// Which subset of the `information_schema.columns` columns to produce.
164#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
165pub enum ColumnsDetail {
166    /// `column_name`, `data_type` and `is_nullable`, as output by `DESCRIBE`.
167    Describe,
168    /// [`Self::Describe`] plus the table's catalog, schema and name, as output
169    /// by `SHOW COLUMNS`.
170    Basic,
171    /// All columns, as output by `SHOW FULL COLUMNS` and `information_schema.columns`.
172    Full,
173}
174
175/// Returns the Arrow schema of `information_schema.columns` rows at the
176/// given [`ColumnsDetail`] level.
177///
178/// The `Full` columns are based on
179/// <https://www.postgresql.org/docs/current/infoschema-columns.html>.
180pub fn columns_schema(detail: ColumnsDetail) -> Schema {
181    match detail {
182        ColumnsDetail::Describe => Schema::new(vec![
183            Field::new("column_name", DataType::Utf8, false),
184            Field::new("data_type", DataType::Utf8, false),
185            Field::new("is_nullable", DataType::Utf8, false),
186        ]),
187        ColumnsDetail::Basic => Schema::new(vec![
188            Field::new("table_catalog", DataType::Utf8, false),
189            Field::new("table_schema", DataType::Utf8, false),
190            Field::new("table_name", DataType::Utf8, false),
191            Field::new("column_name", DataType::Utf8, false),
192            Field::new("data_type", DataType::Utf8, false),
193            Field::new("is_nullable", DataType::Utf8, false),
194        ]),
195        ColumnsDetail::Full => Schema::new(vec![
196            Field::new("table_catalog", DataType::Utf8, false),
197            Field::new("table_schema", DataType::Utf8, false),
198            Field::new("table_name", DataType::Utf8, false),
199            Field::new("column_name", DataType::Utf8, false),
200            Field::new("ordinal_position", DataType::UInt64, false),
201            Field::new("column_default", DataType::Utf8, true),
202            Field::new("is_nullable", DataType::Utf8, false),
203            Field::new("data_type", DataType::Utf8, false),
204            Field::new("character_maximum_length", DataType::UInt64, true),
205            Field::new("character_octet_length", DataType::UInt64, true),
206            Field::new("numeric_precision", DataType::UInt64, true),
207            Field::new("numeric_precision_radix", DataType::UInt64, true),
208            Field::new("numeric_scale", DataType::UInt64, true),
209            Field::new("datetime_precision", DataType::UInt64, true),
210            Field::new("interval_type", DataType::Utf8, true),
211        ]),
212    }
213}
214
215/// Builds `information_schema.columns` rows at a given [`ColumnsDetail`] level.
216#[derive(Debug)]
217pub struct InformationSchemaColumnsBuilder {
218    schema: SchemaRef,
219    detail: ColumnsDetail,
220    catalog_names: Option<StringBuilder>,
221    schema_names: Option<StringBuilder>,
222    table_names: Option<StringBuilder>,
223    column_names: StringBuilder,
224    ordinal_positions: Option<UInt64Builder>,
225    column_defaults: Option<StringBuilder>,
226    is_nullables: StringBuilder,
227    data_types: StringBuilder,
228    character_maximum_lengths: Option<UInt64Builder>,
229    character_octet_lengths: Option<UInt64Builder>,
230    numeric_precisions: Option<UInt64Builder>,
231    numeric_precision_radixes: Option<UInt64Builder>,
232    numeric_scales: Option<UInt64Builder>,
233    datetime_precisions: Option<UInt64Builder>,
234    interval_types: Option<StringBuilder>,
235    extension_types: Option<ExtensionTypeRegistryRef>,
236}
237
238impl InformationSchemaColumnsBuilder {
239    /// Construct an empty builder that will only retain the columns needed
240    /// for `detail`.
241    pub fn new(detail: ColumnsDetail) -> Self {
242        // StringBuilder requires providing an initial capacity, so
243        // pick 10 here arbitrarily as this is not performance
244        // critical code and the number of tables is unavailable here.
245        let default_capacity = 10;
246
247        let with_table_qualifiers =
248            matches!(detail, ColumnsDetail::Basic | ColumnsDetail::Full);
249        let full = detail == ColumnsDetail::Full;
250
251        Self {
252            schema: Arc::new(columns_schema(detail)),
253            detail,
254            catalog_names: with_table_qualifiers.then(StringBuilder::new),
255            schema_names: with_table_qualifiers.then(StringBuilder::new),
256            table_names: with_table_qualifiers.then(StringBuilder::new),
257            column_names: StringBuilder::new(),
258            ordinal_positions: full
259                .then(|| UInt64Builder::with_capacity(default_capacity)),
260            column_defaults: full.then(StringBuilder::new),
261            is_nullables: StringBuilder::new(),
262            data_types: StringBuilder::new(),
263            character_maximum_lengths: full
264                .then(|| UInt64Builder::with_capacity(default_capacity)),
265            character_octet_lengths: full
266                .then(|| UInt64Builder::with_capacity(default_capacity)),
267            numeric_precisions: full
268                .then(|| UInt64Builder::with_capacity(default_capacity)),
269            numeric_precision_radixes: full
270                .then(|| UInt64Builder::with_capacity(default_capacity)),
271            numeric_scales: full.then(|| UInt64Builder::with_capacity(default_capacity)),
272            datetime_precisions: full
273                .then(|| UInt64Builder::with_capacity(default_capacity)),
274            interval_types: full.then(StringBuilder::new),
275            extension_types: None,
276        }
277    }
278
279    /// Use the extension type registry to show the
280    /// [`display_name`](datafusion_common::types::DFExtensionType::display_name)
281    /// of registered extension types in `data_type`.
282    pub fn with_extension_type_registry(
283        mut self,
284        extension_types: Option<ExtensionTypeRegistryRef>,
285    ) -> Self {
286        self.extension_types = extension_types;
287        self
288    }
289
290    /// Append one row describing `field`. Values not needed at this builder's
291    /// detail level are discarded.
292    pub fn add_column(
293        &mut self,
294        catalog_name: &str,
295        schema_name: &str,
296        table_name: &str,
297        field_position: usize,
298        field: &Field,
299    ) {
300        use DataType::*;
301
302        // Note: append_value is actually infallible.
303        if let Some(b) = &mut self.catalog_names {
304            b.append_value(catalog_name);
305        }
306        if let Some(b) = &mut self.schema_names {
307            b.append_value(schema_name);
308        }
309        if let Some(b) = &mut self.table_names {
310            b.append_value(table_name);
311        }
312
313        self.column_names.append_value(field.name());
314
315        if let Some(b) = &mut self.ordinal_positions {
316            b.append_value(field_position as u64);
317        }
318
319        // DataFusion does not support column default values, so null
320        if let Some(b) = &mut self.column_defaults {
321            b.append_null();
322        }
323
324        // "YES if the column is possibly nullable, NO if it is known not nullable. "
325        let nullable_str = if field.is_nullable() { "YES" } else { "NO" };
326        self.is_nullables.append_value(nullable_str);
327
328        // "System supplied type" --> Use the display name of the extension type or the
329        // display format of the datatype
330        append_field_type_display_name(
331            self.extension_types.as_deref(),
332            field,
333            &mut self.data_types,
334        );
335
336        // "If data_type identifies a character or bit string type, the
337        // declared maximum length; null for all other data types or
338        // if no maximum length was declared."
339        //
340        // Arrow has no equivalent of VARCHAR(20), so we leave this as Null
341        if let Some(b) = &mut self.character_maximum_lengths {
342            b.append_option(None);
343        }
344
345        // "Maximum length, in bytes, for binary data, character data,
346        // or text and image data."
347        if let Some(b) = &mut self.character_octet_lengths {
348            let char_len: Option<u64> = match field.data_type() {
349                Utf8 | Binary => Some(i32::MAX as u64),
350                LargeBinary | LargeUtf8 => Some(i64::MAX as u64),
351                _ => None,
352            };
353            b.append_option(char_len);
354        }
355
356        // numeric_precision: "If data_type identifies a numeric type, this column
357        // contains the (declared or implicit) precision of the type
358        // for this column. The precision indicates the number of
359        // significant digits. It can be expressed in decimal (base
360        // 10) or binary (base 2) terms, as specified in the column
361        // numeric_precision_radix. For all other data types, this
362        // column is null."
363        //
364        // numeric_radix: If data_type identifies a numeric type, this
365        // column indicates in which base the values in the columns
366        // numeric_precision and numeric_scale are expressed. The
367        // value is either 2 or 10. For all other data types, this
368        // column is null.
369        //
370        // numeric_scale: If data_type identifies an exact numeric
371        // type, this column contains the (declared or implicit) scale
372        // of the type for this column. The scale indicates the number
373        // of significant digits to the right of the decimal point. It
374        // can be expressed in decimal (base 10) or binary (base 2)
375        // terms, as specified in the column
376        // numeric_precision_radix. For all other data types, this
377        // column is null.
378        if let (Some(precisions), Some(radixes), Some(scales)) = (
379            &mut self.numeric_precisions,
380            &mut self.numeric_precision_radixes,
381            &mut self.numeric_scales,
382        ) {
383            let (numeric_precision, numeric_radix, numeric_scale) =
384                match field.data_type() {
385                    Int8 | UInt8 => (Some(8), Some(2), None),
386                    Int16 | UInt16 => (Some(16), Some(2), None),
387                    Int32 | UInt32 => (Some(32), Some(2), None),
388                    // From max value of 65504 as explained on
389                    // https://en.wikipedia.org/wiki/Half-precision_floating-point_format#Exponent_encoding
390                    Float16 => (Some(15), Some(2), None),
391                    // Numbers from postgres `real` type
392                    Float32 => (Some(24), Some(2), None),
393                    // Numbers from postgres `double` type
394                    Float64 => (Some(24), Some(2), None),
395                    Decimal128(precision, scale) => {
396                        (Some(*precision as u64), Some(10), Some(*scale as u64))
397                    }
398                    _ => (None, None, None),
399                };
400
401            precisions.append_option(numeric_precision);
402            radixes.append_option(numeric_radix);
403            scales.append_option(numeric_scale);
404        }
405
406        if let Some(b) = &mut self.datetime_precisions {
407            b.append_option(None);
408        }
409        if let Some(b) = &mut self.interval_types {
410            b.append_null();
411        }
412    }
413
414    /// Finalize the builder into a [`RecordBatch`].
415    pub fn finish(&mut self) -> RecordBatch {
416        let mut columns: Vec<ArrayRef> = Vec::new();
417        if self.detail != ColumnsDetail::Describe {
418            columns.push(Arc::new(self.catalog_names.as_mut().unwrap().finish()));
419            columns.push(Arc::new(self.schema_names.as_mut().unwrap().finish()));
420            columns.push(Arc::new(self.table_names.as_mut().unwrap().finish()));
421        }
422        columns.push(Arc::new(self.column_names.finish()));
423        if self.detail == ColumnsDetail::Full {
424            columns.push(Arc::new(self.ordinal_positions.as_mut().unwrap().finish()));
425            columns.push(Arc::new(self.column_defaults.as_mut().unwrap().finish()));
426        }
427        if self.detail == ColumnsDetail::Full {
428            columns.push(Arc::new(self.is_nullables.finish()));
429            columns.push(Arc::new(self.data_types.finish()));
430        } else {
431            // `Describe`/`Basic` list `data_type` before `is_nullable`,
432            // unlike the SQL-standard `information_schema.columns` order
433            // used by `Full`.
434            columns.push(Arc::new(self.data_types.finish()));
435            columns.push(Arc::new(self.is_nullables.finish()));
436        }
437        if self.detail == ColumnsDetail::Full {
438            columns.push(Arc::new(
439                self.character_maximum_lengths.as_mut().unwrap().finish(),
440            ));
441            columns.push(Arc::new(
442                self.character_octet_lengths.as_mut().unwrap().finish(),
443            ));
444            columns.push(Arc::new(self.numeric_precisions.as_mut().unwrap().finish()));
445            columns.push(Arc::new(
446                self.numeric_precision_radixes.as_mut().unwrap().finish(),
447            ));
448            columns.push(Arc::new(self.numeric_scales.as_mut().unwrap().finish()));
449            columns.push(Arc::new(
450                self.datetime_precisions.as_mut().unwrap().finish(),
451            ));
452            columns.push(Arc::new(self.interval_types.as_mut().unwrap().finish()));
453        }
454        RecordBatch::try_new(Arc::clone(&self.schema), columns).unwrap()
455    }
456}
457
458/// Appends the name of the type of `field` shown in `data_type` to `builder`.
459///
460/// If the field has an extension type registered in `registry`, appends
461/// [`display_name`] if possible. appended. Otherwise, the storage type (raw
462/// Arrow physical type name) is appended.
463///
464/// [`display_name`]: datafusion_common::types::DFExtensionType::display_name
465fn append_field_type_display_name(
466    registry: Option<&dyn ExtensionTypeRegistry>,
467    field: &Field,
468    builder: &mut StringBuilder,
469) {
470    let extension_type = registry
471        .and_then(|registry| registry.create_extension_type_for_field(field).ok())
472        .flatten();
473    match extension_type
474        .as_ref()
475        .and_then(|extension_type| extension_type.display_name())
476    {
477        Some(name) => builder.append_value(name),
478        None => {
479            // Write the storage type straight into the builder, then finish the row.
480            // Writing to a `StringBuilder` does not fail.
481            let _ = write!(builder, "{}", field.data_type());
482            builder.append_value("");
483        }
484    }
485}
486
487/// Returns the Arrow schema of `information_schema.schemata` rows.
488///
489/// Columns and nullability match
490/// <https://www.postgresql.org/docs/current/infoschema-schemata.html>.
491pub fn schemata_schema() -> Schema {
492    Schema::new(vec![
493        Field::new("catalog_name", DataType::Utf8, false),
494        Field::new("schema_name", DataType::Utf8, false),
495        Field::new("schema_owner", DataType::Utf8, true),
496        Field::new("default_character_set_catalog", DataType::Utf8, true),
497        Field::new("default_character_set_schema", DataType::Utf8, true),
498        Field::new("default_character_set_name", DataType::Utf8, true),
499        Field::new("sql_path", DataType::Utf8, true),
500    ])
501}
502
503/// Builds `information_schema.schemata` rows.
504#[derive(Debug)]
505pub struct InformationSchemataBuilder {
506    schema: SchemaRef,
507    catalog_name: StringBuilder,
508    schema_name: StringBuilder,
509    schema_owner: StringBuilder,
510    default_character_set_catalog: StringBuilder,
511    default_character_set_schema: StringBuilder,
512    default_character_set_name: StringBuilder,
513    sql_path: StringBuilder,
514}
515
516impl Default for InformationSchemataBuilder {
517    fn default() -> Self {
518        Self::new()
519    }
520}
521
522impl InformationSchemataBuilder {
523    /// Construct an empty builder.
524    pub fn new() -> Self {
525        Self {
526            schema: Arc::new(schemata_schema()),
527            catalog_name: StringBuilder::new(),
528            schema_name: StringBuilder::new(),
529            schema_owner: StringBuilder::new(),
530            default_character_set_catalog: StringBuilder::new(),
531            default_character_set_schema: StringBuilder::new(),
532            default_character_set_name: StringBuilder::new(),
533            sql_path: StringBuilder::new(),
534        }
535    }
536
537    /// Append one row. The `default_character_set_*` and `sql_path` columns are
538    /// always null.
539    pub fn add_schemata(
540        &mut self,
541        catalog_name: &str,
542        schema_name: &str,
543        schema_owner: Option<&str>,
544    ) {
545        self.catalog_name.append_value(catalog_name);
546        self.schema_name.append_value(schema_name);
547        match schema_owner {
548            Some(owner) => self.schema_owner.append_value(owner),
549            None => self.schema_owner.append_null(),
550        }
551        self.default_character_set_catalog.append_null();
552        self.default_character_set_schema.append_null();
553        self.default_character_set_name.append_null();
554        self.sql_path.append_null();
555    }
556
557    /// Finalize the builder into a [`RecordBatch`].
558    pub fn finish(&mut self) -> Result<RecordBatch> {
559        Ok(RecordBatch::try_new(
560            Arc::clone(&self.schema),
561            vec![
562                Arc::new(self.catalog_name.finish()),
563                Arc::new(self.schema_name.finish()),
564                Arc::new(self.schema_owner.finish()),
565                Arc::new(self.default_character_set_catalog.finish()),
566                Arc::new(self.default_character_set_schema.finish()),
567                Arc::new(self.default_character_set_name.finish()),
568                Arc::new(self.sql_path.finish()),
569            ],
570        )?)
571    }
572}
573
574/// Returns the Arrow schema of `information_schema.df_settings` rows.
575/// The `description` column is only included when `verbose` is set.
576pub fn df_settings_schema(verbose: bool) -> Schema {
577    let mut fields = vec![
578        Field::new("name", DataType::Utf8, false),
579        Field::new("value", DataType::Utf8, true),
580    ];
581    if verbose {
582        fields.push(Field::new("description", DataType::Utf8, true));
583    }
584    Schema::new(fields)
585}
586
587/// Builds `information_schema.df_settings` rows.
588#[derive(Debug)]
589pub struct InformationSchemaDfSettingsBuilder {
590    schema: SchemaRef,
591    names: StringBuilder,
592    values: StringBuilder,
593    descriptions: Option<StringBuilder>,
594}
595
596impl InformationSchemaDfSettingsBuilder {
597    /// Construct an empty builder producing the columns of
598    /// [`df_settings_schema`]`(verbose)`.
599    pub fn new(verbose: bool) -> Self {
600        Self {
601            schema: Arc::new(df_settings_schema(verbose)),
602            names: StringBuilder::new(),
603            values: StringBuilder::new(),
604            descriptions: verbose.then(StringBuilder::new),
605        }
606    }
607
608    /// Append one row.
609    pub fn add_setting(&mut self, entry: ConfigEntry) {
610        self.names.append_value(entry.key);
611        self.values.append_option(entry.value);
612        if let Some(descriptions) = &mut self.descriptions {
613            descriptions.append_value(entry.description);
614        }
615    }
616
617    /// Finalize the builder into a [`RecordBatch`].
618    pub fn finish(&mut self) -> RecordBatch {
619        let mut columns: Vec<ArrayRef> = vec![
620            Arc::new(self.names.finish()),
621            Arc::new(self.values.finish()),
622        ];
623        if let Some(descriptions) = &mut self.descriptions {
624            columns.push(Arc::new(descriptions.finish()));
625        }
626        RecordBatch::try_new(Arc::clone(&self.schema), columns).unwrap()
627    }
628}
629
630/// Returns the Arrow schema of `information_schema.routines` rows.
631pub fn routines_schema() -> Schema {
632    Schema::new(vec![
633        Field::new("specific_catalog", DataType::Utf8, false),
634        Field::new("specific_schema", DataType::Utf8, false),
635        Field::new("specific_name", DataType::Utf8, false),
636        Field::new("routine_catalog", DataType::Utf8, false),
637        Field::new("routine_schema", DataType::Utf8, false),
638        Field::new("routine_name", DataType::Utf8, false),
639        Field::new("routine_type", DataType::Utf8, false),
640        Field::new("is_deterministic", DataType::Boolean, true),
641        Field::new("data_type", DataType::Utf8, true),
642        Field::new("function_type", DataType::Utf8, true),
643        Field::new("description", DataType::Utf8, true),
644        Field::new("syntax_example", DataType::Utf8, true),
645    ])
646}
647
648/// Builds `information_schema.routines` rows.
649#[derive(Debug)]
650pub struct InformationSchemaRoutinesBuilder {
651    schema: SchemaRef,
652    specific_catalog: StringBuilder,
653    specific_schema: StringBuilder,
654    specific_name: StringBuilder,
655    routine_catalog: StringBuilder,
656    routine_schema: StringBuilder,
657    routine_name: StringBuilder,
658    routine_type: StringBuilder,
659    is_deterministic: BooleanBuilder,
660    data_type: StringBuilder,
661    function_type: StringBuilder,
662    description: StringBuilder,
663    syntax_example: StringBuilder,
664}
665
666impl Default for InformationSchemaRoutinesBuilder {
667    fn default() -> Self {
668        Self::new()
669    }
670}
671
672impl InformationSchemaRoutinesBuilder {
673    /// Construct an empty builder.
674    pub fn new() -> Self {
675        Self {
676            schema: Arc::new(routines_schema()),
677            specific_catalog: StringBuilder::new(),
678            specific_schema: StringBuilder::new(),
679            specific_name: StringBuilder::new(),
680            routine_catalog: StringBuilder::new(),
681            routine_schema: StringBuilder::new(),
682            routine_name: StringBuilder::new(),
683            routine_type: StringBuilder::new(),
684            is_deterministic: BooleanBuilder::new(),
685            data_type: StringBuilder::new(),
686            function_type: StringBuilder::new(),
687            description: StringBuilder::new(),
688            syntax_example: StringBuilder::new(),
689        }
690    }
691
692    /// Append one row.
693    #[expect(clippy::too_many_arguments)]
694    pub fn add_routine(
695        &mut self,
696        catalog_name: impl AsRef<str>,
697        schema_name: impl AsRef<str>,
698        routine_name: impl AsRef<str>,
699        routine_type: impl AsRef<str>,
700        is_deterministic: bool,
701        data_type: Option<&impl AsRef<str>>,
702        function_type: impl AsRef<str>,
703        description: Option<impl AsRef<str>>,
704        syntax_example: Option<impl AsRef<str>>,
705    ) {
706        self.specific_catalog.append_value(catalog_name.as_ref());
707        self.specific_schema.append_value(schema_name.as_ref());
708        self.specific_name.append_value(routine_name.as_ref());
709        self.routine_catalog.append_value(catalog_name.as_ref());
710        self.routine_schema.append_value(schema_name.as_ref());
711        self.routine_name.append_value(routine_name.as_ref());
712        self.routine_type.append_value(routine_type.as_ref());
713        self.is_deterministic.append_value(is_deterministic);
714        self.data_type.append_option(data_type.as_ref());
715        self.function_type.append_value(function_type.as_ref());
716        self.description.append_option(description);
717        self.syntax_example.append_option(syntax_example);
718    }
719
720    /// Finalize the builder into a [`RecordBatch`].
721    pub fn finish(&mut self) -> RecordBatch {
722        RecordBatch::try_new(
723            Arc::clone(&self.schema),
724            vec![
725                Arc::new(self.specific_catalog.finish()),
726                Arc::new(self.specific_schema.finish()),
727                Arc::new(self.specific_name.finish()),
728                Arc::new(self.routine_catalog.finish()),
729                Arc::new(self.routine_schema.finish()),
730                Arc::new(self.routine_name.finish()),
731                Arc::new(self.routine_type.finish()),
732                Arc::new(self.is_deterministic.finish()),
733                Arc::new(self.data_type.finish()),
734                Arc::new(self.function_type.finish()),
735                Arc::new(self.description.finish()),
736                Arc::new(self.syntax_example.finish()),
737            ],
738        )
739        .unwrap()
740    }
741}
742
743/// Returns the Arrow schema of `information_schema.parameters` rows.
744pub fn parameters_schema() -> Schema {
745    Schema::new(vec![
746        Field::new("specific_catalog", DataType::Utf8, false),
747        Field::new("specific_schema", DataType::Utf8, false),
748        Field::new("specific_name", DataType::Utf8, false),
749        Field::new("ordinal_position", DataType::UInt64, false),
750        Field::new("parameter_mode", DataType::Utf8, false),
751        Field::new("parameter_name", DataType::Utf8, true),
752        Field::new("data_type", DataType::Utf8, false),
753        Field::new("parameter_default", DataType::Utf8, true),
754        Field::new("is_variadic", DataType::Boolean, false),
755        // `rid` (short for `routine id`) is used to differentiate parameters from different signatures
756        // (It serves as the group-by key when generating the `SHOW FUNCTIONS` query).
757        // For example, the following signatures have different `rid` values:
758        //     - `datetrunc(Utf8, Timestamp(Microsecond, Some("+TZ"))) -> Timestamp(Microsecond, Some("+TZ"))`
759        //     - `datetrunc(Utf8View, Timestamp(Nanosecond, None)) -> Timestamp(Nanosecond, None)`
760        Field::new("rid", DataType::UInt8, false),
761    ])
762}
763
764/// Builds `information_schema.parameters` rows.
765#[derive(Debug)]
766pub struct InformationSchemaParametersBuilder {
767    schema: SchemaRef,
768    specific_catalog: StringBuilder,
769    specific_schema: StringBuilder,
770    specific_name: StringBuilder,
771    ordinal_position: UInt64Builder,
772    parameter_mode: StringBuilder,
773    parameter_name: StringBuilder,
774    data_type: StringBuilder,
775    parameter_default: StringBuilder,
776    is_variadic: BooleanBuilder,
777    rid: UInt8Builder,
778}
779
780impl Default for InformationSchemaParametersBuilder {
781    fn default() -> Self {
782        Self::new()
783    }
784}
785
786impl InformationSchemaParametersBuilder {
787    /// Construct an empty builder.
788    pub fn new() -> Self {
789        Self {
790            schema: Arc::new(parameters_schema()),
791            specific_catalog: StringBuilder::new(),
792            specific_schema: StringBuilder::new(),
793            specific_name: StringBuilder::new(),
794            ordinal_position: UInt64Builder::new(),
795            parameter_mode: StringBuilder::new(),
796            parameter_name: StringBuilder::new(),
797            data_type: StringBuilder::new(),
798            parameter_default: StringBuilder::new(),
799            is_variadic: BooleanBuilder::new(),
800            rid: UInt8Builder::new(),
801        }
802    }
803
804    /// Append one row.
805    #[expect(clippy::too_many_arguments)]
806    pub fn add_parameter(
807        &mut self,
808        specific_catalog: impl AsRef<str>,
809        specific_schema: impl AsRef<str>,
810        specific_name: impl AsRef<str>,
811        ordinal_position: u64,
812        parameter_mode: impl AsRef<str>,
813        parameter_name: Option<&(impl AsRef<str> + ?Sized)>,
814        data_type: impl AsRef<str>,
815        parameter_default: Option<impl AsRef<str>>,
816        is_variadic: bool,
817        rid: u8,
818    ) {
819        self.specific_catalog
820            .append_value(specific_catalog.as_ref());
821        self.specific_schema.append_value(specific_schema.as_ref());
822        self.specific_name.append_value(specific_name.as_ref());
823        self.ordinal_position.append_value(ordinal_position);
824        self.parameter_mode.append_value(parameter_mode.as_ref());
825        self.parameter_name.append_option(parameter_name.as_ref());
826        self.data_type.append_value(data_type.as_ref());
827        self.parameter_default.append_option(parameter_default);
828        self.is_variadic.append_value(is_variadic);
829        self.rid.append_value(rid);
830    }
831
832    /// Finalize the builder into a [`RecordBatch`].
833    pub fn finish(&mut self) -> RecordBatch {
834        RecordBatch::try_new(
835            Arc::clone(&self.schema),
836            vec![
837                Arc::new(self.specific_catalog.finish()),
838                Arc::new(self.specific_schema.finish()),
839                Arc::new(self.specific_name.finish()),
840                Arc::new(self.ordinal_position.finish()),
841                Arc::new(self.parameter_mode.finish()),
842                Arc::new(self.parameter_name.finish()),
843                Arc::new(self.data_type.finish()),
844                Arc::new(self.parameter_default.finish()),
845                Arc::new(self.is_variadic.finish()),
846                Arc::new(self.rid.finish()),
847            ],
848        )
849        .unwrap()
850    }
851}
852
853/// Returns the Arrow schema of `SHOW FUNCTIONS` output, with one row per function signature:
854///
855/// - `function_name`
856/// - `return_type`
857/// - `parameters`: parameter names, in order
858/// - `parameter_types`: parameter types, in order
859/// - `function_type`: `SCALAR`, `AGGREGATE`, `WINDOW` or `TABLE`
860/// - `description` and `syntax_example`: from the function's documentation
861///
862/// Unlike the other schemas in this module, this does not correspond to an
863/// `information_schema` table.
864pub fn show_functions_schema() -> Schema {
865    Schema::new(vec![
866        Field::new("function_name", DataType::Utf8, false),
867        Field::new("return_type", DataType::Utf8, true),
868        Field::new("parameters", DataType::new_list(DataType::Utf8, true), true),
869        Field::new(
870            "parameter_types",
871            DataType::new_list(DataType::Utf8, true),
872            true,
873        ),
874        Field::new("function_type", DataType::Utf8, true),
875        Field::new("description", DataType::Utf8, true),
876        Field::new("syntax_example", DataType::Utf8, true),
877    ])
878}
879
880#[cfg(test)]
881mod tests {
882    use super::*;
883    use crate::registry::MemoryExtensionTypeRegistry;
884    use arrow::array::Array;
885    use arrow_schema::extension::{EXTENSION_TYPE_NAME_KEY, Uuid};
886    use std::collections::HashMap;
887
888    fn display_names(
889        registry: Option<&dyn ExtensionTypeRegistry>,
890        fields: &[Field],
891    ) -> Vec<String> {
892        let mut builder = StringBuilder::new();
893        for field in fields {
894            append_field_type_display_name(registry, field, &mut builder);
895        }
896        let array = builder.finish();
897        (0..array.len())
898            .map(|i| array.value(i).to_owned())
899            .collect()
900    }
901
902    /// Fields whose extension type cannot be resolved show their storage type. The
903    /// resolvable cases are covered by `sql_extension_types.slt`.
904    #[test]
905    fn test_append_field_type_display_name_fallbacks() {
906        let registry = MemoryExtensionTypeRegistry::new_with_canonical_extension_types();
907
908        let unregistered = Field::new("x", DataType::Int32, true).with_metadata(
909            HashMap::from([(EXTENSION_TYPE_NAME_KEY.to_owned(), "example.x".to_owned())]),
910        );
911        // `arrow.uuid` with a storage type that the extension type does not support
912        let invalid =
913            Field::new("i", DataType::Int32, true).with_metadata(HashMap::from([(
914                EXTENSION_TYPE_NAME_KEY.to_owned(),
915                "arrow.uuid".to_owned(),
916            )]));
917        assert_eq!(
918            display_names(Some(&registry), &[unregistered, invalid]),
919            ["Int32", "Int32"]
920        );
921
922        let uuid = Field::new("u", DataType::FixedSizeBinary(16), true)
923            .with_extension_type(Uuid);
924        let empty_registry = MemoryExtensionTypeRegistry::new_empty();
925        assert_eq!(
926            display_names(Some(&empty_registry), std::slice::from_ref(&uuid)),
927            ["FixedSizeBinary(16)"]
928        );
929        assert_eq!(display_names(None, &[uuid]), ["FixedSizeBinary(16)"]);
930    }
931}