Skip to main content

yang_base/action/builtin/
table.rs

1//! TableAction - 返回表的元信息
2#![cfg(any(feature = "mysql", feature = "postgres"))]
3
4use crate::action::{ActionContext, TypedHandler};
5use crate::error::BaseError;
6use async_trait::async_trait;
7use serde::{Deserialize, Serialize};
8use yang_base_derive::Action;
9
10/// TableAction 的空输入(接受 `{}`)。
11#[derive(Deserialize, schemars::JsonSchema, Default)]
12#[serde(default)]
13pub struct EmptyInput {}
14
15/// 表元信息响应。
16#[derive(Serialize, schemars::JsonSchema)]
17pub struct TableSchemaResponse {
18    /// 表名
19    pub table_name: String,
20    /// 主键字段名
21    pub primary_key: String,
22    /// 表的可写字段 JSON Schema
23    pub input_schema: serde_json::Value,
24    /// 表的可读记录 JSON Schema(供参考,并非某具体 Action 的真实出参)
25    pub output_schema: serde_json::Value,
26}
27
28/// 返回表的元信息。
29#[derive(Action)]
30#[action(
31    name = "table",
32    display_name = "表元信息",
33    description = "返回表结构与字段 schema"
34)]
35pub struct TableAction;
36
37impl TableAction {
38    /// 创建 TableAction 实例。
39    pub fn new() -> Self {
40        Self
41    }
42}
43
44impl Default for TableAction {
45    fn default() -> Self {
46        Self::new()
47    }
48}
49
50#[async_trait]
51impl TypedHandler for TableAction {
52    type Input = EmptyInput;
53    type Output = TableSchemaResponse;
54
55    async fn handle(
56        &self,
57        ctx: ActionContext,
58        _input: EmptyInput,
59    ) -> Result<TableSchemaResponse, BaseError> {
60        let roles = ctx.user_roles_set().cloned().unwrap_or_default();
61        let definition = ctx.table_definition()?;
62        Ok(TableSchemaResponse {
63            table_name: definition.name().to_string(),
64            primary_key: definition.primary_key().to_string(),
65            input_schema: definition.input_schema_for_roles(&roles),
66            output_schema: definition.output_schema_for_roles(&roles),
67        })
68    }
69}