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 1 year has passed since last update.

psqlで¥copyコマンドにパラメータを渡せない問題の対応策

Posted at

公式ページに記載があるが、¥copy コマンドに対して variable interplation(or variable substitution)は使えない。

workaroundとして、コマンド文を組み立てる。

env.env
# Mac's psql install path.
SQL_EXEC=/usr/local/Cellar/libpq/[version]/bin/psql

# DB Connection Info.
POSTGRES_USER=postgres
POSTGRES_DB=postgres
POSTGRES_HOST=localhost
POSTGRES_PORT=5432

DB_CONNECT_STRING="-U ${POSTGRES_USER} -d ${POSTGRES_DB} -h ${POSTGRES_HOST} -p ${POSTGRES_PORT}"
# FILE_NAMES
FILENAME=/Users/username/dev/shell/sample.dat
data_load.sh
# env.envの中身を読み込む
. ./env.env
SQL_FILE=copyFrom.sql
${SQL_EXEC} ${DB_CONNECT_STRING} -f ${SQL_FILE} -v inputFile=${FILENAME}
copyFrom.sql
\set filename :inputFile

--\copyコマンドに変数代入はできない
--\copy temp from :inputpath;

\set command '\\copy temp FROM ' :'filename'
:command

参考URL

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?