sql-splitter 1.18.2

High-performance CLI tool for splitting large SQL dump files into individual table files
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
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
//! Stream a SQL dump into a neutral [`DumpProfile`] in a single pass.
//!
//! [`DumpProfiler`] drives the production parser's [`Parser::visit_events`]
//! visitor: DDL statements build schema evidence as they arrive, and each
//! decoded data row is routed — value by value, by column identity — into the
//! per-column bounded sketches from [`crate::profile::sketches`]. Nothing here
//! buffers a whole INSERT/COPY block: the visitor delivers one tuple / one COPY
//! line at a time, so resident memory is bounded by the [`ProfileBudget`], never
//! by the row count.
//!
//! # Depths
//! * [`ProfileDepth::Schema`] reads no non-null values — it counts rows and,
//!   per column, total/null tallies when the schema is available, producing
//!   the portable schema with no value-derived evidence.
//! * [`ProfileDepth::Basic`] adds the cheap per-column metrics: distinct
//!   estimate, min/max, quantiles, string shape, length, top-k, and a bounded
//!   sample.
//! * [`ProfileDepth::Full`] additionally computes pairwise evidence for the
//!   *bounded* candidate set: declared foreign-key pairs (child→parent coverage)
//!   and same-table temporal orderings. Planner-nominated pairs plug in through
//!   the same [`RelationshipEvidence`] surface.
//!
//! Every depth returns the *same* portable schema and exact table row counts.
//! Schema-late data that exceeds its bounded replay buffer retains partial
//! column evidence; the table and column confidence values report that gap.
//! The depths otherwise differ only in how much value-derived evidence they
//! attach.

use std::collections::HashSet;
use std::io::Read;
use std::path::Path;

use ahash::AHashMap;

use crate::diagnostic::{codes, Diagnostic};
use crate::parser::mysql_insert::{
    hash_pk_tuple, parse_insert_tuple, InsertRowContext, ParsedRow, PkTuple, PkValue, RowExtraction,
};
use crate::parser::postgres_copy::{parse_copy_columns, CopyParser, ParsedCopyRow};
use crate::parser::{
    detect_dialect_from_file, determine_buffer_size, Parser, ParserEvent, RowFlow, SqlDialect,
    StatementType, SMALL_BUFFER_SIZE,
};
use crate::schema::{Column, ColumnType, Schema, SchemaBuilder, TableId, TableSchema};
use crate::synthetic::schema::PortableSchema;

use super::evidence::{ColumnEvidence, DumpProfile, RelationshipEvidence, TableEvidence};
use super::{ColumnSketches, ProfileBudget, ProfileDepth, ProfileValue};

/// Streams a SQL dump into a [`DumpProfile`]. Build one with
/// [`DumpProfiler::builder`].
#[derive(Debug, Clone)]
pub struct DumpProfiler {
    depth: ProfileDepth,
    budget: ProfileBudget,
    seed: u64,
    dialect: Option<SqlDialect>,
}

impl Default for DumpProfiler {
    fn default() -> Self {
        Self {
            depth: ProfileDepth::Full,
            budget: ProfileBudget::default(),
            seed: 0,
            dialect: None,
        }
    }
}

impl DumpProfiler {
    /// Start configuring a profiler.
    pub fn builder() -> DumpProfilerBuilder {
        DumpProfilerBuilder::default()
    }

    /// Profile a dump on disk. Opens the file through the shared input layer
    /// (transparent decompression / zip), and auto-detects the dialect from the
    /// header unless one was configured on the builder.
    pub fn profile_path(&self, path: &Path) -> anyhow::Result<DumpProfile> {
        let dialect = match self.dialect {
            Some(d) => d,
            None => detect_dialect_from_file(path)?.dialect,
        };
        let file_size = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
        let buffer_size = determine_buffer_size(file_size);
        let reader = crate::splitter::open_input(path)?;
        self.run(reader, dialect, buffer_size)
    }

    /// Profile a dump from an arbitrary reader. The dialect must be given
    /// explicitly (there is no file header to sniff a compressed input from).
    pub fn profile_reader<R: Read>(
        &self,
        reader: R,
        dialect: SqlDialect,
    ) -> anyhow::Result<DumpProfile> {
        self.run(reader, dialect, SMALL_BUFFER_SIZE)
    }

    fn run<R: Read>(
        &self,
        reader: R,
        dialect: SqlDialect,
        buffer_size: usize,
    ) -> anyhow::Result<DumpProfile> {
        let mut parser = Parser::with_dialect(reader, buffer_size, dialect);
        let mut run = ProfileRun::new(self.depth, self.budget, self.seed, dialect);
        parser.visit_events(|event| run.on_event(event))?;
        Ok(run.finish())
    }
}

/// Builder for [`DumpProfiler`].
#[derive(Debug, Clone, Default)]
pub struct DumpProfilerBuilder {
    inner: DumpProfilerConfig,
}

