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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
use std::cell::RefCell;
use std::rc::Rc;
use anyhow::anyhow;
use postgres::Row;
use thiserror::Error;
use crate::common::types::ResultAnyError;
use crate::db::psql::connection::PsqlConnection;
use crate::db::psql::dto::*;
pub struct Query {
connection: Rc<RefCell<PsqlConnection>>,
}
#[derive(Error, Debug)]
pub enum QueryError {
#[error("Row with column {column} = {identifier:?} is not found in table {table_id}")]
RowNotFound {
table_id: String,
column: String,
identifier: String,
},
#[error("Too many rows returned({row_count}), expecting only {expected_row_count}")]
TooManyRows {
row_count: usize,
expected_row_count: usize,
},
}
pub struct FetchRowInput<'a> {
pub table_id: &'a PsqlTableIdentity,
pub column_name: &'a str,
pub column_value: &'a PsqlParamValue,
}
impl<'b> FetchRowInput<'b> {
pub fn psql_param_value<'a>(
column_value: String,
column: PsqlTableColumn,
) -> ResultAnyError<PsqlParamValue> {
let data_type: String = column.data_type.to_string();
let mut value: PsqlParamValue = Box::new(column_value.clone());
if data_type == "integer" {
let convert_column_value = column_value.clone().parse::<i32>().map_err(|err| {
return anyhow!(
"Cannot cast column '{}' of value {} to integer. Error: {}",
column.name,
column_value,
err
);
})?;
value = Box::new(convert_column_value);
} else if data_type == "uuid" {
let uuid = Uuid::from_str(&column_value)?;
value = Box::new(uuid);
}
return Ok(value);
}
}
impl Query {
fn find_rows(&mut self, input: &FetchRowInput) -> ResultAnyError<Vec<Row>> {
let query_str = format!(
"SELECT * FROM {} where {} = $1",
input.table_id, input.column_name
);
let mut connection = self.connection.borrow_mut();
let connection = connection.get();
let statement = connection.prepare(&query_str)?;
return connection
.query(&statement, &[input.column_value.as_ref()])
.map_err(anyhow::Error::from);
}
fn find_one_row(&mut self, input: &FetchRowInput) -> ResultAnyError<Option<Row>> {
let rows_result = self.find_rows(input);
return match rows_result {
Err(any) => Err(any),
Ok(mut rows) => {
if rows.len() > 1 {
return Err(anyhow!(QueryError::TooManyRows {
row_count: rows.len(),
expected_row_count: 1,
}));
}
if rows.len() == 0 {
return Ok(None);
}
return Ok(Some(rows.remove(0)));
}
};
}
pub fn get_column_metadata<'a>(
&mut self,
table_id: &PsqlTableIdentity,
column_name: &str,
) -> ResultAnyError<Row> {
let query_str =
"SELECT * FROM information_schema.columns where table_schema = $1 and table_name = $2 and column_name = $3";
let mut connection = self.connection.borrow_mut();
let connection = connection.get();
let statement = connection.prepare(&query_str)?;
return connection
.query_one(
&statement,
&[
&table_id.schema.to_string(),
&table_id.name.to_string(),
&column_name.to_string(),
],
)
.map_err(anyhow::Error::from);
}
}
#[cfg_attr(test, mockall::automock)]
pub trait TableMetadata {
fn get_column(
&self,
table_id: &PsqlTableIdentity,
column_name: &str,
) -> ResultAnyError<PsqlTableColumn>;
fn get_rows<'a>(
&self,
table: PsqlTable,
column_name: &str,
id: &PsqlParamValue,
) -> ResultAnyError<Vec<PsqlTableRow>>;
fn get_one_row(
&self,
table: &PsqlTable,
column_name: &str,
id: &str,
) -> ResultAnyError<PsqlTableRow>;
}
pub struct TableMetadataImpl {
query: RefCell<Query>,
}
impl TableMetadataImpl {
pub fn new(psql_connection: Rc<RefCell<PsqlConnection>>) -> TableMetadataImpl {
return TableMetadataImpl {
query: RefCell::new(Query {
connection: psql_connection,
}),
};
}
}
impl TableMetadata for TableMetadataImpl {
fn get_column(
&self,
table_id: &PsqlTableIdentity,
column_name: &str,
) -> ResultAnyError<PsqlTableColumn> {
let row = self
.query
.borrow_mut()
.get_column_metadata(table_id, column_name)?;
let column = PsqlTableColumn::new(column_name.to_string(), row.get("data_type"));
return Ok(column);
}
fn get_rows(
&self,
table: PsqlTable,
column_name: &str,
id: &PsqlParamValue,
) -> ResultAnyError<Vec<PsqlTableRow>> {
return self
.query
.borrow_mut()
.find_rows(&FetchRowInput {
table_id: &table.id,
column_name,
column_value: id,
})
.map(|rows| {
return rows
.into_iter()
.map(|inner_row| {
return PsqlTableRow::new(table.clone(), Rc::new(inner_row));
})
.collect();
});
}
fn get_one_row<'a>(
&self,
table: &PsqlTable,
column_name: &str,
id: &str,
) -> ResultAnyError<PsqlTableRow> {
let column = self.get_column(&table.id, column_name)?;
let id: PsqlParamValue = FetchRowInput::psql_param_value(id.to_string(), column)?;
let row = self.query.borrow_mut().find_one_row(&FetchRowInput {
table_id: &table.id,
column_name,
column_value: &id,
})?;
return row
.ok_or_else(|| {
anyhow!(QueryError::RowNotFound {
table_id: format!("{:#?}", table.id),
column: column_name.into(),
identifier: format!("{:#?}", id),
})
})
.map(|inner_row| {
return PsqlTableRow::new(table.clone(), Rc::new(inner_row));
});
}
}