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