I had a look to SPOPS (hi chis! ;-)). And especially SPOPS::SQLInterface
it's pretty well writen. And this Class seems to implement a solution to your problem.
SPOPS don't seem to support Postgresql (only mysql) but in CVS version
At last, have look to past nodes on similar subject.