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
use std::marker::PhantomData;
use std::path::Path;

use tokio::sync::oneshot;

use super::connection::{ConnectionHandle, ConnectionTask};
use super::query::QueryHandle;
use super::transaction::TransactionHandle;

pub type Error = rusqlite::Error;

pub type Value = rusqlite::types::Value;

#[derive(Clone, Debug)]
pub struct Row {
    pub(super) values: Vec<Value>,
}

impl Row {
    pub fn values(&self) -> &[Value] {
        &self.values
    }

    pub fn into_values(self) -> Vec<Value> {
        self.values
    }
}

/// A result of executing the statement without the resulting query rows.
#[derive(Default, Clone)]
pub struct Status {
    pub(super) rows_affected: usize,
    pub(super) last_insert_id: Option<i64>,
}

impl Status {
    pub fn rows_affected(&self) -> usize {
        self.rows_affected
    }

    pub fn last_insert_id(&self) -> Option<i64> {
        self.last_insert_id
    }
}

/// An asynchronous stream of resulting query rows.
pub struct Rows<'a> {
    handle: QueryHandle,
    _phantom: PhantomData<&'a ()>,
}

impl<'a> Rows<'a> {
    pub fn columns(&self) -> &[String] {
        self.handle.columns()
    }

    pub async fn next(&mut self) -> Option<Result<Row, Error>> {
        self.handle.next().await
    }
}

impl<'a> Drop for Rows<'a> {
    fn drop(&mut self) {}
}

/// An asynchronous SQLite database transaction.
pub struct Transaction<'a> {
    tx: TransactionHandle,
    _phantom: PhantomData<&'a ()>,
}

impl<'a> Transaction<'a> {
    /// Consumes the transaction, committing all changes made within it.
    pub async fn commit(mut self) -> Result<(), Error> {
        self.tx.commit().await
    }

    /// Rolls the transaction back, discarding all changes made within it.
    pub async fn rollback(mut self) -> Result<(), Error> {
        self.tx.rollback().await
    }

    /// Executes a statement that does not return the resulting rows.
    ///
    /// Returns an error if the query returns resulting rows.
    pub async fn execute(&mut self, statement: &str, arguments: &[Value]) -> Result<Status, Error> {
        self.tx
            .execute(statement.to_owned(), arguments.to_owned())
            .await
    }

    /// Executes a statement that returns the resulting query rows.
    pub async fn query<S, A>(&mut self, statement: S, arguments: A) -> Result<Rows, Error>
    where
        S: Into<String>,
        A: Into<Vec<Value>>,
    {
        let handle = self.tx.query(statement.into(), arguments.into()).await?;
        Ok(Rows {
            handle,
            _phantom: PhantomData,
        })
    }

    /// Executes a statement that returns zero or one resulting query row.
    ///
    /// Returns an error if the query returns more than one row.
    pub async fn query_row<S, A>(
        &mut self,
        statement: S,
        arguments: A,
    ) -> Result<Option<Row>, Error>
    where
        S: Into<String>,
        A: Into<Vec<Value>>,
    {
        let mut rows = self.query(statement, arguments).await?;
        let row = match rows.next().await {
            Some(v) => v?,
            None => return Ok(None),
        };
        if let Some(_) = rows.next().await {
            return Err(Error::QueryReturnedNoRows);
        }
        Ok(Some(row))
    }
}

impl<'a> Drop for Transaction<'a> {
    fn drop(&mut self) {}
}

/// An asynchronous SQLite client.
pub struct Connection {
    tx: Option<ConnectionHandle>,
    handle: Option<tokio::task::JoinHandle<()>>,
}

impl Connection {
    /// Opens a new connection to a SQLite database.
    pub async fn open<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
        let task = ConnectionTask::new(path.as_ref().to_owned());
        let (tx, rx) = oneshot::channel();
        let handle = tokio::task::spawn_blocking(|| task.blocking_run(tx));
        Ok(Connection {
            tx: Some(rx.await.unwrap()?),
            handle: Some(handle),
        })
    }

    /// Begins new transaction.
    pub async fn transaction(&mut self) -> Result<Transaction, Error> {
        let tx = self.tx.as_mut().unwrap().transaction().await?;
        Ok(Transaction {
            tx,
            _phantom: PhantomData,
        })
    }

    /// Executes a statement that does not return the resulting rows.
    ///
    /// Returns an error if the query returns resulting rows.
    pub async fn execute<S, A>(&mut self, statement: S, arguments: A) -> Result<Status, Error>
    where
        S: Into<String>,
        A: Into<Vec<Value>>,
    {
        self.tx
            .as_mut()
            .unwrap()
            .execute(statement.into(), arguments.into())
            .await
    }

    /// Executes a statement that returns the resulting query rows.
    pub async fn query<S, A>(&mut self, statement: S, arguments: A) -> Result<Rows, Error>
    where
        S: Into<String>,
        A: Into<Vec<Value>>,
    {
        let handle = self
            .tx
            .as_mut()
            .unwrap()
            .query(statement.into(), arguments.into())
            .await?;
        Ok(Rows {
            handle,
            _phantom: PhantomData,
        })
    }

    /// Executes a statement that returns zero or one resulting query row.
    ///
    /// Returns an error if the query returns more than one row.
    pub async fn query_row<S, A>(
        &mut self,
        statement: S,
        arguments: A,
    ) -> Result<Option<Row>, Error>
    where
        S: Into<String>,
        A: Into<Vec<Value>>,
    {
        let mut rows = self.query(statement, arguments).await?;
        let row = match rows.next().await {
            Some(v) => v?,
            None => return Ok(None),
        };
        if let Some(_) = rows.next().await {
            return Err(Error::QueryReturnedNoRows);
        }
        Ok(Some(row))
    }
}

impl Drop for Connection {
    fn drop(&mut self) {
        drop(self.tx.take());
        if let Some(handle) = self.handle.take() {
            let _ =
                tokio::task::block_in_place(|| tokio::runtime::Handle::current().block_on(handle));
        };
    }
}