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
use {
	super::{columns_to_positions, validate},
	crate::{
		data::Schema,
		executor::types::{ColumnInfo, Row as VecRow},
		Column, ComplexTableName, ExecuteError, Glue, MetaRecipe, Payload, PlannedRecipe,
		RecipeUtilities, Result, Row, Value,
	},
	sqlparser::ast::{Assignment, Expr, TableFactor, TableWithJoins},
};

impl Glue {
	pub async fn update(
		&mut self,
		table: &TableWithJoins,
		selection: &Option<Expr>,
		assignments: &[Assignment],
	) -> Result<Payload> {
		// TODO: Complex updates (joins)
		let ComplexTableName {
			name: table,
			database,
			..
		} = match &table.relation {
			TableFactor::Table { name, .. } => name.try_into(),
			_ => Err(ExecuteError::QueryNotSupported.into()),
		}?;
		let Schema {
			column_defs,
			indexes,
			..
		} = self
			.get_database(&database)?
			.fetch_schema(&table)
			.await?
			.ok_or(ExecuteError::TableNotExists)?;

		let columns = column_defs
			.clone()
			.into_iter()
			.map(|Column { name, .. }| ColumnInfo::of_name(name))
			.map(|mut col| {
				col.table.name = table.clone();
				col
			})
			.collect::<Vec<ColumnInfo>>();

		let filter = selection
			.clone()
			.map(|selection| {
				PlannedRecipe::new(
					MetaRecipe::new(selection)?.simplify_by_context(&*self.get_context()?)?,
					&columns,
				)
			})
			.unwrap_or(Ok(PlannedRecipe::TRUE))?;

		let assignments = assignments
			.iter()
			.map(|assignment| {
				let Assignment { id, value } = assignment;
				let column_compare = id
					.clone()
					.into_iter()
					.map(|component| component.value)
					.collect();
				let index = columns
					.iter()
					.position(|column| column == &column_compare)
					.ok_or(ExecuteError::ColumnNotFound)?;
				let recipe = PlannedRecipe::new(
					MetaRecipe::new(value.clone())?.simplify_by_context(&*self.get_context()?)?,
					&columns,
				)?;
				Ok((index, recipe))
			})
			.collect::<Result<Vec<(usize, PlannedRecipe)>>>()?;

		let keyed_rows = self
			.get_database(&None)?
			.scan_data(&table)
			.await?
			.into_iter()
			.filter_map(|(key, Row(row))| match filter.confirm_constraint(&row) {
				Ok(false) => None,
				Err(error) => Some(Err(error)),
				Ok(true) => Some(
					row.iter()
						.enumerate()
						.map(|(index, old_value)| {
							assignments
								.iter()
								.find_map(|(assignment_index, assignment_recipe)| {
									if assignment_index == &index {
										Some(
											assignment_recipe
												.clone()
												.simplify_by_row(&row)
												.and_then(|recipe| recipe.confirm()),
										)
									} else {
										None
									}
								})
								.unwrap_or(Ok(old_value.clone()))
						})
						.collect::<Result<VecRow>>()
						.map(|row| (key, row)),
				),
			})
			.collect::<Result<Vec<(Value, VecRow)>>>()?;

		let column_positions = columns_to_positions(&column_defs, &[])?;
		let (keys, mut rows): (Vec<Value>, Vec<VecRow>) = keyed_rows.into_iter().unzip();
		validate(&column_defs, &column_positions, &mut rows)?;

		let table = table.as_str();
		let mut rows: Vec<Row> = rows.into_iter().map(Row).collect();
		#[cfg(feature = "auto-increment")]
		self.auto_increment(&database, table, &column_defs, &mut rows)
			.await?;
		/*self.validate_unique(&database, table, &column_defs, &rows, Some(&keys))
		.await?;*/
		let keyed_rows: Vec<(Value, Row)> = keys.into_iter().zip(rows).collect();
		let num_rows = keyed_rows.len();

		let database = &mut **self.get_mut_database(&database)?;

		let result = database
			.update_data(table, keyed_rows)
			.await
			.map(|_| Payload::Update(num_rows))?;

		for index in indexes.iter() {
			index.reset(database, table, &column_defs).await?; // TODO: Not this; optimise
		}
		Ok(result)
	}
}