Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 22 additions & 7 deletions connector.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,13 @@ package mysql
import (
"context"
"database/sql/driver"
"errors"
"fmt"
"net"
"os"
"strconv"
"strings"
"syscall"
)

type connector struct {
Expand Down Expand Up @@ -98,13 +100,11 @@ func (c *connector) Connect(ctx context.Context) (driver.Conn, error) {
}

// Enable TCP Keepalives on TCP connections
if tc, ok := mc.netConn.(*net.TCPConn); ok {
if err := tc.SetKeepAlive(true); err != nil {
// Don't send COM_QUIT before handshake.
mc.netConn.Close()
mc.netConn = nil
return nil, err
}
if err := enableKeepAlive(mc.netConn); err != nil {
// Don't send COM_QUIT before handshake.
mc.netConn.Close()
mc.netConn = nil
return nil, err
}

// Call startWatcher for context support (From Go 1.8)
Expand Down Expand Up @@ -188,3 +188,18 @@ func (c *connector) Connect(ctx context.Context) (driver.Conn, error) {
func (c *connector) Driver() driver.Driver {
return &MySQLDriver{}
}

func enableKeepAlive(nc net.Conn) error {
if tc, ok := nc.(*net.TCPConn); ok {
if err := tc.SetKeepAlive(true); err != nil {
// The underlying setsockopt syscall may return ENOPROTOOPT if the
// system does not support TCP keep-alive. We can still successfully
// use the driver without keep-alive support, which is why we choose
// to silence it here.
if !errors.Is(err, syscall.ENOPROTOOPT) {
return err
}
}
}
return nil
}