PostgreSQL/クイックスタート

From Gentoo Wiki
Jump to:navigation Jump to:search
This page is a translated version of the page PostgreSQL/QuickStart and the translation is 66% complete.


これは、PostgreSQL のインストールと構成を対応範囲としたクイックスタートガイドです。これは公式ドキュメントを補足するもので、それに取って代わることを意図するものではありません。

はじめに

PostgreSQL はフリーでオープンソースの関係データベース管理システム (RDBMS; Relational Database Management System) です。PostgreSQL はトランザクション、スキーマ、外部キーなどをサポートし、商用も含めて他のいかなるデータベースよりもデフォルトで SQL 標準に追従し、よりセキュアであるとよく言われています。

より詳しい情報をお求めなら、postgresql.org のウェブサイトのページ About をご覧ください。

この記事で説明すること

この記事は Gentoo に特化した PostgresSQL RDBMS のインストールガイドです。

この記事で使用する ebuild は dev-db/postgresql です。

この記事では、あなたが PostgreSQL の最新安定版をインストールするという仮定でお話しします。これを書いている時点でのバージョンは 9.3.5 ですが、あなたがインストールするバージョンに応じてコマンドを調整してください。

ebuild について

PostgreSQLはPortageのebuild機能でメジャーバージョンに基づいたスロットを提供しています。これにより、PostgreSQLの2つの主要バージョンを同時に動作させることができます。9.0-9.4のライブラリとサーバーを同時にインストールして使用することができます。これは、古いデータベースから新しいデータベースにデータを移動する必要がある場合、または本番データベースとテスト用データベースを同じマシンに配置する必要がある場合に役立ちます。また、これにより、データベース、対応するライブラリ、または実行可能ファイルが、互換性のない更新によって上書きされるのを防ぎます。このガイドで説明されている移行が必要になります。

さらに、マイナーバージョンアップで提供されているバグやセキュリティの修正は、データベースやPostgreSQLのインストール自体を破壊する恐れなしに適用することができます。9.3.4は互換性があることが保証されているため9.3.5に更新できます。9.3.4を出現させてサーバープロセスを再起動する以上の操作は不要です。移行、再構成、初期化は不要です。

詳細はPostgreSQLのバージョン管理方針を読んでください。

この記事で説明しないこと

カバーされないことがかなりあります。公式ドキュメントは、2,000ページ近くあります。 そのため、このクイックスタートガイドでは、多くの詳細を省略します。 Gentoo固有の問題といくつかの基本的な構成ガイドラインのみがカバーされます。

インストール

USE フラグ

USE flags for dev-db/postgresql PostgreSQL RDBMS

debug Enable extra debug codepaths, like asserts and extra output. If you want to get meaningful backtraces see https://wiki.gentoo.org/wiki/Project:Quality_Assurance/Backtraces
doc Add extra documentation (API, Javadoc, etc). It is recommended to enable per package instead of globally
icu Enable ICU (Internationalization Components for Unicode) support, using dev-libs/icu
kerberos Add kerberos support
ldap Add LDAP support (Lightweight Directory Access Protocol)
llvm Add support for llvm JIT engine
lz4 Enable support for lz4 compression (as implemented in app-arch/lz4)
nls Add Native Language Support (using gettext - GNU locale utilities)
pam Add support for PAM (Pluggable Authentication Modules) - DANGEROUS to arbitrarily flip
perl Add optional support/bindings for the Perl language
python Add optional support/bindings for the Python language
readline Enable support for libreadline, a GNU line-editing library that almost everyone wants
selinux !!internal use only!! Security Enhanced Linux support, this must be set by the selinux profile or breakage will occur
server Disable to build and install the clients and libraries only.
ssl Add support for SSL/TLS connections (Secure Socket Layer / Transport Layer Security)
static-libs Build static versions of dynamic libraries as well
systemd Enable use of systemd-specific libraries and features like socket activation or session tracking
tcl Add support the Tcl language
uuid Enable server side UUID generation (via dev-libs/ossp-uuid).
xml Add support for XML files
zlib Add support for zlib compression
zstd Enable support for ZSTD compression

