json_agg(expression) - Aggregate values into a JSON array
(conn: &Connection)
| 883 | |
| 884 | /// json_agg(expression) - Aggregate values into a JSON array |
| 885 | fn register_json_agg(conn: &Connection) -> Result<()> { |
| 886 | use rusqlite::functions::Aggregate; |
| 887 | |
| 888 | #[derive(Default)] |
| 889 | struct JsonAgg; |
| 890 | |
| 891 | impl Aggregate<Vec<JsonValue>, Option<String>> for JsonAgg { |
| 892 | fn init(&self, _: &mut rusqlite::functions::Context<'_>) -> Result<Vec<JsonValue>> { |
| 893 | Ok(Vec::new()) |
| 894 | } |
| 895 | |
| 896 | fn step(&self, ctx: &mut rusqlite::functions::Context<'_>, agg: &mut Vec<JsonValue>) -> Result<()> { |
| 897 | let value = ctx.get_raw(0); |
| 898 | |
| 899 | let json_value = match value { |
| 900 | rusqlite::types::ValueRef::Null => JsonValue::Null, |
| 901 | rusqlite::types::ValueRef::Integer(i) => JsonValue::Number(serde_json::Number::from(i)), |
| 902 | rusqlite::types::ValueRef::Real(f) => { |
| 903 | if let Some(num) = serde_json::Number::from_f64(f) { |
| 904 | JsonValue::Number(num) |
| 905 | } else { |
| 906 | JsonValue::Null |
| 907 | } |
| 908 | } |
| 909 | rusqlite::types::ValueRef::Text(s) => { |
| 910 | let text = std::str::from_utf8(s).unwrap_or(""); |
| 911 | // Try to parse as JSON first, if it fails treat as string |
| 912 | serde_json::from_str(text) |
| 913 | .unwrap_or_else(|_| JsonValue::String(text.to_string())) |
| 914 | } |
| 915 | rusqlite::types::ValueRef::Blob(b) => { |
| 916 | // Convert blob to hex string |
| 917 | JsonValue::String(format!("\\x{}", hex::encode(b))) |
| 918 | } |
| 919 | }; |
| 920 | |
| 921 | agg.push(json_value); |
| 922 | Ok(()) |
| 923 | } |
| 924 | |
| 925 | fn finalize(&self, _: &mut rusqlite::functions::Context<'_>, agg: Option<Vec<JsonValue>>) -> Result<Option<String>> { |
| 926 | match agg { |
| 927 | Some(values) => Ok(Some(serde_json::to_string(&values).unwrap_or_else(|_| "[]".to_string()))), |
| 928 | None => Ok(Some("[]".to_string())), // Return empty array for no rows |
| 929 | } |
| 930 | } |
| 931 | } |
| 932 | |
| 933 | conn.create_aggregate_function( |
| 934 | "json_agg", |
| 935 | 1, |
| 936 | FunctionFlags::SQLITE_UTF8, |
| 937 | JsonAgg, |
| 938 | )?; |
| 939 | |
| 940 | Ok(()) |
| 941 | } |
| 942 |
no outgoing calls
no test coverage detected