This task required a lot of experimenting with postgresql and took a lot of time until we found the temporary solution.