MySQL wire protocol implementation
This page describes how SynergyDB implements the MySQL client/server protocol (protocol version 10, CLIENT_PROTOCOL_41). It is the implementation reference. Scores, connection examples, known gaps and how to re-run the proofs are on the operator page, MySQL. Authentication policy across all wires is in Security, and config keys are in the Configuration reference.
Code lives in src/protocol/mysql/:
| File | Role |
|---|---|
mod.rs |
MySqlHandler: listener, handshake, TLS upgrade, the command loop, text and binary result sets, prepared statements, SQL translation, error mapping, SHOW and DESCRIBE |
auth.rs |
MySqlAuthenticator, MySqlAuthConfig, MySqlAuthPlugin
|
session_vars.rs |
@@system and @user variables, SET parsing, SHOW VARIABLES
|
found_rows.rs |
SQL_CALC_FOUND_ROWS / FOUND_ROWS(), MySQL select modifiers, index hints, the shared tokenizer |
fulltext.rs |
MATCH ... AGAINST rewritten to the engine's full-text functions |
multi_delete.rs |
multiple-table DELETE
|
named_locks.rs |
GET_LOCK, RELEASE_LOCK, IS_FREE_LOCK, IS_USED_LOCK, RELEASE_ALL_LOCKS
|
explain.rs |
MySQL-shaped EXPLAIN output |
Shared pieces: src/protocol/tls.rs (TLS), src/protocol/rate_limiter.rs (per-IP login limiter), src/protocol/buffer_limits.rs and src/protocol/timeout.rs (limits). TLS uses the rustls and tokio-rustls crates (source: Cargo.toml).
1. Listener and connection lifecycle
The server starts the handler when server.mysql_port is set (default 3306). With a resolved [tls] certificate it builds the handler with MySqlHandler::with_tls, otherwise MySqlHandler::with_storage. Neither constructor takes an auth config, so the server always runs with MySqlAuthConfig::default(). Server::start_handler binds the port once before spawning the task, so a port clash fails startup. (source: src/server/mod.rs, the MySQL block of server start-up and Server::start_handler; src/protocol/mysql/mod.rs, MySqlHandler::with_storage, MySqlHandler::with_tls)
Each accepted connection is a tokio::spawned task on the shared runtime. There is no thread-per-connection mode as on PostgreSQL. (source: src/protocol/mysql/mod.rs, MySqlHandler::start)
State shared by every connection of one handler (source: src/protocol/mysql/mod.rs, struct MySqlHandler):
-
txn_manager: one transaction manager, so write conflicts between MySQL sessions are detected. Backed bytest_mysql_sessions_share_write_conflict_detectionandtest_mysql_handler_clone_shares_txn_manager. -
stmt_cache: onePreparedStatementCachefor all connections (section 5). -
auto_increment: anAutoIncrementTracker. It only answersLAST_INSERT_ID()when the handler has no storage; with storage, the per-connection session engine tracks it (source:handle_single_statement,handle_last_insert_id_function).
Per connection, handle_connection:
- Wraps the socket in a 64 KiB
BufWriter. - Sends the Handshake v10 packet (section 2) under
TimeoutConfig::write_timeout. - Reads exactly one packet under
read_timeout. If it is an SSLRequest, upgrades to TLS and reads the HandshakeResponse41 over TLS. - Authenticates (section 3), builds a session
QueryEngine, and enters the command loop (section 4).
When the command loop ends, the connection's MySQL named locks are released (source: src/protocol/mysql/mod.rs, run_session_with_response, the call to release_session_advisory_locks after the loop).
Timeouts
The command loop reads each 4-byte packet header under read_timeout (default 60 s) and breaks out on idle_timeout (default 300 s). Because the header read itself has the 60 s limit, a connection that sends no command for 60 s is closed, well before the 300 s idle timeout and far below the wait_timeout of 28800 that @@wait_timeout reports. The server never calls a setter for TimeoutConfig, so these values are fixed. (source: src/protocol/mysql/mod.rs, the command loop in run_session_with_response; src/protocol/timeout.rs, TimeoutConfig::default; src/protocol/mysql/session_vars.rs, default_value) Not verified: no test covers the idle disconnect.
2. Handshake and capability flags
The server speaks first with a Handshake v10 packet (source: src/protocol/mysql/mod.rs, send_handshake_with_scramble):
| Field | Value |
|---|---|
| protocol version | 10 |
| server version | 8.0.35-SynergyDB |
| connection id | random u32
|
| auth-plugin-data part 1 | first 8 bytes of a 20-byte random scramble, then a filler byte |
| capability flags (lower 2 bytes) | see below |
| character set | 255 (utf8mb4_0900_ai_ci) |
| status flags |
0x0002 (SERVER_STATUS_AUTOCOMMIT) |
| capability flags (upper 2 bytes) | see below |
| auth-plugin-data length | 21 |
| reserved | 10 zero bytes |
| auth-plugin-data part 2 | remaining 12 scramble bytes and a NUL |
| auth plugin name | mysql_native_password |
Capabilities advertised by base_capabilities: CLIENT_LONG_PASSWORD, CLIENT_FOUND_ROWS, CLIENT_LONG_FLAG, CLIENT_CONNECT_WITH_DB, CLIENT_PROTOCOL_41, CLIENT_TRANSACTIONS, CLIENT_SECURE_CONNECTION, CLIENT_MULTI_STATEMENTS, CLIENT_MULTI_RESULTS, CLIENT_PLUGIN_AUTH. CLIENT_SSL is added only when TLS is configured. (source: src/protocol/mysql/mod.rs, base_capabilities)
CLIENT_DEPRECATE_EOF is deliberately not advertised. Result sets are framed with classic EOF packets after the column definitions and after the rows, which is only correct without that flag. (source: src/protocol/mysql/mod.rs, base_capabilities, send_result_set; docs/status/2026-11-24-mysql-classic-eof.md)
The client's capability flags are stored in the session (under an internal variable key) and read later for CLIENT_FOUND_ROWS (source: src/protocol/mysql/mod.rs, CLIENT_CAPS_KEY). The character set byte in the client's HandshakeResponse41 is not read; every connection uses UTF-8 (section 9).
TLS negotiation
handle_connection peeks at the CLIENT_SSL bit of the first client packet (source: src/protocol/mysql/mod.rs, handle_connection):
| Case | Result |
|---|---|
TLS required and the client did not set CLIENT_SSL
|
ERR 1045 Connections using insecure transport are prohibited while require_ssl is enabled.
|
CLIENT_SSL set, TLS configured |
tls_listener.accept performs the rustls handshake; the HandshakeResponse41 is then read over TLS |
CLIENT_SSL set, no TLS configured |
ERR 1045 Server is not configured for TLS.
|
no CLIENT_SSL, TLS not required |
plaintext session |
"TLS required" means MySqlAuthConfig::require_ssl (always false, because the server uses the default config) or [tls] require_tls with a non-loopback peer. Loopback peers may stay in plaintext under require_tls. (source: src/protocol/mysql/mod.rs, handle_connection; src/protocol/tls.rs; docs/status/2026-11-30-tls-remaining-wires.md)
After an SSLRequest the auth reply uses sequence id 3. Backed by auth_reply_after_ssl_request_uses_sequence_three in src/protocol/mysql/mod.rs.
TlsConfig::min_version is not applied, so the protocol versions are the rustls defaults (TLS 1.2 and 1.3). Not wired: a configured minimum TLS version. (source: src/protocol/tls.rs)
3. Authentication
run_session_with_response parses the HandshakeResponse41 (source: src/protocol/mysql/mod.rs, run_session_with_response):
- Username: NUL-terminated string at offset 36.
- Auth response: length-prefixed when
CLIENT_SECURE_CONNECTIONis set, else NUL-terminated. - Database: NUL-terminated string when
CLIENT_CONNECT_WITH_DBis set. - The reply's sequence id is the client's plus one.
It then calls MySqlAuthenticator::verify_auth_response and records the attempt with audit::record_login.
Message sequence
S: Handshake v10 (scramble, plugin mysql_native_password)
C: [SSLRequest -> TLS handshake]
C: HandshakeResponse41 (user, SHA1 scramble response, [database])
S: OK login accepted
or ERR 1045/1820/... login refused, connection closed
or ERR 1049 unknown database, connection closed
There is no AuthSwitchRequest and no AuthMoreData exchange. (source: src/protocol/mysql/mod.rs, run_session_with_response; src/protocol/mysql/auth.rs)
Plugins
| Plugin | Status |
|---|---|
mysql_native_password |
The default and the only one the server uses. |
caching_sha2_password |
Implemented in MySqlAuthenticator, but selectable only through MySqlHandler::with_tls_and_auth_config, which the server never calls. Not wired.
|
(source: src/protocol/mysql/auth.rs, MySqlAuthPlugin, MySqlAuthConfig::default; src/server/mod.rs)
@@default_authentication_plugin reports caching_sha2_password, which is not the plugin the server offers (source: src/protocol/mysql/session_vars.rs, default_value).
Native password verification
verify_auth_response (source: src/protocol/mysql/auth.rs, MySqlAuthenticator::verify_auth_response):
-
Per-IP rate limit.
global_auth_rate_limiter().check_allowed(ip). When the IP is locked out the reply is ERR 1045Too many authentication attempts, try again in N seconds. Successes and failures are recorded per IP. The limiter allows 100 attempts per 60 s window and locks out for 60 s (source:src/protocol/rate_limiter.rs). The MySQL wire does not call the shared failed-login brakewire_auth::note_auth_resultthat PostgreSQL uses. -
Role lookup in the catalog. A role without
rolcanloginis refused. A role whoserolvaliduntilhas passed gets ERR 1820 (ER_PASSWORD_EXPIRED). -
Verifier. The expected hash is the catalog's MySQL side record (
get_mysql_native_hash, the*HEX(SHA1(SHA1(password)))form), or a stored password that is already a 41-character*-prefixed native hash. The client response is checked against the scramble in the standard native-password way. - Role with no password. An empty client response logs in. PostgreSQL does not allow this.
-
Argon2-only role. A role that has only an Argon2 hash and no native side record cannot be checked against a SHA1 scramble. With
SYNERGYDB_DEV_INSECURE_AUTHset, the authenticator probes candidate passwords; otherwise login fails. -
Unknown user. ERR 1045 unless
SYNERGYDB_DEV_INSECURE_AUTHis set, in which case a hardcoded development user list inauth.rsis consulted. That list is a development aid; its values are not reproduced here. Backed bytest_default_secure_rejects_legacy_and_unknown_users.
Error codes used by the authenticator: 1045 ER_ACCESS_DENIED, 1044 ER_DBACCESS_DENIED, 1820 ER_PASSWORD_EXPIRED, 1449 ER_NO_SUCH_USER (source: src/protocol/mysql/auth.rs, error_codes).
After login
If a database was given, mysql_database_usable checks that it exists and is connectable; otherwise ERR 1049 Unknown database '<db>'. An empty name or default is always usable. On success the server sends OK, builds an AuthenticatedSession from the catalog role, and creates the session engine with build_session_engine, which turns on the engine's MySQL dialect (section 6). (source: src/protocol/mysql/mod.rs, run_session_with_response, mysql_database_usable, build_session_engine) Backed by use_of_unknown_database_is_refused_not_created.
4. Command dispatch
Each packet is a 4-byte header (3-byte little-endian length, 1-byte sequence id) and a payload whose first byte is the command. A zero-length packet is skipped. (source: src/protocol/mysql/mod.rs, the command loop in run_session_with_response)
| Byte | Command | Handling |
|---|---|---|
0x01 |
COM_QUIT |
Ends the loop. |
0x02 |
COM_INIT_DB |
mysql_database_usable; ERR 1049 if not, else sets the session database and sends OK. |
0x03 |
COM_QUERY |
Text protocol (section 6). |
0x04 |
COM_FIELD_LIST |
Always ERR 1146 Table '<t>' doesn't exist. Not wired.
|
0x0e |
COM_PING |
OK. |
0x11 |
COM_CHANGE_USER |
ERR 1227 asking the client to reconnect. Not wired. |
0x16 |
COM_STMT_PREPARE |
Section 5. |
0x17 |
COM_STMT_EXECUTE |
Section 5. |
0x18 |
COM_STMT_SEND_LONG_DATA |
Read and ignored; no response. Long data is not appended to the parameter. Not wired. |
0x19 |
COM_STMT_CLOSE |
Removes the statement from the cache; no response, as the protocol requires. |
0x1a |
COM_STMT_RESET |
OK if the statement exists, else ERR 1243 Unknown prepared statement handler. |
0x1b |
COM_SET_OPTION |
OK. Multi-statement support is always on, so the option changes nothing. |
0x1c |
COM_STMT_FETCH |
ERR 1235 Cursors are not supported. Not wired.
|
0x1f |
COM_RESET_CONNECTION |
OK. Session variables, user variables and temporary tables are not reset. Not wired: the reset itself. |
| other | ERR 1047 Unknown command. |
(source: src/protocol/mysql/mod.rs, the match command in run_session_with_response)
No code joins a maximum-size packet (0xFFFFFF bytes) with its continuation packets, so a single command payload is limited to 16 MiB minus one byte. Not wired: multi-packet payloads. (source: src/protocol/mysql/mod.rs, the command loop and read_packet)
Packet layouts the server writes (source: src/protocol/mysql/mod.rs, send_ok, send_ok_with_info, send_error, send_eof):
-
OK:
0x00, affected rows (length-encoded), last insert id (length-encoded), status flags (2 bytes), warnings (2 bytes). -
ERR:
0xFF, errno (2 bytes LE),#, 5-character SQLSTATE, message. -
EOF:
0xFE, warnings (2 bytes), status flags (2 bytes).
5. Prepared statements and the binary protocol
COM_STMT_PREPARE
handle_stmt_prepare (source: src/protocol/mysql/mod.rs, handle_stmt_prepare, PreparedStatement::new, PreparedStatementCache::prepare):
- The parameter count is the number of
?characters in the SQL text. This includes a?inside a string literal, although parameter substitution skips literals (see below). - For a statement starting with
SELECT, the column metadata is found by running<sql with every ? replaced by NULL> LIMIT 0on a newQueryEnginebuilt from the handler's storage, not on the session engine, and without MySQL-to-engine translation. If that probe fails, the statement is prepared with zero columns. - Statement ids come from one counter shared by all connections, starting at 1.
- Response:
COM_STMT_PREPARE_OK(status0x00, statement id, column count, parameter count, filler, warning count), then one parameter definition per parameter and an EOF, then one column definition per column and an EOF.
Every parameter definition is named ? with type MYSQL_TYPE_VAR_STRING, charset 255 and length 65535 (source: build_parameter_definition).
Because the cache is shared and statements are removed only by COM_STMT_CLOSE, a statement prepared by a connection that disconnects without closing it stays in memory, and its id can be executed from any other connection. (source: src/protocol/mysql/mod.rs, stmt_cache, the COM_STMT_CLOSE arm) Not verified: no test covers either behaviour.
COM_STMT_EXECUTE
handle_stmt_execute (source: src/protocol/mysql/mod.rs, handle_stmt_execute, parse_bound_parameters, parse_binary_value, int_bound_params, substitute_parameters):
- A payload under 9 bytes gets ERR 1210
Malformed COM_STMT_EXECUTE packet. The flags byte and iteration count are read and ignored. - An unknown statement id gets ERR 1243.
- Parameters are decoded from the NULL bitmap, the new-params-bound flag and the type list. Types sent on the first execute are stored with
update_param_typesand reused when a later execute omits them. A decode error gets ERR 1210Incorrect arguments to mysqld_stmt_execute. - Each value becomes a SQL literal: integers and floats as numbers, strings and decimals as escaped string literals (bytes that are not UTF-8 become
UNHEX(...)),DATE/DATETIME/TIMESTAMPas'YYYY-MM-DD[ HH:MM:SS]',TIMEas'HH:MM:SS',NULLasNULL. Microseconds and negative times are not carried. -
Integer fast path. For a
SELECTwhose parameters are all integers (up to 18 digits) or NULL, and which does not use named locks,SQL_CALC_FOUND_ROWS,MATCH,INTERVALor$, the?marks become$1..$nand the values are bound as real engine parameters. Otherwise every?outside a string literal is replaced by its literal text. Either way the engine sees SQL text, not a server-side plan. - The result goes through the same translation steps as the text protocol (section 6), except that
SET,SHOW,DESCRIBE,@@variable substitution, multi-tableDELETEand the implicit-commit rules apply only on the text path.
Results are sent as a binary result set (send_binary_result_set): column count, column definitions, EOF, binary rows (header 0x00, NULL bitmap with offset 2, values), EOF. encode_binary_value writes:
| Column type | Binary encoding |
|---|---|
TINY (0x01) |
1 byte |
SHORT (0x02) |
2 bytes LE |
LONG (0x03), INT24 (0x09) |
4 bytes LE |
LONGLONG (0x08) |
8 bytes LE |
FLOAT (0x04) |
4-byte IEEE |
DOUBLE (0x05) |
8-byte IEEE |
DATE (0x0a) |
length byte and year, month, day |
DATETIME (0x0c), TIMESTAMP (0x07) |
length byte and date, time, optional microseconds |
TIME (0x0b) |
length byte, sign, days, hours, minutes, seconds |
| everything else | length-encoded string |
(source: src/protocol/mysql/mod.rs, encode_binary_value)
Tests: the PreparedStatementCache unit tests in tests/protocol_mysql.rs (cache_new, prepare_multiple_params, statement_ids_increment, close_prepared_statement, update_param_types and others) check the cache only. Decoding is backed by test_binary_lenenc_string_length_overflow_is_error, test_binary_lenenc_default_branch_overflow_is_null_not_panic, test_binary_lenenc_string_valid_still_parses and test_mysql_binary_uuid_hex_unhex_roundtrip. The live ps phase of the MySQL differential harness exercises COM_STMT_PREPARE/EXECUTE with mysql-connector-python (source: docs/status/2026-11-24-mysql-binary-protocol-ps.md). In the 2026-11-30 proof pack that phase was skipped because mysql-connector-python was not installed (source: docs/proof/2026-11-30/proof-pack-a3232c9/logs/mysql-corpus-second-connection-restart.txt). Not verified by the current proof pack: the binary protocol.
6. Text protocol: from COM_QUERY to the engine
Statement splitting
COM_QUERY decodes the payload with mysql_query_text. Valid UTF-8 is used as is. Otherwise each quoted literal that is not valid UTF-8 becomes UNHEX('...'), so binary data survives. The text is checked against the query length limit, then handle_query splits it with split_sql_statements (which honours backslash escapes and quotes) and drops comment-only pieces. Executable comments such as /*!40101 ... */ are kept as statements. (source: src/protocol/mysql/mod.rs, mysql_query_text, handle_query, split_sql_statements) Backed by test_split_honors_backslash_escapes_with_semicolon_in_string, test_comment_only_statement_is_filtered, mysqldump_statement_shapes.
With several statements, each result set except the last carries SERVER_MORE_RESULTS_EXISTS, sequence ids continue across results, and the first error stops the batch. (source: handle_query)
Per-statement order
handle_single_statement processes each statement in this order (source: src/protocol/mysql/mod.rs, handle_single_statement):
- Empty statement: OK.
- Status flags:
SERVER_STATUS_AUTOCOMMITunlesssession_vars::autocommit_off, plusSERVER_STATUS_IN_TRANSinside a transaction. -
SET ...:apply_set(section 8). -
SELECT @@VERSION_COMMENT LIMIT 1: answersSynergyDB(themysqlcommand-line client sends this on connect). -
SELECT @@...without a session engine:handle_session_variable. -
LAST_INSERT_ID()without a session engine: the handler's tracker. - Backup statements (
handle_dump_admin):LOCK TABLES,UNLOCK TABLES,LOCK INSTANCE FOR BACKUP,UNLOCK INSTANCE,FLUSH ...andALTER TABLE ... DISABLE|ENABLE KEYSreply OK and take no lock.UNLOCK TABLESdoes not commit. -
SHOWandDESCRIBEforms (section 7). -
db.tablerouting: when every database-qualified name points at the same other database, the statement runs in that database with the qualifier removed (route_qualified_database). -
translate_mysql_sql(below). - Database scoping: an empty or
defaultdatabase means thepostgresnamespace. -
session_vars::substitute:@@sysvarand@uservarreferences become literals. An unknown system variable is ERR 1193. -
found_rows::strip_index_hints:USE|FORCE|IGNORE INDEX (...)removed. -
fulltext::rewrite:MATCH (cols) AGAINST ('q' [mode])becomesto_tsvector('simple', ...) @@ to_tsquery('simple', ...)in predicate position and ats_rankvalue elsewhere. Stopwords and minimum token length are not applied. -
mysql_lock_calls:GET_LOCK,RELEASE_LOCK,IS_FREE_LOCK,IS_USED_LOCK,RELEASE_ALL_LOCKSwith literal arguments are evaluated against the engine's named-lock state and replaced by their values. -
DO expr, ...: evaluated as aSELECT, answered with OK. -
found_rows::plan: stripsSQL_CALC_FOUND_ROWS,SQL_NO_CACHE,HIGH_PRIORITY,STRAIGHT_JOIN,SQL_SMALL_RESULT,SQL_BIG_RESULT,SQL_BUFFER_RESULTand similar modifiers, substitutes the currentFOUND_ROWS()value, and forSQL_CALC_FOUND_ROWS ... LIMITalso runs a count without the top-level LIMIT. - Transaction class (
mysql_txn_class):CREATE,DROP(notTEMPORARY),ALTER,TRUNCATE,RENAME,GRANT,REVOKE,LOCK,UNLOCKcommit an open transaction first, as MySQL does. Withautocommit=0, a data statement outside a transaction opens one implicitly. -
multi_delete:DELETE t1, t2 FROM ...andDELETE FROM t1, t2 USING ...run as oneSELECT DISTINCT <primary key>per target over the full join, then one keyedDELETEper target. - The statement runs on the session engine through
PostgresHandler::run_engine(inline orblock_in_place, as on the PostgreSQL wire). -
explain::mysql_explain: forEXPLAIN [FORMAT=TRADITIONAL] <dml>, the engine's one-column plan becomes MySQL's 12-column table. Row estimates are the engine's.
Tests: strips_index_hints, calc_strips_modifier_and_limit, union_counts_whole_union and four more in found_rows.rs; boolean_queries, rewrites_predicate_and_rank in fulltext.rs; rewrites_lock_calls in named_locks.rs; do_statement_runs_as_select; wordpress_transient_purge, using_form_and_aliases and three more in multi_delete.rs; which_statements, converts_plans in explain.rs.
translate_mysql_sql
The MySQL-to-engine rewrite is textual (source: src/protocol/mysql/mod.rs, translate_mysql_sql):
| MySQL | Engine SQL |
|---|---|
`ident` |
"ident" |
"string" (ANSI_QUOTES off) |
'string' |
backslash escapes in strings (\n, \', \\, \0 …) |
decoded once |
X'..', 0x.., _binary '..'
|
string literal or UNHEX('..')
|
AS 'alias' |
AS "alias" |
Backed by test_translate_mysql_double_quoted_strings, test_translate_mysql_quoted_alias, test_translate_mysql_hex_literal, test_mysql_backslash_escapes_decoded_once.
The engine's MySQL dialect
build_session_engine calls QueryEngine::set_mysql_dialect(true). The flag changes expression semantics in the shared engine: / always returns a decimal, division or modulo by zero returns NULL, CONCAT returns NULL when any argument is NULL, GREATEST/LEAST return NULL when any argument is NULL, and ^ is bitwise XOR. String equality ignores case in a MySQL session. (source: src/query/engine.rs, the mysql_dialect field; docs/status/2026-11-27-mysql-varchar-pk-lookups.md) MySQL functions live in src/query/mysql_funcs.rs.
SET sql_mode sets two more engine flags: strict mode when the value contains STRICT_TRANS_TABLES, STRICT_ALL_TABLES or TRADITIONAL, and ONLY_FULL_GROUP_BY checking when it contains that word (source: src/protocol/mysql/mod.rs, apply_set).
Result packets
| Engine result | Reply |
|---|---|
Select |
text result set: column count, column definitions, EOF, rows, EOF |
Insert |
OK with affected rows and the statement's first generated id |
Update |
OK. With CLIENT_FOUND_ROWS the matched-row count, else the changed-row count (update_changed_rows) |
Delete |
OK with the count |
TRUNCATE |
OK with 0, and the table's AUTO_INCREMENT restarts |
CREATE DATABASE |
OK with 1 |
Begin / Commit / Rollback
|
OK; sets or clears SERVER_STATUS_IN_TRANS
|
| DDL | OK |
(source: src/protocol/mysql/mod.rs, handle_single_statement)
AUTO_INCREMENT counters durably record every value handed out, so after a crash the next id is the last one plus one (source: docs/status/2026-11-24-mysql-autoinc-crash-exact.md).
7. SHOW and DESCRIBE
| Statement | Answer | Source |
|---|---|---|
SHOW [FULL] {COLUMNS\|FIELDS} FROM t [LIKE ...], DESCRIBE t [col], DESC t
|
real types, nullability, keys, defaults and auto_increment from the catalog |
handle_show_columns, handle_describe
|
SHOW CREATE TABLE t, SHOW CREATE VIEW v
|
DDL rebuilt from the catalog; ERR 1146 if missing | handle_single_statement |
SHOW CREATE {DATABASE\|SCHEMA} [IF NOT EXISTS] db |
CREATE DATABASE text |
handle_dump_admin |
SHOW [SESSION\|GLOBAL\|LOCAL] VARIABLES [LIKE ...] |
every variable session_vars knows, with session overrides |
session_vars::show_variables |
SHOW TABLE STATUS [FROM db] [LIKE ...] |
one row per table | handle_dump_admin |
SHOW TRIGGERS, SHOW {PROCEDURE\|FUNCTION} STATUS, SHOW EVENTS
|
correct columns, no rows | handle_dump_admin |
SHOW DATABASES |
information_schema, mysql, performance_schema, sys, plus every registered database |
handle_show |
SHOW [FULL] TABLES [FROM db] [LIKE ... \| WHERE ...] |
catalog tables, filtered | handle_show |
SHOW {INDEX\|INDEXES\|KEYS} FROM t |
15-column rows from the same catalog pg_indexes reads |
handle_show, show_index_rows
|
SHOW STATUS |
two constant rows: Uptime 1000 and Threads_connected 1 |
handle_show |
SHOW WARNINGS |
always empty | handle_show |
SHOW COLLATION |
one row: utf8mb4_general_ci
|
handle_show |
any other SHOW
|
OK packet, no result set | handle_show |
(source: src/protocol/mysql/mod.rs, the named functions) Backed by test_mysql_show_columns_and_describe and show_tables_parses_like_where_full_and_from. SHOW STATUS, SHOW WARNINGS and SHOW COLLATION return placeholder data; no warnings are ever recorded.
8. Session variables
Variables are kept per connection in SessionContext::variables, system variables under @@name and user variables under @name. They are substituted into statements as literals, so the engine evaluates the expression around them. (source: src/protocol/mysql/session_vars.rs, module doc, substitute, sysvar_literal)
Lookup order for @@name: version (the server version), last_insert_id/identity, timestamp (current Unix time), then the session value, then default_value. A name not in the table reads as an empty string if it starts with a known MySQL prefix (innodb_, performance_schema_, sql_, max_, net_ and others), and is ERR 1193 otherwise. The 5.7 names tx_isolation, tx_read_only and storage_engine are aliases. Numeric variables are substituted unquoted. (source: src/protocol/mysql/session_vars.rs, sysvar_literal, is_plausible_unlisted, is_numeric_var)
Selected defaults (source: src/protocol/mysql/session_vars.rs, default_value):
| Variable | Default |
|---|---|
autocommit |
1 |
version_comment |
SynergyDB |
character_set_client, _connection, _results, _server, _database
|
utf8mb4 |
collation_connection, _server, _database
|
utf8mb4_0900_ai_ci |
sql_mode |
ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION |
transaction_isolation |
REPEATABLE-READ |
max_allowed_packet |
67108864 |
wait_timeout, interactive_timeout
|
28800 |
time_zone / system_time_zone
|
SYSTEM / UTC |
lower_case_table_names |
0 |
innodb_lock_wait_timeout |
50 |
max_connections |
151 |
port |
3306 |
default_authentication_plugin |
caching_sha2_password |
have_ssl |
YES |
tls_version |
TLSv1.2,TLSv1.3 |
max_allowed_packet, max_connections, port, wait_timeout, have_ssl and default_authentication_plugin are fixed strings; they do not read the server's configuration or limits.
SET
session_vars::parse_set and MySqlHandler::apply_set handle (source: src/protocol/mysql/session_vars.rs, parse_set; src/protocol/mysql/mod.rs, apply_set):
| Form | Effect |
|---|---|
SET NAMES ..., SET CHARACTER SET ..., SET CHARSET ..., SET PASSWORD ..., SET ROLE ..., SET DEFAULT ROLE ...
|
accepted and ignored |
SET [SESSION] TRANSACTION ISOLATION LEVEL ... |
engine.set_mysql_session_isolation |
SET GLOBAL TRANSACTION ... |
accepted and ignored |
SET [SESSION\|LOCAL\|GLOBAL\|PERSIST\|PERSIST_ONLY] name = value |
stored per session; GLOBAL and PERSIST do not reach other connections |
SET @user = expr |
expr evaluated by the engine, stored as a literal |
System variables with an effect on the engine:
| Variable | Effect |
|---|---|
autocommit |
0 makes data statements open implicit transactions; 1 inside a transaction commits it |
transaction_isolation, tx_isolation
|
session isolation level |
foreign_key_checks |
0/OFF/FALSE turns foreign key checks off (mysqldump sets this) |
innodb_lock_wait_timeout |
engine lock wait timeout in seconds |
sql_mode |
strict mode and ONLY_FULL_GROUP_BY flags |
An expression value such as CONCAT(@@sql_mode, ',X') is evaluated by the engine. Backed by set_with_caller_comment, substitutes_and_aliases_select_items, parses_set_forms in session_vars.rs.
9. Character sets
Every connection is UTF-8. The handshake offers charset 255, the client's charset byte is ignored, and SET NAMES is ignored. Column-level CHARACTER SET and COLLATE clauses in DDL are accepted, and text is always stored as UTF-8. (source: src/protocol/mysql/mod.rs, send_handshake_with_scramble, run_session_with_response; src/protocol/mysql/session_vars.rs, parse_set; docs/status/2026-11-24-mysql-column-charset.md)
In column definitions, text columns use charset 255 and numeric, temporal, JSON and binary columns use charset 63 (binary), as MySQL does (source: src/protocol/mysql/mod.rs, build_column_definition_typed).
10. Type mapping
Column type chosen for a result column
effective_mysql_type picks the column type in this order (source: src/protocol/mysql/mod.rs, effective_mysql_type, declared_mysql_type, pg_type_to_mysql):
- A table column with a declared MySQL type reports that type (
declared_mysql_type), unless it isUNSIGNED. - Otherwise the engine type OID is mapped by
pg_type_to_mysql. -
BLOB(frombytea) is never re-typed. -
VARCHAR,CHAR,"char"andnameOIDs (1043, 1042, 18, 19) stayVAR_STRING. - For other generic string columns, the first non-empty value is checked for a temporal shape (
sniff_temporal_mysql_type). - If every non-null value is a canonical integer the column is
LONGLONG; if every value is a canonical integer or decimal it isNEWDECIMAL. Text such as007or1e3stays a string.
Declared types (declared_mysql_type):
| Declared | Wire type |
|---|---|
TINYINT, BOOL, BOOLEAN
|
TINY (0x01) |
SMALLINT |
SHORT (0x02) |
MEDIUMINT |
INT24 (0x09) |
INT, INTEGER
|
LONG (0x03) |
BIGINT |
LONGLONG (0x08) |
FLOAT |
FLOAT (0x04) |
DOUBLE, REAL
|
DOUBLE (0x05) |
TINYTEXT, TEXT
|
BLOB (0xfc), charset 255, length 262140, BLOB_FLAG
|
MEDIUMTEXT |
MEDIUM_BLOB (0xfa), length 67108860 |
LONGTEXT |
LONG_BLOB (0xfb), length 4294967295 |
CHAR |
STRING (0xfe) |
Engine OIDs (pg_type_to_mysql):
| Engine type (OID) | Wire type |
|---|---|
bool (16) |
LONGLONG (0x08); MySQL boolean expressions are BIGINT 1/0 |
int2 (21) |
SHORT (0x02) |
int4 (23) |
LONG (0x03) |
int8 (20) |
LONGLONG (0x08) |
float4 (700) |
FLOAT (0x04) |
float8 (701) |
DOUBLE (0x05) |
varchar (1043), text (25) |
VAR_STRING (0xfd) |
date (1082) |
DATE (0x0a) |
time (1083) |
TIME (0x0b) |
timestamp (1114), timestamptz (1184) |
DATETIME (0x0c) |
bytea (17) |
BLOB (0xfc), BLOB_FLAG \| BINARY_FLAG
|
numeric (1700) |
NEWDECIMAL (0xf6) |
json (114), jsonb (3802) |
JSON (0xf5) |
| anything else |
VAR_STRING (0xfd) |
Column definition fields
Catalog is def; schema, table and original table are empty strings; name and original name are the column name. Lengths: DATETIME/TIMESTAMP 19, DATE 10, TIME 8, otherwise the engine's type size or 255. Temporal columns carry BINARY_FLAG (0x0080). Decimals is always 0. (source: src/protocol/mysql/mod.rs, build_column_definition_typed) Clients that read the table name from column metadata get an empty string.
Text row values
build_text_row_typed rewrites values for the advertised type: ISO timestamps such as 1990-02-06T23:04:56Z become 1990-02-06 23:04:56; engine booleans t/f in integer columns become 1/0; JSON is reformatted to MySQL's spacing and key order (mysql_funcs::normalize_json_text). NULL is 0xFB. (source: src/protocol/mysql/mod.rs, build_text_row_typed, mysql_bool_text, normalize_temporal) Backed by test_mysql_bool_text_coercion, test_text_row_coerces_bool_for_integer_columns, test_mysql_binary_bytes_on_the_wire.
The MySQL differential harness compares each result column's wire type with MySQL 8.0's (source: docs/status/2026-11-30-mysql-diff-column-types.md).
11. Error mapping
Engine errors are mapped to an errno by message text in mysql_errno_for_error, checked in this order (source: src/protocol/mysql/mod.rs, mysql_errno_for_error):
| Message contains | errno |
|---|---|
deadlock, could not serialize, serialization failure, write conflict
|
1213 |
lock timeout, lock wait timeout
|
1205 |
table not found, no such table, doesn't exist, unknown table
|
1146 |
database and already exists
|
1007 |
already exists |
1050 |
duplicate entry, duplicate key, unique constraint
|
1062 |
unknown column, column not found
|
1054 |
doesn't have a default value |
1364 |
violates not-null |
1048 |
violates check |
3819 |
value too long, data too long
|
1406 |
invalid input syntax for type integer, incorrect integer value
|
1366 |
more than one row returned by a subquery |
1242 |
is ambiguous |
1052 |
aggregated query without group by |
1140 |
is not in group by clause |
1055 |
out of range |
1264 |
| anything else | 1064 |
Errors 1213 and 1205 are sent with InnoDB's exact message text. The SQLSTATE comes from mysql_sqlstate (source: src/protocol/mysql/mod.rs, mysql_sqlstate, send_error):
| errno | SQLSTATE |
|---|---|
| 1213 | 40001 |
| 1062, 1048, 1451, 1452, 1052 | 23000 |
| 1406 | 22001 |
| 1264 | 22003 |
| 1146 | 42S02 |
| 1050 | 42S01 |
| 1054 | 42S22 |
| 1045 | 28000 |
| 1242 | 21000 |
| 1049 | 42000 |
| 1205, 1210, 1243, 1366, 3819, 1007 | HY000 |
| anything else | 42000 |
Other errnos the wire sends directly: 1047 unknown command, 1049 unknown database, 1146 from COM_FIELD_LIST and SHOW CREATE, 1193 unknown system variable, 1210 malformed execute, 1227 COM_CHANGE_USER, 1235 cursor fetch, 1243 unknown statement, 1045/1820 login, and ER_BAD_TABLE_ERROR for DROP TABLE of a missing table. Backed by check_constraint_violation_errno.
Because the mapping is by substring, an engine message that happens to contain one of these phrases gets that errno. Not verified: no test covers the table as a whole.
12. Limits and config
| Setting | Value | Where |
|---|---|---|
server.mysql_port |
3306 |
[server] config |
[tls], require_tls / SYNERGYDB_TLS_REQUIRE_TLS
|
off | src/protocol/tls.rs |
SYNERGYDB_DEV_INSECURE_AUTH |
off | src/protocol/mysql/auth.rs |
| max message size | 256 MiB, ERR 1153 | BufferLimits::default |
| max query length | 16 MiB, ERR 1162 | BufferLimits::default |
| max parameters | 65535; ERR 1390 is mapped but the MySQL wire never calls the parameter check |
BufferLimits::default, send_buffer_limit_error
|
| connect / read / write / idle timeout | 30 s / 60 s / 60 s / 300 s | TimeoutConfig::default |
| per-IP login limit | 100 attempts per 60 s, 60 s lockout | src/protocol/rate_limiter.rs |
| reported server version |
8.0.35-SynergyDB, MYSQL_VERSION_ID 80035 for /*!NNNNN */ comments |
MySqlHandler, session_vars.rs
|
A single MySQL packet carries at most 16 MiB minus one byte and continuation packets are not joined, so neither the 256 MiB message limit nor the 16 MiB query limit can be reached. The server never calls with_buffer_limits or a timeout setter, so the limits are not configurable. (source: src/protocol/mysql/mod.rs, command loop; src/protocol/buffer_limits.rs; src/server/mod.rs)
13. Tests and evidence
| Test or suite | What it covers |
|---|---|
tests/protocol_mysql.rs (37 tests) |
PreparedStatementCache lifecycle and parameter counting, SQL on a QueryEngine (DDL, DML, WHERE, joins, aggregates, LIMIT), handler construction, error cases. No socket is opened, so no wire bytes are checked. |
unit tests in src/protocol/mysql/
|
mod.rs 28, found_rows.rs 7, multi_delete.rs 5, auth.rs 4, session_vars.rs 3, fulltext.rs 2, explain.rs 2, named_locks.rs 1. Named throughout this page. |
tests/protocol_coverage.rs, wire_protocol_width_and_depth
|
counts how many COM_* opcode names appear in mod.rs and auth.rs; a source-text scan, not a behaviour test |
test-scripts/wire-matrix/mysql_matrix.py |
pymysql feature matrix against MySQL 8: aggregates 12, control flow 11, dates 22, DML 19, errors 14, grouping 9, joins 7, JSON 35, math 16, metadata 13, query 18, strings 27, types 11, windows 10 |
MySQL differential harness (diff-mysql/diff_mysql.py) |
query corpus diffed against MySQL 8, a second-connection phase, a restart phase and a prepared-statement phase. Run by prove/wires.py. |
docs/proof/2026-11-30/proof-pack-a3232c9/logs/mysql-corpus-second-connection-restart.txt |
output of the harness above; the prepared-statement phase was skipped |
docs/proof/2026-11-30/proof-pack-a3232c9/logs/mysql-feature-matrix.txt |
output of mysql_matrix.py
|
tests/wire_preauth_gate.rs does not cover the MySQL wire. The differential harness directory test-scripts/diff-mysql/ is referenced by prove/wires.py, prove/README.md and the status entries but is not present in the source tree this page was written from.
Status entries for this wire: 2026-11-24-mysql-binary-protocol-ps, 2026-11-24-mysql-classic-eof, 2026-11-24-mysql-column-charset, 2026-11-24-mysql-do-statement, 2026-11-24-mysql-autoinc-crash-exact, 2026-11-24-mysql-point-select-handoff, 2026-11-27-mysql-varchar-pk-lookups, 2026-11-30-mysql-diff-column-types, 2026-11-30-mysql-row-alias-rollup-order (all in docs/status/).