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
use crate::{
    DBPlatform,
    Dao,
    DataError,
    DbError,
    Rows,
    Value,
};

/// an interface executing sql statement and getting the results as generic DAO values
/// without any further conversion.
pub struct DaoManager(pub DBPlatform);

impl DaoManager {
    pub fn begin_transaction(&mut self) -> Result<(), DbError> { self.0.begin_transaction() }

    pub fn commit_transaction(&mut self) -> Result<(), DbError> { self.0.commit_transaction() }

    pub fn rollback_transaction(&mut self) -> Result<(), DbError> { self.0.rollback_transaction() }

    pub fn execute_sql_with_return(
        &mut self,
        sql: &str,
        params: &[&Value],
    ) -> Result<Rows, DbError> {
        let rows = self.0.execute_sql_with_return(sql, params)?;
        Ok(rows)
    }

    pub fn execute_sql_with_records_return(
        &mut self,
        sql: &str,
        params: &[&Value],
    ) -> Result<Vec<Dao>, DbError> {
        let rows = self.0.execute_sql_with_return(sql, params)?;
        let daos: Vec<Dao> = rows.iter().collect();
        Ok(daos)
    }

    pub fn execute_sql_with_one_return(
        &mut self,
        sql: &str,
        params: &[&Value],
    ) -> Result<Dao, DbError> {
        let record: Result<Option<Dao>, DbError> =
            self.execute_sql_with_maybe_one_return(sql, params);
        match record {
            Ok(record) => {
                match record {
                    Some(record) => Ok(record),
                    None => Err(DbError::DataError(DataError::ZeroRecordReturned)),
                }
            }
            Err(e) => Err(e),
        }
    }

    pub fn execute_sql_with_maybe_one_return(
        &mut self,
        sql: &str,
        params: &[&Value],
    ) -> Result<Option<Dao>, DbError> {
        let result: Result<Vec<Dao>, DbError> = self.execute_sql_with_records_return(sql, params);
        match result {
            Ok(mut result) => {
                match result.len() {
                    0 => Ok(None),
                    1 => Ok(Some(result.remove(0))),
                    _ => Err(DbError::DataError(DataError::MoreThan1RecordReturned)),
                }
            }
            Err(e) => Err(e),
        }
    }
}