#![cfg(any(feature = "mysql", feature = "postgres"))]
use crate::action::{ActionContext, TypedHandler};
use crate::error::BaseError;
use crate::table::Record;
use async_trait::async_trait;
use serde::Serialize;
use yang_base_derive::Action;
#[derive(Serialize, schemars::JsonSchema)]
pub struct AffectedResult {
pub affected: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReturningTarget<'a> {
Pk,
Columns(&'a [&'a str]),
All,
}
#[derive(Serialize, schemars::JsonSchema)]
pub struct InsertResult {
pub affected: u64,
pub id: serde_json::Value,
}
impl InsertResult {
pub fn as_u64(&self) -> Option<u64> {
self.id
.as_u64()
.or_else(|| self.id.as_str().and_then(|value| value.parse().ok()))
}
pub fn as_str(&self) -> Option<&str> {
self.id.as_str()
}
}
#[derive(Action)]
#[action(
name = "add",
display_name = "新增数据",
description = "向表中插入一条记录"
)]
pub struct AddAction;
impl AddAction {
pub fn new() -> Self {
Self
}
}
impl Default for AddAction {
fn default() -> Self {
Self::new()
}
}
#[async_trait]
impl TypedHandler for AddAction {
type Input = Record;
type Output = InsertResult;
async fn handle(&self, ctx: ActionContext, input: Record) -> Result<InsertResult, BaseError> {
let (affected, id) = ctx.table_query()?.insert_returning_pk_value(input).await?;
Ok(InsertResult { affected, id })
}
}