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
2 changes: 1 addition & 1 deletion napi/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1125,7 +1125,7 @@ export declare class Connection {
* Primary keys for the given table. All three identifiers are
* exact — ODBC `SQLPrimaryKeys` does not support patterns.
*/
getPrimaryKeys(catalog: string, schema: string, table: string): Promise<Statement>
getPrimaryKeys(catalog: string | undefined | null, schema: string | undefined | null, table: string): Promise<Statement>
/**
* Foreign-key relationships. The parent side is optional. When the
* foreign table is omitted, returns an empty result without issuing a
Expand Down
122 changes: 110 additions & 12 deletions napi/src/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -305,15 +305,21 @@ impl Connection {
#[napi]
pub async fn get_primary_keys(
&self,
catalog: String,
schema: String,
catalog: Option<String>,
schema: Option<String>,
table: String,
) -> napi::Result<Statement> {
let meta = take_metadata(&self.inner).await?;
guarded(async move {
let stream = run_on_blocking(move || async move {
let cat = Some(Identifier::new(&catalog)?);
let sch = Some(Identifier::new(&schema)?);
let cat = catalog
.as_deref()
.map(Identifier::new_allow_empty)
.transpose()?;
let sch = schema
.as_deref()
.map(Identifier::new_allow_empty)
.transpose()?;
let tbl = Identifier::new(&table)?;
meta.primary_keys(cat, sch, tbl).await
})
Expand Down Expand Up @@ -362,7 +368,7 @@ mod tests {
use databricks_sql_kernel::{AuthConfig, ConnectionConfig, ErrorCode, Session};
use serde_json::json;
use tokio::sync::Mutex;
use wiremock::matchers::{method, path};
use wiremock::matchers::{body_partial_json, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

// The `Option<String>` → kernel-newtype conversion now lives on the
Expand Down Expand Up @@ -397,21 +403,19 @@ mod tests {
assert!(LikePattern::from_opt(&input).unwrap().is_none());
}

#[tokio::test]
async fn metadata_short_circuits_return_empty_without_statement_request() {
let server = MockServer::start().await;
async fn open_mock_connection(server: &MockServer) -> Connection {
Mock::given(method("POST"))
.and(path("/api/2.0/sql/sessions"))
.respond_with(
ResponseTemplate::new(200)
.set_body_json(json!({ "session_id": "sess-napi-metadata" })),
)
.mount(&server)
.mount(server)
.await;
Mock::given(method("DELETE"))
.and(path("/api/2.0/sql/sessions/sess-napi-metadata"))
.respond_with(ResponseTemplate::new(200))
.mount(&server)
.mount(server)
.await;

let session = Session::builder()
Expand All @@ -426,10 +430,16 @@ mod tests {
.open()
.await
.expect("session opens against mock server");
let connection = Connection {
Connection {
inner: Arc::new(Mutex::new(Some(session))),
session_id: "sess-napi-metadata".to_owned(),
};
}
}

#[tokio::test]
async fn metadata_short_circuits_return_empty_without_statement_request() {
let server = MockServer::start().await;
let connection = open_mock_connection(&server).await;

let statements = [
connection
Expand Down Expand Up @@ -476,4 +486,92 @@ mod tests {

connection.close().await.expect("connection closes");
}

#[tokio::test]
async fn primary_keys_accepts_null_and_empty_namespace_and_keeps_table_validation() {
let server = MockServer::start().await;
let connection = open_mock_connection(&server).await;
Mock::given(method("POST"))
.and(path("/api/2.0/sql/statements"))
.and(body_partial_json(json!({
"statement": "SHOW KEYS IN CATALOG `` IN SCHEMA `` IN TABLE `t`",
"session_id": "sess-napi-metadata",
})))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"statement_id": "stmt-empty-namespace",
"status": {
"state": "FAILED",
"sql_state": "42704",
"error": {
"error_code": "BAD_REQUEST",
"message": "NO_SUCH_CATALOG_EXCEPTION",
},
},
})))
.expect(1)
.mount(&server)
.await;

let statement = connection
.get_primary_keys(Some(String::new()), Some(String::new()), "t".to_owned())
.await
.expect("empty names reach SHOW KEYS");
assert!(statement.fetch_next_batch().await.unwrap().is_none());
statement.close().await.unwrap();

Mock::given(method("POST"))
.and(path("/api/2.0/sql/statements"))
.and(body_partial_json(json!({
"statement": "SELECT CURRENT_CATALOG(), CURRENT_SCHEMA()",
"session_id": "sess-napi-metadata",
})))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"statement_id": "stmt-current-namespace",
"status": {
"state": "FAILED",
"sql_state": "42501",
"error": {
"error_code": "BAD_REQUEST",
"message": "PERMISSION_DENIED",
},
},
})))
.expect(1)
.mount(&server)
.await;

let error = match connection
.get_primary_keys(None, None, "t".to_owned())
.await
{
Ok(_) => panic!("lookup error must propagate"),
Err(error) => error,
};
assert!(error.reason.contains("PERMISSION_DENIED"));

for table in ["", " "] {
let error = match connection
.get_primary_keys(None, None, table.to_owned())
.await
{
Ok(_) => panic!("invalid table name must fail"),
Err(error) => error,
};
assert!(error.reason.contains("InvalidArgument"));
}
let requests = server.received_requests().await.unwrap();
assert_eq!(
requests
.iter()
.filter(|request| {
request.method.as_str() == "POST"
&& request.url.path() == "/api/2.0/sql/statements"
})
.count(),
2,
"invalid table names must not execute a statement"
);
connection.close().await.unwrap();
server.verify().await;
}
}
73 changes: 62 additions & 11 deletions src/metadata_v0.rs
Original file line number Diff line number Diff line change
Expand Up @@ -461,7 +461,7 @@ impl<'a> LikePattern<'a> {
/// pattern filter.
///
/// Non-empty catalogs remain exact [`Identifier`]s. An empty catalog cannot
/// be represented as an `Identifier`, but JDBC metadata semantics require it
/// be represented by `Identifier::new`, but JDBC metadata semantics require it
/// to match nothing rather than fail validation. Encode that case as an empty
/// [`LikePattern`] on the accompanying pattern dimension; metadata methods
/// short-circuit empty patterns to a typed empty result before any wire call.
Expand Down Expand Up @@ -565,6 +565,51 @@ impl Metadata {
catalog
}

async fn current_catalog_and_schema(&self) -> Result<(String, String)> {
let mut statement = Statement::new(Arc::clone(&self.session));
statement
.spec()
.sql("SELECT CURRENT_CATALOG(), CURRENT_SCHEMA()");
let mut executed = statement.execute().await?;

let namespace = match executed.next_batch().await {
Ok(Some(ResultBatch::Arrow(batch))) => (|| {
if batch.num_columns() != 2 || batch.num_rows() == 0 {
return Err(Error::data_loss()
.message("Current catalog/schema returned no rows or unexpected columns"));
}
let read_name = |index: usize, function: &str| -> Result<String> {
let names = batch
.column(index)
.as_any()
.downcast_ref::<arrow_array::StringArray>()
.ok_or_else(|| {
Error::data_loss()
.message(format!("{function} result is not a UTF-8 string"))
})?;
if names.is_null(0) {
Err(Error::data_loss().message(format!("{function} returned null")))
} else {
Ok(names.value(0).to_owned())
}
};
Ok((
read_name(0, "CURRENT_CATALOG()")?,
read_name(1, "CURRENT_SCHEMA()")?,
))
})(),
Ok(None) => {
Err(Error::data_loss().message("Current catalog/schema returned no result"))
}
Err(error) => Err(error),
};

if let Err(error) = executed.close().await {
debug!(error = %error, "failed to close current catalog/schema statement");
}
namespace
}

async fn resolve_functions_catalog(&self) -> String {
match self.current_catalog().await {
Ok(catalog) => catalog,
Expand Down Expand Up @@ -1175,10 +1220,9 @@ impl Metadata {
/// [`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
/// TABLE` fully qualified. Wrappers that want to fall back to a
/// session default should resolve it before calling.
/// Missing catalog or schema names resolve independently from the
/// current session. Explicit empty names are preserved when constructed
/// with [`Identifier::new_allow_empty`].
Comment thread
vuanhphung marked this conversation as resolved.
Resolved
pub async fn primary_keys(
&self,
catalog: Option<Identifier<'_>>,
Expand All @@ -1189,12 +1233,19 @@ impl Metadata {
let telemetry = self.metadata_telemetry(OperationType::ListPrimaryKeys);
let telemetry_for_body = telemetry.clone();
let result = async {
let catalog = catalog.ok_or_else(|| {
Error::invalid_argument().message("primary_keys requires a catalog identifier")
})?;
let schema = schema.ok_or_else(|| {
Error::invalid_argument().message("primary_keys requires a schema identifier")
})?;
let (current_catalog, current_schema) = if catalog.is_none() || schema.is_none() {
Comment thread
vuanhphung marked this conversation as resolved.
Resolved

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 — When exactly one of catalog/schema is supplied and the other is None, the omitted dimension is filled from the session's current namespace independently of the supplied dimension. For primary_keys(Some("other_cat"), None, table) this pairs the explicit catalog other_cat with the session's CURRENT_SCHEMA() — a schema name that is only meaningful inside the current catalog, not inside other_cat. The resulting SHOW KEYS IN CATALOG \other_cat` IN SCHEMA `<current_schema>` IN TABLE ...` can target a schema that doesn't exist under the explicit catalog, yielding a confusing not-found rather than the keys the caller expected.

This matches the PR's stated "resolve independently from the current session" intent and the all-None / all-explicit paths are correct, so this is a minor edge. If the mixed case is intended to be supported, consider only resolving the current schema when the catalog is also unspecified (or documenting that a partial override is not supported).

self.current_catalog_and_schema().await?
} else {
(String::new(), String::new())
};
let catalog = match catalog {
Some(catalog) => catalog,
None => Identifier::new(&current_catalog)?,
};
let schema = match schema {
Some(schema) => schema,
None => Identifier::new(&current_schema)?,
};
let raw = match self
.session
.transport()
Expand Down
12 changes: 8 additions & 4 deletions src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3227,16 +3227,20 @@ mod is_open_tests {
telemetry_test_session(&server, "sess-telemetry-metadata-error", telemetry).await;

let table = crate::metadata_v0::Identifier::new("tbl").expect("valid table id");
let error = match session.metadata().primary_keys(None, None, table).await {
Ok(_) => panic!("missing catalog/schema should fail"),
let error = match session
.metadata()
.foreign_keys(None, None, None, None, None, Some(table))
.await
{
Ok(_) => panic!("missing foreign catalog/schema should fail"),
Err(error) => error,
};
assert_eq!(error.code, crate::kernel_error::ErrorCode::InvalidArgument);
session.close().await.expect("close succeeds");

let metadata_log = exported_logs(&exporter)
.into_iter()
.find(|log| operation_type(log) == Some("LIST_PRIMARY_KEYS"))
.find(|log| operation_type(log) == Some("LIST_CROSS_REFERENCES"))
.expect("metadata error event exported");
let sql_log = &metadata_log["entry"]["sql_driver_log"];
assert_eq!(sql_log["sql_operation"]["statement_type"], "METADATA");
Expand All @@ -3252,7 +3256,7 @@ mod is_open_tests {
assert!(
!serde_json::to_string(&metadata_log)
.expect("metadata log json")
.contains("primary_keys requires a catalog identifier"),
.contains("foreign_keys requires foreign_catalog"),
"metadata telemetry should not include raw error messages"
);
}
Expand Down
Loading
Loading