

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# Aurora PostgreSQL-Compatible에서 파일 인코딩을 사용하여 BLOB 파일을 TEXT에 로드
<a name="load-blob-files-into-text-by-using-file-encoding-in-aurora-postgresql-compatible"></a>

*Bhanu Ganesh Gudivada, Jeevan Shetty, Amazon Web Services*

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

마이그레이션 중에 로컬 파일 시스템의 파일에서 로드되는 비정형 및 정형 데이터를 처리해야 하는 경우가 종종 있습니다. 데이터가 데이터베이스 문자 집합과 다른 문자 집합으로 되어 있을 수도 있습니다.

이러한 파일에는 다음과 같은 유형의 데이터가 들어 있습니다.
+ **메타데이터** — 이 데이터는 파일 구조를 설명합니다.
+ **반정형 데이터** — JSON 또는 XML과 같은 특정 형식의 텍스트 문자열입니다. 이러한 데이터에 대해 “항상 '< '로 시작” 또는 “줄 바꿈 문자를 포함하지 않음”과 같은 주장을 할 수 있습니다.
+ **전체 텍스트** — 이 데이터에는 일반적으로 줄 바꿈 및 따옴표 문자를 비롯한 모든 유형의 문자가 포함됩니다. 또한 UTF-8 형식의 멀티바이트 문자로 구성될 수도 있습니다.
+ **바이너리 데이터** — 이 데이터에는 null 및 파일 끝 마커를 비롯한 바이트 또는 바이트 조합이 포함될 수 있습니다.

이러한 유형의 데이터를 혼합하여 로드하는 것은 어려울 수 있습니다.

이 패턴은 온프레미스 Oracle 데이터베이스, Amazon Web Services(AWS) Cloud에 있는 Amazon Elastic Compute Cloud(Amazon EC2) 인스턴스 상의 Oracle 데이터베이스 및 Amazon Relational Database Service (Amazon RDS) for Oracle 데이터베이스와 함께 사용될 수 있습니다. 예를 들어 이 패턴은 Amazon Aurora PostgreSQL-Compatible Edition을 사용합니다.

Oracle 데이터베이스에서는 `BFILE` (바이너리 파일) 포인터, `DBMS_LOB` 패키지, Oracle 시스템 함수를 사용하여 파일에서 로드하고 문자 인코딩을 사용해 CLOB로 변환할 수 있습니다. PostgreSQL은 Amazon Aurora PostgreSQL-Compatible Edition 데이터베이스로 마이그레이션할 때 BLOB 데이터 유형을 지원하지 않으므로 이러한 함수를 PostgreSQL 호환 스크립트로 변환해야 합니다.

이 패턴은 Amazon Aurora PostgreSQL-Compatible 데이터베이스의 단일 데이터베이스 열에 파일을 로드하는 두 가지 접근 방식을 제공합니다.
+ 접근 방식 1 – 인코드 옵션과 함께 `aws_s3` 확장 프로그램의 `table_import_from_s3` 함수를 사용하여 Amazon Simple Storage Service(S3) 버킷에서 데이터를 가져옵니다.
+ 접근 방식 2 – 데이터베이스를 벗어나 16진수로 인코딩한 다음 데이터베이스 내부에서 `TEXT`(을)를 볼 수 있도록 디코딩합니다.

Aurora PostgreSQL-Compatible은 `aws_s3` 확장 프로그램과 직접 통합되므로 접근 방식 1을 사용하는 것이 좋습니다.

이 패턴은 멀티바이트 문자와 고유한 형식을 가진 이메일 템플릿이 포함된 플랫 파일을 Amazon Aurora PostgreSQL-Compatible 데이터베이스로 로드하는 예제를 사용합니다.

## 사전 조건 및 제한 사항
<a name="load-blob-files-into-text-by-using-file-encoding-in-aurora-postgresql-compatible-prereqs"></a>

