-1

我在 postgres 中得到了这张表

create table tasks_users(
  id serial primary key,
  user_id smallint,
  task_id integer,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
  deleted_at TIMESTAMP WITH TIME ZONE
)

有了这个

table_name   | column_name |        data_type
-------------+-------------+--------------------------
 tasks_users | id          | integer
 tasks_users | user_id     | smallint
 tasks_users | task_id     | integer
 tasks_users | created_at  | timestamp with time zone
 tasks_users | deleted_at  | timestamp with time zone

我得到了这个结构

#[derive(Serialize, Deserialize, Queryable, PostgresMapper)]
#[pg_mapper(table = "tasks_users")]
pub struct TaskUsers {
    pub id: i32,
    pub user_id: i16,
    pub task_id: Option<i32>,
    pub created_at: DateTime<Utc>,
    pub deleted_at: Option<DateTime<Utc>>,
}

我正在用这个进行查询:

pub async fn get_users_by_tasks(
    client: &Client,
    task_id: i32,
) -> Result<Vec<TaskUsers>, io::Error> {
    let statement = client
        .prepare("select id, user_id, created_at from tasks_users where task_id = $1 and deleted_at is null")
        .await
        .unwrap();

    let usuarios = client
        .query(&statement, &[&task_id])
        .await
        .expect("Hubo un error al recuperar los usuarios de una tarea")
        .iter()
        .map(|row| TaskUsers::from_row_ref(row).unwrap())
        .collect::<Vec<TaskUsers>>();

    Ok(usuarios)
}

但是,当我收到此错误时

thread 'actix-rt:worker:0' panicked at 'called `Result::unwrap()` on an `Err` value: UnknownTokioPG("invalid column `task_id`")',

有什么方法可以重用相同的结构还是我需要构建一个新结构?

4

1 回答 1

1

PostgresMapper 的派生的实现细节https://docs.rs/postgres-mapper-derive/0.1.1/src/postgres_mapper_derive/lib.rs.html#120(看起来github存储库目前不可用) .

该实现要求所有字段都显示在提供的行中。

作为一种可能的解决方案,您可以从表中选择所有必需的列:

--- .prepare("select id, user_id, created_at from tasks_users where task_id = $1 and deleted_at is null")
+++ .prepare("select id, user_id, created_at, task_id, deleted_at  from tasks_users where task_id = $1 and deleted_at is null")

或者您可以创建具有匹配字段的自定义结构。

于 2020-08-20T23:01:57.163 回答