Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

Is it possible to catch PostgreSQL output error messages in OGR after a query has failed?

For example

conn.ExecuteSQL('SELECT * FROM non_existing_table;')

In Postgres this returns an error message:

"Error: relation 'non_existing_table' does not exist."

In ogr we get the standard:

"Error: current transaction is aborted, commands ignored until end of transaction block"

It would be a bonus if we could catch/parse the Postgres error message. I suspect this is a bit of a long-shot given what I've read about SWIG/CPL, but worth asking to see if anyone's got ideas. Ideally this would be in Python, but I'll take C/C++ comments as well!

Thanks.

share|improve this question
add comment

2 Answers

if you are using psycopg2, you can easily print your error message with putting it into "try" function as the following code. the code was taken from zetcode.com for not writing again...

#!/usr/bin/python
# -*- coding: utf-8 -*-

import psycopg2
import sys


con = None

try:

    con = psycopg2.connect(database='testdb', user='janbodnar') 
    cur = con.cursor()
    cur.execute('SELECT version()')          
    ver = cur.fetchone()
    print ver    


except psycopg2.DatabaseError, e:
    print 'Error %s' % e    
    sys.exit(1)


finally:

    if con:
        con.close()

i hope it helps you...

share|improve this answer
    
Thanks Aragon, yes Psycopg2 is a great library, but interested to see if something similar is possible via ogr. We need ogr to handle geometry operations and I'd rather not duplicate connections just for the sake of using a different API. –  thom Jul 31 '12 at 12:24
add comment

You should upgrade to GDAL/OGR 1.9.x where the error reporting for PostgreSQL datasource has been improved :

$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from osgeo import ogr
>>> ogr.UseExceptions()
>>> ds = ogr.Open('pg:dbname=autotest')
>>> ds.ExecuteSQL("SELECT * FROM non_existing_table")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.6/dist-packages/osgeo/ogr.py", line 699, in ExecuteSQL
    return _ogr.DataSource_ExecuteSQL(self, *args, **kwargs)
RuntimeError: ERREUR:  la relation « non_existing_table » n'existe pas
LINE 1: DECLARE executeSQLCursor CURSOR for SELECT * FROM non_existi...
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.