

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 使用兼容 Aurora PostgreSQL 的文件编码将 BLOB 文件加载至文本中
<a name="load-blob-files-into-text-by-using-file-encoding-in-aurora-postgresql-compatible"></a>

*hanu Ganesh Gudivada 和 Jeevan Shetty，Amazon Web Services*

## Summary
<a name="load-blob-files-into-text-by-using-file-encoding-in-aurora-postgresql-compatible-summary"></a>

通常，在迁移过程中，您必须处理从本地文件系统上的文件加载的、非结构化和结构化数据。数据也可采用与数据库字符集不同的字符集。

这些文件包含以下类型数据：
+ **元数据** - 此数据描述了文件结构。
+ **半结构化数据** - 这些是特定格式的文本字符串，例如 JSON 或 XML。你可以对此类数据做出断言，例如将始终以“<”开头” 或不包含任何换行符”。
+ **全文** - 此数据通常包含所有类型的字符，包括换行符和引号字符。它还可能由 UTF-8 格式的多字节字符构成。
+ **二进制数据**-此数据可能包含字节或字节组合，包括空值和 end-of-file标记。

混合加载这些类型的数据，可能是一项挑战。

该模式可用于本地 Oracle 数据库、亚马逊弹性计算云 (AWS) 云上的亚马逊弹性计算云 (Amazon EC2) 实例上的 Oracle 数据库，以及适用于 Oracle 数据库的亚马逊关系数据库服务 (Amazon RDS)。例如，这种模式使用的是与 Amazon Aurora PostgreSQL-Compatible Edition。

在 Oracle 数据库中，借助 `BFILE`（二进制文件）指针、`DBMS_LOB` 软件包和 Oracle 系统函数，您可以从文件加载并使用字符编码转换为 CLOB。由于 PostgreSQL 在迁移到 Amazon Aurora PostgreSQL-Compatible Edition 数据库时不支持 BLOB 数据类型，因此必须将这些函数转换为兼容 PostgreSQL 的脚本。

此模式提供了两种将文件加载至兼容 Amazon Aurora PostgreSQL 的数据库中的单个数据库列中的方法：
+ 方法 1 — 您通过使用带有编码选项的扩展 `table_import_from_s3` `aws_s3` 函数，从 Amazon Simple Storage Service (Amazon S3) 存储桶导入数据。
+ 方法 2 — 在数据库外部编码为十六进制，然后解码以在数据库内部查看 `TEXT`。

我们建议使用 Aurora PostgreSQL，因为PostgreSQL-Compatible 可以直接与 `aws_s3` 扩展集成。

本文介绍：将包含电子邮件模板的平面文件加载到 Amazon Aurora PostgreSQL-Compatible 数据库中的示例，该模板具有多字节字符和不同的格式。

## 先决条件和限制
<a name="load-blob-files-into-text-by-using-file-encoding-in-aurora-postgresql-compatible-prereqs"></a>

