Skip to main content

common_query/
lib.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
15pub mod columnar_value;
16pub mod error;
17pub mod logical_plan;
18pub mod native_histogram;
19pub mod prelude;
20pub mod prometheus;
21pub mod promql_annotations;
22pub mod request;
23pub mod series_frame;
24pub mod stream;
25#[cfg(any(test, feature = "testing"))]
26pub mod test_util;
27
28use std::fmt::{Debug, Display, Formatter};
29use std::future::Future;
30use std::pin::Pin;
31use std::sync::Arc;
32
33use api::greptime_proto::v1::AddColumnLocation as Location;
34use api::greptime_proto::v1::add_column_location::LocationType;
35use common_error::ext::BoxedError;
36use common_recordbatch::{
37    RecordBatches, SendableRecordBatchMapper, SendableRecordBatchStream, map_dictionary_to_values,
38    map_dictionary_to_values_schema,
39};
40use datafusion::physical_plan::ExecutionPlan;
41use serde::{Deserialize, Serialize};
42use snafu::IntoError;
43use sqlparser_derive::{Visit, VisitMut};
44
45/// new Output struct with output data(previously Output) and output meta
46#[derive(Debug)]
47pub struct Output {
48    pub data: OutputData,
49    pub meta: OutputMeta,
50}
51
52/// Original Output struct
53/// carrying result data to response/client/user interface
54pub enum OutputData {
55    AffectedRows(OutputRows),
56    RecordBatches(RecordBatches),
57    Stream(SendableRecordBatchStream),
58}
59
60impl OutputData {
61    /// Consume the data to pretty printed string.
62    pub async fn pretty_print(self) -> String {
63        match self {
64            OutputData::AffectedRows(x) => {
65                format!("Affected Rows: {x}")
66            }
67            OutputData::RecordBatches(x) => x.pretty_print().unwrap_or_else(|e| e.to_string()),
68            OutputData::Stream(x) => common_recordbatch::util::collect_batches(x)
69                .await
70                .and_then(|x| x.pretty_print())
71                .unwrap_or_else(|e| e.to_string()),
72        }
73    }
74}
75
76/// OutputMeta stores meta information produced/generated during the execution
77#[derive(Debug, Default)]
78pub struct OutputMeta {
79    /// May exist for query output. One can retrieve execution metrics from this plan.
80    pub plan: Option<Arc<dyn ExecutionPlan>>,
81    pub cost: OutputCost,
82    /// Process-local storage results retained for asynchronous batching or confirmed writes.
83    /// Callers needing confirmed writes must await these. Dropping them does not cancel writes.
84    pub write_completions: Vec<WriteCompletion>,
85}
86
87/// Storage outcome of an already accepted write, whether synchronous or asynchronous.
88pub struct WriteCompletion(Pin<Box<dyn Future<Output = WriteProgress> + Send>>);
89
90/// Acknowledged rows for one original input, even when another part failed.
91/// Failed or lost acknowledgements do not establish how many rows were persisted.
92#[derive(Debug, Default, Clone)]
93pub struct WriteProgress {
94    pub affected_rows: usize,
95    pub error: Option<Arc<BoxedError>>,
96}
97
98impl WriteProgress {
99    pub fn failed(error: BoxedError) -> Self {
100        Self {
101            affected_rows: 0,
102            error: Some(Arc::new(error)),
103        }
104    }
105
106    pub fn merge(&mut self, other: Self) {
107        self.affected_rows += other.affected_rows;
108        if self.error.is_none() {
109            self.error = other.error;
110        }
111    }
112
113    pub fn into_result(self) -> Result<usize, BoxedError> {
114        match self.error {
115            Some(error) => Err(BoxedError::new(error::StorageWriteSnafu.into_error(error))),
116            None => Ok(self.affected_rows),
117        }
118    }
119}
120
121impl WriteCompletion {
122    /// Wraps the storage result without changing how the write is scheduled.
123    /// Success reports zero affected rows; use [`Self::with_progress`] for counted writes.
124    pub fn new(completion: impl Future<Output = Result<(), BoxedError>> + Send + 'static) -> Self {
125        Self::with_progress(async move {
126            match completion.await {
127                Ok(()) => WriteProgress::default(),
128                Err(error) => WriteProgress::failed(error),
129            }
130        })
131    }
132
133    pub fn with_progress(completion: impl Future<Output = WriteProgress> + Send + 'static) -> Self {
134        Self(Box::pin(completion))
135    }
136
137    pub async fn progress(self) -> WriteProgress {
138        self.0.await
139    }
140
141    /// Waits for storage success or failure, independently of queue admission.
142    pub async fn wait(self) -> Result<(), BoxedError> {
143        self.0.await.into_result().map(|_| ())
144    }
145}
146
147impl Debug for WriteCompletion {
148    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
149        f.debug_struct("WriteCompletion").finish_non_exhaustive()
150    }
151}
152
153impl Output {
154    /// Observes every dispatched completion before returning any failure.
155    pub async fn write_progress(self) -> WriteProgress {
156        if self.meta.write_completions.is_empty() {
157            return WriteProgress {
158                affected_rows: self.extract_rows_and_cost().0,
159                error: None,
160            };
161        }
162        let mut progress = WriteProgress::default();
163        for completion in self.meta.write_completions {
164            progress.merge(completion.progress().await);
165        }
166        progress
167    }
168    pub fn new_with_affected_rows(affected_rows: OutputRows) -> Self {
169        Self {
170            data: OutputData::AffectedRows(affected_rows),
171            meta: Default::default(),
172        }
173    }
174
175    pub fn new_with_record_batches(recordbatches: RecordBatches) -> Self {
176        Self {
177            data: OutputData::RecordBatches(recordbatches),
178            meta: Default::default(),
179        }
180    }
181
182    pub fn new_with_stream(stream: SendableRecordBatchStream) -> Self {
183        Self {
184            data: OutputData::Stream(stream),
185            meta: Default::default(),
186        }
187    }
188
189    pub fn new(data: OutputData, meta: OutputMeta) -> Self {
190        Self { data, meta }
191    }
192
193    /// Expands dictionary arrays before exposing a query result to a client.
194    pub fn map_dictionary_to_values(self) -> common_recordbatch::error::Result<Self> {
195        let Self { data, meta } = self;
196        let data = match data {
197            OutputData::AffectedRows(rows) => OutputData::AffectedRows(rows),
198            OutputData::RecordBatches(record_batches) => {
199                let original_schema = record_batches.schema();
200                let (mapped_schema, apply_mapper) =
201                    map_dictionary_to_values_schema(original_schema.clone());
202                if !apply_mapper {
203                    OutputData::RecordBatches(record_batches)
204                } else {
205                    let batches = record_batches
206                        .into_iter()
207                        .map(|batch| {
208                            map_dictionary_to_values(batch, &original_schema, &mapped_schema)
209                        })
210                        .collect::<common_recordbatch::error::Result<Vec<_>>>()?;
211                    OutputData::RecordBatches(RecordBatches::try_new(mapped_schema, batches)?)
212                }
213            }
214            OutputData::Stream(stream) => {
215                let (_, apply_mapper) = map_dictionary_to_values_schema(stream.schema());
216                if apply_mapper {
217                    OutputData::Stream(Box::pin(SendableRecordBatchMapper::new(
218                        stream,
219                        map_dictionary_to_values,
220                        map_dictionary_to_values_schema,
221                    )))
222                } else {
223                    OutputData::Stream(stream)
224                }
225            }
226        };
227        Ok(Self { data, meta })
228    }
229
230    pub fn extract_rows_and_cost(&self) -> (OutputRows, OutputCost) {
231        match self.data {
232            OutputData::AffectedRows(rows) => (rows, self.meta.cost),
233            _ => (0, self.meta.cost),
234        }
235    }
236}
237
238impl Debug for OutputData {
239    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
240        match self {
241            OutputData::AffectedRows(rows) => write!(f, "OutputData::AffectedRows({rows})"),
242            OutputData::RecordBatches(recordbatches) => {
243                write!(f, "OutputData::RecordBatches({recordbatches:?})")
244            }
245            OutputData::Stream(s) => {
246                write!(f, "OutputData::Stream(<{}>)", s.name())
247            }
248        }
249    }
250}
251
252impl OutputMeta {
253    pub fn new(plan: Option<Arc<dyn ExecutionPlan>>, cost: usize) -> Self {
254        Self {
255            plan,
256            cost,
257            ..Default::default()
258        }
259    }
260
261    pub fn new_with_plan(plan: Arc<dyn ExecutionPlan>) -> Self {
262        Self {
263            plan: Some(plan),
264            cost: 0,
265            ..Default::default()
266        }
267    }
268
269    pub fn new_with_cost(cost: usize) -> Self {
270        Self {
271            cost,
272            ..Default::default()
273        }
274    }
275}
276
277#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Visit, VisitMut)]
278pub enum AddColumnLocation {
279    First,
280    After { column_name: String },
281}
282
283impl Display for AddColumnLocation {
284    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
285        match self {
286            AddColumnLocation::First => write!(f, r#"FIRST"#),
287            AddColumnLocation::After { column_name } => {
288                write!(f, r#"AFTER {column_name}"#)
289            }
290        }
291    }
292}
293
294impl From<&AddColumnLocation> for Location {
295    fn from(value: &AddColumnLocation) -> Self {
296        match value {
297            AddColumnLocation::First => Location {
298                location_type: LocationType::First.into(),
299                after_column_name: String::default(),
300            },
301            AddColumnLocation::After { column_name } => Location {
302                location_type: LocationType::After.into(),
303                after_column_name: column_name.clone(),
304            },
305        }
306    }
307}
308
309pub type OutputRows = usize;
310pub type OutputCost = usize;