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
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,28 @@ determines whether text boxes get drawn and additional settings `padding`,
results in an in-memory cache of its own within one byte budget
(`--results-max-bytes`, default 1 GB, or the `ggsql.resultsMemory`
setting) and never changes the session's reader or dialect (#595).
- ODBC connections to Databricks now pick up Posit Workbench managed
credentials, as Snowflake ones already did: when a connection string names
the Workbench workspace in `Host=` and has no credentials of its own, the
Workbench OAuth token is added.
These tokens last about an hour; when a statement, a catalog lookup for the
Connections pane, or registering or unregistering a table fails because its
token has expired, ggsql reconnects with the current Workbench token and
tries once more. Tables registered before the reconnect are gone after it.

### Changed

- **Breaking**: The `SCALE ... RENAMING` sub clause is renamed to
`SCALE ... LABEL`.
- **Breaking**: The `LABEL` clause is renamed to `TITLE`. The keyword `title`
is now `main` and the `subtitle` keyword is now `sub`.
- On Posit Workbench, ODBC connections to Snowflake get the Workbench OAuth
token only when `Server=` names the Workbench account (its public or
PrivateLink hostname, or the host Workbench names) and the string sets no
`Token=`, `UID=` with `PWD=`, or `Authenticator=` other than `oauth`. A
string for another account no longer receives the token.
- ODBC connection strings are read with braced values (`{...}`) kept whole
and keys matched exactly, so `ProxyUID=` is no longer read as `UID=`.
- Registering a DataFrame of more than 2,048 rows with the DuckDB reader
appends it with DuckDB's Arrow appender rather than one `INSERT` per
2,048-row chunk, about twice as fast on large frames (#617).
Expand Down
124 changes: 112 additions & 12 deletions src/reader/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -643,25 +643,125 @@ pub(crate) fn take_odbc_ggsql_params(conn_str: &str) -> (String, ConnectParams)
(kept.join(";"), ggsql)
}

/// Extract a value from an ODBC connection string by key, stripping braces.
pub fn extract_odbc_value(conn_str: &str, key: &str) -> Option<String> {
let lower = conn_str.to_lowercase();
let prefix = format!("{}=", key);
let start = lower.find(&prefix)?;
let rest = &conn_str[start + prefix.len()..];
let value = rest.split(';').next().unwrap_or("");
let value = value.trim().trim_matches(|c| c == '{' || c == '}');
if value.is_empty() {
None
} else {
Some(value.to_string())
/// Every value of `key` (case-insensitive, whole key) in an ODBC connection
/// string, in order. A value wrapped in `{...}` is read whole, including any
/// `;` or `=` inside it, with `}}` standing for a literal `}`.
pub fn odbc_values(conn_str: &str, key: &str) -> Vec<String> {
odbc_pairs(conn_str)
.into_iter()
.filter(|(k, _)| k.eq_ignore_ascii_case(key))
.map(|(_, v)| v)
.collect()
}

/// Splits an ODBC connection string into `(key, value)` pairs, honoring
/// braced values.
pub(crate) fn odbc_pairs(conn_str: &str) -> Vec<(String, String)> {
let mut pairs = Vec::new();
let mut chars = conn_str.chars().peekable();
while chars.peek().is_some() {
let mut key = String::new();
let mut has_value = false;
for c in chars.by_ref() {
match c {
'=' => {
has_value = true;
break;
}
';' => break,
_ => key.push(c),
}
}
if !has_value {
// A bare attribute with no `=` (e.g. `UseProxy;`).
if !key.trim().is_empty() {
pairs.push((key.trim().to_string(), String::new()));
}
continue;
}
while chars.peek().is_some_and(|c| c.is_whitespace()) {
chars.next();
}
let mut value = String::new();
if chars.peek() == Some(&'{') {
chars.next();
while let Some(c) = chars.next() {
if c == '}' {
if chars.peek() == Some(&'}') {
chars.next();
} else {
break;
}
}
value.push(c);
}
// Anything between the closing brace and the next `;` is ignored.
for c in chars.by_ref() {
if c == ';' {
break;
}
}
} else {
for c in chars.by_ref() {
if c == ';' {
break;
}
value.push(c);
}
}
if !key.trim().is_empty() {
pairs.push((key.trim().to_string(), value.trim().to_string()));
}
}
pairs
}

/// The first non-empty value of `key` in an ODBC connection string, with
/// braces removed (see [`odbc_values`]).
pub fn extract_odbc_value(conn_str: &str, key: &str) -> Option<String> {
odbc_values(conn_str, key)
.into_iter()
.next()
.filter(|value| !value.is_empty())
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_extract_odbc_value_reads_braced_values_whole() {
let conn = "Driver={My;Driver};HTTPPath={/x;Host=evil};Host=h;PWD={p}}q}";
assert_eq!(
extract_odbc_value(conn, "driver").as_deref(),
Some("My;Driver")
);
assert_eq!(
extract_odbc_value(conn, "httppath").as_deref(),
Some("/x;Host=evil")
);
assert_eq!(extract_odbc_value(conn, "host").as_deref(), Some("h"));
assert_eq!(extract_odbc_value(conn, "pwd").as_deref(), Some("p}q"));
assert_eq!(odbc_values(conn, "host"), vec!["h".to_string()]);
assert_eq!(odbc_values("Host=a;host=b", "HOST").len(), 2);
assert_eq!(
extract_odbc_value("UseProxy;Host=h", "host").as_deref(),
Some("h")
);
}

#[test]
fn test_extract_odbc_value_matches_whole_keys_only() {
let conn = "Driver=X;ProxyHost=p;ProxyUID=pu;Host=h; uid = u ";
assert_eq!(extract_odbc_value(conn, "host").as_deref(), Some("h"));
assert_eq!(extract_odbc_value(conn, "uid").as_deref(), Some("u"));
assert_eq!(extract_odbc_value(conn, "pwd"), None);
assert_eq!(
extract_odbc_value("Driver={My Driver}", "driver").as_deref(),
Some("My Driver")
);
}

#[test]
fn test_take_odbc_ggsql_params() {
let (conn, ggsql) = take_odbc_ggsql_params("Driver=X;Server=h;Dialect=ansi;UID=u");
Expand Down
17 changes: 17 additions & 0 deletions src/reader/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1373,6 +1373,12 @@ impl RegisteredTables {
self.0.borrow_mut().remove(name);
}

/// Forget every name, for a reader whose connection was replaced and
/// took its temp tables with it.
pub(crate) fn clear(&self) {
self.0.borrow_mut().clear();
}

pub(crate) fn is_registered(&self, name: &str) -> bool {
self.0.borrow().contains(name)
}
Expand Down Expand Up @@ -1550,6 +1556,17 @@ mod helper_tests {
t.note_unregistered("a");
assert!(!t.is_registered("a"));
}

#[test]
fn registered_tables_clear_forgets_every_name() {
let t = RegisteredTables::new();
t.note_registered("a");
t.note_registered("b");
t.clear();
assert!(!t.is_registered("a"));
assert!(!t.is_registered("b"));
assert!(t.names().is_empty());
}
}

// ============================================================================
Expand Down
Loading
Loading