From 57aef517c3e8c79bc6b346b16e66f8f3a4e01899 Mon Sep 17 00:00:00 2001 From: Madhavendra Rathore Date: Sun, 7 Jun 2026 22:05:45 +0000 Subject: [PATCH] feat(metadata): reshape getPrimaryKeys/getCrossReference to JDBC columns MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `Metadata::primary_keys` and `Metadata::foreign_keys` returned the raw Databricks `SHOW KEYS` / `SHOW FOREIGN KEYS` column names (`catalogName`, `namespace`, `col_name`, `keySeq`, `parentColName`, …), unlike `catalogs` / `schemas` / `tables` / `columns`, which are already reshaped into the canonical JDBC `TGet*Resp` shape. Bindings (node, pyo3, ODBC) therefore saw non-canonical names for these two calls and had to remap them per-binding (or, today, not at all — surfacing the raw names to callers). Wire the existing `ThriftReshapingReader` for both calls: - `reshape_primary_keys` → `TABLE_CAT, TABLE_SCHEM, TABLE_NAME, COLUMN_NAME, KEY_SEQ, PK_NAME`. - `reshape_foreign_keys` → the 14-column JDBC `getCrossReference` set (`PKTABLE_*`, `FKTABLE_*`, `KEY_SEQ`, `UPDATE_RULE`, `DELETE_RULE`, `FK_NAME`, `PK_NAME`, `DEFERRABILITY`). This is a pure column rename + projection. `UPDATE_RULE`, `DELETE_RULE`, and `PK_NAME` have no source in the server response, so they are emitted as typed nulls rather than synthesizing a value (e.g. a JDBC `importedKeyNoAction` rule code). Routing through the shared `not_found_or` helper also makes a lookup on a non-existent table return an empty result rather than raising, matching the sibling metadata calls and the JDBC `DatabaseMetaData` contract. Verified against a live warehouse via the Python `use_kernel` path: both calls now return the canonical column names and values; the non-existent table case returns zero rows. Signed-off-by: Madhavendra Rathore --- src/metadata/thrift_shape.rs | 296 ++++++++++++++++++++++++++++++++++ src/metadata_v0.rs | 58 +++++-- tests/v0_metadata_e2e.rs | 71 ++++---- tests/v0_metadata_wiremock.rs | 153 +++++++++++++++--- 4 files changed, 514 insertions(+), 64 deletions(-) diff --git a/src/metadata/thrift_shape.rs b/src/metadata/thrift_shape.rs index 374bc2fc..8b5fc8f2 100644 --- a/src/metadata/thrift_shape.rs +++ b/src/metadata/thrift_shape.rs @@ -170,6 +170,53 @@ pub(crate) static GET_COLUMNS_SCHEMA: LazyLock = LazyLock::new(|| { ])) }); +/// JDBC `getPrimaryKeys` — 6 columns. Matches +/// `java.sql.DatabaseMetaData.getPrimaryKeys` (and the Databricks +/// Thrift `TGetPrimaryKeysResp` column set). `KEY_SEQ` follows the +/// Thrift wire type (`INT` / Int32), not JDBC's `short`, so the kernel +/// backend is a drop-in replacement for existing PySQL / JDBC users. +pub(crate) static GET_PRIMARY_KEYS_SCHEMA: LazyLock = LazyLock::new(|| { + Arc::new(Schema::new(vec![ + Field::new("TABLE_CAT", DataType::Utf8, true), + Field::new("TABLE_SCHEM", DataType::Utf8, true), + Field::new("TABLE_NAME", DataType::Utf8, false), + Field::new("COLUMN_NAME", DataType::Utf8, false), + // JDBC spec says non-null, but declare nullable so the reshape + // doesn't fail on the rare server response that omits `keySeq`; + // modern DBR always populates it and the value flows through. + Field::new("KEY_SEQ", DataType::Int32, true), + Field::new("PK_NAME", DataType::Utf8, true), + ])) +}); + +/// JDBC `getCrossReference` / `getImportedKeys` — 14 columns. Matches +/// `java.sql.DatabaseMetaData.getCrossReference` (and the Databricks +/// Thrift `TGetCrossReferenceResp` column set). `KEY_SEQ` is `INT` +/// (Int32) and `UPDATE_RULE` / `DELETE_RULE` / `DEFERRABILITY` are +/// `SMALLINT` (Int16), matching the Thrift wire types. `UPDATE_RULE` / +/// `DELETE_RULE` / `PK_NAME` have no source in the Databricks +/// `SHOW FOREIGN KEYS` response, so they are emitted as typed nulls +/// (no value is synthesized). +pub(crate) static GET_CROSS_REFERENCE_SCHEMA: LazyLock = LazyLock::new(|| { + Arc::new(Schema::new(vec![ + Field::new("PKTABLE_CAT", DataType::Utf8, true), + Field::new("PKTABLE_SCHEM", DataType::Utf8, true), + Field::new("PKTABLE_NAME", DataType::Utf8, false), + Field::new("PKCOLUMN_NAME", DataType::Utf8, false), + Field::new("FKTABLE_CAT", DataType::Utf8, true), + Field::new("FKTABLE_SCHEM", DataType::Utf8, true), + Field::new("FKTABLE_NAME", DataType::Utf8, false), + Field::new("FKCOLUMN_NAME", DataType::Utf8, false), + // Nullable for the same reason as `getPrimaryKeys` KEY_SEQ. + Field::new("KEY_SEQ", DataType::Int32, true), + Field::new("UPDATE_RULE", DataType::Int16, true), + Field::new("DELETE_RULE", DataType::Int16, true), + Field::new("FK_NAME", DataType::Utf8, true), + Field::new("PK_NAME", DataType::Utf8, true), + Field::new("DEFERRABILITY", DataType::Int16, true), + ])) +}); + // ─── Helpers ─────────────────────────────────────────────────────── /// Find the index of a column by name in the source schema, returning @@ -298,6 +345,34 @@ fn null_int16(len: usize) -> ArrayRef { Arc::new(arrow_array::Int16Array::from(vec![None::; len])) } +/// Return the named source column as an `Int16` array, casting from a +/// related integer type if necessary. Returns an all-null `Int16` +/// 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. +fn int16_column(batch: &RecordBatch, name: &str) -> Result { + match column_index(batch.schema_ref(), name) { + Some(idx) => { + let col = batch.column(idx); + if col.data_type() == &DataType::Int16 { + Ok(Arc::clone(col)) + } else { + arrow_cast::cast(col.as_ref(), &DataType::Int16).map_err(|e| { + Error::data_loss().message(format!( + "unexpected non-Int16 type for SHOW response column {name:?}: {e}" + )) + }) + } + } + None => Ok(Arc::new(arrow_array::Int16Array::from(vec![ + None::; + batch + .num_rows() + ]))), + } +} + fn null_int8(len: usize) -> ArrayRef { Arc::new(arrow_array::Int8Array::from(vec![None::; len])) } @@ -666,6 +741,84 @@ fn filter_tables_by_type(batch: &RecordBatch, types: &[&str]) -> Result Result { + let table_cat = utf8_column(batch, "catalogName")?; + let table_schem = utf8_column(batch, "namespace")?; + let table_name = utf8_column(batch, "tableName")?; + let column_name = utf8_column(batch, "col_name")?; + let key_seq = int32_column(batch, "keySeq")?; + let pk_name = utf8_column(batch, "constraintName")?; + RecordBatch::try_new( + GET_PRIMARY_KEYS_SCHEMA.clone(), + vec![ + table_cat, + table_schem, + table_name, + column_name, + key_seq, + pk_name, + ], + ) + .map_err(|e| Error::data_loss().message(format!("reshape primary_keys: {e}"))) +} + +/// Reshape Databricks `SHOW FOREIGN KEYS` output into the JDBC +/// `getCrossReference` shape. +/// +/// Server shape (same columns as `SHOW KEYS`): the foreign +/// (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). +pub(crate) fn reshape_foreign_keys(batch: &RecordBatch) -> Result { + let n = batch.num_rows(); + let pktable_cat = utf8_column(batch, "parentCatalogName")?; + let pktable_schem = utf8_column(batch, "parentNamespace")?; + let pktable_name = utf8_column(batch, "parentTableName")?; + let pkcolumn_name = utf8_column(batch, "parentColName")?; + let fktable_cat = utf8_column(batch, "catalogName")?; + let fktable_schem = utf8_column(batch, "namespace")?; + let fktable_name = utf8_column(batch, "tableName")?; + let fkcolumn_name = utf8_column(batch, "col_name")?; + let key_seq = int32_column(batch, "keySeq")?; + let fk_name = utf8_column(batch, "constraintName")?; + let deferrability = int16_column(batch, "deferrability")?; + RecordBatch::try_new( + GET_CROSS_REFERENCE_SCHEMA.clone(), + vec![ + pktable_cat, + pktable_schem, + pktable_name, + pkcolumn_name, + fktable_cat, + fktable_schem, + 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 + fk_name, + null_utf8(n), // PK_NAME — no server source; not synthesized + deferrability, + ], + ) + .map_err(|e| Error::data_loss().message(format!("reshape foreign_keys: {e}"))) +} + // ─── Streaming reshape reader ────────────────────────────────────── /// Per-batch reshape closure used by [`ThriftReshapingReader`]. Held @@ -1131,4 +1284,147 @@ mod tests { .unwrap(); assert_eq!(is_ai.value(0), "NO"); } + + // ─── primary / foreign keys reshape ──────────────────────────── + + fn server_show_keys() -> RecordBatch { + let schema = Arc::new(Schema::new(vec![ + Field::new("catalogName", DataType::Utf8, false), + Field::new("namespace", DataType::Utf8, false), + Field::new("tableName", DataType::Utf8, false), + Field::new("col_name", DataType::Utf8, false), + Field::new("keySeq", DataType::Int32, true), + Field::new("constraintName", DataType::Utf8, true), + Field::new("constraintType", DataType::Utf8, true), + ])); + RecordBatch::try_new( + schema, + vec![ + Arc::new(StringArray::from(vec!["main", "main"])), + Arc::new(StringArray::from(vec!["s", "s"])), + Arc::new(StringArray::from(vec!["t", "t"])), + Arc::new(StringArray::from(vec!["id", "code"])), + Arc::new(Int32Array::from(vec![Some(1), Some(2)])), + Arc::new(StringArray::from(vec!["pk_t", "pk_t"])), + Arc::new(StringArray::from(vec!["PRIMARY", "PRIMARY"])), + ], + ) + .unwrap() + } + + #[test] + fn primary_keys_renames_to_jdbc_columns() { + let out = reshape_primary_keys(&server_show_keys()).unwrap(); + assert_eq!( + out.schema() + .fields() + .iter() + .map(|f| f.name().as_str()) + .collect::>(), + vec![ + "TABLE_CAT", + "TABLE_SCHEM", + "TABLE_NAME", + "COLUMN_NAME", + "KEY_SEQ", + "PK_NAME", + ] + ); + assert_eq!(out.num_rows(), 2); + let key_seq = out.column(4).as_any().downcast_ref::().unwrap(); + assert_eq!(key_seq.value(0), 1); + assert_eq!(key_seq.value(1), 2); + let pk_name = out + .column(5) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(pk_name.value(0), "pk_t"); + } + + fn server_show_foreign_keys() -> RecordBatch { + let schema = Arc::new(Schema::new(vec![ + Field::new("catalogName", DataType::Utf8, false), + Field::new("namespace", DataType::Utf8, false), + Field::new("tableName", DataType::Utf8, false), + Field::new("col_name", DataType::Utf8, false), + Field::new("keySeq", DataType::Int32, true), + Field::new("constraintName", DataType::Utf8, true), + Field::new("parentCatalogName", DataType::Utf8, true), + Field::new("parentNamespace", DataType::Utf8, true), + Field::new("parentTableName", DataType::Utf8, true), + Field::new("parentColName", DataType::Utf8, true), + Field::new("deferrability", DataType::Int32, true), + ])); + RecordBatch::try_new( + schema, + vec![ + Arc::new(StringArray::from(vec!["main"])), + Arc::new(StringArray::from(vec!["s"])), + Arc::new(StringArray::from(vec!["child"])), + Arc::new(StringArray::from(vec!["pid"])), + Arc::new(Int32Array::from(vec![Some(1)])), + Arc::new(StringArray::from(vec!["fk_child"])), + Arc::new(StringArray::from(vec!["main"])), + Arc::new(StringArray::from(vec!["s"])), + Arc::new(StringArray::from(vec!["parent"])), + Arc::new(StringArray::from(vec!["id"])), + Arc::new(Int32Array::from(vec![Some(7)])), + ], + ) + .unwrap() + } + + #[test] + fn foreign_keys_renames_to_jdbc_columns_and_nulls_unsourced() { + let out = reshape_foreign_keys(&server_show_foreign_keys()).unwrap(); + assert_eq!( + out.schema() + .fields() + .iter() + .map(|f| f.name().as_str()) + .collect::>(), + vec![ + "PKTABLE_CAT", + "PKTABLE_SCHEM", + "PKTABLE_NAME", + "PKCOLUMN_NAME", + "FKTABLE_CAT", + "FKTABLE_SCHEM", + "FKTABLE_NAME", + "FKCOLUMN_NAME", + "KEY_SEQ", + "UPDATE_RULE", + "DELETE_RULE", + "FK_NAME", + "PK_NAME", + "DEFERRABILITY", + ] + ); + assert_eq!(out.num_rows(), 1); + // Parent (PK) side and foreign (FK) side land in the right columns. + let pk_table = out + .column(2) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(pk_table.value(0), "parent"); + let fk_table = out + .column(6) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(fk_table.value(0), "child"); + // DEFERRABILITY is cast through to SMALLINT (Int16). + let deferr = out + .column(13) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(deferr.value(0), 7); + // No server source → typed nulls, not synthesized values. + assert!(out.column(9).is_null(0)); // UPDATE_RULE + assert!(out.column(10).is_null(0)); // DELETE_RULE + assert!(out.column(12).is_null(0)); // PK_NAME + } } diff --git a/src/metadata_v0.rs b/src/metadata_v0.rs index 56acda96..e0efde55 100644 --- a/src/metadata_v0.rs +++ b/src/metadata_v0.rs @@ -84,7 +84,7 @@ use crate::kernel_error::{Error, Result}; use crate::metadata::static_data; use crate::metadata::thrift_shape::{ self, is_object_not_found, ThriftReshapingReader, GET_CATALOGS_SCHEMA, GET_COLUMNS_SCHEMA, - GET_SCHEMAS_SCHEMA, GET_TABLES_SCHEMA, + GET_CROSS_REFERENCE_SCHEMA, GET_PRIMARY_KEYS_SCHEMA, GET_SCHEMAS_SCHEMA, GET_TABLES_SCHEMA, }; use crate::reader::EmptyReader; use crate::result_stream::ResultStream; @@ -490,9 +490,11 @@ impl Metadata { /// namespace, tableName, col_name, keySeq, constraintName, /// constraintType, parentCatalogName, parentNamespace, /// parentTableName, parentColName, updateRule, deleteRule, - /// deferrability`. Wrappers filter `constraintType = - /// 'PRIMARY KEY'` to isolate the PK rows from the FK rows the - /// server returns alongside. + /// deferrability`. The result is reshaped kernel-side into the + /// JDBC `getPrimaryKeys` column set (`TABLE_CAT`, `TABLE_SCHEM`, + /// `TABLE_NAME`, `COLUMN_NAME`, `KEY_SEQ`, `PK_NAME`) by + /// [`thrift_shape::reshape_primary_keys`] so every binding sees the + /// canonical names without re-mapping. /// /// Catalog and schema are required at the kernel layer: /// Databricks `SHOW KEYS` needs `IN CATALOG / IN SCHEMA / IN @@ -512,7 +514,7 @@ impl Metadata { let schema = schema.ok_or_else(|| { Error::invalid_argument().message("primary_keys requires a schema identifier") })?; - let raw = self + let raw = match self .session .transport() .list_primary_keys( @@ -521,10 +523,23 @@ impl Metadata { schema.as_str(), table.as_str(), ) - .await?; - let stmt_id = raw.statement_id.clone(); - ResultStream::from_reader_with_close(raw.reader, Arc::clone(&self.session), stmt_id) .await + { + Ok(r) => r, + Err(e) => return not_found_or(e, GET_PRIMARY_KEYS_SCHEMA.clone(), Err).await, + }; + let stmt_id = raw.statement_id.clone(); + let reshaped = ThriftReshapingReader::new( + raw.reader, + GET_PRIMARY_KEYS_SCHEMA.clone(), + Box::new(thrift_shape::reshape_primary_keys), + ); + ResultStream::from_reader_with_close( + Box::new(reshaped), + Arc::clone(&self.session), + stmt_id, + ) + .await } .instrument(span) .await @@ -541,6 +556,12 @@ impl Metadata { /// /// Server shape: same as [`primary_keys`](Self::primary_keys) — /// `SHOW FOREIGN KEYS` shares its result schema with `SHOW KEYS`. + /// The result is reshaped kernel-side into the JDBC + /// `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). pub async fn foreign_keys( &self, parent_catalog: Option>, @@ -561,7 +582,7 @@ impl Metadata { let foreign_table = foreign_table.ok_or_else(|| { Error::invalid_argument().message("foreign_keys requires foreign_table") })?; - let raw = self + let raw = match self .session .transport() .list_foreign_keys( @@ -573,10 +594,23 @@ impl Metadata { foreign_schema.as_str(), foreign_table.as_str(), ) - .await?; - let stmt_id = raw.statement_id.clone(); - ResultStream::from_reader_with_close(raw.reader, Arc::clone(&self.session), stmt_id) .await + { + Ok(r) => r, + Err(e) => return not_found_or(e, GET_CROSS_REFERENCE_SCHEMA.clone(), Err).await, + }; + let stmt_id = raw.statement_id.clone(); + let reshaped = ThriftReshapingReader::new( + raw.reader, + GET_CROSS_REFERENCE_SCHEMA.clone(), + Box::new(thrift_shape::reshape_foreign_keys), + ); + ResultStream::from_reader_with_close( + Box::new(reshaped), + Arc::clone(&self.session), + stmt_id, + ) + .await } .instrument(span) .await diff --git a/tests/v0_metadata_e2e.rs b/tests/v0_metadata_e2e.rs index f1db167c..477ecfea 100644 --- a/tests/v0_metadata_e2e.rs +++ b/tests/v0_metadata_e2e.rs @@ -311,7 +311,7 @@ async fn find_known_table(session: &Session) -> Option<(String, String, String)> #[tokio::test] #[ignore] -async fn primary_keys_returns_server_show_keys_columns() { +async fn primary_keys_returns_jdbc_columns() { let session = live_session().await; let Some((cat, schema, table)) = find_known_table(&session).await else { eprintln!("skipping primary_keys E2E — no known sample table reachable"); @@ -328,24 +328,20 @@ async fn primary_keys_returns_server_show_keys_columns() { .await .expect("primary_keys"); - // Live SHOW KEYS shape on Dogfood: 14 columns including - // catalogName / namespace / tableName / col_name / keySeq / - // constraintName / constraintType / parent* / updateRule / - // deleteRule / deferrability. Required minimum: + // Reshaped kernel-side into the JDBC getPrimaryKeys column set + // (the raw SHOW KEYS columns are renamed by reshape_primary_keys). let names = col_names(&stream.schema()); - for required in [ - "catalogName", - "namespace", - "tableName", - "col_name", - "keySeq", - "constraintName", - ] { - assert!( - names.iter().any(|n| n == required), - "expected '{required}' in {names:?}" - ); - } + assert_eq!( + names, + vec![ + "TABLE_CAT", + "TABLE_SCHEM", + "TABLE_NAME", + "COLUMN_NAME", + "KEY_SEQ", + "PK_NAME", + ] + ); let _ = collect(stream).await; session.close().await.expect("close"); @@ -353,7 +349,7 @@ async fn primary_keys_returns_server_show_keys_columns() { #[tokio::test] #[ignore] -async fn foreign_keys_returns_server_show_foreign_keys_columns() { +async fn foreign_keys_returns_jdbc_columns() { let session = live_session().await; let Some((cat, schema, table)) = find_known_table(&session).await else { eprintln!("skipping foreign_keys E2E — no known sample table reachable"); @@ -373,22 +369,29 @@ async fn foreign_keys_returns_server_show_foreign_keys_columns() { .await .expect("foreign_keys"); + // Reshaped kernel-side into the JDBC getCrossReference column set + // (the raw SHOW FOREIGN KEYS columns are renamed by + // reshape_foreign_keys). let names = col_names(&stream.schema()); - for required in [ - "catalogName", - "namespace", - "tableName", - "col_name", - "parentCatalogName", - "parentNamespace", - "parentTableName", - "parentColName", - ] { - assert!( - names.iter().any(|n| n == required), - "expected '{required}' in {names:?}" - ); - } + assert_eq!( + names, + vec![ + "PKTABLE_CAT", + "PKTABLE_SCHEM", + "PKTABLE_NAME", + "PKCOLUMN_NAME", + "FKTABLE_CAT", + "FKTABLE_SCHEM", + "FKTABLE_NAME", + "FKCOLUMN_NAME", + "KEY_SEQ", + "UPDATE_RULE", + "DELETE_RULE", + "FK_NAME", + "PK_NAME", + "DEFERRABILITY", + ] + ); let _ = collect(stream).await; session.close().await.expect("close"); diff --git a/tests/v0_metadata_wiremock.rs b/tests/v0_metadata_wiremock.rs index 08ab50de..3425eb0a 100644 --- a/tests/v0_metadata_wiremock.rs +++ b/tests/v0_metadata_wiremock.rs @@ -513,20 +513,22 @@ async fn list_columns_without_catalog_emits_all_catalogs_query() { } #[tokio::test] -async fn primary_keys_passes_server_columns_through() { +async fn primary_keys_reshaped_to_jdbc_columns() { let server = MockServer::start().await; mount_create_session(&server).await; mount_delete_session(&server).await; - // Live `SHOW KEYS` shape — full 14-column row including the - // parent linkage columns and constraintType. + // Live `SHOW KEYS` shape — the kernel reshapes the server's + // `catalogName / namespace / tableName / col_name / keySeq / + // constraintName` columns into the JDBC `getPrimaryKeys` set. let raw = string_batch(vec![ - ("catalogName", vec![Some("main")]), - ("namespace", vec![Some("d")]), - ("tableName", vec![Some("t")]), - ("col_name", vec![Some("id")]), - ("constraintName", vec![Some("pk_t")]), - ("constraintType", vec![Some("PRIMARY KEY")]), + ("catalogName", vec![Some("main"), Some("main")]), + ("namespace", vec![Some("d"), Some("d")]), + ("tableName", vec![Some("t"), Some("t")]), + ("col_name", vec![Some("id"), Some("code")]), + ("keySeq", vec![Some("1"), Some("2")]), + ("constraintName", vec![Some("pk_t"), Some("pk_t")]), + ("constraintType", vec![Some("PRIMARY"), Some("PRIMARY")]), ]); mount_execute(&server, succeeded_inline_response_body(&raw)).await; @@ -544,25 +546,140 @@ async fn primary_keys_passes_server_columns_through() { assert_eq!( col_names(&stream.schema()), vec![ - "catalogName", - "namespace", - "tableName", - "col_name", - "constraintName", - "constraintType", + "TABLE_CAT", + "TABLE_SCHEM", + "TABLE_NAME", + "COLUMN_NAME", + "KEY_SEQ", + "PK_NAME", ] ); let batches = drain_stream(&mut stream).await; - assert_eq!(batches[0].num_rows(), 1); + assert_eq!(batches[0].num_rows(), 2); assert_eq!( batches[0] - .column_by_name("constraintType") + .column_by_name("TABLE_CAT") + .unwrap() + .as_string::() + .value(0), + "main" + ); + assert_eq!( + batches[0] + .column_by_name("COLUMN_NAME") + .unwrap() + .as_string::() + .value(1), + "code" + ); + let key_seq = batches[0] + .column_by_name("KEY_SEQ") + .unwrap() + .as_any() + .downcast_ref::() + .expect("KEY_SEQ is Int32"); + assert_eq!(key_seq.value(0), 1); + assert_eq!(key_seq.value(1), 2); + assert_eq!( + batches[0] + .column_by_name("PK_NAME") + .unwrap() + .as_string::() + .value(0), + "pk_t" + ); +} + +#[tokio::test] +async fn foreign_keys_reshaped_to_jdbc_columns() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + + // 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. + let raw = string_batch(vec![ + ("catalogName", vec![Some("main")]), + ("namespace", vec![Some("d")]), + ("tableName", vec![Some("child")]), + ("col_name", vec![Some("pid")]), + ("keySeq", vec![Some("1")]), + ("constraintName", vec![Some("fk_child")]), + ("constraintType", vec![Some("FOREIGN")]), + ("parentCatalogName", vec![Some("main")]), + ("parentNamespace", vec![Some("d")]), + ("parentTableName", vec![Some("parent")]), + ("parentColName", vec![Some("id")]), + ("deferrability", vec![Some("7")]), + ]); + mount_execute(&server, succeeded_inline_response_body(&raw)).await; + + let session = open_session(&server).await; + let mut stream = session + .metadata() + .foreign_keys( + None, + None, + None, + Some(Identifier::new("main").unwrap()), + Some(Identifier::new("d").unwrap()), + Some(Identifier::new("child").unwrap()), + ) + .await + .expect("foreign_keys"); + + assert_eq!( + col_names(&stream.schema()), + vec![ + "PKTABLE_CAT", + "PKTABLE_SCHEM", + "PKTABLE_NAME", + "PKCOLUMN_NAME", + "FKTABLE_CAT", + "FKTABLE_SCHEM", + "FKTABLE_NAME", + "FKCOLUMN_NAME", + "KEY_SEQ", + "UPDATE_RULE", + "DELETE_RULE", + "FK_NAME", + "PK_NAME", + "DEFERRABILITY", + ] + ); + + let batches = drain_stream(&mut stream).await; + assert_eq!(batches[0].num_rows(), 1); + let b = &batches[0]; + assert_eq!( + b.column_by_name("PKTABLE_NAME") + .unwrap() + .as_string::() + .value(0), + "parent" + ); + assert_eq!( + b.column_by_name("FKTABLE_NAME") + .unwrap() + .as_string::() + .value(0), + "child" + ); + assert_eq!( + b.column_by_name("FK_NAME") .unwrap() .as_string::() .value(0), - "PRIMARY KEY" + "fk_child" ); + // UPDATE_RULE / DELETE_RULE / PK_NAME have no server source → 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]