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        "query.enable_remote_dynamic_filter_pushdown" => {
26            Some("query.enable_remote_dynamic_filter_pushdown".to_string())
27        }
28        // The native PromQL route is gated on this per-request extension together with the
29        // engine-wide `experimental_native_promql` option. Without this arm the snapshot
30        // rejects it as an unknown `query.` option, which silently disables the route.
31        // TODO(narthex-merge): drop the public alias once the native route is GA.
32        "query.experimental_native_promql" => Some("query.experimental_native_promql".to_string()),
33        _ if key.starts_with("datafusion.optimizer.") => Some(key),
34        _ => None,
35    }
36}
37
38/// Maximum query parallelism accepted through public query-option inputs.
39pub const MAX_PUBLIC_PARALLELISM: u16 = 1024;
40
41/// Validate a query option, returning its canonical name and normalized value.
42pub fn parse_query_option(
43    key: &str,
44    value: &str,
45    max_parallelism: u16,
46) -> Result<Option<(String, String)>, Error> {
47    let key_lower = key.to_ascii_lowercase();
48    let canonical = match canonical_query_option_name(key) {
49        Some(name) => name,
50        None if key_lower.starts_with("query.") || key_lower.starts_with("datafusion.") => {
51            return InvalidConfigValueSnafu {
52                name: key,
53                value,
54                hint: "Unknown or unsupported query option",
55            }
56            .fail();
57        }
58        None => return Ok(None),
59    };
60
61    let normalized = if canonical == "query.parallelism" {
62        match value.parse::<u16>() {
63            Ok(n) if (1..=max_parallelism).contains(&n) => n.to_string(),
64            _ => {
65                return InvalidConfigValueSnafu {
66                    name: key,
67                    value,
68                    hint: format!("query.parallelism must be between 1 and {max_parallelism}"),
69                }
70                .fail();
71            }
72        }
73    } else if canonical.starts_with("query.") {
74        match value.to_ascii_lowercase().as_str() {
75            "true" => "true".to_string(),
76            "false" => "false".to_string(),
77            _ => {
78                return InvalidConfigValueSnafu {
79                    name: key,
80                    value,
81                    hint: "Expected true or false",
82                }
83                .fail();
84            }
85        }
86    } else {
87        let mut options = datafusion_common::config::ConfigOptions::default();
88        let set_result = options.set(&canonical, value).or_else(|error| {
89            if value.eq_ignore_ascii_case("true") || value.eq_ignore_ascii_case("false") {
90                options.set(&canonical, &value.to_ascii_lowercase())
91            } else {
92                Err(error)
93            }
94        });
95        if let Err(error) = set_result {
96            return InvalidConfigValueSnafu {
97                name: key,
98                value,
99                hint: error.to_string(),
100            }
101            .fail();
102        }
103        match options
104            .entries()
105            .into_iter()
106            .find(|entry| entry.key == canonical)
107            .and_then(|entry| entry.value)
108        {
109            Some(value) => value,
110            None => {
111                return InvalidConfigValueSnafu {
112                    name: key,
113                    value,
114                    hint: "No matching DataFusion configuration entry",
115                }
116                .fail();
117            }
118        }
119    };
120    Ok(Some((canonical, normalized)))
121}