array parsing by value

This commit is contained in:
Conrad Ludgate
2024-09-16 15:45:02 +01:00
parent a8d4634191
commit 4529b463b5

View File

@@ -1,5 +1,6 @@
use std::fmt;
use itertools::Itertools;
use serde::de;
use serde::Deserialize;
use serde::Deserializer;
@@ -433,7 +434,7 @@ fn json_value_to_pg_text(value: Value) -> Option<String> {
Value::String(s) => Some(s),
// special care for arrays
Value::Array(_) => json_array_to_pg_array(&value),
Value::Array(arr) => Some(json_array_to_pg_array(arr)),
}
}
@@ -445,7 +446,17 @@ 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> {
fn json_array_to_pg_array(arr: Vec<Value>) -> String {
let vals = arr
.into_iter()
.map(json_array_value_to_pg_array)
.map(|v| v.unwrap_or_else(|| "NULL".to_string()))
.join(",");
format!("{{{vals}}}")
}
fn json_array_value_to_pg_array(value: Value) -> Option<String> {
match value {
// special care for nulls
Value::Null => None,
@@ -453,19 +464,10 @@ fn json_array_to_pg_array(value: &Value) -> Option<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(_)) => Some(v.to_string()),
v @ Value::Object(_) => json_array_to_pg_array(&Value::String(v.to_string())),
v @ Value::Object(_) => json_array_value_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}}}"))
}
Value::Array(arr) => Some(json_array_to_pg_array(arr)),
}
}