1use std::sync::{Arc, Weak};
16
17use common_catalog::consts::INFORMATION_SCHEMA_FLOW_TABLE_ID;
18use common_error::ext::BoxedError;
19use common_meta::ddl::create_flow::{FlowType, effective_eval_schedule_from_flow_info};
20use common_meta::key::FlowId;
21use common_meta::key::flow::FlowMetadataManager;
22use common_meta::key::flow::flow_info::FlowInfoValue;
23use common_meta::key::flow::flow_state::FlowStat;
24use common_recordbatch::adapter::RecordBatchStreamAdapter;
25use common_recordbatch::{DfSendableRecordBatchStream, RecordBatch, SendableRecordBatchStream};
26use datafusion::execution::TaskContext;
27use datafusion::physical_plan::streaming::PartitionStream as DfPartitionStream;
28use datatypes::prelude::ConcreteDataType as CDT;
29use datatypes::scalars::ScalarVectorBuilder;
30use datatypes::schema::{ColumnSchema, Schema, SchemaRef};
31use datatypes::timestamp::TimestampMillisecond;
32use datatypes::value::Value;
33use datatypes::vectors::{
34 Int64VectorBuilder, StringVectorBuilder, TimestampMillisecondVectorBuilder,
35 UInt32VectorBuilder, UInt64VectorBuilder, VectorRef,
36};
37use futures::{StreamExt, TryStreamExt};
38use snafu::{OptionExt, ResultExt};
39use sql::ast::Ident;
40use sql::dialect::GreptimeDbDialect;
41use sql::parser::ParserContext;
42use sql::statements::create::{CreateFlow, SqlOrTql};
43use sql::statements::statement::Statement;
44use store_api::storage::{ScanRequest, TableId};
45
46use crate::CatalogManager;
47use crate::batch_scan::BatchScanner;
48use crate::error::{
49 CreateRecordBatchSnafu, InternalSnafu, JsonSnafu, ListFlowsSnafu, Result,
50 UpgradeWeakCatalogManagerRefSnafu,
51};
52use crate::information_schema::{FLOWS, Predicates};
53use crate::kvbackend::KvBackendCatalogManager;
54use crate::system_schema::SystemTable;
55use crate::system_schema::information_schema::loaders::{self, FlowInfoLoader};
56use crate::system_schema::information_schema::{InformationSchemaTableScope, InformationTable};
57use crate::system_schema::utils;
58
59const INIT_CAPACITY: usize = 42;
60
61pub const FLOW_NAME: &str = "flow_name";
64pub const FLOW_ID: &str = "flow_id";
65pub const STATE_SIZE: &str = "state_size";
66pub const TABLE_CATALOG: &str = "table_catalog";
67pub const FLOW_DEFINITION: &str = "flow_definition";
68pub const COMMENT: &str = "comment";
69pub const EXPIRE_AFTER: &str = "expire_after";
70pub const SOURCE_TABLE_IDS: &str = "source_table_ids";
71pub const SINK_TABLE_NAME: &str = "sink_table_name";
72pub const FLOWNODE_IDS: &str = "flownode_ids";
73pub const OPTIONS: &str = "options";
74pub const CREATED_TIME: &str = "created_time";
75pub const UPDATED_TIME: &str = "updated_time";
76pub const LAST_EXECUTION_TIME: &str = "last_execution_time";
77pub const SOURCE_TABLE_NAMES: &str = "source_table_names";
78pub const FLOWNODE_ADDRS: &str = "flownode_addrs";
79
80#[derive(Debug)]
82pub(super) struct InformationSchemaFlows {
83 schema: SchemaRef,
84 catalog_name: String,
85 catalog_manager: Weak<dyn CatalogManager>,
86 flow_metadata_manager: Arc<FlowMetadataManager>,
87}
88
89impl InformationSchemaFlows {
90 pub(super) fn new(
91 catalog_name: String,
92 catalog_manager: Weak<dyn CatalogManager>,
93 flow_metadata_manager: Arc<FlowMetadataManager>,
94 ) -> Self {
95 Self {
96 schema: Self::schema(),
97 catalog_name,
98 catalog_manager,
99 flow_metadata_manager,
100 }
101 }
102
103 pub(crate) fn schema() -> SchemaRef {
107 Arc::new(Schema::new(
108 vec![
109 (FLOW_NAME, CDT::string_datatype(), false),
110 (FLOW_ID, CDT::uint32_datatype(), false),
111 (STATE_SIZE, CDT::uint64_datatype(), true),
112 (TABLE_CATALOG, CDT::string_datatype(), false),
113 (FLOW_DEFINITION, CDT::string_datatype(), false),
114 (COMMENT, CDT::string_datatype(), true),
115 (EXPIRE_AFTER, CDT::int64_datatype(), true),
116 (SOURCE_TABLE_IDS, CDT::string_datatype(), true),
117 (SINK_TABLE_NAME, CDT::string_datatype(), false),
118 (FLOWNODE_IDS, CDT::string_datatype(), true),
119 (OPTIONS, CDT::string_datatype(), true),
120 (CREATED_TIME, CDT::timestamp_millisecond_datatype(), false),
121 (UPDATED_TIME, CDT::timestamp_millisecond_datatype(), false),
122 (
123 LAST_EXECUTION_TIME,
124 CDT::timestamp_millisecond_datatype(),
125 true,
126 ),
127 (SOURCE_TABLE_NAMES, CDT::string_datatype(), true),
128 (FLOWNODE_ADDRS, CDT::string_datatype(), true),
129 ]
130 .into_iter()
131 .map(|(name, ty, nullable)| ColumnSchema::new(name, ty, nullable))
132 .collect(),
133 ))
134 }
135
136 pub(crate) fn generate_show_create_flow(flow_info: &FlowInfoValue) -> Result<String> {
138 let mut parser_ctx = ParserContext::new(&GreptimeDbDialect {}, flow_info.raw_sql())
139 .map_err(BoxedError::new)
140 .context(InternalSnafu)?;
141
142 let query = parser_ctx
143 .parse_statement()
144 .map_err(BoxedError::new)
145 .context(InternalSnafu)?;
146
147 let raw_query = match &query {
148 Statement::Tql(_) => flow_info.raw_sql().clone(),
149 _ => query.to_string(),
150 };
151
152 let query = Box::new(
153 SqlOrTql::try_from_statement(query, &raw_query)
154 .map_err(BoxedError::new)
155 .context(InternalSnafu)?,
156 );
157
158 let comment = if flow_info.comment().is_empty() {
159 None
160 } else {
161 Some(flow_info.comment().clone())
162 };
163
164 let stmt = CreateFlow {
165 flow_name: sql::ast::ObjectName::from(vec![Ident::new(flow_info.flow_name())]),
166 sink_table_name: sql::ast::ObjectName::from(vec![
167 Ident::new(&flow_info.sink_table_name().schema_name),
168 Ident::new(&flow_info.sink_table_name().table_name),
169 ]),
170 or_replace: false,
171 if_not_exists: true,
172 expire_after: flow_info.expire_after(),
173 eval_interval: flow_info.eval_interval(),
174 eval_offset: effective_eval_schedule_from_flow_info(flow_info)
175 .map_err(BoxedError::new)
176 .context(InternalSnafu)?
177 .map(|schedule| schedule.anchor_secs)
178 .filter(|anchor_secs| *anchor_secs != 0),
179 comment,
180 flow_options: sql::statements::OptionMap::from_filtered_string_map(
181 flow_info.options(),
182 &[FlowType::FLOW_TYPE_KEY],
183 ),
184 query,
185 };
186
187 Ok(stmt.to_string())
188 }
189
190 fn builder(&self) -> InformationSchemaFlowsBuilder {
191 InformationSchemaFlowsBuilder::new(
192 self.schema.clone(),
193 self.catalog_name.clone(),
194 self.catalog_manager.clone(),
195 &self.flow_metadata_manager,
196 )
197 }
198}
199
200impl InformationTable for InformationSchemaFlows {
201 fn scope(&self) -> InformationSchemaTableScope {
202 InformationSchemaTableScope::Catalog
203 }
204}
205
206impl SystemTable for InformationSchemaFlows {
207 fn table_id(&self) -> TableId {
208 INFORMATION_SCHEMA_FLOW_TABLE_ID
209 }
210
211 fn table_name(&self) -> &'static str {
212 FLOWS
213 }
214
215 fn schema(&self) -> SchemaRef {
216 self.schema.clone()
217 }
218
219 fn to_stream(&self, request: ScanRequest) -> Result<SendableRecordBatchStream> {
220 let stream = utils::record_batch_stream(&self.schema, self.builder().scan(Some(request)));
221 Ok(Box::pin(
222 RecordBatchStreamAdapter::try_new(stream)
223 .map_err(BoxedError::new)
224 .context(InternalSnafu)?,
225 ))
226 }
227}
228
229struct InformationSchemaFlowsBuilder {
233 schema: SchemaRef,
234 catalog_name: String,
235 catalog_manager: Weak<dyn CatalogManager>,
236 flow_metadata_manager: Arc<FlowMetadataManager>,
237
238 flow_names: StringVectorBuilder,
239 flow_ids: UInt32VectorBuilder,
240 state_sizes: UInt64VectorBuilder,
241 table_catalogs: StringVectorBuilder,
242 raw_sqls: StringVectorBuilder,
243 comments: StringVectorBuilder,
244 expire_afters: Int64VectorBuilder,
245 source_table_id_groups: StringVectorBuilder,
246 sink_table_names: StringVectorBuilder,
247 flownode_id_groups: StringVectorBuilder,
248 option_groups: StringVectorBuilder,
249 created_time: TimestampMillisecondVectorBuilder,
250 updated_time: TimestampMillisecondVectorBuilder,
251 last_execution_time: TimestampMillisecondVectorBuilder,
252 source_table_names: StringVectorBuilder,
253 flownode_addr_groups: StringVectorBuilder,
254}
255
256impl InformationSchemaFlowsBuilder {
257 fn new(
258 schema: SchemaRef,
259 catalog_name: String,
260 catalog_manager: Weak<dyn CatalogManager>,
261 flow_metadata_manager: &Arc<FlowMetadataManager>,
262 ) -> Self {
263 Self {
264 schema,
265 catalog_name,
266 catalog_manager,
267 flow_metadata_manager: flow_metadata_manager.clone(),
268
269 flow_names: StringVectorBuilder::with_capacity(INIT_CAPACITY),
270 flow_ids: UInt32VectorBuilder::with_capacity(INIT_CAPACITY),
271 state_sizes: UInt64VectorBuilder::with_capacity(INIT_CAPACITY),
272 table_catalogs: StringVectorBuilder::with_capacity(INIT_CAPACITY),
273 raw_sqls: StringVectorBuilder::with_capacity(INIT_CAPACITY),
274 comments: StringVectorBuilder::with_capacity(INIT_CAPACITY),
275 expire_afters: Int64VectorBuilder::with_capacity(INIT_CAPACITY),
276 source_table_id_groups: StringVectorBuilder::with_capacity(INIT_CAPACITY),
277 sink_table_names: StringVectorBuilder::with_capacity(INIT_CAPACITY),
278 flownode_id_groups: StringVectorBuilder::with_capacity(INIT_CAPACITY),
279 option_groups: StringVectorBuilder::with_capacity(INIT_CAPACITY),
280 created_time: TimestampMillisecondVectorBuilder::with_capacity(INIT_CAPACITY),
281 updated_time: TimestampMillisecondVectorBuilder::with_capacity(INIT_CAPACITY),
282 last_execution_time: TimestampMillisecondVectorBuilder::with_capacity(INIT_CAPACITY),
283 source_table_names: StringVectorBuilder::with_capacity(INIT_CAPACITY),
284 flownode_addr_groups: StringVectorBuilder::with_capacity(INIT_CAPACITY),
285 }
286 }
287
288 fn scan(
290 mut self,
291 request: Option<ScanRequest>,
292 ) -> impl futures::Stream<Item = Result<RecordBatch>> {
293 async_stream::try_stream!({
294 let catalog_name = self.catalog_name.clone();
295 let predicates = Predicates::from_scan_request(&request);
296
297 let flow_info_manager = self.flow_metadata_manager.clone();
298
299 let stream = flow_info_manager
301 .flow_name_manager()
302 .flow_names(&catalog_name)
303 .await;
304
305 let flow_stat = {
306 let information_extension = utils::information_extension(&self.catalog_manager)?;
307 information_extension.flow_stats().await?
308 };
309
310 let catalog_manager = self
311 .catalog_manager
312 .upgrade()
313 .context(UpgradeWeakCatalogManagerRefSnafu)?;
314 let cache = catalog_manager
315 .as_any()
316 .downcast_ref::<KvBackendCatalogManager>()
317 .and_then(|manager| manager.flow_info_cache());
318 let names = stream
319 .map_ok(|(name, id)| (name, id.flow_id()))
320 .map(|entry| {
321 entry.map_err(BoxedError::new).context(ListFlowsSnafu {
322 catalog: &catalog_name,
323 })
324 });
325 let loader = FlowInfoLoader::new(
326 cache.as_deref(),
327 flow_info_manager.flow_info_manager(),
328 &catalog_name,
329 );
330 let batches = BatchScanner::METADATA.scan(names, |entries| loader.load(entries));
331 let mut batches = std::pin::pin!(batches);
332 while let Some(batch) = batches.try_next().await? {
333 let flows: Vec<_> = batch
334 .into_iter()
335 .filter(|(id, info)| {
336 predicates.eval(&[
337 (FLOW_NAME, &Value::from(info.flow_name().clone())),
338 (FLOW_ID, &Value::from(*id)),
339 (TABLE_CATALOG, &Value::from(info.catalog_name().clone())),
340 ])
341 })
342 .collect();
343 let names =
344 loaders::load_source_table_names(catalog_manager.as_ref(), &flows).await?;
345 for (id, info) in flows {
346 let source_names = info
347 .source_table_ids()
348 .iter()
349 .filter_map(|id| names.get(id).map(String::as_str))
350 .collect::<Vec<_>>()
351 .join(",");
352 self.add_flow(id, &info, &flow_stat, &source_names).await?;
353 }
354 yield self.finish()?;
355 }
356 })
357 }
358
359 async fn add_flow(
360 &mut self,
361 flow_id: FlowId,
362 flow_info: &FlowInfoValue,
363 flow_stat: &Option<FlowStat>,
364 source_names: &str,
365 ) -> Result<()> {
366 self.flow_names.push(Some(flow_info.flow_name()));
367 self.flow_ids.push(Some(flow_id));
368 self.state_sizes.push(
369 flow_stat
370 .as_ref()
371 .and_then(|state| state.state_size.get(&flow_id).map(|v| *v as u64)),
372 );
373 self.table_catalogs.push(Some(flow_info.catalog_name()));
374 self.raw_sqls
375 .push(Some(&InformationSchemaFlows::generate_show_create_flow(
376 flow_info,
377 )?));
378 self.comments.push(Some(flow_info.comment()));
379 self.expire_afters.push(flow_info.expire_after());
380 self.source_table_id_groups.push(Some(
381 &serde_json::to_string(flow_info.source_table_ids()).context(JsonSnafu {
382 input: format!("{:?}", flow_info.source_table_ids()),
383 })?,
384 ));
385 self.sink_table_names
386 .push(Some(&flow_info.sink_table_name().to_string()));
387 self.flownode_id_groups.push(Some(
388 &serde_json::to_string(flow_info.flownode_ids()).context({
389 JsonSnafu {
390 input: format!("{:?}", flow_info.flownode_ids()),
391 }
392 })?,
393 ));
394 self.option_groups
395 .push(Some(&serde_json::to_string(flow_info.options()).context(
396 JsonSnafu {
397 input: format!("{:?}", flow_info.options()),
398 },
399 )?));
400 self.created_time
401 .push(Some(flow_info.created_time().timestamp_millis().into()));
402 self.updated_time
403 .push(Some(flow_info.updated_time().timestamp_millis().into()));
404 self.last_execution_time
405 .push(flow_stat.as_ref().and_then(|state| {
406 state
407 .last_exec_time_map
408 .get(&flow_id)
409 .map(|v| TimestampMillisecond::new(*v))
410 }));
411 let flownode_addrs = self
412 .flow_metadata_manager
413 .flownode_addrs(flow_id)
414 .await
415 .map_err(BoxedError::new)
416 .context(InternalSnafu)?;
417 if flownode_addrs.is_empty() {
418 self.flownode_addr_groups.push(None);
419 } else {
420 let flownode_addrs_json =
421 serde_json::to_string(&flownode_addrs).with_context(|_| JsonSnafu {
422 input: format!("{:?}", flownode_addrs),
423 })?;
424 self.flownode_addr_groups.push(Some(&flownode_addrs_json));
425 }
426
427 self.source_table_names.push(Some(source_names));
428
429 Ok(())
430 }
431
432 fn finish(&mut self) -> Result<RecordBatch> {
433 let columns: Vec<VectorRef> = vec![
434 Arc::new(self.flow_names.finish()),
435 Arc::new(self.flow_ids.finish()),
436 Arc::new(self.state_sizes.finish()),
437 Arc::new(self.table_catalogs.finish()),
438 Arc::new(self.raw_sqls.finish()),
439 Arc::new(self.comments.finish()),
440 Arc::new(self.expire_afters.finish()),
441 Arc::new(self.source_table_id_groups.finish()),
442 Arc::new(self.sink_table_names.finish()),
443 Arc::new(self.flownode_id_groups.finish()),
444 Arc::new(self.option_groups.finish()),
445 Arc::new(self.created_time.finish()),
446 Arc::new(self.updated_time.finish()),
447 Arc::new(self.last_execution_time.finish()),
448 Arc::new(self.source_table_names.finish()),
449 Arc::new(self.flownode_addr_groups.finish()),
450 ];
451 RecordBatch::new(self.schema.clone(), columns).context(CreateRecordBatchSnafu)
452 }
453}
454
455impl DfPartitionStream for InformationSchemaFlows {
456 fn schema(&self) -> &arrow_schema::SchemaRef {
457 self.schema.arrow_schema()
458 }
459
460 fn execute(&self, _: Arc<TaskContext>) -> DfSendableRecordBatchStream {
461 utils::record_batch_stream(&self.schema, self.builder().scan(None))
462 }
463}
464
465#[cfg(test)]
466mod tests {
467 use std::collections::{BTreeMap, HashMap};
468
469 use common_meta::key::flow::flow_info::{FlowMissedTickPolicy, FlowScheduleConfig, FlowStatus};
470 use sql::parser::ParseOptions;
471 use table::table_name::TableName;
472
473 use super::*;
474
475 fn flow_info_for_show_create(
476 raw_sql: &str,
477 eval_interval_secs: Option<i64>,
478 anchor_secs: i64,
479 options: HashMap<String, String>,
480 ) -> FlowInfoValue {
481 let created_time = chrono::DateTime::from_timestamp(1_700_000_000, 0).unwrap();
482 FlowInfoValue {
483 source_table_ids: vec![],
484 all_source_table_names: vec![],
485 unresolved_source_table_names: vec![],
486 sink_table_name: TableName::new("greptime", "public", "sink"),
487 flownode_ids: BTreeMap::new(),
488 catalog_name: "greptime".to_string(),
489 query_context: None,
490 flow_name: "my_flow".to_string(),
491 raw_sql: raw_sql.to_string(),
492 expire_after: None,
493 eval_interval_secs,
494 comment: String::new(),
495 options,
496 status: FlowStatus::Active,
497 created_time,
498 updated_time: created_time,
499 eval_schedule: eval_interval_secs.map(|interval| FlowScheduleConfig {
500 anchor_secs,
501 start_secs: anchor_secs + interval,
502 missed_tick_policy: FlowMissedTickPolicy::BoundedCatchUp,
503 catchup_max_runs: 3,
504 catchup_max_lag_secs: 300,
505 }),
506 allow_sink_create: true,
507 }
508 }
509
510 #[tokio::test]
511 async fn test_flow_scan_preserves_source_order_and_duplicates() {
512 use crate::information_schema::NoopInformationExtension;
513 use crate::kvbackend::KvBackendCatalogManagerBuilder;
514 use common_meta::cache::LayeredCacheRegistryBuilder;
515 use common_meta::ddl::test_util::create_table::test_create_table_task;
516 use common_meta::key::table_route::TableRouteValue;
517 use common_meta::kv_backend::memory::MemoryKvBackend;
518
519 let backend = Arc::new(MemoryKvBackend::default());
520 let registry = cache::with_default_composite_cache_registry(
521 LayeredCacheRegistryBuilder::default()
522 .add_cache_registry(cache::build_fundamental_cache_registry(backend.clone())),
523 )
524 .unwrap()
525 .build();
526 let catalog = KvBackendCatalogManagerBuilder::new(
527 Arc::new(NoopInformationExtension),
528 backend.clone(),
529 Arc::new(registry),
530 )
531 .build();
532 for (id, name) in [(1024, "first"), (1025, "second")] {
533 let mut info = test_create_table_task(name, id).table_info;
534 info.catalog_name = "greptime".into();
535 info.schema_name = "public".into();
536 catalog
537 .table_metadata_manager_ref()
538 .create_table_metadata(info, TableRouteValue::physical(vec![]), Default::default())
539 .await
540 .unwrap();
541 }
542
543 let flows = FlowMetadataManager::new(backend);
544 let mut info = flow_info_for_show_create("SELECT 1", None, 0, HashMap::new());
545 info.source_table_ids = vec![1025, 9999, 1024, 1025];
546 flows.create_flow_metadata(1, info, vec![]).await.unwrap();
547
548 let loader = FlowInfoLoader::new(None, flows.flow_info_manager(), "greptime");
549 let entries = vec![("my_flow".into(), 1), ("my_flow".into(), 1)];
550 let loaded = loader.load(entries).await.unwrap();
551 assert_eq!(loaded.len(), 2);
552 assert!(Arc::ptr_eq(&loaded[0].1, &loaded[1].1));
553
554 let table = catalog
555 .table("greptime", "information_schema", FLOWS, None)
556 .await
557 .unwrap()
558 .unwrap();
559 let batches: Vec<_> = table
560 .scan_to_stream(ScanRequest::default())
561 .await
562 .unwrap()
563 .try_collect()
564 .await
565 .unwrap();
566 assert_eq!(batches.len(), 1);
567 assert_eq!(batches[0].num_rows(), 1);
568 let names = batches[0]
569 .column_by_name(SOURCE_TABLE_NAMES)
570 .unwrap()
571 .as_any()
572 .downcast_ref::<arrow::array::StringArray>()
573 .unwrap();
574 assert_eq!(
575 names.value(0),
576 "greptime.public.second,greptime.public.first,greptime.public.second"
577 );
578 assert!(catalog.flow_info_cache().unwrap().contains_key(&1));
579 }
580
581 #[test]
582 fn test_generate_show_create_flow_with_eval_offset() {
583 let raw_sql = "SELECT max(c1) FROM public.src";
585 let flow_info = flow_info_for_show_create(raw_sql, Some(3600), 120, HashMap::new());
586 let sql = InformationSchemaFlows::generate_show_create_flow(&flow_info).unwrap();
587 assert!(
588 sql.contains("EVAL OFFSET '120 s'"),
589 "EVAL OFFSET must be emitted, got:\n{sql}"
590 );
591 assert!(
592 !sql.contains("__greptime_internal_eval_offset_secs"),
593 "internal key must be absent, got:\n{sql}"
594 );
595
596 let stmts = ParserContext::create_with_dialect(
597 &sql,
598 &GreptimeDbDialect {},
599 ParseOptions::default(),
600 )
601 .unwrap();
602 let Statement::CreateFlow(reparsed) = &stmts[0] else {
603 panic!("unexpected stmt: {:?}", stmts[0]);
604 };
605 assert_eq!(reparsed.eval_interval, Some(3600));
606 assert_eq!(reparsed.eval_offset, Some(120));
607 }
608
609 #[test]
610 fn test_generate_show_create_flow_omits_zero_offset() {
611 let raw_sql = "SELECT max(c1) FROM public.src";
612 let flow_info = flow_info_for_show_create(raw_sql, Some(3600), 0, HashMap::new());
613 let sql = InformationSchemaFlows::generate_show_create_flow(&flow_info).unwrap();
614 assert!(
615 !sql.contains("EVAL OFFSET"),
616 "zero offset must be omitted, got:\n{sql}"
617 );
618 let stmts = ParserContext::create_with_dialect(
619 &sql,
620 &GreptimeDbDialect {},
621 ParseOptions::default(),
622 )
623 .unwrap();
624 let Statement::CreateFlow(reparsed) = &stmts[0] else {
625 panic!("unexpected stmt: {:?}", stmts[0]);
626 };
627 assert_eq!(reparsed.eval_offset, None);
628 }
629}