// A small config carrier so the builder can start from `Default` without
// exposing the profiler's private fields.
#[derive(Debug, Clone)]
struct DumpProfilerConfig {
    depth: ProfileDepth,
    budget: ProfileBudget,
    seed: u64,
    dialect: Option<SqlDialect>,
}

impl Default for DumpProfilerConfig {
    fn default() -> Self {
        let d = DumpProfiler::default();
        Self {
            depth: d.depth,
            budget: d.budget,
            seed: d.seed,
            dialect: d.dialect,
        }
    }
}

impl DumpProfilerBuilder {
    /// How deep to profile (default [`ProfileDepth::Full`]).
    pub fn depth(mut self, depth: ProfileDepth) -> Self {
        self.inner.depth = depth;
        self
    }

    /// Per-column retention budget (default [`ProfileBudget::default`]).
    pub fn budget(mut self, budget: ProfileBudget) -> Self {
        self.inner.budget = budget;
        self
    }

    /// Seed for the reservoir sampler, making retained samples reproducible.
    pub fn seed(mut self, seed: u64) -> Self {
        self.inner.seed = seed;
        self
    }

    /// Force a SQL dialect instead of auto-detecting from the file header.
    pub fn dialect(mut self, dialect: SqlDialect) -> Self {
        self.inner.dialect = Some(dialect);
        self
    }

    /// Finalize the profiler.
    pub fn build(self) -> DumpProfiler {
        DumpProfiler {
            depth: self.inner.depth,
            budget: self.inner.budget,
            seed: self.inner.seed,
            dialect: self.inner.dialect,
        }
    }
}

// ---------------------------------------------------------------------------
// Streaming run state
// ---------------------------------------------------------------------------

/// Coarse column family, derived once from the schema so row observation never
/// has to re-borrow the schema to decide how to interpret a value.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ColumnKind {
    Bool,
    Int,
    BigInt,
    Decimal,
    DateTime,
    Json,
    Text,
}

impl ColumnKind {
    fn from_column(col: &Column) -> Self {
        if col.source_type.to_ascii_lowercase().contains("json") {
            return ColumnKind::Json;
        }
        match col.col_type {
            ColumnType::Bool => ColumnKind::Bool,
            ColumnType::Int => ColumnKind::Int,
            ColumnType::BigInt => ColumnKind::BigInt,
            ColumnType::Decimal => ColumnKind::Decimal,
            ColumnType::DateTime => ColumnKind::DateTime,
            ColumnType::Text | ColumnType::Uuid | ColumnType::Other(_) => ColumnKind::Text,
        }
    }
}

/// Per-column accumulator: observed total/null tallies at every depth, plus
/// the value sketches at [`ProfileDepth::Basic`] and above.
struct ColumnAccum {
    name: String,
    kind: ColumnKind,
    total: u64,
    nulls: u64,
    sketches: Option<ColumnSketches>,
}

/// A same-table pair of timestamp columns, tracked for temporal ordering
/// (`from <= to`) at [`ProfileDepth::Full`].
struct TemporalPair {
    from: usize,
    to: usize,
    both_present: u64,
    ordered: u64,
}

/// A budget-capped set of 64-bit value hashes. Once full it stops inserting and
/// records that it overflowed, so retention never scales with the row count.
struct BoundedHashSet {
    set: HashSet<u64>,
    cap: usize,
    overflowed: bool,
}

impl BoundedHashSet {
    fn new(cap: usize) -> Self {
        Self {
            set: HashSet::new(),
            cap: cap.max(1),
            overflowed: false,
        }
    }

    fn insert(&mut self, hash: u64) {
        if self.set.len() < self.cap {
            self.set.insert(hash);
        } else if !self.set.contains(&hash) {
            self.overflowed = true;
        }
    }

    fn contains(&self, hash: u64) -> bool {
        self.set.contains(&hash)
    }

    fn is_empty(&self) -> bool {
        self.set.is_empty()
    }
}

/// A declared foreign key reduced to the local column ordinals that carry its
/// child values, so coverage can be tracked without re-borrowing the schema per
/// row. `referenced_table_id` is resolved only at `build()`, so we key by
/// `fk_index` and resolve the parent at finish.
struct FkCandidate {
    fk_index: u16,
    ordinals: Vec<usize>,
}

/// Per-table profiling state.
struct TableProfile {
    name: String,
    table_id: TableId,
    row_count: u64,
    /// Rows that contributed column evidence. This can be below `row_count`
    /// when schema-late input overflowed the bounded replay buffer or when a
    /// delivered row could not be decoded.
    profiled_row_count: u64,
    columns: Vec<ColumnAccum>,
    // Full-depth relationship tracking (empty otherwise).
    pk_hashes: BoundedHashSet,
    fk_candidates: Vec<FkCandidate>,
    fk_child: AHashMap<u16, BoundedHashSet>,
    temporal: Vec<TemporalPair>,
    /// Whether a `GEN-PROFILE-DECODE-SKIPPED` warning has already been raised for
    /// this table, so a run of undecodable rows warns once, not per row.
    decode_warned: bool,
}

