faucet-source-oracle-cdc 1.2.2

Oracle Database CDC (LogMiner) source for the faucet-stream ecosystem
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
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
//! Parser for LogMiner `SQL_REDO` text (mined with `NO_ROWID_IN_STMT` +
//! `NO_SQL_DELIMITER`). Pure — every shape here was captured from a real
//! Oracle 23ai redo stream.
//!
//! ```text
//! insert into "APP"."T"("ID","NAME") values ('1','it''s')
//! update "APP"."T" set "NAME" = 'bob', "AMT" = NULL where "ID" = '1' and "AMT" IS NULL
//! delete from "APP"."T" where "ID" = '1' and "D" = TO_DATE('2024-01-02 00:00:00', 'YYYY-MM-DD HH24:MI:SS')
//! DECLARE ... BEGIN select "NOTE" into loc_c from "APP"."T" where "ID" = '1' for update;
//!   buf_c := 'aaa'; dbms_lob.write(loc_c, 3, 1, buf_c); END;
//! ```

use std::collections::HashMap;

use faucet_common_oracle::hex_to_bytes;

/// A literal from redo text, before typing against the column.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Resolved {
    /// SQL `NULL`.
    Null,
    /// Text of a quoted literal, number or `TO_*(...)` call.
    Text(String),
    /// Bytes of a `HEXTORAW(...)`.
    Bytes(Vec<u8>),
    /// `EMPTY_CLOB()` / `EMPTY_BLOB()` — content follows as LOB writes.
    EmptyLob,
}

/// Ordered `column → value` pairs.
pub type Image = Vec<(String, Resolved)>;

/// The DML statement kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DmlKind {
    /// `insert into … values …`
    Insert,
    /// `update … set … where …`
    Update,
    /// `delete from … where …`
    Delete,
}

/// A parsed DML statement.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Dml {
    /// Statement kind.
    pub kind: DmlKind,
    /// Owner.
    pub owner: String,
    /// Table.
    pub table: String,
    /// Inserted values (`insert`) or assignments (`update`).
    pub set: Image,
    /// `where` equalities / `IS NULL` tests — the before image.
    pub conditions: Image,
}

/// One `dbms_lob.write` applied to a LOB column.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LobPiece {
    /// 1-based offset (characters for CLOB, bytes for BLOB).
    pub offset: u64,
    /// The written data.
    pub data: Resolved,
}