重要な USE フラグについての情報:

  • doc: システム上にオンラインドキュメントを保存します
  • pg_legacytimestamp: タイムスタンプの整形のために、より高精度な 64 ビット整数ではなく、古い、浮動小数点方式を使用します。この非推奨の方式を利用しているバージョンを以前からインストールしているのでない限り、この USE フラグは無効なままにしておいてください。'pg_legacytimestamp' を変更すると、タイムスタンプを利用するデータベースがひとつでもある場合、データベースのダンプとリストアが必要になるでしょう。2 つの方式はお互いに互換性がありません。
  • readline: これは本当に有効化したいでしょう。無効化すると psql コマンドライン上の編集と履歴機能が取り除かれます。
  • selinux: これは SELinux プロファイルを使用することによってのみ有効化するこができます。
  • uuid: 128 ビットランダム一意識別子の生成のサポートを含めます。衝突の確率が極めて低くなるため、これはデータベースをマージするのに有用です。

Emerge

root #emerge --ask dev-db/postgresql
[ebuild N ] dev-db/postgresql-9.3.5 USE="doc -kerberos -ldap -pg_legacytimestamp
  nls perl python -pg_legacytimestamp (-selinux) readline ssl -tcl -threads
  -uuid -xml zlib" LINGUAS="-af -cs -de -es -fa -fr -hr -hu -it -ko -nb -pl
  -pt_BR -ro -ru -sk -sl -sv -tr -zh_CN -zh_TW" 0 kB

上のパッケージのいずれかが、以下のパッケージの一部または全部によってブロックされているという通知を受け取るかもしれません: dev-db/postgresql-libsdev-db/postgresql-client、または dev-db/libpq。これらのパッケージは保守されておらず、旧式化されました (Gentoo ebuild リポジトリから削除されました)。この状況に対処する方法を知るためには、以前の ebuild から新しい ebuild への移行のセクションを参照してください。

データベースクラスタの初期化の準備をする

パッケージの emerge が完了したら、/etc/conf.d/postgresql-9.3 を編集したいかもしれません。サーバのデフォルト設定に影響し、データベースクラスタを含むディレクトリを削除して再初期化する以外の方法で後で変更できない設定が、3 行あります。

PGDATA defines where to place the configuration files. DATA_DIR defines where to create the database cluster and related files. PG_INITDB_OPTS may contain any extra options you would care to set. The extra options are not required as the reasonable defaults are, ahem, reasonable.

In the following example, PGDATA states that the configuration files are to be located in /etc/postgresql-9.3/ . DATA_DIR states that the database cluster should be installed to /var/lib/postgresql/9.3/data/ , which is the default. If you decide to stray from the default, bear in mind that it is a very good idea to keep the major version in the path. PG_INITDB_OPTS states that the default locale should be en_US.UTF-8 . That is, U.S. English ordering and formatting, and UTF-8 character encoding.

ファイル /etc/conf.d/postgresql-9.3内容例
# 設定ファイルの場所
PGDATA="/etc/postgresql-9.3/"
# data ディレクトリがどこにあるか/作成されるか
DATA_DIR="/var/lib/postgresql/9.3/data"
# initdb に渡す追加のオプション。
# 利用可能なオプションについては 'man initdb' を参照してください。
PG_INITDB_OPTS="--locale=en_US.UTF-8"
メモ
これはデフォルトのロケールと文字エンコーディングを決定しているだけです。同じデータベースクラスタ内にデータベースを作成する (CREATE DATABASE) ときに、異なるロケールや文字エンコーディングを指定することができます。

--locale= を上書きするために設定できる 6 個のロケールオプションがあります。次の表に 6 個のオプションを列挙します。使用する場合は、--option=lo_LO.ENCODING の形式で整形してください。

オプション 効果
lc-collate 文字列のソート順
lc-ctype 文字の分類 (アルファベットとは? この文字の大文字はどれ?)
lc-messages メッセージの言語
lc-monetary 通貨の整形
lc-numeric 数値の整形
lc-time 日付と時刻の整形

したがって、デフォルトを英語にしたいが、たとえばスウェーデン語のメッセージが必要な場合、 PG_INITDB_OPTSは次のようになります。

