Rust Actix-Web sqlx可选功能“time”是列#4(“created_at”)的类型TIMESTAMPTZ所必需的

py49o6xq  于 2023-02-08  发布在  其他
关注(0)|答案(1)|浏览(149)

我正在使用Actix-Web框架和sqlx库创建我的模型,以便使用postgresql进行所有sql查询。
我的问题是,我正在创建模型,当我进行查询以获取表中的所有行时,在'created_at'列中出现错误。
我得到的错误是:'列#4("created_at")的类型TIMESTAMPTZ所需的可选功能time'
我尝试改变我的表创建,来避免这个错误,还有模型声明,但是没有成功,我去掉了"created_at,"和"updated_at,"错误也消失了,所以我知道它一定是和变量声明有关的。
表格创建:

CREATE TABLE IF NOT EXISTS fields (
  "id" uuid PRIMARY KEY,
  "name" varchar NOT NULL,
  "address" varchar NOT NULL,
  "created_at" TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
  "updated_at" TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

我也试过使用TIMESTAMPZ,但也不起作用。
//字段_模型. rs

use serde::{Deserialize, Serialize};
use sqlx::FromRow;
use uuid::Uuid;

#[derive(Debug, FromRow, Deserialize, Serialize)]
#[allow(non_snake_case)]
pub struct FieldModel {
    pub id: Uuid,
    pub name: String,
    pub address: String,
    pub published: Option<bool>,
    #[serde(rename = "createdAt")]
    pub created_at: Option<chrono::DateTime<chrono::Utc>>,
    #[serde(rename = "updatedAt")]
    pub updated_at: Option<chrono::DateTime<chrono::Utc>>,
}

这是字段GET/fields end-point//field_route. rs的路由处理程序

#[get("/api/games")]
pub async fn get_games(opts: web::Query<FilterOptions>,data: web::Data<AppState>) -> impl Responder {

    let query_result = sqlx::query_as!(
        FieldModel,
        "SELECT * FROM fields",
    )
    .fetch_all(&data.db)
    .await;

    if query_result.is_err() {
        let message = "Something bad happened while fetching all not items";
        return HttpResponse::InternalServerError()
            .json(json!({"status": "error", "message": message}));
    }

    let fields = query_result.unwrap();

    let json_response = serde_json::json!({
        "status":"success",
        "results": fields.len(),
        "fields": fields
    });

    HttpResponse::Ok().json(json_response)
}

这是我的货物。如果你想看看图书馆。

[package]
name = "api_service"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
actix = "0.13.0"
actix-cors = "0.6.4"
actix-web = "4"
chrono = {version = "0.4.23", features = ["serde"]}
dotenv = "0.15.0"
env_logger = "0.10.0"
serde = { version = "1.0.145", features = ["derive"]}
serde_json = "1.0.86"
sqlx = {version = "0.6.2", features = ["runtime-async-std-native-tls", "postgres", "uuid"]}
uuid = { version = "1.2.2", features = ["serde", "v4"] }

任何帮助都将不胜感激,谢谢。

nqwrtyyt

nqwrtyyt1#

原来是sqlx库给我带来了麻烦
只需要添加“chrono”库附带的时间功能,但来自crate sqlx。
Cargo.toml依赖项看起来如下所示:

sqlx = { version = "0.6.2", features = ["runtime-async-std-native-tls", "postgres", "uuid", "chrono"] }

之后,问题解决了,我可以正常运行我的API。

相关问题