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
use {
	crate::{result::Result, Column, DatabaseInner, Ingredient, Method, Recipe, Value},
	rayon::prelude::*,
	serde::{Deserialize, Serialize},
	std::{cmp::Ordering, collections::HashMap},
};

#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct Index {
	pub name: String,
	pub column: String,
	pub is_unique: bool,
}

#[derive(Clone, Debug)]
pub enum IndexFilter {
	LessThan(String, Value), // Index, Min, Max
	MoreThan(String, Value), // Index, Min, Max
	Inner(Box<IndexFilter>, Box<IndexFilter>),
	Outer(Box<IndexFilter>, Box<IndexFilter>),
}

impl Index {
	pub fn new(name: String, column: String, is_unique: bool) -> Self {
		Self {
			name,
			column,
			is_unique,
		}
	}
	pub async fn reset(
		&self,
		storage: &mut DatabaseInner,
		table: &str,
		columns: &[Column],
	) -> Result<()> {
		let rows = storage.scan_data(table).await?;
		let column_index: usize = columns
			.iter()
			.enumerate()
			.find_map(|(index, def)| (def.name == self.column).then(|| index))
			.unwrap(); // TODO: Handle

		let mut rows: Vec<(Value, Vec<Value>)> =
			rows.into_iter().map(|(key, row)| (key, row.0)).collect();
		rows.par_sort_unstable_by(|(_, a_values), (_, b_values)| {
			a_values[column_index]
				.partial_cmp(&b_values[column_index])
				.unwrap_or(Ordering::Equal)
		});
		let keys = rows
			.into_iter()
			.map(|(key, mut values)| (values.swap_remove(column_index), key))
			.collect();

		storage.update_index(table, &self.name, keys).await
	}
}

impl Recipe {
	pub fn reduce_by_index_filter(
		self,
		indexed_columns: HashMap<usize, (String, String)>,
	) -> (Self, Option<HashMap<String, IndexFilter>>) {
		// TODO: OR & others
		use IndexFilter::*;
		match self {
			Recipe::Ingredient(_) => (),
			Recipe::Method(ref method) => match *method.clone() {
				Method::BinaryOperation(operator, left, right)
					if operator as usize == Value::and as usize =>
				{
					let (left, left_filters) = left.reduce_by_index_filter(indexed_columns.clone());
					let (right, right_filters) = right.reduce_by_index_filter(indexed_columns);
					return (
						Recipe::Method(Box::new(Method::BinaryOperation(operator, left, right))),
						match (left_filters, right_filters) {
							(Some(filters), None) | (None, Some(filters)) => Some(filters),
							(Some(left_filters), Some(mut right_filters)) => Some(
								left_filters
									.into_iter()
									.map(|(table, filter)| {
										(
											table.clone(),
											match right_filters.remove(&table) {
												Some(right) => {
													Inner(Box::new(filter), Box::new(right))
												}
												None => filter,
											},
										)
									})
									.collect::<HashMap<String, IndexFilter>>()
									.into_iter()
									.chain(right_filters.into_iter())
									.collect::<HashMap<String, IndexFilter>>(),
							),
							(None, None) => None, // TODO: Don't unnecessarily rebuild
						},
					);
				}
				Method::BinaryOperation(
					operator,
					Recipe::Ingredient(Ingredient::Column(column)),
					Recipe::Ingredient(Ingredient::Value(value)),
				) if operator as usize == Value::eq as usize => {
					{
						if let Some((table, index)) = indexed_columns.get(&column) {
							let mut filters = HashMap::new();
							filters.insert(
								table.clone(),
								Inner(
									Box::new(LessThan(index.clone(), value.inc())),
									Box::new(MoreThan(index.clone(), value)),
								),
							); // Eh; TODO: Improve
							return (Recipe::TRUE, Some(filters));
						}
					}
				}
				Method::BinaryOperation(
					operator,
					Recipe::Ingredient(Ingredient::Column(column)),
					Recipe::Ingredient(Ingredient::Value(value)),
				) if operator as usize == Value::gt_eq as usize => {
					if let Some((table, index)) = indexed_columns.get(&column) {
						let mut filters = HashMap::new();
						filters.insert(table.clone(), MoreThan(index.clone(), value));
						return (Recipe::TRUE, Some(filters));
					}
				}
				Method::BinaryOperation(
					operator,
					Recipe::Ingredient(Ingredient::Column(column)),
					Recipe::Ingredient(Ingredient::Value(value)),
				) if operator as usize == Value::gt as usize => {
					if let Some((table, index)) = indexed_columns.get(&column) {
						let mut filters = HashMap::new();
						filters.insert(table.clone(), MoreThan(index.clone(), value.inc()));
						return (Recipe::TRUE, Some(filters));
					}
				}
				Method::BinaryOperation(
					operator,
					Recipe::Ingredient(Ingredient::Column(column)),
					Recipe::Ingredient(Ingredient::Value(value)),
				) if operator as usize == Value::lt as usize => {
					if let Some((table, index)) = indexed_columns.get(&column) {
						let mut filters = HashMap::new();
						filters.insert(table.clone(), LessThan(index.clone(), value));
						return (Recipe::TRUE, Some(filters));
					}
				}
				Method::BinaryOperation(
					operator,
					Recipe::Ingredient(Ingredient::Column(column)),
					Recipe::Ingredient(Ingredient::Value(value)),
				) if operator as usize == Value::lt_eq as usize => {
					if let Some((table, index)) = indexed_columns.get(&column) {
						let mut filters = HashMap::new();
						filters.insert(table.clone(), LessThan(index.clone(), value.inc()));
						return (Recipe::TRUE, Some(filters));
					}
				}
				_ => (),
			},
		}
		(self, None)
	}
}