Skip to content

Commit 4a5ab97

Browse files
cursoragentlovasoa
andcommitted
Refactor: Improve Snowflake integration and examples
Co-authored-by: contact <[email protected]>
1 parent 46bd6f2 commit 4a5ab97

File tree

25 files changed

+150
-130
lines changed

25 files changed

+150
-130
lines changed

examples/snowflake/basic/src/main.rs

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
//! Basic Snowflake connection example
2-
//!
2+
//!
33
//! This example demonstrates the current state of Snowflake support in SQLx.
4-
//!
4+
//!
55
//! Note: This example shows the API structure but requires proper RSA key-pair
66
//! authentication to work with a real Snowflake instance.
77
@@ -15,11 +15,11 @@ async fn main() -> Result<(), sqlx_oldapi::Error> {
1515

1616
// Create connection options
1717
let options = SnowflakeConnectOptions::new()
18-
.account("your-account") // Replace with your Snowflake account
19-
.username("your-username") // Replace with your username
20-
.warehouse("your-warehouse") // Replace with your warehouse
21-
.database("your-database") // Replace with your database
22-
.schema("your-schema"); // Replace with your schema
18+
.account("your-account") // Replace with your Snowflake account
19+
.username("your-username") // Replace with your username
20+
.warehouse("your-warehouse") // Replace with your warehouse
21+
.database("your-database") // Replace with your database
22+
.schema("your-schema"); // Replace with your schema
2323

2424
println!("📋 Configuration:");
2525
println!(" Account: {}", options.get_account());
@@ -36,7 +36,10 @@ async fn main() -> Result<(), sqlx_oldapi::Error> {
3636
// Execute a simple query
3737
println!("\n📊 Executing query...");
3838
let result = connection.execute("SELECT CURRENT_VERSION()").await?;
39-
println!("✅ Query executed! Rows affected: {}", result.rows_affected());
39+
println!(
40+
"✅ Query executed! Rows affected: {}",
41+
result.rows_affected()
42+
);
4043

4144
// Test connection ping
4245
println!("\n🏓 Testing connection ping...");
@@ -49,6 +52,6 @@ async fn main() -> Result<(), sqlx_oldapi::Error> {
4952
println!("✅ Connection closed!");
5053

5154
println!("\n🎉 Example completed successfully!");
52-
55+
5356
Ok(())
54-
}
57+
}

examples/snowflake_basic.rs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,15 +37,18 @@ async fn main() -> Result<(), sqlx_oldapi::Error> {
3737
println!(" Rows affected: {}", result.rows_affected());
3838
}
3939
Err(e) => {
40-
println!("⚠️ Query execution error (expected - auth not fully implemented): {}", e);
40+
println!(
41+
"⚠️ Query execution error (expected - auth not fully implemented): {}",
42+
e
43+
);
4144
}
4245
}
4346

4447
println!("\n🔒 Current Authentication Status:");
4548
println!(" ✅ JWT token generation (with dummy key)");
4649
println!(" ❌ RSA private key authentication (TODO)");
4750
println!(" ❌ OAuth authentication (TODO)");
48-
51+
4952
println!("\n📡 API Integration Status:");
5053
println!(" ✅ HTTP client setup");
5154
println!(" ✅ Request formatting");
@@ -70,4 +73,4 @@ async fn main() -> Result<(), sqlx_oldapi::Error> {
7073
println!(" 8. Create integration tests");
7174

7275
Ok(())
73-
}
76+
}

sqlx-core/src/snowflake/arguments.rs

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
use crate::arguments::Arguments;
22
use crate::encode::{Encode, IsNull};
3-
use crate::snowflake::{Snowflake, SnowflakeTypeInfo};
3+
use crate::snowflake::Snowflake;
44
use crate::types::Type;
5-
use std::borrow::Cow;
65

