The PG db_exec_pgsql routine will bury your code in an inline for you, much as you've done explicitly, so you've got the right idea but actually it's probably best to let the db api routine do it.
Eventually, I'd like to see code like this migrate into PL/[pg]SQL funcs/procs anyway. Not only won't one have to kludge around such inlines for PG and other RDBMS's that don't support inline programmatic code blocks, the code will only have to be compiled once.