

 Amazon Redshift는 패치 198부터 새 Python UDF 생성을 더 이상 지원하지 않습니다. 기존 Python UDF는 2026년 6월 30일까지 계속 작동합니다. 자세한 내용은 [블로그 게시물](https://aws.amazon.com/blogs/big-data/amazon-redshift-python-user-defined-functions-will-reach-end-of-support-after-june-30-2026/)을 참조하세요.

# 클라이언트 도구 및 코드에서 연결
<a name="connecting-via-client-tools"></a>

Amazon Redshift는 Amazon Redshift 쿼리 에디터 v2를 제공하여 클러스터와 작업 그룹에 연결할 수 있습니다. 자세한 내용은 [Query Editor V2를 사용하여 데이터베이스 쿼리Amazon Redshift 쿼리 편집기 v2를 사용하여 데이터베이스 쿼리](query-editor-v2.md) 섹션을 참조하세요.

이 섹션에서는 서드 파티 도구를 연결할 수 있는 몇 가지 옵션을 제공합니다. 또한 프로그래밍 방식으로 클러스터에 연결하는 방법에 대해서도 설명합니다.

**Topics**
+ [Amazon Redshift RSQL을 사용하여 연결](rsql-query-tool.md)
+ [Amazon Redshift RSQL을 사용하여 클러스터에 연결](rsql-query-tool-starting-tool-connection.md)
+ [Amazon Redshift RSQL 메타 명령](rsql-query-tool-commands.md)
+ [Amazon Redshift RSQL 변수](rsql-query-tool-variables.md)
+ [Amazon Redshift RSQL 오류 코드](rsql-query-tool-error-codes.md)
+ [Amazon Redshift RSQL 환경 변수](rsql-query-tool-environment-variables.md)

# Amazon Redshift RSQL을 사용하여 연결
<a name="rsql-query-tool"></a>

 Amazon Redshift RSQL은 Amazon Redshift 클러스터 및 데이터베이스와의 상호 작용을 위한 명령줄 클라이언트입니다. Amazon Redshift 클러스터에 연결하고, 데이터베이스 객체를 설명하고, 데이터를 쿼리하고, 다양한 출력 형식으로 쿼리 결과를 볼 수 있습니다.

 Amazon Redshift RSQL은 Amazon Redshift에 특정한 추가 기능 집합과 함께 PostgreSQL psql 명령줄 도구의 기능을 지원합니다. 여기에는 다음이 포함됩니다.
+ AD FS, PingIdentity, Okta, Azure ADm 또는 기타 SAML/JWT 기반 ID 제공업체를 통한 Single Sign-On을 사용할 수 있습니다. 멀티 팩터 인증(MFA)에 브라우저 기반 SAML 자격 증명 공급자를 사용할 수도 있습니다.
+ 테이블 배포 키, 테이블 정렬 키, 후기 바인딩 보기(LBV) 및 구체화된 보기와 같은 Amazon Redshift 객체의 속성을 설명할 수 있습니다. AWS Glue 카탈로그 또는 Apache Hive Metastore, Amazon RDS for PostgreSQL, Amazon Aurora PostgreSQL 호환 버전, RDS for MySQL(평가판) 및 Amazon Aurora MySQL 호환 버전(평가판)의 외부 데이터베이스, Amazon Redshift 데이터 공유를 사용하여 공유되는 테이블에 있는 외부 테이블의 속성을 설명할 수도 있습니다.
+ `IF`(`\ELSEIF`, `\ELSE,` `\ENDIF`), `\GOTO`, `\LABEL` 등의 향상된 제어 흐름 명령을 사용할 수도 있습니다.

 입력 파라미터로 전달된 스크립트를 실행하는 Amazon Redshift RSQL 배치 모드를 사용하면 SQL 및 복잡한 비즈니스 로직을 모두 포함하는 스크립트를 실행할 수 있습니다. 기존 자체 관리형 온프레미스 데이터 웨어하우스가 있는 경우 Amazon Redshift RSQL을 사용하여 Teradata BTEQ 스크립트와 같은 기존 추출, 변환, 로드 및 자동화 스크립트를 대체할 수 있습니다. RSQL을 사용하면 절차 언어로 스크립트를 수동으로 다시 구현하지 않아도 됩니다.

 Amazon Redshift RSQL은 Linux, Windows 및 macOS X 운영 체제에서 사용할 수 있습니다.

Amazon Redshift RSQL에 대한 문제를 보고하려면 redshift-rsql-support@amazon.com으로 이메일을 보내주세요.

**Topics**
+ [Amazon Redshift RSQL 시작하기](rsql-query-tool-getting-started.md)
+ [Amazon Redshift RSQL 변경 로그](rsql-query-tool-changelog.md)

# Amazon Redshift RSQL 시작하기
<a name="rsql-query-tool-getting-started"></a>

Linux, macOS 또는 Microsoft Windows 운영 체제가 설치된 컴퓨터에 Amazon Redshift RSQL을 설치합니다.

## RSQL 다운로드
<a name="rsql-query-tool-download"></a>
+ Linux 64비트 RPM: [RSQL 버전 1.1.2](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.1.2/AmazonRedshiftRsql-1.1.2.rhel.x86_64.rpm) 
  + Linux 아티팩트 서명 키: [키](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.1.2/AmazonRedshiftRsql-1.1.2-certificate.pem) 
  + Linux 아티팩트 서명된 해시: [해시](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.1.2/AmazonRedshiftRsql-1.1.2-signature.bin) 
+ macOS 64비트 PKG: [RSQL 버전 1.1.2](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.1.2/AmazonRedshiftRsql-1.1.2.universal.pkg) 
+ Windows 64비트 MSI: [RSQL 버전 1.1.2](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.1.2/AmazonRedshiftRsql-1.1.2.x86_64.msi) 

이전 버전의 변경 로그 및 다운로드는 [Amazon Redshift RSQL 변경 로그](rsql-query-tool-changelog.md)에서 확인하세요.

## Linux용 RSQL 설치
<a name="rsql-query-tool-linux-install"></a>

아래 단계에 따라 Linux용 RSQL을 설치하세요.

1. 다음 명령을 사용하여 드라이버 관리자를 설치합니다.

   ```
   sudo yum install unixODBC
   ```

1. ODBC 드라이버를 설치합니다. [Amazon Redshift ODBC 드라이버 다운로드 및 설치ODBC 드라이버 다운로드 및 설치](odbc20-install-linux.md).

1. ini 파일을 홈 디렉터리에 복사합니다.

   ```
   cp /opt/amazon/redshiftodbcx64/odbc.ini ~/.odbc.ini
   ```

1. 파일 위치를 가리키도록 환경 변수를 설정합니다.

   ```
   export ODBCINI=~/.odbc.ini
   export ODBCSYSINI=/opt/amazon/redshiftodbcx64/
   export AMAZONREDSHIFTODBCINI=/opt/amazon/redshiftodbcx64/amazon.redshiftodbc.ini
   ```

1. 이제 다음 명령을 실행하여 RSQL을 설치할 수 있습니다.

   ```
   sudo rpm -i AmazonRedshiftRsql-<version>.rhel.x86_64.rpm
   ```

## Mac용 RSQL 설치
<a name="rsql-query-tool-mac-install"></a>

아래 단계에 따라 macOS X용 RSQL을 설치합니다.

1. 다음 명령을 사용하여 드라이버 관리자를 설치합니다.

   ```
   brew install unixodbc --build-from-source
   ```

1. ODBC 드라이버를 설치합니다. [Amazon Redshift ODBC 드라이버 다운로드 및 설치ODBC 드라이버 다운로드 및 설치](odbc-driver-mac-how-to-install.md).

1. ini 파일을 홈 디렉터리에 복사합니다.

   ```
   cp /opt/amazon/redshift/Setup/odbc.ini ~/.odbc.ini
   ```

1. 파일 위치를 가리키도록 환경 변수를 설정합니다.

   ```
   export ODBCINI=~/.odbc.ini
   export ODBCSYSINI=/opt/amazon/redshift/Setup
   export AMAZONREDSHIFTODBCINI=/opt/amazon/redshift/lib/amazon.redshiftodbc.ini
   ```

1. `/usr/local/lib`에 없으면 `DYLD_LIBRARY_PATH`를 libodbc.dylib의 위치로 설정합니다.

   ```
   export DYLD_LIBRARY_PATH=$DYLD_LIBRARY_PATH:/usr/local/lib
   ```

1. pkg 파일을 두 번 클릭하여 설치 프로그램을 실행합니다.

1. 설치 관리자의 단계에 따라 설치를 완료합니다. 라이선스 계약 조건에 동의합니다.

## Windows용 RSQL 설치
<a name="rsql-query-tool-windows-install"></a>

아래 단계에 따라 Windows용 RSQL을 설치합니다.

1. ODBC 드라이버를 설치합니다. [Amazon Redshift ODBC 드라이버 다운로드 및 설치ODBC 드라이버 다운로드 및 설치](odbc-driver-windows-how-to-install.md).

1. RSQL 다운로드 파일을 두 번 클릭하여 설치 프로그램을 실행한 다음 화면 지시에 따라 설치를 완료합니다.

# Amazon Redshift RSQL 변경 로그
<a name="rsql-query-tool-changelog"></a>

*1.1.2(2025년 12월 11일)*

버그 수정
+ \$1goto 및 \$1label 명령에서 실패를 일으킨 버그를 수정했습니다.
+ 변수를 따옴표로 묶을 때 RSQL이 변수 값을 인쇄하지 못하는 버그를 수정했습니다.
+ UseDeclareFetch가 활성화된 상태에서 쿼리 결과가 ODBC DSN 가져오기 파라미터 크기를 초과할 때 RSQL 충돌이 발생하는 버그를 수정했습니다.
+ 페이저가 켜져 있더라도 여러 페이지의 결과가 한 번에 반환되는 문제를 수정했습니다.
+ 트랜잭션 블록 내에서 쿼리가 실패할 때 RSQL 충돌을 트리거하는 버그를 수정했습니다.

*1.1.1(2025-11-20)*

버그 수정
+ -c 플래그를 사용할 때 RSQL이 쿼리를 잘못 구문 분석하는 문제를 수정했습니다. 이 수정 사항은 모든 플랫폼에 적용됩니다.
+ Mac에서 사용자가 RSQL에서 \$1s 명령을 사용하지 못하게 하는 버그를 수정했습니다.

*1.1.0(2025-11-11)*

버그 수정
+ RSQL에서 예기치 않은 충돌을 일으키는 메모리 누수 문제를 해결했습니다.
+ RSQL에서 OpenSSL 종속성을 제거했습니다.
+ 동일한 환경에서 libpq/psql 설치와의 연결 충돌을 수정했습니다.
+ Amazon Linux 2023, Windows 및 macOS의 플랫폼 호환성을 개선했습니다.
+ 현재 표시 크기를 초과할 때 출력이 잘리는 문제를 수정했습니다.

*1.0.8(2023-06-19)*

버그 수정
+ SHOW 명령으로 출력이 잘리는 문제를 수정했습니다.
+ \$1de에 외부 Kinesis 스트림 및 Kafka 주제 설명을 위한 지원이 추가되었습니다.

*1.0.7(2023-03-22)*

버그 수정
+ RSQL이 구체화된 뷰를 설명할 수 없는 문제가 수정되었습니다.
+ Amazon Redshift Serverless를 사용할 때 stl\$1connection\$1log의 권한 거부 오류가 수정되었습니다.
+ RSQL이 \$1GOTO 레이블을 잘못 처리할 수 있는 문제가 해결되었습니다.
+ 자동 모드에서 SSL 메시지가 출력되는 문제가 해결되었습니다.
+ 저장된 프로시저를 설명할 때 임의의 문자가 표시되는 문제가 해결되었습니다.
+ 중복된 오류/정보 메시지가 출력되는 문제가 해결되었습니다.

New
+ RSQL이 이제 ODBC 드라이버에서 직접 SSL 정보를 가져옵니다.



*1.0.6(2023-02-21)*

버그 수정
+ Redshift 패치 1.0.46086(P173)에서 \$1d가 잘못된 정수 입력 구문: ‘xid’라는 오류가 발생하는 문제를 수정했습니다.

New
+ 지원되는 아키텍처를 반영하도록 설치 파일의 이름을 변경했습니다.



*1.0.5(2022-06-27)*

버그 수정
+ SQL 오류 메시지를 표준 오류(stderr)로 보냅니다.
+ ON\$1ERROR\$1STOP을 사용할 때 발생하는 종료 코드 문제를 해결했습니다. 이제 오류가 발생하면 스크립트가 종료되고 올바른 종료 코드를 반환합니다.
+ Maxerror가 이제 대/소문자를 구분하지 않습니다.

New
+ ODBC 2.x 드라이브에 대한 지원이 추가되었습니다.



*1.0.4(2022-03-19)*
+ RSPASSWORD 환경 변수에 대한 지원을 추가합니다. Amazon Redshift Redshift에 연결할 암호를 설정합니다. 예를 들어 `export RSPASSWORD=TestPassw0rd`입니다.



*1.0.3(2021-12-08)*

버그 수정
+ Windows OS에서 `\c` 또는 `\logon`을 사용하여 데이터베이스 간에 전환할 때 대화 상자 팝업이 수정되었습니다.
+ ssl 정보를 확인할 때 발생하는 충돌이 수정되었습니다.



## Amazon Redshift RSQL 이전 버전
<a name="rsql-query-tool-changelog-legacy-versions"></a>

링크 중 하나를 선택하여 운영 체제에 따라 필요한 Amazon Redshift RSQL 버전을 다운로드합니다.

**Linux 64비트 RPM**
+ [RSQL 버전 1.1.1](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.1.1/AmazonRedshiftRsql-1.1.1.rhel.x86_64.rpm)
+ [RSQL 버전 1.1.0](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.1.0/AmazonRedshiftRsql-1.1.0.rhel.x86_64.rpm)
+ [RSQL 버전 1.0.8](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.8/AmazonRedshiftRsql-1.0.8.x86_64.rpm)
+ [RSQL 버전 1.0.7](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.7/AmazonRedshiftRsql-1.0.7.x86_64.rpm)
+ [RSQL 버전 1.0.6](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.6/AmazonRedshiftRsql-1.0.6.x86_64.rpm)
+ [RSQL 버전 1.0.5](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.5/AmazonRedshiftRsql-1.0.5-1.x86_64.rpm)
+ [RSQL 버전 1.0.4](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.4/AmazonRedshiftRsql-1.0.4-1.x86_64.rpm)
+ [RSQL 버전 1.0.3](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.3/AmazonRedshiftRsql-1.0.3-1.x86_64.rpm)
+ [RSQL 버전 1.0.1](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.1/AmazonRedshiftRsql-1.0.1-1.x86_64.rpm) 

**macOS 64비트 DMG/PKG**
+ [RSQL 버전 1.1.1](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.1.1/AmazonRedshiftRsql-1.1.1.universal.pkg)
+ [RSQL 버전 1.1.0](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.1.0/AmazonRedshiftRsql-1.1.0.universal.pkg)
+ [RSQL 버전 1.0.8](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.8/AmazonRedshiftRsql-1.0.8.x86_64.dmg)
+ [RSQL 버전 1.0.7](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.7/AmazonRedshiftRsql-1.0.7.x86_64.dmg)
+ [RSQL 버전 1.0.6](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.6/AmazonRedshiftRsql-1.0.6.x86_64.dmg)
+ [RSQL 버전 1.0.5](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.5/AmazonRedshiftRsql-1.0.5.dmg)
+ [RSQL 버전 1.0.4](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.4/AmazonRedshiftRsql-1.0.4.dmg)
+ [RSQL 버전 1.0.3](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.3/AmazonRedshiftRsql-1.0.3.dmg)
+ [RSQL 버전 1.0.1](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.1/AmazonRedshiftRsql-1.0.1.dmg) 

**Windows 64비트 MSI**
+ [RSQL 버전 1.1.1](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.1.1/AmazonRedshiftRsql-1.1.1.x86_64.msi)
+ [RSQL 버전 1.1.0](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.1.0/AmazonRedshiftRsql-1.1.0.x86_64.msi)
+ [RSQL 버전 1.0.8](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.8/AmazonRedshiftRsql-1.0.8.x86_64.msi)
+ [RSQL 버전 1.0.7](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.7/AmazonRedshiftRsql-1.0.7.x86_64.msi)
+ [RSQL 버전 1.0.6](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.6/AmazonRedshiftRsql-1.0.6.x86_64.msi)
+ [RSQL 버전 1.0.5](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.5/AmazonRedshiftRsql-1.0.5.msi)
+ [RSQL 버전 1.0.4](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.4/AmazonRedshiftRsql-1.0.4.msi)
+ [RSQL 버전 1.0.3](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.3/AmazonRedshiftRsql-1.0.3.msi)
+ [RSQL 버전 1.0.1](https://s3.amazonaws.com/redshift-downloads/amazon-redshift-rsql/1.0.1/AmazonRedshiftRsql-1.0.1.msi) 

# Amazon Redshift RSQL을 사용하여 클러스터에 연결
<a name="rsql-query-tool-starting-tool-connection"></a>

Amazon Redshift를 사용하면 RSQL로 클러스터에 연결하고 상호 작용할 수 있습니다. 이는 데이터를 쿼리하고, 데이터베이스 객체를 생성하고, Amazon Redshift 클러스터를 관리하는 안전한 방법을 제공하는 명령줄 도구입니다. 다음 섹션에서는 데이터 소스 이름(DSN)이 있거나 없는 RSQL을 사용하여 클러스터에 대한 연결을 설정하는 단계를 안내합니다.

## DSN을 사용하지 않고 연결
<a name="rsql-query-tool-starting-tool-connection-dsn-less-example"></a>

1. Amazon Redshift 콘솔에서 연결할 클러스터를 선택하고 엔드포인트, 데이터베이스 및 포트를 기록해 둡니다.

1. 명령 프롬프트에서 명령줄 파라미터를 사용하여 연결 정보를 지정합니다.

   ```
   rsql -h <endpoint> -U <username> -d <databasename> -p <port>
   ```

    여기에는 다음이 적용됩니다.
   +  *<endpoint>*은(는) 이전 단계에서 기록한 **엔드포인트(Endpoint)**입니다.
   +  *<username>*은 클러스터 연결 권한이 있는 사용자의 이름입니다.
   +  *<databasename>*은(는) 이전 단계에서 입력한 **데이터베이스 이름(Database Name)**입니다.
   +  *<port>*는 이전 단계에서 기록한 **포트(Port)**입니다. *<port>*는 선택적 파라미터입니다.

   예를 들면 다음과 같습니다.

   ```
   rsql -h testcluster.example.amazonaws.com -U user1 -d dev -p 5439
   ```

1.  암호 프롬프트에서 *<username>* 사용자의 암호를 입력합니다.

   성공적인 연결 응답은 다음과 같습니다.

   ```
   % rsql -h testcluster.example.com -d dev -U user1 -p 5349
   Password for user user1:
   DSN-less Connected
   DBMS Name: Amazon Redshift
   Driver Name: Amazon Redshift ODBC Driver
   Driver Version: 1.4.27.1000
   Rsql Version: 1.0.1
   Redshift Version: 1.0.29306
   Type "help" for help.
   
   (testcluster) user1@dev=#
   ```

연결 명령은 Linux, Mac OS 및 Windows에서 동일한 파라미터를 사용합니다.

## DSN으로 연결
<a name="rsql-query-tool-starting-tool-connection-dsn-example"></a>

DSN을 통해 연결 속성 구성을 간소화하여 RSQL을 Amazon Redshift에 연결할 수 있습니다. 이 주제에는 ODBC 드라이버 설치 설명과 DSN 속성 설명이 포함되어 있습니다.

### 암호와 함께 DSN 연결 사용
<a name="rsql-query-tool-starting-tool-connection-dsn-example-password"></a>

다음은 암호를 사용하는 DSN 연결 구성의 예를 보여줍니다. 기본 `<path to driver>`은 Mac OSX의 경우 `/opt/amazon/redshift/lib/libamazonredshiftodbc.dylib`이고 Linux의 경우 `/opt/amazon/redshiftodbc/lib/64/libamazonredshiftodbc64.so`입니다.

```
[testuser]
Driver=/opt/amazon/redshiftodbc/lib/64/libamazonredshiftodbc64.so
SSLMode=verify-ca
Min_TLS=1.2
boolsaschar=0
Host=<server endpoint>
Port=<database port>
Database=<dbname>
UID=<username>
PWD=<password>
sslmode=prefer
```

다음 출력은 성공적인 연결의 결과입니다.

```
% rsql -D testuser
DSN Connected
DBMS Name: Amazon Redshift
Driver Name: Amazon Redshift ODBC Driver
Driver Version: 1.4.27.1000
Rsql Version: 1.0.1
Redshift Version: 1.0.29306
Type "help" for help.

(testcluster) user1@dev=#
```

### 통합 인증 DSN 사용
<a name="rsql-query-tool-starting-tool-connection-dsn"></a>

Single Sign-On 인증을 위해 DSN을 구성할 수 있습니다. 다음은 Okta Single Sign-On을 사용하는 DSN 연결 구성의 예를 보여줍니다.

```
[testokta]
Driver=<path to driver>
SSLMode=verify-ca
Min_TLS=1.2
boolsaschar=0
Host=<server endpoint>
clusterid=<cluster id>
region=<region name>
Database=<dbname>
locale=en-US
iam=1
plugin_name=<plugin name>
uid=<okta username>
pwd=<okta password>
idp_host=<idp endpoint>
app_id=<app id>
app_name=<app name>
preferred_role=<role arn>
```

성공적인 연결의 샘플 출력입니다.

```
% rsql -D testokta 
DSN Connected
DBMS Name: Amazon Redshift
Driver Name: Amazon Redshift ODBC Driver
Driver Version: 1.4.27.1000
Rsql Version: 1.0.1
Redshift Version: 1.0.29306
Type "help" for help.

(testcluster) user1@dev=#
```

다음은 Azure Single Sign-On을 사용하는 DSN 연결 구성의 예를 보여줍니다.

```
[testazure]
Driver=<path to driver>
SSLMode=verify-ca
Min_TLS=1.2
boolsaschar=0
Host=<server endpoint>
Port=<cluster port>
clusterid=<cluster id>
region=<region name>
Database=<dbname>
locale=en-us
iam=1
plugin_name=<plugin name>
uid=<azure username>
pwd=<azure password>
idp_tenant=<Azure idp tenant uuid>
client_id=<Azure idp client uuid>
client_secret=<Azure idp client secret>
```

### IAM 프로파일과 함께 DSN 연결 사용
<a name="rsql-query-tool-starting-tool-connection-dsn-iam"></a>

구성된 IAM 프로파일을 사용하여 Amazon Redshift에 연결할 수 있습니다. IAM 프로파일에 `GetClusterCredentials`를 호출할 수 있는 권한이 있어야 합니다. 다음 예에서는 사용할 DSN 속성을 보여줍니다. `ClusterID` 및 `Region` 파라미터는 `Host`가 `examplecluster.abc123xyz789.us-west-2.redshift.amazonaws.com`과 같이 Amazon에서 제공하는 엔드포인트가 아닌 경우에만 필요합니다.

```
[testiam]
Driver=Default
Host=testcluster.example.com
Database=dev
DbUser=testuser
ClusterID=rsqltestcluster
Region=us-east-1
IAM=1
Profile=default
```

`Profile` 키 값은AWS CLI 자격 증명에서 선택하는 명명된 프로파일입니다. 이 예에서는 `default`라는 프로파일에 대한 자격 증명을 보여줍니다.

```
$ cat .aws/credentials
[default]
aws_access_key_id = ASIAIOSFODNN7EXAMPLE 
aws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
```

다음은 연결 응답을 보여줍니다.

```
$ rsql -D testiam
DSN Connected
DBMS Name: Amazon Redshift
Driver Name: Amazon Redshift ODBC Driver
Driver Version: 1.4.27.1000
Rsql Version: 1.0.1
Redshift Version: 1.0.29306
Type "help" for help.

(testcluster) testuser@dev=>
```

### 인스턴스 프로파일과 함께 DSN 연결 사용
<a name="rsql-query-tool-starting-tool-connection-dsn-instance"></a>

Amazon EC2 인스턴스 프로파일을 사용하여 Amazon Redshift에 연결할 수 있습니다. 인스턴스 프로파일에 `GetClusterCredentials`를 호출할 수 있는 권한이 있어야 합니다. 사용할 DSN 속성은 아래 예를 참조하세요. `ClusterID` 및 `Region` 파라미터는 `Host`가 `examplecluster.abc123xyz789.us-west-2.redshift.amazonaws.com`과 같이 Amazon에서 제공하는 엔드포인트가 아닌 경우에만 필요합니다.

```
[testinstanceprofile]
Driver=Default
Host=testcluster.example.com
Database=dev
DbUser=testuser
ClusterID=rsqltestcluster
Region=us-east-1
IAM=1
Instanceprofile=1
```

다음은 연결 응답을 보여줍니다.

```
$ rsql -D testinstanceprofile
DSN Connected
DBMS Name: Amazon Redshift
Driver Name: Amazon Redshift ODBC Driver
Driver Version: 1.4.27.1000
Rsql Version: 1.0.1
Redshift Version: 1.0.29306
Type "help" for help.

(testcluster) testuser@dev=>
```

### 기본 자격 증명 공급자 체인에서 DSN 연결 사용
<a name="rsql-query-tool-starting-tool-connection-dsn-provider-chain"></a>

기본 자격 증명 공급자 체인을 사용하여 연결하기 위해 IAM 속성만 지정하면 Amazon Redshift RSQL이 Java용 AWS SDK에서 [AWS 자격 증명으로 작업하기](https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html)에 나와 있는 순서대로 자격 증명 획득을 시도합니다. 체인에서 제공자 하나 이상이 `GetClusterCredentials` 권한이 있어야 합니다. 이것은 예를 들어 ECS 컨테이너에서 연결할 때 유용합니다.

```
[iamcredentials]
Driver=Default
Host=testcluster.example.com
Database=dev
DbUser=testuser
ClusterID=rsqltestcluster
Region=us-east-1
IAM=1
```

# Amazon Redshift RSQL 메타 명령
<a name="rsql-query-tool-commands"></a>

Amazon Redshift RSQL 메타 명령은 데이터베이스 또는 특정 데이터베이스 객체에 대한 정보 레코드를 반환합니다. 결과에는 다양한 열과 메타데이터가 포함될 수 있습니다. 다른 명령은 특정 작업을 수행합니다. 이러한 명령 앞에는 백슬래시를 붙입니다.

## \$1d[S\$1]
<a name="rsql-query-tool-describe-d"></a>

 로컬 사용자 생성 테이블, 일반 보기, 후기 바인딩 보기 및 구체화된 보기를 나열합니다. `\dS `는 `\d`와 같은 테이블과 보기도 나열하지만 반환된 레코드에는 시스템 객체가 포함됩니다. `+`는 나열된 모든 객체에 대한 추가 메타데이터 열 `description`을 생성합니다. 다음은 명령의 결과로 반환된 샘플 레코드를 보여줍니다.

```
List of relations
 schema |   name    | type  |  owner  
--------+-----------+-------+---------
 public | category  | table | awsuser
 public | date      | table | awsuser
 public | event     | table | awsuser
 public | listing   | table | awsuser
 public | sales     | table | awsuser
 public | users     | table | awsuser
 public | venue     | table | awsuser
(7 rows)
```

## \$1d[S\$1] NAME
<a name="rsql-query-tool-describe-s-plus-named"></a>

테이블, 보기 또는 인덱스에 대해 설명합니다. 열 이름 및 유형을 포함합니다. 또한 diststyle, 백업 구성, 생성 날짜(2018년 10월 이후 생성된 테이블) 및 제약 조건을 제공합니다. 예를 들어, `\dS+ sample`은 객체 속성을 반환합니다. `S+`를 추가하면 반환된 레코드에 추가 열이 포함됩니다.

```
Table "public.sample"
 Column |            Type             |   Collation    | Nullable | Default Value | Encoding  | DistKey | SortKey
--------+-----------------------------+----------------+----------+---------------+-----------+---------+---------
 col1   | smallint                    |                | NO       |               | none      | t       | 1
 col2   | character(100)              | case_sensitive | YES      |               | none      | f       | 2
 col3   | character varying(100)      | case_sensitive | YES      |               | text32k   | f       | 3
 col4   | timestamp without time zone |                | YES      |               | runlength | f       | 0
 col5   | super                       |                | YES      |               | zstd      | f       | 0
 col6   | bigint                      |                | YES      |               | az64      | f       | 0

Diststyle: KEY
Backup: YES
Created: 2021-07-20 19:47:27.997045
Unique Constraints:
    "sample_pkey" PRIMARY KEY (col1)
    "sample_col2_key" UNIQUE (col2)
Foreign-key constraints:
    "sample_col2_fkey" FOREIGN KEY (col2) REFERENCES lineitem(l_orderkey)
```

테이블의 배포 스타일 또는 *Diststyle*은 KEY, AUTO, EVEN 또는 ALL일 수 있습니다.

*백업(Backup)*은 스냅샷이 생성될 때 테이블이 백업되는지 여부를 나타냅니다. 유효한 값은 `YES` 또는 `NO`입니다.

*생성됨(Created)*은 테이블이 생성될 때의 타임스탬프입니다. 2018년 11월 이전에 생성된 Amazon Redshift 테이블에는 생성 날짜를 사용할 수 없습니다. 이 날짜 이전에 생성된 테이블은 n/a(해당 사항 없음)으로 표시됩니다.

*고유 제약 조건(Unique Constraints)*에는 테이블에 대한 고유 및 기본 키 제약 조건이 나열됩니다.

*외래 키 제약 조건(Foreign-key constraints)*에는 테이블에 대한 외래 키 제약 조건이 나열됩니다.

## \$1dC[\$1] [PATTERN]
<a name="rsql-query-tool-describe-dc"></a>

캐스트를 나열합니다. 소스 유형, 대상 유형 및 캐스트가 암시적인지 여부를 포함합니다.

다음은 `\dC+` 결과의 하위 집합을 보여줍니다.

```
List of casts
         source type         |         target type         |      function       |   implicit?   | description 
-----------------------------+-----------------------------+---------------------+---------------+-------------
 "char"                      | character                   | bpchar              | in assignment | 
 "char"                      | character varying           | text                | in assignment | 
 "char"                      | integer                     | int4                | no            | 
 "char"                      | text                        | text                | yes           | 
 "path"                      | point                       | point               | no            | 
 "path"                      | polygon                     | polygon             | in assignment | 
 abstime                     | date                        | date                | in assignment | 
 abstime                     | integer                     | (binary coercible)  | no            | 
 abstime                     | time without time zone      | time                | in assignment | 
 abstime                     | timestamp with time zone    | timestamptz         | yes           | 
 abstime                     | timestamp without time zone | timestamp           | yes           | 
 bigint                      | bit                         | bit                 | no            | 
 bigint                      | boolean                     | bool                | yes           | 
 bigint                      | character                   | bpchar              | in assignment | 
 bigint                      | character varying           | text                | in assignment | 
 bigint                      | double precision            | float8              | yes           | 
 bigint                      | integer                     | int4                | in assignment | 
 bigint                      | numeric                     | numeric             | yes           | 
 bigint                      | oid                         | oid                 | yes           | 
 bigint                      | real                        | float4              | yes           | 
 bigint                      | regclass                    | oid                 | yes           | 
 bigint                      | regoper                     | oid                 | yes           | 
 bigint                      | regoperator                 | oid                 | yes           | 
 bigint                      | regproc                     | oid                 | yes           | 
 bigint                      | regprocedure                | oid                 | yes           | 
 bigint                      | regtype                     | oid                 | yes           | 
 bigint                      | smallint                    | int2                | in assignment | 
 bigint                      | super                       | int8_partiql        | in assignment |
```

## \$1dd[S] [PATTERN]
<a name="rsql-query-tool-describe-dds"></a>

다른 곳에 표시되지 않는 객체 설명을 보여줍니다.

## \$1de
<a name="rsql-query-tool-describe-de"></a>

외부 테이블을 나열합니다. 여기에는 AWS Glue Data Catalog의 테이블, Hive Metastore 및 Amazon RDS/Aurora MySQL, Amazon RDS/Aurora PostgreSQL 및 Amazon Redshift 데이터 공유 테이블의 페더레이션 테이블이 포함됩니다.

## \$1de NAME
<a name="rsql-query-tool-describe-de-name"></a>

외부 테이블을 설명합니다.

다음 예에서는 AWS Glue 외부 테이블을 보여줍니다.

```
# \de spectrum.lineitem
                            Glue External table "spectrum.lineitem"
     Column      | External Type | Redshift Type | Position | Partition Key | Nullable
-----------------+---------------+---------------+----------+---------------+----------
 l_orderkey      | bigint        | bigint        | 1        | 0             |
 l_partkey       | bigint        | bigint        | 2        | 0             |
 l_suppkey       | int           | int           | 3        | 0             |
 l_linenumber    | int           | int           | 4        | 0             |
 l_quantity      | decimal(12,2) | decimal(12,2) | 5        | 0             |
 l_extendedprice | decimal(12,2) | decimal(12,2) | 6        | 0             |
 l_discount      | decimal(12,2) | decimal(12,2) | 7        | 0             |
 l_tax           | decimal(12,2) | decimal(12,2) | 8        | 0             |
 l_returnflag    | char(1)       | char(1)       | 9        | 0             |
 l_linestatus    | char(1)       | char(1)       | 10       | 0             |
 l_shipdate      | date          | date          | 11       | 0             |
 l_commitdate    | date          | date          | 12       | 0             |
 l_receiptdate   | date          | date          | 13       | 0             |
 l_shipinstruct  | char(25)      | char(25)      | 14       | 0             |
 l_shipmode      | char(10)      | char(10)      | 15       | 0             |
 l_comment       | varchar(44)   | varchar(44)   | 16       | 0             |

Location: s3://redshiftbucket/kfhose2019/12/31
Input_format: org.apache.hadoop.mapred.TextInputFormat
Output_format: org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat
Serialization_lib: org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe
Serde_parameters: {"field.delim":"|","serialization.format":"|"}
Parameters: {"EXTERNAL":"TRUE","numRows":"178196721475","transient_lastDdlTime":"1577771873"}
```

Hive 메타스토어 테이블.입니다.

```
# \de emr.lineitem
                     Hive Metastore External Table "emr.lineitem"
     Column      | External Type | Redshift Type | Position | Partition Key | Nullable
-----------------+---------------+---------------+----------+---------------+----------
 l_orderkey      | bigint        | bigint        | 1        | 0             |
 l_partkey       | bigint        | bigint        | 2        | 0             |
 l_suppkey       | int           | int           | 3        | 0             |
 l_linenumber    | int           | int           | 4        | 0             |
 l_quantity      | decimal(12,2) | decimal(12,2) | 5        | 0             |
 l_extendedprice | decimal(12,2) | decimal(12,2) | 6        | 0             |
 l_discount      | decimal(12,2) | decimal(12,2) | 7        | 0             |
 l_tax           | decimal(12,2) | decimal(12,2) | 8        | 0             |
 l_returnflag    | char(1)       | char(1)       | 9        | 0             |
 l_linestatus    | char(1)       | char(1)       | 10       | 0             |
 l_commitdate    | date          | date          | 11       | 0             |
 l_receiptdate   | date          | date          | 12       | 0             |
 l_shipinstruct  | char(25)      | char(25)      | 13       | 0             |
 l_shipmode      | char(10)      | char(10)      | 14       | 0             |
 l_comment       | varchar(44)   | varchar(44)   | 15       | 0             |
 l_shipdate      | date          | date          | 16       | 1             |

Location: s3://redshiftbucket/cetas
Input_format: org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat
Output_format: org.apache.hadoop.hive.ql.io.parquet.MapredParquetOutputFormat
Serialization_lib: org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe
Serde_parameters: {"serialization.format":"1"}
Parameters: {"EXTERNAL":"TRUE", "numRows":"4307207", "transient_lastDdlTime":"1626990007"}
```

PostgreSQL 외부 테이블입니다.

```
# \de pgrsql.alltypes
                                Postgres Federated Table "pgrsql.alltypes"
 Column |        External Type        |        Redshift Type        | Position | Partition Key | Nullable
--------+-----------------------------+-----------------------------+----------+---------------+----------
 col1   | bigint                      | bigint                      | 1        | 0             |
 col2   | bigint                      | bigint                      | 2        | 0             |
 col5   | boolean                     | boolean                     | 3        | 0             |
 col6   | box                         | varchar(65535)              | 4        | 0             |
 col7   | bytea                       | varchar(65535)              | 5        | 0             |
 col8   | character(10)               | character(10)               | 6        | 0             |
 col9   | character varying(10)       | character varying(10)       | 7        | 0             |
 col10  | cidr                        | varchar(65535)              | 8        | 0             |
 col11  | circle                      | varchar(65535)              | 9        | 0             |
 col12  | date                        | date                        | 10       | 0             |
 col13  | double precision            | double precision            | 11       | 0             |
 col14  | inet                        | varchar(65535)              | 12       | 0             |
 col15  | integer                     | integer                     | 13       | 0             |
 col16  | interval                    | varchar(65535)              | 14       | 0             |
 col17  | json                        | varchar(65535)              | 15       | 0             |
 col18  | jsonb                       | varchar(65535)              | 16       | 0             |
 col19  | line                        | varchar(65535)              | 17       | 0             |
 col20  | lseg                        | varchar(65535)              | 18       | 0             |
 col21  | macaddr                     | varchar(65535)              | 19       | 0             |
 col22  | macaddr8                    | varchar(65535)              | 20       | 0             |
 col23  | money                       | varchar(65535)              | 21       | 0             |
 col24  | numeric                     | numeric(38,20)              | 22       | 0             |
 col25  | path                        | varchar(65535)              | 23       | 0             |
 col26  | pg_lsn                      | varchar(65535)              | 24       | 0             |
 col28  | point                       | varchar(65535)              | 25       | 0             |
 col29  | polygon                     | varchar(65535)              | 26       | 0             |
 col30  | real                        | real                        | 27       | 0             |
 col31  | smallint                    | smallint                    | 28       | 0             |
 col32  | smallint                    | smallint                    | 29       | 0             |
 col33  | integer                     | integer                     | 30       | 0             |
 col34  | text                        | varchar(65535)              | 31       | 0             |
 col35  | time without time zone      | varchar(65535)              | 32       | 0             |
 col36  | time with time zone         | varchar(65535)              | 33       | 0             |
 col37  | timestamp without time zone | timestamp without time zone | 34       | 0             |
 col38  | timestamp with time zone    | timestamp with time zone    | 35       | 0             |
 col39  | tsquery                     | varchar(65535)              | 36       | 0             |
 col40  | tsvector                    | varchar(65535)              | 37       | 0             |
 col41  | txid_snapshot               | varchar(65535)              | 38       | 0             |
 col42  | uuid                        | varchar(65535)              | 39       | 0             |
 col43  | xml                         | varchar(65535)              | 40       | 0             |
```

## \$1df[anptw][S\$1] [PATTERN]
<a name="rsql-query-tool-df"></a>

 다양한 유형의 함수를 나열합니다. 예를 들어 `\df` 명령은 함수 목록을 반환합니다. 결과에는 이름, 반환된 데이터 유형, 액세스 권한 및 추가 메타데이터와 같은 속성이 포함됩니다. 함수 유형에는 트리거, 저장 프로시저, 윈도 함수 및 기타 유형이 포함될 수 있습니다. 명령에 `S+`를 추가하면(예: `\dfantS+`) `owner`, `security`, `access privileges` 등의 추가 메타데이터 열이 포함됩니다.

## \$1dL[S\$1] [PATTERN]
<a name="rsql-query-tool-describe-dl"></a>

 데이터베이스와 연결된 절차 언어에 대한 데이터를 나열합니다. 정보에는 plpgsql과 같은 이름과 신뢰할 수 있는지 여부, 액세스 권한 및 설명이 포함된 추가 메타데이터가 포함됩니다. 예를 들어 샘플 호출은 언어 및 해당 속성을 나열하는 `\dLS+`입니다. 명령에 `S+`를 추가하면 `call handler`, `access privileges`등의 추가 메타데이터 열이 포함됩니다.

샘플 결과:

```
List of languages
   name    | trusted | internal language |      call handler       |                         validator                          | access privileges |          description           
-----------+---------+-------------------+-------------------------+------------------------------------------------------------+-------------------+--------------------------------
 c         | f       | t                 | -                       | fmgr_c_validator(oid)                                      |                   | Dynamically-loaded C functions
 exfunc    | f       | f                 | exfunc_call_handler()   | -                                                          | rdsdb=U/rdsdb     | 
 internal  | f       | t                 | -                       | fmgr_internal_validator(oid)                               |                   | Built-in functions
 mlfunc    | f       | f                 | mlfunc_call_handler()   | -                                                          | rdsdb=U/rdsdb     | 
 plpgsql   | t       | f                 | plpgsql_call_handler()  | plpgsql_validator(oid)                                     |                   | 
 plpythonu | f       | f                 | plpython_call_handler() | plpython_compiler(cstring,cstring,cstring,cstring,cstring) | rdsdb=U/rdsdb     | 
 sql       | t       | t                 | -                       | fmgr_sql_validator(oid)                                    | =U/rdsdb          | SQL-language functions
```

## \$1dm[S\$1] [PATTERN]
<a name="rsql-query-tool-describe-dm"></a>

 구체화된 보기를 나열합니다. 예를 들어 `\dmS+`는 구체화된 보기와 해당 속성을 나열합니다. 명령에 `S+`를 추가하면 추가 메타데이터 열이 포함됩니다.

## \$1dn[S\$1] [PATTERN]
<a name="rsql-query-tool-describe-dn"></a>

 스키마를 나열합니다. 명령에 `S+`를 추가하면(예: `\dnS+`) `description`, `access privileges`등의 추가 메타데이터 열이 포함됩니다.

## \$1dp [PATTERN]
<a name="rsql-query-tool-describe-dp"></a>

 테이블, 보기 및 시퀀스 액세스 권한을 나열합니다.

## \$1dt[S\$1] [PATTERN]
<a name="rsql-query-tool-describe-dt"></a>

 테이블을 나열합니다. 명령에 `S+`를 추가하면(예: `\dtS+`) 이 경우 `description` 등의 추가 메타데이터 열이 포함됩니다.

## \$1du
<a name="rsql-query-tool-describe-du"></a>

 데이터베이스의 사용자를 나열합니다. 해당 이름과 슈퍼 사용자 및 속성 등의 역할을 포함합니다.

## \$1dv[S\$1] [PATTERN]
<a name="rsql-query-tool-describe-dv"></a>

 보기를 나열합니다. 스키마, 유형 및 소유자 데이터를 포함합니다. 명령에 `S+`를 추가하면(예:`\dvS+`) 추가 메타데이터 열이 포함됩니다.

## \$1H
<a name="rsql-query-tool-describe-h"></a>

 HTML 출력을 설정합니다. 이는 형식이 지정된 결과를 빠르게 반환하는 데 유용합니다. 예를 들어 `select * from sales; \H`는 sales 테이블의 결과를 HTML로 반환합니다. 테이블형 결과로 다시 전환하려면 `\q` 또는 quiet을 사용합니다.

## \$1i
<a name="rsql-query-tool-describe-i"></a>

 파일에서 명령을 실행합니다. 예를 들어, 작업 디렉터리에 rsql\$1steps.sql이 있다고 가정하면 `\i rsql_steps.sql`은 파일에서 명령을 실행합니다.

## \$1l[\$1] [PATTERN]
<a name="rsql-query-tool-describe-l"></a>

 데이터베이스를 나열합니다. 소유자, 인코딩 및 추가 정보가 포함됩니다.

## \$1q
<a name="rsql-query-tool-describe-q"></a>

 quit 또는 `\q` 명령은 데이터베이스 세션을 로그오프하고 RSQL을 종료합니다.

## \$1sv[\$1] VIEWNAME
<a name="rsql-query-tool-describe-sv-name"></a>

 보기의 정의를 표시합니다.

## \$1timing
<a name="rsql-query-tool-describe-timing"></a>

 예를 들어 쿼리의 실행 시간을 표시합니다.

## \$1z [PATTERN]
<a name="rsql-query-tool-describe-z"></a>

 \$1dp와 동일한 출력입니다.

## \$1?
<a name="rsql-query-tool-help"></a>

 도움말 정보를 표시합니다. 이 선택적 파라미터는 설명할 항목을 지정합니다.

## \$1EXIT
<a name="rsql-query-tool-flow-control-exit"></a>

 모든 데이터베이스 세션을 로그오프하고 Amazon Redshift RSQL을 종료합니다. 또한 선택적 종료 코드를 지정할 수 있습니다. 예를 들어, `\EXIT 15`는 Amazon Redshift RSQL 터미널을 종료하고 종료 코드 15를 반환합니다.

다음 예는 연결 및 RSQL 종료의 출력을 보여줍니다.

```
% rsql -D testuser
DSN Connected
DBMS Name: Amazon Redshift
Driver Name: Amazon Redshift ODBC Driver
Driver Version: 1.4.34.1000
Rsql Version: 1.0.1
Redshift Version: 1.0.29306 
Type "help" for help.

(testcluster) user1@dev=# \exit 15

% echo $?
15
```

## \$1EXPORT
<a name="rsql-query-tool-export"></a>

 RSQL이 후속 SQL SELECT 문에서 반환하는 데이터베이스 정보를 저장하는 데 사용하는 내보내기 파일의 이름을 지정합니다.

export\$101.sql

```
\export report file='E:\\accounts.out'
\rset rformat off
\rset width 1500
\rset heading "General Title"
\rset titledashes on
select * from td_dwh.accounts;
\export reset
```

콘솔 출력

```
Rformat is off.
Target width is 1500.
Heading is set to: General Title
Titledashes is on.
(exported 40 rows)
```

## \$1LOGON
<a name="rsql-query-tool-flow-control-logon"></a>

 데이터베이스에 연결합니다. 위치 구문이나 연결 문자열을 사용하여 연결 파라미터를 지정할 수 있습니다.

명령 구문은 `\logon {[DBNAME|- USERNAME|- HOST|- PORT|- [PASSWORD]] | conninfo}`입니다.

`DBNAME`은 연결할 데이터베이스의 이름입니다. `USERNAME`은 연결할 사용자 이름입니다. 기본 `HOST`는 `localhost`입니다. 기본 `PORT`는 `5439`입니다.

`\LOGON` 명령에 지정된 호스트 이름이 추가 `\LOGON` 명령에 대한 기본 호스트 이름이 됩니다. 기본 호스트 이름을 변경하려면 추가 `\LOGON` 명령에 새 `HOST`를 지정합니다.

`user1`에 대한 `\LOGON` 명령의 샘플 출력은 다음과 같습니다.

```
(testcluster) user1@redshiftdb=# \logon dev
DBMS Name: Amazon Redshift
Driver Name: Amazon Redshift ODBC Driver
Driver Version: 1.4.27.1000
Rsql Version: 1.0.1
You are now connected to database "dev" as user "user1".
(testcluster) user1@dev=#
```

*user2*에 대한 샘플 출력

```
(testcluster) user1@dev=# \logon dev user2 testcluster2.example.com
Password for user user2: 
DBMS Name: Amazon Redshift
Driver Name: Amazon Redshift ODBC Driver
Driver Version: 1.4.27.1000
Rsql Version: 1.0.1
You are now connected to database "dev" as user "user2" on host "testcluster2.example.com" at port "5439".
(testcluster2) user2@dev=#
```

## \$1REMARK
<a name="rsql-query-tool-flow-control-remark"></a>

 `\echo` 명령의 확장입니다. `\REMARK`는 지정된 문자열을 출력 스트림에 출력합니다. `\REMARK `는 출력을 분리하는 기능을 추가하여 `\echo`를 확장합니다.

다음 샘플은 명령의 출력을 보여줍니다.

```
(testcluster) user1@dev=# \remark 'hello//world'
hello
world
```

## \$1RSET
<a name="rsql-query-tool-rset"></a>

`\rset` 명령은 명령 파라미터와 변수를 설정합니다.`\rset`에는 대화형 모드와 배치 모드가 모두 있습니다. *-x*와 같은 bash 옵션이나 *--<arg>*와 같은 인수의 옵션을 지원하지 않습니다.

다음과 같은 변수를 설정합니다.
+ ERRORLEVEL
+ HEADING 및 RTITLE
+ RFORMAT
+ MAXERROR
+ TITLEDASHES
+ WIDTH

다음 예에서는 헤딩을 지정합니다.

```
\rset heading "Winter Sales Report"
```

`\rset` 사용 방법의 추가 예제를 보려면 [Amazon Redshift RSQL 변수](rsql-query-tool-variables.md) 주제에서 여러 예를 확인할 수 있습니다.

## \$1RUN
<a name="rsql-query-tool-flow-control-run"></a>

 지정된 파일에 포함된 Amazon Redshift RSQL 스크립트를 실행합니다. `\RUN`은 파일의 헤더 행을 건너뛰는 옵션을 추가하여 `\i` 명령을 확장합니다.

파일 이름에 쉼표, 세미콜론 또는 공백이 포함된 경우 작은따옴표로 묶습니다. 또한 텍스트가 파일 이름 뒤에 오는 경우 따옴표로 텍스트를 묶습니다. UNIX에서 파일 이름은 대/소문자를 구분합니다. Windows에서 파일 이름은 대/소문자를 구분하지 않습니다.

다음 샘플은 명령의 출력을 보여줍니다.

```
(testcluster) user1@dev=# \! cat test.sql
select count(*) as lineitem_cnt from lineitem;
select count(*) as customer_cnt from customer;
select count(*) as orders_cnt from orders;



(testcluster) user1@dev=# \run file=test.sql
 lineitem_cnt
--------------
      4307207
(1 row)

 customer_cnt
--------------
     37796166
(1 row)

 orders_cnt
------------
          0
(1 row)


(testcluster) user1@dev=# \run file=test.sql skip=2
2 records skipped in RUN file.
 orders_cnt
------------
          0
(1 row)
```

## \$1OS
<a name="rsql-query-tool-flow-control-os"></a>

 `\!` 명령의 별칭입니다. `\OS`는 파라미터로 전달된 운영 체제 명령을 실행합니다. 명령이 실행되면 컨트롤이 Amazon Redshift RSQL로 돌아갑니다. 예를 들어, `\os date` 명령을 실행하여 현재 시스템 날짜 시간을 인쇄하고 RSQL 터미널로 돌아갈 수 있습니다.

```
(testcluster) user1@dev=# \os date
Tue Sep 7 20:47:54 UTC 2021
```

## \$1GOTO
<a name="rsql-query-tool-flow-control-goto"></a>

 Amazon Redshift RSQL을 위한 새로운 명령입니다. `\GOTO`는 중간에 있는 모든 명령을 건너뛰고 지정된 `\LABEL`에서 처리를 재개합니다. `\LABEL`은 정방향 참조여야 합니다. 사전적으로 `\GOTO` 앞에 오는 `\LABEL`을 건너뛸 수 없습니다.

다음은 샘플 출력을 보여줍니다.

```
(testcluster) user1@dev=# \! cat test.sql
select count(*) as cnt from lineitem \gset
select :cnt as cnt;
\if :cnt > 100
    \goto LABELB
\endif

\label LABELA
\remark 'this is label LABELA'
\label LABELB
\remark 'this is label LABELB'


(testcluster) user1@dev=# \i test.sql
   cnt
---------
 4307207
(1 row)

\label LABELA ignored
\label LABELB processed
this is label LABELB
```

## \$1LABEL
<a name="rsql-query-tool-flow-control-label"></a>

 Amazon Redshift RSQL을 위한 새로운 명령입니다. `\LABEL`은 프로그램을 실행하기 위한 진입점을 `\GOTO` 명령의 대상으로 설정합니다.

다음은 명령의 샘플 출력을 보여줍니다.

```
(testcluster) user1@dev=# \! cat test.sql
select count(*) from lineitem limit 5;
\goto LABELB
\remark "this step was skipped by goto label";
\label LABELA
\remark 'this is label LABELA'
\label LABELB
\remark 'this is label LABELB'



(testcluster) user1@dev=# \i testgoto.sql
  count
 4307193
(1 row)

\label LABELA ignored
\label LABELB processed
this is label LABELB
```

## \$1IF (\$1ELSEIF, \$1ELSE, \$1ENDIF)
<a name="rsql-query-tool-flow-control-if"></a>

 `\IF` 및 관련 명령은 입력 스크립트의 일부를 조건부로 실행합니다. PSQL `\if`(`\elif`, `\else`, `\endif`) 명령의 확장입니다. `\IF` 및 `\ELSEIF`는 `AND`, `OR` 및 `NOT` 조건을 포함한 부울 표현식을 지원합니다.

다음은 명령의 샘플 출력을 보여줍니다.

```
(testcluster) user1@dev=# \! cat test.sql
SELECT query FROM stv_inflight LIMIT 1 \gset
select :query as query;
\if :query > 1000000
    \remark 'Query id is greater than 1000000'
\elseif :query = 1000000
    \remark 'Query id is equal than 1000000'
\else
    \remark 'Query id is less than 1000000'
\endif


(testcluster) user1@dev=# \i test.sql 
 query
--------
 994803
(1 row)
 
Query id is less than 1000000
```

분기 로직에 `ERRORCODE`를 사용합니다.

```
\if :'ERRORCODE' = '00000'
    \remark 'The statement was executed without error'
\else
    \remark :LAST_ERROR_MESSAGE
\endif
```

`\IF` 블록 내에서 `\GOTO`를 사용하여 코드 실행 방법을 제어합니다.

# Amazon Redshift RSQL 변수
<a name="rsql-query-tool-variables"></a>

 RSQL에서 일부 키워드는 변수로 작동합니다. 각각을 특정 값으로 설정하거나 값을 재설정할 수 있습니다. 대부분은 대화형 모드와 배치 모드가 있는 `\rset`에 의해 설정됩니다. 소문자나 대문자로 명령을 정의할 수 있습니다.

## ACTIVITYCOUNT
<a name="rsql-query-tool-activitycount"></a>

 마지막으로 제출된 요청의 영향을 받는 행 수를 나타냅니다. 데이터 반환 요청의 경우 데이터베이스에서 RSQL로 반환되는 행 수입니다. 값은 0 또는 양의 정수입니다. 최댓값은 18,446,744,073,709,551,615입니다.

 특수 처리되는 변수 `ACTIVITYCOUNT`는 `ROW_COUNT` 변수와 비슷합니다. 하지만 `ROW_COUNT`는 `SELECT`, `COPY` 또는 `UNLOAD`에 대한 명령 완료 시 영향을 받는 행 수를 클라이언트 애플리케이션에 보고하지 않습니다. 하지만 `ACTIVITYCOUNT`는 보고합니다.

activitycount\$101.sql:

```
select viewname, schemaname
from pg_views
where schemaname = 'not_existing_schema';
\if :ACTIVITYCOUNT = 0
\remark 'views do not exist'
\endif
```

콘솔 출력:

```
viewname | schemaname
----------+------------
(0 rows)

views do not exist
```

## ERRORLEVEL
<a name="rsql-query-tool-describe-rset-errorlevel"></a>

오류에 심각도 수준을 할당합니다. 심각도 수준에 따라 일련의 조치를 결정할 수 있습니다. `ERRORLEVEL` 명령을 사용하지 않은 경우 해당 값은 기본적으로 `ON`입니다.

errorlevel\$101.sql:

```
\rset errorlevel 42P01 severity 0

select * from tbl;

select 1 as col;

\echo exit
\quit
```

콘솔 출력:

```
Errorlevel is on.
rsql: ERROR: relation "tbl" does not exist
(1 row)

col
1

exit
```

## HEADING 및 RTITLE
<a name="rsql-query-tool-describe-rset-heading-rtitle"></a>

보고서 상단에 표시되는 헤더를 지정할 수 있습니다. `RSET RTITLE` 명령에서 지정한 헤더에는 클라이언트 컴퓨터의 현재 시스템 날짜를 자동으로 포함됩니다.

rset\$1heading\$1rtitle\$102.rsql 내용:

```
\remark Starting...
\rset rtitle "Marketing Department||Confidential//Third Quarter//Chicago"
\rset width 70
\rset rformat on
select * from rsql_test.tbl_currency order by id limit 2;
\exit
\remark Finishing...
```

콘솔 출력:

```
Starting...
Rtitle is set to: &DATE||Marketing Department||Confidential//Third Quarter//Chicago (Changes will take effect after RFORMAT is
switched ON)
Target width is 70.
Rformat is on.
09/11/20       Marketing       Department Confidential
                  Third Quarter
                     Chicago
id  | bankid  | name |      start_date
100 |       1 | USD | 2020-09-11 10:51:39.106905
110 |       1 | EUR | 2020-09-11 10:51:39.106905
(2 rows)

Press any key to continue . . .
```

## MAXERROR
<a name="rsql-query-tool-describe-rset-maxerror"></a>

RSQL이 해당 수준을 넘으면 작업 처리를 종료하는 최대 오류 심각도 수준을 지정합니다. 반환 코드는 각 작업 또는 태스크를 완료한 후 RSQL이 클라이언트 운영 체제에 반환하는 정수 값입니다. 반환 코드 값은 작업 또는 태스크의 완료 상태를 나타냅니다. 지정된 `maxerror` 값보다 큰 오류 심각도 수준을 생성하는 문이 스크립트에 포함된 경우 RSQL이 즉시 종료됩니다. 따라서 오류 심각도 수준 8에서 RSQL가 종료되도록 하려면 `RSET MAXERROR 7`을 사용합니다.

maxerror\$101.sql 내용:

```
\rset maxerror 0
                        
select 1 as col;

\quit
```

콘솔 출력:

```
Maxerror is default.
(1 row)

col
1
```

## RFORMAT
<a name="rsql-query-tool-describe-rset-heading-rformat"></a>

형식 지정 명령에 대한 설정을 적용할지 여부를 지정할 수 있습니다.

rset\$1rformat.rsql 내용:

```
\remark Starting...
\pset border 2
\pset format wrapped
\pset expanded on
\pset title 'Great Title'
select * from rsql_test.tbl_long where id = 500;
\rset rformat
select * from rsql_test.tbl_long where id = 500;
\rset rformat off
select * from rsql_test.tbl_long where id = 500;
\rset rformat on
select * from rsql_test.tbl_long where id = 500;
\exit
\remark Finishing...
```

콘솔 출력:

```
Starting...
Border style is 2. (Changes will take effect after RFORMAT is switched ON)
Output format is wrapped. (Changes will take effect after RFORMAT is switched ON)
Expanded display is on. (Changes will take effect after RFORMAT is switched ON)
Title is "Great Title". (Changes will take effect after RFORMAT is switched ON)
id  |                                                             long_string
500 | In general, the higher the number the more borders and lines the tables will have, but details depend on the particular
format.
(1 row)

Rformat is on.
Great Title
+-[ RECORD 1 ]+----------------------------------------------------------------------------------------------------------------------
-----------+
| id           | 500
|
| long_string | In general, the higher the number the more borders and lines the tables will have, but details depend on the
particular format. |
+-------------+----------------------------------------------------------------------------------------------------------------------
-----------+

Rformat is off.
id  |                                                             long_string
500 | In general, the higher the number the more borders and lines the tables will have, but details depend on the particular format.
(1 row)

Rformat is on.
Great Title
+-[ RECORD 1 ]+----------------------------------------------------------------------------------------------------------------------
-----------+
| id           | 500
|
| long_string | In general, the higher the number the more borders and lines the tables will have, but details depend on the
particular format. |
+-------------+----------------------------------------------------------------------------------------------------------------------
-----------+
Press any key to continue . . .
```

## ROW\$1COUNT
<a name="rsql-query-tool-describe-rset-row_count"></a>

이전 쿼리의 영향을 받는 레코드 수를 가져옵니다. 일반적으로 다음 코드 조각에서처럼 결과를 확인하는 데 사용됩니다.

```
SET result = ROW_COUNT;

IF result = 0
...
```

## TITLEDASHES
<a name="rsql-query-tool-describe-rset-heading-titledashes"></a>

이 컨트롤을 사용하면 SQL 문에 대해 반환된 열 데이터 위에 대시 문자 행을 인쇄할지 여부를 지정할 수 있습니다.

예제:

```
\rset titledashes on
select dept_no, emp_no, salary from rsql_test.EMPLOYEE
where dept_no = 100;
\rset titledashes off
select dept_no, emp_no, salary from rsql_test.EMPLOYEE
where dept_no = 100;
```

콘솔 출력:

```
dept_no      emp_no          salary
----------- ----------- --------------------
100         1000346        1300.00
100         1000245        5000.00
100         1000262        2450.00

dept_no     emp_no         salary
100         1000346        1300.00
100         1000245        5000.00
100         1000262        2450.00
```

## WIDTH
<a name="rsql-query-tool-describe-rset-heading-width"></a>

보고서의 출력 형식을 래핑으로 설정하고 각 행의 대상 너비를 지정합니다. 파라미터를 지정하지 않으면 형식과 대상 너비 모두 현재 설정이 반환됩니다.

rset\$1width\$101.rsql 내용:

```
\echo Starting...
\rset width
\rset width 50
\rset width
\quit
\echo Finishing...
```

콘솔 출력:

```
Starting...
Target width is 75.
Target width is 50.
Target width is 50.
Press any key to continue . . .
```

파라미터를 사용하는 예:

```
\echo Starting...
\rset rformat on
\pset format wrapped
select * from rsql_test.tbl_long where id = 500;
\rset width 50
select * from rsql_test.tbl_long where id = 500;
\quit
\echo Finishing...
```

콘솔 출력:

```
Starting...
Rformat is on.
Output format is wrapped.
id  |                                          long_string
500 | In general, the higher the number the more borders and lines the ta.
    |.bles will have, but details depend on the particular format.
(1 row)

Target width is 50.
id  |                                          long_string
500 | In general, the higher the number the more.
    |. borders and lines the tables will have, b.
    |.ut details depend on the particular format.
    |..
(1 row)
Press any key to continue . . .
```

# Amazon Redshift RSQL 오류 코드
<a name="rsql-query-tool-error-codes"></a>

성공 메시지, 경고 및 예외:

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/redshift/latest/mgmt/rsql-query-tool-error-codes.html)

데이터 예외:

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/redshift/latest/mgmt/rsql-query-tool-error-codes.html)

