1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

psql の URI(接続文字列) でパスワードやスキーマを指定できる

1
Posted at

はじめに

これは、PostgreSQL Advent Calendar 2025の14日目の記事となります。

本当は「Windows版PostgreSQLの拡張機能 pg_dbms_stats をビルドする」の記事を書く予定でしたが、検証に時間がかかりそうなので、シリーズ 2のどこかに書く予定です。

psql の URI指定

最近、psqlでスキーマを指定したいとネット検索していて、この方法を知りました。

従来の指定
psql -h localhost -p 5432 -U postgres -d sampledb

psql は URI(接続文字列) で指定することが出来ます。

URI形式
psql "postgresql://ユーザー名:パスワード@ホスト名:ポート番号/データベース名"
psql "postgresql://postgres:secret@localhost:5432/sampledb"
要素 省略可 説明
ユーザー名 省略すると OS ユーザー名
パスワード 省略可(後述)
@ × 省略不可
ホスト名 省略するとローカル
ポート 省略すると 5432
データベース名 省略するとユーザー名と同名

URI のスキーム

接続 URI のスキーム(postgresql://の部分)はどちらも同義として扱われており、両方をサポートしています。

  • 正式名称:postgresql://
  • 省略エイリアス:postgres://

パスワード指定

筆者は、セキュリティ上は非推奨であるが Windows バッチ内に環境変数(PGPASSWORD)を設定した上で実行していました。

SET PGPASSWORD=(パスワード)
psql -U (ユーザー) -f xxxxx.sql 

URI では接続文字列内に埋め込み可能です。

psql "postgresql://ユーザー名:パスワード@ホスト名:ポート番号/データベース名"

もちろん従来通り(.pgpassファイル)でパスワードを省略することもできます。

接続オプション

接続オプションは、queryパラメータとして指定します。

query(一部) 内容
sslmode SSLモード
connect_timeout タイムアウト
options オプション
sslmode
psql "postgresql://user@host/dbname?sslmode=require"
connect_timeout
psql "postgresql://user@host/dbname?connect_timeout=10"

複数指定は、&で結合します。

複数指定
psql "postgresql://user@host/dbname?sslmode=disable&connect_timeout=5"

スキーマ指定

クエリのoptionsにて、-csearch_pathを指定します。

psql "postgresql://user@localhost/dbname?options=-csearch_path%3Dmyschema"

%3D = =

これまでスキーマ切り替えは、sqlファイル内に埋め込んでいました。
これだとパラメータを渡してスキーマを変更できなくて、スキーマごとにファイル名を分けていて不便でした。

CreateTable.sql
-- スキーマ切り替え
SET search_path = schema1;

\i table_create.sql

主なURIクエリエンコード

クエリパラメータで特殊文字はエンコード指定する必要があります。

記号 変換
空白 %20
@ %40
& %26
/ %2F
: %3A
= %3D
? %3F
% %25
[ %5B
] %5D

最後に

psql の URI(接続文字列) は、いろいろ使えそうですね。
急遽、記事内容を変更しましたが、何とか間に合いました。

1
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?