def with_tx(conn) case conn.transaction_status when PQTRANS_IDLE, PQTRANS_ACTIVE conn.transaction do |conn| yield conn end when PQTRANS_INTRANS name = "savepoint_" + SecureRandom::alphanumeric begin conn.exec("SAVEPOINT #{name}") yield conn conn.exec("RELEASE SAVEPOINT #{name}") rescue conn.exec("ROLLBACK TO SAVEPOINT #{name}") raise end when PQTRANS_INERROR raise "Error" when PQTRANS_UNKNOWN raise "Unknown" end end