Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
128 changes: 116 additions & 12 deletions src/metadata/thrift_shape.rs
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,29 @@ fn constant_utf8(len: usize, value: Option<&str>) -> ArrayRef {
Arc::new(StringArray::from(vec![v; len]))
}

fn table_type_column(batch: &RecordBatch) -> Result<ArrayRef> {
Comment thread
rahuls-db marked this conversation as resolved.
Resolved
if column_index(batch.schema_ref(), "tableType").is_none() {
return Ok(Arc::new(StringArray::from(vec![
Some("TABLE");
batch.num_rows()
])));
}
let column = utf8_column(batch, "tableType")?;
let values = column
.as_any()
.downcast_ref::<StringArray>()
.ok_or_else(|| Error::data_loss().message("tableType is not Utf8"))?;
Ok(Arc::new(StringArray::from_iter((0..values.len()).map(
|row| {
Some(if values.is_null(row) {
""
} else {
values.value(row)
})
},
))))
}

/// Return the named source column as an `Int32` array, casting from a
/// related integer type if necessary. Returns an all-null `Int32`
/// array when the column is absent — symmetric with [`utf8_column`].
Expand Down Expand Up @@ -542,8 +565,9 @@ pub(crate) fn reshape_schemas(
///
/// `requested_catalog` fills `TABLE_CAT` rows for server responses
/// that omit it (single-catalog form). `table_types`, when `Some` with
/// at least one entry, filters rows to those whose `TABLE_TYPE` appears
/// in the slice (matches JDBC `DatabaseMetaData.getTables` behaviour).
/// at least one entry, keeps rows whose known `TABLE_TYPE` appears in the
/// slice and passes through rows whose type is null or empty (matching
/// legacy Thrift `GetTables` behaviour).
/// A `Some(&[])` (explicit empty slice) matches NO table types and
/// yields an empty result — it is NOT treated like `None`. See the
/// inline note in the filter block below (METADATA-035 conformance /
Expand All @@ -567,13 +591,8 @@ pub(crate) fn reshape_tables(
};
let table_schem = utf8_column(batch, "namespace")?;
let table_name = utf8_column(batch, "tableName")?;
let table_type = if column_index(batch.schema_ref(), "tableType").is_some() {
utf8_column(batch, "tableType")?
} else {
// Old DBR fallback: best-effort default. Matches the JDBC
// driver's behaviour when SHOW TABLES doesn't expose tableType.
Arc::new(StringArray::from(vec![Some("TABLE"); n]))
};
// Preserve the Thrift server's empty type for legacy hive_metastore rows.
let table_type = table_type_column(batch)?;
// REMARKS is contractually nullable per the JDBC spec, but the Thrift
// backend has historically emitted `""` for tables without a comment
// and most string-handling consumers expect a `String`, not `null`.
Expand Down Expand Up @@ -1007,8 +1026,12 @@ fn filter_tables_by_type(batch: &RecordBatch, types: &[&str]) -> Result<RecordBa
.ok_or_else(|| Error::data_loss().message("TABLE_TYPE is not Utf8"))?;
let keep: Vec<bool> = (0..batch.num_rows())
.map(|i| {
if types_arr.is_null(i) {
if types.is_empty() {
false
} else if types_arr.is_null(i) || types_arr.value(i).is_empty() {
Comment thread
rahuls-db marked this conversation as resolved.
Resolved
// Thrift GetTables retains legacy rows whose type is unknown
// even when a non-empty table-type filter is supplied.
true
} else {
// Exact (case-sensitive) match, for parity with the Thrift
// server's `GetTables` and the JDBC driver's client-side
Expand Down Expand Up @@ -1403,7 +1426,88 @@ mod tests {
}

#[test]
fn tables_filter_by_type_keeps_only_matching_rows() {
fn tables_preserves_present_null_and_empty_table_types() {
let schema = Arc::new(Schema::new(vec![
Field::new("namespace", DataType::Utf8, false),
Field::new("tableName", DataType::Utf8, false),
Field::new("tableType", DataType::Utf8, true),
]));
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(StringArray::from(vec!["s", "s", "s"])),
Arc::new(StringArray::from(vec!["empty", "null", "view"])),
Arc::new(StringArray::from(vec![Some(""), None, Some("VIEW")])),
],
)
.unwrap();
let output = reshape_tables(&batch, Some("main"), None).unwrap();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Low — The new test only calls reshape_tables with table_types = None. Nothing checks that rows with null or empty types now pass a TABLE filter and are dropped by a VIEW filter. Add a call with Some(&["TABLE"]) and one with Some(&["VIEW"]) and assert the results.

🔀 Found by Claude Opus 5.5 · confirmed by the judge

let table_types = output
.column(3)
.as_any()
.downcast_ref::<StringArray>()
.unwrap();
assert_eq!(
table_types.iter().collect::<Vec<_>>(),
vec![Some(""), Some(""), Some("VIEW")]
);

let schema = Arc::new(Schema::new(vec![
Field::new("namespace", DataType::Utf8, false),
Field::new("tableName", DataType::Utf8, false),
]));
let without_table_type =
RecordBatch::try_new(schema, batch.columns()[..2].to_vec()).unwrap();
let output = reshape_tables(&without_table_type, Some("main"), None).unwrap();
let table_types = output
.column(3)
.as_any()
.downcast_ref::<StringArray>()
.unwrap();
assert_eq!(
table_types.iter().collect::<Vec<_>>(),
vec![Some("TABLE"); 3]
);
}

#[test]
fn tables_filter_by_type_retains_unknown_rows() {
let schema = Arc::new(Schema::new(vec![
Field::new("namespace", DataType::Utf8, false),
Field::new("tableName", DataType::Utf8, false),
Field::new("tableType", DataType::Utf8, false),
]));
let batch = RecordBatch::try_new(
schema,
vec![
Arc::new(StringArray::from(vec!["s", "s", "s"])),
Arc::new(StringArray::from(vec!["unknown", "table", "view"])),
Arc::new(StringArray::from(vec!["", "TABLE", "VIEW"])),
],
)
.unwrap();

let output = reshape_tables(&batch, Some("main"), Some(&["TABLE"])).unwrap();
assert_eq!(
output
.column(2)
.as_string::<i32>()
.iter()
.collect::<Vec<_>>(),
vec![Some("unknown"), Some("table")]
);
assert_eq!(
output
.column(3)
.as_string::<i32>()
.iter()
.collect::<Vec<_>>(),
vec![Some(""), Some("TABLE")]
);
}

#[test]
fn tables_filter_by_type_keeps_matching_and_unknown_rows() {
let b = server_tables_full();
let out = reshape_tables(&b, Some("main"), Some(&["TABLE"])).unwrap();
assert_eq!(out.num_rows(), 2);
Expand Down Expand Up @@ -2117,7 +2221,7 @@ mod tests {
}

#[test]
fn filter_tables_by_type_drops_non_matching_and_nulls() {
fn filter_tables_by_type_drops_non_matching_known_rows() {
let batch = tables_with_types(&["TABLE", "VIEW"]);
let out = filter_tables_by_type(&batch, &["MANAGED"]).unwrap();
assert_eq!(out.num_rows(), 0);
Expand Down
95 changes: 92 additions & 3 deletions src/metadata_v0.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,16 @@ fn normalize_native_metadata_batch(
})?
};

if field.name() == "TABLE_TYPE" {
let values = column
.as_any()
.downcast_ref::<arrow_array::StringArray>()
.ok_or_else(|| Error::data_loss().message("TABLE_TYPE is not Utf8"))?;
return Ok(Arc::new(arrow_array::StringArray::from_iter(
values.iter().map(|value| Some(value.unwrap_or(""))),
)) as ArrayRef);
}

if field.name() != "ORDINAL_POSITION" {
return Ok(column);
}
Expand Down Expand Up @@ -769,9 +779,9 @@ impl Metadata {
/// "must not contain a search pattern", so catalog wildcarding is a
/// `getTables`-only behaviour.
///
/// `table_types`, when `Some(non-empty)`, filters the result to
/// rows whose `TABLE_TYPE` matches one of the listed strings —
/// matches `java.sql.DatabaseMetaData.getTables` behaviour.
/// `table_types`, when `Some(non-empty)`, keeps rows whose known
/// `TABLE_TYPE` matches one of the listed strings. Rows whose type is
/// null or empty also pass through, matching legacy Thrift behaviour.
/// Databricks `SHOW TABLES` itself does not accept a type filter,
/// so the filter is applied kernel-side after reshape.
pub async fn list_tables(
Expand Down Expand Up @@ -1669,6 +1679,85 @@ mod tests {
assert!(ordinals.is_null(2));
}

#[test]
fn native_metadata_preserves_null_and_empty_table_types_as_empty() {
let batch = RecordBatch::try_new(
Arc::new(Schema::new(vec![Field::new(
"TABLE_TYPE",
DataType::Utf8,
true,
)])),
vec![Arc::new(arrow_array::StringArray::from(vec![
Some(""),
None,
Some("VIEW"),
]))],
)
.unwrap();
let public_schema = Arc::new(Schema::new(vec![Field::new(
"TABLE_TYPE",
DataType::Utf8,
false,
)]));

let normalized = normalize_native_metadata_batch(&batch, public_schema).unwrap();
let table_types = normalized.column(0).as_string::<i32>();

assert_eq!(
table_types.iter().collect::<Vec<_>>(),
vec![Some(""), Some(""), Some("VIEW")]
);
}

#[test]
fn native_tables_filter_retains_null_and_empty_table_types() {
let mut fields = GET_TABLES_SCHEMA
.fields()
.iter()
.map(|field| field.as_ref().clone())
.collect::<Vec<_>>();
fields[3] = Field::new("TABLE_TYPE", DataType::Utf8, true);
let nulls = || Arc::new(arrow_array::StringArray::from(vec![None::<&str>; 3])) as ArrayRef;
let batch = RecordBatch::try_new(
Arc::new(Schema::new(fields)),
vec![
Arc::new(arrow_array::StringArray::from(vec!["main"; 3])),
Arc::new(arrow_array::StringArray::from(vec!["default"; 3])),
Arc::new(arrow_array::StringArray::from(vec![
"empty", "null", "view",
])),
Arc::new(arrow_array::StringArray::from(vec![
Some(""),
None,
Some("VIEW"),
])),
nulls(),
nulls(),
nulls(),
nulls(),
nulls(),
nulls(),
],
)
.unwrap();

let normalized =
normalize_native_metadata_batch(&batch, GET_TABLES_SCHEMA.clone()).unwrap();
let tables =
thrift_shape::process_native_tables(&normalized, Some("main"), Some(&["TABLE"]))
.unwrap();

assert_eq!(tables.num_rows(), 2);
assert_eq!(
tables
.column(2)
.as_string::<i32>()
.iter()
.collect::<Vec<_>>(),
vec![Some("empty"), Some("null")]
);
}

#[test]
fn native_metadata_rejects_ordinal_overflow() {
let schema = Arc::new(Schema::new(vec![Field::new(
Expand Down
Loading