Table of Contents for
Mastering PostGIS

Version ebook / Retour

Cover image for bash Cookbook, 2nd Edition Mastering PostGIS by Tomasz Nycz Published by Packt Publishing, 2017
  1. Mastering PostGIS
  2. Title Page
  3. Copyright
  4. Credits
  5. About the Authors
  6. About the Reviewers
  7. www.PacktPub.com
  8. Customer Feedback
  9. Table of Contents
  10. Preface
  11. What this book covers
  12. What you need for this book
  13. Who this book is for
  14. Conventions
  15. Reader feedback
  16. Customer support
  17. Downloading the example code
  18. Downloading the color images of this book
  19. Errata
  20. Piracy
  21. Questions
  22. Importing Spatial Data
  23. Obtaining test data
  24. Setting up the database
  25. Importing flat data
  26. Importing data using psql
  27. Importing data interactively
  28. Importing data non-interactively
  29. Importing data using pgAdmin
  30. Extracting spatial information from flat data
  31. Importing shape files using shp2pgsql
  32. shp2pgsql in cmd
  33. The shp2pgsql GUI version
  34. Importing vector data using ogr2ogr
  35. Importing GML
  36. Importing MIF and TAB
  37. Importing KML
  38. ogr2ogr GUI (Windows only)
  39. Importing data using GIS clients
  40. Exporting a shapefile to PostGIS using QGIS and SPIT
  41. Exporting shapefile to PostGIS using QGIS and DbManager
  42. Exporting spatial data to PostGIS from Manifold GIS
  43. Importing OpenStreetMap data
  44. Connecting to external data sources with foreign data wrappers
  45. Connecting to SQL Server Spatial
  46. Connecting to WFS service
  47. Loading rasters using raster2pgsql
  48. Importing a single raster
  49. Importing multiple rasters
  50. Importing data with pgrestore
  51. Summary
  52. Spatial Data Analysis
  53. Composing and decomposing geometries
  54. Creating points
  55. Extracting coordinates from points
  56. Composing and decomposing Multi-geometries
  57. Multi-geometry decomposition
  58. Composing and decomposing LineStrings
  59. LineString composition
  60. LineString decomposition
  61. Composing and decomposing polygons
  62. Polygon composition
  63. Polygon decomposition
  64. Spatial measurement
  65. General warning - mind the SRID!
  66. Measuring distances between two geometries
  67. Measuring the length, area, and perimeter of geometries
  68. Line length
  69. Polygon perimeter
  70. Polygon area
  71. Geometry bounding boxes
  72. Accessing bounding boxes
  73. Creating bounding boxes
  74. Using bounding boxes in spatial queries
  75. Geometry simplification
  76. Geometry validation
  77. Simplicity and validity
  78. Testing for simplicity and validity
  79. Checking for validity
  80. Repairing geometry errors
  81. Validity constraint
  82. Intersecting geometries
  83. Nearest feature queries
  84. Summary
  85. Data Processing - Vector Ops
  86. Primer - obtaining and importing OpenStreetMap data
  87. Merging geometries
  88. Merging polygons
  89. Merging MultiLineStrings
  90. Slicing geometries
  91. Splitting a polygon by LineString
  92. Splitting a LineString with another LineString
  93. Extracting a section of LineString
  94. Buffering and offsetting geometries
  95. Offsetting features
  96. Creating convex and concave hulls
  97. Computing centroids, points-on-surface, and points-on-line
  98. Reprojecting geometries
  99. Spatial relationships
  100. Touching
  101. Crossing
  102. Overlapping
  103. Containing
  104. Radius queries
  105. Summary
  106. Data Processing - Raster Ops
  107. Preparing data
  108. Processing and analysis
  109. Analytic and statistical functions
  110. Vector to raster conversion
  111. Raster to vector conversion
  112. Spatial relationship
  113. Metadata
  114. Summary
  115. Exporting Spatial Data
  116. Exporting data using \COPY in psql
  117. Exporting data in psql interactively
  118. Exporting data in psql non-interactively
  119. Exporting data in PgAdmin
  120. Exporting vector data using pgsql2shp
  121. pgsql2sph command line
  122. pgsql2shp gui
  123. Exporting vector data using ogr2ogr
  124. Exporting KML revisited
  125. Exporting SHP
  126. Exporting MapInfo TAB and MIF
  127. Exporting to SQL Server
  128. ogr2ogr GUI
  129. Exporting data using GIS clients
  130. Exporting data using QGIS
  131. Exporting data using Manifold.
  132. Outputting rasters using GDAL
  133. Outputting raster using psql
  134. Exporting data using the PostgreSQL backup functionality
  135. Summary
  136. ETL Using Node.js
  137. Setting up Node.js
  138. Making a simple Node.js hello world in the command line
  139. Making a simple HTTP server
  140. Handshaking with a database using Node.js PgSQL client
  141. Retrieving and processing JSON data
  142. Importing shapefiles revisited
  143. Consuming JSON data
  144. Geocoding address data
  145. Consuming WFS data
  146. Summary
  147. PostGIS – Creating Simple WebGIS Applications
  148. ExtJS says Hello World
  149. Configuring GeoServer web services
  150. Importing test data
  151. Outputting vector data as WMS services in GeoServer
  152. Outputting raster data as WMS services in GeoServer
  153. Outputting vector data as WFS services
  154. Making use of PgRaster in a simple WMS GetMap handler
  155. Consuming WMS
  156. Consuming WMS in ol3
  157. Consuming WMS in Leaflet
  158. Enabling CORS in Jetty
  159. Consuming WFS in ol3
  160. Outputting and consuming GeoJSON
  161. Consuming GeoJSON in ol3
  162. Consuming GeoJSON in Leaflet
  163. Outputting and consuming TopoJSON
  164. Consuming TopoJSON in ol3
  165. Consuming TopoJSON in Leaflet
  166. Implementing a simple CRUD application that demonstrates vector editing via web interfaces
  167. WebGIS CRUD server in Node.js
  168. WebGIS CRUD client
  169. Layer manager
  170. Drawing tools
  171. Analysis tools - buffering
  172. Summary
  173. PostGIS Topology
  174. The conceptual model
  175. The data
  176. Installation
  177. Creating an empty topology
  178. Importing Simple Feature data into topology
  179. Checking the validity of input geometries
  180. Creating a TopoGeometry column and a topology layer
  181. Populating a TopoGeometry column from an existing geometry
  182. Inspecting and validating a topology
  183. Topology validation
  184. Accessing the topology data
  185. Querying topological elements by a point
  186. Locating nodes
  187. Locating edges
  188. Locating faces
  189. Topology editing
  190. Adding new elements
  191. Creating TopoGeometries
  192. Splitting and merging features
  193. Splitting features
  194. Merging features
  195. Updating edge geometry
  196. Topology-aware simplification
  197. Importing sample data
  198. Topology output
  199. GML output
  200. TopoJSON output
  201. Summary
  202. pgRouting
  203. Installing the pgRouting extension
  204. Importing routing data
  205. Importing shapefiles
  206. Importing OSM data using osm2pgrouting
  207. pgRouting algorithms
  208. All pairs shortest path
  209. Shortest path
  210. Shortest path Dijkstra
  211. A-Star (A*)
  212. K-Dijkstra
  213. K-Shortest path
  214. Turn restrictions shortest path (TRSP)
  215. Driving distance
  216. Traveling sales person
  217. Handling one-way edges
  218. Consuming pgRouting functionality in a web app
  219. Summary

