Skip to content

Commit cefdebb

Browse files
jyn514Joshua Nelson
authored andcommitted
Add storage.exists()
1 parent b731f84 commit cefdebb

File tree

3 files changed

+43
-0
lines changed

3 files changed

+43
-0
lines changed

src/storage/database.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,12 @@ impl DatabaseBackend {
1313
Self { pool }
1414
}
1515

16+
pub(super) fn exists(&self, path: &str) -> Result<bool, Error> {
17+
let query = "SELECT COUNT(*) > 0 FROM files WHERE path = $1";
18+
let conn = self.pool.get()?;
19+
Ok(conn.query(query, &[&path])?.get(0).get(0))
20+
}
21+
1622
pub(super) fn get(&self, path: &str, max_size: usize) -> Result<Blob, Error> {
1723
use std::convert::TryInto;
1824

src/storage/mod.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,13 @@ impl Storage {
102102
})
103103
}
104104

105+
pub(crate) fn exists(&self, path: &str) -> Result<bool, Error> {
106+
match &self.backend {
107+
StorageBackend::Database(db) => db.exists(path),
108+
StorageBackend::S3(s3) => s3.exists(path),
109+
}
110+
}
111+
105112
pub(crate) fn get(&self, path: &str, max_size: usize) -> Result<Blob, Error> {
106113
let mut blob = match &self.backend {
107114
StorageBackend::Database(db) => db.get(path, max_size),
@@ -307,6 +314,21 @@ mod backend_tests {
307314
use super::*;
308315
use std::fs;
309316

317+
fn test_exists(storage: &Storage) -> Result<(), Error> {
318+
assert!(!storage.exists("path/to/file.txt").unwrap());
319+
let blob = Blob {
320+
path: "path/to/file.txt".into(),
321+
mime: "text/plain".into(),
322+
date_updated: Utc::now(),
323+
content: "Hello world!".into(),
324+
compression: None,
325+
};
326+
storage.store_blobs(vec![blob])?;
327+
assert!(storage.exists("path/to/file.txt")?);
328+
329+
Ok(())
330+
}
331+
310332
fn test_get_object(storage: &Storage) -> Result<(), Error> {
311333
let blob = Blob {
312334
path: "foo/bar.txt".into(),
@@ -570,6 +592,7 @@ mod backend_tests {
570592

571593
tests {
572594
test_batched_uploads,
595+
test_exists,
573596
test_get_object,
574597
test_get_too_big,
575598
test_store_blobs,

src/storage/s3.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,20 @@ impl S3Backend {
5454
})
5555
}
5656

57+
pub(super) fn exists(&self, path: &str) -> Result<bool, Error> {
58+
self.runtime.handle().block_on(async {
59+
let resp = self
60+
.client
61+
.list_objects_v2(ListObjectsV2Request {
62+
bucket: self.bucket.clone(),
63+
prefix: Some(path.into()),
64+
..Default::default()
65+
})
66+
.await?;
67+
Ok(resp.key_count.unwrap() > 0)
68+
})
69+
}
70+
5771
pub(super) fn get(&self, path: &str, max_size: usize) -> Result<Blob, Error> {
5872
self.runtime.handle().block_on(async {
5973
let res = self

0 commit comments

Comments
 (0)