Friday
Mar262010
Calling PostgreSQL Stored Procedures from Grails - Part 3, SqlFunction
Friday, March 26, 2010 at 4:26PM SqlFunction is another class that takes a stored function (which is our sample procedure in Part 1), and runs it. I've done a rather inefficient sample below. In reality, you should be using the constructor passing the input types, and using the version of run which allows you to pass parameters.
The SqlFunction section of our service
def sqlFunction = new SqlFunction(dataSource, "select salesByBookId(${bookId})")
sqlFunction.compile()
def result
try {
result = sqlFunction.run()
} catch (org.springframework.dao.DataAccessException e) {
log.error "Result type cannot be inferred - " +
" no result so returning 0"
0
}
result
I should explain a few things about the code snippet:
- The dataSource I auto-inject using
def dataSourcein the Grails Service - I return 0 if the key is wrong
- The SqlFunction throws subclasses of
DataAccessExceptionwhen the call fails (if the row doesn't come back, for example. You could useTypeMismatchDataAccesException, which is a subclass ofDataAccessExceptionbut I chose the wider exception in the hierarchy. - I'm using the nifty Grails
logvariable, which is wired into every Grails object automatically. You can control logging via theConfig.groovyfile in yourgrails-appdirectory. - Ideally, you should set up the SqlFunction instance and re-use it over and over again, as it is compiled. Again, this is more showing you the features, not best practices, as I'm just blogging this to put a little more information out there. I'll refactor this a bit later, if I get the chance...
tagged
Chariot Solutions,
chariot-news in
Groovy/Grails,
PostgreSQL
Chariot Solutions,
chariot-news in
Groovy/Grails,
PostgreSQL 


Reader Comments