You should have a look to similar existing modules/framework.
For instance :
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.