graphitesql 0.0.5

A pure, safe, no_std Rust re-implementation of SQLite, compatible with the SQLite 3 file format.
Documentation
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
//! A minimal JSON value model with the parser, serializer, and path navigation
//! behind SQLite's core JSON functions (`json`, `json_extract`, `json_type`, …).
//!
//! This is RFC-8259 JSON with SQLite's conventions for the scalar mapping back
//! to SQL values: JSON `true`/`false` become integers `1`/`0`, `null` becomes
//! SQL `NULL`, numbers become INTEGER or REAL, strings become TEXT, and
//! objects/arrays are returned as their minified JSON text.

use crate::value::Value;
use alloc::string::{String, ToString};
use alloc::vec::Vec;

/// A parsed JSON value.
#[derive(Debug, Clone, PartialEq)]
pub enum Json {
    /// `null`
    Null,
    /// `true` / `false`
    Bool(bool),
    /// An integral number that fits in `i64`.
    Int(i64),
    /// Any other number.
    Real(f64),
    /// A string (unescaped).
    Str(String),
    /// An array.
    Array(Vec<Json>),
    /// An object, preserving member order.
    Object(Vec<(String, Json)>),
}

impl Json {
    /// SQLite's `json_type` label for this value.
    pub fn type_name(&self) -> &'static str {
        match self {
            Json::Null => "null",
            Json::Bool(true) => "true",
            Json::Bool(false) => "false",
            Json::Int(_) => "integer",
            Json::Real(_) => "real",
            Json::Str(_) => "text",
            Json::Array(_) => "array",
            Json::Object(_) => "object",
        }
    }

    /// Map a JSON scalar back to a SQL [`Value`]; objects and arrays serialize to
    /// their minified JSON text (matching `json_extract`).
    pub fn to_sql(&self) -> Value {
        match self {
            Json::Null => Value::Null,
            Json::Bool(b) => Value::Integer(*b as i64),
            Json::Int(i) => Value::Integer(*i),
            Json::Real(r) => Value::Real(*r),
            Json::Str(s) => Value::Text(s.clone()),
            Json::Array(_) | Json::Object(_) => Value::Text(self.serialize()),
        }
    }

    /// Serialize to compact (minified) JSON text.
    pub fn serialize(&self) -> String {
        let mut s = String::new();
        self.write(&mut s);
        s
    }

    /// Serialize to pretty-printed JSON using `indent` as the per-level unit
    /// (SQLite's `json_pretty`). Empty arrays/objects stay on one line; scalars
    /// render compactly.
    pub fn pretty(&self, indent: &str) -> String {
        let mut s = String::new();
        self.write_pretty(&mut s, indent, 0);
        s
    }

    fn write_pretty(&self, out: &mut String, indent: &str, depth: usize) {
        let pad = |out: &mut String, n: usize| {
            for _ in 0..n {
                out.push_str(indent);
            }
        };
        match self {
            Json::Array(items) if !items.is_empty() => {
                out.push('[');
                for (i, it) in items.iter().enumerate() {
                    if i > 0 {
                        out.push(',');
                    }
                    out.push('\n');
                    pad(out, depth + 1);
                    it.write_pretty(out, indent, depth + 1);
                }
                out.push('\n');
                pad(out, depth);
                out.push(']');
            }
            Json::Object(members) if !members.is_empty() => {
                out.push('{');
                for (i, (k, v)) in members.iter().enumerate() {
                    if i > 0 {
                        out.push(',');
                    }
                    out.push('\n');
                    pad(out, depth + 1);
                    write_json_string(k, out);
                    out.push_str(": ");
                    v.write_pretty(out, indent, depth + 1);
                }
                out.push('\n');
                pad(out, depth);
                out.push('}');
            }
            // Scalars and empty containers render the same as the compact form.
            _ => self.write(out),
        }
    }

    fn write(&self, out: &mut String) {
        match self {
            Json::Null => out.push_str("null"),
            Json::Bool(true) => out.push_str("true"),
            Json::Bool(false) => out.push_str("false"),
            Json::Int(i) => out.push_str(&i.to_string()),
            Json::Real(r) => out.push_str(&crate::exec::eval::format_real(*r)),
            Json::Str(s) => write_json_string(s, out),
            Json::Array(items) => {
                out.push('[');
                for (i, it) in items.iter().enumerate() {
                    if i > 0 {
                        out.push(',');
                    }
                    it.write(out);
                }
                out.push(']');
            }
            Json::Object(members) => {
                out.push('{');
                for (i, (k, v)) in members.iter().enumerate() {
                    if i > 0 {
                        out.push(',');
                    }
                    write_json_string(k, out);
                    out.push(':');
                    v.write(out);
                }
                out.push('}');
            }
        }
    }
}