**先决条件**
+ 一个有效的 Amazon Web Services account
+ 一个 Amazon RDS 实例或 Aurora PostgreSQL-Compatible 实例
+ 对 SQL 和 Relational Database Management System (RDBMS) 有基本了解
+ Amazon Simple Storage Service (Amazon S3) 存储桶。
+ 了解 Oracle 和 PostgreSQL 中的系统函数
+ RPM Packag HexDump e-XXD-0.1.1（包含在亚马逊 Linux 2 中）
**注意**  
即将终止对 Amazon Linux 2 的支持。欲了解更多信息，请参阅[亚马逊 Linux 2 FAQs](https://aws.amazon.com/amazon-linux-2/faqs/)。

**限制**
+ 对于 `TEXT` 数据类型，可以存储的最长字符串约为 1 GB。

**产品版本**
+ Aurora 支持 [Amazon Aurora PostgreSQL 更新](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraPostgreSQLReleaseNotes/AuroraPostgreSQL.Updates.html)中列出的 PostgreSQL 版本。

## 架构
<a name="load-blob-files-into-text-by-using-file-encoding-in-aurora-postgresql-compatible-architecture"></a>

**目标技术堆栈**
+ Aurora PostgreSQL-Compatible

**目标架构**

*方法 1 — 使用 aws\$1s3.table\$1import\$1from\$1s3*

将包含多字节字符和自定义格式的电子邮件模板文件从本地服务器传输至 Amazon S3。本文提供的自定义数据库函数使用带 `file_encoding` 的 `aws_s3.table_import_from_s3` 函数将文件加载至数据库，并将查询结果以 `TEXT` 数据类型的形式返回。

![\[从本地服务器到 Aurora 数据库 TEXT 输出的四步流程。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/cbf63cac-dcea-4e18-ab4f-c4f6296f60e7/images/9c46b385-e8a0-4e50-b856-d522c44d79e3.png)


1. 文件将传输至 Staging S3 存储桶。

1. 文件将上传至 Amazon Aurora PostgreSQL-Compatible 数据库。

1. 使用 pgAdmin 客户端，将自定义 `load_file_into_clob` 函数部署至 Aurora 数据库。

1. 自定义函数内部 `table_import_from_s3` 与 file\$1encoding 一起使用。该函数的输出是通过使用 `array_to_string` 和 `array_agg` 作为 `TEXT` 输出获得。

*方法 2 — 在数据库外部编码为十六进制，然后解码以查看数据库内文本*

来自本地服务器或本地文件系统的文件将转换至十六进制转储。然后，该文件将作为 `TEXT` 字段导入 PostgreSQL。

![\[使用十六进制转储的三步流程。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/cbf63cac-dcea-4e18-ab4f-c4f6296f60e7/images/563038ca-f890-4874-85df-d0f82d99800a.png)


1. 使用 `xxd -p` 选项在命令行中将文件转换为十六进制转储。

1. 使用 `\copy` 选项将十六进制转储文件上传至兼容 Aurora PostgreSQL 文件，然后将十六进制转储文件解码为二进制。

1. 编码二进制数据，以返回为 `TEXT`。

## 工具
<a name="load-blob-files-into-text-by-using-file-encoding-in-aurora-postgresql-compatible-tools"></a>

**Amazon Web Services**
+ [Amazon Aurora PostgreSQL 兼容版](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.AuroraPostgreSQL.html)是一个完全托管的、与 ACID 兼容的关系数据库引擎，可帮助您建立、运行和扩展 PostgreSQL 部署。
+ [AWS 命令行界面（AWS CLI）](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)是一种开源工具，它可帮助您通过命令行 Shell 中的命令与 Amazon Web Services 交互。

**其他工具**
+ [pgadmin4](https://www.pgadmin.org/) 是 PostgreSQL 的开源管理和开发平台。pgadmin4 可以在 Linux、Unix、Mac OS 和 Windows 上使用 postgreSQL 管理 PostgreSQL。  

## 操作说明
<a name="load-blob-files-into-text-by-using-file-encoding-in-aurora-postgresql-compatible-epics"></a>

### 方法 1：将数据从 Amazon S3 导入至兼容 Amazon S3 的 Aurora
<a name="approach-1-import-data-from-amazon-s3-to-aurora-postgresql-compatible"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 启动实 EC2 例。 | 有关启动实例的说明，请参阅[启动实例](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/LaunchingAndUsingInstances.html)。 | 数据库管理员 | 
| 安装 PostgreSQL 客户端 pgAdmin 工具。 | 下载并安装 [pgAdmin](https://www.pgadmin.org/download/)。 | 数据库管理员 | 
| 创建一个 IAM 策略。 | 创建名为 `aurora-s3-access-pol`的 AWS Identity and Acess Management (IAM) policy，用于授予对存储文件的 S3 存储桶的访问权限。请使用以下代码，将 `<bucket-name>` 替换为您的 S3 存储桶名称。<pre>{<br />    "Version": "2012-10-17",		 	 	 <br />    "Statement": [<br />        {<br />            "Effect": "Allow",<br />            "Action": [<br />                "s3:GetObject",<br />                "s3:AbortMultipartUpload",<br />                "s3:DeleteObject",<br />                "s3:ListMultipartUploadParts",<br />                "s3:PutObject",<br />                "s3:ListBucket"<br />            ],<br />            "Resource": [<br />                "arn:aws:s3:::<bucket-name>/*",<br />                "arn:aws:s3:::<bucket-name>"<br />            ]<br />        }<br />    ]<br />}</pre> | 数据库管理员 | 
| 创建 IAM 角色，将对象从 Amazon S3 导入至 Aurora PostgreSQL-Compatible。 | 使用以下代码创建名`aurora-s3-import-role`为[AssumeRole](https://docs.amazonaws.cn/en_us/STS/latest/APIReference/API_AssumeRole.html)信任关系的 IAM 角色。 `AssumeRole`允许 Aurora 代表您访问其他 AWS 服务。<pre>{<br />  "Version": "2012-10-17",		 	 	 <br />  "Statement": [<br />    {<br />      "Effect": "Allow","Principal": {<br />        "Service": "rds.amazonaws.com"<br />      },"Action": "sts:AssumeRole"<br />    }<br />  ]<br />}<br /></pre> | 数据库管理员 | 
| 将 IAM 角色与集群关联。 | 要将 IAM 角色与 Aurora PostgreSQL-Compatible 数据库集群关联，请运行以下 AWS CLI 命令。将 `<Account-ID>` 更改为托管 Aurora PostgreSQL-Compatible 数据库的 Amazon Web Services account ID。这使与 Aurora PostgreSQL 兼容的数据库可访问 S3 存储桶。<pre>aws rds add-role-to-db-cluster --db-cluster-identifier aurora-postgres-cl<br />--feature-name s3Import --role-arn arn:aws:iam::<Account-ID>:role/aurora-s3-import-role</pre> | 数据库管理员 | 
| 将示例上传到 Amazon S3。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/load-blob-files-into-text-by-using-file-encoding-in-aurora-postgresql-compatible.html) | 数据库管理员、应用程序所有者 | 
| 部署自定义函数。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/load-blob-files-into-text-by-using-file-encoding-in-aurora-postgresql-compatible.html) | 应用程序所有者，数据库管理员 | 
| 运行可将数据导入数据库的自定义函数。 | 运行以下 SQL 命令，将尖括号中的项目替换为相应值。<pre>select load_file_into_clob('aws-s3-import-test'::text,'us-west-1'::text,'employee.salary.event.notification.email.vm'::text);</pre>运行命令之前，请将尖括号中的项目替换为相应的值，如以下示例所示。<pre>Select load_file_into_clob('aws-s3-import-test'::text,'us-west-1'::text,'employee.salary.event.notification.email.vm'::text);</pre>该命令从 Amazon S3 加载文件并将输出返回为 `TEXT`。 | 应用程序所有者，数据库管理员 | 

### 方法 2：在本地 Linux 系统中将模板文件转换至十六进制转储
<a name="approach-2-convert-the-template-file-into-a-hex-dump-in-a-local-linux-system"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 将模板文件转换至十六进制转储。 | Hexdump 实用程序以十六进制、十进制、八进制或 ASCII 格式显示二进制文件内容。该 `hexdump` 命令是 `util-linux` 软件包的一部分，已预先安装在 Linux 发行版中。Hexdump RPM 软件包也是 Amazon Linux 2 的一部分。(: 亚马逊 Linux 2 的支持已接近终止。 欲了解更多信息，请参阅[亚马逊 Linux 2 FAQs](https://aws.amazon.com/amazon-linux-2/faqs/).)要将文件内容转换至十六进制转储，请运行以下 Shell 命令。<pre>xxd -p </path/file.vm> | tr -d '\n' > </path/file.hex></pre>将路径和文件替换为相应的值，如以下示例所示。<pre>xxd -p employee.salary.event.notification.email.vm | tr -d '\n' > employee.salary.event.notification.email.vm.hex</pre> | 数据库管理员 | 
| 将十六进制转储文件加载至数据库架构。 | 使用以下命令将十六进制转储文件加载至 Aurora PostgreSQL-Compatible 数据库。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/load-blob-files-into-text-by-using-file-encoding-in-aurora-postgresql-compatible.html) | 数据库管理员 | 

## 相关资源
<a name="load-blob-files-into-text-by-using-file-encoding-in-aurora-postgresql-compatible-resources"></a>

**参考**
+ [将 PostgreSQL 数据库用作 AWS Database Migration Service 的目标](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.PostgreSQL.html)
+ [参照 PostgreSQL Compatibility (12.4) 迁移手册将 Oracle Database 19c 迁移至 Amazon Aurora](https://d1.awsstatic.com/whitepapers/Migration/oracle-database-amazon-aurora-postgresql-migration-playbook-12.4.pdf)
+ [创建 IAM policy](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create.html)
+ [将 IAM 角色与 Amazon Aurora MySQL 数据库集群关联](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraMySQL.Integrating.Authorizing.IAM.AddRoleToDBCluster.html)
+ [pgAdmin](https://www.pgadmin.org/)

**教程**
+ [Amazon RDS 入门](https://aws.amazon.com/rds/getting-started/)
+ [从 Oracle 迁移到 Amazon Aurora](https://aws.amazon.com/getting-started/projects/migrate-oracle-to-amazon-aurora/)

## 附加信息
<a name="load-blob-files-into-text-by-using-file-encoding-in-aurora-postgresql-compatible-additional"></a>

**load\$1file\$1into\$1clob custom function**

```
CREATE OR REPLACE FUNCTION load_file_into_clob(
    s3_bucket_name text,
    s3_bucket_region text,
    file_name text,
    file_delimiter character DEFAULT '&'::bpchar,
    file_encoding text DEFAULT 'UTF8'::text)
    RETURNS text
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
AS $BODY$
DECLARE
    blob_data BYTEA;
    clob_data TEXT;
    l_table_name CHARACTER VARYING(50) := 'file_upload_hex';
    l_column_name CHARACTER VARYING(50) := 'template';
    l_return_text TEXT;
    l_option_text CHARACTER VARYING(150);
    l_sql_stmt CHARACTER VARYING(500);
        
BEGIN
    
    EXECUTE format ('CREATE TEMPORARY TABLE %I (%I text, id_serial serial)', l_table_name, l_column_name);
    
    l_sql_stmt := 'select ''(format text, delimiter ''''' || file_delimiter || ''''', encoding ''''' || file_encoding ||  ''''')'' ';
    
    EXECUTE FORMAT(l_sql_stmt)
    INTO l_option_text;
    
    EXECUTE FORMAT('SELECT aws_s3.table_import_from_s3($1,$2,$6, aws_commons.create_s3_uri($3,$4,$5))')
    INTO l_return_text
    USING l_table_name, l_column_name, s3_bucket_name, file_name,s3_bucket_region,l_option_text;
    
    EXECUTE format('select array_to_string(array_agg(%I order by id_serial),E''\n'') from %I', l_column_name, l_table_name)
    INTO clob_data;
    
    drop table file_upload_hex;
    
    RETURN clob_data;
END;
$BODY$;
```

**电子邮件模板**

```
######################################################################################
##                                                                                    ##
##    johndoe Template Type: email                                                    ##
##    File: johndoe.salary.event.notification.email.vm                                ##
##    Author: Aimée Étienne    Date 1/10/2021                                                ##
##  Purpose: Email template used by EmplmanagerEJB to inform a johndoe they         ##
##        have been given access to a salary event                                    ##
##    Template Attributes:                                                             ##
##        invitedUser - PersonDetails object for the invited user                        ##
##        salaryEvent - OfferDetails object for the event the user was given access    ##
##        buyercollege - CompDetails object for the college owning the salary event    ##
##        salaryCoordinator - PersonDetails of the salary coordinator for the event    ##
##        idp - Identity Provider of the email recipient                                ##
##        httpWebRoot - HTTP address of the server                                    ##
##                                                                                    ##
######################################################################################

$!invitedUser.firstname $!invitedUser.lastname,

Ce courriel confirme que vous avez ete invite par $!salaryCoordinator.firstname $!salaryCoordinator.lastname de $buyercollege.collegeName a participer a l'evenement "$salaryEvent.offeringtitle" sur johndoeMaster Sourcing Intelligence.

Votre nom d'utilisateur est $!invitedUser.username

Veuillez suivre le lien ci-dessous pour acceder a l'evenement.

${httpWebRoot}/myDashboard.do?idp=$!{idp}

Si vous avez oublie votre mot de passe, utilisez le lien "Mot de passe oublie" situe sur l'ecran de connexion et entrez votre nom d'utilisateur ci-dessus.

Si vous avez des questions ou des preoccupations, nous vous invitons a communiquer avec le coordonnateur de l'evenement $!salaryCoordinator.firstname $!salaryCoordinator.lastname au ${salaryCoordinator.workphone}.

*******

johndoeMaster Sourcing Intelligence est une plateforme de soumission en ligne pour les equipements, les materiaux et les services.

Si vous avez des difficultes ou des questions, envoyez un courriel a support@johndoeMaster.com pour obtenir de l'aide.
```