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
use {
	super::{CSVDatabase, CSVDatabaseError},
	crate::{Cast, DBMut, Result, Row, Schema, WIPError},
	async_trait::async_trait,
	csv::WriterBuilder,
	std::{fs::OpenOptions, io::Write},
};

#[async_trait(?Send)]
impl DBMut for CSVDatabase {
	async fn insert_schema(&mut self, schema: &Schema) -> Result<()> {
		if self.schema.is_some() {
			return Err(CSVDatabaseError::OnlyOneTableAllowed.into());
		}

		let mut writer = WriterBuilder::new()
			.delimiter(self.csv_settings.delimiter)
			.from_writer(vec![]); // Not good but was having Size issues with moving this elsewhere

		let header: Vec<String> = schema
			.column_defs
			.iter()
			.map(|column_def| column_def.name.clone())
			.collect();

		writer
			.write_record(header)
			.map_err(|error| WIPError::Debug(format!("{:?}", error)))?;

		writer
			.flush()
			.map_err(|error| WIPError::Debug(format!("{:?}", error)))?;

		let csv_bytes = writer
			.into_inner()
			.map_err(|error| WIPError::Debug(format!("{:?}", error)))?;

		let mut file = OpenOptions::new()
			.truncate(true)
			.write(true)
			.open(self.path.as_str())
			.map_err(|error| WIPError::Debug(format!("{:?}", error)))?;

		file.write_all(&csv_bytes)
			.map_err(|error| WIPError::Debug(format!("{:?}", error)))?;
		file.flush()
			.map_err(|error| WIPError::Debug(format!("{:?}", error)))?;

		self.schema = Some(schema.clone());
		Ok(())
	}

	async fn delete_schema(&mut self, _table_name: &str) -> Result<()> {
		self.schema = None;
		Ok(())
	}

	async fn insert_data(&mut self, _table_name: &str, rows: Vec<Row>) -> Result<()> {
		let mut writer = WriterBuilder::new()
			.delimiter(self.csv_settings.delimiter)
			.from_writer(vec![]); // Not good but was having Size issues with moving this elsewhere

		for row in rows.into_iter() {
			let string_row = row
				.0
				.into_iter()
				.map(|cell| cell.cast())
				.collect::<Result<Vec<String>>>()?;
			writer
				.write_record(string_row)
				.map_err(|error| WIPError::Debug(format!("{:?}", error)))?;
		}

		writer
			.flush()
			.map_err(|error| WIPError::Debug(format!("{:?}", error)))?;

		let csv_bytes = writer
			.into_inner()
			.map_err(|error| WIPError::Debug(format!("{:?}", error)))?;

		let mut file = OpenOptions::new()
			.append(true)
			.open(self.path.as_str())
			.map_err(|error| WIPError::Debug(format!("{:?}", error)))?;

		file.write_all(&csv_bytes)
			.map_err(|error| WIPError::Debug(format!("{:?}", error)))?;
		file.flush()
			.map_err(|error| WIPError::Debug(format!("{:?}", error)))?;
		Ok(())
	}
}