quinta-feira, 7 de maio de 2015

Configurando Stream Replication No PostgreSQL 9

Esse tutorial explica como configurar 2 servidores PosgreSQL como master e slave com stream replication, é bem simples.
Cenário:
  • Master 192.168.1.200 (Debian 6 – PostgreSQL 9)
  • Slave 192.168.1.201 (Debian 6 – PostgreSQL 9)
Configuração do Master: 
No arquivo postgresql.conf, alterar as seguintes opções:
listen_address = ‘*’ # Reponderá por qualquer ip cadastrado no server
wal_level = hot_standby
max_wal_senders = 1 # Número maximo de servidores slave
wal_keep_segments = 32
No arquivo pg_hba.conf, adicione o servidor slave para replicação:
host    replication     postgres         192.168.1.201/32        trust
Configuração do Slave 
Criar o arquivo recovery.conf no mesmo diretório do arquivo postgresql.conf, com o seguinte conteúdo:
standby_mode = ‘on’
primary_conninfo = ‘host=192.168.1.200 port=5432 user=postgres’
trigger_file = ‘/tmp/pgsql.trigger’
Parar o PostgreSQL dos 2 servidores:
[postgres@server ~]$ /usr/local/pgsql/bin/pg_ctl stop -D /usr/local/pgsql/data/
[postgres@client ~]$ /usr/local/pgsql/bin/pg_ctl stop -D /usr/local/pgsql/data/
Agora você deverá copiar todo o conteúdo do data do master para o data do slaver:
[postgres@server ~]$ rsync -a -v -e ssh /usr/local/pgsql/data/ 192.168.1.201:/usr/local/pgsql/data/ –exclude postmaster.pid
E no arquivo postgresql.conf do slave, alterar as seguintes opções:
hot_standby = on
Agora você pode iniciar os 2 serviços do PostgreSQL:
[postgres@server ~]$ /usr/local/pgsql/bin/pg_ctl start -D /usr/local/pgsql/data/
[postgres@client ~]$ /usr/local/pgsql/bin/pg_ctl start -D /usr/local/pgsql/data/
Para verificar se a replicação está certa você pode ver assim:
No master:
[postgres@server ~]$ ps ax | grep sender
1573 ?        Ss     0:00 postgres: wal sender process postgres 192.168.1.201(53314) streaming 0/C0000D0
No slave:
[postgres@server ~]$ ps ax | grep receiver
3180 ?        Ss     0:00 postgres: wal receiver process   streaming 0/C0000D0
Testando a replicação:
No master crie uma tabela teste e popule:
postgres=# CREATE TABLE tabelaTeste (valor varchar(30));
postgres=# INSERT INTO tabelaTeste VALUES(‘teste1′);
postgres=# INSERT INTO tabelaTeste VALUES(‘teste2′);
Agora no server slave (stand by) veja se a tabela “tabelaTeste| foi criada:
postgres=# SELECT * FROM tabelaTeste;
Se o resultado for esse abaixo, está correto:
valor
—————
teste1
teste2
(2 rows)

terça-feira, 5 de maio de 2015

COMO RECUPERAR BANCO DO POSTGRES PELO DIRETÓRIO


Pode acontecer de você precisar recuperar um banco de dados Postgres, mas tendo a seu dispor apenas uma cópia de um HD como backup, e não um arquivo de backup gerado com o comando pg_dump

Neste caso, após algumas tentativas, consegui restaurar o banco e compartilho aqui o procedimento que funcionou comigo. Ou seja, recuperação do banco através dos diretórios. 

Antes de tudo, instale no servidor a versão do Postgres idêntica à versão instalada no backup. 

Depois, pare o serviço Postgres. No caso do Debian, onde a dica foi testada, executei: 


# sh /etc/init.d/postgresql stop 

Depois, copie do backup os seguintes diretórios, substituindo os mesmos diretórios no servidor atual. Por exemplo, usando o Postgres 9.3:
  • /var/lib/postgresql/9.3
  • /usr/share/postgresql/9.3
  • /etc/postgresql/9.3

