OP says it needs to be a function in sql and backslash commands are psql commands not queries. Probably would not suite their case.
Yes, that's exactly right. Other requirements around this whole thing force us to do this in a function and not through psql. We've actually been thinking about using pl{perl,python,rust} instead because this approach works, but is annoying.