Outputting raster using psql

When you read through the PostGIS documentation carefully, you might find a really short section on using psql to export rasters. Basically, psql does not provide the functionality to easily output binary data, so the approach here is a bit hackish, and relies on the large object support in PostgreSQL (it is worth noting, though, that large object support is considered obsolete in the PgSQL documentation). The steps required to export a raster this way are as follows:

  • Create a large object
  • Output the raster data as bytea
  • Open the large object and write the output bytea
  • Export the large object
  • Unlink it to clean the resources

First, let's make this work in interactive psql mode. Type the following in psql, once connected to our mastering_postgis database:

select 
loid,
lowrite(lo_open(loid, 131072), gtiff) as bytesize
from (
select
lo_create(0) as loid,
ST_AsGDALRaster(rast, 'GTiff') as gtiff
from (
select
ST_Union(rast) as rast
from
data_import.gray_50m_partial
where
filename = 'gray_50m_partial_bl.tif'
) as combined
) as gdal_rasterised;
You should get a similar output to the following:
loid | bytesize
--------+----------
145707 | 14601978
(1 row)
If you happen to get errors mentioning the GDAL driver's loading problems, try enabling it by using SET postgis.gdal_enabled_drivers = 'ENABLE_ALL';.

Once you know your large object identifier, you can export it:

\lo_export 145707 'F:/mastering_postgis/chapter06/gray_50m_partial_bl_psql_interactive.tif'

The output will just be the following:

lo_export

Finally, we'll release the large object storage:

SELECT lo_unlink(145707);

The output should be as follows:

lo_unlink
-----------
1
(1 row)

I am purposefully not explaining the preceding code in detail because we will use its variation to perform the very same operation in one go. To do this, we can put the previous code into one SQL (you'll find the code in the chapter resources):

--Step 1: prepare the data for export 
-------------------------------------
--Note: read this query starting at the inner most sql

--4. store the metadata in a temp table, so it can be used later to drive the xport;
drop table if exists data_export.psql_export_temp_tbl;
create table data_export.psql_export_temp_tbl as
--3. open large object for writing, and write to it the GeoTiff data prepared at lvl 2
select
loid,
lowrite(lo_open(loid, 131072), gtiff) as bytesize --pen large object in wrtie mode, write gtiff data to it; write outputs the byte size
--note: 131072 is a decimal value of the INV_WRITE flag hex value of 0x00020000 (see libpq-fs.h for details)
from (
--2. create a large object, so it can be written to later and prepare GeoTiff binary data
select
lo_create(0) as loid, --note the param here is 'mode' which is unused and ignored as of pgsql 8.1 but left for backwards compatibility
ST_AsGDALRaster(rast, 'GTiff') as gtiff
from (
--1. extract the gray_50m_partial_bl raster tiles and union them back into one raster
select
ST_Union(rast) as rast
from
data_import.gray_50m_partial
where
filename = 'gray_50m_partial_bl.tif'
) as combined
) as gdal_rasterised;

--step 2: export the data
-------------------------
select lo_export((select loid from data_export.psql_export_temp_tbl limit 1), 'F:\mastering_postgis\chapter06\gray_50m_partial_bl.tif');


--step 3: cleanup, cleanup, everybody cleanup...
------------------------------------------------
--release large object resources
select lo_unlink((select loid from data_export.psql_export_temp_tbl limit 1));
--drop temp table
drop table data_export.psql_export_temp_tbl;

The preceding code uses a temporary table to save some large object data, most importantly the large object identifier that is next used to perform the actual export and cleanup. This is because otherwise we would not be able to access the large file by its ID, and the export function would fail.

You can now execute the code in psql:

psql -h localhost -p 5434 -U postgres -d mastering_postgis -f psql_export_raster.sql

The output should be similar to the following:

DROP TABLE
SELECT 1
lo_export
-----------
1
(1 row)

lo_unlink
-----------
1
(1 row)

DROP TABLE

Obviously, the very same code could be executed in PgAdmin too.

Use ST_GDALDrivers() to get a list of the supported drivers, should you wish to export to other formats.
We have not only done some hocus-pocus to export a raster off our PostGIS database; we have also used a PostGIS ST_AsGDALRaster function to output a raster to a desired format.