Home > Back-end >  Error inserting multiple columns into Postgresql DB From SQLX
Error inserting multiple columns into Postgresql DB From SQLX

Time:08-27

I'm trying to perform an insert query into my Postgresql DB, but I am getting a mismatched type issue that I'm unsure how to solve.

Here's the code:

pub struct Product {
    pub id: i32,
    pub product_id: i64,
    pub title: String,
    pub handle: String,
    pub tags: Json<Vec<String>>,
    pub product_type: String,
    pub image_url: String,
    pub created_at: String,
    pub updatedAt: String,
}
pub struct ProductPatch {
    pub product_id: i64,
    pub title: String,
    pub handle: String,
    pub tags: Vec<String>,
    pub product_type: String,
    pub image_url: String
}

async fn add_product(pool: &Db, product: &ProductPatch) -> Result<i64, sqlx::Error> {
    let rec = sqlx::query!(
        r#"
        INSERT INTO products (product_id, title, handle, tags, product_type, image_url)
        VALUES ($1, $2, $3, $4, $5, $6)
        RETURNING product_id, title, handle, tags, product_type, image_url
        "#,
        &product.product_id,
        &product.title,
        &product.handle,
        &product.tags,
        &product.product_type,
        &product.image_url
    )
    .fetch_one(pool)
    .await?;

    Ok(rec.product_id)
}

Here's the error:

mismatched types expected enum Result<_, sqlx::Error> found enum Result<Record, anyhow::Error>

CodePudding user response:

I suppose you've imported anyhow's Result, so your return type Result<i64, sqlx::Error> is actually interpreted as anyhow::Result<i64, sqlx::Error>.

If you intend to return sqlx::Result, either change your return type to sqlx::Result<i64, sqlx::Error> or change your import statements.

If you intend to return anyhow::Result, maybe just return anyhow::Result<i64>.

  • Related