Full Code of go-sql-driver/mysql for AI

master fed2c72bc518 cached
47 files
440.5 KB
138.6k tokens
630 symbols
1 requests
Download .txt
Showing preview only (458K chars total). Download the full file or copy to clipboard to get everything.
Repository: go-sql-driver/mysql
Branch: master
Commit: fed2c72bc518
Files: 47
Total size: 440.5 KB

Directory structure:
gitextract_ul7tfipz/

├── .github/
│   ├── CONTRIBUTING.md
│   ├── ISSUE_TEMPLATE.md
│   ├── PULL_REQUEST_TEMPLATE.md
│   └── workflows/
│       ├── codeql.yml
│       └── test.yml
├── .gitignore
├── AUTHORS
├── CHANGELOG.md
├── LICENSE
├── README.md
├── auth.go
├── auth_test.go
├── benchmark_test.go
├── buffer.go
├── collations.go
├── compress.go
├── compress_test.go
├── conncheck.go
├── conncheck_dummy.go
├── conncheck_test.go
├── connection.go
├── connection_test.go
├── connector.go
├── connector_test.go
├── const.go
├── driver.go
├── driver_test.go
├── dsn.go
├── dsn_fuzz_test.go
├── dsn_test.go
├── errors.go
├── errors_test.go
├── fields.go
├── go.mod
├── go.sum
├── infile.go
├── nulltime.go
├── nulltime_test.go
├── packets.go
├── packets_test.go
├── result.go
├── rows.go
├── statement.go
├── statement_test.go
├── transaction.go
├── utils.go
└── utils_test.go

================================================
FILE CONTENTS
================================================

================================================
FILE: .github/CONTRIBUTING.md
================================================
# Contributing Guidelines

## Reporting Issues

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).

## Contributing Code

By contributing to this project, you share your code under the Mozilla Public License 2, as specified in the LICENSE file.
Don't forget to add yourself to the AUTHORS file.

### Code Review

Everyone is invited to review and comment on pull requests.
If it looks fine to you, comment with "LGTM" (Looks good to me).

If changes are required, notice the reviewers with "PTAL" (Please take another look) after committing the fixes.

