Skip to main content

common_query/
prelude.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 common_base::regex_pattern::NAME_PATTERN_REG;
16pub use datafusion_common::ScalarValue;
17use once_cell::sync::OnceCell;
18use snafu::ensure;
19
20pub use crate::columnar_value::ColumnarValue;
21use crate::error::{InvalidColumnPrefixSnafu, Result};
22use crate::native_histogram::NATIVE_HISTOGRAM_FIELD;
23
24/// Default time index column name.
25static GREPTIME_TIMESTAMP_CELL: OnceCell<String> = OnceCell::new();
26
27/// Default value column name.
28static GREPTIME_VALUE_CELL: OnceCell<String> = OnceCell::new();
29
30/// Default native histogram column name.
31static GREPTIME_NATIVE_HISTOGRAM_CELL: OnceCell<String> = OnceCell::new();
32
33/// Default exemplar labels column name.
34static GREPTIME_EXEMPLAR_LABELS_CELL: OnceCell<String> = OnceCell::new();
35
36pub fn set_default_prefix(prefix: Option<&str>) -> Result<()> {
37    // Strip surrounding double quotes as a defensive measure against upstream
38    // sources (scripts, CI, template engines, incorrect shell escaping) that may
39    // pass literal `""` as the value instead of an empty string.
40    let stripped = prefix.map(|s| {
41        s.strip_prefix('"')
42            .and_then(|s| s.strip_suffix('"'))
43            .unwrap_or(s)
44    });
45
46    match stripped {
47        None => {
48            // use default greptime prefix
49            GREPTIME_TIMESTAMP_CELL.get_or_init(|| GREPTIME_TIMESTAMP.to_string());
50            GREPTIME_VALUE_CELL.get_or_init(|| GREPTIME_VALUE.to_string());
51            GREPTIME_NATIVE_HISTOGRAM_CELL.get_or_init(|| NATIVE_HISTOGRAM_FIELD.to_string());
52            GREPTIME_EXEMPLAR_LABELS_CELL.get_or_init(|| GREPTIME_EXEMPLAR_LABELS.to_string());
53        }
54        Some(s) if s.trim().is_empty() => {
55            // use "" to disable prefix
56            GREPTIME_TIMESTAMP_CELL.get_or_init(|| "timestamp".to_string());
57            GREPTIME_VALUE_CELL.get_or_init(|| "value".to_string());
58            GREPTIME_NATIVE_HISTOGRAM_CELL.get_or_init(|| "native_histogram".to_string());
59            GREPTIME_EXEMPLAR_LABELS_CELL.get_or_init(|| "exemplar_labels".to_string());
60        }
61        Some(x) => {
62            ensure!(
63                NAME_PATTERN_REG.is_match(x),
64                InvalidColumnPrefixSnafu { prefix: x }
65            );
66            GREPTIME_TIMESTAMP_CELL.get_or_init(|| format!("{}_timestamp", x));
67            GREPTIME_VALUE_CELL.get_or_init(|| format!("{}_value", x));
68            GREPTIME_NATIVE_HISTOGRAM_CELL.get_or_init(|| format!("{}_native_histogram", x));
69            GREPTIME_EXEMPLAR_LABELS_CELL.get_or_init(|| format!("{}_exemplar_labels", x));
70        }
71    }
72    Ok(())
73}
74
75/// Get the default timestamp column name.
76/// Returns the configured value, or `greptime_timestamp` if not set.
77pub fn greptime_timestamp() -> &'static str {
78    GREPTIME_TIMESTAMP_CELL.get_or_init(|| GREPTIME_TIMESTAMP.to_string())
79}
80
81/// Get the default value column name.
82/// Returns the configured value, or `greptime_value` if not set.
83pub fn greptime_value() -> &'static str {
84    GREPTIME_VALUE_CELL.get_or_init(|| GREPTIME_VALUE.to_string())
85}
86
87/// Get the default native histogram column name.
88/// Returns the configured value, or `greptime_native_histogram` if not set.
89#[inline]
90pub fn greptime_native_histogram() -> &'static str {
91    GREPTIME_NATIVE_HISTOGRAM_CELL
92        .get()
93        .map_or(NATIVE_HISTOGRAM_FIELD, String::as_str)
94}
95
96/// Returns the configured exemplar labels column name, or `greptime_exemplar_labels` if not set.
97#[inline]
98pub fn greptime_exemplar_labels() -> &'static str {
99    GREPTIME_EXEMPLAR_LABELS_CELL
100        .get()
101        .map_or(GREPTIME_EXEMPLAR_LABELS, String::as_str)
102}
103
104/// Default timestamp column name constant for backward compatibility.
105const GREPTIME_TIMESTAMP: &str = "greptime_timestamp";
106/// Default value column name constant for backward compatibility.
107const GREPTIME_VALUE: &str = "greptime_value";
108/// Query-visible source metric name stored in the exemplar table.
109pub const EXEMPLAR_METRIC_COLUMN: &str = "greptime_metric";
110/// JSON2 object containing exemplar-owned labels.
111const GREPTIME_EXEMPLAR_LABELS: &str = "greptime_exemplar_labels";
112/// Stored series label that opts ordinary float samples into raw-delta math.
113pub const OTLP_AGGREGATION_TEMPORALITY_LABEL: &str = "otlp_aggregation_temporality";
114/// Authoritative raw-delta value for [`OTLP_AGGREGATION_TEMPORALITY_LABEL`].
115pub const GREPTIME_TEMPORALITY_DELTA: &str = "delta";
116/// Default physical table name
117pub const GREPTIME_PHYSICAL_TABLE: &str = "greptime_physical_table";
118
119#[cfg(test)]
120mod tests {
121    use super::*;
122
123    // Each test runs in a separate process via `cargo nextest`, so OnceCell
124    // state does not leak between tests.
125
126    #[test]
127    fn test_set_default_prefix_none() {
128        set_default_prefix(None).unwrap();
129        assert_eq!(greptime_timestamp(), "greptime_timestamp");
130        assert_eq!(greptime_value(), "greptime_value");
131        assert_eq!(greptime_native_histogram(), "greptime_native_histogram");
132        assert_eq!(greptime_exemplar_labels(), "greptime_exemplar_labels");
133    }
134
135    #[test]
136    fn test_set_default_prefix_empty_string() {
137        set_default_prefix(Some("")).unwrap();
138        assert_eq!(greptime_timestamp(), "timestamp");
139        assert_eq!(greptime_value(), "value");
140        assert_eq!(greptime_native_histogram(), "native_histogram");
141        assert_eq!(greptime_exemplar_labels(), "exemplar_labels");
142    }
143
144    #[test]
145    fn test_set_default_prefix_quoted_empty() {
146        // Handles upstream sources that pass literal `""` instead of an empty string
147        set_default_prefix(Some("\"\"")).unwrap();
148        assert_eq!(greptime_timestamp(), "timestamp");
149        assert_eq!(greptime_value(), "value");
150        assert_eq!(greptime_native_histogram(), "native_histogram");
151        assert_eq!(greptime_exemplar_labels(), "exemplar_labels");
152    }
153
154    #[test]
155    fn test_set_default_prefix_custom() {
156        set_default_prefix(Some("mydb")).unwrap();
157        assert_eq!(greptime_timestamp(), "mydb_timestamp");
158        assert_eq!(greptime_value(), "mydb_value");
159        assert_eq!(greptime_native_histogram(), "mydb_native_histogram");
160        assert_eq!(greptime_exemplar_labels(), "mydb_exemplar_labels");
161    }
162
163    #[test]
164    fn test_set_default_prefix_invalid() {
165        assert!(set_default_prefix(Some("invalid prefix!")).is_err());
166    }
167}