FrostByte/server/src/db.rs

27 lines
685 B
Rust
Raw Normal View History

2023-10-20 20:57:58 +02:00
use crate::routes::{NewPost, Post};
use sqlx::{Row, SqlitePool};
2023-10-20 06:06:55 +02:00
2023-10-20 20:57:58 +02:00
// Gets all posts from the database
pub async fn db_get_posts(pool: &SqlitePool) -> Vec<Post> {
sqlx::query_as!(Post, "SELECT * FROM posts")
.fetch_all(pool)
.await
.unwrap()
2023-10-20 06:06:55 +02:00
}
2023-10-20 20:57:58 +02:00
// Inserts a new post to the database
pub async fn db_new_post(post: NewPost, pool: &SqlitePool) -> Option<Post> {
let q2 = sqlx::query!("INSERT INTO posts (content) VALUES (?)", post.content)
.execute(pool)
.await;
2023-10-20 06:06:55 +02:00
2023-10-20 20:57:58 +02:00
let q = sqlx::query_as!(
Post,
"SELECT * FROM posts WHERE id = (SELECT MAX(id) FROM posts)"
)
.fetch_one(pool)
.await
.ok()?;
Some(q)
2023-10-20 06:06:55 +02:00
}