PostgreSQL修改归档模式

联系:手机/微信(+86 17813235971) QQ(107644445)

标题:PostgreSQL修改归档模式

作者:惜分飞©版权所有[未经本人同意,不得以任何形式转载,否则有进一步追究法律责任的权利.]

pg版本

postgres=# select version();
                                                 version
---------------------------------------------------------------------------------------------------------
 PostgreSQL 10.4 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-18), 64-bit
(1 row)

归档配置参数

--pgdata中的postgresql.conf
wal_level = replica
archive_mode = on
archive_command = 'test ! -f /pg_archivedir/%f && cp %p /pg_archivedir/%f'
--重启pg systemctl restart postgresql-10.service
postgres=# show wal_level;
 wal_level
-----------
 replica
(1 row)
postgres=# show archive_mode;
 archive_mode
--------------
 on
(1 row)
postgres=# show archive_command;
                    archive_command
--------------------------------------------------------
 test ! -f /pg_archivedir/%f && cp %p /pg_archivedir/%f
(1 row)

测试归档效果

[root@localhost pg_wal]# ps -ef|grep "postgres: archiver process"
postgres  35300  35293  0 08:43 ?        00:00:00 postgres: archiver process   last was 000000010000000000000004
root      37504  20853  0 09:55 pts/1    00:00:00 grep --color=auto postgres: archiver process
[root@localhost pg_wal]# pwd
/opt/PostgreSQL/10/data/pg_wal
[root@localhost pg_wal]# ls -ltr
total 49156
-rw------- 1 postgres postgres      309 Aug  5 06:05 000000010000000000000002.00000028.backup
-rw------- 1 postgres postgres 16777216 Aug  5 08:43 000000010000000000000006
-rw------- 1 postgres postgres 16777216 Aug  5 08:50 000000010000000000000004
drwx------ 2 postgres postgres       94 Aug  5 08:50 archive_status
-rw------- 1 postgres postgres 16777216 Aug  5 08:53 000000010000000000000005
[root@localhost pg_wal]# ls -l /pg_archivedir/
total 65540
-rw------- 1 postgres postgres 16777216 Aug  5 08:37 000000010000000000000001
-rw------- 1 postgres postgres 16777216 Aug  5 08:37 000000010000000000000002
-rw------- 1 postgres postgres      309 Aug  5 08:37 000000010000000000000002
-rw------- 1 postgres postgres 16777216 Aug  5 08:43 000000010000000000000003
-rw------- 1 postgres postgres 16777216 Aug  5 08:50 000000010000000000000004
--切换日志
postgres=# select pg_switch_wal();
 pg_switch_wal
---------------
 0/5000158
(1 row)
[root@localhost pg_wal]# ps -ef|grep "postgres: archiver process"
postgres  35300  35293  0 08:43 ?        00:00:00 postgres: archiver process   last was 000000010000000000000005
root      37531  20853  0 09:56 pts/1    00:00:00 grep --color=auto postgres: archiver process
[root@localhost pg_wal]# ls -ltr
total 49156
-rw------- 1 postgres postgres      309 Aug  5 06:05 000000010000000000000002
-rw------- 1 postgres postgres 16777216 Aug  5 08:50 000000010000000000000004
-rw------- 1 postgres postgres 16777216 Aug  5 09:55 000000010000000000000005
drwx------ 2 postgres postgres      130 Aug  5 09:55 archive_status
-rw------- 1 postgres postgres 16777216 Aug  5 09:55 000000010000000000000006
[root@localhost pg_wal]# ls -l /pg_archivedir/
total 81924
-rw------- 1 postgres postgres 16777216 Aug  5 08:37 000000010000000000000001
-rw------- 1 postgres postgres 16777216 Aug  5 08:37 000000010000000000000002
-rw------- 1 postgres postgres      309 Aug  5 08:37 000000010000000000000002
-rw------- 1 postgres postgres 16777216 Aug  5 08:43 000000010000000000000003
-rw------- 1 postgres postgres 16777216 Aug  5 08:50 000000010000000000000004
-rw------- 1 postgres postgres 16777216 Aug  5 09:55 000000010000000000000005

PostgreSQL备份工具pg_rman安装

联系:手机/微信(+86 17813235971) QQ(107644445)

标题:PostgreSQL备份工具pg_rman安装

作者:惜分飞©版权所有[未经本人同意,不得以任何形式转载,否则有进一步追究法律责任的权利.]

学习oracle的同学都清楚,oracle的rman是最好的备份工具(一般第三方备份软件也基本上是通过调用rman的备份接口实现的)
pg_rman下载地址https://github.com/ossc-db/pg_rman/releases,下载和当前pg版本/操作系统版本对应的pg_rman包
安装pg_rman缺少包
缺少libpq.so.5()和postgresql10-libs相关的包

[root@localhost lib]# rpm -ivh /tmp/pg_rman-1.3.6-1.pg10.rhel7.x86_64.rpm
error: Failed dependencies:
        libpq.so.5()(64bit) is needed by pg_rman-1.3.6-1.pg10.rhel7.x86_64
        postgresql10-libs is needed by pg_rman-1.3.6-1.pg10.rhel7.x86_64

安装pg相关源

[root@localhost tmp]# rpm -ivh pgdg-redhat10-10-2.noarch.rpm
warning: pgdg-redhat10-10-2.noarch.rpm: Header V4 DSA/SHA1 Signature, key ID 442df0f8: NOKEY
Preparing...                          ################################# [100%]
Updating / installing...
   1:pgdg-redhat10-10-2               ################################# [100%]