**사전 조건 **
+ 활성 상태의 AWS 계정
+ Amazon RDS 인스턴스 또는 Aurora PostgreSQL-Compatible 인스턴스
+ SQL 및 관계형 데이터베이스 관리 시스템(RDBMS)에 대한 기본 이해
+ Amazon Simple Storage Service(S3) 버킷
+ Oracle 및 PostgreSQL의 시스템 함수에 대한 지식
+ RPM Package HexDump-XXD-0.1.1(Amazon Linux 2에 포함됨)
**참고**  
Amazon Linux 2는 곧 지원이 종료됩니다. 자세한 내용은 [Amazon Linux 2 FAQ](https://aws.amazon.com/amazon-linux-2/faqs/)를 참조하세요.

**제한 사항 **
+ `TEXT` 데이터 유형의 경우 저장할 수 있는 가장 긴 문자열은 약 1GB입니다.

**제품 버전**
+ 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 출력까지 4단계 프로세스.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/cbf63cac-dcea-4e18-ab4f-c4f6296f60e7/images/9c46b385-e8a0-4e50-b856-d522c44d79e3.png)


1. 파일이 스테이징 S3 버킷으로 전송됩니다.

1. 파일이 Amazon Aurora PostgreSQL-Compatible 데이터베이스에 업로드됩니다.

1. pgAdmin 클라이언트를 사용하여 사용자 지정 함수 `load_file_into_clob`(을)를 Aurora 데이터베이스에 배포합니다.

1. 사용자 지정 함수는 내부적으로 file\$1encoding과 함께 `table_import_from_s3`(을)를 사용합니다. 함수의 출력은 `array_to_string` 및 `array_agg`(을)를 `TEXT` 출력으로 사용하여 얻습니다.

*접근 방식 2 – 데이터베이스를 벗어나 16진수로 인코딩한 다음 데이터베이스 내부에서 TEXT를 볼 수 있도록 디코딩합니다*.

온프레미스 서버 또는 로컬 파일 시스템의 파일은 16진수 덤프로 변환됩니다. 그런 다음 파일을 PostgreSQL에 `TEXT` 필드로 가져옵니다.

