feat(mcp): add native MySQL session transactions
This commit is contained in:
1 parent
01bd07bb97
commit
1294708eea
27 files changed
+5621
-91
No files matched your search
@@ -1,6 +1,6 @@
|
||||
use chrono::{NaiveDate, NaiveDateTime, NaiveTime};
|
||||
use futures::StreamExt;
|
||||
use mysql_async::consts::{ColumnFlags, ColumnType};
|
||||
use mysql_async::consts::{ColumnFlags, ColumnType, StatusFlags};
|
||||
use mysql_async::prelude::*;
|
||||
use percent_encoding::percent_decode_str;
|
||||
use rust_decimal::Decimal;
|
||||
@@ -191,6 +191,47 @@ pub struct MySqlQueryResult {
|
||||
pub large_value_cells: Vec<LargeValueCell>,
|
||||
}
|
||||
|
||||
/// Result of one MCP fixed-session statement executed through MySQL's text
|
||||
/// protocol. The transaction bit comes from the final server OK/EOF packet,
|
||||
/// never from SQL text or client-side state inference.
|
||||
#[derive(Debug)]
|
||||
pub struct MySqlTransactionExecution {
|
||||
pub result: QueryResult,
|
||||
pub in_transaction: bool,
|
||||
}
|
||||
|
||||
/// Error classification retained by the fixed-session owner. Server errors
|
||||
/// are recoverable protocol responses; every other driver error means the
|
||||
/// connection state cannot be trusted or replayed.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum MySqlTransactionError {
|
||||
Server { code: u16, message: String, state: String },
|
||||
Transport(String),
|
||||
}
|
||||
|
||||
fn transaction_error_from_mysql_error(error: mysql_async::Error) -> MySqlTransactionError {
|
||||
match error {
|
||||
mysql_async::Error::Server(error) => {
|
||||
MySqlTransactionError::Server { code: error.code, message: error.message, state: error.state }
|
||||
}
|
||||
error => MySqlTransactionError::Transport(error.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn transaction_status_from_last_ok(conn: &mysql_async::Conn) -> Result<bool, MySqlTransactionError> {
|
||||
conn.last_ok_packet()
|
||||
.map(|packet| packet.status_flags().contains(StatusFlags::SERVER_STATUS_IN_TRANS))
|
||||
.ok_or_else(|| MySqlTransactionError::Transport("MySQL did not return a final status packet".to_string()))
|
||||
}
|
||||
|
||||
/// Read transaction state after a recoverable server ERR packet. mysql_async
|
||||
/// intentionally clears the cached OK packet for ERR, so COM_PING is required
|
||||
/// to obtain fresh status from the same physical connection.
|
||||
pub async fn ping_transaction_status_on_conn(conn: &mut mysql_async::Conn) -> Result<bool, MySqlTransactionError> {
|
||||
conn.ping().await.map_err(transaction_error_from_mysql_error)?;
|
||||
transaction_status_from_last_ok(conn)
|
||||
}
|
||||
|
||||
impl MySqlQueryResult {
|
||||
fn exact(result: QueryResult) -> Self {
|
||||
Self { result, large_value_cells: Vec::new() }
|
||||
@@ -5274,6 +5315,79 @@ pub async fn execute_query_on_conn_with_max_rows(
|
||||
.map(|result| result.result)
|
||||
}
|
||||
|
||||
/// Execute exactly one policy-approved MCP transaction statement using
|
||||
/// COM_QUERY/text protocol. This path never retries, rewrites or replays user
|
||||
/// SQL. It fully drains the result before exposing the final server status.
|
||||
pub async fn execute_transaction_statement_on_conn(
|
||||
conn: &mut mysql_async::Conn,
|
||||
sql: &str,
|
||||
max_rows: Option<usize>,
|
||||
) -> Result<MySqlTransactionExecution, MySqlTransactionError> {
|
||||
let started_at = Instant::now();
|
||||
let row_limit = query_result_row_limit(max_rows);
|
||||
let mut query = conn.query_iter(sql).await.map_err(transaction_error_from_mysql_error)?;
|
||||
let columns: Vec<String> = query.columns_ref().iter().map(|column| column.name_str().to_string()).collect();
|
||||
let column_types: Vec<String> = query.columns_ref().iter().map(mysql_column_type_name).collect();
|
||||
|
||||
let result = if columns.is_empty() {
|
||||
let affected_rows = query.affected_rows();
|
||||
let warnings = query.warnings();
|
||||
let info = query.info().into_owned();
|
||||
query.drop_result().await.map_err(transaction_error_from_mysql_error)?;
|
||||
let messages = collect_mysql_server_messages(conn, warnings, &info).await;
|
||||
QueryResult {
|
||||
columns,
|
||||
column_types,
|
||||
column_sortables: Vec::new(),
|
||||
spatial_columns: Vec::new(),
|
||||
spatial_values: Vec::new(),
|
||||
rows: Vec::new(),
|
||||
affected_rows,
|
||||
execution_time_ms: started_at.elapsed().as_millis(),
|
||||
truncated: false,
|
||||
session_id: None,
|
||||
has_more: false,
|
||||
elasticsearch_raw_body: None,
|
||||
messages,
|
||||
}
|
||||
} else {
|
||||
let mut spatial_columns = mysql_spatial_column_builder(query.columns_ref());
|
||||
let mut rows = Vec::with_capacity(row_limit.min(128));
|
||||
let mut spatial_values = Vec::new();
|
||||
let mut truncated = false;
|
||||
while let Some(row) = query.next().await.map_err(transaction_error_from_mysql_error)? {
|
||||
if rows.len() < row_limit {
|
||||
let (values, srids) = mysql_row_to_json_with_srids(&row, &mut spatial_columns);
|
||||
spatial_values.push(srids);
|
||||
rows.push(values);
|
||||
} else {
|
||||
truncated = true;
|
||||
}
|
||||
}
|
||||
// `next` stops at the first result-set boundary. Drain every remaining
|
||||
// result set before reading the final status or allowing another
|
||||
// operation on this physical connection.
|
||||
query.drop_result().await.map_err(transaction_error_from_mysql_error)?;
|
||||
QueryResult {
|
||||
columns,
|
||||
column_types,
|
||||
column_sortables: Vec::new(),
|
||||
spatial_columns: spatial_columns.finish(),
|
||||
spatial_values,
|
||||
rows,
|
||||
affected_rows: 0,
|
||||
execution_time_ms: started_at.elapsed().as_millis(),
|
||||
truncated,
|
||||
session_id: None,
|
||||
has_more: false,
|
||||
elasticsearch_raw_body: None,
|
||||
messages: Vec::new(),
|
||||
}
|
||||
};
|
||||
let in_transaction = transaction_status_from_last_ok(conn)?;
|
||||
Ok(MySqlTransactionExecution { result, in_transaction })
|
||||
}
|
||||
|
||||
pub async fn execute_query_on_conn_with_limits(
|
||||
conn: &mut mysql_async::Conn,
|
||||
sql: &str,
|
||||
@@ -6060,6 +6174,24 @@ mod tests {
|
||||
use mysql_async::{consts::ColumnType, Column, Value};
|
||||
use mysql_common::row::new_row;
|
||||
|
||||
#[test]
|
||||
fn transaction_error_preserves_server_code_without_treating_it_as_transport_failure() {
|
||||
let error = mysql_async::Error::Server(mysql_async::ServerError {
|
||||
code: 1062,
|
||||
message: "Duplicate entry".to_string(),
|
||||
state: "23000".to_string(),
|
||||
});
|
||||
|
||||
assert_eq!(
|
||||
transaction_error_from_mysql_error(error),
|
||||
MySqlTransactionError::Server {
|
||||
code: 1062,
|
||||
message: "Duplicate entry".to_string(),
|
||||
state: "23000".to_string(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
fn mysql_test_row(values: Vec<Value>) -> mysql_async::Row {
|
||||
let columns = values
|
||||
.iter()
|
||||
|
||||
Reference in new issue
Block a user