use std::str::FromStr;
use arrow::csv::WriterBuilder;
use crate::{
config::ConfigOptions,
error::{DataFusionError, Result},
parsers::CompressionTypeVariant,
};
use super::StatementOptions;
#[derive(Clone, Debug)]
pub struct CsvWriterOptions {
pub writer_options: WriterBuilder,
pub compression: CompressionTypeVariant,
pub has_header: bool,
}
impl CsvWriterOptions {
pub fn new(
writer_options: WriterBuilder,
compression: CompressionTypeVariant,
) -> Self {
Self {
writer_options,
compression,
has_header: true,
}
}
}
impl TryFrom<(&ConfigOptions, &StatementOptions)> for CsvWriterOptions {
type Error = DataFusionError;
fn try_from(value: (&ConfigOptions, &StatementOptions)) -> Result<Self> {
let _configs = value.0;
let statement_options = value.1;
let mut has_header = true;
let mut builder = WriterBuilder::default();
let mut compression = CompressionTypeVariant::UNCOMPRESSED;
for (option, value) in &statement_options.options {
builder = match option.to_lowercase().as_str(){
"header" => {
has_header = value.parse()
.map_err(|_| DataFusionError::Configuration(format!("Unable to parse {value} as bool as required for {option}!")))?;
builder.has_headers(has_header)
},
"date_format" => builder.with_date_format(value.to_owned()),
"datetime_format" => builder.with_datetime_format(value.to_owned()),
"timestamp_format" => builder.with_timestamp_format(value.to_owned()),
"time_format" => builder.with_time_format(value.to_owned()),
"rfc3339" => {
let value_bool = value.parse()
.map_err(|_| DataFusionError::Configuration(format!("Unable to parse {value} as bool as required for {option}!")))?;
if value_bool{
builder.with_rfc3339()
} else{
builder
}
},
"null_value" => builder.with_null(value.to_owned()),
"compression" => {
compression = CompressionTypeVariant::from_str(value.replace('\'', "").as_str())?;
builder
},
"delimeter" => {
let value = value.replace('\'', "");
let chars: Vec<char> = value.chars().collect();
if chars.len()>1{
return Err(DataFusionError::Configuration(format!(
"CSV Delimeter Option must be a single char, got: {}", value
)))
}
builder.with_delimiter(chars[0].try_into().map_err(|_| {
DataFusionError::Internal(
"Unable to convert CSV delimiter into u8".into(),
)
})?)
},
_ => return Err(DataFusionError::Configuration(format!("Found unsupported option {option} with value {value} for CSV format!")))
}
}
Ok(CsvWriterOptions {
has_header,
writer_options: builder,
compression,
})
}
}