1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

pg_bulkloadを使ってCSVファイルから固定長のバイナリファイルを出力する

Posted at

pg_bulkload(PostgreSQL 向けの高速データロードユーティリティ)には,独自のバイナリフォーマットがあります.
公式ドキュメントに,pg_bulkloadの使い方が載っていますが,バイナリファイルを出力するためのサンプルとなる制御ファイルはありません.
そこで本ページでは,CSVファイルをpg_bulkloadのバイナリフォーマットに変換するための制御ファイルを紹介します.

想定するロード先テーブル

         Table "public.users"
 Column |       Type        | Modifiers 
--------+-------------------+-----------
 name   | character varying | 
 age    | integer           | 
 weight | real              | 

サンプルCSVファイル

input.csv
"taro",17,55.0
"jiro",15,53.0
"saburo",13,45.0

サンプル制御ファイル

output_binary.ctl
# 入力はCSVファイル
TYPE = CSV
# 標準入力から読み込む
INPUT = stdin
WRITER = BINARY
OUTPUT = /tmp/test.bin

# カラムの型情報をOUT_COLで指定する
OUT_COL = VARCHAR(10)
OUT_COL = INTEGER(4)
OUT_COL = FLOAT(4)

コマンド

$ pg_bulkload output_binary.ctl < input.csv
NOTICE: BULK LOAD START
NOTICE: BULK LOAD END
        0 Rows skipped.
        3 Rows successfully loaded.
        0 Rows not loaded due to parse errors.
        0 Rows not loaded due to duplicate errors.
        0 Rows replaced with new rows.

出力

$ od -c /tmp/test.bin
0000000   t   a   r   o                         021  \0  \0  \0  \0  \0
0000020   \   B   j   i   r   o                         017  \0  \0  \0
0000040  \0  \0   T   B   s   a   b   u   r   o                  \r  \0
0000060  \0  \0  \0  \0   4   B
0000066
/tmp/test.bin.ctl
INPUT = /tmp/test.bin
OUTPUT = test
LOGFILE = /tmp/test.bin.log
PARSE_BADFILE = /tmp/test.bin.prs
DUPLICATE_BADFILE = /tmp/test.bin.dup
PARSE_ERRORS = INFINITE
DUPLICATE_ERRORS = 0
ON_DUPLICATE_KEEP = NEW
SKIP = 0
LIMIT = INFINITE
CHECK_CONSTRAINTS = NO
MULTI_PROCESS = YES
VERBOSE = NO
TRUNCATE = NO
WRITER = DIRECT
TYPE = BINARY
COL = VARCHAR (10)
COL = INTEGER (4)
COL = FLOAT (4)
# ENCODING = SQL_ASCII
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?