Skip to main content

risingwave_connector/source/adbc_snowflake/
mod.rs

1// Copyright 2025 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use 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/// Properties for ADBC Snowflake source connector.
44#[derive(Clone, Debug, Deserialize, with_options::WithOptions)]
45pub struct AdbcSnowflakeProperties {
46    /// The Snowflake account identifier (e.g., "myaccount" or "myaccount.us-east-1").
47    #[serde(rename = "adbc_snowflake.account")]
48    pub account: String,
49
50    /// The username for authentication.
51    #[serde(rename = "adbc_snowflake.username")]
52    pub username: String,
53
54    /// The password for authentication.
55    #[serde(rename = "adbc_snowflake.password")]
56    pub password: Option<String>,
57
58    /// The name of the database to use.
59    #[serde(rename = "adbc_snowflake.database")]
60    pub database: String,
61
62    /// The name of the schema to use.
63    #[serde(rename = "adbc_snowflake.schema")]
64    pub schema: String,
65
66    /// The name of the warehouse to use.
67    #[serde(rename = "adbc_snowflake.warehouse")]
68    pub warehouse: String,
69
70    /// The table name to load (full table).
71    #[serde(rename = "adbc_snowflake.table")]
72    pub table: String,
73
74    /// The role to use (optional).
75    #[serde(rename = "adbc_snowflake.role")]
76    pub role: Option<String>,
77
78    /// The host to connect to (optional, defaults to Snowflake cloud).
79    #[serde(rename = "adbc_snowflake.host")]
80    pub host: Option<String>,
81
82    /// The port to connect to (optional).
83    #[serde(rename = "adbc_snowflake.port")]
84    pub port: Option<u16>,
85
86    /// The protocol to use (optional, defaults to "https").
87    #[serde(rename = "adbc_snowflake.protocol")]
88    pub protocol: Option<String>,
89
90    /// The authentication type (optional, defaults to "`auth_snowflake`").
91    /// Possible values: `auth_snowflake`, `auth_oauth`, `auth_ext_browser`, `auth_okta`, `auth_jwt`, `auth_mfa`, `auth_pat`, `auth_wif`
92    #[serde(rename = "adbc_snowflake.auth_type")]
93    pub auth_type: Option<String>,
94
95    /// `OAuth` token for authentication (when using `auth_oauth`).
96    #[serde(rename = "adbc_snowflake.auth_token")]
97    pub auth_token: Option<String>,
98
99    /// JWT private key file path (when using `auth_jwt`).
100    #[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    /// Unknown fields for forward compatibility.
110    #[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    /// Qualified table reference used in all generated queries.
140    pub fn table_ref(&self) -> String {
141        format!(r#""{}"."{}"."{}""#, self.database, self.schema, self.table)
142    }
143
144    /// Default full-table select.
145    pub fn build_select_all_query(&self) -> String {
146        format!("SELECT * FROM {}", self.table_ref())
147    }
148
149    /// Build a database builder from properties.
150    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        // Set the max timestamp precision to microseconds, as RisingWave supports at most microsecond precision.
163        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    /// Create an ADBC Snowflake database connection.
217    /// This validates that the driver library is available before attempting connection.
218    pub fn create_database(&self) -> ConnectorResult<Database> {
219        // Validate driver availability and load the driver
220        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    /// Create a connection from the database.
240    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    /// Create a statement from the connection and set the SQL query.
248    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    /// Execute a custom query using a provided connection.
263    /// This is useful for metadata queries needed for split generation while reusing connections.
264    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        // Collect all batches into a vector
278        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    /// Execute a custom query and return the results as a vector of Arrow record batches.
287    /// This is useful for metadata queries needed for split generation.
288    /// Creates a new connection for each query - use `execute_query_with_connection` for better performance.
289    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/// Split for ADBC Snowflake source.
297/// Since Snowflake queries are executed as a whole, we use a single split with the query as the identifier.
298#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Hash)]
299pub struct AdbcSnowflakeSplit {
300    /// The split identifier (typically based on the query).
301    pub split_id: String,
302    /// The SQL query to execute.
303    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        // ADBC Snowflake doesn't have offset-based reading for now
321        Ok(())
322    }
323}
324
325/// Split enumerator for ADBC Snowflake source.
326pub 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        // Validate connection and access by establishing a connection and preparing the query.
344        // This ensures credentials are correct and the query is valid before returning the split.
345        let database = self.properties.create_database()?;
346        let mut connection = self.properties.create_connection(&database)?;
347
348        // Validate connection and access by running a simple query against the target database/schema
349        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        // Connection and query are valid, return the split
364        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
372/// Split reader for ADBC Snowflake source.
373pub 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        // Execute the query and read the results as Arrow record batches
412        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        // Execute the query and get a record batch reader
418        let reader = statement.execute().context("Failed to execute query")?;
419
420        // Iterate over the record batches and convert them to StreamChunks
421        for batch_result in reader {
422            let batch = batch_result.context("Failed to read record batch")?;
423
424            // Convert Arrow RecordBatch to RisingWave DataChunk
425            let data_chunk = from_arrow58_record_batch(&batch)?;
426
427            // Convert DataChunk to StreamChunk (all inserts)
428            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}