コード PG_INITDB_OPTS を設定する
PG_INITDB_OPTS="--locale=en_US.UTF-8 --lc-messages=sv_SE.UTF-8"

A complete list of language and character encodings supported by the server can be found in the documentation, but your system must also support the respective languages and character encodings. Compare the output of locale -a to the encodings in the documentation.

You can change your locale and encoding selections at database creation time. In order to change the locale for a database after you have created it, you must drop the database and start over again.

root #emerge --config dev-db/postgresql:9.3

これにより、データベースクラスターが作成され、すべての関連サーバーファイルが PGDATAおよび DATA_DIRに格納されます。

設定

設定ファイルはどこにあるのでしょうか

Sample configuration files can be found in /usr/share/postgresql-9.3 (or whatever version), see the trouble shooting section for the script.

This time the focus is upon the files in the PGDATA directory, /etc/postgresql-9.3 , instead with primary focus on the postgresql.conf and pg_hba.conf files.

postgresql.conf

This is the main configuration file. The line that you may find of immediate interest is listen_addresses . This variable defines to which addresses PostgreSQL will bind. By default, only localhost and the Unix socket are bound. Changing listen_addresses is not enough to enable remote connections. That will be covered in the next section. The official documentation is fairly easy to understand and is exhaustive on all the settings available. It would behoove you to read that in addition to what is covered here as some things may change.

Of secondary interest is the logging destination. By default, everything is logged to postmaster.log in the DATA_DIR directory. There is an entire subsection of postgresql.conf that covers a slew of options for how, what and where to log. The subsection is marked: ERROR REPORTING AND LOGGING.

Other than listen_addresses and the logging options, the rest of the defaults in postgresql.conf are reasonable enough to get you going.

pg_hba.conf

pg_hba.confファイルは、誰がデータベースサーバへの接続を許可されているか、接続を確立するためにどの認証方法を使用しなければならないかを記述しています。繰り返しになりますが、ドキュメントには設定とその意味が網羅されていますが、明確にするためにいくつかのことをここでカバーしています。

ファイル pg_hba.confDefault settings
# TYPE  DATABASE    USER        CIDR-ADDRESS          METHOD
# 
# "local" is for Unix domain socket connections only
local   all         all                               trust
# IPv4 local connections:
host    all         all         127.0.0.1/32          trust
# IPv6 local connections:
host    all         all         ::1/128               trust

As has been mentioned before, by default the server is secure. Kind of. There is only one database role that is available for log in by default: postgres . And, the only way to initiate a connection to the database is through the /run/postgresql/.s.PGSQL.5432 Unix socket, which is owned by the postgres system user and system group, or via localhost. Now for the "kind of" bit: Any user on the system can make a connection to the database through the localhost. Even as the postgres database superuser.

警告
Never disable the Unix socket entirely. The initscripts require access to it in order to operate properly. The method can be changed freely.

trustメソッドは、全てのユーザーがパスワードなしで任意のユーザーとしてログオンできるようにするものです。これは、それが暗示するものを指定しているだけです。指定されたデータベースへの指定されたタイプのすべての接続を、指定された場所から指定されたデータベースユーザ(システムユーザではない)からパスワードなしで指定されたデータベースへのすべての接続を信頼します。これにより、システム上の全てのユーザが最初からローカルホスト接続を介して任意のユーザとしてログオンできるようになります。これは見かけほど危険ではありませんが、ほとんどの状況で深刻なセキュリティリスクをもたらします。

最もよく使用する2つの方法は、 passwordmd5です。 passwordメソッドは、接続を開始するためにパスワードが必要であり、パスワードが「in-the-clear」で送信されることのみを指定します。 この方法は、Unixソケットやlocalhostを介して接続するなど、そのような情報がマシンから出てこない場合に適しています。 md5メソッドはパスワードに似ていますが、md5ハッシュを使用してパスワードを保護します。 これは、パスワードがネットワークを通過するときに使用したいものです。

At this point, this author would like to bring your attention to the last two lines, four lines including comments, of the pg_hba.conf file. PostgreSQL has native support for IPv6 regardless of your desires for such support. Additionally, IPv4 addresses are automatically mapped to IPv6 addresses, i.e. , 127.0.0.1 will be mapped to ::FFFF:127.0.0.1 and as "pure" IPv6 ::FFFF:7F00:0001.