/// Buffered rows for a table whose data arrived before its DDL, retained up to
/// the sample budget for a bounded replay once the schema appears.
struct PendingTable {
    row_count: u64,
    retained: Vec<PendingRow>,
    overflowed: bool,
    header: Option<Vec<u8>>,
    copy_columns: Option<Vec<String>>,
}

enum PendingRow {
    Insert(Vec<u8>),
    Copy(Vec<u8>),
}

/// Column context for the INSERT statement currently being streamed.
struct InsertCtx {
    table_idx: usize,
    context: InsertRowContext,
}

/// Column context for the COPY block currently being streamed.
struct CopyCtx {
    table_idx: usize,
    columns: Vec<String>,
}

struct ProfileRun {
    depth: ProfileDepth,
    budget: ProfileBudget,
    seed: u64,
    dialect: SqlDialect,
    builder: SchemaBuilder,
    tables: Vec<TableProfile>,
    table_index: AHashMap<String, usize>,
    insert_ctx: Option<InsertCtx>,
    copy_ctx: Option<CopyCtx>,
    /// The schema-late COPY table whose block is currently open. `CopyRow`
    /// events carry no table name, so this is the *only* reliable way to route
    /// pending COPY rows — a predicate scan over `pending` would misroute when
    /// two tables both have COPY data before either's DDL.
    pending_copy_key: Option<String>,
    pending: AHashMap<String, PendingTable>,
    warnings: Vec<Diagnostic>,
    next_seed: u64,
}

impl ProfileRun {
    fn new(depth: ProfileDepth, budget: ProfileBudget, seed: u64, dialect: SqlDialect) -> Self {
        Self {
            depth,
            budget,
            seed,
            dialect,
            builder: SchemaBuilder::new(),
            tables: Vec::new(),
            table_index: AHashMap::new(),
            insert_ctx: None,
            copy_ctx: None,
            pending_copy_key: None,
            pending: AHashMap::new(),
            warnings: Vec::new(),
            next_seed: 0,
        }
    }

    fn key(name: &str) -> String {
        name.to_ascii_lowercase()
    }

    fn on_event(&mut self, event: ParserEvent<'_>) -> anyhow::Result<RowFlow> {
        match event {
            ParserEvent::Statement(bytes) => self.on_statement(bytes),
            ParserEvent::InsertRow {
                header,
                row,
                first_in_statement,
            } => self.on_insert_row(header, row, first_in_statement),
            ParserEvent::CopyStart(header) => self.on_copy_start(header),
            ParserEvent::CopyRow(line) => self.on_copy_row(line),
            ParserEvent::CopyEnd => {
                self.copy_ctx = None;
                self.pending_copy_key = None;
                Ok(RowFlow::Continue)
            }
        }
    }

    fn on_statement(&mut self, bytes: &[u8]) -> anyhow::Result<RowFlow> {
        let (stmt_type, name) = Parser::<&[u8]>::parse_statement_with_dialect(bytes, self.dialect);
        self.builder.ingest_statement(bytes, self.dialect);
        if stmt_type == StatementType::CreateTable && !name.is_empty() {
            self.register_table(&name);
        }
        Ok(RowFlow::Continue)
    }

    /// Ensure a [`TableProfile`] exists for a freshly created table, then replay
    /// any rows that were buffered before the DDL arrived.
    fn register_table(&mut self, name: &str) {
        let key = Self::key(name);
        if self.table_index.contains_key(&key) {
            return;
        }
        let Some(table_id) = self.builder.schema().get_table_id(name) else {
            return;
        };
        let profile = self.build_table_profile(name, table_id);
        let idx = self.tables.len();
        self.tables.push(profile);
        self.table_index.insert(key.clone(), idx);

        if let Some(pending) = self.pending.remove(&key) {
            self.replay_pending(idx, pending);
        }
    }

