-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathjson_merge.rs
More file actions
68 lines (57 loc) · 1.7 KB
/
json_merge.rs
File metadata and controls
68 lines (57 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
extern crate alloc;
use alloc::format;
use alloc::string::{String, ToString};
use core::ffi::c_int;
use sqlite::ResultCode;
use sqlite_nostd as sqlite;
use sqlite_nostd::{Connection, Context, Value};
use crate::create_sqlite_text_fn;
use crate::error::SQLiteError;
/// Given any number of JSON TEXT arguments, merge them into a single JSON object.
///
/// This assumes each argument is a valid JSON object, with no duplicate keys.
/// No JSON parsing or validation is performed - this performs simple string concatenation.
fn powersync_json_merge_impl(
_ctx: *mut sqlite::context,
args: &[*mut sqlite::value],
) -> Result<String, SQLiteError> {
if args.is_empty() {
return Ok("{}".to_string());
}
let mut result = String::from("{");
for arg in args {
let chunk = arg.text();
if chunk.is_empty() || !chunk.starts_with('{') || !chunk.ends_with('}') {
return Err(SQLiteError::from(ResultCode::MISMATCH));
}
// Strip outer braces
let inner = &chunk[1..(chunk.len() - 1)];
// If this is not the first chunk, insert a comma
if result.len() > 1 {
result.push(',');
}
// Append the inner content
result.push_str(inner);
}
// Close the outer brace
result.push('}');
Ok(result)
}
create_sqlite_text_fn!(
powersync_json_merge,
powersync_json_merge_impl,
"powersync_json_merge"
);
pub fn register(db: *mut sqlite::sqlite3) -> Result<(), ResultCode> {
db.create_function_v2(
"powersync_json_merge",
-1,
sqlite::UTF8 | sqlite::DETERMINISTIC,
None,
Some(powersync_json_merge),
None,
None,
None,
)?;
Ok(())
}