├── go.mod ├── .gitignore ├── go.sum ├── .github ├── PULL_REQUEST_TEMPLATE.md ├── ISSUE_TEMPLATE.md ├── workflows │ ├── codeql.yml │ └── test.yml └── CONTRIBUTING.md ├── conncheck_dummy.go ├── connector_test.go ├── dsn_fuzz_test.go ├── transaction.go ├── conncheck_test.go ├── conncheck.go ├── result.go ├── nulltime_test.go ├── errors_test.go ├── nulltime.go ├── errors.go ├── compress_test.go ├── statement_test.go ├── driver.go ├── buffer.go ├── const.go ├── infile.go ├── rows.go ├── connection_test.go ├── AUTHORS ├── fields.go ├── compress.go ├── statement.go ├── connector.go ├── collations.go ├── packets_test.go ├── benchmark_test.go ├── auth.go ├── utils_test.go ├── CHANGELOG.md ├── LICENSE └── dsn_test.go /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/go-sql-driver/mysql 2 | 3 | go 1.22.0 4 | 5 | require filippo.io/edwards25519 v1.1.0 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .DS_Store? 3 | ._* 4 | .Spotlight-V100 5 | .Trashes 6 | Icon? 7 | ehthumbs.db 8 | Thumbs.db 9 | .idea 10 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= 2 | filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= 3 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ### Description 2 | Please explain the changes you made here. 3 | 4 | ### Checklist 5 | - [ ] Code compiles correctly 6 | - [ ] Created tests which fail without the change (if possible) 7 | - [ ] All tests passing 8 | - [ ] Extended the README / documentation, if necessary 9 | - [ ] Added myself / the copyright holder to the AUTHORS file 10 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ### Issue description 2 | Tell us what should happen and what happens instead 3 | 4 | ### Example code 5 | ```go 6 | If possible, please enter some example code here to reproduce the issue. 7 | ``` 8 | 9 | ### Error log 10 | ``` 11 | If you have an error log, please paste it here. 12 | ``` 13 | 14 | ### Configuration 15 | *Driver version (or git SHA):* 16 | 17 | *Go version:* run `go version` in your console 18 | 19 | *Server version:* E.g. MySQL 5.6, MariaDB 10.0.20 20 | 21 | *Server OS:* E.g. Debian 8.1 (Jessie), Windows 10 22 | -------------------------------------------------------------------------------- /conncheck_dummy.go: -------------------------------------------------------------------------------- 1 | // Go MySQL Driver - A MySQL-Driver for Go's database/sql package 2 | // 3 | // Copyright 2019 The Go-MySQL-Driver Authors. All rights reserved. 4 | // 5 | // This Source Code Form is subject to the terms of the Mozilla Public 6 | // License, v. 2.0. If a copy of the MPL was not distributed with this file, 7 | // You can obtain one at http://mozilla.org/MPL/2.0/. 8 | 9 | //go:build !linux && !darwin && !dragonfly && !freebsd && !netbsd && !openbsd && !solaris && !illumos 10 | // +build !linux,!darwin,!dragonfly,!freebsd,!netbsd,!openbsd,!solaris,!illumos 11 | 12 | package mysql 13 | 14 | import "net" 15 | 16 | func connCheck(conn net.Conn) error { 17 | return nil 18 | } 19 | -------------------------------------------------------------------------------- /connector_test.go: -------------------------------------------------------------------------------- 1 | package mysql 2 | 3 | import ( 4 | "context" 5 | "net" 6 | "testing" 7 | "time" 8 | ) 9 | 10 | func TestConnectorReturnsTimeout(t *testing.T) { 11 | connector := newConnector(&Config{ 12 | Net: "tcp", 13 | Addr: "1.1.1.1:1234", 14 | Timeout: 10 * time.Millisecond, 15 | }) 16 | 17 | _, err := connector.Connect(context.Background()) 18 | if err == nil { 19 | t.Fatal("error expected") 20 | } 21 | 22 | if nerr, ok := err.(*net.OpError); ok { 23 | expected := "dial tcp 1.1.1.1:1234: i/o timeout" 24 | if nerr.Error() != expected { 25 | t.Fatalf("expected %q, got %q", expected, nerr.Error()) 26 | } 27 | } else { 28 | t.Fatalf("expected %T, got %T", nerr, err) 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /.github/workflows/codeql.yml: -------------------------------------------------------------------------------- 1 | name: "CodeQL" 2 | 3 | on: 4 | push: 5 | branches: [ "master" ] 6 | pull_request: 7 | branches: [ "master" ] 8 | schedule: 9 | - cron: "18 19 * * 1" 10 | 11 | jobs: 12 | analyze: 13 | name: Analyze 14 | runs-on: ubuntu-latest 15 | permissions: 16 | actions: read 17 | contents: read 18 | security-events: write 19 | 20 | strategy: 21 | fail-fast: false 22 | matrix: 23 | language: [ go ] 24 | 25 | steps: 26 | - name: Checkout 27 | uses: actions/checkout@v4 28 | 29 | - name: Initialize CodeQL 30 | uses: github/codeql-action/init@v3 31 | with: 32 | languages: ${{ matrix.language }} 33 | queries: +security-and-quality 34 | 35 | - name: Autobuild 36 | uses: github/codeql-action/autobuild@v3 37 | 38 | - name: Perform CodeQL Analysis 39 | uses: github/codeql-action/analyze@v3 40 | with: 41 | category: "/language:${{ matrix.language }}" 42 | -------------------------------------------------------------------------------- /dsn_fuzz_test.go: -------------------------------------------------------------------------------- 1 | //go:build go1.18 2 | // +build go1.18 3 | 4 | package mysql 5 | 6 | import ( 7 | "net" 8 | "testing" 9 | ) 10 | 11 | func FuzzFormatDSN(f *testing.F) { 12 | for _, test := range testDSNs { // See dsn_test.go 13 | f.Add(test.in) 14 | } 15 | 16 | f.Fuzz(func(t *testing.T, dsn1 string) { 17 | // Do not waste resources 18 | if len(dsn1) > 1000 { 19 | t.Skip("ignore: too long") 20 | } 21 | 22 | cfg1, err := ParseDSN(dsn1) 23 | if err != nil { 24 | t.Skipf("invalid DSN: %v", err) 25 | } 26 | 27 | dsn2 := cfg1.FormatDSN() 28 | if dsn2 == dsn1 { 29 | return 30 | } 31 | 32 | // Skip known cases of bad config that are not strictly checked by ParseDSN 33 | if _, _, err := net.SplitHostPort(cfg1.Addr); err != nil { 34 | t.Skipf("invalid addr %q: %v", cfg1.Addr, err) 35 | } 36 | 37 | cfg2, err := ParseDSN(dsn2) 38 | if err != nil { 39 | t.Fatalf("%q rewritten as %q: %v", dsn1, dsn2, err) 40 | } 41 | 42 | dsn3 := cfg2.FormatDSN() 43 | if dsn3 != dsn2 { 44 | t.Errorf("%q rewritten as %q", dsn2, dsn3) 45 | } 46 | }) 47 | } 48 | -------------------------------------------------------------------------------- /transaction.go: -------------------------------------------------------------------------------- 1 | // Go MySQL Driver - A MySQL-Driver for Go's database/sql package 2 | // 3 | // Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. 4 | // 5 | // This Source Code Form is subject to the terms of the Mozilla Public 6 | // License, v. 2.0. If a copy of the MPL was not distributed with this file, 7 | // You can obtain one at http://mozilla.org/MPL/2.0/. 8 | 9 | package mysql 10 | 11 | type mysqlTx struct { 12 | mc *mysqlConn 13 | } 14 | 15 | func (tx *mysqlTx) Commit() (err error) { 16 | if tx.mc == nil { 17 | return ErrInvalidConn 18 | } 19 | if tx.mc.closed.Load() { 20 | err = tx.mc.error() 21 | if err == nil { 22 | err = ErrInvalidConn 23 | } 24 | return 25 | } 26 | err = tx.mc.exec("COMMIT") 27 | tx.mc = nil 28 | return 29 | } 30 | 31 | func (tx *mysqlTx) Rollback() (err error) { 32 | if tx.mc == nil { 33 | return ErrInvalidConn 34 | } 35 | if tx.mc.closed.Load() { 36 | err = tx.mc.error() 37 | if err == nil { 38 | err = ErrInvalidConn 39 | } 40 | return 41 | } 42 | err = tx.mc.exec("ROLLBACK") 43 | tx.mc = nil 44 | return 45 | } 46 | -------------------------------------------------------------------------------- /conncheck_test.go: -------------------------------------------------------------------------------- 1 | // Go MySQL Driver - A MySQL-Driver for Go's database/sql package 2 | // 3 | // Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. 4 | // 5 | // This Source Code Form is subject to the terms of the Mozilla Public 6 | // License, v. 2.0. If a copy of the MPL was not distributed with this file, 7 | // You can obtain one at http://mozilla.org/MPL/2.0/. 8 | 9 | //go:build linux || darwin || dragonfly || freebsd || netbsd || openbsd || solaris || illumos 10 | // +build linux darwin dragonfly freebsd netbsd openbsd solaris illumos 11 | 12 | package mysql 13 | 14 | import ( 15 | "testing" 16 | "time" 17 | ) 18 | 19 | func TestStaleConnectionChecks(t *testing.T) { 20 | runTestsParallel(t, dsn, func(dbt *DBTest, _ string) { 21 | dbt.mustExec("SET @@SESSION.wait_timeout = 2") 22 | 23 | if err := dbt.db.Ping(); err != nil { 24 | dbt.Fatal(err) 25 | } 26 | 27 | // wait for MySQL to close our connection 28 | time.Sleep(3 * time.Second) 29 | 30 | tx, err := dbt.db.Begin() 31 | if err != nil { 32 | dbt.Fatal(err) 33 | } 34 | 35 | if err := tx.Rollback(); err != nil { 36 | dbt.Fatal(err) 37 | } 38 | }) 39 | } 40 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | ## Reporting Issues 4 | 5 | Before creating a new Issue, please check first if a similar Issue [already exists](https://github.com/go-sql-driver/mysql/issues?state=open) or was [recently closed](https://github.com/go-sql-driver/mysql/issues?direction=desc&page=1&sort=updated&state=closed). 6 | 7 | ## Contributing Code 8 | 9 | By contributing to this project, you share your code under the Mozilla Public License 2, as specified in the LICENSE file. 10 | Don't forget to add yourself to the AUTHORS file. 11 | 12 | ### Code Review 13 | 14 | Everyone is invited to review and comment on pull requests. 15 | If it looks fine to you, comment with "LGTM" (Looks good to me). 16 | 17 | If changes are required, notice the reviewers with "PTAL" (Please take another look) after committing the fixes. 18 | 19 | Before merging the Pull Request, at least one [team member](https://github.com/go-sql-driver?tab=members) must have commented with "LGTM". 20 | 21 | ## Development Ideas 22 | 23 | If you are looking for ideas for code contributions, please check our [Development Ideas](https://github.com/go-sql-driver/mysql/wiki/Development-Ideas) Wiki page. 24 | -------------------------------------------------------------------------------- /conncheck.go: -------------------------------------------------------------------------------- 1 | // Go MySQL Driver - A MySQL-Driver for Go's database/sql package 2 | // 3 | // Copyright 2019 The Go-MySQL-Driver Authors. All rights reserved. 4 | // 5 | // This Source Code Form is subject to the terms of the Mozilla Public 6 | // License, v. 2.0. If a copy of the MPL was not distributed with this file, 7 | // You can obtain one at http://mozilla.org/MPL/2.0/. 8 | 9 | //go:build linux || darwin || dragonfly || freebsd || netbsd || openbsd || solaris || illumos 10 | // +build linux darwin dragonfly freebsd netbsd openbsd solaris illumos 11 | 12 | package mysql 13 | 14 | import ( 15 | "errors" 16 | "io" 17 | "net" 18 | "syscall" 19 | ) 20 | 21 | var errUnexpectedRead = errors.New("unexpected read from socket") 22 | 23 | func connCheck(conn net.Conn) error { 24 | var sysErr error 25 | 26 | sysConn, ok := conn.(syscall.Conn) 27 | if !ok { 28 | return nil 29 | } 30 | rawConn, err := sysConn.SyscallConn() 31 | if err != nil { 32 | return err 33 | } 34 | 35 | err = rawConn.Read(func(fd uintptr) bool { 36 | var buf [1]byte 37 | n, err := syscall.Read(int(fd), buf[:]) 38 | switch { 39 | case n == 0 && err == nil: 40 | sysErr = io.EOF 41 | case n > 0: 42 | sysErr = errUnexpectedRead 43 | case err == syscall.EAGAIN || err == syscall.EWOULDBLOCK: 44 | sysErr = nil 45 | default: 46 | sysErr = err 47 | } 48 | return true 49 | }) 50 | if err != nil { 51 | return err 52 | } 53 | 54 | return sysErr 55 | } 56 | -------------------------------------------------------------------------------- /result.go: -------------------------------------------------------------------------------- 1 | // Go MySQL Driver - A MySQL-Driver for Go's database/sql package 2 | // 3 | // Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. 4 | // 5 | // This Source Code Form is subject to the terms of the Mozilla Public 6 | // License, v. 2.0. If a copy of the MPL was not distributed with this file, 7 | // You can obtain one at http://mozilla.org/MPL/2.0/. 8 | 9 | package mysql 10 | 11 | import "slices" 12 | 13 | import "database/sql/driver" 14 | 15 | // Result exposes data not available through *connection.Result. 16 | // 17 | // This is accessible by executing statements using sql.Conn.Raw() and 18 | // downcasting the returned result: 19 | // 20 | // res, err := rawConn.Exec(...) 21 | // res.(mysql.Result).AllRowsAffected() 22 | type Result interface { 23 | driver.Result 24 | // AllRowsAffected returns a slice containing the affected rows for each 25 | // executed statement. 26 | AllRowsAffected() []int64 27 | // AllLastInsertIds returns a slice containing the last inserted ID for each 28 | // executed statement. 29 | AllLastInsertIds() []int64 30 | } 31 | 32 | type mysqlResult struct { 33 | // One entry in both slices is created for every executed statement result. 34 | affectedRows []int64 35 | insertIds []int64 36 | } 37 | 38 | func (res *mysqlResult) LastInsertId() (int64, error) { 39 | return res.insertIds[len(res.insertIds)-1], nil 40 | } 41 | 42 | func (res *mysqlResult) RowsAffected() (int64, error) { 43 | return res.affectedRows[len(res.affectedRows)-1], nil 44 | } 45 | 46 | func (res *mysqlResult) AllLastInsertIds() []int64 { 47 | return slices.Clone(res.insertIds) // defensive copy 48 | } 49 | 50 | func (res *mysqlResult) AllRowsAffected() []int64 { 51 | return slices.Clone(res.affectedRows) // defensive copy 52 | } 53 | -------------------------------------------------------------------------------- /nulltime_test.go: -------------------------------------------------------------------------------- 1 | // Go MySQL Driver - A MySQL-Driver for Go's database/sql package 2 | // 3 | // Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. 4 | // 5 | // This Source Code Form is subject to the terms of the Mozilla Public 6 | // License, v. 2.0. If a copy of the MPL was not distributed with this file, 7 | // You can obtain one at http://mozilla.org/MPL/2.0/. 8 | 9 | package mysql 10 | 11 | import ( 12 | "database/sql" 13 | "database/sql/driver" 14 | "testing" 15 | "time" 16 | ) 17 | 18 | var ( 19 | // Check implementation of interfaces 20 | _ driver.Valuer = NullTime{} 21 | _ sql.Scanner = (*NullTime)(nil) 22 | ) 23 | 24 | func TestScanNullTime(t *testing.T) { 25 | var scanTests = []struct { 26 | in any 27 | error bool 28 | valid bool 29 | time time.Time 30 | }{ 31 | {tDate, false, true, tDate}, 32 | {sDate, false, true, tDate}, 33 | {[]byte(sDate), false, true, tDate}, 34 | {tDateTime, false, true, tDateTime}, 35 | {sDateTime, false, true, tDateTime}, 36 | {[]byte(sDateTime), false, true, tDateTime}, 37 | {tDate0, false, true, tDate0}, 38 | {sDate0, false, true, tDate0}, 39 | {[]byte(sDate0), false, true, tDate0}, 40 | {sDateTime0, false, true, tDate0}, 41 | {[]byte(sDateTime0), false, true, tDate0}, 42 | {"", true, false, tDate0}, 43 | {"1234", true, false, tDate0}, 44 | {0, true, false, tDate0}, 45 | } 46 | 47 | var nt = NullTime{} 48 | var err error 49 | 50 | for _, tst := range scanTests { 51 | err = nt.Scan(tst.in) 52 | if (err != nil) != tst.error { 53 | t.Errorf("%v: expected error status %t, got %t", tst.in, tst.error, (err != nil)) 54 | } 55 | if nt.Valid != tst.valid { 56 | t.Errorf("%v: expected valid status %t, got %t", tst.in, tst.valid, nt.Valid) 57 | } 58 | if nt.Time != tst.time { 59 | t.Errorf("%v: expected time %v, got %v", tst.in, tst.time, nt.Time) 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /errors_test.go: -------------------------------------------------------------------------------- 1 | // Go MySQL Driver - A MySQL-Driver for Go's database/sql package 2 | // 3 | // Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. 4 | // 5 | // This Source Code Form is subject to the terms of the Mozilla Public 6 | // License, v. 2.0. If a copy of the MPL was not distributed with this file, 7 | // You can obtain one at http://mozilla.org/MPL/2.0/. 8 | 9 | package mysql 10 | 11 | import ( 12 | "bytes" 13 | "errors" 14 | "log" 15 | "testing" 16 | ) 17 | 18 | func TestErrorsSetLogger(t *testing.T) { 19 | previous := defaultLogger 20 | defer func() { 21 | defaultLogger = previous 22 | }() 23 | 24 | // set up logger 25 | const expected = "prefix: test\n" 26 | buffer := bytes.NewBuffer(make([]byte, 0, 64)) 27 | logger := log.New(buffer, "prefix: ", 0) 28 | 29 | // print 30 | SetLogger(logger) 31 | defaultLogger.Print("test") 32 | 33 | // check result 34 | if actual := buffer.String(); actual != expected { 35 | t.Errorf("expected %q, got %q", expected, actual) 36 | } 37 | } 38 | 39 | func TestErrorsStrictIgnoreNotes(t *testing.T) { 40 | runTests(t, dsn+"&sql_notes=false", func(dbt *DBTest) { 41 | dbt.mustExec("DROP TABLE IF EXISTS does_not_exist") 42 | }) 43 | } 44 | 45 | func TestMySQLErrIs(t *testing.T) { 46 | infraErr := &MySQLError{Number: 1234, Message: "the server is on fire"} 47 | otherInfraErr := &MySQLError{Number: 1234, Message: "the datacenter is flooded"} 48 | if !errors.Is(infraErr, otherInfraErr) { 49 | t.Errorf("expected errors to be the same: %+v %+v", infraErr, otherInfraErr) 50 | } 51 | 52 | differentCodeErr := &MySQLError{Number: 5678, Message: "the server is on fire"} 53 | if errors.Is(infraErr, differentCodeErr) { 54 | t.Fatalf("expected errors to be different: %+v %+v", infraErr, differentCodeErr) 55 | } 56 | 57 | nonMysqlErr := errors.New("not a mysql error") 58 | if errors.Is(infraErr, nonMysqlErr) { 59 | t.Fatalf("expected errors to be different: %+v %+v", infraErr, nonMysqlErr) 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /nulltime.go: -------------------------------------------------------------------------------- 1 | // Go MySQL Driver - A MySQL-Driver for Go's database/sql package 2 | // 3 | // Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. 4 | // 5 | // This Source Code Form is subject to the terms of the Mozilla Public 6 | // License, v. 2.0. If a copy of the MPL was not distributed with this file, 7 | // You can obtain one at http://mozilla.org/MPL/2.0/. 8 | 9 | package mysql 10 | 11 | import ( 12 | "database/sql" 13 | "database/sql/driver" 14 | "fmt" 15 | "time" 16 | ) 17 | 18 | // NullTime represents a time.Time that may be NULL. 19 | // NullTime implements the Scanner interface so 20 | // it can be used as a scan destination: 21 | // 22 | // var nt NullTime 23 | // err := db.QueryRow("SELECT time FROM foo WHERE id=?", id).Scan(&nt) 24 | // ... 25 | // if nt.Valid { 26 | // // use nt.Time 27 | // } else { 28 | // // NULL value 29 | // } 30 | // 31 | // # This NullTime implementation is not driver-specific 32 | // 33 | // Deprecated: NullTime doesn't honor the loc DSN parameter. 34 | // NullTime.Scan interprets a time as UTC, not the loc DSN parameter. 35 | // Use sql.NullTime instead. 36 | type NullTime sql.NullTime 37 | 38 | // Scan implements the Scanner interface. 39 | // The value type must be time.Time or string / []byte (formatted time-string), 40 | // otherwise Scan fails. 41 | func (nt *NullTime) Scan(value any) (err error) { 42 | if value == nil { 43 | nt.Time, nt.Valid = time.Time{}, false 44 | return 45 | } 46 | 47 | switch v := value.(type) { 48 | case time.Time: 49 | nt.Time, nt.Valid = v, true 50 | return 51 | case []byte: 52 | nt.Time, err = parseDateTime(v, time.UTC) 53 | nt.Valid = (err == nil) 54 | return 55 | case string: 56 | nt.Time, err = parseDateTime([]byte(v), time.UTC) 57 | nt.Valid = (err == nil) 58 | return 59 | } 60 | 61 | nt.Valid = false 62 | return fmt.Errorf("can't convert %T to time.Time", value) 63 | } 64 | 65 | // Value implements the driver Valuer interface. 66 | func (nt NullTime) Value() (driver.Value, error) { 67 | if !nt.Valid { 68 | return nil, nil 69 | } 70 | return nt.Time, nil 71 | } 72 | -------------------------------------------------------------------------------- /errors.go: -------------------------------------------------------------------------------- 1 | // Go MySQL Driver - A MySQL-Driver for Go's database/sql package 2 | // 3 | // Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. 4 | // 5 | // This Source Code Form is subject to the terms of the Mozilla Public 6 | // License, v. 2.0. If a copy of the MPL was not distributed with this file, 7 | // You can obtain one at http://mozilla.org/MPL/2.0/. 8 | 9 | package mysql 10 | 11 | import ( 12 | "errors" 13 | "fmt" 14 | "log" 15 | "os" 16 | ) 17 | 18 | // Various errors the driver might return. Can change between driver versions. 19 | var ( 20 | ErrInvalidConn = errors.New("invalid connection") 21 | ErrMalformPkt = errors.New("malformed packet") 22 | ErrNoTLS = errors.New("TLS requested but server does not support TLS") 23 | ErrCleartextPassword = errors.New("this user requires clear text authentication. If you still want to use it, please add 'allowCleartextPasswords=1' to your DSN") 24 | ErrNativePassword = errors.New("this user requires mysql native password authentication") 25 | ErrOldPassword = errors.New("this user requires old password authentication. If you still want to use it, please add 'allowOldPasswords=1' to your DSN. See also https://github.com/go-sql-driver/mysql/wiki/old_passwords") 26 | ErrUnknownPlugin = errors.New("this authentication plugin is not supported") 27 | ErrOldProtocol = errors.New("MySQL server does not support required protocol 41+") 28 | ErrPktSync = errors.New("commands out of sync. You can't run this command now") 29 | ErrPktSyncMul = errors.New("commands out of sync. Did you run multiple statements at once?") 30 | ErrPktTooLarge = errors.New("packet for query is too large. Try adjusting the `Config.MaxAllowedPacket`") 31 | ErrBusyBuffer = errors.New("busy buffer") 32 | 33 | // errBadConnNoWrite is used for connection errors where nothing was sent to the database yet. 34 | // If this happens first in a function starting a database interaction, it should be replaced by driver.ErrBadConn 35 | // to trigger a resend. Use mc.markBadConn(err) to do this. 36 | // See https://github.com/go-sql-driver/mysql/pull/302 37 | errBadConnNoWrite = errors.New("bad connection") 38 | ) 39 | 40 | var defaultLogger = Logger(log.New(os.Stderr, "[mysql] ", log.Ldate|log.Ltime)) 41 | 42 | // Logger is used to log critical error messages. 43 | type Logger interface { 44 | Print(v ...any) 45 | } 46 | 47 | // NopLogger is a nop implementation of the Logger interface. 48 | type NopLogger struct{} 49 | 50 | // Print implements Logger interface. 51 | func (nl *NopLogger) Print(_ ...any) {} 52 | 53 | // SetLogger is used to set the default logger for critical errors. 54 | // The initial logger is os.Stderr. 55 | func SetLogger(logger Logger) error { 56 | if logger == nil { 57 | return errors.New("logger is nil") 58 | } 59 | defaultLogger = logger 60 | return nil 61 | } 62 | 63 | // MySQLError is an error type which represents a single MySQL error 64 | type MySQLError struct { 65 | Number uint16 66 | SQLState [5]byte 67 | Message string 68 | } 69 | 70 | func (me *MySQLError) Error() string { 71 | if me.SQLState != [5]byte{} { 72 | return fmt.Sprintf("Error %d (%s): %s", me.Number, me.SQLState, me.Message) 73 | } 74 | 75 | return fmt.Sprintf("Error %d: %s", me.Number, me.Message) 76 | } 77 | 78 | func (me *MySQLError) Is(err error) bool { 79 | if merr, ok := err.(*MySQLError); ok { 80 | return merr.Number == me.Number 81 | } 82 | return false 83 | } 84 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: test 2 | on: 3 | pull_request: 4 | push: 5 | workflow_dispatch: 6 | 7 | env: 8 | MYSQL_TEST_USER: gotest 9 | MYSQL_TEST_PASS: secret 10 | MYSQL_TEST_ADDR: 127.0.0.1:3306 11 | MYSQL_TEST_CONCURRENT: 1 12 | 13 | jobs: 14 | lint: 15 | runs-on: ubuntu-latest 16 | steps: 17 | - uses: actions/checkout@v4 18 | - uses: dominikh/staticcheck-action@v1.3.1 19 | 20 | list: 21 | runs-on: ubuntu-latest 22 | outputs: 23 | matrix: ${{ steps.set-matrix.outputs.matrix }} 24 | steps: 25 | - name: list 26 | id: set-matrix 27 | run: | 28 | import json 29 | import os 30 | go = [ 31 | # Keep the most recent production release at the top 32 | '1.24', 33 | # Older production releases 34 | '1.23', 35 | '1.22', 36 | ] 37 | mysql = [ 38 | '9.0', 39 | '8.4', # LTS 40 | '8.0', 41 | '5.7', 42 | 'mariadb-11.4', # LTS 43 | 'mariadb-11.2', 44 | 'mariadb-11.1', 45 | 'mariadb-10.11', # LTS 46 | 'mariadb-10.6', # LTS 47 | 'mariadb-10.5', # LTS 48 | ] 49 | 50 | includes = [] 51 | # Go versions compatibility check 52 | for v in go[1:]: 53 | includes.append({'os': 'ubuntu-latest', 'go': v, 'mysql': mysql[0]}) 54 | 55 | matrix = { 56 | # OS vs MySQL versions 57 | 'os': [ 'ubuntu-latest', 'macos-latest', 'windows-latest' ], 58 | 'go': [ go[0] ], 59 | 'mysql': mysql, 60 | 61 | 'include': includes 62 | } 63 | output = json.dumps(matrix, separators=(',', ':')) 64 | with open(os.environ["GITHUB_OUTPUT"], 'a', encoding="utf-8") as f: 65 | print(f"matrix={output}", file=f) 66 | shell: python 67 | test: 68 | needs: list 69 | runs-on: ${{ matrix.os }} 70 | strategy: 71 | fail-fast: false 72 | matrix: ${{ fromJSON(needs.list.outputs.matrix) }} 73 | steps: 74 | - uses: actions/checkout@v4 75 | - uses: actions/setup-go@v5 76 | with: 77 | go-version: ${{ matrix.go }} 78 | - uses: shogo82148/actions-setup-mysql@v1 79 | with: 80 | mysql-version: ${{ matrix.mysql }} 81 | user: ${{ env.MYSQL_TEST_USER }} 82 | password: ${{ env.MYSQL_TEST_PASS }} 83 | my-cnf: | 84 | innodb_log_file_size=256MB 85 | innodb_buffer_pool_size=512MB 86 | max_allowed_packet=48MB 87 | ; TestConcurrent fails if max_connections is too large 88 | max_connections=50 89 | local_infile=1 90 | performance_schema=on 91 | - name: setup database 92 | run: | 93 | mysql --user 'root' --host '127.0.0.1' -e 'create database gotest;' 94 | 95 | - name: test 96 | run: | 97 | go test -v '-race' '-covermode=atomic' '-coverprofile=coverage.out' -parallel 10 98 | 99 | - name: benchmark 100 | run: | 101 | go test -run '^$' -bench . 102 | 103 | - name: Send coverage 104 | uses: shogo82148/actions-goveralls@v1 105 | with: 106 | path-to-profile: coverage.out 107 | flag-name: ${{ runner.os }}-Go-${{ matrix.go }}-DB-${{ matrix.mysql }} 108 | parallel: true 109 | 110 | # notifies that all test jobs are finished. 111 | finish: 112 | needs: test 113 | if: always() 114 | runs-on: ubuntu-latest 115 | steps: 116 | - uses: shogo82148/actions-goveralls@v1 117 | with: 118 | parallel-finished: true 119 | -------------------------------------------------------------------------------- /compress_test.go: -------------------------------------------------------------------------------- 1 | // Go MySQL Driver - A MySQL-Driver for Go's database/sql package 2 | // 3 | // Copyright 2024 The Go-MySQL-Driver Authors. All rights reserved. 4 | // 5 | // This Source Code Form is subject to the terms of the Mozilla Public 6 | // License, v. 2.0. If a copy of the MPL was not distributed with this file, 7 | // You can obtain one at http://mozilla.org/MPL/2.0/. 8 | 9 | package mysql 10 | 11 | import ( 12 | "bytes" 13 | "crypto/rand" 14 | "io" 15 | "testing" 16 | ) 17 | 18 | func makeRandByteSlice(size int) []byte { 19 | randBytes := make([]byte, size) 20 | rand.Read(randBytes) 21 | return randBytes 22 | } 23 | 24 | // compressHelper compresses uncompressedPacket and checks state variables 25 | func compressHelper(t *testing.T, mc *mysqlConn, uncompressedPacket []byte) []byte { 26 | conn := new(mockConn) 27 | mc.netConn = conn 28 | 29 | err := mc.writePacket(append(make([]byte, 4), uncompressedPacket...)) 30 | if err != nil { 31 | t.Fatal(err) 32 | } 33 | 34 | return conn.written 35 | } 36 | 37 | // uncompressHelper uncompresses compressedPacket and checks state variables 38 | func uncompressHelper(t *testing.T, mc *mysqlConn, compressedPacket []byte) []byte { 39 | // mocking out buf variable 40 | conn := new(mockConn) 41 | conn.data = compressedPacket 42 | mc.netConn = conn 43 | 44 | uncompressedPacket, err := mc.readPacket() 45 | if err != nil { 46 | if err != io.EOF { 47 | t.Fatalf("non-nil/non-EOF error when reading contents: %s", err.Error()) 48 | } 49 | } 50 | return uncompressedPacket 51 | } 52 | 53 | // roundtripHelper compresses then uncompresses uncompressedPacket and checks state variables 54 | func roundtripHelper(t *testing.T, cSend *mysqlConn, cReceive *mysqlConn, uncompressedPacket []byte) []byte { 55 | compressed := compressHelper(t, cSend, uncompressedPacket) 56 | return uncompressHelper(t, cReceive, compressed) 57 | } 58 | 59 | // TestRoundtrip tests two connections, where one is reading and the other is writing 60 | func TestRoundtrip(t *testing.T) { 61 | tests := []struct { 62 | uncompressed []byte 63 | desc string 64 | }{ 65 | {uncompressed: []byte("a"), 66 | desc: "a"}, 67 | {uncompressed: []byte("hello world"), 68 | desc: "hello world"}, 69 | {uncompressed: make([]byte, 100), 70 | desc: "100 bytes"}, 71 | {uncompressed: make([]byte, 32768), 72 | desc: "32768 bytes"}, 73 | {uncompressed: make([]byte, 330000), 74 | desc: "33000 bytes"}, 75 | {uncompressed: makeRandByteSlice(10), 76 | desc: "10 rand bytes", 77 | }, 78 | {uncompressed: makeRandByteSlice(100), 79 | desc: "100 rand bytes", 80 | }, 81 | {uncompressed: makeRandByteSlice(32768), 82 | desc: "32768 rand bytes", 83 | }, 84 | {uncompressed: bytes.Repeat(makeRandByteSlice(100), 10000), 85 | desc: "100 rand * 10000 repeat bytes", 86 | }, 87 | } 88 | 89 | _, cSend := newRWMockConn(0) 90 | cSend.compress = true 91 | cSend.compIO = newCompIO(cSend) 92 | _, cReceive := newRWMockConn(0) 93 | cReceive.compress = true 94 | cReceive.compIO = newCompIO(cReceive) 95 | 96 | for _, test := range tests { 97 | t.Run(test.desc, func(t *testing.T) { 98 | cSend.resetSequence() 99 | cReceive.resetSequence() 100 | 101 | uncompressed := roundtripHelper(t, cSend, cReceive, test.uncompressed) 102 | if len(uncompressed) != len(test.uncompressed) { 103 | t.Errorf("uncompressed size is unexpected. expected %d but got %d", 104 | len(test.uncompressed), len(uncompressed)) 105 | } 106 | if !bytes.Equal(uncompressed, test.uncompressed) { 107 | t.Errorf("roundtrip failed") 108 | } 109 | if cSend.sequence != cReceive.sequence { 110 | t.Errorf("inconsistent sequence number: send=%v recv=%v", 111 | cSend.sequence, cReceive.sequence) 112 | } 113 | if cSend.compressSequence != cReceive.compressSequence { 114 | t.Errorf("inconsistent compress sequence number: send=%v recv=%v", 115 | cSend.compressSequence, cReceive.compressSequence) 116 | } 117 | }) 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /statement_test.go: -------------------------------------------------------------------------------- 1 | // Go MySQL Driver - A MySQL-Driver for Go's database/sql package 2 | // 3 | // Copyright 2017 The Go-MySQL-Driver Authors. All rights reserved. 4 | // 5 | // This Source Code Form is subject to the terms of the Mozilla Public 6 | // License, v. 2.0. If a copy of the MPL was not distributed with this file, 7 | // You can obtain one at http://mozilla.org/MPL/2.0/. 8 | 9 | package mysql 10 | 11 | import ( 12 | "bytes" 13 | "database/sql/driver" 14 | "encoding/json" 15 | "testing" 16 | ) 17 | 18 | func TestConvertDerivedString(t *testing.T) { 19 | type derived string 20 | 21 | output, err := converter{}.ConvertValue(derived("value")) 22 | if err != nil { 23 | t.Fatal("Derived string type not convertible", err) 24 | } 25 | 26 | if output != "value" { 27 | t.Fatalf("Derived string type not converted, got %#v %T", output, output) 28 | } 29 | } 30 | 31 | func TestConvertDerivedByteSlice(t *testing.T) { 32 | type derived []uint8 33 | 34 | output, err := converter{}.ConvertValue(derived("value")) 35 | if err != nil { 36 | t.Fatal("Byte slice not convertible", err) 37 | } 38 | 39 | if !bytes.Equal(output.([]byte), []byte("value")) { 40 | t.Fatalf("Byte slice not converted, got %#v %T", output, output) 41 | } 42 | } 43 | 44 | func TestConvertDerivedUnsupportedSlice(t *testing.T) { 45 | type derived []int 46 | 47 | _, err := converter{}.ConvertValue(derived{1}) 48 | if err == nil || err.Error() != "unsupported type mysql.derived, a slice of int" { 49 | t.Fatal("Unexpected error", err) 50 | } 51 | } 52 | 53 | func TestConvertDerivedBool(t *testing.T) { 54 | type derived bool 55 | 56 | output, err := converter{}.ConvertValue(derived(true)) 57 | if err != nil { 58 | t.Fatal("Derived bool type not convertible", err) 59 | } 60 | 61 | if output != true { 62 | t.Fatalf("Derived bool type not converted, got %#v %T", output, output) 63 | } 64 | } 65 | 66 | func TestConvertPointer(t *testing.T) { 67 | str := "value" 68 | 69 | output, err := converter{}.ConvertValue(&str) 70 | if err != nil { 71 | t.Fatal("Pointer type not convertible", err) 72 | } 73 | 74 | if output != "value" { 75 | t.Fatalf("Pointer type not converted, got %#v %T", output, output) 76 | } 77 | } 78 | 79 | func TestConvertSignedIntegers(t *testing.T) { 80 | values := []any{ 81 | int8(-42), 82 | int16(-42), 83 | int32(-42), 84 | int64(-42), 85 | int(-42), 86 | } 87 | 88 | for _, value := range values { 89 | output, err := converter{}.ConvertValue(value) 90 | if err != nil { 91 | t.Fatalf("%T type not convertible %s", value, err) 92 | } 93 | 94 | if output != int64(-42) { 95 | t.Fatalf("%T type not converted, got %#v %T", value, output, output) 96 | } 97 | } 98 | } 99 | 100 | type myUint64 struct { 101 | value uint64 102 | } 103 | 104 | func (u myUint64) Value() (driver.Value, error) { 105 | return u.value, nil 106 | } 107 | 108 | func TestConvertUnsignedIntegers(t *testing.T) { 109 | values := []any{ 110 | uint8(42), 111 | uint16(42), 112 | uint32(42), 113 | uint64(42), 114 | uint(42), 115 | myUint64{uint64(42)}, 116 | } 117 | 118 | for _, value := range values { 119 | output, err := converter{}.ConvertValue(value) 120 | if err != nil { 121 | t.Fatalf("%T type not convertible %s", value, err) 122 | } 123 | 124 | if output != uint64(42) { 125 | t.Fatalf("%T type not converted, got %#v %T", value, output, output) 126 | } 127 | } 128 | 129 | output, err := converter{}.ConvertValue(^uint64(0)) 130 | if err != nil { 131 | t.Fatal("uint64 high-bit not convertible", err) 132 | } 133 | 134 | if output != ^uint64(0) { 135 | t.Fatalf("uint64 high-bit converted, got %#v %T", output, output) 136 | } 137 | } 138 | 139 | func TestConvertJSON(t *testing.T) { 140 | raw := json.RawMessage("{}") 141 | 142 | out, err := converter{}.ConvertValue(raw) 143 | 144 | if err != nil { 145 | t.Fatal("json.RawMessage was failed in convert", err) 146 | } 147 | 148 | if _, ok := out.(json.RawMessage); !ok { 149 | t.Fatalf("json.RawMessage converted, got %#v %T", out, out) 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /driver.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. 2 | // 3 | // This Source Code Form is subject to the terms of the Mozilla Public 4 | // License, v. 2.0. If a copy of the MPL was not distributed with this file, 5 | // You can obtain one at http://mozilla.org/MPL/2.0/. 6 | 7 | // Package mysql provides a MySQL driver for Go's database/sql package. 8 | // 9 | // The driver should be used via the database/sql package: 10 | // 11 | // import "database/sql" 12 | // import _ "github.com/go-sql-driver/mysql" 13 | // 14 | // db, err := sql.Open("mysql", "user:password@/dbname") 15 | // 16 | // See https://github.com/go-sql-driver/mysql#usage for details 17 | package mysql 18 | 19 | import ( 20 | "context" 21 | "database/sql" 22 | "database/sql/driver" 23 | "net" 24 | "sync" 25 | ) 26 | 27 | // MySQLDriver is exported to make the driver directly accessible. 28 | // In general the driver is used via the database/sql package. 29 | type MySQLDriver struct{} 30 | 31 | // DialFunc is a function which can be used to establish the network connection. 32 | // Custom dial functions must be registered with RegisterDial 33 | // 34 | // Deprecated: users should register a DialContextFunc instead 35 | type DialFunc func(addr string) (net.Conn, error) 36 | 37 | // DialContextFunc is a function which can be used to establish the network connection. 38 | // Custom dial functions must be registered with RegisterDialContext 39 | type DialContextFunc func(ctx context.Context, addr string) (net.Conn, error) 40 | 41 | var ( 42 | dialsLock sync.RWMutex 43 | dials map[string]DialContextFunc 44 | ) 45 | 46 | // RegisterDialContext registers a custom dial function. It can then be used by the 47 | // network address mynet(addr), where mynet is the registered new network. 48 | // The current context for the connection and its address is passed to the dial function. 49 | func RegisterDialContext(net string, dial DialContextFunc) { 50 | dialsLock.Lock() 51 | defer dialsLock.Unlock() 52 | if dials == nil { 53 | dials = make(map[string]DialContextFunc) 54 | } 55 | dials[net] = dial 56 | } 57 | 58 | // DeregisterDialContext removes the custom dial function registered with the given net. 59 | func DeregisterDialContext(net string) { 60 | dialsLock.Lock() 61 | defer dialsLock.Unlock() 62 | if dials != nil { 63 | delete(dials, net) 64 | } 65 | } 66 | 67 | // RegisterDial registers a custom dial function. It can then be used by the 68 | // network address mynet(addr), where mynet is the registered new network. 69 | // addr is passed as a parameter to the dial function. 70 | // 71 | // Deprecated: users should call RegisterDialContext instead 72 | func RegisterDial(network string, dial DialFunc) { 73 | RegisterDialContext(network, func(_ context.Context, addr string) (net.Conn, error) { 74 | return dial(addr) 75 | }) 76 | } 77 | 78 | // Open new Connection. 79 | // See https://github.com/go-sql-driver/mysql#dsn-data-source-name for how 80 | // the DSN string is formatted 81 | func (d MySQLDriver) Open(dsn string) (driver.Conn, error) { 82 | cfg, err := ParseDSN(dsn) 83 | if err != nil { 84 | return nil, err 85 | } 86 | c := newConnector(cfg) 87 | return c.Connect(context.Background()) 88 | } 89 | 90 | // This variable can be replaced with -ldflags like below: 91 | // go build "-ldflags=-X github.com/go-sql-driver/mysql.driverName=custom" 92 | var driverName = "mysql" 93 | 94 | func init() { 95 | if driverName != "" { 96 | sql.Register(driverName, &MySQLDriver{}) 97 | } 98 | } 99 | 100 | // NewConnector returns new driver.Connector. 101 | func NewConnector(cfg *Config) (driver.Connector, error) { 102 | cfg = cfg.Clone() 103 | // normalize the contents of cfg so calls to NewConnector have the same 104 | // behavior as MySQLDriver.OpenConnector 105 | if err := cfg.normalize(); err != nil { 106 | return nil, err 107 | } 108 | return newConnector(cfg), nil 109 | } 110 | 111 | // OpenConnector implements driver.DriverContext. 112 | func (d MySQLDriver) OpenConnector(dsn string) (driver.Connector, error) { 113 | cfg, err := ParseDSN(dsn) 114 | if err != nil { 115 | return nil, err 116 | } 117 | return newConnector(cfg), nil 118 | } 119 | -------------------------------------------------------------------------------- /buffer.go: -------------------------------------------------------------------------------- 1 | // Go MySQL Driver - A MySQL-Driver for Go's database/sql package 2 | // 3 | // Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. 4 | // 5 | // This Source Code Form is subject to the terms of the Mozilla Public 6 | // License, v. 2.0. If a copy of the MPL was not distributed with this file, 7 | // You can obtain one at http://mozilla.org/MPL/2.0/. 8 | 9 | package mysql 10 | 11 | import ( 12 | "io" 13 | ) 14 | 15 | const defaultBufSize = 4096 16 | const maxCachedBufSize = 256 * 1024 17 | 18 | // readerFunc is a function that compatible with io.Reader. 19 | // We use this function type instead of io.Reader because we want to 20 | // just pass mc.readWithTimeout. 21 | type readerFunc func([]byte) (int, error) 22 | 23 | // A buffer which is used for both reading and writing. 24 | // This is possible since communication on each connection is synchronous. 25 | // In other words, we can't write and read simultaneously on the same connection. 26 | // The buffer is similar to bufio.Reader / Writer but zero-copy-ish 27 | // Also highly optimized for this particular use case. 28 | type buffer struct { 29 | buf []byte // read buffer. 30 | cachedBuf []byte // buffer that will be reused. len(cachedBuf) <= maxCachedBufSize. 31 | } 32 | 33 | // newBuffer allocates and returns a new buffer. 34 | func newBuffer() buffer { 35 | return buffer{ 36 | cachedBuf: make([]byte, defaultBufSize), 37 | } 38 | } 39 | 40 | // busy returns true if the read buffer is not empty. 41 | func (b *buffer) busy() bool { 42 | return len(b.buf) > 0 43 | } 44 | 45 | // len returns how many bytes in the read buffer. 46 | func (b *buffer) len() int { 47 | return len(b.buf) 48 | } 49 | 50 | // fill reads into the read buffer until at least _need_ bytes are in it. 51 | func (b *buffer) fill(need int, r readerFunc) error { 52 | // we'll move the contents of the current buffer to dest before filling it. 53 | dest := b.cachedBuf 54 | 55 | // grow buffer if necessary to fit the whole packet. 56 | if need > len(dest) { 57 | // Round up to the next multiple of the default size 58 | dest = make([]byte, ((need/defaultBufSize)+1)*defaultBufSize) 59 | 60 | // if the allocated buffer is not too large, move it to backing storage 61 | // to prevent extra allocations on applications that perform large reads 62 | if len(dest) <= maxCachedBufSize { 63 | b.cachedBuf = dest 64 | } 65 | } 66 | 67 | // move the existing data to the start of the buffer. 68 | n := len(b.buf) 69 | copy(dest[:n], b.buf) 70 | 71 | for { 72 | nn, err := r(dest[n:]) 73 | n += nn 74 | 75 | if err == nil && n < need { 76 | continue 77 | } 78 | 79 | b.buf = dest[:n] 80 | 81 | if err == io.EOF { 82 | if n < need { 83 | err = io.ErrUnexpectedEOF 84 | } else { 85 | err = nil 86 | } 87 | } 88 | return err 89 | } 90 | } 91 | 92 | // returns next N bytes from buffer. 93 | // The returned slice is only guaranteed to be valid until the next read 94 | func (b *buffer) readNext(need int) []byte { 95 | data := b.buf[:need:need] 96 | b.buf = b.buf[need:] 97 | return data 98 | } 99 | 100 | // takeBuffer returns a buffer with the requested size. 101 | // If possible, a slice from the existing buffer is returned. 102 | // Otherwise a bigger buffer is made. 103 | // Only one buffer (total) can be used at a time. 104 | func (b *buffer) takeBuffer(length int) ([]byte, error) { 105 | if b.busy() { 106 | return nil, ErrBusyBuffer 107 | } 108 | 109 | // test (cheap) general case first 110 | if length <= len(b.cachedBuf) { 111 | return b.cachedBuf[:length], nil 112 | } 113 | 114 | if length < maxCachedBufSize { 115 | b.cachedBuf = make([]byte, length) 116 | return b.cachedBuf, nil 117 | } 118 | 119 | // buffer is larger than we want to store. 120 | return make([]byte, length), nil 121 | } 122 | 123 | // takeSmallBuffer is shortcut which can be used if length is 124 | // known to be smaller than defaultBufSize. 125 | // Only one buffer (total) can be used at a time. 126 | func (b *buffer) takeSmallBuffer(length int) ([]byte, error) { 127 | if b.busy() { 128 | return nil, ErrBusyBuffer 129 | } 130 | return b.cachedBuf[:length], nil 131 | } 132 | 133 | // takeCompleteBuffer returns the complete existing buffer. 134 | // This can be used if the necessary buffer size is unknown. 135 | // cap and len of the returned buffer will be equal. 136 | // Only one buffer (total) can be used at a time. 137 | func (b *buffer) takeCompleteBuffer() ([]byte, error) { 138 | if b.busy() { 139 | return nil, ErrBusyBuffer 140 | } 141 | return b.cachedBuf, nil 142 | } 143 | 144 | // store stores buf, an updated buffer, if its suitable to do so. 145 | func (b *buffer) store(buf []byte) { 146 | if cap(buf) <= maxCachedBufSize && cap(buf) > cap(b.cachedBuf) { 147 | b.cachedBuf = buf[:cap(buf)] 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /const.go: -------------------------------------------------------------------------------- 1 | // Go MySQL Driver - A MySQL-Driver for Go's database/sql package 2 | // 3 | // Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. 4 | // 5 | // This Source Code Form is subject to the terms of the Mozilla Public 6 | // License, v. 2.0. If a copy of the MPL was not distributed with this file, 7 | // You can obtain one at http://mozilla.org/MPL/2.0/. 8 | 9 | package mysql 10 | 11 | import "runtime" 12 | 13 | const ( 14 | debug = false // for debugging. Set true only in development. 15 | 16 | defaultAuthPlugin = "mysql_native_password" 17 | defaultMaxAllowedPacket = 64 << 20 // 64 MiB. See https://github.com/go-sql-driver/mysql/issues/1355 18 | minProtocolVersion = 10 19 | maxPacketSize = 1<<24 - 1 20 | timeFormat = "2006-01-02 15:04:05.999999" 21 | 22 | // Connection attributes 23 | // See https://dev.mysql.com/doc/refman/8.0/en/performance-schema-connection-attribute-tables.html#performance-schema-connection-attributes-available 24 | connAttrClientName = "_client_name" 25 | connAttrClientNameValue = "Go-MySQL-Driver" 26 | connAttrOS = "_os" 27 | connAttrOSValue = runtime.GOOS 28 | connAttrPlatform = "_platform" 29 | connAttrPlatformValue = runtime.GOARCH 30 | connAttrPid = "_pid" 31 | connAttrServerHost = "_server_host" 32 | ) 33 | 34 | // MySQL constants documentation: 35 | // https://dev.mysql.com/doc/dev/mysql-server/latest/PAGE_PROTOCOL.html 36 | 37 | const ( 38 | iOK byte = 0x00 39 | iAuthMoreData byte = 0x01 40 | iLocalInFile byte = 0xfb 41 | iEOF byte = 0xfe 42 | iERR byte = 0xff 43 | ) 44 | 45 | // https://dev.mysql.com/doc/dev/mysql-server/latest/group__group__cs__capabilities__flags.html 46 | // https://mariadb.com/kb/en/connection/#capabilities 47 | type capabilityFlag uint32 48 | 49 | const ( 50 | clientMySQL capabilityFlag = 1 << iota 51 | clientFoundRows 52 | clientLongFlag 53 | clientConnectWithDB 54 | clientNoSchema 55 | clientCompress 56 | clientODBC 57 | clientLocalFiles 58 | clientIgnoreSpace 59 | clientProtocol41 60 | clientInteractive 61 | clientSSL 62 | clientIgnoreSIGPIPE 63 | clientTransactions 64 | clientReserved 65 | clientSecureConn 66 | clientMultiStatements 67 | clientMultiResults 68 | clientPSMultiResults 69 | clientPluginAuth 70 | clientConnectAttrs 71 | clientPluginAuthLenEncClientData 72 | clientCanHandleExpiredPasswords 73 | clientSessionTrack 74 | clientDeprecateEOF 75 | ) 76 | 77 | // https://mariadb.com/kb/en/connection/#capabilities 78 | type extendedCapabilityFlag uint32 79 | 80 | const ( 81 | progressIndicator extendedCapabilityFlag = 1 << iota 82 | clientComMulti 83 | clientStmtBulkOperations 84 | clientExtendedMetadata 85 | clientCacheMetadata 86 | clientUnitBulkResult 87 | ) 88 | 89 | const ( 90 | comQuit byte = iota + 1 91 | comInitDB 92 | comQuery 93 | comFieldList 94 | comCreateDB 95 | comDropDB 96 | comRefresh 97 | comShutdown 98 | comStatistics 99 | comProcessInfo 100 | comConnect 101 | comProcessKill 102 | comDebug 103 | comPing 104 | comTime 105 | comDelayedInsert 106 | comChangeUser 107 | comBinlogDump 108 | comTableDump 109 | comConnectOut 110 | comRegisterSlave 111 | comStmtPrepare 112 | comStmtExecute 113 | comStmtSendLongData 114 | comStmtClose 115 | comStmtReset 116 | comSetOption 117 | comStmtFetch 118 | ) 119 | 120 | // https://dev.mysql.com/doc/internals/en/com-query-response.html#packet-Protocol::ColumnType 121 | type fieldType byte 122 | 123 | const ( 124 | fieldTypeDecimal fieldType = iota 125 | fieldTypeTiny 126 | fieldTypeShort 127 | fieldTypeLong 128 | fieldTypeFloat 129 | fieldTypeDouble 130 | fieldTypeNULL 131 | fieldTypeTimestamp 132 | fieldTypeLongLong 133 | fieldTypeInt24 134 | fieldTypeDate 135 | fieldTypeTime 136 | fieldTypeDateTime 137 | fieldTypeYear 138 | fieldTypeNewDate 139 | fieldTypeVarChar 140 | fieldTypeBit 141 | ) 142 | const ( 143 | fieldTypeVector fieldType = iota + 0xf2 144 | fieldTypeInvalid 145 | fieldTypeBool 146 | fieldTypeJSON 147 | fieldTypeNewDecimal 148 | fieldTypeEnum 149 | fieldTypeSet 150 | fieldTypeTinyBLOB 151 | fieldTypeMediumBLOB 152 | fieldTypeLongBLOB 153 | fieldTypeBLOB 154 | fieldTypeVarString 155 | fieldTypeString 156 | fieldTypeGeometry 157 | ) 158 | 159 | type fieldFlag uint16 160 | 161 | const ( 162 | flagNotNULL fieldFlag = 1 << iota 163 | flagPriKey 164 | flagUniqueKey 165 | flagMultipleKey 166 | flagBLOB 167 | flagUnsigned 168 | flagZeroFill 169 | flagBinary 170 | flagEnum 171 | flagAutoIncrement 172 | flagTimestamp 173 | flagSet 174 | flagUnknown1 175 | flagUnknown2 176 | flagUnknown3 177 | flagUnknown4 178 | ) 179 | 180 | // http://dev.mysql.com/doc/internals/en/status-flags.html 181 | type statusFlag uint16 182 | 183 | const ( 184 | statusInTrans statusFlag = 1 << iota 185 | statusInAutocommit 186 | statusReserved // Not in documentation 187 | statusMoreResultsExists 188 | statusNoGoodIndexUsed 189 | statusNoIndexUsed 190 | statusCursorExists 191 | statusLastRowSent 192 | statusDbDropped 193 | statusNoBackslashEscapes 194 | statusMetadataChanged 195 | statusQueryWasSlow 196 | statusPsOutParams 197 | statusInTransReadonly 198 | statusSessionStateChanged 199 | ) 200 | 201 | const ( 202 | cachingSha2PasswordRequestPublicKey = 2 203 | cachingSha2PasswordFastAuthSuccess = 3 204 | cachingSha2PasswordPerformFullAuthentication = 4 205 | ) 206 | -------------------------------------------------------------------------------- /infile.go: -------------------------------------------------------------------------------- 1 | // Go MySQL Driver - A MySQL-Driver for Go's database/sql package 2 | // 3 | // Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. 4 | // 5 | // This Source Code Form is subject to the terms of the Mozilla Public 6 | // License, v. 2.0. If a copy of the MPL was not distributed with this file, 7 | // You can obtain one at http://mozilla.org/MPL/2.0/. 8 | 9 | package mysql 10 | 11 | import ( 12 | "fmt" 13 | "io" 14 | "os" 15 | "strings" 16 | "sync" 17 | ) 18 | 19 | var ( 20 | fileRegister map[string]struct{} 21 | fileRegisterLock sync.RWMutex 22 | readerRegister map[string]func() io.Reader 23 | readerRegisterLock sync.RWMutex 24 | ) 25 | 26 | // RegisterLocalFile adds the given file to the file allowlist, 27 | // so that it can be used by "LOAD DATA LOCAL INFILE ". 28 | // Alternatively you can allow the use of all local files with 29 | // the DSN parameter 'allowAllFiles=true' 30 | // 31 | // filePath := "/home/gopher/data.csv" 32 | // mysql.RegisterLocalFile(filePath) 33 | // err := db.Exec("LOAD DATA LOCAL INFILE '" + filePath + "' INTO TABLE foo") 34 | // if err != nil { 35 | // ... 36 | func RegisterLocalFile(filePath string) { 37 | fileRegisterLock.Lock() 38 | // lazy map init 39 | if fileRegister == nil { 40 | fileRegister = make(map[string]struct{}) 41 | } 42 | 43 | fileRegister[strings.Trim(filePath, `"`)] = struct{}{} 44 | fileRegisterLock.Unlock() 45 | } 46 | 47 | // DeregisterLocalFile removes the given filepath from the allowlist. 48 | func DeregisterLocalFile(filePath string) { 49 | fileRegisterLock.Lock() 50 | delete(fileRegister, strings.Trim(filePath, `"`)) 51 | fileRegisterLock.Unlock() 52 | } 53 | 54 | // RegisterReaderHandler registers a handler function which is used 55 | // to receive a io.Reader. 56 | // The Reader can be used by "LOAD DATA LOCAL INFILE Reader::". 57 | // If the handler returns a io.ReadCloser Close() is called when the 58 | // request is finished. 59 | // 60 | // mysql.RegisterReaderHandler("data", func() io.Reader { 61 | // var csvReader io.Reader // Some Reader that returns CSV data 62 | // ... // Open Reader here 63 | // return csvReader 64 | // }) 65 | // err := db.Exec("LOAD DATA LOCAL INFILE 'Reader::data' INTO TABLE foo") 66 | // if err != nil { 67 | // ... 68 | func RegisterReaderHandler(name string, handler func() io.Reader) { 69 | readerRegisterLock.Lock() 70 | // lazy map init 71 | if readerRegister == nil { 72 | readerRegister = make(map[string]func() io.Reader) 73 | } 74 | 75 | readerRegister[name] = handler 76 | readerRegisterLock.Unlock() 77 | } 78 | 79 | // DeregisterReaderHandler removes the ReaderHandler function with 80 | // the given name from the registry. 81 | func DeregisterReaderHandler(name string) { 82 | readerRegisterLock.Lock() 83 | delete(readerRegister, name) 84 | readerRegisterLock.Unlock() 85 | } 86 | 87 | func deferredClose(err *error, closer io.Closer) { 88 | closeErr := closer.Close() 89 | if *err == nil { 90 | *err = closeErr 91 | } 92 | } 93 | 94 | const defaultPacketSize = 16 * 1024 // 16KB is small enough for disk readahead and large enough for TCP 95 | 96 | func (mc *okHandler) handleInFileRequest(name string) (err error) { 97 | var rdr io.Reader 98 | packetSize := min(mc.maxWriteSize, defaultPacketSize) 99 | 100 | if idx := strings.Index(name, "Reader::"); idx == 0 || (idx > 0 && name[idx-1] == '/') { // io.Reader 101 | // The server might return an an absolute path. See issue #355. 102 | name = name[idx+8:] 103 | 104 | readerRegisterLock.RLock() 105 | handler, inMap := readerRegister[name] 106 | readerRegisterLock.RUnlock() 107 | 108 | if inMap { 109 | rdr = handler() 110 | if rdr != nil { 111 | if cl, ok := rdr.(io.Closer); ok { 112 | defer deferredClose(&err, cl) 113 | } 114 | } else { 115 | err = fmt.Errorf("reader '%s' is ", name) 116 | } 117 | } else { 118 | err = fmt.Errorf("reader '%s' is not registered", name) 119 | } 120 | } else { // File 121 | name = strings.Trim(name, `"`) 122 | fileRegisterLock.RLock() 123 | _, exists := fileRegister[name] 124 | fileRegisterLock.RUnlock() 125 | if mc.cfg.AllowAllFiles || exists { 126 | var file *os.File 127 | var fi os.FileInfo 128 | 129 | if file, err = os.Open(name); err == nil { 130 | defer deferredClose(&err, file) 131 | 132 | // get file size 133 | if fi, err = file.Stat(); err == nil { 134 | rdr = file 135 | if fileSize := int(fi.Size()); fileSize < packetSize { 136 | packetSize = fileSize 137 | } 138 | } 139 | } 140 | } else { 141 | err = fmt.Errorf("local file '%s' is not registered", name) 142 | } 143 | } 144 | 145 | // send content packets 146 | var data []byte 147 | 148 | // if packetSize == 0, the Reader contains no data 149 | if err == nil && packetSize > 0 { 150 | data = make([]byte, 4+packetSize) 151 | var n int 152 | for err == nil { 153 | n, err = rdr.Read(data[4:]) 154 | if n > 0 { 155 | if ioErr := mc.conn().writePacket(data[:4+n]); ioErr != nil { 156 | return ioErr 157 | } 158 | } 159 | } 160 | if err == io.EOF { 161 | err = nil 162 | } 163 | } 164 | 165 | // send empty packet (termination) 166 | if data == nil { 167 | data = make([]byte, 4) 168 | } 169 | if ioErr := mc.conn().writePacket(data[:4]); ioErr != nil { 170 | return ioErr 171 | } 172 | mc.conn().syncSequence() 173 | 174 | // read OK packet 175 | if err == nil { 176 | return mc.readResultOK() 177 | } 178 | 179 | mc.conn().readPacket() 180 | return err 181 | } 182 | -------------------------------------------------------------------------------- /rows.go: -------------------------------------------------------------------------------- 1 | // Go MySQL Driver - A MySQL-Driver for Go's database/sql package 2 | // 3 | // Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. 4 | // 5 | // This Source Code Form is subject to the terms of the Mozilla Public 6 | // License, v. 2.0. If a copy of the MPL was not distributed with this file, 7 | // You can obtain one at http://mozilla.org/MPL/2.0/. 8 | 9 | package mysql 10 | 11 | import ( 12 | "database/sql/driver" 13 | "io" 14 | "math" 15 | "reflect" 16 | ) 17 | 18 | type resultSet struct { 19 | columns []mysqlField 20 | columnNames []string 21 | done bool 22 | } 23 | 24 | type mysqlRows struct { 25 | mc *mysqlConn 26 | rs resultSet 27 | finish func() 28 | } 29 | 30 | type binaryRows struct { 31 | mysqlRows 32 | } 33 | 34 | type textRows struct { 35 | mysqlRows 36 | } 37 | 38 | func (rows *mysqlRows) Columns() []string { 39 | if rows.rs.columnNames != nil { 40 | return rows.rs.columnNames 41 | } 42 | 43 | columns := make([]string, len(rows.rs.columns)) 44 | if rows.mc != nil && rows.mc.cfg.ColumnsWithAlias { 45 | for i := range columns { 46 | if tableName := rows.rs.columns[i].tableName; len(tableName) > 0 { 47 | columns[i] = tableName + "." + rows.rs.columns[i].name 48 | } else { 49 | columns[i] = rows.rs.columns[i].name 50 | } 51 | } 52 | } else { 53 | for i := range columns { 54 | columns[i] = rows.rs.columns[i].name 55 | } 56 | } 57 | 58 | rows.rs.columnNames = columns 59 | return columns 60 | } 61 | 62 | func (rows *mysqlRows) ColumnTypeDatabaseTypeName(i int) string { 63 | return rows.rs.columns[i].typeDatabaseName() 64 | } 65 | 66 | // func (rows *mysqlRows) ColumnTypeLength(i int) (length int64, ok bool) { 67 | // return int64(rows.rs.columns[i].length), true 68 | // } 69 | 70 | func (rows *mysqlRows) ColumnTypeNullable(i int) (nullable, ok bool) { 71 | return rows.rs.columns[i].flags&flagNotNULL == 0, true 72 | } 73 | 74 | func (rows *mysqlRows) ColumnTypePrecisionScale(i int) (int64, int64, bool) { 75 | column := rows.rs.columns[i] 76 | decimals := int64(column.decimals) 77 | 78 | switch column.fieldType { 79 | case fieldTypeDecimal, fieldTypeNewDecimal: 80 | if decimals > 0 { 81 | return int64(column.length) - 2, decimals, true 82 | } 83 | return int64(column.length) - 1, decimals, true 84 | case fieldTypeTimestamp, fieldTypeDateTime, fieldTypeTime: 85 | return decimals, decimals, true 86 | case fieldTypeFloat, fieldTypeDouble: 87 | if decimals == 0x1f { 88 | return math.MaxInt64, math.MaxInt64, true 89 | } 90 | return math.MaxInt64, decimals, true 91 | } 92 | 93 | return 0, 0, false 94 | } 95 | 96 | func (rows *mysqlRows) ColumnTypeScanType(i int) reflect.Type { 97 | return rows.rs.columns[i].scanType() 98 | } 99 | 100 | func (rows *mysqlRows) Close() (err error) { 101 | if f := rows.finish; f != nil { 102 | f() 103 | rows.finish = nil 104 | } 105 | 106 | mc := rows.mc 107 | if mc == nil { 108 | return nil 109 | } 110 | if err := mc.error(); err != nil { 111 | return err 112 | } 113 | 114 | // Remove unread packets from stream 115 | if !rows.rs.done { 116 | err = mc.skipRows() 117 | } 118 | if err == nil { 119 | handleOk := mc.clearResult() 120 | if err = handleOk.discardResults(); err != nil { 121 | return err 122 | } 123 | } 124 | 125 | rows.mc = nil 126 | return err 127 | } 128 | 129 | func (rows *mysqlRows) HasNextResultSet() (b bool) { 130 | if rows.mc == nil { 131 | return false 132 | } 133 | return rows.mc.status&statusMoreResultsExists != 0 134 | } 135 | 136 | func (rows *mysqlRows) nextResultSet() (int, error) { 137 | if rows.mc == nil { 138 | return 0, io.EOF 139 | } 140 | if err := rows.mc.error(); err != nil { 141 | return 0, err 142 | } 143 | 144 | // Remove unread packets from stream 145 | if !rows.rs.done { 146 | if err := rows.mc.skipRows(); err != nil { 147 | return 0, err 148 | } 149 | rows.rs.done = true 150 | } 151 | 152 | if !rows.HasNextResultSet() { 153 | rows.mc = nil 154 | return 0, io.EOF 155 | } 156 | rows.rs = resultSet{} 157 | // rows.mc.affectedRows and rows.mc.insertIds accumulate on each call to 158 | // nextResultSet. 159 | resLen, _, err := rows.mc.resultUnchanged().readResultSetHeaderPacket() 160 | if err != nil { 161 | // Clean up about multi-results flag 162 | rows.rs.done = true 163 | rows.mc.status = rows.mc.status & (^statusMoreResultsExists) 164 | } 165 | return resLen, err 166 | } 167 | 168 | func (rows *mysqlRows) nextNotEmptyResultSet() (int, error) { 169 | for { 170 | resLen, err := rows.nextResultSet() 171 | if err != nil { 172 | return 0, err 173 | } 174 | 175 | if resLen > 0 { 176 | return resLen, nil 177 | } 178 | 179 | rows.rs.done = true 180 | } 181 | } 182 | 183 | func (rows *binaryRows) NextResultSet() error { 184 | resLen, err := rows.nextNotEmptyResultSet() 185 | if err != nil { 186 | return err 187 | } 188 | 189 | rows.rs.columns, err = rows.mc.readColumns(resLen, nil) 190 | return err 191 | } 192 | 193 | func (rows *binaryRows) Next(dest []driver.Value) error { 194 | if mc := rows.mc; mc != nil { 195 | if err := mc.error(); err != nil { 196 | return err 197 | } 198 | 199 | // Fetch next row from stream 200 | return rows.readRow(dest) 201 | } 202 | return io.EOF 203 | } 204 | 205 | func (rows *textRows) NextResultSet() (err error) { 206 | resLen, err := rows.nextNotEmptyResultSet() 207 | if err != nil { 208 | return err 209 | } 210 | 211 | rows.rs.columns, err = rows.mc.readColumns(resLen, nil) 212 | return err 213 | } 214 | 215 | func (rows *textRows) Next(dest []driver.Value) error { 216 | if mc := rows.mc; mc != nil { 217 | if err := mc.error(); err != nil { 218 | return err 219 | } 220 | 221 | // Fetch next row from stream 222 | return rows.readRow(dest) 223 | } 224 | return io.EOF 225 | } 226 | -------------------------------------------------------------------------------- /connection_test.go: -------------------------------------------------------------------------------- 1 | // Go MySQL Driver - A MySQL-Driver for Go's database/sql package 2 | // 3 | // Copyright 2016 The Go-MySQL-Driver Authors. All rights reserved. 4 | // 5 | // This Source Code Form is subject to the terms of the Mozilla Public 6 | // License, v. 2.0. If a copy of the MPL was not distributed with this file, 7 | // You can obtain one at http://mozilla.org/MPL/2.0/. 8 | 9 | package mysql 10 | 11 | import ( 12 | "context" 13 | "database/sql/driver" 14 | "encoding/json" 15 | "errors" 16 | "net" 17 | "testing" 18 | ) 19 | 20 | func TestInterpolateParams(t *testing.T) { 21 | mc := &mysqlConn{ 22 | buf: newBuffer(), 23 | maxAllowedPacket: maxPacketSize, 24 | cfg: &Config{ 25 | InterpolateParams: true, 26 | }, 27 | } 28 | 29 | q, err := mc.interpolateParams("SELECT ?+?", []driver.Value{int64(42), "gopher"}) 30 | if err != nil { 31 | t.Errorf("Expected err=nil, got %#v", err) 32 | return 33 | } 34 | expected := `SELECT 42+'gopher'` 35 | if q != expected { 36 | t.Errorf("Expected: %q\nGot: %q", expected, q) 37 | } 38 | } 39 | 40 | func TestInterpolateParamsJSONRawMessage(t *testing.T) { 41 | mc := &mysqlConn{ 42 | buf: newBuffer(), 43 | maxAllowedPacket: maxPacketSize, 44 | cfg: &Config{ 45 | InterpolateParams: true, 46 | }, 47 | } 48 | 49 | buf, err := json.Marshal(struct { 50 | Value int `json:"value"` 51 | }{Value: 42}) 52 | if err != nil { 53 | t.Errorf("Expected err=nil, got %#v", err) 54 | return 55 | } 56 | q, err := mc.interpolateParams("SELECT ?", []driver.Value{json.RawMessage(buf)}) 57 | if err != nil { 58 | t.Errorf("Expected err=nil, got %#v", err) 59 | return 60 | } 61 | expected := `SELECT '{\"value\":42}'` 62 | if q != expected { 63 | t.Errorf("Expected: %q\nGot: %q", expected, q) 64 | } 65 | } 66 | 67 | func TestInterpolateParamsTooManyPlaceholders(t *testing.T) { 68 | mc := &mysqlConn{ 69 | buf: newBuffer(), 70 | maxAllowedPacket: maxPacketSize, 71 | cfg: &Config{ 72 | InterpolateParams: true, 73 | }, 74 | } 75 | 76 | q, err := mc.interpolateParams("SELECT ?+?", []driver.Value{int64(42)}) 77 | if err != driver.ErrSkip { 78 | t.Errorf("Expected err=driver.ErrSkip, got err=%#v, q=%#v", err, q) 79 | } 80 | } 81 | 82 | // We don't support placeholder in string literal for now. 83 | // https://github.com/go-sql-driver/mysql/pull/490 84 | func TestInterpolateParamsPlaceholderInString(t *testing.T) { 85 | mc := &mysqlConn{ 86 | buf: newBuffer(), 87 | maxAllowedPacket: maxPacketSize, 88 | cfg: &Config{ 89 | InterpolateParams: true, 90 | }, 91 | } 92 | 93 | q, err := mc.interpolateParams("SELECT 'abc?xyz',?", []driver.Value{int64(42)}) 94 | // When InterpolateParams support string literal, this should return `"SELECT 'abc?xyz', 42` 95 | if err != driver.ErrSkip { 96 | t.Errorf("Expected err=driver.ErrSkip, got err=%#v, q=%#v", err, q) 97 | } 98 | } 99 | 100 | func TestInterpolateParamsUint64(t *testing.T) { 101 | mc := &mysqlConn{ 102 | buf: newBuffer(), 103 | maxAllowedPacket: maxPacketSize, 104 | cfg: &Config{ 105 | InterpolateParams: true, 106 | }, 107 | } 108 | 109 | q, err := mc.interpolateParams("SELECT ?", []driver.Value{uint64(42)}) 110 | if err != nil { 111 | t.Errorf("Expected err=nil, got err=%#v, q=%#v", err, q) 112 | } 113 | if q != "SELECT 42" { 114 | t.Errorf("Expected uint64 interpolation to work, got q=%#v", q) 115 | } 116 | } 117 | 118 | func TestCheckNamedValue(t *testing.T) { 119 | value := driver.NamedValue{Value: ^uint64(0)} 120 | mc := &mysqlConn{} 121 | err := mc.CheckNamedValue(&value) 122 | 123 | if err != nil { 124 | t.Fatal("uint64 high-bit not convertible", err) 125 | } 126 | 127 | if value.Value != ^uint64(0) { 128 | t.Fatalf("uint64 high-bit converted, got %#v %T", value.Value, value.Value) 129 | } 130 | } 131 | 132 | // TestCleanCancel tests passed context is cancelled at start. 133 | // No packet should be sent. Connection should keep current status. 134 | func TestCleanCancel(t *testing.T) { 135 | mc := &mysqlConn{ 136 | closech: make(chan struct{}), 137 | } 138 | mc.startWatcher() 139 | defer mc.cleanup() 140 | 141 | ctx, cancel := context.WithCancel(context.Background()) 142 | cancel() 143 | 144 | for range 3 { // Repeat same behavior 145 | err := mc.Ping(ctx) 146 | if err != context.Canceled { 147 | t.Errorf("expected context.Canceled, got %#v", err) 148 | } 149 | 150 | if mc.closed.Load() { 151 | t.Error("expected mc is not closed, closed actually") 152 | } 153 | 154 | if mc.watching { 155 | t.Error("expected watching is false, but true") 156 | } 157 | } 158 | } 159 | 160 | func TestPingMarkBadConnection(t *testing.T) { 161 | nc := badConnection{err: errors.New("boom")} 162 | mc := &mysqlConn{ 163 | netConn: nc, 164 | buf: newBuffer(), 165 | maxAllowedPacket: defaultMaxAllowedPacket, 166 | closech: make(chan struct{}), 167 | cfg: NewConfig(), 168 | } 169 | 170 | err := mc.Ping(context.Background()) 171 | 172 | if err != driver.ErrBadConn { 173 | t.Errorf("expected driver.ErrBadConn, got %#v", err) 174 | } 175 | } 176 | 177 | func TestPingErrInvalidConn(t *testing.T) { 178 | nc := badConnection{err: errors.New("failed to write"), n: 10} 179 | mc := &mysqlConn{ 180 | netConn: nc, 181 | buf: newBuffer(), 182 | maxAllowedPacket: defaultMaxAllowedPacket, 183 | closech: make(chan struct{}), 184 | cfg: NewConfig(), 185 | } 186 | 187 | err := mc.Ping(context.Background()) 188 | 189 | if err != nc.err { 190 | t.Errorf("expected %#v, got %#v", nc.err, err) 191 | } 192 | } 193 | 194 | type badConnection struct { 195 | n int 196 | err error 197 | net.Conn 198 | } 199 | 200 | func (bc badConnection) Write(b []byte) (n int, err error) { 201 | return bc.n, bc.err 202 | } 203 | 204 | func (bc badConnection) Close() error { 205 | return nil 206 | } 207 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | # This is the official list of Go-MySQL-Driver authors for copyright purposes. 2 | 3 | # If you are submitting a patch, please add your name or the name of the 4 | # organization which holds the copyright to this list in alphabetical order. 5 | 6 | # Names should be added to this file as 7 | # Name 8 | # The email address is not required for organizations. 9 | # Please keep the list sorted. 10 | 11 | 12 | # Individual Persons 13 | 14 | Aaron Hopkins 15 | Achille Roussel 16 | Aidan 17 | Alex Snast 18 | Alexey Palazhchenko 19 | Andrew Reid 20 | Animesh Ray 21 | Ariel Mashraki 22 | Arne Hormann 23 | Artur Melanchyk 24 | Asta Xie 25 | B Lamarche 26 | Bes Dollma 27 | Bogdan Constantinescu 28 | Brad Higgins 29 | Brian Hendriks 30 | Bulat Gaifullin 31 | Caine Jette 32 | Carlos Nieto 33 | Chris Kirkland 34 | Chris Moos 35 | Craig Wilson 36 | Daemonxiao <735462752 at qq.com> 37 | Daniel Montoya 38 | Daniel Nichter 39 | Daniël van Eeden 40 | Dave Protasowski 41 | Demouth 42 | Diego Dupin 43 | Dirkjan Bussink 44 | DisposaBoy 45 | Egor Smolyakov 46 | Erwan Martin 47 | Evan Elias 48 | Evan Shaw 49 | Frederick Mayle 50 | Gustavo Kristic 51 | Gusted 52 | Hajime Nakagami 53 | Hanno Braun 54 | Henri Yandell 55 | Hirotaka Yamamoto 56 | Huyiguang 57 | ICHINOSE Shogo 58 | Ilia Cimpoes 59 | INADA Naoki 60 | Jacek Szwec 61 | Jakub Adamus 62 | James Harr 63 | Janek Vedock 64 | Jason Ng 65 | Jean-Yves Pellé 66 | Jeff Hodges 67 | Jeffrey Charles 68 | Jennifer Purevsuren 69 | Jerome Meyer 70 | Jiabin Zhang 71 | Jiajia Zhong 72 | Jian Zhen 73 | Joe Mann 74 | Joshua Prunier 75 | Julien Lefevre 76 | Julien Schmidt 77 | Justin Li 78 | Justin Nuß 79 | Kamil Dziedzic 80 | Kei Kamikawa 81 | Kevin Malachowski 82 | Kieron Woodhouse 83 | Lance Tian 84 | Lennart Rudolph 85 | Leonardo YongUk Kim 86 | Linh Tran Tuan 87 | Lion Yang 88 | Luca Looz 89 | Lucas Liu 90 | Luke Scott 91 | Lunny Xiao 92 | Maciej Zimnoch 93 | Michael Woolnough 94 | Minh Quang 95 | Nao Yokotsuka 96 | Nathanial Murphy 97 | Nicola Peduzzi 98 | Oliver Bone 99 | Olivier Mengué 100 | oscarzhao 101 | Paul Bonser 102 | Paulius Lozys 103 | Peter Schultz 104 | Phil Porada 105 | Rebecca Chin 106 | Reed Allman 107 | Richard Wilkes 108 | Robert Russell 109 | Runrioter Wung 110 | Samantha Frank 111 | Santhosh Kumar Tekuri 112 | Sho Iizuka 113 | Sho Ikeda 114 | Shuode Li 115 | Simon J Mudd 116 | Soroush Pour 117 | Stan Putrya 118 | Stanley Gunawan 119 | Steven Hartland 120 | Tan Jinhua <312841925 at qq.com> 121 | Tetsuro Aoki 122 | Thomas Wodarek 123 | Tim Ruffles 124 | Tom Jenkinson 125 | Vladimir Kovpak 126 | Vladyslav Zhelezniak 127 | Xiangyu Hu 128 | Xiaobing Jiang 129 | Xiuming Chen 130 | Xuehong Chan 131 | Zhang Xiang 132 | Zhenye Xie 133 | Zhixin Wen 134 | Ziheng Lyu 135 | 136 | # Organizations 137 | 138 | Barracuda Networks, Inc. 139 | Counting Ltd. 140 | Defined Networking Inc. 141 | DigitalOcean Inc. 142 | Dolthub Inc. 143 | dyves labs AG 144 | Facebook Inc. 145 | GitHub Inc. 146 | Google Inc. 147 | InfoSum Ltd. 148 | Keybase Inc. 149 | Microsoft Corp. 150 | Multiplay Ltd. 151 | Percona LLC 152 | PingCAP Inc. 153 | Pivotal Inc. 154 | Shattered Silicon Ltd. 155 | Stripe Inc. 156 | ThousandEyes 157 | Zendesk Inc. 158 | -------------------------------------------------------------------------------- /fields.go: -------------------------------------------------------------------------------- 1 | // Go MySQL Driver - A MySQL-Driver for Go's database/sql package 2 | // 3 | // Copyright 2017 The Go-MySQL-Driver Authors. All rights reserved. 4 | // 5 | // This Source Code Form is subject to the terms of the Mozilla Public 6 | // License, v. 2.0. If a copy of the MPL was not distributed with this file, 7 | // You can obtain one at http://mozilla.org/MPL/2.0/. 8 | 9 | package mysql 10 | 11 | import ( 12 | "database/sql" 13 | "reflect" 14 | ) 15 | 16 | func (mf *mysqlField) typeDatabaseName() string { 17 | switch mf.fieldType { 18 | case fieldTypeBit: 19 | return "BIT" 20 | case fieldTypeBLOB: 21 | if mf.charSet != binaryCollationID { 22 | return "TEXT" 23 | } 24 | return "BLOB" 25 | case fieldTypeDate: 26 | return "DATE" 27 | case fieldTypeDateTime: 28 | return "DATETIME" 29 | case fieldTypeDecimal: 30 | return "DECIMAL" 31 | case fieldTypeDouble: 32 | return "DOUBLE" 33 | case fieldTypeEnum: 34 | return "ENUM" 35 | case fieldTypeFloat: 36 | return "FLOAT" 37 | case fieldTypeGeometry: 38 | return "GEOMETRY" 39 | case fieldTypeInt24: 40 | if mf.flags&flagUnsigned != 0 { 41 | return "UNSIGNED MEDIUMINT" 42 | } 43 | return "MEDIUMINT" 44 | case fieldTypeJSON: 45 | return "JSON" 46 | case fieldTypeLong: 47 | if mf.flags&flagUnsigned != 0 { 48 | return "UNSIGNED INT" 49 | } 50 | return "INT" 51 | case fieldTypeLongBLOB: 52 | if mf.charSet != binaryCollationID { 53 | return "LONGTEXT" 54 | } 55 | return "LONGBLOB" 56 | case fieldTypeLongLong: 57 | if mf.flags&flagUnsigned != 0 { 58 | return "UNSIGNED BIGINT" 59 | } 60 | return "BIGINT" 61 | case fieldTypeMediumBLOB: 62 | if mf.charSet != binaryCollationID { 63 | return "MEDIUMTEXT" 64 | } 65 | return "MEDIUMBLOB" 66 | case fieldTypeNewDate: 67 | return "DATE" 68 | case fieldTypeNewDecimal: 69 | return "DECIMAL" 70 | case fieldTypeNULL: 71 | return "NULL" 72 | case fieldTypeSet: 73 | return "SET" 74 | case fieldTypeShort: 75 | if mf.flags&flagUnsigned != 0 { 76 | return "UNSIGNED SMALLINT" 77 | } 78 | return "SMALLINT" 79 | case fieldTypeString: 80 | if mf.flags&flagEnum != 0 { 81 | return "ENUM" 82 | } else if mf.flags&flagSet != 0 { 83 | return "SET" 84 | } 85 | if mf.charSet == binaryCollationID { 86 | return "BINARY" 87 | } 88 | return "CHAR" 89 | case fieldTypeTime: 90 | return "TIME" 91 | case fieldTypeTimestamp: 92 | return "TIMESTAMP" 93 | case fieldTypeTiny: 94 | if mf.flags&flagUnsigned != 0 { 95 | return "UNSIGNED TINYINT" 96 | } 97 | return "TINYINT" 98 | case fieldTypeTinyBLOB: 99 | if mf.charSet != binaryCollationID { 100 | return "TINYTEXT" 101 | } 102 | return "TINYBLOB" 103 | case fieldTypeVarChar: 104 | if mf.charSet == binaryCollationID { 105 | return "VARBINARY" 106 | } 107 | return "VARCHAR" 108 | case fieldTypeVarString: 109 | if mf.charSet == binaryCollationID { 110 | return "VARBINARY" 111 | } 112 | return "VARCHAR" 113 | case fieldTypeYear: 114 | return "YEAR" 115 | case fieldTypeVector: 116 | return "VECTOR" 117 | default: 118 | return "" 119 | } 120 | } 121 | 122 | var ( 123 | scanTypeFloat32 = reflect.TypeOf(float32(0)) 124 | scanTypeFloat64 = reflect.TypeOf(float64(0)) 125 | scanTypeInt8 = reflect.TypeOf(int8(0)) 126 | scanTypeInt16 = reflect.TypeOf(int16(0)) 127 | scanTypeInt32 = reflect.TypeOf(int32(0)) 128 | scanTypeInt64 = reflect.TypeOf(int64(0)) 129 | scanTypeNullFloat = reflect.TypeOf(sql.NullFloat64{}) 130 | scanTypeNullInt = reflect.TypeOf(sql.NullInt64{}) 131 | scanTypeNullUint = reflect.TypeOf(sql.Null[uint64]{}) 132 | scanTypeNullTime = reflect.TypeOf(sql.NullTime{}) 133 | scanTypeUint8 = reflect.TypeOf(uint8(0)) 134 | scanTypeUint16 = reflect.TypeOf(uint16(0)) 135 | scanTypeUint32 = reflect.TypeOf(uint32(0)) 136 | scanTypeUint64 = reflect.TypeOf(uint64(0)) 137 | scanTypeString = reflect.TypeOf("") 138 | scanTypeNullString = reflect.TypeOf(sql.NullString{}) 139 | scanTypeBytes = reflect.TypeOf([]byte{}) 140 | scanTypeUnknown = reflect.TypeOf(new(any)) 141 | ) 142 | 143 | type mysqlField struct { 144 | tableName string 145 | name string 146 | length uint32 147 | flags fieldFlag 148 | fieldType fieldType 149 | decimals byte 150 | charSet uint8 151 | } 152 | 153 | func (mf *mysqlField) scanType() reflect.Type { 154 | switch mf.fieldType { 155 | case fieldTypeTiny: 156 | if mf.flags&flagNotNULL != 0 { 157 | if mf.flags&flagUnsigned != 0 { 158 | return scanTypeUint8 159 | } 160 | return scanTypeInt8 161 | } 162 | return scanTypeNullInt 163 | 164 | case fieldTypeShort, fieldTypeYear: 165 | if mf.flags&flagNotNULL != 0 { 166 | if mf.flags&flagUnsigned != 0 { 167 | return scanTypeUint16 168 | } 169 | return scanTypeInt16 170 | } 171 | return scanTypeNullInt 172 | 173 | case fieldTypeInt24, fieldTypeLong: 174 | if mf.flags&flagNotNULL != 0 { 175 | if mf.flags&flagUnsigned != 0 { 176 | return scanTypeUint32 177 | } 178 | return scanTypeInt32 179 | } 180 | return scanTypeNullInt 181 | 182 | case fieldTypeLongLong: 183 | if mf.flags&flagNotNULL != 0 { 184 | if mf.flags&flagUnsigned != 0 { 185 | return scanTypeUint64 186 | } 187 | return scanTypeInt64 188 | } 189 | if mf.flags&flagUnsigned != 0 { 190 | return scanTypeNullUint 191 | } 192 | return scanTypeNullInt 193 | 194 | case fieldTypeFloat: 195 | if mf.flags&flagNotNULL != 0 { 196 | return scanTypeFloat32 197 | } 198 | return scanTypeNullFloat 199 | 200 | case fieldTypeDouble: 201 | if mf.flags&flagNotNULL != 0 { 202 | return scanTypeFloat64 203 | } 204 | return scanTypeNullFloat 205 | 206 | case fieldTypeBit, fieldTypeTinyBLOB, fieldTypeMediumBLOB, fieldTypeLongBLOB, 207 | fieldTypeBLOB, fieldTypeVarString, fieldTypeString, fieldTypeGeometry, fieldTypeVector: 208 | if mf.charSet == binaryCollationID { 209 | return scanTypeBytes 210 | } 211 | fallthrough 212 | case fieldTypeDecimal, fieldTypeNewDecimal, fieldTypeVarChar, 213 | fieldTypeEnum, fieldTypeSet, fieldTypeJSON, fieldTypeTime: 214 | if mf.flags&flagNotNULL != 0 { 215 | return scanTypeString 216 | } 217 | return scanTypeNullString 218 | 219 | case fieldTypeDate, fieldTypeNewDate, 220 | fieldTypeTimestamp, fieldTypeDateTime: 221 | // NullTime is always returned for more consistent behavior as it can 222 | // handle both cases of parseTime regardless if the field is nullable. 223 | return scanTypeNullTime 224 | 225 | default: 226 | return scanTypeUnknown 227 | } 228 | } 229 | -------------------------------------------------------------------------------- /compress.go: -------------------------------------------------------------------------------- 1 | // Go MySQL Driver - A MySQL-Driver for Go's database/sql package 2 | // 3 | // Copyright 2024 The Go-MySQL-Driver Authors. All rights reserved. 4 | // 5 | // This Source Code Form is subject to the terms of the Mozilla Public 6 | // License, v. 2.0. If a copy of the MPL was not distributed with this file, 7 | // You can obtain one at http://mozilla.org/MPL/2.0/. 8 | 9 | package mysql 10 | 11 | import ( 12 | "bytes" 13 | "compress/zlib" 14 | "fmt" 15 | "io" 16 | "sync" 17 | ) 18 | 19 | var ( 20 | zrPool *sync.Pool // Do not use directly. Use zDecompress() instead. 21 | zwPool *sync.Pool // Do not use directly. Use zCompress() instead. 22 | ) 23 | 24 | func init() { 25 | zrPool = &sync.Pool{ 26 | New: func() any { return nil }, 27 | } 28 | zwPool = &sync.Pool{ 29 | New: func() any { 30 | zw, err := zlib.NewWriterLevel(new(bytes.Buffer), 2) 31 | if err != nil { 32 | panic(err) // compress/zlib return non-nil error only if level is invalid 33 | } 34 | return zw 35 | }, 36 | } 37 | } 38 | 39 | func zDecompress(src []byte, dst *bytes.Buffer) (int, error) { 40 | br := bytes.NewReader(src) 41 | var zr io.ReadCloser 42 | var err error 43 | 44 | if a := zrPool.Get(); a == nil { 45 | if zr, err = zlib.NewReader(br); err != nil { 46 | return 0, err 47 | } 48 | } else { 49 | zr = a.(io.ReadCloser) 50 | if err := zr.(zlib.Resetter).Reset(br, nil); err != nil { 51 | return 0, err 52 | } 53 | } 54 | 55 | n, _ := dst.ReadFrom(zr) // ignore err because zr.Close() will return it again. 56 | err = zr.Close() // zr.Close() may return chuecksum error. 57 | zrPool.Put(zr) 58 | return int(n), err 59 | } 60 | 61 | func zCompress(src []byte, dst io.Writer) error { 62 | zw := zwPool.Get().(*zlib.Writer) 63 | zw.Reset(dst) 64 | if _, err := zw.Write(src); err != nil { 65 | return err 66 | } 67 | err := zw.Close() 68 | zwPool.Put(zw) 69 | return err 70 | } 71 | 72 | type compIO struct { 73 | mc *mysqlConn 74 | buff bytes.Buffer 75 | } 76 | 77 | func newCompIO(mc *mysqlConn) *compIO { 78 | return &compIO{ 79 | mc: mc, 80 | } 81 | } 82 | 83 | func (c *compIO) reset() { 84 | c.buff.Reset() 85 | } 86 | 87 | func (c *compIO) readNext(need int) ([]byte, error) { 88 | for c.buff.Len() < need { 89 | if err := c.readCompressedPacket(); err != nil { 90 | return nil, err 91 | } 92 | } 93 | data := c.buff.Next(need) 94 | return data[:need:need], nil // prevent caller writes into c.buff 95 | } 96 | 97 | func (c *compIO) readCompressedPacket() error { 98 | header, err := c.mc.readNext(7) 99 | if err != nil { 100 | return err 101 | } 102 | _ = header[6] // bounds check hint to compiler; guaranteed by readNext 103 | 104 | // compressed header structure 105 | comprLength := getUint24(header[0:3]) 106 | compressionSequence := header[3] 107 | uncompressedLength := getUint24(header[4:7]) 108 | if debug { 109 | fmt.Printf("uncompress cmplen=%v uncomplen=%v pkt_cmp_seq=%v expected_cmp_seq=%v\n", 110 | comprLength, uncompressedLength, compressionSequence, c.mc.sequence) 111 | } 112 | // Do not return ErrPktSync here. 113 | // Server may return error packet (e.g. 1153 Got a packet bigger than 'max_allowed_packet' bytes) 114 | // before receiving all packets from client. In this case, seqnr is younger than expected. 115 | // NOTE: Both of mariadbclient and mysqlclient do not check seqnr. Only server checks it. 116 | if debug && compressionSequence != c.mc.compressSequence { 117 | fmt.Printf("WARN: unexpected cmpress seq nr: expected %v, got %v", 118 | c.mc.compressSequence, compressionSequence) 119 | } 120 | c.mc.compressSequence = compressionSequence + 1 121 | 122 | comprData, err := c.mc.readNext(comprLength) 123 | if err != nil { 124 | return err 125 | } 126 | 127 | // if payload is uncompressed, its length will be specified as zero, and its 128 | // true length is contained in comprLength 129 | if uncompressedLength == 0 { 130 | c.buff.Write(comprData) 131 | return nil 132 | } 133 | 134 | // use existing capacity in bytesBuf if possible 135 | c.buff.Grow(uncompressedLength) 136 | nread, err := zDecompress(comprData, &c.buff) 137 | if err != nil { 138 | return err 139 | } 140 | if nread != uncompressedLength { 141 | return fmt.Errorf("invalid compressed packet: uncompressed length in header is %d, actual %d", 142 | uncompressedLength, nread) 143 | } 144 | return nil 145 | } 146 | 147 | const minCompressLength = 150 148 | const maxPayloadLen = maxPacketSize - 4 149 | 150 | // writePackets sends one or some packets with compression. 151 | // Use this instead of mc.netConn.Write() when mc.compress is true. 152 | func (c *compIO) writePackets(packets []byte) (int, error) { 153 | totalBytes := len(packets) 154 | blankHeader := make([]byte, 7) 155 | buf := &c.buff 156 | 157 | for len(packets) > 0 { 158 | payloadLen := min(maxPayloadLen, len(packets)) 159 | payload := packets[:payloadLen] 160 | uncompressedLen := payloadLen 161 | 162 | buf.Reset() 163 | buf.Write(blankHeader) // Buffer.Write() never returns error 164 | 165 | // If payload is less than minCompressLength, don't compress. 166 | if uncompressedLen < minCompressLength { 167 | buf.Write(payload) 168 | uncompressedLen = 0 169 | } else { 170 | err := zCompress(payload, buf) 171 | if debug && err != nil { 172 | fmt.Printf("zCompress error: %v", err) 173 | } 174 | // do not compress if compressed data is larger than uncompressed data 175 | // I intentionally miss 7 byte header in the buf; zCompress must compress more than 7 bytes. 176 | if err != nil || buf.Len() >= uncompressedLen { 177 | buf.Reset() 178 | buf.Write(blankHeader) 179 | buf.Write(payload) 180 | uncompressedLen = 0 181 | } 182 | } 183 | 184 | if n, err := c.writeCompressedPacket(buf.Bytes(), uncompressedLen); err != nil { 185 | // To allow returning ErrBadConn when sending really 0 bytes, we sum 186 | // up compressed bytes that is returned by underlying Write(). 187 | return totalBytes - len(packets) + n, err 188 | } 189 | packets = packets[payloadLen:] 190 | } 191 | 192 | return totalBytes, nil 193 | } 194 | 195 | // writeCompressedPacket writes a compressed packet with header. 196 | // data should start with 7 size space for header followed by payload. 197 | func (c *compIO) writeCompressedPacket(data []byte, uncompressedLen int) (int, error) { 198 | mc := c.mc 199 | comprLength := len(data) - 7 200 | if debug { 201 | fmt.Printf( 202 | "writeCompressedPacket: comprLength=%v, uncompressedLen=%v, seq=%v\n", 203 | comprLength, uncompressedLen, mc.compressSequence) 204 | } 205 | 206 | // compression header 207 | putUint24(data[0:3], comprLength) 208 | data[3] = mc.compressSequence 209 | putUint24(data[4:7], uncompressedLen) 210 | 211 | mc.compressSequence++ 212 | return mc.writeWithTimeout(data) 213 | } 214 | -------------------------------------------------------------------------------- /statement.go: -------------------------------------------------------------------------------- 1 | // Go MySQL Driver - A MySQL-Driver for Go's database/sql package 2 | // 3 | // Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. 4 | // 5 | // This Source Code Form is subject to the terms of the Mozilla Public 6 | // License, v. 2.0. If a copy of the MPL was not distributed with this file, 7 | // You can obtain one at http://mozilla.org/MPL/2.0/. 8 | 9 | package mysql 10 | 11 | import ( 12 | "database/sql/driver" 13 | "encoding/json" 14 | "fmt" 15 | "io" 16 | "reflect" 17 | ) 18 | 19 | type mysqlStmt struct { 20 | mc *mysqlConn 21 | id uint32 22 | paramCount int 23 | columns []mysqlField 24 | } 25 | 26 | func (stmt *mysqlStmt) Close() error { 27 | if stmt.mc == nil || stmt.mc.closed.Load() { 28 | // driver.Stmt.Close could be called more than once, thus this function 29 | // had to be idempotent. See also Issue #450 and golang/go#16019. 30 | // This bug has been fixed in Go 1.8. 31 | // https://github.com/golang/go/commit/90b8a0ca2d0b565c7c7199ffcf77b15ea6b6db3a 32 | // But we keep this function idempotent because it is safer. 33 | return nil 34 | } 35 | 36 | err := stmt.mc.writeCommandPacketUint32(comStmtClose, stmt.id) 37 | stmt.mc = nil 38 | return err 39 | } 40 | 41 | func (stmt *mysqlStmt) NumInput() int { 42 | return stmt.paramCount 43 | } 44 | 45 | func (stmt *mysqlStmt) ColumnConverter(idx int) driver.ValueConverter { 46 | return converter{} 47 | } 48 | 49 | func (stmt *mysqlStmt) CheckNamedValue(nv *driver.NamedValue) (err error) { 50 | nv.Value, err = converter{}.ConvertValue(nv.Value) 51 | return 52 | } 53 | 54 | func (stmt *mysqlStmt) Exec(args []driver.Value) (driver.Result, error) { 55 | if stmt.mc.closed.Load() { 56 | return nil, driver.ErrBadConn 57 | } 58 | // Send command 59 | err := stmt.writeExecutePacket(args) 60 | if err != nil { 61 | return nil, stmt.mc.markBadConn(err) 62 | } 63 | 64 | mc := stmt.mc 65 | handleOk := stmt.mc.clearResult() 66 | 67 | // Read Result 68 | resLen, metadataFollows, err := handleOk.readResultSetHeaderPacket() 69 | if err != nil { 70 | return nil, err 71 | } 72 | 73 | if resLen > 0 { 74 | // Columns 75 | if metadataFollows && stmt.mc.extCapabilities&clientCacheMetadata != 0 { 76 | // we can not skip column metadata because next stmt.Query() may use it. 77 | if stmt.columns, err = mc.readColumns(resLen, stmt.columns); err != nil { 78 | return nil, err 79 | } 80 | } else { 81 | if err = mc.skipColumns(resLen); err != nil { 82 | return nil, err 83 | } 84 | } 85 | 86 | // Rows 87 | if err = mc.skipRows(); err != nil { 88 | return nil, err 89 | } 90 | } 91 | 92 | if err := handleOk.discardResults(); err != nil { 93 | return nil, err 94 | } 95 | 96 | copied := mc.result 97 | return &copied, nil 98 | } 99 | 100 | func (stmt *mysqlStmt) Query(args []driver.Value) (driver.Rows, error) { 101 | return stmt.query(args) 102 | } 103 | 104 | func (stmt *mysqlStmt) query(args []driver.Value) (*binaryRows, error) { 105 | if stmt.mc.closed.Load() { 106 | return nil, driver.ErrBadConn 107 | } 108 | // Send command 109 | err := stmt.writeExecutePacket(args) 110 | if err != nil { 111 | return nil, stmt.mc.markBadConn(err) 112 | } 113 | 114 | mc := stmt.mc 115 | 116 | // Read Result 117 | handleOk := stmt.mc.clearResult() 118 | resLen, metadataFollows, err := handleOk.readResultSetHeaderPacket() 119 | if err != nil { 120 | return nil, err 121 | } 122 | 123 | rows := new(binaryRows) 124 | 125 | if resLen > 0 { 126 | rows.mc = mc 127 | if metadataFollows { 128 | if rows.rs.columns, err = mc.readColumns(resLen, stmt.columns); err != nil { 129 | return nil, err 130 | } 131 | stmt.columns = rows.rs.columns 132 | } else { 133 | if err = mc.skipEof(); err != nil { 134 | return nil, err 135 | } 136 | rows.rs.columns = stmt.columns 137 | } 138 | } else { 139 | rows.rs.done = true 140 | 141 | switch err := rows.NextResultSet(); err { 142 | case nil, io.EOF: 143 | return rows, nil 144 | default: 145 | return nil, err 146 | } 147 | } 148 | 149 | return rows, err 150 | } 151 | 152 | var jsonType = reflect.TypeOf(json.RawMessage{}) 153 | 154 | type converter struct{} 155 | 156 | // ConvertValue mirrors the reference/default converter in database/sql/driver 157 | // with _one_ exception. We support uint64 with their high bit and the default 158 | // implementation does not. This function should be kept in sync with 159 | // database/sql/driver defaultConverter.ConvertValue() except for that 160 | // deliberate difference. 161 | func (c converter) ConvertValue(v any) (driver.Value, error) { 162 | if driver.IsValue(v) { 163 | return v, nil 164 | } 165 | 166 | if vr, ok := v.(driver.Valuer); ok { 167 | sv, err := callValuerValue(vr) 168 | if err != nil { 169 | return nil, err 170 | } 171 | if driver.IsValue(sv) { 172 | return sv, nil 173 | } 174 | // A value returned from the Valuer interface can be "a type handled by 175 | // a database driver's NamedValueChecker interface" so we should accept 176 | // uint64 here as well. 177 | if u, ok := sv.(uint64); ok { 178 | return u, nil 179 | } 180 | return nil, fmt.Errorf("non-Value type %T returned from Value", sv) 181 | } 182 | rv := reflect.ValueOf(v) 183 | switch rv.Kind() { 184 | case reflect.Ptr: 185 | // indirect pointers 186 | if rv.IsNil() { 187 | return nil, nil 188 | } else { 189 | return c.ConvertValue(rv.Elem().Interface()) 190 | } 191 | case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 192 | return rv.Int(), nil 193 | case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: 194 | return rv.Uint(), nil 195 | case reflect.Float32, reflect.Float64: 196 | return rv.Float(), nil 197 | case reflect.Bool: 198 | return rv.Bool(), nil 199 | case reflect.Slice: 200 | switch t := rv.Type(); { 201 | case t == jsonType: 202 | return v, nil 203 | case t.Elem().Kind() == reflect.Uint8: 204 | return rv.Bytes(), nil 205 | default: 206 | return nil, fmt.Errorf("unsupported type %T, a slice of %s", v, t.Elem().Kind()) 207 | } 208 | case reflect.String: 209 | return rv.String(), nil 210 | } 211 | return nil, fmt.Errorf("unsupported type %T, a %s", v, rv.Kind()) 212 | } 213 | 214 | var valuerReflectType = reflect.TypeOf((*driver.Valuer)(nil)).Elem() 215 | 216 | // callValuerValue returns vr.Value(), with one exception: 217 | // If vr.Value is an auto-generated method on a pointer type and the 218 | // pointer is nil, it would panic at runtime in the panicwrap 219 | // method. Treat it like nil instead. 220 | // 221 | // This is so people can implement driver.Value on value types and 222 | // still use nil pointers to those types to mean nil/NULL, just like 223 | // string/*string. 224 | // 225 | // This is an exact copy of the same-named unexported function from the 226 | // database/sql package. 227 | func callValuerValue(vr driver.Valuer) (v driver.Value, err error) { 228 | if rv := reflect.ValueOf(vr); rv.Kind() == reflect.Ptr && 229 | rv.IsNil() && 230 | rv.Type().Elem().Implements(valuerReflectType) { 231 | return nil, nil 232 | } 233 | return vr.Value() 234 | } 235 | -------------------------------------------------------------------------------- /connector.go: -------------------------------------------------------------------------------- 1 | // Go MySQL Driver - A MySQL-Driver for Go's database/sql package 2 | // 3 | // Copyright 2018 The Go-MySQL-Driver Authors. All rights reserved. 4 | // 5 | // This Source Code Form is subject to the terms of the Mozilla Public 6 | // License, v. 2.0. If a copy of the MPL was not distributed with this file, 7 | // You can obtain one at http://mozilla.org/MPL/2.0/. 8 | 9 | package mysql 10 | 11 | import ( 12 | "context" 13 | "database/sql/driver" 14 | "fmt" 15 | "net" 16 | "os" 17 | "strconv" 18 | "strings" 19 | ) 20 | 21 | type connector struct { 22 | cfg *Config // immutable private copy. 23 | encodedAttributes string // Encoded connection attributes. 24 | } 25 | 26 | func encodeConnectionAttributes(cfg *Config) string { 27 | connAttrsBuf := make([]byte, 0) 28 | 29 | // default connection attributes 30 | connAttrsBuf = appendLengthEncodedString(connAttrsBuf, connAttrClientName) 31 | connAttrsBuf = appendLengthEncodedString(connAttrsBuf, connAttrClientNameValue) 32 | connAttrsBuf = appendLengthEncodedString(connAttrsBuf, connAttrOS) 33 | connAttrsBuf = appendLengthEncodedString(connAttrsBuf, connAttrOSValue) 34 | connAttrsBuf = appendLengthEncodedString(connAttrsBuf, connAttrPlatform) 35 | connAttrsBuf = appendLengthEncodedString(connAttrsBuf, connAttrPlatformValue) 36 | connAttrsBuf = appendLengthEncodedString(connAttrsBuf, connAttrPid) 37 | connAttrsBuf = appendLengthEncodedString(connAttrsBuf, strconv.Itoa(os.Getpid())) 38 | serverHost, _, _ := net.SplitHostPort(cfg.Addr) 39 | if serverHost != "" { 40 | connAttrsBuf = appendLengthEncodedString(connAttrsBuf, connAttrServerHost) 41 | connAttrsBuf = appendLengthEncodedString(connAttrsBuf, serverHost) 42 | } 43 | 44 | // user-defined connection attributes 45 | for _, connAttr := range strings.Split(cfg.ConnectionAttributes, ",") { 46 | k, v, found := strings.Cut(connAttr, ":") 47 | if !found { 48 | continue 49 | } 50 | connAttrsBuf = appendLengthEncodedString(connAttrsBuf, k) 51 | connAttrsBuf = appendLengthEncodedString(connAttrsBuf, v) 52 | } 53 | 54 | return string(connAttrsBuf) 55 | } 56 | 57 | func newConnector(cfg *Config) *connector { 58 | encodedAttributes := encodeConnectionAttributes(cfg) 59 | return &connector{ 60 | cfg: cfg, 61 | encodedAttributes: encodedAttributes, 62 | } 63 | } 64 | 65 | // Connect implements driver.Connector interface. 66 | // Connect returns a connection to the database. 67 | func (c *connector) Connect(ctx context.Context) (driver.Conn, error) { 68 | var err error 69 | 70 | // Invoke beforeConnect if present, with a copy of the configuration 71 | cfg := c.cfg 72 | if c.cfg.beforeConnect != nil { 73 | cfg = c.cfg.Clone() 74 | err = c.cfg.beforeConnect(ctx, cfg) 75 | if err != nil { 76 | return nil, err 77 | } 78 | } 79 | 80 | // New mysqlConn 81 | mc := &mysqlConn{ 82 | maxAllowedPacket: maxPacketSize, 83 | maxWriteSize: maxPacketSize - 1, 84 | closech: make(chan struct{}), 85 | cfg: cfg, 86 | connector: c, 87 | } 88 | mc.parseTime = mc.cfg.ParseTime 89 | 90 | // Connect to Server 91 | dctx := ctx 92 | if mc.cfg.Timeout > 0 { 93 | var cancel context.CancelFunc 94 | dctx, cancel = context.WithTimeout(ctx, c.cfg.Timeout) 95 | defer cancel() 96 | } 97 | 98 | if c.cfg.DialFunc != nil { 99 | mc.netConn, err = c.cfg.DialFunc(dctx, mc.cfg.Net, mc.cfg.Addr) 100 | } else { 101 | dialsLock.RLock() 102 | dial, ok := dials[mc.cfg.Net] 103 | dialsLock.RUnlock() 104 | if ok { 105 | mc.netConn, err = dial(dctx, mc.cfg.Addr) 106 | } else { 107 | nd := net.Dialer{} 108 | mc.netConn, err = nd.DialContext(dctx, mc.cfg.Net, mc.cfg.Addr) 109 | } 110 | } 111 | if err != nil { 112 | return nil, err 113 | } 114 | mc.rawConn = mc.netConn 115 | 116 | // Enable TCP Keepalives on TCP connections 117 | if tc, ok := mc.netConn.(*net.TCPConn); ok { 118 | if err := tc.SetKeepAlive(true); err != nil { 119 | c.cfg.Logger.Print(err) 120 | } 121 | } 122 | 123 | // Call startWatcher for context support (From Go 1.8) 124 | mc.startWatcher() 125 | if err := mc.watchCancel(ctx); err != nil { 126 | mc.cleanup() 127 | return nil, err 128 | } 129 | defer mc.finish() 130 | 131 | mc.buf = newBuffer() 132 | 133 | // Reading Handshake Initialization Packet 134 | authData, serverCapabilities, serverExtCapabilities, plugin, err := mc.readHandshakePacket() 135 | if err != nil { 136 | mc.cleanup() 137 | return nil, err 138 | } 139 | 140 | if plugin == "" { 141 | plugin = defaultAuthPlugin 142 | } 143 | 144 | // Send Client Authentication Packet 145 | authResp, err := mc.auth(authData, plugin) 146 | if err != nil { 147 | // try the default auth plugin, if using the requested plugin failed 148 | c.cfg.Logger.Print("could not use requested auth plugin '"+plugin+"': ", err.Error()) 149 | plugin = defaultAuthPlugin 150 | authResp, err = mc.auth(authData, plugin) 151 | if err != nil { 152 | mc.cleanup() 153 | return nil, err 154 | } 155 | } 156 | mc.initCapabilities(serverCapabilities, serverExtCapabilities, mc.cfg) 157 | if err = mc.writeHandshakeResponsePacket(authResp, plugin); err != nil { 158 | mc.cleanup() 159 | return nil, err 160 | } 161 | 162 | // Handle response to auth packet, switch methods if possible 163 | if err = mc.handleAuthResult(authData, plugin); err != nil { 164 | // Authentication failed and MySQL has already closed the connection 165 | // (https://dev.mysql.com/doc/dev/mysql-server/latest/page_protocol_connection_phase.html#sect_protocol_connection_phase_fast_path_fails). 166 | // Do not send COM_QUIT, just cleanup and return the error. 167 | mc.cleanup() 168 | return nil, err 169 | } 170 | 171 | // compression is enabled after auth, not right after sending handshake response. 172 | if mc.capabilities&clientCompress > 0 { 173 | mc.compress = true 174 | mc.compIO = newCompIO(mc) 175 | } 176 | if mc.cfg.MaxAllowedPacket > 0 { 177 | mc.maxAllowedPacket = mc.cfg.MaxAllowedPacket 178 | } else { 179 | // Get max allowed packet size 180 | maxap, err := mc.getSystemVar("max_allowed_packet") 181 | if err != nil { 182 | mc.Close() 183 | return nil, err 184 | } 185 | n, err := strconv.Atoi(string(maxap)) 186 | if err != nil { 187 | mc.Close() 188 | return nil, fmt.Errorf("invalid max_allowed_packet value (%q): %w", maxap, err) 189 | } 190 | mc.maxAllowedPacket = n - 1 191 | } 192 | if mc.maxAllowedPacket < maxPacketSize { 193 | mc.maxWriteSize = mc.maxAllowedPacket 194 | } 195 | 196 | // Charset: character_set_connection, character_set_client, character_set_results 197 | if len(mc.cfg.charsets) > 0 { 198 | for _, cs := range mc.cfg.charsets { 199 | // ignore errors here - a charset may not exist 200 | if mc.cfg.Collation != "" { 201 | err = mc.exec("SET NAMES " + cs + " COLLATE " + mc.cfg.Collation) 202 | } else { 203 | err = mc.exec("SET NAMES " + cs) 204 | } 205 | if err == nil { 206 | break 207 | } 208 | } 209 | if err != nil { 210 | mc.Close() 211 | return nil, err 212 | } 213 | } 214 | 215 | // Handle DSN Params 216 | err = mc.handleParams() 217 | if err != nil { 218 | mc.Close() 219 | return nil, err 220 | } 221 | 222 | return mc, nil 223 | } 224 | 225 | // Driver implements driver.Connector interface. 226 | // Driver returns &MySQLDriver{}. 227 | func (c *connector) Driver() driver.Driver { 228 | return &MySQLDriver{} 229 | } 230 | -------------------------------------------------------------------------------- /collations.go: -------------------------------------------------------------------------------- 1 | // Go MySQL Driver - A MySQL-Driver for Go's database/sql package 2 | // 3 | // Copyright 2014 The Go-MySQL-Driver Authors. All rights reserved. 4 | // 5 | // This Source Code Form is subject to the terms of the Mozilla Public 6 | // License, v. 2.0. If a copy of the MPL was not distributed with this file, 7 | // You can obtain one at http://mozilla.org/MPL/2.0/. 8 | 9 | package mysql 10 | 11 | const defaultCollationID = 45 // utf8mb4_general_ci 12 | const binaryCollationID = 63 13 | 14 | // A list of available collations mapped to the internal ID. 15 | // To update this map use the following MySQL query: 16 | // 17 | // SELECT COLLATION_NAME, ID FROM information_schema.COLLATIONS WHERE ID<256 ORDER BY ID 18 | // 19 | // Handshake packet have only 1 byte for collation_id. So we can't use collations with ID > 255. 20 | // 21 | // ucs2, utf16, and utf32 can't be used for connection charset. 22 | // https://dev.mysql.com/doc/refman/5.7/en/charset-connection.html#charset-connection-impermissible-client-charset 23 | // They are commented out to reduce this map. 24 | var collations = map[string]byte{ 25 | "big5_chinese_ci": 1, 26 | "latin2_czech_cs": 2, 27 | "dec8_swedish_ci": 3, 28 | "cp850_general_ci": 4, 29 | "latin1_german1_ci": 5, 30 | "hp8_english_ci": 6, 31 | "koi8r_general_ci": 7, 32 | "latin1_swedish_ci": 8, 33 | "latin2_general_ci": 9, 34 | "swe7_swedish_ci": 10, 35 | "ascii_general_ci": 11, 36 | "ujis_japanese_ci": 12, 37 | "sjis_japanese_ci": 13, 38 | "cp1251_bulgarian_ci": 14, 39 | "latin1_danish_ci": 15, 40 | "hebrew_general_ci": 16, 41 | "tis620_thai_ci": 18, 42 | "euckr_korean_ci": 19, 43 | "latin7_estonian_cs": 20, 44 | "latin2_hungarian_ci": 21, 45 | "koi8u_general_ci": 22, 46 | "cp1251_ukrainian_ci": 23, 47 | "gb2312_chinese_ci": 24, 48 | "greek_general_ci": 25, 49 | "cp1250_general_ci": 26, 50 | "latin2_croatian_ci": 27, 51 | "gbk_chinese_ci": 28, 52 | "cp1257_lithuanian_ci": 29, 53 | "latin5_turkish_ci": 30, 54 | "latin1_german2_ci": 31, 55 | "armscii8_general_ci": 32, 56 | "utf8_general_ci": 33, 57 | "cp1250_czech_cs": 34, 58 | //"ucs2_general_ci": 35, 59 | "cp866_general_ci": 36, 60 | "keybcs2_general_ci": 37, 61 | "macce_general_ci": 38, 62 | "macroman_general_ci": 39, 63 | "cp852_general_ci": 40, 64 | "latin7_general_ci": 41, 65 | "latin7_general_cs": 42, 66 | "macce_bin": 43, 67 | "cp1250_croatian_ci": 44, 68 | "utf8mb4_general_ci": 45, 69 | "utf8mb4_bin": 46, 70 | "latin1_bin": 47, 71 | "latin1_general_ci": 48, 72 | "latin1_general_cs": 49, 73 | "cp1251_bin": 50, 74 | "cp1251_general_ci": 51, 75 | "cp1251_general_cs": 52, 76 | "macroman_bin": 53, 77 | //"utf16_general_ci": 54, 78 | //"utf16_bin": 55, 79 | //"utf16le_general_ci": 56, 80 | "cp1256_general_ci": 57, 81 | "cp1257_bin": 58, 82 | "cp1257_general_ci": 59, 83 | //"utf32_general_ci": 60, 84 | //"utf32_bin": 61, 85 | //"utf16le_bin": 62, 86 | "binary": 63, 87 | "armscii8_bin": 64, 88 | "ascii_bin": 65, 89 | "cp1250_bin": 66, 90 | "cp1256_bin": 67, 91 | "cp866_bin": 68, 92 | "dec8_bin": 69, 93 | "greek_bin": 70, 94 | "hebrew_bin": 71, 95 | "hp8_bin": 72, 96 | "keybcs2_bin": 73, 97 | "koi8r_bin": 74, 98 | "koi8u_bin": 75, 99 | "utf8_tolower_ci": 76, 100 | "latin2_bin": 77, 101 | "latin5_bin": 78, 102 | "latin7_bin": 79, 103 | "cp850_bin": 80, 104 | "cp852_bin": 81, 105 | "swe7_bin": 82, 106 | "utf8_bin": 83, 107 | "big5_bin": 84, 108 | "euckr_bin": 85, 109 | "gb2312_bin": 86, 110 | "gbk_bin": 87, 111 | "sjis_bin": 88, 112 | "tis620_bin": 89, 113 | //"ucs2_bin": 90, 114 | "ujis_bin": 91, 115 | "geostd8_general_ci": 92, 116 | "geostd8_bin": 93, 117 | "latin1_spanish_ci": 94, 118 | "cp932_japanese_ci": 95, 119 | "cp932_bin": 96, 120 | "eucjpms_japanese_ci": 97, 121 | "eucjpms_bin": 98, 122 | "cp1250_polish_ci": 99, 123 | //"utf16_unicode_ci": 101, 124 | //"utf16_icelandic_ci": 102, 125 | //"utf16_latvian_ci": 103, 126 | //"utf16_romanian_ci": 104, 127 | //"utf16_slovenian_ci": 105, 128 | //"utf16_polish_ci": 106, 129 | //"utf16_estonian_ci": 107, 130 | //"utf16_spanish_ci": 108, 131 | //"utf16_swedish_ci": 109, 132 | //"utf16_turkish_ci": 110, 133 | //"utf16_czech_ci": 111, 134 | //"utf16_danish_ci": 112, 135 | //"utf16_lithuanian_ci": 113, 136 | //"utf16_slovak_ci": 114, 137 | //"utf16_spanish2_ci": 115, 138 | //"utf16_roman_ci": 116, 139 | //"utf16_persian_ci": 117, 140 | //"utf16_esperanto_ci": 118, 141 | //"utf16_hungarian_ci": 119, 142 | //"utf16_sinhala_ci": 120, 143 | //"utf16_german2_ci": 121, 144 | //"utf16_croatian_ci": 122, 145 | //"utf16_unicode_520_ci": 123, 146 | //"utf16_vietnamese_ci": 124, 147 | //"ucs2_unicode_ci": 128, 148 | //"ucs2_icelandic_ci": 129, 149 | //"ucs2_latvian_ci": 130, 150 | //"ucs2_romanian_ci": 131, 151 | //"ucs2_slovenian_ci": 132, 152 | //"ucs2_polish_ci": 133, 153 | //"ucs2_estonian_ci": 134, 154 | //"ucs2_spanish_ci": 135, 155 | //"ucs2_swedish_ci": 136, 156 | //"ucs2_turkish_ci": 137, 157 | //"ucs2_czech_ci": 138, 158 | //"ucs2_danish_ci": 139, 159 | //"ucs2_lithuanian_ci": 140, 160 | //"ucs2_slovak_ci": 141, 161 | //"ucs2_spanish2_ci": 142, 162 | //"ucs2_roman_ci": 143, 163 | //"ucs2_persian_ci": 144, 164 | //"ucs2_esperanto_ci": 145, 165 | //"ucs2_hungarian_ci": 146, 166 | //"ucs2_sinhala_ci": 147, 167 | //"ucs2_german2_ci": 148, 168 | //"ucs2_croatian_ci": 149, 169 | //"ucs2_unicode_520_ci": 150, 170 | //"ucs2_vietnamese_ci": 151, 171 | //"ucs2_general_mysql500_ci": 159, 172 | //"utf32_unicode_ci": 160, 173 | //"utf32_icelandic_ci": 161, 174 | //"utf32_latvian_ci": 162, 175 | //"utf32_romanian_ci": 163, 176 | //"utf32_slovenian_ci": 164, 177 | //"utf32_polish_ci": 165, 178 | //"utf32_estonian_ci": 166, 179 | //"utf32_spanish_ci": 167, 180 | //"utf32_swedish_ci": 168, 181 | //"utf32_turkish_ci": 169, 182 | //"utf32_czech_ci": 170, 183 | //"utf32_danish_ci": 171, 184 | //"utf32_lithuanian_ci": 172, 185 | //"utf32_slovak_ci": 173, 186 | //"utf32_spanish2_ci": 174, 187 | //"utf32_roman_ci": 175, 188 | //"utf32_persian_ci": 176, 189 | //"utf32_esperanto_ci": 177, 190 | //"utf32_hungarian_ci": 178, 191 | //"utf32_sinhala_ci": 179, 192 | //"utf32_german2_ci": 180, 193 | //"utf32_croatian_ci": 181, 194 | //"utf32_unicode_520_ci": 182, 195 | //"utf32_vietnamese_ci": 183, 196 | "utf8_unicode_ci": 192, 197 | "utf8_icelandic_ci": 193, 198 | "utf8_latvian_ci": 194, 199 | "utf8_romanian_ci": 195, 200 | "utf8_slovenian_ci": 196, 201 | "utf8_polish_ci": 197, 202 | "utf8_estonian_ci": 198, 203 | "utf8_spanish_ci": 199, 204 | "utf8_swedish_ci": 200, 205 | "utf8_turkish_ci": 201, 206 | "utf8_czech_ci": 202, 207 | "utf8_danish_ci": 203, 208 | "utf8_lithuanian_ci": 204, 209 | "utf8_slovak_ci": 205, 210 | "utf8_spanish2_ci": 206, 211 | "utf8_roman_ci": 207, 212 | "utf8_persian_ci": 208, 213 | "utf8_esperanto_ci": 209, 214 | "utf8_hungarian_ci": 210, 215 | "utf8_sinhala_ci": 211, 216 | "utf8_german2_ci": 212, 217 | "utf8_croatian_ci": 213, 218 | "utf8_unicode_520_ci": 214, 219 | "utf8_vietnamese_ci": 215, 220 | "utf8_general_mysql500_ci": 223, 221 | "utf8mb4_unicode_ci": 224, 222 | "utf8mb4_icelandic_ci": 225, 223 | "utf8mb4_latvian_ci": 226, 224 | "utf8mb4_romanian_ci": 227, 225 | "utf8mb4_slovenian_ci": 228, 226 | "utf8mb4_polish_ci": 229, 227 | "utf8mb4_estonian_ci": 230, 228 | "utf8mb4_spanish_ci": 231, 229 | "utf8mb4_swedish_ci": 232, 230 | "utf8mb4_turkish_ci": 233, 231 | "utf8mb4_czech_ci": 234, 232 | "utf8mb4_danish_ci": 235, 233 | "utf8mb4_lithuanian_ci": 236, 234 | "utf8mb4_slovak_ci": 237, 235 | "utf8mb4_spanish2_ci": 238, 236 | "utf8mb4_roman_ci": 239, 237 | "utf8mb4_persian_ci": 240, 238 | "utf8mb4_esperanto_ci": 241, 239 | "utf8mb4_hungarian_ci": 242, 240 | "utf8mb4_sinhala_ci": 243, 241 | "utf8mb4_german2_ci": 244, 242 | "utf8mb4_croatian_ci": 245, 243 | "utf8mb4_unicode_520_ci": 246, 244 | "utf8mb4_vietnamese_ci": 247, 245 | "gb18030_chinese_ci": 248, 246 | "gb18030_bin": 249, 247 | "gb18030_unicode_520_ci": 250, 248 | "utf8mb4_0900_ai_ci": 255, 249 | } 250 | 251 | // A denylist of collations which is unsafe to interpolate parameters. 252 | // These multibyte encodings may contains 0x5c (`\`) in their trailing bytes. 253 | var unsafeCollations = map[string]bool{ 254 | "big5_chinese_ci": true, 255 | "sjis_japanese_ci": true, 256 | "gbk_chinese_ci": true, 257 | "big5_bin": true, 258 | "gb2312_bin": true, 259 | "gbk_bin": true, 260 | "sjis_bin": true, 261 | "cp932_japanese_ci": true, 262 | "cp932_bin": true, 263 | "gb18030_chinese_ci": true, 264 | "gb18030_bin": true, 265 | "gb18030_unicode_520_ci": true, 266 | } 267 | -------------------------------------------------------------------------------- /packets_test.go: -------------------------------------------------------------------------------- 1 | // Go MySQL Driver - A MySQL-Driver for Go's database/sql package 2 | // 3 | // Copyright 2016 The Go-MySQL-Driver Authors. All rights reserved. 4 | // 5 | // This Source Code Form is subject to the terms of the Mozilla Public 6 | // License, v. 2.0. If a copy of the MPL was not distributed with this file, 7 | // You can obtain one at http://mozilla.org/MPL/2.0/. 8 | 9 | package mysql 10 | 11 | import ( 12 | "bytes" 13 | "errors" 14 | "net" 15 | "testing" 16 | "time" 17 | ) 18 | 19 | var ( 20 | errConnClosed = errors.New("connection is closed") 21 | errConnTooManyReads = errors.New("too many reads") 22 | errConnTooManyWrites = errors.New("too many writes") 23 | ) 24 | 25 | // struct to mock a net.Conn for testing purposes 26 | type mockConn struct { 27 | laddr net.Addr 28 | raddr net.Addr 29 | data []byte 30 | written []byte 31 | queuedReplies [][]byte 32 | closed bool 33 | read int 34 | reads int 35 | writes int 36 | maxReads int 37 | maxWrites int 38 | } 39 | 40 | func (m *mockConn) Read(b []byte) (n int, err error) { 41 | if m.closed { 42 | return 0, errConnClosed 43 | } 44 | 45 | m.reads++ 46 | if m.maxReads > 0 && m.reads > m.maxReads { 47 | return 0, errConnTooManyReads 48 | } 49 | 50 | n = copy(b, m.data) 51 | m.read += n 52 | m.data = m.data[n:] 53 | return 54 | } 55 | func (m *mockConn) Write(b []byte) (n int, err error) { 56 | if m.closed { 57 | return 0, errConnClosed 58 | } 59 | 60 | m.writes++ 61 | if m.maxWrites > 0 && m.writes > m.maxWrites { 62 | return 0, errConnTooManyWrites 63 | } 64 | 65 | n = len(b) 66 | m.written = append(m.written, b...) 67 | 68 | if n > 0 && len(m.queuedReplies) > 0 { 69 | m.data = m.queuedReplies[0] 70 | m.queuedReplies = m.queuedReplies[1:] 71 | } 72 | return 73 | } 74 | func (m *mockConn) Close() error { 75 | m.closed = true 76 | return nil 77 | } 78 | func (m *mockConn) LocalAddr() net.Addr { 79 | return m.laddr 80 | } 81 | func (m *mockConn) RemoteAddr() net.Addr { 82 | return m.raddr 83 | } 84 | func (m *mockConn) SetDeadline(t time.Time) error { 85 | return nil 86 | } 87 | func (m *mockConn) SetReadDeadline(t time.Time) error { 88 | return nil 89 | } 90 | func (m *mockConn) SetWriteDeadline(t time.Time) error { 91 | return nil 92 | } 93 | 94 | // make sure mockConn implements the net.Conn interface 95 | var _ net.Conn = new(mockConn) 96 | 97 | func newRWMockConn(sequence uint8) (*mockConn, *mysqlConn) { 98 | conn := new(mockConn) 99 | connector := newConnector(NewConfig()) 100 | mc := &mysqlConn{ 101 | buf: newBuffer(), 102 | cfg: connector.cfg, 103 | connector: connector, 104 | netConn: conn, 105 | closech: make(chan struct{}), 106 | maxAllowedPacket: defaultMaxAllowedPacket, 107 | sequence: sequence, 108 | } 109 | return conn, mc 110 | } 111 | 112 | func TestReadPacketSingleByte(t *testing.T) { 113 | conn := new(mockConn) 114 | mc := &mysqlConn{ 115 | netConn: conn, 116 | buf: newBuffer(), 117 | cfg: NewConfig(), 118 | } 119 | 120 | conn.data = []byte{0x01, 0x00, 0x00, 0x00, 0xff} 121 | conn.maxReads = 1 122 | packet, err := mc.readPacket() 123 | if err != nil { 124 | t.Fatal(err) 125 | } 126 | if len(packet) != 1 { 127 | t.Fatalf("unexpected packet length: expected %d, got %d", 1, len(packet)) 128 | } 129 | if packet[0] != 0xff { 130 | t.Fatalf("unexpected packet content: expected %x, got %x", 0xff, packet[0]) 131 | } 132 | } 133 | 134 | func TestReadPacketWrongSequenceID(t *testing.T) { 135 | for _, testCase := range []struct { 136 | ClientSequenceID byte 137 | ServerSequenceID byte 138 | ExpectedErr error 139 | }{ 140 | { 141 | ClientSequenceID: 1, 142 | ServerSequenceID: 0, 143 | ExpectedErr: ErrPktSync, 144 | }, 145 | { 146 | ClientSequenceID: 0, 147 | ServerSequenceID: 0x42, 148 | ExpectedErr: ErrPktSync, 149 | }, 150 | } { 151 | conn, mc := newRWMockConn(testCase.ClientSequenceID) 152 | 153 | conn.data = []byte{0x01, 0x00, 0x00, testCase.ServerSequenceID, 0x22} 154 | _, err := mc.readPacket() 155 | if err != testCase.ExpectedErr { 156 | t.Errorf("expected %v, got %v", testCase.ExpectedErr, err) 157 | } 158 | 159 | // connection should not be returned to the pool in this state 160 | if mc.IsValid() { 161 | t.Errorf("expected IsValid() to be false") 162 | } 163 | } 164 | } 165 | 166 | func TestReadPacketSplit(t *testing.T) { 167 | conn := new(mockConn) 168 | mc := &mysqlConn{ 169 | netConn: conn, 170 | buf: newBuffer(), 171 | cfg: NewConfig(), 172 | } 173 | 174 | data := make([]byte, maxPacketSize*2+4*3) 175 | const pkt2ofs = maxPacketSize + 4 176 | const pkt3ofs = 2 * (maxPacketSize + 4) 177 | 178 | // case 1: payload has length maxPacketSize 179 | data = data[:pkt2ofs+4] 180 | 181 | // 1st packet has maxPacketSize length and sequence id 0 182 | // ff ff ff 00 ... 183 | data[0] = 0xff 184 | data[1] = 0xff 185 | data[2] = 0xff 186 | 187 | // mark the payload start and end of 1st packet so that we can check if the 188 | // content was correctly appended 189 | data[4] = 0x11 190 | data[maxPacketSize+3] = 0x22 191 | 192 | // 2nd packet has payload length 0 and sequence id 1 193 | // 00 00 00 01 194 | data[pkt2ofs+3] = 0x01 195 | 196 | conn.data = data 197 | conn.maxReads = 3 198 | packet, err := mc.readPacket() 199 | if err != nil { 200 | t.Fatal(err) 201 | } 202 | if len(packet) != maxPacketSize { 203 | t.Fatalf("unexpected packet length: expected %d, got %d", maxPacketSize, len(packet)) 204 | } 205 | if packet[0] != 0x11 { 206 | t.Fatalf("unexpected payload start: expected %x, got %x", 0x11, packet[0]) 207 | } 208 | if packet[maxPacketSize-1] != 0x22 { 209 | t.Fatalf("unexpected payload end: expected %x, got %x", 0x22, packet[maxPacketSize-1]) 210 | } 211 | 212 | // case 2: payload has length which is a multiple of maxPacketSize 213 | data = data[:cap(data)] 214 | 215 | // 2nd packet now has maxPacketSize length 216 | data[pkt2ofs] = 0xff 217 | data[pkt2ofs+1] = 0xff 218 | data[pkt2ofs+2] = 0xff 219 | 220 | // mark the payload start and end of the 2nd packet 221 | data[pkt2ofs+4] = 0x33 222 | data[pkt2ofs+maxPacketSize+3] = 0x44 223 | 224 | // 3rd packet has payload length 0 and sequence id 2 225 | // 00 00 00 02 226 | data[pkt3ofs+3] = 0x02 227 | 228 | conn.data = data 229 | conn.reads = 0 230 | conn.maxReads = 5 231 | mc.sequence = 0 232 | packet, err = mc.readPacket() 233 | if err != nil { 234 | t.Fatal(err) 235 | } 236 | if len(packet) != 2*maxPacketSize { 237 | t.Fatalf("unexpected packet length: expected %d, got %d", 2*maxPacketSize, len(packet)) 238 | } 239 | if packet[0] != 0x11 { 240 | t.Fatalf("unexpected payload start: expected %x, got %x", 0x11, packet[0]) 241 | } 242 | if packet[2*maxPacketSize-1] != 0x44 { 243 | t.Fatalf("unexpected payload end: expected %x, got %x", 0x44, packet[2*maxPacketSize-1]) 244 | } 245 | 246 | // case 3: payload has a length larger maxPacketSize, which is not an exact 247 | // multiple of it 248 | data = data[:pkt2ofs+4+42] 249 | data[pkt2ofs] = 0x2a 250 | data[pkt2ofs+1] = 0x00 251 | data[pkt2ofs+2] = 0x00 252 | data[pkt2ofs+4+41] = 0x44 253 | 254 | conn.data = data 255 | conn.reads = 0 256 | conn.maxReads = 4 257 | mc.sequence = 0 258 | packet, err = mc.readPacket() 259 | if err != nil { 260 | t.Fatal(err) 261 | } 262 | if len(packet) != maxPacketSize+42 { 263 | t.Fatalf("unexpected packet length: expected %d, got %d", maxPacketSize+42, len(packet)) 264 | } 265 | if packet[0] != 0x11 { 266 | t.Fatalf("unexpected payload start: expected %x, got %x", 0x11, packet[0]) 267 | } 268 | if packet[maxPacketSize+41] != 0x44 { 269 | t.Fatalf("unexpected payload end: expected %x, got %x", 0x44, packet[maxPacketSize+41]) 270 | } 271 | } 272 | 273 | func TestReadPacketFail(t *testing.T) { 274 | conn := new(mockConn) 275 | mc := &mysqlConn{ 276 | netConn: conn, 277 | buf: newBuffer(), 278 | closech: make(chan struct{}), 279 | cfg: NewConfig(), 280 | } 281 | 282 | // illegal empty (stand-alone) packet 283 | conn.data = []byte{0x00, 0x00, 0x00, 0x00} 284 | conn.maxReads = 1 285 | _, err := mc.readPacket() 286 | if err != ErrInvalidConn { 287 | t.Errorf("expected ErrInvalidConn, got %v", err) 288 | } 289 | 290 | // reset 291 | conn.reads = 0 292 | mc.sequence = 0 293 | mc.buf = newBuffer() 294 | 295 | // fail to read header 296 | conn.closed = true 297 | _, err = mc.readPacket() 298 | if err != ErrInvalidConn { 299 | t.Errorf("expected ErrInvalidConn, got %v", err) 300 | } 301 | 302 | // reset 303 | conn.closed = false 304 | conn.reads = 0 305 | mc.sequence = 0 306 | mc.buf = newBuffer() 307 | 308 | // fail to read body 309 | conn.maxReads = 1 310 | _, err = mc.readPacket() 311 | if err != ErrInvalidConn { 312 | t.Errorf("expected ErrInvalidConn, got %v", err) 313 | } 314 | } 315 | 316 | // https://github.com/go-sql-driver/mysql/pull/801 317 | // not-NUL terminated plugin_name in init packet 318 | func TestRegression801(t *testing.T) { 319 | conn := new(mockConn) 320 | mc := &mysqlConn{ 321 | netConn: conn, 322 | buf: newBuffer(), 323 | cfg: new(Config), 324 | sequence: 42, 325 | closech: make(chan struct{}), 326 | } 327 | 328 | conn.data = []byte{72, 0, 0, 42, 10, 53, 46, 53, 46, 56, 0, 165, 0, 0, 0, 329 | 60, 70, 63, 58, 68, 104, 34, 97, 0, 223, 247, 33, 2, 0, 15, 128, 21, 0, 330 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 98, 120, 114, 47, 85, 75, 109, 99, 51, 77, 331 | 50, 64, 0, 109, 121, 115, 113, 108, 95, 110, 97, 116, 105, 118, 101, 95, 332 | 112, 97, 115, 115, 119, 111, 114, 100} 333 | conn.maxReads = 1 334 | 335 | authData, serverCapabilities, serverExtendedCapabilities, pluginName, err := mc.readHandshakePacket() 336 | if err != nil { 337 | t.Fatalf("got error: %v", err) 338 | } 339 | 340 | if serverCapabilities != 2148530143 { 341 | t.Fatalf("expected serverCapabilities to be 2148530143, got %v", serverCapabilities) 342 | } 343 | 344 | if serverExtendedCapabilities != 0 { 345 | t.Fatalf("expected serverExtendedCapabilities to be 0, got %v", serverExtendedCapabilities) 346 | } 347 | 348 | if pluginName != "mysql_native_password" { 349 | t.Errorf("expected plugin name 'mysql_native_password', got '%s'", pluginName) 350 | } 351 | 352 | expectedAuthData := []byte{60, 70, 63, 58, 68, 104, 34, 97, 98, 120, 114, 353 | 47, 85, 75, 109, 99, 51, 77, 50, 64} 354 | if !bytes.Equal(authData, expectedAuthData) { 355 | t.Errorf("expected authData '%v', got '%v'", expectedAuthData, authData) 356 | } 357 | } 358 | -------------------------------------------------------------------------------- /benchmark_test.go: -------------------------------------------------------------------------------- 1 | // Go MySQL Driver - A MySQL-Driver for Go's database/sql package 2 | // 3 | // Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. 4 | // 5 | // This Source Code Form is subject to the terms of the Mozilla Public 6 | // License, v. 2.0. If a copy of the MPL was not distributed with this file, 7 | // You can obtain one at http://mozilla.org/MPL/2.0/. 8 | 9 | package mysql 10 | 11 | import ( 12 | "bytes" 13 | "context" 14 | "database/sql" 15 | "database/sql/driver" 16 | "fmt" 17 | "math" 18 | "runtime" 19 | "strings" 20 | "sync" 21 | "sync/atomic" 22 | "testing" 23 | "time" 24 | ) 25 | 26 | type TB testing.B 27 | 28 | func (tb *TB) check(err error) { 29 | if err != nil { 30 | tb.Fatal(err) 31 | } 32 | } 33 | 34 | func (tb *TB) checkDB(db *sql.DB, err error) *sql.DB { 35 | tb.check(err) 36 | return db 37 | } 38 | 39 | func (tb *TB) checkRows(rows *sql.Rows, err error) *sql.Rows { 40 | tb.check(err) 41 | return rows 42 | } 43 | 44 | func (tb *TB) checkStmt(stmt *sql.Stmt, err error) *sql.Stmt { 45 | tb.check(err) 46 | return stmt 47 | } 48 | 49 | func initDB(b *testing.B, compress bool, queries ...string) *sql.DB { 50 | tb := (*TB)(b) 51 | comprStr := "" 52 | if compress { 53 | comprStr = "&compress=1" 54 | } 55 | db := tb.checkDB(sql.Open(driverNameTest, dsn+comprStr)) 56 | for _, query := range queries { 57 | if _, err := db.Exec(query); err != nil { 58 | b.Fatalf("error on %q: %v", query, err) 59 | } 60 | } 61 | return db 62 | } 63 | 64 | const concurrencyLevel = 10 65 | 66 | func BenchmarkQuery(b *testing.B) { 67 | benchmarkQuery(b, false) 68 | } 69 | 70 | func BenchmarkQueryCompressed(b *testing.B) { 71 | benchmarkQuery(b, true) 72 | } 73 | 74 | func benchmarkQuery(b *testing.B, compr bool) { 75 | tb := (*TB)(b) 76 | b.ReportAllocs() 77 | db := initDB(b, compr, 78 | "DROP TABLE IF EXISTS foo", 79 | "CREATE TABLE foo (id INT PRIMARY KEY, val CHAR(50))", 80 | `INSERT INTO foo VALUES (1, "one")`, 81 | `INSERT INTO foo VALUES (2, "two")`, 82 | ) 83 | db.SetMaxIdleConns(concurrencyLevel) 84 | defer db.Close() 85 | 86 | stmt := tb.checkStmt(db.Prepare("SELECT val FROM foo WHERE id=?")) 87 | defer stmt.Close() 88 | 89 | remain := int64(b.N) 90 | var wg sync.WaitGroup 91 | wg.Add(concurrencyLevel) 92 | defer wg.Wait() 93 | b.StartTimer() 94 | 95 | for i := 0; i < concurrencyLevel; i++ { 96 | go func() { 97 | for { 98 | if atomic.AddInt64(&remain, -1) < 0 { 99 | wg.Done() 100 | return 101 | } 102 | 103 | var got string 104 | tb.check(stmt.QueryRow(1).Scan(&got)) 105 | if got != "one" { 106 | b.Errorf("query = %q; want one", got) 107 | wg.Done() 108 | return 109 | } 110 | } 111 | }() 112 | } 113 | } 114 | 115 | func BenchmarkExec(b *testing.B) { 116 | tb := (*TB)(b) 117 | db := tb.checkDB(sql.Open(driverNameTest, dsn)) 118 | db.SetMaxIdleConns(concurrencyLevel) 119 | defer db.Close() 120 | 121 | stmt := tb.checkStmt(db.Prepare("DO 1")) 122 | defer stmt.Close() 123 | 124 | remain := int64(b.N) 125 | var wg sync.WaitGroup 126 | wg.Add(concurrencyLevel) 127 | defer wg.Wait() 128 | 129 | b.ReportAllocs() 130 | b.ResetTimer() 131 | 132 | for i := 0; i < concurrencyLevel; i++ { 133 | go func() { 134 | for { 135 | if atomic.AddInt64(&remain, -1) < 0 { 136 | wg.Done() 137 | return 138 | } 139 | 140 | if _, err := stmt.Exec(); err != nil { 141 | b.Logf("stmt.Exec failed: %v", err) 142 | b.Fail() 143 | } 144 | } 145 | }() 146 | } 147 | } 148 | 149 | // data, but no db writes 150 | var roundtripSample []byte 151 | 152 | func initRoundtripBenchmarks() ([]byte, int, int) { 153 | if roundtripSample == nil { 154 | roundtripSample = []byte(strings.Repeat("0123456789abcdef", 1024*1024)) 155 | } 156 | return roundtripSample, 16, len(roundtripSample) 157 | } 158 | 159 | func BenchmarkRoundtripTxt(b *testing.B) { 160 | sample, min, max := initRoundtripBenchmarks() 161 | sampleString := string(sample) 162 | tb := (*TB)(b) 163 | db := tb.checkDB(sql.Open(driverNameTest, dsn)) 164 | defer db.Close() 165 | 166 | b.ReportAllocs() 167 | b.ResetTimer() 168 | 169 | var result string 170 | for i := 0; i < b.N; i++ { 171 | length := min + i 172 | if length > max { 173 | length = max 174 | } 175 | test := sampleString[0:length] 176 | rows := tb.checkRows(db.Query(`SELECT "` + test + `"`)) 177 | if !rows.Next() { 178 | rows.Close() 179 | b.Fatalf("crashed") 180 | } 181 | err := rows.Scan(&result) 182 | if err != nil { 183 | rows.Close() 184 | b.Fatalf("crashed") 185 | } 186 | if result != test { 187 | rows.Close() 188 | b.Errorf("mismatch") 189 | } 190 | rows.Close() 191 | } 192 | } 193 | 194 | func BenchmarkRoundtripBin(b *testing.B) { 195 | sample, min, max := initRoundtripBenchmarks() 196 | tb := (*TB)(b) 197 | db := tb.checkDB(sql.Open(driverNameTest, dsn)) 198 | defer db.Close() 199 | stmt := tb.checkStmt(db.Prepare("SELECT ?")) 200 | defer stmt.Close() 201 | 202 | b.ReportAllocs() 203 | b.ResetTimer() 204 | var result sql.RawBytes 205 | for i := 0; i < b.N; i++ { 206 | length := min + i 207 | if length > max { 208 | length = max 209 | } 210 | test := sample[0:length] 211 | rows := tb.checkRows(stmt.Query(test)) 212 | if !rows.Next() { 213 | rows.Close() 214 | b.Fatalf("crashed") 215 | } 216 | err := rows.Scan(&result) 217 | if err != nil { 218 | rows.Close() 219 | b.Fatalf("crashed") 220 | } 221 | if !bytes.Equal(result, test) { 222 | rows.Close() 223 | b.Errorf("mismatch") 224 | } 225 | rows.Close() 226 | } 227 | } 228 | 229 | func BenchmarkInterpolation(b *testing.B) { 230 | mc := &mysqlConn{ 231 | cfg: &Config{ 232 | InterpolateParams: true, 233 | Loc: time.UTC, 234 | }, 235 | maxAllowedPacket: maxPacketSize, 236 | maxWriteSize: maxPacketSize - 1, 237 | buf: newBuffer(), 238 | } 239 | 240 | args := []driver.Value{ 241 | int64(42424242), 242 | float64(math.Pi), 243 | false, 244 | time.Unix(1423411542, 807015000), 245 | []byte("bytes containing special chars ' \" \a \x00"), 246 | "string containing special chars ' \" \a \x00", 247 | } 248 | q := "SELECT ?, ?, ?, ?, ?, ?" 249 | 250 | b.ReportAllocs() 251 | b.ResetTimer() 252 | for i := 0; i < b.N; i++ { 253 | _, err := mc.interpolateParams(q, args) 254 | if err != nil { 255 | b.Fatal(err) 256 | } 257 | } 258 | } 259 | 260 | func benchmarkQueryContext(b *testing.B, db *sql.DB, p int) { 261 | ctx, cancel := context.WithCancel(context.Background()) 262 | defer cancel() 263 | db.SetMaxIdleConns(p * runtime.GOMAXPROCS(0)) 264 | 265 | tb := (*TB)(b) 266 | stmt := tb.checkStmt(db.PrepareContext(ctx, "SELECT val FROM foo WHERE id=?")) 267 | defer stmt.Close() 268 | 269 | b.SetParallelism(p) 270 | b.ReportAllocs() 271 | b.ResetTimer() 272 | b.RunParallel(func(pb *testing.PB) { 273 | var got string 274 | for pb.Next() { 275 | tb.check(stmt.QueryRow(1).Scan(&got)) 276 | if got != "one" { 277 | b.Fatalf("query = %q; want one", got) 278 | } 279 | } 280 | }) 281 | } 282 | 283 | func BenchmarkQueryContext(b *testing.B) { 284 | db := initDB(b, false, 285 | "DROP TABLE IF EXISTS foo", 286 | "CREATE TABLE foo (id INT PRIMARY KEY, val CHAR(50))", 287 | `INSERT INTO foo VALUES (1, "one")`, 288 | `INSERT INTO foo VALUES (2, "two")`, 289 | ) 290 | defer db.Close() 291 | for _, p := range []int{1, 2, 3, 4} { 292 | b.Run(fmt.Sprintf("%d", p), func(b *testing.B) { 293 | benchmarkQueryContext(b, db, p) 294 | }) 295 | } 296 | } 297 | 298 | func benchmarkExecContext(b *testing.B, db *sql.DB, p int) { 299 | ctx, cancel := context.WithCancel(context.Background()) 300 | defer cancel() 301 | db.SetMaxIdleConns(p * runtime.GOMAXPROCS(0)) 302 | 303 | tb := (*TB)(b) 304 | stmt := tb.checkStmt(db.PrepareContext(ctx, "DO 1")) 305 | defer stmt.Close() 306 | 307 | b.SetParallelism(p) 308 | b.ReportAllocs() 309 | b.ResetTimer() 310 | b.RunParallel(func(pb *testing.PB) { 311 | for pb.Next() { 312 | if _, err := stmt.ExecContext(ctx); err != nil { 313 | b.Fatal(err) 314 | } 315 | } 316 | }) 317 | } 318 | 319 | func BenchmarkExecContext(b *testing.B) { 320 | db := initDB(b, false, 321 | "DROP TABLE IF EXISTS foo", 322 | "CREATE TABLE foo (id INT PRIMARY KEY, val CHAR(50))", 323 | `INSERT INTO foo VALUES (1, "one")`, 324 | `INSERT INTO foo VALUES (2, "two")`, 325 | ) 326 | defer db.Close() 327 | for _, p := range []int{1, 2, 3, 4} { 328 | b.Run(fmt.Sprintf("%d", p), func(b *testing.B) { 329 | benchmarkExecContext(b, db, p) 330 | }) 331 | } 332 | } 333 | 334 | // BenchmarkQueryRawBytes benchmarks fetching 100 blobs using sql.RawBytes. 335 | // "size=" means size of each blobs. 336 | func BenchmarkQueryRawBytes(b *testing.B) { 337 | var sizes []int = []int{100, 1000, 2000, 4000, 8000, 12000, 16000, 32000, 64000, 256000} 338 | db := initDB(b, false, 339 | "DROP TABLE IF EXISTS bench_rawbytes", 340 | "CREATE TABLE bench_rawbytes (id INT PRIMARY KEY, val LONGBLOB)", 341 | ) 342 | defer db.Close() 343 | 344 | blob := make([]byte, sizes[len(sizes)-1]) 345 | for i := range blob { 346 | blob[i] = 42 347 | } 348 | for i := 0; i < 100; i++ { 349 | _, err := db.Exec("INSERT INTO bench_rawbytes VALUES (?, ?)", i, blob) 350 | if err != nil { 351 | b.Fatal(err) 352 | } 353 | } 354 | 355 | for _, s := range sizes { 356 | b.Run(fmt.Sprintf("size=%v", s), func(b *testing.B) { 357 | db.SetMaxIdleConns(0) 358 | db.SetMaxIdleConns(1) 359 | b.ReportAllocs() 360 | b.ResetTimer() 361 | 362 | for j := 0; j < b.N; j++ { 363 | rows, err := db.Query("SELECT LEFT(val, ?) as v FROM bench_rawbytes", s) 364 | if err != nil { 365 | b.Fatal(err) 366 | } 367 | nrows := 0 368 | for rows.Next() { 369 | var buf sql.RawBytes 370 | err := rows.Scan(&buf) 371 | if err != nil { 372 | b.Fatal(err) 373 | } 374 | if len(buf) != s { 375 | b.Fatalf("size mismatch: expected %v, got %v", s, len(buf)) 376 | } 377 | nrows++ 378 | } 379 | rows.Close() 380 | if nrows != 100 { 381 | b.Fatalf("numbers of rows mismatch: expected %v, got %v", 100, nrows) 382 | } 383 | } 384 | }) 385 | } 386 | } 387 | 388 | func benchmark10kRows(b *testing.B, compress bool) { 389 | // Setup -- prepare 10000 rows. 390 | db := initDB(b, compress, 391 | "DROP TABLE IF EXISTS foo", 392 | "CREATE TABLE foo (id INT PRIMARY KEY, val TEXT)") 393 | defer db.Close() 394 | 395 | sval := strings.Repeat("x", 50) 396 | stmt, err := db.Prepare(`INSERT INTO foo (id, val) VALUES (?, ?)` + strings.Repeat(",(?,?)", 99)) 397 | if err != nil { 398 | b.Errorf("failed to prepare query: %v", err) 399 | return 400 | } 401 | 402 | args := make([]any, 200) 403 | for i := 1; i < 200; i += 2 { 404 | args[i] = sval 405 | } 406 | for i := 0; i < 10000; i += 100 { 407 | for j := 0; j < 100; j++ { 408 | args[j*2] = i + j 409 | } 410 | _, err := stmt.Exec(args...) 411 | if err != nil { 412 | b.Error(err) 413 | return 414 | } 415 | } 416 | stmt.Close() 417 | 418 | // benchmark function called several times with different b.N. 419 | // it means heavy setup is called multiple times. 420 | // Use b.Run() to run expensive setup only once. 421 | // Go 1.24 introduced b.Loop() for this purpose. But we keep this 422 | // benchmark compatible with Go 1.20. 423 | b.Run("query", func(b *testing.B) { 424 | b.ReportAllocs() 425 | for i := 0; i < b.N; i++ { 426 | rows, err := db.Query(`SELECT id, val FROM foo`) 427 | if err != nil { 428 | b.Errorf("failed to select: %v", err) 429 | return 430 | } 431 | // rows.Scan() escapes arguments. So these variables must be defined 432 | // before loop. 433 | var i int 434 | var s sql.RawBytes 435 | for rows.Next() { 436 | if err := rows.Scan(&i, &s); err != nil { 437 | b.Errorf("failed to scan: %v", err) 438 | rows.Close() 439 | return 440 | } 441 | } 442 | if err = rows.Err(); err != nil { 443 | b.Errorf("failed to read rows: %v", err) 444 | } 445 | rows.Close() 446 | } 447 | }) 448 | } 449 | 450 | // BenchmarkReceive10kRows measures performance of receiving large number of rows. 451 | func BenchmarkReceive10kRows(b *testing.B) { 452 | benchmark10kRows(b, false) 453 | } 454 | 455 | func BenchmarkReceive10kRowsCompressed(b *testing.B) { 456 | benchmark10kRows(b, true) 457 | } 458 | 459 | // BenchmarkReceiveMetadata measures performance of receiving lots of metadata compare to data in rows 460 | func BenchmarkReceiveMetadata(b *testing.B) { 461 | tb := (*TB)(b) 462 | 463 | // Create a table with 1000 integer fields 464 | createTableQuery := "CREATE TABLE large_integer_table (" 465 | for i := 0; i < 1000; i++ { 466 | createTableQuery += fmt.Sprintf("col_%d INT", i) 467 | if i < 999 { 468 | createTableQuery += ", " 469 | } 470 | } 471 | createTableQuery += ")" 472 | 473 | // Initialize database 474 | db := initDB(b, false, 475 | "DROP TABLE IF EXISTS large_integer_table", 476 | createTableQuery, 477 | "INSERT INTO large_integer_table VALUES ("+ 478 | strings.Repeat("0,", 999)+"0)", // Insert a row of zeros 479 | ) 480 | defer db.Close() 481 | 482 | b.Run("query", func(b *testing.B) { 483 | db.SetMaxIdleConns(0) 484 | db.SetMaxIdleConns(1) 485 | 486 | // Create a slice to scan all columns 487 | values := make([]any, 1000) 488 | valuePtrs := make([]any, 1000) 489 | for j := range values { 490 | valuePtrs[j] = &values[j] 491 | } 492 | 493 | // Prepare a SELECT query to retrieve metadata 494 | stmt := tb.checkStmt(db.Prepare("SELECT * FROM large_integer_table LIMIT 1")) 495 | defer stmt.Close() 496 | 497 | // Benchmark metadata retrieval 498 | b.ReportAllocs() 499 | b.ResetTimer() 500 | for range b.N { 501 | rows := tb.checkRows(stmt.Query()) 502 | 503 | rows.Next() 504 | // Scan the row 505 | err := rows.Scan(valuePtrs...) 506 | tb.check(err) 507 | 508 | rows.Close() 509 | } 510 | }) 511 | } 512 | -------------------------------------------------------------------------------- /auth.go: -------------------------------------------------------------------------------- 1 | // Go MySQL Driver - A MySQL-Driver for Go's database/sql package 2 | // 3 | // Copyright 2018 The Go-MySQL-Driver Authors. All rights reserved. 4 | // 5 | // This Source Code Form is subject to the terms of the Mozilla Public 6 | // License, v. 2.0. If a copy of the MPL was not distributed with this file, 7 | // You can obtain one at http://mozilla.org/MPL/2.0/. 8 | 9 | package mysql 10 | 11 | import ( 12 | "crypto/rand" 13 | "crypto/rsa" 14 | "crypto/sha1" 15 | "crypto/sha256" 16 | "crypto/sha512" 17 | "crypto/x509" 18 | "encoding/pem" 19 | "fmt" 20 | "sync" 21 | 22 | "filippo.io/edwards25519" 23 | ) 24 | 25 | // server pub keys registry 26 | var ( 27 | serverPubKeyLock sync.RWMutex 28 | serverPubKeyRegistry map[string]*rsa.PublicKey 29 | ) 30 | 31 | // RegisterServerPubKey registers a server RSA public key which can be used to 32 | // send data in a secure manner to the server without receiving the public key 33 | // in a potentially insecure way from the server first. 34 | // Registered keys can afterwards be used adding serverPubKey= to the DSN. 35 | // 36 | // Note: The provided rsa.PublicKey instance is exclusively owned by the driver 37 | // after registering it and may not be modified. 38 | // 39 | // data, err := os.ReadFile("mykey.pem") 40 | // if err != nil { 41 | // log.Fatal(err) 42 | // } 43 | // 44 | // block, _ := pem.Decode(data) 45 | // if block == nil || block.Type != "PUBLIC KEY" { 46 | // log.Fatal("failed to decode PEM block containing public key") 47 | // } 48 | // 49 | // pub, err := x509.ParsePKIXPublicKey(block.Bytes) 50 | // if err != nil { 51 | // log.Fatal(err) 52 | // } 53 | // 54 | // if rsaPubKey, ok := pub.(*rsa.PublicKey); ok { 55 | // mysql.RegisterServerPubKey("mykey", rsaPubKey) 56 | // } else { 57 | // log.Fatal("not a RSA public key") 58 | // } 59 | func RegisterServerPubKey(name string, pubKey *rsa.PublicKey) { 60 | serverPubKeyLock.Lock() 61 | if serverPubKeyRegistry == nil { 62 | serverPubKeyRegistry = make(map[string]*rsa.PublicKey) 63 | } 64 | 65 | serverPubKeyRegistry[name] = pubKey 66 | serverPubKeyLock.Unlock() 67 | } 68 | 69 | // DeregisterServerPubKey removes the public key registered with the given name. 70 | func DeregisterServerPubKey(name string) { 71 | serverPubKeyLock.Lock() 72 | if serverPubKeyRegistry != nil { 73 | delete(serverPubKeyRegistry, name) 74 | } 75 | serverPubKeyLock.Unlock() 76 | } 77 | 78 | func getServerPubKey(name string) (pubKey *rsa.PublicKey) { 79 | serverPubKeyLock.RLock() 80 | if v, ok := serverPubKeyRegistry[name]; ok { 81 | pubKey = v 82 | } 83 | serverPubKeyLock.RUnlock() 84 | return 85 | } 86 | 87 | // Hash password using pre 4.1 (old password) method 88 | // https://github.com/atcurtis/mariadb/blob/master/mysys/my_rnd.c 89 | type myRnd struct { 90 | seed1, seed2 uint32 91 | } 92 | 93 | const myRndMaxVal = 0x3FFFFFFF 94 | 95 | // Pseudo random number generator 96 | func newMyRnd(seed1, seed2 uint32) *myRnd { 97 | return &myRnd{ 98 | seed1: seed1 % myRndMaxVal, 99 | seed2: seed2 % myRndMaxVal, 100 | } 101 | } 102 | 103 | // Tested to be equivalent to MariaDB's floating point variant 104 | // http://play.golang.org/p/QHvhd4qved 105 | // http://play.golang.org/p/RG0q4ElWDx 106 | func (r *myRnd) NextByte() byte { 107 | r.seed1 = (r.seed1*3 + r.seed2) % myRndMaxVal 108 | r.seed2 = (r.seed1 + r.seed2 + 33) % myRndMaxVal 109 | 110 | return byte(uint64(r.seed1) * 31 / myRndMaxVal) 111 | } 112 | 113 | // Generate binary hash from byte string using insecure pre 4.1 method 114 | func pwHash(password []byte) (result [2]uint32) { 115 | var add uint32 = 7 116 | var tmp uint32 117 | 118 | result[0] = 1345345333 119 | result[1] = 0x12345671 120 | 121 | for _, c := range password { 122 | // skip spaces and tabs in password 123 | if c == ' ' || c == '\t' { 124 | continue 125 | } 126 | 127 | tmp = uint32(c) 128 | result[0] ^= (((result[0] & 63) + add) * tmp) + (result[0] << 8) 129 | result[1] += (result[1] << 8) ^ result[0] 130 | add += tmp 131 | } 132 | 133 | // Remove sign bit (1<<31)-1) 134 | result[0] &= 0x7FFFFFFF 135 | result[1] &= 0x7FFFFFFF 136 | 137 | return 138 | } 139 | 140 | // Hash password using insecure pre 4.1 method 141 | func scrambleOldPassword(scramble []byte, password string) []byte { 142 | scramble = scramble[:8] 143 | 144 | hashPw := pwHash([]byte(password)) 145 | hashSc := pwHash(scramble) 146 | 147 | r := newMyRnd(hashPw[0]^hashSc[0], hashPw[1]^hashSc[1]) 148 | 149 | var out [8]byte 150 | for i := range out { 151 | out[i] = r.NextByte() + 64 152 | } 153 | 154 | mask := r.NextByte() 155 | for i := range out { 156 | out[i] ^= mask 157 | } 158 | 159 | return out[:] 160 | } 161 | 162 | // Hash password using 4.1+ method (SHA1) 163 | func scramblePassword(scramble []byte, password string) []byte { 164 | if len(password) == 0 { 165 | return nil 166 | } 167 | 168 | // stage1Hash = SHA1(password) 169 | crypt := sha1.New() 170 | crypt.Write([]byte(password)) 171 | stage1 := crypt.Sum(nil) 172 | 173 | // scrambleHash = SHA1(scramble + SHA1(stage1Hash)) 174 | // inner Hash 175 | crypt.Reset() 176 | crypt.Write(stage1) 177 | hash := crypt.Sum(nil) 178 | 179 | // outer Hash 180 | crypt.Reset() 181 | crypt.Write(scramble) 182 | crypt.Write(hash) 183 | scramble = crypt.Sum(nil) 184 | 185 | // token = scrambleHash XOR stage1Hash 186 | for i := range scramble { 187 | scramble[i] ^= stage1[i] 188 | } 189 | return scramble 190 | } 191 | 192 | // Hash password using MySQL 8+ method (SHA256) 193 | func scrambleSHA256Password(scramble []byte, password string) []byte { 194 | if len(password) == 0 { 195 | return nil 196 | } 197 | 198 | // XOR(SHA256(password), SHA256(SHA256(SHA256(password)), scramble)) 199 | 200 | crypt := sha256.New() 201 | crypt.Write([]byte(password)) 202 | message1 := crypt.Sum(nil) 203 | 204 | crypt.Reset() 205 | crypt.Write(message1) 206 | message1Hash := crypt.Sum(nil) 207 | 208 | crypt.Reset() 209 | crypt.Write(message1Hash) 210 | crypt.Write(scramble) 211 | message2 := crypt.Sum(nil) 212 | 213 | for i := range message1 { 214 | message1[i] ^= message2[i] 215 | } 216 | 217 | return message1 218 | } 219 | 220 | func encryptPassword(password string, seed []byte, pub *rsa.PublicKey) ([]byte, error) { 221 | plain := make([]byte, len(password)+1) 222 | copy(plain, password) 223 | for i := range plain { 224 | j := i % len(seed) 225 | plain[i] ^= seed[j] 226 | } 227 | sha1 := sha1.New() 228 | return rsa.EncryptOAEP(sha1, rand.Reader, pub, plain, nil) 229 | } 230 | 231 | // authEd25519 does ed25519 authentication used by MariaDB. 232 | func authEd25519(scramble []byte, password string) ([]byte, error) { 233 | // Derived from https://github.com/MariaDB/server/blob/d8e6bb00888b1f82c031938f4c8ac5d97f6874c3/plugin/auth_ed25519/ref10/sign.c 234 | // Code style is from https://cs.opensource.google/go/go/+/refs/tags/go1.21.5:src/crypto/ed25519/ed25519.go;l=207 235 | h := sha512.Sum512([]byte(password)) 236 | 237 | s, err := edwards25519.NewScalar().SetBytesWithClamping(h[:32]) 238 | if err != nil { 239 | return nil, err 240 | } 241 | A := (&edwards25519.Point{}).ScalarBaseMult(s) 242 | 243 | mh := sha512.New() 244 | mh.Write(h[32:]) 245 | mh.Write(scramble) 246 | messageDigest := mh.Sum(nil) 247 | r, err := edwards25519.NewScalar().SetUniformBytes(messageDigest) 248 | if err != nil { 249 | return nil, err 250 | } 251 | 252 | R := (&edwards25519.Point{}).ScalarBaseMult(r) 253 | 254 | kh := sha512.New() 255 | kh.Write(R.Bytes()) 256 | kh.Write(A.Bytes()) 257 | kh.Write(scramble) 258 | hramDigest := kh.Sum(nil) 259 | k, err := edwards25519.NewScalar().SetUniformBytes(hramDigest) 260 | if err != nil { 261 | return nil, err 262 | } 263 | 264 | S := k.MultiplyAdd(k, s, r) 265 | 266 | return append(R.Bytes(), S.Bytes()...), nil 267 | } 268 | 269 | func (mc *mysqlConn) sendEncryptedPassword(seed []byte, pub *rsa.PublicKey) error { 270 | enc, err := encryptPassword(mc.cfg.Passwd, seed, pub) 271 | if err != nil { 272 | return err 273 | } 274 | return mc.writeAuthSwitchPacket(enc) 275 | } 276 | 277 | func (mc *mysqlConn) auth(authData []byte, plugin string) ([]byte, error) { 278 | switch plugin { 279 | case "caching_sha2_password": 280 | authResp := scrambleSHA256Password(authData, mc.cfg.Passwd) 281 | return authResp, nil 282 | 283 | case "mysql_old_password": 284 | if !mc.cfg.AllowOldPasswords { 285 | return nil, ErrOldPassword 286 | } 287 | if len(mc.cfg.Passwd) == 0 { 288 | return nil, nil 289 | } 290 | // Note: there are edge cases where this should work but doesn't; 291 | // this is currently "wontfix": 292 | // https://github.com/go-sql-driver/mysql/issues/184 293 | authResp := append(scrambleOldPassword(authData[:8], mc.cfg.Passwd), 0) 294 | return authResp, nil 295 | 296 | case "mysql_clear_password": 297 | if !mc.cfg.AllowCleartextPasswords { 298 | return nil, ErrCleartextPassword 299 | } 300 | // http://dev.mysql.com/doc/refman/5.7/en/cleartext-authentication-plugin.html 301 | // http://dev.mysql.com/doc/refman/5.7/en/pam-authentication-plugin.html 302 | return append([]byte(mc.cfg.Passwd), 0), nil 303 | 304 | case "mysql_native_password": 305 | if !mc.cfg.AllowNativePasswords { 306 | return nil, ErrNativePassword 307 | } 308 | // https://dev.mysql.com/doc/dev/mysql-server/8.4.5/page_protocol_connection_phase_authentication_methods_native_password_authentication.html 309 | // Native password authentication only need and will need 20-byte challenge. 310 | authResp := scramblePassword(authData[:20], mc.cfg.Passwd) 311 | return authResp, nil 312 | 313 | case "sha256_password": 314 | if len(mc.cfg.Passwd) == 0 { 315 | return []byte{0}, nil 316 | } 317 | // unlike caching_sha2_password, sha256_password does not accept 318 | // cleartext password on unix transport. 319 | if mc.cfg.TLS != nil { 320 | // write cleartext auth packet 321 | return append([]byte(mc.cfg.Passwd), 0), nil 322 | } 323 | 324 | pubKey := mc.cfg.pubKey 325 | if pubKey == nil { 326 | // request public key from server 327 | return []byte{1}, nil 328 | } 329 | 330 | // encrypted password 331 | enc, err := encryptPassword(mc.cfg.Passwd, authData, pubKey) 332 | return enc, err 333 | 334 | case "client_ed25519": 335 | if len(authData) != 32 { 336 | return nil, ErrMalformPkt 337 | } 338 | return authEd25519(authData, mc.cfg.Passwd) 339 | 340 | default: 341 | mc.log("unknown auth plugin:", plugin) 342 | return nil, ErrUnknownPlugin 343 | } 344 | } 345 | 346 | func (mc *mysqlConn) handleAuthResult(oldAuthData []byte, plugin string) error { 347 | // Read Result Packet 348 | authData, newPlugin, err := mc.readAuthResult() 349 | if err != nil { 350 | return err 351 | } 352 | 353 | // handle auth plugin switch, if requested 354 | if newPlugin != "" { 355 | // If CLIENT_PLUGIN_AUTH capability is not supported, no new cipher is 356 | // sent and we have to keep using the cipher sent in the init packet. 357 | if authData == nil { 358 | authData = oldAuthData 359 | } else { 360 | // copy data from read buffer to owned slice 361 | copy(oldAuthData, authData) 362 | } 363 | 364 | plugin = newPlugin 365 | 366 | authResp, err := mc.auth(authData, plugin) 367 | if err != nil { 368 | return err 369 | } 370 | if err = mc.writeAuthSwitchPacket(authResp); err != nil { 371 | return err 372 | } 373 | 374 | // Read Result Packet 375 | authData, newPlugin, err = mc.readAuthResult() 376 | if err != nil { 377 | return err 378 | } 379 | 380 | // Do not allow to change the auth plugin more than once 381 | if newPlugin != "" { 382 | return ErrMalformPkt 383 | } 384 | } 385 | 386 | switch plugin { 387 | 388 | // https://dev.mysql.com/blog-archive/preparing-your-community-connector-for-mysql-8-part-2-sha256/ 389 | case "caching_sha2_password": 390 | switch len(authData) { 391 | case 0: 392 | return nil // auth successful 393 | case 1: 394 | switch authData[0] { 395 | case cachingSha2PasswordFastAuthSuccess: 396 | if err = mc.resultUnchanged().readResultOK(); err == nil { 397 | return nil // auth successful 398 | } 399 | 400 | case cachingSha2PasswordPerformFullAuthentication: 401 | if mc.cfg.TLS != nil || mc.cfg.Net == "unix" { 402 | // write cleartext auth packet 403 | err = mc.writeAuthSwitchPacket(append([]byte(mc.cfg.Passwd), 0)) 404 | if err != nil { 405 | return err 406 | } 407 | } else { 408 | pubKey := mc.cfg.pubKey 409 | if pubKey == nil { 410 | // request public key from server 411 | data, err := mc.buf.takeSmallBuffer(4 + 1) 412 | if err != nil { 413 | return err 414 | } 415 | data[4] = cachingSha2PasswordRequestPublicKey 416 | err = mc.writePacket(data) 417 | if err != nil { 418 | return err 419 | } 420 | 421 | if data, err = mc.readPacket(); err != nil { 422 | return err 423 | } 424 | 425 | if data[0] != iAuthMoreData { 426 | return fmt.Errorf("unexpected resp from server for caching_sha2_password, perform full authentication") 427 | } 428 | 429 | // parse public key 430 | block, rest := pem.Decode(data[1:]) 431 | if block == nil { 432 | return fmt.Errorf("no pem data found, data: %s", rest) 433 | } 434 | pkix, err := x509.ParsePKIXPublicKey(block.Bytes) 435 | if err != nil { 436 | return err 437 | } 438 | pubKey = pkix.(*rsa.PublicKey) 439 | } 440 | 441 | // send encrypted password 442 | err = mc.sendEncryptedPassword(oldAuthData, pubKey) 443 | if err != nil { 444 | return err 445 | } 446 | } 447 | return mc.resultUnchanged().readResultOK() 448 | 449 | default: 450 | return ErrMalformPkt 451 | } 452 | default: 453 | return ErrMalformPkt 454 | } 455 | 456 | case "sha256_password": 457 | switch len(authData) { 458 | case 0: 459 | return nil // auth successful 460 | default: 461 | block, _ := pem.Decode(authData) 462 | if block == nil { 463 | return fmt.Errorf("no Pem data found, data: %s", authData) 464 | } 465 | 466 | pub, err := x509.ParsePKIXPublicKey(block.Bytes) 467 | if err != nil { 468 | return err 469 | } 470 | 471 | // send encrypted password 472 | err = mc.sendEncryptedPassword(oldAuthData, pub.(*rsa.PublicKey)) 473 | if err != nil { 474 | return err 475 | } 476 | return mc.resultUnchanged().readResultOK() 477 | } 478 | 479 | default: 480 | return nil // auth successful 481 | } 482 | 483 | return err 484 | } 485 | -------------------------------------------------------------------------------- /utils_test.go: -------------------------------------------------------------------------------- 1 | // Go MySQL Driver - A MySQL-Driver for Go's database/sql package 2 | // 3 | // Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. 4 | // 5 | // This Source Code Form is subject to the terms of the Mozilla Public 6 | // License, v. 2.0. If a copy of the MPL was not distributed with this file, 7 | // You can obtain one at http://mozilla.org/MPL/2.0/. 8 | 9 | package mysql 10 | 11 | import ( 12 | "bytes" 13 | "database/sql" 14 | "database/sql/driver" 15 | "encoding/binary" 16 | "testing" 17 | "time" 18 | ) 19 | 20 | func TestLengthEncodedInteger(t *testing.T) { 21 | var integerTests = []struct { 22 | num uint64 23 | encoded []byte 24 | }{ 25 | {0x0000000000000000, []byte{0x00}}, 26 | {0x0000000000000012, []byte{0x12}}, 27 | {0x00000000000000fa, []byte{0xfa}}, 28 | {0x0000000000000100, []byte{0xfc, 0x00, 0x01}}, 29 | {0x0000000000001234, []byte{0xfc, 0x34, 0x12}}, 30 | {0x000000000000ffff, []byte{0xfc, 0xff, 0xff}}, 31 | {0x0000000000010000, []byte{0xfd, 0x00, 0x00, 0x01}}, 32 | {0x0000000000123456, []byte{0xfd, 0x56, 0x34, 0x12}}, 33 | {0x0000000000ffffff, []byte{0xfd, 0xff, 0xff, 0xff}}, 34 | {0x0000000001000000, []byte{0xfe, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00}}, 35 | {0x123456789abcdef0, []byte{0xfe, 0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12}}, 36 | {0xffffffffffffffff, []byte{0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}, 37 | } 38 | 39 | for _, tst := range integerTests { 40 | num, isNull, numLen := readLengthEncodedInteger(tst.encoded) 41 | if isNull { 42 | t.Errorf("%x: expected %d, got NULL", tst.encoded, tst.num) 43 | } 44 | if num != tst.num { 45 | t.Errorf("%x: expected %d, got %d", tst.encoded, tst.num, num) 46 | } 47 | if numLen != len(tst.encoded) { 48 | t.Errorf("%x: expected size %d, got %d", tst.encoded, len(tst.encoded), numLen) 49 | } 50 | encoded := appendLengthEncodedInteger(nil, num) 51 | if !bytes.Equal(encoded, tst.encoded) { 52 | t.Errorf("%v: expected %x, got %x", num, tst.encoded, encoded) 53 | } 54 | } 55 | } 56 | 57 | func TestFormatBinaryDateTime(t *testing.T) { 58 | rawDate := [11]byte{} 59 | binary.LittleEndian.PutUint16(rawDate[:2], 1978) // years 60 | rawDate[2] = 12 // months 61 | rawDate[3] = 30 // days 62 | rawDate[4] = 15 // hours 63 | rawDate[5] = 46 // minutes 64 | rawDate[6] = 23 // seconds 65 | binary.LittleEndian.PutUint32(rawDate[7:], 987654) // microseconds 66 | expect := func(expected string, inlen, outlen uint8) { 67 | actual, _ := formatBinaryDateTime(rawDate[:inlen], outlen) 68 | bytes, ok := actual.([]byte) 69 | if !ok { 70 | t.Errorf("formatBinaryDateTime must return []byte, was %T", actual) 71 | } 72 | if string(bytes) != expected { 73 | t.Errorf( 74 | "expected %q, got %q for length in %d, out %d", 75 | expected, actual, inlen, outlen, 76 | ) 77 | } 78 | } 79 | expect("0000-00-00", 0, 10) 80 | expect("0000-00-00 00:00:00", 0, 19) 81 | expect("1978-12-30", 4, 10) 82 | expect("1978-12-30 15:46:23", 7, 19) 83 | expect("1978-12-30 15:46:23.987654", 11, 26) 84 | } 85 | 86 | func TestFormatBinaryTime(t *testing.T) { 87 | expect := func(expected string, src []byte, outlen uint8) { 88 | actual, _ := formatBinaryTime(src, outlen) 89 | bytes, ok := actual.([]byte) 90 | if !ok { 91 | t.Errorf("formatBinaryDateTime must return []byte, was %T", actual) 92 | } 93 | if string(bytes) != expected { 94 | t.Errorf( 95 | "expected %q, got %q for src=%q and outlen=%d", 96 | expected, actual, src, outlen) 97 | } 98 | } 99 | 100 | // binary format: 101 | // sign (0: positive, 1: negative), days(4), hours, minutes, seconds, micro(4) 102 | 103 | // Zeros 104 | expect("00:00:00", []byte{}, 8) 105 | expect("00:00:00.0", []byte{}, 10) 106 | expect("00:00:00.000000", []byte{}, 15) 107 | 108 | // Without micro(4) 109 | expect("12:34:56", []byte{0, 0, 0, 0, 0, 12, 34, 56}, 8) 110 | expect("-12:34:56", []byte{1, 0, 0, 0, 0, 12, 34, 56}, 8) 111 | expect("12:34:56.00", []byte{0, 0, 0, 0, 0, 12, 34, 56}, 11) 112 | expect("24:34:56", []byte{0, 1, 0, 0, 0, 0, 34, 56}, 8) 113 | expect("-99:34:56", []byte{1, 4, 0, 0, 0, 3, 34, 56}, 8) 114 | expect("103079215103:34:56", []byte{0, 255, 255, 255, 255, 23, 34, 56}, 8) 115 | 116 | // With micro(4) 117 | expect("12:34:56.00", []byte{0, 0, 0, 0, 0, 12, 34, 56, 99, 0, 0, 0}, 11) 118 | expect("12:34:56.000099", []byte{0, 0, 0, 0, 0, 12, 34, 56, 99, 0, 0, 0}, 15) 119 | } 120 | 121 | func TestEscapeBackslash(t *testing.T) { 122 | expect := func(expected, value string) { 123 | actual := string(escapeBytesBackslash([]byte{}, []byte(value))) 124 | if actual != expected { 125 | t.Errorf( 126 | "expected %s, got %s", 127 | expected, actual, 128 | ) 129 | } 130 | 131 | actual = string(escapeStringBackslash([]byte{}, value)) 132 | if actual != expected { 133 | t.Errorf( 134 | "expected %s, got %s", 135 | expected, actual, 136 | ) 137 | } 138 | } 139 | 140 | expect("foo\\0bar", "foo\x00bar") 141 | expect("foo\\nbar", "foo\nbar") 142 | expect("foo\\rbar", "foo\rbar") 143 | expect("foo\\Zbar", "foo\x1abar") 144 | expect("foo\\\"bar", "foo\"bar") 145 | expect("foo\\\\bar", "foo\\bar") 146 | expect("foo\\'bar", "foo'bar") 147 | } 148 | 149 | func TestEscapeQuotes(t *testing.T) { 150 | expect := func(expected, value string) { 151 | actual := string(escapeBytesQuotes([]byte{}, []byte(value))) 152 | if actual != expected { 153 | t.Errorf( 154 | "expected %s, got %s", 155 | expected, actual, 156 | ) 157 | } 158 | 159 | actual = string(escapeStringQuotes([]byte{}, value)) 160 | if actual != expected { 161 | t.Errorf( 162 | "expected %s, got %s", 163 | expected, actual, 164 | ) 165 | } 166 | } 167 | 168 | expect("foo\x00bar", "foo\x00bar") // not affected 169 | expect("foo\nbar", "foo\nbar") // not affected 170 | expect("foo\rbar", "foo\rbar") // not affected 171 | expect("foo\x1abar", "foo\x1abar") // not affected 172 | expect("foo''bar", "foo'bar") // affected 173 | expect("foo\"bar", "foo\"bar") // not affected 174 | } 175 | 176 | func TestAtomicError(t *testing.T) { 177 | var ae atomicError 178 | if ae.Value() != nil { 179 | t.Fatal("Expected value to be nil") 180 | } 181 | 182 | ae.Set(ErrMalformPkt) 183 | if v := ae.Value(); v != ErrMalformPkt { 184 | if v == nil { 185 | t.Fatal("Value is still nil") 186 | } 187 | t.Fatal("Error did not match") 188 | } 189 | ae.Set(ErrPktSync) 190 | if ae.Value() == ErrMalformPkt { 191 | t.Fatal("Error still matches old error") 192 | } 193 | if v := ae.Value(); v != ErrPktSync { 194 | t.Fatal("Error did not match") 195 | } 196 | } 197 | 198 | func TestIsolationLevelMapping(t *testing.T) { 199 | data := []struct { 200 | level driver.IsolationLevel 201 | expected string 202 | }{ 203 | { 204 | level: driver.IsolationLevel(sql.LevelReadCommitted), 205 | expected: "READ COMMITTED", 206 | }, 207 | { 208 | level: driver.IsolationLevel(sql.LevelRepeatableRead), 209 | expected: "REPEATABLE READ", 210 | }, 211 | { 212 | level: driver.IsolationLevel(sql.LevelReadUncommitted), 213 | expected: "READ UNCOMMITTED", 214 | }, 215 | { 216 | level: driver.IsolationLevel(sql.LevelSerializable), 217 | expected: "SERIALIZABLE", 218 | }, 219 | } 220 | 221 | for i, td := range data { 222 | if actual, err := mapIsolationLevel(td.level); actual != td.expected || err != nil { 223 | t.Fatal(i, td.expected, actual, err) 224 | } 225 | } 226 | 227 | // check unsupported mapping 228 | expectedErr := "mysql: unsupported isolation level: 7" 229 | actual, err := mapIsolationLevel(driver.IsolationLevel(sql.LevelLinearizable)) 230 | if actual != "" || err == nil { 231 | t.Fatal("Expected error on unsupported isolation level") 232 | } 233 | if err.Error() != expectedErr { 234 | t.Fatalf("Expected error to be %q, got %q", expectedErr, err) 235 | } 236 | } 237 | 238 | func TestAppendDateTime(t *testing.T) { 239 | tests := []struct { 240 | t time.Time 241 | str string 242 | timeTruncate time.Duration 243 | expectedErr bool 244 | }{ 245 | { 246 | t: time.Date(1234, 5, 6, 0, 0, 0, 0, time.UTC), 247 | str: "1234-05-06", 248 | }, 249 | { 250 | t: time.Date(4567, 12, 31, 12, 0, 0, 0, time.UTC), 251 | str: "4567-12-31 12:00:00", 252 | }, 253 | { 254 | t: time.Date(2020, 5, 30, 12, 34, 0, 0, time.UTC), 255 | str: "2020-05-30 12:34:00", 256 | }, 257 | { 258 | t: time.Date(2020, 5, 30, 12, 34, 56, 0, time.UTC), 259 | str: "2020-05-30 12:34:56", 260 | }, 261 | { 262 | t: time.Date(2020, 5, 30, 22, 33, 44, 123000000, time.UTC), 263 | str: "2020-05-30 22:33:44.123", 264 | }, 265 | { 266 | t: time.Date(2020, 5, 30, 22, 33, 44, 123456000, time.UTC), 267 | str: "2020-05-30 22:33:44.123456", 268 | }, 269 | { 270 | t: time.Date(2020, 5, 30, 22, 33, 44, 123456789, time.UTC), 271 | str: "2020-05-30 22:33:44.123456789", 272 | }, 273 | { 274 | t: time.Date(9999, 12, 31, 23, 59, 59, 999999999, time.UTC), 275 | str: "9999-12-31 23:59:59.999999999", 276 | }, 277 | { 278 | t: time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC), 279 | str: "0001-01-01", 280 | }, 281 | // Truncated time 282 | { 283 | t: time.Date(1234, 5, 6, 0, 0, 0, 0, time.UTC), 284 | str: "1234-05-06", 285 | timeTruncate: time.Second, 286 | }, 287 | { 288 | t: time.Date(4567, 12, 31, 12, 0, 0, 0, time.UTC), 289 | str: "4567-12-31 12:00:00", 290 | timeTruncate: time.Minute, 291 | }, 292 | { 293 | t: time.Date(2020, 5, 30, 12, 34, 0, 0, time.UTC), 294 | str: "2020-05-30 12:34:00", 295 | timeTruncate: 0, 296 | }, 297 | { 298 | t: time.Date(2020, 5, 30, 12, 34, 56, 0, time.UTC), 299 | str: "2020-05-30 12:34:56", 300 | timeTruncate: time.Second, 301 | }, 302 | { 303 | t: time.Date(2020, 5, 30, 22, 33, 44, 123000000, time.UTC), 304 | str: "2020-05-30 22:33:44", 305 | timeTruncate: time.Second, 306 | }, 307 | { 308 | t: time.Date(2020, 5, 30, 22, 33, 44, 123456000, time.UTC), 309 | str: "2020-05-30 22:33:44.123", 310 | timeTruncate: time.Millisecond, 311 | }, 312 | { 313 | t: time.Date(2020, 5, 30, 22, 33, 44, 123456789, time.UTC), 314 | str: "2020-05-30 22:33:44", 315 | timeTruncate: time.Second, 316 | }, 317 | { 318 | t: time.Date(9999, 12, 31, 23, 59, 59, 999999999, time.UTC), 319 | str: "9999-12-31 23:59:59.999999999", 320 | timeTruncate: 0, 321 | }, 322 | { 323 | t: time.Date(1, 1, 1, 1, 1, 1, 1, time.UTC), 324 | str: "0001-01-01", 325 | timeTruncate: 365 * 24 * time.Hour, 326 | }, 327 | // year out of range 328 | { 329 | t: time.Date(0, 1, 1, 0, 0, 0, 0, time.UTC), 330 | expectedErr: true, 331 | }, 332 | { 333 | t: time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC), 334 | expectedErr: true, 335 | }, 336 | } 337 | for _, v := range tests { 338 | buf := make([]byte, 0, 32) 339 | buf, err := appendDateTime(buf, v.t, v.timeTruncate) 340 | if err != nil { 341 | if !v.expectedErr { 342 | t.Errorf("appendDateTime(%v) returned an error: %v", v.t, err) 343 | } 344 | continue 345 | } 346 | if str := string(buf); str != v.str { 347 | t.Errorf("appendDateTime(%v), have: %s, want: %s", v.t, str, v.str) 348 | } 349 | } 350 | } 351 | 352 | func TestParseDateTime(t *testing.T) { 353 | cases := []struct { 354 | name string 355 | str string 356 | }{ 357 | { 358 | name: "parse date", 359 | str: "2020-05-13", 360 | }, 361 | { 362 | name: "parse null date", 363 | str: sDate0, 364 | }, 365 | { 366 | name: "parse datetime", 367 | str: "2020-05-13 21:30:45", 368 | }, 369 | { 370 | name: "parse null datetime", 371 | str: sDateTime0, 372 | }, 373 | { 374 | name: "parse datetime nanosec 1-digit", 375 | str: "2020-05-25 23:22:01.1", 376 | }, 377 | { 378 | name: "parse datetime nanosec 2-digits", 379 | str: "2020-05-25 23:22:01.15", 380 | }, 381 | { 382 | name: "parse datetime nanosec 3-digits", 383 | str: "2020-05-25 23:22:01.159", 384 | }, 385 | { 386 | name: "parse datetime nanosec 4-digits", 387 | str: "2020-05-25 23:22:01.1594", 388 | }, 389 | { 390 | name: "parse datetime nanosec 5-digits", 391 | str: "2020-05-25 23:22:01.15949", 392 | }, 393 | { 394 | name: "parse datetime nanosec 6-digits", 395 | str: "2020-05-25 23:22:01.159491", 396 | }, 397 | } 398 | 399 | for _, loc := range []*time.Location{ 400 | time.UTC, 401 | time.FixedZone("test", 8*60*60), 402 | } { 403 | for _, cc := range cases { 404 | t.Run(cc.name+"-"+loc.String(), func(t *testing.T) { 405 | var want time.Time 406 | if cc.str != sDate0 && cc.str != sDateTime0 { 407 | var err error 408 | want, err = time.ParseInLocation(timeFormat[:len(cc.str)], cc.str, loc) 409 | if err != nil { 410 | t.Fatal(err) 411 | } 412 | } 413 | got, err := parseDateTime([]byte(cc.str), loc) 414 | if err != nil { 415 | t.Fatal(err) 416 | } 417 | 418 | if !want.Equal(got) { 419 | t.Fatalf("want: %v, but got %v", want, got) 420 | } 421 | }) 422 | } 423 | } 424 | } 425 | 426 | func TestInvalidDateTime(t *testing.T) { 427 | cases := []struct { 428 | name string 429 | str string 430 | want time.Time 431 | }{ 432 | { 433 | name: "parse datetime without day", 434 | str: "0000-00-00 21:30:45", 435 | want: time.Date(0, 0, 0, 21, 30, 45, 0, time.UTC), 436 | }, 437 | } 438 | 439 | for _, cc := range cases { 440 | t.Run(cc.name, func(t *testing.T) { 441 | got, err := parseDateTime([]byte(cc.str), time.UTC) 442 | if err != nil { 443 | t.Fatal(err) 444 | } 445 | 446 | if !cc.want.Equal(got) { 447 | t.Fatalf("want: %v, but got %v", cc.want, got) 448 | } 449 | }) 450 | } 451 | } 452 | 453 | func TestParseDateTimeFail(t *testing.T) { 454 | cases := []struct { 455 | name string 456 | str string 457 | wantErr string 458 | }{ 459 | { 460 | name: "parse invalid time", 461 | str: "hello", 462 | wantErr: "invalid time bytes: hello", 463 | }, 464 | { 465 | name: "parse year", 466 | str: "000!-00-00 00:00:00.000000", 467 | wantErr: "not [0-9]", 468 | }, 469 | { 470 | name: "parse month", 471 | str: "0000-!0-00 00:00:00.000000", 472 | wantErr: "not [0-9]", 473 | }, 474 | { 475 | name: `parse "-" after parsed year`, 476 | str: "0000:00-00 00:00:00.000000", 477 | wantErr: "bad value for field: `:`", 478 | }, 479 | { 480 | name: `parse "-" after parsed month`, 481 | str: "0000-00:00 00:00:00.000000", 482 | wantErr: "bad value for field: `:`", 483 | }, 484 | { 485 | name: `parse " " after parsed date`, 486 | str: "0000-00-00+00:00:00.000000", 487 | wantErr: "bad value for field: `+`", 488 | }, 489 | { 490 | name: `parse ":" after parsed date`, 491 | str: "0000-00-00 00-00:00.000000", 492 | wantErr: "bad value for field: `-`", 493 | }, 494 | { 495 | name: `parse ":" after parsed hour`, 496 | str: "0000-00-00 00:00-00.000000", 497 | wantErr: "bad value for field: `-`", 498 | }, 499 | { 500 | name: `parse "." after parsed sec`, 501 | str: "0000-00-00 00:00:00?000000", 502 | wantErr: "bad value for field: `?`", 503 | }, 504 | } 505 | 506 | for _, cc := range cases { 507 | t.Run(cc.name, func(t *testing.T) { 508 | got, err := parseDateTime([]byte(cc.str), time.UTC) 509 | if err == nil { 510 | t.Fatal("want error") 511 | } 512 | if cc.wantErr != err.Error() { 513 | t.Fatalf("want `%s`, but got `%s`", cc.wantErr, err) 514 | } 515 | if !got.IsZero() { 516 | t.Fatal("want zero time") 517 | } 518 | }) 519 | } 520 | } 521 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## v1.9.2 (2025-04-07) 4 | 5 | v1.9.2 is a re-release of v1.9.1 due to a release process issue; no changes were made to the content. 6 | 7 | 8 | ## v1.9.1 (2025-03-21) 9 | 10 | ### Major Changes 11 | 12 | * Add Charset() option. (#1679) 13 | 14 | ### Bugfixes 15 | 16 | * go.mod: fix go version format (#1682) 17 | * Fix FormatDSN missing ConnectionAttributes (#1619) 18 | 19 | ## v1.9.0 (2025-02-18) 20 | 21 | ### Major Changes 22 | 23 | - Implement zlib compression. (#1487) 24 | - Supported Go version is updated to Go 1.21+. (#1639) 25 | - Add support for VECTOR type introduced in MySQL 9.0. (#1609) 26 | - Config object can have custom dial function. (#1527) 27 | 28 | ### Bugfixes 29 | 30 | - Fix auth errors when username/password are too long. (#1625) 31 | - Check if MySQL supports CLIENT_CONNECT_ATTRS before sending client attributes. (#1640) 32 | - Fix auth switch request handling. (#1666) 33 | 34 | ### Other changes 35 | 36 | - Add "filename:line" prefix to log in go-mysql. Custom loggers now show it. (#1589) 37 | - Improve error handling. It reduces the "busy buffer" errors. (#1595, #1601, #1641) 38 | - Use `strconv.Atoi` to parse max_allowed_packet. (#1661) 39 | - `rejectReadOnly` option now handles ER_READ_ONLY_MODE (1290) error too. (#1660) 40 | 41 | 42 | ## Version 1.8.1 (2024-03-26) 43 | 44 | Bugfixes: 45 | 46 | - fix race condition when context is canceled in [#1562](https://github.com/go-sql-driver/mysql/pull/1562) and [#1570](https://github.com/go-sql-driver/mysql/pull/1570) 47 | 48 | ## Version 1.8.0 (2024-03-09) 49 | 50 | Major Changes: 51 | 52 | - Use `SET NAMES charset COLLATE collation`. by @methane in [#1437](https://github.com/go-sql-driver/mysql/pull/1437) 53 | - Older go-mysql-driver used `collation_id` in the handshake packet. But it caused collation mismatch in some situation. 54 | - If you don't specify charset nor collation, go-mysql-driver sends `SET NAMES utf8mb4` for new connection. This uses server's default collation for utf8mb4. 55 | - If you specify charset, go-mysql-driver sends `SET NAMES `. This uses the server's default collation for ``. 56 | - If you specify collation and/or charset, go-mysql-driver sends `SET NAMES charset COLLATE collation`. 57 | - PathEscape dbname in DSN. by @methane in [#1432](https://github.com/go-sql-driver/mysql/pull/1432) 58 | - This is backward incompatible in rare case. Check your DSN. 59 | - Drop Go 1.13-17 support by @methane in [#1420](https://github.com/go-sql-driver/mysql/pull/1420) 60 | - Use Go 1.18+ 61 | - Parse numbers on text protocol too by @methane in [#1452](https://github.com/go-sql-driver/mysql/pull/1452) 62 | - When text protocol is used, go-mysql-driver passed bare `[]byte` to database/sql for avoid unnecessary allocation and conversion. 63 | - If user specified `*any` to `Scan()`, database/sql passed the `[]byte` into the target variable. 64 | - This confused users because most user doesn't know when text/binary protocol used. 65 | - go-mysql-driver 1.8 converts integer/float values into int64/double even in text protocol. This doesn't increase allocation compared to `[]byte` and conversion cost is negatable. 66 | - New options start using the Functional Option Pattern to avoid increasing technical debt in the Config object. Future version may introduce Functional Option for existing options, but not for now. 67 | - Make TimeTruncate functional option by @methane in [1552](https://github.com/go-sql-driver/mysql/pull/1552) 68 | - Add BeforeConnect callback to configuration object by @ItalyPaleAle in [#1469](https://github.com/go-sql-driver/mysql/pull/1469) 69 | 70 | 71 | Other changes: 72 | 73 | - Adding DeregisterDialContext to prevent memory leaks with dialers we don't need anymore by @jypelle in https://github.com/go-sql-driver/mysql/pull/1422 74 | - Make logger configurable per connection by @frozenbonito in https://github.com/go-sql-driver/mysql/pull/1408 75 | - Fix ColumnType.DatabaseTypeName for mediumint unsigned by @evanelias in https://github.com/go-sql-driver/mysql/pull/1428 76 | - Add connection attributes by @Daemonxiao in https://github.com/go-sql-driver/mysql/pull/1389 77 | - Stop `ColumnTypeScanType()` from returning `sql.RawBytes` by @methane in https://github.com/go-sql-driver/mysql/pull/1424 78 | - Exec() now provides access to status of multiple statements. by @mherr-google in https://github.com/go-sql-driver/mysql/pull/1309 79 | - Allow to change (or disable) the default driver name for registration by @dolmen in https://github.com/go-sql-driver/mysql/pull/1499 80 | - Add default connection attribute '_server_host' by @oblitorum in https://github.com/go-sql-driver/mysql/pull/1506 81 | - QueryUnescape DSN ConnectionAttribute value by @zhangyangyu in https://github.com/go-sql-driver/mysql/pull/1470 82 | - Add client_ed25519 authentication by @Gusted in https://github.com/go-sql-driver/mysql/pull/1518 83 | 84 | ## Version 1.7.1 (2023-04-25) 85 | 86 | Changes: 87 | 88 | - bump actions/checkout@v3 and actions/setup-go@v3 (#1375) 89 | - Add go1.20 and mariadb10.11 to the testing matrix (#1403) 90 | - Increase default maxAllowedPacket size. (#1411) 91 | 92 | Bugfixes: 93 | 94 | - Use SET syntax as specified in the MySQL documentation (#1402) 95 | 96 | 97 | ## Version 1.7 (2022-11-29) 98 | 99 | Changes: 100 | 101 | - Drop support of Go 1.12 (#1211) 102 | - Refactoring `(*textRows).readRow` in a more clear way (#1230) 103 | - util: Reduce boundary check in escape functions. (#1316) 104 | - enhancement for mysqlConn handleAuthResult (#1250) 105 | 106 | New Features: 107 | 108 | - support Is comparison on MySQLError (#1210) 109 | - return unsigned in database type name when necessary (#1238) 110 | - Add API to express like a --ssl-mode=PREFERRED MySQL client (#1370) 111 | - Add SQLState to MySQLError (#1321) 112 | 113 | Bugfixes: 114 | 115 | - Fix parsing 0 year. (#1257) 116 | 117 | 118 | ## Version 1.6 (2021-04-01) 119 | 120 | Changes: 121 | 122 | - Migrate the CI service from travis-ci to GitHub Actions (#1176, #1183, #1190) 123 | - `NullTime` is deprecated (#960, #1144) 124 | - Reduce allocations when building SET command (#1111) 125 | - Performance improvement for time formatting (#1118) 126 | - Performance improvement for time parsing (#1098, #1113) 127 | 128 | New Features: 129 | 130 | - Implement `driver.Validator` interface (#1106, #1174) 131 | - Support returning `uint64` from `Valuer` in `ConvertValue` (#1143) 132 | - Add `json.RawMessage` for converter and prepared statement (#1059) 133 | - Interpolate `json.RawMessage` as `string` (#1058) 134 | - Implements `CheckNamedValue` (#1090) 135 | 136 | Bugfixes: 137 | 138 | - Stop rounding times (#1121, #1172) 139 | - Put zero filler into the SSL handshake packet (#1066) 140 | - Fix checking cancelled connections back into the connection pool (#1095) 141 | - Fix remove last 0 byte for mysql_old_password when password is empty (#1133) 142 | 143 | 144 | ## Version 1.5 (2020-01-07) 145 | 146 | Changes: 147 | 148 | - Dropped support Go 1.9 and lower (#823, #829, #886, #1016, #1017) 149 | - Improve buffer handling (#890) 150 | - Document potentially insecure TLS configs (#901) 151 | - Use a double-buffering scheme to prevent data races (#943) 152 | - Pass uint64 values without converting them to string (#838, #955) 153 | - Update collations and make utf8mb4 default (#877, #1054) 154 | - Make NullTime compatible with sql.NullTime in Go 1.13+ (#995) 155 | - Removed CloudSQL support (#993, #1007) 156 | - Add Go Module support (#1003) 157 | 158 | New Features: 159 | 160 | - Implement support of optional TLS (#900) 161 | - Check connection liveness (#934, #964, #997, #1048, #1051, #1052) 162 | - Implement Connector Interface (#941, #958, #1020, #1035) 163 | 164 | Bugfixes: 165 | 166 | - Mark connections as bad on error during ping (#875) 167 | - Mark connections as bad on error during dial (#867) 168 | - Fix connection leak caused by rapid context cancellation (#1024) 169 | - Mark connections as bad on error during Conn.Prepare (#1030) 170 | 171 | 172 | ## Version 1.4.1 (2018-11-14) 173 | 174 | Bugfixes: 175 | 176 | - Fix TIME format for binary columns (#818) 177 | - Fix handling of empty auth plugin names (#835) 178 | - Fix caching_sha2_password with empty password (#826) 179 | - Fix canceled context broke mysqlConn (#862) 180 | - Fix OldAuthSwitchRequest support (#870) 181 | - Fix Auth Response packet for cleartext password (#887) 182 | 183 | ## Version 1.4 (2018-06-03) 184 | 185 | Changes: 186 | 187 | - Documentation fixes (#530, #535, #567) 188 | - Refactoring (#575, #579, #580, #581, #603, #615, #704) 189 | - Cache column names (#444) 190 | - Sort the DSN parameters in DSNs generated from a config (#637) 191 | - Allow native password authentication by default (#644) 192 | - Use the default port if it is missing in the DSN (#668) 193 | - Removed the `strict` mode (#676) 194 | - Do not query `max_allowed_packet` by default (#680) 195 | - Dropped support Go 1.6 and lower (#696) 196 | - Updated `ConvertValue()` to match the database/sql/driver implementation (#760) 197 | - Document the usage of `0000-00-00T00:00:00` as the time.Time zero value (#783) 198 | - Improved the compatibility of the authentication system (#807) 199 | 200 | New Features: 201 | 202 | - Multi-Results support (#537) 203 | - `rejectReadOnly` DSN option (#604) 204 | - `context.Context` support (#608, #612, #627, #761) 205 | - Transaction isolation level support (#619, #744) 206 | - Read-Only transactions support (#618, #634) 207 | - `NewConfig` function which initializes a config with default values (#679) 208 | - Implemented the `ColumnType` interfaces (#667, #724) 209 | - Support for custom string types in `ConvertValue` (#623) 210 | - Implemented `NamedValueChecker`, improving support for uint64 with high bit set (#690, #709, #710) 211 | - `caching_sha2_password` authentication plugin support (#794, #800, #801, #802) 212 | - Implemented `driver.SessionResetter` (#779) 213 | - `sha256_password` authentication plugin support (#808) 214 | 215 | Bugfixes: 216 | 217 | - Use the DSN hostname as TLS default ServerName if `tls=true` (#564, #718) 218 | - Fixed LOAD LOCAL DATA INFILE for empty files (#590) 219 | - Removed columns definition cache since it sometimes cached invalid data (#592) 220 | - Don't mutate registered TLS configs (#600) 221 | - Make RegisterTLSConfig concurrency-safe (#613) 222 | - Handle missing auth data in the handshake packet correctly (#646) 223 | - Do not retry queries when data was written to avoid data corruption (#302, #736) 224 | - Cache the connection pointer for error handling before invalidating it (#678) 225 | - Fixed imports for appengine/cloudsql (#700) 226 | - Fix sending STMT_LONG_DATA for 0 byte data (#734) 227 | - Set correct capacity for []bytes read from length-encoded strings (#766) 228 | - Make RegisterDial concurrency-safe (#773) 229 | 230 | 231 | ## Version 1.3 (2016-12-01) 232 | 233 | Changes: 234 | 235 | - Go 1.1 is no longer supported 236 | - Use decimals fields in MySQL to format time types (#249) 237 | - Buffer optimizations (#269) 238 | - TLS ServerName defaults to the host (#283) 239 | - Refactoring (#400, #410, #437) 240 | - Adjusted documentation for second generation CloudSQL (#485) 241 | - Documented DSN system var quoting rules (#502) 242 | - Made statement.Close() calls idempotent to avoid errors in Go 1.6+ (#512) 243 | 244 | New Features: 245 | 246 | - Enable microsecond resolution on TIME, DATETIME and TIMESTAMP (#249) 247 | - Support for returning table alias on Columns() (#289, #359, #382) 248 | - Placeholder interpolation, can be activated with the DSN parameter `interpolateParams=true` (#309, #318, #490) 249 | - Support for uint64 parameters with high bit set (#332, #345) 250 | - Cleartext authentication plugin support (#327) 251 | - Exported ParseDSN function and the Config struct (#403, #419, #429) 252 | - Read / Write timeouts (#401) 253 | - Support for JSON field type (#414) 254 | - Support for multi-statements and multi-results (#411, #431) 255 | - DSN parameter to set the driver-side max_allowed_packet value manually (#489) 256 | - Native password authentication plugin support (#494, #524) 257 | 258 | Bugfixes: 259 | 260 | - Fixed handling of queries without columns and rows (#255) 261 | - Fixed a panic when SetKeepAlive() failed (#298) 262 | - Handle ERR packets while reading rows (#321) 263 | - Fixed reading NULL length-encoded integers in MySQL 5.6+ (#349) 264 | - Fixed absolute paths support in LOAD LOCAL DATA INFILE (#356) 265 | - Actually zero out bytes in handshake response (#378) 266 | - Fixed race condition in registering LOAD DATA INFILE handler (#383) 267 | - Fixed tests with MySQL 5.7.9+ (#380) 268 | - QueryUnescape TLS config names (#397) 269 | - Fixed "broken pipe" error by writing to closed socket (#390) 270 | - Fixed LOAD LOCAL DATA INFILE buffering (#424) 271 | - Fixed parsing of floats into float64 when placeholders are used (#434) 272 | - Fixed DSN tests with Go 1.7+ (#459) 273 | - Handle ERR packets while waiting for EOF (#473) 274 | - Invalidate connection on error while discarding additional results (#513) 275 | - Allow terminating packets of length 0 (#516) 276 | 277 | 278 | ## Version 1.2 (2014-06-03) 279 | 280 | Changes: 281 | 282 | - We switched back to a "rolling release". `go get` installs the current master branch again 283 | - Version v1 of the driver will not be maintained anymore. Go 1.0 is no longer supported by this driver 284 | - Exported errors to allow easy checking from application code 285 | - Enabled TCP Keepalives on TCP connections 286 | - Optimized INFILE handling (better buffer size calculation, lazy init, ...) 287 | - The DSN parser also checks for a missing separating slash 288 | - Faster binary date / datetime to string formatting 289 | - Also exported the MySQLWarning type 290 | - mysqlConn.Close returns the first error encountered instead of ignoring all errors 291 | - writePacket() automatically writes the packet size to the header 292 | - readPacket() uses an iterative approach instead of the recursive approach to merge split packets 293 | 294 | New Features: 295 | 296 | - `RegisterDial` allows the usage of a custom dial function to establish the network connection 297 | - Setting the connection collation is possible with the `collation` DSN parameter. This parameter should be preferred over the `charset` parameter 298 | - Logging of critical errors is configurable with `SetLogger` 299 | - Google CloudSQL support 300 | 301 | Bugfixes: 302 | 303 | - Allow more than 32 parameters in prepared statements 304 | - Various old_password fixes 305 | - Fixed TestConcurrent test to pass Go's race detection 306 | - Fixed appendLengthEncodedInteger for large numbers 307 | - Renamed readLengthEnodedString to readLengthEncodedString and skipLengthEnodedString to skipLengthEncodedString (fixed typo) 308 | 309 | 310 | ## Version 1.1 (2013-11-02) 311 | 312 | Changes: 313 | 314 | - Go-MySQL-Driver now requires Go 1.1 315 | - Connections now use the collation `utf8_general_ci` by default. Adding `&charset=UTF8` to the DSN should not be necessary anymore 316 | - Made closing rows and connections error tolerant. This allows for example deferring rows.Close() without checking for errors 317 | - `[]byte(nil)` is now treated as a NULL value. Before, it was treated like an empty string / `[]byte("")` 318 | - DSN parameter values must now be url.QueryEscape'ed. This allows text values to contain special characters, such as '&'. 319 | - Use the IO buffer also for writing. This results in zero allocations (by the driver) for most queries 320 | - Optimized the buffer for reading 321 | - stmt.Query now caches column metadata 322 | - New Logo 323 | - Changed the copyright header to include all contributors 324 | - Improved the LOAD INFILE documentation 325 | - The driver struct is now exported to make the driver directly accessible 326 | - Refactored the driver tests 327 | - Added more benchmarks and moved all to a separate file 328 | - Other small refactoring 329 | 330 | New Features: 331 | 332 | - Added *old_passwords* support: Required in some cases, but must be enabled by adding `allowOldPasswords=true` to the DSN since it is insecure 333 | - Added a `clientFoundRows` parameter: Return the number of matching rows instead of the number of rows changed on UPDATEs 334 | - Added TLS/SSL support: Use a TLS/SSL encrypted connection to the server. Custom TLS configs can be registered and used 335 | 336 | Bugfixes: 337 | 338 | - Fixed MySQL 4.1 support: MySQL 4.1 sends packets with lengths which differ from the specification 339 | - Convert to DB timezone when inserting `time.Time` 340 | - Split packets (more than 16MB) are now merged correctly 341 | - Fixed false positive `io.EOF` errors when the data was fully read 342 | - Avoid panics on reuse of closed connections 343 | - Fixed empty string producing false nil values 344 | - Fixed sign byte for positive TIME fields 345 | 346 | 347 | ## Version 1.0 (2013-05-14) 348 | 349 | Initial Release 350 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /dsn_test.go: -------------------------------------------------------------------------------- 1 | // Go MySQL Driver - A MySQL-Driver for Go's database/sql package 2 | // 3 | // Copyright 2016 The Go-MySQL-Driver Authors. All rights reserved. 4 | // 5 | // This Source Code Form is subject to the terms of the Mozilla Public 6 | // License, v. 2.0. If a copy of the MPL was not distributed with this file, 7 | // You can obtain one at http://mozilla.org/MPL/2.0/. 8 | 9 | package mysql 10 | 11 | import ( 12 | "crypto/tls" 13 | "fmt" 14 | "net/url" 15 | "reflect" 16 | "testing" 17 | "time" 18 | ) 19 | 20 | var testDSNs = []struct { 21 | in string 22 | out *Config 23 | }{{ 24 | "username:password@protocol(address)/dbname?param=value", 25 | &Config{User: "username", Passwd: "password", Net: "protocol", Addr: "address", DBName: "dbname", Params: map[string]string{"param": "value"}, Loc: time.UTC, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true}, 26 | }, { 27 | "username:password@protocol(address)/dbname?param=value&columnsWithAlias=true", 28 | &Config{User: "username", Passwd: "password", Net: "protocol", Addr: "address", DBName: "dbname", Params: map[string]string{"param": "value"}, Loc: time.UTC, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true, ColumnsWithAlias: true}, 29 | }, { 30 | "username:password@protocol(address)/dbname?param=value&columnsWithAlias=true&multiStatements=true", 31 | &Config{User: "username", Passwd: "password", Net: "protocol", Addr: "address", DBName: "dbname", Params: map[string]string{"param": "value"}, Loc: time.UTC, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true, ColumnsWithAlias: true, MultiStatements: true}, 32 | }, { 33 | "user@unix(/path/to/socket)/dbname?charset=utf8", 34 | &Config{User: "user", Net: "unix", Addr: "/path/to/socket", DBName: "dbname", charsets: []string{"utf8"}, Loc: time.UTC, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true}, 35 | }, { 36 | "user:password@tcp(localhost:5555)/dbname?charset=utf8&tls=true", 37 | &Config{User: "user", Passwd: "password", Net: "tcp", Addr: "localhost:5555", DBName: "dbname", charsets: []string{"utf8"}, Loc: time.UTC, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true, TLSConfig: "true"}, 38 | }, { 39 | "user:password@tcp(localhost:5555)/dbname?charset=utf8mb4,utf8&tls=skip-verify", 40 | &Config{User: "user", Passwd: "password", Net: "tcp", Addr: "localhost:5555", DBName: "dbname", charsets: []string{"utf8mb4", "utf8"}, Loc: time.UTC, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true, TLSConfig: "skip-verify"}, 41 | }, { 42 | "user:password@/dbname?loc=UTC&timeout=30s&readTimeout=1s&writeTimeout=1s&allowAllFiles=1&clientFoundRows=true&allowOldPasswords=TRUE&collation=utf8mb4_unicode_ci&maxAllowedPacket=16777216&tls=false&allowCleartextPasswords=true&parseTime=true&rejectReadOnly=true", 43 | &Config{User: "user", Passwd: "password", Net: "tcp", Addr: "127.0.0.1:3306", DBName: "dbname", Collation: "utf8mb4_unicode_ci", Loc: time.UTC, TLSConfig: "false", AllowCleartextPasswords: true, AllowNativePasswords: true, Timeout: 30 * time.Second, ReadTimeout: time.Second, WriteTimeout: time.Second, Logger: defaultLogger, AllowAllFiles: true, AllowOldPasswords: true, CheckConnLiveness: true, ClientFoundRows: true, MaxAllowedPacket: 16777216, ParseTime: true, RejectReadOnly: true}, 44 | }, { 45 | "user:password@/dbname?allowNativePasswords=false&checkConnLiveness=false&maxAllowedPacket=0&allowFallbackToPlaintext=true", 46 | &Config{User: "user", Passwd: "password", Net: "tcp", Addr: "127.0.0.1:3306", DBName: "dbname", Loc: time.UTC, MaxAllowedPacket: 0, Logger: defaultLogger, AllowFallbackToPlaintext: true, AllowNativePasswords: false, CheckConnLiveness: false}, 47 | }, { 48 | "user:p@ss(word)@tcp([de:ad:be:ef::ca:fe]:80)/dbname?loc=Local", 49 | &Config{User: "user", Passwd: "p@ss(word)", Net: "tcp", Addr: "[de:ad:be:ef::ca:fe]:80", DBName: "dbname", Loc: time.Local, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true}, 50 | }, { 51 | "/dbname", 52 | &Config{Net: "tcp", Addr: "127.0.0.1:3306", DBName: "dbname", Loc: time.UTC, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true}, 53 | }, { 54 | "/dbname%2Fwithslash", 55 | &Config{Net: "tcp", Addr: "127.0.0.1:3306", DBName: "dbname/withslash", Loc: time.UTC, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true}, 56 | }, { 57 | "@/", 58 | &Config{Net: "tcp", Addr: "127.0.0.1:3306", Loc: time.UTC, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true}, 59 | }, { 60 | "/", 61 | &Config{Net: "tcp", Addr: "127.0.0.1:3306", Loc: time.UTC, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true}, 62 | }, { 63 | "", 64 | &Config{Net: "tcp", Addr: "127.0.0.1:3306", Loc: time.UTC, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true}, 65 | }, { 66 | "user:p@/ssword@/", 67 | &Config{User: "user", Passwd: "p@/ssword", Net: "tcp", Addr: "127.0.0.1:3306", Loc: time.UTC, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true}, 68 | }, { 69 | "unix/?arg=%2Fsome%2Fpath.ext", 70 | &Config{Net: "unix", Addr: "/tmp/mysql.sock", Params: map[string]string{"arg": "/some/path.ext"}, Loc: time.UTC, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true}, 71 | }, { 72 | "tcp(127.0.0.1)/dbname", 73 | &Config{Net: "tcp", Addr: "127.0.0.1:3306", DBName: "dbname", Loc: time.UTC, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true}, 74 | }, { 75 | "tcp(de:ad:be:ef::ca:fe)/dbname", 76 | &Config{Net: "tcp", Addr: "[de:ad:be:ef::ca:fe]:3306", DBName: "dbname", Loc: time.UTC, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true}, 77 | }, { 78 | "user:password@/dbname?loc=UTC&timeout=30s&parseTime=true&timeTruncate=1h", 79 | &Config{User: "user", Passwd: "password", Net: "tcp", Addr: "127.0.0.1:3306", DBName: "dbname", Loc: time.UTC, Timeout: 30 * time.Second, ParseTime: true, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true, timeTruncate: time.Hour}, 80 | }, { 81 | "foo:bar@tcp(192.168.1.50:3307)/baz?timeout=10s&connectionAttributes=program_name:MySQLGoDriver%2FTest,program_version:1.2.3", 82 | &Config{User: "foo", Passwd: "bar", Net: "tcp", Addr: "192.168.1.50:3307", DBName: "baz", Loc: time.UTC, Timeout: 10 * time.Second, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true, ConnectionAttributes: "program_name:MySQLGoDriver/Test,program_version:1.2.3"}, 83 | }, 84 | } 85 | 86 | func TestDSNParser(t *testing.T) { 87 | for i, tst := range testDSNs { 88 | t.Run(tst.in, func(t *testing.T) { 89 | cfg, err := ParseDSN(tst.in) 90 | if err != nil { 91 | t.Error(err.Error()) 92 | return 93 | } 94 | 95 | // pointer not static 96 | cfg.TLS = nil 97 | 98 | if !reflect.DeepEqual(cfg, tst.out) { 99 | t.Errorf("%d. ParseDSN(%q) mismatch:\ngot %+v\nwant %+v", i, tst.in, cfg, tst.out) 100 | } 101 | }) 102 | } 103 | } 104 | 105 | func TestDSNParserInvalid(t *testing.T) { 106 | var invalidDSNs = []string{ 107 | "@net(addr/", // no closing brace 108 | "@tcp(/", // no closing brace 109 | "tcp(/", // no closing brace 110 | "(/", // no closing brace 111 | "net(addr)//", // unescaped 112 | "User:pass@tcp(1.2.3.4:3306)", // no trailing slash 113 | "net()/", // unknown default addr 114 | "user:pass@tcp(127.0.0.1:3306)/db/name", // invalid dbname 115 | "user:password@/dbname?allowFallbackToPlaintext=PREFERRED", // wrong bool flag 116 | "user:password@/dbname?connectionAttributes=attr1:/unescaped/value", // unescaped 117 | //"/dbname?arg=/some/unescaped/path", 118 | } 119 | 120 | for i, tst := range invalidDSNs { 121 | if _, err := ParseDSN(tst); err == nil { 122 | t.Errorf("invalid DSN #%d. (%s) didn't error!", i, tst) 123 | } 124 | } 125 | } 126 | 127 | func TestDSNReformat(t *testing.T) { 128 | for i, tst := range testDSNs { 129 | t.Run(tst.in, func(t *testing.T) { 130 | dsn1 := tst.in 131 | cfg1, err := ParseDSN(dsn1) 132 | if err != nil { 133 | t.Error(err.Error()) 134 | return 135 | } 136 | cfg1.TLS = nil // pointer not static 137 | res1 := fmt.Sprintf("%+v", cfg1) 138 | 139 | dsn2 := cfg1.FormatDSN() 140 | if dsn2 != dsn1 { 141 | // Just log 142 | t.Logf("%d. %q reformatted as %q", i, dsn1, dsn2) 143 | } 144 | 145 | cfg2, err := ParseDSN(dsn2) 146 | if err != nil { 147 | t.Error(err.Error()) 148 | return 149 | } 150 | cfg2.TLS = nil // pointer not static 151 | res2 := fmt.Sprintf("%+v", cfg2) 152 | 153 | if res1 != res2 { 154 | t.Errorf("%d. %q does not match %q", i, res2, res1) 155 | } 156 | 157 | dsn3 := cfg2.FormatDSN() 158 | if dsn3 != dsn2 { 159 | t.Errorf("%d. %q does not match %q", i, dsn2, dsn3) 160 | } 161 | }) 162 | } 163 | } 164 | 165 | func TestDSNServerPubKey(t *testing.T) { 166 | baseDSN := "User:password@tcp(localhost:5555)/dbname?serverPubKey=" 167 | 168 | RegisterServerPubKey("testKey", testPubKeyRSA) 169 | defer DeregisterServerPubKey("testKey") 170 | 171 | tst := baseDSN + "testKey" 172 | cfg, err := ParseDSN(tst) 173 | if err != nil { 174 | t.Error(err.Error()) 175 | } 176 | 177 | if cfg.ServerPubKey != "testKey" { 178 | t.Errorf("unexpected cfg.ServerPubKey value: %v", cfg.ServerPubKey) 179 | } 180 | if cfg.pubKey != testPubKeyRSA { 181 | t.Error("pub key pointer doesn't match") 182 | } 183 | 184 | // Key is missing 185 | tst = baseDSN + "invalid_name" 186 | cfg, err = ParseDSN(tst) 187 | if err == nil { 188 | t.Errorf("invalid name in DSN (%s) but did not error. Got config: %#v", tst, cfg) 189 | } 190 | } 191 | 192 | func TestDSNServerPubKeyQueryEscape(t *testing.T) { 193 | const name = "&%!:" 194 | dsn := "User:password@tcp(localhost:5555)/dbname?serverPubKey=" + url.QueryEscape(name) 195 | 196 | RegisterServerPubKey(name, testPubKeyRSA) 197 | defer DeregisterServerPubKey(name) 198 | 199 | cfg, err := ParseDSN(dsn) 200 | if err != nil { 201 | t.Error(err.Error()) 202 | } 203 | 204 | if cfg.pubKey != testPubKeyRSA { 205 | t.Error("pub key pointer doesn't match") 206 | } 207 | } 208 | 209 | func TestDSNWithCustomTLS(t *testing.T) { 210 | baseDSN := "User:password@tcp(localhost:5555)/dbname?tls=" 211 | tlsCfg := tls.Config{} 212 | 213 | RegisterTLSConfig("utils_test", &tlsCfg) 214 | defer DeregisterTLSConfig("utils_test") 215 | 216 | // Custom TLS is missing 217 | tst := baseDSN + "invalid_tls" 218 | cfg, err := ParseDSN(tst) 219 | if err == nil { 220 | t.Errorf("invalid custom TLS in DSN (%s) but did not error. Got config: %#v", tst, cfg) 221 | } 222 | 223 | tst = baseDSN + "utils_test" 224 | 225 | // Custom TLS with a server name 226 | name := "foohost" 227 | tlsCfg.ServerName = name 228 | cfg, err = ParseDSN(tst) 229 | 230 | if err != nil { 231 | t.Error(err.Error()) 232 | } else if cfg.TLS.ServerName != name { 233 | t.Errorf("did not get the correct TLS ServerName (%s) parsing DSN (%s).", name, tst) 234 | } 235 | 236 | // Custom TLS without a server name 237 | name = "localhost" 238 | tlsCfg.ServerName = "" 239 | cfg, err = ParseDSN(tst) 240 | 241 | if err != nil { 242 | t.Error(err.Error()) 243 | } else if cfg.TLS.ServerName != name { 244 | t.Errorf("did not get the correct ServerName (%s) parsing DSN (%s).", name, tst) 245 | } else if tlsCfg.ServerName != "" { 246 | t.Errorf("tlsCfg was mutated ServerName (%s) should be empty parsing DSN (%s).", name, tst) 247 | } 248 | } 249 | 250 | func TestDSNTLSConfig(t *testing.T) { 251 | expectedServerName := "example.com" 252 | dsn := "tcp(example.com:1234)/?tls=true" 253 | 254 | cfg, err := ParseDSN(dsn) 255 | if err != nil { 256 | t.Error(err.Error()) 257 | } 258 | if cfg.TLS == nil { 259 | t.Error("cfg.tls should not be nil") 260 | } 261 | if cfg.TLS.ServerName != expectedServerName { 262 | t.Errorf("cfg.tls.ServerName should be %q, got %q (host with port)", expectedServerName, cfg.TLS.ServerName) 263 | } 264 | 265 | dsn = "tcp(example.com)/?tls=true" 266 | cfg, err = ParseDSN(dsn) 267 | if err != nil { 268 | t.Error(err.Error()) 269 | } 270 | if cfg.TLS == nil { 271 | t.Error("cfg.tls should not be nil") 272 | } 273 | if cfg.TLS.ServerName != expectedServerName { 274 | t.Errorf("cfg.tls.ServerName should be %q, got %q (host without port)", expectedServerName, cfg.TLS.ServerName) 275 | } 276 | } 277 | 278 | func TestDSNWithCustomTLSQueryEscape(t *testing.T) { 279 | const configKey = "&%!:" 280 | dsn := "User:password@tcp(localhost:5555)/dbname?tls=" + url.QueryEscape(configKey) 281 | name := "foohost" 282 | tlsCfg := tls.Config{ServerName: name} 283 | 284 | RegisterTLSConfig(configKey, &tlsCfg) 285 | defer DeregisterTLSConfig(configKey) 286 | 287 | cfg, err := ParseDSN(dsn) 288 | 289 | if err != nil { 290 | t.Error(err.Error()) 291 | } else if cfg.TLS.ServerName != name { 292 | t.Errorf("did not get the correct TLS ServerName (%s) parsing DSN (%s).", name, dsn) 293 | } 294 | } 295 | 296 | func TestDSNUnsafeCollation(t *testing.T) { 297 | _, err := ParseDSN("/dbname?collation=gbk_chinese_ci&interpolateParams=true") 298 | if err != errInvalidDSNUnsafeCollation { 299 | t.Errorf("expected %v, got %v", errInvalidDSNUnsafeCollation, err) 300 | } 301 | 302 | _, err = ParseDSN("/dbname?collation=gbk_chinese_ci&interpolateParams=false") 303 | if err != nil { 304 | t.Errorf("expected %v, got %v", nil, err) 305 | } 306 | 307 | _, err = ParseDSN("/dbname?collation=gbk_chinese_ci") 308 | if err != nil { 309 | t.Errorf("expected %v, got %v", nil, err) 310 | } 311 | 312 | _, err = ParseDSN("/dbname?collation=ascii_bin&interpolateParams=true") 313 | if err != nil { 314 | t.Errorf("expected %v, got %v", nil, err) 315 | } 316 | 317 | _, err = ParseDSN("/dbname?collation=latin1_german1_ci&interpolateParams=true") 318 | if err != nil { 319 | t.Errorf("expected %v, got %v", nil, err) 320 | } 321 | 322 | _, err = ParseDSN("/dbname?collation=utf8_general_ci&interpolateParams=true") 323 | if err != nil { 324 | t.Errorf("expected %v, got %v", nil, err) 325 | } 326 | 327 | _, err = ParseDSN("/dbname?collation=utf8mb4_general_ci&interpolateParams=true") 328 | if err != nil { 329 | t.Errorf("expected %v, got %v", nil, err) 330 | } 331 | } 332 | 333 | func TestParamsAreSorted(t *testing.T) { 334 | expected := "/dbname?interpolateParams=true&foobar=baz&quux=loo" 335 | cfg := NewConfig() 336 | cfg.DBName = "dbname" 337 | cfg.InterpolateParams = true 338 | cfg.Params = map[string]string{ 339 | "quux": "loo", 340 | "foobar": "baz", 341 | } 342 | actual := cfg.FormatDSN() 343 | if actual != expected { 344 | t.Errorf("generic Config.Params were not sorted: want %#v, got %#v", expected, actual) 345 | } 346 | } 347 | 348 | func TestCloneConfig(t *testing.T) { 349 | RegisterServerPubKey("testKey", testPubKeyRSA) 350 | defer DeregisterServerPubKey("testKey") 351 | 352 | expectedServerName := "example.com" 353 | dsn := "tcp(example.com:1234)/?tls=true&foobar=baz&serverPubKey=testKey" 354 | cfg, err := ParseDSN(dsn) 355 | if err != nil { 356 | t.Fatal(err.Error()) 357 | } 358 | 359 | cfg2 := cfg.Clone() 360 | if cfg == cfg2 { 361 | t.Errorf("Config.Clone did not create a separate config struct") 362 | } 363 | 364 | if cfg2.TLS.ServerName != expectedServerName { 365 | t.Errorf("cfg.tls.ServerName should be %q, got %q (host with port)", expectedServerName, cfg.TLS.ServerName) 366 | } 367 | 368 | cfg2.TLS.ServerName = "example2.com" 369 | if cfg.TLS.ServerName == cfg2.TLS.ServerName { 370 | t.Errorf("changed cfg.tls.Server name should not propagate to original Config") 371 | } 372 | 373 | if _, ok := cfg2.Params["foobar"]; !ok { 374 | t.Errorf("cloned Config is missing custom params") 375 | } 376 | 377 | delete(cfg2.Params, "foobar") 378 | 379 | if _, ok := cfg.Params["foobar"]; !ok { 380 | t.Errorf("custom params in cloned Config should not propagate to original Config") 381 | } 382 | 383 | if !reflect.DeepEqual(cfg.pubKey, cfg2.pubKey) { 384 | t.Errorf("public key in Config should be identical") 385 | } 386 | } 387 | 388 | func TestNormalizeTLSConfig(t *testing.T) { 389 | tt := []struct { 390 | tlsConfig string 391 | want *tls.Config 392 | }{ 393 | {"", nil}, 394 | {"false", nil}, 395 | {"true", &tls.Config{ServerName: "myserver"}}, 396 | {"skip-verify", &tls.Config{InsecureSkipVerify: true}}, 397 | {"preferred", &tls.Config{InsecureSkipVerify: true}}, 398 | {"test_tls_config", &tls.Config{ServerName: "myServerName"}}, 399 | } 400 | 401 | RegisterTLSConfig("test_tls_config", &tls.Config{ServerName: "myServerName"}) 402 | defer func() { DeregisterTLSConfig("test_tls_config") }() 403 | 404 | for _, tc := range tt { 405 | t.Run(tc.tlsConfig, func(t *testing.T) { 406 | cfg := &Config{ 407 | Addr: "myserver:3306", 408 | TLSConfig: tc.tlsConfig, 409 | } 410 | 411 | cfg.normalize() 412 | 413 | if cfg.TLS == nil { 414 | if tc.want != nil { 415 | t.Fatal("wanted a tls config but got nil instead") 416 | } 417 | return 418 | } 419 | 420 | if cfg.TLS.ServerName != tc.want.ServerName { 421 | t.Errorf("tls.ServerName doesn't match (want: '%s', got: '%s')", 422 | tc.want.ServerName, cfg.TLS.ServerName) 423 | } 424 | if cfg.TLS.InsecureSkipVerify != tc.want.InsecureSkipVerify { 425 | t.Errorf("tls.InsecureSkipVerify doesn't match (want: %T, got :%T)", 426 | tc.want.InsecureSkipVerify, cfg.TLS.InsecureSkipVerify) 427 | } 428 | }) 429 | } 430 | } 431 | 432 | func BenchmarkParseDSN(b *testing.B) { 433 | b.ReportAllocs() 434 | 435 | for i := 0; i < b.N; i++ { 436 | for _, tst := range testDSNs { 437 | if _, err := ParseDSN(tst.in); err != nil { 438 | b.Error(err.Error()) 439 | } 440 | } 441 | } 442 | } 443 | --------------------------------------------------------------------------------