76
/// Implementation of [`Arguments`] for Snowflake.
87
#[derive(Debug, Default, Clone)]
@@ -12,7 +11,7 @@ pub struct SnowflakeArguments {
1211
}
1312

1413
/// Implementation of [`ArgumentBuffer`] for Snowflake.
15-
#[derive(Debug)]
14+
#[derive(Debug, Default)]
1615
pub struct SnowflakeArgumentBuffer {
1716
pub(crate) buffer: Vec<u8>,
1817
}
@@ -28,6 +27,10 @@ impl SnowflakeArguments {
2827
self.bindings.len()
2928
}
3029

30+
pub fn is_empty(&self) -> bool {
31+
self.bindings.is_empty()
32+
}
33+
3134
pub(crate) fn get(&self, index: usize) -> Option<&String> {
3235
self.bindings.get(index)
3336
}
@@ -60,16 +63,8 @@ impl<'q> Arguments<'q> for SnowflakeArguments {
6063
}
6164
}
6265

63-
impl Default for SnowflakeArgumentBuffer {
64-
fn default() -> Self {
65-
Self {
66-
buffer: Vec::new(),
67-
}
68-
}
69-
}
70-
7166
impl SnowflakeArgumentBuffer {
7267
pub fn new() -> Self {
7368
Self::default()
7469
}
75-
}
70+
}

sqlx-core/src/snowflake/column.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
1-
use crate::column::{Column, ColumnIndex};
2-
use crate::error::Error;
1+
use crate::column::Column;
32
use crate::snowflake::{Snowflake, SnowflakeTypeInfo};
4-
use std::borrow::Cow;
53

64
/// Implementation of [`Column`] for Snowflake.
75
#[derive(Debug, Clone)]

sqlx-core/src/snowflake/connection.rs

