Skip to main content

session/
query_options.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::session_config::{Error, InvalidConfigValueSnafu};
16
17/// Returns a canonical query option alias or a DataFusion optimizer option name.
18pub fn canonical_query_option_name(key: &str) -> Option<String> {
19    let key = key.to_ascii_lowercase();
20    match key.as_str() {
21        "query_parallelism" | "query.parallelism" => Some("query.parallelism".to_string()),
22        "query_fallback" | "allow_query_fallback" | "query.allow_query_fallback" => {
23            Some("query.allow_query_fallback".to_string())
24        }
25        "experimental_enable_factorized_join_agg"
26        | "query.experimental_enable_factorized_join_agg" => {
27            Some("query.experimental_enable_factorized_join_agg".to_string())
28        }
29        "query.enable_remote_dynamic_filter_pushdown" => {
30            Some("query.enable_remote_dynamic_filter_pushdown".to_string())
31        }
32        // The native PromQL route is gated on this per-request extension together with the
33        // engine-wide `experimental_native_promql` option. Without this arm the snapshot
34        // rejects it as an unknown `query.` option, which silently disables the route.
35        // TODO(narthex-merge): drop the public alias once the native route is GA.
36        "query.experimental_native_promql" => Some("query.experimental_native_promql".to_string()),
37        _ if key.starts_with("datafusion.optimizer.") => Some(key),
38        _ => None,
39    }
40}
41
42/// Maximum query parallelism accepted through public query-option inputs.
43pub const MAX_PUBLIC_PARALLELISM: u16 = 1024;
44
45/// Validate a query option, returning its canonical name and normalized value.
46pub fn parse_query_option(
47    key: &str,
48    value: &str,
49    max_parallelism: u16,
50) -> Result<Option<(String, String)>, Error> {
51    let key_lower = key.to_ascii_lowercase();
52    let canonical = match canonical_query_option_name(key) {
53        Some(name) => name,
54        None if key_lower.starts_with("query.") || key_lower.starts_with("datafusion.") => {
55            return InvalidConfigValueSnafu {
56                name: key,
57                value,
58                hint: "Unknown or unsupported query option",
59            }
60            .fail();
61        }
62        None => return Ok(None),
63    };
64
65    let normalized = if canonical == "query.parallelism" {
66        match value.parse::<u16>() {
67            Ok(n) if (1..=max_parallelism).contains(&n) => n.to_string(),
68            _ => {
69                return InvalidConfigValueSnafu {
70                    name: key,
71                    value,
72                    hint: format!("query.parallelism must be between 1 and {max_parallelism}"),
73                }
74                .fail();
75            }
76        }
77    } else if canonical.starts_with("query.") {
78        match value.to_ascii_lowercase().as_str() {
79            "true" => "true".to_string(),
80            "false" => "false".to_string(),
81            _ => {
82                return InvalidConfigValueSnafu {
83                    name: key,
84                    value,
85                    hint: "Expected true or false",
86                }
87                .fail();
88            }
89        }
90    } else {
91        let mut options = datafusion_common::config::ConfigOptions::default();
92        let set_result = options.set(&canonical, value).or_else(|error| {
93            if value.eq_ignore_ascii_case("true") || value.eq_ignore_ascii_case("false") {
94                options.set(&canonical, &value.to_ascii_lowercase())
95            } else {
96                Err(error)
97            }
98        });
99        if let Err(error) = set_result {
100            return InvalidConfigValueSnafu {
101                name: key,
102                value,
103                hint: error.to_string(),
104            }
105            .fail();
106        }
107        match options
108            .entries()
109            .into_iter()
110            .find(|entry| entry.key == canonical)
111            .and_then(|entry| entry.value)
112        {
113            Some(value) => value,
114            None => {
115                return InvalidConfigValueSnafu {
116                    name: key,
117                    value,
118                    hint: "No matching DataFusion configuration entry",
119                }
120                .fail();
121            }
122        }
123    };
124    Ok(Some((canonical, normalized)))
125}