PostgreSQL使用表继承实现分区表

PostgreSQL9.6支持基本表的分区。这部分将描述为什么以及如何来实现表分区作为你数据库设计的一部分。

概述
分区指的是将逻辑上一的一个大表分成多个小的物理上的片(子表),分区可以提供以下好处:
.在某些情况下查询性能能够显著提升,特别是当那些访问压力大的行在一个分区或者少数几个分区时。分区可以取代索引的主导列、减小索引尺寸以及使索引中访问压力大的部分更有可能被放在内存中。

.当查询或更新访问一个分区的大部分行时,可以通过该分区上的一个顺序扫描来取代分散到整个表上的索引和随机访问,这样可以改善性能。

.如果需求计划使用划分设计,可以通过增加或移除分区来完成批量载入和删除。ALTER TABLE NO INHERIT和DROP TABLE都远快于一个批量操作。这些命令也完全避免了由批量DELETE造成的VACUUM负载。

.很少使用的数据可以被迁移到便宜且较慢的存储介质上。

当一个表非常大时,分区所带来的好处是非常值得的。一个表何种情况下会从分区中获益取决于应用,一个经验法则是当表的尺寸超过了数据库服务器物理内存时,分区会为表带来好处。

当前,PostgreSQL支持通过表继承来实现分区。每个分区必须被创建为单个父表的子表。父表它本身正常来说是空的;它存在仅仅是代表整个数据库。在试图设置分区之前应该要先熟悉表继承。

在PostgreSQL中可以实现下列形式的分区:

范围分区
表被根据一个关键列或一组列划分为”范围”分区,不同的分区的范围之间没有重叠。例如,我们可以根据日期范围划分分区,或者根据特定业务对象的标识符划分分区。

列表分区
通过显式地列出每一个分区中出现的键值来划分表。

实现分区
要建立一个分区表,可以这样做:
1.创建一个”主”表,所有的分区都将继承它。
这个表将不包含数据。不要对这个表定义任何检查约束,除非你打算将这些约束应用到所有的分区。同样也不需要定义任何索引或者唯一约束。

2.创建一些继承于主表的”子”表。通常,这些表不会在从主表继承的列集中增加任何列。
们将这些子表认为是分区,尽管它们在各方面来看普通的PostgreSQL表(或者可能是外部表)。

3.为分区表增加表约束以定义每个分区中允许的键值。
典型的例子是:

CHECK ( x = 1 )
CHECK ( county IN ( 'Oxfordshire', 'Buckinghamshire', 'Warwickshire' ))
CHECK ( outletID >= 100 AND outletID < 200 )

要确保这些约束能够保证在不同分区所允许的键值之间不存在重叠。设置范围约束时一种常见的错误是:

CHECK ( outletID BETWEEN 100 AND 200 )
CHECK ( outletID BETWEEN 200 AND 300 )

这是错误的,因为键值200并没有被清楚地分配到某一个分区。注意在语法上范围划分和列表划分没有区别,这些术语只是为了描述方便而存在。

4.对于每一个分区,在关键列上创建一个索引,并创建其他我们所需要的索引(关键索引并不是严格必要的,但是在大部分情况下它都是有用的。如果我们希望键值是唯一的,则我们还要为每一个分区创建一个唯一或者主键约束。)

5.还可以有选择地定义一个触发器或者规则将插入到主表上的数据重定向到合适的分区上。

6.确保在postgresql.conf中constraint_exclusion配置参数没有被禁用。如果它被禁用,查询将不会被按照期望的方式优化。

例如,假设我们正在为一个大型的冰淇淋公司构建一个数据库。该公司测量每天在每一个区域的最高气温以及冰淇淋销售。在概念上,我们想要一个这样的表:

CREATE TABLE measurement (
city_id int not null,
logdate date not null,
peaktemp int,
unitsales int
);

insert into measurement values(1,date '2008-02-01',1,1);

由于该表的主要用途是为管理层提供在线报告,我们知道大部分查询将只会访问上周、上月或者上季度的数据。为了减少需要保存的旧数据的量,我们决定只保留最近3年的数据。在每一个月的开始,我们将删除最老的一个月的数据。

在这种情况下,我们可以使用分区来帮助我们满足对于测量表的所有不同需求。按照上面所勾勒的步骤,分区可以这样来建立:

1.主表是measurement表,完全按照以上的方式声明。

jydb=# CREATE TABLE measurement (
jydb(#     city_id         int not null,
jydb(#     logdate         date not null,
jydb(#     peaktemp        int,
jydb(#     unitsales       int
jydb(# );
CREATE TABLE

2.下一步我们为每一个活动月创建一个分区:

CREATE TABLE measurement_y2006m02 ( ) INHERITS (measurement);
CREATE TABLE measurement_y2006m03 ( ) INHERITS (measurement);
...
CREATE TABLE measurement_y2007m11 ( ) INHERITS (measurement);
CREATE TABLE measurement_y2007m12 ( ) INHERITS (measurement);
CREATE TABLE measurement_y2008m01 ( ) INHERITS (measurement);

每一个分区自身都是完整的表,但是它们的定义都是从measurement表继承而来。

这解决了我们的一个问题:删除旧数据。每个月,我们所需要做的是在最旧的子表上执行一个DROP TABLE命令并为新一个月的数据创建一个新的子表。

3.我们必须提供不重叠的表约束。和前面简单地创建分区表不同,实际的表创建脚本应该是:

jydb=# CREATE TABLE measurement_y2006m02 (
jydb(#     CHECK ( logdate >= DATE '2006-02-01' AND logdate < DATE '2006-03-01' )
jydb(# ) INHERITS (measurement);
CREATE TABLE
jydb=# CREATE TABLE measurement_y2006m03 (
jydb(#     CHECK ( logdate >= DATE '2006-03-01' AND logdate < DATE '2006-04-01' )
jydb(# ) INHERITS (measurement);
CREATE TABLE
jydb=# CREATE TABLE measurement_y2008m02 (
jydb(#     CHECK ( logdate >= DATE '2008-02-01' AND logdate < DATE '2008-03-01' )
jydb(# ) INHERITS (measurement);
CREATE TABLE
jydb=# CREATE TABLE measurement_y2008m03
jydb-#   (LIKE measurement INCLUDING DEFAULTS INCLUDING CONSTRAINTS);
CREATE TABLE

4.我们可能在关键列上也需要索引:

CREATE INDEX measurement_y2006m02_logdate ON measurement_y2006m02 (logdate);
CREATE INDEX measurement_y2006m03_logdate ON measurement_y2006m03 (logdate);
...
CREATE INDEX measurement_y2007m11_logdate ON measurement_y2007m11 (logdate);
CREATE INDEX measurement_y2007m12_logdate ON measurement_y2007m12 (logdate);
CREATE INDEX measurement_y2008m01_logdate ON measurement_y2008m01 (logdate);

在这里我们选择不增加更多的索引。

5.我们希望我们的应用能够使用INSERT INTO measurement …并且数据将被重定向到合适的分区表。我们可以通过为主表附加一个合适的触发器函数来实现这一点。如果数据将只被增加到最后一个分区,我们可以使用一个非常简单的触发器函数:

CREATE OR REPLACE FUNCTION measurement_insert_trigger()
RETURNS TRIGGER AS $$
BEGIN
    INSERT INTO measurement_y2008m01 VALUES (NEW.*);
    RETURN NULL;
END;
$$
LANGUAGE plpgsql;

完成函数创建后,我们创建一个调用该触发器函数的触发器:

CREATE TRIGGER insert_measurement_trigger
    BEFORE INSERT ON measurement
    FOR EACH ROW EXECUTE PROCEDURE measurement_insert_trigger();

我们必须在每个月重新定义触发器函数,这样它才会总是指向当前分区。而触发器的定义则不需要被更新。

我们也可能希望插入数据时服务器会自动地定位应该加入数据的分区。我们可以通过一个更复杂的触发器函数来实现之,例如:

jydb=# CREATE OR REPLACE FUNCTION measurement_insert_trigger()
jydb-# RETURNS TRIGGER AS $$
jydb$# BEGIN
jydb$#
jydb$#     IF ( NEW.logdate >= DATE '2006-03-01' AND
jydb$#             NEW.logdate < DATE '2006-04-01' ) THEN
jydb$#         INSERT INTO measurement_y2006m03 VALUES (NEW.*);
jydb$#     ELSIF ( NEW.logdate >= DATE '2008-02-01' AND
jydb$#             NEW.logdate < DATE '2008-03-01' ) THEN
jydb$#         INSERT INTO measurement_y2008m02 VALUES (NEW.*);
jydb$#     ELSE
jydb$#         RAISE EXCEPTION 'Date out of range.  Fix the measurement_insert_trigger() function!';
jydb$#     END IF;
jydb$#     RETURN NULL;
jydb$# END;
jydb$# $$
jydb-# LANGUAGE plpgsql;
CREATE FUNCTION



jydb=# CREATE TRIGGER insert_measurement_trigger
jydb-#     BEFORE INSERT ON measurement
jydb-#     FOR EACH ROW EXECUTE PROCEDURE measurement_insert_trigger();
CREATE TRIGGER
jydb=# insert into measurement values(1,date '2006-03-03',1,1);
INSERT 0 0
jydb=# insert into measurement values(1,date '2008-02-03',1,1);
INSERT 0 0
jydb=# select * from measurement_y2006m03;
 city_id |  logdate   | peaktemp | unitsales
---------+------------+----------+-----------
       1 | 2006-03-02 |        1 |         1
       1 | 2006-03-03 |        1 |         1
(2 rows)

jydb=# select * from measurement_y2008m02;
 city_id |  logdate   | peaktemp | unitsales
---------+------------+----------+-----------
       1 | 2008-02-01 |        1 |         1
       1 | 2008-02-01 |        1 |         1
       1 | 2008-02-01 |        1 |         1
       1 | 2008-02-02 |        1 |         1
       1 | 2008-02-03 |        1 |         1
(5 rows)

jydb=# select * from measurement;
 city_id |  logdate   | peaktemp | unitsales
---------+------------+----------+-----------
       1 | 2006-03-02 |        1 |         1
       1 | 2006-03-03 |        1 |         1
       1 | 2008-02-01 |        1 |         1
       1 | 2008-02-01 |        1 |         1
       1 | 2008-02-01 |        1 |         1
       1 | 2008-02-02 |        1 |         1
       1 | 2008-02-03 |        1 |         1
(7 rows)

触发器的定义和以前一样。注意每一个IF测试必须准确地匹配它的分区的CHECK约束。当该函数比单月形式更加复杂时,并不需要频繁地更新它,因为可以在需要的时候提前加入分支。

注意: 在实践中,如果大部分插入都会进入最新的分区,最好先检查它。为了简洁,我们为触发器的检查采用了和本例中其他部分一致的顺序。

如我们所见,一个复杂的分区模式可能需要大量的DDL。在上面的例子中,我们需要每月创建一个新分区,所以最好能够编写一个脚本自动地生成所需的DDL。

管理分区
通常当初始定义的表倾向于动态变化时,一组分区会被创建。删除旧的分区并周期性地为新数据增加新分区是很常见的。划分的一个最重要的优点是可以通过操纵分区结构来使得这种痛苦的任务几乎是自发地完成,而不需要去物理地移除大量的数据。

移除旧数据的最简单的选项是直接删除不再需要的分区:

jydb=# DROP TABLE measurement_y2006m02;
DROP TABLE

这可以非常快地删除百万级别的记录,因为它不需要逐一地删除记录。

另一个经常使用的选项是将分区从被划分的表中移除,但是把它作为一个独立的表保留下来:

ALTER TABLE measurement_y2006m02 NO INHERIT measurement;

这允许在数据被删除前执行更进一步的操作。例如,这是一个很有用的时机通过COPY、pg_dump或类似的工具来备份数据。这也是进行数据聚集、执行其他数据操作或运行报表的好时机。

相似地我们也可以增加新分区来处理新数据。我们可以在被划分的表中创建一个新的空分区:

jydb=# CREATE TABLE measurement_y2008m02 (
jydb(#     CHECK ( logdate >= DATE '2008-02-01' AND logdate < DATE '2008-03-01' )
jydb(# ) INHERITS (measurement);
CREATE TABLE

作为一种选择方案,有时创建一个在分区结构之外的新表更方便,并且在以后才将它作为一个合适的分区。这使得数据可以在出现于分区表中之前被载入、检查和转换:

jydb=# CREATE TABLE measurement_y2008m03
jydb-#   (LIKE measurement INCLUDING DEFAULTS INCLUDING CONSTRAINTS);
CREATE TABLE
jydb=# ALTER TABLE measurement_y2008m03 ADD CONSTRAINT y2008m03
jydb-#    CHECK ( logdate >= DATE '2008-03-01' AND logdate < DATE '2008-04-01' );
ALTER TABLE
jydb=# ALTER TABLE measurement_y2008m03 INHERIT measurement;
ALTER TABLE

分区与约束排除
约束排除是一种查询优化技术,它可以为按照以上方式定义的分区表提高性能。例如:

jydb=# SET constraint_exclusion = on;
SET
jydb=# SELECT count(*) FROM measurement WHERE logdate >= DATE '2008-01-01';
 count
-------
     3
(1 row)

如果没有约束排除,上述查询将扫描measurement表的每一个分区。在启用约束排除后,规划器将检查每一个分区的约束来确定该分区需不需要被扫描,因为分区中可能不包含满足查询WHERE子句的行。如果规划器能够证实这一点,则它将会把该分区排除在查询计划之外。

可以使用EXPLAIN命令来显示开启了constraint_exclusion的计划和没有开启该选项的计划之间的区别。一个典型的未优化的计划是:

jydb=# SET constraint_exclusion = off;
SET
jydb=# EXPLAIN SELECT count(*) FROM measurement WHERE logdate >= DATE '2008-01-01';
                                    QUERY PLAN
-----------------------------------------------------------------------------------
 Aggregate  (cost=107.47..107.48 rows=1 width=8)
   ->  Append  (cost=0.00..102.69 rows=1913 width=0)
         ->  Seq Scan on measurement  (cost=0.00..3.31 rows=62 width=0)
               Filter: (logdate >= '2008-01-01'::date)
         ->  Seq Scan on measurement_y2006m03  (cost=0.00..33.12 rows=617 width=0)
               Filter: (logdate >= '2008-01-01'::date)
         ->  Seq Scan on measurement_y2008m02  (cost=0.00..33.12 rows=617 width=0)
               Filter: (logdate >= '2008-01-01'::date)
         ->  Seq Scan on measurement_y2008m03  (cost=0.00..33.12 rows=617 width=0)
               Filter: (logdate >= '2008-01-01'::date)
(10 rows)

其中的某些或者全部分区将会使用索引扫描而不是全表顺序扫描,但是关键在于根本不需要扫描旧分区来回答这个查询。当我们开启约束排除后,对于同一个查询我们会得到一个更加廉价的计划:

jydb=# SET constraint_exclusion = on;
SET
jydb=# EXPLAIN SELECT count(*) FROM measurement WHERE logdate >= DATE '2008-01-01';
                                    QUERY PLAN
-----------------------------------------------------------------------------------
 Aggregate  (cost=72.80..72.81 rows=1 width=8)
   ->  Append  (cost=0.00..69.56 rows=1296 width=0)
         ->  Seq Scan on measurement  (cost=0.00..3.31 rows=62 width=0)
               Filter: (logdate >= '2008-01-01'::date)
         ->  Seq Scan on measurement_y2008m02  (cost=0.00..33.12 rows=617 width=0)
               Filter: (logdate >= '2008-01-01'::date)
         ->  Seq Scan on measurement_y2008m03  (cost=0.00..33.12 rows=617 width=0)
               Filter: (logdate >= '2008-01-01'::date)
(8 rows)

注意约束排除只由CHECK约束驱动,而非索引的存在。因此,没有必要在关键列上定义索引。是否在给定分区上定义索引取决于我们希望查询经常扫描表的大部分还是小部分。在后一种情况中索引将会发挥作用。

constraint_exclusion的默认(也是推荐)设置实际上既不是on也不是off,而是一个被称为partition的中间设置,这使得该技术只被应用于将要在分区表上工作的查询。设置on将使得规划器在所有的查询中检查CHECK约束,即使简单查询不会从中受益。

替代的分区方法
另一种将插入数据重定向到合适的分区的方法是在主表上建立规则而不是触发器,例如:

jydb=# CREATE RULE measurement_insert_y2006m03 AS
jydb-# ON INSERT TO measurement WHERE
jydb-# ( logdate >= DATE '2006-03-01' AND logdate < DATE '2006-04-01' )
jydb-# DO INSTEAD
jydb-# INSERT INTO measurement_y2006m03 VALUES (NEW.*);
CREATE RULE
jydb=# CREATE RULE measurement_insert_y2008m02 AS
jydb-# ON INSERT TO measurement WHERE
jydb-# ( logdate >= DATE '2008-02-01' AND logdate < DATE '2008-03-01' )
jydb-# DO INSTEAD
jydb-# INSERT INTO measurement_y2008m02 VALUES (NEW.*);
CREATE RULE


jydb=# insert into measurement values(1,date '2006-03-02',1,1);
INSERT 0 0
jydb=# insert into measurement values(1,date '2008-02-02',1,1);
INSERT 0 0
jydb=# select * from measurement;
 city_id |  logdate   | peaktemp | unitsales
---------+------------+----------+-----------
       1 | 2006-03-02 |        1 |         1
       1 | 2008-02-01 |        1 |         1
       1 | 2008-02-01 |        1 |         1
       1 | 2008-02-01 |        1 |         1
       1 | 2008-02-02 |        1 |         1
(5 rows)

jydb=# select * from measurement_y2006m03;
 city_id |  logdate   | peaktemp | unitsales
---------+------------+----------+-----------
       1 | 2006-03-02 |        1 |         1
(1 row)

jydb=# select * from measurement_y2008m02;
 city_id |  logdate   | peaktemp | unitsales
---------+------------+----------+-----------
       1 | 2008-02-01 |        1 |         1
       1 | 2008-02-01 |        1 |         1
       1 | 2008-02-01 |        1 |         1
       1 | 2008-02-02 |        1 |         1
(4 rows)

一个规则比一个触发器具有明显更高的负荷,但是该负荷是由每个查询承担而不是每一个行,因此这种方法可能对于批量插入的情况有益。但是,在大部分情况下触发器方法能提供更好的性能。

注意COPY会忽略规则。如果希望使用COPY来插入数据,我们将希望将数据复制到正确的分区表而不是主表。COPY会引发触发器,因此如果使用触发器方法就可以正常地使用它。

规则方法的另一个缺点是如果一组规则没有覆盖被插入的数据,则该数据将被插入到主表中而不会发出任何错误。

分区也可以使用一个UNION ALL视图来组织。例如:

CREATE VIEW measurement AS
          SELECT * FROM measurement_y2006m02
UNION ALL SELECT * FROM measurement_y2006m03
...
UNION ALL SELECT * FROM measurement_y2007m11
UNION ALL SELECT * FROM measurement_y2007m12
UNION ALL SELECT * FROM measurement_y2008m01;

但是,如果要增加或者删除单独的分区,就需要重新地创建视图。在实践中,相对于使用继承,这种方法很少被推荐。

警告
下面的警告适用于分区表:
.没有自动的方法来验证所有的CHECK约束是互斥的。创建代码来生成分区并创建或修改相关对象比手工写命令要更安全。

.这里展示的模式都假设分区的关键列从不改变,或者是其改变不足以导致它被移到另一个分区。一个尝试将行移到另一个分区的UPDATE会失败,因为CHECK约束的存在。如果我们需要处理这类情况,我们可以在分区表上放置合适的更新触发器,但是它会使得结构的管理更加复杂。

.如果我们在使用手工的VACUUM或ANALYZE命令,别忘了需要在每一个分区上都运行一次。以下的命令:
ANALYZE measurement;
只会处理主表。

.带有ON CONFLICT子句的INSERT 语句不太可能按照预期的方式工作,因为ON CONFLICT动作 只有在指定的目标关系(而非它的子关系)上有唯一违背的情况下才会被采用。

下面的警告适用于约束排除:
.只有在查询的WHERE子句包含常量(或者外部提供的参数)时,约束排除才会起效。例如,一个与非不变函数(例如CURRENT_TIMESTAMP)的比较不能被优化,因为规划器不知道该函数的值在运行时会落到哪个分区内。

.保持分区约束简单,否则规划器可能没有办法验证无需访问的分区。按前面的例子所示,为列表分区使用简单相等条件或者为范围分区使用简单范围测试。一个好的经验法则是分区约束应该只包含使用B-tree索引操作符的比较,比较的双方应该是分区列和常量。

.在约束排除期间,主表所有的分区上的所有约束都会被检查,所以大量的分区将会显著地增加查询规划时间。使用这些技术的分区在大约最多100个分区的情况下工作得很好,但是不要尝试使用成千个分区。

PostgreSQL 表继承

PostgreSQL实现了表继承,这对数据库设计者来说是一种有用的工具(SQL:1999及其后的版本定义了一种类型继承特性,但和这里介绍的继承有很大的不同)。让我们从一个例子开始:假设我们要为城市建立一个数据模型。每一个州有很多城市,但是只有一个首府。我们希望能够快速地检索任何特定州的首府城市。这可以通过创建两个表来实现:一个用于州首府,另一个用于不是首府的城市。然而,当我们想要查看一个城市的数据(不管它是不是一个首府)时会发生什么?继承特性将有助于解决这个问题。我们可以将capitals表定义为继承自cities表:

jydb=# CREATE TABLE cities (
jydb(# name text,
jydb(# population float,
jydb(# altitude int -- in feet
jydb(# );
CREATE TABLE
jydb=# CREATE TABLE capitals (
jydb(# state char(2)
jydb(# ) INHERITS (cities);
CREATE TABLE


jydb=# insert into cities values('Las Vegas',600,2174);
INSERT 0 1
jydb=# insert into cities values('Mariposa',500,1953);
INSERT 0 1
jydb=# insert into cities values('Madison',450,845);
INSERT 0 1
jydb=# insert into capitals values('Houston',400,745,'LA');
INSERT 0 1


jydb=# select * from cities;
   name    | population | altitude
-----------+------------+----------
 Las Vegas |        600 |     2174
 Mariposa  |        500 |     1953
 Madison   |        450 |      845
 Houston   |        400 |      745
(4 rows)

jydb=# select * from capitals;
  name   | population | altitude | state
---------+------------+----------+-------
 Houston |        400 |      745 | LA
(1 row)

在这种情况下,capitals表继承了它父表cities的所有列。州首府还有一个额外的列state用来表示它所属的州。

在PostgreSQL中,一个表可以从0个或者多个其他表继承,而对一个表的查询则可以引用一个表的所有行或者该表的所有行加上它所有的后代表。默认情况是后一种行为。例如,下面的查询将查找所有海拔高于500尺的城市的名称,包括州首府:

jydb=# SELECT name, altitude FROM cities WHERE altitude > 500;
   name    | altitude
-----------+----------
 Las Vegas |     2174
 Mariposa  |     1953
 Madison   |      845
 Houston   |      745
(4 rows)

在另一方面,下面的查询将找到海拔超过500尺且不是州首府的所有城市:

jydb=# SELECT name, altitude FROM ONLY cities WHERE altitude > 500;
   name    | altitude
-----------+----------
 Las Vegas |     2174
 Mariposa  |     1953
 Madison   |      845
(3 rows)

这里的ONLY关键词指示查询只被应用于cities上,而其他在继承层次中位于cities之下的其他表都不会被该查询涉及。很多我们已经讨论过的命令(如SELECT、UPDATE和DELETE)都支持ONLY关键词。

我们也可以在表名后写上一个*来显式地将后代表包括在查询范围内:

jydb=# SELECT name, altitude FROM cities* WHERE altitude > 500;
   name    | altitude
-----------+----------
 Las Vegas |     2174
 Mariposa  |     1953
 Madison   |      845
 Houston   |      745
(4 rows)

*并不是必须的,因为它对应的行为是默认的(除非改变sql_inheritance配置选项的设置)。但是书写*有助于强调会有附加表被搜索。

在某些情况下,我们可能希望知道一个特定行来自于哪个表。每个表中的系统列tableoid可以告诉我们行来自于哪个表:

jydb=# SELECT c.tableoid, c.name, c.altitude FROM cities c WHERE c.altitude > 500;
 tableoid |   name    | altitude
----------+-----------+----------
    24653 | Las Vegas |     2174
    24653 | Mariposa  |     1953
    24653 | Madison   |      845
    24659 | Houston   |      745
(4 rows)

(如果重新生成这个结果,可能会得到不同的OID数字。)通过与pg_class进行连接可以看到实际的表名:

jydb=# SELECT p.relname, c.name, c.altitude
jydb-# FROM cities c, pg_class p
jydb-# WHERE c.altitude > 500 AND c.tableoid = p.oid;
 relname  |   name    | altitude
----------+-----------+----------
 cities   | Las Vegas |     2174
 cities   | Mariposa  |     1953
 cities   | Madison   |      845
 capitals | Houston   |      745
(4 rows)

另一种得到同样效果的方法是使用regclass伪类型, 它将象征性地打印出表的 OID:

jydb=# SELECT c.tableoid::regclass, c.name, c.altitude
jydb-# FROM cities c
jydb-# WHERE c.altitude > 500;
 tableoid |   name    | altitude
----------+-----------+----------
 cities   | Las Vegas |     2174
 cities   | Mariposa  |     1953
 cities   | Madison   |      845
 capitals | Houston   |      745
(4 rows)

继承不会自动地将来自INSERT或COPY命令的数据传播到继承层次中的其他表中。在我们的例子中,下面的INSERT语句将会失败:

jydb=# INSERT INTO cities (name, population, altitude, state) VALUES (’Albany’, NULL, NULL, ’NY’);
ERROR:  column "state" of relation "cities" does not exist
LINE 1: INSERT INTO cities (name, population, altitude, state) VALUE...

^

我们也许希望数据能被以某种方式被引入到capitals表中,但是这不会发生:INSERT总是向指定的表中插入。在某些情况下,可以通过使用一个规则(见第 39 章)来将插入动作重定向。但是这对上面的情况并没有帮助,因为cities表根本就不包含state列,因而这个命令将在触发规则之前就被拒绝。

父表上的所有检查约束和非空约束都将自动被它的后代所继承。其他类型的约束(唯一、主键和外键约束)则不会被继承。

一个表可以从多个父表继承,在这种情况下它拥有父表们所定义的列的并集。任何定义在子表上的列也会被加入到其中。如果在这个集合中出现重名列,那么这些列将被”合并”,这样在子表中只会有一个这样的列。重名列能被合并的前提是这些列必须具有相同的数据类型,否则会导致错误。可继承的检查约束和非空约束以类似的方式合并。因此,例如,如果任何列定义被标记为not-null,则合并列将被标记为not-null。如果检查约束具有相同的名称,则合并它们;如果条件不同,则合并将失败。

表继承通常是在子表被创建时建立,使用CREATE TABLE语句的INHERITS子句。一个已经被创建的表也可以另外一种方式增加一个新的父亲关系,使用ALTER TABLE的INHERIT变体。要这样做,新的子表必须已经包括和父表相同名称和数据类型的列。子表还必须包括和父表相同的检查约束和检查表达式。相似地,一个继承链接也可以使用ALTER TABLE的 NO INHERIT变体从一个子表中移除。动态增加和移除继承链接可以用于实现表划分

一种创建一个未来将被用做子女的新表的方法是在CREATE TABLE中使用LIKE子句。这将创建一个和源表具有相同列的新表。如果源表上定义有任何CHECK约束,LIKE的INCLUDING CONSTRAINTS选项可以用来让新的子表也包含和父表相同的约束。

当有任何一个子表存在时,父表不能被删除。当子表的列或者检查约束继承于父表时,它们也不能被删除或修改。如果希望移除一个表和它的所有后代,一种简单的方法是使用CASCADE选项删除父表

ALTER TABLE将会把列的数据定义或检查约束上的任何变化沿着继承层次向下传播。同样,删除被其他表依赖的列只能使用CASCADE选项。ALTER TABLE对于重名列的合并和拒绝遵循与CREATE TABLE同样的规则。

继承查询只对父表执行访问权限检查。因此,例如,对cities表授予update权限会意味着通过cities访问capitals表时也能更新capitals表。这体现了子表中的数据也在父表中。但是capitals表在没有额外地授权情况下不能被直接更新。以类似的方式,父表的行安全策略在执行继承查询时会应用到子表的行记录。子表的策略(如果有的话)仅当它是查询中显式命名的表时才应用;在这种情况下,任何附加到其父级的策略都将被忽略。

外部表也可以是继承层次 中的一部分,即可以作为父表也可以作为子表,就像常规表一样。如果一个外部表是继承层次的一部分,那么任何不被该外部表支持的操作也不被整个层次所支持。

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  postgresql-9.6.6.tar.gz

创建一个软链接

[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数据库就完成了。