<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Linfiniti Geo Blog &#187; Postgres &amp; PostGIS</title>
	<atom:link href="http://linfiniti.com/category/postgis/feed/" rel="self" type="application/rss+xml" />
	<link>http://linfiniti.com</link>
	<description>GIS for Open Source People</description>
	<lastBuildDate>Sat, 24 Jul 2010 20:24:42 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Automated backup of multiple PostgreSQL/PostGIS databases</title>
		<link>http://linfiniti.com/2010/05/automated-backup-of-multiple-postgresqlpostgis-databases/</link>
		<comments>http://linfiniti.com/2010/05/automated-backup-of-multiple-postgresqlpostgis-databases/#comments</comments>
		<pubDate>Sat, 01 May 2010 23:00:26 +0000</pubDate>
		<dc:creator>Tim Sutton</dc:creator>
				<category><![CDATA[Postgres & PostGIS]]></category>

		<guid isPermaLink="false">http://linfiniti.com/?p=456</guid>
		<description><![CDATA[I have a cron job that backs up my PG databases and emails them to me everynight. Today I wanted to upgrade my PostgreSQL 8.3 databases to PG 8.4 so I made a few modifications to my script so that I could dump out my PG data, and then restore it under PG 8.4. In [...]]]></description>
			<content:encoded><![CDATA[<p>I have a cron job that backs up my PG databases and emails them to me everynight. Today I wanted to upgrade my PostgreSQL 8.3 databases to PG 8.4 so I made a few modifications to my script so that I could dump out my PG data, and then restore it under PG 8.4. In case you are wondering I am doing this because Ubuntu Lucid now ships with PG 8.4 (yay!). I also made the script generate another script to restore the databases. So basically the procedure is to run the script below on your 8.3 cluster, shut that down and bring up your 8.4 cluster, and then restore your databases into that. Here follows my little script:</p>
<pre>
MYDATE=`date +%d-%B-%Y`
MYBACKUPDIR=/home/timlinux/sql_backups
MYRECIPIENT=tim@linfiniti.com

DBLIST=`psql -l \
  | awk '{print $1}' | grep -v "+" | grep -v "Name" | \
  grep -v "List" | grep -v "(" | grep -v "template" | \
  grep -v "postgres"`
for DB in ${DBLIST}
do
  echo "Backing up $DB"
  FILENAME=${MYBACKUPDIR}/PG_${DB}.${MYDATE}.sql.tar.gz
  pg_dump -f ${FILENAME} -x -O -F tar ${DB}
  #If you want to email the database uncomment
  #below (will cause issues if backups are large)
  #mpack -s "Daily $DB PG backup for ${MYDATE}" $FILENAME $MYRECIPIENT
done

echo "Procedure to restore one of your backups:"
echo "createdb <dbname>"
echo "pg_restore -F t <backupname>.sql.tar.gz |psql <dbname>"
echo "Or to restore in a batch make a script like this:"
echo "for FILE in /home/timlinux/sql_backups/*; do DB=\$(echo $FILE | \"
echo "  sed 's\/home\/timlinux\/sql_backups\/PG_//g' | sed 's/.${MYDATE}.sql.tar.gz//g'); "
echo " 'Restoring: \$DB'; createdb \$DB; pg_restore -F t \$FILE |psql \$DB; done"
</pre>
<p><b>Update 02 May 2010</b> Uncommented pg_dump line which was inadvertantly commented in my original post.</p>
<img src="http://linfiniti.com/wp-content/plugins/pixelstats/trackingpixel.php?post_id=456&amp;ts=1280627146" style="display:none;" alt="pixelstats trackingpixel"/>]]></content:encoded>
			<wfw:commentRss>http://linfiniti.com/2010/05/automated-backup-of-multiple-postgresqlpostgis-databases/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Dissolving features by an attribute</title>
		<link>http://linfiniti.com/2010/02/dissolving-features-by-an-attribute/</link>
		<comments>http://linfiniti.com/2010/02/dissolving-features-by-an-attribute/#comments</comments>
		<pubDate>Wed, 17 Feb 2010 09:39:08 +0000</pubDate>
		<dc:creator>samantha</dc:creator>
				<category><![CDATA[Postgres & PostGIS]]></category>

		<guid isPermaLink="false">http://linfiniti.com/?p=304</guid>
		<description><![CDATA[Hi, I&#8217;m Sam. I&#8217;ve been learning a lot here at Linfiniti (thanks to the brilliant team!) Just like to add a quick note on one of the tasks I learnt this week. I was working on a shapefile of the suburbs in Cape Town. A client required the suburbs to be grouped by region. After [...]]]></description>
			<content:encoded><![CDATA[<p><!-- 		@page { margin: 0.79in } 		P { margin-bottom: 0.08in } -->Hi, I&#8217;m Sam. I&#8217;ve been learning a lot here at Linfiniti (thanks to the brilliant team!)  Just like to add a quick note on one of the tasks I learnt this week.</p>
<p>I was working on a shapefile of the suburbs in Cape Town.  A client required the suburbs to be grouped by region.  After the tedious part of manually grouping the suburbs (using a created field, REGION), the unioning (dissolving) of the suburbs proved to be quick and painless through PostgreSQL, using this SQL command that implements the geomunion function:</p>
<pre>create table ct_regions as select geomunion(the_geom), "REGION" \
 from "ct_suburbs" group by "REGION";</pre>
<p>“ct_suburbs” is the original shapefile that was loaded into the PostGIS database using the Quantum GIS &#8216;SPIT&#8217; plugin. “REGION” is the class (attribute) that I wish to union by.  And ct_regions will be the output shapefile. See the result here:</p>
<p>Before dissolving (ct_suburbs shows suburbs)</p>
<p><a href="http://linfiniti.com/wp-content/uploads/2010/02/before.png"><img class="alignnone size-medium wp-image-310" title="Cape Town suburbs before dissolving" src="http://linfiniti.com/wp-content/uploads/2010/02/before-265x300.png" alt="Cape Town suburbs before dissolving" width="265" height="300" /></a></p>
<p>After dissolving by suburbs (ct_regions shows collections of suburbs that have been merged)</p>
<p><a href="http://linfiniti.com/wp-content/uploads/2010/02/after.png"><img class="alignnone size-medium wp-image-311" title="Cape Town suburbs after dissolving" src="http://linfiniti.com/wp-content/uploads/2010/02/after-258x300.png" alt="Cape Town suburbs after dissolving" width="258" height="300" /></a></p>
<p style="text-align: justify;">Hopefully this will be of some use when it comes to your own mapping!</p>
<img src="http://linfiniti.com/wp-content/plugins/pixelstats/trackingpixel.php?post_id=304&amp;ts=1280627146" style="display:none;" alt="pixelstats trackingpixel"/>]]></content:encoded>
			<wfw:commentRss>http://linfiniti.com/2010/02/dissolving-features-by-an-attribute/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Getting up and running with PostGIS in a jiffy</title>
		<link>http://linfiniti.com/2009/11/getting-up-and-running-with-postgis-in-a-jiffy/</link>
		<comments>http://linfiniti.com/2009/11/getting-up-and-running-with-postgis-in-a-jiffy/#comments</comments>
		<pubDate>Sat, 28 Nov 2009 12:36:46 +0000</pubDate>
		<dc:creator>Tim Sutton</dc:creator>
				<category><![CDATA[Postgres & PostGIS]]></category>

		<guid isPermaLink="false">http://linfiniti.com/?p=248</guid>
		<description><![CDATA[I&#8217;ve posted this before on my old blog so this is a repeat for those looking to get going with PostGIS in a hurry. This procedure should work on Ubuntu Jaunty or Ubuntu Karmic and possibly earlier versions. sudo apt-get install postgresql-8.3-postgis sudo su - postgres createuser -s -d -r -l -P -E timlinux createdb [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve posted this before on my old blog so this is a repeat for those looking to get going with PostGIS in a hurry. This procedure should work on Ubuntu Jaunty or Ubuntu Karmic and possibly earlier versions.</p>
<pre>
sudo apt-get install postgresql-8.3-postgis
sudo su - postgres
createuser -s -d -r -l -P -E timlinux
createdb gis
createlang plpgsql gis
psql gis < /usr/share/postgresql-8.3-postgis/lwpostgis.sql
psql gis < /usr/share/postgresql-8.3-postgis/spatial_ref_sys.sql
</pre>
<p>Having done that, you should be able to connect to the database by creating a new postgis connection in QGIS. After that you can start to load data into your spatial database using SPIT (QGIS plugin to import shapefiles into QGIS) or the shp2psql command line tool.</p>
<img src="http://linfiniti.com/wp-content/plugins/pixelstats/trackingpixel.php?post_id=248&amp;ts=1280627146" style="display:none;" alt="pixelstats trackingpixel"/>]]></content:encoded>
			<wfw:commentRss>http://linfiniti.com/2009/11/getting-up-and-running-with-postgis-in-a-jiffy/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Clipping data from Postgis</title>
		<link>http://linfiniti.com/2009/09/clipping-data-from-postgis/</link>
		<comments>http://linfiniti.com/2009/09/clipping-data-from-postgis/#comments</comments>
		<pubDate>Tue, 29 Sep 2009 22:44:37 +0000</pubDate>
		<dc:creator>Tim Sutton</dc:creator>
				<category><![CDATA[Postgres & PostGIS]]></category>

		<guid isPermaLink="false">http://linfiniti.com/?p=183</guid>
		<description><![CDATA[So you have moved your spatial data into PostGIS and everything is great&#8230;.until you start wanting to clip it out again. Luckily clipping data within the postgres environment is trivial with the little help of SQL. However I wanted something a little more fancy &#8211; a way to iterate through all my spatial tables and [...]]]></description>
			<content:encoded><![CDATA[<p>So you have moved your spatial data into PostGIS and everything is great&#8230;.until you start wanting to clip it out again. Luckily clipping data within the postgres environment is trivial with the little help of SQL. However I wanted something a little more fancy &#8211; a way to iterate through all my spatial tables and clip out an arbitary polygon, saving the result to a shapefile. To achieve this I wrote a little bash script that does just that. The script will also optionally make sql dumps of the data and clean up after itself when it is done. </p>
<p>The SUFFIX option is used to append to the newly created shapefile / table / sqldump file.<br />
The CLIPTABLE is the table containing polygons that should be used to intersect each table.<br />
The CLIPFIELD is a field used to subset the cliptable e.g. to select a single polygon only.<br />
The CLIPGEOMFIELD is the name of the geometry field in the CLIPTABLE.<br />
The CLIPFIELDVALUE is the clipfield &#8216;where&#8217; clause e.g. &#8220;Eastern Cape&#8221;<br />
The DB is the database containing tables to be intersected.</p>
<p>If you set DELETETABLE to 0, it will create clip tables in the database with the suffix you specify.<br />
If you set DELETEGEOM to 1 it will delete the original geometry, leaving only the intersected geometry.<br />
If you set SHPDUMP to 1 it iwll create a shapefile for each intersected table.<br />
If you set SQLDUMP to 1 it will make a sql dump file of each intersected table.</p>
<p>Note that for large dataset, clipping with an arbitary polygon can take a long time! Here is the script:</p>
<pre>
#!/bin/bash
SUFFIX="ecape"
CLIPTABLE="ecape"
CLIPFIELD="provname"
CLIPGEOMFIELD="the_geom"
CLIPFIELDVALUE="Eastern Cape"
DB="cdsm50k"
DELETETABLE=1
DELETEGEOM=1
SHPDUMP=1
SQLDUMP=0
pushd .
cd /tmp

for TABLE in `echo "\dt" | psql $DB \
    | awk '{print $3}' | grep "^[a-zA-Z]"`

do
  GEOMFIELD=`echo "\d $TABLE" | psql $DB | grep "geometry" \
  | grep -v "geometrytype" |awk '{print $1}'`
  if [ "$GEOMFIELD" == "" ]
  then
    echo "$TABLE has no geometry column, skipping"
  else
    echo "$TABLE -> $GEOMFIELD"
    echo "drop table \"${TABLE}_${SUFFIX}\";" | psql $DB
    # Note we use the &#038;&#038; bounding box query first and
    # then the intersects query to avoid unneeded comparison of
    # complex geometries.
    SQL="CREATE TABLE \"${TABLE}_${SUFFIX}\" AS \
            SELECT \
            ST_Intersection(v.$GEOMFIELD, m.$CLIPGEOMFIELD) AS intersection_geom, \
            v.*, \
            m.$CLIPFIELD \
            FROM \
              \"$TABLE\" v, \
              $CLIPTABLE m \
            WHERE \
              ST_Intersects(v.$GEOMFIELD, m.$CLIPGEOMFIELD) AND \
              $CLIPFIELD='$CLIPFIELDVALUE';"

    echo $SQL  | psql $DB

    if [ $DELETEGEOM -eq 1 ]
    then
      echo "alter table \"${TABLE}_${SUFFIX}\" drop column $GEOMFIELD;" | psql $DB
    fi

    if [ $SHPDUMP -eq 1 ]
    then
      pgsql2shp -f ${TABLE}.shp -g "intersection_geom" $DB ${TABLE}_${SUFFIX}
    fi

    if [ $SQLDUMP -eq 1 ]
    then
      pg_dump -D $DB -t ${TABLE}_${SUFFIX} > ${TABLE}_${SUFFIX}.sql
    fi  

    if [ $DELETETABLE -eq 1 ]
    then
      echo "drop table ${TABLE}_${SUFFIX};" | psql $DB
    fi
  fi
done
echo "vacuum analyze;" | psql $DB
popd
</pre>
<img src="http://linfiniti.com/wp-content/plugins/pixelstats/trackingpixel.php?post_id=183&amp;ts=1280627146" style="display:none;" alt="pixelstats trackingpixel"/>]]></content:encoded>
			<wfw:commentRss>http://linfiniti.com/2009/09/clipping-data-from-postgis/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>EAV Database Modelling</title>
		<link>http://linfiniti.com/2009/08/eav-database-modelling/</link>
		<comments>http://linfiniti.com/2009/08/eav-database-modelling/#comments</comments>
		<pubDate>Thu, 27 Aug 2009 05:30:57 +0000</pubDate>
		<dc:creator>Tim Sutton</dc:creator>
				<category><![CDATA[Postgres & PostGIS]]></category>

		<guid isPermaLink="false">http://linfiniti.com/?p=133</guid>
		<description><![CDATA[Sometimes just because a thing is possible doesn&#8217;t make it a good idea. In the last week I have been helping a client whose web developer has dissapeared. The developer implemented the database using a variation on the Entity Attribute Value (EAV) modelling paradigm. The database consists of only four tables: Entities, Attributes, Values, EntityTypes. [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes just because a thing is possible doesn&#8217;t make it a good idea. In the last week I have been helping a client whose web developer has dissapeared. The developer implemented the database using a variation on the <a href="http://en.wikipedia.org/wiki/Entity-attribute-value_model">Entity Attribute Value (EAV)</a> modelling paradigm. The database consists of only four tables: Entities, Attributes, Values, EntityTypes. So the entities in the database don&#8217;t match any real-world entities &#8211; there is no products table for products, no categories table for categories and so on. This generic modelling approach might sound good but in practice it&#8217;s a real pain. Look at this query diagram representing a simple query to find out what categories exist in the database:</p>
<p><a href="http://www.flickr.com/photos/38241992@N06/3861513480/" title="EAVDBModel by linfiniti.com, on Flickr"><img src="http://farm3.static.flickr.com/2626/3861513480_8ce4f83e79_o.png" width="496" height="351" alt="EAVDBModel" /></a></p>
<p>The query consists of numerous joins and is completely opaque. The EAV wikipedia article I referenced above contains a list of downsides to the EAV approach, with which I can only concur. For a new developer approach an EAV implementation its an uphill battle to understand what is going on. Writing queries is a cumbersome task, and the logic such as foreign key constraints that would normally reside in the database layer now needs to be implemented in the application codebase.</p>
<p>For me EAV is something I will be avoiding in any new developments I embark on&#8230;</p>
<img src="http://linfiniti.com/wp-content/plugins/pixelstats/trackingpixel.php?post_id=133&amp;ts=1280627146" style="display:none;" alt="pixelstats trackingpixel"/>]]></content:encoded>
			<wfw:commentRss>http://linfiniti.com/2009/08/eav-database-modelling/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Automatically dumping all Postgres tables into their own SQL files</title>
		<link>http://linfiniti.com/2009/08/automatically-dumping-all-postgres-tables-into-their-own-sql-files/</link>
		<comments>http://linfiniti.com/2009/08/automatically-dumping-all-postgres-tables-into-their-own-sql-files/#comments</comments>
		<pubDate>Fri, 14 Aug 2009 02:20:25 +0000</pubDate>
		<dc:creator>Tim Sutton</dc:creator>
				<category><![CDATA[Postgres & PostGIS]]></category>

		<guid isPermaLink="false">http://linfiniti.com/?p=104</guid>
		<description><![CDATA[Someone asked on twitter it is possible to dump all the tables in Postgres to individual shp files. Some time ago I wrote a script to dump all tables as SQL dumps. The question prompted me to tweak that script to drop out shapefiles instead. My original script looked like the listing below. The dump [...]]]></description>
			<content:encoded><![CDATA[<p>Someone asked on twitter it is possible to dump all the tables in Postgres to individual shp files. Some time ago I wrote a script to dump all tables as SQL dumps. The question prompted me to tweak that script to drop out shapefiles instead. </p>
<p>My original script looked like the listing below. The dump files contain data only (see the comments in the bash script below) because I use this script to create fixtures for my django projects.</p>
<pre>
#!/bin/bash

# A script to create sql formatted fixtures (serialised models)
# used to initialise the application if you install it to another
# machine. You should run this any time you change your models
# or when you need to make a backup of all your data.

# Tim Sutton 2009
mkdir bees/sql
for TABLE in `echo "\d" | psql sabio | grep -v seq | awk '{print $3}'`
do
  echo $TABLE
  # -a data only
  # -t table
  # -D dump as sql inserts
  pg_dump -a -t $TABLE -D sabio > bees/sql/${TABLE}.sql
  #bzip2 bees/sql/${TABLE}.sql
done
</pre>
<p>To make the script drop out shapefiles I modified it a bit as shown in the next listing. Obviously as we are dumping shapefiles, we should only bother dumping tables with geometry in them so I went the route of using the geometry_columns table to decide which tables to dump&#8230;</p>
<pre>
#!/bin/bash

# A script to dump shapefiles of all tables listed in geometry_columns
# Tim Sutton 2009
mkdir bees/sql
for TABLE in `echo "select f_table_name from geometry_columns;" | psql sabio \
  | head -n -2 | egrep -v "\-\-\-\-\-\-\-\-\-" | egrep -v "f_table_name"`
do
  echo $TABLE
  pgsql2shp sabio $TABLE
done
</pre>
<p>Hope this is useful to someone out there <img src='http://linfiniti.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<img src="http://linfiniti.com/wp-content/plugins/pixelstats/trackingpixel.php?post_id=104&amp;ts=1280627146" style="display:none;" alt="pixelstats trackingpixel"/>]]></content:encoded>
			<wfw:commentRss>http://linfiniti.com/2009/08/automatically-dumping-all-postgres-tables-into-their-own-sql-files/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Handy tip for the day : Backing up PostgreSQL data to a remote machine</title>
		<link>http://linfiniti.com/2009/08/handy-tip-for-the-day-backing-up-postgresql-data-to-a-remote-machine/</link>
		<comments>http://linfiniti.com/2009/08/handy-tip-for-the-day-backing-up-postgresql-data-to-a-remote-machine/#comments</comments>
		<pubDate>Tue, 04 Aug 2009 02:40:48 +0000</pubDate>
		<dc:creator>Tim Sutton</dc:creator>
				<category><![CDATA[Postgres & PostGIS]]></category>

		<guid isPermaLink="false">http://linfiniti.com/?p=100</guid>
		<description><![CDATA[Ok so I have a few production databases that I need to back up regularly. The trick is I want to run the backup from a remote machine so that the backup lives on a separate server to the actual database system. You can run backups manually like this (assuming your database is called &#8216;postgis&#8217;): [...]]]></description>
			<content:encoded><![CDATA[<p>Ok so I have a few production databases that I need to back up regularly. The trick is I want to run the backup from a remote machine so that the backup lives on a separate server to the actual database system. You can run backups manually like this (assuming your database is called &#8216;postgis&#8217;):</p>
<pre>
pg_dump -h dbhost -f postgis_`date +%d%B%Y`.sql.tar.gz -x -O -F tar postgis
</pre>
<p>When you run the above command, you will be prompted for a password. After entering the password you will find a date stamped backup. Very nice, but you may have noted that pg_dump has no option for giving it the password on the command line &#8211; it expects you to do that interactively. So what do we do if we need to automate the packup using a cron job? The solution is to use either ~/.pgpass or the PGPASSWORD environment variable. So here is how I automated the backup by placing a script in /etc/cron.daily/</p>
<pre>
export PGPASSWORD=secret
pg_dump -h dbhost -f postgis_`date +%d%B%Y`.sql.tar.gz -x -O -F tar postgis
</pre>
<img src="http://linfiniti.com/wp-content/plugins/pixelstats/trackingpixel.php?post_id=100&amp;ts=1280627146" style="display:none;" alt="pixelstats trackingpixel"/>]]></content:encoded>
			<wfw:commentRss>http://linfiniti.com/2009/08/handy-tip-for-the-day-backing-up-postgresql-data-to-a-remote-machine/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PostGIS 1.4 Released</title>
		<link>http://linfiniti.com/2009/07/postgis-1-4-released/</link>
		<comments>http://linfiniti.com/2009/07/postgis-1-4-released/#comments</comments>
		<pubDate>Sat, 25 Jul 2009 01:11:47 +0000</pubDate>
		<dc:creator>Tim Sutton</dc:creator>
				<category><![CDATA[Postgres & PostGIS]]></category>

		<guid isPermaLink="false">http://linfiniti.com/?p=95</guid>
		<description><![CDATA[Good news if you are a PostGIS fan &#8211; the PostGIS team just released version 1.4! See the release announcement for full details&#8230;]]></description>
			<content:encoded><![CDATA[<p>Good news if you are a PostGIS fan &#8211; the PostGIS team just released version 1.4! See the <a href="http://www.postgis.org/pipermail/postgis-users/2009-July/024035.html">release announcement</a> for full details&#8230;</p>
<img src="http://linfiniti.com/wp-content/plugins/pixelstats/trackingpixel.php?post_id=95&amp;ts=1280627146" style="display:none;" alt="pixelstats trackingpixel"/>]]></content:encoded>
			<wfw:commentRss>http://linfiniti.com/2009/07/postgis-1-4-released/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
