1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
use std::{cell::RefCell, fs::File, io::Write, path::Path};
use csv::{Writer, WriterBuilder};
use serde::Serialize;
use crate::{core::item::ItemWriter, BatchError};
pub struct CsvItemWriter<T: Write> {
writer: RefCell<Writer<T>>,
}
impl<T: Write, R: Serialize> ItemWriter<R> for CsvItemWriter<T> {
fn write(&self, item: &R) -> Result<(), BatchError> {
let result = self.writer.borrow_mut().serialize(item);
match result {
Ok(()) => Ok(()),
Err(error) => Err(BatchError::ItemWriter(error.to_string())),
}
}
/// Flush the contents of the internal buffer to the underlying writer.
///
/// If there was a problem writing to the underlying writer, then an error
/// is returned.
///
/// Note that this also flushes the underlying writer.
fn flush(&self) -> Result<(), BatchError> {
let result = self.writer.borrow_mut().flush();
match result {
Ok(()) => Ok(()),
Err(error) => Err(BatchError::ItemWriter(error.to_string())),
}
}
}
#[derive(Default)]
pub struct CsvItemWriterBuilder {
delimiter: u8,
has_headers: bool,
}
impl CsvItemWriterBuilder {
pub fn new() -> CsvItemWriterBuilder {
CsvItemWriterBuilder {
delimiter: b',',
has_headers: false,
}
}
pub fn delimiter(mut self, delimiter: u8) -> CsvItemWriterBuilder {
self.delimiter = delimiter;
self
}
pub fn has_headers(mut self, yes: bool) -> CsvItemWriterBuilder {
self.has_headers = yes;
self
}
pub fn from_path<R: AsRef<Path>>(self, path: R) -> CsvItemWriter<File> {
let writer = WriterBuilder::new()
.has_headers(self.has_headers)
.from_path(path);
CsvItemWriter {
writer: RefCell::new(writer.unwrap()),
}
}
/// Serialize a single record using Serde.
///
/// # Example
///
/// This shows how to serialize normal Rust structs as CSV records. The
/// fields of the struct are used to write a header row automatically.
/// (Writing the header row automatically can be disabled by building the
/// CSV writer with a [`WriterBuilder`](struct.WriterBuilder.html) and
/// calling the `has_headers` method.)
///
/// ```
/// # use std::error::Error;
/// # use csv::Writer;
/// # use spring_batch_rs::{item::csv::csv_writer::CsvItemWriterBuilder, core::item::ItemWriter};
/// #[derive(serde::Serialize)]
/// struct Row<'a> {
/// city: &'a str,
/// country: &'a str,
/// #[serde(rename = "popcount")]
/// population: u64,
/// }
///
/// # fn main() { example().unwrap(); }
/// fn example() -> Result<(), Box<dyn Error>> {
/// let wtr = CsvItemWriterBuilder::new()
/// .has_headers(true)
/// .from_writer(vec![]);
///
/// wtr.write(&Row {
/// city: "Boston",
/// country: "United States",
/// population: 4628910,
/// });
///
/// wtr.write(&Row {
/// city: "Concord",
/// country: "United States",
/// population: 42695,
/// });
///
/// Ok(())
/// }
/// ```
pub fn from_writer<W: Write>(self, wtr: W) -> CsvItemWriter<W> {
let wtr = WriterBuilder::new()
.flexible(false)
.has_headers(self.has_headers)
.from_writer(wtr);
CsvItemWriter {
writer: RefCell::new(wtr),
}
}
}
#[cfg(test)]
mod tests {
use std::{env::temp_dir, error::Error};
use crate::{core::item::ItemWriter, item::csv::csv_writer::CsvItemWriterBuilder};
#[derive(serde::Serialize)]
struct Row<'a> {
city: &'a str,
country: &'a str,
#[serde(rename = "popcount")]
population: u64,
}
#[test]
fn this_test_will_pass() -> Result<(), Box<dyn Error>> {
let wtr = CsvItemWriterBuilder::new()
.has_headers(true)
.from_writer(vec![]);
let resut = wtr.write(&Row {
city: "Boston",
country: "United States",
population: 4628910,
});
assert!(resut.is_ok());
let resut = wtr.write(&Row {
city: "Concord",
country: "United States",
population: 42695,
});
assert!(resut.is_ok());
Ok(())
}
#[test]
fn records_should_be_serialized() -> Result<(), Box<dyn Error>> {
let wtr = CsvItemWriterBuilder::new()
.has_headers(false)
.from_path(temp_dir().join("foo.csv"));
let resut = wtr.write(&Row {
city: "Boston",
country: "United States",
population: 4628910,
});
assert!(resut.is_ok());
let resut = wtr.write(&Row {
city: "Concord",
country: "United States",
population: 42695,
});
assert!(resut.is_ok());
Ok(())
}
}