    fn build_table_profile(&mut self, name: &str, table_id: TableId) -> TableProfile {
        let schema = self.builder.schema();
        let table = schema
            .table(table_id)
            .expect("table id just resolved from builder");
        let full = self.depth == ProfileDepth::Full;

        let columns: Vec<ColumnAccum> = table
            .columns
            .iter()
            .map(|col| {
                let kind = ColumnKind::from_column(col);
                // A credential-named, string-shaped column never enters the
                // sketches: its raw values (hashes, tokens, keys) must not be
                // retained in evidence. The observed total/null counts tracked
                // separately below are still kept, so the observed null rate
                // survives.
                let credential = matches!(kind, ColumnKind::Text | ColumnKind::Json)
                    && crate::profile::heuristics::is_credential_name(&col.name);
                let sketches = if self.depth == ProfileDepth::Schema || credential {
                    None
                } else {
                    let s = ColumnSketches::new(&self.budget, self.seed ^ self.next_seed);
                    self.next_seed = self.next_seed.wrapping_add(1);
                    Some(s)
                };
                ColumnAccum {
                    name: col.name.clone(),
                    kind,
                    total: 0,
                    nulls: 0,
                    sketches,
                }
            })
            .collect();

        // Same-table temporal candidate pairs (Full only): ordered pairs of
        // timestamp columns, bounded by the schema's column count.
        let temporal = if full {
            let ts_cols: Vec<usize> = table
                .columns
                .iter()
                .enumerate()
                .filter(|(_, c)| ColumnKind::from_column(c) == ColumnKind::DateTime)
                .map(|(i, _)| i)
                .collect();
            let mut pairs = Vec::new();
            for (a_pos, &a) in ts_cols.iter().enumerate() {
                for &b in &ts_cols[a_pos + 1..] {
                    pairs.push(TemporalPair {
                        from: a,
                        to: b,
                        both_present: 0,
                        ordered: 0,
                    });
                }
            }
            pairs
        } else {
            Vec::new()
        };

        // Declared FKs reduced to local column ordinals (resolved at CREATE
        // TABLE time; only the *referenced* table id is deferred to `build()`).
        let fk_candidates: Vec<FkCandidate> = if full {
            table
                .foreign_keys
                .iter()
                .enumerate()
                .filter(|(_, fk)| !fk.columns.is_empty())
                .map(|(fk_index, fk)| FkCandidate {
                    fk_index: fk_index as u16,
                    ordinals: fk.columns.iter().map(|c| c.0 as usize).collect(),
                })
                .collect()
        } else {
            Vec::new()
        };

        TableProfile {
            name: name.to_string(),
            table_id,
            row_count: 0,
            profiled_row_count: 0,
            columns,
            pk_hashes: BoundedHashSet::new(self.budget.sample_rows),
            fk_candidates,
            fk_child: AHashMap::new(),
            temporal,
            decode_warned: false,
        }
    }

    // --- INSERT path -------------------------------------------------------

    fn on_insert_row(
        &mut self,
        header: &[u8],
        row: &[u8],
        first_in_statement: bool,
    ) -> anyhow::Result<RowFlow> {
        if first_in_statement {
            self.prepare_insert(header);
        }

        // Every delivered `InsertRow` is a real `(...)` tuple, so it counts
        // toward the exact row total for a known table regardless of whether the
        // secondary value decode succeeds. Decode success only governs per-column
        // value/null evidence.
        if let Some(table_idx) = self.insert_ctx.as_ref().map(|c| c.table_idx) {
            match self.decode_insert_row(row) {
                Some((idx, parsed)) => self.observe_insert(idx, &parsed),
                None => {
                    self.tables[table_idx].row_count += 1;
                    self.warn_decode_skipped(table_idx);
                }
            }
        } else {
            // Schema-late: buffer the raw tuple for replay once the DDL arrives.
            let cap = self.budget.sample_rows;
            if let Some(table) = self.pending_insert_target(header) {
                table.push_insert(row, cap);
            }
        }

        Ok(RowFlow::Continue)
    }

    fn decode_insert_row(&self, row: &[u8]) -> Option<(usize, ParsedRow)> {
        let ctx = self.insert_ctx.as_ref()?;
        let table_idx = ctx.table_idx;
        let table_id = self.tables[table_idx].table_id;
        let table = self.builder.schema().table(table_id)?;
        let parsed =
            parse_insert_tuple(row, table, &ctx.context, self.dialect, RowExtraction::Full)?;
        Some((table_idx, parsed))
    }

    fn prepare_insert(&mut self, header: &[u8]) {
        self.insert_ctx = None;
        let (_, name) = Parser::<&[u8]>::parse_statement_with_dialect(header, self.dialect);
        if name.is_empty() {
            return;
        }
        let key = Self::key(&name);
        if let Some(&table_idx) = self.table_index.get(&key) {
            let table_id = self.tables[table_idx].table_id;
            let schema = self.builder.schema();
            if let Some(table) = schema.table(table_id) {
                let context = InsertRowContext::from_header(header, table, self.dialect);
                self.insert_ctx = Some(InsertCtx { table_idx, context });
            }
        } else {
            // Schema-late: remember the first header so the replay can rebuild
            // context (single-layout-per-pending-table assumption — a later
            // INSERT into the same table with a different column list would
            // replay under this one).
            self.pending
                .entry(key)
                .or_insert_with(PendingTable::new)
                .header
                .get_or_insert_with(|| header.to_vec());
        }
    }

    /// Look up (creating if needed) the pending buffer for the INSERT whose
    /// header names an as-yet-unknown table.
    fn pending_insert_target(&mut self, header: &[u8]) -> Option<&mut PendingTable> {
        let (_, name) = Parser::<&[u8]>::parse_statement_with_dialect(header, self.dialect);
        if name.is_empty() {
            return None;
        }
        let key = Self::key(&name);
        let entry = self.pending.entry(key).or_insert_with(PendingTable::new);
        // Single-layout-per-pending-table: the first header wins for replay.
        entry.header.get_or_insert_with(|| header.to_vec());
        Some(entry)
    }

    // --- COPY path ---------------------------------------------------------

