Optimize complex sql

Move SQL-Query logic for recursive Graph-Data queries into a PSQL-Function.