LCOV - code coverage report
Current view: top level - proxy/src/serverless - json.rs (source / functions) Coverage Total Hit
Test: 86c536b7fe84b2afe03c3bb264199e9c319ae0f8.info Lines: 90.0 % 329 296
Test Date: 2024-06-24 16:38:41 Functions: 71.9 % 32 23

            Line data    Source code
       1              : use serde_json::Map;
       2              : use serde_json::Value;
       3              : use tokio_postgres::types::Kind;
       4              : use tokio_postgres::types::Type;
       5              : use tokio_postgres::Row;
       6              : 
       7              : //
       8              : // Convert json non-string types to strings, so that they can be passed to Postgres
       9              : // as parameters.
      10              : //
      11           14 : pub fn json_to_pg_text(json: Vec<Value>) -> Vec<Option<String>> {
      12           14 :     json.iter().map(json_value_to_pg_text).collect()
      13           14 : }
      14              : 
      15           16 : fn json_value_to_pg_text(value: &Value) -> Option<String> {
      16           16 :     match value {
      17              :         // special care for nulls
      18            2 :         Value::Null => None,
      19              : 
      20              :         // convert to text with escaping
      21            6 :         v @ (Value::Bool(_) | Value::Number(_) | Value::Object(_)) => Some(v.to_string()),
      22              : 
      23              :         // avoid escaping here, as we pass this as a parameter
      24            2 :         Value::String(s) => Some(s.to_string()),
      25              : 
      26              :         // special care for arrays
      27            6 :         Value::Array(_) => json_array_to_pg_array(value),
      28              :     }
      29           16 : }
      30              : 
      31              : //
      32              : // Serialize a JSON array to a Postgres array. Contrary to the strings in the params
      33              : // in the array we need to escape the strings. Postgres is okay with arrays of form
      34              : // '{1,"2",3}'::int[], so we don't check that array holds values of the same type, leaving
      35              : // it for Postgres to check.
      36              : //
      37              : // Example of the same escaping in node-postgres: packages/pg/lib/utils.js
      38              : //
      39           46 : fn json_array_to_pg_array(value: &Value) -> Option<String> {
      40           46 :     match value {
      41              :         // special care for nulls
      42            4 :         Value::Null => None,
      43              : 
      44              :         // convert to text with escaping
      45              :         // here string needs to be escaped, as it is part of the array
      46           26 :         v @ (Value::Bool(_) | Value::Number(_) | Value::String(_)) => Some(v.to_string()),
      47            4 :         v @ Value::Object(_) => json_array_to_pg_array(&Value::String(v.to_string())),
      48              : 
      49              :         // recurse into array
      50           12 :         Value::Array(arr) => {
      51           12 :             let vals = arr
      52           12 :                 .iter()
      53           12 :                 .map(json_array_to_pg_array)
      54           36 :                 .map(|v| v.unwrap_or_else(|| "NULL".to_string()))
      55           12 :                 .collect::<Vec<_>>()
      56           12 :                 .join(",");
      57           12 : 
      58           12 :             Some(format!("{{{}}}", vals))
      59              :         }
      60              :     }
      61           46 : }
      62              : 
      63            0 : #[derive(Debug, thiserror::Error)]
      64              : pub enum JsonConversionError {
      65              :     #[error("internal error compute returned invalid data: {0}")]
      66              :     AsTextError(tokio_postgres::Error),
      67              :     #[error("parse int error: {0}")]
      68              :     ParseIntError(#[from] std::num::ParseIntError),
      69              :     #[error("parse float error: {0}")]
      70              :     ParseFloatError(#[from] std::num::ParseFloatError),
      71              :     #[error("parse json error: {0}")]
      72              :     ParseJsonError(#[from] serde_json::Error),
      73              :     #[error("unbalanced array")]
      74              :     UnbalancedArray,
      75              : }
      76              : 
      77              : //
      78              : // Convert postgres row with text-encoded values to JSON object
      79              : //
      80            0 : pub fn pg_text_row_to_json(
      81            0 :     row: &Row,
      82            0 :     columns: &[Type],
      83            0 :     raw_output: bool,
      84            0 :     array_mode: bool,
      85            0 : ) -> Result<Value, JsonConversionError> {
      86            0 :     let iter = row
      87            0 :         .columns()
      88            0 :         .iter()
      89            0 :         .zip(columns)
      90            0 :         .enumerate()
      91            0 :         .map(|(i, (column, typ))| {
      92            0 :             let name = column.name();
      93            0 :             let pg_value = row.as_text(i).map_err(JsonConversionError::AsTextError)?;
      94            0 :             let json_value = if raw_output {
      95            0 :                 match pg_value {
      96            0 :                     Some(v) => Value::String(v.to_string()),
      97            0 :                     None => Value::Null,
      98              :                 }
      99              :             } else {
     100            0 :                 pg_text_to_json(pg_value, typ)?
     101              :             };
     102            0 :             Ok((name.to_string(), json_value))
     103            0 :         });
     104            0 : 
     105            0 :     if array_mode {
     106              :         // drop keys and aggregate into array
     107            0 :         let arr = iter
     108            0 :             .map(|r| r.map(|(_key, val)| val))
     109            0 :             .collect::<Result<Vec<Value>, JsonConversionError>>()?;
     110            0 :         Ok(Value::Array(arr))
     111              :     } else {
     112            0 :         let obj = iter.collect::<Result<Map<String, Value>, JsonConversionError>>()?;
     113            0 :         Ok(Value::Object(obj))
     114              :     }
     115            0 : }
     116              : 
     117              : //
     118              : // Convert postgres text-encoded value to JSON value
     119              : //
     120          168 : fn pg_text_to_json(pg_value: Option<&str>, pg_type: &Type) -> Result<Value, JsonConversionError> {
     121          168 :     if let Some(val) = pg_value {
     122          152 :         if let Kind::Array(elem_type) = pg_type.kind() {
     123            0 :             return pg_array_parse(val, elem_type);
     124          152 :         }
     125          152 : 
     126          152 :         match *pg_type {
     127           24 :             Type::BOOL => Ok(Value::Bool(val == "t")),
     128              :             Type::INT2 | Type::INT4 => {
     129           28 :                 let val = val.parse::<i32>()?;
     130           28 :                 Ok(Value::Number(serde_json::Number::from(val)))
     131              :             }
     132              :             Type::FLOAT4 | Type::FLOAT8 => {
     133           46 :                 let fval = val.parse::<f64>()?;
     134           46 :                 let num = serde_json::Number::from_f64(fval);
     135           46 :                 if let Some(num) = num {
     136           28 :                     Ok(Value::Number(num))
     137              :                 } else {
     138              :                     // Pass Nan, Inf, -Inf as strings
     139              :                     // JS JSON.stringify() does converts them to null, but we
     140              :                     // want to preserve them, so we pass them as strings
     141           18 :                     Ok(Value::String(val.to_string()))
     142              :                 }
     143              :             }
     144           14 :             Type::JSON | Type::JSONB => Ok(serde_json::from_str(val)?),
     145           40 :             _ => Ok(Value::String(val.to_string())),
     146              :         }
     147              :     } else {
     148           16 :         Ok(Value::Null)
     149              :     }
     150          168 : }
     151              : 
     152              : //
     153              : // Parse postgres array into JSON array.
     154              : //
     155              : // This is a bit involved because we need to handle nested arrays and quoted
     156              : // values. Unlike postgres we don't check that all nested arrays have the same
     157              : // dimensions, we just return them as is.
     158              : //
     159           44 : fn pg_array_parse(pg_array: &str, elem_type: &Type) -> Result<Value, JsonConversionError> {
     160           44 :     _pg_array_parse(pg_array, elem_type, false).map(|(v, _)| v)
     161           44 : }
     162              : 
     163           78 : fn _pg_array_parse(
     164           78 :     pg_array: &str,
     165           78 :     elem_type: &Type,
     166           78 :     nested: bool,
     167           78 : ) -> Result<(Value, usize), JsonConversionError> {
     168           78 :     let mut pg_array_chr = pg_array.char_indices();
     169           78 :     let mut level = 0;
     170           78 :     let mut quote = false;
     171           78 :     let mut entries: Vec<Value> = Vec::new();
     172           78 :     let mut entry = String::new();
     173           78 : 
     174           78 :     // skip bounds decoration
     175           78 :     if let Some('[') = pg_array.chars().next() {
     176           36 :         for (_, c) in pg_array_chr.by_ref() {
     177           36 :             if c == '=' {
     178            2 :                 break;
     179           34 :             }
     180              :         }
     181           76 :     }
     182              : 
     183          180 :     fn push_checked(
     184          180 :         entry: &mut String,
     185          180 :         entries: &mut Vec<Value>,
     186          180 :         elem_type: &Type,
     187          180 :     ) -> Result<(), JsonConversionError> {
     188          180 :         if !entry.is_empty() {
     189              :             // While in usual postgres response we get nulls as None and everything else
     190              :             // as Some(&str), in arrays we get NULL as unquoted 'NULL' string (while
     191              :             // string with value 'NULL' will be represented by '"NULL"'). So catch NULLs
     192              :             // here while we have quotation info and convert them to None.
     193          116 :             if entry == "NULL" {
     194           14 :                 entries.push(pg_text_to_json(None, elem_type)?);
     195              :             } else {
     196          102 :                 entries.push(pg_text_to_json(Some(entry), elem_type)?);
     197              :             }
     198          116 :             entry.clear();
     199           64 :         }
     200              : 
     201          180 :         Ok(())
     202          180 :     }
     203              : 
     204          874 :     while let Some((mut i, mut c)) = pg_array_chr.next() {
     205          830 :         let mut escaped = false;
     206          830 : 
     207          830 :         if c == '\\' {
     208           30 :             escaped = true;
     209           30 :             (i, c) = pg_array_chr.next().unwrap();
     210          800 :         }
     211              : 
     212          124 :         match c {
     213          112 :             '{' if !quote => {
     214          112 :                 level += 1;
     215          112 :                 if level > 1 {
     216           34 :                     let (res, off) = _pg_array_parse(&pg_array[i..], elem_type, true)?;
     217           34 :                     entries.push(res);
     218          390 :                     for _ in 0..off - 1 {
     219          390 :                         pg_array_chr.next();
     220          390 :                     }
     221           78 :                 }
     222              :             }
     223          112 :             '}' if !quote => {
     224          112 :                 level -= 1;
     225          112 :                 if level == 0 {
     226           78 :                     push_checked(&mut entry, &mut entries, elem_type)?;
     227           78 :                     if nested {
     228           34 :                         return Ok((Value::Array(entries), i));
     229           44 :                     }
     230           34 :                 }
     231              :             }
     232           60 :             '"' if !escaped => {
     233           60 :                 if quote {
     234              :                     // end of quoted string, so push it manually without any checks
     235              :                     // for emptiness or nulls
     236           30 :                     entries.push(pg_text_to_json(Some(&entry), elem_type)?);
     237           30 :                     entry.clear();
     238           30 :                 }
     239           60 :                 quote = !quote;
     240              :             }
     241          102 :             ',' if !quote => {
     242          102 :                 push_checked(&mut entry, &mut entries, elem_type)?;
     243              :             }
     244          444 :             _ => {
     245          444 :                 entry.push(c);
     246          444 :             }
     247              :         }
     248              :     }
     249              : 
     250           44 :     if level != 0 {
     251            0 :         return Err(JsonConversionError::UnbalancedArray);
     252           44 :     }
     253           44 : 
     254           44 :     Ok((Value::Array(entries), 0))
     255           78 : }
     256              : 
     257              : #[cfg(test)]
     258              : mod tests {
     259              :     use super::*;
     260              :     use serde_json::json;
     261              : 
     262              :     #[test]
     263            2 :     fn test_atomic_types_to_pg_params() {
     264            2 :         let json = vec![Value::Bool(true), Value::Bool(false)];
     265            2 :         let pg_params = json_to_pg_text(json);
     266            2 :         assert_eq!(
     267            2 :             pg_params,
     268            2 :             vec![Some("true".to_owned()), Some("false".to_owned())]
     269            2 :         );
     270              : 
     271            2 :         let json = vec![Value::Number(serde_json::Number::from(42))];
     272            2 :         let pg_params = json_to_pg_text(json);
     273            2 :         assert_eq!(pg_params, vec![Some("42".to_owned())]);
     274              : 
     275            2 :         let json = vec![Value::String("foo\"".to_string())];
     276            2 :         let pg_params = json_to_pg_text(json);
     277            2 :         assert_eq!(pg_params, vec![Some("foo\"".to_owned())]);
     278              : 
     279            2 :         let json = vec![Value::Null];
     280            2 :         let pg_params = json_to_pg_text(json);
     281            2 :         assert_eq!(pg_params, vec![None]);
     282            2 :     }
     283              : 
     284              :     #[test]
     285            2 :     fn test_json_array_to_pg_array() {
     286            2 :         // atoms and escaping
     287            2 :         let json = "[true, false, null, \"NULL\", 42, \"foo\", \"bar\\\"-\\\\\"]";
     288            2 :         let json: Value = serde_json::from_str(json).unwrap();
     289            2 :         let pg_params = json_to_pg_text(vec![json]);
     290            2 :         assert_eq!(
     291            2 :             pg_params,
     292            2 :             vec![Some(
     293            2 :                 "{true,false,NULL,\"NULL\",42,\"foo\",\"bar\\\"-\\\\\"}".to_owned()
     294            2 :             )]
     295            2 :         );
     296              : 
     297              :         // nested arrays
     298            2 :         let json = "[[true, false], [null, 42], [\"foo\", \"bar\\\"-\\\\\"]]";
     299            2 :         let json: Value = serde_json::from_str(json).unwrap();
     300            2 :         let pg_params = json_to_pg_text(vec![json]);
     301            2 :         assert_eq!(
     302            2 :             pg_params,
     303            2 :             vec![Some(
     304            2 :                 "{{true,false},{NULL,42},{\"foo\",\"bar\\\"-\\\\\"}}".to_owned()
     305            2 :             )]
     306            2 :         );
     307              :         // array of objects
     308            2 :         let json = r#"[{"foo": 1},{"bar": 2}]"#;
     309            2 :         let json: Value = serde_json::from_str(json).unwrap();
     310            2 :         let pg_params = json_to_pg_text(vec![json]);
     311            2 :         assert_eq!(
     312            2 :             pg_params,
     313            2 :             vec![Some(r#"{"{\"foo\":1}","{\"bar\":2}"}"#.to_owned())]
     314            2 :         );
     315            2 :     }
     316              : 
     317              :     #[test]
     318            2 :     fn test_atomic_types_parse() {
     319            2 :         assert_eq!(
     320            2 :             pg_text_to_json(Some("foo"), &Type::TEXT).unwrap(),
     321            2 :             json!("foo")
     322            2 :         );
     323            2 :         assert_eq!(pg_text_to_json(None, &Type::TEXT).unwrap(), json!(null));
     324            2 :         assert_eq!(pg_text_to_json(Some("42"), &Type::INT4).unwrap(), json!(42));
     325            2 :         assert_eq!(pg_text_to_json(Some("42"), &Type::INT2).unwrap(), json!(42));
     326            2 :         assert_eq!(
     327            2 :             pg_text_to_json(Some("42"), &Type::INT8).unwrap(),
     328            2 :             json!("42")
     329            2 :         );
     330            2 :         assert_eq!(
     331            2 :             pg_text_to_json(Some("42.42"), &Type::FLOAT8).unwrap(),
     332            2 :             json!(42.42)
     333            2 :         );
     334            2 :         assert_eq!(
     335            2 :             pg_text_to_json(Some("42.42"), &Type::FLOAT4).unwrap(),
     336            2 :             json!(42.42)
     337            2 :         );
     338            2 :         assert_eq!(
     339            2 :             pg_text_to_json(Some("NaN"), &Type::FLOAT4).unwrap(),
     340            2 :             json!("NaN")
     341            2 :         );
     342            2 :         assert_eq!(
     343            2 :             pg_text_to_json(Some("Infinity"), &Type::FLOAT4).unwrap(),
     344            2 :             json!("Infinity")
     345            2 :         );
     346            2 :         assert_eq!(
     347            2 :             pg_text_to_json(Some("-Infinity"), &Type::FLOAT4).unwrap(),
     348            2 :             json!("-Infinity")
     349            2 :         );
     350              : 
     351            2 :         let json: Value =
     352            2 :             serde_json::from_str("{\"s\":\"str\",\"n\":42,\"f\":4.2,\"a\":[null,3,\"a\"]}")
     353            2 :                 .unwrap();
     354            2 :         assert_eq!(
     355            2 :             pg_text_to_json(
     356            2 :                 Some(r#"{"s":"str","n":42,"f":4.2,"a":[null,3,"a"]}"#),
     357            2 :                 &Type::JSONB
     358            2 :             )
     359            2 :             .unwrap(),
     360            2 :             json
     361            2 :         );
     362            2 :     }
     363              : 
     364              :     #[test]
     365            2 :     fn test_pg_array_parse_text() {
     366            8 :         fn pt(pg_arr: &str) -> Value {
     367            8 :             pg_array_parse(pg_arr, &Type::TEXT).unwrap()
     368            8 :         }
     369            2 :         assert_eq!(
     370            2 :             pt(r#"{"aa\"\\\,a",cha,"bbbb"}"#),
     371            2 :             json!(["aa\"\\,a", "cha", "bbbb"])
     372            2 :         );
     373            2 :         assert_eq!(
     374            2 :             pt(r#"{{"foo","bar"},{"bee","bop"}}"#),
     375            2 :             json!([["foo", "bar"], ["bee", "bop"]])
     376            2 :         );
     377            2 :         assert_eq!(
     378            2 :             pt(r#"{{{{"foo",NULL,"bop",bup}}}}"#),
     379            2 :             json!([[[["foo", null, "bop", "bup"]]]])
     380            2 :         );
     381            2 :         assert_eq!(
     382            2 :             pt(r#"{{"1",2,3},{4,NULL,6},{NULL,NULL,NULL}}"#),
     383            2 :             json!([["1", "2", "3"], ["4", null, "6"], [null, null, null]])
     384            2 :         );
     385            2 :     }
     386              : 
     387              :     #[test]
     388            2 :     fn test_pg_array_parse_bool() {
     389            8 :         fn pb(pg_arr: &str) -> Value {
     390            8 :             pg_array_parse(pg_arr, &Type::BOOL).unwrap()
     391            8 :         }
     392            2 :         assert_eq!(pb(r#"{t,f,t}"#), json!([true, false, true]));
     393            2 :         assert_eq!(pb(r#"{{t,f,t}}"#), json!([[true, false, true]]));
     394            2 :         assert_eq!(
     395            2 :             pb(r#"{{t,f},{f,t}}"#),
     396            2 :             json!([[true, false], [false, true]])
     397            2 :         );
     398            2 :         assert_eq!(
     399            2 :             pb(r#"{{t,NULL},{NULL,f}}"#),
     400            2 :             json!([[true, null], [null, false]])
     401            2 :         );
     402            2 :     }
     403              : 
     404              :     #[test]
     405            2 :     fn test_pg_array_parse_numbers() {
     406           18 :         fn pn(pg_arr: &str, ty: &Type) -> Value {
     407           18 :             pg_array_parse(pg_arr, ty).unwrap()
     408           18 :         }
     409            2 :         assert_eq!(pn(r#"{1,2,3}"#, &Type::INT4), json!([1, 2, 3]));
     410            2 :         assert_eq!(pn(r#"{1,2,3}"#, &Type::INT2), json!([1, 2, 3]));
     411            2 :         assert_eq!(pn(r#"{1,2,3}"#, &Type::INT8), json!(["1", "2", "3"]));
     412            2 :         assert_eq!(pn(r#"{1,2,3}"#, &Type::FLOAT4), json!([1.0, 2.0, 3.0]));
     413            2 :         assert_eq!(pn(r#"{1,2,3}"#, &Type::FLOAT8), json!([1.0, 2.0, 3.0]));
     414            2 :         assert_eq!(
     415            2 :             pn(r#"{1.1,2.2,3.3}"#, &Type::FLOAT4),
     416            2 :             json!([1.1, 2.2, 3.3])
     417            2 :         );
     418            2 :         assert_eq!(
     419            2 :             pn(r#"{1.1,2.2,3.3}"#, &Type::FLOAT8),
     420            2 :             json!([1.1, 2.2, 3.3])
     421            2 :         );
     422            2 :         assert_eq!(
     423            2 :             pn(r#"{NaN,Infinity,-Infinity}"#, &Type::FLOAT4),
     424            2 :             json!(["NaN", "Infinity", "-Infinity"])
     425            2 :         );
     426            2 :         assert_eq!(
     427            2 :             pn(r#"{NaN,Infinity,-Infinity}"#, &Type::FLOAT8),
     428            2 :             json!(["NaN", "Infinity", "-Infinity"])
     429            2 :         );
     430            2 :     }
     431              : 
     432              :     #[test]
     433            2 :     fn test_pg_array_with_decoration() {
     434            2 :         fn p(pg_arr: &str) -> Value {
     435            2 :             pg_array_parse(pg_arr, &Type::INT2).unwrap()
     436            2 :         }
     437            2 :         assert_eq!(
     438            2 :             p(r#"[1:1][-2:-1][3:5]={{{1,2,3},{4,5,6}}}"#),
     439            2 :             json!([[[1, 2, 3], [4, 5, 6]]])
     440            2 :         );
     441            2 :     }
     442              : 
     443              :     #[test]
     444            2 :     fn test_pg_array_parse_json() {
     445            8 :         fn pt(pg_arr: &str) -> Value {
     446            8 :             pg_array_parse(pg_arr, &Type::JSONB).unwrap()
     447            8 :         }
     448            2 :         assert_eq!(pt(r#"{"{}"}"#), json!([{}]));
     449            2 :         assert_eq!(
     450            2 :             pt(r#"{"{\"foo\": 1, \"bar\": 2}"}"#),
     451            2 :             json!([{"foo": 1, "bar": 2}])
     452            2 :         );
     453            2 :         assert_eq!(
     454            2 :             pt(r#"{"{\"foo\": 1}", "{\"bar\": 2}"}"#),
     455            2 :             json!([{"foo": 1}, {"bar": 2}])
     456            2 :         );
     457            2 :         assert_eq!(
     458            2 :             pt(r#"{{"{\"foo\": 1}", "{\"bar\": 2}"}}"#),
     459            2 :             json!([[{"foo": 1}, {"bar": 2}]])
     460            2 :         );
     461            2 :     }
     462              : }
        

Generated by: LCOV version 2.1-beta