ねら~ITエンジニア雑記

やきうのお兄ちゃんが綴るOracle Databaseメインのブログ

名前付きパイプ(mkfifo)でsqlplusのspool結果を圧縮しながらファイル出力する。(Oracle Database)

表題の通り、名前付きパイプ(mkfifo)でsqlplusのspool結果を圧縮しながらファイル出力してみるやで彡(゚)(゚)

1. 名前付きパイプの作成(mkfifo)とgzipコマンドのバックグラウンド実行

下記コマンドを実行します。

(1). mkfifoコマンドで名前付きパイプを作成
(2). 名前付きパイプのcat結果をgzip圧縮して、ファイルにリダイレクトするコマンドをバックグラウンド実行

mkfifo gzip.pipe
cat gzip.pipe | gzip -c > orders.csv.gz &
ls -la

total 12
drwxrwxr-x.  2 opc opc 4096 Mar 26 13:47 .
drwxrwxr-x. 24 opc opc 4096 Mar 26 13:23 ..
prw-rw-r--.  1 opc opc    0 Mar 26 13:46 gzip.pipe ★名前付きパイプ
-rw-rw-r--.  1 opc opc    0 Mar 26 13:47 orders.csv.gz
-rw-rw-r--.  1 opc opc  413 Mar 26 13:28 orders_csv.sql

2. ファイル出力のSQL

下記がファイル出力のSQLです。spool先は名前付きパイプ(gzip.pipe)としています。

cat orders_csv.sql

-- orders_csv.sql
SET LINESIZE 32767;
SET PAGESIZE 0;
SET FEED OFF;
SET TRIMSPOOL ON;
SET TERMOUT OFF;
SET ARRAYSIZE 5000;
SET COLSEP ,
ALTER SESSION SET NLS_TIMESTAMP_FORMAT='YYYY/MM/DD HH24:MI:SS.FF';
-- spool to named pipe.
spool gzip.pipe
PROMPT ORDER_ID,ORDER_DATE,CUSTOMER_ID,ORDER_STATUS
SELECT ORDER_ID, ORDER_DATE, CUSTOMER_ID, ORDER_STATUS FROM ORDERS WHERE ROWNUM <= 10000;
spool off;
EXIT;

3. sqlplusでSQLを実行(ファイル出力)

sqlplus で SQL を実行して、ファイルを出力します。

sqlplus /nolog
CONNECT xxxxxxxx/yyyyyyyy@zzzzzzzz
@./orders_csv.sql

Connected.

Disconnected from Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production

[1]+ Done cat gzip.pipe | gzip -c > orders.csv.gz ★バックグラウンドのgzipが終了している。

4. 圧縮ファイルの結果確認

gunzipコマンドで圧縮ファイルの結果を確認します。バッチリや!彡(^)(^)

ls -la
gunzip -c orders.csv.gz

total 140
drwxrwxr-x.  2 opc opc   4096 Mar 26 13:48 .
drwxrwxr-x. 24 opc opc   4096 Mar 26 13:23 ..
prw-rw-r--.  1 opc opc      0 Mar 26 13:49 gzip.pipe
-rw-rw-r--.  1 opc opc 128586 Mar 26 13:49 orders.csv.gz ★gzip圧縮されて出力されたファイル
-rw-rw-r--.  1 opc opc    378 Mar 26 13:48 orders_csv.sql

ORDER_ID,ORDER_DATE,CUSTOMER_ID,ORDER_STATUS
717508,2007/12/13 05:00:00.000000,952991,7
717509,2009/05/28 19:00:00.000000,728526,6
717510,2011/02/28 02:00:00.000000,914050,5
717511,2008/07/11 15:00:00.000000,385931,4
717512,2012/01/30 03:00:00.000000,953603,6
:
:
728011,2007/10/01 00:00:00.000000,830197,4
728012,2010/08/25 01:00:00.000000,39406,6
728013,2007/11/30 23:00:00.000000,280994,4
728014,2007/07/20 12:00:00.000000,342535,6

5. 名前付きパイプの削除(rm)

名前付きパイプはファイル同様にrmコマンドで削除できます。

rm gzip.pipe
ls -la

total 140
drwxrwxr-x.  2 opc opc   4096 Mar 26 13:54 .
drwxrwxr-x. 24 opc opc   4096 Mar 26 13:23 ..
-rw-rw-r--.  1 opc opc 128586 Mar 26 13:49 orders.csv.gz
-rw-rw-r--.  1 opc opc    378 Mar 26 13:48 orders_csv.sql

6. まとめ

圧縮しながらsqlplusでSPOOLできる!今回はsqlplusのspoolでしたが、応用は色々効きそう。
なお名前付きパイプによるxxしながら圧縮は、MySQL界隈では必須テクニックぽい?彡(゚)(゚)

MySQLのダンプファイルを圧縮しながら書き出す
http://huruyosi.hatenablog.com/entry/2015/10/20/014254
 
[mysql]dumpファイルのサイズを気にせずに別サーバへデータを転送する
https://qiita.com/qr_taka/items/7136550a8b8499bab592