/// Append a JSON-escaped string literal (with surrounding quotes).
fn write_json_string(s: &str, out: &mut String) {
    out.push('"');
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            '\u{08}' => out.push_str("\\b"),
            '\u{0c}' => out.push_str("\\f"),
            c if (c as u32) < 0x20 => {
                out.push_str("\\u");
                for shift in [12, 8, 4, 0] {
                    let nib = (c as u32 >> shift) & 0xf;
                    out.push(char::from_digit(nib, 16).unwrap());
                }
            }
            c => out.push(c),
        }
    }
    out.push('"');
}

/// Parse JSON text into a [`Json`], or `None` if it is not valid JSON (trailing
/// non-whitespace also fails).
pub fn parse(text: &str) -> Option<Json> {
    parse_with_error_position(text).ok()
}

/// Parse JSON text, returning the value on success or, on failure, the 0-based
/// byte offset of the first syntax error.
///
/// The offset is chosen to track the position the `sqlite3` CLI reports from
/// `json_error_position(X)` (which is the 1-based form, i.e. this value + 1)
/// for the common malformed-JSON shapes: truncated objects/arrays, missing
/// separators, bad tokens in value position, and unterminated strings.
pub fn parse_with_error_position(text: &str) -> Result<Json, usize> {
    let mut p = Parser {
        bytes: text.as_bytes(),
        pos: 0,
    };
    p.skip_ws();
    // An empty or whitespace-only document has no value at all; sqlite3 reports
    // position 1 (offset 0) here rather than the post-whitespace offset.
    if p.peek().is_none() {
        return Err(0);
    }
    let v = p.value()?;
    p.skip_ws();
    if p.pos == p.bytes.len() {
        Ok(v)
    } else {
        // Trailing non-whitespace: report the start of the document, matching
        // sqlite3's reporting for the common trailing-junk case.
        Err(0)
    }
}

struct Parser<'a> {
    bytes: &'a [u8],
    pos: usize,
}

