Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement driver.Pinger #565

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
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
28 changes: 28 additions & 0 deletions connection_go18.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// +build go1.8

package mysql

import (
"context"
"time"
)

func (mc *mysqlConn) Ping(ctx context.Context) error {
err := mc.writeCommandPacket(comPing)
if err != nil {
return err
}

ch := make(chan error)
go func() {
_, err := mc.readResultOK()
ch <- err
}()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

select {
case <-ctx.Done():
mc.netConn.SetReadDeadline(time.Now())
return ctx.Err()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is dangerous.

  • mc is not thread safe.
  • mc.readResultOK() is still working.
  • After Ping return, database/sql.DB will use this connection again. race may be happen.

case err := <-ch:
return err
}
}
17 changes: 17 additions & 0 deletions driver_go18_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
package mysql

import (
"context"
"database/sql"
"database/sql/driver"
"fmt"
"reflect"
"testing"
Expand Down Expand Up @@ -188,3 +190,18 @@ func TestSkipResults(t *testing.T) {
}
})
}

func TestPing(t *testing.T) {
runTests(t, dsn, func(dbt *DBTest) {
mysqlDriver := dbt.db.Driver().(driver.Driver)
conn, err := mysqlDriver.Open(dsn)
if err != nil {
dbt.Fatalf("error opening conn: %s", err)
}
pinger := conn.(driver.Pinger)
err = pinger.Ping(context.Background())
if err != nil {
dbt.Fatalf("error on ping: %s", err)
}
})
}