array_remove(array, element) - Remove all occurrences of element
(conn: &Connection)
| 266 | |
| 267 | /// array_remove(array, element) - Remove all occurrences of element |
| 268 | fn register_array_remove(conn: &Connection) -> Result<()> { |
| 269 | conn.create_scalar_function( |
| 270 | "array_remove", |
| 271 | 2, |
| 272 | FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_DETERMINISTIC, |
| 273 | |ctx| { |
| 274 | let array_json: String = ctx.get(0)?; |
| 275 | |
| 276 | // Handle element parameter of different types |
| 277 | let elem_value = match ctx.get_raw(1) { |
| 278 | rusqlite::types::ValueRef::Text(s) => { |
| 279 | let text = std::str::from_utf8(s).unwrap_or(""); |
| 280 | serde_json::from_str::<JsonValue>(text) |
| 281 | .unwrap_or_else(|_| JsonValue::String(text.to_string())) |
| 282 | } |
| 283 | rusqlite::types::ValueRef::Integer(i) => JsonValue::Number(serde_json::Number::from(i)), |
| 284 | rusqlite::types::ValueRef::Real(f) => { |
| 285 | JsonValue::Number(serde_json::Number::from_f64(f).unwrap_or_else(|| serde_json::Number::from(0))) |
| 286 | } |
| 287 | rusqlite::types::ValueRef::Null => JsonValue::Null, |
| 288 | rusqlite::types::ValueRef::Blob(b) => { |
| 289 | JsonValue::String(format!("\\x{}", hex::encode(b))) |
| 290 | } |
| 291 | }; |
| 292 | |
| 293 | match serde_json::from_str::<JsonValue>(&array_json) { |
| 294 | Ok(JsonValue::Array(arr)) => { |
| 295 | let filtered: Vec<JsonValue> = arr.into_iter() |
| 296 | .filter(|v| v != &elem_value) |
| 297 | .collect(); |
| 298 | |
| 299 | Ok(serde_json::to_string(&filtered).ok()) |
| 300 | } |
| 301 | _ => Ok(None), |
| 302 | } |
| 303 | }, |
| 304 | )?; |
| 305 | |
| 306 | Ok(()) |
| 307 | } |
| 308 | |
| 309 | /// array_replace(array, old, new) - Replace all occurrences |
| 310 | fn register_array_replace(conn: &Connection) -> Result<()> { |
no test coverage detected