impl Parser<'_> {
    fn peek(&self) -> Option<u8> {
        self.bytes.get(self.pos).copied()
    }

    /// The current position as a parse error.
    fn err<T>(&self) -> Result<T, usize> {
        Err(self.pos)
    }

    fn skip_ws(&mut self) {
        while let Some(c) = self.peek() {
            if c == b' ' || c == b'\t' || c == b'\n' || c == b'\r' {
                self.pos += 1;
            } else {
                break;
            }
        }
    }

    fn value(&mut self) -> Result<Json, usize> {
        self.skip_ws();
        match self.peek() {
            Some(b'{') => self.object(),
            Some(b'[') => self.array(),
            Some(b'"') => self.string().map(Json::Str),
            Some(b't') => self.literal("true", Json::Bool(true)),
            Some(b'f') => self.literal("false", Json::Bool(false)),
            Some(b'n') => self.literal("null", Json::Null),
            Some(b'-' | b'0'..=b'9') => self.number(),
            _ => self.err(),
        }
    }

    fn literal(&mut self, word: &str, val: Json) -> Result<Json, usize> {
        if self.bytes[self.pos..].starts_with(word.as_bytes()) {
            self.pos += word.len();
            Ok(val)
        } else {
            self.err()
        }
    }

    fn object(&mut self) -> Result<Json, usize> {
        self.pos += 1; // '{'
        let mut members = Vec::new();
        self.skip_ws();
        if self.peek() == Some(b'}') {
            self.pos += 1;
            return Ok(Json::Object(members));
        }
        loop {
            self.skip_ws();
            if self.peek() != Some(b'"') {
                // sqlite3 tolerates JSON5-style bare identifier keys, scanning
                // the run of identifier bytes before failing; mirror its error
                // position by skipping that run so we report its end.
                self.skip_bare_key();
                return self.err();
            }
            let key = self.string()?;
            self.skip_ws();
            if self.peek() != Some(b':') {
                return self.err();
            }
            self.pos += 1;
            let val = self.value()?;
            members.push((key, val));
            self.skip_ws();
            match self.peek() {
                Some(b',') => self.pos += 1,
                Some(b'}') => {
                    self.pos += 1;
                    return Ok(Json::Object(members));
                }
                _ => return self.err(),
            }
        }
    }

    /// Advance over a run of bare-key identifier bytes (`A-Za-z0-9_$`), used only
    /// to align the reported error position with sqlite3 when a key is missing.
    fn skip_bare_key(&mut self) {
        while let Some(c) = self.peek() {
            if c.is_ascii_alphanumeric() || c == b'_' || c == b'$' {
                self.pos += 1;
            } else {
                break;
            }
        }
    }

    fn array(&mut self) -> Result<Json, usize> {
        self.pos += 1; // '['
        let mut items = Vec::new();
        self.skip_ws();
        if self.peek() == Some(b']') {
            self.pos += 1;
            return Ok(Json::Array(items));
        }
        loop {
            let val = self.value()?;
            items.push(val);
            self.skip_ws();
            match self.peek() {
                Some(b',') => self.pos += 1,
                Some(b']') => {
                    self.pos += 1;
                    return Ok(Json::Array(items));
                }
                _ => return self.err(),
            }
        }
    }

    fn string(&mut self) -> Result<String, usize> {
        self.pos += 1; // opening quote
        let mut s = String::new();
        loop {
            let Some(c) = self.peek() else {
                return self.err();
            };
            self.pos += 1;
            match c {
                b'"' => return Ok(s),
                b'\\' => {
                    let Some(esc) = self.peek() else {
                        return self.err();
                    };
                    self.pos += 1;
                    match esc {
                        b'"' => s.push('"'),
                        b'\\' => s.push('\\'),
                        b'/' => s.push('/'),
                        b'n' => s.push('\n'),
                        b't' => s.push('\t'),
                        b'r' => s.push('\r'),
                        b'b' => s.push('\u{08}'),
                        b'f' => s.push('\u{0c}'),
                        b'u' => {
                            let cp = self.hex4()?;
                            // Surrogate pair?
                            if (0xD800..=0xDBFF).contains(&cp) {
                                if self.peek() == Some(b'\\') {
                                    self.pos += 1;
                                    if self.peek() == Some(b'u') {
                                        self.pos += 1;
                                        let lo = self.hex4()?;
                                        let c = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00);
                                        match char::from_u32(c) {
                                            Some(ch) => s.push(ch),
                                            None => return self.err(),
                                        }
                                    } else {
                                        return self.err();
                                    }
                                } else {
                                    return self.err();
                                }
                            } else {
                                match char::from_u32(cp) {
                                    Some(ch) => s.push(ch),
                                    None => return self.err(),
                                }
                            }
                        }
                        _ => return self.err(),
                    }
                }
                // A raw multi-byte UTF-8 sequence: copy the bytes through.
                0x80..=0xFF => {
                    let start = self.pos - 1;
                    while self.peek().is_some_and(|b| b >= 0x80) {
                        self.pos += 1;
                    }
                    match core::str::from_utf8(&self.bytes[start..self.pos]) {
                        Ok(chunk) => s.push_str(chunk),
                        Err(_) => return self.err(),
                    }
                }
                c => s.push(c as char),
            }
        }
    }

    fn hex4(&mut self) -> Result<u32, usize> {
        let mut v = 0u32;
        for _ in 0..4 {
            let Some(c) = self.peek() else {
                return self.err();
            };
            let Some(d) = (c as char).to_digit(16) else {
                return self.err();
            };
            v = v * 16 + d;
            self.pos += 1;
        }
        Ok(v)
    }

    fn number(&mut self) -> Result<Json, usize> {
        let start = self.pos;
        if self.peek() == Some(b'-') {
            self.pos += 1;
        }
        let mut is_real = false;
        while let Some(c) = self.peek() {
            match c {
                b'0'..=b'9' => self.pos += 1,
                b'.' | b'e' | b'E' | b'+' | b'-' => {
                    is_real = true;
                    self.pos += 1;
                }
                _ => break,
            }
        }
        let Ok(tok) = core::str::from_utf8(&self.bytes[start..self.pos]) else {
            return Err(start);
        };
        if !is_real {
            if let Ok(i) = tok.parse::<i64>() {
                return Ok(Json::Int(i));
            }
        }
        match tok.parse::<f64>() {
            Ok(r) => Ok(Json::Real(r)),
            Err(_) => Err(start),
        }
    }
}

