【问题标题】:the trait `Queryable<BigInt, _>` is not implemented for `&i64` when using diesel query data使用柴油查询数据时,没有为 `&i64` 实现特征 `Queryable<BigInt, _>`
【发布时间】:2021-11-02 16:49:50
【问题描述】:

我正在学习使用 rustdies 从 PostgreSQL 13 中选择行,这是我的代码:

#[get("/v1/detail/<songId>")]
pub fn detail(songId: &str) -> io::Result<String> {
    use schema::songs::dsl::*;
    let connection = config::establish_connection();
    let results = songs.filter(source_id.eq(songId))
        .limit(5)
        .load::<Songs>(&connection)
        .expect("Error loading posts");
    let result_value = serde_json::to_string(&results).unwrap();
    let res = ApiResponse {
        body: result_value,
        ..Default::default()
    };
    let response_json = serde_json::to_string(&res).unwrap();
    return Ok(response_json);
}

当我构建此代码时,显示如下错误:

    error[E0277]: the trait bound `&i64: Queryable<BigInt, _>` is not satisfied
  --> src/biz/music/songs.rs:23:10
   |
23 |         .load::<Songs>(&connection)
   |          ^^^^ the trait `Queryable<BigInt, _>` is not implemented for `&i64`

Songs 定义如下:

#[derive(Insertable,Serialize,Queryable)]
#[table_name="songs"]
pub struct Songs<'a> {
    pub id: &'a i64,
    pub name: &'a str,
    pub artists: &'a str,
    pub album_id: &'a i64,
    pub publishtime: &'a i64,
    pub status: &'a i32,
    pub duration: &'a i32,
    pub source_id: &'a str,
    pub source: &'a i32,
    pub created_time: &'a i64,
    pub updated_time: &'a i64
}

这是我的数据库 dml:

CREATE TABLE public.songs (
    id int8 NOT NULL GENERATED ALWAYS AS IDENTITY,
    "name" varchar NOT NULL,
    artists varchar NOT NULL,
    album_id int8 NOT NULL,
    publishtime int8 NULL,
    status int4 NOT NULL DEFAULT 1,
    duration int4 NULL,
    source_id varchar NOT NULL,
    "source" int4 NOT NULL,
    created_time int8 NULL,
    updated_time int8 NULL,
    CONSTRAINT songs_id_seq_pk PRIMARY KEY (id),
    CONSTRAINT unique_songs UNIQUE (name, artists, album_id),
    CONSTRAINT unique_songs_source UNIQUE (source, source_id)
);

我应该怎么做才能解决这个问题?

【问题讨论】:

  • 为什么Songs中的所有字段都引用而不是拥有类型(例如&amp;'a i32而不是i32&amp;'a str而不是String)?

标签: rust


【解决方案1】:

Queryable 需要一个看起来像 (i64, str, str, ...) no (&i64, &str, ..) 的元组,请参阅 https://github.com/diesel-rs/diesel/blob/master/guide_drafts/trait_derives.md

你必须像这样定义歌曲

#[derive(Serialize,Queryable)]
#[table_name="songs"]
pub struct Songs {
    pub id: i64,
    pub name: str,
    pub artists: str,
    pub album_id: i64,
    pub publishtime: i64,
    pub status: i32,
    pub duration: i32,
    pub source_id: str,
    pub source: i32,
    pub created_time: i64,
    pub updated_time: i64
}

【讨论】:

    猜你喜欢
    • 2022-01-15
    • 2022-01-05
    • 2021-11-08
    • 2022-01-22
    • 2021-03-17
    • 2022-12-10
    • 2021-11-07
    • 2021-03-10
    • 2021-05-10
    相关资源
    最近更新 更多