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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
|
use std::{path::Path, str::FromStr, time::Duration};
use atuin_common::utils;
use sqlx::{
Result, Row,
sqlite::{
SqliteConnectOptions, SqliteJournalMode, SqlitePool, SqlitePoolOptions, SqliteRow,
SqliteSynchronous,
},
};
use tokio::fs;
use tracing::debug;
use uuid::Uuid;
use crate::store::script::Script;
#[derive(Debug, Clone)]
pub struct Database {
pub pool: SqlitePool,
}
impl Database {
pub async fn new(path: impl AsRef<Path>, timeout: f64) -> Result<Self> {
let path = path.as_ref();
debug!("opening script sqlite database at {:?}", path);
if utils::broken_symlink(path) {
eprintln!(
"Atuin: Script sqlite db path ({path:?}) is a broken symlink. Unable to read or create replacement."
);
std::process::exit(1);
}
if !path.exists()
&& let Some(dir) = path.parent()
{
fs::create_dir_all(dir).await?;
}
let opts = SqliteConnectOptions::from_str(path.as_os_str().to_str().unwrap())?
.journal_mode(SqliteJournalMode::Wal)
.optimize_on_close(true, None)
.synchronous(SqliteSynchronous::Normal)
.with_regexp()
.foreign_keys(true)
.create_if_missing(true);
let pool = SqlitePoolOptions::new()
.acquire_timeout(Duration::from_secs_f64(timeout))
.connect_with(opts)
.await?;
Self::setup_db(&pool).await?;
Ok(Self { pool })
}
pub async fn sqlite_version(&self) -> Result<String> {
sqlx::query_scalar("SELECT sqlite_version()")
.fetch_one(&self.pool)
.await
}
async fn setup_db(pool: &SqlitePool) -> Result<()> {
debug!("running sqlite database setup");
sqlx::migrate!("./migrations").run(pool).await?;
Ok(())
}
async fn save_raw(tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>, s: &Script) -> Result<()> {
sqlx::query(
"insert or ignore into scripts(id, name, description, shebang, script)
values(?1, ?2, ?3, ?4, ?5)",
)
.bind(s.id.to_string())
.bind(s.name.as_str())
.bind(s.description.as_str())
.bind(s.shebang.as_str())
.bind(s.script.as_str())
.execute(&mut **tx)
.await?;
for tag in s.tags.iter() {
sqlx::query(
"insert or ignore into script_tags(script_id, tag)
values(?1, ?2)",
)
.bind(s.id.to_string())
.bind(tag)
.execute(&mut **tx)
.await?;
}
Ok(())
}
pub async fn save(&self, s: &Script) -> Result<()> {
debug!("saving script to sqlite");
let mut tx = self.pool.begin().await?;
Self::save_raw(&mut tx, s).await?;
tx.commit().await?;
Ok(())
}
pub async fn save_bulk(&self, s: &[Script]) -> Result<()> {
debug!("saving scripts to sqlite");
let mut tx = self.pool.begin().await?;
for i in s {
Self::save_raw(&mut tx, i).await?;
}
tx.commit().await?;
Ok(())
}
fn query_script(row: SqliteRow) -> Script {
let id = row.get("id");
let name = row.get("name");
let description = row.get("description");
let shebang = row.get("shebang");
let script = row.get("script");
let id = Uuid::parse_str(id).unwrap();
Script {
id,
name,
description,
shebang,
script,
tags: vec![],
}
}
fn query_script_tags(row: SqliteRow) -> String {
row.get("tag")
}
#[allow(dead_code)]
async fn load(&self, id: &str) -> Result<Option<Script>> {
debug!("loading script item {}", id);
let res = sqlx::query("select * from scripts where id = ?1")
.bind(id)
.map(Self::query_script)
.fetch_optional(&self.pool)
.await?;
// intentionally not joining, don't want to duplicate the script data in memory a whole bunch.
if let Some(mut script) = res {
let tags = sqlx::query("select tag from script_tags where script_id = ?1")
.bind(id)
.map(Self::query_script_tags)
.fetch_all(&self.pool)
.await?;
script.tags = tags;
Ok(Some(script))
} else {
Ok(None)
}
}
pub async fn list(&self) -> Result<Vec<Script>> {
debug!("listing scripts");
let mut res = sqlx::query("select * from scripts")
.map(Self::query_script)
.fetch_all(&self.pool)
.await?;
// Fetch all the tags for each script
for script in res.iter_mut() {
let tags = sqlx::query("select tag from script_tags where script_id = ?1")
.bind(script.id.to_string())
.map(Self::query_script_tags)
.fetch_all(&self.pool)
.await?;
script.tags = tags;
}
Ok(res)
}
pub async fn clear(&self) -> Result<()> {
debug!("clearing all scripts from sqlite");
sqlx::query("delete from script_tags")
.execute(&self.pool)
.await?;
sqlx::query("delete from scripts")
.execute(&self.pool)
.await?;
Ok(())
}
pub async fn delete(&self, id: &str) -> Result<()> {
debug!("deleting script {}", id);
sqlx::query("delete from scripts where id = ?1")
.bind(id)
.execute(&self.pool)
.await?;
// delete all the tags for the script
sqlx::query("delete from script_tags where script_id = ?1")
.bind(id)
.execute(&self.pool)
.await?;
Ok(())
}
pub async fn update(&self, s: &Script) -> Result<()> {
debug!("updating script {:?}", s);
let mut tx = self.pool.begin().await?;
// Update the script's base fields
sqlx::query("update scripts set name = ?1, description = ?2, shebang = ?3, script = ?4 where id = ?5")
.bind(s.name.as_str())
.bind(s.description.as_str())
.bind(s.shebang.as_str())
.bind(s.script.as_str())
.bind(s.id.to_string())
.execute(&mut *tx)
.await?;
// Delete all existing tags for this script
sqlx::query("delete from script_tags where script_id = ?1")
.bind(s.id.to_string())
.execute(&mut *tx)
.await?;
// Insert new tags
for tag in s.tags.iter() {
sqlx::query(
"insert or ignore into script_tags(script_id, tag)
values(?1, ?2)",
)
.bind(s.id.to_string())
.bind(tag)
.execute(&mut *tx)
.await?;
}
tx.commit().await?;
Ok(())
}
pub async fn get_by_name(&self, name: &str) -> Result<Option<Script>> {
let res = sqlx::query("select * from scripts where name = ?1")
.bind(name)
.map(Self::query_script)
.fetch_optional(&self.pool)
.await?;
let script = if let Some(mut script) = res {
let tags = sqlx::query("select tag from script_tags where script_id = ?1")
.bind(script.id.to_string())
.map(Self::query_script_tags)
.fetch_all(&self.pool)
.await?;
script.tags = tags;
Some(script)
} else {
None
};
Ok(script)
}
}
#[cfg(test)]
mod test {
use super::*;
#[tokio::test]
async fn test_list() {
let db = Database::new("sqlite::memory:", 1.0).await.unwrap();
let scripts = db.list().await.unwrap();
assert_eq!(scripts.len(), 0);
let script = Script::builder()
.name("test".to_string())
.description("test".to_string())
.shebang("test".to_string())
.script("test".to_string())
.build();
db.save(&script).await.unwrap();
let scripts = db.list().await.unwrap();
assert_eq!(scripts.len(), 1);
assert_eq!(scripts[0].name, "test");
}
#[tokio::test]
async fn test_save_load() {
let db = Database::new("sqlite::memory:", 1.0).await.unwrap();
let script = Script::builder()
.name("test name".to_string())
.description("test description".to_string())
.shebang("test shebang".to_string())
.script("test script".to_string())
.build();
db.save(&script).await.unwrap();
let loaded = db.load(&script.id.to_string()).await.unwrap().unwrap();
assert_eq!(loaded, script);
}
#[tokio::test]
async fn test_save_bulk() {
let db = Database::new("sqlite::memory:", 1.0).await.unwrap();
let scripts = vec![
Script::builder()
.name("test name".to_string())
.description("test description".to_string())
.shebang("test shebang".to_string())
.script("test script".to_string())
.build(),
Script::builder()
.name("test name 2".to_string())
.description("test description 2".to_string())
.shebang("test shebang 2".to_string())
.script("test script 2".to_string())
.build(),
];
db.save_bulk(&scripts).await.unwrap();
let loaded = db.list().await.unwrap();
assert_eq!(loaded.len(), 2);
assert_eq!(loaded[0].name, "test name");
assert_eq!(loaded[1].name, "test name 2");
}
#[tokio::test]
async fn test_delete() {
let db = Database::new("sqlite::memory:", 1.0).await.unwrap();
let script = Script::builder()
.name("test name".to_string())
.description("test description".to_string())
.shebang("test shebang".to_string())
.script("test script".to_string())
.build();
db.save(&script).await.unwrap();
assert_eq!(db.list().await.unwrap().len(), 1);
db.delete(&script.id.to_string()).await.unwrap();
let loaded = db.list().await.unwrap();
assert_eq!(loaded.len(), 0);
}
}
|