---
title: "带 Attribute 同步的实体 Flow"
description: "每个实体对应一个 Flow，由 Attribute Store 同步把选定的 Attribute 复制到一张可以查询的 SQL 表中（以前叫作带 SQL 投影的实体 Flow）。"
canonical_url: "https://docs.superdurable.io/zh-Hans/design-patterns/data-storage/entity-flow-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-attribute-sync.go.md) · [Java](https://docs.superdurable.io/zh-Hans/design-patterns/data-storage/entity-flow-attribute-sync.java.md) · [TypeScript](https://docs.superdurable.io/zh-Hans/design-patterns/data-storage/entity-flow-attribute-sync.typescript.md) · [Rust](https://docs.superdurable.io/zh-Hans/design-patterns/data-storage/entity-flow-attribute-sync.rust.md)

每个实体对应一个 Flow，由 Attribute Store 同步把选定的 Attribute 复制到一张可以查询的 SQL 表中（以前叫作带 SQL 投影的实体 Flow）。

实体是一个业务对象，例如一个用户。SQL 表归你的应用所有。权威状态保存在 Flow 里，所有写入都经过 Flow。Dex 异步更新 SQL 表，表中只保存最新的值，用于读取和查询。

可运行示例为每个用户保留一个 `UserProfileFlow`。它的 Flow ID 就是 `public.user_profiles` 表的 `user_id` 主键。Server 配置把目标 Attribute Store 命名为 `entityStore`。

## 适用场景

当一个实体需要持久化状态或通过 RPC 更新，而你的应用还要在数据库中查询它的最新状态时，使用这个模式。不要根据 SQL 表做 Flow 决策，应读取 Flow 状态。

## 工作方式

用实体 ID 作为 Flow ID。标记每个要投影的 Attribute，并在启动 Flow 时选择 Attribute Store。通过 Flow 更新或删除 Attribute，Dex 会把结果值投影到 SQL。配置见[在 Flow 之后保留数据](https://docs.superdurable.io/zh-Hans/concepts/primitives/attribute.md#attribute-store-projection)。

示例投影 text、boolean、integer、double、datetime 和 JSON 值。删除 Attribute 时，SQL 行会保留，对应列投影为 `NULL`。列类型、同步时延和重试见 [Attribute Store sync reference](https://docs.superdurable.io/zh-Hans/reference/server/attribute-store-sync.md)。

## 核心实现

### 定义同步的 Attribute

每种 SDK 都把同一组 profile 字段标记为需要投影。Flow 的 persistence schema 包含这些 Attribute，所以 Dex 先把每个值持久保存，再把它同步到 SQL。

**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)

### 通过 Flow RPC 更新

客户端调用这个 RPC 更新 profile。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)

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

Attribute Store 在 Server 上配置。启动 Flow 时，在 `FlowConfig` 中选择它。同一个启动请求中的初始 Attribute 值也会投影到 SQL。

**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)

## API endpoints

- **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=...**：删除同步的值

## 使用 PostgreSQL 运行

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

## 下一步

- [顺序分块 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)
- [在 Flow 之后保留数据](https://docs.superdurable.io/zh-Hans/concepts/primitives/attribute.md#attribute-store-projection)
