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
use crate::storage::error::StorageError;
use diesel::{Connection, SqliteConnection};
use log::*;
use std::{
io,
path::PathBuf,
sync::{Arc, Mutex},
};
use tokio::task;
const LOG_TARGET: &str = "comms::dht::storage::connection";
#[derive(Clone, Debug)]
pub enum DbConnectionUrl {
Memory,
MemoryShared(String),
File(PathBuf),
}
impl DbConnectionUrl {
pub fn to_url_string(&self) -> String {
use DbConnectionUrl::*;
match self {
Memory => ":memory:".to_owned(),
MemoryShared(identifier) => format!("file:{}?mode=memory&cache=shared", identifier),
File(path) => path
.to_str()
.expect("Invalid non-UTF8 character in database path")
.to_owned(),
}
}
}
#[derive(Clone)]
pub struct DbConnection {
inner: Arc<Mutex<SqliteConnection>>,
}
impl DbConnection {
#[cfg(test)]
pub async fn connect_memory(name: String) -> Result<Self, StorageError> {
Self::connect_url(DbConnectionUrl::MemoryShared(name)).await
}
pub async fn connect_url(db_url: DbConnectionUrl) -> Result<Self, StorageError> {
debug!(target: LOG_TARGET, "Connecting to database using '{:?}'", db_url);
let conn = task::spawn_blocking(move || {
let conn = SqliteConnection::establish(&db_url.to_url_string())?;
conn.execute("PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 60000;")?;
Result::<_, StorageError>::Ok(conn)
})
.await??;
Ok(Self::new(conn))
}
pub async fn connect_and_migrate(db_url: DbConnectionUrl) -> Result<Self, StorageError> {
let conn = Self::connect_url(db_url).await?;
let output = conn.migrate().await?;
info!(target: LOG_TARGET, "DHT database migration: {}", output.trim());
Ok(conn)
}
fn new(conn: SqliteConnection) -> Self {
Self {
inner: Arc::new(Mutex::new(conn)),
}
}
pub async fn migrate(&self) -> Result<String, StorageError> {
embed_migrations!("./migrations");
self.with_connection_async(|conn| {
let mut buf = io::Cursor::new(Vec::new());
embedded_migrations::run_with_output(conn, &mut buf)
.map_err(|err| StorageError::DatabaseMigrationFailed(format!("Database migration failed {}", err)))?;
Ok(String::from_utf8_lossy(&buf.into_inner()).to_string())
})
.await
}
pub async fn with_connection_async<F, R>(&self, f: F) -> Result<R, StorageError>
where
F: FnOnce(&SqliteConnection) -> Result<R, StorageError> + Send + 'static,
R: Send + 'static,
{
let conn_mutex = self.inner.clone();
let ret = task::spawn_blocking(move || {
let lock = acquire_lock!(conn_mutex);
f(&*lock)
})
.await??;
Ok(ret)
}
}
#[cfg(test)]
mod test {
use super::*;
use diesel::{expression::sql_literal::sql, sql_types::Integer, RunQueryDsl};
use tari_test_utils::random;
#[tokio_macros::test_basic]
async fn connect_and_migrate() {
let conn = DbConnection::connect_memory(random::string(8)).await.unwrap();
let output = conn.migrate().await.unwrap();
assert!(output.starts_with("Running migration"));
}
#[tokio_macros::test_basic]
async fn memory_connections() {
let id = random::string(8);
let conn = DbConnection::connect_memory(id.clone()).await.unwrap();
conn.migrate().await.unwrap();
let conn = DbConnection::connect_memory(id).await.unwrap();
let count: i32 = conn
.with_connection_async(|c| {
sql::<Integer>("SELECT COUNT(*) FROM stored_messages")
.get_result(c)
.map_err(Into::into)
})
.await
.unwrap();
assert_eq!(count, 0);
}
}