[root@localhost yum.repos.d]# pwd
/etc/yum.repos.d
[root@localhost yum.repos.d]# more pgdg-10-redhat.repo
[pgdg10]
name=PostgreSQL 10 $releasever - $basearch
baseurl=https://download.postgresql.org/pub/repos/yum/10/redhat/rhel-$releasever-$basearch
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-PGDG-10
[pgdg10-source]
name=PostgreSQL 10 $releasever - $basearch - Source
failovermethod=priority
baseurl=https://download.postgresql.org/pub/repos/yum/srpms/10/redhat/rhel-$releasever-$basearch
enabled=0
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-PGDG-10
[pgdg10-updates-testing]
name=PostgreSQL 10 $releasever - $basearch
baseurl=https://download.postgresql.org/pub/repos/yum/testing/10/redhat/rhel-$releasever-$basearch
enabled=0
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-PGDG-10
[pgdg10-source-updates-testing]
name=PostgreSQL 10 $releasever - $basearch - Source
failovermethod=priority
baseurl=https://download.postgresql.org/pub/repos/yum/srpms/testing/10/redhat/rhel-$releasever-$basearch
enabled=0
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-PGDG-10

安装postgresql10-libs包

[root@localhost tmp]# yum install postgresql10-libs
Loaded plugins: langpacks, ulninfo
pgdg10                                         | 4.1 kB  00:00:00
(1/2): pgdg10/7Server/x86_64/group_gz          |  245 B  00:00:01
(2/2): pgdg10/7Server/x86_64/primary_db        | 162 kB  00:00:13
Resolving Dependencies
--> Running transaction check
---> Package postgresql10-libs.x86_64 0:10.4-1PGDG.rhel7 will be installed
--> Finished Dependency Resolution
Dependencies Resolved
==========================================================================
 Package                 Arch     Version               Repository   Size
==========================================================================
Installing:
 postgresql10-libs       x86_64   10.4-1PGDG.rhel7      pgdg10      354 k
Transaction Summary
==========================================================================
Install  1 Package
Total download size: 354 k
Installed size: 1.3 M
Is this ok [y/d/N]: y
Downloading packages:
postgresql10-libs-10.4-1PGDG.rhel7.x86_64.rpm      | 354 kB  00:00:02
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Warning: RPMDB altered outside of yum.
  Installing : postgresql10-libs-10.4-1PGDG.rhel7.x86_64      1/1
  Verifying  : postgresql10-libs-10.4-1PGDG.rhel7.x86_64      1/1
Installed:
  postgresql10-libs.x86_64 0:10.4-1PGDG.rhel7
Complete!

安装pg_rman

[root@localhost tmp]# rpm -ivh pg_rman-1.3.6-1.pg10.rhel7.x86_64.rpm
Preparing...                          ################################# [100%]
Updating / installing...
   1:pg_rman-1.3.6-1.pg10.rhel7       ################################# [100%]

查找默认pg_rman安装路径

[root@localhost bin]# find / -name "pg_rman"
/usr/pgsql-10/bin/pg_rman
[root@localhost bin]# cd /usr/pgsql-10/bin
[root@localhost bin]# ls
pg_rman

迁移到pg安装目录中

[root@localhost bin]# mv pg_rman /opt/PostgreSQL/10/bin

pg_rman命令测试

[root@localhost bin]# pg_rman --help
pg_rman manage backup/recovery of PostgreSQL database.
Usage:
  pg_rman OPTION init
  pg_rman OPTION backup
  pg_rman OPTION restore
  pg_rman OPTION show [DATE]
  pg_rman OPTION show detail [DATE]
  pg_rman OPTION validate [DATE]
  pg_rman OPTION delete DATE
  pg_rman OPTION purge
Common Options:
  -D, --pgdata=PATH         location of the database storage area
  -A, --arclog-path=PATH    location of archive WAL storage area
  -S, --srvlog-path=PATH    location of server log storage area
  -B, --backup-path=PATH    location of the backup storage area
  -c, --check               show what would have been done
  -v, --verbose             show what detail messages
  -P, --progress            show progress of processed files
Backup options:
  -b, --backup-mode=MODE    full, incremental, or archive
  -s, --with-serverlog      also backup server log files
  -Z, --compress-data       compress data backup with zlib
  -C, --smooth-checkpoint   do smooth checkpoint before backup
  -F, --full-backup-on-error   switch to full backup mode
                               if pg_rman cannot find validate full backup
                               on current timeline
      NOTE: this option is only used in --backup-mode=incremental or archive.
  --keep-data-generations=NUM keep NUM generations of full data backup
  --keep-data-days=NUM        keep enough data backup to recover to N days ago
  --keep-arclog-files=NUM   keep NUM of archived WAL
  --keep-arclog-days=DAY    keep archived WAL modified in DAY days
  --keep-srvlog-files=NUM   keep NUM of serverlogs
  --keep-srvlog-days=DAY    keep serverlog modified in DAY days
  --standby-host=HOSTNAME   standby host when taking backup from standby
  --standby-port=PORT       standby port when taking backup from standby
Restore options:
  --recovery-target-time    time stamp up to which recovery will proceed
  --recovery-target-xid     transaction ID up to which recovery will proceed
  --recovery-target-inclusive whether we stop just after the recovery target
  --recovery-target-timeline  recovering into a particular timeline
  --hard-copy                 copying archivelog not symbolic link
Catalog options:
  -a, --show-all            show deleted backup too
Delete options:
  -f, --force               forcibly delete backup older than given DATE
Connection options:
  -d, --dbname=DBNAME       database to connect
  -h, --host=HOSTNAME       database server host or socket directory
  -p, --port=PORT           database server port
  -U, --username=USERNAME   user name to connect as
  -w, --no-password         never prompt for password
  -W, --password            force password prompt
Generic options:
  -q, --quiet               don't show any INFO or DEBUG messages
  --debug                   show DEBUG messages
  --help                    show this help, then exit
  --version                 output version information, then exit
Read the website for details. <http://github.com/ossc-db/pg_rman>
Report bugs to <http://github.com/ossc-db/pg_rman/issues>.

PostgreSQL逻辑导出导入

联系:手机/微信(+86 17813235971) QQ(107644445)

标题:PostgreSQL逻辑导出导入

