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
mod auto_increment;
mod base;
mod discern;
mod mutable;
mod record;
mod utils;

pub use record::*;

use {
	crate::{data::Schema, DBFull, Database, Result, WIPError},
	serde::{Deserialize, Serialize},
	std::{default::Default, fmt::Debug, fs::OpenOptions},
	thiserror::Error,
};

#[derive(Error, Serialize, Debug, PartialEq)]
pub enum CSVDatabaseError {
	#[error("CSV storages only support one table at a time")]
	OnlyOneTableAllowed,

	#[error("Failed to open CSV because of a error with header: {0}")]
	HeaderError(String),
}

pub struct CSVDatabase {
	schema: Option<Schema>,
	path: String,
	pub csv_settings: CSVSettings,
}
#[derive(Clone, Serialize, Deserialize)]
pub struct CSVSettings {
	pub delimiter: u8,
	pub quoting: bool,
	pub has_header: Option<bool>,
	pub sample_rows: usize,
}
impl Default for CSVSettings {
	fn default() -> Self {
		Self {
			delimiter: b',',
			quoting: true,
			has_header: None,
			sample_rows: 100,
		}
	}
}

impl DBFull for CSVDatabase {}

impl Database {
	pub fn new_csv(storage: CSVDatabase) -> Self {
		Self::new(Box::new(storage))
	}
}
impl CSVDatabase {
	pub fn new(path: &str) -> Result<Self> {
		Self::new_with_settings(path, CSVSettings::default())
	}
	pub fn new_with_settings(path: &str, mut csv_settings: CSVSettings) -> Result<Self> {
		let file = OpenOptions::new()
			.read(true)
			.write(true)
			.create(true)
			.open(path)
			.map_err(|error| WIPError::Debug(format!("{:?}", error)))?;

		let schema = csv_settings.discern_schema(file)?;
		Ok(Self {
			schema,
			path: path.to_string(),
			csv_settings,
		})
	}
}