From a26502624663150b71b9d649f4f1913f097281bf Mon Sep 17 00:00:00 2001 From: Jacob Quinn Date: Thu, 19 Nov 2026 03:17:45 -0700 Subject: [PATCH 1/2] Test that reconnect keeps the database a USE selected The fake peer records the database of each handshake: after USE, a dropped connection must come back into that database, and after the current database is dropped, into none. Co-Authored-By: Claude Opus 5.5 --- test/protocol/cursor_tests.jl | 49 +++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/test/protocol/cursor_tests.jl b/test/protocol/cursor_tests.jl index b349bd4a..5191bcec 100644 --- a/test/protocol/cursor_tests.jl +++ b/test/protocol/cursor_tests.jl @@ -965,6 +965,55 @@ end end end +@testset "reconnect restores the database the session last reported" begin + # The server reports a `USE` (or dropping the current database) in a SESSION_TRACK_SCHEMA + # block; libmysqlclient and 1.x reconnect to that database, not the one first requested. + dbs = String[] + accepted = AcceptedCounter(0) + schema_ok(name) = ok_payload(; status=P.SERVER_STATUS_AUTOCOMMIT | P.SERVER_SESSION_STATE_CHANGED, state=state_block(P.SESSION_TRACK_SCHEMA, name), track=true) + listener = Reseau.TCP.listen(Reseau.TCP.loopback_addr(0)) + port = Int(Reseau.TCP.addr(listener).port) + errormonitor(Threads.@spawn begin + while true + c = try; Reseau.TCP.accept(listener); catch; break; end + n = increment!(accepted) + errormonitor(Threads.@spawn begin + try + send_packet(c, 0, greeting(; caps=MYSQL8_SERVER_CAPS & ~P.CLIENT_SSL)) + seq, response = read_packet(c) + caps = UInt32(response[1]) | UInt32(response[2]) << 8 | UInt32(response[3]) << 16 | UInt32(response[4]) << 24 + rc = P.PacketCursor(response) + P.skip!(rc, 32) + P.read_nul_string!(rc) + P.read_lenenc_bytes!(rc) + push!(dbs, caps & P.CLIENT_CONNECT_WITH_DB != 0 ? P.read_nul_string!(rc) : "") + send_packet(c, seq + 1, ok_payload()) + read_command(c) # SET NAMES + send_packet(c, 1, ok_payload()) + expect_query(c) + send_packet(c, 1, n == 1 ? schema_ok("other") : n == 2 ? schema_ok("") : ok_payload()) + stall_until_eof(c) + catch + finally + close(c) + end + end) + end + end) + try + conn = DBInterface.connect(N.Connection, "127.0.0.1", "root", "pw"; port=port, ssl_mode=:disabled, connect_timeout=10, reconnect=true) + DBInterface.execute(conn, "USE other") + P.transport_close(conn.handle.session.transport) + DBInterface.execute(conn, "DROP DATABASE other") # reconnects into `other` + P.transport_close(conn.handle.session.transport) + DBInterface.execute(conn, "SELECT 1") # reconnects with no database + @test dbs == ["", "other", ""] + DBInterface.close!(conn) + finally + close(listener) + end +end + @testset "connection loss tells a sent command from a refused one (#248)" begin # The peer reads the command and hangs up without answering: the server may have run it # (2013). The next command is refused before anything is written (2006). From eeffca812c04563e9f8db137f06048fdd5ecaa16 Mon Sep 17 00:00:00 2001 From: Jacob Quinn Date: Thu, 19 Nov 2026 03:17:45 -0700 Subject: [PATCH 2/2] Reconnect to the database the session last used The server reports USE (and dropping the current database) in a SESSION_TRACK_SCHEMA block. The driver parsed the block but reconnected with the database from connect time, so after a reconnect unqualified queries ran against a different database. libmysqlclient and 1.x follow the tracked schema. Protocol.Session keeps the schema (requested at authentication, then each tracked change in an OK packet), and ensure_live! reconnects with it; connect(opts; db) sets CLIENT_CONNECT_WITH_DB to match. Co-Authored-By: Claude Opus 5.5 --- docs/src/index.md | 2 +- src/Protocol/auth.jl | 1 + src/Protocol/commands.jl | 2 ++ src/Protocol/session.jl | 17 +++++++++++++++-- src/connect.jl | 16 +++++++++------- src/connection.jl | 10 ++++++---- 6 files changed, 34 insertions(+), 14 deletions(-) diff --git a/docs/src/index.md b/docs/src/index.md index 50fcbc65..d507cdc2 100644 --- a/docs/src/index.md +++ b/docs/src/index.md @@ -142,7 +142,7 @@ raise `ArgumentError` unless their value is `nothing` or `false`. | `bind` | `nothing` | local interface/address to connect from | | `connect_timeout` | `nothing` | positive integer seconds for the whole establishment (dial, TLS, authentication, charset bootstrap) | | `read_timeout`, `write_timeout` | `nothing` | positive integer seconds per transport read/write; expiry closes the connection | -| `reconnect` | `false` | after a command fails on a dead connection, the next command reconnects (never inside a transaction) | +| `reconnect` | `false` | after a command fails on a dead connection, the next command reconnects (never inside a transaction) to the database the session last used (`USE` carries over) | | `init_command` | `nothing` | SQL run after authentication and charset bootstrap; it must also succeed in expired-password sandbox mode | | `charset_name` | `"utf8mb4"` | the only supported character set; the session is bootstrapped to utf8mb4 | | `attrs` | client name/version/OS/pid | `Vector{Pair{String, String}}` of connection attributes sent in the handshake | diff --git a/src/Protocol/auth.jl b/src/Protocol/auth.jl index 7b900d63..5ad5b69b 100644 --- a/src/Protocol/auth.jl +++ b/src/Protocol/auth.jl @@ -335,6 +335,7 @@ Policy violations raise `AuthError`, unknown plugins `UnsupportedAuthError`, ser """ function authenticate!(s::Session, user::AbstractString, password::Union{Nothing, AbstractString, AbstractVector{UInt8}}, policy::AuthPolicy; db::AbstractString="", attrs::Vector{Pair{String, String}}=Pair{String, String}[], default_auth::Union{Nothing, AbstractString}=nothing, trace::Union{Nothing, Vector{Symbol}}=nothing) require_phase(s, HANDSHAKE) + s.schema = String(db) note(event::Symbol) = return (trace === nothing || push!(trace, event); nothing) pw = password === nothing ? UInt8[] : password isa AbstractString ? Vector{UInt8}(codeunits(password)) : Vector{UInt8}(password) try diff --git a/src/Protocol/commands.jl b/src/Protocol/commands.jl index da8b7cfe..2ce28138 100644 --- a/src/Protocol/commands.jl +++ b/src/Protocol/commands.jl @@ -226,6 +226,7 @@ end function finish_ok!(s::Session, p::PacketView) ok = guarded(() -> parse_ok(p, s.capabilities, s.limits), s) s.status = ok.status + track_schema!(s, ok) s.command_kind == CMD_LOCAL_INFILE && (s.command_kind = CMD_QUERY) if more_results(ok) transition!(s, :ok_more, RESULT_END) @@ -338,6 +339,7 @@ end function finish_result!(s::Session, p::PacketView) if deprecate_eof(s) ok = guarded(() -> parse_ok(p, s.capabilities, s.limits), s) + track_schema!(s, ok) status, warnings, oksnap = ok.status, ok.warnings, ok else is_eof_packet(p) || throw(fault!(s, ProtocolError("expected EOF terminator, got a $(payload_length(p))-byte 0xFE packet"))) diff --git a/src/Protocol/session.jl b/src/Protocol/session.jl index 3d48f933..686389f1 100644 --- a/src/Protocol/session.jl +++ b/src/Protocol/session.jl @@ -3,7 +3,9 @@ Protocol state for one connection: the transport (replaced in place at STARTTLS), the shared packet reader/writer, negotiated capabilities, server info, the current `Phase`, the -last status flags, and per-command accounting against `Limits`. +last status flags, the default database (`schema`: the one requested at authentication, +then each `SESSION_TRACK_SCHEMA` change the server reports), and per-command accounting +against `Limits`. Every I/O failure (deadline, EOF, malformed packet, limit) moves the session to `BROKEN` and closes the transport: after any such failure the stream position is unknowable. @@ -18,6 +20,7 @@ mutable struct Session capabilities::UInt64 server::Union{Nothing, ServerInfo} status::UInt16 + schema::String generation::Int authenticated::Bool command_kind::CommandKind @@ -28,10 +31,19 @@ end function Session(transport::Transport; limits::Limits=Limits(), capabilities::UInt64=DEFAULT_CLIENT_CAPABILITIES, debug::Bool=false, log_transitions::Bool=false) log = log_transitions ? Tuple{Phase, Symbol, Phase}[] : nothing - return Session(transport, PacketIO(), limits, CONNECTING, debug, capabilities, capabilities, nothing, 0x0000, 1, false, CMD_QUERY, 0, 0, log) + return Session(transport, PacketIO(), limits, CONNECTING, debug, capabilities, capabilities, nothing, 0x0000, "", 1, false, CMD_QUERY, 0, 0, log) end has_capability(s::Session, flag::UInt64) = return has_capability(s.capabilities, flag) + +# A `USE` (or dropping the current database) changes the session's default database; a +# reconnect restores the last one the server reported. +function track_schema!(s::Session, ok::OKPacket) + schema = schema_change(ok) + schema === nothing || (s.schema = schema) + return nothing +end + server_kind(s::Session) = return s.server === nothing ? :unknown : s.server.kind is_mariadb(s::Session) = return server_kind(s) == :mariadb deprecate_eof(s::Session) = return has_capability(s, CLIENT_DEPRECATE_EOF) @@ -299,6 +311,7 @@ function read_auth_packet!(s::Session, round_number::Int, auth_bytes::Int) if kind == :ok ok = guarded(() -> parse_ok(p, s.capabilities, s.limits), s) s.status = ok.status + track_schema!(s, ok) s.authenticated = true transition!(s, :auth_ok, READY) return AuthPacket(:ok, ok, "", UInt8[]) diff --git a/src/connect.jl b/src/connect.jl index 18adf026..19c03f72 100644 --- a/src/connect.jl +++ b/src/connect.jl @@ -297,18 +297,20 @@ end timeout_ns(seconds::Union{Nothing, Int}) = return seconds === nothing ? Int64(0) : Int64(seconds) * 1_000_000_000 """ - connect(opts::ConnectOptions) -> Handle + connect(opts::ConnectOptions; db=opts.db) -> Handle connect(host, user, password=nothing; kw...) -> Handle Establishes an authenticated, utf8mb4-bootstrapped session: dial, greeting, STARTTLS per -`ssl_mode`, authentication, charset bootstrap, then `init_command`. `connect_timeout` bounds -everything up to the bootstrap as a single deadline; afterwards `read_timeout` and -`write_timeout` bound each transport read and write. Any failure closes the transport. +`ssl_mode`, authentication with default database `db`, charset bootstrap, then +`init_command`. `connect_timeout` bounds everything up to the bootstrap as a single +deadline; afterwards `read_timeout` and `write_timeout` bound each transport read and +write. Any failure closes the transport. """ -function connect(opts::ConnectOptions) +function connect(opts::ConnectOptions; db::String=opts.db) deadline = deadline_from(opts.connect_timeout) conn = dial(opts, deadline) - s = P.Session(conn; limits=opts.limits, capabilities=opts.client_flags, debug=opts.debug) + flags = isempty(db) ? opts.client_flags & ~P.CLIENT_CONNECT_WITH_DB : opts.client_flags | P.CLIENT_CONNECT_WITH_DB + s = P.Session(conn; limits=opts.limits, capabilities=flags, debug=opts.debug) try deadline == 0 || apply_deadline!(conn, deadline) P.read_greeting!(s) @@ -316,7 +318,7 @@ function connect(opts::ConnectOptions) (secure && deadline != 0) && apply_deadline!(s.transport, deadline) policy = P.AuthPolicy(opts.auth.secure_transport || secure, secure && opts.tls.mode == P.SSL_VERIFY_IDENTITY, opts.auth.server_public_key, opts.auth.get_server_public_key, opts.auth.enable_cleartext_plugin, opts.auth.insecure_cleartext_auth, opts.unix_socket !== nothing) trace = Symbol[] - ok = P.authenticate!(s, opts.user, opts.password, policy; db=opts.db, attrs=opts.attrs, default_auth=opts.default_auth, trace=trace) + ok = P.authenticate!(s, opts.user, opts.password, policy; db=db, attrs=opts.attrs, default_auth=opts.default_auth, trace=trace) bootstrapped = try bootstrap_charset!(s, ok) catch err diff --git a/src/connection.jl b/src/connection.jl index 4050bd0e..a168013e 100644 --- a/src/connection.jl +++ b/src/connection.jl @@ -156,16 +156,18 @@ end # Reconnect only before a send, once the session is known dead (closed, or broken by a # fault such as the server dropping an idle connection), and never inside a transaction: # the command that hit the failure reports it, the next one reconnects — the libmysqlclient -# contract. Statements and cursors of the old session are invalidated by the generation -# bump. A failed reconnect keeps the (dead) handle so the next command reports the -# connection error again and retries, instead of reporting a closed connection. +# contract. The new session opens the default database the old one last reported (a `USE` +# carries over, as in libmysqlclient). Statements and cursors of the old session are +# invalidated by the generation bump. A failed reconnect keeps the (dead) handle so the +# next command reports the connection error again and retries, instead of reporting a +# closed connection. function ensure_live!(conn::Connection) h = conn.handle isopen(h.session) && return nothing can_reconnect = conn.options.reconnect && conn.transaction_owner === nothing && !P.in_transaction(h.session.status) can_reconnect || throw(P.Error(P.CR_SERVER_GONE_ERROR, "MySQL server has gone away", "HY000")) close!(h) - conn.handle = connect(conn.options) + conn.handle = connect(conn.options; db=h.session.schema) invalidate_cursors!(conn) return nothing end