在Rust Diesel中进行原始sql查询

bvjxkvbb  于 2022-12-13  发布在  其他
关注(0)|答案(1)|浏览(231)

我需要使用diesel查询Postgresql(14)中的一个函数。我已经有了可以在表和视图上工作的查询。这是可以工作的,在本例中是一个视图。

schema.rs:

table! {
    latest_readings {
        measurement_time_default -> Timestamptz,
        id -> Integer,
        data -> Jsonb,
    }
}

models.rs:

#[derive(Serialize, Queryable)]
pub struct LatestReading {
    #[diesel(deserialize_as = "MyDateTimeWrapper")]
    pub measurement_time_default: DateTime<Local>,
    pub id: i32,
    pub data: serde_json::Value,
}

controller.rs:

pub async fn get_readings(db: web::Data<Pool>) -> Result<HttpResponse, Error> {
    Ok(web::block(move || db_get_readings(db))
        .await
        .map(|reading| HttpResponse::Ok().json(reading))
        .map_err(|_| HttpResponse::InternalServerError())?)
}

fn db_get_readings(pool: web::Data<Pool>) -> Result<Vec<LatestReading>, diesel::result::Error> {
    let conn = pool.get().unwrap();
    latest_readings.load::<LatestReading>(&conn)
}

这将无法编译。调用postgresql函数的部分。

schema.rs:

table! {
    measurements_single_location_function {
        id -> Integer,
        name -> Text,
        latitude -> Numeric,
        longitude -> Numeric,
        measurement_time_default -> Timestamptz,
        measurements -> Jsonb,
    }
}

models.rs:

#[derive(Serialize, Queryable, QueryableByName)]
#[table_name = "measurements_single_location_function"]
pub struct MeasurementsSingleLocation {
    pub id: i32,
    pub name: String,
    pub latitude: BigDecimal,
    pub longitude: BigDecimal,
    #[diesel(deserialize_as = "MyDateTimeWrapper")]
    pub measurement_time_default: DateTime<Local>,
    pub measurements: serde_json::Value,
}

DB-query in controllers.rs:

fn db_get_measurements_single_location(
    pool: web::Data<Pool>,
    location_id: i32,
    rows: i32,
) -> QueryResult<Vec<MeasurementsSingleLocation>> {
    let conn = pool.get().unwrap(); // Error on next line
    let result: QueryResult<Vec<MeasurementsSingleLocation>> =
        sql_query("select * from measurements_single_location_function(1,10)")
            .load::<MeasurementsSingleLocation>(&conn);
    return result;
}

编译错误:

Compiling weather_rest v0.1.0 (/Users/claus/devel/rust/vegvesen/weather_rest)
error[E0277]: the trait bound `SqlQuery: LoadQuery<_, MeasurementsSingleLocation>` is not satisfied
    --> src/controller.rs:141:14
     |
141  |             .load::<MeasurementsSingleLocation>(&conn);
     |              ^^^^ the trait `LoadQuery<_, MeasurementsSingleLocation>` is not implemented for `SqlQuery`
     |
     = help: the following implementations were found:
               <SqlQuery as LoadQuery<Conn, T>>
note: required by a bound in `load`
    --> /Users/claus/.cargo/registry/src/github.com-1ecc6299db9ec823/diesel-1.4.6/src/query_dsl/mod.rs:1238:15
     |
1238 |         Self: LoadQuery<Conn, U>,
     |               ^^^^^^^^^^^^^^^^^^ required by this bound in `load`

我不知道我错过了什么。

Cargo.toml:

diesel = { version = "1.4.6", features = ["postgres", "uuidv07", "r2d2", "chrono", "numeric", "serde_json"] }
dxpyg8gm

dxpyg8gm1#

当我使用this优秀示例作为模板编写后端服务时,我将相同的结构应用于此,现在它可以编译了。
第一个

相关问题