Skip to content

Apache DataFusion SQL Query Engine

Doc gen: Migrate aggregate functions doc to attribute based. (#13646)

Oleks Vb312ac167e96
diff --git a/datafusion-cli/Cargo.lock b/datafusion-cli/Cargo.lock
index f06a8b210b..c871b2fdda 100644
--- a/datafusion-cli/Cargo.lock
+++ b/datafusion-cli/Cargo.lock
@@ -63,9 +63,9 @@ dependencies = [
[[package]]
name = "allocator-api2"
-version = "0.2.20"
+version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "45862d1c77f2228b9e10bc609d5bc203d86ebc9b87ad8d5d5167a6c9abf739d9"
+checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
[[package]]
name = "android-tzdata"
@@ -467,7 +467,7 @@ dependencies = [
"aws-sdk-sts",
"aws-smithy-async",
"aws-smithy-http",
- "aws-smithy-json",
+ "aws-smithy-json 0.60.7",
"aws-smithy-runtime",
"aws-smithy-runtime-api",
"aws-smithy-types",
@@ -498,9 +498,9 @@ dependencies = [
[[package]]
name = "aws-runtime"
-version = "1.4.3"
+version = "1.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a10d5c055aa540164d9561a0e2e74ad30f0dcf7393c3a92f6733ddf9c5762468"
+checksum = "b5ac934720fbb46206292d2c75b57e67acfc56fe7dfd34fb9a02334af08409ea"
dependencies = [
"aws-credential-types",
"aws-sigv4",
@@ -523,15 +523,15 @@ dependencies = [
[[package]]
name = "aws-sdk-sso"
-version = "1.49.0"
+version = "1.50.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "09677244a9da92172c8dc60109b4a9658597d4d298b188dd0018b6a66b410ca4"
+checksum = "05ca43a4ef210894f93096039ef1d6fa4ad3edfabb3be92b80908b9f2e4b4eab"
dependencies = [
"aws-credential-types",
"aws-runtime",
"aws-smithy-async",
"aws-smithy-http",
- "aws-smithy-json",
+ "aws-smithy-json 0.61.1",
"aws-smithy-runtime",
"aws-smithy-runtime-api",
"aws-smithy-types",
@@ -545,15 +545,15 @@ dependencies = [
[[package]]
name = "aws-sdk-ssooidc"
-version = "1.50.0"
+version = "1.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "81fea2f3a8bb3bd10932ae7ad59cc59f65f270fc9183a7e91f501dc5efbef7ee"
+checksum = "abaf490c2e48eed0bb8e2da2fb08405647bd7f253996e0f93b981958ea0f73b0"
dependencies = [
"aws-credential-types",
"aws-runtime",
"aws-smithy-async",
"aws-smithy-http",
- "aws-smithy-json",
+ "aws-smithy-json 0.61.1",
"aws-smithy-runtime",
"aws-smithy-runtime-api",
"aws-smithy-types",
@@ -567,15 +567,15 @@ dependencies = [
[[package]]
name = "aws-sdk-sts"
-version = "1.50.0"
+version = "1.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6ada54e5f26ac246dc79727def52f7f8ed38915cb47781e2a72213957dc3a7d5"
+checksum = "b68fde0d69c8bfdc1060ea7da21df3e39f6014da316783336deff0a9ec28f4bf"
dependencies = [
"aws-credential-types",
"aws-runtime",
"aws-smithy-async",
"aws-smithy-http",
- "aws-smithy-json",
+ "aws-smithy-json 0.61.1",
"aws-smithy-query",
"aws-smithy-runtime",
"aws-smithy-runtime-api",
@@ -590,9 +590,9 @@ dependencies = [
[[package]]
name = "aws-sigv4"
-version = "1.2.5"
+version = "1.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5619742a0d8f253be760bfbb8e8e8368c69e3587e4637af5754e488a611499b1"
+checksum = "7d3820e0c08d0737872ff3c7c1f21ebbb6693d832312d6152bf18ef50a5471c2"
dependencies = [
"aws-credential-types",
"aws-smithy-http",
@@ -603,7 +603,7 @@ dependencies = [
"hex",
"hmac",
"http 0.2.12",
- "http 1.1.0",
+ "http 1.2.0",
"once_cell",
"percent-encoding",
"sha2",
@@ -651,6 +651,15 @@ dependencies = [
"aws-smithy-types",
]
+[[package]]
+name = "aws-smithy-json"
+version = "0.61.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ee4e69cc50921eb913c6b662f8d909131bb3e6ad6cb6090d3a39b66fc5c52095"
+dependencies = [
+ "aws-smithy-types",
+]
+
[[package]]
name = "aws-smithy-query"
version = "0.60.7"
@@ -663,9 +672,9 @@ dependencies = [
[[package]]
name = "aws-smithy-runtime"
-version = "1.7.3"
+version = "1.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "be28bd063fa91fd871d131fc8b68d7cd4c5fa0869bea68daca50dcb1cbd76be2"
+checksum = "9f20685047ca9d6f17b994a07f629c813f08b5bce65523e47124879e60103d45"
dependencies = [
"aws-smithy-async",
"aws-smithy-http",
@@ -698,7 +707,7 @@ dependencies = [
"aws-smithy-types",
"bytes",
"http 0.2.12",
- "http 1.1.0",
+ "http 1.2.0",
"pin-project-lite",
"tokio",
"tracing",
@@ -716,7 +725,7 @@ dependencies = [
"bytes-utils",
"futures-core",
"http 0.2.12",
- "http 1.1.0",
+ "http 1.2.0",
"http-body 0.4.6",
"http-body 1.0.1",
"http-body-util",
@@ -980,9 +989,9 @@ dependencies = [
[[package]]
name = "clap"
-version = "4.5.21"
+version = "4.5.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fb3b4b9e5a7c7514dfa52869339ee98b3156b0bfb4e8a77c4ff4babb64b1604f"
+checksum = "69371e34337c4c984bbe322360c2547210bf632eb2814bbe78a6e87a2935bd2b"
dependencies = [
"clap_builder",
"clap_derive",
@@ -990,9 +999,9 @@ dependencies = [
[[package]]
name = "clap_builder"
-version = "4.5.21"
+version = "4.5.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b17a95aa67cc7b5ebd32aa5370189aa0d79069ef1c64ce893bd30fb24bff20ec"
+checksum = "6e24c1b4099818523236a8ca881d2b45db98dadfb4625cf6608c12069fcbbde1"
dependencies = [
"anstream",
"anstyle",
@@ -1415,9 +1424,11 @@ dependencies = [
"arrow",
"arrow-schema",
"datafusion-common",
+ "datafusion-doc",
"datafusion-execution",
"datafusion-expr",
"datafusion-functions-aggregate-common",
+ "datafusion-macros",
"datafusion-physical-expr",
"datafusion-physical-expr-common",
"half",
@@ -1976,7 +1987,7 @@ dependencies = [
"fnv",
"futures-core",
"futures-sink",
- "http 1.1.0",
+ "http 1.2.0",
"indexmap",
"slab",
"tokio",
@@ -2060,9 +2071,9 @@ dependencies = [
[[package]]
name = "http"
-version = "1.1.0"
+version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "21b9ddb458710bc376481b842f5da65cdf31522de232c1ca8146abce2a358258"
+checksum = "f16ca2af56261c99fba8bac40a10251ce8188205a4c448fbb745a2e4daa76fea"
dependencies = [
"bytes",
"fnv",
@@ -2087,7 +2098,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184"
dependencies = [
"bytes",
- "http 1.1.0",
+ "http 1.2.0",
]
[[package]]
@@ -2098,7 +2109,7 @@ checksum = "793429d76616a256bcb62c2a2ec2bed781c8307e797e2598c50010f2bee2544f"
dependencies = [
"bytes",
"futures-util",
- "http 1.1.0",
+ "http 1.2.0",
"http-body 1.0.1",
"pin-project-lite",
]
@@ -2155,7 +2166,7 @@ dependencies = [
"futures-channel",
"futures-util",
"h2 0.4.7",
- "http 1.1.0",
+ "http 1.2.0",
"http-body 1.0.1",
"httparse",
"itoa",
@@ -2188,7 +2199,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08afdbb5c31130e3034af566421053ab03787c640246a446327f550d11bcb333"
dependencies = [
"futures-util",
- "http 1.1.0",
+ "http 1.2.0",
"hyper 1.5.1",
"hyper-util",
"rustls 0.23.19",
@@ -2208,7 +2219,7 @@ dependencies = [
"bytes",
"futures-channel",
"futures-util",
- "http 1.1.0",
+ "http 1.2.0",
"http-body 1.0.1",
"hyper 1.5.1",
"pin-project-lite",
@@ -2382,9 +2393,9 @@ dependencies = [
[[package]]
name = "indexmap"
-version = "2.6.0"
+version = "2.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "707907fe3c25f5424cce2cb7e1cbcafee6bdbe735ca90ef77c29e84591e5b9da"
+checksum = "62f822373a4fe84d4bb149bf54e584a7f4abec90e072ed49cda0edea5b95471f"
dependencies = [
"equivalent",
"hashbrown 0.15.2",
@@ -2434,10 +2445,11 @@ dependencies = [
[[package]]
name = "js-sys"
-version = "0.3.73"
+version = "0.3.74"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fb15147158e79fd8b8afd0252522769c4f48725460b37338544d8379d94fc8f9"
+checksum = "a865e038f7f6ed956f788f0d7d60c541fff74c7bd74272c5d4cf15c63743e705"
dependencies = [
+ "once_cell",
"wasm-bindgen",
]
@@ -3093,7 +3105,7 @@ dependencies = [
"rustc-hash",
"rustls 0.23.19",
"socket2",
- "thiserror 2.0.3",
+ "thiserror 2.0.4",
"tokio",
"tracing",
]
@@ -3112,7 +3124,7 @@ dependencies = [
"rustls 0.23.19",
"rustls-pki-types",
"slab",
- "thiserror 2.0.3",
+ "thiserror 2.0.4",
"tinyvec",
"tracing",
"web-time",
@@ -3273,7 +3285,7 @@ dependencies = [
"futures-core",
"futures-util",
"h2 0.4.7",
- "http 1.1.0",
+ "http 1.2.0",
"http-body 1.0.1",
"http-body-util",
"hyper 1.5.1",
@@ -3366,9 +3378,9 @@ checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f"
[[package]]
name = "rustc-hash"
-version = "2.0.0"
+version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "583034fd73374156e66797ed8e5b0d5690409c9226b22d87cb7f19821c05d152"
+checksum = "c7fb8039b3032c191086b10f11f319a6e99e1e82889c5cc6046f515c9db1d497"
[[package]]
name = "rustc_version"
@@ -3900,11 +3912,11 @@ dependencies = [
[[package]]
name = "thiserror"
-version = "2.0.3"
+version = "2.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c006c85c7651b3cf2ada4584faa36773bd07bac24acfb39f3c431b36d7e667aa"
+checksum = "2f49a1853cf82743e3b7950f77e0f4d622ca36cf4317cba00c767838bac8d490"
dependencies = [
- "thiserror-impl 2.0.3",
+ "thiserror-impl 2.0.4",
]
[[package]]
@@ -3920,9 +3932,9 @@ dependencies = [
[[package]]
name = "thiserror-impl"
-version = "2.0.3"
+version = "2.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f077553d607adc1caf65430528a576c757a71ed73944b66ebb58ef2bbd243568"
+checksum = "8381894bb3efe0c4acac3ded651301ceee58a15d47c2e34885ed1908ad667061"
dependencies = [
"proc-macro2",
"quote",
@@ -3942,9 +3954,9 @@ dependencies = [
[[package]]
name = "time"
-version = "0.3.36"
+version = "0.3.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5dfd88e563464686c916c7e46e623e520ddc6d79fa6641390f2e3fa86e83e885"
+checksum = "35e7868883861bd0e56d9ac6efcaaca0d6d5d82a2a7ec8209ff492c07cf37b21"
dependencies = [
"deranged",
"num-conv",
@@ -3962,9 +3974,9 @@ checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3"
[[package]]
name = "time-macros"
-version = "0.2.18"
+version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3f252a68540fde3a3877aeea552b832b40ab9a69e318efd078774a01ddee1ccf"
+checksum = "2834e6017e3e5e4b9834939793b282bc03b37a3336245fa820e35e233e2a85de"
dependencies = [
"num-conv",
"time-core",
@@ -4006,9 +4018,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]]
name = "tokio"
-version = "1.41.1"
+version = "1.42.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "22cfb5bee7a6a52939ca9224d6ac897bb669134078daa8735560897f69de4d33"
+checksum = "5cec9b21b0450273377fc97bd4c33a8acffc8c996c987a7c5b319a0083707551"
dependencies = [
"backtrace",
"bytes",
@@ -4056,9 +4068,9 @@ dependencies = [
[[package]]
name = "tokio-util"
-version = "0.7.12"
+version = "0.7.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "61e7c3654c13bcd040d4a03abee2c75b1d14a37b423cf5a813ceae1cc903ec6a"
+checksum = "d7fcaa8d55a2bdd6b83ace262b016eca0d79ee02818c5c1bcdf0305114081078"
dependencies = [
"bytes",
"futures-core",
@@ -4286,9 +4298,9 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]
name = "wasm-bindgen"
-version = "0.2.96"
+version = "0.2.97"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "21d3b25c3ea1126a2ad5f4f9068483c2af1e64168f847abe863a526b8dbfe00b"
+checksum = "d15e63b4482863c109d70a7b8706c1e364eb6ea449b201a76c5b89cedcec2d5c"
dependencies = [
"cfg-if",
"once_cell",
@@ -4297,9 +4309,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-backend"
-version = "0.2.96"
+version = "0.2.97"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "52857d4c32e496dc6537646b5b117081e71fd2ff06de792e3577a150627db283"
+checksum = "8d36ef12e3aaca16ddd3f67922bc63e48e953f126de60bd33ccc0101ef9998cd"
dependencies = [
"bumpalo",
"log",
@@ -4312,9 +4324,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-futures"
-version = "0.4.46"
+version = "0.4.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "951fe82312ed48443ac78b66fa43eded9999f738f6022e67aead7b708659e49a"
+checksum = "9dfaf8f50e5f293737ee323940c7d8b08a66a95a419223d9f41610ca08b0833d"
dependencies = [
"cfg-if",
"js-sys",
@@ -4325,9 +4337,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-macro"
-version = "0.2.96"
+version = "0.2.97"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "920b0ffe069571ebbfc9ddc0b36ba305ef65577c94b06262ed793716a1afd981"
+checksum = "705440e08b42d3e4b36de7d66c944be628d579796b8090bfa3471478a2260051"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
@@ -4335,9 +4347,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-macro-support"
-version = "0.2.96"
+version = "0.2.97"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bf59002391099644be3524e23b781fa43d2be0c5aa0719a18c0731b9d195cab6"
+checksum = "98c9ae5a76e46f4deecd0f0255cc223cfa18dc9b261213b8aa0c7b36f61b3f1d"
dependencies = [
"proc-macro2",
"quote",
@@ -4348,9 +4360,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-shared"
-version = "0.2.96"
+version = "0.2.97"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e5047c5392700766601942795a436d7d2599af60dcc3cc1248c9120bfb0827b0"
+checksum = "6ee99da9c5ba11bd675621338ef6fa52296b76b83305e9b6e5c77d4c286d6d49"
[[package]]
name = "wasm-streams"
@@ -4367,9 +4379,9 @@ dependencies = [
[[package]]
name = "web-sys"
-version = "0.3.73"
+version = "0.3.74"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "476364ff87d0ae6bfb661053a9104ab312542658c3d8f963b7ace80b6f9b26b9"
+checksum = "a98bc3c33f0fe7e59ad7cd041b89034fa82a7c2d4365ca538dda6cdaf513863c"
dependencies = [
"js-sys",
"wasm-bindgen",
diff --git a/datafusion/core/src/bin/print_functions_docs.rs b/datafusion/core/src/bin/print_functions_docs.rs
index 7f3990c534..b58f6e47d3 100644
--- a/datafusion/core/src/bin/print_functions_docs.rs
+++ b/datafusion/core/src/bin/print_functions_docs.rs
@@ -84,6 +84,29 @@ fn print_window_docs() -> Result<String> {
print_docs(providers, window_doc_sections::doc_sections())
}
+// Temporary method useful to semi automate
+// the migration of UDF documentation generation from code based
+// to attribute based
+// To be removed
+fn save_doc_code_text(documentation: &Documentation, name: &str) {
+ let attr_text = documentation.to_doc_attribute();
+
+ let file_path = format!("{}.txt", name);
+ if std::path::Path::new(&file_path).exists() {
+ std::fs::remove_file(&file_path).unwrap();
+ }
+
+ // Open the file in append mode, create it if it doesn't exist
+ let mut file = std::fs::OpenOptions::new()
+ .append(true) // Open in append mode
+ .create(true) // Create the file if it doesn't exist
+ .open(file_path)
+ .unwrap();
+
+ use std::io::Write;
+ file.write_all(attr_text.as_bytes()).unwrap();
+}
+
fn print_docs(
providers: Vec<Box<dyn DocProvider>>,
doc_sections: Vec<DocSection>,
@@ -158,6 +181,9 @@ fn print_docs(
unreachable!()
};
+ // Temporary for doc gen migration, see `save_doc_code_text` comments
+ save_doc_code_text(documentation, &name);
+
// first, the name, description and syntax example
let _ = write!(
docs,
diff --git a/datafusion/doc/src/lib.rs b/datafusion/doc/src/lib.rs
index 5bc986d07f..3d8fae6cd3 100644
--- a/datafusion/doc/src/lib.rs
+++ b/datafusion/doc/src/lib.rs
@@ -63,6 +63,90 @@ impl Documentation {
) -> DocumentationBuilder {
DocumentationBuilder::new(doc_section, description, syntax_example)
}
+
+ /// Output the `Documentation` struct in form of custom Rust documentation attributes
+ /// It is useful to semi automate during tmigration of UDF documentation
+ /// generation from code based to attribute based and can be safely removed after
+ pub fn to_doc_attribute(&self) -> String {
+ let mut result = String::new();
+
+ result.push_str("#[user_doc(");
+ // Doc Section
+ result.push_str(
+ format!(
+ "\n doc_section({}label = \"{}\"{}),",
+ if !self.doc_section.include {
+ "include = \"false\", "
+ } else {
+ ""
+ },
+ self.doc_section.label,
+ self.doc_section
+ .description
+ .map(|s| format!(", description = \"{}\"", s))
+ .unwrap_or_default(),
+ )
+ .as_ref(),
+ );
+
+ // Description
+ result.push_str(format!("\n description=\"{}\",", self.description).as_ref());
+ // Syntax Example
+ result.push_str(
+ format!("\n syntax_example=\"{}\",", self.syntax_example).as_ref(),
+ );
+ // SQL Example
+ result.push_str(
+ &self
+ .sql_example
+ .clone()
+ .map(|s| format!("\n sql_example = r#\"{}\"#,", s))
+ .unwrap_or_default(),
+ );
+
+ let st_arg_token = " expression to operate on. Can be a constant, column, or function, and any combination of operators.";
+ // Standard Arguments
+ if let Some(args) = self.arguments.clone() {
+ args.iter().for_each(|(name, value)| {
+ if value.contains(st_arg_token) {
+ if name.starts_with("The ") {
+ result.push_str(format!("\n standard_argument(\n name = \"{}\"),", name).as_ref());
+ } else {
+ result.push_str(format!("\n standard_argument(\n name = \"{}\",\n prefix = \"{}\"\n ),", name, value.replace(st_arg_token, "")).as_ref());
+ }
+ }
+ });
+ }
+
+ // Arguments
+ if let Some(args) = self.arguments.clone() {
+ args.iter().for_each(|(name, value)| {
+ if !value.contains(st_arg_token) {
+ result.push_str(format!("\n argument(\n name = \"{}\",\n description = \"{}\"\n ),", name, value).as_ref());
+ }
+ });
+ }
+
+ if let Some(alt_syntax) = self.alternative_syntax.clone() {
+ alt_syntax.iter().for_each(|syntax| {
+ result.push_str(
+ format!("\n alternative_syntax = \"{}\",", syntax).as_ref(),
+ );
+ });
+ }
+
+ // Related UDFs
+ if let Some(related_udf) = self.related_udfs.clone() {
+ related_udf.iter().for_each(|udf| {
+ result
+ .push_str(format!("\n related_udf(name = \"{}\"),", udf).as_ref());
+ });
+ }
+
+ result.push_str("\n)]");
+
+ result
+ }
}
#[derive(Debug, Clone, PartialEq)]
diff --git a/datafusion/functions-aggregate/Cargo.toml b/datafusion/functions-aggregate/Cargo.toml
index 33a52afbe2..bd65490c5a 100644
--- a/datafusion/functions-aggregate/Cargo.toml
+++ b/datafusion/functions-aggregate/Cargo.toml
@@ -42,9 +42,11 @@ ahash = { workspace = true }
arrow = { workspace = true }
arrow-schema = { workspace = true }
datafusion-common = { workspace = true }
+datafusion-doc = { workspace = true }
datafusion-execution = { workspace = true }
datafusion-expr = { workspace = true }
datafusion-functions-aggregate-common = { workspace = true }
+datafusion-macros = { workspace = true }
datafusion-physical-expr = { workspace = true }
datafusion-physical-expr-common = { workspace = true }
half = { workspace = true }
diff --git a/datafusion/functions-aggregate/src/approx_distinct.rs b/datafusion/functions-aggregate/src/approx_distinct.rs
index e955cea9d1..74691ba740 100644
--- a/datafusion/functions-aggregate/src/approx_distinct.rs
+++ b/datafusion/functions-aggregate/src/approx_distinct.rs
@@ -31,17 +31,19 @@ use datafusion_common::ScalarValue;
use datafusion_common::{
downcast_value, internal_err, not_impl_err, DataFusionError, Result,
};
-use datafusion_expr::aggregate_doc_sections::DOC_SECTION_APPROXIMATE;
+use datafusion_doc::DocSection;
use datafusion_expr::function::{AccumulatorArgs, StateFieldsArgs};
use datafusion_expr::utils::format_state_name;
use datafusion_expr::{
Accumulator, AggregateUDFImpl, Documentation, Signature, Volatility,
};
+use datafusion_macros::user_doc;
use std::any::Any;
use std::fmt::{Debug, Formatter};
use std::hash::Hash;
use std::marker::PhantomData;
use std::sync::OnceLock;
+
make_udaf_expr_and_func!(
ApproxDistinct,
approx_distinct,
@@ -243,6 +245,20 @@ impl Default for ApproxDistinct {
}
}
+#[user_doc(
+ doc_section(label = "Approximate Functions"),
+ description = "Returns the approximate number of distinct input values calculated using the HyperLogLog algorithm.",
+ syntax_example = "approx_distinct(expression)",
+ sql_example = r#"```sql
+> SELECT approx_distinct(column_name) FROM table_name;
++-----------------------------------+
+| approx_distinct(column_name) |
++-----------------------------------+
+| 42 |
++-----------------------------------+
+```"#,
+ standard_argument(name = "expression",)
+)]
pub struct ApproxDistinct {
signature: Signature,
}
@@ -309,25 +325,6 @@ impl AggregateUDFImpl for ApproxDistinct {
}
fn documentation(&self) -> Option<&Documentation> {
- Some(get_approx_distinct_doc())
+ self.doc()
}
}
-
-static DOCUMENTATION: OnceLock<Documentation> = OnceLock::new();
-
-fn get_approx_distinct_doc() -> &'static Documentation {
- DOCUMENTATION.get_or_init(|| {
- Documentation::builder(DOC_SECTION_APPROXIMATE, "Returns the approximate number of distinct input values calculated using the HyperLogLog algorithm.", "approx_distinct(expression)")
- .with_sql_example(r#"```sql
-> SELECT approx_distinct(column_name) FROM table_name;
-+-----------------------------------+
-| approx_distinct(column_name) |
-+-----------------------------------+
-| 42 |
-+-----------------------------------+
-```"#,
- )
- .with_standard_argument("expression", None)
- .build()
- })
-}
diff --git a/datafusion/functions-aggregate/src/approx_median.rs b/datafusion/functions-aggregate/src/approx_median.rs
index f653e94740..d4441da612 100644
--- a/datafusion/functions-aggregate/src/approx_median.rs
+++ b/datafusion/functions-aggregate/src/approx_median.rs
@@ -25,13 +25,14 @@ use arrow::{datatypes::DataType, datatypes::Field};
use arrow_schema::DataType::{Float64, UInt64};
use datafusion_common::{not_impl_err, plan_err, Result};
-use datafusion_expr::aggregate_doc_sections::DOC_SECTION_APPROXIMATE;
+use datafusion_doc::DocSection;
use datafusion_expr::function::{AccumulatorArgs, StateFieldsArgs};
use datafusion_expr::type_coercion::aggregates::NUMERICS;
use datafusion_expr::utils::format_state_name;
use datafusion_expr::{
Accumulator, AggregateUDFImpl, Documentation, Signature, Volatility,
};
+use datafusion_macros::user_doc;
use crate::approx_percentile_cont::ApproxPercentileAccumulator;
@@ -44,6 +45,20 @@ make_udaf_expr_and_func!(
);
/// APPROX_MEDIAN aggregate expression
+#[user_doc(
+ doc_section(label = "Approximate Functions"),
+ description = "Returns the approximate median (50th percentile) of input values. It is an alias of `approx_percentile_cont(x, 0.5)`.",
+ syntax_example = "approx_median(expression)",
+ sql_example = r#"```sql
+> SELECT approx_median(column_name) FROM table_name;
++-----------------------------------+
+| approx_median(column_name) |
++-----------------------------------+
+| 23.5 |
++-----------------------------------+
+```"#,
+ standard_argument(name = "expression",)
+)]
pub struct ApproxMedian {
signature: Signature,
}
@@ -122,29 +137,6 @@ impl AggregateUDFImpl for ApproxMedian {
}
fn documentation(&self) -> Option<&Documentation> {
- Some(get_approx_median_doc())
+ self.doc()
}
}
-
-static DOCUMENTATION: OnceLock<Documentation> = OnceLock::new();
-
-fn get_approx_median_doc() -> &'static Documentation {
- DOCUMENTATION.get_or_init(|| {
- Documentation::builder(
- DOC_SECTION_APPROXIMATE,
- "Returns the approximate median (50th percentile) of input values. It is an alias of `approx_percentile_cont(x, 0.5)`.",
-
- "approx_median(expression)")
- .with_sql_example(r#"```sql
-> SELECT approx_median(column_name) FROM table_name;
-+-----------------------------------+
-| approx_median(column_name) |
-+-----------------------------------+
-| 23.5 |
-+-----------------------------------+
-```"#,
- )
- .with_standard_argument("expression", None)
- .build()
- })
-}
diff --git a/datafusion/functions-aggregate/src/approx_percentile_cont.rs b/datafusion/functions-aggregate/src/approx_percentile_cont.rs
index 197c459d26..13407fecf2 100644
--- a/datafusion/functions-aggregate/src/approx_percentile_cont.rs
+++ b/datafusion/functions-aggregate/src/approx_percentile_cont.rs
@@ -35,7 +35,7 @@ use datafusion_common::{
downcast_value, internal_err, not_impl_datafusion_err, not_impl_err, plan_err,
DataFusionError, Result, ScalarValue,
};
-use datafusion_expr::aggregate_doc_sections::DOC_SECTION_APPROXIMATE;
+use datafusion_doc::DocSection;
use datafusion_expr::function::{AccumulatorArgs, StateFieldsArgs};
use datafusion_expr::type_coercion::aggregates::{INTEGERS, NUMERICS};
use datafusion_expr::utils::format_state_name;
@@ -46,6 +46,7 @@ use datafusion_expr::{
use datafusion_functions_aggregate_common::tdigest::{
TDigest, TryIntoF64, DEFAULT_MAX_SIZE,
};
+use datafusion_macros::user_doc;
use datafusion_physical_expr_common::physical_expr::PhysicalExpr;
create_func!(ApproxPercentileCont, approx_percentile_cont_udaf);
@@ -64,6 +65,28 @@ pub fn approx_percentile_cont(
approx_percentile_cont_udaf().call(args)
}
+#[user_doc(
+ doc_section(label = "Approximate Functions"),
+ description = "Returns the approximate percentile of input values using the t-digest algorithm.",
+ syntax_example = "approx_percentile_cont(expression, percentile, centroids)",
+ sql_example = r#"```sql
+> SELECT approx_percentile_cont(column_name, 0.75, 100) FROM table_name;
++-------------------------------------------------+
+| approx_percentile_cont(column_name, 0.75, 100) |
++-------------------------------------------------+
+| 65.0 |
++-------------------------------------------------+
+```"#,
+ standard_argument(name = "expression",),
+ argument(
+ name = "percentile",
+ description = "Percentile to compute. Must be a float value between 0 and 1 (inclusive)."
+ ),
+ argument(
+ name = "centroids",
+ description = "Number of centroids to use in the t-digest algorithm. _Default is 100_. A higher number results in more accurate approximation but requires more memory."
+ )
+)]
pub struct ApproxPercentileCont {
signature: Signature,
}
@@ -272,33 +295,10 @@ impl AggregateUDFImpl for ApproxPercentileCont {
}
fn documentation(&self) -> Option<&Documentation> {
- Some(get_approx_percentile_cont_doc())
+ self.doc()
}
}
-static DOCUMENTATION: OnceLock<Documentation> = OnceLock::new();
-
-fn get_approx_percentile_cont_doc() -> &'static Documentation {
- DOCUMENTATION.get_or_init(|| {
- Documentation::builder(
- DOC_SECTION_APPROXIMATE,
- "Returns the approximate percentile of input values using the t-digest algorithm.",
- "approx_percentile_cont(expression, percentile, centroids)")
- .with_sql_example(r#"```sql
-> SELECT approx_percentile_cont(column_name, 0.75, 100) FROM table_name;
-+-------------------------------------------------+
-| approx_percentile_cont(column_name, 0.75, 100) |
-+-------------------------------------------------+
-| 65.0 |
-+-------------------------------------------------+
-```"#)
- .with_standard_argument("expression", None)
- .with_argument("percentile", "Percentile to compute. Must be a float value between 0 and 1 (inclusive).")
- .with_argument("centroids", "Number of centroids to use in the t-digest algorithm. _Default is 100_. A higher number results in more accurate approximation but requires more memory.")
- .build()
- })
-}
-
#[derive(Debug)]
pub struct ApproxPercentileAccumulator {
digest: TDigest,
diff --git a/datafusion/functions-aggregate/src/approx_percentile_cont_with_weight.rs b/datafusion/functions-aggregate/src/approx_percentile_cont_with_weight.rs
index 7cf8d2dca1..485874aeb2 100644
--- a/datafusion/functions-aggregate/src/approx_percentile_cont_with_weight.rs
+++ b/datafusion/functions-aggregate/src/approx_percentile_cont_with_weight.rs
@@ -27,7 +27,7 @@ use arrow::{
use datafusion_common::ScalarValue;
use datafusion_common::{not_impl_err, plan_err, Result};
-use datafusion_expr::aggregate_doc_sections::DOC_SECTION_APPROXIMATE;
+use datafusion_doc::DocSection;
use datafusion_expr::function::{AccumulatorArgs, StateFieldsArgs};
use datafusion_expr::type_coercion::aggregates::NUMERICS;
use datafusion_expr::Volatility::Immutable;
@@ -37,6 +37,7 @@ use datafusion_expr::{
use datafusion_functions_aggregate_common::tdigest::{
Centroid, TDigest, DEFAULT_MAX_SIZE,
};
+use datafusion_macros::user_doc;
use crate::approx_percentile_cont::{ApproxPercentileAccumulator, ApproxPercentileCont};
@@ -49,6 +50,28 @@ make_udaf_expr_and_func!(
);
/// APPROX_PERCENTILE_CONT_WITH_WEIGHT aggregate expression
+#[user_doc(
+ doc_section(label = "Approximate Functions"),
+ description = "Returns the weighted approximate percentile of input values using the t-digest algorithm.",
+ syntax_example = "approx_percentile_cont_with_weight(expression, weight, percentile)",
+ sql_example = r#"```sql
+> SELECT approx_percentile_cont_with_weight(column_name, weight_column, 0.90) FROM table_name;
++----------------------------------------------------------------------+
+| approx_percentile_cont_with_weight(column_name, weight_column, 0.90) |
++----------------------------------------------------------------------+
+| 78.5 |
++----------------------------------------------------------------------+
+```"#,
+ standard_argument(name = "expression", prefix = "The"),
+ argument(
+ name = "weight",
+ description = "Expression to use as weight. Can be a constant, column, or function, and any combination of arithmetic operators."
+ ),
+ argument(
+ name = "percentile",
+ description = "Percentile to compute. Must be a float value between 0 and 1 (inclusive)."
+ )
+)]
pub struct ApproxPercentileContWithWeight {
signature: Signature,
approx_percentile_cont: ApproxPercentileCont,
@@ -157,35 +180,10 @@ impl AggregateUDFImpl for ApproxPercentileContWithWeight {
}
fn documentation(&self) -> Option<&Documentation> {
- Some(get_approx_percentile_cont_with_weight_doc())
+ self.doc()
}
}
-static DOCUMENTATION: OnceLock<Documentation> = OnceLock::new();
-
-fn get_approx_percentile_cont_with_weight_doc() -> &'static Documentation {
- DOCUMENTATION.get_or_init(|| {
- Documentation::builder(
- DOC_SECTION_APPROXIMATE,
- "Returns the weighted approximate percentile of input values using the t-digest algorithm.",
-
- "approx_percentile_cont_with_weight(expression, weight, percentile)")
- .with_sql_example(r#"```sql
-> SELECT approx_percentile_cont_with_weight(column_name, weight_column, 0.90) FROM table_name;
-+----------------------------------------------------------------------+
-| approx_percentile_cont_with_weight(column_name, weight_column, 0.90) |
-+----------------------------------------------------------------------+
-| 78.5 |
-+----------------------------------------------------------------------+
-```"#,
- )
- .with_standard_argument("expression", None)
- .with_argument("weight", "Expression to use as weight. Can be a constant, column, or function, and any combination of arithmetic operators.")
- .with_argument("percentile", "Percentile to compute. Must be a float value between 0 and 1 (inclusive).")
- .build()
- })
-}
-
#[derive(Debug)]
pub struct ApproxPercentileWithWeightAccumulator {
approx_percentile_cont_accumulator: ApproxPercentileAccumulator,
diff --git a/datafusion/functions-aggregate/src/array_agg.rs b/datafusion/functions-aggregate/src/array_agg.rs
index 6344dbcd93..98530a9fc2 100644
--- a/datafusion/functions-aggregate/src/array_agg.rs
+++ b/datafusion/functions-aggregate/src/array_agg.rs
@@ -25,13 +25,14 @@ use datafusion_common::cast::as_list_array;
use datafusion_common::utils::{get_row_at_idx, SingleRowListArrayBuilder};
use datafusion_common::{exec_err, ScalarValue};
use datafusion_common::{internal_err, Result};
-use datafusion_expr::aggregate_doc_sections::DOC_SECTION_GENERAL;
+use datafusion_doc::DocSection;
use datafusion_expr::function::{AccumulatorArgs, StateFieldsArgs};
use datafusion_expr::utils::format_state_name;
use datafusion_expr::{Accumulator, Signature, Volatility};
use datafusion_expr::{AggregateUDFImpl, Documentation};
use datafusion_functions_aggregate_common::merge_arrays::merge_ordered_arrays;
use datafusion_functions_aggregate_common::utils::ordering_fields;
+use datafusion_macros::user_doc;
use datafusion_physical_expr_common::sort_expr::{LexOrdering, PhysicalSortExpr};
use std::collections::{HashSet, VecDeque};
use std::mem::{size_of, size_of_val};
@@ -45,6 +46,20 @@ make_udaf_expr_and_func!(
array_agg_udaf
);
+#[user_doc(
+ doc_section(label = "General Functions"),
+ description = "Returns an array created from the expression elements. If ordering is required, elements are inserted in the specified order.",
+ syntax_example = "array_agg(expression [ORDER BY expression])",
+ sql_example = r#"```sql
+> SELECT array_agg(column_name ORDER BY other_column) FROM table_name;
++-----------------------------------------------+
+| array_agg(column_name ORDER BY other_column) |
++-----------------------------------------------+
+| [element1, element2, element3] |
++-----------------------------------------------+
+```"#,
+ standard_argument(name = "expression",)
+)]
#[derive(Debug)]
/// ARRAY_AGG aggregate expression
pub struct ArrayAgg {
@@ -145,33 +160,10 @@ impl AggregateUDFImpl for ArrayAgg {
}
fn documentation(&self) -> Option<&Documentation> {
- Some(get_array_agg_doc())
+ self.doc()
}
}
-static DOCUMENTATION: OnceLock<Documentation> = OnceLock::new();
-
-fn get_array_agg_doc() -> &'static Documentation {
- DOCUMENTATION.get_or_init(|| {
- Documentation::builder(
- DOC_SECTION_GENERAL,
- "Returns an array created from the expression elements. If ordering is required, elements are inserted in the specified order.",
-
- "array_agg(expression [ORDER BY expression])")
- .with_sql_example(r#"```sql
-> SELECT array_agg(column_name ORDER BY other_column) FROM table_name;
-+-----------------------------------------------+
-| array_agg(column_name ORDER BY other_column) |
-+-----------------------------------------------+
-| [element1, element2, element3] |
-+-----------------------------------------------+
-```"#,
- )
- .with_standard_argument("expression", None)
- .build()
- })
-}
-
#[derive(Debug)]
pub struct ArrayAggAccumulator {
values: Vec<ArrayRef>,
diff --git a/datafusion/functions-aggregate/src/average.rs b/datafusion/functions-aggregate/src/average.rs
index 3fa58f3c20..65ca441517 100644
--- a/datafusion/functions-aggregate/src/average.rs
+++ b/datafusion/functions-aggregate/src/average.rs
@@ -28,7 +28,6 @@ use arrow::datatypes::{
Float64Type, UInt64Type,
};
use datafusion_common::{exec_err, not_impl_err, Result, ScalarValue};
-use datafusion_expr::aggregate_doc_sections::DOC_SECTION_GENERAL;
use datafusion_expr::function::{AccumulatorArgs, StateFieldsArgs};
use datafusion_expr::type_coercion::aggregates::{avg_return_type, coerce_avg_type};
use datafusion_expr::utils::format_state_name;
@@ -43,7 +42,9 @@ use datafusion_functions_aggregate_common::aggregate::groups_accumulator::nulls:
filtered_null_mask, set_nulls,
};
+use datafusion_doc::DocSection;
use datafusion_functions_aggregate_common::utils::DecimalAverager;
+use datafusion_macros::user_doc;
use log::debug;
use std::any::Any;
use std::fmt::Debug;
@@ -58,6 +59,20 @@ make_udaf_expr_and_func!(
avg_udaf
);
+#[user_doc(
+ doc_section(label = "General Functions"),
+ description = "Returns the average of numeric values in the specified column.",
+ syntax_example = "avg(expression)",
+ sql_example = r#"```sql
+> SELECT avg(column_name) FROM table_name;
++---------------------------+
+| avg(column_name) |
++---------------------------+
+| 42.75 |
++---------------------------+
+```"#,
+ standard_argument(name = "expression",)
+)]
#[derive(Debug)]
pub struct Avg {
signature: Signature,
@@ -240,34 +255,10 @@ impl AggregateUDFImpl for Avg {
}
fn documentation(&self) -> Option<&Documentation> {
- Some(get_avg_doc())
+ self.doc()
}
}
-static DOCUMENTATION: OnceLock<Documentation> = OnceLock::new();
-
-fn get_avg_doc() -> &'static Documentation {
- DOCUMENTATION.get_or_init(|| {
- Documentation::builder(
- DOC_SECTION_GENERAL,
- "Returns the average of numeric values in the specified column.",
- "avg(expression)",
- )
- .with_sql_example(
- r#"```sql
-> SELECT avg(column_name) FROM table_name;
-+---------------------------+
-| avg(column_name) |
-+---------------------------+
-| 42.75 |
-+---------------------------+
-```"#,
- )
- .with_standard_argument("expression", None)
- .build()
- })
-}
-
/// An accumulator to compute the average
#[derive(Debug, Default)]
pub struct AvgAccumulator {
diff --git a/datafusion/functions-aggregate/src/bool_and_or.rs b/datafusion/functions-aggregate/src/bool_and_or.rs
index df9271d816..1b5b20f43b 100644
--- a/datafusion/functions-aggregate/src/bool_and_or.rs
+++ b/datafusion/functions-aggregate/src/bool_and_or.rs
@@ -31,7 +31,6 @@ use arrow::datatypes::Field;
use datafusion_common::internal_err;
use datafusion_common::{downcast_value, not_impl_err};
use datafusion_common::{DataFusionError, Result, ScalarValue};
-use datafusion_expr::aggregate_doc_sections::DOC_SECTION_GENERAL;
use datafusion_expr::function::{AccumulatorArgs, StateFieldsArgs};
use datafusion_expr::utils::{format_state_name, AggregateOrderSensitivity};
use datafusion_expr::{
@@ -39,7 +38,9 @@ use datafusion_expr::{
Signature, Volatility,
};
+use datafusion_doc::DocSection;
use datafusion_functions_aggregate_common::aggregate::groups_accumulator::bool_op::BooleanGroupsAccumulator;
+use datafusion_macros::user_doc;
// returns the new value after bool_and/bool_or with the new values, taking nullability into account
macro_rules! typed_bool_and_or_batch {
@@ -92,6 +93,20 @@ make_udaf_expr_and_func!(
bool_or_udaf
);
+#[user_doc(
+ doc_section(label = "General Functions"),
+ description = "Returns true if all non-null input values are true, otherwise false.",
+ syntax_example = "bool_and(expression)",
+ sql_example = r#"```sql
+> SELECT bool_and(column_name) FROM table_name;
++----------------------------+
+| bool_and(column_name) |
++----------------------------+
+| true |
++----------------------------+
+```"#,
+ standard_argument(name = "expression", prefix = "The")
+)]
/// BOOL_AND aggregate expression
#[derive(Debug)]
pub struct BoolAnd {
@@ -178,34 +193,10 @@ impl AggregateUDFImpl for BoolAnd {
}
fn documentation(&self) -> Option<&Documentation> {
- Some(get_bool_and_doc())
+ self.doc()
}
}
-static DOCUMENTATION: OnceLock<Documentation> = OnceLock::new();
-
-fn get_bool_and_doc() -> &'static Documentation {
- DOCUMENTATION.get_or_init(|| {
- Documentation::builder(
- DOC_SECTION_GENERAL,
- "Returns true if all non-null input values are true, otherwise false.",
- "bool_and(expression)",
- )
- .with_sql_example(
- r#"```sql
-> SELECT bool_and(column_name) FROM table_name;
-+----------------------------+
-| bool_and(column_name) |
-+----------------------------+
-| true |
-+----------------------------+
-```"#,
- )
- .with_standard_argument("expression", None)
- .build()
- })
-}
-
#[derive(Debug, Default)]
struct BoolAndAccumulator {
acc: Option<bool>,
@@ -240,6 +231,20 @@ impl Accumulator for BoolAndAccumulator {
}
}
+#[user_doc(
+ doc_section(label = "General Functions"),
+ description = "Returns true if all non-null input values are true, otherwise false.",
+ syntax_example = "bool_and(expression)",
+ sql_example = r#"```sql
+> SELECT bool_and(column_name) FROM table_name;
++----------------------------+
+| bool_and(column_name) |
++----------------------------+
+| true |
++----------------------------+
+```"#,
+ standard_argument(name = "expression", prefix = "The")
+)]
/// BOOL_OR aggregate expression
#[derive(Debug, Clone)]
pub struct BoolOr {
@@ -327,32 +332,10 @@ impl AggregateUDFImpl for BoolOr {
}
fn documentation(&self) -> Option<&Documentation> {
- Some(get_bool_or_doc())
+ self.doc()
}
}
-fn get_bool_or_doc() -> &'static Documentation {
- DOCUMENTATION.get_or_init(|| {
- Documentation::builder(
- DOC_SECTION_GENERAL,
- "Returns true if any non-null input value is true, otherwise false.",
- "bool_or(expression)",
- )
- .with_sql_example(
- r#"```sql
-> SELECT bool_or(column_name) FROM table_name;
-+----------------------------+
-| bool_or(column_name) |
-+----------------------------+
-| true |
-+----------------------------+
-```"#,
- )
- .with_standard_argument("expression", None)
- .build()
- })
-}
-
#[derive(Debug, Default)]
struct BoolOrAccumulator {
acc: Option<bool>,
diff --git a/datafusion/functions-aggregate/src/correlation.rs b/datafusion/functions-aggregate/src/correlation.rs
index 4711b42407..b40555bf6c 100644
--- a/datafusion/functions-aggregate/src/correlation.rs
+++ b/datafusion/functions-aggregate/src/correlation.rs
@@ -31,7 +31,7 @@ use arrow::{
use crate::covariance::CovarianceAccumulator;
use crate::stddev::StddevAccumulator;
use datafusion_common::{plan_err, Result, ScalarValue};
-use datafusion_expr::aggregate_doc_sections::DOC_SECTION_STATISTICAL;
+use datafusion_doc::DocSection;
use datafusion_expr::{
function::{AccumulatorArgs, StateFieldsArgs},
type_coercion::aggregates::NUMERICS,
@@ -39,6 +39,7 @@ use datafusion_expr::{
Accumulator, AggregateUDFImpl, Documentation, Signature, Volatility,
};
use datafusion_functions_aggregate_common::stats::StatsType;
+use datafusion_macros::user_doc;
make_udaf_expr_and_func!(
Correlation,
@@ -48,6 +49,21 @@ make_udaf_expr_and_func!(
corr_udaf
);
+#[user_doc(
+ doc_section(label = "Statistical Functions"),
+ description = "Returns the coefficient of correlation between two numeric values.",
+ syntax_example = "corr(expression1, expression2)",
+ sql_example = r#"```sql
+> SELECT corr(column1, column2) FROM table_name;
++--------------------------------+
+| corr(column1, column2) |
++--------------------------------+
+| 0.85 |
++--------------------------------+
+```"#,
+ standard_argument(name = "expression1", prefix = "First"),
+ standard_argument(name = "expression2", prefix = "Second")
+)]
#[derive(Debug)]
pub struct Correlation {
signature: Signature,
@@ -111,35 +127,10 @@ impl AggregateUDFImpl for Correlation {
}
fn documentation(&self) -> Option<&Documentation> {
- Some(get_corr_doc())
+ self.doc()
}
}
-static DOCUMENTATION: OnceLock<Documentation> = OnceLock::new();
-
-fn get_corr_doc() -> &'static Documentation {
- DOCUMENTATION.get_or_init(|| {
- Documentation::builder(
- DOC_SECTION_STATISTICAL,
- "Returns the coefficient of correlation between two numeric values.",
- "corr(expression1, expression2)",
- )
- .with_sql_example(
- r#"```sql
-> SELECT corr(column1, column2) FROM table_name;
-+--------------------------------+
-| corr(column1, column2) |
-+--------------------------------+
-| 0.85 |
-+--------------------------------+
-```"#,
- )
- .with_standard_argument("expression1", Some("First"))
- .with_standard_argument("expression2", Some("Second"))
- .build()
- })
-}
-
/// An accumulator to compute correlation
#[derive(Debug)]
pub struct CorrelationAccumulator {
diff --git a/datafusion/functions-aggregate/src/count.rs b/datafusion/functions-aggregate/src/count.rs
index a191f7bad4..550df8cb4f 100644
--- a/datafusion/functions-aggregate/src/count.rs
+++ b/datafusion/functions-aggregate/src/count.rs
@@ -17,7 +17,9 @@
use ahash::RandomState;
use datafusion_common::stats::Precision;
+use datafusion_doc::DocSection;
use datafusion_functions_aggregate_common::aggregate::count_distinct::BytesViewDistinctCountAccumulator;
+use datafusion_macros::user_doc;
use datafusion_physical_expr::expressions;
use std::collections::HashSet;
use std::fmt::Debug;
@@ -45,7 +47,6 @@ use arrow::{
use datafusion_common::{
downcast_value, internal_err, not_impl_err, DataFusionError, Result, ScalarValue,
};
-use datafusion_expr::aggregate_doc_sections::DOC_SECTION_GENERAL;
use datafusion_expr::function::StateFieldsArgs;
use datafusion_expr::{
function::AccumulatorArgs, utils::format_state_name, Accumulator, AggregateUDFImpl,
@@ -79,6 +80,27 @@ pub fn count_distinct(expr: Expr) -> Expr {
))
}
+#[user_doc(
+ doc_section(label = "General Functions"),
+ description = "Returns the number of non-null values in the specified column. To include null values in the total count, use `count(*)`.",
+ syntax_example = "count(expression)",
+ sql_example = r#"```sql
+> SELECT count(column_name) FROM table_name;
++-----------------------+
+| count(column_name) |
++-----------------------+
+| 100 |
++-----------------------+
+
+> SELECT count(*) FROM table_name;
++------------------+
+| count(*) |
++------------------+
+| 120 |
++------------------+
+```"#,
+ standard_argument(name = "expression",)
+)]
pub struct Count {
signature: Signature,
}
@@ -328,39 +350,10 @@ impl AggregateUDFImpl for Count {
}
fn documentation(&self) -> Option<&Documentation> {
- Some(get_count_doc())
+ self.doc()
}
}
-static DOCUMENTATION: OnceLock<Documentation> = OnceLock::new();
-
-fn get_count_doc() -> &'static Documentation {
- DOCUMENTATION.get_or_init(|| {
- Documentation::builder(
- DOC_SECTION_GENERAL,
- "Returns the number of non-null values in the specified column. To include null values in the total count, use `count(*)`.",
-
- "count(expression)")
- .with_sql_example(r#"```sql
-> SELECT count(column_name) FROM table_name;
-+-----------------------+
-| count(column_name) |
-+-----------------------+
-| 100 |
-+-----------------------+
-
-> SELECT count(*) FROM table_name;
-+------------------+
-| count(*) |
-+------------------+
-| 120 |
-+------------------+
-```"#)
- .with_standard_argument("expression", None)
- .build()
- })
-}
-
#[derive(Debug)]
struct CountAccumulator {
count: i64,
diff --git a/datafusion/functions-aggregate/src/covariance.rs b/datafusion/functions-aggregate/src/covariance.rs
index 0c29589e90..adb546e4d9 100644
--- a/datafusion/functions-aggregate/src/covariance.rs
+++ b/datafusion/functions-aggregate/src/covariance.rs
@@ -31,7 +31,7 @@ use datafusion_common::{
downcast_value, plan_err, unwrap_or_internal_err, DataFusionError, Result,
ScalarValue,
};
-use datafusion_expr::aggregate_doc_sections::DOC_SECTION_STATISTICAL;
+use datafusion_doc::DocSection;
use datafusion_expr::{
function::{AccumulatorArgs, StateFieldsArgs},
type_coercion::aggregates::NUMERICS,
@@ -39,6 +39,7 @@ use datafusion_expr::{
Accumulator, AggregateUDFImpl, Documentation, Signature, Volatility,
};
use datafusion_functions_aggregate_common::stats::StatsType;
+use datafusion_macros::user_doc;
make_udaf_expr_and_func!(
CovarianceSample,
@@ -56,6 +57,21 @@ make_udaf_expr_and_func!(
covar_pop_udaf
);
+#[user_doc(
+ doc_section(label = "Statistical Functions"),
+ description = "Returns the sample covariance of a set of number pairs.",
+ syntax_example = "covar_samp(expression1, expression2)",
+ sql_example = r#"```sql
+> SELECT covar_samp(column1, column2) FROM table_name;
++-----------------------------------+
+| covar_samp(column1, column2) |
++-----------------------------------+
+| 8.25 |
++-----------------------------------+
+```"#,
+ standard_argument(name = "expression1", prefix = "First"),
+ standard_argument(name = "expression2", prefix = "Second")
+)]
pub struct CovarianceSample {
signature: Signature,
aliases: Vec<String>,
@@ -129,21 +145,15 @@ impl AggregateUDFImpl for CovarianceSample {
}
fn documentation(&self) -> Option<&Documentation> {
- Some(get_covar_samp_doc())
+ self.doc()
}
}
-static DOCUMENTATION: OnceLock<Documentation> = OnceLock::new();
-
-fn get_covar_samp_doc() -> &'static Documentation {
- DOCUMENTATION.get_or_init(|| {
- Documentation::builder(
- DOC_SECTION_STATISTICAL,
- "Returns the sample covariance of a set of number pairs.",
- "covar_samp(expression1, expression2)",
- )
- .with_sql_example(
- r#"```sql
+#[user_doc(
+ doc_section(label = "Statistical Functions"),
+ description = "Returns the sample covariance of a set of number pairs.",
+ syntax_example = "covar_samp(expression1, expression2)",
+ sql_example = r#"```sql
> SELECT covar_samp(column1, column2) FROM table_name;
+-----------------------------------+
| covar_samp(column1, column2) |
@@ -151,13 +161,9 @@ fn get_covar_samp_doc() -> &'static Documentation {
| 8.25 |
+-----------------------------------+
```"#,
- )
- .with_standard_argument("expression1", Some("First"))
- .with_standard_argument("expression2", Some("Second"))
- .build()
- })
-}
-
+ standard_argument(name = "expression1", prefix = "First"),
+ standard_argument(name = "expression2", prefix = "Second")
+)]
pub struct CovariancePopulation {
signature: Signature,
}
@@ -227,33 +233,10 @@ impl AggregateUDFImpl for CovariancePopulation {
}
fn documentation(&self) -> Option<&Documentation> {
- Some(get_covar_pop_doc())
+ self.doc()
}
}
-fn get_covar_pop_doc() -> &'static Documentation {
- DOCUMENTATION.get_or_init(|| {
- Documentation::builder(
- DOC_SECTION_STATISTICAL,
- "Returns the population covariance of a set of number pairs.",
- "covar_pop(expression1, expression2)",
- )
- .with_sql_example(
- r#"```sql
-> SELECT covar_pop(column1, column2) FROM table_name;
-+-----------------------------------+
-| covar_pop(column1, column2) |
-+-----------------------------------+
-| 7.63 |
-+-----------------------------------+
-```"#,
- )
- .with_standard_argument("expression1", Some("First"))
- .with_standard_argument("expression2", Some("Second"))
- .build()
- })
-}
-
/// An accumulator to compute covariance
/// The algorithm used is an online implementation and numerically stable. It is derived from the following paper
/// for calculating variance:
diff --git a/datafusion/functions-aggregate/src/first_last.rs b/datafusion/functions-aggregate/src/first_last.rs
index b7001f52ac..f3e66edbc0 100644
--- a/datafusion/functions-aggregate/src/first_last.rs
+++ b/datafusion/functions-aggregate/src/first_last.rs
@@ -29,7 +29,7 @@ use datafusion_common::utils::{compare_rows, get_row_at_idx};
use datafusion_common::{
arrow_datafusion_err, internal_err, DataFusionError, Result, ScalarValue,
};
-use datafusion_expr::aggregate_doc_sections::DOC_SECTION_GENERAL;
+use datafusion_doc::DocSection;
use datafusion_expr::function::{AccumulatorArgs, StateFieldsArgs};
use datafusion_expr::utils::{format_state_name, AggregateOrderSensitivity};
use datafusion_expr::{
@@ -37,6 +37,7 @@ use datafusion_expr::{
SortExpr, Volatility,
};
use datafusion_functions_aggregate_common::utils::get_sort_options;
+use datafusion_macros::user_doc;
use datafusion_physical_expr_common::sort_expr::LexOrdering;
create_func!(FirstValue, first_value_udaf);
@@ -55,6 +56,20 @@ pub fn first_value(expression: Expr, order_by: Option<Vec<SortExpr>>) -> Expr {
}
}
+#[user_doc(
+ doc_section(label = "General Functions"),
+ description = "Returns the first element in an aggregation group according to the requested ordering. If no ordering is given, returns an arbitrary element from the group.",
+ syntax_example = "first_value(expression [ORDER BY expression])",
+ sql_example = r#"```sql
+> SELECT first_value(column_name ORDER BY other_column) FROM table_name;
++-----------------------------------------------+
+| first_value(column_name ORDER BY other_column)|
++-----------------------------------------------+
+| first_element |
++-----------------------------------------------+
+```"#,
+ standard_argument(name = "expression",)
+)]
pub struct FirstValue {
signature: Signature,
requirement_satisfied: bool,
@@ -161,33 +176,10 @@ impl AggregateUDFImpl for FirstValue {
}
fn documentation(&self) -> Option<&Documentation> {
- Some(get_first_value_doc())
+ self.doc()
}
}
-static DOCUMENTATION: OnceLock<Documentation> = OnceLock::new();
-
-fn get_first_value_doc() -> &'static Documentation {
- DOCUMENTATION.get_or_init(|| {
- Documentation::builder(
- DOC_SECTION_GENERAL,
- "Returns the first element in an aggregation group according to the requested ordering. If no ordering is given, returns an arbitrary element from the group.",
-
- "first_value(expression [ORDER BY expression])")
- .with_sql_example(r#"```sql
-> SELECT first_value(column_name ORDER BY other_column) FROM table_name;
-+-----------------------------------------------+
-| first_value(column_name ORDER BY other_column)|
-+-----------------------------------------------+
-| first_element |
-+-----------------------------------------------+
-```"#,
- )
- .with_standard_argument("expression", None)
- .build()
- })
-}
-
#[derive(Debug)]
pub struct FirstValueAccumulator {
first: ScalarValue,
@@ -372,6 +364,20 @@ make_udaf_expr_and_func!(
last_value_udaf
);
+#[user_doc(
+ doc_section(label = "General Functions"),
+ description = "Returns the last element in an aggregation group according to the requested ordering. If no ordering is given, returns an arbitrary element from the group.",
+ syntax_example = "last_value(expression [ORDER BY expression])",
+ sql_example = r#"```sql
+> SELECT last_value(column_name ORDER BY other_column) FROM table_name;
++-----------------------------------------------+
+| last_value(column_name ORDER BY other_column) |
++-----------------------------------------------+
+| last_element |
++-----------------------------------------------+
+```"#,
+ standard_argument(name = "expression",)
+)]
pub struct LastValue {
signature: Signature,
requirement_satisfied: bool,
@@ -483,31 +489,10 @@ impl AggregateUDFImpl for LastValue {
}
fn documentation(&self) -> Option<&Documentation> {
- Some(get_last_value_doc())
+ self.doc()
}
}
-fn get_last_value_doc() -> &'static Documentation {
- DOCUMENTATION.get_or_init(|| {
- Documentation::builder(
- DOC_SECTION_GENERAL,
- "Returns the last element in an aggregation group according to the requested ordering. If no ordering is given, returns an arbitrary element from the group.",
-
- "last_value(expression [ORDER BY expression])")
- .with_sql_example(r#"```sql
-> SELECT last_value(column_name ORDER BY other_column) FROM table_name;
-+-----------------------------------------------+
-| last_value(column_name ORDER BY other_column) |
-+-----------------------------------------------+
-| last_element |
-+-----------------------------------------------+
-```"#,
- )
- .with_standard_argument("expression", None)
- .build()
- })
-}
-
#[derive(Debug)]
struct LastValueAccumulator {
last: ScalarValue,
diff --git a/datafusion/functions-aggregate/src/grouping.rs b/datafusion/functions-aggregate/src/grouping.rs
index 4a45890b0e..36bdf68c1b 100644
--- a/datafusion/functions-aggregate/src/grouping.rs
+++ b/datafusion/functions-aggregate/src/grouping.rs
@@ -24,13 +24,14 @@ use std::sync::OnceLock;
use arrow::datatypes::DataType;
use arrow::datatypes::Field;
use datafusion_common::{not_impl_err, Result};
-use datafusion_expr::aggregate_doc_sections::DOC_SECTION_GENERAL;
+use datafusion_doc::DocSection;
use datafusion_expr::function::AccumulatorArgs;
use datafusion_expr::function::StateFieldsArgs;
use datafusion_expr::utils::format_state_name;
use datafusion_expr::{
Accumulator, AggregateUDFImpl, Documentation, Signature, Volatility,
};
+use datafusion_macros::user_doc;
make_udaf_expr_and_func!(
Grouping,
@@ -40,6 +41,27 @@ make_udaf_expr_and_func!(
grouping_udaf
);
+#[user_doc(
+ doc_section(label = "General Functions"),
+ description = "Returns 1 if the data is aggregated across the specified column, or 0 if it is not aggregated in the result set.",
+ syntax_example = "grouping(expression)",
+ sql_example = r#"```sql
+> SELECT column_name, GROUPING(column_name) AS group_column
+ FROM table_name
+ GROUP BY GROUPING SETS ((column_name), ());
++-------------+-------------+
+| column_name | group_column |
++-------------+-------------+
+| value1 | 0 |
+| value2 | 0 |
+| NULL | 1 |
++-------------+-------------+
+```"#,
+ argument(
+ name = "expression",
+ description = "Expression to evaluate whether data is aggregated across the specified column. Can be a constant, column, or function."
+ )
+)]
pub struct Grouping {
signature: Signature,
}
@@ -100,33 +122,6 @@ impl AggregateUDFImpl for Grouping {
}
fn documentation(&self) -> Option<&Documentation> {
- Some(get_grouping_doc())
+ self.doc()
}
}
-
-static DOCUMENTATION: OnceLock<Documentation> = OnceLock::new();
-
-fn get_grouping_doc() -> &'static Documentation {
- DOCUMENTATION.get_or_init(|| {
- Documentation::builder(
- DOC_SECTION_GENERAL,
- "Returns 1 if the data is aggregated across the specified column, or 0 if it is not aggregated in the result set.",
-
- "grouping(expression)")
- .with_sql_example(r#"```sql
-> SELECT column_name, GROUPING(column_name) AS group_column
- FROM table_name
- GROUP BY GROUPING SETS ((column_name), ());
-+-------------+-------------+
-| column_name | group_column |
-+-------------+-------------+
-| value1 | 0 |
-| value2 | 0 |
-| NULL | 1 |
-+-------------+-------------+
-```"#,
- )
- .with_argument("expression", "Expression to evaluate whether data is aggregated across the specified column. Can be a constant, column, or function.")
- .build()
- })
-}
diff --git a/datafusion/functions-aggregate/src/median.rs b/datafusion/functions-aggregate/src/median.rs
index 0fd9d4ca63..db5fbf0016 100644
--- a/datafusion/functions-aggregate/src/median.rs
+++ b/datafusion/functions-aggregate/src/median.rs
@@ -34,13 +34,14 @@ use arrow::array::ArrowNativeTypeOp;
use arrow::datatypes::{ArrowNativeType, ArrowPrimitiveType};
use datafusion_common::{DataFusionError, HashSet, Result, ScalarValue};
-use datafusion_expr::aggregate_doc_sections::DOC_SECTION_GENERAL;
+use datafusion_doc::DocSection;
use datafusion_expr::function::StateFieldsArgs;
use datafusion_expr::{
function::AccumulatorArgs, utils::format_state_name, Accumulator, AggregateUDFImpl,
Documentation, Signature, Volatility,
};
use datafusion_functions_aggregate_common::utils::Hashable;
+use datafusion_macros::user_doc;
make_udaf_expr_and_func!(
Median,
@@ -50,6 +51,20 @@ make_udaf_expr_and_func!(
median_udaf
);
+#[user_doc(
+ doc_section(label = "General Functions"),
+ description = "Returns the median value in the specified column.",
+ syntax_example = "median(expression)",
+ sql_example = r#"```sql
+> SELECT median(column_name) FROM table_name;
++----------------------+
+| median(column_name) |
++----------------------+
+| 45.5 |
++----------------------+
+```"#,
+ standard_argument(name = "expression", prefix = "The")
+)]
/// MEDIAN aggregate expression. If using the non-distinct variation, then this uses a
/// lot of memory because all values need to be stored in memory before a result can be
/// computed. If an approximation is sufficient then APPROX_MEDIAN provides a much more
@@ -156,34 +171,10 @@ impl AggregateUDFImpl for Median {
}
fn documentation(&self) -> Option<&Documentation> {
- Some(get_median_doc())
+ self.doc()
}
}
-static DOCUMENTATION: OnceLock<Documentation> = OnceLock::new();
-
-fn get_median_doc() -> &'static Documentation {
- DOCUMENTATION.get_or_init(|| {
- Documentation::builder(
- DOC_SECTION_GENERAL,
- "Returns the median value in the specified column.",
- "median(expression)",
- )
- .with_sql_example(
- r#"```sql
-> SELECT median(column_name) FROM table_name;
-+----------------------+
-| median(column_name) |
-+----------------------+
-| 45.5 |
-+----------------------+
-```"#,
- )
- .with_standard_argument("expression", None)
- .build()
- })
-}
-
/// The median accumulator accumulates the raw input values
/// as `ScalarValue`s
///
diff --git a/datafusion/functions-aggregate/src/min_max.rs b/datafusion/functions-aggregate/src/min_max.rs
index 2077f15674..acbeebaad6 100644
--- a/datafusion/functions-aggregate/src/min_max.rs
+++ b/datafusion/functions-aggregate/src/min_max.rs
@@ -41,7 +41,6 @@ use datafusion_common::stats::Precision;
use datafusion_common::{
downcast_value, exec_err, internal_err, ColumnStatistics, DataFusionError, Result,
};
-use datafusion_expr::aggregate_doc_sections::DOC_SECTION_GENERAL;
use datafusion_functions_aggregate_common::aggregate::groups_accumulator::prim_op::PrimitiveGroupsAccumulator;
use datafusion_physical_expr::expressions;
use std::cmp::Ordering;
@@ -56,11 +55,13 @@ use arrow::datatypes::{
use crate::min_max::min_max_bytes::MinMaxBytesAccumulator;
use datafusion_common::ScalarValue;
+use datafusion_doc::DocSection;
use datafusion_expr::{
function::AccumulatorArgs, Accumulator, AggregateUDFImpl, Documentation, Signature,
Volatility,
};
use datafusion_expr::{GroupsAccumulator, StatisticsArgs};
+use datafusion_macros::user_doc;
use half::f16;
use std::mem::size_of_val;
use std::ops::Deref;
@@ -87,6 +88,20 @@ fn get_min_max_result_type(input_types: &[DataType]) -> Result<Vec<DataType>> {
}
}
+#[user_doc(
+ doc_section(label = "General Functions"),
+ description = "Returns the maximum value in the specified column.",
+ syntax_example = "max(expression)",
+ sql_example = r#"```sql
+> SELECT max(column_name) FROM table_name;
++----------------------+
+| max(column_name) |
++----------------------+
+| 150 |
++----------------------+
+```"#,
+ standard_argument(name = "expression",)
+)]
// MAX aggregate UDF
#[derive(Debug)]
pub struct Max {
@@ -346,34 +361,10 @@ impl AggregateUDFImpl for Max {
}
fn documentation(&self) -> Option<&Documentation> {
- Some(get_max_doc())
+ self.doc()
}
}
-static DOCUMENTATION: OnceLock<Documentation> = OnceLock::new();
-
-fn get_max_doc() -> &'static Documentation {
- DOCUMENTATION.get_or_init(|| {
- Documentation::builder(
- DOC_SECTION_GENERAL,
- "Returns the maximum value in the specified column.",
- "max(expression)",
- )
- .with_sql_example(
- r#"```sql
-> SELECT max(column_name) FROM table_name;
-+----------------------+
-| max(column_name) |
-+----------------------+
-| 150 |
-+----------------------+
-```"#,
- )
- .with_standard_argument("expression", None)
- .build()
- })
-}
-
// Statically-typed version of min/max(array) -> ScalarValue for string types
macro_rules! typed_min_max_batch_string {
($VALUES:expr, $ARRAYTYPE:ident, $SCALAR:ident, $OP:ident) => {{
@@ -997,6 +988,20 @@ impl Accumulator for SlidingMaxAccumulator {
}
}
+#[user_doc(
+ doc_section(label = "General Functions"),
+ description = "Returns the minimum value in the specified column.",
+ syntax_example = "min(expression)",
+ sql_example = r#"```sql
+> SELECT min(column_name) FROM table_name;
++----------------------+
+| min(column_name) |
++----------------------+
+| 12 |
++----------------------+
+```"#,
+ standard_argument(name = "expression",)
+)]
#[derive(Debug)]
pub struct Min {
signature: Signature,
@@ -1178,32 +1183,10 @@ impl AggregateUDFImpl for Min {
}
fn documentation(&self) -> Option<&Documentation> {
- Some(get_min_doc())
+ self.doc()
}
}
-fn get_min_doc() -> &'static Documentation {
- DOCUMENTATION.get_or_init(|| {
- Documentation::builder(
- DOC_SECTION_GENERAL,
- "Returns the minimum value in the specified column.",
- "min(expression)",
- )
- .with_sql_example(
- r#"```sql
-> SELECT min(column_name) FROM table_name;
-+----------------------+
-| min(column_name) |
-+----------------------+
-| 12 |
-+----------------------+
-```"#,
- )
- .with_standard_argument("expression", None)
- .build()
- })
-}
-
/// An accumulator to compute the minimum value
#[derive(Debug)]
pub struct MinAccumulator {
diff --git a/datafusion/functions-aggregate/src/nth_value.rs b/datafusion/functions-aggregate/src/nth_value.rs
index d1a3a00763..15b9e97516 100644
--- a/datafusion/functions-aggregate/src/nth_value.rs
+++ b/datafusion/functions-aggregate/src/nth_value.rs
@@ -28,7 +28,7 @@ use arrow_schema::{DataType, Field, Fields};
use datafusion_common::utils::{get_row_at_idx, SingleRowListArrayBuilder};
use datafusion_common::{exec_err, internal_err, not_impl_err, Result, ScalarValue};
-use datafusion_expr::aggregate_doc_sections::DOC_SECTION_STATISTICAL;
+use datafusion_doc::DocSection;
use datafusion_expr::function::{AccumulatorArgs, StateFieldsArgs};
use datafusion_expr::utils::format_state_name;
use datafusion_expr::{
@@ -37,6 +37,7 @@ use datafusion_expr::{
};
use datafusion_functions_aggregate_common::merge_arrays::merge_ordered_arrays;
use datafusion_functions_aggregate_common::utils::ordering_fields;
+use datafusion_macros::user_doc;
use datafusion_physical_expr::expressions::Literal;
use datafusion_physical_expr_common::sort_expr::{LexOrdering, PhysicalSortExpr};
@@ -60,6 +61,32 @@ pub fn nth_value(
}
}
+#[user_doc(
+ doc_section(label = "Statistical Functions"),
+ description = "Returns the nth value in a group of values.",
+ syntax_example = "nth_value(expression, n ORDER BY expression)",
+ sql_example = r#"```sql
+> SELECT dept_id, salary, NTH_VALUE(salary, 2) OVER (PARTITION BY dept_id ORDER BY salary ASC) AS second_salary_by_dept
+ FROM employee;
++---------+--------+-------------------------+
+| dept_id | salary | second_salary_by_dept |
++---------+--------+-------------------------+
+| 1 | 30000 | NULL |
+| 1 | 40000 | 40000 |
+| 1 | 50000 | 40000 |
+| 2 | 35000 | NULL |
+| 2 | 45000 | 45000 |
++---------+--------+-------------------------+
+```"#,
+ argument(
+ name = "expression",
+ description = "The column or expression to retrieve the nth value from."
+ ),
+ argument(
+ name = "n",
+ description = "The position (nth) of the value to retrieve, based on the ordering."
+ )
+)]
/// Expression for a `NTH_VALUE(... ORDER BY ..., ...)` aggregation. In a multi
/// partition setting, partial aggregations are computed for every partition,
/// and then their results are merged.
@@ -165,38 +192,10 @@ impl AggregateUDFImpl for NthValueAgg {
}
fn documentation(&self) -> Option<&Documentation> {
- Some(get_nth_value_doc())
+ self.doc()
}
}
-static DOCUMENTATION: OnceLock<Documentation> = OnceLock::new();
-
-fn get_nth_value_doc() -> &'static Documentation {
- DOCUMENTATION.get_or_init(|| {
- Documentation::builder(
- DOC_SECTION_STATISTICAL,
- "Returns the nth value in a group of values.",
-
- "nth_value(expression, n ORDER BY expression)")
- .with_sql_example(r#"```sql
-> SELECT dept_id, salary, NTH_VALUE(salary, 2) OVER (PARTITION BY dept_id ORDER BY salary ASC) AS second_salary_by_dept
- FROM employee;
-+---------+--------+-------------------------+
-| dept_id | salary | second_salary_by_dept |
-+---------+--------+-------------------------+
-| 1 | 30000 | NULL |
-| 1 | 40000 | 40000 |
-| 1 | 50000 | 40000 |
-| 2 | 35000 | NULL |
-| 2 | 45000 | 45000 |
-+---------+--------+-------------------------+
-```"#)
- .with_argument("expression", "The column or expression to retrieve the nth value from.")
- .with_argument("n", "The position (nth) of the value to retrieve, based on the ordering.")
- .build()
- })
-}
-
#[derive(Debug)]
pub struct NthValueAccumulator {
/// The `N` value.
diff --git a/datafusion/functions-aggregate/src/stddev.rs b/datafusion/functions-aggregate/src/stddev.rs
index afc9bf6255..09a39e342c 100644
--- a/datafusion/functions-aggregate/src/stddev.rs
+++ b/datafusion/functions-aggregate/src/stddev.rs
@@ -27,7 +27,7 @@ use arrow::{array::ArrayRef, datatypes::DataType, datatypes::Field};
use datafusion_common::{internal_err, not_impl_err, Result};
use datafusion_common::{plan_err, ScalarValue};
-use datafusion_expr::aggregate_doc_sections::DOC_SECTION_STATISTICAL;
+use datafusion_doc::DocSection;
use datafusion_expr::function::{AccumulatorArgs, StateFieldsArgs};
use datafusion_expr::utils::format_state_name;
use datafusion_expr::{
@@ -35,6 +35,7 @@ use datafusion_expr::{
Volatility,
};
use datafusion_functions_aggregate_common::stats::StatsType;
+use datafusion_macros::user_doc;
use crate::variance::{VarianceAccumulator, VarianceGroupsAccumulator};
@@ -46,6 +47,20 @@ make_udaf_expr_and_func!(
stddev_udaf
);
+#[user_doc(
+ doc_section(label = "Statistical Functions"),
+ description = "Returns the standard deviation of a set of numbers.",
+ syntax_example = "stddev(expression)",
+ sql_example = r#"```sql
+> SELECT stddev(column_name) FROM table_name;
++----------------------+
+| stddev(column_name) |
++----------------------+
+| 12.34 |
++----------------------+
+```"#,
+ standard_argument(name = "expression",)
+)]
/// STDDEV and STDDEV_SAMP (standard deviation) aggregate expression
pub struct Stddev {
signature: Signature,
@@ -134,34 +149,10 @@ impl AggregateUDFImpl for Stddev {
}
fn documentation(&self) -> Option<&Documentation> {
- Some(get_stddev_doc())
+ self.doc()
}
}
-static DOCUMENTATION: OnceLock<Documentation> = OnceLock::new();
-
-fn get_stddev_doc() -> &'static Documentation {
- DOCUMENTATION.get_or_init(|| {
- Documentation::builder(
- DOC_SECTION_STATISTICAL,
- "Returns the standard deviation of a set of numbers.",
- "stddev(expression)",
- )
- .with_sql_example(
- r#"```sql
-> SELECT stddev(column_name) FROM table_name;
-+----------------------+
-| stddev(column_name) |
-+----------------------+
-| 12.34 |
-+----------------------+
-```"#,
- )
- .with_standard_argument("expression", None)
- .build()
- })
-}
-
make_udaf_expr_and_func!(
StddevPop,
stddev_pop,
@@ -170,6 +161,20 @@ make_udaf_expr_and_func!(
stddev_pop_udaf
);
+#[user_doc(
+ doc_section(label = "Statistical Functions"),
+ description = "Returns the population standard deviation of a set of numbers.",
+ syntax_example = "stddev_pop(expression)",
+ sql_example = r#"```sql
+> SELECT stddev_pop(column_name) FROM table_name;
++--------------------------+
+| stddev_pop(column_name) |
++--------------------------+
+| 10.56 |
++--------------------------+
+```"#,
+ standard_argument(name = "expression",)
+)]
/// STDDEV_POP population aggregate expression
pub struct StddevPop {
signature: Signature,
@@ -258,32 +263,10 @@ impl AggregateUDFImpl for StddevPop {
}
fn documentation(&self) -> Option<&Documentation> {
- Some(get_stddev_pop_doc())
+ self.doc()
}
}
-fn get_stddev_pop_doc() -> &'static Documentation {
- DOCUMENTATION.get_or_init(|| {
- Documentation::builder(
- DOC_SECTION_STATISTICAL,
- "Returns the population standard deviation of a set of numbers.",
- "stddev_pop(expression)",
- )
- .with_sql_example(
- r#"```sql
-> SELECT stddev_pop(column_name) FROM table_name;
-+--------------------------+
-| stddev_pop(column_name) |
-+--------------------------+
-| 10.56 |
-+--------------------------+
-```"#,
- )
- .with_standard_argument("expression", None)
- .build()
- })
-}
-
/// An accumulator to compute the average
#[derive(Debug)]
pub struct StddevAccumulator {
diff --git a/datafusion/functions-aggregate/src/string_agg.rs b/datafusion/functions-aggregate/src/string_agg.rs
index 4fd2d91b46..5a52bec55f 100644
--- a/datafusion/functions-aggregate/src/string_agg.rs
+++ b/datafusion/functions-aggregate/src/string_agg.rs
@@ -22,11 +22,12 @@ use arrow_schema::DataType;
use datafusion_common::cast::as_generic_string_array;
use datafusion_common::Result;
use datafusion_common::{not_impl_err, ScalarValue};
-use datafusion_expr::aggregate_doc_sections::DOC_SECTION_GENERAL;
+use datafusion_doc::DocSection;
use datafusion_expr::function::AccumulatorArgs;
use datafusion_expr::{
Accumulator, AggregateUDFImpl, Documentation, Signature, TypeSignature, Volatility,
};
+use datafusion_macros::user_doc;
use datafusion_physical_expr::expressions::Literal;
use std::any::Any;
use std::mem::size_of_val;
@@ -40,6 +41,28 @@ make_udaf_expr_and_func!(
string_agg_udaf
);
+#[user_doc(
+ doc_section(label = "General Functions"),
+ description = "Concatenates the values of string expressions and places separator values between them.",
+ syntax_example = "string_agg(expression, delimiter)",
+ sql_example = r#"```sql
+> SELECT string_agg(name, ', ') AS names_list
+ FROM employee;
++--------------------------+
+| names_list |
++--------------------------+
+| Alice, Bob, Charlie |
++--------------------------+
+```"#,
+ argument(
+ name = "expression",
+ description = "The string expression to concatenate. Can be a column or any valid string expression."
+ ),
+ argument(
+ name = "delimiter",
+ description = "A literal string used as a separator between the concatenated values."
+ )
+)]
/// STRING_AGG aggregate expression
#[derive(Debug)]
pub struct StringAgg {
@@ -103,35 +126,10 @@ impl AggregateUDFImpl for StringAgg {
}
fn documentation(&self) -> Option<&Documentation> {
- Some(get_string_agg_doc())
+ self.doc()
}
}
-static DOCUMENTATION: OnceLock<Documentation> = OnceLock::new();
-
-fn get_string_agg_doc() -> &'static Documentation {
- DOCUMENTATION.get_or_init(|| {
- Documentation::builder(
- DOC_SECTION_GENERAL,
- "Concatenates the values of string expressions and places separator values between them.",
-
- "string_agg(expression, delimiter)")
- .with_sql_example(r#"```sql
-> SELECT string_agg(name, ', ') AS names_list
- FROM employee;
-+--------------------------+
-| names_list |
-+--------------------------+
-| Alice, Bob, Charlie |
-+--------------------------+
-```"#,
- )
- .with_argument("expression", "The string expression to concatenate. Can be a column or any valid string expression.")
- .with_argument("delimiter", "A literal string used as a separator between the concatenated values.")
- .build()
- })
-}
-
#[derive(Debug)]
pub(crate) struct StringAggAccumulator {
values: Option<String>,
diff --git a/datafusion/functions-aggregate/src/sum.rs b/datafusion/functions-aggregate/src/sum.rs
index df87a593cf..ccc6ee3cf9 100644
--- a/datafusion/functions-aggregate/src/sum.rs
+++ b/datafusion/functions-aggregate/src/sum.rs
@@ -35,7 +35,7 @@ use arrow::datatypes::{
};
use arrow::{array::ArrayRef, datatypes::Field};
use datafusion_common::{exec_err, not_impl_err, Result, ScalarValue};
-use datafusion_expr::aggregate_doc_sections::DOC_SECTION_GENERAL;
+use datafusion_doc::DocSection;
use datafusion_expr::function::AccumulatorArgs;
use datafusion_expr::function::StateFieldsArgs;
use datafusion_expr::utils::format_state_name;
@@ -45,6 +45,7 @@ use datafusion_expr::{
};
use datafusion_functions_aggregate_common::aggregate::groups_accumulator::prim_op::PrimitiveGroupsAccumulator;
use datafusion_functions_aggregate_common::utils::Hashable;
+use datafusion_macros::user_doc;
make_udaf_expr_and_func!(
Sum,
@@ -79,6 +80,20 @@ macro_rules! downcast_sum {
};
}
+#[user_doc(
+ doc_section(label = "General Functions"),
+ description = "Returns the sum of all values in the specified column.",
+ syntax_example = "sum(expression)",
+ sql_example = r#"```sql
+> SELECT sum(column_name) FROM table_name;
++-----------------------+
+| sum(column_name) |
++-----------------------+
+| 12345 |
++-----------------------+
+```"#,
+ standard_argument(name = "expression",)
+)]
#[derive(Debug)]
pub struct Sum {
signature: Signature,
@@ -239,34 +254,10 @@ impl AggregateUDFImpl for Sum {
}
fn documentation(&self) -> Option<&Documentation> {
- Some(get_sum_doc())
+ self.doc()
}
}
-static DOCUMENTATION: OnceLock<Documentation> = OnceLock::new();
-
-fn get_sum_doc() -> &'static Documentation {
- DOCUMENTATION.get_or_init(|| {
- Documentation::builder(
- DOC_SECTION_GENERAL,
- "Returns the sum of all values in the specified column.",
- "sum(expression)",
- )
- .with_sql_example(
- r#"```sql
-> SELECT sum(column_name) FROM table_name;
-+-----------------------+
-| sum(column_name) |
-+-----------------------+
-| 12345 |
-+-----------------------+
-```"#,
- )
- .with_standard_argument("expression", None)
- .build()
- })
-}
-
/// This accumulator computes SUM incrementally
struct SumAccumulator<T: ArrowNumericType> {
sum: Option<T::Native>,
diff --git a/datafusion/functions-aggregate/src/variance.rs b/datafusion/functions-aggregate/src/variance.rs
index 9c99a9138d..70b1073408 100644
--- a/datafusion/functions-aggregate/src/variance.rs
+++ b/datafusion/functions-aggregate/src/variance.rs
@@ -31,7 +31,7 @@ use std::{fmt::Debug, sync::Arc};
use datafusion_common::{
downcast_value, not_impl_err, plan_err, DataFusionError, Result, ScalarValue,
};
-use datafusion_expr::aggregate_doc_sections::DOC_SECTION_GENERAL;
+use datafusion_doc::DocSection;
use datafusion_expr::{
function::{AccumulatorArgs, StateFieldsArgs},
utils::format_state_name,
@@ -41,6 +41,7 @@ use datafusion_expr::{
use datafusion_functions_aggregate_common::{
aggregate::groups_accumulator::accumulate::accumulate, stats::StatsType,
};
+use datafusion_macros::user_doc;
make_udaf_expr_and_func!(
VarianceSample,
@@ -58,6 +59,12 @@ make_udaf_expr_and_func!(
var_pop_udaf
);
+#[user_doc(
+ doc_section(label = "General Functions"),
+ description = "Returns the statistical sample variance of a set of numbers.",
+ syntax_example = "var(expression)",
+ standard_argument(name = "expression", prefix = "Numeric")
+)]
pub struct VarianceSample {
signature: Signature,
aliases: Vec<String>,
@@ -137,24 +144,16 @@ impl AggregateUDFImpl for VarianceSample {
}
fn documentation(&self) -> Option<&Documentation> {
- Some(get_variance_sample_doc())
+ self.doc()
}
}
-static VARIANCE_SAMPLE_DOC: OnceLock<Documentation> = OnceLock::new();
-
-fn get_variance_sample_doc() -> &'static Documentation {
- VARIANCE_SAMPLE_DOC.get_or_init(|| {
- Documentation::builder(
- DOC_SECTION_GENERAL,
- "Returns the statistical sample variance of a set of numbers.",
- "var(expression)",
- )
- .with_standard_argument("expression", Some("Numeric"))
- .build()
- })
-}
-
+#[user_doc(
+ doc_section(label = "General Functions"),
+ description = "Returns the statistical population variance of a set of numbers.",
+ syntax_example = "var_pop(expression)",
+ standard_argument(name = "expression", prefix = "Numeric")
+)]
pub struct VariancePopulation {
signature: Signature,
aliases: Vec<String>,
@@ -241,24 +240,10 @@ impl AggregateUDFImpl for VariancePopulation {
)))
}
fn documentation(&self) -> Option<&Documentation> {
- Some(get_variance_population_doc())
+ self.doc()
}
}
-static VARIANCE_POPULATION_DOC: OnceLock<Documentation> = OnceLock::new();
-
-fn get_variance_population_doc() -> &'static Documentation {
- VARIANCE_POPULATION_DOC.get_or_init(|| {
- Documentation::builder(
- DOC_SECTION_GENERAL,
- "Returns the statistical population variance of a set of numbers.",
- "var_pop(expression)",
- )
- .with_standard_argument("expression", Some("Numeric"))
- .build()
- })
-}
-
/// An accumulator to compute variance
/// The algorithm used is an online implementation and numerically stable. It is based on this paper:
/// Welford, B. P. (1962). "Note on a method for calculating corrected sums of squares and products".
diff --git a/datafusion/functions/src/datetime/to_date.rs b/datafusion/functions/src/datetime/to_date.rs
index 15f1159ef9..e2edea843e 100644
--- a/datafusion/functions/src/datetime/to_date.rs
+++ b/datafusion/functions/src/datetime/to_date.rs
@@ -22,6 +22,7 @@ use arrow::error::ArrowError::ParseError;
use arrow::{array::types::Date32Type, compute::kernels::cast_utils::Parser};
use datafusion_common::error::DataFusionError;
use datafusion_common::{arrow_err, exec_err, internal_datafusion_err, Result};
+use datafusion_doc::DocSection;
use datafusion_expr::{
ColumnarValue, Documentation, ScalarUDFImpl, Signature, Volatility,
};
diff --git a/datafusion/functions/src/math/abs.rs b/datafusion/functions/src/math/abs.rs
index 3565afbe6b..c0c7c6f0f6 100644
--- a/datafusion/functions/src/math/abs.rs
+++ b/datafusion/functions/src/math/abs.rs
@@ -27,12 +27,13 @@ use arrow::array::{
use arrow::datatypes::DataType;
use arrow::error::ArrowError;
use datafusion_common::{exec_err, not_impl_err, DataFusionError, Result};
+use datafusion_doc::DocSection;
use datafusion_expr::interval_arithmetic::Interval;
-use datafusion_expr::scalar_doc_sections::DOC_SECTION_MATH;
use datafusion_expr::sort_properties::{ExprProperties, SortProperties};
use datafusion_expr::{
ColumnarValue, Documentation, ScalarUDFImpl, Signature, Volatility,
};
+use datafusion_macros::user_doc;
type MathArrayFunction = fn(&Vec<ArrayRef>) -> Result<ArrayRef>;
@@ -103,6 +104,12 @@ fn create_abs_function(input_data_type: &DataType) -> Result<MathArrayFunction>
other => not_impl_err!("Unsupported data type {other:?} for function abs"),
}
}
+#[user_doc(
+ doc_section(label = "Math Functions"),
+ description = "Returns the absolute value of a number.",
+ syntax_example = "abs(numeric_expression)",
+ standard_argument(name = "numeric_expression", prefix = "Numeric")
+)]
#[derive(Debug)]
pub struct AbsFunc {
signature: Signature,
@@ -193,20 +200,6 @@ impl ScalarUDFImpl for AbsFunc {
}
fn documentation(&self) -> Option<&Documentation> {
- Some(get_abs_doc())
+ self.doc()
}
}
-
-static DOCUMENTATION: OnceLock<Documentation> = OnceLock::new();
-
-fn get_abs_doc() -> &'static Documentation {
- DOCUMENTATION.get_or_init(|| {
- Documentation::builder(
- DOC_SECTION_MATH,
- "Returns the absolute value of a number.",
- "abs(numeric_expression)",
- )
- .with_standard_argument("numeric_expression", Some("Numeric"))
- .build()
- })
-}
diff --git a/datafusion/functions/src/string/ltrim.rs b/datafusion/functions/src/string/ltrim.rs
index 9347036880..e0e83d1b01 100644
--- a/datafusion/functions/src/string/ltrim.rs
+++ b/datafusion/functions/src/string/ltrim.rs
@@ -22,6 +22,7 @@ use std::any::Any;
use crate::string::common::*;
use crate::utils::{make_scalar_function, utf8_to_str_type};
use datafusion_common::{exec_err, Result};
+use datafusion_doc::DocSection;
use datafusion_expr::function::Hint;
use datafusion_expr::{ColumnarValue, Documentation, TypeSignature, Volatility};
use datafusion_expr::{ScalarUDFImpl, Signature};
diff --git a/datafusion/macros/src/lib.rs b/datafusion/macros/src/lib.rs
index e4eeeba7a4..54b688ac2a 100644
--- a/datafusion/macros/src/lib.rs
+++ b/datafusion/macros/src/lib.rs
@@ -190,6 +190,12 @@ pub fn user_doc(args: TokenStream, input: TokenStream) -> TokenStream {
.map(|desc| quote! { Some(#desc)})
.unwrap_or(quote! { None });
+ let sql_example = sql_example.map(|ex| {
+ quote! {
+ .with_sql_example(#ex)
+ }
+ });
+
let udf_args = udf_args
.iter()
.map(|(name, desc)| {
@@ -202,8 +208,14 @@ pub fn user_doc(args: TokenStream, input: TokenStream) -> TokenStream {
let standard_args = standard_args
.iter()
.map(|(name, desc)| {
+ let desc = if let Some(d) = desc {
+ quote! { #d.into() }
+ } else {
+ quote! { None }
+ };
+
quote! {
- .with_standard_argument(#name, #desc.into())
+ .with_standard_argument(#name, #desc)
}
})
.collect::<Vec<_>>();
@@ -223,20 +235,21 @@ pub fn user_doc(args: TokenStream, input: TokenStream) -> TokenStream {
}
});
+ let lock_name: proc_macro2::TokenStream =
+ format!("{name}_DOCUMENTATION").parse().unwrap();
+
let generated = quote! {
#input
- use datafusion_doc::DocSection;
- use datafusion_doc::DocumentationBuilder;
-
- static DOCUMENTATION: OnceLock<Documentation> = OnceLock::new();
+ static #lock_name: OnceLock<Documentation> = OnceLock::new();
impl #name {
+
fn doc(&self) -> Option<&Documentation> {
- Some(DOCUMENTATION.get_or_init(|| {
+ Some(#lock_name.get_or_init(|| {
Documentation::builder(DocSection { include: #doc_section_include, label: #doc_section_lbl, description: #doc_section_description },
#description.to_string(), #syntax_example.to_string())
- .with_sql_example(#sql_example.to_string())
+ #sql_example
#alt_syntax_example
#(#standard_args)*
#(#udf_args)*
@@ -248,7 +261,9 @@ pub fn user_doc(args: TokenStream, input: TokenStream) -> TokenStream {
};
// Debug the generated code if needed
- //eprintln!("Generated code: {}", generated);
+ // if name == "ArrayAgg" {
+ // eprintln!("Generated code: {}", generated);
+ // }
// Return the generated code
TokenStream::from(generated)
diff --git a/docs/source/user-guide/sql/aggregate_functions.md b/docs/source/user-guide/sql/aggregate_functions.md
index d9fc28a817..221bb0572e 100644
--- a/docs/source/user-guide/sql/aggregate_functions.md
+++ b/docs/source/user-guide/sql/aggregate_functions.md
@@ -268,10 +268,10 @@ grouping(expression)
### `last_value`
-Returns the first element in an aggregation group according to the requested ordering. If no ordering is given, returns an arbitrary element from the group.
+Returns the last element in an aggregation group according to the requested ordering. If no ordering is given, returns an arbitrary element from the group.
```
-first_value(expression [ORDER BY expression])
+last_value(expression [ORDER BY expression])
```
#### Arguments
@@ -281,11 +281,11 @@ first_value(expression [ORDER BY expression])
#### Example
```sql
-> SELECT first_value(column_name ORDER BY other_column) FROM table_name;
+> SELECT last_value(column_name ORDER BY other_column) FROM table_name;
+-----------------------------------------------+
-| first_value(column_name ORDER BY other_column)|
+| last_value(column_name ORDER BY other_column) |
+-----------------------------------------------+
-| first_element |
+| last_element |
+-----------------------------------------------+
```
@@ -341,10 +341,10 @@ median(expression)
### `min`
-Returns the maximum value in the specified column.
+Returns the minimum value in the specified column.
```
-max(expression)
+min(expression)
```
#### Arguments
@@ -354,11 +354,11 @@ max(expression)
#### Example
```sql
-> SELECT max(column_name) FROM table_name;
+> SELECT min(column_name) FROM table_name;
+----------------------+
-| max(column_name) |
+| min(column_name) |
+----------------------+
-| 150 |
+| 12 |
+----------------------+
```
@@ -730,10 +730,10 @@ stddev(expression)
### `stddev_pop`
-Returns the standard deviation of a set of numbers.
+Returns the population standard deviation of a set of numbers.
```
-stddev(expression)
+stddev_pop(expression)
```
#### Arguments
@@ -743,12 +743,12 @@ stddev(expression)
#### Example
```sql
-> SELECT stddev(column_name) FROM table_name;
-+----------------------+
-| stddev(column_name) |
-+----------------------+
-| 12.34 |
-+----------------------+
+> SELECT stddev_pop(column_name) FROM table_name;
++--------------------------+
+| stddev_pop(column_name) |
++--------------------------+
+| 10.56 |
++--------------------------+
```
### `stddev_samp`