0

I am learning use diesel(diesel = { version = "1.4.4", features = ["postgres"] }) to query some records from PostgreSQL 13 database, this is my query code:

#[get("/v1/playlist/detail/<req_playlist_id>")]
pub fn playlist_detail(req_playlist_id: i64) -> content::Json<String> {
    use crate::schema::playlist::dsl::*;
    let connection = config::establish_connection();
    let results = playlist.filter(id.eq(req_playlist_id))
            .limit(1)
            .load::<QueryPlaylist>(&connection)
            .expect("Error loading posts");

    let response_json = serde_json::to_string(&results).unwrap();
    return content::Json(response_json);
}

now I found a problem that the QueryPlaylist column must be the same as database, I could not delete a column because the compile will failed. What make me confusing is that why the column must be the same with database? should I query every column data every time? If I only want to query one column data, what should I do? If I want to query the column I wanted, is it possible? And this is my query model:

#[derive(Insertable,Serialize,Queryable)]
#[table_name="playlist"]
pub struct QueryPlaylist {
    pub id: i64,
    pub creator: i64,
    pub name: String,
    pub cover_url: String,
    pub description: Option<String>,
    pub subscribed: Option<i32>,
    pub subscribed_count: Option<i64>,
    pub comment_count: Option<i64>,
    pub share_count: Option<i32>,
    pub play_count: Option<i32>
    //pub source: i32
}

this is my diesel schema:

table! {
    playlist (id) {
        id -> Int8,
        creator -> Int8,
        name -> Varchar,
        cover_url -> Varchar,
        description -> Nullable<Varchar>,
        subscribed -> Nullable<Int4>,
        subscribed_count -> Nullable<Int8>,
        comment_count -> Nullable<Int8>,
        share_count -> Nullable<Int4>,
        play_count -> Nullable<Int4>,
        source -> Int4,
    }
}
kmdreko
  • 42,554
  • 6
  • 57
  • 106
Dolphin
  • 29,069
  • 61
  • 260
  • 539
  • Please provide your diesel schema for the "playlist" table and the error that you're getting. Its not clear to me what your issue is. – kmdreko Sep 11 '21 at 02:38
  • It is simple: I did not comment `pub source: i32`, it works fine. when I commnet `pub source: i32` in `QueryPlaylist`, the project could not compile.@kmdreko I have pasted my schema of the table. – Dolphin Sep 11 '21 at 03:19
  • 1
    Oh I see. Yeah diesel requires the type you load into to line up exactly with what is queried. Perhaps this can help you out: [How do I select a subset of columns with diesel-rs?](https://stackoverflow.com/q/66048172/2189130) – kmdreko Sep 11 '21 at 03:29

0 Answers0