PostgreSQL 行安全策略

行安全策略除可以通过GRANT使用 SQL 标准的 特权系统之外,表还可以具有 行安全性策略,它针对每一个用户限制哪些行可以 被普通的查询返回或者可以被数据修改命令插入、更新或删除。这种 特性也被称为行级安全性。默认情况下,表不具有 任何策略,这样用户根据 SQL 特权系统具有对表的访问特权,对于 查询或更新来说其中所有的行都是平等的。

当在一个表上启用行安全性时(使用 ALTER TABLE … ENABLE ROW LEVEL SECURITY),所有对该表选择行或者修改行的普通访问都必须被一条 行安全性策略所允许(不过,表的拥有者通常不服从行安全性策略)。如果 表上不存在策略,将使用一条默认的否定策略,即所有的行都不可见或者不能 被修改。应用在整个表上的操作不服从行安全性,例如TRUNCATE和 REFERENCES。

行安全性策略可以针对特定的命令、角色或者两者。一条策略可以被指定为 适用于ALL命令,或者SELECT、 INSERT、UPDATE或者DELETE。 可以为一条给定策略分配多个角色,并且通常的角色成员关系和继承规则也适用。

要指定哪些行根据一条策略是可见的或者是可修改的,需要一个返回布尔结果 的表达式。对于每一行,在计算任何来自用户查询的条件或函数之前,先会计 算这个表达式(这条规则的唯一例外是leakproof函数, 它们被保证不会泄露信息,优化器可能会选择在行安全性检查之前应用这类 函数)。使该表达式不返回true的行将不会被处理。可以指定独立的表达式来单独控制哪些行可见以及哪些行被允许修改。策略表达式会作为查询的一部分运行并且带有运行该查询的用户的特权,但是安全性定义者函数可以被用来访问对调用用户不可用的数据。

具有BYPASSRLS属性的超级用户和角色在访问一个表时总是 可以绕过行安全性系统。表拥有者通常也能绕过行安全性,不过表拥有者 可以选择用ALTER TABLE … FORCE ROW LEVEL SECURITY来服从行安全性。

用和禁用行安全性以及向表增加策略是只有表拥有者具有的特权。

策略的创建可以使用CREATE POLICY命令,策略的修改 可以使用ALTER POLICY命令,而策略的删除可以使用 DROP POLICY命令。要为一个给定表启用或者禁用行 安全性,可以使用ALTER TABLE命令。

每一条策略都有名称并且可以为一个表定义多条策略。由于策略是表相 关的,一个表的每一条策略都必须有一个唯一的名称。不同的表可以拥有 相同名称的策略。

当多条策略适用于一个给定查询时,它们会被用OR 组合起来,这样只要任一策略允许,行就是可访问的。这类似于一个给定 角色具有它所属的所有角色的特权的规则。

作为一个简单的例子,这里是如何在account关系上 创建一条策略以允许只有managers角色的成员能访问行, 并且只能访问它们账户的行:
CREATE TABLE accounts (manager text, company text, contact_email text);

ALTER TABLE accounts ENABLE ROW LEVEL SECURITY;

CREATE POLICY account_managers ON accounts TO managers USING (manager = current_user);

上述政策隐式地提供了一个with check子句来标识它的using子句,因此这个约束应用于通过命令来选所择的行(因此一个管理者不能select,update或delete现有属于不同管理都的行)和通过命令来修改的行(因此属于不同管理者的行不能通过insert或update来创建)。

如果没有指定角色或者指定的用户名为public,那么这个熏将应用给系统中的所有用户。 为了允许所有用户只访问在一个user表中的行记录,可以使用如下一个简单和策略:
CREATE POLICY user_policy ON users USING (user_name = current_user);

这与前面的示例类似

要对添加到表中的行与可见行使用不同的策略,可以组合多个策略。这对策略将允许所有的用户来查看users表中的所有行,但只能修改属于他们自己的行记录:
CREATE POLICY user_sel_policy ON users FOR SELECT USING (true);

CREATE POLICY user_mod_policy ON users USING (user_name = current_user);

在SELECT命令中,使用OR组合来使用这两个策略,最终的效果是可以选择所有行。在其他命令类型中,只应用第二个策略,因此效果与前面相同。

行安全策略也可以使用alter table命令来禁用。禁用行安全策略不会删除在表上所定义的任何策略,它们只是被忽略。然后表中的所有行都可见并且能被修改,服从于标准的SQL特权系统。

下面是一个较大的例子,它展示了这种特性如何被用于生产环境。表 passwd模拟了一个 Unix 口令文件:
— 简单的口令文件例子

