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
use {
	super::types::get_first_name,
	crate::{parse_sql::Query, Glue, Result, Row},
	serde::Serialize,
	sqlparser::ast::{ObjectType, Statement},
	thiserror::Error as ThisError,
};

#[derive(ThisError, Serialize, Debug, PartialEq)]
pub enum ExecuteError {
	#[error("query not supported")]
	QueryNotSupported,

	#[error("SET does not currently support columns, aggregates or subqueries")]
	MissingComponentsForSet,

	#[error("unsupported insert value type: {0}")]
	UnreachableUnsupportedInsertValueType(String),

	#[error("object not recognised")]
	ObjectNotRecognised,
	#[error("unimplemented")]
	Unimplemented,
	#[error("database already exists")]
	DatabaseExists(String),
	#[error("invalid file location")]
	InvalidFileLocation,
	#[error("invalid database location")]
	InvalidDatabaseLocation,

	#[error("table does not exist")]
	TableNotExists,

	#[error("column could not be found")]
	ColumnNotFound,
}

#[derive(Serialize, Debug, PartialEq)]
pub enum Payload {
	Success,
	Create,
	Insert(usize),
	Select {
		labels: Vec<String>,
		rows: Vec<Row>,
	},
	Delete(usize),
	Update(usize),
	DropTable,
	#[cfg(feature = "alter-table")]
	AlterTable,
	TruncateTable,
}

impl Glue {
	pub async fn execute_query(&mut self, statement: &Query) -> Result<Payload> {
		let Query(statement) = statement;

		match statement {
			Statement::CreateDatabase {
				db_name,
				if_not_exists,
				location,
				..
			} => {
				if !self.try_extend_from_path(
					db_name.0[0].value.clone(),
					location
						.clone()
						.ok_or(ExecuteError::InvalidDatabaseLocation)?,
				)? && !if_not_exists
				{
					Err(ExecuteError::DatabaseExists(db_name.0[0].value.clone()).into())
				} else {
					Ok(Payload::Success)
				}
			}
			//- Modification
			//-- Tables
			Statement::CreateTable {
				name,
				columns,
				if_not_exists,
				..
			} => self
				.create_table(name, columns, *if_not_exists)
				.await
				.map(|_| Payload::Create),
			Statement::CreateView {
				name,
				query,
				or_replace,
				..
			} => self
				.create_view(name, query, *or_replace)
				.await
				.map(|_| Payload::Create),
			Statement::Drop {
				object_type,
				names,
				if_exists,
				..
			} => match object_type {
				ObjectType::Schema => {
					// Schema for now // TODO: sqlparser-rs#454
					if !self.reduce(&get_first_name(names)?) && !if_exists {
						Err(ExecuteError::ObjectNotRecognised.into())
					} else {
						Ok(Payload::Success)
					}
				}
				object_type => self
					.drop(object_type, names, *if_exists)
					.await
					.map(|_| Payload::DropTable),
			},
			#[cfg(feature = "alter-table")]
			Statement::AlterTable { name, operation } => self
				.alter_table(name, operation)
				.await
				.map(|_| Payload::AlterTable),
			Statement::Truncate { table_name, .. } => self
				.truncate(table_name)
				.await
				.map(|_| Payload::TruncateTable),
			Statement::CreateIndex {
				name,
				table_name,
				columns,
				unique,
				if_not_exists,
			} => self
				.create_index(table_name, name, columns, *unique, *if_not_exists)
				.await
				.map(|_| Payload::Create),

			//-- Rows
			Statement::Insert {
				table_name,
				columns,
				source,
				..
			} => self.insert(table_name, columns, source, false).await,
			Statement::Update {
				table,
				selection,
				assignments,
				// TODO
				from: _,
			} => self.update(table, selection, assignments).await,
			Statement::Delete {
				table_name,
				selection,
			} => self.delete(table_name, selection).await,

			//- Selection
			Statement::Query(query_value) => {
				let result = self.query(*query_value.clone()).await?;
				let (labels, rows) = result;
				let rows = rows.into_iter().map(Row).collect(); // I don't like this. TODO
				let payload = Payload::Select { labels, rows };
				Ok(payload)
			}

			//- Context
			Statement::SetVariable {
				variable, value, ..
			} => self
				.set_variable(variable, value)
				.await
				.map(|_| Payload::Success),

			Statement::ExplainTable { table_name, .. } => self.explain(table_name).await,

			Statement::Execute { name, parameters } => self.procedure(name, parameters).await,
			_ => Err(ExecuteError::QueryNotSupported.into()),
		}
	}
}