mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-28 05:34:02 +00:00
feat(flow): remove the streaming executor and the dual-engine router
The legacy per-request Flow runtime is gone, leaving the batching scheduler as the only execution profile. A flow whose SQL has no time window therefore needs an explicit `EVAL INTERVAL`; without one it used to run as a request-local streaming query and is now rejected with that hint. Persisted flows whose options say `flow_type: streaming` are still listed and droppable, but creating or recovering one fails with a "drop and recreate" error, so no old definition can silently run on a scheduler that no longer exists. `FlowType::Streaming` and `get_flow_type_from_options` stay for deserializing old metadata and old procedure data, and the reserved `flow_type` key keeps being written so the metadata shape does not change. Instant-TTL sources are rejected for every flow: the batching scheduler cannot read them, and there is no second profile to fall back to. The full-row mirror RPC is deliberately kept. It is not a streaming leftover: it is the only path that tells batching that a SQL `INSERT INTO` changed a source table, since bulk/COPY and the HTTP batcher use the timestamp-only path. `BatchingEngine::handle_inserts_inner` filters requests per task by source table name, so forwarding all of them replaces the removed routing table. Dead code that only the streaming runtime reached is removed as well: the stateless query and its memtable source, the relation/repr row model, the single-attempt frontend insert, and the `InsertIntoFlow` error variant. Those were invisible to the compiler because the crate allows dead code. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
This commit is contained in:
Generated
-7
@@ -5509,7 +5509,6 @@ dependencies = [
|
||||
"datafusion-physical-expr",
|
||||
"datatypes",
|
||||
"futures",
|
||||
"get-size2",
|
||||
"greptime-proto",
|
||||
"hostname 0.4.1",
|
||||
"humantime-serde",
|
||||
@@ -6056,12 +6055,6 @@ dependencies = [
|
||||
"libm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "get-size2"
|
||||
version = "0.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3b5034f0cabe33ffe2b0c193e283568fb0ebe93fe93f05b424ed1b751d2cf42b"
|
||||
|
||||
[[package]]
|
||||
name = "getopts"
|
||||
version = "0.2.23"
|
||||
|
||||
@@ -59,7 +59,7 @@ use datanode::config::{DatanodeOptions, StorageConfig};
|
||||
use datanode::datanode::{Datanode, DatanodeBuilder};
|
||||
use datanode::region_server::RegionServer;
|
||||
use flow::{
|
||||
FlowDualEngineRef, FlownodeBuilder, FlownodeInstance, FlownodeOptions, FrontendClient,
|
||||
FlownodeBuilder, FlownodeEngineRef, FlownodeInstance, FlownodeOptions, FrontendClient,
|
||||
GrpcQueryHandlerWithBoxedError,
|
||||
};
|
||||
use frontend::frontend::Frontend;
|
||||
@@ -958,7 +958,7 @@ pub struct LeaderServicesContext {
|
||||
pub kv_backend: KvBackendRef,
|
||||
pub cache_registry: LayeredCacheRegistryRef,
|
||||
pub catalog_manager: CatalogManagerRef,
|
||||
pub flow_engine: FlowDualEngineRef,
|
||||
pub flow_engine: FlownodeEngineRef,
|
||||
pub frontend_client: Arc<FrontendClient>,
|
||||
pub node_id: Option<DatanodeId>,
|
||||
pub init_regions_parallelism: usize,
|
||||
|
||||
+39
-31
@@ -7,29 +7,33 @@ Repo-wide rules that apply to here: [`.agents/architecture-invariants.md`](../..
|
||||
|
||||
## What this crate does
|
||||
|
||||
Flownode provides two flow profiles:
|
||||
Flownode runs **one** flow execution profile: the batching scheduler.
|
||||
|
||||
- **Streaming mode**: a single stateless DataFusion query profile. Each mirror
|
||||
insert is materialized as a transient input table, executed against the
|
||||
retained logical plan, and written directly to the sink through
|
||||
`batching_mode::frontend_client::FrontendClient`.
|
||||
- **Batching mode**: splits data into time windows and periodically runs
|
||||
aggregation SQL through the frontend, writing results back to a sink table.
|
||||
- **Batching mode** (`batching_mode`): splits data into time windows and
|
||||
periodically runs aggregation SQL through the frontend, writing results back
|
||||
to a sink table. A flow whose SQL has no usable time window runs as an
|
||||
explicit full-query flow and needs `EVAL INTERVAL`.
|
||||
|
||||
Users cannot select a mode directly: `flow_type` is a reserved internal option.
|
||||
The legacy streaming executor (per-insert stateless DataFusion query) has been
|
||||
removed. There is no mode selection left: `FlowEngine` in
|
||||
`src/flow/src/engine.rs` is implemented by `FlownodeEngine`
|
||||
(`adapter/flownode_impl.rs`), which forwards everything to `BatchingEngine`.
|
||||
`StatementExecutor::determine_flow_type` in `src/operator/src/statement/ddl.rs`
|
||||
owns current mode selection. `FlowDualEngine` defaults missing internal
|
||||
`flow_type` metadata to batching for compatibility. Read those paths before
|
||||
changing routing rules.
|
||||
now only *validates* a flow definition and always reports batching.
|
||||
|
||||
Historical `flow_type: streaming` metadata stays readable and droppable, but it
|
||||
must never reach a runtime: `FlownodeEngine::create_flow` rejects it with a
|
||||
"recreate this flow" error. Do not delete `FlowType::Streaming` or
|
||||
`get_flow_type_from_options` — old persisted options and old procedure data
|
||||
must keep deserializing.
|
||||
|
||||
## Module map
|
||||
|
||||
| Module | Path | Purpose |
|
||||
| --- | --- | --- |
|
||||
| `engine` | `src/flow/src/engine.rs` | `FlowEngine` lifecycle contract |
|
||||
| `adapter` | `src/flow/src/adapter.rs`, `src/flow/src/adapter/` | Stateless streaming execution, dual-engine dispatch, shared source schema/default normalization, and sink creation |
|
||||
| `adapter` | `src/flow/src/adapter.rs`, `src/flow/src/adapter/` | `FlownodeEngine` (create/drop/flush/recover, insert routing), auto-column constants shared with batching, and the retained-plan → sink-schema helper |
|
||||
| `batching_mode` | `src/flow/src/batching_mode.rs`, `src/flow/src/batching_mode/` | `BatchingEngine`, scheduling, time windows, frontend client, and checkpoints |
|
||||
| `repr` | `src/flow/src/repr.rs` | Shared row and relation schema representations |
|
||||
| `server` | `src/flow/src/server.rs` | gRPC `Flow` service and flownode builders |
|
||||
| `heartbeat` | `src/flow/src/heartbeat.rs` | Reports flownode state/stats to metasrv |
|
||||
|
||||
@@ -38,24 +42,22 @@ Flow metadata lives in `common-meta`, not here:
|
||||
|
||||
## Data flow
|
||||
|
||||
`Frontend → Flownode (gRPC)` → `FlowService` (`server.rs`) → `FlowDualEngine`
|
||||
(`adapter/flownode_impl.rs`) routes by `FlowType`:
|
||||
`Frontend → Flownode (gRPC)` → `FlowService` (`server.rs`) → `FlownodeEngine`
|
||||
(`adapter/flownode_impl.rs`) → `BatchingEngine`.
|
||||
|
||||
- Streaming: mirror rows are normalized against the source schema, evaluated by
|
||||
the retained stateless DataFusion plan, and sent to the sink via
|
||||
`FrontendClient`.
|
||||
- Batching: marks dirty windows; a task later runs aggregation SQL via the
|
||||
frontend client and writes the sink table.
|
||||
|
||||
`FlowType::Streaming` and mirror routing are shared contracts; preserve both
|
||||
when changing dispatch. Preserve batching behavior and the shared schema,
|
||||
default, and sink-creation helpers.
|
||||
- `FlowService::handle_mirror_request` → `FlowEngine::handle_flow_inserts` →
|
||||
`BatchingEngine::handle_inserts_inner`. The mirrored full-row payload is how
|
||||
batching marks dirty windows (and `set_dirty()` for flows without a time
|
||||
window). **Keep this RPC and this path**: it is not a leftover of the removed
|
||||
streaming executor.
|
||||
- A flow round later runs its SQL through the frontend client and writes the
|
||||
sink table.
|
||||
|
||||
## Public surface
|
||||
|
||||
- gRPC `Flow` service in `src/flow/src/server.rs`.
|
||||
- Local streaming sink writes and batching query execution use `Channel::Internal`
|
||||
so meter collectors can account for sink writes without charging ingestion quota.
|
||||
- Batching query execution uses `Channel::Internal` so meter collectors can
|
||||
account for sink writes without charging ingestion quota.
|
||||
- `FlowEngine` trait in `src/flow/src/engine.rs`.
|
||||
- Started from the `cmd` crate via `FlownodeBuilder` / `FlownodeInstance`.
|
||||
|
||||
@@ -65,12 +67,18 @@ default, and sink-creation helpers.
|
||||
cargo nextest run -p flow
|
||||
```
|
||||
|
||||
Stateless streaming tests are under `src/flow/src/adapter/stateless.rs`.
|
||||
There are no stateless streaming tests left; adapter tests cover the retained
|
||||
plan-to-schema helper shared with batching.
|
||||
|
||||
## Gotchas
|
||||
|
||||
- Batching and streaming differ in latency and state. Confirm the selected mode
|
||||
before reasoning about a flow.
|
||||
- Streaming is finite and stateless per mirror request; it has no worker graph,
|
||||
background runtime, or replay state.
|
||||
- Internal flow timestamps and table time columns are separate contracts.
|
||||
- `adapter.rs` still owns `AUTO_CREATED_PLACEHOLDER_TS_COL` /
|
||||
`AUTO_CREATED_UPDATE_AT_TS_COL` and `output_column_schemas`; batching imports
|
||||
them. Do not move or delete them without updating `batching_mode`.
|
||||
- Recovery collects per-flow errors and logs them
|
||||
(`adapter/flownode_impl.rs`): one rejected (old streaming) flow must not stop
|
||||
the other flows from recovering.
|
||||
- `flow_type` is still written into flow options so the metadata shape does not
|
||||
change; it is a reserved internal key and must stay out of `SHOW CREATE FLOW`
|
||||
rendering.
|
||||
|
||||
@@ -39,7 +39,6 @@ datafusion-expr.workspace = true
|
||||
datafusion-physical-expr.workspace = true
|
||||
datatypes.workspace = true
|
||||
futures.workspace = true
|
||||
get-size2 = "0.1.2"
|
||||
greptime-proto.workspace = true
|
||||
hostname.workspace = true
|
||||
humantime-serde.workspace = true
|
||||
|
||||
+3
-1075
File diff suppressed because it is too large
Load Diff
@@ -39,59 +39,55 @@ use itertools::Itertools;
|
||||
use operator::utils::try_to_session_query_context;
|
||||
use session::context::QueryContextBuilder;
|
||||
use snafu::{OptionExt, ResultExt, ensure};
|
||||
use store_api::storage::{RegionId, TableId};
|
||||
use tokio::sync::{Mutex, RwLock};
|
||||
|
||||
use crate::adapter::{CreateFlowArgs, StreamingEngine};
|
||||
use crate::batching_mode::engine::BatchingEngine;
|
||||
use crate::engine::{FlowEngine, FlowStatProvider};
|
||||
use crate::error::{
|
||||
CreateFlowSnafu, ExternalSnafu, FlowNotFoundSnafu, FlowNotRecoveredSnafu,
|
||||
IllegalCheckTaskStateSnafu, InternalSnafu, JoinTaskSnafu, ListFlowsSnafu,
|
||||
NoAvailableFrontendSnafu, SyncCheckTaskSnafu, UnsupportedSnafu,
|
||||
IllegalCheckTaskStateSnafu, InternalSnafu, ListFlowsSnafu, NoAvailableFrontendSnafu,
|
||||
SyncCheckTaskSnafu, UnsupportedSnafu,
|
||||
};
|
||||
use crate::metrics::{METRIC_FLOW_ROWS, METRIC_FLOW_TASK_COUNT};
|
||||
use crate::utils::StateReportHandler;
|
||||
use crate::{Error, FlowId};
|
||||
use crate::{CreateFlowArgs, Error, FlowId};
|
||||
|
||||
/// Ref to [`FlowDualEngine`]
|
||||
pub type FlowDualEngineRef = Arc<FlowDualEngine>;
|
||||
/// Ref to [`FlownodeEngine`]
|
||||
pub type FlownodeEngineRef = Arc<FlownodeEngine>;
|
||||
|
||||
/// Manage both streaming and batching mode engine
|
||||
/// Manage the batching flow engine
|
||||
///
|
||||
/// including create/drop/flush flow
|
||||
/// and redirect insert requests to the appropriate engine
|
||||
pub struct FlowDualEngine {
|
||||
streaming_engine: Arc<StreamingEngine>,
|
||||
/// and redirect insert requests to the batching engine
|
||||
pub struct FlownodeEngine {
|
||||
batching_engine: Arc<BatchingEngine>,
|
||||
/// receive a oneshot sender to send state report
|
||||
state_report_handler: RwLock<Option<StateReportHandler>>,
|
||||
/// helper struct for faster query flow by table id or vice versa
|
||||
src_table2flow: RwLock<SrcTableToFlow>,
|
||||
flow_metadata_manager: Arc<FlowMetadataManager>,
|
||||
catalog_manager: Arc<dyn CatalogManager>,
|
||||
check_task: tokio::sync::Mutex<Option<ConsistentCheckTask>>,
|
||||
plugins: Plugins,
|
||||
/// `Some` in distributed mode, `None` in standalone mode
|
||||
node_id: Option<u32>,
|
||||
done_recovering: AtomicBool,
|
||||
}
|
||||
|
||||
impl FlowDualEngine {
|
||||
impl FlownodeEngine {
|
||||
pub fn new(
|
||||
streaming_engine: Arc<StreamingEngine>,
|
||||
node_id: Option<u32>,
|
||||
batching_engine: Arc<BatchingEngine>,
|
||||
flow_metadata_manager: Arc<FlowMetadataManager>,
|
||||
catalog_manager: Arc<dyn CatalogManager>,
|
||||
plugins: Plugins,
|
||||
) -> Self {
|
||||
Self {
|
||||
streaming_engine,
|
||||
batching_engine,
|
||||
state_report_handler: Default::default(),
|
||||
src_table2flow: RwLock::new(SrcTableToFlow::default()),
|
||||
flow_metadata_manager,
|
||||
catalog_manager,
|
||||
check_task: Mutex::new(None),
|
||||
plugins,
|
||||
node_id,
|
||||
done_recovering: AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
@@ -99,7 +95,7 @@ impl FlowDualEngine {
|
||||
/// Set `done_recovering` to true
|
||||
/// indicate that we are ready to handle requests
|
||||
pub fn set_done_recovering(&self) {
|
||||
info!("FlowDualEngine done recovering");
|
||||
info!("FlownodeEngine done recovering");
|
||||
self.done_recovering
|
||||
.store(true, std::sync::atomic::Ordering::Release);
|
||||
}
|
||||
@@ -117,7 +113,7 @@ impl FlowDualEngine {
|
||||
}
|
||||
|
||||
warn!(
|
||||
"FlowDualEngine is not done recovering, {} insert request waiting for recovery",
|
||||
"FlownodeEngine is not done recovering, {} insert request waiting for recovery",
|
||||
waiting_req_cnt
|
||||
);
|
||||
// wait 3 seconds, check every 1 second
|
||||
@@ -126,7 +122,7 @@ impl FlowDualEngine {
|
||||
let max_retry = 3;
|
||||
while retry < max_retry && !self.is_recover_done() {
|
||||
warn!(
|
||||
"FlowDualEngine is not done recovering, retry {} in 1s",
|
||||
"FlownodeEngine is not done recovering, retry {} in 1s",
|
||||
retry
|
||||
);
|
||||
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
|
||||
@@ -135,7 +131,7 @@ impl FlowDualEngine {
|
||||
if retry == max_retry {
|
||||
return FlowNotRecoveredSnafu.fail();
|
||||
} else {
|
||||
info!("FlowDualEngine is done recovering");
|
||||
info!("FlownodeEngine is done recovering");
|
||||
}
|
||||
// TODO(discord9): also put to centralized logging for flow once it implemented
|
||||
Ok(())
|
||||
@@ -147,11 +143,7 @@ impl FlowDualEngine {
|
||||
|
||||
/// Determine if the engine is in distributed mode
|
||||
pub fn is_distributed(&self) -> bool {
|
||||
self.streaming_engine.node_id.is_some()
|
||||
}
|
||||
|
||||
pub fn streaming_engine(&self) -> Arc<StreamingEngine> {
|
||||
self.streaming_engine.clone()
|
||||
self.node_id.is_some()
|
||||
}
|
||||
|
||||
pub fn batching_engine(&self) -> Arc<BatchingEngine> {
|
||||
@@ -278,7 +270,7 @@ impl FlowDualEngine {
|
||||
allow_drop: bool,
|
||||
) -> Result<(), Error> {
|
||||
// use nodeid to determine if this is standalone/distributed mode, and retrieve all flows in this node(in distributed mode)/or all flows(in standalone mode)
|
||||
let nodeid = self.streaming_engine.node_id;
|
||||
let nodeid = self.node_id;
|
||||
let should_exists: Vec<_> = if let Some(nodeid) = nodeid {
|
||||
// nodeid is available, so we only need to check flows on this node
|
||||
// which also means we are in distributed mode
|
||||
@@ -493,7 +485,7 @@ struct ConsistentCheckTask {
|
||||
}
|
||||
|
||||
impl ConsistentCheckTask {
|
||||
async fn start_check_task(engine: &Arc<FlowDualEngine>) -> Result<Self, Error> {
|
||||
async fn start_check_task(engine: &Arc<FlownodeEngine>) -> Result<Self, Error> {
|
||||
let engine = engine.clone();
|
||||
let min_refresh_duration = engine
|
||||
.batching_engine()
|
||||
@@ -586,230 +578,89 @@ impl ConsistentCheckTask {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct SrcTableToFlow {
|
||||
/// mapping of table ids to flow ids for streaming mode
|
||||
stream: HashMap<TableId, HashSet<FlowId>>,
|
||||
/// mapping of table ids to flow ids for batching mode
|
||||
batch: HashMap<TableId, HashSet<FlowId>>,
|
||||
/// mapping of flow ids to (flow type, source table ids)
|
||||
flow_infos: HashMap<FlowId, (FlowType, Vec<TableId>)>,
|
||||
}
|
||||
|
||||
impl SrcTableToFlow {
|
||||
fn in_stream(&self, table_id: TableId) -> bool {
|
||||
self.stream.contains_key(&table_id)
|
||||
}
|
||||
fn in_batch(&self, table_id: TableId) -> bool {
|
||||
self.batch.contains_key(&table_id)
|
||||
}
|
||||
fn add_flow(&mut self, flow_id: FlowId, flow_type: FlowType, src_table_ids: Vec<TableId>) {
|
||||
let mapping = match flow_type {
|
||||
FlowType::Streaming => &mut self.stream,
|
||||
FlowType::Batching => &mut self.batch,
|
||||
};
|
||||
|
||||
for src_table in src_table_ids.clone() {
|
||||
mapping
|
||||
.entry(src_table)
|
||||
.and_modify(|flows| {
|
||||
flows.insert(flow_id);
|
||||
})
|
||||
.or_insert_with(|| {
|
||||
let mut set = HashSet::new();
|
||||
set.insert(flow_id);
|
||||
set
|
||||
});
|
||||
}
|
||||
self.flow_infos.insert(flow_id, (flow_type, src_table_ids));
|
||||
}
|
||||
|
||||
fn remove_flow(&mut self, flow_id: FlowId) {
|
||||
let mapping = match self.get_flow_type(flow_id) {
|
||||
Some(FlowType::Streaming) => &mut self.stream,
|
||||
Some(FlowType::Batching) => &mut self.batch,
|
||||
None => return,
|
||||
};
|
||||
if let Some((_, src_table_ids)) = self.flow_infos.remove(&flow_id) {
|
||||
for src_table in src_table_ids {
|
||||
if let Some(flows) = mapping.get_mut(&src_table) {
|
||||
flows.remove(&flow_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn get_flow_type(&self, flow_id: FlowId) -> Option<FlowType> {
|
||||
self.flow_infos
|
||||
.get(&flow_id)
|
||||
.map(|(flow_type, _)| flow_type)
|
||||
.cloned()
|
||||
}
|
||||
}
|
||||
|
||||
impl FlowEngine for FlowDualEngine {
|
||||
impl FlowEngine for FlownodeEngine {
|
||||
async fn create_flow(&self, args: CreateFlowArgs) -> Result<Option<FlowId>, Error> {
|
||||
let flow_type = args
|
||||
.flow_options
|
||||
.get(FlowType::FLOW_TYPE_KEY)
|
||||
.map(|s| s.as_str());
|
||||
|
||||
let flow_type = match flow_type {
|
||||
Some(FlowType::BATCHING) => FlowType::Batching,
|
||||
Some(FlowType::STREAMING) => FlowType::Streaming,
|
||||
None => FlowType::Batching,
|
||||
Some(flow_type) => {
|
||||
return InternalSnafu {
|
||||
reason: format!("Invalid flow type: {}", flow_type),
|
||||
if let Some(flow_type) = args.flow_options.get(FlowType::FLOW_TYPE_KEY) {
|
||||
match flow_type.as_str() {
|
||||
FlowType::BATCHING => {}
|
||||
FlowType::STREAMING => {
|
||||
return UnsupportedSnafu {
|
||||
reason: format!(
|
||||
"Flow {} was created with the legacy streaming flow type, which is no longer supported; drop and recreate the flow so it runs with the batching scheduler",
|
||||
args.flow_id
|
||||
),
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
other => {
|
||||
return UnsupportedSnafu {
|
||||
reason: format!(
|
||||
"Flow {} has unknown flow type `{other}`; only batching flows are supported, drop and recreate the flow",
|
||||
args.flow_id
|
||||
),
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
let flow_id = args.flow_id;
|
||||
let src_table_ids = args.source_table_ids.clone();
|
||||
|
||||
let res = match flow_type {
|
||||
FlowType::Batching => self.batching_engine.create_flow(args).await,
|
||||
FlowType::Streaming => self.streaming_engine.create_flow(args).await,
|
||||
}?;
|
||||
|
||||
self.src_table2flow
|
||||
.write()
|
||||
.await
|
||||
.add_flow(flow_id, flow_type, src_table_ids);
|
||||
|
||||
Ok(res)
|
||||
self.batching_engine.create_flow(args).await
|
||||
}
|
||||
|
||||
async fn remove_flow(&self, flow_id: FlowId) -> Result<(), Error> {
|
||||
let flow_type = self.src_table2flow.read().await.get_flow_type(flow_id);
|
||||
let flow_type = match flow_type {
|
||||
Some(flow_type) => Some(flow_type),
|
||||
None if self.streaming_engine.flow_exist(flow_id).await? => Some(FlowType::Streaming),
|
||||
None => None,
|
||||
};
|
||||
if !self.batching_engine.flow_exist(flow_id).await? {
|
||||
// this can happen if flownode just restart, and is stilling creating the flow
|
||||
// since now that this flow should dropped, we need to trigger the consistent check and allow drop
|
||||
// this rely on drop flow ddl delete metadata first, see src/common/meta/src/ddl/drop_flow.rs
|
||||
warn!(
|
||||
"Flow {} is not exist in the underlying engine, but exist in metadata",
|
||||
flow_id
|
||||
);
|
||||
self.try_sync_with_check_task(flow_id, true).await?;
|
||||
|
||||
match flow_type {
|
||||
Some(FlowType::Batching) => self.batching_engine.remove_flow(flow_id).await,
|
||||
Some(FlowType::Streaming) => self.streaming_engine.remove_flow(flow_id).await,
|
||||
None => {
|
||||
// this can happen if flownode just restart, and is stilling creating the flow
|
||||
// since now that this flow should dropped, we need to trigger the consistent check and allow drop
|
||||
// this rely on drop flow ddl delete metadata first, see src/common/meta/src/ddl/drop_flow.rs
|
||||
warn!(
|
||||
"Flow {} is not exist in the underlying engine, but exist in metadata",
|
||||
flow_id
|
||||
);
|
||||
self.try_sync_with_check_task(flow_id, true).await?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}?;
|
||||
// remove mapping
|
||||
self.src_table2flow.write().await.remove_flow(flow_id);
|
||||
Ok(())
|
||||
self.batching_engine.remove_flow(flow_id).await
|
||||
}
|
||||
|
||||
async fn flush_flow(&self, flow_id: FlowId) -> Result<usize, Error> {
|
||||
// sync with check task
|
||||
self.try_sync_with_check_task(flow_id, false).await?;
|
||||
let flow_type = self.src_table2flow.read().await.get_flow_type(flow_id);
|
||||
match flow_type {
|
||||
Some(FlowType::Batching) => self.batching_engine.flush_flow(flow_id).await,
|
||||
Some(FlowType::Streaming) => self.streaming_engine.flush_flow(flow_id).await,
|
||||
None => {
|
||||
warn!(
|
||||
"Currently flow={flow_id} doesn't exist in flownode, ignore flush_flow request"
|
||||
);
|
||||
Ok(0)
|
||||
}
|
||||
if !self.batching_engine.flow_exist(flow_id).await? {
|
||||
warn!("Currently flow={flow_id} doesn't exist in flownode, ignore flush_flow request");
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
self.batching_engine.flush_flow(flow_id).await
|
||||
}
|
||||
|
||||
async fn flow_exist(&self, flow_id: FlowId) -> Result<bool, Error> {
|
||||
let flow_type = self.src_table2flow.read().await.get_flow_type(flow_id);
|
||||
// Check the underlying registry so stateless flows survive a missing
|
||||
// routing-map entry during recovery.
|
||||
match flow_type {
|
||||
Some(FlowType::Batching) => self.batching_engine.flow_exist(flow_id).await,
|
||||
Some(FlowType::Streaming) => self.streaming_engine.flow_exist(flow_id).await,
|
||||
None => self.streaming_engine.flow_exist(flow_id).await,
|
||||
}
|
||||
self.batching_engine.flow_exist(flow_id).await
|
||||
}
|
||||
|
||||
async fn list_flows(&self) -> Result<impl IntoIterator<Item = FlowId>, Error> {
|
||||
let stream_flows = self.streaming_engine.list_flows().await?;
|
||||
let batch_flows = self.batching_engine.list_flows().await?;
|
||||
|
||||
Ok(stream_flows.into_iter().chain(batch_flows))
|
||||
self.batching_engine.list_flows().await
|
||||
}
|
||||
|
||||
/// Handle mirrored inserts: the batching engine uses them to mark dirty windows, so this
|
||||
/// path must be kept even though there is no streaming executor anymore.
|
||||
async fn handle_flow_inserts(
|
||||
&self,
|
||||
request: api::v1::region::InsertRequests,
|
||||
) -> Result<(), Error> {
|
||||
self.wait_for_all_flow_recover(request.requests.len())
|
||||
.await?;
|
||||
// TODO(discord9): make as little clone as possible
|
||||
let mut to_stream_engine = Vec::with_capacity(request.requests.len());
|
||||
let mut to_batch_engine = request.requests;
|
||||
|
||||
let mut batching_row_cnt = 0;
|
||||
let mut streaming_row_cnt = 0;
|
||||
|
||||
{
|
||||
// not locking this, or recover flows will be starved when also handling flow inserts
|
||||
let src_table2flow = self.src_table2flow.read().await;
|
||||
to_batch_engine.retain(|req| {
|
||||
let region_id = RegionId::from(req.region_id);
|
||||
let table_id = region_id.table_id();
|
||||
let is_in_stream = src_table2flow.in_stream(table_id);
|
||||
let is_in_batch = src_table2flow.in_batch(table_id);
|
||||
if is_in_stream {
|
||||
streaming_row_cnt += req.rows.as_ref().map(|rs| rs.rows.len()).unwrap_or(0);
|
||||
to_stream_engine.push(req.clone());
|
||||
}
|
||||
if is_in_batch {
|
||||
batching_row_cnt += req.rows.as_ref().map(|rs| rs.rows.len()).unwrap_or(0);
|
||||
return true;
|
||||
}
|
||||
if !is_in_batch && !is_in_stream {
|
||||
// TODO(discord9): also put to centralized logging for flow once it implemented
|
||||
warn!("Table {} is not any flow's source table", table_id)
|
||||
}
|
||||
false
|
||||
});
|
||||
// drop(src_table2flow);
|
||||
// can't use drop due to https://github.com/rust-lang/rust/pull/128846
|
||||
}
|
||||
|
||||
METRIC_FLOW_ROWS
|
||||
.with_label_values(&["in-streaming"])
|
||||
.inc_by(streaming_row_cnt as u64);
|
||||
|
||||
let row_cnt = request
|
||||
.requests
|
||||
.iter()
|
||||
.map(|req| req.rows.as_ref().map(|rows| rows.rows.len()).unwrap_or(0))
|
||||
.sum::<usize>();
|
||||
METRIC_FLOW_ROWS
|
||||
.with_label_values(&["in-batching"])
|
||||
.inc_by(batching_row_cnt as u64);
|
||||
.inc_by(row_cnt as u64);
|
||||
|
||||
let streaming_engine = self.streaming_engine.clone();
|
||||
let stream_handler: JoinHandle<Result<(), Error>> =
|
||||
common_runtime::spawn_global(async move {
|
||||
streaming_engine
|
||||
.handle_flow_inserts(api::v1::region::InsertRequests {
|
||||
requests: to_stream_engine,
|
||||
})
|
||||
.await?;
|
||||
Ok(())
|
||||
});
|
||||
self.batching_engine
|
||||
.handle_flow_inserts(api::v1::region::InsertRequests {
|
||||
requests: to_batch_engine,
|
||||
})
|
||||
.await?;
|
||||
stream_handler.await.context(JoinTaskSnafu)??;
|
||||
|
||||
Ok(())
|
||||
self.batching_engine.handle_flow_inserts(request).await
|
||||
}
|
||||
|
||||
async fn handle_mark_window_dirty(
|
||||
@@ -821,7 +672,7 @@ impl FlowEngine for FlowDualEngine {
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl common_meta::node_manager::Flownode for FlowDualEngine {
|
||||
impl common_meta::node_manager::Flownode for FlownodeEngine {
|
||||
async fn handle(&self, request: FlowRequest) -> MetaResult<FlowResponse> {
|
||||
let query_ctx = request
|
||||
.header
|
||||
@@ -969,54 +820,102 @@ fn to_meta_err(
|
||||
}
|
||||
}
|
||||
|
||||
impl FlowEngine for StreamingEngine {
|
||||
async fn create_flow(&self, args: CreateFlowArgs) -> Result<Option<FlowId>, Error> {
|
||||
self.create_flow_inner(args).await
|
||||
}
|
||||
|
||||
async fn remove_flow(&self, flow_id: FlowId) -> Result<(), Error> {
|
||||
self.remove_flow_inner(flow_id).await
|
||||
}
|
||||
|
||||
async fn flush_flow(&self, flow_id: FlowId) -> Result<usize, Error> {
|
||||
self.flush_flow_inner(flow_id).await
|
||||
}
|
||||
|
||||
async fn flow_exist(&self, flow_id: FlowId) -> Result<bool, Error> {
|
||||
self.flow_exist_inner(flow_id).await
|
||||
}
|
||||
|
||||
async fn list_flows(&self) -> Result<impl IntoIterator<Item = FlowId>, Error> {
|
||||
Ok(self.stateless_flow_ids().await)
|
||||
}
|
||||
|
||||
async fn handle_flow_inserts(
|
||||
&self,
|
||||
request: api::v1::region::InsertRequests,
|
||||
) -> Result<(), Error> {
|
||||
self.handle_inserts_inner(request).await
|
||||
}
|
||||
|
||||
async fn handle_mark_window_dirty(
|
||||
&self,
|
||||
_req: api::v1::flow::DirtyWindowRequests,
|
||||
) -> Result<(), Error> {
|
||||
UnsupportedSnafu {
|
||||
reason: "handle_mark_window_dirty in streaming engine",
|
||||
}
|
||||
.fail()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use catalog::memory::new_memory_catalog_manager;
|
||||
use common_base::Plugins;
|
||||
use common_meta::ddl::create_flow::INTERNAL_EVAL_SCHEDULE_KEY;
|
||||
use common_meta::key::TableMetadataManager;
|
||||
use common_meta::key::flow::FlowMetadataManager;
|
||||
use common_meta::kv_backend::memory::MemoryKvBackend;
|
||||
use query::options::QueryOptions;
|
||||
|
||||
use super::decode_internal_eval_schedule;
|
||||
use super::{FlownodeEngine, decode_internal_eval_schedule};
|
||||
use crate::CreateFlowArgs;
|
||||
use crate::batching_mode::BatchingModeOptions;
|
||||
use crate::batching_mode::engine::BatchingEngine;
|
||||
use crate::batching_mode::frontend_client::FrontendClient;
|
||||
use crate::engine::FlowEngine;
|
||||
use crate::error::Error;
|
||||
|
||||
async fn new_test_engine() -> FlownodeEngine {
|
||||
let kv_backend = Arc::new(MemoryKvBackend::new());
|
||||
let table_meta = Arc::new(TableMetadataManager::new(kv_backend.clone()));
|
||||
table_meta.init().await.unwrap();
|
||||
let flow_meta = Arc::new(FlowMetadataManager::new(kv_backend));
|
||||
let catalog_manager = new_memory_catalog_manager().unwrap();
|
||||
let query_engine = crate::test_utils::create_test_query_engine();
|
||||
let (frontend_client, _handler) =
|
||||
FrontendClient::from_empty_grpc_handler(QueryOptions::default());
|
||||
let batching = Arc::new(BatchingEngine::new(
|
||||
Arc::new(frontend_client),
|
||||
query_engine,
|
||||
flow_meta.clone(),
|
||||
table_meta,
|
||||
catalog_manager.clone(),
|
||||
BatchingModeOptions::default(),
|
||||
));
|
||||
|
||||
FlownodeEngine::new(None, batching, flow_meta, catalog_manager, Plugins::new())
|
||||
}
|
||||
|
||||
fn create_flow_args(flow_type: Option<&str>) -> CreateFlowArgs {
|
||||
let mut flow_options = HashMap::new();
|
||||
if let Some(flow_type) = flow_type {
|
||||
flow_options.insert("flow_type".to_string(), flow_type.to_string());
|
||||
}
|
||||
|
||||
CreateFlowArgs {
|
||||
flow_id: 1024,
|
||||
sink_table_name: [
|
||||
"greptime_public".to_string(),
|
||||
"public".to_string(),
|
||||
"old_sink".to_string(),
|
||||
],
|
||||
source_table_ids: vec![],
|
||||
create_if_not_exists: false,
|
||||
or_replace: false,
|
||||
expire_after: None,
|
||||
eval_interval: Some(60),
|
||||
comment: None,
|
||||
sql: "SELECT 1".to_string(),
|
||||
flow_options,
|
||||
query_ctx: None,
|
||||
eval_schedule: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_old_streaming_metadata_asks_for_recreation() {
|
||||
let engine = new_test_engine().await;
|
||||
|
||||
// A flow persisted by the removed streaming executor must not run as batching: the
|
||||
// recovery path goes through `create_flow`, so it reports that the flow needs recreation
|
||||
// instead of silently executing different SQL semantics.
|
||||
let err = engine
|
||||
.create_flow(create_flow_args(Some("streaming")))
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(err, Error::Unsupported { .. }),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
let msg = err.to_string();
|
||||
assert!(msg.contains("no longer supported"), "unexpected: {msg}");
|
||||
assert!(msg.contains("recreate"), "unexpected: {msg}");
|
||||
assert!(!engine.flow_exist(1024).await.unwrap());
|
||||
|
||||
// `batching` and absent `flow_type` still reach the batching engine.
|
||||
for flow_type in [Some("batching"), None] {
|
||||
let err = engine.create_flow(create_flow_args(flow_type)).await;
|
||||
let msg = err.err().map(|err| err.to_string()).unwrap_or_default();
|
||||
assert!(!msg.contains("no longer supported"), "unexpected: {msg}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_malformed_internal_eval_schedule_json_is_error() {
|
||||
let mut flow_options = HashMap::new();
|
||||
|
||||
@@ -1,730 +0,0 @@
|
||||
// Copyright 2023 Greptime Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Stateless DataFusion execution for streaming flows.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use api::helper::{to_grpc_value, vectors_to_rows};
|
||||
use api::v1::greptime_request::Request;
|
||||
use api::v1::{RowInsertRequest, RowInsertRequests, Rows};
|
||||
use common_error::ext::BoxedError;
|
||||
use common_query::OutputData;
|
||||
use common_recordbatch::{RecordBatch, RecordBatches, map_dictionary_to_values_data_type};
|
||||
use common_time::Timestamp;
|
||||
use datafusion::catalog::MemTable;
|
||||
use datafusion::datasource::{TableProvider, provider_as_source, source_as_provider};
|
||||
use datafusion_common::tree_node::{Transformed, TreeNode};
|
||||
use datafusion_common::{Column, DFSchema, TableReference};
|
||||
use datafusion_expr::logical_plan::{Distinct, Projection};
|
||||
use datafusion_expr::{Expr, LogicalPlan};
|
||||
use datatypes::schema::{ColumnSchema, SchemaRef};
|
||||
use datatypes::value::Value;
|
||||
use query::QueryEngine;
|
||||
use session::context::QueryContextRef;
|
||||
use snafu::{OptionExt, ResultExt, ensure};
|
||||
use table::metadata::TableId;
|
||||
use table::table::adapter::DfTableProviderAdapter;
|
||||
|
||||
use crate::TableName;
|
||||
use crate::adapter::util::column_schemas_to_proto;
|
||||
use crate::batching_mode::frontend_client::FrontendClient;
|
||||
use crate::error::{DatafusionSnafu, Error, ExternalSnafu, InvalidQuerySnafu, UnexpectedSnafu};
|
||||
use crate::repr::DiffRow;
|
||||
|
||||
/// The validated, immutable part of one streaming flow.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct StatelessFlow {
|
||||
pub(crate) source_table_id: TableId,
|
||||
pub(crate) source_table_name: TableName,
|
||||
pub(crate) source_schema: SchemaRef,
|
||||
pub(crate) source_schema_version: u32,
|
||||
pub(crate) sink_table_name: TableName,
|
||||
pub(crate) sink_schema: Vec<ColumnSchema>,
|
||||
pub(crate) sink_primary_keys: Vec<String>,
|
||||
/// The exact trailing columns resolved when the flow was created.
|
||||
pub(crate) auto_columns: Vec<ColumnSchema>,
|
||||
pub(crate) plan: LogicalPlan,
|
||||
pub(crate) query_ctx: QueryContextRef,
|
||||
pub(crate) create_args: crate::CreateFlowArgs,
|
||||
}
|
||||
|
||||
/// Per-request input provider. It owns no catalog or storage state.
|
||||
#[cfg(test)]
|
||||
fn test_source_plan(table_name: TableReference, provider: Arc<dyn TableProvider>) -> LogicalPlan {
|
||||
datafusion_expr::LogicalPlanBuilder::scan(table_name, provider_as_source(provider), None)
|
||||
.unwrap()
|
||||
.filter(datafusion_expr::col("number").gt(datafusion_expr::lit(1)))
|
||||
.unwrap()
|
||||
.project(vec![datafusion_expr::col("number")])
|
||||
.unwrap()
|
||||
.build()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn input_provider(batch: &RecordBatch) -> Result<Arc<dyn TableProvider>, Error> {
|
||||
let arrow_batch = batch.df_record_batch().clone();
|
||||
let provider = MemTable::try_new(arrow_batch.schema(), vec![vec![arrow_batch]]).context(
|
||||
DatafusionSnafu {
|
||||
context: "Failed to create transient flow input provider",
|
||||
},
|
||||
)?;
|
||||
Ok(Arc::new(provider))
|
||||
}
|
||||
|
||||
/// Adds the source timestamp to every supported plan node that has to carry it through a
|
||||
/// filter or projection. The expression is appended only after the visible expressions, so the
|
||||
/// sink contract remains positional.
|
||||
pub(crate) fn rewrite_source_timestamp(
|
||||
plan: LogicalPlan,
|
||||
source_name: &TableReference,
|
||||
source_timestamp_name: &str,
|
||||
) -> Result<LogicalPlan, Error> {
|
||||
let mut names = HashSet::new();
|
||||
plan.apply(|node| {
|
||||
names.extend(
|
||||
node.schema()
|
||||
.fields()
|
||||
.iter()
|
||||
.map(|field| field.name().clone()),
|
||||
);
|
||||
Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue)
|
||||
})
|
||||
.context(DatafusionSnafu {
|
||||
context: "Failed to inspect streaming flow plan schema",
|
||||
})?;
|
||||
let mut hidden_name = "__flow_source_timestamp".to_string();
|
||||
let mut suffix = 0;
|
||||
while !names.insert(hidden_name.clone()) {
|
||||
suffix += 1;
|
||||
hidden_name = format!("__flow_source_timestamp_{suffix}");
|
||||
}
|
||||
let visible_count = plan.schema().fields().len();
|
||||
let source_timestamp = Column::from_name(source_timestamp_name);
|
||||
let mut plan = plan
|
||||
.transform_up_with_subqueries(|node| match node {
|
||||
LogicalPlan::TableScan(mut scan) => {
|
||||
if scan.table_name.resolved_eq(source_name)
|
||||
&& let Some(projection) = &mut scan.projection
|
||||
{
|
||||
let timestamp_index = scan
|
||||
.source
|
||||
.schema()
|
||||
.index_of(source_timestamp_name)
|
||||
.map_err(|_| {
|
||||
datafusion::error::DataFusionError::Plan(
|
||||
"Source timestamp is absent from source scan".into(),
|
||||
)
|
||||
})?;
|
||||
if !projection.contains(×tamp_index) {
|
||||
projection.push(timestamp_index);
|
||||
let schema = scan.source.schema();
|
||||
scan.projected_schema = Arc::new(DFSchema::new_with_metadata(
|
||||
projection
|
||||
.iter()
|
||||
.map(|index| {
|
||||
(
|
||||
Some(scan.table_name.clone()),
|
||||
Arc::new(schema.field(*index).clone()),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
schema.metadata().clone(),
|
||||
)?);
|
||||
}
|
||||
}
|
||||
Ok(Transformed::yes(LogicalPlan::TableScan(scan)))
|
||||
}
|
||||
LogicalPlan::Projection(mut projection) => {
|
||||
let hidden_expr = if projection
|
||||
.input
|
||||
.schema()
|
||||
.fields()
|
||||
.iter()
|
||||
.any(|field| field.name() == &hidden_name)
|
||||
{
|
||||
Expr::Column(Column::from_name(hidden_name.clone()))
|
||||
} else {
|
||||
Expr::Column(source_timestamp.clone())
|
||||
};
|
||||
projection.expr.push(hidden_expr.alias(hidden_name.clone()));
|
||||
let projection = Projection::try_new(projection.expr, projection.input)?;
|
||||
Ok(Transformed::yes(LogicalPlan::Projection(projection)))
|
||||
}
|
||||
_ => Ok(Transformed::no(node)),
|
||||
})
|
||||
.context(DatafusionSnafu {
|
||||
context: "Failed to add source timestamp to streaming flow plan",
|
||||
})?
|
||||
.data;
|
||||
|
||||
// A plan ending at a scan or filter has no projection at which to give the carried value its
|
||||
// hidden name. Add one only in that case; a projection below a filter already carries it.
|
||||
if !plan
|
||||
.schema()
|
||||
.fields()
|
||||
.iter()
|
||||
.any(|field| field.name() == &hidden_name)
|
||||
{
|
||||
let expressions = plan
|
||||
.schema()
|
||||
.fields()
|
||||
.iter()
|
||||
.take(visible_count)
|
||||
.map(|field| Expr::Column(Column::from_name(field.name())))
|
||||
.chain(std::iter::once(
|
||||
Expr::Column(source_timestamp).alias(hidden_name),
|
||||
))
|
||||
.collect::<Vec<_>>();
|
||||
plan = Projection::try_new(expressions, Arc::new(plan))
|
||||
.map(LogicalPlan::Projection)
|
||||
.context(DatafusionSnafu {
|
||||
context: "Failed to finalize source timestamp in streaming flow plan",
|
||||
})?;
|
||||
}
|
||||
Ok(plan)
|
||||
}
|
||||
|
||||
fn replace_source(
|
||||
plan: LogicalPlan,
|
||||
source_name: &TableReference,
|
||||
provider: Arc<dyn TableProvider>,
|
||||
) -> Result<LogicalPlan, Error> {
|
||||
let mut scan_count = 0;
|
||||
let mut replaced_scan_count = 0;
|
||||
let plan = plan
|
||||
.transform_up_with_subqueries(|node| match node {
|
||||
LogicalPlan::TableScan(mut scan) => {
|
||||
scan_count += 1;
|
||||
if scan.table_name.resolved_eq(source_name) {
|
||||
replaced_scan_count += 1;
|
||||
scan.source = provider_as_source(provider.clone());
|
||||
let schema = scan.source.schema();
|
||||
scan.projected_schema = if let Some(projection) = &scan.projection {
|
||||
Arc::new(DFSchema::new_with_metadata(
|
||||
projection
|
||||
.iter()
|
||||
.map(|index| {
|
||||
(
|
||||
Some(scan.table_name.clone()),
|
||||
Arc::new(schema.field(*index).clone()),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
schema.metadata().clone(),
|
||||
)?)
|
||||
} else {
|
||||
Arc::new(DFSchema::try_from_qualified_schema(
|
||||
scan.table_name.clone(),
|
||||
&schema,
|
||||
)?)
|
||||
};
|
||||
Ok(Transformed::yes(LogicalPlan::TableScan(scan)))
|
||||
} else {
|
||||
Ok(Transformed::no(LogicalPlan::TableScan(scan)))
|
||||
}
|
||||
}
|
||||
LogicalPlan::Join(_) | LogicalPlan::Aggregate(_) => {
|
||||
Err(datafusion::error::DataFusionError::Plan(
|
||||
"Streaming flow supports only a single projection/filter source".into(),
|
||||
))
|
||||
}
|
||||
_ => Ok(Transformed::no(node)),
|
||||
})
|
||||
.context(DatafusionSnafu {
|
||||
context: "Failed to substitute transient flow input provider",
|
||||
})?
|
||||
.data;
|
||||
ensure!(
|
||||
scan_count == 1 && replaced_scan_count == 1,
|
||||
InvalidQuerySnafu {
|
||||
reason: format!(
|
||||
"Expected one source scan matching {:?}, found {scan_count} scans and {replaced_scan_count} matches",
|
||||
source_name
|
||||
)
|
||||
}
|
||||
);
|
||||
Ok(plan)
|
||||
}
|
||||
|
||||
/// Validates the deliberately small stateless streaming SQL subset.
|
||||
pub(crate) fn validate_plan(plan: &LogicalPlan) -> Result<(), Error> {
|
||||
let mut scans = 0;
|
||||
plan.apply(|node| {
|
||||
match node {
|
||||
LogicalPlan::TableScan(_) => scans += 1,
|
||||
LogicalPlan::Projection(_) | LogicalPlan::Filter(_) => {}
|
||||
LogicalPlan::Aggregate(_) => {
|
||||
return Err(datafusion::error::DataFusionError::Plan(
|
||||
"Aggregation is unsupported in streaming flows. Recreate the flow to select batching mode. A source table with TTL=instant must use persisted retention first. Aggregation SQL without a time window requires EVAL INTERVAL.".into(),
|
||||
));
|
||||
}
|
||||
// DISTINCT is evaluated against this request's transient input only. DISTINCT ON
|
||||
// has ordering/selection semantics beyond the supported stateless subset.
|
||||
LogicalPlan::Distinct(Distinct::All(_)) => {}
|
||||
_ => {
|
||||
return Err(datafusion::error::DataFusionError::Plan(
|
||||
"Streaming flow supports only projection and filter over one source scan"
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue)
|
||||
})
|
||||
.context(DatafusionSnafu {
|
||||
context: "Failed to validate streaming flow plan",
|
||||
})?;
|
||||
ensure!(
|
||||
scans == 1,
|
||||
InvalidQuerySnafu {
|
||||
reason: format!("Expected one source scan, found {scans}")
|
||||
}
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Ensures the retained scan was planned against the source metadata captured for this flow.
|
||||
pub(crate) fn validate_source_scan(
|
||||
plan: &LogicalPlan,
|
||||
source_table_id: TableId,
|
||||
source_schema: &SchemaRef,
|
||||
) -> Result<(), Error> {
|
||||
plan.apply(|node| {
|
||||
if let LogicalPlan::TableScan(scan) = node {
|
||||
let provider = source_as_provider(&scan.source)?;
|
||||
let provider = provider
|
||||
.downcast_ref::<DfTableProviderAdapter>()
|
||||
.ok_or_else(|| {
|
||||
datafusion::error::DataFusionError::Plan(
|
||||
"Streaming flow source scan does not use a table provider".into(),
|
||||
)
|
||||
})?;
|
||||
let table_info = provider.table().table_info();
|
||||
if table_info.ident.table_id != source_table_id
|
||||
|| table_info.meta.schema.as_ref() != source_schema.as_ref()
|
||||
{
|
||||
return Err(datafusion::error::DataFusionError::Plan(format!(
|
||||
"Streaming flow source scan does not match source table {source_table_id} schema version {}",
|
||||
source_schema.version()
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue)
|
||||
})
|
||||
.context(DatafusionSnafu {
|
||||
context: "Failed to validate streaming flow source scan",
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Rejects execution when the source metadata changed after the flow plan was retained.
|
||||
/// The outer adapter replans a flow when it observes a new source schema version; this guard
|
||||
/// rejects a request if the version changes again before execution.
|
||||
fn validate_source_schema_version(
|
||||
retained_version: u32,
|
||||
current_version: u32,
|
||||
) -> Result<(), Error> {
|
||||
ensure!(
|
||||
retained_version == current_version,
|
||||
InvalidQuerySnafu {
|
||||
reason: format!(
|
||||
"Source schema version changed from {retained_version} to {current_version}; recreate or recover the flow before writing"
|
||||
)
|
||||
}
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn synthesize_auto_values(columns: &[ColumnSchema], now: Timestamp) -> Result<Vec<Value>, Error> {
|
||||
columns
|
||||
.iter()
|
||||
.map(|column| {
|
||||
let timestamp_type = column.data_type.as_timestamp().context(InvalidQuerySnafu {
|
||||
reason: format!("Auto sink column {} is not a timestamp", column.name),
|
||||
})?;
|
||||
let value = if column.name == crate::adapter::AUTO_CREATED_UPDATE_AT_TS_COL {
|
||||
now.convert_to(timestamp_type.unit())
|
||||
.context(InvalidQuerySnafu {
|
||||
reason: "Current timestamp cannot be represented in sink timestamp unit",
|
||||
})?
|
||||
} else if column.name == crate::adapter::AUTO_CREATED_PLACEHOLDER_TS_COL {
|
||||
Timestamp::new(0, timestamp_type.unit())
|
||||
} else {
|
||||
return InvalidQuerySnafu {
|
||||
reason: format!("Unsupported auto sink column {}", column.name),
|
||||
}
|
||||
.fail();
|
||||
};
|
||||
Ok(Value::Timestamp(value))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Executes one mirror write using only the supplied batch and writes its output.
|
||||
pub(crate) async fn execute(
|
||||
flow: &StatelessFlow,
|
||||
rows: &[DiffRow],
|
||||
batch_datatypes: &[datatypes::data_type::ConcreteDataType],
|
||||
query_engine: &Arc<dyn QueryEngine>,
|
||||
frontend_client: &Arc<FrontendClient>,
|
||||
current_source_schema_version: u32,
|
||||
) -> Result<usize, Error> {
|
||||
validate_source_schema_version(flow.source_schema_version, current_source_schema_version)?;
|
||||
let values = rows.iter().map(|(row, _, _)| row.clone()).collect();
|
||||
let batch = crate::expr::Batch::try_from_rows_with_types(values, batch_datatypes)
|
||||
.map_err(BoxedError::new)
|
||||
.context(ExternalSnafu)?;
|
||||
let batch = RecordBatch::new(flow.source_schema.clone(), batch.batch().to_vec())
|
||||
.map_err(BoxedError::new)
|
||||
.context(ExternalSnafu)?;
|
||||
let provider = input_provider(&batch)?;
|
||||
let source_ref = TableReference::full(
|
||||
flow.source_table_name[0].clone(),
|
||||
flow.source_table_name[1].clone(),
|
||||
flow.source_table_name[2].clone(),
|
||||
);
|
||||
let plan = replace_source(flow.plan.clone(), &source_ref, provider)?;
|
||||
let output = query_engine
|
||||
.execute(plan, flow.query_ctx.clone())
|
||||
.await
|
||||
.map_err(BoxedError::new)
|
||||
.context(ExternalSnafu)?;
|
||||
let batches = match output.data {
|
||||
OutputData::RecordBatches(batches) => batches,
|
||||
OutputData::Stream(stream) => RecordBatches::try_collect(stream)
|
||||
.await
|
||||
.map_err(BoxedError::new)
|
||||
.context(ExternalSnafu)?,
|
||||
OutputData::AffectedRows(_) => {
|
||||
return UnexpectedSnafu {
|
||||
reason: "Streaming flow query returned affected rows",
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
};
|
||||
|
||||
let output_schema = batches
|
||||
.schema()
|
||||
.column_schemas()
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(|mut column| {
|
||||
column.data_type = map_dictionary_to_values_data_type(&column.data_type);
|
||||
column
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
crate::adapter::validate_sink_layout_with_suffix(
|
||||
&output_schema,
|
||||
&flow.sink_schema,
|
||||
&flow.auto_columns,
|
||||
)?;
|
||||
let mut output_rows = Vec::new();
|
||||
for batch in batches {
|
||||
let vectors = datatypes::vectors::Helper::try_into_vectors(batch.columns())
|
||||
.map_err(BoxedError::new)
|
||||
.context(ExternalSnafu)?;
|
||||
output_rows.extend(vectors_to_rows(vectors.iter(), batch.num_rows()));
|
||||
}
|
||||
if output_rows.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
// Auto columns are deliberately synthesized here rather than in the query plan. This keeps
|
||||
// one current timestamp for the whole request and preserves the sink's timestamp precision.
|
||||
let auto_values = synthesize_auto_values(&flow.auto_columns, Timestamp::current_millis())?
|
||||
.into_iter()
|
||||
.map(to_grpc_value)
|
||||
.collect::<Vec<_>>();
|
||||
for row in &mut output_rows {
|
||||
row.values.extend(auto_values.iter().cloned());
|
||||
}
|
||||
|
||||
let output_row_count = output_rows.len();
|
||||
let proto_schema = column_schemas_to_proto(flow.sink_schema.clone(), &flow.sink_primary_keys)?;
|
||||
let request = Request::RowInserts(RowInsertRequests {
|
||||
inserts: vec![RowInsertRequest {
|
||||
table_name: flow.sink_table_name[2].clone(),
|
||||
rows: Some(Rows {
|
||||
schema: proto_schema,
|
||||
rows: output_rows,
|
||||
}),
|
||||
}],
|
||||
});
|
||||
let mut peer = None;
|
||||
frontend_client
|
||||
.handle_insert_once(
|
||||
request,
|
||||
&flow.sink_table_name[0],
|
||||
&flow.sink_table_name[1],
|
||||
&mut peer,
|
||||
)
|
||||
.await
|
||||
.map_err(BoxedError::new)
|
||||
.context(ExternalSnafu)?;
|
||||
Ok(output_row_count)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use datafusion::catalog::MemTable;
|
||||
use datafusion::logical_expr::LogicalPlanBuilder;
|
||||
use datatypes::data_type::ConcreteDataType;
|
||||
use datatypes::schema::{ColumnSchema, Schema};
|
||||
use datatypes::vectors::{Int32Vector, TimestampMillisecondVector};
|
||||
use session::context::QueryContext;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn validation_accepts_distinct_over_one_source() {
|
||||
let schema = Arc::new(Schema::new(vec![ColumnSchema::new(
|
||||
"number",
|
||||
ConcreteDataType::int32_datatype(),
|
||||
false,
|
||||
)]));
|
||||
let plan = LogicalPlanBuilder::scan(
|
||||
TableReference::bare("source"),
|
||||
provider_as_source(provider(&schema, 1)),
|
||||
None,
|
||||
)
|
||||
.unwrap()
|
||||
.project(vec![datafusion_expr::col("number")])
|
||||
.unwrap()
|
||||
.distinct()
|
||||
.unwrap()
|
||||
.build()
|
||||
.unwrap();
|
||||
assert!(validate_plan(&plan).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validation_rejects_plan_without_source_scan() {
|
||||
let plan = LogicalPlan::EmptyRelation(datafusion_expr::logical_plan::EmptyRelation {
|
||||
produce_one_row: false,
|
||||
schema: Arc::new(DFSchema::empty()),
|
||||
});
|
||||
assert!(validate_plan(&plan).is_err());
|
||||
}
|
||||
|
||||
fn provider(schema: &SchemaRef, value: i32) -> Arc<dyn TableProvider> {
|
||||
let batch = RecordBatch::new(
|
||||
schema.clone(),
|
||||
vec![Arc::new(Int32Vector::from_slice([value])) as datatypes::prelude::VectorRef],
|
||||
)
|
||||
.unwrap();
|
||||
let arrow = batch.df_record_batch().clone();
|
||||
Arc::new(MemTable::try_new(arrow.schema(), vec![vec![arrow]]).unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_schema_version_must_match_retained_plan() {
|
||||
assert!(validate_source_schema_version(7, 7).is_ok());
|
||||
|
||||
let error = validate_source_schema_version(7, 8).unwrap_err();
|
||||
assert!(matches!(error, Error::InvalidQuery { reason, .. } if
|
||||
reason.contains("Source schema version changed from 7 to 8")
|
||||
&& reason.contains("recreate or recover")
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_values_use_the_sink_timestamp_units() {
|
||||
let update_at = ColumnSchema::new(
|
||||
crate::adapter::AUTO_CREATED_UPDATE_AT_TS_COL,
|
||||
datatypes::data_type::ConcreteDataType::timestamp_second_datatype(),
|
||||
true,
|
||||
);
|
||||
let placeholder = ColumnSchema::new(
|
||||
crate::adapter::AUTO_CREATED_PLACEHOLDER_TS_COL,
|
||||
datatypes::data_type::ConcreteDataType::timestamp_nanosecond_datatype(),
|
||||
true,
|
||||
);
|
||||
let values = synthesize_auto_values(
|
||||
&[update_at],
|
||||
Timestamp::new(1_234, common_time::timestamp::TimeUnit::Millisecond),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(values.len(), 1);
|
||||
assert_eq!(
|
||||
values[0].as_timestamp().unwrap().unit(),
|
||||
common_time::timestamp::TimeUnit::Second
|
||||
);
|
||||
assert!(values[0].as_timestamp().unwrap().value() > 0);
|
||||
|
||||
let values = synthesize_auto_values(
|
||||
&[
|
||||
ColumnSchema::new(
|
||||
crate::adapter::AUTO_CREATED_UPDATE_AT_TS_COL,
|
||||
datatypes::data_type::ConcreteDataType::timestamp_microsecond_datatype(),
|
||||
true,
|
||||
),
|
||||
placeholder,
|
||||
],
|
||||
Timestamp::new(1_234, common_time::timestamp::TimeUnit::Millisecond),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(values[1].as_timestamp().unwrap().value(), 0);
|
||||
assert_eq!(
|
||||
values[1].as_timestamp().unwrap().unit(),
|
||||
common_time::timestamp::TimeUnit::Nanosecond
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_values_reject_arbitrary_columns() {
|
||||
let column = ColumnSchema::new(
|
||||
"other",
|
||||
datatypes::data_type::ConcreteDataType::timestamp_millisecond_datatype(),
|
||||
true,
|
||||
);
|
||||
assert!(synthesize_auto_values(&[column], Timestamp::current_millis()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrite_source_timestamp_appends_collision_free_hidden_output() {
|
||||
let schema = Arc::new(Schema::new(vec![
|
||||
ColumnSchema::new("number", ConcreteDataType::int32_datatype(), false),
|
||||
ColumnSchema::new(
|
||||
"ts",
|
||||
ConcreteDataType::timestamp_millisecond_datatype(),
|
||||
false,
|
||||
)
|
||||
.with_time_index(true),
|
||||
ColumnSchema::new(
|
||||
"__flow_source_timestamp",
|
||||
ConcreteDataType::int32_datatype(),
|
||||
false,
|
||||
),
|
||||
]));
|
||||
let batch = RecordBatch::new(
|
||||
schema.clone(),
|
||||
vec![
|
||||
Arc::new(Int32Vector::from_slice([2])) as datatypes::prelude::VectorRef,
|
||||
Arc::new(TimestampMillisecondVector::from_slice([42]))
|
||||
as datatypes::prelude::VectorRef,
|
||||
Arc::new(Int32Vector::from_slice([7])) as datatypes::prelude::VectorRef,
|
||||
],
|
||||
)
|
||||
.unwrap();
|
||||
let plan = datafusion_expr::LogicalPlanBuilder::scan(
|
||||
TableReference::bare("source"),
|
||||
provider_as_source(input_provider(&batch).unwrap()),
|
||||
None,
|
||||
)
|
||||
.unwrap()
|
||||
.filter(datafusion_expr::col("number").gt(datafusion_expr::lit(1)))
|
||||
.unwrap()
|
||||
.project(vec![datafusion_expr::col("number")])
|
||||
.unwrap()
|
||||
.build()
|
||||
.unwrap();
|
||||
let rewritten =
|
||||
rewrite_source_timestamp(plan, &TableReference::bare("source"), "ts").unwrap();
|
||||
assert_eq!(rewritten.schema().fields().len(), 2);
|
||||
assert!(
|
||||
rewritten
|
||||
.schema()
|
||||
.field(1)
|
||||
.name()
|
||||
.starts_with("__flow_source_timestamp")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn finite_projection_filter_does_not_retain_previous_batch() {
|
||||
let schema = Arc::new(Schema::new(vec![ColumnSchema::new(
|
||||
"number",
|
||||
ConcreteDataType::int32_datatype(),
|
||||
false,
|
||||
)]));
|
||||
let initial_provider = provider(&schema, 0);
|
||||
let plan = test_source_plan(TableReference::bare("source"), initial_provider);
|
||||
assert!(validate_plan(&plan).is_ok());
|
||||
|
||||
let engine = crate::test_utils::create_test_query_engine();
|
||||
let run = |input: Arc<dyn TableProvider>| {
|
||||
let engine = engine.clone();
|
||||
let plan = plan.clone();
|
||||
async move {
|
||||
let plan = replace_source(plan, &TableReference::bare("source"), input).unwrap();
|
||||
let output = engine.execute(plan, QueryContext::arc()).await.unwrap();
|
||||
match output.data {
|
||||
OutputData::Stream(stream) => RecordBatches::try_collect(stream)
|
||||
.await
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|batch| batch.num_rows())
|
||||
.sum(),
|
||||
OutputData::RecordBatches(batches) => {
|
||||
batches.iter().map(|batch| batch.num_rows()).sum()
|
||||
}
|
||||
OutputData::AffectedRows(_) => 0,
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
assert_eq!(run(provider(&schema, 1)).await, 0);
|
||||
assert_eq!(run(provider(&schema, 2)).await, 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn finite_distinct_collapses_duplicates_per_request() {
|
||||
let schema = Arc::new(Schema::new(vec![ColumnSchema::new(
|
||||
"number",
|
||||
ConcreteDataType::int32_datatype(),
|
||||
false,
|
||||
)]));
|
||||
let input = |values: &[i32]| {
|
||||
let batch = RecordBatch::new(
|
||||
schema.clone(),
|
||||
vec![Arc::new(Int32Vector::from_slice(values)) as datatypes::prelude::VectorRef],
|
||||
)
|
||||
.unwrap();
|
||||
input_provider(&batch).unwrap()
|
||||
};
|
||||
let plan = LogicalPlanBuilder::scan(
|
||||
TableReference::bare("source"),
|
||||
provider_as_source(input(&[1])),
|
||||
None,
|
||||
)
|
||||
.unwrap()
|
||||
.project(vec![datafusion_expr::col("number")])
|
||||
.unwrap()
|
||||
.distinct()
|
||||
.unwrap()
|
||||
.build()
|
||||
.unwrap();
|
||||
assert!(validate_plan(&plan).is_ok());
|
||||
|
||||
let engine = crate::test_utils::create_test_query_engine();
|
||||
let run = |provider: Arc<dyn TableProvider>| {
|
||||
let engine = engine.clone();
|
||||
let plan = plan.clone();
|
||||
async move {
|
||||
let plan = replace_source(plan, &TableReference::bare("source"), provider).unwrap();
|
||||
let output = engine.execute(plan, QueryContext::arc()).await.unwrap();
|
||||
let batches = match output.data {
|
||||
OutputData::Stream(stream) => RecordBatches::try_collect(stream).await.unwrap(),
|
||||
OutputData::RecordBatches(batches) => batches,
|
||||
OutputData::AffectedRows(_) => panic!("unexpected affected rows"),
|
||||
};
|
||||
batches.iter().map(|batch| batch.num_rows()).sum::<usize>()
|
||||
}
|
||||
};
|
||||
|
||||
assert_eq!(run(input(&[1, 1, 2])).await, 2);
|
||||
assert_eq!(run(input(&[1, 1])).await, 1);
|
||||
}
|
||||
}
|
||||
@@ -1,350 +0,0 @@
|
||||
// Copyright 2023 Greptime Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! How to query table information from database
|
||||
|
||||
use common_error::ext::BoxedError;
|
||||
use common_meta::key::table_info::{TableInfoManager, TableInfoValue};
|
||||
use common_meta::key::table_name::{TableNameKey, TableNameManager};
|
||||
use datatypes::schema::ColumnDefaultConstraint;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use snafu::{OptionExt, ResultExt};
|
||||
use table::metadata::TableId;
|
||||
|
||||
use crate::adapter::TableName;
|
||||
use crate::adapter::util::table_info_value_to_relation_desc;
|
||||
use crate::error::{
|
||||
Error, ExternalSnafu, TableNotFoundMetaSnafu, TableNotFoundSnafu, UnexpectedSnafu,
|
||||
};
|
||||
use crate::repr::RelationDesc;
|
||||
|
||||
/// Table description, include relation desc and default values, which is the minimal information flow needed for table
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct TableDesc {
|
||||
pub relation_desc: RelationDesc,
|
||||
pub default_values: Vec<Option<ColumnDefaultConstraint>>,
|
||||
}
|
||||
|
||||
impl TableDesc {
|
||||
pub fn new(
|
||||
relation_desc: RelationDesc,
|
||||
default_values: Vec<Option<ColumnDefaultConstraint>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
relation_desc,
|
||||
default_values,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn new_no_default(relation_desc: RelationDesc) -> Self {
|
||||
Self {
|
||||
relation_desc,
|
||||
default_values: vec![],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Table source but for flow, provide table schema by table name/id
|
||||
#[async_trait::async_trait]
|
||||
pub trait FlowTableSource: Send + Sync + std::fmt::Debug {
|
||||
async fn table_name_from_id(&self, table_id: &TableId) -> Result<TableName, Error>;
|
||||
async fn table_id_from_name(&self, name: &TableName) -> Result<TableId, Error>;
|
||||
|
||||
/// Get the table schema by table name
|
||||
async fn table(&self, name: &TableName) -> Result<TableDesc, Error> {
|
||||
let id = self.table_id_from_name(name).await?;
|
||||
self.table_from_id(&id).await
|
||||
}
|
||||
async fn table_from_id(&self, table_id: &TableId) -> Result<TableDesc, Error>;
|
||||
}
|
||||
|
||||
/// managed table source information, query from table info manager and table name manager
|
||||
#[derive(Clone)]
|
||||
pub struct ManagedTableSource {
|
||||
/// for query `TableId -> TableName` mapping
|
||||
table_info_manager: TableInfoManager,
|
||||
table_name_manager: TableNameManager,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl FlowTableSource for ManagedTableSource {
|
||||
async fn table_from_id(&self, table_id: &TableId) -> Result<TableDesc, Error> {
|
||||
let table_info_value = self
|
||||
.get_table_info_value(table_id)
|
||||
.await?
|
||||
.with_context(|| TableNotFoundSnafu {
|
||||
name: format!("TableId = {:?}, Can't found table info", table_id),
|
||||
})?;
|
||||
let desc = table_info_value_to_relation_desc(table_info_value)?;
|
||||
|
||||
Ok(desc)
|
||||
}
|
||||
async fn table_name_from_id(&self, table_id: &TableId) -> Result<TableName, Error> {
|
||||
self.get_table_name(table_id).await
|
||||
}
|
||||
async fn table_id_from_name(&self, name: &TableName) -> Result<TableId, Error> {
|
||||
self.get_opt_table_id_from_name(name)
|
||||
.await?
|
||||
.with_context(|| TableNotFoundSnafu {
|
||||
name: name.join("."),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ManagedTableSource {
|
||||
pub fn new(table_info_manager: TableInfoManager, table_name_manager: TableNameManager) -> Self {
|
||||
ManagedTableSource {
|
||||
table_info_manager,
|
||||
table_name_manager,
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the time index column from table id
|
||||
pub async fn get_time_index_column_from_table_id(
|
||||
&self,
|
||||
table_id: TableId,
|
||||
) -> Result<(usize, datatypes::schema::ColumnSchema), Error> {
|
||||
let info = self
|
||||
.table_info_manager
|
||||
.get(table_id)
|
||||
.await
|
||||
.map_err(BoxedError::new)
|
||||
.context(ExternalSnafu)?
|
||||
.context(UnexpectedSnafu {
|
||||
reason: format!("Table id = {:?}, couldn't found table info", table_id),
|
||||
})?;
|
||||
let schema = &info.table_info.meta.schema;
|
||||
let Some(ts_index) = schema.timestamp_index() else {
|
||||
UnexpectedSnafu {
|
||||
reason: format!("Table id = {:?}, couldn't found timestamp index", table_id),
|
||||
}
|
||||
.fail()?
|
||||
};
|
||||
let col_schema = schema.column_schemas()[ts_index].clone();
|
||||
Ok((ts_index, col_schema))
|
||||
}
|
||||
|
||||
pub async fn get_table_id_from_proto_name(
|
||||
&self,
|
||||
name: &greptime_proto::v1::TableName,
|
||||
) -> Result<TableId, Error> {
|
||||
self.table_name_manager
|
||||
.get(TableNameKey::new(
|
||||
&name.catalog_name,
|
||||
&name.schema_name,
|
||||
&name.table_name,
|
||||
))
|
||||
.await
|
||||
.with_context(|_| TableNotFoundMetaSnafu {
|
||||
msg: format!("Table name = {:?}, couldn't found table id", name),
|
||||
})?
|
||||
.with_context(|| UnexpectedSnafu {
|
||||
reason: format!("Table name = {:?}, couldn't found table id", name),
|
||||
})
|
||||
.map(|id| id.table_id())
|
||||
}
|
||||
|
||||
/// If the table haven't been created in database, the tableId returned would be null
|
||||
pub async fn get_opt_table_id_from_name(
|
||||
&self,
|
||||
name: &TableName,
|
||||
) -> Result<Option<TableId>, Error> {
|
||||
let ret = self
|
||||
.table_name_manager
|
||||
.get(TableNameKey::new(&name[0], &name[1], &name[2]))
|
||||
.await
|
||||
.with_context(|_| TableNotFoundMetaSnafu {
|
||||
msg: format!("Table name = {:?}, couldn't found table id", name),
|
||||
})?
|
||||
.map(|id| id.table_id());
|
||||
Ok(ret)
|
||||
}
|
||||
|
||||
/// query metasrv about the table name and table id
|
||||
pub async fn get_table_name(&self, table_id: &TableId) -> Result<TableName, Error> {
|
||||
self.table_info_manager
|
||||
.get(*table_id)
|
||||
.await
|
||||
.map_err(BoxedError::new)
|
||||
.context(ExternalSnafu)?
|
||||
.with_context(|| UnexpectedSnafu {
|
||||
reason: format!("Table id = {:?}, couldn't found table name", table_id),
|
||||
})
|
||||
.map(|name| name.table_name())
|
||||
.map(|name| [name.catalog_name, name.schema_name, name.table_name])
|
||||
}
|
||||
|
||||
/// query metasrv about the `TableInfoValue` and table id
|
||||
pub async fn get_table_info_value(
|
||||
&self,
|
||||
table_id: &TableId,
|
||||
) -> Result<Option<TableInfoValue>, Error> {
|
||||
Ok(self
|
||||
.table_info_manager
|
||||
.get(*table_id)
|
||||
.await
|
||||
.with_context(|_| TableNotFoundMetaSnafu {
|
||||
msg: format!("TableId = {:?}, couldn't found table name", table_id),
|
||||
})?
|
||||
.map(|v| v.into_inner()))
|
||||
}
|
||||
|
||||
pub async fn get_table_name_schema(
|
||||
&self,
|
||||
table_id: &TableId,
|
||||
) -> Result<(TableName, TableDesc), Error> {
|
||||
let table_info_value = self
|
||||
.get_table_info_value(table_id)
|
||||
.await?
|
||||
.with_context(|| TableNotFoundSnafu {
|
||||
name: format!("TableId = {:?}, Can't found table info", table_id),
|
||||
})?;
|
||||
|
||||
let table_name = table_info_value.table_name();
|
||||
let table_name = [
|
||||
table_name.catalog_name,
|
||||
table_name.schema_name,
|
||||
table_name.table_name,
|
||||
];
|
||||
|
||||
let desc = table_info_value_to_relation_desc(table_info_value)?;
|
||||
Ok((table_name, desc))
|
||||
}
|
||||
|
||||
pub async fn check_table_exist(&self, table_id: &TableId) -> Result<bool, Error> {
|
||||
self.table_info_manager
|
||||
.exists(*table_id)
|
||||
.await
|
||||
.map_err(BoxedError::new)
|
||||
.context(ExternalSnafu)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ManagedTableSource {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("KvBackendTableSource").finish()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod test {
|
||||
use std::collections::HashMap;
|
||||
|
||||
use datatypes::data_type::ConcreteDataType as CDT;
|
||||
|
||||
use super::*;
|
||||
use crate::repr::{ColumnType, RelationType};
|
||||
|
||||
pub struct FlowDummyTableSource {
|
||||
pub id_names_to_desc: Vec<(TableId, TableName, TableDesc)>,
|
||||
id_to_idx: HashMap<TableId, usize>,
|
||||
name_to_idx: HashMap<TableName, usize>,
|
||||
}
|
||||
|
||||
impl Default for FlowDummyTableSource {
|
||||
fn default() -> Self {
|
||||
let id_names_to_desc = vec![
|
||||
(
|
||||
1024,
|
||||
[
|
||||
"greptime".to_string(),
|
||||
"public".to_string(),
|
||||
"numbers".to_string(),
|
||||
],
|
||||
TableDesc::new_no_default(
|
||||
RelationType::new(vec![ColumnType::new(CDT::uint32_datatype(), false)])
|
||||
.into_named(vec![Some("number".to_string())]),
|
||||
),
|
||||
),
|
||||
(
|
||||
1025,
|
||||
[
|
||||
"greptime".to_string(),
|
||||
"public".to_string(),
|
||||
"numbers_with_ts".to_string(),
|
||||
],
|
||||
TableDesc::new_no_default(
|
||||
RelationType::new(vec![
|
||||
ColumnType::new(CDT::uint32_datatype(), false),
|
||||
ColumnType::new(CDT::timestamp_millisecond_datatype(), false),
|
||||
])
|
||||
.into_named(vec![Some("number".to_string()), Some("ts".to_string())]),
|
||||
),
|
||||
),
|
||||
];
|
||||
let id_to_idx = id_names_to_desc
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(idx, (id, _name, _desc))| (*id, idx))
|
||||
.collect();
|
||||
let name_to_idx = id_names_to_desc
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(idx, (_id, name, _desc))| (name.clone(), idx))
|
||||
.collect();
|
||||
Self {
|
||||
id_names_to_desc,
|
||||
id_to_idx,
|
||||
name_to_idx,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl FlowTableSource for FlowDummyTableSource {
|
||||
async fn table_from_id(&self, table_id: &TableId) -> Result<TableDesc, Error> {
|
||||
let idx = self.id_to_idx.get(table_id).context(TableNotFoundSnafu {
|
||||
name: format!("Table id = {:?}, couldn't found table desc", table_id),
|
||||
})?;
|
||||
let desc = self
|
||||
.id_names_to_desc
|
||||
.get(*idx)
|
||||
.map(|x| x.2.clone())
|
||||
.context(TableNotFoundSnafu {
|
||||
name: format!("Table id = {:?}, couldn't found table desc", table_id),
|
||||
})?;
|
||||
Ok(desc)
|
||||
}
|
||||
|
||||
async fn table_name_from_id(&self, table_id: &TableId) -> Result<TableName, Error> {
|
||||
let idx = self.id_to_idx.get(table_id).context(TableNotFoundSnafu {
|
||||
name: format!("Table id = {:?}, couldn't found table desc", table_id),
|
||||
})?;
|
||||
self.id_names_to_desc
|
||||
.get(*idx)
|
||||
.map(|x| x.1.clone())
|
||||
.context(TableNotFoundSnafu {
|
||||
name: format!("Table id = {:?}, couldn't found table desc", table_id),
|
||||
})
|
||||
}
|
||||
|
||||
async fn table_id_from_name(&self, name: &TableName) -> Result<TableId, Error> {
|
||||
for (id, table_name, _desc) in &self.id_names_to_desc {
|
||||
if name == table_name {
|
||||
return Ok(*id);
|
||||
}
|
||||
}
|
||||
TableNotFoundSnafu {
|
||||
name: format!("Table name = {:?}, couldn't found table id", name),
|
||||
}
|
||||
.fail()?
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for FlowDummyTableSource {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("DummyTableSource").finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
+65
-1198
File diff suppressed because it is too large
Load Diff
@@ -15,134 +15,11 @@
|
||||
//! Util functions for adapter
|
||||
|
||||
use api::helper::ColumnDataTypeWrapper;
|
||||
use api::v1::column_def::options_from_column_schema;
|
||||
use api::v1::{ColumnDataType, ColumnDataTypeExtension, SemanticType};
|
||||
use common_error::ext::BoxedError;
|
||||
use common_meta::key::table_info::TableInfoValue;
|
||||
use datatypes::prelude::ConcreteDataType;
|
||||
use datatypes::schema::{ColumnDefaultConstraint, ColumnSchema};
|
||||
use itertools::Itertools;
|
||||
use operator::expr_helper;
|
||||
use snafu::ResultExt;
|
||||
use table::table_reference::TableReference;
|
||||
|
||||
use crate::StreamingEngine;
|
||||
use crate::adapter::table_source::TableDesc;
|
||||
use crate::adapter::{AUTO_CREATED_PLACEHOLDER_TS_COL, TableName};
|
||||
use crate::error::{Error, ExternalSnafu};
|
||||
use crate::repr::{ColumnType, RelationDesc, RelationType};
|
||||
impl StreamingEngine {
|
||||
/// Create table from given schema(will adjust to add auto column if needed), return true if table is created
|
||||
pub(crate) async fn create_table_from_relation(
|
||||
&self,
|
||||
flow_name: &str,
|
||||
table_name: &TableName,
|
||||
relation_desc: &RelationDesc,
|
||||
) -> Result<bool, Error> {
|
||||
if self.fetch_table_pk_schema(table_name).await?.is_some() {
|
||||
return Ok(false);
|
||||
}
|
||||
let (pks, tys, _) = self.adjust_auto_created_table_schema(relation_desc).await?;
|
||||
|
||||
//create sink table using pks, column types and is_ts_auto
|
||||
|
||||
let proto_schema = column_schemas_to_proto(tys.clone(), &pks)?;
|
||||
|
||||
// create sink table
|
||||
let create_expr = expr_helper::create_table_expr_by_column_schemas(
|
||||
&TableReference {
|
||||
catalog: &table_name[0],
|
||||
schema: &table_name[1],
|
||||
table: &table_name[2],
|
||||
},
|
||||
&proto_schema,
|
||||
"mito",
|
||||
Some(&format!("Sink table for flow {}", flow_name)),
|
||||
)
|
||||
.map_err(BoxedError::new)
|
||||
.context(ExternalSnafu)?;
|
||||
|
||||
self.frontend_client
|
||||
.create(create_expr, &table_name[0], &table_name[1])
|
||||
.await?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Try fetch table with adjusted schema(added auto column if needed)
|
||||
pub(crate) async fn try_fetch_existing_table(
|
||||
&self,
|
||||
table_name: &TableName,
|
||||
) -> Result<Option<(bool, Vec<api::v1::ColumnSchema>)>, Error> {
|
||||
if let Some((primary_keys, time_index, schema)) =
|
||||
self.fetch_table_pk_schema(table_name).await?
|
||||
{
|
||||
// check if the last column is the auto created timestamp column, hence the table is auto created from
|
||||
// flow's plan type
|
||||
let is_auto_create = {
|
||||
let correct_name = schema
|
||||
.last()
|
||||
.map(|s| s.name == AUTO_CREATED_PLACEHOLDER_TS_COL)
|
||||
.unwrap_or(false);
|
||||
let correct_time_index = time_index == Some(schema.len() - 1);
|
||||
correct_name && correct_time_index
|
||||
};
|
||||
let proto_schema = column_schemas_to_proto(schema, &primary_keys)?;
|
||||
Ok(Some((is_auto_create, proto_schema)))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn table_info_value_to_relation_desc(
|
||||
table_info_value: TableInfoValue,
|
||||
) -> Result<TableDesc, Error> {
|
||||
let raw_schema = table_info_value.table_info.meta.schema;
|
||||
let (column_types, col_names): (Vec<_>, Vec<_>) = raw_schema
|
||||
.column_schemas()
|
||||
.to_vec()
|
||||
.into_iter()
|
||||
.map(|col| {
|
||||
(
|
||||
ColumnType {
|
||||
nullable: col.is_nullable(),
|
||||
scalar_type: col.data_type,
|
||||
},
|
||||
Some(col.name),
|
||||
)
|
||||
})
|
||||
.unzip();
|
||||
|
||||
let key = table_info_value.table_info.meta.primary_key_indices;
|
||||
let keys = vec![crate::repr::Key::from(key)];
|
||||
|
||||
let time_index = raw_schema.timestamp_index();
|
||||
let relation_desc = RelationDesc {
|
||||
typ: RelationType {
|
||||
column_types,
|
||||
keys,
|
||||
time_index,
|
||||
// by default table schema's column are all non-auto
|
||||
auto_columns: vec![],
|
||||
},
|
||||
names: col_names,
|
||||
};
|
||||
let default_values = raw_schema
|
||||
.column_schemas()
|
||||
.iter()
|
||||
.map(|c| {
|
||||
c.default_constraint().cloned().or_else(|| {
|
||||
if c.is_nullable() {
|
||||
Some(ColumnDefaultConstraint::null_value())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect_vec();
|
||||
|
||||
Ok(TableDesc::new(relation_desc, default_values))
|
||||
}
|
||||
|
||||
pub fn from_proto_to_data_type(
|
||||
column_schema: &api::v1::ColumnSchema,
|
||||
@@ -157,68 +34,3 @@ pub fn from_proto_to_data_type(
|
||||
|
||||
Ok(cdt)
|
||||
}
|
||||
|
||||
/// convert `ColumnSchema` lists to it's corresponding proto type
|
||||
pub fn column_schemas_to_proto(
|
||||
column_schemas: Vec<ColumnSchema>,
|
||||
primary_keys: &[String],
|
||||
) -> Result<Vec<api::v1::ColumnSchema>, Error> {
|
||||
let column_datatypes: Vec<(ColumnDataType, Option<ColumnDataTypeExtension>)> = column_schemas
|
||||
.iter()
|
||||
.map(|c| {
|
||||
ColumnDataTypeWrapper::try_from(c.data_type.clone())
|
||||
.map(|w| w.to_parts())
|
||||
.map_err(BoxedError::new)
|
||||
.context(ExternalSnafu)
|
||||
})
|
||||
.try_collect()?;
|
||||
|
||||
let ret = column_schemas
|
||||
.iter()
|
||||
.zip(column_datatypes)
|
||||
.map(|(schema, datatype)| {
|
||||
let semantic_type = if schema.is_time_index() {
|
||||
SemanticType::Timestamp
|
||||
} else if primary_keys.contains(&schema.name) {
|
||||
SemanticType::Tag
|
||||
} else {
|
||||
SemanticType::Field
|
||||
} as i32;
|
||||
|
||||
api::v1::ColumnSchema {
|
||||
column_name: schema.name.clone(),
|
||||
datatype: datatype.0 as i32,
|
||||
semantic_type,
|
||||
datatype_extension: datatype.1,
|
||||
options: options_from_column_schema(schema),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
Ok(ret)
|
||||
}
|
||||
|
||||
/// Convert `RelationDesc` to `ColumnSchema` list,
|
||||
/// if the column name is not present, use `col_{idx}` as the column name
|
||||
pub fn relation_desc_to_column_schemas_with_fallback(schema: &RelationDesc) -> Vec<ColumnSchema> {
|
||||
schema
|
||||
.typ()
|
||||
.column_types
|
||||
.clone()
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(idx, typ)| {
|
||||
let name = schema
|
||||
.names
|
||||
.get(idx)
|
||||
.cloned()
|
||||
.flatten()
|
||||
.unwrap_or(format!("col_{}", idx));
|
||||
let ret = ColumnSchema::new(name, typ.scalar_type, typ.nullable);
|
||||
if schema.typ().time_index == Some(idx) {
|
||||
ret.with_time_index(true)
|
||||
} else {
|
||||
ret
|
||||
}
|
||||
})
|
||||
.collect_vec()
|
||||
}
|
||||
|
||||
@@ -586,87 +586,6 @@ impl FrontendClient {
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle an insert request with one attempt.
|
||||
///
|
||||
/// Unlike [`Self::handle`], this does not use the batching retry policy. It
|
||||
/// is intended for stateless streaming sinks, where retrying an insert can
|
||||
/// duplicate rows.
|
||||
pub(crate) async fn handle_insert_once(
|
||||
&self,
|
||||
req: api::v1::greptime_request::Request,
|
||||
catalog: &str,
|
||||
schema: &str,
|
||||
peer_desc: &mut Option<PeerDesc>,
|
||||
) -> Result<u32, Error> {
|
||||
match self {
|
||||
FrontendClient::Distributed { .. } => {
|
||||
let db = self.get_random_active_frontend(catalog, schema).await?;
|
||||
|
||||
*peer_desc = Some(PeerDesc::Dist {
|
||||
peer: db.peer.clone(),
|
||||
});
|
||||
|
||||
db.database
|
||||
.handle(req.clone())
|
||||
.await
|
||||
.with_context(|_| InvalidRequestSnafu {
|
||||
context: format!("Failed to handle request at {:?}: {:?}", db.peer, req),
|
||||
})
|
||||
}
|
||||
FrontendClient::Standalone {
|
||||
database_client,
|
||||
query,
|
||||
..
|
||||
} => {
|
||||
let ctx = QueryContextBuilder::default()
|
||||
.current_catalog(catalog.to_string())
|
||||
.current_schema(schema.to_string())
|
||||
.channel(Channel::Internal)
|
||||
.extensions(if query.parallelism > 0 {
|
||||
HashMap::from([(
|
||||
QUERY_PARALLELISM_HINT.to_string(),
|
||||
query.parallelism.to_string(),
|
||||
)])
|
||||
} else {
|
||||
HashMap::new()
|
||||
})
|
||||
.build();
|
||||
let ctx = Arc::new(ctx);
|
||||
let database_client = {
|
||||
database_client
|
||||
.handler
|
||||
.lock()
|
||||
.unwrap()
|
||||
.as_ref()
|
||||
.context(UnexpectedSnafu {
|
||||
reason: "Standalone's frontend instance is not set",
|
||||
})?
|
||||
.upgrade()
|
||||
.context(UnexpectedSnafu {
|
||||
reason: "Failed to upgrade database client",
|
||||
})?
|
||||
};
|
||||
let resp: common_query::Output = database_client
|
||||
.do_query(req, ctx)
|
||||
.await
|
||||
.map_err(BoxedError::new)
|
||||
.context(ExternalSnafu)?;
|
||||
match resp.data {
|
||||
common_query::OutputData::AffectedRows(rows) => rows.try_into().map_err(|_| {
|
||||
UnexpectedSnafu {
|
||||
reason: format!("Failed to convert rows to u32: {}", rows),
|
||||
}
|
||||
.build()
|
||||
}),
|
||||
_ => UnexpectedSnafu {
|
||||
reason: "Unexpected output data",
|
||||
}
|
||||
.fail(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle a request to frontend
|
||||
pub(crate) async fn handle(
|
||||
&self,
|
||||
@@ -819,7 +738,6 @@ impl std::fmt::Display for PeerDesc {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::pin::Pin;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::task::{Context, Poll};
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -893,11 +811,6 @@ mod tests {
|
||||
#[derive(Debug)]
|
||||
struct MetricsHandler;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct InsertOnceHandler {
|
||||
calls: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ExtensionAwareHandler;
|
||||
|
||||
@@ -933,19 +846,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl GrpcQueryHandlerWithBoxedError for InsertOnceHandler {
|
||||
async fn do_query(
|
||||
&self,
|
||||
_query: Request,
|
||||
ctx: QueryContextRef,
|
||||
) -> std::result::Result<Output, BoxedError> {
|
||||
assert_eq!(ctx.channel(), Channel::Internal);
|
||||
self.calls.fetch_add(1, Ordering::SeqCst);
|
||||
Ok(Output::new_with_affected_rows(1))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl GrpcQueryHandlerWithBoxedError for MetricsHandler {
|
||||
async fn do_query(
|
||||
@@ -1195,31 +1095,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_handle_insert_once_calls_standalone_handler_once() {
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let handler: Arc<dyn GrpcQueryHandlerWithBoxedError> = Arc::new(InsertOnceHandler {
|
||||
calls: calls.clone(),
|
||||
});
|
||||
let client =
|
||||
FrontendClient::from_grpc_handler(Arc::downgrade(&handler), QueryOptions::default());
|
||||
let mut peer_desc = None;
|
||||
|
||||
let affected_rows = client
|
||||
.handle_insert_once(
|
||||
Request::RowInserts(api::v1::RowInsertRequests { inserts: vec![] }),
|
||||
"greptime",
|
||||
"public",
|
||||
&mut peer_desc,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(affected_rows, 1);
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 1);
|
||||
assert!(peer_desc.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_query_with_terminal_metrics_tracks_watermark_in_standalone_mode() {
|
||||
let handler: Arc<dyn GrpcQueryHandlerWithBoxedError> = Arc::new(MetricsHandler);
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Define a trait for flow engine, which is used by both streaming engine and batch engine
|
||||
//! Defines the flow engine trait implemented by the flownode engine
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
|
||||
+1
-16
@@ -36,19 +36,6 @@ use crate::FlowId;
|
||||
#[snafu(visibility(pub))]
|
||||
#[stack_trace_debug]
|
||||
pub enum Error {
|
||||
#[snafu(display(
|
||||
"Failed to insert into flow: region_id={}, flow_ids={:?}",
|
||||
region_id,
|
||||
flow_ids
|
||||
))]
|
||||
InsertIntoFlow {
|
||||
region_id: u64,
|
||||
flow_ids: Vec<u64>,
|
||||
source: BoxedError,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Flow engine is still recovering"))]
|
||||
FlowNotRecovered {
|
||||
#[snafu(implicit)]
|
||||
@@ -309,7 +296,6 @@ impl ErrorExt for Error {
|
||||
match self {
|
||||
Self::JoinTask { .. }
|
||||
| Self::Datafusion { .. }
|
||||
| Self::InsertIntoFlow { .. }
|
||||
| Self::NoAvailableFrontend { .. }
|
||||
| Self::FlowNotRecovered { .. } => StatusCode::Internal,
|
||||
Self::FlowAlreadyExist { .. } => StatusCode::TableAlreadyExists,
|
||||
@@ -354,8 +340,7 @@ impl ErrorExt for Error {
|
||||
RetryHint::Retryable
|
||||
}
|
||||
|
||||
Self::InsertIntoFlow { source, .. }
|
||||
| Self::CreateFlow { source, .. }
|
||||
Self::CreateFlow { source, .. }
|
||||
| Self::CreateSinkTable { source, .. }
|
||||
| Self::External { source, .. } => source.retry_hint(),
|
||||
|
||||
|
||||
@@ -1,89 +0,0 @@
|
||||
// Copyright 2023 Greptime Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Small row-batch conversion helper used by stateless streaming.
|
||||
|
||||
pub(crate) mod error;
|
||||
use common_recordbatch::RecordBatch;
|
||||
use datatypes::data_type::DataType;
|
||||
use datatypes::prelude::ConcreteDataType;
|
||||
use datatypes::vectors::{Helper, VectorRef};
|
||||
use itertools::Itertools;
|
||||
use snafu::{ResultExt, ensure};
|
||||
|
||||
use crate::Error;
|
||||
use crate::error::DatatypesSnafu;
|
||||
use crate::repr::Row;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Batch {
|
||||
batch: Vec<VectorRef>,
|
||||
row_count: usize,
|
||||
}
|
||||
|
||||
impl TryFrom<RecordBatch> for Batch {
|
||||
type Error = Error;
|
||||
fn try_from(value: RecordBatch) -> Result<Self, Self::Error> {
|
||||
Ok(Self {
|
||||
batch: Helper::try_into_vectors(value.columns()).context(DatatypesSnafu {
|
||||
extra: "failed to convert Arrow array to vector",
|
||||
})?,
|
||||
row_count: value.num_rows(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Batch {
|
||||
pub fn try_from_rows_with_types(
|
||||
rows: Vec<Row>,
|
||||
types: &[ConcreteDataType],
|
||||
) -> Result<Self, error::EvalError> {
|
||||
if rows.is_empty() {
|
||||
return Ok(Self {
|
||||
batch: vec![],
|
||||
row_count: 0,
|
||||
});
|
||||
}
|
||||
let len = rows.len();
|
||||
let mut builders = types
|
||||
.iter()
|
||||
.map(|ty| ty.create_mutable_vector(len))
|
||||
.collect_vec();
|
||||
ensure!(
|
||||
rows.iter().all(|row| row.len() == builders.len()),
|
||||
error::InvalidArgumentSnafu {
|
||||
reason: "row length does not match schema".to_string()
|
||||
}
|
||||
);
|
||||
for row in rows {
|
||||
for (idx, value) in row.iter().enumerate() {
|
||||
builders[idx]
|
||||
.try_push_value_ref(&value.as_value_ref())
|
||||
.context(error::DataTypeSnafu {
|
||||
msg: "failed to convert rows to columns",
|
||||
})?;
|
||||
}
|
||||
}
|
||||
Ok(Self {
|
||||
batch: builders.into_iter().map(|mut b| b.to_vector()).collect(),
|
||||
row_count: len,
|
||||
})
|
||||
}
|
||||
pub fn batch(&self) -> &[VectorRef] {
|
||||
&self.batch
|
||||
}
|
||||
pub fn row_count(&self) -> usize {
|
||||
self.row_count
|
||||
}
|
||||
}
|
||||
@@ -1,133 +0,0 @@
|
||||
// Copyright 2023 Greptime Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Error handling for expression evaluation.
|
||||
|
||||
use std::any::Any;
|
||||
|
||||
use arrow_schema::ArrowError;
|
||||
use common_error::ext::{BoxedError, ErrorExt};
|
||||
use common_error::status_code::StatusCode;
|
||||
use common_macro::stack_trace_debug;
|
||||
use datafusion_common::DataFusionError;
|
||||
use datatypes::data_type::ConcreteDataType;
|
||||
use snafu::{Location, Snafu};
|
||||
|
||||
/// EvalError is about errors happen on columnar evaluation
|
||||
///
|
||||
/// TODO(discord9): add detailed location of column/operator(instead of code) to errors tp help identify related column
|
||||
#[derive(Snafu)]
|
||||
#[snafu(visibility(pub))]
|
||||
#[stack_trace_debug]
|
||||
pub enum EvalError {
|
||||
#[snafu(display("Type mismatch: expected {expected}, actual {actual}"))]
|
||||
TypeMismatch {
|
||||
expected: ConcreteDataType,
|
||||
actual: ConcreteDataType,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
/// can't nest datatypes error because EvalError need to be store in map and serialization
|
||||
#[snafu(display("Fail to unpack from value to given type: {msg}"))]
|
||||
TryFromValue {
|
||||
msg: String,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Fail to cast value of type {from} to given type {to}"))]
|
||||
CastValue {
|
||||
from: ConcreteDataType,
|
||||
to: ConcreteDataType,
|
||||
source: datatypes::Error,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("{msg}"))]
|
||||
DataType {
|
||||
msg: String,
|
||||
source: datatypes::Error,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Invalid argument: {reason}"))]
|
||||
InvalidArgument {
|
||||
reason: String,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Internal error: {reason}"))]
|
||||
Internal {
|
||||
reason: String,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Overflowed during evaluation"))]
|
||||
Overflow {
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Arrow error: {error:?}, context: {context}"))]
|
||||
Arrow {
|
||||
#[snafu(source)]
|
||||
error: ArrowError,
|
||||
context: String,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("DataFusion error: {error:?}, context: {context}"))]
|
||||
Datafusion {
|
||||
#[snafu(source)]
|
||||
error: DataFusionError,
|
||||
context: String,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("External error"))]
|
||||
External {
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
source: BoxedError,
|
||||
},
|
||||
}
|
||||
|
||||
impl ErrorExt for EvalError {
|
||||
fn status_code(&self) -> StatusCode {
|
||||
use EvalError::*;
|
||||
match self {
|
||||
TypeMismatch { .. }
|
||||
| TryFromValue { .. }
|
||||
| InvalidArgument { .. }
|
||||
| Overflow { .. } => StatusCode::InvalidArguments,
|
||||
|
||||
CastValue { source, .. } | DataType { source, .. } => source.status_code(),
|
||||
|
||||
Internal { .. } | Arrow { .. } | Datafusion { .. } | External { .. } => {
|
||||
StatusCode::Internal
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
+2
-4
@@ -26,18 +26,16 @@ pub(crate) mod batching_mode;
|
||||
mod df_optimizer;
|
||||
pub(crate) mod engine;
|
||||
pub mod error;
|
||||
mod expr;
|
||||
pub mod heartbeat;
|
||||
mod metrics;
|
||||
mod repr;
|
||||
mod server;
|
||||
mod utils;
|
||||
|
||||
#[cfg(test)]
|
||||
mod test_utils;
|
||||
|
||||
pub use adapter::flownode_impl::FlowDualEngineRef;
|
||||
pub use adapter::{FlowConfig, FlowStreamingEngineRef, StreamingEngine};
|
||||
pub use adapter::FlowConfig;
|
||||
pub use adapter::flownode_impl::FlownodeEngineRef;
|
||||
pub use batching_mode::BatchingModeOptions;
|
||||
pub use batching_mode::batching_execution::{BatchingExecution, BatchingExecutionFactory};
|
||||
pub use batching_mode::frontend_client::{
|
||||
|
||||
@@ -1,262 +0,0 @@
|
||||
// Copyright 2023 Greptime Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! basically a wrapper around the `datatype` crate
|
||||
//! for basic Data Representation
|
||||
|
||||
mod relation;
|
||||
|
||||
use api::helper::{pb_value_to_value_ref, to_grpc_value};
|
||||
use api::v1::Row as ProtoRow;
|
||||
use datatypes::data_type::ConcreteDataType;
|
||||
use datatypes::types::cast;
|
||||
use datatypes::value::Value;
|
||||
use get_size2::GetSize;
|
||||
use itertools::Itertools;
|
||||
pub(crate) use relation::{ColumnType, Key, RelationDesc, RelationType};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use snafu::ResultExt;
|
||||
|
||||
use crate::expr::error::{CastValueSnafu, EvalError, InvalidArgumentSnafu};
|
||||
use crate::utils::get_value_heap_size;
|
||||
|
||||
/// System-wide Record count difference type. Useful for capture data change
|
||||
///
|
||||
/// i.e. +1 means insert one record, -1 means remove,
|
||||
/// and +/-n means insert/remove multiple duplicate records.
|
||||
pub type Diff = i64;
|
||||
|
||||
/// System-wide default timestamp type, in milliseconds
|
||||
pub type Timestamp = i64;
|
||||
|
||||
/// System-wide default duration type, in milliseconds
|
||||
pub type Duration = i64;
|
||||
|
||||
/// Default type for a repr of changes to a collection.
|
||||
pub type DiffRow = (Row, Timestamp, Diff);
|
||||
|
||||
/// Row with key-value pair, timestamp and diff
|
||||
pub type KeyValDiffRow = ((Row, Row), Timestamp, Diff);
|
||||
|
||||
/// broadcast channel capacity, can be important to memory consumption, since this influence how many
|
||||
/// updates can be buffered in memory in the entire dataflow
|
||||
/// TODO(discord9): add config for this, so cpu&mem usage can be balanced and configured by this
|
||||
pub const BROADCAST_CAP: usize = 1024;
|
||||
|
||||
/// The maximum capacity of the send buffer, to prevent the buffer from growing too large
|
||||
pub const SEND_BUF_CAP: usize = BROADCAST_CAP * 2;
|
||||
|
||||
/// Batch size used by the batching execution path.
|
||||
pub const BATCH_SIZE: usize = 32 * 16384;
|
||||
|
||||
/// Convert a value that is or can be converted to Datetime to internal timestamp
|
||||
///
|
||||
/// support types are: `Date`, `DateTime`, `TimeStamp`, `i64`
|
||||
pub fn value_to_internal_ts(value: Value) -> Result<i64, EvalError> {
|
||||
let is_supported_time_type = |arg: &Value| {
|
||||
let ty = arg.data_type();
|
||||
matches!(
|
||||
ty,
|
||||
ConcreteDataType::Date(..) | ConcreteDataType::Timestamp(..)
|
||||
)
|
||||
};
|
||||
match value {
|
||||
Value::Int64(ts) => Ok(ts),
|
||||
arg if is_supported_time_type(&arg) => {
|
||||
let arg_ty = arg.data_type();
|
||||
let res = cast(arg, &ConcreteDataType::timestamp_millisecond_datatype()).context({
|
||||
CastValueSnafu {
|
||||
from: arg_ty,
|
||||
to: ConcreteDataType::timestamp_millisecond_datatype(),
|
||||
}
|
||||
})?;
|
||||
if let Value::Timestamp(ts) = res {
|
||||
Ok(ts.value())
|
||||
} else {
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
_ => InvalidArgumentSnafu {
|
||||
reason: format!("Expect a time type or i64, got {:?}", value.data_type()),
|
||||
}
|
||||
.fail(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A row is a vector of values.
|
||||
///
|
||||
/// TODO(discord9): use a more efficient representation
|
||||
/// i.e. more compact like raw u8 of \[tag0, value0, tag1, value1, ...\]
|
||||
#[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Default, Serialize, Deserialize)]
|
||||
pub struct Row {
|
||||
/// The inner vector of values
|
||||
pub inner: Vec<Value>,
|
||||
}
|
||||
|
||||
impl GetSize for Row {
|
||||
fn get_heap_size(&self) -> usize {
|
||||
self.inner.iter().map(get_value_heap_size).sum()
|
||||
}
|
||||
}
|
||||
|
||||
impl Row {
|
||||
/// Create an empty row
|
||||
pub fn empty() -> Self {
|
||||
Self { inner: vec![] }
|
||||
}
|
||||
|
||||
/// Returns true if the Row contains no elements.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.inner.is_empty()
|
||||
}
|
||||
|
||||
/// Create a row from a vector of values
|
||||
pub fn new(row: Vec<Value>) -> Self {
|
||||
Self { inner: row }
|
||||
}
|
||||
|
||||
/// Get the value at the given index
|
||||
pub fn get(&self, idx: usize) -> Option<&Value> {
|
||||
self.inner.get(idx)
|
||||
}
|
||||
|
||||
/// Clear the row
|
||||
pub fn clear(&mut self) {
|
||||
self.inner.clear();
|
||||
}
|
||||
|
||||
/// clear and return the inner vector
|
||||
///
|
||||
/// useful if you want to reuse the vector as a buffer
|
||||
pub fn packer(&mut self) -> &mut Vec<Value> {
|
||||
self.inner.clear();
|
||||
&mut self.inner
|
||||
}
|
||||
|
||||
/// pack a iterator of values into a row
|
||||
pub fn pack<I>(iter: I) -> Row
|
||||
where
|
||||
I: IntoIterator<Item = Value>,
|
||||
{
|
||||
Self {
|
||||
inner: iter.into_iter().collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// unpack a row into a vector of values
|
||||
pub fn unpack(self) -> Vec<Value> {
|
||||
self.inner
|
||||
}
|
||||
|
||||
/// extend the row with values from an iterator
|
||||
pub fn extend<I>(&mut self, iter: I)
|
||||
where
|
||||
I: IntoIterator<Item = Value>,
|
||||
{
|
||||
self.inner.extend(iter);
|
||||
}
|
||||
|
||||
/// Creates a consuming iterator, that is, one that moves each value out of the `Row` (from start to end). The `Row` cannot be used after calling this
|
||||
pub fn into_iter(self) -> impl Iterator<Item = Value> {
|
||||
self.inner.into_iter()
|
||||
}
|
||||
|
||||
/// Returns an iterator over the slice.
|
||||
pub fn iter(&self) -> impl Iterator<Item = &Value> {
|
||||
self.inner.iter()
|
||||
}
|
||||
|
||||
/// Returns the number of elements in the row, also known as its 'length'.
|
||||
pub fn len(&self) -> usize {
|
||||
self.inner.len()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Vec<Value>> for Row {
|
||||
fn from(row: Vec<Value>) -> Self {
|
||||
Row::new(row)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ProtoRow> for Row {
|
||||
fn from(row: ProtoRow) -> Self {
|
||||
Row::pack(
|
||||
row.values
|
||||
.iter()
|
||||
.map(|pb_val| -> Value { pb_value_to_value_ref(pb_val, None).into() }),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Row> for ProtoRow {
|
||||
fn from(row: Row) -> Self {
|
||||
let values = row.unpack().into_iter().map(to_grpc_value).collect_vec();
|
||||
ProtoRow { values }
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use common_time::{Date, Timestamp};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_row() {
|
||||
let row = Row::empty();
|
||||
let row_1 = Row::new(vec![]);
|
||||
assert_eq!(row, row_1);
|
||||
let mut row_2 = Row::new(vec![Value::Int32(1), Value::Int32(2)]);
|
||||
assert_eq!(row_2.get(0), Some(&Value::Int32(1)));
|
||||
row_2.clear();
|
||||
assert_eq!(row_2.get(0), None);
|
||||
row_2
|
||||
.packer()
|
||||
.extend(vec![Value::Int32(1), Value::Int32(2)]);
|
||||
assert_eq!(row_2.get(0), Some(&Value::Int32(1)));
|
||||
row_2.extend(vec![Value::Int32(1), Value::Int32(2)]);
|
||||
assert_eq!(row_2.len(), 4);
|
||||
let row_3 = Row::pack(row_2.into_iter());
|
||||
assert_eq!(row_3.len(), 4);
|
||||
let row_4 = Row::pack(row_3.iter().cloned());
|
||||
assert_eq!(row_3, row_4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cast_to_internal_ts() {
|
||||
{
|
||||
let a = Value::from(1i32);
|
||||
let b = Value::from(1i64);
|
||||
let c = Value::Timestamp(Timestamp::new_millisecond(1i64));
|
||||
let d = Value::from(1.0);
|
||||
|
||||
assert!(value_to_internal_ts(a).is_err());
|
||||
assert_eq!(value_to_internal_ts(b).unwrap(), 1i64);
|
||||
assert_eq!(value_to_internal_ts(c).unwrap(), 1i64);
|
||||
assert!(value_to_internal_ts(d).is_err());
|
||||
}
|
||||
|
||||
{
|
||||
// time related type
|
||||
let a = Value::Date(Date::new(1));
|
||||
assert_eq!(value_to_internal_ts(a).unwrap(), 86400 * 1000i64);
|
||||
let b = Value::Timestamp(common_time::Timestamp::new_second(1));
|
||||
assert_eq!(value_to_internal_ts(b).unwrap(), 1000i64);
|
||||
let c = Value::Time(common_time::time::Time::new_second(1));
|
||||
assert!(matches!(
|
||||
value_to_internal_ts(c),
|
||||
Err(EvalError::InvalidArgument { .. })
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,457 +0,0 @@
|
||||
// Copyright 2023 Greptime Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use datafusion_common::DFSchema;
|
||||
use datatypes::data_type::DataType;
|
||||
use datatypes::prelude::ConcreteDataType;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use snafu::{ResultExt, ensure};
|
||||
|
||||
use crate::error::{DatafusionSnafu, InternalSnafu, InvalidQuerySnafu, Result};
|
||||
|
||||
/// a set of column indices that are "keys" for the collection.
|
||||
#[derive(Default, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize, Hash)]
|
||||
pub struct Key {
|
||||
/// indicate whose column form key
|
||||
pub column_indices: Vec<usize>,
|
||||
}
|
||||
|
||||
impl Key {
|
||||
/// create a new Key
|
||||
pub fn new() -> Self {
|
||||
Default::default()
|
||||
}
|
||||
|
||||
/// create a new Key from a vector of column indices
|
||||
pub fn from(mut column_indices: Vec<usize>) -> Self {
|
||||
column_indices.sort_unstable();
|
||||
Self { column_indices }
|
||||
}
|
||||
|
||||
/// Add a column to Key
|
||||
pub fn add_col(&mut self, col: usize) {
|
||||
self.column_indices.push(col);
|
||||
}
|
||||
|
||||
/// Remove a column from Key
|
||||
pub fn remove_col(&mut self, col: usize) {
|
||||
self.column_indices.retain(|&r| r != col);
|
||||
}
|
||||
|
||||
/// get all columns in Key
|
||||
pub fn get(&self) -> &Vec<usize> {
|
||||
&self.column_indices
|
||||
}
|
||||
|
||||
/// True if Key is empty
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.column_indices.is_empty()
|
||||
}
|
||||
|
||||
/// True if all columns in self are also in other
|
||||
pub fn subset_of(&self, other: &Key) -> bool {
|
||||
self.column_indices
|
||||
.iter()
|
||||
.all(|c| other.column_indices.contains(c))
|
||||
}
|
||||
}
|
||||
|
||||
/// The type of a relation.
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize, Hash)]
|
||||
pub struct RelationType {
|
||||
/// The type for each column, in order.
|
||||
pub column_types: Vec<ColumnType>,
|
||||
/// Sets of indices that are "keys" for the collection.
|
||||
///
|
||||
/// Each element in this list is a set of column indices, each with the
|
||||
/// property that the collection contains at most one record with each
|
||||
/// distinct set of values for each column. Alternately, for a specific set
|
||||
/// of values assigned to the these columns there is at most one record.
|
||||
///
|
||||
/// A collection can contain multiple sets of keys, although it is common to
|
||||
/// have either zero or one sets of key indices.
|
||||
pub keys: Vec<Key>,
|
||||
/// optionally indicate the column that is TIME INDEX
|
||||
pub time_index: Option<usize>,
|
||||
/// mark all the columns that are added automatically by flow, but are not present in original sql
|
||||
pub auto_columns: Vec<usize>,
|
||||
}
|
||||
|
||||
impl RelationType {
|
||||
pub fn with_autos(mut self, auto_cols: &[usize]) -> Self {
|
||||
self.auto_columns = auto_cols.to_vec();
|
||||
self
|
||||
}
|
||||
|
||||
/// Constructs a `RelationType` representing the relation with no columns and
|
||||
/// no keys.
|
||||
pub fn empty() -> Self {
|
||||
RelationType::new(vec![])
|
||||
}
|
||||
|
||||
/// Constructs a new `RelationType` from specified column types.
|
||||
///
|
||||
/// The `RelationType` will have no keys.
|
||||
pub fn new(column_types: Vec<ColumnType>) -> Self {
|
||||
RelationType {
|
||||
column_types,
|
||||
keys: Vec::new(),
|
||||
time_index: None,
|
||||
auto_columns: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds a new key for the relation. Also sorts the key indices.
|
||||
///
|
||||
/// will ignore empty key
|
||||
pub fn with_key(mut self, mut indices: Vec<usize>) -> Self {
|
||||
if indices.is_empty() {
|
||||
return self;
|
||||
}
|
||||
indices.sort_unstable();
|
||||
let key = Key::from(indices);
|
||||
if !self.keys.contains(&key) {
|
||||
self.keys.push(key);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds new keys for the relation. Also sorts the key indices.
|
||||
///
|
||||
/// will ignore empty keys
|
||||
pub fn with_keys(mut self, keys: Vec<Vec<usize>>) -> Self {
|
||||
for key in keys {
|
||||
self = self.with_key(key)
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// will also remove time index from keys if it's in keys
|
||||
pub fn with_time_index(mut self, time_index: Option<usize>) -> Self {
|
||||
self.time_index = time_index;
|
||||
for key in &mut self.keys {
|
||||
key.remove_col(time_index.unwrap_or(usize::MAX));
|
||||
}
|
||||
// remove empty keys
|
||||
self.keys.retain(|key| !key.is_empty());
|
||||
self
|
||||
}
|
||||
|
||||
/// Computes the number of columns in the relation.
|
||||
pub fn arity(&self) -> usize {
|
||||
self.column_types.len()
|
||||
}
|
||||
|
||||
/// Gets the index of the columns used when creating a default index.
|
||||
pub fn default_key(&self) -> Vec<usize> {
|
||||
if let Some(key) = self.keys.first() {
|
||||
if key.is_empty() {
|
||||
(0..self.column_types.len()).collect()
|
||||
} else {
|
||||
key.get().clone()
|
||||
}
|
||||
} else {
|
||||
(0..self.column_types.len()).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// True if any collection described by `self` could safely be described by `other`.
|
||||
///
|
||||
/// In practice this means checking that the scalar types match exactly, and that the
|
||||
/// nullability of `self` is at least as strict as `other`, and that all keys of `other`
|
||||
/// contain some key of `self` (as a set of key columns is less strict than any subset).
|
||||
pub fn subtypes(&self, other: &RelationType) -> bool {
|
||||
if self.column_types.len() != other.column_types.len() {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (col1, col2) in self.column_types.iter().zip(other.column_types.iter()) {
|
||||
if col1.nullable && !col2.nullable {
|
||||
return false;
|
||||
}
|
||||
if col1.scalar_type != col2.scalar_type {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
let all_keys = other
|
||||
.keys
|
||||
.iter()
|
||||
.all(|key1| self.keys.iter().any(|key2| key1.subset_of(key2)));
|
||||
if !all_keys {
|
||||
return false;
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
/// Return relation describe with column names
|
||||
pub fn into_named(self, names: Vec<Option<ColumnName>>) -> RelationDesc {
|
||||
RelationDesc { typ: self, names }
|
||||
}
|
||||
|
||||
/// Return relation describe without column names
|
||||
pub fn into_unnamed(self) -> RelationDesc {
|
||||
RelationDesc {
|
||||
names: vec![None; self.column_types.len()],
|
||||
typ: self,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The type of a `Value`
|
||||
///
|
||||
/// [`ColumnType`] bundles information about the scalar type of a datum (e.g.,
|
||||
/// Int32 or String) with its nullability.
|
||||
///
|
||||
/// To construct a column type, either initialize the struct directly, or
|
||||
/// use the [`ScalarType::nullable`] method.
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize, Hash)]
|
||||
pub struct ColumnType {
|
||||
/// The underlying scalar type (e.g., Int32 or String) of this column.
|
||||
pub scalar_type: ConcreteDataType,
|
||||
/// Whether this datum can be null.
|
||||
#[serde(default = "return_true")]
|
||||
pub nullable: bool,
|
||||
}
|
||||
|
||||
impl ColumnType {
|
||||
/// Constructs a new `ColumnType` from a scalar type and a nullability flag.
|
||||
pub fn new(scalar_type: ConcreteDataType, nullable: bool) -> Self {
|
||||
ColumnType {
|
||||
scalar_type,
|
||||
nullable,
|
||||
}
|
||||
}
|
||||
|
||||
/// Constructs a new `ColumnType` from a scalar type, with nullability set to
|
||||
/// ***true***
|
||||
pub fn new_nullable(scalar_type: ConcreteDataType) -> Self {
|
||||
ColumnType {
|
||||
scalar_type,
|
||||
nullable: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the scalar type of this column.
|
||||
pub fn scalar_type(&self) -> &ConcreteDataType {
|
||||
&self.scalar_type
|
||||
}
|
||||
|
||||
/// Returns true if this column can be null.
|
||||
pub fn nullable(&self) -> bool {
|
||||
self.nullable
|
||||
}
|
||||
}
|
||||
|
||||
/// This method exists solely for the purpose of making ColumnType nullable by
|
||||
/// default in unit tests. The default value of a bool is false, and the only
|
||||
/// way to make an object take on any other value by default is to pass it a
|
||||
/// function that returns the desired default value. See
|
||||
/// <https://github.com/serde-rs/serde/issues/1030>
|
||||
#[inline(always)]
|
||||
fn return_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// A description of the shape of a relation.
|
||||
///
|
||||
/// It bundles a [`RelationType`] with the name of each column in the relation.
|
||||
/// Individual column names are optional.
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize, Hash)]
|
||||
pub struct RelationDesc {
|
||||
pub typ: RelationType,
|
||||
pub names: Vec<Option<ColumnName>>,
|
||||
}
|
||||
|
||||
impl RelationDesc {
|
||||
pub fn len(&self) -> Result<usize> {
|
||||
ensure!(
|
||||
self.typ.column_types.len() == self.names.len(),
|
||||
InternalSnafu {
|
||||
reason: "Expect typ and names field to be of same length"
|
||||
}
|
||||
);
|
||||
Ok(self.names.len())
|
||||
}
|
||||
|
||||
pub fn to_df_schema(&self) -> Result<DFSchema> {
|
||||
let fields: Vec<_> = self
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, (name, typ))| {
|
||||
let name = name.clone().unwrap_or(format!("Col_{i}"));
|
||||
let nullable = typ.nullable;
|
||||
let data_type = typ.scalar_type.clone().as_arrow_type();
|
||||
arrow_schema::Field::new(name, data_type, nullable)
|
||||
})
|
||||
.collect();
|
||||
let arrow_schema = arrow_schema::Schema::new(fields);
|
||||
|
||||
DFSchema::try_from(arrow_schema.clone()).with_context(|_e| DatafusionSnafu {
|
||||
context: format!("Error when converting to DFSchema: {:?}", arrow_schema),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl RelationDesc {
|
||||
/// Constructs a new `RelationDesc` that represents the empty relation
|
||||
/// with no columns and no keys.
|
||||
pub fn empty() -> Self {
|
||||
RelationDesc {
|
||||
typ: RelationType::empty(),
|
||||
names: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// Constructs a new `RelationDesc` from a `RelationType` and an iterator
|
||||
/// over column names.
|
||||
///
|
||||
pub fn try_new<I, N>(typ: RelationType, names: I) -> Result<Self>
|
||||
where
|
||||
I: IntoIterator<Item = N>,
|
||||
N: Into<Option<ColumnName>>,
|
||||
{
|
||||
let names: Vec<_> = names.into_iter().map(|name| name.into()).collect();
|
||||
ensure!(
|
||||
typ.arity() == names.len(),
|
||||
InvalidQuerySnafu {
|
||||
reason: format!(
|
||||
"Length mismatch between RelationType {:?} and column names {:?}",
|
||||
typ.column_types, names
|
||||
)
|
||||
}
|
||||
);
|
||||
Ok(RelationDesc { typ, names })
|
||||
}
|
||||
|
||||
/// Constructs a new `RelationDesc` from a `RelationType` and an iterator
|
||||
/// over column names.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if the arity of the `RelationType` is not equal to the number of
|
||||
/// items in `names`.
|
||||
pub fn new_unchecked<I, N>(typ: RelationType, names: I) -> Self
|
||||
where
|
||||
I: IntoIterator<Item = N>,
|
||||
N: Into<Option<ColumnName>>,
|
||||
{
|
||||
let names: Vec<_> = names.into_iter().map(|name| name.into()).collect();
|
||||
assert_eq!(typ.arity(), names.len());
|
||||
RelationDesc { typ, names }
|
||||
}
|
||||
|
||||
pub fn from_names_and_types<I, T, N>(iter: I) -> Self
|
||||
where
|
||||
I: IntoIterator<Item = (N, T)>,
|
||||
T: Into<ColumnType>,
|
||||
N: Into<Option<ColumnName>>,
|
||||
{
|
||||
let (names, types): (Vec<_>, Vec<_>) = iter.into_iter().unzip();
|
||||
let types = types.into_iter().map(Into::into).collect();
|
||||
let typ = RelationType::new(types);
|
||||
Self::new_unchecked(typ, names)
|
||||
}
|
||||
/// Concatenates a `RelationDesc` onto the end of this `RelationDesc`.
|
||||
pub fn concat(mut self, other: Self) -> Self {
|
||||
let self_len = self.typ.column_types.len();
|
||||
self.names.extend(other.names);
|
||||
self.typ.column_types.extend(other.typ.column_types);
|
||||
for k in other.typ.keys {
|
||||
let k = k
|
||||
.column_indices
|
||||
.into_iter()
|
||||
.map(|idx| idx + self_len)
|
||||
.collect();
|
||||
self = self.with_key(k);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Appends a column with the specified name and type.
|
||||
pub fn with_column<N>(mut self, name: N, column_type: ColumnType) -> Self
|
||||
where
|
||||
N: Into<Option<ColumnName>>,
|
||||
{
|
||||
self.typ.column_types.push(column_type);
|
||||
self.names.push(name.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds a new key for the relation.
|
||||
pub fn with_key(mut self, indices: Vec<usize>) -> Self {
|
||||
self.typ = self.typ.with_key(indices);
|
||||
self
|
||||
}
|
||||
|
||||
/// Builds a new relation description with the column names replaced with
|
||||
/// new names.
|
||||
///
|
||||
pub fn try_with_names<I, N>(self, names: I) -> Result<Self>
|
||||
where
|
||||
I: IntoIterator<Item = N>,
|
||||
N: Into<Option<ColumnName>>,
|
||||
{
|
||||
Self::try_new(self.typ, names)
|
||||
}
|
||||
|
||||
/// Computes the number of columns in the relation.
|
||||
pub fn arity(&self) -> usize {
|
||||
self.typ.arity()
|
||||
}
|
||||
|
||||
/// Returns the relation type underlying this relation description.
|
||||
pub fn typ(&self) -> &RelationType {
|
||||
&self.typ
|
||||
}
|
||||
|
||||
/// Returns an iterator over the columns in this relation.
|
||||
pub fn iter(&self) -> impl Iterator<Item = (&Option<ColumnName>, &ColumnType)> {
|
||||
self.iter_names().zip(self.iter_types())
|
||||
}
|
||||
|
||||
/// Returns an iterator over the types of the columns in this relation.
|
||||
pub fn iter_types(&self) -> impl Iterator<Item = &ColumnType> {
|
||||
self.typ.column_types.iter()
|
||||
}
|
||||
|
||||
/// Returns an iterator over the names of the columns in this relation.
|
||||
pub fn iter_names(&self) -> impl Iterator<Item = &Option<ColumnName>> {
|
||||
self.names.iter()
|
||||
}
|
||||
|
||||
/// Finds a column by name.
|
||||
///
|
||||
/// Returns the index and type of the column named `name`. If no column with
|
||||
/// the specified name exists, returns `None`. If multiple columns have the
|
||||
/// specified name, the leftmost column is returned.
|
||||
pub fn get_by_name(&self, name: &ColumnName) -> Option<(usize, &ColumnType)> {
|
||||
self.iter_names()
|
||||
.position(|n| n.as_ref() == Some(name))
|
||||
.map(|i| (i, &self.typ.column_types[i]))
|
||||
}
|
||||
|
||||
/// Gets the name of the `i`th column.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if `i` is not a valid column index.
|
||||
pub fn get_name(&self, i: usize) -> &Option<ColumnName> {
|
||||
&self.names[i]
|
||||
}
|
||||
}
|
||||
|
||||
/// The name of a column in a [`RelationDesc`].
|
||||
pub type ColumnName = String;
|
||||
+18
-36
@@ -38,7 +38,7 @@ use snafu::ResultExt;
|
||||
use tonic::codec::CompressionEncoding;
|
||||
use tonic::{Request, Response, Status};
|
||||
|
||||
use crate::adapter::flownode_impl::{FlowDualEngine, FlowDualEngineRef};
|
||||
use crate::adapter::flownode_impl::{FlownodeEngine, FlownodeEngineRef};
|
||||
use crate::batching_mode::engine::BatchingEngine;
|
||||
use crate::error::{
|
||||
DatafusionSnafu, ExternalSnafu, ListFlowsSnafu, ParseAddrSnafu, ShutdownServerSnafu,
|
||||
@@ -47,20 +47,18 @@ use crate::error::{
|
||||
use crate::heartbeat::HeartbeatTask;
|
||||
use crate::metrics::{METRIC_FLOW_PROCESSING_TIME, METRIC_FLOW_ROWS};
|
||||
use crate::utils::{SizeReportSender, StateReportHandler};
|
||||
use crate::{BatchingExecutionFactory, Error, FlownodeOptions, FrontendClient, StreamingEngine};
|
||||
use crate::{BatchingExecutionFactory, Error, FlownodeOptions, FrontendClient};
|
||||
|
||||
pub const FLOW_NODE_SERVER_NAME: &str = "FLOW_NODE_SERVER";
|
||||
/// wrapping flow node manager to avoid orphan rule with Arc<...>
|
||||
#[derive(Clone)]
|
||||
pub struct FlowService {
|
||||
pub dual_engine: FlowDualEngineRef,
|
||||
pub engine: FlownodeEngineRef,
|
||||
}
|
||||
|
||||
impl FlowService {
|
||||
pub fn new(manager: FlowDualEngineRef) -> Self {
|
||||
Self {
|
||||
dual_engine: manager,
|
||||
}
|
||||
pub fn new(engine: FlownodeEngineRef) -> Self {
|
||||
Self { engine }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,7 +73,7 @@ impl flow_server::Flow for FlowService {
|
||||
.start_timer();
|
||||
|
||||
let request = request.into_inner();
|
||||
self.dual_engine
|
||||
self.engine
|
||||
.handle(request)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
@@ -117,7 +115,7 @@ impl flow_server::Flow for FlowService {
|
||||
.with_label_values(&["in"])
|
||||
.inc_by(row_count as u64);
|
||||
|
||||
self.dual_engine
|
||||
self.engine
|
||||
.handle_inserts(request)
|
||||
.await
|
||||
.map(Response::new)
|
||||
@@ -128,7 +126,7 @@ impl flow_server::Flow for FlowService {
|
||||
&self,
|
||||
reqs: Request<DirtyWindowRequests>,
|
||||
) -> Result<Response<FlowResponse>, Status> {
|
||||
self.dual_engine
|
||||
self.engine
|
||||
.handle_mark_window_dirty(reqs.into_inner())
|
||||
.await
|
||||
.map(Response::new)
|
||||
@@ -238,8 +236,8 @@ impl FlownodeInstance {
|
||||
&self.flownode_server
|
||||
}
|
||||
|
||||
pub fn flow_engine(&self) -> FlowDualEngineRef {
|
||||
self.flownode_server.inner.flow_service.dual_engine.clone()
|
||||
pub fn flow_engine(&self) -> FlownodeEngineRef {
|
||||
self.flownode_server.inner.flow_service.engine.clone()
|
||||
}
|
||||
|
||||
pub fn setup_services(&mut self, services: ServerHandlers) {
|
||||
@@ -332,7 +330,6 @@ impl FlownodeBuilder {
|
||||
.context(DatafusionSnafu {
|
||||
context: "Failed to build query engine",
|
||||
})?;
|
||||
let manager = Arc::new(self.build_manager(query_engine_factory.query_engine()));
|
||||
let batching = Arc::new(BatchingEngine::new_with_execution(
|
||||
self.frontend_client.clone(),
|
||||
query_engine_factory.query_engine(),
|
||||
@@ -342,18 +339,18 @@ impl FlownodeBuilder {
|
||||
self.opts.flow.batching_mode.clone(),
|
||||
self.plugins.get::<Arc<dyn BatchingExecutionFactory>>(),
|
||||
));
|
||||
let dual = Arc::new(FlowDualEngine::new(
|
||||
manager.clone(),
|
||||
let engine = Arc::new(FlownodeEngine::new(
|
||||
self.opts.node_id.map(|id| id as u32),
|
||||
batching,
|
||||
self.flow_metadata_manager.clone(),
|
||||
self.catalog_manager.clone(),
|
||||
self.plugins.clone(),
|
||||
));
|
||||
if let Some(handler) = self.state_report_handler.take() {
|
||||
dual.set_state_report_handler(handler).await;
|
||||
engine.set_state_report_handler(handler).await;
|
||||
}
|
||||
|
||||
let server = FlownodeServer::new(FlowService::new(dual));
|
||||
let server = FlownodeServer::new(FlowService::new(engine));
|
||||
|
||||
let heartbeat_task = self.heartbeat_task;
|
||||
|
||||
@@ -366,15 +363,6 @@ impl FlownodeBuilder {
|
||||
};
|
||||
Ok(instance)
|
||||
}
|
||||
|
||||
fn build_manager(&self, query_engine: Arc<dyn query::QueryEngine>) -> StreamingEngine {
|
||||
StreamingEngine::new(
|
||||
self.opts.node_id.map(|id| id as u32),
|
||||
query_engine,
|
||||
self.table_meta.clone(),
|
||||
self.frontend_client.clone(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Useful in distributed mode
|
||||
@@ -532,12 +520,6 @@ mod tests {
|
||||
let query_engine = crate::test_utils::create_test_query_engine();
|
||||
|
||||
let frontend_client = Arc::new(frontend_client);
|
||||
let streaming_engine = Arc::new(StreamingEngine::new(
|
||||
node_id,
|
||||
query_engine.clone(),
|
||||
table_meta.clone(),
|
||||
frontend_client.clone(),
|
||||
));
|
||||
let batching_engine = Arc::new(BatchingEngine::new(
|
||||
frontend_client,
|
||||
query_engine,
|
||||
@@ -546,8 +528,8 @@ mod tests {
|
||||
catalog_manager.clone(),
|
||||
batching_opts,
|
||||
));
|
||||
let dual_engine = Arc::new(FlowDualEngine::new(
|
||||
streaming_engine,
|
||||
let engine = Arc::new(FlownodeEngine::new(
|
||||
node_id,
|
||||
batching_engine,
|
||||
flow_meta,
|
||||
catalog_manager,
|
||||
@@ -555,9 +537,9 @@ mod tests {
|
||||
));
|
||||
|
||||
let (report_sender, report_handler) = SizeReportSender::new();
|
||||
dual_engine.set_state_report_handler(report_handler).await;
|
||||
engine.set_state_report_handler(report_handler).await;
|
||||
|
||||
let server = FlownodeServer::new(FlowService::new(dual_engine));
|
||||
let server = FlownodeServer::new(FlowService::new(engine));
|
||||
(server, report_sender)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,20 +13,10 @@
|
||||
// limitations under the License.
|
||||
|
||||
use common_meta::key::flow::flow_state::FlowStat;
|
||||
use datatypes::value::Value;
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
|
||||
use crate::error::InternalSnafu;
|
||||
|
||||
pub fn get_value_heap_size(value: &Value) -> usize {
|
||||
match value {
|
||||
Value::Binary(v) => v.len(),
|
||||
Value::String(v) => v.len(),
|
||||
Value::List(v) => v.items().iter().map(get_value_heap_size).sum(),
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct SizeReportSender {
|
||||
inner: mpsc::Sender<oneshot::Sender<FlowStat>>,
|
||||
|
||||
@@ -289,16 +289,12 @@ fn determine_flow_type_for_source_state(
|
||||
flow_options: &HashMap<String, String>,
|
||||
has_missing_source_table: bool,
|
||||
has_instant_ttl_source_table: bool,
|
||||
force_batching: bool,
|
||||
) -> Result<Option<FlowType>> {
|
||||
if has_instant_ttl_source_table && force_batching {
|
||||
// The batching scheduler cannot read instant-TTL source tables, so
|
||||
// reject this combination even when another source table is missing.
|
||||
if has_instant_ttl_source_table {
|
||||
// The batching scheduler cannot read instant-TTL source tables, and it is the
|
||||
// only scheduler left, so reject the flow even when another source is missing.
|
||||
return InvalidSqlSnafu {
|
||||
err_msg: format!(
|
||||
"flow '{}' with EVAL INTERVAL requires the batching scheduler, but source tables with ttl=instant are not supported under batching mode; use a TTL longer than the flush interval",
|
||||
flow_name
|
||||
),
|
||||
err_msg: INSTANT_TTL_FLOW_QUERY_ERROR.to_string(),
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
@@ -326,29 +322,9 @@ fn determine_flow_type_for_source_state(
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// The stateless streaming runtime accepts only a single source scan wrapped by
|
||||
/// projections and filters. Keep this check local to the operator: the flow
|
||||
/// validator is intentionally private to the flow crate.
|
||||
fn is_stateless_flow_plan(plan: &LogicalPlan) -> bool {
|
||||
let mut scans = 0;
|
||||
let mut supported_nodes = true;
|
||||
let result = plan.apply_with_subqueries(|node| {
|
||||
match node {
|
||||
LogicalPlan::TableScan(_) => scans += 1,
|
||||
LogicalPlan::Projection(_) | LogicalPlan::Filter(_) => {}
|
||||
LogicalPlan::Distinct(Distinct::All(_)) => {}
|
||||
_ => supported_nodes = false,
|
||||
}
|
||||
Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue)
|
||||
});
|
||||
const INSTANT_TTL_FLOW_QUERY_ERROR: &str = "instant-TTL source tables are no longer supported as flow sources; create the flow over a persisted source table with a TTL longer than the flush interval";
|
||||
|
||||
result.is_ok() && supported_nodes && scans == 1
|
||||
}
|
||||
|
||||
const INSTANT_TTL_FLOW_QUERY_ERROR: &str = "instant-TTL flow sources support only stateless projection/filter queries over one source; non-stateless queries require a persisted source";
|
||||
|
||||
const STATELESS_FLOW_QUERY_ERROR: &str =
|
||||
"flow streaming supports only stateless projection/filter queries over one source";
|
||||
const DISTINCT_ON_FLOW_QUERY_ERROR: &str = "DISTINCT ON is not supported in flow queries";
|
||||
|
||||
impl StatementExecutor {
|
||||
pub fn catalog_manager(&self) -> CatalogManagerRef {
|
||||
@@ -972,18 +948,17 @@ impl StatementExecutor {
|
||||
.context(error::ExecuteDdlSnafu)
|
||||
}
|
||||
|
||||
/// Determines the flow type from source-table state, schedule requirements,
|
||||
/// and SQL shape.
|
||||
/// Validates a flow definition against its source tables.
|
||||
///
|
||||
/// Aggregates and persisted-source DISTINCT use batching. Plain DISTINCT is request-local only
|
||||
/// for instant-TTL sources, where it retains the legacy streaming compatibility behavior.
|
||||
/// The batching scheduler is the only execution profile, so this no longer selects a mode.
|
||||
/// It keeps the source-table checks that must happen before the DDL procedure runs
|
||||
/// (missing source opt-in, instant-TTL rejection, `DISTINCT ON` rejection) and always
|
||||
/// reports [`FlowType::Batching`].
|
||||
async fn determine_flow_type(
|
||||
&self,
|
||||
expr: &CreateFlowExpr,
|
||||
query_ctx: QueryContextRef,
|
||||
) -> Result<FlowType> {
|
||||
let has_eval_interval = expr.eval_interval.is_some();
|
||||
|
||||
let mut has_missing_source_table = false;
|
||||
let mut has_instant_ttl_source_table = false;
|
||||
|
||||
@@ -1007,18 +982,13 @@ impl StatementExecutor {
|
||||
|
||||
if table.table_info().meta.options.ttl == Some(common_time::TimeToLive::Instant) {
|
||||
warn!(
|
||||
"Source table `{}` for flow `{}`'s ttl=instant, {}",
|
||||
"Source table `{}` for flow `{}`'s ttl=instant, rejecting flow because instant-TTL sources are not supported as flow sources",
|
||||
format_full_table_name(
|
||||
&src_table_name.catalog_name,
|
||||
&src_table_name.schema_name,
|
||||
&src_table_name.table_name
|
||||
),
|
||||
expr.flow_name,
|
||||
if has_eval_interval {
|
||||
"rejecting flow because EVAL INTERVAL requires the batching scheduler which does not support instant TTL"
|
||||
} else {
|
||||
"fallback to streaming mode"
|
||||
}
|
||||
);
|
||||
has_instant_ttl_source_table = true;
|
||||
}
|
||||
@@ -1029,17 +999,14 @@ impl StatementExecutor {
|
||||
&expr.flow_options,
|
||||
has_missing_source_table,
|
||||
has_instant_ttl_source_table,
|
||||
has_eval_interval,
|
||||
)? {
|
||||
return Ok(flow_type);
|
||||
}
|
||||
|
||||
// A flow with `EVAL INTERVAL` (and therefore possibly `EVAL OFFSET`)
|
||||
// always uses the batching scheduler: the fixed epoch-phase schedule is
|
||||
// only honored by the batching scheduler, regardless of the SQL shape.
|
||||
// Non-aggregate SQL is supported as an explicit full-query flow (the
|
||||
// batching engine requires a time-window expression or EVAL INTERVAL).
|
||||
if has_eval_interval {
|
||||
// A flow with `EVAL INTERVAL` (and therefore possibly `EVAL OFFSET`) already runs as an
|
||||
// explicit full-query batching flow, whatever its SQL shape, so there is no schedule-less
|
||||
// request-local shape left to reject here.
|
||||
if expr.eval_interval.is_some() {
|
||||
return Ok(FlowType::Batching);
|
||||
}
|
||||
|
||||
@@ -1064,27 +1031,11 @@ impl StatementExecutor {
|
||||
.map_err(BoxedError::new)
|
||||
.context(ExternalSnafu)?;
|
||||
if is_tql_query {
|
||||
if has_instant_ttl_source_table {
|
||||
return InvalidSqlSnafu {
|
||||
err_msg: INSTANT_TTL_FLOW_QUERY_ERROR.to_string(),
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
return Ok(FlowType::Batching);
|
||||
}
|
||||
|
||||
// Plan before selecting a mode. In particular, instant-TTL sources
|
||||
// must not bypass validation of the stateless streaming subset.
|
||||
let plan = match stmt {
|
||||
Statement::Tql(_) => {
|
||||
if has_instant_ttl_source_table {
|
||||
return InvalidSqlSnafu {
|
||||
err_msg: INSTANT_TTL_FLOW_QUERY_ERROR.to_string(),
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
return Ok(FlowType::Batching);
|
||||
}
|
||||
Statement::Tql(_) => return Ok(FlowType::Batching),
|
||||
_ => engine
|
||||
.planner()
|
||||
.plan(&QueryStatement::Sql(stmt.clone()), query_ctx)
|
||||
@@ -1093,74 +1044,39 @@ impl StatementExecutor {
|
||||
.context(ExternalSnafu)?,
|
||||
};
|
||||
|
||||
/// Visitor to classify aggregation and DISTINCT separately. Plain DISTINCT is request
|
||||
/// local only for instant-TTL sources; persisted-source DISTINCT keeps batching semantics.
|
||||
struct FindQueryShape {
|
||||
is_aggr: bool,
|
||||
is_distinct: bool,
|
||||
/// Visitor that only detects `DISTINCT ON`, which has no batching implementation.
|
||||
struct FindDistinctOn {
|
||||
has_distinct_on: bool,
|
||||
}
|
||||
|
||||
impl TreeNodeVisitor<'_> for FindQueryShape {
|
||||
impl TreeNodeVisitor<'_> for FindDistinctOn {
|
||||
type Node = LogicalPlan;
|
||||
fn f_down(
|
||||
&mut self,
|
||||
node: &Self::Node,
|
||||
) -> datafusion_common::Result<datafusion_common::tree_node::TreeNodeRecursion>
|
||||
{
|
||||
match node {
|
||||
LogicalPlan::Aggregate(_) => self.is_aggr = true,
|
||||
LogicalPlan::Distinct(Distinct::All(_)) => self.is_distinct = true,
|
||||
LogicalPlan::Distinct(Distinct::On(_)) => self.has_distinct_on = true,
|
||||
_ => (),
|
||||
if matches!(node, LogicalPlan::Distinct(Distinct::On(_))) {
|
||||
self.has_distinct_on = true;
|
||||
}
|
||||
Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue)
|
||||
}
|
||||
}
|
||||
|
||||
let mut query_shape = FindQueryShape {
|
||||
is_aggr: false,
|
||||
is_distinct: false,
|
||||
let mut query_shape = FindDistinctOn {
|
||||
has_distinct_on: false,
|
||||
};
|
||||
|
||||
plan.visit_with_subqueries(&mut query_shape)
|
||||
.context(BuildDfLogicalPlanSnafu)?;
|
||||
if query_shape.has_distinct_on {
|
||||
return InvalidSqlSnafu {
|
||||
err_msg: if has_instant_ttl_source_table {
|
||||
INSTANT_TTL_FLOW_QUERY_ERROR.to_string()
|
||||
} else {
|
||||
STATELESS_FLOW_QUERY_ERROR.to_string()
|
||||
},
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
if query_shape.is_aggr {
|
||||
return if has_instant_ttl_source_table {
|
||||
InvalidSqlSnafu {
|
||||
err_msg: INSTANT_TTL_FLOW_QUERY_ERROR.to_string(),
|
||||
}
|
||||
.fail()
|
||||
} else {
|
||||
Ok(FlowType::Batching)
|
||||
};
|
||||
}
|
||||
if query_shape.is_distinct && !has_instant_ttl_source_table {
|
||||
return Ok(FlowType::Batching);
|
||||
}
|
||||
|
||||
ensure!(
|
||||
is_stateless_flow_plan(&plan),
|
||||
!query_shape.has_distinct_on,
|
||||
InvalidSqlSnafu {
|
||||
err_msg: if has_instant_ttl_source_table {
|
||||
INSTANT_TTL_FLOW_QUERY_ERROR.to_string()
|
||||
} else {
|
||||
STATELESS_FLOW_QUERY_ERROR.to_string()
|
||||
},
|
||||
err_msg: DISTINCT_ON_FLOW_QUERY_ERROR.to_string(),
|
||||
}
|
||||
);
|
||||
Ok(FlowType::Streaming)
|
||||
|
||||
Ok(FlowType::Batching)
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all)]
|
||||
@@ -3151,7 +3067,6 @@ mod test {
|
||||
|
||||
#[cfg(feature = "enterprise")]
|
||||
use api::v1::meta::{ProcedureDetailResponse, ReconcileRequest, ReconcileResponse};
|
||||
use arrow::datatypes::{DataType as ArrowDataType, Field as ArrowField};
|
||||
#[cfg(feature = "enterprise")]
|
||||
use common_meta::cache_invalidator::{CacheInvalidator, CacheInvalidatorRef};
|
||||
#[cfg(feature = "enterprise")]
|
||||
@@ -3174,9 +3089,6 @@ mod test {
|
||||
use common_meta::rpc::procedure::{
|
||||
MigrateRegionRequest, MigrateRegionResponse, ProcedureStateResponse,
|
||||
};
|
||||
use datafusion::functions_aggregate::expr_fn::count;
|
||||
use datafusion::logical_expr::builder::LogicalTableSource;
|
||||
use datafusion::logical_expr::{LogicalPlanBuilder, col};
|
||||
use session::context::QueryContext;
|
||||
use sql::dialect::GreptimeDbDialect;
|
||||
use sql::parser::{ParseOptions, ParserContext};
|
||||
@@ -3598,77 +3510,6 @@ SELECT max(c1), min(c2) FROM schema_2.table_2;";
|
||||
);
|
||||
}
|
||||
|
||||
fn stateless_test_scan(name: &str) -> LogicalPlan {
|
||||
let schema = arrow::datatypes::Schema::new(vec![ArrowField::new(
|
||||
"value",
|
||||
ArrowDataType::Int32,
|
||||
true,
|
||||
)]);
|
||||
LogicalPlanBuilder::scan(
|
||||
name,
|
||||
Arc::new(LogicalTableSource::new(Arc::new(schema))),
|
||||
None,
|
||||
)
|
||||
.unwrap()
|
||||
.build()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_stateless_flow_plan_accepts_scan_projection_and_filter() {
|
||||
let scan = stateless_test_scan("source");
|
||||
assert!(is_stateless_flow_plan(&scan));
|
||||
|
||||
let projection = LogicalPlanBuilder::from(scan.clone())
|
||||
.project(vec![col("value")])
|
||||
.unwrap()
|
||||
.build()
|
||||
.unwrap();
|
||||
assert!(is_stateless_flow_plan(&projection));
|
||||
|
||||
let filter = LogicalPlanBuilder::from(projection)
|
||||
.filter(col("value").gt(datafusion_expr::lit(0)))
|
||||
.unwrap()
|
||||
.build()
|
||||
.unwrap();
|
||||
assert!(is_stateless_flow_plan(&filter));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_stateless_flow_plan_rejects_aggregate_and_multiple_scans() {
|
||||
let scan = stateless_test_scan("source");
|
||||
let aggregate = LogicalPlanBuilder::from(scan.clone())
|
||||
.aggregate(
|
||||
Vec::<datafusion_expr::Expr>::new(),
|
||||
vec![count(col("value"))],
|
||||
)
|
||||
.unwrap()
|
||||
.build()
|
||||
.unwrap();
|
||||
assert!(!is_stateless_flow_plan(&aggregate));
|
||||
|
||||
let distinct = LogicalPlanBuilder::from(scan.clone())
|
||||
.distinct()
|
||||
.unwrap()
|
||||
.build()
|
||||
.unwrap();
|
||||
assert!(is_stateless_flow_plan(&distinct));
|
||||
|
||||
let distinct_on_aggregate = LogicalPlanBuilder::from(aggregate)
|
||||
.distinct()
|
||||
.unwrap()
|
||||
.build()
|
||||
.unwrap();
|
||||
assert!(!is_stateless_flow_plan(&distinct_on_aggregate));
|
||||
|
||||
let multiple_scans = LogicalPlanBuilder::from(stateless_test_scan("left"))
|
||||
.cross_join(stateless_test_scan("right"))
|
||||
.unwrap()
|
||||
.build()
|
||||
.unwrap();
|
||||
assert!(!is_stateless_flow_plan(&multiple_scans));
|
||||
}
|
||||
|
||||
// --- Schedule option tests ---
|
||||
|
||||
#[test]
|
||||
@@ -3765,9 +3606,8 @@ SELECT max(c1), min(c2) FROM schema_2.table_2;";
|
||||
|
||||
#[test]
|
||||
fn test_determine_flow_type_for_source_state_missing_sources_require_opt_in() {
|
||||
let err =
|
||||
determine_flow_type_for_source_state("my_flow", &HashMap::new(), true, false, false)
|
||||
.unwrap_err();
|
||||
let err = determine_flow_type_for_source_state("my_flow", &HashMap::new(), true, false)
|
||||
.unwrap_err();
|
||||
|
||||
assert!(err.to_string().contains(
|
||||
"missing source tables for flow 'my_flow'; use WITH (defer_on_missing_source = true) to create a pending flow"
|
||||
@@ -3780,39 +3620,32 @@ SELECT max(c1), min(c2) FROM schema_2.table_2;";
|
||||
HashMap::from([(DEFER_ON_MISSING_SOURCE_KEY.to_string(), "true".to_string())]);
|
||||
|
||||
assert_eq!(
|
||||
determine_flow_type_for_source_state("my_flow", &flow_options, true, true, false)
|
||||
.unwrap(),
|
||||
determine_flow_type_for_source_state("my_flow", &flow_options, true, false).unwrap(),
|
||||
Some(FlowType::Batching)
|
||||
);
|
||||
let err = determine_flow_type_for_source_state("my_flow", &flow_options, true, true, true)
|
||||
.unwrap_err();
|
||||
assert!(err.to_string().contains(
|
||||
"flow 'my_flow' with EVAL INTERVAL requires the batching scheduler, but source tables with ttl=instant are not supported under batching mode"
|
||||
));
|
||||
// An instant-TTL source is rejected even when another source is missing.
|
||||
let err =
|
||||
determine_flow_type_for_source_state("my_flow", &flow_options, true, true).unwrap_err();
|
||||
assert!(err.to_string().contains(INSTANT_TTL_FLOW_QUERY_ERROR));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_determine_flow_type_for_source_state_existing_sources_require_plan() {
|
||||
assert_eq!(
|
||||
determine_flow_type_for_source_state("my_flow", &HashMap::new(), false, true, false)
|
||||
.unwrap(),
|
||||
determine_flow_type_for_source_state("my_flow", &HashMap::new(), false, false).unwrap(),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_determine_flow_type_for_source_state_instant_ttl_with_eval_interval_is_rejected() {
|
||||
// A flow with `EVAL INTERVAL` is forced onto the batching scheduler,
|
||||
// which cannot read instant-TTL source tables: reject instead of
|
||||
// silently falling back to streaming (where the schedule/offset would
|
||||
// be ignored).
|
||||
let err =
|
||||
determine_flow_type_for_source_state("my_flow", &HashMap::new(), false, true, true)
|
||||
.unwrap_err();
|
||||
fn test_determine_flow_type_for_source_state_instant_ttl_is_rejected() {
|
||||
// The batching scheduler is the only execution profile left and it
|
||||
// cannot read instant-TTL source tables, so reject them for every flow
|
||||
// instead of silently degrading.
|
||||
let err = determine_flow_type_for_source_state("my_flow", &HashMap::new(), false, true)
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
err.to_string().contains(
|
||||
"flow 'my_flow' with EVAL INTERVAL requires the batching scheduler, but source tables with ttl=instant are not supported under batching mode"
|
||||
),
|
||||
err.to_string().contains(INSTANT_TTL_FLOW_QUERY_ERROR),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ use common_procedure::{ProcedureInfo, ProcedureManagerRef};
|
||||
use common_query::request::QueryRequest;
|
||||
use common_stat::{ResourceStatImpl, ResourceStatRef};
|
||||
use datanode::region_server::RegionServer;
|
||||
use flow::FlowDualEngineRef;
|
||||
use flow::FlownodeEngineRef;
|
||||
use snafu::ResultExt;
|
||||
use store_api::storage::RegionId;
|
||||
use tokio::sync::RwLock;
|
||||
@@ -35,7 +35,7 @@ pub struct StandaloneInformationExtension {
|
||||
region_server: RegionServer,
|
||||
procedure_manager: ProcedureManagerRef,
|
||||
start_time_ms: u64,
|
||||
flow_engine: RwLock<Option<FlowDualEngineRef>>,
|
||||
flow_engine: RwLock<Option<FlownodeEngineRef>>,
|
||||
resource_stat: ResourceStatRef,
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ impl StandaloneInformationExtension {
|
||||
}
|
||||
|
||||
/// Set the flow engine for the standalone instance.
|
||||
pub async fn set_flow_engine(&self, flow_engine: FlowDualEngineRef) {
|
||||
pub async fn set_flow_engine(&self, flow_engine: FlownodeEngineRef) {
|
||||
let mut guard = self.flow_engine.write().await;
|
||||
*guard = Some(flow_engine);
|
||||
}
|
||||
|
||||
@@ -180,6 +180,7 @@ Affected Rows: 0
|
||||
|
||||
CREATE FLOW flow_comment_test
|
||||
SINK TO flow_sink_comment_test
|
||||
EVAL INTERVAL '1h'
|
||||
AS
|
||||
SELECT desc_str, ts FROM flow_source_comment_test;
|
||||
|
||||
@@ -197,6 +198,7 @@ SHOW CREATE FLOW flow_comment_test;
|
||||
+-------------------+------------------------------------------------------+
|
||||
| flow_comment_test | CREATE FLOW IF NOT EXISTS flow_comment_test |
|
||||
| | SINK TO public.flow_sink_comment_test |
|
||||
| | EVAL INTERVAL '3600 s' |
|
||||
| | COMMENT 'flow level description' |
|
||||
| | AS SELECT desc_str, ts FROM flow_source_comment_test |
|
||||
+-------------------+------------------------------------------------------+
|
||||
@@ -223,6 +225,7 @@ SHOW CREATE FLOW flow_comment_test;
|
||||
+-------------------+------------------------------------------------------+
|
||||
| flow_comment_test | CREATE FLOW IF NOT EXISTS flow_comment_test |
|
||||
| | SINK TO public.flow_sink_comment_test |
|
||||
| | EVAL INTERVAL '3600 s' |
|
||||
| | AS SELECT desc_str, ts FROM flow_source_comment_test |
|
||||
+-------------------+------------------------------------------------------+
|
||||
|
||||
|
||||
@@ -66,6 +66,7 @@ CREATE TABLE flow_sink_comment_test (
|
||||
|
||||
CREATE FLOW flow_comment_test
|
||||
SINK TO flow_sink_comment_test
|
||||
EVAL INTERVAL '1h'
|
||||
AS
|
||||
SELECT desc_str, ts FROM flow_source_comment_test;
|
||||
|
||||
|
||||
@@ -8,210 +8,44 @@ CREATE TABLE distinct_basic (
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
-- request-local DISTINCT is supported in streaming mode
|
||||
-- SQLNESS REPLACE id=\d+ id=REDACTED
|
||||
-- Instant-TTL source tables are no longer accepted as flow sources: a
|
||||
-- stateless projection/DISTINCT query is rejected like any other flow.
|
||||
CREATE FLOW test_distinct_basic SINK TO out_distinct_basic AS
|
||||
SELECT
|
||||
DISTINCT number as dis
|
||||
FROM
|
||||
distinct_basic;
|
||||
|
||||
Affected Rows: 0
|
||||
Error: 1004(InvalidArguments), Invalid SQL, error: instant-TTL source tables are no longer supported as flow sources; create the flow over a persisted source table with a TTL longer than the flush interval
|
||||
|
||||
-- instant-TTL sources reject non-stateless LIMIT plans
|
||||
CREATE FLOW test_limit_instant_rejected SINK TO out_limit_instant_rejected AS
|
||||
-- An aggregate query over an instant-TTL source is rejected as well.
|
||||
CREATE FLOW test_aggr_instant_rejected SINK TO out_aggr_instant_rejected AS
|
||||
SELECT
|
||||
number
|
||||
max(number) AS max_number
|
||||
FROM
|
||||
distinct_basic
|
||||
LIMIT 1;
|
||||
distinct_basic;
|
||||
|
||||
Error: 1004(InvalidArguments), Invalid SQL, error: instant-TTL flow sources support only stateless projection/filter queries over one source; non-stateless queries require a persisted source
|
||||
Error: 1004(InvalidArguments), Invalid SQL, error: instant-TTL source tables are no longer supported as flow sources; create the flow over a persisted source table with a TTL longer than the flush interval
|
||||
|
||||
-- flow_options should have a flow_type:streaming
|
||||
-- since source table's ttl=instant and DISTINCT is request-local
|
||||
SELECT flow_name, options FROM INFORMATION_SCHEMA.FLOWS;
|
||||
|
||||
+---------------------+---------------------------+
|
||||
| flow_name | options |
|
||||
+---------------------+---------------------------+
|
||||
| test_distinct_basic | {"flow_type":"streaming"} |
|
||||
+---------------------+---------------------------+
|
||||
|
||||
SHOW CREATE TABLE distinct_basic;
|
||||
|
||||
+----------------+-----------------------------------------------------------+
|
||||
| Table | Create Table |
|
||||
+----------------+-----------------------------------------------------------+
|
||||
| distinct_basic | CREATE TABLE IF NOT EXISTS "distinct_basic" ( |
|
||||
| | "number" INT NULL, |
|
||||
| | "ts" TIMESTAMP(3) NOT NULL DEFAULT current_timestamp(), |
|
||||
| | TIME INDEX ("ts"), |
|
||||
| | PRIMARY KEY ("number") |
|
||||
| | ) |
|
||||
| | |
|
||||
| | ENGINE=mito |
|
||||
| | WITH( |
|
||||
| | ttl = 'instant' |
|
||||
| | ) |
|
||||
+----------------+-----------------------------------------------------------+
|
||||
|
||||
-- SQLNESS REPLACE \d{4} REDACTED
|
||||
SHOW CREATE TABLE out_distinct_basic;
|
||||
|
||||
+--------------------+---------------------------------------------------+
|
||||
| Table | Create Table |
|
||||
+--------------------+---------------------------------------------------+
|
||||
| out_distinct_basic | CREATE TABLE IF NOT EXISTS "out_distinct_basic" ( |
|
||||
| | "dis" INT NULL, |
|
||||
| | "update_at" TIMESTAMP(3) NULL, |
|
||||
| | "__ts_placeholder" TIMESTAMP(3) NOT NULL, |
|
||||
| | TIME INDEX ("__ts_placeholder"), |
|
||||
| | PRIMARY KEY ("dis") |
|
||||
| | ) |
|
||||
| | |
|
||||
| | ENGINE=mito |
|
||||
| | WITH( |
|
||||
| | 'comment' = 'Sink table for flow flow-id=REDACTED' |
|
||||
| | ) |
|
||||
+--------------------+---------------------------------------------------+
|
||||
|
||||
-- SQLNESS SLEEP 3s
|
||||
INSERT INTO
|
||||
distinct_basic
|
||||
VALUES
|
||||
(20, "2021-07-01 00:00:00.200"),
|
||||
(20, "2021-07-01 00:00:00.200"),
|
||||
(22, "2021-07-01 00:00:00.600");
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
-- Mirror inserts reach the flownode asynchronously; wait before flushing.
|
||||
-- SQLNESS SLEEP 3s
|
||||
-- SQLNESS REPLACE (ADMIN\sFLUSH_FLOW\('\w+'\)\s+\|\n\+-+\+\n\|\s+)[0-9]+\s+\| $1 FLOW_FLUSHED |
|
||||
ADMIN FLUSH_FLOW('test_distinct_basic');
|
||||
|
||||
+-----------------------------------------+
|
||||
| ADMIN FLUSH_FLOW('test_distinct_basic') |
|
||||
+-----------------------------------------+
|
||||
| FLOW_FLUSHED |
|
||||
+-----------------------------------------+
|
||||
|
||||
SELECT
|
||||
dis
|
||||
FROM
|
||||
out_distinct_basic;
|
||||
|
||||
+-----+
|
||||
| dis |
|
||||
+-----+
|
||||
| 20 |
|
||||
| 22 |
|
||||
+-----+
|
||||
|
||||
SELECT number FROM distinct_basic;
|
||||
|
||||
+--------+
|
||||
| number |
|
||||
+--------+
|
||||
+--------+
|
||||
|
||||
ADMIN FLUSH_TABLE('distinct_basic');
|
||||
|
||||
+-------------------------------------+
|
||||
| ADMIN FLUSH_TABLE('distinct_basic') |
|
||||
+-------------------------------------+
|
||||
| 0 |
|
||||
+-------------------------------------+
|
||||
|
||||
-- Recover the persisted streaming DISTINCT flow, then replan its first write
|
||||
-- against an extended source schema without recreating the flow.
|
||||
-- SQLNESS ARG restart=true
|
||||
SELECT 1;
|
||||
|
||||
+----------+
|
||||
| Int64(1) |
|
||||
+----------+
|
||||
| 1 |
|
||||
+----------+
|
||||
|
||||
ALTER TABLE distinct_basic ADD COLUMN extra INT NULL;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
INSERT INTO
|
||||
distinct_basic (number, ts)
|
||||
VALUES
|
||||
(23, "2021-07-01 00:00:01.600"),
|
||||
(23, "2021-07-01 00:00:01.600");
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
-- Mirror inserts reach the flownode asynchronously; wait before flushing.
|
||||
-- SQLNESS SLEEP 3s
|
||||
-- SQLNESS REPLACE (ADMIN\sFLUSH_FLOW\('\w+'\)\s+\|\n\+-+\+\n\|\s+)[0-9]+\s+\| $1 FLOW_FLUSHED |
|
||||
ADMIN FLUSH_FLOW('test_distinct_basic');
|
||||
|
||||
+-----------------------------------------+
|
||||
| ADMIN FLUSH_FLOW('test_distinct_basic') |
|
||||
+-----------------------------------------+
|
||||
| FLOW_FLUSHED |
|
||||
+-----------------------------------------+
|
||||
|
||||
SELECT
|
||||
dis
|
||||
FROM
|
||||
out_distinct_basic;
|
||||
|
||||
+-----+
|
||||
| dis |
|
||||
+-----+
|
||||
| 20 |
|
||||
| 22 |
|
||||
| 23 |
|
||||
+-----+
|
||||
|
||||
SELECT number FROM distinct_basic;
|
||||
|
||||
+--------+
|
||||
| number |
|
||||
+--------+
|
||||
+--------+
|
||||
|
||||
DROP FLOW test_distinct_basic;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
DROP TABLE distinct_basic;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
DROP TABLE out_distinct_basic;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
-- test ttl = instant with EVAL INTERVAL must be rejected
|
||||
-- since the batching scheduler cannot read instant-TTL source tables and the
|
||||
-- streaming engine cannot honor the schedule
|
||||
CREATE TABLE distinct_basic (
|
||||
"number" INT,
|
||||
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY(number),
|
||||
TIME INDEX(ts)
|
||||
)WITH ('ttl' = 'instant');
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
-- SQLNESS REPLACE id=\d+ id=REDACTED
|
||||
CREATE FLOW test_distinct_basic SINK TO out_distinct_basic EVAL INTERVAL '1m' AS
|
||||
-- EVAL INTERVAL does not bypass the rejection: the batching scheduler is the
|
||||
-- only execution profile left and it cannot read instant-TTL source tables.
|
||||
CREATE FLOW test_scheduled_instant_rejected
|
||||
SINK TO out_scheduled_instant_rejected
|
||||
EVAL INTERVAL '1m'
|
||||
AS
|
||||
SELECT
|
||||
DISTINCT number as dis
|
||||
FROM
|
||||
distinct_basic;
|
||||
|
||||
Error: 1004(InvalidArguments), Invalid SQL, error: flow 'test_distinct_basic' with EVAL INTERVAL requires the batching scheduler, but source tables with ttl=instant are not supported under batching mode; use a TTL longer than the flush interval
|
||||
Error: 1004(InvalidArguments), Invalid SQL, error: instant-TTL source tables are no longer supported as flow sources; create the flow over a persisted source table with a TTL longer than the flush interval
|
||||
|
||||
SELECT count(*) FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name = 'test_distinct_basic';
|
||||
SELECT count(*) FROM INFORMATION_SCHEMA.FLOWS
|
||||
WHERE flow_name IN (
|
||||
'test_distinct_basic',
|
||||
'test_aggr_instant_rejected',
|
||||
'test_scheduled_instant_rejected'
|
||||
);
|
||||
|
||||
+----------+
|
||||
| count(*) |
|
||||
@@ -223,7 +57,7 @@ DROP TABLE distinct_basic;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
-- test ttl = 5s (DISTINCT remains batching for persisted sources)
|
||||
-- test ttl = 5s (persisted sources use the batching scheduler)
|
||||
CREATE TABLE distinct_basic (
|
||||
"number" INT,
|
||||
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
@@ -233,8 +67,8 @@ CREATE TABLE distinct_basic (
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
-- Without a schedule, persisted DISTINCT must reach batching validation,
|
||||
-- not silently become request-local streaming.
|
||||
-- Without a schedule, a window-less flow must reach batching validation
|
||||
-- instead of silently becoming a request-local query.
|
||||
CREATE FLOW test_distinct_persisted_unscheduled
|
||||
SINK TO out_distinct_persisted_unscheduled AS
|
||||
SELECT DISTINCT number AS dis FROM distinct_basic;
|
||||
@@ -258,7 +92,6 @@ FROM
|
||||
Affected Rows: 0
|
||||
|
||||
-- flow_options should have a flow_type:batching
|
||||
-- persisted-source DISTINCT retains batching semantics
|
||||
SELECT flow_name, options FROM INFORMATION_SCHEMA.FLOWS;
|
||||
|
||||
+---------------------+--------------------------+
|
||||
@@ -414,110 +247,3 @@ DROP TABLE out_distinct_basic;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
-- Streaming DISTINCT auto-sink retains all 1000 output tuples.
|
||||
CREATE TABLE distinct_auto_sink (
|
||||
v INT,
|
||||
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP TIME INDEX
|
||||
) WITH ('ttl' = 'instant');
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
CREATE FLOW test_distinct_auto_sink SINK TO out_distinct_auto_sink AS
|
||||
SELECT DISTINCT v FROM distinct_auto_sink;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
INSERT INTO distinct_auto_sink (v)
|
||||
SELECT number FROM numbers LIMIT 1000;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
-- Mirror inserts reach the flownode asynchronously; wait before flushing.
|
||||
-- SQLNESS SLEEP 3s
|
||||
-- SQLNESS REPLACE (ADMIN\sFLUSH_FLOW\('\w+'\)\s+\|\n\+-+\+\n\|\s+)[0-9]+\s+\| $1 FLOW_FLUSHED |
|
||||
ADMIN FLUSH_FLOW('test_distinct_auto_sink');
|
||||
|
||||
+---------------------------------------------+
|
||||
| ADMIN FLUSH_FLOW('test_distinct_auto_sink') |
|
||||
+---------------------------------------------+
|
||||
| FLOW_FLUSHED |
|
||||
+---------------------------------------------+
|
||||
|
||||
SELECT count(*) AS rows, count(DISTINCT v) AS distinct_values, min(v) AS min_v, max(v) AS max_v
|
||||
FROM out_distinct_auto_sink;
|
||||
|
||||
+------+-----------------+-------+-------+
|
||||
| rows | distinct_values | min_v | max_v |
|
||||
+------+-----------------+-------+-------+
|
||||
| 1000 | 1000 | 0 | 999 |
|
||||
+------+-----------------+-------+-------+
|
||||
|
||||
DROP FLOW test_distinct_auto_sink;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
DROP TABLE distinct_auto_sink;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
DROP TABLE out_distinct_auto_sink;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
CREATE TABLE distinct_auto_sink_pk (
|
||||
v INT,
|
||||
k INT,
|
||||
extra_value INT,
|
||||
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP TIME INDEX,
|
||||
PRIMARY KEY (v, k)
|
||||
) WITH ('ttl' = 'instant');
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
CREATE FLOW test_distinct_auto_sink_pk SINK TO out_distinct_auto_sink_pk AS
|
||||
SELECT DISTINCT v, extra_value FROM distinct_auto_sink_pk;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
INSERT INTO distinct_auto_sink_pk (v, k, extra_value)
|
||||
SELECT number % 10 AS v, number AS k, number AS extra_value FROM numbers LIMIT 1000;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
-- Mirror inserts reach the flownode asynchronously; wait before flushing.
|
||||
-- SQLNESS SLEEP 3s
|
||||
-- SQLNESS REPLACE (ADMIN\sFLUSH_FLOW\('\w+'\)\s+\|\n\+-+\+\n\|\s+)[0-9]+\s+\| $1 FLOW_FLUSHED |
|
||||
ADMIN FLUSH_FLOW('test_distinct_auto_sink_pk');
|
||||
|
||||
+------------------------------------------------+
|
||||
| ADMIN FLUSH_FLOW('test_distinct_auto_sink_pk') |
|
||||
+------------------------------------------------+
|
||||
| FLOW_FLUSHED |
|
||||
+------------------------------------------------+
|
||||
|
||||
SELECT
|
||||
count(*) AS rows,
|
||||
count(DISTINCT extra_value) AS distinct_values,
|
||||
min(extra_value) AS min_value,
|
||||
max(extra_value) AS max_value,
|
||||
sum(CASE WHEN v = extra_value % 10 THEN 0 ELSE 1 END) AS mismatched_keys
|
||||
FROM out_distinct_auto_sink_pk;
|
||||
|
||||
+------+-----------------+-----------+-----------+-----------------+
|
||||
| rows | distinct_values | min_value | max_value | mismatched_keys |
|
||||
+------+-----------------+-----------+-----------+-----------------+
|
||||
| 1000 | 1000 | 0 | 999 | 0 |
|
||||
+------+-----------------+-----------+-----------+-----------------+
|
||||
|
||||
DROP FLOW test_distinct_auto_sink_pk;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
DROP TABLE distinct_auto_sink_pk;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
DROP TABLE out_distinct_auto_sink_pk;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
|
||||
@@ -6,104 +6,42 @@ CREATE TABLE distinct_basic (
|
||||
TIME INDEX(ts)
|
||||
)WITH ('ttl' = 'instant');
|
||||
|
||||
-- request-local DISTINCT is supported in streaming mode
|
||||
-- SQLNESS REPLACE id=\d+ id=REDACTED
|
||||
-- Instant-TTL source tables are no longer accepted as flow sources: a
|
||||
-- stateless projection/DISTINCT query is rejected like any other flow.
|
||||
CREATE FLOW test_distinct_basic SINK TO out_distinct_basic AS
|
||||
SELECT
|
||||
DISTINCT number as dis
|
||||
FROM
|
||||
distinct_basic;
|
||||
|
||||
-- instant-TTL sources reject non-stateless LIMIT plans
|
||||
CREATE FLOW test_limit_instant_rejected SINK TO out_limit_instant_rejected AS
|
||||
-- An aggregate query over an instant-TTL source is rejected as well.
|
||||
CREATE FLOW test_aggr_instant_rejected SINK TO out_aggr_instant_rejected AS
|
||||
SELECT
|
||||
number
|
||||
max(number) AS max_number
|
||||
FROM
|
||||
distinct_basic
|
||||
LIMIT 1;
|
||||
distinct_basic;
|
||||
|
||||
-- flow_options should have a flow_type:streaming
|
||||
-- since source table's ttl=instant and DISTINCT is request-local
|
||||
SELECT flow_name, options FROM INFORMATION_SCHEMA.FLOWS;
|
||||
|
||||
SHOW CREATE TABLE distinct_basic;
|
||||
|
||||
-- SQLNESS REPLACE \d{4} REDACTED
|
||||
SHOW CREATE TABLE out_distinct_basic;
|
||||
|
||||
-- SQLNESS SLEEP 3s
|
||||
INSERT INTO
|
||||
distinct_basic
|
||||
VALUES
|
||||
(20, "2021-07-01 00:00:00.200"),
|
||||
(20, "2021-07-01 00:00:00.200"),
|
||||
(22, "2021-07-01 00:00:00.600");
|
||||
|
||||
-- Mirror inserts reach the flownode asynchronously; wait before flushing.
|
||||
-- SQLNESS SLEEP 3s
|
||||
-- SQLNESS REPLACE (ADMIN\sFLUSH_FLOW\('\w+'\)\s+\|\n\+-+\+\n\|\s+)[0-9]+\s+\| $1 FLOW_FLUSHED |
|
||||
ADMIN FLUSH_FLOW('test_distinct_basic');
|
||||
|
||||
SELECT
|
||||
dis
|
||||
FROM
|
||||
out_distinct_basic;
|
||||
|
||||
SELECT number FROM distinct_basic;
|
||||
|
||||
ADMIN FLUSH_TABLE('distinct_basic');
|
||||
|
||||
-- Recover the persisted streaming DISTINCT flow, then replan its first write
|
||||
-- against an extended source schema without recreating the flow.
|
||||
-- SQLNESS ARG restart=true
|
||||
SELECT 1;
|
||||
|
||||
ALTER TABLE distinct_basic ADD COLUMN extra INT NULL;
|
||||
|
||||
INSERT INTO
|
||||
distinct_basic (number, ts)
|
||||
VALUES
|
||||
(23, "2021-07-01 00:00:01.600"),
|
||||
(23, "2021-07-01 00:00:01.600");
|
||||
|
||||
-- Mirror inserts reach the flownode asynchronously; wait before flushing.
|
||||
-- SQLNESS SLEEP 3s
|
||||
-- SQLNESS REPLACE (ADMIN\sFLUSH_FLOW\('\w+'\)\s+\|\n\+-+\+\n\|\s+)[0-9]+\s+\| $1 FLOW_FLUSHED |
|
||||
ADMIN FLUSH_FLOW('test_distinct_basic');
|
||||
|
||||
SELECT
|
||||
dis
|
||||
FROM
|
||||
out_distinct_basic;
|
||||
|
||||
SELECT number FROM distinct_basic;
|
||||
|
||||
DROP FLOW test_distinct_basic;
|
||||
DROP TABLE distinct_basic;
|
||||
DROP TABLE out_distinct_basic;
|
||||
|
||||
-- test ttl = instant with EVAL INTERVAL must be rejected
|
||||
-- since the batching scheduler cannot read instant-TTL source tables and the
|
||||
-- streaming engine cannot honor the schedule
|
||||
CREATE TABLE distinct_basic (
|
||||
"number" INT,
|
||||
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY(number),
|
||||
TIME INDEX(ts)
|
||||
)WITH ('ttl' = 'instant');
|
||||
|
||||
-- SQLNESS REPLACE id=\d+ id=REDACTED
|
||||
CREATE FLOW test_distinct_basic SINK TO out_distinct_basic EVAL INTERVAL '1m' AS
|
||||
-- EVAL INTERVAL does not bypass the rejection: the batching scheduler is the
|
||||
-- only execution profile left and it cannot read instant-TTL source tables.
|
||||
CREATE FLOW test_scheduled_instant_rejected
|
||||
SINK TO out_scheduled_instant_rejected
|
||||
EVAL INTERVAL '1m'
|
||||
AS
|
||||
SELECT
|
||||
DISTINCT number as dis
|
||||
FROM
|
||||
distinct_basic;
|
||||
|
||||
SELECT count(*) FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name = 'test_distinct_basic';
|
||||
SELECT count(*) FROM INFORMATION_SCHEMA.FLOWS
|
||||
WHERE flow_name IN (
|
||||
'test_distinct_basic',
|
||||
'test_aggr_instant_rejected',
|
||||
'test_scheduled_instant_rejected'
|
||||
);
|
||||
|
||||
DROP TABLE distinct_basic;
|
||||
|
||||
-- test ttl = 5s (DISTINCT remains batching for persisted sources)
|
||||
-- test ttl = 5s (persisted sources use the batching scheduler)
|
||||
CREATE TABLE distinct_basic (
|
||||
"number" INT,
|
||||
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
@@ -111,8 +49,8 @@ CREATE TABLE distinct_basic (
|
||||
TIME INDEX(ts)
|
||||
)WITH ('ttl' = '5s');
|
||||
|
||||
-- Without a schedule, persisted DISTINCT must reach batching validation,
|
||||
-- not silently become request-local streaming.
|
||||
-- Without a schedule, a window-less flow must reach batching validation
|
||||
-- instead of silently becoming a request-local query.
|
||||
CREATE FLOW test_distinct_persisted_unscheduled
|
||||
SINK TO out_distinct_persisted_unscheduled AS
|
||||
SELECT DISTINCT number AS dis FROM distinct_basic;
|
||||
@@ -127,7 +65,6 @@ FROM
|
||||
distinct_basic;
|
||||
|
||||
-- flow_options should have a flow_type:batching
|
||||
-- persisted-source DISTINCT retains batching semantics
|
||||
SELECT flow_name, options FROM INFORMATION_SCHEMA.FLOWS;
|
||||
|
||||
-- SQLNESS ARG restart=true
|
||||
@@ -179,58 +116,3 @@ SELECT number FROM distinct_basic;
|
||||
DROP FLOW test_distinct_basic;
|
||||
DROP TABLE distinct_basic;
|
||||
DROP TABLE out_distinct_basic;
|
||||
|
||||
-- Streaming DISTINCT auto-sink retains all 1000 output tuples.
|
||||
CREATE TABLE distinct_auto_sink (
|
||||
v INT,
|
||||
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP TIME INDEX
|
||||
) WITH ('ttl' = 'instant');
|
||||
|
||||
CREATE FLOW test_distinct_auto_sink SINK TO out_distinct_auto_sink AS
|
||||
SELECT DISTINCT v FROM distinct_auto_sink;
|
||||
|
||||
INSERT INTO distinct_auto_sink (v)
|
||||
SELECT number FROM numbers LIMIT 1000;
|
||||
|
||||
-- Mirror inserts reach the flownode asynchronously; wait before flushing.
|
||||
-- SQLNESS SLEEP 3s
|
||||
-- SQLNESS REPLACE (ADMIN\sFLUSH_FLOW\('\w+'\)\s+\|\n\+-+\+\n\|\s+)[0-9]+\s+\| $1 FLOW_FLUSHED |
|
||||
ADMIN FLUSH_FLOW('test_distinct_auto_sink');
|
||||
|
||||
SELECT count(*) AS rows, count(DISTINCT v) AS distinct_values, min(v) AS min_v, max(v) AS max_v
|
||||
FROM out_distinct_auto_sink;
|
||||
|
||||
DROP FLOW test_distinct_auto_sink;
|
||||
DROP TABLE distinct_auto_sink;
|
||||
DROP TABLE out_distinct_auto_sink;
|
||||
|
||||
CREATE TABLE distinct_auto_sink_pk (
|
||||
v INT,
|
||||
k INT,
|
||||
extra_value INT,
|
||||
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP TIME INDEX,
|
||||
PRIMARY KEY (v, k)
|
||||
) WITH ('ttl' = 'instant');
|
||||
|
||||
CREATE FLOW test_distinct_auto_sink_pk SINK TO out_distinct_auto_sink_pk AS
|
||||
SELECT DISTINCT v, extra_value FROM distinct_auto_sink_pk;
|
||||
|
||||
INSERT INTO distinct_auto_sink_pk (v, k, extra_value)
|
||||
SELECT number % 10 AS v, number AS k, number AS extra_value FROM numbers LIMIT 1000;
|
||||
|
||||
-- Mirror inserts reach the flownode asynchronously; wait before flushing.
|
||||
-- SQLNESS SLEEP 3s
|
||||
-- SQLNESS REPLACE (ADMIN\sFLUSH_FLOW\('\w+'\)\s+\|\n\+-+\+\n\|\s+)[0-9]+\s+\| $1 FLOW_FLUSHED |
|
||||
ADMIN FLUSH_FLOW('test_distinct_auto_sink_pk');
|
||||
|
||||
SELECT
|
||||
count(*) AS rows,
|
||||
count(DISTINCT extra_value) AS distinct_values,
|
||||
min(extra_value) AS min_value,
|
||||
max(extra_value) AS max_value,
|
||||
sum(CASE WHEN v = extra_value % 10 THEN 0 ELSE 1 END) AS mismatched_keys
|
||||
FROM out_distinct_auto_sink_pk;
|
||||
|
||||
DROP FLOW test_distinct_auto_sink_pk;
|
||||
DROP TABLE distinct_auto_sink_pk;
|
||||
DROP TABLE out_distinct_auto_sink_pk;
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
-- The streaming runtime is gone, so the batching scheduler is the only execution
|
||||
-- profile left. A flow whose SQL has no time window is exactly the shape the
|
||||
-- streaming executor used to handle: it is now rejected, and the supported
|
||||
-- migration is to recreate the flow with an explicit `EVAL INTERVAL`.
|
||||
CREATE TABLE legacy_flow_src (
|
||||
host STRING,
|
||||
val DOUBLE,
|
||||
ts TIMESTAMP TIME INDEX
|
||||
);
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
CREATE TABLE legacy_flow_sink (
|
||||
host STRING,
|
||||
val DOUBLE,
|
||||
ts TIMESTAMP TIME INDEX
|
||||
);
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
CREATE FLOW legacy_flow SINK TO legacy_flow_sink AS
|
||||
SELECT host, val, ts FROM legacy_flow_src;
|
||||
|
||||
Error: 3001(EngineExecuteQuery), Invalid query: SQL batching flow without a time-window expression must specify EVAL INTERVAL to run as an explicit full-query flow
|
||||
|
||||
SELECT count(*) FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name = 'legacy_flow';
|
||||
|
||||
+----------+
|
||||
| count(*) |
|
||||
+----------+
|
||||
| 0 |
|
||||
+----------+
|
||||
|
||||
-- Recreating the flow with a schedule is the supported migration.
|
||||
CREATE FLOW legacy_flow SINK TO legacy_flow_sink EVAL INTERVAL '1h' AS
|
||||
SELECT host, val, ts FROM legacy_flow_src;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
-- The persisted option is still `batching`, so the metadata shape is unchanged.
|
||||
SELECT flow_name, options FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name = 'legacy_flow';
|
||||
|
||||
+-------------+--------------------------+
|
||||
| flow_name | options |
|
||||
+-------------+--------------------------+
|
||||
| legacy_flow | {"flow_type":"batching"} |
|
||||
+-------------+--------------------------+
|
||||
|
||||
INSERT INTO legacy_flow_src VALUES ('host_a', 1.0, '2024-01-01 00:00:00');
|
||||
|
||||
Affected Rows: 1
|
||||
|
||||
-- Mirror inserts reach the flownode asynchronously; wait before flushing.
|
||||
-- SQLNESS SLEEP 3s
|
||||
-- SQLNESS REPLACE (ADMIN\sFLUSH_FLOW\('\w+'\)\s+\|\n\+-+\+\n\|\s+)[0-9]+\s+\| $1 FLOW_FLUSHED |
|
||||
ADMIN FLUSH_FLOW('legacy_flow');
|
||||
|
||||
+---------------------------------+
|
||||
| ADMIN FLUSH_FLOW('legacy_flow') |
|
||||
+---------------------------------+
|
||||
| FLOW_FLUSHED |
|
||||
+---------------------------------+
|
||||
|
||||
SELECT host, val, ts FROM legacy_flow_sink ORDER BY ts;
|
||||
|
||||
+--------+-----+---------------------+
|
||||
| host | val | ts |
|
||||
+--------+-----+---------------------+
|
||||
| host_a | 1.0 | 2024-01-01T00:00:00 |
|
||||
+--------+-----+---------------------+
|
||||
|
||||
DROP FLOW legacy_flow;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
SELECT count(*) FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name = 'legacy_flow';
|
||||
|
||||
+----------+
|
||||
| count(*) |
|
||||
+----------+
|
||||
| 0 |
|
||||
+----------+
|
||||
|
||||
DROP TABLE legacy_flow_src;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
DROP TABLE legacy_flow_sink;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
-- The streaming runtime is gone, so the batching scheduler is the only execution
|
||||
-- profile left. A flow whose SQL has no time window is exactly the shape the
|
||||
-- streaming executor used to handle: it is now rejected, and the supported
|
||||
-- migration is to recreate the flow with an explicit `EVAL INTERVAL`.
|
||||
CREATE TABLE legacy_flow_src (
|
||||
host STRING,
|
||||
val DOUBLE,
|
||||
ts TIMESTAMP TIME INDEX
|
||||
);
|
||||
|
||||
CREATE TABLE legacy_flow_sink (
|
||||
host STRING,
|
||||
val DOUBLE,
|
||||
ts TIMESTAMP TIME INDEX
|
||||
);
|
||||
|
||||
CREATE FLOW legacy_flow SINK TO legacy_flow_sink AS
|
||||
SELECT host, val, ts FROM legacy_flow_src;
|
||||
|
||||
SELECT count(*) FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name = 'legacy_flow';
|
||||
|
||||
-- Recreating the flow with a schedule is the supported migration.
|
||||
CREATE FLOW legacy_flow SINK TO legacy_flow_sink EVAL INTERVAL '1h' AS
|
||||
SELECT host, val, ts FROM legacy_flow_src;
|
||||
|
||||
-- The persisted option is still `batching`, so the metadata shape is unchanged.
|
||||
SELECT flow_name, options FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name = 'legacy_flow';
|
||||
|
||||
INSERT INTO legacy_flow_src VALUES ('host_a', 1.0, '2024-01-01 00:00:00');
|
||||
|
||||
-- Mirror inserts reach the flownode asynchronously; wait before flushing.
|
||||
-- SQLNESS SLEEP 3s
|
||||
-- SQLNESS REPLACE (ADMIN\sFLUSH_FLOW\('\w+'\)\s+\|\n\+-+\+\n\|\s+)[0-9]+\s+\| $1 FLOW_FLUSHED |
|
||||
ADMIN FLUSH_FLOW('legacy_flow');
|
||||
|
||||
SELECT host, val, ts FROM legacy_flow_sink ORDER BY ts;
|
||||
|
||||
DROP FLOW legacy_flow;
|
||||
|
||||
SELECT count(*) FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name = 'legacy_flow';
|
||||
|
||||
DROP TABLE legacy_flow_src;
|
||||
|
||||
DROP TABLE legacy_flow_sink;
|
||||
@@ -12,8 +12,11 @@ CREATE TABLE sink (
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
-- A projection/filter flow has no time window, so it runs as an explicit
|
||||
-- full-query flow on the batching scheduler and needs a schedule.
|
||||
CREATE FLOW filter_out
|
||||
SINK TO sink
|
||||
EVAL INTERVAL '1h'
|
||||
AS
|
||||
SELECT desc_str, ts FROM base
|
||||
WHERE desc_str IN ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j');
|
||||
@@ -22,11 +25,11 @@ Affected Rows: 0
|
||||
|
||||
SELECT options FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name = 'filter_out';
|
||||
|
||||
+---------------------------+
|
||||
| options |
|
||||
+---------------------------+
|
||||
| {"flow_type":"streaming"} |
|
||||
+---------------------------+
|
||||
+--------------------------+
|
||||
| options |
|
||||
+--------------------------+
|
||||
| {"flow_type":"batching"} |
|
||||
+--------------------------+
|
||||
|
||||
INSERT INTO base VALUES
|
||||
('a', '2023-01-01 00:00:00'),
|
||||
@@ -83,6 +86,7 @@ Affected Rows: 0
|
||||
|
||||
CREATE FLOW filter_out
|
||||
SINK TO sink
|
||||
EVAL INTERVAL '1h'
|
||||
AS
|
||||
SELECT desc_str, ts FROM base
|
||||
WHERE desc_str NOT IN ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j');
|
||||
@@ -91,11 +95,11 @@ Affected Rows: 0
|
||||
|
||||
SELECT options FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name = 'filter_out';
|
||||
|
||||
+---------------------------+
|
||||
| options |
|
||||
+---------------------------+
|
||||
| {"flow_type":"streaming"} |
|
||||
+---------------------------+
|
||||
+--------------------------+
|
||||
| options |
|
||||
+--------------------------+
|
||||
| {"flow_type":"batching"} |
|
||||
+--------------------------+
|
||||
|
||||
INSERT INTO base VALUES
|
||||
('a', '2023-01-01 00:00:00'),
|
||||
|
||||
@@ -8,8 +8,11 @@ CREATE TABLE sink (
|
||||
ts TIMESTAMP TIME INDEX
|
||||
);
|
||||
|
||||
-- A projection/filter flow has no time window, so it runs as an explicit
|
||||
-- full-query flow on the batching scheduler and needs a schedule.
|
||||
CREATE FLOW filter_out
|
||||
SINK TO sink
|
||||
EVAL INTERVAL '1h'
|
||||
AS
|
||||
SELECT desc_str, ts FROM base
|
||||
WHERE desc_str IN ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j');
|
||||
@@ -44,6 +47,7 @@ CREATE TABLE sink (
|
||||
|
||||
CREATE FLOW filter_out
|
||||
SINK TO sink
|
||||
EVAL INTERVAL '1h'
|
||||
AS
|
||||
SELECT desc_str, ts FROM base
|
||||
WHERE desc_str NOT IN ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j');
|
||||
|
||||
@@ -242,7 +242,7 @@ CREATE TABLE out_nullable_pk (
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
CREATE FLOW calc_nullable_pk SINK TO out_nullable_pk AS
|
||||
CREATE FLOW calc_nullable_pk SINK TO out_nullable_pk EVAL INTERVAL '1h' AS
|
||||
SELECT
|
||||
pid,
|
||||
client,
|
||||
|
||||
@@ -149,7 +149,7 @@ CREATE TABLE out_nullable_pk (
|
||||
PRIMARY KEY (pid, client)
|
||||
);
|
||||
|
||||
CREATE FLOW calc_nullable_pk SINK TO out_nullable_pk AS
|
||||
CREATE FLOW calc_nullable_pk SINK TO out_nullable_pk EVAL INTERVAL '1h' AS
|
||||
SELECT
|
||||
pid,
|
||||
client,
|
||||
|
||||
@@ -29,7 +29,7 @@ SHOW FLOWS LIKE 'filter_numbers_show';
|
||||
+-------+
|
||||
+-------+
|
||||
|
||||
CREATE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number FROM numbers_input_show where number > 10;
|
||||
CREATE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number FROM numbers_input_show where number > 10;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
@@ -40,6 +40,7 @@ SHOW CREATE FLOW filter_numbers_show;
|
||||
+---------------------+------------------------------------------------------------+
|
||||
| filter_numbers_show | CREATE FLOW IF NOT EXISTS filter_numbers_show |
|
||||
| | SINK TO public.out_num_cnt_show |
|
||||
| | EVAL INTERVAL '3600 s' |
|
||||
| | AS SELECT number FROM numbers_input_show WHERE number > 10 |
|
||||
+---------------------+------------------------------------------------------------+
|
||||
|
||||
@@ -50,6 +51,7 @@ SELECT flow_name, table_catalog, flow_definition, source_table_names FROM INFORM
|
||||
+---------------------+---------------+------------------------------------------------------------+------------------------------------+
|
||||
| filter_numbers_show | greptime | CREATE FLOW IF NOT EXISTS filter_numbers_show | greptime.public.numbers_input_show |
|
||||
| | | SINK TO public.out_num_cnt_show | |
|
||||
| | | EVAL INTERVAL '3600 s' | |
|
||||
| | | AS SELECT number FROM numbers_input_show WHERE number > 10 | |
|
||||
+---------------------+---------------+------------------------------------------------------------+------------------------------------+
|
||||
|
||||
@@ -81,7 +83,7 @@ SHOW FLOWS LIKE 'filter_numbers_show';
|
||||
|
||||
-- also test `CREATE OR REPLACE` and `IF NOT EXISTS`
|
||||
-- (flow exists, replace, if not exists)=(false, false, false)
|
||||
CREATE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number, ts FROM numbers_input_show where number > 10;
|
||||
CREATE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number, ts FROM numbers_input_show where number > 10;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
@@ -92,12 +94,13 @@ SELECT flow_name, table_catalog, flow_definition, source_table_names FROM INFORM
|
||||
+---------------------+---------------+----------------------------------------------------------------+------------------------------------+
|
||||
| filter_numbers_show | greptime | CREATE FLOW IF NOT EXISTS filter_numbers_show | greptime.public.numbers_input_show |
|
||||
| | | SINK TO public.out_num_cnt_show | |
|
||||
| | | EVAL INTERVAL '3600 s' | |
|
||||
| | | AS SELECT number, ts FROM numbers_input_show WHERE number > 10 | |
|
||||
+---------------------+---------------+----------------------------------------------------------------+------------------------------------+
|
||||
|
||||
-- this one should error out
|
||||
-- (flow exists, replace, if not exists)=(true, false, false)
|
||||
CREATE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number, ts FROM numbers_input_show where number > 15;
|
||||
CREATE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number, ts FROM numbers_input_show where number > 15;
|
||||
|
||||
Error: 8000(FlowAlreadyExists), Flow already exists: greptime.filter_numbers_show
|
||||
|
||||
@@ -108,6 +111,7 @@ SELECT flow_name, table_catalog, flow_definition, source_table_names FROM INFORM
|
||||
+---------------------+---------------+----------------------------------------------------------------+------------------------------------+
|
||||
| filter_numbers_show | greptime | CREATE FLOW IF NOT EXISTS filter_numbers_show | greptime.public.numbers_input_show |
|
||||
| | | SINK TO public.out_num_cnt_show | |
|
||||
| | | EVAL INTERVAL '3600 s' | |
|
||||
| | | AS SELECT number, ts FROM numbers_input_show WHERE number > 10 | |
|
||||
+---------------------+---------------+----------------------------------------------------------------+------------------------------------+
|
||||
|
||||
@@ -138,7 +142,7 @@ SELECT number, ts FROM out_num_cnt_show;
|
||||
|
||||
-- after this one, the flow SHOULD NOT be replaced
|
||||
-- (flow exists, replace, if not exists)=(true, false, true)
|
||||
CREATE FLOW IF NOT EXISTS filter_numbers_show SINK TO out_num_cnt_show AS SELECT number, ts FROM numbers_input_show where number > 5;
|
||||
CREATE FLOW IF NOT EXISTS filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number, ts FROM numbers_input_show where number > 5;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
@@ -149,6 +153,7 @@ SELECT flow_name, table_catalog, flow_definition, source_table_names FROM INFORM
|
||||
+---------------------+---------------+----------------------------------------------------------------+------------------------------------+
|
||||
| filter_numbers_show | greptime | CREATE FLOW IF NOT EXISTS filter_numbers_show | greptime.public.numbers_input_show |
|
||||
| | | SINK TO public.out_num_cnt_show | |
|
||||
| | | EVAL INTERVAL '3600 s' | |
|
||||
| | | AS SELECT number, ts FROM numbers_input_show WHERE number > 10 | |
|
||||
+---------------------+---------------+----------------------------------------------------------------+------------------------------------+
|
||||
|
||||
@@ -180,7 +185,7 @@ SELECT number, ts FROM out_num_cnt_show;
|
||||
|
||||
-- after this, the flow SHOULD be replaced
|
||||
-- (flow exists, replace, if not exists)=(true, true, false)
|
||||
CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number, ts FROM numbers_input_show where number > 3;
|
||||
CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number, ts FROM numbers_input_show where number > 3;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
@@ -191,6 +196,7 @@ SELECT flow_name, table_catalog, flow_definition, source_table_names FROM INFORM
|
||||
+---------------------+---------------+---------------------------------------------------------------+------------------------------------+
|
||||
| filter_numbers_show | greptime | CREATE FLOW IF NOT EXISTS filter_numbers_show | greptime.public.numbers_input_show |
|
||||
| | | SINK TO public.out_num_cnt_show | |
|
||||
| | | EVAL INTERVAL '3600 s' | |
|
||||
| | | AS SELECT number, ts FROM numbers_input_show WHERE number > 3 | |
|
||||
+---------------------+---------------+---------------------------------------------------------------+------------------------------------+
|
||||
|
||||
@@ -216,6 +222,9 @@ SELECT number, ts FROM out_num_cnt_show;
|
||||
| number | ts |
|
||||
+--------+-------------------------+
|
||||
| 4 | 1970-01-01T00:00:00.002 |
|
||||
| 4 | 1970-01-01T00:00:00.004 |
|
||||
| 5 | 1970-01-01T00:00:00.004 |
|
||||
| 10 | 1970-01-01T00:00:00 |
|
||||
| 10 | 1970-01-01T00:00:00.003 |
|
||||
| 11 | 1970-01-01T00:00:00.004 |
|
||||
| 15 | 1970-01-01T00:00:00.001 |
|
||||
@@ -235,6 +244,7 @@ SELECT flow_name, table_catalog, flow_definition, source_table_names FROM INFORM
|
||||
+---------------------+---------------+---------------------------------------------------------------+------------------------------------+
|
||||
| filter_numbers_show | greptime | CREATE FLOW IF NOT EXISTS filter_numbers_show | greptime.public.numbers_input_show |
|
||||
| | | SINK TO public.out_num_cnt_show | |
|
||||
| | | EVAL INTERVAL '3600 s' | |
|
||||
| | | AS SELECT number, ts FROM numbers_input_show WHERE number > 3 | |
|
||||
+---------------------+---------------+---------------------------------------------------------------+------------------------------------+
|
||||
|
||||
@@ -260,7 +270,7 @@ Error: 8001(FlowNotFound), Flow not found: greptime.filter_numbers_show
|
||||
|
||||
-- following always create since didn't exist
|
||||
-- (flow exists, replace, if not exists)=(false, true, false)
|
||||
CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number, ts FROM numbers_input_show where number > -2;
|
||||
CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number, ts FROM numbers_input_show where number > -2;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
@@ -271,6 +281,7 @@ SELECT flow_name, table_catalog, flow_definition, source_table_names FROM INFORM
|
||||
+---------------------+---------------+----------------------------------------------------------------+------------------------------------+
|
||||
| filter_numbers_show | greptime | CREATE FLOW IF NOT EXISTS filter_numbers_show | greptime.public.numbers_input_show |
|
||||
| | | SINK TO public.out_num_cnt_show | |
|
||||
| | | EVAL INTERVAL '3600 s' | |
|
||||
| | | AS SELECT number, ts FROM numbers_input_show WHERE number > -2 | |
|
||||
+---------------------+---------------+----------------------------------------------------------------+------------------------------------+
|
||||
|
||||
@@ -279,7 +290,7 @@ DROP FLOW filter_numbers_show;
|
||||
Affected Rows: 0
|
||||
|
||||
-- (flow exists, replace, if not exists)=(false, false, true)
|
||||
CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number, ts FROM numbers_input_show where number > -3;
|
||||
CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number, ts FROM numbers_input_show where number > -3;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
@@ -290,6 +301,7 @@ SELECT flow_name, table_catalog, flow_definition, source_table_names FROM INFORM
|
||||
+---------------------+---------------+----------------------------------------------------------------+------------------------------------+
|
||||
| filter_numbers_show | greptime | CREATE FLOW IF NOT EXISTS filter_numbers_show | greptime.public.numbers_input_show |
|
||||
| | | SINK TO public.out_num_cnt_show | |
|
||||
| | | EVAL INTERVAL '3600 s' | |
|
||||
| | | AS SELECT number, ts FROM numbers_input_show WHERE number > -3 | |
|
||||
+---------------------+---------------+----------------------------------------------------------------+------------------------------------+
|
||||
|
||||
@@ -311,6 +323,7 @@ SELECT flow_name, table_catalog, flow_definition, source_table_names FROM INFORM
|
||||
+---------------------+---------------+----------------------------------------------------------------+------------------------------------+
|
||||
| filter_numbers_show | greptime | CREATE FLOW IF NOT EXISTS filter_numbers_show | greptime.public.numbers_input_show |
|
||||
| | | SINK TO public.out_num_cnt_show | |
|
||||
| | | EVAL INTERVAL '3600 s' | |
|
||||
| | | AS SELECT number, ts FROM numbers_input_show WHERE number > -3 | |
|
||||
+---------------------+---------------+----------------------------------------------------------------+------------------------------------+
|
||||
|
||||
@@ -320,6 +333,9 @@ SELECT * FROM out_num_cnt_show;
|
||||
| number | ts |
|
||||
+--------+-------------------------+
|
||||
| 4 | 1970-01-01T00:00:00.002 |
|
||||
| 4 | 1970-01-01T00:00:00.004 |
|
||||
| 5 | 1970-01-01T00:00:00.004 |
|
||||
| 10 | 1970-01-01T00:00:00 |
|
||||
| 10 | 1970-01-01T00:00:00.003 |
|
||||
| 11 | 1970-01-01T00:00:00.004 |
|
||||
| 15 | 1970-01-01T00:00:00.001 |
|
||||
@@ -348,7 +364,11 @@ SELECT * FROM out_num_cnt_show;
|
||||
+--------+-------------------------+
|
||||
| -2 | 1970-01-01T00:00:00.002 |
|
||||
| -1 | 1970-01-01T00:00:00.003 |
|
||||
| 3 | 1970-01-01T00:00:00.001 |
|
||||
| 4 | 1970-01-01T00:00:00.002 |
|
||||
| 4 | 1970-01-01T00:00:00.004 |
|
||||
| 5 | 1970-01-01T00:00:00.004 |
|
||||
| 10 | 1970-01-01T00:00:00 |
|
||||
| 10 | 1970-01-01T00:00:00.003 |
|
||||
| 11 | 1970-01-01T00:00:00.004 |
|
||||
| 15 | 1970-01-01T00:00:00.001 |
|
||||
@@ -384,7 +404,7 @@ create table out_num_cnt_show (
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
CREATE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number as n1 FROM numbers_input_show where number > 10;
|
||||
CREATE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number as n1 FROM numbers_input_show where number > 10;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
@@ -412,15 +432,20 @@ SELECT number FROM out_num_cnt_show;
|
||||
| 16 |
|
||||
+--------+
|
||||
|
||||
-- The sink schema mismatch is detected on the flownode. In distributed mode the
|
||||
-- error crosses gRPC and loses its source chain, so normalize the trailing chain
|
||||
-- to keep both environments comparable; the rejection itself is identical.
|
||||
-- should mismatch, hence the old flow remains
|
||||
CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number AS n1, number AS n2 FROM numbers_input_show where number > 15;
|
||||
-- SQLNESS REPLACE (in\x20context:\x20Failed\x20to\x20rewrite\x20plan).* in context: Failed to rewrite plan
|
||||
CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number AS n1, number AS n2 FROM numbers_input_show where number > 15;
|
||||
|
||||
Error: 3001(EngineExecuteQuery), Invalid query: Flow output column 1 has type Int32(Int32Type), but sink column ts has type Timestamp(Millisecond(TimestampMillisecondType))
|
||||
Error: 3001(EngineExecuteQuery), Datafusion error: Plan("Cannot match flow output column 'n2' to sink column 'ts' by position: incompatible data types, flow output type is Int32(Int32Type), sink column type is Timestamp(Millisecond(TimestampMillisecondType)). Flow output schema does not match sink table schema: found 2 flow output columns and 2 sink table columns. flow output columns: [\"n1\", \"n2\"], sink table columns: [\"number\", \"ts\"], extra flow columns not in sink: [\"n1\", \"n2\"], missing sink columns from flow output: [\"number\", \"ts\"]") in context: Failed to rewrite plan
|
||||
|
||||
-- should mismatch, hence the old flow remains
|
||||
CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number AS n1, number AS n2, number AS n3 FROM numbers_input_show where number > 15;
|
||||
-- SQLNESS REPLACE (in\x20context:\x20Failed\x20to\x20rewrite\x20plan).* in context: Failed to rewrite plan
|
||||
CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number AS n1, number AS n2, number AS n3 FROM numbers_input_show where number > 15;
|
||||
|
||||
Error: 3001(EngineExecuteQuery), Invalid query: Flow output has 3 columns, but sink has 2 columns; only zero, one, or two trailing auto columns are supported
|
||||
Error: 3001(EngineExecuteQuery), Datafusion error: Plan("Flow output schema does not match sink table schema: found 3 flow output columns and 2 sink table columns. flow output columns: [\"n1\", \"n2\", \"n3\"], sink table columns: [\"number\", \"ts\"], extra flow columns not in sink: [\"n1\", \"n2\", \"n3\"], missing sink columns from flow output: [\"number\", \"ts\"]") in context: Failed to rewrite plan
|
||||
|
||||
SELECT flow_definition, source_table_names FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name='filter_numbers_show';
|
||||
|
||||
@@ -429,6 +454,7 @@ SELECT flow_definition, source_table_names FROM INFORMATION_SCHEMA.FLOWS WHERE f
|
||||
+------------------------------------------------------------------+------------------------------------+
|
||||
| CREATE FLOW IF NOT EXISTS filter_numbers_show | greptime.public.numbers_input_show |
|
||||
| SINK TO public.out_num_cnt_show | |
|
||||
| EVAL INTERVAL '3600 s' | |
|
||||
| AS SELECT number AS n1 FROM numbers_input_show WHERE number > 10 | |
|
||||
+------------------------------------------------------------------+------------------------------------+
|
||||
|
||||
@@ -457,6 +483,7 @@ SELECT number FROM out_num_cnt_show;
|
||||
| 15 |
|
||||
| 15 |
|
||||
| 16 |
|
||||
| 16 |
|
||||
| 18 |
|
||||
+--------+
|
||||
|
||||
@@ -466,6 +493,7 @@ Affected Rows: 0
|
||||
|
||||
CREATE FLOW filter_numbers_show
|
||||
SINK TO out_num_cnt_show
|
||||
EVAL INTERVAL '1h'
|
||||
WITH (defer_on_missing_source = true)
|
||||
AS SELECT number AS n1 FROM numbers_input_show where number > 10;
|
||||
|
||||
@@ -478,6 +506,7 @@ SHOW CREATE FLOW filter_numbers_show;
|
||||
+---------------------+------------------------------------------------------------------+
|
||||
| filter_numbers_show | CREATE FLOW IF NOT EXISTS filter_numbers_show |
|
||||
| | SINK TO public.out_num_cnt_show |
|
||||
| | EVAL INTERVAL '3600 s' |
|
||||
| | WITH (defer_on_missing_source = 'true') |
|
||||
| | AS SELECT number AS n1 FROM numbers_input_show WHERE number > 10 |
|
||||
+---------------------+------------------------------------------------------------------+
|
||||
@@ -489,6 +518,7 @@ SELECT flow_definition FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name='filter_num
|
||||
+------------------------------------------------------------------+
|
||||
| CREATE FLOW IF NOT EXISTS filter_numbers_show |
|
||||
| SINK TO public.out_num_cnt_show |
|
||||
| EVAL INTERVAL '3600 s' |
|
||||
| WITH (defer_on_missing_source = 'true') |
|
||||
| AS SELECT number AS n1 FROM numbers_input_show WHERE number > 10 |
|
||||
+------------------------------------------------------------------+
|
||||
|
||||
@@ -15,7 +15,7 @@ SELECT flow_name, table_catalog, flow_definition, source_table_names FROM INFORM
|
||||
|
||||
SHOW FLOWS LIKE 'filter_numbers_show';
|
||||
|
||||
CREATE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number FROM numbers_input_show where number > 10;
|
||||
CREATE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number FROM numbers_input_show where number > 10;
|
||||
|
||||
SHOW CREATE FLOW filter_numbers_show;
|
||||
|
||||
@@ -32,13 +32,13 @@ SHOW FLOWS LIKE 'filter_numbers_show';
|
||||
-- also test `CREATE OR REPLACE` and `IF NOT EXISTS`
|
||||
|
||||
-- (flow exists, replace, if not exists)=(false, false, false)
|
||||
CREATE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number, ts FROM numbers_input_show where number > 10;
|
||||
CREATE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number, ts FROM numbers_input_show where number > 10;
|
||||
|
||||
SELECT flow_name, table_catalog, flow_definition, source_table_names FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name='filter_numbers_show';
|
||||
|
||||
-- this one should error out
|
||||
-- (flow exists, replace, if not exists)=(true, false, false)
|
||||
CREATE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number, ts FROM numbers_input_show where number > 15;
|
||||
CREATE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number, ts FROM numbers_input_show where number > 15;
|
||||
|
||||
SELECT flow_name, table_catalog, flow_definition, source_table_names FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name='filter_numbers_show';
|
||||
|
||||
@@ -54,7 +54,7 @@ SELECT number, ts FROM out_num_cnt_show;
|
||||
|
||||
-- after this one, the flow SHOULD NOT be replaced
|
||||
-- (flow exists, replace, if not exists)=(true, false, true)
|
||||
CREATE FLOW IF NOT EXISTS filter_numbers_show SINK TO out_num_cnt_show AS SELECT number, ts FROM numbers_input_show where number > 5;
|
||||
CREATE FLOW IF NOT EXISTS filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number, ts FROM numbers_input_show where number > 5;
|
||||
|
||||
SELECT flow_name, table_catalog, flow_definition, source_table_names FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name='filter_numbers_show';
|
||||
|
||||
@@ -70,7 +70,7 @@ SELECT number, ts FROM out_num_cnt_show;
|
||||
|
||||
-- after this, the flow SHOULD be replaced
|
||||
-- (flow exists, replace, if not exists)=(true, true, false)
|
||||
CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number, ts FROM numbers_input_show where number > 3;
|
||||
CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number, ts FROM numbers_input_show where number > 3;
|
||||
|
||||
SELECT flow_name, table_catalog, flow_definition, source_table_names FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name='filter_numbers_show';
|
||||
|
||||
@@ -101,14 +101,14 @@ DROP FLOW filter_numbers_show;
|
||||
|
||||
-- following always create since didn't exist
|
||||
-- (flow exists, replace, if not exists)=(false, true, false)
|
||||
CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number, ts FROM numbers_input_show where number > -2;
|
||||
CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number, ts FROM numbers_input_show where number > -2;
|
||||
|
||||
SELECT flow_name, table_catalog, flow_definition, source_table_names FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name='filter_numbers_show';
|
||||
|
||||
DROP FLOW filter_numbers_show;
|
||||
|
||||
-- (flow exists, replace, if not exists)=(false, false, true)
|
||||
CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number, ts FROM numbers_input_show where number > -3;
|
||||
CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number, ts FROM numbers_input_show where number > -3;
|
||||
|
||||
SELECT flow_name, table_catalog, flow_definition, source_table_names FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name='filter_numbers_show';
|
||||
|
||||
@@ -149,7 +149,7 @@ create table out_num_cnt_show (
|
||||
PRIMARY KEY(number),
|
||||
);
|
||||
|
||||
CREATE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number as n1 FROM numbers_input_show where number > 10;
|
||||
CREATE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number as n1 FROM numbers_input_show where number > 10;
|
||||
|
||||
INSERT INTO numbers_input_show VALUES (10, 0),(15, 1),(16, 2);
|
||||
|
||||
@@ -160,11 +160,16 @@ ADMIN FLUSH_FLOW('filter_numbers_show');
|
||||
|
||||
SELECT number FROM out_num_cnt_show;
|
||||
|
||||
-- The sink schema mismatch is detected on the flownode. In distributed mode the
|
||||
-- error crosses gRPC and loses its source chain, so normalize the trailing chain
|
||||
-- to keep both environments comparable; the rejection itself is identical.
|
||||
-- should mismatch, hence the old flow remains
|
||||
CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number AS n1, number AS n2 FROM numbers_input_show where number > 15;
|
||||
-- SQLNESS REPLACE (in\x20context:\x20Failed\x20to\x20rewrite\x20plan).* in context: Failed to rewrite plan
|
||||
CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number AS n1, number AS n2 FROM numbers_input_show where number > 15;
|
||||
|
||||
-- should mismatch, hence the old flow remains
|
||||
CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show AS SELECT number AS n1, number AS n2, number AS n3 FROM numbers_input_show where number > 15;
|
||||
-- SQLNESS REPLACE (in\x20context:\x20Failed\x20to\x20rewrite\x20plan).* in context: Failed to rewrite plan
|
||||
CREATE OR REPLACE FLOW filter_numbers_show SINK TO out_num_cnt_show EVAL INTERVAL '1h' AS SELECT number AS n1, number AS n2, number AS n3 FROM numbers_input_show where number > 15;
|
||||
|
||||
SELECT flow_definition, source_table_names FROM INFORMATION_SCHEMA.FLOWS WHERE flow_name='filter_numbers_show';
|
||||
|
||||
@@ -182,6 +187,7 @@ DROP FLOW filter_numbers_show;
|
||||
|
||||
CREATE FLOW filter_numbers_show
|
||||
SINK TO out_num_cnt_show
|
||||
EVAL INTERVAL '1h'
|
||||
WITH (defer_on_missing_source = true)
|
||||
AS SELECT number AS n1 FROM numbers_input_show where number > 10;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user