![\[16진수 덤프를 사용하는 3단계 프로세스.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/cbf63cac-dcea-4e18-ab4f-c4f6296f60e7/images/563038ca-f890-4874-85df-d0f82d99800a.png)


1. `xxd -p` 옵션을 사용하여 명령줄에서 파일을 16진수 덤프로 변환합니다.

1. `\copy` 옵션을 사용하여 16진수 덤프 파일을 Aurora PostgreSQL-Compatible로 업로드한 다음 16진수 덤프 파일을 바이너리로 디코딩합니다.

1. 바이너리 데이터를 인코딩하여 `TEXT`(으)로 반환합니다.

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

**서비스**
+ [Amazon Aurora PostgreSQL 호환 에디션](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.AuroraPostgreSQL.html)은 PostgreSQL 배포를 설정, 운영 및 확장할 수 있는 완전 관리형 ACID 준수의 관계형 데이터베이스 엔진입니다.
+ [Command Line Interface(AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)는 명령줄 쉘에서 명령을 사용하여 AWS 서비스와 상호 작용할 수 있는 오픈 소스 도구입니다.

**기타 도구**
+ [pgAdmin4](https://www.pgadmin.org/)는 PostgreSQL을 위한 오픈 소스 관리 및 개발 플랫폼입니다. pgAdmin4는 Linux, Unix, mac OS, Windows에서 PostgreSQL을 관리하는 데 사용할 수 있습니다.  

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

### 접근 방식 1: Amazon S3에서 Aurora PostgreSQL-Compatible로 데이터 가져오기
<a name="approach-1-import-data-from-amazon-s3-to-aurora-postgresql-compatible"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| EC2 인스턴스를 시작합니다. | 인스턴스 시작 지침은 [인스턴스 시작](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/LaunchingAndUsingInstances.html)을 참조하십시오. | DBA | 
| PostgreSQL 클라이언트 pGadmin 도구를 설치합니다. | [pgAdmin](https://www.pgadmin.org/download/)를 다운로드하고 설치합니다. | DBA | 
| IAM 정책을 생성합니다. | 파일이 저장되는 S3 버킷에 대한 액세스 권한을 부여하는 `aurora-s3-access-pol`(이)라 불리는 Identity and Access Management(IAM) 정책을 생성합니다. 다음 코드를 사용하여 S3 버킷의 이름으로 `<bucket-name>`(을)를 바꿉니다.<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> | DBA | 
| Amazon S3에서 Aurora PostgreSQL-Compatible로 객체 가져오기를 위한 IAM 역할을 생성합니다. | 다음 코드를 사용하여 [Assumerole](https://docs.amazonaws.cn/en_us/STS/latest/APIReference/API_AssumeRole.html) 신뢰 관계로 `aurora-s3-import-role`(이)라 불리는 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> | DBA | 
| IAM 역할을 클러스터와 연결합니다. | IAM 역할을 Aurora PostgreSQL-Compatible 데이터베이스 클러스터와 연결하려면 다음 AWS CLI 명령을 실행합니다. Aurora PostgreSQL-Compatible 데이터베이스를 호스팅하는 AWS 계정의 ID로 `<Account-ID>`(을)를 변경합니다. 이렇게 하면 Aurora PostgreSQL-Compatible 데이터베이스에서 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> | DBA | 
| 예제를 Amazon S3으로 업로드합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/load-blob-files-into-text-by-using-file-encoding-in-aurora-postgresql-compatible.html) | DBA, 앱 소유자 | 
| 사용자 지정 함수 배포. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/load-blob-files-into-text-by-using-file-encoding-in-aurora-postgresql-compatible.html) | 앱 소유자, DBA | 
| 데이터를 데이터베이스로 가져오기 위한 사용자 지정 함수를 실행합니다. | 다음 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`(을)로 반환합니다. | 앱 소유자, DBA | 

### 접근 방식 2: 로컬 Linux 시스템에서 템플릿 파일을 16진수 덤프로 변환
<a name="approach-2-convert-the-template-file-into-a-hex-dump-in-a-local-linux-system"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 템플릿 파일을 16진수 덤프로 변환합니다. | Hexdump 유틸리티는 이진 파일의 내용을 16진수, 10진수, 8진수 또는 ASCII로 표시합니다. `hexdump` 명령은 `util-linux` 패키지의 일부이며 Linux 배포판에 사전 설치되어 제공됩니다. Hexdump RPM 패키지도 Amazon Linux 2의 일부입니다. (: Amazon Linux 2의 지원이 거의 종료되었습니다. 자세한 내용은 [Amazon Linux 2 FAQ](https://aws.amazon.com/amazon-linux-2/faqs/)를 참조하세요.)파일 내용을 16진 덤프로 변환하려면 다음 쉘 명령을 실행합니다.<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> | DBA | 
| hexdump 파일을 데이터베이스 스키마에 로드합니다. | 다음 명령을 사용하여 hexdump 파일을 Aurora PostgreSQL-Compatible 데이터베이스에 로드합니다.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/load-blob-files-into-text-by-using-file-encoding-in-aurora-postgresql-compatible.html) | DBA | 

## 관련 리소스
<a name="load-blob-files-into-text-by-using-file-encoding-in-aurora-postgresql-compatible-resources"></a>

**참조**
+ [PostgreSQL 데이터베이스를 데이터베이스 마이그레이션 서비스용 대상으로 사용](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.PostgreSQL.html)
+ [PostgreSQL Compatibility (12.4) Migration Playbook으로 Oracle Database 19c를 Amazon Aurora로](https://d1.awsstatic.com/whitepapers/Migration/oracle-database-amazon-aurora-postgresql-migration-playbook-12.4.pdf)
+ [IAM 정책 생성](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create.html)
+ [IAM 역할을 Amazon Aurora MySQL DB 클러스터와 연결](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 사용자 지정 함수**

```
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.
```