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
185
pub mod join;
mod manual;
mod order;
mod plan;

use {
	crate::{
		executor::{
			types::{LabelsAndRows, Row},
			PlannedRecipe,
		},
		macros::try_option,
		Glue, RecipeUtilities, Result, Value,
	},
	futures::stream::{self, StreamExt, TryStreamExt},
	rayon::prelude::*,
	serde::Serialize,
	sqlparser::ast::{OrderByExpr, Select},
	thiserror::Error as ThisError,
};
pub use {
	manual::{Manual, ManualError, SelectItem},
	order::Order,
	plan::*,
};

#[derive(ThisError, Serialize, Debug, PartialEq)]
pub enum SelectError {
	#[error("aggregate groups not supported")]
	GrouperMayNotContainAggregate,

	#[error("an aggregate was probably used where not allowed")]
	FinalSolveFailure,

	#[error("HAVING does not yet support aggregates")]
	UnimplementedAggregateHaving,

	#[error("this should be impossible, please report")]
	UnreachableFinalSolveFailure,
	#[error("this should be impossible, please report")]
	Unreachable,
}

impl Glue {
	pub async fn select(&self, plan: Plan) -> Result<LabelsAndRows> {
		let Plan {
			joins,
			select_items,
			constraint,
			group_constraint,
			groups,
			order_by,
			labels,
		} = plan;
		let rows = stream::iter(joins)
			.map(Ok)
			.try_fold(vec![], |rows, join| async {
				join.execute(self, rows).await
			})
			.await?;

		let rows = order_by.execute(rows)?; // TODO: This should be done after filtering

		let selected_rows =
			rows.into_par_iter()
				.filter_map(|row| match constraint.confirm_constraint(&row) {
					Ok(true) => Some(
						select_items
							.clone()
							.into_iter()
							.map(|selection| selection.simplify_by_row(&row))
							.collect::<Result<Vec<PlannedRecipe>>>()
							.map(|selection| (selection, row)),
					),
					Ok(false) => None,
					Err(error) => Some(Err(error)),
				});
		let do_group = !groups.is_empty()
			|| select_items
				.iter()
				.any(|select_item| !select_item.aggregates.is_empty());

		let final_rows = if do_group {
			let groups = if groups.is_empty() {
				vec![PlannedRecipe::TRUE]
			} else {
				groups
			};

			let accumulations: Vec<(Vec<Value>, Option<PlannedRecipe>, Vec<PlannedRecipe>)> =
				selected_rows
					.filter_map(|selection| {
						let (selected_row, row) = try_option!(selection);
						let group_constraint =
							try_option!(group_constraint.clone().simplify_by_row(&row));
						let group_constraint = match group_constraint.as_solution() {
							Some(Value::Bool(true)) => None,
							Some(Value::Bool(false)) => return None,
							Some(_) => unreachable!(), // TODO: Handle
							None => Some(group_constraint),
						};
						let groupers = try_option!(groups
							.iter()
							.map(|group| {
								group.clone().simplify_by_row(&row)?.confirm_or_err(
									SelectError::GrouperMayNotContainAggregate.into(),
								)
							})
							.collect::<Result<Vec<Value>>>());
						Some(Ok((groupers, group_constraint, selected_row)))
					})
					.map::<_, Result<_>>(|acc| acc.map(|acc| vec![acc]))
					.try_reduce_with(accumulate)
					.unwrap_or(Ok(vec![]))?; // TODO: Improve

			accumulations
				.into_par_iter()
				.map(|(_grouper, _group_constraint, vals)| {
					vals.into_iter()
						.map(|val| val.finalise_accumulation())
						.collect::<Result<Vec<Value>>>()
				})
				.collect::<Result<Vec<Vec<Value>>>>()?
		// TODO: Manage grouper and constraint
		} else {
			selected_rows
				.map(|selection| {
					selection.and_then(|(selection, _)| {
						selection
							.into_iter()
							.map(|selected| selected.confirm())
							.collect::<Result<Row>>()
					})
				})
				.collect::<Result<Vec<Row>>>()?
		};

		Ok((labels, final_rows))
	}
	pub async fn select_query(
		&self,
		query: Select,
		order_by: Vec<OrderByExpr>,
	) -> Result<LabelsAndRows> {
		let plan = Plan::new(self, query, order_by).await?;
		self.select(plan).await
	}
}

#[allow(clippy::type_complexity)] // TODO
fn accumulate(
	mut rows_l: Vec<(Vec<Value>, Option<PlannedRecipe>, Vec<PlannedRecipe>)>,
	rows_r: Vec<(Vec<Value>, Option<PlannedRecipe>, Vec<PlannedRecipe>)>,
) -> Result<Vec<(Vec<Value>, Option<PlannedRecipe>, Vec<PlannedRecipe>)>> {
	rows_r.into_iter().try_for_each::<_, Result<_>>(|row_r| {
		let (grouper, group_constraint, vals) = row_r;
		let group_index = rows_l.iter().position(|(group, _, _)| group == &grouper);
		let new_group = if let Some(group_index) = group_index {
			let (group_grouper, group_group_constraint, group_vals) =
				rows_l.swap_remove(group_index);
			/*rows_l[group_index].1.map(|constraint| {
				if let Some(group_constraint) = group_constraint {
					constraint.accumulate(group_constraint).unwrap() // TODO: Handle
				};
			});*/
			// TODO

			let group_vals = group_vals
				.into_iter()
				.zip(vals.into_iter())
				.map(|(mut col, val)| {
					col.accumulate(val)?;
					Ok(col)
				})
				.collect::<Result<_>>()?;
			(group_grouper, group_group_constraint, group_vals)
		} else {
			(grouper, group_constraint, vals)
		};
		rows_l.push(new_group);
		Ok(())
	})?;

	Ok(rows_l)
}