Skip to main content

rust_store_core/command/
count.rs

1//! 列表 + total 计划
2
3use serde_json::{json, Map, Value};
4
5use crate::permission::{merge_owner_condition, Context};
6use crate::pipeline::{param, parse_gql};
7use crate::schema::Registry;
8use crate::types::{has_relation_predicate, is_truthy};
9
10use super::cmd::{cmd_count_documents, num_value};
11use super::query::{plan_query_ast_mut, resolve_page, Page, QueryPlan};
12
13#[derive(Debug, Clone)]
14pub struct CountQueryPlan {
15    pub query: QueryPlan,
16    pub page: Page,
17    /// `total` 统计命令(忽略 skip/limit,但含所有者条件)
18    pub count_command: Value,
19}
20
21impl CountQueryPlan {
22    pub fn to_value(&self) -> Value {
23        let mut m = self
24            .query
25            .to_value()
26            .as_object()
27            .cloned()
28            .unwrap_or_default();
29        m.insert("countCommand".to_string(), self.count_command.clone());
30        if let Some(o) = self.page.to_value().as_object() {
31            for (k, v) in o {
32                m.insert(k.clone(), v.clone());
33            }
34        }
35        Value::Object(m)
36    }
37
38    /// `hasMore = (page + 1) * pageSize < total`
39    pub fn has_more(&self, total: f64) -> bool {
40        self.page.has_more(total)
41    }
42}
43
44/// 生成「列表 + total」命令序列(对应 JS `queryWithCount`)
45pub fn plan_query_with_count(
46    gql: &str,
47    params: &Map<String, Value>,
48    registry: &Registry,
49    ctx: Option<&Context>,
50) -> Result<CountQueryPlan, String> {
51    let mut ast = parse_gql(gql)?;
52    let schema = registry.get(&ast.model)?;
53
54    let mut params = params.clone();
55    let page = resolve_page(&ast, &params);
56
57    // R5:让 page/pageSize 真正落库为 LIMIT/OFFSET。
58    // 当用户经 params 传了 page/pageSize 而 GQL 未显式引用 $skip/$limit 时,
59    // 注入合成引用 + 参数,否则 build_pipeline 不产生分页阶段 → 返回全表(A-18 根因)。
60    let wants_pagination = params.contains_key("page") || params.contains_key("pageSize");
61    if wants_pagination && !ast.params.contains_key("skip") {
62        ast.params
63            .insert("skip".to_string(), "@__core_page_skip__".to_string());
64        params.insert(
65            "__core_page_skip__".to_string(),
66            num_value(page.page * page.page_size),
67        );
68    }
69    if wants_pagination && !ast.params.contains_key("limit") {
70        ast.params
71            .insert("limit".to_string(), "@__core_page_limit__".to_string());
72        params.insert("__core_page_limit__".to_string(), num_value(page.page_size));
73    }
74
75    // 确保 GQL 实际使用上述分页值(GQL 已引用 $skip/$limit 时用推导值覆盖,防宿主参数漂移)
76    if let Some(r) = ast.params.get("skip").cloned() {
77        let key = r.get(1..).unwrap_or("").to_string();
78        params.insert(key, num_value(page.page * page.page_size));
79    }
80    if let Some(r) = ast.params.get("limit").cloned() {
81        let key = r.get(1..).unwrap_or("").to_string();
82        params.insert(key, num_value(page.page_size));
83    }
84
85    // 统计 total:取(已被 owner 注入过的)条件后再叠加一次 owner 条件,与 JS 行为一致
86    let count_filter = ast
87        .params
88        .get("condition")
89        .and_then(|r| param(&params, Some(r)).cloned())
90        .filter(is_truthy)
91        .unwrap_or_else(|| json!({}));
92    let count_filter =
93        merge_owner_condition(schema, ctx, Some(count_filter)).unwrap_or_else(|| json!({}));
94
95    // §9.6 关系聚合谓词(`$condition` 中以**关系名**作键)无法用标量 `countDocuments` 表达:
96    // Mongo 会把它当成「字段等于该对象」、SQL 无对应列 → total 与 items 静默不一致。
97    // 显式 Err(D2:绝不静默给错数)。
98    if has_relation_predicate(schema, &count_filter) {
99        return Err(
100            "query_with_count 暂不支持关系聚合谓词条件(§9.6):total 无法与 items 保持一致,\
101             请改用 query 并在调用方自行统计"
102                .to_string(),
103        );
104    }
105
106    let query = plan_query_ast_mut(ast, &mut params, registry, ctx)?;
107
108    let count_command = cmd_count_documents(schema, &count_filter);
109
110    Ok(CountQueryPlan {
111        query,
112        page,
113        count_command,
114    })
115}