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 src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,6 @@ pub use retry::{
pub(crate) use sea::SeaRestTransport;
pub(crate) use transport::{
ChunkLinkFetchResult, DirectOutcome, ExecuteResponse, ExecuteResult, ExecuteResultData,
ExecutionTimeout, InlineChunkFetchResult, SessionAttribution, SessionInfo, Transport,
TransportConfig,
ExecutionTimeout, InlineChunkFetchResult, ListFunctionsResult, SessionAttribution, SessionInfo,
Transport, TransportConfig,
};
45 changes: 30 additions & 15 deletions src/client/sea.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@
use crate::client::retry::RequestType;
use crate::client::{
ChunkLinkFetchResult, DatabricksHttpClient, DirectOutcome, ExecuteResponse, ExecuteResult,
ExecuteResultData, ExecutionTimeout, InlineChunkFetchResult, SessionAttribution, SessionInfo,
Transport, TransportConfig,
ExecuteResultData, ExecutionTimeout, InlineChunkFetchResult, ListFunctionsResult,
SessionAttribution, SessionInfo, Transport, TransportConfig,
};
use crate::kernel_error::{Error, Result};
use crate::klog::{debug, warn};
Expand Down Expand Up @@ -173,6 +173,7 @@ pub(crate) struct SeaRestTransport {
warehouse_id: String,
config: TransportConfig,
session_version: AtomicI64,
session_catalog: OnceLock<Option<String>>,
reader_factory: OnceLock<ResultReaderFactory>,
runtime_handle: OnceLock<RuntimeHandle>,
}
Expand Down Expand Up @@ -214,6 +215,7 @@ impl SeaRestTransport {
warehouse_id: warehouse_id.into(),
config,
session_version: AtomicI64::new(NO_SESSION_VERSION),
session_catalog: OnceLock::new(),
reader_factory: OnceLock::new(),
runtime_handle: OnceLock::new(),
}
Expand Down Expand Up @@ -252,6 +254,13 @@ impl SeaRestTransport {
}
}

fn session_catalog_or_hive_metastore(&self) -> &str {
self.session_catalog
.get()
.and_then(Option::as_deref)
.unwrap_or("hive_metastore")
}

