Have you tried using connection.execute(text( <sql here> ), <bind params here> )
and bind parameters as described in the docs? This can help solve many parameter formatting and performance problems. Maybe the gateway error is a timeout? Bind parameters tend to make complex queries execute substantially faster.