    fn on_copy_start(&mut self, header: &[u8]) -> anyhow::Result<RowFlow> {
        self.copy_ctx = None;
        self.pending_copy_key = None;
        let header_str = String::from_utf8_lossy(header);
        let (_, name) = Parser::<&[u8]>::parse_statement_with_dialect(header, self.dialect);
        if name.is_empty() {
            return Ok(RowFlow::Continue);
        }
        let columns = parse_copy_columns(&header_str);
        let key = Self::key(&name);
        if let Some(&table_idx) = self.table_index.get(&key) {
            self.copy_ctx = Some(CopyCtx { table_idx, columns });
        } else {
            // Schema-late COPY: record which table this open block belongs to so
            // its rows route unambiguously, and stash the column layout for
            // replay (single-layout-per-pending-table assumption).
            //
            // TODO(deferred, L21): if a `CREATE TABLE` for this key arrives while
            // this block is still open, `register_table` removes the pending
            // entry, leaving `pending_copy_key` dangling so the block's remaining
            // rows are silently dropped. Adopting the open block into the newly
            // registered table would fix it. Deferred: pg_dump never interleaves
            // a table definition inside its own open COPY block (malformed input
            // only).
            let entry = self
                .pending
                .entry(key.clone())
                .or_insert_with(PendingTable::new);
            entry.copy_columns.get_or_insert(columns);
            self.pending_copy_key = Some(key);
        }
        Ok(RowFlow::Continue)
    }

    fn on_copy_row(&mut self, line: &[u8]) -> anyhow::Result<RowFlow> {
        if let Some(table_idx) = self.copy_ctx.as_ref().map(|c| c.table_idx) {
            // Known table. A blank line inside a COPY block is padding, not a
            // row, so it must not count; every genuine data line counts toward
            // the exact total whether or not its values decode.
            let single_col = self.tables[table_idx].columns.len() == 1;
            if !copy_line_is_data(line, single_col) {
                return Ok(RowFlow::Continue);
            }
            match self.decode_copy_row(line) {
                Some((idx, parsed)) => self.observe_copy(idx, &parsed),
                None => {
                    self.tables[table_idx].row_count += 1;
                    self.warn_decode_skipped(table_idx);
                }
            }
        } else if let Some(key) = self.pending_copy_key.clone() {
            // Schema-late COPY: route by the explicitly tracked open-block key,
            // never a predicate scan (which would misroute with two pending
            // COPY tables). Buffer genuine data lines only. The COPY header's
            // column list gives the arity even before the CREATE TABLE, so a
            // single-column block correctly treats a blank line as an
            // empty-string row rather than padding.
            let cap = self.budget.sample_rows;
            if let Some(table) = self.pending.get_mut(&key) {
                let single_col = table
                    .copy_columns
                    .as_ref()
                    .is_some_and(|columns| columns.len() == 1);
                if copy_line_is_data(line, single_col) {
                    table.push_copy(line, cap);
                }
            }
        }
        Ok(RowFlow::Continue)
    }

    /// Raise `GEN-PROFILE-DECODE-SKIPPED` once per table when a delivered row
    /// failed value decoding: it is still counted in the exact row total, but
    /// contributes no per-column evidence.
    fn warn_decode_skipped(&mut self, table_idx: usize) {
        let table = &mut self.tables[table_idx];
        if table.decode_warned {
            return;
        }
        table.decode_warned = true;
        self.warnings.push(Diagnostic::warning(
            &codes::PROFILE_DECODE_SKIPPED,
            format!("tables.{}", table.name),
            "rows failed value decoding; they are counted in the exact row total but \
             contributed no per-column evidence",
        ));
    }

    fn decode_copy_row(&self, line: &[u8]) -> Option<(usize, ParsedCopyRow)> {
        let ctx = self.copy_ctx.as_ref()?;
        let table_idx = ctx.table_idx;
        let table_id = self.tables[table_idx].table_id;
        let table = self.builder.schema().table(table_id)?;
        let parsed = decode_copy_line(line, table, ctx.columns.clone())?;
        Some((table_idx, parsed))
    }

    // --- Row observation ---------------------------------------------------

    fn observe_insert(&mut self, table_idx: usize, row: &ParsedRow) {
        let ncols = self.tables[table_idx].columns.len();
        self.observe_row(
            table_idx,
            ncols,
            |ord| row.get_column_value(ord),
            row.pk.as_ref(),
        );
    }

    fn observe_copy(&mut self, table_idx: usize, row: &ParsedCopyRow) {
        let ncols = self.tables[table_idx].columns.len();
        self.observe_row(
            table_idx,
            ncols,
            |ord| row.get_column_value(ord),
            row.pk.as_ref(),
        );
    }

