[
  {
    "path": ".github/CONTRIBUTING.md",
    "content": "# Contributing Guidelines\n\n## Reporting Issues\n\nBefore 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).\n\n## Contributing Code\n\nBy contributing to this project, you share your code under the Mozilla Public License 2, as specified in the LICENSE file.\nDon't forget to add yourself to the AUTHORS file.\n\n### Code Review\n\nEveryone is invited to review and comment on pull requests.\nIf it looks fine to you, comment with \"LGTM\" (Looks good to me).\n\nIf changes are required, notice the reviewers with \"PTAL\" (Please take another look) after committing the fixes.\n\nBefore merging the Pull Request, at least one [team member](https://github.com/go-sql-driver?tab=members) must have commented with \"LGTM\".\n\n## Development Ideas\n\nIf 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.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE.md",
    "content": "### Issue description\nTell us what should happen and what happens instead\n\n### Example code\n```go\nIf possible, please enter some example code here to reproduce the issue.\n```\n\n### Error log\n```\nIf you have an error log, please paste it here.\n```\n\n### Configuration\n*Driver version (or git SHA):*\n\n*Go version:* run `go version` in your console\n\n*Server version:* E.g. MySQL 5.6, MariaDB 10.0.20\n\n*Server OS:* E.g. Debian 8.1 (Jessie), Windows 10\n"
  },
  {
    "path": ".github/PULL_REQUEST_TEMPLATE.md",
    "content": "### Description\nPlease explain the changes you made here.\n\n### Checklist\n- [ ] Code compiles correctly\n- [ ] Created tests which fail without the change (if possible)\n- [ ] All tests passing\n- [ ] Extended the README / documentation, if necessary\n- [ ] Added myself / the copyright holder to the AUTHORS file\n"
  },
  {
    "path": ".github/workflows/codeql.yml",
    "content": "name: \"CodeQL\"\n\non:\n  push:\n    branches: [ \"master\" ]\n  pull_request:\n    branches: [ \"master\" ]\n  schedule:\n    - cron: \"18 19 * * 1\"\n\njobs:\n  analyze:\n    name: Analyze\n    runs-on: ubuntu-latest\n    permissions:\n      actions: read\n      contents: read\n      security-events: write\n\n    strategy:\n      fail-fast: false\n      matrix:\n        language: [ go ]\n\n    steps:\n      - name: Checkout\n        uses: actions/checkout@v4\n\n      - name: Initialize CodeQL\n        uses: github/codeql-action/init@v3\n        with:\n          languages: ${{ matrix.language }}\n          queries: +security-and-quality\n\n      - name: Autobuild\n        uses: github/codeql-action/autobuild@v3\n\n      - name: Perform CodeQL Analysis\n        uses: github/codeql-action/analyze@v3\n        with:\n          category: \"/language:${{ matrix.language }}\"\n"
  },
  {
    "path": ".github/workflows/test.yml",
    "content": "name: test\non:\n  pull_request:\n  push:\n  workflow_dispatch:\n\nenv:\n  MYSQL_TEST_USER: gotest\n  MYSQL_TEST_PASS: secret\n  MYSQL_TEST_ADDR: 127.0.0.1:3306\n  MYSQL_TEST_CONCURRENT: 1\n\njobs:\n  lint:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n      - uses: dominikh/staticcheck-action@v1.3.1\n\n  list:\n    runs-on: ubuntu-latest\n    outputs:\n      matrix: ${{ steps.set-matrix.outputs.matrix }}\n    steps:\n      - name: list\n        id: set-matrix\n        run: |\n          import json\n          import os\n          go = [\n              # Keep the most recent production release at the top\n              '1.24',\n              # Older production releases\n              '1.23',\n              '1.22',\n          ]\n          mysql = [\n              '9.0',\n              '8.4', # LTS\n              '8.0',\n              '5.7',\n              'mariadb-11.4',   # LTS\n              'mariadb-11.2',\n              'mariadb-11.1',\n              'mariadb-10.11',  # LTS\n              'mariadb-10.6',   # LTS\n              'mariadb-10.5',   # LTS\n          ]\n\n          includes = []\n          # Go versions compatibility check\n          for v in go[1:]:\n              includes.append({'os': 'ubuntu-latest', 'go': v, 'mysql': mysql[0]})\n\n          matrix = {\n              # OS vs MySQL versions\n              'os': [ 'ubuntu-latest', 'macos-latest', 'windows-latest' ],\n              'go': [ go[0] ],\n              'mysql': mysql,\n\n              'include': includes\n          }\n          output = json.dumps(matrix, separators=(',', ':'))\n          with open(os.environ[\"GITHUB_OUTPUT\"], 'a', encoding=\"utf-8\") as f:\n              print(f\"matrix={output}\", file=f)\n        shell: python\n  test:\n    needs: list\n    runs-on: ${{ matrix.os }}\n    strategy:\n      fail-fast: false\n      matrix: ${{ fromJSON(needs.list.outputs.matrix) }}\n    steps:\n      - uses: actions/checkout@v4\n      - uses: actions/setup-go@v5\n        with:\n          go-version: ${{ matrix.go }}\n      - uses: shogo82148/actions-setup-mysql@v1\n        with:\n          mysql-version: ${{ matrix.mysql }}\n          user: ${{ env.MYSQL_TEST_USER }}\n          password: ${{ env.MYSQL_TEST_PASS }}\n          my-cnf: |\n            innodb_log_file_size=256MB\n            innodb_buffer_pool_size=512MB\n            max_allowed_packet=48MB\n            ; TestConcurrent fails if max_connections is too large\n            max_connections=50\n            local_infile=1\n            performance_schema=on\n      - name: setup database\n        run: |\n          mysql --user 'root' --host '127.0.0.1' -e 'create database gotest;'\n\n      - name: test\n        run: |\n          go test -v '-race' '-covermode=atomic' '-coverprofile=coverage.out' -parallel 10\n\n      - name: benchmark\n        run: |\n          go test -run '^$' -bench .\n\n      - name: Send coverage\n        uses: shogo82148/actions-goveralls@v1\n        with:\n          path-to-profile: coverage.out\n          flag-name: ${{ runner.os }}-Go-${{ matrix.go }}-DB-${{ matrix.mysql }}\n          parallel: true\n\n  # notifies that all test jobs are finished.\n  finish:\n    needs: test\n    if: always()\n    runs-on: ubuntu-latest\n    steps:\n      - uses: shogo82148/actions-goveralls@v1\n        with:\n          parallel-finished: true\n"
  },
  {
    "path": ".gitignore",
    "content": ".DS_Store\n.DS_Store?\n._*\n.Spotlight-V100\n.Trashes\nIcon?\nehthumbs.db\nThumbs.db\n.idea\n"
  },
  {
    "path": "AUTHORS",
    "content": "# This is the official list of Go-MySQL-Driver authors for copyright purposes.\n\n# If you are submitting a patch, please add your name or the name of the\n# organization which holds the copyright to this list in alphabetical order.\n\n# Names should be added to this file as\n#\tName <email address>\n# The email address is not required for organizations.\n# Please keep the list sorted.\n\n\n# Individual Persons\n\nAaron Hopkins <go-sql-driver at die.net>\nAchille Roussel <achille.roussel at gmail.com>\nAidan <aidan.liu at pingcap.com>\nAlex Snast <alexsn at fb.com>\nAlexey Palazhchenko <alexey.palazhchenko at gmail.com>\nAndrew Reid <andrew.reid at tixtrack.com>\nAnimesh Ray <mail.rayanimesh at gmail.com>\nAriel Mashraki <ariel at mashraki.co.il>\nArne Hormann <arnehormann at gmail.com>\nArtur Melanchyk <artur.melanchyk@gmail.com>\nAsta Xie <xiemengjun at gmail.com>\nB Lamarche <blam413 at gmail.com>\nBes Dollma <bdollma@thousandeyes.com>\nBogdan Constantinescu <bog.con.bc at gmail.com>\nBrad Higgins <brad at defined.net>\nBrian Hendriks <brian at dolthub.com>\nBulat Gaifullin <gaifullinbf at gmail.com>\nCaine Jette <jette at alum.mit.edu>\nCarlos Nieto <jose.carlos at menteslibres.net>\nChris Kirkland <chriskirkland at github.com>\nChris Moos <chris at tech9computers.com>\nCraig Wilson <craiggwilson at gmail.com>\nDaemonxiao <735462752 at qq.com>\nDaniel Montoya <dsmontoyam at gmail.com>\nDaniel Nichter <nil at codenode.com>\nDaniël van Eeden <git at myname.nl>\nDave Protasowski <dprotaso at gmail.com>\nDemouth <yuya at demouth.net>\nDiego Dupin <diego.dupin at gmail.com>\nDirkjan Bussink <d.bussink at gmail.com>\nDisposaBoy <disposaboy at dby.me>\nEgor Smolyakov <egorsmkv at gmail.com>\nErwan Martin <hello at erwan.io>\nEvan Elias <evan at skeema.net>\nEvan Shaw <evan at vendhq.com>\nFrederick Mayle <frederickmayle at gmail.com>\nGustavo Kristic <gkristic at gmail.com>\nGusted <postmaster at gusted.xyz>\nHajime Nakagami <nakagami at gmail.com>\nHanno Braun <mail at hannobraun.com>\nHenri Yandell <flamefew at gmail.com>\nHirotaka Yamamoto <ymmt2005 at gmail.com>\nHuyiguang <hyg at webterren.com>\nICHINOSE Shogo <shogo82148 at gmail.com>\nIlia Cimpoes <ichimpoesh at gmail.com>\nINADA Naoki <songofacandy at gmail.com>\nJacek Szwec <szwec.jacek at gmail.com>\nJakub Adamus <kratky at zobak.cz>\nJames Harr <james.harr at gmail.com>\nJanek Vedock <janekvedock at comcast.net>\nJason Ng <oblitorum at gmail.com>\nJean-Yves Pellé <jy at pelle.link>\nJeff Hodges <jeff at somethingsimilar.com>\nJeffrey Charles <jeffreycharles at gmail.com>\nJennifer Purevsuren <jennifer at dolthub.com>\nJerome Meyer <jxmeyer at gmail.com>\nJiabin Zhang <jiabin.z at qq.com>\nJiajia Zhong <zhong2plus at gmail.com>\nJian Zhen <zhenjl at gmail.com>\nJoe Mann <contact at joemann.co.uk>\nJoshua Prunier <joshua.prunier at gmail.com>\nJulien Lefevre <julien.lefevr at gmail.com>\nJulien Schmidt <go-sql-driver at julienschmidt.com>\nJustin Li <jli at j-li.net>\nJustin Nuß <nuss.justin at gmail.com>\nKamil Dziedzic <kamil at klecza.pl>\nKei Kamikawa <x00.x7f.x86 at gmail.com>\nKevin Malachowski <kevin at chowski.com>\nKieron Woodhouse <kieron.woodhouse at infosum.com>\nLance Tian <lance6716 at gmail.com>\nLennart Rudolph <lrudolph at hmc.edu>\nLeonardo YongUk Kim <dalinaum at gmail.com>\nLinh Tran Tuan <linhduonggnu at gmail.com>\nLion Yang <lion at aosc.xyz>\nLuca Looz <luca.looz92 at gmail.com>\nLucas Liu <extrafliu at gmail.com>\nLuke Scott <luke at webconnex.com>\nLunny Xiao <xiaolunwen at gmail.com>\nMaciej Zimnoch <maciej.zimnoch at codilime.com>\nMichael Woolnough <michael.woolnough at gmail.com>\nMinh Quang <minhquang4334 at gmail.com>\nNao Yokotsuka <yokotukanao at gmail.com>\nNathanial Murphy <nathanial.murphy at gmail.com>\nNicola Peduzzi <thenikso at gmail.com>\nOliver Bone <owbone at github.com>\nOlivier Mengué <dolmen at cpan.org>\noscarzhao <oscarzhaosl at gmail.com>\nPaul Bonser <misterpib at gmail.com>\nPaulius Lozys <pauliuslozys at gmail.com>\nPeter Schultz <peter.schultz at classmarkets.com>\nPhil Porada <philporada at gmail.com>\nRebecca Chin <rchin at pivotal.io>\nReed Allman <rdallman10 at gmail.com>\nRichard Wilkes <wilkes at me.com>\nRobert Russell <robert at rrbrussell.com>\nRunrioter Wung <runrioter at gmail.com>\nSamantha Frank <hello at entropy.cat>\nSanthosh Kumar Tekuri <santhosh.tekuri at gmail.com>\nSho Iizuka <sho.i518 at gmail.com>\nSho Ikeda <suicaicoca at gmail.com>\nShuode Li <elemount at qq.com>\nSimon J Mudd <sjmudd at pobox.com>\nSoroush Pour <me at soroushjp.com>\nStan Putrya <root.vagner at gmail.com>\nStanley Gunawan <gunawan.stanley at gmail.com>\nSteven Hartland <steven.hartland at multiplay.co.uk>\nTan Jinhua <312841925 at qq.com>\nTetsuro Aoki <t.aoki1130 at gmail.com>\nThomas Wodarek <wodarekwebpage at gmail.com>\nTim Ruffles <timruffles at gmail.com>\nTom Jenkinson <tom at tjenkinson.me>\nVladimir Kovpak <cn007b at gmail.com>\nVladyslav Zhelezniak <zhvladi at gmail.com>\nXiangyu Hu <xiangyu.hu at outlook.com>\nXiaobing Jiang <s7v7nislands at gmail.com>\nXiuming Chen <cc at cxm.cc>\nXuehong Chan <chanxuehong at gmail.com>\nZhang Xiang <angwerzx at 126.com>\nZhenye Xie <xiezhenye at gmail.com>\nZhixin Wen <john.wenzhixin at gmail.com>\nZiheng Lyu <zihenglv at gmail.com>\n\n# Organizations\n\nBarracuda Networks, Inc.\nCounting Ltd.\nDefined Networking Inc.\nDigitalOcean Inc.\nDolthub Inc.\ndyves labs AG\nFacebook Inc.\nGitHub Inc.\nGoogle Inc.\nInfoSum Ltd.\nKeybase Inc.\nMicrosoft Corp.\nMultiplay Ltd.\nPercona LLC\nPingCAP Inc.\nPivotal Inc.\nShattered Silicon Ltd.\nStripe Inc.\nThousandEyes\nZendesk Inc.\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# 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 made to the content.\n\n\n## v1.9.1 (2025-03-21)\n\n### Major Changes\n\n* Add Charset() option. (#1679)\n\n### Bugfixes\n\n* go.mod: fix go version format (#1682)\n* Fix FormatDSN missing ConnectionAttributes (#1619)\n\n## v1.9.0 (2025-02-18)\n\n### Major Changes\n\n- Implement zlib compression. (#1487)\n- Supported Go version is updated to Go 1.21+. (#1639)\n- Add support for VECTOR type introduced in MySQL 9.0. (#1609)\n- Config object can have custom dial function. (#1527)\n\n### Bugfixes\n\n- Fix auth errors when username/password are too long. (#1625)\n- Check if MySQL supports CLIENT_CONNECT_ATTRS before sending client attributes. (#1640)\n- Fix auth switch request handling. (#1666)\n\n### Other changes\n\n- Add \"filename:line\" prefix to log in go-mysql. Custom loggers now show it. (#1589)\n- Improve error handling. It reduces the \"busy buffer\" errors. (#1595, #1601, #1641)\n- Use `strconv.Atoi` to parse max_allowed_packet. (#1661)\n- `rejectReadOnly` option now handles ER_READ_ONLY_MODE (1290) error too. (#1660)\n\n\n## Version 1.8.1 (2024-03-26)\n\nBugfixes:\n\n- 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)\n\n## Version 1.8.0 (2024-03-09)\n\nMajor Changes:\n\n- Use `SET NAMES charset COLLATE collation`. by @methane in [#1437](https://github.com/go-sql-driver/mysql/pull/1437)\n  - Older go-mysql-driver used `collation_id` in the handshake packet. But it caused collation mismatch in some situation.\n  - 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.\n  - If you specify charset, go-mysql-driver sends `SET NAMES <charset>`. This uses the server's default collation for `<charset>`.\n  - If you specify collation and/or charset, go-mysql-driver sends `SET NAMES charset COLLATE collation`.\n- PathEscape dbname in DSN. by @methane in [#1432](https://github.com/go-sql-driver/mysql/pull/1432)\n  - This is backward incompatible in rare case. Check your DSN.\n- Drop Go 1.13-17 support by @methane in [#1420](https://github.com/go-sql-driver/mysql/pull/1420)\n  - Use Go 1.18+\n- Parse numbers on text protocol too by @methane in [#1452](https://github.com/go-sql-driver/mysql/pull/1452)\n  - When text protocol is used, go-mysql-driver passed bare `[]byte` to database/sql for avoid unnecessary allocation and conversion.\n  - If user specified `*any` to `Scan()`, database/sql passed the `[]byte` into the target variable.\n  - This confused users because most user doesn't know when text/binary protocol used.\n  - 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.\n- 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.\n  - Make TimeTruncate functional option by @methane in [1552](https://github.com/go-sql-driver/mysql/pull/1552)\n  - Add BeforeConnect callback to configuration object by @ItalyPaleAle in [#1469](https://github.com/go-sql-driver/mysql/pull/1469)\n\n\nOther changes:\n\n- 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\n- Make logger configurable per connection by @frozenbonito in https://github.com/go-sql-driver/mysql/pull/1408\n- Fix ColumnType.DatabaseTypeName for mediumint unsigned by @evanelias in https://github.com/go-sql-driver/mysql/pull/1428\n- Add connection attributes by @Daemonxiao in https://github.com/go-sql-driver/mysql/pull/1389\n- Stop `ColumnTypeScanType()` from returning `sql.RawBytes` by @methane in https://github.com/go-sql-driver/mysql/pull/1424\n- Exec() now provides access to status of multiple statements. by @mherr-google in https://github.com/go-sql-driver/mysql/pull/1309\n- Allow to change (or disable) the default driver name for registration by @dolmen in https://github.com/go-sql-driver/mysql/pull/1499\n- Add default connection attribute '_server_host' by @oblitorum in https://github.com/go-sql-driver/mysql/pull/1506\n- QueryUnescape DSN ConnectionAttribute value by @zhangyangyu in https://github.com/go-sql-driver/mysql/pull/1470\n- Add client_ed25519 authentication by @Gusted in https://github.com/go-sql-driver/mysql/pull/1518\n\n## Version 1.7.1 (2023-04-25)\n\nChanges:\n\n  - bump actions/checkout@v3 and actions/setup-go@v3 (#1375)\n  - Add go1.20 and mariadb10.11 to the testing matrix (#1403)\n  - Increase default maxAllowedPacket size. (#1411)\n\nBugfixes:\n\n  - Use SET syntax as specified in the MySQL documentation (#1402)\n\n\n## Version 1.7 (2022-11-29)\n\nChanges:\n\n  - Drop support of Go 1.12 (#1211)\n  - Refactoring `(*textRows).readRow` in a more clear way (#1230)\n  - util: Reduce boundary check in escape functions. (#1316)\n  - enhancement for mysqlConn handleAuthResult (#1250)\n\nNew Features:\n\n  - support Is comparison on MySQLError (#1210)\n  - return unsigned in database type name when necessary (#1238)\n  - Add API to express like a --ssl-mode=PREFERRED MySQL client (#1370)\n  - Add SQLState to MySQLError (#1321)\n\nBugfixes:\n\n  -  Fix parsing 0 year. (#1257)\n\n\n## Version 1.6 (2021-04-01)\n\nChanges:\n\n  - Migrate the CI service from travis-ci to GitHub Actions (#1176, #1183, #1190)\n  - `NullTime` is deprecated (#960, #1144)\n  - Reduce allocations when building SET command (#1111)\n  - Performance improvement for time formatting (#1118)\n  - Performance improvement for time parsing (#1098, #1113)\n\nNew Features:\n\n  - Implement `driver.Validator` interface (#1106, #1174)\n  - Support returning `uint64` from `Valuer` in `ConvertValue` (#1143)\n  - Add `json.RawMessage` for converter and prepared statement (#1059)\n  - Interpolate `json.RawMessage` as `string` (#1058)\n  - Implements `CheckNamedValue` (#1090)\n\nBugfixes:\n\n  - Stop rounding times (#1121, #1172)\n  - Put zero filler into the SSL handshake packet (#1066)\n  - Fix checking cancelled connections back into the connection pool (#1095)\n  - Fix remove last 0 byte for mysql_old_password when password is empty (#1133)\n\n\n## Version 1.5 (2020-01-07)\n\nChanges:\n\n  - Dropped support Go 1.9 and lower (#823, #829, #886, #1016, #1017)\n  - Improve buffer handling (#890)\n  - Document potentially insecure TLS configs (#901)\n  - Use a double-buffering scheme to prevent data races (#943)\n  - Pass uint64 values without converting them to string (#838, #955)\n  - Update collations and make utf8mb4 default (#877, #1054)\n  - Make NullTime compatible with sql.NullTime in Go 1.13+ (#995)\n  - Removed CloudSQL support (#993, #1007)\n  - Add Go Module support (#1003)\n\nNew Features:\n\n  - Implement support of optional TLS (#900)\n  - Check connection liveness (#934, #964, #997, #1048, #1051, #1052)\n  - Implement Connector Interface (#941, #958, #1020, #1035)\n\nBugfixes:\n\n  - Mark connections as bad on error during ping (#875)\n  - Mark connections as bad on error during dial (#867)\n  - Fix connection leak caused by rapid context cancellation (#1024)\n  - Mark connections as bad on error during Conn.Prepare (#1030)\n\n\n## Version 1.4.1 (2018-11-14)\n\nBugfixes:\n\n - Fix TIME format for binary columns (#818)\n - Fix handling of empty auth plugin names (#835)\n - Fix caching_sha2_password with empty password (#826)\n - Fix canceled context broke mysqlConn (#862)\n - Fix OldAuthSwitchRequest support (#870)\n - Fix Auth Response packet for cleartext password (#887)\n\n## Version 1.4 (2018-06-03)\n\nChanges:\n\n - Documentation fixes (#530, #535, #567)\n - Refactoring (#575, #579, #580, #581, #603, #615, #704)\n - Cache column names (#444)\n - Sort the DSN parameters in DSNs generated from a config (#637)\n - Allow native password authentication by default (#644)\n - Use the default port if it is missing in the DSN (#668)\n - Removed the `strict` mode (#676)\n - Do not query `max_allowed_packet` by default (#680)\n - Dropped support Go 1.6 and lower (#696)\n - Updated `ConvertValue()` to match the database/sql/driver implementation (#760)\n - Document the usage of `0000-00-00T00:00:00` as the time.Time zero value (#783)\n - Improved the compatibility of the authentication system (#807)\n\nNew Features:\n\n - Multi-Results support (#537)\n - `rejectReadOnly` DSN option (#604)\n - `context.Context` support (#608, #612, #627, #761)\n - Transaction isolation level support (#619, #744)\n - Read-Only transactions support (#618, #634)\n - `NewConfig` function which initializes a config with default values (#679)\n - Implemented the `ColumnType` interfaces (#667, #724)\n - Support for custom string types in `ConvertValue` (#623)\n - Implemented `NamedValueChecker`, improving support for uint64 with high bit set (#690, #709, #710)\n - `caching_sha2_password` authentication plugin support (#794, #800, #801, #802)\n - Implemented `driver.SessionResetter` (#779)\n - `sha256_password` authentication plugin support (#808)\n\nBugfixes:\n\n - Use the DSN hostname as TLS default ServerName if `tls=true` (#564, #718)\n - Fixed LOAD LOCAL DATA INFILE for empty files (#590)\n - Removed columns definition cache since it sometimes cached invalid data (#592)\n - Don't mutate registered TLS configs (#600)\n - Make RegisterTLSConfig concurrency-safe (#613)\n - Handle missing auth data in the handshake packet correctly (#646)\n - Do not retry queries when data was written to avoid data corruption (#302, #736)\n - Cache the connection pointer for error handling before invalidating it (#678)\n - Fixed imports for appengine/cloudsql (#700)\n - Fix sending STMT_LONG_DATA for 0 byte data (#734)\n - Set correct capacity for []bytes read from length-encoded strings (#766)\n - Make RegisterDial concurrency-safe (#773)\n\n\n## Version 1.3 (2016-12-01)\n\nChanges:\n\n - Go 1.1 is no longer supported\n - Use decimals fields in MySQL to format time types (#249)\n - Buffer optimizations (#269)\n - TLS ServerName defaults to the host (#283)\n - Refactoring (#400, #410, #437)\n - Adjusted documentation for second generation CloudSQL (#485)\n - Documented DSN system var quoting rules (#502)\n - Made statement.Close() calls idempotent to avoid errors in Go 1.6+ (#512)\n\nNew Features:\n\n - Enable microsecond resolution on TIME, DATETIME and TIMESTAMP (#249)\n - Support for returning table alias on Columns() (#289, #359, #382)\n - Placeholder interpolation, can be activated with the DSN parameter `interpolateParams=true` (#309, #318, #490)\n - Support for uint64 parameters with high bit set (#332, #345)\n - Cleartext authentication plugin support (#327)\n - Exported ParseDSN function and the Config struct (#403, #419, #429)\n - Read / Write timeouts (#401)\n - Support for JSON field type (#414)\n - Support for multi-statements and multi-results (#411, #431)\n - DSN parameter to set the driver-side max_allowed_packet value manually (#489)\n - Native password authentication plugin support (#494, #524)\n\nBugfixes:\n\n - Fixed handling of queries without columns and rows (#255)\n - Fixed a panic when SetKeepAlive() failed (#298)\n - Handle ERR packets while reading rows (#321)\n - Fixed reading NULL length-encoded integers in MySQL 5.6+ (#349)\n - Fixed absolute paths support in LOAD LOCAL DATA INFILE (#356)\n - Actually zero out bytes in handshake response (#378)\n - Fixed race condition in registering LOAD DATA INFILE handler (#383)\n - Fixed tests with MySQL 5.7.9+ (#380)\n - QueryUnescape TLS config names (#397)\n - Fixed \"broken pipe\" error by writing to closed socket (#390)\n - Fixed LOAD LOCAL DATA INFILE buffering (#424)\n - Fixed parsing of floats into float64 when placeholders are used (#434)\n - Fixed DSN tests with Go 1.7+ (#459)\n - Handle ERR packets while waiting for EOF (#473)\n - Invalidate connection on error while discarding additional results (#513)\n - Allow terminating packets of length 0 (#516)\n\n\n## Version 1.2 (2014-06-03)\n\nChanges:\n\n - We switched back to a \"rolling release\". `go get` installs the current master branch again\n - Version v1 of the driver will not be maintained anymore. Go 1.0 is no longer supported by this driver\n - Exported errors to allow easy checking from application code\n - Enabled TCP Keepalives on TCP connections\n - Optimized INFILE handling (better buffer size calculation, lazy init, ...)\n - The DSN parser also checks for a missing separating slash\n - Faster binary date / datetime to string formatting\n - Also exported the MySQLWarning type\n - mysqlConn.Close returns the first error encountered instead of ignoring all errors\n - writePacket() automatically writes the packet size to the header\n - readPacket() uses an iterative approach instead of the recursive approach to merge split packets\n\nNew Features:\n\n - `RegisterDial` allows the usage of a custom dial function to establish the network connection\n - Setting the connection collation is possible with the `collation` DSN parameter. This parameter should be preferred over the `charset` parameter\n - Logging of critical errors is configurable with `SetLogger`\n - Google CloudSQL support\n\nBugfixes:\n\n - Allow more than 32 parameters in prepared statements\n - Various old_password fixes\n - Fixed TestConcurrent test to pass Go's race detection\n - Fixed appendLengthEncodedInteger for large numbers\n - Renamed readLengthEnodedString to readLengthEncodedString and skipLengthEnodedString to skipLengthEncodedString (fixed typo)\n\n\n## Version 1.1 (2013-11-02)\n\nChanges:\n\n  - Go-MySQL-Driver now requires Go 1.1\n  - Connections now use the collation `utf8_general_ci` by default. Adding `&charset=UTF8` to the DSN should not be necessary anymore\n  - Made closing rows and connections error tolerant. This allows for example deferring rows.Close() without checking for errors\n  - `[]byte(nil)` is now treated as a NULL value. Before, it was treated like an empty string / `[]byte(\"\")`\n  - DSN parameter values must now be url.QueryEscape'ed. This allows text values to contain special characters, such as '&'.\n  - Use the IO buffer also for writing. This results in zero allocations (by the driver) for most queries\n  - Optimized the buffer for reading\n  - stmt.Query now caches column metadata\n  - New Logo\n  - Changed the copyright header to include all contributors\n  - Improved the LOAD INFILE documentation\n  - The driver struct is now exported to make the driver directly accessible\n  - Refactored the driver tests\n  - Added more benchmarks and moved all to a separate file\n  - Other small refactoring\n\nNew Features:\n\n  - Added *old_passwords* support: Required in some cases, but must be enabled by adding `allowOldPasswords=true` to the DSN since it is insecure\n  - Added a `clientFoundRows` parameter: Return the number of matching rows instead of the number of rows changed on UPDATEs\n  - Added TLS/SSL support: Use a TLS/SSL encrypted connection to the server. Custom TLS configs can be registered and used\n\nBugfixes:\n\n  - Fixed MySQL 4.1 support: MySQL 4.1 sends packets with lengths which differ from the specification\n  - Convert to DB timezone when inserting `time.Time`\n  - Split packets (more than 16MB) are now merged correctly\n  - Fixed false positive `io.EOF` errors when the data was fully read\n  - Avoid panics on reuse of closed connections\n  - Fixed empty string producing false nil values\n  - Fixed sign byte for positive TIME fields\n\n\n## Version 1.0 (2013-05-14)\n\nInitial Release\n"
  },
  {
    "path": "LICENSE",
    "content": "Mozilla Public License Version 2.0\n==================================\n\n1. Definitions\n--------------\n\n1.1. \"Contributor\"\n    means each individual or legal entity that creates, contributes to\n    the creation of, or owns Covered Software.\n\n1.2. \"Contributor Version\"\n    means the combination of the Contributions of others (if any) used\n    by a Contributor and that particular Contributor's Contribution.\n\n1.3. \"Contribution\"\n    means Covered Software of a particular Contributor.\n\n1.4. \"Covered Software\"\n    means Source Code Form to which the initial Contributor has attached\n    the notice in Exhibit A, the Executable Form of such Source Code\n    Form, and Modifications of such Source Code Form, in each case\n    including portions thereof.\n\n1.5. \"Incompatible With Secondary Licenses\"\n    means\n\n    (a) that the initial Contributor has attached the notice described\n        in Exhibit B to the Covered Software; or\n\n    (b) that the Covered Software was made available under the terms of\n        version 1.1 or earlier of the License, but not also under the\n        terms of a Secondary License.\n\n1.6. \"Executable Form\"\n    means any form of the work other than Source Code Form.\n\n1.7. \"Larger Work\"\n    means a work that combines Covered Software with other material, in \n    a separate file or files, that is not Covered Software.\n\n1.8. \"License\"\n    means this document.\n\n1.9. \"Licensable\"\n    means having the right to grant, to the maximum extent possible,\n    whether at the time of the initial grant or subsequently, any and\n    all of the rights conveyed by this License.\n\n1.10. \"Modifications\"\n    means any of the following:\n\n    (a) any file in Source Code Form that results from an addition to,\n        deletion from, or modification of the contents of Covered\n        Software; or\n\n    (b) any new file in Source Code Form that contains any Covered\n        Software.\n\n1.11. \"Patent Claims\" of a Contributor\n    means any patent claim(s), including without limitation, method,\n    process, and apparatus claims, in any patent Licensable by such\n    Contributor that would be infringed, but for the grant of the\n    License, by the making, using, selling, offering for sale, having\n    made, import, or transfer of either its Contributions or its\n    Contributor Version.\n\n1.12. \"Secondary License\"\n    means either the GNU General Public License, Version 2.0, the GNU\n    Lesser General Public License, Version 2.1, the GNU Affero General\n    Public License, Version 3.0, or any later versions of those\n    licenses.\n\n1.13. \"Source Code Form\"\n    means the form of the work preferred for making modifications.\n\n1.14. \"You\" (or \"Your\")\n    means an individual or a legal entity exercising rights under this\n    License. For legal entities, \"You\" includes any entity that\n    controls, is controlled by, or is under common control with You. For\n    purposes of this definition, \"control\" means (a) the power, direct\n    or indirect, to cause the direction or management of such entity,\n    whether by contract or otherwise, or (b) ownership of more than\n    fifty percent (50%) of the outstanding shares or beneficial\n    ownership of such entity.\n\n2. License Grants and Conditions\n--------------------------------\n\n2.1. Grants\n\nEach Contributor hereby grants You a world-wide, royalty-free,\nnon-exclusive license:\n\n(a) under intellectual property rights (other than patent or trademark)\n    Licensable by such Contributor to use, reproduce, make available,\n    modify, display, perform, distribute, and otherwise exploit its\n    Contributions, either on an unmodified basis, with Modifications, or\n    as part of a Larger Work; and\n\n(b) under Patent Claims of such Contributor to make, use, sell, offer\n    for sale, have made, import, and otherwise transfer either its\n    Contributions or its Contributor Version.\n\n2.2. Effective Date\n\nThe licenses granted in Section 2.1 with respect to any Contribution\nbecome effective for each Contribution on the date the Contributor first\ndistributes such Contribution.\n\n2.3. Limitations on Grant Scope\n\nThe licenses granted in this Section 2 are the only rights granted under\nthis License. No additional rights or licenses will be implied from the\ndistribution or licensing of Covered Software under this License.\nNotwithstanding Section 2.1(b) above, no patent license is granted by a\nContributor:\n\n(a) for any code that a Contributor has removed from Covered Software;\n    or\n\n(b) for infringements caused by: (i) Your and any other third party's\n    modifications of Covered Software, or (ii) the combination of its\n    Contributions with other software (except as part of its Contributor\n    Version); or\n\n(c) under Patent Claims infringed by Covered Software in the absence of\n    its Contributions.\n\nThis License does not grant any rights in the trademarks, service marks,\nor logos of any Contributor (except as may be necessary to comply with\nthe notice requirements in Section 3.4).\n\n2.4. Subsequent Licenses\n\nNo Contributor makes additional grants as a result of Your choice to\ndistribute the Covered Software under a subsequent version of this\nLicense (see Section 10.2) or under the terms of a Secondary License (if\npermitted under the terms of Section 3.3).\n\n2.5. Representation\n\nEach Contributor represents that the Contributor believes its\nContributions are its original creation(s) or it has sufficient rights\nto grant the rights to its Contributions conveyed by this License.\n\n2.6. Fair Use\n\nThis License is not intended to limit any rights You have under\napplicable copyright doctrines of fair use, fair dealing, or other\nequivalents.\n\n2.7. Conditions\n\nSections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted\nin Section 2.1.\n\n3. Responsibilities\n-------------------\n\n3.1. Distribution of Source Form\n\nAll distribution of Covered Software in Source Code Form, including any\nModifications that You create or to which You contribute, must be under\nthe terms of this License. You must inform recipients that the Source\nCode Form of the Covered Software is governed by the terms of this\nLicense, and how they can obtain a copy of this License. You may not\nattempt to alter or restrict the recipients' rights in the Source Code\nForm.\n\n3.2. Distribution of Executable Form\n\nIf You distribute Covered Software in Executable Form then:\n\n(a) such Covered Software must also be made available in Source Code\n    Form, as described in Section 3.1, and You must inform recipients of\n    the Executable Form how they can obtain a copy of such Source Code\n    Form by reasonable means in a timely manner, at a charge no more\n    than the cost of distribution to the recipient; and\n\n(b) You may distribute such Executable Form under the terms of this\n    License, or sublicense it under different terms, provided that the\n    license for the Executable Form does not attempt to limit or alter\n    the recipients' rights in the Source Code Form under this License.\n\n3.3. Distribution of a Larger Work\n\nYou may create and distribute a Larger Work under terms of Your choice,\nprovided that You also comply with the requirements of this License for\nthe Covered Software. If the Larger Work is a combination of Covered\nSoftware with a work governed by one or more Secondary Licenses, and the\nCovered Software is not Incompatible With Secondary Licenses, this\nLicense permits You to additionally distribute such Covered Software\nunder the terms of such Secondary License(s), so that the recipient of\nthe Larger Work may, at their option, further distribute the Covered\nSoftware under the terms of either this License or such Secondary\nLicense(s).\n\n3.4. Notices\n\nYou may not remove or alter the substance of any license notices\n(including copyright notices, patent notices, disclaimers of warranty,\nor limitations of liability) contained within the Source Code Form of\nthe Covered Software, except that You may alter any license notices to\nthe extent required to remedy known factual inaccuracies.\n\n3.5. Application of Additional Terms\n\nYou may choose to offer, and to charge a fee for, warranty, support,\nindemnity or liability obligations to one or more recipients of Covered\nSoftware. However, You may do so only on Your own behalf, and not on\nbehalf of any Contributor. You must make it absolutely clear that any\nsuch warranty, support, indemnity, or liability obligation is offered by\nYou alone, and You hereby agree to indemnify every Contributor for any\nliability incurred by such Contributor as a result of warranty, support,\nindemnity or liability terms You offer. You may include additional\ndisclaimers of warranty and limitations of liability specific to any\njurisdiction.\n\n4. Inability to Comply Due to Statute or Regulation\n---------------------------------------------------\n\nIf it is impossible for You to comply with any of the terms of this\nLicense with respect to some or all of the Covered Software due to\nstatute, judicial order, or regulation then You must: (a) comply with\nthe terms of this License to the maximum extent possible; and (b)\ndescribe the limitations and the code they affect. Such description must\nbe placed in a text file included with all distributions of the Covered\nSoftware under this License. Except to the extent prohibited by statute\nor regulation, such description must be sufficiently detailed for a\nrecipient of ordinary skill to be able to understand it.\n\n5. Termination\n--------------\n\n5.1. The rights granted under this License will terminate automatically\nif You fail to comply with any of its terms. However, if You become\ncompliant, then the rights granted under this License from a particular\nContributor are reinstated (a) provisionally, unless and until such\nContributor explicitly and finally terminates Your grants, and (b) on an\nongoing basis, if such Contributor fails to notify You of the\nnon-compliance by some reasonable means prior to 60 days after You have\ncome back into compliance. Moreover, Your grants from a particular\nContributor are reinstated on an ongoing basis if such Contributor\nnotifies You of the non-compliance by some reasonable means, this is the\nfirst time You have received notice of non-compliance with this License\nfrom such Contributor, and You become compliant prior to 30 days after\nYour receipt of the notice.\n\n5.2. If You initiate litigation against any entity by asserting a patent\ninfringement claim (excluding declaratory judgment actions,\ncounter-claims, and cross-claims) alleging that a Contributor Version\ndirectly or indirectly infringes any patent, then the rights granted to\nYou by any and all Contributors for the Covered Software under Section\n2.1 of this License shall terminate.\n\n5.3. In the event of termination under Sections 5.1 or 5.2 above, all\nend user license agreements (excluding distributors and resellers) which\nhave been validly granted by You or Your distributors under this License\nprior to termination shall survive termination.\n\n************************************************************************\n*                                                                      *\n*  6. Disclaimer of Warranty                                           *\n*  -------------------------                                           *\n*                                                                      *\n*  Covered Software is provided under this License on an \"as is\"       *\n*  basis, without warranty of any kind, either expressed, implied, or  *\n*  statutory, including, without limitation, warranties that the       *\n*  Covered Software is free of defects, merchantable, fit for a        *\n*  particular purpose or non-infringing. The entire risk as to the     *\n*  quality and performance of the Covered Software is with You.        *\n*  Should any Covered Software prove defective in any respect, You     *\n*  (not any Contributor) assume the cost of any necessary servicing,   *\n*  repair, or correction. This disclaimer of warranty constitutes an   *\n*  essential part of this License. No use of any Covered Software is   *\n*  authorized under this License except under this disclaimer.         *\n*                                                                      *\n************************************************************************\n\n************************************************************************\n*                                                                      *\n*  7. Limitation of Liability                                          *\n*  --------------------------                                          *\n*                                                                      *\n*  Under no circumstances and under no legal theory, whether tort      *\n*  (including negligence), contract, or otherwise, shall any           *\n*  Contributor, or anyone who distributes Covered Software as          *\n*  permitted above, be liable to You for any direct, indirect,         *\n*  special, incidental, or consequential damages of any character      *\n*  including, without limitation, damages for lost profits, loss of    *\n*  goodwill, work stoppage, computer failure or malfunction, or any    *\n*  and all other commercial damages or losses, even if such party      *\n*  shall have been informed of the possibility of such damages. This   *\n*  limitation of liability shall not apply to liability for death or   *\n*  personal injury resulting from such party's negligence to the       *\n*  extent applicable law prohibits such limitation. Some               *\n*  jurisdictions do not allow the exclusion or limitation of           *\n*  incidental or consequential damages, so this exclusion and          *\n*  limitation may not apply to You.                                    *\n*                                                                      *\n************************************************************************\n\n8. Litigation\n-------------\n\nAny litigation relating to this License may be brought only in the\ncourts of a jurisdiction where the defendant maintains its principal\nplace of business and such litigation shall be governed by laws of that\njurisdiction, without reference to its conflict-of-law provisions.\nNothing in this Section shall prevent a party's ability to bring\ncross-claims or counter-claims.\n\n9. Miscellaneous\n----------------\n\nThis License represents the complete agreement concerning the subject\nmatter hereof. If any provision of this License is held to be\nunenforceable, such provision shall be reformed only to the extent\nnecessary to make it enforceable. Any law or regulation which provides\nthat the language of a contract shall be construed against the drafter\nshall not be used to construe this License against a Contributor.\n\n10. Versions of the License\n---------------------------\n\n10.1. New Versions\n\nMozilla Foundation is the license steward. Except as provided in Section\n10.3, no one other than the license steward has the right to modify or\npublish new versions of this License. Each version will be given a\ndistinguishing version number.\n\n10.2. Effect of New Versions\n\nYou may distribute the Covered Software under the terms of the version\nof the License under which You originally received the Covered Software,\nor under the terms of any subsequent version published by the license\nsteward.\n\n10.3. Modified Versions\n\nIf you create software not governed by this License, and you want to\ncreate a new license for such software, you may create and use a\nmodified version of this License if you rename the license and remove\nany references to the name of the license steward (except to note that\nsuch modified license differs from this License).\n\n10.4. Distributing Source Code Form that is Incompatible With Secondary\nLicenses\n\nIf You choose to distribute Source Code Form that is Incompatible With\nSecondary Licenses under the terms of this version of the License, the\nnotice described in Exhibit B of this License must be attached.\n\nExhibit A - Source Code Form License Notice\n-------------------------------------------\n\n  This Source Code Form is subject to the terms of the Mozilla Public\n  License, v. 2.0. If a copy of the MPL was not distributed with this\n  file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\nIf it is not possible or desirable to put the notice in a particular\nfile, then You may include the notice in a location (such as a LICENSE\nfile in a relevant directory) where a recipient would be likely to look\nfor such a notice.\n\nYou may add additional accurate notices of copyright ownership.\n\nExhibit B - \"Incompatible With Secondary Licenses\" Notice\n---------------------------------------------------------\n\n  This Source Code Form is \"Incompatible With Secondary Licenses\", as\n  defined by the Mozilla Public License, v. 2.0.\n"
  },
  {
    "path": "README.md",
    "content": "# Go-MySQL-Driver\n\n[![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)\n\n\nA MySQL-Driver for Go's [database/sql](https://golang.org/pkg/database/sql/) package\n\n![Go-MySQL-Driver logo](https://raw.github.com/wiki/go-sql-driver/mysql/gomysql_m.png \"Golang Gopher holding the MySQL Dolphin\")\n\n---------------------------------------\n  * [Features](#features)\n  * [Requirements](#requirements)\n  * [Installation](#installation)\n  * [Usage](#usage)\n    * [DSN (Data Source Name)](#dsn-data-source-name)\n      * [Password](#password)\n      * [Protocol](#protocol)\n      * [Address](#address)\n      * [Parameters](#parameters)\n      * [Examples](#examples)\n    * [Connection pool and timeouts](#connection-pool-and-timeouts)\n    * [context.Context Support](#contextcontext-support)\n    * [ColumnType Support](#columntype-support)\n    * [LOAD DATA LOCAL INFILE support](#load-data-local-infile-support)\n    * [time.Time support](#timetime-support)\n    * [Unicode support](#unicode-support)\n  * [Testing / Development](#testing--development)\n  * [License](#license)\n\n---------------------------------------\n\n## Features\n  * Lightweight and [fast](https://github.com/go-sql-driver/sql-benchmark \"golang MySQL-Driver performance\")\n  * Native Go implementation. No C-bindings, just pure Go\n  * Connections over TCP/IPv4, TCP/IPv6, Unix domain sockets or [custom protocols](https://godoc.org/github.com/go-sql-driver/mysql#DialFunc)\n  * Automatic handling of broken connections\n  * Automatic Connection Pooling *(by database/sql package)*\n  * Supports queries larger than 16MB\n  * Full [`sql.RawBytes`](https://golang.org/pkg/database/sql/#RawBytes) support.\n  * Intelligent `LONG DATA` handling in prepared statements\n  * Secure `LOAD DATA LOCAL INFILE` support with file allowlisting and `io.Reader` support\n  * Optional `time.Time` parsing\n  * Optional placeholder interpolation\n  * Supports zlib compression.\n\n## Requirements\n\n* Go 1.22 or higher. We aim to support the 3 latest versions of Go.\n* MySQL (5.7+) and MariaDB (10.5+) are supported.\n* [TiDB](https://github.com/pingcap/tidb) is supported by PingCAP.\n  * Do not ask questions about TiDB in our issue tracker or forum.\n  * [Document](https://docs.pingcap.com/tidb/v6.1/dev-guide-sample-application-golang)\n  * [Forum](https://ask.pingcap.com/)\n* go-mysql would work with Percona Server, Google CloudSQL or Sphinx (2.2.3+).\n  * Maintainers won't support them. Do not expect issues are investigated and resolved by maintainers.\n  * Investigate issues yourself and please send a pull request to fix it.\n\n---------------------------------------\n\n## Installation\nSimple 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:\n```bash\ngo get -u github.com/go-sql-driver/mysql\n```\nMake sure [Git is installed](https://git-scm.com/downloads) on your machine and in your system's `PATH`.\n\n## Usage\n_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.\n\nUse `mysql` as `driverName` and a valid [DSN](#dsn-data-source-name)  as `dataSourceName`:\n\n```go\nimport (\n\t\"database/sql\"\n\t\"time\"\n\n\t_ \"github.com/go-sql-driver/mysql\"\n)\n\n// ...\n\ndb, err := sql.Open(\"mysql\", \"user:password@/dbname\")\nif err != nil {\n\tpanic(err)\n}\n// See \"Important settings\" section.\ndb.SetConnMaxLifetime(time.Minute * 3)\ndb.SetMaxOpenConns(10)\ndb.SetMaxIdleConns(10)\n```\n\n[Examples are available in our Wiki](https://github.com/go-sql-driver/mysql/wiki/Examples \"Go-MySQL-Driver Examples\").\n\n### Important settings\n\n`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.\n\n`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.\n\n`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.\n\n\n### DSN (Data Source Name)\n\nThe 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):\n```\n[username[:password]@][protocol[(address)]]/dbname[?param1=value1&...&paramN=valueN]\n```\n\nA DSN in its fullest form:\n```\nusername:password@protocol(address)/dbname?param=value\n```\n\nExcept for the databasename, all values are optional. So the minimal DSN is:\n```\n/dbname\n```\n\nIf you do not want to preselect a database, leave `dbname` empty:\n```\n/\n```\nThis has the same effect as an empty DSN string:\n```\n\n```\n\n`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:\n\n```\n/dbname%2Fwithslash\n```\n\nAlternatively, [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.\n\n#### Password\nPasswords can consist of any character. Escaping is **not** necessary.\n\n#### Protocol\nSee [net.Dial](https://golang.org/pkg/net/#Dial) for more information which networks are available.\nIn general you should use a Unix domain socket if available and TCP otherwise for best performance.\n\n#### Address\nFor TCP and UDP networks, addresses have the form `host[:port]`.\nIf `port` is omitted, the default port will be used.\nIf `host` is a literal IPv6 address, it must be enclosed in square brackets.\nThe functions [net.JoinHostPort](https://golang.org/pkg/net/#JoinHostPort) and [net.SplitHostPort](https://golang.org/pkg/net/#SplitHostPort) manipulate addresses in this form.\n\nFor 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`.\n\n#### Parameters\n*Parameters are case-sensitive!*\n\nNotice 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`.\n\n##### `allowAllFiles`\n\n```\nType:           bool\nValid Values:   true, false\nDefault:        false\n```\n\n`allowAllFiles=true` disables the file allowlist for `LOAD DATA LOCAL INFILE` and allows *all* files.\n[*Might be insecure!*](https://dev.mysql.com/doc/refman/8.0/en/load-data.html#load-data-local)\n\n##### `allowCleartextPasswords`\n\n```\nType:           bool\nValid Values:   true, false\nDefault:        false\n```\n\n`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.\n\n\n##### `allowFallbackToPlaintext`\n\n```\nType:           bool\nValid Values:   true, false\nDefault:        false\n```\n\n`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)\n\n##### `allowNativePasswords`\n\n```\nType:           bool\nValid Values:   true, false\nDefault:        true\n```\n`allowNativePasswords=false` disallows the usage of MySQL native password method.\n\n##### `allowOldPasswords`\n\n```\nType:           bool\nValid Values:   true, false\nDefault:        false\n```\n`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).\n\n##### `charset`\n\n```\nType:           string\nValid Values:   <name>\nDefault:        none\n```\n\nSets 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`).\n\nSee also [Unicode Support](#unicode-support).\n\n##### `checkConnLiveness`\n\n```\nType:           bool\nValid Values:   true, false\nDefault:        true\n```\n\nOn 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.\n`checkConnLiveness=false` disables this liveness check of connections.\n\n##### `collation`\n\n```\nType:           string\nValid Values:   <name>\nDefault:        utf8mb4_general_ci\n```\n\nSets 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.\n\nA list of valid charsets for a server is retrievable with `SHOW COLLATION`.\n\nThe 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.\n\nCollations 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)).\n\nSee also [Unicode Support](#unicode-support).\n\n##### `clientFoundRows`\n\n```\nType:           bool\nValid Values:   true, false\nDefault:        false\n```\n\n`clientFoundRows=true` causes an UPDATE to return the number of matching rows instead of the number of rows changed.\n\n##### `columnsWithAlias`\n\n```\nType:           bool\nValid Values:   true, false\nDefault:        false\n```\n\nWhen `columnsWithAlias` is true, calls to `sql.Rows.Columns()` will return the table alias and the column name separated by a dot. For example:\n\n```\nSELECT u.id FROM users as u\n```\n\nwill return `u.id` instead of just `id` if `columnsWithAlias=true`.\n\n##### `compress`\n\n```\nType:           bool\nValid Values:   true, false\nDefault:        false\n```\n\nToggles zlib compression. false by default.\n\n##### `interpolateParams`\n\n```\nType:           bool\nValid Values:   true, false\nDefault:        false\n```\n\nIf `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`.\n\n*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)!*\n\n##### `loc`\n\n```\nType:           string\nValid Values:   <escaped name>\nDefault:        UTC\n```\n\nSets 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.\n\nNote 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.\n\nPlease 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`.\n\n##### `timeTruncate`\n\n```\nType:           duration\nDefault:        0\n```\n\n[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\"*.\n\n##### `maxAllowedPacket`\n```\nType:          decimal number\nDefault:       64*1024*1024\n```\n\nMax 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*.\n\n##### `multiStatements`\n\n```\nType:           bool\nValid Values:   true, false\nDefault:        false\n```\n\nAllow 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.\n\nWhen `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.\n\nIt'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:\n\n```go\nconn, _ := db.Conn(ctx)\nconn.Raw(func(conn any) error {\n  ex := conn.(driver.Execer)\n  res, err := ex.Exec(`\n  UPDATE point SET x = 1 WHERE y = 2;\n  UPDATE point SET x = 2 WHERE y = 3;\n  `, nil)\n  // Both slices have 2 elements.\n  log.Print(res.(mysql.Result).AllRowsAffected())\n  log.Print(res.(mysql.Result).AllLastInsertIds())\n})\n```\n\n##### `parseTime`\n\n```\nType:           bool\nValid Values:   true, false\nDefault:        false\n```\n\n`parseTime=true` changes the output type of `DATE` and `DATETIME` values to `time.Time` instead of `[]byte` / `string`\nThe date or datetime like `0000-00-00 00:00:00` is converted into zero value of `time.Time`.\n\n\n##### `readTimeout`\n\n```\nType:           duration\nDefault:        0\n```\n\nI/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\"*.\n\n##### `rejectReadOnly`\n\n```\nType:           bool\nValid Values:   true, false\nDefault:        false\n```\n\n\n`rejectReadOnly=true` causes the driver to reject read-only connections. This\nis for a possible race condition during an automatic failover, where the mysql\nclient gets connected to a read-only replica after the failover.\n\nNote that this should be a fairly rare case, as an automatic failover normally\nhappens when the primary is down, and the race condition shouldn't happen\nunless it comes back up online as soon as the failover is kicked off. On the\nother hand, when this happens, a MySQL application can get stuck on a\nread-only connection until restarted. It is however fairly easy to reproduce,\nfor example, using a manual failover on AWS Aurora's MySQL-compatible cluster.\n\nIf you are not relying on read-only transactions to reject writes that aren't\nsupposed to happen, setting this on some MySQL providers (such as AWS Aurora)\nis safer for failovers.\n\nNote that ERROR 1290 can be returned for a `read-only` server and this option will\ncause a retry for that error. However the same error number is used for some\nother cases. You should ensure your application will never cause an ERROR 1290\nexcept for `read-only` mode when enabling this option.\n\n\n##### `serverPubKey`\n\n```\nType:           string\nValid Values:   <name>\nDefault:        none\n```\n\nServer 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.\nPublic keys are used to transmit encrypted data, e.g. for authentication.\nIf 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.\n\n\n##### `timeout`\n\n```\nType:           duration\nDefault:        OS default\n```\n\nTimeout 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\"*.\n\n\n##### `tls`\n\n```\nType:           bool / string\nValid Values:   true, false, skip-verify, preferred, <name>\nDefault:        false\n```\n\n`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).\n\n\n##### `writeTimeout`\n\n```\nType:           duration\nDefault:        0\n```\n\nI/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\"*.\n\n##### `connectionAttributes`\n\n```\nType:           comma-delimited string of user-defined \"key:value\" pairs\nValid Values:   (<name1>:<value1>,<name2>:<value2>,...)\nDefault:        none\n```\n\n[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.\n\n##### System Variables\n\nAny other parameters are interpreted as system variables:\n  * `<boolean_var>=<value>`: `SET <boolean_var>=<value>`\n  * `<enum_var>=<value>`: `SET <enum_var>=<value>`\n  * `<string_var>=%27<value>%27`: `SET <string_var>='<value>'`\n\nRules:\n* The values for string variables must be quoted with `'`.\n* The values must also be [url.QueryEscape](http://golang.org/pkg/net/url/#QueryEscape)'ed!\n (which implies values of string variables must be wrapped with `%27`).\n\nExamples:\n  * `autocommit=1`: `SET autocommit=1`\n  * [`time_zone=%27Europe%2FParis%27`](https://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html): `SET time_zone='Europe/Paris'`\n  * [`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'`\n\n\n#### Examples\n```\nuser@unix(/path/to/socket)/dbname\n```\n\n```\nroot:pw@unix(/tmp/mysql.sock)/myDatabase?loc=Local\n```\n\n```\nuser:password@tcp(localhost:5555)/dbname?tls=skip-verify&autocommit=true\n```\n\nTreat warnings as errors by setting the system variable [`sql_mode`](https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html):\n```\nuser:password@/dbname?sql_mode=TRADITIONAL\n```\n\nTCP via IPv6:\n```\nuser:password@tcp([de:ad:be:ef::ca:fe]:80)/dbname?timeout=90s&collation=utf8mb4_unicode_ci\n```\n\nTCP on a remote host, e.g. Amazon RDS:\n```\nid:password@tcp(your-amazonaws-uri.com:3306)/dbname\n```\n\nGoogle Cloud SQL on App Engine:\n```\nuser:password@unix(/cloudsql/project-id:region-name:instance-name)/dbname\n```\n\nTCP using default port (3306) on localhost:\n```\nuser:password@tcp/dbname?charset=utf8mb4,utf8&sys_var=esc%40ped\n```\n\nUse the default protocol (tcp) and host (localhost:3306):\n```\nuser:password@/dbname\n```\n\nNo Database preselected:\n```\nuser:password@/\n```\n\n\n### Connection pool and timeouts\nThe 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.\n\n## `ColumnType` Support\nThis 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`.\n\n## `context.Context` Support\nGo 1.8 added `database/sql` support for `context.Context`. This driver supports query timeouts and cancellation via contexts.\nSee [context support in the database/sql package](https://golang.org/doc/go1.8#database_sql) for more details.\n\n> [!IMPORTANT]\n> 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.\n\n\n### `LOAD DATA LOCAL INFILE` support\nFor this feature you need direct access to the package. Therefore you must change the import path (no `_`):\n```go\nimport \"github.com/go-sql-driver/mysql\"\n```\n\nFiles 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)).\n\nTo 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.\n\nSee the [godoc of Go-MySQL-Driver](https://godoc.org/github.com/go-sql-driver/mysql \"golang mysql driver documentation\") for details.\n\n\n### `time.Time` support\nThe 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.\n\nHowever, 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.\n\n**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).\n\n\n### Unicode support\nSince version 1.5 Go-MySQL-Driver automatically uses the collation ` utf8mb4_general_ci` by default.\n\nOther charsets / collations can be set using the [`charset`](#charset) or [`collation`](#collation) DSN parameter.\n\n- When only the `charset` is specified, the `SET NAMES <charset>` query is sent and the server's default collation is used.\n- When both the `charset` and `collation` are specified, the `SET NAMES <charset> COLLATE <collation>` query is sent.\n- 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.\n\nSee http://dev.mysql.com/doc/refman/8.0/en/charset-unicode.html for more details on MySQL's Unicode support.\n\n## Testing / Development\nTo 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.\n\nGo-MySQL-Driver is not feature-complete yet. Your help is very appreciated.\nIf 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).\n\nSee the [Contribution Guidelines](https://github.com/go-sql-driver/mysql/blob/master/.github/CONTRIBUTING.md) for details.\n\n---------------------------------------\n\n## License\nGo-MySQL-Driver is licensed under the [Mozilla Public License Version 2.0](https://raw.github.com/go-sql-driver/mysql/master/LICENSE)\n\nMozilla summarizes the license scope as follows:\n> MPL: The copyleft applies to any files containing MPLed code.\n\n\nThat means:\n  * You can **use** the **unchanged** source code both in private and commercially.\n  * 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).\n  * You **needn't publish** the source code of your library as long as the files licensed under the MPL 2.0 are **unchanged**.\n\nPlease read the [MPL 2.0 FAQ](https://www.mozilla.org/en-US/MPL/2.0/FAQ/) if you have further questions regarding the license.\n\nYou can read the full terms here: [LICENSE](https://raw.github.com/go-sql-driver/mysql/master/LICENSE).\n\n![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\")\n"
  },
  {
    "path": "auth.go",
    "content": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2018 The Go-MySQL-Driver Authors. All rights reserved.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at http://mozilla.org/MPL/2.0/.\n\npackage mysql\n\nimport (\n\t\"crypto/rand\"\n\t\"crypto/rsa\"\n\t\"crypto/sha1\"\n\t\"crypto/sha256\"\n\t\"crypto/sha512\"\n\t\"crypto/x509\"\n\t\"encoding/pem\"\n\t\"fmt\"\n\t\"sync\"\n\n\t\"filippo.io/edwards25519\"\n)\n\n// server pub keys registry\nvar (\n\tserverPubKeyLock     sync.RWMutex\n\tserverPubKeyRegistry map[string]*rsa.PublicKey\n)\n\n// RegisterServerPubKey registers a server RSA public key which can be used to\n// send data in a secure manner to the server without receiving the public key\n// in a potentially insecure way from the server first.\n// Registered keys can afterwards be used adding serverPubKey=<name> to the DSN.\n//\n// Note: The provided rsa.PublicKey instance is exclusively owned by the driver\n// after registering it and may not be modified.\n//\n//\tdata, err := os.ReadFile(\"mykey.pem\")\n//\tif err != nil {\n//\t\tlog.Fatal(err)\n//\t}\n//\n//\tblock, _ := pem.Decode(data)\n//\tif block == nil || block.Type != \"PUBLIC KEY\" {\n//\t\tlog.Fatal(\"failed to decode PEM block containing public key\")\n//\t}\n//\n//\tpub, err := x509.ParsePKIXPublicKey(block.Bytes)\n//\tif err != nil {\n//\t\tlog.Fatal(err)\n//\t}\n//\n//\tif rsaPubKey, ok := pub.(*rsa.PublicKey); ok {\n//\t\tmysql.RegisterServerPubKey(\"mykey\", rsaPubKey)\n//\t} else {\n//\t\tlog.Fatal(\"not a RSA public key\")\n//\t}\nfunc RegisterServerPubKey(name string, pubKey *rsa.PublicKey) {\n\tserverPubKeyLock.Lock()\n\tif serverPubKeyRegistry == nil {\n\t\tserverPubKeyRegistry = make(map[string]*rsa.PublicKey)\n\t}\n\n\tserverPubKeyRegistry[name] = pubKey\n\tserverPubKeyLock.Unlock()\n}\n\n// DeregisterServerPubKey removes the public key registered with the given name.\nfunc DeregisterServerPubKey(name string) {\n\tserverPubKeyLock.Lock()\n\tif serverPubKeyRegistry != nil {\n\t\tdelete(serverPubKeyRegistry, name)\n\t}\n\tserverPubKeyLock.Unlock()\n}\n\nfunc getServerPubKey(name string) (pubKey *rsa.PublicKey) {\n\tserverPubKeyLock.RLock()\n\tif v, ok := serverPubKeyRegistry[name]; ok {\n\t\tpubKey = v\n\t}\n\tserverPubKeyLock.RUnlock()\n\treturn\n}\n\n// Hash password using pre 4.1 (old password) method\n// https://github.com/atcurtis/mariadb/blob/master/mysys/my_rnd.c\ntype myRnd struct {\n\tseed1, seed2 uint32\n}\n\nconst myRndMaxVal = 0x3FFFFFFF\n\n// Pseudo random number generator\nfunc newMyRnd(seed1, seed2 uint32) *myRnd {\n\treturn &myRnd{\n\t\tseed1: seed1 % myRndMaxVal,\n\t\tseed2: seed2 % myRndMaxVal,\n\t}\n}\n\n// Tested to be equivalent to MariaDB's floating point variant\n// http://play.golang.org/p/QHvhd4qved\n// http://play.golang.org/p/RG0q4ElWDx\nfunc (r *myRnd) NextByte() byte {\n\tr.seed1 = (r.seed1*3 + r.seed2) % myRndMaxVal\n\tr.seed2 = (r.seed1 + r.seed2 + 33) % myRndMaxVal\n\n\treturn byte(uint64(r.seed1) * 31 / myRndMaxVal)\n}\n\n// Generate binary hash from byte string using insecure pre 4.1 method\nfunc pwHash(password []byte) (result [2]uint32) {\n\tvar add uint32 = 7\n\tvar tmp uint32\n\n\tresult[0] = 1345345333\n\tresult[1] = 0x12345671\n\n\tfor _, c := range password {\n\t\t// skip spaces and tabs in password\n\t\tif c == ' ' || c == '\\t' {\n\t\t\tcontinue\n\t\t}\n\n\t\ttmp = uint32(c)\n\t\tresult[0] ^= (((result[0] & 63) + add) * tmp) + (result[0] << 8)\n\t\tresult[1] += (result[1] << 8) ^ result[0]\n\t\tadd += tmp\n\t}\n\n\t// Remove sign bit (1<<31)-1)\n\tresult[0] &= 0x7FFFFFFF\n\tresult[1] &= 0x7FFFFFFF\n\n\treturn\n}\n\n// Hash password using insecure pre 4.1 method\nfunc scrambleOldPassword(scramble []byte, password string) []byte {\n\tscramble = scramble[:8]\n\n\thashPw := pwHash([]byte(password))\n\thashSc := pwHash(scramble)\n\n\tr := newMyRnd(hashPw[0]^hashSc[0], hashPw[1]^hashSc[1])\n\n\tvar out [8]byte\n\tfor i := range out {\n\t\tout[i] = r.NextByte() + 64\n\t}\n\n\tmask := r.NextByte()\n\tfor i := range out {\n\t\tout[i] ^= mask\n\t}\n\n\treturn out[:]\n}\n\n// Hash password using 4.1+ method (SHA1)\nfunc scramblePassword(scramble []byte, password string) []byte {\n\tif len(password) == 0 {\n\t\treturn nil\n\t}\n\n\t// stage1Hash = SHA1(password)\n\tcrypt := sha1.New()\n\tcrypt.Write([]byte(password))\n\tstage1 := crypt.Sum(nil)\n\n\t// scrambleHash = SHA1(scramble + SHA1(stage1Hash))\n\t// inner Hash\n\tcrypt.Reset()\n\tcrypt.Write(stage1)\n\thash := crypt.Sum(nil)\n\n\t// outer Hash\n\tcrypt.Reset()\n\tcrypt.Write(scramble)\n\tcrypt.Write(hash)\n\tscramble = crypt.Sum(nil)\n\n\t// token = scrambleHash XOR stage1Hash\n\tfor i := range scramble {\n\t\tscramble[i] ^= stage1[i]\n\t}\n\treturn scramble\n}\n\n// Hash password using MySQL 8+ method (SHA256)\nfunc scrambleSHA256Password(scramble []byte, password string) []byte {\n\tif len(password) == 0 {\n\t\treturn nil\n\t}\n\n\t// XOR(SHA256(password), SHA256(SHA256(SHA256(password)), scramble))\n\n\tcrypt := sha256.New()\n\tcrypt.Write([]byte(password))\n\tmessage1 := crypt.Sum(nil)\n\n\tcrypt.Reset()\n\tcrypt.Write(message1)\n\tmessage1Hash := crypt.Sum(nil)\n\n\tcrypt.Reset()\n\tcrypt.Write(message1Hash)\n\tcrypt.Write(scramble)\n\tmessage2 := crypt.Sum(nil)\n\n\tfor i := range message1 {\n\t\tmessage1[i] ^= message2[i]\n\t}\n\n\treturn message1\n}\n\nfunc encryptPassword(password string, seed []byte, pub *rsa.PublicKey) ([]byte, error) {\n\tplain := make([]byte, len(password)+1)\n\tcopy(plain, password)\n\tfor i := range plain {\n\t\tj := i % len(seed)\n\t\tplain[i] ^= seed[j]\n\t}\n\tsha1 := sha1.New()\n\treturn rsa.EncryptOAEP(sha1, rand.Reader, pub, plain, nil)\n}\n\n// authEd25519 does ed25519 authentication used by MariaDB.\nfunc authEd25519(scramble []byte, password string) ([]byte, error) {\n\t// Derived from https://github.com/MariaDB/server/blob/d8e6bb00888b1f82c031938f4c8ac5d97f6874c3/plugin/auth_ed25519/ref10/sign.c\n\t// Code style is from https://cs.opensource.google/go/go/+/refs/tags/go1.21.5:src/crypto/ed25519/ed25519.go;l=207\n\th := sha512.Sum512([]byte(password))\n\n\ts, err := edwards25519.NewScalar().SetBytesWithClamping(h[:32])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tA := (&edwards25519.Point{}).ScalarBaseMult(s)\n\n\tmh := sha512.New()\n\tmh.Write(h[32:])\n\tmh.Write(scramble)\n\tmessageDigest := mh.Sum(nil)\n\tr, err := edwards25519.NewScalar().SetUniformBytes(messageDigest)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tR := (&edwards25519.Point{}).ScalarBaseMult(r)\n\n\tkh := sha512.New()\n\tkh.Write(R.Bytes())\n\tkh.Write(A.Bytes())\n\tkh.Write(scramble)\n\thramDigest := kh.Sum(nil)\n\tk, err := edwards25519.NewScalar().SetUniformBytes(hramDigest)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tS := k.MultiplyAdd(k, s, r)\n\n\treturn append(R.Bytes(), S.Bytes()...), nil\n}\n\nfunc (mc *mysqlConn) sendEncryptedPassword(seed []byte, pub *rsa.PublicKey) error {\n\tenc, err := encryptPassword(mc.cfg.Passwd, seed, pub)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn mc.writeAuthSwitchPacket(enc)\n}\n\nfunc (mc *mysqlConn) auth(authData []byte, plugin string) ([]byte, error) {\n\tswitch plugin {\n\tcase \"caching_sha2_password\":\n\t\tauthResp := scrambleSHA256Password(authData, mc.cfg.Passwd)\n\t\treturn authResp, nil\n\n\tcase \"mysql_old_password\":\n\t\tif !mc.cfg.AllowOldPasswords {\n\t\t\treturn nil, ErrOldPassword\n\t\t}\n\t\tif len(mc.cfg.Passwd) == 0 {\n\t\t\treturn nil, nil\n\t\t}\n\t\t// Note: there are edge cases where this should work but doesn't;\n\t\t// this is currently \"wontfix\":\n\t\t// https://github.com/go-sql-driver/mysql/issues/184\n\t\tauthResp := append(scrambleOldPassword(authData[:8], mc.cfg.Passwd), 0)\n\t\treturn authResp, nil\n\n\tcase \"mysql_clear_password\":\n\t\tif !mc.cfg.AllowCleartextPasswords {\n\t\t\treturn nil, ErrCleartextPassword\n\t\t}\n\t\t// http://dev.mysql.com/doc/refman/5.7/en/cleartext-authentication-plugin.html\n\t\t// http://dev.mysql.com/doc/refman/5.7/en/pam-authentication-plugin.html\n\t\treturn append([]byte(mc.cfg.Passwd), 0), nil\n\n\tcase \"mysql_native_password\":\n\t\tif !mc.cfg.AllowNativePasswords {\n\t\t\treturn nil, ErrNativePassword\n\t\t}\n\t\t// https://dev.mysql.com/doc/dev/mysql-server/8.4.5/page_protocol_connection_phase_authentication_methods_native_password_authentication.html\n\t\t// Native password authentication only need and will need 20-byte challenge.\n\t\tauthResp := scramblePassword(authData[:20], mc.cfg.Passwd)\n\t\treturn authResp, nil\n\n\tcase \"sha256_password\":\n\t\tif len(mc.cfg.Passwd) == 0 {\n\t\t\treturn []byte{0}, nil\n\t\t}\n\t\t// unlike caching_sha2_password, sha256_password does not accept\n\t\t// cleartext password on unix transport.\n\t\tif mc.cfg.TLS != nil {\n\t\t\t// write cleartext auth packet\n\t\t\treturn append([]byte(mc.cfg.Passwd), 0), nil\n\t\t}\n\n\t\tpubKey := mc.cfg.pubKey\n\t\tif pubKey == nil {\n\t\t\t// request public key from server\n\t\t\treturn []byte{1}, nil\n\t\t}\n\n\t\t// encrypted password\n\t\tenc, err := encryptPassword(mc.cfg.Passwd, authData, pubKey)\n\t\treturn enc, err\n\n\tcase \"client_ed25519\":\n\t\tif len(authData) != 32 {\n\t\t\treturn nil, ErrMalformPkt\n\t\t}\n\t\treturn authEd25519(authData, mc.cfg.Passwd)\n\n\tdefault:\n\t\tmc.log(\"unknown auth plugin:\", plugin)\n\t\treturn nil, ErrUnknownPlugin\n\t}\n}\n\nfunc (mc *mysqlConn) handleAuthResult(oldAuthData []byte, plugin string) error {\n\t// Read Result Packet\n\tauthData, newPlugin, err := mc.readAuthResult()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// handle auth plugin switch, if requested\n\tif newPlugin != \"\" {\n\t\t// If CLIENT_PLUGIN_AUTH capability is not supported, no new cipher is\n\t\t// sent and we have to keep using the cipher sent in the init packet.\n\t\tif authData == nil {\n\t\t\tauthData = oldAuthData\n\t\t} else {\n\t\t\t// copy data from read buffer to owned slice\n\t\t\tcopy(oldAuthData, authData)\n\t\t}\n\n\t\tplugin = newPlugin\n\n\t\tauthResp, err := mc.auth(authData, plugin)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err = mc.writeAuthSwitchPacket(authResp); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Read Result Packet\n\t\tauthData, newPlugin, err = mc.readAuthResult()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Do not allow to change the auth plugin more than once\n\t\tif newPlugin != \"\" {\n\t\t\treturn ErrMalformPkt\n\t\t}\n\t}\n\n\tswitch plugin {\n\n\t// https://dev.mysql.com/blog-archive/preparing-your-community-connector-for-mysql-8-part-2-sha256/\n\tcase \"caching_sha2_password\":\n\t\tswitch len(authData) {\n\t\tcase 0:\n\t\t\treturn nil // auth successful\n\t\tcase 1:\n\t\t\tswitch authData[0] {\n\t\t\tcase cachingSha2PasswordFastAuthSuccess:\n\t\t\t\tif err = mc.resultUnchanged().readResultOK(); err == nil {\n\t\t\t\t\treturn nil // auth successful\n\t\t\t\t}\n\n\t\t\tcase cachingSha2PasswordPerformFullAuthentication:\n\t\t\t\tif mc.cfg.TLS != nil || mc.cfg.Net == \"unix\" {\n\t\t\t\t\t// write cleartext auth packet\n\t\t\t\t\terr = mc.writeAuthSwitchPacket(append([]byte(mc.cfg.Passwd), 0))\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tpubKey := mc.cfg.pubKey\n\t\t\t\t\tif pubKey == nil {\n\t\t\t\t\t\t// request public key from server\n\t\t\t\t\t\tdata, err := mc.buf.takeSmallBuffer(4 + 1)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdata[4] = cachingSha2PasswordRequestPublicKey\n\t\t\t\t\t\terr = mc.writePacket(data)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif data, err = mc.readPacket(); err != nil {\n\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif data[0] != iAuthMoreData {\n\t\t\t\t\t\t\treturn fmt.Errorf(\"unexpected resp from server for caching_sha2_password, perform full authentication\")\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// parse public key\n\t\t\t\t\t\tblock, rest := pem.Decode(data[1:])\n\t\t\t\t\t\tif block == nil {\n\t\t\t\t\t\t\treturn fmt.Errorf(\"no pem data found, data: %s\", rest)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpkix, err := x509.ParsePKIXPublicKey(block.Bytes)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpubKey = pkix.(*rsa.PublicKey)\n\t\t\t\t\t}\n\n\t\t\t\t\t// send encrypted password\n\t\t\t\t\terr = mc.sendEncryptedPassword(oldAuthData, pubKey)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn mc.resultUnchanged().readResultOK()\n\n\t\t\tdefault:\n\t\t\t\treturn ErrMalformPkt\n\t\t\t}\n\t\tdefault:\n\t\t\treturn ErrMalformPkt\n\t\t}\n\n\tcase \"sha256_password\":\n\t\tswitch len(authData) {\n\t\tcase 0:\n\t\t\treturn nil // auth successful\n\t\tdefault:\n\t\t\tblock, _ := pem.Decode(authData)\n\t\t\tif block == nil {\n\t\t\t\treturn fmt.Errorf(\"no Pem data found, data: %s\", authData)\n\t\t\t}\n\n\t\t\tpub, err := x509.ParsePKIXPublicKey(block.Bytes)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// send encrypted password\n\t\t\terr = mc.sendEncryptedPassword(oldAuthData, pub.(*rsa.PublicKey))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn mc.resultUnchanged().readResultOK()\n\t\t}\n\n\tdefault:\n\t\treturn nil // auth successful\n\t}\n\n\treturn err\n}\n"
  },
  {
    "path": "auth_test.go",
    "content": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2018 The Go-MySQL-Driver Authors. All rights reserved.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at http://mozilla.org/MPL/2.0/.\n\npackage mysql\n\nimport (\n\t\"bytes\"\n\t\"crypto/rsa\"\n\t\"crypto/tls\"\n\t\"crypto/x509\"\n\t\"encoding/pem\"\n\t\"fmt\"\n\t\"testing\"\n)\n\nvar testPubKey = []byte(\"-----BEGIN PUBLIC KEY-----\\n\" +\n\t\"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAol0Z8G8U+25Btxk/g/fm\\n\" +\n\t\"UAW/wEKjQCTjkibDE4B+qkuWeiumg6miIRhtilU6m9BFmLQSy1ltYQuu4k17A4tQ\\n\" +\n\t\"rIPpOQYZges/qsDFkZh3wyK5jL5WEFVdOasf6wsfszExnPmcZS4axxoYJfiuilrN\\n\" +\n\t\"hnwinBAqfi3S0sw5MpSI4Zl1AbOrHG4zDI62Gti2PKiMGyYDZTS9xPrBLbN95Kby\\n\" +\n\t\"FFclQLEzA9RJcS1nHFsWtRgHjGPhhjCQxEm9NQ1nePFhCfBfApyfH1VM2VCOQum6\\n\" +\n\t\"Ci9bMuHWjTjckC84mzF99kOxOWVU7mwS6gnJqBzpuz8t3zq8/iQ2y7QrmZV+jTJP\\n\" +\n\t\"WQIDAQAB\\n\" +\n\t\"-----END PUBLIC KEY-----\\n\")\n\nvar testPubKeyRSA *rsa.PublicKey\n\nfunc init() {\n\tblock, _ := pem.Decode(testPubKey)\n\tpub, err := x509.ParsePKIXPublicKey(block.Bytes)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ttestPubKeyRSA = pub.(*rsa.PublicKey)\n}\n\nfunc TestScrambleOldPass(t *testing.T) {\n\tscramble := []byte{9, 8, 7, 6, 5, 4, 3, 2}\n\tvectors := []struct {\n\t\tpass string\n\t\tout  string\n\t}{\n\t\t{\" pass\", \"47575c5a435b4251\"},\n\t\t{\"pass \", \"47575c5a435b4251\"},\n\t\t{\"123\\t456\", \"575c47505b5b5559\"},\n\t\t{\"C0mpl!ca ted#PASS123\", \"5d5d554849584a45\"},\n\t}\n\tfor _, tuple := range vectors {\n\t\tours := scrambleOldPassword(scramble, tuple.pass)\n\t\tif tuple.out != fmt.Sprintf(\"%x\", ours) {\n\t\t\tt.Errorf(\"Failed old password %q\", tuple.pass)\n\t\t}\n\t}\n}\n\nfunc TestScrambleSHA256Pass(t *testing.T) {\n\tscramble := []byte{10, 47, 74, 111, 75, 73, 34, 48, 88, 76, 114, 74, 37, 13, 3, 80, 82, 2, 23, 21}\n\tvectors := []struct {\n\t\tpass string\n\t\tout  string\n\t}{\n\t\t{\"secret\", \"f490e76f66d9d86665ce54d98c78d0acfe2fb0b08b423da807144873d30b312c\"},\n\t\t{\"secret2\", \"abc3934a012cf342e876071c8ee202de51785b430258a7a0138bc79c4d800bc6\"},\n\t}\n\tfor _, tuple := range vectors {\n\t\tours := scrambleSHA256Password(scramble, tuple.pass)\n\t\tif tuple.out != fmt.Sprintf(\"%x\", ours) {\n\t\t\tt.Errorf(\"Failed SHA256 password %q\", tuple.pass)\n\t\t}\n\t}\n}\n\nfunc TestAuthFastCachingSHA256PasswordCached(t *testing.T) {\n\tconn, mc := newRWMockConn(1)\n\tmc.cfg.User = \"root\"\n\tmc.cfg.Passwd = \"secret\"\n\n\tauthData := []byte{90, 105, 74, 126, 30, 48, 37, 56, 3, 23, 115, 127, 69,\n\t\t22, 41, 84, 32, 123, 43, 118}\n\tplugin := \"caching_sha2_password\"\n\n\t// Send Client Authentication Packet\n\tauthResp, err := mc.auth(authData, plugin)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = mc.writeHandshakeResponsePacket(authResp, plugin)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// check written auth response\n\tauthRespStart := 4 + 4 + 4 + 1 + 23 + len(mc.cfg.User) + 1\n\tauthRespEnd := authRespStart + 1 + len(authResp)\n\twrittenAuthRespLen := conn.written[authRespStart]\n\twrittenAuthResp := conn.written[authRespStart+1 : authRespEnd]\n\texpectedAuthResp := []byte{102, 32, 5, 35, 143, 161, 140, 241, 171, 232, 56,\n\t\t139, 43, 14, 107, 196, 249, 170, 147, 60, 220, 204, 120, 178, 214, 15,\n\t\t184, 150, 26, 61, 57, 235}\n\tif writtenAuthRespLen != 32 || !bytes.Equal(writtenAuthResp, expectedAuthResp) {\n\t\tt.Fatalf(\"unexpected written auth response (%d bytes): %v\", writtenAuthRespLen, writtenAuthResp)\n\t}\n\tconn.written = nil\n\n\t// auth response\n\tconn.data = []byte{\n\t\t2, 0, 0, 2, 1, 3, // Fast Auth Success\n\t\t7, 0, 0, 3, 0, 0, 0, 2, 0, 0, 0, // OK\n\t}\n\tconn.maxReads = 1\n\n\t// Handle response to auth packet\n\tif err := mc.handleAuthResult(authData, plugin); err != nil {\n\t\tt.Errorf(\"got error: %v\", err)\n\t}\n}\n\nfunc TestAuthFastCachingSHA256PasswordEmpty(t *testing.T) {\n\tconn, mc := newRWMockConn(1)\n\tmc.cfg.User = \"root\"\n\tmc.cfg.Passwd = \"\"\n\n\tauthData := []byte{90, 105, 74, 126, 30, 48, 37, 56, 3, 23, 115, 127, 69,\n\t\t22, 41, 84, 32, 123, 43, 118}\n\tplugin := \"caching_sha2_password\"\n\n\t// Send Client Authentication Packet\n\tauthResp, err := mc.auth(authData, plugin)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = mc.writeHandshakeResponsePacket(authResp, plugin)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// check written auth response\n\tauthRespStart := 4 + 4 + 4 + 1 + 23 + len(mc.cfg.User) + 1\n\tauthRespEnd := authRespStart + 1 + len(authResp)\n\twrittenAuthRespLen := conn.written[authRespStart]\n\twrittenAuthResp := conn.written[authRespStart+1 : authRespEnd]\n\tif writtenAuthRespLen != 0 {\n\t\tt.Fatalf(\"unexpected written auth response (%d bytes): %v\",\n\t\t\twrittenAuthRespLen, writtenAuthResp)\n\t}\n\tconn.written = nil\n\n\t// auth response\n\tconn.data = []byte{\n\t\t7, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, // OK\n\t}\n\tconn.maxReads = 1\n\n\t// Handle response to auth packet\n\tif err := mc.handleAuthResult(authData, plugin); err != nil {\n\t\tt.Errorf(\"got error: %v\", err)\n\t}\n}\n\nfunc TestAuthFastCachingSHA256PasswordFullRSA(t *testing.T) {\n\tconn, mc := newRWMockConn(1)\n\tmc.cfg.User = \"root\"\n\tmc.cfg.Passwd = \"secret\"\n\n\tauthData := []byte{6, 81, 96, 114, 14, 42, 50, 30, 76, 47, 1, 95, 126, 81,\n\t\t62, 94, 83, 80, 52, 85}\n\tplugin := \"caching_sha2_password\"\n\n\t// Send Client Authentication Packet\n\tauthResp, err := mc.auth(authData, plugin)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = mc.writeHandshakeResponsePacket(authResp, plugin)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// check written auth response\n\tauthRespStart := 4 + 4 + 4 + 1 + 23 + len(mc.cfg.User) + 1\n\tauthRespEnd := authRespStart + 1 + len(authResp)\n\twrittenAuthRespLen := conn.written[authRespStart]\n\twrittenAuthResp := conn.written[authRespStart+1 : authRespEnd]\n\texpectedAuthResp := []byte{171, 201, 138, 146, 89, 159, 11, 170, 0, 67, 165,\n\t\t49, 175, 94, 218, 68, 177, 109, 110, 86, 34, 33, 44, 190, 67, 240, 70,\n\t\t110, 40, 139, 124, 41}\n\tif writtenAuthRespLen != 32 || !bytes.Equal(writtenAuthResp, expectedAuthResp) {\n\t\tt.Fatalf(\"unexpected written auth response (%d bytes): %v\", writtenAuthRespLen, writtenAuthResp)\n\t}\n\tconn.written = nil\n\n\t// auth response\n\tconn.data = []byte{\n\t\t2, 0, 0, 2, 1, 4, // Perform Full Authentication\n\t}\n\tconn.queuedReplies = [][]byte{\n\t\t// pub key response\n\t\tappend([]byte{byte(1 + len(testPubKey)), 1, 0, 4, 1}, testPubKey...),\n\n\t\t// OK\n\t\t{7, 0, 0, 6, 0, 0, 0, 2, 0, 0, 0},\n\t}\n\tconn.maxReads = 3\n\n\t// Handle response to auth packet\n\tif err := mc.handleAuthResult(authData, plugin); err != nil {\n\t\tt.Errorf(\"got error: %v\", err)\n\t}\n\n\tif !bytes.HasPrefix(conn.written, []byte{1, 0, 0, 3, 2, 0, 1, 0, 5}) {\n\t\tt.Errorf(\"unexpected written data: %v\", conn.written)\n\t}\n}\n\nfunc TestAuthFastCachingSHA256PasswordFullRSAWithKey(t *testing.T) {\n\tconn, mc := newRWMockConn(1)\n\tmc.cfg.User = \"root\"\n\tmc.cfg.Passwd = \"secret\"\n\tmc.cfg.pubKey = testPubKeyRSA\n\n\tauthData := []byte{6, 81, 96, 114, 14, 42, 50, 30, 76, 47, 1, 95, 126, 81,\n\t\t62, 94, 83, 80, 52, 85}\n\tplugin := \"caching_sha2_password\"\n\n\t// Send Client Authentication Packet\n\tauthResp, err := mc.auth(authData, plugin)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = mc.writeHandshakeResponsePacket(authResp, plugin)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// check written auth response\n\tauthRespStart := 4 + 4 + 4 + 1 + 23 + len(mc.cfg.User) + 1\n\tauthRespEnd := authRespStart + 1 + len(authResp)\n\twrittenAuthRespLen := conn.written[authRespStart]\n\twrittenAuthResp := conn.written[authRespStart+1 : authRespEnd]\n\texpectedAuthResp := []byte{171, 201, 138, 146, 89, 159, 11, 170, 0, 67, 165,\n\t\t49, 175, 94, 218, 68, 177, 109, 110, 86, 34, 33, 44, 190, 67, 240, 70,\n\t\t110, 40, 139, 124, 41}\n\tif writtenAuthRespLen != 32 || !bytes.Equal(writtenAuthResp, expectedAuthResp) {\n\t\tt.Fatalf(\"unexpected written auth response (%d bytes): %v\", writtenAuthRespLen, writtenAuthResp)\n\t}\n\tconn.written = nil\n\n\t// auth response\n\tconn.data = []byte{\n\t\t2, 0, 0, 2, 1, 4, // Perform Full Authentication\n\t}\n\tconn.queuedReplies = [][]byte{\n\t\t// OK\n\t\t{7, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0},\n\t}\n\tconn.maxReads = 2\n\n\t// Handle response to auth packet\n\tif err := mc.handleAuthResult(authData, plugin); err != nil {\n\t\tt.Errorf(\"got error: %v\", err)\n\t}\n\n\tif !bytes.HasPrefix(conn.written, []byte{0, 1, 0, 3}) {\n\t\tt.Errorf(\"unexpected written data: %v\", conn.written)\n\t}\n}\n\nfunc TestAuthFastCachingSHA256PasswordFullSecure(t *testing.T) {\n\tconn, mc := newRWMockConn(1)\n\tmc.cfg.User = \"root\"\n\tmc.cfg.Passwd = \"secret\"\n\n\tauthData := []byte{6, 81, 96, 114, 14, 42, 50, 30, 76, 47, 1, 95, 126, 81,\n\t\t62, 94, 83, 80, 52, 85}\n\tplugin := \"caching_sha2_password\"\n\n\t// Send Client Authentication Packet\n\tauthResp, err := mc.auth(authData, plugin)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = mc.writeHandshakeResponsePacket(authResp, plugin)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Hack to make the caching_sha2_password plugin believe that the connection\n\t// is secure\n\tmc.cfg.TLS = &tls.Config{InsecureSkipVerify: true}\n\n\t// check written auth response\n\tauthRespStart := 4 + 4 + 4 + 1 + 23 + len(mc.cfg.User) + 1\n\tauthRespEnd := authRespStart + 1 + len(authResp)\n\twrittenAuthRespLen := conn.written[authRespStart]\n\twrittenAuthResp := conn.written[authRespStart+1 : authRespEnd]\n\texpectedAuthResp := []byte{171, 201, 138, 146, 89, 159, 11, 170, 0, 67, 165,\n\t\t49, 175, 94, 218, 68, 177, 109, 110, 86, 34, 33, 44, 190, 67, 240, 70,\n\t\t110, 40, 139, 124, 41}\n\tif writtenAuthRespLen != 32 || !bytes.Equal(writtenAuthResp, expectedAuthResp) {\n\t\tt.Fatalf(\"unexpected written auth response (%d bytes): %v\", writtenAuthRespLen, writtenAuthResp)\n\t}\n\tconn.written = nil\n\n\t// auth response\n\tconn.data = []byte{\n\t\t2, 0, 0, 2, 1, 4, // Perform Full Authentication\n\t}\n\tconn.queuedReplies = [][]byte{\n\t\t// OK\n\t\t{7, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0},\n\t}\n\tconn.maxReads = 3\n\n\t// Handle response to auth packet\n\tif err := mc.handleAuthResult(authData, plugin); err != nil {\n\t\tt.Errorf(\"got error: %v\", err)\n\t}\n\n\tif !bytes.Equal(conn.written, []byte{7, 0, 0, 3, 115, 101, 99, 114, 101, 116, 0}) {\n\t\tt.Errorf(\"unexpected written data: %v\", conn.written)\n\t}\n}\n\nfunc TestAuthFastCleartextPasswordNotAllowed(t *testing.T) {\n\t_, mc := newRWMockConn(1)\n\tmc.cfg.User = \"root\"\n\tmc.cfg.Passwd = \"secret\"\n\n\tauthData := []byte{70, 114, 92, 94, 1, 38, 11, 116, 63, 114, 23, 101, 126,\n\t\t103, 26, 95, 81, 17, 24, 21}\n\tplugin := \"mysql_clear_password\"\n\n\t// Send Client Authentication Packet\n\t_, err := mc.auth(authData, plugin)\n\tif err != ErrCleartextPassword {\n\t\tt.Errorf(\"expected ErrCleartextPassword, got %v\", err)\n\t}\n}\n\nfunc TestAuthFastCleartextPassword(t *testing.T) {\n\tconn, mc := newRWMockConn(1)\n\tmc.cfg.User = \"root\"\n\tmc.cfg.Passwd = \"secret\"\n\tmc.cfg.AllowCleartextPasswords = true\n\n\tauthData := []byte{70, 114, 92, 94, 1, 38, 11, 116, 63, 114, 23, 101, 126,\n\t\t103, 26, 95, 81, 17, 24, 21}\n\tplugin := \"mysql_clear_password\"\n\n\t// Send Client Authentication Packet\n\tauthResp, err := mc.auth(authData, plugin)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = mc.writeHandshakeResponsePacket(authResp, plugin)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// check written auth response\n\tauthRespStart := 4 + 4 + 4 + 1 + 23 + len(mc.cfg.User) + 1\n\tauthRespEnd := authRespStart + 1 + len(authResp)\n\twrittenAuthRespLen := conn.written[authRespStart]\n\twrittenAuthResp := conn.written[authRespStart+1 : authRespEnd]\n\texpectedAuthResp := []byte{115, 101, 99, 114, 101, 116, 0}\n\tif writtenAuthRespLen != 7 || !bytes.Equal(writtenAuthResp, expectedAuthResp) {\n\t\tt.Fatalf(\"unexpected written auth response (%d bytes): %v\", writtenAuthRespLen, writtenAuthResp)\n\t}\n\tconn.written = nil\n\n\t// auth response\n\tconn.data = []byte{\n\t\t7, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, // OK\n\t}\n\tconn.maxReads = 1\n\n\t// Handle response to auth packet\n\tif err := mc.handleAuthResult(authData, plugin); err != nil {\n\t\tt.Errorf(\"got error: %v\", err)\n\t}\n}\n\nfunc TestAuthFastCleartextPasswordEmpty(t *testing.T) {\n\tconn, mc := newRWMockConn(1)\n\tmc.cfg.User = \"root\"\n\tmc.cfg.Passwd = \"\"\n\tmc.cfg.AllowCleartextPasswords = true\n\n\tauthData := []byte{70, 114, 92, 94, 1, 38, 11, 116, 63, 114, 23, 101, 126,\n\t\t103, 26, 95, 81, 17, 24, 21}\n\tplugin := \"mysql_clear_password\"\n\n\t// Send Client Authentication Packet\n\tauthResp, err := mc.auth(authData, plugin)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = mc.writeHandshakeResponsePacket(authResp, plugin)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// check written auth response\n\tauthRespStart := 4 + 4 + 4 + 1 + 23 + len(mc.cfg.User) + 1\n\tauthRespEnd := authRespStart + 1 + len(authResp)\n\twrittenAuthRespLen := conn.written[authRespStart]\n\twrittenAuthResp := conn.written[authRespStart+1 : authRespEnd]\n\texpectedAuthResp := []byte{0}\n\tif writtenAuthRespLen != 1 || !bytes.Equal(writtenAuthResp, expectedAuthResp) {\n\t\tt.Fatalf(\"unexpected written auth response (%d bytes): %v\", writtenAuthRespLen, writtenAuthResp)\n\t}\n\tconn.written = nil\n\n\t// auth response\n\tconn.data = []byte{\n\t\t7, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, // OK\n\t}\n\tconn.maxReads = 1\n\n\t// Handle response to auth packet\n\tif err := mc.handleAuthResult(authData, plugin); err != nil {\n\t\tt.Errorf(\"got error: %v\", err)\n\t}\n}\n\nfunc TestAuthFastNativePasswordNotAllowed(t *testing.T) {\n\t_, mc := newRWMockConn(1)\n\tmc.cfg.User = \"root\"\n\tmc.cfg.Passwd = \"secret\"\n\tmc.cfg.AllowNativePasswords = false\n\n\tauthData := []byte{70, 114, 92, 94, 1, 38, 11, 116, 63, 114, 23, 101, 126,\n\t\t103, 26, 95, 81, 17, 24, 21}\n\tplugin := \"mysql_native_password\"\n\n\t// Send Client Authentication Packet\n\t_, err := mc.auth(authData, plugin)\n\tif err != ErrNativePassword {\n\t\tt.Errorf(\"expected ErrNativePassword, got %v\", err)\n\t}\n}\n\nfunc TestAuthFastNativePassword(t *testing.T) {\n\tconn, mc := newRWMockConn(1)\n\tmc.cfg.User = \"root\"\n\tmc.cfg.Passwd = \"secret\"\n\n\tauthData := []byte{70, 114, 92, 94, 1, 38, 11, 116, 63, 114, 23, 101, 126,\n\t\t103, 26, 95, 81, 17, 24, 21}\n\tplugin := \"mysql_native_password\"\n\n\t// Send Client Authentication Packet\n\tauthResp, err := mc.auth(authData, plugin)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = mc.writeHandshakeResponsePacket(authResp, plugin)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// check written auth response\n\tauthRespStart := 4 + 4 + 4 + 1 + 23 + len(mc.cfg.User) + 1\n\tauthRespEnd := authRespStart + 1 + len(authResp)\n\twrittenAuthRespLen := conn.written[authRespStart]\n\twrittenAuthResp := conn.written[authRespStart+1 : authRespEnd]\n\texpectedAuthResp := []byte{53, 177, 140, 159, 251, 189, 127, 53, 109, 252,\n\t\t172, 50, 211, 192, 240, 164, 26, 48, 207, 45}\n\tif writtenAuthRespLen != 20 || !bytes.Equal(writtenAuthResp, expectedAuthResp) {\n\t\tt.Fatalf(\"unexpected written auth response (%d bytes): %v\", writtenAuthRespLen, writtenAuthResp)\n\t}\n\tconn.written = nil\n\n\t// auth response\n\tconn.data = []byte{\n\t\t7, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, // OK\n\t}\n\tconn.maxReads = 1\n\n\t// Handle response to auth packet\n\tif err := mc.handleAuthResult(authData, plugin); err != nil {\n\t\tt.Errorf(\"got error: %v\", err)\n\t}\n}\n\nfunc TestAuthFastNativePasswordEmpty(t *testing.T) {\n\tconn, mc := newRWMockConn(1)\n\tmc.cfg.User = \"root\"\n\tmc.cfg.Passwd = \"\"\n\n\tauthData := []byte{70, 114, 92, 94, 1, 38, 11, 116, 63, 114, 23, 101, 126,\n\t\t103, 26, 95, 81, 17, 24, 21}\n\tplugin := \"mysql_native_password\"\n\n\t// Send Client Authentication Packet\n\tauthResp, err := mc.auth(authData, plugin)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = mc.writeHandshakeResponsePacket(authResp, plugin)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// check written auth response\n\tauthRespStart := 4 + 4 + 4 + 1 + 23 + len(mc.cfg.User) + 1\n\tauthRespEnd := authRespStart + 1 + len(authResp)\n\twrittenAuthRespLen := conn.written[authRespStart]\n\twrittenAuthResp := conn.written[authRespStart+1 : authRespEnd]\n\tif writtenAuthRespLen != 0 {\n\t\tt.Fatalf(\"unexpected written auth response (%d bytes): %v\",\n\t\t\twrittenAuthRespLen, writtenAuthResp)\n\t}\n\tconn.written = nil\n\n\t// auth response\n\tconn.data = []byte{\n\t\t7, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, // OK\n\t}\n\tconn.maxReads = 1\n\n\t// Handle response to auth packet\n\tif err := mc.handleAuthResult(authData, plugin); err != nil {\n\t\tt.Errorf(\"got error: %v\", err)\n\t}\n}\n\nfunc TestAuthFastSHA256PasswordEmpty(t *testing.T) {\n\tconn, mc := newRWMockConn(1)\n\tmc.cfg.User = \"root\"\n\tmc.cfg.Passwd = \"\"\n\n\tauthData := []byte{6, 81, 96, 114, 14, 42, 50, 30, 76, 47, 1, 95, 126, 81,\n\t\t62, 94, 83, 80, 52, 85}\n\tplugin := \"sha256_password\"\n\n\t// Send Client Authentication Packet\n\tauthResp, err := mc.auth(authData, plugin)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = mc.writeHandshakeResponsePacket(authResp, plugin)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// check written auth response\n\tauthRespStart := 4 + 4 + 4 + 1 + 23 + len(mc.cfg.User) + 1\n\tauthRespEnd := authRespStart + 1 + len(authResp)\n\twrittenAuthRespLen := conn.written[authRespStart]\n\twrittenAuthResp := conn.written[authRespStart+1 : authRespEnd]\n\texpectedAuthResp := []byte{0}\n\tif writtenAuthRespLen != 1 || !bytes.Equal(writtenAuthResp, expectedAuthResp) {\n\t\tt.Fatalf(\"unexpected written auth response (%d bytes): %v\", writtenAuthRespLen, writtenAuthResp)\n\t}\n\tconn.written = nil\n\n\t// auth response (pub key response)\n\tconn.data = append([]byte{byte(1 + len(testPubKey)), 1, 0, 2, 1}, testPubKey...)\n\tconn.queuedReplies = [][]byte{\n\t\t// OK\n\t\t{7, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0},\n\t}\n\tconn.maxReads = 2\n\n\t// Handle response to auth packet\n\tif err := mc.handleAuthResult(authData, plugin); err != nil {\n\t\tt.Errorf(\"got error: %v\", err)\n\t}\n\n\tif !bytes.HasPrefix(conn.written, []byte{0, 1, 0, 3}) {\n\t\tt.Errorf(\"unexpected written data: %v\", conn.written)\n\t}\n}\n\nfunc TestAuthFastSHA256PasswordRSA(t *testing.T) {\n\tconn, mc := newRWMockConn(1)\n\tmc.cfg.User = \"root\"\n\tmc.cfg.Passwd = \"secret\"\n\n\tauthData := []byte{6, 81, 96, 114, 14, 42, 50, 30, 76, 47, 1, 95, 126, 81,\n\t\t62, 94, 83, 80, 52, 85}\n\tplugin := \"sha256_password\"\n\n\t// Send Client Authentication Packet\n\tauthResp, err := mc.auth(authData, plugin)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = mc.writeHandshakeResponsePacket(authResp, plugin)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// check written auth response\n\tauthRespStart := 4 + 4 + 4 + 1 + 23 + len(mc.cfg.User) + 1\n\tauthRespEnd := authRespStart + 1 + len(authResp)\n\twrittenAuthRespLen := conn.written[authRespStart]\n\twrittenAuthResp := conn.written[authRespStart+1 : authRespEnd]\n\texpectedAuthResp := []byte{1}\n\tif writtenAuthRespLen != 1 || !bytes.Equal(writtenAuthResp, expectedAuthResp) {\n\t\tt.Fatalf(\"unexpected written auth response (%d bytes): %v\", writtenAuthRespLen, writtenAuthResp)\n\t}\n\tconn.written = nil\n\n\t// auth response (pub key response)\n\tconn.data = append([]byte{byte(1 + len(testPubKey)), 1, 0, 2, 1}, testPubKey...)\n\tconn.queuedReplies = [][]byte{\n\t\t// OK\n\t\t{7, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0},\n\t}\n\tconn.maxReads = 2\n\n\t// Handle response to auth packet\n\tif err := mc.handleAuthResult(authData, plugin); err != nil {\n\t\tt.Errorf(\"got error: %v\", err)\n\t}\n\n\tif !bytes.HasPrefix(conn.written, []byte{0, 1, 0, 3}) {\n\t\tt.Errorf(\"unexpected written data: %v\", conn.written)\n\t}\n}\n\nfunc TestAuthFastSHA256PasswordRSAWithKey(t *testing.T) {\n\tconn, mc := newRWMockConn(1)\n\tmc.cfg.User = \"root\"\n\tmc.cfg.Passwd = \"secret\"\n\tmc.cfg.pubKey = testPubKeyRSA\n\n\tauthData := []byte{6, 81, 96, 114, 14, 42, 50, 30, 76, 47, 1, 95, 126, 81,\n\t\t62, 94, 83, 80, 52, 85}\n\tplugin := \"sha256_password\"\n\n\t// Send Client Authentication Packet\n\tauthResp, err := mc.auth(authData, plugin)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = mc.writeHandshakeResponsePacket(authResp, plugin)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// auth response (OK)\n\tconn.data = []byte{7, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0}\n\tconn.maxReads = 1\n\n\t// Handle response to auth packet\n\tif err := mc.handleAuthResult(authData, plugin); err != nil {\n\t\tt.Errorf(\"got error: %v\", err)\n\t}\n}\n\nfunc TestAuthFastSHA256PasswordSecure(t *testing.T) {\n\tconn, mc := newRWMockConn(1)\n\tmc.cfg.User = \"root\"\n\tmc.cfg.Passwd = \"secret\"\n\n\t// hack to make the caching_sha2_password plugin believe that the connection\n\t// is secure\n\tmc.cfg.TLS = &tls.Config{InsecureSkipVerify: true}\n\n\tauthData := []byte{6, 81, 96, 114, 14, 42, 50, 30, 76, 47, 1, 95, 126, 81,\n\t\t62, 94, 83, 80, 52, 85}\n\tplugin := \"sha256_password\"\n\n\t// send Client Authentication Packet\n\tauthResp, err := mc.auth(authData, plugin)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// unset TLS config to prevent the actual establishment of a TLS wrapper\n\tmc.cfg.TLS = nil\n\n\terr = mc.writeHandshakeResponsePacket(authResp, plugin)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// check written auth response\n\tauthRespStart := 4 + 4 + 4 + 1 + 23 + len(mc.cfg.User) + 1\n\tauthRespEnd := authRespStart + 1 + len(authResp)\n\twrittenAuthRespLen := conn.written[authRespStart]\n\twrittenAuthResp := conn.written[authRespStart+1 : authRespEnd]\n\texpectedAuthResp := []byte{115, 101, 99, 114, 101, 116, 0}\n\tif writtenAuthRespLen != 7 || !bytes.Equal(writtenAuthResp, expectedAuthResp) {\n\t\tt.Fatalf(\"unexpected written auth response (%d bytes): %v\", writtenAuthRespLen, writtenAuthResp)\n\t}\n\tconn.written = nil\n\n\t// auth response (OK)\n\tconn.data = []byte{7, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0}\n\tconn.maxReads = 1\n\n\t// Handle response to auth packet\n\tif err := mc.handleAuthResult(authData, plugin); err != nil {\n\t\tt.Errorf(\"got error: %v\", err)\n\t}\n\n\tif !bytes.Equal(conn.written, []byte{}) {\n\t\tt.Errorf(\"unexpected written data: %v\", conn.written)\n\t}\n}\n\nfunc TestAuthSwitchCachingSHA256PasswordCached(t *testing.T) {\n\tconn, mc := newRWMockConn(2)\n\tmc.cfg.Passwd = \"secret\"\n\n\t// auth switch request\n\tconn.data = []byte{44, 0, 0, 2, 254, 99, 97, 99, 104, 105, 110, 103, 95,\n\t\t115, 104, 97, 50, 95, 112, 97, 115, 115, 119, 111, 114, 100, 0, 101,\n\t\t11, 26, 18, 94, 97, 22, 72, 2, 46, 70, 106, 29, 55, 45, 94, 76, 90, 84,\n\t\t50, 0}\n\n\t// auth response\n\tconn.queuedReplies = [][]byte{\n\t\t{7, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0}, // OK\n\t}\n\tconn.maxReads = 3\n\n\tauthData := []byte{123, 87, 15, 84, 20, 58, 37, 121, 91, 117, 51, 24, 19,\n\t\t47, 43, 9, 41, 112, 67, 110}\n\tplugin := \"mysql_native_password\"\n\n\tif err := mc.handleAuthResult(authData, plugin); err != nil {\n\t\tt.Errorf(\"got error: %v\", err)\n\t}\n\n\texpectedReply := []byte{\n\t\t// 1. Packet: Hash\n\t\t32, 0, 0, 3, 219, 72, 64, 97, 56, 197, 167, 203, 64, 236, 168, 80, 223,\n\t\t56, 103, 217, 196, 176, 124, 60, 253, 41, 195, 10, 205, 190, 177, 206, 63,\n\t\t118, 211, 69,\n\t}\n\tif !bytes.Equal(conn.written, expectedReply) {\n\t\tt.Errorf(\"got unexpected data: %v\", conn.written)\n\t}\n}\n\nfunc TestAuthSwitchCachingSHA256PasswordEmpty(t *testing.T) {\n\tconn, mc := newRWMockConn(2)\n\tmc.cfg.Passwd = \"\"\n\n\t// auth switch request\n\tconn.data = []byte{44, 0, 0, 2, 254, 99, 97, 99, 104, 105, 110, 103, 95,\n\t\t115, 104, 97, 50, 95, 112, 97, 115, 115, 119, 111, 114, 100, 0, 101,\n\t\t11, 26, 18, 94, 97, 22, 72, 2, 46, 70, 106, 29, 55, 45, 94, 76, 90, 84,\n\t\t50, 0}\n\n\t// auth response\n\tconn.queuedReplies = [][]byte{{7, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0}}\n\tconn.maxReads = 2\n\n\tauthData := []byte{123, 87, 15, 84, 20, 58, 37, 121, 91, 117, 51, 24, 19,\n\t\t47, 43, 9, 41, 112, 67, 110}\n\tplugin := \"mysql_native_password\"\n\n\tif err := mc.handleAuthResult(authData, plugin); err != nil {\n\t\tt.Errorf(\"got error: %v\", err)\n\t}\n\n\texpectedReply := []byte{0, 0, 0, 3}\n\tif !bytes.Equal(conn.written, expectedReply) {\n\t\tt.Errorf(\"got unexpected data: %v\", conn.written)\n\t}\n}\n\nfunc TestAuthSwitchCachingSHA256PasswordFullRSA(t *testing.T) {\n\tconn, mc := newRWMockConn(2)\n\tmc.cfg.Passwd = \"secret\"\n\n\t// auth switch request\n\tconn.data = []byte{44, 0, 0, 2, 254, 99, 97, 99, 104, 105, 110, 103, 95,\n\t\t115, 104, 97, 50, 95, 112, 97, 115, 115, 119, 111, 114, 100, 0, 101,\n\t\t11, 26, 18, 94, 97, 22, 72, 2, 46, 70, 106, 29, 55, 45, 94, 76, 90, 84,\n\t\t50, 0}\n\n\tconn.queuedReplies = [][]byte{\n\t\t// Perform Full Authentication\n\t\t{2, 0, 0, 4, 1, 4},\n\n\t\t// Pub Key Response\n\t\tappend([]byte{byte(1 + len(testPubKey)), 1, 0, 6, 1}, testPubKey...),\n\n\t\t// OK\n\t\t{7, 0, 0, 8, 0, 0, 0, 2, 0, 0, 0},\n\t}\n\tconn.maxReads = 4\n\n\tauthData := []byte{123, 87, 15, 84, 20, 58, 37, 121, 91, 117, 51, 24, 19,\n\t\t47, 43, 9, 41, 112, 67, 110}\n\tplugin := \"mysql_native_password\"\n\n\tif err := mc.handleAuthResult(authData, plugin); err != nil {\n\t\tt.Errorf(\"got error: %v\", err)\n\t}\n\n\texpectedReplyPrefix := []byte{\n\t\t// 1. Packet: Hash\n\t\t32, 0, 0, 3, 219, 72, 64, 97, 56, 197, 167, 203, 64, 236, 168, 80, 223,\n\t\t56, 103, 217, 196, 176, 124, 60, 253, 41, 195, 10, 205, 190, 177, 206, 63,\n\t\t118, 211, 69,\n\n\t\t// 2. Packet: Pub Key Request\n\t\t1, 0, 0, 5, 2,\n\n\t\t// 3. Packet: Encrypted Password\n\t\t0, 1, 0, 7, // [changing bytes]\n\t}\n\tif !bytes.HasPrefix(conn.written, expectedReplyPrefix) {\n\t\tt.Errorf(\"got unexpected data: %v\", conn.written)\n\t}\n}\n\nfunc TestAuthSwitchCachingSHA256PasswordFullRSAWithKey(t *testing.T) {\n\tconn, mc := newRWMockConn(2)\n\tmc.cfg.Passwd = \"secret\"\n\tmc.cfg.pubKey = testPubKeyRSA\n\n\t// auth switch request\n\tconn.data = []byte{44, 0, 0, 2, 254, 99, 97, 99, 104, 105, 110, 103, 95,\n\t\t115, 104, 97, 50, 95, 112, 97, 115, 115, 119, 111, 114, 100, 0, 101,\n\t\t11, 26, 18, 94, 97, 22, 72, 2, 46, 70, 106, 29, 55, 45, 94, 76, 90, 84,\n\t\t50, 0}\n\n\tconn.queuedReplies = [][]byte{\n\t\t// Perform Full Authentication\n\t\t{2, 0, 0, 4, 1, 4},\n\n\t\t// OK\n\t\t{7, 0, 0, 6, 0, 0, 0, 2, 0, 0, 0},\n\t}\n\tconn.maxReads = 3\n\n\tauthData := []byte{123, 87, 15, 84, 20, 58, 37, 121, 91, 117, 51, 24, 19,\n\t\t47, 43, 9, 41, 112, 67, 110}\n\tplugin := \"mysql_native_password\"\n\n\tif err := mc.handleAuthResult(authData, plugin); err != nil {\n\t\tt.Errorf(\"got error: %v\", err)\n\t}\n\n\texpectedReplyPrefix := []byte{\n\t\t// 1. Packet: Hash\n\t\t32, 0, 0, 3, 219, 72, 64, 97, 56, 197, 167, 203, 64, 236, 168, 80, 223,\n\t\t56, 103, 217, 196, 176, 124, 60, 253, 41, 195, 10, 205, 190, 177, 206, 63,\n\t\t118, 211, 69,\n\n\t\t// 2. Packet: Encrypted Password\n\t\t0, 1, 0, 5, // [changing bytes]\n\t}\n\tif !bytes.HasPrefix(conn.written, expectedReplyPrefix) {\n\t\tt.Errorf(\"got unexpected data: %v\", conn.written)\n\t}\n}\n\nfunc TestAuthSwitchCachingSHA256PasswordFullSecure(t *testing.T) {\n\tconn, mc := newRWMockConn(2)\n\tmc.cfg.Passwd = \"secret\"\n\n\t// Hack to make the caching_sha2_password plugin believe that the connection\n\t// is secure\n\tmc.cfg.TLS = &tls.Config{InsecureSkipVerify: true}\n\n\t// auth switch request\n\tconn.data = []byte{44, 0, 0, 2, 254, 99, 97, 99, 104, 105, 110, 103, 95,\n\t\t115, 104, 97, 50, 95, 112, 97, 115, 115, 119, 111, 114, 100, 0, 101,\n\t\t11, 26, 18, 94, 97, 22, 72, 2, 46, 70, 106, 29, 55, 45, 94, 76, 90, 84,\n\t\t50, 0}\n\n\t// auth response\n\tconn.queuedReplies = [][]byte{\n\t\t{2, 0, 0, 4, 1, 4},                // Perform Full Authentication\n\t\t{7, 0, 0, 6, 0, 0, 0, 2, 0, 0, 0}, // OK\n\t}\n\tconn.maxReads = 3\n\n\tauthData := []byte{123, 87, 15, 84, 20, 58, 37, 121, 91, 117, 51, 24, 19,\n\t\t47, 43, 9, 41, 112, 67, 110}\n\tplugin := \"mysql_native_password\"\n\n\tif err := mc.handleAuthResult(authData, plugin); err != nil {\n\t\tt.Errorf(\"got error: %v\", err)\n\t}\n\n\texpectedReply := []byte{\n\t\t// 1. Packet: Hash\n\t\t32, 0, 0, 3, 219, 72, 64, 97, 56, 197, 167, 203, 64, 236, 168, 80, 223,\n\t\t56, 103, 217, 196, 176, 124, 60, 253, 41, 195, 10, 205, 190, 177, 206, 63,\n\t\t118, 211, 69,\n\n\t\t// 2. Packet: Cleartext password\n\t\t7, 0, 0, 5, 115, 101, 99, 114, 101, 116, 0,\n\t}\n\tif !bytes.Equal(conn.written, expectedReply) {\n\t\tt.Errorf(\"got unexpected data: %v\", conn.written)\n\t}\n}\n\nfunc TestAuthSwitchCleartextPasswordNotAllowed(t *testing.T) {\n\tconn, mc := newRWMockConn(2)\n\n\tconn.data = []byte{22, 0, 0, 2, 254, 109, 121, 115, 113, 108, 95, 99, 108,\n\t\t101, 97, 114, 95, 112, 97, 115, 115, 119, 111, 114, 100, 0}\n\tconn.maxReads = 1\n\tauthData := []byte{123, 87, 15, 84, 20, 58, 37, 121, 91, 117, 51, 24, 19,\n\t\t47, 43, 9, 41, 112, 67, 110}\n\tplugin := \"mysql_native_password\"\n\terr := mc.handleAuthResult(authData, plugin)\n\tif err != ErrCleartextPassword {\n\t\tt.Errorf(\"expected ErrCleartextPassword, got %v\", err)\n\t}\n}\n\nfunc TestAuthSwitchCleartextPassword(t *testing.T) {\n\tconn, mc := newRWMockConn(2)\n\tmc.cfg.AllowCleartextPasswords = true\n\tmc.cfg.Passwd = \"secret\"\n\n\t// auth switch request\n\tconn.data = []byte{22, 0, 0, 2, 254, 109, 121, 115, 113, 108, 95, 99, 108,\n\t\t101, 97, 114, 95, 112, 97, 115, 115, 119, 111, 114, 100, 0}\n\n\t// auth response\n\tconn.queuedReplies = [][]byte{{7, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0}}\n\tconn.maxReads = 2\n\n\tauthData := []byte{123, 87, 15, 84, 20, 58, 37, 121, 91, 117, 51, 24, 19,\n\t\t47, 43, 9, 41, 112, 67, 110}\n\tplugin := \"mysql_native_password\"\n\n\tif err := mc.handleAuthResult(authData, plugin); err != nil {\n\t\tt.Errorf(\"got error: %v\", err)\n\t}\n\n\texpectedReply := []byte{7, 0, 0, 3, 115, 101, 99, 114, 101, 116, 0}\n\tif !bytes.Equal(conn.written, expectedReply) {\n\t\tt.Errorf(\"got unexpected data: %v\", conn.written)\n\t}\n}\n\nfunc TestAuthSwitchCleartextPasswordEmpty(t *testing.T) {\n\tconn, mc := newRWMockConn(2)\n\tmc.cfg.AllowCleartextPasswords = true\n\tmc.cfg.Passwd = \"\"\n\n\t// auth switch request\n\tconn.data = []byte{22, 0, 0, 2, 254, 109, 121, 115, 113, 108, 95, 99, 108,\n\t\t101, 97, 114, 95, 112, 97, 115, 115, 119, 111, 114, 100, 0}\n\n\t// auth response\n\tconn.queuedReplies = [][]byte{{7, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0}}\n\tconn.maxReads = 2\n\n\tauthData := []byte{123, 87, 15, 84, 20, 58, 37, 121, 91, 117, 51, 24, 19,\n\t\t47, 43, 9, 41, 112, 67, 110}\n\tplugin := \"mysql_native_password\"\n\n\tif err := mc.handleAuthResult(authData, plugin); err != nil {\n\t\tt.Errorf(\"got error: %v\", err)\n\t}\n\n\texpectedReply := []byte{1, 0, 0, 3, 0}\n\tif !bytes.Equal(conn.written, expectedReply) {\n\t\tt.Errorf(\"got unexpected data: %v\", conn.written)\n\t}\n}\n\nfunc TestAuthSwitchNativePasswordNotAllowed(t *testing.T) {\n\tconn, mc := newRWMockConn(2)\n\tmc.cfg.AllowNativePasswords = false\n\n\tconn.data = []byte{44, 0, 0, 2, 254, 109, 121, 115, 113, 108, 95, 110, 97,\n\t\t116, 105, 118, 101, 95, 112, 97, 115, 115, 119, 111, 114, 100, 0, 96,\n\t\t71, 63, 8, 1, 58, 75, 12, 69, 95, 66, 60, 117, 31, 48, 31, 89, 39, 55,\n\t\t31, 0}\n\tconn.maxReads = 1\n\tauthData := []byte{96, 71, 63, 8, 1, 58, 75, 12, 69, 95, 66, 60, 117, 31,\n\t\t48, 31, 89, 39, 55, 31}\n\tplugin := \"caching_sha2_password\"\n\terr := mc.handleAuthResult(authData, plugin)\n\tif err != ErrNativePassword {\n\t\tt.Errorf(\"expected ErrNativePassword, got %v\", err)\n\t}\n}\n\nfunc TestAuthSwitchNativePassword(t *testing.T) {\n\tconn, mc := newRWMockConn(2)\n\tmc.cfg.AllowNativePasswords = true\n\tmc.cfg.Passwd = \"secret\"\n\n\t// auth switch request\n\tconn.data = []byte{44, 0, 0, 2, 254, 109, 121, 115, 113, 108, 95, 110, 97,\n\t\t116, 105, 118, 101, 95, 112, 97, 115, 115, 119, 111, 114, 100, 0, 96,\n\t\t71, 63, 8, 1, 58, 75, 12, 69, 95, 66, 60, 117, 31, 48, 31, 89, 39, 55,\n\t\t31, 0}\n\n\t// auth response\n\tconn.queuedReplies = [][]byte{{7, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0}}\n\tconn.maxReads = 2\n\n\tauthData := []byte{96, 71, 63, 8, 1, 58, 75, 12, 69, 95, 66, 60, 117, 31,\n\t\t48, 31, 89, 39, 55, 31}\n\tplugin := \"caching_sha2_password\"\n\n\tif err := mc.handleAuthResult(authData, plugin); err != nil {\n\t\tt.Errorf(\"got error: %v\", err)\n\t}\n\n\texpectedReply := []byte{20, 0, 0, 3, 202, 41, 195, 164, 34, 226, 49, 103,\n\t\t21, 211, 167, 199, 227, 116, 8, 48, 57, 71, 149, 146}\n\tif !bytes.Equal(conn.written, expectedReply) {\n\t\tt.Errorf(\"got unexpected data: %v\", conn.written)\n\t}\n}\n\nfunc TestAuthSwitchNativePasswordEmpty(t *testing.T) {\n\tconn, mc := newRWMockConn(2)\n\tmc.cfg.AllowNativePasswords = true\n\tmc.cfg.Passwd = \"\"\n\n\t// auth switch request\n\tconn.data = []byte{44, 0, 0, 2, 254, 109, 121, 115, 113, 108, 95, 110, 97,\n\t\t116, 105, 118, 101, 95, 112, 97, 115, 115, 119, 111, 114, 100, 0, 96,\n\t\t71, 63, 8, 1, 58, 75, 12, 69, 95, 66, 60, 117, 31, 48, 31, 89, 39, 55,\n\t\t31, 0}\n\n\t// auth response\n\tconn.queuedReplies = [][]byte{{7, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0}}\n\tconn.maxReads = 2\n\n\tauthData := []byte{96, 71, 63, 8, 1, 58, 75, 12, 69, 95, 66, 60, 117, 31,\n\t\t48, 31, 89, 39, 55, 31}\n\tplugin := \"caching_sha2_password\"\n\n\tif err := mc.handleAuthResult(authData, plugin); err != nil {\n\t\tt.Errorf(\"got error: %v\", err)\n\t}\n\n\texpectedReply := []byte{0, 0, 0, 3}\n\tif !bytes.Equal(conn.written, expectedReply) {\n\t\tt.Errorf(\"got unexpected data: %v\", conn.written)\n\t}\n}\n\nfunc TestAuthSwitchOldPasswordNotAllowed(t *testing.T) {\n\tconn, mc := newRWMockConn(2)\n\n\tconn.data = []byte{41, 0, 0, 2, 254, 109, 121, 115, 113, 108, 95, 111, 108,\n\t\t100, 95, 112, 97, 115, 115, 119, 111, 114, 100, 0, 95, 84, 103, 43, 61,\n\t\t49, 123, 61, 91, 50, 40, 113, 35, 84, 96, 101, 92, 123, 121, 107, 0}\n\tconn.maxReads = 1\n\tauthData := []byte{95, 84, 103, 43, 61, 49, 123, 61, 91, 50, 40, 113, 35,\n\t\t84, 96, 101, 92, 123, 121, 107}\n\tplugin := \"mysql_native_password\"\n\terr := mc.handleAuthResult(authData, plugin)\n\tif err != ErrOldPassword {\n\t\tt.Errorf(\"expected ErrOldPassword, got %v\", err)\n\t}\n}\n\n// Same to TestAuthSwitchOldPasswordNotAllowed, but use OldAuthSwitch request.\nfunc TestOldAuthSwitchNotAllowed(t *testing.T) {\n\tconn, mc := newRWMockConn(2)\n\n\t// OldAuthSwitch request\n\tconn.data = []byte{1, 0, 0, 2, 0xfe}\n\tconn.maxReads = 1\n\tauthData := []byte{95, 84, 103, 43, 61, 49, 123, 61, 91, 50, 40, 113, 35,\n\t\t84, 96, 101, 92, 123, 121, 107}\n\tplugin := \"mysql_native_password\"\n\terr := mc.handleAuthResult(authData, plugin)\n\tif err != ErrOldPassword {\n\t\tt.Errorf(\"expected ErrOldPassword, got %v\", err)\n\t}\n}\n\nfunc TestAuthSwitchOldPassword(t *testing.T) {\n\tconn, mc := newRWMockConn(2)\n\tmc.cfg.AllowOldPasswords = true\n\tmc.cfg.Passwd = \"secret\"\n\n\t// auth switch request\n\tconn.data = []byte{41, 0, 0, 2, 254, 109, 121, 115, 113, 108, 95, 111, 108,\n\t\t100, 95, 112, 97, 115, 115, 119, 111, 114, 100, 0, 95, 84, 103, 43, 61,\n\t\t49, 123, 61, 91, 50, 40, 113, 35, 84, 96, 101, 92, 123, 121, 107, 0}\n\n\t// auth response\n\tconn.queuedReplies = [][]byte{{8, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0, 0}}\n\tconn.maxReads = 2\n\n\tauthData := []byte{95, 84, 103, 43, 61, 49, 123, 61, 91, 50, 40, 113, 35,\n\t\t84, 96, 101, 92, 123, 121, 107}\n\tplugin := \"mysql_native_password\"\n\n\tif err := mc.handleAuthResult(authData, plugin); err != nil {\n\t\tt.Errorf(\"got error: %v\", err)\n\t}\n\n\texpectedReply := []byte{9, 0, 0, 3, 86, 83, 83, 79, 74, 78, 65, 66, 0}\n\tif !bytes.Equal(conn.written, expectedReply) {\n\t\tt.Errorf(\"got unexpected data: %v\", conn.written)\n\t}\n}\n\n// Same to TestAuthSwitchOldPassword, but use OldAuthSwitch request.\nfunc TestOldAuthSwitch(t *testing.T) {\n\tconn, mc := newRWMockConn(2)\n\tmc.cfg.AllowOldPasswords = true\n\tmc.cfg.Passwd = \"secret\"\n\n\t// OldAuthSwitch request\n\tconn.data = []byte{1, 0, 0, 2, 0xfe}\n\n\t// auth response\n\tconn.queuedReplies = [][]byte{{8, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0, 0}}\n\tconn.maxReads = 2\n\n\tauthData := []byte{95, 84, 103, 43, 61, 49, 123, 61, 91, 50, 40, 113, 35,\n\t\t84, 96, 101, 92, 123, 121, 107}\n\tplugin := \"mysql_native_password\"\n\n\tif err := mc.handleAuthResult(authData, plugin); err != nil {\n\t\tt.Errorf(\"got error: %v\", err)\n\t}\n\n\texpectedReply := []byte{9, 0, 0, 3, 86, 83, 83, 79, 74, 78, 65, 66, 0}\n\tif !bytes.Equal(conn.written, expectedReply) {\n\t\tt.Errorf(\"got unexpected data: %v\", conn.written)\n\t}\n}\nfunc TestAuthSwitchOldPasswordEmpty(t *testing.T) {\n\tconn, mc := newRWMockConn(2)\n\tmc.cfg.AllowOldPasswords = true\n\tmc.cfg.Passwd = \"\"\n\n\t// auth switch request\n\tconn.data = []byte{41, 0, 0, 2, 254, 109, 121, 115, 113, 108, 95, 111, 108,\n\t\t100, 95, 112, 97, 115, 115, 119, 111, 114, 100, 0, 95, 84, 103, 43, 61,\n\t\t49, 123, 61, 91, 50, 40, 113, 35, 84, 96, 101, 92, 123, 121, 107, 0}\n\n\t// auth response\n\tconn.queuedReplies = [][]byte{{8, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0, 0}}\n\tconn.maxReads = 2\n\n\tauthData := []byte{95, 84, 103, 43, 61, 49, 123, 61, 91, 50, 40, 113, 35,\n\t\t84, 96, 101, 92, 123, 121, 107}\n\tplugin := \"mysql_native_password\"\n\n\tif err := mc.handleAuthResult(authData, plugin); err != nil {\n\t\tt.Errorf(\"got error: %v\", err)\n\t}\n\n\texpectedReply := []byte{0, 0, 0, 3}\n\tif !bytes.Equal(conn.written, expectedReply) {\n\t\tt.Errorf(\"got unexpected data: %v\", conn.written)\n\t}\n}\n\n// Same to TestAuthSwitchOldPasswordEmpty, but use OldAuthSwitch request.\nfunc TestOldAuthSwitchPasswordEmpty(t *testing.T) {\n\tconn, mc := newRWMockConn(2)\n\tmc.cfg.AllowOldPasswords = true\n\tmc.cfg.Passwd = \"\"\n\n\t// OldAuthSwitch request.\n\tconn.data = []byte{1, 0, 0, 2, 0xfe}\n\n\t// auth response\n\tconn.queuedReplies = [][]byte{{8, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0, 0}}\n\tconn.maxReads = 2\n\n\tauthData := []byte{95, 84, 103, 43, 61, 49, 123, 61, 91, 50, 40, 113, 35,\n\t\t84, 96, 101, 92, 123, 121, 107}\n\tplugin := \"mysql_native_password\"\n\n\tif err := mc.handleAuthResult(authData, plugin); err != nil {\n\t\tt.Errorf(\"got error: %v\", err)\n\t}\n\n\texpectedReply := []byte{0, 0, 0, 3}\n\tif !bytes.Equal(conn.written, expectedReply) {\n\t\tt.Errorf(\"got unexpected data: %v\", conn.written)\n\t}\n}\n\nfunc TestAuthSwitchSHA256PasswordEmpty(t *testing.T) {\n\tconn, mc := newRWMockConn(2)\n\tmc.cfg.Passwd = \"\"\n\n\t// auth switch request\n\tconn.data = []byte{38, 0, 0, 2, 254, 115, 104, 97, 50, 53, 54, 95, 112, 97,\n\t\t115, 115, 119, 111, 114, 100, 0, 78, 82, 62, 40, 100, 1, 59, 31, 44, 69,\n\t\t33, 112, 8, 81, 51, 96, 65, 82, 16, 114, 0}\n\n\tconn.queuedReplies = [][]byte{\n\t\t// OK\n\t\t{7, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0},\n\t}\n\tconn.maxReads = 3\n\n\tauthData := []byte{123, 87, 15, 84, 20, 58, 37, 121, 91, 117, 51, 24, 19,\n\t\t47, 43, 9, 41, 112, 67, 110}\n\tplugin := \"mysql_native_password\"\n\n\tif err := mc.handleAuthResult(authData, plugin); err != nil {\n\t\tt.Errorf(\"got error: %v\", err)\n\t}\n\n\texpectedReplyPrefix := []byte{\n\t\t// 1. Packet: Empty Password\n\t\t1, 0, 0, 3, 0,\n\t}\n\tif !bytes.HasPrefix(conn.written, expectedReplyPrefix) {\n\t\tt.Errorf(\"got unexpected data: %v\", conn.written)\n\t}\n}\n\nfunc TestAuthSwitchSHA256PasswordRSA(t *testing.T) {\n\tconn, mc := newRWMockConn(2)\n\tmc.cfg.Passwd = \"secret\"\n\n\t// auth switch request\n\tconn.data = []byte{38, 0, 0, 2, 254, 115, 104, 97, 50, 53, 54, 95, 112, 97,\n\t\t115, 115, 119, 111, 114, 100, 0, 78, 82, 62, 40, 100, 1, 59, 31, 44, 69,\n\t\t33, 112, 8, 81, 51, 96, 65, 82, 16, 114, 0}\n\n\tconn.queuedReplies = [][]byte{\n\t\t// Pub Key Response\n\t\tappend([]byte{byte(1 + len(testPubKey)), 1, 0, 4, 1}, testPubKey...),\n\n\t\t// OK\n\t\t{7, 0, 0, 6, 0, 0, 0, 2, 0, 0, 0},\n\t}\n\tconn.maxReads = 3\n\n\tauthData := []byte{123, 87, 15, 84, 20, 58, 37, 121, 91, 117, 51, 24, 19,\n\t\t47, 43, 9, 41, 112, 67, 110}\n\tplugin := \"mysql_native_password\"\n\n\tif err := mc.handleAuthResult(authData, plugin); err != nil {\n\t\tt.Errorf(\"got error: %v\", err)\n\t}\n\n\texpectedReplyPrefix := []byte{\n\t\t// 1. Packet: Pub Key Request\n\t\t1, 0, 0, 3, 1,\n\n\t\t// 2. Packet: Encrypted Password\n\t\t0, 1, 0, 5, // [changing bytes]\n\t}\n\tif !bytes.HasPrefix(conn.written, expectedReplyPrefix) {\n\t\tt.Errorf(\"got unexpected data: %v\", conn.written)\n\t}\n}\n\nfunc TestAuthSwitchSHA256PasswordRSAWithKey(t *testing.T) {\n\tconn, mc := newRWMockConn(2)\n\tmc.cfg.Passwd = \"secret\"\n\tmc.cfg.pubKey = testPubKeyRSA\n\n\t// auth switch request\n\tconn.data = []byte{38, 0, 0, 2, 254, 115, 104, 97, 50, 53, 54, 95, 112, 97,\n\t\t115, 115, 119, 111, 114, 100, 0, 78, 82, 62, 40, 100, 1, 59, 31, 44, 69,\n\t\t33, 112, 8, 81, 51, 96, 65, 82, 16, 114, 0}\n\n\tconn.queuedReplies = [][]byte{\n\t\t// OK\n\t\t{7, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0},\n\t}\n\tconn.maxReads = 2\n\n\tauthData := []byte{123, 87, 15, 84, 20, 58, 37, 121, 91, 117, 51, 24, 19,\n\t\t47, 43, 9, 41, 112, 67, 110}\n\tplugin := \"mysql_native_password\"\n\n\tif err := mc.handleAuthResult(authData, plugin); err != nil {\n\t\tt.Errorf(\"got error: %v\", err)\n\t}\n\n\texpectedReplyPrefix := []byte{\n\t\t// 1. Packet: Encrypted Password\n\t\t0, 1, 0, 3, // [changing bytes]\n\t}\n\tif !bytes.HasPrefix(conn.written, expectedReplyPrefix) {\n\t\tt.Errorf(\"got unexpected data: %v\", conn.written)\n\t}\n}\n\nfunc TestAuthSwitchSHA256PasswordSecure(t *testing.T) {\n\tconn, mc := newRWMockConn(2)\n\tmc.cfg.Passwd = \"secret\"\n\n\t// Hack to make the caching_sha2_password plugin believe that the connection\n\t// is secure\n\tmc.cfg.TLS = &tls.Config{InsecureSkipVerify: true}\n\n\t// auth switch request\n\tconn.data = []byte{38, 0, 0, 2, 254, 115, 104, 97, 50, 53, 54, 95, 112, 97,\n\t\t115, 115, 119, 111, 114, 100, 0, 78, 82, 62, 40, 100, 1, 59, 31, 44, 69,\n\t\t33, 112, 8, 81, 51, 96, 65, 82, 16, 114, 0}\n\n\tconn.queuedReplies = [][]byte{\n\t\t// OK\n\t\t{7, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0},\n\t}\n\tconn.maxReads = 2\n\n\tauthData := []byte{123, 87, 15, 84, 20, 58, 37, 121, 91, 117, 51, 24, 19,\n\t\t47, 43, 9, 41, 112, 67, 110}\n\tplugin := \"mysql_native_password\"\n\n\tif err := mc.handleAuthResult(authData, plugin); err != nil {\n\t\tt.Errorf(\"got error: %v\", err)\n\t}\n\n\texpectedReplyPrefix := []byte{\n\t\t// 1. Packet: Cleartext Password\n\t\t7, 0, 0, 3, 115, 101, 99, 114, 101, 116, 0,\n\t}\n\tif !bytes.Equal(conn.written, expectedReplyPrefix) {\n\t\tt.Errorf(\"got unexpected data: %v\", conn.written)\n\t}\n}\n\n// Derived from https://github.com/MariaDB/server/blob/6b2287fff23fbdc362499501c562f01d0d2db52e/plugin/auth_ed25519/ed25519-t.c\nfunc TestEd25519Auth(t *testing.T) {\n\tconn, mc := newRWMockConn(1)\n\tmc.cfg.User = \"root\"\n\tmc.cfg.Passwd = \"foobar\"\n\n\tauthData := []byte(\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\")\n\tplugin := \"client_ed25519\"\n\n\t// Send Client Authentication Packet\n\tauthResp, err := mc.auth(authData, plugin)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = mc.writeHandshakeResponsePacket(authResp, plugin)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// check written auth response\n\tauthRespStart := 4 + 4 + 4 + 1 + 23 + len(mc.cfg.User) + 1\n\tauthRespEnd := authRespStart + 1 + len(authResp)\n\twrittenAuthRespLen := conn.written[authRespStart]\n\twrittenAuthResp := conn.written[authRespStart+1 : authRespEnd]\n\texpectedAuthResp := []byte{\n\t\t232, 61, 201, 63, 67, 63, 51, 53, 86, 73, 238, 35, 170, 117, 146,\n\t\t214, 26, 17, 35, 9, 8, 132, 245, 141, 48, 99, 66, 58, 36, 228, 48,\n\t\t84, 115, 254, 187, 168, 88, 162, 249, 57, 35, 85, 79, 238, 167, 106,\n\t\t68, 117, 56, 135, 171, 47, 20, 14, 133, 79, 15, 229, 124, 160, 176,\n\t\t100, 138, 14,\n\t}\n\tif writtenAuthRespLen != 64 {\n\t\tt.Fatalf(\"expected 64 bytes from client, got %d\", writtenAuthRespLen)\n\t}\n\tif !bytes.Equal(writtenAuthResp, expectedAuthResp) {\n\t\tt.Fatalf(\"auth response did not match expected value:\\n%v\\n%v\", writtenAuthResp, expectedAuthResp)\n\t}\n\tconn.written = nil\n\n\t// auth response\n\tconn.data = []byte{\n\t\t7, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, // OK\n\t}\n\tconn.maxReads = 1\n\n\t// Handle response to auth packet\n\tif err := mc.handleAuthResult(authData, plugin); err != nil {\n\t\tt.Errorf(\"got error: %v\", err)\n\t}\n}\n"
  },
  {
    "path": "benchmark_test.go",
    "content": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at http://mozilla.org/MPL/2.0/.\n\npackage mysql\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"database/sql\"\n\t\"database/sql/driver\"\n\t\"fmt\"\n\t\"math\"\n\t\"runtime\"\n\t\"strings\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"testing\"\n\t\"time\"\n)\n\ntype TB testing.B\n\nfunc (tb *TB) check(err error) {\n\tif err != nil {\n\t\ttb.Fatal(err)\n\t}\n}\n\nfunc (tb *TB) checkDB(db *sql.DB, err error) *sql.DB {\n\ttb.check(err)\n\treturn db\n}\n\nfunc (tb *TB) checkRows(rows *sql.Rows, err error) *sql.Rows {\n\ttb.check(err)\n\treturn rows\n}\n\nfunc (tb *TB) checkStmt(stmt *sql.Stmt, err error) *sql.Stmt {\n\ttb.check(err)\n\treturn stmt\n}\n\nfunc initDB(b *testing.B, compress bool, queries ...string) *sql.DB {\n\ttb := (*TB)(b)\n\tcomprStr := \"\"\n\tif compress {\n\t\tcomprStr = \"&compress=1\"\n\t}\n\tdb := tb.checkDB(sql.Open(driverNameTest, dsn+comprStr))\n\tfor _, query := range queries {\n\t\tif _, err := db.Exec(query); err != nil {\n\t\t\tb.Fatalf(\"error on %q: %v\", query, err)\n\t\t}\n\t}\n\treturn db\n}\n\nconst concurrencyLevel = 10\n\nfunc BenchmarkQuery(b *testing.B) {\n\tbenchmarkQuery(b, false)\n}\n\nfunc BenchmarkQueryCompressed(b *testing.B) {\n\tbenchmarkQuery(b, true)\n}\n\nfunc benchmarkQuery(b *testing.B, compr bool) {\n\ttb := (*TB)(b)\n\tb.ReportAllocs()\n\tdb := initDB(b, compr,\n\t\t\"DROP TABLE IF EXISTS foo\",\n\t\t\"CREATE TABLE foo (id INT PRIMARY KEY, val CHAR(50))\",\n\t\t`INSERT INTO foo VALUES (1, \"one\")`,\n\t\t`INSERT INTO foo VALUES (2, \"two\")`,\n\t)\n\tdb.SetMaxIdleConns(concurrencyLevel)\n\tdefer db.Close()\n\n\tstmt := tb.checkStmt(db.Prepare(\"SELECT val FROM foo WHERE id=?\"))\n\tdefer stmt.Close()\n\n\tremain := int64(b.N)\n\tvar wg sync.WaitGroup\n\twg.Add(concurrencyLevel)\n\tdefer wg.Wait()\n\tb.StartTimer()\n\n\tfor i := 0; i < concurrencyLevel; i++ {\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tif atomic.AddInt64(&remain, -1) < 0 {\n\t\t\t\t\twg.Done()\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tvar got string\n\t\t\t\ttb.check(stmt.QueryRow(1).Scan(&got))\n\t\t\t\tif got != \"one\" {\n\t\t\t\t\tb.Errorf(\"query = %q; want one\", got)\n\t\t\t\t\twg.Done()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n}\n\nfunc BenchmarkExec(b *testing.B) {\n\ttb := (*TB)(b)\n\tdb := tb.checkDB(sql.Open(driverNameTest, dsn))\n\tdb.SetMaxIdleConns(concurrencyLevel)\n\tdefer db.Close()\n\n\tstmt := tb.checkStmt(db.Prepare(\"DO 1\"))\n\tdefer stmt.Close()\n\n\tremain := int64(b.N)\n\tvar wg sync.WaitGroup\n\twg.Add(concurrencyLevel)\n\tdefer wg.Wait()\n\n\tb.ReportAllocs()\n\tb.ResetTimer()\n\n\tfor i := 0; i < concurrencyLevel; i++ {\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tif atomic.AddInt64(&remain, -1) < 0 {\n\t\t\t\t\twg.Done()\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif _, err := stmt.Exec(); err != nil {\n\t\t\t\t\tb.Logf(\"stmt.Exec failed: %v\", err)\n\t\t\t\t\tb.Fail()\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n}\n\n// data, but no db writes\nvar roundtripSample []byte\n\nfunc initRoundtripBenchmarks() ([]byte, int, int) {\n\tif roundtripSample == nil {\n\t\troundtripSample = []byte(strings.Repeat(\"0123456789abcdef\", 1024*1024))\n\t}\n\treturn roundtripSample, 16, len(roundtripSample)\n}\n\nfunc BenchmarkRoundtripTxt(b *testing.B) {\n\tsample, min, max := initRoundtripBenchmarks()\n\tsampleString := string(sample)\n\ttb := (*TB)(b)\n\tdb := tb.checkDB(sql.Open(driverNameTest, dsn))\n\tdefer db.Close()\n\n\tb.ReportAllocs()\n\tb.ResetTimer()\n\n\tvar result string\n\tfor i := 0; i < b.N; i++ {\n\t\tlength := min + i\n\t\tif length > max {\n\t\t\tlength = max\n\t\t}\n\t\ttest := sampleString[0:length]\n\t\trows := tb.checkRows(db.Query(`SELECT \"` + test + `\"`))\n\t\tif !rows.Next() {\n\t\t\trows.Close()\n\t\t\tb.Fatalf(\"crashed\")\n\t\t}\n\t\terr := rows.Scan(&result)\n\t\tif err != nil {\n\t\t\trows.Close()\n\t\t\tb.Fatalf(\"crashed\")\n\t\t}\n\t\tif result != test {\n\t\t\trows.Close()\n\t\t\tb.Errorf(\"mismatch\")\n\t\t}\n\t\trows.Close()\n\t}\n}\n\nfunc BenchmarkRoundtripBin(b *testing.B) {\n\tsample, min, max := initRoundtripBenchmarks()\n\ttb := (*TB)(b)\n\tdb := tb.checkDB(sql.Open(driverNameTest, dsn))\n\tdefer db.Close()\n\tstmt := tb.checkStmt(db.Prepare(\"SELECT ?\"))\n\tdefer stmt.Close()\n\n\tb.ReportAllocs()\n\tb.ResetTimer()\n\tvar result sql.RawBytes\n\tfor i := 0; i < b.N; i++ {\n\t\tlength := min + i\n\t\tif length > max {\n\t\t\tlength = max\n\t\t}\n\t\ttest := sample[0:length]\n\t\trows := tb.checkRows(stmt.Query(test))\n\t\tif !rows.Next() {\n\t\t\trows.Close()\n\t\t\tb.Fatalf(\"crashed\")\n\t\t}\n\t\terr := rows.Scan(&result)\n\t\tif err != nil {\n\t\t\trows.Close()\n\t\t\tb.Fatalf(\"crashed\")\n\t\t}\n\t\tif !bytes.Equal(result, test) {\n\t\t\trows.Close()\n\t\t\tb.Errorf(\"mismatch\")\n\t\t}\n\t\trows.Close()\n\t}\n}\n\nfunc BenchmarkInterpolation(b *testing.B) {\n\tmc := &mysqlConn{\n\t\tcfg: &Config{\n\t\t\tInterpolateParams: true,\n\t\t\tLoc:               time.UTC,\n\t\t},\n\t\tmaxAllowedPacket: maxPacketSize,\n\t\tmaxWriteSize:     maxPacketSize - 1,\n\t\tbuf:              newBuffer(),\n\t}\n\n\targs := []driver.Value{\n\t\tint64(42424242),\n\t\tfloat64(math.Pi),\n\t\tfalse,\n\t\ttime.Unix(1423411542, 807015000),\n\t\t[]byte(\"bytes containing special chars ' \\\" \\a \\x00\"),\n\t\t\"string containing special chars ' \\\" \\a \\x00\",\n\t}\n\tq := \"SELECT ?, ?, ?, ?, ?, ?\"\n\n\tb.ReportAllocs()\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\t_, err := mc.interpolateParams(q, args)\n\t\tif err != nil {\n\t\t\tb.Fatal(err)\n\t\t}\n\t}\n}\n\nfunc benchmarkQueryContext(b *testing.B, db *sql.DB, p int) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\tdb.SetMaxIdleConns(p * runtime.GOMAXPROCS(0))\n\n\ttb := (*TB)(b)\n\tstmt := tb.checkStmt(db.PrepareContext(ctx, \"SELECT val FROM foo WHERE id=?\"))\n\tdefer stmt.Close()\n\n\tb.SetParallelism(p)\n\tb.ReportAllocs()\n\tb.ResetTimer()\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tvar got string\n\t\tfor pb.Next() {\n\t\t\ttb.check(stmt.QueryRow(1).Scan(&got))\n\t\t\tif got != \"one\" {\n\t\t\t\tb.Fatalf(\"query = %q; want one\", got)\n\t\t\t}\n\t\t}\n\t})\n}\n\nfunc BenchmarkQueryContext(b *testing.B) {\n\tdb := initDB(b, false,\n\t\t\"DROP TABLE IF EXISTS foo\",\n\t\t\"CREATE TABLE foo (id INT PRIMARY KEY, val CHAR(50))\",\n\t\t`INSERT INTO foo VALUES (1, \"one\")`,\n\t\t`INSERT INTO foo VALUES (2, \"two\")`,\n\t)\n\tdefer db.Close()\n\tfor _, p := range []int{1, 2, 3, 4} {\n\t\tb.Run(fmt.Sprintf(\"%d\", p), func(b *testing.B) {\n\t\t\tbenchmarkQueryContext(b, db, p)\n\t\t})\n\t}\n}\n\nfunc benchmarkExecContext(b *testing.B, db *sql.DB, p int) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\tdb.SetMaxIdleConns(p * runtime.GOMAXPROCS(0))\n\n\ttb := (*TB)(b)\n\tstmt := tb.checkStmt(db.PrepareContext(ctx, \"DO 1\"))\n\tdefer stmt.Close()\n\n\tb.SetParallelism(p)\n\tb.ReportAllocs()\n\tb.ResetTimer()\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tfor pb.Next() {\n\t\t\tif _, err := stmt.ExecContext(ctx); err != nil {\n\t\t\t\tb.Fatal(err)\n\t\t\t}\n\t\t}\n\t})\n}\n\nfunc BenchmarkExecContext(b *testing.B) {\n\tdb := initDB(b, false,\n\t\t\"DROP TABLE IF EXISTS foo\",\n\t\t\"CREATE TABLE foo (id INT PRIMARY KEY, val CHAR(50))\",\n\t\t`INSERT INTO foo VALUES (1, \"one\")`,\n\t\t`INSERT INTO foo VALUES (2, \"two\")`,\n\t)\n\tdefer db.Close()\n\tfor _, p := range []int{1, 2, 3, 4} {\n\t\tb.Run(fmt.Sprintf(\"%d\", p), func(b *testing.B) {\n\t\t\tbenchmarkExecContext(b, db, p)\n\t\t})\n\t}\n}\n\n// BenchmarkQueryRawBytes benchmarks fetching 100 blobs using sql.RawBytes.\n// \"size=\" means size of each blobs.\nfunc BenchmarkQueryRawBytes(b *testing.B) {\n\tvar sizes []int = []int{100, 1000, 2000, 4000, 8000, 12000, 16000, 32000, 64000, 256000}\n\tdb := initDB(b, false,\n\t\t\"DROP TABLE IF EXISTS bench_rawbytes\",\n\t\t\"CREATE TABLE bench_rawbytes (id INT PRIMARY KEY, val LONGBLOB)\",\n\t)\n\tdefer db.Close()\n\n\tblob := make([]byte, sizes[len(sizes)-1])\n\tfor i := range blob {\n\t\tblob[i] = 42\n\t}\n\tfor i := 0; i < 100; i++ {\n\t\t_, err := db.Exec(\"INSERT INTO bench_rawbytes VALUES (?, ?)\", i, blob)\n\t\tif err != nil {\n\t\t\tb.Fatal(err)\n\t\t}\n\t}\n\n\tfor _, s := range sizes {\n\t\tb.Run(fmt.Sprintf(\"size=%v\", s), func(b *testing.B) {\n\t\t\tdb.SetMaxIdleConns(0)\n\t\t\tdb.SetMaxIdleConns(1)\n\t\t\tb.ReportAllocs()\n\t\t\tb.ResetTimer()\n\n\t\t\tfor j := 0; j < b.N; j++ {\n\t\t\t\trows, err := db.Query(\"SELECT LEFT(val, ?) as v FROM bench_rawbytes\", s)\n\t\t\t\tif err != nil {\n\t\t\t\t\tb.Fatal(err)\n\t\t\t\t}\n\t\t\t\tnrows := 0\n\t\t\t\tfor rows.Next() {\n\t\t\t\t\tvar buf sql.RawBytes\n\t\t\t\t\terr := rows.Scan(&buf)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tb.Fatal(err)\n\t\t\t\t\t}\n\t\t\t\t\tif len(buf) != s {\n\t\t\t\t\t\tb.Fatalf(\"size mismatch: expected %v, got %v\", s, len(buf))\n\t\t\t\t\t}\n\t\t\t\t\tnrows++\n\t\t\t\t}\n\t\t\t\trows.Close()\n\t\t\t\tif nrows != 100 {\n\t\t\t\t\tb.Fatalf(\"numbers of rows mismatch: expected %v, got %v\", 100, nrows)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc benchmark10kRows(b *testing.B, compress bool) {\n\t// Setup -- prepare 10000 rows.\n\tdb := initDB(b, compress,\n\t\t\"DROP TABLE IF EXISTS foo\",\n\t\t\"CREATE TABLE foo (id INT PRIMARY KEY, val TEXT)\")\n\tdefer db.Close()\n\n\tsval := strings.Repeat(\"x\", 50)\n\tstmt, err := db.Prepare(`INSERT INTO foo (id, val) VALUES (?, ?)` + strings.Repeat(\",(?,?)\", 99))\n\tif err != nil {\n\t\tb.Errorf(\"failed to prepare query: %v\", err)\n\t\treturn\n\t}\n\n\targs := make([]any, 200)\n\tfor i := 1; i < 200; i += 2 {\n\t\targs[i] = sval\n\t}\n\tfor i := 0; i < 10000; i += 100 {\n\t\tfor j := 0; j < 100; j++ {\n\t\t\targs[j*2] = i + j\n\t\t}\n\t\t_, err := stmt.Exec(args...)\n\t\tif err != nil {\n\t\t\tb.Error(err)\n\t\t\treturn\n\t\t}\n\t}\n\tstmt.Close()\n\n\t// benchmark function called several times with different b.N.\n\t// it means heavy setup is called multiple times.\n\t// Use b.Run() to run expensive setup only once.\n\t// Go 1.24 introduced b.Loop() for this purpose. But we keep this\n\t// benchmark compatible with Go 1.20.\n\tb.Run(\"query\", func(b *testing.B) {\n\t\tb.ReportAllocs()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\trows, err := db.Query(`SELECT id, val FROM foo`)\n\t\t\tif err != nil {\n\t\t\t\tb.Errorf(\"failed to select: %v\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// rows.Scan() escapes arguments. So these variables must be defined\n\t\t\t// before loop.\n\t\t\tvar i int\n\t\t\tvar s sql.RawBytes\n\t\t\tfor rows.Next() {\n\t\t\t\tif err := rows.Scan(&i, &s); err != nil {\n\t\t\t\t\tb.Errorf(\"failed to scan: %v\", err)\n\t\t\t\t\trows.Close()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err = rows.Err(); err != nil {\n\t\t\t\tb.Errorf(\"failed to read rows: %v\", err)\n\t\t\t}\n\t\t\trows.Close()\n\t\t}\n\t})\n}\n\n// BenchmarkReceive10kRows measures performance of receiving large number of rows.\nfunc BenchmarkReceive10kRows(b *testing.B) {\n\tbenchmark10kRows(b, false)\n}\n\nfunc BenchmarkReceive10kRowsCompressed(b *testing.B) {\n\tbenchmark10kRows(b, true)\n}\n\n// BenchmarkReceiveMetadata measures performance of receiving lots of metadata compare to data in rows\nfunc BenchmarkReceiveMetadata(b *testing.B) {\n\ttb := (*TB)(b)\n\n\t// Create a table with 1000 integer fields\n\tcreateTableQuery := \"CREATE TABLE large_integer_table (\"\n\tfor i := 0; i < 1000; i++ {\n\t\tcreateTableQuery += fmt.Sprintf(\"col_%d INT\", i)\n\t\tif i < 999 {\n\t\t\tcreateTableQuery += \", \"\n\t\t}\n\t}\n\tcreateTableQuery += \")\"\n\n\t// Initialize database\n\tdb := initDB(b, false,\n\t\t\"DROP TABLE IF EXISTS large_integer_table\",\n\t\tcreateTableQuery,\n\t\t\"INSERT INTO large_integer_table VALUES (\"+\n\t\t\tstrings.Repeat(\"0,\", 999)+\"0)\", // Insert a row of zeros\n\t)\n\tdefer db.Close()\n\n\tb.Run(\"query\", func(b *testing.B) {\n\t\tdb.SetMaxIdleConns(0)\n\t\tdb.SetMaxIdleConns(1)\n\n\t\t// Create a slice to scan all columns\n\t\tvalues := make([]any, 1000)\n\t\tvaluePtrs := make([]any, 1000)\n\t\tfor j := range values {\n\t\t\tvaluePtrs[j] = &values[j]\n\t\t}\n\n\t\t// Prepare a SELECT query to retrieve metadata\n\t\tstmt := tb.checkStmt(db.Prepare(\"SELECT * FROM large_integer_table LIMIT 1\"))\n\t\tdefer stmt.Close()\n\n\t\t// Benchmark metadata retrieval\n\t\tb.ReportAllocs()\n\t\tb.ResetTimer()\n\t\tfor range b.N {\n\t\t\trows := tb.checkRows(stmt.Query())\n\n\t\t\trows.Next()\n\t\t\t// Scan the row\n\t\t\terr := rows.Scan(valuePtrs...)\n\t\t\ttb.check(err)\n\n\t\t\trows.Close()\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "buffer.go",
    "content": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at http://mozilla.org/MPL/2.0/.\n\npackage mysql\n\nimport (\n\t\"io\"\n)\n\nconst defaultBufSize = 4096\nconst maxCachedBufSize = 256 * 1024\n\n// readerFunc is a function that compatible with io.Reader.\n// We use this function type instead of io.Reader because we want to\n// just pass mc.readWithTimeout.\ntype readerFunc func([]byte) (int, error)\n\n// A buffer which is used for both reading and writing.\n// This is possible since communication on each connection is synchronous.\n// In other words, we can't write and read simultaneously on the same connection.\n// The buffer is similar to bufio.Reader / Writer but zero-copy-ish\n// Also highly optimized for this particular use case.\ntype buffer struct {\n\tbuf       []byte // read buffer.\n\tcachedBuf []byte // buffer that will be reused. len(cachedBuf) <= maxCachedBufSize.\n}\n\n// newBuffer allocates and returns a new buffer.\nfunc newBuffer() buffer {\n\treturn buffer{\n\t\tcachedBuf: make([]byte, defaultBufSize),\n\t}\n}\n\n// busy returns true if the read buffer is not empty.\nfunc (b *buffer) busy() bool {\n\treturn len(b.buf) > 0\n}\n\n// len returns how many bytes in the read buffer.\nfunc (b *buffer) len() int {\n\treturn len(b.buf)\n}\n\n// fill reads into the read buffer until at least _need_ bytes are in it.\nfunc (b *buffer) fill(need int, r readerFunc) error {\n\t// we'll move the contents of the current buffer to dest before filling it.\n\tdest := b.cachedBuf\n\n\t// grow buffer if necessary to fit the whole packet.\n\tif need > len(dest) {\n\t\t// Round up to the next multiple of the default size\n\t\tdest = make([]byte, ((need/defaultBufSize)+1)*defaultBufSize)\n\n\t\t// if the allocated buffer is not too large, move it to backing storage\n\t\t// to prevent extra allocations on applications that perform large reads\n\t\tif len(dest) <= maxCachedBufSize {\n\t\t\tb.cachedBuf = dest\n\t\t}\n\t}\n\n\t// move the existing data to the start of the buffer.\n\tn := len(b.buf)\n\tcopy(dest[:n], b.buf)\n\n\tfor {\n\t\tnn, err := r(dest[n:])\n\t\tn += nn\n\n\t\tif err == nil && n < need {\n\t\t\tcontinue\n\t\t}\n\n\t\tb.buf = dest[:n]\n\n\t\tif err == io.EOF {\n\t\t\tif n < need {\n\t\t\t\terr = io.ErrUnexpectedEOF\n\t\t\t} else {\n\t\t\t\terr = nil\n\t\t\t}\n\t\t}\n\t\treturn err\n\t}\n}\n\n// returns next N bytes from buffer.\n// The returned slice is only guaranteed to be valid until the next read\nfunc (b *buffer) readNext(need int) []byte {\n\tdata := b.buf[:need:need]\n\tb.buf = b.buf[need:]\n\treturn data\n}\n\n// takeBuffer returns a buffer with the requested size.\n// If possible, a slice from the existing buffer is returned.\n// Otherwise a bigger buffer is made.\n// Only one buffer (total) can be used at a time.\nfunc (b *buffer) takeBuffer(length int) ([]byte, error) {\n\tif b.busy() {\n\t\treturn nil, ErrBusyBuffer\n\t}\n\n\t// test (cheap) general case first\n\tif length <= len(b.cachedBuf) {\n\t\treturn b.cachedBuf[:length], nil\n\t}\n\n\tif length < maxCachedBufSize {\n\t\tb.cachedBuf = make([]byte, length)\n\t\treturn b.cachedBuf, nil\n\t}\n\n\t// buffer is larger than we want to store.\n\treturn make([]byte, length), nil\n}\n\n// takeSmallBuffer is shortcut which can be used if length is\n// known to be smaller than defaultBufSize.\n// Only one buffer (total) can be used at a time.\nfunc (b *buffer) takeSmallBuffer(length int) ([]byte, error) {\n\tif b.busy() {\n\t\treturn nil, ErrBusyBuffer\n\t}\n\treturn b.cachedBuf[:length], nil\n}\n\n// takeCompleteBuffer returns the complete existing buffer.\n// This can be used if the necessary buffer size is unknown.\n// cap and len of the returned buffer will be equal.\n// Only one buffer (total) can be used at a time.\nfunc (b *buffer) takeCompleteBuffer() ([]byte, error) {\n\tif b.busy() {\n\t\treturn nil, ErrBusyBuffer\n\t}\n\treturn b.cachedBuf, nil\n}\n\n// store stores buf, an updated buffer, if its suitable to do so.\nfunc (b *buffer) store(buf []byte) {\n\tif cap(buf) <= maxCachedBufSize && cap(buf) > cap(b.cachedBuf) {\n\t\tb.cachedBuf = buf[:cap(buf)]\n\t}\n}\n"
  },
  {
    "path": "collations.go",
    "content": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2014 The Go-MySQL-Driver Authors. All rights reserved.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at http://mozilla.org/MPL/2.0/.\n\npackage mysql\n\nconst defaultCollationID = 45 // utf8mb4_general_ci\nconst binaryCollationID = 63\n\n// A list of available collations mapped to the internal ID.\n// To update this map use the following MySQL query:\n//\n//\tSELECT COLLATION_NAME, ID FROM information_schema.COLLATIONS WHERE ID<256 ORDER BY ID\n//\n// Handshake packet have only 1 byte for collation_id.  So we can't use collations with ID > 255.\n//\n// ucs2, utf16, and utf32 can't be used for connection charset.\n// https://dev.mysql.com/doc/refman/5.7/en/charset-connection.html#charset-connection-impermissible-client-charset\n// They are commented out to reduce this map.\nvar collations = map[string]byte{\n\t\"big5_chinese_ci\":      1,\n\t\"latin2_czech_cs\":      2,\n\t\"dec8_swedish_ci\":      3,\n\t\"cp850_general_ci\":     4,\n\t\"latin1_german1_ci\":    5,\n\t\"hp8_english_ci\":       6,\n\t\"koi8r_general_ci\":     7,\n\t\"latin1_swedish_ci\":    8,\n\t\"latin2_general_ci\":    9,\n\t\"swe7_swedish_ci\":      10,\n\t\"ascii_general_ci\":     11,\n\t\"ujis_japanese_ci\":     12,\n\t\"sjis_japanese_ci\":     13,\n\t\"cp1251_bulgarian_ci\":  14,\n\t\"latin1_danish_ci\":     15,\n\t\"hebrew_general_ci\":    16,\n\t\"tis620_thai_ci\":       18,\n\t\"euckr_korean_ci\":      19,\n\t\"latin7_estonian_cs\":   20,\n\t\"latin2_hungarian_ci\":  21,\n\t\"koi8u_general_ci\":     22,\n\t\"cp1251_ukrainian_ci\":  23,\n\t\"gb2312_chinese_ci\":    24,\n\t\"greek_general_ci\":     25,\n\t\"cp1250_general_ci\":    26,\n\t\"latin2_croatian_ci\":   27,\n\t\"gbk_chinese_ci\":       28,\n\t\"cp1257_lithuanian_ci\": 29,\n\t\"latin5_turkish_ci\":    30,\n\t\"latin1_german2_ci\":    31,\n\t\"armscii8_general_ci\":  32,\n\t\"utf8_general_ci\":      33,\n\t\"cp1250_czech_cs\":      34,\n\t//\"ucs2_general_ci\":          35,\n\t\"cp866_general_ci\":    36,\n\t\"keybcs2_general_ci\":  37,\n\t\"macce_general_ci\":    38,\n\t\"macroman_general_ci\": 39,\n\t\"cp852_general_ci\":    40,\n\t\"latin7_general_ci\":   41,\n\t\"latin7_general_cs\":   42,\n\t\"macce_bin\":           43,\n\t\"cp1250_croatian_ci\":  44,\n\t\"utf8mb4_general_ci\":  45,\n\t\"utf8mb4_bin\":         46,\n\t\"latin1_bin\":          47,\n\t\"latin1_general_ci\":   48,\n\t\"latin1_general_cs\":   49,\n\t\"cp1251_bin\":          50,\n\t\"cp1251_general_ci\":   51,\n\t\"cp1251_general_cs\":   52,\n\t\"macroman_bin\":        53,\n\t//\"utf16_general_ci\":         54,\n\t//\"utf16_bin\":                55,\n\t//\"utf16le_general_ci\":       56,\n\t\"cp1256_general_ci\": 57,\n\t\"cp1257_bin\":        58,\n\t\"cp1257_general_ci\": 59,\n\t//\"utf32_general_ci\":         60,\n\t//\"utf32_bin\":                61,\n\t//\"utf16le_bin\":              62,\n\t\"binary\":          63,\n\t\"armscii8_bin\":    64,\n\t\"ascii_bin\":       65,\n\t\"cp1250_bin\":      66,\n\t\"cp1256_bin\":      67,\n\t\"cp866_bin\":       68,\n\t\"dec8_bin\":        69,\n\t\"greek_bin\":       70,\n\t\"hebrew_bin\":      71,\n\t\"hp8_bin\":         72,\n\t\"keybcs2_bin\":     73,\n\t\"koi8r_bin\":       74,\n\t\"koi8u_bin\":       75,\n\t\"utf8_tolower_ci\": 76,\n\t\"latin2_bin\":      77,\n\t\"latin5_bin\":      78,\n\t\"latin7_bin\":      79,\n\t\"cp850_bin\":       80,\n\t\"cp852_bin\":       81,\n\t\"swe7_bin\":        82,\n\t\"utf8_bin\":        83,\n\t\"big5_bin\":        84,\n\t\"euckr_bin\":       85,\n\t\"gb2312_bin\":      86,\n\t\"gbk_bin\":         87,\n\t\"sjis_bin\":        88,\n\t\"tis620_bin\":      89,\n\t//\"ucs2_bin\":                 90,\n\t\"ujis_bin\":            91,\n\t\"geostd8_general_ci\":  92,\n\t\"geostd8_bin\":         93,\n\t\"latin1_spanish_ci\":   94,\n\t\"cp932_japanese_ci\":   95,\n\t\"cp932_bin\":           96,\n\t\"eucjpms_japanese_ci\": 97,\n\t\"eucjpms_bin\":         98,\n\t\"cp1250_polish_ci\":    99,\n\t//\"utf16_unicode_ci\":         101,\n\t//\"utf16_icelandic_ci\":       102,\n\t//\"utf16_latvian_ci\":         103,\n\t//\"utf16_romanian_ci\":        104,\n\t//\"utf16_slovenian_ci\":       105,\n\t//\"utf16_polish_ci\":          106,\n\t//\"utf16_estonian_ci\":        107,\n\t//\"utf16_spanish_ci\":         108,\n\t//\"utf16_swedish_ci\":         109,\n\t//\"utf16_turkish_ci\":         110,\n\t//\"utf16_czech_ci\":           111,\n\t//\"utf16_danish_ci\":          112,\n\t//\"utf16_lithuanian_ci\":      113,\n\t//\"utf16_slovak_ci\":          114,\n\t//\"utf16_spanish2_ci\":        115,\n\t//\"utf16_roman_ci\":           116,\n\t//\"utf16_persian_ci\":         117,\n\t//\"utf16_esperanto_ci\":       118,\n\t//\"utf16_hungarian_ci\":       119,\n\t//\"utf16_sinhala_ci\":         120,\n\t//\"utf16_german2_ci\":         121,\n\t//\"utf16_croatian_ci\":        122,\n\t//\"utf16_unicode_520_ci\":     123,\n\t//\"utf16_vietnamese_ci\":      124,\n\t//\"ucs2_unicode_ci\":          128,\n\t//\"ucs2_icelandic_ci\":        129,\n\t//\"ucs2_latvian_ci\":          130,\n\t//\"ucs2_romanian_ci\":         131,\n\t//\"ucs2_slovenian_ci\":        132,\n\t//\"ucs2_polish_ci\":           133,\n\t//\"ucs2_estonian_ci\":         134,\n\t//\"ucs2_spanish_ci\":          135,\n\t//\"ucs2_swedish_ci\":          136,\n\t//\"ucs2_turkish_ci\":          137,\n\t//\"ucs2_czech_ci\":            138,\n\t//\"ucs2_danish_ci\":           139,\n\t//\"ucs2_lithuanian_ci\":       140,\n\t//\"ucs2_slovak_ci\":           141,\n\t//\"ucs2_spanish2_ci\":         142,\n\t//\"ucs2_roman_ci\":            143,\n\t//\"ucs2_persian_ci\":          144,\n\t//\"ucs2_esperanto_ci\":        145,\n\t//\"ucs2_hungarian_ci\":        146,\n\t//\"ucs2_sinhala_ci\":          147,\n\t//\"ucs2_german2_ci\":          148,\n\t//\"ucs2_croatian_ci\":         149,\n\t//\"ucs2_unicode_520_ci\":      150,\n\t//\"ucs2_vietnamese_ci\":       151,\n\t//\"ucs2_general_mysql500_ci\": 159,\n\t//\"utf32_unicode_ci\":         160,\n\t//\"utf32_icelandic_ci\":       161,\n\t//\"utf32_latvian_ci\":         162,\n\t//\"utf32_romanian_ci\":        163,\n\t//\"utf32_slovenian_ci\":       164,\n\t//\"utf32_polish_ci\":          165,\n\t//\"utf32_estonian_ci\":        166,\n\t//\"utf32_spanish_ci\":         167,\n\t//\"utf32_swedish_ci\":         168,\n\t//\"utf32_turkish_ci\":         169,\n\t//\"utf32_czech_ci\":           170,\n\t//\"utf32_danish_ci\":          171,\n\t//\"utf32_lithuanian_ci\":      172,\n\t//\"utf32_slovak_ci\":          173,\n\t//\"utf32_spanish2_ci\":        174,\n\t//\"utf32_roman_ci\":           175,\n\t//\"utf32_persian_ci\":         176,\n\t//\"utf32_esperanto_ci\":       177,\n\t//\"utf32_hungarian_ci\":       178,\n\t//\"utf32_sinhala_ci\":         179,\n\t//\"utf32_german2_ci\":         180,\n\t//\"utf32_croatian_ci\":        181,\n\t//\"utf32_unicode_520_ci\":     182,\n\t//\"utf32_vietnamese_ci\":      183,\n\t\"utf8_unicode_ci\":          192,\n\t\"utf8_icelandic_ci\":        193,\n\t\"utf8_latvian_ci\":          194,\n\t\"utf8_romanian_ci\":         195,\n\t\"utf8_slovenian_ci\":        196,\n\t\"utf8_polish_ci\":           197,\n\t\"utf8_estonian_ci\":         198,\n\t\"utf8_spanish_ci\":          199,\n\t\"utf8_swedish_ci\":          200,\n\t\"utf8_turkish_ci\":          201,\n\t\"utf8_czech_ci\":            202,\n\t\"utf8_danish_ci\":           203,\n\t\"utf8_lithuanian_ci\":       204,\n\t\"utf8_slovak_ci\":           205,\n\t\"utf8_spanish2_ci\":         206,\n\t\"utf8_roman_ci\":            207,\n\t\"utf8_persian_ci\":          208,\n\t\"utf8_esperanto_ci\":        209,\n\t\"utf8_hungarian_ci\":        210,\n\t\"utf8_sinhala_ci\":          211,\n\t\"utf8_german2_ci\":          212,\n\t\"utf8_croatian_ci\":         213,\n\t\"utf8_unicode_520_ci\":      214,\n\t\"utf8_vietnamese_ci\":       215,\n\t\"utf8_general_mysql500_ci\": 223,\n\t\"utf8mb4_unicode_ci\":       224,\n\t\"utf8mb4_icelandic_ci\":     225,\n\t\"utf8mb4_latvian_ci\":       226,\n\t\"utf8mb4_romanian_ci\":      227,\n\t\"utf8mb4_slovenian_ci\":     228,\n\t\"utf8mb4_polish_ci\":        229,\n\t\"utf8mb4_estonian_ci\":      230,\n\t\"utf8mb4_spanish_ci\":       231,\n\t\"utf8mb4_swedish_ci\":       232,\n\t\"utf8mb4_turkish_ci\":       233,\n\t\"utf8mb4_czech_ci\":         234,\n\t\"utf8mb4_danish_ci\":        235,\n\t\"utf8mb4_lithuanian_ci\":    236,\n\t\"utf8mb4_slovak_ci\":        237,\n\t\"utf8mb4_spanish2_ci\":      238,\n\t\"utf8mb4_roman_ci\":         239,\n\t\"utf8mb4_persian_ci\":       240,\n\t\"utf8mb4_esperanto_ci\":     241,\n\t\"utf8mb4_hungarian_ci\":     242,\n\t\"utf8mb4_sinhala_ci\":       243,\n\t\"utf8mb4_german2_ci\":       244,\n\t\"utf8mb4_croatian_ci\":      245,\n\t\"utf8mb4_unicode_520_ci\":   246,\n\t\"utf8mb4_vietnamese_ci\":    247,\n\t\"gb18030_chinese_ci\":       248,\n\t\"gb18030_bin\":              249,\n\t\"gb18030_unicode_520_ci\":   250,\n\t\"utf8mb4_0900_ai_ci\":       255,\n}\n\n// A denylist of collations which is unsafe to interpolate parameters.\n// These multibyte encodings may contains 0x5c (`\\`) in their trailing bytes.\nvar unsafeCollations = map[string]bool{\n\t\"big5_chinese_ci\":        true,\n\t\"sjis_japanese_ci\":       true,\n\t\"gbk_chinese_ci\":         true,\n\t\"big5_bin\":               true,\n\t\"gb2312_bin\":             true,\n\t\"gbk_bin\":                true,\n\t\"sjis_bin\":               true,\n\t\"cp932_japanese_ci\":      true,\n\t\"cp932_bin\":              true,\n\t\"gb18030_chinese_ci\":     true,\n\t\"gb18030_bin\":            true,\n\t\"gb18030_unicode_520_ci\": true,\n}\n"
  },
  {
    "path": "compress.go",
    "content": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2024 The Go-MySQL-Driver Authors. All rights reserved.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at http://mozilla.org/MPL/2.0/.\n\npackage mysql\n\nimport (\n\t\"bytes\"\n\t\"compress/zlib\"\n\t\"fmt\"\n\t\"io\"\n\t\"sync\"\n)\n\nvar (\n\tzrPool *sync.Pool // Do not use directly. Use zDecompress() instead.\n\tzwPool *sync.Pool // Do not use directly. Use zCompress() instead.\n)\n\nfunc init() {\n\tzrPool = &sync.Pool{\n\t\tNew: func() any { return nil },\n\t}\n\tzwPool = &sync.Pool{\n\t\tNew: func() any {\n\t\t\tzw, err := zlib.NewWriterLevel(new(bytes.Buffer), 2)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err) // compress/zlib return non-nil error only if level is invalid\n\t\t\t}\n\t\t\treturn zw\n\t\t},\n\t}\n}\n\nfunc zDecompress(src []byte, dst *bytes.Buffer) (int, error) {\n\tbr := bytes.NewReader(src)\n\tvar zr io.ReadCloser\n\tvar err error\n\n\tif a := zrPool.Get(); a == nil {\n\t\tif zr, err = zlib.NewReader(br); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t} else {\n\t\tzr = a.(io.ReadCloser)\n\t\tif err := zr.(zlib.Resetter).Reset(br, nil); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\tn, _ := dst.ReadFrom(zr) // ignore err because zr.Close() will return it again.\n\terr = zr.Close()         // zr.Close() may return chuecksum error.\n\tzrPool.Put(zr)\n\treturn int(n), err\n}\n\nfunc zCompress(src []byte, dst io.Writer) error {\n\tzw := zwPool.Get().(*zlib.Writer)\n\tzw.Reset(dst)\n\tif _, err := zw.Write(src); err != nil {\n\t\treturn err\n\t}\n\terr := zw.Close()\n\tzwPool.Put(zw)\n\treturn err\n}\n\ntype compIO struct {\n\tmc   *mysqlConn\n\tbuff bytes.Buffer\n}\n\nfunc newCompIO(mc *mysqlConn) *compIO {\n\treturn &compIO{\n\t\tmc: mc,\n\t}\n}\n\nfunc (c *compIO) reset() {\n\tc.buff.Reset()\n}\n\nfunc (c *compIO) readNext(need int) ([]byte, error) {\n\tfor c.buff.Len() < need {\n\t\tif err := c.readCompressedPacket(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tdata := c.buff.Next(need)\n\treturn data[:need:need], nil // prevent caller writes into c.buff\n}\n\nfunc (c *compIO) readCompressedPacket() error {\n\theader, err := c.mc.readNext(7)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_ = header[6] // bounds check hint to compiler; guaranteed by readNext\n\n\t// compressed header structure\n\tcomprLength := getUint24(header[0:3])\n\tcompressionSequence := header[3]\n\tuncompressedLength := getUint24(header[4:7])\n\tif debug {\n\t\tfmt.Printf(\"uncompress cmplen=%v uncomplen=%v pkt_cmp_seq=%v expected_cmp_seq=%v\\n\",\n\t\t\tcomprLength, uncompressedLength, compressionSequence, c.mc.sequence)\n\t}\n\t// Do not return ErrPktSync here.\n\t// Server may return error packet (e.g. 1153 Got a packet bigger than 'max_allowed_packet' bytes)\n\t// before receiving all packets from client. In this case, seqnr is younger than expected.\n\t// NOTE: Both of mariadbclient and mysqlclient do not check seqnr. Only server checks it.\n\tif debug && compressionSequence != c.mc.compressSequence {\n\t\tfmt.Printf(\"WARN: unexpected cmpress seq nr: expected %v, got %v\",\n\t\t\tc.mc.compressSequence, compressionSequence)\n\t}\n\tc.mc.compressSequence = compressionSequence + 1\n\n\tcomprData, err := c.mc.readNext(comprLength)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// if payload is uncompressed, its length will be specified as zero, and its\n\t// true length is contained in comprLength\n\tif uncompressedLength == 0 {\n\t\tc.buff.Write(comprData)\n\t\treturn nil\n\t}\n\n\t// use existing capacity in bytesBuf if possible\n\tc.buff.Grow(uncompressedLength)\n\tnread, err := zDecompress(comprData, &c.buff)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif nread != uncompressedLength {\n\t\treturn fmt.Errorf(\"invalid compressed packet: uncompressed length in header is %d, actual %d\",\n\t\t\tuncompressedLength, nread)\n\t}\n\treturn nil\n}\n\nconst minCompressLength = 150\nconst maxPayloadLen = maxPacketSize - 4\n\n// writePackets sends one or some packets with compression.\n// Use this instead of mc.netConn.Write() when mc.compress is true.\nfunc (c *compIO) writePackets(packets []byte) (int, error) {\n\ttotalBytes := len(packets)\n\tblankHeader := make([]byte, 7)\n\tbuf := &c.buff\n\n\tfor len(packets) > 0 {\n\t\tpayloadLen := min(maxPayloadLen, len(packets))\n\t\tpayload := packets[:payloadLen]\n\t\tuncompressedLen := payloadLen\n\n\t\tbuf.Reset()\n\t\tbuf.Write(blankHeader) // Buffer.Write() never returns error\n\n\t\t// If payload is less than minCompressLength, don't compress.\n\t\tif uncompressedLen < minCompressLength {\n\t\t\tbuf.Write(payload)\n\t\t\tuncompressedLen = 0\n\t\t} else {\n\t\t\terr := zCompress(payload, buf)\n\t\t\tif debug && err != nil {\n\t\t\t\tfmt.Printf(\"zCompress error: %v\", err)\n\t\t\t}\n\t\t\t// do not compress if compressed data is larger than uncompressed data\n\t\t\t// I intentionally miss 7 byte header in the buf; zCompress must compress more than 7 bytes.\n\t\t\tif err != nil || buf.Len() >= uncompressedLen {\n\t\t\t\tbuf.Reset()\n\t\t\t\tbuf.Write(blankHeader)\n\t\t\t\tbuf.Write(payload)\n\t\t\t\tuncompressedLen = 0\n\t\t\t}\n\t\t}\n\n\t\tif n, err := c.writeCompressedPacket(buf.Bytes(), uncompressedLen); err != nil {\n\t\t\t// To allow returning ErrBadConn when sending really 0 bytes, we sum\n\t\t\t// up compressed bytes that is returned by underlying Write().\n\t\t\treturn totalBytes - len(packets) + n, err\n\t\t}\n\t\tpackets = packets[payloadLen:]\n\t}\n\n\treturn totalBytes, nil\n}\n\n// writeCompressedPacket writes a compressed packet with header.\n// data should start with 7 size space for header followed by payload.\nfunc (c *compIO) writeCompressedPacket(data []byte, uncompressedLen int) (int, error) {\n\tmc := c.mc\n\tcomprLength := len(data) - 7\n\tif debug {\n\t\tfmt.Printf(\n\t\t\t\"writeCompressedPacket: comprLength=%v, uncompressedLen=%v, seq=%v\\n\",\n\t\t\tcomprLength, uncompressedLen, mc.compressSequence)\n\t}\n\n\t// compression header\n\tputUint24(data[0:3], comprLength)\n\tdata[3] = mc.compressSequence\n\tputUint24(data[4:7], uncompressedLen)\n\n\tmc.compressSequence++\n\treturn mc.writeWithTimeout(data)\n}\n"
  },
  {
    "path": "compress_test.go",
    "content": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2024 The Go-MySQL-Driver Authors. All rights reserved.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at http://mozilla.org/MPL/2.0/.\n\npackage mysql\n\nimport (\n\t\"bytes\"\n\t\"crypto/rand\"\n\t\"io\"\n\t\"testing\"\n)\n\nfunc makeRandByteSlice(size int) []byte {\n\trandBytes := make([]byte, size)\n\trand.Read(randBytes)\n\treturn randBytes\n}\n\n// compressHelper compresses uncompressedPacket and checks state variables\nfunc compressHelper(t *testing.T, mc *mysqlConn, uncompressedPacket []byte) []byte {\n\tconn := new(mockConn)\n\tmc.netConn = conn\n\n\terr := mc.writePacket(append(make([]byte, 4), uncompressedPacket...))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\treturn conn.written\n}\n\n// uncompressHelper uncompresses compressedPacket and checks state variables\nfunc uncompressHelper(t *testing.T, mc *mysqlConn, compressedPacket []byte) []byte {\n\t// mocking out buf variable\n\tconn := new(mockConn)\n\tconn.data = compressedPacket\n\tmc.netConn = conn\n\n\tuncompressedPacket, err := mc.readPacket()\n\tif err != nil {\n\t\tif err != io.EOF {\n\t\t\tt.Fatalf(\"non-nil/non-EOF error when reading contents: %s\", err.Error())\n\t\t}\n\t}\n\treturn uncompressedPacket\n}\n\n// roundtripHelper compresses then uncompresses uncompressedPacket and checks state variables\nfunc roundtripHelper(t *testing.T, cSend *mysqlConn, cReceive *mysqlConn, uncompressedPacket []byte) []byte {\n\tcompressed := compressHelper(t, cSend, uncompressedPacket)\n\treturn uncompressHelper(t, cReceive, compressed)\n}\n\n// TestRoundtrip tests two connections, where one is reading and the other is writing\nfunc TestRoundtrip(t *testing.T) {\n\ttests := []struct {\n\t\tuncompressed []byte\n\t\tdesc         string\n\t}{\n\t\t{uncompressed: []byte(\"a\"),\n\t\t\tdesc: \"a\"},\n\t\t{uncompressed: []byte(\"hello world\"),\n\t\t\tdesc: \"hello world\"},\n\t\t{uncompressed: make([]byte, 100),\n\t\t\tdesc: \"100 bytes\"},\n\t\t{uncompressed: make([]byte, 32768),\n\t\t\tdesc: \"32768 bytes\"},\n\t\t{uncompressed: make([]byte, 330000),\n\t\t\tdesc: \"33000 bytes\"},\n\t\t{uncompressed: makeRandByteSlice(10),\n\t\t\tdesc: \"10 rand bytes\",\n\t\t},\n\t\t{uncompressed: makeRandByteSlice(100),\n\t\t\tdesc: \"100 rand bytes\",\n\t\t},\n\t\t{uncompressed: makeRandByteSlice(32768),\n\t\t\tdesc: \"32768 rand bytes\",\n\t\t},\n\t\t{uncompressed: bytes.Repeat(makeRandByteSlice(100), 10000),\n\t\t\tdesc: \"100 rand * 10000 repeat bytes\",\n\t\t},\n\t}\n\n\t_, cSend := newRWMockConn(0)\n\tcSend.compress = true\n\tcSend.compIO = newCompIO(cSend)\n\t_, cReceive := newRWMockConn(0)\n\tcReceive.compress = true\n\tcReceive.compIO = newCompIO(cReceive)\n\n\tfor _, test := range tests {\n\t\tt.Run(test.desc, func(t *testing.T) {\n\t\t\tcSend.resetSequence()\n\t\t\tcReceive.resetSequence()\n\n\t\t\tuncompressed := roundtripHelper(t, cSend, cReceive, test.uncompressed)\n\t\t\tif len(uncompressed) != len(test.uncompressed) {\n\t\t\t\tt.Errorf(\"uncompressed size is unexpected. expected %d but got %d\",\n\t\t\t\t\tlen(test.uncompressed), len(uncompressed))\n\t\t\t}\n\t\t\tif !bytes.Equal(uncompressed, test.uncompressed) {\n\t\t\t\tt.Errorf(\"roundtrip failed\")\n\t\t\t}\n\t\t\tif cSend.sequence != cReceive.sequence {\n\t\t\t\tt.Errorf(\"inconsistent sequence number: send=%v recv=%v\",\n\t\t\t\t\tcSend.sequence, cReceive.sequence)\n\t\t\t}\n\t\t\tif cSend.compressSequence != cReceive.compressSequence {\n\t\t\t\tt.Errorf(\"inconsistent compress sequence number: send=%v recv=%v\",\n\t\t\t\t\tcSend.compressSequence, cReceive.compressSequence)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "conncheck.go",
    "content": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2019 The Go-MySQL-Driver Authors. All rights reserved.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at http://mozilla.org/MPL/2.0/.\n\n//go:build linux || darwin || dragonfly || freebsd || netbsd || openbsd || solaris || illumos\n// +build linux darwin dragonfly freebsd netbsd openbsd solaris illumos\n\npackage mysql\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"net\"\n\t\"syscall\"\n)\n\nvar errUnexpectedRead = errors.New(\"unexpected read from socket\")\n\nfunc connCheck(conn net.Conn) error {\n\tvar sysErr error\n\n\tsysConn, ok := conn.(syscall.Conn)\n\tif !ok {\n\t\treturn nil\n\t}\n\trawConn, err := sysConn.SyscallConn()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = rawConn.Read(func(fd uintptr) bool {\n\t\tvar buf [1]byte\n\t\tn, err := syscall.Read(int(fd), buf[:])\n\t\tswitch {\n\t\tcase n == 0 && err == nil:\n\t\t\tsysErr = io.EOF\n\t\tcase n > 0:\n\t\t\tsysErr = errUnexpectedRead\n\t\tcase err == syscall.EAGAIN || err == syscall.EWOULDBLOCK:\n\t\t\tsysErr = nil\n\t\tdefault:\n\t\t\tsysErr = err\n\t\t}\n\t\treturn true\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn sysErr\n}\n"
  },
  {
    "path": "conncheck_dummy.go",
    "content": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2019 The Go-MySQL-Driver Authors. All rights reserved.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at http://mozilla.org/MPL/2.0/.\n\n//go:build !linux && !darwin && !dragonfly && !freebsd && !netbsd && !openbsd && !solaris && !illumos\n// +build !linux,!darwin,!dragonfly,!freebsd,!netbsd,!openbsd,!solaris,!illumos\n\npackage mysql\n\nimport \"net\"\n\nfunc connCheck(conn net.Conn) error {\n\treturn nil\n}\n"
  },
  {
    "path": "conncheck_test.go",
    "content": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at http://mozilla.org/MPL/2.0/.\n\n//go:build linux || darwin || dragonfly || freebsd || netbsd || openbsd || solaris || illumos\n// +build linux darwin dragonfly freebsd netbsd openbsd solaris illumos\n\npackage mysql\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestStaleConnectionChecks(t *testing.T) {\n\trunTestsParallel(t, dsn, func(dbt *DBTest, _ string) {\n\t\tdbt.mustExec(\"SET @@SESSION.wait_timeout = 2\")\n\n\t\tif err := dbt.db.Ping(); err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\n\t\t// wait for MySQL to close our connection\n\t\ttime.Sleep(3 * time.Second)\n\n\t\ttx, err := dbt.db.Begin()\n\t\tif err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\n\t\tif err := tx.Rollback(); err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "connection.go",
    "content": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at http://mozilla.org/MPL/2.0/.\n\npackage mysql\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"database/sql/driver\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync/atomic\"\n\t\"time\"\n)\n\ntype mysqlConn struct {\n\tbuf              buffer\n\tnetConn          net.Conn\n\trawConn          net.Conn    // underlying connection when netConn is TLS connection.\n\tresult           mysqlResult // managed by clearResult() and handleOkPacket().\n\tcompIO           *compIO\n\tcfg              *Config\n\tconnector        *connector\n\tmaxAllowedPacket int\n\tmaxWriteSize     int\n\tcapabilities     capabilityFlag\n\textCapabilities  extendedCapabilityFlag\n\tstatus           statusFlag\n\tsequence         uint8\n\tcompressSequence uint8\n\tparseTime        bool\n\tcompress         bool\n\n\t// for context support (Go 1.8+)\n\twatching bool\n\twatcher  chan<- context.Context\n\tclosech  chan struct{}\n\tfinished chan<- struct{}\n\tcanceled atomicError // set non-nil if conn is canceled\n\tclosed   atomic.Bool // set when conn is closed, before closech is closed\n}\n\n// Helper function to call per-connection logger.\nfunc (mc *mysqlConn) log(v ...any) {\n\t_, filename, lineno, ok := runtime.Caller(1)\n\tif ok {\n\t\tpos := strings.LastIndexByte(filename, '/')\n\t\tif pos != -1 {\n\t\t\tfilename = filename[pos+1:]\n\t\t}\n\t\tprefix := fmt.Sprintf(\"%s:%d \", filename, lineno)\n\t\tv = append([]any{prefix}, v...)\n\t}\n\n\tmc.cfg.Logger.Print(v...)\n}\n\nfunc (mc *mysqlConn) readWithTimeout(b []byte) (int, error) {\n\tto := mc.cfg.ReadTimeout\n\tif to > 0 {\n\t\tif err := mc.netConn.SetReadDeadline(time.Now().Add(to)); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\treturn mc.netConn.Read(b)\n}\n\nfunc (mc *mysqlConn) writeWithTimeout(b []byte) (int, error) {\n\tto := mc.cfg.WriteTimeout\n\tif to > 0 {\n\t\tif err := mc.netConn.SetWriteDeadline(time.Now().Add(to)); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\treturn mc.netConn.Write(b)\n}\n\nfunc (mc *mysqlConn) resetSequence() {\n\tmc.sequence = 0\n\tmc.compressSequence = 0\n}\n\n// syncSequence must be called when finished writing some packet and before start reading.\nfunc (mc *mysqlConn) syncSequence() {\n\t// Syncs compressionSequence to sequence.\n\t// This is not documented but done in `net_flush()` in MySQL and MariaDB.\n\t// https://github.com/mariadb-corporation/mariadb-connector-c/blob/8228164f850b12353da24df1b93a1e53cc5e85e9/libmariadb/ma_net.c#L170-L171\n\t// https://github.com/mysql/mysql-server/blob/824e2b4064053f7daf17d7f3f84b7a3ed92e5fb4/sql-common/net_serv.cc#L293\n\tif mc.compress {\n\t\tmc.sequence = mc.compressSequence\n\t\tmc.compIO.reset()\n\t}\n}\n\n// Handles parameters set in DSN after the connection is established\nfunc (mc *mysqlConn) handleParams() (err error) {\n\tvar cmdSet strings.Builder\n\n\tfor param, val := range mc.cfg.Params {\n\t\tif cmdSet.Len() == 0 {\n\t\t\t// Heuristic: 29 chars for each other key=value to reduce reallocations\n\t\t\tcmdSet.Grow(4 + len(param) + 3 + len(val) + 30*(len(mc.cfg.Params)-1))\n\t\t\tcmdSet.WriteString(\"SET \")\n\t\t} else {\n\t\t\tcmdSet.WriteString(\", \")\n\t\t}\n\t\tcmdSet.WriteString(param)\n\t\tcmdSet.WriteString(\" = \")\n\t\tcmdSet.WriteString(val)\n\t}\n\n\tif cmdSet.Len() > 0 {\n\t\terr = mc.exec(cmdSet.String())\n\t}\n\n\treturn\n}\n\n// markBadConn replaces errBadConnNoWrite with driver.ErrBadConn.\n// This function is used to return driver.ErrBadConn only when safe to retry.\nfunc (mc *mysqlConn) markBadConn(err error) error {\n\tif err == errBadConnNoWrite {\n\t\treturn driver.ErrBadConn\n\t}\n\treturn err\n}\n\nfunc (mc *mysqlConn) Begin() (driver.Tx, error) {\n\treturn mc.begin(false)\n}\n\nfunc (mc *mysqlConn) begin(readOnly bool) (driver.Tx, error) {\n\tif mc.closed.Load() {\n\t\treturn nil, driver.ErrBadConn\n\t}\n\tvar q string\n\tif readOnly {\n\t\tq = \"START TRANSACTION READ ONLY\"\n\t} else {\n\t\tq = \"START TRANSACTION\"\n\t}\n\terr := mc.exec(q)\n\tif err == nil {\n\t\treturn &mysqlTx{mc}, err\n\t}\n\treturn nil, mc.markBadConn(err)\n}\n\nfunc (mc *mysqlConn) Close() (err error) {\n\t// Makes Close idempotent\n\tif !mc.closed.Load() {\n\t\terr = mc.writeCommandPacket(comQuit)\n\t}\n\tmc.close()\n\treturn\n}\n\n// close closes the network connection and clear results without sending COM_QUIT.\nfunc (mc *mysqlConn) close() {\n\tmc.cleanup()\n\tmc.clearResult()\n}\n\n// Closes the network connection and unsets internal variables. Do not call this\n// function after successfully authentication, call Close instead. This function\n// is called before auth or on auth failure because MySQL will have already\n// closed the network connection.\nfunc (mc *mysqlConn) cleanup() {\n\tif mc.closed.Swap(true) {\n\t\treturn\n\t}\n\n\t// Makes cleanup idempotent\n\tclose(mc.closech)\n\tconn := mc.rawConn\n\tif conn == nil {\n\t\treturn\n\t}\n\tif err := conn.Close(); err != nil {\n\t\tmc.log(\"closing connection:\", err)\n\t}\n\t// This function can be called from multiple goroutines.\n\t// So we can not mc.clearResult() here.\n\t// Caller should do it if they are in safe goroutine.\n}\n\nfunc (mc *mysqlConn) error() error {\n\tif mc.closed.Load() {\n\t\tif err := mc.canceled.Value(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn ErrInvalidConn\n\t}\n\treturn nil\n}\n\nfunc (mc *mysqlConn) Prepare(query string) (driver.Stmt, error) {\n\tif mc.closed.Load() {\n\t\treturn nil, driver.ErrBadConn\n\t}\n\t// Send command\n\terr := mc.writeCommandPacketStr(comStmtPrepare, query)\n\tif err != nil {\n\t\t// STMT_PREPARE is safe to retry.  So we can return ErrBadConn here.\n\t\tmc.log(err)\n\t\treturn nil, driver.ErrBadConn\n\t}\n\n\tstmt := &mysqlStmt{\n\t\tmc: mc,\n\t}\n\n\t// Read Result\n\tcolumnCount, err := stmt.readPrepareResultPacket()\n\tif err == nil {\n\t\tif stmt.paramCount > 0 {\n\t\t\tif err = mc.skipColumns(stmt.paramCount); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\tif columnCount > 0 {\n\t\t\tif mc.extCapabilities&clientCacheMetadata != 0 {\n\t\t\t\tif stmt.columns, err = mc.readColumns(int(columnCount), nil); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif err = mc.skipColumns(int(columnCount)); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn stmt, err\n}\n\nfunc (mc *mysqlConn) interpolateParams(query string, args []driver.Value) (string, error) {\n\t// Number of ? should be same to len(args)\n\tif strings.Count(query, \"?\") != len(args) {\n\t\treturn \"\", driver.ErrSkip\n\t}\n\n\tbuf, err := mc.buf.takeCompleteBuffer()\n\tif err != nil {\n\t\t// can not take the buffer. Something must be wrong with the connection\n\t\tmc.cleanup()\n\t\t// interpolateParams would be called before sending any query.\n\t\t// So its safe to retry.\n\t\treturn \"\", driver.ErrBadConn\n\t}\n\tbuf = buf[:0]\n\targPos := 0\n\n\tfor i := 0; i < len(query); i++ {\n\t\tq := strings.IndexByte(query[i:], '?')\n\t\tif q == -1 {\n\t\t\tbuf = append(buf, query[i:]...)\n\t\t\tbreak\n\t\t}\n\t\tbuf = append(buf, query[i:i+q]...)\n\t\ti += q\n\n\t\targ := args[argPos]\n\t\targPos++\n\n\t\tif arg == nil {\n\t\t\tbuf = append(buf, \"NULL\"...)\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch v := arg.(type) {\n\t\tcase int64:\n\t\t\tbuf = strconv.AppendInt(buf, v, 10)\n\t\tcase uint64:\n\t\t\t// Handle uint64 explicitly because our custom ConvertValue emits unsigned values\n\t\t\tbuf = strconv.AppendUint(buf, v, 10)\n\t\tcase float64:\n\t\t\tbuf = strconv.AppendFloat(buf, v, 'g', -1, 64)\n\t\tcase bool:\n\t\t\tif v {\n\t\t\t\tbuf = append(buf, '1')\n\t\t\t} else {\n\t\t\t\tbuf = append(buf, '0')\n\t\t\t}\n\t\tcase time.Time:\n\t\t\tif v.IsZero() {\n\t\t\t\tbuf = append(buf, \"'0000-00-00'\"...)\n\t\t\t} else {\n\t\t\t\tbuf = append(buf, '\\'')\n\t\t\t\tbuf, err = appendDateTime(buf, v.In(mc.cfg.Loc), mc.cfg.timeTruncate)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn \"\", err\n\t\t\t\t}\n\t\t\t\tbuf = append(buf, '\\'')\n\t\t\t}\n\t\tcase json.RawMessage:\n\t\t\tbuf = append(buf, '\\'')\n\t\t\tif mc.status&statusNoBackslashEscapes == 0 {\n\t\t\t\tbuf = escapeBytesBackslash(buf, v)\n\t\t\t} else {\n\t\t\t\tbuf = escapeBytesQuotes(buf, v)\n\t\t\t}\n\t\t\tbuf = append(buf, '\\'')\n\t\tcase []byte:\n\t\t\tif v == nil {\n\t\t\t\tbuf = append(buf, \"NULL\"...)\n\t\t\t} else {\n\t\t\t\tbuf = append(buf, \"_binary'\"...)\n\t\t\t\tif mc.status&statusNoBackslashEscapes == 0 {\n\t\t\t\t\tbuf = escapeBytesBackslash(buf, v)\n\t\t\t\t} else {\n\t\t\t\t\tbuf = escapeBytesQuotes(buf, v)\n\t\t\t\t}\n\t\t\t\tbuf = append(buf, '\\'')\n\t\t\t}\n\t\tcase string:\n\t\t\tbuf = append(buf, '\\'')\n\t\t\tif mc.status&statusNoBackslashEscapes == 0 {\n\t\t\t\tbuf = escapeStringBackslash(buf, v)\n\t\t\t} else {\n\t\t\t\tbuf = escapeStringQuotes(buf, v)\n\t\t\t}\n\t\t\tbuf = append(buf, '\\'')\n\t\tdefault:\n\t\t\treturn \"\", driver.ErrSkip\n\t\t}\n\n\t\tif len(buf)+4 > mc.maxAllowedPacket {\n\t\t\treturn \"\", driver.ErrSkip\n\t\t}\n\t}\n\tif argPos != len(args) {\n\t\treturn \"\", driver.ErrSkip\n\t}\n\treturn string(buf), nil\n}\n\nfunc (mc *mysqlConn) Exec(query string, args []driver.Value) (driver.Result, error) {\n\tif mc.closed.Load() {\n\t\treturn nil, driver.ErrBadConn\n\t}\n\tif len(args) != 0 {\n\t\tif !mc.cfg.InterpolateParams {\n\t\t\treturn nil, driver.ErrSkip\n\t\t}\n\t\t// try to interpolate the parameters to save extra roundtrips for preparing and closing a statement\n\t\tprepared, err := mc.interpolateParams(query, args)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tquery = prepared\n\t}\n\n\terr := mc.exec(query)\n\tif err == nil {\n\t\tcopied := mc.result\n\t\treturn &copied, err\n\t}\n\treturn nil, mc.markBadConn(err)\n}\n\n// Internal function to execute commands\nfunc (mc *mysqlConn) exec(query string) error {\n\thandleOk := mc.clearResult()\n\t// Send command\n\tif err := mc.writeCommandPacketStr(comQuery, query); err != nil {\n\t\treturn mc.markBadConn(err)\n\t}\n\n\t// Read Result\n\tresLen, _, err := handleOk.readResultSetHeaderPacket()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif resLen > 0 {\n\t\t// columns\n\t\tif err := mc.skipColumns(resLen); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// rows\n\t\tif err := mc.skipRows(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn handleOk.discardResults()\n}\n\nfunc (mc *mysqlConn) Query(query string, args []driver.Value) (driver.Rows, error) {\n\treturn mc.query(query, args)\n}\n\nfunc (mc *mysqlConn) query(query string, args []driver.Value) (*textRows, error) {\n\thandleOk := mc.clearResult()\n\n\tif mc.closed.Load() {\n\t\treturn nil, driver.ErrBadConn\n\t}\n\tif len(args) != 0 {\n\t\tif !mc.cfg.InterpolateParams {\n\t\t\treturn nil, driver.ErrSkip\n\t\t}\n\t\t// try client-side prepare to reduce roundtrip\n\t\tprepared, err := mc.interpolateParams(query, args)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tquery = prepared\n\t}\n\t// Send command\n\terr := mc.writeCommandPacketStr(comQuery, query)\n\tif err != nil {\n\t\treturn nil, mc.markBadConn(err)\n\t}\n\n\t// Read Result\n\tvar resLen int\n\tresLen, _, err = handleOk.readResultSetHeaderPacket()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trows := new(textRows)\n\trows.mc = mc\n\n\tif resLen == 0 {\n\t\trows.rs.done = true\n\n\t\tswitch err := rows.NextResultSet(); err {\n\t\tcase nil, io.EOF:\n\t\t\treturn rows, nil\n\t\tdefault:\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Columns\n\trows.rs.columns, err = mc.readColumns(resLen, nil)\n\treturn rows, err\n}\n\n// Gets the value of the given MySQL System Variable\n// The returned byte slice is only valid until the next read\nfunc (mc *mysqlConn) getSystemVar(name string) ([]byte, error) {\n\t// Send command\n\thandleOk := mc.clearResult()\n\tif err := mc.writeCommandPacketStr(comQuery, \"SELECT @@\"+name); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Read Result\n\tresLen, _, err := handleOk.readResultSetHeaderPacket()\n\tif err == nil {\n\t\trows := new(textRows)\n\t\trows.mc = mc\n\t\trows.rs.columns = []mysqlField{{fieldType: fieldTypeVarChar}}\n\n\t\tif resLen > 0 {\n\t\t\t// Columns\n\t\t\tif err := mc.skipColumns(resLen); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\tdest := make([]driver.Value, resLen)\n\t\tif err = rows.readRow(dest); err == nil {\n\t\t\treturn dest[0].([]byte), mc.skipRows()\n\t\t}\n\t}\n\treturn nil, err\n}\n\n// cancel is called when the query has canceled.\nfunc (mc *mysqlConn) cancel(err error) {\n\tmc.canceled.Set(err)\n\tmc.cleanup()\n}\n\n// finish is called when the query has succeeded.\nfunc (mc *mysqlConn) finish() {\n\tif !mc.watching || mc.finished == nil {\n\t\treturn\n\t}\n\tselect {\n\tcase mc.finished <- struct{}{}:\n\t\tmc.watching = false\n\tcase <-mc.closech:\n\t}\n}\n\n// Ping implements driver.Pinger interface\nfunc (mc *mysqlConn) Ping(ctx context.Context) (err error) {\n\tif mc.closed.Load() {\n\t\treturn driver.ErrBadConn\n\t}\n\n\tif err = mc.watchCancel(ctx); err != nil {\n\t\treturn\n\t}\n\tdefer mc.finish()\n\n\thandleOk := mc.clearResult()\n\tif err = mc.writeCommandPacket(comPing); err != nil {\n\t\treturn mc.markBadConn(err)\n\t}\n\n\treturn handleOk.readResultOK()\n}\n\n// BeginTx implements driver.ConnBeginTx interface\nfunc (mc *mysqlConn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) {\n\tif mc.closed.Load() {\n\t\treturn nil, driver.ErrBadConn\n\t}\n\n\tif err := mc.watchCancel(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\tdefer mc.finish()\n\n\tif sql.IsolationLevel(opts.Isolation) != sql.LevelDefault {\n\t\tlevel, err := mapIsolationLevel(opts.Isolation)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = mc.exec(\"SET TRANSACTION ISOLATION LEVEL \" + level)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn mc.begin(opts.ReadOnly)\n}\n\nfunc (mc *mysqlConn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) {\n\tdargs, err := namedValueToValue(args)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := mc.watchCancel(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\n\trows, err := mc.query(query, dargs)\n\tif err != nil {\n\t\tmc.finish()\n\t\treturn nil, err\n\t}\n\trows.finish = mc.finish\n\treturn rows, err\n}\n\nfunc (mc *mysqlConn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) {\n\tdargs, err := namedValueToValue(args)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := mc.watchCancel(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\tdefer mc.finish()\n\n\treturn mc.Exec(query, dargs)\n}\n\nfunc (mc *mysqlConn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) {\n\tif err := mc.watchCancel(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\n\tstmt, err := mc.Prepare(query)\n\tmc.finish()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tselect {\n\tdefault:\n\tcase <-ctx.Done():\n\t\tstmt.Close()\n\t\treturn nil, ctx.Err()\n\t}\n\treturn stmt, nil\n}\n\nfunc (stmt *mysqlStmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) {\n\tdargs, err := namedValueToValue(args)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := stmt.mc.watchCancel(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\n\trows, err := stmt.query(dargs)\n\tif err != nil {\n\t\tstmt.mc.finish()\n\t\treturn nil, err\n\t}\n\trows.finish = stmt.mc.finish\n\treturn rows, err\n}\n\nfunc (stmt *mysqlStmt) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error) {\n\tdargs, err := namedValueToValue(args)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := stmt.mc.watchCancel(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\tdefer stmt.mc.finish()\n\n\treturn stmt.Exec(dargs)\n}\n\nfunc (mc *mysqlConn) watchCancel(ctx context.Context) error {\n\tif mc.watching {\n\t\t// Reach here if canceled,\n\t\t// so the connection is already invalid\n\t\tmc.cleanup()\n\t\treturn nil\n\t}\n\t// When ctx is already cancelled, don't watch it.\n\tif err := ctx.Err(); err != nil {\n\t\treturn err\n\t}\n\t// When ctx is not cancellable, don't watch it.\n\tif ctx.Done() == nil {\n\t\treturn nil\n\t}\n\t// When watcher is not alive, can't watch it.\n\tif mc.watcher == nil {\n\t\treturn nil\n\t}\n\n\tmc.watching = true\n\tmc.watcher <- ctx\n\treturn nil\n}\n\nfunc (mc *mysqlConn) startWatcher() {\n\twatcher := make(chan context.Context, 1)\n\tmc.watcher = watcher\n\tfinished := make(chan struct{})\n\tmc.finished = finished\n\tgo func() {\n\t\tfor {\n\t\t\tvar ctx context.Context\n\t\t\tselect {\n\t\t\tcase ctx = <-watcher:\n\t\t\tcase <-mc.closech:\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\tmc.cancel(ctx.Err())\n\t\t\tcase <-finished:\n\t\t\tcase <-mc.closech:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}\n\nfunc (mc *mysqlConn) CheckNamedValue(nv *driver.NamedValue) (err error) {\n\tnv.Value, err = converter{}.ConvertValue(nv.Value)\n\treturn\n}\n\n// ResetSession implements driver.SessionResetter.\n// (From Go 1.10)\nfunc (mc *mysqlConn) ResetSession(ctx context.Context) error {\n\tif mc.closed.Load() || mc.buf.busy() {\n\t\treturn driver.ErrBadConn\n\t}\n\n\t// Perform a stale connection check. We only perform this check for\n\t// the first query on a connection that has been checked out of the\n\t// connection pool: a fresh connection from the pool is more likely\n\t// to be stale, and it has not performed any previous writes that\n\t// could cause data corruption, so it's safe to return ErrBadConn\n\t// if the check fails.\n\tif mc.cfg.CheckConnLiveness {\n\t\tconn := mc.netConn\n\t\tif mc.rawConn != nil {\n\t\t\tconn = mc.rawConn\n\t\t}\n\t\tvar err error\n\t\tif mc.cfg.ReadTimeout != 0 {\n\t\t\terr = conn.SetReadDeadline(time.Now().Add(mc.cfg.ReadTimeout))\n\t\t}\n\t\tif err == nil {\n\t\t\terr = connCheck(conn)\n\t\t}\n\t\tif err != nil {\n\t\t\tmc.log(\"closing bad idle connection: \", err)\n\t\t\treturn driver.ErrBadConn\n\t\t}\n\t}\n\n\treturn nil\n}\n\n// IsValid implements driver.Validator interface\n// (From Go 1.15)\nfunc (mc *mysqlConn) IsValid() bool {\n\treturn !mc.closed.Load() && !mc.buf.busy()\n}\n\nvar _ driver.SessionResetter = &mysqlConn{}\nvar _ driver.Validator = &mysqlConn{}\n"
  },
  {
    "path": "connection_test.go",
    "content": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2016 The Go-MySQL-Driver Authors. All rights reserved.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at http://mozilla.org/MPL/2.0/.\n\npackage mysql\n\nimport (\n\t\"context\"\n\t\"database/sql/driver\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"net\"\n\t\"testing\"\n)\n\nfunc TestInterpolateParams(t *testing.T) {\n\tmc := &mysqlConn{\n\t\tbuf:              newBuffer(),\n\t\tmaxAllowedPacket: maxPacketSize,\n\t\tcfg: &Config{\n\t\t\tInterpolateParams: true,\n\t\t},\n\t}\n\n\tq, err := mc.interpolateParams(\"SELECT ?+?\", []driver.Value{int64(42), \"gopher\"})\n\tif err != nil {\n\t\tt.Errorf(\"Expected err=nil, got %#v\", err)\n\t\treturn\n\t}\n\texpected := `SELECT 42+'gopher'`\n\tif q != expected {\n\t\tt.Errorf(\"Expected: %q\\nGot: %q\", expected, q)\n\t}\n}\n\nfunc TestInterpolateParamsJSONRawMessage(t *testing.T) {\n\tmc := &mysqlConn{\n\t\tbuf:              newBuffer(),\n\t\tmaxAllowedPacket: maxPacketSize,\n\t\tcfg: &Config{\n\t\t\tInterpolateParams: true,\n\t\t},\n\t}\n\n\tbuf, err := json.Marshal(struct {\n\t\tValue int `json:\"value\"`\n\t}{Value: 42})\n\tif err != nil {\n\t\tt.Errorf(\"Expected err=nil, got %#v\", err)\n\t\treturn\n\t}\n\tq, err := mc.interpolateParams(\"SELECT ?\", []driver.Value{json.RawMessage(buf)})\n\tif err != nil {\n\t\tt.Errorf(\"Expected err=nil, got %#v\", err)\n\t\treturn\n\t}\n\texpected := `SELECT '{\\\"value\\\":42}'`\n\tif q != expected {\n\t\tt.Errorf(\"Expected: %q\\nGot: %q\", expected, q)\n\t}\n}\n\nfunc TestInterpolateParamsTooManyPlaceholders(t *testing.T) {\n\tmc := &mysqlConn{\n\t\tbuf:              newBuffer(),\n\t\tmaxAllowedPacket: maxPacketSize,\n\t\tcfg: &Config{\n\t\t\tInterpolateParams: true,\n\t\t},\n\t}\n\n\tq, err := mc.interpolateParams(\"SELECT ?+?\", []driver.Value{int64(42)})\n\tif err != driver.ErrSkip {\n\t\tt.Errorf(\"Expected err=driver.ErrSkip, got err=%#v, q=%#v\", err, q)\n\t}\n}\n\n// We don't support placeholder in string literal for now.\n// https://github.com/go-sql-driver/mysql/pull/490\nfunc TestInterpolateParamsPlaceholderInString(t *testing.T) {\n\tmc := &mysqlConn{\n\t\tbuf:              newBuffer(),\n\t\tmaxAllowedPacket: maxPacketSize,\n\t\tcfg: &Config{\n\t\t\tInterpolateParams: true,\n\t\t},\n\t}\n\n\tq, err := mc.interpolateParams(\"SELECT 'abc?xyz',?\", []driver.Value{int64(42)})\n\t// When InterpolateParams support string literal, this should return `\"SELECT 'abc?xyz', 42`\n\tif err != driver.ErrSkip {\n\t\tt.Errorf(\"Expected err=driver.ErrSkip, got err=%#v, q=%#v\", err, q)\n\t}\n}\n\nfunc TestInterpolateParamsUint64(t *testing.T) {\n\tmc := &mysqlConn{\n\t\tbuf:              newBuffer(),\n\t\tmaxAllowedPacket: maxPacketSize,\n\t\tcfg: &Config{\n\t\t\tInterpolateParams: true,\n\t\t},\n\t}\n\n\tq, err := mc.interpolateParams(\"SELECT ?\", []driver.Value{uint64(42)})\n\tif err != nil {\n\t\tt.Errorf(\"Expected err=nil, got err=%#v, q=%#v\", err, q)\n\t}\n\tif q != \"SELECT 42\" {\n\t\tt.Errorf(\"Expected uint64 interpolation to work, got q=%#v\", q)\n\t}\n}\n\nfunc TestCheckNamedValue(t *testing.T) {\n\tvalue := driver.NamedValue{Value: ^uint64(0)}\n\tmc := &mysqlConn{}\n\terr := mc.CheckNamedValue(&value)\n\n\tif err != nil {\n\t\tt.Fatal(\"uint64 high-bit not convertible\", err)\n\t}\n\n\tif value.Value != ^uint64(0) {\n\t\tt.Fatalf(\"uint64 high-bit converted, got %#v %T\", value.Value, value.Value)\n\t}\n}\n\n// TestCleanCancel tests passed context is cancelled at start.\n// No packet should be sent.  Connection should keep current status.\nfunc TestCleanCancel(t *testing.T) {\n\tmc := &mysqlConn{\n\t\tclosech: make(chan struct{}),\n\t}\n\tmc.startWatcher()\n\tdefer mc.cleanup()\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tcancel()\n\n\tfor range 3 { // Repeat same behavior\n\t\terr := mc.Ping(ctx)\n\t\tif err != context.Canceled {\n\t\t\tt.Errorf(\"expected context.Canceled, got %#v\", err)\n\t\t}\n\n\t\tif mc.closed.Load() {\n\t\t\tt.Error(\"expected mc is not closed, closed actually\")\n\t\t}\n\n\t\tif mc.watching {\n\t\t\tt.Error(\"expected watching is false, but true\")\n\t\t}\n\t}\n}\n\nfunc TestPingMarkBadConnection(t *testing.T) {\n\tnc := badConnection{err: errors.New(\"boom\")}\n\tmc := &mysqlConn{\n\t\tnetConn:          nc,\n\t\tbuf:              newBuffer(),\n\t\tmaxAllowedPacket: defaultMaxAllowedPacket,\n\t\tclosech:          make(chan struct{}),\n\t\tcfg:              NewConfig(),\n\t}\n\n\terr := mc.Ping(context.Background())\n\n\tif err != driver.ErrBadConn {\n\t\tt.Errorf(\"expected driver.ErrBadConn, got  %#v\", err)\n\t}\n}\n\nfunc TestPingErrInvalidConn(t *testing.T) {\n\tnc := badConnection{err: errors.New(\"failed to write\"), n: 10}\n\tmc := &mysqlConn{\n\t\tnetConn:          nc,\n\t\tbuf:              newBuffer(),\n\t\tmaxAllowedPacket: defaultMaxAllowedPacket,\n\t\tclosech:          make(chan struct{}),\n\t\tcfg:              NewConfig(),\n\t}\n\n\terr := mc.Ping(context.Background())\n\n\tif err != nc.err {\n\t\tt.Errorf(\"expected %#v, got  %#v\", nc.err, err)\n\t}\n}\n\ntype badConnection struct {\n\tn   int\n\terr error\n\tnet.Conn\n}\n\nfunc (bc badConnection) Write(b []byte) (n int, err error) {\n\treturn bc.n, bc.err\n}\n\nfunc (bc badConnection) Close() error {\n\treturn nil\n}\n"
  },
  {
    "path": "connector.go",
    "content": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2018 The Go-MySQL-Driver Authors. All rights reserved.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at http://mozilla.org/MPL/2.0/.\n\npackage mysql\n\nimport (\n\t\"context\"\n\t\"database/sql/driver\"\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n)\n\ntype connector struct {\n\tcfg               *Config // immutable private copy.\n\tencodedAttributes string  // Encoded connection attributes.\n}\n\nfunc encodeConnectionAttributes(cfg *Config) string {\n\tconnAttrsBuf := make([]byte, 0)\n\n\t// default connection attributes\n\tconnAttrsBuf = appendLengthEncodedString(connAttrsBuf, connAttrClientName)\n\tconnAttrsBuf = appendLengthEncodedString(connAttrsBuf, connAttrClientNameValue)\n\tconnAttrsBuf = appendLengthEncodedString(connAttrsBuf, connAttrOS)\n\tconnAttrsBuf = appendLengthEncodedString(connAttrsBuf, connAttrOSValue)\n\tconnAttrsBuf = appendLengthEncodedString(connAttrsBuf, connAttrPlatform)\n\tconnAttrsBuf = appendLengthEncodedString(connAttrsBuf, connAttrPlatformValue)\n\tconnAttrsBuf = appendLengthEncodedString(connAttrsBuf, connAttrPid)\n\tconnAttrsBuf = appendLengthEncodedString(connAttrsBuf, strconv.Itoa(os.Getpid()))\n\tserverHost, _, _ := net.SplitHostPort(cfg.Addr)\n\tif serverHost != \"\" {\n\t\tconnAttrsBuf = appendLengthEncodedString(connAttrsBuf, connAttrServerHost)\n\t\tconnAttrsBuf = appendLengthEncodedString(connAttrsBuf, serverHost)\n\t}\n\n\t// user-defined connection attributes\n\tfor _, connAttr := range strings.Split(cfg.ConnectionAttributes, \",\") {\n\t\tk, v, found := strings.Cut(connAttr, \":\")\n\t\tif !found {\n\t\t\tcontinue\n\t\t}\n\t\tconnAttrsBuf = appendLengthEncodedString(connAttrsBuf, k)\n\t\tconnAttrsBuf = appendLengthEncodedString(connAttrsBuf, v)\n\t}\n\n\treturn string(connAttrsBuf)\n}\n\nfunc newConnector(cfg *Config) *connector {\n\tencodedAttributes := encodeConnectionAttributes(cfg)\n\treturn &connector{\n\t\tcfg:               cfg,\n\t\tencodedAttributes: encodedAttributes,\n\t}\n}\n\n// Connect implements driver.Connector interface.\n// Connect returns a connection to the database.\nfunc (c *connector) Connect(ctx context.Context) (driver.Conn, error) {\n\tvar err error\n\n\t// Invoke beforeConnect if present, with a copy of the configuration\n\tcfg := c.cfg\n\tif c.cfg.beforeConnect != nil {\n\t\tcfg = c.cfg.Clone()\n\t\terr = c.cfg.beforeConnect(ctx, cfg)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// New mysqlConn\n\tmc := &mysqlConn{\n\t\tmaxAllowedPacket: maxPacketSize,\n\t\tmaxWriteSize:     maxPacketSize - 1,\n\t\tclosech:          make(chan struct{}),\n\t\tcfg:              cfg,\n\t\tconnector:        c,\n\t}\n\tmc.parseTime = mc.cfg.ParseTime\n\n\t// Connect to Server\n\tdctx := ctx\n\tif mc.cfg.Timeout > 0 {\n\t\tvar cancel context.CancelFunc\n\t\tdctx, cancel = context.WithTimeout(ctx, c.cfg.Timeout)\n\t\tdefer cancel()\n\t}\n\n\tif c.cfg.DialFunc != nil {\n\t\tmc.netConn, err = c.cfg.DialFunc(dctx, mc.cfg.Net, mc.cfg.Addr)\n\t} else {\n\t\tdialsLock.RLock()\n\t\tdial, ok := dials[mc.cfg.Net]\n\t\tdialsLock.RUnlock()\n\t\tif ok {\n\t\t\tmc.netConn, err = dial(dctx, mc.cfg.Addr)\n\t\t} else {\n\t\t\tnd := net.Dialer{}\n\t\t\tmc.netConn, err = nd.DialContext(dctx, mc.cfg.Net, mc.cfg.Addr)\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmc.rawConn = mc.netConn\n\n\t// Enable TCP Keepalives on TCP connections\n\tif tc, ok := mc.netConn.(*net.TCPConn); ok {\n\t\tif err := tc.SetKeepAlive(true); err != nil {\n\t\t\tc.cfg.Logger.Print(err)\n\t\t}\n\t}\n\n\t// Call startWatcher for context support (From Go 1.8)\n\tmc.startWatcher()\n\tif err := mc.watchCancel(ctx); err != nil {\n\t\tmc.cleanup()\n\t\treturn nil, err\n\t}\n\tdefer mc.finish()\n\n\tmc.buf = newBuffer()\n\n\t// Reading Handshake Initialization Packet\n\tauthData, serverCapabilities, serverExtCapabilities, plugin, err := mc.readHandshakePacket()\n\tif err != nil {\n\t\tmc.cleanup()\n\t\treturn nil, err\n\t}\n\n\tif plugin == \"\" {\n\t\tplugin = defaultAuthPlugin\n\t}\n\n\t// Send Client Authentication Packet\n\tauthResp, err := mc.auth(authData, plugin)\n\tif err != nil {\n\t\t// try the default auth plugin, if using the requested plugin failed\n\t\tc.cfg.Logger.Print(\"could not use requested auth plugin '\"+plugin+\"': \", err.Error())\n\t\tplugin = defaultAuthPlugin\n\t\tauthResp, err = mc.auth(authData, plugin)\n\t\tif err != nil {\n\t\t\tmc.cleanup()\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tmc.initCapabilities(serverCapabilities, serverExtCapabilities, mc.cfg)\n\tif err = mc.writeHandshakeResponsePacket(authResp, plugin); err != nil {\n\t\tmc.cleanup()\n\t\treturn nil, err\n\t}\n\n\t// Handle response to auth packet, switch methods if possible\n\tif err = mc.handleAuthResult(authData, plugin); err != nil {\n\t\t// Authentication failed and MySQL has already closed the connection\n\t\t// (https://dev.mysql.com/doc/dev/mysql-server/latest/page_protocol_connection_phase.html#sect_protocol_connection_phase_fast_path_fails).\n\t\t// Do not send COM_QUIT, just cleanup and return the error.\n\t\tmc.cleanup()\n\t\treturn nil, err\n\t}\n\n\t// compression is enabled after auth, not right after sending handshake response.\n\tif mc.capabilities&clientCompress > 0 {\n\t\tmc.compress = true\n\t\tmc.compIO = newCompIO(mc)\n\t}\n\tif mc.cfg.MaxAllowedPacket > 0 {\n\t\tmc.maxAllowedPacket = mc.cfg.MaxAllowedPacket\n\t} else {\n\t\t// Get max allowed packet size\n\t\tmaxap, err := mc.getSystemVar(\"max_allowed_packet\")\n\t\tif err != nil {\n\t\t\tmc.Close()\n\t\t\treturn nil, err\n\t\t}\n\t\tn, err := strconv.Atoi(string(maxap))\n\t\tif err != nil {\n\t\t\tmc.Close()\n\t\t\treturn nil, fmt.Errorf(\"invalid max_allowed_packet value (%q): %w\", maxap, err)\n\t\t}\n\t\tmc.maxAllowedPacket = n - 1\n\t}\n\tif mc.maxAllowedPacket < maxPacketSize {\n\t\tmc.maxWriteSize = mc.maxAllowedPacket\n\t}\n\n\t// Charset: character_set_connection, character_set_client, character_set_results\n\tif len(mc.cfg.charsets) > 0 {\n\t\tfor _, cs := range mc.cfg.charsets {\n\t\t\t// ignore errors here - a charset may not exist\n\t\t\tif mc.cfg.Collation != \"\" {\n\t\t\t\terr = mc.exec(\"SET NAMES \" + cs + \" COLLATE \" + mc.cfg.Collation)\n\t\t\t} else {\n\t\t\t\terr = mc.exec(\"SET NAMES \" + cs)\n\t\t\t}\n\t\t\tif err == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\tmc.Close()\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Handle DSN Params\n\terr = mc.handleParams()\n\tif err != nil {\n\t\tmc.Close()\n\t\treturn nil, err\n\t}\n\n\treturn mc, nil\n}\n\n// Driver implements driver.Connector interface.\n// Driver returns &MySQLDriver{}.\nfunc (c *connector) Driver() driver.Driver {\n\treturn &MySQLDriver{}\n}\n"
  },
  {
    "path": "connector_test.go",
    "content": "package mysql\n\nimport (\n\t\"context\"\n\t\"net\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestConnectorReturnsTimeout(t *testing.T) {\n\tconnector := newConnector(&Config{\n\t\tNet:     \"tcp\",\n\t\tAddr:    \"1.1.1.1:1234\",\n\t\tTimeout: 10 * time.Millisecond,\n\t})\n\n\t_, err := connector.Connect(context.Background())\n\tif err == nil {\n\t\tt.Fatal(\"error expected\")\n\t}\n\n\tif nerr, ok := err.(*net.OpError); ok {\n\t\texpected := \"dial tcp 1.1.1.1:1234: i/o timeout\"\n\t\tif nerr.Error() != expected {\n\t\t\tt.Fatalf(\"expected %q, got %q\", expected, nerr.Error())\n\t\t}\n\t} else {\n\t\tt.Fatalf(\"expected %T, got %T\", nerr, err)\n\t}\n}\n"
  },
  {
    "path": "const.go",
    "content": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at http://mozilla.org/MPL/2.0/.\n\npackage mysql\n\nimport \"runtime\"\n\nconst (\n\tdebug = false // for debugging. Set true only in development.\n\n\tdefaultAuthPlugin       = \"mysql_native_password\"\n\tdefaultMaxAllowedPacket = 64 << 20 // 64 MiB. See https://github.com/go-sql-driver/mysql/issues/1355\n\tminProtocolVersion      = 10\n\tmaxPacketSize           = 1<<24 - 1\n\ttimeFormat              = \"2006-01-02 15:04:05.999999\"\n\n\t// Connection attributes\n\t// See https://dev.mysql.com/doc/refman/8.0/en/performance-schema-connection-attribute-tables.html#performance-schema-connection-attributes-available\n\tconnAttrClientName      = \"_client_name\"\n\tconnAttrClientNameValue = \"Go-MySQL-Driver\"\n\tconnAttrOS              = \"_os\"\n\tconnAttrOSValue         = runtime.GOOS\n\tconnAttrPlatform        = \"_platform\"\n\tconnAttrPlatformValue   = runtime.GOARCH\n\tconnAttrPid             = \"_pid\"\n\tconnAttrServerHost      = \"_server_host\"\n)\n\n// MySQL constants documentation:\n// https://dev.mysql.com/doc/dev/mysql-server/latest/PAGE_PROTOCOL.html\n\nconst (\n\tiOK           byte = 0x00\n\tiAuthMoreData byte = 0x01\n\tiLocalInFile  byte = 0xfb\n\tiEOF          byte = 0xfe\n\tiERR          byte = 0xff\n)\n\n// https://dev.mysql.com/doc/dev/mysql-server/latest/group__group__cs__capabilities__flags.html\n// https://mariadb.com/kb/en/connection/#capabilities\ntype capabilityFlag uint32\n\nconst (\n\tclientMySQL capabilityFlag = 1 << iota\n\tclientFoundRows\n\tclientLongFlag\n\tclientConnectWithDB\n\tclientNoSchema\n\tclientCompress\n\tclientODBC\n\tclientLocalFiles\n\tclientIgnoreSpace\n\tclientProtocol41\n\tclientInteractive\n\tclientSSL\n\tclientIgnoreSIGPIPE\n\tclientTransactions\n\tclientReserved\n\tclientSecureConn\n\tclientMultiStatements\n\tclientMultiResults\n\tclientPSMultiResults\n\tclientPluginAuth\n\tclientConnectAttrs\n\tclientPluginAuthLenEncClientData\n\tclientCanHandleExpiredPasswords\n\tclientSessionTrack\n\tclientDeprecateEOF\n)\n\n// https://mariadb.com/kb/en/connection/#capabilities\ntype extendedCapabilityFlag uint32\n\nconst (\n\tprogressIndicator extendedCapabilityFlag = 1 << iota\n\tclientComMulti\n\tclientStmtBulkOperations\n\tclientExtendedMetadata\n\tclientCacheMetadata\n\tclientUnitBulkResult\n)\n\nconst (\n\tcomQuit byte = iota + 1\n\tcomInitDB\n\tcomQuery\n\tcomFieldList\n\tcomCreateDB\n\tcomDropDB\n\tcomRefresh\n\tcomShutdown\n\tcomStatistics\n\tcomProcessInfo\n\tcomConnect\n\tcomProcessKill\n\tcomDebug\n\tcomPing\n\tcomTime\n\tcomDelayedInsert\n\tcomChangeUser\n\tcomBinlogDump\n\tcomTableDump\n\tcomConnectOut\n\tcomRegisterSlave\n\tcomStmtPrepare\n\tcomStmtExecute\n\tcomStmtSendLongData\n\tcomStmtClose\n\tcomStmtReset\n\tcomSetOption\n\tcomStmtFetch\n)\n\n// https://dev.mysql.com/doc/internals/en/com-query-response.html#packet-Protocol::ColumnType\ntype fieldType byte\n\nconst (\n\tfieldTypeDecimal fieldType = iota\n\tfieldTypeTiny\n\tfieldTypeShort\n\tfieldTypeLong\n\tfieldTypeFloat\n\tfieldTypeDouble\n\tfieldTypeNULL\n\tfieldTypeTimestamp\n\tfieldTypeLongLong\n\tfieldTypeInt24\n\tfieldTypeDate\n\tfieldTypeTime\n\tfieldTypeDateTime\n\tfieldTypeYear\n\tfieldTypeNewDate\n\tfieldTypeVarChar\n\tfieldTypeBit\n)\nconst (\n\tfieldTypeVector fieldType = iota + 0xf2\n\tfieldTypeInvalid\n\tfieldTypeBool\n\tfieldTypeJSON\n\tfieldTypeNewDecimal\n\tfieldTypeEnum\n\tfieldTypeSet\n\tfieldTypeTinyBLOB\n\tfieldTypeMediumBLOB\n\tfieldTypeLongBLOB\n\tfieldTypeBLOB\n\tfieldTypeVarString\n\tfieldTypeString\n\tfieldTypeGeometry\n)\n\ntype fieldFlag uint16\n\nconst (\n\tflagNotNULL fieldFlag = 1 << iota\n\tflagPriKey\n\tflagUniqueKey\n\tflagMultipleKey\n\tflagBLOB\n\tflagUnsigned\n\tflagZeroFill\n\tflagBinary\n\tflagEnum\n\tflagAutoIncrement\n\tflagTimestamp\n\tflagSet\n\tflagUnknown1\n\tflagUnknown2\n\tflagUnknown3\n\tflagUnknown4\n)\n\n// http://dev.mysql.com/doc/internals/en/status-flags.html\ntype statusFlag uint16\n\nconst (\n\tstatusInTrans statusFlag = 1 << iota\n\tstatusInAutocommit\n\tstatusReserved // Not in documentation\n\tstatusMoreResultsExists\n\tstatusNoGoodIndexUsed\n\tstatusNoIndexUsed\n\tstatusCursorExists\n\tstatusLastRowSent\n\tstatusDbDropped\n\tstatusNoBackslashEscapes\n\tstatusMetadataChanged\n\tstatusQueryWasSlow\n\tstatusPsOutParams\n\tstatusInTransReadonly\n\tstatusSessionStateChanged\n)\n\nconst (\n\tcachingSha2PasswordRequestPublicKey          = 2\n\tcachingSha2PasswordFastAuthSuccess           = 3\n\tcachingSha2PasswordPerformFullAuthentication = 4\n)\n"
  },
  {
    "path": "driver.go",
    "content": "// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at http://mozilla.org/MPL/2.0/.\n\n// Package mysql provides a MySQL driver for Go's database/sql package.\n//\n// The driver should be used via the database/sql package:\n//\n//\timport \"database/sql\"\n//\timport _ \"github.com/go-sql-driver/mysql\"\n//\n//\tdb, err := sql.Open(\"mysql\", \"user:password@/dbname\")\n//\n// See https://github.com/go-sql-driver/mysql#usage for details\npackage mysql\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"database/sql/driver\"\n\t\"net\"\n\t\"sync\"\n)\n\n// MySQLDriver is exported to make the driver directly accessible.\n// In general the driver is used via the database/sql package.\ntype MySQLDriver struct{}\n\n// DialFunc is a function which can be used to establish the network connection.\n// Custom dial functions must be registered with RegisterDial\n//\n// Deprecated: users should register a DialContextFunc instead\ntype DialFunc func(addr string) (net.Conn, error)\n\n// DialContextFunc is a function which can be used to establish the network connection.\n// Custom dial functions must be registered with RegisterDialContext\ntype DialContextFunc func(ctx context.Context, addr string) (net.Conn, error)\n\nvar (\n\tdialsLock sync.RWMutex\n\tdials     map[string]DialContextFunc\n)\n\n// RegisterDialContext registers a custom dial function. It can then be used by the\n// network address mynet(addr), where mynet is the registered new network.\n// The current context for the connection and its address is passed to the dial function.\nfunc RegisterDialContext(net string, dial DialContextFunc) {\n\tdialsLock.Lock()\n\tdefer dialsLock.Unlock()\n\tif dials == nil {\n\t\tdials = make(map[string]DialContextFunc)\n\t}\n\tdials[net] = dial\n}\n\n// DeregisterDialContext removes the custom dial function registered with the given net.\nfunc DeregisterDialContext(net string) {\n\tdialsLock.Lock()\n\tdefer dialsLock.Unlock()\n\tif dials != nil {\n\t\tdelete(dials, net)\n\t}\n}\n\n// RegisterDial registers a custom dial function. It can then be used by the\n// network address mynet(addr), where mynet is the registered new network.\n// addr is passed as a parameter to the dial function.\n//\n// Deprecated: users should call RegisterDialContext instead\nfunc RegisterDial(network string, dial DialFunc) {\n\tRegisterDialContext(network, func(_ context.Context, addr string) (net.Conn, error) {\n\t\treturn dial(addr)\n\t})\n}\n\n// Open new Connection.\n// See https://github.com/go-sql-driver/mysql#dsn-data-source-name for how\n// the DSN string is formatted\nfunc (d MySQLDriver) Open(dsn string) (driver.Conn, error) {\n\tcfg, err := ParseDSN(dsn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc := newConnector(cfg)\n\treturn c.Connect(context.Background())\n}\n\n// This variable can be replaced with -ldflags like below:\n// go build \"-ldflags=-X github.com/go-sql-driver/mysql.driverName=custom\"\nvar driverName = \"mysql\"\n\nfunc init() {\n\tif driverName != \"\" {\n\t\tsql.Register(driverName, &MySQLDriver{})\n\t}\n}\n\n// NewConnector returns new driver.Connector.\nfunc NewConnector(cfg *Config) (driver.Connector, error) {\n\tcfg = cfg.Clone()\n\t// normalize the contents of cfg so calls to NewConnector have the same\n\t// behavior as MySQLDriver.OpenConnector\n\tif err := cfg.normalize(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn newConnector(cfg), nil\n}\n\n// OpenConnector implements driver.DriverContext.\nfunc (d MySQLDriver) OpenConnector(dsn string) (driver.Connector, error) {\n\tcfg, err := ParseDSN(dsn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn newConnector(cfg), nil\n}\n"
  },
  {
    "path": "driver_test.go",
    "content": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at http://mozilla.org/MPL/2.0/.\n\npackage mysql\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"crypto/rand\"\n\t\"crypto/tls\"\n\t\"database/sql\"\n\t\"database/sql/driver\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"math\"\n\tmrand \"math/rand\"\n\t\"net\"\n\t\"net/url\"\n\t\"os\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"slices\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"testing\"\n\t\"time\"\n)\n\n// This variable can be replaced with -ldflags like below:\n// go test \"-ldflags=-X github.com/go-sql-driver/mysql.driverNameTest=custom\"\nvar driverNameTest string\n\nfunc init() {\n\tif driverNameTest == \"\" {\n\t\tdriverNameTest = driverName\n\t}\n}\n\n// Ensure that all the driver interfaces are implemented\nvar (\n\t_ driver.Rows = &binaryRows{}\n\t_ driver.Rows = &textRows{}\n)\n\nvar (\n\tuser      string\n\tpass      string\n\tprot      string\n\taddr      string\n\tdbname    string\n\tdsn       string\n\tnetAddr   string\n\tavailable bool\n)\n\nvar (\n\ttDate      = time.Date(2012, 6, 14, 0, 0, 0, 0, time.UTC)\n\tsDate      = \"2012-06-14\"\n\ttDateTime  = time.Date(2011, 11, 20, 21, 27, 37, 0, time.UTC)\n\tsDateTime  = \"2011-11-20 21:27:37\"\n\ttDate0     = time.Time{}\n\tsDate0     = \"0000-00-00\"\n\tsDateTime0 = \"0000-00-00 00:00:00\"\n)\n\n// See https://github.com/go-sql-driver/mysql/wiki/Testing\nfunc init() {\n\t// get environment variables\n\tenv := func(key, defaultValue string) string {\n\t\tif value := os.Getenv(key); value != \"\" {\n\t\t\treturn value\n\t\t}\n\t\treturn defaultValue\n\t}\n\tuser = env(\"MYSQL_TEST_USER\", \"root\")\n\tpass = env(\"MYSQL_TEST_PASS\", \"\")\n\tprot = env(\"MYSQL_TEST_PROT\", \"tcp\")\n\taddr = env(\"MYSQL_TEST_ADDR\", \"localhost:3306\")\n\tdbname = env(\"MYSQL_TEST_DBNAME\", \"gotest\")\n\tnetAddr = fmt.Sprintf(\"%s(%s)\", prot, addr)\n\tdsn = fmt.Sprintf(\"%s:%s@%s/%s?timeout=30s\", user, pass, netAddr, dbname)\n\tc, err := net.Dial(prot, addr)\n\tif err == nil {\n\t\tavailable = true\n\t\tc.Close()\n\t}\n}\n\ntype DBTest struct {\n\ttesting.TB\n\tdb *sql.DB\n}\n\ntype netErrorMock struct {\n\ttemporary bool\n\ttimeout   bool\n}\n\nfunc (e netErrorMock) Temporary() bool {\n\treturn e.temporary\n}\n\nfunc (e netErrorMock) Timeout() bool {\n\treturn e.timeout\n}\n\nfunc (e netErrorMock) Error() string {\n\treturn fmt.Sprintf(\"mock net error. Temporary: %v, Timeout %v\", e.temporary, e.timeout)\n}\n\nfunc runTestsWithMultiStatement(t *testing.T, dsn string, tests ...func(dbt *DBTest)) {\n\tif !available {\n\t\tt.Skipf(\"MySQL server not running on %s\", netAddr)\n\t}\n\n\tdsn += \"&multiStatements=true\"\n\tvar db *sql.DB\n\tif _, err := ParseDSN(dsn); err != errInvalidDSNUnsafeCollation {\n\t\tdb, err = sql.Open(driverNameTest, dsn)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"error connecting: %s\", err.Error())\n\t\t}\n\t\tdefer db.Close()\n\t}\n\t// Previous test may be skipped without dropping the test table\n\tdb.Exec(\"DROP TABLE IF EXISTS test\")\n\n\tdbt := &DBTest{t, db}\n\tfor _, test := range tests {\n\t\ttest(dbt)\n\t\tdbt.db.Exec(\"DROP TABLE IF EXISTS test\")\n\t}\n}\n\nfunc runTests(t *testing.T, dsn string, tests ...func(dbt *DBTest)) {\n\tif !available {\n\t\tt.Skipf(\"MySQL server not running on %s\", netAddr)\n\t}\n\n\tdb, err := sql.Open(driverNameTest, dsn)\n\tif err != nil {\n\t\tt.Fatalf(\"connecting %q: %s\", dsn, err)\n\t}\n\tdefer db.Close()\n\tif err = db.Ping(); err != nil {\n\t\tt.Fatalf(\"connecting %q: %s\", dsn, err)\n\t}\n\n\tdsn2 := dsn + \"&interpolateParams=true\"\n\tvar db2 *sql.DB\n\tif _, err := ParseDSN(dsn2); err != errInvalidDSNUnsafeCollation {\n\t\tdb2, err = sql.Open(driverNameTest, dsn2)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"connecting %q: %s\", dsn2, err)\n\t\t}\n\t\tdefer db2.Close()\n\t}\n\n\tdsn3 := dsn + \"&compress=true\"\n\tvar db3 *sql.DB\n\tdb3, err = sql.Open(driverNameTest, dsn3)\n\tif err != nil {\n\t\tt.Fatalf(\"connecting %q: %s\", dsn3, err)\n\t}\n\tdefer db3.Close()\n\n\tcleanupSql := \"DROP TABLE IF EXISTS test\"\n\n\tfor _, test := range tests {\n\t\ttest := test\n\t\tt.Run(\"default\", func(t *testing.T) {\n\t\t\tdbt := &DBTest{t, db}\n\t\t\tt.Cleanup(func() {\n\t\t\t\tdb.Exec(cleanupSql)\n\t\t\t})\n\t\t\ttest(dbt)\n\t\t})\n\t\tif db2 != nil {\n\t\t\tt.Run(\"interpolateParams\", func(t *testing.T) {\n\t\t\t\tdbt2 := &DBTest{t, db2}\n\t\t\t\tt.Cleanup(func() {\n\t\t\t\t\tdb2.Exec(cleanupSql)\n\t\t\t\t})\n\t\t\t\ttest(dbt2)\n\t\t\t})\n\t\t}\n\t\tt.Run(\"compress\", func(t *testing.T) {\n\t\t\tdbt3 := &DBTest{t, db3}\n\t\t\tt.Cleanup(func() {\n\t\t\t\tdb3.Exec(cleanupSql)\n\t\t\t})\n\t\t\ttest(dbt3)\n\t\t})\n\t}\n}\n\n// runTestsParallel runs the tests in parallel with a separate database connection for each test.\nfunc runTestsParallel(t *testing.T, dsn string, tests ...func(dbt *DBTest, tableName string)) {\n\tif !available {\n\t\tt.Skipf(\"MySQL server not running on %s\", netAddr)\n\t}\n\n\tnewTableName := func(t *testing.T) string {\n\t\tt.Helper()\n\t\tvar buf [8]byte\n\t\tif _, err := rand.Read(buf[:]); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\treturn fmt.Sprintf(\"test_%x\", buf[:])\n\t}\n\n\tt.Parallel()\n\tfor _, test := range tests {\n\t\ttest := test\n\n\t\tt.Run(\"default\", func(t *testing.T) {\n\t\t\tt.Parallel()\n\n\t\t\ttableName := newTableName(t)\n\t\t\tdb, err := sql.Open(\"mysql\", dsn)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"error connecting: %s\", err.Error())\n\t\t\t}\n\t\t\tt.Cleanup(func() {\n\t\t\t\tdb.Exec(\"DROP TABLE IF EXISTS \" + tableName)\n\t\t\t\tdb.Close()\n\t\t\t})\n\n\t\t\tdbt := &DBTest{t, db}\n\t\t\ttest(dbt, tableName)\n\t\t})\n\n\t\tdsn2 := dsn + \"&interpolateParams=true\"\n\t\tif _, err := ParseDSN(dsn2); err == errInvalidDSNUnsafeCollation {\n\t\t\tt.Run(\"interpolateParams\", func(t *testing.T) {\n\t\t\t\tt.Parallel()\n\n\t\t\t\ttableName := newTableName(t)\n\t\t\t\tdb, err := sql.Open(\"mysql\", dsn2)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatalf(\"error connecting: %s\", err.Error())\n\t\t\t\t}\n\t\t\t\tt.Cleanup(func() {\n\t\t\t\t\tdb.Exec(\"DROP TABLE IF EXISTS \" + tableName)\n\t\t\t\t\tdb.Close()\n\t\t\t\t})\n\n\t\t\t\tdbt := &DBTest{t, db}\n\t\t\t\ttest(dbt, tableName)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc (dbt *DBTest) fail(method, query string, err error) {\n\tdbt.Helper()\n\tif len(query) > 300 {\n\t\tquery = \"[query too large to print]\"\n\t}\n\tdbt.Fatalf(\"error on %s %s: %s\", method, query, err.Error())\n}\n\nfunc (dbt *DBTest) mustExec(query string, args ...any) (res sql.Result) {\n\tdbt.Helper()\n\tres, err := dbt.db.Exec(query, args...)\n\tif err != nil {\n\t\tdbt.fail(\"exec\", query, err)\n\t}\n\treturn res\n}\n\nfunc (dbt *DBTest) mustQuery(query string, args ...any) (rows *sql.Rows) {\n\tdbt.Helper()\n\trows, err := dbt.db.Query(query, args...)\n\tif err != nil {\n\t\tdbt.fail(\"query\", query, err)\n\t}\n\treturn rows\n}\n\nfunc maybeSkip(t *testing.T, err error, skipErrno uint16) {\n\tmySQLErr, ok := err.(*MySQLError)\n\tif !ok {\n\t\treturn\n\t}\n\n\tif mySQLErr.Number == skipErrno {\n\t\tt.Skipf(\"skipping test for error: %v\", err)\n\t}\n}\n\nfunc TestEmptyQuery(t *testing.T) {\n\trunTestsParallel(t, dsn, func(dbt *DBTest, _ string) {\n\t\t// just a comment, no query\n\t\trows := dbt.mustQuery(\"--\")\n\t\tdefer rows.Close()\n\t\t// will hang before #255\n\t\tif rows.Next() {\n\t\t\tdbt.Errorf(\"next on rows must be false\")\n\t\t}\n\t})\n}\n\nfunc TestCRUD(t *testing.T) {\n\trunTestsParallel(t, dsn, func(dbt *DBTest, tbl string) {\n\t\t// Create Table\n\t\tdbt.mustExec(\"CREATE TABLE \" + tbl + \" (value BOOL)\")\n\n\t\t// Test for unexpected data\n\t\tvar out bool\n\t\trows := dbt.mustQuery(\"SELECT * FROM \" + tbl)\n\t\tif rows.Next() {\n\t\t\tdbt.Error(\"unexpected data in empty table\")\n\t\t}\n\t\trows.Close()\n\n\t\t// Create Data\n\t\tres := dbt.mustExec(\"INSERT INTO \" + tbl + \" VALUES (1)\")\n\t\tcount, err := res.RowsAffected()\n\t\tif err != nil {\n\t\t\tdbt.Fatalf(\"res.RowsAffected() returned error: %s\", err.Error())\n\t\t}\n\t\tif count != 1 {\n\t\t\tdbt.Fatalf(\"expected 1 affected row, got %d\", count)\n\t\t}\n\n\t\tid, err := res.LastInsertId()\n\t\tif err != nil {\n\t\t\tdbt.Fatalf(\"res.LastInsertId() returned error: %s\", err.Error())\n\t\t}\n\t\tif id != 0 {\n\t\t\tdbt.Fatalf(\"expected InsertId 0, got %d\", id)\n\t\t}\n\n\t\t// Read\n\t\trows = dbt.mustQuery(\"SELECT value FROM \" + tbl)\n\t\tif rows.Next() {\n\t\t\trows.Scan(&out)\n\t\t\tif true != out {\n\t\t\t\tdbt.Errorf(\"true != %t\", out)\n\t\t\t}\n\n\t\t\tif rows.Next() {\n\t\t\t\tdbt.Error(\"unexpected data\")\n\t\t\t}\n\t\t} else {\n\t\t\tdbt.Error(\"no data\")\n\t\t}\n\t\trows.Close()\n\n\t\t// Update\n\t\tres = dbt.mustExec(\"UPDATE \"+tbl+\" SET value = ? WHERE value = ?\", false, true)\n\t\tcount, err = res.RowsAffected()\n\t\tif err != nil {\n\t\t\tdbt.Fatalf(\"res.RowsAffected() returned error: %s\", err.Error())\n\t\t}\n\t\tif count != 1 {\n\t\t\tdbt.Fatalf(\"expected 1 affected row, got %d\", count)\n\t\t}\n\n\t\t// Check Update\n\t\trows = dbt.mustQuery(\"SELECT value FROM \" + tbl)\n\t\tif rows.Next() {\n\t\t\trows.Scan(&out)\n\t\t\tif false != out {\n\t\t\t\tdbt.Errorf(\"false != %t\", out)\n\t\t\t}\n\n\t\t\tif rows.Next() {\n\t\t\t\tdbt.Error(\"unexpected data\")\n\t\t\t}\n\t\t} else {\n\t\t\tdbt.Error(\"no data\")\n\t\t}\n\t\trows.Close()\n\n\t\t// Delete\n\t\tres = dbt.mustExec(\"DELETE FROM \"+tbl+\" WHERE value = ?\", false)\n\t\tcount, err = res.RowsAffected()\n\t\tif err != nil {\n\t\t\tdbt.Fatalf(\"res.RowsAffected() returned error: %s\", err.Error())\n\t\t}\n\t\tif count != 1 {\n\t\t\tdbt.Fatalf(\"expected 1 affected row, got %d\", count)\n\t\t}\n\n\t\t// Check for unexpected rows\n\t\tres = dbt.mustExec(\"DELETE FROM \" + tbl)\n\t\tcount, err = res.RowsAffected()\n\t\tif err != nil {\n\t\t\tdbt.Fatalf(\"res.RowsAffected() returned error: %s\", err.Error())\n\t\t}\n\t\tif count != 0 {\n\t\t\tdbt.Fatalf(\"expected 0 affected row, got %d\", count)\n\t\t}\n\t})\n}\n\n// TestNumbers test that selecting numeric columns.\n// Both of textRows and binaryRows should return same type and value.\nfunc TestNumbersToAny(t *testing.T) {\n\trunTestsParallel(t, dsn, func(dbt *DBTest, tbl string) {\n\t\tdbt.mustExec(\"CREATE TABLE \" + tbl + \" (id INT PRIMARY KEY, b BOOL, i8 TINYINT, \" +\n\t\t\t\"i16 SMALLINT, i32 INT, i64 BIGINT, f32 FLOAT, f64 DOUBLE, iu32 INT UNSIGNED)\")\n\t\tdbt.mustExec(\"INSERT INTO \" + tbl + \" VALUES (1, true, 127, 32767, 2147483647, 9223372036854775807, 1.25, 2.5, 4294967295)\")\n\n\t\t// Use binaryRows for interpolateParams=false and textRows for interpolateParams=true.\n\t\trows := dbt.mustQuery(\"SELECT b, i8, i16, i32, i64, f32, f64, iu32 FROM \"+tbl+\" WHERE id=?\", 1)\n\t\tif !rows.Next() {\n\t\t\tdbt.Fatal(\"no data\")\n\t\t}\n\t\tvar b, i8, i16, i32, i64, f32, f64, iu32 any\n\t\terr := rows.Scan(&b, &i8, &i16, &i32, &i64, &f32, &f64, &iu32)\n\t\tif err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tif b.(int64) != 1 {\n\t\t\tdbt.Errorf(\"b != 1\")\n\t\t}\n\t\tif i8.(int64) != 127 {\n\t\t\tdbt.Errorf(\"i8 != 127\")\n\t\t}\n\t\tif i16.(int64) != 32767 {\n\t\t\tdbt.Errorf(\"i16 != 32767\")\n\t\t}\n\t\tif i32.(int64) != 2147483647 {\n\t\t\tdbt.Errorf(\"i32 != 2147483647\")\n\t\t}\n\t\tif i64.(int64) != 9223372036854775807 {\n\t\t\tdbt.Errorf(\"i64 != 9223372036854775807\")\n\t\t}\n\t\tif f32.(float32) != 1.25 {\n\t\t\tdbt.Errorf(\"f32 != 1.25\")\n\t\t}\n\t\tif f64.(float64) != 2.5 {\n\t\t\tdbt.Errorf(\"f64 != 2.5\")\n\t\t}\n\t\tif iu32.(int64) != 4294967295 {\n\t\t\tdbt.Errorf(\"iu32 != 4294967295\")\n\t\t}\n\t})\n}\n\nfunc TestMultiQuery(t *testing.T) {\n\trunTestsWithMultiStatement(t, dsn, func(dbt *DBTest) {\n\t\t// Create Table\n\t\tdbt.mustExec(\"CREATE TABLE `test` (`id` int(11) NOT NULL, `value` int(11) NOT NULL) \")\n\n\t\t// Create Data\n\t\tres := dbt.mustExec(\"INSERT INTO test VALUES (1, 1)\")\n\t\tcount, err := res.RowsAffected()\n\t\tif err != nil {\n\t\t\tdbt.Fatalf(\"res.RowsAffected() returned error: %s\", err.Error())\n\t\t}\n\t\tif count != 1 {\n\t\t\tdbt.Fatalf(\"expected 1 affected row, got %d\", count)\n\t\t}\n\n\t\t// Update\n\t\tres = dbt.mustExec(\"UPDATE test SET value = 3 WHERE id = 1; UPDATE test SET value = 4 WHERE id = 1; UPDATE test SET value = 5 WHERE id = 1;\")\n\t\tcount, err = res.RowsAffected()\n\t\tif err != nil {\n\t\t\tdbt.Fatalf(\"res.RowsAffected() returned error: %s\", err.Error())\n\t\t}\n\t\tif count != 1 {\n\t\t\tdbt.Fatalf(\"expected 1 affected row, got %d\", count)\n\t\t}\n\n\t\t// Read\n\t\tvar out int\n\t\trows := dbt.mustQuery(\"SELECT value FROM test WHERE id=1;\")\n\t\tif rows.Next() {\n\t\t\trows.Scan(&out)\n\t\t\tif out != 5 {\n\t\t\t\tdbt.Errorf(\"expected 5, got %d\", out)\n\t\t\t}\n\n\t\t\tif rows.Next() {\n\t\t\t\tdbt.Error(\"unexpected data\")\n\t\t\t}\n\t\t} else {\n\t\t\tdbt.Error(\"no data\")\n\t\t}\n\t\trows.Close()\n\n\t})\n}\n\nfunc TestInt(t *testing.T) {\n\trunTestsParallel(t, dsn, func(dbt *DBTest, tbl string) {\n\t\ttypes := [5]string{\"TINYINT\", \"SMALLINT\", \"MEDIUMINT\", \"INT\", \"BIGINT\"}\n\t\tin := int64(42)\n\t\tvar out int64\n\t\tvar rows *sql.Rows\n\n\t\t// SIGNED\n\t\tfor _, v := range types {\n\t\t\tdbt.mustExec(\"CREATE TABLE \" + tbl + \" (value \" + v + \")\")\n\n\t\t\tdbt.mustExec(\"INSERT INTO \"+tbl+\" VALUES (?)\", in)\n\n\t\t\trows = dbt.mustQuery(\"SELECT value FROM \" + tbl)\n\t\t\tif rows.Next() {\n\t\t\t\trows.Scan(&out)\n\t\t\t\tif in != out {\n\t\t\t\t\tdbt.Errorf(\"%s: %d != %d\", v, in, out)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdbt.Errorf(\"%s: no data\", v)\n\t\t\t}\n\t\t\trows.Close()\n\n\t\t\tdbt.mustExec(\"DROP TABLE IF EXISTS \" + tbl)\n\t\t}\n\n\t\t// UNSIGNED ZEROFILL\n\t\tfor _, v := range types {\n\t\t\tdbt.mustExec(\"CREATE TABLE \" + tbl + \" (value \" + v + \" ZEROFILL)\")\n\n\t\t\tdbt.mustExec(\"INSERT INTO \"+tbl+\" VALUES (?)\", in)\n\n\t\t\trows = dbt.mustQuery(\"SELECT value FROM \" + tbl)\n\t\t\tif rows.Next() {\n\t\t\t\trows.Scan(&out)\n\t\t\t\tif in != out {\n\t\t\t\t\tdbt.Errorf(\"%s ZEROFILL: %d != %d\", v, in, out)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdbt.Errorf(\"%s ZEROFILL: no data\", v)\n\t\t\t}\n\t\t\trows.Close()\n\n\t\t\tdbt.mustExec(\"DROP TABLE IF EXISTS \" + tbl)\n\t\t}\n\t})\n}\n\nfunc TestFloat32(t *testing.T) {\n\trunTestsParallel(t, dsn, func(dbt *DBTest, tbl string) {\n\t\ttypes := [2]string{\"FLOAT\", \"DOUBLE\"}\n\t\tin := float32(42.23)\n\t\tvar out float32\n\t\tvar rows *sql.Rows\n\t\tfor _, v := range types {\n\t\t\tdbt.mustExec(\"CREATE TABLE \" + tbl + \" (value \" + v + \")\")\n\t\t\tdbt.mustExec(\"INSERT INTO \"+tbl+\" VALUES (?)\", in)\n\t\t\trows = dbt.mustQuery(\"SELECT value FROM \" + tbl)\n\t\t\tif rows.Next() {\n\t\t\t\trows.Scan(&out)\n\t\t\t\tif in != out {\n\t\t\t\t\tdbt.Errorf(\"%s: %g != %g\", v, in, out)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdbt.Errorf(\"%s: no data\", v)\n\t\t\t}\n\t\t\trows.Close()\n\t\t\tdbt.mustExec(\"DROP TABLE IF EXISTS \" + tbl)\n\t\t}\n\t})\n}\n\nfunc TestFloat64(t *testing.T) {\n\trunTestsParallel(t, dsn, func(dbt *DBTest, tbl string) {\n\t\ttypes := [2]string{\"FLOAT\", \"DOUBLE\"}\n\t\tvar expected float64 = 42.23\n\t\tvar out float64\n\t\tvar rows *sql.Rows\n\t\tfor _, v := range types {\n\t\t\tdbt.mustExec(\"CREATE TABLE \" + tbl + \" (value \" + v + \")\")\n\t\t\tdbt.mustExec(\"INSERT INTO \" + tbl + \" VALUES (42.23)\")\n\t\t\trows = dbt.mustQuery(\"SELECT value FROM \" + tbl)\n\t\t\tif rows.Next() {\n\t\t\t\trows.Scan(&out)\n\t\t\t\tif expected != out {\n\t\t\t\t\tdbt.Errorf(\"%s: %g != %g\", v, expected, out)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdbt.Errorf(\"%s: no data\", v)\n\t\t\t}\n\t\t\trows.Close()\n\t\t\tdbt.mustExec(\"DROP TABLE IF EXISTS \" + tbl)\n\t\t}\n\t})\n}\n\nfunc TestFloat64Placeholder(t *testing.T) {\n\trunTestsParallel(t, dsn, func(dbt *DBTest, tbl string) {\n\t\ttypes := [2]string{\"FLOAT\", \"DOUBLE\"}\n\t\tvar expected float64 = 42.23\n\t\tvar out float64\n\t\tvar rows *sql.Rows\n\t\tfor _, v := range types {\n\t\t\tdbt.mustExec(\"CREATE TABLE \" + tbl + \" (id int, value \" + v + \")\")\n\t\t\tdbt.mustExec(\"INSERT INTO \" + tbl + \" VALUES (1, 42.23)\")\n\t\t\trows = dbt.mustQuery(\"SELECT value FROM \"+tbl+\" WHERE id = ?\", 1)\n\t\t\tif rows.Next() {\n\t\t\t\trows.Scan(&out)\n\t\t\t\tif expected != out {\n\t\t\t\t\tdbt.Errorf(\"%s: %g != %g\", v, expected, out)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdbt.Errorf(\"%s: no data\", v)\n\t\t\t}\n\t\t\trows.Close()\n\t\t\tdbt.mustExec(\"DROP TABLE IF EXISTS \" + tbl)\n\t\t}\n\t})\n}\n\nfunc TestString(t *testing.T) {\n\trunTestsParallel(t, dsn, func(dbt *DBTest, tbl string) {\n\t\ttypes := [6]string{\"CHAR(255)\", \"VARCHAR(255)\", \"TINYTEXT\", \"TEXT\", \"MEDIUMTEXT\", \"LONGTEXT\"}\n\t\tin := \"κόσμε üöäßñóùéàâÿœ'îë Árvíztűrő いろはにほへとちりぬるを イロハニホヘト דג סקרן чащах  น่าฟังเอย\"\n\t\tvar out string\n\t\tvar rows *sql.Rows\n\n\t\tfor _, v := range types {\n\t\t\tdbt.mustExec(\"CREATE TABLE \" + tbl + \" (value \" + v + \") CHARACTER SET utf8\")\n\n\t\t\tdbt.mustExec(\"INSERT INTO \"+tbl+\" VALUES (?)\", in)\n\n\t\t\trows = dbt.mustQuery(\"SELECT value FROM \" + tbl)\n\t\t\tif rows.Next() {\n\t\t\t\trows.Scan(&out)\n\t\t\t\tif in != out {\n\t\t\t\t\tdbt.Errorf(\"%s: %s != %s\", v, in, out)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdbt.Errorf(\"%s: no data\", v)\n\t\t\t}\n\t\t\trows.Close()\n\n\t\t\tdbt.mustExec(\"DROP TABLE IF EXISTS \" + tbl)\n\t\t}\n\n\t\t// BLOB\n\t\tdbt.mustExec(\"CREATE TABLE \" + tbl + \" (id int, value BLOB) CHARACTER SET utf8\")\n\n\t\tid := 2\n\t\tin = \"Lorem ipsum dolor sit amet, consetetur sadipscing elitr, \" +\n\t\t\t\"sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, \" +\n\t\t\t\"sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. \" +\n\t\t\t\"Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. \" +\n\t\t\t\"Lorem ipsum dolor sit amet, consetetur sadipscing elitr, \" +\n\t\t\t\"sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, \" +\n\t\t\t\"sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. \" +\n\t\t\t\"Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.\"\n\t\tdbt.mustExec(\"INSERT INTO \"+tbl+\" VALUES (?, ?)\", id, in)\n\n\t\terr := dbt.db.QueryRow(\"SELECT value FROM \"+tbl+\" WHERE id = ?\", id).Scan(&out)\n\t\tif err != nil {\n\t\t\tdbt.Fatalf(\"Error on BLOB-Query: %s\", err.Error())\n\t\t} else if out != in {\n\t\t\tdbt.Errorf(\"BLOB: %s != %s\", in, out)\n\t\t}\n\t})\n}\n\nfunc TestRawBytes(t *testing.T) {\n\trunTestsParallel(t, dsn, func(dbt *DBTest, _ string) {\n\t\tv1 := []byte(\"aaa\")\n\t\tv2 := []byte(\"bbb\")\n\t\trows := dbt.mustQuery(\"SELECT ?, ?\", v1, v2)\n\t\tdefer rows.Close()\n\t\tif rows.Next() {\n\t\t\tvar o1, o2 sql.RawBytes\n\t\t\tif err := rows.Scan(&o1, &o2); err != nil {\n\t\t\t\tdbt.Errorf(\"Got error: %v\", err)\n\t\t\t}\n\t\t\tif !bytes.Equal(v1, o1) {\n\t\t\t\tdbt.Errorf(\"expected %v, got %v\", v1, o1)\n\t\t\t}\n\t\t\tif !bytes.Equal(v2, o2) {\n\t\t\t\tdbt.Errorf(\"expected %v, got %v\", v2, o2)\n\t\t\t}\n\t\t\t// https://github.com/go-sql-driver/mysql/issues/765\n\t\t\t// Appending to RawBytes shouldn't overwrite next RawBytes.\n\t\t\to1 = append(o1, \"xyzzy\"...)\n\t\t\tif !bytes.Equal(v2, o2) {\n\t\t\t\tdbt.Errorf(\"expected %v, got %v\", v2, o2)\n\t\t\t}\n\t\t} else {\n\t\t\tdbt.Errorf(\"no data\")\n\t\t}\n\t})\n}\n\nfunc TestRawMessage(t *testing.T) {\n\trunTestsParallel(t, dsn, func(dbt *DBTest, _ string) {\n\t\tv1 := json.RawMessage(\"{}\")\n\t\tv2 := json.RawMessage(\"[]\")\n\t\trows := dbt.mustQuery(\"SELECT ?, ?\", v1, v2)\n\t\tdefer rows.Close()\n\t\tif rows.Next() {\n\t\t\tvar o1, o2 json.RawMessage\n\t\t\tif err := rows.Scan(&o1, &o2); err != nil {\n\t\t\t\tdbt.Errorf(\"Got error: %v\", err)\n\t\t\t}\n\t\t\tif !bytes.Equal(v1, o1) {\n\t\t\t\tdbt.Errorf(\"expected %v, got %v\", v1, o1)\n\t\t\t}\n\t\t\tif !bytes.Equal(v2, o2) {\n\t\t\t\tdbt.Errorf(\"expected %v, got %v\", v2, o2)\n\t\t\t}\n\t\t} else {\n\t\t\tdbt.Errorf(\"no data\")\n\t\t}\n\t})\n}\n\ntype testValuer struct {\n\tvalue string\n}\n\nfunc (tv testValuer) Value() (driver.Value, error) {\n\treturn tv.value, nil\n}\n\nfunc TestValuer(t *testing.T) {\n\trunTestsParallel(t, dsn, func(dbt *DBTest, tbl string) {\n\t\tin := testValuer{\"a_value\"}\n\t\tvar out string\n\t\tvar rows *sql.Rows\n\n\t\tdbt.mustExec(\"CREATE TABLE \" + tbl + \" (value VARCHAR(255)) CHARACTER SET utf8\")\n\t\tdbt.mustExec(\"INSERT INTO \"+tbl+\" VALUES (?)\", in)\n\t\trows = dbt.mustQuery(\"SELECT value FROM \" + tbl)\n\t\tif rows.Next() {\n\t\t\trows.Scan(&out)\n\t\t\tif in.value != out {\n\t\t\t\tdbt.Errorf(\"Valuer: %v != %s\", in, out)\n\t\t\t}\n\t\t} else {\n\t\t\tdbt.Errorf(\"Valuer: no data\")\n\t\t}\n\t\trows.Close()\n\t})\n}\n\ntype testValuerWithValidation struct {\n\tvalue string\n}\n\nfunc (tv testValuerWithValidation) Value() (driver.Value, error) {\n\tif len(tv.value) == 0 {\n\t\treturn nil, fmt.Errorf(\"Invalid string valuer. Value must not be empty\")\n\t}\n\n\treturn tv.value, nil\n}\n\nfunc TestValuerWithValidation(t *testing.T) {\n\trunTestsParallel(t, dsn, func(dbt *DBTest, tbl string) {\n\t\tin := testValuerWithValidation{\"a_value\"}\n\t\tvar out string\n\t\tvar rows *sql.Rows\n\n\t\tdbt.mustExec(\"CREATE TABLE \" + tbl + \" (value VARCHAR(255)) CHARACTER SET utf8\")\n\t\tdbt.mustExec(\"INSERT INTO \"+tbl+\" VALUES (?)\", in)\n\n\t\trows = dbt.mustQuery(\"SELECT value FROM \" + tbl)\n\t\tdefer rows.Close()\n\n\t\tif rows.Next() {\n\t\t\trows.Scan(&out)\n\t\t\tif in.value != out {\n\t\t\t\tdbt.Errorf(\"Valuer: %v != %s\", in, out)\n\t\t\t}\n\t\t} else {\n\t\t\tdbt.Errorf(\"Valuer: no data\")\n\t\t}\n\n\t\tif _, err := dbt.db.Exec(\"INSERT INTO \"+tbl+\" VALUES (?)\", testValuerWithValidation{\"\"}); err == nil {\n\t\t\tdbt.Errorf(\"Failed to check valuer error\")\n\t\t}\n\n\t\tif _, err := dbt.db.Exec(\"INSERT INTO \"+tbl+\" VALUES (?)\", nil); err != nil {\n\t\t\tdbt.Errorf(\"Failed to check nil\")\n\t\t}\n\n\t\tif _, err := dbt.db.Exec(\"INSERT INTO \"+tbl+\" VALUES (?)\", map[string]bool{}); err == nil {\n\t\t\tdbt.Errorf(\"Failed to check not valuer\")\n\t\t}\n\t})\n}\n\ntype timeTests struct {\n\tdbtype  string\n\ttlayout string\n\ttests   []timeTest\n}\n\ntype timeTest struct {\n\ts string // leading \"!\": do not use t as value in queries\n\tt time.Time\n}\n\ntype timeMode byte\n\nfunc (t timeMode) String() string {\n\tswitch t {\n\tcase binaryString:\n\t\treturn \"binary:string\"\n\tcase binaryTime:\n\t\treturn \"binary:time.Time\"\n\tcase textString:\n\t\treturn \"text:string\"\n\t}\n\tpanic(\"unsupported timeMode\")\n}\n\nfunc (t timeMode) Binary() bool {\n\tswitch t {\n\tcase binaryString, binaryTime:\n\t\treturn true\n\t}\n\treturn false\n}\n\nconst (\n\tbinaryString timeMode = iota\n\tbinaryTime\n\ttextString\n)\n\nfunc (t timeTest) genQuery(dbtype string, mode timeMode) string {\n\tvar inner string\n\tif mode.Binary() {\n\t\tinner = \"?\"\n\t} else {\n\t\tinner = `\"%s\"`\n\t}\n\treturn `SELECT cast(` + inner + ` as ` + dbtype + `)`\n}\n\nfunc (t timeTest) run(dbt *DBTest, dbtype, tlayout string, mode timeMode) {\n\tvar rows *sql.Rows\n\tquery := t.genQuery(dbtype, mode)\n\tswitch mode {\n\tcase binaryString:\n\t\trows = dbt.mustQuery(query, t.s)\n\tcase binaryTime:\n\t\trows = dbt.mustQuery(query, t.t)\n\tcase textString:\n\t\tquery = fmt.Sprintf(query, t.s)\n\t\trows = dbt.mustQuery(query)\n\tdefault:\n\t\tpanic(\"unsupported mode\")\n\t}\n\tdefer rows.Close()\n\tvar err error\n\tif !rows.Next() {\n\t\terr = rows.Err()\n\t\tif err == nil {\n\t\t\terr = fmt.Errorf(\"no data\")\n\t\t}\n\t\tdbt.Errorf(\"%s [%s]: %s\", dbtype, mode, err)\n\t\treturn\n\t}\n\tvar dst any\n\terr = rows.Scan(&dst)\n\tif err != nil {\n\t\tdbt.Errorf(\"%s [%s]: %s\", dbtype, mode, err)\n\t\treturn\n\t}\n\tswitch val := dst.(type) {\n\tcase []uint8:\n\t\tstr := string(val)\n\t\tif str == t.s {\n\t\t\treturn\n\t\t}\n\t\tif mode.Binary() && dbtype == \"DATETIME\" && len(str) == 26 && str[:19] == t.s {\n\t\t\t// a fix mainly for TravisCI:\n\t\t\t// accept full microsecond resolution in result for DATETIME columns\n\t\t\t// where the binary protocol was used\n\t\t\treturn\n\t\t}\n\t\tdbt.Errorf(\"%s [%s] to string: expected %q, got %q\",\n\t\t\tdbtype, mode,\n\t\t\tt.s, str,\n\t\t)\n\tcase time.Time:\n\t\tif val == t.t {\n\t\t\treturn\n\t\t}\n\t\tdbt.Errorf(\"%s [%s] to string: expected %q, got %q\",\n\t\t\tdbtype, mode,\n\t\t\tt.s, val.Format(tlayout),\n\t\t)\n\tdefault:\n\t\tfmt.Printf(\"%#v\\n\", []any{dbtype, tlayout, mode, t.s, t.t})\n\t\tdbt.Errorf(\"%s [%s]: unhandled type %T (is '%v')\",\n\t\t\tdbtype, mode,\n\t\t\tval, val,\n\t\t)\n\t}\n}\n\nfunc TestDateTime(t *testing.T) {\n\tafterTime := func(t time.Time, d string) time.Time {\n\t\tdur, err := time.ParseDuration(d)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn t.Add(dur)\n\t}\n\t// NOTE: MySQL rounds DATETIME(x) up - but that's not included in the tests\n\tformat := \"2006-01-02 15:04:05.999999\"\n\tt0 := time.Time{}\n\ttstr0 := \"0000-00-00 00:00:00.000000\"\n\ttestcases := []timeTests{\n\t\t{\"DATE\", format[:10], []timeTest{\n\t\t\t{t: time.Date(2011, 11, 20, 0, 0, 0, 0, time.UTC)},\n\t\t\t{t: t0, s: tstr0[:10]},\n\t\t}},\n\t\t{\"DATETIME\", format[:19], []timeTest{\n\t\t\t{t: time.Date(2011, 11, 20, 21, 27, 37, 0, time.UTC)},\n\t\t\t{t: t0, s: tstr0[:19]},\n\t\t}},\n\t\t{\"DATETIME(0)\", format[:21], []timeTest{\n\t\t\t{t: time.Date(2011, 11, 20, 21, 27, 37, 0, time.UTC)},\n\t\t\t{t: t0, s: tstr0[:19]},\n\t\t}},\n\t\t{\"DATETIME(1)\", format[:21], []timeTest{\n\t\t\t{t: time.Date(2011, 11, 20, 21, 27, 37, 100000000, time.UTC)},\n\t\t\t{t: t0, s: tstr0[:21]},\n\t\t}},\n\t\t{\"DATETIME(6)\", format, []timeTest{\n\t\t\t{t: time.Date(2011, 11, 20, 21, 27, 37, 123456000, time.UTC)},\n\t\t\t{t: t0, s: tstr0},\n\t\t}},\n\t\t{\"TIME\", format[11:19], []timeTest{\n\t\t\t{t: afterTime(t0, \"12345s\")},\n\t\t\t{s: \"!-12:34:56\"},\n\t\t\t{s: \"!-838:59:59\"},\n\t\t\t{s: \"!838:59:59\"},\n\t\t\t{t: t0, s: tstr0[11:19]},\n\t\t}},\n\t\t{\"TIME(0)\", format[11:19], []timeTest{\n\t\t\t{t: afterTime(t0, \"12345s\")},\n\t\t\t{s: \"!-12:34:56\"},\n\t\t\t{s: \"!-838:59:59\"},\n\t\t\t{s: \"!838:59:59\"},\n\t\t\t{t: t0, s: tstr0[11:19]},\n\t\t}},\n\t\t{\"TIME(1)\", format[11:21], []timeTest{\n\t\t\t{t: afterTime(t0, \"12345600ms\")},\n\t\t\t{s: \"!-12:34:56.7\"},\n\t\t\t{s: \"!-838:59:58.9\"},\n\t\t\t{s: \"!838:59:58.9\"},\n\t\t\t{t: t0, s: tstr0[11:21]},\n\t\t}},\n\t\t{\"TIME(6)\", format[11:], []timeTest{\n\t\t\t{t: afterTime(t0, \"1234567890123000ns\")},\n\t\t\t{s: \"!-12:34:56.789012\"},\n\t\t\t{s: \"!-838:59:58.999999\"},\n\t\t\t{s: \"!838:59:58.999999\"},\n\t\t\t{t: t0, s: tstr0[11:]},\n\t\t}},\n\t}\n\tdsns := []string{\n\t\tdsn + \"&parseTime=true\",\n\t\tdsn + \"&parseTime=false\",\n\t}\n\tfor _, testdsn := range dsns {\n\t\trunTests(t, testdsn, func(dbt *DBTest) {\n\t\t\tmicrosecsSupported := false\n\t\t\tzeroDateSupported := false\n\t\t\tvar rows *sql.Rows\n\t\t\tvar err error\n\t\t\trows, err = dbt.db.Query(`SELECT cast(\"00:00:00.1\" as TIME(1)) = \"00:00:00.1\"`)\n\t\t\tif err == nil {\n\t\t\t\tif rows.Next() {\n\t\t\t\t\trows.Scan(&microsecsSupported)\n\t\t\t\t}\n\t\t\t\trows.Close()\n\t\t\t}\n\t\t\trows, err = dbt.db.Query(`SELECT cast(\"0000-00-00\" as DATE) = \"0000-00-00\"`)\n\t\t\tif err == nil {\n\t\t\t\tif rows.Next() {\n\t\t\t\t\trows.Scan(&zeroDateSupported)\n\t\t\t\t}\n\t\t\t\trows.Close()\n\t\t\t}\n\t\t\tfor _, setups := range testcases {\n\t\t\t\tif t := setups.dbtype; !microsecsSupported && t[len(t)-1:] == \")\" {\n\t\t\t\t\t// skip fractional second tests if unsupported by server\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfor _, setup := range setups.tests {\n\t\t\t\t\tallowBinTime := true\n\t\t\t\t\tif setup.s == \"\" {\n\t\t\t\t\t\t// fill time string wherever Go can reliable produce it\n\t\t\t\t\t\tsetup.s = setup.t.Format(setups.tlayout)\n\t\t\t\t\t} else if setup.s[0] == '!' {\n\t\t\t\t\t\t// skip tests using setup.t as source in queries\n\t\t\t\t\t\tallowBinTime = false\n\t\t\t\t\t\t// fix setup.s - remove the \"!\"\n\t\t\t\t\t\tsetup.s = setup.s[1:]\n\t\t\t\t\t}\n\t\t\t\t\tif !zeroDateSupported && setup.s == tstr0[:len(setup.s)] {\n\t\t\t\t\t\t// skip disallowed 0000-00-00 date\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tsetup.run(dbt, setups.dbtype, setups.tlayout, textString)\n\t\t\t\t\tsetup.run(dbt, setups.dbtype, setups.tlayout, binaryString)\n\t\t\t\t\tif allowBinTime {\n\t\t\t\t\t\tsetup.run(dbt, setups.dbtype, setups.tlayout, binaryTime)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestTimestampMicros(t *testing.T) {\n\tformat := \"2006-01-02 15:04:05.999999\"\n\tf0 := format[:19]\n\tf1 := format[:21]\n\tf6 := format[:26]\n\trunTestsParallel(t, dsn, func(dbt *DBTest, tbl string) {\n\t\t// check if microseconds are supported.\n\t\t// Do not use timestamp(x) for that check - before 5.5.6, x would mean display width\n\t\t// and not precision.\n\t\t// Se last paragraph at http://dev.mysql.com/doc/refman/5.6/en/fractional-seconds.html\n\t\tmicrosecsSupported := false\n\t\tif rows, err := dbt.db.Query(`SELECT cast(\"00:00:00.1\" as TIME(1)) = \"00:00:00.1\"`); err == nil {\n\t\t\trows.Scan(&microsecsSupported)\n\t\t\trows.Close()\n\t\t}\n\t\tif !microsecsSupported {\n\t\t\t// skip test\n\t\t\treturn\n\t\t}\n\t\t_, err := dbt.db.Exec(`\n\t\t\tCREATE TABLE ` + tbl + ` (\n\t\t\t\tvalue0 TIMESTAMP NOT NULL DEFAULT '` + f0 + `',\n\t\t\t\tvalue1 TIMESTAMP(1) NOT NULL DEFAULT '` + f1 + `',\n\t\t\t\tvalue6 TIMESTAMP(6) NOT NULL DEFAULT '` + f6 + `'\n\t\t\t)`,\n\t\t)\n\t\tif err != nil {\n\t\t\tdbt.Error(err)\n\t\t}\n\t\tdefer dbt.mustExec(\"DROP TABLE IF EXISTS \" + tbl)\n\t\tdbt.mustExec(\"INSERT INTO \"+tbl+\" SET value0=?, value1=?, value6=?\", f0, f1, f6)\n\t\tvar res0, res1, res6 string\n\t\trows := dbt.mustQuery(\"SELECT * FROM \" + tbl)\n\t\tdefer rows.Close()\n\t\tif !rows.Next() {\n\t\t\tdbt.Errorf(\"test contained no selectable values\")\n\t\t}\n\t\terr = rows.Scan(&res0, &res1, &res6)\n\t\tif err != nil {\n\t\t\tdbt.Error(err)\n\t\t}\n\t\tif res0 != f0 {\n\t\t\tdbt.Errorf(\"expected %q, got %q\", f0, res0)\n\t\t}\n\t\tif res1 != f1 {\n\t\t\tdbt.Errorf(\"expected %q, got %q\", f1, res1)\n\t\t}\n\t\tif res6 != f6 {\n\t\t\tdbt.Errorf(\"expected %q, got %q\", f6, res6)\n\t\t}\n\t})\n}\n\nfunc TestNULL(t *testing.T) {\n\trunTestsParallel(t, dsn, func(dbt *DBTest, tbl string) {\n\t\tnullStmt, err := dbt.db.Prepare(\"SELECT NULL\")\n\t\tif err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tdefer nullStmt.Close()\n\n\t\tnonNullStmt, err := dbt.db.Prepare(\"SELECT 1\")\n\t\tif err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tdefer nonNullStmt.Close()\n\n\t\t// NullBool\n\t\tvar nb sql.NullBool\n\t\t// Invalid\n\t\tif err = nullStmt.QueryRow().Scan(&nb); err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tif nb.Valid {\n\t\t\tdbt.Error(\"valid NullBool which should be invalid\")\n\t\t}\n\t\t// Valid\n\t\tif err = nonNullStmt.QueryRow().Scan(&nb); err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tif !nb.Valid {\n\t\t\tdbt.Error(\"invalid NullBool which should be valid\")\n\t\t} else if nb.Bool != true {\n\t\t\tdbt.Errorf(\"Unexpected NullBool value: %t (should be true)\", nb.Bool)\n\t\t}\n\n\t\t// NullFloat64\n\t\tvar nf sql.NullFloat64\n\t\t// Invalid\n\t\tif err = nullStmt.QueryRow().Scan(&nf); err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tif nf.Valid {\n\t\t\tdbt.Error(\"valid NullFloat64 which should be invalid\")\n\t\t}\n\t\t// Valid\n\t\tif err = nonNullStmt.QueryRow().Scan(&nf); err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tif !nf.Valid {\n\t\t\tdbt.Error(\"invalid NullFloat64 which should be valid\")\n\t\t} else if nf.Float64 != float64(1) {\n\t\t\tdbt.Errorf(\"unexpected NullFloat64 value: %f (should be 1.0)\", nf.Float64)\n\t\t}\n\n\t\t// NullInt64\n\t\tvar ni sql.NullInt64\n\t\t// Invalid\n\t\tif err = nullStmt.QueryRow().Scan(&ni); err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tif ni.Valid {\n\t\t\tdbt.Error(\"valid NullInt64 which should be invalid\")\n\t\t}\n\t\t// Valid\n\t\tif err = nonNullStmt.QueryRow().Scan(&ni); err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tif !ni.Valid {\n\t\t\tdbt.Error(\"invalid NullInt64 which should be valid\")\n\t\t} else if ni.Int64 != int64(1) {\n\t\t\tdbt.Errorf(\"unexpected NullInt64 value: %d (should be 1)\", ni.Int64)\n\t\t}\n\n\t\t// NullString\n\t\tvar ns sql.NullString\n\t\t// Invalid\n\t\tif err = nullStmt.QueryRow().Scan(&ns); err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tif ns.Valid {\n\t\t\tdbt.Error(\"valid NullString which should be invalid\")\n\t\t}\n\t\t// Valid\n\t\tif err = nonNullStmt.QueryRow().Scan(&ns); err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tif !ns.Valid {\n\t\t\tdbt.Error(\"invalid NullString which should be valid\")\n\t\t} else if ns.String != `1` {\n\t\t\tdbt.Error(\"unexpected NullString value:\" + ns.String + \" (should be `1`)\")\n\t\t}\n\n\t\t// nil-bytes\n\t\tvar b []byte\n\t\t// Read nil\n\t\tif err = nullStmt.QueryRow().Scan(&b); err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tif b != nil {\n\t\t\tdbt.Error(\"non-nil []byte which should be nil\")\n\t\t}\n\t\t// Read non-nil\n\t\tif err = nonNullStmt.QueryRow().Scan(&b); err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tif b == nil {\n\t\t\tdbt.Error(\"nil []byte which should be non-nil\")\n\t\t}\n\t\t// Insert nil\n\t\tb = nil\n\t\tsuccess := false\n\t\tif err = dbt.db.QueryRow(\"SELECT ? IS NULL\", b).Scan(&success); err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tif !success {\n\t\t\tdbt.Error(\"inserting []byte(nil) as NULL failed\")\n\t\t}\n\t\t// Check input==output with input==nil\n\t\tb = nil\n\t\tif err = dbt.db.QueryRow(\"SELECT ?\", b).Scan(&b); err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tif b != nil {\n\t\t\tdbt.Error(\"non-nil echo from nil input\")\n\t\t}\n\t\t// Check input==output with input!=nil\n\t\tb = []byte(\"\")\n\t\tif err = dbt.db.QueryRow(\"SELECT ?\", b).Scan(&b); err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tif b == nil {\n\t\t\tdbt.Error(\"nil echo from non-nil input\")\n\t\t}\n\n\t\t// Insert NULL\n\t\tdbt.mustExec(\"CREATE TABLE \" + tbl + \" (dummmy1 int, value int, dummy2 int)\")\n\n\t\tdbt.mustExec(\"INSERT INTO \"+tbl+\" VALUES (?, ?, ?)\", 1, nil, 2)\n\n\t\tvar out any\n\t\trows := dbt.mustQuery(\"SELECT * FROM \" + tbl)\n\t\tdefer rows.Close()\n\t\tif rows.Next() {\n\t\t\trows.Scan(&out)\n\t\t\tif out != nil {\n\t\t\t\tdbt.Errorf(\"%v != nil\", out)\n\t\t\t}\n\t\t} else {\n\t\t\tdbt.Error(\"no data\")\n\t\t}\n\t})\n}\n\nfunc TestUint64(t *testing.T) {\n\tconst (\n\t\tu0    = uint64(0)\n\t\tuall  = ^u0\n\t\tuhigh = uall >> 1\n\t\tutop  = ^uhigh\n\t\ts0    = int64(0)\n\t\tsall  = ^s0\n\t\tshigh = int64(uhigh)\n\t\tstop  = ^shigh\n\t)\n\trunTestsParallel(t, dsn, func(dbt *DBTest, _ string) {\n\t\tstmt, err := dbt.db.Prepare(`SELECT ?, ?, ? ,?, ?, ?, ?, ?`)\n\t\tif err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tdefer stmt.Close()\n\t\trow := stmt.QueryRow(\n\t\t\tu0, uhigh, utop, uall,\n\t\t\ts0, shigh, stop, sall,\n\t\t)\n\n\t\tvar ua, ub, uc, ud uint64\n\t\tvar sa, sb, sc, sd int64\n\n\t\terr = row.Scan(&ua, &ub, &uc, &ud, &sa, &sb, &sc, &sd)\n\t\tif err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tswitch {\n\t\tcase ua != u0,\n\t\t\tub != uhigh,\n\t\t\tuc != utop,\n\t\t\tud != uall,\n\t\t\tsa != s0,\n\t\t\tsb != shigh,\n\t\t\tsc != stop,\n\t\t\tsd != sall:\n\t\t\tdbt.Fatal(\"unexpected result value\")\n\t\t}\n\t})\n}\n\nfunc TestLongData(t *testing.T) {\n\trunTests(t, dsn+\"&maxAllowedPacket=0\", func(dbt *DBTest) {\n\t\tvar maxAllowedPacketSize int\n\t\terr := dbt.db.QueryRow(\"select @@max_allowed_packet\").Scan(&maxAllowedPacketSize)\n\t\tif err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tmaxAllowedPacketSize--\n\n\t\t// don't get too ambitious\n\t\tif maxAllowedPacketSize > 1<<25 {\n\t\t\tmaxAllowedPacketSize = 1 << 25\n\t\t}\n\n\t\tdbt.mustExec(\"CREATE TABLE test (value LONGBLOB)\")\n\n\t\tin := strings.Repeat(`a`, maxAllowedPacketSize+1)\n\t\tvar out string\n\t\tvar rows *sql.Rows\n\n\t\t// Long text data\n\t\tinS := in[:maxAllowedPacketSize-100]\n\t\tdbt.mustExec(\"INSERT INTO test VALUES('\" + inS + \"')\")\n\t\trows = dbt.mustQuery(\"SELECT value FROM test\")\n\t\tdefer rows.Close()\n\t\tif rows.Next() {\n\t\t\trows.Scan(&out)\n\t\t\tif inS != out {\n\t\t\t\tdbt.Fatalf(\"LONGBLOB: length in: %d, length out: %d\", len(inS), len(out))\n\t\t\t}\n\t\t\tif rows.Next() {\n\t\t\t\tdbt.Error(\"LONGBLOB: unexpected row\")\n\t\t\t}\n\t\t} else {\n\t\t\tdbt.Fatalf(\"LONGBLOB: no data\")\n\t\t}\n\n\t\t// Empty table\n\t\tdbt.mustExec(\"TRUNCATE TABLE test\")\n\n\t\t// Long binary data\n\t\tdbt.mustExec(\"INSERT INTO test VALUES(?)\", in)\n\t\trows = dbt.mustQuery(\"SELECT value FROM test WHERE 1=?\", 1)\n\t\tdefer rows.Close()\n\t\tif rows.Next() {\n\t\t\trows.Scan(&out)\n\t\t\tif in != out {\n\t\t\t\tdbt.Fatalf(\"LONGBLOB: length in: %d, length out: %d\", len(in), len(out))\n\t\t\t}\n\t\t\tif rows.Next() {\n\t\t\t\tdbt.Error(\"LONGBLOB: unexpected row\")\n\t\t\t}\n\t\t} else {\n\t\t\tif err = rows.Err(); err != nil {\n\t\t\t\tdbt.Fatalf(\"LONGBLOB: no data (err: %s)\", err.Error())\n\t\t\t} else {\n\t\t\t\tdbt.Fatal(\"LONGBLOB: no data (err: <nil>)\")\n\t\t\t}\n\t\t}\n\t})\n}\n\nfunc TestLoadData(t *testing.T) {\n\trunTests(t, dsn, func(dbt *DBTest) {\n\t\tverifyLoadDataResult := func() {\n\t\t\trows, err := dbt.db.Query(\"SELECT * FROM test\")\n\t\t\tif err != nil {\n\t\t\t\tdbt.Fatal(err.Error())\n\t\t\t}\n\n\t\t\ti := 0\n\t\t\tvalues := [4]string{\n\t\t\t\t\"a string\",\n\t\t\t\t\"a string containing a \\t\",\n\t\t\t\t\"a string containing a \\n\",\n\t\t\t\t\"a string containing both \\t\\n\",\n\t\t\t}\n\n\t\t\tvar id int\n\t\t\tvar value string\n\n\t\t\tfor rows.Next() {\n\t\t\t\ti++\n\t\t\t\terr = rows.Scan(&id, &value)\n\t\t\t\tif err != nil {\n\t\t\t\t\tdbt.Fatal(err.Error())\n\t\t\t\t}\n\t\t\t\tif i != id {\n\t\t\t\t\tdbt.Fatalf(\"%d != %d\", i, id)\n\t\t\t\t}\n\t\t\t\tif values[i-1] != value {\n\t\t\t\t\tdbt.Fatalf(\"%q != %q\", values[i-1], value)\n\t\t\t\t}\n\t\t\t}\n\t\t\terr = rows.Err()\n\t\t\tif err != nil {\n\t\t\t\tdbt.Fatal(err.Error())\n\t\t\t}\n\n\t\t\tif i != 4 {\n\t\t\t\tdbt.Fatalf(\"rows count mismatch. Got %d, want 4\", i)\n\t\t\t}\n\t\t}\n\n\t\tdbt.db.Exec(\"DROP TABLE IF EXISTS test\")\n\t\tdbt.mustExec(\"CREATE TABLE test (id INT NOT NULL PRIMARY KEY, value TEXT NOT NULL) CHARACTER SET utf8\")\n\n\t\t// Local File\n\t\tfile, err := os.CreateTemp(\"\", \"gotest\")\n\t\tdefer os.Remove(file.Name())\n\t\tif err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tRegisterLocalFile(file.Name())\n\n\t\t// Try first with empty file\n\t\tdbt.mustExec(fmt.Sprintf(\"LOAD DATA LOCAL INFILE %q INTO TABLE test\", file.Name()))\n\t\tvar count int\n\t\terr = dbt.db.QueryRow(\"SELECT COUNT(*) FROM test\").Scan(&count)\n\t\tif err != nil {\n\t\t\tdbt.Fatal(err.Error())\n\t\t}\n\t\tif count != 0 {\n\t\t\tdbt.Fatalf(\"unexpected row count: got %d, want 0\", count)\n\t\t}\n\n\t\t// Then fill File with data and try to load it\n\t\tfile.WriteString(\"1\\ta string\\n2\\ta string containing a \\\\t\\n3\\ta string containing a \\\\n\\n4\\ta string containing both \\\\t\\\\n\\n\")\n\t\tfile.Close()\n\t\tdbt.mustExec(fmt.Sprintf(\"LOAD DATA LOCAL INFILE %q INTO TABLE test\", file.Name()))\n\t\tverifyLoadDataResult()\n\n\t\t// Try with non-existing file\n\t\t_, err = dbt.db.Exec(\"LOAD DATA LOCAL INFILE 'doesnotexist' INTO TABLE test\")\n\t\tif err == nil {\n\t\t\tdbt.Fatal(\"load non-existent file didn't fail\")\n\t\t} else if err.Error() != \"local file 'doesnotexist' is not registered\" {\n\t\t\tdbt.Fatal(err.Error())\n\t\t}\n\n\t\t// Empty table\n\t\tdbt.mustExec(\"TRUNCATE TABLE test\")\n\n\t\t// Reader\n\t\tRegisterReaderHandler(\"test\", func() io.Reader {\n\t\t\tfile, err = os.Open(file.Name())\n\t\t\tif err != nil {\n\t\t\t\tdbt.Fatal(err)\n\t\t\t}\n\t\t\treturn file\n\t\t})\n\t\tdbt.mustExec(\"LOAD DATA LOCAL INFILE 'Reader::test' INTO TABLE test\")\n\t\tverifyLoadDataResult()\n\t\t// negative test\n\t\t_, err = dbt.db.Exec(\"LOAD DATA LOCAL INFILE 'Reader::doesnotexist' INTO TABLE test\")\n\t\tif err == nil {\n\t\t\tdbt.Fatal(\"load non-existent Reader didn't fail\")\n\t\t} else if err.Error() != \"reader 'doesnotexist' is not registered\" {\n\t\t\tdbt.Fatal(err.Error())\n\t\t}\n\t})\n}\n\nfunc TestFoundRows1(t *testing.T) {\n\trunTestsParallel(t, dsn, func(dbt *DBTest, tbl string) {\n\t\tdbt.mustExec(\"CREATE TABLE \" + tbl + \" (id INT NOT NULL ,data INT NOT NULL)\")\n\t\tdbt.mustExec(\"INSERT INTO \" + tbl + \" (id, data) VALUES (0, 0),(0, 0),(1, 0),(1, 0),(1, 1)\")\n\n\t\tres := dbt.mustExec(\"UPDATE \" + tbl + \" SET data = 1 WHERE id = 0\")\n\t\tcount, err := res.RowsAffected()\n\t\tif err != nil {\n\t\t\tdbt.Fatalf(\"res.RowsAffected() returned error: %s\", err.Error())\n\t\t}\n\t\tif count != 2 {\n\t\t\tdbt.Fatalf(\"Expected 2 affected rows, got %d\", count)\n\t\t}\n\t\tres = dbt.mustExec(\"UPDATE \" + tbl + \" SET data = 1 WHERE id = 1\")\n\t\tcount, err = res.RowsAffected()\n\t\tif err != nil {\n\t\t\tdbt.Fatalf(\"res.RowsAffected() returned error: %s\", err.Error())\n\t\t}\n\t\tif count != 2 {\n\t\t\tdbt.Fatalf(\"Expected 2 affected rows, got %d\", count)\n\t\t}\n\t})\n}\n\nfunc TestFoundRows2(t *testing.T) {\n\trunTestsParallel(t, dsn+\"&clientFoundRows=true\", func(dbt *DBTest, tbl string) {\n\t\tdbt.mustExec(\"CREATE TABLE \" + tbl + \" (id INT NOT NULL ,data INT NOT NULL)\")\n\t\tdbt.mustExec(\"INSERT INTO \" + tbl + \" (id, data) VALUES (0, 0),(0, 0),(1, 0),(1, 0),(1, 1)\")\n\n\t\tres := dbt.mustExec(\"UPDATE \" + tbl + \" SET data = 1 WHERE id = 0\")\n\t\tcount, err := res.RowsAffected()\n\t\tif err != nil {\n\t\t\tdbt.Fatalf(\"res.RowsAffected() returned error: %s\", err.Error())\n\t\t}\n\t\tif count != 2 {\n\t\t\tdbt.Fatalf(\"Expected 2 matched rows, got %d\", count)\n\t\t}\n\t\tres = dbt.mustExec(\"UPDATE \" + tbl + \" SET data = 1 WHERE id = 1\")\n\t\tcount, err = res.RowsAffected()\n\t\tif err != nil {\n\t\t\tdbt.Fatalf(\"res.RowsAffected() returned error: %s\", err.Error())\n\t\t}\n\t\tif count != 3 {\n\t\t\tdbt.Fatalf(\"Expected 3 matched rows, got %d\", count)\n\t\t}\n\t})\n}\n\nfunc TestTLS(t *testing.T) {\n\ttlsTestReq := func(dbt *DBTest) {\n\t\tif err := dbt.db.Ping(); err != nil {\n\t\t\tif err == ErrNoTLS {\n\t\t\t\tdbt.Skip(\"server does not support TLS\")\n\t\t\t} else {\n\t\t\t\tdbt.Fatalf(\"error on Ping: %s\", err.Error())\n\t\t\t}\n\t\t}\n\n\t\trows := dbt.mustQuery(\"SHOW STATUS LIKE 'Ssl_cipher'\")\n\t\tdefer rows.Close()\n\n\t\tvar variable, value *sql.RawBytes\n\t\tfor rows.Next() {\n\t\t\tif err := rows.Scan(&variable, &value); err != nil {\n\t\t\t\tdbt.Fatal(err.Error())\n\t\t\t}\n\n\t\t\tif (*value == nil) || (len(*value) == 0) {\n\t\t\t\tdbt.Fatalf(\"no Cipher\")\n\t\t\t} else {\n\t\t\t\tdbt.Logf(\"Cipher: %s\", *value)\n\t\t\t}\n\t\t}\n\t}\n\ttlsTestOpt := func(dbt *DBTest) {\n\t\tif err := dbt.db.Ping(); err != nil {\n\t\t\tdbt.Fatalf(\"error on Ping: %s\", err.Error())\n\t\t}\n\t}\n\n\trunTests(t, dsn+\"&tls=preferred\", tlsTestOpt)\n\trunTests(t, dsn+\"&tls=skip-verify\", tlsTestReq)\n\n\t// Verify that registering / using a custom cfg works\n\tRegisterTLSConfig(\"custom-skip-verify\", &tls.Config{\n\t\tInsecureSkipVerify: true,\n\t})\n\trunTests(t, dsn+\"&tls=custom-skip-verify\", tlsTestReq)\n}\n\nfunc TestReuseClosedConnection(t *testing.T) {\n\t// this test does not use sql.database, it uses the driver directly\n\tif !available {\n\t\tt.Skipf(\"MySQL server not running on %s\", netAddr)\n\t}\n\n\tmd := &MySQLDriver{}\n\tconn, err := md.Open(dsn)\n\tif err != nil {\n\t\tt.Fatalf(\"error connecting: %s\", err.Error())\n\t}\n\tstmt, err := conn.Prepare(\"DO 1\")\n\tif err != nil {\n\t\tt.Fatalf(\"error preparing statement: %s\", err.Error())\n\t}\n\t//lint:ignore SA1019 this is a test\n\t_, err = stmt.Exec(nil)\n\tif err != nil {\n\t\tt.Fatalf(\"error executing statement: %s\", err.Error())\n\t}\n\terr = conn.Close()\n\tif err != nil {\n\t\tt.Fatalf(\"error closing connection: %s\", err.Error())\n\t}\n\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\tt.Errorf(\"panic after reusing a closed connection: %v\", err)\n\t\t}\n\t}()\n\t//lint:ignore SA1019 this is a test\n\t_, err = stmt.Exec(nil)\n\tif err != nil && err != driver.ErrBadConn {\n\t\tt.Errorf(\"unexpected error '%s', expected '%s'\",\n\t\t\terr.Error(), driver.ErrBadConn.Error())\n\t}\n}\n\nfunc TestCharset(t *testing.T) {\n\tif !available {\n\t\tt.Skipf(\"MySQL server not running on %s\", netAddr)\n\t}\n\n\tmustSetCharset := func(charsetParam, expected string) {\n\t\trunTests(t, dsn+\"&\"+charsetParam, func(dbt *DBTest) {\n\t\t\trows := dbt.mustQuery(\"SELECT @@character_set_connection\")\n\t\t\tdefer rows.Close()\n\n\t\t\tif !rows.Next() {\n\t\t\t\tdbt.Fatalf(\"error getting connection charset: %s\", rows.Err())\n\t\t\t}\n\n\t\t\tvar got string\n\t\t\trows.Scan(&got)\n\n\t\t\tif got != expected {\n\t\t\t\tdbt.Fatalf(\"expected connection charset %s but got %s\", expected, got)\n\t\t\t}\n\t\t})\n\t}\n\n\t// non utf8 test\n\tmustSetCharset(\"charset=ascii\", \"ascii\")\n\n\t// when the first charset is invalid, use the second\n\tmustSetCharset(\"charset=none,utf8mb4\", \"utf8mb4\")\n\n\t// when the first charset is valid, use it\n\tmustSetCharset(\"charset=ascii,utf8mb4\", \"ascii\")\n\tmustSetCharset(\"charset=utf8mb4,ascii\", \"utf8mb4\")\n}\n\nfunc TestFailingCharset(t *testing.T) {\n\trunTestsParallel(t, dsn+\"&charset=none\", func(dbt *DBTest, _ string) {\n\t\t// run query to really establish connection...\n\t\t_, err := dbt.db.Exec(\"SELECT 1\")\n\t\tif err == nil {\n\t\t\tdbt.db.Close()\n\t\t\tt.Fatalf(\"connection must not succeed without a valid charset\")\n\t\t}\n\t})\n}\n\nfunc TestCollation(t *testing.T) {\n\tif !available {\n\t\tt.Skipf(\"MySQL server not running on %s\", netAddr)\n\t}\n\n\t// MariaDB may override collation specified by handshake with `character_set_collations` variable.\n\t// https://mariadb.com/kb/en/setting-character-sets-and-collations/#changing-default-collation\n\t// https://mariadb.com/kb/en/server-system-variables/#character_set_collations\n\t// utf8mb4_general_ci, utf8mb3_general_ci will be overridden by default MariaDB.\n\t// Collations other than charasets default are not overridden. So utf8mb4_unicode_ci is safe.\n\ttestCollations := []string{\n\t\t\"latin1_general_ci\",\n\t\t\"binary\",\n\t\t\"utf8mb4_unicode_ci\",\n\t\t\"cp1257_bin\",\n\t}\n\n\tfor _, collation := range testCollations {\n\t\tt.Run(collation, func(t *testing.T) {\n\t\t\ttdsn := dsn + \"&collation=\" + collation\n\t\t\texpected := collation\n\n\t\t\trunTests(t, tdsn, func(dbt *DBTest) {\n\t\t\t\tvar got string\n\t\t\t\tif err := dbt.db.QueryRow(\"SELECT @@collation_connection\").Scan(&got); err != nil {\n\t\t\t\t\tdbt.Fatal(err)\n\t\t\t\t}\n\t\t\t\tif got != expected {\n\t\t\t\t\tdbt.Fatalf(\"expected connection collation %s but got %s\", expected, got)\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\t}\n}\n\nfunc TestColumnsWithAlias(t *testing.T) {\n\trunTestsParallel(t, dsn+\"&columnsWithAlias=true\", func(dbt *DBTest, _ string) {\n\t\trows := dbt.mustQuery(\"SELECT 1 AS A\")\n\t\tdefer rows.Close()\n\t\tcols, _ := rows.Columns()\n\t\tif len(cols) != 1 {\n\t\t\tt.Fatalf(\"expected 1 column, got %d\", len(cols))\n\t\t}\n\t\tif cols[0] != \"A\" {\n\t\t\tt.Fatalf(\"expected column name \\\"A\\\", got \\\"%s\\\"\", cols[0])\n\t\t}\n\n\t\trows = dbt.mustQuery(\"SELECT * FROM (SELECT 1 AS one) AS A\")\n\t\tdefer rows.Close()\n\t\tcols, _ = rows.Columns()\n\t\tif len(cols) != 1 {\n\t\t\tt.Fatalf(\"expected 1 column, got %d\", len(cols))\n\t\t}\n\t\tif cols[0] != \"A.one\" {\n\t\t\tt.Fatalf(\"expected column name \\\"A.one\\\", got \\\"%s\\\"\", cols[0])\n\t\t}\n\t})\n}\n\nfunc TestRawBytesResultExceedsBuffer(t *testing.T) {\n\trunTestsParallel(t, dsn, func(dbt *DBTest, _ string) {\n\t\t// defaultBufSize from buffer.go\n\t\texpected := strings.Repeat(\"abc\", defaultBufSize)\n\n\t\trows := dbt.mustQuery(\"SELECT '\" + expected + \"'\")\n\t\tdefer rows.Close()\n\t\tif !rows.Next() {\n\t\t\tdbt.Error(\"expected result, got none\")\n\t\t}\n\t\tvar result sql.RawBytes\n\t\trows.Scan(&result)\n\t\tif expected != string(result) {\n\t\t\tdbt.Error(\"result did not match expected value\")\n\t\t}\n\t})\n}\n\nfunc TestTimezoneConversion(t *testing.T) {\n\tzones := []string{\"UTC\", \"America/New_York\", \"Asia/Hong_Kong\", \"Local\"}\n\n\t// Regression test for timezone handling\n\ttzTest := func(dbt *DBTest) {\n\t\t// Create table\n\t\tdbt.mustExec(\"CREATE TABLE test (ts TIMESTAMP)\")\n\n\t\t// Insert local time into database (should be converted)\n\t\tnewYorkTz, _ := time.LoadLocation(\"America/New_York\")\n\t\treftime := time.Date(2014, 05, 30, 18, 03, 17, 0, time.UTC).In(newYorkTz)\n\t\tdbt.mustExec(\"INSERT INTO test VALUE (?)\", reftime)\n\n\t\t// Retrieve time from DB\n\t\trows := dbt.mustQuery(\"SELECT ts FROM test\")\n\t\tdefer rows.Close()\n\t\tif !rows.Next() {\n\t\t\tdbt.Fatal(\"did not get any rows out\")\n\t\t}\n\n\t\tvar dbTime time.Time\n\t\terr := rows.Scan(&dbTime)\n\t\tif err != nil {\n\t\t\tdbt.Fatal(\"Err\", err)\n\t\t}\n\n\t\t// Check that dates match\n\t\tif reftime.Unix() != dbTime.Unix() {\n\t\t\tdbt.Errorf(\"times do not match.\\n\")\n\t\t\tdbt.Errorf(\" Now(%v)=%v\\n\", newYorkTz, reftime)\n\t\t\tdbt.Errorf(\" Now(UTC)=%v\\n\", dbTime)\n\t\t}\n\t}\n\n\tfor _, tz := range zones {\n\t\trunTests(t, dsn+\"&parseTime=true&loc=\"+url.QueryEscape(tz), tzTest)\n\t}\n}\n\n// Special cases\n\nfunc TestRowsClose(t *testing.T) {\n\trunTestsParallel(t, dsn, func(dbt *DBTest, _ string) {\n\t\trows, err := dbt.db.Query(\"SELECT 1\")\n\t\tif err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\n\t\terr = rows.Close()\n\t\tif err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\n\t\tif rows.Next() {\n\t\t\tdbt.Fatal(\"unexpected row after rows.Close()\")\n\t\t}\n\n\t\terr = rows.Err()\n\t\tif err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t})\n}\n\n// dangling statements\n// http://code.google.com/p/go/issues/detail?id=3865\nfunc TestCloseStmtBeforeRows(t *testing.T) {\n\trunTestsParallel(t, dsn, func(dbt *DBTest, _ string) {\n\t\tstmt, err := dbt.db.Prepare(\"SELECT 1\")\n\t\tif err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\n\t\trows, err := stmt.Query()\n\t\tif err != nil {\n\t\t\tstmt.Close()\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tdefer rows.Close()\n\n\t\terr = stmt.Close()\n\t\tif err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\n\t\tif !rows.Next() {\n\t\t\tdbt.Fatal(\"getting row failed\")\n\t\t} else {\n\t\t\terr = rows.Err()\n\t\t\tif err != nil {\n\t\t\t\tdbt.Fatal(err)\n\t\t\t}\n\n\t\t\tvar out bool\n\t\t\terr = rows.Scan(&out)\n\t\t\tif err != nil {\n\t\t\t\tdbt.Fatalf(\"error on rows.Scan(): %s\", err.Error())\n\t\t\t}\n\t\t\tif out != true {\n\t\t\t\tdbt.Errorf(\"true != %t\", out)\n\t\t\t}\n\t\t}\n\t})\n}\n\n// It is valid to have multiple Rows for the same Stmt\n// http://code.google.com/p/go/issues/detail?id=3734\nfunc TestStmtMultiRows(t *testing.T) {\n\trunTestsParallel(t, dsn, func(dbt *DBTest, _ string) {\n\t\tstmt, err := dbt.db.Prepare(\"SELECT 1 UNION SELECT 0\")\n\t\tif err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\n\t\trows1, err := stmt.Query()\n\t\tif err != nil {\n\t\t\tstmt.Close()\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tdefer rows1.Close()\n\n\t\trows2, err := stmt.Query()\n\t\tif err != nil {\n\t\t\tstmt.Close()\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tdefer rows2.Close()\n\n\t\tvar out bool\n\n\t\t// 1\n\t\tif !rows1.Next() {\n\t\t\tdbt.Fatal(\"first rows1.Next failed\")\n\t\t} else {\n\t\t\terr = rows1.Err()\n\t\t\tif err != nil {\n\t\t\t\tdbt.Fatal(err)\n\t\t\t}\n\n\t\t\terr = rows1.Scan(&out)\n\t\t\tif err != nil {\n\t\t\t\tdbt.Fatalf(\"error on rows.Scan(): %s\", err.Error())\n\t\t\t}\n\t\t\tif out != true {\n\t\t\t\tdbt.Errorf(\"true != %t\", out)\n\t\t\t}\n\t\t}\n\n\t\tif !rows2.Next() {\n\t\t\tdbt.Fatal(\"first rows2.Next failed\")\n\t\t} else {\n\t\t\terr = rows2.Err()\n\t\t\tif err != nil {\n\t\t\t\tdbt.Fatal(err)\n\t\t\t}\n\n\t\t\terr = rows2.Scan(&out)\n\t\t\tif err != nil {\n\t\t\t\tdbt.Fatalf(\"error on rows.Scan(): %s\", err.Error())\n\t\t\t}\n\t\t\tif out != true {\n\t\t\t\tdbt.Errorf(\"true != %t\", out)\n\t\t\t}\n\t\t}\n\n\t\t// 2\n\t\tif !rows1.Next() {\n\t\t\tdbt.Fatal(\"second rows1.Next failed\")\n\t\t} else {\n\t\t\terr = rows1.Err()\n\t\t\tif err != nil {\n\t\t\t\tdbt.Fatal(err)\n\t\t\t}\n\n\t\t\terr = rows1.Scan(&out)\n\t\t\tif err != nil {\n\t\t\t\tdbt.Fatalf(\"error on rows.Scan(): %s\", err.Error())\n\t\t\t}\n\t\t\tif out != false {\n\t\t\t\tdbt.Errorf(\"false != %t\", out)\n\t\t\t}\n\n\t\t\tif rows1.Next() {\n\t\t\t\tdbt.Fatal(\"unexpected row on rows1\")\n\t\t\t}\n\t\t\terr = rows1.Close()\n\t\t\tif err != nil {\n\t\t\t\tdbt.Fatal(err)\n\t\t\t}\n\t\t}\n\n\t\tif !rows2.Next() {\n\t\t\tdbt.Fatal(\"second rows2.Next failed\")\n\t\t} else {\n\t\t\terr = rows2.Err()\n\t\t\tif err != nil {\n\t\t\t\tdbt.Fatal(err)\n\t\t\t}\n\n\t\t\terr = rows2.Scan(&out)\n\t\t\tif err != nil {\n\t\t\t\tdbt.Fatalf(\"error on rows.Scan(): %s\", err.Error())\n\t\t\t}\n\t\t\tif out != false {\n\t\t\t\tdbt.Errorf(\"false != %t\", out)\n\t\t\t}\n\n\t\t\tif rows2.Next() {\n\t\t\t\tdbt.Fatal(\"unexpected row on rows2\")\n\t\t\t}\n\t\t\terr = rows2.Close()\n\t\t\tif err != nil {\n\t\t\t\tdbt.Fatal(err)\n\t\t\t}\n\t\t}\n\t})\n}\n\n// Regression test for\n// * more than 32 NULL parameters (issue 209)\n// * more parameters than fit into the buffer (issue 201)\n// * parameters * 64 > max_allowed_packet (issue 734)\nfunc TestPreparedManyCols(t *testing.T) {\n\tnumParams := 65535\n\trunTests(t, dsn, func(dbt *DBTest) {\n\t\tquery := \"SELECT ?\" + strings.Repeat(\",?\", numParams-1)\n\t\tstmt, err := dbt.db.Prepare(query)\n\t\tif err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tdefer stmt.Close()\n\n\t\t// create more parameters than fit into the buffer\n\t\t// which will take nil-values\n\t\tparams := make([]any, numParams)\n\t\trows, err := stmt.Query(params...)\n\t\tif err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\trows.Close()\n\n\t\t// Create 0byte string which we can't send via STMT_LONG_DATA.\n\t\tfor i := range numParams {\n\t\t\tparams[i] = \"\"\n\t\t}\n\t\trows, err = stmt.Query(params...)\n\t\tif err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\trows.Close()\n\t})\n}\n\nfunc TestConcurrent(t *testing.T) {\n\tif enabled, _ := readBool(os.Getenv(\"MYSQL_TEST_CONCURRENT\")); !enabled {\n\t\tt.Skip(\"MYSQL_TEST_CONCURRENT env var not set\")\n\t}\n\n\trunTests(t, dsn, func(dbt *DBTest) {\n\t\t// var version string\n\t\t// if err := dbt.db.QueryRow(\"SELECT @@version\").Scan(&version); err != nil {\n\t\t// \tdbt.Fatal(err)\n\t\t// }\n\t\t// if strings.Contains(strings.ToLower(version), \"mariadb\") {\n\t\t// \tt.Skip(`TODO: \"fix commands out of sync. Did you run multiple statements at once?\" on MariaDB`)\n\t\t// }\n\n\t\tvar max int\n\t\terr := dbt.db.QueryRow(\"SELECT @@max_connections\").Scan(&max)\n\t\tif err != nil {\n\t\t\tdbt.Fatalf(\"%s\", err.Error())\n\t\t}\n\t\tdbt.Logf(\"testing up to %d concurrent connections \\r\\n\", max)\n\n\t\tvar remaining, succeeded int32 = int32(max), 0\n\n\t\tvar wg sync.WaitGroup\n\t\twg.Add(max)\n\n\t\tvar fatalError string\n\t\tvar once sync.Once\n\t\tfatalf := func(s string, vals ...any) {\n\t\t\tonce.Do(func() {\n\t\t\t\tfatalError = fmt.Sprintf(s, vals...)\n\t\t\t})\n\t\t}\n\n\t\tfor i := range max {\n\t\t\tgo func(id int) {\n\t\t\t\tdefer wg.Done()\n\n\t\t\t\ttx, err := dbt.db.Begin()\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tif err.Error() != \"Error 1040: Too many connections\" {\n\t\t\t\t\t\tfatalf(\"error on conn %d: %s\", id, err.Error())\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// keep the connection busy until all connections are open\n\t\t\t\tfor atomic.AddInt32(&remaining, -1) > 0 {\n\t\t\t\t\tif _, err = tx.Exec(\"DO 1\"); err != nil {\n\t\t\t\t\t\tfatalf(\"error on conn %d: %s\", id, err.Error())\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif err = tx.Commit(); err != nil {\n\t\t\t\t\tfatalf(\"error on conn %d: %s\", id, err.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// everything went fine with this connection\n\t\t\t\tatomic.AddInt32(&succeeded, 1)\n\t\t\t}(i)\n\t\t}\n\n\t\t// wait until all connections are open\n\t\twg.Wait()\n\n\t\tif fatalError != \"\" {\n\t\t\tdbt.Fatal(fatalError)\n\t\t}\n\n\t\tdbt.Logf(\"reached %d concurrent connections\\r\\n\", succeeded)\n\t})\n}\n\nfunc testDialError(t *testing.T, dialErr error, expectErr error) {\n\tRegisterDialContext(\"mydial\", func(ctx context.Context, addr string) (net.Conn, error) {\n\t\treturn nil, dialErr\n\t})\n\n\tdb, err := sql.Open(driverNameTest, fmt.Sprintf(\"%s:%s@mydial(%s)/%s?timeout=30s\", user, pass, addr, dbname))\n\tif err != nil {\n\t\tt.Fatalf(\"error connecting: %s\", err.Error())\n\t}\n\tdefer db.Close()\n\n\t_, err = db.Exec(\"DO 1\")\n\tif err != expectErr {\n\t\tt.Fatalf(\"was expecting %s. Got: %s\", dialErr, err)\n\t}\n}\n\nfunc TestDialUnknownError(t *testing.T) {\n\ttestErr := fmt.Errorf(\"test\")\n\ttestDialError(t, testErr, testErr)\n}\n\nfunc TestDialNonRetryableNetErr(t *testing.T) {\n\ttestErr := netErrorMock{}\n\ttestDialError(t, testErr, testErr)\n}\n\nfunc TestDialTemporaryNetErr(t *testing.T) {\n\ttestErr := netErrorMock{temporary: true}\n\ttestDialError(t, testErr, testErr)\n}\n\n// Tests custom dial functions\nfunc TestCustomDial(t *testing.T) {\n\tif !available {\n\t\tt.Skipf(\"MySQL server not running on %s\", netAddr)\n\t}\n\n\t// our custom dial function which just wraps net.Dial here\n\tRegisterDialContext(\"mydial\", func(ctx context.Context, addr string) (net.Conn, error) {\n\t\tvar d net.Dialer\n\t\treturn d.DialContext(ctx, prot, addr)\n\t})\n\n\tdb, err := sql.Open(driverNameTest, fmt.Sprintf(\"%s:%s@mydial(%s)/%s?timeout=30s\", user, pass, addr, dbname))\n\tif err != nil {\n\t\tt.Fatalf(\"error connecting: %s\", err.Error())\n\t}\n\tdefer db.Close()\n\n\tif _, err = db.Exec(\"DO 1\"); err != nil {\n\t\tt.Fatalf(\"connection failed: %s\", err.Error())\n\t}\n}\n\nfunc TestBeforeConnect(t *testing.T) {\n\tif !available {\n\t\tt.Skipf(\"MySQL server not running on %s\", netAddr)\n\t}\n\n\t// dbname is set in the BeforeConnect handle\n\tcfg, err := ParseDSN(fmt.Sprintf(\"%s:%s@%s/%s?timeout=30s\", user, pass, netAddr, \"_\"))\n\tif err != nil {\n\t\tt.Fatalf(\"error parsing DSN: %v\", err)\n\t}\n\n\tcfg.Apply(BeforeConnect(func(ctx context.Context, c *Config) error {\n\t\tc.DBName = dbname\n\t\treturn nil\n\t}))\n\n\tconnector, err := NewConnector(cfg)\n\tif err != nil {\n\t\tt.Fatalf(\"error creating connector: %v\", err)\n\t}\n\n\tdb := sql.OpenDB(connector)\n\tdefer db.Close()\n\n\tvar connectedDb string\n\terr = db.QueryRow(\"SELECT DATABASE();\").Scan(&connectedDb)\n\tif err != nil {\n\t\tt.Fatalf(\"error executing query: %v\", err)\n\t}\n\tif connectedDb != dbname {\n\t\tt.Fatalf(\"expected to connect to DB %s, but connected to %s instead\", dbname, connectedDb)\n\t}\n}\n\nfunc TestSQLInjection(t *testing.T) {\n\tcreateTest := func(arg string) func(dbt *DBTest) {\n\t\treturn func(dbt *DBTest) {\n\t\t\tdbt.mustExec(\"CREATE TABLE test (v INTEGER)\")\n\t\t\tdbt.mustExec(\"INSERT INTO test VALUES (?)\", 1)\n\n\t\t\tvar v int\n\t\t\t// NULL can't be equal to anything, the idea here is to inject query so it returns row\n\t\t\t// This test verifies that escapeQuotes and escapeBackslash are working properly\n\t\t\terr := dbt.db.QueryRow(\"SELECT v FROM test WHERE NULL = ?\", arg).Scan(&v)\n\t\t\tif err == sql.ErrNoRows {\n\t\t\t\treturn // success, sql injection failed\n\t\t\t} else if err == nil {\n\t\t\t\tdbt.Errorf(\"sql injection successful with arg: %s\", arg)\n\t\t\t} else {\n\t\t\t\tdbt.Errorf(\"error running query with arg: %s; err: %s\", arg, err.Error())\n\t\t\t}\n\t\t}\n\t}\n\n\tdsns := []string{\n\t\tdsn,\n\t\tdsn + \"&sql_mode='NO_BACKSLASH_ESCAPES'\",\n\t}\n\tfor _, testdsn := range dsns {\n\t\trunTests(t, testdsn, createTest(\"1 OR 1=1\"))\n\t\trunTests(t, testdsn, createTest(\"' OR '1'='1\"))\n\t}\n}\n\n// Test if inserted data is correctly retrieved after being escaped\nfunc TestInsertRetrieveEscapedData(t *testing.T) {\n\ttestData := func(dbt *DBTest) {\n\t\tdbt.mustExec(\"CREATE TABLE test (v VARCHAR(255))\")\n\n\t\t// All sequences that are escaped by escapeQuotes and escapeBackslash\n\t\tv := \"foo \\x00\\n\\r\\x1a\\\"'\\\\\"\n\t\tdbt.mustExec(\"INSERT INTO test VALUES (?)\", v)\n\n\t\tvar out string\n\t\terr := dbt.db.QueryRow(\"SELECT v FROM test\").Scan(&out)\n\t\tif err != nil {\n\t\t\tdbt.Fatalf(\"%s\", err.Error())\n\t\t}\n\n\t\tif out != v {\n\t\t\tdbt.Errorf(\"%q != %q\", out, v)\n\t\t}\n\t}\n\n\tdsns := []string{\n\t\tdsn,\n\t\tdsn + \"&sql_mode='NO_BACKSLASH_ESCAPES'\",\n\t}\n\tfor _, testdsn := range dsns {\n\t\trunTests(t, testdsn, testData)\n\t}\n}\n\nfunc TestUnixSocketAuthFail(t *testing.T) {\n\trunTests(t, dsn, func(dbt *DBTest) {\n\t\t// Save the current logger so we can restore it.\n\t\toldLogger := defaultLogger\n\n\t\t// Set a new logger so we can capture its output.\n\t\tbuffer := bytes.NewBuffer(make([]byte, 0, 64))\n\t\tnewLogger := log.New(buffer, \"prefix: \", 0)\n\t\tSetLogger(newLogger)\n\n\t\t// Restore the logger.\n\t\tdefer SetLogger(oldLogger)\n\n\t\t// Make a new DSN that uses the MySQL socket file and a bad password, which\n\t\t// we can make by simply appending any character to the real password.\n\t\tbadPass := pass + \"x\"\n\t\tsocket := \"\"\n\t\tif prot == \"unix\" {\n\t\t\tsocket = addr\n\t\t} else {\n\t\t\t// Get socket file from MySQL.\n\t\t\terr := dbt.db.QueryRow(\"SELECT @@socket\").Scan(&socket)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"error on SELECT @@socket: %s\", err.Error())\n\t\t\t}\n\t\t}\n\t\tt.Logf(\"socket: %s\", socket)\n\t\tbadDSN := fmt.Sprintf(\"%s:%s@unix(%s)/%s?timeout=30s\", user, badPass, socket, dbname)\n\t\tdb, err := sql.Open(driverNameTest, badDSN)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"error connecting: %s\", err.Error())\n\t\t}\n\t\tdefer db.Close()\n\n\t\t// Connect to MySQL for real. This will cause an auth failure.\n\t\terr = db.Ping()\n\t\tif err == nil {\n\t\t\tt.Error(\"expected Ping() to return an error\")\n\t\t}\n\n\t\t// The driver should not log anything.\n\t\tif actual := buffer.String(); actual != \"\" {\n\t\t\tt.Errorf(\"expected no output, got %q\", actual)\n\t\t}\n\t})\n}\n\n// See Issue #422\nfunc TestInterruptBySignal(t *testing.T) {\n\trunTestsWithMultiStatement(t, dsn, func(dbt *DBTest) {\n\t\tdbt.mustExec(`\n\t\t\tDROP PROCEDURE IF EXISTS test_signal;\n\t\t\tCREATE PROCEDURE test_signal(ret INT)\n\t\t\tBEGIN\n\t\t\t\tSELECT ret;\n\t\t\t\tSIGNAL SQLSTATE\n\t\t\t\t\t'45001'\n\t\t\t\tSET\n\t\t\t\t\tMESSAGE_TEXT = \"an error\",\n\t\t\t\t\tMYSQL_ERRNO = 45001;\n\t\t\tEND\n\t\t`)\n\t\tdefer dbt.mustExec(\"DROP PROCEDURE test_signal\")\n\n\t\tvar val int\n\n\t\t// text protocol\n\t\trows, err := dbt.db.Query(\"CALL test_signal(42)\")\n\t\tif err != nil {\n\t\t\tdbt.Fatalf(\"error on text query: %s\", err.Error())\n\t\t}\n\t\tfor rows.Next() {\n\t\t\tif err := rows.Scan(&val); err != nil {\n\t\t\t\tdbt.Error(err)\n\t\t\t} else if val != 42 {\n\t\t\t\tdbt.Errorf(\"expected val to be 42\")\n\t\t\t}\n\t\t}\n\t\trows.Close()\n\n\t\t// binary protocol\n\t\trows, err = dbt.db.Query(\"CALL test_signal(?)\", 42)\n\t\tif err != nil {\n\t\t\tdbt.Fatalf(\"error on binary query: %s\", err.Error())\n\t\t}\n\t\tfor rows.Next() {\n\t\t\tif err := rows.Scan(&val); err != nil {\n\t\t\t\tdbt.Error(err)\n\t\t\t} else if val != 42 {\n\t\t\t\tdbt.Errorf(\"expected val to be 42\")\n\t\t\t}\n\t\t}\n\t\trows.Close()\n\t})\n}\n\nfunc TestColumnsReusesSlice(t *testing.T) {\n\trows := mysqlRows{\n\t\trs: resultSet{\n\t\t\tcolumns: []mysqlField{\n\t\t\t\t{\n\t\t\t\t\ttableName: \"test\",\n\t\t\t\t\tname:      \"A\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\ttableName: \"test\",\n\t\t\t\t\tname:      \"B\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tallocs := testing.AllocsPerRun(1, func() {\n\t\tcols := rows.Columns()\n\n\t\tif len(cols) != 2 {\n\t\t\tt.Fatalf(\"expected 2 columns, got %d\", len(cols))\n\t\t}\n\t})\n\n\tif allocs != 0 {\n\t\tt.Fatalf(\"expected 0 allocations, got %d\", int(allocs))\n\t}\n\n\tif rows.rs.columnNames == nil {\n\t\tt.Fatalf(\"expected columnNames to be set, got nil\")\n\t}\n}\n\nfunc TestRejectReadOnly(t *testing.T) {\n\trunTests(t, dsn, func(dbt *DBTest) {\n\t\t// Create Table\n\t\tdbt.mustExec(\"CREATE TABLE test (value BOOL)\")\n\t\t// Set the session to read-only. We didn't set the `rejectReadOnly`\n\t\t// option, so any writes after this should fail.\n\t\t_, err := dbt.db.Exec(\"SET SESSION TRANSACTION READ ONLY\")\n\t\t// Error 1193: Unknown system variable 'TRANSACTION' => skip test,\n\t\t// MySQL server version is too old\n\t\tmaybeSkip(t, err, 1193)\n\t\tif _, err := dbt.db.Exec(\"DROP TABLE test\"); err == nil {\n\t\t\tt.Fatalf(\"writing to DB in read-only session without \" +\n\t\t\t\t\"rejectReadOnly did not error\")\n\t\t}\n\t\t// Set the session back to read-write so runTests() can properly clean\n\t\t// up the table `test`.\n\t\tdbt.mustExec(\"SET SESSION TRANSACTION READ WRITE\")\n\t})\n\n\t// Enable the `rejectReadOnly` option.\n\trunTests(t, dsn+\"&rejectReadOnly=true\", func(dbt *DBTest) {\n\t\t// Create Table\n\t\tdbt.mustExec(\"CREATE TABLE test (value BOOL)\")\n\t\t// Set the session to read only. Any writes after this should error on\n\t\t// a driver.ErrBadConn, and cause `database/sql` to initiate a new\n\t\t// connection.\n\t\tdbt.mustExec(\"SET SESSION TRANSACTION READ ONLY\")\n\t\t// This would error, but `database/sql` should automatically retry on a\n\t\t// new connection which is not read-only, and eventually succeed.\n\t\tdbt.mustExec(\"DROP TABLE test\")\n\t})\n}\n\nfunc TestPing(t *testing.T) {\n\tctx := context.Background()\n\trunTests(t, dsn, func(dbt *DBTest) {\n\t\tif err := dbt.db.Ping(); err != nil {\n\t\t\tdbt.fail(\"Ping\", \"Ping\", err)\n\t\t}\n\t})\n\n\trunTests(t, dsn, func(dbt *DBTest) {\n\t\tconn, err := dbt.db.Conn(ctx)\n\t\tif err != nil {\n\t\t\tdbt.fail(\"db\", \"Conn\", err)\n\t\t}\n\n\t\t// Check that affectedRows and insertIds are cleared after each call.\n\t\tconn.Raw(func(conn any) error {\n\t\t\tc := conn.(*mysqlConn)\n\n\t\t\t// Issue a query that sets affectedRows and insertIds.\n\t\t\tq, err := c.Query(`SELECT 1`, nil)\n\t\t\tif err != nil {\n\t\t\t\tdbt.fail(\"Conn\", \"Query\", err)\n\t\t\t}\n\t\t\tif got, want := c.result.affectedRows, []int64{0}; !reflect.DeepEqual(got, want) {\n\t\t\t\tdbt.Fatalf(\"bad affectedRows: got %v, want=%v\", got, want)\n\t\t\t}\n\t\t\tif got, want := c.result.insertIds, []int64{0}; !reflect.DeepEqual(got, want) {\n\t\t\t\tdbt.Fatalf(\"bad insertIds: got %v, want=%v\", got, want)\n\t\t\t}\n\t\t\tq.Close()\n\n\t\t\t// Verify that Ping() clears both fields.\n\t\t\tfor range 2 {\n\t\t\t\tif err := c.Ping(ctx); err != nil {\n\t\t\t\t\tdbt.fail(\"Pinger\", \"Ping\", err)\n\t\t\t\t}\n\t\t\t\tif got, want := c.result.affectedRows, []int64(nil); !reflect.DeepEqual(got, want) {\n\t\t\t\t\tt.Errorf(\"bad affectedRows: got %v, want=%v\", got, want)\n\t\t\t\t}\n\t\t\t\tif got, want := c.result.insertIds, []int64(nil); !reflect.DeepEqual(got, want) {\n\t\t\t\t\tt.Errorf(\"bad affectedRows: got %v, want=%v\", got, want)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t})\n}\n\n// See Issue #799\nfunc TestEmptyPassword(t *testing.T) {\n\tif !available {\n\t\tt.Skipf(\"MySQL server not running on %s\", netAddr)\n\t}\n\n\tdsn := fmt.Sprintf(\"%s:%s@%s/%s?timeout=30s\", user, \"\", netAddr, dbname)\n\tdb, err := sql.Open(driverNameTest, dsn)\n\tif err == nil {\n\t\tdefer db.Close()\n\t\terr = db.Ping()\n\t}\n\n\tif pass == \"\" {\n\t\tif err != nil {\n\t\t\tt.Fatal(err.Error())\n\t\t}\n\t} else {\n\t\tif err == nil {\n\t\t\tt.Fatal(\"expected authentication error\")\n\t\t}\n\t\tif !strings.HasPrefix(err.Error(), \"Error 1045\") {\n\t\t\tt.Fatal(err.Error())\n\t\t}\n\t}\n}\n\n// static interface implementation checks of mysqlConn\nvar (\n\t_ driver.ConnBeginTx        = &mysqlConn{}\n\t_ driver.ConnPrepareContext = &mysqlConn{}\n\t_ driver.ExecerContext      = &mysqlConn{}\n\t_ driver.Pinger             = &mysqlConn{}\n\t_ driver.QueryerContext     = &mysqlConn{}\n)\n\n// static interface implementation checks of mysqlStmt\nvar (\n\t_ driver.StmtExecContext  = &mysqlStmt{}\n\t_ driver.StmtQueryContext = &mysqlStmt{}\n)\n\n// Ensure that all the driver interfaces are implemented\nvar (\n\t// _ driver.RowsColumnTypeLength        = &binaryRows{}\n\t// _ driver.RowsColumnTypeLength        = &textRows{}\n\t_ driver.RowsColumnTypeDatabaseTypeName = &binaryRows{}\n\t_ driver.RowsColumnTypeDatabaseTypeName = &textRows{}\n\t_ driver.RowsColumnTypeNullable         = &binaryRows{}\n\t_ driver.RowsColumnTypeNullable         = &textRows{}\n\t_ driver.RowsColumnTypePrecisionScale   = &binaryRows{}\n\t_ driver.RowsColumnTypePrecisionScale   = &textRows{}\n\t_ driver.RowsColumnTypeScanType         = &binaryRows{}\n\t_ driver.RowsColumnTypeScanType         = &textRows{}\n\t_ driver.RowsNextResultSet              = &binaryRows{}\n\t_ driver.RowsNextResultSet              = &textRows{}\n)\n\nfunc TestMultiResultSet(t *testing.T) {\n\ttype result struct {\n\t\tvalues  [][]int\n\t\tcolumns []string\n\t}\n\n\t// checkRows is a helper test function to validate rows containing 3 result\n\t// sets with specific values and columns. The basic query would look like this:\n\t//\n\t// SELECT 1 AS col1, 2 AS col2 UNION SELECT 3, 4;\n\t// SELECT 0 UNION SELECT 1;\n\t// SELECT 1 AS col1, 2 AS col2, 3 AS col3 UNION SELECT 4, 5, 6;\n\t//\n\t// to distinguish test cases the first string argument is put in front of\n\t// every error or fatal message.\n\tcheckRows := func(desc string, rows *sql.Rows, dbt *DBTest) {\n\t\texpected := []result{\n\t\t\t{\n\t\t\t\tvalues:  [][]int{{1, 2}, {3, 4}},\n\t\t\t\tcolumns: []string{\"col1\", \"col2\"},\n\t\t\t},\n\t\t\t{\n\t\t\t\tvalues:  [][]int{{1, 2, 3}, {4, 5, 6}},\n\t\t\t\tcolumns: []string{\"col1\", \"col2\", \"col3\"},\n\t\t\t},\n\t\t}\n\n\t\tvar res1 result\n\t\tfor rows.Next() {\n\t\t\tvar res [2]int\n\t\t\tif err := rows.Scan(&res[0], &res[1]); err != nil {\n\t\t\t\tdbt.Fatal(err)\n\t\t\t}\n\t\t\tres1.values = append(res1.values, res[:])\n\t\t}\n\n\t\tcols, err := rows.Columns()\n\t\tif err != nil {\n\t\t\tdbt.Fatal(desc, err)\n\t\t}\n\t\tres1.columns = cols\n\n\t\tif !reflect.DeepEqual(expected[0], res1) {\n\t\t\tdbt.Error(desc, \"want =\", expected[0], \"got =\", res1)\n\t\t}\n\n\t\tif !rows.NextResultSet() {\n\t\t\tdbt.Fatal(desc, \"expected next result set\")\n\t\t}\n\n\t\t// ignoring one result set\n\n\t\tif !rows.NextResultSet() {\n\t\t\tdbt.Fatal(desc, \"expected next result set\")\n\t\t}\n\n\t\tvar res2 result\n\t\tcols, err = rows.Columns()\n\t\tif err != nil {\n\t\t\tdbt.Fatal(desc, err)\n\t\t}\n\t\tres2.columns = cols\n\n\t\tfor rows.Next() {\n\t\t\tvar res [3]int\n\t\t\tif err := rows.Scan(&res[0], &res[1], &res[2]); err != nil {\n\t\t\t\tdbt.Fatal(desc, err)\n\t\t\t}\n\t\t\tres2.values = append(res2.values, res[:])\n\t\t}\n\n\t\tif !reflect.DeepEqual(expected[1], res2) {\n\t\t\tdbt.Error(desc, \"want =\", expected[1], \"got =\", res2)\n\t\t}\n\n\t\tif rows.NextResultSet() {\n\t\t\tdbt.Error(desc, \"unexpected next result set\")\n\t\t}\n\n\t\tif err := rows.Err(); err != nil {\n\t\t\tdbt.Error(desc, err)\n\t\t}\n\t}\n\n\trunTestsWithMultiStatement(t, dsn, func(dbt *DBTest) {\n\t\trows := dbt.mustQuery(`DO 1;\n\t\tSELECT 1 AS col1, 2 AS col2 UNION SELECT 3, 4;\n\t\tDO 1;\n\t\tSELECT 0 UNION SELECT 1;\n\t\tSELECT 1 AS col1, 2 AS col2, 3 AS col3 UNION SELECT 4, 5, 6;`)\n\t\tdefer rows.Close()\n\t\tcheckRows(\"query: \", rows, dbt)\n\t})\n\n\trunTestsWithMultiStatement(t, dsn, func(dbt *DBTest) {\n\t\tqueries := []string{\n\t\t\t`\n\t\t\tDROP PROCEDURE IF EXISTS test_mrss;\n\t\t\tCREATE PROCEDURE test_mrss()\n\t\t\tBEGIN\n\t\t\t\tDO 1;\n\t\t\t\tSELECT 1 AS col1, 2 AS col2 UNION SELECT 3, 4;\n\t\t\t\tDO 1;\n\t\t\t\tSELECT 0 UNION SELECT 1;\n\t\t\t\tSELECT 1 AS col1, 2 AS col2, 3 AS col3 UNION SELECT 4, 5, 6;\n\t\t\tEND\n\t\t`,\n\t\t\t`\n\t\t\tDROP PROCEDURE IF EXISTS test_mrss;\n\t\t\tCREATE PROCEDURE test_mrss()\n\t\t\tBEGIN\n\t\t\t\tSELECT 1 AS col1, 2 AS col2 UNION SELECT 3, 4;\n\t\t\t\tSELECT 0 UNION SELECT 1;\n\t\t\t\tSELECT 1 AS col1, 2 AS col2, 3 AS col3 UNION SELECT 4, 5, 6;\n\t\t\tEND\n\t\t`,\n\t\t}\n\n\t\tdefer dbt.mustExec(\"DROP PROCEDURE IF EXISTS test_mrss\")\n\n\t\tfor i, query := range queries {\n\t\t\tdbt.mustExec(query)\n\n\t\t\tstmt, err := dbt.db.Prepare(\"CALL test_mrss()\")\n\t\t\tif err != nil {\n\t\t\t\tdbt.Fatalf(\"%v (i=%d)\", err, i)\n\t\t\t}\n\t\t\tdefer stmt.Close()\n\n\t\t\tfor j := range 2 {\n\t\t\t\trows, err := stmt.Query()\n\t\t\t\tif err != nil {\n\t\t\t\t\tdbt.Fatalf(\"%v (i=%d) (j=%d)\", err, i, j)\n\t\t\t\t}\n\t\t\t\tcheckRows(fmt.Sprintf(\"prepared stmt query (i=%d) (j=%d): \", i, j), rows, dbt)\n\t\t\t}\n\t\t}\n\t})\n}\n\nfunc TestMultiResultSetNoSelect(t *testing.T) {\n\trunTestsWithMultiStatement(t, dsn, func(dbt *DBTest) {\n\t\trows := dbt.mustQuery(\"DO 1; DO 2;\")\n\t\tdefer rows.Close()\n\n\t\tif rows.Next() {\n\t\t\tdbt.Error(\"unexpected row\")\n\t\t}\n\n\t\tif rows.NextResultSet() {\n\t\t\tdbt.Error(\"unexpected next result set\")\n\t\t}\n\n\t\tif err := rows.Err(); err != nil {\n\t\t\tdbt.Error(\"expected nil; got \", err)\n\t\t}\n\t})\n}\n\nfunc TestExecMultipleResults(t *testing.T) {\n\tctx := context.Background()\n\trunTestsWithMultiStatement(t, dsn, func(dbt *DBTest) {\n\t\tdbt.mustExec(`\n\t\tCREATE TABLE test (\n\t\t\tid INT NOT NULL AUTO_INCREMENT,\n\t\t\tvalue VARCHAR(255),\n\t\t\tPRIMARY KEY (id)\n\t\t)`)\n\t\tconn, err := dbt.db.Conn(ctx)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"failed to connect: %v\", err)\n\t\t}\n\t\tconn.Raw(func(conn any) error {\n\t\t\t//lint:ignore SA1019 this is a test\n\t\t\tex := conn.(driver.Execer)\n\t\t\tres, err := ex.Exec(`\n\t\t\tINSERT INTO test (value) VALUES ('a'), ('b');\n\t\t\tINSERT INTO test (value) VALUES ('c'), ('d'), ('e');\n\t\t\t`, nil)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"insert statements failed: %v\", err)\n\t\t\t}\n\t\t\tmres := res.(Result)\n\t\t\tif got, want := mres.AllRowsAffected(), []int64{2, 3}; !reflect.DeepEqual(got, want) {\n\t\t\t\tt.Errorf(\"bad AllRowsAffected: got %v, want=%v\", got, want)\n\t\t\t}\n\t\t\t// For INSERTs containing multiple rows, LAST_INSERT_ID() returns the\n\t\t\t// first inserted ID, not the last.\n\t\t\tif got, want := mres.AllLastInsertIds(), []int64{1, 3}; !reflect.DeepEqual(got, want) {\n\t\t\t\tt.Errorf(\"bad AllLastInsertIds: got %v, want %v\", got, want)\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t})\n}\n\n// tests if rows are set in a proper state if some results were ignored before\n// calling rows.NextResultSet.\nfunc TestSkipResults(t *testing.T) {\n\trunTestsParallel(t, dsn, func(dbt *DBTest, _ string) {\n\t\trows := dbt.mustQuery(\"SELECT 1, 2\")\n\t\tdefer rows.Close()\n\n\t\tif !rows.Next() {\n\t\t\tdbt.Error(\"expected row\")\n\t\t}\n\n\t\tif rows.NextResultSet() {\n\t\t\tdbt.Error(\"unexpected next result set\")\n\t\t}\n\n\t\tif err := rows.Err(); err != nil {\n\t\t\tdbt.Error(\"expected nil; got \", err)\n\t\t}\n\t})\n}\n\nfunc TestQueryMultipleResults(t *testing.T) {\n\tctx := context.Background()\n\trunTestsWithMultiStatement(t, dsn, func(dbt *DBTest) {\n\t\tdbt.mustExec(`\n\t\tCREATE TABLE test (\n\t\t\tid INT NOT NULL AUTO_INCREMENT,\n\t\t\tvalue VARCHAR(255),\n\t\t\tPRIMARY KEY (id)\n\t\t)`)\n\t\tconn, err := dbt.db.Conn(ctx)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"failed to connect: %v\", err)\n\t\t}\n\t\tconn.Raw(func(conn any) error {\n\t\t\t//lint:ignore SA1019 this is a test\n\t\t\tqr := conn.(driver.Queryer)\n\t\t\tc := conn.(*mysqlConn)\n\n\t\t\t// Demonstrate that repeated queries reset the affectedRows\n\t\t\tfor range 2 {\n\t\t\t\t_, err := qr.Query(`\n\t\t\t\tINSERT INTO test (value) VALUES ('a'), ('b');\n\t\t\t\tINSERT INTO test (value) VALUES ('c'), ('d'), ('e');\n\t\t\t`, nil)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatalf(\"insert statements failed: %v\", err)\n\t\t\t\t}\n\t\t\t\tif got, want := c.result.affectedRows, []int64{2, 3}; !reflect.DeepEqual(got, want) {\n\t\t\t\t\tt.Errorf(\"bad affectedRows: got %v, want=%v\", got, want)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t})\n}\n\nfunc TestPingContext(t *testing.T) {\n\trunTestsParallel(t, dsn, func(dbt *DBTest, _ string) {\n\t\tctx, cancel := context.WithCancel(context.Background())\n\t\tcancel()\n\t\tif err := dbt.db.PingContext(ctx); err != context.Canceled {\n\t\t\tdbt.Errorf(\"expected context.Canceled, got %v\", err)\n\t\t}\n\t})\n}\n\nfunc TestContextCancelExec(t *testing.T) {\n\trunTestsParallel(t, dsn, func(dbt *DBTest, tbl string) {\n\t\tdbt.mustExec(\"CREATE TABLE \" + tbl + \" (v INTEGER)\")\n\t\tctx, cancel := context.WithCancel(context.Background())\n\n\t\t// Delay execution for just a bit until db.ExecContext has begun.\n\t\tdefer time.AfterFunc(250*time.Millisecond, cancel).Stop()\n\n\t\t// This query will be canceled.\n\t\tstartTime := time.Now()\n\t\tif _, err := dbt.db.ExecContext(ctx, \"INSERT INTO \"+tbl+\" VALUES (SLEEP(1))\"); err != context.Canceled {\n\t\t\tdbt.Errorf(\"expected context.Canceled, got %v\", err)\n\t\t}\n\t\tif d := time.Since(startTime); d > 500*time.Millisecond {\n\t\t\tdbt.Errorf(\"too long execution time: %s\", d)\n\t\t}\n\n\t\t// Wait for the INSERT query to be done.\n\t\ttime.Sleep(time.Second)\n\n\t\t// Check how many times the query is executed.\n\t\tvar v int\n\t\tif err := dbt.db.QueryRow(\"SELECT COUNT(*) FROM \" + tbl).Scan(&v); err != nil {\n\t\t\tdbt.Fatalf(\"%s\", err.Error())\n\t\t}\n\t\tif v != 1 { // TODO: need to kill the query, and v should be 0.\n\t\t\tdbt.Skipf(\"[WARN] expected val to be 1, got %d\", v)\n\t\t}\n\n\t\t// Context is already canceled, so error should come before execution.\n\t\tif _, err := dbt.db.ExecContext(ctx, \"INSERT INTO \"+tbl+\" VALUES (1)\"); err == nil {\n\t\t\tdbt.Error(\"expected error\")\n\t\t} else if err.Error() != \"context canceled\" {\n\t\t\tdbt.Fatalf(\"unexpected error: %s\", err)\n\t\t}\n\n\t\t// The second insert query will fail, so the table has no changes.\n\t\tif err := dbt.db.QueryRow(\"SELECT COUNT(*) FROM \" + tbl).Scan(&v); err != nil {\n\t\t\tdbt.Fatalf(\"%s\", err.Error())\n\t\t}\n\t\tif v != 1 {\n\t\t\tdbt.Skipf(\"[WARN] expected val to be 1, got %d\", v)\n\t\t}\n\t})\n}\n\nfunc TestContextCancelQuery(t *testing.T) {\n\trunTestsParallel(t, dsn, func(dbt *DBTest, tbl string) {\n\t\tdbt.mustExec(\"CREATE TABLE \" + tbl + \" (v INTEGER)\")\n\t\tctx, cancel := context.WithCancel(context.Background())\n\n\t\t// Delay execution for just a bit until db.ExecContext has begun.\n\t\tdefer time.AfterFunc(250*time.Millisecond, cancel).Stop()\n\n\t\t// This query will be canceled.\n\t\tstartTime := time.Now()\n\t\tif _, err := dbt.db.QueryContext(ctx, \"INSERT INTO \"+tbl+\" VALUES (SLEEP(1))\"); err != context.Canceled {\n\t\t\tdbt.Errorf(\"expected context.Canceled, got %v\", err)\n\t\t}\n\t\tif d := time.Since(startTime); d > 500*time.Millisecond {\n\t\t\tdbt.Errorf(\"too long execution time: %s\", d)\n\t\t}\n\n\t\t// Wait for the INSERT query to be done.\n\t\ttime.Sleep(time.Second)\n\n\t\t// Check how many times the query is executed.\n\t\tvar v int\n\t\tif err := dbt.db.QueryRow(\"SELECT COUNT(*) FROM \" + tbl).Scan(&v); err != nil {\n\t\t\tdbt.Fatalf(\"%s\", err.Error())\n\t\t}\n\t\tif v != 1 { // TODO: need to kill the query, and v should be 0.\n\t\t\tdbt.Skipf(\"[WARN] expected val to be 1, got %d\", v)\n\t\t}\n\n\t\t// Context is already canceled, so error should come before execution.\n\t\tif _, err := dbt.db.QueryContext(ctx, \"INSERT INTO \"+tbl+\" VALUES (1)\"); err != context.Canceled {\n\t\t\tdbt.Errorf(\"expected context.Canceled, got %v\", err)\n\t\t}\n\n\t\t// The second insert query will fail, so the table has no changes.\n\t\tif err := dbt.db.QueryRow(\"SELECT COUNT(*) FROM \" + tbl).Scan(&v); err != nil {\n\t\t\tdbt.Fatalf(\"%s\", err.Error())\n\t\t}\n\t\tif v != 1 {\n\t\t\tdbt.Skipf(\"[WARN] expected val to be 1, got %d\", v)\n\t\t}\n\t})\n}\n\nfunc TestContextCancelQueryRow(t *testing.T) {\n\trunTestsParallel(t, dsn, func(dbt *DBTest, tbl string) {\n\t\tdbt.mustExec(\"CREATE TABLE \" + tbl + \" (v INTEGER)\")\n\t\tdbt.mustExec(\"INSERT INTO \" + tbl + \" VALUES (1), (2), (3)\")\n\t\tctx, cancel := context.WithCancel(context.Background())\n\n\t\trows, err := dbt.db.QueryContext(ctx, \"SELECT v FROM \"+tbl)\n\t\tif err != nil {\n\t\t\tdbt.Fatalf(\"%s\", err.Error())\n\t\t}\n\n\t\t// the first row will be succeed.\n\t\tvar v int\n\t\tif !rows.Next() {\n\t\t\tdbt.Fatalf(\"unexpected end\")\n\t\t}\n\t\tif err := rows.Scan(&v); err != nil {\n\t\t\tdbt.Fatalf(\"%s\", err.Error())\n\t\t}\n\n\t\tcancel()\n\t\t// make sure the driver receives the cancel request.\n\t\ttime.Sleep(100 * time.Millisecond)\n\n\t\tif rows.Next() {\n\t\t\tdbt.Errorf(\"expected end, but not\")\n\t\t}\n\t\tif err := rows.Err(); err != context.Canceled {\n\t\t\tdbt.Errorf(\"expected context.Canceled, got %v\", err)\n\t\t}\n\t})\n}\n\nfunc TestContextCancelPrepare(t *testing.T) {\n\trunTestsParallel(t, dsn, func(dbt *DBTest, _ string) {\n\t\tctx, cancel := context.WithCancel(context.Background())\n\t\tcancel()\n\t\tif _, err := dbt.db.PrepareContext(ctx, \"SELECT 1\"); err != context.Canceled {\n\t\t\tdbt.Errorf(\"expected context.Canceled, got %v\", err)\n\t\t}\n\t})\n}\n\nfunc TestContextCancelStmtExec(t *testing.T) {\n\trunTestsParallel(t, dsn, func(dbt *DBTest, tbl string) {\n\t\tdbt.mustExec(\"CREATE TABLE \" + tbl + \" (v INTEGER)\")\n\t\tctx, cancel := context.WithCancel(context.Background())\n\t\tstmt, err := dbt.db.PrepareContext(ctx, \"INSERT INTO \"+tbl+\" VALUES (SLEEP(1))\")\n\t\tif err != nil {\n\t\t\tdbt.Fatalf(\"unexpected error: %v\", err)\n\t\t}\n\n\t\t// Delay execution for just a bit until db.ExecContext has begun.\n\t\tdefer time.AfterFunc(250*time.Millisecond, cancel).Stop()\n\n\t\t// This query will be canceled.\n\t\tstartTime := time.Now()\n\t\tif _, err := stmt.ExecContext(ctx); err != context.Canceled {\n\t\t\tdbt.Errorf(\"expected context.Canceled, got %v\", err)\n\t\t}\n\t\tif d := time.Since(startTime); d > 500*time.Millisecond {\n\t\t\tdbt.Errorf(\"too long execution time: %s\", d)\n\t\t}\n\n\t\t// Wait for the INSERT query to be done.\n\t\ttime.Sleep(time.Second)\n\n\t\t// Check how many times the query is executed.\n\t\tvar v int\n\t\tif err := dbt.db.QueryRow(\"SELECT COUNT(*) FROM \" + tbl).Scan(&v); err != nil {\n\t\t\tdbt.Fatalf(\"%s\", err.Error())\n\t\t}\n\t\tif v != 1 { // TODO: need to kill the query, and v should be 0.\n\t\t\tdbt.Skipf(\"[WARN] expected val to be 1, got %d\", v)\n\t\t}\n\t})\n}\n\nfunc TestContextCancelStmtQuery(t *testing.T) {\n\trunTestsParallel(t, dsn, func(dbt *DBTest, tbl string) {\n\t\tdbt.mustExec(\"CREATE TABLE \" + tbl + \" (v INTEGER)\")\n\t\tctx, cancel := context.WithCancel(context.Background())\n\t\tstmt, err := dbt.db.PrepareContext(ctx, \"INSERT INTO \"+tbl+\" VALUES (SLEEP(1))\")\n\t\tif err != nil {\n\t\t\tdbt.Fatalf(\"unexpected error: %v\", err)\n\t\t}\n\n\t\t// Delay execution for just a bit until db.ExecContext has begun.\n\t\tdefer time.AfterFunc(250*time.Millisecond, cancel).Stop()\n\n\t\t// This query will be canceled.\n\t\tstartTime := time.Now()\n\t\tif _, err := stmt.QueryContext(ctx); err != context.Canceled {\n\t\t\tdbt.Errorf(\"expected context.Canceled, got %v\", err)\n\t\t}\n\t\tif d := time.Since(startTime); d > 500*time.Millisecond {\n\t\t\tdbt.Errorf(\"too long execution time: %s\", d)\n\t\t}\n\n\t\t// Wait for the INSERT query has done.\n\t\ttime.Sleep(time.Second)\n\n\t\t// Check how many times the query is executed.\n\t\tvar v int\n\t\tif err := dbt.db.QueryRow(\"SELECT COUNT(*) FROM \" + tbl).Scan(&v); err != nil {\n\t\t\tdbt.Fatalf(\"%s\", err.Error())\n\t\t}\n\t\tif v != 1 { // TODO: need to kill the query, and v should be 0.\n\t\t\tdbt.Skipf(\"[WARN] expected val to be 1, got %d\", v)\n\t\t}\n\t})\n}\n\nfunc TestContextCancelBegin(t *testing.T) {\n\tif runtime.GOOS == \"windows\" || runtime.GOOS == \"darwin\" {\n\t\tt.Skip(`FIXME: it sometime fails with \"expected driver.ErrBadConn, got sql: connection is already closed\" on windows and macOS`)\n\t}\n\n\trunTestsParallel(t, dsn, func(dbt *DBTest, tbl string) {\n\t\tdbt.mustExec(\"CREATE TABLE \" + tbl + \" (v INTEGER)\")\n\t\tctx, cancel := context.WithCancel(context.Background())\n\t\tconn, err := dbt.db.Conn(ctx)\n\t\tif err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tdefer conn.Close()\n\t\ttx, err := conn.BeginTx(ctx, nil)\n\t\tif err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\n\t\t// Delay execution for just a bit until db.ExecContext has begun.\n\t\tdefer time.AfterFunc(100*time.Millisecond, cancel).Stop()\n\n\t\t// This query will be canceled.\n\t\tstartTime := time.Now()\n\t\tif _, err := tx.ExecContext(ctx, \"INSERT INTO \"+tbl+\" VALUES (SLEEP(1))\"); err != context.Canceled {\n\t\t\tdbt.Errorf(\"expected context.Canceled, got %v\", err)\n\t\t}\n\t\tif d := time.Since(startTime); d > 500*time.Millisecond {\n\t\t\tdbt.Errorf(\"too long execution time: %s\", d)\n\t\t}\n\n\t\t// Transaction is canceled, so expect an error.\n\t\tswitch err := tx.Commit(); err {\n\t\tcase sql.ErrTxDone:\n\t\t\t// because the transaction has already been rollbacked.\n\t\t\t// the database/sql package watches ctx\n\t\t\t// and rollbacks when ctx is canceled.\n\t\tcase context.Canceled:\n\t\t\t// the database/sql package rollbacks on another goroutine,\n\t\t\t// so the transaction may not be rollbacked depending on goroutine scheduling.\n\t\tdefault:\n\t\t\tdbt.Errorf(\"expected sql.ErrTxDone or context.Canceled, got %v\", err)\n\t\t}\n\n\t\t// The connection is now in an inoperable state - so performing other\n\t\t// operations should fail with ErrBadConn\n\t\t// Important to exercise isolation level too - it runs SET TRANSACTION ISOLATION\n\t\t// LEVEL XXX first, which needs to return ErrBadConn if the connection's context\n\t\t// is cancelled\n\t\t_, err = conn.BeginTx(context.Background(), &sql.TxOptions{Isolation: sql.LevelReadCommitted})\n\t\tif err != driver.ErrBadConn {\n\t\t\tdbt.Errorf(\"expected driver.ErrBadConn, got %v\", err)\n\t\t}\n\n\t\t// cannot begin a transaction (on a different conn) with a canceled context\n\t\tif _, err := dbt.db.BeginTx(ctx, nil); err != context.Canceled {\n\t\t\tdbt.Errorf(\"expected context.Canceled, got %v\", err)\n\t\t}\n\t})\n}\n\nfunc TestContextBeginIsolationLevel(t *testing.T) {\n\trunTestsParallel(t, dsn, func(dbt *DBTest, tbl string) {\n\t\tdbt.mustExec(\"CREATE TABLE \" + tbl + \" (v INTEGER)\")\n\t\tctx, cancel := context.WithCancel(context.Background())\n\t\tdefer cancel()\n\n\t\ttx1, err := dbt.db.BeginTx(ctx, &sql.TxOptions{\n\t\t\tIsolation: sql.LevelRepeatableRead,\n\t\t})\n\t\tif err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\n\t\ttx2, err := dbt.db.BeginTx(ctx, &sql.TxOptions{\n\t\t\tIsolation: sql.LevelReadCommitted,\n\t\t})\n\t\tif err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\n\t\t_, err = tx1.ExecContext(ctx, \"INSERT INTO \"+tbl+\" VALUES (1)\")\n\t\tif err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\n\t\tvar v int\n\t\trow := tx2.QueryRowContext(ctx, \"SELECT COUNT(*) FROM \"+tbl)\n\t\tif err := row.Scan(&v); err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\t// Because writer transaction wasn't committed yet, it should be available\n\t\tif v != 0 {\n\t\t\tdbt.Errorf(\"expected val to be 0, got %d\", v)\n\t\t}\n\n\t\terr = tx1.Commit()\n\t\tif err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\n\t\trow = tx2.QueryRowContext(ctx, \"SELECT COUNT(*) FROM \"+tbl)\n\t\tif err := row.Scan(&v); err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\t// Data written by writer transaction is already committed, it should be selectable\n\t\tif v != 1 {\n\t\t\tdbt.Errorf(\"expected val to be 1, got %d\", v)\n\t\t}\n\t\ttx2.Commit()\n\t})\n}\n\nfunc TestContextBeginReadOnly(t *testing.T) {\n\trunTestsParallel(t, dsn, func(dbt *DBTest, tbl string) {\n\t\tdbt.mustExec(\"CREATE TABLE \" + tbl + \" (v INTEGER)\")\n\t\tctx, cancel := context.WithCancel(context.Background())\n\t\tdefer cancel()\n\n\t\ttx, err := dbt.db.BeginTx(ctx, &sql.TxOptions{\n\t\t\tReadOnly: true,\n\t\t})\n\t\tif _, ok := err.(*MySQLError); ok {\n\t\t\tdbt.Skip(\"It seems that your MySQL does not support READ ONLY transactions\")\n\t\t\treturn\n\t\t} else if err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\n\t\t// INSERT queries fail in a READ ONLY transaction.\n\t\t_, err = tx.ExecContext(ctx, \"INSERT INTO \"+tbl+\" VALUES (1)\")\n\t\tif _, ok := err.(*MySQLError); !ok {\n\t\t\tdbt.Errorf(\"expected MySQLError, got %v\", err)\n\t\t}\n\n\t\t// SELECT queries can be executed.\n\t\tvar v int\n\t\trow := tx.QueryRowContext(ctx, \"SELECT COUNT(*) FROM \"+tbl)\n\t\tif err := row.Scan(&v); err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t\tif v != 0 {\n\t\t\tdbt.Errorf(\"expected val to be 0, got %d\", v)\n\t\t}\n\n\t\tif err := tx.Commit(); err != nil {\n\t\t\tdbt.Fatal(err)\n\t\t}\n\t})\n}\n\nfunc TestRowsColumnTypes(t *testing.T) {\n\tniNULL := sql.NullInt64{Int64: 0, Valid: false}\n\tni0 := sql.NullInt64{Int64: 0, Valid: true}\n\tni1 := sql.NullInt64{Int64: 1, Valid: true}\n\tni42 := sql.NullInt64{Int64: 42, Valid: true}\n\tnfNULL := sql.NullFloat64{Float64: 0.0, Valid: false}\n\tnf0 := sql.NullFloat64{Float64: 0.0, Valid: true}\n\tnf1337 := sql.NullFloat64{Float64: 13.37, Valid: true}\n\tnt0 := sql.NullTime{Time: time.Date(2006, 01, 02, 15, 04, 05, 0, time.UTC), Valid: true}\n\tnt1 := sql.NullTime{Time: time.Date(2006, 01, 02, 15, 04, 05, 100000000, time.UTC), Valid: true}\n\tnt2 := sql.NullTime{Time: time.Date(2006, 01, 02, 15, 04, 05, 110000000, time.UTC), Valid: true}\n\tnt6 := sql.NullTime{Time: time.Date(2006, 01, 02, 15, 04, 05, 111111000, time.UTC), Valid: true}\n\tnd1 := sql.NullTime{Time: time.Date(2006, 01, 02, 0, 0, 0, 0, time.UTC), Valid: true}\n\tnd2 := sql.NullTime{Time: time.Date(2006, 03, 04, 0, 0, 0, 0, time.UTC), Valid: true}\n\tndNULL := sql.NullTime{Time: time.Time{}, Valid: false}\n\tbNULL := []byte(nil)\n\tnsNULL := sql.NullString{String: \"\", Valid: false}\n\t// Helper function to build NullString from string literal.\n\tns := func(s string) sql.NullString { return sql.NullString{String: s, Valid: true} }\n\tns0 := ns(\"0\")\n\tb0 := []byte(\"0\")\n\tb42 := []byte(\"42\")\n\tnsTest := ns(\"Test\")\n\tbTest := []byte(\"Test\")\n\tb0pad4 := []byte(\"0\\x00\\x00\\x00\") // BINARY right-pads values with 0x00\n\tbx0 := []byte(\"\\x00\")\n\tbx42 := []byte(\"\\x42\")\n\n\tvar columns = []struct {\n\t\tname             string\n\t\tfieldType        string // type used when creating table schema\n\t\tdatabaseTypeName string // actual type used by MySQL\n\t\tscanType         reflect.Type\n\t\tnullable         bool\n\t\tprecision        int64 // 0 if not ok\n\t\tscale            int64\n\t\tvaluesIn         [3]string\n\t\tvaluesOut        [3]any\n\t}{\n\t\t{\"bit8null\", \"BIT(8)\", \"BIT\", scanTypeBytes, true, 0, 0, [3]string{\"0x0\", \"NULL\", \"0x42\"}, [3]any{bx0, bNULL, bx42}},\n\t\t{\"boolnull\", \"BOOL\", \"TINYINT\", scanTypeNullInt, true, 0, 0, [3]string{\"NULL\", \"true\", \"0\"}, [3]any{niNULL, ni1, ni0}},\n\t\t{\"bool\", \"BOOL NOT NULL\", \"TINYINT\", scanTypeInt8, false, 0, 0, [3]string{\"1\", \"0\", \"FALSE\"}, [3]any{int8(1), int8(0), int8(0)}},\n\t\t{\"intnull\", \"INTEGER\", \"INT\", scanTypeNullInt, true, 0, 0, [3]string{\"0\", \"NULL\", \"42\"}, [3]any{ni0, niNULL, ni42}},\n\t\t{\"smallint\", \"SMALLINT NOT NULL\", \"SMALLINT\", scanTypeInt16, false, 0, 0, [3]string{\"0\", \"-32768\", \"32767\"}, [3]any{int16(0), int16(-32768), int16(32767)}},\n\t\t{\"smallintnull\", \"SMALLINT\", \"SMALLINT\", scanTypeNullInt, true, 0, 0, [3]string{\"0\", \"NULL\", \"42\"}, [3]any{ni0, niNULL, ni42}},\n\t\t{\"int3null\", \"INT(3)\", \"INT\", scanTypeNullInt, true, 0, 0, [3]string{\"0\", \"NULL\", \"42\"}, [3]any{ni0, niNULL, ni42}},\n\t\t{\"int7\", \"INT(7) NOT NULL\", \"INT\", scanTypeInt32, false, 0, 0, [3]string{\"0\", \"-1337\", \"42\"}, [3]any{int32(0), int32(-1337), int32(42)}},\n\t\t{\"mediumintnull\", \"MEDIUMINT\", \"MEDIUMINT\", scanTypeNullInt, true, 0, 0, [3]string{\"0\", \"42\", \"NULL\"}, [3]any{ni0, ni42, niNULL}},\n\t\t{\"bigint\", \"BIGINT NOT NULL\", \"BIGINT\", scanTypeInt64, false, 0, 0, [3]string{\"0\", \"65535\", \"-42\"}, [3]any{int64(0), int64(65535), int64(-42)}},\n\t\t{\"bigintnull\", \"BIGINT\", \"BIGINT\", scanTypeNullInt, true, 0, 0, [3]string{\"NULL\", \"1\", \"42\"}, [3]any{niNULL, ni1, ni42}},\n\t\t{\"tinyuint\", \"TINYINT UNSIGNED NOT NULL\", \"UNSIGNED TINYINT\", scanTypeUint8, false, 0, 0, [3]string{\"0\", \"255\", \"42\"}, [3]any{uint8(0), uint8(255), uint8(42)}},\n\t\t{\"smalluint\", \"SMALLINT UNSIGNED NOT NULL\", \"UNSIGNED SMALLINT\", scanTypeUint16, false, 0, 0, [3]string{\"0\", \"65535\", \"42\"}, [3]any{uint16(0), uint16(65535), uint16(42)}},\n\t\t{\"biguint\", \"BIGINT UNSIGNED NOT NULL\", \"UNSIGNED BIGINT\", scanTypeUint64, false, 0, 0, [3]string{\"0\", \"65535\", \"42\"}, [3]any{uint64(0), uint64(65535), uint64(42)}},\n\t\t{\"mediumuint\", \"MEDIUMINT UNSIGNED NOT NULL\", \"UNSIGNED MEDIUMINT\", scanTypeUint32, false, 0, 0, [3]string{\"0\", \"16777215\", \"42\"}, [3]any{uint32(0), uint32(16777215), uint32(42)}},\n\t\t{\"uint13\", \"INT(13) UNSIGNED NOT NULL\", \"UNSIGNED INT\", scanTypeUint32, false, 0, 0, [3]string{\"0\", \"1337\", \"42\"}, [3]any{uint32(0), uint32(1337), uint32(42)}},\n\t\t{\"float\", \"FLOAT NOT NULL\", \"FLOAT\", scanTypeFloat32, false, math.MaxInt64, math.MaxInt64, [3]string{\"0\", \"42\", \"13.37\"}, [3]any{float32(0), float32(42), float32(13.37)}},\n\t\t{\"floatnull\", \"FLOAT\", \"FLOAT\", scanTypeNullFloat, true, math.MaxInt64, math.MaxInt64, [3]string{\"0\", \"NULL\", \"13.37\"}, [3]any{nf0, nfNULL, nf1337}},\n\t\t{\"float74null\", \"FLOAT(7,4)\", \"FLOAT\", scanTypeNullFloat, true, math.MaxInt64, 4, [3]string{\"0\", \"NULL\", \"13.37\"}, [3]any{nf0, nfNULL, nf1337}},\n\t\t{\"double\", \"DOUBLE NOT NULL\", \"DOUBLE\", scanTypeFloat64, false, math.MaxInt64, math.MaxInt64, [3]string{\"0\", \"42\", \"13.37\"}, [3]any{float64(0), float64(42), float64(13.37)}},\n\t\t{\"doublenull\", \"DOUBLE\", \"DOUBLE\", scanTypeNullFloat, true, math.MaxInt64, math.MaxInt64, [3]string{\"0\", \"NULL\", \"13.37\"}, [3]any{nf0, nfNULL, nf1337}},\n\t\t{\"decimal1\", \"DECIMAL(10,6) NOT NULL\", \"DECIMAL\", scanTypeString, false, 10, 6, [3]string{\"0\", \"13.37\", \"1234.123456\"}, [3]any{\"0.000000\", \"13.370000\", \"1234.123456\"}},\n\t\t{\"decimal1null\", \"DECIMAL(10,6)\", \"DECIMAL\", scanTypeNullString, true, 10, 6, [3]string{\"0\", \"NULL\", \"1234.123456\"}, [3]any{ns(\"0.000000\"), nsNULL, ns(\"1234.123456\")}},\n\t\t{\"decimal2\", \"DECIMAL(8,4) NOT NULL\", \"DECIMAL\", scanTypeString, false, 8, 4, [3]string{\"0\", \"13.37\", \"1234.123456\"}, [3]any{\"0.0000\", \"13.3700\", \"1234.1235\"}},\n\t\t{\"decimal2null\", \"DECIMAL(8,4)\", \"DECIMAL\", scanTypeNullString, true, 8, 4, [3]string{\"0\", \"NULL\", \"1234.123456\"}, [3]any{ns(\"0.0000\"), nsNULL, ns(\"1234.1235\")}},\n\t\t{\"decimal3\", \"DECIMAL(5,0) NOT NULL\", \"DECIMAL\", scanTypeString, false, 5, 0, [3]string{\"0\", \"13.37\", \"-12345.123456\"}, [3]any{\"0\", \"13\", \"-12345\"}},\n\t\t{\"decimal3null\", \"DECIMAL(5,0)\", \"DECIMAL\", scanTypeNullString, true, 5, 0, [3]string{\"0\", \"NULL\", \"-12345.123456\"}, [3]any{ns0, nsNULL, ns(\"-12345\")}},\n\t\t{\"char25null\", \"CHAR(25)\", \"CHAR\", scanTypeNullString, true, 0, 0, [3]string{\"0\", \"NULL\", \"'Test'\"}, [3]any{ns0, nsNULL, nsTest}},\n\t\t{\"varchar42\", \"VARCHAR(42) NOT NULL\", \"VARCHAR\", scanTypeString, false, 0, 0, [3]string{\"0\", \"'Test'\", \"42\"}, [3]any{\"0\", \"Test\", \"42\"}},\n\t\t{\"binary4null\", \"BINARY(4)\", \"BINARY\", scanTypeBytes, true, 0, 0, [3]string{\"0\", \"NULL\", \"'Test'\"}, [3]any{b0pad4, bNULL, bTest}},\n\t\t{\"varbinary42\", \"VARBINARY(42) NOT NULL\", \"VARBINARY\", scanTypeBytes, false, 0, 0, [3]string{\"0\", \"'Test'\", \"42\"}, [3]any{b0, bTest, b42}},\n\t\t{\"tinyblobnull\", \"TINYBLOB\", \"BLOB\", scanTypeBytes, true, 0, 0, [3]string{\"0\", \"NULL\", \"'Test'\"}, [3]any{b0, bNULL, bTest}},\n\t\t{\"tinytextnull\", \"TINYTEXT\", \"TEXT\", scanTypeNullString, true, 0, 0, [3]string{\"0\", \"NULL\", \"'Test'\"}, [3]any{ns0, nsNULL, nsTest}},\n\t\t{\"blobnull\", \"BLOB\", \"BLOB\", scanTypeBytes, true, 0, 0, [3]string{\"0\", \"NULL\", \"'Test'\"}, [3]any{b0, bNULL, bTest}},\n\t\t{\"textnull\", \"TEXT\", \"TEXT\", scanTypeNullString, true, 0, 0, [3]string{\"0\", \"NULL\", \"'Test'\"}, [3]any{ns0, nsNULL, nsTest}},\n\t\t{\"mediumblob\", \"MEDIUMBLOB NOT NULL\", \"BLOB\", scanTypeBytes, false, 0, 0, [3]string{\"0\", \"'Test'\", \"42\"}, [3]any{b0, bTest, b42}},\n\t\t{\"mediumtext\", \"MEDIUMTEXT NOT NULL\", \"TEXT\", scanTypeString, false, 0, 0, [3]string{\"0\", \"'Test'\", \"42\"}, [3]any{\"0\", \"Test\", \"42\"}},\n\t\t{\"longblob\", \"LONGBLOB NOT NULL\", \"BLOB\", scanTypeBytes, false, 0, 0, [3]string{\"0\", \"'Test'\", \"42\"}, [3]any{b0, bTest, b42}},\n\t\t{\"longtext\", \"LONGTEXT NOT NULL\", \"TEXT\", scanTypeString, false, 0, 0, [3]string{\"0\", \"'Test'\", \"42\"}, [3]any{\"0\", \"Test\", \"42\"}},\n\t\t{\"datetime\", \"DATETIME\", \"DATETIME\", scanTypeNullTime, true, 0, 0, [3]string{\"'2006-01-02 15:04:05'\", \"'2006-01-02 15:04:05.1'\", \"'2006-01-02 15:04:05.111111'\"}, [3]any{nt0, nt0, nt0}},\n\t\t{\"datetime2\", \"DATETIME(2)\", \"DATETIME\", scanTypeNullTime, true, 2, 2, [3]string{\"'2006-01-02 15:04:05'\", \"'2006-01-02 15:04:05.1'\", \"'2006-01-02 15:04:05.111111'\"}, [3]any{nt0, nt1, nt2}},\n\t\t{\"datetime6\", \"DATETIME(6)\", \"DATETIME\", scanTypeNullTime, true, 6, 6, [3]string{\"'2006-01-02 15:04:05'\", \"'2006-01-02 15:04:05.1'\", \"'2006-01-02 15:04:05.111111'\"}, [3]any{nt0, nt1, nt6}},\n\t\t{\"date\", \"DATE\", \"DATE\", scanTypeNullTime, true, 0, 0, [3]string{\"'2006-01-02'\", \"NULL\", \"'2006-03-04'\"}, [3]any{nd1, ndNULL, nd2}},\n\t\t{\"year\", \"YEAR NOT NULL\", \"YEAR\", scanTypeUint16, false, 0, 0, [3]string{\"2006\", \"2000\", \"1994\"}, [3]any{uint16(2006), uint16(2000), uint16(1994)}},\n\t\t{\"enum\", \"ENUM('', 'v1', 'v2')\", \"ENUM\", scanTypeNullString, true, 0, 0, [3]string{\"''\", \"'v1'\", \"'v2'\"}, [3]any{ns(\"\"), ns(\"v1\"), ns(\"v2\")}},\n\t\t{\"set\", \"set('', 'v1', 'v2')\", \"SET\", scanTypeNullString, true, 0, 0, [3]string{\"''\", \"'v1'\", \"'v1,v2'\"}, [3]any{ns(\"\"), ns(\"v1\"), ns(\"v1,v2\")}},\n\t}\n\n\tschema := \"\"\n\tvalues1 := \"\"\n\tvalues2 := \"\"\n\tvalues3 := \"\"\n\tfor _, column := range columns {\n\t\tschema += fmt.Sprintf(\"`%s` %s, \", column.name, column.fieldType)\n\t\tvalues1 += column.valuesIn[0] + \", \"\n\t\tvalues2 += column.valuesIn[1] + \", \"\n\t\tvalues3 += column.valuesIn[2] + \", \"\n\t}\n\tschema = schema[:len(schema)-2]\n\tvalues1 = values1[:len(values1)-2]\n\tvalues2 = values2[:len(values2)-2]\n\tvalues3 = values3[:len(values3)-2]\n\n\trunTests(t, dsn+\"&parseTime=true\", func(dbt *DBTest) {\n\t\tdbt.mustExec(\"CREATE TABLE test (\" + schema + \")\")\n\t\tdbt.mustExec(\"INSERT INTO test VALUES (\" + values1 + \"), (\" + values2 + \"), (\" + values3 + \")\")\n\n\t\trows, err := dbt.db.Query(\"SELECT * FROM test\")\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Query: %v\", err)\n\t\t}\n\n\t\ttt, err := rows.ColumnTypes()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"ColumnTypes: %v\", err)\n\t\t}\n\n\t\tif len(tt) != len(columns) {\n\t\t\tt.Fatalf(\"unexpected number of columns: expected %d, got %d\", len(columns), len(tt))\n\t\t}\n\n\t\ttypes := make([]reflect.Type, len(tt))\n\t\tfor i, tp := range tt {\n\t\t\tcolumn := columns[i]\n\n\t\t\t// Name\n\t\t\tname := tp.Name()\n\t\t\tif name != column.name {\n\t\t\t\tt.Errorf(\"column name mismatch %s != %s\", name, column.name)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// DatabaseTypeName\n\t\t\tdatabaseTypeName := tp.DatabaseTypeName()\n\t\t\tif databaseTypeName != column.databaseTypeName {\n\t\t\t\tt.Errorf(\"databasetypename name mismatch for column %q: %s != %s\", name, databaseTypeName, column.databaseTypeName)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// ScanType\n\t\t\tscanType := tp.ScanType()\n\t\t\tif scanType != column.scanType {\n\t\t\t\tif scanType == nil {\n\t\t\t\t\tt.Errorf(\"scantype is null for column %q\", name)\n\t\t\t\t} else {\n\t\t\t\t\tt.Errorf(\"scantype mismatch for column %q: %s != %s\", name, scanType.Name(), column.scanType.Name())\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttypes[i] = scanType\n\n\t\t\t// Nullable\n\t\t\tnullable, ok := tp.Nullable()\n\t\t\tif !ok {\n\t\t\t\tt.Errorf(\"nullable not ok %q\", name)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif nullable != column.nullable {\n\t\t\t\tt.Errorf(\"nullable mismatch for column %q: %t != %t\", name, nullable, column.nullable)\n\t\t\t}\n\n\t\t\t// Length\n\t\t\t// length, ok := tp.Length()\n\t\t\t// if length != column.length {\n\t\t\t// \tif !ok {\n\t\t\t// \t\tt.Errorf(\"length not ok for column %q\", name)\n\t\t\t// \t} else {\n\t\t\t// \t\tt.Errorf(\"length mismatch for column %q: %d != %d\", name, length, column.length)\n\t\t\t// \t}\n\t\t\t// \tcontinue\n\t\t\t// }\n\n\t\t\t// Precision and Scale\n\t\t\tprecision, scale, ok := tp.DecimalSize()\n\t\t\tif precision != column.precision {\n\t\t\t\tif !ok {\n\t\t\t\t\tt.Errorf(\"precision not ok for column %q\", name)\n\t\t\t\t} else {\n\t\t\t\t\tt.Errorf(\"precision mismatch for column %q: %d != %d\", name, precision, column.precision)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif scale != column.scale {\n\t\t\t\tif !ok {\n\t\t\t\t\tt.Errorf(\"scale not ok for column %q\", name)\n\t\t\t\t} else {\n\t\t\t\t\tt.Errorf(\"scale mismatch for column %q: %d != %d\", name, scale, column.scale)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\t// Avoid panic caused by nil scantype.\n\t\tif t.Failed() {\n\t\t\treturn\n\t\t}\n\t\tvalues := make([]any, len(tt))\n\t\tfor i := range values {\n\t\t\tvalues[i] = reflect.New(types[i]).Interface()\n\t\t}\n\t\ti := 0\n\t\tfor rows.Next() {\n\t\t\terr = rows.Scan(values...)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"failed to scan values in %v\", err)\n\t\t\t}\n\t\t\tfor j, value := range values {\n\t\t\t\tvalue := reflect.ValueOf(value).Elem().Interface()\n\t\t\t\tif !reflect.DeepEqual(value, columns[j].valuesOut[i]) {\n\t\t\t\t\tt.Errorf(\"row %d, column %d: %v != %v\", i, j, value, columns[j].valuesOut[i])\n\t\t\t\t}\n\t\t\t}\n\t\t\ti++\n\t\t}\n\t\tif i != 3 {\n\t\t\tt.Errorf(\"expected 3 rows, got %d\", i)\n\t\t}\n\n\t\tif err := rows.Close(); err != nil {\n\t\t\tt.Errorf(\"error closing rows: %s\", err)\n\t\t}\n\t})\n}\n\nfunc TestValuerWithValueReceiverGivenNilValue(t *testing.T) {\n\trunTestsParallel(t, dsn, func(dbt *DBTest, tbl string) {\n\t\tdbt.mustExec(\"CREATE TABLE \" + tbl + \" (value VARCHAR(255))\")\n\t\tdbt.db.Exec(\"INSERT INTO \"+tbl+\" VALUES (?)\", (*testValuer)(nil))\n\t\t// This test will panic on the INSERT if ConvertValue() does not check for typed nil before calling Value()\n\t})\n}\n\n// TestRawBytesAreNotModified checks for a race condition that arises when a query context\n// is canceled while a user is calling rows.Scan. This is a more stringent test than the one\n// proposed in https://github.com/golang/go/issues/23519. Here we're explicitly using\n// `sql.RawBytes` to check the contents of our internal buffers are not modified after an implicit\n// call to `Rows.Close`, so Context cancellation should **not** invalidate the backing buffers.\nfunc TestRawBytesAreNotModified(t *testing.T) {\n\tconst blob = \"abcdefghijklmnop\"\n\tconst contextRaceIterations = 20\n\tconst blobSize = defaultBufSize * 3 / 4 // Second row overwrites first row.\n\tconst insertRows = 4\n\n\tvar sqlBlobs = [2]string{\n\t\tstrings.Repeat(blob, blobSize/len(blob)),\n\t\tstrings.Repeat(strings.ToUpper(blob), blobSize/len(blob)),\n\t}\n\n\trunTests(t, dsn, func(dbt *DBTest) {\n\t\tdbt.mustExec(\"CREATE TABLE test (id int, value BLOB) CHARACTER SET utf8\")\n\t\tfor i := range insertRows {\n\t\t\tdbt.mustExec(\"INSERT INTO test VALUES (?, ?)\", i+1, sqlBlobs[i&1])\n\t\t}\n\n\t\tfor i := range contextRaceIterations {\n\t\t\tfunc() {\n\t\t\t\tctx, cancel := context.WithCancel(context.Background())\n\t\t\t\tdefer cancel()\n\n\t\t\t\trows, err := dbt.db.QueryContext(ctx, `SELECT id, value FROM test`)\n\t\t\t\tif err != nil {\n\t\t\t\t\tdbt.Fatal(err)\n\t\t\t\t}\n\t\t\t\tdefer rows.Close()\n\n\t\t\t\tvar b int\n\t\t\t\tvar raw sql.RawBytes\n\t\t\t\tif !rows.Next() {\n\t\t\t\t\tdbt.Fatal(\"expected at least one row\")\n\t\t\t\t}\n\t\t\t\tif err := rows.Scan(&b, &raw); err != nil {\n\t\t\t\t\tdbt.Fatal(err)\n\t\t\t\t}\n\n\t\t\t\tbefore := string(raw)\n\t\t\t\t// Ensure cancelling the query does not corrupt the contents of `raw`\n\t\t\t\tcancel()\n\t\t\t\ttime.Sleep(time.Microsecond * 100)\n\t\t\t\tafter := string(raw)\n\n\t\t\t\tif before != after {\n\t\t\t\t\tdbt.Fatalf(\"the backing storage for sql.RawBytes has been modified (i=%v)\", i)\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t})\n}\n\nvar _ driver.DriverContext = &MySQLDriver{}\n\ntype dialCtxKey struct{}\n\nfunc TestConnectorObeysDialTimeouts(t *testing.T) {\n\tif !available {\n\t\tt.Skipf(\"MySQL server not running on %s\", netAddr)\n\t}\n\n\tRegisterDialContext(\"dialctxtest\", func(ctx context.Context, addr string) (net.Conn, error) {\n\t\tvar d net.Dialer\n\t\tif !ctx.Value(dialCtxKey{}).(bool) {\n\t\t\treturn nil, fmt.Errorf(\"test error: query context is not propagated to our dialer\")\n\t\t}\n\t\treturn d.DialContext(ctx, prot, addr)\n\t})\n\n\tdb, err := sql.Open(driverNameTest, fmt.Sprintf(\"%s:%s@dialctxtest(%s)/%s?timeout=30s\", user, pass, addr, dbname))\n\tif err != nil {\n\t\tt.Fatalf(\"error connecting: %s\", err.Error())\n\t}\n\tdefer db.Close()\n\n\tctx := context.WithValue(context.Background(), dialCtxKey{}, true)\n\n\t_, err = db.ExecContext(ctx, \"DO 1\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc configForTests(t *testing.T) *Config {\n\tif !available {\n\t\tt.Skipf(\"MySQL server not running on %s\", netAddr)\n\t}\n\n\tmycnf := NewConfig()\n\tmycnf.User = user\n\tmycnf.Passwd = pass\n\tmycnf.Addr = addr\n\tmycnf.Net = prot\n\tmycnf.DBName = dbname\n\treturn mycnf\n}\n\nfunc TestNewConnector(t *testing.T) {\n\tmycnf := configForTests(t)\n\tconn, err := NewConnector(mycnf)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tdb := sql.OpenDB(conn)\n\tdefer db.Close()\n\n\tif err := db.Ping(); err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\ntype slowConnection struct {\n\tnet.Conn\n\tslowdown time.Duration\n}\n\nfunc (sc *slowConnection) Read(b []byte) (int, error) {\n\ttime.Sleep(sc.slowdown)\n\treturn sc.Conn.Read(b)\n}\n\ntype connectorHijack struct {\n\tdriver.Connector\n\tconnErr error\n}\n\nfunc (cw *connectorHijack) Connect(ctx context.Context) (driver.Conn, error) {\n\tvar conn driver.Conn\n\tconn, cw.connErr = cw.Connector.Connect(ctx)\n\treturn conn, cw.connErr\n}\n\nfunc TestConnectorTimeoutsDuringOpen(t *testing.T) {\n\tRegisterDialContext(\"slowconn\", func(ctx context.Context, addr string) (net.Conn, error) {\n\t\tvar d net.Dialer\n\t\tconn, err := d.DialContext(ctx, prot, addr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn &slowConnection{Conn: conn, slowdown: 100 * time.Millisecond}, nil\n\t})\n\n\tmycnf := configForTests(t)\n\tmycnf.Net = \"slowconn\"\n\n\tconn, err := NewConnector(mycnf)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\thijack := &connectorHijack{Connector: conn}\n\n\tdb := sql.OpenDB(hijack)\n\tdefer db.Close()\n\n\tctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)\n\tdefer cancel()\n\n\t_, err = db.ExecContext(ctx, \"DO 1\")\n\tif err != context.DeadlineExceeded {\n\t\tt.Fatalf(\"ExecContext should have timed out\")\n\t}\n\tif hijack.connErr != context.DeadlineExceeded {\n\t\tt.Fatalf(\"(*Connector).Connect should have timed out\")\n\t}\n}\n\n// A connection which can only be closed.\ntype dummyConnection struct {\n\tnet.Conn\n\tclosed bool\n}\n\nfunc (d *dummyConnection) Close() error {\n\td.closed = true\n\treturn nil\n}\n\nfunc TestConnectorTimeoutsWatchCancel(t *testing.T) {\n\tvar (\n\t\tcancel  func()           // Used to cancel the context just after connecting.\n\t\tcreated *dummyConnection // The created connection.\n\t)\n\n\tRegisterDialContext(\"TestConnectorTimeoutsWatchCancel\", func(ctx context.Context, addr string) (net.Conn, error) {\n\t\t// Canceling at this time triggers the watchCancel error branch in Connect().\n\t\tcancel()\n\t\tcreated = &dummyConnection{}\n\t\treturn created, nil\n\t})\n\n\tmycnf := NewConfig()\n\tmycnf.User = \"root\"\n\tmycnf.Addr = \"foo\"\n\tmycnf.Net = \"TestConnectorTimeoutsWatchCancel\"\n\n\tconn, err := NewConnector(mycnf)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tdb := sql.OpenDB(conn)\n\tdefer db.Close()\n\n\tvar ctx context.Context\n\tctx, cancel = context.WithCancel(context.Background())\n\tdefer cancel()\n\n\tif _, err := db.Conn(ctx); err != context.Canceled {\n\t\tt.Errorf(\"got %v, want context.Canceled\", err)\n\t}\n\n\tif created == nil {\n\t\tt.Fatal(\"no connection created\")\n\t}\n\tif !created.closed {\n\t\tt.Errorf(\"connection not closed\")\n\t}\n}\n\nfunc TestConnectionAttributes(t *testing.T) {\n\tif !available {\n\t\tt.Skipf(\"MySQL server not running on %s\", netAddr)\n\t}\n\n\tdefaultAttrs := []string{\n\t\tconnAttrClientName,\n\t\tconnAttrOS,\n\t\tconnAttrPlatform,\n\t\tconnAttrPid,\n\t\tconnAttrServerHost,\n\t}\n\thost, _, _ := net.SplitHostPort(addr)\n\tdefaultAttrValues := []string{\n\t\tconnAttrClientNameValue,\n\t\tconnAttrOSValue,\n\t\tconnAttrPlatformValue,\n\t\tstrconv.Itoa(os.Getpid()),\n\t\thost,\n\t}\n\n\tcustomAttrs := []string{\"attr1\", \"fo/o\"}\n\tcustomAttrValues := []string{\"value1\", \"bo/o\"}\n\n\tcustomAttrStrs := make([]string, len(customAttrs))\n\tfor i := range customAttrs {\n\t\tcustomAttrStrs[i] = fmt.Sprintf(\"%s:%s\", customAttrs[i], customAttrValues[i])\n\t}\n\tdsn += \"&connectionAttributes=\" + url.QueryEscape(strings.Join(customAttrStrs, \",\"))\n\n\tvar db *sql.DB\n\tif _, err := ParseDSN(dsn); err != errInvalidDSNUnsafeCollation {\n\t\tdb, err = sql.Open(driverNameTest, dsn)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"error connecting: %s\", err.Error())\n\t\t}\n\t\tdefer db.Close()\n\t}\n\n\tdbt := &DBTest{t, db}\n\n\tvar varName string\n\tvar varValue string\n\terr := dbt.db.QueryRow(\"SHOW VARIABLES LIKE 'performance_schema'\").Scan(&varName, &varValue)\n\tif err != nil {\n\t\tt.Fatalf(\"error: %s\", err.Error())\n\t}\n\tif varValue != \"ON\" {\n\t\tt.Skipf(\"Performance schema is not enabled. skipping\")\n\t}\n\tqueryString := \"SELECT ATTR_NAME, ATTR_VALUE FROM performance_schema.session_account_connect_attrs WHERE PROCESSLIST_ID = CONNECTION_ID()\"\n\trows := dbt.mustQuery(queryString)\n\tdefer rows.Close()\n\n\trowsMap := make(map[string]string)\n\tfor rows.Next() {\n\t\tvar attrName, attrValue string\n\t\trows.Scan(&attrName, &attrValue)\n\t\trowsMap[attrName] = attrValue\n\t}\n\n\tconnAttrs := slices.Concat(defaultAttrs, customAttrs)\n\texpectedAttrValues := slices.Concat(defaultAttrValues, customAttrValues)\n\tfor i := range connAttrs {\n\t\tif gotValue := rowsMap[connAttrs[i]]; gotValue != expectedAttrValues[i] {\n\t\t\tdbt.Errorf(\"expected %q, got %q\", expectedAttrValues[i], gotValue)\n\t\t}\n\t}\n}\n\nfunc TestErrorInMultiResult(t *testing.T) {\n\tif !available {\n\t\tt.Skipf(\"MySQL server not running on %s\", netAddr)\n\t}\n\t// https://github.com/go-sql-driver/mysql/issues/1361\n\tvar db *sql.DB\n\tif _, err := ParseDSN(dsn); err != errInvalidDSNUnsafeCollation {\n\t\tdb, err = sql.Open(\"mysql\", dsn)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"error connecting: %s\", err.Error())\n\t\t}\n\t\tdefer db.Close()\n\t}\n\n\tdbt := &DBTest{t, db}\n\tquery := `\nCREATE PROCEDURE test_proc1()\nBEGIN\n\tSELECT 1,2;\n\tSELECT 3,4;\n\tSIGNAL SQLSTATE '10000' SET MESSAGE_TEXT = \"some error\",  MYSQL_ERRNO = 10000;\nEND;\n`\n\trunCallCommand(dbt, query, \"test_proc1\")\n}\n\nfunc runCallCommand(dbt *DBTest, query, name string) {\n\tdbt.mustExec(fmt.Sprintf(\"DROP PROCEDURE IF EXISTS %s\", name))\n\tdbt.mustExec(query)\n\tdefer dbt.mustExec(\"DROP PROCEDURE \" + name)\n\trows, err := dbt.db.Query(fmt.Sprintf(\"CALL %s\", name))\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t}\n\tfor rows.NextResultSet() {\n\t\tfor rows.Next() {\n\t\t}\n\t}\n}\n\nfunc TestIssue1567(t *testing.T) {\n\t// enable TLS.\n\trunTests(t, dsn+\"&tls=skip-verify\", func(dbt *DBTest) {\n\t\tvar max int\n\t\terr := dbt.db.QueryRow(\"SELECT @@max_connections\").Scan(&max)\n\t\tif err != nil {\n\t\t\tdbt.Fatalf(\"%s\", err.Error())\n\t\t}\n\n\t\t// disable connection pooling.\n\t\t// data race happens when new connection is created.\n\t\tdbt.db.SetMaxIdleConns(0)\n\n\t\t// estimate round trip time.\n\t\tstart := time.Now()\n\t\tif err := dbt.db.PingContext(context.Background()); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\trtt := time.Since(start)\n\t\tif rtt <= 0 {\n\t\t\t// In some environments, rtt may become 0, so set it to at least 1ms.\n\t\t\trtt = time.Millisecond\n\t\t}\n\n\t\tcount := 1000\n\t\tif testing.Short() {\n\t\t\tcount = 10\n\t\t}\n\t\tif count > max {\n\t\t\tcount = max\n\t\t}\n\n\t\tfor range count {\n\t\t\ttimeout := time.Duration(mrand.Int63n(int64(rtt)))\n\t\t\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\t\t\tdbt.db.PingContext(ctx)\n\t\t\tcancel()\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "dsn.go",
    "content": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2016 The Go-MySQL-Driver Authors. All rights reserved.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at http://mozilla.org/MPL/2.0/.\n\npackage mysql\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"crypto/rsa\"\n\t\"crypto/tls\"\n\t\"errors\"\n\t\"fmt\"\n\t\"math/big\"\n\t\"net\"\n\t\"net/url\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar (\n\terrInvalidDSNUnescaped       = errors.New(\"invalid DSN: did you forget to escape a param value?\")\n\terrInvalidDSNAddr            = errors.New(\"invalid DSN: network address not terminated (missing closing brace)\")\n\terrInvalidDSNNoSlash         = errors.New(\"invalid DSN: missing the slash separating the database name\")\n\terrInvalidDSNUnsafeCollation = errors.New(\"invalid DSN: interpolateParams can not be used with unsafe collations\")\n)\n\n// Config is a configuration parsed from a DSN string.\n// If a new Config is created instead of being parsed from a DSN string,\n// the NewConfig function should be used, which sets default values.\ntype Config struct {\n\t// non boolean fields\n\n\tUser                 string            // Username\n\tPasswd               string            // Password (requires User)\n\tNet                  string            // Network (e.g. \"tcp\", \"tcp6\", \"unix\". default: \"tcp\")\n\tAddr                 string            // Address (default: \"127.0.0.1:3306\" for \"tcp\" and \"/tmp/mysql.sock\" for \"unix\")\n\tDBName               string            // Database name\n\tParams               map[string]string // Connection parameters\n\tConnectionAttributes string            // Connection Attributes, comma-delimited string of user-defined \"key:value\" pairs\n\tCollation            string            // Connection collation. When set, this will be set in SET NAMES <charset> COLLATE <collation> query\n\tLoc                  *time.Location    // Location for time.Time values\n\tMaxAllowedPacket     int               // Max packet size allowed\n\tServerPubKey         string            // Server public key name\n\tTLSConfig            string            // TLS configuration name\n\tTLS                  *tls.Config       // TLS configuration, its priority is higher than TLSConfig\n\tTimeout              time.Duration     // Dial timeout\n\tReadTimeout          time.Duration     // I/O read timeout\n\tWriteTimeout         time.Duration     // I/O write timeout\n\tLogger               Logger            // Logger\n\t// DialFunc specifies the dial function for creating connections\n\tDialFunc func(ctx context.Context, network, addr string) (net.Conn, error)\n\n\t// boolean fields\n\n\tAllowAllFiles            bool // Allow all files to be used with LOAD DATA LOCAL INFILE\n\tAllowCleartextPasswords  bool // Allows the cleartext client side plugin\n\tAllowFallbackToPlaintext bool // Allows fallback to unencrypted connection if server does not support TLS\n\tAllowNativePasswords     bool // Allows the native password authentication method\n\tAllowOldPasswords        bool // Allows the old insecure password method\n\tCheckConnLiveness        bool // Check connections for liveness before using them\n\tClientFoundRows          bool // Return number of matching rows instead of rows changed\n\tColumnsWithAlias         bool // Prepend table alias to column names\n\tInterpolateParams        bool // Interpolate placeholders into query string\n\tMultiStatements          bool // Allow multiple statements in one query\n\tParseTime                bool // Parse time values to time.Time\n\tRejectReadOnly           bool // Reject read-only connections\n\n\t// unexported fields. new options should be come here.\n\t// boolean first. alphabetical order.\n\n\tcompress bool // Enable zlib compression\n\n\tbeforeConnect func(context.Context, *Config) error // Invoked before a connection is established\n\tpubKey        *rsa.PublicKey                       // Server public key\n\ttimeTruncate  time.Duration                        // Truncate time.Time values to the specified duration\n\tcharsets      []string                             // Connection charset. When set, this will be set in SET NAMES <charset> query\n}\n\n// Functional Options Pattern\n// https://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis\ntype Option func(*Config) error\n\n// NewConfig creates a new Config and sets default values.\nfunc NewConfig() *Config {\n\tcfg := &Config{\n\t\tLoc:                  time.UTC,\n\t\tMaxAllowedPacket:     defaultMaxAllowedPacket,\n\t\tLogger:               defaultLogger,\n\t\tAllowNativePasswords: true,\n\t\tCheckConnLiveness:    true,\n\t}\n\treturn cfg\n}\n\n// Apply applies the given options to the Config object.\nfunc (c *Config) Apply(opts ...Option) error {\n\tfor _, opt := range opts {\n\t\terr := opt(c)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n// TimeTruncate sets the time duration to truncate time.Time values in\n// query parameters.\nfunc TimeTruncate(d time.Duration) Option {\n\treturn func(cfg *Config) error {\n\t\tcfg.timeTruncate = d\n\t\treturn nil\n\t}\n}\n\n// BeforeConnect sets the function to be invoked before a connection is established.\nfunc BeforeConnect(fn func(context.Context, *Config) error) Option {\n\treturn func(cfg *Config) error {\n\t\tcfg.beforeConnect = fn\n\t\treturn nil\n\t}\n}\n\n// EnableCompress sets the compression mode.\nfunc EnableCompression(yes bool) Option {\n\treturn func(cfg *Config) error {\n\t\tcfg.compress = yes\n\t\treturn nil\n\t}\n}\n\n// Charset sets the connection charset and collation.\n//\n// charset is the connection charset.\n// collation is the connection collation. It can be null or empty string.\n//\n// When collation is not specified, `SET NAMES <charset>` command is sent when the connection is established.\n// When collation is specified, `SET NAMES <charset> COLLATE <collation>` command is sent when the connection is established.\nfunc Charset(charset, collation string) Option {\n\treturn func(cfg *Config) error {\n\t\tcfg.charsets = []string{charset}\n\t\tcfg.Collation = collation\n\t\treturn nil\n\t}\n}\n\nfunc (cfg *Config) Clone() *Config {\n\tcp := *cfg\n\tif cp.TLS != nil {\n\t\tcp.TLS = cfg.TLS.Clone()\n\t}\n\tif len(cp.Params) > 0 {\n\t\tcp.Params = make(map[string]string, len(cfg.Params))\n\t\tfor k, v := range cfg.Params {\n\t\t\tcp.Params[k] = v\n\t\t}\n\t}\n\tif cfg.pubKey != nil {\n\t\tcp.pubKey = &rsa.PublicKey{\n\t\t\tN: new(big.Int).Set(cfg.pubKey.N),\n\t\t\tE: cfg.pubKey.E,\n\t\t}\n\t}\n\treturn &cp\n}\n\nfunc (cfg *Config) normalize() error {\n\tif cfg.InterpolateParams && cfg.Collation != \"\" && unsafeCollations[cfg.Collation] {\n\t\treturn errInvalidDSNUnsafeCollation\n\t}\n\n\t// Set default network if empty\n\tif cfg.Net == \"\" {\n\t\tcfg.Net = \"tcp\"\n\t}\n\n\t// Set default address if empty\n\tif cfg.Addr == \"\" {\n\t\tswitch cfg.Net {\n\t\tcase \"tcp\":\n\t\t\tcfg.Addr = \"127.0.0.1:3306\"\n\t\tcase \"unix\":\n\t\t\tcfg.Addr = \"/tmp/mysql.sock\"\n\t\tdefault:\n\t\t\treturn errors.New(\"default addr for network '\" + cfg.Net + \"' unknown\")\n\t\t}\n\t} else if cfg.Net == \"tcp\" {\n\t\tcfg.Addr = ensureHavePort(cfg.Addr)\n\t}\n\n\tif cfg.TLS == nil {\n\t\tswitch cfg.TLSConfig {\n\t\tcase \"false\", \"\":\n\t\t\t// don't set anything\n\t\tcase \"true\":\n\t\t\tcfg.TLS = &tls.Config{}\n\t\tcase \"skip-verify\":\n\t\t\tcfg.TLS = &tls.Config{InsecureSkipVerify: true}\n\t\tcase \"preferred\":\n\t\t\tcfg.TLS = &tls.Config{InsecureSkipVerify: true}\n\t\t\tcfg.AllowFallbackToPlaintext = true\n\t\tdefault:\n\t\t\tcfg.TLS = getTLSConfigClone(cfg.TLSConfig)\n\t\t\tif cfg.TLS == nil {\n\t\t\t\treturn errors.New(\"invalid value / unknown config name: \" + cfg.TLSConfig)\n\t\t\t}\n\t\t}\n\t}\n\n\tif cfg.TLS != nil && cfg.TLS.ServerName == \"\" && !cfg.TLS.InsecureSkipVerify {\n\t\thost, _, err := net.SplitHostPort(cfg.Addr)\n\t\tif err == nil {\n\t\t\tcfg.TLS.ServerName = host\n\t\t}\n\t}\n\n\tif cfg.ServerPubKey != \"\" {\n\t\tcfg.pubKey = getServerPubKey(cfg.ServerPubKey)\n\t\tif cfg.pubKey == nil {\n\t\t\treturn errors.New(\"invalid value / unknown server pub key name: \" + cfg.ServerPubKey)\n\t\t}\n\t}\n\n\tif cfg.Logger == nil {\n\t\tcfg.Logger = defaultLogger\n\t}\n\n\treturn nil\n}\n\nfunc writeDSNParam(buf *bytes.Buffer, hasParam *bool, name, value string) {\n\tbuf.Grow(1 + len(name) + 1 + len(value))\n\tif !*hasParam {\n\t\t*hasParam = true\n\t\tbuf.WriteByte('?')\n\t} else {\n\t\tbuf.WriteByte('&')\n\t}\n\tbuf.WriteString(name)\n\tbuf.WriteByte('=')\n\tbuf.WriteString(value)\n}\n\n// FormatDSN formats the given Config into a DSN string which can be passed to\n// the driver.\n//\n// Note: use [NewConnector] and [database/sql.OpenDB] to open a connection from a [*Config].\nfunc (cfg *Config) FormatDSN() string {\n\tvar buf bytes.Buffer\n\n\t// [username[:password]@]\n\tif len(cfg.User) > 0 {\n\t\tbuf.WriteString(cfg.User)\n\t\tif len(cfg.Passwd) > 0 {\n\t\t\tbuf.WriteByte(':')\n\t\t\tbuf.WriteString(cfg.Passwd)\n\t\t}\n\t\tbuf.WriteByte('@')\n\t}\n\n\t// [protocol[(address)]]\n\tif len(cfg.Net) > 0 {\n\t\tbuf.WriteString(cfg.Net)\n\t\tif len(cfg.Addr) > 0 {\n\t\t\tbuf.WriteByte('(')\n\t\t\tbuf.WriteString(cfg.Addr)\n\t\t\tbuf.WriteByte(')')\n\t\t}\n\t}\n\n\t// /dbname\n\tbuf.WriteByte('/')\n\tbuf.WriteString(url.PathEscape(cfg.DBName))\n\n\t// [?param1=value1&...&paramN=valueN]\n\thasParam := false\n\n\tif cfg.AllowAllFiles {\n\t\thasParam = true\n\t\tbuf.WriteString(\"?allowAllFiles=true\")\n\t}\n\n\tif cfg.AllowCleartextPasswords {\n\t\twriteDSNParam(&buf, &hasParam, \"allowCleartextPasswords\", \"true\")\n\t}\n\n\tif cfg.AllowFallbackToPlaintext {\n\t\twriteDSNParam(&buf, &hasParam, \"allowFallbackToPlaintext\", \"true\")\n\t}\n\n\tif !cfg.AllowNativePasswords {\n\t\twriteDSNParam(&buf, &hasParam, \"allowNativePasswords\", \"false\")\n\t}\n\n\tif cfg.AllowOldPasswords {\n\t\twriteDSNParam(&buf, &hasParam, \"allowOldPasswords\", \"true\")\n\t}\n\n\tif !cfg.CheckConnLiveness {\n\t\twriteDSNParam(&buf, &hasParam, \"checkConnLiveness\", \"false\")\n\t}\n\n\tif cfg.ClientFoundRows {\n\t\twriteDSNParam(&buf, &hasParam, \"clientFoundRows\", \"true\")\n\t}\n\n\tif charsets := cfg.charsets; len(charsets) > 0 {\n\t\twriteDSNParam(&buf, &hasParam, \"charset\", strings.Join(charsets, \",\"))\n\t}\n\n\tif col := cfg.Collation; col != \"\" {\n\t\twriteDSNParam(&buf, &hasParam, \"collation\", col)\n\t}\n\n\tif cfg.ColumnsWithAlias {\n\t\twriteDSNParam(&buf, &hasParam, \"columnsWithAlias\", \"true\")\n\t}\n\n\tif cfg.ConnectionAttributes != \"\" {\n\t\twriteDSNParam(&buf, &hasParam, \"connectionAttributes\", url.QueryEscape(cfg.ConnectionAttributes))\n\t}\n\n\tif cfg.compress {\n\t\twriteDSNParam(&buf, &hasParam, \"compress\", \"true\")\n\t}\n\n\tif cfg.InterpolateParams {\n\t\twriteDSNParam(&buf, &hasParam, \"interpolateParams\", \"true\")\n\t}\n\n\tif cfg.Loc != time.UTC && cfg.Loc != nil {\n\t\twriteDSNParam(&buf, &hasParam, \"loc\", url.QueryEscape(cfg.Loc.String()))\n\t}\n\n\tif cfg.MultiStatements {\n\t\twriteDSNParam(&buf, &hasParam, \"multiStatements\", \"true\")\n\t}\n\n\tif cfg.ParseTime {\n\t\twriteDSNParam(&buf, &hasParam, \"parseTime\", \"true\")\n\t}\n\n\tif cfg.timeTruncate > 0 {\n\t\twriteDSNParam(&buf, &hasParam, \"timeTruncate\", cfg.timeTruncate.String())\n\t}\n\n\tif cfg.ReadTimeout > 0 {\n\t\twriteDSNParam(&buf, &hasParam, \"readTimeout\", cfg.ReadTimeout.String())\n\t}\n\n\tif cfg.RejectReadOnly {\n\t\twriteDSNParam(&buf, &hasParam, \"rejectReadOnly\", \"true\")\n\t}\n\n\tif len(cfg.ServerPubKey) > 0 {\n\t\twriteDSNParam(&buf, &hasParam, \"serverPubKey\", url.QueryEscape(cfg.ServerPubKey))\n\t}\n\n\tif cfg.Timeout > 0 {\n\t\twriteDSNParam(&buf, &hasParam, \"timeout\", cfg.Timeout.String())\n\t}\n\n\tif len(cfg.TLSConfig) > 0 {\n\t\twriteDSNParam(&buf, &hasParam, \"tls\", url.QueryEscape(cfg.TLSConfig))\n\t}\n\n\tif cfg.WriteTimeout > 0 {\n\t\twriteDSNParam(&buf, &hasParam, \"writeTimeout\", cfg.WriteTimeout.String())\n\t}\n\n\tif cfg.MaxAllowedPacket != defaultMaxAllowedPacket {\n\t\twriteDSNParam(&buf, &hasParam, \"maxAllowedPacket\", strconv.Itoa(cfg.MaxAllowedPacket))\n\t}\n\n\t// other params\n\tif cfg.Params != nil {\n\t\tvar params []string\n\t\tfor param := range cfg.Params {\n\t\t\tparams = append(params, param)\n\t\t}\n\t\tsort.Strings(params)\n\t\tfor _, param := range params {\n\t\t\twriteDSNParam(&buf, &hasParam, param, url.QueryEscape(cfg.Params[param]))\n\t\t}\n\t}\n\n\treturn buf.String()\n}\n\n// ParseDSN parses the DSN string to a Config\nfunc ParseDSN(dsn string) (cfg *Config, err error) {\n\t// New config with some default values\n\tcfg = NewConfig()\n\n\t// [user[:password]@][net[(addr)]]/dbname[?param1=value1&paramN=valueN]\n\t// Find the last '/' (since the password or the net addr might contain a '/')\n\tfoundSlash := false\n\tfor i := len(dsn) - 1; i >= 0; i-- {\n\t\tif dsn[i] == '/' {\n\t\t\tfoundSlash = true\n\t\t\tvar j, k int\n\n\t\t\t// left part is empty if i <= 0\n\t\t\tif i > 0 {\n\t\t\t\t// [username[:password]@][protocol[(address)]]\n\t\t\t\t// Find the last '@' in dsn[:i]\n\t\t\t\tfor j = i; j >= 0; j-- {\n\t\t\t\t\tif dsn[j] == '@' {\n\t\t\t\t\t\t// username[:password]\n\t\t\t\t\t\t// Find the first ':' in dsn[:j]\n\t\t\t\t\t\tfor k = 0; k < j; k++ { // We cannot use k = range j here, because we use dsn[:k] below\n\t\t\t\t\t\t\tif dsn[k] == ':' {\n\t\t\t\t\t\t\t\tcfg.Passwd = dsn[k+1 : j]\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcfg.User = dsn[:k]\n\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// [protocol[(address)]]\n\t\t\t\t// Find the first '(' in dsn[j+1:i]\n\t\t\t\tfor k = j + 1; k < i; k++ {\n\t\t\t\t\tif dsn[k] == '(' {\n\t\t\t\t\t\t// dsn[i-1] must be == ')' if an address is specified\n\t\t\t\t\t\tif dsn[i-1] != ')' {\n\t\t\t\t\t\t\tif strings.ContainsRune(dsn[k+1:i], ')') {\n\t\t\t\t\t\t\t\treturn nil, errInvalidDSNUnescaped\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn nil, errInvalidDSNAddr\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcfg.Addr = dsn[k+1 : i-1]\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcfg.Net = dsn[j+1 : k]\n\t\t\t}\n\n\t\t\t// dbname[?param1=value1&...&paramN=valueN]\n\t\t\t// Find the first '?' in dsn[i+1:]\n\t\t\tfor j = i + 1; j < len(dsn); j++ {\n\t\t\t\tif dsn[j] == '?' {\n\t\t\t\t\tif err = parseDSNParams(cfg, dsn[j+1:]); err != nil {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdbname := dsn[i+1 : j]\n\t\t\tif cfg.DBName, err = url.PathUnescape(dbname); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"invalid dbname %q: %w\", dbname, err)\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !foundSlash && len(dsn) > 0 {\n\t\treturn nil, errInvalidDSNNoSlash\n\t}\n\n\tif err = cfg.normalize(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn\n}\n\n// parseDSNParams parses the DSN \"query string\"\n// Values must be url.QueryEscape'ed\nfunc parseDSNParams(cfg *Config, params string) (err error) {\n\tfor _, v := range strings.Split(params, \"&\") {\n\t\tkey, value, found := strings.Cut(v, \"=\")\n\t\tif !found {\n\t\t\tcontinue\n\t\t}\n\n\t\t// cfg params\n\t\tswitch key {\n\t\t// Disable INFILE allowlist / enable all files\n\t\tcase \"allowAllFiles\":\n\t\t\tvar isBool bool\n\t\t\tcfg.AllowAllFiles, isBool = readBool(value)\n\t\t\tif !isBool {\n\t\t\t\treturn errors.New(\"invalid bool value: \" + value)\n\t\t\t}\n\n\t\t// Use cleartext authentication mode (MySQL 5.5.10+)\n\t\tcase \"allowCleartextPasswords\":\n\t\t\tvar isBool bool\n\t\t\tcfg.AllowCleartextPasswords, isBool = readBool(value)\n\t\t\tif !isBool {\n\t\t\t\treturn errors.New(\"invalid bool value: \" + value)\n\t\t\t}\n\n\t\t// Allow fallback to unencrypted connection if server does not support TLS\n\t\tcase \"allowFallbackToPlaintext\":\n\t\t\tvar isBool bool\n\t\t\tcfg.AllowFallbackToPlaintext, isBool = readBool(value)\n\t\t\tif !isBool {\n\t\t\t\treturn errors.New(\"invalid bool value: \" + value)\n\t\t\t}\n\n\t\t// Use native password authentication\n\t\tcase \"allowNativePasswords\":\n\t\t\tvar isBool bool\n\t\t\tcfg.AllowNativePasswords, isBool = readBool(value)\n\t\t\tif !isBool {\n\t\t\t\treturn errors.New(\"invalid bool value: \" + value)\n\t\t\t}\n\n\t\t// Use old authentication mode (pre MySQL 4.1)\n\t\tcase \"allowOldPasswords\":\n\t\t\tvar isBool bool\n\t\t\tcfg.AllowOldPasswords, isBool = readBool(value)\n\t\t\tif !isBool {\n\t\t\t\treturn errors.New(\"invalid bool value: \" + value)\n\t\t\t}\n\n\t\t// Check connections for Liveness before using them\n\t\tcase \"checkConnLiveness\":\n\t\t\tvar isBool bool\n\t\t\tcfg.CheckConnLiveness, isBool = readBool(value)\n\t\t\tif !isBool {\n\t\t\t\treturn errors.New(\"invalid bool value: \" + value)\n\t\t\t}\n\n\t\t// Switch \"rowsAffected\" mode\n\t\tcase \"clientFoundRows\":\n\t\t\tvar isBool bool\n\t\t\tcfg.ClientFoundRows, isBool = readBool(value)\n\t\t\tif !isBool {\n\t\t\t\treturn errors.New(\"invalid bool value: \" + value)\n\t\t\t}\n\n\t\t// charset\n\t\tcase \"charset\":\n\t\t\tcfg.charsets = strings.Split(value, \",\")\n\n\t\t// Collation\n\t\tcase \"collation\":\n\t\t\tcfg.Collation = value\n\n\t\tcase \"columnsWithAlias\":\n\t\t\tvar isBool bool\n\t\t\tcfg.ColumnsWithAlias, isBool = readBool(value)\n\t\t\tif !isBool {\n\t\t\t\treturn errors.New(\"invalid bool value: \" + value)\n\t\t\t}\n\n\t\t// Compression\n\t\tcase \"compress\":\n\t\t\tvar isBool bool\n\t\t\tcfg.compress, isBool = readBool(value)\n\t\t\tif !isBool {\n\t\t\t\treturn errors.New(\"invalid bool value: \" + value)\n\t\t\t}\n\n\t\t// Enable client side placeholder substitution\n\t\tcase \"interpolateParams\":\n\t\t\tvar isBool bool\n\t\t\tcfg.InterpolateParams, isBool = readBool(value)\n\t\t\tif !isBool {\n\t\t\t\treturn errors.New(\"invalid bool value: \" + value)\n\t\t\t}\n\n\t\t// Time Location\n\t\tcase \"loc\":\n\t\t\tif value, err = url.QueryUnescape(value); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcfg.Loc, err = time.LoadLocation(value)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t// multiple statements in one query\n\t\tcase \"multiStatements\":\n\t\t\tvar isBool bool\n\t\t\tcfg.MultiStatements, isBool = readBool(value)\n\t\t\tif !isBool {\n\t\t\t\treturn errors.New(\"invalid bool value: \" + value)\n\t\t\t}\n\n\t\t// time.Time parsing\n\t\tcase \"parseTime\":\n\t\t\tvar isBool bool\n\t\t\tcfg.ParseTime, isBool = readBool(value)\n\t\t\tif !isBool {\n\t\t\t\treturn errors.New(\"invalid bool value: \" + value)\n\t\t\t}\n\n\t\t// time.Time truncation\n\t\tcase \"timeTruncate\":\n\t\t\tcfg.timeTruncate, err = time.ParseDuration(value)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"invalid timeTruncate value: %v, error: %w\", value, err)\n\t\t\t}\n\n\t\t// I/O read Timeout\n\t\tcase \"readTimeout\":\n\t\t\tcfg.ReadTimeout, err = time.ParseDuration(value)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t// Reject read-only connections\n\t\tcase \"rejectReadOnly\":\n\t\t\tvar isBool bool\n\t\t\tcfg.RejectReadOnly, isBool = readBool(value)\n\t\t\tif !isBool {\n\t\t\t\treturn errors.New(\"invalid bool value: \" + value)\n\t\t\t}\n\n\t\t// Server public key\n\t\tcase \"serverPubKey\":\n\t\t\tname, err := url.QueryUnescape(value)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"invalid value for server pub key name: %v\", err)\n\t\t\t}\n\t\t\tcfg.ServerPubKey = name\n\n\t\t// Strict mode\n\t\tcase \"strict\":\n\t\t\tpanic(\"strict mode has been removed. See https://github.com/go-sql-driver/mysql/wiki/strict-mode\")\n\n\t\t// Dial Timeout\n\t\tcase \"timeout\":\n\t\t\tcfg.Timeout, err = time.ParseDuration(value)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t// TLS-Encryption\n\t\tcase \"tls\":\n\t\t\tboolValue, isBool := readBool(value)\n\t\t\tif isBool {\n\t\t\t\tif boolValue {\n\t\t\t\t\tcfg.TLSConfig = \"true\"\n\t\t\t\t} else {\n\t\t\t\t\tcfg.TLSConfig = \"false\"\n\t\t\t\t}\n\t\t\t} else if vl := strings.ToLower(value); vl == \"skip-verify\" || vl == \"preferred\" {\n\t\t\t\tcfg.TLSConfig = vl\n\t\t\t} else {\n\t\t\t\tname, err := url.QueryUnescape(value)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"invalid value for TLS config name: %v\", err)\n\t\t\t\t}\n\t\t\t\tcfg.TLSConfig = name\n\t\t\t}\n\n\t\t// I/O write Timeout\n\t\tcase \"writeTimeout\":\n\t\t\tcfg.WriteTimeout, err = time.ParseDuration(value)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase \"maxAllowedPacket\":\n\t\t\tcfg.MaxAllowedPacket, err = strconv.Atoi(value)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t// Connection attributes\n\t\tcase \"connectionAttributes\":\n\t\t\tconnectionAttributes, err := url.QueryUnescape(value)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"invalid connectionAttributes value: %v\", err)\n\t\t\t}\n\t\t\tcfg.ConnectionAttributes = connectionAttributes\n\n\t\tdefault:\n\t\t\t// lazy init\n\t\t\tif cfg.Params == nil {\n\t\t\t\tcfg.Params = make(map[string]string)\n\t\t\t}\n\n\t\t\tif cfg.Params[key], err = url.QueryUnescape(value); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc ensureHavePort(addr string) string {\n\tif _, _, err := net.SplitHostPort(addr); err != nil {\n\t\treturn net.JoinHostPort(addr, \"3306\")\n\t}\n\treturn addr\n}\n"
  },
  {
    "path": "dsn_fuzz_test.go",
    "content": "//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 _, test := range testDSNs { // See dsn_test.go\n\t\tf.Add(test.in)\n\t}\n\n\tf.Fuzz(func(t *testing.T, dsn1 string) {\n\t\t// Do not waste resources\n\t\tif len(dsn1) > 1000 {\n\t\t\tt.Skip(\"ignore: too long\")\n\t\t}\n\n\t\tcfg1, err := ParseDSN(dsn1)\n\t\tif err != nil {\n\t\t\tt.Skipf(\"invalid DSN: %v\", err)\n\t\t}\n\n\t\tdsn2 := cfg1.FormatDSN()\n\t\tif dsn2 == dsn1 {\n\t\t\treturn\n\t\t}\n\n\t\t// Skip known cases of bad config that are not strictly checked by ParseDSN\n\t\tif _, _, err := net.SplitHostPort(cfg1.Addr); err != nil {\n\t\t\tt.Skipf(\"invalid addr %q: %v\", cfg1.Addr, err)\n\t\t}\n\n\t\tcfg2, err := ParseDSN(dsn2)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"%q rewritten as %q: %v\", dsn1, dsn2, err)\n\t\t}\n\n\t\tdsn3 := cfg2.FormatDSN()\n\t\tif dsn3 != dsn2 {\n\t\t\tt.Errorf(\"%q rewritten as %q\", dsn2, dsn3)\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "dsn_test.go",
    "content": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2016 The Go-MySQL-Driver Authors. All rights reserved.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at http://mozilla.org/MPL/2.0/.\n\npackage mysql\n\nimport (\n\t\"crypto/tls\"\n\t\"fmt\"\n\t\"net/url\"\n\t\"reflect\"\n\t\"testing\"\n\t\"time\"\n)\n\nvar testDSNs = []struct {\n\tin  string\n\tout *Config\n}{{\n\t\"username:password@protocol(address)/dbname?param=value\",\n\t&Config{User: \"username\", Passwd: \"password\", Net: \"protocol\", Addr: \"address\", DBName: \"dbname\", Params: map[string]string{\"param\": \"value\"}, Loc: time.UTC, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true},\n}, {\n\t\"username:password@protocol(address)/dbname?param=value&columnsWithAlias=true\",\n\t&Config{User: \"username\", Passwd: \"password\", Net: \"protocol\", Addr: \"address\", DBName: \"dbname\", Params: map[string]string{\"param\": \"value\"}, Loc: time.UTC, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true, ColumnsWithAlias: true},\n}, {\n\t\"username:password@protocol(address)/dbname?param=value&columnsWithAlias=true&multiStatements=true\",\n\t&Config{User: \"username\", Passwd: \"password\", Net: \"protocol\", Addr: \"address\", DBName: \"dbname\", Params: map[string]string{\"param\": \"value\"}, Loc: time.UTC, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true, ColumnsWithAlias: true, MultiStatements: true},\n}, {\n\t\"user@unix(/path/to/socket)/dbname?charset=utf8\",\n\t&Config{User: \"user\", Net: \"unix\", Addr: \"/path/to/socket\", DBName: \"dbname\", charsets: []string{\"utf8\"}, Loc: time.UTC, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true},\n}, {\n\t\"user:password@tcp(localhost:5555)/dbname?charset=utf8&tls=true\",\n\t&Config{User: \"user\", Passwd: \"password\", Net: \"tcp\", Addr: \"localhost:5555\", DBName: \"dbname\", charsets: []string{\"utf8\"}, Loc: time.UTC, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true, TLSConfig: \"true\"},\n}, {\n\t\"user:password@tcp(localhost:5555)/dbname?charset=utf8mb4,utf8&tls=skip-verify\",\n\t&Config{User: \"user\", Passwd: \"password\", Net: \"tcp\", Addr: \"localhost:5555\", DBName: \"dbname\", charsets: []string{\"utf8mb4\", \"utf8\"}, Loc: time.UTC, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true, TLSConfig: \"skip-verify\"},\n}, {\n\t\"user:password@/dbname?loc=UTC&timeout=30s&readTimeout=1s&writeTimeout=1s&allowAllFiles=1&clientFoundRows=true&allowOldPasswords=TRUE&collation=utf8mb4_unicode_ci&maxAllowedPacket=16777216&tls=false&allowCleartextPasswords=true&parseTime=true&rejectReadOnly=true\",\n\t&Config{User: \"user\", Passwd: \"password\", Net: \"tcp\", Addr: \"127.0.0.1:3306\", DBName: \"dbname\", Collation: \"utf8mb4_unicode_ci\", Loc: time.UTC, TLSConfig: \"false\", AllowCleartextPasswords: true, AllowNativePasswords: true, Timeout: 30 * time.Second, ReadTimeout: time.Second, WriteTimeout: time.Second, Logger: defaultLogger, AllowAllFiles: true, AllowOldPasswords: true, CheckConnLiveness: true, ClientFoundRows: true, MaxAllowedPacket: 16777216, ParseTime: true, RejectReadOnly: true},\n}, {\n\t\"user:password@/dbname?allowNativePasswords=false&checkConnLiveness=false&maxAllowedPacket=0&allowFallbackToPlaintext=true\",\n\t&Config{User: \"user\", Passwd: \"password\", Net: \"tcp\", Addr: \"127.0.0.1:3306\", DBName: \"dbname\", Loc: time.UTC, MaxAllowedPacket: 0, Logger: defaultLogger, AllowFallbackToPlaintext: true, AllowNativePasswords: false, CheckConnLiveness: false},\n}, {\n\t\"user:p@ss(word)@tcp([de:ad:be:ef::ca:fe]:80)/dbname?loc=Local\",\n\t&Config{User: \"user\", Passwd: \"p@ss(word)\", Net: \"tcp\", Addr: \"[de:ad:be:ef::ca:fe]:80\", DBName: \"dbname\", Loc: time.Local, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true},\n}, {\n\t\"/dbname\",\n\t&Config{Net: \"tcp\", Addr: \"127.0.0.1:3306\", DBName: \"dbname\", Loc: time.UTC, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true},\n}, {\n\t\"/dbname%2Fwithslash\",\n\t&Config{Net: \"tcp\", Addr: \"127.0.0.1:3306\", DBName: \"dbname/withslash\", Loc: time.UTC, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true},\n}, {\n\t\"@/\",\n\t&Config{Net: \"tcp\", Addr: \"127.0.0.1:3306\", Loc: time.UTC, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true},\n}, {\n\t\"/\",\n\t&Config{Net: \"tcp\", Addr: \"127.0.0.1:3306\", Loc: time.UTC, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true},\n}, {\n\t\"\",\n\t&Config{Net: \"tcp\", Addr: \"127.0.0.1:3306\", Loc: time.UTC, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true},\n}, {\n\t\"user:p@/ssword@/\",\n\t&Config{User: \"user\", Passwd: \"p@/ssword\", Net: \"tcp\", Addr: \"127.0.0.1:3306\", Loc: time.UTC, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true},\n}, {\n\t\"unix/?arg=%2Fsome%2Fpath.ext\",\n\t&Config{Net: \"unix\", Addr: \"/tmp/mysql.sock\", Params: map[string]string{\"arg\": \"/some/path.ext\"}, Loc: time.UTC, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true},\n}, {\n\t\"tcp(127.0.0.1)/dbname\",\n\t&Config{Net: \"tcp\", Addr: \"127.0.0.1:3306\", DBName: \"dbname\", Loc: time.UTC, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true},\n}, {\n\t\"tcp(de:ad:be:ef::ca:fe)/dbname\",\n\t&Config{Net: \"tcp\", Addr: \"[de:ad:be:ef::ca:fe]:3306\", DBName: \"dbname\", Loc: time.UTC, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true},\n}, {\n\t\"user:password@/dbname?loc=UTC&timeout=30s&parseTime=true&timeTruncate=1h\",\n\t&Config{User: \"user\", Passwd: \"password\", Net: \"tcp\", Addr: \"127.0.0.1:3306\", DBName: \"dbname\", Loc: time.UTC, Timeout: 30 * time.Second, ParseTime: true, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true, timeTruncate: time.Hour},\n}, {\n\t\"foo:bar@tcp(192.168.1.50:3307)/baz?timeout=10s&connectionAttributes=program_name:MySQLGoDriver%2FTest,program_version:1.2.3\",\n\t&Config{User: \"foo\", Passwd: \"bar\", Net: \"tcp\", Addr: \"192.168.1.50:3307\", DBName: \"baz\", Loc: time.UTC, Timeout: 10 * time.Second, MaxAllowedPacket: defaultMaxAllowedPacket, Logger: defaultLogger, AllowNativePasswords: true, CheckConnLiveness: true, ConnectionAttributes: \"program_name:MySQLGoDriver/Test,program_version:1.2.3\"},\n},\n}\n\nfunc TestDSNParser(t *testing.T) {\n\tfor i, tst := range testDSNs {\n\t\tt.Run(tst.in, func(t *testing.T) {\n\t\t\tcfg, err := ParseDSN(tst.in)\n\t\t\tif err != nil {\n\t\t\t\tt.Error(err.Error())\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// pointer not static\n\t\t\tcfg.TLS = nil\n\n\t\t\tif !reflect.DeepEqual(cfg, tst.out) {\n\t\t\t\tt.Errorf(\"%d. ParseDSN(%q) mismatch:\\ngot  %+v\\nwant %+v\", i, tst.in, cfg, tst.out)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestDSNParserInvalid(t *testing.T) {\n\tvar invalidDSNs = []string{\n\t\t\"@net(addr/\",                            // no closing brace\n\t\t\"@tcp(/\",                                // no closing brace\n\t\t\"tcp(/\",                                 // no closing brace\n\t\t\"(/\",                                    // no closing brace\n\t\t\"net(addr)//\",                           // unescaped\n\t\t\"User:pass@tcp(1.2.3.4:3306)\",           // no trailing slash\n\t\t\"net()/\",                                // unknown default addr\n\t\t\"user:pass@tcp(127.0.0.1:3306)/db/name\", // invalid dbname\n\t\t\"user:password@/dbname?allowFallbackToPlaintext=PREFERRED\",          // wrong bool flag\n\t\t\"user:password@/dbname?connectionAttributes=attr1:/unescaped/value\", // unescaped\n\t\t//\"/dbname?arg=/some/unescaped/path\",\n\t}\n\n\tfor i, tst := range invalidDSNs {\n\t\tif _, err := ParseDSN(tst); err == nil {\n\t\t\tt.Errorf(\"invalid DSN #%d. (%s) didn't error!\", i, tst)\n\t\t}\n\t}\n}\n\nfunc TestDSNReformat(t *testing.T) {\n\tfor i, tst := range testDSNs {\n\t\tt.Run(tst.in, func(t *testing.T) {\n\t\t\tdsn1 := tst.in\n\t\t\tcfg1, err := ParseDSN(dsn1)\n\t\t\tif err != nil {\n\t\t\t\tt.Error(err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcfg1.TLS = nil // pointer not static\n\t\t\tres1 := fmt.Sprintf(\"%+v\", cfg1)\n\n\t\t\tdsn2 := cfg1.FormatDSN()\n\t\t\tif dsn2 != dsn1 {\n\t\t\t\t// Just log\n\t\t\t\tt.Logf(\"%d. %q reformatted as %q\", i, dsn1, dsn2)\n\t\t\t}\n\n\t\t\tcfg2, err := ParseDSN(dsn2)\n\t\t\tif err != nil {\n\t\t\t\tt.Error(err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcfg2.TLS = nil // pointer not static\n\t\t\tres2 := fmt.Sprintf(\"%+v\", cfg2)\n\n\t\t\tif res1 != res2 {\n\t\t\t\tt.Errorf(\"%d. %q does not match %q\", i, res2, res1)\n\t\t\t}\n\n\t\t\tdsn3 := cfg2.FormatDSN()\n\t\t\tif dsn3 != dsn2 {\n\t\t\t\tt.Errorf(\"%d. %q does not match %q\", i, dsn2, dsn3)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestDSNServerPubKey(t *testing.T) {\n\tbaseDSN := \"User:password@tcp(localhost:5555)/dbname?serverPubKey=\"\n\n\tRegisterServerPubKey(\"testKey\", testPubKeyRSA)\n\tdefer DeregisterServerPubKey(\"testKey\")\n\n\ttst := baseDSN + \"testKey\"\n\tcfg, err := ParseDSN(tst)\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\tif cfg.ServerPubKey != \"testKey\" {\n\t\tt.Errorf(\"unexpected cfg.ServerPubKey value: %v\", cfg.ServerPubKey)\n\t}\n\tif cfg.pubKey != testPubKeyRSA {\n\t\tt.Error(\"pub key pointer doesn't match\")\n\t}\n\n\t// Key is missing\n\ttst = baseDSN + \"invalid_name\"\n\tcfg, err = ParseDSN(tst)\n\tif err == nil {\n\t\tt.Errorf(\"invalid name in DSN (%s) but did not error. Got config: %#v\", tst, cfg)\n\t}\n}\n\nfunc TestDSNServerPubKeyQueryEscape(t *testing.T) {\n\tconst name = \"&%!:\"\n\tdsn := \"User:password@tcp(localhost:5555)/dbname?serverPubKey=\" + url.QueryEscape(name)\n\n\tRegisterServerPubKey(name, testPubKeyRSA)\n\tdefer DeregisterServerPubKey(name)\n\n\tcfg, err := ParseDSN(dsn)\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\tif cfg.pubKey != testPubKeyRSA {\n\t\tt.Error(\"pub key pointer doesn't match\")\n\t}\n}\n\nfunc TestDSNWithCustomTLS(t *testing.T) {\n\tbaseDSN := \"User:password@tcp(localhost:5555)/dbname?tls=\"\n\ttlsCfg := tls.Config{}\n\n\tRegisterTLSConfig(\"utils_test\", &tlsCfg)\n\tdefer DeregisterTLSConfig(\"utils_test\")\n\n\t// Custom TLS is missing\n\ttst := baseDSN + \"invalid_tls\"\n\tcfg, err := ParseDSN(tst)\n\tif err == nil {\n\t\tt.Errorf(\"invalid custom TLS in DSN (%s) but did not error. Got config: %#v\", tst, cfg)\n\t}\n\n\ttst = baseDSN + \"utils_test\"\n\n\t// Custom TLS with a server name\n\tname := \"foohost\"\n\ttlsCfg.ServerName = name\n\tcfg, err = ParseDSN(tst)\n\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t} else if cfg.TLS.ServerName != name {\n\t\tt.Errorf(\"did not get the correct TLS ServerName (%s) parsing DSN (%s).\", name, tst)\n\t}\n\n\t// Custom TLS without a server name\n\tname = \"localhost\"\n\ttlsCfg.ServerName = \"\"\n\tcfg, err = ParseDSN(tst)\n\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t} else if cfg.TLS.ServerName != name {\n\t\tt.Errorf(\"did not get the correct ServerName (%s) parsing DSN (%s).\", name, tst)\n\t} else if tlsCfg.ServerName != \"\" {\n\t\tt.Errorf(\"tlsCfg was mutated ServerName (%s) should be empty parsing DSN (%s).\", name, tst)\n\t}\n}\n\nfunc TestDSNTLSConfig(t *testing.T) {\n\texpectedServerName := \"example.com\"\n\tdsn := \"tcp(example.com:1234)/?tls=true\"\n\n\tcfg, err := ParseDSN(dsn)\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t}\n\tif cfg.TLS == nil {\n\t\tt.Error(\"cfg.tls should not be nil\")\n\t}\n\tif cfg.TLS.ServerName != expectedServerName {\n\t\tt.Errorf(\"cfg.tls.ServerName should be %q, got %q (host with port)\", expectedServerName, cfg.TLS.ServerName)\n\t}\n\n\tdsn = \"tcp(example.com)/?tls=true\"\n\tcfg, err = ParseDSN(dsn)\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t}\n\tif cfg.TLS == nil {\n\t\tt.Error(\"cfg.tls should not be nil\")\n\t}\n\tif cfg.TLS.ServerName != expectedServerName {\n\t\tt.Errorf(\"cfg.tls.ServerName should be %q, got %q (host without port)\", expectedServerName, cfg.TLS.ServerName)\n\t}\n}\n\nfunc TestDSNWithCustomTLSQueryEscape(t *testing.T) {\n\tconst configKey = \"&%!:\"\n\tdsn := \"User:password@tcp(localhost:5555)/dbname?tls=\" + url.QueryEscape(configKey)\n\tname := \"foohost\"\n\ttlsCfg := tls.Config{ServerName: name}\n\n\tRegisterTLSConfig(configKey, &tlsCfg)\n\tdefer DeregisterTLSConfig(configKey)\n\n\tcfg, err := ParseDSN(dsn)\n\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t} else if cfg.TLS.ServerName != name {\n\t\tt.Errorf(\"did not get the correct TLS ServerName (%s) parsing DSN (%s).\", name, dsn)\n\t}\n}\n\nfunc TestDSNUnsafeCollation(t *testing.T) {\n\t_, err := ParseDSN(\"/dbname?collation=gbk_chinese_ci&interpolateParams=true\")\n\tif err != errInvalidDSNUnsafeCollation {\n\t\tt.Errorf(\"expected %v, got %v\", errInvalidDSNUnsafeCollation, err)\n\t}\n\n\t_, err = ParseDSN(\"/dbname?collation=gbk_chinese_ci&interpolateParams=false\")\n\tif err != nil {\n\t\tt.Errorf(\"expected %v, got %v\", nil, err)\n\t}\n\n\t_, err = ParseDSN(\"/dbname?collation=gbk_chinese_ci\")\n\tif err != nil {\n\t\tt.Errorf(\"expected %v, got %v\", nil, err)\n\t}\n\n\t_, err = ParseDSN(\"/dbname?collation=ascii_bin&interpolateParams=true\")\n\tif err != nil {\n\t\tt.Errorf(\"expected %v, got %v\", nil, err)\n\t}\n\n\t_, err = ParseDSN(\"/dbname?collation=latin1_german1_ci&interpolateParams=true\")\n\tif err != nil {\n\t\tt.Errorf(\"expected %v, got %v\", nil, err)\n\t}\n\n\t_, err = ParseDSN(\"/dbname?collation=utf8_general_ci&interpolateParams=true\")\n\tif err != nil {\n\t\tt.Errorf(\"expected %v, got %v\", nil, err)\n\t}\n\n\t_, err = ParseDSN(\"/dbname?collation=utf8mb4_general_ci&interpolateParams=true\")\n\tif err != nil {\n\t\tt.Errorf(\"expected %v, got %v\", nil, err)\n\t}\n}\n\nfunc TestParamsAreSorted(t *testing.T) {\n\texpected := \"/dbname?interpolateParams=true&foobar=baz&quux=loo\"\n\tcfg := NewConfig()\n\tcfg.DBName = \"dbname\"\n\tcfg.InterpolateParams = true\n\tcfg.Params = map[string]string{\n\t\t\"quux\":   \"loo\",\n\t\t\"foobar\": \"baz\",\n\t}\n\tactual := cfg.FormatDSN()\n\tif actual != expected {\n\t\tt.Errorf(\"generic Config.Params were not sorted: want %#v, got %#v\", expected, actual)\n\t}\n}\n\nfunc TestCloneConfig(t *testing.T) {\n\tRegisterServerPubKey(\"testKey\", testPubKeyRSA)\n\tdefer DeregisterServerPubKey(\"testKey\")\n\n\texpectedServerName := \"example.com\"\n\tdsn := \"tcp(example.com:1234)/?tls=true&foobar=baz&serverPubKey=testKey\"\n\tcfg, err := ParseDSN(dsn)\n\tif err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n\n\tcfg2 := cfg.Clone()\n\tif cfg == cfg2 {\n\t\tt.Errorf(\"Config.Clone did not create a separate config struct\")\n\t}\n\n\tif cfg2.TLS.ServerName != expectedServerName {\n\t\tt.Errorf(\"cfg.tls.ServerName should be %q, got %q (host with port)\", expectedServerName, cfg.TLS.ServerName)\n\t}\n\n\tcfg2.TLS.ServerName = \"example2.com\"\n\tif cfg.TLS.ServerName == cfg2.TLS.ServerName {\n\t\tt.Errorf(\"changed cfg.tls.Server name should not propagate to original Config\")\n\t}\n\n\tif _, ok := cfg2.Params[\"foobar\"]; !ok {\n\t\tt.Errorf(\"cloned Config is missing custom params\")\n\t}\n\n\tdelete(cfg2.Params, \"foobar\")\n\n\tif _, ok := cfg.Params[\"foobar\"]; !ok {\n\t\tt.Errorf(\"custom params in cloned Config should not propagate to original Config\")\n\t}\n\n\tif !reflect.DeepEqual(cfg.pubKey, cfg2.pubKey) {\n\t\tt.Errorf(\"public key in Config should be identical\")\n\t}\n}\n\nfunc TestNormalizeTLSConfig(t *testing.T) {\n\ttt := []struct {\n\t\ttlsConfig string\n\t\twant      *tls.Config\n\t}{\n\t\t{\"\", nil},\n\t\t{\"false\", nil},\n\t\t{\"true\", &tls.Config{ServerName: \"myserver\"}},\n\t\t{\"skip-verify\", &tls.Config{InsecureSkipVerify: true}},\n\t\t{\"preferred\", &tls.Config{InsecureSkipVerify: true}},\n\t\t{\"test_tls_config\", &tls.Config{ServerName: \"myServerName\"}},\n\t}\n\n\tRegisterTLSConfig(\"test_tls_config\", &tls.Config{ServerName: \"myServerName\"})\n\tdefer func() { DeregisterTLSConfig(\"test_tls_config\") }()\n\n\tfor _, tc := range tt {\n\t\tt.Run(tc.tlsConfig, func(t *testing.T) {\n\t\t\tcfg := &Config{\n\t\t\t\tAddr:      \"myserver:3306\",\n\t\t\t\tTLSConfig: tc.tlsConfig,\n\t\t\t}\n\n\t\t\tcfg.normalize()\n\n\t\t\tif cfg.TLS == nil {\n\t\t\t\tif tc.want != nil {\n\t\t\t\t\tt.Fatal(\"wanted a tls config but got nil instead\")\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif cfg.TLS.ServerName != tc.want.ServerName {\n\t\t\t\tt.Errorf(\"tls.ServerName doesn't match (want: '%s', got: '%s')\",\n\t\t\t\t\ttc.want.ServerName, cfg.TLS.ServerName)\n\t\t\t}\n\t\t\tif cfg.TLS.InsecureSkipVerify != tc.want.InsecureSkipVerify {\n\t\t\t\tt.Errorf(\"tls.InsecureSkipVerify doesn't match (want: %T, got :%T)\",\n\t\t\t\t\ttc.want.InsecureSkipVerify, cfg.TLS.InsecureSkipVerify)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc BenchmarkParseDSN(b *testing.B) {\n\tb.ReportAllocs()\n\n\tfor i := 0; i < b.N; i++ {\n\t\tfor _, tst := range testDSNs {\n\t\t\tif _, err := ParseDSN(tst.in); err != nil {\n\t\t\t\tb.Error(err.Error())\n\t\t\t}\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "errors.go",
    "content": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at http://mozilla.org/MPL/2.0/.\n\npackage mysql\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n)\n\n// Various errors the driver might return. Can change between driver versions.\nvar (\n\tErrInvalidConn       = errors.New(\"invalid connection\")\n\tErrMalformPkt        = errors.New(\"malformed packet\")\n\tErrNoTLS             = errors.New(\"TLS requested but server does not support TLS\")\n\tErrCleartextPassword = errors.New(\"this user requires clear text authentication. If you still want to use it, please add 'allowCleartextPasswords=1' to your DSN\")\n\tErrNativePassword    = errors.New(\"this user requires mysql native password authentication\")\n\tErrOldPassword       = errors.New(\"this user requires old password authentication. If you still want to use it, please add 'allowOldPasswords=1' to your DSN. See also https://github.com/go-sql-driver/mysql/wiki/old_passwords\")\n\tErrUnknownPlugin     = errors.New(\"this authentication plugin is not supported\")\n\tErrOldProtocol       = errors.New(\"MySQL server does not support required protocol 41+\")\n\tErrPktSync           = errors.New(\"commands out of sync. You can't run this command now\")\n\tErrPktSyncMul        = errors.New(\"commands out of sync. Did you run multiple statements at once?\")\n\tErrPktTooLarge       = errors.New(\"packet for query is too large. Try adjusting the `Config.MaxAllowedPacket`\")\n\tErrBusyBuffer        = errors.New(\"busy buffer\")\n\n\t// errBadConnNoWrite is used for connection errors where nothing was sent to the database yet.\n\t// If this happens first in a function starting a database interaction, it should be replaced by driver.ErrBadConn\n\t// to trigger a resend. Use mc.markBadConn(err) to do this.\n\t// See https://github.com/go-sql-driver/mysql/pull/302\n\terrBadConnNoWrite = errors.New(\"bad connection\")\n)\n\nvar defaultLogger = Logger(log.New(os.Stderr, \"[mysql] \", log.Ldate|log.Ltime))\n\n// Logger is used to log critical error messages.\ntype Logger interface {\n\tPrint(v ...any)\n}\n\n// NopLogger is a nop implementation of the Logger interface.\ntype NopLogger struct{}\n\n// Print implements Logger interface.\nfunc (nl *NopLogger) Print(_ ...any) {}\n\n// SetLogger is used to set the default logger for critical errors.\n// The initial logger is os.Stderr.\nfunc SetLogger(logger Logger) error {\n\tif logger == nil {\n\t\treturn errors.New(\"logger is nil\")\n\t}\n\tdefaultLogger = logger\n\treturn nil\n}\n\n// MySQLError is an error type which represents a single MySQL error\ntype MySQLError struct {\n\tNumber   uint16\n\tSQLState [5]byte\n\tMessage  string\n}\n\nfunc (me *MySQLError) Error() string {\n\tif me.SQLState != [5]byte{} {\n\t\treturn fmt.Sprintf(\"Error %d (%s): %s\", me.Number, me.SQLState, me.Message)\n\t}\n\n\treturn fmt.Sprintf(\"Error %d: %s\", me.Number, me.Message)\n}\n\nfunc (me *MySQLError) Is(err error) bool {\n\tif merr, ok := err.(*MySQLError); ok {\n\t\treturn merr.Number == me.Number\n\t}\n\treturn false\n}\n"
  },
  {
    "path": "errors_test.go",
    "content": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at http://mozilla.org/MPL/2.0/.\n\npackage mysql\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"log\"\n\t\"testing\"\n)\n\nfunc TestErrorsSetLogger(t *testing.T) {\n\tprevious := defaultLogger\n\tdefer func() {\n\t\tdefaultLogger = previous\n\t}()\n\n\t// set up logger\n\tconst expected = \"prefix: test\\n\"\n\tbuffer := bytes.NewBuffer(make([]byte, 0, 64))\n\tlogger := log.New(buffer, \"prefix: \", 0)\n\n\t// print\n\tSetLogger(logger)\n\tdefaultLogger.Print(\"test\")\n\n\t// check result\n\tif actual := buffer.String(); actual != expected {\n\t\tt.Errorf(\"expected %q, got %q\", expected, actual)\n\t}\n}\n\nfunc TestErrorsStrictIgnoreNotes(t *testing.T) {\n\trunTests(t, dsn+\"&sql_notes=false\", func(dbt *DBTest) {\n\t\tdbt.mustExec(\"DROP TABLE IF EXISTS does_not_exist\")\n\t})\n}\n\nfunc TestMySQLErrIs(t *testing.T) {\n\tinfraErr := &MySQLError{Number: 1234, Message: \"the server is on fire\"}\n\totherInfraErr := &MySQLError{Number: 1234, Message: \"the datacenter is flooded\"}\n\tif !errors.Is(infraErr, otherInfraErr) {\n\t\tt.Errorf(\"expected errors to be the same: %+v %+v\", infraErr, otherInfraErr)\n\t}\n\n\tdifferentCodeErr := &MySQLError{Number: 5678, Message: \"the server is on fire\"}\n\tif errors.Is(infraErr, differentCodeErr) {\n\t\tt.Fatalf(\"expected errors to be different: %+v %+v\", infraErr, differentCodeErr)\n\t}\n\n\tnonMysqlErr := errors.New(\"not a mysql error\")\n\tif errors.Is(infraErr, nonMysqlErr) {\n\t\tt.Fatalf(\"expected errors to be different: %+v %+v\", infraErr, nonMysqlErr)\n\t}\n}\n"
  },
  {
    "path": "fields.go",
    "content": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2017 The Go-MySQL-Driver Authors. All rights reserved.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at http://mozilla.org/MPL/2.0/.\n\npackage mysql\n\nimport (\n\t\"database/sql\"\n\t\"reflect\"\n)\n\nfunc (mf *mysqlField) typeDatabaseName() string {\n\tswitch mf.fieldType {\n\tcase fieldTypeBit:\n\t\treturn \"BIT\"\n\tcase fieldTypeBLOB:\n\t\tif mf.charSet != binaryCollationID {\n\t\t\treturn \"TEXT\"\n\t\t}\n\t\treturn \"BLOB\"\n\tcase fieldTypeDate:\n\t\treturn \"DATE\"\n\tcase fieldTypeDateTime:\n\t\treturn \"DATETIME\"\n\tcase fieldTypeDecimal:\n\t\treturn \"DECIMAL\"\n\tcase fieldTypeDouble:\n\t\treturn \"DOUBLE\"\n\tcase fieldTypeEnum:\n\t\treturn \"ENUM\"\n\tcase fieldTypeFloat:\n\t\treturn \"FLOAT\"\n\tcase fieldTypeGeometry:\n\t\treturn \"GEOMETRY\"\n\tcase fieldTypeInt24:\n\t\tif mf.flags&flagUnsigned != 0 {\n\t\t\treturn \"UNSIGNED MEDIUMINT\"\n\t\t}\n\t\treturn \"MEDIUMINT\"\n\tcase fieldTypeJSON:\n\t\treturn \"JSON\"\n\tcase fieldTypeLong:\n\t\tif mf.flags&flagUnsigned != 0 {\n\t\t\treturn \"UNSIGNED INT\"\n\t\t}\n\t\treturn \"INT\"\n\tcase fieldTypeLongBLOB:\n\t\tif mf.charSet != binaryCollationID {\n\t\t\treturn \"LONGTEXT\"\n\t\t}\n\t\treturn \"LONGBLOB\"\n\tcase fieldTypeLongLong:\n\t\tif mf.flags&flagUnsigned != 0 {\n\t\t\treturn \"UNSIGNED BIGINT\"\n\t\t}\n\t\treturn \"BIGINT\"\n\tcase fieldTypeMediumBLOB:\n\t\tif mf.charSet != binaryCollationID {\n\t\t\treturn \"MEDIUMTEXT\"\n\t\t}\n\t\treturn \"MEDIUMBLOB\"\n\tcase fieldTypeNewDate:\n\t\treturn \"DATE\"\n\tcase fieldTypeNewDecimal:\n\t\treturn \"DECIMAL\"\n\tcase fieldTypeNULL:\n\t\treturn \"NULL\"\n\tcase fieldTypeSet:\n\t\treturn \"SET\"\n\tcase fieldTypeShort:\n\t\tif mf.flags&flagUnsigned != 0 {\n\t\t\treturn \"UNSIGNED SMALLINT\"\n\t\t}\n\t\treturn \"SMALLINT\"\n\tcase fieldTypeString:\n\t\tif mf.flags&flagEnum != 0 {\n\t\t\treturn \"ENUM\"\n\t\t} else if mf.flags&flagSet != 0 {\n\t\t\treturn \"SET\"\n\t\t}\n\t\tif mf.charSet == binaryCollationID {\n\t\t\treturn \"BINARY\"\n\t\t}\n\t\treturn \"CHAR\"\n\tcase fieldTypeTime:\n\t\treturn \"TIME\"\n\tcase fieldTypeTimestamp:\n\t\treturn \"TIMESTAMP\"\n\tcase fieldTypeTiny:\n\t\tif mf.flags&flagUnsigned != 0 {\n\t\t\treturn \"UNSIGNED TINYINT\"\n\t\t}\n\t\treturn \"TINYINT\"\n\tcase fieldTypeTinyBLOB:\n\t\tif mf.charSet != binaryCollationID {\n\t\t\treturn \"TINYTEXT\"\n\t\t}\n\t\treturn \"TINYBLOB\"\n\tcase fieldTypeVarChar:\n\t\tif mf.charSet == binaryCollationID {\n\t\t\treturn \"VARBINARY\"\n\t\t}\n\t\treturn \"VARCHAR\"\n\tcase fieldTypeVarString:\n\t\tif mf.charSet == binaryCollationID {\n\t\t\treturn \"VARBINARY\"\n\t\t}\n\t\treturn \"VARCHAR\"\n\tcase fieldTypeYear:\n\t\treturn \"YEAR\"\n\tcase fieldTypeVector:\n\t\treturn \"VECTOR\"\n\tdefault:\n\t\treturn \"\"\n\t}\n}\n\nvar (\n\tscanTypeFloat32    = reflect.TypeOf(float32(0))\n\tscanTypeFloat64    = reflect.TypeOf(float64(0))\n\tscanTypeInt8       = reflect.TypeOf(int8(0))\n\tscanTypeInt16      = reflect.TypeOf(int16(0))\n\tscanTypeInt32      = reflect.TypeOf(int32(0))\n\tscanTypeInt64      = reflect.TypeOf(int64(0))\n\tscanTypeNullFloat  = reflect.TypeOf(sql.NullFloat64{})\n\tscanTypeNullInt    = reflect.TypeOf(sql.NullInt64{})\n\tscanTypeNullUint   = reflect.TypeOf(sql.Null[uint64]{})\n\tscanTypeNullTime   = reflect.TypeOf(sql.NullTime{})\n\tscanTypeUint8      = reflect.TypeOf(uint8(0))\n\tscanTypeUint16     = reflect.TypeOf(uint16(0))\n\tscanTypeUint32     = reflect.TypeOf(uint32(0))\n\tscanTypeUint64     = reflect.TypeOf(uint64(0))\n\tscanTypeString     = reflect.TypeOf(\"\")\n\tscanTypeNullString = reflect.TypeOf(sql.NullString{})\n\tscanTypeBytes      = reflect.TypeOf([]byte{})\n\tscanTypeUnknown    = reflect.TypeOf(new(any))\n)\n\ntype mysqlField struct {\n\ttableName string\n\tname      string\n\tlength    uint32\n\tflags     fieldFlag\n\tfieldType fieldType\n\tdecimals  byte\n\tcharSet   uint8\n}\n\nfunc (mf *mysqlField) scanType() reflect.Type {\n\tswitch mf.fieldType {\n\tcase fieldTypeTiny:\n\t\tif mf.flags&flagNotNULL != 0 {\n\t\t\tif mf.flags&flagUnsigned != 0 {\n\t\t\t\treturn scanTypeUint8\n\t\t\t}\n\t\t\treturn scanTypeInt8\n\t\t}\n\t\treturn scanTypeNullInt\n\n\tcase fieldTypeShort, fieldTypeYear:\n\t\tif mf.flags&flagNotNULL != 0 {\n\t\t\tif mf.flags&flagUnsigned != 0 {\n\t\t\t\treturn scanTypeUint16\n\t\t\t}\n\t\t\treturn scanTypeInt16\n\t\t}\n\t\treturn scanTypeNullInt\n\n\tcase fieldTypeInt24, fieldTypeLong:\n\t\tif mf.flags&flagNotNULL != 0 {\n\t\t\tif mf.flags&flagUnsigned != 0 {\n\t\t\t\treturn scanTypeUint32\n\t\t\t}\n\t\t\treturn scanTypeInt32\n\t\t}\n\t\treturn scanTypeNullInt\n\n\tcase fieldTypeLongLong:\n\t\tif mf.flags&flagNotNULL != 0 {\n\t\t\tif mf.flags&flagUnsigned != 0 {\n\t\t\t\treturn scanTypeUint64\n\t\t\t}\n\t\t\treturn scanTypeInt64\n\t\t}\n\t\tif mf.flags&flagUnsigned != 0 {\n\t\t\treturn scanTypeNullUint\n\t\t}\n\t\treturn scanTypeNullInt\n\n\tcase fieldTypeFloat:\n\t\tif mf.flags&flagNotNULL != 0 {\n\t\t\treturn scanTypeFloat32\n\t\t}\n\t\treturn scanTypeNullFloat\n\n\tcase fieldTypeDouble:\n\t\tif mf.flags&flagNotNULL != 0 {\n\t\t\treturn scanTypeFloat64\n\t\t}\n\t\treturn scanTypeNullFloat\n\n\tcase fieldTypeBit, fieldTypeTinyBLOB, fieldTypeMediumBLOB, fieldTypeLongBLOB,\n\t\tfieldTypeBLOB, fieldTypeVarString, fieldTypeString, fieldTypeGeometry, fieldTypeVector:\n\t\tif mf.charSet == binaryCollationID {\n\t\t\treturn scanTypeBytes\n\t\t}\n\t\tfallthrough\n\tcase fieldTypeDecimal, fieldTypeNewDecimal, fieldTypeVarChar,\n\t\tfieldTypeEnum, fieldTypeSet, fieldTypeJSON, fieldTypeTime:\n\t\tif mf.flags&flagNotNULL != 0 {\n\t\t\treturn scanTypeString\n\t\t}\n\t\treturn scanTypeNullString\n\n\tcase fieldTypeDate, fieldTypeNewDate,\n\t\tfieldTypeTimestamp, fieldTypeDateTime:\n\t\t// NullTime is always returned for more consistent behavior as it can\n\t\t// handle both cases of parseTime regardless if the field is nullable.\n\t\treturn scanTypeNullTime\n\n\tdefault:\n\t\treturn scanTypeUnknown\n\t}\n}\n"
  },
  {
    "path": "go.mod",
    "content": "module github.com/go-sql-driver/mysql\n\ngo 1.22.0\n\nrequire filippo.io/edwards25519 v1.1.1\n"
  },
  {
    "path": "go.sum",
    "content": "filippo.io/edwards25519 v1.1.1 h1:YpjwWWlNmGIDyXOn8zLzqiD+9TyIlPhGFG96P39uBpw=\nfilippo.io/edwards25519 v1.1.1/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=\n"
  },
  {
    "path": "infile.go",
    "content": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at http://mozilla.org/MPL/2.0/.\n\npackage mysql\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n)\n\nvar (\n\tfileRegister       map[string]struct{}\n\tfileRegisterLock   sync.RWMutex\n\treaderRegister     map[string]func() io.Reader\n\treaderRegisterLock sync.RWMutex\n)\n\n// RegisterLocalFile adds the given file to the file allowlist,\n// so that it can be used by \"LOAD DATA LOCAL INFILE <filepath>\".\n// Alternatively you can allow the use of all local files with\n// the DSN parameter 'allowAllFiles=true'\n//\n//\tfilePath := \"/home/gopher/data.csv\"\n//\tmysql.RegisterLocalFile(filePath)\n//\terr := db.Exec(\"LOAD DATA LOCAL INFILE '\" + filePath + \"' INTO TABLE foo\")\n//\tif err != nil {\n//\t...\nfunc RegisterLocalFile(filePath string) {\n\tfileRegisterLock.Lock()\n\t// lazy map init\n\tif fileRegister == nil {\n\t\tfileRegister = make(map[string]struct{})\n\t}\n\n\tfileRegister[strings.Trim(filePath, `\"`)] = struct{}{}\n\tfileRegisterLock.Unlock()\n}\n\n// DeregisterLocalFile removes the given filepath from the allowlist.\nfunc DeregisterLocalFile(filePath string) {\n\tfileRegisterLock.Lock()\n\tdelete(fileRegister, strings.Trim(filePath, `\"`))\n\tfileRegisterLock.Unlock()\n}\n\n// RegisterReaderHandler registers a handler function which is used\n// to receive a io.Reader.\n// The Reader can be used by \"LOAD DATA LOCAL INFILE Reader::<name>\".\n// If the handler returns a io.ReadCloser Close() is called when the\n// request is finished.\n//\n//\tmysql.RegisterReaderHandler(\"data\", func() io.Reader {\n//\t\tvar csvReader io.Reader // Some Reader that returns CSV data\n//\t\t... // Open Reader here\n//\t\treturn csvReader\n//\t})\n//\terr := db.Exec(\"LOAD DATA LOCAL INFILE 'Reader::data' INTO TABLE foo\")\n//\tif err != nil {\n//\t...\nfunc RegisterReaderHandler(name string, handler func() io.Reader) {\n\treaderRegisterLock.Lock()\n\t// lazy map init\n\tif readerRegister == nil {\n\t\treaderRegister = make(map[string]func() io.Reader)\n\t}\n\n\treaderRegister[name] = handler\n\treaderRegisterLock.Unlock()\n}\n\n// DeregisterReaderHandler removes the ReaderHandler function with\n// the given name from the registry.\nfunc DeregisterReaderHandler(name string) {\n\treaderRegisterLock.Lock()\n\tdelete(readerRegister, name)\n\treaderRegisterLock.Unlock()\n}\n\nfunc deferredClose(err *error, closer io.Closer) {\n\tcloseErr := closer.Close()\n\tif *err == nil {\n\t\t*err = closeErr\n\t}\n}\n\nconst defaultPacketSize = 16 * 1024 // 16KB is small enough for disk readahead and large enough for TCP\n\nfunc (mc *okHandler) handleInFileRequest(name string) (err error) {\n\tvar rdr io.Reader\n\tpacketSize := min(mc.maxWriteSize, defaultPacketSize)\n\n\tif idx := strings.Index(name, \"Reader::\"); idx == 0 || (idx > 0 && name[idx-1] == '/') { // io.Reader\n\t\t// The server might return an an absolute path. See issue #355.\n\t\tname = name[idx+8:]\n\n\t\treaderRegisterLock.RLock()\n\t\thandler, inMap := readerRegister[name]\n\t\treaderRegisterLock.RUnlock()\n\n\t\tif inMap {\n\t\t\trdr = handler()\n\t\t\tif rdr != nil {\n\t\t\t\tif cl, ok := rdr.(io.Closer); ok {\n\t\t\t\t\tdefer deferredClose(&err, cl)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terr = fmt.Errorf(\"reader '%s' is <nil>\", name)\n\t\t\t}\n\t\t} else {\n\t\t\terr = fmt.Errorf(\"reader '%s' is not registered\", name)\n\t\t}\n\t} else { // File\n\t\tname = strings.Trim(name, `\"`)\n\t\tfileRegisterLock.RLock()\n\t\t_, exists := fileRegister[name]\n\t\tfileRegisterLock.RUnlock()\n\t\tif mc.cfg.AllowAllFiles || exists {\n\t\t\tvar file *os.File\n\t\t\tvar fi os.FileInfo\n\n\t\t\tif file, err = os.Open(name); err == nil {\n\t\t\t\tdefer deferredClose(&err, file)\n\n\t\t\t\t// get file size\n\t\t\t\tif fi, err = file.Stat(); err == nil {\n\t\t\t\t\trdr = file\n\t\t\t\t\tif fileSize := int(fi.Size()); fileSize < packetSize {\n\t\t\t\t\t\tpacketSize = fileSize\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\terr = fmt.Errorf(\"local file '%s' is not registered\", name)\n\t\t}\n\t}\n\n\t// send content packets\n\tvar data []byte\n\n\t// if packetSize == 0, the Reader contains no data\n\tif err == nil && packetSize > 0 {\n\t\tdata = make([]byte, 4+packetSize)\n\t\tvar n int\n\t\tfor err == nil {\n\t\t\tn, err = rdr.Read(data[4:])\n\t\t\tif n > 0 {\n\t\t\t\tif ioErr := mc.conn().writePacket(data[:4+n]); ioErr != nil {\n\t\t\t\t\treturn ioErr\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif err == io.EOF {\n\t\t\terr = nil\n\t\t}\n\t}\n\n\t// send empty packet (termination)\n\tif data == nil {\n\t\tdata = make([]byte, 4)\n\t}\n\tif ioErr := mc.conn().writePacket(data[:4]); ioErr != nil {\n\t\treturn ioErr\n\t}\n\tmc.conn().syncSequence()\n\n\t// read OK packet\n\tif err == nil {\n\t\treturn mc.readResultOK()\n\t}\n\n\tmc.conn().readPacket()\n\treturn err\n}\n"
  },
  {
    "path": "nulltime.go",
    "content": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at http://mozilla.org/MPL/2.0/.\n\npackage mysql\n\nimport (\n\t\"database/sql\"\n\t\"database/sql/driver\"\n\t\"fmt\"\n\t\"time\"\n)\n\n// NullTime represents a time.Time that may be NULL.\n// NullTime implements the Scanner interface so\n// it can be used as a scan destination:\n//\n//\tvar nt NullTime\n//\terr := db.QueryRow(\"SELECT time FROM foo WHERE id=?\", id).Scan(&nt)\n//\t...\n//\tif nt.Valid {\n//\t   // use nt.Time\n//\t} else {\n//\t   // NULL value\n//\t}\n//\n// # This NullTime implementation is not driver-specific\n//\n// Deprecated: NullTime doesn't honor the loc DSN parameter.\n// NullTime.Scan interprets a time as UTC, not the loc DSN parameter.\n// Use sql.NullTime instead.\ntype NullTime sql.NullTime\n\n// Scan implements the Scanner interface.\n// The value type must be time.Time or string / []byte (formatted time-string),\n// otherwise Scan fails.\nfunc (nt *NullTime) Scan(value any) (err error) {\n\tif value == nil {\n\t\tnt.Time, nt.Valid = time.Time{}, false\n\t\treturn\n\t}\n\n\tswitch v := value.(type) {\n\tcase time.Time:\n\t\tnt.Time, nt.Valid = v, true\n\t\treturn\n\tcase []byte:\n\t\tnt.Time, err = parseDateTime(v, time.UTC)\n\t\tnt.Valid = (err == nil)\n\t\treturn\n\tcase string:\n\t\tnt.Time, err = parseDateTime([]byte(v), time.UTC)\n\t\tnt.Valid = (err == nil)\n\t\treturn\n\t}\n\n\tnt.Valid = false\n\treturn fmt.Errorf(\"can't convert %T to time.Time\", value)\n}\n\n// Value implements the driver Valuer interface.\nfunc (nt NullTime) Value() (driver.Value, error) {\n\tif !nt.Valid {\n\t\treturn nil, nil\n\t}\n\treturn nt.Time, nil\n}\n"
  },
  {
    "path": "nulltime_test.go",
    "content": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at http://mozilla.org/MPL/2.0/.\n\npackage mysql\n\nimport (\n\t\"database/sql\"\n\t\"database/sql/driver\"\n\t\"testing\"\n\t\"time\"\n)\n\nvar (\n\t// Check implementation of interfaces\n\t_ driver.Valuer = NullTime{}\n\t_ sql.Scanner   = (*NullTime)(nil)\n)\n\nfunc TestScanNullTime(t *testing.T) {\n\tvar scanTests = []struct {\n\t\tin    any\n\t\terror bool\n\t\tvalid bool\n\t\ttime  time.Time\n\t}{\n\t\t{tDate, false, true, tDate},\n\t\t{sDate, false, true, tDate},\n\t\t{[]byte(sDate), false, true, tDate},\n\t\t{tDateTime, false, true, tDateTime},\n\t\t{sDateTime, false, true, tDateTime},\n\t\t{[]byte(sDateTime), false, true, tDateTime},\n\t\t{tDate0, false, true, tDate0},\n\t\t{sDate0, false, true, tDate0},\n\t\t{[]byte(sDate0), false, true, tDate0},\n\t\t{sDateTime0, false, true, tDate0},\n\t\t{[]byte(sDateTime0), false, true, tDate0},\n\t\t{\"\", true, false, tDate0},\n\t\t{\"1234\", true, false, tDate0},\n\t\t{0, true, false, tDate0},\n\t}\n\n\tvar nt = NullTime{}\n\tvar err error\n\n\tfor _, tst := range scanTests {\n\t\terr = nt.Scan(tst.in)\n\t\tif (err != nil) != tst.error {\n\t\t\tt.Errorf(\"%v: expected error status %t, got %t\", tst.in, tst.error, (err != nil))\n\t\t}\n\t\tif nt.Valid != tst.valid {\n\t\t\tt.Errorf(\"%v: expected valid status %t, got %t\", tst.in, tst.valid, nt.Valid)\n\t\t}\n\t\tif nt.Time != tst.time {\n\t\t\tt.Errorf(\"%v: expected time %v, got %v\", tst.in, tst.time, nt.Time)\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "packets.go",
    "content": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at http://mozilla.org/MPL/2.0/.\n\npackage mysql\n\nimport (\n\t\"bytes\"\n\t\"crypto/tls\"\n\t\"database/sql/driver\"\n\t\"encoding/binary\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n)\n\n// MySQL client/server protocol documentations.\n// https://dev.mysql.com/doc/dev/mysql-server/latest/PAGE_PROTOCOL.html\n// https://mariadb.com/kb/en/clientserver-protocol/\n\n// read n bytes from mc.buf\nfunc (mc *mysqlConn) readNext(n int) ([]byte, error) {\n\tif mc.buf.len() < n {\n\t\terr := mc.buf.fill(n, mc.readWithTimeout)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn mc.buf.readNext(n), nil\n}\n\n// Read packet to buffer 'data'\nfunc (mc *mysqlConn) readPacket() ([]byte, error) {\n\tvar prevData []byte\n\tinvalidSequence := false\n\n\treadNext := mc.readNext\n\tif mc.compress {\n\t\treadNext = mc.compIO.readNext\n\t}\n\n\tfor {\n\t\t// read packet header\n\t\tdata, err := readNext(4)\n\t\tif err != nil {\n\t\t\tmc.close()\n\t\t\tif cerr := mc.canceled.Value(); cerr != nil {\n\t\t\t\treturn nil, cerr\n\t\t\t}\n\t\t\tmc.log(err)\n\t\t\treturn nil, ErrInvalidConn\n\t\t}\n\n\t\t// packet length [24 bit]\n\t\tpktLen := getUint24(data[:3])\n\t\tseq := data[3]\n\n\t\t// check packet sync [8 bit]\n\t\tif seq != mc.sequence {\n\t\t\tmc.log(fmt.Sprintf(\"[warn] unexpected sequence nr: expected %v, got %v\", mc.sequence, seq))\n\t\t\t// MySQL and MariaDB doesn't check packet nr in compressed packet.\n\t\t\tif !mc.compress {\n\t\t\t\t// For large packets, we stop reading as soon as sync error.\n\t\t\t\tif len(prevData) > 0 {\n\t\t\t\t\tmc.close()\n\t\t\t\t\treturn nil, ErrPktSyncMul\n\t\t\t\t}\n\t\t\t\tinvalidSequence = true\n\t\t\t}\n\t\t}\n\t\tmc.sequence = seq + 1\n\n\t\t// packets with length 0 terminate a previous packet which is a\n\t\t// multiple of (2^24)-1 bytes long\n\t\tif pktLen == 0 {\n\t\t\t// there was no previous packet\n\t\t\tif prevData == nil {\n\t\t\t\tmc.log(ErrMalformPkt)\n\t\t\t\tmc.close()\n\t\t\t\treturn nil, ErrInvalidConn\n\t\t\t}\n\t\t\treturn prevData, nil\n\t\t}\n\n\t\t// read packet body [pktLen bytes]\n\t\tdata, err = readNext(pktLen)\n\t\tif err != nil {\n\t\t\tmc.close()\n\t\t\tif cerr := mc.canceled.Value(); cerr != nil {\n\t\t\t\treturn nil, cerr\n\t\t\t}\n\t\t\tmc.log(err)\n\t\t\treturn nil, ErrInvalidConn\n\t\t}\n\n\t\t// return data if this was the last packet\n\t\tif pktLen < maxPacketSize {\n\t\t\t// zero allocations for non-split packets\n\t\t\tif prevData != nil {\n\t\t\t\tdata = append(prevData, data...)\n\t\t\t}\n\t\t\tif invalidSequence {\n\t\t\t\tmc.close()\n\t\t\t\t// return sync error only for regular packet.\n\t\t\t\t// error packets may have wrong sequence number.\n\t\t\t\tif data[0] != iERR {\n\t\t\t\t\treturn nil, ErrPktSync\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn data, nil\n\t\t}\n\n\t\tprevData = append(prevData, data...)\n\t}\n}\n\n// Write packet buffer 'data'\nfunc (mc *mysqlConn) writePacket(data []byte) error {\n\tpktLen := len(data) - 4\n\tif pktLen > mc.maxAllowedPacket {\n\t\treturn ErrPktTooLarge\n\t}\n\n\twriteFunc := mc.writeWithTimeout\n\tif mc.compress {\n\t\twriteFunc = mc.compIO.writePackets\n\t}\n\n\tfor {\n\t\tsize := min(maxPacketSize, pktLen)\n\t\tputUint24(data[:3], size)\n\t\tdata[3] = mc.sequence\n\n\t\t// Write packet\n\t\tif debug {\n\t\t\tfmt.Fprintf(os.Stderr, \"writePacket: size=%v seq=%v\\n\", size, mc.sequence)\n\t\t}\n\n\t\tn, err := writeFunc(data[:4+size])\n\t\tif err != nil {\n\t\t\tmc.cleanup()\n\t\t\tif cerr := mc.canceled.Value(); cerr != nil {\n\t\t\t\treturn cerr\n\t\t\t}\n\t\t\tif n == 0 && pktLen == len(data)-4 {\n\t\t\t\t// only for the first loop iteration when nothing was written yet\n\t\t\t\tmc.log(err)\n\t\t\t\treturn errBadConnNoWrite\n\t\t\t} else {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif n != 4+size {\n\t\t\t// io.Writer(b) must return a non-nil error if it cannot write len(b) bytes.\n\t\t\t// The io.ErrShortWrite error is used to indicate that this rule has not been followed.\n\t\t\tmc.cleanup()\n\t\t\treturn io.ErrShortWrite\n\t\t}\n\n\t\tmc.sequence++\n\t\tif size != maxPacketSize {\n\t\t\treturn nil\n\t\t}\n\t\tpktLen -= size\n\t\tdata = data[size:]\n\t}\n}\n\n/******************************************************************************\n*                           Initialization Process                            *\n******************************************************************************/\n\n// Handshake Initialization Packet\n// https://dev.mysql.com/doc/dev/mysql-server/latest/page_protocol_connection_phase_packets_protocol_handshake_v10.html\n// https://mariadb.com/kb/en/connection/#initial-handshake-packet\nfunc (mc *mysqlConn) readHandshakePacket() (data []byte, capabilities capabilityFlag, extendedCapabilities extendedCapabilityFlag, plugin string, err error) {\n\tdata, err = mc.readPacket()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif data[0] == iERR {\n\t\terr = mc.handleErrorPacket(data)\n\t\treturn\n\t}\n\n\t// protocol version [1 byte]\n\tif data[0] < minProtocolVersion {\n\t\treturn nil, 0, 0, \"\", fmt.Errorf(\n\t\t\t\"unsupported protocol version %d. Version %d or higher is required\",\n\t\t\tdata[0],\n\t\t\tminProtocolVersion,\n\t\t)\n\t}\n\n\t// server version [null terminated string]\n\t// connection id [4 bytes]\n\tpos := 1 + bytes.IndexByte(data[1:], 0x00) + 1 + 4\n\n\t// first part of the password cipher [8 bytes]\n\tauthData := data[pos : pos+8]\n\n\t// (filler) always 0x00 [1 byte]\n\tpos += 8 + 1\n\n\t// capability flags (lower 2 bytes) [2 bytes]\n\tcapabilities = capabilityFlag(binary.LittleEndian.Uint16(data[pos : pos+2]))\n\tif capabilities&clientProtocol41 == 0 {\n\t\treturn nil, capabilities, 0, \"\", ErrOldProtocol\n\t}\n\tif capabilities&clientSSL == 0 && mc.cfg.TLS != nil {\n\t\tif mc.cfg.AllowFallbackToPlaintext {\n\t\t\tmc.cfg.TLS = nil\n\t\t} else {\n\t\t\treturn nil, capabilities, 0, \"\", ErrNoTLS\n\t\t}\n\t}\n\tpos += 2\n\n\tif len(data) > pos {\n\t\t// character set [1 byte]\n\t\t// status flags [2 bytes]\n\t\tpos += 3\n\t\t// capability flags (upper 2 bytes) [2 bytes]\n\t\tcapabilities |= capabilityFlag(binary.LittleEndian.Uint16(data[pos:pos+2])) << 16\n\t\tpos += 2\n\t\t// length of auth-plugin-data [1 byte]\n\t\t// reserved (all [00]) [6 bytes]\n\t\tpos += 7\n\t\tif capabilities&clientMySQL == 0 {\n\t\t\t// MariaDB server extended flag\n\t\t\textendedCapabilities = extendedCapabilityFlag(binary.LittleEndian.Uint32(data[pos : pos+4]))\n\t\t}\n\t\tpos += 4\n\n\t\t// second part of the password cipher [minimum 13 bytes],\n\t\t// where len=MAX(13, length of auth-plugin-data - 8)\n\t\t//\n\t\t// The web documentation is ambiguous about the length. However,\n\t\t// according to mysql-5.7/sql/auth/sql_authentication.cc line 538,\n\t\t// the 13th byte is \"\\0 byte, terminating the second part of\n\t\t// a scramble\". So the second part of the password cipher is\n\t\t// a NULL terminated string that's at least 13 bytes with the\n\t\t// last byte being NULL.\n\t\t//\n\t\t// The official Python library uses the fixed length 12\n\t\t// which seems to work but technically could have a hidden bug.\n\t\tauthData = append(authData, data[pos:pos+12]...)\n\t\tpos += 13\n\n\t\t// EOF if version (>= 5.5.7 and < 5.5.10) or (>= 5.6.0 and < 5.6.2)\n\t\t// \\NUL otherwise\n\t\tif end := bytes.IndexByte(data[pos:], 0x00); end != -1 {\n\t\t\tplugin = string(data[pos : pos+end])\n\t\t} else {\n\t\t\tplugin = string(data[pos:])\n\t\t}\n\n\t\t// make a memory safe copy of the cipher slice\n\t\tvar b [20]byte\n\t\tcopy(b[:], authData)\n\t\treturn b[:], capabilities, extendedCapabilities, plugin, nil\n\t}\n\n\t// make a memory safe copy of the cipher slice\n\tvar b [8]byte\n\tcopy(b[:], authData)\n\treturn b[:], capabilities, 0, plugin, nil\n}\n\n// initCapabilities initializes the capabilities based on server support and configuration\nfunc (mc *mysqlConn) initCapabilities(serverCapabilities capabilityFlag, serverExtCapabilities extendedCapabilityFlag, cfg *Config) {\n\tclientCapabilities :=\n\t\tclientMySQL |\n\t\t\tclientLongFlag |\n\t\t\tclientProtocol41 |\n\t\t\tclientSecureConn |\n\t\t\tclientTransactions |\n\t\t\tclientPluginAuthLenEncClientData |\n\t\t\tclientLocalFiles |\n\t\t\tclientPluginAuth |\n\t\t\tclientMultiResults |\n\t\t\tclientConnectAttrs |\n\t\t\tclientDeprecateEOF\n\n\tif cfg.ClientFoundRows {\n\t\tclientCapabilities |= clientFoundRows\n\t}\n\tif cfg.compress {\n\t\tclientCapabilities |= clientCompress\n\t}\n\t// To enable TLS / SSL\n\tif mc.cfg.TLS != nil {\n\t\tclientCapabilities |= clientSSL\n\t}\n\n\tif mc.cfg.MultiStatements {\n\t\tclientCapabilities |= clientMultiStatements\n\t}\n\tif n := len(cfg.DBName); n > 0 {\n\t\tclientCapabilities |= clientConnectWithDB\n\t}\n\n\t// only keep client capabilities that server have\n\tmc.capabilities = clientCapabilities & serverCapabilities\n\n\t// set MariaDB extended clientCacheMetadata capability if server support it\n\tmc.extCapabilities = clientCacheMetadata & serverExtCapabilities\n}\n\n// Client Authentication Packet\n// https://dev.mysql.com/doc/dev/mysql-server/latest/page_protocol_connection_phase_packets_protocol_handshake_response.html\nfunc (mc *mysqlConn) writeHandshakeResponsePacket(authResp []byte, plugin string) error {\n\t// packet header  4\n\t// capabilities   4\n\t// maxPacketSize  4\n\t// collation id   1\n\t// filler        23\n\tdata, err := mc.buf.takeSmallBuffer(4*3 + 24)\n\tif err != nil {\n\t\tmc.cleanup()\n\t\treturn err\n\t}\n\t_ = data[4*3+23] // boundery check\n\n\t// clientCapabilities [32 bit]\n\tbinary.LittleEndian.PutUint32(data[4:], uint32(mc.capabilities))\n\n\t// MaxPacketSize [32 bit] (none)\n\tbinary.LittleEndian.PutUint32(data[8:], 0)\n\n\t// Collation ID [1 byte]\n\tdata[12] = defaultCollationID\n\tif cname := mc.cfg.Collation; cname != \"\" {\n\t\tcolID, ok := collations[cname]\n\t\tif ok {\n\t\t\tdata[12] = colID\n\t\t} else if len(mc.cfg.charsets) > 0 {\n\t\t\t// When cfg.charset is set, the collation is set by `SET NAMES <charset> COLLATE <collation>`.\n\t\t\treturn fmt.Errorf(\"unknown collation: %q\", cname)\n\t\t}\n\t}\n\n\t// Filler [23 bytes] (all 0x00)\n\t// or filler 19bytes + mariadb extCapabilities\n\tpos := 13\n\tif mc.capabilities&clientMySQL == 0 {\n\t\tfor ; pos < 13+19; pos++ {\n\t\t\tdata[pos] = 0\n\t\t}\n\t\t// MariaDB Extended Capabilities\n\t\tbinary.LittleEndian.PutUint32(data[13+19:], uint32(mc.extCapabilities))\n\t} else {\n\t\tfor ; pos < 13+23; pos++ {\n\t\t\tdata[pos] = 0\n\t\t}\n\t}\n\n\t// SSL Connection Request Packet\n\t// https://dev.mysql.com/doc/dev/mysql-server/latest/page_protocol_connection_phase_packets_protocol_ssl_request.html\n\t// https://mariadb.com/kb/en/connection/#sslrequest-packet\n\tif mc.cfg.TLS != nil {\n\t\t// Send TLS / SSL request packet\n\t\tif err := mc.writePacket(data); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Switch to TLS\n\t\ttlsConn := tls.Client(mc.netConn, mc.cfg.TLS)\n\t\tif err := tlsConn.Handshake(); err != nil {\n\t\t\tif cerr := mc.canceled.Value(); cerr != nil {\n\t\t\t\treturn cerr\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\tmc.netConn = tlsConn\n\t}\n\n\t// User [null terminated string]\n\tif len(mc.cfg.User) > 0 {\n\t\tdata = append(data, mc.cfg.User...)\n\t}\n\tdata = append(data, 0)\n\n\t// Auth Data [length encoded integer]\n\tdata = appendLengthEncodedInteger(data, uint64(len(authResp)))\n\tdata = append(data, authResp...)\n\n\t// Database name [null terminated string]\n\tif mc.capabilities&clientConnectWithDB != 0 {\n\t\tdata = append(data, mc.cfg.DBName...)\n\t\tdata = append(data, 0)\n\t}\n\n\tdata = append(data, plugin...)\n\tdata = append(data, 0)\n\n\t// Connection Attributes\n\tif mc.capabilities&clientConnectAttrs != 0 {\n\t\tconnAttrsLen := len(mc.connector.encodedAttributes)\n\t\tdata = appendLengthEncodedInteger(data, uint64(connAttrsLen))\n\t\tdata = append(data, mc.connector.encodedAttributes...)\n\t}\n\n\t// Send Auth packet\n\treturn mc.writePacket(data)\n}\n\n// https://dev.mysql.com/doc/dev/mysql-server/latest/page_protocol_connection_phase_packets_protocol_auth_switch_response.html\nfunc (mc *mysqlConn) writeAuthSwitchPacket(authData []byte) error {\n\tpktLen := 4 + len(authData)\n\tdata, err := mc.buf.takeBuffer(pktLen)\n\tif err != nil {\n\t\tmc.cleanup()\n\t\treturn err\n\t}\n\n\t// Add the auth data [EOF]\n\tcopy(data[4:], authData)\n\treturn mc.writePacket(data)\n}\n\n/******************************************************************************\n*                             Command Packets                                 *\n******************************************************************************/\n\nfunc (mc *mysqlConn) writeCommandPacket(command byte) error {\n\t// Reset Packet Sequence\n\tmc.resetSequence()\n\n\tdata, err := mc.buf.takeSmallBuffer(4 + 1)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Add command byte\n\tdata[4] = command\n\n\t// Send CMD packet\n\terr = mc.writePacket(data)\n\tmc.syncSequence()\n\treturn err\n}\n\nfunc (mc *mysqlConn) writeCommandPacketStr(command byte, arg string) error {\n\t// Reset Packet Sequence\n\tmc.resetSequence()\n\n\tpktLen := 1 + len(arg)\n\tdata, err := mc.buf.takeBuffer(pktLen + 4)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Add command byte\n\tdata[4] = command\n\n\t// Add arg\n\tcopy(data[5:], arg)\n\n\t// Send CMD packet\n\terr = mc.writePacket(data)\n\tmc.syncSequence()\n\treturn err\n}\n\nfunc (mc *mysqlConn) writeCommandPacketUint32(command byte, arg uint32) error {\n\t// Reset Packet Sequence\n\tmc.resetSequence()\n\n\tdata, err := mc.buf.takeSmallBuffer(4 + 1 + 4)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Add command byte\n\tdata[4] = command\n\n\t// Add arg [32 bit]\n\tbinary.LittleEndian.PutUint32(data[5:], arg)\n\n\t// Send CMD packet\n\terr = mc.writePacket(data)\n\tmc.syncSequence()\n\treturn err\n}\n\n/******************************************************************************\n*                              Result Packets                                 *\n******************************************************************************/\n\nfunc (mc *mysqlConn) readAuthResult() ([]byte, string, error) {\n\tdata, err := mc.readPacket()\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\t// packet indicator\n\tswitch data[0] {\n\n\tcase iOK:\n\t\t// resultUnchanged, since auth happens before any queries or\n\t\t// commands have been executed.\n\t\treturn nil, \"\", mc.resultUnchanged().handleOkPacket(data)\n\n\tcase iAuthMoreData:\n\t\treturn data[1:], \"\", err\n\n\tcase iEOF:\n\t\tif len(data) == 1 {\n\t\t\t// https://dev.mysql.com/doc/dev/mysql-server/latest/page_protocol_connection_phase_packets_protocol_old_auth_switch_request.html\n\t\t\treturn nil, \"mysql_old_password\", nil\n\t\t}\n\t\tpluginEndIndex := bytes.IndexByte(data, 0x00)\n\t\tif pluginEndIndex < 0 {\n\t\t\treturn nil, \"\", ErrMalformPkt\n\t\t}\n\t\tplugin := string(data[1:pluginEndIndex])\n\t\tauthData := data[pluginEndIndex+1:]\n\t\tif len(authData) > 0 && authData[len(authData)-1] == 0 {\n\t\t\tauthData = authData[:len(authData)-1]\n\t\t}\n\t\treturn authData, plugin, nil\n\n\tdefault: // Error otherwise\n\t\treturn nil, \"\", mc.handleErrorPacket(data)\n\t}\n}\n\n// Returns error if Packet is not a 'Result OK'-Packet\nfunc (mc *okHandler) readResultOK() error {\n\tdata, err := mc.conn().readPacket()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif data[0] == iOK {\n\t\treturn mc.handleOkPacket(data)\n\t}\n\treturn mc.conn().handleErrorPacket(data)\n}\n\n// Result Set Header Packet\n// https://dev.mysql.com/doc/dev/mysql-server/latest/page_protocol_com_query_response.html\nfunc (mc *okHandler) readResultSetHeaderPacket() (int, bool, error) {\n\t// handleOkPacket replaces both values; other cases leave the values unchanged.\n\tmc.result.affectedRows = append(mc.result.affectedRows, 0)\n\tmc.result.insertIds = append(mc.result.insertIds, 0)\n\n\tdata, err := mc.conn().readPacket()\n\tif err != nil {\n\t\treturn 0, false, err\n\t}\n\n\tswitch data[0] {\n\tcase iOK:\n\t\treturn 0, false, mc.handleOkPacket(data)\n\n\tcase iERR:\n\t\treturn 0, false, mc.conn().handleErrorPacket(data)\n\n\tcase iLocalInFile:\n\t\treturn 0, false, mc.handleInFileRequest(string(data[1:]))\n\t}\n\n\t// column count\n\t// https://dev.mysql.com/doc/dev/mysql-server/latest/page_protocol_com_query_response_text_resultset.html\n\t// https://mariadb.com/kb/en/result-set-packets/#column-count-packet\n\tnum, _, len := readLengthEncodedInteger(data)\n\n\tif mc.extCapabilities&clientCacheMetadata != 0 {\n\t\treturn int(num), data[len] == 0x01, nil\n\t}\n\t// ignore remaining data in the packet. see #1478.\n\treturn int(num), true, nil\n}\n\n// Error Packet\n// https://dev.mysql.com/doc/dev/mysql-server/latest/page_protocol_basic_err_packet.html\nfunc (mc *mysqlConn) handleErrorPacket(data []byte) error {\n\tif data[0] != iERR {\n\t\treturn ErrMalformPkt\n\t}\n\n\t// 0xff [1 byte]\n\n\t// Error Number [16 bit uint]\n\terrno := binary.LittleEndian.Uint16(data[1:3])\n\n\t// 1792: ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION\n\t// 1290: ER_OPTION_PREVENTS_STATEMENT (returned by Aurora during failover)\n\t// 1836: ER_READ_ONLY_MODE\n\tif (errno == 1792 || errno == 1290 || errno == 1836) && mc.cfg.RejectReadOnly {\n\t\t// Oops; we are connected to a read-only connection, and won't be able\n\t\t// to issue any write statements. Since RejectReadOnly is configured,\n\t\t// we throw away this connection hoping this one would have write\n\t\t// permission. This is specifically for a possible race condition\n\t\t// during failover (e.g. on AWS Aurora). See README.md for more.\n\t\t//\n\t\t// We explicitly close the connection before returning\n\t\t// driver.ErrBadConn to ensure that `database/sql` purges this\n\t\t// connection and initiates a new one for next statement next time.\n\t\tmc.Close()\n\t\treturn driver.ErrBadConn\n\t}\n\n\tme := &MySQLError{Number: errno}\n\n\tpos := 3\n\n\t// SQL State [optional: # + 5bytes string]\n\tif data[3] == 0x23 {\n\t\tcopy(me.SQLState[:], data[4:4+5])\n\t\tpos = 9\n\t}\n\n\t// Error Message [string]\n\tme.Message = string(data[pos:])\n\n\treturn me\n}\n\nfunc readStatus(b []byte) statusFlag {\n\treturn statusFlag(b[0]) | statusFlag(b[1])<<8\n}\n\n// Returns an instance of okHandler for codepaths where mysqlConn.result doesn't\n// need to be cleared first (e.g. during authentication, or while additional\n// resultsets are being fetched.)\nfunc (mc *mysqlConn) resultUnchanged() *okHandler {\n\treturn (*okHandler)(mc)\n}\n\n// okHandler represents the state of the connection when mysqlConn.result has\n// been prepared for processing of OK packets.\n//\n// To correctly populate mysqlConn.result (updated by handleOkPacket()), all\n// callpaths must either:\n//\n// 1. first clear it using clearResult(), or\n// 2. confirm that they don't need to (by calling resultUnchanged()).\n//\n// Both return an instance of type *okHandler.\ntype okHandler mysqlConn\n\n// Exposes the underlying type's methods.\nfunc (mc *okHandler) conn() *mysqlConn {\n\treturn (*mysqlConn)(mc)\n}\n\n// clearResult clears the connection's stored affectedRows and insertIds\n// fields.\n//\n// It returns a handler that can process OK responses.\nfunc (mc *mysqlConn) clearResult() *okHandler {\n\tmc.result = mysqlResult{}\n\treturn (*okHandler)(mc)\n}\n\n// Ok Packet\n// https://dev.mysql.com/doc/dev/mysql-server/latest/page_protocol_basic_ok_packet.html\nfunc (mc *okHandler) handleOkPacket(data []byte) error {\n\tvar n, m int\n\tvar affectedRows, insertId uint64\n\n\t// 0x00 [1 byte]\n\n\t// Affected rows [Length Coded Binary]\n\taffectedRows, _, n = readLengthEncodedInteger(data[1:])\n\n\t// Insert id [Length Coded Binary]\n\tinsertId, _, m = readLengthEncodedInteger(data[1+n:])\n\n\t// Update for the current statement result (only used by\n\t// readResultSetHeaderPacket).\n\tif len(mc.result.affectedRows) > 0 {\n\t\tmc.result.affectedRows[len(mc.result.affectedRows)-1] = int64(affectedRows)\n\t}\n\tif len(mc.result.insertIds) > 0 {\n\t\tmc.result.insertIds[len(mc.result.insertIds)-1] = int64(insertId)\n\t}\n\n\t// server_status [2 bytes]\n\tmc.status = readStatus(data[1+n+m : 1+n+m+2])\n\tif mc.status&statusMoreResultsExists != 0 {\n\t\treturn nil\n\t}\n\n\t// warning count [2 bytes]\n\n\treturn nil\n}\n\n// Read Packets as Field Packets until EOF-Packet or an Error appears\n// https://dev.mysql.com/doc/dev/mysql-server/latest/page_protocol_com_query_response_text_resultset_column_definition.html#sect_protocol_com_query_response_text_resultset_column_definition_41\nfunc (mc *mysqlConn) readColumns(count int, old []mysqlField) ([]mysqlField, error) {\n\tcolumns := make([]mysqlField, count)\n\tif len(old) != count {\n\t\told = nil\n\t}\n\n\tfor i := range count {\n\t\tdata, err := mc.readPacket()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Catalog\n\t\tpos, err := skipLengthEncodedString(data)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Database [len coded string]\n\t\tn, err := skipLengthEncodedString(data[pos:])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpos += n\n\n\t\t// Table [len coded string]\n\t\tif mc.cfg.ColumnsWithAlias {\n\t\t\ttableName, _, n, err := readLengthEncodedString(data[pos:])\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tpos += n\n\t\t\tif old != nil && old[i].tableName == string(tableName) {\n\t\t\t\t// avoid allocating new string\n\t\t\t\tcolumns[i].tableName = old[i].tableName\n\t\t\t} else {\n\t\t\t\tcolumns[i].tableName = string(tableName)\n\t\t\t}\n\t\t} else {\n\t\t\tn, err = skipLengthEncodedString(data[pos:])\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tpos += n\n\t\t}\n\n\t\t// Original table [len coded string]\n\t\tn, err = skipLengthEncodedString(data[pos:])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpos += n\n\n\t\t// Name [len coded string]\n\t\tname, _, n, err := readLengthEncodedString(data[pos:])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif old != nil && old[i].name == string(name) {\n\t\t\t// avoid allocating new string\n\t\t\tcolumns[i].name = old[i].name\n\t\t} else {\n\t\t\tcolumns[i].name = string(name)\n\t\t}\n\t\tpos += n\n\n\t\t// Original name [len coded string]\n\t\tn, err = skipLengthEncodedString(data[pos:])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpos += n\n\n\t\t// Filler [uint8]\n\t\tpos++\n\n\t\t// Charset [charset, collation uint8]\n\t\tcolumns[i].charSet = data[pos]\n\t\tpos += 2\n\n\t\t// Length [uint32]\n\t\tcolumns[i].length = binary.LittleEndian.Uint32(data[pos : pos+4])\n\t\tpos += 4\n\n\t\t// Field type [uint8]\n\t\tcolumns[i].fieldType = fieldType(data[pos])\n\t\tpos++\n\n\t\t// Flags [uint16]\n\t\tcolumns[i].flags = fieldFlag(binary.LittleEndian.Uint16(data[pos : pos+2]))\n\t\tpos += 2\n\n\t\t// Decimals [uint8]\n\t\tcolumns[i].decimals = data[pos]\n\t}\n\n\t// skip EOF packet if client does not support deprecateEOF\n\tif err := mc.skipEof(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn columns, nil\n}\n\n// Read Packets as Field Packets until EOF-Packet or an Error appears\n// https://dev.mysql.com/doc/dev/mysql-server/latest/page_protocol_com_query_response_text_resultset_row.html\nfunc (rows *textRows) readRow(dest []driver.Value) error {\n\tmc := rows.mc\n\n\tif rows.rs.done {\n\t\treturn io.EOF\n\t}\n\n\tdata, err := mc.readPacket()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// EOF Packet\n\t// text row packets may starts with LengthEncodedString.\n\t// In such case, 0xFE can mean string larger than 0xffffff.\n\t// https://dev.mysql.com/doc/dev/mysql-server/latest/page_protocol_basic_dt_integers.html#sect_protocol_basic_dt_int_le\n\tif data[0] == iEOF && len(data) <= 0xffffff {\n\t\tif mc.capabilities&clientDeprecateEOF == 0 {\n\t\t\t// Deprecated EOF packet\n\t\t\t// https://dev.mysql.com/doc/dev/mysql-server/latest/page_protocol_basic_eof_packet.html\n\t\t\tmc.status = readStatus(data[3:])\n\t\t} else {\n\t\t\t// Ok Packet with an 0xFE header\n\t\t\t_, _, n := readLengthEncodedInteger(data[1:])   // affected_rows\n\t\t\t_, _, m := readLengthEncodedInteger(data[1+n:]) // last_insert_id\n\t\t\tmc.status = readStatus(data[1+n+m:])\n\t\t}\n\t\trows.rs.done = true\n\t\tif !rows.HasNextResultSet() {\n\t\t\trows.mc = nil\n\t\t}\n\t\treturn io.EOF\n\t}\n\tif data[0] == iERR {\n\t\trows.mc = nil\n\t\treturn mc.handleErrorPacket(data)\n\t}\n\n\t// RowSet Packet\n\tvar (\n\t\tn      int\n\t\tisNull bool\n\t\tpos    int = 0\n\t)\n\n\tfor i := range dest {\n\t\t// Read bytes and convert to string\n\t\tvar buf []byte\n\t\tbuf, isNull, n, err = readLengthEncodedString(data[pos:])\n\t\tpos += n\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif isNull {\n\t\t\tdest[i] = nil\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch rows.rs.columns[i].fieldType {\n\t\tcase fieldTypeTimestamp,\n\t\t\tfieldTypeDateTime,\n\t\t\tfieldTypeDate,\n\t\t\tfieldTypeNewDate:\n\t\t\tif mc.parseTime {\n\t\t\t\tdest[i], err = parseDateTime(buf, mc.cfg.Loc)\n\t\t\t} else {\n\t\t\t\tdest[i] = buf\n\t\t\t}\n\n\t\tcase fieldTypeTiny, fieldTypeShort, fieldTypeInt24, fieldTypeYear, fieldTypeLong:\n\t\t\tdest[i], err = strconv.ParseInt(string(buf), 10, 64)\n\n\t\tcase fieldTypeLongLong:\n\t\t\tif rows.rs.columns[i].flags&flagUnsigned != 0 {\n\t\t\t\tdest[i], err = strconv.ParseUint(string(buf), 10, 64)\n\t\t\t} else {\n\t\t\t\tdest[i], err = strconv.ParseInt(string(buf), 10, 64)\n\t\t\t}\n\n\t\tcase fieldTypeFloat:\n\t\t\tvar d float64\n\t\t\td, err = strconv.ParseFloat(string(buf), 32)\n\t\t\tdest[i] = float32(d)\n\n\t\tcase fieldTypeDouble:\n\t\t\tdest[i], err = strconv.ParseFloat(string(buf), 64)\n\n\t\tdefault:\n\t\t\tdest[i] = buf\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (mc *mysqlConn) skipPackets(n int) error {\n\tfor i := 0; i < n; i++ {\n\t\tif _, err := mc.readPacket(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n// skips EOF packet after n * ColumnDefinition packets when clientDeprecateEOF is not set\nfunc (mc *mysqlConn) skipEof() error {\n\tif mc.capabilities&clientDeprecateEOF == 0 {\n\t\tif _, err := mc.readPacket(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (mc *mysqlConn) skipColumns(n int) error {\n\tif err := mc.skipPackets(n); err != nil {\n\t\treturn err\n\t}\n\treturn mc.skipEof()\n}\n\n// Reads Packets until EOF-Packet or an Error appears.\nfunc (mc *mysqlConn) skipRows() error {\n\tfor {\n\t\tdata, err := mc.readPacket()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tswitch data[0] {\n\t\tcase iERR:\n\t\t\treturn mc.handleErrorPacket(data)\n\t\tcase iEOF:\n\t\t\t// text row packets may starts with LengthEncodedString.\n\t\t\t// In such case, 0xFE can mean string larger than 0xffffff.\n\t\t\tif len(data) <= 0xffffff {\n\t\t\t\tif mc.capabilities&clientDeprecateEOF == 0 {\n\t\t\t\t\t// EOF packet\n\t\t\t\t\tmc.status = readStatus(data[3:])\n\t\t\t\t} else {\n\t\t\t\t\t// OK packet with an 0xFE header\n\t\t\t\t\t_, _, n := readLengthEncodedInteger(data[1:])   // affected_rows\n\t\t\t\t\t_, _, m := readLengthEncodedInteger(data[1+n:]) // last_insert_id\n\t\t\t\t\tmc.status = readStatus(data[1+n+m:])\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n}\n\n/******************************************************************************\n*                           Prepared Statements                               *\n******************************************************************************/\n\n// Prepare Result Packets\n// https://dev.mysql.com/doc/dev/mysql-server/latest/page_protocol_com_stmt_prepare.html#sect_protocol_com_stmt_prepare_response\nfunc (stmt *mysqlStmt) readPrepareResultPacket() (uint16, error) {\n\tdata, err := stmt.mc.readPacket()\n\tif err == nil {\n\t\t// packet indicator [1 byte]\n\t\tif data[0] != iOK {\n\t\t\treturn 0, stmt.mc.handleErrorPacket(data)\n\t\t}\n\n\t\t// statement id [4 bytes]\n\t\tstmt.id = binary.LittleEndian.Uint32(data[1:5])\n\n\t\t// Column count [16 bit uint]\n\t\tcolumnCount := binary.LittleEndian.Uint16(data[5:7])\n\n\t\t// Param count [16 bit uint]\n\t\tstmt.paramCount = int(binary.LittleEndian.Uint16(data[7:9]))\n\n\t\t// Reserved [8 bit]\n\n\t\t// Warning count [16 bit uint]\n\n\t\treturn columnCount, nil\n\t}\n\treturn 0, err\n}\n\n// https://dev.mysql.com/doc/dev/mysql-server/latest/page_protocol_com_stmt_send_long_data.html\nfunc (stmt *mysqlStmt) writeCommandLongData(paramID int, arg []byte) error {\n\tmaxLen := stmt.mc.maxAllowedPacket - 1\n\tpktLen := maxLen\n\n\t// After the header (bytes 0-3) follows before the data:\n\t// 1 byte command\n\t// 4 bytes stmtID\n\t// 2 bytes paramID\n\tconst dataOffset = 1 + 4 + 2\n\n\t// Cannot use the write buffer since\n\t// a) the buffer is too small\n\t// b) it is in use\n\tdata := make([]byte, 4+1+4+2+len(arg))\n\n\tcopy(data[4+dataOffset:], arg)\n\n\tfor argLen := len(arg); argLen > 0; argLen -= pktLen - dataOffset {\n\t\tif dataOffset+argLen < maxLen {\n\t\t\tpktLen = dataOffset + argLen\n\t\t}\n\n\t\t// Add command byte [1 byte]\n\t\tdata[4] = comStmtSendLongData\n\n\t\t// Add stmtID [32 bit]\n\t\tbinary.LittleEndian.PutUint32(data[5:], stmt.id)\n\n\t\t// Add paramID [16 bit]\n\t\tbinary.LittleEndian.PutUint16(data[9:], uint16(paramID))\n\n\t\t// Send CMD packet\n\t\terr := stmt.mc.writePacket(data[:4+pktLen])\n\t\t// Every COM_LONG_DATA packet reset Packet Sequence\n\t\tstmt.mc.resetSequence()\n\t\tif err == nil {\n\t\t\tdata = data[pktLen-dataOffset:]\n\t\t\tcontinue\n\t\t}\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n// Execute Prepared Statement\n// https://dev.mysql.com/doc/dev/mysql-server/latest/page_protocol_com_stmt_execute.html\nfunc (stmt *mysqlStmt) writeExecutePacket(args []driver.Value) error {\n\tif len(args) != stmt.paramCount {\n\t\treturn fmt.Errorf(\n\t\t\t\"argument count mismatch (got: %d; has: %d)\",\n\t\t\tlen(args),\n\t\t\tstmt.paramCount,\n\t\t)\n\t}\n\n\tconst minPktLen = 4 + 1 + 4 + 1 + 4\n\tmc := stmt.mc\n\n\t// Determine threshold dynamically to avoid packet size shortage.\n\tlongDataSize := max(mc.maxAllowedPacket/(stmt.paramCount+1), 64)\n\n\t// Reset packet-sequence\n\tmc.resetSequence()\n\n\tvar data []byte\n\tvar err error\n\n\tif len(args) == 0 {\n\t\tdata, err = mc.buf.takeBuffer(minPktLen)\n\t} else {\n\t\tdata, err = mc.buf.takeCompleteBuffer()\n\t\t// In this case the len(data) == cap(data) which is used to optimise the flow below.\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// command [1 byte]\n\tdata[4] = comStmtExecute\n\n\t// statement_id [4 bytes]\n\tbinary.LittleEndian.PutUint32(data[5:], stmt.id)\n\n\t// flags (0: CURSOR_TYPE_NO_CURSOR) [1 byte]\n\tdata[9] = 0x00\n\n\t// iteration_count (uint32(1)) [4 bytes]\n\tbinary.LittleEndian.PutUint32(data[10:], 1)\n\n\tif len(args) > 0 {\n\t\tpos := minPktLen\n\n\t\tvar nullMask []byte\n\t\tif maskLen, typesLen := (len(args)+7)/8, 1+2*len(args); pos+maskLen+typesLen >= cap(data) {\n\t\t\t// buffer has to be extended but we don't know by how much so\n\t\t\t// we depend on append after all data with known sizes fit.\n\t\t\t// We stop at that because we deal with a lot of columns here\n\t\t\t// which makes the required allocation size hard to guess.\n\t\t\ttmp := make([]byte, pos+maskLen+typesLen)\n\t\t\tcopy(tmp[:pos], data[:pos])\n\t\t\tdata = tmp\n\t\t\tnullMask = data[pos : pos+maskLen]\n\t\t\t// No need to clean nullMask as make ensures that.\n\t\t\tpos += maskLen\n\t\t} else {\n\t\t\tnullMask = data[pos : pos+maskLen]\n\t\t\tfor i := range nullMask {\n\t\t\t\tnullMask[i] = 0\n\t\t\t}\n\t\t\tpos += maskLen\n\t\t}\n\n\t\t// newParameterBoundFlag 1 [1 byte]\n\t\tdata[pos] = 0x01\n\t\tpos++\n\n\t\t// type of each parameter [len(args)*2 bytes]\n\t\tparamTypes := data[pos:]\n\t\tpos += len(args) * 2\n\n\t\t// value of each parameter [n bytes]\n\t\tparamValues := data[pos:pos]\n\t\tvaluesCap := cap(paramValues)\n\n\t\tfor i, arg := range args {\n\t\t\t// build NULL-bitmap\n\t\t\tif arg == nil {\n\t\t\t\tnullMask[i/8] |= 1 << (uint(i) & 7)\n\t\t\t\tparamTypes[i+i] = byte(fieldTypeNULL)\n\t\t\t\tparamTypes[i+i+1] = 0x00\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif v, ok := arg.(json.RawMessage); ok {\n\t\t\t\targ = []byte(v)\n\t\t\t}\n\t\t\t// cache types and values\n\t\t\tswitch v := arg.(type) {\n\t\t\tcase int64:\n\t\t\t\tparamTypes[i+i] = byte(fieldTypeLongLong)\n\t\t\t\tparamTypes[i+i+1] = 0x00\n\t\t\t\tparamValues = binary.LittleEndian.AppendUint64(paramValues, uint64(v))\n\n\t\t\tcase uint64:\n\t\t\t\tparamTypes[i+i] = byte(fieldTypeLongLong)\n\t\t\t\tparamTypes[i+i+1] = 0x80 // type is unsigned\n\t\t\t\tparamValues = binary.LittleEndian.AppendUint64(paramValues, uint64(v))\n\n\t\t\tcase float64:\n\t\t\t\tparamTypes[i+i] = byte(fieldTypeDouble)\n\t\t\t\tparamTypes[i+i+1] = 0x00\n\t\t\t\tparamValues = binary.LittleEndian.AppendUint64(paramValues, math.Float64bits(v))\n\n\t\t\tcase bool:\n\t\t\t\tparamTypes[i+i] = byte(fieldTypeTiny)\n\t\t\t\tparamTypes[i+i+1] = 0x00\n\n\t\t\t\tif v {\n\t\t\t\t\tparamValues = append(paramValues, 0x01)\n\t\t\t\t} else {\n\t\t\t\t\tparamValues = append(paramValues, 0x00)\n\t\t\t\t}\n\n\t\t\tcase []byte:\n\t\t\t\t// Common case (non-nil value) first\n\t\t\t\tif v != nil {\n\t\t\t\t\tparamTypes[i+i] = byte(fieldTypeString)\n\t\t\t\t\tparamTypes[i+i+1] = 0x00\n\n\t\t\t\t\tif len(v) < longDataSize {\n\t\t\t\t\t\tparamValues = appendLengthEncodedInteger(paramValues,\n\t\t\t\t\t\t\tuint64(len(v)),\n\t\t\t\t\t\t)\n\t\t\t\t\t\tparamValues = append(paramValues, v...)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif err := stmt.writeCommandLongData(i, v); err != nil {\n\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// Handle []byte(nil) as a NULL value\n\t\t\t\tnullMask[i/8] |= 1 << (uint(i) & 7)\n\t\t\t\tparamTypes[i+i] = byte(fieldTypeNULL)\n\t\t\t\tparamTypes[i+i+1] = 0x00\n\n\t\t\tcase string:\n\t\t\t\tparamTypes[i+i] = byte(fieldTypeString)\n\t\t\t\tparamTypes[i+i+1] = 0x00\n\n\t\t\t\tif len(v) < longDataSize {\n\t\t\t\t\tparamValues = appendLengthEncodedInteger(paramValues,\n\t\t\t\t\t\tuint64(len(v)),\n\t\t\t\t\t)\n\t\t\t\t\tparamValues = append(paramValues, v...)\n\t\t\t\t} else {\n\t\t\t\t\tif err := stmt.writeCommandLongData(i, []byte(v)); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\tcase time.Time:\n\t\t\t\tparamTypes[i+i] = byte(fieldTypeString)\n\t\t\t\tparamTypes[i+i+1] = 0x00\n\n\t\t\t\tvar a [64]byte\n\t\t\t\tvar b = a[:0]\n\n\t\t\t\tif v.IsZero() {\n\t\t\t\t\tb = append(b, \"0000-00-00\"...)\n\t\t\t\t} else {\n\t\t\t\t\tb, err = appendDateTime(b, v.In(mc.cfg.Loc), mc.cfg.timeTruncate)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tparamValues = appendLengthEncodedInteger(paramValues,\n\t\t\t\t\tuint64(len(b)),\n\t\t\t\t)\n\t\t\t\tparamValues = append(paramValues, b...)\n\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"cannot convert type: %T\", arg)\n\t\t\t}\n\t\t}\n\n\t\t// Check if param values exceeded the available buffer\n\t\t// In that case we must build the data packet with the new values buffer\n\t\tif valuesCap != cap(paramValues) {\n\t\t\tdata = append(data[:pos], paramValues...)\n\t\t\tmc.buf.store(data) // allow this buffer to be reused\n\t\t}\n\n\t\tpos += len(paramValues)\n\t\tdata = data[:pos]\n\t}\n\n\terr = mc.writePacket(data)\n\tmc.syncSequence()\n\treturn err\n}\n\n// For each remaining resultset in the stream, discards its rows and updates\n// mc.affectedRows and mc.insertIds.\nfunc (mc *okHandler) discardResults() error {\n\tfor mc.status&statusMoreResultsExists != 0 {\n\t\tresLen, _, err := mc.readResultSetHeaderPacket()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif resLen > 0 {\n\t\t\t// columns\n\t\t\tif err := mc.conn().skipColumns(resLen); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// rows\n\t\t\tif err := mc.conn().skipRows(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\n// https://dev.mysql.com/doc/dev/mysql-server/latest/page_protocol_binary_resultset.html#sect_protocol_binary_resultset_row\nfunc (rows *binaryRows) readRow(dest []driver.Value) error {\n\tdata, err := rows.mc.readPacket()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// packet indicator [1 byte]\n\tif data[0] != iOK {\n\t\t// EOF/OK Packet\n\t\tif data[0] == iEOF {\n\t\t\tif rows.mc.capabilities&clientDeprecateEOF == 0 {\n\t\t\t\t// EOF packet\n\t\t\t\trows.mc.status = readStatus(data[3:])\n\t\t\t} else {\n\t\t\t\t// OK Packet with an 0xFE header\n\t\t\t\t_, _, n := readLengthEncodedInteger(data[1:])\n\t\t\t\t_, _, m := readLengthEncodedInteger(data[1+n:])\n\t\t\t\trows.mc.status = readStatus(data[1+n+m:])\n\t\t\t}\n\t\t\trows.rs.done = true\n\t\t\tif !rows.HasNextResultSet() {\n\t\t\t\trows.mc = nil\n\t\t\t}\n\t\t\treturn io.EOF\n\t\t}\n\t\tmc := rows.mc\n\t\trows.mc = nil\n\n\t\t// Error otherwise\n\t\treturn mc.handleErrorPacket(data)\n\t}\n\n\t// NULL-bitmap,  [(column-count + 7 + 2) / 8 bytes]\n\tpos := 1 + (len(dest)+7+2)>>3\n\tnullMask := data[1:pos]\n\n\tfor i := range dest {\n\t\t// Field is NULL\n\t\t// (byte >> bit-pos) % 2 == 1\n\t\tif ((nullMask[(i+2)>>3] >> uint((i+2)&7)) & 1) == 1 {\n\t\t\tdest[i] = nil\n\t\t\tcontinue\n\t\t}\n\n\t\t// Convert to byte-coded string\n\t\tswitch rows.rs.columns[i].fieldType {\n\t\tcase fieldTypeNULL:\n\t\t\tdest[i] = nil\n\t\t\tcontinue\n\n\t\t// Numeric Types\n\t\tcase fieldTypeTiny:\n\t\t\tif rows.rs.columns[i].flags&flagUnsigned != 0 {\n\t\t\t\tdest[i] = int64(data[pos])\n\t\t\t} else {\n\t\t\t\tdest[i] = int64(int8(data[pos]))\n\t\t\t}\n\t\t\tpos++\n\t\t\tcontinue\n\n\t\tcase fieldTypeShort, fieldTypeYear:\n\t\t\tif rows.rs.columns[i].flags&flagUnsigned != 0 {\n\t\t\t\tdest[i] = int64(binary.LittleEndian.Uint16(data[pos : pos+2]))\n\t\t\t} else {\n\t\t\t\tdest[i] = int64(int16(binary.LittleEndian.Uint16(data[pos : pos+2])))\n\t\t\t}\n\t\t\tpos += 2\n\t\t\tcontinue\n\n\t\tcase fieldTypeInt24, fieldTypeLong:\n\t\t\tif rows.rs.columns[i].flags&flagUnsigned != 0 {\n\t\t\t\tdest[i] = int64(binary.LittleEndian.Uint32(data[pos : pos+4]))\n\t\t\t} else {\n\t\t\t\tdest[i] = int64(int32(binary.LittleEndian.Uint32(data[pos : pos+4])))\n\t\t\t}\n\t\t\tpos += 4\n\t\t\tcontinue\n\n\t\tcase fieldTypeLongLong:\n\t\t\tif rows.rs.columns[i].flags&flagUnsigned != 0 {\n\t\t\t\tval := binary.LittleEndian.Uint64(data[pos : pos+8])\n\t\t\t\tif val > math.MaxInt64 {\n\t\t\t\t\tdest[i] = uint64ToString(val)\n\t\t\t\t} else {\n\t\t\t\t\tdest[i] = int64(val)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdest[i] = int64(binary.LittleEndian.Uint64(data[pos : pos+8]))\n\t\t\t}\n\t\t\tpos += 8\n\t\t\tcontinue\n\n\t\tcase fieldTypeFloat:\n\t\t\tdest[i] = math.Float32frombits(binary.LittleEndian.Uint32(data[pos : pos+4]))\n\t\t\tpos += 4\n\t\t\tcontinue\n\n\t\tcase fieldTypeDouble:\n\t\t\tdest[i] = math.Float64frombits(binary.LittleEndian.Uint64(data[pos : pos+8]))\n\t\t\tpos += 8\n\t\t\tcontinue\n\n\t\t// Length coded Binary Strings\n\t\tcase fieldTypeDecimal, fieldTypeNewDecimal, fieldTypeVarChar,\n\t\t\tfieldTypeBit, fieldTypeEnum, fieldTypeSet, fieldTypeTinyBLOB,\n\t\t\tfieldTypeMediumBLOB, fieldTypeLongBLOB, fieldTypeBLOB,\n\t\t\tfieldTypeVarString, fieldTypeString, fieldTypeGeometry, fieldTypeJSON,\n\t\t\tfieldTypeVector:\n\t\t\tvar isNull bool\n\t\t\tvar n int\n\t\t\tdest[i], isNull, n, err = readLengthEncodedString(data[pos:])\n\t\t\tpos += n\n\t\t\tif err == nil {\n\t\t\t\tif !isNull {\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\tdest[i] = nil\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn err\n\n\t\tcase\n\t\t\tfieldTypeDate, fieldTypeNewDate, // Date YYYY-MM-DD\n\t\t\tfieldTypeTime,                         // Time [-][H]HH:MM:SS[.fractal]\n\t\t\tfieldTypeTimestamp, fieldTypeDateTime: // Timestamp YYYY-MM-DD HH:MM:SS[.fractal]\n\n\t\t\tnum, isNull, n := readLengthEncodedInteger(data[pos:])\n\t\t\tpos += n\n\n\t\t\tswitch {\n\t\t\tcase isNull:\n\t\t\t\tdest[i] = nil\n\t\t\t\tcontinue\n\t\t\tcase rows.rs.columns[i].fieldType == fieldTypeTime:\n\t\t\t\t// database/sql does not support an equivalent to TIME, return a string\n\t\t\t\tvar dstlen uint8\n\t\t\t\tswitch decimals := rows.rs.columns[i].decimals; decimals {\n\t\t\t\tcase 0x00, 0x1f:\n\t\t\t\t\tdstlen = 8\n\t\t\t\tcase 1, 2, 3, 4, 5, 6:\n\t\t\t\t\tdstlen = 8 + 1 + decimals\n\t\t\t\tdefault:\n\t\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\t\"protocol error, illegal decimals value %d\",\n\t\t\t\t\t\trows.rs.columns[i].decimals,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tdest[i], err = formatBinaryTime(data[pos:pos+int(num)], dstlen)\n\t\t\tcase rows.mc.parseTime:\n\t\t\t\tdest[i], err = parseBinaryDateTime(num, data[pos:], rows.mc.cfg.Loc)\n\t\t\tdefault:\n\t\t\t\tvar dstlen uint8\n\t\t\t\tif rows.rs.columns[i].fieldType == fieldTypeDate {\n\t\t\t\t\tdstlen = 10\n\t\t\t\t} else {\n\t\t\t\t\tswitch decimals := rows.rs.columns[i].decimals; decimals {\n\t\t\t\t\tcase 0x00, 0x1f:\n\t\t\t\t\t\tdstlen = 19\n\t\t\t\t\tcase 1, 2, 3, 4, 5, 6:\n\t\t\t\t\t\tdstlen = 19 + 1 + decimals\n\t\t\t\t\tdefault:\n\t\t\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\t\t\"protocol error, illegal decimals value %d\",\n\t\t\t\t\t\t\trows.rs.columns[i].decimals,\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tdest[i], err = formatBinaryDateTime(data[pos:pos+int(num)], dstlen)\n\t\t\t}\n\n\t\t\tif err == nil {\n\t\t\t\tpos += int(num)\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t// Please report if this happens!\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"unknown field type %d\", rows.rs.columns[i].fieldType)\n\t\t}\n\t}\n\n\treturn nil\n}\n"
  },
  {
    "path": "packets_test.go",
    "content": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2016 The Go-MySQL-Driver Authors. All rights reserved.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at http://mozilla.org/MPL/2.0/.\n\npackage mysql\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"net\"\n\t\"testing\"\n\t\"time\"\n)\n\nvar (\n\terrConnClosed        = errors.New(\"connection is closed\")\n\terrConnTooManyReads  = errors.New(\"too many reads\")\n\terrConnTooManyWrites = errors.New(\"too many writes\")\n)\n\n// struct to mock a net.Conn for testing purposes\ntype mockConn struct {\n\tladdr         net.Addr\n\traddr         net.Addr\n\tdata          []byte\n\twritten       []byte\n\tqueuedReplies [][]byte\n\tclosed        bool\n\tread          int\n\treads         int\n\twrites        int\n\tmaxReads      int\n\tmaxWrites     int\n}\n\nfunc (m *mockConn) Read(b []byte) (n int, err error) {\n\tif m.closed {\n\t\treturn 0, errConnClosed\n\t}\n\n\tm.reads++\n\tif m.maxReads > 0 && m.reads > m.maxReads {\n\t\treturn 0, errConnTooManyReads\n\t}\n\n\tn = copy(b, m.data)\n\tm.read += n\n\tm.data = m.data[n:]\n\treturn\n}\nfunc (m *mockConn) Write(b []byte) (n int, err error) {\n\tif m.closed {\n\t\treturn 0, errConnClosed\n\t}\n\n\tm.writes++\n\tif m.maxWrites > 0 && m.writes > m.maxWrites {\n\t\treturn 0, errConnTooManyWrites\n\t}\n\n\tn = len(b)\n\tm.written = append(m.written, b...)\n\n\tif n > 0 && len(m.queuedReplies) > 0 {\n\t\tm.data = m.queuedReplies[0]\n\t\tm.queuedReplies = m.queuedReplies[1:]\n\t}\n\treturn\n}\nfunc (m *mockConn) Close() error {\n\tm.closed = true\n\treturn nil\n}\nfunc (m *mockConn) LocalAddr() net.Addr {\n\treturn m.laddr\n}\nfunc (m *mockConn) RemoteAddr() net.Addr {\n\treturn m.raddr\n}\nfunc (m *mockConn) SetDeadline(t time.Time) error {\n\treturn nil\n}\nfunc (m *mockConn) SetReadDeadline(t time.Time) error {\n\treturn nil\n}\nfunc (m *mockConn) SetWriteDeadline(t time.Time) error {\n\treturn nil\n}\n\n// make sure mockConn implements the net.Conn interface\nvar _ net.Conn = new(mockConn)\n\nfunc newRWMockConn(sequence uint8) (*mockConn, *mysqlConn) {\n\tconn := new(mockConn)\n\tconnector := newConnector(NewConfig())\n\tmc := &mysqlConn{\n\t\tbuf:              newBuffer(),\n\t\tcfg:              connector.cfg,\n\t\tconnector:        connector,\n\t\tnetConn:          conn,\n\t\tclosech:          make(chan struct{}),\n\t\tmaxAllowedPacket: defaultMaxAllowedPacket,\n\t\tsequence:         sequence,\n\t}\n\treturn conn, mc\n}\n\nfunc TestReadPacketSingleByte(t *testing.T) {\n\tconn := new(mockConn)\n\tmc := &mysqlConn{\n\t\tnetConn: conn,\n\t\tbuf:     newBuffer(),\n\t\tcfg:     NewConfig(),\n\t}\n\n\tconn.data = []byte{0x01, 0x00, 0x00, 0x00, 0xff}\n\tconn.maxReads = 1\n\tpacket, err := mc.readPacket()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif len(packet) != 1 {\n\t\tt.Fatalf(\"unexpected packet length: expected %d, got %d\", 1, len(packet))\n\t}\n\tif packet[0] != 0xff {\n\t\tt.Fatalf(\"unexpected packet content: expected %x, got %x\", 0xff, packet[0])\n\t}\n}\n\nfunc TestReadPacketWrongSequenceID(t *testing.T) {\n\tfor _, testCase := range []struct {\n\t\tClientSequenceID byte\n\t\tServerSequenceID byte\n\t\tExpectedErr      error\n\t}{\n\t\t{\n\t\t\tClientSequenceID: 1,\n\t\t\tServerSequenceID: 0,\n\t\t\tExpectedErr:      ErrPktSync,\n\t\t},\n\t\t{\n\t\t\tClientSequenceID: 0,\n\t\t\tServerSequenceID: 0x42,\n\t\t\tExpectedErr:      ErrPktSync,\n\t\t},\n\t} {\n\t\tconn, mc := newRWMockConn(testCase.ClientSequenceID)\n\n\t\tconn.data = []byte{0x01, 0x00, 0x00, testCase.ServerSequenceID, 0x22}\n\t\t_, err := mc.readPacket()\n\t\tif err != testCase.ExpectedErr {\n\t\t\tt.Errorf(\"expected %v, got %v\", testCase.ExpectedErr, err)\n\t\t}\n\n\t\t// connection should not be returned to the pool in this state\n\t\tif mc.IsValid() {\n\t\t\tt.Errorf(\"expected IsValid() to be false\")\n\t\t}\n\t}\n}\n\nfunc TestReadPacketSplit(t *testing.T) {\n\tconn := new(mockConn)\n\tmc := &mysqlConn{\n\t\tnetConn: conn,\n\t\tbuf:     newBuffer(),\n\t\tcfg:     NewConfig(),\n\t}\n\n\tdata := make([]byte, maxPacketSize*2+4*3)\n\tconst pkt2ofs = maxPacketSize + 4\n\tconst pkt3ofs = 2 * (maxPacketSize + 4)\n\n\t// case 1: payload has length maxPacketSize\n\tdata = data[:pkt2ofs+4]\n\n\t// 1st packet has maxPacketSize length and sequence id 0\n\t// ff ff ff 00 ...\n\tdata[0] = 0xff\n\tdata[1] = 0xff\n\tdata[2] = 0xff\n\n\t// mark the payload start and end of 1st packet so that we can check if the\n\t// content was correctly appended\n\tdata[4] = 0x11\n\tdata[maxPacketSize+3] = 0x22\n\n\t// 2nd packet has payload length 0 and sequence id 1\n\t// 00 00 00 01\n\tdata[pkt2ofs+3] = 0x01\n\n\tconn.data = data\n\tconn.maxReads = 3\n\tpacket, err := mc.readPacket()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif len(packet) != maxPacketSize {\n\t\tt.Fatalf(\"unexpected packet length: expected %d, got %d\", maxPacketSize, len(packet))\n\t}\n\tif packet[0] != 0x11 {\n\t\tt.Fatalf(\"unexpected payload start: expected %x, got %x\", 0x11, packet[0])\n\t}\n\tif packet[maxPacketSize-1] != 0x22 {\n\t\tt.Fatalf(\"unexpected payload end: expected %x, got %x\", 0x22, packet[maxPacketSize-1])\n\t}\n\n\t// case 2: payload has length which is a multiple of maxPacketSize\n\tdata = data[:cap(data)]\n\n\t// 2nd packet now has maxPacketSize length\n\tdata[pkt2ofs] = 0xff\n\tdata[pkt2ofs+1] = 0xff\n\tdata[pkt2ofs+2] = 0xff\n\n\t// mark the payload start and end of the 2nd packet\n\tdata[pkt2ofs+4] = 0x33\n\tdata[pkt2ofs+maxPacketSize+3] = 0x44\n\n\t// 3rd packet has payload length 0 and sequence id 2\n\t// 00 00 00 02\n\tdata[pkt3ofs+3] = 0x02\n\n\tconn.data = data\n\tconn.reads = 0\n\tconn.maxReads = 5\n\tmc.sequence = 0\n\tpacket, err = mc.readPacket()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif len(packet) != 2*maxPacketSize {\n\t\tt.Fatalf(\"unexpected packet length: expected %d, got %d\", 2*maxPacketSize, len(packet))\n\t}\n\tif packet[0] != 0x11 {\n\t\tt.Fatalf(\"unexpected payload start: expected %x, got %x\", 0x11, packet[0])\n\t}\n\tif packet[2*maxPacketSize-1] != 0x44 {\n\t\tt.Fatalf(\"unexpected payload end: expected %x, got %x\", 0x44, packet[2*maxPacketSize-1])\n\t}\n\n\t// case 3: payload has a length larger maxPacketSize, which is not an exact\n\t// multiple of it\n\tdata = data[:pkt2ofs+4+42]\n\tdata[pkt2ofs] = 0x2a\n\tdata[pkt2ofs+1] = 0x00\n\tdata[pkt2ofs+2] = 0x00\n\tdata[pkt2ofs+4+41] = 0x44\n\n\tconn.data = data\n\tconn.reads = 0\n\tconn.maxReads = 4\n\tmc.sequence = 0\n\tpacket, err = mc.readPacket()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif len(packet) != maxPacketSize+42 {\n\t\tt.Fatalf(\"unexpected packet length: expected %d, got %d\", maxPacketSize+42, len(packet))\n\t}\n\tif packet[0] != 0x11 {\n\t\tt.Fatalf(\"unexpected payload start: expected %x, got %x\", 0x11, packet[0])\n\t}\n\tif packet[maxPacketSize+41] != 0x44 {\n\t\tt.Fatalf(\"unexpected payload end: expected %x, got %x\", 0x44, packet[maxPacketSize+41])\n\t}\n}\n\nfunc TestReadPacketFail(t *testing.T) {\n\tconn := new(mockConn)\n\tmc := &mysqlConn{\n\t\tnetConn: conn,\n\t\tbuf:     newBuffer(),\n\t\tclosech: make(chan struct{}),\n\t\tcfg:     NewConfig(),\n\t}\n\n\t// illegal empty (stand-alone) packet\n\tconn.data = []byte{0x00, 0x00, 0x00, 0x00}\n\tconn.maxReads = 1\n\t_, err := mc.readPacket()\n\tif err != ErrInvalidConn {\n\t\tt.Errorf(\"expected ErrInvalidConn, got %v\", err)\n\t}\n\n\t// reset\n\tconn.reads = 0\n\tmc.sequence = 0\n\tmc.buf = newBuffer()\n\n\t// fail to read header\n\tconn.closed = true\n\t_, err = mc.readPacket()\n\tif err != ErrInvalidConn {\n\t\tt.Errorf(\"expected ErrInvalidConn, got %v\", err)\n\t}\n\n\t// reset\n\tconn.closed = false\n\tconn.reads = 0\n\tmc.sequence = 0\n\tmc.buf = newBuffer()\n\n\t// fail to read body\n\tconn.maxReads = 1\n\t_, err = mc.readPacket()\n\tif err != ErrInvalidConn {\n\t\tt.Errorf(\"expected ErrInvalidConn, got %v\", err)\n\t}\n}\n\n// https://github.com/go-sql-driver/mysql/pull/801\n// not-NUL terminated plugin_name in init packet\nfunc TestRegression801(t *testing.T) {\n\tconn := new(mockConn)\n\tmc := &mysqlConn{\n\t\tnetConn:  conn,\n\t\tbuf:      newBuffer(),\n\t\tcfg:      new(Config),\n\t\tsequence: 42,\n\t\tclosech:  make(chan struct{}),\n\t}\n\n\tconn.data = []byte{72, 0, 0, 42, 10, 53, 46, 53, 46, 56, 0, 165, 0, 0, 0,\n\t\t60, 70, 63, 58, 68, 104, 34, 97, 0, 223, 247, 33, 2, 0, 15, 128, 21, 0,\n\t\t0, 0, 0, 0, 0, 0, 0, 0, 0, 98, 120, 114, 47, 85, 75, 109, 99, 51, 77,\n\t\t50, 64, 0, 109, 121, 115, 113, 108, 95, 110, 97, 116, 105, 118, 101, 95,\n\t\t112, 97, 115, 115, 119, 111, 114, 100}\n\tconn.maxReads = 1\n\n\tauthData, serverCapabilities, serverExtendedCapabilities, pluginName, err := mc.readHandshakePacket()\n\tif err != nil {\n\t\tt.Fatalf(\"got error: %v\", err)\n\t}\n\n\tif serverCapabilities != 2148530143 {\n\t\tt.Fatalf(\"expected serverCapabilities to be 2148530143, got %v\", serverCapabilities)\n\t}\n\n\tif serverExtendedCapabilities != 0 {\n\t\tt.Fatalf(\"expected serverExtendedCapabilities to be 0, got %v\", serverExtendedCapabilities)\n\t}\n\n\tif pluginName != \"mysql_native_password\" {\n\t\tt.Errorf(\"expected plugin name 'mysql_native_password', got '%s'\", pluginName)\n\t}\n\n\texpectedAuthData := []byte{60, 70, 63, 58, 68, 104, 34, 97, 98, 120, 114,\n\t\t47, 85, 75, 109, 99, 51, 77, 50, 64}\n\tif !bytes.Equal(authData, expectedAuthData) {\n\t\tt.Errorf(\"expected authData '%v', got '%v'\", expectedAuthData, authData)\n\t}\n}\n"
  },
  {
    "path": "result.go",
    "content": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at http://mozilla.org/MPL/2.0/.\n\npackage mysql\n\nimport \"slices\"\n\nimport \"database/sql/driver\"\n\n// Result exposes data not available through *connection.Result.\n//\n// This is accessible by executing statements using sql.Conn.Raw() and\n// downcasting the returned result:\n//\n//\tres, err := rawConn.Exec(...)\n//\tres.(mysql.Result).AllRowsAffected()\ntype Result interface {\n\tdriver.Result\n\t// AllRowsAffected returns a slice containing the affected rows for each\n\t// executed statement.\n\tAllRowsAffected() []int64\n\t// AllLastInsertIds returns a slice containing the last inserted ID for each\n\t// executed statement.\n\tAllLastInsertIds() []int64\n}\n\ntype mysqlResult struct {\n\t// One entry in both slices is created for every executed statement result.\n\taffectedRows []int64\n\tinsertIds    []int64\n}\n\nfunc (res *mysqlResult) LastInsertId() (int64, error) {\n\treturn res.insertIds[len(res.insertIds)-1], nil\n}\n\nfunc (res *mysqlResult) RowsAffected() (int64, error) {\n\treturn res.affectedRows[len(res.affectedRows)-1], nil\n}\n\nfunc (res *mysqlResult) AllLastInsertIds() []int64 {\n\treturn slices.Clone(res.insertIds) // defensive copy\n}\n\nfunc (res *mysqlResult) AllRowsAffected() []int64 {\n\treturn slices.Clone(res.affectedRows) // defensive copy\n}\n"
  },
  {
    "path": "rows.go",
    "content": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at http://mozilla.org/MPL/2.0/.\n\npackage mysql\n\nimport (\n\t\"database/sql/driver\"\n\t\"io\"\n\t\"math\"\n\t\"reflect\"\n)\n\ntype resultSet struct {\n\tcolumns     []mysqlField\n\tcolumnNames []string\n\tdone        bool\n}\n\ntype mysqlRows struct {\n\tmc     *mysqlConn\n\trs     resultSet\n\tfinish func()\n}\n\ntype binaryRows struct {\n\tmysqlRows\n}\n\ntype textRows struct {\n\tmysqlRows\n}\n\nfunc (rows *mysqlRows) Columns() []string {\n\tif rows.rs.columnNames != nil {\n\t\treturn rows.rs.columnNames\n\t}\n\n\tcolumns := make([]string, len(rows.rs.columns))\n\tif rows.mc != nil && rows.mc.cfg.ColumnsWithAlias {\n\t\tfor i := range columns {\n\t\t\tif tableName := rows.rs.columns[i].tableName; len(tableName) > 0 {\n\t\t\t\tcolumns[i] = tableName + \".\" + rows.rs.columns[i].name\n\t\t\t} else {\n\t\t\t\tcolumns[i] = rows.rs.columns[i].name\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor i := range columns {\n\t\t\tcolumns[i] = rows.rs.columns[i].name\n\t\t}\n\t}\n\n\trows.rs.columnNames = columns\n\treturn columns\n}\n\nfunc (rows *mysqlRows) ColumnTypeDatabaseTypeName(i int) string {\n\treturn rows.rs.columns[i].typeDatabaseName()\n}\n\n// func (rows *mysqlRows) ColumnTypeLength(i int) (length int64, ok bool) {\n// \treturn int64(rows.rs.columns[i].length), true\n// }\n\nfunc (rows *mysqlRows) ColumnTypeNullable(i int) (nullable, ok bool) {\n\treturn rows.rs.columns[i].flags&flagNotNULL == 0, true\n}\n\nfunc (rows *mysqlRows) ColumnTypePrecisionScale(i int) (int64, int64, bool) {\n\tcolumn := rows.rs.columns[i]\n\tdecimals := int64(column.decimals)\n\n\tswitch column.fieldType {\n\tcase fieldTypeDecimal, fieldTypeNewDecimal:\n\t\tif decimals > 0 {\n\t\t\treturn int64(column.length) - 2, decimals, true\n\t\t}\n\t\treturn int64(column.length) - 1, decimals, true\n\tcase fieldTypeTimestamp, fieldTypeDateTime, fieldTypeTime:\n\t\treturn decimals, decimals, true\n\tcase fieldTypeFloat, fieldTypeDouble:\n\t\tif decimals == 0x1f {\n\t\t\treturn math.MaxInt64, math.MaxInt64, true\n\t\t}\n\t\treturn math.MaxInt64, decimals, true\n\t}\n\n\treturn 0, 0, false\n}\n\nfunc (rows *mysqlRows) ColumnTypeScanType(i int) reflect.Type {\n\treturn rows.rs.columns[i].scanType()\n}\n\nfunc (rows *mysqlRows) Close() (err error) {\n\tif f := rows.finish; f != nil {\n\t\tf()\n\t\trows.finish = nil\n\t}\n\n\tmc := rows.mc\n\tif mc == nil {\n\t\treturn nil\n\t}\n\tif err := mc.error(); err != nil {\n\t\treturn err\n\t}\n\n\t// Remove unread packets from stream\n\tif !rows.rs.done {\n\t\terr = mc.skipRows()\n\t}\n\tif err == nil {\n\t\thandleOk := mc.clearResult()\n\t\tif err = handleOk.discardResults(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\trows.mc = nil\n\treturn err\n}\n\nfunc (rows *mysqlRows) HasNextResultSet() (b bool) {\n\tif rows.mc == nil {\n\t\treturn false\n\t}\n\treturn rows.mc.status&statusMoreResultsExists != 0\n}\n\nfunc (rows *mysqlRows) nextResultSet() (int, error) {\n\tif rows.mc == nil {\n\t\treturn 0, io.EOF\n\t}\n\tif err := rows.mc.error(); err != nil {\n\t\treturn 0, err\n\t}\n\n\t// Remove unread packets from stream\n\tif !rows.rs.done {\n\t\tif err := rows.mc.skipRows(); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\trows.rs.done = true\n\t}\n\n\tif !rows.HasNextResultSet() {\n\t\trows.mc = nil\n\t\treturn 0, io.EOF\n\t}\n\trows.rs = resultSet{}\n\t// rows.mc.affectedRows and rows.mc.insertIds accumulate on each call to\n\t// nextResultSet.\n\tresLen, _, err := rows.mc.resultUnchanged().readResultSetHeaderPacket()\n\tif err != nil {\n\t\t// Clean up about multi-results flag\n\t\trows.rs.done = true\n\t\trows.mc.status = rows.mc.status & (^statusMoreResultsExists)\n\t}\n\treturn resLen, err\n}\n\nfunc (rows *mysqlRows) nextNotEmptyResultSet() (int, error) {\n\tfor {\n\t\tresLen, err := rows.nextResultSet()\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\tif resLen > 0 {\n\t\t\treturn resLen, nil\n\t\t}\n\n\t\trows.rs.done = true\n\t}\n}\n\nfunc (rows *binaryRows) NextResultSet() error {\n\tresLen, err := rows.nextNotEmptyResultSet()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trows.rs.columns, err = rows.mc.readColumns(resLen, nil)\n\treturn err\n}\n\nfunc (rows *binaryRows) Next(dest []driver.Value) error {\n\tif mc := rows.mc; mc != nil {\n\t\tif err := mc.error(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Fetch next row from stream\n\t\treturn rows.readRow(dest)\n\t}\n\treturn io.EOF\n}\n\nfunc (rows *textRows) NextResultSet() (err error) {\n\tresLen, err := rows.nextNotEmptyResultSet()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trows.rs.columns, err = rows.mc.readColumns(resLen, nil)\n\treturn err\n}\n\nfunc (rows *textRows) Next(dest []driver.Value) error {\n\tif mc := rows.mc; mc != nil {\n\t\tif err := mc.error(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Fetch next row from stream\n\t\treturn rows.readRow(dest)\n\t}\n\treturn io.EOF\n}\n"
  },
  {
    "path": "statement.go",
    "content": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at http://mozilla.org/MPL/2.0/.\n\npackage mysql\n\nimport (\n\t\"database/sql/driver\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"reflect\"\n)\n\ntype mysqlStmt struct {\n\tmc         *mysqlConn\n\tid         uint32\n\tparamCount int\n\tcolumns    []mysqlField\n}\n\nfunc (stmt *mysqlStmt) Close() error {\n\tif stmt.mc == nil || stmt.mc.closed.Load() {\n\t\t// driver.Stmt.Close could be called more than once, thus this function\n\t\t// had to be idempotent. See also Issue #450 and golang/go#16019.\n\t\t// This bug has been fixed in Go 1.8.\n\t\t// https://github.com/golang/go/commit/90b8a0ca2d0b565c7c7199ffcf77b15ea6b6db3a\n\t\t// But we keep this function idempotent because it is safer.\n\t\treturn nil\n\t}\n\n\terr := stmt.mc.writeCommandPacketUint32(comStmtClose, stmt.id)\n\tstmt.mc = nil\n\treturn err\n}\n\nfunc (stmt *mysqlStmt) NumInput() int {\n\treturn stmt.paramCount\n}\n\nfunc (stmt *mysqlStmt) ColumnConverter(idx int) driver.ValueConverter {\n\treturn converter{}\n}\n\nfunc (stmt *mysqlStmt) CheckNamedValue(nv *driver.NamedValue) (err error) {\n\tnv.Value, err = converter{}.ConvertValue(nv.Value)\n\treturn\n}\n\nfunc (stmt *mysqlStmt) Exec(args []driver.Value) (driver.Result, error) {\n\tif stmt.mc.closed.Load() {\n\t\treturn nil, driver.ErrBadConn\n\t}\n\t// Send command\n\terr := stmt.writeExecutePacket(args)\n\tif err != nil {\n\t\treturn nil, stmt.mc.markBadConn(err)\n\t}\n\n\tmc := stmt.mc\n\thandleOk := stmt.mc.clearResult()\n\n\t// Read Result\n\tresLen, metadataFollows, err := handleOk.readResultSetHeaderPacket()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resLen > 0 {\n\t\t// Columns\n\t\tif metadataFollows && stmt.mc.extCapabilities&clientCacheMetadata != 0 {\n\t\t\t// we can not skip column metadata because next stmt.Query() may use it.\n\t\t\tif stmt.columns, err = mc.readColumns(resLen, stmt.columns); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\tif err = mc.skipColumns(resLen); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\t// Rows\n\t\tif err = mc.skipRows(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif err := handleOk.discardResults(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tcopied := mc.result\n\treturn &copied, nil\n}\n\nfunc (stmt *mysqlStmt) Query(args []driver.Value) (driver.Rows, error) {\n\treturn stmt.query(args)\n}\n\nfunc (stmt *mysqlStmt) query(args []driver.Value) (*binaryRows, error) {\n\tif stmt.mc.closed.Load() {\n\t\treturn nil, driver.ErrBadConn\n\t}\n\t// Send command\n\terr := stmt.writeExecutePacket(args)\n\tif err != nil {\n\t\treturn nil, stmt.mc.markBadConn(err)\n\t}\n\n\tmc := stmt.mc\n\n\t// Read Result\n\thandleOk := stmt.mc.clearResult()\n\tresLen, metadataFollows, err := handleOk.readResultSetHeaderPacket()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trows := new(binaryRows)\n\n\tif resLen > 0 {\n\t\trows.mc = mc\n\t\tif metadataFollows {\n\t\t\tif rows.rs.columns, err = mc.readColumns(resLen, stmt.columns); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tstmt.columns = rows.rs.columns\n\t\t} else {\n\t\t\tif err = mc.skipEof(); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\trows.rs.columns = stmt.columns\n\t\t}\n\t} else {\n\t\trows.rs.done = true\n\n\t\tswitch err := rows.NextResultSet(); err {\n\t\tcase nil, io.EOF:\n\t\t\treturn rows, nil\n\t\tdefault:\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn rows, err\n}\n\nvar jsonType = reflect.TypeOf(json.RawMessage{})\n\ntype converter struct{}\n\n// ConvertValue mirrors the reference/default converter in database/sql/driver\n// with _one_ exception.  We support uint64 with their high bit and the default\n// implementation does not.  This function should be kept in sync with\n// database/sql/driver defaultConverter.ConvertValue() except for that\n// deliberate difference.\nfunc (c converter) ConvertValue(v any) (driver.Value, error) {\n\tif driver.IsValue(v) {\n\t\treturn v, nil\n\t}\n\n\tif vr, ok := v.(driver.Valuer); ok {\n\t\tsv, err := callValuerValue(vr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif driver.IsValue(sv) {\n\t\t\treturn sv, nil\n\t\t}\n\t\t// A value returned from the Valuer interface can be \"a type handled by\n\t\t// a database driver's NamedValueChecker interface\" so we should accept\n\t\t// uint64 here as well.\n\t\tif u, ok := sv.(uint64); ok {\n\t\t\treturn u, nil\n\t\t}\n\t\treturn nil, fmt.Errorf(\"non-Value type %T returned from Value\", sv)\n\t}\n\trv := reflect.ValueOf(v)\n\tswitch rv.Kind() {\n\tcase reflect.Ptr:\n\t\t// indirect pointers\n\t\tif rv.IsNil() {\n\t\t\treturn nil, nil\n\t\t} else {\n\t\t\treturn c.ConvertValue(rv.Elem().Interface())\n\t\t}\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\treturn rv.Int(), nil\n\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\treturn rv.Uint(), nil\n\tcase reflect.Float32, reflect.Float64:\n\t\treturn rv.Float(), nil\n\tcase reflect.Bool:\n\t\treturn rv.Bool(), nil\n\tcase reflect.Slice:\n\t\tswitch t := rv.Type(); {\n\t\tcase t == jsonType:\n\t\t\treturn v, nil\n\t\tcase t.Elem().Kind() == reflect.Uint8:\n\t\t\treturn rv.Bytes(), nil\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unsupported type %T, a slice of %s\", v, t.Elem().Kind())\n\t\t}\n\tcase reflect.String:\n\t\treturn rv.String(), nil\n\t}\n\treturn nil, fmt.Errorf(\"unsupported type %T, a %s\", v, rv.Kind())\n}\n\nvar valuerReflectType = reflect.TypeOf((*driver.Valuer)(nil)).Elem()\n\n// callValuerValue returns vr.Value(), with one exception:\n// If vr.Value is an auto-generated method on a pointer type and the\n// pointer is nil, it would panic at runtime in the panicwrap\n// method. Treat it like nil instead.\n//\n// This is so people can implement driver.Value on value types and\n// still use nil pointers to those types to mean nil/NULL, just like\n// string/*string.\n//\n// This is an exact copy of the same-named unexported function from the\n// database/sql package.\nfunc callValuerValue(vr driver.Valuer) (v driver.Value, err error) {\n\tif rv := reflect.ValueOf(vr); rv.Kind() == reflect.Ptr &&\n\t\trv.IsNil() &&\n\t\trv.Type().Elem().Implements(valuerReflectType) {\n\t\treturn nil, nil\n\t}\n\treturn vr.Value()\n}\n"
  },
  {
    "path": "statement_test.go",
    "content": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2017 The Go-MySQL-Driver Authors. All rights reserved.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at http://mozilla.org/MPL/2.0/.\n\npackage mysql\n\nimport (\n\t\"bytes\"\n\t\"database/sql/driver\"\n\t\"encoding/json\"\n\t\"testing\"\n)\n\nfunc TestConvertDerivedString(t *testing.T) {\n\ttype derived string\n\n\toutput, err := converter{}.ConvertValue(derived(\"value\"))\n\tif err != nil {\n\t\tt.Fatal(\"Derived string type not convertible\", err)\n\t}\n\n\tif output != \"value\" {\n\t\tt.Fatalf(\"Derived string type not converted, got %#v %T\", output, output)\n\t}\n}\n\nfunc TestConvertDerivedByteSlice(t *testing.T) {\n\ttype derived []uint8\n\n\toutput, err := converter{}.ConvertValue(derived(\"value\"))\n\tif err != nil {\n\t\tt.Fatal(\"Byte slice not convertible\", err)\n\t}\n\n\tif !bytes.Equal(output.([]byte), []byte(\"value\")) {\n\t\tt.Fatalf(\"Byte slice not converted, got %#v %T\", output, output)\n\t}\n}\n\nfunc TestConvertDerivedUnsupportedSlice(t *testing.T) {\n\ttype derived []int\n\n\t_, err := converter{}.ConvertValue(derived{1})\n\tif err == nil || err.Error() != \"unsupported type mysql.derived, a slice of int\" {\n\t\tt.Fatal(\"Unexpected error\", err)\n\t}\n}\n\nfunc TestConvertDerivedBool(t *testing.T) {\n\ttype derived bool\n\n\toutput, err := converter{}.ConvertValue(derived(true))\n\tif err != nil {\n\t\tt.Fatal(\"Derived bool type not convertible\", err)\n\t}\n\n\tif output != true {\n\t\tt.Fatalf(\"Derived bool type not converted, got %#v %T\", output, output)\n\t}\n}\n\nfunc TestConvertPointer(t *testing.T) {\n\tstr := \"value\"\n\n\toutput, err := converter{}.ConvertValue(&str)\n\tif err != nil {\n\t\tt.Fatal(\"Pointer type not convertible\", err)\n\t}\n\n\tif output != \"value\" {\n\t\tt.Fatalf(\"Pointer type not converted, got %#v %T\", output, output)\n\t}\n}\n\nfunc TestConvertSignedIntegers(t *testing.T) {\n\tvalues := []any{\n\t\tint8(-42),\n\t\tint16(-42),\n\t\tint32(-42),\n\t\tint64(-42),\n\t\tint(-42),\n\t}\n\n\tfor _, value := range values {\n\t\toutput, err := converter{}.ConvertValue(value)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"%T type not convertible %s\", value, err)\n\t\t}\n\n\t\tif output != int64(-42) {\n\t\t\tt.Fatalf(\"%T type not converted, got %#v %T\", value, output, output)\n\t\t}\n\t}\n}\n\ntype myUint64 struct {\n\tvalue uint64\n}\n\nfunc (u myUint64) Value() (driver.Value, error) {\n\treturn u.value, nil\n}\n\nfunc TestConvertUnsignedIntegers(t *testing.T) {\n\tvalues := []any{\n\t\tuint8(42),\n\t\tuint16(42),\n\t\tuint32(42),\n\t\tuint64(42),\n\t\tuint(42),\n\t\tmyUint64{uint64(42)},\n\t}\n\n\tfor _, value := range values {\n\t\toutput, err := converter{}.ConvertValue(value)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"%T type not convertible %s\", value, err)\n\t\t}\n\n\t\tif output != uint64(42) {\n\t\t\tt.Fatalf(\"%T type not converted, got %#v %T\", value, output, output)\n\t\t}\n\t}\n\n\toutput, err := converter{}.ConvertValue(^uint64(0))\n\tif err != nil {\n\t\tt.Fatal(\"uint64 high-bit not convertible\", err)\n\t}\n\n\tif output != ^uint64(0) {\n\t\tt.Fatalf(\"uint64 high-bit converted, got %#v %T\", output, output)\n\t}\n}\n\nfunc TestConvertJSON(t *testing.T) {\n\traw := json.RawMessage(\"{}\")\n\n\tout, err := converter{}.ConvertValue(raw)\n\n\tif err != nil {\n\t\tt.Fatal(\"json.RawMessage was failed in convert\", err)\n\t}\n\n\tif _, ok := out.(json.RawMessage); !ok {\n\t\tt.Fatalf(\"json.RawMessage converted, got %#v %T\", out, out)\n\t}\n}\n"
  },
  {
    "path": "transaction.go",
    "content": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at http://mozilla.org/MPL/2.0/.\n\npackage mysql\n\ntype mysqlTx struct {\n\tmc *mysqlConn\n}\n\nfunc (tx *mysqlTx) Commit() (err error) {\n\tif tx.mc == nil {\n\t\treturn ErrInvalidConn\n\t}\n\tif tx.mc.closed.Load() {\n\t\terr = tx.mc.error()\n\t\tif err == nil {\n\t\t\terr = ErrInvalidConn\n\t\t}\n\t\treturn\n\t}\n\terr = tx.mc.exec(\"COMMIT\")\n\ttx.mc = nil\n\treturn\n}\n\nfunc (tx *mysqlTx) Rollback() (err error) {\n\tif tx.mc == nil {\n\t\treturn ErrInvalidConn\n\t}\n\tif tx.mc.closed.Load() {\n\t\terr = tx.mc.error()\n\t\tif err == nil {\n\t\t\terr = ErrInvalidConn\n\t\t}\n\t\treturn\n\t}\n\terr = tx.mc.exec(\"ROLLBACK\")\n\ttx.mc = nil\n\treturn\n}\n"
  },
  {
    "path": "utils.go",
    "content": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at http://mozilla.org/MPL/2.0/.\n\npackage mysql\n\nimport (\n\t\"crypto/tls\"\n\t\"database/sql\"\n\t\"database/sql/driver\"\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"time\"\n)\n\n// Registry for custom tls.Configs\nvar (\n\ttlsConfigLock     sync.RWMutex\n\ttlsConfigRegistry map[string]*tls.Config\n)\n\n// RegisterTLSConfig registers a custom tls.Config to be used with sql.Open.\n// Use the key as a value in the DSN where tls=value.\n//\n// Note: The provided tls.Config is exclusively owned by the driver after\n// registering it.\n//\n//\trootCertPool := x509.NewCertPool()\n//\tpem, err := os.ReadFile(\"/path/ca-cert.pem\")\n//\tif err != nil {\n//\t    log.Fatal(err)\n//\t}\n//\tif ok := rootCertPool.AppendCertsFromPEM(pem); !ok {\n//\t    log.Fatal(\"Failed to append PEM.\")\n//\t}\n//\tclientCert := make([]tls.Certificate, 0, 1)\n//\tcerts, err := tls.LoadX509KeyPair(\"/path/client-cert.pem\", \"/path/client-key.pem\")\n//\tif err != nil {\n//\t    log.Fatal(err)\n//\t}\n//\tclientCert = append(clientCert, certs)\n//\tmysql.RegisterTLSConfig(\"custom\", &tls.Config{\n//\t    RootCAs: rootCertPool,\n//\t    Certificates: clientCert,\n//\t})\n//\tdb, err := sql.Open(\"mysql\", \"user@tcp(localhost:3306)/test?tls=custom\")\nfunc RegisterTLSConfig(key string, config *tls.Config) error {\n\tif _, isBool := readBool(key); isBool || strings.ToLower(key) == \"skip-verify\" || strings.ToLower(key) == \"preferred\" {\n\t\treturn fmt.Errorf(\"key '%s' is reserved\", key)\n\t}\n\n\ttlsConfigLock.Lock()\n\tif tlsConfigRegistry == nil {\n\t\ttlsConfigRegistry = make(map[string]*tls.Config)\n\t}\n\n\ttlsConfigRegistry[key] = config\n\ttlsConfigLock.Unlock()\n\treturn nil\n}\n\n// DeregisterTLSConfig removes the tls.Config associated with key.\nfunc DeregisterTLSConfig(key string) {\n\ttlsConfigLock.Lock()\n\tif tlsConfigRegistry != nil {\n\t\tdelete(tlsConfigRegistry, key)\n\t}\n\ttlsConfigLock.Unlock()\n}\n\nfunc getTLSConfigClone(key string) (config *tls.Config) {\n\ttlsConfigLock.RLock()\n\tif v, ok := tlsConfigRegistry[key]; ok {\n\t\tconfig = v.Clone()\n\t}\n\ttlsConfigLock.RUnlock()\n\treturn\n}\n\n// Returns the bool value of the input.\n// The 2nd return value indicates if the input was a valid bool value\nfunc readBool(input string) (value bool, valid bool) {\n\tswitch input {\n\tcase \"1\", \"true\", \"TRUE\", \"True\":\n\t\treturn true, true\n\tcase \"0\", \"false\", \"FALSE\", \"False\":\n\t\treturn false, true\n\t}\n\n\t// Not a valid bool value\n\treturn\n}\n\n/******************************************************************************\n*                           Time related utils                                *\n******************************************************************************/\n\nfunc parseDateTime(b []byte, loc *time.Location) (time.Time, error) {\n\tconst base = \"0000-00-00 00:00:00.000000\"\n\tswitch len(b) {\n\tcase 10, 19, 21, 22, 23, 24, 25, 26: // up to \"YYYY-MM-DD HH:MM:SS.MMMMMM\"\n\t\tif string(b) == base[:len(b)] {\n\t\t\treturn time.Time{}, nil\n\t\t}\n\n\t\tyear, err := parseByteYear(b)\n\t\tif err != nil {\n\t\t\treturn time.Time{}, err\n\t\t}\n\t\tif b[4] != '-' {\n\t\t\treturn time.Time{}, fmt.Errorf(\"bad value for field: `%c`\", b[4])\n\t\t}\n\n\t\tm, err := parseByte2Digits(b[5], b[6])\n\t\tif err != nil {\n\t\t\treturn time.Time{}, err\n\t\t}\n\t\tmonth := time.Month(m)\n\n\t\tif b[7] != '-' {\n\t\t\treturn time.Time{}, fmt.Errorf(\"bad value for field: `%c`\", b[7])\n\t\t}\n\n\t\tday, err := parseByte2Digits(b[8], b[9])\n\t\tif err != nil {\n\t\t\treturn time.Time{}, err\n\t\t}\n\t\tif len(b) == 10 {\n\t\t\treturn time.Date(year, month, day, 0, 0, 0, 0, loc), nil\n\t\t}\n\n\t\tif b[10] != ' ' {\n\t\t\treturn time.Time{}, fmt.Errorf(\"bad value for field: `%c`\", b[10])\n\t\t}\n\n\t\thour, err := parseByte2Digits(b[11], b[12])\n\t\tif err != nil {\n\t\t\treturn time.Time{}, err\n\t\t}\n\t\tif b[13] != ':' {\n\t\t\treturn time.Time{}, fmt.Errorf(\"bad value for field: `%c`\", b[13])\n\t\t}\n\n\t\tmin, err := parseByte2Digits(b[14], b[15])\n\t\tif err != nil {\n\t\t\treturn time.Time{}, err\n\t\t}\n\t\tif b[16] != ':' {\n\t\t\treturn time.Time{}, fmt.Errorf(\"bad value for field: `%c`\", b[16])\n\t\t}\n\n\t\tsec, err := parseByte2Digits(b[17], b[18])\n\t\tif err != nil {\n\t\t\treturn time.Time{}, err\n\t\t}\n\t\tif len(b) == 19 {\n\t\t\treturn time.Date(year, month, day, hour, min, sec, 0, loc), nil\n\t\t}\n\n\t\tif b[19] != '.' {\n\t\t\treturn time.Time{}, fmt.Errorf(\"bad value for field: `%c`\", b[19])\n\t\t}\n\t\tnsec, err := parseByteNanoSec(b[20:])\n\t\tif err != nil {\n\t\t\treturn time.Time{}, err\n\t\t}\n\t\treturn time.Date(year, month, day, hour, min, sec, nsec, loc), nil\n\tdefault:\n\t\treturn time.Time{}, fmt.Errorf(\"invalid time bytes: %s\", b)\n\t}\n}\n\nfunc parseByteYear(b []byte) (int, error) {\n\tyear, n := 0, 1000\n\tfor i := range 4 {\n\t\tv, err := bToi(b[i])\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tyear += v * n\n\t\tn /= 10\n\t}\n\treturn year, nil\n}\n\nfunc parseByte2Digits(b1, b2 byte) (int, error) {\n\td1, err := bToi(b1)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\td2, err := bToi(b2)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn d1*10 + d2, nil\n}\n\nfunc parseByteNanoSec(b []byte) (int, error) {\n\tns, digit := 0, 100000 // max is 6-digits\n\tfor i := range b {\n\t\tv, err := bToi(b[i])\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tns += v * digit\n\t\tdigit /= 10\n\t}\n\t// nanoseconds has 10-digits. (needs to scale digits)\n\t// 10 - 6 = 4, so we have to multiple 1000.\n\treturn ns * 1000, nil\n}\n\nfunc bToi(b byte) (int, error) {\n\tif b < '0' || b > '9' {\n\t\treturn 0, errors.New(\"not [0-9]\")\n\t}\n\treturn int(b - '0'), nil\n}\n\nfunc parseBinaryDateTime(num uint64, data []byte, loc *time.Location) (driver.Value, error) {\n\tswitch num {\n\tcase 0:\n\t\treturn time.Time{}, nil\n\tcase 4:\n\t\treturn time.Date(\n\t\t\tint(binary.LittleEndian.Uint16(data[:2])), // year\n\t\t\ttime.Month(data[2]),                       // month\n\t\t\tint(data[3]),                              // day\n\t\t\t0, 0, 0, 0,\n\t\t\tloc,\n\t\t), nil\n\tcase 7:\n\t\treturn time.Date(\n\t\t\tint(binary.LittleEndian.Uint16(data[:2])), // year\n\t\t\ttime.Month(data[2]),                       // month\n\t\t\tint(data[3]),                              // day\n\t\t\tint(data[4]),                              // hour\n\t\t\tint(data[5]),                              // minutes\n\t\t\tint(data[6]),                              // seconds\n\t\t\t0,\n\t\t\tloc,\n\t\t), nil\n\tcase 11:\n\t\treturn time.Date(\n\t\t\tint(binary.LittleEndian.Uint16(data[:2])), // year\n\t\t\ttime.Month(data[2]),                       // month\n\t\t\tint(data[3]),                              // day\n\t\t\tint(data[4]),                              // hour\n\t\t\tint(data[5]),                              // minutes\n\t\t\tint(data[6]),                              // seconds\n\t\t\tint(binary.LittleEndian.Uint32(data[7:11]))*1000, // nanoseconds\n\t\t\tloc,\n\t\t), nil\n\t}\n\treturn nil, fmt.Errorf(\"invalid DATETIME packet length %d\", num)\n}\n\nfunc appendDateTime(buf []byte, t time.Time, timeTruncate time.Duration) ([]byte, error) {\n\tif timeTruncate > 0 {\n\t\tt = t.Truncate(timeTruncate)\n\t}\n\n\tyear, month, day := t.Date()\n\thour, min, sec := t.Clock()\n\tnsec := t.Nanosecond()\n\n\tif year < 1 || year > 9999 {\n\t\treturn buf, errors.New(\"year is not in the range [1, 9999]: \" + strconv.Itoa(year)) // use errors.New instead of fmt.Errorf to avoid year escape to heap\n\t}\n\tyear100 := year / 100\n\tyear1 := year % 100\n\n\tvar localBuf [len(\"2006-01-02T15:04:05.999999999\")]byte // does not escape\n\tlocalBuf[0], localBuf[1], localBuf[2], localBuf[3] = digits10[year100], digits01[year100], digits10[year1], digits01[year1]\n\tlocalBuf[4] = '-'\n\tlocalBuf[5], localBuf[6] = digits10[month], digits01[month]\n\tlocalBuf[7] = '-'\n\tlocalBuf[8], localBuf[9] = digits10[day], digits01[day]\n\n\tif hour == 0 && min == 0 && sec == 0 && nsec == 0 {\n\t\treturn append(buf, localBuf[:10]...), nil\n\t}\n\n\tlocalBuf[10] = ' '\n\tlocalBuf[11], localBuf[12] = digits10[hour], digits01[hour]\n\tlocalBuf[13] = ':'\n\tlocalBuf[14], localBuf[15] = digits10[min], digits01[min]\n\tlocalBuf[16] = ':'\n\tlocalBuf[17], localBuf[18] = digits10[sec], digits01[sec]\n\n\tif nsec == 0 {\n\t\treturn append(buf, localBuf[:19]...), nil\n\t}\n\tnsec100000000 := nsec / 100000000\n\tnsec1000000 := (nsec / 1000000) % 100\n\tnsec10000 := (nsec / 10000) % 100\n\tnsec100 := (nsec / 100) % 100\n\tnsec1 := nsec % 100\n\tlocalBuf[19] = '.'\n\n\t// milli second\n\tlocalBuf[20], localBuf[21], localBuf[22] =\n\t\tdigits01[nsec100000000], digits10[nsec1000000], digits01[nsec1000000]\n\t// micro second\n\tlocalBuf[23], localBuf[24], localBuf[25] =\n\t\tdigits10[nsec10000], digits01[nsec10000], digits10[nsec100]\n\t// nano second\n\tlocalBuf[26], localBuf[27], localBuf[28] =\n\t\tdigits01[nsec100], digits10[nsec1], digits01[nsec1]\n\n\t// trim trailing zeros\n\tn := len(localBuf)\n\tfor n > 0 && localBuf[n-1] == '0' {\n\t\tn--\n\t}\n\n\treturn append(buf, localBuf[:n]...), nil\n}\n\n// zeroDateTime is used in formatBinaryDateTime to avoid an allocation\n// if the DATE or DATETIME has the zero value.\n// It must never be changed.\n// The current behavior depends on database/sql copying the result.\nvar zeroDateTime = []byte(\"0000-00-00 00:00:00.000000\")\n\nconst digits01 = \"0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789\"\nconst digits10 = \"0000000000111111111122222222223333333333444444444455555555556666666666777777777788888888889999999999\"\n\nfunc appendMicrosecs(dst, src []byte, decimals int) []byte {\n\tif decimals <= 0 {\n\t\treturn dst\n\t}\n\tif len(src) == 0 {\n\t\treturn append(dst, \".000000\"[:decimals+1]...)\n\t}\n\n\tmicrosecs := binary.LittleEndian.Uint32(src[:4])\n\tp1 := byte(microsecs / 10000)\n\tmicrosecs -= 10000 * uint32(p1)\n\tp2 := byte(microsecs / 100)\n\tmicrosecs -= 100 * uint32(p2)\n\tp3 := byte(microsecs)\n\n\tswitch decimals {\n\tdefault:\n\t\treturn append(dst, '.',\n\t\t\tdigits10[p1], digits01[p1],\n\t\t\tdigits10[p2], digits01[p2],\n\t\t\tdigits10[p3], digits01[p3],\n\t\t)\n\tcase 1:\n\t\treturn append(dst, '.',\n\t\t\tdigits10[p1],\n\t\t)\n\tcase 2:\n\t\treturn append(dst, '.',\n\t\t\tdigits10[p1], digits01[p1],\n\t\t)\n\tcase 3:\n\t\treturn append(dst, '.',\n\t\t\tdigits10[p1], digits01[p1],\n\t\t\tdigits10[p2],\n\t\t)\n\tcase 4:\n\t\treturn append(dst, '.',\n\t\t\tdigits10[p1], digits01[p1],\n\t\t\tdigits10[p2], digits01[p2],\n\t\t)\n\tcase 5:\n\t\treturn append(dst, '.',\n\t\t\tdigits10[p1], digits01[p1],\n\t\t\tdigits10[p2], digits01[p2],\n\t\t\tdigits10[p3],\n\t\t)\n\t}\n}\n\nfunc formatBinaryDateTime(src []byte, length uint8) (driver.Value, error) {\n\t// length expects the deterministic length of the zero value,\n\t// negative time and 100+ hours are automatically added if needed\n\tif len(src) == 0 {\n\t\treturn zeroDateTime[:length], nil\n\t}\n\tvar dst []byte      // return value\n\tvar p1, p2, p3 byte // current digit pair\n\n\tswitch length {\n\tcase 10, 19, 21, 22, 23, 24, 25, 26:\n\tdefault:\n\t\tt := \"DATE\"\n\t\tif length > 10 {\n\t\t\tt += \"TIME\"\n\t\t}\n\t\treturn nil, fmt.Errorf(\"illegal %s length %d\", t, length)\n\t}\n\tswitch len(src) {\n\tcase 4, 7, 11:\n\tdefault:\n\t\tt := \"DATE\"\n\t\tif length > 10 {\n\t\t\tt += \"TIME\"\n\t\t}\n\t\treturn nil, fmt.Errorf(\"illegal %s packet length %d\", t, len(src))\n\t}\n\tdst = make([]byte, 0, length)\n\t// start with the date\n\tyear := binary.LittleEndian.Uint16(src[:2])\n\tpt := year / 100\n\tp1 = byte(year - 100*uint16(pt))\n\tp2, p3 = src[2], src[3]\n\tdst = append(dst,\n\t\tdigits10[pt], digits01[pt],\n\t\tdigits10[p1], digits01[p1], '-',\n\t\tdigits10[p2], digits01[p2], '-',\n\t\tdigits10[p3], digits01[p3],\n\t)\n\tif length == 10 {\n\t\treturn dst, nil\n\t}\n\tif len(src) == 4 {\n\t\treturn append(dst, zeroDateTime[10:length]...), nil\n\t}\n\tdst = append(dst, ' ')\n\tp1 = src[4] // hour\n\tsrc = src[5:]\n\n\t// p1 is 2-digit hour, src is after hour\n\tp2, p3 = src[0], src[1]\n\tdst = append(dst,\n\t\tdigits10[p1], digits01[p1], ':',\n\t\tdigits10[p2], digits01[p2], ':',\n\t\tdigits10[p3], digits01[p3],\n\t)\n\treturn appendMicrosecs(dst, src[2:], int(length)-20), nil\n}\n\nfunc formatBinaryTime(src []byte, length uint8) (driver.Value, error) {\n\t// length expects the deterministic length of the zero value,\n\t// negative time and 100+ hours are automatically added if needed\n\tif len(src) == 0 {\n\t\treturn zeroDateTime[11 : 11+length], nil\n\t}\n\tvar dst []byte // return value\n\n\tswitch length {\n\tcase\n\t\t8,                      // time (can be up to 10 when negative and 100+ hours)\n\t\t10, 11, 12, 13, 14, 15: // time with fractional seconds\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"illegal TIME length %d\", length)\n\t}\n\tswitch len(src) {\n\tcase 8, 12:\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"invalid TIME packet length %d\", len(src))\n\t}\n\t// +2 to enable negative time and 100+ hours\n\tdst = make([]byte, 0, length+2)\n\tif src[0] == 1 {\n\t\tdst = append(dst, '-')\n\t}\n\tdays := binary.LittleEndian.Uint32(src[1:5])\n\thours := int64(days)*24 + int64(src[5])\n\n\tif hours >= 100 {\n\t\tdst = strconv.AppendInt(dst, hours, 10)\n\t} else {\n\t\tdst = append(dst, digits10[hours], digits01[hours])\n\t}\n\n\tmin, sec := src[6], src[7]\n\tdst = append(dst, ':',\n\t\tdigits10[min], digits01[min], ':',\n\t\tdigits10[sec], digits01[sec],\n\t)\n\treturn appendMicrosecs(dst, src[8:], int(length)-9), nil\n}\n\n/******************************************************************************\n*                       Convert from and to bytes                             *\n******************************************************************************/\n\n// 24bit integer: used for packet headers.\n\nfunc putUint24(data []byte, n int) {\n\tdata[2] = byte(n >> 16)\n\tdata[1] = byte(n >> 8)\n\tdata[0] = byte(n)\n}\n\nfunc getUint24(data []byte) int {\n\treturn int(data[2])<<16 | int(data[1])<<8 | int(data[0])\n}\n\nfunc uint64ToString(n uint64) []byte {\n\tvar a [20]byte\n\ti := 20\n\n\t// U+0030 = 0\n\t// ...\n\t// U+0039 = 9\n\n\tvar q uint64\n\tfor n >= 10 {\n\t\ti--\n\t\tq = n / 10\n\t\ta[i] = uint8(n-q*10) + 0x30\n\t\tn = q\n\t}\n\n\ti--\n\ta[i] = uint8(n) + 0x30\n\n\treturn a[i:]\n}\n\n// returns the string read as a bytes slice, whether the value is NULL,\n// the number of bytes read and an error, in case the string is longer than\n// the input slice\nfunc readLengthEncodedString(b []byte) ([]byte, bool, int, error) {\n\t// Get length\n\tnum, isNull, n := readLengthEncodedInteger(b)\n\tif num < 1 {\n\t\treturn b[n:n], isNull, n, nil\n\t}\n\n\tn += int(num)\n\n\t// Check data length\n\tif len(b) >= n {\n\t\treturn b[n-int(num) : n : n], false, n, nil\n\t}\n\treturn nil, false, n, io.EOF\n}\n\n// returns the number of bytes skipped and an error, in case the string is\n// longer than the input slice\nfunc skipLengthEncodedString(b []byte) (int, error) {\n\t// Get length\n\tnum, _, n := readLengthEncodedInteger(b)\n\tif num < 1 {\n\t\treturn n, nil\n\t}\n\n\tn += int(num)\n\n\t// Check data length\n\tif len(b) >= n {\n\t\treturn n, nil\n\t}\n\treturn n, io.EOF\n}\n\n// returns the number read, whether the value is NULL and the number of bytes read\nfunc readLengthEncodedInteger(b []byte) (uint64, bool, int) {\n\t// See issue #349\n\tif len(b) == 0 {\n\t\treturn 0, true, 1\n\t}\n\n\tswitch b[0] {\n\t// 251: NULL\n\tcase 0xfb:\n\t\treturn 0, true, 1\n\n\t// 252: value of following 2\n\tcase 0xfc:\n\t\treturn uint64(binary.LittleEndian.Uint16(b[1:])), false, 3\n\n\t// 253: value of following 3\n\tcase 0xfd:\n\t\treturn uint64(getUint24(b[1:])), false, 4\n\n\t// 254: value of following 8\n\tcase 0xfe:\n\t\treturn uint64(binary.LittleEndian.Uint64(b[1:])), false, 9\n\t}\n\n\t// 0-250: value of first byte\n\treturn uint64(b[0]), false, 1\n}\n\n// encodes a uint64 value and appends it to the given bytes slice\nfunc appendLengthEncodedInteger(b []byte, n uint64) []byte {\n\tswitch {\n\tcase n <= 250:\n\t\treturn append(b, byte(n))\n\n\tcase n <= 0xffff:\n\t\tb = append(b, 0xfc)\n\t\treturn binary.LittleEndian.AppendUint16(b, uint16(n))\n\n\tcase n <= 0xffffff:\n\t\treturn append(b, 0xfd, byte(n), byte(n>>8), byte(n>>16))\n\t}\n\tb = append(b, 0xfe)\n\treturn binary.LittleEndian.AppendUint64(b, n)\n}\n\nfunc appendLengthEncodedString(b []byte, s string) []byte {\n\tb = appendLengthEncodedInteger(b, uint64(len(s)))\n\treturn append(b, s...)\n}\n\n// reserveBuffer checks cap(buf) and expand buffer to len(buf) + appendSize.\n// If cap(buf) is not enough, reallocate new buffer.\nfunc reserveBuffer(buf []byte, appendSize int) []byte {\n\tnewSize := len(buf) + appendSize\n\tif cap(buf) < newSize {\n\t\t// Grow buffer exponentially\n\t\tnewBuf := make([]byte, len(buf)*2+appendSize)\n\t\tcopy(newBuf, buf)\n\t\tbuf = newBuf\n\t}\n\treturn buf[:newSize]\n}\n\n// escapeBytesBackslash escapes []byte with backslashes (\\)\n// This escapes the contents of a string (provided as []byte) by adding backslashes before special\n// characters, and turning others into specific escape sequences, such as\n// turning newlines into \\n and null bytes into \\0.\n// https://github.com/mysql/mysql-server/blob/mysql-5.7.5/mysys/charset.c#L823-L932\nfunc escapeBytesBackslash(buf, v []byte) []byte {\n\tpos := len(buf)\n\tbuf = reserveBuffer(buf, len(v)*2)\n\n\tfor _, c := range v {\n\t\tswitch c {\n\t\tcase '\\x00':\n\t\t\tbuf[pos+1] = '0'\n\t\t\tbuf[pos] = '\\\\'\n\t\t\tpos += 2\n\t\tcase '\\n':\n\t\t\tbuf[pos+1] = 'n'\n\t\t\tbuf[pos] = '\\\\'\n\t\t\tpos += 2\n\t\tcase '\\r':\n\t\t\tbuf[pos+1] = 'r'\n\t\t\tbuf[pos] = '\\\\'\n\t\t\tpos += 2\n\t\tcase '\\x1a':\n\t\t\tbuf[pos+1] = 'Z'\n\t\t\tbuf[pos] = '\\\\'\n\t\t\tpos += 2\n\t\tcase '\\'':\n\t\t\tbuf[pos+1] = '\\''\n\t\t\tbuf[pos] = '\\\\'\n\t\t\tpos += 2\n\t\tcase '\"':\n\t\t\tbuf[pos+1] = '\"'\n\t\t\tbuf[pos] = '\\\\'\n\t\t\tpos += 2\n\t\tcase '\\\\':\n\t\t\tbuf[pos+1] = '\\\\'\n\t\t\tbuf[pos] = '\\\\'\n\t\t\tpos += 2\n\t\tdefault:\n\t\t\tbuf[pos] = c\n\t\t\tpos++\n\t\t}\n\t}\n\n\treturn buf[:pos]\n}\n\n// escapeStringBackslash is similar to escapeBytesBackslash but for string.\nfunc escapeStringBackslash(buf []byte, v string) []byte {\n\tpos := len(buf)\n\tbuf = reserveBuffer(buf, len(v)*2)\n\n\tfor i := range len(v) {\n\t\tc := v[i]\n\t\tswitch c {\n\t\tcase '\\x00':\n\t\t\tbuf[pos+1] = '0'\n\t\t\tbuf[pos] = '\\\\'\n\t\t\tpos += 2\n\t\tcase '\\n':\n\t\t\tbuf[pos+1] = 'n'\n\t\t\tbuf[pos] = '\\\\'\n\t\t\tpos += 2\n\t\tcase '\\r':\n\t\t\tbuf[pos+1] = 'r'\n\t\t\tbuf[pos] = '\\\\'\n\t\t\tpos += 2\n\t\tcase '\\x1a':\n\t\t\tbuf[pos+1] = 'Z'\n\t\t\tbuf[pos] = '\\\\'\n\t\t\tpos += 2\n\t\tcase '\\'':\n\t\t\tbuf[pos+1] = '\\''\n\t\t\tbuf[pos] = '\\\\'\n\t\t\tpos += 2\n\t\tcase '\"':\n\t\t\tbuf[pos+1] = '\"'\n\t\t\tbuf[pos] = '\\\\'\n\t\t\tpos += 2\n\t\tcase '\\\\':\n\t\t\tbuf[pos+1] = '\\\\'\n\t\t\tbuf[pos] = '\\\\'\n\t\t\tpos += 2\n\t\tdefault:\n\t\t\tbuf[pos] = c\n\t\t\tpos++\n\t\t}\n\t}\n\n\treturn buf[:pos]\n}\n\n// escapeBytesQuotes escapes apostrophes in []byte by doubling them up.\n// This escapes the contents of a string by doubling up any apostrophes that\n// it contains. This is used when the NO_BACKSLASH_ESCAPES SQL_MODE is in\n// effect on the server.\n// https://github.com/mysql/mysql-server/blob/mysql-5.7.5/mysys/charset.c#L963-L1038\nfunc escapeBytesQuotes(buf, v []byte) []byte {\n\tpos := len(buf)\n\tbuf = reserveBuffer(buf, len(v)*2)\n\n\tfor _, c := range v {\n\t\tif c == '\\'' {\n\t\t\tbuf[pos+1] = '\\''\n\t\t\tbuf[pos] = '\\''\n\t\t\tpos += 2\n\t\t} else {\n\t\t\tbuf[pos] = c\n\t\t\tpos++\n\t\t}\n\t}\n\n\treturn buf[:pos]\n}\n\n// escapeStringQuotes is similar to escapeBytesQuotes but for string.\nfunc escapeStringQuotes(buf []byte, v string) []byte {\n\tpos := len(buf)\n\tbuf = reserveBuffer(buf, len(v)*2)\n\n\tfor i := range len(v) {\n\t\tc := v[i]\n\t\tif c == '\\'' {\n\t\t\tbuf[pos+1] = '\\''\n\t\t\tbuf[pos] = '\\''\n\t\t\tpos += 2\n\t\t} else {\n\t\t\tbuf[pos] = c\n\t\t\tpos++\n\t\t}\n\t}\n\n\treturn buf[:pos]\n}\n\n/******************************************************************************\n*                               Sync utils                                    *\n******************************************************************************/\n\n// noCopy may be embedded into structs which must not be copied\n// after the first use.\n//\n// See https://github.com/golang/go/issues/8005#issuecomment-190753527\n// for details.\ntype noCopy struct{}\n\n// Lock is a no-op used by -copylocks checker from `go vet`.\nfunc (*noCopy) Lock() {}\n\n// Unlock is a no-op used by -copylocks checker from `go vet`.\n// noCopy should implement sync.Locker from Go 1.11\n// https://github.com/golang/go/commit/c2eba53e7f80df21d51285879d51ab81bcfbf6bc\n// https://github.com/golang/go/issues/26165\nfunc (*noCopy) Unlock() {}\n\n// atomicError is a wrapper for atomically accessed error values\ntype atomicError struct {\n\t_     noCopy\n\tvalue atomic.Value\n}\n\n// Set sets the error value regardless of the previous value.\n// The value must not be nil\nfunc (ae *atomicError) Set(value error) {\n\tae.value.Store(value)\n}\n\n// Value returns the current error value\nfunc (ae *atomicError) Value() error {\n\tif v := ae.value.Load(); v != nil {\n\t\t// this will panic if the value doesn't implement the error interface\n\t\treturn v.(error)\n\t}\n\treturn nil\n}\n\nfunc namedValueToValue(named []driver.NamedValue) ([]driver.Value, error) {\n\tdargs := make([]driver.Value, len(named))\n\tfor n, param := range named {\n\t\tif len(param.Name) > 0 {\n\t\t\t// TODO: support the use of Named Parameters #561\n\t\t\treturn nil, errors.New(\"mysql: driver does not support the use of Named Parameters\")\n\t\t}\n\t\tdargs[n] = param.Value\n\t}\n\treturn dargs, nil\n}\n\nfunc mapIsolationLevel(level driver.IsolationLevel) (string, error) {\n\tswitch sql.IsolationLevel(level) {\n\tcase sql.LevelRepeatableRead:\n\t\treturn \"REPEATABLE READ\", nil\n\tcase sql.LevelReadCommitted:\n\t\treturn \"READ COMMITTED\", nil\n\tcase sql.LevelReadUncommitted:\n\t\treturn \"READ UNCOMMITTED\", nil\n\tcase sql.LevelSerializable:\n\t\treturn \"SERIALIZABLE\", nil\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"mysql: unsupported isolation level: %v\", level)\n\t}\n}\n"
  },
  {
    "path": "utils_test.go",
    "content": "// Go MySQL Driver - A MySQL-Driver for Go's database/sql package\n//\n// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at http://mozilla.org/MPL/2.0/.\n\npackage mysql\n\nimport (\n\t\"bytes\"\n\t\"database/sql\"\n\t\"database/sql/driver\"\n\t\"encoding/binary\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestLengthEncodedInteger(t *testing.T) {\n\tvar integerTests = []struct {\n\t\tnum     uint64\n\t\tencoded []byte\n\t}{\n\t\t{0x0000000000000000, []byte{0x00}},\n\t\t{0x0000000000000012, []byte{0x12}},\n\t\t{0x00000000000000fa, []byte{0xfa}},\n\t\t{0x0000000000000100, []byte{0xfc, 0x00, 0x01}},\n\t\t{0x0000000000001234, []byte{0xfc, 0x34, 0x12}},\n\t\t{0x000000000000ffff, []byte{0xfc, 0xff, 0xff}},\n\t\t{0x0000000000010000, []byte{0xfd, 0x00, 0x00, 0x01}},\n\t\t{0x0000000000123456, []byte{0xfd, 0x56, 0x34, 0x12}},\n\t\t{0x0000000000ffffff, []byte{0xfd, 0xff, 0xff, 0xff}},\n\t\t{0x0000000001000000, []byte{0xfe, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00}},\n\t\t{0x123456789abcdef0, []byte{0xfe, 0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12}},\n\t\t{0xffffffffffffffff, []byte{0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}},\n\t}\n\n\tfor _, tst := range integerTests {\n\t\tnum, isNull, numLen := readLengthEncodedInteger(tst.encoded)\n\t\tif isNull {\n\t\t\tt.Errorf(\"%x: expected %d, got NULL\", tst.encoded, tst.num)\n\t\t}\n\t\tif num != tst.num {\n\t\t\tt.Errorf(\"%x: expected %d, got %d\", tst.encoded, tst.num, num)\n\t\t}\n\t\tif numLen != len(tst.encoded) {\n\t\t\tt.Errorf(\"%x: expected size %d, got %d\", tst.encoded, len(tst.encoded), numLen)\n\t\t}\n\t\tencoded := appendLengthEncodedInteger(nil, num)\n\t\tif !bytes.Equal(encoded, tst.encoded) {\n\t\t\tt.Errorf(\"%v: expected %x, got %x\", num, tst.encoded, encoded)\n\t\t}\n\t}\n}\n\nfunc TestFormatBinaryDateTime(t *testing.T) {\n\trawDate := [11]byte{}\n\tbinary.LittleEndian.PutUint16(rawDate[:2], 1978)   // years\n\trawDate[2] = 12                                    // months\n\trawDate[3] = 30                                    // days\n\trawDate[4] = 15                                    // hours\n\trawDate[5] = 46                                    // minutes\n\trawDate[6] = 23                                    // seconds\n\tbinary.LittleEndian.PutUint32(rawDate[7:], 987654) // microseconds\n\texpect := func(expected string, inlen, outlen uint8) {\n\t\tactual, _ := formatBinaryDateTime(rawDate[:inlen], outlen)\n\t\tbytes, ok := actual.([]byte)\n\t\tif !ok {\n\t\t\tt.Errorf(\"formatBinaryDateTime must return []byte, was %T\", actual)\n\t\t}\n\t\tif string(bytes) != expected {\n\t\t\tt.Errorf(\n\t\t\t\t\"expected %q, got %q for length in %d, out %d\",\n\t\t\t\texpected, actual, inlen, outlen,\n\t\t\t)\n\t\t}\n\t}\n\texpect(\"0000-00-00\", 0, 10)\n\texpect(\"0000-00-00 00:00:00\", 0, 19)\n\texpect(\"1978-12-30\", 4, 10)\n\texpect(\"1978-12-30 15:46:23\", 7, 19)\n\texpect(\"1978-12-30 15:46:23.987654\", 11, 26)\n}\n\nfunc TestFormatBinaryTime(t *testing.T) {\n\texpect := func(expected string, src []byte, outlen uint8) {\n\t\tactual, _ := formatBinaryTime(src, outlen)\n\t\tbytes, ok := actual.([]byte)\n\t\tif !ok {\n\t\t\tt.Errorf(\"formatBinaryDateTime must return []byte, was %T\", actual)\n\t\t}\n\t\tif string(bytes) != expected {\n\t\t\tt.Errorf(\n\t\t\t\t\"expected %q, got %q for src=%q and outlen=%d\",\n\t\t\t\texpected, actual, src, outlen)\n\t\t}\n\t}\n\n\t// binary format:\n\t// sign (0: positive, 1: negative), days(4), hours, minutes, seconds, micro(4)\n\n\t// Zeros\n\texpect(\"00:00:00\", []byte{}, 8)\n\texpect(\"00:00:00.0\", []byte{}, 10)\n\texpect(\"00:00:00.000000\", []byte{}, 15)\n\n\t// Without micro(4)\n\texpect(\"12:34:56\", []byte{0, 0, 0, 0, 0, 12, 34, 56}, 8)\n\texpect(\"-12:34:56\", []byte{1, 0, 0, 0, 0, 12, 34, 56}, 8)\n\texpect(\"12:34:56.00\", []byte{0, 0, 0, 0, 0, 12, 34, 56}, 11)\n\texpect(\"24:34:56\", []byte{0, 1, 0, 0, 0, 0, 34, 56}, 8)\n\texpect(\"-99:34:56\", []byte{1, 4, 0, 0, 0, 3, 34, 56}, 8)\n\texpect(\"103079215103:34:56\", []byte{0, 255, 255, 255, 255, 23, 34, 56}, 8)\n\n\t// With micro(4)\n\texpect(\"12:34:56.00\", []byte{0, 0, 0, 0, 0, 12, 34, 56, 99, 0, 0, 0}, 11)\n\texpect(\"12:34:56.000099\", []byte{0, 0, 0, 0, 0, 12, 34, 56, 99, 0, 0, 0}, 15)\n}\n\nfunc TestEscapeBackslash(t *testing.T) {\n\texpect := func(expected, value string) {\n\t\tactual := string(escapeBytesBackslash([]byte{}, []byte(value)))\n\t\tif actual != expected {\n\t\t\tt.Errorf(\n\t\t\t\t\"expected %s, got %s\",\n\t\t\t\texpected, actual,\n\t\t\t)\n\t\t}\n\n\t\tactual = string(escapeStringBackslash([]byte{}, value))\n\t\tif actual != expected {\n\t\t\tt.Errorf(\n\t\t\t\t\"expected %s, got %s\",\n\t\t\t\texpected, actual,\n\t\t\t)\n\t\t}\n\t}\n\n\texpect(\"foo\\\\0bar\", \"foo\\x00bar\")\n\texpect(\"foo\\\\nbar\", \"foo\\nbar\")\n\texpect(\"foo\\\\rbar\", \"foo\\rbar\")\n\texpect(\"foo\\\\Zbar\", \"foo\\x1abar\")\n\texpect(\"foo\\\\\\\"bar\", \"foo\\\"bar\")\n\texpect(\"foo\\\\\\\\bar\", \"foo\\\\bar\")\n\texpect(\"foo\\\\'bar\", \"foo'bar\")\n}\n\nfunc TestEscapeQuotes(t *testing.T) {\n\texpect := func(expected, value string) {\n\t\tactual := string(escapeBytesQuotes([]byte{}, []byte(value)))\n\t\tif actual != expected {\n\t\t\tt.Errorf(\n\t\t\t\t\"expected %s, got %s\",\n\t\t\t\texpected, actual,\n\t\t\t)\n\t\t}\n\n\t\tactual = string(escapeStringQuotes([]byte{}, value))\n\t\tif actual != expected {\n\t\t\tt.Errorf(\n\t\t\t\t\"expected %s, got %s\",\n\t\t\t\texpected, actual,\n\t\t\t)\n\t\t}\n\t}\n\n\texpect(\"foo\\x00bar\", \"foo\\x00bar\") // not affected\n\texpect(\"foo\\nbar\", \"foo\\nbar\")     // not affected\n\texpect(\"foo\\rbar\", \"foo\\rbar\")     // not affected\n\texpect(\"foo\\x1abar\", \"foo\\x1abar\") // not affected\n\texpect(\"foo''bar\", \"foo'bar\")      // affected\n\texpect(\"foo\\\"bar\", \"foo\\\"bar\")     // not affected\n}\n\nfunc TestAtomicError(t *testing.T) {\n\tvar ae atomicError\n\tif ae.Value() != nil {\n\t\tt.Fatal(\"Expected value to be nil\")\n\t}\n\n\tae.Set(ErrMalformPkt)\n\tif v := ae.Value(); v != ErrMalformPkt {\n\t\tif v == nil {\n\t\t\tt.Fatal(\"Value is still nil\")\n\t\t}\n\t\tt.Fatal(\"Error did not match\")\n\t}\n\tae.Set(ErrPktSync)\n\tif ae.Value() == ErrMalformPkt {\n\t\tt.Fatal(\"Error still matches old error\")\n\t}\n\tif v := ae.Value(); v != ErrPktSync {\n\t\tt.Fatal(\"Error did not match\")\n\t}\n}\n\nfunc TestIsolationLevelMapping(t *testing.T) {\n\tdata := []struct {\n\t\tlevel    driver.IsolationLevel\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tlevel:    driver.IsolationLevel(sql.LevelReadCommitted),\n\t\t\texpected: \"READ COMMITTED\",\n\t\t},\n\t\t{\n\t\t\tlevel:    driver.IsolationLevel(sql.LevelRepeatableRead),\n\t\t\texpected: \"REPEATABLE READ\",\n\t\t},\n\t\t{\n\t\t\tlevel:    driver.IsolationLevel(sql.LevelReadUncommitted),\n\t\t\texpected: \"READ UNCOMMITTED\",\n\t\t},\n\t\t{\n\t\t\tlevel:    driver.IsolationLevel(sql.LevelSerializable),\n\t\t\texpected: \"SERIALIZABLE\",\n\t\t},\n\t}\n\n\tfor i, td := range data {\n\t\tif actual, err := mapIsolationLevel(td.level); actual != td.expected || err != nil {\n\t\t\tt.Fatal(i, td.expected, actual, err)\n\t\t}\n\t}\n\n\t// check unsupported mapping\n\texpectedErr := \"mysql: unsupported isolation level: 7\"\n\tactual, err := mapIsolationLevel(driver.IsolationLevel(sql.LevelLinearizable))\n\tif actual != \"\" || err == nil {\n\t\tt.Fatal(\"Expected error on unsupported isolation level\")\n\t}\n\tif err.Error() != expectedErr {\n\t\tt.Fatalf(\"Expected error to be %q, got %q\", expectedErr, err)\n\t}\n}\n\nfunc TestAppendDateTime(t *testing.T) {\n\ttests := []struct {\n\t\tt            time.Time\n\t\tstr          string\n\t\ttimeTruncate time.Duration\n\t\texpectedErr  bool\n\t}{\n\t\t{\n\t\t\tt:   time.Date(1234, 5, 6, 0, 0, 0, 0, time.UTC),\n\t\t\tstr: \"1234-05-06\",\n\t\t},\n\t\t{\n\t\t\tt:   time.Date(4567, 12, 31, 12, 0, 0, 0, time.UTC),\n\t\t\tstr: \"4567-12-31 12:00:00\",\n\t\t},\n\t\t{\n\t\t\tt:   time.Date(2020, 5, 30, 12, 34, 0, 0, time.UTC),\n\t\t\tstr: \"2020-05-30 12:34:00\",\n\t\t},\n\t\t{\n\t\t\tt:   time.Date(2020, 5, 30, 12, 34, 56, 0, time.UTC),\n\t\t\tstr: \"2020-05-30 12:34:56\",\n\t\t},\n\t\t{\n\t\t\tt:   time.Date(2020, 5, 30, 22, 33, 44, 123000000, time.UTC),\n\t\t\tstr: \"2020-05-30 22:33:44.123\",\n\t\t},\n\t\t{\n\t\t\tt:   time.Date(2020, 5, 30, 22, 33, 44, 123456000, time.UTC),\n\t\t\tstr: \"2020-05-30 22:33:44.123456\",\n\t\t},\n\t\t{\n\t\t\tt:   time.Date(2020, 5, 30, 22, 33, 44, 123456789, time.UTC),\n\t\t\tstr: \"2020-05-30 22:33:44.123456789\",\n\t\t},\n\t\t{\n\t\t\tt:   time.Date(9999, 12, 31, 23, 59, 59, 999999999, time.UTC),\n\t\t\tstr: \"9999-12-31 23:59:59.999999999\",\n\t\t},\n\t\t{\n\t\t\tt:   time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC),\n\t\t\tstr: \"0001-01-01\",\n\t\t},\n\t\t// Truncated time\n\t\t{\n\t\t\tt:            time.Date(1234, 5, 6, 0, 0, 0, 0, time.UTC),\n\t\t\tstr:          \"1234-05-06\",\n\t\t\ttimeTruncate: time.Second,\n\t\t},\n\t\t{\n\t\t\tt:            time.Date(4567, 12, 31, 12, 0, 0, 0, time.UTC),\n\t\t\tstr:          \"4567-12-31 12:00:00\",\n\t\t\ttimeTruncate: time.Minute,\n\t\t},\n\t\t{\n\t\t\tt:            time.Date(2020, 5, 30, 12, 34, 0, 0, time.UTC),\n\t\t\tstr:          \"2020-05-30 12:34:00\",\n\t\t\ttimeTruncate: 0,\n\t\t},\n\t\t{\n\t\t\tt:            time.Date(2020, 5, 30, 12, 34, 56, 0, time.UTC),\n\t\t\tstr:          \"2020-05-30 12:34:56\",\n\t\t\ttimeTruncate: time.Second,\n\t\t},\n\t\t{\n\t\t\tt:            time.Date(2020, 5, 30, 22, 33, 44, 123000000, time.UTC),\n\t\t\tstr:          \"2020-05-30 22:33:44\",\n\t\t\ttimeTruncate: time.Second,\n\t\t},\n\t\t{\n\t\t\tt:            time.Date(2020, 5, 30, 22, 33, 44, 123456000, time.UTC),\n\t\t\tstr:          \"2020-05-30 22:33:44.123\",\n\t\t\ttimeTruncate: time.Millisecond,\n\t\t},\n\t\t{\n\t\t\tt:            time.Date(2020, 5, 30, 22, 33, 44, 123456789, time.UTC),\n\t\t\tstr:          \"2020-05-30 22:33:44\",\n\t\t\ttimeTruncate: time.Second,\n\t\t},\n\t\t{\n\t\t\tt:            time.Date(9999, 12, 31, 23, 59, 59, 999999999, time.UTC),\n\t\t\tstr:          \"9999-12-31 23:59:59.999999999\",\n\t\t\ttimeTruncate: 0,\n\t\t},\n\t\t{\n\t\t\tt:            time.Date(1, 1, 1, 1, 1, 1, 1, time.UTC),\n\t\t\tstr:          \"0001-01-01\",\n\t\t\ttimeTruncate: 365 * 24 * time.Hour,\n\t\t},\n\t\t// year out of range\n\t\t{\n\t\t\tt:           time.Date(0, 1, 1, 0, 0, 0, 0, time.UTC),\n\t\t\texpectedErr: true,\n\t\t},\n\t\t{\n\t\t\tt:           time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC),\n\t\t\texpectedErr: true,\n\t\t},\n\t}\n\tfor _, v := range tests {\n\t\tbuf := make([]byte, 0, 32)\n\t\tbuf, err := appendDateTime(buf, v.t, v.timeTruncate)\n\t\tif err != nil {\n\t\t\tif !v.expectedErr {\n\t\t\t\tt.Errorf(\"appendDateTime(%v) returned an error: %v\", v.t, err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif str := string(buf); str != v.str {\n\t\t\tt.Errorf(\"appendDateTime(%v), have: %s, want: %s\", v.t, str, v.str)\n\t\t}\n\t}\n}\n\nfunc TestParseDateTime(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tstr  string\n\t}{\n\t\t{\n\t\t\tname: \"parse date\",\n\t\t\tstr:  \"2020-05-13\",\n\t\t},\n\t\t{\n\t\t\tname: \"parse null date\",\n\t\t\tstr:  sDate0,\n\t\t},\n\t\t{\n\t\t\tname: \"parse datetime\",\n\t\t\tstr:  \"2020-05-13 21:30:45\",\n\t\t},\n\t\t{\n\t\t\tname: \"parse null datetime\",\n\t\t\tstr:  sDateTime0,\n\t\t},\n\t\t{\n\t\t\tname: \"parse datetime nanosec 1-digit\",\n\t\t\tstr:  \"2020-05-25 23:22:01.1\",\n\t\t},\n\t\t{\n\t\t\tname: \"parse datetime nanosec 2-digits\",\n\t\t\tstr:  \"2020-05-25 23:22:01.15\",\n\t\t},\n\t\t{\n\t\t\tname: \"parse datetime nanosec 3-digits\",\n\t\t\tstr:  \"2020-05-25 23:22:01.159\",\n\t\t},\n\t\t{\n\t\t\tname: \"parse datetime nanosec 4-digits\",\n\t\t\tstr:  \"2020-05-25 23:22:01.1594\",\n\t\t},\n\t\t{\n\t\t\tname: \"parse datetime nanosec 5-digits\",\n\t\t\tstr:  \"2020-05-25 23:22:01.15949\",\n\t\t},\n\t\t{\n\t\t\tname: \"parse datetime nanosec 6-digits\",\n\t\t\tstr:  \"2020-05-25 23:22:01.159491\",\n\t\t},\n\t}\n\n\tfor _, loc := range []*time.Location{\n\t\ttime.UTC,\n\t\ttime.FixedZone(\"test\", 8*60*60),\n\t} {\n\t\tfor _, cc := range cases {\n\t\t\tt.Run(cc.name+\"-\"+loc.String(), func(t *testing.T) {\n\t\t\t\tvar want time.Time\n\t\t\t\tif cc.str != sDate0 && cc.str != sDateTime0 {\n\t\t\t\t\tvar err error\n\t\t\t\t\twant, err = time.ParseInLocation(timeFormat[:len(cc.str)], cc.str, loc)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tt.Fatal(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tgot, err := parseDateTime([]byte(cc.str), loc)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\n\t\t\t\tif !want.Equal(got) {\n\t\t\t\t\tt.Fatalf(\"want: %v, but got %v\", want, got)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestInvalidDateTime(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tstr  string\n\t\twant time.Time\n\t}{\n\t\t{\n\t\t\tname: \"parse datetime without day\",\n\t\t\tstr:  \"0000-00-00 21:30:45\",\n\t\t\twant: time.Date(0, 0, 0, 21, 30, 45, 0, time.UTC),\n\t\t},\n\t}\n\n\tfor _, cc := range cases {\n\t\tt.Run(cc.name, func(t *testing.T) {\n\t\t\tgot, err := parseDateTime([]byte(cc.str), time.UTC)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\n\t\t\tif !cc.want.Equal(got) {\n\t\t\t\tt.Fatalf(\"want: %v, but got %v\", cc.want, got)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestParseDateTimeFail(t *testing.T) {\n\tcases := []struct {\n\t\tname    string\n\t\tstr     string\n\t\twantErr string\n\t}{\n\t\t{\n\t\t\tname:    \"parse invalid time\",\n\t\t\tstr:     \"hello\",\n\t\t\twantErr: \"invalid time bytes: hello\",\n\t\t},\n\t\t{\n\t\t\tname:    \"parse year\",\n\t\t\tstr:     \"000!-00-00 00:00:00.000000\",\n\t\t\twantErr: \"not [0-9]\",\n\t\t},\n\t\t{\n\t\t\tname:    \"parse month\",\n\t\t\tstr:     \"0000-!0-00 00:00:00.000000\",\n\t\t\twantErr: \"not [0-9]\",\n\t\t},\n\t\t{\n\t\t\tname:    `parse \"-\" after parsed year`,\n\t\t\tstr:     \"0000:00-00 00:00:00.000000\",\n\t\t\twantErr: \"bad value for field: `:`\",\n\t\t},\n\t\t{\n\t\t\tname:    `parse \"-\" after parsed month`,\n\t\t\tstr:     \"0000-00:00 00:00:00.000000\",\n\t\t\twantErr: \"bad value for field: `:`\",\n\t\t},\n\t\t{\n\t\t\tname:    `parse \" \" after parsed date`,\n\t\t\tstr:     \"0000-00-00+00:00:00.000000\",\n\t\t\twantErr: \"bad value for field: `+`\",\n\t\t},\n\t\t{\n\t\t\tname:    `parse \":\" after parsed date`,\n\t\t\tstr:     \"0000-00-00 00-00:00.000000\",\n\t\t\twantErr: \"bad value for field: `-`\",\n\t\t},\n\t\t{\n\t\t\tname:    `parse \":\" after parsed hour`,\n\t\t\tstr:     \"0000-00-00 00:00-00.000000\",\n\t\t\twantErr: \"bad value for field: `-`\",\n\t\t},\n\t\t{\n\t\t\tname:    `parse \".\" after parsed sec`,\n\t\t\tstr:     \"0000-00-00 00:00:00?000000\",\n\t\t\twantErr: \"bad value for field: `?`\",\n\t\t},\n\t}\n\n\tfor _, cc := range cases {\n\t\tt.Run(cc.name, func(t *testing.T) {\n\t\t\tgot, err := parseDateTime([]byte(cc.str), time.UTC)\n\t\t\tif err == nil {\n\t\t\t\tt.Fatal(\"want error\")\n\t\t\t}\n\t\t\tif cc.wantErr != err.Error() {\n\t\t\t\tt.Fatalf(\"want `%s`, but got `%s`\", cc.wantErr, err)\n\t\t\t}\n\t\t\tif !got.IsZero() {\n\t\t\t\tt.Fatal(\"want zero time\")\n\t\t\t}\n\t\t})\n\t}\n}\n"
  }
]