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
use futures_core::future::BoxFuture;

use libsqlite3_sys::sqlite3_changes;

use crate::cursor::Cursor;
use crate::describe::{Column, Describe};
use crate::executor::{Execute, Executor, RefExecutor};
use crate::sqlite::cursor::SqliteCursor;
use crate::sqlite::statement::{Statement, Step};
use crate::sqlite::type_info::SqliteType;
use crate::sqlite::{Sqlite, SqliteConnection, SqliteTypeInfo};

impl SqliteConnection {
    pub(super) fn prepare(
        &mut self,
        query: &mut &str,
        persistent: bool,
    ) -> crate::Result<Option<usize>> {
        // TODO: Revisit statement caching and allow cache expiration by using a

        //       generational index


        if !persistent {
            // A non-persistent query will be immediately prepared and returned,

            // regardless of the current state of the cache

            self.statement = Some(Statement::new(self, query, false)?);
            return Ok(None);
        }

        if let Some(key) = self.statement_by_query.get(&**query) {
            let statement = &mut self.statements[*key];

            // Adjust the passed in query string as if [string3_prepare]

            // did the tail parsing

            *query = &query[statement.tail..];

            // As this statement has very likely been used before, we reset

            // it to clear the bindings and its program state

            statement.reset();

            return Ok(Some(*key));
        }

        // Prepare a new statement object; ensuring to tell SQLite that this will be stored

        // for a "long" time and re-used multiple times


        let query_key = query.to_owned();
        let statement = Statement::new(self, query, true)?;

        let key = self.statements.len();

        self.statement_by_query.insert(query_key, key);
        self.statements.push(statement);

        Ok(Some(key))
    }

    // This is used for [affected_rows] in the public API.

    fn changes(&mut self) -> u64 {
        // Returns the number of rows modified, inserted or deleted by the most recently

        // completed INSERT, UPDATE or DELETE statement.


        // https://www.sqlite.org/c3ref/changes.html

        let changes = unsafe { sqlite3_changes(self.handle()) };
        changes as u64
    }

    #[inline]
    pub(super) fn statement(&self, key: Option<usize>) -> &Statement {
        match key {
            Some(key) => &self.statements[key],
            None => self.statement.as_ref().unwrap(),
        }
    }

    #[inline]
    pub(super) fn statement_mut(&mut self, key: Option<usize>) -> &mut Statement {
        match key {
            Some(key) => &mut self.statements[key],
            None => self.statement.as_mut().unwrap(),
        }
    }
}

impl Executor for SqliteConnection {
    type Database = Sqlite;

    fn execute<'e, 'q: 'e, 'c: 'e, E: 'e>(
        &'c mut self,
        query: E,
    ) -> BoxFuture<'e, crate::Result<u64>>
    where
        E: Execute<'q, Self::Database>,
    {
        let (mut query, mut arguments) = query.into_parts();

        Box::pin(async move {
            loop {
                let key = self.prepare(&mut query, arguments.is_some())?;
                let statement = self.statement_mut(key);

                if let Some(arguments) = &mut arguments {
                    statement.bind(arguments)?;
                }

                while let Step::Row = statement.step().await? {
                    // We only care about the rows modified; ignore

                }

                if query.is_empty() {
                    break;
                }
            }

            Ok(self.changes())
        })
    }

    fn cursor<'q, E>(&mut self, query: E) -> SqliteCursor<'_, 'q>
    where
        E: Execute<'q, Self::Database>,
    {
        SqliteCursor::from_connection(self, query)
    }

    #[doc(hidden)]
    fn describe<'e, 'q, E: 'e>(
        &'e mut self,
        query: E,
    ) -> BoxFuture<'e, crate::Result<Describe<Self::Database>>>
    where
        E: Execute<'q, Self::Database>,
    {
        Box::pin(async move {
            let (mut query, _) = query.into_parts();
            let key = self.prepare(&mut query, false)?;
            let statement = self.statement_mut(key);

            // First let's attempt to describe what we can about parameter types

            // Which happens to just be the count, heh

            let num_params = statement.params();
            let params = vec![None; num_params].into_boxed_slice();

            // Next, collect (return) column types and names

            let num_columns = statement.column_count();
            let mut columns = Vec::with_capacity(num_columns);
            for i in 0..num_columns {
                let name = statement.column_name(i).to_owned();
                let decl = statement.column_decltype(i);

                let r#type = match decl {
                    None => None,
                    Some(decl) => match &*decl.to_ascii_lowercase() {
                        "bool" | "boolean" => Some(SqliteType::Boolean),
                        "clob" | "text" => Some(SqliteType::Text),
                        "blob" => Some(SqliteType::Blob),
                        "real" | "double" | "double precision" | "float" => Some(SqliteType::Float),
                        decl @ _ if decl.contains("int") => Some(SqliteType::Integer),
                        decl @ _ if decl.contains("char") => Some(SqliteType::Text),
                        _ => None,
                    },
                };

                columns.push(Column {
                    name: Some(name.into()),
                    non_null: statement.column_not_null(i)?,
                    table_id: None,
                    type_info: r#type.map(|r#type| SqliteTypeInfo {
                        r#type,
                        affinity: None,
                    }),
                })
            }

            Ok(Describe {
                param_types: params,
                result_columns: columns.into_boxed_slice(),
            })
        })
    }
}

impl<'e> RefExecutor<'e> for &'e mut SqliteConnection {
    type Database = Sqlite;

    fn fetch_by_ref<'q, E>(self, query: E) -> SqliteCursor<'e, 'q>
    where
        E: Execute<'q, Self::Database>,
    {
        SqliteCursor::from_connection(self, query)
    }
}