You are on page 1of 10

28/03/12 Administracin y manual de PostgreSQL en Linux

1/10 wiki.woop.es/PostgreSQL
Administracin y manual de PostgreSQL en Linux
Instalacin de PostgreSQL en CentOS
Conexin a un servidor PostgreSQL
Permitir conexiones remotas a PostgreSQL
Modificar la contrasea del usuario postgres de PostgreSQL
Comprobar la versin de PostgreSQL instalada
Backup y restore de bases de datos en PostgreSQL
Activar el modo de compatibilidad con versiones anteriores de PostgreSQL
Instalacin de PostgreSQL en un servidor con Plesk
Conexin a PostgreSQL desde PHP
Actualizar el formato/esquema de las bases de datos PostgreSQL
Instalacin de PostgreSQL en CentOS
Para utilizar el servidor de bases de datos PostgreSQL en CentOS es necesario instalar los paquetes
postgresql y postgresql-server:
yum 1nsfa11 posfgesq1-seve posfgesq1
El paquete postgresql-server contiene los binarios del servidor DBMS, y postgresql las utilidades
cliente para conectarnos a un servidor, as como documentacin en formato HTML y las pginas "man".
El servicio no queda activado en el arranque, as que lo activaremos con la utilidad chkconfig:
# chkconf1g posfgesq1 on
# /efc/1n1f.d/posfgesq1 sfaf
ln1c1ando 1a base de dafos: | Ok ]
ln1c1ando sev1c1os posfgesq1: | Ok ]
Conexin a un servidor PostgreSQL
Para conectarnos al servidor PostgreSQL nos cambiamos al usuario postgres y utilizamos el CLI psql,
ejemplo:

28/03/12 Administracin y manual de PostgreSQL en Linux


2/10 wiki.woop.es/PostgreSQL
# su - posfges
$ psq1 -d femp1afe1 -u posfges
We1come fo psq1 .1.11, fhe Posfge5qL 1nfeacf1ve fem1na1.
1ype: \copy1ghf fo d1sf1buf1on fems
\h fo he1p W1fh 5qL commands
\? fo he1p W1fh psq1 commands
\g o fem1nafe W1fh sem1co1on fo execufe quey
\q fo qu1f
femp1afe1=#
Permitir conexiones remotas a PostgreSQL
Por seguridad, tras una instalacin por defecto de PostgreSQL en CentOS, este aceptar nicamente
conexiones locales en el puerto 5432/tcp:
# nefsfaf -punfa | gep Ll51LN
fcp 0 0 127.0.0.1:5432 0.0.0.0:" Ll51LN 15112/posfmasfe
Para modificar este comportamiento tenemos que editar el fichero
/var/lib/pgsql/data/pg_hba.conf, que contiene la configuracin para la autenticacin de clientes y
aadir el listado de las redes y/o IPs desde las que nos vamos a conectar:
# v1m /va/11b/pgsq1/dafa/pghba.conf
hosf a11 a11 192.16.0.0/24 fusf
hosf a11 a11 10.10.0.1/32 fusf
Adems, tenemos que editar el fichero /var/lib/pgsql/data/postgresql.conf y modificar el
parmetro listen_addresses para indicar que escuche en las interfaces necesarias, en este caso lo
habilitaremos para todas:
# v1m /va/11b/pgsq1/dafa/posfgesq1.conf
11sfenaddesses="
28/03/12 Administracin y manual de PostgreSQL en Linux
3/10 wiki.woop.es/PostgreSQL
El ltimo paso es reiniciar el servicio y comprobar que los cambios se han aplicado correctamente:
# /efc/1n1f.d/posfgesq1 esfaf
Paando e1 sev1c1o posfgesq1: | Ok ]
ln1c1ando sev1c1os posfgesq1: | Ok ]
# nefsfaf -punfa | gep Ll51LN
fcp 0 0 0.0.0.0:5432 0.0.0.0:" Ll51LN 1560/posfmasfe
En este ejemplo, permitimos el acceso a la red 192.168.0.0/24 y a la IP 10.10.0.1, quedando el servicio
postmaster escuchando en todas las interfaces . Para mas informacin consultar el captulo Client
Authentication de la gua de Administracin de PostgreSQL .
Modificar la contrasea del usuario postgres de PostgreSQL
Para cambiar la contrasea de un usuario de PostgreSQL tenemos que utilizar la sentencia SQL ALTER
USER usuario WITH PASSWORD:
# su - posfges
$ psq1 -d femp1afe1 -u posfges
femp1afe1=# AL1Lk u5Lk posfges Wl1h PA55WOkD zaq6kzkhIb
AL1Lk kOLL
Comprobar la versin de PostgreSQL instalada
La forma mas cmoda es ejecutando la sentencia SQL SELECT VERSION(), ejemplo:
femp1afe1=# 5LLLC1 vLk5lON{}
ves1on
-----------------------------------------------------------------------------------------------------------
Posfge5qL .1.11 on x664-edhaf-11nux-gnu, comp11ed by GCC gcc {GCC} 4.1.2 20070626 {ked haf 4.1.2-14}