作者:惜分飞©版权所有[未经本人同意,不得以任何形式转载,否则有进一步追究法律责任的权利.]

pg_dump命令说明

C:\Users\Administrator>pg_dump --help
pg_dump 把一个数据库转储为纯文本文件或者是其它格式.
用法:
  pg_dump [选项]... [数据库名字]
一般选项:
  -f, --file=FILENAME          输出文件或目录名
  -F, --format=c|d|t|p         输出文件格式 (定制, 目录, tar)
                               明文 (默认值))
  -j, --jobs=NUM               执行多个并行任务进行备份转储工作
  -v, --verbose                详细模式
  -V, --version                输出版本信息,然后退出
  -Z, --compress=0-9           被压缩格式的压缩级别
  --lock-wait-timeout=TIMEOUT  在等待表锁超时后操作失败
  --no-sync                    do not wait for changes to be written safely to disk
  -?, --help                   显示此帮助, 然后退出
控制输出内容选项:
  -a, --data-only              只转储数据,不包括模式
  -b, --blobs                  在转储中包括大对象
  -B, --no-blobs               exclude large objects in dump
  -c, --clean                  在重新创建之前,先清除(删除)数据库对象
  -C, --create                 在转储中包括命令,以便创建数据库
  -E, --encoding=ENCODING      转储以ENCODING形式编码的数据
  -n, --schema=SCHEMA          只转储指定名称的模式
  -N, --exclude-schema=SCHEMA  不转储已命名的模式
  -o, --oids                   在转储中包括 OID
  -O, --no-owner               在明文格式中, 忽略恢复对象所属者
  -s, --schema-only            只转储模式, 不包括数据
  -S, --superuser=NAME         在明文格式中使用指定的超级用户名
  -t, --table=TABLE            只转储指定名称的表
  -T, --exclude-table=TABLE    不转储指定名称的表
  -x, --no-privileges          不要转储权限 (grant/revoke)
  --binary-upgrade             只能由升级工具使用
  --column-inserts             以带有列名的INSERT命令形式转储数据
  --disable-dollar-quoting     取消美元 (符号) 引号, 使用 SQL 标准引号
  --disable-triggers           在只恢复数据的过程中禁用触发器
  --enable-row-security        启用行安全性(只转储用户能够访问的内容)
  --exclude-table-data=TABLE   不转储指定名称的表中的数据
  --if-exists              当删除对象时使用IF EXISTS
  --inserts                    以INSERT命令,而不是COPY命令的形式转储数据
  --no-publications            do not dump publications
  --no-security-labels         不转储安全标签的分配
  --no-subscriptions           do not dump subscriptions
  --no-synchronized-snapshots  在并行工作集中不使用同步快照
  --no-tablespaces             不转储表空间分配信息
  --no-unlogged-table-data     不转储没有日志的表数据
  --quote-all-identifiers      所有标识符加引号,即使不是关键字
  --section=SECTION            备份命名的节 (数据前, 数据, 及 数据后)
  --serializable-deferrable   等到备份可以无异常运行
  --snapshot=SNAPSHOT          为转储使用给定的快照
  --strict-names               要求每个表和/或schema包括模式以匹配至少一个实体
  --use-set-session-authorization
                               使用 SESSION AUTHORIZATION 命令代替
                ALTER OWNER 命令来设置所有权
联接选项:
  -d, --dbname=DBNAME       对数据库 DBNAME备份
  -h, --host=主机名        数据库服务器的主机名或套接字目录
  -p, --port=端口号        数据库服务器的端口号
  -U, --username=名字      以指定的数据库用户联接
  -w, --no-password        永远不提示输入口令
  -W, --password           强制口令提示 (自动)
  --role=ROLENAME          在转储前运行SET ROLE
如果没有提供数据库名字, 那么使用 PGDATABASE 环境变量
的数值.
报告错误至 <pgsql-bugs@postgresql.org>.
C:\Users\Administrator>

导出环境准备

C:\Users\Administrator>psql -U u_xifenfei -d db_xifenfei
用户 u_xifenfei 的口令:
psql (10.4)
输入 "help" 来获取帮助信息.
db_xifenfei=# create table t_dump as select * from pg_tables;
SELECT 69
db_xifenfei=# insert into t_dump select * from t_dump;
INSERT 0 69
…………
db_xifenfei=# insert into t_dump select * from t_dump;
INSERT 0 565248
db_xifenfei=# create table public.t_dump_pub as select * from t_dump;
SELECT 1130496
db_xifenfei=# select count(*) from t_dump;
  count
---------
 1130496
(1 行记录)
db_xifenfei=# select count(*) from public.t_dump_pub;
  count
---------
 1130496
(1 行记录)

导出命令

pg_dump  -U u_xifenfei -f e:/u_xifenfei.sql db_xifenfei
pg_dump  -U u_xifenfei -f e:/u_xifenfei2.sql --inserts db_xifenfei

psql导入说明

C:\Users\Administrator>psql -?
psql是PostgreSQL 的交互式客户端工具。
使用方法:
  psql [选项]... [数据库名称 [用户名称]]
通用选项:
  -c,--command=命令        执行单一命令(SQL或内部指令)然后结束
 -d, --dbname=数据库名称   指定要连接的数据库 (默认:"Administrator")
  -f, --file=文件名      从文件中执行命令然后退出
  -l, --list             列出所有可用的数据库,然后退出
  -v, --set=, --variable=NAME=VALUE
                           设置psql变量NAME为VALUE
                           (例如,-v ON_ERROR_STOP=1)
  -V, --version            输出版本信息, 然后退出
  -X, --no-psqlrc         不读取启动文档(~/.psqlrc)
  -1 ("one"), --single-transaction
                          作为一个单一事务来执行命令文件(如果是非交互型的)
  -?, --help[=options]     显示此帮助,然后退出
      --help=commands      列出反斜线命令,然后退出
      --help=variables     列出特殊变量,然后退出
