Report and close on connection errors from the server (#1852)

When a query exceeds the server's max_allowed_packet but not the client's
maxAllowedPacket, the server answers ERR 1153 (08S01) and closes the
connection.

- writePacket: when a write fails after part of the command was sent,
  read a pending ERR packet with the bounded reader of the idle check
  (now pendingError) and return it.
- handleErrorPacket: after an error in SQLSTATE class 08 (connection
  exception), except 1047, close the connection so database/sql does not
  reuse it; the server error is still returned.

Fixes #1849

Signed-off-by: Giulio Calzolari <gcalzolari@nvidia.com>
diff --git a/conncheck_error.go b/conncheck_error.go
index c54efc7..d4023d8 100644
--- a/conncheck_error.go
+++ b/conncheck_error.go
@@ -17,6 +17,16 @@
 // idle connection. It never makes a connection reusable, even if the pending
 // bytes turn out to be TLS control traffic rather than a MySQL packet.
 func (mc *mysqlConn) idleError() error {
+	if serverErr := mc.pendingError(); serverErr != nil {
+		return serverErr
+	}
+	return errUnexpectedRead
+}
+
+// pendingError reads an ERR packet the server has already sent, bounded by
+// idleErrorTimeout and maxIdleErrorPacketSize, and closes the connection. It
+// returns nil when no complete ERR packet can be read in time.
+func (mc *mysqlConn) pendingError() *MySQLError {
 	conn := mc.rawConn
 	if conn == nil {
 		conn = mc.netConn
@@ -28,7 +38,7 @@
 	defer timer.Stop()
 	defer mc.close()
 	if err := mc.netConn.SetDeadline(time.Now().Add(idleErrorTimeout)); err != nil {
-		return errUnexpectedRead
+		return nil
 	}
 
 	readNext := mc.readNext
@@ -41,19 +51,19 @@
 	// packets, or apply RejectReadOnly to the original server error.
 	header, err := readNext(4)
 	if err != nil {
-		return errUnexpectedRead
+		return nil
 	}
 	n := getUint24(header[:3])
 	if n < 3 || n > maxIdleErrorPacketSize {
-		return errUnexpectedRead
+		return nil
 	}
 	data, err := readNext(n)
 	if err != nil {
-		return errUnexpectedRead
+		return nil
 	}
 	serverErr, err := decodeErrorPacket(data)
 	if err != nil {
-		return errUnexpectedRead
+		return nil
 	}
 	return serverErr
 }
diff --git a/connection_test.go b/connection_test.go
index 2cdc778..ca1df3b 100644
--- a/connection_test.go
+++ b/connection_test.go
@@ -13,6 +13,7 @@
 	"database/sql/driver"
 	"encoding/json"
 	"errors"
+	"io"
 	"net"
 	"testing"
 	"time"
@@ -210,6 +211,15 @@
 	return nil
 }
 
+// Read and SetDeadline let a failed write look for a pending server error.
+func (bc badConnection) Read(b []byte) (n int, err error) {
+	return 0, io.EOF
+}
+
+func (bc badConnection) SetDeadline(time.Time) error {
+	return nil
+}
+
 func TestInterpolateParamsWithComments(t *testing.T) {
 	mc := &mysqlConn{
 		buf:              newBuffer(),
diff --git a/packets.go b/packets.go
index 507f4be..214c031 100644
--- a/packets.go
+++ b/packets.go
@@ -136,6 +136,7 @@
 		writeFunc = mc.compIO.writePackets
 	}
 
+	sent := false
 	for {
 		size := min(maxPacketSize, pktLen)
 		putUint24(data[:3], size)
@@ -148,17 +149,29 @@
 
 		n, err := writeFunc(data[:4+size])
 		if err != nil {
-			mc.cleanup()
 			if cerr := mc.canceled.Value(); cerr != nil {
+				mc.cleanup()
 				return cerr
 			}
-			if n == 0 && pktLen == len(data)-4 {
-				// only for the first loop iteration when nothing was written yet
+			if n == 0 && !sent {
+				// nothing of the command was written yet
+				mc.cleanup()
 				mc.log(err)
 				return errBadConnNoWrite
-			} else {
-				return err
 			}
+			// Part of the command was sent. The server may have rejected it
+			// with an error packet before closing the connection, as it does
+			// with 1153 when the packet exceeds its max_allowed_packet:
+			// return that error instead of the write error.
+			if mc.compress {
+				// compIO.buff still holds the outgoing frame: discard it
+				// so that only bytes from the server are read.
+				mc.compIO.reset()
+			}
+			if serverErr := mc.pendingError(); serverErr != nil {
+				return serverErr
+			}
+			return err
 		}
 		if n != 4+size {
 			// io.Writer(b) must return a non-nil error if it cannot write len(b) bytes.
@@ -167,6 +180,7 @@
 			return io.ErrShortWrite
 		}
 
+		sent = true
 		mc.sequence++
 		if size != maxPacketSize {
 			return nil
@@ -601,6 +615,16 @@
 		return driver.ErrBadConn
 	}
 
+	// SQLSTATE class 08 is a connection exception, such as 1153
+	// (ER_NET_PACKET_TOO_LARGE): the server closes the connection after
+	// sending it. Close ours too, so database/sql does not reuse it, but keep
+	// the result read so far and return the server error. 1047
+	// (ER_UNKNOWN_COM_ERROR) is also in class 08, but the server keeps the
+	// connection open after it.
+	if me.SQLState[0] == '0' && me.SQLState[1] == '8' && errno != 1047 {
+		mc.cleanup()
+	}
+
 	return me
 }
 
diff --git a/packets_test.go b/packets_test.go
index 3a6e6e6..cc318bd 100644
--- a/packets_test.go
+++ b/packets_test.go
@@ -14,7 +14,10 @@
 	"encoding/binary"
 	"errors"
 	"fmt"
+	"io"
 	"net"
+	"strings"
+	"syscall"
 	"testing"
 	"time"
 )
@@ -761,3 +764,138 @@
 		}
 	}
 }
