> ## Documentation Index
> Fetch the complete documentation index at: https://private-7c7dfe99-revert-104359-revert-104251-parquet-single.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 使用 ClickPipes 中的数据源迁移 PostgreSQL 数据

> 了解如何使用 ClickPipes 将 PostgreSQL 数据库迁移到 ClickHouse Managed Postgres。

export const Image = ({img, alt, size = "lg"}) => {
  const normalizedSize = ["sm", "md", "lg"].includes(size) ? size : "lg";
  return <div className={`ch-image-${normalizedSize}`}>
      <Frame>
        <img src={img} alt={alt} />
      </Frame>
    </div>;
};

export const BetaBadge = ({link, galaxyTrack, galaxyEvent}) => {
  if (link) {
    return <a href={link} target="_blank" rel="noopener noreferrer" className="betaBadge" onClick={galaxyTrack && galaxyEvent ? galaxyOnClick(galaxyEvent) : undefined}>
                <span>Beta</span>
            </a>;
  }
  return <a href="https://clickhouse.com/docs/reference/settings/beta-and-experimental-features#beta-features" className="betaBadge">
            <span>Beta 版功能</span>
        </a>;
};

<BetaBadge link="https://clickhouse.com/cloud/postgres" galaxyTrack={true} galaxyEvent="docs.managed-postgres.migration-guide-clickhouse-cloud-beta" />

ClickHouse Cloud 现已提供 ClickPipes，可将外部 PostgreSQL 数据库迁移到 Managed Postgres 服务。这项内置集成简化了整个流程，帮助您连接源数据库、导出 schema、将其导入 Managed Postgres，并设置持续复制。

<div id="prerequisites">
  ## 前置条件
</div>

* 能够使用具有复制权限的用户访问源 PostgreSQL 数据库。请按照与您的数据源对应的设置指南进行配置：
  * [Amazon RDS Postgres](/zh/integrations/clickpipes/postgres/source/rds)
  * [Amazon Aurora Postgres](/zh/integrations/clickpipes/postgres/source/aurora)
  * [Supabase Postgres](/zh/integrations/clickpipes/postgres/source/supabase)
  * [Google Cloud SQL Postgres](/zh/integrations/clickpipes/postgres/source/google-cloudsql)
  * [Azure PostgreSQL 灵活服务器](/zh/integrations/clickpipes/postgres/source/azure-flexible-server-postgres)
  * [Neon Postgres](/zh/integrations/clickpipes/postgres/source/neon-postgres)
  * [Crunchy Bridge Postgres](/zh/integrations/clickpipes/postgres/source/crunchy-postgres)
  * [TimescaleDB](/zh/integrations/clickpipes/postgres/source/timescale)
  * [通用 Postgres 源](/zh/integrations/clickpipes/postgres/source/generic)，适用于任何其他提供商或自托管实例
* 准备一个 ClickHouse Managed Postgres 服务作为迁移目标。如果您还没有，请参阅[快速入门](/zh/products/managed-postgres/quickstart)。
* 在本地计算机上安装 `pg_dump` 和 `psql`。两者都包含在标准 PostgreSQL 客户端工具中。

<div id="considerations">
  ## 迁移前注意事项
</div>

* **DDL 传播**：持续复制 (CDC) 会捕获 DML 操作和 `ADD COLUMN`。其他 DDL 更改 (如 `DROP COLUMN` 和 `ALTER COLUMN`) 不会自动传播，必须在目标端手动执行。

<Note>
  如果您在迁移过程中遇到问题，请查看 [Managed Postgres Migrations FAQ](/zh/products/managed-postgres/migrations/faq)，了解常见错误及其解决方案。
</Note>

<div id="step-1-connect">
  ## 步骤 1：连接到源数据库
</div>

