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 dataflow-state/src/persistent_state/format_version.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ use super::{serialize_key, PersistentMeta, PointKey};
/// - Changes to [`PointKey`]'s `Serialize` impl (tuple/seq wrapping)
/// - Changes to [`serialize_key()`](super::serialize_key) (length-prefix wrapping, extra data
/// encoding)
pub(super) const PERSISTENT_STATE_VERSION: u8 = 7;
pub(super) const PERSISTENT_STATE_VERSION: u8 = 8;

/// Returns labeled single-element `DfValue`s exercising each normalization path in the key
/// serialization pipeline.
Expand Down
8 changes: 4 additions & 4 deletions dataflow-state/tests/serialized-meta.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"index_type": "HashMap"
}
],
"persistent_state_version": 7,
"persistent_state_version": 8,
"replication_offset": null
},
{
Expand All @@ -29,7 +29,7 @@
"index_type": "BTreeMap"
}
],
"persistent_state_version": 7,
"persistent_state_version": 8,
"replication_offset": {
"MySql": {
"binlog_file_base_name": "binlog",
Expand All @@ -49,7 +49,7 @@
"index_type": "HashMap"
}
],
"persistent_state_version": 7,
"persistent_state_version": 8,
"replication_offset": {
"Postgres": {
"commit_lsn": 12345,
Expand All @@ -69,7 +69,7 @@
"index_type": "BTreeMap"
}
],
"persistent_state_version": 7,
"persistent_state_version": 8,
"replication_offset": {
"Gtid": {
"entries": {
Expand Down
13 changes: 8 additions & 5 deletions replicators/src/mysql_connector/connector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,9 @@ use replication_offset::mysql::MySqlPosition;
use replication_offset::{GtidEvent, GtidSet, GtidSource, ReplicationOffset};
use uuid::Uuid;

use crate::mysql_connector::utils::{mysql_pad_binary_column, mysql_pad_char_column};
use crate::mysql_connector::utils::{
mysql_json_print, mysql_pad_binary_column, mysql_pad_char_column,
};
use crate::noria_adapter::{Connector, ReplicationAction};
use crate::table_filter::TableFilter;

Expand Down Expand Up @@ -2515,10 +2517,11 @@ fn binlog_row_to_noria_row(
BinlogValue::Jsonb(val) => {
let json: Result<serde_json::Value, _> = val.clone().try_into(); // urgh no TryFrom impl
match json {
Ok(val) => Ok(DfValue::from(&val)),
Err(JsonbToJsonError::Opaque) => {
Ok(DfValue::from(&binlog_to_serde_jsonb_value(val)?))
}
Ok(val) => mysql_json_print(&val).map(DfValue::from),
Err(JsonbToJsonError::Opaque) => mysql_json_print(
&binlog_to_serde_jsonb_value(val)?,
)
.map(DfValue::from),
Err(JsonbToJsonError::InvalidUtf8(e)) => Err(e.into()),
Err(JsonbToJsonError::InvalidJsonb(e)) => Err(e.into()),
}
Expand Down
32 changes: 15 additions & 17 deletions replicators/src/mysql_connector/snapshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ use readyset_sql_parsing::ParsingPreset;
use readyset_util::failpoints;
use replication_offset::mysql::MySqlPosition;
use replication_offset::{GtidSet, ReplicationOffset, ReplicationOffsets};
use serde_json::Value;
use tokio::sync::mpsc::UnboundedSender;
use tokio::task::JoinHandle;
use tracing::{debug, error, info, info_span, warn};
Expand Down Expand Up @@ -1107,22 +1106,21 @@ fn mysql_value_to_noria_value(
_ => return Err(internal_err!("Expected a bytes value for decimal column")),
},
ColumnType::MYSQL_TYPE_JSON => {
let df_val = match val {
mysql_common::value::Value::Bytes(b) => {
let s = str::from_utf8(&b)
.map_err(|e| internal_err!("Failed to parse JSON value: {e}"))?;
let json: Value = serde_json::from_str(s)
.map_err(|e| internal_err!("Failed to parse JSON value: {e}"))?;
DfValue::from(json)
}
mysql_common::value::Value::NULL => DfValue::None,
_ => {
return Err(internal_err!(
"Expected a bytes value for JSON column, got {:?}",
Sensitive(&val)
));
}
};
let df_val =
match val {
// Upstream renders JSON columns canonically, so its bytes are already the
// representation we want to store.
mysql_common::value::Value::Bytes(b) => str::from_utf8(&b)
.map(DfValue::from)
.map_err(|e| internal_err!("Invalid UTF-8 in JSON value: {e}"))?,
mysql_common::value::Value::NULL => DfValue::None,
_ => {
return Err(internal_err!(
"Expected a bytes value for JSON column, got {:?}",
Sensitive(&val)
));
}
};
noria_row.push(df_val);
}
ColumnType::MYSQL_TYPE_VAR_STRING
Expand Down
88 changes: 88 additions & 0 deletions replicators/src/mysql_connector/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use mysql_common::collations::{Collation as MyCollation, CollationId};
use readyset_data::encoding::Encoding;
use readyset_data::{Collation as RsCollation, DfValue, Dialect};
use readyset_errors::{internal, replication_failed, replication_failed_err, ReadySetResult};
use serde_json::Value as JsonValue;
use std::sync::Arc;

//TODO(marce): Make this a configuration parameter or dynamically adjust based on the table size
Expand Down Expand Up @@ -108,6 +109,57 @@ pub fn parse_mysql_version(version: &str) -> mysql_async::Result<u32> {
Ok(major * 10000 + minor * 100 + patch)
}

/// Format JSON the same way MySQL renders a JSON column in a result set.
pub(crate) fn mysql_json_print(json: &JsonValue) -> ReadySetResult<String> {
fn write_json_string(output: &mut String, string: &str) -> ReadySetResult<()> {
output.push_str(&serde_json::to_string(string)?);
Ok(())
}

fn write_json(output: &mut String, json: &JsonValue) -> ReadySetResult<()> {
match json {
JsonValue::Object(object) => {
let mut fields = object.iter().collect::<Vec<_>>();
fields.sort_unstable_by(|(left, _), (right, _)| {
left.len()
.cmp(&right.len())
.then_with(|| left.as_bytes().cmp(right.as_bytes()))
});

output.push('{');
for (index, (key, value)) in fields.into_iter().enumerate() {
if index != 0 {
output.push_str(", ");
}
write_json_string(output, key)?;
output.push_str(": ");
write_json(output, value)?;
}
output.push('}');
}
JsonValue::Array(array) => {
output.push('[');
for (index, value) in array.iter().enumerate() {
if index != 0 {
output.push_str(", ");
}
write_json(output, value)?;
}
output.push(']');
}
JsonValue::String(string) => write_json_string(output, string)?,
JsonValue::Number(number) => output.push_str(&number.to_string()),
JsonValue::Bool(boolean) => output.push_str(if *boolean { "true" } else { "false" }),
JsonValue::Null => output.push_str("null"),
}
Ok(())
}

let mut output = String::with_capacity(64);
write_json(&mut output, json)?;
Ok(output)
}

/// Get MySQL Server Version
pub async fn get_mysql_version(conn: &mut mysql_async::Conn) -> mysql::Result<u32> {
let version: mysql::Row = conn.query_first("SELECT VERSION()").await?.unwrap();
Expand All @@ -133,4 +185,40 @@ mod tests {
let version_number = parse_mysql_version(version).unwrap();
assert_eq!(version_number, 80023);
}

#[test]
fn mysql_json_print_matches_mysql_key_order_and_spacing() {
let json = serde_json::json!({
"zeta": 1,
"alpha": 2,
"middle": {
"z": 1,
"a": 2,
"m": 3
},
"numeric": {
"10": "ten",
"2": "two",
"1": "one",
"20": "twenty"
}
});

assert_eq!(
mysql_json_print(&json).unwrap(),
r#"{"zeta": 1, "alpha": 2, "middle": {"a": 2, "m": 3, "z": 1}, "numeric": {"1": "one", "2": "two", "10": "ten", "20": "twenty"}}"#
);
}

#[test]
fn mysql_json_print_escapes_strings() {
let json = serde_json::json!({
"quote\"": "line\nslash\\tab\t"
});

assert_eq!(
mysql_json_print(&json).unwrap(),
r#"{"quote\"": "line\nslash\\tab\t"}"#
);
}
}
50 changes: 42 additions & 8 deletions replicators/tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3824,7 +3824,9 @@ async fn mysql_replicate_json_field() {
INSERT INTO j_table (id, data, c) VALUES (1, '{\"age\": 30, \"car\": [\"Ford\", \"BMW\", \"Fiat\"], \"name\": \"John\"}', 'A');
INSERT INTO j_table (id, data, c) VALUES (2, '{\"car\": [\"Ford\", \"BMW\", \"Fiat\"], \"name\": \"John\", \"age\":30}', 'A');
INSERT INTO j_table (id, data, c) VALUES (3, '{\"amount\": {\"amount\": \"0.0\", \"currency\": \"USD\"}, \"is_custom\": false, \"description\": \"My Description\", \"amount_formatted\": \"$0.00\"}', 'A');
INSERT INTO j_table (id, data, c) VALUES (4, NULL, 'A');",
INSERT INTO j_table (id, data, c) VALUES (4, NULL, 'A');
INSERT INTO j_table (id, data, c) VALUES (5, '{\"zeta\":1,\"alpha\":2,\"middle\":{\"z\":1,\"a\":2,\"m\":3}}', 'A');
INSERT INTO j_table (id, data, c) VALUES (6, '{\"10\":\"ten\",\"2\":\"two\",\"1\":\"one\",\"20\":\"twenty\"}', 'A');",
)
.await
.unwrap();
Expand All @@ -3846,33 +3848,49 @@ async fn mysql_replicate_json_field() {
&[
DfValue::Int(1),
DfValue::Text(
"{\"age\":30,\"car\":[\"Ford\",\"BMW\",\"Fiat\"],\"name\":\"John\"}"
"{\"age\": 30, \"car\": [\"Ford\", \"BMW\", \"Fiat\"], \"name\": \"John\"}"
.into(),
),
DfValue::Text("A".into()),
],
&[
DfValue::Int(2),
DfValue::Text(
"{\"age\":30,\"car\":[\"Ford\",\"BMW\",\"Fiat\"],\"name\":\"John\"}"
"{\"age\": 30, \"car\": [\"Ford\", \"BMW\", \"Fiat\"], \"name\": \"John\"}"
.into(),
),
DfValue::Text("A".into()),
],
&[
DfValue::Int(3),
DfValue::Text(
"{\"amount\":{\"amount\":\"0.0\",\"currency\":\"USD\"},\"amount_formatted\":\"$0.00\",\"description\":\"My Description\",\"is_custom\":false}"
"{\"amount\": {\"amount\": \"0.0\", \"currency\": \"USD\"}, \"is_custom\": false, \"description\": \"My Description\", \"amount_formatted\": \"$0.00\"}"
.into(),
),
DfValue::Text("A".into()),
],
&[DfValue::Int(4), DfValue::None, DfValue::Text("A".into())],
&[
DfValue::Int(5),
DfValue::Text(
"{\"zeta\": 1, \"alpha\": 2, \"middle\": {\"a\": 2, \"m\": 3, \"z\": 1}}"
.into(),
),
DfValue::Text("A".into()),
],
&[
DfValue::Int(6),
DfValue::Text(
"{\"1\": \"one\", \"2\": \"two\", \"10\": \"ten\", \"20\": \"twenty\"}"
.into(),
),
DfValue::Text("A".into()),
],
],);

// Update the JSON data
client
.query("UPDATE j_table SET c = 'B' WHERE id IN (1, 2, 3, 4);")
.query("UPDATE j_table SET c = 'B' WHERE id IN (1, 2, 3, 4, 5, 6);")
.await
.unwrap();

Expand All @@ -3883,28 +3901,44 @@ async fn mysql_replicate_json_field() {
&[
DfValue::Int(1),
DfValue::Text(
"{\"age\":30,\"car\":[\"Ford\",\"BMW\",\"Fiat\"],\"name\":\"John\"}"
"{\"age\": 30, \"car\": [\"Ford\", \"BMW\", \"Fiat\"], \"name\": \"John\"}"
.into(),
),
DfValue::Text("B".into()),
],
&[
DfValue::Int(2),
DfValue::Text(
"{\"age\":30,\"car\":[\"Ford\",\"BMW\",\"Fiat\"],\"name\":\"John\"}"
"{\"age\": 30, \"car\": [\"Ford\", \"BMW\", \"Fiat\"], \"name\": \"John\"}"
.into(),
),
DfValue::Text("B".into()),
],
&[
DfValue::Int(3),
DfValue::Text(
"{\"amount\":{\"amount\":\"0.0\",\"currency\":\"USD\"},\"amount_formatted\":\"$0.00\",\"description\":\"My Description\",\"is_custom\":false}"
"{\"amount\": {\"amount\": \"0.0\", \"currency\": \"USD\"}, \"is_custom\": false, \"description\": \"My Description\", \"amount_formatted\": \"$0.00\"}"
.into(),
),
DfValue::Text("B".into()),
],
&[DfValue::Int(4), DfValue::None, DfValue::Text("B".into())],
&[
DfValue::Int(5),
DfValue::Text(
"{\"zeta\": 1, \"alpha\": 2, \"middle\": {\"a\": 2, \"m\": 3, \"z\": 1}}"
.into(),
),
DfValue::Text("B".into()),
],
&[
DfValue::Int(6),
DfValue::Text(
"{\"1\": \"one\", \"2\": \"two\", \"10\": \"ten\", \"20\": \"twenty\"}"
.into(),
),
DfValue::Text("B".into()),
],
],);

shutdown_tx.shutdown().await;
Expand Down