Skip to content

Commit cd87616

Browse files
committed
fix(metadata): normalize native metadata fallbacks
Signed-off-by: Vu Anh Phung <vu.phung@databricks.com>
1 parent 0a42c4b commit cd87616

10 files changed

Lines changed: 409 additions & 108 deletions

File tree

‎src/client/mod.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,6 @@ pub use retry::{
4646
pub(crate) use sea::SeaRestTransport;
4747
pub(crate) use transport::{
4848
ChunkLinkFetchResult, DirectOutcome, ExecuteResponse, ExecuteResult, ExecuteResultData,
49-
ExecutionTimeout, InlineChunkFetchResult, SessionAttribution, SessionInfo, Transport,
50-
TransportConfig,
49+
ExecutionTimeout, InlineChunkFetchResult, ListFunctionsResult, SessionAttribution, SessionInfo,
50+
Transport, TransportConfig,
5151
};

‎src/client/sea.rs‎

Lines changed: 31 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,8 @@
2020
use crate::client::retry::RequestType;
2121
use crate::client::{
2222
ChunkLinkFetchResult, DatabricksHttpClient, DirectOutcome, ExecuteResponse, ExecuteResult,
23-
ExecuteResultData, ExecutionTimeout, InlineChunkFetchResult, SessionAttribution, SessionInfo,
24-
Transport, TransportConfig,
23+
ExecuteResultData, ExecutionTimeout, InlineChunkFetchResult, ListFunctionsResult,
24+
SessionAttribution, SessionInfo, Transport, TransportConfig,
2525
};
2626
use crate::kernel_error::{Error, Result};
2727
use crate::klog::{debug, warn};
@@ -173,6 +173,7 @@ pub(crate) struct SeaRestTransport {
173173
warehouse_id: String,
174174
config: TransportConfig,
175175
session_version: AtomicI64,
176+
session_catalog: OnceLock<Option<String>>,
176177
reader_factory: OnceLock<ResultReaderFactory>,
177178
runtime_handle: OnceLock<RuntimeHandle>,
178179
}
@@ -214,6 +215,7 @@ impl SeaRestTransport {
214215
warehouse_id: warehouse_id.into(),
215216
config,
216217
session_version: AtomicI64::new(NO_SESSION_VERSION),
218+
session_catalog: OnceLock::new(),
217219
reader_factory: OnceLock::new(),
218220
runtime_handle: OnceLock::new(),
219221
}
@@ -252,6 +254,13 @@ impl SeaRestTransport {
252254
}
253255
}
254256

