Chapter 2. Instalación de PostGIS

Table of Contents

En este capítulo se detallan los pasos necesarios para instalar PostGIS .

2.1. Versión corta

Para compilar asumiendo que tiene todas las dependencias en su ruta de búsqueda:

tar -xvzf postgis-3.7.0dev.tar.gz
cd postgis-3.7.0dev
./configure
make
make install

Una vez instalado PostGIS, es necesario habilitarlo (Section 3.3, “Creación de bases de datos espaciales”) o actualizarlo (Section 3.4, “Actualización de bases de datos espaciales”) en cada base de datos individual en la que desee utilizarlo.

2.2. Compilación e instalación desde el código fuente

[Note]

Muchos Sistemas Operativos incluyen ya paquetes precompilados PostgreSQL/PostGIS. En la mayoría de casos no es necesario compilar salvo si quieres las ultimas versiones o haces mantenimiento de paquetes.

This section includes general compilation instructions, if you are compiling for Windows etc or another OS, you may find additional more detailed help at PostGIS User contributed compile guides and PostGIS Dev Wiki.

Pre-Built Packages for various OS are listed in PostGIS Pre-built Packages

Si eres usuario de Windows, puedes obtener versiones estables compiladas via Stackbuilder o el sitio de descargas de PostGIS para Windows También tenemos versiones experimentales para Windows que son publicadas normalmente una o dos veces por semana o cuando ocurre algo interesante. Puedes utilizar éstas para experimentar con las versiones de desarrollo de PostGIS

The PostGIS module is an extension to the PostgreSQL backend server. As such, PostGIS 3.7.0dev requires full PostgreSQL server headers access in order to compile. It can be built against PostgreSQL versions 14 - 18. Earlier versions of PostgreSQL are not supported.

Refer to the PostgreSQL installation guides if you haven't already installed PostgreSQL. https://www.postgresql.org .

[Note]

Para tener compatibilidad con las funcionalidades GEOS, cuando instales PostgreSQL necesitar hacer un enlace explícito con la librería estándar C++:

LDFLAGS=-lstdc++ ./configure [YOUR OPTIONS HERE]

Esta es una solución para falsas excepciones C++ con herramientas de desarrollo antiguas. Prueba este truco si experimentas problemas extraños (backend cerrado inesperadamente o cosas similares). Porc supuesto, será necesario volver a compilar PostgreSQL desde cero.

Los siguientes pasos describen la configuración y compilación del código fuente de PostGIS. Están escritas para usuarios Linux y no funcionarán con Windows o Mac.

2.2.1. Obteniendo el código fuente

Retrieve the PostGIS source archive from the downloads website https://postgis.net/stuff/postgis-3.7.0dev.tar.gz

wget https://postgis.net/stuff/postgis-3.7.0dev.tar.gz
tar -xvzf postgis-3.7.0dev.tar.gz
cd postgis-3.7.0dev

Esto creara un directorio llamado postgis-3.7.0dev en el directorio de trabajo actual.

De forma alternativa se puede obtener el código fuente del git repositorio https://git.osgeo.org/gitea/postgis/postgis/ .

git clone https://git.osgeo.org/gitea/postgis/postgis.git postgis
cd postgis
sh autogen.sh
    

Vaya al nuevo directorio postgis-3.7.0dev creado para continuar con la instalación.

./configure

2.2.2. Install Requirements

PostGIS tiene los siguientes requisitos para compilarlo y usarlo:

