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
6 changes: 6 additions & 0 deletions NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,12 @@ changes go in their respective binding's NEXT_CHANGELOG.
- Configure the Arrow result LZ4 session default with `ResultConfig.lz4_compression_enabled`
(client config key `lz4_compression_enabled`) and override it with `StatementSpec::lz4_compression`.
ADBC exposes the default through `adbc.databricks.enable_query_result_lz4_compression`.
- C ABI: `kernel_statement_set_volume_options`, the
`kernel_*_is_volume_operation` flags, and `kernel_get_last_error_code` /
`_local_os_error` / `_local_path`.
- ADBC: the `adbc.databricks.statement.staging_allowed_local_paths` statement
option runs Volume transfers. The driver takes no upload bytes, so a
`PUT '__input_stream__'` fails with `InvalidArguments`.

### Changed

Expand Down
2 changes: 2 additions & 0 deletions adbc/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions adbc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ serde_json = "1"
tokio = { version = "1", features = ["rt-multi-thread"] }

[dev-dependencies]
arrow-ipc = "59"
base64 = "0.22"
adbc_driver_manager = "0.24"
arrow-cast = "59"
wiremock = "0.6"
Expand Down
12 changes: 12 additions & 0 deletions adbc/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,18 @@ optional C interface and native Rust asynchronous submission and polling.
Transactions, partitioned execution, statistics, and progress reporting are
not currently implemented.

## Volume file operations

Set the statement option `adbc.databricks.statement.staging_allowed_local_paths`
to a JSON array of local directories to run the file transfer for a Volume
`PUT`, `GET` or `REMOVE` before results are returned; the instruction row stays
readable. Local paths, with symlinks resolved, must be inside one of those
directories, and `[]` allows only `REMOVE`. The option stays set until it is set
to JSON `null`. Without it, `execute` returns the server's instruction row and
moves no file, and `execute_update` fails with `InvalidState`. `REMOVE` of a
missing object succeeds. `PUT` from an input stream is not supported.
`SocketTimeout` also limits how long a transfer may go without progress.

## Compatibility and status

The current implementation targets Rust 1.89+, Rust edition 2021, ADBC 1.1,
Expand Down
217 changes: 216 additions & 1 deletion adbc/src/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ use crate::runtime::{RuntimeExt as _, RuntimeHandle};

