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
use crate::query::SqliteQuery;
use crate::type_info::Type;
use crate::{SqliteConnectOptions, SqliteConnection};
use either::Either;
use futures_core::future::BoxFuture;
use futures_core::stream::BoxStream;
use futures_util::{StreamExt, TryStreamExt};
use log::LevelFilter;
use rbdc::db::{Connection, ExecResult, Row};
use rbdc::error::Error;
use rbs::Value;
use std::fmt::Write;
use std::time::Duration;

impl SqliteConnectOptions {
    pub fn connect(&self) -> BoxFuture<'_, Result<SqliteConnection, Error>> {
        Box::pin(async move {
            let mut conn = SqliteConnection::establish(self).await?;

            // send an initial sql statement comprised of options
            let mut init = String::new();

            // This is a special case for sqlcipher. When the `key` pragma
            // is set, we have to make sure it's executed first in order.
            if let Some(pragma_key_password) = self.pragmas.get("key") {
                write!(init, "PRAGMA key = {}; ", pragma_key_password).ok();
            }

            for (key, value) in &self.pragmas {
                // Since we've already written the possible `key` pragma
                // above, we shall skip it now.
                if key == "key" {
                    continue;
                }
                write!(init, "PRAGMA {} = {}; ", key, value).ok();
            }

            conn.exec(&*init, vec![]).await?;

            if !self.collations.is_empty() {
                let mut locked = conn.lock_handle().await?;

                for collation in &self.collations {
                    collation.create(&mut locked.guard.handle)?;
                }
            }

            Ok(conn)
        })
    }
}

impl Connection for SqliteConnection {
    fn get_rows(
        &mut self,
        sql: &str,
        params: Vec<Value>,
    ) -> BoxFuture<Result<Vec<Box<dyn Row>>, Error>> {
        let sql = sql.to_owned();
        Box::pin(async move {
            if params.len() == 0 {
                let mut many = self.fetch_many(SqliteQuery {
                    statement: Either::Left(sql),
                    arguments: params,
                    persistent: false,
                });
                let mut data: Vec<Box<dyn Row>> = Vec::new();
                while let Some(item) = many.next().await {
                    match item? {
                        Either::Left(l) => {}
                        Either::Right(r) => {
                            data.push(Box::new(r));
                        }
                    }
                }
                return Ok(data);
            } else {
                let stmt = self.prepare_with(&sql, &[]).await?;
                let mut many = self.fetch_many(SqliteQuery {
                    statement: Either::Right(stmt),
                    arguments: params,
                    persistent: true,
                });
                let mut data: Vec<Box<dyn Row>> = Vec::new();
                while let Some(item) = many.next().await {
                    match item? {
                        Either::Left(l) => {}
                        Either::Right(r) => {
                            data.push(Box::new(r));
                        }
                    }
                }
                return Ok(data);
            }
        })
    }

    fn exec(&mut self, sql: &str, params: Vec<Value>) -> BoxFuture<Result<ExecResult, Error>> {
        let sql = sql.to_owned();
        Box::pin(async move {
            if params.len() == 0 {
                let mut many = self.fetch_many(SqliteQuery {
                    statement: Either::Left(sql),
                    arguments: params,
                    persistent: false,
                });
                while let Some(item) = many.next().await {
                    match item? {
                        Either::Left(l) => {
                            return Ok(ExecResult {
                                rows_affected: l.rows_affected(),
                                last_insert_id: Value::U64(l.last_insert_rowid as u64),
                            });
                        }
                        Either::Right(r) => {}
                    }
                }
                return Ok(ExecResult {
                    rows_affected: 0,
                    last_insert_id: Value::Null,
                });
            } else {
                let mut type_info = Vec::with_capacity(params.len());
                for x in &params {
                    type_info.push(x.type_info());
                }
                let stmt = self.prepare_with(&sql, &type_info).await?;
                let mut many = self.fetch_many(SqliteQuery {
                    statement: Either::Right(stmt),
                    arguments: params,
                    persistent: true,
                });
                while let Some(item) = many.next().await {
                    match item? {
                        Either::Left(l) => {
                            return Ok(ExecResult {
                                rows_affected: l.rows_affected(),
                                last_insert_id: Value::U64(l.last_insert_rowid as u64),
                            });
                        }
                        Either::Right(r) => {}
                    }
                }
                return Ok(ExecResult {
                    rows_affected: 0,
                    last_insert_id: Value::Null,
                });
            }
        })
    }

    fn close(&mut self) -> BoxFuture<'static, Result<(), Error>> {
        let c = self.close();
        Box::pin(async move { c.await })
    }

    fn ping(&mut self) -> BoxFuture<Result<(), Error>> {
        Box::pin(async move {
            self.worker
                .oneshot_cmd(|tx| crate::connection::Command::Ping { tx })
                .await?;
            Ok(())
        })
    }
}