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 ggsql-jupyter/src/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ pub fn display_name_for_uri(uri: &str) -> String {
pub fn type_name_for_uri(uri: &str) -> String {
if let Some(odbc) = uri.strip_prefix("odbc://") {
let driver = extract_odbc_value(odbc, "driver");
if let Some(entry) = ggsql::reader::registry::detect(None, driver.as_deref()) {
if let Ok(entry) = ggsql::reader::registry::detect(None, driver.as_deref()) {
return entry.display_name.to_string();
}
return "ODBC".to_string();
Expand Down
33 changes: 18 additions & 15 deletions src/reader/adbc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,11 @@ pub struct AdbcReader<D: Driver> {
// takes &self.
connection: RefCell<<D::DatabaseType as Database>::ConnectionType>,
dialect: crate::reader::DialectRef,
/// Registry-declared driver quirks (error-text conventions), when the
/// reader was built for a registered backend. `None` for ad-hoc drivers.
adbc_info: Option<crate::reader::registry::AdbcInfo>,
/// The registry entry for this backend, when the reader was built from
/// a connection string for a registered backend — source of the
/// driver quirks (error-text conventions) honored in `execute_sql` and
/// `register`. `None` for ad-hoc drivers (`new`, `with_dialect`).
entry: Option<&'static crate::reader::registry::DatabaseEntry>,
registered_tables: crate::reader::RegisteredTables,
// Driver-specific statement options (from `stmt.`-prefixed URI params)
// applied to every statement created in execute_sql.
Expand Down Expand Up @@ -62,7 +64,7 @@ impl<D: Driver> AdbcReader<D> {
_database: database,
connection: RefCell::new(connection),
dialect,
adbc_info: None,
entry: None,
registered_tables: crate::reader::RegisteredTables::new(),
statement_opts: Vec::new(),
})
Expand Down Expand Up @@ -93,7 +95,7 @@ impl<D: Driver> AdbcReader<D> {
_database: database,
connection: RefCell::new(connection),
dialect,
adbc_info: None,
entry: None,
registered_tables: crate::reader::RegisteredTables::new(),
statement_opts: Vec::new(),
})
Expand All @@ -112,11 +114,11 @@ impl<D: Driver> AdbcReader<D> {
self
}

/// Attach the registry's driver quirks for this backend, so error-text
/// conventions (DDL-without-result-set signaling, ingest schema
/// mismatches) are honored where the driver requires them.
fn with_adbc_info(mut self, info: crate::reader::registry::AdbcInfo) -> Self {
self.adbc_info = Some(info);
/// Attach the registry entry for this backend, so its driver quirks
/// (DDL-without-result-set signaling, ingest schema mismatches) are
/// honored where the driver requires them.
fn with_entry(mut self, entry: &'static crate::reader::registry::DatabaseEntry) -> Self {
self.entry = Some(entry);
self
}

Expand Down Expand Up @@ -371,10 +373,10 @@ impl AdbcReader<ManagedDriver> {

let reader = Self::new_with_database_opts(driver, dialect, opts)?
.with_statement_opts(conn.ggsql.stmt_options.clone());
// adbc://<driver> with a recognized short name also gets quirks.
// adbc://<driver> with a recognized short name also resolves an entry.
Ok(
match adbc_info_for_scheme(if scheme == "adbc" { body } else { scheme }) {
Some(info) => reader.with_adbc_info(info),
match crate::reader::registry::by_scheme(if scheme == "adbc" { body } else { scheme }) {
Some(entry) => reader.with_entry(entry),
None => reader,
},
)
Expand Down Expand Up @@ -546,7 +548,7 @@ where
// - `ddl_retry_error` (Databricks): the query path cannot
// run resultless statements at all; retry via
// execute_update, the path meant for them.
let info = self.adbc_info;
let info = self.entry.and_then(|e| e.adbc);
if info
.and_then(|i| i.ddl_empty_result_error)
.is_some_and(|needle| msg.contains(needle))
Expand Down Expand Up @@ -695,7 +697,8 @@ where
Ok(_) => break,
Err(e) => {
let schema_mismatch = self
.adbc_info
.entry
.and_then(|e| e.adbc)
.and_then(|i| i.ingest_schema_align_error)
.is_some_and(|needle| e.to_string().contains(needle));
if attempts == 0 && schema_mismatch {
Expand Down
9 changes: 8 additions & 1 deletion src/reader/dialects/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,14 @@ pub(crate) fn case_least(exprs: &[&str]) -> String {
#[cfg(test)]
mod tests {
use super::*;
use crate::reader::registry::{by_scheme, detect_or_err as detect_dialect};
use crate::reader::registry::{by_scheme, detect};

fn detect_dialect(
dbms_name: Option<&str>,
driver_hint: Option<&str>,
) -> crate::Result<crate::reader::DialectRef> {
detect(dbms_name, driver_hint).map(|e| e.dialect())
}

fn dialect_for_scheme(scheme: &str) -> Option<crate::reader::DialectRef> {
by_scheme(scheme).map(|e| e.dialect())
Expand Down
64 changes: 33 additions & 31 deletions src/reader/odbc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

#[allow(dead_code)]
pub(crate) mod ffi;
mod snowflake;
pub(crate) mod snowflake;
mod wrapper;

use crate::reader::Reader;
Expand All @@ -18,15 +18,6 @@ use ffi::*;
use std::sync::Arc;
use wrapper::{Connection, Statement};

/// Detect the backend SQL dialect from the DBMS name and connection string.
///
/// Delegates to the shared matcher in [`crate::reader::dialects`]; the
/// `Driver=` value from the ODBC connection string serves as the driver hint.
fn detect_dialect(dbms_name: Option<&str>, conn_str: &str) -> Result<super::DialectRef> {
let driver = super::connection::extract_odbc_value(conn_str, "driver");
super::registry::detect_or_err(dbms_name, driver.as_deref())
}

/// Pull ggsql-owned keys (`Dialect=<name>`) out of an ODBC connection
/// string before connecting. `Dialect=` is ggsql's escape hatch for unknown
/// backends, not a driver option — drivers reject unknown keys.
Expand Down Expand Up @@ -82,16 +73,16 @@ impl OdbcReader {
(None, None) => None,
};

if snowflake::is_snowflake(&conn_str) {
if let Some(resolved) = snowflake::resolve_connection_name(&conn_str) {
conn_str = resolved;
}
}

if snowflake::is_snowflake(&conn_str) && !snowflake::has_token(&conn_str) {
if let Some(token) = snowflake::detect_workbench_token() {
conn_str = snowflake::inject_snowflake_token(&conn_str, &token);
}
// Backend-specific credential resolution (Snowflake Workbench OAuth
// tokens, `ConnectionName=` lookup), dispatched through the registry
// on the `Driver=` value — the DBMS name isn't known until after
// connecting, which is too late to supply credentials.
let driver = super::connection::extract_odbc_value(&conn_str, "driver");
if let Some(apply) = super::registry::detect(None, driver.as_deref())
.ok()
.and_then(|e| e.odbc_credential_provider)
{
apply(&mut conn_str);
}

let connection = match Connection::connect(wrapper::odbc_env()?, &conn_str) {
Expand All @@ -110,20 +101,27 @@ impl OdbcReader {
};

let dbms_name = connection.dbms_name();

let dialect = match dialect {
Some(d) => d,
None => detect_dialect(dbms_name.as_deref(), &conn_str)?,
let driver = super::connection::extract_odbc_value(&conn_str, "driver");

// One registry resolution per connection: dialect and fetch behavior
// both derive from the same entry. With a pinned dialect the entry
// is best-effort (fetch quirks only); without one the entry must
// resolve so the dialect can come from it.
let (entry, dialect) = match dialect {
Some(d) => (
super::registry::detect(dbms_name.as_deref(), driver.as_deref()).ok(),
d,
),
None => {
let entry = super::registry::detect(dbms_name.as_deref(), driver.as_deref())?;
(Some(entry), entry.dialect())
}
};

// Fetch behavior is a per-backend capability: Oracle ODBC rejects
// block cursors (`odbc_row_array_size`; HY090 at SQLFetch time, and
// the failed fetch leaves the cursor unusable) and cannot convert
// DECIMAL to integer C types (`odbc_numeric_as_double`).
let entry = super::registry::detect(
dbms_name.as_deref(),
super::connection::extract_odbc_value(&conn_str, "driver").as_deref(),
);
let batch_size = entry
.and_then(|e| e.odbc_row_array_size)
.unwrap_or(BATCH_SIZE);
Expand Down Expand Up @@ -841,13 +839,17 @@ mod tests {

#[test]
fn test_detect_dialect_from_dbms_name() {
let d = detect_dialect(Some("Snowflake"), "anything").unwrap();
let d = crate::reader::registry::detect(Some("Snowflake"), None)
.unwrap()
.dialect();
assert!(!d.sql_greatest(&["a", "b"]).is_empty());

let d = detect_dialect(None, "Driver=Snowflake;Server=foo").unwrap();
let d = crate::reader::registry::detect(None, Some("Snowflake ODBC Driver"))
.unwrap()
.dialect();
assert!(!d.sql_greatest(&["a", "b"]).is_empty());

let err = detect_dialect(None, "Driver=SomeOther;Server=localhost")
let err = crate::reader::registry::detect(None, Some("SomeOther"))
.err()
.unwrap()
.to_string();
Expand Down
39 changes: 30 additions & 9 deletions src/reader/odbc/snowflake.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,19 @@
//! Snowflake Workbench credential detection and connection resolution.

pub(super) fn is_snowflake(conn_str: &str) -> bool {
crate::reader::connection::extract_odbc_value(conn_str, "driver")
.map(|d| d.to_lowercase().contains("snowflake"))
.unwrap_or(false)
/// Registry `odbc_credential_provider` hook for Snowflake: rewrite the
/// connection string to supply credentials before connecting. Resolves a
/// `ConnectionName=` reference from `~/.snowflake/connections.toml`, then
/// injects a Posit Workbench OAuth token when one is available and the
/// string doesn't carry a token already.
pub(crate) fn apply_workbench_credentials(conn_str: &mut String) {
if let Some(resolved) = resolve_connection_name(conn_str) {
*conn_str = resolved;
}
if !has_token(conn_str) {
if let Some(token) = detect_workbench_token() {
*conn_str = inject_snowflake_token(conn_str, &token);
}
}
}

pub(super) fn has_token(conn_str: &str) -> bool {
Expand Down Expand Up @@ -169,11 +179,22 @@ mod tests {
use super::*;

#[test]
fn test_is_snowflake() {
assert!(is_snowflake(
"Driver=Snowflake;Server=foo.snowflakecomputing.com"
));
assert!(!is_snowflake("Driver={PostgreSQL};Server=localhost"));
fn test_credential_hook_dispatches_on_driver() {
// The registry dispatches the credential hook on the Driver= value.
let driver = crate::reader::connection::extract_odbc_value(
"Driver=Snowflake;Server=foo.snowflakecomputing.com",
"driver",
);
let entry = crate::reader::registry::detect(None, driver.as_deref()).unwrap();
assert_eq!(entry.scheme, "snowflake");
assert!(entry.odbc_credential_provider.is_some());

let driver = crate::reader::connection::extract_odbc_value(
"Driver={PostgreSQL};Server=localhost",
"driver",
);
let entry = crate::reader::registry::detect(None, driver.as_deref()).unwrap();
assert!(entry.odbc_credential_provider.is_none());
}

#[test]
Expand Down
Loading
Loading