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
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;

use std::ops::Deref;

use rusqlite::*;

use thread_local::ThreadLocal;

static COUNTER: AtomicU64 = AtomicU64::new(0u64);

pub fn open_shared(name: &str) -> Result<Connection> {
    let uri = format!("file:{}?mode=memory&cache=shared", name);
    Connection::open(uri)
}

pub fn new_shared() -> Result<Connection> {
    open_shared(&format!(
        "shared_{}",
        COUNTER.fetch_add(1u64, Ordering::AcqRel)
    ))
}

pub struct SyncSqliteConnection {
    connection: ThreadLocal<Connection>,
    name: String,
}

impl SyncSqliteConnection {
    pub fn new() -> Result<Self> {
        let name = format!("shared_{}", COUNTER.fetch_add(1u64, Ordering::AcqRel));

        let this = SyncSqliteConnection {
            connection: ThreadLocal::new(),
            name: name,
        };

        this.try_get()?;
        Result::Ok(this)
    }

    pub fn open(name: String) -> Result<Self> {
        let this = SyncSqliteConnection {
            connection: ThreadLocal::new(),
            name: name,
        };

        this.try_get()?;
        Result::Ok(this)
    }

    pub fn name(&self) -> &String {
        &self.name
    }

    fn try_get(&self) -> Result<&Connection> {
        self.connection.get_or_try(|| open_shared(&self.name()))
    }

    pub fn force(&self) -> &Connection {
        self.try_get()
            .expect("ERROR: Creating the connection to the sqlite in memory database has failed!")
    }

    pub fn execute<P>(&self, sql: &str, params: P) -> Result<usize>
    where
        P: IntoIterator,
        P::Item: ToSql,
    {
        self.try_get()
            .and_then(|conn| conn.execute(sql, params))
    }

    pub fn prepare<'conn>(&'conn self, sql: &str) -> Result<SyncStatement<'conn>> {
        SyncStatement::new(self, sql.to_owned())
    }
}

impl Deref for SyncSqliteConnection {
    type Target = Connection;
    fn deref(&self) -> &Self::Target {
        self.force()
    }
}

impl Clone for SyncSqliteConnection {
    fn clone(&self) -> Self {
        SyncSqliteConnection::open(self.name().clone())
            .expect("ERROR: opening the sqlite database has failed!")
    }

    fn clone_from(&mut self, source: &Self) {
        self.name = source.name().clone();
        self.connection.clear();
    }
}

struct SendStatement<'a>(Statement<'a>);

unsafe impl<'a> Send for SendStatement<'a> {}

pub struct SyncStatement<'conn> {
    conn: &'conn SyncSqliteConnection,
    stmt: ThreadLocal<SendStatement<'conn>>,
    sql: String,
}

impl<'conn> SyncStatement<'conn> {
    fn new(conn: &'conn SyncSqliteConnection, sql: String) -> Result<SyncStatement<'conn>> {
        let this = SyncStatement {
            conn: conn,
            stmt: ThreadLocal::new(),
            sql: sql,
        };

        this.try_get()?;
        Result::Ok(this)
    }

    fn try_get(&self) -> Result<&Statement<'_>> {
        self.stmt
            .get_or_try(|| {
                self.conn
                    .try_get()
                    .and_then(|conn| conn.prepare(&self.sql).map(|stmt| SendStatement(stmt)))
            })
            .map(|ss| &ss.0)
    }

    pub fn execute<P>(&self, params: P) -> Result<usize>
    where
        P: IntoIterator,
        P::Item: ToSql,
    {
        let statement = self.try_get()?;
        unsafe {  &mut*(statement as *const _ as *mut Statement) }.execute(params)
    }

    pub fn force(&self) -> &Statement<'_> {
        self.try_get()
            .expect("ERROR: Building the prepared statement has failed!")
    }

    pub fn deref(&self) -> &Statement<'_> {
        self.force()
    }
}

impl<'conn> Clone for SyncStatement<'conn> {
    fn clone(&self) -> Self {
        SyncStatement::new(self.conn, self.sql.clone())
            .expect("ERROR: creating the sqlitet prepared statement has failed!")
    }

    fn clone_from(&mut self, source: &Self) {
        self.conn = source.conn;
        self.sql = source.sql.clone();
        self.stmt.clear();
    }
}

mod test {

    #[test]
    fn testnew() {
        let _ignore = crate::SyncSqliteConnection::new();
    }

    #[test]
    fn testnewrealconnection() {
        let _connection = crate::SyncSqliteConnection::new().unwrap();
    }

    #[test]
    fn test_open() {
        let dummy = crate::SyncSqliteConnection::new().unwrap();

        let c1 = crate::SyncSqliteConnection::new().unwrap();

        let c2 = crate::SyncSqliteConnection::open(c1.name().clone()).unwrap();

        assert_eq!(c1.name(), c2.name());
        assert_ne!(dummy.name(), c1.name());
    }

    #[test]
    fn test_clone() {
        let c1 = crate::SyncSqliteConnection::new().unwrap();

        let c2 = c1.clone();
        assert_eq!(c1.name(), c2.name());
    }
}