Lines changed: 40 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,7 @@ use crate::connection::Connection;
33
use crate::describe::Describe;
44
use crate::error::Error;
55
use crate::executor::{Execute, Executor};
6-
use crate::snowflake::{
7-
Snowflake, SnowflakeArguments, SnowflakeConnectOptions, SnowflakeQueryResult, SnowflakeRow,
8-
SnowflakeStatement, SnowflakeTransactionManager, SnowflakeTypeInfo,
9-
};
6+
use crate::snowflake::{Snowflake, SnowflakeConnectOptions, SnowflakeQueryResult, SnowflakeStatement};
107
use crate::transaction::Transaction;
118
use either::Either;
129
use futures_core::future::BoxFuture;
@@ -42,7 +39,11 @@ impl Debug for SnowflakeConnection {
4239
impl SnowflakeConnection {
4340
pub(crate) async fn establish(options: &SnowflakeConnectOptions) -> Result<Self, Error> {
4441
let client = reqwest::Client::builder()
45-
.timeout(options.timeout.unwrap_or(std::time::Duration::from_secs(30)))
42+
.timeout(
43+
options
44+
.timeout
45+
.unwrap_or(std::time::Duration::from_secs(30)),
46+
)
4647
.user_agent("SQLx-Snowflake/0.6.48")
4748
.build()
4849
.map_err(|e| Error::Configuration(e.into()))?;
@@ -70,7 +71,7 @@ impl SnowflakeConnection {
7071
async fn authenticate(&mut self) -> Result<(), Error> {
7172
// For now, implement username/password authentication
7273
// TODO: Implement JWT authentication with private key
73-
74+
7475
if self.options.username.is_empty() {
7576
return Err(Error::Configuration(
7677
"Username is required for Snowflake authentication".into(),
@@ -81,7 +82,7 @@ impl SnowflakeConnection {
8182
// In a real implementation, this would use RSA private keys
8283
let token = self.generate_jwt_token()?;
8384
self.auth_token = Some(token);
84-
85+
8586
Ok(())
8687
}
8788

@@ -123,7 +124,9 @@ impl SnowflakeConnection {
123124
pub(crate) async fn execute(&mut self, query: &str) -> Result<SnowflakeQueryResult, Error> {
124125
use serde_json::json;
125126

126-
let auth_token = self.auth_token.as_ref()
127+
let auth_token = self
128+
.auth_token
129+
.as_ref()
127130
.ok_or_else(|| Error::Configuration("Not authenticated".into()))?;
128131

129132
let request_body = json!({
@@ -135,29 +138,36 @@ impl SnowflakeConnection {
135138
"role": self.options.role
136139
});
137140

138-
let response = self.client
141+
let response = self
142+
.client
139143
.post(&self.base_url)
140144
.header("Authorization", format!("Bearer {}", auth_token))
141145
.header("Content-Type", "application/json")
142146
.header("Accept", "application/json")
143147
.json(&request_body)
144148
.send()
145149
.await
146-
.map_err(|e| Error::Io(std::io::Error::new(std::io::ErrorKind::Other, e)))?;
150+
.map_err(|e| Error::Io(std::io::Error::other(e)))?;
147151

148152
if !response.status().is_success() {
149153
let status = response.status();
150-
let error_text = response.text().await
154+
let error_text = response
155+
.text()
156+
.await
151157
.unwrap_or_else(|_| "Unknown error".to_string());
152-
return Err(Error::Database(Box::new(crate::snowflake::SnowflakeDatabaseError::new(
153-
status.as_u16().to_string(),
154-
format!("HTTP {}: {}", status, error_text),
155-
None,
156-
))));
158+
return Err(Error::Database(Box::new(
159+
crate::snowflake::SnowflakeDatabaseError::new(
160+
status.as_u16().to_string(),
161+
format!("HTTP {}: {}", status, error_text),
162+
None,
163+
),
164+
)));
157165
}
158166

159-
let response_json: serde_json::Value = response.json().await
160-
.map_err(|e| Error::Io(std::io::Error::new(std::io::ErrorKind::Other, e)))?;
167+
let response_json: serde_json::Value = response
168+
.json()
169+
.await
170+
.map_err(|e| Error::Io(std::io::Error::other(e)))?;
161171

162172
// Parse the response to extract row count and other metadata
163173
let rows_affected = response_json
@@ -234,11 +244,14 @@ impl<'c> Executor<'c> for &'c mut SnowflakeConnection {
234244

235245
fn fetch_many<'e, 'q: 'e, E>(
236246
self,
237-
query: E,
247+
_query: E,
238248
) -> BoxStream<
239249
'e,
240250
Result<
241-
Either<<Self::Database as crate::database::Database>::QueryResult, <Self::Database as crate::database::Database>::Row>,
251+
Either<
252+
<Self::Database as crate::database::Database>::QueryResult,
253+
<Self::Database as crate::database::Database>::Row,
254+
>,
242255
Error,
243256
>,
244257
>
@@ -253,7 +266,7 @@ impl<'c> Executor<'c> for &'c mut SnowflakeConnection {
253266

254267
fn fetch_optional<'e, 'q: 'e, E>(
255268
self,
256-
query: E,
269+
_query: E,
257270
) -> BoxFuture<'e, Result<Option<<Self::Database as crate::database::Database>::Row>, Error>>
258271
where
259272
'c: 'e,
@@ -270,7 +283,10 @@ impl<'c> Executor<'c> for &'c mut SnowflakeConnection {
270283
self,
271284
sql: &'q str,
272285
parameters: &'e [<Self::Database as crate::database::Database>::TypeInfo],
273-
) -> BoxFuture<'e, Result<<Self::Database as crate::database::HasStatement<'q>>::Statement, Error>>
286+
) -> BoxFuture<
287+
'e,
288+
Result<<Self::Database as crate::database::HasStatement<'q>>::Statement, Error>,
289+
>
274290
where
275291
'c: 'e,
276292
{
@@ -288,7 +304,7 @@ impl<'c> Executor<'c> for &'c mut SnowflakeConnection {
288304

289305
fn describe<'e, 'q: 'e>(
290306
self,
291-
sql: &'q str,
307+
_sql: &'q str,
292308
) -> BoxFuture<'e, Result<Describe<Self::Database>, Error>>
293309
where
294310
'c: 'e,
@@ -303,4 +319,4 @@ impl<'c> Executor<'c> for &'c mut SnowflakeConnection {
303319
})
304320
})
305321
}
306-
}
322+
}

