// 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 std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use std::time::Duration; use client::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME, OutputData}; use common_error::root_source; use common_event_recorder::{PersistentEventContext, TriggerReason}; use common_meta::key::table_name::TableNameKey; use common_procedure::{ProcedureContext, ProcedureId, ProcedureWithId, watcher}; use common_query::Output; use common_telemetry::info; use common_test_util::recordbatch::check_output_stream; use common_test_util::temp_dir::{TempDir, create_temp_dir}; use common_wal::config::DatanodeWalConfig; use datatypes::arrow::array::AsArray; use datatypes::value::Value; use frontend::instance::Instance; use meta_srv::gc::{self, BatchGcProcedure, GcSchedulerOptions, GcTickerRef}; use meta_srv::metasrv::Metasrv; use mito2::gc::GcConfig; use partition::expr::{PartitionExpr, RestrictedOp}; use partition::function::IcebergHash; use servers::error::Result as ServerResult; use servers::query_handler::sql::SqlQueryHandler; use session::Session; use session::context::{Channel, QueryContext, QueryContextRef}; use sqlx::Row; use store_api::codec::PrimaryKeyEncoding; use store_api::metric_engine_consts::{DATA_SCHEMA_TABLE_ID_COLUMN_NAME, METRIC_DATA_REGION_GROUP}; use store_api::storage::{RegionId, TableId}; use tests_integration::cluster::{GreptimeDbCluster, GreptimeDbClusterBuilder}; use tests_integration::test_util::{ StorageType, get_test_store_config, setup_mysql_server_for_frontend_instance, setup_pg_server_for_frontend_instance, }; use tokio::sync::oneshot; /// Each partition/format combination uses its own cluster and test timeout. #[macro_export] macro_rules! table_id_partition_tests { ($service:ident, $(($name:ident, $mixed:expr, $hashed:expr, $flat:expr, $encoding:ident)),+ $(,)?) => { $( #[tokio::test(flavor = "multi_thread")] async fn $name() { let store_type = tests_integration::test_util::StorageType::$service; if store_type.test_on() { common_telemetry::init_default_ut_logging(); $crate::repartition::test_partition_unpartitioned_metric_by_table_id( store_type, $mixed, $hashed, $flat, store_api::codec::PrimaryKeyEncoding::$encoding, ).await; } } )+ }; } #[macro_export] macro_rules! repartition_tests { ($($service:ident),*) => { $( paste::item! { mod [] { // Every case below builds its own cluster and runs a full repartition plus // GC cycle, which takes around a minute on object-store backends. Keep one // case per test so a case stays well inside the nextest slow timeout and // cases run in parallel; do not fold several cases back into one test. #[tokio::test(flavor = "multi_thread")] async fn [< test_repartition_mito_flat >]() { let store_type = tests_integration::test_util::StorageType::$service; if store_type.test_on() { common_telemetry::init_default_ut_logging(); $crate::repartition::test_repartition_mito(store_type, true).await; } } #[tokio::test(flavor = "multi_thread")] async fn [< test_repartition_mito_primary_key >]() { let store_type = tests_integration::test_util::StorageType::$service; if store_type.test_on() { common_telemetry::init_default_ut_logging(); $crate::repartition::test_repartition_mito(store_type, false).await; } } #[tokio::test(flavor = "multi_thread")] async fn [< test_partition_unpartitioned_mito >]() { let store_type = tests_integration::test_util::StorageType::$service; if store_type.test_on() { common_telemetry::init_default_ut_logging(); $crate::repartition::test_partition_unpartitioned_mito(store_type).await; } } #[tokio::test(flavor = "multi_thread")] async fn [< test_repartition_on_columns_metadata_mito >]() { let store_type = tests_integration::test_util::StorageType::$service; if store_type.test_on() { common_telemetry::init_default_ut_logging(); $crate::repartition::test_repartition_on_columns_metadata_mito(store_type).await; } } #[tokio::test(flavor = "multi_thread")] async fn [< test_repartition_on_columns_data_correctness_mito >]() { let store_type = tests_integration::test_util::StorageType::$service; if store_type.test_on() { common_telemetry::init_default_ut_logging(); $crate::repartition::test_repartition_on_columns_data_correctness_mito(store_type).await; } } #[tokio::test(flavor = "multi_thread")] async fn [< test_partition_unpartitioned_metric >]() { let store_type = tests_integration::test_util::StorageType::$service; if store_type.test_on() { common_telemetry::init_default_ut_logging(); $crate::repartition::test_partition_unpartitioned_metric(store_type).await; } } $crate::table_id_partition_tests! { $service, (test_partition_unpartitioned_metric_by_table_id_primary_key_sparse, false, false, false, Sparse), (test_partition_unpartitioned_metric_by_table_id_and_host_primary_key_sparse, true, false, false, Sparse), (test_partition_unpartitioned_metric_by_table_id_hash_primary_key_sparse, false, true, false, Sparse), (test_partition_unpartitioned_metric_by_table_id_hash_and_host_flat_dense, true, true, true, Dense), (test_partition_unpartitioned_metric_by_table_id_hash_and_host_primary_key_sparse, true, true, false, Sparse), } #[tokio::test(flavor = "multi_thread")] async fn [< test_repartition_metric_flat_sparse >]() { let store_type = tests_integration::test_util::StorageType::$service; if store_type.test_on() { use store_api::codec::PrimaryKeyEncoding; common_telemetry::init_default_ut_logging(); $crate::repartition::test_repartition_metric(store_type, true, PrimaryKeyEncoding::Sparse).await; } } #[tokio::test(flavor = "multi_thread")] async fn [< test_repartition_metric_flat_dense >]() { let store_type = tests_integration::test_util::StorageType::$service; if store_type.test_on() { use store_api::codec::PrimaryKeyEncoding; common_telemetry::init_default_ut_logging(); $crate::repartition::test_repartition_metric(store_type, true, PrimaryKeyEncoding::Dense).await; } } #[tokio::test(flavor = "multi_thread")] async fn [< test_repartition_metric_primary_key_sparse >]() { let store_type = tests_integration::test_util::StorageType::$service; if store_type.test_on() { use store_api::codec::PrimaryKeyEncoding; common_telemetry::init_default_ut_logging(); $crate::repartition::test_repartition_metric(store_type, false, PrimaryKeyEncoding::Sparse).await; } } #[tokio::test(flavor = "multi_thread")] async fn [< test_repartition_metric_primary_key_dense >]() { let store_type = tests_integration::test_util::StorageType::$service; if store_type.test_on() { use store_api::codec::PrimaryKeyEncoding; common_telemetry::init_default_ut_logging(); $crate::repartition::test_repartition_metric(store_type, false, PrimaryKeyEncoding::Dense).await; } } } } )* }; } #[tokio::test(flavor = "multi_thread")] async fn test_repartition_procedure_id_session() { let (cluster, _home_guard) = repartition_cluster("repartition_procedure_id_session").await; let instance = cluster.fe_instance(); let session = Session::new(None, Channel::Postgres, Default::default(), 0); let query_ctx = session.new_query_context(); run_sql( instance, r#"CREATE TABLE repartition_session_test ("id" INT PRIMARY KEY, ts TIMESTAMP TIME INDEX) PARTITION ON COLUMNS ("id") ("id" < 10, "id" >= 10)"#, session.new_query_context(), ) .await .unwrap(); query_ctx.set_last_procedure_id("previous-id".to_string()); let sql = r#"ALTER TABLE repartition_session_test REPARTITION ("id" < 10) INTO ("id" < 5, "id" >= 5 AND "id" < 10) WITH (wait=false)"#; let OutputData::RecordBatches(batches) = run_sql(instance, sql, session.new_query_context()) .await .unwrap() .data else { panic!("expected Procedure ID result"); }; let batch = batches.iter().next().unwrap(); let id = batch .column_by_name("Procedure ID") .unwrap() .as_string::() .value(0); assert_eq!(query_ctx.last_procedure_id().as_deref(), Some(id)); let mut watcher = cluster .metasrv .procedure_manager() .procedure_watcher(ProcedureId::parse_str(id).unwrap()) .unwrap(); tokio::time::timeout(Duration::from_secs(60), watcher::wait(&mut watcher)) .await .unwrap() .unwrap(); } #[tokio::test(flavor = "multi_thread")] async fn test_repartition_physical_metric_without_logical_table() { common_telemetry::init_default_ut_logging(); let (store_config, _guard) = get_test_store_config(&StorageType::File); let home_dir = create_temp_dir("repartition_physical_metric_without_logical_table"); let cluster = GreptimeDbClusterBuilder::new("test_repartition_physical_metric_without_logical_table") .await .with_datanodes(3) .with_store_config(store_config) .with_shared_home_dir(Arc::new(home_dir)) .with_datanode_wal_config(DatanodeWalConfig::Noop) .with_metasrv_gc_config(GcSchedulerOptions { enable: true, gc_cooldown_period: Duration::from_nanos(1), ..Default::default() }) .with_datanode_gc_config(GcConfig { enable: true, lingering_time: Some(Duration::from_secs(0)), unknown_file_lingering_time: Duration::from_secs(0), ..Default::default() }) .build(true) .await; let instance = cluster.fe_instance(); let query_ctx = QueryContext::arc(); let sql = r#" CREATE TABLE `physical_metric_without_logical`( `ts` TIMESTAMP TIME INDEX, `val` DOUBLE, `host` STRING PRIMARY KEY ) PARTITION ON COLUMNS (`host`) ( `host` < 'm', `host` >= 'm' ) ENGINE = metric WITH ( "physical_metric_table" = "true" ); "#; run_sql(instance, sql, query_ctx.clone()).await.unwrap(); let table_id = get_table_id(&cluster.metasrv, "physical_metric_without_logical").await; let table_info = cluster .metasrv .table_metadata_manager() .table_info_manager() .get(table_id) .await .unwrap() .unwrap(); let column_ids_before_split = table_info.table_info.meta.column_ids.clone(); assert_eq!(column_ids_before_split, vec![0, 1, 2]); let sql = r#" ALTER TABLE `physical_metric_without_logical` SPLIT PARTITION ( `host` < 'm' ) INTO ( `host` < 'g', `host` >= 'g' AND `host` < 'm' ); "#; run_sql(instance, sql, query_ctx.clone()).await.unwrap(); let table_info = cluster .metasrv .table_metadata_manager() .table_info_manager() .get(table_id) .await .unwrap() .unwrap(); assert_eq!( table_info.table_info.meta.column_ids, column_ids_before_split ); let result = run_sql( instance, &query_partitions_sql("physical_metric_without_logical"), query_ctx, ) .await .unwrap(); let expected = r#"+---------------+--------------+---------------------------------+----------------+----------------------+------------------------+-----------------------+----------------------------+ | table_catalog | table_schema | table_name | partition_name | partition_expression | partition_description | greptime_partition_id | partition_ordinal_position | +---------------+--------------+---------------------------------+----------------+----------------------+------------------------+-----------------------+----------------------------+ | greptime | public | physical_metric_without_logical | p0 | host | host < g | 4398046511104 | 1 | | greptime | public | physical_metric_without_logical | p1 | host | host >= m | 4398046511105 | 2 | | greptime | public | physical_metric_without_logical | p2 | host | host >= g AND host < m | 4398046511106 | 3 | +---------------+--------------+---------------------------------+----------------+----------------------+------------------------+-----------------------+----------------------------+"#; check_output_stream(result.data, expected).await; } /// COUNT must use visible rows rather than the full row counts of shared SSTs. #[tokio::test(flavor = "multi_thread")] async fn test_repartition_append_count_file() { let (cluster, _home_guard) = repartition_cluster("repartition_append_count").await; let instance = cluster.fe_instance(); let table = "count_repartition"; prepare_append_count_table(instance, table, "").await; assert_append_count(instance, table, 100, 1).await; flush_append_count_table(instance, table).await; assert_append_count(instance, table, 100, 1).await; let sql = "ALTER TABLE count_repartition PARTITION ON COLUMNS (device_id) \ (device_id < 50, device_id >= 50)"; run_sql(instance, sql, QueryContext::arc()).await.unwrap(); wait_for_append_count_regions(instance, table, 2).await; assert_append_count(instance, table, 100, 0).await; check_append_count_after_write(instance, table, 0).await; } #[tokio::test(flavor = "multi_thread")] async fn test_split_append_count_file() { let (cluster, _home_guard) = repartition_cluster("split_append_count").await; let instance = cluster.fe_instance(); let table = "count_split"; prepare_append_count_table( instance, table, "PARTITION ON COLUMNS (device_id) (device_id < 50, device_id >= 50)", ) .await; assert_append_count(instance, table, 100, 2).await; flush_append_count_table(instance, table).await; assert_append_count(instance, table, 100, 2).await; let sql = "ALTER TABLE count_split SPLIT PARTITION (device_id < 50) INTO \ (device_id < 25, device_id >= 25 AND device_id < 50)"; run_sql(instance, sql, QueryContext::arc()).await.unwrap(); wait_for_append_count_regions(instance, table, 3).await; assert_append_count(instance, table, 100, 1).await; check_append_count_after_write(instance, table, 1).await; } #[tokio::test(flavor = "multi_thread")] async fn test_repartition_append_count_memtable_file() { let (cluster, home_guard) = repartition_cluster("repartition_append_count_memtable").await; assert!(home_guard.path().is_dir()); let instance = cluster.fe_instance(); let table = "count_repartition_memtable"; prepare_append_count_table(instance, table, "").await; assert_append_count(instance, table, 100, 1).await; // Entering staging must flush the populated memtable before changing partitions. let sql = "ALTER TABLE count_repartition_memtable PARTITION ON COLUMNS (device_id) \ (device_id < 50, device_id >= 50)"; run_sql(instance, sql, QueryContext::arc()).await.unwrap(); wait_for_append_count_regions(instance, table, 2).await; assert_append_count(instance, table, 100, 0).await; check_append_count_after_write(instance, table, 0).await; assert!(home_guard.path().is_dir()); } async fn repartition_cluster(name: &str) -> (GreptimeDbCluster, Arc) { common_telemetry::init_default_ut_logging(); let (store_config, _guard) = get_test_store_config(&StorageType::File); let home_dir = Arc::new(create_temp_dir(name)); let cluster = GreptimeDbClusterBuilder::new(name) .await .with_shared_home_dir(Arc::clone(&home_dir)) .with_datanodes(3) .with_store_config(store_config) .with_datanode_wal_config(DatanodeWalConfig::Noop) .with_metasrv_gc_config(GcSchedulerOptions { enable: true, ..Default::default() }) .with_datanode_gc_config(GcConfig { enable: true, ..Default::default() }) .build(true) .await; (cluster, home_dir) } async fn prepare_append_count_table(instance: &Arc, table: &str, partitions: &str) { let sql = format!( "CREATE TABLE {table} (ts TIMESTAMP TIME INDEX, device_id INT) \ {partitions} ENGINE=mito WITH(append_mode='true')" ); run_sql(instance, &sql, QueryContext::arc()).await.unwrap(); let sql = format!( "INSERT INTO {table} SELECT to_timestamp_millis(value), CAST(value AS INT) \ FROM generate_series(0, 99)" ); run_sql(instance, &sql, QueryContext::arc()).await.unwrap(); } async fn flush_append_count_table(instance: &Arc, table: &str) { run_sql( instance, &format!("ADMIN flush_table('{table}')"), QueryContext::arc(), ) .await .unwrap(); } async fn check_append_count_after_write( instance: &Arc, table: &str, statistics_regions: usize, ) { run_sql( instance, &format!("INSERT INTO {table} VALUES (to_timestamp_millis(100), 100)"), QueryContext::arc(), ) .await .unwrap(); assert_append_count(instance, table, 101, statistics_regions).await; flush_append_count_table(instance, table).await; assert_append_count(instance, table, 101, statistics_regions).await; } async fn wait_for_append_count_regions(instance: &Arc, table: &str, expected: usize) { // Wait for frontend routing, not for COUNT to become correct. tokio::time::timeout(Duration::from_secs(10), async { loop { let plan = append_count_query(instance, &format!("EXPLAIN ANALYZE SELECT * FROM {table}")) .await; if plan.matches("UnorderedScan: region=").count() == expected { return; } tokio::time::sleep(Duration::from_millis(50)).await; } }) .await .expect("new partition routes must become visible"); } async fn append_count_query(instance: &Arc, sql: &str) -> String { let output = run_sql(instance, sql, QueryContext::arc()).await.unwrap(); let batches = match output.data { common_query::OutputData::Stream(stream) => { common_recordbatch::RecordBatches::try_collect(stream) .await .unwrap() } common_query::OutputData::RecordBatches(batches) => batches, _ => panic!("expected query output: {sql}"), }; batches.pretty_print().unwrap() } async fn assert_append_count( instance: &Arc, table: &str, rows: usize, statistics_regions: usize, ) { let expected = format!("+-----+\n| n |\n+-----+\n| {rows:<3} |\n+-----+"); let count = append_count_query(instance, &format!("SELECT count(*) AS n FROM {table}")).await; assert_eq!(count, expected, "unbounded COUNT for {table}"); let scanned_count = append_count_query( instance, &format!("SELECT count(*) AS n FROM (SELECT * FROM {table} LIMIT 1000)"), ) .await; assert_eq!(scanned_count, expected, "scanned COUNT for {table}"); // Only regions whose source row counts are exact may use statistics. let plan = append_count_query( instance, &format!("EXPLAIN ANALYZE SELECT count(*) FROM {table}"), ) .await; assert_eq!( plan.matches("PlaceholderRowExec").count(), statistics_regions, "{plan}" ); } #[tokio::test(flavor = "multi_thread")] async fn test_exemplar_sparse_repartition_compaction() { let (cluster, _home_guard) = repartition_cluster("exemplar_sparse_repartition").await; let instance = cluster.fe_instance(); let ctx = QueryContext::arc(); for sql in [ "CREATE TABLE exemplar_sparse_repartition ( __table_id INT UNSIGNED NOT NULL, __tsid BIGINT UNSIGNED NOT NULL, host STRING, ts TIMESTAMP TIME INDEX, val DOUBLE, PRIMARY KEY (__table_id, __tsid, host) ) PARTITION ON COLUMNS(host) (host < 'm', host >= 'm') WITH ('primary_key_encoding'='sparse', 'append_mode'='true')", "INSERT INTO exemplar_sparse_repartition VALUES (42, 7, 'a', 1, 1), (42, 7, 'h', 1, 2), (43, 7, 'z', 1, 3)", "ADMIN FLUSH_TABLE('exemplar_sparse_repartition')", "INSERT INTO exemplar_sparse_repartition VALUES (42, 7, 'a', 1, 4), (42, 7, 'h', 1, 5), (43, 7, 'z', 1, 6)", "ADMIN FLUSH_TABLE('exemplar_sparse_repartition')", "ALTER TABLE exemplar_sparse_repartition SPLIT PARTITION (host < 'm') INTO (host < 'g', host >= 'g' AND host < 'm')", ] { run_sql(instance, sql, ctx.clone()).await.unwrap(); } // Refresh routes synchronously instead of depending on heartbeat timing. instance.cache_invalidator().invalidate_all().unwrap(); let mut inherited_ssts = 0; for datanode in cluster.datanode_instances.values() { inherited_ssts += datanode .region_server() .mito_engine() .unwrap() .all_ssts_from_manifest() .await .into_iter() .filter(|entry| entry.origin_region_id != entry.region_id) .count(); } assert!(inherited_ssts > 0); run_sql( instance, "ADMIN COMPACT_TABLE('exemplar_sparse_repartition', 'swcs', '3600')", ctx.clone(), ) .await .unwrap(); let output = run_sql( instance, "SELECT host, COUNT(*) AS n, SUM(val) AS total FROM exemplar_sparse_repartition GROUP BY host ORDER BY host", ctx.clone(), ) .await .unwrap(); check_output_stream( output.data, "+------+---+-------+\n\ | host | n | total |\n\ +------+---+-------+\n\ | a | 2 | 5.0 |\n\ | h | 2 | 7.0 |\n\ | z | 2 | 9.0 |\n\ +------+---+-------+", ) .await; let output = run_sql( instance, "SELECT COUNT(*) FROM exemplar_sparse_repartition WHERE __table_id=42 AND __tsid=7", ctx, ) .await .unwrap(); check_output_stream( output.data, "+----------+\n| count(*) |\n+----------+\n| 4 |\n+----------+", ) .await; } #[tokio::test(flavor = "multi_thread")] async fn test_repartition_multi_hop_fulltext_index_gc_file() { if StorageType::File.test_on() { common_telemetry::init_default_ut_logging(); test_repartition_multi_hop_fulltext_index_gc().await; } } async fn test_repartition_multi_hop_fulltext_index_gc() { let store_type = StorageType::File; let cluster_name = "test_repartition_multi_hop_fulltext_index_gc"; let table_name = "repartition_multi_hop_index_table"; let (store_config, _guard) = get_test_store_config(&store_type); let datanodes = 3u64; let home_dir = create_temp_dir("test_repartition_multi_hop_fulltext_index_gc_data_home"); let cluster = GreptimeDbClusterBuilder::new(cluster_name) .await .with_shared_home_dir(Arc::new(home_dir)) .with_datanodes(datanodes as u32) .with_store_config(store_config) .with_datanode_wal_config(DatanodeWalConfig::Noop) .with_metasrv_gc_config(GcSchedulerOptions { enable: true, gc_cooldown_period: Duration::from_nanos(1), ..Default::default() }) .with_datanode_gc_config(GcConfig { enable: true, lingering_time: Some(Duration::from_secs(0)), unknown_file_lingering_time: Duration::from_secs(0), ..Default::default() }) .build(true) .await; let metasrv = &cluster.metasrv; let ticker = metasrv.gc_ticker().unwrap(); let query_ctx = QueryContext::arc(); let instance = cluster.fe_instance(); run_sql( instance, r#" CREATE TABLE `repartition_multi_hop_index_table`( `id` INT, `msg` STRING FULLTEXT INDEX, `ts` TIMESTAMP TIME INDEX, PRIMARY KEY(`id`) ) PARTITION ON COLUMNS (`id`) ( `id` < 100, `id` >= 100 ) ENGINE = mito WITH ('sst_format' = 'flat'); "#, query_ctx.clone(), ) .await .unwrap(); run_sql( instance, r#" INSERT INTO `repartition_multi_hop_index_table` VALUES (10, 'quick fox in low partition', '2022-01-01 00:00:00'), (60, 'quick fox in middle partition', '2022-01-01 00:00:01'), (90, 'quick fox in high partition', '2022-01-01 00:00:02'), (120, 'quick fox in outer partition', '2022-01-01 00:00:03'); "#, query_ctx.clone(), ) .await .unwrap(); run_sql( instance, "ADMIN FLUSH_TABLE('repartition_multi_hop_index_table')", query_ctx.clone(), ) .await .unwrap(); run_sql( instance, r#" ALTER TABLE `repartition_multi_hop_index_table` SPLIT PARTITION ( `id` < 100 ) INTO ( `id` < 50, `id` >= 50 AND `id` < 100 ); "#, query_ctx.clone(), ) .await .unwrap(); tokio::time::sleep(Duration::from_millis(500)).await; run_sql( instance, r#" ALTER TABLE `repartition_multi_hop_index_table` SPLIT PARTITION ( `id` >= 50 AND `id` < 100 ) INTO ( `id` >= 50 AND `id` < 75, `id` >= 75 AND `id` < 100 ); "#, query_ctx.clone(), ) .await .unwrap(); tokio::time::sleep(Duration::from_millis(500)).await; run_sql( instance, r#" INSERT INTO `repartition_multi_hop_index_table` VALUES (80, 'fresh fox in soon dropped source', '2022-01-01 00:00:04'); "#, query_ctx.clone(), ) .await .unwrap(); run_sql( instance, "ADMIN FLUSH_TABLE('repartition_multi_hop_index_table')", query_ctx.clone(), ) .await .unwrap(); let fox_query = "SELECT id, msg FROM `repartition_multi_hop_index_table` WHERE MATCHES(msg, 'fox') ORDER BY id"; let expected = "\ +-----+----------------------------------+ | id | msg | +-----+----------------------------------+ | 10 | quick fox in low partition | | 60 | quick fox in middle partition | | 80 | fresh fox in soon dropped source | | 90 | quick fox in high partition | | 120 | quick fox in outer partition | +-----+----------------------------------+"; let result = run_sql(instance, fox_query, query_ctx.clone()) .await .unwrap(); check_output_stream(result.data, expected).await; let manifest_entries = cluster_manifest_index_entries(&cluster).await; assert!( manifest_entries .iter() .any(|(_, origin_region_id, region_id)| origin_region_id != region_id), "expected at least one cross-origin indexed SST before GC, got {manifest_entries:?}" ); run_sql( instance, r#" ALTER TABLE `repartition_multi_hop_index_table` MERGE PARTITION ( `id` >= 50 AND `id` < 75, `id` >= 75 AND `id` < 100 ); "#, query_ctx.clone(), ) .await .unwrap(); tokio::time::sleep(Duration::from_millis(500)).await; trigger_full_gc(&ticker).await; trigger_table_gc(metasrv, table_name).await; let result = run_sql(instance, fox_query, query_ctx.clone()) .await .unwrap(); check_output_stream(result.data, expected).await; let manifest_index_paths = cluster_manifest_index_paths(&cluster).await; assert!( !manifest_index_paths.is_empty(), "expected manifest index paths after GC" ); let storage_paths = cluster.list_sst_files_from_all_datanodes().await; assert!( manifest_index_paths.is_subset(&storage_paths), "manifest index paths should exist in storage after GC, missing: {:?}", manifest_index_paths .difference(&storage_paths) .collect::>() ); let cross_origin_index_paths = cluster_manifest_index_entries(&cluster) .await .into_iter() .filter_map(|(index_file_path, origin_region_id, region_id)| { (origin_region_id != region_id).then_some(index_file_path) }) .collect::>(); assert!( !cross_origin_index_paths.is_empty(), "expected cross-origin indexed SSTs after GC" ); assert!( cross_origin_index_paths.is_subset(&storage_paths), "cross-origin manifest index paths should exist in storage after GC, missing: {:?}", cross_origin_index_paths .difference(&storage_paths) .collect::>() ); } const DEVICES: &str = "CREATE TABLE {t} (ts TIMESTAMP TIME INDEX, city STRING, device_id BIGINT, \ PRIMARY KEY(city, device_id))"; const DEVICES_ON_DEVICE_ID: &str = "CREATE TABLE {t} (ts TIMESTAMP TIME INDEX, city STRING, device_id BIGINT, \ PRIMARY KEY(city, device_id)) PARTITION ON COLUMNS (device_id) (device_id < 10, device_id >= 10)"; const DEVICE_ROWS: &str = "INSERT INTO {t} VALUES (1000, 'Aachen', 1), (1000, 'Zurich', 1), \ (1000, 'Paris', 2), (1000, 'Aachen', 10), (1000, 'Zurich', 10), (1000, 'Beijing', 20)"; const PARTITION_DEVICES: &str = "ALTER TABLE {t} PARTITION ON COLUMNS (device_id) \ (device_id < 10, device_id >= 10 AND device_id < 20, device_id >= 20)"; const METRIC_PHYSICAL: &str = r#"CREATE TABLE {t}_phy (ts TIMESTAMP TIME INDEX, val DOUBLE, host STRING PRIMARY KEY) ENGINE = metric WITH ("physical_metric_table" = "true")"#; const METRIC_LOGICAL: &str = r#"CREATE TABLE {t} (ts TIMESTAMP TIME INDEX, val DOUBLE, host STRING PRIMARY KEY) ENGINE = metric WITH ("on_physical_table" = "{t}_phy")"#; const METRIC_LOGICAL_NO_HOST: &str = r#"CREATE TABLE {t}_job (ts TIMESTAMP TIME INDEX, val DOUBLE, job STRING PRIMARY KEY) ENGINE = metric WITH ("on_physical_table" = "{t}_phy")"#; const METRIC_ROWS: &str = "INSERT INTO {t} (host, ts, val) VALUES ('a_host', 1000, 1), \ ('b_host', 1000, 2), ('n_host', 1000, 2), ('z_host', 1000, 2)"; const METRIC_NO_HOST_ROWS: &str = "INSERT INTO {t}_job (job, ts, val) VALUES ('a', 1000, 1), ('b', 1000, 2)"; const PARTITION_METRIC_PHYSICAL: &str = "ALTER TABLE {t}_phy PARTITION ON COLUMNS (host) \ (host < 'g', host >= 'g' AND host < 'p', host >= 'p')"; const COUNT: &str = "SELECT COUNT(1) FROM {t}"; const COUNT_BY_CITY: &str = "SELECT COUNT(1) FROM {t} GROUP BY city ORDER BY city"; const COUNT_BY_DEVICE: &str = "SELECT COUNT(1) FROM {t} GROUP BY device_id ORDER BY device_id"; const COUNT_BY_VAL: &str = "SELECT COUNT(1) FROM {t} GROUP BY val ORDER BY val"; const FIRST_DEVICES: &str = "SELECT device_id FROM {t} ORDER BY device_id LIMIT 2"; const FIRST_DEVICES_ALL_COLUMNS: &str = "SELECT * FROM {t} ORDER BY device_id LIMIT 2"; /// What a statement prepared before a case's DDL returns after it. enum Expected { /// The same as the same text prepared on a new connection. NewStatement, /// These values of the last column. Rows(&'static [i64]), Error, } /// `{t}` in the statements stands for a table name unique to the case. struct PreparedStatementCase { name: &'static str, setup: &'static [&'static str], queries: &'static [(&'static str, Expected)], ddl: &'static [&'static str], } const PREPARED_STATEMENT_CASES: &[PreparedStatementCase] = &[ PreparedStatementCase { name: "first partitioning", setup: &[ DEVICES, DEVICE_ROWS, "CREATE VIEW {t}_view AS SELECT city, COUNT(1) AS c FROM {t} GROUP BY city", "CREATE TABLE {t}_sink (city STRING PRIMARY KEY, c BIGINT, ts TIMESTAMP TIME INDEX)", ], queries: &[ (COUNT, Expected::NewStatement), (COUNT_BY_CITY, Expected::NewStatement), (FIRST_DEVICES, Expected::NewStatement), ( "SELECT COUNT(1) FROM {t} WHERE device_id >= ?", Expected::NewStatement, ), ("SELECT (SELECT COUNT(1) FROM {t})", Expected::NewStatement), ( "SELECT c FROM {t}_view ORDER BY city", Expected::NewStatement, ), ( "INSERT INTO {t}_sink SELECT city, COUNT(1), MAX(ts) FROM {t} GROUP BY city", Expected::NewStatement, ), ( "SELECT c FROM {t}_sink ORDER BY city", Expected::Rows(&[2, 1, 1, 2]), ), ], ddl: &[PARTITION_DEVICES], }, PreparedStatementCase { name: "split adding a partition column", setup: &[DEVICES_ON_DEVICE_ID, DEVICE_ROWS], queries: &[(COUNT_BY_DEVICE, Expected::NewStatement)], ddl: &[ "ALTER TABLE {t} SPLIT PARTITION (device_id >= 10) ON COLUMNS (device_id, city) \ INTO (device_id >= 10 AND city < 'M', device_id >= 10 AND city >= 'M')", ], }, PreparedStatementCase { name: "repartition replacing the partition column", setup: &[DEVICES_ON_DEVICE_ID, DEVICE_ROWS], queries: &[(COUNT_BY_DEVICE, Expected::NewStatement)], ddl: &[ "ALTER TABLE {t} REPARTITION (device_id < 10, device_id >= 10) ON COLUMNS (city) \ INTO (city < 'M', city >= 'M')", ], }, PreparedStatementCase { name: "metric logical tables with and without the physical partition column", setup: &[ METRIC_PHYSICAL, METRIC_LOGICAL, METRIC_LOGICAL_NO_HOST, METRIC_ROWS, METRIC_NO_HOST_ROWS, ], queries: &[ (COUNT, Expected::NewStatement), (COUNT_BY_VAL, Expected::NewStatement), ("TQL EVAL (0, 10, '5s') sum({t})", Expected::NewStatement), ("SELECT COUNT(1) FROM {t}_job", Expected::NewStatement), ], ddl: &[PARTITION_METRIC_PHYSICAL], }, PreparedStatementCase { name: "metric logical table gains the physical partition column", setup: &[ METRIC_PHYSICAL, METRIC_LOGICAL_NO_HOST, METRIC_NO_HOST_ROWS, PARTITION_METRIC_PHYSICAL, ], queries: &[("SELECT COUNT(1) FROM {t}_job", Expected::NewStatement)], ddl: &["ALTER TABLE {t}_job ADD COLUMN host STRING PRIMARY KEY"], }, PreparedStatementCase { name: "schema and partition columns change", setup: &[DEVICES, DEVICE_ROWS], queries: &[ (COUNT, Expected::NewStatement), (COUNT_BY_CITY, Expected::NewStatement), (FIRST_DEVICES, Expected::NewStatement), (FIRST_DEVICES_ALL_COLUMNS, Expected::Rows(&[1, 1])), ], ddl: &["ALTER TABLE {t} ADD COLUMN zone STRING", PARTITION_DEVICES], }, PreparedStatementCase { name: "metric logical table schema and physical partition columns change", setup: &[METRIC_PHYSICAL, METRIC_LOGICAL, METRIC_ROWS], queries: &[ (COUNT, Expected::NewStatement), (COUNT_BY_VAL, Expected::NewStatement), ], ddl: &[ "ALTER TABLE {t} ADD COLUMN job STRING PRIMARY KEY", PARTITION_METRIC_PHYSICAL, ], }, PreparedStatementCase { name: "column comment and partition columns change", setup: &[DEVICES, DEVICE_ROWS], queries: &[ (COUNT, Expected::NewStatement), (COUNT_BY_CITY, Expected::NewStatement), ], ddl: &["COMMENT ON COLUMN {t}.city IS 'x'", PARTITION_DEVICES], }, PreparedStatementCase { name: "rename and partition columns change", setup: &[DEVICES, DEVICE_ROWS], queries: &[(COUNT, Expected::Rows(&[6]))], ddl: &[ "ALTER TABLE {t} RENAME {t}_renamed", "ALTER TABLE {t}_renamed PARTITION ON COLUMNS (device_id) \ (device_id < 10, device_id >= 10 AND device_id < 20, device_id >= 20)", ], }, PreparedStatementCase { name: "schema change alone", setup: &[DEVICES_ON_DEVICE_ID, DEVICE_ROWS], queries: &[ (COUNT, Expected::NewStatement), (FIRST_DEVICES_ALL_COLUMNS, Expected::Rows(&[1, 1])), ], ddl: &["ALTER TABLE {t} ADD COLUMN zone STRING"], }, PreparedStatementCase { name: "dropped and recreated", setup: &[DEVICES, DEVICE_ROWS], queries: &[(COUNT, Expected::Error)], ddl: &["DROP TABLE {t}", DEVICES], }, ]; macro_rules! fetch_last_column { ($pool:expr, $sql:expr, $param:expr) => {{ let mut query = sqlx::query(sqlx::AssertSqlSafe($sql)); if let Some(param) = $param { query = query.bind(param); } let rows = query.fetch_all($pool).await.map_err(|e| e.to_string())?; rows.iter() .map(|row| { let last = row.len() - 1; row.try_get::(last) .or_else(|_| row.try_get::(last).map(|v| v as i64)) .map_err(|e| e.to_string()) }) .collect() }}; } /// A connection that keeps the statements it prepares. enum PreparedClient { Mysql(sqlx::MySqlPool), Postgres(sqlx::PgPool), } impl PreparedClient { async fn connect_each(mysql_addr: &str, pg_addr: &str) -> [Self; 2] { [ Self::Mysql( sqlx::mysql::MySqlPoolOptions::new() .max_connections(1) .connect(&format!("mysql://{mysql_addr}/public")) .await .unwrap(), ), Self::Postgres( sqlx::postgres::PgPoolOptions::new() .max_connections(1) .connect(&format!("postgres://{pg_addr}/public")) .await .unwrap(), ), ] } fn protocol(&self) -> &'static str { match self { Self::Mysql(_) => "mysql", Self::Postgres(_) => "postgres", } } /// Returns the last column of each row, binding 2 to a `?` in `sql`. async fn fetch(&self, sql: &str) -> Result, String> { let param = sql.contains('?').then_some(2i64); match self { Self::Mysql(pool) => fetch_last_column!(pool, sql, param), Self::Postgres(pool) => fetch_last_column!(pool, sql.replace('?', "$1"), param), } } } #[tokio::test(flavor = "multi_thread")] async fn test_prepared_statement_across_partition_column_change() { let (cluster, _home_guard) = repartition_cluster("prepared_statement_partition").await; let instance = cluster.fe_instance(); let mysql = setup_mysql_server_for_frontend_instance(instance.clone(), None).await; let pg = setup_pg_server_for_frontend_instance(instance.clone(), None).await; let mysql_addr = mysql.bind_addr().unwrap().to_string(); let pg_addr = pg.bind_addr().unwrap().to_string(); let mut failures = Vec::new(); for (index, case) in PREPARED_STATEMENT_CASES.iter().enumerate() { let table = format!("prepared_{index}"); let sql = |template: &str| template.replace("{t}", &table); for setup in case.setup { run_sql(instance, &sql(setup), QueryContext::arc()) .await .unwrap(); } let held = PreparedClient::connect_each(&mysql_addr, &pg_addr).await; for client in &held { for (query, _) in case.queries { client.fetch(&sql(query)).await.unwrap(); } } for ddl in case.ddl { run_sql(instance, &sql(ddl), QueryContext::arc()) .await .unwrap(); } let new = PreparedClient::connect_each(&mysql_addr, &pg_addr).await; for (held, new) in held.iter().zip(&new) { for (query, expected) in case.queries { let query = sql(query); let expected = match expected { // Runs first, so that the held statement of an `INSERT` writes last. Expected::NewStatement => Some(new.fetch(&query).await.unwrap()), Expected::Rows(rows) => Some(rows.to_vec()), Expected::Error => None, }; let actual = held.fetch(&query).await; if actual.as_ref().ok() != expected.as_ref() { failures.push(format!( "{}, {}, {query}: got {actual:?}, expected {expected:?}", case.name, held.protocol(), )); } } } } assert!(failures.is_empty(), "{failures:#?}"); } pub async fn test_partition_unpartitioned_mito(store_type: StorageType) { info!( "test_partition_unpartitioned_mito: store_type: {:?}", store_type ); let cluster_name = "test_partition_unpartitioned_mito"; let (store_config, _guard) = get_test_store_config(&store_type); let datanodes = 3u64; let mut builder = GreptimeDbClusterBuilder::new(cluster_name).await; if matches!(store_type, StorageType::File) { let home_dir = create_temp_dir("test_partition_unpartitioned_mito_data_home"); builder = builder.with_shared_home_dir(Arc::new(home_dir)); } let cluster = builder .with_datanodes(datanodes as u32) .with_store_config(store_config) .with_datanode_wal_config(DatanodeWalConfig::Noop) .with_metasrv_gc_config(GcSchedulerOptions { enable: true, gc_cooldown_period: Duration::from_nanos(1), ..Default::default() }) .with_datanode_gc_config(GcConfig { enable: true, lingering_time: Some(Duration::from_secs(0)), unknown_file_lingering_time: Duration::from_secs(0), ..Default::default() }) .build(true) .await; let query_ctx = QueryContext::arc(); let instance = cluster.fe_instance(); let sql = r#" CREATE TABLE `partition_unpartitioned_mito_table`( `id` INT, `city` STRING, `ts` TIMESTAMP TIME INDEX, PRIMARY KEY(`id`, `city`) ) ENGINE = mito; "#; run_sql(instance, sql, query_ctx.clone()).await.unwrap(); let sql = r#" INSERT INTO `partition_unpartitioned_mito_table` VALUES (1, 'New York', '2022-01-01 00:00:00'), (10, 'Paris', '2022-01-01 00:00:00'), (20, 'Beijing', '2022-01-01 00:00:00'); "#; run_sql(instance, sql, query_ctx.clone()).await.unwrap(); let sql = r#" ALTER TABLE `partition_unpartitioned_mito_table` PARTITION ON COLUMNS (`id`) ( `id` < 10, `id` >= 10 AND `id` < 20, `id` >= 20 ); "#; run_sql(instance, sql, query_ctx.clone()).await.unwrap(); // Wait for cache invalidation. tokio::time::sleep(Duration::from_millis(500)).await; let result = run_sql( instance, "SELECT * FROM `partition_unpartitioned_mito_table` ORDER BY `id`", query_ctx.clone(), ) .await .unwrap(); let expected = "\ +----+----------+---------------------+ | id | city | ts | +----+----------+---------------------+ | 1 | New York | 2022-01-01T00:00:00 | | 10 | Paris | 2022-01-01T00:00:00 | | 20 | Beijing | 2022-01-01T00:00:00 | +----+----------+---------------------+"; check_output_stream(result.data, expected).await; let result = run_sql( instance, "\ SELECT partition_expression, partition_description \ FROM information_schema.partitions \ WHERE table_name = 'partition_unpartitioned_mito_table' \ ORDER BY partition_ordinal_position;", query_ctx.clone(), ) .await .unwrap(); let expected_partitions = r#"+----------------------+-----------------------+ | partition_expression | partition_description | +----------------------+-----------------------+ | id | id < 10 | | id | id >= 10 AND id < 20 | | id | id >= 20 | +----------------------+-----------------------+"#; check_output_stream(result.data, expected_partitions).await; let sql = r#" INSERT INTO `partition_unpartitioned_mito_table` VALUES (5, 'London', '2022-01-02 00:00:00'), (15, 'Tokyo', '2022-01-02 00:00:00'), (25, 'Shanghai', '2022-01-02 00:00:00'); "#; run_sql(instance, sql, query_ctx.clone()).await.unwrap(); let result = run_sql( instance, "SELECT * FROM `partition_unpartitioned_mito_table` ORDER BY `id`", query_ctx.clone(), ) .await .unwrap(); let expected = "\ +----+----------+---------------------+ | id | city | ts | +----+----------+---------------------+ | 1 | New York | 2022-01-01T00:00:00 | | 5 | London | 2022-01-02T00:00:00 | | 10 | Paris | 2022-01-01T00:00:00 | | 15 | Tokyo | 2022-01-02T00:00:00 | | 20 | Beijing | 2022-01-01T00:00:00 | | 25 | Shanghai | 2022-01-02T00:00:00 | +----+----------+---------------------+"; check_output_stream(result.data, expected).await; run_sql( instance, "DROP TABLE `partition_unpartitioned_mito_table`", query_ctx.clone(), ) .await .unwrap(); } pub async fn test_repartition_on_columns_metadata_mito(store_type: StorageType) { info!( "test_repartition_on_columns_metadata_mito: store_type: {:?}", store_type ); let cluster_name = "test_repartition_on_columns_metadata_mito"; let (store_config, _guard) = get_test_store_config(&store_type); let datanodes = 3u64; let mut builder = GreptimeDbClusterBuilder::new(cluster_name).await; if matches!(store_type, StorageType::File) { let home_dir = create_temp_dir("test_repartition_on_columns_metadata_mito_data_home"); builder = builder.with_shared_home_dir(Arc::new(home_dir)); } let cluster = builder .with_datanodes(datanodes as u32) .with_store_config(store_config) .with_datanode_wal_config(DatanodeWalConfig::Noop) .with_metasrv_gc_config(GcSchedulerOptions { enable: true, gc_cooldown_period: Duration::from_nanos(1), ..Default::default() }) .with_datanode_gc_config(GcConfig { enable: true, lingering_time: Some(Duration::from_secs(0)), unknown_file_lingering_time: Duration::from_secs(0), ..Default::default() }) .build(true) .await; let query_ctx = QueryContext::arc(); let instance = cluster.fe_instance(); assert_on_columns_metadata_overwrite( instance, "repartition_on_columns_metadata_table", &repartition_on_columns_sql("repartition_on_columns_metadata_table"), query_ctx.clone(), ) .await; assert_on_columns_metadata_overwrite( instance, "split_on_columns_metadata_table", &split_on_columns_sql("split_on_columns_metadata_table"), query_ctx.clone(), ) .await; assert_on_columns_rejects_removed_remaining_column( instance, "repartition_on_columns_error_table", &repartition_on_columns_removed_column_sql("repartition_on_columns_error_table"), query_ctx.clone(), ) .await; assert_on_columns_rejects_removed_remaining_column( instance, "split_on_columns_error_table", &split_on_columns_removed_column_sql("split_on_columns_error_table"), query_ctx.clone(), ) .await; run_sql( instance, "DROP TABLE `repartition_on_columns_metadata_table`", query_ctx.clone(), ) .await .unwrap(); run_sql( instance, "DROP TABLE `split_on_columns_metadata_table`", query_ctx.clone(), ) .await .unwrap(); run_sql( instance, "DROP TABLE `repartition_on_columns_error_table`", query_ctx.clone(), ) .await .unwrap(); run_sql( instance, "DROP TABLE `split_on_columns_error_table`", query_ctx.clone(), ) .await .unwrap(); } pub async fn test_repartition_on_columns_data_correctness_mito(store_type: StorageType) { info!( "test_repartition_on_columns_data_correctness_mito: store_type: {:?}", store_type ); let cluster_name = "test_repartition_on_columns_data_correctness_mito"; let (store_config, _guard) = get_test_store_config(&store_type); let datanodes = 3u64; let mut builder = GreptimeDbClusterBuilder::new(cluster_name).await; if matches!(store_type, StorageType::File) { let home_dir = create_temp_dir("test_repartition_on_columns_data_correctness_mito_data_home"); builder = builder.with_shared_home_dir(Arc::new(home_dir)); } let cluster = builder .with_datanodes(datanodes as u32) .with_store_config(store_config) .with_datanode_wal_config(DatanodeWalConfig::Noop) .with_metasrv_gc_config(GcSchedulerOptions { enable: true, gc_cooldown_period: Duration::from_nanos(1), ..Default::default() }) .with_datanode_gc_config(GcConfig { enable: true, lingering_time: Some(Duration::from_secs(0)), unknown_file_lingering_time: Duration::from_secs(0), ..Default::default() }) .build(true) .await; let query_ctx = QueryContext::arc(); let instance = cluster.fe_instance(); assert_on_columns_data_correctness( instance, "repartition_on_columns_data_table", &repartition_on_columns_sql("repartition_on_columns_data_table"), query_ctx.clone(), ) .await; assert_on_columns_data_correctness( instance, "split_on_columns_data_table", &split_on_columns_sql("split_on_columns_data_table"), query_ctx.clone(), ) .await; run_sql( instance, "DROP TABLE `repartition_on_columns_data_table`", query_ctx.clone(), ) .await .unwrap(); run_sql( instance, "DROP TABLE `split_on_columns_data_table`", query_ctx.clone(), ) .await .unwrap(); } pub async fn test_partition_unpartitioned_metric(store_type: StorageType) { info!( "test_partition_unpartitioned_metric: store_type: {:?}", store_type ); let cluster_name = "test_partition_unpartitioned_metric"; let (store_config, _guard) = get_test_store_config(&store_type); let datanodes = 3u64; let mut builder = GreptimeDbClusterBuilder::new(cluster_name).await; if matches!(store_type, StorageType::File) { let home_dir = create_temp_dir("test_partition_unpartitioned_metric_data_home"); builder = builder.with_shared_home_dir(Arc::new(home_dir)); } let cluster = builder .with_datanodes(datanodes as u32) .with_store_config(store_config) .with_datanode_wal_config(DatanodeWalConfig::Noop) .with_metasrv_gc_config(GcSchedulerOptions { enable: true, gc_cooldown_period: Duration::from_nanos(1), ..Default::default() }) .with_datanode_gc_config(GcConfig { enable: true, lingering_time: Some(Duration::from_secs(0)), unknown_file_lingering_time: Duration::from_secs(0), ..Default::default() }) .build(true) .await; let query_ctx = QueryContext::arc(); let instance = cluster.fe_instance(); let sql = r#" CREATE TABLE `partition_unpartitioned_metric_phy`( `ts` TIMESTAMP TIME INDEX, `val` DOUBLE, `host` STRING PRIMARY KEY ) ENGINE = metric WITH ( "physical_metric_table" = "true" ); "#; run_sql(instance, sql, query_ctx.clone()).await.unwrap(); let sql = r#" CREATE TABLE `partition_unpartitioned_metric_log`( `ts` TIMESTAMP TIME INDEX, `val` DOUBLE, `host` STRING PRIMARY KEY ) ENGINE = metric WITH ( "on_physical_table" = "partition_unpartitioned_metric_phy" ); "#; run_sql(instance, sql, query_ctx.clone()).await.unwrap(); let sql = r#" INSERT INTO `partition_unpartitioned_metric_log` (`host`, `ts`, `val`) VALUES ('a_host', '2022-01-01 00:00:00', 1), ('z_host', '2022-01-01 00:00:00', 2); "#; run_sql(instance, sql, query_ctx.clone()).await.unwrap(); let sql = r#" ALTER TABLE `partition_unpartitioned_metric_phy` PARTITION ON COLUMNS (`host`) ( `host` < 'm', `host` >= 'm' ); "#; run_sql(instance, sql, query_ctx.clone()).await.unwrap(); // Wait for cache invalidation. tokio::time::sleep(Duration::from_millis(500)).await; let result = run_sql( instance, "SELECT * FROM `partition_unpartitioned_metric_log` ORDER BY `host`", query_ctx.clone(), ) .await .unwrap(); let expected = "\ +--------+---------------------+-----+ | host | ts | val | +--------+---------------------+-----+ | a_host | 2022-01-01T00:00:00 | 1.0 | | z_host | 2022-01-01T00:00:00 | 2.0 | +--------+---------------------+-----+"; check_output_stream(result.data, expected).await; let result = run_sql( instance, "\ SELECT partition_expression, partition_description \ FROM information_schema.partitions \ WHERE table_name = 'partition_unpartitioned_metric_phy' \ ORDER BY partition_ordinal_position;", query_ctx.clone(), ) .await .unwrap(); let expected_partitions = r#"+----------------------+-----------------------+ | partition_expression | partition_description | +----------------------+-----------------------+ | host | host < m | | host | host >= m | +----------------------+-----------------------+"#; check_output_stream(result.data, expected_partitions).await; let sql = r#" INSERT INTO `partition_unpartitioned_metric_log` (`host`, `ts`, `val`) VALUES ('b_host', '2022-01-02 00:00:00', 3), ('x_host', '2022-01-02 00:00:00', 4); "#; run_sql(instance, sql, query_ctx.clone()).await.unwrap(); let result = run_sql( instance, "SELECT * FROM `partition_unpartitioned_metric_log` ORDER BY `host`", query_ctx.clone(), ) .await .unwrap(); let expected = "\ +--------+---------------------+-----+ | host | ts | val | +--------+---------------------+-----+ | a_host | 2022-01-01T00:00:00 | 1.0 | | b_host | 2022-01-02T00:00:00 | 3.0 | | x_host | 2022-01-02T00:00:00 | 4.0 | | z_host | 2022-01-01T00:00:00 | 2.0 | +--------+---------------------+-----+"; check_output_stream(result.data, expected).await; run_sql( instance, "DROP TABLE `partition_unpartitioned_metric_log`", query_ctx.clone(), ) .await .unwrap(); run_sql( instance, "DROP TABLE `partition_unpartitioned_metric_phy`", query_ctx.clone(), ) .await .unwrap(); } /// Verifies table-id repartitioning, optionally with user columns and hash expressions. pub async fn test_partition_unpartitioned_metric_by_table_id( store_type: StorageType, mixed: bool, hashed: bool, flat_format: bool, primary_key_encoding: PrimaryKeyEncoding, ) { info!( "test_partition_unpartitioned_metric_by_table_id: store_type: {:?}", store_type ); let cluster_name = "test_partition_unpartitioned_metric_by_table_id"; let (store_config, _guard) = get_test_store_config(&store_type); let datanodes = 3u64; let mut builder = GreptimeDbClusterBuilder::new(cluster_name).await; if matches!(store_type, StorageType::File) { let home_dir = create_temp_dir("test_partition_unpartitioned_metric_by_table_id_data_home"); builder = builder.with_shared_home_dir(Arc::new(home_dir)); } let cluster = builder .with_datanodes(datanodes as u32) .with_store_config(store_config) .with_datanode_wal_config(DatanodeWalConfig::Noop) .with_metasrv_gc_config(GcSchedulerOptions { enable: true, gc_cooldown_period: Duration::from_nanos(1), ..Default::default() }) .with_datanode_gc_config(GcConfig { enable: true, lingering_time: Some(Duration::from_secs(0)), unknown_file_lingering_time: Duration::from_secs(0), ..Default::default() }) .build(true) .await; let query_ctx = QueryContext::arc(); let instance = cluster.fe_instance(); let sst_format = if flat_format { "flat" } else { "primary_key" }; let primary_key_encoding = match primary_key_encoding { PrimaryKeyEncoding::Dense => "dense", PrimaryKeyEncoding::Sparse => "sparse", }; let sql = format!( r#" CREATE TABLE `partition_table_id_metric_phy`( `ts` TIMESTAMP TIME INDEX, `val` DOUBLE, `host` STRING PRIMARY KEY ) ENGINE = metric WITH ( "physical_metric_table" = "true", "sst_format" = "{sst_format}", "primary_key_encoding" = "{primary_key_encoding}" ); "# ); run_sql(instance, &sql, query_ctx.clone()).await.unwrap(); for logical in [ "partition_table_id_metric_low", "partition_table_id_metric_high", ] { let sql = format!( r#" CREATE TABLE `{logical}`( `ts` TIMESTAMP TIME INDEX, `val` DOUBLE, `host` STRING PRIMARY KEY ) ENGINE = metric WITH ( "on_physical_table" = "partition_table_id_metric_phy" ); "# ); run_sql(instance, &sql, query_ctx.clone()).await.unwrap(); } run_sql( instance, r#" CREATE TABLE partition_table_id_metric_null_host ( ts TIMESTAMP TIME INDEX, val DOUBLE, host STRING PRIMARY KEY ) ENGINE = metric WITH ("on_physical_table" = "partition_table_id_metric_phy") "#, query_ctx.clone(), ) .await .unwrap(); run_sql( instance, "INSERT INTO partition_table_id_metric_null_host (ts, val) VALUES (0, 98)", query_ctx.clone(), ) .await .unwrap(); if mixed { run_sql( instance, r#"CREATE TABLE partition_table_id_metric_no_host ( ts TIMESTAMP TIME INDEX, val DOUBLE ) ENGINE = metric WITH ("on_physical_table" = "partition_table_id_metric_phy")"#, query_ctx.clone(), ) .await .unwrap(); } let sql = r#" INSERT INTO `partition_table_id_metric_low` (`host`, `ts`, `val`) VALUES ('a_host', '2022-01-01 00:00:00', 1); "#; run_sql(instance, sql, query_ctx.clone()).await.unwrap(); let sql = r#" INSERT INTO `partition_table_id_metric_high` (`host`, `ts`, `val`) VALUES ('a_host', '2022-01-01 00:00:00', 10); "#; run_sql(instance, sql, query_ctx.clone()).await.unwrap(); let low_table_id = get_table_id(&cluster.metasrv, "partition_table_id_metric_low").await; let high_table_id = get_table_id(&cluster.metasrv, "partition_table_id_metric_high").await; assert!(low_table_id < high_table_id); // Exercise repartition of persisted data in each SST/primary-key format. run_sql( instance, "ADMIN flush_table('partition_table_id_metric_phy')", query_ctx.clone(), ) .await .unwrap(); let (operand, boundary) = if hashed { let Value::Int32(boundary) = IcebergHash::evaluate_value(&Value::UInt32(high_table_id)).unwrap() else { panic!("expected an INT hash for the logical table id"); }; ("iceberg_hash(__table_id)", i64::from(boundary)) } else { (DATA_SCHEMA_TABLE_ID_COLUMN_NAME, i64::from(high_table_id)) }; let partition_columns = if mixed { "`__table_id`, `host`" } else { "`__table_id`" }; let expressions = if mixed { format!( "{operand} < {boundary}, {operand} >= {boundary} AND host < 'm', {operand} >= {boundary} AND host >= 'm'" ) } else { format!("{operand} < {boundary}, {operand} >= {boundary}") }; let sql = format!( "ALTER TABLE partition_table_id_metric_phy PARTITION ON COLUMNS ({partition_columns}) ({expressions})" ); run_sql(instance, &sql, query_ctx.clone()).await.unwrap(); // Refresh routes synchronously so the checks exercise the new partitions. instance.cache_invalidator().invalidate_all().unwrap(); let logical_table = instance .catalog_manager() .table("greptime", "public", "partition_table_id_metric_high", None) .await .unwrap() .unwrap(); let partition_columns = logical_table .table_info() .meta .partition_column_names() .cloned() .collect::>(); assert_eq!(partition_columns, if mixed { vec!["host"] } else { vec![] }); assert_eq!( logical_table .partition_rules() .unwrap() .extra_phy_cols_not_in_logical_table, vec![DATA_SCHEMA_TABLE_ID_COLUMN_NAME] ); if mixed { // A missing schema column cannot be supplied by the table identity context. assert_sql_err_eq( instance, "INSERT INTO partition_table_id_metric_no_host (ts, val) VALUES (1000, 99)", "Undefined column: host", query_ctx.clone(), ) .await; run_sql( instance, "DROP TABLE partition_table_id_metric_no_host", query_ctx.clone(), ) .await .unwrap(); } for (logical, expected) in [ ( "partition_table_id_metric_low", "+-----+\n| val |\n+-----+\n| 1.0 |\n+-----+", ), ( "partition_table_id_metric_high", "+------+\n| val |\n+------+\n| 10.0 |\n+------+", ), ] { let result = run_sql( instance, &format!("SELECT val FROM `{logical}` WHERE host = 'a_host'"), query_ctx.clone(), ) .await .unwrap(); check_output_stream(result.data, expected).await; } { // Hash predicates cannot always prune reads, so visible rows alone do not prove // correct routing. Observe writes on the actual data-region leaders as well. let physical_id = get_table_id(&cluster.metasrv, "partition_table_id_metric_phy").await; let (_, physical_route) = cluster .metasrv .table_metadata_manager() .table_route_manager() .get_physical_table_route(physical_id) .await .unwrap(); let written_bytes = || { physical_route .region_routes .iter() .map(|route| { let datanode = &cluster.datanode_instances[&route.leader_peer.as_ref().unwrap().id]; let data_region = RegionId::with_group_and_seq( physical_id, METRIC_DATA_REGION_GROUP, route.region.id.region_sequence(), ); let stats = datanode .region_server() .mito_engine() .unwrap() .get_region_statistic(data_region) .unwrap(); (route.region.id, stats.written_bytes) }) .collect::>() }; // The high table is exactly on the >= boundary. Its two hosts target both // host partitions when mixed, and the single >= partition otherwise. let expected_regions = physical_route .region_routes .iter() .filter(|route| { PartitionExpr::from_json_str(&route.region.partition_expr) .unwrap() .unwrap() .op != RestrictedOp::Lt }) .map(|route| route.region.id) .collect::>(); assert_eq!(expected_regions.len(), if mixed { 2 } else { 1 }); let before = written_bytes(); run_sql(instance, "INSERT INTO partition_table_id_metric_high (host, ts, val) VALUES ('c_host', '2022-01-02 00:00:00', 30), ('z_host', '2022-01-02 00:00:00', 40)", query_ctx.clone()).await.unwrap(); let actual_regions = written_bytes() .into_iter() .filter_map(|(region, bytes)| (bytes > before[®ion]).then_some(region)) .collect::>(); assert_eq!( actual_regions, expected_regions, "writes must reach the physical expression's regions" ); run_sql( instance, "ADMIN flush_table('partition_table_id_metric_phy')", query_ctx.clone(), ) .await .unwrap(); let result = run_sql( instance, "SELECT host, val FROM partition_table_id_metric_high WHERE host IN ('c_host', 'z_host') ORDER BY host", query_ctx.clone(), ) .await .unwrap(); check_output_stream( result.data, "\ +--------+------+ | host | val | +--------+------+ | c_host | 30.0 | | z_host | 40.0 | +--------+------+", ) .await; run_sql( instance, "DELETE FROM partition_table_id_metric_high WHERE host IN ('c_host', 'z_host')", query_ctx.clone(), ) .await .unwrap(); } let sql = r#" INSERT INTO `partition_table_id_metric_low` (`host`, `ts`, `val`) VALUES ('b_host', '2022-01-02 00:00:00', 2); "#; run_sql(instance, sql, query_ctx.clone()).await.unwrap(); let sql = r#" INSERT INTO `partition_table_id_metric_high` (`host`, `ts`, `val`) VALUES ('b_host', '2022-01-02 00:00:00', 20); "#; run_sql(instance, sql, query_ctx.clone()).await.unwrap(); for logical in [ "partition_table_id_metric_low", "partition_table_id_metric_high", ] { let result = run_sql( instance, &format!("SELECT host FROM `{logical}` WHERE host = 'b_host'"), query_ctx.clone(), ) .await .unwrap(); let expected = "\ +--------+ | host | +--------+ | b_host | +--------+"; check_output_stream(result.data, expected).await; } run_sql( instance, "ADMIN flush_table('partition_table_id_metric_phy')", query_ctx.clone(), ) .await .unwrap(); run_sql( instance, "INSERT INTO partition_table_id_metric_null_host (ts, val) VALUES (1000, 99)", query_ctx.clone(), ) .await .unwrap(); run_sql( instance, "ADMIN flush_table('partition_table_id_metric_phy')", query_ctx.clone(), ) .await .unwrap(); let output = run_sql( instance, "SELECT val FROM partition_table_id_metric_null_host WHERE ts = 1000", query_ctx.clone(), ) .await .unwrap(); check_output_stream( output.data, "+------+\n| val |\n+------+\n| 99.0 |\n+------+", ) .await; let output = run_sql( instance, "SELECT val FROM partition_table_id_metric_null_host ORDER BY ts", query_ctx.clone(), ) .await .unwrap(); check_output_stream( output.data, "+------+\n| val |\n+------+\n| 98.0 |\n| 99.0 |\n+------+", ) .await; // Logical tables created after repartition must inherit usable routing metadata. run_sql( instance, r#" CREATE TABLE partition_table_id_metric_new ( ts TIMESTAMP TIME INDEX, val DOUBLE, host STRING PRIMARY KEY ) ENGINE = metric WITH ("on_physical_table" = "partition_table_id_metric_phy") "#, query_ctx.clone(), ) .await .unwrap(); run_sql( instance, "INSERT INTO partition_table_id_metric_new (host, ts, val) VALUES ('new_host', 1000, 100)", query_ctx.clone(), ) .await .unwrap(); let output = run_sql( instance, "SELECT val FROM partition_table_id_metric_new", query_ctx.clone(), ) .await .unwrap(); check_output_stream( output.data, "+-------+\n| val |\n+-------+\n| 100.0 |\n+-------+", ) .await; run_sql( instance, "DELETE FROM partition_table_id_metric_new WHERE host = 'new_host'", query_ctx.clone(), ) .await .unwrap(); let output = run_sql( instance, "SELECT count(*) AS n FROM partition_table_id_metric_new", query_ctx.clone(), ) .await .unwrap(); check_output_stream(output.data, "+---+\n| n |\n+---+\n| 0 |\n+---+").await; let sql = r#" DELETE FROM `partition_table_id_metric_low` WHERE `host` = 'a_host'; "#; run_sql(instance, sql, query_ctx.clone()).await.unwrap(); let result = run_sql( instance, "SELECT * FROM `partition_table_id_metric_low` ORDER BY `host`", query_ctx.clone(), ) .await .unwrap(); let expected = "\ +--------+---------------------+-----+ | host | ts | val | +--------+---------------------+-----+ | b_host | 2022-01-02T00:00:00 | 2.0 | +--------+---------------------+-----+"; check_output_stream(result.data, expected).await; let result = run_sql( instance, "SELECT * FROM `partition_table_id_metric_high` ORDER BY `host`", query_ctx.clone(), ) .await .unwrap(); let expected = "\ +--------+---------------------+------+ | host | ts | val | +--------+---------------------+------+ | a_host | 2022-01-01T00:00:00 | 10.0 | | b_host | 2022-01-02T00:00:00 | 20.0 | +--------+---------------------+------+"; check_output_stream(result.data, expected).await; let result = run_sql( instance, "\ SELECT count(*) AS partition_count \ FROM information_schema.partitions \ WHERE table_name = 'partition_table_id_metric_phy';", query_ctx.clone(), ) .await .unwrap(); let count = if mixed { 3 } else { 2 }; let expected = format!( "+-----------------+\n| partition_count |\n+-----------------+\n| {count} |\n+-----------------+" ); check_output_stream(result.data, &expected).await; for table in [ "partition_table_id_metric_new", "partition_table_id_metric_null_host", "partition_table_id_metric_low", "partition_table_id_metric_high", "partition_table_id_metric_phy", ] { run_sql( instance, &format!("DROP TABLE `{table}`"), query_ctx.clone(), ) .await .unwrap(); } } async fn get_table_id(metasrv: &Arc, table_name: &str) -> TableId { metasrv .table_metadata_manager() .table_name_manager() .get(TableNameKey::new( DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME, table_name, )) .await .unwrap() .unwrap() .table_id() } async fn trigger_table_gc(metasrv: &Arc, table_name: &str) { info!("triggering table gc for table: {}", table_name); let table_metadata_manager = metasrv.table_metadata_manager(); let table_id = get_table_id(metasrv, table_name).await; let (_, table_route_value) = table_metadata_manager .table_route_manager() .get_physical_table_route(table_id) .await .unwrap(); let region_ids = table_route_value .region_routes .iter() .map(|r| r.region.id) .collect::>(); let procedure = BatchGcProcedure::new( metasrv.mailbox().clone(), metasrv.table_metadata_manager().clone(), metasrv.runtime_switch_manager().clone(), metasrv.options().grpc.server_addr.clone(), region_ids.clone(), false, // full_file_listing Duration::from_secs(10), // timeout Default::default(), ); // Submit the procedure to the procedure manager let procedure_with_id = ProcedureWithId::with_random_id(Box::new(procedure)); let mut watcher = metasrv .procedure_manager() .submit(procedure_with_id) .await .unwrap(); watcher::wait(&mut watcher).await.unwrap(); } async fn assert_table_sst_files_match_manifests(cluster: &GreptimeDbCluster, table_name: &str) { // Other tables may retain compacted SSTs until their own GC runs. let table_id = get_table_id(&cluster.metasrv, table_name).await; let table_dir = format!("/{table_id}/"); let retain_table_files = |files: BTreeSet| { files .into_iter() .filter(|path| path.contains(&table_dir)) .collect::>() }; let storage_files = retain_table_files(cluster.list_sst_files_from_all_datanodes().await); let manifest_files = retain_table_files(cluster.list_sst_files_from_manifests().await); assert_eq!(storage_files, manifest_files); } async fn trigger_full_gc(ticker: &GcTickerRef) { info!("triggering full gc"); let (tx, rx) = oneshot::channel(); ticker .sender .send(gc::Event::Manually { sender: tx, region_ids: None, full_file_listing: None, timeout: None, procedure_context: ProcedureContext::from_event_context(PersistentEventContext::new( TriggerReason::Manual, )), }) .await .unwrap(); let _ = rx.await.unwrap().unwrap(); } async fn cluster_manifest_index_entries( cluster: &GreptimeDbCluster, ) -> Vec<(String, RegionId, RegionId)> { let mut entries = Vec::new(); for datanode in cluster.datanode_instances.values() { let region_server = datanode.region_server(); let mito = region_server.mito_engine().unwrap(); entries.extend( mito.all_ssts_from_manifest() .await .into_iter() .filter_map(|entry| { entry.index_file_path.map(|index_file_path| { (index_file_path, entry.origin_region_id, entry.region_id) }) }), ); } entries } async fn cluster_manifest_index_paths(cluster: &GreptimeDbCluster) -> BTreeSet { cluster_manifest_index_entries(cluster) .await .into_iter() .map(|(index_file_path, _, _)| index_file_path) .collect() } fn query_partitions_sql(table_name: &str) -> String { // We query information_schema.partitions to assert repartition results across engines, // rather than relying on SHOW CREATE TABLE formatting differences. format!( "\ SELECT table_catalog, table_schema, table_name, partition_name, partition_expression, \ partition_description, greptime_partition_id, partition_ordinal_position \ FROM information_schema.partitions \ WHERE table_name = '{}' \ ORDER BY partition_ordinal_position;", table_name ) } pub async fn test_repartition_mito(store_type: StorageType, flat_format: bool) { info!( "test_repartition_mito: store_type: {:?}, flat_format: {:?}", store_type, flat_format ); let cluster_name = "test_repartition_mito"; let (store_config, _guard) = get_test_store_config(&store_type); let datanodes = 3u64; let mut builder = GreptimeDbClusterBuilder::new(cluster_name).await; if matches!(store_type, StorageType::File) { let home_dir = create_temp_dir("test_repartition_mito_data_home"); builder = builder.with_shared_home_dir(Arc::new(home_dir)); } let cluster = builder .with_datanodes(datanodes as u32) .with_store_config(store_config) .with_datanode_wal_config(DatanodeWalConfig::Noop) .with_metasrv_gc_config(GcSchedulerOptions { enable: true, gc_cooldown_period: Duration::from_nanos(1), ..Default::default() }) .with_datanode_gc_config(GcConfig { enable: true, lingering_time: Some(Duration::from_secs(0)), unknown_file_lingering_time: Duration::from_secs(0), ..Default::default() }) .build(true) .await; let metasrv = &cluster.metasrv; let ticker = metasrv.gc_ticker().unwrap(); let query_ctx = QueryContext::arc(); let instance = cluster.fe_instance(); // 1. Setup: Create a table with partitions (format varies by test case) let sql = if flat_format { r#" CREATE TABLE `repartition_mito_table`( `id` INT, `city` STRING, `ts` TIMESTAMP TIME INDEX, PRIMARY KEY(`id`, `city`) ) PARTITION ON COLUMNS (`id`) ( `id` < 10, `id` >= 10 AND `id` < 20, `id` >= 20 ) ENGINE = mito WITH ( 'sst_format' = 'flat' ); "# } else { r#" CREATE TABLE `repartition_mito_table`( `id` INT, `city` STRING, `ts` TIMESTAMP TIME INDEX, PRIMARY KEY(`id`, `city`) ) PARTITION ON COLUMNS (`id`) ( `id` < 10, `id` >= 10 AND `id` < 20, `id` >= 20 ) ENGINE = mito; "# }; run_sql(instance, sql, query_ctx.clone()).await.unwrap(); let sql = r#" INSERT INTO `repartition_mito_table` VALUES (1, 'New York', '2022-01-01 00:00:00'), (5, 'London', '2022-01-01 00:00:00'), (10, 'Paris', '2022-01-01 00:00:00'), (15, 'Tokyo', '2022-01-01 00:00:00'), (20, 'Beijing', '2022-01-01 00:00:00'), (25, 'Shanghai', '2022-01-01 00:00:00'); "#; run_sql(instance, sql, query_ctx.clone()).await.unwrap(); let result = run_sql( instance, "SELECT * FROM `repartition_mito_table` ORDER BY `id`", query_ctx.clone(), ) .await .unwrap(); let expected = "\ +----+----------+---------------------+ | id | city | ts | +----+----------+---------------------+ | 1 | New York | 2022-01-01T00:00:00 | | 5 | London | 2022-01-01T00:00:00 | | 10 | Paris | 2022-01-01T00:00:00 | | 15 | Tokyo | 2022-01-01T00:00:00 | | 20 | Beijing | 2022-01-01T00:00:00 | | 25 | Shanghai | 2022-01-01T00:00:00 | +----+----------+---------------------+"; check_output_stream(result.data, expected).await; // 2. Split Partition let sql = r#" ALTER TABLE `repartition_mito_table` SPLIT PARTITION ( `id` < 10 ) INTO ( `id` < 5, `id` >= 5 AND `id` < 10 ); "#; let _result = run_sql(instance, sql, query_ctx.clone()).await.unwrap(); // Wait for cache invalidation tokio::time::sleep(Duration::from_millis(500)).await; let result = run_sql( instance, "SELECT * FROM `repartition_mito_table` ORDER BY `id`", query_ctx.clone(), ) .await .unwrap(); let expected = "\ +----+----------+---------------------+ | id | city | ts | +----+----------+---------------------+ | 1 | New York | 2022-01-01T00:00:00 | | 5 | London | 2022-01-01T00:00:00 | | 10 | Paris | 2022-01-01T00:00:00 | | 15 | Tokyo | 2022-01-01T00:00:00 | | 20 | Beijing | 2022-01-01T00:00:00 | | 25 | Shanghai | 2022-01-01T00:00:00 | +----+----------+---------------------+"; check_output_stream(result.data, expected).await; trigger_table_gc(metasrv, "repartition_mito_table").await; // Should be ok before compact. let result = run_sql( instance, "SELECT * FROM `repartition_mito_table` ORDER BY `id`", query_ctx.clone(), ) .await .unwrap(); check_output_stream(result.data, expected).await; assert_table_sst_files_match_manifests(&cluster, "repartition_mito_table").await; // It should be ok, if we try to compact the table after split partition. let compact_sql = "ADMIN COMPACT_TABLE('repartition_mito_table', 'swcs', '3600')"; let _result = run_sql(instance, compact_sql, query_ctx.clone()) .await .unwrap(); // Should be no change after compact. let result = run_sql( instance, "SELECT * FROM `repartition_mito_table` ORDER BY `id`", query_ctx.clone(), ) .await .unwrap(); check_output_stream(result.data, expected).await; // Trigger GC to clean up the compacted files. trigger_table_gc(metasrv, "repartition_mito_table").await; // Should be no change after GC. let result = run_sql( instance, "SELECT * FROM `repartition_mito_table` ORDER BY `id`", query_ctx.clone(), ) .await .unwrap(); check_output_stream(result.data, expected).await; assert_table_sst_files_match_manifests(&cluster, "repartition_mito_table").await; let result = run_sql( instance, &query_partitions_sql("repartition_mito_table"), query_ctx.clone(), ) .await .unwrap(); let expected_create_table_after_split = r#"+---------------+--------------+------------------------+----------------+----------------------+-----------------------+-----------------------+----------------------------+ | table_catalog | table_schema | table_name | partition_name | partition_expression | partition_description | greptime_partition_id | partition_ordinal_position | +---------------+--------------+------------------------+----------------+----------------------+-----------------------+-----------------------+----------------------------+ | greptime | public | repartition_mito_table | p0 | id | id < 5 | 4398046511104 | 1 | | greptime | public | repartition_mito_table | p1 | id | id >= 10 AND id < 20 | 4398046511105 | 2 | | greptime | public | repartition_mito_table | p2 | id | id >= 20 | 4398046511106 | 3 | | greptime | public | repartition_mito_table | p3 | id | id >= 5 AND id < 10 | 4398046511107 | 4 | +---------------+--------------+------------------------+----------------+----------------------+-----------------------+-----------------------+----------------------------+"#; check_output_stream(result.data, expected_create_table_after_split).await; let sql = r#"INSERT INTO `repartition_mito_table` VALUES (2, 'Split1', '2022-01-02 00:00:00');"#; run_sql(instance, sql, query_ctx.clone()).await.unwrap(); let sql = r#"INSERT INTO `repartition_mito_table` VALUES (7, 'Split2', '2022-01-02 00:00:00');"#; run_sql(instance, sql, query_ctx.clone()).await.unwrap(); let result = run_sql( instance, "SELECT * FROM `repartition_mito_table` WHERE `id` IN (2, 7) ORDER BY `id`", query_ctx.clone(), ) .await .unwrap(); let expected_split_inserts = "\ +----+--------+---------------------+ | id | city | ts | +----+--------+---------------------+ | 2 | Split1 | 2022-01-02T00:00:00 | | 7 | Split2 | 2022-01-02T00:00:00 | +----+--------+---------------------+"; check_output_stream(result.data, expected_split_inserts).await; // 3. Merge Partition let sql = r#" ALTER TABLE `repartition_mito_table` MERGE PARTITION ( `id` >= 10 AND `id` < 20, `id` >= 20 ); "#; run_sql(instance, sql, query_ctx.clone()).await.unwrap(); // Wait for cache invalidation tokio::time::sleep(Duration::from_millis(500)).await; let result = run_sql( instance, "SELECT * FROM `repartition_mito_table` ORDER BY `id`", query_ctx.clone(), ) .await .unwrap(); let expected_all = "\ +----+----------+---------------------+ | id | city | ts | +----+----------+---------------------+ | 1 | New York | 2022-01-01T00:00:00 | | 2 | Split1 | 2022-01-02T00:00:00 | | 5 | London | 2022-01-01T00:00:00 | | 7 | Split2 | 2022-01-02T00:00:00 | | 10 | Paris | 2022-01-01T00:00:00 | | 15 | Tokyo | 2022-01-01T00:00:00 | | 20 | Beijing | 2022-01-01T00:00:00 | | 25 | Shanghai | 2022-01-01T00:00:00 | +----+----------+---------------------+"; check_output_stream(result.data, expected_all).await; trigger_table_gc(metasrv, "repartition_mito_table").await; // Trigger GC to clean up the compacted files. trigger_full_gc(&ticker).await; let result = run_sql( instance, "SELECT * FROM `repartition_mito_table` ORDER BY `id`", query_ctx.clone(), ) .await .unwrap(); check_output_stream(result.data, expected_all).await; assert_table_sst_files_match_manifests(&cluster, "repartition_mito_table").await; // It should be ok, if we try to compact the table after merge partition. let compact_sql = "ADMIN COMPACT_TABLE('repartition_mito_table', 'swcs', '3600')"; let _result = run_sql(instance, compact_sql, query_ctx.clone()) .await .unwrap(); // Should be no change after compact. let result = run_sql( instance, "SELECT * FROM `repartition_mito_table` ORDER BY `id`", query_ctx.clone(), ) .await .unwrap(); check_output_stream(result.data, expected_all).await; trigger_table_gc(metasrv, "repartition_mito_table").await; trigger_full_gc(&ticker).await; // Should be no change after GC. let result = run_sql( instance, "SELECT * FROM `repartition_mito_table` ORDER BY `id`", query_ctx.clone(), ) .await .unwrap(); check_output_stream(result.data, expected_all).await; assert_table_sst_files_match_manifests(&cluster, "repartition_mito_table").await; let result = run_sql( instance, &query_partitions_sql("repartition_mito_table"), query_ctx.clone(), ) .await .unwrap(); let expected_create_table_after_merge = r#"+---------------+--------------+------------------------+----------------+----------------------+-----------------------+-----------------------+----------------------------+ | table_catalog | table_schema | table_name | partition_name | partition_expression | partition_description | greptime_partition_id | partition_ordinal_position | +---------------+--------------+------------------------+----------------+----------------------+-----------------------+-----------------------+----------------------------+ | greptime | public | repartition_mito_table | p0 | id | id < 5 | 4398046511104 | 1 | | greptime | public | repartition_mito_table | p1 | id | id >= 10 | 4398046511105 | 2 | | greptime | public | repartition_mito_table | p2 | id | id >= 5 AND id < 10 | 4398046511107 | 3 | +---------------+--------------+------------------------+----------------+----------------------+-----------------------+-----------------------+----------------------------+"#; check_output_stream(result.data, expected_create_table_after_merge).await; let sql = r#"INSERT INTO `repartition_mito_table` VALUES (12, 'Merge1', '2022-01-03 00:00:00');"#; run_sql(instance, sql, query_ctx.clone()).await.unwrap(); let sql = r#"INSERT INTO `repartition_mito_table` VALUES (30, 'Merge2', '2022-01-03 00:00:00');"#; run_sql(instance, sql, query_ctx.clone()).await.unwrap(); let result = run_sql( instance, "SELECT * FROM `repartition_mito_table` WHERE `id` IN (12, 30) ORDER BY `id`", query_ctx.clone(), ) .await .unwrap(); let expected_merge_inserts = "\ +----+--------+---------------------+ | id | city | ts | +----+--------+---------------------+ | 12 | Merge1 | 2022-01-03T00:00:00 | | 30 | Merge2 | 2022-01-03T00:00:00 | +----+--------+---------------------+"; check_output_stream(result.data, expected_merge_inserts).await; run_sql( instance, "DROP TABLE `repartition_mito_table`", query_ctx.clone(), ) .await .unwrap(); } pub async fn test_repartition_metric( store_type: StorageType, flat_format: bool, primary_key_encoding: PrimaryKeyEncoding, ) { info!( "test_repartition_metric: store_type: {:?}, flat_format: {:?}, primary_key_encoding: {:?}", store_type, flat_format, primary_key_encoding ); let cluster_name = "test_repartition_metric"; let (store_config, _guard) = get_test_store_config(&store_type); let datanodes = 3u64; let mut builder = GreptimeDbClusterBuilder::new(cluster_name).await; if matches!(store_type, StorageType::File) { let home_dir = create_temp_dir("test_repartition_metric_data_home"); builder = builder.with_shared_home_dir(Arc::new(home_dir)); } let cluster = builder .with_datanodes(datanodes as u32) .with_store_config(store_config) .with_datanode_wal_config(DatanodeWalConfig::Noop) .with_metasrv_gc_config(GcSchedulerOptions { enable: true, gc_cooldown_period: Duration::from_nanos(1), ..Default::default() }) .with_datanode_gc_config(GcConfig { enable: true, lingering_time: Some(Duration::from_secs(0)), unknown_file_lingering_time: Duration::from_secs(0), ..Default::default() }) .build(true) .await; let metasrv = &cluster.metasrv; let ticker = metasrv.gc_ticker().unwrap(); let query_ctx = QueryContext::arc(); let instance = cluster.fe_instance(); // Explicitly configure sst_format and primary key encoding to cover the matrix. let sst_format = if flat_format { "flat" } else { "primary_key" }; let primary_key_encoding = match primary_key_encoding { PrimaryKeyEncoding::Dense => "dense", PrimaryKeyEncoding::Sparse => "sparse", }; let sql = format!( r#" CREATE TABLE `repart_phy_metric`( `ts` TIMESTAMP TIME INDEX, `val` DOUBLE, `host` STRING PRIMARY KEY ) PARTITION ON COLUMNS (`host`) ( `host` < 'm', `host` >= 'm' ) ENGINE = metric WITH ( "physical_metric_table" = "", 'sst_format' = '{sst_format}', "primary_key_encoding" = "{primary_key_encoding}", "index.type" = "inverted", ); "# ); run_sql(instance, &sql, query_ctx.clone()).await.unwrap(); // A second logical table exercises repartition behavior across multiple logical tables // sharing the same physical metric table. let sql = r#" CREATE TABLE `repart_log_metric`( `ts` TIMESTAMP TIME INDEX, `val` DOUBLE, `host` STRING PRIMARY KEY ) ENGINE = metric WITH ("on_physical_table" = "repart_phy_metric"); "#; run_sql(instance, sql, query_ctx.clone()).await.unwrap(); let sql = r#" CREATE TABLE `repart_log_metric_job`( `ts` TIMESTAMP TIME INDEX, `val` DOUBLE, `job` STRING PRIMARY KEY ) ENGINE = metric WITH ("on_physical_table" = "repart_phy_metric"); "#; run_sql(instance, sql, query_ctx.clone()).await.unwrap(); let sql = r#" INSERT INTO `repart_log_metric` (`host`, `ts`, `val`) VALUES ('a_host', '2022-01-01 00:00:00', 1), ('z_host', '2022-01-01 00:00:00', 2); "#; run_sql(instance, sql, query_ctx.clone()).await.unwrap(); let result = run_sql( instance, "SELECT * FROM `repart_log_metric` ORDER BY `host`", query_ctx.clone(), ) .await .unwrap(); let expected = "\ +--------+---------------------+-----+ | host | ts | val | +--------+---------------------+-----+ | a_host | 2022-01-01T00:00:00 | 1.0 | | z_host | 2022-01-01T00:00:00 | 2.0 | +--------+---------------------+-----+"; check_output_stream(result.data, expected).await; // Split physical table partition let sql = r#" ALTER TABLE `repart_phy_metric` SPLIT PARTITION ( `host` < 'm' ) INTO ( `host` < 'g', `host` >= 'g' AND `host` < 'm' ); "#; run_sql(instance, sql, query_ctx.clone()).await.unwrap(); // Wait for cache invalidation tokio::time::sleep(Duration::from_millis(500)).await; let result = run_sql( instance, &query_partitions_sql("repart_phy_metric"), query_ctx.clone(), ) .await .unwrap(); // Partition ids and order are expected to be stable within a single test run. let expected_create_table_after_split = r#"+---------------+--------------+-------------------+----------------+----------------------+------------------------+-----------------------+----------------------------+ | table_catalog | table_schema | table_name | partition_name | partition_expression | partition_description | greptime_partition_id | partition_ordinal_position | +---------------+--------------+-------------------+----------------+----------------------+------------------------+-----------------------+----------------------------+ | greptime | public | repart_phy_metric | p0 | host | host < g | 4398046511104 | 1 | | greptime | public | repart_phy_metric | p1 | host | host >= m | 4398046511105 | 2 | | greptime | public | repart_phy_metric | p2 | host | host >= g AND host < m | 4398046511106 | 3 | +---------------+--------------+-------------------+----------------+----------------------+------------------------+-----------------------+----------------------------+"#; check_output_stream(result.data, expected_create_table_after_split).await; let regions = cluster.list_all_regions().await; let region0 = regions.get(&RegionId::new(1024, 0)).unwrap(); let region2 = regions.get(&RegionId::new(1024, 2)).unwrap(); let primary_keys_in_region_0 = region0 .metadata() .primary_key_columns() .cloned() .collect::>(); let primary_keys_in_region_2 = region2 .metadata() .primary_key_columns() .cloned() .collect::>(); info!("primary_keys_in_region_0: {:?}", primary_keys_in_region_0); info!("primary_keys_in_region_2: {:?}", primary_keys_in_region_2); assert_eq!(primary_keys_in_region_0, primary_keys_in_region_2); let sql = r#" ALTER TABLE `repart_log_metric_job` ADD COLUMN `cpu` STRING PRIMARY KEY; "#; run_sql(instance, sql, query_ctx.clone()).await.unwrap(); let result = run_sql( instance, "SELECT * FROM `repart_log_metric` ORDER BY `host`", query_ctx.clone(), ) .await .unwrap(); let expected = "\ +--------+---------------------+-----+ | host | ts | val | +--------+---------------------+-----+ | a_host | 2022-01-01T00:00:00 | 1.0 | | z_host | 2022-01-01T00:00:00 | 2.0 | +--------+---------------------+-----+"; check_output_stream(result.data, expected).await; trigger_table_gc(metasrv, "repart_phy_metric").await; // Should be ok before compact. let result = run_sql( instance, "SELECT * FROM `repart_log_metric` ORDER BY `host`", query_ctx.clone(), ) .await .unwrap(); check_output_stream(result.data, expected).await; assert_table_sst_files_match_manifests(&cluster, "repart_phy_metric").await; // It should be ok, if we try to compact the table after split partition. let compact_sql = "ADMIN COMPACT_TABLE('repart_phy_metric', 'swcs', '3600')"; let _result = run_sql(instance, compact_sql, query_ctx.clone()) .await .unwrap(); // Should be no change after compact. let result = run_sql( instance, "SELECT * FROM `repart_log_metric` ORDER BY `host`", query_ctx.clone(), ) .await .unwrap(); check_output_stream(result.data, expected).await; // Trigger GC to clean up the compacted files. trigger_table_gc(metasrv, "repart_phy_metric").await; // Should be no change after GC. let result = run_sql( instance, "SELECT * FROM `repart_log_metric` ORDER BY `host`", query_ctx.clone(), ) .await .unwrap(); check_output_stream(result.data, expected).await; assert_table_sst_files_match_manifests(&cluster, "repart_phy_metric").await; let sql = r#"INSERT INTO `repart_log_metric` (`host`, `ts`, `val`) VALUES ('b_host', '2022-01-02 00:00:00', 3.0);"#; run_sql(instance, sql, query_ctx.clone()).await.unwrap(); let sql = r#"INSERT INTO `repart_log_metric` (`host`, `ts`, `val`) VALUES ('h_host', '2022-01-02 00:00:00', 4.0);"#; run_sql(instance, sql, query_ctx.clone()).await.unwrap(); let result = run_sql( instance, "SELECT * FROM `repart_log_metric` WHERE `host` IN ('b_host', 'h_host') ORDER BY `host`", query_ctx.clone(), ) .await .unwrap(); let expected = "\ +--------+---------------------+-----+ | host | ts | val | +--------+---------------------+-----+ | b_host | 2022-01-02T00:00:00 | 3.0 | | h_host | 2022-01-02T00:00:00 | 4.0 | +--------+---------------------+-----+"; check_output_stream(result.data, expected).await; let sql = r#" ALTER TABLE `repart_phy_metric` MERGE PARTITION ( `host` < 'g', `host` >= 'g' AND `host` < 'm' ); "#; run_sql(instance, sql, query_ctx.clone()).await.unwrap(); // Wait for cache invalidation tokio::time::sleep(Duration::from_millis(500)).await; let result = run_sql( instance, &query_partitions_sql("repart_phy_metric"), query_ctx.clone(), ) .await .unwrap(); let expected_create_table_after_merge = r#"+---------------+--------------+-------------------+----------------+----------------------+-----------------------+-----------------------+----------------------------+ | table_catalog | table_schema | table_name | partition_name | partition_expression | partition_description | greptime_partition_id | partition_ordinal_position | +---------------+--------------+-------------------+----------------+----------------------+-----------------------+-----------------------+----------------------------+ | greptime | public | repart_phy_metric | p0 | host | host < m | 4398046511104 | 1 | | greptime | public | repart_phy_metric | p1 | host | host >= m | 4398046511105 | 2 | +---------------+--------------+-------------------+----------------+----------------------+-----------------------+-----------------------+----------------------------+"#; check_output_stream(result.data, expected_create_table_after_merge).await; let result = run_sql( instance, "SELECT * FROM `repart_log_metric` ORDER BY `host`", query_ctx.clone(), ) .await .unwrap(); let expected = "\ +--------+---------------------+-----+ | host | ts | val | +--------+---------------------+-----+ | a_host | 2022-01-01T00:00:00 | 1.0 | | b_host | 2022-01-02T00:00:00 | 3.0 | | h_host | 2022-01-02T00:00:00 | 4.0 | | z_host | 2022-01-01T00:00:00 | 2.0 | +--------+---------------------+-----+"; check_output_stream(result.data, expected).await; trigger_table_gc(metasrv, "repart_phy_metric").await; trigger_full_gc(&ticker).await; // Should be no change after GC. let result = run_sql( instance, "SELECT * FROM `repart_log_metric` ORDER BY `host`", query_ctx.clone(), ) .await .unwrap(); check_output_stream(result.data, expected).await; assert_table_sst_files_match_manifests(&cluster, "repart_phy_metric").await; // It should be ok, if we try to compact the table after merge partition. let compact_sql = "ADMIN COMPACT_TABLE('repart_phy_metric', 'swcs', '3600')"; let _result = run_sql(instance, compact_sql, query_ctx.clone()) .await .unwrap(); // Should be no change after compact. let result = run_sql( instance, "SELECT * FROM `repart_log_metric` ORDER BY `host`", query_ctx.clone(), ) .await .unwrap(); check_output_stream(result.data, expected).await; // Trigger GC to clean up the compacted files. trigger_table_gc(metasrv, "repart_phy_metric").await; trigger_full_gc(&ticker).await; // Should be no change after GC. let result = run_sql( instance, "SELECT * FROM `repart_log_metric` ORDER BY `host`", query_ctx.clone(), ) .await .unwrap(); check_output_stream(result.data, expected).await; assert_table_sst_files_match_manifests(&cluster, "repart_phy_metric").await; let sql = r#"INSERT INTO `repart_log_metric` (`host`, `ts`, `val`) VALUES ('c_host', '2022-01-03 00:00:00', 5.0);"#; run_sql(instance, sql, query_ctx.clone()).await.unwrap(); let result = run_sql( instance, "SELECT * FROM `repart_log_metric` WHERE `host` = 'c_host'", query_ctx.clone(), ) .await .unwrap(); let expected = "\ +--------+---------------------+-----+ | host | ts | val | +--------+---------------------+-----+ | c_host | 2022-01-03T00:00:00 | 5.0 | +--------+---------------------+-----+"; check_output_stream(result.data, expected).await; run_sql( instance, "DROP TABLE `repart_log_metric_job`", query_ctx.clone(), ) .await .unwrap(); run_sql( instance, "DROP TABLE `repart_log_metric`", query_ctx.clone(), ) .await .unwrap(); run_sql( instance, "DROP TABLE `repart_phy_metric`", query_ctx.clone(), ) .await .unwrap(); } async fn create_on_columns_test_table( instance: &Arc, table_name: &str, query_ctx: QueryContextRef, ) { let sql = format!( r#" CREATE TABLE `{table_name}`( `id` INT, `city` STRING, `ts` TIMESTAMP TIME INDEX, PRIMARY KEY(`id`, `city`) ) PARTITION ON COLUMNS (`id`) ( `id` < 10, `id` >= 10 AND `id` < 20, `id` >= 20 ) ENGINE = mito; "# ); run_sql(instance, &sql, query_ctx).await.unwrap(); } async fn insert_on_columns_old_rows( instance: &Arc, table_name: &str, query_ctx: QueryContextRef, ) { let sql = format!( r#" INSERT INTO `{table_name}` VALUES (1, 'London', '2022-01-01 00:00:00'), (5, 'New York', '2022-01-01 00:00:00'), (10, 'Paris', '2022-01-01 00:00:00'), (15, 'Tokyo', '2022-01-01 00:00:00'), (20, 'Beijing', '2022-01-01 00:00:00'); "# ); run_sql(instance, &sql, query_ctx).await.unwrap(); } async fn assert_on_columns_metadata_overwrite( instance: &Arc, table_name: &str, alter_sql: &str, query_ctx: QueryContextRef, ) { create_on_columns_test_table(instance, table_name, query_ctx.clone()).await; run_sql(instance, alter_sql, query_ctx.clone()) .await .unwrap(); tokio::time::sleep(Duration::from_millis(500)).await; assert_partition_expression(instance, table_name, "id, city", query_ctx).await; } async fn assert_on_columns_rejects_removed_remaining_column( instance: &Arc, table_name: &str, alter_sql: &str, query_ctx: QueryContextRef, ) { create_on_columns_test_table(instance, table_name, query_ctx.clone()).await; assert_sql_err_eq( instance, alter_sql, "Invalid partition rule: partition expression references column 'id' that is not in target partition columns", query_ctx, ) .await; } async fn assert_on_columns_data_correctness( instance: &Arc, table_name: &str, alter_sql: &str, query_ctx: QueryContextRef, ) { create_on_columns_test_table(instance, table_name, query_ctx.clone()).await; insert_on_columns_old_rows(instance, table_name, query_ctx.clone()).await; run_sql(instance, alter_sql, query_ctx.clone()) .await .unwrap(); tokio::time::sleep(Duration::from_millis(500)).await; let result = run_sql( instance, &format!("SELECT * FROM `{table_name}` ORDER BY `id`, `city`"), query_ctx.clone(), ) .await .unwrap(); let expected = "\ +----+----------+---------------------+ | id | city | ts | +----+----------+---------------------+ | 1 | London | 2022-01-01T00:00:00 | | 5 | New York | 2022-01-01T00:00:00 | | 10 | Paris | 2022-01-01T00:00:00 | | 15 | Tokyo | 2022-01-01T00:00:00 | | 20 | Beijing | 2022-01-01T00:00:00 | +----+----------+---------------------+"; check_output_stream(result.data, expected).await; let sql = format!( r#" INSERT INTO `{table_name}` VALUES (2, 'Amsterdam', '2022-01-02 00:00:00'), (7, 'Zurich', '2022-01-02 00:00:00'), (12, 'Berlin', '2022-01-02 00:00:00'); "# ); run_sql(instance, &sql, query_ctx.clone()).await.unwrap(); let result = run_sql( instance, &format!("SELECT * FROM `{table_name}` ORDER BY `id`, `city`"), query_ctx, ) .await .unwrap(); let expected = "\ +----+-----------+---------------------+ | id | city | ts | +----+-----------+---------------------+ | 1 | London | 2022-01-01T00:00:00 | | 2 | Amsterdam | 2022-01-02T00:00:00 | | 5 | New York | 2022-01-01T00:00:00 | | 7 | Zurich | 2022-01-02T00:00:00 | | 10 | Paris | 2022-01-01T00:00:00 | | 12 | Berlin | 2022-01-02T00:00:00 | | 15 | Tokyo | 2022-01-01T00:00:00 | | 20 | Beijing | 2022-01-01T00:00:00 | +----+-----------+---------------------+"; check_output_stream(result.data, expected).await; } fn repartition_on_columns_sql(table_name: &str) -> String { format!( r#" ALTER TABLE `{table_name}` REPARTITION ( `id` < 10 ) ON COLUMNS (`id`, `city`) INTO ( `id` < 10 AND `city` < 'M', `id` < 10 AND `city` >= 'M' ); "# ) } fn split_on_columns_sql(table_name: &str) -> String { format!( r#" ALTER TABLE `{table_name}` SPLIT PARTITION ( `id` < 10 ) ON COLUMNS (`id`, `city`) INTO ( `id` < 10 AND `city` < 'M', `id` < 10 AND `city` >= 'M' ); "# ) } fn repartition_on_columns_removed_column_sql(table_name: &str) -> String { format!( r#" ALTER TABLE `{table_name}` REPARTITION ( `id` < 10 ) ON COLUMNS (`city`) INTO ( `city` < 'M', `city` >= 'M' ); "# ) } fn split_on_columns_removed_column_sql(table_name: &str) -> String { format!( r#" ALTER TABLE `{table_name}` SPLIT PARTITION ( `id` < 10 ) ON COLUMNS (`city`) INTO ( `city` < 'M', `city` >= 'M' ); "# ) } async fn assert_partition_expression( instance: &Arc, table_name: &str, expected_partition_expression: &str, query_ctx: QueryContextRef, ) { let result = run_sql( instance, &format!( "SELECT DISTINCT partition_expression FROM information_schema.partitions WHERE table_name = '{table_name}' ORDER BY partition_expression" ), query_ctx, ) .await .unwrap(); let expected = format!( "\ +----------------------+ | partition_expression | +----------------------+ | {expected_partition_expression:<20} | +----------------------+" ); check_output_stream(result.data, &expected).await; } async fn assert_sql_err_eq( instance: &Arc, sql: &str, expected: &str, query_ctx: QueryContextRef, ) { let err = run_sql(instance, sql, query_ctx).await.unwrap_err(); let root = root_source(&err).unwrap_or(&err); assert_eq!(root.to_string(), expected); } async fn run_sql( instance: &Arc, sql: &str, query_ctx: QueryContextRef, ) -> ServerResult { info!("Run SQL: {sql}"); instance.do_query(sql, query_ctx).await.remove(0) }