MCPcopy Create free account
hub / github.com/erans/pgsqlite / register_array_replace

Function register_array_replace

src/functions/array_functions.rs:310–366  ·  view source on GitHub ↗

array_replace(array, old, new) - Replace all occurrences

(conn: &Connection)

Source from the content-addressed store, hash-verified

308
309/// array_replace(array, old, new) - Replace all occurrences
310fn register_array_replace(conn: &Connection) -> Result<()> {
311 conn.create_scalar_function(
312 "array_replace",
313 3,
314 FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_DETERMINISTIC,
315 |ctx| {
316 let array_json: String = ctx.get(0)?;
317
318 // Handle old_element parameter of different types
319 let old_value = match ctx.get_raw(1) {
320 rusqlite::types::ValueRef::Text(s) => {
321 let text = std::str::from_utf8(s).unwrap_or("");
322 serde_json::from_str::<JsonValue>(text)
323 .unwrap_or_else(|_| JsonValue::String(text.to_string()))
324 }
325 rusqlite::types::ValueRef::Integer(i) => JsonValue::Number(serde_json::Number::from(i)),
326 rusqlite::types::ValueRef::Real(f) => {
327 JsonValue::Number(serde_json::Number::from_f64(f).unwrap_or_else(|| serde_json::Number::from(0)))
328 }
329 rusqlite::types::ValueRef::Null => JsonValue::Null,
330 rusqlite::types::ValueRef::Blob(b) => {
331 JsonValue::String(format!("\\x{}", hex::encode(b)))
332 }
333 };
334
335 // Handle new_element parameter of different types
336 let new_value = match ctx.get_raw(2) {
337 rusqlite::types::ValueRef::Text(s) => {
338 let text = std::str::from_utf8(s).unwrap_or("");
339 serde_json::from_str::<JsonValue>(text)
340 .unwrap_or_else(|_| JsonValue::String(text.to_string()))
341 }
342 rusqlite::types::ValueRef::Integer(i) => JsonValue::Number(serde_json::Number::from(i)),
343 rusqlite::types::ValueRef::Real(f) => {
344 JsonValue::Number(serde_json::Number::from_f64(f).unwrap_or_else(|| serde_json::Number::from(0)))
345 }
346 rusqlite::types::ValueRef::Null => JsonValue::Null,
347 rusqlite::types::ValueRef::Blob(b) => {
348 JsonValue::String(format!("\\x{}", hex::encode(b)))
349 }
350 };
351
352 match serde_json::from_str::<JsonValue>(&array_json) {
353 Ok(JsonValue::Array(arr)) => {
354 let replaced: Vec<JsonValue> = arr.into_iter()
355 .map(|v| if v == old_value { new_value.clone() } else { v })
356 .collect();
357
358 Ok(serde_json::to_string(&replaced).ok())
359 }
360 _ => Ok(None),
361 }
362 },
363 )?;
364
365 Ok(())
366}
367

Callers 1

register_array_functionsFunction · 0.85

Calls 2

getMethod · 0.45
cloneMethod · 0.45

Tested by

no test coverage detected