Está en la página 1de 7

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 install postgresql-server postgresql

Grab

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:

# chkconfig postgresql on # /etc/init.d/postgresql start Iniciando la base de datos: Iniciando servicios postgresql: [ [ OK OK ] ]

Grab

Conexin a un servidor PostgreSQL


Para conectarnos al servidor PostgreSQL nos cambiamos al usuario postgres y utilizamos el CLI psql, ejemplo:

# su - postgres $ psql -d template1 -U postgres Welcome to psql 8.1.11, the PostgreSQL interactive terminal.

Type:

\copyright for distribution terms \h for help with SQL commands \? for help with psql commands \g or terminate with semicolon to execute query \q to quit

template1=#

Grab

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:

# netstat -punta | grep LISTEN tcp 0 0 127.0.0.1:5432 0.0.0.0:* LISTEN 15112/postmaster

Grab

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:

# vim /var/lib/pgsql/data/pg_hba.conf host all all 192.168.0.0/24 trust host all all 10.10.0.1/32 trust

Grab

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:

# vim /var/lib/pgsql/data/postgresql.conf listen_addresses='*'

Grab

El ltimo paso es reiniciar el servicio y comprobar que los cambios se han aplicado correctamente:

# /etc/init.d/postgresql restart Parando el servicio postgresql: [ [ OK OK ] ]

Iniciando servicios postgresql:

# netstat -punta | grep LISTEN tcp 0 0 0.0.0.0:5432 0.0.0.0:* LISTEN 15608/postmaster

Grab

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 - postgres $ psql -d template1 -U postgres

template1=# ALTER USER postgres WITH PASSWORD 'zaQ6RzRhFb'; ALTER ROLE

Grab

Comprobar la versin de PostgreSQL instalada


La forma mas cmoda es ejecutando la sentencia SQL SELECT VERSION(), ejemplo:

template1=# SELECT VERSION();

----------------------------------------------------------------------------------------------------------PostgreSQL 8.1.11 on x86_64-redhat-linux-gnu, compiled by GCC gcc (GCC) 4.1.2 20070626 (Red Hat 4.1.2-14) (1 fila)

Grab

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=en_US psql -l List of databases Name | Owner | Encoding

--------------+----------+---------postgres template0 template1 | postgres | UTF8 | postgres | UTF8 | postgres | UTF8

woop_pruebas | postgres | UTF8 (4 rows)

$ pg_dump woop_pruebas > /tmp/woop_pruebas.pg

Grab

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:

$ psql -d woop_pruebas -f /tmp/woop_pruebas.pg SET SET SET COMMENT REVOKE REVOKE GRANT GRANT

Grab

Para hacer un backup de todas las BBDD podemos utilizar el comando pg_dumpall o realizar un pequeo script en BASH, ejemplo:

#!/bin/bash DIR=/var/lib/pgsql/backups LANG=en_US LIST=$(psql -l | awk '{ print $1}' | grep -vE '^-|^List|^Name|template[0|1]|^\(') for db in $LIST do

pg_dump $db | gzip -c > done

$DIR/$db.gz

Grab

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):

add_missing_from = on array_nulls = on backslash_quote = safe_encoding default_with_oids = on escape_string_warning = on standard_conforming_strings = off regex_flavor = advanced sql_inheritance = on

Grab

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.

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 - postgres -bash-3.2$ psql -d template1 -U postgres template1=# SELECT name, setting FROM pg_settings ;

Grab

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:

FATAL: FATAL:

unrecognized configuration parameter "array_nulls" parameter "standard_conforming_strings" cannot be changed

Grab

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":

# autoinstaller --select-release-current --install-component postgresql

Grab

El siguiente paso es activarlo en el inicio del servidor, arrancar el servicio y asignar una contrasea al usuario administrador "postgres" :

# chkconfig postgresql on # /etc/init.d/postgresql start # su - postgres $ psql -d template1 -U postgres template1=# ALTER USER postgres WITH PASSWORD 'password'; ALTER ROLE

Grab

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 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 servicioPostgreSQL.

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 install php-pgsql # /etc/init.d/httpd restart

Grab

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:

could not connect to Ident server at address "127.0.0.1", port 113: Connection refused Ident authentication failed for user "recover"

FATAL:

Grab

La solucin pasa por editar el fichero /var/lib/pgsql/data/pg_hba.conf y cambiar el mtodo de autenticacin:

# vim /var/lib/pgsql/data/pg_hba.conf (..) #host host all all all all 127.0.0.1/32 127.0.0.1/32 ident sameuser md5

Grab

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: 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

# /etc/init.d/postgresql stop # su - postgres $ pg_dump woop_pruebas > /tmp/woop_pruebas.pg $ rm -rf $PGDATA $ initdb $ psql -d woop_pruebas -f /tmp/woop_pruebas.pg # /etc/init.d/postgresql start

Grab

Si tras actualizar una instacia de PostgreSQL no actualizamos el formato de las bases de datos al arrancar nos encontraramos con este error:

An old version of the database format was found. You need to upgrade the data format before using PostgreSQL. See /usr/share/doc/postgresql-8.4.7/README.rpm-dist for more information.

Grab

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.

También podría gustarte