diff --git a/src/common/meta/src/reconciliation/reconcile_table/resolve_column_metadata.rs b/src/common/meta/src/reconciliation/reconcile_table/resolve_column_metadata.rs index 8defc6bd0f2..e95edd34546 100644 --- a/src/common/meta/src/reconciliation/reconcile_table/resolve_column_metadata.rs +++ b/src/common/meta/src/reconciliation/reconcile_table/resolve_column_metadata.rs @@ -92,6 +92,9 @@ impl State for ResolveColumnMetadata { ctx.persistent_ctx.table_info_value = Some(table_info_value); if let Some(column_metadatas) = check_column_metadatas_consistent(&self.region_metadata) { + // The consistent regions share their key: order the tags as the regions keep them, which + // also checks that the region's primary key matches its tag columns. Column order still + // comes from the stored `TableInfo`; see `build_table_meta_from_column_metadatas`. let column_metadatas = reorder_tag_columns(&column_metadatas, &self.region_metadata[0].primary_key)?; // Safety: fetched in the above. diff --git a/src/common/meta/src/reconciliation/utils.rs b/src/common/meta/src/reconciliation/utils.rs index 326516ecd80..f65af771310 100644 --- a/src/common/meta/src/reconciliation/utils.rs +++ b/src/common/meta/src/reconciliation/utils.rs @@ -358,15 +358,24 @@ pub(crate) fn check_column_metadata_invariants( Ok(()) } -/// Builds a [`TableMeta`] from the provided [`ColumnMetadata`]s. +/// Builds a [`TableMeta`] from the provided [`ColumnMetadata`]s, preserving schema column order +/// from `table_meta` and taking the primary key order from the input tags. +/// +/// The input [`ColumnMetadata`]s determine which columns currently exist in region metadata: +/// - Columns present in `table_meta` but missing from `column_metadata` are dropped. +/// - Columns present in both retain the column order from `table_meta.schema`. +/// - Columns present only in `column_metadata` are appended. +/// - Primary key order follows the tag columns in `column_metadata`, which the physical-table +/// reconcile paths feed in the regions' key order (`table_meta.primary_key_indices` only +/// determines which columns must remain tags). The logical-table reconcile path feeds columns +/// in column-position order and relies on a subsequent `sort_columns()` call. /// /// Returns an error if: /// - Any column is missing in the `name_to_ids`(if `name_to_ids` is provided). /// - The column id in table metadata is not the same as the column id in the column metadata.(if `name_to_ids` is provided) /// - The table index is missing in the column metadata. +/// - Any primary key column of `table_meta` is not [`SemanticType::Tag`] in `column_metadata`. /// - The primary key or partition key columns are missing in the column metadata. -/// -/// TODO(weny): add tests pub(crate) fn build_table_meta_from_column_metadatas( table_id: TableId, table_ref: TableReference, @@ -434,11 +443,30 @@ pub(crate) fn build_table_meta_from_column_metadatas( ); } + let mut ordered_column_metadatas = Vec::with_capacity(column_metadata.len()); + let mut existing_names = HashSet::with_capacity(column_schemas.len()); + + // Preserves the original table column order from `table_meta.schema`. + for col_schema in column_schemas { + if let Some(col) = column_in_column_metadata.get(col_schema.name.as_str()) { + ordered_column_metadatas.push(*col); + existing_names.insert(col_schema.name.as_str()); + } + } + + // Appends any newly added columns from `column_metadata`. + for col in column_metadata { + if !existing_names.contains(col.column_schema.name.as_str()) { + ordered_column_metadatas.push(col); + } + } + let mut new_raw_table_meta = table_meta.clone(); let primary_key_indices = &mut new_raw_table_meta.primary_key_indices; let partition_key_indices = &mut new_raw_table_meta.partition_key_indices; let value_indices = &mut new_raw_table_meta.value_indices; - let mut columns = Vec::with_capacity(column_metadata.len()); + let mut columns = Vec::with_capacity(ordered_column_metadatas.len()); + let mut column_name_to_index = HashMap::with_capacity(ordered_column_metadatas.len()); let column_ids = &mut new_raw_table_meta.column_ids; let next_column_id = &mut new_raw_table_meta.next_column_id; @@ -447,24 +475,47 @@ pub(crate) fn build_table_meta_from_column_metadatas( primary_key_indices.clear(); partition_key_indices.clear(); - for (idx, col) in column_metadata.iter().enumerate() { - if partition_key_names.contains(&col.column_schema.name.as_str()) { - partition_key_indices.push(idx); - } - match col.semantic_type { - SemanticType::Tag => { - primary_key_indices.push(idx); - } - SemanticType::Field => { - value_indices.push(idx); - } - SemanticType::Timestamp => { - value_indices.push(idx); - } + for (idx, col) in ordered_column_metadatas.iter().enumerate() { + if col.semantic_type != SemanticType::Tag { + value_indices.push(idx); } columns.push(col.column_schema.clone()); column_ids.push(col.column_id); + column_name_to_index.insert(col.column_schema.name.as_str(), idx); + } + + // Physical-table reconciliation supplies tags in region primary key order. + for col in column_metadata + .iter() + .filter(|c| c.semantic_type == SemanticType::Tag) + { + primary_key_indices.push(column_name_to_index[col.column_schema.name.as_str()]); + } + + // Ensures every stored primary key column is still a tag in the region metadata. + for old_idx in &table_meta.primary_key_indices { + let col_schema = &column_schemas[*old_idx]; + if let Some(col) = column_in_column_metadata.get(col_schema.name.as_str()) { + ensure!( + col.semantic_type == SemanticType::Tag, + UnexpectedSnafu { + err_msg: format!( + "Primary key column '{}' has invalid semantic type '{:?}', expected Tag, table: {}, table_id: {}", + col_schema.name, col.semantic_type, table_ref, table_id + ), + } + ); + } + } + + // Preserves the order of partition keys as defined in the original table info. + for old_idx in &table_meta.partition_key_indices { + let col_schema = &column_schemas[*old_idx]; + let Some(&new_idx) = column_name_to_index.get(col_schema.name.as_str()) else { + continue; + }; + partition_key_indices.push(new_idx); } *next_column_id = column_ids @@ -1265,6 +1316,180 @@ mod tests { assert_matches!(err, Error::MissingColumnInColumnMetadata { .. }); } + fn new_test_q8_raw_table_info() -> (TableMeta, HashMap) { + let column_schemas = vec![ + ColumnSchema::new( + "ts", + ConcreteDataType::timestamp_millisecond_datatype(), + false, + ) + .with_time_index(true), + ColumnSchema::new("a", ConcreteDataType::string_datatype(), true), + ColumnSchema::new("b", ConcreteDataType::string_datatype(), true), + ]; + let schema = SchemaBuilder::try_from(column_schemas) + .unwrap() + .version(1) + .build() + .unwrap(); + + let mut table_meta_builder = TableMetaBuilder::empty(); + let mut table_meta = table_meta_builder + .schema(Arc::new(schema)) + .primary_key_indices(vec![2, 1]) + .next_column_id(4) + .build() + .unwrap(); + table_meta.column_ids = vec![1, 2, 3]; + + let name_to_ids = HashMap::from([ + ("ts".to_string(), 1), + ("a".to_string(), 2), + ("b".to_string(), 3), + ]); + + (table_meta, name_to_ids) + } + + #[test] + fn test_build_table_meta_preserves_column_order_and_primary_key_indices() { + let (mut table_meta, name_to_ids) = new_test_q8_raw_table_info(); + table_meta.partition_key_indices = vec![2, 1]; + let table_id = 100; + let table_ref = TableReference::full("test_catalog", "test_schema", "test_table"); + + let region_column_metadatas = vec![ + ColumnMetadata { + column_schema: ColumnSchema::new( + "ts", + ConcreteDataType::timestamp_millisecond_datatype(), + false, + ) + .with_time_index(true), + semantic_type: SemanticType::Timestamp, + column_id: 1, + }, + ColumnMetadata { + column_schema: ColumnSchema::new("a", ConcreteDataType::string_datatype(), true), + semantic_type: SemanticType::Tag, + column_id: 2, + }, + ColumnMetadata { + column_schema: ColumnSchema::new("b", ConcreteDataType::string_datatype(), true), + semantic_type: SemanticType::Tag, + column_id: 3, + }, + ]; + + // 1. Consistent case where region columns match table schema order: + // Column order comes from table_meta; the primary key order follows the input tags. + let new_table_meta = build_table_meta_from_column_metadatas( + table_id, + table_ref, + &table_meta, + Some(name_to_ids.clone()), + ®ion_column_metadatas, + ) + .unwrap(); + + assert_eq!(new_table_meta.primary_key_indices, vec![1, 2]); + assert_eq!(new_table_meta.partition_key_indices, vec![2, 1]); + assert_eq!(new_table_meta.column_ids, table_meta.column_ids); + + // 2. Case where input column metadata has reordered tags (e.g. ts, b, a): + // Table schema column order must still be preserved according to table_meta.schema. + let reordered_column_metadatas = vec![ + region_column_metadatas[0].clone(), + region_column_metadatas[2].clone(), + region_column_metadatas[1].clone(), + ]; + let new_table_meta = build_table_meta_from_column_metadatas( + table_id, + table_ref, + &table_meta, + Some(name_to_ids.clone()), + &reordered_column_metadatas, + ) + .unwrap(); + + assert_eq!(new_table_meta, table_meta); + + // 3. Case where a new field column is added: + let mut extended_column_metadatas = region_column_metadatas.clone(); + extended_column_metadatas.push(ColumnMetadata { + column_schema: ColumnSchema::new("c", ConcreteDataType::int32_datatype(), true), + semantic_type: SemanticType::Field, + column_id: 4, + }); + let mut extended_name_to_ids = name_to_ids; + extended_name_to_ids.insert("c".to_string(), 4); + + let new_table_meta = build_table_meta_from_column_metadatas( + table_id, + table_ref, + &table_meta, + Some(extended_name_to_ids), + &extended_column_metadatas, + ) + .unwrap(); + + assert_eq!( + new_table_meta + .schema + .column_schemas() + .iter() + .map(|c| c.name.as_str()) + .collect::>(), + vec!["ts", "a", "b", "c"] + ); + assert_eq!(new_table_meta.primary_key_indices, vec![1, 2]); + assert_eq!(new_table_meta.value_indices, vec![0, 3]); + assert_eq!(new_table_meta.column_ids, vec![1, 2, 3, 4]); + } + + #[test] + fn test_build_table_meta_rejects_non_tag_primary_key() { + let (table_meta, name_to_ids) = new_test_q8_raw_table_info(); + let table_id = 100; + let table_ref = TableReference::full("test_catalog", "test_schema", "test_table"); + + // Input column metadata erroneously reports primary key column 'b' as Field instead of Tag + let invalid_column_metadatas = vec![ + ColumnMetadata { + column_schema: ColumnSchema::new( + "ts", + ConcreteDataType::timestamp_millisecond_datatype(), + false, + ) + .with_time_index(true), + semantic_type: SemanticType::Timestamp, + column_id: 1, + }, + ColumnMetadata { + column_schema: ColumnSchema::new("a", ConcreteDataType::string_datatype(), true), + semantic_type: SemanticType::Tag, + column_id: 2, + }, + ColumnMetadata { + column_schema: ColumnSchema::new("b", ConcreteDataType::string_datatype(), true), + semantic_type: SemanticType::Field, + column_id: 3, + }, + ]; + + let err = build_table_meta_from_column_metadatas( + table_id, + table_ref, + &table_meta, + Some(name_to_ids), + &invalid_column_metadatas, + ) + .unwrap_err(); + + assert_matches!(err, Error::Unexpected { .. }); + assert!(err.to_string().contains("expected Tag")); + } + #[test] fn test_reconciliation_columns_follow_primary_key_order() { let columns = vec![ diff --git a/tests-integration/src/tests/reconcile_table.rs b/tests-integration/src/tests/reconcile_table.rs index d31845be461..40ce339259f 100644 --- a/tests-integration/src/tests/reconcile_table.rs +++ b/tests-integration/src/tests/reconcile_table.rs @@ -541,6 +541,77 @@ async fn test_renamed_table() { check_output_stream(output.data, expected).await; } +#[tokio::test] +async fn test_reconcile_table_preserves_column_order_and_pk_order() { + let builder = + GreptimeDbClusterBuilder::new("test_reconcile_table_preserves_column_order_and_pk_order") + .await; + let test_context = TestContext::new(MockInstanceBuilder::Distributed(builder)).await; + let frontend = test_context.frontend(); + let metasrv = test_context.metasrv(); + let reconciliation_manager = metasrv.reconciliation_manager(); + + // 1. CREATE TABLE q8 with columns ts, a, b and non-column-ordered PRIMARY KEY (b, a) + let output = execute_sql( + &frontend, + "CREATE TABLE q8 (ts TIMESTAMP TIME INDEX, a STRING, b STRING, PRIMARY KEY(b, a));", + ) + .await; + assert_affected_rows(output.data).await; + + // 2. Positional INSERT before ALTER TABLE + let output = execute_sql( + &frontend, + "INSERT INTO q8 VALUES ('1970-01-01 00:00:01', 'a1', 'b1');", + ) + .await; + assert_affected_rows(output.data).await; + + // 3. ALTER TABLE q8 ADD COLUMN c INT introduces #10248 stale primary_key_indices order + let output = execute_sql(&frontend, "ALTER TABLE q8 ADD COLUMN c INT;").await; + assert_affected_rows(output.data).await; + + // 4. Reconcile the table (repairs stale primary key order while preserving column order) + reconcile_table(metasrv.procedure_manager(), reconciliation_manager, "q8").await; + + // 5. Positional INSERT after reconcile (must insert into ts, a, b, c) + let output = execute_sql( + &frontend, + "INSERT INTO q8 VALUES ('1970-01-01 00:00:02', 'a2', 'b2', 2);", + ) + .await; + assert_affected_rows(output.data).await; + + // 6. SELECT * asserts columns are ts, a, b, c and positional inserts landed correctly + let output = execute_sql(&frontend, "SELECT * FROM q8 ORDER BY ts").await; + let expected = r#"+---------------------+----+----+---+ +| ts | a | b | c | ++---------------------+----+----+---+ +| 1970-01-01T00:00:01 | a1 | b1 | | +| 1970-01-01T00:00:02 | a2 | b2 | 2 | ++---------------------+----+----+---+"#; + check_output_stream(output.data, expected).await; + + // 7. SHOW CREATE TABLE q8 asserts columns ts, a, b, c and PRIMARY KEY (b, a). + let output = execute_sql(&frontend, "SHOW CREATE TABLE q8").await; + let expected = r#"+-------+-----------------------------------+ +| Table | Create Table | ++-------+-----------------------------------+ +| q8 | CREATE TABLE IF NOT EXISTS "q8" ( | +| | "ts" TIMESTAMP(3) NOT NULL, | +| | "a" STRING NULL, | +| | "b" STRING NULL, | +| | "c" INT NULL, | +| | TIME INDEX ("ts"), | +| | PRIMARY KEY ("b", "a") | +| | ) | +| | | +| | ENGINE=mito | +| | | ++-------+-----------------------------------+"#; + check_output_stream(output.data, expected).await; +} + async fn unwrap_err(output: OutputData) -> String { let error = match output { OutputData::Stream(stream) => collect_batches(stream).await.unwrap_err(),