arturfil
arturfil

Reputation: 450

Rust Actix-Web sqlx optional feature `time` required for type TIMESTAMPTZ of column #4 ("created_at")

I'm creating my model using Actix-Web framework and sqlx library to make all sql queries with postgresql.

My problem is that I'm creating my model and when I query to get all the rows from a table, it gives me an error in the 'created_at' column.

The error I get is: 'optional feature time required for type TIMESTAMPTZ of column #4 ("created_at")'

And my attempts have been to change my table creation to avoid this error also the model declaration and haven't got any luck. I got rid of the "created_at" & "updated_at" and the error went away so I know it has to be with those variables declarations in particular.

table creation:

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()
);

I have also tried using TIMESTAMPZ and also it didn't work.

// field_model.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>>,
}

And this is my route handler for the field 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)
}

This is my Cargo.toml in case you want to see the libraries.

[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"] }

Any help will be appreciated, thanks.

Upvotes: 2

Views: 1501

Answers (1)

arturfil
arturfil

Reputation: 450

Turns out it was the sqlx library that is the one that was giving me trouble

Just had to add the time functionality that comes with the "chrono" library but from the crate sqlx.

Cargo.toml dependency then looks like this:

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

After that the problem is solved and I can run my api properly.

Upvotes: 4

Related Questions