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 60% complete.
Outdated translations are marked like this.
Other languages:


这是一个关于PostgreSQL的快速入门指南。它涵盖了安装和配置PostgreSQL。这是对官方文档的补充,但不能代替它。

简介

PostgreSQL/ 是一个自由和开源的对象-关系型数据库管理系统(RDBMS)。它支持诸如复杂查询、视图和外键等功能,并且经常被认为更严格地遵守SQL标准,在默认情况下比任何其他数据库(商业或其他)更安全。

请访问postgresql.org上的关于页面了解更多信息。

本文将涉及的内容

这篇文章将指导你通过Gentoo的特定步骤来安装PostgreSQL RDBMS。

本文所涉及的ebuild是dev-db/postgresql

本文假设你将安装最新的PostgreSQL稳定版本;在撰写本文时,该版本是9.3.5。根据你的具体版本,对本文中的命令进行必要的调整。

关于 ebuild

Portage中的PostgreSQL ebuilds具有基于主要版本的solt。这允许你有两个主要版本的PostgreSQL同时运行;9.0-9.4库和服务器可以同时安装和提供服务。这在你需要把数据从一个旧的数据库转移到一个新的数据库,或者需要在同一台机器上有一个生产和一个测试数据库的情况下很有用。除此之外,这可以防止数据库、相应的库或可执行文件被不兼容的更新所覆盖。这需要进行迁移,本指南在后文会进行描述。

另外,通过次要版本更新提供的错误和安全修复,可以应用而不必担心破坏数据库或已安装的PostgreSQL;9.3.4可以更新到9.3.5,因为它们被保证是兼容的,并且除了安装它和重新启动服务器外,不需要你更多的操作。迁移、重新配置和初始化都是不必要的。

阅读 PostgreSQL版本政策 以了解更多信息。

本文不会涉及的内容

本指南将不涵盖相当多的内容。官方文档大约有2000多页。因此,在这个快速入门指南中,很多细节将被遗漏。将只包括Gentoo的特有问题和一些基本的配置指南。

安装

USE 标记

USE flags for dev-db/postgresql PostgreSQL RDBMS

+icu Enable ICU (Internationalization Components for Unicode) support, using dev-libs/icu
+lz4 Enable support for lz4 compression (as implemented in app-arch/lz4)
+readline Enable support for libreadline, a GNU line-editing library that almost everyone wants
+server Disable to build and install the clients and libraries only.
+zstd Enable support for ZSTD compression
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
kerberos Add kerberos support
ldap Add LDAP support (Lightweight Directory Access Protocol)
llvm Add support for llvm JIT engine
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
selinux !!internal use only!! Security Enhanced Linux support, this must be set by the selinux profile or breakage will occur
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
test Enable dependencies and/or preparations necessary to run tests (usually controlled by FEATURES=test but can be toggled independently)
uuid Enable server side UUID generation (via dev-libs/ossp-uuid).
xml Add support for XML files
zlib Add support for zlib compression

有关USE标志的信息。

  • doc: 包括在线文档,并存储在你的系统中。
  • pg_legacytimestamp。使用老式的浮点方法来格式化时间戳,而不是分辨率更高的64位整数方法。除非你以前的安装使用了这种过时的方法,否则请将这个USE标志关闭。如果你的数据库使用了时间戳,更改'pg_legacytimestamp'将需要你做一个转储和恢复。这两种方法是互不兼容的。
  • 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-libs, dev-db/postgresql-client, 或 dev-db/libpq 。这些包都是不维护并被淘汰的且已从Gentoo仓库中删除。请参考如何从旧版本的ebuild迁移到新版本的ebuild的章节,了解如何处理这种情况。

准备初始化数据库集群

一旦软件包完成,你可能想编辑/etc/conf.d/postgresql-9.3。其中有三行影响到服务器的默认值,如果不删除包含数据库集群的目录并重新初始化,以后就不能更改。

PGDATA定义了放置配置文件的位置。DATA_DIR定义了创建数据库集群和相关文件的位置。PG_INITDB_OPTS可以包含任何你想设置的额外选项。额外的选项是需要的,因为合理的默认值是,嗯,合理的。