输入和输出选项:
  -a, --echo-all          显示所有来自于脚本的输入
  -b, --echo-errors        回显失败的命令
  -e, --echo-queries      显示发送给服务器的命令
 -E, --echo-hidden        显示内部命令产生的查询
  -L, --log-file=文件名  将会话日志写入文件
  -n, --no-readline       禁用增强命令行编辑功能(readline)
  -o, --output=FILENAME 将查询结果写入文件(或 |管道)
  -q, --quiet             以沉默模式运行(不显示消息,只有查询结果)
  -s, --single-step       单步模式 (确认每个查询)
  -S, --single-line        单行模式 (一行就是一条 SQL 命令)
输出格式选项 :
 -A, --no-align           使用非对齐表格输出模式
  -F, --field-separator=STRING
             为字段设置分隔符,用于不整齐的输出(默认:"|")
  -H, --html             HTML 表格输出模式
  -P, --pset=变量[=参数]    设置将变量打印到参数的选项(查阅 \pset 命令)
  -R, --record-separator=STRING
             为不整齐的输出设置字录的分隔符(默认:换行符号)
  -t, --tuples-only      只打印记录i
  -T, --table-attr=文本   设定 HTML 表格标记属性(例如,宽度,边界)
  -x, --expanded           打开扩展表格输出
  -z, --field-separator-zero
                           为不整齐的输出设置字段分隔符为字节0
  -0, --record-separator-zero
                           为不整齐的输出设置记录分隔符为字节0
联接选项:
  -h, --host=主机名        数据库服务器主机或socket目录(默认:"本地接口")
  -p, --port=端口        数据库服务器的端口(默认:"5432")
  -U, --username=用户名    指定数据库用户名(默认:"Administrator")
  -w, --no-password       永远不提示输入口令
  -W, --password           强制口令提示 (自动)
更多信息,请在psql中输入"\?"(用于内部指令)或者 "\help"(用于SQL命令),
或者参考PostgreSQL文档中的psql章节.
臭虫报告至 <pgsql-bugs@postgresql.org>.

导入操作

C:\Users\Administrator>psql -U u_xifenfei -d db_xifenfei
用户 u_xifenfei 的口令:
psql (10.4)
输入 "help" 来获取帮助信息.
db_xifenfei=# create database test_pump;
CREATE DATABASE
C:\Users\Administrator>psql -d test_pump -U u_xifenfei -f e:/u_xifenfei.sql
用户 u_xifenfei 的口令:
SET
SET
SET
SET
SET
 set_config
------------
(1 行记录)
SET
SET
SET
CREATE SCHEMA
ALTER SCHEMA
CREATE EXTENSION
COMMENT
SET
SET
CREATE TABLE
ALTER TABLE
CREATE TABLE
ALTER TABLE
COPY 1130496
COPY 1130496

导出/导入数据核对

C:\Users\Administrator>psql -d test_pump -U u_xifenfei
用户 u_xifenfei 的口令:
psql (10.4)
输入 "help" 来获取帮助信息.
test_pump=# \d
                   关联列表
  架构模式  |    名称    |  类型  |   拥有者
------------+------------+--------+------------
 public     | t_dump_pub | 数据表 | u_xifenfei
 u_xifenfei | t_dump     | 数据表 | u_xifenfei
(2 行记录)

PostgreSQL模式理解

联系:手机/微信(+86 17813235971) QQ(107644445)

标题:PostgreSQL模式理解

作者:惜分飞©版权所有[未经本人同意,不得以任何形式转载,否则有进一步追究法律责任的权利.]

在PostgreSQL中schema和oracle中不一样,在oracle中schema基本上可以理解为user,但是在PostgreSQL中user和schema没有严格意义上的对应关系.
创建模式
这里可以看到使用u_xifenfei创建的schema就是属于该用户,默认的public schema属于postgres用户.

db_xifenfei=# \c
您现在已经连接到数据库 "db_xifenfei",用户 "u_xifenfei".
db_xifenfei=# create schema u_xifenfei;
CREATE SCHEMA
db_xifenfei=# \dn
      架构模式列表
    名称    |   拥有者
------------+------------
 public     | postgres
 u_xifenfei | u_xifenfei
(2 行记录)

数据库检索schema的顺序
默认情况下优先检索和用户名一致的schema,然后是public schema

db_xifenfei=# show search_path;
   search_path
-----------------
 "$user", public
(1 行记录)

测试schema的检索顺序
这里比较明显优先使用/找到的是u_xifenfei schema(和用户名匹配的schema),然后再是默认的public schema

db_xifenfei=# create table t_xifenfei as select * from pg_database;
SELECT 4
db_xifenfei=# select pg_relation_filepath('t_xifenfei');
            pg_relation_filepath
---------------------------------------------
 pg_tblspc/16406/PG_10_201707211/16407/16421
(1 行记录)
db_xifenfei=# select count(*) from t_xifenfei;
 count
-------
     4
(1 行记录)
db_xifenfei=# select schemaname,tablename,tableowner,tablespace
db_xifenfei-# from pg_tables where tableowner='u_xifenfei';
 schemaname |  tablename  | tableowner | tablespace
------------+-------------+------------+------------
 public     | t_xifenfei  | u_xifenfei |
 u_xifenfei | t_xifenfei  | u_xifenfei |
(3 行记录)
--public.t_xifenfei和public.t_xifenfei2昨天创建
db_xifenfei=# select count(*) from public.t_xifenfei;
  count
---------
 1310720
(1 行记录)
db_xifenfei=# drop table t_xifenfei;
DROP TABLE
db_xifenfei=# select count(*) from t_xifenfei;
  count
---------
 1310720
(1 行记录)

PostgreSQL的表空间、数据库、用户之间的关系

联系:手机/微信(+86 17813235971) QQ(107644445)

标题:PostgreSQL的表空间、数据库、用户之间的关系

