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
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

139 changes: 132 additions & 7 deletions src/metadata/thrift_shape.rs
Original file line number Diff line number Diff line change
Expand Up @@ -423,7 +423,8 @@ fn null_int16(len: usize) -> ArrayRef {
/// array when the column is absent — symmetric with [`int32_column`].
/// A cast failure is surfaced as `Error::data_loss` rather than
/// silently producing nulls. Used for JDBC `SMALLINT` columns
/// (`DEFERRABILITY`) whose server source ships as a wider integer.
/// (`UPDATE_RULE`, `DELETE_RULE`, `DEFERRABILITY`) whose server source
/// ships as a wider integer.
fn int16_column(batch: &RecordBatch, name: &str) -> Result<ArrayRef> {
match column_index(batch.schema_ref(), name) {
Some(idx) => {
Expand Down Expand Up @@ -1141,10 +1142,8 @@ pub(crate) fn reshape_primary_keys(batch: &RecordBatch) -> Result<RecordBatch> {
/// (FK-bearing) side is in `catalogName / namespace / tableName /
/// col_name`, and the referenced primary side is in the `parent*`
/// columns. This is a pure column rename + projection onto the 14
/// JDBC columns. `UPDATE_RULE`, `DELETE_RULE`, and `PK_NAME` have no
/// source in the server response — they are emitted as typed nulls
/// rather than synthesizing a value (e.g. the kernel does not fabricate
/// a JDBC `importedKeyNoAction` rule code).
/// JDBC columns. Rule values are preserved when present, otherwise
/// emitted as typed nulls. `PK_NAME` has no server source and remains null.
pub(crate) fn reshape_foreign_keys(batch: &RecordBatch) -> Result<RecordBatch> {
let n = batch.num_rows();
let pktable_cat = utf8_column(batch, "parentCatalogName")?;
Expand All @@ -1156,6 +1155,8 @@ pub(crate) fn reshape_foreign_keys(batch: &RecordBatch) -> Result<RecordBatch> {
let fktable_name = utf8_column(batch, "tableName")?;
let fkcolumn_name = utf8_column(batch, "col_name")?;
let key_seq = int32_column(batch, "keySeq")?;
let update_rule = int16_column(batch, "updateRule")?;
let delete_rule = int16_column(batch, "deleteRule")?;
let fk_name = utf8_column(batch, "constraintName")?;
let deferrability = int16_column(batch, "deferrability")?;
RecordBatch::try_new(
Expand All @@ -1170,8 +1171,8 @@ pub(crate) fn reshape_foreign_keys(batch: &RecordBatch) -> Result<RecordBatch> {
fktable_name,
fkcolumn_name,
key_seq,
null_int16(n), // UPDATE_RULE — no server source; not synthesized
null_int16(n), // DELETE_RULE — no server source; not synthesized
update_rule,
delete_rule,
fk_name,
null_utf8(n), // PK_NAME — no server source; not synthesized
deferrability,
Expand Down Expand Up @@ -1868,6 +1869,130 @@ mod tests {
.unwrap()
}

fn server_show_foreign_keys_with_rules(
update_rule: ArrayRef,
delete_rule: ArrayRef,
) -> RecordBatch {
let batch = server_show_foreign_keys();
let mut fields = batch.schema().fields().to_vec();
fields.push(Arc::new(Field::new(
"updateRule",
update_rule.data_type().clone(),
true,
)));
fields.push(Arc::new(Field::new(
"deleteRule",
delete_rule.data_type().clone(),
true,
)));
let mut columns = batch.columns().to_vec();
columns.extend([update_rule, delete_rule]);
RecordBatch::try_new(Arc::new(Schema::new(fields)), columns).unwrap()
}

#[test]
fn foreign_keys_preserves_server_rule_values() {
for (update_rule, delete_rule) in [(3, 3), (0, 2)] {
let raw = server_show_foreign_keys_with_rules(
Arc::new(Int32Array::from(vec![update_rule])),
Arc::new(Int32Array::from(vec![delete_rule])),
);
let out = reshape_foreign_keys(&raw).unwrap();
for (name, expected) in [
("UPDATE_RULE", update_rule as i16),
("DELETE_RULE", delete_rule as i16),
] {
let values = out
.column_by_name(name)
.unwrap()
.as_any()
.downcast_ref::<Int16Array>()
.unwrap();
assert_eq!(values, &Int16Array::from(vec![expected]));
}
}
}

#[test]
fn foreign_keys_preserves_null_rules() {
for (update_rule, delete_rule) in [(None, Some(3)), (Some(3), None), (None, None)] {
let raw = server_show_foreign_keys_with_rules(
Arc::new(Int32Array::from(vec![update_rule])),
Arc::new(Int32Array::from(vec![delete_rule])),
);
let out = reshape_foreign_keys(&raw).unwrap();
for (name, expected) in [
("UPDATE_RULE", update_rule.map(|v| v as i16)),
("DELETE_RULE", delete_rule.map(|v| v as i16)),
] {
let values = out
.column_by_name(name)
.unwrap()
.as_any()
.downcast_ref::<Int16Array>()
.unwrap();
assert_eq!(values, &Int16Array::from(vec![expected]));
}
}
}

#[test]
fn foreign_keys_preserves_int16_rules() {
let raw = server_show_foreign_keys_with_rules(
Arc::new(Int16Array::from(vec![3])),
Arc::new(Int16Array::from(vec![2])),
);
let out = reshape_foreign_keys(&raw).unwrap();
for (source, target) in [("updateRule", "UPDATE_RULE"), ("deleteRule", "DELETE_RULE")] {
assert_eq!(
out.column_by_name(target).unwrap(),
raw.column_by_name(source).unwrap()
);
}
}

#[test]
fn foreign_keys_handles_each_missing_rule_independently() {
let raw = server_show_foreign_keys_with_rules(
Arc::new(Int32Array::from(vec![3])),
Arc::new(Int32Array::from(vec![3])),
);
for (missing, update_rule, delete_rule) in
[("updateRule", None, Some(3)), ("deleteRule", Some(3), None)]
{
let indices: Vec<_> = raw
.schema()
.fields()
.iter()
.enumerate()
.filter_map(|(i, field)| (field.name() != missing).then_some(i))
.collect();
let out = reshape_foreign_keys(&raw.project(&indices).unwrap()).unwrap();
for (name, expected) in [("UPDATE_RULE", update_rule), ("DELETE_RULE", delete_rule)] {
let values = out
.column_by_name(name)
.unwrap()
.as_any()
.downcast_ref::<Int16Array>()
.unwrap();
assert_eq!(values, &Int16Array::from(vec![expected]));
}
}
}

#[test]
fn foreign_keys_empty_result_preserves_jdbc_schema() {
let raw = server_show_foreign_keys_with_rules(
Arc::new(Int32Array::from(vec![3])),
Arc::new(Int32Array::from(vec![3])),
);
for batch in [raw.slice(0, 0), server_show_foreign_keys().slice(0, 0)] {
let out = reshape_foreign_keys(&batch).unwrap();
assert_eq!(out.schema(), GET_CROSS_REFERENCE_SCHEMA.clone());
assert_eq!(out.num_rows(), 0);
}
}

#[test]
fn foreign_keys_renames_to_jdbc_columns_and_nulls_unsourced() {
let out = reshape_foreign_keys(&server_show_foreign_keys()).unwrap();
Expand Down
4 changes: 2 additions & 2 deletions src/metadata_v0.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1257,8 +1257,8 @@ impl Metadata {
/// `getCrossReference` column set (`PKTABLE_*`, `FKTABLE_*`,
/// `KEY_SEQ`, `UPDATE_RULE`, `DELETE_RULE`, `FK_NAME`, `PK_NAME`,
/// `DEFERRABILITY`) by [`thrift_shape::reshape_foreign_keys`].
/// `UPDATE_RULE` / `DELETE_RULE` / `PK_NAME` have no source in the
/// server response and are emitted as typed nulls (not synthesized).
/// Rule values are preserved when present, otherwise emitted as
/// typed nulls. `PK_NAME` has no server source and remains null.
pub async fn foreign_keys(
&self,
parent_catalog: Option<Identifier<'_>>,
Expand Down
111 changes: 108 additions & 3 deletions tests/v0_metadata_wiremock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1585,8 +1585,8 @@ async fn foreign_keys_reshaped_to_jdbc_columns() {
// Live `SHOW FOREIGN KEYS` shape — the FK-bearing side is in
// `catalogName / namespace / tableName / col_name`, the referenced
// primary side in the `parent*` columns. The kernel reshapes into
// the JDBC `getCrossReference` set; UPDATE_RULE / DELETE_RULE /
// PK_NAME have no server source and come back null.
// the JDBC `getCrossReference` set. This older response omits
// rule columns, so they remain null along with PK_NAME.
let raw = string_batch(vec![
("catalogName", vec![Some("main")]),
("namespace", vec![Some("d")]),
Expand Down Expand Up @@ -1661,12 +1661,117 @@ async fn foreign_keys_reshaped_to_jdbc_columns() {
.value(0),
"fk_child"
);
// UPDATE_RULE / DELETE_RULE / PK_NAME have no server source → null.
// Absent rule fields and PK_NAME remain null.
assert!(b.column_by_name("UPDATE_RULE").unwrap().is_null(0));
assert!(b.column_by_name("DELETE_RULE").unwrap().is_null(0));
assert!(b.column_by_name("PK_NAME").unwrap().is_null(0));
}

#[tokio::test]
async fn foreign_keys_preserves_rules_for_show_and_native_responses() {
for native in [false, true] {
let server = MockServer::start().await;
mount_create_session(&server).await;
mount_delete_session(&server).await;

let names = if native {
[
"PKTABLE_CAT",
"PKTABLE_SCHEM",
"PKTABLE_NAME",
"PKCOLUMN_NAME",
"FKTABLE_CAT",
"FKTABLE_SCHEM",
"FKTABLE_NAME",
"FKCOLUMN_NAME",
"KEY_SEQ",
"UPDATE_RULE",
"DELETE_RULE",
"FK_NAME",
"DEFERRABILITY",
]
} else {
[
"parentCatalogName",
"parentNamespace",
"parentTableName",
"parentColName",
"catalogName",
"namespace",
"tableName",
"col_name",
"keySeq",
"updateRule",
"deleteRule",
"constraintName",
"deferrability",
]
};
let mut columns: Vec<ArrayRef> = vec![
Arc::new(StringArray::from(vec!["main"; 3])),
Arc::new(StringArray::from(vec!["d"; 3])),
Arc::new(StringArray::from(vec!["parent"; 3])),
Arc::new(StringArray::from(vec!["id"; 3])),
Arc::new(StringArray::from(vec!["main"; 3])),
Arc::new(StringArray::from(vec!["d"; 3])),
Arc::new(StringArray::from(vec!["child"; 3])),
Arc::new(StringArray::from(vec!["pid"; 3])),
Arc::new(Int32Array::from(vec![1; 3])),
Arc::new(Int32Array::from(vec![Some(3), Some(0), None])),
Arc::new(Int32Array::from(vec![Some(3), Some(2), Some(4)])),
Arc::new(StringArray::from(vec!["fk_child"; 3])),
Arc::new(Int32Array::from(vec![7; 3])),
];
let mut fields: Vec<_> = names
.into_iter()
.zip(&columns)
.map(|(name, column)| Field::new(name, column.data_type().clone(), true))
.collect();
if native {
fields.insert(12, Field::new("PK_NAME", DataType::Utf8, true));
columns.insert(12, Arc::new(StringArray::from(vec![None::<&str>; 3])));
}
let raw = RecordBatch::try_new(Arc::new(Schema::new(fields)), columns).unwrap();
let body = if native {
native_inline_response_body(&raw)
} else {
succeeded_inline_response_body(&raw)
};
mount_execute_expecting_sql(&server, "SHOW FOREIGN KEYS", body).await;

let session = open_session(&server).await;
let mut stream = session
.metadata()
.foreign_keys(
Some(Identifier::new("main").unwrap()),
Some(Identifier::new("d").unwrap()),
Some(Identifier::new("parent").unwrap()),
Some(Identifier::new("main").unwrap()),
Some(Identifier::new("d").unwrap()),
Some(Identifier::new("child").unwrap()),
)
.await
.expect("foreign_keys");
let batches = drain_stream(&mut stream).await;
assert_eq!(batches.len(), 1);
let batch = &batches[0];
assert_eq!(batch.num_rows(), 3);
for (name, expected) in [
("UPDATE_RULE", vec![Some(3), Some(0), None]),
("DELETE_RULE", vec![Some(3), Some(2), Some(4)]),
] {
let values = batch
.column_by_name(name)
.unwrap()
.as_any()
.downcast_ref::<Int16Array>()
.expect("rule column is Int16");
assert_eq!(values, &Int16Array::from(expected), "native={native}");
}
assert_eq!(batch.column_by_name("PK_NAME").unwrap().null_count(), 3);
}
}

#[tokio::test]
async fn foreign_keys_null_foreign_table_returns_empty_without_wire_call() {
// Conformance (METADATA-037): the PK (parent) side is fully
Expand Down
Loading