Fix SQL function creation for tests and scenarios

Supersedes #415.