From 469a3ad33914f7eff6edc9ca7fabb12f2950da84 Mon Sep 17 00:00:00 2001 From: cel 🌸 Date: Thu, 14 Nov 2024 17:59:21 +0000 Subject: database work --- src/db/artists.rs | 56 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 src/db/artists.rs (limited to 'src/db/artists.rs') diff --git a/src/db/artists.rs b/src/db/artists.rs new file mode 100644 index 0000000..043f0bd --- /dev/null +++ b/src/db/artists.rs @@ -0,0 +1,56 @@ +use sqlx::{Pool, Postgres}; + +use crate::artist::Artist; +use crate::Result; + +#[derive(Clone)] +pub struct Artists(Pool); + +impl Artists { + pub fn new(pool: Pool) -> Self { + Self(pool) + } + + pub async fn create(&self, artist: Artist) -> Result { + let artist_id = sqlx::query!( + "insert into artists (handle, name, bio, site) values ($1, $2, $3, $4) returning id", + artist.handle, + artist.name, + artist.bio, + artist.site + ) + .fetch_one(&self.0) + .await? + .id; + Ok(artist_id) + } + + pub async fn read(&self, id: i32) -> Result { + Ok(sqlx::query_as("select * from artists where id = $1") + .bind(id) + .fetch_one(&self.0) + .await?) + } + + pub async fn read_handle(&self, handle: &str) -> Result { + Ok(sqlx::query_as("select * from artists where handle = $1") + .bind(handle) + .fetch_one(&self.0) + .await?) + } + + pub async fn read_all(&self) -> Result> { + Ok(sqlx::query_as("select * from artists") + .fetch_all(&self.0) + .await?) + } + + pub async fn search(&self, query: &str) -> Result> { + Ok( + sqlx::query_as("select * from artists where handle + name like '%$1%'") + .bind(query) + .fetch_all(&self.0) + .await?, + ) + } +} -- cgit