무결성 제약 조건 위반:

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/redshift/latest/mgmt/rsql-query-tool-error-codes.html)

# Amazon Redshift RSQL 환경 변수
<a name="rsql-query-tool-environment-variables"></a>

 Amazon Redshift RSQL은 환경 변수를 사용하여 기본 파라미터 값을 선택할 수 있습니다.

## RSPASSWORD
<a name="rsql-query-tool-rspassword"></a>

**중요**  
일부 운영 체제에서는 관리자 사용자가 아닌 사용자가 프로세스 환경 변수를 볼 수 있으므로 보안상의 이유로 이 환경 변수를 사용하지 않는 것이 좋습니다.

 Amazon Redshift에 연결할 때 사용할 Amazon Redshift RSQL의 암호를 설정합니다. 이 환경 변수에는 Amazon Redshift RSQL 1.0.4 이상이 필요합니다.

 RSPASSWORD가 설정된 경우 RSQL은 RSPASSWORD에 우선 순위를 둡니다. RSPASSWORD가 설정되지 않고 DSN을 사용해 연결하는 경우 RSQL은 DSN 파일의 파라미터에서 암호를 가져옵니다. 또한 RSPASSWORD가 설정되지 않고 DSN을 사용하지 않는 경우 RSQL은 연결을 시도한 후 암호 프롬프트를 제공합니다.

다음은 RSPASSWORD를 설정하는 예입니다.

```
export RSPASSWORD=TestPassw0rd
```