作者:惜分飞©版权所有[未经本人同意,不得以任何形式转载,否则有进一步追究法律责任的权利.]

玩多了Oracle,习惯了使用Oracle的体系架构去对比别的数据库,今天看PostgreSQL发现两者明显不一样:
1. 在数据库/表空间/schema三者关系上的区别
20180803011116


表空间是物理结构,同一表空间下可以有多个数据库
数据库是逻辑结构,是表/索引/视图/存储过程的集合,一个数据库下可以有多个schema
模式是逻辑结构,是对数据库的逻辑划分
2. 在oracle中用户和schema基本上可以画上等同关系,但是pg中两者没有这样严格的对应关系

相关测试实验
创建用户
在pg中role比user少login,其他基本上相同(也就是说如果给role授权login,等同user)

postgres=# CREATE USER u_xifenfei WITH
postgres-# LOGIN
postgres-# SUPERUSER
postgres-# CREATEDB
postgres-# CREATEROLE
postgres-# INHERIT
postgres-# REPLICATION
postgres-# CONNECTION LIMIT -1
postgres-# PASSWORD 'xifenfei';
CREATE ROLE

创建表空间

postgres=# CREATE TABLESPACE tbs_xifenfei
postgres-#   OWNER u_xifenfei
postgres-#   LOCATION 'D:\Program Files\PostgreSQL\tbs_xifenfei';
CREATE TABLESPACE

创建数据库

postgres=# CREATE DATABASE db_xifenfei
postgres-#     WITH
postgres-#     OWNER = u_xifenfei
postgres-#     ENCODING = 'UTF8'
postgres-#     TABLESPACE = tbs_xifenfei
postgres-#     CONNECTION LIMIT = -1;
CREATE DATABASE

查询数据库和表空间信息

postgres=# select oid, datname, datlastsysoid, dattablespace
postgres-#  from pg_catalog.pg_database order by 1,2;
  oid  |   datname   | datlastsysoid | dattablespace
-------+-------------+---------------+---------------
     1 | template1   |         12937 |          1663
 12937 | template0   |         12937 |          1663
 12938 | postgres    |         12937 |          1663
 16407 | db_xifenfei |         12937 |         16406
(4 行记录)
postgres=# select oid,* from pg_catalog.pg_tablespace;
  oid  |   spcname    | spcowner | spcacl | spcoptions
-------+--------------+----------+--------+------------
  1663 | pg_default   |       10 |        |
  1664 | pg_global    |       10 |        |
 16406 | tbs_xifenfei |    16405 |        |
(3 行记录)

使用u_xifenfei用户登录

C:\Users\Administrator>psql -U u_xifenfei -d db_xifenfei
用户 u_xifenfei 的口令:
psql (10.4)
输入 "help" 来获取帮助信息.
db_xifenfei=# \c
您现在已经连接到数据库 "db_xifenfei",用户 "u_xifenfei".

创建测试表

db_xifenfei=# create table t_xifenfei as select * from pg_database;
SELECT 5
db_xifenfei=# select pg_relation_filepath('t_xifenfei');
            pg_relation_filepath
---------------------------------------------
 pg_tblspc/16406/PG_10_201707211/16407/16408
(1 行记录)
db_xifenfei=# insert into t_xifenfei select * from t_xifenfei;
INSERT 0 5
…………
db_xifenfei=# insert into t_xifenfei select * from t_xifenfei;
INSERT 0 327680
db_xifenfei=# select count(*) from t_xifenfei;
  count
---------
 1310720
(1 行记录)

20180803001342


这里可以发现,创建表空间其实对应的是一个文件夹路径,创建数据库是在对应的表空间中创建相关目录和文件,创建表是对应的相关文件.
参考:PostgreSQL tablespace database schema

PostgreSQL简单操作之—创建库,登录,ddl,dml,help,登出,删除库

联系:手机/微信(+86 17813235971) QQ(107644445)

标题:PostgreSQL简单操作之—创建库,登录,ddl,dml,help,登出,删除库

作者:惜分飞©版权所有[未经本人同意,不得以任何形式转载,否则有进一步追究法律责任的权利.]

PostgreSQL创建数据库
使用shell级别的createdb命令创建xifenfei库

-bash-3.2$ createdb xifenfei

系统认证登录PostgreSQL数据库
使用psql登录PostgreSQL中的xifenfei数据库

-bash-3.2$ psql xifenfei
psql (9.4.4)
Type "help" for help.

PostgreSQL简单查询测试
通过查询版本,当前日期,简单加法等sql语句,测试PostgreSQL中的sql操作

xifenfei=#
xifenfei=# SELECT version();
                                                    version
---------------------------------------------------------------------------------------------------------------
 PostgreSQL 9.4.4 on x86_64-unknown-linux-gnu, compiled by gcc (GCC) 4.1.2 20080704 (Red Hat 4.1.2-55), 64-bit
(1 row)
xifenfei=# SELECT current_date;
    date
------------
 2015-06-21
(1 row)
xifenfei=# SELECT 2 + 2;
 ?column?
----------
        4
(1 row)

PostgreSQL数据库简单ddl和dml测试
通过创建表,插入/更新/删除记录,删除表等操作

xifenfei=# create table t_xifenfei(id int,name varchar(100));
CREATE TABLE
xifenfei=# insert into t_xifenfei values(1,'www.xifenfei.com');
INSERT 0 1
xifenfei=# select * from t_xifenfei;
 id |       name
----+------------------
  1 | www.xifenfei.com
(1 row)
xifenfei=# insert into t_xifenfei values(2,'www.orasos.com');
INSERT 0 1
xifenfei=# select * from t_xifenfei;
 id |       name
----+------------------
  1 | www.xifenfei.com
  2 | www.orasos.com
(2 rows)
xifenfei=# update t_xifenfei set name='WWW.XIFENFEI.COM' WHERE ID=2;
UPDATE 1
xifenfei=#  select * from t_xifenfei;
 id |       name