+
+// brokenPipeConn accepts okWrites writes, then fails the next one, as a socket
+// does when the server closes the connection while a command is being sent.
+// The failing write sends half of its bytes if partial is set, none otherwise.
+// Reads return pending, then io.EOF.
+type brokenPipeConn struct {
+	*mockConn
+	pending  []byte
+	okWrites int
+	partial  bool
+}
+
+func (c *brokenPipeConn) Write(b []byte) (int, error) {
+	if c.okWrites > 0 {
+		c.okWrites--
+		return len(b), nil
+	}
+	if c.partial {
+		return len(b) / 2, syscall.EPIPE
+	}
+	return 0, syscall.EPIPE
+}
+
+func (c *brokenPipeConn) Read(b []byte) (int, error) {
+	if len(c.pending) == 0 {
+		return 0, io.EOF
+	}
+	n := copy(b, c.pending)
+	c.pending = c.pending[n:]
+	return n, nil
+}
+
+// A write that fails after part of the command was sent returns the error
+// packet the server sent before closing the connection, if there is one, and
+// the write error otherwise. The connection is closed either way.
+func TestWritePacketPendingError(t *testing.T) {
+	// ERR 1153 (08S01) Got a packet bigger than 'max_allowed_packet' bytes
+	errPacket := append([]byte{0x3a, 0x00, 0x00, 0x01, 0xff, 0x81, 0x04, '#', '0', '8', 'S', '0', '1'},
+		"Got a packet bigger than 'max_allowed_packet' bytes"...)
+	isServerErr := func(err error) bool {
+		var me *MySQLError
+		return errors.As(err, &me) && me.Number == 1153 && string(me.SQLState[:]) == "08S01"
+	}
+	isWriteErr := func(err error) bool { return errors.Is(err, syscall.EPIPE) }
+
+	for _, write := range []struct {
+		name     string
+		query    string
+		okWrites int
+		partial  bool
+	}{{
+		name:    "first packet partially sent",
+		query:   "INSERT INTO t VALUES ('" + strings.Repeat("a", 4096) + "')",
+		partial: true,
+	}, {
+		// The first 16 MiB packet is sent, the next one is not sent at all.
+		name:     "later packet not sent",
+		query:    "INSERT INTO t VALUES ('" + strings.Repeat("a", maxPacketSize) + "')",
+		okWrites: 1,
+	}} {
+		for _, compress := range []bool{false, true} {
+			for _, tc := range []struct {
+				name    string
+				pending []byte
+				want    func(error) bool
+			}{
+				{"server error", errPacket, isServerErr},
+				{"no server error", nil, isWriteErr},
+			} {
+				t.Run(fmt.Sprintf("%s/compress=%t/%s", write.name, compress, tc.name), func(t *testing.T) {
+					pending := tc.pending
+					if compress && pending != nil {
+						// uncompressed payload in a compressed packet
+						pending = append([]byte{byte(len(pending)), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, pending...)
+					}
+					conn := &brokenPipeConn{
+						mockConn: new(mockConn),
+						pending:  pending,
+						okWrites: write.okWrites,
+						partial:  write.partial,
+					}
+					mc := &mysqlConn{
+						buf:              newBuffer(),
+						cfg:              NewConfig(),
+						netConn:          conn,
+						closech:          make(chan struct{}),
+						maxAllowedPacket: defaultMaxAllowedPacket,
+						compress:         compress,
+					}
+					if compress {
+						mc.compIO = newCompIO(mc)
+					}
+					err := mc.writeCommandPacketStr(comQuery, write.query)
+					if !tc.want(err) {
+						t.Fatalf("writeCommandPacketStr = %v", err)
+					}
+					if mc.IsValid() {
+						t.Error("connection is still valid")
+					}
+				})
+			}
+		}
+	}
+}
+
+// An error in SQLSTATE class 08 (connection exception) closes the connection,
+// so database/sql does not reuse it, and is returned as the server sent it.
+// Other errors, and 1047 (ER_UNKNOWN_COM_ERROR, class 08 but the server keeps
+// the connection), leave it open.
+func TestHandleErrorPacketConnectionException(t *testing.T) {
+	for _, tc := range []struct {
+		number uint16
+		state  string
+		closed bool
+	}{
+		{1153, "08S01", true},
+		{1040, "08004", true},
+		{1047, "08S01", false},
+		{1062, "23000", false},
+	} {
+		t.Run(fmt.Sprint(tc.number), func(t *testing.T) {
+			conn, mc := newRWMockConn(0)
+			body := append([]byte{0xff, byte(tc.number), byte(tc.number >> 8), '#'}, tc.state+"server error"...)
+			conn.data = append([]byte{byte(len(body)), 0x00, 0x00, 0x01}, body...)
+			err := mc.exec("SELECT 1")
+			var me *MySQLError
+			if !errors.As(err, &me) || me.Number != tc.number || string(me.SQLState[:]) != tc.state {
+				t.Fatalf("exec = %v, want error %d (%s)", err, tc.number, tc.state)
+			}
+			if closed := !mc.IsValid(); closed != tc.closed {
+				t.Errorf("connection closed = %t, want %t", closed, tc.closed)
+			}
+		})
+	}
+}