1use std::sync::{Arc, Mutex};
2
3use crate::driver;
4
5use super::{driver::AsyncDriver, ConnectionPool, Rows};
6
7use anyhow::Result;
8
9pub type Argument = driver::Argument;
11
12pub type ExecResult = driver::ExecResult;
14
15pub type ArgName = driver::ArgName;
17
18pub type ArgValue = driver::ArgValue;
20
21pub type Column = driver::Column;
23
24pub type ColumnType = driver::ColumnType;
26
27#[allow(dead_code)]
28struct Inner<DB>
29where
30 DB: ConnectionPool + Sync + Send,
31{
32 db: Option<DB>,
33 conn: Option<Box<dyn driver::Connection>>,
34 stmt: Option<Box<dyn driver::Statement>>,
35}
36impl<DB> Drop for Inner<DB>
38where
39 DB: ConnectionPool + Sync + Send,
40{
41 fn drop(&mut self) {
42 if let Some(conn) = self.conn.take() {
43 if let Some(db) = self.db.take() {
44 drop(self.stmt.take().unwrap());
45 db.release_conn(conn);
46 }
47 }
48 }
49}
50
51#[allow(dead_code)]
53#[derive(Clone)]
54pub struct Statement<DB>
55where
56 DB: ConnectionPool + Sync + Send,
57{
58 inner: Arc<Mutex<Inner<DB>>>,
59}
60
61impl<DB> Statement<DB>
62where
63 DB: ConnectionPool + Sync + Send + Clone,
64{
65 pub fn new(
66 db: Option<DB>,
67 conn: Option<Box<dyn driver::Connection>>,
68 stmt: Box<dyn driver::Statement>,
69 ) -> Self {
70 Self {
71 inner: Arc::new(Mutex::new(Inner {
72 db,
73 conn,
74 stmt: Some(stmt),
75 })),
76 }
77 }
78
79 pub async fn num_input(&self) -> Result<Option<usize>> {
80 let async_driver = AsyncDriver::new();
81
82 self.inner
83 .lock()
84 .unwrap()
85 .stmt
86 .as_ref()
87 .unwrap()
88 .num_input(async_driver.callback());
89
90 async_driver.await
91 }
92
93 pub async fn execute(&mut self, args: Vec<Argument>) -> Result<ExecResult> {
94 let async_driver = AsyncDriver::new();
95
96 self.inner
97 .lock()
98 .unwrap()
99 .stmt
100 .as_mut()
101 .unwrap()
102 .execute(args, async_driver.callback());
103
104 async_driver.await
105 }
106
107 pub async fn query(&mut self, args: Vec<Argument>) -> Result<Rows<DB>> {
108 let async_driver = AsyncDriver::new();
109
110 self.inner
111 .lock()
112 .unwrap()
113 .stmt
114 .as_mut()
115 .unwrap()
116 .query(args, async_driver.callback());
117
118 Ok(Rows::new(async_driver.await?, self.clone()))
119 }
120}