----+------------------
  1 | www.xifenfei.com
  2 | WWW.XIFENFEI.COM
(2 rows)
xifenfei=# delete from t_xifenfei where id=2;
DELETE 1
xifenfei=# select * from t_xifenfei;
 id |       name
----+------------------
  1 | www.xifenfei.com
(1 row)
xifenfei=# drop table t_xifenfei;
DROP TABLE
xifenfei=# select * from t_xifenfei;
ERROR:  relation "t_xifenfei" does not exist
LINE 1: select * from t_xifenfei;
                      ^

PostgreSQL数据库帮助使用方法
PostgreSQL数据库使用\h命令来查看帮助

xifenfei=# \h
Available help:
  ABORT                            CLUSTER                          DECLARE                          EXPLAIN
  ALTER AGGREGATE                  COMMENT                          DELETE                           FETCH
  ALTER COLLATION                  COMMIT                           DISCARD                          GRANT
  ALTER CONVERSION                 COMMIT PREPARED                  DO                               INSERT
  ALTER DATABASE                   COPY                             DROP AGGREGATE                   LISTEN
  ALTER DEFAULT PRIVILEGES         CREATE AGGREGATE                 DROP CAST                        LOAD
  ALTER DOMAIN                     CREATE CAST                      DROP COLLATION                   LOCK
  ALTER EVENT TRIGGER              CREATE COLLATION                 DROP CONVERSION                  MOVE
  ALTER EXTENSION                  CREATE CONVERSION                DROP DATABASE                    NOTIFY
  ALTER FOREIGN DATA WRAPPER       CREATE DATABASE                  DROP DOMAIN                      PREPARE
  ALTER FOREIGN TABLE              CREATE DOMAIN                    DROP EVENT TRIGGER               PREPARE TRANSACTION
  ALTER FUNCTION                   CREATE EVENT TRIGGER             DROP EXTENSION                   REASSIGN OWNED
  ALTER GROUP                      CREATE EXTENSION                 DROP FOREIGN DATA WRAPPER        REFRESH MATERIALIZED VIEW
  ALTER INDEX                      CREATE FOREIGN DATA WRAPPER      DROP FOREIGN TABLE               REINDEX
  ALTER LANGUAGE                   CREATE FOREIGN TABLE             DROP FUNCTION                    RELEASE SAVEPOINT
  ALTER LARGE OBJECT               CREATE FUNCTION                  DROP GROUP                       RESET
  ALTER MATERIALIZED VIEW          CREATE GROUP                     DROP INDEX                       REVOKE
  ALTER OPERATOR                   CREATE INDEX                     DROP LANGUAGE                    ROLLBACK
  ALTER OPERATOR CLASS             CREATE LANGUAGE                  DROP MATERIALIZED VIEW           ROLLBACK PREPARED
  ALTER OPERATOR FAMILY            CREATE MATERIALIZED VIEW         DROP OPERATOR                    ROLLBACK TO SAVEPOINT
  ALTER ROLE                       CREATE OPERATOR                  DROP OPERATOR CLASS              SAVEPOINT
  ALTER RULE                       CREATE OPERATOR CLASS            DROP OPERATOR FAMILY             SECURITY LABEL
  ALTER SCHEMA                     CREATE OPERATOR FAMILY           DROP OWNED                       SELECT
  ALTER SEQUENCE                   CREATE ROLE                      DROP ROLE                        SELECT INTO
  ALTER SERVER                     CREATE RULE                      DROP RULE                        SET
  ALTER SYSTEM                     CREATE SCHEMA                    DROP SCHEMA                      SET CONSTRAINTS
  ALTER TABLE                      CREATE SEQUENCE                  DROP SEQUENCE                    SET ROLE
  ALTER TABLESPACE                 CREATE SERVER                    DROP SERVER                      SET SESSION AUTHORIZATION
  ALTER TEXT SEARCH CONFIGURATION  CREATE TABLE                     DROP TABLE                       SET TRANSACTION
  ALTER TEXT SEARCH DICTIONARY     CREATE TABLE AS                  DROP TABLESPACE                  SHOW
  ALTER TEXT SEARCH PARSER         CREATE TABLESPACE                DROP TEXT SEARCH CONFIGURATION   START TRANSACTION
  ALTER TEXT SEARCH TEMPLATE       CREATE TEXT SEARCH CONFIGURATION DROP TEXT SEARCH DICTIONARY      TABLE
  ALTER TRIGGER                    CREATE TEXT SEARCH DICTIONARY    DROP TEXT SEARCH PARSER          TRUNCATE
  ALTER TYPE                       CREATE TEXT SEARCH PARSER        DROP TEXT SEARCH TEMPLATE        UNLISTEN
  ALTER USER                       CREATE TEXT SEARCH TEMPLATE      DROP TRIGGER                     UPDATE
  ALTER USER MAPPING               CREATE TRIGGER                   DROP TYPE                        VACUUM
  ALTER VIEW                       CREATE TYPE                      DROP USER                        VALUES
  ANALYZE                          CREATE USER                      DROP USER MAPPING                WITH
  BEGIN                            CREATE USER MAPPING              DROP VIEW
  CHECKPOINT                       CREATE VIEW                      END
  CLOSE                            DEALLOCATE                       EXECUTE
xifenfei-# \h CREATE TABLE AS
Command:     CREATE TABLE AS
Description: define a new table from the results of a query
Syntax:
CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } | UNLOGGED ] TABLE table_name
    [ (column_name [, ...] ) ]
    [ WITH ( storage_parameter [= value] [, ... ] ) | WITH OIDS | WITHOUT OIDS ]
    [ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ]
    [ TABLESPACE tablespace_name ]
    AS query
    [ WITH [ NO ] DATA ]

PostgreSQL退出登录

xifenfei-# \q
-bash-3.2$

PostgreSQL删除数据库