    /// The single per-row hot path shared by INSERT and COPY: tally total/null,
    /// feed the value sketches, and (at Full depth) update FK/PK/temporal
    /// evidence.
    fn observe_row<'r>(
        &mut self,
        table_idx: usize,
        ncols: usize,
        value: impl Fn(usize) -> Option<&'r PkValue>,
        pk: Option<&PkTuple>,
    ) {
        let full = self.depth == ProfileDepth::Full;
        let cap = self.budget.sample_rows;
        let table = &mut self.tables[table_idx];
        table.row_count += 1;
        table.profiled_row_count += 1;

        for (ord, acc) in table.columns.iter_mut().enumerate().take(ncols) {
            let Some(v) = value(ord) else { continue };
            acc.total += 1;
            if v.is_null() {
                acc.nulls += 1;
            }
            if let Some(sketches) = &mut acc.sketches {
                observe_pk_value(sketches, acc.kind, v);
            }
        }

        if !full {
            return;
        }

        if let Some(pk) = pk {
            table.pk_hashes.insert(hash_pk_tuple(pk));
        }
        // Child FK values, hashed the same way parent PKs are, so coverage is a
        // plain set-membership test at finish.
        for candidate in &table.fk_candidates {
            let mut tuple = PkTuple::new();
            let mut complete = true;
            for &ord in &candidate.ordinals {
                match value(ord) {
                    Some(v) if !v.is_null() => tuple.push(v.clone()),
                    _ => {
                        complete = false;
                        break;
                    }
                }
            }
            if complete && !tuple.is_empty() {
                table
                    .fk_child
                    .entry(candidate.fk_index)
                    .or_insert_with(|| BoundedHashSet::new(cap))
                    .insert(hash_pk_tuple(&tuple));
            }
        }
        for pair in &mut table.temporal {
            if let (Some(PkValue::Text(a)), Some(PkValue::Text(b))) =
                (value(pair.from), value(pair.to))
            {
                pair.both_present += 1;
                if a <= b {
                    pair.ordered += 1;
                }
            }
        }
    }

    // --- Schema-late replay ------------------------------------------------

    fn replay_pending(&mut self, table_idx: usize, pending: PendingTable) {
        let table_id = self.tables[table_idx].table_id;

        // Replay every retained row through the normal decode/observe path.
        for row in &pending.retained {
            match row {
                PendingRow::Insert(bytes) => {
                    let parsed = pending.header.as_ref().and_then(|header| {
                        let schema = self.builder.schema();
                        let table = schema.table(table_id)?;
                        let ctx = InsertRowContext::from_header(header, table, self.dialect);
                        parse_insert_tuple(bytes, table, &ctx, self.dialect, RowExtraction::Full)
                    });
                    if let Some(parsed) = parsed {
                        self.observe_insert(table_idx, &parsed);
                    }
                }
                PendingRow::Copy(bytes) => {
                    let cols = pending.copy_columns.clone().unwrap_or_default();
                    let parsed = {
                        let schema = self.builder.schema();
                        schema
                            .table(table_id)
                            .and_then(|table| decode_copy_line(bytes, table, cols))
                    };
                    if let Some(parsed) = parsed {
                        self.observe_copy(table_idx, &parsed);
                    }
                }
            }
        }

        // The retained sample may be smaller than what actually streamed by:
        // fix the row count to the true total and flag the coverage gap.
        let observed = self.tables[table_idx].row_count;
        if pending.row_count > observed {
            self.tables[table_idx].row_count = pending.row_count;
        }
        if pending.overflowed {
            self.warnings.push(Diagnostic::warning(
                &codes::PROFILE_SCHEMA_LATE,
                format!("tables.{}", self.tables[table_idx].name),
                format!(
                    "had {} data rows before its DDL; only {} were retained for column profiling \
                     (the table row count is exact, but column counts and null rates cover retained rows only)",
                    pending.row_count,
                    pending.retained.len()
                ),
            ));
        }
    }

    // --- Finalize ----------------------------------------------------------

    fn finish(mut self) -> DumpProfile {
        // Resolve FK references now that all DDL has been seen.
        let schema = std::mem::take(&mut self.builder).build();

        // Map table id -> profile index, so FK coverage can reach the parent's
        // retained PK set.
        let mut id_to_idx: AHashMap<u32, usize> = AHashMap::new();
        for (idx, t) in self.tables.iter().enumerate() {
            id_to_idx.insert(t.table_id.0, idx);
        }

        // Any pending table that never got its DDL: surface its exact row count
        // and warn that its columns could not be profiled.
        // Sort by table key so the warnings are deterministic; the pending map
        // is a randomized-seed hashmap whose drain order varies run to run.
        let mut leftovers: Vec<(String, PendingTable)> = self.pending.drain().collect();
        leftovers.sort_by(|a, b| a.0.cmp(&b.0));
        for (key, pending) in leftovers {
            self.warnings.push(Diagnostic::warning(
                &codes::PROFILE_SCHEMA_LATE,
                format!("tables.{key}"),
                format!(
                    "had {} data rows but no CREATE TABLE was seen; it could not be profiled",
                    pending.row_count
                ),
            ));
        }

        let depth = self.depth;
        let relationships = self.compute_relationships(&schema, &id_to_idx);

        let tables = self
            .tables
            .into_iter()
            .enumerate()
            .map(|(idx, table)| {
                finish_table(table, relationships.get(&idx).cloned().unwrap_or_default())
            })
            .collect();

        // The profiler already built the full DDL schema in this same pass;
        // capture it as a portable snapshot so downstream inference never has
        // to re-read the dump to recover it.
        let portable = PortableSchema::from_runtime(&schema, self.dialect);

        DumpProfile {
            depth,
            schema: portable,
            tables,
            warnings: self.warnings,
        }
    }

    /// Build the Full-depth relationship evidence per table index.
    fn compute_relationships(
        &self,
        schema: &Schema,
        id_to_idx: &AHashMap<u32, usize>,
    ) -> AHashMap<usize, Vec<RelationshipEvidence>> {
        let mut out: AHashMap<usize, Vec<RelationshipEvidence>> = AHashMap::new();
        if self.depth != ProfileDepth::Full {
            return out;
        }

        for (idx, table) in self.tables.iter().enumerate() {
            let Some(table_schema) = schema.table(table.table_id) else {
                continue;
            };
            let mut rels = Vec::new();

            // Declared foreign keys: child -> parent coverage over bounded sets.
            for (fk_index, fk) in table_schema.foreign_keys.iter().enumerate() {
                let Some(child) = table.fk_child.get(&(fk_index as u16)) else {
                    continue;
                };
                if child.is_empty() {
                    continue;
                }
                let Some(parent_id) = fk.referenced_table_id else {
                    continue;
                };
                let Some(&parent_idx) = id_to_idx.get(&parent_id.0) else {
                    continue;
                };
                let parent = &self.tables[parent_idx].pk_hashes;
                let matched = child.set.iter().filter(|h| parent.contains(**h)).count();
                let coverage = matched as f64 / child.set.len() as f64;
                let bounded = child.overflowed || parent.overflowed;
                rels.push(RelationshipEvidence {
                    from_column: fk.column_names.join(","),
                    to_table: fk.referenced_table.clone(),
                    to_column: fk.referenced_columns.join(","),
                    coverage,
                    confidence: if bounded { 0.5 } else { 1.0 },
                });
            }

            // Same-table temporal orderings.
            for pair in &table.temporal {
                if pair.both_present == 0 {
                    continue;
                }
                let coverage = pair.ordered as f64 / pair.both_present as f64;
                rels.push(RelationshipEvidence {
                    from_column: table.columns[pair.from].name.clone(),
                    to_table: table.name.clone(),
                    to_column: table.columns[pair.to].name.clone(),
                    coverage,
                    confidence: coverage,
                });
            }

            if !rels.is_empty() {
                out.insert(idx, rels);
            }
        }
        out
    }
}

