Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/src/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
1 change: 1 addition & 0 deletions src/Protocol/auth.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions src/Protocol/commands.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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")))
Expand Down
17 changes: 15 additions & 2 deletions src/Protocol/session.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -18,6 +20,7 @@ mutable struct Session
capabilities::UInt64
server::Union{Nothing, ServerInfo}
status::UInt16
schema::String
generation::Int
authenticated::Bool
command_kind::CommandKind
Expand All @@ -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)
Expand Down Expand Up @@ -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[])
Expand Down
16 changes: 9 additions & 7 deletions src/connect.jl
Original file line number Diff line number Diff line change
Expand Up @@ -297,26 +297,28 @@ 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)
secure = P.starttls!(s, opts.tls, opts.host; handshake_timeout_ns=deadline == 0 ? 0 : remaining_ns(deadline))
(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
Expand Down
10 changes: 6 additions & 4 deletions src/connection.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
49 changes: 49 additions & 0 deletions test/protocol/cursor_tests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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) : "<none>")
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 == ["<none>", "other", "<none>"]
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).
Expand Down
Loading