-bash-3.2$ dropdb xifenfei
-bash-3.2$ psql xifenfei
psql: FATAL:  database "xifenfei" does not exist

在linux上安装PostgreSQL 9.4并启动和关闭数据库

联系:手机/微信(+86 17813235971) QQ(107644445)

标题:在linux上安装PostgreSQL 9.4并启动和关闭数据库

作者:惜分飞©版权所有[未经本人同意,不得以任何形式转载,否则有进一步追究法律责任的权利.]

PostgreSQL是以加州大学伯克利分校计算机系开发的 POSTGRES, Version 4.2为基础的对象关系型数据库管理系统(ORDBMS)。POSTGRES开创的许多概念在很久以后才出现在商业数据库中。PostgreSQL是最初伯克利代码的一个开放源码的继承者。它支持大部分SQL标准并且提供了许多其它现代特性:
复杂查询
外键
触发器
可更新的视图
事务完整性
多版本并发控制

另外,PostgreSQL可以用许多方法进行扩展,比如通过增加新的:
数据类型
函数
操作符
聚合函数
索引方法
过程语言
在个人看来,在开源数据库中PostgreSQL 是和ORACLE最相近的一个,和ORACLE兼容性较好,如果去IOE,该数据库是一个不错的选择

操作系统版本

[root@web103 ~]# more /etc/issue
CentOS release 5.9 (Final)
Kernel \r on an \m
[root@web103 ~]# uname -a
Linux web103 2.6.18-348.el5 #1 SMP Tue Jan 8 17:53:53 EST 2013 x86_64 x86_64 x86_64 GNU/Linux

下载对应PostgreSQL对应rpm包
因为操作系统版本为CentOS 5.9的64位Linux,因此下载对应版本prm包,主要下载了server,client,contrib,libs四个包

[root@web103 ~]# mkdir pg
[root@web103 ~]# cd pg
[root@web103 pg]# wget http://yum.postgresql.org/9.4/redhat/rhel-5-x86_64/postgresql94-9.4.4-1PGDG.rhel5.x86_64.rpm
--2015-06-16 20:44:52--  http://yum.postgresql.org/9.4/redhat/rhel-5-x86_64/postgresql94-9.4.4-1PGDG.rhel5.x86_64.rpm
Resolving yum.postgresql.org... 174.143.35.196, 2001:4800:1501:1::196
Connecting to yum.postgresql.org|174.143.35.196|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1807607 (1.7M) [application/x-redhat-package-manager]
Saving to: `postgresql94-9.4.4-1PGDG.rhel5.x86_64.rpm'
100%[===================================================================================================================>] 1,807,607   73.6K/s   in 30s
2015-06-16 20:45:24 (58.1 KB/s) - `postgresql94-9.4.4-1PGDG.rhel5.x86_64.rpm' saved [1807607/1807607]
[root@web103 pg]# wget http://yum.postgresql.org/9.4/redhat/rhel-5-x86_64/postgresql94-server-9.4.4-1PGDG.rhel5.x86_64.rpm
--2015-06-16 20:45:35--  http://yum.postgresql.org/9.4/redhat/rhel-5-x86_64/postgresql94-server-9.4.4-1PGDG.rhel5.x86_64.rpm
Resolving yum.postgresql.org... 174.143.35.196, 2001:4800:1501:1::196
Connecting to yum.postgresql.org|174.143.35.196|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 6175991 (5.9M) [application/x-redhat-package-manager]
Saving to: `postgresql94-server-9.4.4-1PGDG.rhel5.x86_64.rpm'
100%[===================================================================================================================>] 6,175,991   58.5K/s   in 2m 4s
2015-06-16 20:47:42 (48.6 KB/s) - `postgresql94-server-9.4.4-1PGDG.rhel5.x86_64.rpm' saved [6175991/6175991]
[root@web103 pg]# wget http://yum.postgresql.org/9.4/redhat/rhel-5-x86_64/postgresql94-contrib-9.4.4-1PGDG.rhel5.x86_64.rpm
--2015-06-16 20:47:51--  http://yum.postgresql.org/9.4/redhat/rhel-5-x86_64/postgresql94-contrib-9.4.4-1PGDG.rhel5.x86_64.rpm
Resolving yum.postgresql.org... 174.143.35.196, 2001:4800:1501:1::196
Connecting to yum.postgresql.org|174.143.35.196|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 664051 (648K) [application/x-redhat-package-manager]
Saving to: `postgresql94-contrib-9.4.4-1PGDG.rhel5.x86_64.rpm'
100%[===================================================================================================================>] 664,051     28.1K/s   in 53s
2015-06-16 20:48:46 (12.3 KB/s) - `postgresql94-contrib-9.4.4-1PGDG.rhel5.x86_64.rpm' saved [664051/664051]
[root@web103 pg]# wget http://yum.postgresql.org/9.4/redhat/rhel-5-x86_64/postgresql94-libs-9.4.4-1PGDG.rhel5.x86_64.rpm
--2015-06-16 20:51:10--  http://yum.postgresql.org/9.4/redhat/rhel-5-x86_64/postgresql94-libs-9.4.4-1PGDG.rhel5.x86_64.rpm
Resolving yum.postgresql.org... 174.143.35.196, 2001:4800:1501:1::196
Connecting to yum.postgresql.org|174.143.35.196|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 233206 (228K) [application/x-redhat-package-manager]
Saving to: `postgresql94-libs-9.4.4-1PGDG.rhel5.x86_64.rpm'
100%[===================================================================================================================>] 233,206     70.3K/s   in 3.2s
2015-06-16 20:51:16 (70.3 KB/s) - `postgresql94-libs-9.4.4-1PGDG.rhel5.x86_64.rpm' saved [233206/233206]
[root@web103 pg]# ls
postgresql94-9.4.4-1PGDG.rhel5.x86_64.rpm          postgresql94-libs-9.4.4-1PGDG.rhel5.x86_64.rpm
postgresql94-contrib-9.4.4-1PGDG.rhel5.x86_64.rpm  postgresql94-server-9.4.4-1PGDG.rhel5.x86_64.rpm

