< 返回我的博客

BlackStone 发表于 2024-04-13 17:40

Tags:sqlb return all fields after insert data

Category Struct:

#[derive(sqlx::FromRow,sqlb::Fields,Debug,Serialize, Default, Clone, Deserialize)]
pub struct Category {
    pub id: i32,
    pub name: String,
    pub icon: Option<String>,
    pub poster: Option<String>,
    pub z_key: Option<String>,
    pub z_order: i32,
    pub created_at: Option<chrono::DateTime<Utc>>,
    pub updated_at: Option<chrono::DateTime<Utc>>,
    // #[field(name = "description")]
    pub description: Option<String>,
    // #[field(skip)]
    pub status: bool,
    pub z_extra: Option<String>,
    
}

pub async fn create(
    State(state): State<AppState>,
    extract::Json(payload): extract::Json<CategoryForCreate>,
) -> impl IntoResponse {
    let category = CategoryForCreate {
        name: payload.name,
        icon: payload.icon,
        poster: payload.poster,
        z_key: payload.z_key,
        description: payload.description,
        z_order: payload.z_order
        
    };
    let sb = sqlb::insert().table("categories").data(category.all_fields());
    let sb = sb.returning(&Category::field_names());
    //return some fields
    //  let sb:Result<Option<(i32, String)>, sqlx::Error>= sb.fetch_optional::<_,(i32,String)>(&state.pool).await;
    let sb:Result<Option<Category>, sqlx::Error>= sb.fetch_optional(&state.pool).await;
    match sb {
        Ok(row) => {
            match row{
                Some(category)=>{
                    info!("category={:?}", category);
                    (
                        StatusCode::CREATED,
                        Json(json!({
                          "data":category
                        })),
                    )
                },
                None=>{
                    (
                        StatusCode::CONFLICT,
                        Json(json!({
                          "err":"no category".to_string()
                        })),
                    )
                }
            }
            

        }
        Err(err) => {
            println!("err={:?}", err);
            (
                StatusCode::BAD_REQUEST,
                Json(json!({
                  "err":err.to_string()
                })),
            )
        }
    }
}

评论区

写评论

还没有评论

1 共 0 条评论, 1 页