-
Notifications
You must be signed in to change notification settings - Fork 221
/
db.rs
240 lines (224 loc) · 7.75 KB
/
db.rs
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
use std::{
path::Path,
sync::{Arc, Mutex},
};
use interrupt_support::SqlInterruptHandle;
use rusqlite::{
named_params,
types::{FromSql, ToSql},
Connection, OpenFlags,
};
use sql_support::{open_database::open_database_with_flags, ConnExt};
use crate::{
keyword::full_keyword, schema::SuggestConnectionInitializer, RemoteRecordId, RemoteSuggestion,
Result, Suggestion,
};
pub const LAST_FETCH_META_KEY: &str = "last_fetch";
pub const NONSPONSORED_IAB_CATEGORIES: &[&str] = &["5 - Education"];
#[derive(Clone, Copy)]
pub enum ConnectionType {
ReadOnly,
ReadWrite,
}
impl From<ConnectionType> for OpenFlags {
fn from(type_: ConnectionType) -> Self {
match type_ {
ConnectionType::ReadOnly => {
OpenFlags::SQLITE_OPEN_URI | OpenFlags::SQLITE_OPEN_READ_ONLY
}
ConnectionType::ReadWrite => {
OpenFlags::SQLITE_OPEN_URI
| OpenFlags::SQLITE_OPEN_CREATE
| OpenFlags::SQLITE_OPEN_READ_WRITE
}
}
}
}
pub struct SuggestDb {
conn: Mutex<Connection>,
pub type_: ConnectionType,
pub interrupt_handle: Arc<SqlInterruptHandle>,
}
impl SuggestDb {
pub fn open(path: impl AsRef<Path>, type_: ConnectionType) -> Result<Self> {
let conn = open_database_with_flags(path, type_.into(), &SuggestConnectionInitializer)?;
Ok(Self::with_connection(conn, type_))
}
fn with_connection(conn: Connection, type_: ConnectionType) -> Self {
let interrupt_handle = Arc::new(SqlInterruptHandle::new(&conn));
Self {
conn: Mutex::new(conn),
type_,
interrupt_handle,
}
}
pub fn fetch_by_keyword(&self, keyword: &str) -> Result<Vec<Suggestion>> {
let conn = self.conn.lock().unwrap();
conn.query_rows_and_then_cached(
"SELECT s.id, k.rank, s.block_id, s.advertiser, s.iab_category,
s.title, s.url, s.impression_url, s.click_url,
(SELECT i.data FROM icons i WHERE i.id = s.icon_id) AS icon
FROM suggestions s
JOIN keywords k ON k.suggestion_id = s.id
WHERE k.keyword = :keyword
LIMIT 1",
named_params! {
":keyword": keyword,
},
|row| -> Result<Suggestion> {
let keywords: Vec<String> = conn.query_rows_and_then(
"SELECT keyword FROM keywords
WHERE suggestion_id = :suggestion_id AND rank >= :rank
ORDER BY rank ASC",
named_params! {
":suggestion_id": row.get::<_, i64>("id")?,
":rank": row.get::<_, i64>("rank")?,
},
|row| row.get(0),
)?;
let iab_category = row.get::<_, String>("iab_category")?;
let is_sponsored = !NONSPONSORED_IAB_CATEGORIES.contains(&iab_category.as_str());
Ok(Suggestion {
block_id: row.get("block_id")?,
advertiser: row.get("advertiser")?,
iab_category,
is_sponsored,
title: row.get("title")?,
url: row.get("url")?,
full_keyword: full_keyword(keyword, &keywords),
icon: row.get("icon")?,
impression_url: row.get("impression_url")?,
click_url: row.get("click_url")?,
})
},
)
}
pub fn ingest(
&self,
record_id: &RemoteRecordId,
suggestions: &[RemoteSuggestion],
) -> Result<()> {
let scope = self.interrupt_handle.begin_interrupt_scope()?;
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction()?;
for suggestion in suggestions {
scope.err_if_interrupted()?;
let suggestion_id: i64 = tx.query_row_and_then_cachable(
"INSERT INTO suggestions(
record_id,
block_id,
advertiser,
iab_category,
title,
url,
icon_id,
impression_url,
click_url
)
VALUES(
:record_id,
:block_id,
:advertiser,
:iab_category,
:title,
:url,
:icon_id,
:impression_url,
:click_url
)
RETURNING id",
named_params! {
":record_id": record_id.as_str(),
":block_id": suggestion.block_id,
":advertiser": suggestion.advertiser,
":iab_category": suggestion.iab_category,
":title": suggestion.title,
":url": suggestion.url,
":icon_id": suggestion.icon_id,
":impression_url": suggestion.impression_url,
":click_url": suggestion.click_url,
},
|row| row.get(0),
true,
)?;
for (index, keyword) in suggestion.keywords.iter().enumerate() {
tx.execute(
"INSERT INTO keywords(
keyword,
suggestion_id,
rank
)
VALUES(
:keyword,
:suggestion_id,
:rank
)",
named_params! {
":keyword": keyword,
":rank": index,
":suggestion_id": suggestion_id,
},
)?;
}
}
tx.commit()?;
Ok(())
}
// ...
pub fn put_icon(&self, icon_id: &str, data: &[u8]) -> Result<()> {
self.conn.lock().unwrap().execute(
"INSERT INTO icons(
id,
data
)
VALUES(
:id,
:data
)",
named_params! {
":id": icon_id,
":data": data,
},
)?;
Ok(())
}
// ...
pub fn drop(&self, record_id: &RemoteRecordId) -> Result<()> {
self.conn.lock().unwrap().execute_cached(
"DELETE FROM suggestions WHERE record_id = :record_id",
named_params! { ":record_id": record_id.as_str() },
)?;
Ok(())
}
// ...
pub fn drop_icon(&self, icon_id: &str) -> Result<()> {
self.conn.lock().unwrap().execute_cached(
"DELETE FROM icons WHERE id = :id",
named_params! { ":id": icon_id },
)?;
Ok(())
}
/// Clears the database, removing all suggestions, icons, and metadata.
pub fn clear(&self) -> Result<()> {
self.conn.lock().unwrap().execute_batch(
"DELETE FROM suggestions;
DELETE FROM icons;
DELETE FROM meta;",
)?;
Ok(())
}
pub fn get_meta<T: FromSql>(&self, key: &str) -> Result<Option<T>> {
Ok(self.conn.lock().unwrap().try_query_one(
"SELECT value FROM meta WHERE key = :key",
named_params! { ":key": key },
true,
)?)
}
pub fn put_meta(&self, key: &str, value: impl ToSql) -> Result<()> {
self.conn.lock().unwrap().execute_cached(
"REPLACE INTO meta(key, value) VALUES(:key, :value)",
named_params! { ":key": key, ":value": value },
)?;
Ok(())
}
}