/// Build the `/result/chunks/{idx}` URL, optionally with the
/// `row_offset` query parameter set.
///
Expand Down Expand Up @@ -1156,6 +1165,7 @@ impl Transport for SeaRestTransport {
session_config: HashMap<String, String>,
) -> Result<SessionInfo> {
let url = format!("{}/sessions", self.base_url());
let _ = self.session_catalog.set(catalog.map(str::to_owned));

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 create_session fallback catalog is cached via session_catalog.set(...) with the Result discarded. This is correct for the normal 1:1 transport→session lifecycle, but because session_catalog is a OnceLock, a second create_session on the same transport (e.g. a future session re-establishment path) would silently keep the first catalog and drop the new one, so session_catalog_or_hive_metastore() would resolve to a stale catalog with no warning. Not reachable today (each SeaRestTransport opens one session), so filing as Low — consider either asserting/logging on a non-first set, or documenting the single-open invariant next to the field.


let request_body = CreateSessionRequest {
warehouse_id: self.warehouse_id.clone(),
Expand Down Expand Up @@ -1746,18 +1756,18 @@ impl Transport for SeaRestTransport {
catalog: Option<&str>,
schema_pattern: Option<&str>,
function_pattern: Option<&str>,
) -> Result<ExecuteResult> {
) -> Result<ListFunctionsResult> {
let resolved_catalog = match catalog {
Some(catalog) => catalog.to_owned(),
None => match self.query_current_catalog(session_id).await {
Ok(Some(catalog)) if !catalog.is_empty() => catalog,
Ok(_) => "hive_metastore".to_owned(),
Ok(_) => self.session_catalog_or_hive_metastore().to_owned(),
Err(e) => {
warn!(
error = %e,
"failed to query current catalog for list_functions; using hive_metastore"
"failed to query current catalog for list_functions; using session catalog fallback"
);
"hive_metastore".to_owned()
self.session_catalog_or_hive_metastore().to_owned()
}
},
};
Expand All @@ -1767,15 +1777,20 @@ impl Transport for SeaRestTransport {
function_pattern,
);
debug!("list_functions: {}", sql);
self.execute_and_read(
session_id,
&sql,
&ExecuteParams::default(),
RequestType::ExecuteMetadataQuery,
Some(MetadataOperation::Functions),
ExecutionTimeout::Default,
)
.await
let execute_result = self
.execute_and_read(
session_id,
&sql,
&ExecuteParams::default(),
RequestType::ExecuteMetadataQuery,
Some(MetadataOperation::Functions),
ExecutionTimeout::Default,
)
.await?;
Ok(ListFunctionsResult {
execute_result,
resolved_catalog,
})
}

async fn list_procedure_columns(
Expand Down
8 changes: 7 additions & 1 deletion src/client/transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,12 @@ pub(crate) struct ExecuteResult {
pub status: StatementStatus,
}

/// Result of listing functions, including the catalog used by the SHOW query.
pub(crate) struct ListFunctionsResult {
pub execute_result: ExecuteResult,
pub resolved_catalog: String,
}

impl std::fmt::Debug for ExecuteResult {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ExecuteResult")
Expand Down Expand Up @@ -503,7 +509,7 @@ pub(crate) trait Transport: Send + Sync + std::fmt::Debug {
catalog: Option<&str>,
schema_pattern: Option<&str>,
function_pattern: Option<&str>,
) -> Result<ExecuteResult>;
) -> Result<ListFunctionsResult>;

/// List procedure parameter / return columns, optionally filtered by
/// catalog, schema pattern, procedure name pattern, and column name
Expand Down
73 changes: 50 additions & 23 deletions src/metadata/sql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,17 +39,17 @@ impl SqlCommandBuilder {
}

pub fn with_schema_pattern(mut self, pattern: Option<&str>) -> Self {
self.schema_pattern = pattern.map(Self::jdbc_pattern_to_hive);
self.schema_pattern = pattern.map(str::to_owned);
self
}

pub fn with_table_pattern(mut self, pattern: Option<&str>) -> Self {
self.table_pattern = pattern.map(Self::jdbc_pattern_to_hive);
self.table_pattern = pattern.map(str::to_owned);
self
}

pub fn with_column_pattern(mut self, pattern: Option<&str>) -> Self {
self.column_pattern = pattern.map(Self::jdbc_pattern_to_hive);
self.column_pattern = pattern.map(str::to_owned);
self
}

Expand All @@ -63,9 +63,10 @@ impl SqlCommandBuilder {
/// - `_` → `.` (single-char wildcard)
/// - `\%` → `%` (escaped literal percent)
/// - `\_` → `_` (escaped literal underscore)
/// - `\\` → `\\` (escaped backslash)
/// - `\\` → `\` (escaped backslash)
///
/// Also escapes single quotes for safe SQL embedding.
/// This only converts wildcards; callers must separately escape the
/// converted value before embedding it in a SQL string literal.
/// Matches JDBC driver's `WildcardUtil.jdbcPatternToHive`.
fn jdbc_pattern_to_hive(pattern: &str) -> String {
let mut result = String::with_capacity(pattern.len());
Expand All @@ -77,24 +78,26 @@ impl SqlCommandBuilder {
}
if escape_next {
// Escaped character: emit literally
if ch == '\\' {
result.push_str("\\\\");
} else {
result.push(ch);
}
result.push(ch);
escape_next = false;
} else {
match ch {
'%' => result.push('*'),
'_' => result.push('.'),
'\'' => result.push_str("''"),
_ => result.push(ch),
}
}
}
if escape_next {
result.push('\\');
}
result
}

fn escape_show_pattern(pattern: &str) -> String {
Self::escape_sql_string(&Self::jdbc_pattern_to_hive(pattern))
}

/// Whether an ODBC/JDBC-style pattern contains an *active* wildcard
/// (`%` or `_`) — i.e. one that is not backslash-escaped.
///
Expand Down Expand Up @@ -213,7 +216,7 @@ impl SqlCommandBuilder {
};

if let Some(ref pattern) = self.schema_pattern {
sql.push_str(&format!(" LIKE '{}'", pattern));
sql.push_str(&format!(" LIKE '{}'", Self::escape_show_pattern(pattern)));
}

sql
Expand All @@ -235,11 +238,14 @@ impl SqlCommandBuilder {
};

if let Some(ref pattern) = self.schema_pattern {
sql.push_str(&format!(" SCHEMA LIKE '{}'", pattern));
sql.push_str(&format!(
" SCHEMA LIKE '{}'",
Self::escape_show_pattern(pattern)
));
}

if let Some(ref pattern) = self.table_pattern {
sql.push_str(&format!(" LIKE '{}'", pattern));
sql.push_str(&format!(" LIKE '{}'", Self::escape_show_pattern(pattern)));
}

sql
Expand All @@ -260,15 +266,21 @@ impl SqlCommandBuilder {
};

if let Some(ref pattern) = self.schema_pattern {
sql.push_str(&format!(" SCHEMA LIKE '{}'", pattern));
sql.push_str(&format!(
" SCHEMA LIKE '{}'",
Self::escape_show_pattern(pattern)
));
}

if let Some(ref pattern) = self.table_pattern {
sql.push_str(&format!(" TABLE LIKE '{}'", pattern));
sql.push_str(&format!(
" TABLE LIKE '{}'",
Self::escape_show_pattern(pattern)
));
}

if let Some(ref pattern) = self.column_pattern {
sql.push_str(&format!(" LIKE '{}'", pattern));
sql.push_str(&format!(" LIKE '{}'", Self::escape_show_pattern(pattern)));
}

sql
Expand All @@ -278,7 +290,7 @@ impl SqlCommandBuilder {
///
/// Use for `LIKE` pattern values in `information_schema` queries.
/// For identifiers (catalog/schema/table names), use [`escape_identifier`] instead.
/// For `SHOW` command patterns, use [`jdbc_pattern_to_hive`] instead.
/// For `SHOW` command patterns, use [`escape_show_pattern`] instead.
///
/// Databricks SQL treats backslash as an escape character in string literals
/// by default, so both single quotes and backslashes must be escaped.
Expand Down Expand Up @@ -358,12 +370,12 @@ impl SqlCommandBuilder {
if let Some(pattern) = schema_pattern {
sql.push_str(&format!(
" SCHEMA LIKE '{}'",
Self::jdbc_pattern_to_hive(pattern)
Self::escape_show_pattern(pattern)
));
}

let pattern = function_pattern.unwrap_or("%");
sql.push_str(&format!(" LIKE '{}'", Self::jdbc_pattern_to_hive(pattern)));
sql.push_str(&format!(" LIKE '{}'", Self::escape_show_pattern(pattern)));

sql
}
Expand Down Expand Up @@ -963,6 +975,16 @@ mod tests {
);
}

#[test]
fn test_get_functions_escaped_quotes_are_sql_escaped_once() {
let sql =
SqlCommandBuilder::build_show_functions("main", Some(r"sch\'ema"), Some(r"fn\'name"));
assert_eq!(
sql,
"SHOW FUNCTIONS IN CATALOG `main` SCHEMA LIKE 'sch''ema' LIKE 'fn''name'"
);
}

// --- foreign keys with special characters ---

#[test]
Expand Down Expand Up @@ -1001,7 +1023,7 @@ mod tests {

#[test]
fn test_pattern_escaped_backslash() {
assert_eq!(SqlCommandBuilder::jdbc_pattern_to_hive(r"abc\\"), r"abc\\");
assert_eq!(SqlCommandBuilder::jdbc_pattern_to_hive(r"abc\\"), r"abc\");
}

#[test]
Expand All @@ -1010,8 +1032,13 @@ mod tests {
}

#[test]
fn test_pattern_single_quote_escaped() {
assert_eq!(SqlCommandBuilder::jdbc_pattern_to_hive("it's"), "it''s");
fn test_pattern_single_quote_unchanged() {
assert_eq!(SqlCommandBuilder::jdbc_pattern_to_hive("it's"), "it's");
}

#[test]
fn test_pattern_trailing_backslash_preserved() {
assert_eq!(SqlCommandBuilder::jdbc_pattern_to_hive(r"abc\"), r"abc\");
}

// --- catalog wildcard helpers (list_tables client-side path) ---
Expand Down
9 changes: 6 additions & 3 deletions src/metadata/thrift_shape.rs
Original file line number Diff line number Diff line change
Expand Up @@ -838,8 +838,11 @@ pub(crate) fn reshape_procedures(batch: &RecordBatch) -> Result<RecordBatch> {
}

/// Reshape the raw `SHOW FUNCTIONS` result into the JDBC `getFunctions` shape.
pub(crate) fn reshape_functions(batch: &RecordBatch) -> Result<RecordBatch> {
let function_cat = utf8_column(batch, "catalogName")?;
pub(crate) fn reshape_functions(
batch: &RecordBatch,
resolved_catalog: &str,
) -> Result<RecordBatch> {
let function_cat = constant_utf8(batch.num_rows(), Some(resolved_catalog));
let function_schem = utf8_column(batch, "namespace")?;
let function_name = utf8_column(batch, "functionName")?;
let remarks = utf8_column(batch, "remarks")?;
Expand Down Expand Up @@ -2060,7 +2063,7 @@ mod tests {

#[test]
fn reshape_functions_produces_jdbc_get_functions_shape() {
let out = reshape_functions(&server_function_row()).unwrap();
let out = reshape_functions(&server_function_row(), "main").unwrap();
assert_eq!(
col_names(&out),
vec![
Expand Down
Loading
Loading