typed_statements.rs

 1use anyhow::{Context, Result};
 2
 3use crate::{
 4    bindable::{Bind, Column},
 5    connection::Connection,
 6    statement::Statement,
 7};
 8
 9impl Connection {
10    pub fn exec<'a>(&'a self, query: &str) -> Result<impl 'a + FnMut() -> Result<()>> {
11        let mut statement = Statement::prepare(self, query)?;
12        Ok(move || statement.exec())
13    }
14
15    pub fn exec_bound<'a, B: Bind>(
16        &'a self,
17        query: &str,
18    ) -> Result<impl 'a + FnMut(B) -> Result<()>> {
19        let mut statement = Statement::prepare(self, query)?;
20        Ok(move |bindings| statement.with_bindings(bindings)?.exec())
21    }
22
23    pub fn select<'a, C: Column>(
24        &'a self,
25        query: &str,
26    ) -> Result<impl 'a + FnMut() -> Result<Vec<C>>> {
27        let mut statement = Statement::prepare(self, query)?;
28        Ok(move || statement.rows::<C>())
29    }
30
31    pub fn select_bound<'a, B: Bind, C: Column>(
32        &'a self,
33        query: &str,
34    ) -> Result<impl 'a + FnMut(B) -> Result<Vec<C>>> {
35        let mut statement = Statement::prepare(self, query)?;
36        Ok(move |bindings| statement.with_bindings(bindings)?.rows::<C>())
37    }
38
39    pub fn select_row<'a, C: Column>(
40        &'a self,
41        query: &str,
42    ) -> Result<impl 'a + FnMut() -> Result<Option<C>>> {
43        let mut statement = Statement::prepare(self, query)?;
44        Ok(move || statement.maybe_row::<C>())
45    }
46
47    pub fn select_row_bound<'a, B: Bind, C: Column>(
48        &'a self,
49        query: &str,
50    ) -> Result<impl 'a + FnMut(B) -> Result<Option<C>>> {
51        let mut statement = Statement::prepare(self, query)?;
52        Ok(move |bindings| {
53            statement
54                .with_bindings(bindings)
55                .context("Bindings failed")?
56                .maybe_row::<C>()
57                .context("Maybe row failed")
58        })
59    }
60}