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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
use {
	super::{
		join::{JoinExecute, JoinPlan},
		Manual, Order, SelectItem,
	},
	crate::{
		executor::{types::ColumnInfo, PlannedRecipe},
		Glue, Result,
	},
	futures::future::join_all,
	serde::Serialize,
	sqlparser::ast::{OrderByExpr, Select},
	thiserror::Error as ThisError,
};

pub struct Plan {
	pub joins: Vec<JoinExecute>,
	pub select_items: Vec<PlannedRecipe>,
	pub constraint: PlannedRecipe,
	pub groups: Vec<PlannedRecipe>,
	pub group_constraint: PlannedRecipe,
	pub order_by: Order,
	pub labels: Vec<String>,
}

#[derive(ThisError, Serialize, Debug, PartialEq)]
pub enum PlanError {
	#[error("this should be impossible, please report")]
	UnreachableNoColumns,
	#[error("this should be impossible, please report")]
	UnreachableNoSelectItems,
	#[error("this should be impossible, please report")]
	Unreachable,
}

impl Plan {
	pub async fn new(glue: &Glue, select: Select, order_by: Vec<OrderByExpr>) -> Result<Plan> {
		let Manual {
			joins,
			select_items,
			constraint,
			group_constraint,
			groups,
		} = Manual::new(select, &*glue.get_context()?)?;

		let mut joins: Vec<JoinPlan> = join_all(
			joins
				.into_iter()
				.map(|join| JoinPlan::new(join, glue))
				.collect::<Vec<_>>(),
		)
		.await
		.into_iter()
		.collect::<Result<Vec<JoinPlan>>>()?;

		joins.sort_unstable();
		let table_columns = joins
			.iter()
			.map(|join| join.columns.clone())
			.collect::<Vec<Vec<ColumnInfo>>>();
		let joins = joins
			.into_iter()
			.map(|mut join| {
				join.calculate_needed_tables(&table_columns);
				join
			})
			.enumerate()
			.collect();

		let mut needed_joins: Vec<(usize, JoinPlan)> = joins;
		let mut requested_joins: Vec<(usize, JoinPlan)> = vec![];
		let mut len_last: usize;
		let mut len = 0;
		loop {
			len_last = len;
			len = needed_joins.len();
			if needed_joins.is_empty() {
				break;
			}
			let needed_joins_iter = needed_joins.into_iter();
			needed_joins = vec![];
			needed_joins_iter.for_each(|(needed_index, join)| {
				if !join.needed_tables.iter().any(|needed_table_index| {
					!(&needed_index == needed_table_index
						|| requested_joins
							.iter()
							.any(|(requested_index, _)| needed_table_index == requested_index))
				}) {
					requested_joins.push((needed_index, join))
				} else {
					if len == len_last {
						// TODO
						panic!(
							"Impossible Join, table not present or tables require eachother: {:?}",
							join
						)
						// TODO: Handle
					}
					needed_joins.push((needed_index, join))
				}
			});
		}
		let columns = requested_joins
			.iter()
			.fold(vec![], |mut columns, (index, _)| {
				columns.extend(
					table_columns
						.get(*index)
						.expect("Something went very wrong")
						.clone(),
				);
				columns
			});

		let (constraint, mut index_filters) = PlannedRecipe::new_constraint(constraint, &columns)?;

		let mut joins = requested_joins
			.into_iter()
			.map(|(_, join)| {
				let index_filter = index_filters.remove(&join.table);
				JoinExecute::new(join, &columns, index_filter)
			})
			.collect::<Result<Vec<JoinExecute>>>()?;

		if let Some(first) = joins.first_mut() {
			first.set_first_table()
		}

		let include_table = joins.len() != 1;
		let select_items = select_items
			.into_iter()
			.enumerate()
			.map(|(index, select_item)| {
				Ok(match select_item {
					SelectItem::Recipe(meta_recipe, alias) => {
						let recipe = PlannedRecipe::new(meta_recipe, &columns)?;
						let label = alias
							.unwrap_or_else(|| recipe.get_label(index, include_table, &columns));
						vec![(recipe, label)]
					}
					SelectItem::Wildcard(specifier) => {
						let specified_table =
							specifier.and_then(|specifier| specifier.get(0).cloned());
						let matches_table = |column: &ColumnInfo| {
							specified_table
								.clone()
								.map(|specified_table| {
									column.table.name == specified_table
										|| column
											.table
											.alias
											.clone()
											.map(|alias| alias == specified_table)
											.unwrap_or(false)
								})
								.unwrap_or(true)
						};
						columns
							.iter()
							.enumerate()
							.filter_map(|(index, column)| {
								if matches_table(column) {
									Some((
										PlannedRecipe::of_index(index),
										if include_table {
											format!("{}.{}", column.table.name, column.name)
										} else {
											column.name.clone()
										},
									))
								} else {
									None
								}
							})
							.collect()
					}
				})
			})
			.collect::<Result<Vec<Vec<(PlannedRecipe, String)>>>>()? // TODO: Don't do this
			.into_iter()
			.reduce(|mut select_items, select_item_set| {
				select_items.extend(select_item_set);
				select_items
			})
			.ok_or(PlanError::UnreachableNoSelectItems)?;

		let (select_items, labels) = select_items.into_iter().unzip();

		let group_constraint = PlannedRecipe::new(group_constraint, &columns)?;
		let groups = groups
			.into_iter()
			.map(|group| PlannedRecipe::new(group, &columns))
			.collect::<Result<Vec<PlannedRecipe>>>()?;
		let order_by = Order::new(order_by, &columns)?;

		Ok(Plan {
			joins,
			select_items,
			constraint,
			groups,
			group_constraint,
			order_by,
			labels,
		})
	}
}