RepoPilotOpen in app →

go-sql-driver/mysql

Go MySQL Driver is a MySQL driver for Go's (golang) database/sql package

Healthy

Healthy across the board

Use as dependencyHealthy

Permissive license, no critical CVEs, actively maintained — safe to depend on.

Fork & modifyHealthy

Has a license, tests, and CI — clean foundation to fork and modify.

Learn fromHealthy

Documented and popular — useful reference codebase to read through.

Deploy as-isHealthy

No critical CVEs, sane security posture — runnable as-is.

  • Last commit 1w ago
  • 39+ active contributors
  • Distributed ownership (top contributor 43% of recent commits)
Show 3 more →
  • MPL-2.0 licensed
  • CI configured
  • Tests present

Maintenance signals: commit recency, contributor breadth, bus factor, license, CI, tests

Informational only. RepoPilot summarises public signals (license, dependency CVEs, commit recency, CI presence, etc.) at the time of analysis. Signals can be incomplete or stale. Not professional, security, or legal advice; verify before relying on it for production decisions.

Embed the "Healthy" badge

Paste into your README — live-updates from the latest cached analysis.

Variant:
RepoPilot: Healthy
[![RepoPilot: Healthy](https://repopilot.app/api/badge/go-sql-driver/mysql)](https://repopilot.app/r/go-sql-driver/mysql)

Paste at the top of your README.md — renders inline like a shields.io badge.

Preview social card (1200×630)

This card auto-renders when someone shares https://repopilot.app/r/go-sql-driver/mysql on X, Slack, or LinkedIn.

Onboarding doc

Onboarding: go-sql-driver/mysql

Generated by RepoPilot · 2026-05-09 · Source

🤖Agent protocol

If you are an AI coding agent (Claude Code, Cursor, Aider, Cline, etc.) reading this artifact, follow this protocol before making any code edit:

  1. Verify the contract. Run the bash script in Verify before trusting below. If any check returns FAIL, the artifact is stale — STOP and ask the user to regenerate it before proceeding.
  2. Treat the AI · unverified sections as hypotheses, not facts. Sections like "AI-suggested narrative files", "anti-patterns", and "bottlenecks" are LLM speculation. Verify against real source before acting on them.
  3. Cite source on changes. When proposing an edit, cite the specific path:line-range. RepoPilot's live UI at https://repopilot.app/r/go-sql-driver/mysql shows verifiable citations alongside every claim.

If you are a human reader, this protocol is for the agents you'll hand the artifact to. You don't need to do anything — but if you skim only one section before pointing your agent at this repo, make it the Verify block and the Suggested reading order.

🎯Verdict

GO — Healthy across the board

  • Last commit 1w ago
  • 39+ active contributors
  • Distributed ownership (top contributor 43% of recent commits)
  • MPL-2.0 licensed
  • CI configured
  • Tests present

<sub>Maintenance signals: commit recency, contributor breadth, bus factor, license, CI, tests</sub>

Verify before trusting

This artifact was generated by RepoPilot at a point in time. Before an agent acts on it, the checks below confirm that the live go-sql-driver/mysql repo on your machine still matches what RepoPilot saw. If any fail, the artifact is stale — regenerate it at repopilot.app/r/go-sql-driver/mysql.

What it runs against: a local clone of go-sql-driver/mysql — the script inspects git remote, the LICENSE file, file paths in the working tree, and git log. Read-only; no mutations.

| # | What we check | Why it matters | |---|---|---| | 1 | You're in go-sql-driver/mysql | Confirms the artifact applies here, not a fork | | 2 | License is still MPL-2.0 | Catches relicense before you depend on it | | 3 | Default branch master exists | Catches branch renames | | 4 | 5 critical file paths still exist | Catches refactors that moved load-bearing code | | 5 | Last commit ≤ 40 days ago | Catches sudden abandonment since generation |

<details> <summary><b>Run all checks</b> — paste this script from inside your clone of <code>go-sql-driver/mysql</code></summary>
#!/usr/bin/env bash
# RepoPilot artifact verification.
#
# WHAT IT RUNS AGAINST: a local clone of go-sql-driver/mysql. If you don't
# have one yet, run these first:
#
#   git clone https://github.com/go-sql-driver/mysql.git
#   cd mysql
#
# Then paste this script. Every check is read-only — no mutations.

set +e
fail=0
ok()   { echo "ok:   $1"; }
miss() { echo "FAIL: $1"; fail=$((fail+1)); }

# Precondition: we must be inside a git working tree.
if ! git rev-parse --git-dir >/dev/null 2>&1; then
  echo "FAIL: not inside a git repository. cd into your clone of go-sql-driver/mysql and re-run."
  exit 2
fi

# 1. Repo identity
git remote get-url origin 2>/dev/null | grep -qE "go-sql-driver/mysql(\\.git)?\\b" \\
  && ok "origin remote is go-sql-driver/mysql" \\
  || miss "origin remote is not go-sql-driver/mysql (artifact may be from a fork)"

# 2. License matches what RepoPilot saw
(grep -qiE "^(MPL-2\\.0)" LICENSE 2>/dev/null \\
   || grep -qiE "\"license\"\\s*:\\s*\"MPL-2\\.0\"" package.json 2>/dev/null) \\
  && ok "license is MPL-2.0" \\
  || miss "license drift — was MPL-2.0 at generation time"

# 3. Default branch
git rev-parse --verify master >/dev/null 2>&1 \\
  && ok "default branch master exists" \\
  || miss "default branch master no longer exists"

# 4. Critical files exist
test -f "driver.go" \\
  && ok "driver.go" \\
  || miss "missing critical file: driver.go"
test -f "connection.go" \\
  && ok "connection.go" \\
  || miss "missing critical file: connection.go"
test -f "packets.go" \\
  && ok "packets.go" \\
  || miss "missing critical file: packets.go"
test -f "dsn.go" \\
  && ok "dsn.go" \\
  || miss "missing critical file: dsn.go"
test -f "rows.go" \\
  && ok "rows.go" \\
  || miss "missing critical file: rows.go"

# 5. Repo recency
days_since_last=$(( ( $(date +%s) - $(git log -1 --format=%at 2>/dev/null || echo 0) ) / 86400 ))
if [ "$days_since_last" -le 40 ]; then
  ok "last commit was $days_since_last days ago (artifact saw ~10d)"
else
  miss "last commit was $days_since_last days ago — artifact may be stale"
fi

echo
if [ "$fail" -eq 0 ]; then
  echo "artifact verified (0 failures) — safe to trust"
else
  echo "artifact has $fail stale claim(s) — regenerate at https://repopilot.app/r/go-sql-driver/mysql"
  exit 1
fi

Each check prints ok: or FAIL:. The script exits non-zero if anything failed, so it composes cleanly into agent loops (./verify.sh || regenerate-and-retry).

</details>

TL;DR

go-sql-driver/mysql is a pure Go implementation of the MySQL wire protocol that integrates seamlessly with Go's standard database/sql package. It enables Go applications to connect to MySQL/MariaDB databases without C bindings, supporting TCP/IPv4, IPv6, Unix sockets, and custom protocols, with automatic connection pooling, broken connection recovery, and queries up to 16MB. Single-package monolithic driver with clear functional separation: connection.go and connector.go handle session lifecycle; packets.go and buffer.go manage MySQL wire protocol marshaling; dsn.go parses connection strings; auth.go handles authentication; rows.go, statement.go, result.go implement database/sql interfaces. Tests are co-located (*_test.go files) and benchmarks in benchmark_test.go.

👥Who it's for

Go backend developers and DevOps engineers building production systems that need reliable MySQL connectivity without cgo overhead. Users range from microservice developers using database/sql with ORMs (like gorm) to those writing custom SQL query layers who need bulletproof, zero-dependency database access.

🌱Maturity & risk

Highly mature and production-ready. The codebase shows comprehensive test coverage (auth_test.go, connection_test.go, dsn_test.go, etc.), active CI/CD via GitHub Actions (test.yml, codeql.yml), and explicit Go 1.24.0 support in go.mod. Minimal dependencies (only filippo.io/edwards25519 for auth) and widespread use in production Go applications indicate stable, battle-tested code.

Very low risk. Single dependency (edwards25519) is well-maintained; the driver is broadly compatible across Go versions; no security advisories evident. Main consideration: this is the de facto MySQL driver for Go, so any breaking changes would impact the ecosystem—maintainers are cautious. Performance-critical paths (packet parsing, buffer management) are mature but worth reviewing if you modify low-level connection handling.

Active areas of work

No specific recent commits or PRs visible in the provided data, but the codebase includes modern Go patterns (context.Context support via the presence of connection lifecycle files), fuzzing tests (dsn_fuzz_test.go), and active security scanning (codeql.yml workflow). Dependabot is configured (.github/dependabot.yml), indicating active dependency maintenance.

🚀Get running

git clone https://github.com/go-sql-driver/mysql.git
cd mysql
go mod download
go test ./...

Daily commands: This is a library, not an executable. Run tests with go test ./... or go test -bench=. ./... for benchmarks (see benchmark_test.go). For CI integration, the repo uses GitHub Actions: see .github/workflows/test.yml for the exact test matrix and commands.

🗺️Map of the codebase

  • driver.go — Entry point that registers the MySQL driver with Go's database/sql package; every contributor must understand the driver initialization flow.
  • connection.go — Core abstraction managing the TCP/socket connection lifecycle, packet I/O, and authentication; the most critical runtime component.
  • packets.go — Low-level MySQL wire protocol serialization and deserialization; required knowledge for debugging network-level issues.
  • dsn.go — Parses Data Source Name configuration; essential for understanding connection setup and parameter validation.
  • rows.go — Implements database/sql Rows interface for result set iteration; the primary API surface for query consumers.
  • statement.go — Implements prepared statement execution and parameter binding; critical for SQL injection prevention and query optimization.
  • auth.go — Handles MySQL authentication mechanisms (native, SHA2); security-critical code for credential handling.

🧩Components & responsibilities

  • Driver (driver.go) (Go database/sql standard library) — Register the MySQL driver with sql.Open(), implement sql.Driver interface, and dispatch to Connector
    • Failure mode: Registration failure prevents any MySQL connections; panics if driver already registered
  • undefined — undefined

🛠️How to make changes

Add support for a new MySQL authentication plugin

  1. Define the plugin name constant in const.go (const.go)
  2. Implement the authentication logic in auth.go following the authPlugin interface pattern used by authNative and authCachingSha2 (auth.go)
  3. Register the plugin in the auth dispatch logic within connection.go's handleAuthPluginChange() and readAuthPluginRequired() (connection.go)
  4. Add test cases in auth_test.go covering successful and failed authentication flows (auth_test.go)

Add a new connection configuration parameter

  1. Add the field to the Config struct and document its purpose in dsn.go (dsn.go)
  2. Implement parsing logic in the parseDSN() function in dsn.go to extract the parameter from the DSN string (dsn.go)
  3. Use the Config field in connection.go or connector.go during connection setup or initialization (connection.go)
  4. Add test cases in dsn_test.go to verify parsing of valid/invalid values (dsn_test.go)

Add support for a new MySQL protocol feature or command

  1. Define command/flag constants in const.go (const.go)
  2. Implement packet reading/writing logic in packets.go, following the pattern of existing command handlers (packets.go)
  3. Integrate command execution into connection.go's command dispatch or query execution flow (connection.go)
  4. Handle result parsing in rows.go or result.go if the command returns data (rows.go)
  5. Add comprehensive tests in packets_test.go and integration tests in connection_test.go (packets_test.go)

Improve connection pooling or statement caching behavior

  1. Add configuration fields to Config in dsn.go with reasonable defaults documented in README.md (dsn.go)
  2. Implement cache/pool logic in connector.go if using sql.Connector, or in connection.go for per-connection statement caching (connector.go)
  3. Implement cache eviction and lifecycle management in statement.go if caching prepared statements (statement.go)
  4. Add benchmarks in benchmark_test.go measuring cache hit/miss performance improvements (benchmark_test.go)

🔧Why these technologies

  • Go standard library database/sql — Provides a stable, well-known interface for database access; Go community standard for relational DB drivers
  • MySQL wire protocol (TCP/Unix sockets) — Direct protocol implementation avoids C bindings and CGO overhead; enables pure-Go deployment and cross-compilation
  • ed25519 (filippo.io/edwards25519) — Supports modern MySQL 8.0+ ed25519 password authentication plugin; cryptographically secure and performant
  • zlib compression (compress.go) — Optional protocol-level compression reduces bandwidth for large result sets; negotiated at connection time

⚖️Trade-offs already made

  • Pure Go implementation (no CGO bindings to libmysqlclient)

    • Why: Simplifies deployment, enables cross-compilation, avoids C dependency complexity, and reduces security surface
    • Consequence: Must maintain full MySQL wire protocol parser in Go; more maintenance burden than FFI, but pays off for portability
  • Statement caching managed per-connection rather than driver-wide

    • Why: Avoids synchronization overhead and makes cache eviction simpler within connection lifecycle
    • Consequence: Cache benefits only within a single connection; pooled connections do not share prepared statement cache across the pool
  • Synchronous request-response model for all operations

    • Why: Matches MySQL protocol semantics; aligns with Go's database/sql blocking model
    • Consequence: No multiplexing of concurrent requests over a single connection; each query holds exclusive connection lock
  • Platform-specific connection health checks (conncheck.go vs conncheck_dummy.go)

    • Why: Enables efficient keep-alive on platforms with TCP_USER_TIMEOUT support; fallback for unsupported platforms
    • Consequence: Connection validation behavior varies by OS; dummy implementation may miss stale connections

🚫Non-goals (don't propose these)

  • Does not provide connection pooling—that is delegated to sql.DB and sql.Connector (conncheck validates existing connections)
  • Does not implement sharding, replication awareness, or multi-master failover—single-server driver only
  • Does not support X Protocol (MySQL X DevAPI)—wire protocol only
  • Does not provide ORM or query builder functionality—low-level driver only

🪤Traps & gotchas

No external test server required: tests mock connections or use environment-injected MySQL instances (see .github/workflows/test.yml for CI setup). DSN format is strict: connection strings must follow the exact format or dsn.go will panic; validate user input. Unicode handling is implicit: charset parameter in DSN affects how strings are encoded; incorrect charset causes silent data corruption, not loud errors. Buffer reuse across packets: buffer.go reuses memory pools, so holding onto raw byte slices from old packets will produce corrupted data.

🏗️Architecture

💡Concepts to learn

  • MySQL Wire Protocol — The entire driver is a state machine that reads and writes MySQL's binary protocol; understanding handshakes, OK packets, EOF markers, and error packets is essential to debugging connection issues or extending the driver.
  • Connection Pooling (database/sql layer) — The driver delegates to Go's database/sql for connection pooling, but understanding MaxOpenConns, MaxIdleConns, and connection lifetime is critical for production Go applications using this driver.
  • DSN (Data Source Name) Parsing — Users specify all connection parameters through a DSN string (dsn.go); malformed DSNs cause silent failures or security issues (e.g., plaintext passwords in URLs). Parsing must handle edge cases like URL encoding in passwords.
  • context.Context Propagation — Modern Go requires context support for timeouts, cancellation, and tracing; this driver must respect context deadlines across connect, query, and fetch phases without blocking.
  • MySQL Authentication (SHA2-256) — Modern MySQL versions use SHA2-256 password hashing; the driver uses edwards25519 for this. Understanding salts, challenges, and handshake negotiation is needed to debug auth failures.
  • Buffer Management & Zero-Copy Patterns — High-performance drivers minimize allocations; buffer.go uses object pools and unsafe pointer tricks to avoid GC pressure. Understanding these patterns is critical for performance tuning and avoiding data corruption bugs.
  • LOAD DATA LOCAL INFILE (Security Implications) — This MySQL feature allows clients to upload files to the server; it's powerful but dangerous (file path traversal, ACL bypass). The driver must validate file paths and respect allowlist/denylist policies (infile.go).
  • golang/go — Go standard library, specifically database/sql package that this driver implements interfaces for.
  • gohxs/gohx — Alternative MySQL driver using a different protocol implementation approach; useful for comparative understanding.
  • go-sql-driver/mysql-research — Historical research repo tracking MySQL wire protocol changes and compatibility matrices across MySQL/MariaDB versions.
  • jinzhu/gorm — Popular Go ORM that depends on this driver for its MySQL backend and database/sql integration.
  • lib/pq — PostgreSQL driver for Go using the same database/sql interface pattern; useful for understanding driver design patterns across databases.

🪄PR ideas

To work on one of these in Claude Code or Cursor, paste: Implement the "<title>" PR idea from CLAUDE.md, working through the checklist as the task list.

Add fuzzing tests for packets.go and buffer.go parsing logic

The repo already has dsn_fuzz_test.go demonstrating fuzzing adoption, but critical parsing code in packets.go and buffer.go lacks fuzz tests. These handle binary protocol parsing from untrusted network input, making them high-value targets for fuzzing. This would catch edge cases, buffer overflows, and malformed packet handling issues early.

  • [ ] Create packets_fuzz_test.go with fuzzing for readPacket() and writePacket() functions
  • [ ] Create buffer_fuzz_test.go with fuzzing for buffer read/write operations
  • [ ] Ensure fuzz targets exercise boundary conditions (empty packets, max size packets, truncated data)
  • [ ] Add fuzz tests to GitHub Actions test.yml workflow if not already running go test -fuzz

Add comprehensive integration tests for transaction.go edge cases

transaction.go handles critical state management but transaction_test.go likely has limited coverage. The driver should have explicit tests for: nested transaction handling, rollback on connection errors, transaction isolation levels, and the interaction between transaction state and connection pooling. These are complex scenarios that real-world users encounter.

  • [ ] Review transaction_test.go and identify missing scenarios (nested txns, isolation levels, error recovery)
  • [ ] Add tests for BEGIN/COMMIT/ROLLBACK failure scenarios with mock connection failures
  • [ ] Add tests verifying transaction state is properly cleaned up after errors
  • [ ] Add tests for transaction interaction with connection.maxLifetime and reconnection

Add Go 1.24 specific compatibility tests and update conncheck.go for modern Go versions

The repo targets go 1.24.0 but conncheck.go and conncheck_dummy.go suggest platform-specific connection validation code. Go 1.24 may have new features or deprecations affecting connection handling. Adding version-gated tests and validating the driver works correctly with the latest Go releases (especially async features in net package) would ensure forward compatibility and catch issues early.

  • [ ] Review conncheck.go to identify deprecated net package APIs or missing Go 1.24 features
  • [ ] Add build-tag gated tests in conncheck_test.go for Go 1.24+ features (e.g., context.WithDeadline behavior changes)
  • [ ] Update .github/workflows/test.yml to test against go 1.24.0 if not already present, plus a canary test for go 1.25.0 development version
  • [ ] Document in CONTRIBUTING.md any Go version-specific behaviors in connection handling

🌿Good first issues

  • Add unit tests for nulltime.go's edge cases (leap seconds, timezone transitions, NULL handling) since nulltime_test.go exists but likely has gaps in coverage for MySQL DATETIME precision modes.
  • Document the conncheck.go and conncheck_dummy.go split (platform-specific connection validation) with examples of why different OS platforms need different approaches.
  • Add integration tests for the LOAD DATA LOCAL INFILE feature (infile.go) covering security implications (file path validation, ACL restrictions) and edge cases (binary data, large files).

Top contributors

Click to expand

📝Recent commits

Click to expand
  • a065b60 — release v1.10.0 (#1765) (methane)
  • 09e4187 — modernize (#1764) (methane)
  • 6c44a9a — Enhance interpolateParams to correctly handle placeholders (#1732) (rusher)
  • 688ce56 — Update supported Go version to 1.24–1.26 (#1763) (Copilot)
  • 118d07f — Bump filippo.io/edwards25519 from 1.1.1 to 1.2.0 (#1756) (dependabot[bot])
  • d6b2d3e — Consolidate Dependabot update noise by grouping weekly dependency PRs (#1762) (Copilot)
  • 037dfd8 — Fix getSystemVar buffer reuse (#1754) (morgo)
  • 900f330 — Bump actions/checkout from 4 to 6 (#1758) (dependabot[bot])
  • ab9e380 — fix staticcheck error (#1761) (methane)
  • f298c66 — Bump actions/setup-go from 5 to 6 (#1757) (dependabot[bot])

🔒Security observations

The go-sql-driver/mysql codebase demonstrates a good security posture with appropriate use of cryptographic libraries, comprehensive test coverage including fuzzing (dsn_fuzz_test.go), and CI/CD security scanning (CodeQL workflow). The primary concerns are: (1) lack of security policy documentation for vulnerability disclosure, (2) ensuring consumers use the driver with parameterized queries to prevent SQL injection, and (3) maintaining regular dependency updates. The codebase shows no hardcoded credentials, exposed secrets, or obvious injection vulnerabilities in the driver itself. Recommendation: Address the missing SECURITY.md file and enhance documentation around secure usage patterns.

  • Low · Dependency on Edwards25519 Cryptography Library — go.mod. The codebase depends on filippo.io/edwards25519 v1.2.0 for cryptographic operations, likely used in authentication. While this is a well-maintained library, it's important to ensure this dependency is kept up-to-date to receive security patches. Fix: Regularly audit and update dependencies using 'go get -u' and review the edwards25519 repository for security advisories. Consider using dependabot (already configured in .github/dependabot.yml) to automate dependency updates.
  • Medium · Potential SQL Injection in Dynamic Query Construction — connection.go, statement.go, rows.go. As a MySQL driver handling database connections and queries, the codebase processes user-supplied SQL statements. While the driver itself should not be vulnerable to SQLi, improper usage by consumers could lead to injection attacks if parameterized queries are not used. Fix: Ensure comprehensive documentation and examples emphasize the use of prepared statements with parameterized queries. Add security warnings in README.md about proper SQL injection prevention practices. Implement input validation at driver boundaries where applicable.
  • Low · Missing Security Policy Documentation — Repository root. No SECURITY.md file is present in the repository root, which should outline how to responsibly disclose security vulnerabilities to the maintainers. Fix: Create a SECURITY.md file following GitHub's recommended format (https://docs.github.com/en/code-security/getting-started/adding-a-security-policy-to-your-repository) that includes vulnerability disclosure guidelines and contact information.
  • Low · No Code Signing for Releases — Repository configuration. There is no visible evidence of code signing or release signing practices documented, which could allow tampering with distributed binaries. Fix: Implement GPG signing for releases and tags. Document the process in CONTRIBUTING.md. Provide public keys for verification of release artifacts.
  • Low · Limited Input Validation Documentation — dsn.go, dsn_fuzz_test.go. DSN (Data Source Name) parsing in dsn.go and dsn_fuzz_test.go suggests fuzzing is used, but there's no clear documentation about what inputs are validated and what edge cases are handled. Fix: Document DSN parsing rules and validation logic. Ensure all fuzz test findings are addressed. Consider expanding fuzzing coverage for critical functions like auth.go and packets.go.

LLM-derived; treat as a starting point, not a security audit.


Generated by RepoPilot. Verdict based on maintenance signals — see the live page for receipts. Re-run on a new commit to refresh.

Healthy signals · go-sql-driver/mysql — RepoPilot