Skip to main content

file_engine/
query.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(crate) mod file_stream;
16
17use std::collections::HashSet;
18use std::pin::Pin;
19use std::sync::Arc;
20use std::task::{Context, Poll};
21
22use common_datasource::object_store::{LocalFileAccess, RemoteStorageAccess, build_backend};
23use common_recordbatch::adapter::RecordBatchMetrics;
24use common_recordbatch::error::{self as recordbatch_error, Result as RecordBatchResult};
25use common_recordbatch::{
26    DfSendableRecordBatchStream, OrderOption, RecordBatch, RecordBatchStream,
27    SendableRecordBatchStream,
28};
29use datafusion::logical_expr::utils as df_logical_expr_utils;
30use datafusion_expr::expr::Expr;
31use datatypes::arrow::compute as arrow_compute;
32use datatypes::data_type::DataType;
33use datatypes::schema::{Schema, SchemaRef};
34use datatypes::vectors::Helper;
35use futures::Stream;
36use snafu::{GenerateImplicitData, ResultExt, ensure};
37use store_api::storage::ScanRequest;
38
39use self::file_stream::ScanPlanConfig;
40use crate::error::{BuildBackendSnafu, ProjectSchemaSnafu, ProjectionOutOfBoundsSnafu, Result};
41use crate::region::FileRegion;
42
43impl FileRegion {
44    pub async fn query(
45        &self,
46        request: ScanRequest,
47        local_file_access: &LocalFileAccess,
48        remote_storage_access: &RemoteStorageAccess,
49    ) -> Result<SendableRecordBatchStream> {
50        let store = build_backend(
51            &self.url,
52            &self.options,
53            local_file_access,
54            remote_storage_access,
55        )
56        .await
57        .context(BuildBackendSnafu)?;
58
59        let projection = request.projection.as_deref();
60        let file_projection = self.projection_pushdown_to_file(projection)?;
61        let file_filters = self.filters_pushdown_to_file(&request.filters)?;
62        let file_schema = Arc::new(Schema::new(self.file_options.file_column_schemas.clone()));
63
64        let projected_file_schema = if let Some(projection) = &file_projection {
65            Arc::new(
66                file_schema
67                    .try_project(projection)
68                    .context(ProjectSchemaSnafu)?,
69            )
70        } else {
71            file_schema.clone()
72        };
73
74        let file_stream = file_stream::create_stream(
75            &self.format,
76            &ScanPlanConfig {
77                file_schema,
78                files: &self.file_options.files,
79                projection: file_projection.as_ref(),
80                filters: &file_filters,
81                limit: request.limit,
82                store,
83            },
84        )?;
85
86        let scan_schema = self.scan_schema(projection)?;
87
88        Ok(Box::pin(FileToScanRegionStream::new(
89            scan_schema,
90            projected_file_schema,
91            file_stream,
92        )))
93    }
94
95    fn projection_pushdown_to_file(
96        &self,
97        req_projection: Option<&[usize]>,
98    ) -> Result<Option<Vec<usize>>> {
99        let Some(scan_projection) = req_projection else {
100            return Ok(None);
101        };
102
103        let file_column_schemas = &self.file_options.file_column_schemas;
104        let mut file_projection = Vec::with_capacity(scan_projection.len());
105        for column_index in scan_projection {
106            ensure!(
107                *column_index < self.metadata.schema.num_columns(),
108                ProjectionOutOfBoundsSnafu {
109                    column_index: *column_index,
110                    bounds: self.metadata.schema.num_columns()
111                }
112            );
113
114            let column_name = self.metadata.schema.column_name_by_index(*column_index);
115            let file_column_index = file_column_schemas
116                .iter()
117                .position(|c| c.name == column_name);
118            if let Some(file_column_index) = file_column_index {
119                file_projection.push(file_column_index);
120            }
121        }
122        Ok(Some(file_projection))
123    }
124
125    // Collects filters that can be pushed down to the file, specifically filters where Expr
126    // only contains columns from the file.
127    fn filters_pushdown_to_file(&self, scan_filters: &[Expr]) -> Result<Vec<Expr>> {
128        let mut file_filters = Vec::with_capacity(scan_filters.len());
129
130        let file_column_names = self
131            .file_options
132            .file_column_schemas
133            .iter()
134            .map(|c| &c.name)
135            .collect::<HashSet<_>>();
136
137        let mut aux_column_set = HashSet::new();
138        for scan_filter in scan_filters {
139            df_logical_expr_utils::expr_to_columns(scan_filter, &mut aux_column_set)?;
140
141            let all_file_columns = aux_column_set
142                .iter()
143                .all(|column_in_expr| file_column_names.contains(&column_in_expr.name));
144            if all_file_columns {
145                file_filters.push(scan_filter.clone());
146            }
147            aux_column_set.clear();
148        }
149        Ok(file_filters)
150    }
151
152    fn scan_schema(&self, req_projection: Option<&[usize]>) -> Result<SchemaRef> {
153        let schema = if let Some(indices) = req_projection {
154            Arc::new(
155                self.metadata
156                    .schema
157                    .try_project(indices)
158                    .context(ProjectSchemaSnafu)?,
159            )
160        } else {
161            self.metadata.schema.clone()
162        };
163
164        Ok(schema)
165    }
166}
167
168struct FileToScanRegionStream {
169    scan_schema: SchemaRef,
170    file_stream: DfSendableRecordBatchStream,
171    /// Maps columns in `scan_schema` to their index in the projected file schema.
172    /// `None` means the column doesn't exist in the file and should be filled with default values.
173    scan_to_file_projection: Vec<Option<usize>>,
174}
175
176impl RecordBatchStream for FileToScanRegionStream {
177    fn schema(&self) -> SchemaRef {
178        self.scan_schema.clone()
179    }
180
181    fn output_ordering(&self) -> Option<&[OrderOption]> {
182        None
183    }
184
185    fn metrics(&self) -> Option<RecordBatchMetrics> {
186        None
187    }
188}
189
190impl Stream for FileToScanRegionStream {
191    type Item = RecordBatchResult<RecordBatch>;
192
193    fn poll_next(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
194        match Pin::new(&mut self.file_stream).poll_next(ctx) {
195            Poll::Pending => Poll::Pending,
196            Poll::Ready(Some(Ok(file_record_batch))) => {
197                let num_rows = file_record_batch.num_rows();
198                let mut columns = Vec::with_capacity(self.scan_schema.num_columns());
199
200                for (idx, column_schema) in self.scan_schema.column_schemas().iter().enumerate() {
201                    if let Some(file_idx) = self.scan_to_file_projection[idx] {
202                        let expected_arrow_type = column_schema.data_type.as_arrow_type();
203                        let mut array = file_record_batch.column(file_idx).clone();
204
205                        if array.data_type() != &expected_arrow_type {
206                            array = arrow_compute::cast(array.as_ref(), &expected_arrow_type)
207                                .context(recordbatch_error::ArrowComputeSnafu)?;
208                        }
209
210                        let vector = Helper::try_into_vector(array)
211                            .context(recordbatch_error::DataTypesSnafu)?;
212                        columns.push(vector);
213                    } else {
214                        let vector = column_schema
215                            .create_default_vector(num_rows)
216                            .context(recordbatch_error::DataTypesSnafu)?
217                            .ok_or_else(|| {
218                                recordbatch_error::CreateRecordBatchesSnafu {
219                                    reason: format!(
220                                        "column {} is missing from file source and has no default",
221                                        column_schema.name
222                                    ),
223                                }
224                                .build()
225                            })?;
226                        columns.push(vector);
227                    }
228                }
229
230                let record_batch = RecordBatch::new(self.scan_schema.clone(), columns)?;
231
232                Poll::Ready(Some(Ok(record_batch)))
233            }
234            Poll::Ready(Some(Err(error))) => {
235                Poll::Ready(Some(Err(recordbatch_error::Error::PollStream {
236                    error,
237                    location: snafu::Location::generate(),
238                })))
239            }
240            Poll::Ready(None) => Poll::Ready(None),
241        }
242    }
243}
244
245impl FileToScanRegionStream {
246    fn new(
247        scan_schema: SchemaRef,
248        file_schema: SchemaRef,
249        file_stream: DfSendableRecordBatchStream,
250    ) -> Self {
251        let scan_to_file_projection = scan_schema
252            .column_schemas()
253            .iter()
254            .map(|column| file_schema.column_index_by_name(&column.name))
255            .collect();
256
257        Self {
258            scan_schema,
259            file_stream,
260            scan_to_file_projection,
261        }
262    }
263}