/// True when a raw COPY line is a genuine data row, matching
/// [`CopyParser::parse_line`]'s own skip rules: the `\.` terminator and (for
/// multi-column tables) a blank padding line are *not* rows. Lets the exact row
/// count be decided independently of whether the value decode succeeds.
fn copy_line_is_data(line: &[u8], empty_is_row: bool) -> bool {
    let line = if line.last() == Some(&b'\r') {
        &line[..line.len() - 1]
    } else {
        line
    };
    !(line == b"\\." || (line.is_empty() && !empty_is_row))
}

/// Decode one COPY data line into a [`ParsedCopyRow`] with full column identity,
/// building a fresh (bounded, per-line) parser context bound to the schema.
fn decode_copy_line(
    line: &[u8],
    table: &TableSchema,
    columns: Vec<String>,
) -> Option<ParsedCopyRow> {
    let (parser, empty_is_row) = CopyParser::new(b"")
        .with_schema(table)
        .with_column_order(columns)
        .with_extraction(RowExtraction::Full)
        .prepared();
    parser.parse_line(line, empty_is_row)
}

/// Fold one already-decoded column value into its sketches, interpreting it
/// through the schema-derived [`ColumnKind`].
fn observe_pk_value(sketches: &mut ColumnSketches, kind: ColumnKind, value: &PkValue) {
    match value {
        PkValue::Null => sketches.observe(ProfileValue::Null),
        PkValue::Int(n) => observe_integer(sketches, kind, *n as i128),
        PkValue::BigInt(n) => observe_integer(sketches, kind, *n),
        PkValue::Text(s) => observe_text(sketches, kind, s),
    }
}

fn observe_integer(sketches: &mut ColumnSketches, kind: ColumnKind, n: i128) {
    match kind {
        ColumnKind::Bool if n == 0 || n == 1 => {
            sketches.observe(ProfileValue::Boolean(n == 1));
        }
        ColumnKind::Decimal => sketches.observe(ProfileValue::Decimal { minor: n, scale: 0 }),
        _ => match i64::try_from(n) {
            Ok(v) => sketches.observe(ProfileValue::Integer(v)),
            Err(_) => sketches.observe(ProfileValue::Decimal { minor: n, scale: 0 }),
        },
    }
}