ただし、ホスト名がIPアドレスにどのようにマップされるかについては、誤解があるようです。 /etc/hostsファイルを見てみましょう。

ファイル /etc/hosts
# IPv4 and IPv6 localhost aliases
127.0.0.1       localhost
::1             localhost

From the example above you can see that both an IPv4 and an IPv6 IP address are mapped to localhost. When psql refers to this file, it will grab the first match and use that as the address; in this case 127.0.0.1. When PostgreSQL parses this, it will match the IPv6 formatted address as well, e.g. ::ffff:127.0.0.1. If, however, the IPv6 address appears first, then psql will map to ::1 alone; ::1 is not the same as ::ffff:127.0.0.1. As such, if you do not have ::1 as a permitted means of access, psql will not be able to establish a connection. Furthermore, your kernel needs to support the IPv6 protocol.

So, it is better to specify IP addresses alone to psql and in pg_hba.conf rather than to rely on /etc/hosts to be ordered properly, and it removes any doubt as to which IP addresses are allowed or to which server you will connect.

サーバを起動する

やってみよう!

Now start PostgreSQL and set the password for the database superuser postgres.

Change 'trust' to 'password' for the 'host' (not the 'local', Unix domain socket) connections.

root #nano -w /etc/postgresql-9.3/pg_hba.conf

Now start the database:

root #/etc/init.d/postgresql-9.3 start
postgresql-9.3  | * Starting PostgreSQL ...                             [ ok ]

サーバーへの接続を開き、パスワードを設定します:

root #psql -U postgres
psql (9.3.5)
Type "help" for help.
postgres=#\password
Enter new password:
Enter it again:
postgres=#\q

Change 'trust' to 'password' for the local connection:

root #nano -w /etc/postgresql-9.3/pg_hba.conf

次に、データベースに構成を再ロードさせます:

root #/etc/init.d/postgresql-9.3 reload
postgresql-9.3 | * Reloading PostgreSQL configuration ...               [ ok ]

Finally, once everything works as it should, have PostgreSQL start at boot:

root ## rc-update add postgresql-9.3 default
 * service postgresql-9.3 added to runlevel default

At this point you are ready to continue on with the official PostgreSQL Tutorial. The tutorial will guide you through creating roles, databases, schemata and all that fun and useful stuff.

PostgreSQL のバージョンを移行する

いつ移行する必要があるのか

移行を実行する必要がある理由は2つだけあります。あるメジャーバージョンから別のメジャーバージョンに移行する場合、たとえば、PostgreSQL 8.4.7から9.0.3に移行しますが、9.0.2から9.0.3には移行しません。 または、非推奨の浮動小数点タイムスタンプ形式から新しい64ビット整数タイムスタンプ形式に切り替える場合。

メモ
You will need to migrate your database when you move from the obsolete ebuilds dev-db/libpq, dev-db/postgresql-libs, and dev-db/postgresql-client or dev-db/postgresql older than 9.0 to the new dev-db/postgresql ebuild.


Post-9.0 migration

When upgrading from a previous version of the recent ebuilds, which is any version after 8.4, follow the beginning of this guide before proceeding with this migration.

pg_upgrade, a new utility that comes along with 9.0 and later, simplifies the migration process rather drastically.

However, there are two caveats with using pg_upgrade. Firstly, it does not support configuration files being in a different directory than where the data is stored. This can be resolved by using symbolic links. Lastly, it can only migrate from a database from 8.3 or newer. If the database is older, then follow the instructions to migrate from pre-9.0 deployments.

First ensure that the new database cluster is initialized (as described above). Then stop the servers that are going to migrate from and to:

root #/etc/init.d/postgresql-8.4 stop
root #/etc/init.d/postgresql-9.3 stop
root #ln -s /etc/postgresql-8.4/*.conf /var/lib/postgresql/8.4/data/
root #ln -s /etc/postgresql-9.3/*.conf /var/lib/postgresql/9.3/data/
メモ
Symbolic links are already in place from version 9.4 onward.

