atuin_scripts/
database.rs1use std::{path::Path, str::FromStr, time::Duration};
2
3use atuin_common::utils;
4use sqlx::{
5 Result, Row,
6 sqlite::{
7 SqliteConnectOptions, SqliteJournalMode, SqlitePool, SqlitePoolOptions, SqliteRow,
8 SqliteSynchronous,
9 },
10};
11use tokio::fs;
12use tracing::debug;
13use uuid::Uuid;
14
15use crate::store::script::Script;
16
17#[derive(Debug, Clone)]
18pub struct Database {
19 pub pool: SqlitePool,
20}
21
22impl Database {
23 pub async fn new(path: impl AsRef<Path>, timeout: f64) -> Result<Self> {
24 let path = path.as_ref();
25 debug!("opening script sqlite database at {:?}", path);
26
27 if utils::broken_symlink(path) {
28 eprintln!(
29 "Atuin: Script sqlite db path ({path:?}) is a broken symlink. Unable to read or create replacement."
30 );
31 std::process::exit(1);
32 }
33
34 if !path.exists() {
35 if let Some(dir) = path.parent() {
36 fs::create_dir_all(dir).await?;
37 }
38 }
39
40 let opts = SqliteConnectOptions::from_str(path.as_os_str().to_str().unwrap())?
41 .journal_mode(SqliteJournalMode::Wal)
42 .optimize_on_close(true, None)
43 .synchronous(SqliteSynchronous::Normal)
44 .with_regexp()
45 .foreign_keys(true)
46 .create_if_missing(true);
47
48 let pool = SqlitePoolOptions::new()
49 .acquire_timeout(Duration::from_secs_f64(timeout))
50 .connect_with(opts)
51 .await?;
52
53 Self::setup_db(&pool).await?;
54 Ok(Self { pool })
55 }
56
57 pub async fn sqlite_version(&self) -> Result<String> {
58 sqlx::query_scalar("SELECT sqlite_version()")
59 .fetch_one(&self.pool)
60 .await
61 }
62
63 async fn setup_db(pool: &SqlitePool) -> Result<()> {
64 debug!("running sqlite database setup");
65
66 sqlx::migrate!("./migrations").run(pool).await?;
67
68 Ok(())
69 }
70
71 async fn save_raw(tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>, s: &Script) -> Result<()> {
72 sqlx::query(
73 "insert or ignore into scripts(id, name, description, shebang, script)
74 values(?1, ?2, ?3, ?4, ?5)",
75 )
76 .bind(s.id.to_string())
77 .bind(s.name.as_str())
78 .bind(s.description.as_str())
79 .bind(s.shebang.as_str())
80 .bind(s.script.as_str())
81 .execute(&mut **tx)
82 .await?;
83
84 for tag in s.tags.iter() {
85 sqlx::query(
86 "insert or ignore into script_tags(script_id, tag)
87 values(?1, ?2)",
88 )
89 .bind(s.id.to_string())
90 .bind(tag)
91 .execute(&mut **tx)
92 .await?;
93 }
94
95 Ok(())
96 }
97
98 pub async fn save(&self, s: &Script) -> Result<()> {
99 debug!("saving script to sqlite");
100 let mut tx = self.pool.begin().await?;
101 Self::save_raw(&mut tx, s).await?;
102 tx.commit().await?;
103
104 Ok(())
105 }
106
107 pub async fn save_bulk(&self, s: &[Script]) -> Result<()> {
108 debug!("saving scripts to sqlite");
109
110 let mut tx = self.pool.begin().await?;
111
112 for i in s {
113 Self::save_raw(&mut tx, i).await?;
114 }
115
116 tx.commit().await?;
117
118 Ok(())
119 }
120
121 fn query_script(row: SqliteRow) -> Script {
122 let id = row.get("id");
123 let name = row.get("name");
124 let description = row.get("description");
125 let shebang = row.get("shebang");
126 let script = row.get("script");
127
128 let id = Uuid::parse_str(id).unwrap();
129
130 Script {
131 id,
132 name,
133 description,
134 shebang,
135 script,
136 tags: vec![],
137 }
138 }
139
140 fn query_script_tags(row: SqliteRow) -> String {
141 row.get("tag")
142 }
143
144 #[allow(dead_code)]
145 async fn load(&self, id: &str) -> Result<Option<Script>> {
146 debug!("loading script item {}", id);
147
148 let res = sqlx::query("select * from scripts where id = ?1")
149 .bind(id)
150 .map(Self::query_script)
151 .fetch_optional(&self.pool)
152 .await?;
153
154 if let Some(mut script) = res {
156 let tags = sqlx::query("select tag from script_tags where script_id = ?1")
157 .bind(id)
158 .map(Self::query_script_tags)
159 .fetch_all(&self.pool)
160 .await?;
161
162 script.tags = tags;
163 Ok(Some(script))
164 } else {
165 Ok(None)
166 }
167 }
168
169 pub async fn list(&self) -> Result<Vec<Script>> {
170 debug!("listing scripts");
171
172 let mut res = sqlx::query("select * from scripts")
173 .map(Self::query_script)
174 .fetch_all(&self.pool)
175 .await?;
176
177 for script in res.iter_mut() {
179 let tags = sqlx::query("select tag from script_tags where script_id = ?1")
180 .bind(script.id.to_string())
181 .map(Self::query_script_tags)
182 .fetch_all(&self.pool)
183 .await?;
184
185 script.tags = tags;
186 }
187
188 Ok(res)
189 }
190
191 pub async fn delete(&self, id: &str) -> Result<()> {
192 debug!("deleting script {}", id);
193
194 sqlx::query("delete from scripts where id = ?1")
195 .bind(id)
196 .execute(&self.pool)
197 .await?;
198
199 sqlx::query("delete from script_tags where script_id = ?1")
201 .bind(id)
202 .execute(&self.pool)
203 .await?;
204
205 Ok(())
206 }
207
208 pub async fn update(&self, s: &Script) -> Result<()> {
209 debug!("updating script {:?}", s);
210
211 let mut tx = self.pool.begin().await?;
212
213 sqlx::query("update scripts set name = ?1, description = ?2, shebang = ?3, script = ?4 where id = ?5")
215 .bind(s.name.as_str())
216 .bind(s.description.as_str())
217 .bind(s.shebang.as_str())
218 .bind(s.script.as_str())
219 .bind(s.id.to_string())
220 .execute(&mut *tx)
221 .await?;
222
223 sqlx::query("delete from script_tags where script_id = ?1")
225 .bind(s.id.to_string())
226 .execute(&mut *tx)
227 .await?;
228
229 for tag in s.tags.iter() {
231 sqlx::query(
232 "insert or ignore into script_tags(script_id, tag)
233 values(?1, ?2)",
234 )
235 .bind(s.id.to_string())
236 .bind(tag)
237 .execute(&mut *tx)
238 .await?;
239 }
240
241 tx.commit().await?;
242
243 Ok(())
244 }
245
246 pub async fn get_by_name(&self, name: &str) -> Result<Option<Script>> {
247 let res = sqlx::query("select * from scripts where name = ?1")
248 .bind(name)
249 .map(Self::query_script)
250 .fetch_optional(&self.pool)
251 .await?;
252
253 let script = if let Some(mut script) = res {
254 let tags = sqlx::query("select tag from script_tags where script_id = ?1")
255 .bind(script.id.to_string())
256 .map(Self::query_script_tags)
257 .fetch_all(&self.pool)
258 .await?;
259
260 script.tags = tags;
261 Some(script)
262 } else {
263 None
264 };
265
266 Ok(script)
267 }
268}
269
270#[cfg(test)]
271mod test {
272 use super::*;
273
274 #[tokio::test]
275 async fn test_list() {
276 let db = Database::new("sqlite::memory:", 1.0).await.unwrap();
277 let scripts = db.list().await.unwrap();
278 assert_eq!(scripts.len(), 0);
279
280 let script = Script::builder()
281 .name("test".to_string())
282 .description("test".to_string())
283 .shebang("test".to_string())
284 .script("test".to_string())
285 .build();
286
287 db.save(&script).await.unwrap();
288
289 let scripts = db.list().await.unwrap();
290 assert_eq!(scripts.len(), 1);
291 assert_eq!(scripts[0].name, "test");
292 }
293
294 #[tokio::test]
295 async fn test_save_load() {
296 let db = Database::new("sqlite::memory:", 1.0).await.unwrap();
297
298 let script = Script::builder()
299 .name("test name".to_string())
300 .description("test description".to_string())
301 .shebang("test shebang".to_string())
302 .script("test script".to_string())
303 .build();
304
305 db.save(&script).await.unwrap();
306
307 let loaded = db.load(&script.id.to_string()).await.unwrap().unwrap();
308
309 assert_eq!(loaded, script);
310 }
311
312 #[tokio::test]
313 async fn test_save_bulk() {
314 let db = Database::new("sqlite::memory:", 1.0).await.unwrap();
315
316 let scripts = vec![
317 Script::builder()
318 .name("test name".to_string())
319 .description("test description".to_string())
320 .shebang("test shebang".to_string())
321 .script("test script".to_string())
322 .build(),
323 Script::builder()
324 .name("test name 2".to_string())
325 .description("test description 2".to_string())
326 .shebang("test shebang 2".to_string())
327 .script("test script 2".to_string())
328 .build(),
329 ];
330
331 db.save_bulk(&scripts).await.unwrap();
332
333 let loaded = db.list().await.unwrap();
334 assert_eq!(loaded.len(), 2);
335 assert_eq!(loaded[0].name, "test name");
336 assert_eq!(loaded[1].name, "test name 2");
337 }
338
339 #[tokio::test]
340 async fn test_delete() {
341 let db = Database::new("sqlite::memory:", 1.0).await.unwrap();
342
343 let script = Script::builder()
344 .name("test name".to_string())
345 .description("test description".to_string())
346 .shebang("test shebang".to_string())
347 .script("test script".to_string())
348 .build();
349
350 db.save(&script).await.unwrap();
351
352 assert_eq!(db.list().await.unwrap().len(), 1);
353 db.delete(&script.id.to_string()).await.unwrap();
354
355 let loaded = db.list().await.unwrap();
356 assert_eq!(loaded.len(), 0);
357 }
358}