/// Navigate a JSON value by a SQLite path expression (`$`, `.key`, `[index]`).
/// Returns `None` if the path does not resolve. Only the common subset is
/// supported: object keys via `.name` or `."name"`, array elements via `[n]`.
pub fn navigate<'a>(root: &'a Json, path: &str) -> Option<&'a Json> {
    let bytes = path.as_bytes();
    if bytes.first() != Some(&b'$') {
        return None;
    }
    let mut cur = root;
    let mut i = 1;
    while i < bytes.len() {
        match bytes[i] {
            b'.' => {
                i += 1;
                let (key, next) = parse_key(bytes, i)?;
                i = next;
                let Json::Object(members) = cur else {
                    return None;
                };
                cur = members.iter().find(|(k, _)| *k == key).map(|(_, v)| v)?;
            }
            b'[' => {
                i += 1;
                let start = i;
                while i < bytes.len() && bytes[i] != b']' {
                    i += 1;
                }
                if i >= bytes.len() {
                    return None;
                }
                let idx_str = core::str::from_utf8(&bytes[start..i]).ok()?;
                i += 1; // ']'
                let Json::Array(items) = cur else {
                    return None;
                };
                let n: usize = idx_str.trim().parse().ok()?;
                cur = items.get(n)?;
            }
            _ => return None,
        }
    }
    Some(cur)
}

/// Parse an object-key path segment starting at `i`, returning `(key, next_i)`.
/// Handles a bare identifier or a `"quoted"` key.
fn parse_key(bytes: &[u8], i: usize) -> Option<(String, usize)> {
    if bytes.get(i) == Some(&b'"') {
        // Quoted key: read until the closing quote.
        let mut j = i + 1;
        let mut s = String::new();
        while j < bytes.len() && bytes[j] != b'"' {
            s.push(bytes[j] as char);
            j += 1;
        }
        if j >= bytes.len() {
            return None;
        }
        Some((s, j + 1))
    } else {
        let start = i;
        let mut j = i;
        while j < bytes.len() && bytes[j] != b'.' && bytes[j] != b'[' {
            j += 1;
        }
        if j == start {
            return None;
        }
        let key = core::str::from_utf8(&bytes[start..j]).ok()?.to_string();
        Some((key, j))
    }
}

/// Convert a SQL [`Value`] to a [`Json`] for `json_array`/`json_object`. A text
/// value that is itself valid JSON is *not* re-parsed here (SQLite only treats
/// arguments as JSON when wrapped in `json()`); plain text becomes a JSON string.
pub fn value_to_json(v: &Value) -> Json {
    match v {
        Value::Null => Json::Null,
        Value::Integer(i) => Json::Int(*i),
        Value::Real(r) => Json::Real(*r),
        Value::Text(s) => Json::Str(s.clone()),
        Value::Blob(_) => Json::Str(String::new()),
    }
}

/// The `->` / `->>` operators. `doc` is the JSON document, `path_arg` the right
/// operand (a JSON path, a bare object label, or an integer array index). With
/// `as_text` (the `->>` form) the result is the SQL value at the path; otherwise
/// (`->`) it is that node re-rendered as JSON text. NULL doc or a missing path
/// yields SQL NULL.
pub fn arrow(doc: &Value, path_arg: &Value, as_text: bool) -> Value {
    if matches!(doc, Value::Null) {
        return Value::Null;
    }
    let text = crate::exec::eval::to_text(doc);
    let Some(root) = parse(&text) else {
        return Value::Null;
    };
    let path = arrow_path(path_arg);
    match navigate(&root, &path) {
        None => Value::Null,
        Some(node) => {
            if as_text {
                node.to_sql()
            } else {
                Value::Text(node.serialize())
            }
        }
    }
}

/// Normalize an `->`/`->>` right operand into a JSON path: an integer is an array
/// index `$[n]`, a string starting with `$` is used verbatim, any other string is
/// an object label `$.label`.
fn arrow_path(v: &Value) -> String {
    match v {
        Value::Integer(i) => alloc::format!("$[{i}]"),
        Value::Text(s) if s.starts_with('$') => s.clone(),
        Value::Text(s) => alloc::format!("$.{s}"),
        other => alloc::format!("$.{}", crate::exec::eval::to_text(other)),
    }
}

/// One step of a JSON path: an object key or an array index.
enum Seg {
    Key(String),
    Index(usize),
}