jydb=# CREATE TABLE passwd (
jydb(# user_name text UNIQUE NOT NULL,
jydb(# pwhash text,
jydb(# uid int PRIMARY KEY,
jydb(# gid int NOT NULL,
jydb(# real_name text NOT NULL,
jydb(# home_phone text,
jydb(# extra_info text,
jydb(# home_dir text NOT NULL,
jydb(# shell text NOT NULL
jydb(# );
CREATE TABLE

–创建用户:

jydb=# CREATE ROLE admin;
CREATE ROLE
jydb=# CREATE ROLE bob;
CREATE ROLE
jydb=# CREATE ROLE alice;
CREATE ROLE

— 向表中插入数据

jydb=# INSERT INTO passwd VALUES('admin','xxx',0,0,'Admin','111-222-3333',null,'/root','/bin/dash');
INSERT 0 1
jydb=# INSERT INTO passwd VALUES('bob','xxx',1,1,'Bob','123-456-7890',null,'/home/bob','/bin/zsh');
INSERT 0 1
jydb=# INSERT INTO passwd VALUES('alice','xxx',2,1,'Alice','098-765-4321',null,'/home/alice','/bin/zsh');
INSERT 0 1

–确保在表上启用行级安全性

jydb=# ALTER TABLE passwd ENABLE ROW LEVEL SECURITY;
ALTER TABLE

创建策略
— 管理员能看见所有行并且增加任意行

jydb=# CREATE POLICY admin_all ON passwd TO admin USING (true) WITH CHECK (true);
CREATE POLICY

–普通用户可以看见所有行

jydb=# CREATE POLICY all_view ON passwd FOR SELECT USING (true);
CREATE POLICY

–普通用户可以更新它们自己的记录,但是限制普通用户可用的 shell

jydb=# CREATE POLICY user_mod ON passwd FOR UPDATE
jydb-#   USING (current_user = user_name)
jydb-#   WITH CHECK (
jydb(#     current_user = user_name AND
jydb(#     shell IN ('/bin/bash','/bin/sh','/bin/dash','/bin/zsh','/bin/tcsh')
jydb(#   );
CREATE POLICY

–允许admin有所有普通权限

jydb=# GRANT SELECT, INSERT, UPDATE, DELETE ON passwd TO admin;
GRANT

–普通用户只在公共列上得到选择访问权限

jydb=# GRANT SELECT
jydb-# (user_name, uid, gid, real_name, home_phone, extra_info, home_dir, shell)
jydb-# ON passwd TO public;
GRANT

— 允许普通用户更新特定行

jydb=# GRANT UPDATE
jydb-# (pwhash, real_name, home_phone, extra_info, shell)
jydb-# ON passwd TO public;
GRANT

对于任意安全性设置来说,重要的是测试并确保系统的行为符合预期。 使用上述的例子,下面展示了权限系统工作正确:

–admin 可以看到所有的行和字段

jydb=# set role admin;
SET
jydb=> table passwd;
 user_name | pwhash | uid | gid | real_name |  home_phone  | extra_info |  home_dir   |   shell   
-----------+--------+-----+-----+-----------+--------------+------------+-------------+-----------
 admin     | xxx    |   0 |   0 | Admin     | 111-222-3333 |            | /root       | /bin/dash
 bob       | xxx    |   1 |   1 | Bob       | 123-456-7890 |            | /home/bob   | /bin/zsh
 alice     | xxx    |   2 |   1 | Alice     | 098-765-4321 |            | /home/alice | /bin/zsh
(3 rows)

jydb=> select * from passwd;
 user_name | pwhash | uid | gid | real_name |  home_phone  | extra_info |  home_dir   |   shell   
-----------+--------+-----+-----+-----------+--------------+------------+-------------+-----------
 admin     | xxx    |   0 |   0 | Admin     | 111-222-3333 |            | /root       | /bin/dash
 bob       | xxx    |   1 |   1 | Bob       | 123-456-7890 |            | /home/bob   | /bin/zsh
 alice     | xxx    |   2 |   1 | Alice     | 098-765-4321 |            | /home/alice | /bin/zsh
(3 rows)

— 测试 Alice 能做什么

jydb=> set role alice;
SET
jydb=>  table passwd;
ERROR:  permission denied for relation passwd
jydb=> select * from passwd;
ERROR:  permission denied for relation passwd
jydb=> select user_name,real_name,home_phone,extra_info,home_dir,shell from passwd;
 user_name | real_name |  home_phone  | extra_info |  home_dir   |   shell   
-----------+-----------+--------------+------------+-------------+-----------
 admin     | Admin     | 111-222-3333 |            | /root       | /bin/dash
 bob       | Bob       | 123-456-7890 |            | /home/bob   | /bin/zsh
 alice     | Alice     | 098-765-4321 |            | /home/alice | /bin/zsh
(3 rows)


jydb=> update passwd set user_name = 'joe';
ERROR:  permission denied for relation passwd

–Alice 被允许更改她自己的 real_name,但不能改其他的

jydb=> update passwd set real_name = 'Alice Doe';
UPDATE 1
jydb=> update passwd set real_name = 'John Doe' where user_name = 'admin';
UPDATE 0
jydb=> update passwd set shell = '/bin/xx';
ERROR:  new row violates row-level security policy for table "passwd"
jydb=> delete from passwd;
ERROR:  permission denied for relation passwd
jydb=> insert into passwd (user_name) values ('xxx');
ERROR:  permission denied for relation passwd

— Alice 可以更改她自己的口令;行级安全性会悄悄地阻止更新其他行

jydb=> update passwd set pwhash = 'abc';
UPDATE 1

引用完整性检查(例如唯一或主键约束和外键引用)总是会绕过行级安全策略以保证数据完整性得到维护。在开发模式和行级安全策略时必须小心避免 “隐蔽通道”通过这类引用完整性检查泄露信息。

在某些环境中确保不应用行级安全策略是很重要的。例如,当执行备份时,如果行级安全策略默默地造成备份操作忽略了一些行数据这将是灾难性的。在这种情部钙,你可以将row_security配置参数设置为off。这本身不会绕过行级安全策略,如果任何查询结果因为行级安全策略而被过滤掉记录时就是抛出一个错误,然后就可以找到错误原因并修复它。

在上面的例子中,策略表达式只考虑了要被访问或被更新行中的当前值。这是最简单并且表现最好的情况。如果可能,最好设计行级安全策略应用来以这种方式工作。 如果需要参考其他行或者其他表来做出策略的决定,可以在策略表达式中通过使用子-SELECTs或者包含SELECT的函数来实现。不过要注意这类访问可能会导致竞争条件,在不小心的情况下这可能会导致信息泄露。作为一个例子,考虑下面的表设计:
–定义权限组

jydb=> CREATE TABLE groups (group_id int PRIMARY KEY,group_name text NOT NULL);
CREATE TABLE
jydb=> INSERT INTO groups VALUES
jydb->   (1, 'low'),
jydb->   (2, 'medium'),
jydb->   (5, 'high');
INSERT 0 3
jydb=> GRANT ALL ON groups TO alice;
GRANT
jydb=> GRANT SELECT ON groups TO public;
GRANT
jydb=> select * from groups;
 group_id | group_name 
----------+------------
        1 | low
        2 | medium
        5 | high
(3 rows)

–定义用户的权限级别

jydb=# CREATE TABLE users (user_name text PRIMARY KEY,
jydb(#                     group_id int NOT NULL REFERENCES groups);
CREATE TABLE
jydb=# INSERT INTO users VALUES
jydb-#   ('alice', 5),
jydb-#   ('bob', 2),
jydb-#   ('mallory', 2);
INSERT 0 3
jydb=# GRANT ALL ON users TO alice;
GRANT
jydb=# GRANT SELECT ON users TO public;
GRANT

jydb=# CREATE ROLE mallory;
CREATE ROLE

jydb=# select * from users;
 user_name | group_id 
-----------+----------
 alice     |        5
 bob       |        2
 mallory   |        2
(3 rows)

–保存的信息的表将被保护

jydb=# CREATE TABLE information (info text,
jydb(#                           group_id int NOT NULL REFERENCES groups);
CREATE TABLE
jydb=# INSERT INTO information VALUES
jydb-#   ('barely secret', 1),
jydb-#   ('slightly secret', 2),
jydb-#   ('very secret', 5);
INSERT 0 3
jydb=# ALTER TABLE information ENABLE ROW LEVEL SECURITY;
ALTER TABLE

–对于用户的安全策略group_id大于等于行的group_id的,这行记录应该是可见的或可被更新的

jydb=# CREATE POLICY fp_s ON information FOR SELECT
jydb-#   USING (group_id < = (SELECT group_id FROM users WHERE user_name = current_user));
CREATE POLICY
jydb=# CREATE POLICY fp_u ON information FOR UPDATE
jydb-#   USING (group_id <= (SELECT group_id FROM users WHERE user_name = current_user));
CREATE POLICY

--我们只依赖于行级安全性来保护信息表

jydb=# GRANT ALL ON information TO public;
GRANT

现在假设alice希望更改information表中的”slightly secret”的信息,但是觉得用户mallory不应该看到该行中的新内容,因此她这样做:

jydb=# BEGIN;
BEGIN
jydb=# UPDATE users SET group_id = 1 WHERE user_name = 'mallory';
UPDATE 1
jydb=# UPDATE information SET info = 'secret from mallory' WHERE group_id = 2;
UPDATE 1
jydb=# COMMIT;
COMMIT

jydb=> select * from users;
 user_name | group_id 
-----------+----------
 alice     |        5
 bob       |        2
 mallory   |        1
(3 rows)

jydb=> select * from information;
        info         | group_id 
---------------------+----------
 barely secret       |        1
 very secret         |        5
 secret from mallory |        2
(3 rows)

–检查用户mallory是否可以查看information表中的group_id=2的记录

jydb=> set role mallory ;
SET
jydb=> SELECT * FROM information WHERE group_id = 2;
 info | group_id 
------+----------
(0 rows)


jydb=> SELECT * FROM information;
     info      | group_id 
---------------+----------
 barely secret |        1
(1 row)

可以看到现有用户mallory因为users表中的group_id被修改为1了,所以不能查看表information中的group_id为2的记录了。

这看起来是安全的,没有窗口可供用户mallory看到”secret from mallory”字符串。不过,这里有一种竞争条件。如果mallory正在并行地做:
SELECT * FROM information WHERE group_id = 2 FOR UPDATE;

并且她的事务处于READ COMMITTED模式,她就可能看到”secret from mallory”字符串。如果她的事务在alice做完之后就到达information表的行记录,这就会发生。它会阻塞等待alice的事务提交,然后拜FOR UPDATE子句所赐取得更新后的行内容。不过,对于来自users的隐式SELECT,它不会取得一个已更新的行, 因为子-SELECT没有FOR UPDATE,相反会使用查询开始时取得的快照读取users行。因此策略表达式会测试mallory的权限级别的旧值并且允许她看到被更新的行。

有多种方法能解决这个问题。一种简单的答案是在行安全性策略中的 子-SELECT里使用SELECT … FOR SHARE。 不过,这要求在被引用表(这里是users)上授予 UPDATE特权给受影响的用户,这可能不是我们想要的(但是另一条行安全性策略可能被应用来阻止它们实际使用这个特权,或者子-SELECT可能被嵌入到一个安全性定义者函数中)。 还有,在被引用的表上过多并发地使用行共享锁可能会导致性能问题, 特别是表更新比较频繁时。另一种解决方案(如果被引用表上的更新 不频繁就可行)是在更新被引用表时对它取一个排他锁,这样就没有 并发事务能够检查旧的行值了。或者我们可以在提交对被引用表的更新 之后、在做依赖于新安全性情况的更改之前等待所有并发事务结束。

在Oracle Linux 7.1中使用源码来安装PostgreSQL 9.6

在Oracle Linux 7.1中使用源码来安装PostgreSQL 9.6
编译PostgreSQL需要下列软件包:
1.GUN make版本3.80或新的要求。

[root@cs1 /]# make --version
GNU Make 3.82
Built for x86_64-redhat-linux-gnu
Copyright (C) 2010  Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later 
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

2.需要一个ISO/ANSI C 编译器(至少是 C89兼容的)。我们推荐使用最近版本的GCC

[root@cs1 /]# gcc --version
gcc (GCC) 4.8.3 20140911 (Red Hat 4.8.3-9)
Copyright (C) 2013 Free Software Foundation, Inc.
本程序是自由软件;请参看源代码的版权声明。本软件没有任何担保;
包括没有适销性和某一专用目的下的适用性担保。

3.除了gzip和bzip2之外,我们还需要tar来解包源代码发布。

4.GNU Readline库

[root@cs1 /]# rpm -aq | grep readline
readline-6.2-9.el7.x86_64
[root@cs1 /]# rpm -aq | grep readline-deve
readline-devel-6.2-9.el7.x86_64
[root@cs1 /]# rpm -aq | grep libedit
libedit-3.0-12.20121213cvs.el7.x86_64

5.可选工具包在默认配置的时候并不要求它们,但是如果打开了一些编译选项之后就需要它们了

perl 5.8 or later
python
Kerberos
OpenSSL
OpenLDAP and/or PAM
Flex 2.5.31 or later
Bison 1.875 or later

6.创建用户与组

[root@cs1 local]# groupadd pgsql
[root@cs1 local]# useradd -g pgsql pgsql

7.下载源码包postgresql-9.6.6.tar.gz并上传到服务器并解压

[root@cs1 local]# gunzip  mariadb-10.0.38-linux-glibc_214-x86_64

创建一个软链接

[root@cs1 local]# ln -s postgresql-9.6.6 pgsql
[root@cs1 local]# ls -lrt
总用量 8
drwxr-xr-x.  2 root  root     6 5月   8 2014 src
drwxr-xr-x.  2 root  root     6 5月   8 2014 sbin
drwxr-xr-x.  2 root  root     6 5月   8 2014 libexec
drwxr-xr-x.  2 root  root     6 5月   8 2014 lib64
drwxr-xr-x.  2 root  root     6 5月   8 2014 lib
drwxr-xr-x.  2 root  root     6 5月   8 2014 include
drwxr-xr-x.  2 root  root     6 5月   8 2014 games
drwxr-xr-x.  2 root  root     6 5月   8 2014 etc
drwxr-xr-x.  5 root  root    46 10月 12 2017 share
drwxrwxrwx   6 pgsql pgsql 4096 11月  7 2017 postgresql-9.6.6
drwxr-xr-x.  2 root  root    46 3月   9 2018 bin
drwxrwxr-x  13 root  mysql 4096 1月  31 02:40 mariadb-10.0.38-linux-glibc_214-x86_64
lrwxrwxrwx   1 root  root    38 6月   4 14:43 mysql -> mariadb-10.0.38-linux-glibc_214-x86_64
lrwxrwxrwx   1 root  root    16 6月   4 21:24 pgsql -> postgresql-9.6.6

8.安装

root@cs1 local]# cd pgsql

8.1安装过程的第一步就是为你的系统配置源代码树并选择你喜欢的选项。这个工作是通过运行configure脚本实现的,对于默认安装,你只需要简单地输入:

[root@cs1 pgsql]# ./configure
checking build system type... x86_64-pc-linux-gnu
checking host system type... x86_64-pc-linux-gnu
checking which template to use... linux
checking whether to build with 64-bit integer date/time support... yes
checking whether NLS is wanted... no
checking for default port number... 5432
checking for block size... 8kB
checking for segment size... 1GB
checking for WAL block size... 8kB
checking for WAL segment size... 16MB
checking for gcc... gcc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables... 
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
checking whether gcc accepts -g... yes
checking for gcc option to accept ISO C89... none needed
checking whether gcc supports -Wdeclaration-after-statement... yes
checking whether gcc supports -Wendif-labels... yes
checking whether gcc supports -Wmissing-format-attribute... yes
checking whether gcc supports -Wformat-security... yes
checking whether gcc supports -fno-strict-aliasing... yes
checking whether gcc supports -fwrapv... yes
checking whether gcc supports -fexcess-precision=standard... yes
checking whether gcc supports -funroll-loops... yes
checking whether gcc supports -ftree-vectorize... yes
checking whether gcc supports -Wunused-command-line-argument... no
checking whether the C compiler still works... yes
checking how to run the C preprocessor... gcc -E
checking allow thread-safe client libraries... yes
checking whether to build with Tcl... no
checking whether to build Perl modules... no
checking whether to build Python modules... no
checking whether to build with GSSAPI support... no
checking whether to build with PAM support... no
checking whether to build with BSD Authentication support... no
checking whether to build with LDAP support... no
checking whether to build with Bonjour support... no
checking whether to build with OpenSSL support... no
checking whether to build with SELinux support... no
checking whether to build with systemd support... no
checking for grep that handles long lines and -e... /usr/bin/grep
checking for egrep... /usr/bin/grep -E
checking for ld used by GCC... /usr/bin/ld
checking if the linker (/usr/bin/ld) is GNU ld... yes
checking for ranlib... ranlib
checking for strip... strip
checking whether it is possible to strip libraries... yes
checking for ar... ar
checking for a BSD-compatible install... /usr/bin/install -c
checking for tar... /usr/bin/tar
checking whether ln -s works... yes
checking for gawk... gawk
checking for a thread-safe mkdir -p... /usr/bin/mkdir -p
checking for bison... /usr/bin/bison
configure: using bison (GNU Bison) 2.7
checking for flex... /usr/bin/flex
configure: using flex 2.5.37
checking for perl... /usr/bin/perl
configure: using perl 5.16.3
checking for ANSI C header files... yes
checking for sys/types.h... yes
checking for sys/stat.h... yes
checking for stdlib.h... yes
checking for string.h... yes
checking for memory.h... yes
checking for strings.h... yes
checking for inttypes.h... yes
checking for stdint.h... yes
checking for unistd.h... yes
checking if compiler needs certain flags to reject unknown flags... no
checking for the pthreads library -lpthreads... no
checking whether pthreads work without any flags... no
checking whether pthreads work with -Kthread... no
checking whether pthreads work with -kthread... no
checking for the pthreads library -llthread... no
checking whether pthreads work with -pthread... yes
checking for joinable pthread attribute... PTHREAD_CREATE_JOINABLE
checking if more special flags are required for pthreads... no
checking for PTHREAD_PRIO_INHERIT... yes
checking pthread.h usability... yes
checking pthread.h presence... yes
checking for pthread.h... yes
checking for strerror_r... yes
checking for getpwuid_r... yes
checking for gethostbyname_r... yes
checking whether strerror_r returns int... no
checking for main in -lm... yes
checking for library containing setproctitle... no
checking for library containing dlopen... -ldl
checking for library containing socket... none required
checking for library containing shl_load... no
checking for library containing getopt_long... none required
checking for library containing crypt... -lcrypt
checking for library containing shm_open... -lrt
checking for library containing shm_unlink... none required
checking for library containing fdatasync... none required
checking for library containing sched_yield... none required
checking for library containing gethostbyname_r... none required
checking for library containing shmget... none required
checking for library containing readline... -lreadline
checking for inflate in -lz... yes
checking atomic.h usability... no
checking atomic.h presence... no
checking for atomic.h... no
checking crypt.h usability... yes
checking crypt.h presence... yes
checking for crypt.h... yes
checking dld.h usability... no
checking dld.h presence... no
checking for dld.h... no
checking fp_class.h usability... no
checking fp_class.h presence... no
checking for fp_class.h... no
checking getopt.h usability... yes
checking getopt.h presence... yes
checking for getopt.h... yes
checking ieeefp.h usability... no
checking ieeefp.h presence... no
checking for ieeefp.h... no
checking ifaddrs.h usability... yes
checking ifaddrs.h presence... yes
checking for ifaddrs.h... yes
checking langinfo.h usability... yes
checking langinfo.h presence... yes
checking for langinfo.h... yes
checking mbarrier.h usability... no
checking mbarrier.h presence... no
checking for mbarrier.h... no
checking poll.h usability... yes
checking poll.h presence... yes
checking for poll.h... yes
checking pwd.h usability... yes
checking pwd.h presence... yes
checking for pwd.h... yes
checking sys/epoll.h usability... yes
checking sys/epoll.h presence... yes
checking for sys/epoll.h... yes
checking sys/ioctl.h usability... yes
checking sys/ioctl.h presence... yes
checking for sys/ioctl.h... yes
checking sys/ipc.h usability... yes
checking sys/ipc.h presence... yes
checking for sys/ipc.h... yes
checking sys/poll.h usability... yes
checking sys/poll.h presence... yes
checking for sys/poll.h... yes
checking sys/pstat.h usability... no
checking sys/pstat.h presence... no
checking for sys/pstat.h... no
checking sys/resource.h usability... yes
checking sys/resource.h presence... yes
checking for sys/resource.h... yes
checking sys/select.h usability... yes
checking sys/select.h presence... yes
checking for sys/select.h... yes
checking sys/sem.h usability... yes
checking sys/sem.h presence... yes
checking for sys/sem.h... yes
checking sys/shm.h usability... yes
checking sys/shm.h presence... yes
checking for sys/shm.h... yes
checking sys/socket.h usability... yes
checking sys/socket.h presence... yes
checking for sys/socket.h... yes
checking sys/sockio.h usability... no
checking sys/sockio.h presence... no
checking for sys/sockio.h... no
checking sys/tas.h usability... no
checking sys/tas.h presence... no
checking for sys/tas.h... no
checking sys/time.h usability... yes
checking sys/time.h presence... yes
checking for sys/time.h... yes
checking sys/un.h usability... yes
checking sys/un.h presence... yes
checking for sys/un.h... yes
checking termios.h usability... yes
checking termios.h presence... yes
checking for termios.h... yes
checking ucred.h usability... no
checking ucred.h presence... no
checking for ucred.h... no
checking utime.h usability... yes
checking utime.h presence... yes
checking for utime.h... yes
checking wchar.h usability... yes
checking wchar.h presence... yes
checking for wchar.h... yes
checking wctype.h usability... yes
checking wctype.h presence... yes
checking for wctype.h... yes
checking for net/if.h... yes
checking for sys/ucred.h... no
checking netinet/in.h usability... yes
checking netinet/in.h presence... yes
checking for netinet/in.h... yes
checking for netinet/tcp.h... yes
checking readline/readline.h usability... yes
checking readline/readline.h presence... yes
checking for readline/readline.h... yes
checking readline/history.h usability... yes
checking readline/history.h presence... yes
checking for readline/history.h... yes
checking zlib.h usability... yes
checking zlib.h presence... yes
checking for zlib.h... yes
checking whether byte ordering is bigendian... no
checking for inline... inline
checking for printf format archetype... gnu_printf
checking for flexible array members... yes
checking for signed types... yes
checking for __func__... yes
checking for _Static_assert... yes
checking for __builtin_types_compatible_p... yes
checking for __builtin_bswap32... yes
checking for __builtin_bswap64... yes
checking for __builtin_constant_p... yes
checking for __builtin_unreachable... yes
checking for __VA_ARGS__... yes
checking whether struct tm is in sys/time.h or time.h... time.h
checking for struct tm.tm_zone... yes
checking for tzname... yes
checking for union semun... no
checking for struct sockaddr_un... yes
checking for struct sockaddr_storage... yes
checking for struct sockaddr_storage.ss_family... yes
checking for struct sockaddr_storage.__ss_family... no
checking for struct sockaddr_storage.ss_len... no
checking for struct sockaddr_storage.__ss_len... no
checking for struct sockaddr.sa_len... no
checking for struct addrinfo... yes
checking for intptr_t... yes
checking for uintptr_t... yes
checking for unsigned long long int... yes
checking for long long int... yes
checking for locale_t... yes
checking for struct cmsgcred... no
checking for struct option... yes
checking for z_streamp... yes
checking for special C compiler options needed for large files... no
checking for _FILE_OFFSET_BITS value needed for large files... no
checking size of off_t... 8
checking for int timezone... yes
checking types of arguments for accept()... int, int, struct sockaddr *, socklen_t *
checking whether gettimeofday takes only one argument... no
checking for wcstombs_l declaration... no
checking for cbrt... yes
checking for dlopen... yes
checking for fdatasync... yes
checking for getifaddrs... yes
checking for getpeerucred... no
checking for getrlimit... yes
checking for mbstowcs_l... no
checking for memmove... yes
checking for poll... yes
checking for posix_fallocate... yes
checking for pstat... no
checking for pthread_is_threaded_np... no
checking for readlink... yes
checking for setproctitle... no
checking for setsid... yes
checking for shm_open... yes
checking for symlink... yes
checking for sync_file_range... yes
checking for towlower... yes
checking for utime... yes
checking for utimes... yes
checking for wcstombs... yes
checking for wcstombs_l... no
checking for fseeko... yes
checking for _LARGEFILE_SOURCE value needed for large files... no
checking for posix_fadvise... yes
checking whether posix_fadvise is declared... yes
checking whether fdatasync is declared... yes
checking whether strlcat is declared... no
checking whether strlcpy is declared... no
checking whether F_FULLFSYNC is declared... no
checking for struct sockaddr_in6... yes
checking for PS_STRINGS... no
checking for snprintf... yes
checking for vsnprintf... yes
checking whether snprintf is declared... yes
checking whether vsnprintf is declared... yes
checking for isinf... yes
checking for crypt... yes
checking for fls... no
checking for getopt... yes
checking for getrusage... yes
checking for inet_aton... yes
checking for mkdtemp... yes
checking for random... yes
checking for rint... yes
checking for srandom... yes
checking for strerror... yes
checking for strlcat... no
checking for strlcpy... no
checking for unsetenv... yes
checking for getpeereid... no
checking for getaddrinfo... yes
checking for getopt_long... yes
checking whether sys_siglist is declared... yes
checking for syslog... yes
checking syslog.h usability... yes
checking syslog.h presence... yes
checking for syslog.h... yes
checking for opterr... yes
checking for optreset... no
checking for strtoll... yes
checking for strtoull... yes
checking for rl_completion_append_character... yes
checking for rl_completion_matches... yes
checking for rl_filename_completion_function... yes
checking for rl_reset_screen_size... yes
checking for append_history... yes
checking for history_truncate_file... yes
checking test program... ok
checking whether long int is 64 bits... yes
checking whether snprintf supports the %z modifier... yes
checking size of void *... 8
checking size of size_t... 8
checking size of long... 8
checking whether to build with float4 passed by value... yes
checking whether to build with float8 passed by value... yes
checking alignment of short... 2
checking alignment of int... 4
checking alignment of long... 8
checking alignment of double... 8
checking for int8... no
checking for uint8... no
checking for int64... no
checking for uint64... no
checking for __int128... yes
checking for builtin __sync char locking functions... yes
checking for builtin __sync int32 locking functions... yes
checking for builtin __sync int32 atomic operations... yes
checking for builtin __sync int64 atomic operations... yes
checking for builtin __atomic int32 atomic operations... yes
checking for builtin __atomic int64 atomic operations... yes
checking for __get_cpuid... yes
checking for __cpuid... no
checking for _mm_crc32_u8 and _mm_crc32_u32 with CFLAGS=... no
checking for _mm_crc32_u8 and _mm_crc32_u32 with CFLAGS=-msse4.2... yes
checking which CRC-32C implementation to use... SSE 4.2 with runtime check
checking for onsgmls... no
checking for nsgmls... no
checking for openjade... no
checking for jade... no
checking for DocBook V4.2... no
checking for DocBook stylesheets... no
checking for collateindex.pl... no
checking for dbtoepub... no
checking for xmllint... xmllint
checking for xsltproc... xsltproc
checking for osx... no
checking for sgml2xml... no
checking for sx... sx
checking thread safety of required library functions... yes
checking whether gcc supports -Wl,--as-needed... yes
configure: using compiler=gcc (GCC) 4.8.3 20140911 (Red Hat 4.8.3-9)
configure: using CFLAGS=-Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -O2
configure: using CPPFLAGS= -D_GNU_SOURCE 
configure: using LDFLAGS=  -Wl,--as-needed
configure: creating ./config.status
config.status: creating GNUmakefile
config.status: creating src/Makefile.global
config.status: creating src/include/pg_config.h
config.status: creating src/include/pg_config_ext.h
config.status: creating src/interfaces/ecpg/include/ecpg_config.h
config.status: linking src/backend/port/tas/dummy.s to src/backend/port/tas.s
config.status: linking src/backend/port/dynloader/linux.c to src/backend/port/dynloader.c
config.status: linking src/backend/port/sysv_sema.c to src/backend/port/pg_sema.c
config.status: linking src/backend/port/sysv_shmem.c to src/backend/port/pg_shmem.c
config.status: linking src/backend/port/dynloader/linux.h to src/include/dynloader.h
config.status: linking src/include/port/linux.h to src/include/pg_config_os.h
config.status: linking src/makefiles/Makefile.linux to src/Makefile.port

默认安装目录/usr/local/pgsql,可以使用–prefix=path进行修改,./configure –help

8.2 编译
要开始编译,键入:

root@cs1 local]# make

(一定要记得用GNU make)。依你的硬件而异,编译过程可能需要 5 分钟到半小时。显示的最后一行应该是:

All of PostgreSQL successfully made. Ready to install.

如果你希望编译所有能编译的东西,包括文档(HTML和手册页)以及附加模块(contrib),这样键入:

[root@cs1 pgsql]# make world
.....省略.....
make[2]: 离开目录“/usr/local/postgresql-9.6.6/contrib/vacuumlo”
make[1]: 离开目录“/usr/local/postgresql-9.6.6/contrib”
PostgreSQL, contrib, and documentation successfully made. Ready to install.

8.3安装文件
要安装PostgreSQL,输入:

make install

这条命令将把文件安装到在步骤 1中指定的目录。确保你有足够的权限向该区域写入。通常你需要用 root 权限做这一步。或者你也可以事先创建目标目录并且分派合适的权限。

要安装文档(HTML和手册页),输入:

make install-docs

如果你按照上面的方法编译了所有东西,输入:

make install-world

这也会安装文档。

[root@cs1 pgsql]# make install-world
......省略....
make[2]: 离开目录“/usr/local/postgresql-9.6.6/contrib/vacuumlo”
make[1]: 离开目录“/usr/local/postgresql-9.6.6/contrib”
PostgreSQL, contrib, and documentation installation complete.

9.设置环境变量
创建目录/usr/local/pgsql/data用来存放数据

[root@cs1 pgsql]# mkdir /usr/local/pgsql/data
[root@cs1 pgsql]# chown pgsql:pgsql data

[root@cs1 pgsql]# su - pgsql
[pgsql@cs1 ~]$ vi .bash_profile
# .bash_profile

# Get the aliases and functions
if [ -f ~/.bashrc ]; then
        . ~/.bashrc
fi

# User specific environment and startup programs

PATH=$PATH:$HOME/.local/bin:$HOME/bin

export PATH
export LD_LIBRARY_PATH=/usr/local/pgsql/lib
export PG_HOME=/usr/local/pgsql
export PATH=$PG_HOME/bin/:$PATH
export PGDATA=/usr/local/pgsql/data

10.初始化数据库
使用pgsql用户来执行

[pgsql@cs1 ~]$ initdb --help
initdb initializes a PostgreSQL database cluster.

Usage:
  initdb [OPTION]... [DATADIR]

Options:
  -A, --auth=METHOD         default authentication method for local connections
      --auth-host=METHOD    default authentication method for local TCP/IP connections
      --auth-local=METHOD   default authentication method for local-socket connections
 [-D, --pgdata=]DATADIR     location for this database cluster
  -E, --encoding=ENCODING   set default encoding for new databases
      --locale=LOCALE       set default locale for new databases
      --lc-collate=, --lc-ctype=, --lc-messages=LOCALE
      --lc-monetary=, --lc-numeric=, --lc-time=LOCALE
                            set default locale in the respective category for
                            new databases (default taken from environment)
      --no-locale           equivalent to --locale=C
      --pwfile=FILE         read password for the new superuser from file
  -T, --text-search-config=CFG
                            default text search configuration
  -U, --username=NAME       database superuser name
  -W, --pwprompt            prompt for a password for the new superuser
  -X, --xlogdir=XLOGDIR     location for the transaction log directory

Less commonly used options:
  -d, --debug               generate lots of debugging output
  -k, --data-checksums      use data page checksums
  -L DIRECTORY              where to find the input files
  -n, --noclean             do not clean up after errors
  -N, --nosync              do not wait for changes to be written safely to disk
  -s, --show                show internal settings
  -S, --sync-only           only sync data directory

Other options:
  -V, --version             output version information, then exit
  -?, --help                show this help, then exit

If the data directory is not specified, the environment variable PGDATA
is used.

Report bugs to .
[pgsql@cs1 ~]$ initdb -D /usr/local/pgsql/data
The files belonging to this database system will be owned by user "pgsql".
This user must also own the server process.

The database cluster will be initialized with locale "zh_CN.gb2312".
The default database encoding has accordingly been set to "EUC_CN".
initdb: could not find suitable text search configuration for locale "zh_CN.gb2312"
The default text search configuration will be set to "simple".

Data page checksums are disabled.

fixing permissions on existing directory /usr/local/pgsql/data ... ok
creating subdirectories ... ok
selecting default max_connections ... 100
selecting default shared_buffers ... 128MB
selecting dynamic shared memory implementation ... posix
creating configuration files ... ok
running bootstrap script ... ok
performing post-bootstrap initialization ... ok
syncing data to disk ... ok

WARNING: enabling "trust" authentication for local connections
You can change this by editing pg_hba.conf or using the option -A, or
--auth-local and --auth-host, the next time you run initdb.

Success. You can now start the database server using:

    pg_ctl -D /usr/local/pgsql/data -l logfile start

同时在pgsql的目录可以看到生成的数据目录data以及该目录的相关数据和配置文件:

[root@cs1 soft]# cd /usr/local/pgsql
[root@cs1 pgsql]# ls -lrt
总用量 1080
-rw-r--r--  1 pgsql pgsql   1212 11月  7 2017 README
-rw-r--r--  1 pgsql pgsql   1529 11月  7 2017 Makefile
-rw-r--r--  1 pgsql pgsql    284 11月  7 2017 HISTORY
-rw-r--r--  1 pgsql pgsql   3638 11月  7 2017 GNUmakefile.in
-rw-r--r--  1 pgsql pgsql   1192 11月  7 2017 COPYRIGHT
-rw-r--r--  1 pgsql pgsql  74867 11月  7 2017 configure.in
-rwxr-xr-x  1 pgsql pgsql 471555 11月  7 2017 configure
-rw-r--r--  1 pgsql pgsql    384 11月  7 2017 aclocal.m4
drwxrwxrwx 55 pgsql pgsql   4096 11月  7 2017 contrib
drwxrwxrwx  2 pgsql pgsql   4096 11月  7 2017 config
drwxrwxrwx  3 pgsql pgsql    101 11月  7 2017 doc
-rw-r--r--  1 pgsql pgsql  76016 11月  7 2017 INSTALL
-rwxr-xr-x  1 root  root   39264 6月   4 21:29 config.status
-rw-r--r--  1 root  root    3638 6月   4 21:29 GNUmakefile
drwxrwxrwx 16 pgsql pgsql   4096 6月   4 21:29 src
-rw-r--r--  1 root  root  370213 6月   4 21:29 config.log
drwxr-xr-x  4 root  root      26 6月   4 21:43 tmp_install
drwxr-xr-x  6 root  root    4096 6月   4 21:45 include
drwxr-xr-x  8 root  root    4096 6月   4 21:45 share
drwxr-xr-x  4 root  root    4096 6月   4 21:45 lib
drwxr-xr-x  2 root  root    4096 6月   4 21:45 bin
drwx------ 19 pgsql pgsql   4096 6月   4 21:56 data
[root@cs1 pgsql]# cd data
[root@cs1 data]# ls -lrt
总用量 48
drwx------ 2 pgsql pgsql     6 6月   4 21:56 pg_twophase
drwx------ 2 pgsql pgsql     6 6月   4 21:56 pg_snapshots
drwx------ 2 pgsql pgsql     6 6月   4 21:56 pg_serial
drwx------ 2 pgsql pgsql     6 6月   4 21:56 pg_replslot
drwx------ 4 pgsql pgsql    34 6月   4 21:56 pg_multixact
drwx------ 2 pgsql pgsql     6 6月   4 21:56 pg_dynshmem
drwx------ 2 pgsql pgsql     6 6月   4 21:56 pg_commit_ts
-rw------- 1 pgsql pgsql     4 6月   4 21:56 PG_VERSION
drwx------ 2 pgsql pgsql     6 6月   4 21:56 pg_tblspc
drwx------ 2 pgsql pgsql     6 6月   4 21:56 pg_stat_tmp
drwx------ 2 pgsql pgsql     6 6月   4 21:56 pg_stat
drwx------ 4 pgsql pgsql    37 6月   4 21:56 pg_logical
-rw------- 1 pgsql pgsql 22304 6月   4 21:56 postgresql.conf
-rw------- 1 pgsql pgsql    88 6月   4 21:56 postgresql.auto.conf
-rw------- 1 pgsql pgsql  1636 6月   4 21:56 pg_ident.conf
-rw------- 1 pgsql pgsql  4459 6月   4 21:56 pg_hba.conf
drwx------ 3 pgsql pgsql    58 6月   4 21:56 pg_xlog
drwx------ 2 pgsql pgsql    17 6月   4 21:56 pg_subtrans
drwx------ 2 pgsql pgsql    17 6月   4 21:56 pg_clog
drwx------ 2 pgsql pgsql    17 6月   4 21:56 pg_notify
drwx------ 2 pgsql pgsql  4096 6月   4 21:56 global
drwx------ 5 pgsql pgsql    38 6月   4 21:56 base

11.启动数据库
在初始化数据库结束后看到了启动命令:

Success. You can now start the database server using:

    pg_ctl -D /usr/local/pgsql/data -l logfile start
[pgsql@cs1 ~]$ echo $PGDATA
/usr/local/pgsql/data

由于我们设置了环境变量,所以已经指定了数据目录PGDATA, -l表示日志文件目录,通常需要指定,所以我们在/usr/local/pgsql根目录下再创建一个log目录用来存放日志文件(注意别忘记赋予可写的权限)

[root@cs1 pgsql]# chown -R pgsql:pgsql log
[root@cs1 pgsql]# chmod -R 775 log
[root@cs1 pgsql]# ls -lrt
总用量 1080
-rw-r--r--  1 pgsql pgsql   1212 11月  7 2017 README
-rw-r--r--  1 pgsql pgsql   1529 11月  7 2017 Makefile
-rw-r--r--  1 pgsql pgsql    284 11月  7 2017 HISTORY
-rw-r--r--  1 pgsql pgsql   3638 11月  7 2017 GNUmakefile.in
-rw-r--r--  1 pgsql pgsql   1192 11月  7 2017 COPYRIGHT
-rw-r--r--  1 pgsql pgsql  74867 11月  7 2017 configure.in
-rwxr-xr-x  1 pgsql pgsql 471555 11月  7 2017 configure
-rw-r--r--  1 pgsql pgsql    384 11月  7 2017 aclocal.m4
drwxrwxrwx 55 pgsql pgsql   4096 11月  7 2017 contrib
drwxrwxrwx  2 pgsql pgsql   4096 11月  7 2017 config
drwxrwxrwx  3 pgsql pgsql    101 11月  7 2017 doc
-rw-r--r--  1 pgsql pgsql  76016 11月  7 2017 INSTALL
-rwxr-xr-x  1 root  root   39264 6月   4 21:29 config.status
-rw-r--r--  1 root  root    3638 6月   4 21:29 GNUmakefile
drwxrwxrwx 16 pgsql pgsql   4096 6月   4 21:29 src
-rw-r--r--  1 root  root  370213 6月   4 21:29 config.log
drwxr-xr-x  4 root  root      26 6月   4 21:43 tmp_install
drwxr-xr-x  6 root  root    4096 6月   4 21:45 include
drwxr-xr-x  8 root  root    4096 6月   4 21:45 share
drwxr-xr-x  4 root  root    4096 6月   4 21:45 lib
drwxr-xr-x  2 root  root    4096 6月   4 21:45 bin
drwx------ 19 pgsql pgsql   4096 6月   4 21:56 data
drwxrwxr-x  2 pgsql pgsql      6 6月   4 22:04 log

运行pg_ctl start -l /usr/local/pgsql/log/pg_server.log即可启动数据库

[pgsql@cs1 ~]$ pg_ctl start -l /usr/local/pgsql/log/pg_server.log
server starting

通过ps -ef|grep postgres查看一下postgres相关是否存在相关进程

[root@cs1 log]# ps -ef|grep postgres
pgsql     4977     1  0 22:05 pts/3    00:00:00 /usr/local/postgresql-9.6.6/bin/postgres
pgsql     4980  4977  0 22:05 ?        00:00:00 postgres: checkpointer process   
pgsql     4981  4977  0 22:05 ?        00:00:00 postgres: writer process   
pgsql     4982  4977  0 22:05 ?        00:00:00 postgres: wal writer process   
pgsql     4983  4977  0 22:05 ?        00:00:00 postgres: autovacuum launcher process   
pgsql     4984  4977  0 22:05 ?        00:00:00 postgres: stats collector process   
root      5145 15622  0 22:06 pts/4    00:00:00 grep --color=auto postgres

从数据库日志文件可以看到如下信息:

[root@cs1 log]# tail -f pg_server.log 
LOG:  database system was shut down at 2019-06-04 21:56:12 CST
LOG:  MultiXact member wraparound protections are now enabled
LOG:  database system is ready to accept connections
LOG:  autovacuum launcher started

12.连接数据库

[pgsql@cs1 ~]$ psql --list
                               List of databases
   Name    | Owner | Encoding |   Collate    |    Ctype     | Access privileges 
-----------+-------+----------+--------------+--------------+-------------------
 postgres  | pgsql | EUC_CN   | zh_CN.gb2312 | zh_CN.gb2312 | 
 template0 | pgsql | EUC_CN   | zh_CN.gb2312 | zh_CN.gb2312 | =c/pgsql         +
           |       |          |              |              | pgsql=CTc/pgsql
 template1 | pgsql | EUC_CN   | zh_CN.gb2312 | zh_CN.gb2312 | =c/pgsql         +
           |       |          |              |              | pgsql=CTc/pgsql
(3 rows)

启动成功后我们就可以通过postgresql自带的客户端工具psql来进行连接,直接输入psql看到版本信息则说明连接成功:

[pgsql@cs1 ~]$ psql postgres
psql (9.6.6)
Type "help" for help.

postgres=# 

接下来要做的第一件事就是设置postgres用户的密码(默认为空),用psql连接成功后直接输入\password即会提示输入两次密码

[pgsql@cs1 ~]$ psql postgres
psql (9.6.6)
Type "help" for help.

postgres=# \password
Enter new password: 
Enter it again: 
postgres=# \l
                               List of databases
   Name    | Owner | Encoding |   Collate    |    Ctype     | Access privileges 
-----------+-------+----------+--------------+--------------+-------------------
 postgres  | pgsql | EUC_CN   | zh_CN.gb2312 | zh_CN.gb2312 | 
 template0 | pgsql | EUC_CN   | zh_CN.gb2312 | zh_CN.gb2312 | =c/pgsql         +
           |       |          |              |              | pgsql=CTc/pgsql
 template1 | pgsql | EUC_CN   | zh_CN.gb2312 | zh_CN.gb2312 | =c/pgsql         +
           |       |          |              |              | pgsql=CTc/pgsql
(3 rows)


postgres=# \l
                               List of databases
   Name    | Owner | Encoding |   Collate    |    Ctype     | Access privileges 
-----------+-------+----------+--------------+--------------+-------------------
 postgres  | pgsql | EUC_CN   | zh_CN.gb2312 | zh_CN.gb2312 | 
 template0 | pgsql | EUC_CN   | zh_CN.gb2312 | zh_CN.gb2312 | =c/pgsql         +
           |       |          |              |              | pgsql=CTc/pgsql
 template1 | pgsql | EUC_CN   | zh_CN.gb2312 | zh_CN.gb2312 | =c/pgsql         +
           |       |          |              |              | pgsql=CTc/pgsql
(3 rows)

postgres=# select version();
                                                 version                                                 
---------------------------------------------------------------------------------------------------------
 PostgreSQL 9.6.6 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.3 20140911 (Red Hat 4.8.3-9), 64-bit
(1 row)

postgres=# select current_date;
    date    
------------
 2019-06-04
(1 row)

postgres=# 

到此使用源码来安装pg数据库就完成了。

Proudly powered by WordPress | Indrajeet by Sus Hill.