利用可能なバージョンを確認してから、あなたのバージョンを選択してください:

root #eselect postgresql list
root #eselect postgresql set 9.3

Change the method of database user 'postgres' to trust on local connections on all databases:

root #nano -w /etc/postgresql-8.4/pg_hba.conf
root #nano -w /etc/postgresql-9.3/pg_hba.conf

It may be necessary to change the permissions of /var/lib/postgresql/ before performing the next step.

root #su - postgres
user $pg_upgrade -U postgres \

-d /var/lib/postgresql/8.4/data -D /var/lib/postgresql/9.3/data \

-b /usr/lib/postgresql-8.4/bin -B /usr/lib/postgresql-9.3/bin
メモ
PostgreSQL prior to version 9.4 used the -u option instead of -U.
メモ
On amd64 and other multilib capable arches, the binary path will be /usr/lib64/postgresql-${PV}/bin.

Perform the tasks pg_upgrade tells you to do, if any.

user $logout

これで完了です:

root #/etc/init.d/postgresql-9.3 start

Pre-9.0 migration: With the new ebuilds

Because the new ebuilds feature a more advanced slotting method than the previous ones, the downtime is quite minimal, most likely minutes rather than hours.

In the following examples, it is assumed that you are using the default locations and port settings, and that you are migrating from 8.3 to 8.4. Adjust accordingly if you have deviated from the default.

If you have not already done so, follow the installation instructions before starting the migration. Such a compile may hamper performance on the database server but it can keep going.

A couple of files need to be tweaked before beginning the migration. Edit PGPORT in the /etc/conf.d/postgresql-8.4 configuration file to 6543. (Any port number other than what your old installation is bound to will do.)

Next, edit /etc/postgresql-8.3/pg_hba.conf so that only the database superuser postgres can access the database cluster via the Unix socket.

root #cp -p /etc/postgresql-8.3/pg_hba.conf /etc/postgresql-8.4/

The following should be safe. Read the documentation to be sure.

root #cp -p /etc/postgresql-8.3/postgresql.conf /etc/postgresql-8.4/

Don't forget to copy over any other configuration files that you may need.

root #/etc/init.d/postgresql-8.3 reload
root #/etc/init.d/postgresql-8.4 start

Begin piping the data from the old cluster to the new cluster.

root #pg_dumpall -U postgres -p 5432 | psql -U postgres -d postgres -p 6543
root #/etc/init.d/postgresql-8.3 stop
root #/etc/init.d/postgresql-8.4 stop

PGPORT を編集して 5432 に戻します。

root #nano -w /etc/conf.d/postgresql-8.4

ユーザーにもう一度アクセスを許可します。

root #nano -w /etc/postgresql-8.4/pg_hba.conf
root #/etc/init.d/postgresql-8.4 start
root #rc-update del postgresql-8.3 && rc-update add postgresql-8.4 default

Hopefully everything went according to plan and you have a successfully updated server that contains precisely the same data, bit for bit, as the old server.

Pre-9.0 migration: From the obsolete ebuilds

サーバーのダウンタイムを予定する必要があります。古い ebuilds は新しい ebuilds と同時にインストールすることはできません。そのため、サーバーを数時間ダウンさせなければならないことを想定してください。もしかしたら週末になるかもしれません。

Before starting, you will need to deny access to the server, so that no changes are made. You may also want to backup your postgresql.conf and pg_hba.conf and any other configuration file that you deem important.

root #pg_dumpall -U postgres > backup_file
root #/etc/init.d/postgresql stop
root #emerge -C dev-db/libpq dev-db/postgresql-client dev-db/postgresql-libs

Follow the steps detailed in this article for installing and configuring the server.

root #/etc/init.d/postgresql-8.4 start
root #psql -f backup_file postgres

You may break some packages that were built against those packages, but once you have installed dev-db/postgresql you can run revdep-rebuild to reemerge any packages that may have been broken.

ユーティリティー

pgAdmin

pgAdmin は、PostgreSQL を管理するためのグラフィカルなユーティリティです。dev-db/pgadmin4 として利用可能です。

pgbouncer