/// Parse a `$`-rooted path into its segments (the subset used by the mutators:
/// `.key`, `."key"`, `[n]`). Returns `None` on a malformed path.
fn parse_path(path: &str) -> Option<Vec<Seg>> {
    let bytes = path.as_bytes();
    if bytes.first() != Some(&b'$') {
        return None;
    }
    let mut segs = Vec::new();
    let mut i = 1;
    while i < bytes.len() {
        match bytes[i] {
            b'.' => {
                let (key, next) = parse_key(bytes, i + 1)?;
                segs.push(Seg::Key(key));
                i = next;
            }
            b'[' => {
                let start = i + 1;
                let mut j = start;
                while j < bytes.len() && bytes[j] != b']' {
                    j += 1;
                }
                if j >= bytes.len() {
                    return None;
                }
                let n: usize = core::str::from_utf8(&bytes[start..j])
                    .ok()?
                    .trim()
                    .parse()
                    .ok()?;
                segs.push(Seg::Index(n));
                i = j + 1;
            }
            _ => return None,
        }
    }
    Some(segs)
}

/// How a `json_set`/`json_insert`/`json_replace` write applies at the leaf.
#[derive(Clone, Copy, PartialEq)]
pub enum SetMode {
    /// `json_set`: create or overwrite.
    Set,
    /// `json_insert`: only create when absent.
    Insert,
    /// `json_replace`: only overwrite when present.
    Replace,
}

/// Apply one `(path, value)` write to `root` under `mode`. Missing parent
/// containers are left untouched (matching SQLite, which only writes the leaf).
pub fn set_path(root: &mut Json, path: &str, value: Json, mode: SetMode) -> Option<()> {
    let segs = parse_path(path)?;
    if segs.is_empty() {
        if mode != SetMode::Insert {
            *root = value; // `$` targets the whole document
        }
        return Some(());
    }
    let mut cur = root;
    for seg in &segs[..segs.len() - 1] {
        cur = match (cur, seg) {
            (Json::Object(m), Seg::Key(k)) => {
                m.iter_mut().find(|(kk, _)| kk == k).map(|(_, v)| v)?
            }
            (Json::Array(a), Seg::Index(i)) => a.get_mut(*i)?,
            _ => return None,
        };
    }
    match (cur, segs.last()?) {
        (Json::Object(m), Seg::Key(k)) => {
            let slot = m.iter_mut().find(|(kk, _)| kk == k);
            match (slot, mode) {
                (Some(s), SetMode::Set) | (Some(s), SetMode::Replace) => s.1 = value,
                (None, SetMode::Set) | (None, SetMode::Insert) => m.push((k.clone(), value)),
                _ => {}
            }
        }
        (Json::Array(a), Seg::Index(i)) => {
            let exists = *i < a.len();
            match mode {
                SetMode::Set if exists => a[*i] = value,
                SetMode::Replace if exists => a[*i] = value,
                SetMode::Set | SetMode::Insert if !exists => a.push(value),
                _ => {}
            }
        }
        _ => return None,
    }
    Some(())
}

/// Remove the element at `path` from `root` if present.
pub fn remove_path(root: &mut Json, path: &str) -> Option<()> {
    let segs = parse_path(path)?;
    if segs.is_empty() {
        return None; // `$` cannot be removed
    }
    let mut cur = root;
    for seg in &segs[..segs.len() - 1] {
        cur = match (cur, seg) {
            (Json::Object(m), Seg::Key(k)) => {
                m.iter_mut().find(|(kk, _)| kk == k).map(|(_, v)| v)?
            }
            (Json::Array(a), Seg::Index(i)) => a.get_mut(*i)?,
            _ => return None,
        };
    }
    match (cur, segs.last()?) {
        (Json::Object(m), Seg::Key(k)) => m.retain(|(kk, _)| kk != k),
        (Json::Array(a), Seg::Index(i)) if *i < a.len() => {
            a.remove(*i);
        }
        _ => {}
    }
    Some(())
}

/// Apply an RFC 7396 JSON merge patch: object members merge recursively, a member
/// whose patch value is `null` is removed, and a non-object patch replaces the
/// target outright.
pub fn merge_patch(target: &mut Json, patch: &Json) {
    let Json::Object(pm) = patch else {
        *target = patch.clone();
        return;
    };
    if !matches!(target, Json::Object(_)) {
        *target = Json::Object(Vec::new());
    }
    let Json::Object(tm) = target else {
        return;
    };
    for (k, pv) in pm {
        if matches!(pv, Json::Null) {
            tm.retain(|(kk, _)| kk != k);
        } else if let Some(slot) = tm.iter_mut().find(|(kk, _)| kk == k) {
            merge_patch(&mut slot.1, pv);
        } else {
            tm.push((k.clone(), Json::Null));
            let slot = tm.last_mut().unwrap();
            merge_patch(&mut slot.1, pv);
        }
    }
}