use crate::action::{Action, ActionContext, ApiResponse};
use crate::error::BaseError;
use crate::table::{SortOrder, TableConfig};
use async_trait::async_trait;
use std::sync::Arc;
#[allow(dead_code)]
pub struct SelectAction {
table_config: Arc<TableConfig>,
}
impl SelectAction {
pub fn new(table_config: Arc<TableConfig>) -> Self {
Self { table_config }
}
}
fn parse_paging_param(
ctx: &ActionContext,
key: &str,
default: i64,
min: i64,
max: i64,
) -> Result<usize, BaseError> {
let raw_value: i64 = ctx.param_optional::<i64>(key).unwrap_or(default);
if raw_value < min || raw_value > max {
return Err(BaseError::ParamInvalid(
key.to_string(),
format!(
"参数值 {} 超出允许范围 [{}, {}]",
raw_value, min, max
),
));
}
usize::try_from(raw_value).map_err(|_| {
BaseError::ParamInvalid(
key.to_string(),
format!("参数值 {} 无法转换为 usize", raw_value),
)
})
}
#[async_trait]
impl Action for SelectAction {
async fn execute(&self, context: ActionContext) -> Result<ApiResponse, BaseError> {
let page = parse_paging_param(&context, "page", 1, 1, i64::MAX)?;
let page_size = parse_paging_param(&context, "page_size", 10, 1, 100)?;
let mut query = context.table_query()?;
if let Some(fields) = context.param_optional::<Vec<String>>("fields") {
let field_refs: Vec<&str> = fields.iter().map(|s| s.as_str()).collect();
query = query.select_fields(&field_refs)?;
}
if let Some(where_conditions) = context.param_optional::<serde_json::Value>("where") {
if let Some(obj) = where_conditions.as_object() {
for (field, value) in obj {
query = query.where_eq(field.as_str(), value.clone())?;
}
}
}
if let Some(order_by) = context.param_optional::<Vec<serde_json::Value>>("order_by") {
for order in order_by {
if let Some(obj) = order.as_object() {
if let (Some(field), Some(direction)) = (obj.get("field"), obj.get("direction"))
{
let field_str = field.as_str().ok_or_else(|| {
BaseError::ParamInvalid(
"order_by".to_string(),
"field 必须是字符串".to_string(),
)
})?;
let direction_str = direction.as_str().ok_or_else(|| {
BaseError::ParamInvalid(
"order_by".to_string(),
"direction 必须是字符串".to_string(),
)
})?;
let sort_order = match direction_str.to_lowercase().as_str() {
"asc" => SortOrder::Asc,
"desc" => SortOrder::Desc,
_ => {
return Err(BaseError::ParamInvalid(
"order_by".to_string(),
"direction 必须是 'asc' 或 'desc'".to_string(),
))
}
};
query = query.order_by(field_str, sort_order)?;
}
}
}
}
let query = query.page(page, page_size)?;
#[cfg(feature = "mysql")]
{
use crate::table::DynamicRow;
let result = query.paginate::<DynamicRow>().await?;
return ApiResponse::success(result, "查询成功");
}
#[cfg(not(feature = "mysql"))]
{
let _ = query;
Err(BaseError::Unknown(
"SelectAction 需要启用 mysql feature".to_string(),
))
}
}
fn name(&self) -> &str {
"select"
}
fn display_name(&self) -> &str {
"查询列表"
}
fn description(&self) -> &str {
"分页查询数据表中的记录列表"
}
fn params_schema(&self) -> Option<serde_json::Value> {
Some(serde_json::json!({
"type": "object",
"properties": {
"fields": {
"type": "array",
"items": { "type": "string" },
"description": "要查询的字段列表"
},
"where": {
"type": "object",
"description": "筛选条件"
},
"order_by": {
"type": "array",
"items": {
"type": "object",
"properties": {
"field": { "type": "string" },
"direction": { "type": "string", "enum": ["asc", "desc"] }
}
},
"description": "排序规则"
},
"page": {
"type": "integer",
"minimum": 1,
"description": "页码(默认 1)"
},
"page_size": {
"type": "integer",
"minimum": 1,
"maximum": 100,
"description": "每页大小(默认 10,最大 100)"
}
}
}))
}
}