---
title: "带 Attribute 同步的实体 Flow"
description: "每个实体对应一个 Flow，由 Attribute Store 同步把选定的 Attribute 复制到一张归你所有的 SQL 表中。当实体需要持久状态，而你还要用 SQL 查询这些状态时，使用这个模式，例如通过 RPC 修改、又要一起搜索的用户。"
canonical_url: "https://docs.superdurable.io/zh-Hans/design-patterns/data-storage/entity-flow-with-attribute-sync/"
source: "docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/design-patterns/data-storage/entity-flow-attribute-sync.mdx"
locale: "zh-Hans"
language: "python"
---

> 供 AI Agent 使用的全部页面索引：https://docs.superdurable.io/zh-Hans/llms.txt

# 带 Attribute 同步的实体 Flow

本页代码为 Python。其他语言：[Go](https://docs.superdurable.io/zh-Hans/design-patterns/data-storage/entity-flow-with-attribute-sync.go.md) · [Java](https://docs.superdurable.io/zh-Hans/design-patterns/data-storage/entity-flow-with-attribute-sync.java.md) · [TypeScript](https://docs.superdurable.io/zh-Hans/design-patterns/data-storage/entity-flow-with-attribute-sync.typescript.md) · [Rust](https://docs.superdurable.io/zh-Hans/design-patterns/data-storage/entity-flow-with-attribute-sync.rust.md)

每个实体对应一个 Flow，由 Attribute Store 同步把选定的 Attribute 复制到一张归你所有的 SQL 表中。当实体需要持久状态，而你还要用 SQL 查询这些状态时，使用这个模式，例如通过 RPC 修改、又要一起搜索的用户。

<a id="when-to-use-this-pattern"></a>

<a id="how-it-works"></a>

## 工作方式

用实体 ID 作为 Flow ID。它会成为表的主键。示例为每个用户保留一个 `UserProfileFlow`，在 `public.user_profiles` 中以 `user_id` 为键。Server 配置把 Attribute Store 命名为 `entityStore`。

1. **标记要同步的 Attribute。** 每个要复制的 Attribute 带上同步标记。
2. **启动时选择存储。** 启动请求在 `FlowConfig` 中指定这个存储。
3. **通过 Flow 修改状态。** RPC 更新或删除 Attribute。随后 Dex 在后台把最新的值写入表中。

<a id="core-implementation"></a>

## 核心实现

<a id="define-synced-attributes"></a>

### 定义同步的 Attribute

把每个要同步的 Attribute 加入 persistence schema。Dex 先把每个值保存在 Flow 里，再同步它。

**Python**

```python
class UserProfileFlow(Flow[None]):
    display_name = Attribute("display_name", str, sync_to_attribute_store=True)
    email = Attribute("email", str, sync_to_attribute_store=True)
    marketing_opt_in = Attribute("marketing_opt_in", bool, sync_to_attribute_store=True)
    credits = Attribute("credits", int, sync_to_attribute_store=True)
    weight = Attribute("weight", float, sync_to_attribute_store=True)
    last_logged_in_time = Attribute(
        "last_logged_in_time", datetime, sync_to_attribute_store=True
    )
    metadata = Attribute(
        "metadata", UserProfileMetadata, sync_to_attribute_store=True
    )

    def get_persistence_schema(self) -> PersistenceSchema:
        return PersistenceSchema.of(
            self.display_name,
            self.email,
            self.marketing_opt_in,
            self.credits,
            self.weight,
            self.last_logged_in_time,
            self.metadata,
        )
```

例子: [examples/python/dex_examples/patterns/entity-store/user_profile_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/entity-store/user_profile_flow.py)

<a id="update-through-a-flow-rpc"></a>

### 通过 Flow RPC 更新

更新 RPC 先校验 profile，再写入每个要同步的 Attribute。

**Python**

```python
@rpc
def update_profile(self, context: Context, input: UserProfile) -> None:
    input.validate()
    self.display_name.set(context, input.display_name)
    self.email.set(context, input.email)
    self.marketing_opt_in.set(context, input.marketing_opt_in)
    self.credits.set(context, input.credits)
    self.weight.set(context, input.weight)
    self.last_logged_in_time.set(context, input.last_logged_in_time)
    self.metadata.set(context, input.metadata)
```

例子: [examples/python/dex_examples/patterns/entity-store/user_profile_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/entity-store/user_profile_flow.py)

<a id="select-the-storage-target-at-flow-start"></a>

### 启动 Flow 时选择存储目标

启动 Flow 时，在 `FlowConfig` 中选择 Server 上配置的 Attribute Store。这个启动请求中的初始 Attribute 值也会同步。

**Python**

```python
config_override=FlowConfig(attribute_store_names=[STORE_NAME]),
```

例子: [examples/python/dex_examples/patterns/entity-store/controller.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/entity-store/controller.py)

<a id="rules-and-pitfalls"></a>

## 规则和陷阱

- **根据 Flow 做决策。** 权威状态保存在 Flow 里，所有写入都经过 Flow。Flow 决策读取它的 Attribute，而不是这张表。
- **把表当作最新状态的副本。** Dex 异步写入这张表，一行只保存最新的值。用它做读取和查询。
- **删除后列为 NULL。** 删除 Attribute 时行会保留，对应列写为 `NULL`。

列类型、同步时延和重试见 [Attribute Store 同步参考](https://docs.superdurable.io/zh-Hans/reference/server/attribute-store-sync.md)。

<a id="api-endpoints"></a>

## API 端点

- **POST /patterns/entity-store/profile**：创建 profile Flow
- **POST /patterns/entity-store/profile/update**：更新同步的字段
- **GET /patterns/entity-store/profile?userId=...**：从 Flow 读取 profile
- **POST /patterns/entity-store/profile/clear?userId=...**：删除同步的值

<a id="run-with-postgresql"></a>

## 使用 PostgreSQL 运行

[共享示例配置](https://github.com/superdurable/dex/tree/main/examples/entity-store) 会创建 `public.user_profiles`，并用 `entityStore` 配置启动 **dexcli dev**。其中有每种语言的 curl 命令。

<a id="next"></a>

## 下一步

- [顺序分块 AttributeMap](https://docs.superdurable.io/zh-Hans/design-patterns/data-storage/sequentially-chunked-attribute-map.md)
- [Attribute](https://docs.superdurable.io/zh-Hans/concepts/primitives/attribute.md)
- [把 Attribute 数据同步到外部存储](https://docs.superdurable.io/zh-Hans/concepts/primitives/attribute.md#attribute-store-projection)：Attribute Store 同步的配置步骤。
