use crate::routes::{NewPost, Post}; use log::warn; use sqlx::SqlitePool; // Gets the latest posts from the database, ordered by created_at pub async fn db_get_latest_posts(pool: &SqlitePool, limit: i64, offset: i64) -> Vec { sqlx::query_as!( Post, "SELECT * FROM posts ORDER BY created_at DESC LIMIT ? OFFSET ?", limit, offset ) .fetch_all(pool) .await .unwrap() } // Inserts a new post to the database pub async fn db_new_post(post: NewPost, pool: &SqlitePool) -> Option { let insert_query = sqlx::query!( "INSERT INTO posts (user_id, content) VALUES (1, ?)", post.content ) .execute(pool) .await; if insert_query.is_err() { let s = insert_query.err().unwrap(); warn!("Error inserting post into database: {}", s); return None; } // Dips into the database to get the post we just inserted let post = sqlx::query_as!( Post, "SELECT * FROM posts WHERE id = (SELECT MAX(id) FROM posts)" ) .fetch_one(pool) .await .ok()?; Some(post) }