Skip to main content

rust_store_core/computes/
cache.rs

1//! schema 维度缓存:字段默认值 / 计算列零值 / fn 与 asyncFn 声明列表
2
3use serde_json::{Map, Value};
4
5use crate::schema::Schema;
6use crate::types::get_default;
7
8/// fn / asyncFn 计算列的声明信息(fn_ref 绑定 Host 实现)
9#[derive(Debug, Clone)]
10pub struct ComputeEntry {
11    pub key: String,
12    /// 回调标识(`fnRef`,缺省 = key 名)
13    pub fn_ref: String,
14    pub depends: Vec<String>,
15}
16
17#[derive(Debug, Clone, Default)]
18pub struct Cache {
19    /// 有默认值的字段:`key → 默认值`
20    pub field_defaults: Map<String, Value>,
21    /// 计算列按 `type` 推出的零值:`key → 零值`
22    pub compute_defaults: Map<String, Value>,
23    pub fn_list: Vec<ComputeEntry>,
24    pub async_fn_list: Vec<ComputeEntry>,
25}
26
27/// 构建 schema 维度的默认值 / 计算列缓存(对应 JS `_ensureCache`)
28pub fn ensure_cache(schema: &Schema) -> Cache {
29    let mut field_defaults = Map::new();
30    for (key, field) in &schema.fields {
31        // read 后处理 `fill_defaults` 只应补「schema 显式 `default`」的字段;
32        // 不按类型派生零值注入,否则存储 null/缺失 的标量被覆盖为 ""/0
33        // (H-01:summary/categoryId 无显式 default,null→null、缺失→缺失)。
34        // 写入路径的 `apply_defaults_and_computes` 仍走 `field_default` 保留类型默认。
35        if let Some(d) = field.default.as_ref() {
36            if !d.is_null() {
37                field_defaults.insert(key.clone(), d.clone());
38            }
39        }
40    }
41
42    let mut compute_defaults = Map::new();
43    let mut fn_list = Vec::new();
44    let mut async_fn_list = Vec::new();
45    for (key, comp) in &schema.computes {
46        compute_defaults.insert(key.clone(), get_default(&comp.comp_type));
47        let fn_ref = comp.fn_ref.clone().unwrap_or_else(|| key.clone());
48        if comp.has_fn {
49            fn_list.push(ComputeEntry {
50                key: key.clone(),
51                fn_ref: fn_ref.clone(),
52                depends: comp.depends.clone(),
53            });
54        }
55        if comp.has_async_fn {
56            async_fn_list.push(ComputeEntry {
57                key: key.clone(),
58                fn_ref,
59                depends: comp.depends.clone(),
60            });
61        }
62    }
63
64    Cache {
65        field_defaults,
66        compute_defaults,
67        fn_list,
68        async_fn_list,
69    }
70}