Skip to main content

store_api/storage/
requests.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 std::collections::HashMap;
16use std::fmt::{Display, Formatter};
17
18use common_recordbatch::OrderOption;
19use datafusion_expr::expr::Expr;
20use datatypes::types::json_type::JsonNativeType;
21use itertools::Itertools;
22use strum::Display;
23
24use crate::storage::SequenceNumber;
25
26/// A hint on how to select rows from a time-series.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Display)]
28pub enum TimeSeriesRowSelector {
29    /// Only keep the last row of each time-series.
30    #[strum(to_string = "LastRow {{ after_merge: {after_merge} }}")]
31    LastRow {
32        /// Whether selection runs after cross-source merge and deduplication.
33        after_merge: bool,
34    },
35}
36
37/// A hint on how to distribute time-series data on the scan output.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Display)]
39pub enum TimeSeriesDistribution {
40    /// Data are distributed by time window first. The scanner will
41    /// return all data within one time window before moving to the next one.
42    TimeWindowed,
43    /// Data are organized by time-series first. The scanner will return
44    /// all data for one time-series before moving to the next one.
45    PerSeries,
46}
47
48#[derive(Default, Clone, Debug, PartialEq)]
49pub struct ScanRequest {
50    /// Requests bounded asynchronous exact-count preparation for a scalar COUNT.
51    /// This is an optimization hint; unsupported scans retain normal execution.
52    pub metadata_aggr_hint: bool,
53    /// Optional projection information for the scan. `None` reads all root
54    /// columns.
55    pub projection: Option<Vec<usize>>,
56    /// Filters pushed down
57    pub filters: Vec<Expr>,
58    /// Expected output ordering. This is only a hint and isn't guaranteed.
59    pub output_ordering: Option<Vec<OrderOption>>,
60    /// limit can be used to reduce the amount scanned
61    /// from the datasource as a performance optimization.
62    /// If set, it contains the amount of rows needed by the caller,
63    /// The data source should return *at least* this number of rows if available.
64    pub limit: Option<usize>,
65    /// Optional hint to select rows from time-series.
66    pub series_row_selector: Option<TimeSeriesRowSelector>,
67    /// Optional constraint on the sequence number of the rows to read.
68    /// If set, only rows with a sequence number **lesser or equal** to this value
69    /// will be returned.
70    /// This is the effective memtable upper bound used by the scan, whether provided
71    /// explicitly or bound on scan open.
72    pub memtable_max_sequence: Option<SequenceNumber>,
73    /// Optional constraint on the minimal sequence number in the memtable.
74    /// If set, only the memtables that contain sequences **greater than** this value will be scanned
75    pub memtable_min_sequence: Option<SequenceNumber>,
76    /// Optional constraint on the minimal sequence number in the SST files.
77    /// If set, only the SST files that contain sequences greater than this value will be scanned.
78    pub sst_min_sequence: Option<SequenceNumber>,
79    /// Whether to skip all SST files.
80    /// This is stronger than `sst_min_sequence` and also skips SST files without sequence metadata.
81    pub skip_sst_files: bool,
82    /// Whether to bind the effective snapshot upper bound when opening the scan.
83    pub snapshot_on_scan: bool,
84    /// Explicit intent to read an exact row-level sequence delta `(min, max]`
85    /// across memtables and all SST files (Flow's `sequence_range` incremental
86    /// mode). The engine performs exact row-level filtering only when the region
87    /// preserves per-row sequences and every participating SST file is trusted;
88    /// otherwise it returns a structured stale/unsupported error so the caller
89    /// falls back instead of silently approximating.
90    ///
91    /// Historical `memtable_only` reads must never set this flag.
92    pub exact_sequence_range: bool,
93    /// Optional hint for the distribution of time-series data.
94    pub distribution: Option<TimeSeriesDistribution>,
95    /// Optional hint from query-driven JSON type concretization.
96    pub json_type_hint: HashMap<String, JsonNativeType>,
97    /// Whether Mito should keep string primary-key columns dictionary encoded in its output.
98    pub preserve_pk_dictionary_encoding: bool,
99}
100
101impl Display for ScanRequest {
102    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
103        enum Delimiter {
104            None,
105            Init,
106        }
107
108        impl Delimiter {
109            fn as_str(&mut self) -> &str {
110                match self {
111                    Delimiter::None => {
112                        *self = Delimiter::Init;
113                        ""
114                    }
115                    Delimiter::Init => ", ",
116                }
117            }
118        }
119
120        let mut delimiter = Delimiter::None;
121
122        write!(f, "ScanRequest {{ ")?;
123        if let Some(projection) = &self.projection {
124            write!(f, "{}projection: {:?}", delimiter.as_str(), projection)?;
125        }
126        if !self.filters.is_empty() {
127            write!(
128                f,
129                "{}filters: [{}]",
130                delimiter.as_str(),
131                self.filters
132                    .iter()
133                    .map(|f| f.to_string())
134                    .collect::<Vec<_>>()
135                    .join(", ")
136            )?;
137        }
138        if let Some(output_ordering) = &self.output_ordering {
139            write!(
140                f,
141                "{}output_ordering: {:?}",
142                delimiter.as_str(),
143                output_ordering
144            )?;
145        }
146        if let Some(limit) = &self.limit {
147            write!(f, "{}limit: {}", delimiter.as_str(), limit)?;
148        }
149        if let Some(series_row_selector) = &self.series_row_selector {
150            write!(
151                f,
152                "{}series_row_selector: {}",
153                delimiter.as_str(),
154                series_row_selector
155            )?;
156        }
157        if let Some(sequence) = &self.memtable_max_sequence {
158            write!(f, "{}sequence: {}", delimiter.as_str(), sequence)?;
159        }
160        if let Some(sst_min_sequence) = &self.sst_min_sequence {
161            write!(
162                f,
163                "{}sst_min_sequence: {}",
164                delimiter.as_str(),
165                sst_min_sequence
166            )?;
167        }
168        if self.skip_sst_files {
169            write!(
170                f,
171                "{}skip_sst_files: {}",
172                delimiter.as_str(),
173                self.skip_sst_files
174            )?;
175        }
176        if self.snapshot_on_scan {
177            write!(
178                f,
179                "{}snapshot_on_scan: {}",
180                delimiter.as_str(),
181                self.snapshot_on_scan
182            )?;
183        }
184        if self.exact_sequence_range {
185            write!(f, "{}exact_sequence_range: true", delimiter.as_str())?;
186        }
187        if self.preserve_pk_dictionary_encoding {
188            write!(
189                f,
190                "{}preserve_pk_dictionary_encoding: true",
191                delimiter.as_str()
192            )?;
193        }
194        if let Some(distribution) = &self.distribution {
195            write!(f, "{}distribution: {}", delimiter.as_str(), distribution)?;
196        }
197        if !self.json_type_hint.is_empty() {
198            write!(
199                f,
200                "{}json_type_hint: {}",
201                delimiter.as_str(),
202                self.json_type_hint
203                    .iter()
204                    .map(|(column, json_type)| format!("({column}: {json_type})"))
205                    .join(", ")
206            )?;
207        }
208        write!(f, " }}")
209    }
210}
211
212#[cfg(test)]
213mod tests {
214    use datafusion_expr::{Operator, binary_expr, col, lit};
215
216    use super::*;
217
218    #[test]
219    fn test_display_scan_request() {
220        let request = ScanRequest {
221            ..Default::default()
222        };
223        assert_eq!(request.to_string(), "ScanRequest {  }");
224
225        let projection = Some(vec![1, 2]);
226        let request = ScanRequest {
227            projection,
228            filters: vec![
229                binary_expr(col("i"), Operator::Gt, lit(1)),
230                binary_expr(col("s"), Operator::Eq, lit("x")),
231            ],
232            limit: Some(10),
233            ..Default::default()
234        };
235        assert_eq!(
236            request.to_string(),
237            r#"ScanRequest { projection: [1, 2], filters: [i > Int32(1), s = Utf8("x")], limit: 10 }"#
238        );
239
240        let request = ScanRequest {
241            filters: vec![
242                binary_expr(col("i"), Operator::Gt, lit(1)),
243                binary_expr(col("s"), Operator::Eq, lit("x")),
244            ],
245            limit: Some(10),
246            ..Default::default()
247        };
248        assert_eq!(
249            request.to_string(),
250            r#"ScanRequest { filters: [i > Int32(1), s = Utf8("x")], limit: 10 }"#
251        );
252
253        let projection = Some(vec![1, 2]);
254        let request = ScanRequest {
255            projection,
256            limit: Some(10),
257            ..Default::default()
258        };
259        assert_eq!(
260            request.to_string(),
261            "ScanRequest { projection: [1, 2], limit: 10 }"
262        );
263
264        let request = ScanRequest {
265            series_row_selector: Some(TimeSeriesRowSelector::LastRow { after_merge: true }),
266            snapshot_on_scan: true,
267            exact_sequence_range: true,
268            ..Default::default()
269        };
270        assert_eq!(
271            request.to_string(),
272            "ScanRequest { series_row_selector: LastRow { after_merge: true }, snapshot_on_scan: true, exact_sequence_range: true }"
273        );
274
275        assert_eq!(
276            TimeSeriesRowSelector::LastRow { after_merge: false }.to_string(),
277            "LastRow { after_merge: false }"
278        );
279
280        let request = ScanRequest {
281            skip_sst_files: true,
282            ..Default::default()
283        };
284        assert_eq!(request.to_string(), "ScanRequest { skip_sst_files: true }");
285    }
286}