risingwave_connector/source/adbc_snowflake/
mod.rs1use std::collections::HashMap;
16
17use adbc_core::options::{OptionDatabase, OptionValue};
18use adbc_core::{
19 Connection as AdbcCoreConnection, Database as AdbcCoreDatabase, Statement as AdbcCoreStatement,
20};
21use adbc_snowflake::database::Builder as DatabaseBuilder;
22pub use adbc_snowflake::{Connection, Database, Driver, Statement};
23use anyhow::{Context, anyhow};
24use async_trait::async_trait;
25use futures::StreamExt;
26use futures_async_stream::try_stream;
27use risingwave_common::array::StreamChunk;
28use risingwave_common::array::arrow::{arrow_array_58 as arrow, from_arrow58_record_batch};
29use risingwave_common::types::JsonbVal;
30use serde::{Deserialize, Serialize};
31
32use crate::error::ConnectorResult;
33use crate::parser::ParserConfig;
34use crate::source::{
35 BoxSourceChunkStream, Column, SourceContextRef, SourceEnumeratorContextRef, SourceProperties,
36 SplitEnumerator, SplitId, SplitMetaData, SplitReader, UnknownFields,
37};
38
39pub const ADBC_SNOWFLAKE_CONNECTOR: &str = "adbc_snowflake";
40
41mod schema;
42
43#[derive(Clone, Debug, Deserialize, with_options::WithOptions)]
45pub struct AdbcSnowflakeProperties {
46 #[serde(rename = "adbc_snowflake.account")]
48 pub account: String,
49
50 #[serde(rename = "adbc_snowflake.username")]
52 pub username: String,
53
54 #[serde(rename = "adbc_snowflake.password")]
56 pub password: Option<String>,
57
58 #[serde(rename = "adbc_snowflake.database")]
60 pub database: String,
61
62 #[serde(rename = "adbc_snowflake.schema")]
64 pub schema: String,
65
66 #[serde(rename = "adbc_snowflake.warehouse")]
68 pub warehouse: String,
69
70 #[serde(rename = "adbc_snowflake.table")]
72 pub table: String,
73
74 #[serde(rename = "adbc_snowflake.role")]
76 pub role: Option<String>,
77
78 #[serde(rename = "adbc_snowflake.host")]
80 pub host: Option<String>,
81
82 #[serde(rename = "adbc_snowflake.port")]
84 pub port: Option<u16>,
85
86 #[serde(rename = "adbc_snowflake.protocol")]
88 pub protocol: Option<String>,
89
90 #[serde(rename = "adbc_snowflake.auth_type")]
93 pub auth_type: Option<String>,
94
95 #[serde(rename = "adbc_snowflake.auth_token")]
97 pub auth_token: Option<String>,
98
99 #[serde(rename = "adbc_snowflake.jwt_private_key_path")]
101 pub jwt_private_key_path: Option<String>,
102
103 #[serde(rename = "adbc_snowflake.jwt_private_key_pkcs8_value")]
104 pub jwt_private_key_pkcs8_value: Option<String>,
105
106 #[serde(rename = "adbc_snowflake.jwt_private_key_pkcs8_password")]
107 pub jwt_private_key_pkcs8_password: Option<String>,
108
109 #[serde(flatten)]
111 pub unknown_fields: HashMap<String, String>,
112}
113
114impl crate::enforce_secret::EnforceSecret for AdbcSnowflakeProperties {
115 const ENFORCE_SECRET_PROPERTIES: phf::Set<&'static str> = phf::phf_set! {
116 "adbc_snowflake.password",
117 "adbc_snowflake.auth_token",
118 "adbc_snowflake.jwt_private_key_path",
119 "adbc_snowflake.jwt_private_key_pkcs8_value",
120 "adbc_snowflake.jwt_private_key_pkcs8_password"
121 };
122}
123
124impl UnknownFields for AdbcSnowflakeProperties {
125 fn unknown_fields(&self) -> HashMap<String, String> {
126 self.unknown_fields.clone()
127 }
128}
129
130impl SourceProperties for AdbcSnowflakeProperties {
131 type Split = AdbcSnowflakeSplit;
132 type SplitEnumerator = AdbcSnowflakeSplitEnumerator;
133 type SplitReader = AdbcSnowflakeSplitReader;
134
135 const SOURCE_NAME: &'static str = ADBC_SNOWFLAKE_CONNECTOR;
136}
137
138impl AdbcSnowflakeProperties {
139 pub fn table_ref(&self) -> String {
141 format!(r#""{}"."{}"."{}""#, self.database, self.schema, self.table)
142 }
143
144 pub fn build_select_all_query(&self) -> String {
146 format!("SELECT * FROM {}", self.table_ref())
147 }
148
149 fn build_database_builder(&self) -> ConnectorResult<DatabaseBuilder> {
151 let mut builder = DatabaseBuilder::default()
152 .with_account(&self.account)
153 .with_username(&self.username)
154 .with_database(&self.database)
155 .with_schema(&self.schema)
156 .with_warehouse(&self.warehouse);
157
158 if let Some(ref password) = self.password {
159 builder = builder.with_password(password);
160 }
161
162 builder.other.push((
164 OptionDatabase::Other(
165 "adbc.snowflake.sql.client_option.max_timestamp_precision".to_owned(),
166 ),
167 OptionValue::String("microseconds".to_owned()),
168 ));
169
170 if let Some(ref role) = self.role {
171 builder = builder.with_role(role);
172 }
173
174 if let Some(ref host) = self.host {
175 builder = builder
176 .with_parse_host(host)
177 .context("Failed to parse host")?;
178 }
179
180 if let Some(port) = self.port {
181 builder = builder.with_port(port);
182 }
183
184 if let Some(ref protocol) = self.protocol {
185 builder = builder
186 .with_parse_protocol(protocol)
187 .context("Failed to parse protocol")?;
188 }
189
190 if let Some(ref auth_type) = self.auth_type {
191 builder = builder
192 .with_parse_auth_type(auth_type)
193 .context("Failed to parse auth type")?;
194 }
195
196 if let Some(ref auth_token) = self.auth_token {
197 builder = builder.with_auth_token(auth_token);
198 }
199
200 if let Some(ref jwt_private_key_path) = self.jwt_private_key_path {
201 builder = builder.with_jwt_private_key(jwt_private_key_path.into());
202 }
203
204 if let Some(ref jwt_private_key_pkcs8_value) = self.jwt_private_key_pkcs8_value {
205 builder = builder.with_jwt_private_key_pkcs8_value(jwt_private_key_pkcs8_value.into());
206 }
207
208 if let Some(ref jwt_private_key_pkcs8_password) = self.jwt_private_key_pkcs8_password {
209 builder =
210 builder.with_jwt_private_key_pkcs8_password(jwt_private_key_pkcs8_password.into());
211 }
212
213 Ok(builder)
214 }
215
216 pub fn create_database(&self) -> ConnectorResult<Database> {
219 let mut driver = Driver::try_load().context(
221 "Failed to load ADBC Snowflake driver shared library. \
222 Check the following:\n\
223 1. The ADBC Snowflake driver is installed correctly\n\
224 2. The shared library (libadbc_driver_snowflake.so on Linux, \
225 libadbc_driver_snowflake.dylib on macOS, or \
226 adbc_driver_snowflake.dll on Windows) is in your library path\n\
227 3. Environment variables like LD_LIBRARY_PATH (Linux), \
228 DYLD_LIBRARY_PATH (macOS), or PATH (Windows) are set correctly\n\
229 4. All required dependencies of the ADBC Snowflake driver are installed",
230 )?;
231
232 let builder = self.build_database_builder()?;
233 let database = builder
234 .build(&mut driver)
235 .context("Failed to build database")?;
236 Ok(database)
237 }
238
239 pub fn create_connection(&self, database: &Database) -> ConnectorResult<Connection> {
241 let connection = database
242 .new_connection()
243 .context("Failed to create connection")?;
244 Ok(connection)
245 }
246
247 pub fn create_statement(
249 &self,
250 connection: &mut Connection,
251 query: &str,
252 ) -> ConnectorResult<Statement> {
253 let mut statement = connection
254 .new_statement()
255 .context("Failed to create statement")?;
256 statement
257 .set_sql_query(query)
258 .context("Failed to set SQL query")?;
259 Ok(statement)
260 }
261
262 pub fn execute_query_with_connection(
265 &self,
266 connection: &mut Connection,
267 query: &str,
268 ) -> ConnectorResult<Vec<arrow::RecordBatch>> {
269 let mut statement = connection
270 .new_statement()
271 .context("Failed to create statement")?;
272 statement
273 .set_sql_query(query)
274 .context("Failed to set SQL query")?;
275 let reader = statement.execute().context("Failed to execute query")?;
276
277 let mut batches = Vec::new();
279 for batch_result in reader {
280 let batch = batch_result.context("Failed to read record batch")?;
281 batches.push(batch);
282 }
283 Ok(batches)
284 }
285
286 pub fn execute_query(&self, query: &str) -> ConnectorResult<Vec<arrow::RecordBatch>> {
290 let database = self.create_database()?;
291 let mut connection = self.create_connection(&database)?;
292 self.execute_query_with_connection(&mut connection, query)
293 }
294}
295
296#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Hash)]
299pub struct AdbcSnowflakeSplit {
300 pub split_id: String,
302 pub query: String,
304}
305
306impl SplitMetaData for AdbcSnowflakeSplit {
307 fn id(&self) -> SplitId {
308 self.split_id.clone().into()
309 }
310
311 fn restore_from_json(value: JsonbVal) -> ConnectorResult<Self> {
312 serde_json::from_value(value.take()).map_err(|e| anyhow!(e).into())
313 }
314
315 fn encode_to_json(&self) -> JsonbVal {
316 serde_json::to_value(self.clone()).unwrap().into()
317 }
318
319 fn update_offset(&mut self, _last_seen_offset: String) -> ConnectorResult<()> {
320 Ok(())
322 }
323}
324
325pub struct AdbcSnowflakeSplitEnumerator {
327 properties: AdbcSnowflakeProperties,
328}
329
330#[async_trait]
331impl SplitEnumerator for AdbcSnowflakeSplitEnumerator {
332 type Properties = AdbcSnowflakeProperties;
333 type Split = AdbcSnowflakeSplit;
334
335 async fn new(
336 properties: Self::Properties,
337 _context: SourceEnumeratorContextRef,
338 ) -> ConnectorResult<Self> {
339 Ok(Self { properties })
340 }
341
342 async fn list_splits(&mut self) -> ConnectorResult<Vec<Self::Split>> {
343 let database = self.properties.create_database()?;
346 let mut connection = self.properties.create_connection(&database)?;
347
348 let validation_query = format!(
350 "SELECT * FROM {}.information_schema.tables WHERE table_schema = '{}' LIMIT 1",
351 self.properties.database, self.properties.schema
352 );
353 let mut statement = connection
354 .new_statement()
355 .context("Failed to create statement")?;
356 statement
357 .set_sql_query(&validation_query)
358 .context("Failed to set SQL query")?;
359 let _ = statement
360 .execute()
361 .context("Failed to validate connection")?;
362
363 let split = AdbcSnowflakeSplit {
365 split_id: "0".to_owned(),
366 query: self.properties.build_select_all_query(),
367 };
368 Ok(vec![split])
369 }
370}
371
372pub struct AdbcSnowflakeSplitReader {
374 properties: AdbcSnowflakeProperties,
375 #[expect(dead_code)]
376 splits: Vec<AdbcSnowflakeSplit>,
377 #[expect(dead_code)]
378 parser_config: ParserConfig,
379 #[expect(dead_code)]
380 source_ctx: SourceContextRef,
381}
382
383#[async_trait]
384impl SplitReader for AdbcSnowflakeSplitReader {
385 type Properties = AdbcSnowflakeProperties;
386 type Split = AdbcSnowflakeSplit;
387
388 async fn new(
389 properties: Self::Properties,
390 splits: Vec<Self::Split>,
391 parser_config: ParserConfig,
392 source_ctx: SourceContextRef,
393 _columns: Option<Vec<Column>>,
394 ) -> ConnectorResult<Self> {
395 Ok(Self {
396 properties,
397 splits,
398 parser_config,
399 source_ctx,
400 })
401 }
402
403 fn into_stream(self) -> BoxSourceChunkStream {
404 self.into_chunk_stream().boxed()
405 }
406}
407
408impl AdbcSnowflakeSplitReader {
409 #[try_stream(boxed, ok = StreamChunk, error = crate::error::ConnectorError)]
410 async fn into_chunk_stream(self) {
411 let database = self.properties.create_database()?;
413 let mut connection = self.properties.create_connection(&database)?;
414 let query = self.properties.build_select_all_query();
415 let mut statement = self.properties.create_statement(&mut connection, &query)?;
416
417 let reader = statement.execute().context("Failed to execute query")?;
419
420 for batch_result in reader {
422 let batch = batch_result.context("Failed to read record batch")?;
423
424 let data_chunk = from_arrow58_record_batch(&batch)?;
426
427 let stream_chunk = StreamChunk::from_parts(
429 vec![risingwave_common::array::Op::Insert; data_chunk.capacity()],
430 data_chunk,
431 );
432
433 yield stream_chunk;
434 }
435 }
436}