Forward-ported from 3.1.2, with minor modifications for defensiveness against the JDBC driver. Issue: SPR-10084