28/03/12 Administracin y manual de PostgreSQL en Linux
4/10 wiki.woop.es/PostgreSQL
{1 f11a}
Backup y restore de bases de datos en PostgreSQL
En PostgreSQL tenemos el comando pg_dump para realizar copias de seguridad de BBDD, su uso es
muy similar al mysqldump de MySQL. En este ejemplo obtenemos un listado de todas las BBDD
existentes y realizamos el backup de una de ellas:
$ LANG=enu5 psq1 -1
L1sf of dafabases
Name | OWne | Lncod1ng
--------------+----------+----------
posfges | posfges | u1I
femp1afe0 | posfges | u1I
femp1afe1 | posfges | u1I
Wooppuebas | posfges | u1I
{4 oWs}
$ pgdump Wooppuebas > /fmp/Wooppuebas.pg
El resultado es un fichero ASCII con todas las sentencias SQL necesarias para restaurar la BBDD.
Para restaurar una BBDD desde un fichero utilizaremos el comando:
$ psq1 -d Wooppuebas -f /fmp/Wooppuebas.pg
5L1
5L1
5L1
COMMLN1
kLvOkL
kLvOkL
GkAN1
GkAN1
Para hacer un backup de todas las BBDD podemos utilizar el comando pg_dumpall o realizar un
28/03/12 Administracin y manual de PostgreSQL en Linux
5/10 wiki.woop.es/PostgreSQL
pequeo script en BASH, ejemplo:
#!/b1n/bash
Dlk=/va/11b/pgsq1/backups
LANG=enu5 Ll51=${psq1 -1 | aWk { p1nf $1} | gep -vL ^-|^L1sf|^Name|femp1afe|0|1]|^\{}
fo db 1n $Ll51
do
pgdump $db | gz1p -c > $Dlk/$db.gz
done
Activar el modo de compatibilidad con versiones anteriores de
PostgreSQL
Para habilitar la compatibilidad con versiones anteriores de PostgreSQL tenemos que editar el fichero
/var/lib/pgsql/data/postgresql.conf y aadir las siguientes variables (mas informacin en el
captulo Version and Platform Compatibility ):
addm1ss1ngfom = on
aaynu11s = on
backs1ashquofe = safeencod1ng
defau1fW1fho1ds = on
escapesf1ngWan1ng = on
sfandadconfom1ngsf1ngs = off
egexf1avo = advanced
sq11nhe1fance = on
add_missing_from: When on, tables that are referenced by a query will be automatically added
to the FROM clause if not already present. This behavior does not comply with the SQL standard
and many people dislike it because it can mask mistakes (such as referencing a table where you
should have referenced its alias). The default is off. This variable can be enabled for compatibility
with releases of PostgreSQL prior to 8.1, where this behavior was allowed by default.
array_nulls: This controls whether the array input parser recognizes unquoted NULL as
specifying a null array element. By default, this is on, allowing array values containing null values
to be entered. However, PostgreSQL versions before 8.2 did not support null values in arrays, and
therefore would treat NULL as specifying a normal array element with the string value "NULL". For
backwards compatibility with applications that require the old behavior, this variable can be
turned off.