Obs.: recomendo renomear os diretórios originais para "nome-backup", ao invés de simplesmente substituí-los. 

É necessário dar permissão para um diretório, após a cópia para o servidor: 

# chmod 700 /var/lib/postgresql/9.3 -R 

Inicialmente usei "777", mas o próprio sistema informou que era para mudar para 700, quando tentei iniciar o serviço. 

Depois inicie o serviço: 

# sh /etc/init.d/postgresql start 

Pronto! Se tiver o phpPgAdmin instalado, poderá acessá-lo para visualizar o banco, acessando: 

Talvez exista uma forma mais fácil, mas essa foi a que eu encontrei. 

Foi na base do comando find que encontrei os referidos diretórios e fui copiando para o servidor. 

Espero ajudar alguém na mesma situação.
Abraço! 

quinta-feira, 9 de abril de 2015

CRIAÇÃO DE 1° SUPER USUÁRIO NO POSTGRESQL


Depois de instalado seu SGBD postgres, como criar seu 1° usuário? Qual a senha de root? Qual a senha padrão? 

Esta dica é para iniciantes. 

Após a instalação dos seu PostgreSQL no Linux, como criar seu 1° usuário para administração do banco? 

Simples, na máquina com o banco instalado siga os seguintes passos. 

Logue-se como root, tecle "su root" ou "sudo -i" no Ubuntu (no terminal a mensagem padrão deve terminar com #). 

Entre como usuário postgres comando: 

# su postgres 

Conecte no banco comando: 

$ psql 

Agora deve aparecer a frase de boas vindas (Bem vindo ao psql...) e você está no terminal do posgres. 

Entre com o comando: 

CREATE USER nomedousuario SUPERUSER INHERIT CREATEDB CREATEROLE; 

e tecle enter. 

Depois entre com o comando: 

ALTER USER nomedousuario PASSWORD 'senha'; 

e tecle enter. 

Pronto! Usuário criado. 

Agora para este usuário acessar o banco de outras máquinas da rede devemos liberar se acesso no arquivo pg_hba.conf com o usuário root, siga os passos. 

A localização deste arquivo varia segundo a distribuição Linux, no SUSE está em ~postgres/data/pg_hba.conf, no Ubuntu está em/etc/postgres/8.4/pg_hba.conf. Adicione a linha: 

host    all         nomedousuario         0/0                   password

Para que seu usuário tenha acesso de qualquer máquina a todos os bancos de dados neste servidor. 

Feito isso reinicie o postgres ou recarregue como o comando: 

# /etc/init.d/posgresql restart 
ou 
# /etc/init.d/posgresql reload 

segunda-feira, 6 de abril de 2015

INSTALANDO O POSTGRES 9.4 NO RHEL 7

Recentemente precisei instalar um Postgres DB em uma VM RHEL 7 para testes. Aproveitei para compartilhar os passos seguidos aqui no Blog. Esse passo a passo deve funcionar em qualquer Distro RHEL-like: Fedora, Centos, Scientific Linux, OEL, etc.
A instalação é a mais básica possível, pois o propósito desse DB é apenas para testes e laboratórios. Nada de tuning ou personalização.
Instale os seguintes pacotes do repositório Postgresql.org oficial.
[rsoares@rhel7-server-1 ~]$ sudo yum install http://yum.postgresql.org/9.4/redhat/rhel-7-x86_64/pgdg-redhat94-9.4-1.noarch.rpm
[rsoares@rhel7-server-1 ~]$ sudo yum groupinstall "PostgreSQL Database Server 9.4 PGDG"
Inicialize o Postgres DB.
sudo /usr/pgsql-9.4/bin/postgresql94-setup initdb
Habilite e teste o serviço do Postgres.
[rsoares@rhel7-server-1 ~]$ sudo systemctl enable postgresql-9.4.service
[rsoares@rhel7-server-1 ~]$ sudo systemctl start postgresql-9.4.service
[rsoares@rhel7-server-1 ~]$ sudo systemctl stop postgresql-9.4.service
Troque para o usuário de sistema do postgres.
[rsoares@rhel7-server-1 ~]$ sudo su - postgres
Altere o pg_hba.conf (espécie de “firewall” do Postgres) para permitir o acesso externo através da rede da VM.
-bash-4.2$ vim /var/lib/pgsql/9.4/data/pg_hba.conf
# TYPE DATABASE USER ADDRESS METHOD

# "local" is for Unix domain socket connections only
local all all peer
# IPv4 local connections:
host all all 127.0.0.1/32 ident
host all all 192.168.122.0/24 md5
Altere o binding do serviço para aceitar conexões em qualquer endereço IP da VM.
-bash-4.2$ vim /var/lib/pgsql/9.4/data/postgresql.conf
#------------------------------------------------------------------------------
# CONNECTIONS AND AUTHENTICATION
#------------------------------------------------------------------------------

# - Connection Settings -

listen_addresses = '*' # what IP address(es) to listen on;
Logout do postgres user.
Ctrl + D no terminal
Reinicie o serviço postgres
[rsoares@rhel7-server-1 ~]$ sudo systemctl start postgresql-9.4.service
[rsoares@rhel7-server-1 ~]$ sudo systemctl status postgresql-9.4.service
postgresql-9.4.service - PostgreSQL 9.4 database server
Loaded: loaded (/usr/lib/systemd/system/postgresql-9.4.service; enabled)
Active: active (running) since Thu 2014-11-06 17:21:38 BRST; 1s ago
Process: 24832 ExecStop=/usr/pgsql-9.4/bin/pg_ctl stop -D ${PGDATA} -s -m fast (code=exited, status=0/SUCCESS)
Process: 25292 ExecStart=/usr/pgsql-9.4/bin/pg_ctl start -D ${PGDATA} -s -w -t 300 (code=exited, status=0/SUCCESS)
Process: 25286 ExecStartPre=/usr/pgsql-9.4/bin/postgresql94-check-db-dir ${PGDATA} (code=exited, status=0/SUCCESS)
Main PID: 25296 (postgres)
CGroup: /system.slice/postgresql-9.4.service
├─25296 /usr/pgsql-9.4/bin/postgres -D /var/lib/pgsql/9.4/data
├─25297 postgres: logger process
├─25299 postgres: checkpointer process
├─25300 postgres: writer process
├─25301 postgres: wal writer process
├─25302 postgres: autovacuum launcher process
└─25303 postgres: stats collector process
Confira o binding do serviço na porta TCP padrão so Postgres (5432)
[rsoares@rhel7-server-1 ~]$ netstat -tanp
(Not all processes could be identified, non-owned process info
will not be shown, you would have to be root to see it all.)
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN -
tcp 0 0 0.0.0.0:55970 0.0.0.0:* LISTEN -
tcp 0 0 0.0.0.0:111 0.0.0.0:* LISTEN -
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN -
tcp 0 0 127.0.0.1:631 0.0.0.0:* LISTEN -
tcp 0 0 0.0.0.0:5432 0.0.0.0:* LISTEN -
tcp 0 0 192.168.122.65:22 192.168.122.1:39634 ESTABLISHED -
tcp6 0 0 ::1:25 :::* LISTEN -
tcp6 0 0 :::47021 :::* LISTEN -
tcp6 0 0 :::111 :::* LISTEN -
tcp6 0 0 :::22 :::* LISTEN -
tcp6 0 0 ::1:631 :::* LISTEN -
tcp6 0 0 :::5432 :::* LISTEN -
Crie um novo DB User
-bash-4.2$ createuser -d -l -P --interactive NEW_DB_USER
Enter password for new role:
Enter it again:
Shall the new role be a superuser? (y/n) n
Shall the new role be allowed to create more new roles? (y/n) n
Crie um novo Data Base
-bash-4.2$ createdb -e -O NEW_DB_USER NEW_DB "New DataBase"
CREATE DATABASE "NEW_DB" OWNER "NEW_DB_USER";
COMMENT ON DATABASE "NEW_DB" IS 'New DataBase';

quinta-feira, 2 de abril de 2015

Paginando resultados com limit e offset

Neste post, veremos como utilizar o LIMIT e o OFFSET para paginar resultados de uma SQL.
A cláusula LIMIT é utilizada para limitar o número de resultados de uma SQL. Então, se sua SQL retornar 1000 linhas, mas você quer apenas as 10 primeiras, você deve executar uma instrução mais ou menos assim:
1
SELECT coluna FROM tabela LIMIT 10;
Agora, vamos supor que você quer somente os resultados de 11 a 20. Com a instrução OFFSET fica fácil, basta proceder da seguinte forma:
1
SELECT coluna FROM tabela LIMIT 10 OFFSET 10;
O comando OFFSET indica o início da leitura, e o LIMIT o máximo de registros a serem lidos. Para os registros de 61 a 75, por exemplo:
1
SELECT coluna FROM tabela LIMIT 15 OFFSET 60;
Com este recurso, fica fácil paginar os resultados de uma SQL e mostrar ao usuário apenas a página, ao invés de retornar todos os registros da tabela. Uma tabela com 2000 registros, por exemplo, fica muito melhor mostrar ao usuário de 10 em 10, por exemplo, e diminui a carga no banco de dados, melhorando a sua performance.

quarta-feira, 25 de março de 2015

Alterando Tablespace de Tabelas e Indices no PostgreSQL





ALTERANDO AS TABELAS
– Cria TableSpace
CREATE TABLESPACE “banco_data” OWNER postgres LOCATION ‘/postgres/pg825/dados/pg_tblspc/banco_data';
– verifica se as tablespaces foram criadas
SELECT spcname AS “Tablespace”,
pg_size_pretty(pg_tablespace_size (spcname)) AS “Tamanho”,
spclocation as “Caminho”
FROM pg_tableSpace;
– Gera Script para alterar tabelas
SELECT ‘ALTER TABLE’ ,n.nspname AS schemaname,’.’, c.relname AS tablename, ‘SET TABLESPACE banco_data;’
FROM pg_class c
LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
LEFT JOIN pg_tablespace t ON t.oid = c.reltablespace
WHERE c.relkind = ‘r'::”char”
AND nspname NOT IN
(‘dbateste’,’information_schema’,’pg_catalog’,’pg_temp_1′,’pg_toast’,’postgres’,’publico’,’public’)
ORDER BY n.nspname
– Confere alteracao das tabelas
SELECT n.nspname AS schemaname, c.relname AS tablename, t.spcname AS “Tablespace”
FROM pg_class c
LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
LEFT JOIN pg_tablespace t ON t.oid = c.reltablespace
WHERE c.relkind = ‘r'::”char”
AND nspname NOT IN
(‘dbateste’,’information_schema’,’pg_catalog’,’pg_temp_1′,’pg_toast’,’postgres’,’publico’,’public’)
ORDER BY n.nspname, c.relname
– Verifica tabelas sem tablespace
SELECT n.nspname AS schemaname, c.relname AS tablename, t.spcname AS “Tablespace”
FROM pg_class c
LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
LEFT JOIN pg_tablespace t ON t.oid = c.reltablespace
WHERE c.relkind = ‘r'::”char”
AND nspname NOT IN
(‘dbateste’,’information_schema’,’pg_catalog’,’pg_temp_1′,’pg_toast’,’postgres’,’publico’,’public’)
AND t.spcname IS NULL
ORDER BY t.spcname DESC

– Verifica tamanho da tablespace
SELECT spcname AS “Tablespace”,
pg_size_pretty(pg_tablespace_size (spcname)) AS “Tamanho”,
spclocation as “Caminho”
FROM pg_tableSpace;
ALTERANDO OS INDICES
– Cria TableSpace
CREATE TABLESPACE “banco_idx” OWNER postgres LOCATION ‘/postgres/pg825/dados/pg_tblspc/banco_idx';
– verifica se as tablespaces foram criadas
SELECT spcname AS “Tablespace”,
pg_size_pretty(pg_tablespace_size (spcname)) AS “Tamanho”,
spclocation as “Caminho”
FROM pg_tableSpace;
– Verifica quais sao os indices ( Nao primarios) e o tamanho
SELECT n.nspname AS schemaname,c.relname AS tablename,
c.relpages::numeric * 4.096 / 1024::numeric AS espaco_mb
FROM pg_class c
LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
LEFT JOIN pg_tablespace t ON t.oid = c.reltablespace
LEFT JOIN pg_index x ON x.indexrelid = c.oid
WHERE c.relkind = ‘i'::”char”
AND x.indisprimary != ‘t’
AND x.indisunique != ‘t’
AND nspname NOT IN
(‘dbateste’,’information_schema’,’pg_catalog’,’pg_temp_1′,’pg_toast’,’postgres’,’publico’,’public’)
ORDER BY n.nspname
– Gera Script para alterar indices
SELECT ‘ALTER INDEX’, n.nspname AS schemaname , ‘.’ ,c.relname AS tablename, ‘SET TABLESPACE banco_idx;’
FROM pg_class c
LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
LEFT JOIN pg_tablespace t ON t.oid = c.reltablespace
LEFT JOIN pg_index x ON x.indexrelid = c.oid
WHERE c.relkind = ‘i'::”char”
AND x.indisprimary != ‘t’
AND x.indisunique != ‘t’
AND nspname NOT IN
(‘dbateste’,’information_schema’,’pg_catalog’,’pg_temp_1′,’pg_toast’,’postgres’,’publico’,’public’)
ORDER BY n.nspname
– Confere alteracao dos indices
SELECT n.nspname AS schemaname ,c.relname AS tablename,t.spcname AS “Tablespace”
FROM pg_class c
LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
LEFT JOIN pg_tablespace t ON t.oid = c.reltablespace
LEFT JOIN pg_index x ON x.indexrelid = c.oid
WHERE c.relkind = ‘i'::”char”
AND x.indisprimary != ‘t’
AND x.indisunique != ‘t’
AND nspname NOT IN
(‘dbateste’,’information_schema’,’pg_catalog’,’pg_temp_1′,’pg_toast’,’postgres’,’publico’,’public’)
ORDER BY n.nspname
– Verifica indice sem tablespace
SELECT n.nspname AS schemaname ,c.relname AS tablename,t.spcname AS “Tablespace”
FROM pg_class c
LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
LEFT JOIN pg_tablespace t ON t.oid = c.reltablespace
LEFT JOIN pg_index x ON x.indexrelid = c.oid
WHERE c.relkind = ‘i'::”char”
AND x.indisprimary != ‘t’
AND x.indisunique != ‘t’
AND nspname NOT IN
(‘dbateste’,’information_schema’,’pg_catalog’,’pg_temp_1′,’pg_toast’,’postgres’,’publico’,’public’)
AND t.spcname IS NULL
ORDER BY t.spcname DESC

– Verifica tamanho da tablespace
SELECT spcname AS “Tablespace”,
pg_size_pretty(pg_tablespace_size (spcname)) AS “Tamanho”,
spclocation as “Caminho”
FROM pg_tableSpace;

terça-feira, 10 de fevereiro de 2015

Upgrade de PostgreSQL 9.3 para 9.4 (em CentOS 7)

[root@localhost ~]# su - postgres
Last login: Thu Dec 25 04:31:05 EST 2014 on pts/0
-bash-4.2$ pg_dumpall > backup.sql
-bash-4.2$ exit
logout
[root@localhost ~]# wget http://yum.postgresql.org/9.4/redhat/rhel-7-x86_64/pgdg-centos94-9.4-1.noarch.rpm
--2014-12-25 04:33:01--  http://yum.postgresql.org/9.4/redhat/rhel-7-x86_64/pgdg-centos94-9.4-1.noarch.rpm
Resolving yum.postgresql.org (yum.postgresql.org)... 174.143.35.196, 2001:4800:1501:1::196
Connecting to yum.postgresql.org (yum.postgresql.org)|174.143.35.196|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 5328 (5.2K) [application/x-redhat-package-manager]
Saving to: ‘pgdg-centos94-9.4-1.noarch.rpm’

100%[==============================================>] 5,328       --.-K/s   in 0.002s  

2014-12-25 04:33:08 (2.46 MB/s) - ‘pgdg-centos94-9.4-1.noarch.rpm’ saved [5328/5328]

[root@localhost ~]# rpm -ivh pgdg-centos94-9.4-1.noarch.rpm 
Preparing...                          ################################# [100%]
Updating / installing...
   1:pgdg-centos94-9.4-1              ################################# [100%]
[root@localhost ~]# systemctl stop postgresql-9.3
[root@localhost ~]# yum -y install postgresql94 postgresql94-devel postgresql94-contrib postgresql94-libs postgresql94-test postgresql94-server postgresql94-docs
Loaded plugins: fastestmirror
base                                                                                                                                            | 3.6 kB  00:00:00     
extras                                                                                                                                          | 3.4 kB  00:00:00     
pgdg93                                                                                                                                          | 3.6 kB  00:00:00     
pgdg94                                                                                                                                          | 3.6 kB  00:00:00     
updates                                                                                                                                         | 3.4 kB  00:00:00     
Loading mirror speeds from cached hostfile
 * base: mirror.powerhost.cl
 * extras: centos.ufms.br
 * updates: centos.ufms.br
Resolving Dependencies
--> Running transaction check
---> Package postgresql94.x86_64 0:9.4.0-1PGDG.rhel7 will be installed
---> Package postgresql94-contrib.x86_64 0:9.4.0-1PGDG.rhel7 will be installed
---> Package postgresql94-devel.x86_64 0:9.4.0-1PGDG.rhel7 will be installed
---> Package postgresql94-docs.x86_64 0:9.4.0-1PGDG.rhel7 will be installed
---> Package postgresql94-libs.x86_64 0:9.4.0-1PGDG.rhel7 will be installed
---> Package postgresql94-server.x86_64 0:9.4.0-1PGDG.rhel7 will be installed
---> Package postgresql94-test.x86_64 0:9.4.0-1PGDG.rhel7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

====================================================================================
 Package                                        Arch                             Version                                        Repository                        Size
====================================================================================
Installing:
 postgresql94                                   x86_64                           9.4.0-1PGDG.rhel7                              pgdg94                           1.0 M
 postgresql94-contrib                           x86_64                           9.4.0-1PGDG.rhel7                              pgdg94                           601 k
 postgresql94-devel                             x86_64                           9.4.0-1PGDG.rhel7                              pgdg94                           1.6 M
 postgresql94-docs                              x86_64                           9.4.0-1PGDG.rhel7                              pgdg94                            13 M
 postgresql94-libs                              x86_64                           9.4.0-1PGDG.rhel7                              pgdg94                           201 k
 postgresql94-server                            x86_64                           9.4.0-1PGDG.rhel7                              pgdg94                           3.8 M
 postgresql94-test                              x86_64                           9.4.0-1PGDG.rhel7                              pgdg94                           1.3 M

Transaction Summary
==========================================================================================
Install  7 Packages

Total download size: 22 M
Installed size: 72 M
Downloading packages:
(1/7): postgresql94-contrib-9.4.0-1PGDG.rhel7.x86_64.rpm                                                                                        | 601 kB  00:00:02     
(2/7): postgresql94-devel-9.4.0-1PGDG.rhel7.x86_64.rpm                                                                                          | 1.6 MB  00:00:01     
(3/7): postgresql94-9.4.0-1PGDG.rhel7.x86_64.rpm                                                                                                | 1.0 MB  00:00:17     
(4/7): postgresql94-docs-9.4.0-1PGDG.rhel7.x86_64.rpm                                                                                           |  13 MB  00:00:13     
(5/7): postgresql94-libs-9.4.0-1PGDG.rhel7.x86_64.rpm                                                                                           | 201 kB  00:00:00     
(6/7): postgresql94-server-9.4.0-1PGDG.rhel7.x86_64.rpm                                                                                         | 3.8 MB  00:00:04     
(7/7): postgresql94-test-9.4.0-1PGDG.rhel7.x86_64.rpm                                                                                           | 1.3 MB  00:00:05     
---------------------------------------------------------------------------------------
Total                                                                                                                                  933 kB/s |  22 MB  00:00:23     
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : postgresql94-libs-9.4.0-1PGDG.rhel7.x86_64                                                                                                          1/7 
  Installing : postgresql94-9.4.0-1PGDG.rhel7.x86_64                                                                                                               2/7 
  Installing : postgresql94-devel-9.4.0-1PGDG.rhel7.x86_64                                                                                                         3/7 
  Installing : postgresql94-server-9.4.0-1PGDG.rhel7.x86_64                                                                                                        4/7 
  Installing : postgresql94-test-9.4.0-1PGDG.rhel7.x86_64                                                                                                          5/7 
  Installing : postgresql94-contrib-9.4.0-1PGDG.rhel7.x86_64                                                                                                       6/7 
  Installing : postgresql94-docs-9.4.0-1PGDG.rhel7.x86_64                                                                                                          7/7 
  Verifying  : postgresql94-contrib-9.4.0-1PGDG.rhel7.x86_64                                                                                                       1/7 
  Verifying  : postgresql94-test-9.4.0-1PGDG.rhel7.x86_64                                                                                                          2/7 
  Verifying  : postgresql94-9.4.0-1PGDG.rhel7.x86_64                                                                                                               3/7 
  Verifying  : postgresql94-devel-9.4.0-1PGDG.rhel7.x86_64                                                                                                         4/7 
  Verifying  : postgresql94-docs-9.4.0-1PGDG.rhel7.x86_64                                                                                                          5/7 
  Verifying  : postgresql94-server-9.4.0-1PGDG.rhel7.x86_64                                                                                                        6/7 
  Verifying  : postgresql94-libs-9.4.0-1PGDG.rhel7.x86_64                                                                                                          7/7 

Installed:
  postgresql94.x86_64 0:9.4.0-1PGDG.rhel7              postgresql94-contrib.x86_64 0:9.4.0-1PGDG.rhel7         postgresql94-devel.x86_64 0:9.4.0-1PGDG.rhel7         
  postgresql94-docs.x86_64 0:9.4.0-1PGDG.rhel7         postgresql94-libs.x86_64 0:9.4.0-1PGDG.rhel7            postgresql94-server.x86_64 0:9.4.0-1PGDG.rhel7        
  postgresql94-test.x86_64 0:9.4.0-1PGDG.rhel7        

Complete!
[root@localhost ~]# /usr/pgsql-9.4/bin/postgresql94-setup initdb
Initializing database ... OK

[root@localhost ~]# systemctl enable postgresql-9.4
ln -s '/usr/lib/systemd/system/postgresql-9.4.service' '/etc/systemd/system/multi-user.target.wants/postgresql-9.4.service'
[root@localhost ~]# systemctl disable postgresql-9.3
rm '/etc/systemd/system/multi-user.target.wants/postgresql-9.3.service'
[root@localhost ~]# systemctl start postgresql-9.4
[root@localhost ~]# su - postgres
Last login: Thu Dec 25 04:31:31 EST 2014 on pts/0
-bash-4.2$ psql
psql (9.4.0)
Type "help" for help.

postgres=# \q
-bash-4.2$ psql < backup.sql 
SET
SET
SET
ERROR:  role "postgres" already exists
ALTER ROLE
REVOKE
REVOKE
GRANT
GRANT
You are now connected to database "postgres" as user "postgres".
SET
SET
SET
SET
SET
SET
SET
COMMENT
CREATE EXTENSION
COMMENT
REVOKE
REVOKE
GRANT
GRANT
You are now connected to database "template1" as user "postgres".
SET
SET
SET
SET
SET
SET
SET
COMMENT
CREATE EXTENSION
COMMENT
REVOKE
REVOKE
GRANT
GRANT
-bash-4.2$