Requerido

  • PostgreSQL 14 - 18. A complete installation of PostgreSQL (including server headers) is required. PostgreSQL is available from https://www.postgresql.org 18 .

    For a full PostgreSQL / PostGIS support matrix and PostGIS/GEOS support matrix refer to https://trac.osgeo.org/postgis/wiki/UsersWikiPostgreSQLPostGIS

  • compilador GNU C (gcc). Otros compiladores ANSI C pueden utilizarse para compilar PostGIS, pero encontraremos menos problemas al compilar con gcc.

  • GNU Make (gmake or make). Para muchos sistemas , GNU make es la versión por defecto de make. Para verificar la versión de make podemos ejecutar el siguiente comando make -v. Otras versiones de make pueden no procesar el fichero PostGIS Makefile de forma correcta.

  • Proj reprojection library. Proj 6.1 or above is required. The Proj library is used to provide coordinate reprojection support within PostGIS. Proj is available for download from https://proj.org/ .

  • GEOS geometry library, version 3.8.0 or greater, but GEOS 3.14+ is required to take full advantage of all the new functions and features. GEOS is available for download from https://libgeos.org .

  • LibXML2, version 2.5.x or higher. LibXML2 is currently used in some imports functions (ST_GeomFromGML and ST_GeomFromKML). LibXML2 is available for download from https://gitlab.gnome.org/GNOME/libxml2/-/releases.

  • JSON-C, versión 0.9 o superior. JSON-C se utiliza actualmente para importar GeoJSON a través de la función ST_GeomFromGeoJson. JSON-C puede descargarse de https://github.com/json-c/json-c/releases/.

  • Se prefiere GDAL, versión 3+. Esto es necesario para el soporte raster. https://gdal.org/download.html.

  • Si se compila con PostgreSQL+JIT, se requiere la versión >=6 de LLVM https://trac.osgeo.org/postgis/ticket/4125.

