Skip to main content

datafusion_doc/
lib.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#![cfg_attr(test, allow(clippy::needless_pass_by_value))]
6#![doc(
7    html_logo_url = "https://raw.githubusercontent.com/apache/datafusion/19fe44cf2f30cbdd63d4a4f52c74055163c6cc38/docs/logos/standalone_logo/logo_original.svg",
8    html_favicon_url = "https://raw.githubusercontent.com/apache/datafusion/19fe44cf2f30cbdd63d4a4f52c74055163c6cc38/docs/logos/standalone_logo/logo_original.svg"
9)]
10#![cfg_attr(docsrs, feature(doc_cfg))]
11
12mod udaf;
13mod udf;
14mod udwf;
15
16pub use udaf::aggregate_doc_sections;
17pub use udf::scalar_doc_sections;
18pub use udwf::window_doc_sections;
19
20/// Documentation for use by `ScalarUDFImpl`, `AggregateUDFImpl` and `WindowUDFImpl` functions.
21///
22/// See the [`DocumentationBuilder`] to create a new [`Documentation`] struct.
23///
24/// The DataFusion [SQL function documentation] is automatically  generated from these structs.
25/// The name of the udf will be pulled from the `ScalarUDFImpl::name`,
26/// `AggregateUDFImpl::name` or `WindowUDFImpl::name`
27/// function as appropriate.
28///
29/// All strings in the documentation are required to be
30/// in [markdown format](https://www.markdownguide.org/basic-syntax/).
31///
32/// Currently, documentation only supports a single language
33/// thus all text should be in English.
34///
35/// [SQL function documentation]: https://datafusion.apache.org/user-guide/sql/index.html
36#[derive(Debug, Clone, PartialEq, Eq, Hash)]
37pub struct Documentation {
38    /// The section in the documentation where the UDF will be documented
39    pub doc_section: DocSection,
40    /// The description for the UDF
41    pub description: String,
42    /// A brief example of the syntax. For example "ascii(str)"
43    pub syntax_example: String,
44    /// A sql example for the UDF, usually in the form of a sql prompt
45    /// query and output. It is strongly recommended to provide an
46    /// example for anything but the most basic UDF's
47    pub sql_example: Option<String>,
48    /// Arguments for the UDF which will be displayed in array order.
49    /// Left member of a pair is the argument name, right is a
50    /// description for the argument
51    pub arguments: Option<Vec<(String, String)>>,
52    /// A list of alternative syntax examples for a function
53    pub alternative_syntax: Option<Vec<String>>,
54    /// Related functions if any. Values should match the related
55    /// udf's name exactly. Related udf's must be of the same
56    /// UDF type (scalar, aggregate or window) for proper linking to
57    /// occur
58    pub related_udfs: Option<Vec<String>>,
59}
60
61impl Documentation {
62    /// Returns a new [`DocumentationBuilder`] with no options set.
63    pub fn builder(
64        doc_section: DocSection,
65        description: impl Into<String>,
66        syntax_example: impl Into<String>,
67    ) -> DocumentationBuilder {
68        DocumentationBuilder::new_with_details(doc_section, description, syntax_example)
69    }
70
71    /// Output the `Documentation` struct in form of custom Rust documentation attributes
72    /// It is useful to semi automate during tmigration of UDF documentation
73    /// generation from code based to attribute based and can be safely removed after
74    pub fn to_doc_attribute(&self) -> String {
75        let mut result = String::new();
76
77        result.push_str("#[user_doc(");
78        // Doc Section
79        result.push_str(
80            format!(
81                "\n    doc_section({}label = \"{}\"{}),",
82                if !self.doc_section.include {
83                    "include = \"false\", "
84                } else {
85                    ""
86                },
87                self.doc_section.label,
88                self.doc_section
89                    .description
90                    .map(|s| format!(", description = \"{s}\""))
91                    .unwrap_or_default(),
92            )
93            .as_ref(),
94        );
95
96        // Description
97        result.push_str(format!("\n    description=\"{}\",", self.description).as_ref());
98        // Syntax Example
99        result.push_str(
100            format!("\n    syntax_example=\"{}\",", self.syntax_example).as_ref(),
101        );
102        // SQL Example
103        result.push_str(
104            &self
105                .sql_example
106                .clone()
107                .map(|s| format!("\n    sql_example = r#\"{s}\"#,"))
108                .unwrap_or_default(),
109        );
110
111        let st_arg_token = " expression to operate on. Can be a constant, column, or function, and any combination of operators.";
112        // Standard Arguments
113        if let Some(args) = self.arguments.clone() {
114            for (name, value) in &args {
115                if value.contains(st_arg_token) {
116                    if name.starts_with("The ") {
117                        result.push_str(
118                            format!(
119                                "\n    standard_argument(\n        name = \"{name}\"),"
120                            )
121                            .as_ref(),
122                        );
123                    } else {
124                        result.push_str(format!("\n    standard_argument(\n        name = \"{}\",\n        prefix = \"{}\"\n    ),", name, value.replace(st_arg_token, "")).as_ref());
125                    }
126                }
127            }
128        }
129
130        // Arguments
131        if let Some(args) = self.arguments.clone() {
132            for (name, value) in &args {
133                if !value.contains(st_arg_token) {
134                    result.push_str(format!("\n    argument(\n        name = \"{name}\",\n        description = \"{value}\"\n    ),").as_ref());
135                }
136            }
137        }
138
139        if let Some(alt_syntax) = self.alternative_syntax.clone() {
140            for syntax in &alt_syntax {
141                result.push_str(
142                    format!("\n    alternative_syntax = \"{syntax}\",").as_ref(),
143                );
144            }
145        }
146
147        // Related UDFs
148        if let Some(related_udf) = self.related_udfs.clone() {
149            for udf in &related_udf {
150                result.push_str(format!("\n    related_udf(name = \"{udf}\"),").as_ref());
151            }
152        }
153
154        result.push_str("\n)]");
155
156        result
157    }
158}
159
160#[derive(Debug, Clone, PartialEq, Eq, Hash)]
161pub struct DocSection {
162    /// True to include this doc section in the public
163    /// documentation, false otherwise
164    pub include: bool,
165    /// A display label for the doc section. For example: "Math Expressions"
166    pub label: &'static str,
167    /// An optional description for the doc section
168    pub description: Option<&'static str>,
169}
170
171impl Default for DocSection {
172    /// Returns a "default" Doc section.
173    ///
174    /// This is suitable for user defined functions that do not appear in the
175    /// DataFusion documentation.
176    fn default() -> Self {
177        Self {
178            include: true,
179            label: "Default",
180            description: None,
181        }
182    }
183}
184
185/// A builder for [`Documentation`]'s.
186///
187/// Example:
188///
189/// ```rust
190///
191/// # fn main() {
192///     use datafusion_doc::{DocSection, Documentation};
193///     let doc_section = DocSection {
194///         include: true,
195///         label: "Display Label",
196///         description: None,
197///     };
198///
199///     let documentation = Documentation::builder(doc_section, "Add one to an int32".to_owned(), "add_one(2)".to_owned())
200///           .with_argument("arg_1", "The int32 number to add one to")
201///           .build();
202/// # }
203pub struct DocumentationBuilder {
204    pub doc_section: DocSection,
205    pub description: String,
206    pub syntax_example: String,
207    pub sql_example: Option<String>,
208    pub arguments: Option<Vec<(String, String)>>,
209    pub alternative_syntax: Option<Vec<String>>,
210    pub related_udfs: Option<Vec<String>>,
211}
212
213impl DocumentationBuilder {
214    /// Creates a new [`DocumentationBuilder`] with all required fields
215    pub fn new_with_details(
216        doc_section: DocSection,
217        description: impl Into<String>,
218        syntax_example: impl Into<String>,
219    ) -> Self {
220        Self {
221            doc_section,
222            description: description.into(),
223            syntax_example: syntax_example.into(),
224            sql_example: None,
225            arguments: None,
226            alternative_syntax: None,
227            related_udfs: None,
228        }
229    }
230
231    pub fn with_doc_section(mut self, doc_section: DocSection) -> Self {
232        self.doc_section = doc_section;
233        self
234    }
235
236    pub fn with_description(mut self, description: impl Into<String>) -> Self {
237        self.description = description.into();
238        self
239    }
240
241    pub fn with_syntax_example(mut self, syntax_example: impl Into<String>) -> Self {
242        self.syntax_example = syntax_example.into();
243        self
244    }
245
246    pub fn with_sql_example(mut self, sql_example: impl Into<String>) -> Self {
247        self.sql_example = Some(sql_example.into());
248        self
249    }
250
251    /// Adds documentation for a specific argument to the documentation.
252    ///
253    /// Arguments are displayed in the order they are added.
254    pub fn with_argument(
255        mut self,
256        arg_name: impl Into<String>,
257        arg_description: impl Into<String>,
258    ) -> Self {
259        let mut args = self.arguments.unwrap_or_default();
260        args.push((arg_name.into(), arg_description.into()));
261        self.arguments = Some(args);
262        self
263    }
264
265    /// Add a standard "expression" argument to the documentation
266    ///
267    /// The argument is rendered like below if Some() is passed through:
268    ///
269    /// ```text
270    /// <arg_name>:
271    ///   <expression_type> expression to operate on. Can be a constant, column, or function, and any combination of operators.
272    /// ```
273    ///
274    /// The argument is rendered like below if None is passed through:
275    ///
276    /// ```text
277    /// <arg_name>:
278    ///   The expression to operate on. Can be a constant, column, or function, and any combination of operators.
279    /// ```
280    pub fn with_standard_argument(
281        self,
282        arg_name: impl Into<String>,
283        expression_type: Option<&str>,
284    ) -> Self {
285        let description = format!(
286            "{} expression to operate on. Can be a constant, column, or function, and any combination of operators.",
287            expression_type.unwrap_or("The")
288        );
289        self.with_argument(arg_name, description)
290    }
291
292    pub fn with_alternative_syntax(mut self, syntax_name: impl Into<String>) -> Self {
293        let mut alternative_syntax_array = self.alternative_syntax.unwrap_or_default();
294        alternative_syntax_array.push(syntax_name.into());
295        self.alternative_syntax = Some(alternative_syntax_array);
296        self
297    }
298
299    pub fn with_related_udf(mut self, related_udf: impl Into<String>) -> Self {
300        let mut related = self.related_udfs.unwrap_or_default();
301        related.push(related_udf.into());
302        self.related_udfs = Some(related);
303        self
304    }
305
306    /// Build the documentation from provided components
307    ///
308    /// Panics if `doc_section`, `description` or `syntax_example` is not set
309    pub fn build(self) -> Documentation {
310        let Self {
311            doc_section,
312            description,
313            syntax_example,
314            sql_example,
315            arguments,
316            alternative_syntax,
317            related_udfs,
318        } = self;
319
320        Documentation {
321            doc_section,
322            description,
323            syntax_example,
324            sql_example,
325            arguments,
326            alternative_syntax,
327            related_udfs,
328        }
329    }
330}