invert json_array_to_pg_array

This commit is contained in:
Conrad Ludgate
2025-07-07 17:53:13 +01:00
parent 55aef2993d
commit 539150ff64

View File

@@ -22,7 +22,7 @@ fn json_value_to_pg_text(value: &Value) -> Option<String> {
Value::String(s) => Some(s.clone()),
// special care for arrays
Value::Array(_) => json_array_to_pg_array(value),
Value::Array(arr) => Some(json_array_to_pg_array(arr)),
}
}
@@ -34,28 +34,29 @@ fn json_value_to_pg_text(value: &Value) -> Option<String> {
//
// Example of the same escaping in node-postgres: packages/pg/lib/utils.js
//
fn json_array_to_pg_array(value: &Value) -> Option<String> {
match value {
// special care for nulls
Value::Null => None,
// convert to text with escaping
// here string needs to be escaped, as it is part of the array
v @ (Value::Bool(_) | Value::Number(_) | Value::String(_)) => Some(v.to_string()),
v @ Value::Object(_) => json_array_to_pg_array(&Value::String(v.to_string())),
// recurse into array
Value::Array(arr) => {
let vals = arr
.iter()
.map(json_array_to_pg_array)
.map(|v| v.unwrap_or_else(|| "NULL".to_string()))
.collect::<Vec<_>>()
.join(",");
Some(format!("{{{vals}}}"))
fn json_array_to_pg_array(arr: &[Value]) -> String {
let mut output = String::new();
output.push('{');
for val in arr {
if output.len() > 1 {
output.push(',');
}
let val = match val {
Value::Null => "NULL".to_string(),
// convert to text with escaping
// here string needs to be escaped, as it is part of the array
v @ (Value::Bool(_) | Value::Number(_) | Value::String(_)) => v.to_string(),
v @ Value::Object(_) => Value::String(v.to_string()).to_string(),
// recurse into array
Value::Array(arr) => json_array_to_pg_array(arr),
};
output.push_str(&val);
}
output.push('}');
output
}
#[derive(Debug, thiserror::Error)]