Opcional

  • GDAL (pseudo opcional) solo si no quieres raster puedes dejarlo fuera. También asegúrese de habilitar los controladores que desea utilizar como se describe en Section 3.2, “Configuración del soporte raster”.

  • GTK (GTK+2.0, 2.8+ requerida) para compilar el cargador de shapefiles shp2pgsql-gui. http://www.gtk.org/ .

  • SFCGAL, 1.4.1 or higher is required and 2.1+ is needed to be able to use all functionality. SFCGAL can be used to provide additional 2D and 3D advanced analysis functions to PostGIS cf Chapter 8, SFCGAL Functions Reference. And also allow to use SFCGAL rather than GEOS for some 2D functions provided by both backends (like ST_Intersection or ST_Area, for instance). A PostgreSQL configuration variable postgis.backend allow end user to control which backend he want to use if SFCGAL is installed (GEOS by default). Nota: SFCGAL 1.2 require at least CGAL 4.3 and Boost 1.54 (cf: https://sfcgal.org) https://gitlab.com/sfcgal/SFCGAL/.

  • To enable ST_AsMVT protobuf-c library 1.1.0 or higher (for usage) and the protoc-c compiler (for building) are required. Also, pkg-config is required to verify the correct minimum version of protobuf-c. See protobuf-c. By default, Postgis will use Wagyu to validate MVT polygons faster which requires a c++11 compiler. It will use CXXFLAGS and the same compiler as the PostgreSQL installation. To disable this and use GEOS instead use the --without-wagyu during the configure step.

  • CUnit (CUnit). Se necesita para hacer test de regresión. http://cunit.sourceforge.net/

  • DocBook (xsltproc) es necesario para compilar la documentación. Docbook esta disponible en http://www.docbook.org/ .

  • DBLatex (dblatex) necesario para construir la documentación en formato PDF. DBLatex esta disponible en http://dblatex.sourceforge.net/ .

  • GraphicsMagick (gm convert) is required to generate the images used in the documentation. If GraphicsMagick is unavailable, ImageMagick (convert or magick convert) provides the same command-line syntax. GraphicsMagick is available from http://www.graphicsmagick.org/ and ImageMagick from https://imagemagick.org/ .

2.2.3. Configuración

Como en la gran mayoría de instalaciones Linux, el primer paso es generar el Makefile que se utilizara para compilar el código fuente. Esto se hace ejecutando el script de shell.

./configure

Sin parámetros adicionales, este comando intentara localizar los componentes y librerías necesarios para construir el código fuente PostGIS de forma automática en tu sistema. Aunque este es el uso mas común de ./configure, el script acepta varios parámetros para aquellos que han instalado las librerías y programas en lugares no standard.

La siguiente lista muestra los parámetros utilizados mas comunes. Para obtener una lista completa, puedes utilizar los parámetros --help o --help=short.

--with-library-minor-version

Starting with PostGIS 3.0, the library files generated by default will no longer have the minor version as part of the file name. This means all PostGIS 3 libs will end in postgis-3. This was done to make pg_upgrade easier, with downside that you can only install one version PostGIS 3 series in your server. To get the old behavior of file including the minor version: e.g. postgis-3.0 add this switch to your configure statement.

--prefix=PREFIX

Esta es la localización donde se instalaran las librerías PostGIS y los scripts SQL. Por defecto, esta localización es la misma que la detectada para la instalación PostgreSQL.

[Caution]

Este parámetro está roto actualmente, ya que el paquete sólo se instalará en el directorio de instalación de PostgreSQL. Para seguir avence de este bug visita http://trac.osgeo.org/postgis/ticket/635

--with-pgconfig=FILE

PostgreSQL tiene una herramienta llamada pg_config para activar extensiones como PostGIS o para localizar el directorio de instalación de PostgreSQL. Utiliza este parámetro (--with-pgconfig=/path/to/pg_config) para especificar una instalación personalizada de PostgreSQL de forma manual que PostGIS utilizara para compilar.

--with-gdalconfig=FILE

GDAL, una biblioteca necesaria, proporciona la funcionalidad necesaria para el soporte de raster gdal-config para activar la instalación de software para localizar el directorio de instalación de GDAL. Utilice este parámetro ( - with-gdalconfig = / ruta /a/ gdal config-) para especificar manualmente una instalación de GDAL personalizada que PostGIS utilizara para compilar.

--with-geosconfig=FILE

GEOS, libreria de geometrías requerida, tiene una utilidad llamada geos-config para activar la localización del directorio de instalación del software GEOS. Utiliza este parametro (--with-geosconfig=/path/to/geos-config) para especificar de forma manual una instalación personalizada de GEOS que PostGIS puede utilizar para compilar.

--with-xml2config=FILE

LibXML is the library required for doing GeomFromKML/GML processes. It normally is found if you have libxml installed, but if not or you want a specific version used, you'll need to point PostGIS at a specific xml2-config confi file to enable software installations to locate the LibXML installation directory. Use this parameter (>--with-xml2config=/path/to/xml2-config) to manually specify a particular LibXML installation that PostGIS will build against.

--with-projdir=DIR

Proj4 es una libreria de reproyecciones necesaria de PostGIS. Utiliza el siguiente parametro (--with-projdir=/path/to/projdir) para definir manualmente una instalación personalizada de Proj4 para compilar PostGIS.

--with-libiconv=DIR

Directorio donde iconv esta instalado.

--with-jsondir=DIR

JSON-Ces una libreria con licencia MIT-licensed JSON necesaria para dar soporte a PostGIS ST_GeomFromJSON. Utiliza este parametro (--with-jsondir=/path/to/jsondir) para especificar de forma manual el directorio de instalación personalizado de instalación de JSON-C que PostGIS utilizara para compilar.

--with-gui

Compilar la GUI de importar datos (necesita GTK+2.0). Esto creara una interfaz gráfica shp2pgsql-gui para el comando shp2pgsql.

--without-raster

Compile without raster support.

--without-topology

Compile without topology support.

--with-gettext=no

PostGIS intentara detectar soporte gettext y compilar con el por defecto, de todas formas si existen incompatibilidades que causan errores de carga, se puede desactivar por completo con este comando. Para ver un ejemplo de resolución de problemas configurando en gettext puedes ver el siguiente enlace http://trac.osgeo.org/postgis/ticket/748. NOTA: No te pierdes mucho si desactivas esta opción. Se utiliza principalmente para soporte de ayuda/etiquetas internacionales en la GUI de carga, que actualmente no esta documentada y sigue siendo experimental.

--with-sfcgal=PATH

By default PostGIS will not install with sfcgal support without this switch. PATH is an optional argument that allows to specify an alternate PATH to sfcgal-config.

--without-phony-revision

Disable updating postgis_revision.h to match current HEAD of the git repository.

[Note]

If you obtained PostGIS from the code repository , the first step is really to run the script

./autogen.sh

Este Script generara el script configure que a su vez se utiliza para personalizar la instalación de PostGIS.

Si, por el contrario, as obtenido PostGIS como tarball, ejecutar ./autogen.sh no es necesario ya que ya se ha generado configure.

2.2.4. Compilando

Una vez generado el Makefile, compilar PostGIS es tan simple como ejecutar

make

La ultima linea de salida del terminal debe ser "PostGIS copilado con éxito. Listo para instalar."

All the functions have comments generated from the documentation. If you wish to install these comments into your spatial databases later, run the command which requires docbook. The postgis_comments.sql and other package comment files are also packaged in the tar.gz distribution in the doc folder so no need to make comments if installing from the tar ball. Comments are also included as part of the CREATE EXTENSION install.

make comments

The make cheatsheets target generates html cheat sheets suitable for quick reference or for student handouts. This requires xsltproc to build and will generate 4 files in doc folder topology_cheatsheet.html, raster_cheatsheet.html, postgis_cheatsheet.html

Puedes descargar algunos ya compilados en formato html o pdf en Guias de Estudio PostGIS / PostgreSQL

make cheatsheets

2.2.5. Compilando e Instalando Extensiones de PostGIS

The PostGIS extensions are built and installed automatically when PostgreSQL extension support is available.

Si estas compilando desde el repositorio de código fuente, necesitas compilar primero la función descriptions. Si tienes instaldo docbook ya esta compilado. También puedes compilarla manualmente con la sentencia:

make comments

Compilar los comentarios no es necesario si estas compilando desde un tar ya que están en el paquete pre-compilados con el tar.

Si estas compilando para PostgreSQL 9.1, la extension debería compilarse de forma automática como parte del proceso del comando make install. Si lo necesitas, puedes compilar la extensión desde las carpetas de la extensión o copiar los ficheros en un servidor diferente.

cd extensions
cd postgis
make clean
make
export PGUSER=postgres #overwrite psql variables
make check #to test before install
make install
# to test extensions
make check RUNTESTFLAGS=--extension
[Note]

make check uses psql to run tests and as such can use psql environment variables. Common ones useful to override are PGUSER,PGPORT, and PGHOST. Refer to psql environment variables

Los ficheros de la extension serán siempre los mismos para la misma versión de PostgreSQL independientemente del Sistema Operativo, así que se pueden copiar los ficheros de la extensión de un Sistema Operativo a otro si ya tienes los binarios de PostGIS ya instalados en tus servidores.

Si quieres instalar la extensión de forma manual en un servidor separado de tu servidor de desarrollo, necesitas copiar los siguientes archivos de la carpeta de la extensión en la carpeta PostgreSQL / share / extension de la instalación de PostgreSQL y los binarios normales para PostGIS si no los tienes instalados en el servidor.

  • Estos son los ficheros de control que contienen información como la versión de la extensión a instalar si no lo has especificado. postgis.control, postgis_topology.control.

  • Todos los ficheros en la carpeta /sql de la extension. Estos ficheros deben ser copiados en la raiz de PostgreSQL en la carpeta share/extension extensions/postgis/sql/*.sql, extensions/postgis_topology/sql/*.sql

Once you do that, you should see postgis, postgis_topology as available extensions in PgAdmin -> extensions.

Si estas utilizando psql, puedes verificar que las extensiones están instaladas ejecutando la siguiente sentencia:

SELECT name, default_version, installed_version
FROM pg_available_extensions WHERE name LIKE 'postgis%';

             name             | default_version | installed_version
------------------------------+-----------------+-------------------
 postgis                      | 3.7.0dev         | 3.7.0dev
 postgis_raster               | 3.7.0dev         | 3.7.0dev
 postgis_sfcgal               | 3.7.0dev         |
 postgis_topology             | 3.7.0dev         |
(6 rows)

Si tienes instalada una extension en la base de datos que estas consultando, deberías verla mencionada la columna installed_version. Si la consulta no devuelve ningún registro, significa que no tienes la extension PostGIS instalada en el servidor. PgAdmin III 1.14+ muestra esta información en la sección extensiones en el navegador de bases de datos y permite actualizar o instalar haciendo click derecho.

Si la extension esta disponible, puedes instalar la extension postgis en la base de datos de tu elección utilizando la interfaz de extensiones de pgAdmin o ejecutando la siguiente sentencia:

CREATE EXTENSION postgis;
CREATE EXTENSION postgis_raster;
CREATE EXTENSION postgis_sfcgal;
CREATE EXTENSION postgis_topology;

In psql you can use to see what versions you have installed and also what schema they are installed.

\connect mygisdb
\x
\dx postgis*
List of installed extensions
-[ RECORD 1 ]-------------------------------------------------
Name        | postgis
Version     | 3.7.0dev
Schema      | public
Description | PostGIS geometry, geography, and raster spat..
-[ RECORD 2 ]-------------------------------------------------
Name        | postgis_raster
Version     | 3.0.0dev
Schema      | public
Description | PostGIS raster types and functions
-[ RECORD 3 ]-------------------------------------------------
Name        | postgis_topology
Version     | 3.7.0dev
Schema      | topology
Description | PostGIS topology spatial types and functions
[Warning]

Extension tables spatial_ref_sys, layer, topology can not be explicitly backed up. They can only be backed up when the respective postgis or postgis_topology extension is backed up, which only happens when you back up the whole database. Only srid records not packaged with PostGIS are captured in backups, so don't change the entries we ship and expect the modifications to persist. Put in a ticket if you find an issue. The structures of extension tables are never backed up since they are created with CREATE EXTENSION and assumed to be the same for a given version of an extension. These behaviors are built into the current PostgreSQL extension model.

If you installed 3.7.0dev, without using our wonderful extension system, you can change it to be extension based by running the below commands to package the functions in their respective extension. Installing using `unpackaged` was removed in PostgreSQL 13, so you are advised to switch to an extension build before upgrading to PostgreSQL 13.

CREATE EXTENSION postgis FROM unpackaged;
CREATE EXTENSION postgis_raster FROM unpackaged;
CREATE EXTENSION postgis_topology FROM unpackaged;

2.2.6. Tests

Si quieres hacer un test en la compilación de PostGIS, ejecuta

make check

El comando anterior ejecutará varias comprobaciones y tests de regresión utilizando la librería generada para la version de base de datos PostgreSQL actual.

[Note]

Si ha configurado PostGIS utilizando ubicaciones no estándar de PostgreSQL, GEOS o Proj, puede que necesite añadir sus ubicaciones de biblioteca a la variable de entorno LD_LIBRARY_PATH.

[Caution]

Actualmente, el comando make check une las variables de entorno PATH y PGPORT cundo ejecuta las comprobaciones - no utiliza la version de PostgreSQL especificada utilizando el parametro de configuración --with-pgconfig. Así que hay que estar seguros de modificar la variable de entorno PATH para que apunte a la instalación de PostgreSQL detectada durante la configuración o estar preparado para tener algún que otro dolor de cabeza.

[Note]

Sandboxed build accounts that are not PostgreSQL superusers can delegate database ownership during the regression cycle by exporting POSTGIS_REGRESS_DB_OWNER. The harness will create the temporary regression database owned by the nominated role while continuing to connect using the less privileged account. Combine this with POSTGIS_REGRESS_ROLE_EXT_CREATOR when the extension creation role must differ from the database owner.

These variables allow automated environments to exercise the full upgrade and extension install paths without promoting the calling account to superuser, provided the target PostgreSQL instance permits extension installation by those delegate roles.

If successful, make check will produce the output of almost 500 tests. The results will look similar to the following (numerous lines omitted below):

CUnit - A unit testing framework for C - Version 2.1-3
     http://cunit.sourceforge.net/

  .
  .
  .

Run Summary:    Type  Total    Ran Passed Failed Inactive
              suites     44     44    n/a      0        0
               tests    300    300    300      0        0
             asserts   4215   4215   4215      0      n/a
Elapsed time =    0.229 seconds

  .
  .
  .

Running tests

  .
  .
  .

Run tests: 134
Failed: 0


-- if you build with SFCGAL

  .
  .
  .

Running tests

  .
  .
  .

Run tests: 13
Failed: 0

-- if you built with raster support

  .
  .
  .

Run Summary:    Type  Total    Ran Passed Failed Inactive
              suites     12     12    n/a      0        0
               tests     65     65     65      0        0
             asserts  45896  45896  45896      0      n/a


  .
  .
  .

Running tests

  .
  .
  .

Run tests: 101
Failed: 0

-- topology regress

.
.
.

Running tests

  .
  .
  .

Run tests: 51
Failed: 0

-- if you built --with-gui, you should see this too

     CUnit - A unit testing framework for C - Version 2.1-2
     http://cunit.sourceforge.net/

  .
  .
  .

Run Summary:    Type  Total    Ran Passed Failed Inactive
              suites      2      2    n/a      0        0
               tests      4      4      4      0        0
             asserts      4      4      4      0      n/a

output should look like:

============== dropping database "contrib_regression" ==============
DROP DATABASE
============== creating database "contrib_regression" ==============
CREATE DATABASE
ALTER DATABASE
============== installing fuzzystrmatch               ==============
CREATE EXTENSION
============== installing postgis                     ==============
CREATE EXTENSION
============== running regression test queries        ==============
test test-normalize_address   ... ok

=====================
All 2 tests passed.
=====================

2.2.7. Instalación

Para instalar PostGIS entre

make install

Esto copiará los ficheros de instalación de PostGIS en el subdirectorio especificado por el parámetro de configuración --prefix del comando . En particular:

  • Los archivos binarios de carga y dumper estarán instalados en [prefix]/bin.

  • Los archivos SQL, tal como postgis.sql, están instalados en [prefix]/share/contrib.

  • Las librerías de PostGIS estarán instaladas en [prefix]/lib.

Si has ejecutado el comando make comments previamente para generar los ficheros postgis_comments.sql, raster_comments.sql, instala los ficheros sql ejecutando:

make comments-install

[Note]

postgis_comments.sql, raster_comments.sql, topology_comments.sql han sido separados de la compilación y de la instalación típicos ya que tienen una dependencia extra de la librería xsltproc.

2.3. Common Problems during installation

Hay varias cosas a comprobar cuando la instalación o actualización no han fusionado como se esperaba.

  1. Comprueba que tienes instalado PostgreSQL 14 o posterior, y que estas compilando para esta version de PostgreSQL que estas utilizando. Se pueden producir confusiones cuando tu distribución (Linux)ya tiene instalada PostgreSQL, o has instalado antes PostgreSQL y lo has olvidado. PostGIS solo funcionará con PostgreSQL 14 o superior, y errores inesperados o extraños pueden ocurrir si utilizas una version mas antigua. Para comprobar la version de PostgreSQL que esta instalada y ejecutándose, conectare a la base de datos utilizando psql y ejecuta la siguiente consulta:

    SELECT version();

    Si estas ejecutando una version basada en una distribución RPM, puedes comprobar si existen paquetes pre-instalados utilizando el comando rpm como sigue: rpm -qa | grep postgresql

  2. Si tienes errores en la actualización, asegúrate de que estas restaurando tu base de datos en una que tenga instalada PostGIS.

    SELECT postgis_full_version();

Comprueba que tu configuración detecta la ubicación y la version correctas de PostgreSQL, la librería Proj4 y la librería GEOS.

  1. La salida de configure se utiliza para generar el fichero postgis_config.h. Comprueba que la variables POSTGIS_PGSQL_VERSION, POSTGIS_PROJ_VERSION y POSTGIS_GEOS_VERSION, han sido bien configuradas.