diff options
Diffstat (limited to 'src/db/artists.rs')
-rw-r--r-- | src/db/artists.rs | 56 |
1 files changed, 56 insertions, 0 deletions
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<Postgres>); + +impl Artists { + pub fn new(pool: Pool<Postgres>) -> Self { + Self(pool) + } + + pub async fn create(&self, artist: Artist) -> Result<i32> { + 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<Artist> { + 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<Artist> { + Ok(sqlx::query_as("select * from artists where handle = $1") + .bind(handle) + .fetch_one(&self.0) + .await?) + } + + pub async fn read_all(&self) -> Result<Vec<Artist>> { + Ok(sqlx::query_as("select * from artists") + .fetch_all(&self.0) + .await?) + } + + pub async fn search(&self, query: &str) -> Result<Vec<Artist>> { + Ok( + sqlx::query_as("select * from artists where handle + name like '%$1%'") + .bind(query) + .fetch_all(&self.0) + .await?, + ) + } +} |