Performance issues with CAST function
Put auto_explain into shared_preload_libraries in postgresql.conf and restart PostgreSQL.

Set

auto_explain.log_min_duration = 0
auto_explain.log_nested_statements = on
auto_explain.log_analyze = on
auto_explain.log_buffers = on


in postgresql.conf (and reload).

Then run the slow query again.

This will log all SQL statements and their execution plan in the PostgreSQL log. Examine the plan for the statement run in your function. That should give you a clue.

The most likely explanation would be a missing index on catalogue.users(username).