yang_base/action/builtin/
put.rs1#![cfg(any(feature = "mysql", feature = "postgres"))]
3
4use crate::action::builtin::add::AffectedResult;
5use crate::action::{ActionContext, TypedHandler};
6use crate::error::BaseError;
7use crate::table::Record;
8use async_trait::async_trait;
9use serde::Deserialize;
10use serde_json::Value;
11use yang_base_derive::Action;
12
13#[derive(Deserialize, schemars::JsonSchema)]
20#[serde(deny_unknown_fields)]
21pub struct PutInput {
22 pub id: Value,
24 pub data: Record,
26}
27
28#[derive(Action)]
30#[action(
31 name = "put",
32 display_name = "更新数据",
33 description = "按主键更新指定字段"
34)]
35pub struct PutAction;
36
37impl PutAction {
38 pub fn new() -> Self {
40 Self
41 }
42}
43
44impl Default for PutAction {
45 fn default() -> Self {
46 Self::new()
47 }
48}
49
50#[async_trait]
51impl TypedHandler for PutAction {
52 type Input = PutInput;
53 type Output = AffectedResult;
54
55 async fn handle(
56 &self,
57 ctx: ActionContext,
58 input: PutInput,
59 ) -> Result<AffectedResult, BaseError> {
60 if input.data.as_map().is_empty() {
61 return Err(BaseError::ParamInvalid(
62 "data".into(),
63 "至少需要一个字段".into(),
64 ));
65 }
66 let affected = ctx
68 .table_query()?
69 .where_primary_key_eq(input.id)?
70 .update(input.data)
71 .await?;
72 Ok(AffectedResult { affected })
73 }
74}