安装PostgreSQL rpm包

[root@web103 pg]# rpm -ivh *.rpm
warning: postgresql94-9.4.4-1PGDG.rhel5.x86_64.rpm: Header V3 DSA signature: NOKEY, key ID 442df0f8
Preparing...                ########################################### [100%]
   1:postgresql94-libs      ########################################### [ 25%]
   2:postgresql94           ########################################### [ 50%]
   3:postgresql94-contrib   ########################################### [ 75%]
   4:postgresql94-server    ########################################### [100%]

创建PostgreSQL 默认库

[root@web103 pg]# service postgresql-9.4 initdb
Initializing database: [  OK  ]
[root@web103 data]# pwd
/var/lib/pgsql/9.4/data
[root@web103 data]# ls -ltr
total 120
-rw------- 1 postgres postgres 21265 Jun 16 20:52 postgresql.conf
-rw------- 1 postgres postgres    88 Jun 16 20:52 postgresql.auto.conf
drwx------ 3 postgres postgres  4096 Jun 16 20:52 pg_xlog
-rw------- 1 postgres postgres     4 Jun 16 20:52 PG_VERSION
drwx------ 2 postgres postgres  4096 Jun 16 20:52 pg_twophase
drwx------ 2 postgres postgres  4096 Jun 16 20:52 pg_tblspc
drwx------ 2 postgres postgres  4096 Jun 16 20:52 pg_subtrans
drwx------ 2 postgres postgres  4096 Jun 16 20:52 pg_snapshots
drwx------ 2 postgres postgres  4096 Jun 16 20:52 pg_serial
drwx------ 2 postgres postgres  4096 Jun 16 20:52 pg_replslot
drwx------ 4 postgres postgres  4096 Jun 16 20:52 pg_multixact
drwx------ 4 postgres postgres  4096 Jun 16 20:52 pg_logical
-rw------- 1 postgres postgres  1636 Jun 16 20:52 pg_ident.conf
-rw------- 1 postgres postgres  4224 Jun 16 20:52 pg_hba.conf
drwx------ 2 postgres postgres  4096 Jun 16 20:52 pg_dynshmem
drwx------ 2 postgres postgres  4096 Jun 16 20:52 pg_clog
drwx------ 5 postgres postgres  4096 Jun 16 20:52 base
drwx------ 2 postgres postgres  4096 Jun 16 21:16 pg_log
drwx------ 2 postgres postgres  4096 Jun 16 21:16 global
-rw------- 1 postgres postgres    80 Jun 16 21:39 postmaster.pid
-rw------- 1 postgres postgres    59 Jun 16 21:39 postmaster.opts
drwx------ 2 postgres postgres  4096 Jun 16 21:39 pg_stat
drwx------ 2 postgres postgres  4096 Jun 16 21:39 pg_notify
drwx------ 2 postgres postgres  4096 Jun 16 22:00 pg_stat_tmp

另外还可以通过如下两种方式创建

initdb -D /var/lib/pgsql/9.4/data
pg_ctl -D /var/lib/pgsql/9.4/data

设置PostgreSQL 开机自动启动

[root@web103 pg]# chkconfig postgresql-9.4 on
[root@web103 pg]# chkconfig --list|grep post
postgresql-9.4  0:off   1:off   2:on    3:on    4:on    5:on    6:off

查看默认创建PostgreSQL 用户

[root@web103 data]# more /etc/passwd|grep post
postgres:x:26:26:PostgreSQL Server:/var/lib/pgsql:/bin/bash

增加PATH环境变量

-bash-3.2$echo "PATH=$PATH:/usr/pgsql-9.4/bin;export PATH" >>~/.bash_profile

启动PostgreSQL 数据库

--方法1
-bash-3.2$ postgres -D /var/lib/pgsql/9.4/data
----或者
-bash-3.2$ postgres -D /var/lib/pgsql/9.4/data >~/pg.log 2>&1 &
方法2
pg_ctl start -l ~/pg.log -D /var/lib/pgsql/9.4/data

这里如果在环境变量中配置了PGDATA,那-D也可以不指定,-l为指定日志目录,建议使用封装的方法2启动pg

查看PostgreSQL进程信息

[root@web103 data]# ps -ef|grep post|grep -v grep
postgres  4432     1  0 21:39 ?        00:00:00 /usr/pgsql-9.4/bin/postgres -D /var/lib/pgsql/9.4/data
postgres  4433  4432  0 21:39 ?        00:00:00 postgres: logger process
postgres  4435  4432  0 21:39 ?        00:00:00 postgres: checkpointer process
postgres  4436  4432  0 21:39 ?        00:00:00 postgres: writer process
postgres  4437  4432  0 21:39 ?        00:00:00 postgres: wal writer process
postgres  4438  4432  0 21:39 ?        00:00:00 postgres: autovacuum launcher process
postgres  4439  4432  0 21:39 ?        00:00:00 postgres: stats collector process

这里可以看到pg也和oracle有几分类似,有日志进程,checkpoint进程,有写进程等(具体以后分析)

停止PostgreSQL数据库

-bash-3.2$ pg_ctl stop -D /var/lib/pgsql/9.4/data
waiting for server to shut down.... done
server stopped
-bash-3.2$  ps -ef|grep post|grep -v grep
root      6036   499  0 22:07 pts/0    00:00:00 su - postgres
postgres  6037  6036  0 22:07 pts/0    00:00:00 -bash
postgres  6113  6037  0 22:08 pts/0    00:00:00 ps -ef

PostgreSQL默认监听端口
在后续章节中进一步讲解相关配置和访问

[root@web103 pgsql]# netstat -natp|grep postgres
tcp        0      0 127.0.0.1:5432              0.0.0.0:*                   LISTEN      4432/postgres