在下面的例子中,PGDATA被设置为配置文件将位于/etc/postgresql-9.3/。. DATA_DIR被设置为数据库集群应安装在/var/lib/postgresql/9.3/data/,这是默认的。这是默认的。如果你决定更改默认位置,请记住,在路径中保留主要版本是一个非常好的主意PG_INITDB_OPTS指出默认的locale应该是en_US.UTF-8 。意味着美式英语排序和格式化,以及UTF-8字符编码。

文件 /etc/conf.d/postgresql-9.3Example content
# Location of configuration files
PGDATA="/etc/postgresql-9.3/"
# Where the data directory is located/to be created
DATA_DIR="/var/lib/postgresql/9.3/data"
# Additional options to pass to initdb.
# See 'man initdb' for available options.
PG_INITDB_OPTS="--locale=en_US.UTF-8"
附注
这只决定了默认的语言环境和字符编码。您可以在创建数据库时(CREATE DATABASE)在同一数据库集群中指定不同的语言和/或字符编码。

有六个语言环境选项可以设置并覆盖--locale =。 下表列出了这六个选项,如果使用,格式为:--option=lo_LO.ENCODING

选项 用途
lc-collate 字符串排列顺序
lc-ctype 字符串格式 (What is a letter? Its upper-case equivalent?)
lc-messages 消息的语言
lc-monetary 货币金额的格式
lc-numeric 数字格式
lc-time 日期和时间格式

因此,如果你希望默认为英语,但你希望信息是瑞典语,那么你的PG_INITDB_OPTS将看起来像这样:

代码 Setting PG_INITDB_OPTS
PG_INITDB_OPTS="--locale=en_US.UTF-8 --lc-messages=sv_SE.UTF-8"

可以在文档中找到服务器支持的完整语言和字符编码列表,但您的系统也支持各种语言和字符编码。 将 locale -a 的输出与文档中的[1]进行比较。

你可以在数据库[2]创建时改变你的地域和编码选择。为了在你创建数据库后改变它的地区设置,你必须放弃该数据库并重新开始。

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

这将根据配置文件中的PGDATADATA_DIR创建数据库集群并将所有相关的服务器文件存储

配置

配置文件的位置

配置文件样本可以在/usr/share/postgresql-9.3中找到。(或任何版本),见脚本的故障排除部分。

这次的重点从 "PGDATA "目录下的文件移开,/etc/postgresql-9.3。而主要关注postgresql.confpg_hba.conf文件。

postgresql.conf

这是主配置文件。你可能会发现直接感兴趣的一行是listen_addresses 。这个变量定义了PostgreSQL将与哪些地址绑定。默认情况下,只有localhost和Unix套接字被绑定。改变listen_addresses还不足以启用远程连接。这将在下一节中讲述。官方文档是相当容易理解的,而且对所有可用的设置都很详尽。除了这里的内容外,你最好还能阅读一下,因为有些东西可能会改变。

另一个是日志记录的目的地。默认情况下,所有日志都被记录到postmaster.log的 "DATA_DIR "目录下。在postgresql.conf中,有一整个小节涵盖了一系列关于如何记录、记录什么和在哪里记录的选项。该小节被标记为错误报告和日志记录。

除了listen_addresses和日志选项外,postgresql.conf中的其他默认值都足够合理,可以正常工作。

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

正如之前提到的,默认情况下,服务器是安全的。算是吧。默认情况下,只有一个数据库角色可供登录:"postgres"。而且,启动与数据库的连接的唯一方法是通过/run/postgresql/.s.PGSQL.5432Unix套接字,该套接字由postgres系统用户和系统组拥有,或者通过localhost访问。现在说说 "有点隐患"的地方。系统中的任何用户都可以通过localhost与数据库建立连接。甚至可以作为postgres数据库的超级用户。

警告
不要完全禁用Unix套接字。initscripts需要访问它以便正常运行。该方法可以改变。

信任模式是允许任何用户在没有密码的情况下以任何用户身份登录。它暗示:信任所有来自给定数据库用户(但不是系统用户)的给定类型的数据库连接,不需要密码。这就是允许系统中的任何用户从一开始就以任何用户的身份通过localhost连接登录的原因。这并不像它看起来那么危险,但在大多数情况下确实构成了严重的安全风险。

