Skip to main content

yang_base/action/builtin/
put.rs

1//! PutAction - 按主键更新指定字段
2#![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/// PutAction 的输入:动态主键值 + 字段更新对象。
14///
15/// JSON 形态:
16/// ```json
17/// { "id": 1, "data": { "username": "alice", "age": 30 } }
18/// ```
19#[derive(Deserialize, schemars::JsonSchema)]
20#[serde(deny_unknown_fields)]
21pub struct PutInput {
22    /// 主键值
23    pub id: Value,
24    /// 字段更新对象。空对象将被拒绝。
25    pub data: Record,
26}
27
28/// 按主键更新记录。
29#[derive(Action)]
30#[action(
31    name = "put",
32    display_name = "更新数据",
33    description = "按主键更新指定字段"
34)]
35pub struct PutAction;
36
37impl PutAction {
38    /// 创建 PutAction 实例。
39    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        // 主键定位是 Action 自有寻址机制,绕过 filterable 业务筛选权限。
67        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}