Fix concurrency issue with pgsql stored function