Skip to content

Commit 6c976d1

Browse files
committed
feat(db): add CRUD for snippets
1 parent 2a0299e commit 6c976d1

1 file changed

Lines changed: 103 additions & 0 deletions

File tree

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
use crate::prelude::errors::*;
2+
use crate::prelude::types::*;
3+
4+
pub async fn create_snippet(
5+
key: &str,
6+
content: &str,
7+
created_by: &str,
8+
pool: &sqlx::SqlitePool,
9+
) -> ModmailResult<()> {
10+
sqlx::query!(
11+
r#"
12+
INSERT INTO snippets (key, content, created_by)
13+
VALUES (?, ?, ?)
14+
"#,
15+
key,
16+
content,
17+
created_by
18+
)
19+
.execute(pool)
20+
.await?;
21+
22+
Ok(())
23+
}
24+
25+
pub async fn get_snippet_by_key(
26+
key: &str,
27+
pool: &sqlx::SqlitePool,
28+
) -> ModmailResult<Option<Snippet>> {
29+
let snippet = sqlx::query_as!(
30+
Snippet,
31+
r#"
32+
SELECT id as "id!", key, content, created_by, created_at as "created_at: String", updated_at as "updated_at: String"
33+
FROM snippets
34+
WHERE key = ?
35+
"#,
36+
key
37+
)
38+
.fetch_optional(pool)
39+
.await?;
40+
41+
Ok(snippet)
42+
}
43+
44+
pub async fn get_all_snippets(pool: &sqlx::SqlitePool) -> ModmailResult<Vec<Snippet>> {
45+
let snippets = sqlx::query_as!(
46+
Snippet,
47+
r#"
48+
SELECT id as "id!", key, content, created_by, created_at as "created_at: String", updated_at as "updated_at: String"
49+
FROM snippets
50+
ORDER BY created_at DESC
51+
"#
52+
)
53+
.fetch_all(pool)
54+
.await?;
55+
56+
Ok(snippets)
57+
}
58+
59+
pub async fn update_snippet(
60+
key: &str,
61+
content: &str,
62+
pool: &sqlx::SqlitePool,
63+
) -> ModmailResult<()> {
64+
let result = sqlx::query!(
65+
r#"
66+
UPDATE snippets
67+
SET content = ?, updated_at = CURRENT_TIMESTAMP
68+
WHERE key = ?
69+
"#,
70+
content,
71+
key
72+
)
73+
.execute(pool)
74+
.await?;
75+
76+
if result.rows_affected() == 0 {
77+
return Err(ModmailError::Database(DatabaseError::NotFound(
78+
"Snippet not found".to_string(),
79+
)));
80+
}
81+
82+
Ok(())
83+
}
84+
85+
pub async fn delete_snippet(key: &str, pool: &sqlx::SqlitePool) -> ModmailResult<()> {
86+
let result = sqlx::query!(
87+
r#"
88+
DELETE FROM snippets
89+
WHERE key = ?
90+
"#,
91+
key
92+
)
93+
.execute(pool)
94+
.await?;
95+
96+
if result.rows_affected() == 0 {
97+
return Err(ModmailError::Database(DatabaseError::NotFound(
98+
"Snippet not found".to_string(),
99+
)));
100+
}
101+
102+
Ok(())
103+
}

0 commit comments

Comments
 (0)