打开 [ClickHouse Cloud 控制台](https://clickhouse.cloud)，选择您的 Managed Postgres 服务。

<Image img="https://mintcdn.com/private-7c7dfe99-revert-104359-revert-104251-parquet-single/g8hpkImHjWTMvqC-/images/managed-postgres/pgpg/servicecard.webp?fit=max&auto=format&n=g8hpkImHjWTMvqC-&q=85&s=289741405a0299a5867abc1423c56bc3" alt="ClickHouse Cloud 服务列表中的 Managed Postgres 服务卡片" size="lg" border width="3680" height="2392" data-path="images/managed-postgres/pgpg/servicecard.webp" />

在左侧边栏中，点击 **数据源**。

<Image img="https://mintcdn.com/private-7c7dfe99-revert-104359-revert-104251-parquet-single/g8hpkImHjWTMvqC-/images/managed-postgres/pgpg/overview.webp?fit=max&auto=format&n=g8hpkImHjWTMvqC-&q=85&s=5990542940214be859f2a20c494502b2" alt="Managed Postgres 服务侧边栏中的数据源条目" size="lg" border width="3680" height="2392" data-path="images/managed-postgres/pgpg/overview.webp" />

点击 **开始导入**。

<Image img="https://mintcdn.com/private-7c7dfe99-revert-104359-revert-104251-parquet-single/g8hpkImHjWTMvqC-/images/managed-postgres/pgpg/startimport.webp?fit=max&auto=format&n=g8hpkImHjWTMvqC-&q=85&s=4716cc9d860f2f0d9522b6ea99e0c0e9" alt="带有“开始导入”按钮的数据源页面" size="lg" border width="3680" height="2392" data-path="images/managed-postgres/pgpg/startimport.webp" />

填写源 PostgreSQL 数据库的连接信息：主机、端口、用户名、密码和数据库名称。如果源数据库要求使用 **TLS**，请启用该选项。

如果您需要通过私网连接访问源数据库，可以选择 **SSH 隧道** 并提供所需的 SSH 信息。这样，迁移便可安全连接到无法从公网访问的数据库。

选择一种摄取方式：

* **初始加载 + CDC** — 先复制现有数据，然后持续将后续变更同步到目标端。
* **仅初始加载** — 一次性复制，不进行持续复制。
* **仅 CDC** — 跳过初始复制，仅复制从此刻开始产生的新变更。

<Image img="https://mintcdn.com/private-7c7dfe99-revert-104359-revert-104251-parquet-single/g8hpkImHjWTMvqC-/images/managed-postgres/pgpg/migrationform.webp?fit=max&auto=format&n=g8hpkImHjWTMvqC-&q=85&s=79dfe4a2ce35b448c0c59e1ff4e97582" alt="步骤 1：带有摄取方式选项的源数据库连接表单" size="lg" border width="3680" height="2392" data-path="images/managed-postgres/pgpg/migrationform.webp" />

点击 **下一步**。

<div id="automated-schema-migration">
  ## 自动 schema 迁移
</div>

<Image img="https://mintcdn.com/private-7c7dfe99-revert-104359-revert-104251-parquet-single/76_4bqp95JvxWs34/images/managed-postgres/pg_dump_restore/automated.webp?fit=max&auto=format&n=76_4bqp95JvxWs34&q=85&s=18e2f35e5eb5012e329be8aed22313c4" alt="第 2 步：使用目标数据库选择器自动迁移 schema" size="lg" border width="2632" height="742" data-path="images/managed-postgres/pg_dump_restore/automated.webp" />

选择此选项后，ClickPipe 会在创建完成后的 [Setup 阶段](/zh/integrations/clickpipes/postgres/lifecycle#setup) 自动获取源数据库的 schema，并将其应用到您的 Managed Postgres 服务。

此功能要求**目标数据库为空**，因为无论您稍后在向导中选择哪些表，它都会从源数据库获取所有数据库对象。如果目标数据库中已有数据，或需要更灵活的自定义配置，则必须改用 [**手动**](#manual-schema-migration) 模式。

从下拉列表中选择目标数据库，或单击**创建新数据库**来预配一个数据库。

<Image img="https://mintcdn.com/private-7c7dfe99-revert-104359-revert-104251-parquet-single/76_4bqp95JvxWs34/images/managed-postgres/pg_dump_restore/newdb.webp?fit=max&auto=format&n=76_4bqp95JvxWs34&q=85&s=2efc6920d5bac8606aa67669e1d81d77" alt="创建新 Postgres 数据库对话框" size="lg" border width="1642" height="742" data-path="images/managed-postgres/pg_dump_restore/newdb.webp" />

<div id="monitoring">
  ### 监控
</div>

您可以在 ClickPipes 详情视图中跟踪 schema 迁移进度。**日志**会显示 schema 迁移的状态，以及过程中遇到的任何错误。

此模式存在以下限制：

* 使用 SSH 隧道的管道无法使用自动 schema 迁移。必须[手动导出和导入 schema](#manual-schema-migration)。

<div id="manual-schema-migration">
  ## 手动 schema 迁移
</div>

如果目标数据库中已有数据，或者希望采用比自动模式所要求的全新环境更灵活的自定义设置，可以在此选择 **手动** 模式。

<Image img="https://mintcdn.com/private-7c7dfe99-revert-104359-revert-104251-parquet-single/76_4bqp95JvxWs34/images/managed-postgres/pg_dump_restore/manual.webp?fit=max&auto=format&n=76_4bqp95JvxWs34&q=85&s=c576b22c0898bcdf971c58091be56a0e" alt="第 2 步：使用 pg_dump 导出命令进行手动 schema 迁移" size="lg" border width="2632" height="1022" data-path="images/managed-postgres/pg_dump_restore/manual.webp" />

<div id="step-2-export-schema">
  ### 导出数据库 schema
</div>

向导会显示一条已预填源连接信息的 `pg_dump` 命令。在终端中运行它：

<Image img="https://mintcdn.com/private-7c7dfe99-revert-104359-revert-104251-parquet-single/g8hpkImHjWTMvqC-/images/managed-postgres/pgpg/nextexport.webp?fit=max&auto=format&n=g8hpkImHjWTMvqC-&q=85&s=24b6cd4f45113a8c2df3404de2b38fb2" alt="步骤 2：用于导出 schema 的 pg_dump 命令" size="lg" border width="3680" height="2392" data-path="images/managed-postgres/pgpg/nextexport.webp" />

```shell theme={null}
pg_dump \
  -h <source_host> \
  -U <source_user> \
  -d <source_database> \
  --schema-only \
  -f pg.sql
```

这会在当前目录中创建 `pg.sql`。

<Image img="https://mintcdn.com/private-7c7dfe99-revert-104359-revert-104251-parquet-single/g8hpkImHjWTMvqC-/images/managed-postgres/pgpg/psqlexport.webp?fit=max&auto=format&n=g8hpkImHjWTMvqC-&q=85&s=964b2087e1cf5957ff507a4287a90b09" alt="运行 pg_dump 后的终端输出" size="lg" border width="1452" height="422" data-path="images/managed-postgres/pgpg/psqlexport.webp" />

点击 **下一步**。

<div id="step-3-import-schema">
  ### 将 schema 导入您的 Managed Postgres 服务
</div>

从下拉列表中选择目标数据库，或点击 **创建新数据库** 来创建新数据库。

向导会显示一条 `psql` 命令，用于将 schema 转储导入您的 Managed Postgres 服务。在终端中运行它：

<Image img="https://mintcdn.com/private-7c7dfe99-revert-104359-revert-104251-parquet-single/g8hpkImHjWTMvqC-/images/managed-postgres/pgpg/nextimport.webp?fit=max&auto=format&n=g8hpkImHjWTMvqC-&q=85&s=d49484c6fb84089a91ee7cc7e92b3544" alt="步骤 3：用于导入 schema 的 psql 命令" size="lg" border width="3680" height="2392" data-path="images/managed-postgres/pgpg/nextimport.webp" />

```shell theme={null}
psql \
  -h <target_host> \
  -p 5432 \
  -U <target_user> \
  -d <target_database> \
  -f pg.sql
```

<Image img="https://mintcdn.com/private-7c7dfe99-revert-104359-revert-104251-parquet-single/g8hpkImHjWTMvqC-/images/managed-postgres/pgpg/psqlimport.webp?fit=max&auto=format&n=g8hpkImHjWTMvqC-&q=85&s=79ff27ca6baab542a892a954c90f8313" alt="运行 psql 导入 schema 后的终端输出" size="lg" border width="2362" height="762" data-path="images/managed-postgres/pgpg/psqlimport.webp" />

点击 **下一步**。

<div id="step-4-ingestion-settings">
  ## Step 4: 配置摄取设置
</div>

指定用于逻辑复制的 publication。将此项留空时，系统会自动创建 publication。

展开 **高级复制设置** 以调整吞吐量：

| 设置         | 默认值     | 说明                      |
| ---------- | ------- | ----------------------- |
| 同步间隔 (秒)   | 10      | 轮询 replication slot 的频率 |
| 初始加载的并行线程数 | 4       | 批量复制阶段使用的线程数            |
| 拉取批次大小     | 100,000 | 每个复制批次拉取的行数             |
| 每个分区快照的行数  | 100000  | 大表快照的分区大小               |
| 并行创建快照的表数量 | 1       | 并行执行快照的表数量              |

<Image img="https://mintcdn.com/private-7c7dfe99-revert-104359-revert-104251-parquet-single/g8hpkImHjWTMvqC-/images/managed-postgres/pgpg/advancedsettings.webp?fit=max&auto=format&n=g8hpkImHjWTMvqC-&q=85&s=694cd7a04e7f0b4328d6d3b27f54928d" alt="第 4 步：包含 publication 和高级复制选项的摄取设置表单" size="lg" border width="3680" height="2392" data-path="images/managed-postgres/pgpg/advancedsettings.webp" />

点击 **下一步**。

<div id="step-5-select-tables">
  ## 第 5 步：选择表
</div>

选择要复制的表。表会按 schema 分组显示。你可以选择单个表，也可以展开某个 schema，一次性选择其中的所有表。

<Image img="https://mintcdn.com/private-7c7dfe99-revert-104359-revert-104251-parquet-single/g8hpkImHjWTMvqC-/images/managed-postgres/pgpg/tablepicker.webp?fit=max&auto=format&n=g8hpkImHjWTMvqC-&q=85&s=f115cc6daa9c88ffdbe0bdcc5c49c3d8" alt="第 5 步：按 schema 分组的表选择器，带有“Create migration”按钮" size="lg" border width="3680" height="2392" data-path="images/managed-postgres/pgpg/tablepicker.webp" />

点击 **Create migration**。

<div id="monitor">
  ## 监控迁移
</div>

创建迁移后，你会在**数据源**中看到它，状态为 **运行中**。

<Image img="https://mintcdn.com/private-7c7dfe99-revert-104359-revert-104251-parquet-single/g8hpkImHjWTMvqC-/images/managed-postgres/pgpg/migrationlist.webp?fit=max&auto=format&n=g8hpkImHjWTMvqC-&q=85&s=f48d58085d584d813b98568c3b21f5b8" alt="显示正在运行的迁移的数据源列表" size="lg" border width="3680" height="2392" data-path="images/managed-postgres/pgpg/migrationlist.webp" />

点击该迁移以打开详情视图。**Tables** 选项卡会显示每个表的初始加载进度，包括已处理的行数、分区数，以及每个分区的平均耗时。**Metrics** 选项卡则会在 CDC 开始后显示复制延迟和吞吐量。

<Image img="https://mintcdn.com/private-7c7dfe99-revert-104359-revert-104251-parquet-single/g8hpkImHjWTMvqC-/images/managed-postgres/pgpg/initialload.webp?fit=max&auto=format&n=g8hpkImHjWTMvqC-&q=85&s=600899644142bb7b4034953845d86565" alt="显示各表初始加载统计信息的迁移详情视图" size="lg" border width="3680" height="2392" data-path="images/managed-postgres/pgpg/initialload.webp" />

<div id="post-migration">
  ## 迁移后任务
</div>

初始加载完成后，如果使用 CDC，且复制延迟几乎为零：

**验证行数。** 在切换流量之前，对源端和目标端的关键表进行抽查：

```sql theme={null}
SELECT COUNT(*) FROM public.orders;
```

**停止向源端写入。** 暂停应用写入。要在切换期间强制设为只读模式：

```sql theme={null}
ALTER DATABASE <source_db> SET default_transaction_read_only = on;
```

**确认复制已追上。** 比较源端和目标端的最新一行：

```sql theme={null}
-- 在源端和目标端均执行
SELECT MAX(id), MAX(updated_at) FROM public.orders;
```

**重置序列。** 使序列与各表中的当前最大值保持一致：

```sql theme={null}
DO $$
DECLARE r RECORD;
BEGIN
    FOR r IN
        SELECT
            n.nspname AS schema_name,
            c.relname AS table_name,
            a.attname AS column_name,
            pg_get_serial_sequence(format('%I.%I', n.nspname, c.relname), a.attname) AS seq_name
        FROM pg_class c
        JOIN pg_namespace n ON n.oid = c.relnamespace
        JOIN pg_attribute a ON a.attrelid = c.oid
        WHERE c.relkind = 'r'
            AND a.attnum > 0
            AND NOT a.attisdropped
            AND n.nspname NOT IN ('pg_catalog', 'information_schema')
    LOOP
        IF r.seq_name IS NOT NULL THEN
            EXECUTE format(
                'SELECT setval(%L, COALESCE((SELECT MAX(%I) FROM %I.%I), 0) + 1, false)',
                r.seq_name, r.column_name, r.schema_name, r.table_name
            );
        END IF;
    END LOOP;
END $$;
```

**切换应用流量。** 将读写流量切换到你的 Managed Postgres 服务，并监控错误、约束冲突以及复制状态是否正常。

**清理。**  完成切换并确认新服务运行正常后，从**数据源**中删除此次迁移。如果你使用了 CDC，请从源端删除 replication slot 以释放资源：

```sql theme={null}
SELECT pg_drop_replication_slot('<slot_name>');
```

<div id="next-steps">
  ## 后续步骤
</div>

* [Managed Postgres 快速入门](/zh/products/managed-postgres/quickstart)
* [Managed Postgres 连接信息](/zh/products/managed-postgres/connection)
* [ClickPipes Postgres FAQ](/zh/integrations/clickpipes/postgres/faq)