Before merging the Pull Request, at least one [team member](https://github.com/go-sql-driver?tab=members) must have commented with "LGTM".

## Development Ideas

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.


================================================
FILE: .github/ISSUE_TEMPLATE.md
================================================
### Issue description
Tell us what should happen and what happens instead

### Example code
```go
If possible, please enter some example code here to reproduce the issue.
```

### Error log
```
If you have an error log, please paste it here.
```

### Configuration
*Driver version (or git SHA):*

*Go version:* run `go version` in your console

*Server version:* E.g. MySQL 5.6, MariaDB 10.0.20

*Server OS:* E.g. Debian 8.1 (Jessie), Windows 10


================================================
FILE: .github/PULL_REQUEST_TEMPLATE.md
================================================
### Description
Please explain the changes you made here.

### Checklist
- [ ] Code compiles correctly
- [ ] Created tests which fail without the change (if possible)
- [ ] All tests passing
- [ ] Extended the README / documentation, if necessary
- [ ] Added myself / the copyright holder to the AUTHORS file


================================================
FILE: .github/workflows/codeql.yml
================================================
name: "CodeQL"

on:
  push:
    branches: [ "master" ]
  pull_request:
    branches: [ "master" ]
  schedule:
    - cron: "18 19 * * 1"

jobs:
  analyze:
    name: Analyze
    runs-on: ubuntu-latest
    permissions:
      actions: read
      contents: read
      security-events: write

    strategy:
      fail-fast: false
      matrix:
        language: [ go ]

    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Initialize CodeQL
        uses: github/codeql-action/init@v3
        with:
          languages: ${{ matrix.language }}
          queries: +security-and-quality

      - name: Autobuild
        uses: github/codeql-action/autobuild@v3

      - name: Perform CodeQL Analysis
        uses: github/codeql-action/analyze@v3
        with:
          category: "/language:${{ matrix.language }}"


================================================
FILE: .github/workflows/test.yml
================================================
name: test
on:
  pull_request:
  push:
  workflow_dispatch:

env:
  MYSQL_TEST_USER: gotest
  MYSQL_TEST_PASS: secret
  MYSQL_TEST_ADDR: 127.0.0.1:3306
  MYSQL_TEST_CONCURRENT: 1

jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: dominikh/staticcheck-action@v1.3.1

  list:
    runs-on: ubuntu-latest
    outputs:
      matrix: ${{ steps.set-matrix.outputs.matrix }}
    steps:
      - name: list
        id: set-matrix
        run: |
          import json
          import os
          go = [
              # Keep the most recent production release at the top
              '1.24',
              # Older production releases
              '1.23',
              '1.22',
          ]
          mysql = [
              '9.0',
              '8.4', # LTS
              '8.0',
              '5.7',
              'mariadb-11.4',   # LTS
              'mariadb-11.2',
              'mariadb-11.1',
              'mariadb-10.11',  # LTS
              'mariadb-10.6',   # LTS
              'mariadb-10.5',   # LTS
          ]

          includes = []
          # Go versions compatibility check
          for v in go[1:]:
              includes.append({'os': 'ubuntu-latest', 'go': v, 'mysql': mysql[0]})

          matrix = {
              # OS vs MySQL versions
              'os': [ 'ubuntu-latest', 'macos-latest', 'windows-latest' ],
              'go': [ go[0] ],
              'mysql': mysql,

              'include': includes
          }
          output = json.dumps(matrix, separators=(',', ':'))
          with open(os.environ["GITHUB_OUTPUT"], 'a', encoding="utf-8") as f:
              print(f"matrix={output}", file=f)
        shell: python
  test:
    needs: list
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix: ${{ fromJSON(needs.list.outputs.matrix) }}
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-go@v5
        with:
          go-version: ${{ matrix.go }}
      - uses: shogo82148/actions-setup-mysql@v1
        with:
          mysql-version: ${{ matrix.mysql }}
          user: ${{ env.MYSQL_TEST_USER }}
          password: ${{ env.MYSQL_TEST_PASS }}
          my-cnf: |
            innodb_log_file_size=256MB
            innodb_buffer_pool_size=512MB
            max_allowed_packet=48MB
            ; TestConcurrent fails if max_connections is too large
            max_connections=50
            local_infile=1
            performance_schema=on
      - name: setup database
        run: |
          mysql --user 'root' --host '127.0.0.1' -e 'create database gotest;'

      - name: test
        run: |
          go test -v '-race' '-covermode=atomic' '-coverprofile=coverage.out' -parallel 10

      - name: benchmark
        run: |
          go test -run '^$' -bench .

      - name: Send coverage
        uses: shogo82148/actions-goveralls@v1
        with:
          path-to-profile: coverage.out
          flag-name: ${{ runner.os }}-Go-${{ matrix.go }}-DB-${{ matrix.mysql }}
          parallel: true

  # notifies that all test jobs are finished.
  finish:
    needs: test
    if: always()
    runs-on: ubuntu-latest
    steps:
      - uses: shogo82148/actions-goveralls@v1
        with:
          parallel-finished: true


================================================
FILE: .gitignore
================================================
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
Icon?
ehthumbs.db
Thumbs.db
.idea


================================================
FILE: AUTHORS
================================================
# This is the official list of Go-MySQL-Driver authors for copyright purposes.

# If you are submitting a patch, please add your name or the name of the
# organization which holds the copyright to this list in alphabetical order.

# Names should be added to this file as
#	Name <email address>
# The email address is not required for organizations.
# Please keep the list sorted.


# Individual Persons

Aaron Hopkins <go-sql-driver at die.net>
Achille Roussel <achille.roussel at gmail.com>
Aidan <aidan.liu at pingcap.com>
Alex Snast <alexsn at fb.com>
Alexey Palazhchenko <alexey.palazhchenko at gmail.com>
Andrew Reid <andrew.reid at tixtrack.com>
Animesh Ray <mail.rayanimesh at gmail.com>
Ariel Mashraki <ariel at mashraki.co.il>
Arne Hormann <arnehormann at gmail.com>
Artur Melanchyk <artur.melanchyk@gmail.com>
Asta Xie <xiemengjun at gmail.com>
B Lamarche <blam413 at gmail.com>
Bes Dollma <bdollma@thousandeyes.com>
Bogdan Constantinescu <bog.con.bc at gmail.com>
Brad Higgins <brad at defined.net>
Brian Hendriks <brian at dolthub.com>
Bulat Gaifullin <gaifullinbf at gmail.com>
Caine Jette <jette at alum.mit.edu>
Carlos Nieto <jose.carlos at menteslibres.net>
Chris Kirkland <chriskirkland at github.com>
Chris Moos <chris at tech9computers.com>
Craig Wilson <craiggwilson at gmail.com>
Daemonxiao <735462752 at qq.com>
Daniel Montoya <dsmontoyam at gmail.com>
Daniel Nichter <nil at codenode.com>
Daniël van Eeden <git at myname.nl>
Dave Protasowski <dprotaso at gmail.com>
Demouth <yuya at demouth.net>
Diego Dupin <diego.dupin at gmail.com>
Dirkjan Bussink <d.bussink at gmail.com>
DisposaBoy <disposaboy at dby.me>
Egor Smolyakov <egorsmkv at gmail.com>
Erwan Martin <hello at erwan.io>
Evan Elias <evan at skeema.net>
Evan Shaw <evan at vendhq.com>
Frederick Mayle <frederickmayle at gmail.com>
Gustavo Kristic <gkristic at gmail.com>
Gusted <postmaster at gusted.xyz>
Hajime Nakagami <nakagami at gmail.com>
Hanno Braun <mail at hannobraun.com>
Henri Yandell <flamefew at gmail.com>
Hirotaka Yamamoto <ymmt2005 at gmail.com>
Huyiguang <hyg at webterren.com>
ICHINOSE Shogo <shogo82148 at gmail.com>
Ilia Cimpoes <ichimpoesh at gmail.com>
INADA Naoki <songofacandy at gmail.com>
Jacek Szwec <szwec.jacek at gmail.com>
Jakub Adamus <kratky at zobak.cz>
James Harr <james.harr at gmail.com>
Janek Vedock <janekvedock at comcast.net>
Jason Ng <oblitorum at gmail.com>
Jean-Yves Pellé <jy at pelle.link>
Jeff Hodges <jeff at somethingsimilar.com>
Jeffrey Charles <jeffreycharles at gmail.com>
Jennifer Purevsuren <jennifer at dolthub.com>
Jerome Meyer <jxmeyer at gmail.com>
Jiabin Zhang <jiabin.z at qq.com>
Jiajia Zhong <zhong2plus at gmail.com>
Jian Zhen <zhenjl at gmail.com>
Joe Mann <contact at joemann.co.uk>
Joshua Prunier <joshua.prunier at gmail.com>
Julien Lefevre <julien.lefevr at gmail.com>
Julien Schmidt <go-sql-driver at julienschmidt.com>
Justin Li <jli at j-li.net>
Justin Nuß <nuss.justin at gmail.com>
Kamil Dziedzic <kamil at klecza.pl>
Kei Kamikawa <x00.x7f.x86 at gmail.com>
Kevin Malachowski <kevin at chowski.com>
Kieron Woodhouse <kieron.woodhouse at infosum.com>
Lance Tian <lance6716 at gmail.com>
Lennart Rudolph <lrudolph at hmc.edu>
Leonardo YongUk Kim <dalinaum at gmail.com>
Linh Tran Tuan <linhduonggnu at gmail.com>
Lion Yang <lion at aosc.xyz>
Luca Looz <luca.looz92 at gmail.com>
Lucas Liu <extrafliu at gmail.com>
Luke Scott <luke at webconnex.com>
Lunny Xiao <xiaolunwen at gmail.com>
Maciej Zimnoch <maciej.zimnoch at codilime.com>
Michael Woolnough <michael.woolnough at gmail.com>
Minh Quang <minhquang4334 at gmail.com>
Nao Yokotsuka <yokotukanao at gmail.com>
Nathanial Murphy <nathanial.murphy at gmail.com>
Nicola Peduzzi <thenikso at gmail.com>
Oliver Bone <owbone at github.com>
Olivier Mengué <dolmen at cpan.org>
oscarzhao <oscarzhaosl at gmail.com>
Paul Bonser <misterpib at gmail.com>
Paulius Lozys <pauliuslozys at gmail.com>
Peter Schultz <peter.schultz at classmarkets.com>
Phil Porada <philporada at gmail.com>
Rebecca Chin <rchin at pivotal.io>
Reed Allman <rdallman10 at gmail.com>
Richard Wilkes <wilkes at me.com>
Robert Russell <robert at rrbrussell.com>
Runrioter Wung <runrioter at gmail.com>
Samantha Frank <hello at entropy.cat>
Santhosh Kumar Tekuri <santhosh.tekuri at gmail.com>
Sho Iizuka <sho.i518 at gmail.com>
Sho Ikeda <suicaicoca at gmail.com>
Shuode Li <elemount at qq.com>
Simon J Mudd <sjmudd at pobox.com>
Soroush Pour <me at soroushjp.com>
Stan Putrya <root.vagner at gmail.com>
Stanley Gunawan <gunawan.stanley at gmail.com>
Steven Hartland <steven.hartland at multiplay.co.uk>
Tan Jinhua <312841925 at qq.com>
Tetsuro Aoki <t.aoki1130 at gmail.com>
Thomas Wodarek <wodarekwebpage at gmail.com>
Tim Ruffles <timruffles at gmail.com>
Tom Jenkinson <tom at tjenkinson.me>
Vladimir Kovpak <cn007b at gmail.com>
Vladyslav Zhelezniak <zhvladi at gmail.com>
Xiangyu Hu <xiangyu.hu at outlook.com>
Xiaobing Jiang <s7v7nislands at gmail.com>
Xiuming Chen <cc at cxm.cc>
Xuehong Chan <chanxuehong at gmail.com>
Zhang Xiang <angwerzx at 126.com>
Zhenye Xie <xiezhenye at gmail.com>
Zhixin Wen <john.wenzhixin at gmail.com>
Ziheng Lyu <zihenglv at gmail.com>

# Organizations

Barracuda Networks, Inc.
Counting Ltd.
Defined Networking Inc.
DigitalOcean Inc.
Dolthub Inc.
dyves labs AG
Facebook Inc.
GitHub Inc.
Google Inc.
InfoSum Ltd.
Keybase Inc.
Microsoft Corp.
Multiplay Ltd.
Percona LLC
PingCAP Inc.
Pivotal Inc.
Shattered Silicon Ltd.
Stripe Inc.
ThousandEyes
Zendesk Inc.


================================================
FILE: CHANGELOG.md
================================================
# Changelog

## v1.9.2 (2025-04-07)

v1.9.2 is a re-release of v1.9.1 due to a release process issue; no changes were made to the content.


## v1.9.1 (2025-03-21)

### Major Changes

* Add Charset() option. (#1679)

### Bugfixes

* go.mod: fix go version format (#1682)
* Fix FormatDSN missing ConnectionAttributes (#1619)

## v1.9.0 (2025-02-18)

### Major Changes

- Implement zlib compression. (#1487)
- Supported Go version is updated to Go 1.21+. (#1639)
- Add support for VECTOR type introduced in MySQL 9.0. (#1609)
- Config object can have custom dial function. (#1527)

### Bugfixes

- Fix auth errors when username/password are too long. (#1625)
- Check if MySQL supports CLIENT_CONNECT_ATTRS before sending client attributes. (#1640)
- Fix auth switch request handling. (#1666)

### Other changes

- Add "filename:line" prefix to log in go-mysql. Custom loggers now show it. (#1589)
- Improve error handling. It reduces the "busy buffer" errors. (#1595, #1601, #1641)
- Use `strconv.Atoi` to parse max_allowed_packet. (#1661)
- `rejectReadOnly` option now handles ER_READ_ONLY_MODE (1290) error too. (#1660)


## Version 1.8.1 (2024-03-26)

Bugfixes:

- 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)

## Version 1.8.0 (2024-03-09)

Major Changes:

- Use `SET NAMES charset COLLATE collation`. by @methane in [#1437](https://github.com/go-sql-driver/mysql/pull/1437)
  - Older go-mysql-driver used `collation_id` in the handshake packet. But it caused collation mismatch in some situation.
  - 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.
  - If you specify charset, go-mysql-driver sends `SET NAMES <charset>`. This uses the server's default collation for `<charset>`.
  - If you specify collation and/or charset, go-mysql-driver sends `SET NAMES charset COLLATE collation`.
- PathEscape dbname in DSN. by @methane in [#1432](https://github.com/go-sql-driver/mysql/pull/1432)
  - This is backward incompatible in rare case. Check your DSN.
- Drop Go 1.13-17 support by @methane in [#1420](https://github.com/go-sql-driver/mysql/pull/1420)
  - Use Go 1.18+
- Parse numbers on text protocol too by @methane in [#1452](https://github.com/go-sql-driver/mysql/pull/1452)
  - When text protocol is used, go-mysql-driver passed bare `[]byte` to database/sql for avoid unnecessary allocation and conversion.
  - If user specified `*any` to `Scan()`, database/sql passed the `[]byte` into the target variable.
  - This confused users because most user doesn't know when text/binary protocol used.
  - 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.
- 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.
  - Make TimeTruncate functional option by @methane in [1552](https://github.com/go-sql-driver/mysql/pull/1552)
  - Add BeforeConnect callback to configuration object by @ItalyPaleAle in [#1469](https://github.com/go-sql-driver/mysql/pull/1469)


Other changes:

- 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
- Make logger configurable per connection by @frozenbonito in https://github.com/go-sql-driver/mysql/pull/1408
- Fix ColumnType.DatabaseTypeName for mediumint unsigned by @evanelias in https://github.com/go-sql-driver/mysql/pull/1428
- Add connection attributes by @Daemonxiao in https://github.com/go-sql-driver/mysql/pull/1389
- Stop `ColumnTypeScanType()` from returning `sql.RawBytes` by @methane in https://github.com/go-sql-driver/mysql/pull/1424
- Exec() now provides access to status of multiple statements. by @mherr-google in https://github.com/go-sql-driver/mysql/pull/1309
- Allow to change (or disable) the default driver name for registration by @dolmen in https://github.com/go-sql-driver/mysql/pull/1499
- Add default connection attribute '_server_host' by @oblitorum in https://github.com/go-sql-driver/mysql/pull/1506
- QueryUnescape DSN ConnectionAttribute value by @zhangyangyu in https://github.com/go-sql-driver/mysql/pull/1470
- Add client_ed25519 authentication by @Gusted in https://github.com/go-sql-driver/mysql/pull/1518

## Version 1.7.1 (2023-04-25)

Changes:

  - bump actions/checkout@v3 and actions/setup-go@v3 (#1375)
  - Add go1.20 and mariadb10.11 to the testing matrix (#1403)
  - Increase default maxAllowedPacket size. (#1411)

Bugfixes:

  - Use SET syntax as specified in the MySQL documentation (#1402)


## Version 1.7 (2022-11-29)

Changes:

  - Drop support of Go 1.12 (#1211)
  - Refactoring `(*textRows).readRow` in a more clear way (#1230)
  - util: Reduce boundary check in escape functions. (#1316)
  - enhancement for mysqlConn handleAuthResult (#1250)

New Features:

  - support Is comparison on MySQLError (#1210)
  - return unsigned in database type name when necessary (#1238)
  - Add API to express like a --ssl-mode=PREFERRED MySQL client (#1370)
  - Add SQLState to MySQLError (#1321)

Bugfixes:

  -  Fix parsing 0 year. (#1257)


## Version 1.6 (2021-04-01)

Changes:

  - Migrate the CI service from travis-ci to GitHub Actions (#1176, #1183, #1190)
  - `NullTime` is deprecated (#960, #1144)
  - Reduce allocations when building SET command (#1111)
  - Performance improvement for time formatting (#1118)
  - Performance improvement for time parsing (#1098, #1113)

New Features:

  - Implement `driver.Validator` interface (#1106, #1174)
  - Support returning `uint64` from `Valuer` in `ConvertValue` (#1143)
  - Add `json.RawMessage` for converter and prepared statement (#1059)
  - Interpolate `json.RawMessage` as `string` (#1058)
  - Implements `CheckNamedValue` (#1090)

Bugfixes:

  - Stop rounding times (#1121, #1172)
  - Put zero filler into the SSL handshake packet (#1066)
  - Fix checking cancelled connections back into the connection pool (#1095)
  - Fix remove last 0 byte for mysql_old_password when password is empty (#1133)


## Version 1.5 (2020-01-07)

Changes:

  - Dropped support Go 1.9 and lower (#823, #829, #886, #1016, #1017)
  - Improve buffer handling (#890)
  - Document potentially insecure TLS configs (#901)
  - Use a double-buffering scheme to prevent data races (#943)
  - Pass uint64 values without converting them to string (#838, #955)
  - Update collations and make utf8mb4 default (#877, #1054)
  - Make NullTime compatible with sql.NullTime in Go 1.13+ (#995)
  - Removed CloudSQL support (#993, #1007)
  - Add Go Module support (#1003)

New Features:

  - Implement support of optional TLS (#900)
  - Check connection liveness (#934, #964, #997, #1048, #1051, #1052)
  - Implement Connector Interface (#941, #958, #1020, #1035)

Bugfixes:

  - Mark connections as bad on error during ping (#875)
  - Mark connections as bad on error during dial (#867)
  - Fix connection leak caused by rapid context cancellation (#1024)
  - Mark connections as bad on error during Conn.Prepare (#1030)


## Version 1.4.1 (2018-11-14)

Bugfixes:

 - Fix TIME format for binary columns (#818)
 - Fix handling of empty auth plugin names (#835)
 - Fix caching_sha2_password with empty password (#826)
 - Fix canceled context broke mysqlConn (#862)
 - Fix OldAuthSwitchRequest support (#870)
 - Fix Auth Response packet for cleartext password (#887)

## Version 1.4 (2018-06-03)

Changes:

 - Documentation fixes (#530, #535, #567)
 - Refactoring (#575, #579, #580, #581, #603, #615, #704)
 - Cache column names (#444)
 - Sort the DSN parameters in DSNs generated from a config (#637)
 - Allow native password authentication by default (#644)
 - Use the default port if it is missing in the DSN (#668)
 - Removed the `strict` mode (#676)
 - Do not query `max_allowed_packet` by default (#680)
 - Dropped support Go 1.6 and lower (#696)
 - Updated `ConvertValue()` to match the database/sql/driver implementation (#760)
 - Document the usage of `0000-00-00T00:00:00` as the time.Time zero value (#783)
 - Improved the compatibility of the authentication system (#807)

New Features:

 - Multi-Results support (#537)
 - `rejectReadOnly` DSN option (#604)
 - `context.Context` support (#608, #612, #627, #761)
 - Transaction isolation level support (#619, #744)
 - Read-Only transactions support (#618, #634)
 - `NewConfig` function which initializes a config with default values (#679)
 - Implemented the `ColumnType` interfaces (#667, #724)
 - Support for custom string types in `ConvertValue` (#623)
 - Implemented `NamedValueChecker`, improving support for uint64 with high bit set (#690, #709, #710)
 - `caching_sha2_password` authentication plugin support (#794, #800, #801, #802)
 - Implemented `driver.SessionResetter` (#779)
 - `sha256_password` authentication plugin support (#808)

Bugfixes:

 - Use the DSN hostname as TLS default ServerName if `tls=true` (#564, #718)
 - Fixed LOAD LOCAL DATA INFILE for empty files (#590)
 - Removed columns definition cache since it sometimes cached invalid data (#592)
 - Don't mutate registered TLS configs (#600)
 - Make RegisterTLSConfig concurrency-safe (#613)
 - Handle missing auth data in the handshake packet correctly (#646)
 - Do not retry queries when data was written to avoid data corruption (#302, #736)
 - Cache the connection pointer for error handling before invalidating it (#678)
 - Fixed imports for appengine/cloudsql (#700)
 - Fix sending STMT_LONG_DATA for 0 byte data (#734)
 - Set correct capacity for []bytes read from length-encoded strings (#766)
 - Make RegisterDial concurrency-safe (#773)


## Version 1.3 (2016-12-01)

Changes:

 - Go 1.1 is no longer supported
 - Use decimals fields in MySQL to format time types (#249)
 - Buffer optimizations (#269)
 - TLS ServerName defaults to the host (#283)
 - Refactoring (#400, #410, #437)
 - Adjusted documentation for second generation CloudSQL (#485)
 - Documented DSN system var quoting rules (#502)
 - Made statement.Close() calls idempotent to avoid errors in Go 1.6+ (#512)

New Features:

 - Enable microsecond resolution on TIME, DATETIME and TIMESTAMP (#249)
 - Support for returning table alias on Columns() (#289, #359, #382)
 - Placeholder interpolation, can be activated with the DSN parameter `interpolateParams=true` (#309, #318, #490)
 - Support for uint64 parameters with high bit set (#332, #345)
 - Cleartext authentication plugin support (#327)
 - Exported ParseDSN function and the Config struct (#403, #419, #429)
 - Read / Write timeouts (#401)
 - Support for JSON field type (#414)
 - Support for multi-statements and multi-results (#411, #431)
 - DSN parameter to set the driver-side max_allowed_packet value manually (#489)
 - Native password authentication plugin support (#494, #524)

Bugfixes:

 - Fixed handling of queries without columns and rows (#255)
 - Fixed a panic when SetKeepAlive() failed (#298)
 - Handle ERR packets while reading rows (#321)
 - Fixed reading NULL length-encoded integers in MySQL 5.6+ (#349)
 - Fixed absolute paths support in LOAD LOCAL DATA INFILE (#356)
 - Actually zero out bytes in handshake response (#378)
 - Fixed race condition in registering LOAD DATA INFILE handler (#383)
 - Fixed tests with MySQL 5.7.9+ (#380)
 - QueryUnescape TLS config names (#397)
 - Fixed "broken pipe" error by writing to closed socket (#390)
 - Fixed LOAD LOCAL DATA INFILE buffering (#424)
 - Fixed parsing of floats into float64 when placeholders are used (#434)
 - Fixed DSN tests with Go 1.7+ (#459)
 - Handle ERR packets while waiting for EOF (#473)
 - Invalidate connection on error while discarding additional results (#513)
 - Allow terminating packets of length 0 (#516)


## Version 1.2 (2014-06-03)

Changes:

 - We switched back to a "rolling release". `go get` installs the current master branch again
 - Version v1 of the driver will not be maintained anymore. Go 1.0 is no longer supported by this driver
 - Exported errors to allow easy checking from application code
 - Enabled TCP Keepalives on TCP connections
 - Optimized INFILE handling (better buffer size calculation, lazy init, ...)
 - The DSN parser also checks for a missing separating slash
 - Faster binary date / datetime to string formatting
 - Also exported the MySQLWarning type
 - mysqlConn.Close returns the first error encountered instead of ignoring all errors
 - writePacket() automatically writes the packet size to the header
 - readPacket() uses an iterative approach instead of the recursive approach to merge split packets

New Features:

 - `RegisterDial` allows the usage of a custom dial function to establish the network connection
 - Setting the connection collation is possible with the `collation` DSN parameter. This parameter should be preferred over the `charset` parameter
 - Logging of critical errors is configurable with `SetLogger`
 - Google CloudSQL support

Bugfixes:

 - Allow more than 32 parameters in prepared statements
 - Various old_password fixes
 - Fixed TestConcurrent test to pass Go's race detection
 - Fixed appendLengthEncodedInteger for large numbers
 - Renamed readLengthEnodedString to readLengthEncodedString and skipLengthEnodedString to skipLengthEncodedString (fixed typo)


## Version 1.1 (2013-11-02)

Changes:

  - Go-MySQL-Driver now requires Go 1.1
  - Connections now use the collation `utf8_general_ci` by default. Adding `&charset=UTF8` to the DSN should not be necessary anymore
  - Made closing rows and connections error tolerant. This allows for example deferring rows.Close() without checking for errors
  - `[]byte(nil)` is now treated as a NULL value. Before, it was treated like an empty string / `[]byte("")`
  - DSN parameter values must now be url.QueryEscape'ed. This allows text values to contain special characters, such as '&'.
  - Use the IO buffer also for writing. This results in zero allocations (by the driver) for most queries
  - Optimized the buffer for reading
  - stmt.Query now caches column metadata
  - New Logo
  - Changed the copyright header to include all contributors
  - Improved the LOAD INFILE documentation
  - The driver struct is now exported to make the driver directly accessible
  - Refactored the driver tests
  - Added more benchmarks and moved all to a separate file
  - Other small refactoring

New Features:

  - Added *old_passwords* support: Required in some cases, but must be enabled by adding `allowOldPasswords=true` to the DSN since it is insecure
  - Added a `clientFoundRows` parameter: Return the number of matching rows instead of the number of rows changed on UPDATEs
  - Added TLS/SSL support: Use a TLS/SSL encrypted connection to the server. Custom TLS configs can be registered and used

Bugfixes:

  - Fixed MySQL 4.1 support: MySQL 4.1 sends packets with lengths which differ from the specification
  - Convert to DB timezone when inserting `time.Time`
  - Split packets (more than 16MB) are now merged correctly
  - Fixed false positive `io.EOF` errors when the data was fully read
  - Avoid panics on reuse of closed connections
  - Fixed empty string producing false nil values
  - Fixed sign byte for positive TIME fields


## Version 1.0 (2013-05-14)

Initial Release


================================================
FILE: LICENSE
================================================
Mozilla Public License Version 2.0
==================================

1. Definitions
--------------

1.1. "Contributor"
    means each individual or legal entity that creates, contributes to
    the creation of, or owns Covered Software.

1.2. "Contributor Version"
    means the combination of the Contributions of others (if any) used
    by a Contributor and that particular Contributor's Contribution.

1.3. "Contribution"
    means Covered Software of a particular Contributor.

1.4. "Covered Software"
    means Source Code Form to which the initial Contributor has attached
    the notice in Exhibit A, the Executable Form of such Source Code
    Form, and Modifications of such Source Code Form, in each case
    including portions thereof.

1.5. "Incompatible With Secondary Licenses"
    means

    (a) that the initial Contributor has attached the notice described
        in Exhibit B to the Covered Software; or

    (b) that the Covered Software was made available under the terms of
        version 1.1 or earlier of the License, but not also under the
        terms of a Secondary License.

1.6. "Executable Form"
    means any form of the work other than Source Code Form.

1.7. "Larger Work"
    means a work that combines Covered Software with other material, in 
    a separate file or files, that is not Covered Software.

1.8. "License"
    means this document.

1.9. "Licensable"
    means having the right to grant, to the maximum extent possible,
    whether at the time of the initial grant or subsequently, any and
    all of the rights conveyed by this License.

1.10. "Modifications"
    means any of the following:

    (a) any file in Source Code Form that results from an addition to,
        deletion from, or modification of the contents of Covered
        Software; or

    (b) any new file in Source Code Form that contains any Covered
        Software.

1.11. "Patent Claims" of a Contributor
    means any patent claim(s), including without limitation, method,
    process, and apparatus claims, in any patent Licensable by such
    Contributor that would be infringed, but for the grant of the
    License, by the making, using, selling, offering for sale, having
    made, import, or transfer of either its Contributions or its
    Contributor Version.

1.12. "Secondary License"
    means either the GNU General Public License, Version 2.0, the GNU
    Lesser General Public License, Version 2.1, the GNU Affero General
    Public License, Version 3.0, or any later versions of those
    licenses.

1.13. "Source Code Form"
    means the form of the work preferred for making modifications.

1.14. "You" (or "Your")
    means an individual or a legal entity exercising rights under this
    License. For legal entities, "You" includes any entity that
    controls, is controlled by, or is under common control with You. For
    purposes of this definition, "control" means (a) the power, direct
    or indirect, to cause the direction or management of such entity,
    whether by contract or otherwise, or (b) ownership of more than
    fifty percent (50%) of the outstanding shares or beneficial
    ownership of such entity.

2. License Grants and Conditions
--------------------------------

2.1. Grants

Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:

(a) under intellectual property rights (other than patent or trademark)
    Licensable by such Contributor to use, reproduce, make available,
    modify, display, perform, distribute, and otherwise exploit its
    Contributions, either on an unmodified basis, with Modifications, or
    as part of a Larger Work; and

(b) under Patent Claims of such Contributor to make, use, sell, offer
    for sale, have made, import, and otherwise transfer either its
    Contributions or its Contributor Version.

2.2. Effective Date

The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.

2.3. Limitations on Grant Scope

The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:

(a) for any code that a Contributor has removed from Covered Software;
    or

(b) for infringements caused by: (i) Your and any other third party's
    modifications of Covered Software, or (ii) the combination of its
    Contributions with other software (except as part of its Contributor
    Version); or

(c) under Patent Claims infringed by Covered Software in the absence of
    its Contributions.

This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).

2.4. Subsequent Licenses

No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).

2.5. Representation

Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.

2.6. Fair Use

This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.

2.7. Conditions

Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.

3. Responsibilities
-------------------

3.1. Distribution of Source Form

All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.

3.2. Distribution of Executable Form

If You distribute Covered Software in Executable Form then:

(a) such Covered Software must also be made available in Source Code
    Form, as described in Section 3.1, and You must inform recipients of
    the Executable Form how they can obtain a copy of such Source Code
    Form by reasonable means in a timely manner, at a charge no more
    than the cost of distribution to the recipient; and

(b) You may distribute such Executable Form under the terms of this
    License, or sublicense it under different terms, provided that the
    license for the Executable Form does not attempt to limit or alter
    the recipients' rights in the Source Code Form under this License.

3.3. Distribution of a Larger Work

You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).

3.4. Notices

You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.

3.5. Application of Additional Terms

You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.

4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------

If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.

5. Termination
--------------

5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.

5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.

5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.

************************************************************************
*                                                                      *
*  6. Disclaimer of Warranty                                           *
*  -------------------------                                           *
*                                                                      *
*  Covered Software is provided under this License on an "as is"       *
*  basis, without warranty of any kind, either expressed, implied, or  *
*  statutory, including, without limitation, warranties that the       *
*  Covered Software is free of defects, merchantable, fit for a        *
*  particular purpose or non-infringing. The entire risk as to the     *
*  quality and performance of the Covered Software is with You.        *
*  Should any Covered Software prove defective in any respect, You     *
*  (not any Contributor) assume the cost of any necessary servicing,   *
*  repair, or correction. This disclaimer of warranty constitutes an   *
*  essential part of this License. No use of any Covered Software is   *
*  authorized under this License except under this disclaimer.         *
*                                                                      *
************************************************************************

************************************************************************
*                                                                      *
*  7. Limitation of Liability                                          *
*  --------------------------                                          *
*                                                                      *
*  Under no circumstances and under no legal theory, whether tort      *
*  (including negligence), contract, or otherwise, shall any           *
*  Contributor, or anyone who distributes Covered Software as          *
*  permitted above, be liable to You for any direct, indirect,         *
*  special, incidental, or consequential damages of any character      *
*  including, without limitation, damages for lost profits, loss of    *
*  goodwill, work stoppage, computer failure or malfunction, or any    *
*  and all other commercial damages or losses, even if such party      *
*  shall have been informed of the possibility of such damages. This   *
*  limitation of liability shall not apply to liability for death or   *
*  personal injury resulting from such party's negligence to the       *
*  extent applicable law prohibits such limitation. Some               *
*  jurisdictions do not allow the exclusion or limitation of           *
*  incidental or consequential damages, so this exclusion and          *
*  limitation may not apply to You.                                    *
*                                                                      *
************************************************************************

8. Litigation
-------------

Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.

9. Miscellaneous
----------------

This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.

10. Versions of the License
---------------------------

10.1. New Versions

Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.

10.2. Effect of New Versions

You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.

10.3. Modified Versions

If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).

10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses

If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.

Exhibit A - Source Code Form License Notice
-------------------------------------------

  This Source Code Form is subject to the terms of the Mozilla Public
  License, v. 2.0. If a copy of the MPL was not distributed with this
  file, You can obtain one at http://mozilla.org/MPL/2.0/.

If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.

You may add additional accurate notices of copyright ownership.

Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------

  This Source Code Form is "Incompatible With Secondary Licenses", as
  defined by the Mozilla Public License, v. 2.0.


================================================
FILE: README.md
================================================
# Go-MySQL-Driver

[![DeepWiki](https://img.shields.io/badge/DeepWiki-go--sql--driver%2Fmysql-blue.svg?logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACwAAAAyCAYAAAAnWDnqAAAAAXNSR0IArs4c6QAAA05JREFUaEPtmUtyEzEQhtWTQyQLHNak2AB7ZnyXZMEjXMGeK/AIi+QuHrMnbChYY7MIh8g01fJoopFb0uhhEqqcbWTp06/uv1saEDv4O3n3dV60RfP947Mm9/SQc0ICFQgzfc4CYZoTPAswgSJCCUJUnAAoRHOAUOcATwbmVLWdGoH//PB8mnKqScAhsD0kYP3j/Yt5LPQe2KvcXmGvRHcDnpxfL2zOYJ1mFwrryWTz0advv1Ut4CJgf5uhDuDj5eUcAUoahrdY/56ebRWeraTjMt/00Sh3UDtjgHtQNHwcRGOC98BJEAEymycmYcWwOprTgcB6VZ5JK5TAJ+fXGLBm3FDAmn6oPPjR4rKCAoJCal2eAiQp2x0vxTPB3ALO2CRkwmDy5WohzBDwSEFKRwPbknEggCPB/imwrycgxX2NzoMCHhPkDwqYMr9tRcP5qNrMZHkVnOjRMWwLCcr8ohBVb1OMjxLwGCvjTikrsBOiA6fNyCrm8V1rP93iVPpwaE+gO0SsWmPiXB+jikdf6SizrT5qKasx5j8ABbHpFTx+vFXp9EnYQmLx02h1QTTrl6eDqxLnGjporxl3NL3agEvXdT0WmEost648sQOYAeJS9Q7bfUVoMGnjo4AZdUMQku50McDcMWcBPvr0SzbTAFDfvJqwLzgxwATnCgnp4wDl6Aa+Ax283gghmj+vj7feE2KBBRMW3FzOpLOADl0Isb5587h/U4gGvkt5v60Z1VLG8BhYjbzRwyQZemwAd6cCR5/XFWLYZRIMpX39AR0tjaGGiGzLVyhse5C9RKC6ai42ppWPKiBagOvaYk8lO7DajerabOZP46Lby5wKjw1HCRx7p9sVMOWGzb/vA1hwiWc6jm3MvQDTogQkiqIhJV0nBQBTU+3okKCFDy9WwferkHjtxib7t3xIUQtHxnIwtx4mpg26/HfwVNVDb4oI9RHmx5WGelRVlrtiw43zboCLaxv46AZeB3IlTkwouebTr1y2NjSpHz68WNFjHvupy3q8TFn3Hos2IAk4Ju5dCo8B3wP7VPr/FGaKiG+T+v+TQqIrOqMTL1VdWV1DdmcbO8KXBz6esmYWYKPwDL5b5FA1a0hwapHiom0r/cKaoqr+27/XcrS5UwSMbQAAAABJRU5ErkJggg==)](https://deepwiki.com/go-sql-driver/mysql)


A MySQL-Driver for Go's [database/sql](https://golang.org/pkg/database/sql/) package

![Go-MySQL-Driver logo](https://raw.github.com/wiki/go-sql-driver/mysql/gomysql_m.png "Golang Gopher holding the MySQL Dolphin")

---------------------------------------
  * [Features](#features)
  * [Requirements](#requirements)
  * [Installation](#installation)
  * [Usage](#usage)
    * [DSN (Data Source Name)](#dsn-data-source-name)
      * [Password](#password)
      * [Protocol](#protocol)
      * [Address](#address)
      * [Parameters](#parameters)
      * [Examples](#examples)
    * [Connection pool and timeouts](#connection-pool-and-timeouts)
    * [context.Context Support](#contextcontext-support)
    * [ColumnType Support](#columntype-support)
    * [LOAD DATA LOCAL INFILE support](#load-data-local-infile-support)
    * [time.Time support](#timetime-support)
    * [Unicode support](#unicode-support)
  * [Testing / Development](#testing--development)
  * [License](#license)

---------------------------------------

## Features
  * Lightweight and [fast](https://github.com/go-sql-driver/sql-benchmark "golang MySQL-Driver performance")
  * Native Go implementation. No C-bindings, just pure Go
  * Connections over TCP/IPv4, TCP/IPv6, Unix domain sockets or [custom protocols](https://godoc.org/github.com/go-sql-driver/mysql#DialFunc)
  * Automatic handling of broken connections
  * Automatic Connection Pooling *(by database/sql package)*
  * Supports queries larger than 16MB
  * Full [`sql.RawBytes`](https://golang.org/pkg/database/sql/#RawBytes) support.
  * Intelligent `LONG DATA` handling in prepared statements
  * Secure `LOAD DATA LOCAL INFILE` support with file allowlisting and `io.Reader` support
  * Optional `time.Time` parsing
  * Optional placeholder interpolation
  * Supports zlib compression.

## Requirements

* Go 1.22 or higher. We aim to support the 3 latest versions of Go.
* MySQL (5.7+) and MariaDB (10.5+) are supported.
* [TiDB](https://github.com/pingcap/tidb) is supported by PingCAP.
  * Do not ask questions about TiDB in our issue tracker or forum.
  * [Document](https://docs.pingcap.com/tidb/v6.1/dev-guide-sample-application-golang)
  * [Forum](https://ask.pingcap.com/)
* go-mysql would work with Percona Server, Google CloudSQL or Sphinx (2.2.3+).
  * Maintainers won't support them. Do not expect issues are investigated and resolved by maintainers.
  * Investigate issues yourself and please send a pull request to fix it.

---------------------------------------

## Installation
Simple install the package to your [$GOPATH](https://github.com/golang/go/wiki/GOPATH "GOPATH") with the [go tool](https://golang.org/cmd/go/ "go command") from shell:
```bash
go get -u github.com/go-sql-driver/mysql
```
Make sure [Git is installed](https://git-scm.com/downloads) on your machine and in your system's `PATH`.

## Usage
_Go MySQL Driver_ is an implementation of Go's `database/sql/driver` interface. You only need to import the driver and can use the full [`database/sql`](https://golang.org/pkg/database/sql/) API then.

Use `mysql` as `driverName` and a valid [DSN](#dsn-data-source-name)  as `dataSourceName`:

```go
import (
	"database/sql"
	"time"

	_ "github.com/go-sql-driver/mysql"
)

// ...

db, err := sql.Open("mysql", "user:password@/dbname")
if err != nil {
	panic(err)
}
// See "Important settings" section.
db.SetConnMaxLifetime(time.Minute * 3)
db.SetMaxOpenConns(10)
db.SetMaxIdleConns(10)
```

[Examples are available in our Wiki](https://github.com/go-sql-driver/mysql/wiki/Examples "Go-MySQL-Driver Examples").

### Important settings

`db.SetConnMaxLifetime()` is required to ensure connections are closed by the driver safely before connection is closed by MySQL server, OS, or other middlewares. Since some middlewares close idle connections by 5 minutes, we recommend timeout shorter than 5 minutes. This setting helps load balancing and changing system variables too.

`db.SetMaxOpenConns()` is highly recommended to limit the number of connection used by the application. There is no recommended limit number because it depends on application and MySQL server.

`db.SetMaxIdleConns()` is recommended to be set same to `db.SetMaxOpenConns()`. When it is smaller than `SetMaxOpenConns()`, connections can be opened and closed much more frequently than you expect. Idle connections can be closed by the `db.SetConnMaxLifetime()`. If you want to close idle connections more rapidly, you can use `db.SetConnMaxIdleTime()` since Go 1.15.


### DSN (Data Source Name)

The Data Source Name has a common format, like e.g. [PEAR DB](http://pear.php.net/manual/en/package.database.db.intro-dsn.php) uses it, but without type-prefix (optional parts marked by squared brackets):
```
[username[:password]@][protocol[(address)]]/dbname[?param1=value1&...&paramN=valueN]
```

A DSN in its fullest form:
```
username:password@protocol(address)/dbname?param=value
```

Except for the databasename, all values are optional. So the minimal DSN is:
```
/dbname
```

If you do not want to preselect a database, leave `dbname` empty:
```
/
```
This has the same effect as an empty DSN string:
```

```

`dbname` is escaped by [PathEscape()](https://pkg.go.dev/net/url#PathEscape) since v1.8.0. If your database name is `dbname/withslash`, it becomes:

```
/dbname%2Fwithslash
```

Alternatively, [Config.FormatDSN](https://godoc.org/github.com/go-sql-driver/mysql#Config.FormatDSN) can be used to create a DSN string by filling a struct.

#### Password
Passwords can consist of any character. Escaping is **not** necessary.

#### Protocol
See [net.Dial](https://golang.org/pkg/net/#Dial) for more information which networks are available.
In general you should use a Unix domain socket if available and TCP otherwise for best performance.

#### Address
For TCP and UDP networks, addresses have the form `host[:port]`.
If `port` is omitted, the default port will be used.
If `host` is a literal IPv6 address, it must be enclosed in square brackets.
The functions [net.JoinHostPort](https://golang.org/pkg/net/#JoinHostPort) and [net.SplitHostPort](https://golang.org/pkg/net/#SplitHostPort) manipulate addresses in this form.

For Unix domain sockets the address is the absolute path to the MySQL-Server-socket, e.g. `/var/run/mysqld/mysqld.sock` or `/tmp/mysql.sock`.

#### Parameters
*Parameters are case-sensitive!*

Notice that any of `true`, `TRUE`, `True` or `1` is accepted to stand for a true boolean value. Not surprisingly, false can be specified as any of: `false`, `FALSE`, `False` or `0`.

##### `allowAllFiles`

```
Type:           bool
Valid Values:   true, false
Default:        false
```

`allowAllFiles=true` disables the file allowlist for `LOAD DATA LOCAL INFILE` and allows *all* files.
[*Might be insecure!*](https://dev.mysql.com/doc/refman/8.0/en/load-data.html#load-data-local)

##### `allowCleartextPasswords`

```
Type:           bool
Valid Values:   true, false
Default:        false
```

`allowCleartextPasswords=true` allows using the [cleartext client side plugin](https://dev.mysql.com/doc/en/cleartext-pluggable-authentication.html) if required by an account, such as one defined with the [PAM authentication plugin](http://dev.mysql.com/doc/en/pam-authentication-plugin.html). Sending passwords in clear text may be a security problem in some configurations. To avoid problems if there is any possibility that the password would be intercepted, clients should connect to MySQL Server using a method that protects the password. Possibilities include [TLS / SSL](#tls), IPsec, or a private network.


##### `allowFallbackToPlaintext`

```
Type:           bool
Valid Values:   true, false
Default:        false
```

`allowFallbackToPlaintext=true` acts like a `--ssl-mode=PREFERRED` MySQL client as described in [Command Options for Connecting to the Server](https://dev.mysql.com/doc/refman/5.7/en/connection-options.html#option_general_ssl-mode)

##### `allowNativePasswords`

```
Type:           bool
Valid Values:   true, false
Default:        true
```
`allowNativePasswords=false` disallows the usage of MySQL native password method.

##### `allowOldPasswords`

```
Type:           bool
Valid Values:   true, false
Default:        false
```
`allowOldPasswords=true` allows the usage of the insecure old password method. This should be avoided, but is necessary in some cases. See also [the old_passwords wiki page](https://github.com/go-sql-driver/mysql/wiki/old_passwords).

##### `charset`

```
Type:           string
Valid Values:   <name>
Default:        none
```

Sets the charset used for client-server interaction (`"SET NAMES <value>"`). If multiple charsets are set (separated by a comma), the following charset is used if setting the charset fails. This enables for example support for `utf8mb4` ([introduced in MySQL 5.5.3](http://dev.mysql.com/doc/refman/5.5/en/charset-unicode-utf8mb4.html)) with fallback to `utf8` for older servers (`charset=utf8mb4,utf8`).

See also [Unicode Support](#unicode-support).

##### `checkConnLiveness`

```
Type:           bool
Valid Values:   true, false
Default:        true
```

On supported platforms connections retrieved from the connection pool are checked for liveness before using them. If the check fails, the respective connection is marked as bad and the query retried with another connection.
`checkConnLiveness=false` disables this liveness check of connections.

##### `collation`

```
Type:           string
Valid Values:   <name>
Default:        utf8mb4_general_ci
```

Sets the collation used for client-server interaction on connection. In contrast to `charset`, `collation` does not issue additional queries. If the specified collation is unavailable on the target server, the connection will fail.

A list of valid charsets for a server is retrievable with `SHOW COLLATION`.

The default collation (`utf8mb4_general_ci`) is supported from MySQL 5.5.  You should use an older collation (e.g. `utf8_general_ci`) for older MySQL.

Collations for charset "ucs2", "utf16", "utf16le", and "utf32" can not be used ([ref](https://dev.mysql.com/doc/refman/5.7/en/charset-connection.html#charset-connection-impermissible-client-charset)).

See also [Unicode Support](#unicode-support).

##### `clientFoundRows`

```
Type:           bool
Valid Values:   true, false
Default:        false
```

`clientFoundRows=true` causes an UPDATE to return the number of matching rows instead of the number of rows changed.

##### `columnsWithAlias`

```
Type:           bool
Valid Values:   true, false
Default:        false
```

When `columnsWithAlias` is true, calls to `sql.Rows.Columns()` will return the table alias and the column name separated by a dot. For example:

```
SELECT u.id FROM users as u
```

will return `u.id` instead of just `id` if `columnsWithAlias=true`.

##### `compress`

```
Type:           bool
Valid Values:   true, false
Default:        false
```

Toggles zlib compression. false by default.

##### `interpolateParams`

```
Type:           bool
Valid Values:   true, false
Default:        false
```

If `interpolateParams` is true, placeholders (`?`) in calls to `db.Query()` and `db.Exec()` are interpolated into a single query string with given parameters. This reduces the number of roundtrips, since the driver has to prepare a statement, execute it with given parameters and close the statement again with `interpolateParams=false`.

*This can not be used together with the multibyte encodings BIG5, CP932, GB2312, GBK or SJIS. These are rejected as they may [introduce a SQL injection vulnerability](http://stackoverflow.com/a/12118602/3430118)!*

##### `loc`

```
Type:           string
Valid Values:   <escaped name>
Default:        UTC
```

Sets the location for time.Time values (when using `parseTime=true`). *"Local"* sets the system's location. See [time.LoadLocation](https://golang.org/pkg/time/#LoadLocation) for details.

Note that this sets the location for time.Time values but does not change MySQL's [time_zone setting](https://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html). For that see the [time_zone system variable](#system-variables), which can also be set as a DSN parameter.

Please keep in mind, that param values must be [url.QueryEscape](https://golang.org/pkg/net/url/#QueryEscape)'ed. Alternatively you can manually replace the `/` with `%2F`. For example `US/Pacific` would be `loc=US%2FPacific`.

##### `timeTruncate`

```
Type:           duration
Default:        0
```

[Truncate time values](https://pkg.go.dev/time#Duration.Truncate) to the specified duration. The value must be a decimal number with a unit suffix (*"ms"*, *"s"*, *"m"*, *"h"*), such as *"30s"*, *"0.5m"* or *"1m30s"*.

##### `maxAllowedPacket`
```
Type:          decimal number
Default:       64*1024*1024
```

Max packet size allowed in bytes. The default value is 64 MiB and should be adjusted to match the server settings. `maxAllowedPacket=0` can be used to automatically fetch the `max_allowed_packet` variable from server *on every connection*.

##### `multiStatements`

```
Type:           bool
Valid Values:   true, false
Default:        false
```

Allow multiple statements in one query. This can be used to bach multiple queries. Use [Rows.NextResultSet()](https://pkg.go.dev/database/sql#Rows.NextResultSet) to get result of the second and subsequent queries.

When `multiStatements` is used, `?` parameters must only be used in the first statement. [interpolateParams](#interpolateparams) can be used to avoid this limitation unless prepared statement is used explicitly.

It's possible to access the last inserted ID and number of affected rows for multiple statements by using `sql.Conn.Raw()` and the `mysql.Result`. For example:

```go
conn, _ := db.Conn(ctx)
conn.Raw(func(conn any) error {
  ex := conn.(driver.Execer)
  res, err := ex.Exec(`
  UPDATE point SET x = 1 WHERE y = 2;
  UPDATE point SET x = 2 WHERE y = 3;
  `, nil)
  // Both slices have 2 elements.
  log.Print(res.(mysql.Result).AllRowsAffected())
  log.Print(res.(mysql.Result).AllLastInsertIds())
})
```

##### `parseTime`

```
Type:           bool
Valid Values:   true, false
Default:        false
```

`parseTime=true` changes the output type of `DATE` and `DATETIME` values to `time.Time` instead of `[]byte` / `string`
The date or datetime like `0000-00-00 00:00:00` is converted into zero value of `time.Time`.


##### `readTimeout`

```
Type:           duration
Default:        0
```

I/O read timeout. The value must be a decimal number with a unit suffix (*"ms"*, *"s"*, *"m"*, *"h"*), such as *"30s"*, *"0.5m"* or *"1m30s"*.

##### `rejectReadOnly`

```
Type:           bool
Valid Values:   true, false
Default:        false
```


`rejectReadOnly=true` causes the driver to reject read-only connections. This
is for a possible race condition during an automatic failover, where the mysql
client gets connected to a read-only replica after the failover.

Note that this should be a fairly rare case, as an automatic failover normally
happens when the primary is down, and the race condition shouldn't happen
unless it comes back up online as soon as the failover is kicked off. On the
other hand, when this happens, a MySQL application can get stuck on a
read-only connection until restarted. It is however fairly easy to reproduce,
for example, using a manual failover on AWS Aurora's MySQL-compatible cluster.

If you are not relying on read-only transactions to reject writes that aren't
supposed to happen, setting this on some MySQL providers (such as AWS Aurora)
is safer for failovers.

Note that ERROR 1290 can be returned for a `read-only` server and this option will
cause a retry for that error. However the same error number is used for some
other cases. You should ensure your application will never cause an ERROR 1290
except for `read-only` mode when enabling this option.


##### `serverPubKey`

```
Type:           string
Valid Values:   <name>
Default:        none
```

Server public keys can be registered with [`mysql.RegisterServerPubKey`](https://godoc.org/github.com/go-sql-driver/mysql#RegisterServerPubKey), which can then be used by the assigned name in the DSN.
Public keys are used to transmit encrypted data, e.g. for authentication.
If the server's public key is known, it should be set manually to avoid expensive and potentially insecure transmissions of the public key from the server to the client each time it is required.


##### `timeout`

```
Type:           duration
Default:        OS default
```

Timeout for establishing connections, aka dial timeout. The value must be a decimal number with a unit suffix (*"ms"*, *"s"*, *"m"*, *"h"*), such as *"30s"*, *"0.5m"* or *"1m30s"*.


##### `tls`

```
Type:           bool / string
Valid Values:   true, false, skip-verify, preferred, <name>
Default:        false
```

`tls=true` enables TLS / SSL encrypted connection to the server. Use `skip-verify` if you want to use a self-signed or invalid certificate (server side) or use `preferred` to use TLS only when advertised by the server. This is similar to `skip-verify`, but additionally allows a fallback to a connection which is not encrypted. Neither `skip-verify` nor `preferred` add any reliable security. You can use a custom TLS config after registering it with [`mysql.RegisterTLSConfig`](https://godoc.org/github.com/go-sql-driver/mysql#RegisterTLSConfig).


##### `writeTimeout`

```
Type:           duration
Default:        0
```

I/O write timeout. The value must be a decimal number with a unit suffix (*"ms"*, *"s"*, *"m"*, *"h"*), such as *"30s"*, *"0.5m"* or *"1m30s"*.

##### `connectionAttributes`

```
Type:           comma-delimited string of user-defined "key:value" pairs
Valid Values:   (<name1>:<value1>,<name2>:<value2>,...)
Default:        none
```

[Connection attributes](https://dev.mysql.com/doc/refman/8.0/en/performance-schema-connection-attribute-tables.html) are key-value pairs that application programs can pass to the server at connect time.

##### System Variables

Any other parameters are interpreted as system variables:
  * `<boolean_var>=<value>`: `SET <boolean_var>=<value>`
  * `<enum_var>=<value>`: `SET <enum_var>=<value>`
  * `<string_var>=%27<value>%27`: `SET <string_var>='<value>'`

Rules:
* The values for string variables must be quoted with `'`.
* The values must also be [url.QueryEscape](http://golang.org/pkg/net/url/#QueryEscape)'ed!
 (which implies values of string variables must be wrapped with `%27`).

Examples:
  * `autocommit=1`: `SET autocommit=1`
  * [`time_zone=%27Europe%2FParis%27`](https://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html): `SET time_zone='Europe/Paris'`
  * [`transaction_isolation=%27REPEATABLE-READ%27`](https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html#sysvar_transaction_isolation): `SET transaction_isolation='REPEATABLE-READ'`


#### Examples
```
user@unix(/path/to/socket)/dbname
```

```
root:pw@unix(/tmp/mysql.sock)/myDatabase?loc=Local
```

```
user:password@tcp(localhost:5555)/dbname?tls=skip-verify&autocommit=true
```

Treat warnings as errors by setting the system variable [`sql_mode`](https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html):
```
user:password@/dbname?sql_mode=TRADITIONAL
```

TCP via IPv6:
```
user:password@tcp([de:ad:be:ef::ca:fe]:80)/dbname?timeout=90s&collation=utf8mb4_unicode_ci
```

TCP on a remote host, e.g. Amazon RDS:
```
id:password@tcp(your-amazonaws-uri.com:3306)/dbname
```

Google Cloud SQL on App Engine:
```
user:password@unix(/cloudsql/project-id:region-name:instance-name)/dbname
```

TCP using default port (3306) on localhost:
```
user:password@tcp/dbname?charset=utf8mb4,utf8&sys_var=esc%40ped
```

Use the default protocol (tcp) and host (localhost:3306):
```
user:password@/dbname
```

No Database preselected:
```
user:password@/
```


### Connection pool and timeouts
The connection pool is managed by Go's database/sql package. For details on how to configure the size of the pool and how long connections stay in the pool see `*DB.SetMaxOpenConns`, `*DB.SetMaxIdleConns`, and `*DB.SetConnMaxLifetime` in the [database/sql documentation](https://golang.org/pkg/database/sql/). The read, write, and dial timeouts for each individual connection are configured with the DSN parameters [`readTimeout`](#readtimeout), [`writeTimeout`](#writetimeout), and [`timeout`](#timeout), respectively.

## `ColumnType` Support
This driver supports the [`ColumnType` interface](https://golang.org/pkg/database/sql/#ColumnType) introduced in Go 1.8, with the exception of [`ColumnType.Length()`](https://golang.org/pkg/database/sql/#ColumnType.Length), which is currently not supported. All Unsigned database type names will be returned `UNSIGNED ` with `INT`, `TINYINT`, `SMALLINT`, `MEDIUMINT`, `BIGINT`.

## `context.Context` Support
Go 1.8 added `database/sql` support for `context.Context`. This driver supports query timeouts and cancellation via contexts.
See [context support in the database/sql package](https://golang.org/doc/go1.8#database_sql) for more details.

> [!IMPORTANT]
> The `QueryContext`, `ExecContext`, etc. variants provided by `database/sql` will cause the connection to be closed if the provided context is cancelled or timed out before the result is received by the driver.


### `LOAD DATA LOCAL INFILE` support
For this feature you need direct access to the package. Therefore you must change the import path (no `_`):
```go
import "github.com/go-sql-driver/mysql"
```

Files must be explicitly allowed by registering them with `mysql.RegisterLocalFile(filepath)` (recommended) or the allowlist check must be deactivated by using the DSN parameter `allowAllFiles=true` ([*Might be insecure!*](https://dev.mysql.com/doc/refman/8.0/en/load-data.html#load-data-local)).

To use a `io.Reader` a handler function must be registered with `mysql.RegisterReaderHandler(name, handler)` which returns a `io.Reader` or `io.ReadCloser`. The Reader is available with the filepath `Reader::<name>` then. Choose different names for different handlers and `DeregisterReaderHandler` when you don't need it anymore.

See the [godoc of Go-MySQL-Driver](https://godoc.org/github.com/go-sql-driver/mysql "golang mysql driver documentation") for details.


### `time.Time` support
The default internal output type of MySQL `DATE` and `DATETIME` values is `[]byte` which allows you to scan the value into a `[]byte`, `string` or `sql.RawBytes` variable in your program.

However, many want to scan MySQL `DATE` and `DATETIME` values into `time.Time` variables, which is the logical equivalent in Go to `DATE` and `DATETIME` in MySQL. You can do that by changing the internal output type from `[]byte` to `time.Time` with the DSN parameter `parseTime=true`. You can set the default [`time.Time` location](https://golang.org/pkg/time/#Location) with the `loc` DSN parameter.

**Caution:** As of Go 1.1, this makes `time.Time` the only variable type you can scan `DATE` and `DATETIME` values into. This breaks for example [`sql.RawBytes` support](https://github.com/go-sql-driver/mysql/wiki/Examples#rawbytes).


### Unicode support
Since version 1.5 Go-MySQL-Driver automatically uses the collation ` utf8mb4_general_ci` by default.

Other charsets / collations can be set using the [`charset`](#charset) or [`collation`](#collation) DSN parameter.

- When only the `charset` is specified, the `SET NAMES <charset>` query is sent and the server's default collation is used.
- When both the `charset` and `collation` are specified, the `SET NAMES <charset> COLLATE <collation>` query is sent.
- When only the `collation` is specified, the collation is specified in the protocol handshake and the `SET NAMES` query is not sent. This can save one roundtrip, but note that the server may ignore the specified collation silently and use the server's default charset/collation instead.

See http://dev.mysql.com/doc/refman/8.0/en/charset-unicode.html for more details on MySQL's Unicode support.

## Testing / Development
To run the driver tests you may need to adjust the configuration. See the [Testing Wiki-Page](https://github.com/go-sql-driver/mysql/wiki/Testing "Testing") for details.

Go-MySQL-Driver is not feature-complete yet. Your help is very appreciated.
If you want to contribute, you can work on an [open issue](https://github.com/go-sql-driver/mysql/issues?state=open) or review a [pull request](https://github.com/go-sql-driver/mysql/pulls).

See the [Contribution Guidelines](https://github.com/go-sql-driver/mysql/blob/master/.github/CONTRIBUTING.md) for details.

---------------------------------------

## License
Go-MySQL-Driver is licensed under the [Mozilla Public License Version 2.0](https://raw.github.com/go-sql-driver/mysql/master/LICENSE)

Mozilla summarizes the license scope as follows:
> MPL: The copyleft applies to any files containing MPLed code.


That means:
  * You can **use** the **unchanged** source code both in private and commercially.
  * When distributing, you **must publish** the source code of any **changed files** licensed under the MPL 2.0 under a) the MPL 2.0 itself or b) a compatible license (e.g. GPL 3.0 or Apache License 2.0).
  * You **needn't publish** the source code of your library as long as the files licensed under the MPL 2.0 are **unchanged**.

Please read the [MPL 2.0 FAQ](https://www.mozilla.org/en-US/MPL/2.0/FAQ/) if you have further questions regarding the license.

You can read the full terms here: [LICENSE](https://raw.github.com/go-sql-driver/mysql/master/LICENSE).

![Go Gopher and MySQL Dolphin](https://raw.github.com/wiki/go-sql-driver/mysql/go-mysql-driver_m.jpg "Golang Gopher transporting the MySQL Dolphin in a wheelbarrow")


================================================
FILE: auth.go
================================================
// Go MySQL Driver - A MySQL-Driver for Go's database/sql package
//
// Copyright 2018 The Go-MySQL-Driver Authors. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.

package mysql

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha1"
	"crypto/sha256"
	"crypto/sha512"
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"sync"

	"filippo.io/edwards25519"
)

// server pub keys registry
var (
	serverPubKeyLock     sync.RWMutex
	serverPubKeyRegistry map[string]*rsa.PublicKey
)

// RegisterServerPubKey registers a server RSA public key which can be used to
// send data in a secure manner to the server without receiving the public key
// in a potentially insecure way from the server first.
// Registered keys can afterwards be used adding serverPubKey=<name> to the DSN.
//
// Note: The provided rsa.PublicKey instance is exclusively owned by the driver
// after registering it and may not be modified.
//
//	data, err := os.ReadFile("mykey.pem")
//	if err != nil {
//		log.Fatal(err)
//	}
//
//	block, _ := pem.Decode(data)
//	if block == nil || block.Type != "PUBLIC KEY" {
//		log.Fatal("failed to decode PEM block containing public key")
//	}
//
//	pub, err := x509.ParsePKIXPublicKey(block.Bytes)
//	if err != nil {
//		log.Fatal(err)
//	}
//
//	if rsaPubKey, ok := pub.(*rsa.PublicKey); ok {
//		mysql.RegisterServerPubKey("mykey", rsaPubKey)
//	} else {
//		log.Fatal("not a RSA public key")
//	}
func RegisterServerPubKey(name string, pubKey *rsa.PublicKey) {
	serverPubKeyLock.Lock()
	if serverPubKeyRegistry == nil {
		serverPubKeyRegistry = make(map[string]*rsa.PublicKey)
	}

	serverPubKeyRegistry[name] = pubKey
	serverPubKeyLock.Unlock()
}

// DeregisterServerPubKey removes the public key registered with the given name.
func DeregisterServerPubKey(name string) {
	serverPubKeyLock.Lock()
	if serverPubKeyRegistry != nil {
		delete(serverPubKeyRegistry, name)
	}
	serverPubKeyLock.Unlock()
}

func getServerPubKey(name string) (pubKey *rsa.PublicKey) {
	serverPubKeyLock.RLock()
	if v, ok := serverPubKeyRegistry[name]; ok {
		pubKey = v
	}
	serverPubKeyLock.RUnlock()
	return
}

// Hash password using pre 4.1 (old password) method
// https://github.com/atcurtis/mariadb/blob/master/mysys/my_rnd.c
type myRnd struct {
	seed1, seed2 uint32
}

const myRndMaxVal = 0x3FFFFFFF

// Pseudo random number generator
func newMyRnd(seed1, seed2 uint32) *myRnd {
	return &myRnd{
		seed1: seed1 % myRndMaxVal,
		seed2: seed2 % myRndMaxVal,
	}
}

// Tested to be equivalent to MariaDB's floating point variant
// http://play.golang.org/p/QHvhd4qved
// http://play.golang.org/p/RG0q4ElWDx
func (r *myRnd) NextByte() byte {
	r.seed1 = (r.seed1*3 + r.seed2) % myRndMaxVal
	r.seed2 = (r.seed1 + r.seed2 + 33) % myRndMaxVal

	return byte(uint64(r.seed1) * 31 / myRndMaxVal)
}

// Generate binary hash from byte string using insecure pre 4.1 method
func pwHash(password []byte) (result [2]uint32) {
	var add uint32 = 7
	var tmp uint32

	result[0] = 1345345333
	result[1] = 0x12345671

	for _, c := range password {
		// skip spaces and tabs in password
		if c == ' ' || c == '\t' {
			continue
		}

		tmp = uint32(c)
		result[0] ^= (((result[0] & 63) + add) * tmp) + (result[0] << 8)
		result[1] += (result[1] << 8) ^ result[0]
		add += tmp
	}

	// Remove sign bit (1<<31)-1)
	result[0] &= 0x7FFFFFFF
	result[1] &= 0x7FFFFFFF

	return
}

// Hash password using insecure pre 4.1 method
func scrambleOldPassword(scramble []byte, password string) []byte {
	scramble = scramble[:8]

	hashPw := pwHash([]byte(password))
	hashSc := pwHash(scramble)

	r := newMyRnd(hashPw[0]^hashSc[0], hashPw[1]^hashSc[1])

	var out [8]byte
	for i := range out {
		out[i] = r.NextByte() + 64
	}

	mask := r.NextByte()
	for i := range out {
		out[i] ^= mask
	}

	return out[:]
}

// Hash password using 4.1+ method (SHA1)
func scramblePassword(scramble []byte, password string) []byte {
	if len(password) == 0 {
		return nil
	}

	// stage1Hash = SHA1(password)
	crypt := sha1.New()
	crypt.Write([]byte(password))
	stage1 := crypt.Sum(nil)

	// scrambleHash = SHA1(scramble + SHA1(stage1Hash))
	// inner Hash
	crypt.Reset()
	crypt.Write(stage1)
	hash := crypt.Sum(nil)

	// outer Hash
	crypt.Reset()
	crypt.Write(scramble)
	crypt.Write(hash)
	scramble = crypt.Sum(nil)

	// token = scrambleHash XOR stage1Hash
	for i := range scramble {
		scramble[i] ^= stage1[i]
	}
	return scramble
}

// Hash password using MySQL 8+ method (SHA256)
func scrambleSHA256Password(scramble []byte, password string) []byte {
	if len(password) == 0 {
		return nil
	}

	// XOR(SHA256(password), SHA256(SHA256(SHA256(password)), scramble))

	crypt := sha256.New()
	crypt.Write([]byte(password))
	message1 := crypt.Sum(nil)

	crypt.Reset()
	crypt.Write(message1)
	message1Hash := crypt.Sum(nil)

	crypt.Reset()
	crypt.Write(message1Hash)
	crypt.Write(scramble)
	message2 := crypt.Sum(nil)

	for i := range message1 {
		message1[i] ^= message2[i]
	}

	return message1
}

func encryptPassword(password string, seed []byte, pub *rsa.PublicKey) ([]byte, error) {
	plain := make([]byte, len(password)+1)
	copy(plain, password)
	for i := range plain {
		j := i % len(seed)
		plain[i] ^= seed[j]
	}
	sha1 := sha1.New()
	return rsa.EncryptOAEP(sha1, rand.Reader, pub, plain, nil)
}

// authEd25519 does ed25519 authentication used by MariaDB.
func authEd25519(scramble []byte, password string) ([]byte, error) {
	// Derived from https://github.com/MariaDB/server/blob/d8e6bb00888b1f82c031938f4c8ac5d97f6874c3/plugin/auth_ed25519/ref10/sign.c
	// Code style is from https://cs.opensource.google/go/go/+/refs/tags/go1.21.5:src/crypto/ed25519/ed25519.go;l=207
	h := sha512.Sum512([]byte(password))

	s, err := edwards25519.NewScalar().SetBytesWithClamping(h[:32])
	if err != nil {
		return nil, err
	}
	A := (&edwards25519.Point{}).ScalarBaseMult(s)

	mh := sha512.New()
	mh.Write(h[32:])
	mh.Write(scramble)
	messageDigest := mh.Sum(nil)
	r, err := edwards25519.NewScalar().SetUniformBytes(messageDigest)
	if err != nil {
		return nil, err
	}

	R := (&edwards25519.Point{}).ScalarBaseMult(r)

	kh := sha512.New()
	kh.Write(R.Bytes())
	kh.Write(A.Bytes())
	kh.Write(scramble)
	hramDigest := kh.Sum(nil)
	k, err := edwards25519.NewScalar().SetUniformBytes(hramDigest)
	if err != nil {
		return nil, err
	}

	S := k.MultiplyAdd(k, s, r)

	return append(R.Bytes(), S.Bytes()...), nil
}

func (mc *mysqlConn) sendEncryptedPassword(seed []byte, pub *rsa.PublicKey) error {
	enc, err := encryptPassword(mc.cfg.Passwd, seed, pub)
	if err != nil {
		return err
	}
	return mc.writeAuthSwitchPacket(enc)
}

func (mc *mysqlConn) auth(authData []byte, plugin string) ([]byte, error) {
	switch plugin {
	case "caching_sha2_password":
		authResp := scrambleSHA256Password(authData, mc.cfg.Passwd)
		return authResp, nil

	case "mysql_old_password":
		if !mc.cfg.AllowOldPasswords {
			return nil, ErrOldPassword
		}
		if len(mc.cfg.Passwd) == 0 {
			return nil, nil
		}
		// Note: there are edge cases where this should work but doesn't;
		// this is currently "wontfix":
		// https://github.com/go-sql-driver/mysql/issues/184
		authResp := append(scrambleOldPassword(authData[:8], mc.cfg.Passwd), 0)
		return authResp, nil

	case "mysql_clear_password":
		if !mc.cfg.AllowCleartextPasswords {
			return nil, ErrCleartextPassword
		}
		// http://dev.mysql.com/doc/refman/5.7/en/cleartext-authentication-plugin.html
		// http://dev.mysql.com/doc/refman/5.7/en/pam-authentication-plugin.html
		return append([]byte(mc.cfg.Passwd), 0), nil

	case "mysql_native_password":
		if !mc.cfg.AllowNativePasswords {
			return nil, ErrNativePassword
		}
		// https://dev.mysql.com/doc/dev/mysql-server/8.4.5/page_protocol_connection_phase_authentication_methods_native_password_authentication.html
		// Native password authentication only need and will need 20-byte challenge.
		authResp := scramblePassword(authData[:20], mc.cfg.Passwd)
		return authResp, nil

	case "sha256_password":
		if len(mc.cfg.Passwd) == 0 {
			return []byte{0}, nil
		}
		// unlike caching_sha2_password, sha256_password does not accept
		// cleartext password on unix transport.
		if mc.cfg.TLS != nil {
			// write cleartext auth packet
			return append([]byte(mc.cfg.Passwd), 0), nil
		}

		pubKey := mc.cfg.pubKey
		if pubKey == nil {
			// request public key from server
			return []byte{1}, nil
		}

		// encrypted password
		enc, err := encryptPassword(mc.cfg.Passwd, authData, pubKey)
		return enc, err

	case "client_ed25519":
		if len(authData) != 32 {
			return nil, ErrMalformPkt
		}
		return authEd25519(authData, mc.cfg.Passwd)

	default:
		mc.log("unknown auth plugin:", plugin)
		return nil, ErrUnknownPlugin
	}
}

func (mc *mysqlConn) handleAuthResult(oldAuthData []byte, plugin string) error {
	// Read Result Packet
	authData, newPlugin, err := mc.readAuthResult()
	if err != nil {
		return err
	}

	// handle auth plugin switch, if requested
	if newPlugin != "" {
		// If CLIENT_PLUGIN_AUTH capability is not supported, no new cipher is
		// sent and we have to keep using the cipher sent in the init packet.
		if authData == nil {
			authData = oldAuthData
		} else {
			// copy data from read buffer to owned slice
			copy(oldAuthData, authData)
		}

		plugin = newPlugin

		authResp, err := mc.auth(authData, plugin)
		if err != nil {
			return err
		}
		if err = mc.writeAuthSwitchPacket(authResp); err != nil {
			return err
		}

		// Read Result Packet
		authData, newPlugin, err = mc.readAuthResult()
		if err != nil {
			return err
		}

		// Do not allow to change the auth plugin more than once
		if newPlugin != "" {
			return ErrMalformPkt
		}
	}

	switch plugin {

	// https://dev.mysql.com/blog-archive/preparing-your-community-connector-for-mysql-8-part-2-sha256/
	case "caching_sha2_password":
		switch len(authData) {
		case 0:
			return nil // auth successful
		case 1:
			switch authData[0] {
			case cachingSha2PasswordFastAuthSuccess:
				if err = mc.resultUnchanged().readResultOK(); err == nil {
					return nil // auth successful
				}

			case cachingSha2PasswordPerformFullAuthentication:
				if mc.cfg.TLS != nil || mc.cfg.Net == "unix" {
					// write cleartext auth packet
					err = mc.writeAuthSwitchPacket(append([]byte(mc.cfg.Passwd), 0))
					if err != nil {
						return err
					}
				} else {
					pubKey := mc.cfg.pubKey
					if pubKey == nil {
						// request public key from server
						data, err := mc.buf.takeSmallBuffer(4 + 1)
						if err != nil {
							return err
						}
						data[4] = cachingSha2PasswordRequestPublicKey
						err = mc.writePacket(data)
						if err != nil {
							return err
						}

						if data, err = mc.readPacket(); err != nil {
							return err
						}

						if data[0] != iAuthMoreData {
							return fmt.Errorf("unexpected resp from server for caching_sha2_password, perform full authentication")
						}

						// parse public key
						block, rest := pem.Decode(data[1:])
						if block == nil {
							return fmt.Errorf("no pem data found, data: %s", rest)
						}
						pkix, err := x509.ParsePKIXPublicKey(block.Bytes)
						if err != nil {
							return err
						}
						pubKey = pkix.(*rsa.PublicKey)
					}

					// send encrypted password
					err = mc.sendEncryptedPassword(oldAuthData, pubKey)
					if err != nil {
						return err
					}
				}
				return mc.resultUnchanged().readResultOK()

			default:
				return ErrMalformPkt
			}
		default:
			return ErrMalformPkt
		}

	case "sha256_password":
		switch len(authData) {
		case 0:
			return nil // auth successful
		default:
			block, _ := pem.Decode(authData)
			if block == nil {
				return fmt.Errorf("no Pem data found, data: %s", authData)
			}

			pub, err := x509.ParsePKIXPublicKey(block.Bytes)
			if err != nil {
				return err
			}

			// send encrypted password
			err = mc.sendEncryptedPassword(oldAuthData, pub.(*rsa.PublicKey))
			if err != nil {
				return err
			}
			return mc.resultUnchanged().readResultOK()
		}

	default:
		return nil // auth successful
	}

	return err
}


================================================
FILE: auth_test.go
================================================
// Go MySQL Driver - A MySQL-Driver for Go's database/sql package
//
// Copyright 2018 The Go-MySQL-Driver Authors. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.

package mysql

import (
	"bytes"
	"crypto/rsa"
	"crypto/tls"
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"testing"
)

var testPubKey = []byte("-----BEGIN PUBLIC KEY-----\n" +
	"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAol0Z8G8U+25Btxk/g/fm\n" +
	"UAW/wEKjQCTjkibDE4B+qkuWeiumg6miIRhtilU6m9BFmLQSy1ltYQuu4k17A4tQ\n" +
	"rIPpOQYZges/qsDFkZh3wyK5jL5WEFVdOasf6wsfszExnPmcZS4axxoYJfiuilrN\n" +
	"hnwinBAqfi3S0sw5MpSI4Zl1AbOrHG4zDI62Gti2PKiMGyYDZTS9xPrBLbN95Kby\n" +
	"FFclQLEzA9RJcS1nHFsWtRgHjGPhhjCQxEm9NQ1nePFhCfBfApyfH1VM2VCOQum6\n" +
	"Ci9bMuHWjTjckC84mzF99kOxOWVU7mwS6gnJqBzpuz8t3zq8/iQ2y7QrmZV+jTJP\n" +
	"WQIDAQAB\n" +
	"-----END PUBLIC KEY-----\n")

var testPubKeyRSA *rsa.PublicKey

func init() {
	block, _ := pem.Decode(testPubKey)
	pub, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		panic(err)
	}
	testPubKeyRSA = pub.(*rsa.PublicKey)
}

func TestScrambleOldPass(t *testing.T) {
	scramble := []byte{9, 8, 7, 6, 5, 4, 3, 2}
	vectors := []struct {
		pass string
		out  string
	}{
		{" pass", "47575c5a435b4251"},
		{"pass ", "47575c5a435b4251"},
		{"123\t456", "575c47505b5b5559"},
		{"C0mpl!ca ted#PASS123", "5d5d554849584a45"},
	}
	for _, tuple := range vectors {
		ours := scrambleOldPassword(scramble, tuple.pass)
		if tuple.out != fmt.Sprintf("%x", ours) {
			t.Errorf("Failed old password %q", tuple.pass)
		}
	}
}

func TestScrambleSHA256Pass(t *testing.T) {
	scramble := []byte{10, 47, 74, 111, 75, 73, 34, 48, 88, 76, 114, 74, 37, 13, 3, 80, 82, 2, 23, 21}
	vectors := []struct {
		pass string
		out  string
	}{
		{"secret", "f490e76f66d9d86665ce54d98c78d0acfe2fb0b08b423da807144873d30b312c"},
		{"secret2", "abc3934a012cf342e876071c8ee202de51785b430258a7a0138bc79c4d800bc6"},
	}
	for _, tuple := range vectors {
		ours := scrambleSHA256Password(scramble, tuple.pass)
		if tuple.out != fmt.Sprintf("%x", ours) {
			t.Errorf("Failed SHA256 password %q", tuple.pass)
		}
	}
}

func TestAuthFastCachingSHA256PasswordCached(t *testing.T) {
	conn, mc := newRWMockConn(1)
	mc.cfg.User = "root"
	mc.cfg.Passwd = "secret"

	authData := []byte{90, 105, 74, 126, 30, 48, 37, 56, 3, 23, 115, 127, 69,
		22, 41, 84, 32, 123, 43, 118}
	plugin := "caching_sha2_password"

	// Send Client Authentication Packet
	authResp, err := mc.auth(authData, plugin)
	if err != nil {
		t.Fatal(err)
	}
	err = mc.writeHandshakeResponsePacket(authResp, plugin)
	if err != nil {
		t.Fatal(err)
	}

	// check written auth response
	authRespStart := 4 + 4 + 4 + 1 + 23 + len(mc.cfg.User) + 1
	authRespEnd := authRespStart + 1 + len(authResp)
	writtenAuthRespLen := conn.written[authRespStart]
	writtenAuthResp := conn.written[authRespStart+1 : authRespEnd]
	expectedAuthResp := []byte{102, 32, 5, 35, 143, 161, 140, 241, 171, 232, 56,
		139, 43, 14, 107, 196, 249, 170, 147, 60, 220, 204, 120, 178, 214, 15,
		184, 150, 26, 61, 57, 235}
	if writtenAuthRespLen != 32 || !bytes.Equal(writtenAuthResp, expectedAuthResp) {
		t.Fatalf("unexpected written auth response (%d bytes): %v", writtenAuthRespLen, writtenAuthResp)
	}
	conn.written = nil

	// auth response
	conn.data = []byte{
		2, 0, 0, 2, 1, 3, // Fast Auth Success
		7, 0, 0, 3, 0, 0, 0, 2, 0, 0, 0, // OK
	}
	conn.maxReads = 1

	// Handle response to auth packet
	if err := mc.handleAuthResult(authData, plugin); err != nil {
		t.Errorf("got error: %v", err)
	}
}

func TestAuthFastCachingSHA256PasswordEmpty(t *testing.T) {
	conn, mc := newRWMockConn(1)
	mc.cfg.User = "root"
	mc.cfg.Passwd = ""

	authData := []byte{90, 105, 74, 126, 30, 48, 37, 56, 3, 23, 115, 127, 69,
		22, 41, 84, 32, 123, 43, 118}
	plugin := "caching_sha2_password"

	// Send Client Authentication Packet
	authResp, err := mc.auth(authData, plugin)
	if err != nil {
		t.Fatal(err)
	}
	err = mc.writeHandshakeResponsePacket(authResp, plugin)
	if err != nil {
		t.Fatal(err)
	}

	// check written auth response
	authRespStart := 4 + 4 + 4 + 1 + 23 + len(mc.cfg.User) + 1
	authRespEnd := authRespStart + 1 + len(authResp)
	writtenAuthRespLen := conn.written[authRespStart]
	writtenAuthResp := conn.written[authRespStart+1 : authRespEnd]
	if writtenAuthRespLen != 0 {
		t.Fatalf("unexpected written auth response (%d bytes): %v",
			writtenAuthRespLen, writtenAuthResp)
	}
	conn.written = nil

	// auth response
	conn.data = []byte{
		7, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, // OK
	}
	conn.maxReads = 1

	// Handle response to auth packet
	if err := mc.handleAuthResult(authData, plugin); err != nil {
		t.Errorf("got error: %v", err)
	}
}

func TestAuthFastCachingSHA256PasswordFullRSA(t *testing.T) {
	conn, mc := newRWMockConn(1)
	mc.cfg.User = "root"
	mc.cfg.Passwd = "secret"

	authData := []byte{6, 81, 96, 114, 14, 42, 50, 30, 76, 47, 1, 95, 126, 81,
		62, 94, 83, 80, 52, 85}
	plugin := "caching_sha2_password"

	// Send Client Authentication Packet
	authResp, err := mc.auth(authData, plugin)
	if err != nil {
		t.Fatal(err)
	}
	err = mc.writeHandshakeResponsePacket(authResp, plugin)
	if err != nil {
		t.Fatal(err)
	}

	// check written auth response
	authRespStart := 4 + 4 + 4 + 1 + 23 + len(mc.cfg.User) + 1
	authRespEnd := authRespStart + 1 + len(authResp)
	writtenAuthRespLen := conn.written[authRespStart]
	writtenAuthResp := conn.written[authRespStart+1 : authRespEnd]
	expectedAuthResp := []byte{171, 201, 138, 146, 89, 159, 11, 170, 0, 67, 165,
		49, 175, 94, 218, 68, 177, 109, 110, 86, 34, 33, 44, 190, 67, 240, 70,
		110, 40, 139, 124, 41}
	if writtenAuthRespLen != 32 || !bytes.Equal(writtenAuthResp, expectedAuthResp) {
		t.Fatalf("unexpected written auth response (%d bytes): %v", writtenAuthRespLen, writtenAuthResp)
	}
	conn.written = nil

	// auth response
	conn.data = []byte{
		2, 0, 0, 2, 1, 4, // Perform Full Authentication
	}
	conn.queuedReplies = [][]byte{
		// pub key response
		append([]byte{byte(1 + len(testPubKey)), 1, 0, 4, 1}, testPubKey...),

		// OK
		{7, 0, 0, 6, 0, 0, 0, 2, 0, 0, 0},
	}
	conn.maxReads = 3

	// Handle response to auth packet
	if err := mc.handleAuthResult(authData, plugin); err != nil {
		t.Errorf("got error: %v", err)
	}

	if !bytes.HasPrefix(conn.written, []byte{1, 0, 0, 3, 2, 0, 1, 0, 5}) {
		t.Errorf("unexpected written data: %v", conn.written)
	}
}

func TestAuthFastCachingSHA256PasswordFullRSAWithKey(t *testing.T) {
	conn, mc := newRWMockConn(1)
	mc.cfg.User = "root"
	mc.cfg.Passwd = "secret"
	mc.cfg.pubKey = testPubKeyRSA

	authData := []byte{6, 81, 96, 114, 14, 42, 50, 30, 76, 47, 1, 95, 126, 81,
		62, 94, 83, 80, 52, 85}
	plugin := "caching_sha2_password"

	// Send Client Authentication Packet
	authResp, err := mc.auth(authData, plugin)
	if err != nil {
		t.Fatal(err)
	}
	err = mc.writeHandshakeResponsePacket(authResp, plugin)
	if err != nil {
		t.Fatal(err)
	}

	// check written auth response
	authRespStart := 4 + 4 + 4 + 1 + 23 + len(mc.cfg.User) + 1
	authRespEnd := authRespStart + 1 + len(authResp)
	writtenAuthRespLen := conn.written[authRespStart]
	writtenAuthResp := conn.written[authRespStart+1 : authRespEnd]
	expectedAuthResp := []byte{171, 201, 138, 146, 89, 159, 11, 170, 0, 67, 165,
		49, 175, 94, 218, 68, 177, 109, 110, 86, 34, 33, 44, 190, 67, 240, 70,
		110, 40, 139, 124, 41}
	if writtenAuthRespLen != 32 || !bytes.Equal(writtenAuthResp, expectedAuthResp) {
		t.Fatalf("unexpected written auth response (%d bytes): %v", writtenAuthRespLen, writtenAuthResp)
	}
	conn.written = nil

	// auth response
	conn.data = []byte{
		2, 0, 0, 2, 1, 4, // Perform Full Authentication
	}
	conn.queuedReplies = [][]byte{
		// OK
		{7, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0},
	}
	conn.maxReads = 2

	// Handle response to auth packet
	if err := mc.handleAuthResult(authData, plugin); err != nil {
		t.Errorf("got error: %v", err)
	}

	if !bytes.HasPrefix(conn.written, []byte{0, 1, 0, 3}) {
		t.Errorf("unexpected written data: %v", conn.written)
	}
}

func TestAuthFastCachingSHA256PasswordFullSecure(t *testing.T) {
	conn, mc := newRWMockConn(1)
	mc.cfg.User = "root"
	mc.cfg.Passwd = "secret"

	authData := []byte{6, 81, 96, 114, 14, 42, 50, 30, 76, 47, 1, 95, 126, 81,
		62, 94, 83, 80, 52, 85}
	plugin := "caching_sha2_password"

	// Send Client Authentication Packet
	authResp, err := mc.auth(authData, plugin)
	if err != nil {
		t.Fatal(err)
	}
	err = mc.writeHandshakeResponsePacket(authResp, plugin)
	if err != nil {
		t.Fatal(err)
	}

	// Hack to make the caching_sha2_password plugin believe that the connection
	// is secure
	mc.cfg.TLS = &tls.Config{InsecureSkipVerify: true}

	// check written auth response
	authRespStart := 4 + 4 + 4 + 1 + 23 + len(mc.cfg.User) + 1
	authRespEnd := authRespStart + 1 + len(authResp)
	writtenAuthRespLen := conn.written[authRespStart]
	writtenAuthResp := conn.written[authRespStart+1 : authRespEnd]
	expectedAuthResp := []byte{171, 201, 138, 146, 89, 159, 11, 170, 0, 67, 165,
		49, 175, 94, 218, 68, 177, 109, 110, 86, 34, 33, 44, 190, 67, 240, 70,
		110, 40, 139, 124, 41}
	if writtenAuthRespLen != 32 || !bytes.Equal(writtenAuthResp, expectedAuthResp) {
		t.Fatalf("unexpected written auth response (%d bytes): %v", writtenAuthRespLen, writtenAuthResp)
	}
	conn.written = nil

	// auth response
	conn.data = []byte{
		2, 0, 0, 2, 1, 4, // Perform Full Authentication
	}
	conn.queuedReplies = [][]byte{
		// OK
		{7, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0},
	}
	conn.maxReads = 3

	// Handle response to auth packet
	if err := mc.handleAuthResult(authData, plugin); err != nil {
		t.Errorf("got error: %v", err)
	}

	if !bytes.Equal(conn.written, []byte{7, 0, 0, 3, 115, 101, 99, 114, 101, 116, 0}) {
		t.Errorf("unexpected written data: %v", conn.written)
	}
}

func TestAuthFastCleartextPasswordNotAllowed(t *testing.T) {
	_, mc := newRWMockConn(1)
	mc.cfg.User = "root"
	mc.cfg.Passwd = "secret"

	authData := []byte{70, 114, 92, 94, 1, 38, 11, 116, 63, 114, 23, 101, 126,
		103, 26, 95, 81, 17, 24, 21}
	plugin := "mysql_clear_password"

	// Send Client Authentication Packet
	_, err := mc.auth(authData, plugin)
	if err != ErrCleartextPassword {
		t.Errorf("expected ErrCleartextPassword, got %v", err)
	}
}

func TestAuthFastCleartextPassword(t *testing.T) {
	conn, mc := newRWMockConn(1)
	mc.cfg.User = "root"
	mc.cfg.Passwd = "secret"
	mc.cfg.AllowCleartextPasswords = true

	authData := []byte{70, 114, 92, 94, 1, 38, 11, 116, 63, 114, 23, 101, 126,
		103, 26, 95, 81, 17, 24, 21}
	plugin := "mysql_clear_password"

	// Send Client Authentication Packet
	authResp, err := mc.auth(authData, plugin)
	if err != nil {
		t.Fatal(err)
	}
	err = mc.writeHandshakeResponsePacket(authResp, plugin)
	if err != nil {
		t.Fatal(err)
	}

	// check written auth response
	authRespStart := 4 + 4 + 4 + 1 + 23 + len(mc.cfg.User) + 1
	authRespEnd := authRespStart + 1 + len(authResp)
	writtenAuthRespLen := conn.written[authRespStart]
	writtenAuthResp := conn.written[authRespStart+1 : authRespEnd]
	expectedAuthResp := []byte{115, 101, 99, 114, 101, 116, 0}
	if writtenAuthRespLen != 7 || !bytes.Equal(writtenAuthResp, expectedAuthResp) {
		t.Fatalf("unexpected written auth response (%d bytes): %v", writtenAuthRespLen, writtenAuthResp)
	}
	conn.written = nil

	// auth response
	conn.data = []byte{
		7, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, // OK
	}
	conn.maxReads = 1

	// Handle response to auth packet
	if err := mc.handleAuthResult(authData, plugin); err != nil {
		t.Errorf("got error: %v", err)
	}
}

func TestAuthFastCleartextPasswordEmpty(t *testing.T) {
	conn, mc := newRWMockConn(1)
	mc.cfg.User = "root"
	mc.cfg.Passwd = ""
	mc.cfg.AllowCleartextPasswords = true

	authData := []byte{70, 114, 92, 94, 1, 38, 11, 116, 63, 114, 23, 101, 126,
		103, 26, 95, 81, 17, 24, 21}
	plugin := "mysql_clear_password"

	// Send Client Authentication Packet
	authResp, err := mc.auth(authData, plugin)
	if err != nil {
		t.Fatal(err)
	}
	err = mc.writeHandshakeResponsePacket(authResp, plugin)
	if err != nil {
		t.Fatal(err)
	}

	// check written auth response
	authRespStart := 4 + 4 + 4 + 1 + 23 + len(mc.cfg.User) + 1
	authRespEnd := authRespStart + 1 + len(authResp)
	writtenAuthRespLen := conn.written[authRespStart]
	writtenAuthResp := conn.written[authRespStart+1 : authRespEnd]
	expectedAuthResp := []byte{0}
	if writtenAuthRespLen != 1 || !bytes.Equal(writtenAuthResp, expectedAuthResp) {
		t.Fatalf("unexpected written auth response (%d bytes): %v", writtenAuthRespLen, writtenAuthResp)
	}
	conn.written = nil

	// auth response
	conn.data = []byte{
		7, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, // OK
	}
	conn.maxReads = 1

	// Handle response to auth packet
	if err := mc.handleAuthResult(authData, plugin); err != nil {
		t.Errorf("got error: %v", err)
	}
}

func TestAuthFastNativePasswordNotAllowed(t *testing.T) {
	_, mc := newRWMockConn(1)
	mc.cfg.User = "root"
	mc.cfg.Passwd = "secret"
	mc.cfg.AllowNativePasswords = false

	authData := []byte{70, 114, 92, 94, 1, 38, 11, 116, 63, 114, 23, 101, 126,
		103, 26, 95, 81, 17, 24, 21}
	plugin := "mysql_native_password"

	// Send Client Authentication Packet
	_, err := mc.auth(authData, plugin)
	if err != ErrNativePassword {
		t.Errorf("expected ErrNativePassword, got %v", err)
	}
}

func TestAuthFastNativePassword(t *testing.T) {
	conn, mc := newRWMockConn(1)
	mc.cfg.User = "root"
	mc.cfg.Passwd = "secret"

	authData := []byte{70, 114, 92, 94, 1, 38, 11, 116, 63, 114, 23, 101, 126,
		103, 26, 95, 81, 17, 24, 21}
	plugin := "mysql_native_password"

	// Send Client Authentication Packet
	authResp, err := mc.auth(authData, plugin)
	if err != nil {
		t.Fatal(err)
	}
	err = mc.writeHandshakeResponsePacket(authResp, plugin)
	if err != nil {
		t.Fatal(err)
	}

	// check written auth response
	authRespStart := 4 + 4 + 4 + 1 + 23 + len(mc.cfg.User) + 1
	authRespEnd := authRespStart + 1 + len(authResp)
	writtenAuthRespLen := conn.written[authRespStart]
	writtenAuthResp := conn.written[authRespStart+1 : authRespEnd]
	expectedAuthResp := []byte{53, 177, 140, 159, 251, 189, 127, 53, 109, 252,
		172, 50, 211, 192, 240, 164, 26, 48, 207, 45}
	if writtenAuthRespLen != 20 || !bytes.Equal(writtenAuthResp, expectedAuthResp) {
		t.Fatalf("unexpected written auth response (%d bytes): %v", writtenAuthRespLen, writtenAuthResp)
	}
	conn.written = nil

	// auth response
	conn.data = []byte{
		7, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, // OK
	}
	conn.maxReads = 1

	// Handle response to auth packet
	if err := mc.handleAuthResult(authData, plugin); err != nil {
		t.Errorf("got error: %v", err)
	}
}

func TestAuthFastNativePasswordEmpty(t *testing.T) {
	conn, mc := newRWMockConn(1)
	mc.cfg.User = "root"
	mc.cfg.Passwd = ""

	authData := []byte{70, 114, 92, 94, 1, 38, 11, 116, 63, 114, 23, 101, 126,
		103, 26, 95, 81, 17, 24, 21}
	plugin := "mysql_native_password"

	// Send Client Authentication Packet
	authResp, err := mc.auth(authData, plugin)
	if err != nil {
		t.Fatal(err)
	}
	err = mc.writeHandshakeResponsePacket(authResp, plugin)
	if err != nil {
		t.Fatal(err)
	}

	// check written auth response
	authRespStart := 4 + 4 + 4 + 1 + 23 + len(mc.cfg.User) + 1
	authRespEnd := authRespStart + 1 + len(authResp)
	writtenAuthRespLen := conn.written[authRespStart]
	writtenAuthResp := conn.written[authRespStart+1 : authRespEnd]
	if writtenAuthRespLen != 0 {
		t.Fatalf("unexpected written auth response (%d bytes): %v",
			writtenAuthRespLen, writtenAuthResp)
	}
	conn.written = nil

	// auth response
	conn.data = []byte{
		7, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, // OK
	}
	conn.maxReads = 1

	// Handle response to auth packet
	if err := mc.handleAuthResult(authData, plugin); err != nil {
		t.Errorf("got error: %v", err)
	}
}

func TestAuthFastSHA256PasswordEmpty(t *testing.T) {
	conn, mc := newRWMockConn(1)
	mc.cfg.User = "root"
	mc.cfg.Passwd = ""

	authData := []byte{6, 81, 96, 114, 14, 42, 50, 30, 76, 47, 1, 95, 126, 81,
		62, 94, 83, 80, 52, 85}
	plugin := "sha256_password"

	// Send Client Authentication Packet
	authResp, err := mc.auth(authData, plugin)
	if err != nil {
		t.Fatal(err)
	}
	err = mc.writeHandshakeResponsePacket(authResp, plugin)
	if err != nil {
		t.Fatal(err)
	}

	// check written auth response
	authRespStart := 4 + 4 + 4 + 1 + 23 + len(mc.cfg.User) + 1
	authRespEnd := authRespStart + 1 + len(authResp)
	writtenAuthRespLen := conn.written[authRespStart]
	writtenAuthResp := conn.written[authRespStart+1 : authRespEnd]
	expectedAuthResp := []byte{0}
	if writtenAuthRespLen != 1 || !bytes.Equal(writtenAuthResp, expectedAuthResp) {
		t.Fatalf("unexpected written auth response (%d bytes): %v", writtenAuthRespLen, writtenAuthResp)
	}
	conn.written = nil

	// auth response (pub key response)
	conn.data = append([]byte{byte(1 + len(testPubKey)), 1, 0, 2, 1}, testPubKey...)
	conn.queuedReplies = [][]byte{
		// OK
		{7, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0},
	}
	conn.maxReads = 2

	// Handle response to auth packet
	if err := mc.handleAuthResult(authData, plugin); err != nil {
		t.Errorf("got error: %v", err)
	}

	if !bytes.HasPrefix(conn.written, []byte{0, 1, 0, 3}) {
		t.Errorf("unexpected written data: %v", conn.written)
	}
}

func TestAuthFastSHA256PasswordRSA(t *testing.T) {
	conn, mc := newRWMockConn(1)
	mc.cfg.User = "root"
	mc.cfg.Passwd = "secret"

	authData := []byte{6, 81, 96, 114, 14, 42, 50, 30, 76, 47, 1, 95, 126, 81,
		62, 94, 83, 80, 52, 85}
	plugin := "sha256_password"

	// Send Client Authentication Packet
	authResp, err := mc.auth(authData, plugin)
	if err != nil {
		t.Fatal(err)
	}
	err = mc.writeHandshakeResponsePacket(authResp, plugin)
	if err != nil {
		t.Fatal(err)
	}

	// check written auth response
	authRespStart := 4 + 4 + 4 + 1 + 23 + len(mc.cfg.User) + 1
	authRespEnd := authRespStart + 1 + len(authResp)
	writtenAuthRespLen := conn.written[authRespStart]
	writtenAuthResp := conn.written[authRespStart+1 : authRespEnd]
	expectedAuthResp := []byte{1}
	if writtenAuthRespLen != 1 || !bytes.Equal(writtenAuthResp, expectedAuthResp) {
		t.Fatalf("unexpected written auth response (%d bytes): %v", writtenAuthRespLen, writtenAuthResp)
	}
	conn.written = nil

	// auth response (pub key response)
	conn.data = append([]byte{byte(1 + len(testPubKey)), 1, 0, 2, 1}, testPubKey...)
	conn.queuedReplies = [][]byte{
		// OK
		{7, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0},
	}
	conn.maxReads = 2

	// Handle response to auth packet
	if err := mc.handleAuthResult(authData, plugin); err != nil {
		t.Errorf("got error: %v", err)
	}

	if !bytes.HasPrefix(conn.written, []byte{0, 1, 0, 3}) {
		t.Errorf("unexpected written data: %v", conn.written)
	}
}

func TestAuthFastSHA256PasswordRSAWithKey(t *testing.T) {
	conn, mc := newRWMockConn(1)
	mc.cfg.User = "root"
	mc.cfg.Passwd = "secret"
	mc.cfg.pubKey = testPubKeyRSA

	authData := []byte{6, 81, 96, 114, 14, 42, 50, 30, 76, 47, 1, 95, 126, 81,
		62, 94, 83, 80, 52, 85}
	plugin := "sha256_password"

	// Send Client Authentication Packet
	authResp, err := mc.auth(authData, plugin)
	if err != nil {
		t.Fatal(err)
	}
	err = mc.writeHandshakeResponsePacket(authResp, plugin)
	if err != nil {
		t.Fatal(err)
	}

	// auth response (OK)
	conn.data = []byte{7, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0}
	conn.maxReads = 1

	// Handle response to auth packet
	if err := mc.handleAuthResult(authData, plugin); err != nil {
		t.Errorf("got error: %v", err)
	}
}

func TestAuthFastSHA256PasswordSecure(t *testing.T) {
	conn, mc := newRWMockConn(1)
	mc.cfg.User = "root"
	mc.cfg.Passwd = "secret"

	// hack to make the caching_sha2_password plugin believe that the connection
	// is secure
	mc.cfg.TLS = &tls.Config{InsecureSkipVerify: true}

	authData := []byte{6, 81, 96, 114, 14, 42, 50, 30, 76, 47, 1, 95, 126, 81,
		62, 94, 83, 80, 52, 85}
	plugin := "sha256_password"

	// send Client Authentication Packet
	authResp, err := mc.auth(authData, plugin)
	if err != nil {
		t.Fatal(err)
	}

	// unset TLS config to prevent the actual establishment of a TLS wrapper
	mc.cfg.TLS = nil

	err = mc.writeHandshakeResponsePacket(authResp, plugin)
	if err != nil {
		t.Fatal(err)
	}

	// check written auth response
	authRespStart := 4 + 4 + 4 + 1 + 23 + len(mc.cfg.User) + 1
	authRespEnd := authRespStart + 1 + len(authResp)
	writtenAuthRespLen := conn.written[authRespStart]
	writtenAuthResp := conn.written[authRespStart+1 : authRespEnd]
	expectedAuthResp := []byte{115, 101, 99, 114, 101, 116, 0}
	if writtenAuthRespLen != 7 || !bytes.Equal(writtenAuthResp, expectedAuthResp) {
		t.Fatalf("unexpected written auth response (%d bytes): %v", writtenAuthRespLen, writtenAuthResp)
	}
	conn.written = nil

	// auth response (OK)
	conn.data = []byte{7, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0}
	conn.maxReads = 1

	// Handle response to auth packet
	if err := mc.handleAuthResult(authData, plugin); err != nil {
		t.Errorf("got error: %v", err)
	}

	if !bytes.Equal(conn.written, []byte{}) {
		t.Errorf("unexpected written data: %v", conn.written)
	}
}

func TestAuthSwitchCachingSHA256PasswordCached(t *testing.T) {
	conn, mc := newRWMockConn(2)
	mc.cfg.Passwd = "secret"

	// auth switch request
	conn.data = []byte{44, 0, 0, 2, 254, 99, 97, 99, 104, 105, 110, 103, 95,
		115, 104, 97, 50, 95, 112, 97, 115, 115, 119, 111, 114, 100, 0, 101,
		11, 26, 18, 94, 97, 22, 72, 2, 46, 70, 106, 29, 55, 45, 94, 76, 90, 84,
		50, 0}

	// auth response
	conn.queuedReplies = [][]byte{
		{7, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0}, // OK
	}
	conn.maxReads = 3

	authData := []byte{123, 87, 15, 84, 20, 58, 37, 121, 91, 117, 51, 24, 19,
		47, 43, 9, 41, 112, 67, 110}
	plugin := "mysql_native_password"

	if err := mc.handleAuthResult(authData, plugin); err != nil {
		t.Errorf("got error: %v", err)
	}

	expectedReply := []byte{
		// 1. Packet: Hash
		32, 0, 0, 3, 219, 72, 64, 97, 56, 197, 167, 203, 64, 236, 168, 80, 223,
		56, 103, 217, 196, 176, 124, 60, 253, 41, 195, 10, 205, 190, 177, 206, 63,
		118, 211, 69,
	}
	if !bytes.Equal(conn.written, expectedReply) {
		t.Errorf("got unexpected data: %v", conn.written)
	}
}

func TestAuthSwitchCachingSHA256PasswordEmpty(t *testing.T) {
	conn, mc := newRWMockConn(2)
	mc.cfg.Passwd = ""

	// auth switch request
	conn.data = []byte{44, 0, 0, 2, 254, 99, 97, 99, 104, 105, 110, 103, 95,
		115, 104, 97, 50, 95, 112, 97, 115, 115, 119, 111, 114, 100, 0, 101,
		11, 26, 18, 94, 97, 22, 72, 2, 46, 70, 106, 29, 55, 45, 94, 76, 90, 84,
		50, 0}

	// auth response
	conn.queuedReplies = [][]byte{{7, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0}}
	conn.maxReads = 2

	authData := []byte{123, 87, 15, 84, 20, 58, 37, 121, 91, 117, 51, 24, 19,
		47, 43, 9, 41, 112, 67, 110}
	plugin := "mysql_native_password"

	if err := mc.handleAuthResult(authData, plugin); err != nil {
		t.Errorf("got error: %v", err)
	}

	expectedReply := []byte{0, 0, 0, 3}
	if !bytes.Equal(conn.written, expectedReply) {
		t.Errorf("got unexpected data: %v", conn.written)
	}
}

func TestAuthSwitchCachingSHA256PasswordFullRSA(t *testing.T) {
	conn, mc := newRWMockConn(2)
	mc.cfg.Passwd = "secret"

	// auth switch request
	conn.data = []byte{44, 0, 0, 2, 254, 99, 97, 99, 104, 105, 110, 103, 95,
		115, 104, 97, 50, 95, 112, 97, 115, 115, 119, 111, 114, 100, 0, 101,
		11, 26, 18, 94, 97, 22, 72, 2, 46, 70, 106, 29, 55, 45, 94, 76, 90, 84,
		50, 0}

	conn.queuedReplies = [][]byte{
		// Perform Full Authentication
		{2, 0, 0, 4, 1, 4},

		// Pub Key Response
		append([]byte{byte(1 + len(testPubKey)), 1, 0, 6, 1}, testPubKey...),

		// OK
		{7, 0, 0, 8, 0, 0, 0, 2, 0, 0, 0},
	}
	conn.maxReads = 4

	authData := []byte{123, 87, 15, 84, 20, 58, 37, 121, 91, 117, 51, 24, 19,
		47, 43, 9, 41, 112, 67, 110}
	plugin := "mysql_native_password"

	if err := mc.handleAuthResult(authData, plugin); err != nil {
		t.Errorf("got error: %v", err)
	}

	expectedReplyPrefix := []byte{
		// 1. Packet: Hash
		32, 0, 0, 3, 219, 72, 64, 97, 56, 197, 167, 203, 64, 236, 168, 80, 223,
		56, 103, 217, 196, 176, 124, 60, 253, 41, 195, 10, 205, 190, 177, 206, 63,
		118, 211, 69,

		// 2. Packet: Pub Key Request
		1, 0, 0, 5, 2,

		// 3. Packet: Encrypted Password
		0, 1, 0, 7, // [changing bytes]
	}
	if !bytes.HasPrefix(conn.written, expectedReplyPrefix) {
		t.Errorf("got unexpected data: %v", conn.written)
	}
}

func TestAuthSwitchCachingSHA256PasswordFullRSAWithKey(t *testing.T) {
	conn, mc := newRWMockConn(2)
	mc.cfg.Passwd = "secret"
	mc.cfg.pubKey = testPubKeyRSA

	// auth switch request
	conn.data = []byte{44, 0, 0, 2, 254, 99, 97, 99, 104, 105, 110, 103, 95,
		115, 104, 97, 50, 95, 112, 97, 115, 115, 119, 111, 114, 100, 0, 101,
		11, 26, 18, 94, 97, 22, 72, 2, 46, 70, 106, 29, 55, 45, 94, 76, 90, 84,
		50, 0}

	conn.queuedReplies = [][]byte{
		// Perform Full Authentication
		{2, 0, 0, 4, 1, 4},

		// OK
		{7, 0, 0, 6, 0, 0, 0, 2, 0, 0, 0},
	}
	conn.maxReads = 3

	authData := []byte{123, 87, 15, 84, 20, 58, 37, 121, 91, 117, 51, 24, 19,
		47, 43, 9, 41, 112, 67, 110}
	plugin := "mysql_native_password"

	if err := mc.handleAuthResult(authData, plugin); err != nil {
		t.Errorf("got error: %v", err)
	}

	expectedReplyPrefix := []byte{
		// 1. Packet: Hash
		32, 0, 0, 3, 219, 72, 64, 97, 56, 197, 167, 203, 64, 236, 168, 80, 223,
		56, 103, 217, 196, 176, 124, 60, 253, 41, 195, 10, 205, 190, 177, 206, 63,
		118, 211, 69,

		// 2. Packet: Encrypted Password
		0, 1, 0, 5, // [changing bytes]
	}
	if !bytes.HasPrefix(conn.written, expectedReplyPrefix) {
		t.Errorf("got unexpected data: %v", conn.written)
	}
}

func TestAuthSwitchCachingSHA256PasswordFullSecure(t *testing.T) {
	conn, mc := newRWMockConn(2)
	mc.cfg.Passwd = "secret"

	// Hack to make the caching_sha2_password plugin believe that the connection
	// is secure
	mc.cfg.TLS = &tls.Config{InsecureSkipVerify: true}

	// auth switch request
	conn.data = []byte{44, 0, 0, 2, 254, 99, 97, 99, 104, 105, 110, 103, 95,
		115, 104, 97, 50, 95, 112, 97, 115, 115, 119, 111, 114, 100, 0, 101,
		11, 26, 18, 94, 97, 22, 72, 2, 46, 70, 106, 29, 55, 45, 94, 76, 90, 84,
		50, 0}

	// auth response
	conn.queuedReplies = [][]byte{
		{2, 0, 0, 4, 1, 4},                // Perform Full Authentication
		{7, 0, 0, 6, 0, 0, 0, 2, 0, 0, 0}, // OK
	}
	conn.maxReads = 3

	authData := []byte{123, 87, 15, 84, 20, 58, 37, 121, 91, 117, 51, 24, 19,
		47, 43, 9, 41, 112, 67, 110}
	plugin := "mysql_native_password"

	if err := mc.handleAuthResult(authData, plugin); err != nil {
		t.Errorf("got error: %v", err)
	}

	expectedReply := []byte{
		// 1. Packet: Hash
		32, 0, 0, 3, 219, 72, 64, 97, 56, 197, 167, 203, 64, 236, 168, 80, 223,
		56, 103, 217, 196, 176, 124, 60, 253, 41, 195, 10, 205, 190, 177, 206, 63,
		118, 211, 69,

		// 2. Packet: Cleartext password
		7, 0, 0, 5, 115, 101, 99, 114, 101, 116, 0,
	}
	if !bytes.Equal(conn.written, expectedReply) {
		t.Errorf("got unexpected data: %v", conn.written)
	}
}

func TestAuthSwitchCleartextPasswordNotAllowed(t *testing.T) {
	conn, mc := newRWMockConn(2)

	conn.data = []byte{22, 0, 0, 2, 254, 109, 121, 115, 113, 108, 95, 99, 108,
		101, 97, 114, 95, 112, 97, 115, 115, 119, 111, 114, 100, 0}
	conn.maxReads = 1
	authData := []byte{123, 87, 15, 84, 20, 58, 37, 121, 91, 117, 51, 24, 19,
		47, 43, 9, 41, 112, 67, 110}
	plugin := "mysql_native_password"
	err := mc.handleAuthResult(authData, plugin)
	if err != ErrCleartextPassword {
		t.Errorf("expected ErrCleartextPassword, got %v", err)
	}
}

func TestAuthSwitchCleartextPassword(t *testing.T) {
	conn, mc := newRWMockConn(2)
	mc.cfg.AllowCleartextPasswords = true
	mc.cfg.Passwd = "secret"

	// auth switch request
	conn.data = []byte{22, 0, 0, 2, 254, 109, 121, 115, 113, 108, 95, 99, 108,
		101, 97, 114, 95, 112, 97, 115, 115, 119, 111, 114, 100, 0}

	// auth response
	conn.queuedReplies = [][]byte{{7, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0}}
	conn.maxReads = 2

	authData := []byte{123, 87, 15, 84, 20, 58, 37, 121, 91, 117, 51, 24, 19,
		47, 43, 9, 41, 112, 67, 110}
	plugin := "mysql_native_password"

	if err := mc.handleAuthResult(authData, plugin); err != nil {
		t.Errorf("got error: %v", err)
	}

	expectedReply := []byte{7, 0, 0, 3, 115, 101, 99, 114, 101, 116, 0}
	if !bytes.Equal(conn.written, expectedReply) {
		t.Errorf("got unexpected data: %v", conn.written)
	}
}

func TestAuthSwitchCleartextPasswordEmpty(t *testing.T) {
	conn, mc := newRWMockConn(2)
	mc.cfg.AllowCleartextPasswords = true
	mc.cfg.Passwd = ""

	// auth switch request
	conn.data = []byte{22, 0, 0, 2, 254, 109, 121, 115, 113, 108, 95, 99, 108,
		101, 97, 114, 95, 112, 97, 115, 115, 119, 111, 114, 100, 0}

	// auth response
	conn.queuedReplies = [][]byte{{7, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0}}
	conn.maxReads = 2

	authData := []byte{123, 87, 15, 84, 20, 58, 37, 121, 91, 117, 51, 24, 19,
		47, 43, 9, 41, 112, 67, 110}
	plugin := "mysql_native_password"

	if err := mc.handleAuthResult(authData, plugin); err != nil {
		t.Errorf("got error: %v", err)
	}

	expectedReply := []byte{1, 0, 0, 3, 0}
	if !bytes.Equal(conn.written, expectedReply) {
		t.Errorf("got unexpected data: %v", conn.written)
	}
}

func TestAuthSwitchNativePasswordNotAllowed(t *testing.T) {
	conn, mc := newRWMockConn(2)
	mc.cfg.AllowNativePasswords = false

	conn.data = []byte{44, 0, 0, 2, 254, 109, 121, 115, 113, 108, 95, 110, 97,
		116, 105, 118, 101, 95, 112, 97, 115, 115, 119, 111, 114, 100, 0, 96,
		71, 63, 8, 1, 58, 75, 12, 69, 95, 66, 60, 117, 31, 48, 31, 89, 39, 55,
		31, 0}
	conn.maxReads = 1
	authData := []byte{96, 71, 63, 8, 1, 58, 75, 12, 69, 95, 66, 60, 117, 31,
		48, 31, 89, 39, 55, 31}
	plugin := "caching_sha2_password"
	err := mc.handleAuthResult(authData, plugin)
	if err != ErrNativePassword {
		t.Errorf("expected ErrNativePassword, got %v", err)
	}
}

func TestAuthSwitchNativePassword(t *testing.T) {
	conn, mc := newRWMockConn(2)
	mc.cfg.AllowNativePasswords = true
	mc.cfg.Passwd = "secret"

	// auth switch request
	conn.data = []byte{44, 0, 0, 2, 254, 109, 121, 115, 113, 108, 95, 110, 97,
		116, 105, 118, 101, 95, 112, 97, 115, 115, 119, 111, 114, 100, 0, 96,
		71, 63, 8, 1, 58, 75, 12, 69, 95, 66, 60, 117, 31, 48, 31, 89, 39, 55,
		31, 0}

	// auth response
	conn.queuedReplies = [][]byte{{7, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0}}
	conn.maxReads = 2

	authData := []byte{96, 71, 63, 8, 1, 58, 75, 12, 69, 95, 66, 60, 117, 31,
		48, 31, 89, 39, 55, 31}
	plugin := "caching_sha2_password"

	if err := mc.handleAuthResult(authData, plugin); err != nil {
		t.Errorf("got error: %v", err)
	}

	expectedReply := []byte{20, 0, 0, 3, 202, 41, 195, 164, 34, 226, 49, 103,
		21, 211, 167, 199, 227, 116, 8, 48, 57, 71, 149, 146}
	if !bytes.Equal(conn.written, expectedReply) {
		t.Errorf("got unexpected data: %v", conn.written)
	}
}

func TestAuthSwitchNativePasswordEmpty(t *testing.T) {
	conn, mc := newRWMockConn(2)
	mc.cfg.AllowNativePasswords = true
	mc.cfg.Passwd = ""

	// auth switch request
	conn.data = []byte{44, 0, 0, 2, 254, 109, 121, 115, 113, 108, 95, 110, 97,
		116, 105, 118, 101, 95, 112, 97, 115, 115, 119, 111, 114, 100, 0, 96,
		71, 63, 8, 1, 58, 75, 12, 69, 95, 66, 60, 117, 31, 48, 31, 89, 39, 55,
		31, 0}

	// auth response
	conn.queuedReplies = [][]byte{{7, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0}}
	conn.maxReads = 2

	authData := []byte{96, 71, 63, 8, 1, 58, 75, 12, 69, 95, 66, 60, 117, 31,
		48, 31, 89, 39, 55, 31}
	plugin := "caching_sha2_password"

	if err := mc.handleAuthResult(authData, plugin); err != nil {
		t.Errorf("got error: %v", err)
	}

	expectedReply := []byte{0, 0, 0, 3}
	if !bytes.Equal(conn.written, expectedReply) {
		t.Errorf("got unexpected data: %v", conn.written)
	}
}

func TestAuthSwitchOldPasswordNotAllowed(t *testing.T) {
	conn, mc := newRWMockConn(2)

	conn.data = []byte{41, 0, 0, 2, 254, 109, 121, 115, 113, 108, 95, 111, 108,
		100, 95, 112, 97, 115, 115, 119, 111, 114, 100, 0, 95, 84, 103, 43, 61,
		49, 123, 61, 91, 50, 40, 113, 35, 84, 96, 101, 92, 123, 121, 107, 0}
	conn.maxReads = 1
	authData := []byte{95, 84, 103, 43, 61, 49, 123, 61, 91, 50, 40, 113, 35,
		84, 96, 101, 92, 123, 121, 107}
	plugin := "mysql_native_password"
	err := mc.handleAuthResult(authData, plugin)
	if err != ErrOldPassword {
		t.Errorf("expected ErrOldPassword, got %v", err)
	}
}

// Same to TestAuthSwitchOldPasswordNotAllowed, but use OldAuthSwitch request.
func TestOldAuthSwitchNotAllowed(t *testing.T) {
	conn, mc := newRWMockConn(2)

	// OldAuthSwitch request
	conn.data = []byte{1, 0, 0, 2, 0xfe}
	conn.maxReads = 1
	authData := []byte{95, 84, 103, 43, 61, 49, 123, 61, 91, 50, 40, 113, 35,
		84, 96, 101, 92, 123, 121, 107}
	plugin := "mysql_native_password"
	err := mc.handleAuthResult(authData, plugin)
	if err != ErrOldPassword {
		t.Errorf("expected ErrOldPassword, got %v", err)
	}
}

func TestAuthSwitchOldPassword(t *testing.T) {
	conn, mc := newRWMockConn(2)
	mc.cfg.AllowOldPasswords = true
	mc.cfg.Passwd = "secret"

	// auth switch request
	conn.data = []byte{41, 0, 0, 2, 254, 109, 121, 115, 113, 108, 95, 111, 108,
		100, 95, 112, 97, 115, 115, 119, 111, 114, 100, 0, 95, 84, 103, 43, 61,
		49, 123, 61, 91, 50, 40, 113, 35, 84, 96, 101, 92, 123, 121, 107, 0}

	// auth response
	conn.queuedReplies = [][]byte{{8, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0, 0}}
	conn.maxReads = 2

	authData := []byte{95, 84, 103, 43, 61, 49, 123, 61, 91, 50, 40, 113, 35,
		84, 96, 101, 92, 123, 121, 107}
	plugin := "mysql_native_password"

	if err := mc.handleAuthResult(authData, plugin); err != nil {
		t.Errorf("got error: %v", err)
	}

	expectedReply := []byte{9, 0, 0, 3, 86, 83, 83, 79, 74, 78, 65, 66, 0}
	if !bytes.Equal(conn.written, expectedReply) {
		t.Errorf("got unexpected data: %v", conn.written)
	}
}

// Same to TestAuthSwitchOldPassword, but use OldAuthSwitch request.
func TestOldAuthSwitch(t *testing.T) {
	conn, mc := newRWMockConn(2)
	mc.cfg.AllowOldPasswords = true
	mc.cfg.Passwd = "secret"

	// OldAuthSwitch request
	conn.data = []byte{1, 0, 0, 2, 0xfe}

	// auth response
	conn.queuedReplies = [][]byte{{8, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0, 0}}
	conn.maxReads = 2

	authData := []byte{95, 84, 103, 43, 61, 49, 123, 61, 91, 50, 40, 113, 35,
		84, 96, 101, 92, 123, 121, 107}
	plugin := "mysql_native_password"

	if err := mc.handleAuthResult(authData, plugin); err != nil {
		t.Errorf("got error: %v", err)
	}

	expectedReply := []byte{9, 0, 0, 3, 86, 83, 83, 79, 74, 78, 65, 66, 0}
	if !bytes.Equal(conn.written, expectedReply) {
		t.Errorf("got unexpected data: %v", conn.written)
	}
}
func TestAuthSwitchOldPasswordEmpty(t *testing.T) {
	conn, mc := newRWMockConn(2)
	mc.cfg.AllowOldPasswords = true
	mc.cfg.Passwd = ""

	// auth switch request
	conn.data = []byte{41, 0, 0, 2, 254, 109, 121, 115, 113, 108, 95, 111, 108,
		100, 95, 112, 97, 115, 115, 119, 111, 114, 100, 0, 95, 84, 103, 43, 61,
		49, 123, 61, 91, 50, 40, 113, 35, 84, 96, 101, 92, 123, 121, 107, 0}

	// auth response
	conn.queuedReplies = [][]byte{{8, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0, 0}}
	conn.maxReads = 2

	authData := []byte{95, 84, 103, 43, 61, 49, 123, 61, 91, 50, 40, 113, 35,
		84, 96, 101, 92, 123, 121, 107}
	plugin := "mysql_native_password"

	if err := mc.handleAuthResult(authData, plugin); err != nil {
		t.Errorf("got error: %v", err)
	}

	expectedReply := []byte{0, 0, 0, 3}
	if !bytes.Equal(conn.written, expectedReply) {
		t.Errorf("got unexpected data: %v", conn.written)
	}
}

// Same to TestAuthSwitchOldPasswordEmpty, but use OldAuthSwitch request.
func TestOldAuthSwitchPasswordEmpty(t *testing.T) {
	conn, mc := newRWMockConn(2)
	mc.cfg.AllowOldPasswords = true
	mc.cfg.Passwd = ""

	// OldAuthSwitch request.
	conn.data = []byte{1, 0, 0, 2, 0xfe}

	// auth response
	conn.queuedReplies = [][]byte{{8, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0, 0}}
	conn.maxReads = 2

	authData := []byte{95, 84, 103, 43, 61, 49, 123, 61, 91, 50, 40, 113, 35,
		84, 96, 101, 92, 123, 121, 107}
	plugin := "mysql_native_password"

	if err := mc.handleAuthResult(authData, plugin); err != nil {
		t.Errorf("got error: %v", err)
	}

	expectedReply := []byte{0, 0, 0, 3}
	if !bytes.Equal(conn.written, expectedReply) {
		t.Errorf("got unexpected data: %v", conn.written)
	}
}

func TestAuthSwitchSHA256PasswordEmpty(t *testing.T) {
	conn, mc := newRWMockConn(2)
	mc.cfg.Passwd = ""

	// auth switch request
	conn.data = []byte{38, 0, 0, 2, 254, 115, 104, 97, 50, 53, 54, 95, 112, 97,
		115, 115, 119, 111, 114, 100, 0, 78, 82, 62, 40, 100, 1, 59, 31, 44, 69,
		33, 112, 8, 81, 51, 96, 65, 82, 16, 114, 0}

	conn.queuedReplies = [][]byte{
		// OK
		{7, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0},
	}
	conn.maxReads = 3

	authData := []byte{123, 87, 15, 84, 20, 58, 37, 121, 91, 117, 51, 24, 19,
		47, 43, 9, 41, 112, 67, 110}
	plugin := "mysql_native_password"

	if err := mc.handleAuthResult(authData, plugin); err != nil {
		t.Errorf("got error: %v", err)
	}

	expectedReplyPrefix := []byte{
		// 1. Packet: Empty Password
		1, 0, 0, 3, 0,
	}
	if !bytes.HasPrefix(conn.written, expectedReplyPrefix) {
		t.Errorf("got unexpected data: %v", conn.written)
	}
}

func TestAuthSwitchSHA256PasswordRSA(t *testing.T) {
	conn, mc := newRWMockConn(2)
	mc.cfg.Passwd = "secret"

	// auth switch request
	conn.data = []byte{38, 0, 0, 2, 254, 115, 104, 97, 50, 53, 54, 95, 112, 97,
		115, 115, 119, 111, 114, 100, 0, 78, 82, 62, 40, 100, 1, 59, 31, 44, 69,
		33, 112, 8, 81, 51, 96, 65, 82, 16, 114, 0}

	conn.queuedReplies = [][]byte{
		// Pub Key Response
		append([]byte{byte(1 + len(testPubKey)), 1, 0, 4, 1}, testPubKey...),

		// OK
		{7, 0, 0, 6, 0, 0, 0, 2, 0, 0, 0},
	}
	conn.maxReads = 3

	authData := []byte{123, 87, 15, 84, 20, 58, 37, 121, 91, 117, 51, 24, 19,
		47, 43, 9, 41, 112, 67, 110}
	plugin := "mysql_native_password"

	if err := mc.handleAuthResult(authData, plugin); err != nil {
		t.Errorf("got error: %v", err)
	}

	expectedReplyPrefix := []byte{
		// 1. Packet: Pub Key Request
		1, 0, 0, 3, 1,

		// 2. Packet: Encrypted Password
		0, 1, 0, 5, // [changing bytes]
	}
	if !bytes.HasPrefix(conn.written, expectedReplyPrefix) {
		t.Errorf("got unexpected data: %v", conn.written)
	}
}

func TestAuthSwitchSHA256PasswordRSAWithKey(t *testing.T) {
	conn, mc := newRWMockConn(2)
	mc.cfg.Passwd = "secret"
	mc.cfg.pubKey = testPubKeyRSA

	// auth switch request
	conn.data = []byte{38, 0, 0, 2, 254, 115, 104, 97, 50, 53, 54, 95, 112, 97,
		115, 115, 119, 111, 114, 100, 0, 78, 82, 62, 40, 100, 1, 59, 31, 44, 69,
		33, 112, 8, 81, 51, 96, 65, 82, 16, 114, 0}

	conn.queuedReplies = [][]byte{
		// OK
		{7, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0},
	}
	conn.maxReads = 2

	authData := []byte{123, 87, 15, 84, 20, 58, 37, 121, 91, 117, 51, 24, 19,
		47, 43, 9, 41, 112, 67, 110}
	plugin := "mysql_native_password"

	if err := mc.handleAuthResult(authData, plugin); err != nil {
		t.Errorf("got error: %v", err)
	}

	expectedReplyPrefix := []byte{
		// 1. Packet: Encrypted Password
		0, 1, 0, 3, // [changing bytes]
	}
	if !bytes.HasPrefix(conn.written, expectedReplyPrefix) {
		t.Errorf("got unexpected data: %v", conn.written)
	}
}

func TestAuthSwitchSHA256PasswordSecure(t *testing.T) {
	conn, mc := newRWMockConn(2)
	mc.cfg.Passwd = "secret"

	// Hack to make the caching_sha2_password plugin believe that the connection
	// is secure
	mc.cfg.TLS = &tls.Config{InsecureSkipVerify: true}

	// auth switch request
	conn.data = []byte{38, 0, 0, 2, 254, 115, 104, 97, 50, 53, 54, 95, 112, 97,
		115, 115, 119, 111, 114, 100, 0, 78, 82, 62, 40, 100, 1, 59, 31, 44, 69,
		33, 112, 8, 81, 51, 96, 65, 82, 16, 114, 0}

	conn.queuedReplies = [][]byte{
		// OK
		{7, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0},
	}
	conn.maxReads = 2

	authData := []byte{123, 87, 15, 84, 20, 58, 37, 121, 91, 117, 51, 24, 19,
		47, 43, 9, 41, 112, 67, 110}
	plugin := "mysql_native_password"

	if err := mc.handleAuthResult(authData, plugin); err != nil {
		t.Errorf("got error: %v", err)
	}

	expectedReplyPrefix := []byte{
		// 1. Packet: Cleartext Password
		7, 0, 0, 3, 115, 101, 99, 114, 101, 116, 0,
	}
	if !bytes.Equal(conn.written, expectedReplyPrefix) {
		t.Errorf("got unexpected data: %v", conn.written)
	}
}

// Derived from https://github.com/MariaDB/server/blob/6b2287fff23fbdc362499501c562f01d0d2db52e/plugin/auth_ed25519/ed25519-t.c
func TestEd25519Auth(t *testing.T) {
	conn, mc := newRWMockConn(1)
	mc.cfg.User = "root"
	mc.cfg.Passwd = "foobar"

	authData := []byte("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")
	plugin := "client_ed25519"

	// Send Client Authentication Packet
	authResp, err := mc.auth(authData, plugin)
	if err != nil {
		t.Fatal(err)
	}
	err = mc.writeHandshakeResponsePacket(authResp, plugin)
	if err != nil {
		t.Fatal(err)
	}

	// check written auth response
	authRespStart := 4 + 4 + 4 + 1 + 23 + len(mc.cfg.User) + 1
	authRespEnd := authRespStart + 1 + len(authResp)
	writtenAuthRespLen := conn.written[authRespStart]
	writtenAuthResp := conn.written[authRespStart+1 : authRespEnd]
	expectedAuthResp := []byte{
		232, 61, 201, 63, 67, 63, 51, 53, 86, 73, 238, 35, 170, 117, 146,
		214, 26, 17, 35, 9, 8, 132, 245, 141, 48, 99, 66, 58, 36, 228, 48,
		84, 115, 254, 187, 168, 88, 162, 249, 57, 35, 85, 79, 238, 167, 106,
		68, 117, 56, 135, 171, 47, 20, 14, 133, 79, 15, 229, 124, 160, 176,
		100, 138, 14,
	}
	if writtenAuthRespLen != 64 {
		t.Fatalf("expected 64 bytes from client, got %d", writtenAuthRespLen)
	}
	if !bytes.Equal(writtenAuthResp, expectedAuthResp) {
		t.Fatalf("auth response did not match expected value:\n%v\n%v", writtenAuthResp, expectedAuthResp)
	}
	conn.written = nil

	// auth response
	conn.data = []byte{
		7, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, // OK
	}
	conn.maxReads = 1

	// Handle response to auth packet
	if err := mc.handleAuthResult(authData, plugin); err != nil {
		t.Errorf("got error: %v", err)
	}
}


================================================
FILE: benchmark_test.go
================================================
// Go MySQL Driver - A MySQL-Driver for Go's database/sql package
//
// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.

package mysql

import (
	"bytes"
	"context"
	"database/sql"
	"database/sql/driver"
	"fmt"
	"math"
	"runtime"
	"strings"
	"sync"
	"sync/atomic"
	"testing"
	"time"
)

type TB testing.B

func (tb *TB) check(err error) {
	if err != nil {
		tb.Fatal(err)
	}
}

func (tb *TB) checkDB(db *sql.DB, err error) *sql.DB {
	tb.check(err)
	return db
}

func (tb *TB) checkRows(rows *sql.Rows, err error) *sql.Rows {
	tb.check(err)
	return rows
}

func (tb *TB) checkStmt(stmt *sql.Stmt, err error) *sql.Stmt {
	tb.check(err)
	return stmt
}

func initDB(b *testing.B, compress bool, queries ...string) *sql.DB {
	tb := (*TB)(b)
	comprStr := ""
	if compress {
		comprStr = "&compress=1"
	}
	db := tb.checkDB(sql.Open(driverNameTest, dsn+comprStr))
	for _, query := range queries {
		if _, err := db.Exec(query); err != nil {
			b.Fatalf("error on %q: %v", query, err)
		}
	}
	return db
}

const concurrencyLevel = 10

func BenchmarkQuery(b *testing.B) {
	benchmarkQuery(b, false)
}

func BenchmarkQueryCompressed(b *testing.B) {
	benchmarkQuery(b, true)
}

func benchmarkQuery(b *testing.B, compr bool) {
	tb := (*TB)(b)
	b.ReportAllocs()
	db := initDB(b, compr,
		"DROP TABLE IF EXISTS foo",
		"CREATE TABLE foo (id INT PRIMARY KEY, val CHAR(50))",
		`INSERT INTO foo VALUES (1, "one")`,
		`INSERT INTO foo VALUES (2, "two")`,
	)
	db.SetMaxIdleConns(concurrencyLevel)
	defer db.Close()

	stmt := tb.checkStmt(db.Prepare("SELECT val FROM foo WHERE id=?"))
	defer stmt.Close()

	remain := int64(b.N)
	var wg sync.WaitGroup
	wg.Add(concurrencyLevel)
	defer wg.Wait()
	b.StartTimer()

	for i := 0; i < concurrencyLevel; i++ {
		go func() {
			for {
				if atomic.AddInt64(&remain, -1) < 0 {
					wg.Done()
					return
				}

				var got string
				tb.check(stmt.QueryRow(1).Scan(&got))
				if got != "one" {
					b.Errorf("query = %q; want one", got)
					wg.Done()
					return
				}
			}
		}()
	}
}

func BenchmarkExec(b *testing.B) {
	tb := (*TB)(b)
	db := tb.checkDB(sql.Open(driverNameTest, dsn))
	db.SetMaxIdleConns(concurrencyLevel)
	defer db.Close()

	stmt := tb.checkStmt(db.Prepare("DO 1"))
	defer stmt.Close()

	remain := int64(b.N)
	var wg sync.WaitGroup
	wg.Add(concurrencyLevel)
	defer wg.Wait()

	b.ReportAllocs()
	b.ResetTimer()

	for i := 0; i < concurrencyLevel; i++ {
		go func() {
			for {
				if atomic.AddInt64(&remain, -1) < 0 {
					wg.Done()
					return
				}

				if _, err := stmt.Exec(); err != nil {
					b.Logf("stmt.Exec failed: %v", err)
					b.Fail()
				}
			}
		}()
	}
}

// data, but no db writes
var roundtripSample []byte

func initRoundtripBenchmarks() ([]byte, int, int) {
	if roundtripSample == nil {
		roundtripSample = []byte(strings.Repeat("0123456789abcdef", 1024*1024))
	}
	return roundtripSample, 16, len(roundtripSample)
}

func BenchmarkRoundtripTxt(b *testing.B) {
	sample, min, max := initRoundtripBenchmarks()
	sampleString := string(sample)
	tb := (*TB)(b)
	db := tb.checkDB(sql.Open(driverNameTest, dsn))
	defer db.Close()

	b.ReportAllocs()
	b.ResetTimer()

	var result string
	for i := 0; i < b.N; i++ {
		length := min + i
		if length > max {
			length = max
		}
		test := sampleString[0:length]
		rows := tb.checkRows(db.Query(`SELECT "` + test + `"`))
		if !rows.Next() {
			rows.Close()
			b.Fatalf("crashed")
		}
		err := rows.Scan(&result)
		if err != nil {
			rows.Close()
			b.Fatalf("crashed")
		}
		if result != test {
			rows.Close()
			b.Errorf("mismatch")
		}
		rows.Close()
	}
}

func BenchmarkRoundtripBin(b *testing.B) {
	sample, min, max := initRoundtripBenchmarks()
	tb := (*TB)(b)
	db := tb.checkDB(sql.Open(driverNameTest, dsn))
	defer db.Close()
	stmt := tb.checkStmt(db.Prepare("SELECT ?"))
	defer stmt.Close()

	b.ReportAllocs()
	b.ResetTimer()
	var result sql.RawBytes
	for i := 0; i < b.N; i++ {
		length := min + i
		if length > max {
			length = max
		}
		test := sample[0:length]
		rows := tb.checkRows(stmt.Query(test))
		if !rows.Next() {
			rows.Close()
			b.Fatalf("crashed")
		}
		err := rows.Scan(&result)
		if err != nil {
			rows.Close()
			b.Fatalf("crashed")
		}
		if !bytes.Equal(result, test) {
			rows.Close()
			b.Errorf("mismatch")
		}
		rows.Close()
	}
}

func BenchmarkInterpolation(b *testing.B) {
	mc := &mysqlConn{
		cfg: &Config{
			InterpolateParams: true,
			Loc:               time.UTC,
		},
		maxAllowedPacket: maxPacketSize,
		maxWriteSize:     maxPacketSize - 1,
		buf:              newBuffer(),
	}

	args := []driver.Value{
		int64(42424242),
		float64(math.Pi),
		false,
		time.Unix(1423411542, 807015000),
		[]byte("bytes containing special chars ' \" \a \x00"),
		"string containing special chars ' \" \a \x00",
	}
	q := "SELECT ?, ?, ?, ?, ?, ?"

	b.ReportAllocs()
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		_, err := mc.interpolateParams(q, args)
		if err != nil {
			b.Fatal(err)
		}
	}
}

func benchmarkQueryContext(b *testing.B, db *sql.DB, p int) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	db.SetMaxIdleConns(p * runtime.GOMAXPROCS(0))

	tb := (*TB)(b)
	stmt := tb.checkStmt(db.PrepareContext(ctx, "SELECT val FROM foo WHERE id=?"))
	defer stmt.Close()

	b.SetParallelism(p)
	b.ReportAllocs()
	b.ResetTimer()
	b.RunParallel(func(pb *testing.PB) {
		var got string
		for pb.Next() {
			tb.check(stmt.QueryRow(1).Scan(&got))
			if got != "one" {
				b.Fatalf("query = %q; want one", got)
			}
		}
	})
}

func BenchmarkQueryContext(b *testing.B) {
	db := initDB(b, false,
		"DROP TABLE IF EXISTS foo",
		"CREATE TABLE foo (id INT PRIMARY KEY, val CHAR(50))",
		`INSERT INTO foo VALUES (1, "one")`,
		`INSERT INTO foo VALUES (2, "two")`,
	)
	defer db.Close()
	for _, p := range []int{1, 2, 3, 4} {
		b.Run(fmt.Sprintf("%d", p), func(b *testing.B) {
			benchmarkQueryContext(b, db, p)
		})
	}
}

func benchmarkExecContext(b *testing.B, db *sql.DB, p int) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	db.SetMaxIdleConns(p * runtime.GOMAXPROCS(0))

	tb := (*TB)(b)
	stmt := tb.checkStmt(db.PrepareContext(ctx, "DO 1"))
	defer stmt.Close()

	b.SetParallelism(p)
	b.ReportAllocs()
	b.ResetTimer()
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			if _, err := stmt.ExecContext(ctx); err != nil {
				b.Fatal(err)
			}
		}
	})
}

func BenchmarkExecContext(b *testing.B) {
	db := initDB(b, false,
		"DROP TABLE IF EXISTS foo",
		"CREATE TABLE foo (id INT PRIMARY KEY, val CHAR(50))",
		`INSERT INTO foo VALUES (1, "one")`,
		`INSERT INTO foo VALUES (2, "two")`,
	)
	defer db.Close()
	for _, p := range []int{1, 2, 3, 4} {
		b.Run(fmt.Sprintf("%d", p), func(b *testing.B) {
			benchmarkExecContext(b, db, p)
		})
	}
}

// BenchmarkQueryRawBytes benchmarks fetching 100 blobs using sql.RawBytes.
// "size=" means size of each blobs.
func BenchmarkQueryRawBytes(b *testing.B) {
	var sizes []int = []int{100, 1000, 2000, 4000, 8000, 12000, 16000, 32000, 64000, 256000}
	db := initDB(b, false,
		"DROP TABLE IF EXISTS bench_rawbytes",
		"CREATE TABLE bench_rawbytes (id INT PRIMARY KEY, val LONGBLOB)",
	)
	defer db.Close()

	blob := make([]byte, sizes[len(sizes)-1])
	for i := range blob {
		blob[i] = 42
	}
	for i := 0; i < 100; i++ {
		_, err := db.Exec("INSERT INTO bench_rawbytes VALUES (?, ?)", i, blob)
		if err != nil {
			b.Fatal(err)
		}
	}

	for _, s := range sizes {
		b.Run(fmt.Sprintf("size=%v", s), func(b *testing.B) {
			db.SetMaxIdleConns(0)
			db.SetMaxIdleConns(1)
			b.ReportAllocs()
			b.ResetTimer()

			for j := 0; j < b.N; j++ {
				rows, err := db.Query("SELECT LEFT(val, ?) as v FROM bench_rawbytes", s)
				if err != nil {
					b.Fatal(err)
				}
				nrows := 0
				for rows.Next() {
					var buf sql.RawBytes
					err := rows.Scan(&buf)
					if err != nil {
						b.Fatal(err)
					}
					if len(buf) != s {
						b.Fatalf("size mismatch: expected %v, got %v", s, len(buf))
					}
					nrows++
				}
				rows.Close()
				if nrows != 100 {
					b.Fatalf("numbers of rows mismatch: expected %v, got %v", 100, nrows)
				}
			}
		})
	}
}

func benchmark10kRows(b *testing.B, compress bool) {
	// Setup -- prepare 10000 rows.
	db := initDB(b, compress,
		"DROP TABLE IF EXISTS foo",
		"CREATE TABLE foo (id INT PRIMARY KEY, val TEXT)")
	defer db.Close()

	sval := strings.Repeat("x", 50)
	stmt, err := db.Prepare(`INSERT INTO foo (id, val) VALUES (?, ?)` + strings.Repeat(",(?,?)", 99))
	if err != nil {
		b.Errorf("failed to prepare query: %v", err)
		return
	}

	args := make([]any, 200)
	for i := 1; i < 200; i += 2 {
		args[i] = sval
	}
	for i := 0; i < 10000; i += 100 {
		for j := 0; j < 100; j++ {
			args[j*2] = i + j
		}
		_, err := stmt.Exec(args...)
		if err != nil {
			b.Error(err)
			return
		}
	}
	stmt.Close()

	// benchmark function called several times with different b.N.
	// it means heavy setup is called multiple times.
	// Use b.Run() to run expensive setup only once.
	// Go 1.24 introduced b.Loop() for this purpose. But we keep this
	// benchmark compatible with Go 1.20.
	b.Run("query", func(b *testing.B) {
		b.ReportAllocs()
		for i := 0; i < b.N; i++ {
			rows, err := db.Query(`SELECT id, val FROM foo`)
			if err != nil {
				b.Errorf("failed to select: %v", err)
				return
			}
			// rows.Scan() escapes arguments. So these variables must be defined
			// before loop.
			var i int
			var s sql.RawBytes
			for rows.Next() {
				if err := rows.Scan(&i, &s); err != nil {
					b.Errorf("failed to scan: %v", err)
					rows.Close()
					return
				}
			}
			if err = rows.Err(); err != nil {
				b.Errorf("failed to read rows: %v", err)
			}
			rows.Close()
		}
	})
}

// BenchmarkReceive10kRows measures performance of receiving large number of rows.
func BenchmarkReceive10kRows(b *testing.B) {
	benchmark10kRows(b, false)
}

func BenchmarkReceive10kRowsCompressed(b *testing.B) {
	benchmark10kRows(b, true)
}

// BenchmarkReceiveMetadata measures performance of receiving lots of metadata compare to data in rows
func BenchmarkReceiveMetadata(b *testing.B) {
	tb := (*TB)(b)

	// Create a table with 1000 integer fields
	createTableQuery := "CREATE TABLE large_integer_table ("
	for i := 0; i < 1000; i++ {
		createTableQuery += fmt.Sprintf("col_%d INT", i)
		if i < 999 {
			createTableQuery += ", "
		}
	}
	createTableQuery += ")"

	// Initialize database
	db := initDB(b, false,
		"DROP TABLE IF EXISTS large_integer_table",
		createTableQuery,
		"INSERT INTO large_integer_table VALUES ("+
			strings.Repeat("0,", 999)+"0)", // Insert a row of zeros
	)
	defer db.Close()

	b.Run("query", func(b *testing.B) {
		db.SetMaxIdleConns(0)
		db.SetMaxIdleConns(1)

		// Create a slice to scan all columns
		values := make([]any, 1000)
		valuePtrs := make([]any, 1000)
		for j := range values {
			valuePtrs[j] = &values[j]
		}

		// Prepare a SELECT query to retrieve metadata
		stmt := tb.checkStmt(db.Prepare("SELECT * FROM large_integer_table LIMIT 1"))
		defer stmt.Close()

		// Benchmark metadata retrieval
		b.ReportAllocs()
		b.ResetTimer()
		for range b.N {
			rows := tb.checkRows(stmt.Query())

			rows.Next()
			// Scan the row
			err := rows.Scan(valuePtrs...)
			tb.check(err)

			rows.Close()
		}
	})
}


================================================
FILE: buffer.go
================================================
// Go MySQL Driver - A MySQL-Driver for Go's database/sql package
//
// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.

package mysql

import (
	"io"
)

const defaultBufSize = 4096
const maxCachedBufSize = 256 * 1024

// readerFunc is a function that compatible with io.Reader.
// We use this function type instead of io.Reader because we want to
// just pass mc.readWithTimeout.
type readerFunc func([]byte) (int, error)

// A buffer which is used for both reading and writing.
// This is possible since communication on each connection is synchronous.
// In other words, we can't write and read simultaneously on the same connection.
// The buffer is similar to bufio.Reader / Writer but zero-copy-ish
// Also highly optimized for this particular use case.
type buffer struct {
	buf       []byte // read buffer.
	cachedBuf []byte // buffer that will be reused. len(cachedBuf) <= maxCachedBufSize.
}

// newBuffer allocates and returns a new buffer.
func newBuffer() buffer {
	return buffer{
		cachedBuf: make([]byte, defaultBufSize),
	}
}

// busy returns true if the read buffer is not empty.
func (b *buffer) busy() bool {
	return len(b.buf) > 0
}

// len returns how many bytes in the read buffer.
func (b *buffer) len() int {
	return len(b.buf)
}

// fill reads into the read buffer until at least _need_ bytes are in it.
func (b *buffer) fill(need int, r readerFunc) error {
	// we'll move the contents of the current buffer to dest before filling it.
	dest := b.cachedBuf

	// grow buffer if necessary to fit the whole packet.
	if need > len(dest) {
		// Round up to the next multiple of the default size
		dest = make([]byte, ((need/defaultBufSize)+1)*defaultBufSize)

		// if the allocated buffer is not too large, move it to backing storage
		// to prevent extra allocations on applications that perform large reads
		if len(dest) <= maxCachedBufSize {
			b.cachedBuf = dest
		}
	}

	// move the existing data to the start of the buffer.
	n := len(b.buf)
	copy(dest[:n], b.buf)

	for {
		nn, err := r(dest[n:])
		n += nn

		if err == nil && n < need {
			continue
		}

		b.buf = dest[:n]

		if err == io.EOF {
			if n < need {
				err = io.ErrUnexpectedEOF
			} else {
				err = nil
			}
		}
		return err
	}
}

// returns next N bytes from buffer.
// The returned slice is only guaranteed to be valid until the next read
func (b *buffer) readNext(need int) []byte {
	data := b.buf[:need:need]
	b.buf = b.buf[need:]
	return data
}

// takeBuffer returns a buffer with the requested size.
// If possible, a slice from the existing buffer is returned.
// Otherwise a bigger buffer is made.
// Only one buffer (total) can be used at a time.
func (b *buffer) takeBuffer(length int) ([]byte, error) {
	if b.busy() {
		return nil, ErrBusyBuffer
	}

	// test (cheap) general case first
	if length <= len(b.cachedBuf) {
		return b.cachedBuf[:length], nil
	}

	if length < maxCachedBufSize {
		b.cachedBuf = make([]byte, length)
		return b.cachedBuf, nil
	}

	// buffer is larger than we want to store.
	return make([]byte, length), nil
}

// takeSmallBuffer is shortcut which can be used if length is
// known to be smaller than defaultBufSize.
// Only one buffer (total) can be used at a time.
func (b *buffer) takeSmallBuffer(length int) ([]byte, error) {
	if b.busy() {
		return nil, ErrBusyBuffer
	}
	return b.cachedBuf[:length], nil
}

// takeCompleteBuffer returns the complete existing buffer.
// This can be used if the necessary buffer size is unknown.
// cap and len of the returned buffer will be equal.
// Only one buffer (total) can be used at a time.
func (b *buffer) takeCompleteBuffer() ([]byte, error) {
	if b.busy() {
		return nil, ErrBusyBuffer
	}
	return b.cachedBuf, nil
}

// store stores buf, an updated buffer, if its suitable to do so.
func (b *buffer) store(buf []byte) {
	if cap(buf) <= maxCachedBufSize && cap(buf) > cap(b.cachedBuf) {
		b.cachedBuf = buf[:cap(buf)]
	}
}


================================================
FILE: collations.go
================================================
// Go MySQL Driver - A MySQL-Driver for Go's database/sql package
//
// Copyright 2014 The Go-MySQL-Driver Authors. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.

package mysql

const defaultCollationID = 45 // utf8mb4_general_ci
const binaryCollationID = 63

// A list of available collations mapped to the internal ID.
// To update this map use the following MySQL query:
//
//	SELECT COLLATION_NAME, ID FROM information_schema.COLLATIONS WHERE ID<256 ORDER BY ID
//
// Handshake packet have only 1 byte for collation_id.  So we can't use collations with ID > 255.
//
// ucs2, utf16, and utf32 can't be used for connection charset.
// https://dev.mysql.com/doc/refman/5.7/en/charset-connection.html#charset-connection-impermissible-client-charset
// They are commented out to reduce this map.
var collations = map[string]byte{
	"big5_chinese_ci":      1,
	"latin2_czech_cs":      2,
	"dec8_swedish_ci":      3,
	"cp850_general_ci":     4,
	"latin1_german1_ci":    5,
	"hp8_english_ci":       6,
	"koi8r_general_ci":     7,
	"latin1_swedish_ci":    8,
	"latin2_general_ci":    9,
	"swe7_swedish_ci":      10,
	"ascii_general_ci":     11,
	"ujis_japanese_ci":     12,
	"sjis_japanese_ci":     13,
	"cp1251_bulgarian_ci":  14,
	"latin1_danish_ci":     15,
	"hebrew_general_ci":    16,
	"tis620_thai_ci":       18,
	"euckr_korean_ci":      19,
	"latin7_estonian_cs":   20,
	"latin2_hungarian_ci":  21,
	"koi8u_general_ci":     22,
	"cp1251_ukrainian_ci":  23,
	"gb2312_chinese_ci":    24,
	"greek_general_ci":     25,
	"cp1250_general_ci":    26,
	"latin2_croatian_ci":   27,
	"gbk_chinese_ci":       28,
	"cp1257_lithuanian_ci": 29,
	"latin5_turkish_ci":    30,
	"latin1_german2_ci":    31,
	"armscii8_general_ci":  32,
	"utf8_general_ci":      33,
	"cp1250_czech_cs":      34,
	//"ucs2_general_ci":          35,
	"cp866_general_ci":    36,
	"keybcs2_general_ci":  37,
	"macce_general_ci":    38,
	"macroman_general_ci": 39,
	"cp852_general_ci":    40,
	"latin7_general_ci":   41,
	"latin7_general_cs":   42,
	"macce_bin":           43,
	"cp1250_croatian_ci":  44,
	"utf8mb4_general_ci":  45,
	"utf8mb4_bin":         46,
	"latin1_bin":          47,
	"latin1_general_ci":   48,
	"latin1_general_cs":   49,
	"cp1251_bin":          50,
	"cp1251_general_ci":   51,
	"cp1251_general_cs":   52,
	"macroman_bin":        53,
	//"utf16_general_ci":         54,
	//"utf16_bin":                55,
	//"utf16le_general_ci":       56,
	"cp1256_general_ci": 57,
	"cp1257_bin":        58,
	"cp1257_general_ci": 59,
	//"utf32_general_ci":         60,
	//"utf32_bin":                61,
	//"utf16le_bin":              62,
	"binary":          63,
	"armscii8_bin":    64,
	"ascii_bin":       65,
	"cp1250_bin":      66,
	"cp1256_bin":      67,
	"cp866_bin":       68,
	"dec8_bin":        69,
	"greek_bin":       70,
	"hebrew_bin":      71,
	"hp8_bin":         72,
	"keybcs2_bin":     73,
	"koi8r_bin":       74,
	"koi8u_bin":       75,
	"utf8_tolower_ci": 76,
	"latin2_bin":      77,
	"latin5_bin":      78,
	"latin7_bin":      79,
	"cp850_bin":       80,
	"cp852_bin":       81,
	"swe7_bin":        82,
	"utf8_bin":        83,
	"big5_bin":        84,
	"euckr_bin":       85,
	"gb2312_bin":      86,
	"gbk_bin":         87,
	"sjis_bin":        88,
	"tis620_bin":      89,
	//"ucs2_bin":                 90,
	"ujis_bin":            91,
	"geostd8_general_ci":  92,
	"geostd8_bin":         93,
	"latin1_spanish_ci":   94,
	"cp932_japanese_ci":   95,
	"cp932_bin":           96,
	"eucjpms_japanese_ci": 97,
	"eucjpms_bin":         98,
	"cp1250_polish_ci":    99,
	//"utf16_unicode_ci":         101,
	//"utf16_icelandic_ci":       102,
	//"utf16_latvian_ci":         103,
	//"utf16_romanian_ci":        104,
	//"utf16_slovenian_ci":       105,
	//"utf16_polish_ci":          106,
	//"utf16_estonian_ci":        107,
	//"utf16_spanish_ci":         108,
	//"utf16_swedish_ci":         109,
	//"utf16_turkish_ci":         110,
	//"utf16_czech_ci":           111,
	//"utf16_danish_ci":          112,
	//"utf16_lithuanian_ci":      113,
	//"utf16_slovak_ci":          114,
	//"utf16_spanish2_ci":        115,
	//"utf16_roman_ci":           116,
	//"utf16_persian_ci":         117,
	//"utf16_esperanto_ci":       118,
	//"utf16_hungarian_ci":       119,
	//"utf16_sinhala_ci":         120,
	//"utf16_german2_ci":         121,
	//"utf16_croatian_ci":        122,
	//"utf16_unicode_520_ci":     123,
	//"utf16_vietnamese_ci":      124,
	//"ucs2_unicode_ci":          128,
	//"ucs2_icelandic_ci":        129,
	//"ucs2_latvian_ci":          130,
	//"ucs2_romanian_ci":         131,
	//"ucs2_slovenian_ci":        132,
	//"ucs2_polish_ci":           133,
	//"ucs2_estonian_ci":         134,
	//"ucs2_spanish_ci":          135,
	//"ucs2_swedish_ci":          136,
	//"ucs2_turkish_ci":          137,
	//"ucs2_czech_ci":            138,
	//"ucs2_danish_ci":           139,
	//"ucs2_lithuanian_ci":       140,
	//"ucs2_slovak_ci":           141,
	//"ucs2_spanish2_ci":         142,
	//"ucs2_roman_ci":            143,
	//"ucs2_persian_ci":          144,
	//"ucs2_esperanto_ci":        145,
	//"ucs2_hungarian_ci":        146,
	//"ucs2_sinhala_ci":          147,
	//"ucs2_german2_ci":          148,
	//"ucs2_croatian_ci":         149,
	//"ucs2_unicode_520_ci":      150,
	//"ucs2_vietnamese_ci":       151,
	//"ucs2_general_mysql500_ci": 159,
	//"utf32_unicode_ci":         160,
	//"utf32_icelandic_ci":       161,
	//"utf32_latvian_ci":         162,
	//"utf32_romanian_ci":        163,
	//"utf32_slovenian_ci":       164,
	//"utf32_polish_ci":          165,
	//"utf32_estonian_ci":        166,
	//"utf32_spanish_ci":         167,
	//"utf32_swedish_ci":         168,
	//"utf32_turkish_ci":         169,
	//"utf32_czech_ci":           170,
	//"utf32_danish_ci":          171,
	//"utf32_lithuanian_ci":      172,
	//"utf32_slovak_ci":          173,
	//"utf32_spanish2_ci":        174,
	//"utf32_roman_ci":           175,
	//"utf32_persian_ci":         176,
	//"utf32_esperanto_ci":       177,
	//"utf32_hungarian_ci":       178,
	//"utf32_sinhala_ci":         179,
	//"utf32_german2_ci":         180,
	//"utf32_croatian_ci":        181,
	//"utf32_unicode_520_ci":     182,
	//"utf32_vietnamese_ci":      183,
	"utf8_unicode_ci":          192,
	"utf8_icelandic_ci":        193,
	"utf8_latvian_ci":          194,
	"utf8_romanian_ci":         195,
	"utf8_slovenian_ci":        196,
	"utf8_polish_ci":           197,
	"utf8_estonian_ci":         198,
	"utf8_spanish_ci":          199,
	"utf8_swedish_ci":          200,
	"utf8_turkish_ci":          201,
	"utf8_czech_ci":            202,
	"utf8_danish_ci":           203,
	"utf8_lithuanian_ci":       204,
	"utf8_slovak_ci":           205,
	"utf8_spanish2_ci":         206,
	"utf8_roman_ci":            207,
	"utf8_persian_ci":          208,
	"utf8_esperanto_ci":        209,
	"utf8_hungarian_ci":        210,
	"utf8_sinhala_ci":          211,
	"utf8_german2_ci":          212,
	"utf8_croatian_ci":         213,
	"utf8_unicode_520_ci":      214,
	"utf8_vietnamese_ci":       215,
	"utf8_general_mysql500_ci": 223,
	"utf8mb4_unicode_ci":       224,
	"utf8mb4_icelandic_ci":     225,
	"utf8mb4_latvian_ci":       226,
	"utf8mb4_romanian_ci":      227,
	"utf8mb4_slovenian_ci":     228,
	"utf8mb4_polish_ci":        229,
	"utf8mb4_estonian_ci":      230,
	"utf8mb4_spanish_ci":       231,
	"utf8mb4_swedish_ci":       232,
	"utf8mb4_turkish_ci":       233,
	"utf8mb4_czech_ci":         234,
	"utf8mb4_danish_ci":        235,
	"utf8mb4_lithuanian_ci":    236,
	"utf8mb4_slovak_ci":        237,
	"utf8mb4_spanish2_ci":      238,
	"utf8mb4_roman_ci":         239,
	"utf8mb4_persian_ci":       240,
	"utf8mb4_esperanto_ci":     241,
	"utf8mb4_hungarian_ci":     242,
	"utf8mb4_sinhala_ci":       243,
	"utf8mb4_german2_ci":       244,
	"utf8mb4_croatian_ci":      245,
	"utf8mb4_unicode_520_ci":   246,
	"utf8mb4_vietnamese_ci":    247,
	"gb18030_chinese_ci":       248,
	"gb18030_bin":              249,
	"gb18030_unicode_520_ci":   250,
	"utf8mb4_0900_ai_ci":       255,
}

// A denylist of collations which is unsafe to interpolate parameters.
// These multibyte encodings may contains 0x5c (`\`) in their trailing bytes.
var unsafeCollations = map[string]bool{
	"big5_chinese_ci":        true,
	"sjis_japanese_ci":       true,
	"gbk_chinese_ci":         true,
	"big5_bin":               true,
	"gb2312_bin":             true,
	"gbk_bin":                true,
	"sjis_bin":               true,
	"cp932_japanese_ci":      true,
	"cp932_bin":              true,
	"gb18030_chinese_ci":     true,
	"gb18030_bin":            true,
	"gb18030_unicode_520_ci": true,
}


================================================
FILE: compress.go
================================================
// Go MySQL Driver - A MySQL-Driver for Go's database/sql package
//
// Copyright 2024 The Go-MySQL-Driver Authors. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.

package mysql

import (
	"bytes"
	"compress/zlib"
	"fmt"
	"io"
	"sync"
)

var (
	zrPool *sync.Pool // Do not use directly. Use zDecompress() instead.
	zwPool *sync.Pool // Do not use directly. Use zCompress() instead.
)

func init() {
	zrPool = &sync.Pool{
		New: func() any { return nil },
	}
	zwPool = &sync.Pool{
		New: func() any {
			zw, err := zlib.NewWriterLevel(new(bytes.Buffer), 2)
			if err != nil {
				panic(err) // compress/zlib return non-nil error only if level is invalid
			}
			return zw
		},
	}
}

func zDecompress(src []byte, dst *bytes.Buffer) (int, error) {
	br := bytes.NewReader(src)
	var zr io.ReadCloser
	var err error

	if a := zrPool.Get(); a == nil {
		if zr, err = zlib.NewReader(br); err != nil {
			return 0, err
		}
	} else {
		zr = a.(io.ReadCloser)
		if err := zr.(zlib.Resetter).Reset(br, nil); err != nil {
			return 0, err
		}
	}

	n, _ := dst.ReadFrom(zr) // ignore err because zr.Close() will return it again.
	err = zr.Close()         // zr.Close() may return chuecksum error.
	zrPool.Put(zr)
	return int(n), err
}

func zCompress(src []byte, dst io.Writer) error {
	zw := zwPool.Get().(*zlib.Writer)
	zw.Reset(dst)
	if _, err := zw.Write(src); err != nil {
		return err
	}
	err := zw.Close()
	zwPool.Put(zw)
	return err
}

type compIO struct {
	mc   *mysqlConn
	buff bytes.Buffer
}

func newCompIO(mc *mysqlConn) *compIO {
	return &compIO{
		mc: mc,
	}
}

func (c *compIO) reset() {
	c.buff.Reset()
}

func (c *compIO) readNext(need int) ([]byte, error) {
	for c.buff.Len() < need {
		if err := c.readCompressedPacket(); err != nil {
			return nil, err
		}
	}
	data := c.buff.Next(need)
	return data[:need:need], nil // prevent caller writes into c.buff
}

func (c *compIO) readCompressedPacket() error {
	header, err := c.mc.readNext(7)
	if err != nil {
		return err
	}
	_ = header[6] // bounds check hint to compiler; guaranteed by readNext

	// compressed header structure
	comprLength := getUint24(header[0:3])
	compressionSequence := header[3]
	uncompressedLength := getUint24(header[4:7])
	if debug {
		fmt.Printf("uncompress cmplen=%v uncomplen=%v pkt_cmp_seq=%v expected_cmp_seq=%v\n",
			comprLength, uncompressedLength, compressionSequence, c.mc.sequence)
	}
	// Do not return ErrPktSync here.
	// Server may return error packet (e.g. 1153 Got a packet bigger than 'max_allowed_packet' bytes)
	// before receiving all packets from client. In this case, seqnr is younger than expected.
	// NOTE: Both of mariadbclient and mysqlclient do not check seqnr. Only server checks it.
	if debug && compressionSequence != c.mc.compressSequence {
		fmt.Printf("WARN: unexpected cmpress seq nr: expected %v, got %v",
			c.mc.compressSequence, compressionSequence)
	}
	c.mc.compressSequence = compressionSequence + 1

	comprData, err := c.mc.readNext(comprLength)
	if err != nil {
		return err
	}

	// if payload is uncompressed, its length will be specified as zero, and its
	// true length is contained in comprLength
	if uncompressedLength == 0 {
		c.buff.Write(comprData)
		return nil
	}

	// use existing capacity in bytesBuf if possible
	c.buff.Grow(uncompressedLength)
	nread, err := zDecompress(comprData, &c.buff)
	if err != nil {
		return err
	}
	if nread != uncompressedLength {
		return fmt.Errorf("invalid compressed packet: uncompressed length in header is %d, actual %d",
			uncompressedLength, nread)
	}
	return nil
}

const minCompressLength = 150
const maxPayloadLen = maxPacketSize - 4

// writePackets sends one or some packets with compression.
// Use this instead of mc.netConn.Write() when mc.compress is true.
func (c *compIO) writePackets(packets []byte) (int, error) {
	totalBytes := len(packets)
	blankHeader := make([]byte, 7)
	buf := &c.buff

	for len(packets) > 0 {
		payloadLen := min(maxPayloadLen, len(packets))
		payload := packets[:payloadLen]
		uncompressedLen := payloadLen

		buf.Reset()
		buf.Write(blankHeader) // Buffer.Write() never returns error

		// If payload is less than minCompressLength, don't compress.
		if uncompressedLen < minCompressLength {
			buf.Write(payload)
			uncompressedLen = 0
		} else {
			err := zCompress(payload, buf)
			if debug && err != nil {
				fmt.Printf("zCompress error: %v", err)
			}
			// do not compress if compressed data is larger than uncompressed data
			// I intentionally miss 7 byte header in the buf; zCompress must compress more than 7 bytes.
			if err != nil || buf.Len() >= uncompressedLen {
				buf.Reset()
				buf.Write(blankHeader)
				buf.Write(payload)
				uncompressedLen = 0
			}
		}

		if n, err := c.writeCompressedPacket(buf.Bytes(), uncompressedLen); err != nil {
			// To allow returning ErrBadConn when sending really 0 bytes, we sum
			// up compressed bytes that is returned by underlying Write().
			return totalBytes - len(packets) + n, err
		}
		packets = packets[payloadLen:]
	}

	return totalBytes, nil
}

// writeCompressedPacket writes a compressed packet with header.
// data should start with 7 size space for header followed by payload.
func (c *compIO) writeCompressedPacket(data []byte, uncompressedLen int) (int, error) {
	mc := c.mc
	comprLength := len(data) - 7
	if debug {
		fmt.Printf(
			"writeCompressedPacket: comprLength=%v, uncompressedLen=%v, seq=%v\n",
			comprLength, uncompressedLen, mc.compressSequence)
	}

	// compression header
	putUint24(data[0:3], comprLength)
	data[3] = mc.compressSequence
	putUint24(data[4:7], uncompressedLen)

	mc.compressSequence++
	return mc.writeWithTimeout(data)
}


================================================
FILE: compress_test.go
================================================
// Go MySQL Driver - A MySQL-Driver for Go's database/sql package
//
// Copyright 2024 The Go-MySQL-Driver Authors. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.

package mysql

import (
	"bytes"
	"crypto/rand"
	"io"
	"testing"
)

func makeRandByteSlice(size int) []byte {
	randBytes := make([]byte, size)
	rand.Read(randBytes)
	return randBytes
}

// compressHelper compresses uncompressedPacket and checks state variables
func compressHelper(t *testing.T, mc *mysqlConn, uncompressedPacket []byte) []byte {
	conn := new(mockConn)
	mc.netConn = conn

	err := mc.writePacket(append(make([]byte, 4), uncompressedPacket...))
	if err != nil {
		t.Fatal(err)
	}

	return conn.written
}

// uncompressHelper uncompresses compressedPacket and checks state variables
func uncompressHelper(t *testing.T, mc *mysqlConn, compressedPacket []byte) []byte {
	// mocking out buf variable
	conn := new(mockConn)
	conn.data = compressedPacket
	mc.netConn = conn

	uncompressedPacket, err := mc.readPacket()
	if err != nil {
		if err != io.EOF {
			t.Fatalf("non-nil/non-EOF error when reading contents: %s", err.Error())
		}
	}
	return uncompressedPacket
}

// roundtripHelper compresses then uncompresses uncompressedPacket and checks state variables
func roundtripHelper(t *testing.T, cSend *mysqlConn, cReceive *mysqlConn, uncompressedPacket []byte) []byte {
	compressed := compressHelper(t, cSend, uncompressedPacket)
	return uncompressHelper(t, cReceive, compressed)
}

// TestRoundtrip tests two connections, where one is reading and the other is writing
func TestRoundtrip(t *testing.T) {
	tests := []struct {
		uncompressed []byte
		desc         string
	}{
		{uncompressed: []byte("a"),
			desc: "a"},
		{uncompressed: []byte("hello world"),
			desc: "hello world"},
		{uncompressed: make([]byte, 100),
			desc: "100 bytes"},
		{uncompressed: make([]byte, 32768),
			desc: "32768 bytes"},
		{uncompressed: make([]byte, 330000),
			desc: "33000 bytes"},
		{uncompressed: makeRandByteSlice(10),
			desc: "10 rand bytes",
		},
		{uncompressed: makeRandByteSlice(100),
			desc: "100 rand bytes",
		},
		{uncompressed: makeRandByteSlice(32768),
			desc: "32768 rand bytes",
		},
		{uncompressed: bytes.Repeat(makeRandByteSlice(100), 10000),
			desc: "100 rand * 10000 repeat bytes",
		},
	}

	_, cSend := newRWMockConn(0)
	cSend.compress = true
	cSend.compIO = newCompIO(cSend)
	_, cReceive := newRWMockConn(0)
	cReceive.compress = true
	cReceive.compIO = newCompIO(cReceive)

	for _, test := range tests {
		t.Run(test.desc, func(t *testing.T) {
			cSend.resetSequence()
			cReceive.resetSequence()

			uncompressed := roundtripHelper(t, cSend, cReceive, test.uncompressed)
			if len(uncompressed) != len(test.uncompressed) {
				t.Errorf("uncompressed size is unexpected. expected %d but got %d",
					len(test.uncompressed), len(uncompressed))
			}
			if !bytes.Equal(uncompressed, test.uncompressed) {
				t.Errorf("roundtrip failed")
			}
			if cSend.sequence != cReceive.sequence {
				t.Errorf("inconsistent sequence number: send=%v recv=%v",
					cSend.sequence, cReceive.sequence)
			}
			if cSend.compressSequence != cReceive.compressSequence {
				t.Errorf("inconsistent compress sequence number: send=%v recv=%v",
					cSend.compressSequence, cReceive.compressSequence)
			}
		})
	}
}


================================================
FILE: conncheck.go
================================================
// Go MySQL Driver - A MySQL-Driver for Go's database/sql package
//
// Copyright 2019 The Go-MySQL-Driver Authors. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.

//go:build linux || darwin || dragonfly || freebsd || netbsd || openbsd || solaris || illumos
// +build linux darwin dragonfly freebsd netbsd openbsd solaris illumos

package mysql

import (
	"errors"
	"io"
	"net"
	"syscall"
)

var errUnexpectedRead = errors.New("unexpected read from socket")

func connCheck(conn net.Conn) error {
	var sysErr error

	sysConn, ok := conn.(syscall.Conn)
	if !ok {
		return nil
	}
	rawConn, err := sysConn.SyscallConn()
	if err != nil {
		return err
	}

	err = rawConn.Read(func(fd uintptr) bool {
		var buf [1]byte
		n, err := syscall.Read(int(fd), buf[:])
		switch {
		case n == 0 && err == nil:
			sysErr = io.EOF
		case n > 0:
			sysErr = errUnexpectedRead
		case err == syscall.EAGAIN || err == syscall.EWOULDBLOCK:
			sysErr = nil
		default:
			sysErr = err
		}
		return true
	})
	if err != nil {
		return err
	}

	return sysErr
}


================================================
FILE: conncheck_dummy.go
================================================
// Go MySQL Driver - A MySQL-Driver for Go's database/sql package
//
// Copyright 2019 The Go-MySQL-Driver Authors. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.

//go:build !linux && !darwin && !dragonfly && !freebsd && !netbsd && !openbsd && !solaris && !illumos
// +build !linux,!darwin,!dragonfly,!freebsd,!netbsd,!openbsd,!solaris,!illumos

package mysql

import "net"

func connCheck(conn net.Conn) error {
	return nil
}


================================================
FILE: conncheck_test.go
================================================
// Go MySQL Driver - A MySQL-Driver for Go's database/sql package
//
// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.

//go:build linux || darwin || dragonfly || freebsd || netbsd || openbsd || solaris || illumos
// +build linux darwin dragonfly freebsd netbsd openbsd solaris illumos

package mysql

import (
	"testing"
	"time"
)

func TestStaleConnectionChecks(t *testing.T) {
	runTestsParallel(t, dsn, func(dbt *DBTest, _ string) {
		dbt.mustExec("SET @@SESSION.wait_timeout = 2")

		if err := dbt.db.Ping(); err != nil {
			dbt.Fatal(err)
		}

		// wait for MySQL to close our connection
		time.Sleep(3 * time.Second)

		tx, err := dbt.db.Begin()
		if err != nil {
			dbt.Fatal(err)
		}

		if err := tx.Rollback(); err != nil {
			dbt.Fatal(err)
		}
	})
}


================================================
FILE: connection.go
================================================
// Go MySQL Driver - A MySQL-Driver for Go's database/sql package
//
// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.

package mysql

import (
	"context"
	"database/sql"
	"database/sql/driver"
	"encoding/json"
	"fmt"
	"io"
	"net"
	"runtime"
	"strconv"
	"strings"
	"sync/atomic"
	"time"
)

type mysqlConn struct {
	buf              buffer
	netConn          net.Conn
	rawConn          net.Conn    // underlying connection when netConn is TLS connection.
	result           mysqlResult // managed by clearResult() and handleOkPacket().
	compIO           *compIO
	cfg              *Config
	connector        *connector
	maxAllowedPacket int
	maxWriteSize     int
	capabilities     capabilityFlag
	extCapabilities  extendedCapabilityFlag
	status           statusFlag
	sequence         uint8
	compressSequence uint8
	parseTime        bool
	compress         bool

	// for context support (Go 1.8+)
	watching bool
	watcher  chan<- context.Context
	closech  chan struct{}
	finished chan<- struct{}
	canceled atomicError // set non-nil if conn is canceled
	closed   atomic.Bool // set when conn is closed, before closech is closed
}

// Helper function to call per-connection logger.
func (mc *mysqlConn) log(v ...any) {
	_, filename, lineno, ok := runtime.Caller(1)
	if ok {
		pos := strings.LastIndexByte(filename, '/')
		if pos != -1 {
			filename = filename[pos+1:]
		}
		prefix := fmt.Sprintf("%s:%d ", filename, lineno)
		v = append([]any{prefix}, v...)
	}

	mc.cfg.Logger.Print(v...)
}

func (mc *mysqlConn) readWithTimeout(b []byte) (int, error) {
	to := mc.cfg.ReadTimeout
	if to > 0 {
		if err := mc.netConn.SetReadDeadline(time.Now().Add(to)); err != nil {
			return 0, err
		}
	}
	return mc.netConn.Read(b)
}

func (mc *mysqlConn) writeWithTimeout(b []byte) (int, error) {
	to := mc.cfg.WriteTimeout
	if to > 0 {
		if err := mc.netConn.SetWriteDeadline(time.Now().Add(to)); err != nil {
			return 0, err
		}
	}
	return mc.netConn.Write(b)
}

func (mc *mysqlConn) resetSequence() {
	mc.sequence = 0
	mc.compressSequence = 0
}

// syncSequence must be called when finished writing some packet and before start reading.
func (mc *mysqlConn) syncSequence() {
	// Syncs compressionSequence to sequence.
	// This is not documented but done in `net_flush()` in MySQL and MariaDB.
	// https://github.com/mariadb-corporation/mariadb-connector-c/blob/8228164f850b12353da24df1b93a1e53cc5e85e9/libmariadb/ma_net.c#L170-L171
	// https://github.com/mysql/mysql-server/blob/824e2b4064053f7daf17d7f3f84b7a3ed92e5fb4/sql-common/net_serv.cc#L293
	if mc.compress {
		mc.sequence = mc.compressSequence
		mc.compIO.reset()
	}
}

// Handles parameters set in DSN after the connection is established
func (mc *mysqlConn) handleParams() (err error) {
	var cmdSet strings.Builder

	for param, val := range mc.cfg.Params {
		if cmdSet.Len() == 0 {
			// Heuristic: 29 chars for each other key=value to reduce reallocations
			cmdSet.Grow(4 + len(param) + 3 + len(val) + 30*(len(mc.cfg.Params)-1))
			cmdSet.WriteString("SET ")
		} else {
			cmdSet.WriteString(", ")
		}
		cmdSet.WriteString(param)
		cmdSet.WriteString(" = ")
		cmdSet.WriteString(val)
	}

	if cmdSet.Len() > 0 {
		err = mc.exec(cmdSet.String())
	}

	return
}

// markBadConn replaces errBadConnNoWrite with driver.ErrBadConn.
// This function is used to return driver.ErrBadConn only when safe to retry.
func (mc *mysqlConn) markBadConn(err error) error {
	if err == errBadConnNoWrite {
		return driver.ErrBadConn
	}
	return err
}

func (mc *mysqlConn) Begin() (driver.Tx, error) {
	return mc.begin(false)
}

func (mc *mysqlConn) begin(readOnly bool) (driver.Tx, error) {
	if mc.closed.Load() {
		return nil, driver.ErrBadConn
	}
	var q string
	if readOnly {
		q = "START TRANSACTION READ ONLY"
	} else {
		q = "START TRANSACTION"
	}
	err := mc.exec(q)
	if err == nil {
		return &mysqlTx{mc}, err
	}
	return nil, mc.markBadConn(err)
}

func (mc *mysqlConn) Close() (err error) {
	// Makes Close idempotent
	if !mc.closed.Load() {
		err = mc.writeCommandPacket(comQuit)
	}
	mc.close()
	return
}

// close closes the network connection and clear results without sending COM_QUIT.
func (mc *mysqlConn) close() {
	mc.cleanup()
	mc.clearResult()
}

// Closes the network connection and unsets internal variables. Do not call this
// function after successfully authentication, call Close instead. This function
// is called before auth or on auth failure because MySQL will have already
// closed the network connection.
func (mc *mysqlConn) cleanup() {
	if mc.closed.Swap(true) {
		return
	}

	// Makes cleanup idempotent
	close(mc.closech)
	conn := mc.rawConn
	if conn == nil {
		return
	}
	if err := conn.Close(); err != nil {
		mc.log("closing connection:", err)
	}
	// This function can be called from multiple goroutines.
	// So we can not mc.clearResult() here.
	// Caller should do it if they are in safe goroutine.
}

func (mc *mysqlConn) error() error {
	if mc.closed.Load() {
		if err := mc.canceled.Value(); err != nil {
			return err
		}
		return ErrInvalidConn
	}
	return nil
}

func (mc *mysqlConn) Prepare(query string) (driver.Stmt, error) {
	if mc.closed.Load() {
		return nil, driver.ErrBadConn
	}
	// Send command
	err := mc.writeCommandPacketStr(comStmtPrepare, query)
	if err != nil {
		// STMT_PREPARE is safe to retry.  So we can return ErrBadConn here.
		mc.log(err)
		return nil, driver.ErrBadConn
	}

	stmt := &mysqlStmt{
		mc: mc,
	}

	// Read Result
	columnCount, err := stmt.readPrepareResultPacket()
	if err == nil {
		if stmt.paramCount > 0 {
			if err = mc.skipColumns(stmt.paramCount); err != nil {
				return nil, err
			}
		}

		if columnCount > 0 {
			if mc.extCapabilities&clientCacheMetadata != 0 {
				if stmt.columns, err = mc.readColumns(int(columnCount), nil); err != nil {
					return nil, err
				}
			} else {
				if err = mc.skipColumns(int(columnCount)); err != nil {
					return nil, err
				}
			}
		}
	}

	return stmt, err
}

func (mc *mysqlConn) interpolateParams(query string, args []driver.Value) (string, error) {
	// Number of ? should be same to len(args)
	if strings.Count(query, "?") != len(args) {
		return "", driver.ErrSkip
	}

	buf, err := mc.buf.takeCompleteBuffer()
	if err != nil {
		// can not take the buffer. Something must be wrong with the connection
		mc.cleanup()
		// interpolateParams would be called before sending any query.
		// So its safe to retry.
		return "", driver.ErrBadConn
	}
	buf = buf[:0]
	argPos := 0

	for i := 0; i < len(query); i++ {
		q := strings.IndexByte(query[i:], '?')
		if q == -1 {
			buf = append(buf, query[i:]...)
			break
		}
		buf = append(buf, query[i:i+q]...)
		i += q

		arg := args[argPos]
		argPos++

		if arg == nil {
			buf = append(buf, "NULL"...)
			continue
		}

		switch v := arg.(type) {
		case int64:
			buf = strconv.AppendInt(buf, v, 10)
		case uint64:
			// Handle uint64 explicitly because our custom ConvertValue emits unsigned values
			buf = strconv.AppendUint(buf, v, 10)
		case float64:
			buf = strconv.AppendFloat(buf, v, 'g', -1, 64)
		case bool:
			if v {
				buf = append(buf, '1')
			} else {
				buf = append(buf, '0')
			}
		case time.Time:
			if v.IsZero() {
				buf = append(buf, "'0000-00-00'"...)
			} else {
				buf = append(buf, '\'')
				buf, err = appendDateTime(buf, v.In(mc.cfg.Loc), mc.cfg.timeTruncate)
				if err != nil {
					return "", err
				}
				buf = append(buf, '\'')
			}
		case json.RawMessage:
			buf = append(buf, '\'')
			if mc.status&statusNoBackslashEscapes == 0 {
				buf = escapeBytesBackslash(buf, v)
			} else {
				buf = escapeBytesQuotes(buf, v)
			}
			buf = append(buf, '\'')
		case []byte:
			if v == nil {
				buf = append(buf, "NULL"...)
			} else {
				buf = append(buf, "_binary'"...)
				if mc.status&statusNoBackslashEscapes == 0 {
					buf = escapeBytesBackslash(buf, v)
				} else {
					buf = escapeBytesQuotes(buf, v)
				}
				buf = append(buf, '\'')
			}
		case string:
			buf = append(buf, '\'')
			if mc.status&statusNoBackslashEscapes == 0 {
				buf = escapeStringBackslash(buf, v)
			} else {
				buf = escapeStringQuotes(buf, v)
			}
			buf = append(buf, '\'')
		default:
			return "", driver.ErrSkip
		}

		if len(buf)+4 > mc.maxAllowedPacket {
			return "", driver.ErrSkip
		}
	}
	if argPos != len(args) {
		return "", driver.ErrSkip
	}
	return string(buf), nil
}

func (mc *mysqlConn) Exec(query string, args []driver.Value) (driver.Result, error) {
	if mc.closed.Load() {
		return nil, driver.ErrBadConn
	}
	if len(args) != 0 {
		if !mc.cfg.InterpolateParams {
			return nil, driver.ErrSkip
		}
		// try to interpolate the parameters to save extra roundtrips for preparing and closing a statement
		prepared, err := mc.interpolateParams(query, args)
		if err != nil {
			return nil, err
		}
		query = prepared
	}

	err := mc.exec(query)
	if err == nil {
		copied := mc.result
		return &copied, err
	}
	return nil, mc.markBadConn(err)
}

// Internal function to execute commands
func (mc *mysqlConn) exec(query string) error {
	handleOk := mc.clearResult()
	// Send command
	if err := mc.writeCommandPacketStr(comQuery, query); err != nil {
		return mc.markBadConn(err)
	}

	// Read Result
	resLen, _, err := handleOk.readResultSetHeaderPacket()
	if err != nil {
		return err
	}

	if resLen > 0 {
		// columns
		if err := mc.skipColumns(resLen); err != nil {
			return err
		}

		// rows
		if err := mc.skipRows(); err != nil {
			return err
		}
	}

	return handleOk.discardResults()
}

func (mc *mysqlConn) Query(query string, args []driver.Value) (driver.Rows, error) {
	return mc.query(query, args)
}

func (mc *mysqlConn) query(query string, args []driver.Value) (*textRows, error) {
	handleOk := mc.clearResult()

	if mc.closed.Load() {
		return nil, driver.ErrBadConn
	}
	if len(args) != 0 {
		if !mc.cfg.InterpolateParams {
			return nil, driver.ErrSkip
		}
		// try client-side prepare to reduce roundtrip
		prepared, err := mc.interpolateParams(query, args)
		if err != nil {
			return nil, err
		}
		query = prepared
	}
	// Send command
	err := mc.writeCommandPacketStr(comQuery, query)
	if err != nil {
		return nil, mc.markBadConn(err)
	}

	// Read Result
	var resLen int
	resLen, _, err = handleOk.readResultSetHeaderPacket()
	if err != nil {
		return nil, err
	}

	rows := new(textRows)
	rows.mc = mc

	if resLen == 0 {
		rows.rs.done = true

		switch err := rows.NextResultSet(); err {
		case nil, io.EOF:
			return rows, nil
		default:
			return nil, err
		}
	}

	// Columns
	rows.rs.columns, err = mc.readColumns(resLen, nil)
	return rows, err
}

// Gets the value of the given MySQL System Variable
// The returned byte slice is only valid until the next read
func (mc *mysqlConn) getSystemVar(name string) ([]byte, error) {
	// Send command
	handleOk := mc.clearResult()
	if err := mc.writeCommandPacketStr(comQuery, "SELECT @@"+name); err != nil {
		return nil, err
	}

	// Read Result
	resLen, _, err := handleOk.readResultSetHeaderPacket()
	if err == nil {
		rows := new(textRows)
		rows.mc = mc
		rows.rs.columns = []mysqlField{{fieldType: fieldTypeVarChar}}

		if resLen > 0 {
			// Columns
			if err := mc.skipColumns(resLen); err != nil {
				return nil, err
			}
		}

		dest := make([]driver.Value, resLen)
		if err = rows.readRow(dest); err == nil {
			return dest[0].([]byte), mc.skipRows()
		}
	}
	return nil, err
}

// cancel is called when the query has canceled.
func (mc *mysqlConn) cancel(err error) {
	mc.canceled.Set(err)
	mc.cleanup()
}

// finish is called when the query has succeeded.
func (mc *mysqlConn) finish() {
	if !mc.watching || mc.finished == nil {
		return
	}
	select {
	case mc.finished <- struct{}{}:
		mc.watching = false
	case <-mc.closech:
	}
}

// Ping implements driver.Pinger interface
func (mc *mysqlConn) Ping(ctx context.Context) (err error) {
	if mc.closed.Load() {
		return driver.ErrBadConn
	}

	if err = mc.watchCancel(ctx); err != nil {
		return
	}
	defer mc.finish()

	handleOk := mc.clearResult()
	if err = mc.writeCommandPacket(comPing); err != nil {
		return mc.markBadConn(err)
	}

	return handleOk.readResultOK()
}

// BeginTx implements driver.ConnBeginTx interface
func (mc *mysqlConn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) {
	if mc.closed.Load() {
		return nil, driver.ErrBadConn
	}

	if err := mc.watchCancel(ctx); err != nil {
		return nil, err
	}
	defer mc.finish()

	if sql.IsolationLevel(opts.Isolation) != sql.LevelDefault {
		level, err := mapIsolationLevel(opts.Isolation)
		if err != nil {
			return nil, err
		}
		err = mc.exec("SET TRANSACTION ISOLATION LEVEL " + level)
		if err != nil {
			return nil, err
		}
	}

	return mc.begin(opts.ReadOnly)
}

func (mc *mysqlConn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) {
	dargs, err := namedValueToValue(args)
	if err != nil {
		return nil, err
	}

	if err := mc.watchCancel(ctx); err != nil {
		return nil, err
	}

	rows, err := mc.query(query, dargs)
	if err != nil {
		mc.finish()
		return nil, err
	}
	rows.finish = mc.finish
	return rows, err
}

func (mc *mysqlConn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) {
	dargs, err := namedValueToValue(args)
	if err != nil {
		return nil, err
	}

	if err := mc.watchCancel(ctx); err != nil {
		return nil, err
	}
	defer mc.finish()

	return mc.Exec(query, dargs)
}

func (mc *mysqlConn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) {
	if err := mc.watchCancel(ctx); err != nil {
		return nil, err
	}

	stmt, err := mc.Prepare(query)
	mc.finish()
	if err != nil {
		return nil, err
	}

	select {
	default:
	case <-ctx.Done():
		stmt.Close()
		return nil, ctx.Err()
	}
	return stmt, nil
}

func (stmt *mysqlStmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) {
	dargs, err := namedValueToValue(args)
	if err != nil {
		return nil, err
	}

	if err := stmt.mc.watchCancel(ctx); err != nil {
		return nil, err
	}

	rows, err := stmt.query(dargs)
	if err != nil {
		stmt.mc.finish()
		return nil, err
	}
	rows.finish = stmt.mc.finish
	return rows, err
}

func (stmt *mysqlStmt) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error) {
	dargs, err := namedValueToValue(args)
	if err != nil {
		return nil, err
	}

	if err := stmt.mc.watchCancel(ctx); err != nil {
		return nil, err
	}
	defer stmt.mc.finish()

	return stmt.Exec(dargs)
}

func (mc *mysqlConn) watchCancel(ctx context.Context) error {
	if mc.watching {
		// Reach here if canceled,
		// so the connection is already invalid
		mc.cleanup()
		return nil
	}
	// When ctx is already cancelled, don't watch it.
	if err := ctx.Err(); err != nil {
		return err
	}
	// When ctx is not cancellable, don't watch it.
	if ctx.Done() == nil {
		return nil
	}
	// When watcher is not alive, can't watch it.
	if mc.watcher == nil {
		return nil
	}

	mc.watching = true
	mc.watcher <- ctx
	return nil
}

func (mc *mysqlConn) startWatcher() {
	watcher := make(chan context.Context, 1)
	mc.watcher = watcher
	finished := make(chan struct{})
	mc.finished = finished
	go func() {
		for {
			var ctx context.Context
			select {
			case ctx = <-watcher:
			case <-mc.closech:
				return
			}

			select {
			case <-ctx.Done():
				mc.cancel(ctx.Err())
			case <-finished:
			case <-mc.closech:
				return
			}
		}
	}()
}

func (mc *mysqlConn) CheckNamedValue(nv *driver.NamedValue) (err error) {
	nv.Value, err = converter{}.ConvertValue(nv.Value)
	return
}

// ResetSession implements driver.SessionResetter.
// (From Go 1.10)
func (mc *mysqlConn) ResetSession(ctx context.Context) error {
	if mc.closed.Load() || mc.buf.busy() {
		return driver.ErrBadConn
	}

	// Perform a stale connection check. We only perform this check for
	// the first query on a connection that has been checked out of the
	// connection pool: a fresh connection from the pool is more likely
	// to be stale, and it has not performed any previous writes that
	// could cause data corruption, so it's safe to return ErrBadConn
	// if the check fails.
	if mc.cfg.CheckConnLiveness {
		conn := mc.netConn
		if mc.rawConn != nil {
			conn = mc.rawConn
		}
		var err error
		if mc.cfg.ReadTimeout != 0 {
			err = conn.SetReadDeadline(time.Now().Add(mc.cfg.ReadTimeout))
		}
		if err == nil {
			err = connCheck(conn)
		}
		if err != nil {
			mc.log("closing bad idle connection: ", err)
			return driver.ErrBadConn
		}
	}

	return nil
}

// IsValid implements driver.Validator interface
// (From Go 1.15)
func (mc *mysqlConn) IsValid() bool {
	return !mc.closed.Load() && !mc.buf.busy()
}

var _ driver.SessionResetter = &mysqlConn{}
var _ driver.Validator = &mysqlConn{}


================================================
FILE: connection_test.go
================================================
// Go MySQL Driver - A MySQL-Driver for Go's database/sql package
//
// Copyright 2016 The Go-MySQL-Driver Authors. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.

package mysql

import (
	"context"
	"database/sql/driver"
	"encoding/json"
	"errors"
	"net"
	"testing"
)

func TestInterpolateParams(t *testing.T) {
	mc := &mysqlConn{
		buf:              newBuffer(),
		maxAllowedPacket: maxPacketSize,
		cfg: &Config{
			InterpolateParams: true,
		},
	}

	q, err := mc.interpolateParams("SELECT ?+?", []driver.Value{int64(42), "gopher"})
	if err != nil {
		t.Errorf("Expected err=nil, got %#v", err)
		return
	}
	expected := `SELECT 42+'gopher'`
	if q != expected {
		t.Errorf("Expected: %q\nGot: %q", expected, q)
	}
}

func TestInterpolateParamsJSONRawMessage(t *testing.T) {
	mc := &mysqlConn{
		buf:              newBuffer(),
		maxAllowedPacket: maxPacketSize,
		cfg: &Config{
			InterpolateParams: true,
		},
	}

	buf, err := json.Marshal(struct {
		Value int `json:"value"`
	}{Value: 42})
	if err != nil {
		t.Errorf("Expected err=nil, got %#v", err)
		return
	}
	q, err := mc.interpolateParams("SELECT ?", []driver.Value{json.RawMessage(buf)})
	if err != nil {
		t.Errorf("Expected err=nil, got %#v", err)
		return
	}
	expected := `SELECT '{\"value\":42}'`
	if q != expected {
		t.Errorf("Expected: %q\nGot: %q", expected, q)
	}
}

func TestInterpolateParamsTooManyPlaceholders(t *testing.T) {
	mc := &mysqlConn{
		buf:              newBuffer(),
		maxAllowedPacket: maxPacketSize,
		cfg: &Config{
			InterpolateParams: true,
		},
	}

	q, err := mc.interpolateParams("SELECT ?+?", []driver.Value{int64(42)})
	if err != driver.ErrSkip {
		t.Errorf("Expected err=driver.ErrSkip, got err=%#v, q=%#v", err, q)
	}
}

// We don't support placeholder in string literal for now.
// https://github.com/go-sql-driver/mysql/pull/490
func TestInterpolateParamsPlaceholderInString(t *testing.T) {
	mc := &mysqlConn{
		buf:              newBuffer(),
		maxAllowedPacket: maxPacketSize,
		cfg: &Config{
			InterpolateParams: true,
		},
	}

	q, err := mc.interpolateParams("SELECT 'abc?xyz',?", []driver.Value{int64(42)})
	// When InterpolateParams support string literal, this should return `"SELECT 'abc?xyz', 42`
	if err != driver.ErrSkip {
		t.Errorf("Expected err=driver.ErrSkip, got err=%#v, q=%#v", err, q)
	}
}

func TestInterpolateParamsUint64(t *testing.T) {
	mc := &mysqlConn{
		buf:              newBuffer(),
		maxAllowedPacket: maxPacketSize,
		cfg: &Config{
			InterpolateParams: true,
		},
	}

	q, err := mc.interpolateParams("SELECT ?", []driver.Value{uint64(42)})
	if err != nil {
		t.Errorf("Expected err=nil, got err=%#v, q=%#v", err, q)
	}
	if q != "SELECT 42" {
		t.Errorf("Expected uint64 interpolation to work, got q=%#v", q)
	}
}

func TestCheckNamedValue(t *testing.T) {
	value := driver.NamedValue{Value: ^uint64(0)}
	mc := &mysqlConn{}
	err := mc.CheckNamedValue(&value)

	if err != nil {
		t.Fatal("uint64 high-bit not convertible", err)
	}

	if value.Value != ^uint64(0) {
		t.Fatalf("uint64 high-bit converted, got %#v %T", value.Value, value.Value)
	}
}

// TestCleanCancel tests passed context is cancelled at start.
// No packet should be sent.  Connection should keep current status.
func TestCleanCancel(t *testing.T) {
	mc := &mysqlConn{
		closech: make(chan struct{}),
	}
	mc.startWatcher()
	defer mc.cleanup()

	ctx, cancel := context.WithCancel(context.Background())
	cancel()

	for range 3 { // Repeat same behavior
		err := mc.Ping(ctx)
		if err != context.Canceled {
			t.Errorf("expected context.Canceled, got %#v", err)
		}

		if mc.closed.Load() {
			t.Error("expected mc is not closed, closed actually")
		}

		if mc.watching {
			t.Error("expected watching is false, but true")
		}
	}
}

func TestPingMarkBadConnection(t *testing.T) {
	nc := badConnection{err: errors.New("boom")}
	mc := &mysqlConn{
		netConn:          nc,
		buf:              newBuffer(),
		maxAllowedPacket: defaultMaxAllowedPacket,
		closech:          make(chan struct{}),
		cfg:              NewConfig(),
	}

	err := mc.Ping(context.Background())

	if err != driver.ErrBadConn {
		t.Errorf("expected driver.ErrBadConn, got  %#v", err)
	}
}

func TestPingErrInvalidConn(t *testing.T) {
	nc := badConnection{err: errors.New("failed to write"), n: 10}
	mc := &mysqlConn{
		netConn:          nc,
		buf:              newBuffer(),
		maxAllowedPacket: defaultMaxAllowedPacket,
		closech:          make(chan struct{}),
		cfg:              NewConfig(),
	}

	err := mc.Ping(context.Background())

	if err != nc.err {
		t.Errorf("expected %#v, got  %#v", nc.err, err)
	}
}

type badConnection struct {
	n   int
	err error
	net.Conn
}

func (bc badConnection) Write(b []byte) (n int, err error) {
	return bc.n, bc.err
}

func (bc badConnection) Close() error {
	return nil
}


================================================
FILE: connector.go
================================================
// Go MySQL Driver - A MySQL-Driver for Go's database/sql package
//
// Copyright 2018 The Go-MySQL-Driver Authors. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.

package mysql

import (
	"context"
	"database/sql/driver"
	"fmt"
	"net"
	"os"
	"strconv"
	"strings"
)

type connector struct {
	cfg               *Config // immutable private copy.
	encodedAttributes string  // Encoded connection attributes.
}

func encodeConnectionAttributes(cfg *Config) string {
	connAttrsBuf := make([]byte, 0)

	// default connection attributes
	connAttrsBuf = appendLengthEncodedString(connAttrsBuf, connAttrClientName)
	connAttrsBuf = appendLengthEncodedString(connAttrsBuf, connAttrClientNameValue)
	connAttrsBuf = appendLengthEncodedString(connAttrsBuf, connAttrOS)
	connAttrsBuf = appendLengthEncodedString(connAttrsBuf, connAttrOSValue)
	connAttrsBuf = appendLengthEncodedString(connAttrsBuf, connAttrPlatform)
	connAttrsBuf = appendLengthEncodedString(connAttrsBuf, connAttrPlatformValue)
	connAttrsBuf = appendLengthEncodedString(connAttrsBuf, connAttrPid)
	connAttrsBuf = appendLengthEncodedString(connAttrsBuf, strconv.Itoa(os.Getpid()))
	serverHost, _, _ := net.SplitHostPort(cfg.Addr)
	if serverHost != "" {
		connAttrsBuf = appendLengthEncodedString(connAttrsBuf, connAttrServerHost)
		connAttrsBuf = appendLengthEncodedString(connAttrsBuf, serverHost)
	}

	// user-defined connection attributes
	for _, connAttr := range strings.Split(cfg.ConnectionAttributes, ",") {
		k, v, found := strings.Cut(connAttr, ":")
		if !found {
			continue
		}
		connAttrsBuf = appendLengthEncodedString(connAttrsBuf, k)
		connAttrsBuf = appendLengthEncodedString(connAttrsBuf, v)
	}

	return string(connAttrsBuf)
}

func newConnector(cfg *Config) *connector {
	encodedAttributes := encodeConnectionAttributes(cfg)
	return &connector{
		cfg:               cfg,
		encodedAttributes: encodedAttributes,
	}
}

// Connect implements driver.Connector interface.
// Connect returns a connection to the database.
func (c *connector) Connect(ctx context.Context) (driver.Conn, error) {
	var err error

	// Invoke beforeConnect if present, with a copy of the configuration
	cfg := c.cfg
	if c.cfg.beforeConnect != nil {
		cfg = c.cfg.Clone()
		err = c.cfg.beforeConnect(ctx, cfg)
		if err != nil {
			return nil, err
		}
	}

	// New mysqlConn
	mc := &mysqlConn{
		maxAllowedPacket: maxPacketSize,
		maxWriteSize:     maxPacketSize - 1,
		closech:          make(chan struct{}),
		cfg:              cfg,
		connector:        c,
	}
	mc.parseTime = mc.cfg.ParseTime

	// Connect to Server
	dctx := ctx
	if mc.cfg.Timeout > 0 {
		var cancel context.CancelFunc
		dctx, cancel = context.WithTimeout(ctx, c.cfg.Timeout)
		defer cancel()
	}

	if c.cfg.DialFunc != nil {
		mc.netConn, err = c.cfg.DialFunc(dctx, mc.cfg.Net, mc.cfg.Addr)
	} else {
		dialsLock.RLock()
		dial, ok := dials[mc.cfg.Net]
		dialsLock.RUnlock()
		if ok {
			mc.netConn, err = dial(dctx, mc.cfg.Addr)
		} else {
			nd := net.Dialer{}
			mc.netConn, err = nd.DialContext(dctx, mc.cfg.Net, mc.cfg.Addr)
		}
	}
	if err != nil {
		return nil, err
	}
	mc.rawConn = mc.netConn

	// Enable TCP Keepalives on TCP connections
	if tc, ok := mc.netConn.(*net.TCPConn); ok {
		if err := tc.SetKeepAlive(true); err != nil {
			c.cfg.Logger.Print(err)
		}
	}

	// Call startWatcher for context support (From Go 1.8)
	mc.startWatcher()
	if err := mc.watchCancel(ctx); err != nil {
		mc.cleanup()
		return nil, err
	}
	defer mc.finish()

	mc.buf = newBuffer()

	// Reading Handshake Initialization Packet
	authData, serverCapabilities, serverExtCapabilities, plugin, err := mc.readHandshakePacket()
	if err != nil {
		mc.cleanup()
		return nil, err
	}

	if plugin == "" {
		plugin = defaultAuthPlugin
	}

	// Send Client Authentication Packet
	authResp, err := mc.auth(authData, plugin)
	if err != nil {
		// try the default auth plugin, if using the requested plugin failed
		c.cfg.Logger.Print("could not use requested auth plugin '"+plugin+"': ", err.Error())
		plugin = defaultAuthPlugin
		authResp, err = mc.auth(authData, plugin)
		if err != nil {
			mc.cleanup()
			return nil, err
		}
	}
	mc.initCapabilities(serverCapabilities, serverExtCapabilities, mc.cfg)
	if err = mc.writeHandshakeResponsePacket(authResp, plugin); err != nil {
		mc.cleanup()
		return nil, err
	}

	// Handle response to auth packet, switch methods if possible
	if err = mc.handleAuthResult(authData, plugin); err != nil {
		// Authentication failed and MySQL has already closed the connection
		// (https://dev.mysql.com/doc/dev/mysql-server/latest/page_protocol_connection_phase.html#sect_protocol_connection_phase_fast_path_fails).
		// Do not send COM_QUIT, just cleanup and return the error.
		mc.cleanup()
		return nil, err
	}

	// compression is enabled after auth, not right after sending handshake response.
	if mc.capabilities&clientCompress > 0 {
		mc.compress = true
		mc.compIO = newCompIO(mc)
	}
	if mc.cfg.MaxAllowedPacket > 0 {
		mc.maxAllowedPacket = mc.cfg.MaxAllowedPacket
	} else {
		// Get max allowed packet size
		maxap, err := mc.getSystemVar("max_allowed_packet")
		if err != nil {
			mc.Close()
			return nil, err
		}
		n, err := strconv.Atoi(string(maxap))
		if err != nil {
			mc.Close()
			return nil, fmt.Errorf("invalid max_allowed_packet value (%q): %w", maxap, err)
		}
		mc.maxAllowedPacket = n - 1
	}
	if mc.maxAllowedPacket < maxPacketSize {
		mc.maxWriteSize = mc.maxAllowedPacket
	}

	// Charset: character_set_connection, character_set_client, character_set_results
	if len(mc.cfg.charsets) > 0 {
		for _, cs := range mc.cfg.charsets {
			// ignore errors here - a charset may not exist
			if mc.cfg.Collation != "" {
				err = mc.exec("SET NAMES " + cs + " COLLATE " + mc.cfg.Collation)
			} else {
				err = mc.exec("SET NAMES " + cs)
			}
			if err == nil {
				break
			}
		}
		if err != nil {
			mc.Close()
			return nil, err
		}
	}

	// Handle DSN Params
	err = mc.handleParams()
	if err != nil {
		mc.Close()
		return nil, err
	}

	return mc, nil
}

// Driver implements driver.Connector interface.
// Driver returns &MySQLDriver{}.
func (c *connector) Driver() driver.Driver {
	return &MySQLDriver{}
}


================================================
FILE: connector_test.go
================================================
package mysql

import (
	"context"
	"net"
	"testing"
	"time"
)

func TestConnectorReturnsTimeout(t *testing.T) {
	connector := newConnector(&Config{
		Net:     "tcp",
		Addr:    "1.1.1.1:1234",
		Timeout: 10 * time.Millisecond,
	})

	_, err := connector.Connect(context.Background())
	if err == nil {
		t.Fatal("error expected")
	}

	if nerr, ok := err.(*net.OpError); ok {
		expected := "dial tcp 1.1.1.1:1234: i/o timeout"
		if nerr.Error() != expected {
			t.Fatalf("expected %q, got %q", expected, nerr.Error())
		}
	} else {
		t.Fatalf("expected %T, got %T", nerr, err)
	}
}


================================================
FILE: const.go
================================================
// Go MySQL Driver - A MySQL-Driver for Go's database/sql package
//
// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.

package mysql

import "runtime"

const (
	debug = false // for debugging. Set true only in development.

	defaultAuthPlugin       = "mysql_native_password"
	defaultMaxAllowedPacket = 64 << 20 // 64 MiB. See https://github.com/go-sql-driver/mysql/issues/1355
	minProtocolVersion      = 10
	maxPacketSize           = 1<<24 - 1
	timeFormat              = "2006-01-02 15:04:05.999999"

	// Connection attributes
	// See https://dev.mysql.com/doc/refman/8.0/en/performance-schema-connection-attribute-tables.html#performance-schema-connection-attributes-available
	connAttrClientName      = "_client_name"
	connAttrClientNameValue = "Go-MySQL-Driver"
	connAttrOS              = "_os"
	connAttrOSValue         = runtime.GOOS
	connAttrPlatform        = "_platform"
	connAttrPlatformValue   = runtime.GOARCH
	connAttrPid             = "_pid"
	connAttrServerHost      = "_server_host"
)

// MySQL constants documentation:
// https://dev.mysql.com/doc/dev/mysql-server/latest/PAGE_PROTOCOL.html

const (
	iOK           byte = 0x00
	iAuthMoreData byte = 0x01
	iLocalInFile  byte = 0xfb
	iEOF          byte = 0xfe
	iERR          byte = 0xff
)

// https://dev.mysql.com/doc/dev/mysql-server/latest/group__group__cs__capabilities__flags.html
// https://mariadb.com/kb/en/connection/#capabilities
type capabilityFlag uint32

const (
	clientMySQL capabilityFlag = 1 << iota
	clientFoundRows
	clientLongFlag
	clientConnectWithDB
	clientNoSchema
	clientCompress
	clientODBC
	clientLocalFiles
	clientIgnoreSpace
	clientProtocol41
	clientInteractive
	clientSSL
	clientIgnoreSIGPIPE
	clientTransactions
	clientReserved
	clientSecureConn
	clientMultiStatements
	clientMultiResults
	clientPSMultiResults
	clientPluginAuth
	clientConnectAttrs
	clientPluginAuthLenEncClientData
	clientCanHandleExpiredPasswords
	clientSessionTrack
	clientDeprecateEOF
)

// https://mariadb.com/kb/en/connection/#capabilities
type extendedCapabilityFlag uint32

const (
	progressIndicator extendedCapabilityFlag = 1 << iota
	clientComMulti
	clientStmtBulkOperations
	clientExtendedMetadata
	clientCacheMetadata
	clientUnitBulkResult
)

const (
	comQuit byte = iota + 1
	comInitDB
	comQuery
	comFieldList
	comCreateDB
	comDropDB
	comRefresh
	comShutdown
	comStatistics
	comProcessInfo
	comConnect
	comProcessKill
	comDebug
	comPing
	comTime
	comDelayedInsert
	comChangeUser
	comBinlogDump
	comTableDump
	comConnectOut
	comRegisterSlave
	comStmtPrepare
	comStmtExecute
	comStmtSendLongData
	comStmtClose
	comStmtReset
	comSetOption
	comStmtFetch
)

// https://dev.mysql.com/doc/internals/en/com-query-response.html#packet-Protocol::ColumnType
type fieldType byte

const (
	fieldTypeDecimal fieldType = iota
	fieldTypeTiny
	fieldTypeShort
	fieldTypeLong
	fieldTypeFloat
	fieldTypeDouble
	fieldTypeNULL
	fieldTypeTimestamp
	fieldTypeLongLong
	fieldTypeInt24
	fieldTypeDate
	fieldTypeTime
	fieldTypeDateTime
	fieldTypeYear
	fieldTypeNewDate
	fieldTypeVarChar
	fieldTypeBit
)
const (
	fieldTypeVector fieldType = iota + 0xf2
	fieldTypeInvalid
	fieldTypeBool
	fieldTypeJSON
	fieldTypeNewDecimal
	fieldTypeEnum
	fieldTypeSet
	fieldTypeTinyBLOB
	fieldTypeMediumBLOB
	fieldTypeLongBLOB
	fieldTypeBLOB
	fieldTypeVarString
	fieldTypeString
	fieldTypeGeometry
)

type fieldFlag uint16

const (
	flagNotNULL fieldFlag = 1 << iota
	flagPriKey
	flagUniqueKey
	flagMultipleKey
	flagBLOB
	flagUnsigned
	flagZeroFill
	flagBinary
	flagEnum
	flagAutoIncrement
	flagTimestamp
	flagSet
	flagUnknown1
	flagUnknown2
	flagUnknown3
	flagUnknown4
)

// http://dev.mysql.com/doc/internals/en/status-flags.html
type statusFlag uint16

const (
	statusInTrans statusFlag = 1 << iota
	statusInAutocommit
	statusReserved // Not in documentation
	statusMoreResultsExists
	statusNoGoodIndexUsed
	statusNoIndexUsed
	statusCursorExists
	statusLastRowSent
	statusDbDropped
	statusNoBackslashEscapes
	statusMetadataChanged
	statusQueryWasSlow
	statusPsOutParams
	statusInTransReadonly
	statusSessionStateChanged
)

const (
	cachingSha2PasswordRequestPublicKey          = 2
	cachingSha2PasswordFastAuthSuccess           = 3
	cachingSha2PasswordPerformFullAuthentication = 4
)


================================================
FILE: driver.go
================================================
// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.

// Package mysql provides a MySQL driver for Go's database/sql package.
//
// The driver should be used via the database/sql package:
//
//	import "database/sql"
//	import _ "github.com/go-sql-driver/mysql"
//
//	db, err := sql.Open("mysql", "user:password@/dbname")
//
// See https://github.com/go-sql-driver/mysql#usage for details
package mysql

import (
	"context"
	"database/sql"
	"database/sql/driver"
	"net"
	"sync"
)

// MySQLDriver is exported to make the driver directly accessible.
// In general the driver is used via the database/sql package.
type MySQLDriver struct{}

// DialFunc is a function which can be used to establish the network connection.
// Custom dial functions must be registered with RegisterDial
//
// Deprecated: users should register a DialContextFunc instead
type DialFunc func(addr string) (net.Conn, error)

// DialContextFunc is a function which can be used to establish the network connection.
// Custom dial functions must be registered with RegisterDialContext
type DialContextFunc func(ctx context.Context, addr string) (net.Conn, error)

var (
	dialsLock sync.RWMutex
	dials     map[string]DialContextFunc
)

// RegisterDialContext registers a custom dial function. It can then be used by the
// network address mynet(addr), where mynet is the registered new network.
// The current context for the connection and its address is passed to the dial function.
func RegisterDialContext(net string, dial DialContextFunc) {
	dialsLock.Lock()
	defer dialsLock.Unlock()
	if dials == nil {
		dials = make(map[string]DialContextFunc)
	}
	dials[net] = dial
}

// DeregisterDialContext removes the custom dial function registered with the given net.
func DeregisterDialContext(net string) {
	dialsLock.Lock()
	defer dialsLock.Unlock()
	if dials != nil {
		delete(dials, net)
	}
}

// RegisterDial registers a custom dial function. It can then be used by the
// network address mynet(addr), where mynet is the registered new network.
// addr is passed as a parameter to the dial function.
//
// Deprecated: users should call RegisterDialContext instead
func RegisterDial(network string, dial DialFunc) {
	RegisterDialContext(network, func(_ context.Context, addr string) (net.Conn, error) {
		return dial(addr)
	})
}

// Open new Connection.
// See https://github.com/go-sql-driver/mysql#dsn-data-source-name for how
// the DSN string is formatted
func (d MySQLDriver) Open(dsn string) (driver.Conn, error) {
	cfg, err := ParseDSN(dsn)
	if err != nil {
		return nil, err
	}
	c := newConnector(cfg)
	return c.Connect(context.Background())
}

// This variable can be replaced with -ldflags like below:
// go build "-ldflags=-X github.com/go-sql-driver/mysql.driverName=custom"
var driverName = "mysql"

func init() {
	if driverName != "" {
		sql.Register(driverName, &MySQLDriv
Download .txt
gitextract_ul7tfipz/

├── .github/
│   ├── CONTRIBUTING.md
│   ├── ISSUE_TEMPLATE.md
│   ├── PULL_REQUEST_TEMPLATE.md
│   └── workflows/
│       ├── codeql.yml
│       └── test.yml
├── .gitignore
├── AUTHORS
├── CHANGELOG.md
├── LICENSE
├── README.md
├── auth.go
├── auth_test.go
├── benchmark_test.go
├── buffer.go
├── collations.go
├── compress.go
├── compress_test.go
├── conncheck.go
├── conncheck_dummy.go
├── conncheck_test.go
├── connection.go
├── connection_test.go
├── connector.go
├── connector_test.go
├── const.go
├── driver.go
├── driver_test.go
├── dsn.go
├── dsn_fuzz_test.go
├── dsn_test.go
├── errors.go
├── errors_test.go
├── fields.go
├── go.mod
├── go.sum
├── infile.go
├── nulltime.go
├── nulltime_test.go
├── packets.go
├── packets_test.go
├── result.go
├── rows.go
├── statement.go
├── statement_test.go
├── transaction.go
├── utils.go
└── utils_test.go
Download .txt
SYMBOL INDEX (630 symbols across 35 files)

FILE: auth.go
  function RegisterServerPubKey (line 59) | func RegisterServerPubKey(name string, pubKey *rsa.PublicKey) {
  function DeregisterServerPubKey (line 70) | func DeregisterServerPubKey(name string) {
  function getServerPubKey (line 78) | func getServerPubKey(name string) (pubKey *rsa.PublicKey) {
  type myRnd (line 89) | type myRnd struct
    method NextByte (line 106) | func (r *myRnd) NextByte() byte {
  constant myRndMaxVal (line 93) | myRndMaxVal = 0x3FFFFFFF
  function newMyRnd (line 96) | func newMyRnd(seed1, seed2 uint32) *myRnd {
  function pwHash (line 114) | func pwHash(password []byte) (result [2]uint32) {
  function scrambleOldPassword (line 141) | func scrambleOldPassword(scramble []byte, password string) []byte {
  function scramblePassword (line 163) | func scramblePassword(scramble []byte, password string) []byte {
  function scrambleSHA256Password (line 193) | func scrambleSHA256Password(scramble []byte, password string) []byte {
  function encryptPassword (line 220) | func encryptPassword(password string, seed []byte, pub *rsa.PublicKey) (...
  function authEd25519 (line 232) | func authEd25519(scramble []byte, password string) ([]byte, error) {
  method sendEncryptedPassword (line 269) | func (mc *mysqlConn) sendEncryptedPassword(seed []byte, pub *rsa.PublicK...
  method auth (line 277) | func (mc *mysqlConn) auth(authData []byte, plugin string) ([]byte, error) {
  method handleAuthResult (line 346) | func (mc *mysqlConn) handleAuthResult(oldAuthData []byte, plugin string)...

FILE: auth_test.go
  function init (line 33) | func init() {
  function TestScrambleOldPass (line 42) | func TestScrambleOldPass(t *testing.T) {
  function TestScrambleSHA256Pass (line 61) | func TestScrambleSHA256Pass(t *testing.T) {
  function TestAuthFastCachingSHA256PasswordCached (line 78) | func TestAuthFastCachingSHA256PasswordCached(t *testing.T) {
  function TestAuthFastCachingSHA256PasswordEmpty (line 123) | func TestAuthFastCachingSHA256PasswordEmpty(t *testing.T) {
  function TestAuthFastCachingSHA256PasswordFullRSA (line 165) | func TestAuthFastCachingSHA256PasswordFullRSA(t *testing.T) {
  function TestAuthFastCachingSHA256PasswordFullRSAWithKey (line 220) | func TestAuthFastCachingSHA256PasswordFullRSAWithKey(t *testing.T) {
  function TestAuthFastCachingSHA256PasswordFullSecure (line 273) | func TestAuthFastCachingSHA256PasswordFullSecure(t *testing.T) {
  function TestAuthFastCleartextPasswordNotAllowed (line 329) | func TestAuthFastCleartextPasswordNotAllowed(t *testing.T) {
  function TestAuthFastCleartextPassword (line 345) | func TestAuthFastCleartextPassword(t *testing.T) {
  function TestAuthFastCleartextPasswordEmpty (line 388) | func TestAuthFastCleartextPasswordEmpty(t *testing.T) {
  function TestAuthFastNativePasswordNotAllowed (line 431) | func TestAuthFastNativePasswordNotAllowed(t *testing.T) {
  function TestAuthFastNativePassword (line 448) | func TestAuthFastNativePassword(t *testing.T) {
  function TestAuthFastNativePasswordEmpty (line 491) | func TestAuthFastNativePasswordEmpty(t *testing.T) {
  function TestAuthFastSHA256PasswordEmpty (line 533) | func TestAuthFastSHA256PasswordEmpty(t *testing.T) {
  function TestAuthFastSHA256PasswordRSA (line 581) | func TestAuthFastSHA256PasswordRSA(t *testing.T) {
  function TestAuthFastSHA256PasswordRSAWithKey (line 629) | func TestAuthFastSHA256PasswordRSAWithKey(t *testing.T) {
  function TestAuthFastSHA256PasswordSecure (line 659) | func TestAuthFastSHA256PasswordSecure(t *testing.T) {
  function TestAuthSwitchCachingSHA256PasswordCached (line 711) | func TestAuthSwitchCachingSHA256PasswordCached(t *testing.T) {
  function TestAuthSwitchCachingSHA256PasswordEmpty (line 746) | func TestAuthSwitchCachingSHA256PasswordEmpty(t *testing.T) {
  function TestAuthSwitchCachingSHA256PasswordFullRSA (line 774) | func TestAuthSwitchCachingSHA256PasswordFullRSA(t *testing.T) {
  function TestAuthSwitchCachingSHA256PasswordFullRSAWithKey (line 821) | func TestAuthSwitchCachingSHA256PasswordFullRSAWithKey(t *testing.T) {
  function TestAuthSwitchCachingSHA256PasswordFullSecure (line 863) | func TestAuthSwitchCachingSHA256PasswordFullSecure(t *testing.T) {
  function TestAuthSwitchCleartextPasswordNotAllowed (line 906) | func TestAuthSwitchCleartextPasswordNotAllowed(t *testing.T) {
  function TestAuthSwitchCleartextPassword (line 921) | func TestAuthSwitchCleartextPassword(t *testing.T) {
  function TestAuthSwitchCleartextPasswordEmpty (line 948) | func TestAuthSwitchCleartextPasswordEmpty(t *testing.T) {
  function TestAuthSwitchNativePasswordNotAllowed (line 975) | func TestAuthSwitchNativePasswordNotAllowed(t *testing.T) {
  function TestAuthSwitchNativePassword (line 993) | func TestAuthSwitchNativePassword(t *testing.T) {
  function TestAuthSwitchNativePasswordEmpty (line 1023) | func TestAuthSwitchNativePasswordEmpty(t *testing.T) {
  function TestAuthSwitchOldPasswordNotAllowed (line 1052) | func TestAuthSwitchOldPasswordNotAllowed(t *testing.T) {
  function TestOldAuthSwitchNotAllowed (line 1069) | func TestOldAuthSwitchNotAllowed(t *testing.T) {
  function TestAuthSwitchOldPassword (line 1084) | func TestAuthSwitchOldPassword(t *testing.T) {
  function TestOldAuthSwitch (line 1113) | func TestOldAuthSwitch(t *testing.T) {
  function TestAuthSwitchOldPasswordEmpty (line 1138) | func TestAuthSwitchOldPasswordEmpty(t *testing.T) {
  function TestOldAuthSwitchPasswordEmpty (line 1167) | func TestOldAuthSwitchPasswordEmpty(t *testing.T) {
  function TestAuthSwitchSHA256PasswordEmpty (line 1193) | func TestAuthSwitchSHA256PasswordEmpty(t *testing.T) {
  function TestAuthSwitchSHA256PasswordRSA (line 1225) | func TestAuthSwitchSHA256PasswordRSA(t *testing.T) {
  function TestAuthSwitchSHA256PasswordRSAWithKey (line 1263) | func TestAuthSwitchSHA256PasswordRSAWithKey(t *testing.T) {
  function TestAuthSwitchSHA256PasswordSecure (line 1296) | func TestAuthSwitchSHA256PasswordSecure(t *testing.T) {
  function TestEd25519Auth (line 1333) | func TestEd25519Auth(t *testing.T) {

FILE: benchmark_test.go
  type TB (line 26) | type TB
    method check (line 28) | func (tb *TB) check(err error) {
    method checkDB (line 34) | func (tb *TB) checkDB(db *sql.DB, err error) *sql.DB {
    method checkRows (line 39) | func (tb *TB) checkRows(rows *sql.Rows, err error) *sql.Rows {
    method checkStmt (line 44) | func (tb *TB) checkStmt(stmt *sql.Stmt, err error) *sql.Stmt {
  function initDB (line 49) | func initDB(b *testing.B, compress bool, queries ...string) *sql.DB {
  constant concurrencyLevel (line 64) | concurrencyLevel = 10
  function BenchmarkQuery (line 66) | func BenchmarkQuery(b *testing.B) {
  function BenchmarkQueryCompressed (line 70) | func BenchmarkQueryCompressed(b *testing.B) {
  function benchmarkQuery (line 74) | func benchmarkQuery(b *testing.B, compr bool) {
  function BenchmarkExec (line 115) | func BenchmarkExec(b *testing.B) {
  function initRoundtripBenchmarks (line 152) | func initRoundtripBenchmarks() ([]byte, int, int) {
  function BenchmarkRoundtripTxt (line 159) | func BenchmarkRoundtripTxt(b *testing.B) {
  function BenchmarkRoundtripBin (line 194) | func BenchmarkRoundtripBin(b *testing.B) {
  function BenchmarkInterpolation (line 229) | func BenchmarkInterpolation(b *testing.B) {
  function benchmarkQueryContext (line 260) | func benchmarkQueryContext(b *testing.B, db *sql.DB, p int) {
  function BenchmarkQueryContext (line 283) | func BenchmarkQueryContext(b *testing.B) {
  function benchmarkExecContext (line 298) | func benchmarkExecContext(b *testing.B, db *sql.DB, p int) {
  function BenchmarkExecContext (line 319) | func BenchmarkExecContext(b *testing.B) {
  function BenchmarkQueryRawBytes (line 336) | func BenchmarkQueryRawBytes(b *testing.B) {
  function benchmark10kRows (line 388) | func benchmark10kRows(b *testing.B, compress bool) {
  function BenchmarkReceive10kRows (line 451) | func BenchmarkReceive10kRows(b *testing.B) {
  function BenchmarkReceive10kRowsCompressed (line 455) | func BenchmarkReceive10kRowsCompressed(b *testing.B) {
  function BenchmarkReceiveMetadata (line 460) | func BenchmarkReceiveMetadata(b *testing.B) {

FILE: buffer.go
  constant defaultBufSize (line 15) | defaultBufSize = 4096
  constant maxCachedBufSize (line 16) | maxCachedBufSize = 256 * 1024
  type readerFunc (line 21) | type readerFunc
  type buffer (line 28) | type buffer struct
    method busy (line 41) | func (b *buffer) busy() bool {
    method len (line 46) | func (b *buffer) len() int {
    method fill (line 51) | func (b *buffer) fill(need int, r readerFunc) error {
    method readNext (line 94) | func (b *buffer) readNext(need int) []byte {
    method takeBuffer (line 104) | func (b *buffer) takeBuffer(length int) ([]byte, error) {
    method takeSmallBuffer (line 126) | func (b *buffer) takeSmallBuffer(length int) ([]byte, error) {
    method takeCompleteBuffer (line 137) | func (b *buffer) takeCompleteBuffer() ([]byte, error) {
    method store (line 145) | func (b *buffer) store(buf []byte) {
  function newBuffer (line 34) | func newBuffer() buffer {

FILE: collations.go
  constant defaultCollationID (line 11) | defaultCollationID = 45
  constant binaryCollationID (line 12) | binaryCollationID = 63

FILE: compress.go
  function init (line 24) | func init() {
  function zDecompress (line 39) | func zDecompress(src []byte, dst *bytes.Buffer) (int, error) {
  function zCompress (line 61) | func zCompress(src []byte, dst io.Writer) error {
  type compIO (line 72) | type compIO struct
    method reset (line 83) | func (c *compIO) reset() {
    method readNext (line 87) | func (c *compIO) readNext(need int) ([]byte, error) {
    method readCompressedPacket (line 97) | func (c *compIO) readCompressedPacket() error {
    method writePackets (line 152) | func (c *compIO) writePackets(packets []byte) (int, error) {
    method writeCompressedPacket (line 197) | func (c *compIO) writeCompressedPacket(data []byte, uncompressedLen in...
  function newCompIO (line 77) | func newCompIO(mc *mysqlConn) *compIO {
  constant minCompressLength (line 147) | minCompressLength = 150
  constant maxPayloadLen (line 148) | maxPayloadLen = maxPacketSize - 4

FILE: compress_test.go
  function makeRandByteSlice (line 18) | func makeRandByteSlice(size int) []byte {
  function compressHelper (line 25) | func compressHelper(t *testing.T, mc *mysqlConn, uncompressedPacket []by...
  function uncompressHelper (line 38) | func uncompressHelper(t *testing.T, mc *mysqlConn, compressedPacket []by...
  function roundtripHelper (line 54) | func roundtripHelper(t *testing.T, cSend *mysqlConn, cReceive *mysqlConn...
  function TestRoundtrip (line 60) | func TestRoundtrip(t *testing.T) {

FILE: conncheck.go
  function connCheck (line 23) | func connCheck(conn net.Conn) error {

FILE: conncheck_dummy.go
  function connCheck (line 16) | func connCheck(conn net.Conn) error {

FILE: conncheck_test.go
  function TestStaleConnectionChecks (line 19) | func TestStaleConnectionChecks(t *testing.T) {

FILE: connection.go
  type mysqlConn (line 26) | type mysqlConn struct
    method log (line 54) | func (mc *mysqlConn) log(v ...any) {
    method readWithTimeout (line 68) | func (mc *mysqlConn) readWithTimeout(b []byte) (int, error) {
    method writeWithTimeout (line 78) | func (mc *mysqlConn) writeWithTimeout(b []byte) (int, error) {
    method resetSequence (line 88) | func (mc *mysqlConn) resetSequence() {
    method syncSequence (line 94) | func (mc *mysqlConn) syncSequence() {
    method handleParams (line 106) | func (mc *mysqlConn) handleParams() (err error) {
    method markBadConn (line 131) | func (mc *mysqlConn) markBadConn(err error) error {
    method Begin (line 138) | func (mc *mysqlConn) Begin() (driver.Tx, error) {
    method begin (line 142) | func (mc *mysqlConn) begin(readOnly bool) (driver.Tx, error) {
    method Close (line 159) | func (mc *mysqlConn) Close() (err error) {
    method close (line 169) | func (mc *mysqlConn) close() {
    method cleanup (line 178) | func (mc *mysqlConn) cleanup() {
    method error (line 197) | func (mc *mysqlConn) error() error {
    method Prepare (line 207) | func (mc *mysqlConn) Prepare(query string) (driver.Stmt, error) {
    method interpolateParams (line 248) | func (mc *mysqlConn) interpolateParams(query string, args []driver.Val...
    method Exec (line 349) | func (mc *mysqlConn) Exec(query string, args []driver.Value) (driver.R...
    method exec (line 374) | func (mc *mysqlConn) exec(query string) error {
    method Query (line 402) | func (mc *mysqlConn) Query(query string, args []driver.Value) (driver....
    method query (line 406) | func (mc *mysqlConn) query(query string, args []driver.Value) (*textRo...
    method getSystemVar (line 457) | func (mc *mysqlConn) getSystemVar(name string) ([]byte, error) {
    method cancel (line 487) | func (mc *mysqlConn) cancel(err error) {
    method finish (line 493) | func (mc *mysqlConn) finish() {
    method Ping (line 505) | func (mc *mysqlConn) Ping(ctx context.Context) (err error) {
    method BeginTx (line 524) | func (mc *mysqlConn) BeginTx(ctx context.Context, opts driver.TxOption...
    method QueryContext (line 548) | func (mc *mysqlConn) QueryContext(ctx context.Context, query string, a...
    method ExecContext (line 567) | func (mc *mysqlConn) ExecContext(ctx context.Context, query string, ar...
    method PrepareContext (line 581) | func (mc *mysqlConn) PrepareContext(ctx context.Context, query string)...
    method watchCancel (line 634) | func (mc *mysqlConn) watchCancel(ctx context.Context) error {
    method startWatcher (line 659) | func (mc *mysqlConn) startWatcher() {
    method CheckNamedValue (line 684) | func (mc *mysqlConn) CheckNamedValue(nv *driver.NamedValue) (err error) {
    method ResetSession (line 691) | func (mc *mysqlConn) ResetSession(ctx context.Context) error {
    method IsValid (line 725) | func (mc *mysqlConn) IsValid() bool {
  method QueryContext (line 601) | func (stmt *mysqlStmt) QueryContext(ctx context.Context, args []driver.N...
  method ExecContext (line 620) | func (stmt *mysqlStmt) ExecContext(ctx context.Context, args []driver.Na...

FILE: connection_test.go
  function TestInterpolateParams (line 20) | func TestInterpolateParams(t *testing.T) {
  function TestInterpolateParamsJSONRawMessage (line 40) | func TestInterpolateParamsJSONRawMessage(t *testing.T) {
  function TestInterpolateParamsTooManyPlaceholders (line 67) | func TestInterpolateParamsTooManyPlaceholders(t *testing.T) {
  function TestInterpolateParamsPlaceholderInString (line 84) | func TestInterpolateParamsPlaceholderInString(t *testing.T) {
  function TestInterpolateParamsUint64 (line 100) | func TestInterpolateParamsUint64(t *testing.T) {
  function TestCheckNamedValue (line 118) | func TestCheckNamedValue(t *testing.T) {
  function TestCleanCancel (line 134) | func TestCleanCancel(t *testing.T) {
  function TestPingMarkBadConnection (line 160) | func TestPingMarkBadConnection(t *testing.T) {
  function TestPingErrInvalidConn (line 177) | func TestPingErrInvalidConn(t *testing.T) {
  type badConnection (line 194) | type badConnection struct
    method Write (line 200) | func (bc badConnection) Write(b []byte) (n int, err error) {
    method Close (line 204) | func (bc badConnection) Close() error {

FILE: connector.go
  type connector (line 21) | type connector struct
    method Connect (line 67) | func (c *connector) Connect(ctx context.Context) (driver.Conn, error) {
    method Driver (line 227) | func (c *connector) Driver() driver.Driver {
  function encodeConnectionAttributes (line 26) | func encodeConnectionAttributes(cfg *Config) string {
  function newConnector (line 57) | func newConnector(cfg *Config) *connector {

FILE: connector_test.go
  function TestConnectorReturnsTimeout (line 10) | func TestConnectorReturnsTimeout(t *testing.T) {

FILE: const.go
  constant debug (line 14) | debug = false
  constant defaultAuthPlugin (line 16) | defaultAuthPlugin       = "mysql_native_password"
  constant defaultMaxAllowedPacket (line 17) | defaultMaxAllowedPacket = 64 << 20
  constant minProtocolVersion (line 18) | minProtocolVersion      = 10
  constant maxPacketSize (line 19) | maxPacketSize           = 1<<24 - 1
  constant timeFormat (line 20) | timeFormat              = "2006-01-02 15:04:05.999999"
  constant connAttrClientName (line 24) | connAttrClientName      = "_client_name"
  constant connAttrClientNameValue (line 25) | connAttrClientNameValue = "Go-MySQL-Driver"
  constant connAttrOS (line 26) | connAttrOS              = "_os"
  constant connAttrOSValue (line 27) | connAttrOSValue         = runtime.GOOS
  constant connAttrPlatform (line 28) | connAttrPlatform        = "_platform"
  constant connAttrPlatformValue (line 29) | connAttrPlatformValue   = runtime.GOARCH
  constant connAttrPid (line 30) | connAttrPid             = "_pid"
  constant connAttrServerHost (line 31) | connAttrServerHost      = "_server_host"
  constant iOK (line 38) | iOK           byte = 0x00
  constant iAuthMoreData (line 39) | iAuthMoreData byte = 0x01
  constant iLocalInFile (line 40) | iLocalInFile  byte = 0xfb
  constant iEOF (line 41) | iEOF          byte = 0xfe
  constant iERR (line 42) | iERR          byte = 0xff
  type capabilityFlag (line 47) | type capabilityFlag
  constant clientMySQL (line 50) | clientMySQL capabilityFlag = 1 << iota
  constant clientFoundRows (line 51) | clientFoundRows
  constant clientLongFlag (line 52) | clientLongFlag
  constant clientConnectWithDB (line 53) | clientConnectWithDB
  constant clientNoSchema (line 54) | clientNoSchema
  constant clientCompress (line 55) | clientCompress
  constant clientODBC (line 56) | clientODBC
  constant clientLocalFiles (line 57) | clientLocalFiles
  constant clientIgnoreSpace (line 58) | clientIgnoreSpace
  constant clientProtocol41 (line 59) | clientProtocol41
  constant clientInteractive (line 60) | clientInteractive
  constant clientSSL (line 61) | clientSSL
  constant clientIgnoreSIGPIPE (line 62) | clientIgnoreSIGPIPE
  constant clientTransactions (line 63) | clientTransactions
  constant clientReserved (line 64) | clientReserved
  constant clientSecureConn (line 65) | clientSecureConn
  constant clientMultiStatements (line 66) | clientMultiStatements
  constant clientMultiResults (line 67) | clientMultiResults
  constant clientPSMultiResults (line 68) | clientPSMultiResults
  constant clientPluginAuth (line 69) | clientPluginAuth
  constant clientConnectAttrs (line 70) | clientConnectAttrs
  constant clientPluginAuthLenEncClientData (line 71) | clientPluginAuthLenEncClientData
  constant clientCanHandleExpiredPasswords (line 72) | clientCanHandleExpiredPasswords
  constant clientSessionTrack (line 73) | clientSessionTrack
  constant clientDeprecateEOF (line 74) | clientDeprecateEOF
  type extendedCapabilityFlag (line 78) | type extendedCapabilityFlag
  constant progressIndicator (line 81) | progressIndicator extendedCapabilityFlag = 1 << iota
  constant clientComMulti (line 82) | clientComMulti
  constant clientStmtBulkOperations (line 83) | clientStmtBulkOperations
  constant clientExtendedMetadata (line 84) | clientExtendedMetadata
  constant clientCacheMetadata (line 85) | clientCacheMetadata
  constant clientUnitBulkResult (line 86) | clientUnitBulkResult
  constant comQuit (line 90) | comQuit byte = iota + 1
  constant comInitDB (line 91) | comInitDB
  constant comQuery (line 92) | comQuery
  constant comFieldList (line 93) | comFieldList
  constant comCreateDB (line 94) | comCreateDB
  constant comDropDB (line 95) | comDropDB
  constant comRefresh (line 96) | comRefresh
  constant comShutdown (line 97) | comShutdown
  constant comStatistics (line 98) | comStatistics
  constant comProcessInfo (line 99) | comProcessInfo
  constant comConnect (line 100) | comConnect
  constant comProcessKill (line 101) | comProcessKill
  constant comDebug (line 102) | comDebug
  constant comPing (line 103) | comPing
  constant comTime (line 104) | comTime
  constant comDelayedInsert (line 105) | comDelayedInsert
  constant comChangeUser (line 106) | comChangeUser
  constant comBinlogDump (line 107) | comBinlogDump
  constant comTableDump (line 108) | comTableDump
  constant comConnectOut (line 109) | comConnectOut
  constant comRegisterSlave (line 110) | comRegisterSlave
  constant comStmtPrepare (line 111) | comStmtPrepare
  constant comStmtExecute (line 112) | comStmtExecute
  constant comStmtSendLongData (line 113) | comStmtSendLongData
  constant comStmtClose (line 114) | comStmtClose
  constant comStmtReset (line 115) | comStmtReset
  constant comSetOption (line 116) | comSetOption
  constant comStmtFetch (line 117) | comStmtFetch
  type fieldType (line 121) | type fieldType
  constant fieldTypeDecimal (line 124) | fieldTypeDecimal fieldType = iota
  constant fieldTypeTiny (line 125) | fieldTypeTiny
  constant fieldTypeShort (line 126) | fieldTypeShort
  constant fieldTypeLong (line 127) | fieldTypeLong
  constant fieldTypeFloat (line 128) | fieldTypeFloat
  constant fieldTypeDouble (line 129) | fieldTypeDouble
  constant fieldTypeNULL (line 130) | fieldTypeNULL
  constant fieldTypeTimestamp (line 131) | fieldTypeTimestamp
  constant fieldTypeLongLong (line 132) | fieldTypeLongLong
  constant fieldTypeInt24 (line 133) | fieldTypeInt24
  constant fieldTypeDate (line 134) | fieldTypeDate
  constant fieldTypeTime (line 135) | fieldTypeTime
  constant fieldTypeDateTime (line 136) | fieldTypeDateTime
  constant fieldTypeYear (line 137) | fieldTypeYear
  constant fieldTypeNewDate (line 138) | fieldTypeNewDate
  constant fieldTypeVarChar (line 139) | fieldTypeVarChar
  constant fieldTypeBit (line 140) | fieldTypeBit
  constant fieldTypeVector (line 143) | fieldTypeVector fieldType = iota + 0xf2
  constant fieldTypeInvalid (line 144) | fieldTypeInvalid
  constant fieldTypeBool (line 145) | fieldTypeBool
  constant fieldTypeJSON (line 146) | fieldTypeJSON
  constant fieldTypeNewDecimal (line 147) | fieldTypeNewDecimal
  constant fieldTypeEnum (line 148) | fieldTypeEnum
  constant fieldTypeSet (line 149) | fieldTypeSet
  constant fieldTypeTinyBLOB (line 150) | fieldTypeTinyBLOB
  constant fieldTypeMediumBLOB (line 151) | fieldTypeMediumBLOB
  constant fieldTypeLongBLOB (line 152) | fieldTypeLongBLOB
  constant fieldTypeBLOB (line 153) | fieldTypeBLOB
  constant fieldTypeVarString (line 154) | fieldTypeVarString
  constant fieldTypeString (line 155) | fieldTypeString
  constant fieldTypeGeometry (line 156) | fieldTypeGeometry
  type fieldFlag (line 159) | type fieldFlag
  constant flagNotNULL (line 162) | flagNotNULL fieldFlag = 1 << iota
  constant flagPriKey (line 163) | flagPriKey
  constant flagUniqueKey (line 164) | flagUniqueKey
  constant flagMultipleKey (line 165) | flagMultipleKey
  constant flagBLOB (line 166) | flagBLOB
  constant flagUnsigned (line 167) | flagUnsigned
  constant flagZeroFill (line 168) | flagZeroFill
  constant flagBinary (line 169) | flagBinary
  constant flagEnum (line 170) | flagEnum
  constant flagAutoIncrement (line 171) | flagAutoIncrement
  constant flagTimestamp (line 172) | flagTimestamp
  constant flagSet (line 173) | flagSet
  constant flagUnknown1 (line 174) | flagUnknown1
  constant flagUnknown2 (line 175) | flagUnknown2
  constant flagUnknown3 (line 176) | flagUnknown3
  constant flagUnknown4 (line 177) | flagUnknown4
  type statusFlag (line 181) | type statusFlag
  constant statusInTrans (line 184) | statusInTrans statusFlag = 1 << iota
  constant statusInAutocommit (line 185) | statusInAutocommit
  constant statusReserved (line 186) | statusReserved
  constant statusMoreResultsExists (line 187) | statusMoreResultsExists
  constant statusNoGoodIndexUsed (line 188) | statusNoGoodIndexUsed
  constant statusNoIndexUsed (line 189) | statusNoIndexUsed
  constant statusCursorExists (line 190) | statusCursorExists
  constant statusLastRowSent (line 191) | statusLastRowSent
  constant statusDbDropped (line 192) | statusDbDropped
  constant statusNoBackslashEscapes (line 193) | statusNoBackslashEscapes
  constant statusMetadataChanged (line 194) | statusMetadataChanged
  constant statusQueryWasSlow (line 195) | statusQueryWasSlow
  constant statusPsOutParams (line 196) | statusPsOutParams
  constant statusInTransReadonly (line 197) | statusInTransReadonly
  constant statusSessionStateChanged (line 198) | statusSessionStateChanged
  constant cachingSha2PasswordRequestPublicKey (line 202) | cachingSha2PasswordRequestPublicKey          = 2
  constant cachingSha2PasswordFastAuthSuccess (line 203) | cachingSha2PasswordFastAuthSuccess           = 3
  constant cachingSha2PasswordPerformFullAuthentication (line 204) | cachingSha2PasswordPerformFullAuthentication = 4

FILE: driver.go
  type MySQLDriver (line 29) | type MySQLDriver struct
    method Open (line 81) | func (d MySQLDriver) Open(dsn string) (driver.Conn, error) {
    method OpenConnector (line 112) | func (d MySQLDriver) OpenConnector(dsn string) (driver.Connector, erro...
  type DialFunc (line 35) | type DialFunc
  type DialContextFunc (line 39) | type DialContextFunc
  function RegisterDialContext (line 49) | func RegisterDialContext(net string, dial DialContextFunc) {
  function DeregisterDialContext (line 59) | func DeregisterDialContext(net string) {
  function RegisterDial (line 72) | func RegisterDial(network string, dial DialFunc) {
  function init (line 94) | func init() {
  function NewConnector (line 101) | func NewConnector(cfg *Config) (driver.Connector, error) {

FILE: driver_test.go
  function init (line 42) | func init() {
  function init (line 76) | func init() {
  type DBTest (line 98) | type DBTest struct
    method fail (line 264) | func (dbt *DBTest) fail(method, query string, err error) {
    method mustExec (line 272) | func (dbt *DBTest) mustExec(query string, args ...any) (res sql.Result) {
    method mustQuery (line 281) | func (dbt *DBTest) mustQuery(query string, args ...any) (rows *sql.Row...
  type netErrorMock (line 103) | type netErrorMock struct
    method Temporary (line 108) | func (e netErrorMock) Temporary() bool {
    method Timeout (line 112) | func (e netErrorMock) Timeout() bool {
    method Error (line 116) | func (e netErrorMock) Error() string {
  function runTestsWithMultiStatement (line 120) | func runTestsWithMultiStatement(t *testing.T, dsn string, tests ...func(...
  function runTests (line 144) | func runTests(t *testing.T, dsn string, tests ...func(dbt *DBTest)) {
  function runTestsParallel (line 207) | func runTestsParallel(t *testing.T, dsn string, tests ...func(dbt *DBTes...
  function maybeSkip (line 290) | func maybeSkip(t *testing.T, err error, skipErrno uint16) {
  function TestEmptyQuery (line 301) | func TestEmptyQuery(t *testing.T) {
  function TestCRUD (line 313) | func TestCRUD(t *testing.T) {
  function TestNumbersToAny (line 410) | func TestNumbersToAny(t *testing.T) {
  function TestMultiQuery (line 453) | func TestMultiQuery(t *testing.T) {
  function TestInt (line 498) | func TestInt(t *testing.T) {
  function TestFloat32 (line 547) | func TestFloat32(t *testing.T) {
  function TestFloat64 (line 571) | func TestFloat64(t *testing.T) {
  function TestFloat64Placeholder (line 595) | func TestFloat64Placeholder(t *testing.T) {
  function TestString (line 619) | func TestString(t *testing.T) {
  function TestRawBytes (line 668) | func TestRawBytes(t *testing.T) {
  function TestRawMessage (line 697) | func TestRawMessage(t *testing.T) {
  type testValuer (line 720) | type testValuer struct
    method Value (line 724) | func (tv testValuer) Value() (driver.Value, error) {
  function TestValuer (line 728) | func TestValuer(t *testing.T) {
  type testValuerWithValidation (line 749) | type testValuerWithValidation struct
    method Value (line 753) | func (tv testValuerWithValidation) Value() (driver.Value, error) {
  function TestValuerWithValidation (line 761) | func TestValuerWithValidation(t *testing.T) {
  type timeTests (line 796) | type timeTests struct
  type timeTest (line 802) | type timeTest struct
    method genQuery (line 835) | func (t timeTest) genQuery(dbtype string, mode timeMode) string {
    method run (line 845) | func (t timeTest) run(dbt *DBTest, dbtype, tlayout string, mode timeMo...
  type timeMode (line 807) | type timeMode
    method String (line 809) | func (t timeMode) String() string {
    method Binary (line 821) | func (t timeMode) Binary() bool {
  constant binaryString (line 830) | binaryString timeMode = iota
  constant binaryTime (line 831) | binaryTime
  constant textString (line 832) | textString
  function TestDateTime (line 908) | func TestDateTime(t *testing.T) {
  function TestTimestampMicros (line 1025) | func TestTimestampMicros(t *testing.T) {
  function TestNULL (line 1078) | func TestNULL(t *testing.T) {
  function TestUint64 (line 1229) | func TestUint64(t *testing.T) {
  function TestLongData (line 1272) | func TestLongData(t *testing.T) {
  function TestLoadData (line 1334) | func TestLoadData(t *testing.T) {
  function TestFoundRows1 (line 1435) | func TestFoundRows1(t *testing.T) {
  function TestFoundRows2 (line 1459) | func TestFoundRows2(t *testing.T) {
  function TestTLS (line 1483) | func TestTLS(t *testing.T) {
  function TestReuseClosedConnection (line 1525) | func TestReuseClosedConnection(t *testing.T) {
  function TestCharset (line 1563) | func TestCharset(t *testing.T) {
  function TestFailingCharset (line 1597) | func TestFailingCharset(t *testing.T) {
  function TestCollation (line 1608) | func TestCollation(t *testing.T) {
  function TestColumnsWithAlias (line 1643) | func TestColumnsWithAlias(t *testing.T) {
  function TestRawBytesResultExceedsBuffer (line 1667) | func TestRawBytesResultExceedsBuffer(t *testing.T) {
  function TestTimezoneConversion (line 1685) | func TestTimezoneConversion(t *testing.T) {
  function TestRowsClose (line 1726) | func TestRowsClose(t *testing.T) {
  function TestCloseStmtBeforeRows (line 1751) | func TestCloseStmtBeforeRows(t *testing.T) {
  function TestStmtMultiRows (line 1792) | func TestStmtMultiRows(t *testing.T) {
  function TestPreparedManyCols (line 1907) | func TestPreparedManyCols(t *testing.T) {
  function TestConcurrent (line 1938) | func TestConcurrent(t *testing.T) {
  function testDialError (line 2014) | func testDialError(t *testing.T, dialErr error, expectErr error) {
  function TestDialUnknownError (line 2031) | func TestDialUnknownError(t *testing.T) {
  function TestDialNonRetryableNetErr (line 2036) | func TestDialNonRetryableNetErr(t *testing.T) {
  function TestDialTemporaryNetErr (line 2041) | func TestDialTemporaryNetErr(t *testing.T) {
  function TestCustomDial (line 2047) | func TestCustomDial(t *testing.T) {
  function TestBeforeConnect (line 2069) | func TestBeforeConnect(t *testing.T) {
  function TestSQLInjection (line 2103) | func TestSQLInjection(t *testing.T) {
  function TestInsertRetrieveEscapedData (line 2134) | func TestInsertRetrieveEscapedData(t *testing.T) {
  function TestUnixSocketAuthFail (line 2162) | func TestUnixSocketAuthFail(t *testing.T) {
  function TestInterruptBySignal (line 2210) | func TestInterruptBySignal(t *testing.T) {
  function TestColumnsReusesSlice (line 2258) | func TestColumnsReusesSlice(t *testing.T) {
  function TestRejectReadOnly (line 2291) | func TestRejectReadOnly(t *testing.T) {
  function TestPing (line 2324) | func TestPing(t *testing.T) {
  function TestEmptyPassword (line 2373) | func TestEmptyPassword(t *testing.T) {
  function TestMultiResultSet (line 2430) | func TestMultiResultSet(t *testing.T) {
  function TestMultiResultSetNoSelect (line 2570) | func TestMultiResultSetNoSelect(t *testing.T) {
  function TestExecMultipleResults (line 2589) | func TestExecMultipleResults(t *testing.T) {
  function TestSkipResults (line 2628) | func TestSkipResults(t *testing.T) {
  function TestQueryMultipleResults (line 2647) | func TestQueryMultipleResults(t *testing.T) {
  function TestPingContext (line 2683) | func TestPingContext(t *testing.T) {
  function TestContextCancelExec (line 2693) | func TestContextCancelExec(t *testing.T) {
  function TestContextCancelQuery (line 2739) | func TestContextCancelQuery(t *testing.T) {
  function TestContextCancelQueryRow (line 2783) | func TestContextCancelQueryRow(t *testing.T) {
  function TestContextCancelPrepare (line 2816) | func TestContextCancelPrepare(t *testing.T) {
  function TestContextCancelStmtExec (line 2826) | func TestContextCancelStmtExec(t *testing.T) {
  function TestContextCancelStmtQuery (line 2861) | func TestContextCancelStmtQuery(t *testing.T) {
  function TestContextCancelBegin (line 2896) | func TestContextCancelBegin(t *testing.T) {
  function TestContextBeginIsolationLevel (line 2956) | func TestContextBeginIsolationLevel(t *testing.T) {
  function TestContextBeginReadOnly (line 3008) | func TestContextBeginReadOnly(t *testing.T) {
  function TestRowsColumnTypes (line 3046) | func TestRowsColumnTypes(t *testing.T) {
  function TestValuerWithValueReceiverGivenNilValue (line 3268) | func TestValuerWithValueReceiverGivenNilValue(t *testing.T) {
  function TestRawBytesAreNotModified (line 3281) | func TestRawBytesAreNotModified(t *testing.T) {
  type dialCtxKey (line 3334) | type dialCtxKey struct
  function TestConnectorObeysDialTimeouts (line 3336) | func TestConnectorObeysDialTimeouts(t *testing.T) {
  function configForTests (line 3363) | func configForTests(t *testing.T) *Config {
  function TestNewConnector (line 3377) | func TestNewConnector(t *testing.T) {
  type slowConnection (line 3392) | type slowConnection struct
    method Read (line 3397) | func (sc *slowConnection) Read(b []byte) (int, error) {
  type connectorHijack (line 3402) | type connectorHijack struct
    method Connect (line 3407) | func (cw *connectorHijack) Connect(ctx context.Context) (driver.Conn, ...
  function TestConnectorTimeoutsDuringOpen (line 3413) | func TestConnectorTimeoutsDuringOpen(t *testing.T) {
  type dummyConnection (line 3449) | type dummyConnection struct
    method Close (line 3454) | func (d *dummyConnection) Close() error {
  function TestConnectorTimeoutsWatchCancel (line 3459) | func TestConnectorTimeoutsWatchCancel(t *testing.T) {
  function TestConnectionAttributes (line 3501) | func TestConnectionAttributes(t *testing.T) {
  function TestErrorInMultiResult (line 3571) | func TestErrorInMultiResult(t *testing.T) {
  function runCallCommand (line 3597) | func runCallCommand(dbt *DBTest, query, name string) {
  function TestIssue1567 (line 3615) | func TestIssue1567(t *testing.T) {

FILE: dsn.go
  type Config (line 37) | type Config struct
    method Apply (line 103) | func (c *Config) Apply(opts ...Option) error {
    method Clone (line 153) | func (cfg *Config) Clone() *Config {
    method normalize (line 173) | func (cfg *Config) normalize() error {
    method FormatDSN (line 254) | func (cfg *Config) FormatDSN() string {
  type Option (line 88) | type Option
  function NewConfig (line 91) | func NewConfig() *Config {
  function TimeTruncate (line 115) | func TimeTruncate(d time.Duration) Option {
  function BeforeConnect (line 123) | func BeforeConnect(fn func(context.Context, *Config) error) Option {
  function EnableCompression (line 131) | func EnableCompression(yes bool) Option {
  function Charset (line 145) | func Charset(charset, collation string) Option {
  function writeDSNParam (line 237) | func writeDSNParam(buf *bytes.Buffer, hasParam *bool, name, value string) {
  function ParseDSN (line 397) | func ParseDSN(dsn string) (cfg *Config, err error) {
  function parseDSNParams (line 479) | func parseDSNParams(cfg *Config, params string) (err error) {
  function ensureHavePort (line 696) | func ensureHavePort(addr string) string {

FILE: dsn_fuzz_test.go
  function FuzzFormatDSN (line 11) | func FuzzFormatDSN(f *testing.F) {

FILE: dsn_test.go
  function TestDSNParser (line 86) | func TestDSNParser(t *testing.T) {
  function TestDSNParserInvalid (line 105) | func TestDSNParserInvalid(t *testing.T) {
  function TestDSNReformat (line 127) | func TestDSNReformat(t *testing.T) {
  function TestDSNServerPubKey (line 165) | func TestDSNServerPubKey(t *testing.T) {
  function TestDSNServerPubKeyQueryEscape (line 192) | func TestDSNServerPubKeyQueryEscape(t *testing.T) {
  function TestDSNWithCustomTLS (line 209) | func TestDSNWithCustomTLS(t *testing.T) {
  function TestDSNTLSConfig (line 250) | func TestDSNTLSConfig(t *testing.T) {
  function TestDSNWithCustomTLSQueryEscape (line 278) | func TestDSNWithCustomTLSQueryEscape(t *testing.T) {
  function TestDSNUnsafeCollation (line 296) | func TestDSNUnsafeCollation(t *testing.T) {
  function TestParamsAreSorted (line 333) | func TestParamsAreSorted(t *testing.T) {
  function TestCloneConfig (line 348) | func TestCloneConfig(t *testing.T) {
  function TestNormalizeTLSConfig (line 388) | func TestNormalizeTLSConfig(t *testing.T) {
  function BenchmarkParseDSN (line 432) | func BenchmarkParseDSN(b *testing.B) {

FILE: errors.go
  type Logger (line 43) | type Logger interface
  type NopLogger (line 48) | type NopLogger struct
    method Print (line 51) | func (nl *NopLogger) Print(_ ...any) {}
  function SetLogger (line 55) | func SetLogger(logger Logger) error {
  type MySQLError (line 64) | type MySQLError struct
    method Error (line 70) | func (me *MySQLError) Error() string {
    method Is (line 78) | func (me *MySQLError) Is(err error) bool {

FILE: errors_test.go
  function TestErrorsSetLogger (line 18) | func TestErrorsSetLogger(t *testing.T) {
  function TestErrorsStrictIgnoreNotes (line 39) | func TestErrorsStrictIgnoreNotes(t *testing.T) {
  function TestMySQLErrIs (line 45) | func TestMySQLErrIs(t *testing.T) {

FILE: fields.go
  type mysqlField (line 143) | type mysqlField struct
    method typeDatabaseName (line 16) | func (mf *mysqlField) typeDatabaseName() string {
    method scanType (line 153) | func (mf *mysqlField) scanType() reflect.Type {

FILE: infile.go
  function RegisterLocalFile (line 36) | func RegisterLocalFile(filePath string) {
  function DeregisterLocalFile (line 48) | func DeregisterLocalFile(filePath string) {
  function RegisterReaderHandler (line 68) | func RegisterReaderHandler(name string, handler func() io.Reader) {
  function DeregisterReaderHandler (line 81) | func DeregisterReaderHandler(name string) {
  function deferredClose (line 87) | func deferredClose(err *error, closer io.Closer) {
  constant defaultPacketSize (line 94) | defaultPacketSize = 16 * 1024
  method handleInFileRequest (line 96) | func (mc *okHandler) handleInFileRequest(name string) (err error) {

FILE: nulltime.go
  type NullTime (line 36) | type NullTime
    method Scan (line 41) | func (nt *NullTime) Scan(value any) (err error) {
    method Value (line 66) | func (nt NullTime) Value() (driver.Value, error) {

FILE: nulltime_test.go
  function TestScanNullTime (line 24) | func TestScanNullTime(t *testing.T) {

FILE: packets.go
  method readNext (line 30) | func (mc *mysqlConn) readNext(n int) ([]byte, error) {
  method readPacket (line 41) | func (mc *mysqlConn) readPacket() ([]byte, error) {
  method writePacket (line 126) | func (mc *mysqlConn) writePacket(data []byte) error {
  method readHandshakePacket (line 184) | func (mc *mysqlConn) readHandshakePacket() (data []byte, capabilities ca...
  method initCapabilities (line 280) | func (mc *mysqlConn) initCapabilities(serverCapabilities capabilityFlag,...
  method writeHandshakeResponsePacket (line 321) | func (mc *mysqlConn) writeHandshakeResponsePacket(authResp []byte, plugi...
  method writeAuthSwitchPacket (line 418) | func (mc *mysqlConn) writeAuthSwitchPacket(authData []byte) error {
  method writeCommandPacket (line 435) | func (mc *mysqlConn) writeCommandPacket(command byte) error {
  method writeCommandPacketStr (line 453) | func (mc *mysqlConn) writeCommandPacketStr(command byte, arg string) err...
  method writeCommandPacketUint32 (line 475) | func (mc *mysqlConn) writeCommandPacketUint32(command byte, arg uint32) ...
  method readAuthResult (line 500) | func (mc *mysqlConn) readAuthResult() ([]byte, string, error) {
  method handleErrorPacket (line 588) | func (mc *mysqlConn) handleErrorPacket(data []byte) error {
  function readStatus (line 631) | func readStatus(b []byte) statusFlag {
  method resultUnchanged (line 638) | func (mc *mysqlConn) resultUnchanged() *okHandler {
  type okHandler (line 652) | type okHandler
    method readResultOK (line 539) | func (mc *okHandler) readResultOK() error {
    method readResultSetHeaderPacket (line 553) | func (mc *okHandler) readResultSetHeaderPacket() (int, bool, error) {
    method conn (line 655) | func (mc *okHandler) conn() *mysqlConn {
    method handleOkPacket (line 670) | func (mc *okHandler) handleOkPacket(data []byte) error {
    method discardResults (line 1245) | func (mc *okHandler) discardResults() error {
  method clearResult (line 663) | func (mc *mysqlConn) clearResult() *okHandler {
  method readColumns (line 704) | func (mc *mysqlConn) readColumns(count int, old []mysqlField) ([]mysqlFi...
  method readRow (line 809) | func (rows *textRows) readRow(dest []driver.Value) error {
  method skipPackets (line 909) | func (mc *mysqlConn) skipPackets(n int) error {
  method skipEof (line 919) | func (mc *mysqlConn) skipEof() error {
  method skipColumns (line 928) | func (mc *mysqlConn) skipColumns(n int) error {
  method skipRows (line 936) | func (mc *mysqlConn) skipRows() error {
  method readPrepareResultPacket (line 971) | func (stmt *mysqlStmt) readPrepareResultPacket() (uint16, error) {
  method writeCommandLongData (line 998) | func (stmt *mysqlStmt) writeCommandLongData(paramID int, arg []byte) err...
  method writeExecutePacket (line 1045) | func (stmt *mysqlStmt) writeExecutePacket(args []driver.Value) error {
  method readRow (line 1266) | func (rows *binaryRows) readRow(dest []driver.Value) error {

FILE: packets_test.go
  type mockConn (line 26) | type mockConn struct
    method Read (line 40) | func (m *mockConn) Read(b []byte) (n int, err error) {
    method Write (line 55) | func (m *mockConn) Write(b []byte) (n int, err error) {
    method Close (line 74) | func (m *mockConn) Close() error {
    method LocalAddr (line 78) | func (m *mockConn) LocalAddr() net.Addr {
    method RemoteAddr (line 81) | func (m *mockConn) RemoteAddr() net.Addr {
    method SetDeadline (line 84) | func (m *mockConn) SetDeadline(t time.Time) error {
    method SetReadDeadline (line 87) | func (m *mockConn) SetReadDeadline(t time.Time) error {
    method SetWriteDeadline (line 90) | func (m *mockConn) SetWriteDeadline(t time.Time) error {
  function newRWMockConn (line 97) | func newRWMockConn(sequence uint8) (*mockConn, *mysqlConn) {
  function TestReadPacketSingleByte (line 112) | func TestReadPacketSingleByte(t *testing.T) {
  function TestReadPacketWrongSequenceID (line 134) | func TestReadPacketWrongSequenceID(t *testing.T) {
  function TestReadPacketSplit (line 166) | func TestReadPacketSplit(t *testing.T) {
  function TestReadPacketFail (line 273) | func TestReadPacketFail(t *testing.T) {
  function TestRegression801 (line 318) | func TestRegression801(t *testing.T) {

FILE: result.go
  type Result (line 22) | type Result interface
  type mysqlResult (line 32) | type mysqlResult struct
    method LastInsertId (line 38) | func (res *mysqlResult) LastInsertId() (int64, error) {
    method RowsAffected (line 42) | func (res *mysqlResult) RowsAffected() (int64, error) {
    method AllLastInsertIds (line 46) | func (res *mysqlResult) AllLastInsertIds() []int64 {
    method AllRowsAffected (line 50) | func (res *mysqlResult) AllRowsAffected() []int64 {

FILE: rows.go
  type resultSet (line 18) | type resultSet struct
  type mysqlRows (line 24) | type mysqlRows struct
    method Columns (line 38) | func (rows *mysqlRows) Columns() []string {
    method ColumnTypeDatabaseTypeName (line 62) | func (rows *mysqlRows) ColumnTypeDatabaseTypeName(i int) string {
    method ColumnTypeNullable (line 70) | func (rows *mysqlRows) ColumnTypeNullable(i int) (nullable, ok bool) {
    method ColumnTypePrecisionScale (line 74) | func (rows *mysqlRows) ColumnTypePrecisionScale(i int) (int64, int64, ...
    method ColumnTypeScanType (line 96) | func (rows *mysqlRows) ColumnTypeScanType(i int) reflect.Type {
    method Close (line 100) | func (rows *mysqlRows) Close() (err error) {
    method HasNextResultSet (line 129) | func (rows *mysqlRows) HasNextResultSet() (b bool) {
    method nextResultSet (line 136) | func (rows *mysqlRows) nextResultSet() (int, error) {
    method nextNotEmptyResultSet (line 168) | func (rows *mysqlRows) nextNotEmptyResultSet() (int, error) {
  type binaryRows (line 30) | type binaryRows struct
    method NextResultSet (line 183) | func (rows *binaryRows) NextResultSet() error {
    method Next (line 193) | func (rows *binaryRows) Next(dest []driver.Value) error {
  type textRows (line 34) | type textRows struct
    method NextResultSet (line 205) | func (rows *textRows) NextResultSet() (err error) {
    method Next (line 215) | func (rows *textRows) Next(dest []driver.Value) error {

FILE: statement.go
  type mysqlStmt (line 19) | type mysqlStmt struct
    method Close (line 26) | func (stmt *mysqlStmt) Close() error {
    method NumInput (line 41) | func (stmt *mysqlStmt) NumInput() int {
    method ColumnConverter (line 45) | func (stmt *mysqlStmt) ColumnConverter(idx int) driver.ValueConverter {
    method CheckNamedValue (line 49) | func (stmt *mysqlStmt) CheckNamedValue(nv *driver.NamedValue) (err err...
    method Exec (line 54) | func (stmt *mysqlStmt) Exec(args []driver.Value) (driver.Result, error) {
    method Query (line 100) | func (stmt *mysqlStmt) Query(args []driver.Value) (driver.Rows, error) {
    method query (line 104) | func (stmt *mysqlStmt) query(args []driver.Value) (*binaryRows, error) {
  type converter (line 154) | type converter struct
    method ConvertValue (line 161) | func (c converter) ConvertValue(v any) (driver.Value, error) {
  function callValuerValue (line 227) | func callValuerValue(vr driver.Valuer) (v driver.Value, err error) {

FILE: statement_test.go
  function TestConvertDerivedString (line 18) | func TestConvertDerivedString(t *testing.T) {
  function TestConvertDerivedByteSlice (line 31) | func TestConvertDerivedByteSlice(t *testing.T) {
  function TestConvertDerivedUnsupportedSlice (line 44) | func TestConvertDerivedUnsupportedSlice(t *testing.T) {
  function TestConvertDerivedBool (line 53) | func TestConvertDerivedBool(t *testing.T) {
  function TestConvertPointer (line 66) | func TestConvertPointer(t *testing.T) {
  function TestConvertSignedIntegers (line 79) | func TestConvertSignedIntegers(t *testing.T) {
  type myUint64 (line 100) | type myUint64 struct
    method Value (line 104) | func (u myUint64) Value() (driver.Value, error) {
  function TestConvertUnsignedIntegers (line 108) | func TestConvertUnsignedIntegers(t *testing.T) {
  function TestConvertJSON (line 139) | func TestConvertJSON(t *testing.T) {

FILE: transaction.go
  type mysqlTx (line 11) | type mysqlTx struct
    method Commit (line 15) | func (tx *mysqlTx) Commit() (err error) {
    method Rollback (line 31) | func (tx *mysqlTx) Rollback() (err error) {

FILE: utils.go
  function RegisterTLSConfig (line 57) | func RegisterTLSConfig(key string, config *tls.Config) error {
  function DeregisterTLSConfig (line 73) | func DeregisterTLSConfig(key string) {
  function getTLSConfigClone (line 81) | func getTLSConfigClone(key string) (config *tls.Config) {
  function readBool (line 92) | func readBool(input string) (value bool, valid bool) {
  function parseDateTime (line 108) | func parseDateTime(b []byte, loc *time.Location) (time.Time, error) {
  function parseByteYear (line 183) | func parseByteYear(b []byte) (int, error) {
  function parseByte2Digits (line 196) | func parseByte2Digits(b1, b2 byte) (int, error) {
  function parseByteNanoSec (line 208) | func parseByteNanoSec(b []byte) (int, error) {
  function bToi (line 223) | func bToi(b byte) (int, error) {
  function parseBinaryDateTime (line 230) | func parseBinaryDateTime(num uint64, data []byte, loc *time.Location) (d...
  function appendDateTime (line 268) | func appendDateTime(buf []byte, t time.Time, timeTruncate time.Duration)...
  constant digits01 (line 336) | digits01 = "012345678901234567890123456789012345678901234567890123456789...
  constant digits10 (line 337) | digits10 = "000000000011111111112222222222333333333344444444445555555555...
  function appendMicrosecs (line 339) | func appendMicrosecs(dst, src []byte, decimals int) []byte {
  function formatBinaryDateTime (line 388) | func formatBinaryDateTime(src []byte, length uint8) (driver.Value, error) {
  function formatBinaryTime (line 447) | func formatBinaryTime(src []byte, length uint8) (driver.Value, error) {
  function putUint24 (line 495) | func putUint24(data []byte, n int) {
  function getUint24 (line 501) | func getUint24(data []byte) int {
  function uint64ToString (line 505) | func uint64ToString(n uint64) []byte {
  function readLengthEncodedString (line 530) | func readLengthEncodedString(b []byte) ([]byte, bool, int, error) {
  function skipLengthEncodedString (line 548) | func skipLengthEncodedString(b []byte) (int, error) {
  function readLengthEncodedInteger (line 565) | func readLengthEncodedInteger(b []byte) (uint64, bool, int) {
  function appendLengthEncodedInteger (line 594) | func appendLengthEncodedInteger(b []byte, n uint64) []byte {
  function appendLengthEncodedString (line 610) | func appendLengthEncodedString(b []byte, s string) []byte {
  function reserveBuffer (line 617) | func reserveBuffer(buf []byte, appendSize int) []byte {
  function escapeBytesBackslash (line 633) | func escapeBytesBackslash(buf, v []byte) []byte {
  function escapeStringBackslash (line 677) | func escapeStringBackslash(buf []byte, v string) []byte {
  function escapeBytesQuotes (line 726) | func escapeBytesQuotes(buf, v []byte) []byte {
  function escapeStringQuotes (line 745) | func escapeStringQuotes(buf []byte, v string) []byte {
  type noCopy (line 773) | type noCopy struct
    method Lock (line 776) | func (*noCopy) Lock() {}
    method Unlock (line 782) | func (*noCopy) Unlock() {}
  type atomicError (line 785) | type atomicError struct
    method Set (line 792) | func (ae *atomicError) Set(value error) {
    method Value (line 797) | func (ae *atomicError) Value() error {
  function namedValueToValue (line 805) | func namedValueToValue(named []driver.NamedValue) ([]driver.Value, error) {
  function mapIsolationLevel (line 817) | func mapIsolationLevel(level driver.IsolationLevel) (string, error) {

FILE: utils_test.go
  function TestLengthEncodedInteger (line 20) | func TestLengthEncodedInteger(t *testing.T) {
  function TestFormatBinaryDateTime (line 57) | func TestFormatBinaryDateTime(t *testing.T) {
  function TestFormatBinaryTime (line 86) | func TestFormatBinaryTime(t *testing.T) {
  function TestEscapeBackslash (line 121) | func TestEscapeBackslash(t *testing.T) {
  function TestEscapeQuotes (line 149) | func TestEscapeQuotes(t *testing.T) {
  function TestAtomicError (line 176) | func TestAtomicError(t *testing.T) {
  function TestIsolationLevelMapping (line 198) | func TestIsolationLevelMapping(t *testing.T) {
  function TestAppendDateTime (line 238) | func TestAppendDateTime(t *testing.T) {
  function TestParseDateTime (line 352) | func TestParseDateTime(t *testing.T) {
  function TestInvalidDateTime (line 426) | func TestInvalidDateTime(t *testing.T) {
  function TestParseDateTimeFail (line 453) | func TestParseDateTimeFail(t *testing.T) {
Condensed preview — 47 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (495K chars).
[
  {
    "path": ".github/CONTRIBUTING.md",
    "chars": 1091,
    "preview": "# Contributing Guidelines\n\n## Reporting Issues\n\nBefore creating a new Issue, please check first if a similar Issue [alre"
  },
  {
    "path": ".github/ISSUE_TEMPLATE.md",
    "chars": 446,
    "preview": "### Issue description\nTell us what should happen and what happens instead\n\n### Example code\n```go\nIf possible, please en"
  },
  {
    "path": ".github/PULL_REQUEST_TEMPLATE.md",
    "chars": 309,
    "preview": "### Description\nPlease explain the changes you made here.\n\n### Checklist\n- [ ] Code compiles correctly\n- [ ] Created tes"
  },
  {
    "path": ".github/workflows/codeql.yml",
    "chars": 834,
    "preview": "name: \"CodeQL\"\n\non:\n  push:\n    branches: [ \"master\" ]\n  pull_request:\n    branches: [ \"master\" ]\n  schedule:\n    - cron"
  },
  {
    "path": ".github/workflows/test.yml",
    "chars": 3250,
    "preview": "name: test\non:\n  pull_request:\n  push:\n  workflow_dispatch:\n\nenv:\n  MYSQL_TEST_USER: gotest\n  MYSQL_TEST_PASS: secret\n  "
  },
  {
    "path": ".gitignore",
    "chars": 84,
    "preview": ".DS_Store\n.DS_Store?\n._*\n.Spotlight-V100\n.Trashes\nIcon?\nehthumbs.db\nThumbs.db\n.idea\n"
  },
  {
    "path": "AUTHORS",
    "chars": 5464,
    "preview": "# This is the official list of Go-MySQL-Driver authors for copyright purposes.\n\n# If you are submitting a patch, please "
  },
  {
    "path": "CHANGELOG.md",
    "chars": 15461,
    "preview": "# Changelog\n\n## v1.9.2 (2025-04-07)\n\nv1.9.2 is a re-release of v1.9.1 due to a release process issue; no changes were ma"
  },
  {
    "path": "LICENSE",
    "chars": 16726,
    "preview": "Mozilla Public License Version 2.0\n==================================\n\n1. Definitions\n--------------\n\n1.1. \"Contributor\""
  },
  {
    "path": "README.md",
    "chars": 27084,
    "preview": "# Go-MySQL-Driver\n\n[![DeepWiki](https://img.shields.io/badge/DeepWiki-go--sql--driver%2Fmysql-blue.svg?logo=data:image/p"
  },
  {
    "path": "auth.go",
    "chars": 12115,
    "preview": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2018 The Go-MySQL-Driver Authors. All "
  },
  {
    "path": "auth_test.go",
    "chars": 41434,
    "preview": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2018 The Go-MySQL-Driver Authors. All "
  },
  {
    "path": "benchmark_test.go",
    "chars": 11380,
    "preview": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2013 The Go-MySQL-Driver Authors. All "
  },
  {
    "path": "buffer.go",
    "chars": 4125,
    "preview": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2013 The Go-MySQL-Driver Authors. All "
  },
  {
    "path": "collations.go",
    "chars": 8739,
    "preview": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2014 The Go-MySQL-Driver Authors. All "
  },
  {
    "path": "compress.go",
    "chars": 5813,
    "preview": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2024 The Go-MySQL-Driver Authors. All "
  },
  {
    "path": "compress_test.go",
    "chars": 3464,
    "preview": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2024 The Go-MySQL-Driver Authors. All "
  },
  {
    "path": "conncheck.go",
    "chars": 1213,
    "preview": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2019 The Go-MySQL-Driver Authors. All "
  },
  {
    "path": "conncheck_dummy.go",
    "chars": 607,
    "preview": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2019 The Go-MySQL-Driver Authors. All "
  },
  {
    "path": "conncheck_test.go",
    "chars": 984,
    "preview": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2013 The Go-MySQL-Driver Authors. All "
  },
  {
    "path": "connection.go",
    "chars": 16840,
    "preview": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2012 The Go-MySQL-Driver Authors. All "
  },
  {
    "path": "connection_test.go",
    "chars": 4947,
    "preview": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2016 The Go-MySQL-Driver Authors. All "
  },
  {
    "path": "connector.go",
    "chars": 6329,
    "preview": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2018 The Go-MySQL-Driver Authors. All "
  },
  {
    "path": "connector_test.go",
    "chars": 580,
    "preview": "package mysql\n\nimport (\n\t\"context\"\n\t\"net\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestConnectorReturnsTimeout(t *testing.T) {\n\tconnec"
  },
  {
    "path": "const.go",
    "chars": 4435,
    "preview": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2012 The Go-MySQL-Driver Authors. All "
  },
  {
    "path": "driver.go",
    "chars": 3648,
    "preview": "// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved.\n//\n// This Source Code Form is subject to the terms "
  },
  {
    "path": "driver_test.go",
    "chars": 100959,
    "preview": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2013 The Go-MySQL-Driver Authors. All "
  },
  {
    "path": "dsn.go",
    "chars": 19147,
    "preview": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2016 The Go-MySQL-Driver Authors. All "
  },
  {
    "path": "dsn_fuzz_test.go",
    "chars": 873,
    "preview": "//go:build go1.18\n// +build go1.18\n\npackage mysql\n\nimport (\n\t\"net\"\n\t\"testing\"\n)\n\nfunc FuzzFormatDSN(f *testing.F) {\n\tfor"
  },
  {
    "path": "dsn_test.go",
    "chars": 16560,
    "preview": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2016 The Go-MySQL-Driver Authors. All "
  },
  {
    "path": "errors.go",
    "chars": 3158,
    "preview": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2013 The Go-MySQL-Driver Authors. All "
  },
  {
    "path": "errors_test.go",
    "chars": 1719,
    "preview": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2013 The Go-MySQL-Driver Authors. All "
  },
  {
    "path": "fields.go",
    "chars": 5468,
    "preview": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2017 The Go-MySQL-Driver Authors. All "
  },
  {
    "path": "go.mod",
    "chars": 89,
    "preview": "module github.com/go-sql-driver/mysql\n\ngo 1.22.0\n\nrequire filippo.io/edwards25519 v1.1.1\n"
  },
  {
    "path": "go.sum",
    "chars": 165,
    "preview": "filippo.io/edwards25519 v1.1.1 h1:YpjwWWlNmGIDyXOn8zLzqiD+9TyIlPhGFG96P39uBpw=\nfilippo.io/edwards25519 v1.1.1/go.mod h1:"
  },
  {
    "path": "infile.go",
    "chars": 4677,
    "preview": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2013 The Go-MySQL-Driver Authors. All "
  },
  {
    "path": "nulltime.go",
    "chars": 1784,
    "preview": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2013 The Go-MySQL-Driver Authors. All "
  },
  {
    "path": "nulltime_test.go",
    "chars": 1614,
    "preview": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2013 The Go-MySQL-Driver Authors. All "
  },
  {
    "path": "packets.go",
    "chars": 37754,
    "preview": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2012 The Go-MySQL-Driver Authors. All "
  },
  {
    "path": "packets_test.go",
    "chars": 8818,
    "preview": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2016 The Go-MySQL-Driver Authors. All "
  },
  {
    "path": "result.go",
    "chars": 1546,
    "preview": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2012 The Go-MySQL-Driver Authors. All "
  },
  {
    "path": "rows.go",
    "chars": 4720,
    "preview": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2012 The Go-MySQL-Driver Authors. All "
  },
  {
    "path": "statement.go",
    "chars": 6041,
    "preview": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2012 The Go-MySQL-Driver Authors. All "
  },
  {
    "path": "statement_test.go",
    "chars": 3345,
    "preview": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2017 The Go-MySQL-Driver Authors. All "
  },
  {
    "path": "transaction.go",
    "chars": 893,
    "preview": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2012 The Go-MySQL-Driver Authors. All "
  },
  {
    "path": "utils.go",
    "chars": 20862,
    "preview": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2012 The Go-MySQL-Driver Authors. All "
  },
  {
    "path": "utils_test.go",
    "chars": 13465,
    "preview": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2013 The Go-MySQL-Driver Authors. All "
  }
]

About this extraction

This page contains the full source code of the go-sql-driver/mysql GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 47 files (440.5 KB), approximately 138.6k tokens, and a symbol index with 630 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!