use async_trait::async_trait;
use url::Url;
use std::collections::HashMap;
use tempfile::NamedTempFile;
use std::io::Write;
use tracing::{info, debug, error, warn};
use crate::{
Result, TinyEtlError,
connectors::{Source, Target},
protocols::Protocol,
schema::{Schema, Row, Column, DataType},
};
pub struct SnowflakeProtocol;
#[derive(Debug, Clone)]
pub struct SnowflakeConnection {
pub account: String,
pub username: String,
pub password: String,
pub database: String,
pub schema: String,
pub warehouse: Option<String>,
pub role: Option<String>,
pub table: String,
}
impl SnowflakeProtocol {
pub fn new() -> Self {
Self
}
fn parse_url(&self, url: &Url) -> Result<SnowflakeConnection> {
if url.scheme() != "snowflake" {
return Err(TinyEtlError::Configuration(
format!("Expected snowflake:// scheme, got: {}", url.scheme())
));
}
let username = url.username();
if username.is_empty() {
return Err(TinyEtlError::Configuration(
"Snowflake URL must include username".to_string()
));
}
let password = url.password().unwrap_or("");
if password.is_empty() {
return Err(TinyEtlError::Configuration(
"Snowflake URL must include password".to_string()
));
}
let account = url.host_str()
.ok_or_else(|| TinyEtlError::Configuration(
"Snowflake URL must include account in host".to_string()
))?
.to_string();
if account.is_empty() {
return Err(TinyEtlError::Configuration(
"Snowflake URL must include account in host".to_string()
));
}
let path_segments: Vec<&str> = url.path().trim_start_matches('/').split('/').collect();
if path_segments.len() < 2 {
return Err(TinyEtlError::Configuration(
"Snowflake URL must include database and schema in path: /database/schema".to_string()
));
}
let database = path_segments[0].to_string();
let schema = path_segments[1].to_string();
let query_params: HashMap<String, String> = url.query_pairs()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
let table = query_params.get("table")
.ok_or_else(|| TinyEtlError::Configuration(
"Snowflake URL must include table parameter: ?table=TABLE_NAME".to_string()
))?
.clone();
let warehouse = query_params.get("warehouse").cloned();
let role = query_params.get("role").cloned();
Ok(SnowflakeConnection {
account,
username: username.to_string(),
password: password.to_string(),
database,
schema,
warehouse,
role,
table,
})
}
async fn create_connection(&self, conn: &SnowflakeConnection) -> Result<()> {
info!("Creating connection to Snowflake account: {}", conn.account);
info!("Database: {}, Schema: {}, Table: {}", conn.database, conn.schema, conn.table);
warn!("Snowflake protocol is currently a mock implementation");
warn!("For production use, implement proper Snowflake REST API or JDBC connection");
Ok(())
}
}
#[async_trait]
impl Protocol for SnowflakeProtocol {
async fn create_source(&self, url: &Url) -> Result<Box<dyn Source>> {
let conn = self.parse_url(url)?;
Ok(Box::new(SnowflakeSource::new(conn).await?))
}
async fn create_target(&self, url: &Url) -> Result<Box<dyn Target>> {
let conn = self.parse_url(url)?;
Ok(Box::new(SnowflakeTarget::new(conn).await?))
}
fn validate_url(&self, url: &Url) -> Result<()> {
self.parse_url(url)?;
Ok(())
}
fn name(&self) -> &'static str {
"snowflake"
}
}
pub struct SnowflakeSource {
connection: SnowflakeConnection,
temp_file: Option<NamedTempFile>,
parquet_source: Option<Box<dyn Source>>,
schema: Option<Schema>,
}
impl SnowflakeSource {
pub async fn new(connection: SnowflakeConnection) -> Result<Self> {
Ok(Self {
connection,
temp_file: None,
parquet_source: None,
schema: None,
})
}
async fn export_to_temp_file(&mut self) -> Result<()> {
info!("Simulating export of Snowflake table {} to temporary Parquet file", self.connection.table);
let temp_file = NamedTempFile::new()
.map_err(|e| TinyEtlError::Io(e))?;
let temp_path = temp_file.path().to_string_lossy().to_string();
warn!("Mock implementation: Creating sample Parquet file for testing");
let mut parquet_target = crate::connectors::parquet::ParquetTarget::new(&temp_path)?;
parquet_target.connect().await?;
let sample_schema = Schema {
columns: vec![
Column {
name: "id".to_string(),
data_type: DataType::Integer,
nullable: false,
},
Column {
name: "name".to_string(),
data_type: DataType::String,
nullable: true,
},
Column {
name: "created_at".to_string(),
data_type: DataType::DateTime,
nullable: true,
},
],
estimated_rows: Some(2),
primary_key_candidate: Some("id".to_string()),
};
parquet_target.create_table("mock_table", &sample_schema).await?;
use crate::schema::Value;
use chrono::Utc;
let sample_rows = vec![
{
let mut row = std::collections::HashMap::new();
row.insert("id".to_string(), Value::Integer(1));
row.insert("name".to_string(), Value::String("Sample User 1".to_string()));
row.insert("created_at".to_string(), Value::Date(Utc::now()));
row
},
{
let mut row = std::collections::HashMap::new();
row.insert("id".to_string(), Value::Integer(2));
row.insert("name".to_string(), Value::String("Sample User 2".to_string()));
row.insert("created_at".to_string(), Value::Date(Utc::now()));
row
}
];
parquet_target.write_batch(&sample_rows).await?;
parquet_target.finalize().await?;
let parquet_source = crate::connectors::parquet::ParquetSource::new(&temp_path)?;
self.temp_file = Some(temp_file);
self.parquet_source = Some(Box::new(parquet_source));
info!("Created mock Parquet file with sample data");
Ok(())
}
}
#[async_trait]
impl Source for SnowflakeSource {
async fn connect(&mut self) -> Result<()> {
info!("Connecting to Snowflake account: {}", self.connection.account);
let protocol = SnowflakeProtocol::new();
protocol.create_connection(&self.connection).await?;
info!("Successfully connected to Snowflake");
Ok(())
}
async fn infer_schema(&mut self, sample_size: usize) -> Result<Schema> {
if self.schema.is_none() {
if self.parquet_source.is_none() {
self.export_to_temp_file().await?;
}
if let Some(ref mut source) = self.parquet_source {
source.connect().await?;
let schema = source.infer_schema(sample_size).await?;
self.schema = Some(schema.clone());
return Ok(schema);
}
}
self.schema.clone()
.ok_or_else(|| TinyEtlError::SchemaInference("Schema not available".to_string()))
}
async fn read_batch(&mut self, batch_size: usize) -> Result<Vec<Row>> {
if self.parquet_source.is_none() {
self.export_to_temp_file().await?;
}
if let Some(ref mut source) = self.parquet_source {
if self.schema.is_none() {
source.connect().await?;
}
source.read_batch(batch_size).await
} else {
warn!("Mock implementation: No parquet source available, returning empty batch");
Ok(vec![])
}
}
async fn estimated_row_count(&self) -> Result<Option<usize>> {
if let Some(ref source) = self.parquet_source {
source.estimated_row_count().await
} else {
Ok(Some(2)) }
}
async fn reset(&mut self) -> Result<()> {
if let Some(ref mut source) = self.parquet_source {
source.reset().await
} else {
Ok(())
}
}
fn has_more(&self) -> bool {
self.parquet_source.as_ref()
.map(|source| source.has_more())
.unwrap_or(false)
}
}
pub struct SnowflakeTarget {
connection: SnowflakeConnection,
temp_file: Option<NamedTempFile>,
parquet_target: Option<Box<dyn Target>>,
}
impl SnowflakeTarget {
pub async fn new(connection: SnowflakeConnection) -> Result<Self> {
Ok(Self {
connection,
temp_file: None,
parquet_target: None,
})
}
async fn setup_temp_target(&mut self) -> Result<()> {
if self.parquet_target.is_none() {
let temp_file = NamedTempFile::new()
.map_err(|e| TinyEtlError::Io(e))?;
let temp_path = temp_file.path().to_string_lossy().to_string();
let parquet_target = crate::connectors::parquet::ParquetTarget::new(&temp_path)?;
self.temp_file = Some(temp_file);
self.parquet_target = Some(Box::new(parquet_target));
}
Ok(())
}
async fn import_from_temp_file(&mut self) -> Result<()> {
if let Some(ref temp_file) = self.temp_file {
let temp_path = temp_file.path().to_string_lossy().to_string();
info!("Simulating import from temporary Parquet file to Snowflake table {}", self.connection.table);
warn!("Mock implementation: Simulating data import to Snowflake");
info!("Successfully simulated import to Snowflake");
}
Ok(())
}
}
#[async_trait]
impl Target for SnowflakeTarget {
async fn connect(&mut self) -> Result<()> {
info!("Connecting to Snowflake account: {}", self.connection.account);
let protocol = SnowflakeProtocol::new();
protocol.create_connection(&self.connection).await?;
self.setup_temp_target().await?;
if let Some(ref mut target) = self.parquet_target {
target.connect().await?;
}
info!("Successfully connected to Snowflake");
Ok(())
}
async fn create_table(&mut self, table_name: &str, schema: &Schema) -> Result<()> {
warn!("Mock implementation: Simulating table creation in Snowflake");
let mut ddl = format!("CREATE TABLE IF NOT EXISTS {} (", self.connection.table);
for (i, column) in schema.columns.iter().enumerate() {
if i > 0 {
ddl.push_str(", ");
}
let snowflake_type = match column.data_type {
DataType::Integer => "INTEGER",
DataType::Decimal => "NUMBER(38,18)", DataType::String => "VARCHAR(16777216)", DataType::Boolean => "BOOLEAN",
DataType::DateTime => "TIMESTAMP",
DataType::Date => "DATE",
DataType::Json => "VARIANT", DataType::Null => "VARCHAR(16777216)", };
ddl.push_str(&format!("{} {}", column.name, snowflake_type));
}
ddl.push(')');
info!("Simulating Snowflake table creation: {}", ddl);
if let Some(ref mut target) = self.parquet_target {
target.create_table(table_name, schema).await?;
}
Ok(())
}
async fn write_batch(&mut self, rows: &[Row]) -> Result<usize> {
if let Some(ref mut target) = self.parquet_target {
target.write_batch(rows).await
} else {
Ok(0)
}
}
async fn finalize(&mut self) -> Result<()> {
if let Some(ref mut target) = self.parquet_target {
target.finalize().await?;
}
self.import_from_temp_file().await?;
Ok(())
}
async fn exists(&self, table_name: &str) -> Result<bool> {
warn!("Mock implementation: Assuming table does not exist");
Ok(false)
}
async fn truncate(&mut self, table_name: &str) -> Result<()> {
warn!("Mock implementation: Simulating table truncation in Snowflake");
info!("Simulating Snowflake table truncation: TRUNCATE TABLE {}", table_name);
if let Some(ref mut target) = self.parquet_target {
target.truncate(table_name).await?;
}
Ok(())
}
fn supports_append(&self) -> bool {
true
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_snowflake_url() {
let protocol = SnowflakeProtocol::new();
let url = Url::parse("snowflake://alex:password@xy12345.east-us.azure/mydb/public?warehouse=COMPUTE_WH&table=sales").unwrap();
let conn = protocol.parse_url(&url).unwrap();
assert_eq!(conn.username, "alex");
assert_eq!(conn.password, "password");
assert_eq!(conn.account, "xy12345.east-us.azure");
assert_eq!(conn.database, "mydb");
assert_eq!(conn.schema, "public");
assert_eq!(conn.warehouse, Some("COMPUTE_WH".to_string()));
assert_eq!(conn.table, "sales");
}
#[test]
fn test_parse_snowflake_url_missing_table() {
let protocol = SnowflakeProtocol::new();
let url = Url::parse("snowflake://alex:password@xy12345.east-us.azure/mydb/public?warehouse=COMPUTE_WH").unwrap();
let result = protocol.parse_url(&url);
assert!(result.is_err());
assert!(result.unwrap_err().to_string().contains("table parameter"));
}
#[test]
fn test_parse_snowflake_url_missing_credentials() {
let protocol = SnowflakeProtocol::new();
let url = Url::parse("snowflake://xy12345.east-us.azure/mydb/public?table=sales").unwrap();
let result = protocol.parse_url(&url);
assert!(result.is_err());
assert!(result.unwrap_err().to_string().contains("username"));
}
#[test]
fn test_validate_url() {
let protocol = SnowflakeProtocol::new();
let url = Url::parse("snowflake://alex:password@xy12345.east-us.azure/mydb/public?warehouse=COMPUTE_WH&table=sales").unwrap();
assert!(protocol.validate_url(&url).is_ok());
let url = Url::parse("http://example.com").unwrap();
assert!(protocol.validate_url(&url).is_err());
}
#[test]
fn test_protocol_name() {
let protocol = SnowflakeProtocol::new();
assert_eq!(protocol.name(), "snowflake");
}
#[test]
fn test_parse_url_missing_password() {
let protocol = SnowflakeProtocol::new();
let url = Url::parse("snowflake://alex@xy12345.east-us.azure/mydb/public?table=sales").unwrap();
let result = protocol.parse_url(&url);
assert!(result.is_err());
if let Err(TinyEtlError::Configuration(msg)) = result {
assert!(msg.contains("password"));
}
}
#[test]
fn test_parse_url_missing_database() {
let protocol = SnowflakeProtocol::new();
let url = Url::parse("snowflake://alex:pass@xy12345.east-us.azure/?table=sales").unwrap();
let result = protocol.parse_url(&url);
assert!(result.is_err());
if let Err(TinyEtlError::Configuration(msg)) = result {
assert!(msg.contains("database and schema"));
}
}
#[test]
fn test_parse_url_missing_schema() {
let protocol = SnowflakeProtocol::new();
let url = Url::parse("snowflake://alex:pass@xy12345.east-us.azure/mydb?table=sales").unwrap();
let result = protocol.parse_url(&url);
assert!(result.is_err());
if let Err(TinyEtlError::Configuration(msg)) = result {
assert!(msg.contains("database and schema"));
}
}
#[test]
fn test_parse_url_with_role() {
let protocol = SnowflakeProtocol::new();
let url = Url::parse("snowflake://user:pass@account.region.cloud/db/schema?warehouse=WH&role=ANALYST&table=data").unwrap();
let conn = protocol.parse_url(&url).unwrap();
assert_eq!(conn.role, Some("ANALYST".to_string()));
assert_eq!(conn.warehouse, Some("WH".to_string()));
}
#[test]
fn test_parse_url_without_optional_params() {
let protocol = SnowflakeProtocol::new();
let url = Url::parse("snowflake://user:pass@account.region.cloud/db/schema?table=data").unwrap();
let conn = protocol.parse_url(&url).unwrap();
assert_eq!(conn.username, "user");
assert_eq!(conn.password, "pass");
assert_eq!(conn.database, "db");
assert_eq!(conn.schema, "schema");
assert_eq!(conn.table, "data");
assert_eq!(conn.warehouse, None);
assert_eq!(conn.role, None);
}
#[test]
fn test_parse_url_with_special_characters_in_password() {
let protocol = SnowflakeProtocol::new();
let url = Url::parse("snowflake://user:p%40ssw0rd%21@account.region.cloud/db/schema?table=data").unwrap();
let conn = protocol.parse_url(&url).unwrap();
assert_eq!(conn.username, "user");
assert_eq!(conn.password, "p%40ssw0rd%21");
}
#[test]
fn test_parse_url_different_regions() {
let protocol = SnowflakeProtocol::new();
let regions = vec![
"account.us-east-1.aws",
"account.eu-west-1.aws",
"account.ap-southeast-2.aws",
"account.eastus2.azure",
"account.westeurope.azure",
];
for region in regions {
let url_str = format!("snowflake://user:pass@{}/db/schema?table=test", region);
let url = Url::parse(&url_str).unwrap();
let conn = protocol.parse_url(&url).unwrap();
assert_eq!(conn.account, region);
}
}
#[test]
fn test_parse_url_invalid_scheme() {
let protocol = SnowflakeProtocol::new();
let url = Url::parse("mysql://user:pass@host/db?table=test").unwrap();
let result = protocol.parse_url(&url);
assert!(result.is_err());
if let Err(TinyEtlError::Configuration(msg)) = result {
assert!(msg.contains("snowflake://"));
assert!(msg.contains("mysql"));
}
}
#[test]
fn test_parse_url_case_sensitive_params() {
let protocol = SnowflakeProtocol::new();
let url = Url::parse("snowflake://user:pass@account.region.cloud/DB/SCHEMA?table=TABLE&warehouse=WH").unwrap();
let conn = protocol.parse_url(&url).unwrap();
assert_eq!(conn.database, "DB");
assert_eq!(conn.schema, "SCHEMA");
assert_eq!(conn.table, "TABLE");
}
#[test]
fn test_parse_url_with_extra_query_params() {
let protocol = SnowflakeProtocol::new();
let url = Url::parse("snowflake://user:pass@account.region.cloud/db/schema?table=data&warehouse=WH&custom=value&timeout=30").unwrap();
let conn = protocol.parse_url(&url).unwrap();
assert_eq!(conn.table, "data");
assert_eq!(conn.warehouse, Some("WH".to_string()));
}
#[test]
fn test_snowflake_connection_clone() {
let conn = SnowflakeConnection {
account: "account".to_string(),
username: "user".to_string(),
password: "pass".to_string(),
database: "db".to_string(),
schema: "schema".to_string(),
warehouse: Some("WH".to_string()),
role: Some("ROLE".to_string()),
table: "table".to_string(),
};
let cloned = conn.clone();
assert_eq!(conn.account, cloned.account);
assert_eq!(conn.username, cloned.username);
assert_eq!(conn.password, cloned.password);
assert_eq!(conn.table, cloned.table);
}
#[test]
fn test_connection_debug_format() {
let conn = SnowflakeConnection {
account: "test_account".to_string(),
username: "test_user".to_string(),
password: "secret".to_string(),
database: "test_db".to_string(),
schema: "test_schema".to_string(),
warehouse: None,
role: None,
table: "test_table".to_string(),
};
let debug_str = format!("{:?}", conn);
assert!(debug_str.contains("test_account"));
assert!(debug_str.contains("test_user"));
assert!(debug_str.contains("test_table"));
}
#[test]
fn test_parse_url_empty_table_param() {
let protocol = SnowflakeProtocol::new();
let url = Url::parse("snowflake://user:pass@account.region.cloud/db/schema?table=").unwrap();
let conn = protocol.parse_url(&url).unwrap();
assert_eq!(conn.table, "");
}
#[test]
fn test_parse_url_complex_path() {
let protocol = SnowflakeProtocol::new();
let url = Url::parse("snowflake://user:pass@account.region.cloud/db/schema/extra/path?table=test").unwrap();
let conn = protocol.parse_url(&url).unwrap();
assert_eq!(conn.database, "db");
assert_eq!(conn.schema, "schema");
}
#[test]
fn test_parse_url_no_host() {
let protocol = SnowflakeProtocol::new();
match Url::parse("snowflake://user:pass@/db/schema?table=test") {
Ok(url) => {
let result = protocol.parse_url(&url);
assert!(result.is_err());
}
Err(_) => {
}
}
}
#[test]
fn test_parse_url_localhost_host() {
let protocol = SnowflakeProtocol::new();
let url = Url::parse("snowflake://user:pass@localhost/db/schema").unwrap();
let result = protocol.parse_url(&url);
assert!(result.is_err());
match result {
Err(TinyEtlError::Configuration(msg)) => {
assert!(msg.contains("table"), "Error message was: {}", msg);
}
_ => panic!("Expected Configuration error about table"),
}
}
#[test]
fn test_validate_url_with_different_schemes() {
let protocol = SnowflakeProtocol::new();
let invalid_schemes = vec![
"http://example.com",
"https://example.com",
"mysql://host/db",
"postgres://host/db",
"ftp://example.com",
];
for scheme in invalid_schemes {
let url = Url::parse(scheme).unwrap();
assert!(protocol.validate_url(&url).is_err(), "Should reject scheme: {}", scheme);
}
}
#[test]
fn test_snowflake_url_with_port() {
let protocol = SnowflakeProtocol::new();
let url = Url::parse("snowflake://user:pass@account.region.cloud:443/db/schema?table=test").unwrap();
let conn = protocol.parse_url(&url).unwrap();
assert!(conn.account.contains("account.region.cloud"));
}
#[test]
fn test_parse_url_with_underscore_and_numbers() {
let protocol = SnowflakeProtocol::new();
let url = Url::parse("snowflake://user_123:pass@account_456.region.cloud/db_test/schema_v2?table=table_2024&warehouse=WH_PROD").unwrap();
let conn = protocol.parse_url(&url).unwrap();
assert_eq!(conn.username, "user_123");
assert_eq!(conn.account, "account_456.region.cloud");
assert_eq!(conn.database, "db_test");
assert_eq!(conn.schema, "schema_v2");
assert_eq!(conn.table, "table_2024");
assert_eq!(conn.warehouse, Some("WH_PROD".to_string()));
}
}