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
use {
	super::join::JoinManual,
	crate::{
		executor::{
			types::{Alias, ObjectName},
			MetaRecipe,
		},
		Glue, Result,
	},
	serde::Serialize,
	sqlparser::ast::{Expr, Ident, Select, SelectItem as SelectItemAst},
	std::fmt::Debug,
	thiserror::Error as ThisError,
};

#[derive(ThisError, Serialize, Debug, PartialEq)]
pub enum ManualError {
	#[error("subqueries are not yet supported")]
	UnimplementedSubquery,

	#[error("this should be impossible, please report")]
	UncaughtASTError(String),

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

pub struct Manual {
	pub joins: Vec<JoinManual>,
	pub select_items: Vec<SelectItem>,
	pub constraint: MetaRecipe,
	pub group_constraint: MetaRecipe,
	pub groups: Vec<MetaRecipe>,
}
pub enum SelectItem {
	Recipe(MetaRecipe, Alias),
	Wildcard(Option<ObjectName>),
}

impl Manual {
	pub fn new(glue: &Glue, select: Select) -> Result<Self> {
		let Select {
			projection,
			from,
			selection,
			group_by,
			having,
			// TODO (below)
			distinct: _,
			top: _,
			lateral_views: _,
			cluster_by: _,
			distribute_by: _,
			sort_by: _,
			into: _,
		} = select;

		let constraint = selection
			.map(|selection| {
				MetaRecipe::new(selection)?.simplify_by_context(&glue.get_context().unwrap())
			})
			.unwrap_or(Ok(MetaRecipe::TRUE))?;

		let group_constraint = having
			.map(|having| {
				MetaRecipe::new(having)?.simplify_by_context(&glue.get_context().unwrap())
			})
			.unwrap_or(Ok(MetaRecipe::TRUE))?;

		let groups = group_by
			.into_iter()
			.map(|expression| {
				MetaRecipe::new(expression)?.simplify_by_context(&glue.get_context().unwrap())
			})
			.collect::<Result<Vec<MetaRecipe>>>()?;

		let (select_items, _subqueries): (Vec<SelectItem>, Vec<Vec<JoinManual>>) = projection
			.into_iter()
			.map(|select_item| convert_select_item(glue, select_item))
			.collect::<Result<Vec<(SelectItem, Vec<JoinManual>)>>>()?
			.into_iter()
			.unzip();

		let joins = from
			.into_iter()
			.map(|from| {
				let main = JoinManual::new_implicit_join(from.relation)?;
				let mut joins = from
					.joins
					.into_iter()
					.map(|join| JoinManual::new(join, &glue.get_context().unwrap()))
					.collect::<Result<Vec<JoinManual>>>()?;
				joins.push(main);
				Ok(joins)
			})
			.collect::<Result<Vec<Vec<JoinManual>>>>()?
			.into_iter()
			.reduce(|mut all_joins, joins| {
				all_joins.extend(joins);
				all_joins
			})
			.ok_or_else(|| ManualError::UncaughtASTError(String::from("No tables")))?;

		Ok(Manual {
			joins,
			select_items,
			constraint,
			group_constraint,
			groups,
		})
	}
}

fn identifier_into_object_name(identifier: Vec<Ident>) -> ObjectName {
	identifier
		.into_iter()
		.map(|identifier| identifier.value)
		.collect()
}

fn convert_select_item(
	glue: &Glue,
	select_item: SelectItemAst,
) -> Result<(SelectItem, Vec<JoinManual>)> {
	Ok(match select_item {
		SelectItemAst::UnnamedExpr(_) | SelectItemAst::ExprWithAlias { .. } => {
			let (expression, alias) = match select_item {
				SelectItemAst::UnnamedExpr(expression) => {
					let alias = if let Expr::Identifier(identifier) = expression.clone() {
						Some(identifier.value)
					} else {
						None
					};
					(expression, alias)
				}
				SelectItemAst::ExprWithAlias { expr, alias } => (expr, Some(alias.value)),
				_ => unreachable!(),
			};
			let recipe =
				MetaRecipe::new(expression)?.simplify_by_context(&glue.get_context().unwrap())?;
			let subqueries = recipe.meta.subqueries.clone();
			(SelectItem::Recipe(recipe, alias), subqueries)
		}
		SelectItemAst::Wildcard => (SelectItem::Wildcard(None), vec![]),
		SelectItemAst::QualifiedWildcard(qualifier) => (
			SelectItem::Wildcard(Some(identifier_into_object_name(qualifier.0))),
			vec![],
		),
	})
}