/// A parsed LOB change block (`LOB_WRITE` / `LOB_TRIM`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LobChange {
    /// Owner.
    pub owner: String,
    /// Table.
    pub table: String,
    /// The LOB column.
    pub column: String,
    /// Row identity from the locator `select … where …`.
    pub conditions: Image,
    /// Writes, in order.
    pub writes: Vec<LobPiece>,
    /// Final length after a `dbms_lob.trim`.
    pub trim: Option<u64>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum Tok {
    Ident(String),
    Str(String),
    Word(String),
    Sym(&'static str),
}

fn tokenize(s: &str) -> Result<Vec<Tok>, String> {
    let chars: Vec<char> = s.chars().collect();
    let mut out = Vec::new();
    let mut i = 0;
    while i < chars.len() {
        let c = chars[i];
        match c {
            c if c.is_whitespace() => i += 1,
            '"' => {
                let end = chars[i + 1..]
                    .iter()
                    .position(|&ch| ch == '"')
                    .ok_or("unterminated quoted identifier")?;
                out.push(Tok::Ident(chars[i + 1..i + 1 + end].iter().collect()));
                i += end + 2;
            }
            '\'' => {
                let mut text = String::new();
                i += 1;
                loop {
                    match chars.get(i) {
                        None => return Err("unterminated string literal".into()),
                        Some('\'') if chars.get(i + 1) == Some(&'\'') => {
                            text.push('\'');
                            i += 2;
                        }
                        Some('\'') => {
                            i += 1;
                            break;
                        }
                        Some(&ch) => {
                            text.push(ch);
                            i += 1;
                        }
                    }
                }
                out.push(Tok::Str(text));
            }
            '(' | ')' | ',' | '=' | '.' | ';' => {
                out.push(Tok::Sym(match c {
                    '(' => "(",
                    ')' => ")",
                    ',' => ",",
                    '=' => "=",
                    '.' => ".",
                    _ => ";",
                }));
                i += 1;
            }
            '|' if chars.get(i + 1) == Some(&'|') => {
                out.push(Tok::Sym("||"));
                i += 2;
            }
            ':' if chars.get(i + 1) == Some(&'=') => {
                out.push(Tok::Sym(":="));
                i += 2;
            }
            c if c.is_ascii_digit()
                || ((c == '-' || c == '+')
                    && chars
                        .get(i + 1)
                        .is_some_and(|d| d.is_ascii_digit() || *d == '.')) =>
            {
                let start = i;
                i += 1;
                while i < chars.len() {
                    let ch = chars[i];
                    let exp_sign = (ch == '+' || ch == '-') && matches!(chars[i - 1], 'e' | 'E');
                    if ch.is_ascii_digit() || ch == '.' || ch == 'e' || ch == 'E' || exp_sign {
                        i += 1;
                    } else {
                        break;
                    }
                }
                out.push(Tok::Word(chars[start..i].iter().collect()));
            }
            c if c.is_alphanumeric() || c == '_' || c == '$' || c == '#' => {
                let start = i;
                while i < chars.len()
                    && (chars[i].is_alphanumeric() || matches!(chars[i], '_' | '$' | '#'))
                {
                    i += 1;
                }
                out.push(Tok::Word(chars[start..i].iter().collect()));
            }
            other => return Err(format!("unexpected character {other:?} in redo")),
        }
    }
    Ok(out)
}

struct Cursor {
    toks: Vec<Tok>,
    pos: usize,
}

impl Cursor {
    fn peek(&self) -> Option<&Tok> {
        self.toks.get(self.pos)
    }

    fn next(&mut self) -> Option<Tok> {
        let t = self.toks.get(self.pos).cloned();
        self.pos += 1;
        t
    }

    fn at_word(&self, w: &str) -> bool {
        matches!(self.peek(), Some(Tok::Word(x)) if x.eq_ignore_ascii_case(w))
    }

    fn at_sym(&self, s: &str) -> bool {
        matches!(self.peek(), Some(Tok::Sym(x)) if *x == s)
    }

    fn word(&mut self, w: &str) -> Result<(), String> {
        if self.at_word(w) {
            self.pos += 1;
            Ok(())
        } else {
            Err(format!("expected `{w}`, found {:?}", self.peek()))
        }
    }

    fn sym(&mut self, s: &str) -> Result<(), String> {
        if self.at_sym(s) {
            self.pos += 1;
            Ok(())
        } else {
            Err(format!("expected `{s}`, found {:?}", self.peek()))
        }
    }

    fn ident(&mut self) -> Result<String, String> {
        match self.next() {
            Some(Tok::Ident(s)) => Ok(s),
            other => Err(format!("expected a quoted identifier, found {other:?}")),
        }
    }

    fn table_ref(&mut self) -> Result<(String, String), String> {
        let first = self.ident()?;
        if self.at_sym(".") {
            self.pos += 1;
            Ok((first, self.ident()?))
        } else {
            Ok((String::new(), first))
        }
    }

    fn value(&mut self) -> Result<Resolved, String> {
        let mut v = self.term()?;
        while self.at_sym("||") {
            self.pos += 1;
            let rhs = self.term()?;
            v = concat(v, rhs)?;
        }
        Ok(v)
    }

    fn term(&mut self) -> Result<Resolved, String> {
        match self.next() {
            Some(Tok::Str(s)) => Ok(Resolved::Text(s)),
            Some(Tok::Word(w)) if w.eq_ignore_ascii_case("NULL") => Ok(Resolved::Null),
            Some(Tok::Word(w)) if self.at_sym("(") => {
                self.pos += 1;
                let mut args = Vec::new();
                if !self.at_sym(")") {
                    args.push(self.value()?);
                    while self.at_sym(",") {
                        self.pos += 1;
                        args.push(self.value()?);
                    }
                }
                self.sym(")")?;
                apply_function(&w, args)
            }
            Some(Tok::Word(w))
                if w.starts_with(|c: char| c.is_ascii_digit() || c == '-' || c == '+') =>
            {
                Ok(Resolved::Text(w))
            }
            other => Err(format!("unexpected value token {other:?}")),
        }
    }

    /// `"C" = v [and "D" IS NULL]…`, stopping at the end or at `stop`.
    fn conditions(&mut self, stop: Option<&str>) -> Result<Image, String> {
        let mut out = Vec::new();
        loop {
            if self.peek().is_none() || self.at_sym(";") || stop.is_some_and(|s| self.at_word(s)) {
                break;
            }
            if self.at_word("ROWID") {
                self.pos += 1;
                self.sym("=")?;
                self.value()?;
            } else {
                let col = self.ident()?;
                if self.at_word("IS") {
                    self.pos += 1;
                    self.word("NULL")?;
                    out.push((col, Resolved::Null));
                } else {
                    self.sym("=")?;
                    out.push((col, self.value()?));
                }
            }
            if self.at_word("and") {
                self.pos += 1;
            } else {
                break;
            }
        }
        Ok(out)
    }

    fn expect_end(&mut self) -> Result<(), String> {
        while self.at_sym(";") {
            self.pos += 1;
        }
        match self.peek() {
            None => Ok(()),
            Some(t) => Err(format!("unexpected trailing token {t:?}")),
        }
    }
}

fn concat(a: Resolved, b: Resolved) -> Result<Resolved, String> {
    let text = |r: Resolved| match r {
        Resolved::Null | Resolved::EmptyLob => Ok(String::new()),
        Resolved::Text(s) => Ok(s),
        Resolved::Bytes(_) => Err("cannot concatenate a RAW value".to_string()),
    };
    Ok(Resolved::Text(text(a)? + &text(b)?))
}

fn apply_function(name: &str, args: Vec<Resolved>) -> Result<Resolved, String> {
    let first = || args.first().cloned().unwrap_or(Resolved::Null);
    match name.to_ascii_uppercase().as_str() {
        "TO_DATE" | "TO_TIMESTAMP" | "TO_TIMESTAMP_TZ" | "TO_DSINTERVAL" | "TO_YMINTERVAL"
        | "TO_NUMBER" | "TO_BINARY_DOUBLE" | "TO_BINARY_FLOAT" | "TO_CHAR" | "TO_NCHAR"
        | "TO_CLOB" | "TO_NCLOB" => Ok(first()),
        "HEXTORAW" => match first() {
            Resolved::Text(h) => hex_to_bytes(&h)
                .map(Resolved::Bytes)
                .ok_or_else(|| format!("invalid HEXTORAW literal {h:?}")),
            other => Ok(other),
        },
        "UNISTR" => match first() {
            Resolved::Text(s) => decode_unistr(&s).map(Resolved::Text),
            other => Ok(other),
        },
        "EMPTY_CLOB" | "EMPTY_BLOB" => Ok(Resolved::EmptyLob),
        other => Err(format!("unsupported function {other}() in redo")),
    }
}

/// Decode `UNISTR` escapes: `\XXXX` UTF-16 code units, `\\` a backslash.
pub fn decode_unistr(s: &str) -> Result<String, String> {
    let mut units: Vec<u16> = Vec::new();
    let mut out = String::new();
    let flush = |units: &mut Vec<u16>, out: &mut String| -> Result<(), String> {
        if !units.is_empty() {
            out.push_str(&String::from_utf16(units).map_err(|e| format!("bad UNISTR: {e}"))?);
            units.clear();
        }
        Ok(())
    };
    let chars: Vec<char> = s.chars().collect();
    let mut i = 0;
    while i < chars.len() {
        if chars[i] == '\\' {
            if chars.get(i + 1) == Some(&'\\') {
                flush(&mut units, &mut out)?;
                out.push('\\');
                i += 2;
                continue;
            }
            let hex: String = chars
                .get(i + 1..i + 5)
                .ok_or("truncated UNISTR escape")?
                .iter()
                .collect();
            units.push(
                u16::from_str_radix(&hex, 16).map_err(|_| format!("bad UNISTR escape {hex}"))?,
            );
            i += 5;
        } else {
            flush(&mut units, &mut out)?;
            out.push(chars[i]);
            i += 1;
        }
    }
    flush(&mut units, &mut out)?;
    Ok(out)
}

/// Parse an `insert` / `update` / `delete` redo statement.
pub fn parse_dml(sql: &str) -> Result<Dml, String> {
    let mut c = Cursor {
        toks: tokenize(sql)?,
        pos: 0,
    };
    let dml = if c.at_word("insert") {
        c.pos += 1;
        c.word("into")?;
        let (owner, table) = c.table_ref()?;
        c.sym("(")?;
        let mut cols = vec![c.ident()?];
        while c.at_sym(",") {
            c.pos += 1;
            cols.push(c.ident()?);
        }
        c.sym(")")?;
        c.word("values")?;
        c.sym("(")?;
        let mut vals = vec![c.value()?];
        while c.at_sym(",") {
            c.pos += 1;
            vals.push(c.value()?);
        }
        c.sym(")")?;
        if cols.len() != vals.len() {
            return Err(format!("{} columns but {} values", cols.len(), vals.len()));
        }
        Dml {
            kind: DmlKind::Insert,
            owner,
            table,
            set: cols.into_iter().zip(vals).collect(),
            conditions: Vec::new(),
        }
    } else if c.at_word("update") {
        c.pos += 1;
        let (owner, table) = c.table_ref()?;
        c.word("set")?;
        let mut set = Vec::new();
        loop {
            let col = c.ident()?;
            c.sym("=")?;
            set.push((col, c.value()?));
            if c.at_sym(",") {
                c.pos += 1;
            } else {
                break;
            }
        }
        let conditions = if c.at_word("where") {
            c.pos += 1;
            c.conditions(None)?
        } else {
            Vec::new()
        };
        Dml {
            kind: DmlKind::Update,
            owner,
            table,
            set,
            conditions,
        }
    } else if c.at_word("delete") {
        c.pos += 1;
        c.word("from")?;
        let (owner, table) = c.table_ref()?;
        let conditions = if c.at_word("where") {
            c.pos += 1;
            c.conditions(None)?
        } else {
            Vec::new()
        };
        Dml {
            kind: DmlKind::Delete,
            owner,
            table,
            set: Vec::new(),
            conditions,
        }
    } else {
        return Err(format!("not a DML statement: {}", truncate(sql)));
    };
    c.expect_end()?;
    Ok(dml)
}

/// Parse a `LOB_WRITE` / `LOB_TRIM` PL/SQL block.
pub fn parse_lob_change(sql: &str) -> Result<LobChange, String> {
    let mut c = Cursor {
        toks: tokenize(sql)?,
        pos: 0,
    };
    let mut target: Option<(String, String, String, Image)> = None;
    let mut buffer: Option<Resolved> = None;
    let mut writes = Vec::new();
    let mut trim = None;
    while let Some(tok) = c.next() {
        let Tok::Word(w) = tok else { continue };
        if w.eq_ignore_ascii_case("select") && matches!(c.peek(), Some(Tok::Ident(_))) {
            let column = c.ident()?;
            c.word("into")?;
            c.next();
            c.word("from")?;
            let (owner, table) = c.table_ref()?;
            let conditions = if c.at_word("where") {
                c.pos += 1;
                c.conditions(Some("for"))?
            } else {
                Vec::new()
            };
            target = Some((owner, table, column, conditions));
        } else if w.to_ascii_lowercase().starts_with("buf_") && c.at_sym(":=") {
            c.pos += 1;
            buffer = Some(c.value()?);
        } else if w.eq_ignore_ascii_case("dbms_lob") && c.at_sym(".") {
            c.pos += 1;
            let op = match c.next() {
                Some(Tok::Word(op)) => op.to_ascii_lowercase(),
                other => return Err(format!("expected a dbms_lob call, found {other:?}")),
            };
            c.sym("(")?;
            let mut args = Vec::new();
            while !c.at_sym(")") {
                match c.next() {
                    Some(Tok::Word(a)) => args.push(a),
                    Some(Tok::Sym(",")) => {}
                    other => return Err(format!("unexpected dbms_lob argument {other:?}")),
                }
            }
            c.sym(")")?;
            let num = |i: usize| -> Result<u64, String> {
                args.get(i)
                    .and_then(|a| a.parse::<u64>().ok())
                    .ok_or_else(|| format!("dbms_lob.{op}: bad argument {i}"))
            };
            match op.as_str() {
                "write" => writes.push(LobPiece {
                    offset: num(2)?.max(1),
                    data: buffer.clone().ok_or("dbms_lob.write before any buffer")?,
                }),
                "trim" => trim = Some(num(1)?),
                other => return Err(format!("unsupported dbms_lob.{other}")),
            }
        }
    }
    let (owner, table, column, conditions) = target.ok_or("LOB change without a locator select")?;
    Ok(LobChange {
        owner,
        table,
        column,
        conditions,
        writes,
        trim,
    })
}

/// Whether the changes a transaction made to one LOB rewrite the whole value:
/// writes covering it from offset 1 without a gap, in any logged order, and no
/// trim, so the result does not depend on the value it replaced. An in-place
/// overwrite of a longer value's prefix logs the same pieces and is
/// indistinguishable here (documented in the README).
pub fn is_full_rewrite_all(changes: &[LobChange]) -> bool {
    if changes.iter().any(|c| c.trim.is_some()) {
        return false;
    }
    let writes: Vec<&LobPiece> = changes.iter().flat_map(|c| &c.writes).collect();
    if writes.is_empty() {
        return false;
    }
    let mut pieces: Vec<_> = unit_offsets(&writes).into_iter().zip(writes).collect();
    pieces.sort_by_key(|(offset, _)| *offset);
    let mut end = 1u64;
    for (offset, w) in pieces {
        if offset > end {
            return false;
        }
        let len = match &w.data {
            Resolved::Bytes(b) => b.len(),
            Resolved::Text(t) => t.encode_utf16().count(),
            _ => 0,
        } as u64;
        end = end.max(offset + len);
    }
    true
}

/// Each write's offset in UTF-16 code units. A caller's `dbms_lob.write` and
/// `trim` are logged in UTF-16 units, but when LogMiner splits one write into
/// pieces, each piece after the first starts at the previous piece's offset
/// plus its *character* count, so a supplementary-plane character shifts every
/// later piece of the chain back by one unit.
fn unit_offsets(writes: &[&LobPiece]) -> Vec<u64> {
    let mut order: Vec<usize> = (0..writes.len()).collect();
    order.sort_by_key(|&i| writes[i].offset);
    let mut shift_at_end: HashMap<u64, u64> = HashMap::new();
    let mut offsets = vec![0; writes.len()];
    for i in order {
        let w = writes[i];
        let shift = shift_at_end.get(&w.offset).copied().unwrap_or(0);
        offsets[i] = w.offset + shift;
        if let Resolved::Text(t) = &w.data {
            let chars = t.chars().count() as u64;
            let units = t.encode_utf16().count() as u64;
            shift_at_end.insert(w.offset + chars, shift + units - chars);
        }
    }
    offsets
}

/// Apply every change a transaction made to one LOB to its current value, in
/// logged order (each change's writes, then its trim). CLOB positions are
/// UTF-16 code units, as Oracle counts them, resolved over all the changes
/// together since the pieces of one write can arrive in any order (see
/// [`unit_offsets`]).
pub fn apply_lob_all(current: &Resolved, changes: &[LobChange]) -> Resolved {
    let writes: Vec<&LobPiece> = changes.iter().flat_map(|c| &c.writes).collect();
    let binary = matches!(current, Resolved::Bytes(_))
        || writes.iter().any(|w| matches!(w.data, Resolved::Bytes(_)));
    if binary {
        let mut bytes = match current {
            Resolved::Bytes(b) => b.clone(),
            _ => Vec::new(),
        };
        for change in changes {
            for w in &change.writes {
                let data = match &w.data {
                    Resolved::Bytes(b) => b.clone(),
                    Resolved::Text(t) => t.as_bytes().to_vec(),
                    _ => Vec::new(),
                };
                let at = (w.offset - 1) as usize;
                if bytes.len() < at + data.len() {
                    bytes.resize(at + data.len(), 0);
                }
                bytes[at..at + data.len()].copy_from_slice(&data);
            }
            if let Some(n) = change.trim {
                bytes.truncate(n as usize);
            }
        }
        return Resolved::Bytes(bytes);
    }
    let mut offsets = unit_offsets(&writes).into_iter();
    let mut units: Vec<u16> = match current {
        Resolved::Text(t) => t.encode_utf16().collect(),
        _ => Vec::new(),
    };
    for change in changes {
        for (w, offset) in change.writes.iter().zip(offsets.by_ref()) {
            let data: Vec<u16> = match &w.data {
                Resolved::Text(t) => t.encode_utf16().collect(),
                _ => Vec::new(),
            };
            let at = (offset - 1) as usize;
            if units.len() < at + data.len() {
                units.resize(at + data.len(), u16::from(b' '));
            }
            units[at..at + data.len()].copy_from_slice(&data);
        }
        if let Some(n) = change.trim {
            units.truncate(n as usize);
        }
    }
    Resolved::Text(String::from_utf16_lossy(&units))
}

fn truncate(s: &str) -> String {
    s.chars().take(120).collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    fn is_full_rewrite(change: &LobChange) -> bool {
        is_full_rewrite_all(std::slice::from_ref(change))
    }

    fn apply_lob(current: &Resolved, change: &LobChange) -> Resolved {
        apply_lob_all(current, std::slice::from_ref(change))
    }

    fn t(s: &str) -> Resolved {
        Resolved::Text(s.into())
    }

    #[test]
    fn insert_with_every_literal_shape() {
        let sql = r#"insert into "FAUCET"."CDC_U"("ID","NAME","AMT","D","TS","TSZ","BIN","NV","NOTE","IDS","IYM","F") values ('1','it''s','12.5',TO_DATE('2024-01-02 00:00:00', 'YYYY-MM-DD HH24:MI:SS'),TO_TIMESTAMP('2024-01-02 03:04:05.500000000'),TO_TIMESTAMP_TZ('2024-01-02 03:04:05.000000000 +05:30'),HEXTORAW('0102'),UNISTR('h\00E9llo'),EMPTY_CLOB(),TO_DSINTERVAL('+01 02:03:04.500000'),TO_YMINTERVAL('+01-02'),'2.5E+000')"#;
        let d = parse_dml(sql).unwrap();
        assert_eq!(d.kind, DmlKind::Insert);
        assert_eq!((d.owner.as_str(), d.table.as_str()), ("FAUCET", "CDC_U"));
        let get = |c: &str| d.set.iter().find(|(k, _)| k == c).unwrap().1.clone();
        assert_eq!(get("ID"), t("1"));
        assert_eq!(get("NAME"), t("it's"));
        assert_eq!(get("D"), t("2024-01-02 00:00:00"));
        assert_eq!(get("TSZ"), t("2024-01-02 03:04:05.000000000 +05:30"));
        assert_eq!(get("BIN"), Resolved::Bytes(vec![1, 2]));
        assert_eq!(get("NV"), t("héllo"));
        assert_eq!(get("NOTE"), Resolved::EmptyLob);
        assert_eq!(get("IDS"), t("+01 02:03:04.500000"));
        assert_eq!(get("F"), t("2.5E+000"));
        assert!(d.conditions.is_empty());
    }

    #[test]
    fn update_and_delete_conditions() {
        let d = parse_dml(
            r#"update "A"."T" set "NAME" = 'bob', "AMT" = NULL where "ID" = '1' and "AMT" IS NULL and ROWID = 'AAAR5J'"#,
        )
        .unwrap();
        assert_eq!(d.kind, DmlKind::Update);
        assert_eq!(
            d.set,
            vec![("NAME".into(), t("bob")), ("AMT".into(), Resolved::Null)]
        );
        assert_eq!(
            d.conditions,
            vec![("ID".into(), t("1")), ("AMT".into(), Resolved::Null)]
        );

        let d = parse_dml(r#"delete from "A"."T" where "ID" = 12.5 and "N" = -3;"#).unwrap();
        assert_eq!(d.kind, DmlKind::Delete);
        assert_eq!(
            d.conditions,
            vec![("ID".into(), t("12.5")), ("N".into(), t("-3"))]
        );

        let d = parse_dml(r#"delete from "T""#).unwrap();
        assert_eq!(d.owner, "");
        assert!(d.conditions.is_empty());
        let d = parse_dml(r#"update "T" set "A" = 'x'"#).unwrap();
        assert!(d.conditions.is_empty());
    }

    #[test]
    fn concatenation_and_numbers() {
        let d = parse_dml(r#"insert into "A"."T"("S","E","P") values ('ab' || NULL || UNISTR('\0063'), 1.5E+10, +4)"#)
            .unwrap();
        assert_eq!(d.set[0].1, t("abc"));
        assert_eq!(d.set[1].1, t("1.5E+10"));
        assert_eq!(d.set[2].1, t("+4"));
    }

    #[test]
    fn malformed_redo_is_an_error() {
        for bad in [
            "set transaction read write",
            r#"insert into "A"."T"("X") values ('1', '2')"#,
            r#"insert into "A"."T"("X") values (FOO('1'))"#,
            r#"insert into "A"."T"("X") values (HEXTORAW('zz'))"#,
            r#"insert into "A"."T"("X") values ('1') extra"#,
            r#"insert into "A"."T"("X) values ('1')"#,
            r#"insert into "A"."T"("X") values ('1)"#,
            r#"insert into "A"."T"("X") values ('a' || HEXTORAW('01'))"#,
            r#"update "A"."T" set "X" = 'a' where "Y" IS 'b'"#,
            r#"update "A"."T" set "X" 'a'"#,
            r#"update A set "X" = 'a'"#,
            r#"delete "A"."T""#,
            "insert into \"A\".\"T\"(\"X\") values (@)",
            r#"insert into "A"."T"("X") values (INTO)"#,
        ] {
            assert!(parse_dml(bad).is_err(), "{bad}");
        }
    }

    #[test]
    fn unistr_decoding() {
        assert_eq!(decode_unistr(r"h\00E9llo").unwrap(), "héllo");
        assert_eq!(decode_unistr(r"\D83D\DE00!").unwrap(), "😀!");
        assert_eq!(decode_unistr(r"a\\b").unwrap(), r"a\b");
        assert!(decode_unistr(r"\00").is_err());
        assert!(decode_unistr(r"\ZZZZ").is_err());
        assert!(decode_unistr(r"\D83D").is_err());
        assert_eq!(
            apply_function("UNISTR", vec![Resolved::Null]).unwrap(),
            Resolved::Null
        );
        assert_eq!(apply_function("HEXTORAW", vec![]).unwrap(), Resolved::Null);
        assert_eq!(apply_function("TO_DATE", vec![]).unwrap(), Resolved::Null);
    }

    const LOB_WRITE: &str = "DECLARE\n loc_c CLOB;\n buf_c VARCHAR2(6156);\n loc_b BLOB;\n buf_b RAW(6156);\n loc_nc NCLOB;\n buf_nc NVARCHAR2(6156);\n e_len NUMBER;\nBEGIN\n select \"NOTE\" into loc_c from \"FAUCET\".\"LOB_V\" where \"ID\" = '1' for update;\n\n buf_c := 'aa''b';\n  dbms_lob.write(loc_c, 4, 3, buf_c);\nEND;";

    #[test]
    fn lob_write_block() {
        let c = parse_lob_change(LOB_WRITE).unwrap();
        assert_eq!(
            (c.owner.as_str(), c.table.as_str(), c.column.as_str()),
            ("FAUCET", "LOB_V", "NOTE")
        );
        assert_eq!(c.conditions, vec![("ID".into(), t("1"))]);
        assert_eq!(
            c.writes,
            vec![LobPiece {
                offset: 3,
                data: t("aa'b")
            }]
        );
        assert_eq!(apply_lob(&t("xy"), &c), t("xyaa'b"));
        assert_eq!(apply_lob(&Resolved::EmptyLob, &c), t("  aa'b"));
        assert_eq!(apply_lob(&t("0123456789"), &c), t("01aa'b6789"));
    }

    #[test]
    fn full_rewrite_and_utf16_offsets() {
        let piece = |offset, s: &str| LobPiece { offset, data: t(s) };
        let mk = |writes, trim| LobChange {
            owner: "A".into(),
            table: "T".into(),
            column: "C".into(),
            conditions: vec![],
            writes,
            trim,
        };
        assert!(is_full_rewrite(&mk(
            vec![piece(1, "ab"), piece(3, "c")],
            None
        )));
        assert!(!is_full_rewrite(&mk(
            vec![piece(1, "ab"), piece(4, "c")],
            None
        )));
        assert!(!is_full_rewrite(&mk(vec![piece(2, "ab")], None)));
        assert!(!is_full_rewrite(&mk(vec![piece(1, "ab")], Some(1))));
        assert!(!is_full_rewrite(&mk(vec![], None)));
        assert!(is_full_rewrite(&mk(
            vec![
                LobPiece {
                    offset: 1,
                    data: Resolved::Bytes(vec![1, 2])
                },
                LobPiece {
                    offset: 3,
                    data: Resolved::Null
                },
            ],
            None
        )));
        // An emoji is two UTF-16 units, so the write at 4 lands after it.
        let c = mk(vec![piece(4, "x")], None);
        assert_eq!(apply_lob(&t("a😀b"), &c), t("a😀x"));
    }

    /// Piece layouts as Oracle 23 LogMiner logs them (#862 L-058).
    #[test]
    fn chained_pieces_advance_by_characters() {
        let piece = |offset, s: String| LobPiece {
            offset,
            data: Resolved::Text(s),
        };
        let mk = |writes, trim| LobChange {
            owner: "A".into(),
            table: "T".into(),
            column: "C".into(),
            conditions: vec![],
            writes,
            trim,
        };
        let r = |c: &str, n| c.repeat(n);
        // An inserted value of 4000 x, an emoji and 3000 y: pieces logged out
        // of order, each after the emoji's piece one unit early.
        let insert = mk(
            vec![
                piece(3067, format!("{}😀{}", r("x", 934), r("y", 28))),
                piece(1023, r("x", 1022)),
                piece(1, r("x", 1022)),
                piece(2045, r("x", 1022)),
                piece(5052, r("y", 1022)),
                piece(6074, r("y", 928)),
                piece(4030, r("y", 1022)),
            ],
            None,
        );
        let value = format!("{}😀{}", r("x", 4000), r("y", 3000));
        assert!(is_full_rewrite(&insert));
        assert_eq!(
            apply_lob(&Resolved::Null, &insert),
            Resolved::Text(value.clone())
        );

        // A caller's write is in UTF-16 units; its chain starts there.
        let write = mk(
            vec![
                piece(1032, format!("{}😀{}", r("a", 478), r("b", 542))),
                piece(10, r("a", 1022)),
                piece(2053, r("b", 458)),
            ],
            None,
        );
        let expected = format!(
            "{}{}😀{}{}",
            r("x", 9),
            r("a", 1500),
            r("b", 1000),
            &value[9 + 2502..]
        );
        assert!(!is_full_rewrite(&write));
        assert_eq!(
            apply_lob(&Resolved::Text(value.clone()), &write),
            Resolved::Text(expected)
        );

        // A lone caller write and trim after the emoji stay in UTF-16 units.
        let patch = mk(vec![piece(4004, "ZQ".into())], Some(5000));
        let Resolved::Text(out) = apply_lob(&Resolved::Text(value), &patch) else {
            panic!("text")
        };
        assert_eq!(out.encode_utf16().count(), 5000);
        assert_eq!(&out[3997..4009], "xxx😀yZQyy");
    }

    #[test]
    fn blob_write_and_trim() {
        let sql = "DECLARE loc_b BLOB; buf_b RAW(10); BEGIN select \"B\" into loc_b from \"A\".\"T\" where \"ID\" = '2' for update; buf_b := HEXTORAW('ABCD'); dbms_lob.write(loc_b, 2, 0, buf_b); dbms_lob.trim(loc_b, 1); END;";
        let c = parse_lob_change(sql).unwrap();
        assert_eq!(c.writes[0].offset, 1);
        assert_eq!(c.trim, Some(1));
        assert_eq!(apply_lob(&Resolved::Null, &c), Resolved::Bytes(vec![0xAB]));
        assert_eq!(
            apply_lob(&Resolved::Bytes(vec![1, 2, 3]), &c),
            Resolved::Bytes(vec![0xAB])
        );
        let trim_only = "DECLARE loc_c CLOB; BEGIN select \"N\" into loc_c from \"A\".\"T\" where \"ID\" = '2' for update; dbms_lob.trim(loc_c, 2); END;";
        let c = parse_lob_change(trim_only).unwrap();
        assert_eq!(apply_lob(&t("hello"), &c), t("he"));
        let mut mixed = c.clone();
        mixed.writes.push(LobPiece {
            offset: 1,
            data: t("Z"),
        });
        mixed.trim = None;
        assert_eq!(
            apply_lob(&Resolved::Bytes(vec![1]), &mixed),
            Resolved::Bytes(b"Z".to_vec())
        );
        mixed.writes[0].data = Resolved::Null;
        assert_eq!(apply_lob(&t("q"), &mixed), t("q"));
        assert_eq!(
            apply_lob(&Resolved::Bytes(vec![9]), &mixed),
            Resolved::Bytes(vec![9])
        );
    }

    #[test]
    fn lob_block_errors() {
        assert!(parse_lob_change("BEGIN dbms_lob.write(loc_c, 1, 1, buf_c); END;").is_err());
        assert!(parse_lob_change("BEGIN END;").is_err());
        let no_select = "BEGIN buf_c := 'a'; END;";
        assert!(parse_lob_change(no_select).is_err());
        let erase = "BEGIN select \"N\" into loc_c from \"A\".\"T\" where \"ID\" = '1' for update; dbms_lob.erase(loc_c, 1, 1); END;";
        assert!(parse_lob_change(erase).is_err());
        let bad_arg = "BEGIN select \"N\" into loc_c from \"A\".\"T\" for update; buf_c := 'a'; dbms_lob.write(loc_c, 1, x, buf_c); END;";
        assert!(parse_lob_change(bad_arg).is_err());
        let str_arg = "BEGIN select \"N\" into loc_c from \"A\".\"T\" for update; buf_c := 'a'; dbms_lob.write(loc_c, 'x'); END;";
        assert!(parse_lob_change(str_arg).is_err());
        let not_call =
            "BEGIN select \"N\" into loc_c from \"A\".\"T\" for update; dbms_lob.(x); END;";
        assert!(parse_lob_change(not_call).is_err());
        let no_where = "BEGIN select \"N\" into loc_c from \"A\".\"T\" for update; END;";
        assert!(parse_lob_change(no_where).unwrap().conditions.is_empty());
    }
}