1use std::sync::{Arc, Weak};
16
17use arrow_schema::SchemaRef as ArrowSchemaRef;
18use common_catalog::consts::INFORMATION_SCHEMA_REGION_STATISTICS_TABLE_ID;
19use common_error::ext::BoxedError;
20use common_meta::datanode::RegionStat;
21use common_recordbatch::adapter::RecordBatchStreamAdapter;
22use common_recordbatch::{DfSendableRecordBatchStream, RecordBatch, SendableRecordBatchStream};
23use common_time::timestamp::TimeUnit;
24use datafusion::execution::TaskContext;
25use datafusion::physical_plan::stream::RecordBatchStreamAdapter as DfRecordBatchStreamAdapter;
26use datafusion::physical_plan::streaming::PartitionStream as DfPartitionStream;
27use datatypes::prelude::{ConcreteDataType, ScalarVectorBuilder, VectorRef};
28use datatypes::schema::{ColumnSchema, Schema, SchemaRef};
29use datatypes::timestamp::TimestampMillisecond;
30use datatypes::value::Value;
31use datatypes::vectors::{
32 StringVectorBuilder, TimestampMillisecondVectorBuilder, UInt32VectorBuilder,
33 UInt64VectorBuilder,
34};
35use snafu::ResultExt;
36use store_api::storage::{ScanRequest, TableId};
37
38use crate::CatalogManager;
39use crate::error::{CreateRecordBatchSnafu, InternalSnafu, Result};
40use crate::information_schema::Predicates;
41use crate::system_schema::SystemTable;
42use crate::system_schema::information_schema::{
43 InformationSchemaTableScope, InformationTable, REGION_STATISTICS,
44};
45use crate::system_schema::utils;
46
47const REGION_ID: &str = "region_id";
48const TABLE_ID: &str = "table_id";
49const REGION_NUMBER: &str = "region_number";
50const REGION_ROWS: &str = "region_rows";
51const WRITTEN_BYTES: &str = "written_bytes_since_open";
52const QUERY_CPU_TIME_MILLIS: &str = "query_cpu_time_millis";
53const QUERY_SCANNED_BYTES: &str = "query_scanned_bytes";
54const DISK_SIZE: &str = "disk_size";
55const MEMTABLE_SIZE: &str = "memtable_size";
56const MANIFEST_SIZE: &str = "manifest_size";
57const SST_SIZE: &str = "sst_size";
58const SST_NUM: &str = "sst_num";
59const INDEX_SIZE: &str = "index_size";
60const ENGINE: &str = "engine";
61const REGION_ROLE: &str = "region_role";
62const MIN_TIMESTAMP: &str = "min_timestamp";
63const MAX_TIMESTAMP: &str = "max_timestamp";
64
65const INIT_CAPACITY: usize = 42;
66
67#[derive(Debug)]
84pub(super) struct InformationSchemaRegionStatistics {
85 schema: SchemaRef,
86 catalog_manager: Weak<dyn CatalogManager>,
87}
88
89impl InformationSchemaRegionStatistics {
90 pub(super) fn new(catalog_manager: Weak<dyn CatalogManager>) -> Self {
91 Self {
92 schema: Self::schema(),
93 catalog_manager,
94 }
95 }
96
97 pub(crate) fn schema() -> SchemaRef {
98 Arc::new(Schema::new(vec![
99 ColumnSchema::new(REGION_ID, ConcreteDataType::uint64_datatype(), false),
100 ColumnSchema::new(TABLE_ID, ConcreteDataType::uint32_datatype(), false),
101 ColumnSchema::new(REGION_NUMBER, ConcreteDataType::uint32_datatype(), false),
102 ColumnSchema::new(REGION_ROWS, ConcreteDataType::uint64_datatype(), true),
103 ColumnSchema::new(WRITTEN_BYTES, ConcreteDataType::uint64_datatype(), true),
104 ColumnSchema::new(
105 QUERY_CPU_TIME_MILLIS,
106 ConcreteDataType::uint64_datatype(),
107 true,
108 ),
109 ColumnSchema::new(
110 QUERY_SCANNED_BYTES,
111 ConcreteDataType::uint64_datatype(),
112 true,
113 ),
114 ColumnSchema::new(DISK_SIZE, ConcreteDataType::uint64_datatype(), true),
115 ColumnSchema::new(MEMTABLE_SIZE, ConcreteDataType::uint64_datatype(), true),
116 ColumnSchema::new(MANIFEST_SIZE, ConcreteDataType::uint64_datatype(), true),
117 ColumnSchema::new(SST_SIZE, ConcreteDataType::uint64_datatype(), true),
118 ColumnSchema::new(SST_NUM, ConcreteDataType::uint64_datatype(), true),
119 ColumnSchema::new(INDEX_SIZE, ConcreteDataType::uint64_datatype(), true),
120 ColumnSchema::new(ENGINE, ConcreteDataType::string_datatype(), true),
121 ColumnSchema::new(REGION_ROLE, ConcreteDataType::string_datatype(), true),
122 ColumnSchema::new(
123 MIN_TIMESTAMP,
124 ConcreteDataType::timestamp_millisecond_datatype(),
125 true,
126 ),
127 ColumnSchema::new(
128 MAX_TIMESTAMP,
129 ConcreteDataType::timestamp_millisecond_datatype(),
130 true,
131 ),
132 ]))
133 }
134
135 fn builder(&self) -> InformationSchemaRegionStatisticsBuilder {
136 InformationSchemaRegionStatisticsBuilder::new(
137 self.schema.clone(),
138 self.catalog_manager.clone(),
139 )
140 }
141}
142
143impl InformationTable for InformationSchemaRegionStatistics {
144 fn scope(&self) -> InformationSchemaTableScope {
145 InformationSchemaTableScope::Global
146 }
147}
148
149impl SystemTable for InformationSchemaRegionStatistics {
150 fn table_id(&self) -> TableId {
151 INFORMATION_SCHEMA_REGION_STATISTICS_TABLE_ID
152 }
153
154 fn table_name(&self) -> &'static str {
155 REGION_STATISTICS
156 }
157
158 fn schema(&self) -> SchemaRef {
159 self.schema.clone()
160 }
161
162 fn to_stream(&self, request: ScanRequest) -> Result<SendableRecordBatchStream> {
163 let schema = self.schema.arrow_schema().clone();
164 let mut builder = self.builder();
165
166 let stream = Box::pin(DfRecordBatchStreamAdapter::new(
167 schema,
168 futures::stream::once(async move {
169 builder
170 .make_region_statistics(Some(request))
171 .await
172 .map(|x| x.into_df_record_batch())
173 .map_err(Into::into)
174 }),
175 ));
176
177 Ok(Box::pin(
178 RecordBatchStreamAdapter::try_new(stream)
179 .map_err(BoxedError::new)
180 .context(InternalSnafu)?,
181 ))
182 }
183}
184
185struct InformationSchemaRegionStatisticsBuilder {
186 schema: SchemaRef,
187 catalog_manager: Weak<dyn CatalogManager>,
188
189 region_ids: UInt64VectorBuilder,
190 table_ids: UInt32VectorBuilder,
191 region_numbers: UInt32VectorBuilder,
192 region_rows: UInt64VectorBuilder,
193 written_bytes: UInt64VectorBuilder,
194 query_cpu_time_millis: UInt64VectorBuilder,
195 query_scanned_bytes: UInt64VectorBuilder,
196 disk_sizes: UInt64VectorBuilder,
197 memtable_sizes: UInt64VectorBuilder,
198 manifest_sizes: UInt64VectorBuilder,
199 sst_sizes: UInt64VectorBuilder,
200 sst_nums: UInt64VectorBuilder,
201 index_sizes: UInt64VectorBuilder,
202 engines: StringVectorBuilder,
203 region_roles: StringVectorBuilder,
204 min_timestamps: TimestampMillisecondVectorBuilder,
205 max_timestamps: TimestampMillisecondVectorBuilder,
206}
207
208impl InformationSchemaRegionStatisticsBuilder {
209 fn new(schema: SchemaRef, catalog_manager: Weak<dyn CatalogManager>) -> Self {
210 Self {
211 schema,
212 catalog_manager,
213 region_ids: UInt64VectorBuilder::with_capacity(INIT_CAPACITY),
214 table_ids: UInt32VectorBuilder::with_capacity(INIT_CAPACITY),
215 region_numbers: UInt32VectorBuilder::with_capacity(INIT_CAPACITY),
216 region_rows: UInt64VectorBuilder::with_capacity(INIT_CAPACITY),
217 written_bytes: UInt64VectorBuilder::with_capacity(INIT_CAPACITY),
218 query_cpu_time_millis: UInt64VectorBuilder::with_capacity(INIT_CAPACITY),
219 query_scanned_bytes: UInt64VectorBuilder::with_capacity(INIT_CAPACITY),
220 disk_sizes: UInt64VectorBuilder::with_capacity(INIT_CAPACITY),
221 memtable_sizes: UInt64VectorBuilder::with_capacity(INIT_CAPACITY),
222 manifest_sizes: UInt64VectorBuilder::with_capacity(INIT_CAPACITY),
223 sst_sizes: UInt64VectorBuilder::with_capacity(INIT_CAPACITY),
224 sst_nums: UInt64VectorBuilder::with_capacity(INIT_CAPACITY),
225 index_sizes: UInt64VectorBuilder::with_capacity(INIT_CAPACITY),
226 engines: StringVectorBuilder::with_capacity(INIT_CAPACITY),
227 region_roles: StringVectorBuilder::with_capacity(INIT_CAPACITY),
228 min_timestamps: TimestampMillisecondVectorBuilder::with_capacity(INIT_CAPACITY),
229 max_timestamps: TimestampMillisecondVectorBuilder::with_capacity(INIT_CAPACITY),
230 }
231 }
232
233 async fn make_region_statistics(
235 &mut self,
236 request: Option<ScanRequest>,
237 ) -> Result<RecordBatch> {
238 let predicates = Predicates::from_scan_request(&request);
239 let information_extension = utils::information_extension(&self.catalog_manager)?;
240 let region_stats = information_extension.region_stats().await?;
241 for region_stat in region_stats {
242 self.add_region_statistic(&predicates, region_stat);
243 }
244 self.finish()
245 }
246
247 fn add_region_statistic(&mut self, predicate: &Predicates, region_stat: RegionStat) {
248 let row = [
249 (REGION_ID, &Value::from(region_stat.id.as_u64())),
250 (TABLE_ID, &Value::from(region_stat.id.table_id())),
251 (REGION_NUMBER, &Value::from(region_stat.id.region_number())),
252 (REGION_ROWS, &Value::from(region_stat.num_rows)),
253 (WRITTEN_BYTES, &Value::from(region_stat.written_bytes)),
254 (
255 QUERY_CPU_TIME_MILLIS,
256 &Value::from(region_stat.query_cpu_time / 1_000_000),
257 ),
258 (
259 QUERY_SCANNED_BYTES,
260 &Value::from(region_stat.query_scanned_bytes),
261 ),
262 (DISK_SIZE, &Value::from(region_stat.approximate_bytes)),
263 (MEMTABLE_SIZE, &Value::from(region_stat.memtable_size)),
264 (MANIFEST_SIZE, &Value::from(region_stat.manifest_size)),
265 (SST_SIZE, &Value::from(region_stat.sst_size)),
266 (SST_NUM, &Value::from(region_stat.sst_num)),
267 (INDEX_SIZE, &Value::from(region_stat.index_size)),
268 (ENGINE, &Value::from(region_stat.engine.as_str())),
269 (REGION_ROLE, &Value::from(region_stat.role.to_string())),
270 ];
271
272 if !predicate.eval(&row) {
273 return;
274 }
275
276 self.region_ids.push(Some(region_stat.id.as_u64()));
277 self.table_ids.push(Some(region_stat.id.table_id()));
278 self.region_numbers
279 .push(Some(region_stat.id.region_number()));
280 self.region_rows.push(Some(region_stat.num_rows));
281 self.written_bytes.push(Some(region_stat.written_bytes));
282 self.query_cpu_time_millis
283 .push(Some(region_stat.query_cpu_time / 1_000_000));
284 self.query_scanned_bytes
285 .push(Some(region_stat.query_scanned_bytes));
286 self.disk_sizes.push(Some(region_stat.approximate_bytes));
287 self.memtable_sizes.push(Some(region_stat.memtable_size));
288 self.manifest_sizes.push(Some(region_stat.manifest_size));
289 self.sst_sizes.push(Some(region_stat.sst_size));
290 self.sst_nums.push(Some(region_stat.sst_num));
291 self.index_sizes.push(Some(region_stat.index_size));
292 self.engines.push(Some(®ion_stat.engine));
293 self.region_roles.push(Some(®ion_stat.role.to_string()));
294 self.min_timestamps.push(
297 region_stat
298 .min_timestamp
299 .and_then(|ts| ts.convert_to(TimeUnit::Millisecond))
300 .map(TimestampMillisecond),
301 );
302 self.max_timestamps.push(
303 region_stat
304 .max_timestamp
305 .and_then(|ts| ts.convert_to_ceil(TimeUnit::Millisecond))
306 .map(TimestampMillisecond),
307 );
308 }
309
310 fn finish(&mut self) -> Result<RecordBatch> {
311 let columns: Vec<VectorRef> = vec![
312 Arc::new(self.region_ids.finish()),
313 Arc::new(self.table_ids.finish()),
314 Arc::new(self.region_numbers.finish()),
315 Arc::new(self.region_rows.finish()),
316 Arc::new(self.written_bytes.finish()),
317 Arc::new(self.query_cpu_time_millis.finish()),
318 Arc::new(self.query_scanned_bytes.finish()),
319 Arc::new(self.disk_sizes.finish()),
320 Arc::new(self.memtable_sizes.finish()),
321 Arc::new(self.manifest_sizes.finish()),
322 Arc::new(self.sst_sizes.finish()),
323 Arc::new(self.sst_nums.finish()),
324 Arc::new(self.index_sizes.finish()),
325 Arc::new(self.engines.finish()),
326 Arc::new(self.region_roles.finish()),
327 Arc::new(self.min_timestamps.finish()),
328 Arc::new(self.max_timestamps.finish()),
329 ];
330
331 RecordBatch::new(self.schema.clone(), columns).context(CreateRecordBatchSnafu)
332 }
333}
334
335impl DfPartitionStream for InformationSchemaRegionStatistics {
336 fn schema(&self) -> &ArrowSchemaRef {
337 self.schema.arrow_schema()
338 }
339
340 fn execute(&self, _: Arc<TaskContext>) -> DfSendableRecordBatchStream {
341 let schema = self.schema.arrow_schema().clone();
342 let mut builder = self.builder();
343 Box::pin(DfRecordBatchStreamAdapter::new(
344 schema,
345 futures::stream::once(async move {
346 builder
347 .make_region_statistics(None)
348 .await
349 .map(|x| x.into_df_record_batch())
350 .map_err(Into::into)
351 }),
352 ))
353 }
354}