summaryrefslogblamecommitdiffstats
path: root/src/db/artists.rs
blob: 043f0bdf7ca00ae56a736f81ed28135bc6d38b77 (plain) (tree)























































                                                                                                 
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?,
        )
    }
}