257+
fn session_catalog_or_hive_metastore(&self) -> &str {
258+
self.session_catalog
259+
.get()
260+
.and_then(Option::as_deref)
261+
.unwrap_or("hive_metastore")
262+
}
263+
255264
/// Build the `/result/chunks/{idx}` URL, optionally with the
256265
/// `row_offset` query parameter set.
257266
///
@@ -1032,6 +1041,7 @@ impl SeaRestTransport {
10321041
&ExecuteParams::default(),
10331042
RequestType::ExecuteMetadataQuery,
10341043
None,
1044+
ExecutionTimeout::Default,
10351045
)
10361046
.await?;
10371047
let statement_id = raw.statement_id.clone();
@@ -1155,6 +1165,7 @@ impl Transport for SeaRestTransport {
11551165
session_config: HashMap<String, String>,
11561166
) -> Result<SessionInfo> {
11571167
let url = format!("{}/sessions", self.base_url());
1168+
let _ = self.session_catalog.set(catalog.map(str::to_owned));
11581169

11591170
let request_body = CreateSessionRequest {
11601171
warehouse_id: self.warehouse_id.clone(),
@@ -1745,18 +1756,18 @@ impl Transport for SeaRestTransport {
17451756
catalog: Option<&str>,
17461757
schema_pattern: Option<&str>,
17471758
function_pattern: Option<&str>,
1748-
) -> Result<ExecuteResult> {
1759+
) -> Result<ListFunctionsResult> {
17491760
let resolved_catalog = match catalog {
17501761
Some(catalog) => catalog.to_owned(),
17511762
None => match self.query_current_catalog(session_id).await {
17521763
Ok(Some(catalog)) if !catalog.is_empty() => catalog,
1753-
Ok(_) => "hive_metastore".to_owned(),
1764+
Ok(_) => self.session_catalog_or_hive_metastore().to_owned(),
17541765
Err(e) => {
17551766
warn!(
17561767
error = %e,
1757-
"failed to query current catalog for list_functions; using hive_metastore"
1768+
"failed to query current catalog for list_functions; using session catalog fallback"
17581769
);
1759-
"hive_metastore".to_owned()
1770+
self.session_catalog_or_hive_metastore().to_owned()
17601771
}
17611772
},
17621773
};
@@ -1766,15 +1777,20 @@ impl Transport for SeaRestTransport {
17661777
function_pattern,
17671778
);
17681779
debug!("list_functions: {}", sql);
1769-
self.execute_and_read(
1770-
session_id,
1771-
&sql,
1772-
&ExecuteParams::default(),
1773-
RequestType::ExecuteMetadataQuery,
1774-
Some(MetadataOperation::Functions),
1775-
ExecutionTimeout::Default,
1776-
)
1777-
.await
1780+
let execute_result = self
1781+
.execute_and_read(
1782+
session_id,
1783+
&sql,
1784+
&ExecuteParams::default(),
1785+
RequestType::ExecuteMetadataQuery,
1786+
Some(MetadataOperation::Functions),
1787+
ExecutionTimeout::Default,
1788+
)
1789+
.await?;
1790+
Ok(ListFunctionsResult {
1791+
execute_result,
1792+
resolved_catalog,
1793+
})
17781794
}
17791795

17801796
async fn list_procedure_columns(

‎src/client/transport.rs‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,12 @@ pub(crate) struct ExecuteResult {
145145
pub status: StatementStatus,
146146
}
147147

148+
/// Result of listing functions, including the catalog used by the SHOW query.
149+
pub(crate) struct ListFunctionsResult {
150+
pub execute_result: ExecuteResult,
151+
pub resolved_catalog: String,
152+
}
153+
148154
impl std::fmt::Debug for ExecuteResult {
149155
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
150156
f.debug_struct("ExecuteResult")
@@ -503,7 +509,7 @@ pub(crate) trait Transport: Send + Sync + std::fmt::Debug {
503509
catalog: Option<&str>,
504510
schema_pattern: Option<&str>,
505511
function_pattern: Option<&str>,
506-
) -> Result<ExecuteResult>;
512+
) -> Result<ListFunctionsResult>;
507513

508514
/// List procedure parameter / return columns, optionally filtered by
509515
/// catalog, schema pattern, procedure name pattern, and column name

‎src/metadata/sql.rs‎

Lines changed: 50 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -39,17 +39,17 @@ impl SqlCommandBuilder {
3939
}
4040

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

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

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

@@ -63,9 +63,10 @@ impl SqlCommandBuilder {
6363
/// - `_` → `.` (single-char wildcard)
6464
/// - `\%` → `%` (escaped literal percent)
6565
/// - `\_` → `_` (escaped literal underscore)
66-
/// - `\\` → `\\` (escaped backslash)
66+
/// - `\\` → `\` (escaped backslash)
6767
///
68-
/// Also escapes single quotes for safe SQL embedding.
68+
/// This only converts wildcards; callers must separately escape the
69+
/// converted value before embedding it in a SQL string literal.
6970
/// Matches JDBC driver's `WildcardUtil.jdbcPatternToHive`.
7071
fn jdbc_pattern_to_hive(pattern: &str) -> String {
7172
let mut result = String::with_capacity(pattern.len());
@@ -77,24 +78,26 @@ impl SqlCommandBuilder {
7778
}
7879
if escape_next {
7980
// Escaped character: emit literally
80-
if ch == '\\' {
81-
result.push_str("\\\\");
82-
} else {
83-
result.push(ch);
84-
}
81+
result.push(ch);
8582
escape_next = false;
8683
} else {
8784
match ch {
8885
'%' => result.push('*'),
8986
'_' => result.push('.'),
90-
'\'' => result.push_str("''"),
9187
_ => result.push(ch),
9288
}
9389
}
9490
}
91+
if escape_next {
92+
result.push('\\');
93+
}
9594
result
9695
}
9796

97+
fn escape_show_pattern(pattern: &str) -> String {
98+
Self::escape_sql_string(&Self::jdbc_pattern_to_hive(pattern))
99+
}
100+
98101
/// Whether an ODBC/JDBC-style pattern contains an *active* wildcard
99102
/// (`%` or `_`) — i.e. one that is not backslash-escaped.
100103
///
@@ -213,7 +216,7 @@ impl SqlCommandBuilder {
213216
};
214217

215218
if let Some(ref pattern) = self.schema_pattern {
216-
sql.push_str(&format!(" LIKE '{}'", pattern));
219+
sql.push_str(&format!(" LIKE '{}'", Self::escape_show_pattern(pattern)));
217220
}
218221

219222
sql
@@ -235,11 +238,14 @@ impl SqlCommandBuilder {
235238
};
236239

237240
if let Some(ref pattern) = self.schema_pattern {
238-
sql.push_str(&format!(" SCHEMA LIKE '{}'", pattern));
241+
sql.push_str(&format!(
242+
" SCHEMA LIKE '{}'",
243+
Self::escape_show_pattern(pattern)
244+
));
239245
}
240246

241247
if let Some(ref pattern) = self.table_pattern {
242-
sql.push_str(&format!(" LIKE '{}'", pattern));
248+
sql.push_str(&format!(" LIKE '{}'", Self::escape_show_pattern(pattern)));
243249
}
244250

245251
sql
@@ -260,15 +266,21 @@ impl SqlCommandBuilder {
260266
};
261267

262268
if let Some(ref pattern) = self.schema_pattern {
263-
sql.push_str(&format!(" SCHEMA LIKE '{}'", pattern));
269+
sql.push_str(&format!(
270+
" SCHEMA LIKE '{}'",
271+
Self::escape_show_pattern(pattern)
272+
));
264273
}
265274

266275
if let Some(ref pattern) = self.table_pattern {
267-
sql.push_str(&format!(" TABLE LIKE '{}'", pattern));
276+
sql.push_str(&format!(
277+
" TABLE LIKE '{}'",
278+
Self::escape_show_pattern(pattern)
279+
));
268280
}
269281

270282
if let Some(ref pattern) = self.column_pattern {
271-
sql.push_str(&format!(" LIKE '{}'", pattern));
283+
sql.push_str(&format!(" LIKE '{}'", Self::escape_show_pattern(pattern)));
272284
}
273285

274286
sql
@@ -278,7 +290,7 @@ impl SqlCommandBuilder {
278290
///
279291
/// Use for `LIKE` pattern values in `information_schema` queries.
280292
/// For identifiers (catalog/schema/table names), use [`escape_identifier`] instead.
281-
/// For `SHOW` command patterns, use [`jdbc_pattern_to_hive`] instead.
293+
/// For `SHOW` command patterns, use [`escape_show_pattern`] instead.
282294
///
283295
/// Databricks SQL treats backslash as an escape character in string literals
284296
/// by default, so both single quotes and backslashes must be escaped.
@@ -358,12 +370,12 @@ impl SqlCommandBuilder {
358370
if let Some(pattern) = schema_pattern {
359371
sql.push_str(&format!(
360372
" SCHEMA LIKE '{}'",
361-
Self::jdbc_pattern_to_hive(pattern)
373+
Self::escape_show_pattern(pattern)
362374
));
363375
}
364376

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

368380
sql
369381
}
@@ -963,6 +975,16 @@ mod tests {
963975
);
964976
}
965977

978+
#[test]
979+
fn test_get_functions_escaped_quotes_are_sql_escaped_once() {
980+
let sql =
981+
SqlCommandBuilder::build_show_functions("main", Some(r"sch\'ema"), Some(r"fn\'name"));
982+
assert_eq!(
983+
sql,
984+
"SHOW FUNCTIONS IN CATALOG `main` SCHEMA LIKE 'sch''ema' LIKE 'fn''name'"
985+
);
986+
}
987+
966988
// --- foreign keys with special characters ---
967989

968990
#[test]
@@ -1001,7 +1023,7 @@ mod tests {
10011023

10021024
#[test]
10031025
fn test_pattern_escaped_backslash() {
1004-
assert_eq!(SqlCommandBuilder::jdbc_pattern_to_hive(r"abc\\"), r"abc\\");
1026+
assert_eq!(SqlCommandBuilder::jdbc_pattern_to_hive(r"abc\\"), r"abc\");
10051027
}
10061028

10071029
#[test]
@@ -1010,8 +1032,13 @@ mod tests {
10101032
}
10111033

10121034
#[test]
1013-
fn test_pattern_single_quote_escaped() {
1014-
assert_eq!(SqlCommandBuilder::jdbc_pattern_to_hive("it's"), "it''s");
1035+
fn test_pattern_single_quote_unchanged() {
1036+
assert_eq!(SqlCommandBuilder::jdbc_pattern_to_hive("it's"), "it's");
1037+
}
1038+
1039+
#[test]
1040+
fn test_pattern_trailing_backslash_preserved() {
1041+
assert_eq!(SqlCommandBuilder::jdbc_pattern_to_hive(r"abc\"), r"abc\");
10151042
}
10161043

10171044
// --- catalog wildcard helpers (list_tables client-side path) ---

‎src/metadata/thrift_shape.rs‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -838,8 +838,11 @@ pub(crate) fn reshape_procedures(batch: &RecordBatch) -> Result<RecordBatch> {
838838
}
839839

840840
/// Reshape the raw `SHOW FUNCTIONS` result into the JDBC `getFunctions` shape.
841-
pub(crate) fn reshape_functions(batch: &RecordBatch) -> Result<RecordBatch> {
842-
let function_cat = utf8_column(batch, "catalogName")?;
841+
pub(crate) fn reshape_functions(
842+
batch: &RecordBatch,
843+
resolved_catalog: &str,
844+
) -> Result<RecordBatch> {
845+
let function_cat = constant_utf8(batch.num_rows(), Some(resolved_catalog));
843846
let function_schem = utf8_column(batch, "namespace")?;
844847
let function_name = utf8_column(batch, "functionName")?;
845848
let remarks = utf8_column(batch, "remarks")?;
@@ -1042,7 +1045,7 @@ pub(crate) fn process_native_tables(
10421045
.ok_or_else(|| Error::data_loss().message("TABLE_CAT is not Utf8"))?;
10431046
let keep = arrow_array::BooleanArray::from(
10441047
(0..batch.num_rows())
1045-
.map(|i| !catalogs.is_null(i) && catalogs.value(i) == catalog)
1048+
.map(|i| !catalogs.is_null(i) && catalogs.value(i).eq_ignore_ascii_case(catalog))
10461049
.collect::<Vec<_>>(),
10471050
);
10481051
arrow_select::filter::filter_record_batch(batch, &keep).map_err(|e| {
@@ -1429,10 +1432,10 @@ mod tests {
14291432
}
14301433

14311434
#[test]
1432-
fn native_tables_apply_catalog_and_type_filters() {
1435+
fn native_tables_apply_case_insensitive_catalog_and_type_filters() {
14331436
let native = reshape_tables(&server_tables_full(), Some("main"), None).unwrap();
14341437

1435-
let views = process_native_tables(&native, Some("main"), Some(&["view"])).unwrap();
1438+
let views = process_native_tables(&native, Some("MAIN"), Some(&["view"])).unwrap();
14361439
assert_eq!(views.num_rows(), 1);
14371440
assert_eq!(
14381441
views
@@ -2060,7 +2063,7 @@ mod tests {
20602063

20612064
#[test]
20622065
fn reshape_functions_produces_jdbc_get_functions_shape() {
2063-
let out = reshape_functions(&server_function_row()).unwrap();
2066+
let out = reshape_functions(&server_function_row(), "main").unwrap();
20642067
assert_eq!(
20652068
col_names(&out),
20662069
vec![

0 commit comments

Comments
 (0)