Skip to main content

common_function/
state.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 crate::handlers::{FlowServiceHandlerRef, ProcedureServiceHandlerRef, TableMutationHandlerRef};
16
17/// Shared state for SQL functions.
18/// The handlers in state may be `None` in cli command-line or test cases.
19#[derive(Clone, Default)]
20pub struct FunctionState {
21    // The table mutation handler
22    pub table_mutation_handler: Option<TableMutationHandlerRef>,
23    // The procedure service handler
24    pub procedure_service_handler: Option<ProcedureServiceHandlerRef>,
25    // The flownode handler
26    pub flow_service_handler: Option<FlowServiceHandlerRef>,
27}
28
29impl FunctionState {
30    /// Create a mock [`FunctionState`] for test.
31    #[cfg(any(test, feature = "testing"))]
32    pub fn mock() -> Self {
33        use std::sync::Arc;
34
35        use api::v1::meta::{ProcedureStatus, ReconcileRequest};
36        use async_trait::async_trait;
37        use catalog::CatalogManagerRef;
38        use common_base::AffectedRows;
39        use common_meta::rpc::procedure::{
40            GcRegionsRequest, GcResponse, GcTableRequest, ManageRegionFollowerRequest,
41            MigrateRegionRequest, ProcedureStateResponse,
42        };
43        use common_query::Output;
44        use common_query::error::Result;
45        use session::context::QueryContextRef;
46        use store_api::storage::RegionId;
47        use table::requests::{
48            BuildIndexTableRequest, CompactTableRequest, DeleteRequest, FlushTableRequest,
49            InsertRequest,
50        };
51        use table::table_name::TableName;
52
53        use crate::handlers::{FlowServiceHandler, ProcedureServiceHandler, TableMutationHandler};
54        struct MockProcedureServiceHandler;
55        struct MockTableMutationHandler;
56        struct MockFlowServiceHandler;
57        const ROWS: usize = 42;
58
59        #[async_trait]
60        impl ProcedureServiceHandler for MockProcedureServiceHandler {
61            async fn purge_table(
62                &self,
63                _table_name: table::table_name::TableName,
64                _query_ctx: QueryContextRef,
65            ) -> Result<()> {
66                Ok(())
67            }
68
69            async fn migrate_region(
70                &self,
71                _request: MigrateRegionRequest,
72            ) -> Result<Option<String>> {
73                Ok(Some("test_pid".to_string()))
74            }
75
76            async fn reconcile(&self, _request: ReconcileRequest) -> Result<Option<String>> {
77                Ok(Some("test_pid".to_string()))
78            }
79
80            async fn query_procedure_state(&self, _pid: &str) -> Result<ProcedureStateResponse> {
81                Ok(ProcedureStateResponse {
82                    status: ProcedureStatus::Done.into(),
83                    error: "OK".to_string(),
84                    ..Default::default()
85                })
86            }
87
88            async fn manage_region_follower(
89                &self,
90                _request: ManageRegionFollowerRequest,
91            ) -> Result<()> {
92                Ok(())
93            }
94
95            async fn gc_regions(&self, _request: GcRegionsRequest) -> Result<GcResponse> {
96                Ok(GcResponse {
97                    processed_regions: 1,
98                    need_retry_regions: vec![],
99                    deleted_files: 0,
100                    deleted_indexes: 0,
101                })
102            }
103
104            async fn gc_table(&self, _request: GcTableRequest) -> Result<GcResponse> {
105                Ok(GcResponse {
106                    processed_regions: 1,
107                    need_retry_regions: vec![],
108                    deleted_files: 0,
109                    deleted_indexes: 0,
110                })
111            }
112
113            fn catalog_manager(&self) -> &CatalogManagerRef {
114                unimplemented!()
115            }
116        }
117
118        #[async_trait]
119        impl TableMutationHandler for MockTableMutationHandler {
120            async fn insert(
121                &self,
122                _request: InsertRequest,
123                _ctx: QueryContextRef,
124            ) -> Result<Output> {
125                Ok(Output::new_with_affected_rows(ROWS))
126            }
127
128            async fn delete(
129                &self,
130                _request: DeleteRequest,
131                _ctx: QueryContextRef,
132            ) -> Result<AffectedRows> {
133                Ok(ROWS)
134            }
135
136            async fn flush(
137                &self,
138                _request: FlushTableRequest,
139                _ctx: QueryContextRef,
140            ) -> Result<AffectedRows> {
141                Ok(ROWS)
142            }
143
144            async fn compact(
145                &self,
146                _request: CompactTableRequest,
147                _ctx: QueryContextRef,
148            ) -> Result<AffectedRows> {
149                Ok(ROWS)
150            }
151
152            async fn build_index(
153                &self,
154                _request: BuildIndexTableRequest,
155                _ctx: QueryContextRef,
156            ) -> Result<AffectedRows> {
157                Ok(ROWS)
158            }
159
160            async fn flush_region(
161                &self,
162                _region_id: RegionId,
163                _ctx: QueryContextRef,
164            ) -> Result<AffectedRows> {
165                Ok(ROWS)
166            }
167
168            async fn compact_region(
169                &self,
170                _region_id: RegionId,
171                _ctx: QueryContextRef,
172            ) -> Result<AffectedRows> {
173                Ok(ROWS)
174            }
175
176            async fn discard_unflushed_data(
177                &self,
178                _region_id: RegionId,
179                _ctx: QueryContextRef,
180            ) -> Result<AffectedRows> {
181                Ok(ROWS)
182            }
183
184            async fn discard_unflushed_data_by_table(
185                &self,
186                _table_name: TableName,
187                _ctx: QueryContextRef,
188            ) -> Result<AffectedRows> {
189                Ok(ROWS)
190            }
191        }
192
193        #[async_trait]
194        impl FlowServiceHandler for MockFlowServiceHandler {
195            async fn flush(
196                &self,
197                _catalog: &str,
198                _flow: &str,
199                _ctx: QueryContextRef,
200            ) -> Result<api::v1::flow::FlowResponse> {
201                todo!()
202            }
203        }
204
205        Self {
206            table_mutation_handler: Some(Arc::new(MockTableMutationHandler)),
207            procedure_service_handler: Some(Arc::new(MockProcedureServiceHandler)),
208            flow_service_handler: Some(Arc::new(MockFlowServiceHandler)),
209        }
210    }
211}