sqlx-core/src/snowflake/database.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,4 +46,4 @@ impl<'q> HasStatement<'q> for Snowflake {
4646
type Statement = SnowflakeStatement<'q>;
4747
}
4848

49-
impl HasStatementCache for Snowflake {}
49+
impl HasStatementCache for Snowflake {}

sqlx-core/src/snowflake/error.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,4 +55,4 @@ impl DatabaseError for SnowflakeDatabaseError {
5555
fn into_error(self: Box<Self>) -> Box<dyn std::error::Error + Send + Sync + 'static> {
5656
self
5757
}
58-
}
58+
}

sqlx-core/src/snowflake/migrate.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
// Placeholder for migration support
2-
// TODO: Implement migration utilities for Snowflake
2+
// TODO: Implement migration utilities for Snowflake

sqlx-core/src/snowflake/mod.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ pub use query_result::SnowflakeQueryResult;
3434
pub use row::SnowflakeRow;
3535
pub use statement::SnowflakeStatement;
3636
pub use transaction::SnowflakeTransactionManager;
37-
pub use type_info::{SnowflakeTypeInfo, SnowflakeType};
37+
pub use type_info::{SnowflakeType, SnowflakeTypeInfo};
3838
pub use value::{SnowflakeValue, SnowflakeValueRef};
3939

4040
/// An alias for [`Pool`][crate::pool::Pool], specialized for Snowflake.
@@ -54,4 +54,4 @@ impl_acquire!(Snowflake, SnowflakeConnection);
5454
impl_column_index_for_row!(SnowflakeRow);
5555
impl_column_index_for_statement!(SnowflakeStatement);
5656
impl_into_maybe_pool!(Snowflake, SnowflakeConnection);
57-
impl_encode_for_option!(Snowflake);
57+
impl_encode_for_option!(Snowflake);

sqlx-core/src/snowflake/options.rs

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
use crate::connection::ConnectOptions;
22
use crate::error::Error;
3-
use std::borrow::Cow;
43
use std::str::FromStr;
54
use url::Url;
65

@@ -23,18 +22,13 @@ pub struct SnowflakeConnectOptions {
2322
/// SSL mode for Snowflake connections.
2423
///
2524
/// Snowflake always uses SSL, so this is mainly for future extensibility.
26-
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25+
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2726
pub enum SnowflakeSslMode {
2827
/// Always use SSL (default and only supported mode for Snowflake)
28+
#[default]
2929
Require,
3030
}
3131

32-
impl Default for SnowflakeSslMode {
33-
fn default() -> Self {
34-
SnowflakeSslMode::Require
35-
}
36-
}
37-
3832
impl SnowflakeConnectOptions {
3933
pub fn new() -> Self {
4034
Self {
@@ -197,9 +191,7 @@ impl ConnectOptions for SnowflakeConnectOptions {
197191
where
198192
Self::Connection: Sized,
199193
{
200-
Box::pin(async move {
201-
crate::snowflake::SnowflakeConnection::establish(self).await
202-
})
194+
Box::pin(async move { crate::snowflake::SnowflakeConnection::establish(self).await })
203195
}
204196

205197
fn log_statements(&mut self, _level: log::LevelFilter) -> &mut Self {
@@ -215,4 +207,4 @@ impl ConnectOptions for SnowflakeConnectOptions {
215207
// TODO: implement slow statement logging
216208
self
217209
}
218-
}
210+
}

0 commit comments

Comments
 (0)