28/03/12 Administracin y manual de PostgreSQL en Linux


6/10 wiki.woop.es/PostgreSQL
backslash_quote: This controls whether a quote mark can be represented by \' in a string
literal. The preferred, SQL-standard way to represent a quote mark is by doubling it ('') but
PostgreSQL has historically also accepted \'. However, use of \' creates security risks because in
some client character set encodings, there are multibyte characters in which the last byte is
numerically equivalent to ASCII \. If client-side code does escaping incorrectly then a SQL-
injection attack is possible. This risk can be prevented by making the server reject queries in
which a quote mark appears to be escaped by a backslash. The allowed values of
backslash_quote are on (allow \' always), off (reject always), and safe_encoding (allow only if
client encoding does not allow ASCII \ within a multibyte character). safe_encoding is the default
setting.
default_with_oids: This controls whether CREATE TABLE and CREATE TABLE AS include an OID
column in newly-created tables, if neither WITH OIDS nor WITHOUT OIDS is specified. It also
determines whether OIDs will be included in tables created by SELECT INTO. In PostgreSQL 8.1
default_with_oids is off by default; in prior versions of PostgreSQL, it was on by default.
escape_string_warning: When on, a warning is issued if a backslash (\) appears in an ordinary
string literal ('...' syntax) and standard_conforming_strings is off. The default is on. Applications
that wish to use backslash as escape should be modified to use escape string syntax (E'...'),
because the default behavior of ordinary strings will change in a future release for SQL
compatibility. This variable can be enabled to help detect applications that will break.
standard_conforming_strings: This controls whether ordinary string literals ('...') treat
backslashes literally, as specified in the SQL standard. The default is currently off, causing
PostgreSQL to have its historical behavior of treating backslashes as escape characters. The
default will change to on in a future release to improve compatibility with the standard.
Applications can check this parameter to determine how string literals will be processed. The
presence of this parameter can also be taken as an indication that the escape string syntax
(E'...') is supported. Escape string syntax should be used if an application desires backslashes to
be treated as escape characters.
regex_flavor: The regular expression "flavor" can be set to advanced, extended, or basic. The
default is advanced. The extended setting might be useful for exact backwards compatibility with
pre-7.4 releases of PostgreSQL.
sql_inheritance: This controls the inheritance semantics. If turned off, subtables are not
included by various commands by default; basically an implied ONLY key word. This was added for
compatibility with releases prior to 7.1.
Podemos comprobar que el cambio de dichas variables de configuracin se ha realizado correctamente
con la siguiente consulta:
# su - posfges
28/03/12 Administracin y manual de PostgreSQL en Linux
7/10 wiki.woop.es/PostgreSQL
-bash-3.2$ psq1 -d femp1afe1 -u posfges
femp1afe1=# 5LLLC1 name, seff1ng IkOM pgseff1ngs
Si al aadir y/o modificar cualquier variable PostgreSQL no arranca tendremos que revisar el fichero de
log /var/lib/pgsql/pgstartup.log para encontrar cualquier warning/error del tipo:
IA1AL: unecogn1zed conf1guaf1on paamefe "aaynu11s"
IA1AL: paamefe "sfandadconfom1ngsf1ngs" cannof be changed
Instalacin de PostgreSQL en un servidor con Plesk
NOTA: Para poder gestionar bases de datos PostgreSQL desde Plesk se necesita comprar el addon
"Power Pack" !!
Una vez comprado el addon, el panel de control Plesk permite la gestin de bases de datos PostgreSQL.
Podemos instalar PostgreSQL en Plesk de dos formas: 1) desde el interfaz web (Home -> Updates ->
PostgreSQL) y 2) desde una shell con el "autoinstaller":
# aufo1nsfa11e --se1ecf-e1ease-cuenf --1nsfa11-componenf posfgesq1
El siguiente paso es activarlo en el inicio del servidor, arrancar el servicio y asignar una contrasea al
usuario administrador "postgres" :
# chkconf1g posfgesq1 on
# /efc/1n1f.d/posfgesq1 sfaf
# su - posfges
$ psq1 -d femp1afe1 -u posfges
femp1afe1=# AL1Lk u5Lk posfges Wl1h PA55WOkD passWod
AL1Lk kOLL
Depus tenemos que entrar al interfaz web (Home -> Database Servers) y configurar el usuario
administrador "postgres" con su contrasea, a partir de aqu podremos gestionar PostgreSQL desde el