fn observe_text(sketches: &mut ColumnSketches, kind: ColumnKind, s: &str) {
    match kind {
        ColumnKind::DateTime => sketches.observe(ProfileValue::DateTime(s)),
        ColumnKind::Json => sketches.observe(ProfileValue::Json(s)),
        ColumnKind::Bool => match parse_bool(s) {
            Some(b) => sketches.observe(ProfileValue::Boolean(b)),
            None => sketches.observe(ProfileValue::Text(s)),
        },
        ColumnKind::Decimal => match parse_decimal(s) {
            Some((minor, scale)) => sketches.observe(ProfileValue::Decimal { minor, scale }),
            None => sketches.observe(ProfileValue::Text(s)),
        },
        ColumnKind::Int | ColumnKind::BigInt => match s.parse::<i128>() {
            Ok(n) => observe_integer(sketches, kind, n),
            Err(_) => sketches.observe(ProfileValue::Text(s)),
        },
        ColumnKind::Text => sketches.observe(ProfileValue::Text(s)),
    }
}

/// Parse a boolean rendered as text (`t`/`true`/`1`/`yes` and their negatives).
fn parse_bool(s: &str) -> Option<bool> {
    match s.trim().to_ascii_lowercase().as_str() {
        "t" | "true" | "yes" | "y" => Some(true),
        "f" | "false" | "no" | "n" => Some(false),
        _ => None,
    }
}

/// Parse a plain fixed-point decimal string into `(minor, scale)` such that the
/// value equals `minor * 10^-scale`. Rejects anything that is not sign + digits
/// with at most one decimal point (scientific notation, currency, etc.).
fn parse_decimal(s: &str) -> Option<(i128, u8)> {
    let s = s.trim();
    let (neg, body) = match s.strip_prefix('-') {
        Some(rest) => (true, rest),
        None => (false, s.strip_prefix('+').unwrap_or(s)),
    };
    let (int_part, frac_part) = match body.split_once('.') {
        Some((a, b)) => (a, b),
        None => (body, ""),
    };
    if int_part.is_empty() && frac_part.is_empty() {
        return None;
    }
    if !int_part.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    if !frac_part.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    let mut digits = String::with_capacity(int_part.len() + frac_part.len());
    digits.push_str(int_part);
    digits.push_str(frac_part);
    let mut minor: i128 = digits.parse().ok()?;
    if neg {
        minor = -minor;
    }
    let scale = u8::try_from(frac_part.len()).ok()?;
    Some((minor, scale))
}

/// Finalize one table's accumulated state into neutral evidence.
fn finish_table(table: TableProfile, relationships: Vec<RelationshipEvidence>) -> TableEvidence {
    let coverage = if table.row_count == 0 {
        0.0
    } else {
        table.profiled_row_count as f64 / table.row_count as f64
    };
    let columns = table
        .columns
        .into_iter()
        .map(|column| finish_column(column, coverage))
        .collect::<Vec<_>>();
    TableEvidence {
        table: table.name,
        row_count: Some(table.row_count),
        columns,
        relationships,
        confidence: coverage,
    }
}

fn finish_column(acc: ColumnAccum, coverage: f64) -> ColumnEvidence {
    match acc.sketches {
        Some(sketches) => {
            let mut ev = sketches.finish();
            ev.name = acc.name;
            ev.confidence = ev.confidence.min(coverage);
            ev
        }
        None => {
            // Schema depth: exact counts, no value-derived evidence.
            let null_rate = if acc.total == 0 {
                0.0
            } else {
                acc.nulls as f64 / acc.total as f64
            };
            // Ad-hoc confidence: rises toward 1.0 with the non-null observation
            // count (mirrors `ColumnSketches::confidence`). Both paths share
            // this intentionally heuristic scale.
            let non_null = acc.total.saturating_sub(acc.nulls);
            ColumnEvidence {
                name: acc.name,
                total_count: acc.total,
                null_count: acc.nulls,
                null_rate,
                distinct_estimate: 0.0,
                sample_values: Vec::new(),
                truncated_sample_count: 0,
                boolean: None,
                numeric: None,
                decimal_scale: None,
                string_shape: None,
                top_k: Vec::new(),
                timestamp_range: None,
                json_valid_rate: None,
                confidence: (1.0 - 1.0 / (1.0 + non_null as f64)).min(coverage),
            }
        }
    }
}

impl PendingTable {
    fn new() -> Self {
        Self {
            row_count: 0,
            retained: Vec::new(),
            overflowed: false,
            header: None,
            copy_columns: None,
        }
    }

    fn push_insert(&mut self, row: &[u8], cap: usize) {
        self.row_count += 1;
        if self.retained.len() < cap {
            self.retained.push(PendingRow::Insert(row.to_vec()));
        } else {
            self.overflowed = true;
        }
    }

    fn push_copy(&mut self, line: &[u8], cap: usize) {
        self.row_count += 1;
        if self.retained.len() < cap {
            self.retained.push(PendingRow::Copy(line.to_vec()));
        } else {
            self.overflowed = true;
        }
    }
}