-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlib.rs
More file actions
121 lines (98 loc) · 3.91 KB
/
lib.rs
File metadata and controls
121 lines (98 loc) · 3.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/*
Copyright 2026 The Spice.ai OSS Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pub mod databricks;
pub mod spiceai;
use std::collections::HashMap;
use adbc_core::options::{AdbcVersion, OptionDatabase, OptionValue};
use adbc_core::{Connection, Database, Driver, LOAD_FLAG_DEFAULT, Statement};
use adbc_driver_manager::ManagedDriver;
use arrow_array::RecordBatch;
use snafu::prelude::*;
#[derive(Debug, Snafu)]
pub enum Error {
#[snafu(display("Failed to load ADBC driver: {reason}"))]
LoadDriver { reason: String },
#[snafu(display("Failed to create database handle: {reason}"))]
CreateDatabase { reason: String },
#[snafu(display("Failed to create connection: {reason}"))]
CreateConnection { reason: String },
#[snafu(display("Failed to execute query: {reason}"))]
ExecuteQuery { reason: String },
#[snafu(display("Failed to read result batch: {source}"))]
ReadBatch { source: arrow::error::ArrowError },
}
pub type Result<T, E = Error> = std::result::Result<T, E>;
/// A generic ADBC connection wrapping [`adbc_driver_manager::ManagedConnection`].
///
/// Use a connector-specific builder (e.g. [`databricks::connect`]) to obtain an instance.
pub struct AdbcConnection {
conn: adbc_driver_manager::ManagedConnection,
}
impl AdbcConnection {
/// Create an `AdbcConnection` from an already-established [`ManagedConnection`].
#[must_use]
pub fn new(conn: adbc_driver_manager::ManagedConnection) -> Self {
Self { conn }
}
/// Create an `AdbcConnection` from a driver name and a map of key-value options.
///
/// Each key in `kwargs` is converted to an [`OptionDatabase`] variant
/// (matching canonical keys like `"uri"`, `"username"`, `"password"`,
/// or falling back to [`OptionDatabase::Other`]).
pub fn create(driver_name: &str, kwargs: HashMap<String, serde_json::Value>) -> Result<Self> {
let mut driver = ManagedDriver::load_from_name(
driver_name,
None,
AdbcVersion::default(),
LOAD_FLAG_DEFAULT,
None,
)
.map_err(|e| Error::LoadDriver {
reason: e.to_string(),
})?;
let opts: Vec<(OptionDatabase, OptionValue)> = kwargs
.into_iter()
.map(|(k, v)| {
let val = match v {
serde_json::Value::String(s) => s,
other => other.to_string(),
};
(OptionDatabase::from(k.as_str()), OptionValue::from(val))
})
.collect();
let db = driver
.new_database_with_opts(opts)
.map_err(|e| Error::CreateDatabase {
reason: e.to_string(),
})?;
let conn = db.new_connection().map_err(|e| Error::CreateConnection {
reason: e.to_string(),
})?;
Ok(Self::new(conn))
}
/// Execute a SQL query and collect all result batches.
pub fn query(&mut self, sql: &str) -> Result<Vec<RecordBatch>> {
let mut stmt = self.conn.new_statement().map_err(|e| Error::ExecuteQuery {
reason: e.to_string(),
})?;
stmt.set_sql_query(sql).map_err(|e| Error::ExecuteQuery {
reason: e.to_string(),
})?;
let reader = stmt.execute().map_err(|e| Error::ExecuteQuery {
reason: e.to_string(),
})?;
reader
.collect::<std::result::Result<Vec<_>, _>>()
.context(ReadBatchSnafu)
}
}