28/03/12 Administracin y manual de PostgreSQL en Linux


8/10 wiki.woop.es/PostgreSQL
Plesk. Adems, se instala la herramienta de adminstracin web phpPgAdmin para los clientes junto con
una utilidad muy bsica pg_manage que permite parar, arrancar e reinciar el servicio PostgreSQL.
Conexin a PostgreSQL desde PHP
Para conectarnos a PostgreSQL desde PHP necesitamos instalar el paquete php-pgsql, que
propociona las extensiones pdo_pgsql.so y pgsql.so:
# yum 1nsfa11 php-pgsq1
# /efc/1n1f.d/hffpd esfaf
En una instalacin de PostgreSQL sobre CentOS, el mtodo de autenticacin configurado por defecto es
"ident" (servicio que no est habilitado por defecto), por lo que al conectarnos desde PHP obtendremos
el siguiente error:
LOG: cou1d nof connecf fo ldenf seve af addess "127.0.0.1", pof 113: Connecf1on efused
IA1AL: ldenf aufhenf1caf1on fa11ed fo use "ecove"
La solucin pasa por editar el fichero /var/lib/pgsql/data/pg_hba.conf y cambiar el mtodo de
autenticacin:
# v1m /va/11b/pgsq1/dafa/pghba.conf
{..}
#hosf a11 a11 127.0.0.1/32 1denf sameuse
hosf a11 a11 127.0.0.1/32 md5
Actualizar el formato/esquema de las bases de datos
PostgreSQL
Cuando actualizamos y/o cambiamos de versin un servidor PostgreSQL tenemos que actualizar tambin
el formato/esquema de las bases de datos. En PostgreSQL no existe una herramienta similar al
mysql_upgrade de MySQL que nos automatizara la tarea, por lo que tenemos que realizar una serie de
pasos:
28/03/12 Administracin y manual de PostgreSQL en Linux
9/10 wiki.woop.es/PostgreSQL
1) Backup
2) Borrar/mover el contenido de $PGDATA y volver a inicializar con initdb el nuevo formato de las bases
de datos PostgreSQL
3) Restore
# /efc/1n1f.d/posfgesq1 sfop
# su - posfges
$ pgdump Wooppuebas > /fmp/Wooppuebas.pg
$ m -f $PGDA1A
$ 1n1fdb
$ psq1 -d Wooppuebas -f /fmp/Wooppuebas.pg
# /efc/1n1f.d/posfgesq1 sfaf
Si tras actualizar una instacia de PostgreSQL no actualizamos el formato de las bases de datos al
arrancar nos encontraramos con este error:
An o1d ves1on of fhe dafabase fomaf Was found.
You need fo upgade fhe dafa fomaf befoe us1ng Posfge5qL.
5ee /us/shae/doc/posfgesq1-.4.7/kLADML.pm-d1sf fo moe 1nfomaf1on.
Tip! Si utilizas RHEL/CentOS puedes utilizar el repositorio PowerStack para ejecutar la ltima versin
estable de PostgreSQL.
Referencias sobre PostgreSQL
Comandos bsicos de administracin PostgreSQL , es una traduccin al castellano de 15 practical
PostgreSQL database Administration commands .
Replicacin y alta disponibilidad de PostgreSQL con pgpool-II y Heartbeat .
Powered by Woop!

28/03/12 Administracin y manual de PostgreSQL en Linux


10/10 wiki.woop.es/PostgreSQL

You might also like