PgBouncer はコネクションプールサービスです。dev-db/pgbouncer として利用可能です。

その主な設計目標は、短期間のコネクションのパフォーマンスを改善することです。[1]

トラブルシューティング

旧式化された ebuild

もし次に示す PostgreSQL ebuild のどれかがシステムにインストールされているなら、そのシステムは非常に古い、旧式化された PostgreSQL インストール方式を使っているので、移行すべきです: dev-db/postgresql-libsdev-db/postgresql-clientdev-db/libpq、そして dev-db/postgresql の 9.0 より古いバージョン。

dev-db/postgresql-docsdev-db/postgresql-base、そして dev-db/postgresql-server という名前で分かれていた ebuild 群は、単一の不可分な ebuild dev-db/postgresql に統合されました。個別 ebuild から統合 ebuild への移行は、統合 ebuild を emerge するだけでよく、他に必要なことはありません。

この記事では、古い ebuild から新しい ebuild への移行について説明します

Server lacks instrumentation functions

This problem is easy to solve, with the solution depending on the version you are using. What is difficult about it is finding the answer. What is required is an import from a file that already exists on the storage drive: adminpack.sql . To resolve this issue, run one of the following commands appropriate to the version you have.

For PostgreSQL 9.0 and earlier:

user $psql -U postgres --file /usr/share/postgresql-9.0/contrib/adminpack.sql

For PostgreSQL 9.1 and later:

user $psql -U postgres -c "CREATE EXTENSION adminpack;"

Missing config files in /etc/postgresql-9.x and /var/lib/postgresql/9.x/data

You can try to move the config files into the directory, where x is your postgresql version number, as follows:

root #cp /var/lib/postgresql/9.x/data/*.conf /etc/postgresql-9.x/

If those files are missing you will need to initialize them.

最初にpostgresのユーザにsuします:

root #su postgres

Then, as the postgres user, run initdb and specify the data directory:

user $initdb -D /var/lib/postgresql/9.x/data/

This will generate your configuration files and allow you to copy them over to /etc/postgresql-9.x/ as shown in the first command in this section.

"ERROR: timezone directory stack overflow" または "FATAL: too many private dirs demanded"

これはシンボリックリンクループが原因です。これを修正するには、以下のように入力します:

root #rm /usr/share/zoneinfo/posix

zoneinfo を更新するとこのシンボリックリンクが再作成されるので、再度削除する必要があることに注意してください。

systemd

起動時にサービスを開始させてください:

root #systemctl enable postgresql-9.4

サービスをすぐに開始するには:

root #systemctl start postgresql-9.4

エラーが発生した場合は、/run/postgresql ディレクトリが存在するか確認してください。もし無い場合は、次のように作成してください:

root #systemd-tmpfiles --create

コンフィグファイルのパーミッションを確認してください:

root #ls -l /etc/postgresql-9.*/*
root #chown postgres:postgres /etc/postgresql-9.*/*
root #chmod 600 /etc/postgresql-9.*/*

サービスファイルとそれに対する変更

systemd サービスファイル (postgresql-@SLOT@-.service) は /lib/systemd/system/ 内で見つかります:

設定変更の例:

ファイル /lib/systemd/system/postgresql-@SLOT@.serviceポート変更の設定例
[Service]
Environment=PGPORT=5433

これで /lib/systemd/system/postgresql-@SLOT@.service にある設定は無視されるでしょう。

(情報源: postgresql-10.service file)

RemoveIPC

PostgreSQL は wiki.postgresql.org/wiki/Systemd で、/etc/systemd/logind.conf 内の RemoveIPC の設定を no に変更することを推奨しています:

ファイル /etc/systemd/logind.confRemoveIPC
RemoveIPC=no

(情報源: wiki.postgresql.org/wiki/Systemd)



This page is based on a document formerly found on our main website gentoo.org.
The following people contributed to the original document: Aaron W. Swenson,Mikkel A. Clausen
They are listed here because wiki history does not allow for any external attribution. If you edit the wiki article, please do not add yourself here; your contributions are recorded on each article's associated history page.

References

  1. PgBouncer command-line usage、pgbouncer。2022 年 2 月 11 日取得。