你最可能使用的两种方法是。密码md5。密码方法只规定在开始连接时需要密码,而且密码是 "透明 "的发送。当信息永远不会离开机器时,比如通过Unix套接字或localhost连接,这种方法就很好。md5方法与密码类似,但使用md5哈希值来保护密码。当密码要通过网络时,你应该使用这种方法。

在这一点上,本作者想提醒你注意pg_hba.conf文件的最后两行,包括注释在内的四行。无论你希望得到什么支持,PostgreSQL都有对IPv6的本地支持。此外,IPv4地址会自动映射到IPv6地址,。127.0.0.1将被映射为::FFF:127.0.0.1作为 "纯"IPv6::FFF: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.

所以,最好单独向psqlpg_hba.conf中指定IP地址,而不是依靠/etc/hosts正确排序,它将消除你对允许哪些IP地址或将连接到哪个服务器的疑问。

启动服务器

开始吧!

现在启动PostgreSQL并为数据库超级用户postgres设置密码。

将 "主机"(不是 "本地",Unix域套接字)连接的 "信任 "改为 "密码"。

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

现在启动数据库

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

将本地连接的 "信任 "改为 "密码":

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 ]

最后,一旦一切工作正常,让PostgreSQL在系统启动时启动:

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

在这一点上,你已经准备好继续学习官方的PostgreSQL教程。该教程将指导你创建用户、数据库、模式和所有这些有趣和有用的东西。

迁移PostgreSQL

什么时候你需要迁移

只有两个原因使你需要进行迁移:当从一个主要版本迁移到另一个主要版本时,比如从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.

Check available versions, then select yours:

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

And now you're done:

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

Edit PGPORT back to 5432.

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

Allow users access once more.

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

You will need to schedule some downtime for your server. The old ebuilds cannot be installed at the same time as the new ebuilds. As such, assume that the server will have to be down for a few hours. Maybe for the weekend, even.

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.

Utilities

pgAdmin

pgAdmin is a graphical utility for managing PostgreSQL. It is available as dev-db/pgadmin4.

pgbouncer

PgBouncer is a connection pooling service. It is available as dev-db/pgbouncer.

Its main design goal is improving performance of short-lived connections.[1]

Troubleshooting

陈旧的 ebuild

如果您安装了以下任何一个ebuilds,那么您的Gentoo PostgreSQL安装已经过时了,现在应该迁移。

dev-db/postgresql-libs, dev-db/postgresql-client, dev-db/libpq, 和dev-db/postgresql9.0以上的版本。

分离的ebuilds dev-db/postgresql-docs, dev-db/postgresql-base, 和/或dev-db/postgresql-server已经统一为一个软件包:dev-db/postgresql。除了安装统一的ebuild版本之外,你不需要从分裂的ebuild版本转移到统一的ebuild版本

这篇文章涵盖了如何从旧的ebuilds迁移到新的ebuilds。

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.

First su into the postgres user:

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" or "FATAL: too many private dirs demanded"

This is caused by a symlink loop. To fix it, type the following:

root #rm /usr/share/zoneinfo/posix

Keep in mind that any update to zoneinfo will recreate this symlink, thus requiring you to remove it again.

systemd

Force the service to start on bootup:

root #systemctl enable postgresql-9.4

To start service immediately:

root #systemctl start postgresql-9.4

If an error occurs check if the /run/postgresql/ directory is there. If not, then create it like so:

root #systemd-tmpfiles --create

Check the config file permissions:

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

Service file and changes to it

Systemd service files (postgresql-@SLOT@-.service) can be found in /lib/systemd/system/:

example config change:

文件 /lib/systemd/system/postgresql-@SLOT@.serviceExample config port change
[Service]
Environment=PGPORT=5433

这将覆盖/lib/systemd/system/postgresql-@SLOT@.service的设置。

(source: postgresql-10.service file)

RemoveIPC

PostgreSQL recommends in wiki.postgresql.org/wiki/Systemd to change the RemoveIPC setting to no in /etc/systemd/logind.conf:

文件 /etc/systemd/logind.confRemoveIPC
RemoveIPC=no

(source: 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. Retrieved on February 11, 2022