const PARAMETER_STYLE_OPTION: &str = "adbc.databricks.statement.parameter_style";
const QUERY_TAGS_OPTION: &str = "adbc.databricks.statement.query_tags";
const STAGING_ALLOWED_PATHS_OPTION: &str = "adbc.databricks.statement.staging_allowed_local_paths";
const CLIENT_TIMEOUT_OPTION: &str = "adbc.databricks.statement.client_timeout_ms";
const QUERY_TIMEOUT_OPTION: &str = "adbc.apache.statement.query_timeout_s";
const ENABLE_DIRECT_RESULTS_OPTION: &str = "adbc.databricks.enable_direct_results";
Expand Down Expand Up @@ -540,6 +541,19 @@ impl Statement {
.row_limit(Some(expect_nonnegative_int(value, key)?));
Ok(())
}
STAGING_ALLOWED_PATHS_OPTION => {
let roots: Option<Vec<std::path::PathBuf>> =
serde_json::from_str(&expect_string(value, key)?).map_err(|_| {
adbc_error(
format!("{key} expects a JSON array of strings or null"),
Status::InvalidArguments,
)
})?;
self.inner()?
.spec()
.volume(roots.map(|roots| kernel::VolumeOptions::new(roots, true)));
Ok(())
}
ROWS_FETCHED_PER_BLOCK_OPTION | "adbc.databricks.rows_fetched_per_block" => {
let rows = expect_nonnegative_int(value, key)?;
if rows == 0 {
Expand Down Expand Up @@ -632,6 +646,15 @@ impl Statement {
.get("query_tags")
.cloned()
.ok_or_else(|| adbc_error("query tags are not set", Status::NotFound)),
STAGING_ALLOWED_PATHS_OPTION => self
.inner()?
.spec_ref()
.volume
.as_ref()
.map(|options| {
serde_json::to_string(&options.allowed_paths).expect("paths serialize")
})
.ok_or_else(|| option_not_found("statement string", key)),
_ if key.starts_with(STATEMENT_CONF_PREFIX) => self
.inner()?
.spec_ref()
Expand Down Expand Up @@ -848,21 +871,26 @@ impl adbc_core::Statement for Statement {
fn execute_update(&mut self) -> Result<Option<i64>> {
self.invalidate_results();
let _connection_operation = self.register_connection_operation()?;
let staging = self.inner()?.spec_ref().volume.is_some();
let Some(binding) = self.binding.take() else {
if !self.enable_direct_results {
let (executed, stream) = self.execute_async_inner()?;
let marked = stream.is_volume_operation();
let count = executed.num_modified_rows();
drop(stream);
self.runtime
.block_on_safe(executed.close())
.map_err(map_kernel_error)?;
require_staging_option(marked, staging)?;
return Ok(count);
}
let executed = self.execute_inner()?;
let marked = executed.result_stream().is_volume_operation();
let count = executed.num_modified_rows();
self.runtime
.block_on_safe(executed.close())
.map_err(map_kernel_error)?;
require_staging_option(marked, staging)?;
return Ok(count);
};

Expand All @@ -888,7 +916,11 @@ impl adbc_core::Statement for Statement {
&row,
self.parameter_style,
self.client_timeout,
) {
)
.and_then(|executed| {
Comment thread
aakash-saravanan-db marked this conversation as resolved.
Resolved
Comment thread
aakash-saravanan-db marked this conversation as resolved.
Resolved
Comment thread
aakash-saravanan-db marked this conversation as resolved.
Resolved
require_staging_option(executed.result_stream().is_volume_operation(), staging)?;
Comment thread
aakash-saravanan-db marked this conversation as resolved.
Resolved
Ok(executed)
}) {
Ok(executed) => executed,
Err(mut error) => {
row_index += 1;
Expand Down Expand Up @@ -1116,6 +1148,18 @@ fn is_valid_named_parameter(name: &str) -> bool {
&& bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
}

/// `execute_update` returns no rows, so a Volume statement executed without the
/// staging option, which therefore moved no file, would otherwise read as success.
fn require_staging_option(marked: bool, staging: bool) -> Result<()> {
if marked && !staging {
return Err(adbc_error(
format!("execute_update on a Volume PUT, GET or REMOVE requires {STAGING_ALLOWED_PATHS_OPTION}"),
Status::InvalidState,
));
}
Ok(())
}

pub(crate) fn execute_bound_row(
inner: &Arc<Mutex<kernel::Statement>>,
runtime: &Arc<RuntimeHandle>,
Expand Down Expand Up @@ -1684,4 +1728,175 @@ mod tests {
assert!(!is_describable_query("INSERT INTO t VALUES (1)"));
assert!(!is_describable_query("DESCRIBE TABLE t"));
}

#[test]
fn staging_option_runs_volume_transfers_and_execute_update_requires_it() {
use adbc_core::options::OptionDatabase;
use adbc_core::{
Connection as _, Database as _, Driver as _, Optionable as _, Statement as _,
};
use base64::Engine as _;
use wiremock::matchers::{body_string_contains, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

let runtime = RuntimeHandle::create().unwrap();
let server = runtime.block_on_safe(MockServer::start());
let response = |operation: &str, route: &str, local_file: &str| {
let values = [
operation.to_owned(),
format!("{}/{route}", server.uri()),
"{}".into(),
local_file.to_owned(),
];
let names = ["operation", "presignedUrl", "headers", "localFile"];
let batch =
RecordBatch::try_from_iter(names.into_iter().zip(values).map(|(name, value)| {
(
name,
Arc::new(StringArray::from(vec![value])) as arrow_array::ArrayRef,
)
}))
.unwrap();
let mut ipc = Vec::new();
let mut writer =
arrow_ipc::writer::StreamWriter::try_new(&mut ipc, &batch.schema()).unwrap();
writer.write(&batch).unwrap();
writer.finish().unwrap();
drop(writer);
let columns: Vec<_> = names
.iter()
.enumerate()
.map(|(position, name)| serde_json::json!({"name": name, "type_name": "STRING", "type_text": "STRING", "position": position}))
.collect();
serde_json::json!({
"statement_id": "stmt-volume",
"status": {"state": "SUCCEEDED"},
"manifest": {"is_volume_operation": true, "format": "ARROW_STREAM", "schema": {"column_count": 4, "columns": columns}, "total_chunk_count": 1, "total_row_count": 1},
"result": {"chunk_index": 0, "row_offset": 0, "row_count": 1, "attachment": base64::engine::general_purpose::STANDARD.encode(&ipc)},
})
.to_string()
};
let remove = response("REMOVE", "object", "");
let slow_remove = response("REMOVE", "slow", "");
runtime.block_on_safe(async {
Mock::given(method("POST"))
.and(path("/api/2.0/sql/statements"))
.and(body_string_contains("files/slow"))
.respond_with(ResponseTemplate::new(200).set_body_string(slow_remove))
.mount(&server)
.await;
for (verb, route, body) in [
(
"POST",
"/api/2.0/sql/warehouses/test_wh/sessions",
r#"{"session_id":"sess-test"}"#.to_owned(),
),
("POST", "/api/2.0/sql/statements", remove.clone()),
(
"POST",
"/api/2.0/sql/statements/stmt-volume/cancel",
"{}".into(),
),
("GET", "/api/2.0/sql/statements/stmt-volume", remove),
] {
Mock::given(method(verb))
.and(path(route))
.respond_with(ResponseTemplate::new(200).set_body_string(body))
.mount(&server)
.await;
}
Mock::given(method("DELETE"))
.and(path("/object"))
.respond_with(ResponseTemplate::new(204))
.expect(1)
.mount(&server)
.await;
Mock::given(method("DELETE"))
.and(path("/slow"))
.respond_with(ResponseTemplate::new(204).set_delay(Duration::from_secs(30)))
.mount(&server)
.await;
Mock::given(method("DELETE"))
.respond_with(ResponseTemplate::new(200).set_body_string("{}"))
.mount(&server)
.await;
});
let database = crate::Driver
.new_database_with_opts([
(OptionDatabase::Uri, server.uri().into()),
(
OptionDatabase::Other(crate::config::HTTP_PATH.into()),
"/sql/1.0/warehouses/test_wh".into(),
),
(
OptionDatabase::Other(crate::config::ACCESS_TOKEN.into()),
"secret".into(),
),
])
.unwrap();
let mut connection = database.new_connection().unwrap();
// The option reads back as set, clears with JSON null and rejects other JSON.
let mut options = connection.new_statement().unwrap();
let key = || OptionStatement::Other(STAGING_ALLOWED_PATHS_OPTION.into());
options
.set_option(key(), r#"["/tmp/files"]"#.into())
.unwrap();
assert_eq!(
options.get_option_string(key()).unwrap(),
r#"["/tmp/files"]"#
);
options.set_option(key(), "null".into()).unwrap();
assert_eq!(
options.get_option_string(key()).unwrap_err().status,
Status::NotFound
);
let error = options.set_option(key(), "{}".into()).unwrap_err();
assert_eq!(error.status, Status::InvalidArguments);
drop(options);
let mut statement = |sql: &str, staging: bool| {
let mut statement = connection.new_statement().unwrap();
statement.set_sql_query(sql).unwrap();
if staging {
statement
.set_option(
OptionStatement::Other(STAGING_ALLOWED_PATHS_OPTION.into()),
"[]".into(),
)
.unwrap();
}
statement
};
let remove = "REMOVE '/Volumes/main/default/files/file'";
// With the option, execute_update runs the transfer.
statement(remove, true).execute_update().unwrap();
// Without it, execute returns the instruction row and moves no file, and
// execute_update, which returns no rows, refuses the statement.
let mut reader = statement(remove, false).execute().unwrap();
assert_eq!(reader.next().unwrap().unwrap().num_rows(), 1);
let error = statement(remove, false).execute_update().unwrap_err();
assert_eq!(error.status, Status::InvalidState);

// The cancellation handle stops a running transfer.
let mut slow = statement("REMOVE '/Volumes/main/default/files/slow'", true);
let cancellation = slow.cancellation_handle();
let started = std::time::Instant::now();
std::thread::scope(|scope| {
scope.spawn(|| {
while !runtime
.block_on_safe(server.received_requests())
.unwrap()
.iter()
.any(|request| request.url.path() == "/slow")
{
assert!(started.elapsed() < Duration::from_secs(10));
std::thread::sleep(Duration::from_millis(10));
}
cancellation.cancel().unwrap();
});
let error = slow.execute_update().unwrap_err();
assert_eq!(error.status, Status::Cancelled);
});
assert!(started.elapsed() < Duration::from_secs(10));
runtime.block_on_safe(server.verify());
}
}
Loading
Loading